query
stringlengths 7
3.85k
| document
stringlengths 11
430k
| metadata
dict | negatives
sequencelengths 0
101
| negative_scores
sequencelengths 0
101
| document_score
stringlengths 3
10
| document_rank
stringclasses 102
values |
---|---|---|---|---|---|---|
GetTopicPolicy gets an existing TopicPolicy resource's state with the given name, ID, and optional state properties that are used to uniquely qualify the lookup (nil if not required). | func GetTopicPolicy(ctx *pulumi.Context,
name string, id pulumi.IDInput, state *TopicPolicyState, opts ...pulumi.ResourceOption) (*TopicPolicy, error) {
var resource TopicPolicy
err := ctx.ReadResource("aws:sns/topicPolicy:TopicPolicy", name, id, state, &resource, opts...)
if err != nil {
return nil, err
}
return &resource, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func GetPolicy(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *PolicyState, opts ...pulumi.ResourceOption) (*Policy, error) {\n\tvar resource Policy\n\terr := ctx.ReadResource(\"gcp:organizations/policy:Policy\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func GetPolicy(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *PolicyState, opts ...pulumi.ResourceOption) (*Policy, error) {\n\tvar resource Policy\n\terr := ctx.ReadResource(\"aws-native:iot:Policy\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func GetTopic(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *TopicState, opts ...pulumi.ResourceOption) (*Topic, error) {\n\tvar resource Topic\n\terr := ctx.ReadResource(\"google-native:pubsub/v1beta1a:Topic\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func (c *Client) GetPolicy(name string) (*Policy, error) {\n\tif name == \"\" {\n\t\treturn nil, errored.Errorf(\"Policy invalid: empty string for name\")\n\t}\n\n\tresp, err := c.etcdClient.Get(context.Background(), c.policy(name), nil)\n\tif err != nil {\n\t\treturn nil, errors.EtcdToErrored(err)\n\t}\n\n\ttc := NewPolicy()\n\tif err := json.Unmarshal([]byte(resp.Node.Value), tc); err != nil {\n\t\treturn nil, err\n\t}\n\n\ttc.Name = name\n\n\terr = tc.Validate()\n\treturn tc, err\n}",
"func GetTopicRule(ctx *pulumi.Context,\n\tname string, id pulumi.ID, state *TopicRuleState, opts ...pulumi.ResourceOpt) (*TopicRule, error) {\n\tinputs := make(map[string]interface{})\n\tif state != nil {\n\t\tinputs[\"arn\"] = state.Arn\n\t\tinputs[\"cloudwatchAlarm\"] = state.CloudwatchAlarm\n\t\tinputs[\"cloudwatchMetric\"] = state.CloudwatchMetric\n\t\tinputs[\"description\"] = state.Description\n\t\tinputs[\"dynamodb\"] = state.Dynamodb\n\t\tinputs[\"elasticsearch\"] = state.Elasticsearch\n\t\tinputs[\"enabled\"] = state.Enabled\n\t\tinputs[\"firehose\"] = state.Firehose\n\t\tinputs[\"kinesis\"] = state.Kinesis\n\t\tinputs[\"lambda\"] = state.Lambda\n\t\tinputs[\"name\"] = state.Name\n\t\tinputs[\"republish\"] = state.Republish\n\t\tinputs[\"s3\"] = state.S3\n\t\tinputs[\"sns\"] = state.Sns\n\t\tinputs[\"sql\"] = state.Sql\n\t\tinputs[\"sqlVersion\"] = state.SqlVersion\n\t\tinputs[\"sqs\"] = state.Sqs\n\t}\n\ts, err := ctx.ReadResource(\"aws:iot/topicRule:TopicRule\", name, id, inputs, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TopicRule{s: s}, nil\n}",
"func GetPolicy(ctx *pulumi.Context,\n\tname string, id pulumi.ID, state *PolicyState, opts ...pulumi.ResourceOpt) (*Policy, error) {\n\tinputs := make(map[string]interface{})\n\tif state != nil {\n\t\tinputs[\"alarms\"] = state.Alarms\n\t\tinputs[\"arn\"] = state.Arn\n\t\tinputs[\"name\"] = state.Name\n\t\tinputs[\"policyType\"] = state.PolicyType\n\t\tinputs[\"resourceId\"] = state.ResourceId\n\t\tinputs[\"scalableDimension\"] = state.ScalableDimension\n\t\tinputs[\"serviceNamespace\"] = state.ServiceNamespace\n\t\tinputs[\"stepScalingPolicyConfiguration\"] = state.StepScalingPolicyConfiguration\n\t\tinputs[\"targetTrackingScalingPolicyConfiguration\"] = state.TargetTrackingScalingPolicyConfiguration\n\t}\n\ts, err := ctx.ReadResource(\"aws:appautoscaling/policy:Policy\", name, id, inputs, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Policy{s: s}, nil\n}",
"func (c *controller) GetPolicy(ctx context.Context, id int64) (*policyModels.Schema, error) {\n\treturn c.pManager.Get(ctx, id)\n}",
"func (k *PoliciesCollection) Get(id string) (*Policy, error) {\n\tif id == \"\" {\n\t\treturn nil, errIDRequired\n\t}\n\n\ttxn := k.db.Txn(false)\n\tdefer txn.Abort()\n\treturn getPolicy(txn, id)\n}",
"func GetTopic(name string) (*Topic, error) {\n\tentity := Topic{ID: strings.ToLower(name)}\n\terr := DS.GetByKey(&entity)\n\treturn &entity, err\n}",
"func (t *TopicService) Get(id string) (*Topic, error) {\n\tquery := `\n\tquery ($id: ID){\n\t\ttopic(id: $id){\n\t\t\tid,\n\t\t\tname,\n\t\t\tdescription,\n\t\t\tposts{id, title},\n\t\t\thierarchy,\n\t\t\tparent{id},\n\t\t\tancestors{id},\n\t\t\tchildren{id},\n\t\t\tinsertedAt,\n\t\t\tupdatedAt\n\t\t}\n\t}`\n\tvar resp struct {\n\t\tTopic *Topic `json:\"topic\"`\n\t}\n\tvars := map[string]interface{}{\"id\": id}\n\terr := t.client.Do(context.Background(), query, vars, &resp)\n\treturn resp.Topic, err\n}",
"func (e *Enforcer) GetNamedPolicy(ctx context.Context, ptype string) ([][]string, error) {\n\tres, err := e.client.remoteClient.GetNamedPolicy(ctx, &pb.PolicyRequest{\n\t\tEnforcerHandler: e.handler,\n\t\tPType: ptype,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn replyTo2DSlice(res), nil\n}",
"func GetTopic(name string) *Topic {\n\treturn registry.GetTopic(name)\n}",
"func (s *Storage) GetPolicy(ctx context.Context, ID int64) (*Policy, error) {\n\tvar policy Policy\n\terr := s.db.QueryRowContext(ctx, `SELECT query_policy($1);`, ID).Scan(&policy)\n\tif err != nil {\n\t\treturn nil, s.database.ProcessError(err)\n\t}\n\n\treturn &policy, nil\n}",
"func (c *Client) GetPolicy(ctx context.Context, r ResourceWithPolicy) (*Policy, error) {\n\tu, v, body, err := r.GetPolicy(c.Config.BasePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := dcl.SendRequest(ctx, c.Config, v, u, body, c.Config.RetryProvider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Response.Body.Close()\n\tb, err := ioutil.ReadAll(resp.Response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp := &Policy{}\n\tif err := json.Unmarshal(b, p); err != nil {\n\t\treturn nil, err\n\t}\n\tp.Resource = r\n\treturn p, nil\n}",
"func (s *policies) Read(ctx context.Context, policyID string) (*Policy, error) {\n\tif !validStringID(&policyID) {\n\t\treturn nil, ErrInvalidPolicyID\n\t}\n\n\tu := fmt.Sprintf(\"policies/%s\", url.QueryEscape(policyID))\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp := &Policy{}\n\terr = req.Do(ctx, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn p, err\n}",
"func (p *PolicyResource) GetById(id string) (*Policy, error) {\n\tpolicies, err := p.GetBy(\"id\", id)\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\tif len(policies) > 0 {\n\t\tpolicy := policies[0]\n\t\treturn policy, nil\n\t}\n\n\treturn nil, errors.New(\"Resource doesn't exist\")\n}",
"func GetTopicRule(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *TopicRuleState, opts ...pulumi.ResourceOption) (*TopicRule, error) {\n\tvar resource TopicRule\n\terr := ctx.ReadResource(\"aws-native:iot:TopicRule\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func (e *Enforcer) GetNamedPolicy(ptype string) [][]string {\n\treturn e.model.GetPolicy(\"p\", ptype)\n}",
"func (m *MongoManager) Get(id string) (Policy, error) {\n\tm.RLock()\n\tdefer m.RUnlock()\n\n\tp, ok := m.Policies[id]\n\tif !ok {\n\t\treturn nil, errors.New(\"Not found\")\n\t}\n\n\treturn p, nil\n}",
"func GetAuthorizationPolicy(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *AuthorizationPolicyState, opts ...pulumi.ResourceOption) (*AuthorizationPolicy, error) {\n\tvar resource AuthorizationPolicy\n\terr := ctx.ReadResource(\"gcp:networksecurity/authorizationPolicy:AuthorizationPolicy\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func (c *controller) GetPolicyByName(ctx context.Context, projectID int64, name string) (*policyModels.Schema, error) {\n\treturn c.pManager.GetByName(ctx, projectID, name)\n}",
"func GetUserPolicy(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *UserPolicyState, opts ...pulumi.ResourceOption) (*UserPolicy, error) {\n\tvar resource UserPolicy\n\terr := ctx.ReadResource(\"aws:iam/userPolicy:UserPolicy\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func PolicyGet(client *golangsdk.ServiceClient, clusterId string) (r PolicyResult) {\n\t_, r.Err = client.Get(policyURL(client, clusterId), &r.Body, nil)\n\treturn\n}",
"func GetResiliencyPolicy(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *ResiliencyPolicyState, opts ...pulumi.ResourceOption) (*ResiliencyPolicy, error) {\n\tvar resource ResiliencyPolicy\n\terr := ctx.ReadResource(\"aws-native:resiliencehub:ResiliencyPolicy\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func GetTopic(tid string) (*Topic, error) {\n\ttidNum, err := strconv.ParseInt(tid, 10, 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\to := orm.NewOrm()\n\n\ttopic := new(Topic)\n\n\tqs := o.QueryTable(\"topic\")\n\terr = qs.Filter(\"id\", tidNum).One(topic)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttopic.Views++\n\t_, err = o.Update(topic)\n\n\treturn topic, err\n}",
"func NewTopicPolicy(ctx *pulumi.Context,\n\tname string, args *TopicPolicyArgs, opts ...pulumi.ResourceOption) (*TopicPolicy, error) {\n\tif args == nil || args.Arn == nil {\n\t\treturn nil, errors.New(\"missing required argument 'Arn'\")\n\t}\n\tif args == nil || args.Policy == nil {\n\t\treturn nil, errors.New(\"missing required argument 'Policy'\")\n\t}\n\tif args == nil {\n\t\targs = &TopicPolicyArgs{}\n\t}\n\tvar resource TopicPolicy\n\terr := ctx.RegisterResource(\"aws:sns/topicPolicy:TopicPolicy\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func NewTopicPolicy(ctx *pulumi.Context,\n\tname string, args *TopicPolicyArgs, opts ...pulumi.ResourceOption) (*TopicPolicy, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Arn == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Arn'\")\n\t}\n\tif args.Policy == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Policy'\")\n\t}\n\tvar resource TopicPolicy\n\terr := ctx.RegisterResource(\"aws:sns/topicPolicy:TopicPolicy\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func GetGroupPolicy(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *GroupPolicyState, opts ...pulumi.ResourceOption) (*GroupPolicy, error) {\n\tvar resource GroupPolicy\n\terr := ctx.ReadResource(\"aws-native:iam:GroupPolicy\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func (ps *PolicyStore) GetPolicy(name string) (*Policy, error) {\n\tdefer metrics.MeasureSince([]string{\"policy\", \"get_policy\"}, time.Now())\n\tif ps.lru != nil {\n\t\t// Check for cached policy\n\t\tif raw, ok := ps.lru.Get(name); ok {\n\t\t\treturn raw.(*Policy), nil\n\t\t}\n\t}\n\n\t// Special case the root policy\n\tif name == \"root\" {\n\t\tp := &Policy{Name: \"root\"}\n\t\tif ps.lru != nil {\n\t\t\tps.lru.Add(p.Name, p)\n\t\t}\n\t\treturn p, nil\n\t}\n\n\t// Load the policy in\n\tout, err := ps.view.Get(name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read policy: %v\", err)\n\t}\n\tif out == nil {\n\t\treturn nil, nil\n\t}\n\n\t// In Vault 0.1.X we stored the raw policy, but in\n\t// Vault 0.2 we switch to the PolicyEntry\n\tpolicyEntry := new(PolicyEntry)\n\tvar policy *Policy\n\tif err := out.DecodeJSON(policyEntry); err == nil {\n\t\t// Parse normally\n\t\tp, err := Parse(policyEntry.Raw)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse policy: %v\", err)\n\t\t}\n\t\tp.Name = name\n\t\tpolicy = p\n\n\t} else {\n\t\t// On error, attempt to use V1 parsing\n\t\tp, err := Parse(string(out.Value))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse policy: %v\", err)\n\t\t}\n\t\tp.Name = name\n\n\t\t// V1 used implicit glob, we need to do a fix-up\n\t\tfor _, pp := range p.Paths {\n\t\t\tpp.Glob = true\n\t\t}\n\t\tpolicy = p\n\t}\n\n\tif ps.lru != nil {\n\t\t// Update the LRU cache\n\t\tps.lru.Add(name, policy)\n\t}\n\n\treturn policy, nil\n}",
"func (aaa *NotificationService) GetTopicByTopicName(input *notification.GetTopicByTopicNameParams) (*lobbyclientmodels.ModelNotificationTopicResponse, error) {\n\ttoken, err := aaa.TokenRepository.GetToken()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tok, unauthorized, forbidden, notFound, internalServerError, err := aaa.Client.Notification.GetTopicByTopicName(input, client.BearerToken(*token.AccessToken))\n\tif unauthorized != nil {\n\t\treturn nil, unauthorized\n\t}\n\tif forbidden != nil {\n\t\treturn nil, forbidden\n\t}\n\tif notFound != nil {\n\t\treturn nil, notFound\n\t}\n\tif internalServerError != nil {\n\t\treturn nil, internalServerError\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ok.GetPayload(), nil\n}",
"func (e *CachedEnforcer) GetNamedPolicy(ptype string) [][]string {\n\treturn e.api.GetNamedPolicy(ptype)\n}",
"func (s *DefaultStore) GetPolicy(policyGen object.Generation) (*lang.Policy, object.Generation, error) {\n\t// todo should we use RWMutex for get/update policy?\n\tpolicyData, err := s.GetPolicyData(policyGen)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\treturn s.getPolicyFromData(policyData)\n}",
"func (eventNotifications *EventNotificationsV1) GetTopic(getTopicOptions *GetTopicOptions) (result *Topic, response *core.DetailedResponse, err error) {\n\treturn eventNotifications.GetTopicWithContext(context.Background(), getTopicOptions)\n}",
"func (a *DefaultApiService) GetTopic(ctx _context.Context, topicName string) ApiGetTopicRequest {\n\treturn ApiGetTopicRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\ttopicName: topicName,\n\t}\n}",
"func (c *KafkaCluster) getTopicState(groupID, topicName string) *topicState {\n\tgroup := c.getGroupState(groupID)\n\n\t// Read lock check\n\tc.lock.RLock()\n\tif topic, ok := group[topicName]; ok {\n\t\tc.lock.RUnlock()\n\t\treturn topic\n\t}\n\tc.lock.RUnlock()\n\n\t// Write lock check and possible create\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tif topic, ok := group[topicName]; ok {\n\t\treturn topic\n\t}\n\tgroup[topicName] = &topicState{\n\t\tclaimPartition: c.getClaimPartition(topicName),\n\t\tpartitions: nil,\n\t\tlock: &sync.RWMutex{},\n\t}\n\treturn group[topicName]\n}",
"func (r *OrderRepositoryImpl) Get(id int) (*domain.Order, error) {\n\tOrder := &domain.Order{}\n\tif err := r.Conn.Preload(\"Topic\").First(&Order, id).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn Order, nil\n}",
"func (p *PolicyResource) GetByName(name string) (*Policy, error) {\n\tpolicies, err := p.GetBy(\"name\", name)\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\tif len(policies) > 0 {\n\t\tpolicy := policies[0]\n\t\treturn policy, nil\n\t}\n\n\treturn nil, errors.New(\"Resource doesn't exist\")\n}",
"func (e *Enforcer) GetPolicy(ctx context.Context) ([][]string, error) {\n\tres, err := e.client.remoteClient.GetPolicy(ctx, &pb.EmptyRequest{Handler: e.handler})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn replyTo2DSlice(res), nil\n}",
"func (f *Factory) GetPolicyStatement() (string, error) {\n\t// Perform checks\n\tif len(f.accountID) == 0 {\n\t\treturn \"\", errors.New(AccountIDMissingErr)\n\t}\n\n\tif len(f.region) == 0 {\n\t\treturn \"\", errors.New(RegionMissingErr)\n\t}\n\n\tif len(f.partition) == 0 {\n\t\treturn \"\", errors.New(PartitionMissingErr)\n\t}\n\n\t// Replace AWS placeholders\n\tt := fmt.Sprintf(iamTemplate, strings.Join(f.policies, \",\"))\n\tt = strings.ReplaceAll(t, \"${AWS::Partition}\", f.partition)\n\tt = strings.ReplaceAll(t, \"${AWS::Region}\", f.region)\n\tt = strings.ReplaceAll(t, \"${AWS::AccountId}\", f.accountID)\n\n\t// Return the policy document\n\treturn t, nil\n}",
"func (r *PolicyRequest) Get(ctx context.Context) (resObj *Policy, err error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\terr = r.JSONRequest(ctx, \"GET\", query, nil, &resObj)\n\treturn\n}",
"func (client IdentityClient) GetPolicy(ctx context.Context, request GetPolicyRequest) (response GetPolicyResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.getPolicy, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = GetPolicyResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = GetPolicyResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(GetPolicyResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into GetPolicyResponse\")\n\t}\n\treturn\n}",
"func (c readOnlyAuthorizationCache) GetPolicy(ctx kapi.Context, name string) (*authorizationapi.Policy, error) {\n\tnamespace, _ := kapi.NamespaceFrom(ctx)\n\n\tif namespaceRefersToCluster(namespace) {\n\t\tclusterPolicy, err := c.ReadOnlyClusterPolicies().Get(name)\n\t\tif err != nil {\n\t\t\treturn &authorizationapi.Policy{}, err\n\t\t}\n\t\treturn authorizationapi.ToPolicy(clusterPolicy), nil\n\t} else {\n\t\tpolicy, err := c.ReadOnlyPolicies(namespace).Get(name)\n\t\tif err != nil {\n\t\t\treturn &authorizationapi.Policy{}, err\n\t\t}\n\t\treturn policy, nil\n\t}\n}",
"func LookupPolicy(ctx *pulumi.Context, args *LookupPolicyArgs, opts ...pulumi.InvokeOption) (*LookupPolicyResult, error) {\n\tvar rv LookupPolicyResult\n\terr := ctx.Invoke(\"aws:organizations/getPolicy:getPolicy\", args, &rv, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rv, nil\n}",
"func (o TopicPolicyOutput) Policy() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *TopicPolicy) pulumi.StringOutput { return v.Policy }).(pulumi.StringOutput)\n}",
"func (s iotPolicyNamespaceLister) Get(name string) (*v1alpha1.IotPolicy, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"iotpolicy\"), name)\n\t}\n\treturn obj.(*v1alpha1.IotPolicy), nil\n}",
"func (e *Enforcer) GetFilteredNamedPolicy(ctx context.Context, ptype string, fieldIndex int32, fieldValues ...string) ([][]string, error) {\n\tres, err := e.client.remoteClient.GetFilteredNamedPolicy(ctx, &pb.FilteredPolicyRequest{\n\t\tEnforcerHandler: e.handler,\n\t\tPType: ptype,\n\t\tFieldIndex: fieldIndex,\n\t\tFieldValues: fieldValues,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn replyTo2DSlice(res), nil\n}",
"func (e *Enforcer) GetFilteredNamedPolicy(ptype string, fieldIndex int, fieldValues ...string) [][]string {\n\treturn e.model.GetFilteredPolicy(\"p\", ptype, fieldIndex, fieldValues...)\n}",
"func (t TestRepo) GetPolicyByName(org string, name string) (*Policy, error) {\n\tt.ArgsIn[GetPolicyByNameMethod][0] = org\n\tt.ArgsIn[GetPolicyByNameMethod][1] = name\n\tif specialFunc, ok := t.SpecialFuncs[GetPolicyByNameMethod].(func(org string, name string) (*Policy, error)); ok && specialFunc != nil {\n\t\treturn specialFunc(org, name)\n\t}\n\tvar policy *Policy\n\tif t.ArgsOut[GetPolicyByNameMethod][0] != nil {\n\t\tpolicy = t.ArgsOut[GetPolicyByNameMethod][0].(*Policy)\n\t}\n\tvar err error\n\tif t.ArgsOut[GetPolicyByNameMethod][1] != nil {\n\t\terr = t.ArgsOut[GetPolicyByNameMethod][1].(error)\n\t}\n\treturn policy, err\n}",
"func (c *destinationPolicies) Get(name string, options v1.GetOptions) (result *v1alpha2.DestinationPolicy, err error) {\n\tresult = &v1alpha2.DestinationPolicy{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"destinationpolicies\").\n\t\tName(name).\n\t\tVersionedParams(&options, scheme.ParameterCodec).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}",
"func (client IdentityClient) getPolicy(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/policies/{policyId}\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response GetPolicyResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}",
"func (c *PublisherClient) GetTopic(ctx context.Context, req *pubsubpb.GetTopicRequest) (*pubsubpb.Topic, error) {\n\tctx = metadata.NewContext(ctx, c.metadata)\n\tvar resp *pubsubpb.Topic\n\terr := gax.Invoke(ctx, func(ctx context.Context) error {\n\t\tvar err error\n\t\tresp, err = c.client.GetTopic(ctx, req)\n\t\treturn err\n\t}, c.CallOptions.GetTopic...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}",
"func (v *KILLYD) GetTopic(topicName string) *Topic {\n\t// most likely, we already have this topic, so try read lock first.\n\tv.RLock()\n\tt, ok := v.topicMap[topicName]\n\tv.RUnlock()\n\tif ok {\n\t\treturn t\n\t}\n\n\tv.Lock()\n\tt, ok = v.topicMap[topicName]\n\tif ok {\n\t\tv.Unlock()\n\t\treturn t\n\t}\n\tt = NewTopic(topicName, &context{v})\n\tv.topicMap[topicName] = t\n\tv.logf(LOG_INFO, \"TOPIC(%s): created\", t.name)\n\tv.Unlock()\n\treturn t\n}",
"func GetPolicy(serviceName string, baseUrl string) (*Service, error) {\n\tclient := http.Client{}\n\treq, err := http.NewRequest(\"GET\", baseUrl + policyEndpoint + serviceName, nil)\n\n\tif err != nil {\n\t\tlog.Fatal(\"Request to Apache Ranger failed\", err)\n\t\treturn nil, err\n\t}\n\n\tparams := req.URL.Query()\n\tparams.Add(pluginId, serviceName + string(\"@bla\"))\n\n\treq.URL.RawQuery = params.Encode()\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatal(\"Request to Apache Ranger failed\", err)\n\t\treturn nil, err\n\t}\n\n\tdata, _ := ioutil.ReadAll(resp.Body)\n\n\tvar service Service\n\n\terr = json.Unmarshal(data, &service)\n\n\tif err != nil {\n\t\tlog.Fatal(\"Could not unmarshal json data\", err)\n\t\treturn nil, err\n\t}\n\n\treturn &service, nil\n}",
"func (sys *IAMSys) PolicyDBGet(name string) (string, error) {\n\tif name == \"\" {\n\t\treturn \"\", errInvalidArgument\n\t}\n\n\tobjectAPI := newObjectLayerFn()\n\tif objectAPI == nil {\n\t\treturn \"\", errServerNotInitialized\n\t}\n\n\tsys.RLock()\n\tdefer sys.RUnlock()\n\n\tif _, ok := sys.iamUsersMap[name]; !ok {\n\t\treturn \"\", errNoSuchUser\n\t}\n\n\tpolicy := sys.iamUserPolicyMap[name]\n\t// returned policy could be empty\n\treturn policy.Policy, nil\n}",
"func (c *sonicwallNetworkPolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.SonicwallNetworkPolicy, err error) {\n\tresult = &v1alpha1.SonicwallNetworkPolicy{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"sonicwallnetworkpolicies\").\n\t\tName(name).\n\t\tVersionedParams(&options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}",
"func GetAccessPointPolicy(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *AccessPointPolicyState, opts ...pulumi.ResourceOption) (*AccessPointPolicy, error) {\n\tvar resource AccessPointPolicy\n\terr := ctx.ReadResource(\"aws-native:s3objectlambda:AccessPointPolicy\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func GetNetworkPolicy(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *NetworkPolicyState, opts ...pulumi.ResourceOption) (*NetworkPolicy, error) {\n\tvar resource NetworkPolicy\n\terr := ctx.ReadResource(\"kubernetes:extensions/v1beta1:NetworkPolicy\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func (e *Enforcer) GetPolicy() [][]string {\n\treturn e.GetNamedPolicy(\"p\")\n}",
"func (o HPAScalingRulesPtrOutput) SelectPolicy() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *HPAScalingRules) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.SelectPolicy\n\t}).(pulumi.StringPtrOutput)\n}",
"func GetClientTimePolicy(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *ClientTimePolicyState, opts ...pulumi.ResourceOption) (*ClientTimePolicy, error) {\n\tvar resource ClientTimePolicy\n\terr := ctx.ReadResource(\"keycloak:openid/clientTimePolicy:ClientTimePolicy\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func getPolicy(crmService *cloudresourcemanager.Service, projectID string) *cloudresourcemanager.Policy {\n\n\tctx := context.Background()\n\n\tctx, cancel := context.WithTimeout(ctx, time.Second*10)\n\tdefer cancel()\n\trequest := new(cloudresourcemanager.GetIamPolicyRequest)\n\tpolicy, err := crmService.Projects.GetIamPolicy(projectID, request).Do()\n\tif err != nil {\n\t\tlog.Fatalf(\"Projects.GetIamPolicy: %v\", err)\n\t}\n\n\treturn policy\n}",
"func (c *FakeSnatPolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *acisnatv1.SnatPolicy, err error) {\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewRootGetAction(snatpoliciesResource, name), &acisnatv1.SnatPolicy{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*acisnatv1.SnatPolicy), err\n}",
"func GetAlertPolicy(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *AlertPolicyState, opts ...pulumi.ResourceOption) (*AlertPolicy, error) {\n\tvar resource AlertPolicy\n\terr := ctx.ReadResource(\"gcp:monitoring/alertPolicy:AlertPolicy\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func (s sqsQueuePolicyNamespaceLister) Get(name string) (*v1alpha1.SqsQueuePolicy, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"sqsqueuepolicy\"), name)\n\t}\n\treturn obj.(*v1alpha1.SqsQueuePolicy), nil\n}",
"func (e *CachedEnforcer) GetFilteredNamedPolicy(ptype string, fieldIndex int, fieldValues ...string) [][]string {\n\treturn e.api.GetFilteredNamedPolicy(ptype, fieldIndex, fieldValues...)\n}",
"func (c *Client) GetEscalationPolicy(id string, o *GetEscalationPolicyOptions) (*EscalationPolicy, error) {\n\tv, err := query.Values(o)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := c.get(escPath + \"/\" + id + \"?\" + v.Encode())\n\treturn getEscalationPolicyFromResponse(c, resp, err)\n}",
"func ReadPolicy(in io.Reader) (Policy, error) {\n\t// TODO: implement\n\treturn nil, fmt.Errorf(\"not implemented\")\n}",
"func (p *Partition) GetTopic() string {\n\treturn p.topic\n}",
"func GetAccessPolicy(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *AccessPolicyState, opts ...pulumi.ResourceOption) (*AccessPolicy, error) {\n\tvar resource AccessPolicy\n\terr := ctx.ReadResource(\"azure-native:timeseriesinsights:AccessPolicy\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func GetReplicationPolicy(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *ReplicationPolicyState, opts ...pulumi.ResourceOption) (*ReplicationPolicy, error) {\n\tvar resource ReplicationPolicy\n\terr := ctx.ReadResource(\"azure-native:recoveryservices/v20180110:ReplicationPolicy\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func GetTopicName(completeName string) (*TopicName, error) {\n\tvar topicName TopicName\n\t// The short topic name can be:\n\t// - <topic>\n\t// - <tenant>/<namespace>/<topic>\n\tif !strings.Contains(completeName, \"://\") {\n\t\tparts := strings.Split(completeName, \"/\")\n\t\tswitch len(parts) {\n\t\tcase 3:\n\t\t\tcompleteName = persistent.String() + \"://\" + completeName\n\t\tcase 1:\n\t\t\tcompleteName = persistent.String() + \"://\" + PUBLICTENANT + \"/\" + DEFAULTNAMESPACE + \"/\" + parts[0]\n\t\tdefault:\n\t\t\treturn nil, errors.Errorf(\"Invalid short topic name '%s', it should be \"+\n\t\t\t\t\"in the format of <tenant>/<namespace>/<topic> or <topic>\", completeName)\n\t\t}\n\t}\n\n\t// The fully qualified topic name can be:\n\t// <domain>://<tenant>/<namespace>/<topic>\n\n\tparts := strings.SplitN(completeName, \"://\", 2)\n\n\tdomain, err := ParseTopicDomain(parts[0])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttopicName.domain = domain\n\n\trest := parts[1]\n\tparts = strings.SplitN(rest, \"/\", 3)\n\tif len(parts) == 3 {\n\t\ttopicName.tenant = parts[0]\n\t\ttopicName.namespace = parts[1]\n\t\ttopicName.topic = parts[2]\n\t\ttopicName.partitionIndex = getPartitionIndex(completeName)\n\t} else {\n\t\treturn nil, errors.Errorf(\"invalid topic name '%s', it should be in the format of \"+\n\t\t\t\"<tenant>/<namespace>/<topic>\", rest)\n\t}\n\n\tif topicName.topic == \"\" {\n\t\treturn nil, errors.New(\"topic name can not be empty\")\n\t}\n\n\tn, err := GetNameSpaceName(topicName.tenant, topicName.namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttopicName.namespaceName = n\n\n\treturn &topicName, nil\n}",
"func (c *Client) GetTopic() string {\n\treturn c.topic\n}",
"func (ac *Client) GetTopic(ctx context.Context, topicName string, options *GetTopicOptions) (*GetTopicResponse, error) {\n\tvar atomResp *atom.TopicEnvelope\n\t_, err := ac.em.Get(ctx, \"/\"+topicName, &atomResp)\n\n\tif err != nil {\n\t\treturn mapATOMError[GetTopicResponse](err)\n\t}\n\n\ttopicItem, err := newTopicItem(atomResp)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &GetTopicResponse{\n\t\tTopicProperties: topicItem.TopicProperties,\n\t}, nil\n}",
"func (log Log) GetTopic(idx uint) (common.Hash, error) {\n\tif len(log.Topics) <= int(idx) {\n\t\treturn common.Hash{}, fmt.Errorf(\"Log: Unable to get topic #%v for %v\", idx, log)\n\t}\n\n\treturn log.Topics[idx], nil\n}",
"func (o GetServiceTopicsResultOutput) TopicName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GetServiceTopicsResult) *string { return v.TopicName }).(pulumi.StringPtrOutput)\n}",
"func GetOrCreateTopic(name string, ts []string) *Topic {\n\ttopic, err := GetTopic(name)\n\tif err != nil {\n\t\ttopic = NewTopic(name, ts)\n\t\ttopic.Save()\n\t\treturn topic\n\t}\n\treturn topic\n}",
"func NewGetReplicationPolicyOK() *GetReplicationPolicyOK {\n\treturn &GetReplicationPolicyOK{}\n}",
"func GenerateTopic(name string, s v1alpha1.TopicParameters) *pubsub.Topic {\n\tt := &pubsub.Topic{\n\t\tName: name,\n\t\tLabels: s.Labels,\n\t\tKmsKeyName: gcp.StringValue(s.KmsKeyName),\n\t}\n\tif s.MessageStoragePolicy != nil {\n\t\tt.MessageStoragePolicy = &pubsub.MessageStoragePolicy{\n\t\t\tAllowedPersistenceRegions: s.MessageStoragePolicy.AllowedPersistenceRegions,\n\t\t}\n\t}\n\tif s.MessageRetentionDuration != nil {\n\t\tt.MessageRetentionDuration = gcp.StringValue(s.MessageRetentionDuration)\n\t}\n\treturn t\n}",
"func (m *Medium) Topic(name string) (Topic, bool) {\n\tm.mx.RLock()\n\tdefer m.mx.RUnlock()\n\tt, ok := m.topics[name]\n\treturn t, ok\n}",
"func (s *EscalationPoliciesService) Get(id string) (*EscalationPolicy, *Response, error) {\n\turi := fmt.Sprintf(\"escalation_policies/%s\", id)\n\n\tpolicy := new(escalationPolicyWrapper)\n\tresp, err := s.client.Get(uri, policy)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn policy.EscalationPolicy, resp, err\n}",
"func (policy *PolicySvc) findPolicyByName(input interface{}, ctx common.RestContext) (interface{}, error) {\n\tnameStr := ctx.PathVariables[\"policyName\"]\n\tlog.Printf(\"In findPolicy(%s)\\n\", nameStr)\n\tif nameStr == \"\" {\n\t\treturn nil, common.NewError500(fmt.Sprintf(\"Expected policy name, got %s\", nameStr))\n\t}\n\tpolicyDoc, err := policy.store.findPolicyByName(nameStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpolicyDoc.Datacenter = nil\n\treturn policyDoc, nil\n}",
"func (o HPAScalingRulesPatchPtrOutput) SelectPolicy() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *HPAScalingRulesPatch) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.SelectPolicy\n\t}).(pulumi.StringPtrOutput)\n}",
"func (pg *PolicyGroup) GetPolicy() *api.Policy {\n\treturn pg.Policy\n}",
"func GetServerPolicy(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *ServerPolicyState, opts ...pulumi.ResourceOption) (*ServerPolicy, error) {\n\tvar resource ServerPolicy\n\terr := ctx.ReadResource(\"okta:auth/serverPolicy:ServerPolicy\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func GetPolicyStore(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *PolicyStoreState, opts ...pulumi.ResourceOption) (*PolicyStore, error) {\n\tvar resource PolicyStore\n\terr := ctx.ReadResource(\"aws-native:verifiedpermissions:PolicyStore\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func (h *httpJSONRPCClient) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) {\n\tres, err := h.call(\"SessionState.GetConfigPolicy\", []interface{}{})\n\tif err != nil {\n\t\tlogger.WithFields(log.Fields{\n\t\t\t\"_block\": \"GetConfigPolicy\",\n\t\t\t\"result\": fmt.Sprintf(\"%+v\", res),\n\t\t\t\"error\": err,\n\t\t}).Error(\"error getting config policy\")\n\t\treturn nil, err\n\t}\n\tif len(res.Result) == 0 {\n\t\treturn nil, errors.New(res.Error)\n\t}\n\tvar cpr plugin.GetConfigPolicyReply\n\terr = h.encoder.Decode(res.Result, &cpr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cpr.Policy, nil\n}",
"func (tm *topicManager) getTopicForName(name string) (log, error) {\n\ttm.topicsMutex.Lock()\n\tdefer tm.topicsMutex.Unlock()\n\n\tlc, ok := tm.topicNamesToLogs[name]\n\tif ok {\n\t\tlc.refCount++\n\t\treturn lc.l, nil\n\t}\n\n\tid, ok := tm.topicNamesToIds[name]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"No topic with name [%s]\", name)\n\t}\n\n\treturn tm.createNewTopic(name, id)\n}",
"func (ClearTrans) GetTopic() string {\n\treturn \"cy.rubik.clearTrans\"\n}",
"func LookupPolicy(ctx *pulumi.Context, args *LookupPolicyArgs, opts ...pulumi.InvokeOption) (*LookupPolicyResult, error) {\n\topts = internal.PkgInvokeDefaultOpts(opts)\n\tvar rv LookupPolicyResult\n\terr := ctx.Invoke(\"google-native:orgpolicy/v2:getPolicy\", args, &rv, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rv, nil\n}",
"func GetProtectionPolicy(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *ProtectionPolicyState, opts ...pulumi.ResourceOption) (*ProtectionPolicy, error) {\n\tvar resource ProtectionPolicy\n\terr := ctx.ReadResource(\"azure-native:recoveryservices/v20210601:ProtectionPolicy\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func (o HPAScalingRulesOutput) SelectPolicy() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v HPAScalingRules) *string { return v.SelectPolicy }).(pulumi.StringPtrOutput)\n}",
"func getPolicy(policyPath string) (policyContent, error) {\n\tvar policyContentStruct policyContent\n\tpolicyContent, err := os.ReadFile(policyPath)\n\tif err != nil {\n\t\treturn policyContentStruct, fmt.Errorf(\"unable to read policy file: %w\", err)\n\t}\n\tif err := json.Unmarshal(policyContent, &policyContentStruct); err != nil {\n\t\treturn policyContentStruct, fmt.Errorf(\"could not parse trust policies from %s: %w\", policyPath, err)\n\t}\n\treturn policyContentStruct, nil\n}",
"func (o *ProjectWebhook) GetTopicName() datamodel.TopicNameType {\n\treturn ProjectWebhookTopic\n}",
"func (c *FakeHealthCheckPolicies) Get(name string, options v1.GetOptions) (result *v1alpha1.HealthCheckPolicy, err error) {\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewGetAction(healthcheckpoliciesResource, c.ns, name), &v1alpha1.HealthCheckPolicy{})\n\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*v1alpha1.HealthCheckPolicy), err\n}",
"func (a *Client) GetMsgVpnSequencedTopic(params *GetMsgVpnSequencedTopicParams, authInfo runtime.ClientAuthInfoWriter) (*GetMsgVpnSequencedTopicOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetMsgVpnSequencedTopicParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getMsgVpnSequencedTopic\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/msgVpns/{msgVpnName}/sequencedTopics/{sequencedTopic}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetMsgVpnSequencedTopicReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetMsgVpnSequencedTopicOK), nil\n\n}",
"func (c *PolicyService) GetPolicy(opt *GetPolicyOptions, options ...OptionFunc) ([]*Policy, *Response, error) {\n\n\treq, err := c.client.newRequest(\"GET\", \"core/credentials/Policy\", opt, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif opt.ProductKey == nil {\n\t\treturn nil, nil, ErrMissingProductKey\n\t}\n\n\treq.Header.Set(\"Api-Version\", CredentialsAPIVersion)\n\treq.Header.Set(\"X-Product-Key\", *opt.ProductKey)\n\n\tvar policyGetResponse []*Policy\n\n\tresp, err := c.client.Do(req, &policyGetResponse)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\t// Set ProductKey\n\tfor _, policy := range policyGetResponse {\n\t\tpolicy.ProductKey = *opt.ProductKey\n\t}\n\treturn policyGetResponse, resp, err\n}",
"func (r *TopicsService) Get(topic string) *TopicsGetCall {\n\tc := &TopicsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.topic = topic\n\treturn c\n}",
"func (m *Client) GetSLAPolicy(arg0 context.Context, arg1 int64) (zendesk.SLAPolicy, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetSLAPolicy\", arg0, arg1)\n\tret0, _ := ret[0].(zendesk.SLAPolicy)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}",
"func GetPolicyFromDB(c echo.Context) error {\n\tid := c.Param(\"id\")\n\tlog.Printf(\"fetching policy from adapter %v\", id)\n\n\tok, err, res := GetAdapterPolicies(id)\n\tif err != \"\" {\n\t\tlog.Fatal(err)\n\t}\n\n\tif ok {\n\t\tlog.Print(res)\n\t}\n\treturn c.String(http.StatusOK, fmt.Sprintf(\"%v\", res))\n}"
] | [
"0.64879876",
"0.64640427",
"0.64134675",
"0.62294334",
"0.6224702",
"0.620955",
"0.60941464",
"0.59451884",
"0.5925728",
"0.5681729",
"0.5660166",
"0.56317604",
"0.56239426",
"0.5612255",
"0.5568526",
"0.55326533",
"0.5526049",
"0.54757094",
"0.5453719",
"0.5436477",
"0.5389416",
"0.5373329",
"0.5371217",
"0.53346366",
"0.5331727",
"0.5320583",
"0.530647",
"0.52730733",
"0.5262324",
"0.52369964",
"0.5226337",
"0.5197623",
"0.5188008",
"0.51700306",
"0.5164719",
"0.5164624",
"0.51479226",
"0.51392233",
"0.5125589",
"0.5109177",
"0.50824904",
"0.50793207",
"0.5071915",
"0.50710875",
"0.5065798",
"0.49563882",
"0.49559602",
"0.4942405",
"0.49348325",
"0.4919733",
"0.49144086",
"0.48986405",
"0.4895064",
"0.48834717",
"0.48811784",
"0.48453575",
"0.48216152",
"0.4817622",
"0.48002502",
"0.47968012",
"0.47903252",
"0.47878724",
"0.47865313",
"0.4782593",
"0.4777862",
"0.47701833",
"0.47583067",
"0.47454762",
"0.47396627",
"0.47135818",
"0.4689308",
"0.4680461",
"0.46673882",
"0.46569645",
"0.4653781",
"0.4651345",
"0.46456188",
"0.46448743",
"0.46326432",
"0.4629392",
"0.46211708",
"0.46135098",
"0.4609146",
"0.4603295",
"0.46000516",
"0.45991454",
"0.45979822",
"0.4593487",
"0.45893326",
"0.45806694",
"0.4578925",
"0.4571472",
"0.45709175",
"0.456339",
"0.45605928",
"0.45549914",
"0.45372",
"0.4522131",
"0.4521411"
] | 0.70151097 | 1 |
The ARN of the SNS topic | func (o TopicPolicyOutput) Arn() pulumi.StringOutput {
return o.ApplyT(func(v *TopicPolicy) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func TopicArn(client *sns.SNS, topic string) (topicArn string, err error) {\n\tif len(topic) < 1 {\n\t\terr = errors.New(\"Invalid empty parameter topic\")\n\t\treturn\n\t}\n\ttopics, err := client.ListTopics(nil)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"Error executing sns.ListTopics\")\n\t\treturn\n\t}\n\n\tfor _, t := range topics.Topics {\n\t\ttopicArn = *t.TopicArn\n\t\tif topic == topicArn[strings.LastIndex(topicArn, \":\")+1:] {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}",
"func (o ConfigurationSetEventDestinationEventDestinationSnsDestinationOutput) TopicArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ConfigurationSetEventDestinationEventDestinationSnsDestination) string { return v.TopicArn }).(pulumi.StringOutput)\n}",
"func (o MitigationActionPublishFindingToSnsParamsOutput) TopicArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MitigationActionPublishFindingToSnsParams) string { return v.TopicArn }).(pulumi.StringOutput)\n}",
"func (r *TopicRule) Arn() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"arn\"])\n}",
"func (o ConfigurationSetEventDestinationEventDestinationSnsDestinationPtrOutput) TopicArn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ConfigurationSetEventDestinationEventDestinationSnsDestination) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.TopicArn\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o MitigationActionPublishFindingToSnsParamsPtrOutput) TopicArn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *MitigationActionPublishFindingToSnsParams) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.TopicArn\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o AnomalySubscriptionOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AnomalySubscription) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o ClusterOutput) NotificationTopicArn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Cluster) pulumi.StringPtrOutput { return v.NotificationTopicArn }).(pulumi.StringPtrOutput)\n}",
"func (a *Funcs) ARN() (string, error) {\n\ta.stsInit.Do(a.initSTS)\n\treturn a.sts.Arn()\n}",
"func (o TopicRuleSnsOutput) RoleArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleSns) string { return v.RoleArn }).(pulumi.StringOutput)\n}",
"func (o ResponsePlanIncidentTemplateNotificationTargetOutput) SnsTopicArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResponsePlanIncidentTemplateNotificationTarget) string { return v.SnsTopicArn }).(pulumi.StringOutput)\n}",
"func (o GetResponsePlanIncidentTemplateNotificationTargetOutput) SnsTopicArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetResponsePlanIncidentTemplateNotificationTarget) string { return v.SnsTopicArn }).(pulumi.StringOutput)\n}",
"func (o TopicRuleSnsOutput) TargetArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleSns) string { return v.TargetArn }).(pulumi.StringOutput)\n}",
"func (o StreamOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Stream) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o TopicRuleKafkaOutput) DestinationArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleKafka) string { return v.DestinationArn }).(pulumi.StringOutput)\n}",
"func (r *ServiceLinkedRole) Arn() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"arn\"])\n}",
"func (o ListenerRuleOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ListenerRule) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o AggregateAuthorizationOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AggregateAuthorization) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o ClusterOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Cluster) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o AssociationOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Association) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o NetworkInsightsAnalysisOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *NetworkInsightsAnalysis) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o ReplicaExternalKeyOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ReplicaExternalKey) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (r *FirehoseDeliveryStream) Arn() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"arn\"])\n}",
"func (r *ScheduledAction) Arn() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"arn\"])\n}",
"func (o TaskDefinitionOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *TaskDefinition) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o SchemaOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Schema) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o ClusterInstanceOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ClusterInstance) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o NetworkProfileOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *NetworkProfile) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (r *ResourceGroup) Arn() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"arn\"])\n}",
"func (o LookupSigningProfileResultOutput) Arn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupSigningProfileResult) *string { return v.Arn }).(pulumi.StringPtrOutput)\n}",
"func (o ServiceOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Service) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o TaskOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Task) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o SignalingChannelOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SignalingChannel) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (r *Cluster) Arn() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"arn\"])\n}",
"func (r *Cluster) Arn() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"arn\"])\n}",
"func (o TopicRuleSnsPtrOutput) RoleArn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TopicRuleSns) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.RoleArn\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o LookupLoggingConfigurationResultOutput) Arn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupLoggingConfigurationResult) *string { return v.Arn }).(pulumi.StringPtrOutput)\n}",
"func (o TopicRuleSqsOutput) RoleArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleSqs) string { return v.RoleArn }).(pulumi.StringOutput)\n}",
"func (o AccessPointOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AccessPoint) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o ThingGroupOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ThingGroup) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func FormatARN(partition, location string) string {\n\treturn fmt.Sprintf(\"arn:%s:s3:::%s\", partition, location)\n}",
"func (o LookupAliasResultOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupAliasResult) string { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o LookupAliasResultOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupAliasResult) string { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o LookupMulticastDomainResultOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupMulticastDomainResult) string { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o TopicRuleRepublishOutput) RoleArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleRepublish) string { return v.RoleArn }).(pulumi.StringOutput)\n}",
"func (o LookupListenerResultOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupListenerResult) string { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o SnapshotOutput) NamespaceArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Snapshot) pulumi.StringOutput { return v.NamespaceArn }).(pulumi.StringOutput)\n}",
"func (o AppMonitorOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AppMonitor) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o LookupConfigurationResultOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupConfigurationResult) string { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o DomainNameOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DomainName) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o ApplicationOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Application) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o TopicRuleErrorActionKafkaOutput) DestinationArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleErrorActionKafka) string { return v.DestinationArn }).(pulumi.StringOutput)\n}",
"func (r *Rule) Arn() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"arn\"])\n}",
"func (o DataSourceOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DataSource) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o LookupManagedPrefixListResultOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupManagedPrefixListResult) string { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o TopicRuleErrorActionSnsOutput) RoleArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleErrorActionSns) string { return v.RoleArn }).(pulumi.StringOutput)\n}",
"func (o LookupGroupResultOutput) Arn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupGroupResult) *string { return v.Arn }).(pulumi.StringPtrOutput)\n}",
"func (o ContainerServiceOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ContainerService) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o QueueOutput) InstanceArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Queue) pulumi.StringOutput { return v.InstanceArn }).(pulumi.StringOutput)\n}",
"func (o LookupPolicyResultOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupPolicyResult) string { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o LookupTaskDefinitionResultOutput) Arn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupTaskDefinitionResult) *string { return v.Arn }).(pulumi.StringPtrOutput)\n}",
"func (o AssociationOutput) ResourceArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Association) pulumi.StringOutput { return v.ResourceArn }).(pulumi.StringOutput)\n}",
"func (o ReplicationSetOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ReplicationSet) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o TopicRuleCloudwatchMetricOutput) RoleArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleCloudwatchMetric) string { return v.RoleArn }).(pulumi.StringOutput)\n}",
"func (o PlaybackKeyPairOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PlaybackKeyPair) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o CustomLayerOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *CustomLayer) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o CustomerGatewayOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *CustomerGateway) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o AnalyzerOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Analyzer) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o TopicRuleTimestreamOutput) RoleArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleTimestream) string { return v.RoleArn }).(pulumi.StringOutput)\n}",
"func (svc *SNS) createTopic(name string) (topicARN string, err error) {\n\ttopicName := svc.prefix + name\n\tin := &SDK.CreateTopicInput{\n\t\tName: pointers.String(topicName),\n\t}\n\tresp, err := svc.client.CreateTopic(in)\n\tif err != nil {\n\t\tsvc.Errorf(\"error on `CreateTopic` operation; name=%s; error=%s;\", name, err.Error())\n\t\treturn \"\", err\n\t}\n\treturn *resp.TopicArn, nil\n}",
"func (r *DomainIdentity) Arn() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"arn\"])\n}",
"func (o LookupLinkResultOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupLinkResult) string { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o PhpAppLayerOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PhpAppLayer) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o BucketOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Bucket) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o BucketOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Bucket) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (r *Policy) Arn() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"arn\"])\n}",
"func (o TopicRuleSqsPtrOutput) RoleArn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TopicRuleSqs) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.RoleArn\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o TrailOutput) SnsTopicName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Trail) pulumi.StringPtrOutput { return v.SnsTopicName }).(pulumi.StringPtrOutput)\n}",
"func (o GetQuicksightGroupResultOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetQuicksightGroupResult) string { return v.Arn }).(pulumi.StringOutput)\n}",
"func (e *Ender) Topic() string {\n\treturn fmt.Sprintf(queues.TopicBroadcastFormat.String(), e.broadcastModel.GetID())\n}",
"func (o TopicRuleLambdaOutput) FunctionArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleLambda) string { return v.FunctionArn }).(pulumi.StringOutput)\n}",
"func (o FaqOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Faq) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (r *Distribution) Arn() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"arn\"])\n}",
"func (r *LogGroup) Arn() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"arn\"])\n}",
"func (o LookupAuthorizerResultOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupAuthorizerResult) string { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o TopicRuleS3Output) RoleArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleS3) string { return v.RoleArn }).(pulumi.StringOutput)\n}",
"func (o PlacementGroupOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PlacementGroup) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o TopicRuleCloudwatchAlarmOutput) RoleArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleCloudwatchAlarm) string { return v.RoleArn }).(pulumi.StringOutput)\n}",
"func (o LookupProfileResultOutput) Arn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupProfileResult) *string { return v.Arn }).(pulumi.StringPtrOutput)\n}",
"func (o TopicRuleIotEventOutput) RoleArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleIotEvent) string { return v.RoleArn }).(pulumi.StringOutput)\n}",
"func (o TopicRuleSnsPtrOutput) TargetArn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TopicRuleSns) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.TargetArn\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o LookupWirelessDeviceResultOutput) Arn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupWirelessDeviceResult) *string { return v.Arn }).(pulumi.StringPtrOutput)\n}",
"func (o TopicRuleDynamodbOutput) RoleArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleDynamodb) string { return v.RoleArn }).(pulumi.StringOutput)\n}",
"func (o LookupTaskTemplateResultOutput) Arn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupTaskTemplateResult) *string { return v.Arn }).(pulumi.StringPtrOutput)\n}",
"func (o SnapshotOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Snapshot) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o LaunchOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Launch) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o LookupInstanceResultOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupInstanceResult) string { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o PermissionSetOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PermissionSet) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}",
"func (o TopicRuleErrorActionRepublishOutput) RoleArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleErrorActionRepublish) string { return v.RoleArn }).(pulumi.StringOutput)\n}",
"func (o LookupAnalyzerResultOutput) Arn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupAnalyzerResult) *string { return v.Arn }).(pulumi.StringPtrOutput)\n}"
] | [
"0.69621265",
"0.6895645",
"0.68012255",
"0.67309815",
"0.6554301",
"0.6484052",
"0.63492167",
"0.62923425",
"0.6269797",
"0.61727065",
"0.61695236",
"0.60918313",
"0.60273963",
"0.60163915",
"0.59327096",
"0.5930566",
"0.58926547",
"0.5889949",
"0.58889246",
"0.5885422",
"0.5868473",
"0.5850069",
"0.5847201",
"0.5838548",
"0.583375",
"0.5806053",
"0.57955253",
"0.57901615",
"0.5773975",
"0.57636034",
"0.5745989",
"0.5745336",
"0.5733713",
"0.57246953",
"0.57246953",
"0.5723568",
"0.5718221",
"0.57162094",
"0.5687299",
"0.567698",
"0.5650792",
"0.56377196",
"0.56377196",
"0.56213593",
"0.5618639",
"0.56146777",
"0.56078714",
"0.56024957",
"0.55949974",
"0.55930704",
"0.5592748",
"0.5572533",
"0.55719393",
"0.5552899",
"0.5549222",
"0.5533548",
"0.55225253",
"0.5513949",
"0.55090284",
"0.5507772",
"0.55073875",
"0.55038446",
"0.5503617",
"0.5498243",
"0.54935044",
"0.54923445",
"0.5491485",
"0.5487742",
"0.5487358",
"0.5485714",
"0.54852444",
"0.5479014",
"0.5466238",
"0.5461728",
"0.5461728",
"0.5456738",
"0.54553956",
"0.54506487",
"0.54494286",
"0.5445377",
"0.5442781",
"0.5442582",
"0.54386914",
"0.5432288",
"0.5430298",
"0.5428704",
"0.5424812",
"0.5424744",
"0.54240996",
"0.5418473",
"0.5418415",
"0.5411314",
"0.5382111",
"0.53800166",
"0.537815",
"0.5366057",
"0.53634846",
"0.5363034",
"0.5360599",
"0.5357919"
] | 0.6557125 | 4 |
The AWS Account ID of the SNS topic owner | func (o TopicPolicyOutput) Owner() pulumi.StringOutput {
return o.ApplyT(func(v *TopicPolicy) pulumi.StringOutput { return v.Owner }).(pulumi.StringOutput)
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (sm S3Manager) AWSSessionAccountID(sess *session.Session) (acID string, err error) {\n\tsvc := sts.New(sess)\n\tresult, err := svc.GetCallerIdentity(&sts.GetCallerIdentityInput{})\n\tif err != nil {\n\t\tfmt.Printf(\"Error requesting AWS caller identity: %v\", err.Error())\n\t\treturn\n\t}\n\tacID = *result.Account\n\treturn\n}",
"func TopicArn(client *sns.SNS, topic string) (topicArn string, err error) {\n\tif len(topic) < 1 {\n\t\terr = errors.New(\"Invalid empty parameter topic\")\n\t\treturn\n\t}\n\ttopics, err := client.ListTopics(nil)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"Error executing sns.ListTopics\")\n\t\treturn\n\t}\n\n\tfor _, t := range topics.Topics {\n\t\ttopicArn = *t.TopicArn\n\t\tif topic == topicArn[strings.LastIndex(topicArn, \":\")+1:] {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}",
"func (topic *Topic) Owner() *genruntime.ResourceReference {\n\tgroup, kind := genruntime.LookupOwnerGroupKind(topic.Spec)\n\treturn &genruntime.ResourceReference{\n\t\tGroup: group,\n\t\tKind: kind,\n\t\tName: topic.Spec.Owner.Name,\n\t}\n}",
"func (rule *NamespacesTopicsSubscriptionsRule) Owner() *genruntime.ResourceReference {\n\tgroup, kind := genruntime.LookupOwnerGroupKind(rule.Spec)\n\treturn &genruntime.ResourceReference{\n\t\tGroup: group,\n\t\tKind: kind,\n\t\tName: rule.Spec.Owner.Name,\n\t}\n}",
"func (subscription *NamespacesTopicsSubscription) Owner() *genruntime.ResourceReference {\n\tgroup, kind := genruntime.LookupOwnerGroupKind(subscription.Spec)\n\treturn &genruntime.ResourceReference{\n\t\tGroup: group,\n\t\tKind: kind,\n\t\tName: subscription.Spec.Owner.Name,\n\t}\n}",
"func (self *SHuaweiClient) GetOwnerId() (string, error) {\n\tif len(self.ownerId) > 0 {\n\t\treturn self.ownerId, nil\n\t}\n\tuserId, err := self.GetUserId()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"SHuaweiClient.GetOwnerId.GetUserId\")\n\t}\n\n\tclient, err := self.newGeneralAPIClient()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"SHuaweiClient.GetOwnerId.newGeneralAPIClient\")\n\t}\n\n\ttype user struct {\n\t\tDomainId string `json:\"domain_id\"`\n\t\tName string `json:\"name\"`\n\t\tCreateTime string\n\t}\n\n\tret := &user{}\n\terr = DoGet(client.Users.Get, userId, nil, ret)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"SHuaweiClient.GetOwnerId.DoGet\")\n\t}\n\tself.ownerName = ret.Name\n\t// 2021-02-02 02:43:28.0\n\tself.ownerCreateTime, _ = timeutils.ParseTimeStr(strings.TrimSuffix(ret.CreateTime, \".0\"))\n\tself.ownerId = ret.DomainId\n\treturn self.ownerId, nil\n}",
"func (w *Watch) OwnerID() uint64 {\n\treturn w.owner.id\n}",
"func (o BucketNotificationTopicOutput) Id() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketNotificationTopic) *string { return v.Id }).(pulumi.StringPtrOutput)\n}",
"func (o SecurityGroupIngressOutput) SecurityGroupOwnerId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v SecurityGroupIngress) *string { return v.SecurityGroupOwnerId }).(pulumi.StringPtrOutput)\n}",
"func (j *ScheduledJob) Owner() security.SQLUsername {\n\treturn j.rec.Owner\n}",
"func (sub *Subscription) ID() string {\n return sub.id\n}",
"func (o AnomalySubscriptionOutput) AccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AnomalySubscription) pulumi.StringOutput { return v.AccountId }).(pulumi.StringOutput)\n}",
"func (o *ProjectApiKey) GetOwnerId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.OwnerId\n}",
"func getCreator() string {\n\tserializedIdentity := &mspProtobuf.SerializedIdentity{}\n\teCertBytes, _ := base64.StdEncoding.DecodeString(getTxCreatorECertBase64())\n\tserializedIdentity.IdBytes = []byte(eCertBytes)\n\tserializedIdentity.Mspid = \"ca.org1.example.com\"\n\tserializedIdentityBytes, _ := proto.Marshal(serializedIdentity)\n\n\treturn string(serializedIdentityBytes)\n}",
"func (c *Client) AccountSid() string {\n\treturn c.accountSid\n}",
"func (m *ScheduleChangeRequest) GetSenderUserId()(*string) {\n val, err := m.GetBackingStore().Get(\"senderUserId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (o *Channel) GetResourceOwnerId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.ResourceOwnerId\n}",
"func (c *Consumer) ID() string { return c.id }",
"func getWorkerIdentity(taskqueueName string) string {\n\treturn fmt.Sprintf(\"%d@%s@%s\", os.Getpid(), getHostName(), taskqueueName)\n}",
"func shareID(account string, createdOn int64) string {\n\tvar buf bytes.Buffer\n\t_, _ = buf.WriteString(hex.EncodeToString(nanoToBigEndianBytes(createdOn)))\n\t_, _ = buf.WriteString(account)\n\treturn buf.String()\n}",
"func (o *Echo) GetTopicKey() string {\n\tvar i interface{} = o.ID\n\tif s, ok := i.(string); ok {\n\t\treturn s\n\t}\n\treturn fmt.Sprintf(\"%v\", i)\n}",
"func (o LookupGatewayResultOutput) OwnerAccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupGatewayResult) string { return v.OwnerAccountId }).(pulumi.StringOutput)\n}",
"func getAWSAccountID(ia string) string {\n\treturn strings.Split(ia, \":\")[1]\n}",
"func (theAccount Account) Owner() string {\n\treturn theAccount.owner\n}",
"func (o ConfigurationSetEventDestinationEventDestinationSnsDestinationOutput) TopicArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ConfigurationSetEventDestinationEventDestinationSnsDestination) string { return v.TopicArn }).(pulumi.StringOutput)\n}",
"func (m *UnifiedRoleAssignmentScheduleRequest) GetPrincipalId()(*string) {\n return m.principalId\n}",
"func (r *ReplyTopic) ClientID() string {\n\treturn r.c\n}",
"func (k Keeper) GetMessageOwner(ctx sdk.Context, id uint64) string {\n\treturn k.GetMessage(ctx, id).Creator\n}",
"func (c *Consumer) Topic() string { return c.topic }",
"func (o ConfigurationSetEventDestinationEventDestinationSnsDestinationPtrOutput) TopicArn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ConfigurationSetEventDestinationEventDestinationSnsDestination) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.TopicArn\n\t}).(pulumi.StringPtrOutput)\n}",
"func IdentifierFromMsg(msg chat1.MsgSummary) string {\n\tswitch msg.Channel.MembersType {\n\tcase \"team\":\n\t\treturn msg.Channel.Name\n\tdefault:\n\t\treturn msg.Sender.Username\n\t}\n}",
"func (o GatewayAssociationProposalOutput) AssociatedGatewayOwnerAccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *GatewayAssociationProposal) pulumi.StringOutput { return v.AssociatedGatewayOwnerAccountId }).(pulumi.StringOutput)\n}",
"func (r *ReplyTopic) SessionID() string {\n\treturn r.s\n}",
"func (o TrailOutput) SnsTopicName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Trail) pulumi.StringPtrOutput { return v.SnsTopicName }).(pulumi.StringPtrOutput)\n}",
"func (me TAttlistGeneralNoteOwner) String() string { return xsdt.Token(me).String() }",
"func (o SynchronizationJobOutput) ServicePrincipalId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SynchronizationJob) pulumi.StringOutput { return v.ServicePrincipalId }).(pulumi.StringOutput)\n}",
"func (r RoleARN) AccountID() string {\n\treturn r.accountID\n}",
"func SubscriptionID() string {\n\treturn subscriptionID\n}",
"func SubscriptionID() string {\n\treturn subscriptionID\n}",
"func (o SubnetOutput) OwnerId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Subnet) pulumi.StringOutput { return v.OwnerId }).(pulumi.StringOutput)\n}",
"func (s *Stream) Owner() string {\n\tif s.OwnerRaw == nil {\n\t\treturn \"\"\n\t}\n\n\treturn *s.OwnerRaw\n}",
"func (o AwsVpcPeeringConnectionOutput) AwsAccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AwsVpcPeeringConnection) pulumi.StringOutput { return v.AwsAccountId }).(pulumi.StringOutput)\n}",
"func (o BucketAclV2AccessControlPolicyOwnerOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketAclV2AccessControlPolicyOwner) string { return v.Id }).(pulumi.StringOutput)\n}",
"func (o NamespaceCustomerManagedKeyOutput) EventhubNamespaceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *NamespaceCustomerManagedKey) pulumi.StringOutput { return v.EventhubNamespaceId }).(pulumi.StringOutput)\n}",
"func (o KafkaAclOutput) Username() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *KafkaAcl) pulumi.StringOutput { return v.Username }).(pulumi.StringOutput)\n}",
"func getUserIDKey(token string) string {\n\treturn utils.RedisKey(\"TOKEN\", \"getUserID\", token)\n}",
"func (o AttachmentAccepterOutput) OwnerAccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AttachmentAccepter) pulumi.StringOutput { return v.OwnerAccountId }).(pulumi.StringOutput)\n}",
"func getOwnerSidString(sd []byte) (string, error) {\n\t// Make sure we have enough bytes to safely read the required fields.\n\tif len(sd) < int(unsafe.Sizeof(SECURITY_DESCRIPTOR_RELATIVE{})) {\n\t\treturn \"\", fmt.Errorf(\"Short Security Descriptor: %d bytes!\", len(sd))\n\t}\n\n\t// Only valid revision is 1, verify that.\n\trevision := getRevision(sd)\n\tif revision != SID_REVISION {\n\t\treturn \"\", fmt.Errorf(\"Invalid SID revision (%d), expected %d!\", revision, SID_REVISION)\n\t}\n\n\t// SECURITY_DESCRIPTOR_RELATIVE.OffsetOwner.\n\toffsetOwner := binary.LittleEndian.Uint32(sd[4:8])\n\tif offsetOwner >= uint32(len(sd)) {\n\t\treturn \"\", fmt.Errorf(\"offsetOwner (%d) points outside Security Descriptor of size %d bytes!\",\n\t\t\toffsetOwner, len(sd))\n\t}\n\n\tsidStr, err := sidToString(sd[offsetOwner:])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn \"O:\" + sidStr, nil\n}",
"func (m *Metadata) AccountID(ctx context.Context) (string, error) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tif m.client == nil {\n\t\tclient, err := NewClient()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tm.client = client\n\t}\n\n\tif m.accountID == \"\" {\n\t\tapiKeyDetails, err := m.client.GetAuthenticatorAPIKeyDetails(ctx)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tm.accountID = *apiKeyDetails.AccountID\n\t}\n\n\treturn m.accountID, nil\n}",
"func (o ResponsePlanIncidentTemplateNotificationTargetOutput) SnsTopicArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResponsePlanIncidentTemplateNotificationTarget) string { return v.SnsTopicArn }).(pulumi.StringOutput)\n}",
"func (t *Token) UserID() string {\n\tclaims, ok := t.JWT.Claims.(*Claims)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn claims.Subject\n}",
"func (p Order) GetOwnerID() string {\n\treturn p.OwnerID.Hex()\n}",
"func (utilityProtocol *UtilityProtocol) GetAssociatedNexUniqueIDWithMyPrincipalID(handler func(err error, client *nex.Client, callID uint32)) {\n\tutilityProtocol.GetAssociatedNexUniqueIDWithMyPrincipalIDHandler = handler\n}",
"func (c *Client)GetOwner(name string)string{\n\treturn strings.Split(name,\"-\")[0]\n}",
"func GetSenderID(event *linebot.Event) string {\r\n\tswitch event.Source.Type {\r\n\tcase linebot.EventSourceTypeGroup:\r\n\t\treturn event.Source.GroupID\r\n\tcase linebot.EventSourceTypeRoom:\r\n\t\treturn event.Source.RoomID\r\n\tcase linebot.EventSourceTypeUser:\r\n\t\treturn event.Source.UserID\r\n\t}\r\n\tlog.Printf(\"Can not get sender id. type: %v\\n\", event.Source.Type)\r\n\treturn \"\"\r\n}",
"func (o ContainerServiceOutput) PrincipalArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ContainerService) pulumi.StringOutput { return v.PrincipalArn }).(pulumi.StringOutput)\n}",
"func AWSGetToken(accessKeyId, secretAccessKey, region, clusterID string) (string, error) {\n\tcred := credentials.NewStaticCredentials(accessKeyId, secretAccessKey, \"\")\n\n\tsess, err := session.NewSession(&aws.Config{Region: aws.String(region), Credentials: cred})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstsClient := sts.New(sess)\n\n\trequest, _ := stsClient.GetCallerIdentityRequest(&sts.GetCallerIdentityInput{})\n\trequest.HTTPRequest.Header.Add(\"x-k8s-aws-id\", clusterID)\n\tpresignedURLString, err := request.Presign(60)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(`{\"token\": \"k8s-aws-v1.%s\"}`, base64.RawURLEncoding.EncodeToString([]byte(presignedURLString))), nil\n}",
"func (r *RouteTable) OwnerId() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"ownerId\"])\n}",
"func (o RouteOutput) InstanceOwnerId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Route) pulumi.StringOutput { return v.InstanceOwnerId }).(pulumi.StringOutput)\n}",
"func (m *AmazonResourceEvidence) GetAmazonAccountId()(*string) {\n val, err := m.GetBackingStore().Get(\"amazonAccountId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (k *SKey) UID() string {\n\tb := bytes.Buffer{}\n\tb.WriteString(k.tableName)\n\tb.WriteString(k.id)\n\treturn b.String()\n}",
"func (o MitigationActionPublishFindingToSnsParamsOutput) TopicArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MitigationActionPublishFindingToSnsParams) string { return v.TopicArn }).(pulumi.StringOutput)\n}",
"func (o *Transaction) GetAccountOwner() string {\n\tif o == nil || o.AccountOwner.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn *o.AccountOwner.Get()\n}",
"func (m *SmsLogRow) GetUserPrincipalName()(*string) {\n val, err := m.GetBackingStore().Get(\"userPrincipalName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (a Account) ShowOwner() string {\n\treturn a.owner\n}",
"func (o MitigationActionPublishFindingToSnsParamsPtrOutput) TopicArn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *MitigationActionPublishFindingToSnsParams) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.TopicArn\n\t}).(pulumi.StringPtrOutput)\n}",
"func (me *CONFIGURATION_IMPL) UserId() string{\r\n return me.user-id\r\n}",
"func (s MessageState) UserID() disgord.Snowflake {\n\treturn s.Event.Message.Author.ID\n}",
"func (sa ServiceAccount) Key() string {\n\treturn fmt.Sprintf(\"%s/%s\", sa.Namespace, sa.Name)\n}",
"func getUTSNamespace(pid uint32) string {\n\treturn fmt.Sprintf(utsNSFormat, pid)\n}",
"func (t *Transaction) Owner() string {\n\treturn utils.EncodeToBase64(t.owner.Bytes())\n}",
"func xmppUser(senderId string) string {\n\treturn senderId + \"@\" + xmppHost\n}",
"func (s *Session) PublicUserID() string {\n\treturn strconv.FormatInt(s.UserID, 10)\n}",
"func (o DelegatedAdminAccountOutput) AccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DelegatedAdminAccount) pulumi.StringOutput { return v.AccountId }).(pulumi.StringOutput)\n}",
"func (o MemberOutput) AccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Member) pulumi.StringOutput { return v.AccountId }).(pulumi.StringOutput)\n}",
"func (rule *NamespacesEventhubsAuthorizationRule) Owner() *genruntime.ResourceReference {\n\tgroup, kind := genruntime.LookupOwnerGroupKind(rule.Spec)\n\treturn &genruntime.ResourceReference{\n\t\tGroup: group,\n\t\tKind: kind,\n\t\tName: rule.Spec.Owner.Name,\n\t}\n}",
"func (o GetResponsePlanIncidentTemplateNotificationTargetOutput) SnsTopicArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetResponsePlanIncidentTemplateNotificationTarget) string { return v.SnsTopicArn }).(pulumi.StringOutput)\n}",
"func (o FluxConfigurationBlobStorageServicePrincipalOutput) ClientId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FluxConfigurationBlobStorageServicePrincipal) string { return v.ClientId }).(pulumi.StringOutput)\n}",
"func (o ResourceGroupOutput) AccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ResourceGroup) pulumi.StringOutput { return v.AccountId }).(pulumi.StringOutput)\n}",
"func (pm *MultiFactorPush) AmazonSNS() (*MultiFactorProviderAmazonSNS, error) {\n\tsc := new(MultiFactorProviderAmazonSNS)\n\terr := pm.m.get(pm.m.uri(\"guardian\", \"factors\", \"push-notification\", \"providers\", \"sns\"), sc)\n\treturn sc, err\n}",
"func topic(prefix string, obj metav1.Object) string {\n\treturn fmt.Sprintf(\"%s.%s.%s\", prefix, obj.GetNamespace(), obj.GetName())\n}",
"func generateCloudWatchLogStreamPrefix(context context.T, commandID string) (string, error) {\n\n\tinstanceID, err := context.Identity().ShortInstanceID()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%s/%s\", commandID, instanceID), nil\n}",
"func (o ClusterOutput) NotificationTopicArn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Cluster) pulumi.StringPtrOutput { return v.NotificationTopicArn }).(pulumi.StringPtrOutput)\n}",
"func (id ClientEncryptionKeyId) ID() string {\n\tfmtString := \"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.DocumentDB/databaseAccounts/%s/sqlDatabases/%s/clientEncryptionKeys/%s\"\n\treturn fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.DatabaseAccountName, id.SqlDatabaseName, id.ClientEncryptionKeyName)\n}",
"func (o GetTopicSubscriptionsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetTopicSubscriptionsResult) string { return v.Id }).(pulumi.StringOutput)\n}",
"func (cc *KubeClusterClient) GetNamespaceUID(\n\tctx context.Context,\n\tnamespace string,\n) (string, error) {\n\treturn cc.kubeClient.GetNamespaceUID(ctx, namespace)\n}",
"func (o *ProjectWebhook) GetTopicKey() string {\n\tvar i interface{} = o.ID\n\tif s, ok := i.(string); ok {\n\t\treturn s\n\t}\n\treturn fmt.Sprintf(\"%v\", i)\n}",
"func (o VpcAttachmentOutput) OwnerAccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *VpcAttachment) pulumi.StringOutput { return v.OwnerAccountId }).(pulumi.StringOutput)\n}",
"func (o LookupManagedPrefixListResultOutput) OwnerId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupManagedPrefixListResult) string { return v.OwnerId }).(pulumi.StringOutput)\n}",
"func (CcsAwsSession *ccsAwsSession) GetAccountId() string {\n\treturn CcsAwsSession.accountId\n}",
"func (o ConnectionCloudSqlOutput) ServiceAccountId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ConnectionCloudSql) *string { return v.ServiceAccountId }).(pulumi.StringPtrOutput)\n}",
"func APIGatewayUserID(ctx events.APIGatewayProxyRequestContext) string {\n\tif ctx.Authorizer == nil {\n\t\treturn \"\"\n\t}\n\tclaims := ctx.Authorizer[\"claims\"]\n\tif claims == nil {\n\t\treturn \"\"\n\t}\n\tclaimsMap, ok := claims.(map[string]interface{})\n\tif !ok {\n\t\treturn \"\"\n\t}\n\tuserID := claimsMap[\"sub\"]\n\tif userID == nil {\n\t\treturn \"\"\n\t}\n\tid, ok := userID.(string)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn id\n}",
"func (o ConnectionCloudResourceOutput) ServiceAccountId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ConnectionCloudResource) *string { return v.ServiceAccountId }).(pulumi.StringPtrOutput)\n}",
"func (n *Node) Owner() *userpb.UserId {\n\treturn n.SpaceRoot.owner\n}",
"func (o ConnectionCloudSqlPtrOutput) ServiceAccountId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ConnectionCloudSql) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ServiceAccountId\n\t}).(pulumi.StringPtrOutput)\n}",
"func (c *Config) AdminSid() string {\n\treturn c.RunDir + \"/sid.txt\"\n}",
"func (o DocumentDbOutputDataSourceOutput) AccountId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DocumentDbOutputDataSource) *string { return v.AccountId }).(pulumi.StringPtrOutput)\n}",
"func (o ConnectionCloudResourcePtrOutput) ServiceAccountId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ConnectionCloudResource) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ServiceAccountId\n\t}).(pulumi.StringPtrOutput)\n}",
"func (s *Service) subscriptionToken(username string) string {\n\treturn username[len(subscriptionUsernamePrefix):]\n}",
"func (m *DiscordMessage) UserID() string {\n\tif m.DiscordgoMessage.Author == nil {\n\t\treturn \"\"\n\t}\n\n\treturn m.DiscordgoMessage.Author.ID\n}"
] | [
"0.61183256",
"0.58557355",
"0.56401485",
"0.55619484",
"0.55538666",
"0.5534637",
"0.5451483",
"0.5416939",
"0.53665286",
"0.5300897",
"0.529901",
"0.52606803",
"0.5258515",
"0.5241705",
"0.52199906",
"0.52011776",
"0.5194686",
"0.5192432",
"0.51535434",
"0.5130193",
"0.51078814",
"0.51054263",
"0.51039463",
"0.5101265",
"0.5098686",
"0.50863177",
"0.50846195",
"0.5081913",
"0.5076033",
"0.5072724",
"0.5057763",
"0.5049862",
"0.5008284",
"0.5003767",
"0.5002411",
"0.49876562",
"0.49758857",
"0.49742618",
"0.49742618",
"0.4973312",
"0.49681252",
"0.49678373",
"0.4962904",
"0.49563956",
"0.49531442",
"0.49487004",
"0.4948479",
"0.49474296",
"0.49469802",
"0.49432397",
"0.4941311",
"0.49369857",
"0.49363077",
"0.4935346",
"0.49342188",
"0.49295464",
"0.49168512",
"0.49129432",
"0.4910741",
"0.4909823",
"0.49083194",
"0.4905144",
"0.49036056",
"0.48923108",
"0.48865086",
"0.48798728",
"0.48760974",
"0.48720855",
"0.4870281",
"0.48668143",
"0.48647386",
"0.48563287",
"0.48559633",
"0.48505655",
"0.48492628",
"0.4846867",
"0.48420855",
"0.48399487",
"0.48337084",
"0.4832398",
"0.4831135",
"0.48279047",
"0.48195148",
"0.48173934",
"0.4815701",
"0.48133156",
"0.4812274",
"0.48092425",
"0.4806803",
"0.48024574",
"0.48023212",
"0.48008686",
"0.47975165",
"0.4797226",
"0.4796138",
"0.47896373",
"0.47883692",
"0.47784802",
"0.47747082",
"0.47697747"
] | 0.5589212 | 3 |
The fullyformed AWS policy as JSON. | func (o TopicPolicyOutput) Policy() pulumi.StringOutput {
return o.ApplyT(func(v *TopicPolicy) pulumi.StringOutput { return v.Policy }).(pulumi.StringOutput)
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (s policyRules) JSON() string {\n\tpolicyJSONBytes, e := json.MarshalIndent(s, \"\", \" \")\n\tfatalIf(probe.NewError(e), \"Unable to marshal into JSON.\")\n\treturn string(policyJSONBytes)\n}",
"func (p *Policy) String() string {\n\tresult, _ := json.MarshalIndent(p, \"\", \" \")\n\treturn string(result)\n}",
"func (s policyMessage) JSON() string {\n\tpolicyJSONBytes, e := json.MarshalIndent(s, \"\", \" \")\n\tfatalIf(probe.NewError(e), \"Unable to marshal into JSON.\")\n\n\treturn string(policyJSONBytes)\n}",
"func (s BucketPolicy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s Policy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s Policy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s Policy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (p *Policy) Get() ([]byte, error) {\n\tresult, err := json.Marshal(p)\n\treturn result, err\n}",
"func (policy RedrivePolicy) GetAsAWSString() (policyString *string, err error) {\n\tjsonBytes, err := json.Marshal(policy)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err,\n\t\t}).Error(\"Marshal the RedrivePolicy\")\n\t\treturn\n\t}\n\n\tpolicyString = aws.String(string(jsonBytes))\n\treturn\n}",
"func (r *Bucket) Policy() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"policy\"])\n}",
"func (s policyLinksMessage) JSON() string {\n\tpolicyJSONBytes, e := json.MarshalIndent(s, \"\", \" \")\n\tfatalIf(probe.NewError(e), \"Unable to marshal into JSON.\")\n\n\treturn string(policyJSONBytes)\n}",
"func (p Policy) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", p.ID)\n\tpopulate(objectMap, \"location\", p.Location)\n\tpopulate(objectMap, \"name\", p.Name)\n\tpopulate(objectMap, \"properties\", p.Properties)\n\tpopulate(objectMap, \"tags\", p.Tags)\n\tpopulate(objectMap, \"type\", p.Type)\n\treturn json.Marshal(objectMap)\n}",
"func (o BucketOutput) Policy() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Bucket) pulumi.StringPtrOutput { return v.Policy }).(pulumi.StringPtrOutput)\n}",
"func (s ResourcePolicy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s ResourcePolicy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (policy Policy) MarshalJSON() ([]byte, error) {\n\tif err := policy.isValid(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// subtype to avoid recursive call to MarshalJSON()\n\ttype subPolicy Policy\n\treturn json.Marshal(subPolicy(policy))\n}",
"func (o UserPolicyOutput) Policy() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *UserPolicy) pulumi.StringOutput { return v.Policy }).(pulumi.StringOutput)\n}",
"func (o CloudConfigurationRuleOutput) Policy() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *CloudConfigurationRule) pulumi.StringOutput { return v.Policy }).(pulumi.StringOutput)\n}",
"func (p *Policy) Encode() (map[string]interface{}, error) {\n\tm := make(map[string]interface{})\n\tvar bindings []map[string]interface{}\n\tfor _, b := range p.Bindings {\n\t\tbb, err := b.Encode()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbindings = append(bindings, bb)\n\t}\n\tm[\"bindings\"] = bindings\n\tm[\"etag\"] = p.Etag\n\tm[\"version\"] = p.Version\n\treturn map[string]interface{}{\"policy\": m}, nil\n}",
"func (m *StsPolicy) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.PolicyBase.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAppliesTo() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAppliesTo())\n err = writer.WriteCollectionOfObjectValues(\"appliesTo\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetDefinition() != nil {\n err = writer.WriteCollectionOfStringValues(\"definition\", m.GetDefinition())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isOrganizationDefault\", m.GetIsOrganizationDefault())\n if err != nil {\n return err\n }\n }\n return nil\n}",
"func MarshalIAMPolicy(role awsv1alpha1.AWSFederatedRole) (string, error) {\n\tstatements := []awsStatement{}\n\n\tfor _, statement := range role.Spec.AWSCustomPolicy.Statements {\n\t\tstatements = append(statements, awsStatement(statement))\n\t}\n\n\t// Create a aws policydoc formated struct\n\tpolicyDoc := awsPolicy{\n\t\tVersion: \"2012-10-17\",\n\t\tStatement: statements,\n\t}\n\n\t// Marshal policydoc to json\n\tjsonPolicyDoc, err := json.Marshal(&policyDoc)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(jsonPolicyDoc), nil\n}",
"func (s defaultStore) SerializePolicies() (string, error) {\n\treturn s.policies.String()\n}",
"func (s PolicyDetails) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s EffectivePolicy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s EffectivePolicy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (p *policy) String() string {\n\treturn fmt.Sprintf(policyDocument,\n\t\tp.Expiration,\n\t\tp.Bucket,\n\t\tp.Key,\n\t\tp.O.MaxFileSize,\n\t\tp.Credential,\n\t\tp.Date,\n\t)\n}",
"func (s LifecyclePolicy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s RetentionPolicy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func NewPolicy(key string, c *Credentials, o *PolicyOptions) *policy {\n\tt := time.Now().Add(time.Minute * time.Duration(o.ExpiryMinutes))\n\tformattedShortTime := t.UTC().Format(shortTimeFormat)\n\tdate := t.UTC().Format(timeFormat)\n\tcred := fmt.Sprintf(\"%s/%s/%s/s3/aws4_request\", c.AccessKeyID, formattedShortTime, c.Region)\n\treturn &policy{\n\t\tExpiration: t.UTC().Format(expirationFormat),\n\t\tRegion: c.Region,\n\t\tBucket: c.Bucket,\n\t\tKey: key,\n\t\tCredential: cred,\n\t\tDate: date,\n\t\tC: c,\n\t\tO: o,\n\t}\n}",
"func BucketPolicy(bucketName string, roleName string) (json.RawMessage, error) {\n\tswitch roleName {\n\tcase \"admin\":\n\t\treturn []byte(fmt.Sprintf(`{\n\t\t\t\"Version\": \"2012-10-17\",\n\t\t\t\"Statement\": [{\n\t\t\t\t\"Effect\": \"Allow\",\n\t\t\t\t\"Action\": [\n\t\t\t\t\t\"s3:*\"\n\t\t\t\t],\n\t\t\t\t\"Resource\": [\n\t\t\t\t\t\"arn:aws:s3:::%s/*\"\n\t\t\t\t]\n\t\t\t}]\n\t\t}`, bucketName)), nil\n\tcase \"read-only\":\n\t\treturn []byte(fmt.Sprintf(`{\n\t\t\t\"Version\": \"2012-10-17\",\n\t\t\t\"Statement\": [{\n\t\t\t\t\"Effect\": \"Allow\",\n\t\t\t\t\"Action\": [\n\t\t\t\t\t\"s3:ListBucket\",\n\t\t\t\t\t\"s3:GetBucketLocation\",\n\t\t\t\t\t\"s3:GetObject\",\n\t\t\t\t\t\"s3:GetObjectVersion\"\n\t\t\t\t],\n\t\t\t\t\"Resource\": [\n\t\t\t\t\t\"arn:aws:s3:::%s/*\"\n\t\t\t\t]\n\t\t\t}]\n\t\t}`, bucketName)), nil\n\t}\n\n\treturn nil, fmt.Errorf(\"Invalid key role\")\n}",
"func (o ArgoCDSpecRbacOutput) Policy() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDSpecRbac) *string { return v.Policy }).(pulumi.StringPtrOutput)\n}",
"func (o ReplicaExternalKeyOutput) Policy() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ReplicaExternalKey) pulumi.StringOutput { return v.Policy }).(pulumi.StringOutput)\n}",
"func generatePolicyResponse(resp *http.Response, policy BucketAccessPolicy) (*http.Response, error) {\n\tpolicyBytes, err := json.Marshal(policy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp.StatusCode = http.StatusOK\n\tresp.Body = ioutil.NopCloser(bytes.NewBuffer(policyBytes))\n\treturn resp, nil\n}",
"func (opts UpdateOpts) ToPolicyUpdateMap() (map[string]interface{}, error) {\n\treturn gophercloud.BuildRequestBody(opts, \"policy\")\n}",
"func (p Policy) Value() (string, error) {\n\tif data, err := json.Marshal(p); err != nil {\n\t\treturn \"\", err\n\t} else {\n\t\treturn string(data), nil\n\t}\n}",
"func (s ServiceEndpointPolicy) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", s.Etag)\n\tpopulate(objectMap, \"id\", s.ID)\n\tpopulate(objectMap, \"kind\", s.Kind)\n\tpopulate(objectMap, \"location\", s.Location)\n\tpopulate(objectMap, \"name\", s.Name)\n\tpopulate(objectMap, \"properties\", s.Properties)\n\tpopulate(objectMap, \"tags\", s.Tags)\n\tpopulate(objectMap, \"type\", s.Type)\n\treturn json.Marshal(objectMap)\n}",
"func (o AclTokenPolicyAttachmentOutput) Policy() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AclTokenPolicyAttachment) pulumi.StringOutput { return v.Policy }).(pulumi.StringOutput)\n}",
"func (f *Factory) GetPolicyStatement() (string, error) {\n\t// Perform checks\n\tif len(f.accountID) == 0 {\n\t\treturn \"\", errors.New(AccountIDMissingErr)\n\t}\n\n\tif len(f.region) == 0 {\n\t\treturn \"\", errors.New(RegionMissingErr)\n\t}\n\n\tif len(f.partition) == 0 {\n\t\treturn \"\", errors.New(PartitionMissingErr)\n\t}\n\n\t// Replace AWS placeholders\n\tt := fmt.Sprintf(iamTemplate, strings.Join(f.policies, \",\"))\n\tt = strings.ReplaceAll(t, \"${AWS::Partition}\", f.partition)\n\tt = strings.ReplaceAll(t, \"${AWS::Region}\", f.region)\n\tt = strings.ReplaceAll(t, \"${AWS::AccountId}\", f.accountID)\n\n\t// Return the policy document\n\treturn t, nil\n}",
"func (s StreamingPolicy) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", s.ID)\n\tpopulate(objectMap, \"name\", s.Name)\n\tpopulate(objectMap, \"properties\", s.Properties)\n\tpopulate(objectMap, \"systemData\", s.SystemData)\n\tpopulate(objectMap, \"type\", s.Type)\n\treturn json.Marshal(objectMap)\n}",
"func (s ScalingPolicy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (i IntentPolicy) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", i.Etag)\n\tpopulate(objectMap, \"id\", i.ID)\n\tpopulate(objectMap, \"location\", i.Location)\n\tpopulate(objectMap, \"name\", i.Name)\n\tpopulate(objectMap, \"tags\", i.Tags)\n\tpopulate(objectMap, \"type\", i.Type)\n\treturn json.Marshal(objectMap)\n}",
"func (s VotingPolicy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s BlueGreenUpdatePolicy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s BatchPolicy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func generatePolicy(principalId, effect, resource string) events.APIGatewayCustomAuthorizerResponse {\n\tauthResponse := events.APIGatewayCustomAuthorizerResponse{PrincipalID: principalId}\n\n\tif effect != \"\" && resource != \"\" {\n\t\tauthResponse.PolicyDocument = events.APIGatewayCustomAuthorizerPolicy{\n\t\t\tVersion: \"2012-10-17\",\n\t\t\tStatement: []events.IAMPolicyStatement{\n\t\t\t\t{\n\t\t\t\t\tAction: []string{\"execute-api:Invoke\"},\n\t\t\t\t\tEffect: effect,\n\t\t\t\t\tResource: []string{resource},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\t// Optional output with custom properties of the String, Number or Boolean type.\n\tauthResponse.Context = map[string]interface{}{\n\t\t\"stringKey\": \"stringval\",\n\t\t\"numberKey\": 123,\n\t\t\"booleanKey\": true,\n\t}\n\treturn authResponse\n}",
"func (s policyMessage) String() string {\n\tif s.Operation == \"set\" {\n\t\treturn console.Colorize(\"Policy\",\n\t\t\t\"Access permission for `\"+s.Bucket+\"` is set to `\"+string(s.Perms)+\"`\")\n\t}\n\tif s.Operation == \"get\" {\n\t\treturn console.Colorize(\"Policy\",\n\t\t\t\"Access permission for `\"+s.Bucket+\"`\"+\" is `\"+string(s.Perms)+\"`\")\n\t}\n\tif s.Operation == \"set-json\" {\n\t\treturn console.Colorize(\"Policy\",\n\t\t\t\"Access permission for `\"+s.Bucket+\"`\"+\" is set from `\"+string(s.Perms)+\"`\")\n\t}\n\tif s.Operation == \"get-json\" {\n\t\tpolicy, e := json.MarshalIndent(s.Policy, \"\", \" \")\n\t\tfatalIf(probe.NewError(e), \"Unable to marshal into JSON.\")\n\t\treturn string(policy)\n\t}\n\t// nothing to print\n\treturn \"\"\n}",
"func (opts CreateOpts) ToPolicyCreateMap() (map[string]interface{}, error) {\n\treturn gophercloud.BuildRequestBody(opts, \"policy\")\n}",
"func (s VirtualGatewayClientPolicy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (i IPSecPolicy) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"dhGroup\", i.DhGroup)\n\tpopulate(objectMap, \"ipsecEncryption\", i.IPSecEncryption)\n\tpopulate(objectMap, \"ipsecIntegrity\", i.IPSecIntegrity)\n\tpopulate(objectMap, \"ikeEncryption\", i.IkeEncryption)\n\tpopulate(objectMap, \"ikeIntegrity\", i.IkeIntegrity)\n\tpopulate(objectMap, \"pfsGroup\", i.PfsGroup)\n\tpopulate(objectMap, \"saDataSizeKilobytes\", i.SaDataSizeKilobytes)\n\tpopulate(objectMap, \"saLifeTimeSeconds\", i.SaLifeTimeSeconds)\n\treturn json.Marshal(objectMap)\n}",
"func (m *Aws) ToJSON() (string, error) {\n\treturn codec.ToJSON(m)\n}",
"func (s BackupPolicy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s CreatePolicyOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s CreatePolicyOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s DescribePolicyOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (o SecretBackendRoleOutput) PolicyArns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *SecretBackendRole) pulumi.StringArrayOutput { return v.PolicyArns }).(pulumi.StringArrayOutput)\n}",
"func (s GetPolicyOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s GetPolicyOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s GetPolicyOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s RollingUpdatePolicy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (p *Policy) UnmarshalJSON(data []byte) error {\n\t*p = Policy{}\n\ttransports := policyTransportsMap{}\n\tif err := internal.ParanoidUnmarshalJSONObject(data, func(key string) any {\n\t\tswitch key {\n\t\tcase \"default\":\n\t\t\treturn &p.Default\n\t\tcase \"transports\":\n\t\t\treturn &transports\n\t\tdefault:\n\t\t\treturn nil\n\t\t}\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tif p.Default == nil {\n\t\treturn InvalidPolicyFormatError(\"Default policy is missing\")\n\t}\n\tp.Transports = map[string]PolicyTransportScopes(transports)\n\treturn nil\n}",
"func (s CreateResourcePolicyOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s HealthCheckPolicy) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (o *SnapmirrorCreateRequest) Policy() string {\n\tvar r string\n\tif o.PolicyPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.PolicyPtr\n\treturn r\n}",
"func (cp ComputePolicy) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif cp.ComputePolicyProperties != nil {\n\t\tobjectMap[\"properties\"] = cp.ComputePolicyProperties\n\t}\n\tif cp.ID != nil {\n\t\tobjectMap[\"id\"] = cp.ID\n\t}\n\tif cp.Name != nil {\n\t\tobjectMap[\"name\"] = cp.Name\n\t}\n\tif cp.Type != nil {\n\t\tobjectMap[\"type\"] = cp.Type\n\t}\n\treturn json.Marshal(objectMap)\n}",
"func (km KeyValueMap) Policy() string {\n\treturn km[kmPolicy]\n}",
"func (o FhirStoreIamPolicyOutput) PolicyData() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FhirStoreIamPolicy) pulumi.StringOutput { return v.PolicyData }).(pulumi.StringOutput)\n}",
"func (s GetResourcePolicyOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s GetResourcePolicyOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (o ApplicationStatusOutput) Policy() ApplicationStatusPolicyArrayOutput {\n\treturn o.ApplyT(func(v ApplicationStatus) []ApplicationStatusPolicy { return v.Policy }).(ApplicationStatusPolicyArrayOutput)\n}",
"func getPolicy(policyPath string) (policyContent, error) {\n\tvar policyContentStruct policyContent\n\tpolicyContent, err := os.ReadFile(policyPath)\n\tif err != nil {\n\t\treturn policyContentStruct, fmt.Errorf(\"unable to read policy file: %w\", err)\n\t}\n\tif err := json.Unmarshal(policyContent, &policyContentStruct); err != nil {\n\t\treturn policyContentStruct, fmt.Errorf(\"could not parse trust policies from %s: %w\", policyPath, err)\n\t}\n\treturn policyContentStruct, nil\n}",
"func (o *VolumeExportAttributesType) Policy() string {\n\tvar r string\n\tif o.PolicyPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.PolicyPtr\n\treturn r\n}",
"func (c *Client) Policy() (*www.PolicyReply, error) {\n\tresponseBody, err := c.makeRequest(http.MethodGet,\n\t\twww.PoliteiaWWWAPIRoute, www.RoutePolicy, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pr www.PolicyReply\n\terr = json.Unmarshal(responseBody, &pr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshal PolicyReply: %v\", err)\n\t}\n\n\tif c.cfg.Verbose {\n\t\terr := prettyPrintJSON(pr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &pr, nil\n}",
"func (s DescribeResourcePolicyOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s DescribeResourcePolicyOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s GetPolicyInput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s GetPolicyInput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s GetPolicyInput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func CreatePolicy(nbmaster string, httpClient *http.Client, jwt string) {\r\n fmt.Printf(\"\\nSending a POST request to create %s with defaults...\\n\", testPolicyName)\r\n\r\n policy := map[string]interface{}{\r\n \"data\": map[string]interface{}{\r\n \"type\": \"policy\",\r\n \"id\": testPolicyName,\r\n \"attributes\": map[string]interface{}{\r\n \"policy\": map[string]interface{}{\r\n \"policyName\": testPolicyName,\r\n \"policyType\": \"VMware\",\r\n \"policyAttributes\": map[string]interface{}{\r\n \"active\": true,\r\n \"applicationConsistent\": true,\r\n \"applicationDiscovery\": true,\r\n \"applicationProtection\": []string{},\r\n \"autoManagedLabel\": nil,\r\n \"autoManagedType\": 0,\r\n \"backupHost\": \"MEDIA_SERVER\",\r\n \"blockIncremental\": true,\r\n \"dataClassification\": nil,\r\n \"disableClientSideDeduplication\": false,\r\n \"discoveryLifetime\": 28800,\r\n \"effectiveDateUTC\": \"2018-06-19T18:47:25Z\",\r\n \"jobLimit\": 2147483647,\r\n \"keyword\": testPolicyName,\r\n \"mediaOwner\": \"*ANY*\",\r\n \"priority\": 0,\r\n \"secondarySnapshotMethodArgs\": nil,\r\n \"snapshotMethodArgs\": \"skipnodisk=0,post_events=1,multi_org=0,Virtual_machine_backup=2,continue_discovery=0,nameuse=0,exclude_swap=1,tags_unset=0,ignore_irvm=1,rLim=10,snapact=3,enable_quiesce_failover=0,file_system_optimization=1,drive_selection=0,disable_quiesce=0,enable_vCloud=0,trantype=san:hotadd:nbd:nbdssl,rHz=10,rTO=0\",\r\n \"storage\": nil,\r\n \"storageIsSLP\": false,\r\n \"useAccelerator\": false,\r\n \"useReplicationDirector\": false,\r\n \"volumePool\": \"NetBackup\"},\r\n \"clients\":[]map[string]string{{\r\n \"hardware\": \"VMware\",\r\n \"hostName\": testClientName,\r\n \"OS\": \"VMware\"}},\r\n \"schedules\":[]map[string]interface{}{{\r\n \"acceleratorForcedRescan\": false,\r\n \"backupCopies\": map[string]interface{}{\r\n \"priority\": 9999,\r\n \"copies\": []map[string]interface{}{{\r\n \"mediaOwner\": \"owner1\",\r\n \"storage\": nil,\r\n \"retentionPeriod\": map[string]interface{}{\r\n \"value\": 9,\r\n \"unit\": \"WEEKS\"},\r\n \"volumePool\": \"NetBackup\",\r\n \"failStrategy\": \"Continue\"}}},\r\n \"backupType\": \"Full Backup\",\r\n \"excludeDates\": map[string]interface{}{\r\n \"lastDayOfMonth\": true,\r\n \"recurringDaysOfWeek\": []string{\"4:6\", \"2:5\"},\r\n \"recurringDaysOfMonth\": []int{10},\r\n \"specificDates\": []string{\"2018-1-1\", \"2018-2-30\"}},\r\n \"frequencySeconds\": 4800,\r\n \"includeDates\": map[string]interface{}{\r\n \"lastDayOfMonth\": true,\r\n \"recurringDaysOfWeek\": []string{\"2:3\", \"3:4\"},\r\n \"recurringDaysOfMonth\": []int{10,13},\r\n \"specificDates\": []string{\"2018-12-31\"}},\r\n \"mediaMultiplexing\": 2,\r\n \"retriesAllowedAfterRunDay\": true,\r\n \"scheduleName\": testScheduleName,\r\n \"scheduleType\": \"Calendar\",\r\n \"snapshotOnly\": false,\r\n \"startWindow\": []map[string]interface{}{{\r\n \"dayOfWeek\": 1,\r\n \"startSeconds\": 14600,\r\n \"durationSeconds\": 24600},\r\n {\"dayOfWeek\": 2,\r\n \"startSeconds\": 14600,\r\n \"durationSeconds\": 24600},\r\n {\"dayOfWeek\": 3,\r\n \"startSeconds\": 14600,\r\n \"durationSeconds\": 24600},\r\n {\"dayOfWeek\": 4,\r\n \"startSeconds\": 14600,\r\n \"durationSeconds\": 24600},\r\n {\"dayOfWeek\": 5,\r\n \"startSeconds\": 14600,\r\n \"durationSeconds\": 24600},\r\n {\"dayOfWeek\": 6,\r\n \"startSeconds\": 14600,\r\n \"durationSeconds\": 24600},\r\n {\"dayOfWeek\": 7,\r\n \"startSeconds\": 14600,\r\n \"durationSeconds\": 24600}},\r\n \"syntheticBackup\": false,\r\n \"storageIsSLP\": false}},\r\n \"backupSelections\": map[string]interface{}{\r\n \"selections\": []string{\"vmware:/?filter=Displayname Contains 'rsv' OR Displayname Contains 'mtv'\"}}}}}}\r\n\r\n policyRequest, _ := json.Marshal(policy)\r\n\r\n uri := \"https://\" + nbmaster + \":\" + port + \"/netbackup/\" + policiesUri\r\n\r\n request, _ := http.NewRequest(http.MethodPost, uri, bytes.NewBuffer(policyRequest))\r\n request.Header.Add(\"Content-Type\", contentTypeV2);\r\n request.Header.Add(\"Authorization\", jwt);\r\n request.Header.Add(\"X-NetBackup-Audit-Reason\", \"created policy \" + testPolicyName);\r\n\r\n response, err := httpClient.Do(request)\r\n\r\n if err != nil {\r\n fmt.Printf(\"The HTTP request failed with error: %s\\n\", err)\r\n panic(\"Unable to create policy.\\n\")\r\n } else {\r\n if response.StatusCode != 204 {\r\n printErrorResponse(response)\r\n } else {\r\n fmt.Printf(\"%s created successfully.\\n\", testPolicyName);\r\n responseDetails, _ := httputil.DumpResponse(response, true);\r\n fmt.Printf(string(responseDetails))\r\n }\r\n }\r\n}",
"func (s GetResourcePoliciesOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (e *Enforcer) GetPolicy() [][]string {\n\treturn e.GetNamedPolicy(\"p\")\n}",
"func ReadPolicy(src io.Reader) (*policyv1.Policy, error) {\n\tpolicy := &policyv1.Policy{}\n\tif err := util.ReadJSONOrYAML(src, policy); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn policy, nil\n}",
"func (m *ServicePolicyHitsRequest) ToJSON() (string, error) {\n\treturn codec.ToJSON(m)\n}",
"func (s GetResourcePoliciesInput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (Recommendations) Policy() ent.Policy {\n\t/*return authz.NewPolicy(\n\t\tauthz.WithMutationRules(\n\t\t\tauthz.AssuranceTemplatesWritePolicyRule(),\n\t\t),\n\t)*/\n\treturn authz.NewPolicy(\n\t\tauthz.WithMutationRules(\n\t\t\tprivacy.AlwaysAllowRule(),\n\t\t),\n\t)\n}",
"func (s GetResourcePolicyInput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s GetResourcePolicyInput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (m *ServicePolicyHits) ToJSON() (string, error) {\n\treturn codec.ToJSON(m)\n}",
"func (s PutResourcePolicyOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s PutResourcePolicyOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (o ArgoCDSpecRbacPtrOutput) Policy() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDSpecRbac) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Policy\n\t}).(pulumi.StringPtrOutput)\n}",
"func (s ServiceEndpointPolicyDefinition) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", s.Etag)\n\tpopulate(objectMap, \"id\", s.ID)\n\tpopulate(objectMap, \"name\", s.Name)\n\tpopulate(objectMap, \"properties\", s.Properties)\n\tpopulate(objectMap, \"type\", s.Type)\n\treturn json.Marshal(objectMap)\n}",
"func (d DdosCustomPolicy) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", d.Etag)\n\tpopulate(objectMap, \"id\", d.ID)\n\tpopulate(objectMap, \"location\", d.Location)\n\tpopulate(objectMap, \"name\", d.Name)\n\tpopulate(objectMap, \"properties\", d.Properties)\n\tpopulate(objectMap, \"tags\", d.Tags)\n\tpopulate(objectMap, \"type\", d.Type)\n\treturn json.Marshal(objectMap)\n}",
"func NewStsPolicy()(*StsPolicy) {\n m := &StsPolicy{\n PolicyBase: *NewPolicyBase(),\n }\n odataTypeValue := \"#microsoft.graph.stsPolicy\";\n m.SetOdataType(&odataTypeValue);\n return m\n}",
"func (o JobIamPolicyOutput) PolicyData() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *JobIamPolicy) pulumi.StringOutput { return v.PolicyData }).(pulumi.StringOutput)\n}",
"func newPolicy() *Policy {\n\tp := &Policy{ContractMD: *interop.NewContractMD(policyName)}\n\n\tp.ContractID = policyContractID\n\tp.Manifest.Features |= smartcontract.HasStorage\n\n\tdesc := newDescriptor(\"getMaxTransactionsPerBlock\", smartcontract.IntegerType)\n\tmd := newMethodAndPrice(p.getMaxTransactionsPerBlock, 1000000, smartcontract.AllowStates)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"getMaxBlockSize\", smartcontract.IntegerType)\n\tmd = newMethodAndPrice(p.getMaxBlockSize, 1000000, smartcontract.AllowStates)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"getFeePerByte\", smartcontract.IntegerType)\n\tmd = newMethodAndPrice(p.getFeePerByte, 1000000, smartcontract.AllowStates)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"getBlockedAccounts\", smartcontract.ArrayType)\n\tmd = newMethodAndPrice(p.getBlockedAccounts, 1000000, smartcontract.AllowStates)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"getMaxBlockSystemFee\", smartcontract.IntegerType)\n\tmd = newMethodAndPrice(p.getMaxBlockSystemFee, 1000000, smartcontract.AllowStates)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"setMaxBlockSize\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"value\", smartcontract.IntegerType))\n\tmd = newMethodAndPrice(p.setMaxBlockSize, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"setMaxTransactionsPerBlock\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"value\", smartcontract.IntegerType))\n\tmd = newMethodAndPrice(p.setMaxTransactionsPerBlock, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"setFeePerByte\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"value\", smartcontract.IntegerType))\n\tmd = newMethodAndPrice(p.setFeePerByte, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"setMaxBlockSystemFee\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"value\", smartcontract.IntegerType))\n\tmd = newMethodAndPrice(p.setMaxBlockSystemFee, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"blockAccount\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"account\", smartcontract.Hash160Type))\n\tmd = newMethodAndPrice(p.blockAccount, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"unblockAccount\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"account\", smartcontract.Hash160Type))\n\tmd = newMethodAndPrice(p.unblockAccount, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"name\", smartcontract.StringType)\n\tmd = newMethodAndPrice(nameMethod(policyName), 0, smartcontract.NoneFlag)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"onPersist\", smartcontract.VoidType)\n\tmd = newMethodAndPrice(getOnPersistWrapper(p.OnPersist), 0, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"postPersist\", smartcontract.VoidType)\n\tmd = newMethodAndPrice(getOnPersistWrapper(postPersistBase), 0, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\treturn p\n}",
"func (b Bucket) JSON() string {\n\treturn strutil.JSON(b)\n}",
"func (s CreatePolicyInput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s CreatePolicyInput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (e *CachedEnforcer) GetPolicy() [][]string {\n\treturn e.api.GetPolicy()\n}",
"func (m policyMap) Value() (driver.Value, error) {\n\treturn json.Marshal(m)\n}"
] | [
"0.6656958",
"0.66203696",
"0.6376475",
"0.6134301",
"0.6078109",
"0.6078109",
"0.6078109",
"0.60112184",
"0.5989728",
"0.5977709",
"0.5887819",
"0.58731294",
"0.5855159",
"0.58102757",
"0.5806688",
"0.57956064",
"0.579379",
"0.5787152",
"0.5777116",
"0.5723759",
"0.57001734",
"0.5647394",
"0.5623134",
"0.5590748",
"0.5590748",
"0.55300766",
"0.5501378",
"0.5493267",
"0.5482832",
"0.5482053",
"0.5480643",
"0.5464276",
"0.54624104",
"0.54436296",
"0.543919",
"0.54346234",
"0.54321617",
"0.5429288",
"0.54157364",
"0.5409912",
"0.54086065",
"0.54052323",
"0.53837514",
"0.53647",
"0.5347161",
"0.5336481",
"0.53236413",
"0.5319827",
"0.53004086",
"0.52922714",
"0.52481496",
"0.5247856",
"0.5247856",
"0.5244794",
"0.52406734",
"0.52389634",
"0.52389634",
"0.52389634",
"0.5238253",
"0.52377826",
"0.5228582",
"0.5222321",
"0.5214692",
"0.5207538",
"0.5205363",
"0.5201523",
"0.5196722",
"0.5196722",
"0.51907045",
"0.5176305",
"0.51749486",
"0.5165066",
"0.516132",
"0.516132",
"0.51509434",
"0.51509434",
"0.51509434",
"0.51467746",
"0.514317",
"0.51425284",
"0.5130241",
"0.5115566",
"0.5105763",
"0.5104909",
"0.5103808",
"0.5103808",
"0.5101408",
"0.5090897",
"0.5089773",
"0.50873715",
"0.5087102",
"0.508337",
"0.50824094",
"0.5081391",
"0.5075918",
"0.5065069",
"0.50647354",
"0.50647354",
"0.5059129",
"0.50555575"
] | 0.5516189 | 26 |
New creates a gin engine to serve HTTP requests. | func New() *gin.Engine {
gin.SetMode(gin.ReleaseMode)
router := gin.New()
router.Use(gin.Logger())
router.Use(gin.Recovery())
router.Use(
cors.New(cors.Config{
AllowAllOrigins: true,
AllowMethods: []string{http.MethodPost, http.MethodPut, http.MethodGet},
}),
)
return router
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func New(port string) *Engine {\n\tg := gin.New()\n\tg.Use(gin.Recovery())\n\tg.GET(\"/ping\", func(c *gin.Context) {\n\t\tc.String(200, \"pong\")\n\t})\n\treturn &Engine{g, port}\n}",
"func New() *gin.Engine {\n\n\tconfigureRouter()\n\n\treturn mapUrls(Router)\n}",
"func New() *gin.Engine {\n\n\tgin.SetMode(gin.ReleaseMode)\n\trouter := gin.Default()\n\n\tbootstrap(router)\n\n\treturn router\n}",
"func New() *gin.Engine {\n\trouter := gin.New()\n\n\trouter.Use(\n\t\tgin.LoggerWithWriter(DefaultWriter),\n\t\tginzap.Ginzap(zap.L(), time.RFC3339Nano, false),\n\t\tginzap.RecoveryWithZap(zap.L(), true),\n\t)\n\n\treturn router\n}",
"func New() *Engine {\n\treturn &Engine{router: newRouter()}\n}",
"func New(name string) *Engine {\n\tengine := &Engine{Name: name}\n\tengine.RouterGroup = &RouterGroup{prefix: \"/\", engine: engine}\n\tengine.router = httprouter.New()\n\tengine.router.NotFound = engine.handle404\n\tengine.cache.New = func() interface{} {\n\t\tc := &Context{Engine: engine}\n\t\tc.Writer = &c.writermem\n\t\treturn c\n\t}\n\treturn engine\n}",
"func New() *Server {\n\tr := gin.Default()\n\treturn &Server{Engine: r}\n}",
"func New() Engine {\n\treturn new(engine)\n}",
"func New(cfgPath string, devel bool) (*gin.Engine, error) {\n\treturn DefaultFactory.New(cfgPath, devel)\n}",
"func New(c config.Template) *Engine {\n\ts := &Engine{Config: &c, templateCache: make(map[string]*raymond.Template, 0)}\n\treturn s\n}",
"func NewEngine(config *rest.Config) *Engine {\n\treturn &Engine{\n\t\ttemplate: template.New(\"gotpl\"),\n\t\tconfig: config,\n\t}\n}",
"func New() (*Engine, error) {\n\tdownloader, err := cache.NewDownloader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcmdExec := exec.NewExec()\n\tloopbackRouting, err := sysctl.NewIpv4RouteLocalNet(cmdExec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tipv6RouterAdvertisements, err := sysctl.NewIpv6RouterAdvertisements(cmdExec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcredentialsProxyRoute, err := iptables.NewNetfilterRoute(cmdExec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Engine{\n\t\tdownloader: downloader,\n\t\tloopbackRouting: loopbackRouting,\n\t\tcredentialsProxyRoute: credentialsProxyRoute,\n\t\tipv6RouterAdvertisements: ipv6RouterAdvertisements,\n\t\tnvidiaGPUManager: gpu.NewNvidiaGPUManager(),\n\t}, nil\n}",
"func New(c *config.Config, cc *Clients, l hclog.Logger) *Engine {\n\tp := generateProviders(c, cc, l)\n\n\treturn &Engine{\n\t\tproviders: p,\n\t\tclients: cc,\n\t\tconfig: c,\n\t\tlog: l,\n\t}\n}",
"func New(storage Storager) *gin.Engine {\n\te := gin.New()\n\n\tpublicAPI := e.Group(\"\")\n\tpublicAPI.POST(\"/message\", postNewMessageHandler(storage))\n\n\tprivateAPI := e.Group(\"\", gin.BasicAuth(gin.Accounts(users)))\n\tmessages := privateAPI.Group(\"/message\")\n\t{\n\t\tmessages.GET(\"\", getListMessagesHandler(storage))\n\t\tmessageID := messages.Group(\"/:id\")\n\t\t{\n\t\t\tmessageID.GET(\"\", getMessageHandler(storage))\n\t\t\tmessageID.POST(\"\", updateMessageHandler(storage))\n\t\t}\n\t}\n\n\treturn e\n}",
"func New(config Configuration, storage storage.Storage, groups map[string]groups.Group) *HTTPServer {\n\treturn &HTTPServer{\n\t\tConfig: config,\n\t\tStorage: storage,\n\t\tGroups: groups,\n\t}\n}",
"func New(s *service.Service) (engine *bm.Engine, err error) {\n\tvar (\n\t\tcfg struct {\n\t\t\tbm.ServerConfig\n\t\t\tCrossDomains []string\n\t\t}\n\t\tct paladin.TOML\n\t)\n\tif err = paladin.Get(\"http.toml\").Unmarshal(&ct); err != nil {\n\t\treturn\n\t}\n\tif err = ct.Get(\"Server\").UnmarshalTOML(&cfg); err != nil {\n\t\treturn\n\t}\n\tengine = bm.DefaultServer(&cfg.ServerConfig)\n\tengine.Use(s.As.CORS(cfg.CrossDomains))\n\tengine.Use(gzip.Gzip(gzip.DefaultCompression))\n\tinitRouter(engine, s)\n\terr = engine.Start()\n\treturn\n}",
"func New(cfg *config.Config, cache cache.Cacher, tr *http.Transport) *HttpHandler {\n\treturn &HttpHandler{handler.Handler{cache, cfg, tr}}\n}",
"func New(s *service.Canal) (engine *bm.Engine, err error) {\n\tcs = s\n\tengine = bm.DefaultServer(conf.Conf.BM)\n\n\tinitRouter(engine)\n\terr = engine.Start()\n\treturn\n}",
"func New(target Target) *gin.Engine {\n\tvar man *autocert.Manager\n\tvar server *http.Server\n\tr := gin.New()\n\n\t// zap.Logger integration with gin\n\tr.Use(ginzap.Ginzap(target.Logger, time.RFC3339, true))\n\tr.Use(ginzap.RecoveryWithZap(target.Logger, true))\n\n\tif target.Environment != \"local\" {\n\t\thost := \"\"\n\t\tman = &autocert.Manager{\n\t\t\tPrompt: autocert.AcceptTOS,\n\t\t\tCache: autocert.DirCache(\"certs\"),\n\t\t}\n\n\t\tserver = &http.Server{\n\t\t\tAddr: host + \":443\",\n\t\t\tHandler: r,\n\t\t\tTLSConfig: &tls.Config{\n\t\t\t\tGetCertificate: man.GetCertificate,\n\t\t\t},\n\t\t}\n\t} else {\n\t\thost := \"localhost\"\n\t\tserver = &http.Server{\n\t\t\tAddr: host + \":\" + target.Port,\n\t\t\tHandler: r,\n\t\t}\n\t}\n\n\ttarget.Lc.Append(fx.Hook{\n\t\tOnStart: func(context.Context) error {\n\t\t\tif target.Environment != \"local\" {\n\t\t\t\ttarget.Logger.Info(\"Starting HTTPS server at \" + server.Addr)\n\t\t\t\tgo server.ListenAndServeTLS(\"\", \"\")\n\t\t\t\tgo http.ListenAndServe(\":80\", man.HTTPHandler(nil))\n\t\t\t} else {\n\t\t\t\ttarget.Logger.Info(\"Starting HTTP server at \" + server.Addr)\n\t\t\t\tgo server.ListenAndServe()\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\tOnStop: func(ctx context.Context) error {\n\t\t\ttarget.Logger.Info(\"Stopping HTTPS server.\")\n\t\t\treturn server.Shutdown(ctx)\n\t\t},\n\t})\n\n\treturn r\n}",
"func New(api restapi.Connector) *Engine {\n\treturn &Engine{api: api}\n}",
"func New() {\n\te := echo.New()\n\n\te.Use(middleware.Logger())\n\te.Use(middleware.Recover())\n\n\te.GET(\"/auth/google/sign_in\", handler.GoogleSignIn)\n\te.GET(\"/auth/google/callback\", handler.GoogleCallbackAfterSuccess)\n\n\te.Logger.Fatal(e.Start(\":3000\"))\n}",
"func New() *Engine {\n\tengine := &Engine{router: newRouter()}\n\tengine.RouterGroup = &RouterGroup{engine: engine}\n\tengine.groups = []*RouterGroup{engine.RouterGroup}\n\treturn engine\n}",
"func New() *HTTPTransport {\n\treturn &HTTPTransport{\n\t\tmux: http.NewServeMux(),\n\t\treqs: make(chan transport.Request),\n\t}\n}",
"func New() *Engine {\n\tengine := &Engine{}\n\n\tLog = NewLogger(os.Stdout)\n\n\tengine.pool = NewContextPool()\n\tengine.Router = NewRouter()\n\n\tengine.sharedData = make(map[string]string)\n\n\t// Try to determine engine path\n\twd, _ := osext.ExecutableFolder()\n\tengine.Path = filepath.Clean(wd) + \"/\"\n\n\tif strings.Contains(filepath.Dir(engine.Path), \"go-build\") {\n\t\twd, _ = os.Getwd()\n\t\tengine.Path = filepath.Clean(wd) + \"/\"\n\t}\n\n\tif filepath.Base(engine.Path) == \"tests\" {\n\t\tengine.Path = engine.Path + \"../\"\n\t}\n\n\tif flag.Lookup(\"test.v\") != nil {\n\t\tSetMode(\"test\")\n\t\tengine.Path = engine.Path + \"../example\"\n\t}\n\n\t// Load configuration file.\n\tConfig = LoadConfig(engine.Path + \"config/app.json\")\n\n\treturn engine\n}",
"func New(db db.Store, r *gin.Engine) {\n\tinitEndpointUser(db, r)\n\tinitEndpointVideoGame(db, r)\n}",
"func New() *Engine {\n\tv := &Engine{Layer: layer.New()}\n\t// Use the default proxyer as final middleware handler\n\tv.UseFinalHandler(DefaultFinalHandler)\n\treturn v\n}",
"func New(h *handler.Handler, c *config.Config) {\n\ttokenAuth = jwtauth.New(\"HS256\", []byte(c.Token), nil)\n\tr := chi.NewRouter()\n\ts := &server{\n\t\thand: h,\n\t\trouter: r,\n\t\taddress: c.Address,\n\t}\n\ts.makeHandlers()\n\ts.startServer()\n}",
"func NewEngine() error {\n\t\n\treturn nil\n}",
"func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {\n\n\tif len(config.Name) == 0 {\n\t\treturn nil, fmt.Errorf(\"name cannot be null\")\n\t}\n\n\trequest, err := buildRequest(config.ServiceUrl, config.Name, config.Timeout, \"\", \"\")\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while building request\")\n\t}\n\n\treturn &Manager{\n\t\tnext: next,\n\t\tname: config.Name,\n\t\trequest: request,\n\t\tserviceUrl: config.ServiceUrl,\n\t\ttimeout: config.Timeout,\n\t}, nil\n}",
"func New(w http.ResponseWriter, r *http.Request) {\n\tgetTemplates().ExecuteTemplate(w, \"New\", nil)\n}",
"func New(s *service.Service) (engine *bm.Engine) {\n\tvar (\n\t\thc struct {\n\t\t\tServer *bm.ServerConfig\n\t\t}\n\t)\n\tif err := paladin.Get(\"http.toml\").UnmarshalTOML(&hc); err != nil {\n\t\tif err != paladin.ErrNotExist {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tsvc = s\n\tengine = bm.DefaultServer(hc.Server)\n\tinitRouter(engine)\n\tif err := engine.Start(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}",
"func New(store stores.Store) (*Handler, error) {\n\tif !util.GetConfig().EnableDebugMode {\n\t\tgin.SetMode(gin.ReleaseMode)\n\t}\n\th := &Handler{\n\t\tstore: store,\n\t\tengine: gin.New(),\n\t}\n\tif err := h.setHandlers(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not set handlers\")\n\t}\n\tif util.GetConfig().AuthBackend == \"oauth\" {\n\t\tif !DoNotPrivateKeyChecking {\n\t\t\tif err := util.CheckForPrivateKey(); err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"could not check for private key\")\n\t\t\t}\n\t\t}\n\t\th.initOAuth()\n\t} else if util.GetConfig().AuthBackend == \"proxy\" {\n\t\th.initProxyAuth()\n\t}\n\treturn h, nil\n}",
"func New(config config.Config) Workloads {\n\treturn Workloads{\n\t\tclient: http.NewClient(config),\n\t\tlogger: config.GetLogger(),\n\t}\n}",
"func New(w http.ResponseWriter, r *http.Request) {\r\n\ttmpl.ExecuteTemplate(w, \"New\", nil)\r\n}",
"func New(w http.ResponseWriter, r *http.Request) {\r\n\ttmpl.ExecuteTemplate(w, \"New\", nil)\r\n}",
"func New(context *contexter.Context, contexter *contexter.Contexter) (*Server) {\n\ts := &Server{\n\t\tcontext: context,\n\t\tcontexter: contexter,\n }\n\tif !context.GetAPIServer().Debug {\n\t\tgin.SetMode(gin.ReleaseMode)\n\t}\n\treturn s\n}",
"func New() DefaultEngine {\n\treturn DefaultEngine{}\n}",
"func New(consumer Consumer, handler Handler, publisher Publisher) *Engine {\n\treturn &Engine{\n\t\tconsumer: consumer,\n\t\thandler: handler,\n\t\tpublisher: publisher,\n\t}\n}",
"func New(service storage.Service) http.Handler {\n\tr := mux.NewRouter()\n\n\th := handler{service}\n\n\tr.HandleFunc(\"/health\", health)\n\tr.HandleFunc(\"/insfile\", responseJSONWithModules(h.insfileWithModules)).Methods(http.MethodPost)\n\tr.HandleFunc(\"/insfile/text\", responseTextWithModules(h.insfileWithModules)).Methods(http.MethodPost)\n\tr.HandleFunc(\"/insfile/traverse\", responseJSON(h.insfile)).Methods(http.MethodPost)\n\tr.HandleFunc(\"/insfile/traverse/text\", responseText(h.insfile)).Methods(http.MethodPost)\n\n\treturn r\n}",
"func New(info Info) *WebServer {\n\trouter := bone.New()\n\t// Add more to this later on\n\treturn &WebServer{info.Listen + \":\" + info.Port, router}\n}",
"func New(config *Config, next http.RoundTripper) http.RoundTripper {\n\t// Need to delay fetching auth settings until env vars have had a chance to propagate\n\tif authSettings == nil {\n\t\tauthSettings = awsds.ReadAuthSettingsFromEnvironmentVariables()\n\t}\n\n\treturn RoundTripperFunc(func(r *http.Request) (*http.Response, error) {\n\t\tif next == nil {\n\t\t\tnext = http.DefaultTransport\n\t\t}\n\t\treturn (&middleware{\n\t\t\tconfig: config,\n\t\t\tnext: next,\n\t\t}).exec(r)\n\t})\n}",
"func New(out string, truncate bool) *Engine {\n\tif (len(_extractors) < 1) || (len(_loaders) < 1) {\n\t\t// we need at least 1 extractor and 1 loader for work\n\t\treturn nil\n\t}\n\te := &Engine{\n\t\textractors: _extractors,\n\t\tloaders: _loaders,\n\t\toutputFolder: out,\n\t}\n\tif truncate {\n\t\te.Clean()\n\t}\n\treturn e\n}",
"func New(middleware ...Handler) *Server {\n\tdebugPrintWARNINGNew()\n\tserv := &Server{\n\t\trouter: make(tree.Trees, 0, 9),\n\t\tnotFound: []Handler{default404Handler},\n\t\tnoMethod: []Handler{default405Handler},\n\t\tmiddleware: middleware,\n\t\tRedirectTrailingSlash: true,\n\t\tRedirectFixedPath: false,\n\t\tMaxMultipartMemory: defaultMultipartMemory,\n\t}\n\n\tserv.pool.New = func() interface{} {\n\t\treturn serv.allocateContext()\n\t}\n\treturn serv\n}",
"func New(fs ...MiddlewareFunc) Router {\n\tglobalMiddleware := transformMiddlewareFunc(fs...)\n\n\tr := &router{\n\t\ttree: mux.NewTree(),\n\t\tglobalMiddleware: globalMiddleware,\n\t}\n\n\tr.handler = globalMiddleware.Compose(http.HandlerFunc(r.serveHTTP)).(http.Handler)\n\n\treturn r\n}",
"func New(token string, words []string) (*Engine, error) {\n\tbot, err := tgbotapi.NewBotAPI(token)\n\tif err != nil {\n\t\treturn &Engine{}, err\n\t}\n\n\treturn &Engine{\n\t\tBot: bot,\n\t\tRoomList: make(map[int64]*room.Room),\n\t\tSendChan: make(chan message.Request),\n\n\t\tWords: words,\n\t}, nil\n}",
"func New(url string) (*Handler, error) {\n\tc, err := golf.NewClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = c.Dial(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tl, err := c.NewLogger()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Handler{\n\t\tlogger: l,\n\t\tclient: c,\n\t}, nil\n}",
"func New(url string) (*Handler, error) {\n\tc, err := golf.NewClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = c.Dial(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tl, err := c.NewLogger()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Handler{\n\t\tlogger: l,\n\t\tclient: c,\n\t}, nil\n}",
"func New() (interface{}, error) {\n\treturn Backend(), nil\n}",
"func New(\n\troute *gin.Engine,\n\tcommandBus *command.Bus,\n\tqueryBus *query.Bus,\n\tutil *util.Util,\n\tconfig config.Interface,\n\tapi api.Interface,\n) *Controller {\n\tcontroller := &Controller{\n\t\troute: route,\n\t\tcommandBus: commandBus,\n\t\tqueryBus: queryBus,\n\t\tutil: util,\n\t\tconfig: config,\n\t\tapi: api,\n\t}\n\tcontroller.SetupRoutes()\n\treturn controller\n}",
"func New() (backends.Backend, error) {\n\treturn &inMemoryBackend{\n\t\tdata: make(map[string]string),\n\t}, nil\n}",
"func New() *web.Mux {\n\tmux := web.New()\n\tmux.Get(\"/api/hello\", handler.HelloWorld)\n\tmux.Get(\"/api/hello/:name\", handler.HelloName)\n\treturn mux\n}",
"func New(config *config.ServerConfig, html *render.HTML) http.Handler {\n\treturn &indexController{config, html}\n}",
"func New(this *Handler) *Handler {\n\ta := &API{Cfg: this.Cfg, Interactor: this.Interactor}\n\troutes(a).Register()\n\treturn this\n}",
"func New(ctx context.Context, connection string, tlsInfo tls.Config) (server.Backend, error) {\n\treturn newBackend(ctx, connection, tlsInfo, false)\n}",
"func New(middlewares ...Middleware) Middleware {\n\treturn Middleware(func(handler http.Handler) http.Handler {\n\t\treturn handler\n\t}).Use(middlewares...)\n}",
"func NewHTTP(host string, port int) Static {\n\treturn Static{\n\t\tprotocol: ProtocolHTTP,\n\t\thost: host,\n\t\tport: port,\n\t}\n}",
"func New(storage Storage) Server {\n\ts := &server{\n\t\tstorage: storage,\n\t\tr: chi.NewMux(),\n\t}\n\ts.routes()\n\treturn s\n}",
"func New(\n\troute *gin.Engine,\n\tcommandBus *command.Bus,\n\tqueryBus *query.Bus,\n\tutil *util.Util,\n\tapi api.Interface,\n) *Controller {\n\tcontroller := &Controller{\n\t\troute: route,\n\t\tcommandBus: commandBus,\n\t\tqueryBus: queryBus,\n\t\tutil: util,\n\t\tapi: api,\n\t}\n\tcontroller.SetupRoutes()\n\treturn controller\n}",
"func New(store *vehicle.Store, mngr *extlookup.Manager, cnf config.Config) *WebServer {\n\treturn &WebServer{time.Now(), store, mngr, cnf}\n}",
"func NewGinHandler(routes *routes.HTTPRoutes) *gin.Engine {\n\tgin.SetMode(gin.ReleaseMode)\n\n\te := gin.New()\n\n\troutes.AddAllHTTPRoutes(e)\n\n\treturn e\n}",
"func NewEngine(signalClient *signal.Client, mgmClient *mgm.Client, config *EngineConfig, cancel context.CancelFunc) *Engine {\n\treturn &Engine{\n\t\tsignal: signalClient,\n\t\tmgmClient: mgmClient,\n\t\tconns: map[string]*Connection{},\n\t\tpeerMux: &sync.Mutex{},\n\t\tsyncMsgMux: &sync.Mutex{},\n\t\tconfig: config,\n\t\tSTUNs: []*ice.URL{},\n\t\tTURNs: []*ice.URL{},\n\t\tcancel: cancel,\n\t}\n}",
"func New(host, port string, h http.Handler) *WebServer {\n\tvar ws WebServer\n\n\tws.Addr = net.JoinHostPort(host, port)\n\tws.Handler = h\n\n\treturn &ws\n}",
"func New(backend Backend, frameSize int, opts ...Option) (*Engine, error) {\n\te := &Engine{\n\t\tbackend: backend,\n\t\tmessages: newMessageChannel(),\n\t\tgraph: NewGraph(frameSize),\n\t\terrors: make(chan error),\n\t\tstop: make(chan error),\n\t\tchunks: int(backend.FrameSize() / frameSize),\n\t\tframeSize: frameSize,\n\t\tgain: 1,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(e)\n\t}\n\n\treturn e, e.graph.Reset(e.fadeIn, e.frameSize, backend.SampleRate())\n}",
"func New(cfg config.Proxy, bp httputil.BufferPool, token ntokend.TokenProvider, access service.AccessProvider, role service.RoleProvider, svcCert service.SvcCertProvider) Handler {\n\treturn &handler{\n\t\tproxy: &httputil.ReverseProxy{\n\t\t\tBufferPool: bp,\n\t\t},\n\t\ttoken: token,\n\t\taccess: access,\n\t\trole: role,\n\t\tcfg: cfg,\n\t\tsvcCert: svcCert,\n\t}\n}",
"func New(ctx context.Context, s *Session, health healthcheck.Handler) Controller {\n\ttemp := controller{\n\t\tcmd: make(chan int),\n\t\tsong: make(chan string),\n\t\tplaylist: make(chan string),\n\t\tready: make(chan struct{}),\n\t\tcurrentToken: make(chan oauth2.Token),\n\t\thealth: health,\n\t}\n\n\tgo run(ctx, s, temp)\n\treturn temp\n}",
"func New(r *httprouter.Router) Transport {\n\treturn &transport{r}\n}",
"func New(config Config, storageConfig storage.Config) *Server {\n\tstore, err := storage.New(storageConfig)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\thandler := NewHandler(config, store)\n\thandler.RegisterRoutes()\n\n\treturn &Server{\n\t\tconfig: config,\n\t\tserver: http.Server{\n\t\t\tHandler: handler.Router,\n\t\t\tWriteTimeout: config.WriteTimeout,\n\t\t\tReadTimeout: config.ReadTimeout,\n\t\t\tIdleTimeout: config.IdleTimeout,\n\t\t},\n\t\tstore: store,\n\t}\n}",
"func New(config ...Config) fiber.Handler {\n\t// Set default config\n\tcfg = configDefault(config...)\n\n\t// Return new handler\n\treturn func(c *fiber.Ctx) error {\n\t\t// Don't execute middleware if Next returns true\n\t\tif cfg.Next != nil && cfg.Next(c) {\n\t\t\treturn c.Next()\n\t\t}\n\n\t\t// validate request before continuing to next handler\n\t\tok, err := validateRequest(c)\n\t\tif !ok {\n\t\t\treturn fiber.NewError(fiber.StatusForbidden, err.Error())\n\t\t}\n\n\t\t// Continue stack\n\t\treturn c.Next()\n\t}\n}",
"func New(c *Config) (*Backend, error) {\n\tif err := validation.Validate.Struct(c); err != nil {\n\t\treturn nil, err\n\t}\n\tb := &Backend{\n\t\tkeys: make(chan *template.Key, 500),\n\t\tlog: c.Logger,\n\t\tsvc: c.SSM,\n\t}\n\treturn b, nil\n}",
"func New(cfg *Config) *Engine {\n\tif cfg.OpenCacheSize == 0 {\n\t\tcfg.OpenCacheSize = DefaultOpenCacheSize\n\t}\n\n\tif cfg.BatchSize == 0 {\n\t\tcfg.BatchSize = DefaultBatchSize\n\t}\n\n\tif cfg.KVStore == \"\" {\n\t\tcfg.KVStore = DefaultKVStore\n\t}\n\n\tif cfg.KVConfig == nil {\n\t\tcfg.KVConfig = store.KVConfig{}\n\t}\n\n\tng := &Engine{\n\t\tconfig: cfg,\n\t\tstores: cache.NewLRUCache(cfg.OpenCacheSize),\n\t}\n\n\tif debug, ok := cfg.KVConfig[\"debug\"].(bool); ok {\n\t\tng.debug = debug\n\t}\n\n\tng.stores.OnRemove(func(key string, value interface{}) {\n\t\tstorekv, ok := value.(store.KVStore)\n\n\t\tif !ok {\n\t\t\tpanic(\"Unexpected value in cache\")\n\t\t}\n\n\t\tif storekv.IsOpen() {\n\t\t\tstorekv.Close()\n\t\t}\n\t})\n\n\treturn ng\n}",
"func New(cfg config.Config, logger *zap.Logger) *Engine {\n\tvar b []*backendWrapper\n\n\tif cfg.Backends == nil {\n\t\tb = append(b, &backendWrapper{\n\t\t\tbackend: &backend.GoImage{},\n\t\t\tmimetypes: MimeTypes,\n\t\t})\n\t} else {\n\t\tif cfg.Backends.Gifsicle != nil {\n\t\t\tpath := cfg.Backends.Gifsicle.Path\n\t\t\tif path == \"\" {\n\t\t\t\tpath = \"gifsicle\"\n\t\t\t}\n\n\t\t\tif _, err := exec.LookPath(path); err == nil {\n\t\t\t\tb = append(b, &backendWrapper{\n\t\t\t\t\tbackend: &backend.Gifsicle{Path: path},\n\t\t\t\t\tmimetypes: cfg.Backends.Gifsicle.Mimetypes,\n\t\t\t\t\tweight: cfg.Backends.Gifsicle.Weight,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tif cfg.Backends.GoImage != nil {\n\t\t\tb = append(b, &backendWrapper{\n\t\t\t\tbackend: &backend.GoImage{},\n\t\t\t\tmimetypes: cfg.Backends.GoImage.Mimetypes,\n\t\t\t\tweight: cfg.Backends.GoImage.Weight,\n\t\t\t})\n\t\t}\n\t}\n\n\tsort.Slice(b, func(i, j int) bool {\n\t\treturn b[i].weight < b[j].weight\n\t})\n\n\tquality := config.DefaultQuality\n\tif cfg.Quality != 0 {\n\t\tquality = cfg.Quality\n\t}\n\n\treturn &Engine{\n\t\tDefaultFormat: cfg.DefaultFormat,\n\t\tDefaultQuality: quality,\n\t\tFormat: cfg.Format,\n\t\tbackends: b,\n\t\tlogger: logger,\n\t}\n}",
"func create() *Engine {\n\tengine := &Engine{\n\t\tRouterGroup: RouterGroup{\n\t\t\tHandlers: nil,\n\t\t\tbasePath: \"/\",\n\t\t\troot: true,\n\t\t},\n\t\ttrees: make(methodTrees, 0, 9),\n\t}\n\tengine.RouterGroup.engine = engine\n\treturn engine\n}",
"func New(c *Config) *Server {\n\ts := &Server{\n\t\techo: echo.New(),\n\t\ttasksConfig: c.Tasks,\n\t}\n\n\te := s.echo\n\te.Logger.SetLevel(glog.INFO)\n\t//e.Use(middleware.Logger())\n\n\tssoConf := &sso.OAuth2Config{\n\t\tJWTAuthConfig: sso.JWTAuthConfig{\n\t\t\tPrivateKey: c.PrivateKey,\n\t\t},\n\t\tOAuth2: &oauth2.Config{\n\t\t\tClientID: c.OAuthClientID,\n\t\t\tClientSecret: c.OAuthClientSecret,\n\t\t\tScopes: []string{\"user:email\"},\n\t\t\tEndpoint: sso.GithubEnterpriseEndpoint(githubEnterpriseDomain),\n\t\t},\n\t\tEmailLookupFunc: sso.GithubEnterpriseEmailLookup(githubEnterpriseDomain),\n\t\tNoAuthn: true,\n\t}\n\n\te.Use(sso.OAuth2FromConfig(ssoConf))\n\n\tapi := e.Group(\"/api\")\n\tapi.Use(sso.JWTAuthFromConfig(&ssoConf.JWTAuthConfig))\n\ttasks := api.Group(\"/tasks\")\n\ttasks.GET(\"\", s.getTasks)\n\ttasks.POST(\"/:name/run\", s.runTask)\n\n\tnames := s.tasksConfig.TaskNames()\n\tfor _, n := range names {\n\t\te.GET(fmt.Sprintf(\"/%s\", n), serveStatic(\"build/index.html\"))\n\t}\n\n\te.GET(\"/*\", serveStatic(\"build\"))\n\n\treturn s\n}",
"func New(config config.Config) Plugins {\n\tpkg := Plugins{\n\t\tclient: http.NewClient(config),\n\t\tpager: &http.LinkHeaderPager{},\n\t}\n\n\treturn pkg\n}",
"func New(sigs chan os.Signal) *Server {\n\ts := &Server{mux: http.NewServeMux(), sigs: sigs}\n\n\tif s.logger == nil {\n\t\ts.logger = log.New(os.Stdout, \"\", 0)\n\t}\n\n\ts.db = store.NewStore()\n\n\ts.mux.HandleFunc(\"/\", s.latencyMiddleware(s.index))\n\ts.mux.HandleFunc(\"/hash/\", s.latencyMiddleware(s.hash))\n\ts.mux.HandleFunc(\"/shutdown/\", s.latencyMiddleware(s.shutdown))\n\ts.mux.HandleFunc(\"/stats/\", s.stats)\n\n\treturn s\n}",
"func New(mws ...Middleware) *Router {\n\tr := &Router{\n\t\tparent: nil,\n\t\thostrm: newHostMatcher(),\n\t\tmiddlewares: Middlewares{},\n\t\tnamedMiddlewares: make(map[string]Middlewares),\n\t\tpool: newCtxPool(),\n\t}\n\tr.Use(mws...)\n\tr.Configure(\n\t\tWithLogger(lionLogger),\n\t\tWithServer(&http.Server{\n\t\t\tReadTimeout: 5 * time.Second,\n\t\t\tWriteTimeout: 10 * time.Second,\n\t\t}),\n\t)\n\treturn r\n}",
"func New(host, port string, handlers handler.Param) *Server {\n\tfor path, hndl := range handlers {\n\t\thttp.HandleFunc(path, hndl)\n\t}\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\treturn &Server{\n\t\tHost: host,\n\t\tPort: port,\n\t\tHandlers: handlers,\n\t\tListener: nil,\n\t\tClient: &http.Client{Transport: tr},\n\t\tSecureClient: nil,\n\t\tCertificate: &certificate.CACertificate{},\n\t}\n}",
"func NewEngine(cfg *Config) (*Engine, error) {\n\te := &Engine{\n\t\tcfg: *cfg,\n\t}\n\n\terr := e.SetMethods(e.cfg.AvailableMethods)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn e, nil\n}",
"func New(service Service) interface {\n\tmodule.Module\n\tbackend.Module\n} {\n\treturn newBackendModule(service)\n}",
"func New(cfg *config.Config) *Handler {\n\treturn &Handler{\n\t\tconfig: cfg,\n\t\tclient: &http.Client{Transport: &http.Transport{Proxy: cfg.Proxy}},\n\t}\n}",
"func New(host string) *service {\n\treturn &service{\n\t\thost: host,\n\t\tmux: http.NewServeMux(),\n\t}\n}",
"func New(c Config) *http.Server {\n\n\thandler := &RateLimitHandler{\n\t\trecords: map[string]*Record{},\n\t\tlimit: c.Limit,\n\t\twindow: c.Window,\n\t}\n\n\ts := &http.Server{\n\t\tAddr: fmt.Sprintf(\"0.0.0.0:%d\", c.Port),\n\t\tHandler: handler,\n\t}\n\treturn s\n}",
"func NewEngine() *Engine {\n\treturn &Engine{}\n}",
"func New(app dogma.Application, options ...EngineOption) *Engine {\n\tif app != nil {\n\t\toptions = append(options, WithApplication(app))\n\t}\n\n\topts := resolveEngineOptions(options...)\n\n\treturn &Engine{\n\t\topts: opts,\n\t\tdataStores: &persistence.DataStoreSet{\n\t\t\tProvider: opts.PersistenceProvider,\n\t\t},\n\t\tsemaphore: semaphore.NewWeighted(int64(opts.ConcurrencyLimit)),\n\t\tlogger: loggingx.WithPrefix(\n\t\t\topts.Logger,\n\t\t\t\"engine \",\n\t\t),\n\t\tready: make(chan struct{}),\n\t}\n}",
"func New(url string) *Client {\n\treturn &Client{&http.Client{}, url, func(r *http.Request) *http.Request { return r }}\n}",
"func New(e *calc.Endpoints, uh goagrpc.UnaryHandler) *Server {\n\treturn &Server{\n\t\tAddH: NewAddHandler(e.Add, uh),\n\t}\n}",
"func New(c *client.Client, u *client.UserConfig) Gateway {\n\treturn &gateway{\n\t\t*gw.NewHTTPGateway(c, u),\n\t}\n}",
"func New() (*Router, error) {\n\tmux := http.NewServeMux()\n\tmux.Handle(\"/ping\", generichandler.NewPingPongHandler())\n\tmux.Handle(\"/\", http.NotFoundHandler())\n\treturn &Router{mux}, nil\n}",
"func New(config *config.Config, fetcher *fetcher.Fetcher) Handler {\n\treturn Handler{\n\t\tfetcher: fetcher,\n\t\tconfig: config,\n\t}\n}",
"func New(e *calc.Endpoints, uh goagrpc.UnaryHandler) *Server {\n\treturn &Server{\n\t\tDivideH: NewDivideHandler(e.Divide, uh),\n\t}\n}",
"func New() *Engine {\n\tf := sprig.TxtFuncMap()\n\n\t// Prevent environment access inside the running KUDO Controller\n\tfuncs := []string{\"env\", \"expandenv\", \"base\", \"dir\", \"clean\", \"ext\", \"isAbs\"}\n\n\tfor _, fun := range funcs {\n\t\tdelete(f, fun)\n\t}\n\n\treturn &Engine{\n\t\tFuncMap: f,\n\t}\n}",
"func New(dir string, port int) *Controller {\n\tpublicErrorHandler, err := file.Open(dir+\"logs/\"+file.LOG_PUBLIC_ERRORS, true)\n\tif err != nil {\n\t\tfmt.Errorf(\"Error whilst trying to start public logging instance: %v\\n\", err.Error())\n\t}\n\n\tloadLogHandler, err := file.Open(dir+\"logs/\"+file.LOG_PUBLIC_LOAD, true)\n\tif err != nil {\n\t\tfmt.Errorf(\"Error whilst trying to start public load time logging instance: %v\\n\", err.Error())\n\t}\n\n\tcontroller = Controller{\n\t\tDocumentRoot: dir + \"public/\",\n\t\tPort: port,\n\t\tGracefulShutdownTimeout: 5 * time.Second,\n\t\tStatus: 0,\n\t\tPublicLogger: publicErrorHandler,\n\t\tLoadTimeLogger: loadLogHandler,\n\t}\n\n\tserver = http.Server{\n\t\tAddr: \"localhost:\" + strconv.Itoa(controller.Port),\n\t\tHandler: &controller,\n\t\tReadTimeout: 30 * time.Second,\n\t\tWriteTimeout: 30 * time.Second,\n\t\tMaxHeaderBytes: 0,\n\t}\n\n\treturn &controller\n}",
"func New() *keePassHTTP {\n\tkph := new(keePassHTTP)\n\n\t// replace mock fields\n\tkph.httpClient = &http.Client{Timeout: time.Second * 30}\n\tkph.randBytes = new(aes256CBCPksc7).randBytes\n\n\treturn kph\n}",
"func New() Go { return Go{} }",
"func New(URL string, username string, password string) *Hub {\n\tc := newClient(URL+\"/cgi/json-req\", username, password)\n\tlog.SetPrefix(\"INFO: \")\n\tlog.SetFlags(log.LstdFlags)\n\tlog.SetOutput(ioutil.Discard)\n\treturn &Hub{c}\n}",
"func New(s pb.AppServer) (engine *bm.Engine, err error) {\n\tvar (\n\t\tcfg bm.ServerConfig\n\t\tbbr bbr.Config\n\t\tkeep keepConfig\n\t\tct paladin.TOML\n\t)\n\terr = paladin.Get(\"http.toml\").Unmarshal(&ct)\n\thelper.Panic(err)\n\terr = config.Env(&ct, &cfg, \"Server\")\n\thelper.Panic(err)\n\terr = config.Env(&ct, &bbr, \"Bbr\")\n\thelper.Panic(err)\n\terr = config.Env(&ct, &keep, \"Keep\")\n\thelper.Panic(err)\n\tsvc = s\n\tengine = bm.DefaultServer(&cfg)\n\tlimiter := bm.NewRateLimiter(&bbr)\n\tengine.Use(limiter.Limit())\n\tengine.Use(keepAlive(&keep))\n\tcors := bm.CORS([]string{\"null\"})\n\tengine.Use(cors)\n\tpb.RegisterAppBMServer(engine, s)\n\t//initRouter(engine)\n\terr = engine.Start()\n\treturn\n}",
"func New() *Handler {\n\tp := &Handler{}\n\tp.reverseProxy = &httputil.ReverseProxy{\n\t\tTransport: &http.Transport{\n\t\t\tDial: func(network, address string) (net.Conn, error) {\n\t\t\t\treturn p.dial(context.TODO(), address)\n\t\t\t},\n\t\t},\n\t\tDirector: func(*http.Request) {\n\t\t\t// Do nothing, the request is self-sufficient\n\t\t},\n\t}\n\treturn p\n}",
"func New() iface.Backend {\n\treturn &Backend{\n\t\tBackend: common.NewBackend(new(config.Config)),\n\t\tgroups: make(map[string][]string),\n\t\ttasks: make(map[string][]byte),\n\t}\n}",
"func NewServer() (router *gin.Engine) {\n\tgin.SetMode(gin.ReleaseMode)\n\t// TODO: should this be New or Default?\n\trouter = gin.Default()\n\treturn router\n}",
"func New(env *solo.Solo) *RequestManager {\n\trequestManager := &RequestManager{env: env}\n\treturn requestManager\n}"
] | [
"0.7471335",
"0.74314415",
"0.7330198",
"0.70697814",
"0.6980976",
"0.6932873",
"0.6863734",
"0.681759",
"0.68026483",
"0.6745169",
"0.6705615",
"0.65955484",
"0.6583239",
"0.656722",
"0.6558003",
"0.65446764",
"0.6513068",
"0.65088445",
"0.6502816",
"0.64987904",
"0.64949733",
"0.6460053",
"0.64083207",
"0.63881",
"0.63801336",
"0.6378092",
"0.63733476",
"0.6344426",
"0.63369393",
"0.6311033",
"0.62918067",
"0.6263193",
"0.6223955",
"0.6212258",
"0.6212258",
"0.6184176",
"0.61732334",
"0.61657757",
"0.61412686",
"0.61272824",
"0.6122835",
"0.6108402",
"0.6087646",
"0.60866505",
"0.60809684",
"0.6079548",
"0.6079548",
"0.6077947",
"0.6071856",
"0.6067276",
"0.6066362",
"0.6051041",
"0.604432",
"0.6039772",
"0.6033468",
"0.6029741",
"0.6017392",
"0.60123086",
"0.5989048",
"0.59795934",
"0.59719115",
"0.59712297",
"0.5960983",
"0.59557825",
"0.59542173",
"0.59531415",
"0.59524965",
"0.5950749",
"0.59442765",
"0.5942547",
"0.5920758",
"0.59187007",
"0.5916557",
"0.5916217",
"0.59124273",
"0.5910388",
"0.59043694",
"0.58999777",
"0.5895053",
"0.58931285",
"0.5892615",
"0.5886346",
"0.58830607",
"0.5876769",
"0.5874698",
"0.58738625",
"0.58733445",
"0.5855377",
"0.585372",
"0.58508384",
"0.5850696",
"0.58496594",
"0.5849161",
"0.58469725",
"0.5846969",
"0.58462054",
"0.5845564",
"0.58436817",
"0.5839857",
"0.5834997"
] | 0.7473012 | 0 |
AddRoutes adds routes to our router. | func AddRoutes(router *gin.Engine, db storage.Storage, tracer tracer.Tracer) {
apiRoutes := router.Group("/v0")
// routes.GET("/", ReturnData(db))
// routes.GET("/key/:key", ReturnSingleObject(db))
apiRoutes.GET("/graph", routes.GetGraph(db))
apiRoutes.GET("/metrics", routes.GetMetrics(db))
apiRoutes.POST("/start", routes.AddTrace(db, tracer))
apiRoutes.DELETE("/stop", routes.StopTrace(db, tracer))
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func AddRoutes(app *server.App) {\n\t// Internal routes\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /phone\",\n\t\tType: server.RouteTypeCustom,\n\t\tPublic: true,\n\t\tNoProtoCheck: true,\n\t\tHandler: controllers.PhoneController,\n\t}, server.RouteInternal)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /locked\",\n\t\tType: server.RouteTypeCustom,\n\t\tPublic: true,\n\t\tNoProtoCheck: true,\n\t\tHandler: controllers.LockedController,\n\t}, server.RouteInternal)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /cloud-init/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tPublic: true,\n\t\tNoProtoCheck: true,\n\t\tHandler: controllers.CloudInitController,\n\t}, server.RouteInternal)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /env\",\n\t\tType: server.RouteTypeCustom,\n\t\tPublic: true,\n\t\tNoProtoCheck: true,\n\t\tHandler: controllers.EnvController,\n\t}, server.RouteInternal)\n\n\t// API routes\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /log/history\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetLogHistoryController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /log\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.LogController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /vm\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.ListVMsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /vm/search\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.SearchVMsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /vm/config/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetVMConfigController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /vm/infos/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetVMInfosController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /vm/do-actions/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetVMDoActionsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /vm/console/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetVMConsoleController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /vm\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.NewVMSyncController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /vm-async\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.NewVMAsyncController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /vm/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.ActionVMController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"DELETE /vm/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.DeleteVMController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /version\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.VersionController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /seed\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.ListSeedController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /seed/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetSeedStatusController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /seed/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.ActionSeedController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /backup\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.ListBackupsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /backup\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.UploadBackupController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /backup/expire/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.SetBackupExpireController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /backup/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.DownloadBackupController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"DELETE /backup/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.DeleteBackupController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /key\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.ListKeysController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /key\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.NewKeyController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /key/right/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.ListKeyRightsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /key/right/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.NewKeyRightController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"DELETE /key/right/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.DeleteKeyRightController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /sshpair\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetKeyPairController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /status\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetStatusController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /state/zip\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetStateZipController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /peer\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.ListPeersController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /secret\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.ListSecretsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /secret/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetSecretController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /secret/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.SetSecretController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"DELETE /secret/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.DeleteSecretController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /secret-sync\",\n\t\tHandler: controllers.SyncSecretsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /vm/with-secret/*\",\n\t\tHandler: controllers.GetVMsUsingSecretsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /greenhouse\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.ListGreenhouseVMsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"DELETE /greenhouse/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.AbordGreenhouseVMController,\n\t}, server.RouteAPI)\n\n}",
"func AddRoutes(e *echo.Echo) {\n\te.GET(\"/\", func(ctx echo.Context) error { return ctx.JSON(http.StatusOK, Heartbeat()) })\n\te.POST(\"/order\", handlers.CreateOrder)\n\te.PUT(\"/order/:id\", handlers.UpdateOrder)\n\te.PATCH(\"/order/:id\", handlers.UpdateOrder)\n\te.GET(\"/orders\", handlers.ListOrders)\n}",
"func AddRoutes(app *fiber.App) {\n\tapp.Static(\"/\", \"./public\")\n\tapp.Get(\"/ws/status\", websocket.New(StatusWSView))\n\n\tapp.Put(\"/flight\", CreateFlightView)\n\tapp.Delete(\"/flight/:route\", DeleteFlightView)\n\tapp.Put(\"/flights/import/csv\", ImportFlightsView)\n\tapp.Get(\"/flights/search/:route\", CheapestRouteView)\n\n\tapp.Use(NotFoundView)\n}",
"func (c *controlAPI) AddRoutes(router *gin.Engine) {\n\trouter.GET(\"/health\", c.CheckHealth)\n\trouter.GET(\"/version\", c.VersionInfo)\n}",
"func AddRoutes(mx *mux.Router) {\n\tformatter := render.New(render.Options{\n\t\tIndentJSON: true,\n\t})\n\t//create session here\n\tsession, err := mgo.Dial(dbcfg.IP)\n\t// should close the session on exit?\n\tif err != nil {\n\t\tpanic(\"Could not connect to db\")\n\t}\n\tproductRepo := NewMongoProductRepository(session, dbcfg)\n\n\tinitRoutes(mx, formatter, productRepo)\n}",
"func (c *Controller) AddRoutes(router *mux.Router) *mux.Router {\n\tfmt.Println(&c.Repo.users)\n\tbasePath := \"/api\"\n\trouter.HandleFunc(basePath+\"/login\", c.login).Methods(\"POST\")\n\trouter.HandleFunc(basePath+\"/register\", c.register).Methods(\"POST\")\n\trouter.HandleFunc(basePath+\"/users\", c.createUser).Methods(\"POST\")\n\trouter.HandleFunc(basePath+\"/users\", c.listUsers).Methods(\"GET\")\n\trouter.HandleFunc(basePath+\"/users/{id}\", c.getUser).Methods(\"GET\")\n\trouter.HandleFunc(basePath+\"/users/{id}\", c.updateUser).Methods(\"PUT\")\n\trouter.HandleFunc(basePath+\"/users/{id}\", c.deleteUser).Methods(\"DELETE\")\n\treturn router\n}",
"func (e *Server) AddRoutes(rs []Route, opts ...RouteOption) {\n\tr := featuredRoutes{\n\t\troutes: rs,\n\t}\n\tfor _, opt := range opts {\n\t\topt(&r)\n\t}\n\te.ngin.AddRoutes(r)\n}",
"func (p *proxyAPI) AddRoutes(router *gin.Engine) {\n\trouter.POST(\"/pool\", p.createPool)\n\trouter.DELETE(\"/pool/:poolId\", p.deletePool)\n\trouter.POST(\"/pool/:poolId\", p.addToPool)\n\trouter.DELETE(\"/pool/:poolId/:endpointId\", p.deleteFromPool)\n\trouter.Any(\"/api/:id/*path\", p.proxy)\n\trouter.GET(\"/ws/:id/*path\", p.proxy)\n}",
"func (h *WorkloadHandler) AddRoutes(e *gin.Engine) {\n\te.GET(WorkloadRoot, h.Get)\n}",
"func (r *RestRouter) Add(s restinterface.IRestRoutes) {\n\tr.add(s.GetRoutes())\n}",
"func (h *Handler) AddRoutes(router *mux.Router) {\n\trouter.Methods(http.MethodGet, http.MethodHead).Path(\"/ping\").\n\t\tHandlerFunc(func(response http.ResponseWriter, request *http.Request) {\n\t\t\tstatusCode := http.StatusOK\n\t\t\tif h.terminating {\n\t\t\t\tstatusCode = http.StatusServiceUnavailable\n\t\t\t}\n\t\t\tresponse.WriteHeader(statusCode)\n\t\t\tfmt.Fprint(response, http.StatusText(statusCode))\n\t\t})\n}",
"func (hr *httpRouter) AddRoute(p string, public bool, c controller.Interface, m *middleware.Chain) {\n\tr := route{pattern: p, public: public, controller: c, mws: m}\n\thr.routes = append(hr.routes, r)\n}",
"func (h *StorageClassHandler) AddRoutes(e *gin.Engine) {\n\te.GET(StorageClassesRoot, h.List)\n\te.GET(StorageClassesRoot+\"/\", h.List)\n\te.GET(StorageClassRoot, h.Get)\n}",
"func (routes *Routes) Add(url string, handlers ...interface{}) {\n\tslice := strings.SplitN(url, \":\", 2)\n\n\t*routes = append(*routes, Route{\n\t\tMethod: slice[0],\n\t\tUrl: slice[1],\n\t\tHandlers: Middware{}.Then(handlers...),\n\t})\n\treturn\n}",
"func (h *StaticHandler) AddRoutes(apply func(m, p string, h http.Handler, mws ...func(http.Handler) http.Handler)) {\n\tfileServer := http.FileServer(h.fs)\n\tapply(http.MethodGet, \"/*filepath\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tr.URL.Path = routegroup.PathParam(r.Context(), \"filepath\")\n\t\tfileServer.ServeHTTP(w, r)\n\t}))\n}",
"func (h *handle) AddRoute(path string, handlers ...fiber.Handler) *handle {\n\th.Application.Add(\"get\", path, handlers...)\n\treturn h\n}",
"func RegisterRoutes(router *mux.Router, service ServiceInterface) {\n\troutes.AddRoutes(newRoutes(service), router)\n}",
"func (s *Server) AddRoutes(e *echo.Echo) {\n\te.GET(\"/sigchain/:kid/:seq\", s.getSigchainStatement)\n\te.PUT(\"/sigchain/:kid/:seq\", s.putSigchainStatement)\n\te.GET(\"/sigchain/:kid\", s.getSigchain)\n\n\te.POST(\"/check\", s.check)\n\n\te.GET(\"/user/search\", s.getUserSearch)\n\te.GET(\"/user/:kid\", s.getUser)\n\n\t// Tasks\n\te.POST(\"/task/check/:kid\", s.taskCheck)\n\n\t// Cron\n\te.POST(\"/cron/check\", s.cronCheck)\n\n\t// Channel\n\te.PUT(\"/channel/:cid\", s.putChannel)\n\te.GET(\"/channel/:cid\", s.getChannel)\n\t// Channel (users)\n\te.GET(\"/channel/:cid/users\", s.getChannelUsers)\n\t// e.POST(\"/channel/:cid/users\", s.postChannelUsers)\n\t// Messages\n\te.POST(\"/channel/:cid/msgs\", s.postMessage)\n\te.GET(\"/channel/:cid/msgs\", s.listMessages)\n\t// Channel (invite)\n\te.POST(\"/channel/:cid/invites\", s.postChannelInvites)\n\te.GET(\"/channel/:cid/invites\", s.getChannelInvites)\n\n\t// User (channels)\n\te.GET(\"/user/:kid/channels\", s.usersChannels)\n\te.GET(\"/user/:kid/invites\", s.userChannelInvites)\n\te.GET(\"/user/:kid/invite/:cid\", s.getUserChannelInvite)\n\te.POST(\"/user/:kid/invite/:cid/accept\", s.acceptUserChannelInvite)\n\te.DELETE(\"/user/:kid/invite/:cid\", s.deleteUserChannelInvite)\n\n\t// Vault\n\te.POST(\"/vault/:kid\", s.postVault)\n\te.GET(\"/vault/:kid\", s.listVault)\n\te.DELETE(\"/vault/:kid\", s.deleteVault)\n\te.HEAD(\"/vault/:kid\", s.headVault)\n\n\t// Disco\n\te.PUT(\"/disco/:kid/:rid/:type\", s.putDisco)\n\te.GET(\"/disco/:kid/:rid/:type\", s.getDisco)\n\te.DELETE(\"/disco/:kid/:rid\", s.deleteDisco)\n\n\t// Invite Code\n\te.POST(\"/invite/code/:kid/:rid\", s.postInviteCode)\n\te.GET(\"/invite/code/:code\", s.getInviteCode)\n\n\t// Share\n\te.GET(\"/share/:kid\", s.getShare)\n\te.PUT(\"/share/:kid\", s.putShare)\n\n\t// Sigchain (aliases)\n\te.GET(\"/:kid\", s.getSigchainAliased)\n\te.GET(\"/:kid/:seq\", s.getSigchainStatementAliased)\n\te.PUT(\"/:kid/:seq\", s.putSigchainStatementAliased)\n\n\t// Admin\n\te.POST(\"/admin/check/:kid\", s.adminCheck)\n}",
"func (f *File) AddRoutes(name string, routes []*types.Route) error {\n\tp, err := f.GetProfile(name)\n\tif err != nil && !errors.Is(err, types.ErrUnknownProfile) {\n\t\treturn err\n\t}\n\n\tif p == nil {\n\t\tp = &types.Profile{\n\t\t\tName: name,\n\t\t\tStatus: types.Enabled,\n\t\t\tRoutes: map[string]*types.Route{},\n\t\t}\n\n\t\tp.AddRoutes(routes)\n\n\t\treturn f.AddProfile(p)\n\t}\n\n\tp.AddRoutes(routes)\n\n\treturn nil\n}",
"func (h *Handler) AddRoute(service config.Service) {\n\th.Routes = append(h.Routes, service)\n}",
"func RegisterRoutes(router *apirouter.Router) {\n\n\t// Load the service dependencies\n\tloadService()\n\n\t// Set the main index page (navigating to slash)\n\trouter.HTTPRouter.GET(\"/\", router.Request(index))\n\trouter.HTTPRouter.OPTIONS(\"/\", router.SetCrossOriginHeaders)\n\n\t// Set the health request (used for load balancers)\n\trouter.HTTPRouter.GET(\"/\"+config.HealthRequestPath, router.Request(health))\n\trouter.HTTPRouter.OPTIONS(\"/\"+config.HealthRequestPath, router.SetCrossOriginHeaders)\n\trouter.HTTPRouter.HEAD(\"/\"+config.HealthRequestPath, router.SetCrossOriginHeaders)\n\n\t// Set the 404 handler (any request not detected)\n\trouter.HTTPRouter.NotFound = http.HandlerFunc(notFound)\n\n\t// Set the method not allowed\n\trouter.HTTPRouter.MethodNotAllowed = http.HandlerFunc(notAllowed)\n}",
"func (service *Service) RegisterRoutes() {\n\tvar (\n\t\tbaseEndpoint = \"/api/\"\n\t\tconvertEndpoint = baseEndpoint + \"convert\"\n\t\thealthEndpoint = baseEndpoint + \"health\"\n\t)\n\n\tservice.router.GET(healthEndpoint, business.Health)\n\n\t// The snapmatic files usually are less than 1 MB but buffer for 2 just to be safe\n\tservice.router.MaxMultipartMemory = 2 << 20 // 2 MiB\n\tservice.router.POST(convertEndpoint, business.Convert)\n}",
"func addRoutes(p *nats.Conn) {\n\tr := mux.NewRouter()\n\tr.Methods(\"POST\").Path(\"/topics/{topic}\").Handler(\n\t\thandlers.LoggingHandler(os.Stdout, handler(p, topic)))\n\tr.Methods(\"POST\").Path(\"/requests/{topic}\").Handler(\n\t\thandlers.LoggingHandler(os.Stdout, handler(p, request)))\n\thttp.Handle(\"/\", r)\n}",
"func (rtr *Router) AddRoute(path string, method string, handler http.Handler) *Router {\n\trtr.routes[route{Path: path, Method: method}] = handler\n\treturn rtr\n}",
"func (r *Router) Add(route *model.Route) error {\n\tr.rMutex.Lock()\n\tdefer r.rMutex.Unlock()\n\tr.routes = append([]*model.Route{route}, r.routes...)\n\treturn r.saveToDB()\n}",
"func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, storeName string) {\n\ts := r.PathPrefix(fmt.Sprintf(\"/%s\", storeName)).Subrouter()\n\n\t// add new tx msg routes here\n\ts.HandleFunc(\"/ingestheaderchain\", ingestHeaderChainHandler(cliCtx)).Methods(\"POST\")\n\ts.HandleFunc(\"/ingestdiffchange\", ingestDifficultyChangeHandler(cliCtx)).Methods(\"POST\")\n\ts.HandleFunc(\"/marknewheaviest\", markNewHeaviestHandler(cliCtx)).Methods(\"POST\")\n\ts.HandleFunc(\"/newrequest\", newRequestHandler(cliCtx)).Methods(\"POST\")\n\ts.HandleFunc(\"/provideproof\", provideProofHandler(cliCtx)).Methods(\"POST\")\n\n\t// add new query routes below\n\t// {} denotes variable parts of the url route\n\t// These are our function arguments\n\ts.HandleFunc(\"/isancestor/{digest}/{ancestor}/\", isAncestorHandler(cliCtx, storeName)).Methods(\"GET\")\n\ts.HandleFunc(\"/isancestor/{digest}/{ancestor}/{limit}\", isAncestorHandler(cliCtx, storeName)).Methods(\"GET\")\n\ts.HandleFunc(\"/getrelaygenesis\", getRelayGenesisHandler(cliCtx, storeName)).Methods(\"GET\")\n\ts.HandleFunc(\"/getlastreorglca\", getLastReorgLCAHandler(cliCtx, storeName)).Methods(\"GET\")\n\ts.HandleFunc(\"/getbestdigest\", getBestDigest(cliCtx, storeName)).Methods(\"GET\")\n\ts.HandleFunc(\"/findancestor/{digest}/{offset}\", findAncestorHandler(cliCtx, storeName)).Methods(\"GET\")\n\ts.HandleFunc(\"/ismostrecentcommonancestor/{ancestor}/{left}/{right}/\", isMostRecentCommonAncestorHandler(cliCtx, storeName)).Methods(\"GET\")\n\ts.HandleFunc(\"/ismostrecentcommonancestor/{ancestor}/{left}/{right}/{limit}\", isMostRecentCommonAncestorHandler(cliCtx, storeName)).Methods(\"GET\")\n\ts.HandleFunc(\"/heaviestfromancestor/{ancestor}/{currentbest}/{newbest}/\", heaviestFromAncestorHandler(cliCtx, storeName)).Methods(\"GET\")\n\ts.HandleFunc(\"/heaviestfromancestor/{ancestor}/{currentbest}/{newbest}/{limit}\", heaviestFromAncestorHandler(cliCtx, storeName)).Methods(\"GET\")\n\ts.HandleFunc(\"/getrequest/{id}\", getRequestHandler(cliCtx, storeName)).Methods(\"GET\")\n\ts.HandleFunc(\"/checkrequests\", checkRequestsHandler(cliCtx, storeName)).Methods(\"POST\") // technically a view only query, POST is due to complex params\n\ts.HandleFunc(\"/checkproof\", checkProofHandler(cliCtx, storeName)).Methods(\"POST\") // technically a view only query, POST is due to complex params\n}",
"func (rtr *Router) AddRoute(path string, h sdk.Handler) sdk.Router {\n\tif !isAlphaNumeric(path) {\n\t\tpanic(\"route expressions can only contain alphanumeric characters\")\n\t}\n\tif rtr.routes[path] != nil {\n\t\tpanic(fmt.Sprintf(\"route %s has already been initialized\", path))\n\t}\n\n\trtr.routes[path] = h\n\treturn rtr\n}",
"func RegisterRoutes() arbor.RouteCollection {\n\troutes = append(routes, productServiceRoutes...)\n\treturn routes\n}",
"func (server *testHTTPServerImpl) AddRoute(method string, path string, handlerFunc http.HandlerFunc) {\n\tserver.router.HandleFunc(path, server.wrapHandlerFunc(handlerFunc)).Methods(method)\n}",
"func (s *Server) addRoute(method string, pattern string, handler RouteHandler) {\n\ts.routes = append(s.routes, Route{handler : handler, pattern : pattern, method : method})\n}",
"func (wr *WebRouter) AddRoute(r *Route) *WebRouter {\n\twr.routes = append(wr.routes, r)\n\n\treturn wr\n}",
"func (ifc *Interface) AddRoutes(routesData []*RouteData) error {\n\tvar errs []error\n\tfor _, rd := range routesData {\n\t\tif err := ifc.AddRoute(rd); err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"%v: %w\", rd, err))\n\t\t}\n\t}\n\tif len(errs) == 0 {\n\t\treturn nil\n\t}\n\tif len(errs) == 1 {\n\t\treturn errs[0]\n\t}\n\treturn multiError(errs)\n}",
"func AddRoute(method, path, handlerName string) error {\n\trouteDefinition := fmt.Sprintf(`app.%v(\"%v\", %v)`, method, path, handlerName)\n\treturn AddInsideAppBlock(routeDefinition)\n}",
"func AddRouter() *mux.Router {\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"/health\", getHealthAPI).Methods(\"GET\")\n\trouter.HandleFunc(\"/sleep\", sleepAPI).Methods(\"GET\")\n\trouter.HandleFunc(\"/postKafka\", postKafkaAPI).Methods(\"POST\")\n\treturn router\n}",
"func RegisterRoutes(ctx client.Context, r *mux.Router, ns string) {\n\t// Get all orders\n\tr.HandleFunc(fmt.Sprintf(\"/%s/order/list\", ns), listOrdersHandler(ctx, ns)).Methods(\"GET\")\n\n\t// Get single order info\n\tr.HandleFunc(fmt.Sprintf(\"/%s/order/info\", ns), getOrderHandler(ctx, ns)).Methods(\"GET\")\n\n\t// Get all bids\n\tr.HandleFunc(fmt.Sprintf(\"/%s/bid/list\", ns), listBidsHandler(ctx, ns)).Methods(\"GET\")\n\n\t// Get single bid info\n\tr.HandleFunc(fmt.Sprintf(\"/%s/bid/info\", ns), getBidHandler(ctx, ns)).Methods(\"GET\")\n\n\t// Get all leases\n\tr.HandleFunc(fmt.Sprintf(\"/%s/lease/list\", ns), listLeasesHandler(ctx, ns)).Methods(\"GET\")\n\n\t// Get single order info\n\tr.HandleFunc(fmt.Sprintf(\"/%s/lease/info\", ns), getLeaseHandler(ctx, ns)).Methods(\"GET\")\n}",
"func RegisterRoutes(router *mux.Router, service ServiceInterface) {\n\tsubRouter := router.PathPrefix(\"/v1\").Subrouter()\n\troutes.AddRoutes(newRoutes(service), subRouter)\n}",
"func (rest *RestRouter) AddRoute(method string, urlPattern string, handler func(http.ResponseWriter, *http.Request, *RestParams)) (err error) {\n\trest.mu.Lock()\n\tdefer rest.mu.Unlock()\n\n\tif method == \"\" || urlPattern == \"\" {\n\t\terr = NewRouterError(\"Cannot have an empty pattern or method\")\n\t\treturn\n\t}\n\n\tif handler == nil {\n\t\terr = NewRouterError(\"Cannot have a nil handler\")\n\t\treturn\n\t}\n\n\tre := routeEntry{}\n\tre.handler = handler\n\tre.path, re.pathParams, err = makePath(urlPattern)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, ok := rest.routes[method]; !ok {\n\t\trest.routes[method] = make([]routeEntry, 0)\n\t}\n\trest.routes[method] = append(rest.routes[method], re)\n\n\treturn\n}",
"func AddRoutingUrls(router *gin.Engine) {\n\trouter.GET(\"/ping\", api.Ping)\n\trouter.GET(\"/ipinformation\", api.IpInfo)\n}",
"func AddSecureRoutes(router *mux.Router, routers ...openapi.Router) *mux.Router {\n\tfor _, api := range routers {\n\t\tfor _, route := range api.Routes() {\n\t\t\tvar handler http.Handler\n\t\t\thandler = route.HandlerFunc\n\t\t\thandler = openapi.Logger(handler, route.Name)\n\t\t\thandler = NewEnsureAuth(handler, route.Permission)\n\n\t\t\trouter.\n\t\t\t\tMethods(route.Method).\n\t\t\t\tPath(route.Pattern).\n\t\t\t\tName(route.Name).\n\t\t\t\tHandler(handler)\n\t\t}\n\t}\n\n\treturn router\n}",
"func (r *Router) addRoute(method, path string, handlers []HandlerFunc) {\n\troute := &route{\n\t\tmethod: method,\n\t\thandlers: handlers,\n\t}\n\tr.routers[fmt.Sprintf(RouterKey, path, method)] = route\n}",
"func (r *Routes) Add(pattern string, f fasthttp.RequestHandler) {\n\tr.Routes[normaliseRoute(pattern)] = f\n}",
"func (r *Router) AddRoute(path string, rh RouteHandler) error {\n\n\tmp, err := parseMpath(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.rlist = append(r.rlist, routeEntry{\n\t\tmpath: mp,\n\t\trh: rh,\n\t})\n\n\treturn nil\n}",
"func AddRoutes(r api.RoomserverInternalAPI, internalAPIMux *mux.Router) {\n\tinternalAPIMux.Handle(RoomserverInputRoomEventsPath,\n\t\thttputil.MakeInternalAPI(\"inputRoomEvents\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.InputRoomEventsRequest\n\t\t\tvar response api.InputRoomEventsResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tr.InputRoomEvents(req.Context(), &request, &response)\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverPerformInvitePath,\n\t\thttputil.MakeInternalAPI(\"performInvite\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformInviteRequest\n\t\t\tvar response api.PerformInviteResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.PerformInvite(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverPerformJoinPath,\n\t\thttputil.MakeInternalAPI(\"performJoin\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformJoinRequest\n\t\t\tvar response api.PerformJoinResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tr.PerformJoin(req.Context(), &request, &response)\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverPerformLeavePath,\n\t\thttputil.MakeInternalAPI(\"performLeave\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformLeaveRequest\n\t\t\tvar response api.PerformLeaveResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.PerformLeave(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverPerformPeekPath,\n\t\thttputil.MakeInternalAPI(\"performPeek\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformPeekRequest\n\t\t\tvar response api.PerformPeekResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tr.PerformPeek(req.Context(), &request, &response)\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverPerformInboundPeekPath,\n\t\thttputil.MakeInternalAPI(\"performInboundPeek\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformInboundPeekRequest\n\t\t\tvar response api.PerformInboundPeekResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.PerformInboundPeek(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverPerformPeekPath,\n\t\thttputil.MakeInternalAPI(\"performUnpeek\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformUnpeekRequest\n\t\t\tvar response api.PerformUnpeekResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tr.PerformUnpeek(req.Context(), &request, &response)\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverPerformRoomUpgradePath,\n\t\thttputil.MakeInternalAPI(\"performRoomUpgrade\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformRoomUpgradeRequest\n\t\t\tvar response api.PerformRoomUpgradeResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tr.PerformRoomUpgrade(req.Context(), &request, &response)\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverPerformPublishPath,\n\t\thttputil.MakeInternalAPI(\"performPublish\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformPublishRequest\n\t\t\tvar response api.PerformPublishResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tr.PerformPublish(req.Context(), &request, &response)\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryPublishedRoomsPath,\n\t\thttputil.MakeInternalAPI(\"queryPublishedRooms\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryPublishedRoomsRequest\n\t\t\tvar response api.QueryPublishedRoomsResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryPublishedRooms(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryLatestEventsAndStatePath,\n\t\thttputil.MakeInternalAPI(\"queryLatestEventsAndState\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryLatestEventsAndStateRequest\n\t\t\tvar response api.QueryLatestEventsAndStateResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryLatestEventsAndState(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryStateAfterEventsPath,\n\t\thttputil.MakeInternalAPI(\"queryStateAfterEvents\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryStateAfterEventsRequest\n\t\t\tvar response api.QueryStateAfterEventsResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryStateAfterEvents(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryEventsByIDPath,\n\t\thttputil.MakeInternalAPI(\"queryEventsByID\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryEventsByIDRequest\n\t\t\tvar response api.QueryEventsByIDResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryEventsByID(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryMembershipForUserPath,\n\t\thttputil.MakeInternalAPI(\"QueryMembershipForUser\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryMembershipForUserRequest\n\t\t\tvar response api.QueryMembershipForUserResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryMembershipForUser(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryMembershipsForRoomPath,\n\t\thttputil.MakeInternalAPI(\"queryMembershipsForRoom\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryMembershipsForRoomRequest\n\t\t\tvar response api.QueryMembershipsForRoomResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryMembershipsForRoom(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryServerJoinedToRoomPath,\n\t\thttputil.MakeInternalAPI(\"queryServerJoinedToRoom\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryServerJoinedToRoomRequest\n\t\t\tvar response api.QueryServerJoinedToRoomResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryServerJoinedToRoom(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryServerAllowedToSeeEventPath,\n\t\thttputil.MakeInternalAPI(\"queryServerAllowedToSeeEvent\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryServerAllowedToSeeEventRequest\n\t\t\tvar response api.QueryServerAllowedToSeeEventResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryServerAllowedToSeeEvent(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryMissingEventsPath,\n\t\thttputil.MakeInternalAPI(\"queryMissingEvents\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryMissingEventsRequest\n\t\t\tvar response api.QueryMissingEventsResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryMissingEvents(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryStateAndAuthChainPath,\n\t\thttputil.MakeInternalAPI(\"queryStateAndAuthChain\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryStateAndAuthChainRequest\n\t\t\tvar response api.QueryStateAndAuthChainResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryStateAndAuthChain(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverPerformBackfillPath,\n\t\thttputil.MakeInternalAPI(\"PerformBackfill\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformBackfillRequest\n\t\t\tvar response api.PerformBackfillResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.PerformBackfill(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverPerformForgetPath,\n\t\thttputil.MakeInternalAPI(\"PerformForget\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformForgetRequest\n\t\t\tvar response api.PerformForgetResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.PerformForget(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryRoomVersionCapabilitiesPath,\n\t\thttputil.MakeInternalAPI(\"QueryRoomVersionCapabilities\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryRoomVersionCapabilitiesRequest\n\t\t\tvar response api.QueryRoomVersionCapabilitiesResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryRoomVersionCapabilities(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryRoomVersionForRoomPath,\n\t\thttputil.MakeInternalAPI(\"QueryRoomVersionForRoom\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryRoomVersionForRoomRequest\n\t\t\tvar response api.QueryRoomVersionForRoomResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryRoomVersionForRoom(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverSetRoomAliasPath,\n\t\thttputil.MakeInternalAPI(\"setRoomAlias\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.SetRoomAliasRequest\n\t\t\tvar response api.SetRoomAliasResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.SetRoomAlias(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverGetRoomIDForAliasPath,\n\t\thttputil.MakeInternalAPI(\"GetRoomIDForAlias\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.GetRoomIDForAliasRequest\n\t\t\tvar response api.GetRoomIDForAliasResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.GetRoomIDForAlias(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverGetCreatorIDForAliasPath,\n\t\thttputil.MakeInternalAPI(\"GetCreatorIDForAlias\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.GetCreatorIDForAliasRequest\n\t\t\tvar response api.GetCreatorIDForAliasResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.GetCreatorIDForAlias(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverGetAliasesForRoomIDPath,\n\t\thttputil.MakeInternalAPI(\"getAliasesForRoomID\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.GetAliasesForRoomIDRequest\n\t\t\tvar response api.GetAliasesForRoomIDResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.GetAliasesForRoomID(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverRemoveRoomAliasPath,\n\t\thttputil.MakeInternalAPI(\"removeRoomAlias\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.RemoveRoomAliasRequest\n\t\t\tvar response api.RemoveRoomAliasResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.RemoveRoomAlias(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverQueryCurrentStatePath,\n\t\thttputil.MakeInternalAPI(\"queryCurrentState\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.QueryCurrentStateRequest{}\n\t\t\tresponse := api.QueryCurrentStateResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.QueryCurrentState(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverQueryRoomsForUserPath,\n\t\thttputil.MakeInternalAPI(\"queryRoomsForUser\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.QueryRoomsForUserRequest{}\n\t\t\tresponse := api.QueryRoomsForUserResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.QueryRoomsForUser(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverQueryBulkStateContentPath,\n\t\thttputil.MakeInternalAPI(\"queryBulkStateContent\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.QueryBulkStateContentRequest{}\n\t\t\tresponse := api.QueryBulkStateContentResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.QueryBulkStateContent(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverQuerySharedUsersPath,\n\t\thttputil.MakeInternalAPI(\"querySharedUsers\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.QuerySharedUsersRequest{}\n\t\t\tresponse := api.QuerySharedUsersResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.QuerySharedUsers(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverQueryKnownUsersPath,\n\t\thttputil.MakeInternalAPI(\"queryKnownUsers\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.QueryKnownUsersRequest{}\n\t\t\tresponse := api.QueryKnownUsersResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.QueryKnownUsers(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverQueryServerBannedFromRoomPath,\n\t\thttputil.MakeInternalAPI(\"queryServerBannedFromRoom\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.QueryServerBannedFromRoomRequest{}\n\t\t\tresponse := api.QueryServerBannedFromRoomResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.QueryServerBannedFromRoom(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverQueryAuthChainPath,\n\t\thttputil.MakeInternalAPI(\"queryAuthChain\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.QueryAuthChainRequest{}\n\t\t\tresponse := api.QueryAuthChainResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.QueryAuthChain(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n}",
"func AddRoutes(intAPI api.FederationInternalAPI, internalAPIMux *mux.Router) {\n\tinternalAPIMux.Handle(\n\t\tFederationAPIQueryJoinedHostServerNamesInRoomPath,\n\t\thttputil.MakeInternalAPI(\"QueryJoinedHostServerNamesInRoom\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryJoinedHostServerNamesInRoomRequest\n\t\t\tvar response api.QueryJoinedHostServerNamesInRoomResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := intAPI.QueryJoinedHostServerNamesInRoom(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIPerformJoinRequestPath,\n\t\thttputil.MakeInternalAPI(\"PerformJoinRequest\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformJoinRequest\n\t\t\tvar response api.PerformJoinResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tintAPI.PerformJoin(req.Context(), &request, &response)\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIPerformLeaveRequestPath,\n\t\thttputil.MakeInternalAPI(\"PerformLeaveRequest\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformLeaveRequest\n\t\t\tvar response api.PerformLeaveResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := intAPI.PerformLeave(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIPerformInviteRequestPath,\n\t\thttputil.MakeInternalAPI(\"PerformInviteRequest\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformInviteRequest\n\t\t\tvar response api.PerformInviteResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := intAPI.PerformInvite(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIPerformDirectoryLookupRequestPath,\n\t\thttputil.MakeInternalAPI(\"PerformDirectoryLookupRequest\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformDirectoryLookupRequest\n\t\t\tvar response api.PerformDirectoryLookupResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := intAPI.PerformDirectoryLookup(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIPerformServersAlivePath,\n\t\thttputil.MakeInternalAPI(\"PerformServersAliveRequest\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformServersAliveRequest\n\t\t\tvar response api.PerformServersAliveResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := intAPI.PerformServersAlive(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIPerformBroadcastEDUPath,\n\t\thttputil.MakeInternalAPI(\"PerformBroadcastEDU\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformBroadcastEDURequest\n\t\t\tvar response api.PerformBroadcastEDUResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := intAPI.PerformBroadcastEDU(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIGetUserDevicesPath,\n\t\thttputil.MakeInternalAPI(\"GetUserDevices\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request getUserDevices\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.GetUserDevices(req.Context(), request.S, request.UserID)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = &res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIClaimKeysPath,\n\t\thttputil.MakeInternalAPI(\"ClaimKeys\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request claimKeys\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.ClaimKeys(req.Context(), request.S, request.OneTimeKeys)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = &res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIQueryKeysPath,\n\t\thttputil.MakeInternalAPI(\"QueryKeys\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request queryKeys\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.QueryKeys(req.Context(), request.S, request.Keys)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = &res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIBackfillPath,\n\t\thttputil.MakeInternalAPI(\"Backfill\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request backfill\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.Backfill(req.Context(), request.S, request.RoomID, request.Limit, request.EventIDs)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = &res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPILookupStatePath,\n\t\thttputil.MakeInternalAPI(\"LookupState\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request lookupState\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.LookupState(req.Context(), request.S, request.RoomID, request.EventID, request.RoomVersion)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = &res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPILookupStateIDsPath,\n\t\thttputil.MakeInternalAPI(\"LookupStateIDs\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request lookupStateIDs\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.LookupStateIDs(req.Context(), request.S, request.RoomID, request.EventID)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = &res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPILookupMissingEventsPath,\n\t\thttputil.MakeInternalAPI(\"LookupMissingEvents\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request lookupMissingEvents\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.LookupMissingEvents(req.Context(), request.S, request.RoomID, request.Missing, request.RoomVersion)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, event := range res.Events {\n\t\t\t\tjs, err := json.Marshal(event)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn util.MessageResponse(http.StatusInternalServerError, err.Error())\n\t\t\t\t}\n\t\t\t\trequest.Res.Events = append(request.Res.Events, js)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIGetEventPath,\n\t\thttputil.MakeInternalAPI(\"GetEvent\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request getEvent\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.GetEvent(req.Context(), request.S, request.EventID)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = &res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIGetEventAuthPath,\n\t\thttputil.MakeInternalAPI(\"GetEventAuth\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request getEventAuth\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.GetEventAuth(req.Context(), request.S, request.RoomVersion, request.RoomID, request.EventID)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = &res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIQueryServerKeysPath,\n\t\thttputil.MakeInternalAPI(\"QueryServerKeys\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryServerKeysRequest\n\t\t\tvar response api.QueryServerKeysResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := intAPI.QueryServerKeys(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPILookupServerKeysPath,\n\t\thttputil.MakeInternalAPI(\"LookupServerKeys\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request lookupServerKeys\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.LookupServerKeys(req.Context(), request.S, request.KeyRequests)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.ServerKeys = res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIEventRelationshipsPath,\n\t\thttputil.MakeInternalAPI(\"MSC2836EventRelationships\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request eventRelationships\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.MSC2836EventRelationships(req.Context(), request.S, request.Req, request.RoomVer)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPISpacesSummaryPath,\n\t\thttputil.MakeInternalAPI(\"MSC2946SpacesSummary\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request spacesReq\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.MSC2946Spaces(req.Context(), request.S, request.RoomID, request.SuggestedOnly)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(FederationAPIQueryPublicKeyPath,\n\t\thttputil.MakeInternalAPI(\"queryPublicKeys\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.QueryPublicKeysRequest{}\n\t\t\tresponse := api.QueryPublicKeysResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tkeys, err := intAPI.FetchKeys(req.Context(), request.Requests)\n\t\t\tif err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tresponse.Results = keys\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(FederationAPIInputPublicKeyPath,\n\t\thttputil.MakeInternalAPI(\"inputPublicKeys\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.InputPublicKeysRequest{}\n\t\t\tresponse := api.InputPublicKeysResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := intAPI.StoreKeys(req.Context(), request.Keys); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n}",
"func AddRoute(endpoints []HNSEndpoint, destinationPrefix string, nextHop string, encapEnabled bool) (*PolicyList, error) {\n\treturn hns.AddRoute(endpoints, destinationPrefix, nextHop, encapEnabled)\n}",
"func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, storeName string) {\n\n\tif svrConfig.ApiSecurityLevel == svrConfig.ValueSecurityLevel_Low {\n\t\tr.HandleFunc(fmt.Sprintf(\"/%s/send\", storeName), SendTxRequestHandlerFn(cdc, cliCtx)).Methods(\"POST\")\n\t\tr.HandleFunc(fmt.Sprintf(\"/%s/create\", storeName), CreateTxRequestHandlerFn(cdc, cliCtx)).Methods(\"POST\")\n\t\tr.HandleFunc(fmt.Sprintf(\"/%s/sign\", storeName), SignTxRawRequestHandlerFn(cdc, cliCtx)).Methods(\"POST\")\n\t}\n\tr.HandleFunc(fmt.Sprintf(\"/%s/broadcast\", storeName), BroadcastTxRawRequestHandlerFn(cdc, cliCtx)).Methods(\"POST\")\n\t//\n\tr.HandleFunc(\n\t\tfmt.Sprintf(\"/%s/contract/{address}/{code}\", storeName),\n\t\tQueryContractRequestHandlerFn(storeName, cdc, context.GetAccountDecoder(cdc), cliCtx),\n\t).Methods(\"GET\")\n}",
"func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, storePoolData string) {\n\tr.HandleFunc(fmt.Sprintf(\"/%s/pools\", storePoolData), poolHandler(cdc, cliCtx, storePoolData)).Methods(\"GET\")\n\tr.HandleFunc(fmt.Sprintf(\"/%s/account/{%s}\", storePoolData, accData), accHandler(cdc, cliCtx, storePoolData)).Methods(\"GET\")\n\tr.HandleFunc(fmt.Sprintf(\"/%s/stake/{%s}\", storePoolData, stakeData), stakeHandler(cdc, cliCtx, storePoolData)).Methods(\"GET\")\n\tr.HandleFunc(fmt.Sprintf(\"/%s/stake\", storePoolData), setStakeDataHandler(cdc, cliCtx)).Methods(\"PUT\")\n}",
"func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, storeData string) {\n\tr.HandleFunc(fmt.Sprintf(\"/%s/key\", storeData), postKeyValueHandler(cliCtx)).Methods(\"POST\")\n\tr.HandleFunc(fmt.Sprintf(\"/%s/key/{%s}\", storeData, restKey), getKeyValueHandler(cliCtx, storeData)).Methods(\"GET\")\n\tr.HandleFunc(fmt.Sprintf(\"/%s/signTx\", storeData), postSignHandler( cliCtx)).Methods(\"POST\")\n\tr.HandleFunc(fmt.Sprintf(\"/Acc\"), postAddHandler( cliCtx)).Methods(\"POST\")\n\tr.HandleFunc(fmt.Sprintf(\"/ConPub\"), postConPubHandler( cliCtx)).Methods(\"POST\")\n\t\n}",
"func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) {\n\tr.HandleFunc(\"/billboard/advertisement\", listAdvertisementHandler(cliCtx, \"billboard\")).Methods(\"GET\")\n\tr.HandleFunc(\"/billboard/advertisement/{key}\", getAdvertisementHandler(cliCtx, \"billboard\")).Methods(\"GET\")\n\n}",
"func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, storeName string) {\n\t// tx\n\tr.HandleFunc(fmt.Sprintf(\"/%s/set_data\", storeName), setDataHandler(cliCtx)).Methods(\"PUT\")\n\n\t// query\n\tr.HandleFunc(fmt.Sprintf(\"/%s/addrs\", storeName), addrsHandler(cliCtx, storeName)).Methods(\"GET\")\n\tr.HandleFunc(fmt.Sprintf(\"/%s/all_data\", storeName), allDataHandler(cliCtx, storeName)).Methods(\"GET\")\n\tr.HandleFunc(fmt.Sprintf(\"/%s/range_data\", storeName), rangeDataHandler(cliCtx, storeName)).Methods(\"GET\")\n}",
"func (s *Service) RegisterRoutes(router *mux.Router, prefix string) {\n\tsubRouter := router.PathPrefix(prefix).Subrouter()\n\troutes.AddRoutes(s.GetRoutes(), subRouter)\n}",
"func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, storeName string) {\n\tr.HandleFunc(\n\t\t\"/assets/coins/{account}\",\n\t\tgetCoinsHandlerFn(cliCtx),\n\t).Methods(\"GET\")\n\tr.HandleFunc(\n\t\t\"/assets/coin_powers/{account}\",\n\t\tgetCoinPowersHandlerFn(cliCtx),\n\t).Methods(\"GET\")\n\tr.HandleFunc(\n\t\t\"/assets/coins_locked/{account}\",\n\t\tgetCoinsLockedHandlerFn(cliCtx),\n\t).Methods(\"GET\")\n\tr.HandleFunc(\n\t\t\"/assets/coin_stat/{creator}/{symbol}\",\n\t\tgetCoinStatHandlerFn(cliCtx),\n\t).Methods(\"GET\")\n\n\tr.HandleFunc(\n\t\t\"/assets/transfer\",\n\t\tTransferRequestHandlerFn(cliCtx),\n\t).Methods(\"POST\")\n\tr.HandleFunc(\n\t\t\"/assets/create\",\n\t\tCreateRequestHandlerFn(cliCtx),\n\t).Methods(\"POST\")\n\tr.HandleFunc(\n\t\t\"/assets/issue\",\n\t\tIssueRequestHandlerFn(cliCtx),\n\t).Methods(\"POST\")\n\tr.HandleFunc(\n\t\t\"/assets/burn\",\n\t\tBurnRequestHandlerFn(cliCtx),\n\t)\n\tr.HandleFunc(\n\t\t\"/assets/lock\",\n\t\tLockRequestHandlerFn(cliCtx),\n\t).Methods(\"POST\")\n\tr.HandleFunc(\n\t\t\"/assets/unlock\",\n\t\tUnlockRequestHandlerFn(cliCtx),\n\t).Methods(\"POST\")\n\tr.HandleFunc(\n\t\t\"/assets/exercise\",\n\t\tExerciseRequestHandlerFn(cliCtx),\n\t).Methods(\"POST\")\n}",
"func (rtr *msRouter) AddRoute(path string, h MsHandler) MsRouter {\n\tif rtr.sealed {\n\t\tpanic(\"router sealed; cannot add route handler\")\n\t}\n\tif !isAlphaNumeric(path) {\n\t\tpanic(\"route expressions can only contain alphanumeric characters\")\n\t}\n\tif rtr.HasRoute(path) {\n\t\tpanic(fmt.Sprintf(\"route %s has already been initialized\", path))\n\t}\n\n\trtr.routes[path] = h\n\n\treturn rtr\n}",
"func RegisterRoutes(e *echo.Echo) {\n\tfor _, route := range router.List() {\n\t\tutil.CallFuncByName(e, route.Method, route.Path, route.Controller)\n\t}\n}",
"func (r *Router) AddRoute(method string, path string, callback http.HandlerFunc) (err error) {\n\tkeys := setupKeys(strings.Split(path, \"/\"))\n\tpathParams := []string{}\n\n\tif r.root == nil {\n\t\tr.root = &segment{}\n\t\tr.root.children = map[string]*segment{}\n\t\tr.root.endpoints = map[string]*endpoint{}\n\t}\n\n\tcurr := r.root\n\n\tfor i, key := range keys {\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif isParameter(key) {\n\t\t\tpathParams = append(pathParams, key[2:])\n\n\t\t}\n\n\t\tif child, _ := getChild(key, curr); child == nil {\n\t\t\tseg := addSegment(curr, key)\n\t\t\tcurr = seg\n\t\t} else {\n\t\t\tcurr = child\n\t\t}\n\t}\n\n\tif _, ok := curr.endpoints[method]; ok {\n\t\terr = errors.New(\"path already exists\")\n\n\t\treturn\n\t}\n\n\tcurr.endpoints[method] = &endpoint{callback, path, pathParams}\n\tr.routes = append(r.routes, route{callback, method, path})\n\n\treturn\n}",
"func (r *Route) RegisterRoutes() {\n\n\tr.router.GET(\"/categories\", r.ctrl.handleGetCategories)\n\tr.router.GET(\"/category/:id\", r.ctrl.handleGetCategoryByID)\n\tr.router.POST(\"/category\", r.ctrl.handleCreateCategory)\n\tr.router.PUT(\"/category/:id\", r.ctrl.handleUpdateCategory)\n\tr.router.DELETE(\"/category/:id\", r.ctrl.handleDeleteCategory)\n\n}",
"func RegisterRoutes(r weave.Registry, auth x.Authenticator,\n\tcontrol Controller) {\n\n\tr.Handle(pathUpdate, NewUpdateHandler(auth, control, authCheckAddress))\n}",
"func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) {\n\t// this line is used by starport scaffolding # 1\n\tr.HandleFunc(\"/nym/gateway\", createGatewayHandler(cliCtx)).Methods(\"POST\")\n\tr.HandleFunc(\"/nym/gateway\", listGatewayHandler(cliCtx, \"nym\")).Methods(\"GET\")\n\tr.HandleFunc(\"/nym/gateway/{key}\", getGatewayHandler(cliCtx, \"nym\")).Methods(\"GET\")\n\tr.HandleFunc(\"/nym/gateway\", setGatewayHandler(cliCtx)).Methods(\"PUT\")\n\tr.HandleFunc(\"/nym/gateway\", deleteGatewayHandler(cliCtx)).Methods(\"DELETE\")\n\n\tr.HandleFunc(\"/nym/mixnode\", createMixnodeHandler(cliCtx)).Methods(\"POST\")\n\tr.HandleFunc(\"/nym/mixnode\", listMixnodeHandler(cliCtx, \"nym\")).Methods(\"GET\")\n\tr.HandleFunc(\"/nym/mixnode/{key}\", getMixnodeHandler(cliCtx, \"nym\")).Methods(\"GET\")\n\tr.HandleFunc(\"/nym/mixnode\", setMixnodeHandler(cliCtx)).Methods(\"PUT\")\n\tr.HandleFunc(\"/nym/mixnode\", deleteMixnodeHandler(cliCtx)).Methods(\"DELETE\")\n\n}",
"func (m *Mux) AddRoute(method, path string, h Handler) {\n\tmethod = strings.ToUpper(method)\n\tm.tree[method+path] = h\n}",
"func (s *Service) RegisterRoutes(router *mux.Router, prefix string) {\n\tsubRouter := router.PathPrefix(prefix).Subrouter()\n\taddRoutes(s.GetRoutes(), subRouter)\n}",
"func (r apiV1Router) RegisterRoutes(routerGroup *gin.RouterGroup) {\n\trouterGroup.GET(\"/\", r.Heartbeat)\n\n\tshopsGroup := routerGroup.Group(\"/shops\")\n\tshopsGroup.GET(\"/\", r.GetAllShops)\n\tshopsGroup.GET(\"/nearby\", r.GetNearbyShops)\n\n\titemGroupsGroup := routerGroup.Group(\"/itemgroups\")\n\titemGroupsGroup.GET(\"/\", r.GetItemGroups)\n}",
"func (h *RouteMux) addRoute(r *route) {\n\t//and finally append to the list of Routes\n\t//create the Route\n\th.routes = append(h.routes, r)\n}",
"func AddApproutes(route *mux.Router) {\r\n\r\n\tlog.Println(\"Loadeding Routes...\")\r\n\r\n\troute.HandleFunc(\"/\", RenderHome)\r\n\r\n\troute.HandleFunc(\"/login\", RenderLogin)\r\n\r\n\troute.HandleFunc(\"/register\", RenderRegister)\r\n\r\n\troute.HandleFunc(\"/signin\", SignInUser).Methods(\"POST\")\r\n\r\n\troute.HandleFunc(\"/signup\", SignUpUser).Methods(\"POST\")\r\n\r\n\troute.HandleFunc(\"/userDetails\", GetUserDetails).Methods(\"GET\")\r\n\r\n\tlog.Println(\"Routes are Loaded.\")\r\n}",
"func (mux *Mux) Add(m Router, h Handler) {\n\tmux.Route(&Route{\n\t\tHandler: h,\n\t\tRouter: m,\n\t})\n}",
"func (s *server) RegisterRoutes(ws *web.Server) {\n\tfor _, subsystem := range s.handlers {\n\t\tif subsystem, ok := subsystem.(web.Registerer); ok {\n\t\t\tsubsystem.RegisterRoutes(ws)\n\t\t}\n\t}\n}",
"func RegisterRoutes(r weave.Registry, auth x.Authenticator) {\n\tblogs := NewBlogBucket()\n\tr.Handle(PathCreateBlogMsg, CreateBlogMsgHandler{auth, blogs})\n\tr.Handle(PathCreatePostMsg, CreatePostMsgHandler{auth, NewPostBucket(), blogs})\n\tr.Handle(PathRenameBlogMsg, RenameBlogMsgHandler{auth, blogs})\n\tr.Handle(PathChangeBlogAuthorsMsg, ChangeBlogAuthorsMsgHandler{auth, blogs})\n\tr.Handle(PathSetProfileMsg, SetProfileMsgHandler{auth, NewProfileBucket()})\n}",
"func (rtr *router) AddRoute(path string, h Handler) Router {\n\tif rtr.sealed {\n\t\tpanic(fmt.Sprintf(\"router sealed; cannot register %s route handler\", path))\n\t}\n\tif !sdk.IsAlphaNumeric(path) {\n\t\tpanic(\"route expressions can only contain alphanumeric characters\")\n\t}\n\tif rtr.HasRoute(path) {\n\t\tpanic(fmt.Sprintf(\"route %s has already been registered\", path))\n\t}\n\n\trtr.routes[path] = h\n\treturn rtr\n}",
"func (myAPI API) CreateRoutes(route ...api.Route) {\n\tfor _, myRoute := range route {\n\t\tif len(myRoute.Methods) > 0 {\n\t\t\tmyAPI.router.HandleFunc(myRoute.Path, myRoute.Handler).Methods(myRoute.Methods...)\n\t\t} else {\n\t\t\tmyAPI.router.HandleFunc(myRoute.Path, myRoute.Handler)\n\t\t}\n\t}\n}",
"func (r *Router) AddRoutes(apiGroup string, routes []*Route) {\n\tklog.V(3).Infof(\"load apiGroup:%s\", apiGroup)\n\tfor _, route := range routes {\n\t\tswitch route.Method {\n\t\tcase \"GET\":\n\t\t\tr.GET(route.Path, route.Handler)\n\t\tcase \"POST\":\n\t\t\tr.POST(route.Path, route.Handler)\n\t\tcase \"DELETE\":\n\t\t\tr.DELETE(route.Path, route.Handler)\n\t\tcase \"Any\":\n\t\t\tr.Any(route.Path, route.Handler)\n\t\tdefault:\n\t\t\tklog.Warningf(\"no method:%s apiGroup:%s\", route.Method, apiGroup)\n\t\t}\n\t}\n\n\tif _, ok := r.Routes[apiGroup]; !ok {\n\t\tr.Routes[apiGroup] = routes\n\t}\n\n\tif apiGroup == \"health\" {\n\t\tr.AddProfile(\"GET\", LivePath, `liveness check: <br/>\n\t\t\t<a href=\"/live?full=true\"> query the full body`)\n\t\tr.AddProfile(\"GET\", ReadyPath, `readyness check: <br/>\n\t\t\t<a href=\"/ready?full=true\"> query the full body`)\n\t\tr.AddProfile(\"GET\", VersionPath, `version describe: <br/>\n <a href=\"/version\"> query version info`)\n\t} else if apiGroup == \"cluster\" {\n\t\tfor _, route := range routes {\n\t\t\tvar desc string\n\t\t\tif route.Desc == \"\" {\n\t\t\t\tdesc = fmt.Sprintf(\"name: the unique cluster name and all <br/> appName: the unique app name\")\n\t\t\t} else {\n\t\t\t\tdesc = route.Desc\n\t\t\t}\n\t\t\tr.AddProfile(route.Method, route.Path, desc)\n\t\t}\n\t}\n}",
"func (m *RouteMux) AddRoute(method string, pattern string, handler http.HandlerFunc) {\n\n\t//split the url into sections\n\tparts := strings.Split(pattern, \"/\")\n\n\t//find params that start with \":\"\n\t//replace with regular expressions\n\tj := 0\n\tparams := make(map[int]string)\n\tfor i, part := range parts {\n\t\tif strings.HasPrefix(part, \":\") {\n\t\t\texpr := \"([^/]+)\"\n\t\t\t//a user may choose to override the defult expression\n\t\t\t// similar to expressjs: ‘/user/:id([0-9]+)’ \n\t\t\tif index := strings.Index(part, \"(\"); index != -1 {\n\t\t\t\texpr = part[index:]\n\t\t\t\tpart = part[:index]\n\t\t\t}\n\t\t\tparams[j] = part\n\t\t\tparts[i] = expr\n\t\t\tj++\n\t\t}\n\t}\n\n\t//recreate the url pattern, with parameters replaced\n\t//by regular expressions. then compile the regex\n\tpattern = strings.Join(parts, \"/\")\n\tregex, regexErr := regexp.Compile(pattern)\n\tif regexErr != nil {\n\t\t//TODO add error handling here to avoid panic\n\t\tpanic(regexErr)\n\t\treturn\n\t}\n\n\t//now create the Route\n\troute := &route{}\n\troute.method = method\n\troute.regex = regex\n\troute.handler = handler\n\troute.params = params\n\n\t//and finally append to the list of Routes\n\tm.routes = append(m.routes, route)\n}",
"func SetRoutes(r *mux.Router) {\n\tr.HandleFunc(\"\", Add).Methods(\"POST\")\n\tr.HandleFunc(\"\", GetAll).Methods(\"GET\")\n\tr.HandleFunc(\"/names/{name}\", FindByName).Methods(\"GET\")\n\tr.HandleFunc(\"/{id}\", FindByID).Methods(\"GET\")\n\tr.HandleFunc(\"/{id}\", DeleteByID).Methods(\"DELETE\")\n\tr.HandleFunc(\"/{id}\", UpdateByID).Methods(\"PUT\")\n}",
"func (s *DeviceService) AddRoute(route string, handler func(http.ResponseWriter, *http.Request), methods ...string) error {\n\treturn s.controller.AddRoute(route, handler, methods...)\n}",
"func (rs *routeServer) addRoutesHandler(w http.ResponseWriter, req *http.Request) {\n\tlog.Printf(\"Adding routes at %s\\n\", req.URL.Path)\n\n\tloc := mux.Vars(req)[\"location\"]\n\n\tmediatype, _, err := mime.ParseMediaType(req.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tif mediatype != \"application/json\" {\n\t\thttp.Error(w, \"requires application/json Content-Type\", http.StatusUnsupportedMediaType)\n\t\treturn\n\t}\n\n\tdec := json.NewDecoder(req.Body)\n\tvar routes map[string]float64\n\tif err := dec.Decode(&routes); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif rs.store.AddRoutes(loc, routes) != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n}",
"func (s *Server) AddRoute(handler *common.HTTPHandler, lock *sync.RWMutex, base, endpoint string, log logging.Logger) error {\n\turl := fmt.Sprintf(\"%s/%s\", baseURL, base)\n\ts.log.Info(\"adding route %s%s\", url, endpoint)\n\t// Apply logging middleware\n\th := handlers.CombinedLoggingHandler(log, handler.Handler)\n\t// Apply middleware to grab/release chain's lock before/after calling API method\n\th, err := lockMiddleware(h, handler.LockOptions, lock)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.router.AddRouter(url, endpoint, h)\n}",
"func (c *Client) AddRoutes(podCIDR *net.IPNet, nodeIP, nodeGwIP net.IP) error {\n\tpodCIDRStr := podCIDR.String()\n\t// Add this podCIDR to antreaPodIPSet so that packets to them won't be masqueraded when they leave the host.\n\tif err := ipset.AddEntry(antreaPodIPSet, podCIDRStr); err != nil {\n\t\treturn err\n\t}\n\n\t// Install routes to this Node.\n\troutes := []*netlink.Route{\n\t\t{\n\t\t\tDst: podCIDR,\n\t\t\tFlags: int(netlink.FLAG_ONLINK),\n\t\t\tLinkIndex: c.nodeConfig.GatewayConfig.LinkIndex,\n\t\t\tGw: nodeGwIP,\n\t\t\tTable: c.serviceRtTable.Idx,\n\t\t},\n\t}\n\n\t// If service route table and main route table is not the same , add\n\t// peer CIDR to main route table too (i.e in NoEncap and hybrid mode)\n\tif !c.serviceRtTable.IsMainTable() {\n\t\tif c.encapMode.NeedsEncapToPeer(nodeIP, c.nodeConfig.NodeIPAddr) {\n\t\t\t// need overlay tunnel\n\t\t\troutes = append(routes, &netlink.Route{\n\t\t\t\tDst: podCIDR,\n\t\t\t\tFlags: int(netlink.FLAG_ONLINK),\n\t\t\t\tLinkIndex: c.nodeConfig.GatewayConfig.LinkIndex,\n\t\t\t\tGw: nodeGwIP,\n\t\t\t})\n\t\t} else if !c.encapMode.NeedsRoutingToPeer(nodeIP, c.nodeConfig.NodeIPAddr) {\n\t\t\troutes = append(routes, &netlink.Route{\n\t\t\t\tDst: podCIDR,\n\t\t\t\tGw: nodeIP,\n\t\t\t})\n\t\t}\n\t\t// If Pod traffic needs underlying routing support, it is handled by host default route.\n\t}\n\n\t// clean up function if any route add failed\n\tdeleteRtFn := func() {\n\t\tfor _, route := range routes {\n\t\t\t_ = netlink.RouteDel(route)\n\t\t}\n\t}\n\n\tfor _, route := range routes {\n\t\tif err := netlink.RouteReplace(route); err != nil {\n\t\t\tdeleteRtFn()\n\t\t\treturn fmt.Errorf(\"failed to install route to peer %s with netlink: %v\", nodeIP, err)\n\t\t}\n\t}\n\tc.nodeRoutes.Store(podCIDRStr, routes)\n\treturn nil\n}",
"func (e *Server) AddRoute(r Route, opts ...RouteOption) {\n\te.AddRoutes([]Route{r}, opts...)\n}",
"func (g *Group) Add(method, path string, handler Handler, middleware ...Middleware) *Group {\n\tm := make([]Middleware, len(g.middleware)+len(middleware))\n\tcopy(m, g.middleware)\n\tcopy(m[len(g.middleware):], middleware)\n\n\tg.routes = append(g.routes, route{\n\t\tmethod: method,\n\t\tpath: g.relativePath(path),\n\t\thandler: handler,\n\t\tmiddleware: m,\n\t})\n\n\treturn g\n}",
"func (e *Endpoint) RegisterRoutes(g *echo.Group) {\n\tg.GET(\"/health\", e.Check)\n}",
"func (plugin *RouteConfigurator) ConfigureRoutes(config *l3.StaticRoutes) (wasError error) {\n\troutes := plugin.protoRoutesToStruct(config)\n\n\tfor i := range routes {\n\t\terr := plugin.vppAddRoute(routes[i])\n\t\tif err != nil {\n\t\t\twasError = err\n\t\t}\n\t}\n\n\treturn wasError\n}",
"func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) {\r\n\tregisterQueryRoutes(cliCtx, r)\r\n\tregisterTxRoutes(cliCtx, r)\r\n}",
"func (s *HTTPService) RegisterRoutes(srv *server.Server) {\n\tbaseMW := router.NewMiddlewareChain()\n\tbaseAuthMW := baseMW.Extend(\n\t\tmiddleware.WithContextTimeout(time.Minute),\n\t\tauth.Authenticate(srv.CookieAuth),\n\t)\n\n\tsrv.Routes.GET(\"/raw-artifact/*artifactName\", baseAuthMW, handleError(s.buildRawArtifactHandler(\"/raw-artifact/\")))\n}",
"func (rb *routeBuilder) AddRoute(fn RouteFunc) *routeBuilder {\n\trb.routes = append(rb.routes, fn)\n\treturn rb\n}",
"func (srv *AppServer) SetupRoutes() error {\n\tvar err error\n\tsrv.routesSetup.Do(func() {\n\n\t\t// /status is something you should always have in any of your services,\n\t\t// please leave it as is.\n\t\tsrv.router.HandleFunc(\"/status\", srv.HandleStatus()).Queries(\"format\", \"{format:(?:json|yaml)}\").\n\t\t\tName(\"status\").\n\t\t\tMethods(\"GET\")\n\n\t\t// ADD YOUR OWN ROUTES HERE\n\t\tsrv.router.HandleFunc(\"/topology\", srv.HandleTopology()).\n\t\t\tName(\"topology\").\n\t\t\tMethods(\"GET\")\n\t})\n\treturn err\n}",
"func (r *Router) Add(method, path string, h Handler) {\n\tr.Router.Add(method, path, WrapHandler(h))\n}",
"func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) {\n\tregisterQueryRoutes(cliCtx, r)\n\tregisterTxRoutes(cliCtx, r)\n}",
"func (a *API) RegisterRoutes(r *mux.Router) {\n\tfor _, route := range []struct {\n\t\tname, method, path string\n\t\thandler http.HandlerFunc\n\t}{\n\t\t{\"get_config\", \"GET\", \"/api/v1/config\", a.getConfig},\n\t\t{\"set_config\", \"POST\", \"/api/v1/config\", a.setConfig},\n\t\t{\"deactivate_config\", \"DELETE\", \"/api/v1/config/deactivate\", a.deactivateConfig},\n\t\t{\"restore_config\", \"POST\", \"/api/v1/config/restore\", a.restoreConfig},\n\t} {\n\t\tr.Handle(route.path, route.handler).Methods(route.method).Name(route.name)\n\t}\n}",
"func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Codec, storeName string, kb keys.Keybase, kafka bool, kafkaState rest.KafkaState) {\n\tr.HandleFunc(\"/issue/fiat\", IssueFiatHandlerFunction(cliCtx, cdc, kb, kafka, kafkaState)).Methods(\"POST\")\n\tr.HandleFunc(\"/fiat/{pegHash}\", QueryFiatRequestHandlerFn(storeName, cdc, r, fiatcmd.GetFiatPegDecoder(cdc), cliCtx)).Methods(\"GET\")\n\tr.HandleFunc(\"/redeem/fiat\", RedeemFiatHandlerFunction(cliCtx, cdc, kb, kafka, kafkaState)).Methods(\"POST\")\n\tr.HandleFunc(\"/send/fiat\", SendFiatHandlerFunction(cliCtx, cdc, kb, kafka, kafkaState)).Methods(\"POST\")\n\tr.HandleFunc(\"/execute/fiat\", ExecuteFiatHandlerFunction(cliCtx, cdc, kb, kafka, kafkaState)).Methods(\"POST\")\n}",
"func RegisterRoutes(router *gin.RouterGroup, logger lumber.Logger) {\n\trouter.GET(\"/hello\", middleware.Authentication(), versionedHello)\n\trouter.GET(\"/getAccounts\", controller.GetAccounts)\n\tlogger.Infof(\"v1.0 routes injected\")\n}",
"func AddMonitoringRoutes(router *chi.Mux, monitoringHandler *handler.MonitoringHandler, logger *logger.Logger) {\n\n\trouter.Group(func(r chi.Router) {\n\t\tr.Use(middleware.Recoverer)\n\t\tr.Use(middleware.DefaultCompress)\n\t\tr.Use(middleware.Timeout(60 * time.Second))\n\t\tr.Use(render.SetContentType(render.ContentTypeJSON))\n\t\tr.Use(middleware.RequestLogger(&middleware.DefaultLogFormatter{Logger: logger}))\n\n\t\tr.Get(\"/health\", monitoringHandler.GetHealth)\n\t})\n\n}",
"func RegisterRoutes(ctx context.CLIContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase, storeName string) {\n\tr.HandleFunc(\"/assets\", createAssetHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/assets/{id}\", queryAssetRequestHandlerFn(ctx, storeName, cdc)).Methods(\"GET\")\n\tr.HandleFunc(\"/assets/{id}/owners/history\", queryHistoryOwnersHandlerFn(ctx, cdc)).Methods(\"GET\")\n\tr.HandleFunc(\"/assets/{id}/txs\", assetTxsHandlerFn(ctx, storeName, cdc)).Methods(\"GET\")\n\tr.HandleFunc(\"/assets/{id}/children\", queryAssetChildrensHandlerFn(ctx, storeName, cdc, kb)).Methods(\"GET\")\n\tr.HandleFunc(\"/assets/{id}/add\", addAssetQuantityHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/assets/{id}/subtract\", subtractQuantityBodyHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/assets/{id}/properties\", updateAttributeHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/assets/{id}/properties/{name}/history\", queryHistoryUpdatePropertiesHandlerFn(ctx, cdc)).Methods(\"GET\")\n\tr.HandleFunc(\"/assets/{id}/materials\", addMaterialsHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/assets/{id}/materials/history\", queryHistoryTransferMaterialsHandlerFn(ctx, cdc)).Methods(\"GET\")\n\tr.HandleFunc(\"/assets/{id}/finalize\", finalizeHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/assets/{id}/reporters/{address}/revoke\", revokeReporterHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/assets/{id}/proposals\", createProposalHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/assets/{id}/proposals\", queryProposalsHandlerFn(ctx, storeName, cdc, kb)).Methods(\"GET\")\n\tr.HandleFunc(\"/assets/{id}/proposals/{recipient}/answer\", answerProposalHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/accounts/{address}/assets\", queryAccountAssetsHandlerFn(ctx, storeName, cdc, kb)).Methods(\"GET\")\n\tr.HandleFunc(\"/accounts/{address}/proposals\", queryAccountProposalsHandlerFn(ctx, storeName, cdc, kb)).Methods(\"GET\")\n\tr.HandleFunc(\"/accounts/{address}/report-assets\", queryReporterAssetsHandlerFn(ctx, storeName, cdc, kb)).Methods(\"GET\")\n\n}",
"func (a *App) InitRoutes() {\n\ta.Router = mux.NewRouter()\n\n\tsrv := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &graph.Resolver{Service: a.Service}}))\n\ta.Router.Handle(\"/playground\", playground.Handler(\"GoNeo4jGql GraphQL playground\", \"/movies\"))\n\ta.Router.Handle(\"/movies\", srv)\n}",
"func AddRoute(e *echo.Group) {\n\tgroups := e.Group(\"/groups\")\n\n\t// Basic daemon request\n\tgroups.GET(\"\", getAllWithDaemons)\n\tgroups.POST(\"\", save)\n\tgroups.GET(fmt.Sprintf(\"/daemon/:%s\", types.DAEMON_ID_PARAM), getByDaemon, middleware.WithAdmin)\n\n\t{\n\t\tgroup := groups.Group(fmt.Sprintf(\"/:%s\", types.GROUP_ID_PARAM))\n\t\tgroup.Use(middleware.WithGroup)\n\n\t\tgroup.GET(\"\", getByID)\n\t\tgroup.DELETE(\"\", deleteByID, middleware.WithAdmin)\n\t\tgroup.POST(\"/updateuser/:username/:status\", updateUser)\n\n\t\t{\n\t\t\t// Compose requests\n\t\t\tcompose := group.Group(\"/compose\")\n\t\t\tcompose.POST(fmt.Sprintf(\"/create/:%s\", types.SUBSERVICE_ID_PARAM), createServiceGroup, middleware.WithGroupAdmin)\n\t\t\tcompose.GET(fmt.Sprintf(\"/status/:%s\", types.GROUPSERVICE_NAME_PARAM), getServiceGroupStatus)\n\t\t\tcompose.POST(fmt.Sprintf(\"/status/:%s\", types.GROUPSERVICE_NAME_PARAM), updateServiceGroupStatus)\n\t\t}\n\n\t\t{\n\t\t\tservices := group.Group(\"/services\")\n\t\t\tservices.POST(fmt.Sprintf(\"/:%s\", types.GROUPSERVICE_NAME_PARAM), saveGroupService, middleware.WithAdmin)\n\t\t\tservices.GET(fmt.Sprintf(\"/:%s/update\", types.GROUPSERVICE_NAME_PARAM), getGroupServiceUpdate, middleware.WithGroupAdmin)\n\t\t\tservices.POST(fmt.Sprintf(\"/:%s/update\", types.GROUPSERVICE_NAME_PARAM), updateGroupService, middleware.WithGroupAdmin)\n\t\t}\n\n\t\t{\n\t\t\t// Docker requests\n\t\t\tdocker := group.Group(\"/docker/containers\")\n\t\t\tdocker.GET(\"\", getContainers)\n\t\t\tdocker.POST(\"\", saveContainers)\n\t\t\tdocker.GET(\"/transform\", transformServices)\n\t\t}\n\n\t\t{\n\t\t\t// CAdvisor requests\n\t\t\tcadvisor := group.Group(\"/cadvisor\")\n\t\t\tcadvisor.GET(\"\", getCAdvisorInfo)\n\t\t}\n\t}\n}",
"func (m *Mux) Add(pattern string, handler HandlerFunc) Route {\n\troute, err := NewRoute(pattern, handler)\n\tif err != nil {\n\t\t// errors should be rare, but log them to stdout for debug\n\t\tprintln(\"mux: error parsing route:%s\", pattern)\n\t}\n\n\tm.routes = append(m.routes, route)\n\treturn route\n}",
"func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) {\n // this line is used by starport scaffolding # 1\n\t\tr.HandleFunc(\"/policingnetworkcosmos/judgement\", createJudgementHandler(cliCtx)).Methods(\"POST\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/judgement\", listJudgementHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/judgement/{key}\", getJudgementHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/judgement\", setJudgementHandler(cliCtx)).Methods(\"PUT\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/judgement\", deleteJudgementHandler(cliCtx)).Methods(\"DELETE\")\n\n\t\t\n\t\tr.HandleFunc(\"/policingnetworkcosmos/chargesheet\", createChargesheetHandler(cliCtx)).Methods(\"POST\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/chargesheet\", listChargesheetHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/chargesheet/{key}\", getChargesheetHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/chargesheet\", setChargesheetHandler(cliCtx)).Methods(\"PUT\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/chargesheet\", deleteChargesheetHandler(cliCtx)).Methods(\"DELETE\")\n\n\t\t\n\t\tr.HandleFunc(\"/policingnetworkcosmos/evidence\", createEvidenceHandler(cliCtx)).Methods(\"POST\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/evidence\", listEvidenceHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/evidence/{key}\", getEvidenceHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/evidence\", setEvidenceHandler(cliCtx)).Methods(\"PUT\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/evidence\", deleteEvidenceHandler(cliCtx)).Methods(\"DELETE\")\n\n\t\t\n\t\tr.HandleFunc(\"/policingnetworkcosmos/investigation\", createInvestigationHandler(cliCtx)).Methods(\"POST\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/investigation\", listInvestigationHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/investigation/{key}\", getInvestigationHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/investigation\", setInvestigationHandler(cliCtx)).Methods(\"PUT\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/investigation\", deleteInvestigationHandler(cliCtx)).Methods(\"DELETE\")\n\n\t\t\n\t\tr.HandleFunc(\"/policingnetworkcosmos/fir\", createFirHandler(cliCtx)).Methods(\"POST\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/fir\", listFirHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/fir/{key}\", getFirHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/fir\", setFirHandler(cliCtx)).Methods(\"PUT\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/fir\", deleteFirHandler(cliCtx)).Methods(\"DELETE\")\n\n\t\t\n\t\tr.HandleFunc(\"/policingnetworkcosmos/profile\", createProfileHandler(cliCtx)).Methods(\"POST\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/profile\", listProfileHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/profile/{key}\", getProfileHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/profile\", setProfileHandler(cliCtx)).Methods(\"PUT\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/profile\", deleteProfileHandler(cliCtx)).Methods(\"DELETE\")\n\n\t\t\n}",
"func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) {\r\n\t// this line is used by starport scaffolding\r\n\tr.HandleFunc(\"/voter/poll\", ListPollHandler(cliCtx, \"voter\")).Methods(\"GET\")\r\n\tr.HandleFunc(\"/voter/poll\", createPollHandler(cliCtx)).Methods(\"POST\")\r\n}",
"func (r *ItemRouter) RegisterRoutes() {\n\tr.router.HandleFunc(\"/item\", r.ctrl.handleCreate).Methods(http.MethodPost)\n\tr.router.HandleFunc(\"/item/{item_id}\", r.ctrl.handleGetByID).Methods(http.MethodGet)\n\n\tr.router.HandleFunc(\"/item/search\", r.ctrl.handleSearch).Methods(http.MethodPost)\n}",
"func (router *Router) AddRoute(route *routers.Route) error {\n\tmethod := route.Method\n\tif method == \"\" {\n\t\treturn errors.New(\"route is missing method\")\n\t}\n\tmethod = strings.ToUpper(method)\n\tpath := route.Path\n\tif path == \"\" {\n\t\treturn errors.New(\"route is missing path\")\n\t}\n\treturn router.node().Add(method+\" \"+path, router, nil)\n}",
"func (c *Controller) RegisterRoutes(router gin.IRouter) {\n\tauthorized := router.Use(middleware.RequiredAccessToken())\n\t{\n\t\tauthorized.POST(\"api/todos\", c.AddTodo)\n\t\tauthorized.GET(\"api/todos\", c.Todos)\n\t\tauthorized.DELETE(\"api/todos/:todo_id\", c.RemoveTodoByTodoID)\n\t}\n}",
"func (record *RouteRecord) AddRouter(router Router) {\n\trecord.Path = append(record.Path, router)\n}",
"func InitRoutes() *mux.Router {\n\trouter := mux.NewRouter()\n\trouter = SetFinancialTransationsRoutes(router)\n\trouter = SetLastPurchasesRoutes(router)\n\trouter = SetConsultedCPFRoutes(router)\n\treturn router\n}"
] | [
"0.7806086",
"0.77646935",
"0.7712947",
"0.7693626",
"0.75555754",
"0.754306",
"0.74934345",
"0.73942876",
"0.7368001",
"0.7342897",
"0.7211632",
"0.7062798",
"0.70559645",
"0.6891687",
"0.6837901",
"0.68338466",
"0.6792862",
"0.67765653",
"0.676611",
"0.67304075",
"0.67247146",
"0.6716149",
"0.6686801",
"0.6683039",
"0.6667514",
"0.666469",
"0.6663408",
"0.66539884",
"0.66325635",
"0.66275555",
"0.6612961",
"0.6610284",
"0.6584559",
"0.65770423",
"0.657536",
"0.65584826",
"0.6557696",
"0.65573585",
"0.65503526",
"0.6526767",
"0.65253055",
"0.6525183",
"0.6524696",
"0.6523823",
"0.6520699",
"0.6504079",
"0.6453549",
"0.6448697",
"0.64470816",
"0.6436169",
"0.64257807",
"0.6421938",
"0.6421448",
"0.6407032",
"0.64069945",
"0.6401752",
"0.6399819",
"0.6396505",
"0.63868093",
"0.63859075",
"0.63777286",
"0.6370838",
"0.6366421",
"0.635809",
"0.6355386",
"0.6353111",
"0.6347153",
"0.6340344",
"0.63293546",
"0.63197696",
"0.63145614",
"0.63085157",
"0.6304474",
"0.6304074",
"0.63036126",
"0.6299197",
"0.6286536",
"0.6273206",
"0.6269761",
"0.625464",
"0.62452674",
"0.62393606",
"0.62260944",
"0.62127805",
"0.62011707",
"0.6183513",
"0.61814356",
"0.61779845",
"0.61642236",
"0.61506754",
"0.6148674",
"0.6145407",
"0.613943",
"0.61156934",
"0.61145353",
"0.6105693",
"0.6098449",
"0.60980314",
"0.6097903",
"0.6091924"
] | 0.8018205 | 0 |
returns len of next chunk | func rkChunk(buf []byte) int {
var off uint64
var hash uint64
var b_n uint64
if b == 0 {
b = THE_PRIME
b_n = 1
for i := 0; i < (HASHLEN - 1); i++ {
b_n *= b
}
for i := uint64(0); i < 256; i++ {
saved[i] = i * b_n
}
}
for off = 0; off < HASHLEN && off < uint64(len(buf)); off++ {
hash = hash*b + uint64((buf[off]))
}
for off < uint64(len(buf)) {
hash = (hash-saved[buf[off-HASHLEN]])*b + uint64(buf[off])
off++
if (off >= MINCHUNK && ((hash % TARGETCHUNK) == 1)) || (off >= MAXCHUNK) {
return int(off)
}
}
return int(off)
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (reader *ProtocolReader) Len() int { return len(reader.buf) - reader.off }",
"func (w *writer) chunkCount(b []byte) int {\n\tlenB := len(b)\n\tif lenB <= w.chunkSize {\n\t\treturn 1\n\t}\n\n\treturn len(b)/w.chunkDataSize + 1\n}",
"func (r *Reader) Size() int64 { return int64(len(r.s)) }",
"func (reader *StunReader) Size() int64 { return reader.limit - reader.base }",
"func (v Chunk) Len() int {\n\treturn v.buf.Len()\n}",
"func (d *Decoder) Len() int { return d.buf.Len() }",
"func (c *Chunk) Len() int {\n\treturn len(c.data)\n}",
"func (s *Segment) Size() int64 {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tvar n int64 = 0\n\tfor i := range s.chunks {\n\t\tc := s.chunks[i]\n\t\tn += int64(len(*c))\n\t}\n\treturn n\n}",
"func (r *Reader) Len() int {\n\treturn int(r.size)\n}",
"func (b *Buffer) Len() int { return b.length }",
"func Len(s io.Seeker) (int64, error) {\n\tswitch s := s.(type) {\n\tcase sizer:\n\t\treturn s.Size(), nil\n\tcase lener:\n\t\treturn int64(s.Len()), nil\n\tcase stater:\n\t\tinfo, err := s.Stat()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\treturn info.Size(), nil\n\t}\n\ti, err := s.Seek(0, os.SEEK_CUR)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tj, err := s.Seek(0, os.SEEK_END)\n\tif err != nil {\n\t\treturn j, err\n\t}\n\t_, err = s.Seek(i, os.SEEK_SET)\n\treturn j, err\n}",
"func (b *Buffer) Len() (n int) {\n\tfor _, l := range b.lines {\n\t\tn += utf8.RuneCount(l.data)\n\t}\n\n\tif len(b.lines) > 1 {\n\t\tn += len(b.lines) - 1 // account for newlines\n\t}\n\n\treturn\n}",
"func calculateStreamContentLength(dataLen, chunkSize int64) int64 {\n\tif dataLen <= 0 {\n\t\treturn 0\n\t}\n\tchunksCount := int64(dataLen / chunkSize)\n\tremainingBytes := int64(dataLen % chunkSize)\n\tvar streamLen int64\n\tstreamLen += chunksCount * calculateSignedChunkLength(chunkSize)\n\tif remainingBytes > 0 {\n\t\tstreamLen += calculateSignedChunkLength(remainingBytes)\n\t}\n\tstreamLen += calculateSignedChunkLength(0)\n\treturn streamLen\n}",
"func (s *Stream) GetSize() uint { return s.cur_size }",
"func (r *Reader) Len() int {\n\tif r.i >= int64(len(r.s)) {\n\t\treturn 0\n\t}\n\treturn int(int64(len(r.s)) - r.i)\n}",
"func (rss *reedSolomonSplitter) ChunkSize() uint64 {\n\treturn uint64(rss.size)\n}",
"func (b *loopBuffer) Len() int {\n\tif b.looped {\n\t\treturn cap(b.buf)\n\t}\n\treturn b.off\n}",
"func (w *ByteWriter) Len() int { return len(w.buffer) }",
"func decodedLen(src []byte) (blockLen, headerLen int, err error) {\n\tv, n := binary.Uvarint(src)\n\tif n == 0 {\n\t\treturn 0, 0, ErrCorrupt\n\t}\n\n\tif uint64(int(v)) != v {\n\t\treturn 0, 0, errors.New(\"zappy: decoded block is too large\")\n\t}\n\n\treturn int(v), n, nil\n}",
"func (sb *SeekableBuffer) Len() int {\n\treturn len(sb.data)\n\n}",
"func (r *PrivateRR) len(off int, compression map[string]struct{}) int {\n\tl := r.Hdr.len(off, compression)\n\tl += r.Data.Len()\n\treturn l\n}",
"func (b *BitStream) Len() int {\n\treturn int(b.bitsWritten / 8)\n}",
"func NextLength(data []byte) (length int, rest []byte, err error) {\n\tswitch {\n\tcase len(data) == 0:\n\t\terr = io.EOF\n\n\tcase data[0] < 0x80:\n\t\tlength = int(data[0])\n\t\trest = data[1:]\n\n\tcase data[0] == 0x81:\n\t\tif len(data) < 2 {\n\t\t\terr = io.EOF\n\t\t} else {\n\t\t\tlength = int(data[1])\n\t\t\trest = data[2:]\n\t\t}\n\n\tcase data[0] == 0x82:\n\t\tif len(data) < 3 {\n\t\t\terr = io.EOF\n\t\t} else {\n\t\t\tlength = int(data[1])<<8 | int(data[2])\n\t\t\trest = data[3:]\n\t\t}\n\n\tdefault:\n\t\t// Only 1 & 2 byte lengths can be expected from smart cards\n\t\t// so don't support longer formats\n\t\terr = errors.Errorf(\"Length format 0x%x unsupported\", data[0])\n\t}\n\treturn\n}",
"func (r *Reader) len() (length uint64, err error) {\n\tfile := r.file\n\t// Note current position.\n\toffset, err := file.Seek(0, io.SeekCurrent)\n\tif err != nil {\n\t\terr = liberr.Wrap(err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\t_, err = file.Seek(offset, io.SeekStart)\n\t\tif err != nil {\n\t\t\terr = liberr.Wrap(err)\n\t\t}\n\t}()\n\t// Seek to beginning of the file.\n\t_, err = file.Seek(0, io.SeekStart)\n\tif err != nil {\n\t\terr = liberr.Wrap(err)\n\t\treturn\n\t}\n\t// Read length.\n\tb := make([]byte, 8)\n\t_, err = file.Read(b)\n\tif err != nil {\n\t\tif err != io.EOF {\n\t\t\terr = liberr.Wrap(err)\n\t\t} else {\n\t\t\terr = nil\n\t\t}\n\t\treturn\n\t}\n\n\tlength = binary.LittleEndian.Uint64(b)\n\n\treturn\n}",
"func (b *Buf) Len() int { return len(b.b) }",
"func (r *Reader) Len() int {\n\tif r.file_v0 != nil {\n\t\treturn r.file_v0.Len()\n\t}\n\treturn int(r.header.num)\n}",
"func (b *Buffer) Len() int {\n\treturn b.Width * b.Height\n}",
"func (r *Decoder) Len() int { x := r.Uint64(); v := int(x); assert(uint64(v) == x); return v }",
"func (s *Server) getSize(reader *bufio.Reader) (uint32, error) {\n\t// Reader would be empty until peek.\n\tif _, err := reader.Peek(1); err != nil {\n\t\treturn 0, err\n\t}\n\n\tbtsSize := make([]byte, 4)\n\n\t_, err := reader.Read(btsSize)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn binary.BigEndian.Uint32(btsSize), nil\n}",
"func Len(p uint8) int {\n\tm := int(1 << uint(p))\n\treturn hdrLen + bitbucket.Len(m, 6)\n}",
"func (e *Encoder) Len() int { return len(e.buf) }",
"func (r *Reader) Len() (length int) {\n\t// Lazy open.\n\terr := r.open()\n\tif err != nil {\n\t\treturn\n\t}\n\tn, _ := r.len()\n\tlength = int(n)\n\treturn\n}",
"func (rb *RingBuffer) Len() int {\n\trb.lock.RLock()\n\tdefer rb.lock.RUnlock()\n\tif n := len(rb.data); rb.seq < uint64(n) {\n\t\treturn int(rb.seq)\n\t} else {\n\t\treturn n\n\t}\n}",
"func (b *Buffer) Size() int { return b.size }",
"func (b *FixedBuffer) Len() int {\n\treturn b.w - b.r\n}",
"func (bs *BitStream) Len() int {\n\treturn bs.bitBuffer.Len()\n}",
"func (b *Buffer) size() int {\n\treturn len(b.data)\n}",
"func (f *IndexFile) Size() int64 { return int64(len(f.data)) }",
"func numChunks(size int64) int32 {\n\td := float64(size) / float64(1024*1024)\n\tn := int(math.Ceil(d))\n\treturn int32(n)\n}",
"func (chunk *ResultNodeListChunk) Size() int {\n\treturn len(chunk.nodes)\n}",
"func (v *SrsMp4Sample) size() uint32 {\n if v.handlerType == SrsMp4HandlerTypeSOUN {\n if v.codec == SrsAudioCodecIdAAC {\n return v.nbSample + 2\n }\n return v.nbSample + 1\n }\n if v.codec == SrsVideoCodecIdAVC {\n return v.nbSample + 5\n }\n return v.nbSample + 1\n}",
"func (s *Pool) Len() int { return int(atomic.LoadUint32(&s.avail)) }",
"func (f *OpenStreamReply) ByteCount() int {\n\treturn 4\n}",
"func (c *asciiChunk) writeNext() int {\n\tif c.wroteSoFar >= c.totalLength {\n\t\treturn 0\n\t}\n\tlast := min(c.totalLength-c.wroteSoFar, len(c.buf)-c.posInBuf)\n\tn, err := c.w.Write(c.buf[c.posInBuf:last])\n\tif err != nil {\n\t\tc.wroteSoFar = c.totalLength\n\t\treturn 0\n\t}\n\tc.wroteSoFar += n\n\tc.posInBuf = (c.posInBuf + n) % len(c.buf)\n\treturn n\n}",
"func (f *File) Size() (uint32, error) {\n\tif err := f.unlocker.Ensure(); err != nil {\n\t\treturn 0, err\n\t}\n\t// file chunks include an embedded length field at the start\n\tbinlength, _, err := f.t.client.Read(f.chunk, 0, 4)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn binary.LittleEndian.Uint32(binlength), nil\n}",
"func (c *Counter) Len() int {\n\treturn hdrLen + c.bits.Len()\n}",
"func length(s *Skiplist) int {\n\tcount := 0\n\n\tvar it Iterator\n\tit.Init(s)\n\n\tfor it.SeekToFirst(); it.Valid(); it.Next() {\n\t\tcount++\n\t}\n\n\treturn count\n}",
"func (ri *rawItemList) len() int { return len(ri.cumSize) }",
"func (bs endecBytes) Length() uint32 {\n\treturn uint32(len(bs))\n}",
"func (f *ReadRequest) ByteCount() int {\n\treturn 1 + 8 + 8\n}",
"func (v Binary) Len(width int) int {\n\tw := dataWidth(width)\n\tl := v.size / int64(w)\n\tif v.size%int64(w) > 0 {\n\t\tl++\n\t}\n\treturn int(l)\n}",
"func (q *chunkQueue) Size() uint32 {\n\tq.Lock()\n\tdefer q.Unlock()\n\tif q.snapshot == nil {\n\t\treturn 0\n\t}\n\treturn q.snapshot.Chunks\n}",
"func (b *Bytes) Len() int {\n\tif b.p != nil {\n\t\treturn len(*b.p)\n\t}\n\n\treturn 0\n}",
"func (s *Storage) GetChunkDataSize() int {\n\treturn int(s.header.ChunkSize) - chunkHeaderSize\n}",
"func (s *stream) read(b []byte) (int, error) {\n\ts.log(logTypeStream, \"Reading from stream %v requested len = %v current chunks=%v\", s.id, len(b), len(s.recv.chunks))\n\n\tread := 0\n\n\tfor len(b) > 0 {\n\t\tif len(s.recv.chunks) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tchunk := s.recv.chunks[0]\n\n\t\t// We have a gap.\n\t\tif chunk.offset > s.recv.offset {\n\t\t\tbreak\n\t\t}\n\n\t\t// Remove leading bytes\n\t\tremove := s.recv.offset - chunk.offset\n\t\tif remove > uint64(len(chunk.data)) {\n\t\t\t// Nothing left.\n\t\t\ts.recv.chunks = s.recv.chunks[1:]\n\t\t\tcontinue\n\t\t}\n\n\t\tchunk.offset += remove\n\t\tchunk.data = chunk.data[remove:]\n\n\t\t// Now figure out how much we can read\n\t\tn := copy(b, chunk.data)\n\t\tchunk.data = chunk.data[n:]\n\t\tchunk.offset += uint64(n)\n\t\ts.recv.offset += uint64(n)\n\t\tb = b[n:]\n\t\tread += n\n\n\t\t// This chunk is empty.\n\t\tif len(chunk.data) == 0 {\n\t\t\ts.recv.chunks = s.recv.chunks[1:]\n\t\t\tif chunk.last {\n\t\t\t\ts.closeRecv()\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we have read no data, say we would have blocked.\n\tif read == 0 {\n\t\tif s.recv.closed {\n\t\t\treturn 0, ErrorStreamIsClosed\n\t\t}\n\t\treturn 0, ErrorWouldBlock\n\t}\n\treturn read, nil\n}",
"func (batch *BatchEncoder) Len() int {\n\treturn batch.keyBuf.Len() + batch.valueBuf.Len() - 8\n}",
"func (h literalsHeader) size() int {\n\treturn int(h >> 60)\n}",
"func (r *Reader) Len() int64 {\n\treturn r.len\n}",
"func (s *Store) Len() int {\n\tcnt := 0\n\tdl := len(s.delim)\n\tfor i := range s.lines {\n\t\tcnt += s.lines[i].Len() + dl\n\t}\n\treturn cnt\n}",
"func (obj *chunk) SizeInBytes() uint {\n\treturn obj.sizeInBytes\n}",
"func TestCalculateNumberOfChunks(t *testing.T) {\n\tfor _, tc := range []struct{ len, chunks int64 }{\n\t\t{len: 1000, chunks: 1},\n\t\t{len: 5000, chunks: 3},\n\t\t{len: 10000, chunks: 4},\n\t\t{len: 100000, chunks: 26},\n\t\t{len: 1000000, chunks: 248},\n\t\t{len: 325839339210, chunks: 79550620 + 621490 + 4856 + 38 + 1},\n\t} {\n\t\tres := api.CalculateNumberOfChunks(tc.len, false)\n\t\tif res != tc.chunks {\n\t\t\tt.Fatalf(\"expected result for %d bytes to be %d got %d\", tc.len, tc.chunks, res)\n\t\t}\n\t}\n}",
"func (r *Record) Len() int {\n\treturn r.End() - r.Start()\n}",
"func (ll *LinkedList) getMeTrueSize() int {\n\tll.lock.RLock()\n\tdefer ll.lock.RUnlock()\n\n\tsize := 1\n\tlast := ll.head\n\tfor {\n\t\tif last == nil || last.next == nil {\n\t\t\tbreak\n\t\t}\n\t\tlast = last.next\n\t\tsize++\n\t}\n\n\treturn size\n}",
"func (f *Frame) Len() int64 {\n\treturn f.Nchars\n}",
"func readerLen(r io.Reader) (int, bool) {\n\t// Establish the interfaces\n\t// Not Size() as Size returns the size of the underlying data, but not how much you'll read.\n\ttype lener interface {\n\t\tLen() int\n\t}\n\ttype byteser interface {\n\t\tBytes() int\n\t}\n\n\t// Switch over the interfaces\n\tswitch r := r.(type) {\n\tcase lener:\n\t\treturn r.Len(), true\n\tcase byteser:\n\t\treturn r.Bytes(), true\n\t}\n\n\treturn 0, false\n}",
"func (b *bigchunk) Entries() int { return 0 }",
"func (u *ChunkUpload) incrementNumReceivedParts() {\n\tu.lock.Lock()\n\tdefer u.lock.Unlock()\n\n\tu.numReceivedParts++\n}",
"func seekerSize(seeker io.ReadSeeker) (int64, error) {\n\tcurrent, err := seeker.Seek(0, os.SEEK_CUR)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tend, err := seeker.Seek(0, os.SEEK_END)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tresumed, err := seeker.Seek(current, os.SEEK_SET)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif resumed != current {\n\t\treturn 0, fmt.Errorf(\"error returning seeker to original state, could not seek back to original location\")\n\t}\n\n\treturn end, nil\n}",
"func (cp *ConnectPacket) Len() int {\r\n\tml := cp.len()\r\n\treturn headerLen(ml) + ml\r\n}",
"func (s Section) Len() uint32 { return bytes.ReadUint32(s[2:6]) }",
"func usedSize(size, offset, chunkSize int) int {\n\tsize += offset % chunkSize\n\tusedSize := (size / chunkSize) * chunkSize\n\tif size%chunkSize > 0 {\n\t\tusedSize += chunkSize\n\t}\n\n\treturn usedSize\n}",
"func (r *chunkReader) Read(data []byte) (int, error) {\n\tbytesToRead := len(data)\n\tr.l.Debug(\"Start cafs reader Read\", zap.Int(\"length\", bytesToRead))\n\n\tif r.lastChunk && r.rdr == nil {\n\t\treturn 0, io.EOF\n\t}\n\tfor {\n\t\tkey := r.keys[r.idx]\n\t\tif r.rdr == nil {\n\t\t\trdr, err := r.fs.Get(context.Background(), r.pather(key))\n\t\t\tif err != nil {\n\t\t\t\treturn r.readSoFar, err\n\t\t\t}\n\t\t\tr.rdr = rdr\n\t\t}\n\n\t\tn, errRead := r.rdr.Read(data[r.readSoFar:])\n\n\t\tdefer func() {\n\t\t\tif r.MetricsEnabled() && errRead == nil {\n\t\t\t\tr.m.Volume.Blobs.IncBlob(\"read\")\n\t\t\t\tr.m.Volume.Blobs.Size(int64(n), \"read\")\n\t\t\t}\n\t\t\tr.l.Debug(\"End cafs reader Read\", zap.Int(\"length\", bytesToRead))\n\t\t}()\n\n\t\tr.currLeaf = append(r.currLeaf, data[r.readSoFar:r.readSoFar+n]...)\n\t\tif errRead != nil {\n\t\t\tr.rdr.Close() // TODO(fred): nice - why are we ignoring errors here?\n\t\t\tr.readSoFar += n\n\t\t\tif errRead == io.EOF { // we reached the end of the stream for this key\n\t\t\t\tr.idx++\n\t\t\t\tr.rdr = nil\n\t\t\t\tr.lastChunk = r.idx == len(r.keys)\n\t\t\t\tif r.withVerifyHash {\n\t\t\t\t\tnodeOffset := r.idx\n\t\t\t\t\tisLastNode := false\n\n\t\t\t\t\t// NOTE: we follow the checksumming scheme adopted by the writer.\n\t\t\t\t\t// The writer behaves in a way a bit unexpected here: not only offets don't start at zero\n\t\t\t\t\t// as one might expect, but the last node is not flagged as the last one\n\t\t\t\t\t// when the content size is aligned with the leaf size.\n\t\t\t\t\tif r.lastChunk && uint32(len(r.currLeaf)) != r.leafSize {\n\t\t\t\t\t\tnodeOffset--\n\t\t\t\t\t\tisLastNode = true\n\t\t\t\t\t}\n\t\t\t\t\tr.l.Debug(\"cafs reader Read: hash verification\", zap.Stringer(\"key\", key))\n\t\t\t\t\tif err := r.verifyHash(key, r.currLeaf, nodeOffset, isLastNode); err != nil {\n\t\t\t\t\t\treturn 0, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif r.lastChunk { // this was the last chunk, so also EOF for this hash\n\t\t\t\t\tif n == bytesToRead {\n\t\t\t\t\t\treturn n, nil\n\t\t\t\t\t}\n\t\t\t\t\treturn r.readSoFar, io.EOF\n\t\t\t\t}\n\t\t\t\t// move on to the next key\n\t\t\t\tr.currLeaf = make([]byte, 0)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn n, errRead\n\t\t}\n\t\t// we filled up the entire byte slice but still have data remaining in the reader,\n\t\t// we should move on to receive the next buffer\n\t\tr.readSoFar += n\n\t\tif r.readSoFar >= bytesToRead {\n\t\t\tr.readSoFar = 0\n\t\t\t// return without error\n\t\t\treturn bytesToRead, nil\n\t\t}\n\t}\n}",
"func (b *Buffer) Len() uint64 {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\treturn b.length\n}",
"func (a blocksByWork) Len() int { return len(a) }",
"func (s *Storage) GetNumChunks() int {\n\treturn int(s.header.NumChunks)\n}",
"func (q *chunkQueue) nextUp() (uint32, error) {\n\tif q.snapshot == nil {\n\t\treturn 0, errDone\n\t}\n\tfor i := uint32(0); i < q.snapshot.Chunks; i++ {\n\t\tif !q.chunkReturned[i] {\n\t\t\treturn i, nil\n\t\t}\n\t}\n\treturn 0, errDone\n}",
"func (r *reader) readSize(rdr io.Reader) (int, error) {\n\tvar temp [4]byte\n\t_, err := io.ReadFull(rdr, temp[:])\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn int(binary.LittleEndian.Uint32(temp[:])), nil\n}",
"func Len(msg []byte) (length int32) {\n\tr := bytes.NewReader(msg[MsgLenStart:MsgLenEnd])\n\tbinary.Read(r, binary.BigEndian, &length)\n\treturn length\n}",
"func (s *SliceOfByte) Len() int {\n\treturn len(s.items)\n}",
"func (c *Chunker) Next(data []byte) (Chunk, error) {\n\tdata = data[:0]\n\n\t// go guarantees the expected behavior for bit shifts even for shift counts\n\t// larger than the value width. Bounding the value of polShift allows the compiler\n\t// to optimize the code for 'digest >> polShift'\n\n\tminSize := c.MinSize\n\tmaxSize := c.MaxSize\n\tbuf := c.buf\n\n\tfor {\n\t\tif c.bpos >= c.bmax {\n\t\t\tn, err := io.ReadFull(c.rd, buf[:])\n\n\t\t\tif err == io.ErrUnexpectedEOF {\n\t\t\t\terr = nil\n\t\t\t}\n\n\t\t\t// io.ReadFull only returns io.EOF when no bytes could be read. If\n\t\t\t// this is the case and we're in this branch, there are no more\n\t\t\t// bytes to buffer, so this was the last chunk. If a different\n\t\t\t// error has occurred, return that error and abandon the current\n\t\t\t// chunk.\n\t\t\tif err == io.EOF && !c.closed {\n\t\t\t\tc.closed = true\n\n\t\t\t\t// return current chunk, if any bytes have been processed\n\t\t\t\tif c.count > 0 {\n\t\t\t\t\treturn Chunk{\n\t\t\t\t\t\tStart: c.start,\n\t\t\t\t\t\tLength: c.count,\n\t\t\t\t\t\tCut: c.digest,\n\t\t\t\t\t\tData: data,\n\t\t\t\t\t}, nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\treturn Chunk{}, err\n\t\t\t}\n\n\t\t\tc.bpos = 0\n\t\t\tc.bmax = uint(n)\n\t\t}\n\n\t\t// check if bytes have to be dismissed before starting a new chunk\n\t\tif c.pre > 0 {\n\t\t\tn := c.bmax - c.bpos\n\t\t\tif c.pre > uint(n) {\n\t\t\t\tc.pre -= uint(n)\n\t\t\t\tdata = append(data, buf[c.bpos:c.bmax]...)\n\n\t\t\t\tc.count += uint(n)\n\t\t\t\tc.pos += uint(n)\n\t\t\t\tc.bpos = c.bmax\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdata = append(data, buf[c.bpos:c.bpos+c.pre]...)\n\n\t\t\tc.bpos += c.pre\n\t\t\tc.count += c.pre\n\t\t\tc.pos += c.pre\n\t\t\tc.pre = 0\n\t\t}\n\n\t\tadd := c.count\n\n n := c.bmax - c.bpos\n\t\tmid := minSize + 4 * 1024\n\t\tif n > maxSize {\n\t\t\tn = maxSize\n\t\t}else if n < mid{\n\t\t\tmid = n\n\t\t}\n\n\t\t// calculate fp when loop idx from bpos to n\n\t\t// when fp matches the pre-defined splitmask\n\t\t// it generate a cut point\n\t\t// when idx reaches n and still not matches mask, it stores the data.\n\t\t// if idx reaches maxSize, it generate a cut point directly to limit the chunk size.\n\n\t\tidx := c.bpos\n\t\tvar fp uint64 = 0\n\t\tfor ; idx < mid; idx++ {\n\t\t\tfp = (fp << 1) + table[buf[idx]]\n\t\t\tadd ++\n\t\t\tif fp & c.splitmask == 0 {\n\t\t\t\ti := add - c.count - 1\n\t\t\t\tdata = append(data, c.buf[c.bpos:c.bpos + i + 1]...)\n\t\t\t\tc.count = add\n\t\t\t\tc.pos += uint(i) + 1\n\t\t\t\tc.bpos += uint(i) + 1\n\t\t\t\tc.buf = buf\n\t\t\t\tchunk := Chunk {\n\t\t\t\t\tStart: c.start,\n\t\t\t\t\tLength: c.count,\n\t\t\t\t\tCut: fp,\n\t\t\t\t\tData: data,\n\t\t\t\t}\n\t\t\t\tc.reset()\n\t\t\t\treturn chunk, nil\n\t\t\t}\n\t\t}\n\n\t\tfor ; idx < n; idx ++ {\n\t\t\tfp = (fp << 1) + table[buf[idx]]\n\t\t\tadd ++\n\t\t\tif fp & c.splitmask2 == 0 {\n\t\t\t\ti := add - c.count - 1\n\t\t\t\tdata = append(data, c.buf[c.bpos: c.bpos + i + 1]...)\n\t\t\t\tc.count = add\n\t\t\t\tc.pos += uint(i) + 1\n\t\t\t\tc.bpos += uint(i) + 1\n\t\t\t\tc.buf = buf\n\n\t\t\t\tchunk := Chunk {\n\t\t\t\t\tStart: c.start,\n\t\t\t\t\tLength: c.count,\n\t\t\t\t\tCut: fp,\n\t\t\t\t\tData: data,\n\t\t\t\t}\n\t\t\t\tc.reset()\n\t\t\t\treturn chunk, nil\n\t\t\t}\n\t\t}\n\n\t\tif idx >= maxSize {\n\t\t\ti := add - c.count - 1\n\t\t\tdata = append(data, c.buf[c.bpos: c.bpos+i+1]...)\n\t\t\tc.count = add\n\t\t\tc.pos += uint(i) + 1\n\t\t\tc.bpos += uint(i) + 1\n\t\t\tc.buf = buf\n\n\t\t\tchunk := Chunk {\n\t\t\t\tStart: c.start,\n\t\t\t\tLength: c.count,\n\t\t\t\tCut: fp,\n\t\t\t\tData: data,\n\t\t\t}\n\t\t\tc.reset()\n\t\t\treturn chunk, nil\n\t\t}\n\n\n\t\tsteps := c.bmax - c.bpos\n\t\tif steps > 0 {\n\t\t\tdata = append(data, c.buf[c.bpos:c.bpos+steps]...)\n\t\t}\n\t\tc.count += steps\n\t\tc.pos += steps\n\t\tc.bpos = c.bmax\n\t}\n}",
"func (b *Writer) Len() int {\n\treturn b.n\n}",
"func (w *writer) ChunkSize() int {\n\treturn ChunkSize(w.Capacity(), w.in.Size())\n}",
"func Len(input []byte) int {\n\treturn len(input) * 8\n}",
"func (tbs *TSBlobStore) Length(dataSourceID string) (int, error) {\n\tpath := \"/ts/blob/\" + dataSourceID + \"/length\"\n\n\tresp, getErr := tbs.csc.read(path, tbs.contentType)\n\tif getErr != nil {\n\t\treturn 0, getErr\n\t}\n\n\ttype legnthResult struct {\n\t\tLength int `json:\"length\"`\n\t}\n\n\tvar val legnthResult\n\terr := json.Unmarshal(resp, &val)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn val.Length, nil\n}",
"func countingSplitFunc(split bufio.SplitFunc, bytesRead *int64) bufio.SplitFunc {\n\treturn func(data []byte, atEOF bool) (advance int, token []byte, err error) {\n\t\tadv, tok, err := split(data, atEOF)\n\t\t(*bytesRead) += int64(adv)\n\t\treturn adv, tok, err\n\t}\n}",
"func (d *Dataset) Size() int64 {\n\tsize := int64(0)\n\tfor _, block := range d.blocks {\n\t\tsize += block.size\n\t}\n\n\treturn size\n}",
"func (h *Header) Len() int {\n\treturn len(h.slice) / 2\n}",
"func (p Pool) Len() int { return len(p) }",
"func (rcv *Buffer) Length() int64 {\n\treturn rcv._tab.GetInt64(rcv._tab.Pos + flatbuffers.UOffsetT(8))\n}",
"func (r *wrappedReader) TotalBytesRead() int {\n\treturn r.totalBytesRead\n}",
"func chunkify(chunkSize uint64, buf []byte, fn func([]byte, uint64) (uint64, error)) (uint64, error) {\n\ttoProcess := uint64(len(buf))\n\tvar (\n\t\ttotalProcessed uint64\n\t\tcurProcessed uint64\n\t\toff uint64\n\t\terr error\n\t)\n\tfor {\n\t\tif totalProcessed == toProcess {\n\t\t\treturn totalProcessed, nil\n\t\t}\n\n\t\tif totalProcessed+chunkSize > toProcess {\n\t\t\tcurProcessed, err = fn(buf[totalProcessed:], off)\n\t\t} else {\n\t\t\tcurProcessed, err = fn(buf[totalProcessed:totalProcessed+chunkSize], off)\n\t\t}\n\t\ttotalProcessed += curProcessed\n\t\toff += curProcessed\n\n\t\tif err != nil {\n\t\t\treturn totalProcessed, err\n\t\t}\n\n\t\t// Return partial result immediately.\n\t\tif curProcessed < chunkSize {\n\t\t\treturn totalProcessed, nil\n\t\t}\n\n\t\t// If we received more bytes than we ever requested, this is a problem.\n\t\tif totalProcessed > toProcess {\n\t\t\tpanic(fmt.Sprintf(\"bytes completed (%d)) > requested (%d)\", totalProcessed, toProcess))\n\t\t}\n\t}\n}",
"func fread(tls TLS, ptr uintptr, size, nmemb size_t, stream uintptr) size_t {\n\thi, lo := mathutil.MulUint128_64(uint64(size), uint64(nmemb))\n\tif hi != 0 || lo > uint64(len(rawmem{})) {\n\t\ttls.setErrno(errno.XE2BIG)\n\t\treturn 0\n\t}\n\n\tn, err := files.reader(stream).Read((*rawmem)(unsafe.Pointer(ptr))[:lo])\n\tif err != nil {\n\t\ttls.setErrno(errno.XEIO)\n\t}\n\treturn size_t(n) / size\n}",
"func (s *Stream) Count() int {\n\treturn len(s.b) + s.stream.count()\n}",
"func (wb *fieldWriteBuf) totalLen() int {\n\treturn len(wb.defaultBuf) + len(wb.blobBuf)\n}",
"func (q *wantConnQueue) len() int {\n\treturn len(q.head) - q.headPos + len(q.tail)\n}",
"func (m *QueryStreamResponse) ChunksCount() int {\n\tif len(m.Chunkseries) == 0 {\n\t\treturn 0\n\t}\n\n\tcount := 0\n\tfor _, entry := range m.Chunkseries {\n\t\tcount += len(entry.Chunks)\n\t}\n\treturn count\n}",
"func (s *safeBuffer) Len() int {\n\ts.Lock()\n\tdefer s.Unlock()\n\treturn s.buf.Len()\n}",
"func (D DiskIterator) Next() (string, error) {\n\n\tof, ind := D.readHeader()\n\tif of < 0 || ind > D.recordInx || ind < 0 {\n\t\treturn \"\", errors.New(\"errore nella lettura del heder\")\n\t}\n\tlen := D.actualOfset - of\n\tD.actualOfset = of\n\tD.recordInx = ind\n\tcnt, err := D.readN(int(len))\n\tif err != nil {\n\t\treturn \"\", errors.New(\"errore nella lettura del record\")\n\t}\n\n\treturn string(cnt), nil\n}",
"func (n *RNSNum) size() int {\n\treturn len(n.buffer)\n}",
"func (e *Encoder) Len() int {\n\treturn e.buf.Len()\n}"
] | [
"0.6866359",
"0.6837389",
"0.6811439",
"0.6689204",
"0.6628324",
"0.65963304",
"0.6485892",
"0.6412918",
"0.63652194",
"0.636248",
"0.63501394",
"0.6267112",
"0.6244418",
"0.6226337",
"0.6223782",
"0.61840355",
"0.6176268",
"0.6161804",
"0.6148599",
"0.6135891",
"0.61323494",
"0.6129212",
"0.61220646",
"0.6121597",
"0.611275",
"0.61054623",
"0.60819805",
"0.60586065",
"0.6047629",
"0.60181236",
"0.59957284",
"0.5981984",
"0.5976918",
"0.5962876",
"0.59539735",
"0.59518665",
"0.5948405",
"0.59428644",
"0.59234726",
"0.59085697",
"0.5899827",
"0.5878917",
"0.58663803",
"0.5864301",
"0.58562565",
"0.5850639",
"0.5847451",
"0.58438015",
"0.5838542",
"0.58264375",
"0.5821168",
"0.5813333",
"0.5803325",
"0.5803167",
"0.58013463",
"0.5799342",
"0.57970434",
"0.5793329",
"0.5792219",
"0.578334",
"0.57710046",
"0.5766467",
"0.57547075",
"0.57438964",
"0.5742109",
"0.57241035",
"0.5723479",
"0.57046306",
"0.5701364",
"0.5700384",
"0.56971765",
"0.56938",
"0.56936157",
"0.56934816",
"0.5688957",
"0.5686454",
"0.56844914",
"0.5684074",
"0.5683442",
"0.5682146",
"0.5674502",
"0.56661123",
"0.5654112",
"0.564837",
"0.5647242",
"0.56397676",
"0.56367296",
"0.5631249",
"0.56236947",
"0.562181",
"0.56216776",
"0.5603069",
"0.5601455",
"0.56013495",
"0.55969816",
"0.5592637",
"0.5586829",
"0.5585554",
"0.5576828",
"0.55757964"
] | 0.5715816 | 67 |
return base64 (stringified) version of sha1 hash of array of bytes | func shaString(buf []byte) string {
h := sha1.Sum(buf)
return base64.StdEncoding.EncodeToString(h[:])
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func sha1Hash(slices [][]byte) []byte {\n\thsha1 := sha1.New()\n\tfor _, slice := range slices {\n\t\thsha1.Write(slice)\n\t}\n\treturn hsha1.Sum(nil)\n}",
"func Sha1(data []byte) string {\n\tshaInst := sha1.New()\n\t_, err := shaInst.Write(data)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%x\", shaInst.Sum(nil))\n}",
"func SHA1Base64String(data string) string {\n\thash := sha1.Sum([]byte(data))\n\treturn base64.StdEncoding.EncodeToString(hash[:])\n}",
"func GetSHA1hash(obj interface{}) string {\n\tsha1Hash := sha1.New()\n\tswitch t := obj.(type) {\n\tcase *corev1.Secret:\n\t\tvar (\n\t\t\tsortedDataKeys []string\n\t\t\tsortedStringDataKeys []string\n\t\t)\n\t\tfor k := range t.Data {\n\t\t\tsortedDataKeys = append(sortedDataKeys, k)\n\t\t}\n\t\tfor k := range t.StringData {\n\t\t\tsortedStringDataKeys = append(sortedStringDataKeys, k)\n\t\t}\n\t\tif len(sortedDataKeys) == 0 && len(sortedStringDataKeys) == 0 {\n\t\t\treturn \"\"\n\t\t}\n\t\tsort.Strings(sortedDataKeys)\n\t\tsha1Hash.Write([]byte(strings.Join(sortedDataKeys, \"\")))\n\t\tsort.Strings(sortedStringDataKeys)\n\t\tsha1Hash.Write([]byte(strings.Join(sortedStringDataKeys, \"\")))\n\n\t\tfor _, key := range sortedDataKeys {\n\t\t\tsha1Hash.Write(t.Data[key])\n\t\t}\n\t\tfor _, key := range sortedStringDataKeys {\n\t\t\tsha1Hash.Write([]byte(t.StringData[key]))\n\t\t}\n\tdefault:\n\t\tutilruntime.HandleError(fmt.Errorf(\"Unknown object: %v\", obj))\n\t\treturn \"\"\n\t}\n\treturn hex.EncodeToString(sha1Hash.Sum(nil))\n}",
"func (CryptoFuncs) SHA1Bytes(input interface{}) ([]byte, error) {\n\t//nolint:gosec\n\tb := sha1.Sum(toBytes(input))\n\tout := make([]byte, len(b))\n\tcopy(out, b[:])\n\treturn out, nil\n}",
"func GetSHA1(content []byte) string {\n\tsha := sha1.New()\n\tsha.Write(content)\n\n\treturn base32.StdEncoding.EncodeToString(sha.Sum(nil))\n}",
"func Bashit(tox []byte) string {\n h:= sha256.New()\n h.Write([]byte(tox))\n bs := h.Sum([]byte{})\n str := base64.StdEncoding.EncodeToString(bs)\n return str\n}",
"func hashBytes(input ...interface{}) []byte {\n\tvar combine []string\n\tfor _, v := range input {\n\t\tif x, ok := v.([]byte); ok {\n\t\t\tv = string(x)\n\t\t}\n\t\tcombine = append(combine, fmt.Sprintf(\"%v\", v))\n\t}\n\tsum := sha256.Sum256([]byte(strings.Join(combine[0:], NONE)))\n\tvar output []byte\n\toutput = append(output[0:], sum[0:]...)\n\treturn output\n}",
"func HashBase64(input string) string {\n\thash512 := sha512.Sum512([]byte(input))\n\n\treturn base64.StdEncoding.EncodeToString(hash512[:])\n}",
"func (f CryptoFuncs) SHA1(input interface{}) string {\n\t// nolint: gosec\n\tout, _ := f.SHA1Bytes(input)\n\treturn fmt.Sprintf(\"%02x\", out)\n}",
"func HashStringSha1(hs string) []byte {\n\tdata := []byte(hs)\n\thash := sha1.Sum(data)\n\treturn hash[:]\n}",
"func Sha1(input string) string {\n\thash := sha1.New()\n\thash.Write([]byte(input))\n\thashed := hash.Sum(nil)\n\treturn fmt.Sprintf(\"%x\", hashed)\n}",
"func SHA1(s string) string {\n\treturn stringHasher(sha1.New(), s)\n}",
"func Sha1(s string) string {\n\treturn hashing(sha1.New(), s)\n}",
"func SHA1(input string) string {\n\n\t//Initiate SHA-1 type\n\th := sha1.New()\n\n\t//Set input\n\th.Write([]byte(input))\n\n\t//Return hash as string\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func Hashit(tox string) string {\n h:= sha256.New()\n h.Write([]byte(tox))\n bs := h.Sum([]byte{})\n str := base64.StdEncoding.EncodeToString(bs)\n return str\n}",
"func Sha1(src []byte) (out [20]byte, err error) {\n\tif len(src) == 0 {\n\t\tout = EmptySHA1Hash\n\t\treturn\n\t}\n\tret := C.X_mbedtls_sha1_ret((*C.uchar)(unsafe.Pointer(&src[0])), C.int(len(src)), (*C.uchar)(unsafe.Pointer(&out[0])))\n\tif ret != 0 {\n\t\terr = GetMessageDigestErrorByErrorCode((int)(ret))\n\t\treturn\n\t}\n\treturn\n}",
"func hashStr(toHash string) string {\n\th := sha1.New()\n\tio.WriteString(h, toHash)\n\thashed := base64.StdEncoding.EncodeToString(h.Sum(nil))\n\treturn hashed\n}",
"func md5SHA1Hash(slices [][]byte) []byte {\n\tmd5sha1 := make([]byte, md5.Size+sha1.Size)\n\thmd5 := md5.New()\n\tfor _, slice := range slices {\n\t\thmd5.Write(slice)\n\t}\n\tcopy(md5sha1, hmd5.Sum(nil))\n\tcopy(md5sha1[md5.Size:], sha1Hash(slices))\n\treturn md5sha1\n}",
"func SHA1(s string) string {\n\th := sha1.New()\n\th.Write([]byte(s))\n\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func SHA1(s string) string {\n\th := sha1.New()\n\th.Write([]byte(s))\n\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func Hash(input []byte) string {\n\treturn fmt.Sprintf(\"%x\", sha256.Sum256(input))\n}",
"func Sha1(s string) string {\n\tdigest := sha1.Sum([]byte(s))\n\treturn hex.EncodeToString(digest[:])\n}",
"func generateSHA256HashInBase64Form(preimage string) string {\n\thasher := sha256.New()\n\thasher.Write([]byte(preimage))\n\tshaHash := hasher.Sum(nil)\n\tshaHashBase64 := base64.StdEncoding.EncodeToString(shaHash)\n\treturn shaHashBase64\n}",
"func Hash1(usr string) string {\n\tbytes := []byte(usr)\n\thash_bytes := hasher1.Sum(bytes)\n\treturn hex.EncodeToString(hash_bytes)\n}",
"func shaEncode(input string) string {\n\tsha := sha512.Sum512([]byte(input))\n\treturn hex.EncodeToString(sha[:])\n}",
"func hasher(s string) []byte {\n\tval := sha256.Sum256([]byte(s))\n\tvar hex []string\n\n\t// Iterate through the bytes.\n\tfor i := 0; i < len(val); i++ {\n\t\t// We want each number to be represented by 2 chars.\n\t\tplaceHolder := []string{\"0\"}\n\t\tvalue := strconv.FormatInt(int64(val[i]), 16)\n\n\t\tif len(value) != 2 {\n\t\t\tplaceHolder = append(placeHolder, value)\n\t\t\thex = append(hex, strings.Join(placeHolder, \"\"))\n\t\t} else {\n\t\t\thex = append(hex, value)\n\t\t}\n\t}\n\treturn []byte(strings.Join(hex, \"\"))\n\n}",
"func GenerateSHA1(s string) string {\n\thasher := sha1.New()\n\tbv := []byte(s)\n\thasher.Write(bv)\n\tsha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))\n\treturn sha\n}",
"func (o LookupAndroidAppResultOutput) Sha1Hashes() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupAndroidAppResult) []string { return v.Sha1Hashes }).(pulumi.StringArrayOutput)\n}",
"func Hash(a interface{}) (string, error) {\n\th := sha1.New()\n\tif err := json.NewEncoder(h).Encode(a); err != nil {\n\t\treturn \"\", nil\n\t}\n\treturn base64.URLEncoding.EncodeToString(h.Sum(nil)), nil\n}",
"func createHash(byteStr []byte) []byte {\n\tvar hashVal hash.Hash\n\thashVal = sha1.New()\n\thashVal.Write(byteStr)\n\n\tvar bytes []byte\n\n\tbytes = hashVal.Sum(nil)\n\treturn bytes\n}",
"func toSha1(s string) string {\n\th := sha1.New()\n\th.Write([]byte(s))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func Hashbin(tox string) []byte {\n h:= sha256.New()\n h.Write([]byte(tox))\n bs := h.Sum([]byte{})\n return bs \n}",
"func EncodeSHA1(str string) string {\n\th := sha1.New()\n\th.Write([]byte(str))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func CreateSha1(data []byte) string {\n\t_sha1 := sha1.New()\n\treturn base64.StdEncoding.EncodeToString(_sha1.Sum(data))\n}",
"func SHA1HMAC(salt, message []byte) string {\n\t// GitHub creates a SHA1 HMAC, where the key is the GitHub secret and the\n\t// message is the JSON body.\n\tdigest := hmac.New(sha1.New, salt)\n\tdigest.Write(message)\n\tsum := digest.Sum(nil)\n\treturn fmt.Sprintf(\"sha1=%x\", sum)\n}",
"func (this *HashHmacGenerator) Sha1String(data string) string {\n\thmacBytes := this.Sha1([]byte(data))\n\treturn fmt.Sprintf(\"%x\", hmacBytes)\n}",
"func Hash(s string) string {\n\tSha1Inst := sha1.New()\n\tSha1Inst.Write([]byte(s))\n\tresult := Sha1Inst.Sum([]byte(\"\"))\n\treturn fmt.Sprintf(\"%x\", result)\n}",
"func hashbyte(a ...[]byte) []byte {\n\th := mac()\n\tfor _, z := range a {\n\t\th.Write(z)\n\t}\n\treturn h.Sum(nil)\n}",
"func BytesString(hash []byte) string {\n\treturn fmt.Sprintf(\"%X\", hash)\n}",
"func HashBytes(bytes []byte) string {\n\thash := blake2b.Sum256(bytes)\n\treturn hex.EncodeToString(hash[:])\n}",
"func hashString(str string) string {\n\thash := sha256.Sum256([]byte(str))\n\treturn base64.StdEncoding.EncodeToString(hash[:])\n}",
"func Sha1() (sum [sha1.Size]byte) {\n\ts, err := hex.DecodeString(packerSHA1)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tcopy(sum[0:], s)\n\treturn\n}",
"func Hash(str string) string {\n\tout, err := b64.StdEncoding.DecodeString(str)\n\tif err == nil && len(out) > 1 {\n\t\t// if already b64 encoded don't hash\n\t\treturn str\n\t}\n\tv := sha256.Sum256([]byte(str))\n\treturn string(b64.StdEncoding.EncodeToString(v[:]))\n}",
"func genhash(in []string) string {\n\th := md5.New()\n\tio.WriteString(h, strings.Join(in, \"\"))\n\treturn fmt.Sprintf(\"%x\", h.Sum([]byte{}))\n}",
"func (o *Aliyun) hmacSha1(s string) string {\n\tkey := []byte(o.Account.AccessSecret + \"&\")\n\tmac := hmac.New(sha1.New, key)\n\tmac.Write([]byte(s))\n\tsignure := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\treturn o.percentEncode(signure)\n}",
"func hash_file_sha1(f File_s) (string, error) {\n\t//Initialize variable returnMD5String now in case an error has to be returned\n\tvar returnSHA1String string\n\n\t//Open the filepath passed by the argument and check for any error\n\tfile, err := os.Open(f.path)\n\tif err != nil {\n\t\treturn returnSHA1String, err\n\t}\n\t// Read first 20 bytes.\n\tb1 := make([]byte, 20)\n\tfile.Read(b1)\n\tss := f.Name + string(f.Size) + string(b1)\n\t//Tell the program to call the following function when the current function returns\n\tdefer file.Close()\n\n\t//Open a new SHA1 hash interface to write to\n\thash := sha1.New()\n\n\thash.Write([]byte(ss))\n\t//Get the 20 bytes hash\n\thashInBytes := hash.Sum(nil)[:20]\n\n\t//Convert the bytes to a string\n\treturnSHA1String = hex.EncodeToString(hashInBytes)\n\n\treturn returnSHA1String, nil\n\n}",
"func hashBytes(hashType HashType, bytes []byte) []byte {\n var idHash []byte\n switch hashType {\n case SHA3:\n hash := sha3.Sum224(bytes)\n return hash[:]\n case Shake128:\n sha3.ShakeSum256(idHash, bytes)\n return idHash\n default: // Undefined\n return bytes\n }\n}",
"func hash(elements ...[32]byte) [32]byte {\n\tvar hash []byte\n\tfor i := range elements {\n\t\thash = append(hash, elements[i][:]...)\n\t}\n\treturn sha256.Sum256(hash)\n}",
"func hexEncodeSHA256Hash(body []byte) (string, error) {\n\thash := sha256.New()\n\tif body == nil {\n\t\tbody = []byte(\"\")\n\t}\n\t_, err := hash.Write(body)\n\treturn hex.EncodeToString(hash.Sum(nil)), err\n}",
"func SHA1(space string, data []byte) (string, error) {\n\tu, err := uuid.Parse(string(space))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(uuid.NewSHA1(u, data).String()), nil\n}",
"func Bashbin(tox []byte) []byte {\n h:= sha256.New()\n h.Write([]byte(tox))\n bs := h.Sum([]byte{})\n return bs \n}",
"func hashhex(a ...[]byte) string {\n\th := hashbyte(a...)\n\ts := fmt.Sprintf(\"%x\", h)\n\treturn s\n}",
"func Sha1(token, timestamp, nonce, msg string) string {\n\tsl := []string{token, timestamp, nonce, msg}\n\tsort.Strings(sl)\n\n\th := sha1.New()\n\tfor _, s := range sl {\n\t\tio.WriteString(h, s)\n\t}\n\tencode := h.Sum(nil)\n\n\treturn hex.EncodeToString(encode)\n\n}",
"func DERToHash(der string) string {\n\n bites, _ := base64.StdEncoding.DecodeString(der)\n \n return Bashit(bites)\n\n}",
"func HmacSha1(message []byte, secret string) []byte {\n\th := hmac.New(sha1.New, []byte(secret))\n\th.Write(message)\n\treturn h.Sum(nil)\n}",
"func HMACSHA1(secret, msg []byte) []byte {\n\tvar k []byte\n\tif len(secret) > 64 {\n\t\tt := sha1.Sum(secret)\n\t\tk = t[:]\n\t} else {\n\t\tk = make([]byte, 64)\n\t\tfor i, v := range secret {\n\t\t\tk[i] = v\n\t\t}\n\t}\n\topad := make([]byte, 64)\n\tipad := make([]byte, 64)\n\tfor i := range opad {\n\t\topad[i] = 0x5C\n\t\tipad[i] = 0x36\n\t}\n\n\tiKey, _ := XorBufs(k, ipad)\n\toKey, _ := XorBufs(k, opad)\n\n\tm := sha1.Sum(append(iKey, msg...))\n\tm = sha1.Sum(append(oKey, m[:]...))\n\treturn m[:]\n}",
"func HashToString(nbytes [crypto.HashLen]byte) string {\n\tbytes := nbytes[:]\n\treturn hex.EncodeToString(bytes)\n}",
"func (s *SHA1) String() string {\n\ts.strOnce.Do(func() {\n\t\tresult := make([]byte, 0, 40)\n\t\thexvalues := []byte(\"0123456789abcdef\")\n\t\tfor i := 0; i < 20; i++ {\n\t\t\tresult = append(result, hexvalues[s.bytes[i]>>4])\n\t\t\tresult = append(result, hexvalues[s.bytes[i]&0xf])\n\t\t}\n\t\ts.str = string(result)\n\t})\n\treturn s.str\n}",
"func Hash(k []byte) [HashSize]byte {\r\n\thasher := sha1.New()\r\n\thasher.Write(k)\r\n\thashSlice := hasher.Sum(nil)\r\n\tvar hash [HashSize]byte;\r\n\tcopy(hash[:], hashSlice)\r\n\treturn hash\r\n}",
"func Hash(v []byte) string {\n\th := sha256.Sum256(v)\n\treturn hex.EncodeToString(h[:])\n}",
"func AggregateSignatures(signatures []string) string {\n\thasher := sha1.New()\n\tlength := 0\n\tfor _, signature := range signatures {\n\t\t// Hash the strings, with separator/terminator. We do\n\t\t// __not__ want {\"ab\",\"a\"} and {\"a\",\"ba\"} to hash to\n\t\t// the same value.\n\t\thasher.Write([]byte(signature))\n\t\thasher.Write([]byte(\"\\x00\"))\n\t\tlength = length + len(signature)\n\t}\n\t// Hash in the total length of the input\n\thasher.Write([]byte(fmt.Sprintf(\"%d\", length)))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}",
"func (this *MatchString) GetSha1(content string) string {\n\thasher := sha1.New()\n\t_, err = hasher.Write([]byte(content))\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tsha := hasher.Sum(nil)\n\treturn hex.EncodeToString(sha)\n}",
"func HashFileSha1(hs string) []byte {\n\tfile, err := os.Open(hs)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer func() {\n\t\terr := file.Close()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\tdata := sha1.New()\n\tif _, err := io.Copy(data, file); err != nil {\n\t\tpanic(err)\n\t}\n\n\thash := data.Sum(nil)\n\treturn hash[:]\n}",
"func xx512x1(inner_512 []byte) [20]byte {\n\touter_512 := sha512.Sum512(inner_512)\n\treturn sha1.Sum(outer_512[:])\n}",
"func byteshash(p *[]byte, h uintptr) uintptr",
"func (h Hash) String() string { return hex.EncodeToString(h[:]) }",
"func HmacSha1ToHex(message []byte, secret string) string {\n\th := hmac.New(sha1.New, []byte(secret))\n\th.Write(message)\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func (s *SRP) hashbyte(a ...[]byte) []byte {\n\th := s.h.New()\n\tfor _, z := range a {\n\t\th.Write(z)\n\t}\n\treturn h.Sum(nil)\n}",
"func hash(f []byte) (string, error) {\n\tsha := sha256.New()\n\t_, err := sha.Write(f)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%x\", sha.Sum(nil)), nil\n}",
"func hashSHA256(input string) string {\n\th := sha1.New()\n\th.Write([]byte(input))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func getSHA256Hash(data []byte) string {\n\treturn hex.EncodeToString(getSHA256Sum(data))\n}",
"func (m *Manifest) SHA1() (string, error) {\n\tmanifestBytes, err := yaml.Marshal(m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%x\", sha1.Sum(manifestBytes)), nil\n}",
"func hash(s string) string {\n\treturn fmt.Sprintf(\"%x\", md5.Sum([]byte(s)))\n}",
"func Base64(bin []byte) string {\n\treturn base64.StdEncoding.EncodeToString(bin)\n}",
"func computeMD5Hash(toBeEncoded int64) string {\n\tvar computedString string\n\n\tbyteArray := make([]byte, 1024)\n\tn := binary.PutVarint(byteArray, toBeEncoded)\n\n\tcomputedMD5 := md5.Sum(byteArray[0:n])\n\n\tcomputedString = fmt.Sprintf(\"%x\", computedMD5)\n\n\treturn computedString\n\n}",
"func (o SslCertOutput) Sha1Fingerprint() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SslCert) pulumi.StringOutput { return v.Sha1Fingerprint }).(pulumi.StringOutput)\n}",
"func shortSha1(s string) string {\n\th := sha1.New()\n\n\th.Write([]byte(s))\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))[:6]\n}",
"func ShortHash(data ...string) string {\n\th := sha1.New()\n\tio.WriteString(h, strings.Join(data, \"\"))\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil)[:4])\n}",
"func ShaSum256HexEncoded(b []byte) string {\n\tsha := sha256.Sum256(b)\n\tshaHex := hex.EncodeToString(sha[:])\n\n\treturn shaHex\n}",
"func ShaSum256HexEncoded(b []byte) string {\n\tsha := sha256.Sum256(b)\n\tshaHex := hex.EncodeToString(sha[:])\n\n\treturn shaHex\n}",
"func (h Hash) Bytes() []byte { return h[:] }",
"func (h Hash) Bytes() []byte { return h[:] }",
"func (me TCryptoBinary) String() string { return xsdt.Base64Binary(me).String() }",
"func Hash256Bytes(bytes []byte) string {\n\thasher := sha256.New()\n\thasher.Write(bytes)\n\tmsgDigest := hasher.Sum(nil)\n\tsha256Hex := hex.EncodeToString(msgDigest)\n\treturn sha256Hex\n}",
"func EncodeHash(s string) string {\n\th := sha1.New()\n\th.Write([]byte(s))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func (sw *SigningWriter) SHA1Sum() [sha1.Size]byte {\n\treturn sha1.Sum(sw.digest.Bytes())\n}",
"func hash(ba string) string {\n\th := sha256.New()\n\th.Write([]byte(ba))\n\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}",
"func SHA1(password, salt []byte, iter, keyLen int) []byte {\n\tprf := hmac.New(sha1.New, password)\n\tnumBlocks := (keyLen + sha1.Size - 1) / sha1.Size\n\n\tvar inner, outer block\n\thmac_init(&inner, &outer, password)\n\n\tvar buf [4]byte\n\tvar tmp block\n\tvar U block\n\tdk := make([]byte, 0, numBlocks*sha1.Size)\n\ttpad := make([]byte, sha1.BlockSize)\n\tfor block := 1; block <= numBlocks; block++ {\n\t\t// N.B.: || means concatenation, ^ means XOR\n\t\t// for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter\n\t\t// U_1 = PRF(password, salt || uint(i))\n\t\tprf.Reset()\n\t\tprf.Write(salt)\n\t\tputUint32(buf[:], uint32(block))\n\t\tprf.Write(buf[:4])\n\t\tdk = prf.Sum(dk)\n\t\tT := dk[len(dk)-sha1.Size:]\n\n\t\t//sha1_input(&tmp, T)\n\t\tfor i := range tmp.h[:5] {\n\t\t\ttmp.h[i] = readUint32(T[i*4:])\n\t\t}\n\t\t// U_n = PRF(password, U_(n-1))\n\t\tcopy(tpad, T)\n\t\tsha1_pad(tpad, sha1.BlockSize+sha1.Size)\n\t\tsha1_input(&U, tpad)\n\t\tfor n := 2; n <= iter; n++ {\n\t\t\tsha1_block(&U, &inner, &U)\n\t\t\tsha1_block(&U, &outer, &U)\n\t\t\ttmp.h[0] ^= U.h[0]\n\t\t\ttmp.h[1] ^= U.h[1]\n\t\t\ttmp.h[2] ^= U.h[2]\n\t\t\ttmp.h[3] ^= U.h[3]\n\t\t\ttmp.h[4] ^= U.h[4]\n\t\t}\n\t\tsha1_output(T, &tmp)\n\t}\n\treturn dk[:keyLen]\n}",
"func Base64Transaction(tx []byte) (bs string) {\n jtx, _ := json.Marshal(tx)\n bs = base64.StdEncoding.EncodeToString(jtx)\n return bs\n}",
"func Hash(input []byte) (out []byte) {\n\thash := sha256.New()\n\thash.Write(input)\n\treturn hash.Sum(nil)\n}",
"func getMD5Hash(data []byte) string {\n\treturn hex.EncodeToString(getMD5Sum(data))\n}",
"func hashBytes(data []byte) []byte {\n\th := sha256.New()\n\t_, err := h.Write(data)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn h.Sum(nil)\n}",
"func SHA1MSG1(mx, x operand.Op) { ctx.SHA1MSG1(mx, x) }",
"func Base64ToBytes(h string) []byte {\n\ts, err := base64.URLEncoding.DecodeString(h)\n\tif err != nil {\n\t\tfmt.Errorf(\"faild to convert Base64ToBytes(%s) with error : %s\", h, err.Error())\n\t\treturn []byte(\"\")\n\t}\n\treturn s\n}",
"func hash(password string) string {\n\thash := sha512.New()\n\thash.Write([]byte(password))\n\tb := hash.Sum(nil)\n\treturn base64.StdEncoding.EncodeToString(b)\n}",
"func HexToBase64(hex []byte) string {\n\tencoder := base64.StdEncoding\n\treturn encoder.EncodeToString(hex)\n}",
"func getClaimSignatureDigest(bytes ...[]byte) [32]byte {\n\n\tvar combined []byte\n\tfor _, b := range bytes {\n\t\tcombined = append(combined, b...)\n\t}\n\tdigest := sha256.Sum256(combined)\n\treturn [32]byte(digest)\n}",
"func BenchmarkSHA1(b *testing.B) {\n\tstr := \"[email protected]\"\n\tbytes := []byte(str)\n\th := sha1.New()\n\tfor i := 0; i < b.N; i++ {\n\t\th.Reset()\n\t\th.Write(bytes)\n\t\t_ = h.Sum([]byte{})\n\t}\n}",
"func htkey_hash_str(k1 voidptr, len int) usize {\n\tvar k1p byteptr = (byteptr)(k1)\n\tvar hash usize\n\n\thash = 0 + 5381 + len + 1\n\tfor i := 0; i < len; i++ {\n\t\tc := k1p[i]\n\t\thash = ((hash << 5) + hash) ^ usize(c)\n\t}\n\n\treturn hash\n}"
] | [
"0.7108705",
"0.6960605",
"0.6952508",
"0.6891505",
"0.6877706",
"0.685306",
"0.6784708",
"0.6765739",
"0.67434824",
"0.6663368",
"0.65995187",
"0.65584576",
"0.6525033",
"0.6502301",
"0.64993083",
"0.6484184",
"0.6469908",
"0.64496136",
"0.6448522",
"0.6447964",
"0.6447964",
"0.64229745",
"0.6372142",
"0.63709503",
"0.6362566",
"0.63543266",
"0.6349246",
"0.6347239",
"0.63366127",
"0.63115245",
"0.6300736",
"0.62952614",
"0.62876785",
"0.62693346",
"0.6205071",
"0.6200978",
"0.61892813",
"0.618801",
"0.6171453",
"0.61678374",
"0.61612326",
"0.6142946",
"0.6131875",
"0.61230177",
"0.6116098",
"0.608077",
"0.6059839",
"0.6033964",
"0.6031445",
"0.6010882",
"0.6000006",
"0.5987162",
"0.5986316",
"0.5985897",
"0.5982813",
"0.596918",
"0.59613615",
"0.5959816",
"0.59584606",
"0.59466946",
"0.5930745",
"0.5920519",
"0.59060156",
"0.59000146",
"0.5893285",
"0.5889009",
"0.58853626",
"0.5860144",
"0.5837148",
"0.58351994",
"0.582877",
"0.58191293",
"0.5817171",
"0.58170605",
"0.58164746",
"0.5805015",
"0.58042425",
"0.58027",
"0.5798142",
"0.57889694",
"0.57889694",
"0.5781762",
"0.5781762",
"0.5780482",
"0.5768728",
"0.5763816",
"0.5763311",
"0.5748415",
"0.5744214",
"0.5733374",
"0.5727195",
"0.5715034",
"0.57150143",
"0.5709854",
"0.5702428",
"0.57023793",
"0.5701558",
"0.5700061",
"0.5690989",
"0.56840724"
] | 0.7195556 | 0 |
Use rk fingerprints to chunkify array of data. Take the stringified sha1 hash of each such chunk and use as key to store in keyvalue store. Return array of such strings. | func putBlocks(data []byte) (s []string) {
off := 0
for off < len(data) {
ret := rkChunk(data[off:])
// p_out("offset: %d, length: %d\n", off, ret)
s = append(s, putBlock(data[off:(off+ret)]))
off += ret
}
return
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func getKeyHash(k string) [4]int {\n\th1 := sha1.New()\n\th1.Write([]byte(k))\n\tb1 := h1.Sum(nil)\n\tdata1 := b1[0]\n\tid1 := data1 % 8\n\tid1 = id1 * 4\n\tidint := int(id1)\n\tvar nodelist [4]int\n\tfor k := 0; k < 4; k++ {\n\t\tnodelist[k] = k + idint\n\t}\n\n\t//fmt.Println(\"Nodelist for given key\", nodelist)\n\treturn nodelist\n}",
"func deriveKeys(parts ...*[32]byte) (*[32]byte, *[32]byte) {\n\td := sha512.New()\n\tfor _, p := range parts {\n\t\td.Write(p[:])\n\t}\n\tk := d.Sum(nil)\n\ta := new([32]byte)\n\tb := new([32]byte)\n\tcopy(a[:], k[:32])\n\tcopy(b[:], k[32:64])\n\treturn a, b\n}",
"func getChunksByKey(chunkedFile *chunker.ChunkedFile) (map[string]*chunker.Chunk, string) {\n\tvar sb strings.Builder\n\n\ttotalChunks := len(chunkedFile.Chunks())\n\tchunksByKey := make(map[string]*chunker.Chunk, totalChunks)\n\tfor count, chunk := range chunkedFile.Chunks() {\n\t\tkey := fmt.Sprintf(\"%s-part-%d-of-%d\", chunkedFile.Checksum(), count, totalChunks)\n\t\tchunksByKey[key] = chunk\n\n\t\tsb.WriteString(key)\n\t\tsb.WriteString(\",\")\n\t}\n\treturn chunksByKey, strings.TrimSuffix(sb.String(), \",\")\n}",
"func divideByChunkSize(keys []peer.ID, chunkSize int) [][]peer.ID {\n\tif len(keys) == 0 {\n\t\treturn nil\n\t}\n\n\tif chunkSize < 1 {\n\t\tpanic(fmt.Sprintf(\"fullrt: divide into groups: invalid chunk size %d\", chunkSize))\n\t}\n\n\tvar keyChunks [][]peer.ID\n\tvar nextChunk []peer.ID\n\tchunkProgress := 0\n\tfor _, k := range keys {\n\t\tnextChunk = append(nextChunk, k)\n\t\tchunkProgress++\n\t\tif chunkProgress == chunkSize {\n\t\t\tkeyChunks = append(keyChunks, nextChunk)\n\t\t\tchunkProgress = 0\n\t\t\tnextChunk = make([]peer.ID, 0, len(nextChunk))\n\t\t}\n\t}\n\tif chunkProgress != 0 {\n\t\tkeyChunks = append(keyChunks, nextChunk)\n\t}\n\treturn keyChunks\n}",
"func rkChunk(buf []byte) int {\n\tvar off uint64\n\tvar hash uint64\n\tvar b_n uint64\n\tif b == 0 {\n\t\tb = THE_PRIME\n\t\tb_n = 1\n\t\tfor i := 0; i < (HASHLEN - 1); i++ {\n\t\t\tb_n *= b\n\t\t}\n\t\tfor i := uint64(0); i < 256; i++ {\n\t\t\tsaved[i] = i * b_n\n\t\t}\n\t}\n\n\tfor off = 0; off < HASHLEN && off < uint64(len(buf)); off++ {\n\t\thash = hash*b + uint64((buf[off]))\n\t}\n\n\tfor off < uint64(len(buf)) {\n\t\thash = (hash-saved[buf[off-HASHLEN]])*b + uint64(buf[off])\n\t\toff++\n\n\t\tif (off >= MINCHUNK && ((hash % TARGETCHUNK) == 1)) || (off >= MAXCHUNK) {\n\t\t\treturn int(off)\n\t\t}\n\t}\n\treturn int(off)\n}",
"func calcChunkWorkers(chunks <-chan chunkInput, results chan<- chunkOutput) {\n\n\tfor c := range chunks {\n\n\t\tblake := blake2.New(&blake2.Config{Size: KeySize, Tree: &blake2.Tree{Fanout: 0, MaxDepth: 2, LeafSize: config.Config.LeafSize, NodeOffset: uint64(c.part), NodeDepth: 0, InnerHashSize: KeySize, IsLastNode: c.lastChunk}})\n\n\t\t_, err := io.Copy(blake, bytes.NewBuffer(c.partBuffer))\n\t\tif err != nil {\n\t\t\t// TODO: fmt.Println(\"Failing to compute hash: \", err)\n\t\t\tresults <- chunkOutput{digest: []byte(\"\"), part: c.part}\n\t\t} else {\n\t\t\tdigest := blake.Sum(nil)\n\t\t\tresults <- chunkOutput{digest: digest, part: c.part}\n\t\t}\n\t}\n}",
"func groupKeysByServer(numServers int, keys []KeyValue) [][]KeyValue {\n\tserverKeys := initServerKeys(numServers)\n\tfor _, k := range keys {\n\t\tif k.Encoding == \"binary\" {\n\t\t\tk.Data = base64.StdEncoding.EncodeToString([]byte(k.Data))\n\t\t}\n\t\tserverIndex := hash(k.Data) % numServers\n\t\tserverKeys[serverIndex] = append(serverKeys[serverIndex], k)\n\t}\n\treturn serverKeys\n}",
"func (f *FileCache) getFileChunksKeys(checksum string) ([]string, error) {\n\tvar keys []string\n\tfileKeys, err := f.memcache.Get(checksum)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get file keys\")\n\t}\n\tchunksKeys := string(fileKeys.Value)\n\tif chunksKeys != \"\" {\n\t\tkeys = strings.Split(chunksKeys, \",\")\n\t}\n\treturn keys, nil\n}",
"func Hash(k []byte) [HashSize]byte {\r\n\thasher := sha1.New()\r\n\thasher.Write(k)\r\n\thashSlice := hasher.Sum(nil)\r\n\tvar hash [HashSize]byte;\r\n\tcopy(hash[:], hashSlice)\r\n\treturn hash\r\n}",
"func SplitByHashSlot(uris []string) [][]string {\n\t// TODO : implement when redis-cluster package is ready\n\treturn nil\n}",
"func determineChunkKeys(step model.InsightStep, from time.Time, count int) []string {\n\tvar to time.Time\n\n\tswitch step {\n\tcase model.InsightStep_YEARLY:\n\t\tto = from.AddDate(count-1, 0, 0)\n\tcase model.InsightStep_MONTHLY:\n\t\tto = from.AddDate(0, count-1, 0)\n\tcase model.InsightStep_WEEKLY:\n\t\tto = from.AddDate(0, 0, (count-1)*7)\n\tcase model.InsightStep_DAILY:\n\t\tto = from.AddDate(0, 0, count-1)\n\t}\n\n\tfrom = time.Date(from.Year(), from.Month(), 1, 0, 0, 0, 0, time.UTC)\n\tto = time.Date(to.Year(), to.Month(), 1, 0, 0, 0, 0, time.UTC)\n\n\tvar keys []string\n\tcur := from\n\tfor !cur.After(to) {\n\t\tkeys = append(keys, cur.Format(\"2006-01\"))\n\t\tcur = cur.AddDate(0, 1, 0)\n\t}\n\treturn keys\n}",
"func main() {\n\tvalues := []string{\"ABC\", \"ACB\", \"BAC\", \"BCA\", \"CAB\", \"CBA\"}\n\t// values := []string{\"to\", \"to\", \"top\", \"ton\", \"tom\"}\n\tfactor := []int{100, 10, 1}\n\n\t// 65x100 + 66x10 + 67x1 = 7227\n\thashKey := 0\n\tfor v := range values {\n\t\tbytes := []byte(values[v])\n\t\tf := 0\n\t\thashKey = 0\n\t\tfor i := range bytes {\n\t\t\tfmt.Print(bytes[i], \" \")\n\t\t\thashKey += int(bytes[i]) * factor[f]\n\t\t\tf++\n\t\t}\n\t\tfmt.Printf(\" (hashKey: %d) \\n\", hashKey)\n\t}\n}",
"func chunk(s string, size int) []string {\n\tvar chunks []string\n\tfor b := []byte(s); len(b) > 0; {\n\t\tn := size\n\t\tif n > len(b) {\n\t\t\tn = len(b)\n\t\t}\n\t\tchunks = append(chunks, string(b[:n]))\n\t\tb = b[n:]\n\t}\n\treturn chunks\n}",
"func chunk(arr []string, size int) [][]string {\n\tif len(arr) == 0 {\n\t\treturn [][]string{}\n\t}\n\n\t// That was easy...\n\tif len(arr) < size {\n\t\treturn [][]string{arr}\n\t}\n\n\tresults := make([][]string, 0)\n\toffset := 0\n\n\tvar current []string\n\n\tfor i := range arr {\n\t\tif i%size == 0 {\n\t\t\tcurrent = make([]string, size)\n\t\t\tresults = append(results, current)\n\n\t\t\tif i > 0 {\n\t\t\t\toffset++\n\t\t\t}\n\t\t}\n\n\t\tcurrent[i%size] = arr[i]\n\t}\n\n\treturn results\n}",
"func generate_keys(key string, round_keys *([]string)) {\n\t// The PC1 table\n\tpc1 := [56]int{\n\t\t57, 49, 41, 33, 25, 17, 9,\n\t\t1, 58, 50, 42, 34, 26, 18,\n\t\t10, 2, 59, 51, 43, 35, 27,\n\t\t19, 11, 3, 60, 52, 44, 36,\n\t\t63, 55, 47, 39, 31, 23, 15,\n\t\t7, 62, 54, 46, 38, 30, 22,\n\t\t14, 6, 61, 53, 45, 37, 29,\n\t\t21, 13, 5, 28, 20, 12, 4,\n\t}\n\t// The PC2 table\n\tpc2 := [48]int{\n\t\t14, 17, 11, 24, 1, 5,\n\t\t3, 28, 15, 6, 21, 10,\n\t\t23, 19, 12, 4, 26, 8,\n\t\t16, 7, 27, 20, 13, 2,\n\t\t41, 52, 31, 37, 47, 55,\n\t\t30, 40, 51, 45, 33, 48,\n\t\t44, 49, 39, 56, 34, 53,\n\t\t46, 42, 50, 36, 29, 32,\n\t}\n\t// 1. Compressing the key using the PC1 table\n\tperm_key := \"\"\n\tfor i := 0; i < 56; i++ {\n\t\tperm_key += string(key[pc1[i]-1])\n\t}\n\t// 2. Dividing the key into two equal halves\n\t// left := perm_key.substr(0, 28)\n\tleft := perm_key[0:28]\n\tright := perm_key[28:56]\n\tfor i := 0; i < 16; i++ {\n\t\t// 3.1. For rounds 1, 2, 9, 16 the key_chunks\n\t\t// are shifted by one.\n\t\tif i == 0 || i == 1 || i == 8 || i == 15 {\n\t\t\tleft = shift_left_once(left)\n\t\t\tright = shift_left_once(right)\n\t\t} else {\n\t\t\t// 3.2. For other rounds, the key_chunks\n\t\t\t// are shifted by two\n\t\t\tleft = shift_left_twice(left)\n\t\t\tright = shift_left_twice(right)\n\t\t}\n\t\t// Combining the two chunks\n\t\tcombined_key := left + right\n\t\tround_key := \"\"\n\t\t// Finally, using the PC2 table to transpose the key bits\n\t\tfor i := 0; i < 48; i++ {\n\t\t\tround_key += string(combined_key[pc2[i]-1])\n\t\t}\n\t\t(*round_keys)[i] = round_key\n\t}\n\n}",
"func Fingerprint(slice []byte) []byte {\n\tfingerprint := make([]byte, 6)\n\tcopy(fingerprint, slice)\n\treturn fingerprint\n}",
"func getStringChunks(items []string, chunkSize int) (chunks [][]string) {\n\tfor chunkSize < len(items) {\n\t\titems, chunks = items[chunkSize:], append(chunks, items[0:chunkSize:chunkSize])\n\t}\n\n\treturn append(chunks, items)\n}",
"func hasher(s string) []byte {\n\tval := sha256.Sum256([]byte(s))\n\tvar hex []string\n\n\t// Iterate through the bytes.\n\tfor i := 0; i < len(val); i++ {\n\t\t// We want each number to be represented by 2 chars.\n\t\tplaceHolder := []string{\"0\"}\n\t\tvalue := strconv.FormatInt(int64(val[i]), 16)\n\n\t\tif len(value) != 2 {\n\t\t\tplaceHolder = append(placeHolder, value)\n\t\t\thex = append(hex, strings.Join(placeHolder, \"\"))\n\t\t} else {\n\t\t\thex = append(hex, value)\n\t\t}\n\t}\n\treturn []byte(strings.Join(hex, \"\"))\n\n}",
"func kdf2(key []byte, length int, h func() hash.Hash) []byte {\n\tkdfHash := h()\n\toutLen := kdfHash.Size()\n\n\tcThreshold := (length + outLen - 1) / outLen\n\tvar counter uint32 = 1\n\toutOff := 0\n\tres := make([]byte, length)\n\tb := make([]byte, 4)\n\tfor i := 0; i < cThreshold; i++ {\n\t\tkdfHash.Write(key)\n\t\tbinary.BigEndian.PutUint32(b, counter)\n\t\tkdfHash.Write(b)\n\t\tcounter++\n\t\tdigest := kdfHash.Sum(nil)\n\n\t\tif length > outLen {\n\t\t\tcopy(res[outOff:], digest[:])\n\t\t\toutOff += outLen\n\t\t\tlength -= outLen\n\t\t} else {\n\t\t\tcopy(res[outOff:], digest[:length])\n\t\t}\n\t\tkdfHash.Reset()\n\t}\n\treturn res\n\n}",
"func Chunk(fileNames []os.FileInfo) [][]string {\n\tchunked := [][]string{}\n\tindex, chunkSize := 0, 100\n\n\tfor i := 0; i < len(fileNames)/chunkSize+1; i++ {\n\t\tsection := make([]string, chunkSize)\n\t\tfor j := 0; j < chunkSize && index < len(fileNames); j++ {\n\t\t\tsection[j] = fileNames[index].Name()\n\t\t\tindex++\n\t\t}\n\t\tchunked = append(chunked, section)\n\t}\n\treturn chunked\n}",
"func sliceKeyHash(k []byte) string {\n\tif k == nil {\n\t\treturn \"\"\n\t}\n\n\th := sha256.New()\n\t_, _ = h.Write(k)\n\treturn hex.EncodeToString(h.Sum(nil))[:6]\n}",
"func fingerprintKey(s string) (fingerprint string, err error) {\n\tdata, err := base64.StdEncoding.DecodeString(s)\n\tif err != nil {\n\t\treturn \"\", errors.New(\"Can't base64 decode original key\")\n\t}\n\tsha256 := sha256.New()\n\tsha256.Write(data)\n\tb64 := base64.StdEncoding.EncodeToString(sha256.Sum(nil))\n\treturn strings.TrimRight(b64, \"=\"), nil\n}",
"func (c *Reader) GetChunk(sha256sum []byte) {\n}",
"func GetBytesSlice1K() []byte {\n\tif p := get1K(); p != nil {\n\t\treturn internal.Puts(p)\n\t}\n\tif b := getb1K(); b != nil {\n\t\treturn internal.Bb2bs(b)\n\t}\n\tp := make([]byte, 1024)\n\treturn p\n}",
"func chunkArrayOfStrings(targetGroupArns []*string, chunkSize int) (chunkedTargetGroupArns [][]*string) {\n\tfor i := 0; i < len(targetGroupArns); i += chunkSize {\n\t\tend := i + chunkSize\n\t\tif end > len(targetGroupArns) {\n\t\t\tend = len(targetGroupArns)\n\t\t}\n\t\tchunkedTargetGroupArns = append(chunkedTargetGroupArns, targetGroupArns[i:end])\n\t}\n\treturn chunkedTargetGroupArns\n}",
"func Split(reader io.Reader, chunkSizeBytes int) []Chunk {\n\tchunks := make([]Chunk, 0)\n\ti := 0\n\n\tfor {\n\t\tbuf := make([]byte, chunkSizeBytes)\n\t\tn, err := reader.Read(buf)\n\t\tbuf = buf[:n]\n\n\t\tif n == 0 {\n\t\t\tif err == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tif err != nil && err != io.EOF {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tchunk := Chunk{\n\t\t\tData: buf,\n\t\t\tOffset: i,\n\t\t\tWeakSum: adler32.Checksum(buf),\n\t\t\tStrongSum: sha256.Sum256(buf),\n\t\t}\n\n\t\tchunks = append(chunks, chunk)\n\n\t\ti += chunkSizeBytes\n\t}\n\n\treturn chunks\n}",
"func SHA1(password, salt []byte, iter, keyLen int) []byte {\n\tprf := hmac.New(sha1.New, password)\n\tnumBlocks := (keyLen + sha1.Size - 1) / sha1.Size\n\n\tvar inner, outer block\n\thmac_init(&inner, &outer, password)\n\n\tvar buf [4]byte\n\tvar tmp block\n\tvar U block\n\tdk := make([]byte, 0, numBlocks*sha1.Size)\n\ttpad := make([]byte, sha1.BlockSize)\n\tfor block := 1; block <= numBlocks; block++ {\n\t\t// N.B.: || means concatenation, ^ means XOR\n\t\t// for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter\n\t\t// U_1 = PRF(password, salt || uint(i))\n\t\tprf.Reset()\n\t\tprf.Write(salt)\n\t\tputUint32(buf[:], uint32(block))\n\t\tprf.Write(buf[:4])\n\t\tdk = prf.Sum(dk)\n\t\tT := dk[len(dk)-sha1.Size:]\n\n\t\t//sha1_input(&tmp, T)\n\t\tfor i := range tmp.h[:5] {\n\t\t\ttmp.h[i] = readUint32(T[i*4:])\n\t\t}\n\t\t// U_n = PRF(password, U_(n-1))\n\t\tcopy(tpad, T)\n\t\tsha1_pad(tpad, sha1.BlockSize+sha1.Size)\n\t\tsha1_input(&U, tpad)\n\t\tfor n := 2; n <= iter; n++ {\n\t\t\tsha1_block(&U, &inner, &U)\n\t\t\tsha1_block(&U, &outer, &U)\n\t\t\ttmp.h[0] ^= U.h[0]\n\t\t\ttmp.h[1] ^= U.h[1]\n\t\t\ttmp.h[2] ^= U.h[2]\n\t\t\ttmp.h[3] ^= U.h[3]\n\t\t\ttmp.h[4] ^= U.h[4]\n\t\t}\n\t\tsha1_output(T, &tmp)\n\t}\n\treturn dk[:keyLen]\n}",
"func calcMultiHash(data string, out chan interface{}) {\n\twg := &sync.WaitGroup{}\n\n\thashes := make([]string, 6)\n\twg.Add(6)\n\tfor i := 0; i < 6; i++ {\n\t\tth := strconv.Itoa(i)\n\t\tgo func(data string, wgForClosingChannel *sync.WaitGroup, index int, hashes []string) {\n\t\t\thash := DataSignerCrc32(data)\n\t\t\thashes[index] = hash\n\t\t\tdefer wgForClosingChannel.Done()\n\t\t}(th+data, wg, i, hashes)\n\t}\n\twg.Wait()\n\n\tresult := strings.Join(hashes, \"\")\n\tout <- result\n}",
"func encodeBytes(data []byte) []byte {\n\t// Allocate more space to avoid unnecessary slice growing.\n\t// Assume that the byte slice size is about `(len(data) / encGroupSize + 1) * (encGroupSize + 1)` bytes,\n\t// that is `(len(data) / 8 + 1) * 9` in our implement.\n\tdLen := len(data)\n\tresult := make([]byte, 0, (dLen/encGroupSize+1)*(encGroupSize+1))\n\tfor idx := 0; idx <= dLen; idx += encGroupSize {\n\t\tremain := dLen - idx\n\t\tpadCount := 0\n\t\tif remain >= encGroupSize {\n\t\t\tresult = append(result, data[idx:idx+encGroupSize]...)\n\t\t} else {\n\t\t\tpadCount = encGroupSize - remain\n\t\t\tresult = append(result, data[idx:]...)\n\t\t\tresult = append(result, pads[:padCount]...)\n\t\t}\n\n\t\tmarker := encMarker - byte(padCount)\n\t\tresult = append(result, marker)\n\t}\n\treturn result\n}",
"func expandHash(data []byte) []byte {\n\tpart0 := sha512.Sum512(append(data, 0))\n\tpart1 := sha512.Sum512(append(data, 1))\n\tpart2 := sha512.Sum512(append(data, 2))\n\tpart3 := sha512.Sum512(append(data, 3))\n\treturn bytes.Join([][]byte{\n\t\tpart0[:],\n\t\tpart1[:],\n\t\tpart2[:],\n\t\tpart3[:],\n\t}, []byte{})\n}",
"func MultiHash(in, out chan interface{}) {\n\twg := &sync.WaitGroup{}\n\n\tfor rawData := range in {\n\t\tsingleHashResult, ok := rawData.(string)\n\t\tif !ok {\n\t\t\tfmt.Print(\"cant convert data to string in MultiHash function\")\n\t\t}\n\n\t\twg.Add(1)\n\n\t\tgo func(wg *sync.WaitGroup, data string, out chan interface{}) {\n\t\t\tcalcMultiHash(data, out)\n\t\t\tdefer wg.Done()\n\t\t}(wg, singleHashResult, out)\n\n\t}\n\twg.Wait()\n}",
"func getHashesFromBytesInput(input []byte, sep string) ([][]byte, int) {\n\tvar hashes = [][]byte{}\n\tvar count int\n\n\t// Create a line reading buffer\n\tlbuf := bytes.NewBuffer(input)\n\tlscan := bufio.NewScanner(lbuf)\n\n\t// Loop on each line and store in array of hashes\n\tfor lscan.Scan() {\n\t\tvar b []byte\n\n\t\tcount = bytes.Count(lscan.Bytes(), []byte(\":\"))\n\n\t\tb = lscan.Bytes()\n\n\t\thashes = append(hashes, b)\n\t}\n\n\t// return what we have\n\treturn hashes, count\n}",
"func getRelHash(r string) [8]int {\n\th1 := sha1.New()\n\th1.Write([]byte(r))\n\tb1 := h1.Sum(nil)\n\tdata1 := b1[0]\n\tid1 := data1 % 4\n\tidint := int(id1)\n\tvar nodelist [8]int\n\tfor k := 0; k < 8; k++ {\n\t\tnodelist[k] = (k * 4) + idint\n\t}\n\t//fmt.Println(\"Nodelist for given relation\", nodelist)\n\treturn nodelist\n}",
"func fingerprint(str []byte) uint64 {\n\tvar hi = hash32(str, 0, len(str), 0)\n\tvar lo = hash32(str, 0, len(str), 102072)\n\tif (hi == 0) && (lo == 0 || lo == 1) {\n\t\t// Turn 0/1 into another fingerprint\n\t\thi ^= 0x130f9bef\n\t\tlo ^= 0x94a0a928\n\t}\n\treturn (uint64(hi) << 32) | uint64(lo&0xffffffff)\n}",
"func sha1Hash(slices [][]byte) []byte {\n\thsha1 := sha1.New()\n\tfor _, slice := range slices {\n\t\thsha1.Write(slice)\n\t}\n\treturn hsha1.Sum(nil)\n}",
"func GetStartingHashs(bds Extrema, minp int) []string {\n\ten := Geohash([]float64{bds.E, bds.N}, minp)\n\tes := Geohash([]float64{bds.E, bds.S}, minp)\n\twn := Geohash([]float64{bds.W, bds.N}, minp)\n\tws := Geohash([]float64{bds.W, bds.S}, minp)\n\n\t// creating map and adding each corner geohash\n\tnewmap := map[string]string{}\n\tnewmap[en] = \"\"\n\tnewmap[es] = \"\"\n\tnewmap[wn] = \"\"\n\tnewmap[ws] = \"\"\n\n\t// starting the iterating process\n\tbdsg := GetExtrema(en)\n\tdeltax := bdsg.E - bdsg.W\n\tdeltay := bdsg.N - bdsg.S\n\tfor i := bds.W; i < bdsg.E; i += deltax {\n\t\tfor j := bds.S; j < bdsg.N; j += deltay {\n\t\t\tghash := Geohash([]float64{i, j}, minp)\n\t\t\tnewmap[ghash] = \"\"\n\t\t}\n\t}\n\tnewlist := make([]string, len(newmap))\n\ti := 0\n\tfor k := range newmap {\n\t\tnewlist[i] = k\n\t\ti++\n\t}\n\treturn newlist\n}",
"func reassembleChunks(chunks *[][]byte) *[]byte {\n\tr := make([]byte, 0)\n\tfor i := 0; i < len(*chunks); i++ {\n\t\tr = append(r, (*chunks)[i]...)\n\t}\n\n\treturn &r\n}",
"func h(s string) []byte {\n\thash := md5.Sum([]byte(s))\n\treturn hash[:]\n}",
"func Generateloads(klen, vlen, n int64) func(k, v []byte) ([]byte, []byte) {\n\tvar textint [1024]byte\n\n\tkeynum := int64(0)\n\treturn func(key, value []byte) ([]byte, []byte) {\n\t\tif keynum >= n {\n\t\t\treturn nil, nil\n\t\t}\n\t\tascii := strconv.AppendInt(textint[:0], int64(keynum), 10)\n\t\t// create key\n\t\tkey = Fixbuffer(key, int64(klen))\n\t\tcopy(key, zeros)\n\t\tcopy(key[klen-int64(len(ascii)):klen], ascii)\n\t\tif value != nil { // create value\n\t\t\tvalue = Fixbuffer(value, int64(vlen))\n\t\t\tcopytovalue(value, ascii, klen, vlen)\n\t\t}\n\n\t\tkeynum++\n\t\treturn key, value\n\t}\n}",
"func Hash(content string, size int) int {\n\tsequence := sliceutil.Atoi(content, \",\")\n\tcircleKnots := GetStringCircle(size)\n\tfor _, n := range sequence {\n\t\tcircleKnots.ComputeKnot(n)\n\t}\n\treturn circleKnots.GetHash()\n}",
"func toEncoded(keys []*datastore.Key) (full []string, roots stringset.Set) {\n\troots = stringset.New(len(keys))\n\tfull = make([]string, len(keys))\n\tfor i, k := range keys {\n\t\troots.Add(string(datastore.Serialize.ToBytes(k.Root())))\n\t\tfull[i] = string(datastore.Serialize.ToBytes(k))\n\t}\n\treturn\n}",
"func FullHash(content string, size int) string {\n\tvar buffer bytes.Buffer\n\tasciiSequence := []byte(content)\n\tbuffer.WriteString(convert(asciiSequence))\n\tif buffer.Len() > 0 {\n\t\tbuffer.WriteString(\",17,31,73,47,23\")\n\t} else {\n\t\tbuffer.WriteString(\"17,31,73,47,23\")\n\t}\n\tsequence := sliceutil.Atoi(buffer.String(), \",\")\n\tcircleKnots := GetStringCircle(size)\n\tfor i := 0; i < 64; i++ {\n\t\tfor _, n := range sequence {\n\t\t\tcircleKnots.ComputeKnot(n)\n\t\t}\n\t}\n\tvar knotHash = \"\"\n\tfor i := 0; i < 256; i++ {\n\t\tvar hexaBlock = circleKnots.list[i]\n\t\tfor j := i + 1; j < i+16; j++ {\n\t\t\thexaBlock ^= circleKnots.list[j]\n\t\t}\n\t\tknotHash = fmt.Sprintf(\"%s%02x\", knotHash, hexaBlock)\n\t\ti += 15\n\t}\n\treturn knotHash\n}",
"func splitInChunks(data []byte, chunksize uint) *[][]byte {\n\tlength := len(data)\n\tremaining := uint(length)\n\n\tchunks := make([][]byte, 0)\n\n\tvar i uint\n\tfor i = 0; remaining > 0; i += chunksize {\n\t\tj := chunksize\n\t\tif j > remaining {\n\t\t\tj = remaining\n\t\t}\n\n\t\tchunks = append(chunks, data[i:i+j])\n\t\tremaining -= j\n\t}\n\n\treturn &chunks\n}",
"func keyify(key string) []byte {\n\th := fnv.New64a()\n\th.Write([]byte(key))\n\tb := make([]byte, 0, 8)\n\treturn h.Sum(b)\n}",
"func TmMerkleHash(chunks []Chunk) Digest { panic(\"\") }",
"func publicKeysHash(publicKeys []kyber.Point) ([]byte) {\n h := testSuite.Hash()\n for i := 0; i < len(publicKeys); i++ {\n publicKeys[i].MarshalTo(h)\n }\n return h.Sum(nil)\n}",
"func groupAnagrams3(strs []string) [][]string {\n\tif len(strs) <= 1 {\n\t\treturn [][]string{strs}\n\t}\n\thash := make(map[int32]int)\n\tvar result [][]string\n\tfor _, str := range strs {\n\t\tvar mul int32 = 1\n\t\tvar sum int32 = 0\n\t\tfor _, r := range str {\n\t\t\tmul *= r\n\t\t\tsum += r\n\t\t}\n\t\tsum += mul\n\t\tif index, ok := hash[sum]; ok {\n\t\t\tresult[index] = append(result[index], str)\n\t\t} else {\n\t\t\thash[sum] = len(result)\n\t\t\tresult = append(result, []string{str})\n\t\t}\n\t}\n\treturn result\n}",
"func allKmers(k int, alphabet []byte) []string {\n\tvar fn func(partial string, length int) []string\n\tfn = func(partial string, length int) []string {\n\t\tif len(partial) == length {\n\t\t\treturn []string{partial}\n\t\t}\n\n\t\tkmers := []string{}\n\t\tfor _, c := range alphabet {\n\t\t\tnewPartial := append([]byte(partial), c)\n\t\t\tkmers = append(kmers, fn(string(newPartial), length)...)\n\t\t}\n\t\treturn kmers\n\t}\n\n\treturn fn(\"\", k)\n}",
"func GetKeyFingerprints(keyData string) (result []string, err string) {\n\tr, e := chevronlib.GetKeyFingerprints(keyData)\n\tresult = r\n\tif e != nil {\n\t\terr = e.Error()\n\t}\n\n\treturn\n}",
"func md5SHA1Hash(slices [][]byte) []byte {\n\tmd5sha1 := make([]byte, md5.Size+sha1.Size)\n\thmd5 := md5.New()\n\tfor _, slice := range slices {\n\t\thmd5.Write(slice)\n\t}\n\tcopy(md5sha1, hmd5.Sum(nil))\n\tcopy(md5sha1[md5.Size:], sha1Hash(slices))\n\treturn md5sha1\n}",
"func CreateChunks(scfg config.SchemaConfig, startIndex, batchSize int, from model.Time, through model.Time) ([]string, []chunk.Chunk, error) {\n\tkeys := []string{}\n\tchunks := []chunk.Chunk{}\n\tfor j := 0; j < batchSize; j++ {\n\t\tchunk := DummyChunkFor(from, through, labels.Labels{\n\t\t\t{Name: model.MetricNameLabel, Value: \"foo\"},\n\t\t\t{Name: \"index\", Value: strconv.Itoa(startIndex*batchSize + j)},\n\t\t})\n\t\tchunks = append(chunks, chunk)\n\t\tkeys = append(keys, scfg.ExternalKey(chunk.ChunkRef))\n\t}\n\treturn keys, chunks, nil\n}",
"func htkey_hash_str(k1 voidptr, len int) usize {\n\tvar k1p byteptr = (byteptr)(k1)\n\tvar hash usize\n\n\thash = 0 + 5381 + len + 1\n\tfor i := 0; i < len; i++ {\n\t\tc := k1p[i]\n\t\thash = ((hash << 5) + hash) ^ usize(c)\n\t}\n\n\treturn hash\n}",
"func ChunkSplit(s string)(r string, err error){\n const LENTH = 76\n var bfr, bfw *bytes.Buffer\n var data, block []byte\n\n data = make([]byte, 0)\n block = make([]byte, LENTH)\n bfr = bytes.NewBufferString(s)\n bfw = bytes.NewBuffer(data)\n var l int\n for {\n l, err = bfr.Read(block)\n if err == io.EOF{\n err = nil\n break\n }\n if err != nil{\n return\n }\n _, err = bfw.Write(block[:l])\n if err != nil{\n return\n }\n _, err = bfw.WriteString(\"\\r\\n\")\n if err != nil{\n return\n }\n }\n r = bfw.String()\n return\n}",
"func blake2HashFromFileUUID(fileUUID []string) ([64]byte, error) {\n\tvar buffer bytes.Buffer\n\tencoder := gob.NewEncoder(&buffer)\n\n\terr := encoder.Encode(fileUUID)\n\tif err != nil {\n\t\treturn [64]byte{}, err\n\t}\n\treturn blake2b.Sum512(buffer.Bytes()), nil\n}",
"func groupAnagrams2(strs []string) [][]string {\n\thash := make(map[string]int)\n\tvar result [][]string\n\tkey := make([]rune, 26)\n\tfor _, str := range strs {\n\t\tfor _, r := range str {\n\t\t\tkey[r-'a']++\n\t\t}\n\t\tstrKey := string(key)\n\t\tif index, ok := hash[strKey]; ok {\n\t\t\tresult[index] = append(result[index], str)\n\t\t} else {\n\t\t\thash[strKey] = len(result)\n\t\t\tresult = append(result, []string{str})\n\t\t}\n\t}\n\treturn result\n}",
"func groupedBytes(s string, size int) string {\n\tgroups := make([]string, 0, (len(s)/size + 1))\n\n\tfor len(s) >= size {\n\t\tgroups = append(groups, s[:size])\n\t\ts = s[size:]\n\t}\n\n\tif len(s) > 0 {\n\t\tgroups = append(groups, s)\n\t}\n\n\treturn strings.Join(groups, \" \")\n}",
"func (an *analysisNode) cacheKey() [sha256.Size]byte {\n\thasher := sha256.New()\n\n\t// In principle, a key must be the hash of an\n\t// unambiguous encoding of all the relevant data.\n\t// If it's ambiguous, we risk collisions.\n\n\t// analyzers\n\tfmt.Fprintf(hasher, \"analyzers: %d\\n\", len(an.analyzers))\n\tfor _, a := range an.analyzers {\n\t\tfmt.Fprintln(hasher, a.Name)\n\t}\n\n\t// package metadata\n\tm := an.m\n\tfmt.Fprintf(hasher, \"package: %s %s %s\\n\", m.ID, m.Name, m.PkgPath)\n\t// We can ignore m.DepsBy{Pkg,Import}Path: although the logic\n\t// uses those fields, we account for them by hashing vdeps.\n\n\t// type sizes\n\twordSize := an.m.TypesSizes.Sizeof(types.Typ[types.Int])\n\tmaxAlign := an.m.TypesSizes.Alignof(types.NewPointer(types.Typ[types.Int64]))\n\tfmt.Fprintf(hasher, \"sizes: %d %d\\n\", wordSize, maxAlign)\n\n\t// metadata errors: used for 'compiles' field\n\tfmt.Fprintf(hasher, \"errors: %d\", len(m.Errors))\n\n\t// module Go version\n\tif m.Module != nil && m.Module.GoVersion != \"\" {\n\t\tfmt.Fprintf(hasher, \"go %s\\n\", m.Module.GoVersion)\n\t}\n\n\t// file names and contents\n\tfmt.Fprintf(hasher, \"files: %d\\n\", len(an.files))\n\tfor _, fh := range an.files {\n\t\tfmt.Fprintln(hasher, fh.FileIdentity())\n\t}\n\n\t// vdeps, in PackageID order\n\tdepIDs := make([]string, 0, len(an.succs))\n\tfor depID := range an.succs {\n\t\tdepIDs = append(depIDs, string(depID))\n\t}\n\tsort.Strings(depIDs) // TODO(adonovan): avoid conversions by using slices.Sort[PackageID]\n\tfor _, depID := range depIDs {\n\t\tvdep := an.succs[PackageID(depID)]\n\t\tfmt.Fprintf(hasher, \"dep: %s\\n\", vdep.m.PkgPath)\n\t\tfmt.Fprintf(hasher, \"export: %s\\n\", vdep.summary.DeepExportHash)\n\n\t\t// action results: errors and facts\n\t\tactions := vdep.summary.Actions\n\t\tnames := make([]string, 0, len(actions))\n\t\tfor name := range actions {\n\t\t\tnames = append(names, name)\n\t\t}\n\t\tsort.Strings(names)\n\t\tfor _, name := range names {\n\t\t\tsummary := actions[name]\n\t\t\tfmt.Fprintf(hasher, \"action %s\\n\", name)\n\t\t\tif summary.Err != \"\" {\n\t\t\t\tfmt.Fprintf(hasher, \"error %s\\n\", summary.Err)\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(hasher, \"facts %s\\n\", summary.FactsHash)\n\t\t\t\t// We can safely omit summary.diagnostics\n\t\t\t\t// from the key since they have no downstream effect.\n\t\t\t}\n\t\t}\n\t}\n\n\tvar hash [sha256.Size]byte\n\thasher.Sum(hash[:0])\n\treturn hash\n}",
"func Fingerprint(labels []*remote.LabelPair) uint64 {\n\tif len(labels) == 0 {\n\t\treturn offset64\n\t}\n\n\tsum := offset64\n\tfor _, l := range labels {\n\t\tsum = hashAdd(sum, l.Name)\n\t\tsum = hashAddByte(sum, separatorByte)\n\t\tsum = hashAdd(sum, l.Value)\n\t\tsum = hashAddByte(sum, separatorByte)\n\t}\n\treturn sum\n}",
"func bruteForceKey(cipherText []byte, minKeyLength int, maxKeyLength int) ([]byte, []byte) {\n\n\t_, bestBlocks := findBlockSize(cipherText, minKeyLength, maxKeyLength)\n\n\t//This will effectively be the transpose of the matrix so that each of the bytes that use the same key byte will be together\n\t//This will allow us to use existing code to brute force them.\n\tsingleByteGroups := make([][]byte, len(bestBlocks[0]))\n\t//transpose the matrix... First byte of each will use same key, so we will brute force them together.\n\tfor i := 0; i < len(bestBlocks[0]); i++ {\n\t\tgroup := make([]byte, len(bestBlocks))\n\t\tsingleByteGroups[i] = group\n\t\tfor j, block := range bestBlocks {\n\t\t\tgroup[j] = block[i]\n\t\t}\n\t}\n\n\tkey := make([]byte, len(singleByteGroups))\n\tfor i, group := range singleByteGroups {\n\t\tgroup, groupKey, _ := bruteForceSingleByte(group)\n\t\tsingleByteGroups[i] = group\n\t\tkey = append(key, groupKey)\n\t\tfmt.Println(singleByteGroups[i])\n\t}\n\tfmt.Println(hex.Dump(singleByteGroups[0]))\n\t//transpose the matrix back. First byte of each will use same key, so we will brute force them together.\n\tfmt.Println(\"\")\n\tfmt.Println(hex.Dump(bestBlocks[0]))\n\tfor i, group := range singleByteGroups {\n\t\tfor j, block := range bestBlocks {\n\t\t\tblock[i] = group[j]\n\t\t\tbestBlocks[j] = block\n\t\t}\n\t}\n\n\tplainText := make([]byte, len(cipherText))\n\tfor _, block := range bestBlocks {\n\t\tplainText = append(plainText, block...)\n\t}\n\t//fmt.Println(hex.Dump(plainText))\n\t//fmt.Println(hex.Dump(key))\n\treturn plainText, key\n}",
"func ArrayStringChunk(arr []string, size int) [][]string {\n\tvar chunks [][]string\n\tarrSize := len(arr)\n\tfor i := 0; i < arrSize; i += size {\n\t\tend := i + size\n\t\tif arrSize < end {\n\t\t\tend = arrSize\n\t\t}\n\t\tchunks = append(chunks, arr[i:end])\n\t}\n\treturn chunks\n}",
"func (c *sigCache) key(rrs []dns.RR) string {\n\th := sha1.New()\n\ti := []byte(rrs[0].Header().Name)\n\ti = append(i, packUint16(rrs[0].Header().Rrtype)...)\n\tfor _, r := range rrs {\n\t\tswitch t := r.(type) { // we only do a few type, serialize these manually\n\t\tcase *dns.SOA:\n\t\t\ti = append(i, packUint32(t.Serial)...)\n\t\t\t// we only fiddle with the serial so store that\n\t\tcase *dns.SRV:\n\t\t\ti = append(i, packUint16(t.Priority)...)\n\t\t\ti = append(i, packUint16(t.Weight)...)\n\t\t\ti = append(i, packUint16(t.Weight)...)\n\t\t\ti = append(i, []byte(t.Target)...)\n\t\tcase *dns.A:\n\t\t\ti = append(i, []byte(t.A)...)\n\t\tcase *dns.AAAA:\n\t\t\ti = append(i, []byte(t.AAAA)...)\n\t\tcase *dns.DNSKEY:\n\t\t\t// Need nothing more, the rdata stays the same during a run\n\t\tcase *dns.NSEC:\n\t\t\ti = append(i, []byte(t.NextDomain)...)\n\t\t\t// bitmap does not differentiate\n\t\tdefault:\n\t\t\tlog.Printf(\"DNS Signature for unhandled type %T seen\", t)\n\t\t}\n\t}\n\treturn string(h.Sum(i))\n}",
"func marshalData(t testing.TB, tree map[string]string) (map[string]string, []byte) {\n\tsha1tree := map[string]string{}\n\tentries := &dumbcaslib.Entry{}\n\tfor k, v := range tree {\n\t\th := dumbcaslib.Sha1Bytes([]byte(v))\n\t\tsha1tree[k] = h\n\t\te := entries\n\t\tparts := strings.Split(k, \"/\")\n\t\tfor i := 0; i < len(parts)-1; i++ {\n\t\t\tif e.Files == nil {\n\t\t\t\te.Files = map[string]*dumbcaslib.Entry{}\n\t\t\t}\n\t\t\tif e.Files[parts[i]] == nil {\n\t\t\t\te.Files[parts[i]] = &dumbcaslib.Entry{}\n\t\t\t}\n\t\t\te = e.Files[parts[i]]\n\t\t}\n\t\tif e.Files == nil {\n\t\t\te.Files = map[string]*dumbcaslib.Entry{}\n\t\t}\n\t\te.Files[parts[len(parts)-1]] = &dumbcaslib.Entry{\n\t\t\tSha1: h,\n\t\t\tSize: int64(len(v)),\n\t\t}\n\t}\n\n\t// Then process entries itself.\n\tdata, err := json.Marshal(entries)\n\tut.AssertEqual(t, nil, err)\n\treturn sha1tree, data\n}",
"func serializeTicketHashes(ths TicketHashes) []byte {\n\tb := make([]byte, len(ths)*chainhash.HashSize)\n\toffset := 0\n\tfor _, th := range ths {\n\t\tcopy(b[offset:offset+chainhash.HashSize], th[:])\n\t\toffset += chainhash.HashSize\n\t}\n\n\treturn b\n}",
"func mkKey(data []byte) string {\n\tif n := len(data); n >= hashLen {\n\t\treturn string(data[:n-hashLen])\n\t}\n\treturn \"\" // invalid data\n}",
"func HashPermsSHA3(toHash []string) []string {\n\thashed := []string{}\n\n\t// get the private key from file\n\tpkSecret, err := ioutil.ReadFile(\"../../../private.ppk\") // in form of byte\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// iterates through toHash and hashes them all\n\tfor i := 0; i < len(toHash); i++ {\n\t\th := make([]byte, 32)\n\t\td := sha3.NewShake256()\n\t\t// Write the key into the hash.\n\t\td.Write(pkSecret)\n\t\t// Now write the data.\n\t\td.Write([]byte(toHash[i]))\n\t\t// Read 32 bytes of output from the hash into h.\n\t\td.Read(h)\n\t\tfmt.Printf(\"%x\\n\", h)\n\n\t\thashString := fmt.Sprintf(\"%x\\n\", h)\n\t\tfmt.Println(\"Hash casted to string is\", hashString)\n\n\t\t// add the new hash to the slice\n\t\thashed = append(hashed, hashString)\n\t}\n\treturn hashed\n}",
"func ChunkStringArray(array []string, chunkSize int) (divided [][]string) {\n\tfor i := 0; i < len(array); i += chunkSize {\n\t\tend := i + chunkSize\n\n\t\tif end > len(array) {\n\t\t\tend = len(array)\n\t\t}\n\n\t\tdivided = append(divided, array[i:end])\n\t}\n\treturn\n}",
"func makeSomeUniqueKeys(N, K int) (rawKeys [][]byte, bKeys []BytesKey) {\n\n\trng := xr.MakeSimpleRNG()\n\trawKeys = make([][]byte, N)\n\tbKeys = make([]BytesKey, N)\n\tkeyMap := make(map[uint64]bool)\n\n\tfor i := 0; i < N; i++ {\n\t\tvar bKey BytesKey\n\t\tkey := make([]byte, K)\n\t\tfor {\n\t\t\trng.NextBytes(key)\n\t\t\tbKey, _ = NewBytesKey(key)\n\t\t\thc := bKey.Hashcode()\n\t\t\t_, ok := keyMap[hc]\n\t\t\tif !ok { // value is not in the map\n\t\t\t\tkeyMap[hc] = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\trawKeys[i] = key\n\t\tbKeys[i] = bKey\n\t}\n\treturn\n}",
"func deserializeUserInvalTickets(serializedTickets []byte) ([]*chainhash.Hash, error) {\n\t// Cursory check to make sure that the number of records\n\t// makes sense.\n\tif len(serializedTickets)%chainhash.HashSize != 0 {\n\t\terr := io.ErrUnexpectedEOF\n\t\treturn nil, err\n\t}\n\n\tnumRecords := len(serializedTickets) / chainhash.HashSize\n\n\trecords := make([]*chainhash.Hash, numRecords)\n\n\t// Loop through all the ssgen records, deserialize them, and\n\t// store them.\n\tfor i := 0; i < numRecords; i++ {\n\t\tstart := i * chainhash.HashSize\n\t\tend := (i + 1) * chainhash.HashSize\n\t\th, err := chainhash.NewHash(serializedTickets[start:end])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\trecords[i] = h\n\t}\n\n\treturn records, nil\n}",
"func hkdfExpand(hash func() hash.Hash, prk, info []byte, length int) []byte {\n\thashSize := hash().Size()\n\tif length > 255*hashSize {\n\t\tpanic(\"hkdfExpand: length too long\")\n\t}\n\tif len(prk) < hashSize {\n\t\tpanic(\"hkdfExpand: prk too short\")\n\t}\n\tvar lastBlock []byte\n\tcounter := byte(0)\n\tokm := make([]byte, length)\n\thmac := hmac.New(hash, prk)\n\tfor length > 0 {\n\t\thmac.Reset()\n\t\tcounter++\n\t\thmac.Write(lastBlock)\n\t\thmac.Write(info)\n\t\thmac.Write([]byte{counter})\n\t\tblock := hmac.Sum(nil)\n\t\tlastBlock = block\n\t\tcopy(okm[(int(counter)-1)*hashSize:], block)\n\t\tlength -= hashSize\n\t}\n\treturn okm\n}",
"func makeSomeUniqueKeys(N, K int) (rawKeys [][]byte, bKeys []gh.BytesKey) {\n\n\trng := xr.MakeSimpleRNG()\n\trawKeys = make([][]byte, N)\n\tbKeys = make([]gh.BytesKey, N)\n\tkeyMap := make(map[uint64]bool)\n\n\tfor i := 0; i < N; i++ {\n\t\tvar bKey gh.BytesKey\n\t\tkey := make([]byte, K)\n\t\tfor {\n\t\t\trng.NextBytes(key)\n\t\t\tbKey, _ = gh.NewBytesKey(key)\n\t\t\thc := bKey.Hashcode()\n\t\t\t_, ok := keyMap[hc]\n\t\t\tif !ok { // value is not in the map\n\t\t\t\tkeyMap[hc] = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\trawKeys[i] = key\n\t\tbKeys[i] = bKey\n\t}\n\treturn\n}",
"func xx512x1(inner_512 []byte) [20]byte {\n\touter_512 := sha512.Sum512(inner_512)\n\treturn sha1.Sum(outer_512[:])\n}",
"func getSequentialFileContent() (string, map[int]compareFunc) {\n\tsb := strings.Builder{}\n\texpectedLines := make(map[int]compareFunc)\n\n\tfor i := 0; i < 1000000; i++ {\n\t\tline := fmt.Sprintf(`{ \"line\": \"%d\", \"id\": \"i%d\", data: \"some event %d\" }`, i, i, i)\n\t\tsb.WriteString(line)\n\t\tsb.WriteString(\"\\n\")\n\n\t\texpectedLines[i] = equals(line)\n\t}\n\n\treturn sb.String(), expectedLines\n}",
"func getClaimSignatureDigest(bytes ...[]byte) [32]byte {\n\n\tvar combined []byte\n\tfor _, b := range bytes {\n\t\tcombined = append(combined, b...)\n\t}\n\tdigest := sha256.Sum256(combined)\n\treturn [32]byte(digest)\n}",
"func GetMerkleRootHash(input [][]byte) []byte {\n\tif len(input) == 0 {\n\t\treturn []byte{} //return an empty slice\n\t}\n\t//first add all the slices to a list\n\tl := list.New()\n\tfor _, s := range input {\n\t\t//while pushing elements to the list, double hash them\n\t\tl.PushBack(New(New(s)))\n\t}\n\treturn getMerkleRoot(l)\n}",
"func fingerprint(cm *v1.ConfigMap) uint64 {\n\thash := fnv.New64a()\n\tdata := json.NewEncoder(hash)\n\tdata.Encode(cm.Labels)\n\tdata.Encode(cm.Data)\n\treturn hash.Sum64()\n}",
"func (ee ee) ReaderHashes(pd []byte) (readers [][]byte, err error) {\n\tconst op errors.Op = \"pack/ee.ReaderHashes\"\n\tvar d packdata\n\tif err := d.Unmarshal(pd); err != nil {\n\t\treturn nil, errors.E(op, errors.Invalid, err)\n\t}\n\treaders = make([][]byte, len(d.wrap))\n\tfor i := 0; i < len(d.wrap); i++ {\n\t\treaders[i] = d.wrap[i].keyHash\n\t}\n\treturn readers, nil\n}",
"func MerkleTree(inputHashes []Hash, hasher Hasher) []Hash {\n // don't mutate the input\n hashes := make([]Hash, len(inputHashes), len(inputHashes) * 2)\n copy(hashes, inputHashes)\n // each row of the tree is half the length of the previous row until\n // reaching the root row of one hash\n for ii := len(hashes); ii > 1; ii /= 2 {\n // if a row has an odd number of hashes, duplicate the last hash for a\n // clean halving\n if ii % 2 != 0 {\n hashes = append(hashes, hashes[len(hashes)-1])\n ii++\n }\n // for each pair of hashes in the current row, compute the hash of the\n // concatenation of the two hashes and append the resulting hash to the\n // new tree row\n newRow := make([]Hash, 0, 8)\n for jj := ii; jj > 0; jj -= 2 {\n hashA := hashes[len(hashes)-jj]\n hashB := hashes[len(hashes)-(jj-1)]\n hashC := hasher.Hash(bytes.Join(\n [][]byte{ hashA.Bytes(), hashB.Bytes() }, nil))\n newRow = append(newRow, hashC)\n }\n // add the new tree row to the tree\n hashes = append(hashes, newRow...)\n }\n\n return hashes\n}",
"func MapElgamalCiphersChunked(f func([2]kyber.Point, [2]kyber.Point, kyber.Point) ([2]kyber.Point, [2]kyber.Point, proof.Prover), x [][2]kyber.Point, y [][2]kyber.Point, Y kyber.Point, n int) ([][2]kyber.Point, [][2]kyber.Point, []proof.Prover) {\n return MapElgamalCiphers(ForChunked, f, x, y, Y, n)\n}",
"func GetBytesSlicePtr1K() *[]byte {\n\tif p := get1K(); p != nil {\n\t\treturn p\n\t}\n\tif b := getb1K(); b != nil {\n\t\tp := internal.Bb2bs(b)\n\t\treturn internal.Gets(p)\n\t}\n\tp := make([]byte, 1024)\n\treturn &p\n}",
"func (ids identities) getPub1s() [][2]string {\n\tpubKeys := make([][2]string, len(ids))\n\tfor i := 0; i < len(ids); i++ {\n\t\tpubKeys[i] = ids[i].pub1.ToHex()\n\t}\n\treturn pubKeys\n}",
"func serializeUserInvalTickets(records []*chainhash.Hash) []byte {\n\tnumRecords := len(records)\n\n\tbuf := make([]byte, numRecords*chainhash.HashSize)\n\n\t// Serialize and write each record into the slice sequentially.\n\tfor i := 0; i < numRecords; i++ {\n\t\tstart := i * chainhash.HashSize\n\t\tend := (i + 1) * chainhash.HashSize\n\t\tcopy(buf[start:end], records[i][:])\n\t}\n\n\treturn buf\n}",
"func getGPGIdFromKeyData(idReader gpgIDReader, key string) []string {\n\tdecodeKey, err := base64.StdEncoding.DecodeString(key)\n\tif err != nil {\n\t\tlogrus.Errorf(\"%s, error decoding key data\", err)\n\t\treturn nil\n\t}\n\ttmpfileName, err := createTmpFile(\"\", \"\", decodeKey)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Creating key date temp file %s\", err)\n\t}\n\tdefer os.Remove(tmpfileName)\n\treturn idReader(tmpfileName)\n}",
"func (lx LXRHash) HashParallel(base []byte, batch [][]byte) [][]byte {\n\tvar work []*HashParallelItem\n\tfor _, src := range batch {\n\t\twork = append(work, &HashParallelItem{\n\t\t\tsrc: src,\n\t\t\tas: lx.Seed,\n\t\t\ths: make([]uint64, lx.HashSize),\n\t\t})\n\t}\n\n\tmk := lx.MapSize - 1\n\n\tB := func(v uint64) uint64 { return uint64(lx.ByteMap[v&mk]) }\n\tb := func(v uint64) byte { return byte(B(v)) }\n\n\tsource := func(work *HashParallelItem, i int) byte {\n\t\tif i < len(base) {\n\t\t\treturn base[i]\n\t\t}\n\t\treturn work.src[i-len(base)]\n\t}\n\n\tfaststep := func(work []*HashParallelItem, i int, idx uint64) {\n\t\tfor _, h := range work {\n\t\t\tv2 := uint64(source(h, i))\n\t\t\tb := B(h.as ^ v2)\n\t\t\th.as = h.as<<7 ^ h.as>>5 ^ v2<<20 ^ v2<<16 ^ v2 ^ b<<20 ^ b<<12 ^ b<<4\n\t\t\th.s1 = h.s1<<9 ^ h.s1>>3 ^ h.hs[idx]\n\t\t\th.hs[idx] = h.s1 ^ h.as\n\t\t\th.s1, h.s2, h.s3 = h.s3, h.s1, h.s2\n\t\t}\n\t}\n\n\tstep := func(work []*HashParallelItem, i int, idx uint64, reduce bool) {\n\t\tfor _, h := range work {\n\t\t\tif reduce {\n\t\t\t\th.v2 = uint64(h.hs[i])\n\t\t\t} else {\n\t\t\t\th.v2 = uint64(source(h, i))\n\t\t\t}\n\t\t\th.s1 = h.s1<<9 ^ h.s1>>1 ^ h.as ^ B(h.as>>5^h.v2)<<3\n\t\t}\n\n\t\tfor _, h := range work {\n\t\t\th.s1 = h.s1<<5 ^ h.s1>>3 ^ B(h.s1^h.v2)<<7\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.s1 = h.s1<<7 ^ h.s1>>7 ^ B(h.as^h.s1>>7)<<5\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.s1 = h.s1<<11 ^ h.s1>>5 ^ B(h.v2^h.as>>11^h.s1)<<27\n\t\t\th.hs[idx] = h.s1 ^ h.as ^ h.hs[idx]<<7 ^ h.hs[idx]>>13\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.as = h.as<<17 ^ h.as>>5 ^ h.s1 ^ B(h.as^h.s1>>27^h.v2)<<3\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.as = h.as<<13 ^ h.as>>3 ^ B(h.as^h.s1)<<7\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.as = h.as<<15 ^ h.as>>7 ^ B(h.as>>7^h.s1)<<11\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.as = h.as<<9 ^ h.as>>11 ^ B(h.v2^h.as^h.s1)<<3\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.s1 = h.s1<<7 ^ h.s1>>27 ^ h.as ^ B(h.as>>3)<<13\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.s1 = h.s1<<3 ^ h.s1>>13 ^ B(h.s1^h.v2)<<11\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.s1 = h.s1<<8 ^ h.s1>>11 ^ B(h.as^h.s1>>11)<<9\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.s1 = h.s1<<6 ^ h.s1>>9 ^ B(h.v2^h.as^h.s1)<<3\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.as = h.as<<23 ^ h.as>>3 ^ h.s1 ^ B(h.as^h.v2^h.s1>>3)<<7\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.as = h.as<<17 ^ h.as>>7 ^ B(h.as^h.s1>>3)<<5\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.as = h.as<<13 ^ h.as>>5 ^ B(h.as>>5^h.s1)<<1\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.as = h.as<<11 ^ h.as>>1 ^ B(h.v2^h.as^h.s1)<<7\n\t\t}\n\n\t\tfor _, h := range work {\n\t\t\th.s1 = h.s1<<5 ^ h.s1>>3 ^ h.as ^ B(h.as>>7^h.s1>>3)<<6\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.s1 = h.s1<<8 ^ h.s1>>6 ^ B(h.s1^h.v2)<<11\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.s1 = h.s1<<11 ^ h.s1>>11 ^ B(h.as^h.s1>>11)<<5\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.s1 = h.s1<<7 ^ h.s1>>5 ^ B(h.v2^h.as>>7^h.as^h.s1)<<17\n\t\t}\n\n\t\tfor _, h := range work {\n\t\t\th.s2 = h.s2<<3 ^ h.s2>>17 ^ h.s1 ^ B(h.as^h.s2>>5^h.v2)<<13\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.s2 = h.s2<<6 ^ h.s2>>13 ^ B(h.s2)<<11\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.s2 = h.s2<<11 ^ h.s2>>11 ^ B(h.as^h.s1^h.s2>>11)<<23\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.s2 = h.s2<<4 ^ h.s2>>23 ^ B(h.v2^h.as>>8^h.as^h.s2>>10)<<1\n\t\t\th.s1 = h.s2<<3 ^ h.s2>>1 ^ h.hs[idx] ^ h.v2\n\t\t}\n\t\tfor _, h := range work {\n\t\t\th.as = h.as<<9 ^ h.as>>7 ^ h.s1>>1 ^ B(h.s2>>1^h.hs[idx])<<5\n\t\t\th.s1, h.s2, h.s3 = h.s3, h.s1, h.s2\n\t\t}\n\n\t}\n\n\tidx := uint64(0)\n\t// Fast spin to prevent caching state\n\tfor i := 0; i < len(base)+len(work[0].src); i++ {\n\t\tif idx >= lx.HashSize { // Use an if to avoid modulo math\n\t\t\tidx = 0\n\t\t}\n\t\tfaststep(work, i, idx)\n\t\tidx++\n\t}\n\n\tidx = 0\n\t// Actual work to compute the hash\n\tfor i := 0; i < len(base)+len(work[0].src); i++ {\n\t\tif idx >= lx.HashSize { // Use an if to avoid modulo math\n\t\t\tidx = 0\n\t\t}\n\t\tstep(work, i, idx, false)\n\t\tidx++\n\t}\n\n\tret := make([][]byte, len(batch))\n\tfor i := range ret {\n\t\tret[i] = make([]byte, lx.HashSize)\n\t}\n\n\tfor i := int64(lx.HashSize - 1); i >= 0; i-- {\n\t\tstep(work, int(i), uint64(i), true) // Step the hash functions and then\n\t\tfor j, h := range work {\n\t\t\tret[j][i] = b(h.as) ^ b(h.hs[i]) // Xor two resulting sequences\n\t\t}\n\t}\n\n\t// Return the resulting hash\n\treturn ret\n}",
"func GeneratePartitions(input string, num int, erule ERule) ([][]string, bool) {\n\tinputSlice := []rune(input)\n\n\t// set condition to finish recursive\n\t// true: generated successfully\n\t// false: cannot be partitoined\n\tif num == 0 {\n\t\tif len(inputSlice) == 0 {\n\t\t\treturn [][]string{}, true\n\t\t} else {\n\t\t\treturn [][]string{}, false\n\t\t}\n\t} else {\n\t\tif erule == HasERule && num == 1 && input == \"\" {\n\t\t\treturn [][]string{\n\t\t\t\t{\"\"},\n\t\t\t}, true\n\t\t} else if erule == NoERule && num > len(inputSlice) {\n\t\t\treturn [][]string{}, false\n\t\t}\n\t}\n\n\t// startIdx depends on e-rule\n\tvar startIdx int\n\tif erule == HasERule && num != 1 {\n\t\tstartIdx = 0\n\t} else {\n\t\tstartIdx = 1\n\t}\n\n\t/* combine current string and next sub string into result*/\n\t/* current string = \"xx\" */\n\t/* next string = [][]string{\n\t\t[]string{\"a\", \"bc\"},\n\t\t[]string{\"ab\", \"c\"},\n\t}\n\t res string = [][]string{\n\t\t[]string{\"xx\", \"a\", \"bc\"},\n\t\t[]string{\"xx\", \"ab\", \"c\"},\n\t }\n\t*/\n\tvar res = [][]string{}\n\tN := len(inputSlice)\n\tfor i := startIdx; i <= N; i++ {\n\t\tcurRes := inputSlice[0:i]\n\t\tnxtRes, ok := GeneratePartitions(string(inputSlice[i:N]), num-1, erule)\n\t\tif ok == true {\n\t\t\t// nxtRes length is 0\n\t\t\tif len(nxtRes) == 0 {\n\t\t\t\tcombRes := []string{string(curRes)}\n\t\t\t\tres = append(res, combRes)\n\t\t\t\t// nxtRes length > 0\n\t\t\t} else {\n\t\t\t\tfor _, nxt := range nxtRes {\n\t\t\t\t\tcombRes := []string{string(curRes)}\n\t\t\t\t\tcombRes = append(combRes, nxt...)\n\t\t\t\t\tres = append(res, combRes)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn res, true\n}",
"func PutBytesSlice1K(p []byte) bool {\n\tif l := cap(p); l < 1024 || l >= 2048 {\n\t\treturn PutBytesSlice(p)\n\t}\n\tp = p[0:1024]\n\tput1K(internal.Gets(p))\n\treturn true\n}",
"func Hashes(r Roller, p []byte) []uint64 {\n\tn := r.Len()\n\tif len(p) < n {\n\t\treturn nil\n\t}\n\th := make([]uint64, len(p)-n+1)\n\tfor i := 0; i < n-1; i++ {\n\t\tr.RollByte(p[i])\n\t}\n\tfor i := range h {\n\t\th[i] = r.RollByte(p[i+n-1])\n\t}\n\treturn h\n}",
"func updateStringEntries(f *Forest, baseHash primitives.MerkleSha256, keyValues ...string) primitives.MerkleSha256 {\n\tif len(keyValues)%2 != 0 {\n\t\tpanic(\"expected key value pairs\")\n\t}\n\tcurrentRoot := baseHash\n\tfor i := 0; i < len(keyValues); i = i + 2 {\n\t\tcurrentRoot = f.updateSingleEntry(currentRoot, keyValues[i], hash.CalcSha256([]byte(keyValues[i+1])))\n\t}\n\treturn currentRoot\n}",
"func main() {\n\tvar buffer bytes.Buffer\n\tvar validHash = regexp.MustCompile(`^0{5}.*$`)\n\tcount := 0\n\tinput := \"ugkcyxxp\"\n\n\tfor len(buffer.String()) < 8 {\n\t\ttmp := md5.Sum([]byte(fmt.Sprintf(\"%s%d\", input, count)))\n\t\tif str := hex.EncodeToString(tmp[:]); validHash.MatchString(str) {\n\t\t\tbuffer.WriteByte(str[5])\n\t\t}\n\t\tcount++\n\t}\n\n\tfmt.Println(buffer.String())\n}",
"func SplitBytesByMod(inputBytes []byte, modulus int) (splitBytes [][]byte) {\n\t// Break the input bytes into N arrays\n\tsplitBytes = make([][]byte, modulus)\n\tfor i := 0; i < len(inputBytes); i++ {\n\t\tsplitBytes[i%modulus] = append(splitBytes[i%modulus], inputBytes[i])\n\t}\n\treturn splitBytes\n}",
"func TestHasher(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tkey uint64\n\t\tbucket []int\n\t}{\n\t\t// Generated from the reference C++ code\n\t\t{0, []int{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},\n\t\t{1, []int{0, 0, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 17, 17}},\n\t\t{0xdeadbeef, []int{0, 1, 2, 3, 3, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 16, 16, 16}},\n\t\t{0x0ddc0ffeebadf00d, []int{0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 15, 15, 15, 15}},\n\t} {\n\t\tfor i, v := range tt.bucket {\n\t\t\thasher := &jmphasher{}\n\t\t\tif got := hasher.Hash(tt.key, i+1); got != v {\n\t\t\t\tt.Errorf(\"hash(%v,%v)=%v, want %v\", tt.key, i+1, got, v)\n\t\t\t}\n\t\t}\n\t}\n}",
"func filenodehash(filename string,ch string,nodenum int64,readbitlen int64) []byte{\n\t//H(ch)is parsed into k indexes.\n\t//Calculate the hash value HCH of ch\n\tvar Hch string = GetSHA256HashCodeString(ch)\n\tvar Hchbyte, _ = hex.DecodeString(Hch)\n\t//Hch,_ := hex.DecodeString(ch)\n\tfmt.Println(\"Hch is \", Hch)\n\tfmt.Println(\"Hchbyte is \", Hchbyte)\n\t//Convert Hch to 01 string\n\tvar Hchstring string = biu.ToBinaryString(Hchbyte)\n\t//remove all \"[\"\n\tHchstring = strings.Replace(Hchstring, \"[\", \"\", -1)\n\t//remove all \"]\"\n\tHchstring = strings.Replace(Hchstring, \"]\", \"\", -1)\n\t//remove all space\n\tHchstring = strings.Replace(Hchstring, \" \", \"\", -1)\n\tfmt.Println(\"Hchstring is \", Hchstring)\n\t//convert nodenum to 01\n\tvar bittosting string = biu.ToBinaryString(nodenum)\n\n\tbittosting = strings.Replace(bittosting, \"[\", \"\", -1)\n\tbittosting = strings.Replace(bittosting, \"]\", \"\", -1)\n\tbittosting = strings.Replace(bittosting, \" \", \"\", -1)\n\tvar stringlen = len(bittosting)\n\n\tfmt.Println(\"nodenum is \", bittosting)\n\tfmt.Println(\"stringlen is \", stringlen)\n\n\tvar stringiter int = 0\n\tvar zerolen int = 0\n\tfor stringiter = 0; stringiter < stringlen; stringiter++ {\n\t\tif '0' != bittosting[stringiter] {\n\t\t\t//zerolen = stringiter + 1\n\t\t\tzerolen = stringiter\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfmt.Println(\"zerolen is \", zerolen)\n\n\n\n\t//The calculation requires eachlen bits to represent the total number of leaf nodes.\n\t//For example, if the number of leaf nodes is 245441, 17 bits are needed to represent it\n\tvar eachlen uintptr = ((unsafe.Sizeof(nodenum) * 8) - uintptr(zerolen))\n\tfmt.Println(\"eachlen is \", eachlen)\n\n\n\n\t//由Hchstring切割得到原文件序号\n\tvar fileposition []int64\n\t//将Hchstring的bit字符串按每eachlen一份进行切割,生成[]string\n\tvar Hcharray []string = ChunkString(Hchstring, int(eachlen))\n\t//fmt.Println(\"chunkarray is \", chunkarray)\n\tvar filebititer int = 0\n\tfor filebititer = 0; filebititer < len(Hcharray); filebititer++ {\n\t\tvar tmpint int64 = 0\n\t\tvar partiter int = 0\n\t\tfor partiter = 0; partiter < len(Hcharray[filebititer]); partiter++ {\n\t\t\ttmpint = (tmpint << 1)\n\t\t\tif '1' == Hcharray[filebititer][partiter] {\n\t\t\t\ttmpint = (tmpint) ^ 1\n\t\t\t}\n\t\t\tif tmpint >= nodenum {\n\t\t\t\ttmpint = tmpint % nodenum\n\t\t\t}\n\n\t\t}\n\t\tfileposition = append(fileposition, tmpint)\n\t}\n\n\tfmt.Println(\"fileposition is \", fileposition)\n\tfileposition = RemoveRepeatedElement(fileposition)\n\tfmt.Println(\"fileposition is \", fileposition)\n\tvar fileretdata []byte\n\t//retdata, _ := ReadBlock(filename, readbitlen, 0*readbitlen)\n\t//fmt.Println(\"000000000000retdata is \", retdata)\n\tvar readiter int\n\tfor readiter = 0; readiter < len(fileposition); readiter++ {\n\t\t//fmt.Println(\"readiter is \", readiter)\n\t\t//fmt.Println(\"now fileposition is \", fileposition[readiter])\n\t\tretdata, _ := ReadBlock(filename, readbitlen, (fileposition[readiter])*readbitlen)\n\t\t//fmt.Println(\"retdata is \", retdata)\n\t\tfor _,nounceum := range retdata{\n\t\t\tfileretdata=append(fileretdata,nounceum)\n\t\t}\n\n\t}\n\tfmt.Println(\"fileretdata is \", fileretdata)\n\tfileretdata_hash := GetSHA256HashCode([]byte(fileretdata))\n\n\tvar filebyte_hash []byte\n\tfilebyte_hash, _ = hex.DecodeString(fileretdata_hash)\n\tfmt.Println(\"filebyte_hash is \", filebyte_hash)\n\treturn filebyte_hash\n\n}",
"func fixedHashGetNodesFunc(ids []NodeID) [][]byte {\n\thashes := make([][]byte, len(ids))\n\tfor i := range ids {\n\t\thashes[i] = []byte(\"12345678901234567890123456789012\")\n\t}\n\treturn hashes\n}",
"func TestMemKeynames(t *testing.T) {\n\t// setup\n\tmb := newMemBlobs()\n\t// exercise\n\tfor _, testCase := range testData {\n\t\tkey := blobKey(sha1.New(), ([]byte)(testCase.input))\n\t\tassert(key.Equals(toKeyOrDie(t, testCase.expectedHash)), t,\n\t\t\t\"Input's '%s' expected hash was %s but got %s!\", testCase.input, testCase.expectedHash, key)\n\t\tkeyname := mb.Keyname(key)\n\t\tassert(keyname == testCase.expectedHash, t,\n\t\t\t\"Input's '%s' expected keyname was:\\n%s\\nBut got:\\n%s\", testCase.input, testCase.expectedHash, keyname)\n\t}\n}",
"func (pr *PkgDecoder) Fingerprint() [8]byte {\n\tvar fp [8]byte\n\tcopy(fp[:], pr.elemData[len(pr.elemData)-8:])\n\treturn fp\n}",
"func ChunkStrings(targets []string, chunkSize int) [][]string {\n\tvar chunks [][]string\n\tfor i := 0; i < len(targets); i += chunkSize {\n\t\tend := i + chunkSize\n\t\tif end > len(targets) {\n\t\t\tend = len(targets)\n\t\t}\n\t\tchunks = append(chunks, targets[i:end])\n\t}\n\treturn chunks\n}",
"func (cache *Cache) Keys () []string {\n keys := make([]string, len(cache.FilePrints))\n n := 0;\n for k := range cache.FilePrints { keys[n] = k; n++ }\n if len(keys) > 1 { sort.Strings(keys) }\n return keys\n}",
"func makeKey(objId string, sliceId uint32, id blizstorage.ChunkIdentity, field string) []byte {\r\n\r\n\tif bytes.Equal(id[:], sliceDBNilChunkId[:]) {\r\n\t\treturn []byte(field)\r\n\t}\r\n\r\n\t// blizstorage.ChunkIdentity2Int(id)\r\n\tpart := fmt.Sprintf(\"%s:%d:%s\", objId, sliceId, field)\r\n\r\n\treturn append(sliceDBItemPrefix, append(id[:], part...)...)\r\n}",
"func getkey(ciphers []string) []int{\n\tN := len(ciphers[len(ciphers)-1])\n\tvar keys []int\n\tfor i := 0; i < N; i+=2 {\n\t\tvar sample []int\n\t\tfor j := 0; j < len(ciphers); j++ {\n\t\t\tsample = append(sample,formSample(ciphers[j][i:i+2]))\n\t\t}\n\t\tkey := findKey(sample)\n\t\tkeys = append(keys,key)\n\t}\n\treturn keys\n}",
"func keyextend(mac mac, data, digest, suffix []byte, maxlen int) (guesshash, msg []byte) {\n\tregs := sha1regs(digest)\n\tfor i := 1; i <= maxlen; i++ {\n\t\tmsg = append(data, sha1glue(i+len(data))...)\n\t\tmsg = append(msg, suffix...)\n\t\tguesshash = sha1sum(suffix, regs, i+len(msg))\n\t\tif mac.valid(guesshash, msg) {\n\t\t\treturn guesshash, msg\n\t\t}\n\t}\n\treturn nil, nil\n}",
"func SplitEach(data []byte, n int) (chunks [][]byte) {\n\tif n <= 0 {\n\t\tchunks = append(chunks, data)\n\t\treturn chunks\n\t}\n\n\tvar (\n\t\tsize = len(data)\n\t\trows = (size / n)\n\t\ttotal int\n\t)\n\tfor x := 0; x < rows; x++ {\n\t\tchunks = append(chunks, data[total:total+n])\n\t\ttotal += n\n\t}\n\tif total < size {\n\t\tchunks = append(chunks, data[total:])\n\t}\n\treturn chunks\n}"
] | [
"0.5811624",
"0.5636826",
"0.5601441",
"0.55719113",
"0.54282063",
"0.5416999",
"0.53885263",
"0.53736913",
"0.5303537",
"0.5296824",
"0.5251822",
"0.52308726",
"0.5208301",
"0.52032715",
"0.5174986",
"0.5139402",
"0.5128886",
"0.5120651",
"0.50604546",
"0.4995872",
"0.49872482",
"0.49826565",
"0.49819952",
"0.49813405",
"0.49690232",
"0.4959375",
"0.49571812",
"0.4953045",
"0.4951313",
"0.49324882",
"0.49272183",
"0.4917112",
"0.49149317",
"0.49124327",
"0.49074838",
"0.4904082",
"0.48984197",
"0.48629737",
"0.48501253",
"0.4838185",
"0.48255587",
"0.4816556",
"0.48034868",
"0.47980818",
"0.4789062",
"0.4786568",
"0.47809082",
"0.4778006",
"0.47737515",
"0.4756166",
"0.47502655",
"0.473657",
"0.47237554",
"0.47165784",
"0.47146714",
"0.47128958",
"0.4707049",
"0.47029173",
"0.46944982",
"0.46943185",
"0.4689742",
"0.4681807",
"0.46799344",
"0.4666745",
"0.46643293",
"0.46616825",
"0.46581244",
"0.4656415",
"0.46514326",
"0.46508372",
"0.46387437",
"0.46277148",
"0.46270093",
"0.46259072",
"0.46224436",
"0.46031037",
"0.45995817",
"0.45835805",
"0.45761052",
"0.4573725",
"0.4572403",
"0.4557074",
"0.45504367",
"0.45503557",
"0.4530524",
"0.45224956",
"0.45210147",
"0.45205155",
"0.45194972",
"0.45153844",
"0.45084137",
"0.4499804",
"0.44969097",
"0.44945",
"0.44936895",
"0.4489259",
"0.44862363",
"0.44847926",
"0.44819686",
"0.44812146"
] | 0.48362434 | 40 |
puts a block of data at key defined by hash of data. Return ASCII hash. | func putBlock(data []byte) string {
sig := shaString(data)
if err := putBlockSig(sig, data); err == nil {
db.Put([]byte(sig), data, nil)
return sig
} else {
panic(fmt.Sprintf("FAIL: putBlock(%s): [%q]\n", sig, err))
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (s *DHT) hashKey(data []byte) []byte {\n\tsha := sha3.Sum256(data)\n\treturn sha[:]\n}",
"func (e *Encoder) PutHash(h hash.Hash) {\n\te.write(h[:])\n}",
"func Put(key string, value string){\n \n h := sha256.New()\n h.Write([]byte(value))\n sha := base64.URLEncoding.EncodeToString(h.Sum(nil))\n \n //fmt.Println(sha)\n var n Data \n \n n.val = value //storing key value in keyValue hash map\n n.hash = sha // storing key hash in keyHash hash map \n \n keyValue[key] = n\n}",
"func hash(key string) int{\n\tvar num = 0\n\t// get the lenght of the key\n\tvar length = len(key)\n\n\t// add the ascii character value to creat a sum \n\tfor i := 0; i < length; i++{\n\n\t\tnum += int(key[i])\n\t}\n\t\n\t// square in the middle hash method\n\tvar avg = num * int((math.Pow(5.0, 0.5) - 1)) / 2\n\tvar numeric = avg - int(math.Floor(float64(avg)))\n\n\n\t// hash value to place into the table slice between -1 and CAPACITY - 1\n\treturn int(math.Floor(float64(numeric * CAPACITY)))\n}",
"func (ref *Hash) Hash(src []byte, dst []byte) {\n\toutHash := get_x16rv3_order(src)\n\tin := ref.tha[:]\n\tcopy(in[:], outHash[:])\n\tout := ref.thb[:]\n\tfor i := 0; i < 16; i++ {\n\t\tswitch x16rv3_hashOrder[i] {\n\t\tcase BLAKE:\n\t\t\tref.blake.Write(in)\n\t\t\tref.blake.Close(out, 0, 0)\n\t\t\tcopy(in, out)\n\t\tcase BMW:\n\t\t\tref.bmw.Write(in)\n\t\t\tref.bmw.Close(out, 0, 0)\n\t\t\tcopy(in, out)\n\t\tcase GROESTL:\n\t\t\tref.groestl.Write(in)\n\t\t\tref.groestl.Close(out, 0, 0)\n\t\t\tcopy(in, out)\n\t\tcase SKEIN:\n\t\t\tref.skein.Write(in)\n\t\t\tref.skein.Close(out, 0, 0)\n\t\t\tcopy(in, out)\n\t\tcase JH:\n\t\t\tref.jh.Write(in)\n\t\t\tref.jh.Close(out, 0, 0)\n\t\t\tcopy(in, out)\n\t\tcase KECCAK:\n\t\t\tref.keccak.Write(in)\n\t\t\tref.keccak.Close(out, 0, 0)\n\t\t\tcopy(in, out)\n\t\tcase LUFFA:\n\t\t\tref.luffa.Write(in)\n\t\t\tref.luffa.Close(out, 0, 0)\n\t\t\tcopy(in, out)\n\t\tcase CUBEHASH:\n\t\t\tref.cubehash.Write(in)\n\t\t\tref.cubehash.Close(out, 0, 0)\n\t\t\tcopy(in, out)\n\t\tcase SHAVITE:\n\t\t\tref.shavite.Write(in)\n\t\t\tref.shavite.Close(out, 0, 0)\n\t\t\tcopy(in, out)\n\t\tcase SIMD:\n\t\t\tref.simd.Write(in)\n\t\t\tref.simd.Close(out, 0, 0)\n\t\t\tcopy(in, out)\n\t\tcase ECHO:\n\t\t\tref.echo.Write(in)\n\t\t\tref.echo.Close(out, 0, 0)\n\t\t\tcopy(in, out)\n\t\tcase HAMSI:\n\t\t\thamsi.Sph_hamsi512_process(in[:], out[:], 64)\n\t\t\tcopy(in, out)\n\t\tcase FUGUE:\n\t\t\tfugue.Sph_fugue512_process(in[:], out[:], 64)\n\t\t\tcopy(in, out)\n\t\tcase SHABAL:\n\t\t\tshabal.Shabal_512_process(in[:], out[:], 64)\n\t\t\tcopy(in, out)\n\t\tcase WHIRLPOOL:\n\t\t\twh := whirlpool.New()\n\t\t\twh.Write(in)\n\t\t\tout = wh.Sum(nil)\n\t\t\tcopy(in, out)\n\t\tcase SHA512:\n\t\t\tsha := sha512.New()\n\t\t\tsha.Write(in)\n\t\t\tout = sha.Sum(nil)\n\t\t\tcopy(in, out)\n\t\t}\n\t}\n\tcopy(dst, in[:len(dst)])\n}",
"func Hash(data []byte) (string, int64) {\n\thasher := adler32.New()\n\tb, e := hasher.Write(data)\n\tif e != nil {\n\t\tlogs.WithFields(logs.Fields{\n\t\t\t\"Error\": e,\n\t\t}).Error(\"Unable to write chunk of data via hasher.Write\", e)\n\t}\n\treturn hex.EncodeToString(hasher.Sum(nil)), int64(b)\n}",
"func (h Hasher) Hash(data []byte) []byte {\n\thf := h.New()\n\tif hf == nil {\n\t\treturn nil\n\t}\n\thf.Write(data)\n\treturn hf.Sum(nil)\n}",
"func (h Hash) Bytes() []byte { return h[:] }",
"func (h Hash) Bytes() []byte { return h[:] }",
"func Hash(data interface{}) string {\n\treturn hex.EncodeToString(RawHash(data))\n}",
"func (h Hash20) Bytes() []byte { return h[:] }",
"func (p BnetAuthCheckPacket) KeyHash(index int) string {\n\tconst keyOffset = 24\n\tconst keyLen = 4 * 9\n\toffset := keyOffset + index*keyLen + 8\n\thashBytes := p[offset : offset+4]\n\treturn hex.EncodeToString(hashBytes)\n}",
"func (t *openAddressing) hash(key string, round int) uint32 {\n\tnum := uint(stringToInt(key))\n\tmax := uint(len(t.values) - 1)\n\treturn uint32((hashDivision(num, max) + uint(round)*hashDivision2(num, max)) % max)\n}",
"func hashData(src io.Reader) (string, error) {\n\th := sha256.New()\n\tif _, err := io.Copy(h, src); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn \"sha256:\" + hex.EncodeToString(h.Sum(nil)), nil\n}",
"func (id *Public) hash() []byte {\n\treturn hashHelper(id.SigningKey.SerializeUncompressed(),\n\t\tid.EncryptionKey.SerializeUncompressed())\n}",
"func (u *UFlat) PutData(data []byte, key []byte) (\n\tlength int64, hash []byte, err error) {\n\n\tif key == nil {\n\t\terr = NilKey\n\t} else {\n\t\tvar strHash string\n\t\tstrKey := hex.EncodeToString(key)\n\t\tswitch len(strKey) {\n\t\tcase xu.SHA1_HEX_LEN:\n\t\t\tlength, strHash, err = u.PutData1(data, strKey)\n\t\tcase xu.SHA3_HEX_LEN:\n\t\t\tlength, strHash, err = u.PutData3(data, strKey)\n\t\tdefault:\n\t\t\terr = BadKeyLength\n\t\t}\n\t\tif err == nil {\n\t\t\thash, err = hex.DecodeString(strHash)\n\t\t}\n\t}\n\treturn\n}",
"func hashSum(data io.Reader, h hash.Hash) (io.Reader, error) {\n\tif _, err := io.Copy(h, data); err != nil {\n\t\treturn nil, err\n\t}\n\treturn strings.NewReader(hex.EncodeToString(h.Sum(nil))), nil\n}",
"func (h *hmacsha256) Write(p []byte) {\n\th.inner.Write(p)\n}",
"func (hm HMACHasher) Hash(str string) string {\n\th := hm.p.Get().(hash.Hash)\n\tif _, err := h.Write([]byte(str)); err != nil {\n\t\t// Write() on hash never fails\n\t\tpanic(err)\n\t}\n\n\treturn base64.StdEncoding.EncodeToString(h.Sum(nil))\n}",
"func byteshash(p *[]byte, h uintptr) uintptr",
"func hash(obj interface{}) KHash {\n\tvar buffer bytes.Buffer\n\tencoder := json.NewEncoder(&buffer)\n\terr := encoder.Encode(obj)\n\tif err != nil {\n\t\tpanic(\"cannot encode object\")\n\t}\n\n\tdata := buffer.Bytes()\n\th := sha256.Sum256(data)\n\n\t// log.Printf(\"hashing %#v represented as %s with hash %X\", obj, data, h)\n\treturn h\n}",
"func hashKey(b []byte) string {\n\th := sha1.New() // #nosec G401 Used only to generate random value to be used to generate hash string\n\t_, err := h.Write(b)\n\n\tif err != nil {\n\t\tklog.Error(\"Failed to hash key with error:\", err)\n\t}\n\n\treturn string(h.Sum(nil))\n}",
"func (h dataUsageHash) Key() string {\n\treturn string(h)\n}",
"func hash(key, value string) int64 {\n\thash := siphash.New(sipConst)\n\thash.Write([]byte(key + \":::\" + value))\n\treturn int64(hash.Sum64())\n}",
"func (s *DHT) Store(ctx context.Context, data []byte) (string, error) {\n\tkey := s.hashKey(data)\n\n\t// replicate time for the key\n\treplication := time.Now().Add(defaultReplicateTime)\n\n\t// store the key to local storage\n\tif err := s.store.Store(ctx, key, data, replication); err != nil {\n\t\treturn \"\", fmt.Errorf(\"store data to local storage: %v\", err)\n\t}\n\n\t// iterative store the data\n\tif _, err := s.iterate(ctx, IterateStore, key, data); err != nil {\n\t\treturn \"\", fmt.Errorf(\"iterative store data: %v\", err)\n\t}\n\n\treturn base58.Encode(key), nil\n}",
"func (tt Hash) Bytes() []byte {\n return tt[:]\n}",
"func Hash(length int, key string) int64 {\n\tif key == \"\" {\n\t\treturn 0\n\t}\n\thc := hashCode(key)\n\treturn (hc ^ (hc >> 16)) % int64(length)\n}",
"func (tt *TtTable) hash(key position.Key) uint64 {\n\treturn uint64(key) & tt.hashKeyMask\n}",
"func (hash Hash) String() string {\n\treturn BytesString(hash[:])\n}",
"func hashKey(b []byte) string {\n\th := sha1.New()\n\t_, err := h.Write(b)\n\n\tif err != nil {\n\t\tklog.Error(\"Failed to hash key with error:\", err)\n\t}\n\n\treturn string(h.Sum(nil))\n}",
"func RawHash(data interface{}) []byte {\n\tvar databuf []byte\n\tswitch dataImpl := data.(type) {\n\tcase []byte:\n\t\tdatabuf = dataImpl\n\tcase HashBytes:\n\t\tdatabuf = dataImpl[:]\n\tcase string:\n\t\tdatabuf = []byte(dataImpl)\n\tdefault:\n\t\tpanic(\"unknown type\")\n\t}\n\thash := sha3.New256()\n\thash.Write(databuf)\n\tvar buf []byte\n\treturn hash.Sum(buf)\n}",
"func (z *Block) MarshalHash() (o []byte, err error) {\n\tvar b []byte\n\to = hsp.Require(b, z.Msgsize())\n\t// map header, size 4\n\to = append(o, 0x84)\n\to = hsp.AppendArrayHeader(o, uint32(len(z.Acks)))\n\tfor za0003 := range z.Acks {\n\t\tif z.Acks[za0003] == nil {\n\t\t\to = hsp.AppendNil(o)\n\t\t} else {\n\t\t\tif oTemp, err := z.Acks[za0003].MarshalHash(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t} else {\n\t\t\t\to = hsp.AppendBytes(o, oTemp)\n\t\t\t}\n\t\t}\n\t}\n\to = hsp.AppendArrayHeader(o, uint32(len(z.FailedReqs)))\n\tfor za0001 := range z.FailedReqs {\n\t\tif z.FailedReqs[za0001] == nil {\n\t\t\to = hsp.AppendNil(o)\n\t\t} else {\n\t\t\tif oTemp, err := z.FailedReqs[za0001].MarshalHash(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t} else {\n\t\t\t\to = hsp.AppendBytes(o, oTemp)\n\t\t\t}\n\t\t}\n\t}\n\to = hsp.AppendArrayHeader(o, uint32(len(z.QueryTxs)))\n\tfor za0002 := range z.QueryTxs {\n\t\tif z.QueryTxs[za0002] == nil {\n\t\t\to = hsp.AppendNil(o)\n\t\t} else {\n\t\t\tif oTemp, err := z.QueryTxs[za0002].MarshalHash(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t} else {\n\t\t\t\to = hsp.AppendBytes(o, oTemp)\n\t\t\t}\n\t\t}\n\t}\n\t// map header, size 2\n\to = append(o, 0x82)\n\tif oTemp, err := z.SignedHeader.Header.MarshalHash(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\to = hsp.AppendBytes(o, oTemp)\n\t}\n\tif oTemp, err := z.SignedHeader.HSV.MarshalHash(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\to = hsp.AppendBytes(o, oTemp)\n\t}\n\treturn\n}",
"func (k *Kademlia) HandleHash() {\n\tfor {\n\t\tcmd := <-k.hashchannel\n\t\tnumber := cmd.cmd\n\t\tswitch number {\n\t\tcase 1:\n\t\t\tk.hash[cmd.key] = cmd.value\n\t\tcase 2:\n\t\t\tresult, ok := k.hash[cmd.key]\n\t\t\tcmd.returnchannel <- hashreturn{result, ok}\n\t\t}\n\t}\n}",
"func (h *ihash) Write(b []byte) (int, error) {\n\terr := h.s.Sendto(b, unix.MSG_MORE, h.addr)\n\treturn len(b), err\n}",
"func Key(hash *chainhash.Hash) [gcs.KeySize]byte {\n\tvar key [gcs.KeySize]byte\n\tcopy(key[:], hash[:])\n\treturn key\n}",
"func doSum(h hash.Hash, b []byte, data ...[]byte) ([]byte, error) {\n\th.Reset()\n\tfor _, v := range data {\n\t\tvar err error\n\t\t_, err = h.Write(v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn h.Sum(b), nil\n}",
"func (h Hash) String() string { return hex.EncodeToString(h[:]) }",
"func encodeKeyHash(verPublicKeyHash []byte, checkSum []byte) string {\n\n\ts := \"START encodeKeyHash() - Encodes verPublicKeyHash & checkSum\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\t// 7 - CONCAT\n\taddressHex := append(verPublicKeyHash, checkSum...)\n\ts = \"7 - CONCAT \" + hex.EncodeToString(addressHex)\n\tlog.Info(\"WALLET: GUTS \" + s)\n\n\t// 8 - BASE58 ENCODING\n\tjeffCoinAddressHex := base58.Encode(addressHex)\n\ts = \"8 - BASE58 ENCODING \" + jeffCoinAddressHex\n\tlog.Info(\"WALLET: GUTS \" + s)\n\n\ts = \"END encodeKeyHash() - Encodes verPublicKeyHash & checkSum\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\treturn jeffCoinAddressHex\n\n}",
"func (h *Hash) Write(p []byte) (n int, err error) {\n\treturn h.hmac.Write(p)\n}",
"func blockHashKey(number uint64) []byte {\n\treturn append(append(blockPrefix, encodeBlockNumber(number)...), blockHashSuffix...)\n}",
"func blockKey(number uint64, hash ibft.Hash) []byte {\n\treturn append(append(blockPrefix, encodeBlockNumber(number)...), hash.Bytes()...)\n}",
"func (cb *cachedBatch) hash(namespace string, key []byte) hash.CacheHash {\n\tstream := hash.Hash160b([]byte(namespace))\n\tstream = append(stream, key...)\n\treturn byteutil.BytesToCacheHash(hash.Hash160b(stream))\n}",
"func (rh *RefHasher) hash(data []byte, length int) []byte {\n\tvar section []byte\n\tif length == rh.sectionLength {\n\t\t// section contains two data segments (d)\n\t\tsection = data\n\t} else {\n\t\t// section contains hashes of left and right BMT subtreea\n\t\t// to be calculated by calling hash recursively on left and right half of d\n\t\tlength /= 2\n\t\tsection = append(rh.hash(data[:length], length), rh.hash(data[length:], length)...)\n\t}\n\trh.hasher.Reset()\n\trh.hasher.Write(section)\n\treturn rh.hasher.Sum(nil)\n}",
"func (h Hash) Str() string { return string(h[:]) }",
"func Hash(key []byte) uint64 {\n\treturn murmur3.Sum64(key)\n}",
"func (h *ConsistentHash) dohash(key string) uint32 {\n\treturn h.hash([]byte(key))\n}",
"func hash(key string) int {\n\tsum := 0\n\tfor _, v := range key {\n\t\tsum += int(v)\n\t}\n\n\treturn sum\n}",
"func Hash(key string) uint32 {\n\treturn uint32(aeshashstr(noescape(unsafe.Pointer(&key)), 0))\n}",
"func (d *Data)ComputeHash(k int, s string) {\n\n time.Sleep(5 * time.Second)\n\n h := sha512.New()\n h.Write([]byte(s))\n val := base64.StdEncoding.EncodeToString(h.Sum(nil))\n\n mutex.Lock()\n d.hashMap[k] = val\n d.inProgressCount--\n mutex.Unlock()\n}",
"func (h dataUsageHash) String() string {\n\treturn string(h)\n}",
"func calculateHash(index int, previousHash string, timestamp int64, data transaction.Transaction) string {\n\tvar foo = strconv.Itoa(index) + string(previousHash) + strconv.Itoa(int(timestamp)) + hex.EncodeToString(data.Id)\n\tinput :=strings.NewReader(foo)\n\tvar newHash = sha256.New()\n\tif _, err := io.Copy(newHash, input); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn hex.EncodeToString(newHash.Sum(nil))\n}",
"func hash(data []byte) [32]byte {\n\tvar hash [32]byte\n\n\th := sha256.New()\n\t// The hash interface never returns an error, for that reason\n\t// we are not handling the error below. For reference, it is\n\t// stated here https://golang.org/pkg/hash/#Hash\n\t// #nosec G104\n\th.Write(data)\n\th.Sum(hash[:0])\n\n\treturn hash\n}",
"func (h *MemHash) Write(bb []byte) {\n\th.buf = append(h.buf, bb...)\n}",
"func (h Hash32) Bytes() []byte { return h[:] }",
"func calculateHash(block Block) string {\n\n\t// Time and vehicle identifier (v5c) are the key block items to generate the hash\n\trecord := string(string(block.Index) + block.Timestamp + block.Event.PerformedOnVehicle.V5c + block.PrevHash)\n\th := sha256.New()\n\th.Write([]byte(record))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}",
"func SdscHash(htype byte, data []byte, lenData int) ([]byte, uint, error) {\n\t//80 08 00 00 07 09 00\n\tcommand := []byte{0x80, 0x08, 0x00, 0x00, byte(lenData + 2), 0x09, byte(htype)}\n\tcommand = append(command, data...)\n\tcHash := make([]byte, 34)\t//0x9000\n\tvar respLen uint\n\tvar err error\n\n\tif respLen, err = Sdsc_SendAPDUA(command, len(command), cHash, 0, 2); err != nil {\n\t\tfmt.Println(\"sdsc error, ret \", err)\n\t\treturn nil, 0, err\n\t}\n\n\tfmt.Printf(\"sdsc hash result: %x, len %d \\n\", cHash, respLen)\n\treturn cHash, respLen, nil\n}",
"func hash(key uint64) uint64 {\r\n\tkey ^= key >> 33\r\n\tkey *= 0xff51afd7ed558ccd\r\n\tkey ^= key >> 33\r\n\tkey *= 0xc4ceb9fe1a85ec53\r\n\tkey ^= key >> 33\r\n\treturn key\r\n}",
"func (gen *IDGenerator) Hash(string) string {\n\tid := <-gen.ch\n\treturn strconv.FormatUint(id, 10)\n}",
"func (h *Key) Hex() string { return strings.ToLower(hex.EncodeToString(h[:])) }",
"func (p *Pool) Put(h *Hasher) {\n\tp.c <- h.bmt\n}",
"func blockIndexKey(blockHash *common.Hash, blockHeight uint32) []byte {\n\tindexKey := make([]byte, common.HashLength+4)\n\tbinary.BigEndian.PutUint32(indexKey[0:4], blockHeight)\n\tcopy(indexKey[4:common.HashLength+4], blockHash[:])\n\treturn indexKey\n}",
"func (h Hash) String() string {\n\treturn fmt.Sprintf(\"%032x\", []byte(h))\n}",
"func (b BlockChain) Hash() {\n\n}",
"func Hash(data []byte) {\n\tfor i := 0; i < 50; i++ {\n\t\tsha256.Sum256(data)\n\t}\n}",
"func (kvStore *KVStore) Lookup(hash KademliaID) (output []byte, err error) {\n kvStore.mutex.Lock()\n if val, ok := kvStore.mapping[hash]; ok {\n output = val.data\n } else {\n err = NotFoundError\n }\n kvStore.mutex.Unlock()\n return\n}",
"func op_BLOCKHASH(pc *uint64, in *interpreter, ctx *callCtx) uint64 {\n\tnum := ctx.stack.Peek()\n\tnum64, overflow := num.Uint64WithOverflow()\n\tif overflow {\n\t\tnum.Clear()\n\t}\n\tvar upper, lower uint64\n\tupper = in.evm.block.NumberU64()\n\tif upper < 257 {\n\t\tlower = 0\n\t} else {\n\t\tlower = upper - 256\n\t}\n\tif num64 >= lower && num64 < upper {\n\t\tnum.SetBytes(in.evm.block.Hash().Bytes())\n\t} else {\n\t\tnum.Clear()\n\t}\n\treturn 0\n}",
"func calculateHash(block Block) string {\n\trecord := strconv.Itoa(block.Index) + block.Timestamp + strconv.Itoa(block.Key) + block.PrevHash\n\th := sha256.New()\n\th.Write([]byte(record))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}",
"func hashFunc(blockSize int, key Key) int {\n\th := 0\n\tfor i := 0; i < len(key); i++ {\n\t\th = 31*h + int(key[i])\n\t}\n\treturn h % blockSize\n}",
"func HashASM(k0, k1 uint64, p []byte) uint64",
"func (d *keyData) write(w io.Writer) error {\n\tif _, err := tpm2.MarshalToWriter(w, keyDataHeader, d); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func memhash(p unsafe.Pointer, h, s uintptr) uintptr",
"func memhash(p unsafe.Pointer, h, s uintptr) uintptr",
"func ihash(key string) int {\n\th := fnv.New32a()\n\th.Write([]byte(key))\n\treturn int(h.Sum32() & 0x7fffffff) % 10\n}",
"func Hash(data []byte) [blake2b.Size]byte {\n\treturn blake2b.Sum512(data)\n}",
"func (h Hash) Bytes() []byte {\n\treturn h[:]\n}",
"func keyHash(k crypto.Key) ([]byte, error) {\n\tkb, err := k.Bytes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th, _ := mh.Sum(kb, mh.SHA2_256, -1)\n\treturn []byte(h), nil\n}",
"func (g *generator) Write(data []byte) (int, error) {\n\tg.lock.Lock()\n\tdefer g.lock.Unlock()\n\n\tg.key = DoubleHash(g.h, g.key, data)\n\tg.counter.incr()\n\tg.initialized = true\n\treturn len(data), nil\n}",
"func (k Key) Hash() []byte {\n\tsum := sha256.Sum256(k)\n\treturn sum[:]\n}",
"func (db *CDB) Data(key []byte) (val []byte, err error) {\n\t// catch array range checks, etc.\n\tdefer func() {\n\t\tif val := recover(); val != nil {\n\t\t\tconst size = 4096\n\t\t\tbuf := make([]byte, size)\n\t\t\tbuf = buf[:runtime.Stack(buf, false)]\n\t\t\tlog.Printf(\"cdb: panic finding %v: %v\\n%s\", key, val, buf)\n\t\t\t// set named return value\n\t\t\tif perr, ok := val.(error); ok {\n\t\t\t\terr = perr\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"cdb: panic in find: %v\", val)\n\t\t\t}\n\t\t}\n\t}()\n\n\thashcode := uint32(5381)\n\tfor _, c := range key {\n\t\thashcode = ((hashcode << 5) + hashcode) ^ uint32(c)\n\t}\n\n\theader := db.header[hashcode&0xff]\n\tif header.nslots == 0 {\n\t\treturn nil, ErrNotFound\n\t}\n\n\ttable := db.data[header.pos : header.pos+header.nslots*slotWidth]\n\n\tslot := ((hashcode >> 8) % header.nslots) * slotWidth\n\n\t// prevent endless loops if no slots are empty\n\tfor i := uint32(0); i < header.nslots; i++ {\n\t\thash := binary.LittleEndian.Uint32(table[slot:])\n\t\tpos := binary.LittleEndian.Uint32(table[slot+4:])\n\t\tif pos == 0 {\n\t\t\treturn nil, ErrNotFound\n\t\t}\n\t\tif hash == hashcode {\n\t\t\trecord := db.data[pos:]\n\t\t\tkeyLen := binary.LittleEndian.Uint32(record)\n\t\t\tdataLen := binary.LittleEndian.Uint32(record[4:])\n\t\t\trecKey := record[8 : 8+keyLen]\n\t\t\tif bytes.Equal(key, recKey) {\n\t\t\t\tdata := record[8+keyLen : 8+keyLen+dataLen]\n\t\t\t\treturn data, nil\n\t\t\t}\n\t\t}\n\n\t\t// search next slot, wrapping around\n\t\tslot += slotWidth\n\t\tif slot >= uint32(len(table)) {\n\t\t\tslot = 0\n\t\t}\n\t}\n\n\treturn nil, ErrNotFound\n}",
"func hash(data []byte) uint32 {\n\tvar h uint32 = binary.LittleEndian.Uint32(data) * kDictHashMul32\n\n\t/* The higher bits contain more mixture from the multiplication,\n\t so we take our results from there. */\n\treturn h >> uint(32-kDictNumBits)\n}",
"func (h *Hash) hashKey(key string) int {\n\n\t// Reset the maphash to initial state so we'll get the same\n\t// hash value for the same key.\n\th.hash.Reset()\n\n\t// Write the key to the maphash to update the current state.\n\t// We don't check error value since WriteString never fails.\n\th.hash.WriteString(key)\n\n\t// Ask the maphash for its current state which we will\n\t// use to calculate the final bucket index.\n\tn := h.hash.Sum64()\n\n\t// Use the modulu operator to return a value in the range\n\t// of our bucket length defined by the const numBuckets.\n\treturn int(n % numBuckets)\n}",
"func (h *Hash) String() string {\n\treturn hex.EncodeToString((*h)[:])\n}",
"func (h *BlockHasher) Write(p []byte) (n int, err error) {\n\tn2, err := h.ReadFrom(bytes.NewReader(p))\n\treturn int(n2), err\n}",
"func strhash(a unsafe.Pointer, h uintptr) uintptr",
"func Hash(data ...[]byte) []byte {\n\treturn crypto.Keccak256(data...)\n}",
"func (dtk *DcmTagKey) Hash() uint32 {\n\treturn ((uint32(int(dtk.group)<<16) & 0xffff0000) | (uint32(int(dtk.element) & 0xffff)))\n}",
"func (bh *BuzHash) Write(p []byte) (int, error) {\n\tfor _, b := range p {\n\t\tbh.HashByte(b)\n\t}\n\n\treturn len(p), nil\n}",
"func (o *ExportData) Hash() string {\n\targs := make([]interface{}, 0)\n\targs = append(args, o.CustomerID)\n\targs = append(args, o.ID)\n\targs = append(args, o.IntegrationInstanceID)\n\targs = append(args, o.JobID)\n\targs = append(args, o.Objects)\n\targs = append(args, o.RefID)\n\targs = append(args, o.RefType)\n\to.Hashcode = hash.Values(args...)\n\treturn o.Hashcode\n}",
"func (p McpJoinedGamePacket) Hash() []byte {\n\treturn p[13:17]\n}",
"func PrintHash(hashtable [][]string) {\n\tfmt.Println(hashtable)\n}",
"func h(data string) string {\n\tdigest := md5.New()\n\tdigest.Write([]byte(data))\n\treturn fmt.Sprintf(\"%x\", digest.Sum(nil))\n}",
"func (h *BlockHeader) Hash() string {\n\thash := Suite.Hash()\n\tbinary.Write(hash, binary.BigEndian, h.Owner)\n\tbinary.Write(hash, binary.BigEndian, h.Round)\n\thash.Write([]byte(h.PrvHash))\n\thash.Write([]byte(h.Root))\n\thash.Write(h.PrvSig)\n\tbuff := hash.Sum(nil)\n\treturn hex.EncodeToString(buff)\n}",
"func (self *XXHash) Write(data []byte) (nn int, err error) {\n\tif len(data) == 0 {\n\t\treturn 0, errors.New(\"Data cannot be nil or empty.\")\n\t}\n\tl := len(data)\n\tif l > 1<<30 {\n\t\treturn 0, errors.New(\"Cannot add more than 1 Gigabytes at once.\")\n\t}\n\tself.feed(data)\n\treturn len(data), nil\n}",
"func blockNumberKey(hash ibft.Hash) []byte {\n\treturn append(blockNumberPrefix, hash.Bytes()...)\n}",
"func main() {\n\tvalues := []string{\"ABC\", \"ACB\", \"BAC\", \"BCA\", \"CAB\", \"CBA\"}\n\t// values := []string{\"to\", \"to\", \"top\", \"ton\", \"tom\"}\n\tfactor := []int{100, 10, 1}\n\n\t// 65x100 + 66x10 + 67x1 = 7227\n\thashKey := 0\n\tfor v := range values {\n\t\tbytes := []byte(values[v])\n\t\tf := 0\n\t\thashKey = 0\n\t\tfor i := range bytes {\n\t\t\tfmt.Print(bytes[i], \" \")\n\t\t\thashKey += int(bytes[i]) * factor[f]\n\t\t\tf++\n\t\t}\n\t\tfmt.Printf(\" (hashKey: %d) \\n\", hashKey)\n\t}\n}",
"func (bc *Blockchain) Hash() {\n\n}",
"func (s *ShardMap) hash(v interface{}) int {\n\tswitch s.Type {\n\tcase \"string\":\n\t\tval, ok := v.(string)\n\t\tif !ok {\n\t\t\treturn -1\n\t\t}\n\n\t\thash := fnv.New32()\n\t\thash.Write([]byte(val))\n\t\treturn int(hash.Sum32() % NumShards)\n\tcase \"int32\":\n\t\t// Values that come as numbers in JSON are of type float64.\n\t\tval, ok := v.(float64)\n\t\tif !ok {\n\t\t\treturn -1\n\t\t}\n\n\t\treturn int(int32(val) % NumShards)\n\tdefault:\n\t\treturn -1\n\t}\n}",
"func htkey_hash_str(k1 voidptr, len int) usize {\n\tvar k1p byteptr = (byteptr)(k1)\n\tvar hash usize\n\n\thash = 0 + 5381 + len + 1\n\tfor i := 0; i < len; i++ {\n\t\tc := k1p[i]\n\t\thash = ((hash << 5) + hash) ^ usize(c)\n\t}\n\n\treturn hash\n}",
"func (o KubernetesClusterLinuxProfileSshKeyOutput) KeyData() pulumi.StringOutput {\n\treturn o.ApplyT(func(v KubernetesClusterLinuxProfileSshKey) string { return v.KeyData }).(pulumi.StringOutput)\n}",
"func (i Hash) String() string {\n\tstart := uint32(i >> 8)\n\tn := uint32(i & 0xff)\n\tif start+n > uint32(len(_Hash_text)) {\n\t\treturn \"\"\n\t}\n\treturn _Hash_text[start : start+n]\n}"
] | [
"0.6409849",
"0.59212303",
"0.5753035",
"0.56125563",
"0.55268365",
"0.54892313",
"0.54063344",
"0.5388259",
"0.5388259",
"0.5364874",
"0.53545535",
"0.5347696",
"0.5302847",
"0.52838427",
"0.52708936",
"0.52646226",
"0.5261133",
"0.52604115",
"0.5257445",
"0.52573097",
"0.5256685",
"0.52559847",
"0.52279836",
"0.5192613",
"0.5184249",
"0.51811326",
"0.51806027",
"0.51742655",
"0.51594883",
"0.51515144",
"0.51469326",
"0.5129983",
"0.5118836",
"0.5118637",
"0.50998473",
"0.5099098",
"0.5097591",
"0.5093513",
"0.5088516",
"0.5083367",
"0.5081745",
"0.5078227",
"0.5067904",
"0.50578314",
"0.5053466",
"0.50517106",
"0.50341403",
"0.50286776",
"0.50204855",
"0.50176203",
"0.5012664",
"0.50073385",
"0.5003811",
"0.50034696",
"0.49903393",
"0.4976191",
"0.4971904",
"0.49711895",
"0.49676642",
"0.4964543",
"0.4959208",
"0.49551743",
"0.49513492",
"0.49457803",
"0.4944409",
"0.49409142",
"0.49407685",
"0.49311113",
"0.49246365",
"0.49223164",
"0.49027538",
"0.49027538",
"0.49024272",
"0.48992002",
"0.4897628",
"0.4895058",
"0.48825398",
"0.48799488",
"0.48783764",
"0.48655775",
"0.4861664",
"0.48609096",
"0.4857959",
"0.48541597",
"0.48491758",
"0.48445308",
"0.4836951",
"0.4836595",
"0.4831487",
"0.4829944",
"0.48295966",
"0.4828309",
"0.48278135",
"0.48263773",
"0.4824959",
"0.48245314",
"0.4820715",
"0.4811502",
"0.48087856",
"0.47976714"
] | 0.5234257 | 22 |
store data at a specific key, used for "head" | func putBlockSig(s string, data []byte) error {
return db.Put([]byte(s), data, nil)
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (kvstore *KVStore) put(key string, value []byte) {\n\t/* kvstore is a pointer, can it be used in this way? yes*/\n\tkvstore.kvstore[key] = value\n}",
"func (st *SequentialSearchST) Put(key, val interface{}) {\n\tfor x := st.first; x != nil; x = x.next {\n\t\tif x.key == key {\n\t\t\tx.val = val\n\t\t\treturn\n\t\t}\n\t}\n\tst.first = &node{key, val, st.first}\n\tst.n++\n}",
"func (node *Node) put(key int, value string) error {\n\tnode.dataStoreLock.Lock()\n\tdefer node.dataStoreLock.Unlock()\n\t_, keyExists := node.hashTable[key]\n\tif keyExists {\n\t\treturn errors.New(\"Error putting file \" + value + \" into hashtable: identifier \" + strconv.Itoa(key) + \" already exists in hash table\")\n\t}\n\t// Add file in hash table if it does not exist\n\tnode.hashTable[key] = value\n\treturn nil\n}",
"func (store *KVStore) add(key string, val []byte, isOrigin bool) {\n\tstore.ht[key] = val\n\tstore.isOrigin[key] = isOrigin\n}",
"func (d *Datastore) Store(key []byte, data interface{}) error {\n\td.mutex.Lock()\n\tdefer d.mutex.Unlock()\n\n\td.cleanup()\n\tsKey := convertKey(key)\n\td.items[sKey] = item{data, time.Now()}\n\treturn nil\n}",
"func (s Storage) set(k string, v *metadata) {\n\ts.store[k] = v\n}",
"func (db *MemoryStorage) Put(key []byte, value []byte) error {\n\tdb.data.Store(common.BytesToHex(key), value)\n\treturn nil\n}",
"func (n *NodeStore) Put(key []byte, data []byte) error {\n\treturn n.store.Put(n.addr, key, data)\n}",
"func (p *MemDB) Put(key []byte, value []byte) {\n\tif node, exact := p.findGE(key, true); exact {\n\t\tif len(value) != 0 {\n\t\t\tkvOffset := len(p.kvData)\n\t\t\tp.kvData = append(p.kvData, key...)\n\t\t\tp.kvData = append(p.kvData, value...)\n\t\t\tp.nodeData[node] = kvOffset\n\t\t}\n\t\tm := p.nodeData[node+nVal]\n\t\tp.nodeData[node+nVal] = len(value)\n\t\tp.kvSize += len(value) - m\n\t\treturn\n\t}\n\n\th := p.randHeight()\n\tif h > p.maxHeight {\n\t\tfor i := p.maxHeight; i < h; i++ {\n\t\t\tp.prevNode[i] = 0\n\t\t}\n\t\tp.maxHeight = h\n\t}\n\n\tkvOffset := len(p.kvData)\n\tp.kvData = append(p.kvData, key...)\n\tp.kvData = append(p.kvData, value...)\n\t// Node\n\tnode := len(p.nodeData)\n\tp.nodeData = append(p.nodeData, kvOffset, len(key), len(value), h)\n\tfor i, n := range p.prevNode[:h] {\n\t\tm := n + nNext + i\n\t\tp.nodeData = append(p.nodeData, p.nodeData[m])\n\t\tp.nodeData[m] = node\n\t}\n\n\tp.kvSize += len(key) + len(value)\n\tp.n++\n\treturn\n}",
"func (h *RedisHelper) Store(key string, data []byte) (err error) {\n\tif 1 == 2 {\n\t\tfmt.Printf(\"key: %s\\n\", key)\n\t}\n\t_, err = h.Conn.Do(\"SET\", []byte(key), data)\n\treturn\n}",
"func (c *Cache) Set(key string, value interface{}) {\n\tif c.lists[0].Len() < c.capacity {\n\t\tc.data[key] = c.lists[0].PushFront(&cacheItem{0, key, value})\n\t\treturn\n\t}\n\n\t// reuse the tail item\n\te := c.lists[0].Back()\n\titem := e.Value.(*cacheItem)\n\n\tdelete(c.data, item.key)\n\titem.key = key\n\titem.value = value\n\tc.data[key] = e\n\tc.lists[0].MoveToFront(e)\n}",
"func (s *Store) Set(key string, value interface{}) {\n\ts.access.Lock()\n\tdefer s.access.Unlock()\n\n\ts.data[key] = value\n\ts.sendDataChanged()\n\ts.doKeyChanged(key)\n}",
"func store(ctx gliderssh.Context, key string, value interface{}) {\n\tctx.SetValue(key, value)\n}",
"func (mc *MemoryStorage) Add(key string, data interface{}) {\n\tmc.Lock()\n\tif _, found := mc.bucket[key]; found {\n\t\tdelete(mc.bucket, key)\n\t}\n\tmc.bucket[key] = entity{object: data}\n\tmc.Unlock()\n}",
"func (s *MemStore) Set(key, val interface{}) error {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\ts.data[key] = val\n\treturn nil\n}",
"func (s *PostgresStore) Set(key, value interface{}) error {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\ts.data[key] = value\n\treturn nil\n}",
"func (c *Cache) Put(key string, data interface{}) {\n\tbigHash := Utils.GetStringHash(key)\n\t//key to identify set number\n\tintKey := bigHash % c.sets\n\n\tif v, ok := c._cache[intKey]; !ok {\n\t\tc._cache[intKey] = NewCacheEntrySet(c.n)\n\t\tc._cache[intKey].Put(bigHash, data)\n\t} else {\n\t\tv.Put(bigHash, data)\n\t}\n}",
"func (db *LDB) Put(key []byte, value []byte) error {\n return db.db.Put(key, value, nil)\n}",
"func (s *VirtualStore) Set(key, val any) error {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\ts.data[key] = val\n\treturn nil\n}",
"func (m *DHTModule) Store(key string, val string) {\n\n\tif m.IsAttached() {\n\t\tif err := m.Client.DHT().Store(key, val); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn\n\t}\n\n\tctx, cn := context.WithTimeout(context.Background(), 60*time.Second)\n\tdefer cn()\n\tif err := m.dht.Store(ctx, dht2.MakeKey(key), []byte(val)); err != nil {\n\t\tpanic(errors.ReqErr(500, StatusCodeServerErr, \"key\", err.Error()))\n\t}\n}",
"func (s *DHT) Store(ctx context.Context, data []byte) (string, error) {\n\tkey := s.hashKey(data)\n\n\t// replicate time for the key\n\treplication := time.Now().Add(defaultReplicateTime)\n\n\t// store the key to local storage\n\tif err := s.store.Store(ctx, key, data, replication); err != nil {\n\t\treturn \"\", fmt.Errorf(\"store data to local storage: %v\", err)\n\t}\n\n\t// iterative store the data\n\tif _, err := s.iterate(ctx, IterateStore, key, data); err != nil {\n\t\treturn \"\", fmt.Errorf(\"iterative store data: %v\", err)\n\t}\n\n\treturn base58.Encode(key), nil\n}",
"func (m *MemoryStorage) Put(key string, value interface{}) error {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tm.store[key] = value\n\treturn nil\n}",
"func (q *dStarLiteQueue) insert(u *dStarLiteNode, k key) {\n\tu.key = k\n\theap.Push(q, u)\n}",
"func (bs *cachedFlatFsDataStore) Put(key string, value []byte) (err error) {\n\n\tbs.Lock()\n\tdefer bs.Unlock()\n\tif err = bs.dataStore.Put(key, value); err != nil {\n\t\tbs.cacheSet[key] = struct{}{}\n\t}\n\n\treturn err\n}",
"func (c *Context) Store(key string, value interface{}) {\n\tc.Data[key] = value\n}",
"func (m *docsMap) Store(key string, value *Doc) {\n\tm.Data().Store(key, value)\n}",
"func (l *LocalStore) Set(ctx context.Context, key, data string) error {\n\tl.lock.Lock()\n\tl.store[key] = data\n\tl.lock.Unlock()\n\n\treturn nil\n}",
"func (t *LRUCache) Put(key int, value int) {\n\n}",
"func (m *jobMap) Store(key string, value *Job) {\n\tm.data.Store(key, value)\n}",
"func (j *JobWorker) store(key string, value *Job) {\n\tj.Lock()\n\tj.jobs[key] = value\n\tj.Unlock()\n}",
"func (s *Store) Put(key string, v interface{}) {\n\ts.store.Put(key, v)\n}",
"func (b *LDBBatch) Put(key []byte, value []byte) error {\n b.batch.Put(key, value)\n return nil\n}",
"func (c *memoryCache) Set(key string, value interface{}) {\n\tc.data[key] = value\n}",
"func (db *FlatDatabase) Put(key []byte, value []byte) error {\n\tif len(key) == 0 || len(value) == 0 {\n\t\treturn ErrEmptyEntry\n\t}\n\tdb.lock.Lock()\n\tdefer db.lock.Unlock()\n\n\tif db.read {\n\t\treturn ErrReadOnly\n\t}\n\tn := 2*binary.MaxVarintLen32 + len(key) + len(value)\n\tdb.grow(n)\n\toffset, previous := len(db.buff), len(db.buff)\n\tdb.buff = db.buff[:offset+n]\n\toffset += binary.PutUvarint(db.buff[offset:], uint64(len(key)))\n\toffset += copy(db.buff[offset:], key)\n\toffset += binary.PutUvarint(db.buff[offset:], uint64(len(value)))\n\toffset += copy(db.buff[offset:], value)\n\tdb.buff = db.buff[:offset]\n\tdb.items += 1\n\n\t// db.offset is monotonic increasing in \"WRITE\" mode which\n\t// indicates the offset of the last written entry in GLOBAL\n\t// view. So everytime only the diff is added.\n\tdb.offset += uint64(offset) - uint64(previous)\n\treturn db.writeChunk(false)\n}",
"func (s *Mem) Write(key interface{}, object []byte) error {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.store[s.Key(key)] = object\n\treturn nil\n}",
"func (d Data) Add(key uint32, value interface{}) {\n\td.mutex.Lock()\n\tdefer d.mutex.Unlock()\n\td.data[key] = value\n\td.counts[key] = d.counts[key] + 1\n}",
"func StoreMe(key interface{}, val interface{}) error {\n\treturn nil\n}",
"func (db *memorydb) Put(key, value []byte) error {\n\n\tif db.enableBatch {\n\t\tdb.batch.Put(key, value)\n\t} else {\n\t\tdb.writeLock <- struct{}{}\n\t\tdefer func() {\n\t\t\t<-db.writeLock\n\t\t}()\n\n\t\tdb.sm.Lock()\n\t\tdefer db.sm.Unlock()\n\n\t\tdb.db[string(key)] = value\n\t}\n\n\treturn nil\n}",
"func (s *syncMapInt64) store(key int, value int64) {\n\ts.Lock()\n\ts.m[key] = value\n\ts.Unlock()\n}",
"func (c *Cache) Set(key string, value interface{}) {\n\tif el, ok := c.cacheByKey[key]; ok {\n\t\tc.linkedList.MoveToFront(el)\n\t\tel.Value.(*entry).value = value\n\t\treturn\n\t}\n\n\tel := c.linkedList.PushFront(&entry{key: key, value: value})\n\tc.cacheByKey[key] = el\n\n\tif c.linkedList.Len() > c.maxEntries {\n\t\tc.cleanUp()\n\t}\n}",
"func (c *FIFO) Put(key uint64, value interface{}) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tkv := &Item{Key: key, Value: value}\n\tc.ll.PushFront(kv)\n\n\tif c.maxCount != 0 && c.ll.Len() > c.maxCount {\n\t\tc.ll.Remove(c.ll.Back())\n\t}\n}",
"func (m *MemoQueue) Put(key string, value string) {\n\n\tm.lock.Lock()\n\n\tqueue, found := m.table[key]\n\tif !found {\n\t\tvar newlist *list.List = list.New()\n\t\tm.table[key] = newlist\n\t\tqueue = newlist\n\t} \n\t\n\tqueue.PushBack(value)\n\n\tm.lock.Unlock()\n}",
"func (m *infoMap) Store(key string, value Info) {\n\tm.data.Store(key, value)\n}",
"func (tl *TransactionList) Set(key, value string) {\n\tif tl.head != nil {\n\t\ttl.head.Set(key, value)\n\t} else {\n\t\tStorage[key] = value\n\t}\n}",
"func (hm *MyHashMap) Put(key int, value int) {\n\tvar prev *Node\n\tindex := hm.HashFunc(key)\n\tentry := hm.Arrays[index]\n\tfor entry != nil && entry.Key != key {\n\t\tprev = entry\n\t\tentry = entry.Next\n\t}\n\n\tif entry == nil {\n\t\tif prev == nil {\n\t\t\tprev = hm.NewNode(key, value)\n\t\t\thm.Arrays[index] = prev\n\t\t} else {\n\t\t\tentry = hm.NewNode(key, value)\n\t\t\tprev.Next = entry\n\t\t}\n\t} else {\n\t\tentry.Value = value\n\t}\n\n}",
"func (s *MemStore) Store(mimetype string, k string, v string) error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif curVal := s.items[k]; curVal != \"\" {\n\t\treturn KeyConflict\n\t}\n\ts.items[k] = v\n\ts.mimetype[k] = mimetype\n\treturn nil\n}",
"func SetKey(key string, data interface{}) {\n\tconnect := Connect()\n\tif data == nil {\n\t\tlog.Println(\"should not be nil\")\n\t}\n\t_, err := connect.Do(\"SET\", key, data)\n\tif err != nil {\n\t\tlog.Fatal(err, \"not ok\")\n\t}\n\tdefer connect.Close()\n}",
"func (cache *Cache) Set(key string, data interface{}, ttl time.Duration) {\n\tcache.mutex.Lock()\n\tdefer cache.mutex.Unlock()\n\tcache.entries[key] = &entry{data, time.Now().Add(ttl)}\n}",
"func (h *Hash) Store(key string, value int) {\n\n\t// For the specified key, identify what bucket in\n\t// the slice we need to store the key/value inside of.\n\tidx := h.hashKey(key)\n\n\t// Extract a copy of the bucket from the hash table.\n\tbucket := h.buckets[idx]\n\t// Iterate over the indexes for the specified bucket.\n\tfor idx := range bucket {\n\n\t\t// Compare the keys and if there is a match replace the\n\t\t// existing entry value for the new value.\n\t\tif bucket[idx].key == key {\n\t\t\tbucket[idx].value = value\n\t\t\treturn\n\t\t}\n\t}\n\n\t// This key does not exist, so add this new value.\n\th.buckets[idx] = append(bucket, entry{key, value})\n}",
"func (c *DictCache) Push(key string) {\n\tif key == \"\" {\n\t\treturn\n\t}\n\tc.entries[key] = time.Now()\n\tc.count++\n}",
"func (p *keyPool) Put(key *aero.Key) {\n\tp.Lock()\n\tp.buffer = append(p.buffer, key)\n\tp.Unlock()\n}",
"func Put(key string, value string){\n \n h := sha256.New()\n h.Write([]byte(value))\n sha := base64.URLEncoding.EncodeToString(h.Sum(nil))\n \n //fmt.Println(sha)\n var n Data \n \n n.val = value //storing key value in keyValue hash map\n n.hash = sha // storing key hash in keyHash hash map \n \n keyValue[key] = n\n}",
"func (storage *Storage) Put(key []byte, data []byte) error {\n\tstorage.Db[string(key)] = string(data)\n\treturn nil\n}",
"func (local *Node) Store(key string, value []byte) (err error) {\n\tdone, err := local.Publish(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlocal.blobstore.Put(key, value, done)\n\treturn nil\n}",
"func (s *Arena) putKey(key []byte) uint32 {\n\tkeySz := uint32(len(key))\n\toffset := s.allocate(keySz) - keySz\n\tbuf := s.data[offset : offset+keySz]\n\ty.AssertTrue(len(key) == copy(buf, key))\n\treturn offset\n}",
"func (hm *HashMap) Put(key, value string) {\n\tindex := hm.getIndex(key)\n\thm.rwMutex.Lock()\n\tdefer hm.rwMutex.Unlock()\n\thas, _ := hm.getNode(key)\n\tif has != nil {\n\t\thas.value = value\n\t\treturn\n\t}\n\thm.nodes[index].append(&node{key: key, value:value})\n}",
"func (tb *tableManager) write(keyIn uint64, val *Block) error {\n\tkey, ok := CleanKey(keyIn)\n\tif !ok {\n\t\tlog.Println(\"Key out of range.\")\n\t\treturn errors.New(\"Key out of range.\")\n\t}\n\tentry, err := tb.getEntry(key)\n\tif err != nil {\n\t\tif len(tb.data) >= tableSize {\n\t\t\t// Table is full, we need to pick a cache victim.\n\t\t\terr := tb.evict()\n\t\t\tif err != nil {\n\t\t\t\treturn errors.New(\"Table is full and needs to be flushed.\")\n\t\t\t}\n\t\t}\n\t\tentry = new(tableEntry)\n\t\tif entry == nil {\n\t\t\tlog.Println(\"Could not allocate table entry.\")\n\t\t\treturn errors.New(\"Could not allocate table entry.\")\n\t\t}\n\t}\n\tentry.block = val\n\tentry.flags = flagDirty\n\tentry.assignedKey = key\n\ttb.data[key] = entry\n\n\ttb.updateLRUCacheHead(entry)\n\treturn nil\n}",
"func (ht *HashTable) Put(key string, value int) *HashTable {\n\thash := hash(key)\n\tindex := index(hash)\n\n\tif ht[index] == nil {\n\t\tht[index] = NewLinkedList()\n\t\tht[index].Add(&listData{key, value})\n\t} else {\n\t\tnode := ht[index].Head\n\t\tfor {\n\t\t\tif node != nil {\n\t\t\t\td := node.Value.(*listData)\n\t\t\t\tif d.key == key {\n\t\t\t\t\td.value = value\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tht[index].Add(&listData{key, value})\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tnode = node.Next\n\t\t}\n\t}\n\treturn ht\n}",
"func (s *Store) Put(key string, value interface{}) error {\n\treturn s.Add(key, value)\n}",
"func (m *Map) Store(key, value interface{}) {\n\tif v, ok := m.Map.Load(key); !ok || !reflect.DeepEqual(v, value) {\n\t\tm.change = true\n\t\tm.Map.Store(key, value)\n\n\t\tif !ok {\n\t\t\t// TODO: new content, should update index\n\t\t\t// c.\n\t\t}\n\t}\n}",
"func (n *nodeBlock) insert(key uint128) error {\n\ti, found := n.find(key)\n\t//log.Println(n.children, n.items, item, i, found)\n\tif found {\n\t\treturn ErrKeyExisted\n\t}\n\n\tif n.childrenSize == 0 {\n\t\tp, err := n._super.writeMetadata(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn.insertItemAt(i, p)\n\t\treturn nil\n\t}\n\n\tif n.maybeSplitChild(i) {\n\t\tinTree := n.items[i]\n\t\tswitch {\n\t\tcase key.less(inTree.key):\n\t\t\t// no change, we want first split node\n\t\tcase inTree.key.less(key):\n\t\t\ti++ // we want second split node\n\t\tdefault:\n\t\t\treturn ErrKeyExisted\n\t\t}\n\t}\n\n\t//log.Println(n._children, n.childrenOffset, n.childrenSize)\n\tch, err := n.child(i)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ch.insert(key)\n}",
"func (ht *HashTable) put(pos *Position, entry hashEntry) {\n\tlock, key0, key1 := split(pos.Zobrist(), ht.mask)\n\tentry.lock = lock\n\n\tif e := &ht.table[key0]; e.lock == lock || e.kind == 0 || e.depth >= entry.depth {\n\t\tht.table[key0] = entry\n\t} else {\n\t\tht.table[key1] = entry\n\t}\n}",
"func (db *Database) Set(key string, data []byte) error {\n\tif db == nil || db.conn == nil {\n\t\treturn hord.ErrNoDial\n\t}\n\n\tif err := hord.ValidKey(key); err != nil {\n\t\treturn err\n\t}\n\n\tif err := hord.ValidData(data); err != nil {\n\t\treturn err\n\t}\n\n\terr := db.conn.Query(`UPDATE hord SET data = ? WHERE key = ?`, data, key).Exec()\n\treturn err\n}",
"func (m *MySQL) Set(key string, th *Blob) error {\n\tstart := time.Now()\n\tgo func() {\n\t\tklog.Infof(\"set(%q) took %s\", key, time.Since(start))\n\t}()\n\n\tsetMem(m.memcache, key, th)\n\n\tgo func() {\n\t\tb := new(bytes.Buffer)\n\t\tge := gob.NewEncoder(b)\n\n\t\tif err := ge.Encode(th); err != nil {\n\t\t\tklog.Errorf(\"encode: %w\", err)\n\t\t}\n\n\t\t_, err := m.db.Exec(`\n\t\t\tINSERT INTO persist2 (k, v, saved) VALUES (?, ?, ?)\n\t\t\tON DUPLICATE KEY UPDATE k=VALUES(k), v=VALUES(v)`, key, b.Bytes(), time.Now())\n\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"insert failed: %v\", err)\n\t\t}\n\t}()\n\treturn nil\n}",
"func (h *HashTable) put(key int, value int) bool {\n\tindex := hashFunction(key, len(h.table.buckets))\n\titerator := h.table.buckets[index]\n\tnode := Element{key, value, nil}\n\tif iterator == nil {\n\t\th.table.buckets[index] = &node\n\t} else {\n\t\tprev := &Element{0, 0, nil}\n\t\tfor iterator != nil {\n\t\t\tif iterator.key == key { // Key already exists\n\t\t\t\titerator.value = value\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tprev = iterator\n\t\t\titerator = iterator.next\n\t\t}\n\t\tprev.next = &node\n\t}\n\t*h.size += 1\n\treturn true\n}",
"func (c *SliceCache) Push(key string) {\n\tif key == \"\" {\n\t\treturn\n\t}\n\tc.keys = append(c.keys, key)\n\tc.times = append(c.times, time.Now())\n\tc.count++\n}",
"func (cache *Cache) Set(key, data interface{}) {\n\tcache.mutex.Lock()\n\tdefer cache.mutex.Unlock()\n\titem := &Item{data: data}\n\tif cache.hasAutoExpire() {\n\t\titem.addTimeout(cache.ttl)\n\t}\n\tcache.items[key] = item\n}",
"func (this *MyHashMap) Put(key int, value int) {\n\tkey = this.hash(key)\n\tnode := this.ht[key]\n\tfor ; node != nil; node = node.next {\n\t\tif node.k == key {\n\t\t\tnode.v = value\n\t\t\treturn\n\t\t}\n\t}\n\tif node == nil {\n\t\tthis.ht[key] = &Node{key, value, nil}\n\t} else {\n\t\tthis.ht[key] = &Node{key, value, this.ht[key]}\n\t}\n}",
"func (s *SyncMap) Put(key string, value []byte) (err error) {\n\ts.data.Store(key, value)\n\treturn nil\n}",
"func (ds *DataStore) Add(key uint64, value []byte) error {\n\tds.dataStoreLock.Lock()\n\tdefer ds.dataStoreLock.Unlock()\n\tif _, present := ds.kvSet[key]; present {\n\t\tds.kvTime[key] = time.Now().UnixNano()\n\t\treturn fmt.Errorf(\"Key %d already exists\", key)\n\t}\n\tds.kvSet[key] = value\n\treturn nil\n}",
"func (m *Machine) DataPut(key string, val any) error {\n\tm.dataMu.Lock()\n\tdefer m.dataMu.Unlock()\n\n\tm.data[key] = val\n\n\terr := m.saveData()\n\tif err != nil {\n\t\tm.Errorf(\"machine\", \"Could not save data to %s: %s\", dataFileName, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func (st *Store) Set(key, value []byte) error {\n\tst.lock.Lock()\n\tdefer st.lock.Unlock()\n\tif err := st.beforeSet(key, value); err != nil {\n\t\treturn err\n\t}\n\tif st.compression {\n\t\tvalue = compress(value)\n\t}\n\terr := st.store.Put(key, value, ds.ItemOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn st.writeToLogFile(key, value)\n}",
"func (tx *transaction) putKey(key, value []byte) error {\n\t// Prevent the key from being deleted if it was previously scheduled\n\t// to be deleted on transaction commit.\n\ttx.pendingRemove.Delete(key)\n\n\t// Add the key/value pair to the list to be written on transaction\n\t// commit.\n\ttx.pendingKeys.Put(key, value)\n\ttx.notifyActiveIters()\n\treturn nil\n}",
"func (m *Hashmap) Put(key int, val string) {\n\tif m.size*loadFactor <= m.entries {\n\t\tm.rehash()\n\t}\n\n\tidx := hash(key) % m.size\n\tvar curr *node = &m.buckets[idx]\n\t// If the key doesn't exist yet, traverse\n\t// the list until it reaches the end.\n\t// If the key does exist, traverse until\n\t// it reaches the key\n\tfor curr.next != nil && curr.key != key {\n\t\tcurr = curr.next\n\t}\n\tif curr.next == nil {\n\t\t// If it reached the end of the list (didn't encounter the key)\n\t\tcurr.key = key\n\t\tcurr.next = &node{0, \"\", nil}\n\t}\n\tcurr.val = val\n\tm.entries++\n}",
"func StoreKey(key, value string, d time.Duration) error {\n\tconn := aredis.Connection()\n\tdefer func() {\n\t\t_ = conn.Close()\n\t}()\n\n\t_, err := redis.String(conn.Do(\"PSETEX\", prefix+key, d.Nanoseconds()/1000, value))\n\treturn errors.Wrap(err, \"set failed\")\n}",
"func (o *wordTrie) put(key ngram) {\n\tcurrent := o.root\n\tvar i int\n\tfor ; i < len(key)-1; i++ {\n\t\tcurrent = current.children[key[i]]\n\t}\n\tnode, ok := current.children[key[i]]\n\tif ok {\n\t\tnode.freq++\n\t} else {\n\t\tnode = newNode(1)\n\t\tcurrent.children[key[i]] = node\n\t}\n\tnode.prob = float64(node.freq) / float64(current.freq)\n}",
"func (u *UdMap) Set(key, value string) { u.Data[key] = value }",
"func (r *redisPersist) Store(key string, p mqtt.Packet) error {\n\tif p == nil || r.conn == nil {\n\t\treturn nil\n\t}\n\n\tif ok, err := r.conn.HSet(r.mainKey, key, p.Bytes()).Result(); !ok {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func (h *data) Push(kv interface{}) {\n\tkeyValue := kv.(*itemKeyValue)\n\tn := len(h.queue)\n\th.items[keyValue.key] = &heapItem{keyValue.obj, n}\n\th.queue = append(h.queue, keyValue.key)\n}",
"func (m *RedisStore) Set(key interface{}, value interface{}) error {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tm.sessionData[key] = value\n\treturn nil\n}",
"func (a *Adapter) Set(key uint64, response []byte, expiration time.Time) {\n\ta.mutex.Lock()\n\tdefer a.mutex.Unlock()\n\n\tif _, ok := a.store[key]; ok {\n\t\t// Known key, overwrite previous item.\n\t\ta.store[key] = response\n\t\treturn\n\t}\n\n\t// New key, make sure we have the capacity.\n\tif len(a.store) == a.capacity {\n\t\ta.evict()\n\t}\n\n\ta.store[key] = response\n}",
"func (this *MyHashMap) Put(key int, value int) {\n\tindex := this.nodeIndex(key)\n\tv := this.table[index]\n\tif v == nil {\n\t\tthis.table[index] = &Node{key: key, val: value}\n\t\tthis.size++\n\t} else if v.key == key {\n\t\tv.val = value\n\t\treturn\n\t} else {\n\t\tfor v.next != nil {\n\t\t\tif v.next.key == key {\n\t\t\t\tv.next.val = value\n\t\t\t\treturn\n\t\t\t}\n\t\t\tv = v.next\n\t\t}\n\t\tv.next = &Node{key: key, val: value}\n\t\tthis.size++\n\t}\n\tif float32(this.size) >= float32(this.container)*ResetMultiple {\n\t\tthis.reset()\n\t}\n}",
"func (p KvStore) Put(key, value string, ttl int) (err error) {\n\tif p.CTable == nil {\n\t\treturn errors.New(\"table not open: \" + p.Name)\n\t}\n\tckey := C.CString(key)\n\tdefer C.free(unsafe.Pointer(ckey))\n\tcvalue := C.CString(value)\n\tdefer C.free(unsafe.Pointer(cvalue))\n\tckeylen := C.uint64_t(len(key))\n\tcvallen := C.uint64_t(len(value))\n\tret := C.tera_table_put_kv(p.CTable, ckey, ckeylen, cvalue, cvallen, C.int32_t(ttl), nil)\n\tif !ret {\n\t\terr = errors.New(\"put kv error\")\n\t}\n\treturn\n}",
"func setLocation(location map[string]interface{}){\n\t//basically, go to redis, set the key of userID:location:whatever to their current locatio\n\n}",
"func (t *chaining) Insert(key string, val interface{}) {\n\tif t.loadFactor() > t.maxLoad {\n\t\tt.tableDouble()\n\t}\n\thash := t.hash(key)\n\tif t.values[hash] == nil {\n\t\tt.values[hash] = list.New()\n\t}\n\tt.values[hash].Insert(&pair{key, val})\n\tt.len++\n}",
"func (c *layerCache) Set(key interface{}, value interface{}) (err error) {\n\terr = c.Storage.Add(key, value)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif c.next == nil {\n\t\t// This backend cache is final destination\n\t\treturn nil\n\t}\n\t// Queue to flush\n\tc.log <- log{key, &Message{Value: value, Message: MessageSet}}\n\treturn nil\n}",
"func (s *Store) Set(ctx context.Context, key interface{}, v json.Marshaler) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t}\n\n\tb, err := v.MarshalJSON()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t}\n\n\ts.m[key] = entry{data: b}\n\treturn nil\n}",
"func (w *diskTableWriter) write(key, value []byte) error {\n\tdataBytes, err := encode(key, value, w.dataFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write to the data file: %w\", err)\n\t}\n\n\tindexBytes, err := encodeKeyOffset(key, w.dataPos, w.indexFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write to the index file: %w\", err)\n\t}\n\n\tif w.keyNum%w.sparseKeyDistance == 0 {\n\t\tif _, err := encodeKeyOffset(key, w.indexPos, w.sparseIndexFile); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to write to the file: %w\", err)\n\t\t}\n\t}\n\n\tw.dataPos += dataBytes\n\tw.indexPos += indexBytes\n\tw.keyNum++\n\n\treturn nil\n}",
"func (bs *badgerStore) Set(key []byte, data []byte, ttl time.Duration) (err error) {\n\treturn bs.db.Update(func(txn *badger.Txn) error {\n\t\te := badger.NewEntry(key, data).\n\t\t\tWithTTL(ttl)\n\t\treturn txn.SetEntry(e)\n\t})\n}",
"func (s *InMemoryHashStorage) Set(key int64, value string) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\ts.hashes[key] = value\n}",
"func (l *localStore) Set(key string, b []byte) error {\n\t_, ok := l.m[key]\n\tl.m[key] = b\n\tif ok {\n\t\treturn ErrKeyExist\n\t}\n\treturn nil\n}",
"func (i *InmemStore) Set(key []byte, val []byte) error {\n\ti.l.Lock()\n\tdefer i.l.Unlock()\n\ti.kv[string(key)] = val\n\treturn nil\n}",
"func (index *ind) add(value string) {\n\tvar halfhash string\n\n\tif len(value) <= hashKeySize {\n\t\thalfhash = value\n\t} else {\n\t\thalfhash = value[:hashKeySize]\n\t}\n\n\tindex.Storage[halfhash] = append(index.Storage[halfhash], value)\n}",
"func (t *HashTable) Put(key, value string) {\n\thash := adler32.Checksum([]byte(key)) % maxTableSize\n\tfor {\n\t\tif t.Table[hash] != nil && t.Table[hash].Key != key {\n\t\t\thash = (hash + 1) % maxTableSize\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tt.Table[hash] = &node{key, value}\n}",
"func (w *tWriter) append(key, value []byte) error {\n\tif w.first == nil {\n\t\tw.first = append([]byte{}, key...)\n\t}\n\tw.last = append(w.last[:0], key...)\n\treturn w.tw.Append(key, value)\n}",
"func (fdb *fdbSlice) insert(k Key, v Value, workerId int) {\n\n\tvar err error\n\tvar oldkey Key\n\n\tcommon.Tracef(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Set Key - %s \"+\n\t\t\"Value - %s\", fdb.id, fdb.idxInstId, k, v)\n\n\t//check if the docid exists in the back index\n\tif oldkey, err = fdb.getBackIndexEntry(v.Docid(), workerId); err != nil {\n\t\tfdb.checkFatalDbError(err)\n\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Error locating \"+\n\t\t\t\"backindex entry %v\", fdb.id, fdb.idxInstId, err)\n\t\treturn\n\t} else if oldkey.EncodedBytes() != nil {\n\t\t//TODO: Handle the case if old-value from backindex matches with the\n\t\t//new-value(false mutation). Skip It.\n\n\t\t//there is already an entry in main index for this docid\n\t\t//delete from main index\n\t\tif err = fdb.main[workerId].DeleteKV(oldkey.EncodedBytes()); err != nil {\n\t\t\tfdb.checkFatalDbError(err)\n\t\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Error deleting \"+\n\t\t\t\t\"entry from main index %v\", fdb.id, fdb.idxInstId, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t//If secondary-key is nil, no further processing is required. If this was a KV insert,\n\t//nothing needs to be done. If this was a KV update, only delete old back/main index entry\n\tif v.KeyBytes() == nil {\n\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Received NIL secondary key. \"+\n\t\t\t\"Skipped Key %s. Value %s.\", fdb.id, fdb.idxInstId, k, v)\n\t\treturn\n\t}\n\n\t//set the back index entry <docid, encodedkey>\n\tif err = fdb.back[workerId].SetKV([]byte(v.Docid()), k.EncodedBytes()); err != nil {\n\t\tfdb.checkFatalDbError(err)\n\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Error in Back Index Set. \"+\n\t\t\t\"Skipped Key %s. Value %s. Error %v\", fdb.id, fdb.idxInstId, v, k, err)\n\t\treturn\n\t}\n\n\t//set in main index\n\tif err = fdb.main[workerId].SetKV(k.EncodedBytes(), v.EncodedBytes()); err != nil {\n\t\tfdb.checkFatalDbError(err)\n\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Error in Main Index Set. \"+\n\t\t\t\"Skipped Key %s. Value %s. Error %v\", fdb.id, fdb.idxInstId, k, v, err)\n\t\treturn\n\t}\n\n}",
"func (d Data) set(keys []string, value interface{}) error {\n\tswitch len(keys) {\n\tcase 0:\n\t\treturn nil\n\tcase 1:\n\t\treturn d.setValue(keys[0], value)\n\t}\n\n\tkeyData, err := d.Data(keys[0])\n\tswitch err {\n\tcase ErrUnexpectedType, ErrNotFound:\n\t\tkeyData = make(Data)\n\t\td[keys[0]] = keyData\n\t\treturn keyData.set(keys[1:], value)\n\tcase nil:\n\t\treturn keyData.set(keys[1:], value)\n\tdefault:\n\t\treturn err\n\t}\n}",
"func (c *cache) write(key string, val interface{}) {\n\tc.Fields[key] = val\n}",
"func (ds *KVStorage) Insert(ID string, g graph.Graph) {\n\tds.data[ID] = g\n}",
"func (mp *mirmap) insert(k voidptr, v voidptr) bool {\n\tmp.expand()\n\n\t// mp.keyalg.hash(&k, mp.keysz) // TODO compiler\n\tfnptr := mp.keyalg.hash\n\thash := fnptr(k, mp.keysz)\n\tidx := hash % usize(mp.cap_)\n\t// println(idx, hash, mp.cap_)\n\n\tvar onode *mapnode = mp.ptr[idx]\n\tfor onode != nil {\n\t\tif onode.hash == hash {\n\t\t\t// println(\"replace\", idx, k)\n\t\t\tmemcpy3(onode.val, v, mp.valsz)\n\t\t\treturn true\n\t\t}\n\t\tonode = onode.next\n\t}\n\n\tnode := &mapnode{}\n\t// node.key = k\n\t// node.val = v\n\tnode.key = malloc3(mp.keysz)\n\tmemcpy3(node.key, k, mp.keysz)\n\tnode.val = malloc3(mp.valsz)\n\tmemcpy3(node.val, v, mp.valsz)\n\tnode.hash = hash\n\tnode.next = mp.ptr[idx]\n\n\t// println(\"insert\", mp.len_, idx, mp.cap_, node)\n\tmp.ptr[idx] = node\n\tmp.len_++\n\n\treturn true\n}",
"func (fc *fasterCache) set(key string, value interface{}, expiration time.Duration) {\n\tif key == \"\" {\n\t\treturn\n\t}\n\t//key是否存在\n\tif e, ok := fc.dataMap[key]; ok {\n\t\tent := e.Value.(*entry)\n\t\t//key 存在,数据类型不为0,移除旧数据\n\t\tif ent.dataType != typeKv {\n\t\t\tfc.removeElement(e)\n\t\t\t//如果没有设置过期时间,使用默认过期时间\n\t\t\tif expiration <= 0 {\n\t\t\t\texpiration = defaultExpire\n\t\t\t}\n\t\t\tent := &entry{\n\t\t\t\tdataType: typeKv,\n\t\t\t\texpiration: time.Now().Add(expiration).UnixNano(),\n\t\t\t\tkey: key,\n\t\t\t\tvalue: value,\n\t\t\t}\n\t\t\te := fc.evictList.PushFront(ent)\n\t\t\tfc.dataMap[key] = e\n\t\t} else {\n\t\t\tent.value = value\n\t\t\t//如果没有设置过期时间,使用默认过期时间\n\t\t\tif expiration <= 0 {\n\t\t\t\texpiration = defaultExpire\n\t\t\t}\n\t\t\t//更新过期时间\n\t\t\tent.expiration = time.Now().Add(expiration).UnixNano()\n\t\t\tif fc.mode == modeLru {\n\t\t\t\tfc.evictList.MoveToFront(e)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t//如果没有设置过期时间,使用默认过期时间\n\t\tif expiration <= 0 {\n\t\t\texpiration = defaultExpire\n\t\t}\n\t\tent := &entry{\n\t\t\tdataType: typeKv,\n\t\t\texpiration: time.Now().Add(expiration).UnixNano(),\n\t\t\tkey: key,\n\t\t\tvalue: value,\n\t\t}\n\t\te := fc.evictList.PushFront(ent)\n\t\tfc.dataMap[key] = e\n\t\tif fc.evictList.Len() > fc.size {\n\t\t\tfc.removeTail()\n\t\t}\n\t}\n\treturn\n}"
] | [
"0.6831132",
"0.65417117",
"0.65272564",
"0.6416407",
"0.6362406",
"0.6357661",
"0.6356435",
"0.634632",
"0.6316669",
"0.6308005",
"0.6288156",
"0.6286835",
"0.6249248",
"0.6236562",
"0.620385",
"0.61428183",
"0.61350024",
"0.6132527",
"0.61297405",
"0.61019385",
"0.6080874",
"0.60738385",
"0.60655797",
"0.60617554",
"0.60611796",
"0.6052411",
"0.6052016",
"0.60509896",
"0.60467255",
"0.60445917",
"0.60377294",
"0.60283935",
"0.60194445",
"0.60075986",
"0.6007468",
"0.6005714",
"0.6005196",
"0.59995854",
"0.5994099",
"0.59927213",
"0.5987554",
"0.5944831",
"0.5943164",
"0.59428537",
"0.5937905",
"0.593517",
"0.5934074",
"0.59224796",
"0.59202516",
"0.5911965",
"0.5900328",
"0.59002656",
"0.58950925",
"0.5892697",
"0.5889412",
"0.58859646",
"0.5885388",
"0.5875126",
"0.5873003",
"0.5866825",
"0.5865397",
"0.58626026",
"0.58449525",
"0.58443564",
"0.5843844",
"0.5843297",
"0.5841146",
"0.583251",
"0.5828952",
"0.58211535",
"0.5808786",
"0.5804637",
"0.5802542",
"0.5800911",
"0.5795026",
"0.5782802",
"0.57790947",
"0.5769886",
"0.57634115",
"0.57601863",
"0.57589304",
"0.5755299",
"0.5755144",
"0.57549703",
"0.5753413",
"0.5743004",
"0.57395524",
"0.5733706",
"0.5733558",
"0.5732764",
"0.57325613",
"0.57309294",
"0.57287633",
"0.5726189",
"0.57224023",
"0.5717959",
"0.5715968",
"0.5713576",
"0.5712699",
"0.5710572",
"0.5709796"
] | 0.0 | -1 |
EncodeHash returns the sha1 encoding of s. | func EncodeHash(s string) string {
h := sha1.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func EncodeSHA1(str string) string {\n\th := sha1.New()\n\th.Write([]byte(str))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func toSha1(s string) string {\n\th := sha1.New()\n\th.Write([]byte(s))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func Hash(s string) string {\n\tSha1Inst := sha1.New()\n\tSha1Inst.Write([]byte(s))\n\tresult := Sha1Inst.Sum([]byte(\"\"))\n\treturn fmt.Sprintf(\"%x\", result)\n}",
"func shaEncode(input string) string {\n\tsha := sha512.Sum512([]byte(input))\n\treturn hex.EncodeToString(sha[:])\n}",
"func SHA1(s string) string {\n\treturn stringHasher(sha1.New(), s)\n}",
"func Sha1(s string) string {\n\treturn hashing(sha1.New(), s)\n}",
"func SHA1(s string) string {\n\th := sha1.New()\n\th.Write([]byte(s))\n\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func SHA1(s string) string {\n\th := sha1.New()\n\th.Write([]byte(s))\n\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func Sha1(s string) string {\n\tdigest := sha1.Sum([]byte(s))\n\treturn hex.EncodeToString(digest[:])\n}",
"func Hash(s string) string {\n\tfmt.Println(\"Hashing string:\", s)\n\thash := sha256.Sum256([]byte(s))\n\tniceHash := fmt.Sprintf(\"%x\", hash)\n\tfmt.Println(\"Created hash:\", hash)\n\treturn niceHash\n}",
"func hash(s string) string {\n\th := fnv.New32a()\n\t_, err := h.Write([]byte(s))\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprint(h.Sum32())\n}",
"func SHA1(input string) string {\n\n\t//Initiate SHA-1 type\n\th := sha1.New()\n\n\t//Set input\n\th.Write([]byte(input))\n\n\t//Return hash as string\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func Sha1(input string) string {\n\thash := sha1.New()\n\thash.Write([]byte(input))\n\thashed := hash.Sum(nil)\n\treturn fmt.Sprintf(\"%x\", hashed)\n}",
"func Hash(algo HashAlgo, s string) string {\n\tvar h hash.Hash\n\n\tswitch algo {\n\tcase AlgoMD5:\n\t\th = md5.New()\n\tcase AlgoSha1:\n\t\th = sha1.New()\n\tcase AlgoSha224:\n\t\th = sha256.New224()\n\tcase AlgoSha256:\n\t\th = sha256.New()\n\tcase AlgoSha384:\n\t\th = sha512.New384()\n\tcase AlgoSha512:\n\t\th = sha512.New()\n\tdefault:\n\t\treturn s\n\t}\n\n\th.Write([]byte(s))\n\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func hashStr(toHash string) string {\n\th := sha1.New()\n\tio.WriteString(h, toHash)\n\thashed := base64.StdEncoding.EncodeToString(h.Sum(nil))\n\treturn hashed\n}",
"func EncodeHash(hash []byte) string {\n\treturn hex.EncodeToString(hash[:])\n}",
"func EncodeHash256(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func Hash1(usr string) string {\n\tbytes := []byte(usr)\n\thash_bytes := hasher1.Sum(bytes)\n\treturn hex.EncodeToString(hash_bytes)\n}",
"func hash(s string) string {\n\treturn fmt.Sprintf(\"%x\", md5.Sum([]byte(s)))\n}",
"func hash(s string) string {\n\thash := fnv.New32a()\n\thash.Write([]byte(s))\n\tintHash := hash.Sum32()\n\tresult := fmt.Sprintf(\"%08x\", intHash)\n\treturn result\n}",
"func Hash(a interface{}) (string, error) {\n\th := sha1.New()\n\tif err := json.NewEncoder(h).Encode(a); err != nil {\n\t\treturn \"\", nil\n\t}\n\treturn base64.URLEncoding.EncodeToString(h.Sum(nil)), nil\n}",
"func HashStringSha1(hs string) []byte {\n\tdata := []byte(hs)\n\thash := sha1.Sum(data)\n\treturn hash[:]\n}",
"func Sha1(data []byte) string {\n\tshaInst := sha1.New()\n\t_, err := shaInst.Write(data)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%x\", shaInst.Sum(nil))\n}",
"func HashString(s string) string {\n\thash := sha256.Sum256([]byte(s))\n\treturn base64.StdEncoding.EncodeToString(hash[:])\n}",
"func shaString(buf []byte) string {\n\th := sha1.Sum(buf)\n\treturn base64.StdEncoding.EncodeToString(h[:])\n}",
"func HashString(toHash string) string {\n\thashed := sha256.Sum256([]byte(toHash))\n\treturn hex.EncodeToString(hashed[:])\n}",
"func ComputeHash(p, s string) string {\n\th := sha1.New()\n\tio.WriteString(h, p+s)\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func (f CryptoFuncs) SHA1(input interface{}) string {\n\t// nolint: gosec\n\tout, _ := f.SHA1Bytes(input)\n\treturn fmt.Sprintf(\"%02x\", out)\n}",
"func GetSHA1hash(obj interface{}) string {\n\tsha1Hash := sha1.New()\n\tswitch t := obj.(type) {\n\tcase *corev1.Secret:\n\t\tvar (\n\t\t\tsortedDataKeys []string\n\t\t\tsortedStringDataKeys []string\n\t\t)\n\t\tfor k := range t.Data {\n\t\t\tsortedDataKeys = append(sortedDataKeys, k)\n\t\t}\n\t\tfor k := range t.StringData {\n\t\t\tsortedStringDataKeys = append(sortedStringDataKeys, k)\n\t\t}\n\t\tif len(sortedDataKeys) == 0 && len(sortedStringDataKeys) == 0 {\n\t\t\treturn \"\"\n\t\t}\n\t\tsort.Strings(sortedDataKeys)\n\t\tsha1Hash.Write([]byte(strings.Join(sortedDataKeys, \"\")))\n\t\tsort.Strings(sortedStringDataKeys)\n\t\tsha1Hash.Write([]byte(strings.Join(sortedStringDataKeys, \"\")))\n\n\t\tfor _, key := range sortedDataKeys {\n\t\t\tsha1Hash.Write(t.Data[key])\n\t\t}\n\t\tfor _, key := range sortedStringDataKeys {\n\t\t\tsha1Hash.Write([]byte(t.StringData[key]))\n\t\t}\n\tdefault:\n\t\tutilruntime.HandleError(fmt.Errorf(\"Unknown object: %v\", obj))\n\t\treturn \"\"\n\t}\n\treturn hex.EncodeToString(sha1Hash.Sum(nil))\n}",
"func hashString(str string) string {\n\thash := sha256.Sum256([]byte(str))\n\treturn base64.StdEncoding.EncodeToString(hash[:])\n}",
"func (h Hash) String() string { return hex.EncodeToString(h[:]) }",
"func HashString(stringValue string) string {\n\th := sha256.New()\n\t_, _ = h.Write([]byte(stringValue))\n\treturn base64.StdEncoding.EncodeToString(h.Sum(nil))\n}",
"func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}",
"func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}",
"func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}",
"func (o *Aliyun) hmacSha1(s string) string {\n\tkey := []byte(o.Account.AccessSecret + \"&\")\n\tmac := hmac.New(sha1.New, key)\n\tmac.Write([]byte(s))\n\tsignure := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\treturn o.percentEncode(signure)\n}",
"func hexEncodeSHA256Hash(body []byte) (string, error) {\n\thash := sha256.New()\n\tif body == nil {\n\t\tbody = []byte(\"\")\n\t}\n\t_, err := hash.Write(body)\n\treturn hex.EncodeToString(hash.Sum(nil)), err\n}",
"func Hash(str string) string {\n\thasher := fnv.New64a()\n\thasher.Write([]byte(str))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}",
"func hash(s string) uint32 {\n h := fnv.New32a()\n h.Write([]byte(s))\n return h.Sum32()\n}",
"func hashString(input string) string {\n\tdefer loggerHighwayHasher.Reset()\n\tloggerHighwayHasher.Write([]byte(input))\n\tchecksum := loggerHighwayHasher.Sum(nil)\n\treturn hex.EncodeToString(checksum)\n}",
"func EncodeHash512(s string) string {\n\th := sha512.New()\n\th.Write([]byte(s))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func Hashit(tox string) string {\n h:= sha256.New()\n h.Write([]byte(tox))\n bs := h.Sum([]byte{})\n str := base64.StdEncoding.EncodeToString(bs)\n return str\n}",
"func (hash Sha) String() string {\n\treturn hex.EncodeToString(hash[:])\n}",
"func (s sha256hashing) HashString(hashme string, digest []byte) error {\n\thashAlgo := sha256.New()\n\thashAlgo.Write([]byte(hashme))\n\n\tcopySHA256(digest, hashAlgo.Sum(nil))\n\n\treturn nil\n}",
"func GenerateSHA1(s string) string {\n\thasher := sha1.New()\n\tbv := []byte(s)\n\thasher.Write(bv)\n\tsha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))\n\treturn sha\n}",
"func hash(s string) int {\n\th := fnv.New32a()\n\tif _, err := h.Write([]byte(s)); err != nil {\n\t\tpanic(err) // should never happen\n\t}\n\n\treturn int(h.Sum32() & 0x7FFFFFFF) // mask MSB of uint32 as this will be sign bit\n}",
"func hashme(s interface{}) string {\n\tbytes, _ := json.Marshal(s)\n\th := sha256.New()\n\th.Write(bytes)\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func stringHash(s string) string {\n\treturn fmt.Sprintf(\"%x\", md5.Sum([]byte(s)))\n}",
"func stringHash(s string) string {\n\treturn fmt.Sprintf(\"%x\", md5.Sum([]byte(s)))\n}",
"func (h Hash) String() string {\n\treturn hex.EncodeToString(h.Bytes())\n}",
"func Sha1(token, timestamp, nonce, msg string) string {\n\tsl := []string{token, timestamp, nonce, msg}\n\tsort.Strings(sl)\n\n\th := sha1.New()\n\tfor _, s := range sl {\n\t\tio.WriteString(h, s)\n\t}\n\tencode := h.Sum(nil)\n\n\treturn hex.EncodeToString(encode)\n\n}",
"func (hash Hash) String() string {\n\treturn hex.EncodeToString(hash[:])\n}",
"func (s *SHA1) String() string {\n\ts.strOnce.Do(func() {\n\t\tresult := make([]byte, 0, 40)\n\t\thexvalues := []byte(\"0123456789abcdef\")\n\t\tfor i := 0; i < 20; i++ {\n\t\t\tresult = append(result, hexvalues[s.bytes[i]>>4])\n\t\t\tresult = append(result, hexvalues[s.bytes[i]&0xf])\n\t\t}\n\t\ts.str = string(result)\n\t})\n\treturn s.str\n}",
"func (r *Repository) CreateHash(str string) string {\n\taStringToHash := []byte(str + r.salt)\n\tsha1Bytes := sha1.Sum(aStringToHash)\n\tencodedStr := hex.EncodeToString(sha1Bytes[:])\n\treturn encodedStr\n}",
"func Hash(input []byte) string {\n\treturn fmt.Sprintf(\"%x\", sha256.Sum256(input))\n}",
"func (p PlainTextHasher) Hash(str string) string { return str }",
"func Hash(obj interface{}) (string, error) {\n\tb, err := GetBytes(obj)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\thasher := sha256.New()\n\thasher.Write(b)\n\n\treturn base64.URLEncoding.EncodeToString(hasher.Sum(nil)), nil\n}",
"func (this *HashHmacGenerator) Sha1String(data string) string {\n\thmacBytes := this.Sha1([]byte(data))\n\treturn fmt.Sprintf(\"%x\", hmacBytes)\n}",
"func (h *Hash) String() string {\n\treturn hex.EncodeToString((*h)[:])\n}",
"func Hash(str string) string {\n\tout, err := b64.StdEncoding.DecodeString(str)\n\tif err == nil && len(out) > 1 {\n\t\t// if already b64 encoded don't hash\n\t\treturn str\n\t}\n\tv := sha256.Sum256([]byte(str))\n\treturn string(b64.StdEncoding.EncodeToString(v[:]))\n}",
"func (hash Hash) String() string {\n\tfor i := 0; i < HashSize/2; i++ {\n\t\thash[i], hash[HashSize-1-i] = hash[HashSize-1-i], hash[i]\n\t}\n\treturn hex.EncodeToString(hash[:])\n}",
"func hash(ba string) string {\n\th := sha256.New()\n\th.Write([]byte(ba))\n\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}",
"func GetSHA1(content []byte) string {\n\tsha := sha1.New()\n\tsha.Write(content)\n\n\treturn base32.StdEncoding.EncodeToString(sha.Sum(nil))\n}",
"func shortSha1(s string) string {\n\th := sha1.New()\n\n\th.Write([]byte(s))\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))[:6]\n}",
"func stringToHash(s string) uint32 {\n\th := fnv.New32a()\n\th.Write([]byte(s))\n\treturn h.Sum32()\n}",
"func (tt Hash) String() string {\n buf := make([]byte, len(tt))\n for ii := 0; ii < len(tt); ii++ {\n buf[len(tt)-1-ii] = tt[ii]\n }\n return hex.EncodeToString(buf)\n}",
"func (s String) Hash32(h hash.Hash32) { h.Write([]byte(s)) }",
"func hash_file_sha1(f File_s) (string, error) {\n\t//Initialize variable returnMD5String now in case an error has to be returned\n\tvar returnSHA1String string\n\n\t//Open the filepath passed by the argument and check for any error\n\tfile, err := os.Open(f.path)\n\tif err != nil {\n\t\treturn returnSHA1String, err\n\t}\n\t// Read first 20 bytes.\n\tb1 := make([]byte, 20)\n\tfile.Read(b1)\n\tss := f.Name + string(f.Size) + string(b1)\n\t//Tell the program to call the following function when the current function returns\n\tdefer file.Close()\n\n\t//Open a new SHA1 hash interface to write to\n\thash := sha1.New()\n\n\thash.Write([]byte(ss))\n\t//Get the 20 bytes hash\n\thashInBytes := hash.Sum(nil)[:20]\n\n\t//Convert the bytes to a string\n\treturnSHA1String = hex.EncodeToString(hashInBytes)\n\n\treturn returnSHA1String, nil\n\n}",
"func (hm HMACHasher) Hash(str string) string {\n\th := hm.p.Get().(hash.Hash)\n\tif _, err := h.Write([]byte(str)); err != nil {\n\t\t// Write() on hash never fails\n\t\tpanic(err)\n\t}\n\n\treturn base64.StdEncoding.EncodeToString(h.Sum(nil))\n}",
"func (this *MatchString) GetSha1(content string) string {\n\thasher := sha1.New()\n\t_, err = hasher.Write([]byte(content))\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tsha := hasher.Sum(nil)\n\treturn hex.EncodeToString(sha)\n}",
"func encodeHash(x uint64, p, pPrime uint) (hashCode uint64) {\n\tif x&onesFromTo(64-pPrime, 63-p) == 0 {\n\t\tr := rho(extractShift(x, 0, 63-pPrime))\n\t\treturn concat([]concatInput{\n\t\t\t{x, 64 - pPrime, 63},\n\t\t\t{uint64(r), 0, 5},\n\t\t\t{1, 0, 0}, // this just adds a 1 bit at the end\n\t\t})\n\t} else {\n\t\treturn concat([]concatInput{\n\t\t\t{x, 64 - pPrime, 63},\n\t\t\t{0, 0, 0}, // this just adds a 0 bit at the end\n\t\t})\n\t}\n}",
"func (s *hashingServer) Encode(ctx context.Context, request *proto.HashingEncodeRequest) (*proto.HashingEncodeResponse, error) {\n\tplainText := request.GetPlainText()\n\n\thashedText := base64.StdEncoding.EncodeToString([]byte(plainText))\n\n\treturn &proto.HashingEncodeResponse{HashedText: hashedText}, nil\n}",
"func NewHash(key string) string {\n\th := sha1.New()\n\th.Write([]byte(key))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func (h Hash) String() string {\n\treturn hex.EncodeToString(h[:])\n}",
"func (h Hash) String() string {\n\treturn hex.EncodeToString(h[:])\n}",
"func hexHash(input string) string {\n return idToString(hash([]byte(input)))\n}",
"func SHA1(space string, data []byte) (string, error) {\n\tu, err := uuid.Parse(string(space))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(uuid.NewSHA1(u, data).String()), nil\n}",
"func Hash(data interface{}) string {\n\treturn hex.EncodeToString(RawHash(data))\n}",
"func hash(f []byte) (string, error) {\n\tsha := sha256.New()\n\t_, err := sha.Write(f)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%x\", sha.Sum(nil)), nil\n}",
"func hasher(s string) []byte {\n\tval := sha256.Sum256([]byte(s))\n\tvar hex []string\n\n\t// Iterate through the bytes.\n\tfor i := 0; i < len(val); i++ {\n\t\t// We want each number to be represented by 2 chars.\n\t\tplaceHolder := []string{\"0\"}\n\t\tvalue := strconv.FormatInt(int64(val[i]), 16)\n\n\t\tif len(value) != 2 {\n\t\t\tplaceHolder = append(placeHolder, value)\n\t\t\thex = append(hex, strings.Join(placeHolder, \"\"))\n\t\t} else {\n\t\t\thex = append(hex, value)\n\t\t}\n\t}\n\treturn []byte(strings.Join(hex, \"\"))\n\n}",
"func ToHash(s []byte) Hash {\n\tif len(s) == 0 || len(s) > _Hash_maxLen {\n\t\treturn 0\n\t}\n\th := uint32(_Hash_hash0)\n\tfor i := 0; i < len(s); i++ {\n\t\th ^= uint32(s[i])\n\t\th *= 16777619\n\t}\n\tif i := _Hash_table[h&uint32(len(_Hash_table)-1)]; int(i&0xff) == len(s) {\n\t\tt := _Hash_text[i>>8 : i>>8+i&0xff]\n\t\tfor i := 0; i < len(s); i++ {\n\t\t\tif t[i] != s[i] {\n\t\t\t\tgoto NEXT\n\t\t\t}\n\t\t}\n\t\treturn i\n\t}\nNEXT:\n\tif i := _Hash_table[(h>>16)&uint32(len(_Hash_table)-1)]; int(i&0xff) == len(s) {\n\t\tt := _Hash_text[i>>8 : i>>8+i&0xff]\n\t\tfor i := 0; i < len(s); i++ {\n\t\t\tif t[i] != s[i] {\n\t\t\t\treturn 0\n\t\t\t}\n\t\t}\n\t\treturn i\n\t}\n\treturn 0\n}",
"func hashString(data string) string {\n\treturn fmt.Sprintf(\"%x\", hashBytes([]byte(data)))\n}",
"func (hash Hash) String() string {\n\treturn BytesString(hash[:])\n}",
"func CreateSha1(data []byte) string {\n\t_sha1 := sha1.New()\n\treturn base64.StdEncoding.EncodeToString(_sha1.Sum(data))\n}",
"func (h Hash) String() string {\n\treturn fmt.Sprintf(\"%032x\", []byte(h))\n}",
"func (h HashAlgorithm) String() string {\n\treturn string(h)\n}",
"func HashString(source string) string {\n\ttarget := md5.New()\n\tio.WriteString(target, source)\n\treturn fmt.Sprintf(\"%x\", target.Sum(nil))\n}",
"func HASH(s string, salt string) string {\n\treturn MD5(SHA256(s, salt), salt)\n}",
"func (h Hash) Hex() string { return hexutil.Encode(h[:]) }",
"func hashString(original string) string {\n\th := md5.New()\n\tio.WriteString(h, original)\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}",
"func hashIt(s string, bit int) int {\n\th := sha1.New()\n\th.Write([]byte(s))\n\tbs := h.Sum(nil)\n\thashValue := math.Mod(float64(bs[len(bs)-1]), math.Exp2(float64(bit)))\n\treturn int(hashValue)\n}",
"func hashSHA256(input string) string {\n\th := sha1.New()\n\th.Write([]byte(input))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func hashstr(s string) HashType {\n\tvar result uint32\n\tresult = 0\n\tbytes := []byte(s)\n\n\tfor n, b := range bytes {\n\t\tresult ^= uint32(b) ^ (uint32(n*int(b)) << 8)\n\t\ttmp := result >> 27\n\t\tresult = result << 5\n\t\tresult = result | tmp\n\t}\n\n\treturn HashType(result)\n\n}",
"func HashString(s string) Hash {\n\th := NewHasher()\n\th.Write([]byte(s))\n\treturn h.Sum()\n}",
"func sha1Hash(slices [][]byte) []byte {\n\thsha1 := sha1.New()\n\tfor _, slice := range slices {\n\t\thsha1.Write(slice)\n\t}\n\treturn hsha1.Sum(nil)\n}",
"func SHA1Base64String(data string) string {\n\thash := sha1.Sum([]byte(data))\n\treturn base64.StdEncoding.EncodeToString(hash[:])\n}",
"func (o *ResultAllOfHashes) GetSha1() string {\n\tif o == nil || o.Sha1 == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Sha1\n}",
"func Hasher(value string) string {\n\th := fnv.New32a()\n\t_, _ = h.Write([]byte(value))\n\treturn fmt.Sprintf(\"%v\", h.Sum32())\n}",
"func hashString(s string) int {\n\tvar h uint32\n\tfor i := 0; i < len(s); i++ {\n\t\th ^= uint32(s[i])\n\t\th *= 16777619\n\t}\n\treturn int(h)\n}",
"func SignatureHash(signature string) string {\n\treturn fmt.Sprintf(\"%x\", sha512.Sum384([]byte(signature)))\n}"
] | [
"0.7269807",
"0.7203534",
"0.71482205",
"0.7119544",
"0.7103812",
"0.70607626",
"0.70053756",
"0.70053756",
"0.6750188",
"0.66032577",
"0.6569838",
"0.6504363",
"0.64967155",
"0.6471179",
"0.6468159",
"0.6466895",
"0.645789",
"0.6418545",
"0.63692164",
"0.6360325",
"0.63306606",
"0.63185275",
"0.63097715",
"0.6231314",
"0.6222296",
"0.6213212",
"0.6201908",
"0.6194555",
"0.6171105",
"0.61684245",
"0.6165259",
"0.61396444",
"0.61167645",
"0.61167645",
"0.61167645",
"0.6112145",
"0.6108902",
"0.61049855",
"0.6104622",
"0.60690403",
"0.6038568",
"0.6025319",
"0.60241723",
"0.60182935",
"0.6016029",
"0.5972861",
"0.597277",
"0.59690326",
"0.59690326",
"0.5947493",
"0.59330744",
"0.5914738",
"0.59005207",
"0.5872273",
"0.5869013",
"0.5867003",
"0.5852959",
"0.5831152",
"0.5824684",
"0.58202237",
"0.58197665",
"0.58164376",
"0.58109117",
"0.58108634",
"0.57697445",
"0.57644945",
"0.5764041",
"0.5763578",
"0.57634383",
"0.57507634",
"0.5747379",
"0.57466197",
"0.5740013",
"0.5727811",
"0.5727811",
"0.5709531",
"0.5700596",
"0.5692872",
"0.5687977",
"0.5681934",
"0.5655973",
"0.5651875",
"0.5633806",
"0.563191",
"0.5631278",
"0.56306475",
"0.5623299",
"0.56227595",
"0.5622595",
"0.5619548",
"0.56080294",
"0.56025875",
"0.5588391",
"0.55869937",
"0.5578658",
"0.5556694",
"0.55528146",
"0.5548023",
"0.55427843",
"0.5541988"
] | 0.8327798 | 0 |
ValidHash returns true if length of s same as size of a SHA1 checksum. | func ValidHash(s string) bool {
return len(s) == sha1.Size*2
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func HashIsSHA1(hash string) bool {\n\treturn len(hash) == 40\n}",
"func isValidHash(hashType, hash string) bool {\n\tswitch hashType {\n\tcase string(HashMD5):\n\t\treturn len(hash) == 32\n\tcase string(HashSHA1):\n\t\treturn len(hash) == 40\n\tcase string(HashSHA256):\n\t\treturn len(hash) == 64\n\tcase string(HashSHA512):\n\t\treturn len(hash) == 128\n\tdefault:\n\t\treturn false\n\t}\n}",
"func Validate(h, s, p string) bool {\n\treturn h == ComputeHash(p, s)\n}",
"func IsValidHash(s string) bool {\n\tout, err := b58.Decode(s)\n\tif err != nil {\n\t\treturn false\n\t}\n\t_, err = mh.Cast(out)\n\treturn err == nil\n}",
"func ValidHash512(s string) bool {\n\treturn len(s) == sha512.Size*2\n}",
"func IsSHA1(str string) bool {\n\treturn IsHash(str, \"sha1\")\n}",
"func (blk Block) ValidHash() bool {\n\t// TODO\n\n\thash := blk.Hash\n\n\tif hash == nil {\n\t\treturn false\n\t}\n\n\tl := len(hash)\n\n\tnBytes := int(blk.Difficulty / 8)\n\tnBits := blk.Difficulty % 8\n\n\tfor i := l - 1; i >= l-nBytes; i-- {\n\t\tif hash[i] != '\\x00' {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif hash[l-nBytes-1]%(1<<nBits) != 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}",
"func IsValidDigest(hash string) bool {\n\t// Currently we expect all digests to be ASCII encoded MD5 hashes.\n\tif len(hash) != 32 {\n\t\treturn false\n\t}\n\n\tfor _, c := range []byte(hash) {\n\t\tif ((c >= '0') && (c <= '9')) ||\n\t\t\t((c >= 'a') && (c <= 'f')) ||\n\t\t\t((c >= 'A') && (c <= 'F')) {\n\t\t\tcontinue\n\t\t}\n\t\treturn false\n\t}\n\treturn true\n}",
"func IsHashValid(hash string, difficulty int) bool {\n\tprefix := strings.Repeat(\"0\", difficulty)\n\treturn strings.HasPrefix(hash, prefix)\n}",
"func IsHashValid(hash string, difficulty int) bool {\n\tprefix := strings.Repeat(\"0\", difficulty)\n\treturn strings.HasPrefix(hash, prefix)\n}",
"func IsValidHash(obj string) bool {\n\treturn hashPtn.MatchString(obj)\n}",
"func Sha1Check(hashed, pwd string) bool {\n\thashed = Base64Decode(hashed)\n\tif len(hashed) < 4 {\n\t\treturn false\n\t}\n\n\tsalt := hashed[len(hashed)-4:]\n\treturn Sha1(Md5(pwd)+salt)+salt == hashed\n}",
"func IsHash(str string, algorithm string) bool {\n\tlen := \"0\"\n\talgo := strings.ToLower(algorithm)\n\n\tif algo == \"crc32\" || algo == \"crc32b\" {\n\t\tlen = \"8\"\n\t} else if algo == \"md5\" || algo == \"md4\" || algo == \"ripemd128\" || algo == \"tiger128\" {\n\t\tlen = \"32\"\n\t} else if algo == \"sha1\" || algo == \"ripemd160\" || algo == \"tiger160\" {\n\t\tlen = \"40\"\n\t} else if algo == \"tiger192\" {\n\t\tlen = \"48\"\n\t} else if algo == \"sha256\" {\n\t\tlen = \"64\"\n\t} else if algo == \"sha384\" {\n\t\tlen = \"96\"\n\t} else if algo == \"sha512\" {\n\t\tlen = \"128\"\n\t} else {\n\t\treturn false\n\t}\n\n\treturn Matches(str, \"^[a-f0-9]{\"+len+\"}$\")\n}",
"func hasChecksum(n int64) bool {\n\t// 512 is chosen because it's a minimum disk sector size\n\t// smaller than (and multiplies to) OS page size in most systems\n\treturn (n % 512) == sha256.Size\n}",
"func (s *grpcServer) validateHash(hash string, logPrefix string) error {\n\tif len(hash) != hashKeyLength {\n\t\tmsg := fmt.Sprintf(\"Hash length must be length %d\", hashKeyLength)\n\t\ts.accessLogger.Printf(\"%s %s: %s\", logPrefix, hash, msg)\n\t\treturn status.Error(codes.InvalidArgument, msg)\n\t}\n\n\tif !hashKeyRegex.MatchString(hash) {\n\t\tmsg := \"Malformed hash\"\n\t\ts.accessLogger.Printf(\"%s %s: %s\", logPrefix, hash, msg)\n\t\treturn status.Error(codes.InvalidArgument, msg)\n\t}\n\n\treturn nil\n}",
"func (s *Salt) IsValid() bool {\n\treturn len(*s) == saltLen\n}",
"func HashIsMD5(hash string) bool {\n\treturn len(hash) == 32\n}",
"func Validate(digest *repb.Digest) error {\n\tif digest == nil {\n\t\treturn errors.New(\"nil digest\")\n\t}\n\tif ok, err := validateHashLength(digest.Hash); !ok {\n\t\treturn err\n\t}\n\tif !hexStringRegex.MatchString(digest.Hash) {\n\t\treturn fmt.Errorf(\"hash is not a lowercase hex string (%s)\", digest.Hash)\n\t}\n\tif digest.SizeBytes < 0 {\n\t\treturn fmt.Errorf(\"expected non-negative size, got %d\", digest.SizeBytes)\n\t}\n\treturn nil\n}",
"func validateHexHash(s string) error {\n\tif has0xPrefix(s) {\n\t\ts = s[2:]\n\t}\n\tif len(s)%2 == 1 {\n\t\ts = \"0\" + s\n\t}\n\t_, err := hex.DecodeString(s)\n\treturn err\n}",
"func IsDigestValid(decryptedCell []byte) bool {\n\n\tif len(decryptedCell) != 512 {\n\t\treturn false\n\t}\n\tdigest := DecodePayloadDigest(decryptedCell)\n\tpayload := DecodeRelayPayload(decryptedCell)\n\tsum := md5.Sum(payload)\n\n\tfor i := 0; i < DigestLength; i++ {\n\t\tif digest[i] != sum[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}",
"func ValidHash256(s string) bool {\n\treturn len(s) == sha256.Size*2\n}",
"func checkHashSize(hexStr string) int {\n\tmaxint64 := 9223372036854775807\n\tminint64 := -9223372036854775807\n\tint64val := hex2int(hexStr)\n\n\tfor len(hexStr) > 0 && int64val >= maxint64 || int64val <= minint64 {\n\t\thexStr = hexStr[:len(hexStr)-1]\n\t\tint64val = hex2int(hexStr)\n\t}\n\treturn int64val\n}",
"func TestHash(t *testing.T) {\n\t// Hash of block 234439.\n\tblockHashStr := \"14a0810ac680a3eb3f82edc878cea25ec41d6b790744e5daeef\"\n\tblockHash, err := NewHashFromStr(blockHashStr)\n\tassert.NoError(t, err)\n\n\t// Hash of block 234440 as byte slice.\n\tbuf := []byte{\n\t\t0x79, 0xa6, 0x1a, 0xdb, 0xc6, 0xe5, 0xa2, 0xe1,\n\t\t0x39, 0xd2, 0x71, 0x3a, 0x54, 0x6e, 0xc7, 0xc8,\n\t\t0x75, 0x63, 0x2e, 0x75, 0xf1, 0xdf, 0x9c, 0x3f,\n\t\t0xa6, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t}\n\n\thash, err := NewHash(buf)\n\tassert.NoError(t, err)\n\n\t// Ensure proper size.\n\tassert.Equal(t, HashSize, len(hash))\n\n\t// Ensure contents match.\n\tassert.Equal(t, buf[:], hash[:])\n\n\t// Ensure contents of hash of block 234440 don't match 234439.\n\tassert.False(t, hash.IsEqual(blockHash))\n\n\t// Set hash from byte slice and ensure contents match.\n\terr = hash.SetBytes(blockHash.CloneBytes())\n\tassert.NoError(t, err)\n\tassert.True(t, hash.IsEqual(blockHash))\n\n\t// Ensure nil hashes are handled properly.\n\tassert.True(t, (*Hash)(nil).IsEqual(nil))\n\n\tassert.False(t, hash.IsEqual(nil))\n\n\t// Invalid size for SetBytes.\n\terr = hash.SetBytes([]byte{0x00})\n\tassert.NotNil(t, err)\n\n\t// Invalid size for NewHash.\n\tinvalidHash := make([]byte, HashSize+1)\n\t_, err = NewHash(invalidHash)\n\tassert.NotNil(t, err)\n\n\tif err == nil {\n\t\tt.Errorf(\"NewHash: failed to received expected err - got: nil\")\n\t}\n}",
"func Valid(luhnString string) bool {\n\tchecksumMod := calculateChecksum(luhnString, false) % 10\n\n\treturn checksumMod == 0\n}",
"func IsSignerHashValid(hash []byte) (bool, *Signer) {\n\tif sha512.Size != len(hash) {\n\t\treturn false, nil\n\t}\n\n\treturn true, NewSigner(hash)\n}",
"func isValidHashType(ht string) bool {\n\treturn ht == string(HashMD5) || ht == string(HashSHA1) || ht == string(HashSHA256) || ht == string(HashSHA512)\n}",
"func (ma *MixedcaseAddress) ValidChecksum() bool {\n\treturn ma.original == ma.addr.Hex()\n}",
"func HashIsSHA256(hash string) bool {\n\treturn len(hash) == 64\n}",
"func CheckHash(password, hash string) (match bool, params *Params, err error) {\n\tparams, salt, key, err := DecodeHash(hash)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\n\totherKey := argon2.IDKey([]byte(password), salt, params.Iterations, params.Memory, params.Parallelism, params.KeyLength)\n\n\tkeyLen := int32(len(key))\n\totherKeyLen := int32(len(otherKey))\n\n\tif subtle.ConstantTimeEq(keyLen, otherKeyLen) == 0 {\n\t\treturn false, params, nil\n\t}\n\tif subtle.ConstantTimeCompare(key, otherKey) == 1 {\n\t\treturn true, params, nil\n\t}\n\treturn false, params, nil\n}",
"func validSha(sha string) error {\n\tif len(sha) != 40 {\n\t\treturn fmt.Errorf(\"sha not 40 characters: %s\", sha)\n\t}\n\t// TODO(dbentley): check that it's hexadecimal?\n\treturn nil\n}",
"func Valid(input string) bool {\n\tstrippedString := strings.Replace(input, \" \", \"\", -1)\n\tsum := checksum(strippedString)\n\tif len(strippedString) < 2 {\n\t\treturn false\n\t}\n\treturn (sum % 10) == 0\n}",
"func Validate(token []byte) (isValid bool) {\n\t//fast path\n\tif len(token) != TOKEN_SIZE {\n\t\treturn\n\t}\n\n\thash := createHash(token[32:])\n\n\t//now compare our hash with input\n\tif bytes.Compare(token[0:32], hash) == 0 {\n\t\tisValid = true\n\t}\n\n\treturn\n}",
"func (o *ResultAllOfHashes) HasSha1() bool {\n\tif o != nil && o.Sha1 != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func testLenHash(b []byte) uint {\n\treturn uint(len(b))\n}",
"func (h *ArgonHasher) Validate(password, encoded string) (bool, error) {\n\tparams, salt, hash, err := decodeHash(encoded)\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tpasswordHash := argon2.IDKey([]byte(password), salt, params.Iterations, params.Memory, params.Threads, params.KeyLength)\n\n\tif subtle.ConstantTimeCompare(hash, passwordHash) == 0 {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}",
"func Validate(username, hash string, userCreds database.UserCreds) (bool, string) {\n\t// Take SHA256 hash of the hash given by user\n\thashOfHash := sha256.Sum256([]byte(hash))\n\thashString := hex.EncodeToString(hashOfHash[:])\n\t// If the hash is not equal throw error\n\tif hashString != userCreds.Hash {\n\t\tfmt.Printf(\"%s Error ::%s Hash is Invalid\\n\\n\", chalk.Red, chalk.Reset)\n\t\treturn false, \"Invalid Hash. Your password was incorrect.\"\n\t}\n\n\t// If equal decrement n and change hash in database\n\tuserCreds.Hash = hash\n\tuserCreds.N -= 1\n\tdatabase.Set(username, userCreds)\n\treturn true, \"\"\n}",
"func VerifyHmacSha1(message []byte, secret string, signature string) bool {\n\n\tsign := HmacSha1(message, secret)\n\n\tactual := make([]byte, 20)\n\thex.Decode(actual, []byte(signature))\n\n\treturn hmac.Equal(sign, actual)\n}",
"func CheckHash(s, hash string) bool {\n\terr := bcrypt.CompareHashAndPassword([]byte(hash), []byte(s))\n\treturn err == nil\n}",
"func Valid(password string, hashedPassword string) (valid bool,\n\tinsecure bool, err error) {\n\n\tif strings.HasPrefix(hashedPassword, \"$2a$\") {\n\t\tinsecure = false\n\t\tvalid, err = validBCRYPT(password, hashedPassword)\n\t\treturn\n\t}\n\n\tinsecure = true\n\tswitch {\n\tcase strings.HasPrefix(hashedPassword, \"{MD5}\"):\n\t\tvalid, err = validMD5(password, hashedPassword)\n\t\treturn\n\tcase strings.HasPrefix(hashedPassword, \"{SHA}\"):\n\t\tvalid, err = validSHA1(password, hashedPassword)\n\t\treturn\n\tcase strings.HasPrefix(hashedPassword, \"{SSHA}\"):\n\t\tvalid, err = validSSHA(password, hashedPassword)\n\t\treturn\n\tdefault:\n\t\treturn false, false, merry.New(\"could not identify password hash type\")\n\t}\n}",
"func CheckHash(data []byte, target [blake2b.Size]byte) bool {\n\tif Hash(data) == target {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}",
"func hash(s string) uint32 {\n h := fnv.New32a()\n h.Write([]byte(s))\n return h.Sum32()\n}",
"func (h *bcryptHash) Check(s, hash string) bool {\n\terr := bcrypt.CompareHashAndPassword([]byte(hash), []byte(s))\n\treturn err == nil\n}",
"func (imageName *ImageName) HasDigest() bool {\n\treturn strings.HasPrefix(imageName.Tag, \"sha256:\")\n}",
"func (self *Address) HasValidChecksum() bool {\n\tc := self.CreateChecksum()\n\treturn bytes.Equal(c[:], self.Checksum[:])\n}",
"func Check(name string, hash, pass, salt []byte) (bool, error) {\n\tp, err := Hash(name, pass, salt)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif len(p) != len(hash) {\n\t\treturn false, nil\n\t}\n\tfor i, c := range hash {\n\t\tif c != p[i] {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn true, nil\n}",
"func (h *Hash) Check(plainText string) error {\n\tb, err := hex.DecodeString(h.Salt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\th.HashFn.Reset() // allow reuse\n\th.HashFn.Write([]byte(plainText))\n\th.HashFn.Write(b)\n\tif result := hex.EncodeToString(h.HashFn.Sum(nil)); result != h.Hash {\n\t\treturn ErrIncorrect\n\t}\n\n\treturn nil\n}",
"func (h Bcrypt) IsValid(hash string, raw string) bool {\n\terr := bcrypt.CompareHashAndPassword([]byte(hash), []byte(raw))\n\treturn err == nil\n}",
"func (s *SHA1) Equal(s2 interface{}) bool {\n\tswitch v := s2.(type) {\n\tcase string:\n\t\treturn v == s.String()\n\tcase [20]byte:\n\t\treturn v == s.bytes\n\tcase *SHA1:\n\t\treturn v.bytes == s.bytes\n\t}\n\treturn false\n}",
"func (bh *BlockHeader) Valid() bool {\r\n\ttarget, err := ExpandTargetFromAsInt(hex.EncodeToString(bh.Bits))\r\n\tif err != nil {\r\n\t\treturn false\r\n\t}\r\n\r\n\tdigest := bt.ReverseBytes(crypto.Sha256d(bh.Bytes()))\r\n\tvar bn *big.Int = big.NewInt(0)\r\n\tbn.SetBytes(digest)\r\n\r\n\treturn bn.Cmp(target) < 0\r\n}",
"func Hash(s string) string {\n\tSha1Inst := sha1.New()\n\tSha1Inst.Write([]byte(s))\n\tresult := Sha1Inst.Sum([]byte(\"\"))\n\treturn fmt.Sprintf(\"%x\", result)\n}",
"func verifySHA1(filename, checksum string) error {\n\t// Try to open the file with the given filename.\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\t// Generate a SHA1 hash for the file.\n\thash := sha1.New()\n\tif _, err := io.Copy(hash, file); err != nil {\n\t\treturn err\n\t}\n\n\t// Test if the hash matches the checksum.\n\tsha1 := hex.EncodeToString(hash.Sum(nil))\n\tif sha1 != checksum {\n\t\treturn errors.New(\"sha1 checksum doesn't validate\")\n\t}\n\n\treturn nil\n}",
"func validSignature(body, key []byte, sig string) bool {\n\tconst prefix = \"sha1=\"\n\tif len(sig) < len(prefix) {\n\t\treturn false\n\t}\n\tsig = sig[len(prefix):]\n\tmac := hmac.New(sha1.New, key)\n\tmac.Write(body)\n\tb, err := hex.DecodeString(sig)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\t// Use hmac.Equal to avoid timing attacks.\n\treturn hmac.Equal(mac.Sum(nil), b)\n}",
"func Check(hashed, pwd string) bool {\n\thashed = Base64Decode(hashed)\n\tif len(hashed) < 4 {\n\t\treturn false\n\t}\n\n\tsalt := hashed[len(hashed)-4:]\n\treturn Sha256(Md5(pwd)+salt)+salt == hashed\n}",
"func IsValid(matricule string) (bool, error) {\n\tr := true\n\n\tif len([]rune(matricule)) != 13 {\n\t\t// Matricule is of wrong size\n\t\tr = false\n\t} else if !containsOnlyDigits(matricule) {\n\t\t// Matricule contains non-digit character\n\t\tr = false\n\t} else {\n\t\t// compute the checksum of the matricule's root\n\t\tchecksum, err := generateChecksum(matricule[0:11])\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\t// Compare checksums (computed vs given)\n\t\tif checksum != matricule[11:] {\n\t\t\tr = false\n\t\t}\n\t}\n\n\treturn r, nil\n}",
"func IsSHA512(str string) bool {\n\treturn IsHash(str, \"sha512\")\n}",
"func (s *Storage) Check(sha256Hash string) (exists bool, size int64, err error) {\n\tf, err := s.fs.Open(hashName(sha256Hash))\n\tif err != nil && err != mgo.ErrNotFound {\n\t\treturn false, 0, err\n\t}\n\tif err == nil {\n\t\tsize := f.Size()\n\t\tf.Close()\n\t\treturn true, size, nil\n\t}\n\treturn false, 0, nil\n}",
"func checksumOK(data []byte) bool {\n\tif len(data) <= 4 {\n\t\treturn false\n\t}\n\tsum := crc32.ChecksumIEEE(data[4:])\n\treturn binary.BigEndian.Uint32(data[:4]) == sum\n}",
"func CheckHMACHash(data string, hash string, secret string) bool {\n\th := hmac.New(sha256.New, []byte(secret))\n\th.Write([]byte(data))\n\t// Get result and encode as hexadecimal string\n\tsha := hex.EncodeToString(h.Sum(nil))\n\treturn sha == hash\n}",
"func CheckString(name, hash, pass, salt string) (bool, error) {\n\t_hash, err := HashString(name, pass, salt)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn hash == _hash, nil\n}",
"func TestHashString(t *testing.T) {\n\t// Block 100000 hash.\n\twantStr := \"000000000003ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506\"\n\thash := Hash([HashSize]byte{ // Make go vet happy.\n\t\t0x06, 0xe5, 0x33, 0xfd, 0x1a, 0xda, 0x86, 0x39,\n\t\t0x1f, 0x3f, 0x6c, 0x34, 0x32, 0x04, 0xb0, 0xd2,\n\t\t0x78, 0xd4, 0xaa, 0xec, 0x1c, 0x0b, 0x20, 0xaa,\n\t\t0x27, 0xba, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t})\n\n\thashStr := hash.String()\n\tassert.Equal(t, wantStr, hashStr)\n}",
"func hash(s string) int {\n\th := fnv.New32a()\n\tif _, err := h.Write([]byte(s)); err != nil {\n\t\tpanic(err) // should never happen\n\t}\n\n\treturn int(h.Sum32() & 0x7FFFFFFF) // mask MSB of uint32 as this will be sign bit\n}",
"func VerifyShaHashedPassword(password, hashedPassword, saltPassword string) bool {\n\treturn HashPassword(password, saltPassword) == hashedPassword\n}",
"func SHA1(s string) string {\n\th := sha1.New()\n\th.Write([]byte(s))\n\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func SHA1(s string) string {\n\th := sha1.New()\n\th.Write([]byte(s))\n\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func (t *HashType) IsValid() bool {\n\t_, valid := validHashes[*t]\n\treturn valid\n}",
"func (d *digest) Size() int { return crc64.Size }",
"func hashLen(u uint64, hashLog, mls uint8) uint32 {\n\tswitch mls {\n\tcase 5:\n\t\treturn hash5(u, hashLog)\n\tcase 6:\n\t\treturn hash6(u, hashLog)\n\tcase 7:\n\t\treturn hash7(u, hashLog)\n\tcase 8:\n\t\treturn hash8(u, hashLog)\n\tdefault:\n\t\treturn hash4x64(u, hashLog)\n\t}\n}",
"func CheckIntegrity(content string, hash string) bool {\n\tif hash != GetChecksum(content) {\n\t\treturn false\n\t}\n\treturn true\n}",
"func Valid(data []byte) (ok bool, start int) {\n n := len(data)\n if n == 0 {\n return false, -1\n }\n s := rt.Mem2Str(data)\n p := 0\n m := types.NewStateMachine()\n ret := native.ValidateOne(&s, &p, m)\n types.FreeStateMachine(m)\n\n if ret < 0 {\n return false, p-1\n }\n\n /* check for trailing spaces */\n for ;p < n; p++ {\n if (types.SPACE_MASK & (1 << data[p])) == 0 {\n return false, p\n }\n }\n\n return true, ret\n}",
"func verifyChecksum(in uint8, cmd uint8, dataLen uint8, data []byte) bool {\n\n\treturn in == calculateChecksum(cmd, dataLen, data)\n}",
"func Hash(length int, key string) int64 {\n\tif key == \"\" {\n\t\treturn 0\n\t}\n\thc := hashCode(key)\n\treturn (hc ^ (hc >> 16)) % int64(length)\n}",
"func SHA1(s string) string {\n\treturn stringHasher(sha1.New(), s)\n}",
"func (hasher *SHA256) HashLength() uint {\n\treturn 64\n}",
"func IsTSValid(hash []byte, timestamp int64) bool {\n\treturn IsTSValid_(hash, timestamp, time.Now().Unix())\n}",
"func CheckHash(input, hash string) bool {\n\terr := bcrypt.CompareHashAndPassword([]byte(hash), []byte(input))\n\treturn err == nil\n}",
"func (p *PasswordStruct) CheckHash(password string) (bool, error) {\n\terr := bcrypt.CompareHashAndPassword(p.hash, []byte(password))\n\treturn err == nil, nil\n}",
"func VerifySha256(password, hash string) bool {\n return Sha256Hash(password) == hash\n}",
"func sameHash(a, b func() hash.Hash) bool {\n\tha := a().Sum(make([]byte, 0))\n\thb := b().Sum(make([]byte, 0))\n\treturn bytes.Equal(ha, hb)\n}",
"func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool",
"func IsTruncatedCommitSHA(sha string) bool {\n\treturn truncatedCommitSHARegex.MatchString(sha)\n}",
"func (s *Script) IsPayToScriptHash() bool {\n\tss := *s\n\tif len(ss) != p2SHScriptLen {\n\t\treturn false\n\t}\n\treturn ss[0] == byte(OPHASH160) && ss[1] == ripemd160.Size && ss[22] == byte(OPEQUAL)\n}",
"func (p password) isValid1() bool {\n\tcount := strings.Count(p.value, p.policy.letter)\n\treturn p.policy.min <= count && count <= p.policy.max\n}",
"func HashStringSha1(hs string) []byte {\n\tdata := []byte(hs)\n\thash := sha1.Sum(data)\n\treturn hash[:]\n}",
"func checkContentHash(hash string, data []byte) error {\n\tif hash == \"\" {\n\t\treturn nil\n\t}\n\thexHash := fmt.Sprintf(\"%x\", md5.Sum(data))\n\tif hexHash != hash {\n\t\treturn fmt.Errorf(\"content hash incorrect. expected %s, got %s\", hash, hexHash)\n\t}\n\treturn nil\n}",
"func CheckValid(data Dstream) bool {\n\n\tdata.Reset()\n\tnames := data.Names()\n\n\tfor c := 0; data.Next(); c++ {\n\t\tn0 := ilen(data.GetPos(0))\n\t\tfor j := 1; j < len(names); j++ {\n\t\t\tn1 := ilen(data.GetPos(j))\n\t\t\tif n1 != n0 {\n\t\t\t\tmsg := fmt.Sprintf(\"Length mismatch in chunk %d: len(%s) = %d, len(%s) = %d\\n\",\n\t\t\t\t\tc, names[0], n0, names[j], n1)\n\t\t\t\t_, _ = io.WriteString(os.Stderr, msg)\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\tdata.Reset()\n\n\treturn true\n}",
"func Valid(s string) bool {\n\ts = strings.ReplaceAll(s, \" \", \"\")\n\tif len(s) <= 1 {\n\t\treturn false\n\t}\n\tcheckDigit, err := checkSum(s)\n\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn checkDigit%10 == 0\n}",
"func (this Hash) IsValid() <-chan bool {\n\tc := make(chan bool, 1)\n\tgo func() {\n\t\tdefer close(c)\n\t\tc <- (<-this.Type() == \"hash\")\n\t}()\n\treturn c\n}",
"func stringHash(s string, seed uintptr) uintptr",
"func ValidateBlockLength(blockLength uint32) (bool) {\n if blockLength <= 4294967295 && blockLength > 0 { //2^32 -1 ~ 4GB or maximum possible block length\n return true\n }\n return false\n}",
"func TestNewHashFromStr(t *testing.T) {\n\ttests := []struct {\n\t\tin string\n\t\twant Hash\n\t\terr error\n\t}{\n\t\t// Genesis hash.\n\t\t{\n\t\t\t\"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f\",\n\t\t\tmainNetGenesisHash,\n\t\t\tnil,\n\t\t},\n\n\t\t// Genesis hash with stripped leading zeros.\n\t\t{\n\t\t\t\"19d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f\",\n\t\t\tmainNetGenesisHash,\n\t\t\tnil,\n\t\t},\n\n\t\t// Empty string.\n\t\t{\n\t\t\t\"\",\n\t\t\tHash{},\n\t\t\tnil,\n\t\t},\n\n\t\t// Single digit hash.\n\t\t{\n\t\t\t\"1\",\n\t\t\tHash([HashSize]byte{ // Make go vet happy.\n\t\t\t\t0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t}),\n\t\t\tnil,\n\t\t},\n\n\t\t// Block 203707 with stripped leading zeros.\n\t\t{\n\t\t\t\"3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc\",\n\t\t\tHash([HashSize]byte{ // Make go vet happy.\n\t\t\t\t0xdc, 0xe9, 0x69, 0x10, 0x94, 0xda, 0x23, 0xc7,\n\t\t\t\t0xe7, 0x67, 0x13, 0xd0, 0x75, 0xd4, 0xa1, 0x0b,\n\t\t\t\t0x79, 0x40, 0x08, 0xa6, 0x36, 0xac, 0xc2, 0x4b,\n\t\t\t\t0x26, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t}),\n\t\t\tnil,\n\t\t},\n\n\t\t// Hash string that is too long.\n\t\t{\n\t\t\t\"01234567890123456789012345678901234567890123456789012345678912345\",\n\t\t\tHash{},\n\t\t\tErrHashStrSize,\n\t\t},\n\n\t\t// Hash string that is contains non-hex chars.\n\t\t{\n\t\t\t\"abcdefg\",\n\t\t\tHash{},\n\t\t\thex.InvalidByteError('g'),\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tresult, err := NewHashFromStr(test.in)\n\t\tif assert.Equal(t, test.err, err) {\n\t\t\tcontinue\n\t\t}\n\t\tif assert.NoError(t, err) {\n\t\t\tcontinue\n\t\t}\n\t\tif assert.False(t, test.want.IsEqual(result)) {\n\t\t\tcontinue\n\t\t}\n\t}\n}",
"func CheckPasswordHash(password, hash string) bool {\n\treturn true\n}",
"func (s *SSN) Valid() bool {\n\t// Ommit all but 10 digits from the SSN\n\tssn := fmt.Sprintf(\"%s%s\", s.Formatted[2:8], s.Formatted[9:13])\n\n\t// Add the Luhn iteration sum to the last digit and ensure\n\t// that we always get 0 rest from mod 10.\n\tsum, _ := strconv.Atoi(string(ssn[len(ssn)-1]))\n\tsum += calculateLuhnSum(ssn)\n\n\treturn sum%10 == 0\n}",
"func ValidateFileHash(filepath string, hashed string) error {\n\ths := strings.Split(hashed, \":\")\n\tif len(hs) != 2 {\n\t\treturn errors.Errorf(\"unknown hashed format, expect is `sha256:xxxx`, but got `%s`\", hashed)\n\t}\n\n\tvar hasher hash.Hash\n\tswitch hs[0] {\n\tcase \"sha256\":\n\t\thasher = sha256.New()\n\tcase \"md5\":\n\t\thasher = md5.New()\n\tdefault:\n\t\treturn errors.Errorf(\"unknown hasher `%s`\", hs[0])\n\t}\n\n\tfp, err := os.Open(filepath)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"open file `%s`\", filepath)\n\t}\n\tdefer CloseQuietly(fp)\n\n\tif _, err = io.Copy(hasher, fp); err != nil {\n\t\treturn errors.Wrap(err, \"read file content\")\n\t}\n\n\tactualHash := hex.EncodeToString(hasher.Sum(nil))\n\tif hs[1] != actualHash {\n\t\treturn errors.Errorf(\"hash `%s` not match expect `%s`\", actualHash, hs[1])\n\t}\n\n\treturn nil\n}",
"func strhash0(p unsafe.Pointer, h uintptr) uintptr",
"func (s *hashBLAKE2s) HashLen() int {\n\treturn blake2s.Size\n}",
"func memhash(p unsafe.Pointer, h, s uintptr) uintptr",
"func memhash(p unsafe.Pointer, h, s uintptr) uintptr",
"func strhash(a unsafe.Pointer, h uintptr) uintptr",
"func isEquivalentHash(alg Algorithm, signatureValue string, secret *pbauth.Secret, hashedValue string) bool {\n\tif err := ValidateSecret(secret); err != nil {\n\t\treturn false\n\t}\n\t/*\n\t\thashSignature cannot be reversed all you can do is hash the same character and compare it with a hashed value.\n\t\tIf it evaluates to true, then the character is a what is in the hash.\n\t\tThe isValidHash function only hashes the value with the secret and compared it with the hash.\n\t*/\n\tactualHashedValue, err := hashSignature(alg, signatureValue, secret)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn hashedValue == actualHashedValue\n}",
"func (e ChecksumMismatch) IsChecksumMismatch() {}"
] | [
"0.6951018",
"0.669786",
"0.65804607",
"0.6508801",
"0.6503572",
"0.64998055",
"0.64975005",
"0.6400095",
"0.6377068",
"0.6377068",
"0.63320214",
"0.62742746",
"0.62287146",
"0.6126085",
"0.6044074",
"0.60417765",
"0.6033562",
"0.6029276",
"0.6018738",
"0.6017965",
"0.5970436",
"0.59081525",
"0.5856068",
"0.58525574",
"0.5787849",
"0.57754046",
"0.57475346",
"0.5698196",
"0.56860596",
"0.56757724",
"0.56535023",
"0.5644713",
"0.56386805",
"0.5623341",
"0.55981153",
"0.5593289",
"0.55844694",
"0.55647147",
"0.5541143",
"0.5536487",
"0.5526588",
"0.54844475",
"0.54701334",
"0.54479396",
"0.5441614",
"0.544123",
"0.5412116",
"0.54000324",
"0.5379872",
"0.53758514",
"0.53748375",
"0.53662556",
"0.5360387",
"0.5360177",
"0.53596216",
"0.53545904",
"0.5343959",
"0.53388333",
"0.5338548",
"0.5334769",
"0.53281116",
"0.53260237",
"0.53208274",
"0.53208274",
"0.53163534",
"0.53078264",
"0.5271204",
"0.5261905",
"0.52595776",
"0.5255606",
"0.5252732",
"0.525036",
"0.522856",
"0.52144605",
"0.5205566",
"0.5201508",
"0.5200335",
"0.5190594",
"0.5178754",
"0.517601",
"0.5175751",
"0.51742995",
"0.5167423",
"0.5166772",
"0.51659876",
"0.51506746",
"0.51483357",
"0.5139993",
"0.512979",
"0.51273346",
"0.5119314",
"0.5100328",
"0.5097528",
"0.50952023",
"0.50890535",
"0.50742173",
"0.50742173",
"0.5071576",
"0.50664234",
"0.5063732"
] | 0.8167188 | 0 |
EncodeHash256 returns the sha256 encoding of s. | func EncodeHash256(s string) string {
h := sha256.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func SHA256(s string) string {\n\treturn stringHasher(sha256.New(), s)\n}",
"func SHA256(text string) string {\n\talgorithm := sha256.New()\n\treturn stringHasher(algorithm, text)\n}",
"func hashSHA256(str string) string {\n\ts := sha256.New()\n\ts.Write([]byte(str))\n\treturn base64.StdEncoding.EncodeToString(s.Sum(nil))\n}",
"func hashSHA256(input string) string {\n\th := sha1.New()\n\th.Write([]byte(input))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func Hash256(pass string, salt string) string {\n\tcombined_bytes := []byte(pass + salt)\n\thash_bytes := hasher256.Sum(combined_bytes)\n\treturn hex.EncodeToString(hash_bytes)\n}",
"func EncodeToSHA256(message string) string {\n\tbytes2 := sha256.Sum256([]byte(message))\n\treturn hex.EncodeToString(bytes2[:])\n}",
"func EncryptSHA256(text string) string {\n h := sha256.New()\n h.Write([]byte(text))\n s := base64.URLEncoding.EncodeToString(h.Sum(nil))\n return (s)\n}",
"func Sha256Hash(password string) string {\n h := sha256.Sum256([]byte(password))\n return \"{SHA256}\" + base64.StdEncoding.EncodeToString(h[:])\n}",
"func Sha256(data string, salt string) string {\n\tb := []byte(data + salt)\n\treturn fmt.Sprintf(\"%X\", sha256.Sum256(b))\n}",
"func SHA256Hex(data []byte) string {\n\treturn hex.EncodeToString(SHA256(data))\n}",
"func SignSha256(data, secretKey string) string {\n\tdata, err := url.QueryUnescape(data)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\thm := hmac.New(sha256.New, []byte(secretKey))\n\thm.Write([]byte(data + \"&key=\" + secretKey))\n\treturn fmt.Sprintf(\"%X\", hm.Sum(nil))\n}",
"func HashStringSha256(hs string) []byte {\n\tdata := []byte(hs)\n\thash := sha256.Sum256(data)\n\treturn hash[:]\n}",
"func (n Node) CalSHA256Hash(input []byte) []byte {\r\n\th := sha256.New()\r\n\th.Write(input)\r\n\treturn h.Sum(nil)\r\n}",
"func SHA256(raw []byte) Hash {\n\treturn gosha256.Sum256(raw)\n}",
"func Sha256(o interface{}) ([]byte, error) {\n\thash := sha256.New()\n\tif _, err := hash.Write([]byte(fmt.Sprintf(\"%+v\", o))); err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn hash.Sum(nil), nil\n}",
"func Hash256Bytes(bytes []byte) string {\n\thasher := sha256.New()\n\thasher.Write(bytes)\n\tmsgDigest := hasher.Sum(nil)\n\tsha256Hex := hex.EncodeToString(msgDigest)\n\treturn sha256Hex\n}",
"func GetSHA256Hash(text string) string {\n\thasher := sha256.New()\n\thasher.Write([]byte(text))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}",
"func SHA256(in []byte) []byte {\n\thash := sha256.Sum256(in)\n\treturn hash[:]\n}",
"func TestSha2_256(t *testing.T) {\n\tinput := []byte(\"test\")\n\texpected, _ := hex.DecodeString(\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\")\n\n\talg := NewSHA2_256()\n\thash := alg.ComputeHash(input)\n\tcheckBytes(t, input, expected, hash)\n\n\talg.Reset()\n\t_, _ = alg.Write([]byte(\"te\"))\n\t_, _ = alg.Write([]byte(\"s\"))\n\t_, _ = alg.Write([]byte(\"t\"))\n\thash = alg.SumHash()\n\tcheckBytes(t, input, expected, hash)\n}",
"func Sha256(data []byte) Hash {\n\th := sha256.Sum256(data)\n\n\treturn NewHash(h[:])\n}",
"func Sha256Hash(data []byte) [32]byte {\n\tsum := sha256.Sum256(data)\n\treturn sum\n}",
"func getSHA256Hash(data []byte) string {\n\treturn hex.EncodeToString(getSHA256Sum(data))\n}",
"func SHA256Hash(data []byte) []byte {\n\tsum := sha256.Sum256(data)\n\treturn sum[:]\n}",
"func Sha256(k []byte) []byte {\n\thash := sha256.New()\n\thash.Write(k)\n\treturn hash.Sum(nil)\n}",
"func Sha256(buf []byte) []byte {\n\treturn CalcHash(buf, sha256.New())\n}",
"func ComputeSHA256(data []byte) (hash []byte) {\r\n\treturn util.ComputeSHA256(data)\r\n}",
"func Sha256(data []byte) []byte {\n\n\thash := sha256.New()\n\thash.Write(data)\n\treturn hash.Sum(nil)\n}",
"func UsingSha256(data []byte) []byte {\n\th := sha256.New()\n\th.Write(data)\n\tout := h.Sum(nil)\n\n\treturn out\n}",
"func Sha256(source io.Reader) (string, int64, error) {\n\thash := hash.New()\n\tsize, err := io.Copy(hash, source)\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\treturn hex.EncodeToString(hash.Sum(nil)) + \"-sha256\", size, nil\n}",
"func Sha256(in, out []byte) error {\n\th := poolSha256.Get().(hash.Hash)\n\tif _, err := h.Write(in); err != nil {\n\t\th.Reset()\n\t\tpoolSha256.Put(h)\n\t\treturn err\n\t}\n\th.Sum(out)\n\th.Reset()\n\tpoolSha256.Put(h)\n\treturn nil\n}",
"func ShaSum256HexEncoded(b []byte) string {\n\tsha := sha256.Sum256(b)\n\tshaHex := hex.EncodeToString(sha[:])\n\n\treturn shaHex\n}",
"func ShaSum256HexEncoded(b []byte) string {\n\tsha := sha256.Sum256(b)\n\tshaHex := hex.EncodeToString(sha[:])\n\n\treturn shaHex\n}",
"func newSHA256() hash.Hash { return sha256.New() }",
"func TestSha3_256(t *testing.T) {\n\tinput := []byte(\"test\")\n\texpected, _ := hex.DecodeString(\"36f028580bb02cc8272a9a020f4200e346e276ae664e45ee80745574e2f5ab80\")\n\n\talg := NewSHA3_256()\n\thash := alg.ComputeHash(input)\n\tcheckBytes(t, input, expected, hash)\n\n\talg.Reset()\n\t_, _ = alg.Write([]byte(\"te\"))\n\t_, _ = alg.Write([]byte(\"s\"))\n\t_, _ = alg.Write([]byte(\"t\"))\n\thash = alg.SumHash()\n\tcheckBytes(t, input, expected, hash)\n}",
"func Sha256d(input []byte) Hash {\n sha := sha256.New()\n sha.Write(input)\n intermediate := sha.Sum(nil)\n sha.Reset()\n sha.Write(intermediate)\n hash, err := HashFromBytes(sha.Sum(nil), LittleEndian)\n if err != nil {\n panic(\"impossible flow, this is a bug: \" + err.Error())\n }\n return hash\n}",
"func SHA256(data []byte) []byte {\n\tb := sha256.Sum256(data)\n\treturn b[:]\n}",
"func Sha256Hash(file io.Reader) (string, error) {\n\tbuf := bytes.NewBuffer(nil)\n\tif _, err := io.Copy(buf, file); err != nil {\n\t\tlog.Println(\"Failed to copy file to buffer in hashing function...\")\n\t\treturn \"\", err\n\t}\n\n\thasher := sha256.New()\n\thasher.Write(buf.Bytes())\n\n\tsha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))\n\n\treturn sha, nil\n}",
"func CreateHashStringSHA256(passphrase string) (KeyEncodedHexString string, KeyBytes []byte) {\n\thasher := sha256.New()\n\thasher.Write([]byte(passphrase))\n\tdata := hasher.Sum(nil)\n\treturn hex.EncodeToString(data), data\n}",
"func (trans *Transaction) HashSHA256() [32]byte {\n\tmessage, err := json.Marshal(trans)\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to marshal transaction with error: %s\", err)\n\t}\n\treturn sha256.Sum256([]byte(message))\n}",
"func (b *Binary) SHA256() (string, error) {\n\tf, err := os.Open(b.LocalPath())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\n\tdata, err := io.ReadAll(f)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%x\", sha256.Sum256(data)), nil\n}",
"func hexEncodeSHA256Hash(body []byte) (string, error) {\n\thash := sha256.New()\n\tif body == nil {\n\t\tbody = []byte(\"\")\n\t}\n\t_, err := hash.Write(body)\n\treturn hex.EncodeToString(hash.Sum(nil)), err\n}",
"func Hash256(N int, data []byte) []byte {\n\treturn hasher.Hash(u, data, 0, uint64(N))\n}",
"func GenerateSHA256Hash() string {\n\tkey := getSecretPhrase()\n\thasher := sha256.New()\n\thasher.Write([]byte(key))\n\n\tactual, err := strkey.Encode(strkey.VersionByteHashX, hasher.Sum(nil))\n\tif err != nil {\n\t\tpanic(err);\n\t\t//LOGGER.Fatal(err)\n\t\treturn \"\"\n\t}\n\treturn actual\n}",
"func HS256(value string, key string) ([]byte, error) {\n\tcipher := hmac.New(sha256.New, []byte(key))\n\t_, err := cipher.Write([]byte(value))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cipher.Sum(nil), nil\n}",
"func FingerprintSHA256(b []byte) string {\n\tdigest := sha256.Sum256(b)\n\treturn hex.EncodeToString(digest[:])\n}",
"func sha256hex(buf []byte) (string, error) {\n\thasher := sha256.New()\n\tif _, err := hasher.Write(buf); err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to get sha256 hash: %w\", err)\n\t}\n\tcCodeHash := hasher.Sum(nil)\n\treturn hex.EncodeToString(cCodeHash), nil\n}",
"func Sha256Hmac(secret string, data string) string {\n\t// Create a new HMAC by defining the hash type and the key (as byte array)\n\th := hmac.New(sha256.New, []byte(secret))\n\n\t// Write Data to it\n\th.Write([]byte(data))\n\n\t// Get result and encode as hexadecimal string\n\tsha := hex.EncodeToString(h.Sum(nil))\n\n\treturn sha\n}",
"func NewHash256(N int) hash.Hash {\n\treturn hasher.NewHasher(u, N)\n}",
"func IntHashSha256(input []byte) *big.Int {\n\th := sha256.New()\n\th.Write(input)\n\treturn new(big.Int).SetBytes(h.Sum(nil))\n}",
"func Sha256(buf []byte) []byte {\n\tdigest := sha256.Sum256(buf)\n\treturn digest[:]\n}",
"func calcSha256(f io.Reader) (string, error) {\n\th := sha256.New()\n\tif _, err := io.Copy(h, f); err != nil {\n\t\treturn \"\", nil\n\t}\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil)), nil\n}",
"func ScryptSHA256(password string, salt []byte, N, r, p int) string {\n\tpasswordb := []byte(password)\n\n\thash, err := scrypt.Key(passwordb, salt, N, r, p, 32)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\thstr := base64.StdEncoding.EncodeToString(hash)\n\tsstr := base64.StdEncoding.EncodeToString(salt)\n\n\treturn fmt.Sprintf(\"$s2$%d$%d$%d$%s$%s\", N, r, p, sstr, hstr)\n}",
"func Hash(input []byte) string {\n\treturn fmt.Sprintf(\"%x\", sha256.Sum256(input))\n}",
"func Hashit(tox string) string {\n h:= sha256.New()\n h.Write([]byte(tox))\n bs := h.Sum([]byte{})\n str := base64.StdEncoding.EncodeToString(bs)\n return str\n}",
"func New256() hash.Hash {\n\td := new(digest)\n\td.is256 = true\n\td.Reset()\n\treturn d\n}",
"func generateSHA256HashInHexForm(preimage string) string {\n\thasher := sha256.New()\n\thasher.Write([]byte(preimage))\n\tshaHash := hasher.Sum(nil)\n\tshaHashHex := hex.EncodeToString(shaHash)\n\treturn shaHashHex\n}",
"func (o *ResultAllOfHashes) SetSha256(v string) {\n\to.Sha256 = &v\n}",
"func Sha256() (sum [sha256.Size]byte) {\n\ts, err := hex.DecodeString(packerSHA256)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tcopy(sum[0:], s)\n\treturn\n}",
"func HMAC_SHA256(src, key string) string {\n\tm := hmac.New(sha256.New, []byte(key))\n\tm.Write([]byte(src))\n\treturn hex.EncodeToString(m.Sum(nil))\n}",
"func NewSHA256() *SHA256 {\n\treturn &SHA256{sha256.New()}\n}",
"func GenerateSHA256FromString(password string) (string, error) {\n\tcrypter := sha256_crypt.New()\n\tpasswordByteStream := []byte(password)\n\tpasswordHash, err := crypter.Generate(passwordByteStream, []byte{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn passwordHash, nil\n}",
"func SSHFingerprintSHA256FromString(key string) string {\n\tpubKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(key))\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn SSHFingerprintSHA256(pubKey)\n}",
"func (o *ResultAllOfHashes) GetSha256() string {\n\tif o == nil || o.Sha256 == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Sha256\n}",
"func Hash256Bits(N int, data []byte, lbb int) []byte {\n\treturn hasher.Hash(u, data, lbb, uint64(N))\n}",
"func (t SimpleHash) Sum256(data []byte) []byte {\n\tsha3Hash := t.wrapper.Sha256(data)\n\tblakeHash := t.wrapper.Blake2s(sha3Hash[:])\n\treturn blakeHash[:]\n}",
"func SHA256(secret, salt string) string {\n key := []byte(secret)\n h := hmac.New(sha256.New, key)\n h.Write([]byte(\"_remote_db\"))\n return base64.StdEncoding.EncodeToString(h.Sum(nil))\n}",
"func MASSSHA256(raw []byte) Hash {\n\treturn sha256.Sum256(raw)\n}",
"func sha256a(authKey Key, msgKey bin.Int128, x int) []byte {\n\th := getSHA256()\n\tdefer sha256Pool.Put(h)\n\n\t_, _ = h.Write(msgKey[:])\n\t_, _ = h.Write(authKey[x : x+36])\n\n\treturn h.Sum(nil)\n}",
"func SHA256HashBytes(bytes []byte) ([]byte, error) {\n\thash := sha256.New()\n\t_, err := hash.Write(bytes)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"hash bytes\")\n\t}\n\thashedBytes := hash.Sum(nil)\n\treturn hashedBytes, nil\n}",
"func ComputeHmac256(message string, secret string) string {\n\tkey := []byte(secret)\n\th := hmac.New(sha256.New, key)\n\th.Write([]byte(message))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func (o CustomerEncryptionKeyResponseOutput) Sha256() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CustomerEncryptionKeyResponse) string { return v.Sha256 }).(pulumi.StringOutput)\n}",
"func Keccak256Hex(data []byte) string {\n\treturn hex.EncodeToString(Keccak256Hash(data))\n}",
"func ComputeHmac256(message string, secret string) string {\n\tkey := []byte(secret)\n\th := hmac.New(sha256.New, key)\n\th.Write([]byte(message))\n\treturn base64.StdEncoding.EncodeToString(h.Sum(nil))\n}",
"func Keccak256Hash(data ...[]byte) (h common.Hash) {\n\td := sha3.NewLegacyKeccak256()\n\tfor _, b := range data {\n\t\td.Write(b)\n\t}\n\td.Sum(h[:0])\n\treturn h\n}",
"func TreeHash256(N int, Yl, Yf, Ym byte, data []byte) []byte {\n\treturn hasher.TreeHash(u, data, 0, uint64(N), Yl, Yf, Ym)\n}",
"func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}",
"func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}",
"func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}",
"func ValidateSHA256(s string) error {\n\tif len(s) != 64 {\n\t\treturn fmt.Errorf(\"expected 64 characters, got %d from %q\", len(s), s)\n\t}\n\tif _, err := hex.DecodeString(s); err != nil {\n\t\treturn fmt.Errorf(\"hex: %s\", err)\n\t}\n\treturn nil\n}",
"func Hash(s string) string {\n\tfmt.Println(\"Hashing string:\", s)\n\thash := sha256.Sum256([]byte(s))\n\tniceHash := fmt.Sprintf(\"%x\", hash)\n\tfmt.Println(\"Created hash:\", hash)\n\treturn niceHash\n}",
"func DoubleSha256(data []byte) Hash {\n\th := sha256.Sum256(data)\n\th = sha256.Sum256(h[:])\n\n\treturn NewHash(h[:])\n}",
"func IsSHA256(str string) bool {\n\treturn IsHash(str, \"sha256\")\n}",
"func EncryptSHA256(data []byte, p Passphrase) (EncryptedData, error) {\n\tsalt := make([]byte, saltSize)\n\n\t// Generate a Salt\n\tif _, err := rand.Read(salt); err != nil {\n\t\treturn EncryptedData(\"\"), err\n\t}\n\n\t// convert string to bytes\n\tkey, err := CreateHashArgon(string(p), salt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create a new cipher block from the key\n\tblock, err := aes.NewCipher([]byte(key))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create a new GCM\n\taesGCM, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create a nonce (12 bytes)\n\tnonce := make([]byte, aesGCM.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// encrypt the data using aesGCM.Seal\n\tcipherData := append([]byte(encryptionVer), salt...)\n\tcipherData = append(cipherData, aesGCM.Seal(nonce, nonce, data, nil)...)\n\treturn cipherData, nil\n\n}",
"func sha256b(authKey Key, msgKey bin.Int128, x int) []byte {\n\th := getSHA256()\n\tdefer sha256Pool.Put(h)\n\n\t_, _ = h.Write(authKey[40+x : 40+x+36])\n\t_, _ = h.Write(msgKey[:])\n\n\treturn h.Sum(nil)\n}",
"func S256(x *big.Int) *big.Int {\n\treturn FromTwosComplement(x, Word256Bits)\n}",
"func Keccak256Hash(data ...[]byte) (h common.Hash) {\n\td := sha3.NewKeccak256()\n\tfor _, b := range data {\n\t\td.Write(b)\n\t}\n\td.Sum(h[:0])\n\treturn h\n}",
"func Keccak256Hash(data ...[]byte) (h common.Hash) {\n\td := sha3.NewKeccak256()\n\tfor _, b := range data {\n\t\td.Write(b)\n\t}\n\td.Sum(h[:0])\n\treturn h\n}",
"func Keccak256Hash(data ...[]byte) (h Hash) {\n\td := sha3.NewKeccak256()\n\tfor _, b := range data {\n\t\td.Write(b)\n\t}\n\td.Sum(h[:0])\n\treturn h\n}",
"func Hash(v []byte) string {\n\th := sha256.Sum256(v)\n\treturn hex.EncodeToString(h[:])\n}",
"func (this *serviceImpl) HmacSha256(key, input []byte) (h []byte) {\n\tmac := hmac.New(sha256.New, key)\n\tmac.Write(input)\n\th = mac.Sum(nil)\n\treturn\n}",
"func (p *Password) SHA256(saltConf ...*SaltConf) ([32]byte, []byte) {\n\tif len(saltConf) > 0 {\n\t\tvar saltLength int\n\n\t\tfor _, i := range saltConf[0:] {\n\t\t\tsaltLength = i.Length\n\t\t}\n\n\t\tsalt := getRandomBytes(saltLength)\n\t\treturn sha256.Sum256([]byte(fmt.Sprintf(\"%s%x\", p.Pass, salt))), salt\n\t}\n\treturn sha256.Sum256([]byte(p.Pass)), nil\n}",
"func DoubleSha256SH(b []byte) ShaHash {\n\tfirst := fastsha256.Sum256(b)\n\treturn ShaHash(fastsha256.Sum256(first[:]))\n}",
"func (ska *SharedKeyCredentials) computeHMACSHA256(message string) (base64String string) {\n\th := hmac.New(sha256.New, ska.AccountKey.Load().([]byte))\n\th.Write([]byte(message))\n\treturn base64.StdEncoding.EncodeToString(h.Sum(nil))\n}",
"func EncodeHash(s string) string {\n\th := sha1.New()\n\th.Write([]byte(s))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func PutSHA256(h hash.Hash) {\n\thm := h.(*hmac) //nolint:forcetypeassert\n\tassertHMACSize(hm, sha256.Size, sha256.BlockSize)\n\thmacSHA256Pool.Put(hm)\n}",
"func SHA3Bytes256(b []byte) []byte {\n\th := sha3.Sum256(b)\n\treturn h[:]\n}",
"func VerifySha256(password, hash string) bool {\n return Sha256Hash(password) == hash\n}",
"func HashIsSHA256(hash string) bool {\n\treturn len(hash) == 64\n}",
"func hash(s string) string {\n\th := fnv.New32a()\n\t_, err := h.Write([]byte(s))\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprint(h.Sum32())\n}",
"func Sha256ToAddress(hashString string) string {\n\tobfuscatedHash := HashHex(hashString, sha512.New384())\n\treturn string(MakeAddress(obfuscatedHash))\n}"
] | [
"0.78868866",
"0.75389344",
"0.73703635",
"0.73541105",
"0.7323915",
"0.72577405",
"0.7078919",
"0.70664424",
"0.7009623",
"0.6980737",
"0.6976358",
"0.69640523",
"0.6962225",
"0.69570786",
"0.69312173",
"0.6929021",
"0.689338",
"0.68863624",
"0.68730766",
"0.6869996",
"0.684289",
"0.6833163",
"0.67746526",
"0.6762697",
"0.6740156",
"0.67251545",
"0.6691932",
"0.6643554",
"0.6590656",
"0.65793747",
"0.6572474",
"0.6572474",
"0.6571621",
"0.65669703",
"0.6552658",
"0.6545302",
"0.6542543",
"0.652305",
"0.65158117",
"0.6508349",
"0.6476162",
"0.6459912",
"0.64329123",
"0.6415491",
"0.63908887",
"0.63809663",
"0.6336647",
"0.63153654",
"0.6216118",
"0.6176238",
"0.6174872",
"0.6168514",
"0.6145588",
"0.6135096",
"0.61293244",
"0.6126738",
"0.6124339",
"0.61143255",
"0.61102027",
"0.61058927",
"0.60792774",
"0.605193",
"0.60387117",
"0.6037375",
"0.6018127",
"0.6014208",
"0.60073334",
"0.60058695",
"0.5994703",
"0.59846205",
"0.59835625",
"0.5982752",
"0.5976978",
"0.59723496",
"0.59656817",
"0.5947542",
"0.5947542",
"0.5947542",
"0.5946081",
"0.5945653",
"0.5944141",
"0.59419906",
"0.5941975",
"0.5925379",
"0.59134036",
"0.59020346",
"0.59020346",
"0.58927965",
"0.58872145",
"0.5884571",
"0.58796674",
"0.58479345",
"0.582665",
"0.581871",
"0.5806766",
"0.5806444",
"0.58063996",
"0.578608",
"0.5781872",
"0.57816917"
] | 0.8472539 | 0 |
ValidHash256 returns true if length of s same as size of a SHA256 checksum. | func ValidHash256(s string) bool {
return len(s) == sha256.Size*2
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func HashIsSHA256(hash string) bool {\n\treturn len(hash) == 64\n}",
"func IsSHA256(str string) bool {\n\treturn IsHash(str, \"sha256\")\n}",
"func ValidateSHA256(s string) error {\n\tif len(s) != 64 {\n\t\treturn fmt.Errorf(\"expected 64 characters, got %d from %q\", len(s), s)\n\t}\n\tif _, err := hex.DecodeString(s); err != nil {\n\t\treturn fmt.Errorf(\"hex: %s\", err)\n\t}\n\treturn nil\n}",
"func VerifySha256(password, hash string) bool {\n return Sha256Hash(password) == hash\n}",
"func ValidHash(s string) bool {\n\treturn len(s) == sha1.Size*2\n}",
"func CheckSingSha256(data, secretKey, sign string) bool {\n\treturn SignSha256(data, secretKey) == sign\n}",
"func isSHA256(fl FieldLevel) bool {\n\treturn sha256Regex.MatchString(fl.Field().String())\n}",
"func (b *KubeBinary) SHA256Check() error {\n\toutput, err := sha256sum(b.Path())\n\tif err != nil {\n\t\treturn errors.Wrap(err, fmt.Sprintf(\"Failed to check SHA256 of %s\", b.Path()))\n\t}\n\n\tif strings.TrimSpace(b.GetSha256()) == \"\" {\n\t\treturn errors.New(fmt.Sprintf(\"No SHA256 found for %s. %s is not supported.\", b.ID, b.Version))\n\t}\n\tif output != b.GetSha256() {\n\t\treturn errors.New(fmt.Sprintf(\"SHA256 no match. %s not equal %s\", b.GetSha256(), output))\n\t}\n\treturn nil\n}",
"func SHA256Check(binary files.KubeBinary, version string) error {\n\toutput, err := exec.Command(\"/bin/sh\", \"-c\", fmt.Sprintf(\"sha256sum %s\", binary.Path)).CombinedOutput()\n\tif err != nil {\n\t\treturn errors.Wrap(err, fmt.Sprintf(\"Failed to check SHA256 of %s\", binary.Path))\n\t}\n\n\tif strings.TrimSpace(binary.GetSha256()) == \"\" {\n\t\treturn errors.New(fmt.Sprintf(\"No SHA256 found for %s. %s is not supported.\", version, version))\n\t}\n\tif !strings.Contains(strings.TrimSpace(string(output)), binary.GetSha256()) {\n\t\treturn errors.New(fmt.Sprintf(\"SHA256 no match. %s not in %s\", binary.GetSha256(), strings.TrimSpace(string(output))))\n\t}\n\treturn nil\n}",
"func (hash SHA256Hash) Equals(bSlice []byte) bool {\n\treturn bytes.Equal(hash.SecureHash, New(bSlice))\n}",
"func (o *ResultAllOfHashes) HasSha256() bool {\n\tif o != nil && o.Sha256 != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func SHA256Hash(data []byte) []byte {\n\tsum := sha256.Sum256(data)\n\treturn sum[:]\n}",
"func Sha256Hash(data []byte) [32]byte {\n\tsum := sha256.Sum256(data)\n\treturn sum\n}",
"func SHA256(s string) string {\n\treturn stringHasher(sha256.New(), s)\n}",
"func TestSha2_256(t *testing.T) {\n\tinput := []byte(\"test\")\n\texpected, _ := hex.DecodeString(\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\")\n\n\talg := NewSHA2_256()\n\thash := alg.ComputeHash(input)\n\tcheckBytes(t, input, expected, hash)\n\n\talg.Reset()\n\t_, _ = alg.Write([]byte(\"te\"))\n\t_, _ = alg.Write([]byte(\"s\"))\n\t_, _ = alg.Write([]byte(\"t\"))\n\thash = alg.SumHash()\n\tcheckBytes(t, input, expected, hash)\n}",
"func TestSha3_256(t *testing.T) {\n\tinput := []byte(\"test\")\n\texpected, _ := hex.DecodeString(\"36f028580bb02cc8272a9a020f4200e346e276ae664e45ee80745574e2f5ab80\")\n\n\talg := NewSHA3_256()\n\thash := alg.ComputeHash(input)\n\tcheckBytes(t, input, expected, hash)\n\n\talg.Reset()\n\t_, _ = alg.Write([]byte(\"te\"))\n\t_, _ = alg.Write([]byte(\"s\"))\n\t_, _ = alg.Write([]byte(\"t\"))\n\thash = alg.SumHash()\n\tcheckBytes(t, input, expected, hash)\n}",
"func hasChecksum(n int64) bool {\n\t// 512 is chosen because it's a minimum disk sector size\n\t// smaller than (and multiplies to) OS page size in most systems\n\treturn (n % 512) == sha256.Size\n}",
"func (n Node) CalSHA256Hash(input []byte) []byte {\r\n\th := sha256.New()\r\n\th.Write(input)\r\n\treturn h.Sum(nil)\r\n}",
"func Validate(h, s, p string) bool {\n\treturn h == ComputeHash(p, s)\n}",
"func ValidHash512(s string) bool {\n\treturn len(s) == sha512.Size*2\n}",
"func SHA256(raw []byte) Hash {\n\treturn gosha256.Sum256(raw)\n}",
"func (p *Password) SHA256(saltConf ...*SaltConf) ([32]byte, []byte) {\n\tif len(saltConf) > 0 {\n\t\tvar saltLength int\n\n\t\tfor _, i := range saltConf[0:] {\n\t\t\tsaltLength = i.Length\n\t\t}\n\n\t\tsalt := getRandomBytes(saltLength)\n\t\treturn sha256.Sum256([]byte(fmt.Sprintf(\"%s%x\", p.Pass, salt))), salt\n\t}\n\treturn sha256.Sum256([]byte(p.Pass)), nil\n}",
"func IsDigestValid(decryptedCell []byte) bool {\n\n\tif len(decryptedCell) != 512 {\n\t\treturn false\n\t}\n\tdigest := DecodePayloadDigest(decryptedCell)\n\tpayload := DecodeRelayPayload(decryptedCell)\n\tsum := md5.Sum(payload)\n\n\tfor i := 0; i < DigestLength; i++ {\n\t\tif digest[i] != sum[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}",
"func isValidHash(hashType, hash string) bool {\n\tswitch hashType {\n\tcase string(HashMD5):\n\t\treturn len(hash) == 32\n\tcase string(HashSHA1):\n\t\treturn len(hash) == 40\n\tcase string(HashSHA256):\n\t\treturn len(hash) == 64\n\tcase string(HashSHA512):\n\t\treturn len(hash) == 128\n\tdefault:\n\t\treturn false\n\t}\n}",
"func MASSSHA256(raw []byte) Hash {\n\treturn sha256.Sum256(raw)\n}",
"func IsValidHash(s string) bool {\n\tout, err := b58.Decode(s)\n\tif err != nil {\n\t\treturn false\n\t}\n\t_, err = mh.Cast(out)\n\treturn err == nil\n}",
"func IsHash(str string, algorithm string) bool {\n\tlen := \"0\"\n\talgo := strings.ToLower(algorithm)\n\n\tif algo == \"crc32\" || algo == \"crc32b\" {\n\t\tlen = \"8\"\n\t} else if algo == \"md5\" || algo == \"md4\" || algo == \"ripemd128\" || algo == \"tiger128\" {\n\t\tlen = \"32\"\n\t} else if algo == \"sha1\" || algo == \"ripemd160\" || algo == \"tiger160\" {\n\t\tlen = \"40\"\n\t} else if algo == \"tiger192\" {\n\t\tlen = \"48\"\n\t} else if algo == \"sha256\" {\n\t\tlen = \"64\"\n\t} else if algo == \"sha384\" {\n\t\tlen = \"96\"\n\t} else if algo == \"sha512\" {\n\t\tlen = \"128\"\n\t} else {\n\t\treturn false\n\t}\n\n\treturn Matches(str, \"^[a-f0-9]{\"+len+\"}$\")\n}",
"func checkHashSize(hexStr string) int {\n\tmaxint64 := 9223372036854775807\n\tminint64 := -9223372036854775807\n\tint64val := hex2int(hexStr)\n\n\tfor len(hexStr) > 0 && int64val >= maxint64 || int64val <= minint64 {\n\t\thexStr = hexStr[:len(hexStr)-1]\n\t\tint64val = hex2int(hexStr)\n\t}\n\treturn int64val\n}",
"func (blk Block) ValidHash() bool {\n\t// TODO\n\n\thash := blk.Hash\n\n\tif hash == nil {\n\t\treturn false\n\t}\n\n\tl := len(hash)\n\n\tnBytes := int(blk.Difficulty / 8)\n\tnBits := blk.Difficulty % 8\n\n\tfor i := l - 1; i >= l-nBytes; i-- {\n\t\tif hash[i] != '\\x00' {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif hash[l-nBytes-1]%(1<<nBits) != 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}",
"func Hash256(N int, data []byte) []byte {\n\treturn hasher.Hash(u, data, 0, uint64(N))\n}",
"func (s *Salt) IsValid() bool {\n\treturn len(*s) == saltLen\n}",
"func Sha256d(input []byte) Hash {\n sha := sha256.New()\n sha.Write(input)\n intermediate := sha.Sum(nil)\n sha.Reset()\n sha.Write(intermediate)\n hash, err := HashFromBytes(sha.Sum(nil), LittleEndian)\n if err != nil {\n panic(\"impossible flow, this is a bug: \" + err.Error())\n }\n return hash\n}",
"func hashSHA256(input string) string {\n\th := sha1.New()\n\th.Write([]byte(input))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func SHA256(in []byte) []byte {\n\thash := sha256.Sum256(in)\n\treturn hash[:]\n}",
"func Sum256(data []byte) [Size]byte {\n\tvar d digest\n\td.hashSize = 256\n\td.Reset()\n\td.Write(data)\n\treturn d.checkSum()\n}",
"func validateHexHash(s string) error {\n\tif has0xPrefix(s) {\n\t\ts = s[2:]\n\t}\n\tif len(s)%2 == 1 {\n\t\ts = \"0\" + s\n\t}\n\t_, err := hex.DecodeString(s)\n\treturn err\n}",
"func hashSHA256(str string) string {\n\ts := sha256.New()\n\ts.Write([]byte(str))\n\treturn base64.StdEncoding.EncodeToString(s.Sum(nil))\n}",
"func (h *ArgonHasher) Validate(password, encoded string) (bool, error) {\n\tparams, salt, hash, err := decodeHash(encoded)\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tpasswordHash := argon2.IDKey([]byte(password), salt, params.Iterations, params.Memory, params.Threads, params.KeyLength)\n\n\tif subtle.ConstantTimeCompare(hash, passwordHash) == 0 {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}",
"func SHA256(data []byte) []byte {\n\tb := sha256.Sum256(data)\n\treturn b[:]\n}",
"func validateSHA256Value(v string) error {\n\tif err := util.ValidateSHA256Value(v); err != nil {\n\t\treturn fmt.Errorf(\"error parsing %v flag: %w\", shaFlag, err)\n\t}\n\n\treturn nil\n}",
"func Sha256Hash(password string) string {\n h := sha256.Sum256([]byte(password))\n return \"{SHA256}\" + base64.StdEncoding.EncodeToString(h[:])\n}",
"func Sha256() (sum [sha256.Size]byte) {\n\ts, err := hex.DecodeString(packerSHA256)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tcopy(sum[0:], s)\n\treturn\n}",
"func SHA256(text string) string {\n\talgorithm := sha256.New()\n\treturn stringHasher(algorithm, text)\n}",
"func (o *ResultAllOfHashes) GetSha256Ok() (*string, bool) {\n\tif o == nil || o.Sha256 == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Sha256, true\n}",
"func (s *grpcServer) validateHash(hash string, logPrefix string) error {\n\tif len(hash) != hashKeyLength {\n\t\tmsg := fmt.Sprintf(\"Hash length must be length %d\", hashKeyLength)\n\t\ts.accessLogger.Printf(\"%s %s: %s\", logPrefix, hash, msg)\n\t\treturn status.Error(codes.InvalidArgument, msg)\n\t}\n\n\tif !hashKeyRegex.MatchString(hash) {\n\t\tmsg := \"Malformed hash\"\n\t\ts.accessLogger.Printf(\"%s %s: %s\", logPrefix, hash, msg)\n\t\treturn status.Error(codes.InvalidArgument, msg)\n\t}\n\n\treturn nil\n}",
"func (hasher *SHA256) HashLength() uint {\n\treturn 64\n}",
"func Validate(token []byte) (isValid bool) {\n\t//fast path\n\tif len(token) != TOKEN_SIZE {\n\t\treturn\n\t}\n\n\thash := createHash(token[32:])\n\n\t//now compare our hash with input\n\tif bytes.Compare(token[0:32], hash) == 0 {\n\t\tisValid = true\n\t}\n\n\treturn\n}",
"func Sha256Hash(file io.Reader) (string, error) {\n\tbuf := bytes.NewBuffer(nil)\n\tif _, err := io.Copy(buf, file); err != nil {\n\t\tlog.Println(\"Failed to copy file to buffer in hashing function...\")\n\t\treturn \"\", err\n\t}\n\n\thasher := sha256.New()\n\thasher.Write(buf.Bytes())\n\n\tsha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))\n\n\treturn sha, nil\n}",
"func (e Aes128CtsHmacSha256128) VerifyChecksum(protocolKey, data, chksum []byte, usage uint32) bool {\n\tc, err := e.GetChecksumHash(protocolKey, data, usage)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn hmac.Equal(chksum, c)\n}",
"func (b *Binary) SHA256() (string, error) {\n\tf, err := os.Open(b.LocalPath())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\n\tdata, err := io.ReadAll(f)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%x\", sha256.Sum256(data)), nil\n}",
"func DigestSize() int {\n\treturn sha256DigestSize\n}",
"func checkSigS256(msg msgjson.Signable, pubKey *secp256k1.PublicKey) error {\n\tsignature, err := ecdsa.ParseDERSignature(msg.SigBytes())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error decoding secp256k1 Signature from bytes: %w\", err)\n\t}\n\tif !signature.Verify(msg.Serialize(), pubKey) {\n\t\treturn fmt.Errorf(\"secp256k1 signature verification failed\")\n\t}\n\treturn nil\n}",
"func Hash256(pass string, salt string) string {\n\tcombined_bytes := []byte(pass + salt)\n\thash_bytes := hasher256.Sum(combined_bytes)\n\treturn hex.EncodeToString(hash_bytes)\n}",
"func calcSha256(f io.Reader) (string, error) {\n\th := sha256.New()\n\tif _, err := io.Copy(h, f); err != nil {\n\t\treturn \"\", nil\n\t}\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil)), nil\n}",
"func ComputeSHA256(data []byte) (hash []byte) {\r\n\treturn util.ComputeSHA256(data)\r\n}",
"func Sha256(data []byte) Hash {\n\th := sha256.Sum256(data)\n\n\treturn NewHash(h[:])\n}",
"func Sha256(data []byte) []byte {\n\n\thash := sha256.New()\n\thash.Write(data)\n\treturn hash.Sum(nil)\n}",
"func (b *Bundler) ChecksumSHA256(name, sum string) {\n\tb.checksumsSHA256.Add(name, sum)\n}",
"func IsValidDigest(hash string) bool {\n\t// Currently we expect all digests to be ASCII encoded MD5 hashes.\n\tif len(hash) != 32 {\n\t\treturn false\n\t}\n\n\tfor _, c := range []byte(hash) {\n\t\tif ((c >= '0') && (c <= '9')) ||\n\t\t\t((c >= 'a') && (c <= 'f')) ||\n\t\t\t((c >= 'A') && (c <= 'F')) {\n\t\t\tcontinue\n\t\t}\n\t\treturn false\n\t}\n\treturn true\n}",
"func HashStringSha256(hs string) []byte {\n\tdata := []byte(hs)\n\thash := sha256.Sum256(data)\n\treturn hash[:]\n}",
"func IsHashValid(hash string, difficulty int) bool {\n\tprefix := strings.Repeat(\"0\", difficulty)\n\treturn strings.HasPrefix(hash, prefix)\n}",
"func IsHashValid(hash string, difficulty int) bool {\n\tprefix := strings.Repeat(\"0\", difficulty)\n\treturn strings.HasPrefix(hash, prefix)\n}",
"func Sum256(data []byte) (sum256 [Size256]byte) {\n\tvar d digest\n\td.is256 = true\n\td.Reset()\n\td.Write(data)\n\tsum := d.checkSum()\n\tcopy(sum256[:], sum[Size256:])\n\treturn\n}",
"func CheckHash(password, hash string) (match bool, params *Params, err error) {\n\tparams, salt, key, err := DecodeHash(hash)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\n\totherKey := argon2.IDKey([]byte(password), salt, params.Iterations, params.Memory, params.Parallelism, params.KeyLength)\n\n\tkeyLen := int32(len(key))\n\totherKeyLen := int32(len(otherKey))\n\n\tif subtle.ConstantTimeEq(keyLen, otherKeyLen) == 0 {\n\t\treturn false, params, nil\n\t}\n\tif subtle.ConstantTimeCompare(key, otherKey) == 1 {\n\t\treturn true, params, nil\n\t}\n\treturn false, params, nil\n}",
"func Hash256Bits(N int, data []byte, lbb int) []byte {\n\treturn hasher.Hash(u, data, lbb, uint64(N))\n}",
"func Hash256Bytes(bytes []byte) string {\n\thasher := sha256.New()\n\thasher.Write(bytes)\n\tmsgDigest := hasher.Sum(nil)\n\tsha256Hex := hex.EncodeToString(msgDigest)\n\treturn sha256Hex\n}",
"func (trans *Transaction) HashSHA256() [32]byte {\n\tmessage, err := json.Marshal(trans)\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to marshal transaction with error: %s\", err)\n\t}\n\treturn sha256.Sum256([]byte(message))\n}",
"func newSHA256() hash.Hash { return sha256.New() }",
"func IsValidHash(obj string) bool {\n\treturn hashPtn.MatchString(obj)\n}",
"func (imageName *ImageName) HasDigest() bool {\n\treturn strings.HasPrefix(imageName.Tag, \"sha256:\")\n}",
"func testLenHash(b []byte) uint {\n\treturn uint(len(b))\n}",
"func CheckHMACHash(data string, hash string, secret string) bool {\n\th := hmac.New(sha256.New, []byte(secret))\n\th.Write([]byte(data))\n\t// Get result and encode as hexadecimal string\n\tsha := hex.EncodeToString(h.Sum(nil))\n\treturn sha == hash\n}",
"func diffBitsSHA256(x *[32]byte, y *[32]byte) uint8 {\n\tvar diffBites uint8 = 0\n\tfor i := uint8(0); i < 32; i++ {\n\t\tdiffBites += pc[x[i]^y[i]]\n\t}\n\treturn diffBites\n}",
"func Sha256(source io.Reader) (string, int64, error) {\n\thash := hash.New()\n\tsize, err := io.Copy(hash, source)\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\treturn hex.EncodeToString(hash.Sum(nil)) + \"-sha256\", size, nil\n}",
"func getSHA256Hash(data []byte) string {\n\treturn hex.EncodeToString(getSHA256Sum(data))\n}",
"func HS256(secret []byte) SignerVerifier {\n\treturn SymmetricSignature(&HMACSignerVerifier{\n\t\th: sha256.New,\n\t\tsecret: secret,\n\t\talg: ALG_HS256,\n\t})\n}",
"func (t X12Hash) Sum256(data []byte) ([]byte, error) {\n\tval := t.wrapper.X11(data)\n\tscryptHash, err := t.wrapper.Scrypt(val, nil, 32768, 8, 1, 32)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn scryptHash, nil\n}",
"func Validate(username, hash string, userCreds database.UserCreds) (bool, string) {\n\t// Take SHA256 hash of the hash given by user\n\thashOfHash := sha256.Sum256([]byte(hash))\n\thashString := hex.EncodeToString(hashOfHash[:])\n\t// If the hash is not equal throw error\n\tif hashString != userCreds.Hash {\n\t\tfmt.Printf(\"%s Error ::%s Hash is Invalid\\n\\n\", chalk.Red, chalk.Reset)\n\t\treturn false, \"Invalid Hash. Your password was incorrect.\"\n\t}\n\n\t// If equal decrement n and change hash in database\n\tuserCreds.Hash = hash\n\tuserCreds.N -= 1\n\tdatabase.Set(username, userCreds)\n\treturn true, \"\"\n}",
"func Sha256(buf []byte) []byte {\n\treturn CalcHash(buf, sha256.New())\n}",
"func sum256(data []byte) []byte {\n\thash := sha256.New()\n\thash.Write(data)\n\treturn hash.Sum(nil)\n}",
"func checkSigS256(msg, sig []byte, pubKey *secp256k1.PublicKey) error {\n\tsignature, err := secp256k1.ParseDERSignature(sig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error decoding secp256k1 Signature from bytes: %v\", err)\n\t}\n\tif !signature.Verify(msg, pubKey) {\n\t\treturn fmt.Errorf(\"secp256k1 signature verification failed\")\n\t}\n\treturn nil\n}",
"func CheckHash(data []byte, target [blake2b.Size]byte) bool {\n\tif Hash(data) == target {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}",
"func checkSigS256(msg, pkBytes, sigBytes []byte) error {\n\tpubKey, err := secp256k1.ParsePubKey(pkBytes)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error decoding secp256k1 PublicKey from bytes: %v\", err)\n\t}\n\tsignature, err := secp256k1.ParseDERSignature(sigBytes)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error decoding secp256k1 Signature from bytes: %v\", err)\n\t}\n\tif !signature.Verify(msg, pubKey) {\n\t\treturn fmt.Errorf(\"secp256k1 signature verification failed\")\n\t}\n\treturn nil\n}",
"func TestHash(t *testing.T) {\n\t// Hash of block 234439.\n\tblockHashStr := \"14a0810ac680a3eb3f82edc878cea25ec41d6b790744e5daeef\"\n\tblockHash, err := NewHashFromStr(blockHashStr)\n\tassert.NoError(t, err)\n\n\t// Hash of block 234440 as byte slice.\n\tbuf := []byte{\n\t\t0x79, 0xa6, 0x1a, 0xdb, 0xc6, 0xe5, 0xa2, 0xe1,\n\t\t0x39, 0xd2, 0x71, 0x3a, 0x54, 0x6e, 0xc7, 0xc8,\n\t\t0x75, 0x63, 0x2e, 0x75, 0xf1, 0xdf, 0x9c, 0x3f,\n\t\t0xa6, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t}\n\n\thash, err := NewHash(buf)\n\tassert.NoError(t, err)\n\n\t// Ensure proper size.\n\tassert.Equal(t, HashSize, len(hash))\n\n\t// Ensure contents match.\n\tassert.Equal(t, buf[:], hash[:])\n\n\t// Ensure contents of hash of block 234440 don't match 234439.\n\tassert.False(t, hash.IsEqual(blockHash))\n\n\t// Set hash from byte slice and ensure contents match.\n\terr = hash.SetBytes(blockHash.CloneBytes())\n\tassert.NoError(t, err)\n\tassert.True(t, hash.IsEqual(blockHash))\n\n\t// Ensure nil hashes are handled properly.\n\tassert.True(t, (*Hash)(nil).IsEqual(nil))\n\n\tassert.False(t, hash.IsEqual(nil))\n\n\t// Invalid size for SetBytes.\n\terr = hash.SetBytes([]byte{0x00})\n\tassert.NotNil(t, err)\n\n\t// Invalid size for NewHash.\n\tinvalidHash := make([]byte, HashSize+1)\n\t_, err = NewHash(invalidHash)\n\tassert.NotNil(t, err)\n\n\tif err == nil {\n\t\tt.Errorf(\"NewHash: failed to received expected err - got: nil\")\n\t}\n}",
"func (t SimpleHash) Sum256(data []byte) []byte {\n\tsha3Hash := t.wrapper.Sha256(data)\n\tblakeHash := t.wrapper.Blake2s(sha3Hash[:])\n\treturn blakeHash[:]\n}",
"func (s *Storage) Check(sha256Hash string) (exists bool, size int64, err error) {\n\tf, err := s.fs.Open(hashName(sha256Hash))\n\tif err != nil && err != mgo.ErrNotFound {\n\t\treturn false, 0, err\n\t}\n\tif err == nil {\n\t\tsize := f.Size()\n\t\tf.Close()\n\t\treturn true, size, nil\n\t}\n\treturn false, 0, nil\n}",
"func Sha256DiffSuppress(_, old, new string, _ *schema.ResourceData) bool {\n\treturn hex.EncodeToString(sha256.New().Sum([]byte(old))) == new\n}",
"func UsingSha256(data []byte) []byte {\n\th := sha256.New()\n\th.Write(data)\n\tout := h.Sum(nil)\n\n\treturn out\n}",
"func SHA256Hex(data []byte) string {\n\treturn hex.EncodeToString(SHA256(data))\n}",
"func getSHA256Sum(data []byte) []byte {\n\thash := sha256.New()\n\thash.Write(data)\n\treturn hash.Sum(nil)\n}",
"func (d *digest) Size() int { return crc64.Size }",
"func SHA3Bytes256(b []byte) []byte {\n\th := sha3.Sum256(b)\n\treturn h[:]\n}",
"func DoubleSha256(data []byte) Hash {\n\th := sha256.Sum256(data)\n\th = sha256.Sum256(h[:])\n\n\treturn NewHash(h[:])\n}",
"func SHA256(secret, salt string) string {\n key := []byte(secret)\n h := hmac.New(sha256.New, key)\n h.Write([]byte(\"_remote_db\"))\n return base64.StdEncoding.EncodeToString(h.Sum(nil))\n}",
"func Sha256(data string, salt string) string {\n\tb := []byte(data + salt)\n\treturn fmt.Sprintf(\"%X\", sha256.Sum256(b))\n}",
"func Sha256(k []byte) []byte {\n\thash := sha256.New()\n\thash.Write(k)\n\treturn hash.Sum(nil)\n}",
"func Validate(digest *repb.Digest) error {\n\tif digest == nil {\n\t\treturn errors.New(\"nil digest\")\n\t}\n\tif ok, err := validateHashLength(digest.Hash); !ok {\n\t\treturn err\n\t}\n\tif !hexStringRegex.MatchString(digest.Hash) {\n\t\treturn fmt.Errorf(\"hash is not a lowercase hex string (%s)\", digest.Hash)\n\t}\n\tif digest.SizeBytes < 0 {\n\t\treturn fmt.Errorf(\"expected non-negative size, got %d\", digest.SizeBytes)\n\t}\n\treturn nil\n}",
"func verifyChecksum(in uint8, cmd uint8, dataLen uint8, data []byte) bool {\n\n\treturn in == calculateChecksum(cmd, dataLen, data)\n}",
"func (ma *MixedcaseAddress) ValidChecksum() bool {\n\treturn ma.original == ma.addr.Hex()\n}",
"func hashLen(u uint64, hashLog, mls uint8) uint32 {\n\tswitch mls {\n\tcase 5:\n\t\treturn hash5(u, hashLog)\n\tcase 6:\n\t\treturn hash6(u, hashLog)\n\tcase 7:\n\t\treturn hash7(u, hashLog)\n\tcase 8:\n\t\treturn hash8(u, hashLog)\n\tdefault:\n\t\treturn hash4x64(u, hashLog)\n\t}\n}"
] | [
"0.74213064",
"0.720326",
"0.71772283",
"0.71187437",
"0.6873682",
"0.6820071",
"0.67264324",
"0.64932925",
"0.6450667",
"0.6186646",
"0.61686945",
"0.61643356",
"0.6150378",
"0.6100094",
"0.6095919",
"0.60918564",
"0.60624623",
"0.60607797",
"0.5992483",
"0.59822756",
"0.5907219",
"0.57981217",
"0.57855433",
"0.57752866",
"0.5766721",
"0.5742982",
"0.5728296",
"0.57212925",
"0.57193005",
"0.5708615",
"0.56876564",
"0.5663503",
"0.5656341",
"0.5650773",
"0.5647811",
"0.5645878",
"0.56439245",
"0.5640449",
"0.5632402",
"0.562501",
"0.5622598",
"0.5607301",
"0.56011933",
"0.55986935",
"0.55888665",
"0.55772537",
"0.5559382",
"0.5549182",
"0.55261654",
"0.5516975",
"0.55099773",
"0.55079806",
"0.550033",
"0.54955214",
"0.5491783",
"0.5480069",
"0.5478145",
"0.5459028",
"0.54249835",
"0.54248804",
"0.5424643",
"0.5424643",
"0.5423893",
"0.54230255",
"0.5421669",
"0.5418765",
"0.5417948",
"0.54108846",
"0.54009515",
"0.5399968",
"0.53960633",
"0.539279",
"0.5386387",
"0.5386341",
"0.53861856",
"0.5374689",
"0.535903",
"0.5355057",
"0.5345102",
"0.5341013",
"0.5331346",
"0.53132194",
"0.5311617",
"0.5299629",
"0.52970177",
"0.5296247",
"0.52887017",
"0.52576727",
"0.5242084",
"0.5239204",
"0.5223007",
"0.5214987",
"0.5193315",
"0.5189015",
"0.51878023",
"0.518553",
"0.5180725",
"0.5159094",
"0.51467097",
"0.51449144"
] | 0.83286315 | 0 |
EncodeHash512 returns the sha256 encoding of s. | func EncodeHash512(s string) string {
h := sha512.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func SHA512(text string) string {\n\treturn stringHasher(sha512.New(), text)\n}",
"func SHA512Digest(s string) string {\n\th := sha512.Sum512([]byte(s))\n\treturn hex.EncodeToString(h[:])\n}",
"func SHA512(text string) string {\n\thasher := sha512.New()\n\thasher.Write([]byte(text))\n\treturn strings.ToUpper(hex.EncodeToString(hasher.Sum(nil)))\n}",
"func hashSHA512(text string) []byte {\n\thash := sha512.New()\n\thash.Write([]byte(text))\n\treturn hash.Sum(nil)\n}",
"func shaEncode(input string) string {\n\tsha := sha512.Sum512([]byte(input))\n\treturn hex.EncodeToString(sha[:])\n}",
"func Hash512(tag string, data []byte) []byte {\n\th := hmac.New(sha512.New512_256, []byte(tag))\n\th.Write(data)\n\treturn h.Sum(nil)\n}",
"func Sha512(in, out []byte) error {\n\th := poolSha512.Get().(hash.Hash)\n\tif _, err := h.Write(in); err != nil {\n\t\th.Reset()\n\t\tpoolSha512.Put(h)\n\t\treturn err\n\t}\n\th.Sum(out)\n\th.Reset()\n\tpoolSha512.Put(h)\n\treturn nil\n}",
"func hash(password string) string {\n\thash := sha512.New()\n\thash.Write([]byte(password))\n\tb := hash.Sum(nil)\n\treturn base64.StdEncoding.EncodeToString(b)\n}",
"func GenerateSHA512FromString(password string) (string, error) {\n\tcrypter := sha512_crypt.New()\n\tpasswordByteStream := []byte(password)\n\tpasswordHash, err := crypter.Generate(passwordByteStream, []byte{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn passwordHash, nil\n}",
"func EncodeHash256(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func Sha512(master, salt, info []byte) ([32]byte, error) {\n\thash := sha512.New\n\thkdf := hkdf.New(hash, master, salt, info)\n\n\tkey := make([]byte, 32) // 256 bit\n\t_, err := io.ReadFull(hkdf, key)\n\n\tvar result [32]byte\n\tcopy(result[:], key)\n\n\treturn result, err\n}",
"func (p *Password) SHA512(saltConf ...*SaltConf) ([64]byte, []byte) {\n\tif len(saltConf) > 0 {\n\t\tvar saltLength int\n\n\t\tfor _, i := range saltConf[0:] {\n\t\t\tsaltLength = i.Length\n\t\t}\n\n\t\tsalt := getRandomBytes(saltLength)\n\t\treturn sha512.Sum512([]byte(fmt.Sprintf(\"%s%x\", p.Pass, salt))), salt\n\t}\n\treturn sha512.Sum512([]byte(p.Pass)), nil\n}",
"func IsSHA512(str string) bool {\n\treturn IsHash(str, \"sha512\")\n}",
"func TestSsha512(t *testing.T) {\n\tconst plain = \"Hi, arche.\"\n\tencode, err := nut.SumSsha512(plain, 32)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Logf(`doveadm pw -t {SSHA512}%s -p \"%s\"`, encode, plain)\n\tif !nut.EqualSsha512(encode, plain) {\n\t\tt.Error(\"check password failed\")\n\t}\n}",
"func new512Asm() hash.Hash { return nil }",
"func SHA256(s string) string {\n\treturn stringHasher(sha256.New(), s)\n}",
"func Encrypt(password []byte, e interface{}) (data, hash []byte, err error) {\n\tvar encoded bytes.Buffer\n\n\tif err = gob.NewEncoder(&encoded).Encode(e); err != nil {\n\t\treturn\n\t}\n\n\tvar compressed bytes.Buffer\n\tw := gzip.NewWriter(&compressed)\n\n\tif _, err = w.Write(encoded.Bytes()); err != nil {\n\t\treturn\n\t}\n\n\tif err = w.Close(); err != nil {\n\t\treturn\n\t}\n\n\tsalt := make([]byte, saltSize)\n\tif _, err = rand.Read(salt); err != nil {\n\t\treturn\n\t}\n\n\tc, err := aes.NewCipher(derive(password, salt))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgcm, err := cipher.NewGCM(c)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tnonce := make([]byte, gcm.NonceSize())\n\tif _, err = rand.Read(nonce); err != nil {\n\t\treturn\n\t}\n\n\tvar buf bytes.Buffer\n\tsha := sha512.New()\n\tmw := io.MultiWriter(&buf, sha)\n\n\tver := make([]byte, 8)\n\tbinary.LittleEndian.PutUint64(ver, Version)\n\n\tif _, err = mw.Write(ver); err != nil {\n\t\treturn\n\t}\n\n\tif _, err = mw.Write(salt); err != nil {\n\t\treturn\n\t}\n\n\tif _, err = mw.Write(nonce); err != nil {\n\t\treturn\n\t}\n\n\tif _, err = mw.Write(gcm.Seal(nil, nonce, compressed.Bytes(), nil)); err != nil {\n\t\treturn\n\t}\n\n\treturn buf.Bytes(), sha.Sum(nil), nil\n}",
"func Hmac512(key string, data io.Reader) (b64 string, err error) {\n\thash := hmac.New(sha512.New, []byte(key))\n\tb, err := ioutil.ReadAll(data)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to read data from reader\")\n\t}\n\tif _, err := hash.Write(b); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to hash data\")\n\t}\n\treturn base64.StdEncoding.EncodeToString(hash.Sum(nil)), nil\n}",
"func Sha256Hash(password string) string {\n h := sha256.Sum256([]byte(password))\n return \"{SHA256}\" + base64.StdEncoding.EncodeToString(h[:])\n}",
"func ValidHash512(s string) bool {\n\treturn len(s) == sha512.Size*2\n}",
"func HS512(secret []byte) SignerVerifier {\n\treturn SymmetricSignature(&HMACSignerVerifier{\n\t\th: sha512.New,\n\t\tsecret: secret,\n\t\talg: ALG_HS512,\n\t})\n}",
"func Sum512(data []byte) [Size]byte {\n\tvar d digest\n\td.Reset()\n\td.Write(data)\n\treturn d.checkSum()\n}",
"func expandHash(data []byte) []byte {\n\tpart0 := sha512.Sum512(append(data, 0))\n\tpart1 := sha512.Sum512(append(data, 1))\n\tpart2 := sha512.Sum512(append(data, 2))\n\tpart3 := sha512.Sum512(append(data, 3))\n\treturn bytes.Join([][]byte{\n\t\tpart0[:],\n\t\tpart1[:],\n\t\tpart2[:],\n\t\tpart3[:],\n\t}, []byte{})\n}",
"func hashSHA256(str string) string {\n\ts := sha256.New()\n\ts.Write([]byte(str))\n\treturn base64.StdEncoding.EncodeToString(s.Sum(nil))\n}",
"func Hexdigest(str string) string {\n\thash := sha512.New()\n\thash.Write([]byte(str))\n\thashBytes := hash.Sum(nil)\n\treturn strings.ToLower(hex.EncodeToString(hashBytes))\n}",
"func xx512x1(inner_512 []byte) [20]byte {\n\touter_512 := sha512.Sum512(inner_512)\n\treturn sha1.Sum(outer_512[:])\n}",
"func SignatureHash(signature string) string {\n\treturn fmt.Sprintf(\"%x\", sha512.Sum384([]byte(signature)))\n}",
"func SHA512Half(v []byte) (string, error) {\n\th := sha512.New()\n\t_, err := io.Copy(h, bytes.NewBuffer(v))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil)[:sha512.Size/2]), nil\n}",
"func WithSHA512(enabled bool) Option {\n\treturn func(s *settings) {\n\t\tif enabled {\n\t\t\ts.h = sha512.New\n\t\t}\n\t}\n}",
"func hasher(s string) []byte {\n\tval := sha256.Sum256([]byte(s))\n\tvar hex []string\n\n\t// Iterate through the bytes.\n\tfor i := 0; i < len(val); i++ {\n\t\t// We want each number to be represented by 2 chars.\n\t\tplaceHolder := []string{\"0\"}\n\t\tvalue := strconv.FormatInt(int64(val[i]), 16)\n\n\t\tif len(value) != 2 {\n\t\t\tplaceHolder = append(placeHolder, value)\n\t\t\thex = append(hex, strings.Join(placeHolder, \"\"))\n\t\t} else {\n\t\t\thex = append(hex, value)\n\t\t}\n\t}\n\treturn []byte(strings.Join(hex, \"\"))\n\n}",
"func (e *sha512Encryptor) Hash(password []byte) []byte {\n\te.hashFn.Reset()\n\te.hashFn.Write(password)\n\treturn e.hashFn.Sum(nil)\n}",
"func smash(s string) string {\n\th := md5.New()\n\tio.WriteString(h, s)\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}",
"func Keccak512(data ...[]byte) []byte {\n\td := sha3.NewKeccak512()\n\tfor _, b := range data {\n\t\td.Write(b)\n\t}\n\treturn d.Sum(nil)\n}",
"func Keccak512(data ...[]byte) []byte {\n\td := sha3.NewKeccak512()\n\tfor _, b := range data {\n\t\td.Write(b)\n\t}\n\treturn d.Sum(nil)\n}",
"func Keccak512(data ...[]byte) []byte {\n\td := sha3.NewKeccak512()\n\tfor _, b := range data {\n\t\td.Write(b)\n\t}\n\treturn d.Sum(nil)\n}",
"func Hash(password, salt string) string {\n\thasher := sha512.New()\n\tbuf := bufferpool.Get()\n\tdefer bufferpool.Release(buf)\n\tbuf.WriteString(password)\n\tencoder := hex.NewEncoder(buf)\n\tfor i := 0; i < 30; i++ {\n\t\tbuf.WriteString(salt)\n\t\tbuf.WriteTo(hasher)\n\t\tencoder.Write(hasher.Sum(nil))\n\t\thasher.Reset()\n\t}\n\n\treturn buf.String()\n}",
"func hashSHA256(input string) string {\n\th := sha1.New()\n\th.Write([]byte(input))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func hash(s string) string {\n\th := fnv.New32a()\n\t_, err := h.Write([]byte(s))\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprint(h.Sum32())\n}",
"func NewKeccak512() hash.Hash { return &state{rate: 72, outputLen: 64, dsbyte: 0x01} }",
"func NewFzSha512Ref(ref unsafe.Pointer) *FzSha512 {\n\treturn (*FzSha512)(ref)\n}",
"func EncodeHash(s string) string {\n\th := sha1.New()\n\th.Write([]byte(s))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func encodeHash(x uint64, p, pPrime uint) (hashCode uint64) {\n\tif x&onesFromTo(64-pPrime, 63-p) == 0 {\n\t\tr := rho(extractShift(x, 0, 63-pPrime))\n\t\treturn concat([]concatInput{\n\t\t\t{x, 64 - pPrime, 63},\n\t\t\t{uint64(r), 0, 5},\n\t\t\t{1, 0, 0}, // this just adds a 1 bit at the end\n\t\t})\n\t} else {\n\t\treturn concat([]concatInput{\n\t\t\t{x, 64 - pPrime, 63},\n\t\t\t{0, 0, 0}, // this just adds a 0 bit at the end\n\t\t})\n\t}\n}",
"func Hash(data []byte) [blake2b.Size]byte {\n\treturn blake2b.Sum512(data)\n}",
"func SHA256Hex(data []byte) string {\n\treturn hex.EncodeToString(SHA256(data))\n}",
"func (d *Data)ComputeHash(k int, s string) {\n\n time.Sleep(5 * time.Second)\n\n h := sha512.New()\n h.Write([]byte(s))\n val := base64.StdEncoding.EncodeToString(h.Sum(nil))\n\n mutex.Lock()\n d.hashMap[k] = val\n d.inProgressCount--\n mutex.Unlock()\n}",
"func EncryptSHA256(text string) string {\n h := sha256.New()\n h.Write([]byte(text))\n s := base64.URLEncoding.EncodeToString(h.Sum(nil))\n return (s)\n}",
"func NewFzSha512() *FzSha512 {\n\treturn (*FzSha512)(allocFzSha512Memory(1))\n}",
"func hexEncodeSHA256Hash(body []byte) (string, error) {\n\thash := sha256.New()\n\tif body == nil {\n\t\tbody = []byte(\"\")\n\t}\n\t_, err := hash.Write(body)\n\treturn hex.EncodeToString(hash.Sum(nil)), err\n}",
"func GetKeccak512(from []byte) []byte {\n\thash := sha3.NewLegacyKeccak512()\n\thash.Write(from)\n\treturn hash.Sum(nil)\n}",
"func RS512(priv *rsa.PrivateKey, pub *rsa.PublicKey) Signer {\n\treturn &rsasha{priv: priv, pub: pub, hash: crypto.SHA512, alg: MethodRS512}\n}",
"func hash(s string) string {\n\thash := fnv.New32a()\n\thash.Write([]byte(s))\n\tintHash := hash.Sum32()\n\tresult := fmt.Sprintf(\"%08x\", intHash)\n\treturn result\n}",
"func SHA256(text string) string {\n\talgorithm := sha256.New()\n\treturn stringHasher(algorithm, text)\n}",
"func NewAvx512(a512srv *Avx512Server) hash.Hash {\n\tuid := atomic.AddUint64(&uidCounter, 1)\n\treturn &Avx512Digest{uid: uid, a512srv: a512srv}\n}",
"func KeccakSum512(data []byte) (digest [64]byte) {\n\th := NewKeccak512()\n\th.Write(data)\n\th.Sum(digest[:0])\n\treturn\n}",
"func Hashit(tox string) string {\n h:= sha256.New()\n h.Write([]byte(tox))\n bs := h.Sum([]byte{})\n str := base64.StdEncoding.EncodeToString(bs)\n return str\n}",
"func EncodeToSHA256(message string) string {\n\tbytes2 := sha256.Sum256([]byte(message))\n\treturn hex.EncodeToString(bytes2[:])\n}",
"func Encrypt512(block *[8]uint64, keys *[9]uint64, tweak *[3]uint64) {\n\tb0, b1, b2, b3 := block[0], block[1], block[2], block[3]\n\tb4, b5, b6, b7 := block[4], block[5], block[6], block[7]\n\n\tfor r := 0; r < 17; r++ {\n\t\tb0 += keys[r%9]\n\t\tb1 += keys[(r+1)%9]\n\t\tb2 += keys[(r+2)%9]\n\t\tb3 += keys[(r+3)%9]\n\t\tb4 += keys[(r+4)%9]\n\t\tb5 += keys[(r+5)%9] + tweak[r%3]\n\t\tb6 += keys[(r+6)%9] + tweak[(r+1)%3]\n\t\tb7 += keys[(r+7)%9] + uint64(r)\n\n\t\tb0 += b1\n\t\tb1 = (b1<<46 | b1>>(64-46)) ^ b0\n\t\tb2 += b3\n\t\tb3 = (b3<<36 | b3>>(64-36)) ^ b2\n\t\tb4 += b5\n\t\tb5 = (b5<<19 | b5>>(64-19)) ^ b4\n\t\tb6 += b7\n\t\tb7 = (b7<<37 | b7>>(64-37)) ^ b6\n\n\t\tb2 += b1\n\t\tb1 = (b1<<33 | b1>>(64-33)) ^ b2\n\t\tb4 += b7\n\t\tb7 = (b7<<27 | b7>>(64-27)) ^ b4\n\t\tb6 += b5\n\t\tb5 = (b5<<14 | b5>>(64-14)) ^ b6\n\t\tb0 += b3\n\t\tb3 = (b3<<42 | b3>>(64-42)) ^ b0\n\n\t\tb4 += b1\n\t\tb1 = (b1<<17 | b1>>(64-17)) ^ b4\n\t\tb6 += b3\n\t\tb3 = (b3<<49 | b3>>(64-49)) ^ b6\n\t\tb0 += b5\n\t\tb5 = (b5<<36 | b5>>(64-36)) ^ b0\n\t\tb2 += b7\n\t\tb7 = (b7<<39 | b7>>(64-39)) ^ b2\n\n\t\tb6 += b1\n\t\tb1 = (b1<<44 | b1>>(64-44)) ^ b6\n\t\tb0 += b7\n\t\tb7 = (b7<<9 | b7>>(64-9)) ^ b0\n\t\tb2 += b5\n\t\tb5 = (b5<<54 | b5>>(64-54)) ^ b2\n\t\tb4 += b3\n\t\tb3 = (b3<<56 | b3>>(64-56)) ^ b4\n\n\t\tr++\n\n\t\tb0 += keys[r%9]\n\t\tb1 += keys[(r+1)%9]\n\t\tb2 += keys[(r+2)%9]\n\t\tb3 += keys[(r+3)%9]\n\t\tb4 += keys[(r+4)%9]\n\t\tb5 += keys[(r+5)%9] + tweak[r%3]\n\t\tb6 += keys[(r+6)%9] + tweak[(r+1)%3]\n\t\tb7 += keys[(r+7)%9] + uint64(r)\n\n\t\tb0 += b1\n\t\tb1 = (b1<<39 | b1>>(64-39)) ^ b0\n\t\tb2 += b3\n\t\tb3 = (b3<<30 | b3>>(64-30)) ^ b2\n\t\tb4 += b5\n\t\tb5 = (b5<<34 | b5>>(64-34)) ^ b4\n\t\tb6 += b7\n\t\tb7 = (b7<<24 | b7>>(64-24)) ^ b6\n\n\t\tb2 += b1\n\t\tb1 = (b1<<13 | b1>>(64-13)) ^ b2\n\t\tb4 += b7\n\t\tb7 = (b7<<50 | b7>>(64-50)) ^ b4\n\t\tb6 += b5\n\t\tb5 = (b5<<10 | b5>>(64-10)) ^ b6\n\t\tb0 += b3\n\t\tb3 = (b3<<17 | b3>>(64-17)) ^ b0\n\n\t\tb4 += b1\n\t\tb1 = (b1<<25 | b1>>(64-25)) ^ b4\n\t\tb6 += b3\n\t\tb3 = (b3<<29 | b3>>(64-29)) ^ b6\n\t\tb0 += b5\n\t\tb5 = (b5<<39 | b5>>(64-39)) ^ b0\n\t\tb2 += b7\n\t\tb7 = (b7<<43 | b7>>(64-43)) ^ b2\n\n\t\tb6 += b1\n\t\tb1 = (b1<<8 | b1>>(64-8)) ^ b6\n\t\tb0 += b7\n\t\tb7 = (b7<<35 | b7>>(64-35)) ^ b0\n\t\tb2 += b5\n\t\tb5 = (b5<<56 | b5>>(64-56)) ^ b2\n\t\tb4 += b3\n\t\tb3 = (b3<<22 | b3>>(64-22)) ^ b4\n\t}\n\n\tb0 += keys[0]\n\tb1 += keys[1]\n\tb2 += keys[2]\n\tb3 += keys[3]\n\tb4 += keys[4]\n\tb5 += keys[5] + tweak[0]\n\tb6 += keys[6] + tweak[1]\n\tb7 += keys[7] + 18\n\n\tblock[0], block[1], block[2], block[3] = b0, b1, b2, b3\n\tblock[4], block[5], block[6], block[7] = b4, b5, b6, b7\n}",
"func sha256hex(buf []byte) (string, error) {\n\thasher := sha256.New()\n\tif _, err := hasher.Write(buf); err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to get sha256 hash: %w\", err)\n\t}\n\tcCodeHash := hasher.Sum(nil)\n\treturn hex.EncodeToString(cCodeHash), nil\n}",
"func encrypt512(dst, src *[8]uint64, k *[8]uint64, t *[2]uint64) {\n\tvar p0, p1, p2, p3, p4, p5, p6, p7 = src[0], src[1], src[2], src[3], src[4], src[5], src[6], src[7]\n\tt2 := t[0] ^ t[1]\n\tk8 := c240 ^ k[0] ^ k[1] ^ k[2] ^ k[3] ^ k[4] ^ k[5] ^ k[6] ^ k[7]\n\n\tp0 += k[0]\n\n\tp1 += k[1]\n\n\tp2 += k[2]\n\n\tp3 += k[3]\n\n\tp4 += k[4]\n\n\tp5 += k[5] + t[0]\n\n\tp6 += k[6] + t[1]\n\n\tp7 += k[7] + 0\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k[1]\n\n\tp1 += k[2]\n\n\tp2 += k[3]\n\n\tp3 += k[4]\n\n\tp4 += k[5]\n\n\tp5 += k[6] + t[1]\n\n\tp6 += k[7] + t2\n\n\tp7 += k8 + 1\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k[2]\n\n\tp1 += k[3]\n\n\tp2 += k[4]\n\n\tp3 += k[5]\n\n\tp4 += k[6]\n\n\tp5 += k[7] + t2\n\n\tp6 += k8 + t[0]\n\n\tp7 += k[0] + 2\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k[3]\n\n\tp1 += k[4]\n\n\tp2 += k[5]\n\n\tp3 += k[6]\n\n\tp4 += k[7]\n\n\tp5 += k8 + t[0]\n\n\tp6 += k[0] + t[1]\n\n\tp7 += k[1] + 3\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k[4]\n\n\tp1 += k[5]\n\n\tp2 += k[6]\n\n\tp3 += k[7]\n\n\tp4 += k8\n\n\tp5 += k[0] + t[1]\n\n\tp6 += k[1] + t2\n\n\tp7 += k[2] + 4\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k[5]\n\n\tp1 += k[6]\n\n\tp2 += k[7]\n\n\tp3 += k8\n\n\tp4 += k[0]\n\n\tp5 += k[1] + t2\n\n\tp6 += k[2] + t[0]\n\n\tp7 += k[3] + 5\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k[6]\n\n\tp1 += k[7]\n\n\tp2 += k8\n\n\tp3 += k[0]\n\n\tp4 += k[1]\n\n\tp5 += k[2] + t[0]\n\n\tp6 += k[3] + t[1]\n\n\tp7 += k[4] + 6\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k[7]\n\n\tp1 += k8\n\n\tp2 += k[0]\n\n\tp3 += k[1]\n\n\tp4 += k[2]\n\n\tp5 += k[3] + t[1]\n\n\tp6 += k[4] + t2\n\n\tp7 += k[5] + 7\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k8\n\n\tp1 += k[0]\n\n\tp2 += k[1]\n\n\tp3 += k[2]\n\n\tp4 += k[3]\n\n\tp5 += k[4] + t2\n\n\tp6 += k[5] + t[0]\n\n\tp7 += k[6] + 8\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k[0]\n\n\tp1 += k[1]\n\n\tp2 += k[2]\n\n\tp3 += k[3]\n\n\tp4 += k[4]\n\n\tp5 += k[5] + t[0]\n\n\tp6 += k[6] + t[1]\n\n\tp7 += k[7] + 9\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k[1]\n\n\tp1 += k[2]\n\n\tp2 += k[3]\n\n\tp3 += k[4]\n\n\tp4 += k[5]\n\n\tp5 += k[6] + t[1]\n\n\tp6 += k[7] + t2\n\n\tp7 += k8 + 10\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k[2]\n\n\tp1 += k[3]\n\n\tp2 += k[4]\n\n\tp3 += k[5]\n\n\tp4 += k[6]\n\n\tp5 += k[7] + t2\n\n\tp6 += k8 + t[0]\n\n\tp7 += k[0] + 11\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k[3]\n\n\tp1 += k[4]\n\n\tp2 += k[5]\n\n\tp3 += k[6]\n\n\tp4 += k[7]\n\n\tp5 += k8 + t[0]\n\n\tp6 += k[0] + t[1]\n\n\tp7 += k[1] + 12\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k[4]\n\n\tp1 += k[5]\n\n\tp2 += k[6]\n\n\tp3 += k[7]\n\n\tp4 += k8\n\n\tp5 += k[0] + t[1]\n\n\tp6 += k[1] + t2\n\n\tp7 += k[2] + 13\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k[5]\n\n\tp1 += k[6]\n\n\tp2 += k[7]\n\n\tp3 += k8\n\n\tp4 += k[0]\n\n\tp5 += k[1] + t2\n\n\tp6 += k[2] + t[0]\n\n\tp7 += k[3] + 14\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k[6]\n\n\tp1 += k[7]\n\n\tp2 += k8\n\n\tp3 += k[0]\n\n\tp4 += k[1]\n\n\tp5 += k[2] + t[0]\n\n\tp6 += k[3] + t[1]\n\n\tp7 += k[4] + 15\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k[7]\n\n\tp1 += k8\n\n\tp2 += k[0]\n\n\tp3 += k[1]\n\n\tp4 += k[2]\n\n\tp5 += k[3] + t[1]\n\n\tp6 += k[4] + t2\n\n\tp7 += k[5] + 16\n\n\tp0 += p1\n\tp1 = p1<<46 | p1>>(64-46)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<36 | p3>>(64-36)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<19 | p5>>(64-19)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<37 | p7>>(64-37)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<33 | p1>>(64-33)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<27 | p7>>(64-27)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<14 | p5>>(64-14)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<42 | p3>>(64-42)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<17 | p1>>(64-17)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<49 | p3>>(64-49)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<36 | p5>>(64-36)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<39 | p7>>(64-39)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<44 | p1>>(64-44)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<9 | p7>>(64-9)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<54 | p5>>(64-54)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<56 | p3>>(64-56)\n\tp3 ^= p4\n\n\tp0 += k8\n\n\tp1 += k[0]\n\n\tp2 += k[1]\n\n\tp3 += k[2]\n\n\tp4 += k[3]\n\n\tp5 += k[4] + t2\n\n\tp6 += k[5] + t[0]\n\n\tp7 += k[6] + 17\n\n\tp0 += p1\n\tp1 = p1<<39 | p1>>(64-39)\n\tp1 ^= p0\n\n\tp2 += p3\n\tp3 = p3<<30 | p3>>(64-30)\n\tp3 ^= p2\n\n\tp4 += p5\n\tp5 = p5<<34 | p5>>(64-34)\n\tp5 ^= p4\n\n\tp6 += p7\n\tp7 = p7<<24 | p7>>(64-24)\n\tp7 ^= p6\n\n\tp2 += p1\n\tp1 = p1<<13 | p1>>(64-13)\n\tp1 ^= p2\n\n\tp4 += p7\n\tp7 = p7<<50 | p7>>(64-50)\n\tp7 ^= p4\n\n\tp6 += p5\n\tp5 = p5<<10 | p5>>(64-10)\n\tp5 ^= p6\n\n\tp0 += p3\n\tp3 = p3<<17 | p3>>(64-17)\n\tp3 ^= p0\n\n\tp4 += p1\n\tp1 = p1<<25 | p1>>(64-25)\n\tp1 ^= p4\n\n\tp6 += p3\n\tp3 = p3<<29 | p3>>(64-29)\n\tp3 ^= p6\n\n\tp0 += p5\n\tp5 = p5<<39 | p5>>(64-39)\n\tp5 ^= p0\n\n\tp2 += p7\n\tp7 = p7<<43 | p7>>(64-43)\n\tp7 ^= p2\n\n\tp6 += p1\n\tp1 = p1<<8 | p1>>(64-8)\n\tp1 ^= p6\n\n\tp0 += p7\n\tp7 = p7<<35 | p7>>(64-35)\n\tp7 ^= p0\n\n\tp2 += p5\n\tp5 = p5<<56 | p5>>(64-56)\n\tp5 ^= p2\n\n\tp4 += p3\n\tp3 = p3<<22 | p3>>(64-22)\n\tp3 ^= p4\n\n\tp0 += k[0]\n\n\tp1 += k[1]\n\n\tp2 += k[2]\n\n\tp3 += k[3]\n\n\tp4 += k[4]\n\n\tp5 += k[5] + t[0]\n\n\tp6 += k[6] + t[1]\n\n\tp7 += k[7] + 18\n\n\tdst[0], dst[1], dst[2], dst[3], dst[4], dst[5], dst[6], dst[7] = p0, p1, p2, p3, p4, p5, p6, p7\n}",
"func Sha256d(input []byte) Hash {\n sha := sha256.New()\n sha.Write(input)\n intermediate := sha.Sum(nil)\n sha.Reset()\n sha.Write(intermediate)\n hash, err := HashFromBytes(sha.Sum(nil), LittleEndian)\n if err != nil {\n panic(\"impossible flow, this is a bug: \" + err.Error())\n }\n return hash\n}",
"func HashStringSha256(hs string) []byte {\n\tdata := []byte(hs)\n\thash := sha256.Sum256(data)\n\treturn hash[:]\n}",
"func hashme(s interface{}) string {\n\tbytes, _ := json.Marshal(s)\n\th := sha256.New()\n\th.Write(bytes)\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func (r *Restriction) hash() ([]byte, error) {\n\tj, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn hashUtils.SHA512(j), nil\n}",
"func hash(passphrase, token string, timestamp int64) string {\n\tbase := fmt.Sprintf(\"%s-%s-%d\", passphrase, token, timestamp)\n\treturn fmt.Sprintf(\"%x\", sha512.Sum512([]byte(base)))\n}",
"func generateSHA256HashInHexForm(preimage string) string {\n\thasher := sha256.New()\n\thasher.Write([]byte(preimage))\n\tshaHash := hasher.Sum(nil)\n\tshaHashHex := hex.EncodeToString(shaHash)\n\treturn shaHashHex\n}",
"func hash(s string) string {\n\treturn fmt.Sprintf(\"%x\", md5.Sum([]byte(s)))\n}",
"func ScryptSHA256(password string, salt []byte, N, r, p int) string {\n\tpasswordb := []byte(password)\n\n\thash, err := scrypt.Key(passwordb, salt, N, r, p, 32)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\thstr := base64.StdEncoding.EncodeToString(hash)\n\tsstr := base64.StdEncoding.EncodeToString(salt)\n\n\treturn fmt.Sprintf(\"$s2$%d$%d$%d$%s$%s\", N, r, p, sstr, hstr)\n}",
"func SHA512ChecksumData(data []byte) ([]byte, error) {\n\th := sha512.New()\n\tif _, err := h.Write(data); err != nil {\n\t\tpanic(errors.Wrap(err, `\"It never returns an error.\" -- https://golang.org/pkg/hash`))\n\t}\n\treturn h.Sum(nil), nil\n}",
"func Sha256(o interface{}) ([]byte, error) {\n\thash := sha256.New()\n\tif _, err := hash.Write([]byte(fmt.Sprintf(\"%+v\", o))); err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn hash.Sum(nil), nil\n}",
"func Sha256(data string, salt string) string {\n\tb := []byte(data + salt)\n\treturn fmt.Sprintf(\"%X\", sha256.Sum256(b))\n}",
"func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}",
"func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}",
"func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}",
"func Sha256Hash(data []byte) [32]byte {\n\tsum := sha256.Sum256(data)\n\treturn sum\n}",
"func CalculateSRI(bytes []byte) string {\n\th := sha512.New()\n\t_, err := h.Write(bytes)\n\tutil.Check(err)\n\n\tsri := base64.StdEncoding.EncodeToString(h.Sum(nil))\n\treturn fmt.Sprintf(\"sha512-%s\", sri)\n}",
"func DoubleSha256SH(b []byte) ShaHash {\n\tfirst := fastsha256.Sum256(b)\n\treturn ShaHash(fastsha256.Sum256(first[:]))\n}",
"func hash(s string) uint32 {\n h := fnv.New32a()\n h.Write([]byte(s))\n return h.Sum32()\n}",
"func Hash256(pass string, salt string) string {\n\tcombined_bytes := []byte(pass + salt)\n\thash_bytes := hasher256.Sum(combined_bytes)\n\treturn hex.EncodeToString(hash_bytes)\n}",
"func (n Node) CalSHA256Hash(input []byte) []byte {\r\n\th := sha256.New()\r\n\th.Write(input)\r\n\treturn h.Sum(nil)\r\n}",
"func PasswordHash(username string, password string, userID string) (h string) {\n\thash := sha512.New()\n\n\t// Can not use username as hash salt\n\trunes := []rune(password)\n\tfor i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {\n\t\trunes[i], runes[j] = runes[j], runes[i]\n\t}\n\treversePassword := string(runes)\n\n\thash.Write([]byte(password + userID + reversePassword))\n\th = hex.EncodeToString(hash.Sum(nil))\n\toutput.Debug(\"%+v\", h)\n\treturn\n}",
"func (h SenHash) Write(p []byte) (n int, err error) {\n\treturn h.blake512hasher.Write(p)\n}",
"func ShaSum256HexEncoded(b []byte) string {\n\tsha := sha256.Sum256(b)\n\tshaHex := hex.EncodeToString(sha[:])\n\n\treturn shaHex\n}",
"func ShaSum256HexEncoded(b []byte) string {\n\tsha := sha256.Sum256(b)\n\tshaHex := hex.EncodeToString(sha[:])\n\n\treturn shaHex\n}",
"func getSHA256Hash(data []byte) string {\n\treturn hex.EncodeToString(getSHA256Sum(data))\n}",
"func sha52(data []byte) []byte {\n\th1 := sha512.Sum512(data)\n\th2 := sha256.Sum256(append(h1[:], data...))\n\treturn h2[:]\n}",
"func Hash(input []byte) string {\n\treturn fmt.Sprintf(\"%x\", sha256.Sum256(input))\n}",
"func MustSHA512Half(v []byte) string {\n\th, err := SHA512Half(v)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn h\n}",
"func Hash256Bytes(bytes []byte) string {\n\thasher := sha256.New()\n\thasher.Write(bytes)\n\tmsgDigest := hasher.Sum(nil)\n\tsha256Hex := hex.EncodeToString(msgDigest)\n\treturn sha256Hex\n}",
"func hash(ba string) string {\n\th := sha256.New()\n\th.Write([]byte(ba))\n\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}",
"func SHA256(raw []byte) Hash {\n\treturn gosha256.Sum256(raw)\n}",
"func isSHA512(fl FieldLevel) bool {\n\treturn sha512Regex.MatchString(fl.Field().String())\n}",
"func (f *Filter) marshal() (buf *bytes.Buffer,\n\thash [sha512.Size384]byte,\n\terr error,\n) {\n\tf.lock.RLock()\n\tdefer f.lock.RUnlock()\n\n\tdebug(\"write bf k=%d n=%d m=%d\\n\", f.K(), f.n, f.m)\n\n\tbuf = new(bytes.Buffer)\n\n\terr = binary.Write(buf, binary.LittleEndian, f.K())\n\tif err != nil {\n\t\treturn nil, hash, err\n\t}\n\n\terr = binary.Write(buf, binary.LittleEndian, f.n)\n\tif err != nil {\n\t\treturn nil, hash, err\n\t}\n\n\terr = binary.Write(buf, binary.LittleEndian, f.m)\n\tif err != nil {\n\t\treturn nil, hash, err\n\t}\n\n\terr = binary.Write(buf, binary.LittleEndian, f.keys)\n\tif err != nil {\n\t\treturn nil, hash, err\n\t}\n\n\terr = binary.Write(buf, binary.LittleEndian, f.bits)\n\tif err != nil {\n\t\treturn nil, hash, err\n\t}\n\n\thash = sha512.Sum384(buf.Bytes())\n\terr = binary.Write(buf, binary.LittleEndian, hash)\n\treturn buf, hash, err\n}",
"func Sha256(buf []byte) []byte {\n\treturn CalcHash(buf, sha256.New())\n}",
"func Hash128(s []byte) (lo, hi uint64) {\n\tif len(s) >= 16 {\n\t\treturn Hash128WithSeed(s[16:], fetch64(s), fetch64(s[8:])+k0)\n\t}\n\treturn Hash128WithSeed(s, k0, k1)\n}",
"func Sha256Hash(file io.Reader) (string, error) {\n\tbuf := bytes.NewBuffer(nil)\n\tif _, err := io.Copy(buf, file); err != nil {\n\t\tlog.Println(\"Failed to copy file to buffer in hashing function...\")\n\t\treturn \"\", err\n\t}\n\n\thasher := sha256.New()\n\thasher.Write(buf.Bytes())\n\n\tsha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))\n\n\treturn sha, nil\n}",
"func NewSenHash() hash.Hash {\n\tb2b, _ := blake2b.New512(nil)\n\treturn SenHash{\n\t\tblake512hasher: b2b,\n\t}\n}",
"func (h Hash) String() string { return hex.EncodeToString(h[:]) }",
"func HS256(value string, key string) ([]byte, error) {\n\tcipher := hmac.New(sha256.New, []byte(key))\n\t_, err := cipher.Write([]byte(value))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cipher.Sum(nil), nil\n}",
"func Hash(s string) string {\n\tfmt.Println(\"Hashing string:\", s)\n\thash := sha256.Sum256([]byte(s))\n\tniceHash := fmt.Sprintf(\"%x\", hash)\n\tfmt.Println(\"Created hash:\", hash)\n\treturn niceHash\n}",
"func ShortenSHA(s string) string {\n\treturn s[:6]\n}"
] | [
"0.7580785",
"0.7445982",
"0.7233762",
"0.6934386",
"0.69034374",
"0.653398",
"0.6385893",
"0.62731814",
"0.6130927",
"0.610307",
"0.6040214",
"0.6000387",
"0.6000006",
"0.59936017",
"0.59203404",
"0.59176266",
"0.589954",
"0.58605695",
"0.58491516",
"0.5779612",
"0.57791406",
"0.57764685",
"0.57283777",
"0.5721603",
"0.5713147",
"0.56263334",
"0.56185347",
"0.5615665",
"0.561277",
"0.5594654",
"0.5577691",
"0.5576321",
"0.5563482",
"0.5563482",
"0.5563482",
"0.5556629",
"0.5545969",
"0.5540707",
"0.5531486",
"0.5513439",
"0.5510655",
"0.5475605",
"0.5461174",
"0.5457364",
"0.54523516",
"0.5438061",
"0.54089147",
"0.54085517",
"0.5402201",
"0.53743553",
"0.5363283",
"0.535081",
"0.5341807",
"0.53254443",
"0.5324678",
"0.5312923",
"0.5304831",
"0.53029776",
"0.52931255",
"0.52885514",
"0.5287539",
"0.5275901",
"0.5275166",
"0.52682555",
"0.52666247",
"0.52444303",
"0.5241553",
"0.52374697",
"0.52370095",
"0.5233217",
"0.5224542",
"0.5224542",
"0.5224542",
"0.52210075",
"0.52122736",
"0.5211974",
"0.52075285",
"0.52060616",
"0.5191713",
"0.51868457",
"0.51862603",
"0.5175901",
"0.5175901",
"0.51738006",
"0.5158322",
"0.51580924",
"0.51454103",
"0.5133259",
"0.51289845",
"0.511822",
"0.5117541",
"0.5115155",
"0.5109975",
"0.51007867",
"0.5098374",
"0.5085974",
"0.5085517",
"0.508047",
"0.5076665",
"0.5075225"
] | 0.83931375 | 0 |
ValidHash512 returns true if length of s same as size of a SHA512 checksum. | func ValidHash512(s string) bool {
return len(s) == sha512.Size*2
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func IsSHA512(str string) bool {\n\treturn IsHash(str, \"sha512\")\n}",
"func isSHA512(fl FieldLevel) bool {\n\treturn sha512Regex.MatchString(fl.Field().String())\n}",
"func (p *Password) SHA512(saltConf ...*SaltConf) ([64]byte, []byte) {\n\tif len(saltConf) > 0 {\n\t\tvar saltLength int\n\n\t\tfor _, i := range saltConf[0:] {\n\t\t\tsaltLength = i.Length\n\t\t}\n\n\t\tsalt := getRandomBytes(saltLength)\n\t\treturn sha512.Sum512([]byte(fmt.Sprintf(\"%s%x\", p.Pass, salt))), salt\n\t}\n\treturn sha512.Sum512([]byte(p.Pass)), nil\n}",
"func SHA512Digest(s string) string {\n\th := sha512.Sum512([]byte(s))\n\treturn hex.EncodeToString(h[:])\n}",
"func TestSsha512(t *testing.T) {\n\tconst plain = \"Hi, arche.\"\n\tencode, err := nut.SumSsha512(plain, 32)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Logf(`doveadm pw -t {SSHA512}%s -p \"%s\"`, encode, plain)\n\tif !nut.EqualSsha512(encode, plain) {\n\t\tt.Error(\"check password failed\")\n\t}\n}",
"func SHA512(text string) string {\n\treturn stringHasher(sha512.New(), text)\n}",
"func ValidHash(s string) bool {\n\treturn len(s) == sha1.Size*2\n}",
"func Hash512(tag string, data []byte) []byte {\n\th := hmac.New(sha512.New512_256, []byte(tag))\n\th.Write(data)\n\treturn h.Sum(nil)\n}",
"func SHA512ChecksumData(data []byte) ([]byte, error) {\n\th := sha512.New()\n\tif _, err := h.Write(data); err != nil {\n\t\tpanic(errors.Wrap(err, `\"It never returns an error.\" -- https://golang.org/pkg/hash`))\n\t}\n\treturn h.Sum(nil), nil\n}",
"func hashSHA512(text string) []byte {\n\thash := sha512.New()\n\thash.Write([]byte(text))\n\treturn hash.Sum(nil)\n}",
"func Sum512(data []byte) [Size]byte {\n\tvar d digest\n\td.Reset()\n\td.Write(data)\n\treturn d.checkSum()\n}",
"func HS512(secret []byte) SignerVerifier {\n\treturn SymmetricSignature(&HMACSignerVerifier{\n\t\th: sha512.New,\n\t\tsecret: secret,\n\t\talg: ALG_HS512,\n\t})\n}",
"func (d *Avx512Digest) Size() int { return Size }",
"func SHA512(text string) string {\n\thasher := sha512.New()\n\thasher.Write([]byte(text))\n\treturn strings.ToUpper(hex.EncodeToString(hasher.Sum(nil)))\n}",
"func GenerateSHA512FromString(password string) (string, error) {\n\tcrypter := sha512_crypt.New()\n\tpasswordByteStream := []byte(password)\n\tpasswordHash, err := crypter.Generate(passwordByteStream, []byte{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn passwordHash, nil\n}",
"func EncodeHash512(s string) string {\n\th := sha512.New()\n\th.Write([]byte(s))\n\treturn hex.EncodeToString(h.Sum(nil))\n}",
"func hasChecksum(n int64) bool {\n\t// 512 is chosen because it's a minimum disk sector size\n\t// smaller than (and multiplies to) OS page size in most systems\n\treturn (n % 512) == sha256.Size\n}",
"func MustSHA512Half(v []byte) string {\n\th, err := SHA512Half(v)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn h\n}",
"func Sha512(master, salt, info []byte) ([32]byte, error) {\n\thash := sha512.New\n\thkdf := hkdf.New(hash, master, salt, info)\n\n\tkey := make([]byte, 32) // 256 bit\n\t_, err := io.ReadFull(hkdf, key)\n\n\tvar result [32]byte\n\tcopy(result[:], key)\n\n\treturn result, err\n}",
"func Validate(h, s, p string) bool {\n\treturn h == ComputeHash(p, s)\n}",
"func ValidHash256(s string) bool {\n\treturn len(s) == sha256.Size*2\n}",
"func Sha512(in, out []byte) error {\n\th := poolSha512.Get().(hash.Hash)\n\tif _, err := h.Write(in); err != nil {\n\t\th.Reset()\n\t\tpoolSha512.Put(h)\n\t\treturn err\n\t}\n\th.Sum(out)\n\th.Reset()\n\tpoolSha512.Put(h)\n\treturn nil\n}",
"func WithSHA512(enabled bool) Option {\n\treturn func(s *settings) {\n\t\tif enabled {\n\t\t\ts.h = sha512.New\n\t\t}\n\t}\n}",
"func Hmac512(key string, data io.Reader) (b64 string, err error) {\n\thash := hmac.New(sha512.New, []byte(key))\n\tb, err := ioutil.ReadAll(data)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to read data from reader\")\n\t}\n\tif _, err := hash.Write(b); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to hash data\")\n\t}\n\treturn base64.StdEncoding.EncodeToString(hash.Sum(nil)), nil\n}",
"func HashIsSHA256(hash string) bool {\n\treturn len(hash) == 64\n}",
"func IsSignerHashValid(hash []byte) (bool, *Signer) {\n\tif sha512.Size != len(hash) {\n\t\treturn false, nil\n\t}\n\n\treturn true, NewSigner(hash)\n}",
"func HashIsSHA1(hash string) bool {\n\treturn len(hash) == 40\n}",
"func IsDigestValid(decryptedCell []byte) bool {\n\n\tif len(decryptedCell) != 512 {\n\t\treturn false\n\t}\n\tdigest := DecodePayloadDigest(decryptedCell)\n\tpayload := DecodeRelayPayload(decryptedCell)\n\tsum := md5.Sum(payload)\n\n\tfor i := 0; i < DigestLength; i++ {\n\t\tif digest[i] != sum[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}",
"func xx512x1(inner_512 []byte) [20]byte {\n\touter_512 := sha512.Sum512(inner_512)\n\treturn sha1.Sum(outer_512[:])\n}",
"func isValidHash(hashType, hash string) bool {\n\tswitch hashType {\n\tcase string(HashMD5):\n\t\treturn len(hash) == 32\n\tcase string(HashSHA1):\n\t\treturn len(hash) == 40\n\tcase string(HashSHA256):\n\t\treturn len(hash) == 64\n\tcase string(HashSHA512):\n\t\treturn len(hash) == 128\n\tdefault:\n\t\treturn false\n\t}\n}",
"func SHA512Half(v []byte) (string, error) {\n\th := sha512.New()\n\t_, err := io.Copy(h, bytes.NewBuffer(v))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil)[:sha512.Size/2]), nil\n}",
"func PutBytesSlice512(p []byte) bool {\n\tif l := cap(p); l < 512 || l >= 1024 {\n\t\treturn PutBytesSlice(p)\n\t}\n\tp = p[0:512]\n\tput512(internal.Gets(p))\n\treturn true\n}",
"func NewFzSha512Ref(ref unsafe.Pointer) *FzSha512 {\n\treturn (*FzSha512)(ref)\n}",
"func HashIsMD5(hash string) bool {\n\treturn len(hash) == 32\n}",
"func PutBytesBuffer512(b *bytes.Buffer) bool {\n\tif b == nil {\n\t\treturn false\n\t}\n\tif l := b.Cap(); l < 512 || l >= 1024 {\n\t\treturn PutBytesBuffer(b)\n\t}\n\tb.Reset()\n\tputb512(b)\n\treturn true\n}",
"func IsValidDigest(hash string) bool {\n\t// Currently we expect all digests to be ASCII encoded MD5 hashes.\n\tif len(hash) != 32 {\n\t\treturn false\n\t}\n\n\tfor _, c := range []byte(hash) {\n\t\tif ((c >= '0') && (c <= '9')) ||\n\t\t\t((c >= 'a') && (c <= 'f')) ||\n\t\t\t((c >= 'A') && (c <= 'F')) {\n\t\t\tcontinue\n\t\t}\n\t\treturn false\n\t}\n\treturn true\n}",
"func (d Avx512Digest) BlockSize() int { return BlockSize }",
"func RS512(priv *rsa.PrivateKey, pub *rsa.PublicKey) Signer {\n\treturn &rsasha{priv: priv, pub: pub, hash: crypto.SHA512, alg: MethodRS512}\n}",
"func Validate(username, hash string, userCreds database.UserCreds) (bool, string) {\n\t// Take SHA256 hash of the hash given by user\n\thashOfHash := sha256.Sum256([]byte(hash))\n\thashString := hex.EncodeToString(hashOfHash[:])\n\t// If the hash is not equal throw error\n\tif hashString != userCreds.Hash {\n\t\tfmt.Printf(\"%s Error ::%s Hash is Invalid\\n\\n\", chalk.Red, chalk.Reset)\n\t\treturn false, \"Invalid Hash. Your password was incorrect.\"\n\t}\n\n\t// If equal decrement n and change hash in database\n\tuserCreds.Hash = hash\n\tuserCreds.N -= 1\n\tdatabase.Set(username, userCreds)\n\treturn true, \"\"\n}",
"func KeccakSum512(data []byte) (digest [64]byte) {\n\th := NewKeccak512()\n\th.Write(data)\n\th.Sum(digest[:0])\n\treturn\n}",
"func (h *ArgonHasher) Validate(password, encoded string) (bool, error) {\n\tparams, salt, hash, err := decodeHash(encoded)\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tpasswordHash := argon2.IDKey([]byte(password), salt, params.Iterations, params.Memory, params.Threads, params.KeyLength)\n\n\tif subtle.ConstantTimeCompare(hash, passwordHash) == 0 {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}",
"func IsTruncatedCommitSHA(sha string) bool {\n\treturn truncatedCommitSHARegex.MatchString(sha)\n}",
"func VerifySha256(password, hash string) bool {\n return Sha256Hash(password) == hash\n}",
"func Validate(token []byte) (isValid bool) {\n\t//fast path\n\tif len(token) != TOKEN_SIZE {\n\t\treturn\n\t}\n\n\thash := createHash(token[32:])\n\n\t//now compare our hash with input\n\tif bytes.Compare(token[0:32], hash) == 0 {\n\t\tisValid = true\n\t}\n\n\treturn\n}",
"func sha52(data []byte) []byte {\n\th1 := sha512.Sum512(data)\n\th2 := sha256.Sum256(append(h1[:], data...))\n\treturn h2[:]\n}",
"func (s *Salt) IsValid() bool {\n\treturn len(*s) == saltLen\n}",
"func IsValidHash(obj string) bool {\n\treturn hashPtn.MatchString(obj)\n}",
"func validSha(sha string) error {\n\tif len(sha) != 40 {\n\t\treturn fmt.Errorf(\"sha not 40 characters: %s\", sha)\n\t}\n\t// TODO(dbentley): check that it's hexadecimal?\n\treturn nil\n}",
"func isServerProxyHeadersHashBucketSizeDirective(directive string) bool {\n\tif isEqualString(directive, ServerProxyHeadersHashBucketSizeDirective) {\n\t\treturn true\n\t}\n\treturn false\n}",
"func Keccak512(data ...[]byte) []byte {\n\td := sha3.NewKeccak512()\n\tfor _, b := range data {\n\t\td.Write(b)\n\t}\n\treturn d.Sum(nil)\n}",
"func Keccak512(data ...[]byte) []byte {\n\td := sha3.NewKeccak512()\n\tfor _, b := range data {\n\t\td.Write(b)\n\t}\n\treturn d.Sum(nil)\n}",
"func Keccak512(data ...[]byte) []byte {\n\td := sha3.NewKeccak512()\n\tfor _, b := range data {\n\t\td.Write(b)\n\t}\n\treturn d.Sum(nil)\n}",
"func CheckHMACHash(data string, hash string, secret string) bool {\n\th := hmac.New(sha256.New, []byte(secret))\n\th.Write([]byte(data))\n\t// Get result and encode as hexadecimal string\n\tsha := hex.EncodeToString(h.Sum(nil))\n\treturn sha == hash\n}",
"func IsValidHash(s string) bool {\n\tout, err := b58.Decode(s)\n\tif err != nil {\n\t\treturn false\n\t}\n\t_, err = mh.Cast(out)\n\treturn err == nil\n}",
"func IsHash(str string, algorithm string) bool {\n\tlen := \"0\"\n\talgo := strings.ToLower(algorithm)\n\n\tif algo == \"crc32\" || algo == \"crc32b\" {\n\t\tlen = \"8\"\n\t} else if algo == \"md5\" || algo == \"md4\" || algo == \"ripemd128\" || algo == \"tiger128\" {\n\t\tlen = \"32\"\n\t} else if algo == \"sha1\" || algo == \"ripemd160\" || algo == \"tiger160\" {\n\t\tlen = \"40\"\n\t} else if algo == \"tiger192\" {\n\t\tlen = \"48\"\n\t} else if algo == \"sha256\" {\n\t\tlen = \"64\"\n\t} else if algo == \"sha384\" {\n\t\tlen = \"96\"\n\t} else if algo == \"sha512\" {\n\t\tlen = \"128\"\n\t} else {\n\t\treturn false\n\t}\n\n\treturn Matches(str, \"^[a-f0-9]{\"+len+\"}$\")\n}",
"func Validate(digest *repb.Digest) error {\n\tif digest == nil {\n\t\treturn errors.New(\"nil digest\")\n\t}\n\tif ok, err := validateHashLength(digest.Hash); !ok {\n\t\treturn err\n\t}\n\tif !hexStringRegex.MatchString(digest.Hash) {\n\t\treturn fmt.Errorf(\"hash is not a lowercase hex string (%s)\", digest.Hash)\n\t}\n\tif digest.SizeBytes < 0 {\n\t\treturn fmt.Errorf(\"expected non-negative size, got %d\", digest.SizeBytes)\n\t}\n\treturn nil\n}",
"func Verify(sig *Signature, hash []byte) (bool, error) {\n\tif sig.Mode == ModeEdDSA {\n\t\tif len(hash) != crypto.SHA512.Size() {\n\t\t\tmsg := fmt.Sprintf(\"invalid hash length. wanted: %d, got: %d\", crypto.SHA512.Size(), len(hash))\n\t\t\treturn false, errors.New(msg)\n\t\t}\n\n\t\teddsaSig := sig.Signature\n\t\tif len(eddsaSig) != SignatureLength {\n\t\t\tmsg := fmt.Sprintf(\"invalid signature length. wanted: %d, got: %d\", SignatureLength, len(eddsaSig))\n\t\t\treturn false, errors.New(msg)\n\t\t}\n\t\topts := ed25519.Options{\n\t\t\tHash: crypto.SHA512,\n\t\t}\n\t\treturn ed25519.VerifyWithOptions(sig.Address, hash, eddsaSig, &opts), nil\n\t} else if sig.Mode == ModeBLS {\n\t\tif len(hash) != crypto.SHA3_256.Size() {\n\t\t\tmsg := fmt.Sprintf(\"invalid hash length. wanted: %d, got: %d\", crypto.SHA3_256.Size(), len(hash))\n\t\t\treturn false, errors.New(msg)\n\t\t}\n\n\t\tvar blsSig bls.Sign\n\t\tblsSig.Deserialize(sig.Signature)\n\t\tvar blsPub bls.PublicKey\n\t\tblsPub.Deserialize(sig.Address)\n\n\t\treturn blsSig.VerifyHash(&blsPub, hash), nil\n\t} else if sig.Mode == ModeMerkle {\n\t\t// calculate master\n\t\tcurrent := hash\n\t\tfor i := range sig.MerklePath {\n\t\t\th := sha512.New()\n\t\t\thash := sig.MerklePath[i]\n\t\t\tindex := sig.MerkleIndexes[i]\n\t\t\tvar msg []byte\n\t\t\tif index == false {\n\t\t\t\t// hash is left\n\t\t\t\tmsg = append(hash, current...)\n\t\t\t} else {\n\t\t\t\t// hash is right\n\t\t\t\tmsg = append(current, hash...)\n\t\t\t}\n\t\t\tif _, err := h.Write(msg); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\tcurrent = h.Sum(nil)\n\t\t}\n\n\t\t// `current` should now be the merkle root.\n\n\t\t// use caching: find out whether we previously already checked that\n\t\t// signature is ok. for this, use hash(addr || merkle root || sig)\n\t\th := crypto.SHA256.New()\n\t\th.Write(sig.Address)\n\t\th.Write(current)\n\t\th.Write(sig.Signature)\n\t\tsigHash := h.Sum(nil)\n\t\tsigHashIndex := [32]byte{}\n\t\tcopy(sigHashIndex[:], sigHash[:])\n\n\t\t// lookup cache and return if cached\n\t\tif UseMerkleSignatureCaching {\n\t\t\tcachedValid, ok := merkleSigCache.Load(sigHashIndex)\n\t\t\tif ok && cachedValid == true {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t\t// there is no cache entry, or entry was false.\n\t\topts := ed25519.Options{\n\t\t\tHash: crypto.SHA512,\n\t\t}\n\t\tvalid := ed25519.VerifyWithOptions(sig.Address, current, sig.Signature, &opts)\n\t\tif valid {\n\t\t\tmerkleSigCache.Store(sigHashIndex, true)\n\t\t}\n\t\treturn valid, nil\n\t} else {\n\t\treturn false, errors.New(\"mode not supported\")\n\t}\n}",
"func (s *grpcServer) validateHash(hash string, logPrefix string) error {\n\tif len(hash) != hashKeyLength {\n\t\tmsg := fmt.Sprintf(\"Hash length must be length %d\", hashKeyLength)\n\t\ts.accessLogger.Printf(\"%s %s: %s\", logPrefix, hash, msg)\n\t\treturn status.Error(codes.InvalidArgument, msg)\n\t}\n\n\tif !hashKeyRegex.MatchString(hash) {\n\t\tmsg := \"Malformed hash\"\n\t\ts.accessLogger.Printf(\"%s %s: %s\", logPrefix, hash, msg)\n\t\treturn status.Error(codes.InvalidArgument, msg)\n\t}\n\n\treturn nil\n}",
"func Sha3512(bs []byte) ([]byte, error) {\n\treturn PerformHash(sha3.New512(), bs)\n}",
"func ValidateSledPassword(password string, rule Rule) bool {\n\n\tcount := 0\n\n\tfor _, letter := range password {\n\t\tif letter == rule.letter {\n\t\t\tcount = count + 1\n\t\t}\n\t}\n\n\treturn count >= rule.min && count <= rule.max\n}",
"func isSHA384(fl FieldLevel) bool {\n\treturn sha384Regex.MatchString(fl.Field().String())\n}",
"func IsSHA256(str string) bool {\n\treturn IsHash(str, \"sha256\")\n}",
"func CheckHash(password, hash string) (match bool, params *Params, err error) {\n\tparams, salt, key, err := DecodeHash(hash)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\n\totherKey := argon2.IDKey([]byte(password), salt, params.Iterations, params.Memory, params.Parallelism, params.KeyLength)\n\n\tkeyLen := int32(len(key))\n\totherKeyLen := int32(len(otherKey))\n\n\tif subtle.ConstantTimeEq(keyLen, otherKeyLen) == 0 {\n\t\treturn false, params, nil\n\t}\n\tif subtle.ConstantTimeCompare(key, otherKey) == 1 {\n\t\treturn true, params, nil\n\t}\n\treturn false, params, nil\n}",
"func new512Asm() hash.Hash { return nil }",
"func isValidHashType(ht string) bool {\n\treturn ht == string(HashMD5) || ht == string(HashSHA1) || ht == string(HashSHA256) || ht == string(HashSHA512)\n}",
"func validateHexHash(s string) error {\n\tif has0xPrefix(s) {\n\t\ts = s[2:]\n\t}\n\tif len(s)%2 == 1 {\n\t\ts = \"0\" + s\n\t}\n\t_, err := hex.DecodeString(s)\n\treturn err\n}",
"func checkHashSize(hexStr string) int {\n\tmaxint64 := 9223372036854775807\n\tminint64 := -9223372036854775807\n\tint64val := hex2int(hexStr)\n\n\tfor len(hexStr) > 0 && int64val >= maxint64 || int64val <= minint64 {\n\t\thexStr = hexStr[:len(hexStr)-1]\n\t\tint64val = hex2int(hexStr)\n\t}\n\treturn int64val\n}",
"func Sha3256(bs []byte) ([]byte, error) {\n\treturn PerformHash(sha3.New256(), bs)\n}",
"func NewAvx512(a512srv *Avx512Server) hash.Hash {\n\tuid := atomic.AddUint64(&uidCounter, 1)\n\treturn &Avx512Digest{uid: uid, a512srv: a512srv}\n}",
"func PasswordMatchesHash(hashedPassword []byte, password string) (bool, error) {\n\n\tif len(password) == 0 { return false, NewStackError(\"You must pass in a non-empty password\") }\n\n\tif len(hashedPassword) == 0 { return false, NewStackError(\"You must pass in a non-empty hashed password\") }\n\n\terr := bcrypt.CompareHashAndPassword(hashedPassword, []byte(password))\n\treturn err == nil, nil\n}",
"func ValidateSignature(r *http.Request, secret []byte) (bool, error) {\n\tbody, err := ReadBodyRequest(r)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"read body: %w\", err)\n\t}\n\n\tr.Body = io.NopCloser(bytes.NewBuffer(body))\n\n\tif fmt.Sprintf(\"SHA-512=%x\", sha512.Sum512(body)) != r.Header.Get(\"Digest\") {\n\t\treturn false, model.WrapInvalid(errors.New(\"SHA-512 signature of body doesn't match\"))\n\t}\n\n\tsignatureString, signature, err := parseAuthorizationHeader(r)\n\tif err != nil {\n\t\treturn false, model.WrapInvalid(fmt.Errorf(\"parse authorization header: %w\", err))\n\t}\n\n\treturn hmac.Equal(signContent(secret, signatureString), signature), nil\n}",
"func VerifyShaHashedPassword(password, hashedPassword, saltPassword string) bool {\n\treturn HashPassword(password, saltPassword) == hashedPassword\n}",
"func (blk Block) ValidHash() bool {\n\t// TODO\n\n\thash := blk.Hash\n\n\tif hash == nil {\n\t\treturn false\n\t}\n\n\tl := len(hash)\n\n\tnBytes := int(blk.Difficulty / 8)\n\tnBits := blk.Difficulty % 8\n\n\tfor i := l - 1; i >= l-nBytes; i-- {\n\t\tif hash[i] != '\\x00' {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif hash[l-nBytes-1]%(1<<nBits) != 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}",
"func Sha1Check(hashed, pwd string) bool {\n\thashed = Base64Decode(hashed)\n\tif len(hashed) < 4 {\n\t\treturn false\n\t}\n\n\tsalt := hashed[len(hashed)-4:]\n\treturn Sha1(Md5(pwd)+salt)+salt == hashed\n}",
"func NewFzSha512() *FzSha512 {\n\treturn (*FzSha512)(allocFzSha512Memory(1))\n}",
"func Valid(input string) bool {\n\tstrippedString := strings.Replace(input, \" \", \"\", -1)\n\tsum := checksum(strippedString)\n\tif len(strippedString) < 2 {\n\t\treturn false\n\t}\n\treturn (sum % 10) == 0\n}",
"func IsSHA1(str string) bool {\n\treturn IsHash(str, \"sha1\")\n}",
"func Check(hashed, pwd string) bool {\n\thashed = Base64Decode(hashed)\n\tif len(hashed) < 4 {\n\t\treturn false\n\t}\n\n\tsalt := hashed[len(hashed)-4:]\n\treturn Sha256(Md5(pwd)+salt)+salt == hashed\n}",
"func hashLen(u uint64, hashLog, mls uint8) uint32 {\n\tswitch mls {\n\tcase 5:\n\t\treturn hash5(u, hashLog)\n\tcase 6:\n\t\treturn hash6(u, hashLog)\n\tcase 7:\n\t\treturn hash7(u, hashLog)\n\tcase 8:\n\t\treturn hash8(u, hashLog)\n\tdefault:\n\t\treturn hash4x64(u, hashLog)\n\t}\n}",
"func Valid(password string, hashedPassword string) (valid bool,\n\tinsecure bool, err error) {\n\n\tif strings.HasPrefix(hashedPassword, \"$2a$\") {\n\t\tinsecure = false\n\t\tvalid, err = validBCRYPT(password, hashedPassword)\n\t\treturn\n\t}\n\n\tinsecure = true\n\tswitch {\n\tcase strings.HasPrefix(hashedPassword, \"{MD5}\"):\n\t\tvalid, err = validMD5(password, hashedPassword)\n\t\treturn\n\tcase strings.HasPrefix(hashedPassword, \"{SHA}\"):\n\t\tvalid, err = validSHA1(password, hashedPassword)\n\t\treturn\n\tcase strings.HasPrefix(hashedPassword, \"{SSHA}\"):\n\t\tvalid, err = validSSHA(password, hashedPassword)\n\t\treturn\n\tdefault:\n\t\treturn false, false, merry.New(\"could not identify password hash type\")\n\t}\n}",
"func isServerGzipMinLengthDirective(directive string) bool {\n\tif isEqualString(directive, ServerGzipMinLengthDirective) {\n\t\treturn true\n\t}\n\treturn false\n}",
"func comparePassword(hash, pw []byte) bool {\n\treturn bytes.Equal(hash, hashPassword(pw, hash[:saltSize]))\n}",
"func expandHash(data []byte) []byte {\n\tpart0 := sha512.Sum512(append(data, 0))\n\tpart1 := sha512.Sum512(append(data, 1))\n\tpart2 := sha512.Sum512(append(data, 2))\n\tpart3 := sha512.Sum512(append(data, 3))\n\treturn bytes.Join([][]byte{\n\t\tpart0[:],\n\t\tpart1[:],\n\t\tpart2[:],\n\t\tpart3[:],\n\t}, []byte{})\n}",
"func IsSHA384(str string) bool {\n\treturn IsHash(str, \"sha384\")\n}",
"func testLenHash(b []byte) uint {\n\treturn uint(len(b))\n}",
"func Hash(data []byte) [blake2b.Size]byte {\n\treturn blake2b.Sum512(data)\n}",
"func (d *digest) Size() int { return crc64.Size }",
"func isServerTypesHashBucketSizeDirective(directive string) bool {\n\tif isEqualString(directive, ServerTypesHashBucketSizeDirective) {\n\t\treturn true\n\t}\n\treturn false\n}",
"func (e *sha512Encryptor) Hash(password []byte) []byte {\n\te.hashFn.Reset()\n\te.hashFn.Write(password)\n\treturn e.hashFn.Sum(nil)\n}",
"func verifyChecksum(in uint8, cmd uint8, dataLen uint8, data []byte) bool {\n\n\treturn in == calculateChecksum(cmd, dataLen, data)\n}",
"func hash(password string) string {\n\thash := sha512.New()\n\thash.Write([]byte(password))\n\tb := hash.Sum(nil)\n\treturn base64.StdEncoding.EncodeToString(b)\n}",
"func PutBytesBuffer512K(b *bytes.Buffer) bool {\n\tif b == nil {\n\t\treturn false\n\t}\n\tif l := b.Cap(); l < 524288 || l >= 1048576 {\n\t\treturn PutBytesBuffer(b)\n\t}\n\tb.Reset()\n\tputb512K(b)\n\treturn true\n}",
"func PutBytesSlicePtr512(p *[]byte) bool {\n\tif p == nil {\n\t\treturn false\n\t}\n\tif l := cap(*p); l < 512 || l >= 1024 {\n\t\treturn PutBytesSlicePtr(p)\n\t}\n\t*p = (*p)[0:512]\n\tput512(p)\n\treturn true\n}",
"func isSHA256(fl FieldLevel) bool {\n\treturn sha256Regex.MatchString(fl.Field().String())\n}",
"func HashesMatch(providedHash, challenge string) bool {\n\tcomputedChallenge := ComputeChallenge(challenge)\n\tresult := computedChallenge == providedHash\n\treturn result\n}",
"func PutBytesSlice512K(p []byte) bool {\n\tif l := cap(p); l < 524288 || l >= 1048576 {\n\t\treturn PutBytesSlice(p)\n\t}\n\tp = p[0:524288]\n\tput512K(internal.Gets(p))\n\treturn true\n}",
"func CheckHash(data []byte, target [blake2b.Size]byte) bool {\n\tif Hash(data) == target {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}",
"func isServerProxyHeadersHashMaxSizeDirective(directive string) bool {\n\tif isEqualString(directive, ServerProxyHeadersHashMaxSizeDirective) {\n\t\treturn true\n\t}\n\treturn false\n}",
"func hashLen(u uint64, length, mls uint8) uint32 {\n\tswitch mls {\n\tcase 3:\n\t\treturn (uint32(u<<8) * prime3bytes) >> (32 - length)\n\tcase 5:\n\t\treturn uint32(((u << (64 - 40)) * prime5bytes) >> (64 - length))\n\tcase 6:\n\t\treturn uint32(((u << (64 - 48)) * prime6bytes) >> (64 - length))\n\tcase 7:\n\t\treturn uint32(((u << (64 - 56)) * prime7bytes) >> (64 - length))\n\tcase 8:\n\t\treturn uint32((u * prime8bytes) >> (64 - length))\n\tdefault:\n\t\treturn (uint32(u) * prime4bytes) >> (32 - length)\n\t}\n}",
"func CheckPasswordHash(password, hash string) bool {\n\treturn true\n}"
] | [
"0.79532444",
"0.74527377",
"0.6559105",
"0.6552208",
"0.64293355",
"0.6401247",
"0.6335104",
"0.632823",
"0.6273769",
"0.62705004",
"0.6251818",
"0.62249917",
"0.61148924",
"0.60441554",
"0.6012789",
"0.60074663",
"0.5912162",
"0.58050203",
"0.5766438",
"0.5550642",
"0.5534905",
"0.55075437",
"0.54892826",
"0.54882455",
"0.54852057",
"0.53798145",
"0.5378258",
"0.5372583",
"0.5370655",
"0.53672695",
"0.5359578",
"0.53099895",
"0.5263321",
"0.52429825",
"0.5222444",
"0.5196569",
"0.5193902",
"0.51892006",
"0.51823866",
"0.51518583",
"0.5149591",
"0.51468307",
"0.51461864",
"0.5144609",
"0.5143599",
"0.51207536",
"0.50862944",
"0.50568634",
"0.5052987",
"0.5033206",
"0.5033206",
"0.5033206",
"0.50331295",
"0.5025473",
"0.501737",
"0.49929696",
"0.49771148",
"0.4974908",
"0.49422038",
"0.4940272",
"0.49224377",
"0.49209556",
"0.48985565",
"0.48968676",
"0.48926085",
"0.48853812",
"0.48804945",
"0.48775432",
"0.48749876",
"0.48662645",
"0.48634183",
"0.4857294",
"0.48537362",
"0.48489156",
"0.4844501",
"0.48338863",
"0.48324737",
"0.4824238",
"0.48231348",
"0.4819821",
"0.48108977",
"0.48074904",
"0.48036686",
"0.47960436",
"0.47903153",
"0.47886246",
"0.47875068",
"0.4779289",
"0.47695592",
"0.47628653",
"0.47502163",
"0.47475272",
"0.47396317",
"0.47375402",
"0.47196385",
"0.47134498",
"0.47112858",
"0.47019216",
"0.47005042",
"0.4698845"
] | 0.87895745 | 0 |
Match determines whether an Instance matches a field and label selector. | func Match(label labels.Selector, field fields.Selector) storage.SelectionPredicate {
return storage.SelectionPredicate{
Label: label,
Field: field,
GetAttrs: GetAttrs,
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func Matcher(label labels.Selector, field fields.Selector) apistorage.SelectionPredicate {\n\treturn apistorage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t}\n}",
"func (m StructMatcher) Match(got reflect.Value, d data.Data, r Region) (data.Data, bool) {\n\tif m.Type != got.Type() {\n\t\treturn d, false\n\t}\n\tfor i, f := range m.Fields {\n\t\tvar ok bool\n\t\td, ok = f.Match(got.Field(i), d, r)\n\t\tif !ok {\n\t\t\treturn d, false\n\t\t}\n\t}\n\treturn d, true\n}",
"func (vb *Builder) Match(fieldName string, str1, str2 interface{}) {\n\tif str1 != str2 {\n\t\tvb.Append(fieldName, doesNotMatch)\n\t}\n}",
"func (m fieldMatcher) Matches(x interface{}) bool {\n\tval := reflect.ValueOf(x)\n\tfor i := 0; i < val.NumField(); i++ {\n\t\tfield := val.Type().Field(i)\n\t\tif field.Name == m.Key {\n\t\t\tif reflect.DeepEqual(getValue(val.Field(i)), m.Value) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}",
"func shouldSelectInstance(selector, instanceLabels map[string]string) bool {\n\tif len(instanceLabels) == 0 {\n\t\t// only an empty selector can match empty labels\n\t\treturn len(selector) == 0\n\t}\n\n\tfor k, v := range selector {\n\t\tinstanceVal, ok := instanceLabels[k]\n\t\tif !ok {\n\t\t\t// the selector key is missing from the instance labels\n\t\t\treturn false\n\t\t}\n\t\tif v != instanceVal {\n\t\t\t// the label value in the selector does not match\n\t\t\t// the label value from the instance\n\t\t\treturn false\n\t\t}\n\t}\n\t// we didn't catch a mismatch by now, they match\n\treturn true\n}",
"func (s Selector) Match(n *Node) bool {\n\treturn s(n)\n}",
"func Matcher(label labels.Selector, field fields.Selector) pkgstorage.SelectionPredicate {\n\treturn pkgstorage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t}\n}",
"func (s inputPseudoClassSelector) Match(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && (n.Data == \"input\" || n.Data == \"select\" || n.Data == \"textarea\" || n.Data == \"button\")\n}",
"func (s *Selector) Matches(l Labels) bool {\n\tif len(s.Requirements) == 0 {\n\t\treturn false\n\t}\n\tfor ii := range s.Requirements {\n\t\tif matches := s.Requirements[ii].Matches(l); !matches {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}",
"func (s Selector) Match(n *html.Node) bool {\n\treturn s(n)\n}",
"func Matcher(label labels.Selector, field fields.Selector) generic.Matcher {\n\treturn &generic.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: func(obj runtime.Object) (labels.Set, fields.Set, error) {\n\t\t\tsb, ok := obj.(*api.ServiceBroker)\n\t\t\tif !ok {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"not a servicebroker\")\n\t\t\t}\n\t\t\treturn labels.Set(sb.ObjectMeta.Labels), api.ServiceBrokerToSelectableFields(sb), nil\n\t\t},\n\t}\n}",
"func (s internalSelector) Matches(l Labels) bool {\n\tfor ix := range s {\n\t\tif matches := s[ix].Matches(l); !matches {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}",
"func (cont *Container) MatchField(name string, filters ...fl.Filter) bool {\n\tswitch name {\n\tcase \"Name\":\n\t\tfor _, filter := range filters {\n\t\t\tif fl.MatchString(cont.Name, filter) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\tcase \"Create\":\n\t\tfor _, filter := range filters {\n\t\t\tif fl.MatchTime(time.Unix(0, cont.Create), filter) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\n\tcase \"Start\":\n\t\tfor _, filter := range filters {\n\t\t\tif fl.MatchTime(time.Unix(0, cont.Start), filter) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\tcase \"Stop\":\n\t\tfor _, filter := range filters {\n\t\t\tif fl.MatchTime(time.Unix(0, cont.Stop), filter) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\tcase \"Destroy\":\n\t\tfor _, filter := range filters {\n\t\t\tif fl.MatchTime(time.Unix(0, cont.Destroy), filter) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\tcase \"CPUShares\":\n\t\tfor _, filter := range filters {\n\t\t\tif fl.MatchInt64(cont.CPUShares, filter) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\tcase \"Memory\":\n\t\tfor _, filter := range filters {\n\t\t\tif fl.MatchInt64(cont.Memory, filter) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\n\tdefault:\n\t\tfor _, filter := range filters {\n\t\t\tif cont.MatchLabel(name, filter) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n}",
"func (t Term) Match(args ...interface{}) Term {\n\treturn constructMethodTerm(t, \"Match\", p.Term_MATCH, args, map[string]interface{}{})\n}",
"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 (t *dataType) Match(r *regexp.Regexp) *dataType {\n\tt.str.Match(r)\n\treturn t\n}",
"func (t attrSelector) Match(n *html.Node) bool {\n\tswitch t.operation {\n\tcase \"\":\n\t\treturn matchAttribute(n, t.key, func(string) bool { return true })\n\tcase \"=\":\n\t\treturn matchAttribute(n, t.key, func(s string) bool { return s == t.val })\n\tcase \"!=\":\n\t\treturn attributeNotEqualMatch(t.key, t.val, n)\n\tcase \"~=\":\n\t\t// matches elements where the attribute named key is a whitespace-separated list that includes val.\n\t\treturn matchAttribute(n, t.key, func(s string) bool { return matchInclude(t.val, s) })\n\tcase \"|=\":\n\t\treturn attributeDashMatch(t.key, t.val, n)\n\tcase \"^=\":\n\t\treturn attributePrefixMatch(t.key, t.val, n)\n\tcase \"$=\":\n\t\treturn attributeSuffixMatch(t.key, t.val, n)\n\tcase \"*=\":\n\t\treturn attributeSubstringMatch(t.key, t.val, n)\n\tcase \"#=\":\n\t\treturn attributeRegexMatch(t.key, t.regexp, n)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unsuported operation : %s\", t.operation))\n\t}\n}",
"func (MatchedText) Matches(pattern string) bool { return boolResult }",
"func (t idSelector) Match(n *html.Node) bool {\n\treturn matchAttribute(n, \"id\", func(s string) bool {\n\t\treturn s == t.id\n\t})\n}",
"func (f *Filter) Match(res *benchfmt.Result) (Match, error) {\n\tm, x := f.match(res)\n\treturn Match{len(res.Values), m, x}, nil\n}",
"func Match(t TestingT, r, v interface{}, extras ...interface{}) bool {\n\treg, ok := tryMatch(r, v)\n\tif !ok {\n\t\t_, acts := toString(nil, v)\n\n\t\tErrorf(t, \"Expect to match regexp\", []labeledOutput{\n\t\t\t{\n\t\t\t\tlabel: labelMessages,\n\t\t\t\tcontent: formatExtras(extras...),\n\t\t\t},\n\t\t\t{\n\t\t\t\tlabel: \"-regexp\",\n\t\t\t\tcontent: fmt.Sprintf(\"%#v\", reg.String()),\n\t\t\t},\n\t\t\t{\n\t\t\t\tlabel: \"+value\",\n\t\t\t\tcontent: fmt.Sprintf(\"%#v\", acts),\n\t\t\t},\n\t\t})\n\t}\n\n\treturn ok\n}",
"func (at *AffinityTerm) Matches(pod *v1.Pod, nsLabels labels.Set) bool {\n\tif at.Namespaces.Has(pod.Namespace) || at.NamespaceSelector.Matches(nsLabels) {\n\t\treturn at.Selector.Matches(labels.Set(pod.Labels))\n\t}\n\treturn false\n}",
"func (s SelectorGroup) Match(n *html.Node) bool {\n\tfor _, sel := range s {\n\t\tif sel.Match(n) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}",
"func (m scanOpMatcher) Matches(x interface{}) bool {\n\top, ok := x.(*ScanOp)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tfor _, field := range op.fieldsToRead {\n\t\tif !m.fields[field] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn op.limit == m.limit && op.token == m.token && reflect.TypeOf(op.object).Elem() == m.typ\n}",
"func (m ValueMatcher) Match(got reflect.Value, d data.Data, _ Region) (data.Data, bool) {\n\tif m.Type != got.Type() {\n\t\treturn d, false\n\t}\n\treturn d, m.Value == got.Interface()\n}",
"func (t classSelector) Match(n *html.Node) bool {\n\treturn matchAttribute(n, \"class\", func(s string) bool {\n\t\treturn matchInclude(t.class, s)\n\t})\n}",
"func metricMatches(m model.Metric, selector labels.Selector) bool {\n\tvar labelStrings []string\n\tfor key, value := range m {\n\t\tlabelStrings = append(labelStrings, string(key), string(value))\n\t}\n\n\treturn selector.Matches(labels.FromStrings(labelStrings...))\n}",
"func (m Matcher) Match(pattern string, alternatives ...string) Matcher {\n\treturn m\n}",
"func (m InterfaceMatcher) Match(got reflect.Value, d data.Data, r Region) (data.Data, bool) {\n\tif got.Kind() != reflect.Interface || got.IsNil() {\n\t\treturn d, false\n\t}\n\treturn m.Matcher.Match(got.Elem(), d, r)\n}",
"func matchLabelForLabelSelector(targetLabels map[string]string, labelSelector *metav1.LabelSelector) bool {\n\tvar err error\n\tvar selector = labels.Everything()\n\n\tif labelSelector != nil {\n\t\tselector, err = metav1.LabelSelectorAsSelector(labelSelector)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif selector.Matches(labels.Set(targetLabels)) {\n\t\treturn true\n\t}\n\treturn false\n}",
"func (mf *ElementFilter) Match(g common.Getter) bool {\n\treturn mf.filter.Eval(g)\n}",
"func (m *Matcher) Match(actual interface{}) (success bool, err error) {\n\t// Nil checks required first here for:\n\t// 1) Nil equality which returns true\n\t// 2) One object nil which returns an error\n\n\tif util.IsNil(actual) && util.IsNil(m.original) {\n\t\treturn true, nil\n\t}\n\tif util.IsNil(actual) || util.IsNil(m.original) {\n\t\treturn false, fmt.Errorf(\"can not compare an object with a nil. original %v , actual %v\", m.original, actual)\n\t}\n\n\t// Calculate diff returns a json diff between the two objects.\n\tm.diff, err = m.calculateDiff(actual)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn bytes.Equal(m.diff, []byte(\"{}\")), nil\n}",
"func (pattern targetPattern) Match(object *metav1.ObjectMeta) bool {\n\treturn object.Name == pattern.name && pattern.namespace.MatchString(object.Namespace)\n}",
"func whereLabelMatches(label, pattern string, in interface{}) ([]interface{}, error) {\n\trx, err := regexp.Compile(pattern)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn whereLabel(\"whereLabelMatches\", in, label, func(value string, ok bool) bool {\n\t\treturn ok && rx.MatchString(value)\n\t})\n}",
"func (c *CompleterCustom) Match(ctx *Context, content IContent, line interface{}, index int) (int, bool) {\n\ttokens := line.([]string)\n\tif tokens[index] == content.GetLabel() {\n\t\treturn index + 1, true\n\t}\n\treturn index, false\n}",
"func (r *Instance) matcher(c *Client) func([]byte) bool {\n\treturn func(b []byte) bool {\n\t\tcr, err := unmarshalInstance(b, c)\n\t\tif err != nil {\n\t\t\tc.Config.Logger.Warning(\"failed to unmarshal provided resource in matcher.\")\n\t\t\treturn false\n\t\t}\n\t\tnr := r.urlNormalized()\n\t\tncr := cr.urlNormalized()\n\t\tc.Config.Logger.Infof(\"looking for %v\\nin %v\", nr, ncr)\n\n\t\tif nr.Project == nil && ncr.Project == nil {\n\t\t\tc.Config.Logger.Info(\"Both Project fields null - considering equal.\")\n\t\t} else if nr.Project == nil || ncr.Project == nil {\n\t\t\tc.Config.Logger.Info(\"Only one Project field is null - considering unequal.\")\n\t\t\treturn false\n\t\t} else if *nr.Project != *ncr.Project {\n\t\t\treturn false\n\t\t}\n\t\tif nr.Location == nil && ncr.Location == nil {\n\t\t\tc.Config.Logger.Info(\"Both Location fields null - considering equal.\")\n\t\t} else if nr.Location == nil || ncr.Location == nil {\n\t\t\tc.Config.Logger.Info(\"Only one Location field is null - considering unequal.\")\n\t\t\treturn false\n\t\t} else if *nr.Location != *ncr.Location {\n\t\t\treturn false\n\t\t}\n\t\tif nr.Name == nil && ncr.Name == nil {\n\t\t\tc.Config.Logger.Info(\"Both Name fields null - considering equal.\")\n\t\t} else if nr.Name == nil || ncr.Name == nil {\n\t\t\tc.Config.Logger.Info(\"Only one Name field is null - considering unequal.\")\n\t\t\treturn false\n\t\t} else if *nr.Name != *ncr.Name {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n}",
"func (t tagSelector) Match(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && n.Data == t.tag\n}",
"func (s *Plugin) Match(ctx context.Context, request *interact.Request, condition *v1alpha1.MockAPI_Condition) (match bool, err error) {\n\tsimple := condition.GetSimple()\n\tif simple == nil {\n\t\treturn false, nil\n\t}\n\tc := core.NewContext(request)\n\tfor _, item := range simple.Items {\n\t\toperandX := core.Render(c, item.OperandX)\n\t\toperandY := core.Render(c, item.OperandY)\n\t\tmatched, err := core.Match(operandX, item.Operator, operandY)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif item.Opposite {\n\t\t\tmatched = !matched\n\t\t}\n\t\tif matched {\n\t\t\tif simple.UseOrAmongItems {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tcontinue\n\t\t} else {\n\t\t\tif simple.UseOrAmongItems {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn true, nil\n}",
"func (ps *Segment) Match(s string) (name string, capture bool, wildcard bool, matches bool) {\n\tif ps.IsWildcard {\n\t\twildcard = true\n\t\tmatches = true\n\t\treturn\n\t}\n\tif ps.IsVariable {\n\t\tname = ps.Name\n\t\tcapture = true\n\t\tmatches = true\n\t\treturn\n\t}\n\tif strings.EqualFold(s, ps.Name) {\n\t\tmatches = true\n\t\treturn\n\t}\n\treturn\n}",
"func (b *Builder) Matches(re string) *predicate.Predicate {\n\tb.p.RegisterPredicate(impl.Matches(re))\n\tif b.t != nil {\n\t\tb.t.Helper()\n\t\tEvaluate(b)\n\t}\n\treturn &b.p\n}",
"func (nf *nlFilter) match(nl nl.Listener) bool {\n\tif nl.UUID() == nf.ID {\n\t\treturn true\n\t}\n\tif nf.Kind == \"\" || nl.Kind() == nf.Kind {\n\t\tif nf.Bck == nil || nf.Bck.IsEmpty() {\n\t\t\treturn true\n\t\t}\n\t\tfor _, bck := range nl.Bcks() {\n\t\t\tqbck := (*cmn.QueryBcks)(nf.Bck.Bucket())\n\t\t\tif qbck.Contains(bck) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}",
"func Match(m Matcher, data interface{}) error {\n\tif err := m.Match(data); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func Match(t Testing, reg, str interface{}, formatAndArgs ...interface{}) bool {\n\tif !tryMatch(reg, str) {\n\t\treturn Fail(t,\n\t\t\tfmt.Sprintf(\"Expect string(%s) to match regexp(%s)\", fmt.Sprint(str), fmt.Sprint(reg)),\n\t\t\tformatAndArgs...)\n\t}\n\n\treturn true\n}",
"func Matches(pattern string, operand string) (bool, error) {\n\treturn regexp.MatchString(pattern, operand)\n}",
"func (i Info) Matches(value string) bool {\n\tif strings.Contains(i.Name, value) {\n\t\treturn true\n\t}\n\tif strings.Contains(i.Zone, value) {\n\t\treturn true\n\t}\n\tif strings.Contains(i.AliasTarget, value) {\n\t\treturn true\n\t}\n\tfor _, v := range i.Values {\n\t\tif strings.Contains(v, value) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}",
"func matchesSelector(blockMeta *metadata.Meta, selectorLabels labels.Labels) bool {\n\tfor _, l := range selectorLabels {\n\t\tif v, ok := blockMeta.Thanos.Labels[l.Name]; !ok || (l.Value != \"*\" && v != l.Value) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}",
"func (f *StringField) Matches(re *regexp.Regexp) {\n\tmsg := \"The value of this field is invalid\"\n\tf.check(func() (err *FieldError) {\n\t\tif !re.MatchString(f.Value) {\n\t\t\terr = NewFieldError(INVALID, f.Name, msg)\n\t\t}\n\t\treturn\n\t})\n}",
"func MatchLabels(selector map[string]string, target map[string]string) bool {\n\t// empty selector matches nothing\n\tif len(selector) == 0 {\n\t\treturn false\n\t}\n\t// *: * matches everything even empty target set\n\tif selector[Wildcard] == Wildcard {\n\t\treturn true\n\t}\n\tfor key, val := range selector {\n\t\tif targetVal, ok := target[key]; !ok || (val != targetVal && val != Wildcard) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}",
"func (a *CompleterAny) Match(ctx *Context, content IContent, line interface{}, index int) (int, bool) {\n\ttokens := line.([]string)\n\tif tokens[index] == CR.GetLabel() {\n\t\treturn index, false\n\t}\n\treturn index + 1, true\n}",
"func MatchesSelector(installable interfaces.IInstallable, selector string) (bool, error) {\n\n\tlog.Logger.Tracef(\"Testing whether installable '%s' matches the selector '%s'\",\n\t\tinstallable.FullyQualifiedId(), selector)\n\n\tselectorParts := strings.Split(selector, constants.NamespaceSeparator)\n\tif len(selectorParts) != 2 {\n\t\treturn false, errors.New(fmt.Sprintf(\"Fully-qualified IDs must \"+\n\t\t\t\"be given, i.e. formatted 'manifest-id%skapp-id' or 'manifest-id%s%s' \"+\n\t\t\t\"for all kapps in a manifest\", constants.NamespaceSeparator,\n\t\t\tconstants.NamespaceSeparator, constants.WildcardCharacter))\n\t}\n\n\tselectorManifestId := selectorParts[0]\n\tselectorId := selectorParts[1]\n\n\tidParts := strings.Split(installable.FullyQualifiedId(), constants.NamespaceSeparator)\n\tif len(idParts) != 2 {\n\t\treturn false, errors.New(fmt.Sprintf(\"Fully-qualified kapp ID \"+\n\t\t\t\"has an unexpected format: %s\", installable.FullyQualifiedId()))\n\t}\n\n\tkappManifestId := idParts[0]\n\tkappId := idParts[1]\n\n\tif selectorManifestId == kappManifestId {\n\t\tif selectorId == constants.WildcardCharacter || selectorId == kappId {\n\t\t\tlog.Logger.Tracef(\"Installable '%s' did match the selector '%s'\", installable.FullyQualifiedId(), selector)\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\tlog.Logger.Tracef(\"Installable '%s' didn't match the selector '%s'\", installable.FullyQualifiedId(), selector)\n\treturn false, nil\n}",
"func (CWMatcher) Matches(cw interface{}) bool {\n\tif reflect.TypeOf(cw) == reflect.TypeOf(&ContentWrapper{}) {\n\t\treturn true\n\t}\n\treturn false\n}",
"func (a AnyArgument) Match(v driver.Value) bool {\n\treturn true\n}",
"func (a AnyArgument) Match(v driver.Value) bool {\n\treturn true\n}",
"func (a sqlMockTime) Match(v driver.Value) bool {\n\tvar secondValue time.Time\n\tswitch value := v.(type) {\n\tcase sqlMockTime:\n\t\tsecondValue = value.Time\n\tcase time.Time:\n\t\tsecondValue = value\n\tdefault:\n\t\treturn false\n\t}\n\treturn a.Time.Equal(secondValue)\n}",
"func (s onlyChildPseudoClassSelector) Match(n *html.Node) bool {\n\tif n.Type != html.ElementNode {\n\t\treturn false\n\t}\n\n\tparent := n.Parent\n\tif parent == nil {\n\t\treturn false\n\t}\n\n\tif parent.Type == html.DocumentNode {\n\t\treturn false\n\t}\n\n\tcount := 0\n\tfor c := parent.FirstChild; c != nil; c = c.NextSibling {\n\t\tif (c.Type != html.ElementNode) || (s.ofType && c.Data != n.Data) {\n\t\t\tcontinue\n\t\t}\n\t\tcount++\n\t\tif count > 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn count == 1\n}",
"func (e Entity) matches(ctx labels.LabelArray) bool {\n\treturn EntitySlice{e}.matches(ctx)\n}",
"func (m GenericNodeMatcher) Match(got reflect.Value, d data.Data, r Region) (data.Data, bool) {\n\t// Collapse the region under consideration down to the region covered by\n\t// this node.\n\tif !got.IsNil() {\n\t\tr = nodeRegion(got.Interface().(ast.Node))\n\t}\n\treturn m.Matcher.Match(got, d, r)\n}",
"func (m PtrMatcher) Match(got reflect.Value, d data.Data, r Region) (data.Data, bool) {\n\tif got.Kind() != reflect.Ptr || got.IsNil() {\n\t\treturn d, false\n\t}\n\treturn m.Matcher.Match(got.Elem(), d, r)\n}",
"func (kv BatchJobReplicateKV) Match(ikv BatchJobReplicateKV) bool {\n\tif kv.Empty() {\n\t\treturn true\n\t}\n\tif strings.EqualFold(kv.Key, ikv.Key) {\n\t\treturn wildcard.Match(kv.Value, ikv.Value)\n\t}\n\treturn false\n}",
"func (cc *CompleterCommand) Match(ctx *Context, content IContent, line interface{}, index int) (int, bool) {\n\ttokens := line.([]string)\n\tif tokens[index] == content.GetLabel() {\n\t\treturn index + 1, true\n\t}\n\treturn index, false\n}",
"func (a AnyTime) Match(v driver.Value) bool {\n\t_, ok := v.(time.Time)\n\treturn ok\n}",
"func (Any) IsMatch(ctx runtime.PatternContext) bool {\n\treturn true\n}",
"func (Any) IsMatch(ctx runtime.PatternContext) bool {\n\treturn true\n}",
"func (m IfMatcher) Match(r *http.Request) bool {\n\tif m.isOr {\n\t\treturn m.Or(r)\n\t}\n\treturn m.And(r)\n}",
"func (k *VRFKey) Match(srcIP net.IP, cidr *net.IPNet) bool {\n\treturn k.SourceIP.String() == srcIP.String() && k.DestCIDR.String() == cidr.String()\n}",
"func (t *StringDataType) Match(r *regexp.Regexp) *StringDataType {\n\treturn t.Validate(func(s string) error {\n\t\tif !r.MatchString(s) {\n\t\t\treturn fmt.Errorf(\"value does not match passed in regex %s\", r.String())\n\t\t}\n\t\treturn nil\n\t})\n}",
"func RegexMatch(pattern string) MatcherFunc {\n\treg := regexp.MustCompile(pattern)\n\n\treturn func(el Elem) bool {\n\t\treturn reg.MatchString(el.Name())\n\t}\n}",
"func (t compoundSelector) Match(n *html.Node) bool {\n\tif len(t.selectors) == 0 {\n\t\treturn n.Type == html.ElementNode\n\t}\n\n\tfor _, sel := range t.selectors {\n\t\tif !sel.Match(n) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}",
"func (r *Requirement) Matches(ls Labels) bool {\n\tswitch strings.ToLower(r.Operator) {\n\tcase strings.ToLower(Operator_equals.String()), strings.ToLower(Operator_in.String()):\n\t\tif !ls.Has(r.Key) {\n\t\t\treturn false\n\t\t}\n\t\treturn r.hasValue(ls.Get(r.Key))\n\tcase strings.ToLower(Operator_notEquals.String()), strings.ToLower(Operator_notIn.String()):\n\t\tif !ls.Has(r.Key) {\n\t\t\treturn false\n\t\t}\n\t\treturn !r.hasValue(ls.Get(r.Key))\n\tdefault:\n\t\treturn false\n\t}\n}",
"func (card Card) fieldsMatchByType(name, value string) (fields []Field) {\n name = strings.ToLower(name)\n value = strings.ToLower(value)\n for _, f := range card.Fields {\n if strings.ToLower(f.Type) == name &&\n strings.Contains(strings.ToLower(f.Value), value) {\n fields = append(fields, f)\n }\n }\n\n return\n}",
"func (a AnyPastTime) Match(v driver.Value) bool {\n\tstr, ok := v.(string)\n\tif !ok {\n\t\treturn false\n\t}\n\tt := types.Timestamp{}\n\tif err := t.Scan(str); err != nil {\n\t\treturn false\n\t}\n\treturn time.Since(t.Time()) < a.Range\n}",
"func (c *TimerCond) Match(t *TimerRecord) bool {\n\tif val, ok := c.ID.Get(); ok && t.ID != val {\n\t\treturn false\n\t}\n\n\tif val, ok := c.Namespace.Get(); ok && t.Namespace != val {\n\t\treturn false\n\t}\n\n\tif val, ok := c.Key.Get(); ok {\n\t\tif c.KeyPrefix && !strings.HasPrefix(t.Key, val) {\n\t\t\treturn false\n\t\t}\n\n\t\tif !c.KeyPrefix && t.Key != val {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}",
"func hasMatchingLabels(matchSelector metav1.LabelSelector, matchLabels map[string]string) bool {\n\t// This should never fail, validating webhook should catch this first\n\tselector, err := metav1.LabelSelectorAsSelector(&matchSelector)\n\tif err != nil {\n\t\treturn false\n\t}\n\t// If a nil or empty selector creeps in, it should match nothing, not everything.\n\tif selector.Empty() {\n\t\treturn false\n\t}\n\tif !selector.Matches(labels.Set(matchLabels)) {\n\t\treturn false\n\t}\n\treturn true\n}",
"func labelExactMatch(pr *gogithub.PullRequest, labelToFind string) bool {\n\tfor _, label := range pr.Labels {\n\t\tif *label.Name == labelToFind {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}",
"func (c *Command) Match(msg string) bool {\n\treturn c.Reg.MatchString(msg)\n}",
"func (m *matcher) Matches(x interface{}) bool {\n\td1 := m.StoredData\n\td2, ok := x.(*repo.StoredData)\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn d1.Data == d2.Data && d1.ID == d2.ID\n}",
"func (e Matcher_OnMatchValidationError) Field() string { return e.field }",
"func Matches(p v1.MatchTransformPattern, input any) (bool, error) {\n\tswitch p.Type {\n\tcase v1.MatchTransformPatternTypeLiteral:\n\t\treturn matchesLiteral(p, input)\n\tcase v1.MatchTransformPatternTypeRegexp:\n\t\treturn matchesRegexp(p, input)\n\t}\n\treturn false, errors.Errorf(errFmtMatchPatternTypeInvalid, string(p.Type))\n}",
"func (f field) match(value int) bool {\n\treturn f&(1<<uint64(value)) != 0\n}",
"func (s Selection) Match(msg Event) (bool, bool) {\n\tfor _, v := range s.N {\n\t\tval, ok := msg.Select(v.Key)\n\t\tif !ok {\n\t\t\treturn false, false\n\t\t}\n\t\tswitch vt := val.(type) {\n\t\tcase float64:\n\t\t\t// JSON numbers are all by spec float64 values\n\t\t\tif !v.Pattern.NumMatch(int(vt)) {\n\t\t\t\treturn false, true\n\t\t\t}\n\t\tcase int:\n\t\t\t// JSON numbers are all by spec float64 values\n\t\t\tif !v.Pattern.NumMatch(vt) {\n\t\t\t\treturn false, true\n\t\t\t}\n\t\tcase int64:\n\t\t\t// JSON numbers are all by spec float64 values\n\t\t\tif !v.Pattern.NumMatch(int(vt)) {\n\t\t\t\treturn false, true\n\t\t\t}\n\t\tcase int32:\n\t\t\t// JSON numbers are all by spec float64 values\n\t\t\tif !v.Pattern.NumMatch(int(vt)) {\n\t\t\t\treturn false, true\n\t\t\t}\n\t\tcase uint:\n\t\t\t// JSON numbers are all by spec float64 values\n\t\t\tif !v.Pattern.NumMatch(int(vt)) {\n\t\t\t\treturn false, true\n\t\t\t}\n\t\tcase uint32:\n\t\t\t// JSON numbers are all by spec float64 values\n\t\t\tif !v.Pattern.NumMatch(int(vt)) {\n\t\t\t\treturn false, true\n\t\t\t}\n\t\tcase uint64:\n\t\t\t// JSON numbers are all by spec float64 values\n\t\t\tif !v.Pattern.NumMatch(int(vt)) {\n\t\t\t\treturn false, true\n\t\t\t}\n\t\t}\n\t}\n\tfor _, v := range s.S {\n\t\tval, ok := msg.Select(v.Key)\n\t\tif !ok {\n\t\t\treturn false, false\n\t\t}\n\t\tswitch vt := val.(type) {\n\t\tcase string:\n\t\t\tif !v.Pattern.StringMatch(vt) {\n\t\t\t\treturn false, true\n\t\t\t}\n\t\tcase float64:\n\t\t\t// TODO - tmp hack that also loses floating point accuracy\n\t\t\tif !v.Pattern.StringMatch(strconv.Itoa(int(vt))) {\n\t\t\t\treturn false, true\n\t\t\t}\n\t\tdefault:\n\t\t\ts.incrementMismatchCount()\n\t\t\treturn false, true\n\t\t}\n\t}\n\treturn true, true\n}",
"func Match(pattern string, target []byte) (bool, error) {\n\tr, err := Convert(pattern)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn r.Match(target), nil\n}",
"func Match(query *AddressBookQuery, ao *AddressObject) (matched bool, err error) {\n\tif query == nil {\n\t\treturn true, nil\n\t}\n\n\tswitch query.FilterTest {\n\tdefault:\n\t\treturn false, fmt.Errorf(\"unknown query filter test %q\", query.FilterTest)\n\n\tcase FilterAnyOf, \"\":\n\t\tfor _, prop := range query.PropFilters {\n\t\t\tok, err := matchPropFilter(prop, ao)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tif ok {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t\treturn false, nil\n\n\tcase FilterAllOf:\n\t\tfor _, prop := range query.PropFilters {\n\t\t\tok, err := matchPropFilter(prop, ao)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tif !ok {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t}\n}",
"func (m SliceMatcher) Match(got reflect.Value, d data.Data, r Region) (data.Data, bool) {\n\tif got.Kind() != reflect.Slice || len(m.Items) != got.Len() {\n\t\treturn d, false\n\t}\n\n\tfor i, im := range m.Items {\n\t\tvar ok bool\n\t\td, ok = im.Match(got.Index(i), d, r)\n\t\tif !ok {\n\t\t\treturn d, false\n\t\t}\n\t}\n\n\treturn d, true\n}",
"func (a *Arg) Match(arg string) bool {\n\tswitch {\n\tcase a.ShortName != \"\" && a.ShortName == arg:\n\t\treturn true\n\tcase a.LongName != \"\" && a.LongName == arg:\n\t\treturn true\n\t}\n\treturn false\n}",
"func (i *CompleterIdent) Match(ctx *Context, content IContent, line interface{}, index int) (int, bool) {\n\ttokens := line.([]string)\n\tif tokens[index] == i.GetLabel() {\n\t\treturn index + 1, true\n\t}\n\treturn index, false\n}",
"func TestMatching(t *testing.T) {\n\tassert := assert.New(t)\n\treplacementEntityMD := new(EntityDTO_ReplacementEntityMetaData)\n\treplacementEMB := &ReplacementEntityMetaDataBuilder{\n\t\tmetaData: replacementEntityMD,\n\t}\n\tpropStr := rand.String(6)\n\trEMB := replacementEMB.Matching(propStr)\n\tassert.Equal(propStr, rEMB.metaData.IdentifyingProp[0])\n\tassert.Equal(&propStr, &rEMB.metaData.IdentifyingProp[0])\n}",
"func (j *CompleterJoint) Match(ctx *Context, content IContent, line interface{}, index int) (int, bool) {\n\tif content == nil {\n\t\treturn index, true\n\t}\n\ttokens := line.([]string)\n\tif tokens[index] == content.GetLabel() {\n\t\treturn index + 1, true\n\t}\n\treturn index, true\n}",
"func Match(op aof.Operation, filter Filter, inverse bool) bool {\n\trCode := false\n\tif inverse {\n\t\trCode = true\n\t}\n\tif filter.Command != nil && filter.Command.FindStringIndex(strings.ToUpper(op.Command)) == nil {\n\t\treturn rCode\n\t}\n\tif filter.SubOp != nil && filter.SubOp.FindStringIndex(strings.ToUpper(op.SubOp)) == nil {\n\t\treturn rCode\n\t}\n\tif filter.Key != nil && filter.Key.FindStringIndex(op.Key) == nil {\n\t\treturn rCode\n\t}\n\tif filter.Parameter == nil {\n\t\treturn !rCode\n\t}\n\tfor _, p := range op.Arguments {\n\t\tif filter.Parameter.FindStringIndex(p) != nil {\n\t\t\treturn !rCode\n\t\t}\n\t}\n\treturn rCode\n}",
"func (a ApplyTo) Matches(gvk schema.GroupVersionKind) bool {\n\tif !contains(a.Groups, gvk.Group) {\n\t\treturn false\n\t}\n\tif !contains(a.Versions, gvk.Version) {\n\t\treturn false\n\t}\n\tif !contains(a.Kinds, gvk.Kind) {\n\t\treturn false\n\t}\n\n\treturn true\n}",
"func (s internalSelector) RequiresExactMatch(label string) (value string, found bool) {\n\tfor ix := range s {\n\t\tif s[ix].key == label {\n\t\t\tswitch s[ix].operator {\n\t\t\tcase selection.Equals, selection.DoubleEquals, selection.In:\n\t\t\t\tif len(s[ix].strValues) == 1 {\n\t\t\t\t\treturn s[ix].strValues[0], true\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn \"\", false\n\t\t}\n\t}\n\treturn \"\", false\n}",
"func (m *MetricDeclaration) Matches(metric *pdata.Metric) bool {\n\tfor _, regex := range m.metricRegexList {\n\t\tif regex.MatchString(metric.Name()) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}",
"func (inv *Inventory) matchInstances(patterns ...string) ([]string, error) {\n\trows := make([][]string, 0, len(inv.Instances))\n\tfor name, cfg := range inv.Instances {\n\t\trow := make([]string, 2+len(cfg.Tags))\n\t\trow[0] = name\n\t\trow[1] = cfg.System\n\t\tcopy(row[2:], cfg.Tags)\n\t\trows = append(rows, row)\n\t}\n\treturn matchPatterns(patterns, rows...)\n}",
"func Match(regx string, arg string) bool {\n\tmatched, err := regexp.MatchString(\"^(\"+regx+\")$\", arg)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn matched\n}",
"func (m EqualsMatcher) Match(s string) bool {\n\tfor _, term := range m.list {\n\t\tif term == s {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}",
"func (m *MatcherFunc) Match(r *Request) bool {\n\treturn m.Func(r)\n}",
"func (q *Query) Match(indexName string, param interface{}) *Query {\n\t// For a single parameter 'exact match' search, it is non sensical to pass nil\n\t// Set the error and return the query unchanged\n\tif param == nil {\n\t\tq.err = errors.New(ErrNilInputMatchIndexQuery)\n\t\treturn q\n\t}\n\n\t// If we are matching a string, lower-case it\n\tswitch param.(type) {\n\tcase string:\n\t\tparam = strings.ToLower(param.(string))\n\t}\n\n\tq.start = param\n\tq.end = param\n\tq.isIndexQuery = true\n\tq.indexName = []byte(strings.ToLower(indexName))\n\treturn q\n}",
"func (m RegexpMatcher) Match(s string) bool {\n\treturn m.re.MatchString(s)\n}",
"func MatchCluster(label labels.Selector, field fields.Selector) storage.SelectionPredicate {\n\treturn storage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t}\n}",
"func (h *Beer) Match(_, msg string) bool {\n\tre := regexp.MustCompile(h.Re())\n\treturn re.MatchString(msg)\n}",
"func Match(filter *datastore.Filter, message descriptor.Message) bool {\n\tif filter != nil {\n\t\tswitch filter.FilterType.(type) {\n\t\tcase *datastore.Filter_PropertyFilter:\n\t\t\timpl := filter.GetPropertyFilter()\n\t\t\tproperty := impl.GetProperty()\n\t\t\tif property == nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tvalue := impl.GetValue()\n\t\t\tif value == nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn compare(message, property.Name, impl.GetOp(), *value)\n\t\tcase *datastore.Filter_CompositeFilter:\n\t\t\tfilters := filter.GetCompositeFilter().GetFilters()\n\t\t\tmatched := len(filters) > 0\n\t\t\tfor _, filter := range filters {\n\t\t\t\tmatched = matched && Match(filter, message)\n\t\t\t}\n\t\t\treturn matched\n\t\t}\n\t}\n\t// no filter: match everything\n\treturn true\n}"
] | [
"0.632903",
"0.6183046",
"0.6145482",
"0.60348094",
"0.6022036",
"0.6001453",
"0.5987963",
"0.59004235",
"0.5861921",
"0.5819812",
"0.5819247",
"0.5764969",
"0.57329255",
"0.5693797",
"0.56565136",
"0.55746704",
"0.5573523",
"0.557265",
"0.5564328",
"0.55546397",
"0.553474",
"0.5465109",
"0.5446412",
"0.5418231",
"0.54046834",
"0.5393091",
"0.5346466",
"0.5335702",
"0.5332222",
"0.5292165",
"0.52749443",
"0.525146",
"0.524747",
"0.5244551",
"0.5228008",
"0.52183723",
"0.5217993",
"0.52130693",
"0.51938355",
"0.5188245",
"0.5179277",
"0.51717716",
"0.5169919",
"0.51510364",
"0.5139817",
"0.5134295",
"0.5121011",
"0.5117719",
"0.5110495",
"0.51086456",
"0.5096803",
"0.5095054",
"0.5095054",
"0.50784063",
"0.5077735",
"0.50644183",
"0.50603086",
"0.50582695",
"0.50498027",
"0.50227726",
"0.50213104",
"0.50073576",
"0.50073576",
"0.50011486",
"0.49860087",
"0.49738228",
"0.4973309",
"0.49684775",
"0.4961033",
"0.4953716",
"0.49524835",
"0.49503458",
"0.4939387",
"0.49259597",
"0.4919286",
"0.491288",
"0.4899588",
"0.48937783",
"0.48930004",
"0.48901528",
"0.4882403",
"0.48721796",
"0.4862083",
"0.48555288",
"0.48554778",
"0.48273635",
"0.4821326",
"0.48064628",
"0.48016012",
"0.480125",
"0.47898442",
"0.47893608",
"0.47889334",
"0.47875232",
"0.47850487",
"0.47847468",
"0.4777632",
"0.47724003",
"0.4771849",
"0.477173"
] | 0.7476873 | 0 |
ToSelectableFields returns a field set that represents the object for matching purposes. | func ToSelectableFields(serviceClass *servicecatalog.ServiceClass) fields.Set {
objectMetaFieldsSet := generic.ObjectMetaFieldsSet(&serviceClass.ObjectMeta, true)
return generic.MergeFieldsSets(objectMetaFieldsSet, nil)
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func RoleToSelectableFields(role *Role) fields.Set {\n\treturn fields.Set{\n\t\t\"metadata.name\": role.Name,\n\t\t\"metadata.namespace\": role.Namespace,\n\t}\n}",
"func SelectableFields(pip *settings.PodPreset) fields.Set {\n\treturn generic.ObjectMetaFieldsSet(&pip.ObjectMeta, true)\n}",
"func PolicyToSelectableFields(policy *Policy) fields.Set {\n\treturn fields.Set{\n\t\t\"metadata.name\": policy.Name,\n\t\t\"metadata.namespace\": policy.Namespace,\n\t}\n}",
"func SelectableFields(obj *v1alpha1.Cluster) fields.Set {\n\treturn generic.ObjectMetaFieldsSet(&obj.ObjectMeta, true)\n}",
"func SelectableFields(obj *api.Secret) fields.Set {\n\tobjectMetaFieldsSet := generic.ObjectMetaFieldsSet(&obj.ObjectMeta, true)\n\tsecretSpecificFieldsSet := fields.Set{\n\t\t\"type\": string(obj.Type),\n\t}\n\treturn generic.MergeFieldsSets(objectMetaFieldsSet, secretSpecificFieldsSet)\n}",
"func RoleBindingRestrictionToSelectableFields(rbr *RoleBindingRestriction) fields.Set {\n\treturn fields.Set{\n\t\t\"metadata.name\": rbr.Name,\n\t\t\"metadata.namespace\": rbr.Namespace,\n\t}\n}",
"func RoleBindingToSelectableFields(roleBinding *RoleBinding) fields.Set {\n\treturn fields.Set{\n\t\t\"metadata.name\": roleBinding.Name,\n\t\t\"metadata.namespace\": roleBinding.Namespace,\n\t}\n}",
"func PolicyToSelectableFields(policy *authorizationapi.Policy) labels.Set {\n\treturn labels.Set{\n\t\t\"metadata.name\": policy.Name,\n\t}\n}",
"func ClusterPolicyToSelectableFields(policy *ClusterPolicy) fields.Set {\n\treturn fields.Set{\n\t\t\"metadata.name\": policy.Name,\n\t}\n}",
"func PolicyBindingToSelectableFields(policyBinding *authorizationapi.PolicyBinding) labels.Set {\n\treturn labels.Set{\n\t\t\"metadata.name\": policyBinding.Name,\n\t}\n}",
"func ClusterPolicyToSelectableFields(clusterPolicy *authorizationapi.ClusterPolicy) labels.Set {\n\treturn labels.Set{\n\t\t\"metadata.name\": clusterPolicy.Name,\n\t}\n}",
"func PolicyBindingToSelectableFields(policyBinding *PolicyBinding) fields.Set {\n\treturn fields.Set{\n\t\t\"metadata.name\": policyBinding.Name,\n\t\t\"metadata.namespace\": policyBinding.Namespace,\n\t\t\"policyRef.namespace\": policyBinding.PolicyRef.Namespace,\n\t}\n}",
"func ClusterPolicyBindingToSelectableFields(policyBinding *ClusterPolicyBinding) fields.Set {\n\treturn fields.Set{\n\t\t\"metadata.name\": policyBinding.Name,\n\t}\n}",
"func ClusterPolicyBindingToSelectableFields(clusterPolicyBinding *authorizationapi.ClusterPolicyBinding) labels.Set {\n\treturn labels.Set{\n\t\t\"metadata.name\": clusterPolicyBinding.Name,\n\t}\n}",
"func ImageRepositoryToSelectableFields(ir *api.ImageRepository) labels.Set {\n\treturn labels.Set{\n\t\t\"name\": ir.Name,\n\t\t\"dockerImageRepository\": ir.DockerImageRepository,\n\t\t\"status.dockerImageRepository\": ir.Status.DockerImageRepository,\n\t}\n}",
"func (m *RawMapper) Fields() []string { return append(m.selectFields, m.selectTags...) }",
"func (f *Fields) Slice() []*Field",
"func GetSelectedFields(selectionPath []string, query string) []string {\n\t// (?s) - multiline search, .+? not greedy search\n\tvar regexpStr = `(?s)` + strings.Join(selectionPath, `.+?`)\n\n\tvar ss = selectionAfter(regexpStr, query)\n\tif ss == \"\" {\n\t\treturn []string{}\n\t}\n\n\t// remove all ()\n\tfor o := outsideBrackets(\"()\", ss); o != ss; o = outsideBrackets(\"()\", ss) {\n\t\tss = o\n\t}\n\t// remove all {}\n\tfor o := outsideBrackets(\"{}\", ss); o != ss; o = outsideBrackets(\"{}\", ss) {\n\t\tss = o\n\t}\n\tss = removeSpaces(ss)\n\treturn strings.Split(ss, \" \")\n}",
"func (t *Type) FieldSlice() []*Field",
"func (cpy *impl) CopyFromField(\n\t_ reflect.Type,\n\tfromT reflect.Type,\n\tdst reflect.Value,\n\tsrc reflect.Value,\n\tselected []string,\n\tomit []string,\n\tfilter FilterFn,\n) (err error) {\n\tconst paramName = `name`\n\tvar (\n\t\tfromF reflect.Value\n\t\tfield reflect.StructField\n\t\tsrcName, dstName string\n\t)\n\n\t// Copy from field or method to field\n\tfor _, field = range cpy.Fields(fromT) {\n\t\tsrcName = field.Name\n\t\tif dstName = cpy.FieldReplaceName(field, paramName); dstName == \"\" {\n\t\t\tdstName = srcName\n\t\t}\n\t\tif cpy.IsSkip(selected, omit, srcName, dstName) {\n\t\t\tcontinue\n\t\t}\n\t\tfromF = src.FieldByName(srcName)\n\t\tif fromF.IsValid() {\n\t\t\terr = cpy.SetToFieldOrMethod(dst, dstName, fromF, srcName, selected, omit, filter)\n\t\t}\n\t}\n\n\treturn\n}",
"func (tm *TableModel) FormFields() A.MSX {\n\tcache := FORM_CACHE.Get(tm.CacheName)\n\tjson_arr, ok := cache.(A.MSX)\n\tif !ok {\n\t\tjson_arr = A.MSX{}\n\t\tfor _, field := range tm.Fields {\n\t\t\tswitch field.Key {\n\t\t\tcase `id`, `is_deleted`, `modified_at`, `unique_id`, `created_at`, `updated_at`, `deleted_at`, `restored_at`:\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif field.Hide || field.HtmlHide || field.FormHide {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tjson_obj := M.SX{\n\t\t\t\t`key`: field.Key,\n\t\t\t\t`label`: S.Coalesce(field.FormLabel, field.HtmlLabel, field.Label),\n\t\t\t\t`type`: S.Coalesce(field.FormType, field.HtmlLabel, field.Type),\n\t\t\t\t`tooltip`: S.Coalesce(field.FormTooltip, field.FormLabel, field.HtmlLabel, field.Label),\n\t\t\t}\n\t\t\tif field.Required {\n\t\t\t\tjson_obj[`required`] = true\n\t\t\t}\n\t\t\tif field.HtmlSubType != `` {\n\t\t\t\tjson_obj[`sub_type`] = field.HtmlSubType\n\t\t\t}\n\t\t\tjson_arr = append(json_arr, json_obj)\n\t\t\tif DEBUG {\n\t\t\t\tL.Print(`Creating FORM_CACHE.Select`, tm.CacheName)\n\t\t\t}\n\t\t}\n\t\tFORM_CACHE.Set(tm.CacheName, json_arr)\n\t}\n\treturn json_arr\n}",
"func FindAllSpecificFields(s Session, dbname string, collection string, query, fields map[string]interface{}) ([]interface{}, error) {\n\tvar object []interface{}\n\tif err := s.DB(dbname).C(collection).Find(query).Select(fields).All(&object); err != nil {\n\t\treturn object, err\n\t}\n\treturn object, nil\n}",
"func (builder QueryBuilder) Fields(predicates ...interface{}) QueryBuilder {\n\treturn builder.Select(predicates...)\n}",
"func (cpy *impl) SetToFieldOrMethod(\n\tdst reflect.Value,\n\tdstName string,\n\tfrom reflect.Value,\n\t_ string,\n\tselected []string,\n\tomit []string,\n\tfilter FilterFn,\n) (err error) {\n\tconst paramName = `name`\n\tvar (\n\t\ttoF, toM reflect.Value\n\t\tfield reflect.StructField\n\t\tvalues []reflect.Value\n\t\tname string\n\t)\n\n\t// By field name\n\ttoF = dst.FieldByName(dstName)\n\t// Search by tag name\n\tif !toF.IsValid() {\n\t\tfor _, field = range cpy.Fields(dst.Type()) {\n\t\t\tif name = field.Name; cpy.FieldReplaceName(field, paramName) == dstName {\n\t\t\t\ttoF = dst.FieldByName(name)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\t// Если field\n\tif toF.IsValid() {\n\t\t// Try to can set\n\t\tif toF.CanSet() {\n\t\t\tif !cpy.Set(toF, from) {\n\t\t\t\tif from.Kind() == reflect.Func &&\n\t\t\t\t\tfrom.Type().NumIn() == 0 &&\n\t\t\t\t\tfrom.Type().NumOut() >= 1 {\n\t\t\t\t\tif values = from.Call([]reflect.Value{}); len(values) > 0 {\n\t\t\t\t\t\tcpy.Set(toF, values[0])\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\terr = cpy.Copy(toF.Addr().Interface(), from.Interface(), selected, omit, filter)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Try to set call method\n\t\ttoM = dst.MethodByName(dstName)\n\t\tif !toM.IsValid() && dst.CanAddr() {\n\t\t\ttoM = dst.Addr().MethodByName(dstName)\n\t\t}\n\t\tif toM.IsValid() &&\n\t\t\ttoM.Type().NumIn() == 1 &&\n\t\t\tfrom.Type().AssignableTo(toM.Type().In(0)) {\n\t\t\ttoM.Call([]reflect.Value{from})\n\t\t}\n\t}\n\n\treturn\n}",
"func selectNutritionFields(recipeNutrition recipaliser.RecipeNutrition, selections ...string) []recipeNutritionField {\n\tselectionSets := map[string][]recipeNutritionField{\n\t\t\"macronutrients\": {\n\t\t\t{field: \"Energy (kJ)\", value: recipeNutrition.EnergyWithDietaryFibre},\n\t\t\t{field: \"Available carbohydrates (with sugar alcohols)\", value: recipeNutrition.AvailableCarbohydratesWithSugarAlcohols},\n\t\t\t{field: \"Dietary fibre\", value: recipeNutrition.DietaryFibre},\n\t\t\t{field: \"Protein\", value: recipeNutrition.Protein},\n\t\t\t{field: \"Total fat\", value: recipeNutrition.TotalFat},\n\t\t},\n\t\t\"carbohydrates\": {\n\t\t\t{field: \"Available carbohydrates (with sugar alcohols)\", value: recipeNutrition.AvailableCarbohydratesWithSugarAlcohols},\n\t\t\t{field: \"Available carbohydrates (without sugar alcohols)\", value: recipeNutrition.AvailableCarbohydratesWithoutSugarAlcohol},\n\t\t\t{field: \"Starch\", value: recipeNutrition.Starch},\n\t\t\t{field: \"Total sugars\", value: recipeNutrition.TotalSugars},\n\t\t\t{field: \"Added sugars\", value: recipeNutrition.AddedSugars},\n\t\t\t{field: \"Free sugars\", value: recipeNutrition.FreeSugars},\n\t\t},\n\t\t\"protein\": {\n\t\t\t{field: \"Protein\", value: recipeNutrition.Protein},\n\t\t\t{field: \"Tryptophan\", value: recipeNutrition.Tryptophan},\n\t\t},\n\t\t\"fats\": {\n\t\t\t{field: \"Total fat\", value: recipeNutrition.TotalFat},\n\t\t\t{field: \"Cholesterol\", value: recipeNutrition.Cholesterol},\n\t\t\t{field: \"Total saturated fat\", value: recipeNutrition.TotalSaturatedFat},\n\t\t\t{field: \"Total monounsaturated fat\", value: recipeNutrition.TotalMonounsaturatedFat},\n\t\t\t{field: \"Total polyunsaturated fat\", value: recipeNutrition.TotalPolyunsaturatedFat},\n\t\t\t{field: \"Linoleic acid\", value: recipeNutrition.LinoleicAcid},\n\t\t\t{field: \"Alphalinolenic acid\", value: recipeNutrition.AlphalinolenicAcid},\n\t\t\t{field: \"EPA\", value: recipeNutrition.C205w3Eicosapentaenoic},\n\t\t\t{field: \"DPA\", value: recipeNutrition.C225w3Docosapentaenoic},\n\t\t\t{field: \"DHA\", value: recipeNutrition.C226w3Docosahexaenoic},\n\t\t\t{field: \"Total long-chain omega-3 fatty acids\", value: recipeNutrition.TotalLongChainOmega3FattyAcids},\n\t\t\t{field: \"Total trans-fatty acids\", value: recipeNutrition.TotalTransFattyAcids},\n\t\t},\n\t\t\"vitamins\": {\n\t\t\t{field: \"Vitamin A (retinol equivalents)\", value: recipeNutrition.VitaminARetinolEquivalents},\n\t\t\t{field: \"Thiamin (B1)\", value: recipeNutrition.ThiaminB1},\n\t\t\t{field: \"Riboflavin (B2)\", value: recipeNutrition.RiboflavinB2},\n\t\t\t{field: \"Niacin (B3) (derived equivalents)\", value: recipeNutrition.NiacinDerivedEquivalents},\n\t\t\t{field: \"Dietary folate equivalents\", value: recipeNutrition.DietaryFolateEquivalents},\n\t\t\t{field: \"Vitamin B6\", value: recipeNutrition.VitaminB6},\n\t\t\t{field: \"Vitamin B12\", value: recipeNutrition.VitaminB12},\n\t\t\t{field: \"Vitamin C\", value: recipeNutrition.VitaminC},\n\t\t\t{field: \"Vitamin E\", value: recipeNutrition.VitaminE},\n\t\t},\n\t\t\"minerals\": {\n\t\t\t{field: \"Calcium (Ca)\", value: recipeNutrition.CalciumCa},\n\t\t\t{field: \"Iodine (I)\", value: recipeNutrition.IodineI},\n\t\t\t{field: \"Iron (Fe)\", value: recipeNutrition.IronFe},\n\t\t\t{field: \"Magnesium (Mg)\", value: recipeNutrition.MagnesiumMg},\n\t\t\t{field: \"Phosphorus (P)\", value: recipeNutrition.PhosphorusP},\n\t\t\t{field: \"Potassium (K)\", value: recipeNutrition.PotassiumK},\n\t\t\t{field: \"Selenium (Se)\", value: recipeNutrition.SeleniumSe},\n\t\t\t{field: \"Sodium (Na)\", value: recipeNutrition.SodiumNa},\n\t\t\t{field: \"Zinc (Zn)\", value: recipeNutrition.ZincZn},\n\t\t},\n\t\t\"stimulants\": {\n\t\t\t{field: \"Caffeine\", value: recipeNutrition.Caffeine},\n\t\t},\n\t\t\"depressants\": {\n\t\t\t{field: \"Alcohol\", value: recipeNutrition.Alcohol},\n\t\t},\n\t}\n\n\tvar selectionSet [][]recipeNutritionField\n\tfor _, selection := range selections {\n\t\tselectionSet = append(selectionSet, selectionSets[selection])\n\t}\n\n\treturn flattenSelectionSetForRecipe(selectionSet)\n}",
"func (s SelectStatement) Fields() []string {\n\treturn s.fields\n}",
"func buildSelectFields(selects []interface{}) string {\n\tif len(selects) == 0 {\n\t\treturn \"*\"\n\t}\n\tfields := \"\"\n\tfor _, f := range selects {\n\t\tif v, ok := f.(Raw); ok {\n\t\t\tfields += v.String() + \", \"\n\t\t} else if v, ok := f.(alias); ok {\n\t\t\tfields += v.String() + \", \"\n\t\t} else if v, ok := f.(string); ok {\n\t\t\tfields += quote(v) + \", \"\n\t\t}\n\t}\n\treturn strings.TrimRight(fields, \", \")\n}",
"func (tm *TableModel) GridFields() A.MSX {\n\tcache := GRID_CACHE.Get(tm.CacheName)\n\tjson_arr, ok := cache.(A.MSX)\n\tif !ok {\n\t\tjson_arr = A.MSX{}\n\t\tfor _, field := range tm.Fields {\n\t\t\tswitch field.Key {\n\t\t\tcase `id`, `is_deleted`, `modified_at`:\n\t\t\t\tcontinue\n\t\t\tcase `created_at`, `updated_at`, `deleted_at`, `restored_at`:\n\t\t\t\tfield.GridType = `datetime`\n\t\t\t}\n\t\t\tif field.Hide || field.HtmlHide || field.GridHide {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tjson_obj := M.SX{\n\t\t\t\t`key`: field.Key,\n\t\t\t\t`label`: S.Coalesce(field.GridLabel, field.HtmlLabel, field.Label),\n\t\t\t\t`type`: S.IfEmpty(field.GridType, field.Type),\n\t\t\t}\n\t\t\tif field.GridFooter == `` {\n\t\t\t\tjson_obj[`footer`] = field.GridFooter\n\t\t\t}\n\t\t\tif field.HtmlSubType != `` {\n\t\t\t\tjson_obj[`sub_type`] = field.HtmlSubType\n\t\t\t}\n\t\t\tjson_arr = append(json_arr, json_obj)\n\t\t\tif DEBUG {\n\t\t\t\tL.Print(`Creating GRID_CACHE.Select`, tm.CacheName)\n\t\t\t}\n\t\t}\n\t\tGRID_CACHE.Set(tm.CacheName, json_arr)\n\t}\n\treturn json_arr\n}",
"func TagsToFields(ctx context.Context) []zapcore.Field {\n\treturn ctxzap.TagsToFields(ctx)\n}",
"func (f Fields) Fields() map[string]interface{} {\n\treturn f\n}",
"func (f *Field) toK8S() *v1.ObjectFieldSelector {\n\treturn &v1.ObjectFieldSelector{\n\t\tAPIVersion: f.APIVersion,\n\t\tFieldPath: f.Path,\n\t}\n}",
"func (s *Set) GetFields(vcursor VCursor, bindVars map[string]*querypb.BindVariable) (*sqltypes.Result, error) {\n\tpanic(\"implement me\")\n}",
"func rtSetToSlice(set map[reflect.Type]bool) (result []reflect.Type) {\n\tfor rt := range set {\n\t\tresult = append(result, rt)\n\t}\n\treturn\n}",
"func (s Strategy) GetFieldsForSubDocument(model string, foreignfield string) []map[string]interface{} {\n\tvar fields []map[string]interface{}\n\n\tfor _, f := range s.Map.Entities[model].Fields { // search foreign field in []map[string]interface{}\n\t\tif f[\"foreign\"] == foreignfield {\n\t\t\tfi := f[\"fields\"].([]interface{})\n\t\t\t// Convert the []interface into []map[string]interface{}\n\t\t\tfields = make([]map[string]interface{}, len(fi))\n\t\t\tfor i := range fields {\n\t\t\t\tfields[i] = fi[i].(map[string]interface{})\n\t\t\t}\n\t\t\treturn fields\n\t\t}\n\t}\n\treturn fields\n}",
"func printerConvertSelectionSet(selectionSet ast.SelectionSet) (*gAst.SelectionSet, error) {\n\t// the list of selections for this\n\tselections := []gAst.Selection{}\n\n\tfor _, selection := range selectionSet {\n\t\tswitch selection := selection.(type) {\n\t\tcase *ast.Field:\n\t\t\t// convert the field\n\t\t\tfield, err := printerConvertField(selection)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t// add the field to the selection\n\t\t\tselections = append(selections, field)\n\t\tcase *ast.InlineFragment:\n\t\t\tfragment, err := printerConvertInlineFragment(selection)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t// add the field to the selection\n\t\t\tselections = append(selections, fragment)\n\t\tcase *ast.FragmentSpread:\n\t\t\tfragment, err := printerConvertFragmentSpread(selection)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t// add the field to the selection\n\t\t\tselections = append(selections, fragment)\n\t\t}\n\t}\n\n\treturn &gAst.SelectionSet{\n\t\tKind: \"SelectionSet\",\n\t\tSelections: selections,\n\t}, nil\n}",
"func (fuo *FriendshipUpdateOne) Select(field string, fields ...string) *FriendshipUpdateOne {\n\tfuo.fields = append([]string{field}, fields...)\n\treturn fuo\n}",
"func getComparableFields() []string {\n\tfields := []string{}\n\n\tfor _, fieldName := range getContainerFields() {\n\t\t// Skip some fields\n\t\tif unicode.IsLower((rune)(fieldName[0])) {\n\t\t\tcontinue\n\t\t}\n\n\t\tskip := false\n\t\tfor _, f := range compareSkipFields {\n\t\t\tif f == fieldName {\n\t\t\t\tskip = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !skip {\n\t\t\tfields = append(fields, fieldName)\n\t\t}\n\t}\n\n\treturn fields\n}",
"func (s UserSet) SelfReadableFields() map[string]bool {\n\tres := s.Collection().Call(\"SelfReadableFields\")\n\tresTyped, _ := res.(map[string]bool)\n\treturn resTyped\n}",
"func (guo *GroupUpdateOne) Select(field string, fields ...string) *GroupUpdateOne {\n\tguo.fields = append([]string{field}, fields...)\n\treturn guo\n}",
"func (pl List) ToBitField() uint32 {\n\tvar ret uint32\n\tfor _, p := range pl {\n\t\tret |= p.Mask()\n\t}\n\treturn ret\n}",
"func (o *ProvenanceOptionsDTO) GetSearchableFields() []ProvenanceSearchableFieldDTO {\n\tif o == nil || o.SearchableFields == nil {\n\t\tvar ret []ProvenanceSearchableFieldDTO\n\t\treturn ret\n\t}\n\treturn *o.SearchableFields\n}",
"func (muo *ModelUpdateOne) Select(field string, fields ...string) *ModelUpdateOne {\n\tmuo.fields = append([]string{field}, fields...)\n\treturn muo\n}",
"func (conn *Connection) GetLimitFields(q, selector, doc interface{}, fields ...string) error {\n\tif len(fields) == 0 {\n\t\treturn conn.collection.Find(q).Select(selector).All(doc)\n\t}\n\n\treturn conn.collection.Find(q).Sort(fields...).Select(selector).All(doc)\n}",
"func (s FindingCriteria) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Criterion != nil {\n\t\tv := s.Criterion\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"criterion\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\treturn nil\n}",
"func (f *FieldHandler) FieldSelector() FieldSelector {\n\treturn FieldSelector(f.selector)\n}",
"func (c *commentsQueryBuilder) Select(fields ...string) *commentsQueryBuilder {\n\tif c.err != nil {\n\t\treturn c\n\t}\n\tvar fieldSet []*mapping.StructField\n\tfor _, field := range fields {\n\t\tstructField, ok := NRN_Comments.Model.FieldByName(field)\n\t\tif !ok {\n\t\t\tc.err = errors.Wrapf(mapping.ErrInvalidModelField, \"field: '%s' is not valid for model: '_Comments'\", field)\n\t\t\treturn c\n\t\t}\n\t\tfieldSet = append(fieldSet, structField)\n\t}\n\tc.builder.Select(fieldSet...)\n\treturn c\n}",
"func FieldsToSQLiteColumns(list ...map[string]interface{}) []sqlite.Column {\n\tuniqCols := map[string]sqlite.Column{}\n\tfor _, fields := range list {\n\t\tfor field, tp := range fields {\n\t\t\tstr, isString := tp.(string)\n\t\t\tif isString {\n\t\t\t\tuniqCols[field] = sqlite.Column{field, str}\n\t\t\t}\n\t\t}\n\t}\n\tcols := make([]sqlite.Column, len(uniqCols))\n\tidx := 0\n\tfor _, col := range uniqCols {\n\t\tcols[idx] = col\n\t\tidx = idx + 1\n\t}\n\treturn cols\n}",
"func (ruo *RevisionUpdateOne) Select(field string, fields ...string) *RevisionUpdateOne {\n\truo.fields = append([]string{field}, fields...)\n\treturn ruo\n}",
"func (cuo *CarUpdateOne) Select(field string, fields ...string) *CarUpdateOne {\n\tcuo.fields = append([]string{field}, fields...)\n\treturn cuo\n}",
"func (Patientroom) Fields() []ent.Field {\n return []ent.Field{\n field.String(\"Typeroom\").\n Unique(),\n \n } \n}",
"func (s *Select) SetFields(fieldName ...string) *Select {\n\tfor _, field := range fieldName {\n\t\ts.fields = append(s.fields, strings.ToLower(field))\n\t}\n\treturn s\n}",
"func Where(conditions interface {}, fields ...interface {}) (users []User) {\n var result []interface{}\n collection.Find(conditions).Select(fields).All(&result)\n mapstructure.Decode(result, &users)\n\n return users\n}",
"func (bv Values) CloneWithFieldsOf(s interface{}) Values {\n\tvalues := bv.Clone()\n\n\t// add the manual filled fields to the dependencies.\n\tfilledFieldValues := LookupNonZeroFieldsValues(ValueOf(s), true)\n\n\tfor i, filled := range filledFieldValues {\n\t\tfor _, v := range values {\n\t\t\t// do NOT keep duplicate equal values (09-Jul-2019).\n\t\t\tif reflect.DeepEqual(v, filled) {\n\t\t\t\tif last := len(filledFieldValues) - 1; last > i {\n\t\t\t\t\tfilledFieldValues = append(filledFieldValues[:i], filledFieldValues[i+1:]...)\n\t\t\t\t} else {\n\t\t\t\t\tfilledFieldValues = filledFieldValues[0:last]\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tvalues = append(values, filledFieldValues...)\n\n\treturn values\n}",
"func getFields(s interface{}) []interface{} {\n\tv := reflect.ValueOf(s)\n\tv = dereference(v)\n\tfields := []interface{}{}\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tfield := v.Field(i)\n\t\tif field.CanInterface() {\n\t\t\tfields = append(fields, field.Interface())\n\t\t}\n\t}\n\treturn fields\n}",
"func (set *AppleSet) ToInterfaceSlice() []interface{} {\n\tset.s.RLock()\n\tdefer set.s.RUnlock()\n\n\ts := make([]interface{}, 0, len(set.m))\n\tfor v := range set.m {\n\t\ts = append(s, v)\n\t}\n\treturn s\n}",
"func (f *Fields) Set(s []*Field)",
"func (c *TimerCond) FieldsSet(excludes ...unsafe.Pointer) (fields []string) {\n\titerOptionalFields(reflect.ValueOf(c).Elem(), excludes, func(name string, val optionalVal) bool {\n\t\tif val.Present() {\n\t\t\tfields = append(fields, name)\n\t\t}\n\t\treturn true\n\t})\n\treturn\n}",
"func StructureFieldSelectors(local *ast.Field, fields ...*ast.Field) []ast.Expr {\n\tselectors := make([]ast.Expr, 0, len(fields))\n\tfor _, n := range local.Names {\n\t\tfor _, field := range fields {\n\t\t\tsel := MapFieldsToNameIdent(field)[0]\n\t\t\tsel.NamePos = 0\n\t\t\tselectors = append(selectors, &ast.SelectorExpr{\n\t\t\t\tX: n,\n\t\t\t\tSel: sel,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn selectors\n}",
"func (tuo *TeamUpdateOne) Select(field string, fields ...string) *TeamUpdateOne {\n\ttuo.fields = append([]string{field}, fields...)\n\treturn tuo\n}",
"func (pfmuo *ParticipantFlowModuleUpdateOne) Select(field string, fields ...string) *ParticipantFlowModuleUpdateOne {\n\tpfmuo.fields = append([]string{field}, fields...)\n\treturn pfmuo\n}",
"func (u *TimerUpdate) FieldsSet(excludes ...unsafe.Pointer) (fields []string) {\n\titerOptionalFields(reflect.ValueOf(u).Elem(), excludes, func(name string, val optionalVal) bool {\n\t\tif val.Present() {\n\t\t\tfields = append(fields, name)\n\t\t}\n\t\treturn true\n\t})\n\treturn\n}",
"func (auo *AdministratorUpdateOne) Select(field string, fields ...string) *AdministratorUpdateOne {\n\tauo.fields = append([]string{field}, fields...)\n\treturn auo\n}",
"func ConvertToFieldNameSlice(fields []string) []FieldNamer {\n\tres := make([]FieldNamer, len(fields))\n\tfor i, v := range fields {\n\t\tres[i] = FieldName(v)\n\t}\n\treturn res\n}",
"func filterOnDBFields(mi *modelInfo, fields []string) []string {\n\tvar res []string\n\t// Check if fields are stored\n\tfor _, field := range fields {\n\t\tfieldExprs := jsonizeExpr(mi, strings.Split(field, ExprSep))\n\t\tfi, ok := mi.fields.get(fieldExprs[0])\n\t\tif !ok {\n\t\t\ttools.LogAndPanic(log, \"Unknown Field in model\", \"field\", fieldExprs[0], \"model\", mi.name)\n\t\t}\n\t\tvar resExprs []string\n\t\tif fi.isStored() {\n\t\t\tresExprs = append(resExprs, fi.json)\n\t\t}\n\t\tif len(fieldExprs) > 1 {\n\t\t\t// Related field (e.g. User.Profile.Age)\n\t\t\tif fi.relatedModel != nil {\n\t\t\t\tsubFieldName := strings.Join(fieldExprs[1:], ExprSep)\n\t\t\t\tsubFieldRes := filterOnDBFields(fi.relatedModel, []string{subFieldName})\n\t\t\t\tif len(subFieldRes) > 0 {\n\t\t\t\t\tresExprs = append(resExprs, subFieldRes[0])\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttools.LogAndPanic(log, \"Field is not a relation in model\", \"field\", fieldExprs[0], \"model\", mi.name)\n\t\t\t}\n\t\t}\n\t\tif len(resExprs) > 0 {\n\t\t\tres = append(res, strings.Join(resExprs, ExprSep))\n\t\t}\n\t}\n\t// Check we have \"id\" else add it to our list\n\tvar idPresent bool\n\tfor _, r := range res {\n\t\tif r == \"id\" {\n\t\t\tidPresent = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !idPresent {\n\t\tres = append(res, \"id\")\n\t}\n\treturn res\n}",
"func getAllFields(o interface{}) map[string]interface{} {\n\tt := reflect.TypeOf(o)\n\tif t.Kind() == reflect.Ptr || t.Kind() == reflect.Interface {\n\t\tt = reflect.ValueOf(o).Elem().Type()\n\t\to = reflect.ValueOf(o).Elem().Interface()\n\t}\n\n\tchanges := make(map[string]interface{})\n\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tfield := t.Field(i)\n\t\tvalue, exists := field.Tag.Lookup(changeTag)\n\t\tif exists {\n\t\t\tif value == \"inner\" {\n\n\t\t\t\tchanges[field.Name] = getAllFields(reflect.ValueOf(o).FieldByName(field.Name).Interface())\n\t\t\t} else {\n\t\t\t\tjsonFieldName, exists := field.Tag.Lookup(\"json\")\n\n\t\t\t\tif !exists {\n\t\t\t\t\tjsonFieldName = field.Name\n\t\t\t\t} else {\n\t\t\t\t\tcommaIndex := strings.Index(jsonFieldName, \",\")\n\t\t\t\t\tif commaIndex != -1 {\n\t\t\t\t\t\tjsonFieldName = jsonFieldName[:commaIndex]\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tchangeField := &ChangeField{\n\t\t\t\t\tValue: getValue(o, field.Name),\n\t\t\t\t\tField: jsonFieldName,\n\t\t\t\t}\n\t\t\t\tchanges[field.Name] = changeField\n\t\t\t}\n\t\t}\n\t}\n\treturn changes\n}",
"func (BaseMixin) Fields() []ent.Field {\n\treturn []ent.Field{\n\t\tfield.UUID(\"id\", uuid.UUID{}).Default(uuid.New),\n\t\tfield.String(\"some_field\"),\n\t}\n}",
"func (pt *ProcessTemplate) GetEditableFields(fields []string) []string {\n\teditableFields := pt.ExtractEditableFields()\n\tresult := make([]string, 0)\n\tfor _, field := range fields {\n\t\tif util.InStrArr(editableFields, field) {\n\t\t\tresult = append(result, field)\n\t\t}\n\t}\n\treturn result\n}",
"func SelectorFromSet(ls Set) Selector {\n\tif ls == nil {\n\t\treturn Everything()\n\t}\n\titems := make([]Selector, 0, len(ls))\n\tfor field, value := range ls {\n\t\titems = append(items, &hasTerm{field: field, value: value})\n\t}\n\tif len(items) == 1 {\n\t\treturn items[0]\n\t}\n\treturn andTerm(items)\n}",
"func SetToSlice(set map[string]struct{}) []string {\n\tdata := make([]string, 0, len(set))\n\tfor key := range set {\n\t\tdata = append(data, key)\n\t}\n\treturn data\n}",
"func (i PullAll) Fields() []interface{} {\n\treturn nil\n}",
"func (s UserSet) FieldsGet(args models.FieldsGetArgs) map[string]*models.FieldInfo {\n\tres := s.Collection().Call(\"FieldsGet\", args)\n\tresTyped, _ := res.(map[string]*models.FieldInfo)\n\treturn resTyped\n}",
"func (md CountryModel) Fields() country.FieldsCollection {\n\treturn country.FieldsCollection{\n\t\tFieldsCollection: md.Model.Fields(),\n\t}\n}",
"func (gsuo *GameServerUpdateOne) Select(field string, fields ...string) *GameServerUpdateOne {\n\tgsuo.fields = append([]string{field}, fields...)\n\treturn gsuo\n}",
"func objFields(obj interface{}, skipKey bool) (interface{}, []interface{}) {\n\tval := reflect.ValueOf(obj)\n\tt := reflect.TypeOf(obj)\n\ta := make([]interface{}, 0, t.NumField())\n\tvar key interface{}\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tf := t.Field(i)\n\t\tif len(f.Tag.Get(\"sql\")) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif f.Tag.Get(\"key\") == \"true\" {\n\t\t\tkey = val.Field(i).Interface()\n\t\t\tif skipKey {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\ta = append(a, val.Field(i).Interface())\n\t}\n\treturn key, a\n}",
"func (c Container) CloneWithFieldsOf(i interface{}) Container {\n\tvalues := c.Clone()\n\n\t// add the manual filled fields to the dependencies.\n\tfilledFieldValues := LookupNonZeroFieldsValues(ValueOf(i), true)\n\tvalues = append(values, filledFieldValues...)\n\treturn values\n}",
"func (ouo *OtherUpdateOne) Select(field string, fields ...string) *OtherUpdateOne {\n\touo.fields = append([]string{field}, fields...)\n\treturn ouo\n}",
"func (suo *SkillUpdateOne) Select(field string, fields ...string) *SkillUpdateOne {\n\tsuo.fields = append([]string{field}, fields...)\n\treturn suo\n}",
"func Fields(v interface{}) []*Fieldx {\n\treturn New(v).Fields()\n}",
"func (s UserSet) SelfWritableFields() map[string]bool {\n\tres := s.Collection().Call(\"SelfWritableFields\")\n\tresTyped, _ := res.(map[string]bool)\n\treturn resTyped\n}",
"func (cpy *impl) CopyFromMethod(\n\ttoT reflect.Type,\n\t_ reflect.Type,\n\tdst reflect.Value,\n\tsrc reflect.Value,\n\tselected []string,\n\tomit []string,\n\tfilter FilterFn,\n) (err error) {\n\tconst paramName = `name`\n\tvar (\n\t\tfromM reflect.Value\n\t\tfield reflect.StructField\n\t\tsrcName, dstName string\n\t)\n\n\tfor _, field = range cpy.Fields(toT) {\n\t\tdstName = field.Name\n\t\tif srcName = cpy.FieldReplaceName(field, paramName); srcName == \"\" {\n\t\t\tsrcName = dstName\n\t\t}\n\t\tif cpy.IsSkip(selected, omit, srcName, dstName) {\n\t\t\tcontinue\n\t\t}\n\t\tfromM = src.MethodByName(srcName)\n\t\tif !fromM.IsValid() && src.CanAddr() {\n\t\t\tfromM = src.Addr().MethodByName(srcName)\n\t\t}\n\t\tif fromM.IsValid() {\n\t\t\terr = cpy.SetToFieldOrMethod(dst, dstName, fromM, srcName, selected, omit, filter)\n\t\t}\n\t}\n\n\treturn\n}",
"func (ttruo *TradeTimeRangeUpdateOne) Select(field string, fields ...string) *TradeTimeRangeUpdateOne {\n\tttruo.fields = append([]string{field}, fields...)\n\treturn ttruo\n}",
"func (truo *TradeRecordUpdateOne) Select(field string, fields ...string) *TradeRecordUpdateOne {\n\ttruo.fields = append([]string{field}, fields...)\n\treturn truo\n}",
"func (duo *DocUpdateOne) Select(field string, fields ...string) *DocUpdateOne {\n\tduo.fields = append([]string{field}, fields...)\n\treturn duo\n}",
"func ttSetToSlice(set map[*vdl.Type]bool) (result []*vdl.Type) {\n\tfor tt := range set {\n\t\tresult = append(result, tt)\n\t}\n\treturn\n}",
"func (tuo *TagUpdateOne) Select(field string, fields ...string) *TagUpdateOne {\n\ttuo.fields = append([]string{field}, fields...)\n\treturn tuo\n}",
"func (oliuo *OrderLineItemUpdateOne) Select(field string, fields ...string) *OrderLineItemUpdateOne {\n\toliuo.fields = append([]string{field}, fields...)\n\treturn oliuo\n}",
"func (o *MicrosoftGraphListItem) GetFields() AnyOfmicrosoftGraphFieldValueSet {\n\tif o == nil || o.Fields == nil {\n\t\tvar ret AnyOfmicrosoftGraphFieldValueSet\n\t\treturn ret\n\t}\n\treturn *o.Fields\n}",
"func (s *SelectableAttribute) Selectable() Attribute {\n\treturn s.attr\n}",
"func convertToStringSlice(fieldNames []FieldNamer) []string {\n\tres := make([]string, len(fieldNames))\n\tfor i, v := range fieldNames {\n\t\tres[i] = string(v.FieldName())\n\t}\n\treturn res\n}",
"func (suo *StateUpdateOne) Select(field string, fields ...string) *StateUpdateOne {\n\tsuo.fields = append([]string{field}, fields...)\n\treturn suo\n}",
"func (f Fields) Clone(keysAndValues ...interface{}) Fields {\n\tclone := f\n\tfor i := 0; i+1 < len(keysAndValues); i += 2 {\n\t\tclone = append(clone, Field{keysAndValues[i], keysAndValues[i+1]})\n\t}\n\treturn clone\n}",
"func (duo *DealUpdateOne) Select(field string, fields ...string) *DealUpdateOne {\n\tduo.fields = append([]string{field}, fields...)\n\treturn duo\n}",
"func (DrugAllergy) Fields() []ent.Field {\n return []ent.Field{\n \n }\n }",
"func ReflectFieldsFq(\n\tt reflect.Type,\n\ttypeMap TypeMap,\n\texclude ExcludeFieldTag,\n) graphql.Fields {\n\tif t.Kind() != reflect.Struct {\n\t\tpanic(fmt.Sprintf(`ReflectFieldsFq can only work on struct types.\n\t\t\tReceived instead %s`, t.Kind()))\n\t}\n\tfields := make(graphql.Fields)\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tf := t.Field(i)\n\t\tif includeField(f, exclude) {\n\t\t\tname := GqlName(GetFieldFirstTag(f, \"json\"))\n\t\t\tfields[string(name)] = ReflectFieldFq(name, f.Type, typeMap, exclude)\n\t\t}\n\t}\n\treturn fields\n}",
"func (oiuo *OrderInfoUpdateOne) Select(field string, fields ...string) *OrderInfoUpdateOne {\n\toiuo.fields = append([]string{field}, fields...)\n\treturn oiuo\n}",
"func IterFields(t *Type) (*Field, Iter)",
"func (self *mergeState) getFields() []string {\n\tfields := make([]string, len(self.fields))\n\tfor f, i := range self.fields {\n\t\tfields[i] = f\n\t}\n\treturn fields\n}",
"func (Physician) Fields() []ent.Field {\n return []ent.Field{\n field.String(\"Physicianname\"),\n field.String(\"Physicianemail\"). \n Unique(), \n field.String(\"Password\"), \n } \n}",
"func (set *SetThreadSafe) ToSlice() []interface{} {\n\tvar ret []interface{}\n\tset.Items.Range(func(k, v interface{}) bool {\n\t\tret = append(ret, k)\n\t\treturn true\n\t})\n\treturn ret\n}",
"func (auo *ArticleUpdateOne) Select(field string, fields ...string) *ArticleUpdateOne {\n\tauo.fields = append([]string{field}, fields...)\n\treturn auo\n}"
] | [
"0.6919115",
"0.68036646",
"0.67700404",
"0.6673591",
"0.6653567",
"0.6620765",
"0.649165",
"0.6437286",
"0.6310288",
"0.61175853",
"0.60585755",
"0.6037737",
"0.5860326",
"0.5822092",
"0.5734321",
"0.5474438",
"0.52635175",
"0.51580745",
"0.50482243",
"0.48879197",
"0.48681897",
"0.4859733",
"0.48594555",
"0.4858361",
"0.4838909",
"0.4813087",
"0.4784026",
"0.47737053",
"0.47730526",
"0.4716383",
"0.47038648",
"0.47035325",
"0.46651927",
"0.46491736",
"0.46476027",
"0.46360272",
"0.46260208",
"0.46115667",
"0.45983937",
"0.4586237",
"0.4576377",
"0.45622092",
"0.45596716",
"0.45592993",
"0.45590678",
"0.4523508",
"0.4514686",
"0.4501409",
"0.44996366",
"0.44967207",
"0.4492016",
"0.44909424",
"0.44887754",
"0.44869652",
"0.44790053",
"0.44788873",
"0.44765517",
"0.44701794",
"0.44559315",
"0.44501725",
"0.44306627",
"0.44285396",
"0.44225425",
"0.44096813",
"0.44083354",
"0.44061816",
"0.43988234",
"0.43599647",
"0.4358133",
"0.43566588",
"0.435427",
"0.43540996",
"0.43518722",
"0.4349707",
"0.43490115",
"0.43443102",
"0.43406832",
"0.4338282",
"0.43359882",
"0.43350983",
"0.4334729",
"0.43283406",
"0.43240592",
"0.4322064",
"0.43218407",
"0.43188983",
"0.43026334",
"0.43022615",
"0.43005556",
"0.42986092",
"0.42904705",
"0.42903075",
"0.4287879",
"0.4287413",
"0.42825952",
"0.42815936",
"0.42808005",
"0.4277789",
"0.42656142",
"0.4264299"
] | 0.7299822 | 0 |
GetAttrs returns labels and fields of a given object for filtering purposes. | func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {
serviceclass, ok := obj.(*servicecatalog.ServiceClass)
if !ok {
return nil, nil, fmt.Errorf("given object is not a ServiceClass")
}
return labels.Set(serviceclass.ObjectMeta.Labels), ToSelectableFields(serviceclass), nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tsecret, ok := obj.(*api.Secret)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"not a secret\")\n\t}\n\treturn labels.Set(secret.Labels), SelectableFields(secret), nil\n}",
"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tapiserver, ok := obj.(*v1alpha1.Cluster)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"given object is not a Cluster\")\n\t}\n\treturn labels.Set(apiserver.ObjectMeta.Labels), SelectableFields(apiserver), nil\n}",
"func (f *File) getObjectAttrs() (*storage.ObjectAttrs, error) {\n\thandle, err := f.getObjectHandle()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn handle.Attrs(f.fileSystem.ctx)\n}",
"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, bool, error) {\n\tpip, ok := obj.(*settings.PodPreset)\n\tif !ok {\n\t\treturn nil, nil, false, fmt.Errorf(\"given object is not a PodPreset.\")\n\t}\n\treturn labels.Set(pip.ObjectMeta.Labels), SelectableFields(pip), pip.Initializers != nil, nil\n}",
"func (o *ObjectData) GetAttr(name string) (value Object, present bool) {\n value, present = o.Attrs[name]\n return \n}",
"func GetAttributes(t reflect.Type) (attrs []AttributeDesc) {\n\tif t == nil {\n\t\treturn\n\t}\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tdfield := t.Field(i)\n\t\tattr := AttributeDesc{\n\t\t\tName: dfield.Name,\n\t\t\tIndex: i + 1,\n\t\t\tDesc: dfield.Tag.Get(\"description\"),\n\t\t\tKind: dfield.Tag.Get(\"kind\"),\n\t\t\tRelation: dfield.Tag.Get(\"ref\"),\n\t\t}\n\t\tattrs = append(attrs, attr)\n\t}\n\treturn\n}",
"func (s *stack) GetAttrs() map[string]string {\n\tans := make(map[string]string)\n\tcurr := s.last\n\tfor curr != nil {\n\t\tfor k, v := range curr.value.Attrs {\n\t\t\tans[curr.value.Name+\".\"+k] = v\n\t\t}\n\t\tcurr = curr.prev\n\t}\n\treturn ans\n}",
"func (c EntityObject) Attributes() map[string]interface{} {\n\treturn c.attributes\n}",
"func (a adapter) Attrs(key string) []string {\n\treturn a.entry.GetAttributeValues(key)\n}",
"func (t *largeFlatTable) Attrs(ctx context.Context) TableAttrs { return t.attrs }",
"func (obj *SObject) AttributesField() *SObjectAttributes {\n\tattributes := obj.InterfaceField(sobjectAttributesKey)\n\n\tswitch attributes.(type) {\n\tcase SObjectAttributes:\n\t\t// Use a temporary variable to copy the value of attributes and return the address of the temp value.\n\t\tattrs := (attributes).(SObjectAttributes)\n\t\treturn &attrs\n\tcase map[string]interface{}:\n\t\t// Can't convert attributes to concrete type; decode interface.\n\t\tmapper := attributes.(map[string]interface{})\n\t\tattrs := &SObjectAttributes{}\n\t\tif mapper[\"type\"] != nil {\n\t\t\tattrs.Type = mapper[\"type\"].(string)\n\t\t}\n\t\tif mapper[\"url\"] != nil {\n\t\t\tattrs.URL = mapper[\"url\"].(string)\n\t\t}\n\t\treturn attrs\n\tdefault:\n\t\treturn nil\n\t}\n}",
"func (b *Bucket) Attributes(ctx context.Context, name string) (objstore.ObjectAttributes, error) {\n\tattrs, err := b.bkt.Object(name).Attrs(ctx)\n\tif err != nil {\n\t\treturn objstore.ObjectAttributes{}, err\n\t}\n\n\treturn objstore.ObjectAttributes{\n\t\tSize: attrs.Size,\n\t\tLastModified: attrs.Updated,\n\t}, nil\n}",
"func (b *Bucket) Attributes(_ context.Context, name string) (objstore.ObjectAttributes, error) {\n\tobjMeta, err := b.client.GetObjectMeta(b.name, name)\n\tif err != nil {\n\t\treturn objstore.ObjectAttributes{}, errors.Wrapf(err, \"gettting objectmeta of %s\", name)\n\t}\n\n\tlastModified, err := time.Parse(time.RFC1123, objMeta.LastModified)\n\tif err != nil {\n\t\treturn objstore.ObjectAttributes{}, err\n\t}\n\n\treturn objstore.ObjectAttributes{\n\t\tSize: objMeta.ContentLength,\n\t\tLastModified: lastModified,\n\t}, nil\n}",
"func attributes(m interface{}) map[string]reflect.Type {\n\ttyp := reflect.TypeOf(m)\n\t// if a pointer to a struct is passed, get the type of the dereferenced object\n\tif typ.Kind() == reflect.Ptr {\n\t\ttyp = typ.Elem()\n\t}\n\n\t// create an attribute data structure as a map of types keyed by a string.\n\tattrs := make(map[string]reflect.Type)\n\t// Only structs are supported so return an empty result if the passed object\n\t// isn't a struct\n\tif typ.Kind() != reflect.Struct {\n\t\tfmt.Printf(\"%v type can't have attributes inspected\\n\", typ.Kind())\n\t\treturn attrs\n\t}\n\n\t// loop through the struct's fields and set the map\n\tfor i := 0; i < typ.NumField(); i++ {\n\t\tp := typ.Field(i)\n\t\tif !p.Anonymous {\n\t\t\tattrs[p.Name] = p.Type\n\t\t}\n\t}\n\n\treturn attrs\n}",
"func (k2h *K2hash) GetAttrs(k string) ([]Attr, error) {\n\t// 1. retrieve an attribute using k2h_get_attrs\n\t// bool k2h_get_attrs(k2h_h handle, const unsigned char* pkey, size_t keylength, PK2HATTRPCK* ppattrspck, int* pattrspckcnt)\n\tcKey := C.CBytes([]byte(k))\n\tdefer C.free(unsafe.Pointer(cKey))\n\tvar attrpack C.PK2HATTRPCK\n\tvar attrpackCnt C.int\n\tok := C.k2h_get_attrs(\n\t\tk2h.handle,\n\t\t(*C.uchar)(cKey),\n\t\tC.size_t(len([]byte(k))+1), // plus one for a null termination\n\t\t&attrpack,\n\t\t&attrpackCnt,\n\t)\n\tdefer C.k2h_free_attrpack(attrpack, attrpackCnt) // free the memory for the keypack for myself(GC doesn't know the area)\n\n\tif ok == false {\n\t\tfmt.Println(\"C.k2h_get_attrs returns false\")\n\t\treturn []Attr{}, fmt.Errorf(\"C.k2h_get_attrs() = %v\", ok)\n\t} else if attrpackCnt == 0 {\n\t\tfmt.Printf(\"attrpackLen is zero\")\n\t\treturn []Attr{}, nil\n\t} else {\n\t\tfmt.Printf(\"attrpackLen is %v\\n\", attrpackCnt)\n\t}\n\t// 2. copy an attribute data to a slice\n\tvar CAttrs C.PK2HATTRPCK = attrpack\n\tcount := (int)(attrpackCnt)\n\tslice := (*[1 << 28]C.K2HATTRPCK)(unsafe.Pointer(CAttrs))[:count:count]\n\tfmt.Printf(\"slice size is %v\\n\", len(slice))\n\t//\n\tattrs := make([]Attr, count) // copy\n\tfor i, data := range slice {\n\t\t// copy the data with len-1 length, which exclude a null termination.\n\t\tattrkey := C.GoBytes(unsafe.Pointer(data.pkey), (C.int)(data.keylength-1))\n\t\tfmt.Printf(\"i %v data %T pkey %v length %v attrkey %v\\n\", i, data, data.pkey, data.keylength, string(attrkey))\n\t\tattrval := C.GoBytes(unsafe.Pointer(data.pval), (C.int)(data.vallength-1))\n\t\tfmt.Printf(\"i %v data %T pval %v length %v attrval %v\\n\", i, data, data.pval, data.vallength, string(attrval))\n\t\t// cast bytes to a string\n\t\tattrs[i].key = string(attrkey)\n\t\tattrs[i].val = string(attrval)\n\t}\n\treturn attrs, nil\n}",
"func attrsFrom(schema interface{}) (attrs []string) {\n\t// fields from schema\n\ts := reflect.ValueOf(schema).Elem()\n\tfs := s.Type()\n\tfor i := 0; i < s.NumField(); i++ {\n\t\tfield := s.Field(i)\n\t\tif skipField(fs.Field(i).Name, field) {\n\t\t\tcontinue\n\t\t}\n\t\tattrs = append(attrs, fs.Field(i).Name)\n\t}\n\treturn\n}",
"func (res *Resource) IndexAttrs(values ...interface{}) []*Section {\n\tres.setSections(&res.indexSections, values...)\n\tres.SearchAttrs()\n\treturn res.indexSections\n}",
"func Attr(attrs ...a.Attribute) []a.Attribute {\n return attrs\n}",
"func (attestedClaim *AttestedClaim) getAttributes() ([]*Attribute, error) {\n\tbInts := attestedClaim.getRawAttributes()\n\tattributes, err := BigIntsToAttributes(bInts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsorted := sort.SliceIsSorted(attributes, func(p, q int) bool {\n\t\treturn strings.Compare(attributes[p].Name, attributes[q].Name) < 0\n\t})\n\tif !sorted {\n\t\treturn nil, errors.New(\"expected attributes inside credential to be sorted\")\n\t}\n\treturn attributes, nil\n}",
"func (c *APIClient) GetCustomAttributes(ctx _context.Context) apiGetCustomAttributesRequest {\n\treturn apiGetCustomAttributesRequest{\n\t\tclient: c,\n\t\tctx: ctx,\n\t}\n}",
"func (res *Resource) SearchAttrs(columns ...string) []string {\n\tif len(columns) != 0 || res.searchAttrs == nil {\n\t\tif len(columns) == 0 {\n\t\t\tcolumns = res.ConvertSectionToStrings(res.indexSections)\n\t\t}\n\n\t\tif len(columns) > 0 {\n\t\t\tres.searchAttrs = &columns\n\t\t\tres.SearchHandler = func(keyword string, context *qor.Context) *gorm.DB {\n\t\t\t\treturn defaultFieldFilter(res, columns, keyword, context.GetDB(), context)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn columns\n}",
"func (o *VirtualizationVmwareVirtualMachineAllOf) GetCustomAttributes() []string {\n\tif o == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn o.CustomAttributes\n}",
"func GetFields(m interface{}) (ns []string) {\n\ttyp := GetType(m)\n\t// Only structs are supported so return an empty result if the passed object\n\t// isn't a struct\n\tif typ.Kind() != reflect.Struct {\n\t\tfmt.Printf(\"%v type can't have attributes inspected\\n\", typ.Kind())\n\t\treturn\n\t}\n\t// loop through the struct's fields\n\tfor i := 0; i < typ.NumField(); i++ {\n\t\tf := typ.Field(i)\n\t\tif f.Anonymous {\n\t\t\tfkind := f.Type.Kind()\n\t\t\tif fkind == reflect.Struct || fkind == reflect.Ptr {\n\t\t\t\tfns := GetFields(reflect.New(f.Type).Interface())\n\t\t\t\tfor _, fn := range fns {\n\t\t\t\t\tif String(fn).IsInArray(ns) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tns = append(ns, fn)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif String(f.Name).IsInArray(ns) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tns = append(ns, f.Name)\n\t\t}\n\t}\n\treturn ns\n}",
"func ObjectGetAttr(o Object, attr string) Object {\n\t// FIXME\n\treturn nil\n}",
"func ObjectGetAttr(o Object, attr string) Object {\n\t// FIXME\n\treturn nil\n}",
"func (a *ManagementApiService) GetAttributes(ctx _context.Context) apiGetAttributesRequest {\n\treturn apiGetAttributesRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t}\n}",
"func attributes(m interface{}) map[string]reflect.Type {\n\ttyp := reflect.TypeOf(m)\n\tif typ.Kind() == reflect.Ptr {\n\t\ttyp = typ.Elem()\n\t}\n\n\tattrs := make(map[string]reflect.Type)\n\tif typ.Kind() != reflect.Struct {\n\t\treturn nil\n\t}\n\n\tfor i := 0; i < typ.NumField(); i++ {\n\t\tp := typ.Field(i)\n\t\tif !p.Anonymous {\n\t\t\tattrs[p.Name] = p.Type\n\t\t}\n\t}\n\n\treturn attrs\n}",
"func (r *GetAttrsResult) Bytes() []*Attr {\n\treturn r.attrs\n}",
"func (c *ServiceCurve) Attrs() (uint32, uint32, uint32) {\n\treturn c.m1, c.d, c.m2\n}",
"func (s *Prototype) AttrOf(name string, target Value) (Value, error) {\n\tfor _, parent := range s.parents {\n\t\tif parent.name == name {\n\t\t\treturn parent.value, nil\n\t\t}\n\t}\n\n\tvar val Value\n\n\ts.AlongChain(func(p *Prototype) error {\n\t\t// Binary search the entries.\n\t\t// This implementation is a specialization of\n\t\t// sort.Search that avoids dynamic dispatch.\n\t\tn := len(p.entries)\n\t\ti, j := 0, n\n\t\tfor i < j {\n\t\t\th := int(uint(i+j) >> 1)\n\t\t\tif p.entries[h].name < name {\n\t\t\t\ti = h + 1\n\t\t\t} else {\n\t\t\t\tj = h\n\t\t\t}\n\t\t}\n\t\tif i < n && p.entries[i].name == name {\n\t\t\tval = p.entries[i].value\n\t\t\treturn StopChain\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif val != nil {\n\t\tif br, ok := val.(HasBindReceiver); ok {\n\t\t\treturn br.BindReceiver(target), nil\n\t\t}\n\n\t\treturn val, nil\n\t}\n\n\treturn nil, NoSuchAttrError(\n\t\tfmt.Sprintf(\"no .%s field or method\", name))\n}",
"func (O *Object) GetAttribute(data *Data, name string) error {\n\tif O == nil || O.dpiObject == nil {\n\t\tpanic(\"nil dpiObject\")\n\t}\n\tattr, ok := O.Attributes[name]\n\tif !ok {\n\t\treturn errors.Errorf(\"%s: %w\", name, ErrNoSuchKey)\n\t}\n\n\tdata.reset()\n\tdata.NativeTypeNum = attr.NativeTypeNum\n\tdata.ObjectType = attr.ObjectType\n\tdata.implicitObj = true\n\t// the maximum length of that buffer must be supplied\n\t// in the value.asBytes.length attribute before calling this function.\n\tif attr.NativeTypeNum == C.DPI_NATIVE_TYPE_BYTES && attr.OracleTypeNum == C.DPI_ORACLE_TYPE_NUMBER {\n\t\tvar a [39]byte\n\t\tC.dpiData_setBytes(&data.dpiData, (*C.char)(unsafe.Pointer(&a[0])), C.uint32_t(len(a)))\n\t}\n\n\t//fmt.Printf(\"getAttributeValue(%p, %p, %d, %+v)\\n\", O.dpiObject, attr.dpiObjectAttr, data.NativeTypeNum, data.dpiData)\n\tif C.dpiObject_getAttributeValue(O.dpiObject, attr.dpiObjectAttr, data.NativeTypeNum, &data.dpiData) == C.DPI_FAILURE {\n\t\treturn errors.Errorf(\"getAttributeValue(%q, obj=%+v, attr=%+v, typ=%d): %w\", name, O, attr.dpiObjectAttr, data.NativeTypeNum, O.getError())\n\t}\n\t//fmt.Printf(\"getAttributeValue(%p, %q=%p, %d, %+v)\\n\", O.dpiObject, attr.Name, attr.dpiObjectAttr, data.NativeTypeNum, data.dpiData)\n\treturn nil\n}",
"func (e *Element) FindAllWithAttrs(tagName string, attrs Attributes) []*Element {\n\treturn e.findAll(tagName, attrs)\n}",
"func (o *ObjectNode) getObjectXAttr(w http.ResponseWriter, r *http.Request) {\n\t// TODO: implement 'getObjectXAttr'\n}",
"func Attrs(attr ...Attribute) []Attribute {\n\treturn attr\n}",
"func (obj *Edge) GetAttributes() ([]types.TGAttribute, types.TGError) {\n\treturn obj.getAttributes()\n}",
"func (o *Giveaway) GetAttributes() map[string]interface{} {\n\tif o == nil || o.Attributes == nil {\n\t\tvar ret map[string]interface{}\n\t\treturn ret\n\t}\n\treturn *o.Attributes\n}",
"func (e *Element) FindWithAttrs(tagName string, attrs Attributes) *Element {\n\treturn e.findOne(tagName, attrs)\n}",
"func (m *Device) GetAttributes() (val map[string]interface{}, set bool) {\n\tif m.Attributes == nil {\n\t\treturn\n\t}\n\n\treturn *m.Attributes, true\n}",
"func (m *Smart) getAttributes(acc telegraf.Accumulator, devices []string) {\n\tvar wg sync.WaitGroup\n\twg.Add(len(devices))\n\n\tfor _, device := range devices {\n\t\tgo gatherDisk(acc, m.UseSudo, m.Attributes, m.Path, m.Nocheck, device, &wg)\n\t}\n\n\twg.Wait()\n}",
"func (d *cudaDevice) GetAttributes() (map[string]interface{}, error) {\n\treturn nil, fmt.Errorf(\"GetAttributes is not supported for CUDA devices\")\n}",
"func (r *GetAttrsResult) String() map[string]string {\n\tif r.attrs == nil {\n\t\treturn nil\n\t}\n\tattrs := make(map[string]string, len(r.attrs))\n\tfor _, attr := range r.attrs {\n\t\tkey := string(attr.key)\n\t\tif string(attr.key[len(attr.key)-1]) == string(\"\\u0000\") {\n\t\t\tkey = string(attr.key[:len(attr.key)-1])\n\t\t}\n\t\tval := string(attr.val)\n\t\tif key == \"expire\" || key == \"mtime\" {\n\t\t\tif unixTime, err := getUnixTime(attr.val); err == nil {\n\t\t\t\tval = strconv.FormatUint(unixTime, 10)\n\t\t\t}\n\t\t}\n\t\tattrs[key] = val\n\t}\n\treturn attrs\n}",
"func (o *NodeUpdate) GetAttributes() []map[string]interface{} {\n\tif o == nil || o.Attributes == nil {\n\t\tvar ret []map[string]interface{}\n\t\treturn ret\n\t}\n\treturn *o.Attributes\n}",
"func (m *MockGCS) ObjectAttrs(arg0 string) (*storage.ObjectAttrs, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ObjectAttrs\", arg0)\n\tret0, _ := ret[0].(*storage.ObjectAttrs)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}",
"func (t *Transaction) GetAttributes(typ AttrType) []Attribute {\n\tvar result []Attribute\n\tfor _, attr := range t.Attributes {\n\t\tif attr.Type == typ {\n\t\t\tresult = append(result, attr)\n\t\t}\n\t}\n\treturn result\n}",
"func (mq *LinuxMessageQueue) getAttrs() (*linuxMqAttr, error) {\n\tattrs := new(linuxMqAttr)\n\tif err := mq_getsetattr(mq.ID(), nil, attrs); err != nil {\n\t\treturn nil, errors.Wrap(err, \"mq_getsetattr failed\")\n\t}\n\treturn attrs, nil\n}",
"func (w *Wireguard) Attrs() *netlink.LinkAttrs {\n\treturn w.attrs\n}",
"func (c *DOM) GetAttributesWithParams(v *DOMGetAttributesParams) ([]string, error) {\n\tresp, err := gcdmessage.SendCustomReturn(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: \"DOM.getAttributes\", Params: v})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar chromeData struct {\n\t\tResult struct {\n\t\t\tAttributes []string\n\t\t}\n\t}\n\n\tif resp == nil {\n\t\treturn nil, &gcdmessage.ChromeEmptyResponseErr{}\n\t}\n\n\t// test if error first\n\tcerr := &gcdmessage.ChromeErrorResponse{}\n\tjson.Unmarshal(resp.Data, cerr)\n\tif cerr != nil && cerr.Error != nil {\n\t\treturn nil, &gcdmessage.ChromeRequestErr{Resp: cerr}\n\t}\n\n\tif err := json.Unmarshal(resp.Data, &chromeData); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn chromeData.Result.Attributes, nil\n}",
"func (e *Environment) Attr(environmentName, attr string) ([]Attr, error) {\n\n\targkeys := []string{\"attr\"}\n\targvalues := []interface{}{attr}\n\tbaseCommand := fmt.Sprintf(\"list environment attr %s\", environmentName)\n\n\tc, err := cmd.ArgsExpander(baseCommand, argkeys, argvalues)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb, err := cmd.RunCommand(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tattrs := []Attr{}\n\terr = json.Unmarshal(b, &attrs)\n\tif err != nil {\n\t\t// it may have been just an empty output from the Frontend\n\t\tnullOutput := NullOutput{}\n\t\terr = json.Unmarshal(b, &nullOutput)\n\t\tif err != nil {\n\t\t\t// if we still can't recognize the output, return an error\n\t\t\treturn nil, err\n\t\t}\n\t\treturn attrs, err\n\t}\n\treturn attrs, err\n}",
"func (ns Nodes) Attrs(key string) []string {\n\treturn getAttrs(ns, key)\n}",
"func (class *GenericClass) Attrs() *ClassAttrs {\n\treturn &class.ClassAttrs\n}",
"func GetBusAttributes(LicenseNo string)(models.Attributes, error){\n\tvar result models.Attributes\n\terr := DB.QueryRow(\"SELECT PathNo, AC, Availability FROM busattributes WHERE LicenseNo=?\", LicenseNo).Scan(\n\t\t&result.PathNo,\n\t\t&result.AC,\n\t\t&result.Availability,\n\t)\n\tif err != nil{\n\t\treturn result, err\n\t}\n\treturn result, nil\n}",
"func (repo *Repository) GetAttr(path, name string, flags ...AttrFlag) (string, error) {\n\tvar value [1]int8\n\tcvalue := (*C.char)(&value[0])\n\tcpath := C.CString(path)\n\tdefer C.free(unsafe.Pointer(cpath))\n\tcname := C.CString(name)\n\tdefer C.free(unsafe.Pointer(cname))\n\n\tvar cflags C.uint32_t\n\tfor _, flag := range flags {\n\t\tcflags |= C.uint32_t(flag)\n\t}\n\n\tecode := C.git_attr_get(&cvalue, repo.git_repository, cflags, cpath, cname)\n\tif ecode != git_SUCCESS {\n\t\treturn \"\", gitError()\n\t}\n\treturn C.GoString(cvalue), nil\n}",
"func (n Node) Attrs() attrs.Attrs {\n\treturn n.attrs\n}",
"func (n *UseList) Attributes() map[string]interface{} {\n\treturn nil\n}",
"func (res *Resource) GetMetas(attrs []string) []resource.Metaor {\n\tif len(attrs) == 0 {\n\t\tattrs = res.allAttrs()\n\t}\n\tvar showSections, ignoredAttrs []string\n\tfor _, attr := range attrs {\n\t\tif strings.HasPrefix(attr, \"-\") {\n\t\t\tignoredAttrs = append(ignoredAttrs, strings.TrimLeft(attr, \"-\"))\n\t\t} else {\n\t\t\tshowSections = append(showSections, attr)\n\t\t}\n\t}\n\n\tprimaryKey := res.PrimaryFieldName()\n\n\tmetas := []resource.Metaor{}\n\nAttrs:\n\tfor _, attr := range showSections {\n\t\tfor _, a := range ignoredAttrs {\n\t\t\tif attr == a {\n\t\t\t\tcontinue Attrs\n\t\t\t}\n\t\t}\n\n\t\tvar meta *Meta\n\t\tfor _, m := range res.Metas {\n\t\t\tif m.GetName() == attr {\n\t\t\t\tmeta = m\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif meta == nil {\n\t\t\tmeta = &Meta{Name: attr, baseResource: res}\n\t\t\tif attr == primaryKey {\n\t\t\t\tmeta.Type = \"hidden\"\n\t\t\t}\n\t\t\tmeta.updateMeta()\n\t\t}\n\n\t\tmetas = append(metas, meta)\n\t}\n\n\treturn metas\n}",
"func (ifi *Interface) idAttrs() []netlink.Attribute {\n\treturn []netlink.Attribute{\n\t\t{\n\t\t\tType: unix.NL80211_ATTR_IFINDEX,\n\t\t\tData: nlenc.Uint32Bytes(uint32(ifi.Index)),\n\t\t},\n\t\t{\n\t\t\tType: unix.NL80211_ATTR_MAC,\n\t\t\tData: ifi.HardwareAddr,\n\t\t},\n\t}\n}",
"func (a rawDef) rawParseObjAttr() def {\n objDef := def{}\n for _,attr := range a {\n oAttr := attrVal{}\n oAttrVal := strings.Split(attr[2], \",\")\n for _,val := range oAttrVal {\n oAttr.Add(strings.TrimSpace(val))\n }\n oAttr.Remove(\"\") // remove empty attr val silently\n objDef[attr[1]] = &oAttr // add attr to the def\n }\n return objDef\n}",
"func (i *Index) Attr(name string) (starlark.Value, error) {\n\tswitch name {\n\tcase \"name\":\n\t\treturn starlark.String(i.name), nil\n\tcase \"str\":\n\t\treturn &stringMethods{subject: i}, nil\n\t}\n\treturn nil, starlark.NoSuchAttrError(name)\n}",
"func (repo *Repository) GetAttributes(id string) (attributes []Attribute, err error) {\n\trows, err := repo.db.Query(\"SELECT attribute_id FROM product_attributes WHERE product_id LIKE $1\", id)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer func() { _ = rows.Close() }()\n\tvar attributeIds []int\n\tvar attr int\n\tfor rows.Next() {\n\t\terr = rows.Scan(&attr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tattributeIds = append(attributeIds, attr)\n\t}\n\n\tattributes = make([]Attribute, len(attributeIds))\n\tfor i := range attributeIds {\n\t\tattributes[i], err = repo.attributeName(attributeIds[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn attributes, rows.Err()\n}",
"func (o *LogContent) GetAttributes() map[string]interface{} {\n\tif o == nil || o.Attributes == nil {\n\t\tvar ret map[string]interface{}\n\t\treturn ret\n\t}\n\treturn o.Attributes\n}",
"func GetLogAttrs(text0 string, length0 int, level0 int, language0 *Language, log_attrs0 *LogAttr, attrs_len0 int) {\n\tvar text1 *C.char\n\tvar length1 C.int32_t\n\tvar level1 C.int32_t\n\tvar language1 *C.PangoLanguage\n\tvar log_attrs1 *C.PangoLogAttr\n\tvar attrs_len1 C.int32_t\n\ttext1 = _GoStringToGString(text0)\n\tdefer C.free(unsafe.Pointer(text1))\n\tlength1 = C.int32_t(length0)\n\tlevel1 = C.int32_t(level0)\n\tlanguage1 = (*C.PangoLanguage)(unsafe.Pointer(language0))\n\tlog_attrs1 = (*C.PangoLogAttr)(unsafe.Pointer(log_attrs0))\n\tattrs_len1 = C.int32_t(attrs_len0)\n\tC.pango_get_log_attrs(text1, length1, level1, language1, log_attrs1, attrs_len1)\n}",
"func getAttrList(selection *goquery.Selection, attrName string) []string {\n\tres := selection.Map(func(ind int, s *goquery.Selection) string {\n\t\tattr, _ := s.Attr(attrName)\n\t\treturn attr\n\t})\n\treturn removeEmpty(res)\n}",
"func ReadCustomAttributes(rows *sql.Rows, a *CustomAttribute) error {\n\treturn rows.Scan(&a.CID, &a.BID, &a.Type, &a.Name, &a.Value, &a.Units, &a.CreateTS, &a.CreateBy, &a.LastModTime, &a.LastModBy)\n}",
"func (s *Store) Attrs() roachpb.Attributes {\n\treturn s.engine.Attrs()\n}",
"func (res *Resource) SortableAttrs(columns ...string) []string {\n\tif len(columns) != 0 || res.sortableAttrs == nil {\n\t\tif len(columns) == 0 {\n\t\t\tcolumns = res.ConvertSectionToStrings(res.indexSections)\n\t\t}\n\t\tres.sortableAttrs = &[]string{}\n\t\tscope := res.GetAdmin().Config.DB.NewScope(res.Value)\n\t\tfor _, column := range columns {\n\t\t\tif field, ok := scope.FieldByName(column); ok && field.DBName != \"\" {\n\t\t\t\tattrs := append(*res.sortableAttrs, column)\n\t\t\t\tres.sortableAttrs = &attrs\n\t\t\t}\n\t\t}\n\t}\n\treturn *res.sortableAttrs\n}",
"func (o ThingTypePropertiesPtrOutput) SearchableAttributes() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *ThingTypeProperties) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.SearchableAttributes\n\t}).(pulumi.StringArrayOutput)\n}",
"func (o ThingTypePropertiesOutput) SearchableAttributes() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ThingTypeProperties) []string { return v.SearchableAttributes }).(pulumi.StringArrayOutput)\n}",
"func (g *gcs) Attributes(ctx context.Context, remotePath string) (attributes interface{}, err error) {\n\tfile := g.bucket.Object(remotePath)\n\tattributes, err = file.Attrs(g.context)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}",
"func (o *object) Attr(i uint8) bool {\n\treturn o.Attributes[i/8]&(1<<(7-i%8)) != 0\n}",
"func (o *VirtualizationVmwareVirtualMachineAllOf) GetCustomAttributesOk() ([]string, bool) {\n\tif o == nil || o.CustomAttributes == nil {\n\t\treturn nil, false\n\t}\n\treturn o.CustomAttributes, true\n}",
"func objFields(obj interface{}, skipKey bool) (interface{}, []interface{}) {\n\tval := reflect.ValueOf(obj)\n\tt := reflect.TypeOf(obj)\n\ta := make([]interface{}, 0, t.NumField())\n\tvar key interface{}\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tf := t.Field(i)\n\t\tif len(f.Tag.Get(\"sql\")) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif f.Tag.Get(\"key\") == \"true\" {\n\t\t\tkey = val.Field(i).Interface()\n\t\t\tif skipKey {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\ta = append(a, val.Field(i).Interface())\n\t}\n\treturn key, a\n}",
"func (f *fs) GetAttr(name string, context *fuse.Context) (*fuse.Attr, fuse.Status) {\n\tlog.Printf(\"GetAttr '%s'\\n\", name)\n\tvar attr *fuse.Attr\n\tswitch {\n\tcase name == \"\": // Base directory\n\t\tm, err := f.client.Sys().ListMounts()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tattr = f.directoryAttr(1, 0755)\n\t\t}\n\t\tattr = f.directoryAttr(len(m), 0755)\n\tcase name == \"secret\":\n\t\tattr = f.directoryAttr(1, 0755)\n\tcase name == \"sys\":\n\t\tattr = f.directoryAttr(1, 0755)\n\tcase strings.HasPrefix(name, \"secret/\"):\n\t\ts, err := f.client.Logical().Read(name)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn nil, fuse.ENOENT\n\t\t}\n\n\t\tif s == nil || s.Data == nil {\n\t\t\tattr = f.directoryAttr(1, 0755)\n\t\t} else {\n\t\t\tattr = f.secretAttr(s.Data[\"value\"].(string) + \"\\n\")\n\t\t}\n\t}\n\n\tif attr != nil {\n\t\treturn attr, fuse.OK\n\t}\n\treturn nil, fuse.ENOENT\n}",
"func (c *jsiiProxy_CfnFilter) GetAtt(attributeName *string) awscdk.Reference {\n\tvar returns awscdk.Reference\n\n\t_jsii_.Invoke(\n\t\tc,\n\t\t\"getAtt\",\n\t\t[]interface{}{attributeName},\n\t\t&returns,\n\t)\n\n\treturn returns\n}",
"func (c *CheckboxBase) GetDrawingLabelAttributes() html5tag.Attributes {\n\ta := c.LabelAttributes().Copy()\n\n\t// copy tooltip to wrapping label\n\tif title := c.Attribute(\"title\"); title != \"\" {\n\t\ta.Set(\"title\", title)\n\t}\n\n\tif c.IsDisabled() {\n\t\ta.AddClass(\"disabled\") // For styling the text associated with a disabled checkbox or control.\n\t}\n\n\tif !c.IsDisplayed() {\n\t\ta.SetStyle(\"display\", \"none\")\n\t}\n\n\ta.SetData(\"grel\", a.ID()) // make sure label gets replaced when drawing\n\treturn a\n}",
"func (t Type) GetAttrFrom(inst Instance, atomValue uint8) Value {\n\tfor instanceIndex, atomIndex := range t.Attributes {\n\t\tif atomIndex == atomValue {\n\t\t\treturn inst.Attributes[instanceIndex]\n\t\t}\n\t}\n\tpanic(\"Could not get attribute from instance!\")\n}",
"func (ac *AttrCache) GetAttr(options internal.GetAttrOptions) (*internal.ObjAttr, error) {\n\tlog.Trace(\"AttrCache::GetAttr : %s\", options.Name)\n\ttruncatedPath := internal.TruncateDirName(options.Name)\n\n\tac.cacheLock.RLock()\n\tvalue, found := ac.cacheMap[truncatedPath]\n\tac.cacheLock.RUnlock()\n\n\t// Try to serve the request from the attribute cache\n\tif found && value.valid() && time.Since(value.cachedAt).Seconds() < float64(ac.cacheTimeout) {\n\t\tif value.isDeleted() {\n\t\t\tlog.Debug(\"AttrCache::GetAttr : %s served from cache\", options.Name)\n\t\t\t// no entry if path does not exist\n\t\t\treturn &internal.ObjAttr{}, syscall.ENOENT\n\t\t} else {\n\t\t\t// IsMetadataRetrieved is false in the case of ADLS List since the API does not support metadata.\n\t\t\t// Once migration of ADLS list to blob endpoint is done (in future service versions), we can remove this.\n\t\t\t// options.RetrieveMetadata is set by CopyFromFile and WriteFile which need metadata to ensure it is preserved.\n\t\t\tif value.getAttr().IsMetadataRetrieved() || (ac.noSymlinks && !options.RetrieveMetadata) {\n\t\t\t\t// path exists and we have all the metadata required or we do not care about metadata\n\t\t\t\tlog.Debug(\"AttrCache::GetAttr : %s served from cache\", options.Name)\n\t\t\t\treturn value.getAttr(), nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Get the attributes from next component and cache them\n\tpathAttr, err := ac.NextComponent().GetAttr(options)\n\n\tac.cacheLock.Lock()\n\tdefer ac.cacheLock.Unlock()\n\n\tif err == nil {\n\t\t// Retrieved attributes so cache them\n\t\tif len(ac.cacheMap) < maxTotalFiles {\n\t\t\tac.cacheMap[truncatedPath] = newAttrCacheItem(pathAttr, true, time.Now())\n\t\t}\n\t} else if err == syscall.ENOENT {\n\t\t// Path does not exist so cache a no-entry item\n\t\tac.cacheMap[truncatedPath] = newAttrCacheItem(&internal.ObjAttr{}, false, time.Now())\n\t}\n\n\treturn pathAttr, err\n}",
"func objToNames(obj interface{}, names []string, tag string) []string {\n\tvar typ reflect.Type\n\n\tif sf, ok := obj.(reflect.StructField); ok {\n\t\ttyp = sf.Type\n\t} else {\n\t\ttyp = reflect.TypeOf(obj)\n\t\tif typ.Kind() == reflect.Ptr {\n\t\t\ttyp = typ.Elem()\n\t\t}\n\t}\n\n\tfor i := 0; i < typ.NumField(); i++ {\n\t\tfield := typ.Field(i)\n\n\t\tif field.Type.Kind() == reflect.Struct {\n\t\t\tnames = objToNames(field, names, tag)\n\t\t\tcontinue\n\t\t}\n\n\t\t// If tag is passed to the function, we only append if the field is tagged and that it matches tag.\n\t\tif tag == \"\" || field.Tag.Get(tag) != \"\" {\n\t\t\tnames = append(names, field.Name)\n\t\t}\n\t}\n\n\treturn names\n}",
"func TestAttrStore_Attrs(t *testing.T) {\n\ts := MustOpenAttrStore()\n\tdefer s.Close()\n\n\t// Set attributes.\n\tif err := s.SetAttrs(1, map[string]interface{}{\"A\": 100, \"C\": -27}); err != nil {\n\t\tt.Fatal(err)\n\t} else if err := s.SetAttrs(2, map[string]interface{}{\"A\": uint64(200)}); err != nil {\n\t\tt.Fatal(err)\n\t} else if err := s.SetAttrs(1, map[string]interface{}{\"B\": \"VALUE\"}); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Retrieve attributes for column #1.\n\tif m, err := s.Attrs(1); err != nil {\n\t\tt.Fatal(err)\n\t} else if !reflect.DeepEqual(m, map[string]interface{}{\"A\": int64(100), \"B\": \"VALUE\", \"C\": int64(-27)}) {\n\t\tt.Fatalf(\"unexpected attrs(1): %#v\", m)\n\t}\n\n\t// Retrieve attributes for column #2.\n\tif m, err := s.Attrs(2); err != nil {\n\t\tt.Fatal(err)\n\t} else if !reflect.DeepEqual(m, map[string]interface{}{\"A\": int64(200)}) {\n\t\tt.Fatalf(\"unexpected attrs(2): %#v\", m)\n\t}\n}",
"func (attestedClaim *AttestedClaim) getRawAttributes() []*big.Int {\n\treturn attestedClaim.Credential.Attributes[1:]\n}",
"func (n *Use) Attributes() map[string]interface{} {\n\treturn nil\n}",
"func (a *Client) GetAttributes(params *GetAttributesParams) (*GetAttributesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetAttributesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"get_attributes\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/rest/v1/attributes\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetAttributesReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetAttributesOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for get_attributes: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}",
"func (fsys *FS) Getattr(path string, stat *fuse.Stat_t, fh uint64) (errc int) {\n\tdefer fs.Trace(path, \"fh=0x%X\", fh)(\"errc=%v\", &errc)\n\tnode, errc := fsys.getNode(path, fh)\n\tif errc == 0 {\n\t\terrc = fsys.stat(node, stat)\n\t}\n\treturn\n}",
"func (svc *DynamoAccessor) Get(ctx context.Context,\n\tkeyPath string,\n\tdestObject interface{}) error {\n\tgetItemInput := &dynamodb.GetItemInput{\n\t\tTableName: aws.String(svc.dynamoTableName()),\n\t\tKey: dynamoKeyValueAttrMap(keyPath),\n\t}\n\n\tgetItemResult, getItemResultErr := svc.dynamoSvc(ctx).GetItemWithContext(ctx, getItemInput)\n\tif getItemResultErr != nil {\n\t\treturn getItemResultErr\n\t}\n\treturn dynamodbattribute.UnmarshalMap(getItemResult.Item, destObject)\n}",
"func (o *LDAPIdentityProvider) GetAttributes() (value *LDAPAttributes, ok bool) {\n\tok = o != nil && o.bitmap_&4 != 0\n\tif ok {\n\t\tvalue = o.attributes\n\t}\n\treturn\n}",
"func (i *Index) AttrNames() []string {\n\treturn []string{\"name\", \"str\"}\n}",
"func NewModelAttrs(schema ModelData) ModelAttrs {\n\tattrs := make(ModelAttrs)\n\n\t//loop through the map and generate the ModelAttrs\n\tfor id, to := range schema {\n\t\tattrs[id] = NewModelAttr(id, id, to)\n\t}\n\n\treturn attrs\n}",
"func containsAttrs(base Attributes, attrs Attributes) bool {\n\tfor key, val := range attrs {\n\t\tif v, ok := base[key]; !ok || v != val {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}",
"func AttributesAll(ctx context.Context) schema.Attribute {\n\treturn Attributes(ctx, Opts{\n\t\tCreate: true,\n\t\tRead: true,\n\t\tUpdate: true,\n\t\tDelete: true,\n\t})\n}",
"func (o *Giveaway) GetAttributesOk() (map[string]interface{}, bool) {\n\tif o == nil || o.Attributes == nil {\n\t\tvar ret map[string]interface{}\n\t\treturn ret, false\n\t}\n\treturn *o.Attributes, true\n}",
"func getAllAttributes(elements []goquery.Selection, attribute_name string) ([]string, error) {\n\tall_attributes := make([len(elements)]string)\n\telements.Each(func(index int, element *goquery.Selection) {\n\t\tattribute, attribute_exists := element.Attr(attribute_name)\n\t\tif attribute_exists {\n\t\t\tall_attributes.append(attr)\n\t\t}\n\t})\n\treturn all_attributes\n}",
"func (o *Service) GetAttributes() map[string]string {\n\tif o == nil || o.Attributes == nil {\n\t\tvar ret map[string]string\n\t\treturn ret\n\t}\n\treturn *o.Attributes\n}",
"func (b *Container) ExposeAttributes(i interface{}, pattern string, name ...string) (ret Bindings) {\n\ti = resolvePointer(i)\n\n\t// Find name either by args or by interface type.\n\tvar in string\n\tif len(name) > 0 {\n\t\tin = name[0]\n\t} else {\n\t\tin = findInterfaceName(i)\n\t}\n\n\tt := reflect.TypeOf(i)\n\tc := 0\n\tret = make(Bindings, t.Elem().NumField())\n\tfor x := 0; x < t.Elem().NumField(); x++ {\n\t\tan := t.Elem().Field(x).Name\n\n\t\tif f, _ := regexp.Match(pattern, []byte(an)); len(pattern) == 0 || f {\n\t\t\tpm := b.newAttributeBinding(i, x, in, an)\n\t\t\tret[c] = pm\n\t\t\tc++\n\t\t}\n\t}\n\n\tif c > 0 {\n\t\tb.revision++\n\t}\n\treturn ret[:c]\n}",
"func (w *wrapper) Getattr(path string, stat *fuse.Stat_t, fd uint64) int {\n\tfi, err := w.underlying.Stat(path)\n\tif err != nil {\n\t\treturn convertError(err)\n\t}\n\tfileInfoToStat(fi, stat)\n\treturn 0\n}",
"func cmdAttributeList(c *cli.Context) error {\n\tif err := adm.VerifyNoArgument(c); err != nil {\n\t\treturn err\n\t}\n\n\treturn adm.Perform(`get`, `/attribute/`, `list`, nil, c)\n}",
"func (o *Object) Attribute(name string) *AttributeExpr {\n\tfor _, nat := range *o {\n\t\tif nat.Name == name {\n\t\t\treturn nat.Attribute\n\t\t}\n\t}\n\treturn nil\n}",
"func getModelInfo(o interface{}) (*modelInfo, error) {\n\tmv, err := getModelValue(o)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar mi = modelInfo{\n\t\ttable: reflect.New(mv.Type()).Interface().(IModel).Table(),\n\t\tvalue: mv,\n\t}\n\n\tfor i := 0; i < mv.NumField(); i++ {\n\t\tif !mv.Field(i).CanInterface() {\n\t\t\tcontinue // skip unexported fields\n\t\t}\n\t\tmf, err := getFieldInfo(mv, i)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmi.fields = append(mi.fields, mf)\n\t}\n\treturn &mi, nil\n}",
"func (c cacheObjects) getMetadata(objInfo ObjectInfo) map[string]string {\n\tmetadata := make(map[string]string)\n\tmetadata[\"etag\"] = objInfo.ETag\n\tmetadata[\"content-type\"] = objInfo.ContentType\n\tmetadata[\"content-encoding\"] = objInfo.ContentEncoding\n\n\tfor key, val := range objInfo.UserDefined {\n\t\tmetadata[key] = val\n\t}\n\treturn metadata\n}",
"func (e *FileEntries) CheckAttrs() error {\n\tcmd := exec.Command(\n\t\t\"git\",\n\t\t\"check-attr\",\n\t\t\"--stdin\",\n\t\t\"filter\",\n\t)\n\n\tfeeder, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"getting input pipe: %w\", err)\n\t}\n\n\treceiver, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"getting output pipe: %w\", err)\n\t}\n\n\terrorstream, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"getting error pipe: %w\", err)\n\t}\n\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"starting git command: %w\", err)\n\t}\n\n\tgo e.feedWithFileNames(feeder)\n\n\tgo e.logErrors(errorstream)\n\n\terr = e.readCheckAttrs(receiver)\n\tif err != nil {\n\t\te.AddError(\"git command output\", err)\n\t}\n\n\treturn cmd.Wait()\n}",
"func GetFieldMap(obj interface{}) (ret map[string]string) {\n\tval := reflect.ValueOf(obj).Elem()\n\tret = make(map[string]string)\n\tfor i := 0; i < val.NumField(); i++ {\n\t\ttypeField := val.Type().Field(i)\n\t\tkey := strings.ToLower(typeField.Name)\n\t\tif typeField.PkgPath != \"\" {\n\t\t\t// Private method\n\t\t\tcontinue\n\t\t} else {\n\t\t\tret[key] = typeField.Name\n\t\t}\n\t}\n\treturn\n}",
"func (n *node) Attr(ctx context.Context, a *fuse.Attr) error {\n\tfi := n.te.Stat()\n\ta.Valid = 30 * 24 * time.Hour\n\ta.Inode = inodeOfEnt(n.te)\n\ta.Size = uint64(fi.Size())\n\ta.Blocks = a.Size / 512\n\ta.Mtime = fi.ModTime()\n\ta.Mode = fi.Mode()\n\ta.Uid = uint32(n.te.Uid)\n\ta.Gid = uint32(n.te.Gid)\n\tif debug {\n\t\tlog.Printf(\"attr of %s: %s\", n.te.Name, *a)\n\t}\n\treturn nil\n}"
] | [
"0.746335",
"0.69868463",
"0.6534447",
"0.6527506",
"0.61508244",
"0.60428786",
"0.562088",
"0.55375737",
"0.55142826",
"0.5511392",
"0.55067647",
"0.54565465",
"0.5419644",
"0.5417537",
"0.53777504",
"0.5361932",
"0.5348078",
"0.5327245",
"0.5284654",
"0.5237316",
"0.5228544",
"0.51941884",
"0.51825905",
"0.511578",
"0.511578",
"0.50336814",
"0.5029512",
"0.50126415",
"0.49990356",
"0.49982202",
"0.49974424",
"0.49829894",
"0.4962808",
"0.4936746",
"0.4934411",
"0.49313238",
"0.49162218",
"0.49071732",
"0.48673856",
"0.48591083",
"0.48564297",
"0.48471376",
"0.4843182",
"0.48424965",
"0.4839691",
"0.4837469",
"0.48371556",
"0.48298582",
"0.48076463",
"0.48014018",
"0.47882533",
"0.47764078",
"0.47705355",
"0.4752097",
"0.47457287",
"0.4738921",
"0.47387937",
"0.47163412",
"0.4711177",
"0.46961692",
"0.4687001",
"0.4682346",
"0.46762124",
"0.46756914",
"0.4655771",
"0.46439722",
"0.4640724",
"0.4640647",
"0.46168545",
"0.46150166",
"0.4608576",
"0.46049199",
"0.46005234",
"0.45991203",
"0.45875052",
"0.4577505",
"0.45774433",
"0.45611054",
"0.45510125",
"0.45482633",
"0.4547798",
"0.45369324",
"0.4533175",
"0.4531332",
"0.45304435",
"0.4528467",
"0.4523874",
"0.45046362",
"0.44971928",
"0.44932863",
"0.44900745",
"0.44836557",
"0.4479815",
"0.4474252",
"0.44649884",
"0.44566268",
"0.44549567",
"0.44459933",
"0.4441735",
"0.4438603"
] | 0.7109358 | 1 |
NewStorage creates a new rest.Storage responsible for accessing ServiceClass resources | func NewStorage(opts generic.RESTOptions) rest.Storage {
prefix := "/" + opts.ResourcePrefix
newListFunc := func() runtime.Object { return &servicecatalog.ServiceClassList{} }
storageInterface, dFunc := opts.Decorator(
opts.StorageConfig,
1000,
&servicecatalog.ServiceClass{},
prefix,
serviceclassRESTStrategies,
newListFunc,
nil,
storage.NoTriggerPublisher,
)
store := registry.Store{
NewFunc: func() runtime.Object {
return &servicecatalog.ServiceClass{}
},
// NewListFunc returns an object capable of storing results of an etcd list.
NewListFunc: newListFunc,
// KeyRootFunc places this resource at the prefix for this resource;
// not namespaced.
KeyRootFunc: func(ctx api.Context) string {
return prefix
},
// Produces a path that etcd understands by combining the object's
// name with the prefix.
KeyFunc: func(ctx api.Context, name string) (string, error) {
return registry.NoNamespaceKeyFunc(ctx, prefix, name)
},
// Retrieve the name field of the resource.
ObjectNameFunc: func(obj runtime.Object) (string, error) {
return obj.(*servicecatalog.ServiceClass).Name, nil
},
// Used to match objects based on labels/fields for list.
PredicateFunc: Match,
// QualifiedResource should always be plural
QualifiedResource: api.Resource("serviceclasses"),
CreateStrategy: serviceclassRESTStrategies,
UpdateStrategy: serviceclassRESTStrategies,
DeleteStrategy: serviceclassRESTStrategies,
Storage: storageInterface,
DestroyFunc: dFunc,
}
return &store
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func newServiceStorage() *ServiceStorage {\n\ts := new(ServiceStorage)\n\ts.cache = cache.NewCache(24 * time.Hour)\n\treturn s\n}",
"func NewStorage(cfg *api.Config, rootPath string, syncFrequency time.Duration) (storage.Interface, error) {\n\tcfg.WaitTime = syncFrequency\n\n\t// Get a new client\n\tclient, err := api.NewClient(cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"creating consul client\")\n\t}\n\n\treturn &Client{\n\t\tv1: &v1client{\n\t\t\tupstreams: &upstreamsClient{\n\t\t\t\tbase: base.NewConsulStorageClient(rootPath+\"/upstreams\", client),\n\t\t\t},\n\t\t\tvirtualHosts: &virtualHostsClient{\n\t\t\t\tbase: base.NewConsulStorageClient(rootPath+\"/virtualhosts\", client),\n\t\t\t},\n\t\t},\n\t}, nil\n}",
"func NewStorage(namespace, name string) (*Storage, error) {\n\tif err := k8sutil.CreateCRD(name); err != nil {\n\t\treturn nil, err\n\t}\n\tcli := k8sutil.NewRESTClient()\n\treturn &Storage{\n\t\tNamespace: namespace,\n\t\tName: strings.ToLower(name),\n\t\trestcli: cli,\n\t}, nil\n}",
"func newStorage(account *account, prov provider.Account, cfg *config.Storage) (*storage, error) {\n\tlog.Debug(\"Initializing Storage\")\n\n\t// Validate the config.Storage object.\n\tif cfg.Buckets == nil {\n\t\treturn nil, fmt.Errorf(\"The buckets element is missing from the storage configuration\")\n\t}\n\n\ts := &storage{\n\t\tResources: resource.NewResources(),\n\t\tStorage: cfg,\n\t\taccount: account,\n\t}\n\n\tvar err error\n\ts.providerStorage, err = prov.NewStorage(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.buckets, err = newBuckets(s, prov, cfg.Buckets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.Append(s.buckets)\n\treturn s, nil\n}",
"func NewStorage(s map[string]interface{}) (Storage, error) {\n\tstype, ok := s[\"Type\"].(string)\n\tif !ok || stype == \"\" {\n\t\treturn nil, errors.New(\"Template do not have Storage type\")\n\t}\n\n\tswitch stype {\n\tcase \"Local\":\n\t\treturn newStorageLocal(s), nil\n\tcase \"S3\":\n\t\treturn newStorageS3(s)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unexecepted Storage type: %v\", stype)\n\t}\n}",
"func NewStorage(config StorageConfig) (spec.Storage, error) {\n\tnewStorage := &storage{\n\t\tStorageConfig: config,\n\n\t\tID: id.MustNew(),\n\t\tShutdownOnce: sync.Once{},\n\t\tType: ObjectType,\n\t}\n\n\t// Dependencies.\n\tif newStorage.Log == nil {\n\t\treturn nil, maskAnyf(invalidConfigError, \"logger must not be empty\")\n\t}\n\tif newStorage.Pool == nil {\n\t\treturn nil, maskAnyf(invalidConfigError, \"connection pool must not be empty\")\n\t}\n\t// Settings.\n\tif newStorage.BackOffFactory == nil {\n\t\treturn nil, maskAnyf(invalidConfigError, \"backoff factory must not be empty\")\n\t}\n\tif newStorage.Prefix == \"\" {\n\t\treturn nil, maskAnyf(invalidConfigError, \"prefix must not be empty\")\n\t}\n\n\tnewStorage.Log.Register(newStorage.GetType())\n\n\treturn newStorage, nil\n}",
"func NewStorage() *Storage {\r\n\treturn new(Storage)\r\n}",
"func newStorageObject(URL string, source interface{}, fileInfo os.FileInfo) storage.Object {\n\tabstract := storage.NewAbstractStorageObject(URL, source, fileInfo)\n\tresult := &object{\n\t\tAbstractObject: abstract,\n\t}\n\tresult.AbstractObject.Object = result\n\treturn result\n}",
"func NewStorage() *Storage {\n\tstorageHandler = new(Storage)\n\n\treturn storageHandler\n}",
"func NewStorage(t mockConstructorTestingTNewStorage) *Storage {\n\tmock := &Storage{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}",
"func NewStorage(t mockConstructorTestingTNewStorage) *Storage {\n\tmock := &Storage{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}",
"func NewStorage(l log.Logger, reg prometheus.Registerer, stCallback startTimeCallback, walDir string, flushDeadline time.Duration, sm ReadyScrapeManager) *Storage {\n\tif l == nil {\n\t\tl = log.NewNopLogger()\n\t}\n\tlogger := logging.Dedupe(l, 1*time.Minute)\n\n\ts := &Storage{\n\t\tlogger: logger,\n\t\tlocalStartTimeCallback: stCallback,\n\t}\n\ts.rws = NewWriteStorage(s.logger, reg, walDir, flushDeadline, sm)\n\treturn s\n}",
"func NewStorage(cfg *Config) *Storage {\n\tif cfg.Engine == nil {\n\t\tlog.Fatalln(\"Cannot create a ops proxy without an engine\")\n\t}\n\tif cfg.App == nil {\n\t\tnrConfig := newrelic.NewConfig(\"widget\", \"\")\n\t\tnrConfig.Enabled = false\n\t\tapp, err := newrelic.NewApplication(nrConfig)\n\t\tif err != nil {\n\t\t\tlogrus.WithField(\"error\", err).Fatalln(\"could not create dummy new relic app\")\n\t\t}\n\t\tcfg.App = app\n\t}\n\treturn &Storage{engine: cfg.Engine, newrelic: cfg.App}\n}",
"func NewStorage() *Storage {\n\treturn &Storage{}\n}",
"func NewStorageService(conf *myconf.Config) (*StorageService, error) {\n\tbranch := util.GetRequiredEnv(\"BRANCH\")\n\tvar svc *minio.Client\n\tvar err error\n\tif branch != \"production\" {\n\t\tcredentials, err := myaws.NewSession().Config.Credentials.Get()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tendPoint := \"s3.amazonaws.com\"\n\t\tuseSSL := true\n\t\tsvc, err = minio.NewWithRegion(\n\t\t\tendPoint,\n\t\t\tcredentials.AccessKeyID,\n\t\t\tcredentials.SecretAccessKey,\n\t\t\tuseSSL,\n\t\t\tmyaws.AWSRegion,\n\t\t)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tiam := minioCreds.NewIAM(\"\")\n\t\tendPoint := \"s3.amazonaws.com\"\n\t\tuseSSL := true\n\t\tsvc, err = minio.NewWithCredentials(\n\t\t\tendPoint,\n\t\t\tiam,\n\t\t\tuseSSL,\n\t\t\tmyaws.AWSRegion,\n\t\t)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// svc.TraceOn(nil)\n\treturn &StorageService{\n\t\tbucket: conf.AWSUploadBucket,\n\t\tsvc: svc,\n\t}, nil\n}",
"func NewStorage() Storage {\n\treturn &storage{}\n}",
"func New(configs ...Configurator) (*Storage, error) {\n\tinstance := &Storage{}\n\tfor _, configure := range configs {\n\t\tif err := configure(instance); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn instance, nil\n}",
"func NewStorage(cat *repository.MongoCatalog, cache *rediscache.Redis) *Storage {\n\treturn &Storage{\n\t\tcat,\n\t\tcache,\n\t}\n}",
"func NewStorageAPI(g func(ctx context.Context) (*grpc.ClientConn, error)) *StorageAPI {\n\treturn &StorageAPI{g}\n}",
"func New(o *Options) *Storage {\n\ts := &Storage{}\n\tif o.GraphiteAddress != \"\" {\n\t\tc := graphite.NewClient(\n\t\t\to.GraphiteAddress, o.GraphiteTransport,\n\t\t\to.StorageTimeout, o.GraphitePrefix)\n\t\ts.queues = append(s.queues, NewStorageQueueManager(c, defaultConfig))\n\t}\n\tif o.OpentsdbURL != \"\" {\n\t\tc := opentsdb.NewClient(o.OpentsdbURL, o.StorageTimeout)\n\t\ts.queues = append(s.queues, NewStorageQueueManager(c, defaultConfig))\n\t}\n\tif o.InfluxdbURL != nil {\n\t\tconf := influx.Config{\n\t\t\tURL: *o.InfluxdbURL,\n\t\t\tUsername: o.InfluxdbUsername,\n\t\t\tPassword: o.InfluxdbPassword,\n\t\t\tTimeout: o.StorageTimeout,\n\t\t}\n\t\tc := influxdb.NewClient(conf, o.InfluxdbDatabase, o.InfluxdbRetentionPolicy)\n\t\tprometheus.MustRegister(c)\n\t\ts.queues = append(s.queues, NewStorageQueueManager(c, defaultConfig))\n\t}\n\tif o.GenericURL != \"\" {\n\t\theaders := http.Header{}\n\t\tif o.GenericHeaderName != \"\" {\n\t\t\theaders.Add(o.GenericHeaderName, o.GenericHeaderValue)\n\t\t}\n\t\tc := generic.NewClient(o.GenericURL, headers, o.StorageTimeout)\n\t\ts.queues = append(s.queues, NewStorageQueueManager(c, defaultConfig))\n\t}\n\tif len(s.queues) == 0 {\n\t\treturn nil\n\t}\n\treturn s\n}",
"func (p StorageProvider) NewRESTStorage(\n\tapiResourceConfigSource serverstorage.APIResourceConfigSource,\n\trestOptionsGetter generic.RESTOptionsGetter,\n) (*genericapiserver.APIGroupInfo, error) {\n\n\tstorage, err := p.v1beta1Storage(apiResourceConfigSource, restOptionsGetter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(servicecatalog.GroupName, api.Registry, api.Scheme, api.ParameterCodec, api.Codecs)\n\tapiGroupInfo.GroupMeta.GroupVersion = servicecatalogv1beta1.SchemeGroupVersion\n\n\tapiGroupInfo.VersionedResourcesStorageMap = map[string]map[string]rest.Storage{\n\t\tservicecatalogv1beta1.SchemeGroupVersion.Version: storage,\n\t}\n\n\treturn &apiGroupInfo, nil\n}",
"func newStorage() *storage {\n\tr := make(map[string][]byte)\n\treturn &storage{\n\t\trepository: r,\n\t}\n}",
"func Storage(config map[string]interface{}) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tstorage, err := storage.Create(config)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tc.Set(\"storage\", storage)\n\t\tc.Next()\n\t}\n}",
"func NewStorage(opts ...StorageOption) *Storage {\n\ts := &Storage{\n\t\tcr: config.DefaultManager,\n\t\tmu: sync.RWMutex{},\n\t}\n\tfor _, opt := range opts {\n\t\tif opt != nil {\n\t\t\topt(s)\n\t\t}\n\t}\n\treturn s\n}",
"func NewStorageAPI(spec *loads.Document) *StorageAPI {\n\treturn &StorageAPI{\n\t\thandlers: make(map[string]map[string]http.Handler),\n\t\tformats: strfmt.Default,\n\t\tdefaultConsumes: \"application/json\",\n\t\tdefaultProduces: \"application/json\",\n\t\tcustomConsumers: make(map[string]runtime.Consumer),\n\t\tcustomProducers: make(map[string]runtime.Producer),\n\t\tServerShutdown: func() {},\n\t\tspec: spec,\n\t\tServeError: errors.ServeError,\n\t\tBasicAuthenticator: security.BasicAuth,\n\t\tAPIKeyAuthenticator: security.APIKeyAuth,\n\t\tBearerAuthenticator: security.BearerAuth,\n\t\tJSONConsumer: runtime.JSONConsumer(),\n\t\tJSONProducer: runtime.JSONProducer(),\n\t\tAirlinesGetAirlinesHandler: airlines.GetAirlinesHandlerFunc(func(params airlines.GetAirlinesParams) middleware.Responder {\n\t\t\treturn middleware.NotImplemented(\"operation AirlinesGetAirlines has not yet been implemented\")\n\t\t}),\n\t\tAirportsGetAirportsHandler: airports.GetAirportsHandlerFunc(func(params airports.GetAirportsParams) middleware.Responder {\n\t\t\treturn middleware.NotImplemented(\"operation AirportsGetAirports has not yet been implemented\")\n\t\t}),\n\t\tLivenessGetLiveHandler: liveness.GetLiveHandlerFunc(func(params liveness.GetLiveParams) middleware.Responder {\n\t\t\treturn middleware.NotImplemented(\"operation LivenessGetLive has not yet been implemented\")\n\t\t}),\n\t\tReadinessGetReadyHandler: readiness.GetReadyHandlerFunc(func(params readiness.GetReadyParams) middleware.Responder {\n\t\t\treturn middleware.NotImplemented(\"operation ReadinessGetReady has not yet been implemented\")\n\t\t}),\n\t\tSchedulesGetSchedulesHandler: schedules.GetSchedulesHandlerFunc(func(params schedules.GetSchedulesParams) middleware.Responder {\n\t\t\treturn middleware.NotImplemented(\"operation SchedulesGetSchedules has not yet been implemented\")\n\t\t}),\n\t\tVersionGetVersionHandler: version.GetVersionHandlerFunc(func(params version.GetVersionParams) middleware.Responder {\n\t\t\treturn middleware.NotImplemented(\"operation VersionGetVersion has not yet been implemented\")\n\t\t}),\n\t\tAirlinesAddAirlineHandler: airlines.AddAirlineHandlerFunc(func(params airlines.AddAirlineParams) middleware.Responder {\n\t\t\treturn middleware.NotImplemented(\"operation AirlinesAddAirline has not yet been implemented\")\n\t\t}),\n\t\tAirportsAddAirportHandler: airports.AddAirportHandlerFunc(func(params airports.AddAirportParams) middleware.Responder {\n\t\t\treturn middleware.NotImplemented(\"operation AirportsAddAirport has not yet been implemented\")\n\t\t}),\n\t\tSchedulesAddScheduleHandler: schedules.AddScheduleHandlerFunc(func(params schedules.AddScheduleParams) middleware.Responder {\n\t\t\treturn middleware.NotImplemented(\"operation SchedulesAddSchedule has not yet been implemented\")\n\t\t}),\n\t\tSchedulesDeleteScheduleHandler: schedules.DeleteScheduleHandlerFunc(func(params schedules.DeleteScheduleParams) middleware.Responder {\n\t\t\treturn middleware.NotImplemented(\"operation SchedulesDeleteSchedule has not yet been implemented\")\n\t\t}),\n\t\tSchedulesGetScheduleHandler: schedules.GetScheduleHandlerFunc(func(params schedules.GetScheduleParams) middleware.Responder {\n\t\t\treturn middleware.NotImplemented(\"operation SchedulesGetSchedule has not yet been implemented\")\n\t\t}),\n\t\tSchedulesUpdateScheduleHandler: schedules.UpdateScheduleHandlerFunc(func(params schedules.UpdateScheduleParams) middleware.Responder {\n\t\t\treturn middleware.NotImplemented(\"operation SchedulesUpdateSchedule has not yet been implemented\")\n\t\t}),\n\t}\n}",
"func NewStorage(address common.Address, backend bind.ContractBackend) (*Storage, error) {\n\tcontract, err := bindStorage(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Storage{StorageCaller: StorageCaller{contract: contract}, StorageTransactor: StorageTransactor{contract: contract}, StorageFilterer: StorageFilterer{contract: contract}}, nil\n}",
"func NewStorage(address common.Address, backend bind.ContractBackend) (*Storage, error) {\n\tcontract, err := bindStorage(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Storage{StorageCaller: StorageCaller{contract: contract}, StorageTransactor: StorageTransactor{contract: contract}, StorageFilterer: StorageFilterer{contract: contract}}, nil\n}",
"func NewStorage(address common.Address, backend bind.ContractBackend) (*Storage, error) {\n\tcontract, err := bindStorage(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Storage{StorageCaller: StorageCaller{contract: contract}, StorageTransactor: StorageTransactor{contract: contract}, StorageFilterer: StorageFilterer{contract: contract}}, nil\n}",
"func NewStorage(conf *ConfService) (*goejdb.Ejdb, error) {\n\tvar storageConf StorageConfiguration\n\tconf.Get(&storageConf)\n\n\t// Create a new database file and open it\n\tdb, err := goejdb.Open(storageConf.DBName, goejdb.JBOWRITER|goejdb.JBOCREAT)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}",
"func New(ctx context.Context, storageConfig *config.StorageConfig) *Storage {\n\tctx, cancel := context.WithCancel(ctx)\n\treturn &Storage{\n\t\tctx: ctx,\n\t\tconfig: storageConfig,\n\t\tcancel: cancel,\n\t\tstate: Created,\n\t\tlog: logger.GetLogger(),\n\t}\n}",
"func NewRawStorage(config *storagebackend.ConfigForResource, newFunc func() runtime.Object) (storage.Interface, factory.DestroyFunc, error) {\n\treturn factory.Create(*config, newFunc)\n}",
"func NewStorage() (*Storage, error) {\n\tvar err error\n\n\ts := new(Storage)\n\n\t_, filename, _, _ := runtime.Caller(0)\n\tp := path.Dir(filename)\n\n\ts.db, err = scribble.New(p+dir, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s, nil\n}",
"func NewStorage() (*Storage, error) {\n\tvar err error\n\ts := new(Storage)\n\tcwd, _ := os.Getwd()\n\ts.db, err = scribble.New(cwd+viper.GetString(\"storage.basedir\"), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s, nil\n}",
"func NewStorage(first, second storage.Storage) (*Storage, error) {\n\treturn &Storage{first, second}, nil\n}",
"func newStorageImpl(db orm.DB) *storageImpl {\n\treturn &storageImpl{\n\t\tdb: db,\n\t}\n}",
"func newStorageLayer(disk string) (storage StorageAPI, err error) {\n\tif !strings.ContainsRune(disk, ':') || filepath.VolumeName(disk) != \"\" {\n\t\t// Initialize filesystem storage API.\n\t\treturn newPosix(disk)\n\t}\n\t// Initialize rpc client storage API.\n\treturn newRPCClient(disk)\n}",
"func FakeNewStorage() *fakeStorage {\n\treturn &fakeStorage{}\n}",
"func NewStorage(client *clientv3.Client, codec codec.Codec) storage.Store {\n\treturn &Storage{\n\t\tclient: client,\n\t\tcodec: codec,\n\t}\n}",
"func (c *S3StorageConfig) NewStorage() (Storage, error) {\n\treturn NewS3Storage(c, nil)\n}",
"func NewStorage(db *sql.DB) *Storage {\n\treturn &Storage{db}\n}",
"func CreateStorage(projectID, description, plan, facility, frequency string, size, count int) error {\n\tclient, err := NewExtPacketClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create a snapshot policy. If `count` is 0, we shall pass an empty object\n\tsnapshotPolicies := make([]*extpackngo.SnapshotPolicy, 1)\n\tif count != 0 {\n\t\tsnapshotPolicies = append(snapshotPolicies, &extpackngo.SnapshotPolicy{\n\t\t\tSnapshotFrequency: frequency,\n\t\t\tSnapshotCount: count})\n\t}\n\trequest := &extpackngo.StorageCreateRequest{\n\t\tDescription: description,\n\t\tPlan: plan,\n\t\tSize: size,\n\t\tFacility: facility,\n\t\tSnapshotPolicies: snapshotPolicies,\n\t}\n\n\tstorage, _, err := client.Storages.Create(projectID, request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te := MarshallAndPrint(storage)\n\treturn e\n}",
"func NewStorage() (s *Storage, err error) {\n\ts = new(Storage)\n\n\terr = s.initDB()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tc := make(chan time.Time, 10)\n\ts.C = c\n\ts.c = c\n\n\treturn\n}",
"func New() *Storage {\n\treturn &Storage{\n\t\tstat: &statApp{},\n\t}\n}",
"func NewStorage(ctx context.Context, id StorageBackend, url *URL) (Storage, error) {\n\tif be, found := storageRegistry[id]; found {\n\t\treturn be.New(ctx, url)\n\t}\n\treturn nil, errors.Wrapf(ErrNotFound, \"unknown backend: %s\", url.String())\n}",
"func New(config *config.ConfYaml) *Storage {\n\treturn &Storage{\n\t\tconfig: config,\n\t}\n}",
"func NewStorage(lgr *log.Logger) *Storage {\n\treturn &Storage{\n\t\tdataStack: graph.NewStack(),\n\t\tdataStorage: NewKVStorage(),\n\t\tlgr: lgr,\n\t}\n}",
"func NewStorage(typ string) (*Storage, error) {\n\tswitch typ {\n\tcase \"\", \"postgres\":\n\t\tpostgresStore, err := NewPostgresStorage()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinst := Storage(postgresStore)\n\t\treturn &inst, nil\n\tcase \"inmem\":\n\t\tinst := Storage(new(InMemStorage))\n\t\treturn &inst, nil\n\tdefault:\n\t\treturn nil, errors.New(\"Invalid storage type provided.\")\n\t}\n}",
"func NewStorage(vol string) *Storage {\n\tloc := vol\n\n\tif vol[len(vol)-1:] != \"/\" {\n\t\tloc = fmt.Sprintf(\"%s/\", vol)\n\t}\n\n\treturn &Storage{\n\t\tloc,\n\t}\n}",
"func NewStorage(db *gorm.DB) *Storage {\n\treturn &Storage{\n\t\tdb: db,\n\t}\n}",
"func NewStorage_Client(addresse string) *Storage_Client {\n\tclient := new(Storage_Client)\n\tclient.cc = getClientConnection(addresse)\n\tclient.c = storagepb.NewStorageServiceClient(client.cc)\n\treturn client\n}",
"func NewService(ctx context.Context) (*storage.Service, error) {\n\thttpClient, err := google.DefaultClient(ctx, storage.CloudPlatformScope)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := storage.New(httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient.UserAgent = UserAgent\n\treturn client, nil\n}",
"func NewService(s Storage) *Service {\n\treturn &Service{s}\n}",
"func NewService(s Storage) *Service {\n\treturn &Service{s}\n}",
"func NewStorage(cfg *configuration.Storage, timeout time.Duration) (*Storage, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\tclient, err := mongo.Connect(ctx, options.Client().ApplyURI(cfg.URI))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"connect to mongo %s: %s\", cfg.URI, err)\n\t}\n\n\terr = client.Ping(ctx, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ping mongo %s: %s\", cfg.URI, err)\n\t}\n\n\treturn &Storage{\n\t\tclient: client,\n\t\tcollection: client.Database(cfg.DBName).Collection(cfg.CollectionName),\n\t}, nil\n}",
"func NewStorage() *Storage {\n\treturn &Storage{\n\t\tReferenceStorage: make(ReferenceStorage),\n\t\tConfigStorage: ConfigStorage{},\n\t\tShallowStorage: ShallowStorage{},\n\t\tObjectStorage: ObjectStorage{\n\t\t\tObjects: make(map[plumbing.Hash]plumbing.EncodedObject),\n\t\t\tCommits: make(map[plumbing.Hash]plumbing.EncodedObject),\n\t\t\tTrees: make(map[plumbing.Hash]plumbing.EncodedObject),\n\t\t\tBlobs: make(map[plumbing.Hash]plumbing.EncodedObject),\n\t\t\tTags: make(map[plumbing.Hash]plumbing.EncodedObject),\n\t\t},\n\t\tModuleStorage: make(ModuleStorage),\n\t}\n}",
"func NewGenericStorage(rawStorage RawStorage, serializer serializer.Serializer) Storage {\n\treturn &GenericStorage{rawStorage, serializer, patchutil.NewPatcher(serializer)}\n}",
"func NewStorage(path string) (Storage, error) {\n\tif err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {\n\t\treturn Storage{}, err\n\t}\n\n\treturn Storage{path}, nil\n}",
"func newStorage() *storage {\n\treturn &storage{\n\t\tsto: make(map[uint16]mqtt.Message),\n\t\tmux: new(sync.RWMutex),\n\t}\n}",
"func NewStorage(size int, hash HashFunc) *Storage {\n\ts := &Storage{n: size, h: hash}\n\ts.Reset()\n\treturn s\n}",
"func newStorage(\n\tmachineName,\n\ttablename,\n\tdatabase,\n\tretentionPolicy,\n\tusername,\n\tpassword,\n\tinfluxdbHost string,\n\tisSecure bool,\n\tbufferDuration time.Duration,\n) (*influxdbStorage, error) {\n\turl := &url.URL{\n\t\tScheme: \"http\",\n\t\tHost: influxdbHost,\n\t}\n\tif isSecure {\n\t\turl.Scheme = \"https\"\n\t}\n\n\tconfig := &influxdb.Config{\n\t\tURL: *url,\n\t\tUsername: username,\n\t\tPassword: password,\n\t\tUserAgent: fmt.Sprintf(\"%v/%v\", \"cAdvisor\", version.Info[\"version\"]),\n\t}\n\tclient, err := influxdb.NewClient(*config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := &influxdbStorage{\n\t\tclient: client,\n\t\tmachineName: machineName,\n\t\tdatabase: database,\n\t\tretentionPolicy: retentionPolicy,\n\t\tbufferDuration: bufferDuration,\n\t\tlastWrite: time.Now(),\n\t\tpoints: make([]*influxdb.Point, 0),\n\t}\n\tret.readyToFlush = ret.defaultReadyToFlush\n\treturn ret, nil\n}",
"func NewStorage(mds MetadataStore, tr track.Tracker, chunks *chunk.Storage, opts ...StorageOption) *Storage {\n\ts := &Storage{\n\t\tstore: mds,\n\t\ttracker: tr,\n\t\tchunks: chunks,\n\t\tidxCache: index.NewCache(chunks, DefaultIndexCacheSize),\n\t\tmemThreshold: DefaultMemoryThreshold,\n\t\tshardConfig: &index.ShardConfig{\n\t\t\tNumFiles: index.DefaultShardNumThreshold,\n\t\t\tSizeBytes: index.DefaultShardSizeThreshold,\n\t\t},\n\t\tcompactionConfig: &CompactionConfig{\n\t\t\tLevelFactor: DefaultCompactionLevelFactor,\n\t\t},\n\t\tfilesetSem: semaphore.NewWeighted(math.MaxInt64),\n\t\tprefetchLimit: DefaultPrefetchLimit,\n\t}\n\tfor _, opt := range opts {\n\t\topt(s)\n\t}\n\tif s.compactionConfig.LevelFactor < 1 {\n\t\tpanic(\"level factor cannot be < 1\")\n\t}\n\treturn s\n}",
"func NewService(tr Transactioner, storage Storage) *Service {\n\treturn &Service{tr: tr, storage: storage}\n}",
"func makeStorage(name string) ds.Storage {\n\tswitch name {\n\tcase \"skiplist\":\n\t\treturn ds.NewSkipList()\n\tcase \"dict\":\n\t\treturn ds.NewDict()\n\tcase \"b-tree\":\n\t\treturn ds.InitBTree(10)\n\t}\n\treturn ds.NewDict()\n}",
"func newClusterStorage() *ClusterStorage {\n\ts := new(ClusterStorage)\n\treturn s\n}",
"func NewStorage(\n\tlogger *zerolog.Logger,\n\tcfg *config.TSDBStorageConfig,\n\tmetadataStorage metadata.Storage,\n) (data.Storage, error) {\n\tgoKitWrapper, err := NewGoKitLogWrapper(logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create data directory if not exists\n\tif _, err = os.Stat(cfg.DataDir); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tif err = os.MkdirAll(cfg.DataDir, 0750); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// create storage\n\tstor, err := prometheus.OpenTSDB(cfg.DataDir, goKitWrapper)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\ts := &storage{\n\t\tcodec: newB64Codec(),\n\t\tmetadataStorage: metadataStorage,\n\t\tcfg: cfg,\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\twg: sync.WaitGroup{},\n\t\tlogger: logger,\n\t\ttsdbStorage: stor,\n\t}\n\treturn s, nil\n}",
"func NewStorage(path string) (*Storage, error) {\n\tdb, err := bolt.Open(path, 0600, nil)\n\tif err != nil {\n\t\treturn nil, common.Error(common.InitFailed, err)\n\t}\n\tstore := &Storage{db}\n\treturn store, nil\n}",
"func NewStorage(opts generic.RESTOptions, connection client.ConnectionInfoGetter, proxyTransport http.RoundTripper) NodeStorage {\n\tprefix := \"/minions\"\n\n\tnewListFunc := func() runtime.Object { return &api.NodeList{} }\n\tstorageInterface := opts.Decorator(\n\t\topts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.Nodes), &api.Node{}, prefix, node.Strategy, newListFunc)\n\n\tstore := &etcdgeneric.Etcd{\n\t\tNewFunc: func() runtime.Object { return &api.Node{} },\n\t\tNewListFunc: newListFunc,\n\t\tKeyRootFunc: func(ctx api.Context) string {\n\t\t\treturn prefix\n\t\t},\n\t\tKeyFunc: func(ctx api.Context, name string) (string, error) {\n\t\t\treturn etcdgeneric.NoNamespaceKeyFunc(ctx, prefix, name)\n\t\t},\n\t\tObjectNameFunc: func(obj runtime.Object) (string, error) {\n\t\t\treturn obj.(*api.Node).Name, nil\n\t\t},\n\t\tPredicateFunc: node.MatchNode,\n\t\tQualifiedResource: api.Resource(\"nodes\"),\n\t\tDeleteCollectionWorkers: opts.DeleteCollectionWorkers,\n\n\t\tCreateStrategy: node.Strategy,\n\t\tUpdateStrategy: node.Strategy,\n\t\tExportStrategy: node.Strategy,\n\n\t\tStorage: storageInterface,\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = node.StatusStrategy\n\n\tnodeREST := &REST{store, connection, proxyTransport}\n\n\treturn NodeStorage{\n\t\tNode: nodeREST,\n\t\tStatus: &StatusREST{store: &statusStore},\n\t\tProxy: &noderest.ProxyREST{Store: store, Connection: client.ConnectionInfoGetter(nodeREST), ProxyTransport: proxyTransport},\n\t}\n}",
"func (s *GenericStorage) New(gvk schema.GroupVersionKind) (runtime.Object, error) {\n\tobj, err := s.serializer.Scheme().New(gvk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Default either through the scheme, or the high-level serializer Object\n\tif gvk.Version == kruntime.APIVersionInternal {\n\t\tif err := s.serializer.DefaultInternal(obj); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\ts.serializer.Scheme().Default(obj)\n\t}\n\n\t// Cast to runtime.Object, and make sure it works\n\tmetaObj, ok := obj.(runtime.Object)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"can't convert to libgitops.runtime.Object\")\n\t}\n\t// Set the desired gvk from the caller of this Object\n\t// In practice, this means, although we created an internal type,\n\t// from defaulting external TypeMeta information was set. Set the\n\t// desired gvk here so it's correctly handled in all code that gets\n\t// the gvk from the Object\n\tmetaObj.SetGroupVersionKind(gvk)\n\treturn metaObj, nil\n}",
"func newTestModel() *Storage {\n\treturn &Storage{}\n}",
"func NewStorage() *Storage {\n\treturn &Storage{\n\t\tgames: make(map[game.ID]*game.Game),\n\t}\n}",
"func New(timeout time.Duration) (*Storage, error) {\n\tif timeout <= 0 {\n\t\treturn nil, errors.New(\"timeout must be positive\")\n\t}\n\treturn &Storage{\n\t\tdata: make(map[string]interface{}),\n\t\tcancelFuncs: make(map[string]context.CancelFunc),\n\t\ttimeout: timeout,\n\t}, nil\n}",
"func NewStorage() *Storage {\n\tConfig := util.NewConfig()\n\tses, err := mgo.Dial(string(Config.Mongo.Addr))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn &Storage{database: Config.Mongo.DB, table: Config.Mongo.Table, session: ses}\n}",
"func NewService(s order.StorageGateway, router *mux.Router) *Service {\n\tservice := &Service{\n\t\tstorage: s,\n\t\trouter: router,\n\t}\n\tservice.initializeRoutes()\n\n\treturn service\n}",
"func InitStorage(service string, bucket string) {\n\ttransferType = service\n\tbenchName = bucket\n\tawsAccessKey, ok := os.LookupEnv(\"AWS_ACCESS_KEY\")\n\tif ok {\n\t\tAKID = awsAccessKey\n\t}\n\tawsSecretKey, ok := os.LookupEnv(\"AWS_SECRET_KEY\")\n\tif ok {\n\t\tSECRET_KEY = awsSecretKey\n\t}\n\tAWS_S3_REGION = \"us-west-1\"\n\tawsRegion, ok := os.LookupEnv(\"AWS_REGION\")\n\tif ok {\n\t\tAWS_S3_REGION = awsRegion\n\t}\n\tif transferType == S3 {\n\t\tvar err error\n\t\ts3session, err = session.NewSession(&aws.Config{\n\t\t\tRegion: aws.String(AWS_S3_REGION),\n\t\t\tCredentials: credentials.NewStaticCredentials(AKID, SECRET_KEY, TOKEN),\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed establish s3 session: %s\", err)\n\t\t}\n\t} else if transferType == ELASTICACHE {\n\t\tredisClient = redis.NewClient(&redis.Options{\n\t\t\tAddr: benchName,\n\t\t\tPassword: \"\", // no password set\n\t\t\tDB: 0, // use default DB\n\t\t})\n\t}\n}",
"func (s *StorageBase) New(ctx context.Context, ttl time.Duration) (id string, err error) {\n\treturn \"\", ErrorDisabled\n}",
"func NewStorage() *Storage {\n\treturn &Storage{\n\t\tkv: btree.NewKVTree(),\n\t}\n}",
"func NewService(rs *res.Service, storage iapi.Storage) *Service {\n\ts := &Service{rs, storage}\n\t// Add handlers for \"lookup.$key\" models. The response will always be a struct\n\t// containing a value.\n\trs.Handle(\n\t\t`>`,\n\t\tres.Access(res.AccessGranted),\n\t\tres.GetResource(s.getHandler),\n\t\tres.Set(s.setHandler),\n\t\tres.Call(\"delete\", s.deleteHandler),\n\t)\n\treturn s\n}",
"func NewStorage() (Storage, error) {\n\tstorage, err := newBoltStorage()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn store{storage}, nil\n}",
"func NewStorage() SafeMap {\n\tsm := make(safeMap)\n\tgo sm.run()\n\treturn sm\n}",
"func createNewStorageClass(ctx context.Context, clientset kubernetes.Interface,\n\tstorageClassName, provisioner string, defaultAnnotation bool) (*storagev1.StorageClass, error) {\n\tstorageClass := &storagev1.StorageClass{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: storageClassName,\n\t\t},\n\t\tProvisioner: provisioner,\n\t}\n\n\tif defaultAnnotation {\n\t\tstorageClass.Annotations = map[string]string{\n\t\t\t\"storageclass.kubernetes.io/is-default-class\": \"true\",\n\t\t}\n\t}\n\n\treturn clientset.StorageV1().StorageClasses().Create(ctx, storageClass, metav1.CreateOptions{})\n}",
"func (d *driver) CreateStorage(cr *opapi.ImageRegistry, modified *bool) error {\n\tsvc, err := d.getSVC()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tic, err := util.GetInstallConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcv, err := util.GetClusterVersionConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i := 0; i < 5000; i++ {\n\t\tif len(d.Config.Bucket) == 0 {\n\t\t\td.Config.Bucket = fmt.Sprintf(\"%s-%s-%s-%s\", clusterconfig.StoragePrefix, d.Config.Region, strings.Replace(string(cv.Spec.ClusterID), \"-\", \"\", -1), strings.Replace(string(uuid.NewUUID()), \"-\", \"\", -1))[0:62]\n\t\t}\n\n\t\t_, err := svc.CreateBucket(&s3.CreateBucketInput{\n\t\t\tBucket: aws.String(d.Config.Bucket),\n\t\t})\n\t\tif err != nil {\n\t\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\t\tswitch aerr.Code() {\n\t\t\t\tcase s3.ErrCodeBucketAlreadyExists:\n\t\t\t\t\tif cr.Spec.Storage.S3.Bucket != \"\" {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\td.Config.Bucket = \"\"\n\t\t\t\t\tcontinue\n\t\t\t\tdefault:\n\t\t\t\t\tutil.UpdateCondition(cr, opapi.StorageExists, operatorapi.ConditionFalse, aerr.Code(), aerr.Error(), modified)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak\n\t}\n\n\tif len(cr.Spec.Storage.S3.Bucket) == 0 && len(d.Config.Bucket) == 0 {\n\t\tutil.UpdateCondition(cr, opapi.StorageExists, operatorapi.ConditionFalse, \"Unable to Generate Unique Bucket Name\", \"\", modified)\n\t\treturn fmt.Errorf(\"unable to generate a unique s3 bucket name\")\n\t}\n\n\t// Wait until the bucket exists\n\tif err := svc.WaitUntilBucketExists(&s3.HeadBucketInput{\n\t\tBucket: aws.String(d.Config.Bucket),\n\t}); err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageExists, operatorapi.ConditionFalse, aerr.Code(), aerr.Error(), modified)\n\t\t}\n\n\t\treturn err\n\t}\n\n\t// Tag the bucket with the openshiftClusterID\n\t// along with any user defined tags from the cluster configuration\n\tif ic.Platform.AWS != nil {\n\t\tvar tagSet []*s3.Tag\n\t\ttagSet = append(tagSet, &s3.Tag{Key: aws.String(\"openshiftClusterID\"), Value: aws.String(string(cv.Spec.ClusterID))})\n\t\tfor k, v := range ic.Platform.AWS.UserTags {\n\t\t\ttagSet = append(tagSet, &s3.Tag{Key: aws.String(k), Value: aws.String(v)})\n\t\t}\n\n\t\t_, err := svc.PutBucketTagging(&s3.PutBucketTaggingInput{\n\t\t\tBucket: aws.String(d.Config.Bucket),\n\t\t\tTagging: &s3.Tagging{\n\t\t\t\tTagSet: tagSet,\n\t\t\t},\n\t\t})\n\t\tif err != nil {\n\t\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\t\tutil.UpdateCondition(cr, opapi.StorageTagged, operatorapi.ConditionFalse, aerr.Code(), aerr.Error(), modified)\n\t\t\t} else {\n\t\t\t\tutil.UpdateCondition(cr, opapi.StorageTagged, operatorapi.ConditionFalse, \"Unknown Error Occurred\", err.Error(), modified)\n\t\t\t}\n\t\t} else {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageTagged, operatorapi.ConditionTrue, \"Tagging Successful\", \"UserTags were successfully applied to the S3 bucket\", modified)\n\t\t}\n\t}\n\n\t// Enable default encryption on the bucket\n\t_, err = svc.PutBucketEncryption(&s3.PutBucketEncryptionInput{\n\t\tBucket: aws.String(d.Config.Bucket),\n\t\tServerSideEncryptionConfiguration: &s3.ServerSideEncryptionConfiguration{\n\t\t\tRules: []*s3.ServerSideEncryptionRule{\n\t\t\t\t{\n\t\t\t\t\tApplyServerSideEncryptionByDefault: &s3.ServerSideEncryptionByDefault{\n\t\t\t\t\t\tSSEAlgorithm: aws.String(s3.ServerSideEncryptionAes256),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageEncrypted, operatorapi.ConditionFalse, aerr.Code(), aerr.Error(), modified)\n\t\t} else {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageEncrypted, operatorapi.ConditionFalse, \"Unknown Error Occurred\", err.Error(), modified)\n\t\t}\n\t} else {\n\t\tutil.UpdateCondition(cr, opapi.StorageEncrypted, operatorapi.ConditionTrue, \"Encryption Successful\", \"Default encryption was successfully enabled on the S3 bucket\", modified)\n\t}\n\n\t// Enable default incomplete multipart upload cleanup after one (1) day\n\t_, err = svc.PutBucketLifecycleConfiguration(&s3.PutBucketLifecycleConfigurationInput{\n\t\tBucket: aws.String(d.Config.Bucket),\n\t\tLifecycleConfiguration: &s3.BucketLifecycleConfiguration{\n\t\t\tRules: []*s3.LifecycleRule{\n\t\t\t\t{\n\t\t\t\t\tID: aws.String(\"cleanup-incomplete-multipart-registry-uploads\"),\n\t\t\t\t\tStatus: aws.String(\"Enabled\"),\n\t\t\t\t\tFilter: &s3.LifecycleRuleFilter{\n\t\t\t\t\t\tPrefix: aws.String(\"\"),\n\t\t\t\t\t},\n\t\t\t\t\tAbortIncompleteMultipartUpload: &s3.AbortIncompleteMultipartUpload{\n\t\t\t\t\t\tDaysAfterInitiation: aws.Int64(1),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageIncompleteUploadCleanupEnabled, operatorapi.ConditionFalse, aerr.Code(), aerr.Error(), modified)\n\t\t} else {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageIncompleteUploadCleanupEnabled, operatorapi.ConditionFalse, \"Unknown Error Occurred\", err.Error(), modified)\n\t\t}\n\t} else {\n\t\tutil.UpdateCondition(cr, opapi.StorageIncompleteUploadCleanupEnabled, operatorapi.ConditionTrue, \"Enable Cleanup Successful\", \"Default cleanup of incomplete multipart uploads after one (1) day was successfully enabled\", modified)\n\t}\n\n\tcr.Status.Storage.State.S3 = d.Config\n\tcr.Status.Storage.Managed = true\n\n\tutil.UpdateCondition(cr, opapi.StorageExists, operatorapi.ConditionTrue, \"Creation Successful\", \"S3 bucket was successfully created\", modified)\n\n\treturn nil\n}",
"func newStorage(\n\tmachineName,\n\ttablename,\n\tdatabase,\n\tusername,\n\tpassword,\n\tinfluxdbHost string,\n\tisSecure bool,\n\tbufferDuration time.Duration,\n) (*influxdbStorage, error) {\n\tconfig := &influxdb.ClientConfig{\n\t\tHost: influxdbHost,\n\t\tUsername: username,\n\t\tPassword: password,\n\t\tDatabase: database,\n\t\tIsSecure: isSecure,\n\t}\n\tclient, err := influxdb.NewClient(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// TODO(monnand): With go 1.3, we cannot compress data now.\n\tclient.DisableCompression()\n\n\tret := &influxdbStorage{\n\t\tclient: client,\n\t\tmachineName: machineName,\n\t\ttableName: tablename,\n\t\tbufferDuration: bufferDuration,\n\t\tlastWrite: time.Now(),\n\t\tseries: make([]*influxdb.Series, 0),\n\t}\n\tret.readyToFlush = ret.defaultReadyToFlush\n\treturn ret, nil\n}",
"func New(bucket string) (*Storage, error) {\n\tif bucket == \"\" {\n\t\treturn nil, errors.New(\"a bucket is required to create a storage\")\n\t}\n\n\tsess, err := session.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Storage{\n\t\tsvc: s3.New(sess),\n\t\tuploader: s3manager.NewUploader(sess),\n\t\tdownloader: s3manager.NewDownloader(sess),\n\t\tBucket: bucket,\n\t}, nil\n}",
"func New(db *badger.DB) *Storage {\n\treturn &Storage{DB: db}\n}",
"func (m *Manager) AddStorage(s Storage) {\n\tm.storageServices[s.GetStorageServiceName()] = s\n}",
"func New(store Storage) *Service {\n\ts := &Service{\n\t\tstorage: store,\n\t}\n\treturn s\n}",
"func NewStorageLoadBalancer(ss *StorageService) *StorageLoadBalancer {\n\tslb := new(StorageLoadBalancer)\n\tslb.storageService = ss\n\t// StageManager.registerStage\n\t// MessagingService.registerVerbHandlers\n\t// storageService.registerComponentForShutdown\n\treturn slb\n}",
"func newGoogleStorageClient(config stow.Config) (*storage.Service, error) {\n\tjson, _ := config.Config(ConfigJSON)\n\tvar httpClient *http.Client\n\tscopes := []string{storage.DevstorageReadWriteScope}\n\tif s, ok := config.Config(ConfigScopes); ok && s != \"\" {\n\t\tscopes = strings.Split(s, \",\")\n\t}\n\tif json != \"\" {\n\t\tjwtConf, err := google.JWTConfigFromJSON([]byte(json), scopes...)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thttpClient = jwtConf.Client(context.Background())\n\n\t} else {\n\t\tcreds, err := google.FindDefaultCredentials(context.Background(), strings.Join(scopes, \",\"))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thttpClient = oauth2.NewClient(context.Background(), creds.TokenSource)\n\t}\n\tservice, err := storage.New(httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn service, nil\n}",
"func NewService(storage Storage, factory Factory) *Service {\n\treturn &Service{\n\t\tstorage: storage,\n\t\tfactory: factory,\n\t}\n}",
"func NewStorageMock(t minimock.Tester) *StorageMock {\n\tm := &StorageMock{t: t}\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.AllMock = mStorageMockAll{mock: m}\n\tm.AllMock.callArgs = []*StorageMockAllParams{}\n\n\tm.CloneMock = mStorageMockClone{mock: m}\n\tm.CloneMock.callArgs = []*StorageMockCloneParams{}\n\n\tm.ForIDMock = mStorageMockForID{mock: m}\n\tm.ForIDMock.callArgs = []*StorageMockForIDParams{}\n\n\tm.SplitMock = mStorageMockSplit{mock: m}\n\tm.SplitMock.callArgs = []*StorageMockSplitParams{}\n\n\tm.UpdateMock = mStorageMockUpdate{mock: m}\n\tm.UpdateMock.callArgs = []*StorageMockUpdateParams{}\n\n\treturn m\n}",
"func NewStorage() Storage {\n\tmemtable := memtable.NewRollingMemtable()\n\n\tstorage := Storage{memtable: memtable, wal: wal.Wal{Memtable: &memtable}}\n\tstorage.wal.Start()\n\treturn storage\n}",
"func New(path string) (Storage, error) {\n\tif path == \":memory:\" {\n\t\treturn newMemoryStorage(), nil\n\t}\n\n\treturn newFileStorage(path)\n}",
"func NewStorage(mongoURI string, dbname string) (*Storage, error) {\r\n\tclientOptions := options.Client().ApplyURI(mongoURI)\r\n\tclient, err := mongo.Connect(context.Background(), clientOptions)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tdb := client.Database(dbname)\r\n\ts := &Storage{Client: client, DB: db}\r\n\treturn s, nil\r\n}",
"func MakeHTTPStorage(\n\tbase string, settings *cluster.Settings, ioConf base.ExternalIODirConfig,\n) (cloud.ExternalStorage, error) {\n\tif base == \"\" {\n\t\treturn nil, errors.Errorf(\"HTTP storage requested but prefix path not provided\")\n\t}\n\n\tclient, err := makeHTTPClient(settings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turi, err := url.Parse(base)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &httpStorage{\n\t\tbase: uri,\n\t\tclient: client,\n\t\thosts: strings.Split(uri.Host, \",\"),\n\t\tsettings: settings,\n\t\tioConf: ioConf,\n\t}, nil\n}",
"func (as *AppServant) AddStorage(storage *agentd.Storage) {\n\tas.InAddStorageS = storage\n}",
"func NewStorage(DBName string) *Storage {\n\ts := &Storage{}\n\tmutex.Lock()\n\tif db == nil {\n\t\ts.checkMakeDatabase(DBName)\n\t\tdb = s.db\n\t\tif chQueryArgs == nil {\n\t\t\tchQueryArgs = make(chan *queryArgs, 100)\n\t\t\tgo executeStatements()\n\t\t}\n\n\t\ts.setupTables()\n\t}\n\tmutex.Unlock()\n\treturn s\n}",
"func GetStorage(ctx *Context, storageType string, storageConfig interface{}) (Storage, error) {\n\tLog(INFO, ctx, \"System.GetStorage\", \"storageType\", storageType, \"storageConfig\", storageConfig)\n\n\tswitch storageType {\n\tcase \"none\":\n\t\treturn NewNoStorage(ctx)\n\n\tcase \"memory\", \"mem\":\n\t\treturn NewMemStorage(ctx)\n\n\tcase \"cassandra\":\n\t\tnodes := storageConfig\n\t\tvar ns []string\n\t\tvar configStr string\n\n\t\tswitch vv := nodes.(type) {\n\t\tcase []interface{}:\n\t\t\tns = make([]string, 0, len(vv))\n\t\t\tfor _, n := range vv {\n\t\t\t\tns = append(ns, n.(string))\n\t\t\t}\n\t\t\tLog(INFO, ctx, \"core.GetStorage\", \"nodes\", ns)\n\t\t\tconfigStr = strings.Join(ns, \",\")\n\t\tcase string:\n\t\t\tconfigStr = nodes.(string)\n\t\tcase []string:\n\t\t\tconfigStr = strings.Join(nodes.([]string), \",\")\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"bad type for nodes %v (%T); should be []interface{}.\", nodes, nodes)\n\t\t}\n\t\tconfig, err := cassandra.ParseConfig(configStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn cassandra.NewStorage(ctx, *config)\n\n\tcase \"bolt\":\n\t\tfilename := storageConfig\n\t\tswitch s := filename.(type) {\n\t\tcase string:\n\t\t\treturn bolt.NewStorage(ctx, s)\n\t\tdefault:\n\t\t\treturn nil,\n\t\t\t\tfmt.Errorf(\"Bad type for filenames %v (%T); should be a string\", filename, filename)\n\t\t}\n\n\tcase \"dynamodb\":\n\t\tregion := storageConfig\n\t\tswitch vv := region.(type) {\n\t\tcase string:\n\t\t\tconfig, err := dynamodb.ParseConfig(vv)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn dynamodb.GetStorage(ctx, *config)\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"Bad type for DynamoDB region %v (%T); should be string.\",\n\t\t\t\tstorageConfig,\n\t\t\t\tstorageConfig)\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown storage '%s'\", storageType)\n\t}\n\n}",
"func NewStorageClient(cfg Config) (*server, error) {\n\tsession, err := cfg.session()\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\tlogger, _ := zap.NewProduction()\n\tclient := &server{\n\t\tCfg: cfg,\n\t\tSession: session,\n\t\tLogger: logger,\n\t}\n\treturn client, nil\n}",
"func New(db *mgo.Database, collectionPrefix string) *Storage {\n\ts := &Storage{\n\t\tfs: db.GridFS(collectionPrefix),\n\t}\n\t// TODO check error\n\ts.fs.Files.EnsureIndex(mgo.Index{\n\t\tKey: []string{\"filename\"},\n\t\tUnique: true,\n\t})\n\treturn s\n}",
"func NewStorageConfig(ctx context.Context, c client.Reader, ns string) (*StorageConfig, error) {\n\tvar configMap corev1.ConfigMap\n\tkey := client.ObjectKey{\n\t\tName: constants.ConfigMapS3Storage,\n\t\tNamespace: ns,\n\t}\n\tif err := c.Get(ctx, key, &configMap); errors.IsNotFound(err) {\n\t\t// Try koalja-system namespace\n\t\tkey.Namespace = constants.NamespaceKoaljaSystem\n\t\tif err := c.Get(ctx, key, &configMap); err != nil {\n\t\t\treturn nil, maskAny(err)\n\t\t}\n\t} else if err != nil {\n\t\treturn nil, maskAny(err)\n\t}\n\t// Parse config map\n\tsc, err := newStorageConfigFromConfigMap(ctx, &configMap, c, ns)\n\tif err != nil {\n\t\treturn nil, maskAny(err)\n\t}\n\treturn sc, nil\n}"
] | [
"0.70326805",
"0.6985419",
"0.6894278",
"0.6741007",
"0.6693594",
"0.66347814",
"0.6632377",
"0.66183275",
"0.65855944",
"0.6583316",
"0.6583316",
"0.6582425",
"0.6549339",
"0.6535365",
"0.6502325",
"0.6485666",
"0.6459821",
"0.6446026",
"0.64381516",
"0.64352506",
"0.6429695",
"0.6412391",
"0.64023",
"0.6394986",
"0.6315536",
"0.62962705",
"0.62962705",
"0.6295122",
"0.62655115",
"0.6252415",
"0.6241762",
"0.621893",
"0.62115216",
"0.6204905",
"0.6204704",
"0.6190468",
"0.6172641",
"0.61708426",
"0.61645496",
"0.6156513",
"0.61549103",
"0.6149183",
"0.6135608",
"0.6134838",
"0.6127504",
"0.61248636",
"0.61099803",
"0.6108118",
"0.61009926",
"0.60854113",
"0.60821027",
"0.6079689",
"0.6079689",
"0.60791135",
"0.6078007",
"0.60540205",
"0.60417956",
"0.60414743",
"0.60313314",
"0.60032856",
"0.60026747",
"0.5998941",
"0.59841657",
"0.59797746",
"0.59556323",
"0.59497637",
"0.5948294",
"0.5948075",
"0.5926387",
"0.59244585",
"0.5898651",
"0.5883876",
"0.586671",
"0.5861994",
"0.5855349",
"0.5850286",
"0.5837751",
"0.58348095",
"0.583257",
"0.58294624",
"0.5828372",
"0.58251804",
"0.5814298",
"0.5795106",
"0.57950896",
"0.578863",
"0.5765146",
"0.57641447",
"0.576152",
"0.57598776",
"0.57515806",
"0.574724",
"0.5746424",
"0.5734887",
"0.5730047",
"0.5710441",
"0.5710068",
"0.56889075",
"0.568858",
"0.56753576"
] | 0.79189503 | 0 |
Validate that options are usable | func (opts *Options) Validate() error {
return nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (o *Options) Verify() error {\n\tif o.GC != \"\" {\n\t\tvalid := isInArray(validGCOptions, o.GC)\n\t\tif !valid {\n\t\t\treturn fmt.Errorf(`invalid gc option '%s': valid values are %s`,\n\t\t\t\to.GC,\n\t\t\t\tstrings.Join(validGCOptions, \", \"))\n\t\t}\n\t}\n\n\tif o.Scheduler != \"\" {\n\t\tvalid := isInArray(validSchedulerOptions, o.Scheduler)\n\t\tif !valid {\n\t\t\treturn fmt.Errorf(`invalid scheduler option '%s': valid values are %s`,\n\t\t\t\to.Scheduler,\n\t\t\t\tstrings.Join(validSchedulerOptions, \", \"))\n\t\t}\n\t}\n\n\tif o.Serial != \"\" {\n\t\tvalid := isInArray(validSerialOptions, o.Serial)\n\t\tif !valid {\n\t\t\treturn fmt.Errorf(`invalid serial option '%s': valid values are %s`,\n\t\t\t\to.Serial,\n\t\t\t\tstrings.Join(validSerialOptions, \", \"))\n\t\t}\n\t}\n\n\tif o.PrintSizes != \"\" {\n\t\tvalid := isInArray(validPrintSizeOptions, o.PrintSizes)\n\t\tif !valid {\n\t\t\treturn fmt.Errorf(`invalid size option '%s': valid values are %s`,\n\t\t\t\to.PrintSizes,\n\t\t\t\tstrings.Join(validPrintSizeOptions, \", \"))\n\t\t}\n\t}\n\n\tif o.PanicStrategy != \"\" {\n\t\tvalid := isInArray(validPanicStrategyOptions, o.PanicStrategy)\n\t\tif !valid {\n\t\t\treturn fmt.Errorf(`invalid panic option '%s': valid values are %s`,\n\t\t\t\to.PanicStrategy,\n\t\t\t\tstrings.Join(validPanicStrategyOptions, \", \"))\n\t\t}\n\t}\n\n\tif o.Opt != \"\" {\n\t\tif !isInArray(validOptOptions, o.Opt) {\n\t\t\treturn fmt.Errorf(\"invalid -opt=%s: valid values are %s\", o.Opt, strings.Join(validOptOptions, \", \"))\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (o *Options) validate(args []string) error {\n\tif len(args) != 0 {\n\t\treturn errors.New(\"arguments are not supported\")\n\t}\n\treturn nil\n}",
"func (o *Options) Validate() error {\n\tif len(o.args) > 0 {\n\t\treturn errors.New(\"no argument is allowed\")\n\t}\n\tif o.useServicePrincipal && o.useUserPrincipal {\n\t\treturn errors.New(\"service principal and user principal cannot be used at the same time\")\n\t}\n\treturn nil\n}",
"func (o *ChonkOptions) Validate() error {\n\tif len(o.args) > 0 {\n\t\treturn fmt.Errorf(\"no arguments expected\")\n\t}\n\n\treturn nil\n}",
"func (o *options) validate() error {\n\treturn nil\n}",
"func validateOptions(options Options) (errors []string) {\n\n\t// options.scale\n\tif options.Scale != nil {\n\t\tif options.Scale.Min != nil {\n\t\t\tif *options.Scale.Min < 0 {\n\t\t\t\terrors = append(errors, fmt.Sprintf(\"options field \\\"scale.min\\\" has invalid value set: %d, the value must be greater than \\\"0\\\"\",\n\t\t\t\t\t*options.Scale.Min))\n\t\t\t}\n\t\t}\n\n\t\tif options.Scale.Max != nil {\n\t\t\tif *options.Scale.Max < 0 {\n\t\t\t\terrors = append(errors, fmt.Sprintf(\"options field \\\"scale.max\\\" has invalid value set: %d, the value must be greater than \\\"0\\\"\",\n\t\t\t\t\t*options.Scale.Max))\n\t\t\t}\n\t\t}\n\n\t\tif options.Scale.Min != nil && options.Scale.Max != nil {\n\t\t\tif *options.Scale.Max < *options.Scale.Min {\n\t\t\t\terrors = append(errors, \"options field \\\"scale.max\\\" value must be greater or equal to \\\"scale.min\\\"\")\n\t\t\t}\n\t\t}\n\n\t\tif options.Scale.Metric != nil {\n\t\t\tif *options.Scale.Metric != \"concurrency\" && *options.Scale.Metric != \"rps\" {\n\t\t\t\terrors = append(errors, fmt.Sprintf(\"options field \\\"scale.metric\\\" has invalid value set: %s, allowed is only \\\"concurrency\\\" or \\\"rps\\\"\",\n\t\t\t\t\t*options.Scale.Metric))\n\t\t\t}\n\t\t}\n\n\t\tif options.Scale.Target != nil {\n\t\t\tif *options.Scale.Target < 0.01 {\n\t\t\t\terrors = append(errors, fmt.Sprintf(\"options field \\\"scale.target\\\" has value set to \\\"%f\\\", but it must not be less than 0.01\",\n\t\t\t\t\t*options.Scale.Target))\n\t\t\t}\n\t\t}\n\n\t\tif options.Scale.Utilization != nil {\n\t\t\tif *options.Scale.Utilization < 1 || *options.Scale.Utilization > 100 {\n\t\t\t\terrors = append(errors,\n\t\t\t\t\tfmt.Sprintf(\"options field \\\"scale.utilization\\\" has value set to \\\"%f\\\", but it must not be less than 1 or greater than 100\",\n\t\t\t\t\t\t*options.Scale.Utilization))\n\t\t\t}\n\t\t}\n\t}\n\n\t// options.resource\n\tif options.Resources != nil {\n\n\t\t// options.resource.requests\n\t\tif options.Resources.Requests != nil {\n\n\t\t\tif options.Resources.Requests.CPU != nil {\n\t\t\t\t_, err := resource.ParseQuantity(*options.Resources.Requests.CPU)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrors = append(errors, fmt.Sprintf(\"options field \\\"resources.requests.cpu\\\" has invalid value set: \\\"%s\\\"; \\\"%s\\\"\",\n\t\t\t\t\t\t*options.Resources.Requests.CPU, err.Error()))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif options.Resources.Requests.Memory != nil {\n\t\t\t\t_, err := resource.ParseQuantity(*options.Resources.Requests.Memory)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrors = append(errors, fmt.Sprintf(\"options field \\\"resources.requests.memory\\\" has invalid value set: \\\"%s\\\"; \\\"%s\\\"\",\n\t\t\t\t\t\t*options.Resources.Requests.Memory, err.Error()))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// options.resource.limits\n\t\tif options.Resources.Limits != nil {\n\n\t\t\tif options.Resources.Limits.CPU != nil {\n\t\t\t\t_, err := resource.ParseQuantity(*options.Resources.Limits.CPU)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrors = append(errors, fmt.Sprintf(\"options field \\\"resources.limits.cpu\\\" has invalid value set: \\\"%s\\\"; \\\"%s\\\"\",\n\t\t\t\t\t\t*options.Resources.Limits.CPU, err.Error()))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif options.Resources.Limits.Memory != nil {\n\t\t\t\t_, err := resource.ParseQuantity(*options.Resources.Limits.Memory)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrors = append(errors, fmt.Sprintf(\"options field \\\"resources.limits.memory\\\" has invalid value set: \\\"%s\\\"; \\\"%s\\\"\",\n\t\t\t\t\t\t*options.Resources.Limits.Memory, err.Error()))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif options.Resources.Limits.Concurrency != nil {\n\t\t\t\tif *options.Resources.Limits.Concurrency < 0 {\n\t\t\t\t\terrors = append(errors, fmt.Sprintf(\"options field \\\"resources.limits.concurrency\\\" has value set to \\\"%d\\\", but it must not be less than 0\",\n\t\t\t\t\t\t*options.Resources.Limits.Concurrency))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}",
"func validateWriteOptions(opts *cli.Options) error {\n\treturn nil\n}",
"func (o *Opts) Validate() error {\n\tvar e []string\n\tif o.Queue == 0 {\n\t\te = append(e, \"queue size must be greater than 0\")\n\t}\n\tif len(e) > 0 {\n\t\treturn fmt.Errorf(\"%s\", strings.Join(e, \"; \"))\n\t}\n\treturn nil\n}",
"func validateOptions(s string, options []string) (bool, error) {\n\tl := strings.ToLower(s)\n\tfor _, option := range options {\n\t\tif l == option {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, fmt.Errorf(\"%s is a not a valid option. Valid options are %v\", s, options)\n}",
"func (o *Options) validate() error {\n\tif len(o.BindAddress) == 0 {\n\t\treturn fmt.Errorf(\"missing bind address\")\n\t}\n\n\tif o.Port == 0 {\n\t\treturn fmt.Errorf(\"missing port\")\n\t}\n\n\tif len(o.ServerCertDir) == 0 {\n\t\treturn fmt.Errorf(\"missing server tls cert path\")\n\t}\n\n\treturn nil\n}",
"func validateOptions(opts *initClusterRegistryOptions) error {\n\topts.apiServerServiceType = v1.ServiceType(opts.apiServerServiceTypeString)\n\tif opts.apiServerServiceType != v1.ServiceTypeLoadBalancer && opts.apiServerServiceType != v1.ServiceTypeNodePort {\n\t\treturn fmt.Errorf(\"invalid %s: %s, should be either %s or %s\", apiserverServiceTypeFlag, opts.apiServerServiceType, v1.ServiceTypeLoadBalancer, v1.ServiceTypeNodePort)\n\t}\n\tif opts.apiServerAdvertiseAddress != \"\" {\n\t\tip := net.ParseIP(opts.apiServerAdvertiseAddress)\n\t\tif ip == nil {\n\t\t\treturn fmt.Errorf(\"invalid %s: %s, should be a valid ip address\", apiserverAdvertiseAddressFlag, opts.apiServerAdvertiseAddress)\n\t\t}\n\t\tif opts.apiServerServiceType != v1.ServiceTypeNodePort {\n\t\t\treturn fmt.Errorf(\"%s should be passed only with '%s=NodePort'\", apiserverAdvertiseAddressFlag, apiserverServiceTypeFlag)\n\t\t}\n\t}\n\n\tif opts.apiServerNodePortPort != 0 {\n\t\tif opts.apiServerServiceType != v1.ServiceTypeNodePort {\n\t\t\treturn fmt.Errorf(\"%s should be passed only with '%s=NodePort'\", apiserverPortFlag, apiserverServiceTypeFlag)\n\t\t}\n\t\topts.apiServerNodePortPortPtr = &opts.apiServerNodePortPort\n\t} else {\n\t\topts.apiServerNodePortPortPtr = nil\n\t}\n\tif opts.apiServerNodePortPort < 0 || opts.apiServerNodePortPort > 65535 {\n\t\treturn fmt.Errorf(\"Please provide a valid port number for %s\", apiserverPortFlag)\n\t}\n\n\treturn nil\n}",
"func ValidateOptions(options []*commonpb.KeyValuePair) error {\n\toptionMap := funcutil.KeyValuePair2Map(options)\n\t// StartTs should be int\n\t_, ok := optionMap[StartTs]\n\tvar startTs uint64\n\tvar endTs uint64 = math.MaxInt64\n\tvar err error\n\tif ok {\n\t\tstartTs, err = strconv.ParseUint(optionMap[StartTs], 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// EndTs should be int\n\t_, ok = optionMap[EndTs]\n\tif ok {\n\t\tendTs, err = strconv.ParseUint(optionMap[EndTs], 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif startTs > endTs {\n\t\treturn errors.New(\"start_ts shouldn't be larger than end_ts\")\n\t}\n\treturn nil\n}",
"func (self *ToolOptions) Validate() error {\n\t/*\n\t\tif self.ExtraOptions != nil {\n\t\t\tif err := self.ExtraOptions.Validate(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t*/\n\n\tswitch {\n\tcase self.DBPath != \"\" && self.Host != \"\":\n\t\treturn fmt.Errorf(\"--dbpath is not allowed when --host is specified\")\n\t}\n\n\treturn nil\n}",
"func (lo *Option) Valid() bool {\n\treturn lo.MaxConnections > 0 || lo.MaxQPS > 0\n}",
"func (opts resourceOptions) validate() error {\n\t// Check that the required flags did not get a flag as their value.\n\t// We can safely look for a '-' as the first char as none of the fields accepts it.\n\t// NOTE: We must do this for all the required flags first or we may output the wrong\n\t// error as flags may seem to be missing because Cobra assigned them to another flag.\n\tif strings.HasPrefix(opts.Group, \"-\") {\n\t\treturn fmt.Errorf(groupPresent)\n\t}\n\tif strings.HasPrefix(opts.Version, \"-\") {\n\t\treturn fmt.Errorf(versionPresent)\n\t}\n\tif strings.HasPrefix(opts.Kind, \"-\") {\n\t\treturn fmt.Errorf(kindPresent)\n\t}\n\n\t// We do not check here if the GVK values are empty because that would\n\t// make them mandatory and some plugins may want to set default values.\n\t// Instead, this is checked by resource.GVK.Validate()\n\n\treturn nil\n}",
"func (opts Options) validate() error {\n\t// AzureDNSClient is only not nil for the tests.\n\tif opts.AzureAuthentication == nil && opts.AzureDNSClient == nil {\n\t\treturn errAzureAuthenticationNil\n\t}\n\n\tif opts.KubeClient == nil {\n\t\treturn errKubeClientNil\n\t}\n\n\tif len(opts.DomainNameRoot) <= 0 {\n\t\treturn errDomainNameRootEmpty\n\t}\n\n\tif len(opts.ResourceGroupName) <= 0 {\n\t\treturn errResourceGroupNameEmpty\n\t}\n\n\tif len(opts.ResourceName) <= 0 {\n\t\treturn errResourceNameEmpty\n\t}\n\n\tif len(opts.Region) <= 0 {\n\t\treturn errRegionEmpty\n\t}\n\n\treturn nil\n}",
"func (o DownsamplerOptions) validate() error {\n\tif o.Storage == nil {\n\t\treturn errNoStorage\n\t}\n\tif o.ClusterClient == nil {\n\t\treturn errNoClusterClient\n\t}\n\tif o.RulesKVStore == nil {\n\t\treturn errNoRulesStore\n\t}\n\tif o.ClockOptions == nil {\n\t\treturn errNoClockOptions\n\t}\n\tif o.InstrumentOptions == nil {\n\t\treturn errNoInstrumentOptions\n\t}\n\tif o.TagEncoderOptions == nil {\n\t\treturn errNoTagEncoderOptions\n\t}\n\tif o.TagDecoderOptions == nil {\n\t\treturn errNoTagDecoderOptions\n\t}\n\tif o.TagEncoderPoolOptions == nil {\n\t\treturn errNoTagEncoderPoolOptions\n\t}\n\tif o.TagDecoderPoolOptions == nil {\n\t\treturn errNoTagDecoderPoolOptions\n\t}\n\treturn nil\n}",
"func validateOpts(opts VerifyOpts) error {\n\tcheckPub := len(opts.TrustedAKs) > 0\n\tcheckCert := len(opts.TrustedRootCerts) > 0\n\tif !checkPub && !checkCert {\n\t\treturn fmt.Errorf(\"no trust mechanism provided, either use TrustedAKs or TrustedRootCerts\")\n\t}\n\tif checkPub && checkCert {\n\t\treturn fmt.Errorf(\"multiple trust mechanisms provided, only use one of TrustedAKs or TrustedRootCerts\")\n\t}\n\treturn nil\n}",
"func (o *Options) ValidateOptions() error {\n\to.Web.Sync = func() (string, error) {\n\t\treturn o.DoSync()\n\t}\n\n\tvar err error\n\to.KubeClient, err = kube.LazyCreateKubeClient(o.KubeClient)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create kube client\")\n\t}\n\tif o.LabelSelector == nil {\n\t\to.LabelSelector = labels.NewSelector()\n\t}\n\tif o.SyncDuration.Milliseconds() == int64(0) {\n\t\to.SyncDuration = time.Minute * 5\n\t}\n\tif o.Dir == \"\" {\n\t\to.Dir, err = ioutil.TempDir(\"\", \"jx-test-collector-\")\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to create temp dir\")\n\t\t}\n\t}\n\tlogrus.Infof(\"writing files to dir: %s\", o.Dir)\n\n\terr = o.GitStore.Validate(o.KubeClient, o.Dir)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to validate GitStore\")\n\t}\n\n\terr = o.Resources.Validate(filepath.Join(o.Dir, o.ResourcePath))\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to setup resource fetcher\")\n\t}\n\treturn nil\n}",
"func (m *Option) Validate() error {\n\treturn nil\n}",
"func validateArgs() {\n\tif *optionsEndpoint == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\tif *inputEndpoint == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\tif *outputEndpoint == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n}",
"func (gto *GetOptions) Validate() (err error) {\n\treturn\n}",
"func (opts *Options) Validate() error {\n\tif opts.LockTimeout < 0 {\n\t\treturn errors.New(\"cannot have negative lock timeout\")\n\t}\n\n\tif opts.LockTimeout == 0 {\n\t\topts.LockTimeout = amboy.LockTimeout\n\t}\n\n\tif opts.PoolSize == 0 {\n\t\topts.PoolSize = runtime.NumCPU()\n\t}\n\n\tif opts.WaitInterval == 0 {\n\t\topts.WaitInterval = 100 * time.Millisecond\n\t}\n\n\tif opts.SchemaName == \"\" {\n\t\topts.SchemaName = \"amboy\"\n\t}\n\n\treturn nil\n}",
"func (o *options) validateFlags() error {\n\tvar err error\n\n\tif len(o.name) == 0 {\n\t\treturn &util.ExitError{Message: \"-n, --name option is required.\", Code: 1}\n\t}\n\n\to.output, err = filepath.Abs(o.output)\n\tif err != nil {\n\t\treturn &util.ExitError{Message: fmt.Sprintf(\"-o, --output option invalid: %v.\", o.output), Code: 1}\n\t}\n\n\tif util.DirExists(o.output) {\n\t\treturn &util.ExitError{Message: fmt.Sprintf(\"-o, --output already exists and is a directory: %v.\", o.output), Code: 1}\n\t}\n\n\tif o.serviceaccount && o.certificate {\n\t\treturn &util.ExitError{Message: \"-c, --certificate and -s, --serviceaccount are mutually exclusive options.\", Code: 1}\n\t}\n\n\treturn nil\n}",
"func (o *Options) CheckOptions() error {\n\tif o.ViceCrtFile == \"\" {\n\t\treturn fmt.Errorf(\"path to vice certificate not provided. Aborting\")\n\t}\n\tif o.ViceKeyFile == \"\" {\n\t\treturn fmt.Errorf(\"path to vice key not provided. Aborting\")\n\t}\n\tif o.VicePresidentConfig == \"\" {\n\t\treturn fmt.Errorf(\"path to vice config not provided. Aborting\")\n\t}\n\tif o.IntermediateCertificate == \"\" {\n\t\tLogDebug(\"Intermediate certificate not provided\")\n\t}\n\tif o.KubeConfig == \"\" {\n\t\tLogDebug(\"Path to kubeconfig not provided. Using Default\")\n\t}\n\n\tif o.MinCertValidityDays <= 0 {\n\t\tLogDebug(\"Minimum certificate validity invalid. Using default: 30 days\")\n\t\to.MinCertValidityDays = 30\n\t}\n\n\tif o.MetricPort == 0 {\n\t\to.MetricPort = 9091\n\t\tLogDebug(\"Metric port not provided. Using default port: 9091\")\n\t}\n\tif !o.IsEnableAdditionalSymantecMetrics {\n\t\tLogDebug(\"Not exposing additional Symantec metrics\")\n\t} else {\n\t\tLogDebug(\"Exposing additional Symantec metrics\")\n\t}\n\n\treturn nil\n}",
"func (o *options) Validate() error {\n\tif len(o.tmKubeconfigPath) == 0 {\n\t\treturn errors.New(\"tm-kubeconfig-path is required\")\n\t}\n\tif len(o.testrunNamePrefix) == 0 {\n\t\treturn errors.New(\"testrun-prefix is required\")\n\t}\n\tif len(o.testrunPath) == 0 {\n\t\treturn errors.New(\"file is required\")\n\t}\n\treturn nil\n}",
"func (o *Options) Validate() error {\n\n\tif len(o.OrchestratorTopologyUser) == 0 {\n\t\to.OrchestratorTopologyUser = getFromEnvOrDefault(\"ORC_TOPOLOGY_USER\", \"\")\n\t}\n\tif len(o.OrchestratorTopologyPassword) == 0 {\n\t\to.OrchestratorTopologyPassword = getFromEnvOrDefault(\"ORC_TOPOLOGY_PASSWORD\", \"\")\n\t}\n\treturn nil\n}",
"func (opt *Options) Valid() bool {\n\n\tif opt.Image == \"\" {\n\t\toutput.Error(\"An image is required\")\n\t}\n\n\tif !(opt.Gif || opt.Trigger || opt.Shake) && opt.OutName != \"\" {\n\t\tif !strings.HasSuffix(strings.ToLower(opt.OutName), \".png\") {\n\t\t\toutput.Error(\"The output file name must have the suffix of .png\")\n\t\t}\n\t}\n\n\tif (opt.Gif || opt.Trigger || opt.Shake) && opt.OutName != \"\" {\n\t\tif !strings.HasSuffix(strings.ToLower(opt.OutName), \".gif\") {\n\t\t\toutput.Error(\"The output file name must have the suffix of .gif\")\n\t\t}\n\t}\n\n\treturn true\n}",
"func (opts *Options) Validate() error {\n\tif len(opts.GitHubToken) == 0 {\n\t\topts.GitHubToken = envy.Get(\"GITHUB_TOKEN\", \"\")\n\t\tif len(opts.GitHubToken) == 0 {\n\t\t\treturn fmt.Errorf(\"you must set a GITHUB_TOKEN\")\n\t\t}\n\t}\n\tif len(opts.Version) == 0 {\n\t\topts.Version = \"v0.0.1\"\n\t}\n\n\tif !strings.HasPrefix(opts.Version, \"v\") {\n\t\topts.Version = \"v\" + opts.Version\n\t}\n\n\tv, err := semver.NewVersion(strings.TrimPrefix(opts.Version, \"v\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\topts.semVersion = v\n\tif len(opts.Branch) == 0 {\n\t\topts.Branch = \"master\"\n\t}\n\treturn nil\n}",
"func validateOptions(cfg *config) (err error) {\n\t// step: read in the token if required\n\n\tif cfg.vaultAuthFile != \"\" {\n\t\tif exists, _ := fileExists(cfg.vaultAuthFile); !exists {\n\t\t\treturn fmt.Errorf(\"the token file: %s does not exists, please check\", cfg.vaultAuthFile)\n\t\t}\n\n\t\tcfg.vaultAuthOptions, err = readConfigFile(cfg.vaultAuthFile, cfg.vaultAuthFileFormat)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to read in authentication options from: %s, error: %s\", cfg.vaultAuthFile, err)\n\t\t}\n\t\tif cfg.vaultAuthOptions.VaultURL != \"\" {\n\t\t\tcfg.vaultURL = cfg.vaultAuthOptions.VaultURL\n\t\t}\n\t}\n\n\tif cfg.vaultURL == \"\" {\n\t\tcfg.vaultURL = os.Getenv(\"VAULT_ADDR\")\n\t}\n\n\tif cfg.vaultURL == \"\" {\n\t\treturn fmt.Errorf(\"VAULT_ADDR is unset\")\n\t}\n\n\t// step: validate the vault url\n\tif _, err = url.Parse(cfg.vaultURL); err != nil {\n\t\treturn fmt.Errorf(\"invalid vault url: '%s' specified\", cfg.vaultURL)\n\t}\n\n\tif cfg.vaultCaFile != \"\" {\n\t\tif exists, _ := fileExists(cfg.vaultCaFile); !exists {\n\t\t\treturn fmt.Errorf(\"the ca certificate file: %s does not exist\", cfg.vaultCaFile)\n\t\t}\n\t}\n\n\tif cfg.skipTLSVerify == true && cfg.vaultCaFile != \"\" {\n\t\treturn fmt.Errorf(\"you are skipping the tls but supplying a CA, doesn't make sense\")\n\t}\n\n\treturn nil\n}",
"func checkPossibleOptions(param interface{}, paramOptions []interface{}) bool {\n\tfor _, opt := range paramOptions {\n\t\tif opt == param {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}",
"func (opt *Options) Valid() bool {\n\tif err := compile(opt.Regex, opt.Case); err != nil {\n\t\tfmt.Fprintln(Stderr, color.RedString(\"Find pattern: %s\", err.Error()))\n\t\treturn false\n\t}\n\n\tif err := compile(opt.Ignore, opt.Case); err != nil {\n\t\tfmt.Fprintln(Stderr, color.RedString(\"Ignore pattern: %s\", err.Error()))\n\t\treturn false\n\t}\n\n\tif opt.Regex == \"\" {\n\t\tfmt.Fprintln(Stderr, color.RedString(\"Find pattern cannot be empty.\"))\n\t\treturn false\n\t}\n\n\treturn true\n}",
"func (opts *Options) Validate() (err error) {\n\tif opts.ClientID == \"\" {\n\t\treturn ErrClientID\n\t}\n\tif opts.ClientSecret == \"\" {\n\t\treturn ErrClientSecret\n\t}\n\tif opts.CallbackAddress == \"\" {\n\t\treturn ErrCallbackAddress\n\t}\n\tif opts.OAuthRoot == \"\" {\n\t\topts.OAuthRoot = TranquilityOAuth\n\t}\n\tif opts.OAuthRoot != TranquilityOAuth && opts.OAuthRoot != SingularityOAuth {\n\t\treturn ErrBadOAuthAddress\n\t}\n\treturn\n}",
"func (c Counter) Valid(options ...string) bool {\n\tv := reflect.ValueOf(c)\n\tfor i := 0; i < v.NumField(); i++ {\n\t\t// can't use \"!= 0\" check here, because such shell syntax may occur in rpm specfile:\n\t\t// case `value` in\n\t\t// *)\n\t\t// `command`\n\t\t//\t\t ;;\n\t\t// esac\n\t\t// there's no opening \"(\" here, so the parenteses counter will be negative, but it's still valid\n\t\tif ok, _ := slice.Contains(options, v.Type().Field(i).Name); !ok && v.Field(i).Int() > 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}",
"func validateFileOption(option Option, value interface{}, optionValues OptionValues) error {\n\tvalType := reflect.TypeOf(value)\n\tdefaultVal := option.Default(&optionValues)\n\tdefaultType := reflect.TypeOf(defaultVal)\n\tif valType != defaultType {\n\t\treturn &ErrTypeMismatch{\n\t\t\tExpected: defaultType.Name(),\n\t\t\tActual: valType.Name(),\n\t\t}\n\t}\n\n\tif err := option.Validate(value); err != nil {\n\t\treturn errors.Wrap(ErrMalformedInput, fmt.Sprintf(\"%s: %s\", option.Name(), err.Error()))\n\t}\n\n\t// if it is set to sth else than default with shouldDisplay returning false it means the parameters does not have any effect\n\tif value != defaultVal && !option.ShouldDisplay(&optionValues) {\n\t\treturn errors.Wrap(ErrParameterSet, option.Name())\n\t}\n\n\treturn nil\n}",
"func validateManagerOptions(opt ManagerOptions) Neo4GoError {\n\tif opt.URI == \"\" {\n\t\treturn &internalErr.InitError{\n\t\t\tErr: \"Database URI given in options is empty\",\n\t\t\tDBName: opt.DatabaseName,\n\t\t\tURI: opt.URI,\n\t\t}\n\t}\n\n\tif opt.DatabaseName == \"\" {\n\t\treturn &internalErr.InitError{\n\t\t\tErr: \"Database name given in options is empty\",\n\t\t\tDBName: opt.DatabaseName,\n\t\t\tURI: opt.URI,\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (o *dryrunOptions) validate() error {\n\tif o.userWPAName == \"\" && o.labelSelector == \"\" && !o.allWPA {\n\t\treturn fmt.Errorf(\"the watermarkpodautoscaler name or label-selector is required\")\n\t}\n\n\treturn nil\n}",
"func validateKubeOpts(opts []string) error {\n\terrMsg := \"Kubectl option %s invalid, check it by 'kubectl options'\"\n\tfor _, opt := range opts {\n\t\t// validate like '--kubeconfig=/path/to/kube/config'\n\t\tif strings.Contains(opt, \"=\") && len(strings.Fields(opt)) != 1 {\n\t\t\treturn fmt.Errorf(errMsg, opt)\n\t\t}\n\t\t// validate like '-n default'\n\t\tif strings.Contains(opt, \" \") && len(strings.Fields(opt)) != 2 {\n\t\t\treturn fmt.Errorf(errMsg, opt)\n\t\t}\n\t}\n\treturn nil\n}",
"func checkOptions() {\n\tif !options.GetB(OPT_UNINSTALL) {\n\t\tproc := options.GetS(OPT_PROCFILE)\n\n\t\tswitch {\n\t\tcase proc == \"\":\n\t\t\tprintErrorAndExit(\"You should define path to procfile\", proc)\n\n\t\tcase fsutil.IsExist(proc) == false:\n\t\t\tprintErrorAndExit(\"Procfile %s does not exist\", proc)\n\n\t\tcase fsutil.IsReadable(proc) == false:\n\t\t\tprintErrorAndExit(\"Procfile %s is not readable\", proc)\n\n\t\tcase fsutil.IsNonEmpty(proc) == false:\n\t\t\tprintErrorAndExit(\"Procfile %s is empty\", proc)\n\t\t}\n\t}\n}",
"func TestNew(t *testing.T) {\n\tt.Run(\"one required int option\", func(t *testing.T) {\n\t\t_, err := New(Option{\n\t\t\tKey: \"int\",\n\t\t\tValueType: \"int\",\n\t\t\tDescription: \"some int value\",\n\t\t\tRequired: true,\n\t\t})\n\t\ttestUtil.NoError(t, err)\n\t})\n\n\tt.Run(\"one int option\", func(t *testing.T) {\n\t\t_, err := New(Option{\n\t\t\tKey: \"int\",\n\t\t\tValueType: \"int\",\n\t\t\tDescription: \"some int value\",\n\t\t\tDefaultValue: 10,\n\t\t})\n\t\ttestUtil.NoError(t, err)\n\t})\n\n\tt.Run(\"one required string option\", func(t *testing.T) {\n\t\t_, err := New(Option{\n\t\t\tKey: \"string\",\n\t\t\tValueType: \"string\",\n\t\t\tDescription: \"some string value\",\n\t\t\tRequired: true,\n\t\t})\n\t\ttestUtil.NoError(t, err)\n\t})\n\n\tt.Run(\"one string option\", func(t *testing.T) {\n\t\t_, err := New(Option{\n\t\t\tKey: \"string\",\n\t\t\tValueType: \"string\",\n\t\t\tDescription: \"some string value\",\n\t\t\tDefaultValue: \"default value\",\n\t\t})\n\t\ttestUtil.NoError(t, err)\n\t})\n\n\tt.Run(\"one option with validator\", func(t *testing.T) {\n\t\t_, err := New(Option{\n\t\t\tKey: \"int\",\n\t\t\tValueType: \"int\",\n\t\t\tDescription: \"some int value\",\n\t\t\tDefaultValue: 10,\n\t\t\tValidator: validator.IntWithin,\n\t\t\tValidatorParam: []int{9, 11},\n\t\t})\n\t\ttestUtil.NoError(t, err)\n\t})\n\n\tt.Run(\"invalid option (no key)\", func(t *testing.T) {\n\t\t_, err := New(Option{\n\t\t\tKey: \"\",\n\t\t\tValueType: \"string\",\n\t\t\tDescription: \"some string value\",\n\t\t\tDefaultValue: \"default value\",\n\t\t})\n\t\ttestUtil.WithError(t, err)\n\t})\n\n\tt.Run(\"invalid option (required and default value are specified)\", func(t *testing.T) {\n\t\t_, err := New(Option{\n\t\t\tKey: \"\",\n\t\t\tValueType: \"string\",\n\t\t\tDescription: \"some string value\",\n\t\t\tRequired: true,\n\t\t\tDefaultValue: \"default value\",\n\t\t})\n\t\ttestUtil.WithError(t, err)\n\t})\n\n\tt.Run(\"invalid option with validator (validation failed)\", func(t *testing.T) {\n\t\t_, err := New(Option{\n\t\t\tKey: \"int\",\n\t\t\tValueType: \"int\",\n\t\t\tDescription: \"some int value\",\n\t\t\tDefaultValue: 10,\n\t\t\tValidator: validator.IntSmallerThan,\n\t\t\tValidatorParam: 10,\n\t\t})\n\t\ttestUtil.NoError(t, err)\n\t})\n}",
"func (o *conversionOptions) validate() error {\r\n\tif o.goalID == 0 && len(o.goalName) == 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute(s): %s or %s\", fieldID, fieldName)\r\n\t} else if o.goalID == 0 && o.tonicPowUserID > 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute: %s\", fieldID)\r\n\t} else if o.tonicPowUserID == 0 && len(o.tncpwSession) == 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute(s): %s or %s\", fieldVisitorSessionGUID, fieldUserID)\r\n\t}\r\n\treturn nil\r\n}",
"func (mt *EasypostOptions) Validate() (err error) {\n\tif mt.CodMethod != nil {\n\t\tif !(*mt.CodMethod == \"CASH\" || *mt.CodMethod == \"CHECK\" || *mt.CodMethod == \"MONEY_ORDER\") {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.cod_method`, *mt.CodMethod, []interface{}{\"CASH\", \"CHECK\", \"MONEY_ORDER\"}))\n\t\t}\n\t}\n\tif mt.HandlingInstructions != nil {\n\t\tif !(*mt.HandlingInstructions == \"ORMD\" || *mt.HandlingInstructions == \"LIMITED_QUANTITY\") {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.handling_instructions`, *mt.HandlingInstructions, []interface{}{\"ORMD\", \"LIMITED_QUANTITY\"}))\n\t\t}\n\t}\n\tif mt.LabelFormat != nil {\n\t\tif !(*mt.LabelFormat == \"PNG\" || *mt.LabelFormat == \"PDF\" || *mt.LabelFormat == \"ZPL\" || *mt.LabelFormat == \"EPL2\") {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.label_format`, *mt.LabelFormat, []interface{}{\"PNG\", \"PDF\", \"ZPL\", \"EPL2\"}))\n\t\t}\n\t}\n\treturn\n}",
"func ValidOptions(method string) []string {\n\tnames := []string{}\n\n\tfor n, m := range endpointMethodSupports {\n\t\tif m[method] {\n\t\t\tnames = append(names, n)\n\t\t}\n\t}\n\n\tsort.Strings(names)\n\n\treturn names\n}",
"func (o AgentOptions) Validate() error {\n\tif o.Mbus == \"\" {\n\t\treturn bosherr.Error(\"Must provide a non-empty Mbus\")\n\t}\n\n\treturn nil\n}",
"func (o *PodnetOptions) Validate() error {\n\t/*\n\t\tif len(o.rawConfig.CurrentContext) == 0 {\n\t\t\treturn errNoContext\n\t\t}\n\t\tif len(o.args) > 1 {\n\t\t\treturn fmt.Errorf(\"either one or no arguments are allowed\")\n\t\t}\n\t*/\n\n\tif o.outputFormat != \"\" {\n\t\to.outputFormat = strings.ToLower(o.outputFormat)\n\n\t\tswitch o.outputFormat {\n\t\tcase \"json\", \"text\": // valid format\n\t\tdefault: // illegal format\n\t\t\treturn fmt.Errorf(\"unknown output format %s\", o.outputFormat)\n\t\t}\n\t}\n\n\treturn nil\n}",
"func TestOptionsHaveHelp(t *testing.T) {\n\tfor _, f := range configFields {\n\t\t// Check all choices if this is a group, else check f.name.\n\t\tnames := f.choices\n\t\tif len(names) == 0 {\n\t\t\tnames = []string{f.name}\n\t\t}\n\t\tfor _, name := range names {\n\t\t\tif _, ok := configHelp[name]; !ok {\n\t\t\t\tt.Errorf(\"missing help message for %q\", name)\n\t\t\t}\n\t\t}\n\t}\n}",
"func (o *Options) Validate() error {\n\tif o.NumWorkers == 0 {\n\t\treturn errors.New(\"number of workers cannot be zero\")\n\t}\n\n\tif o.ProwJobNamespace == \"\" {\n\t\treturn errors.New(\"namespace containing ProwJobs not configured\")\n\t}\n\n\treturn o.Options.Validate()\n}",
"func (o *Options) Validate() []error {\n\tvar errs []error\n\terr := validateShowHiddenMetricsVersion(parseVersion(version.Get()), o.ShowHiddenMetricsForVersion)\n\tif err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tif err := validateAllowMetricLabel(o.AllowListMapping); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tif len(errs) == 0 {\n\t\treturn nil\n\t}\n\treturn errs\n}",
"func (sto *SetOptions) Validate() (err error) {\n\treturn\n}",
"func TestAreOpts(t *testing.T) {\n\tcases := []struct {\n\t\tc string\n\t\tisOpt bool\n\t}{\n\t\t{\"se\", true},\n\t\t{\"bg\", true},\n\t\t{\"il\", true},\n\t\t{\"za\", true},\n\t\t{\"ba\", false},\n\t\t{\"12\", false},\n\t\t{\"\", false},\n\t\t{\"hugh\", false},\n\t}\n\n\tfor _, i := range cases {\n\t\tvar isCountry bool = isOptOf(i.c, countryOpts)\n\t\tif isCountry != i.isOpt {\n\t\t\tt.Errorf(\"Expected %v but got %v when case=%v\", i.isOpt, isCountry, i.c)\n\t\t}\n\t}\n}",
"func (lbl Labeler) ValidateOptions() error {\n\treturn lbl.options.Validate()\n}",
"func ValidateCommonOptions(opts config.Options) error {\n\tvar err error\n\n\trpcutils.RPCCertVerify, err = strconv.ParseBool(opts.RPCCertVerify)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error parsing rpc-cert-verify value %v\", err)\n\t}\n\trpcutils.RPCDisableTLS, err = strconv.ParseBool(opts.RPCDisableTLS)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error parsing rpc-disable-tls value %v\", err)\n\t}\n\n\tif err := validation.ValidUIAddress(opts.UIPort); err != nil {\n\t\treturn fmt.Errorf(\"error validating UI port: %s\", err)\n\t}\n\n\t// TODO: move this to ValidateServerOptions if this is really only used by master/agent, and not cli\n\tif err := validation.IsSubnetCIDR(opts.VirtualAddressSubnet); err != nil {\n\t\treturn fmt.Errorf(\"error validating virtual-address-subnet: %s\", err)\n\t}\n\n\treturn nil\n}",
"func (o LogOptions) validateOpts(logDriver string, supportedOpts map[string]bool, validKVs map[string][]string) error {\n\tfor k, v := range o {\n\t\tif !supportedOpts[k] {\n\t\t\treturn fmt.Errorf(\"provided configuration key %q is not supported as a logging option for log driver %s\", k, logDriver)\n\t\t}\n\t\tif validValues, ok := validKVs[k]; ok {\n\t\t\tvalid := false\n\t\t\tfor _, vv := range validValues {\n\t\t\t\tif v == vv {\n\t\t\t\t\tvalid = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !valid {\n\t\t\t\treturn fmt.Errorf(\"provided configuration value %q is not a valid value for %q in log driver %s, valid values: %v\", v, k, logDriver, validValues)\n\t\t\t}\n\n\t\t}\n\t}\n\treturn nil\n}",
"func (o *Options) Validate() []error {\n\tvar errs []error\n\n\treturn errs\n}",
"func (m *UpsertEventRequest_Option) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif utf8.RuneCountInString(m.GetContent()) < 1 {\n\t\treturn UpsertEventRequest_OptionValidationError{\n\t\t\tfield: \"Content\",\n\t\t\treason: \"value length must be at least 1 runes\",\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (o *DebugOptions) Validate() error {\n\tif len(o.args) < 1 {\n\t\treturn fmt.Errorf(\"pod name required\")\n\t}\n\n\treturn nil\n}",
"func (opts *Options) Validate() error {\n\tif len(opts.VersionFile) == 0 {\n\t\topts.VersionFile = \"version.go\"\n\t}\n\tif len(opts.BuildPath) == 0 {\n\t\topts.BuildPath = \".\"\n\t}\n\tif len(opts.MainFile) > 0 {\n\t\tif filepath.Ext(opts.MainFile) != \".go\" {\n\t\t\treturn fmt.Errorf(\"%s is not a .go file\", opts.MainFile)\n\t\t}\n\t\topts.BuildPath = filepath.Dir(opts.MainFile)\n\t\tif len(opts.BuildPath) > 0 {\n\t\t\topts.BuildPath = \"./\" + opts.BuildPath\n\t\t}\n\t}\n\tif len(opts.Root) == 0 {\n\t\treturn fmt.Errorf(\"root can not be empty\")\n\t}\n\treturn nil\n}",
"func (o *Options) Validate() error {\n\terr := o.Options.Validate()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to validate repository options\")\n\t}\n\n\tif o.PreviewHelmfile == \"\" {\n\t\treturn options.MissingOption(\"helmfile\")\n\t}\n\tif o.Number <= 0 {\n\t\tprName := os.Getenv(\"PULL_NUMBER\")\n\t\tif prName != \"\" {\n\t\t\to.Number, err = strconv.Atoi(prName)\n\t\t\tif err != nil {\n\t\t\t\tlog.Logger().Warnf(\n\t\t\t\t\t\"Unable to convert PR \" + prName + \" to a number\")\n\t\t\t}\n\t\t}\n\t\tif o.Number <= 0 {\n\t\t\treturn options.MissingOption(\"pr\")\n\t\t}\n\t}\n\n\to.PreviewClient, o.Namespace, err = previews.LazyCreatePreviewClientAndNamespace(o.PreviewClient, o.Namespace)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create Preview client\")\n\t}\n\tif o.CommandRunner == nil {\n\t\to.CommandRunner = cmdrunner.DefaultCommandRunner\n\t}\n\treturn nil\n}",
"func (m *Arg) Validate() error {\n\tif m.Options != nil {\n\t\tfor _, r := range *m.Options {\n\t\t\tif err := r.Validate(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (f *flag) validate() error {\n\tif f.Type != \"string\" || len(f.Enum) == 0 {\n\t\treturn nil\n\t}\n\tval := f.cobraFlag.Value.String()\n\tfor _, validVal := range f.Enum {\n\t\tif val == validVal {\n\t\t\treturn nil\n\t\t}\n\t}\n\toptions := fmt.Sprintf(\"[%v]\", strings.Join(f.Enum, \", \"))\n\terrMsg := fmt.Sprintf(\"Invalid \\\"%s\\\" flag option: %s\\nAvailable options are: %s\\n\", f.Long, val, options)\n\treturn errors.New(errMsg)\n\t// ===== Sample Output =====\n\t// Invalid \"environment\" flag option: testing\n\t// Available options are: [development, staging, production]\n}",
"func (do *DescribeOptions) Validate() (err error) {\n\tisExists, err := component.Exists(do.Context.Client, do.componentName, do.Context.Application)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !isExists {\n\t\treturn fmt.Errorf(\"component %s does not exist\", do.componentName)\n\t}\n\n\treturn odoutil.CheckOutputFlag(do.outputFlag)\n}",
"func (o *overrideOpts) Validate() error {\n\tif err := o.validateAppName(); err != nil {\n\t\treturn err\n\t}\n\treturn o.validateCDKLang()\n}",
"func (o *CreateDeploymentOptions) Validate() error {\n\tif len(o.Images) > 1 && len(o.Command) > 0 {\n\t\treturn fmt.Errorf(\"cannot specify multiple --image options and command\")\n\t}\n\treturn nil\n}",
"func (b *BaseOptions) Check() {\n\n\t// Check port first\n\tif b.port > 65535 {\n\t\tlog.Fatal(\"Invalid port: \", b.port)\n\t}\n\n\t// Update settings from config and config from parameters\n\tb.updateFromConfig()\n\tif b.domain == \"\" {\n\t\tlog.Fatal(\"-domain is mandatory\")\n\t}\n\n}",
"func (o *YurttunnelServerOptions) validate() error {\n\tif len(o.bindAddr) == 0 {\n\t\treturn fmt.Errorf(\"%s's bind address can't be empty\",\n\t\t\tprojectinfo.GetServerName())\n\t}\n\treturn nil\n}",
"func (o *showSvcOpts) Validate() error {\n\treturn nil\n}",
"func (o *KubeOptions) Validate() error {\n\n\treturn nil\n}",
"func (o *KubeOptions) Validate() error {\n\n\treturn nil\n}",
"func (o PlannerOptions) Validate() error {\n\tif o.MutableCompactionAgeThreshold < 0 {\n\t\treturn errMutableCompactionAgeNegative\n\t}\n\tif len(o.Levels) == 0 {\n\t\treturn errLevelsUndefined\n\t}\n\tsort.Sort(ByMinSize(o.Levels))\n\tfor i := 0; i < len(o.Levels); i++ {\n\t\tcurrent := o.Levels[i]\n\t\tif current.MaxSizeExclusive <= current.MinSizeInclusive {\n\t\t\treturn fmt.Errorf(\"illegal size levels definition, MaxSize <= MinSize (%+v)\", current)\n\t\t}\n\t}\n\treturn nil\n}",
"func (o *TunnelServerOptions) validate() error {\n\tif len(o.bindAddr) == 0 {\n\t\treturn fmt.Errorf(\"%s's bind address can't be empty\",\n\t\t\tversion.GetServerName())\n\t}\n\treturn nil\n}",
"func validate(cfg Settings) error {\n\tif len(cfg.Selectors) == 0 {\n\t\treturn errors.New(\"no selectors configured\")\n\t}\n\tif cfg.ServiceTLS {\n\t\treturn errors.New(\"TLS mode not yet implemented\")\n\t}\n\n\treturn nil\n}",
"func (c *Tag) CheckOption(args ...string) bool {\n\tfor _, arg := range args {\n\t\t_, exist := c.Values[arg]\n\t\tif exist {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}",
"func (o TopImagesOptions) Validate(cmd *cobra.Command) error {\n\treturn nil\n}",
"func validateCmdLineOpts(start_domain string, max_concurrent int) (bool, string) {\n\tif govalidator.IsURL(start_domain) == false {\n\t\treturn false, fmt.Sprintf(\"Please specify a valid URL to crawl. You entered %s.\\n\", start_domain)\n\t}\n\t// We only need to confirm if start_domain starts with http.\n\t// govalidator validates absolute and non-absolute URLs. If an absolute URL\n\t// is entered in a illegal format, govalidator will catch it.\n\tif strings.HasPrefix(start_domain, \"http\") == false {\n\t\treturn false, fmt.Sprintf(\"The domain name must be in the form http[s]://name.xx. You entered %s.\\n\", start_domain)\n\t}\n\tif max_concurrent < 1 || max_concurrent > 50 {\n\t\treturn false, fmt.Sprintf(\"Max concurrent process value must be between 1 and 50. You entered %d.\\n\", max_concurrent)\n\t}\n\treturn true, \"\"\n}",
"func (g *GenOpts) CheckOpts() error {\n\tif g == nil {\n\t\treturn errors.New(\"gen opts are required\")\n\t}\n\n\tif !filepath.IsAbs(g.Target) {\n\t\tif _, err := filepath.Abs(g.Target); err != nil {\n\t\t\treturn fmt.Errorf(\"could not locate target %s: %v\", g.Target, err)\n\t\t}\n\t}\n\n\tif filepath.IsAbs(g.ServerPackage) {\n\t\treturn fmt.Errorf(\"you shouldn't specify an absolute path in --server-package: %s\", g.ServerPackage)\n\t}\n\n\tif strings.HasPrefix(g.Spec, \"http://\") || strings.HasPrefix(g.Spec, \"https://\") {\n\t\treturn nil\n\t}\n\n\tpth, err := findSwaggerSpec(g.Spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// ensure spec path is absolute\n\tg.Spec, err = filepath.Abs(pth)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not locate spec: %s\", g.Spec)\n\t}\n\n\treturn nil\n}",
"func ValidateGlobalOpts() error {\n\tvar reqGlobalOpts = []string{GlobalOpts.oidcIssuerURL, GlobalOpts.oidcClientID, GlobalOpts.kebAPIURL, GlobalOpts.mothershipAPIURL}\n\tvar missingGlobalOpts []string\n\tfor _, opt := range reqGlobalOpts {\n\t\tif viper.GetString(opt) == \"\" {\n\t\t\tmissingGlobalOpts = append(missingGlobalOpts, opt)\n\t\t}\n\t}\n\n\tif len(missingGlobalOpts) == 0 {\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"missing required options: %s. See kcp --help for more information\", strings.Join(missingGlobalOpts, \", \"))\n}",
"func (o *ViewOptions) Validate() (err error) {\n\treturn\n}",
"func (pOpts *HelperPodOptions) validate() error {\n\tif pOpts.name == \"\" || pOpts.path == \"\" || pOpts.nodeName == \"\" {\n\t\treturn errors.Errorf(\"invalid empty name or path or node\")\n\t}\n\treturn nil\n}",
"func (opts *Options) valid() (err error) {\n\tif opts.Threads <= 0 {\n\t\treturn errors.New(\"invalid number of threads\")\n\t}\n\n\tif len(opts.Range) > 0 && opts.Filename != \"\" {\n\t\treturn errors.New(\"only one source allowed but both range and filename specified\")\n\t}\n\n\tif len(opts.Range) == 0 && opts.Filename == \"\" {\n\t\treturn errors.New(\"neither file nor range specified, nothing to do\")\n\t}\n\n\topts.extract, err = compileRegexps(opts.Extract)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\topts.extractPipe, err = splitShell(opts.ExtractPipe)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\topts.hidePattern, err = compileRegexps(opts.HidePattern)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\topts.showPattern, err = compileRegexps(opts.ShowPattern)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func (opts *SyncOpts) Valid() error {\n\tif opts == nil {\n\t\treturn errors.New(\"mount sync options are nil\")\n\t}\n\tif opts.ClientFunc == nil {\n\t\treturn errors.New(\"nil dynamic client function\")\n\t}\n\tif opts.NotifyBuilder == nil {\n\t\treturn errors.New(\"file system notification builder is nil\")\n\t}\n\tif opts.SyncBuilder == nil {\n\t\treturn errors.New(\"synchronization builder is nil\")\n\t}\n\tif opts.WorkDir == \"\" {\n\t\treturn errors.New(\"working directory is not set\")\n\t}\n\n\treturn nil\n}",
"func (o Order) Valid() error {\n\t_, ok := orderOptions[o]\n\tif !ok {\n\t\tlog.Println(\"error while validating query param: order\")\n\t\tlog.Printf(\"value: %s\", string(o))\n\t\treturn errors.New(\"invalid query param: order\")\n\t}\n\treturn nil\n}",
"func (o DeleteOptions) Validate(c *cobra.Command, args []string) error {\n\treturn nil\n}",
"func validateProgramArgs() {\n\tif *version {\n\t\tshowVersion()\n\t}\n\n\tif *helpUsage {\n\t\tusage(0)\n\t}\n\n\tif *helpFull {\n\t\tshowHelp(0)\n\t}\n\n\tif *LocalFolderPath == \"\" ||\n\t\t(*dpUsername != \"\" && *dpRestURL == \"\" && *dpSomaURL == \"\") {\n\t\tusage(1)\n\t}\n\n}",
"func (s *Options) Validate() []error {\n\tvar errs []error\n\n\terrs = append(errs, s.Etcd.Validate()...)\n\terrs = append(errs, validateAPIPriorityAndFairness(s)...)\n\terrs = append(errs, s.SecureServing.Validate()...)\n\terrs = append(errs, s.Authentication.Validate()...)\n\terrs = append(errs, s.Authorization.Validate()...)\n\terrs = append(errs, s.Audit.Validate()...)\n\terrs = append(errs, s.Admission.Validate()...)\n\terrs = append(errs, s.APIEnablement.Validate(legacyscheme.Scheme, apiextensionsapiserver.Scheme, aggregatorscheme.Scheme)...)\n\terrs = append(errs, validateTokenRequest(s)...)\n\terrs = append(errs, s.Metrics.Validate()...)\n\terrs = append(errs, validateUnknownVersionInteroperabilityProxyFeature()...)\n\terrs = append(errs, validateUnknownVersionInteroperabilityProxyFlags(s)...)\n\n\treturn errs\n}",
"func (o Options) Validate() []error {\n\treturn []error{\n\t\to.validateTLS(),\n\t}\n}",
"func (o ModuleOptions) Validate(c *cobra.Command, args []string) error {\n\tif len(o.falcoVersion) == 0 {\n\t\treturn fmt.Errorf(\"missing Falco version: specify it via FALCOCTL_FALCO_VERSION env variable or via --falco-version flag\")\n\t}\n\treturn nil\n}",
"func (o *GrowManifestOptions) Validate() error {\n\tif o.BaseDir == \"\" {\n\t\treturn xerrors.New(\"must specify --base_dir\")\n\t}\n\n\tif o.StagingRepo == \"\" {\n\t\treturn xerrors.New(\"must specify --staging_repo\")\n\t}\n\n\tif o.FilterTag == latestTag {\n\t\treturn xerrors.Errorf(\n\t\t\t\"--filter_tag cannot be %q (anti-pattern)\", latestTag)\n\t}\n\treturn nil\n}",
"func (m *CreateStatusOption) Validate(formats strfmt.Registry) error {\n\treturn nil\n}",
"func (o CertificateCreateOpts) Validate() error {\n\tif o.Name == \"\" {\n\t\treturn errors.New(\"missing name\")\n\t}\n\tif o.Certificate == \"\" {\n\t\treturn errors.New(\"missing certificate\")\n\t}\n\tif o.PrivateKey == \"\" {\n\t\treturn errors.New(\"missing private key\")\n\t}\n\treturn nil\n}",
"func (v *Validator) Validate(cfg map[string]map[string]string) (map[string]map[string]interface{}, error) {\n\tstates := v.ensureTypes(cfg)\n\tv.ensureValid(states)\n\tknown, required := v.getKnownRequired(states)\n\n\tfor section, options := range cfg {\n\t\toptionKnown, sectionIsKnown := known[section]\n\t\tif !sectionIsKnown {\n\t\t\treturn nil, errors.New(\"bad section: \" + section)\n\t\t}\n\n\t\tfor option := range options {\n\t\t\toptionNotIgnored, optionIsKnown := optionKnown[option]\n\t\t\tif !optionIsKnown || !optionNotIgnored {\n\t\t\t\treturn nil, errors.New(\"bad option: \" + section + \".\" + option)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor section, options := range required {\n\t\toptionStates := states[section]\n\n\t\tfor option, isRequired := range options {\n\t\t\tif isRequired && !optionStates[option].Present {\n\t\t\t\treturn nil, errors.New(\"missing option: \" + section + \".\" + option)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor section, options := range states {\n\t\tfor option, state := range options {\n\t\t\tif state.TypeError != nil {\n\t\t\t\treturn nil, errors.New(\"bad type of option: \" + section + \".\" + option + \": \" + state.TypeError.Error())\n\t\t\t}\n\t\t}\n\t}\n\n\tfor section, options := range states {\n\t\tfor option, state := range options {\n\t\t\tif state.ValidationError != nil {\n\t\t\t\treturn nil, errors.New(\"bad value of option: \" + section + \".\" + option + \": \" + state.ValidationError.Error())\n\t\t\t}\n\t\t}\n\t}\n\n\tresult := map[string]map[string]interface{}{}\n\n\tfor section, options := range states {\n\t\tresultSection := map[string]interface{}{}\n\n\t\tfor option, state := range options {\n\t\t\tresultSection[option] = state.Value\n\t\t}\n\n\t\tresult[section] = resultSection\n\t}\n\n\treturn result, nil\n}",
"func (o *SubjectOptions) Validate() error {\n\tif o.Local && o.DryRunStrategy == cmdutil.DryRunServer {\n\t\treturn fmt.Errorf(\"cannot specify --local and --dry-run=server - did you mean --dry-run=client?\")\n\t}\n\tif o.All && len(o.Selector) > 0 {\n\t\treturn fmt.Errorf(\"cannot set --all and --selector at the same time\")\n\t}\n\tif len(o.Users) == 0 && len(o.Groups) == 0 && len(o.ServiceAccounts) == 0 {\n\t\treturn fmt.Errorf(\"you must specify at least one value of user, group or serviceaccount\")\n\t}\n\n\tfor _, sa := range o.ServiceAccounts {\n\t\ttokens := strings.Split(sa, \":\")\n\t\tif len(tokens) != 2 || tokens[1] == \"\" {\n\t\t\treturn fmt.Errorf(\"serviceaccount must be <namespace>:<name>\")\n\t\t}\n\n\t\tfor _, info := range o.Infos {\n\t\t\t_, ok := info.Object.(*rbacv1.ClusterRoleBinding)\n\t\t\tif ok && tokens[0] == \"\" {\n\t\t\t\treturn fmt.Errorf(\"serviceaccount must be <namespace>:<name>, namespace must be specified\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (opts *generateOptions) Validate() error {\n\tif opts.configFile == \"\" &&\n\t\tlen(opts.images) == 0 &&\n\t\tlen(opts.files) == 0 &&\n\t\tlen(opts.imageArchives) == 0 &&\n\t\tlen(opts.archives) == 0 &&\n\t\tlen(opts.archives) == 0 &&\n\t\tlen(opts.directories) == 0 {\n\t\treturn errors.New(\"to generate a SPDX BOM you have to provide at least one image or file\")\n\t}\n\n\tif opts.format != spdx.FormatTagValue && opts.format != spdx.FormatJSON {\n\t\treturn fmt.Errorf(\"unknown format provided, must be one of [%s, %s]: %s\",\n\t\t\tspdx.FormatTagValue, spdx.FormatJSON, opts.format)\n\t}\n\n\t// Check if specified local files exist\n\tfor _, col := range []struct {\n\t\tItems []string\n\t\tName string\n\t}{\n\t\t{opts.imageArchives, \"image archive\"},\n\t\t{opts.files, \"file\"},\n\t\t{opts.directories, \"directory\"},\n\t\t{opts.archives, \"archive\"},\n\t} {\n\t\t// Check if image archives exist\n\t\tfor i, iPath := range col.Items {\n\t\t\tif !isGlob(iPath) && !util.Exists(iPath) {\n\t\t\t\treturn fmt.Errorf(\"%s #%d not found (%s)\", col.Name, i+1, iPath)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}",
"func (opts *ClientOptions) Validate() error {\n\tif opts.Host == \"\" {\n\t\treturn errors.New(\"error: Host must be specified\")\n\t}\n\tif opts.Version == \"\" {\n\t\treturn errors.New(\"error: Version must be specified\")\n\t}\n\tif opts.Key == \"\" {\n\t\treturn errors.New(\"error: Key must be specified\")\n\t}\n\tif !keyRegex.MatchString(opts.Key) {\n\t\treturn errors.New(\"error: Key must be 26 hex characters long\")\n\t}\n\n\tisSupportedVersion := false\n\tfor _, v := range supportedVersions {\n\t\tif v == opts.Version {\n\t\t\tisSupportedVersion = true\n\t\t}\n\t}\n\tif !isSupportedVersion {\n\t\treturn errors.New(fmt.Sprintf(\"error: Version %s is not supported by the Content API\", opts.Version))\n\t}\n\n\tif opts.GhostPath == \"\" {\n\t\topts.GhostPath = \"ghost\"\n\t}\n\n\treturn nil\n}",
"func (o Aliases) IsOption() {}",
"func (d *deliveryRepository) validateDeliveryOption(tx *gorm.DB, p *delivery.RequestCreateDelivery) error {\n\tvar deliveryOption delivery.DeliveryOption\n\n\tres := tx.Table(\"delivery_option\").\n\t\tSelect(\"name\").\n\t\tWhere(\"name = ?\", p.DeliveryOption).\n\t\tFirst(&deliveryOption).Error\n\n\t// No record found\n\tif errors.Is(res, gorm.ErrRecordNotFound) {\n\t\treturn errors.New(\"delivery_option not found\")\n\t}\n\t// MYSQL err\n\tif res != nil {\n\t\treturn errors.New(\"error validating the delivery option: \" + res.Error())\n\t}\n\t// Dropship only...\n\tif deliveryOption.Name != \"Dropship\" {\n\t\treturn errors.New(\"delivery_option must be dropship only: \")\n\t}\n\treturn nil\n}",
"func (o Options) ValidateNormalize(options map[string]string) (map[string]interface{}, error) {\n\toutput := make(map[string]interface{})\n\n\tfor key, value := range options {\n\t\toption, found := o[key]\n\t\tif !found {\n\t\t\treturn output, fmt.Errorf(\"invalid option: %s\", key)\n\t\t}\n\n\t\tswitch option.Type {\n\t\tcase OptionTypeBool:\n\t\t\t// Try to convert to bool\n\t\t\tif parsed, err := strconv.ParseBool(value); err == nil {\n\t\t\t\toutput[key] = parsed\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlower := strings.ToLower(value)\n\t\t\toutput[key] = lower == \"on\" || lower == \"yes\" || lower == \"y\"\n\t\tcase OptionTypeInt:\n\t\t\t// Try to convert to int\n\t\t\tparsed, err := strconv.Atoi(value)\n\t\t\tif err != nil {\n\t\t\t\treturn output, fmt.Errorf(\"couldn't convert option %s value (%s) to int\", key, value)\n\t\t\t}\n\t\t\toutput[key] = parsed\n\t\tcase OptionTypeEnum:\n\t\t\t// Try to convert to int\n\t\t\tif option.AllowedValues == nil {\n\t\t\t\treturn output, fmt.Errorf(\"no allowed values set for option %s\", key)\n\t\t\t}\n\t\t\tif IndexOf(value, option.AllowedValues) < 0 {\n\t\t\t\treturn output, fmt.Errorf(\n\t\t\t\t\t\"invalid value set for option %s: %s (allowed values are %s)\",\n\t\t\t\t\tkey,\n\t\t\t\t\tvalue,\n\t\t\t\t\tstrings.Join(option.AllowedValues, \", \"),\n\t\t\t\t)\n\t\t\t}\n\t\t\toutput[key] = value\n\t\t}\n\t}\n\n\treturn output, nil\n}",
"func ValidateRecommendedOptions(o *options.RecommendedOptions) []error {\n\terrors := []error{}\n\n\terrors = append(errors, o.Etcd.Validate()...)\n\terrors = append(errors, o.SecureServing.Validate()...)\n\n\tif o.Authentication != nil {\n\t\terrors = append(errors, o.Authentication.Validate()...)\n\t}\n\tif o.Authorization != nil {\n\t\terrors = append(errors, o.Authorization.Validate()...)\n\t}\n\n\terrors = append(errors, o.Audit.Validate()...)\n\terrors = append(errors, o.Features.Validate()...)\n\terrors = append(errors, o.CoreAPI.Validate()...)\n\terrors = append(errors, o.Admission.Validate()...)\n\terrors = append(errors, o.EgressSelector.Validate()...)\n\n\treturn errors\n\n}",
"func (s *DeprecatedInsecureServingOptions) Validate() []error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\terrors := []error{}\n\n\tif s.BindPort < 0 || s.BindPort > 65535 {\n\t\terrors = append(errors, fmt.Errorf(\"insecure port %v must be between 0 and 65535, inclusive. 0 for turning off insecure (HTTP) port\", s.BindPort))\n\t}\n\n\treturn errors\n}",
"func (o PruneBuildsOptions) Validate() error {\n\tif o.KeepYoungerThan < 0 {\n\t\treturn fmt.Errorf(\"--keep-younger-than must be greater than or equal to 0\")\n\t}\n\tif o.KeepComplete < 0 {\n\t\treturn fmt.Errorf(\"--keep-complete must be greater than or equal to 0\")\n\t}\n\tif o.KeepFailed < 0 {\n\t\treturn fmt.Errorf(\"--keep-failed must be greater than or equal to 0\")\n\t}\n\treturn nil\n}",
"func (m *HealthCheck_TlsOptions) Validate() error {\n\treturn m.validate(false)\n}"
] | [
"0.7381278",
"0.721756",
"0.7131414",
"0.709364",
"0.7065572",
"0.70514625",
"0.69760054",
"0.69511366",
"0.69257426",
"0.69165695",
"0.690812",
"0.6894476",
"0.68906975",
"0.6711808",
"0.66819566",
"0.664281",
"0.66051817",
"0.6581078",
"0.65646976",
"0.6562564",
"0.6533593",
"0.6519913",
"0.6502058",
"0.64879864",
"0.6473262",
"0.6469526",
"0.6465653",
"0.6450042",
"0.6428175",
"0.63862777",
"0.63542604",
"0.6347241",
"0.63405406",
"0.63103783",
"0.63050145",
"0.6259997",
"0.6254983",
"0.62536395",
"0.6230642",
"0.6225397",
"0.62252975",
"0.6224867",
"0.6219907",
"0.6214924",
"0.6207852",
"0.6199673",
"0.6195125",
"0.6187022",
"0.6156811",
"0.6143853",
"0.6137783",
"0.6125543",
"0.61195564",
"0.6103484",
"0.6100027",
"0.60943156",
"0.60876787",
"0.60859513",
"0.60758275",
"0.6066651",
"0.60417116",
"0.60382336",
"0.6034929",
"0.60325223",
"0.6029262",
"0.6027636",
"0.6016266",
"0.6016266",
"0.6013808",
"0.60032636",
"0.60030663",
"0.59958494",
"0.59917164",
"0.59876096",
"0.5984272",
"0.5976349",
"0.5973117",
"0.59454197",
"0.59408814",
"0.59264624",
"0.5919848",
"0.5919818",
"0.591351",
"0.59059715",
"0.5904748",
"0.59004027",
"0.588976",
"0.58875746",
"0.58867115",
"0.5866164",
"0.5856591",
"0.5843187",
"0.58395714",
"0.5837701",
"0.58364594",
"0.5836168",
"0.5831144",
"0.582063",
"0.5806985",
"0.5801259"
] | 0.6878621 | 13 |
NewNetworkProvider is a constructor for the TCP based peering network implementation. | func NewNetworkProvider(myNetID string, port int, nodeKeyPair *key.Pair, suite kyber.Group, log *logger.Logger) (*NetImpl, error) {
if err := peering.CheckMyNetID(myNetID, port); err != nil {
// can't continue because NetID parameter is not correct
log.Panicf("checkMyNetworkID: '%v'. || Check the 'netid' parameter in config.json", err)
return nil, err
}
n := NetImpl{
myNetID: myNetID,
port: port,
peers: make(map[string]*peer),
peersMutex: &sync.RWMutex{},
nodeKeyPair: nodeKeyPair,
suite: suite,
log: log,
}
n.events = events.NewEvent(n.eventHandler)
return &n, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func newNetworkLayer(ln net.Listener, publicRaftAddr string) *networkLayer {\n\taddr, _ := net.ResolveTCPAddr(\"tcp\", publicRaftAddr)\n\treturn &networkLayer{\n\t\tln: ln,\n\t\taddr: addr,\n\t}\n}",
"func newNetwork(peers ...stateMachine) *network {\n\treturn newNetworkWithConfig(nil, peers...)\n}",
"func NewNetwork(prcId uint32, chanFromMutex chan string, chanToMutex chan string, mutex mutex.Mutex)*Network {\n\tnetwork := new(Network)\n\tnetwork.procId = prcId\n\tnetwork.in = make(chan string)\n\tnetwork.out = make(chan string)\n\tnetwork.entering = make(chan struct{\n\t\tuint32\n\t\tnet.Conn\n\t})\n\tnetwork.chanToMutex = chanToMutex\n\tnetwork.chanFromMutex = chanFromMutex\n\tnetwork.mutex = mutex\n\tnetwork.site = make(map[uint32]net.Conn)\n\treturn network\n\n}",
"func NewNetwork() *Network {\n\treturn &Network{\n\t\tport: 1234,\n\t}\n}",
"func NewNetwork() *Network {\n\tnet := &Network{\n\t\tvms: make(map[int]*intcode.VM),\n\t\tmsgs: make(map[int]chan int),\n\t\tpackets: make(chan packet, 128),\n\t}\n\tnet.nat = newNAT(net)\n\treturn net\n}",
"func NewNetwork(dht *DHT, self *Node) (*Network, error) {\n\ts := &Network{\n\t\tdht: dht,\n\t\tself: self,\n\t\tdone: make(chan struct{}),\n\t}\n\t// init the rate limiter\n\ts.limiter = ratelimit.New(defaultConnRate)\n\n\taddr := fmt.Sprintf(\"%s:%d\", self.IP, self.Port)\n\t// new the network socket\n\tsocket, err := utp.NewSocket(\"udp\", addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.socket = socket\n\n\treturn s, nil\n}",
"func New(pg plugingetter.PluginGetter, netConfig *NetworkConfig) (networkallocator.NetworkAllocator, error) {\n\tna := &cnmNetworkAllocator{\n\t\tnetworks: make(map[string]*network),\n\t\tservices: make(map[string]struct{}),\n\t\ttasks: make(map[string]struct{}),\n\t\tnodes: make(map[string]map[string]struct{}),\n\t\tpg: pg,\n\t}\n\n\tfor ntype, i := range initializers {\n\t\tif err := i(&na.networkRegistry); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to register %q network driver: %w\", ntype, err)\n\t\t}\n\t}\n\tif err := remote.Register(&na.networkRegistry, pg); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize network driver plugins: %w\", err)\n\t}\n\n\tif err := initIPAMDrivers(&na.ipamRegistry, netConfig); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := remoteipam.Register(&na.ipamRegistry, pg); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize IPAM driver plugins: %w\", err)\n\t}\n\n\tpa, err := newPortAllocator()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tna.portAllocator = pa\n\treturn na, nil\n}",
"func NewNetwork(opts ...options.Option) Network {\n\toptions := options.NewOptions(opts...)\n\n\t// get router\n\n\t// get proxy\n\n\treturn &network{\n\t\tOptions: options,\n\t\t// fill the blanks\n\t\t// router: r,\n\t\t// proxy: p,\n\t}\n}",
"func newNetwork(networkType NetworkModel) network {\n\tswitch networkType {\n\tcase NoopNetworkModel:\n\t\treturn &noopNetwork{}\n\tcase DefaultNetworkModel:\n\t\treturn &defNetwork{}\n\tdefault:\n\t\treturn &noopNetwork{}\n\t}\n}",
"func NewNetwork(cfg SourceGeneratorConfig) Sourcer {\n\treturn &Network{\n\t\tschema: []idk.Field{\n\t\t\tidk.IDField{NameVal: \"id\"}, // 0\n\t\t\tidk.IDField{NameVal: \"qos_tier\"}, // 1\n\t\t\tidk.IntField{NameVal: \"source_equip_id\"}, // 2\n\t\t\tidk.IntField{NameVal: \"dest_equip_id\"}, // 3\n\t\t\tidk.IntField{NameVal: \"data_size\"}, // 4\n\t\t\tidk.StringField{NameVal: \"data_type\"}, // 5\n\t\t\tidk.StringField{NameVal: \"customer\"}, // 6\n\t\t\tidk.IntField{NameVal: \"timestamp\"}, // 7\n\t\t},\n\t}\n}",
"func New(chain []byte) (p *Provider, err error) {\n\tp = &Provider{}\n\tif err = p.Decode(chain); err != nil {\n\t\treturn nil, err\n\t}\n\treturn p, nil\n}",
"func NewNetwork(ctx *pulumi.Context,\n\tname string, args *NetworkArgs, opts ...pulumi.ResourceOpt) (*Network, error) {\n\tinputs := make(map[string]interface{})\n\tif args == nil {\n\t\tinputs[\"attachable\"] = nil\n\t\tinputs[\"checkDuplicate\"] = nil\n\t\tinputs[\"driver\"] = nil\n\t\tinputs[\"ingress\"] = nil\n\t\tinputs[\"internal\"] = nil\n\t\tinputs[\"ipamConfigs\"] = nil\n\t\tinputs[\"ipamDriver\"] = nil\n\t\tinputs[\"ipv6\"] = nil\n\t\tinputs[\"labels\"] = nil\n\t\tinputs[\"name\"] = nil\n\t\tinputs[\"options\"] = nil\n\t} else {\n\t\tinputs[\"attachable\"] = args.Attachable\n\t\tinputs[\"checkDuplicate\"] = args.CheckDuplicate\n\t\tinputs[\"driver\"] = args.Driver\n\t\tinputs[\"ingress\"] = args.Ingress\n\t\tinputs[\"internal\"] = args.Internal\n\t\tinputs[\"ipamConfigs\"] = args.IpamConfigs\n\t\tinputs[\"ipamDriver\"] = args.IpamDriver\n\t\tinputs[\"ipv6\"] = args.Ipv6\n\t\tinputs[\"labels\"] = args.Labels\n\t\tinputs[\"name\"] = args.Name\n\t\tinputs[\"options\"] = args.Options\n\t}\n\tinputs[\"scope\"] = nil\n\ts, err := ctx.RegisterResource(\"docker:index/network:Network\", name, true, inputs, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Network{s: s}, nil\n}",
"func New(address mynet.Address) Network {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", address.(string))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tnetwork := Network{\n\t\taddress: addr,\n\t}\n\t// FIXME: error handling\n\tlistener, err := net.Listen(\"tcp\", \":\"+strconv.Itoa(addr.Port))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tnetwork.listener = listener\n\n\treturn network\n}",
"func NewNetwork(ctx *pulumi.Context,\n\tname string, args *NetworkArgs, opts ...pulumi.ResourceOption) (*Network, error) {\n\tif args == nil {\n\t\targs = &NetworkArgs{}\n\t}\n\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Network\n\terr := ctx.RegisterResource(\"openstack:networking/network:Network\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func NewNetwork(ctx context.Context, num int) ([]*Peer, error) {\n\tvar span opentracing.Span\n\tspan, ctx = opentracing.StartSpanFromContext(ctx, \"NewNetwork\")\n\tpeers := make([]*Peer, 0, num)\n\n\tfor i := 0; i < num; i++ {\n\t\tparams, err := testutil.RandPeerNetParams()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tp, err := NewPeer(ctx, params)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"error creating peer: %s\", err.Error())\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpeers = append(peers, p)\n\t}\n\tspan.Finish()\n\treturn peers, nil\n}",
"func NewProvider(kubeClient kubernetes.Interface, wsCatalog *witesand.WitesandCatalog, clusterId string, stop chan struct{}, meshSpec smi.MeshSpec, providerIdent string) (*Client, error) {\n\n\tclient := Client{\n\t\twsCatalog: wsCatalog,\n\t\tproviderIdent: providerIdent,\n\t\tclusterId: clusterId,\n\t\tmeshSpec: meshSpec,\n\t\tcaches: nil,\n\t\tannouncements: make(chan a.Announcement),\n\t}\n\n\tclient.caches = &CacheCollection{\n\t\tk8sToServiceEndpoints: make(map[string]*ServiceToEndpointMap),\n\t}\n\n\tif err := client.run(); err != nil {\n\t\treturn nil, errors.Errorf(\"Failed to start Remote EndpointProvider client: %+v\", err)\n\t}\n\tlog.Info().Msgf(\"[NewProvider] started Remote provider\")\n\n\treturn &client, nil\n}",
"func newClusterNetwork(c *Client) *clusterNetwork {\n\treturn &clusterNetwork{\n\t\tr: c,\n\t}\n}",
"func NewTCP(config *ConfigTCP, internal *InternalConfig) (Provider, error) {\n\tl := &tcp{}\n\n\tl.quit = make(chan struct{})\n\tl.InternalConfig = *internal\n\tl.config = *config.transport\n\tl.tls = config.TLS\n\n\tvar err error\n\n\tif l.listener, err = net.Listen(config.Scheme, config.transport.Host+\":\"+config.transport.Port); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif l.tls != nil {\n\t\tl.protocol = \"ssl\"\n\t} else {\n\t\tl.protocol = \"tcp\"\n\n\t}\n\n\tl.log = configuration.GetLogger().Named(\"listener: \" + l.protocol + \"://:\" + config.transport.Port)\n\n\treturn l, nil\n}",
"func newNetwork(cfg *config.Network, c *ec2.EC2) (*network, error) {\n\tlog.Debug(\"Initializing AWS Network\")\n\tn := &network{\n\t\tResources: resource.NewResources(),\n\t\tNetwork: cfg,\n\t\tec2: c,\n\t}\n\n\tvpc, err := newVpc(c, n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn.vpc = vpc\n\tn.Append(vpc)\n\n\trouteTables, err := newRouteTables(c, n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn.routeTables = routeTables\n\tn.Append(routeTables)\n\n\tinternetGateway, err := newInternetGateway(c, n, \"public\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn.internetGateway = internetGateway\n\tn.Append(internetGateway)\n\n\t// Load the vpc since it is needed for the caches.\n\terr = n.vpc.Load()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tn.subnetCache, err = newSubnetCache(n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn.secgroupCache, err = newSecurityGroupCache(n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn n, nil\n}",
"func NewProvider(typeName string, crypto domain.Crypto) *Provider {\n\treturn &Provider{\n\t\ttypeName: typeName,\n\t\tbqClients: map[string]*bigQueryClient{},\n\t\tiamClients: map[string]*iamClient{},\n\t\tcrypto: crypto,\n\t}\n}",
"func newNetService() *netService {\n\treturn &netService{\n\t\tagents: make(map[int64]*agent),\n\t\tacceptorUid: 0,\n\t\tacceptors: make(map[int64]*acceptor),\n\t}\n}",
"func NewProvider(username string, password string) *Provider {\n transport := httptransport.New(\"api.autodns.com\", \"/v1\", []string{\"https\"})\n transport.DefaultAuthentication = httptransport.BasicAuth(username, password)\n\n formats := strfmt.Default\n\n return &Provider{\n username: username,\n password: password,\n client: zone_tasks.New(transport, formats),\n }\n}",
"func NewNetworkPeering(ctx *pulumi.Context,\n\tname string, args *NetworkPeeringArgs, opts ...pulumi.ResourceOption) (*NetworkPeering, error) {\n\tif args == nil || args.Network == nil {\n\t\treturn nil, errors.New(\"missing required argument 'Network'\")\n\t}\n\tif args == nil || args.PeerNetwork == nil {\n\t\treturn nil, errors.New(\"missing required argument 'PeerNetwork'\")\n\t}\n\tif args == nil {\n\t\targs = &NetworkPeeringArgs{}\n\t}\n\tvar resource NetworkPeering\n\terr := ctx.RegisterResource(\"gcp:compute/networkPeering:NetworkPeering\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func NewProvider(provider, username, password string) (Provider, error) {\n\tswitch provider {\n\tcase \"ptc\":\n\t\treturn ptc.NewProvider(username, password), nil\n\tcase \"google\":\n\t\treturn google.NewProvider(username, password), nil\n\tdefault:\n\t\treturn &UnknownProvider{}, fmt.Errorf(\"Provider \\\"%s\\\" is not supported\", provider)\n\t}\n}",
"func NewNetwork(spec *types.NetworkSpec) (Network, error) {\n\tn := &network{\n\t\tname: spec.Name,\n\t\ttyp: spec.Type,\n\t\tuseNAT: spec.UseNAT,\n\t}\n\tif len(spec.Address) > 0 {\n\t\taddr, err := netlink.ParseAddr(spec.Address)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tn.addr = addr\n\t}\n\n\treturn n, nil\n}",
"func New(provider string) (Provider, error) {\n\tswitch provider {\n\tcase \"freeGeoIP\":\n\t\tpr := new(freeGeoIP)\n\t\treturn pr, nil\n\t}\n\treturn nil, ErrNoSuchProvider\n}",
"func New(providerType string) CloudProvider {\n\tproviderType = strings.ToLower(providerType)\n\tswitch providerType {\n\tcase \"centurylink\":\n\t\treturn NewCenturylink()\n\tcase \"amazon\":\n\t\treturn NewAmazon()\n\t}\n\treturn nil\n}",
"func NewProvider() (Service, error) {\n\treturn &WinProvider{}, nil\n}",
"func newProviderImpl(name string) (Provider, error) {\n\tif name == LOCAL {\n\t\treturn &LocalProvider{}, nil\n\t}\n\n\tif name == AWS {\n\t\treturn &AwsProvider{}, nil\n\t}\n\n\treturn nil, errors.New(fmt.Sprintf(\"Provider '%s' doesn't exist\", name))\n}",
"func newNetwork(config neuralNetConfig) *neuralNet {\n\treturn &neuralNet{config: config}\n}",
"func New(provider string, p *ProviderData) Provider {\n\tswitch provider {\n\tcase \"myusa\":\n\t\treturn NewMyUsaProvider(p)\n\tcase \"linkedin\":\n\t\treturn NewLinkedInProvider(p)\n\tcase \"facebook\":\n\t\treturn NewFacebookProvider(p)\n\tcase \"github\":\n\t\treturn NewGitHubProvider(p)\n\tcase \"azure\":\n\t\treturn NewAzureProvider(p)\n\tcase \"gitlab\":\n\t\treturn NewGitLabProvider(p)\n\tdefault:\n\t\treturn NewGoogleProvider(p)\n\t}\n}",
"func New(fabricProvider api.FabricProvider) (*ChannelProvider, error) {\n\tcp := ChannelProvider{fabricProvider: fabricProvider}\n\treturn &cp, nil\n}",
"func NewProvider(region string, profile string) (*clusterProvider, error) {\n\tsession, err := session.NewAwsSession(profile, region)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error obtaining a valid AWS session\")\n\t}\n\n\tservices := providerServices{}\n\n\tec2Options, err := ec2.NewEC2APIHandler(session)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error initializing the EC2 API\")\n\t}\n\tservices.ec2 = ec2Options\n\n\teksOptions, err := eks.NewEKSAPIHandler(session)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error initializing the EKS API\")\n\t}\n\tservices.eks = eksOptions\n\n\tservices.eksctl = eksctl.NewEksctlClient()\n\n\tservices.cli = awscli.NewAWSCli()\n\n\tprovider := &clusterProvider{\n\t\tproviderServices: services,\n\t\tRegion: region,\n\t\tProfile: profile,\n\t}\n\treturn provider, nil\n}",
"func NewNetwork(svc iaas.Service) (resources.Network, fail.Error) {\n\tif svc == nil {\n\t\treturn NullValue(), fail.InvalidParameterCannotBeNilError(\"svc\")\n\t}\n\n\tcoreInstance, xerr := NewCore(svc, networkKind, networksFolderName, &abstract.Network{})\n\txerr = debug.InjectPlannedFail(xerr)\n\tif xerr != nil {\n\t\treturn NullValue(), xerr\n\t}\n\n\tinstance := &Network{\n\t\tMetadataCore: coreInstance,\n\t}\n\treturn instance, nil\n}",
"func NewNetwork(in, out, all []*NNode, netId int) *Network {\n\tn := Network{\n\t\tId: netId,\n\t\tinputs: in,\n\t\tOutputs: out,\n\t\tallNodes: all,\n\t\tnumLinks: -1,\n\t\tallNodesMIMO: all,\n\t}\n\treturn &n\n}",
"func New(chainID, remote string) (provider.Provider, error) {\n\thttpClient, err := rpcclient.NewHTTP(remote, \"/websocket\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewWithClient(chainID, httpClient), nil\n}",
"func NewNetworkWatcherProvider() *networkWatcherProvider {\n\treturn &networkWatcherProvider{\n\t\tinitialized: false,\n\t}\n}",
"func NewNetworkClient(settings Settings) Network {\n\tn := Network{}\n\tn.connect(settings.Address)\n\treturn n\n}",
"func NewProvider(paymentAddress address.Address, node retrievalmarket.RetrievalProviderNode, network rmnet.RetrievalMarketNetwork) retrievalmarket.RetrievalProvider {\n\treturn &provider{\n\t\tnode: node,\n\t\tnetwork: network,\n\t\tpaymentAddress: paymentAddress,\n\t\tpricePerByte: tokenamount.FromInt(2), // TODO: allow setting\n\t}\n}",
"func NewProvider(log *zap.Logger, url, clusterID, clientID string) mq.Provider {\n\tif len(clusterID) == 0 || len(clientID) == 0 {\n\t\treturn nil\n\t}\n\n\tcfg := newConfig(url, clusterID, clientID)\n\n\tif log == nil {\n\t\tlog = zap.NewNop()\n\t}\n\n\treturn &provider{\n\t\tconfig: cfg,\n\t\tconsumer: newConsumer(log, url, clusterID, clientID),\n\t\tlog: log,\n\t}\n}",
"func newNetSocket(ip net.IP, port int) (*netSocket, error) {\n\t// ForkLock docs state that socket syscall requires the lock.\n\tsyscall.ForkLock.Lock()\n\t// AF_INET = Address Family for IPv4\n\t// SOCK_STREAM = virtual circuit service\n\t// 0: the protocol for SOCK_STREAM, there's only 1.\n\tfd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0)\n\tif err != nil {\n\t\treturn nil, os.NewSyscallError(\"socket\", err)\n\t}\n\tsyscall.ForkLock.Unlock()\n\n\t// Allow reuse of recently-used addresses.\n\tif err = syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {\n\t\tsyscall.Close(fd)\n\t\treturn nil, os.NewSyscallError(\"setsockopt\", err)\n\t}\n\n\tsa := &syscall.SockaddrInet4{Port: port}\n\tcopy(sa.Addr[:], ip)\n\n\t// Bind the socket to a port\n\tif err = syscall.Bind(fd, sa); err != nil {\n\t\treturn nil, os.NewSyscallError(\"bind\", err)\n\t}\n\n\t// Listen for incoming connections.\n\tif err = syscall.Listen(fd, syscall.SOMAXCONN); err != nil {\n\t\treturn nil, os.NewSyscallError(\"listen\", err)\n\t}\n\n\treturn &netSocket{fd: fd}, nil\n}",
"func NewNetwork(c *Config) *Network {\n\tn := c.Inputs\n\tr := c.ConnectionRatio\n\tw := c.SharedWeight\n\tif n <= 0 {\n\t\treturn nil\n\t}\n\t// Pre-allocate room for n neurons and set the shared weight to the configured value.\n\toutputNode := NewRandomNeuron()\n\tallNodes := make([]Neuron, 0, n+1)\n\tallNodes = append(allNodes, outputNode)\n\tnet := &Network{allNodes, make([]*Neuron, n), &outputNode, w, 100}\n\n\t// Initialize n input nodes that all are inputs to the one output node.\n\tfor i := 0; i < n; i++ {\n\t\tinputNode := NewRandomNeuron()\n\t\tallNodes = append(allNodes, inputNode)\n\t\tnet.InputNodes[i] = &inputNode\n\t\t// Make connections for all nodes where a random number between 0 and 1 are larger than r\n\t\tif rand.Float64() > r {\n\t\t\tif err := net.OutputNode.AddInput(net.InputNodes[i]); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}\n\n\tnet.AllNodes = allNodes\n\treturn net\n}",
"func NewProvider(ptype int, config config.ProviderConfig) DataProvider {\n\tswitch ptype {\n\tcase FtpProv:\n\t\treturn NewFtpProvider(config.FtpConfig)\n\tcase FsProv:\n\t\treturn NewFileProvider()\n\tdefault:\n\t\tlog.Fatalf(\"No such provider: %d (%s)\", ptype, ProvTypeString(ptype))\n\t\treturn nil\n\t}\n}",
"func New(t *testing.T, configs ...Config) *Network {\n\tt.Helper()\n\tif len(configs) > 1 {\n\t\tpanic(\"at most one config should be provided\")\n\t}\n\tvar cfg Config\n\tif len(configs) == 0 {\n\t\tcfg = DefaultConfig()\n\t} else {\n\t\tcfg = configs[0]\n\t}\n\tnet := newNetwork(t, cfg)\n\tt.Cleanup(net.Cleanup)\n\n\treturn net\n}",
"func New(configVarResolver *providerconfig.ConfigVarResolver) cloudprovidertypes.Provider {\n\treturn &provider{\n\t\tconfigVarResolver: configVarResolver,\n\t\tclientGetter: getClient,\n\t\tportReadinessWaiter: waitForPort,\n\t}\n}",
"func NewProvider() *Provider {\n\treturn &Provider{}\n}",
"func newPeer(conn net.Conn, peerNodeInfo *types.NodeInfo, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{})) *Peer {\n\tvar p *Peer\n\tonReceive := func(chID byte, msgBytes []byte) {\n\t\treactor := reactorsByCh[chID]\n\t\tif reactor == nil {\n\t\t\tPanicSanity(Fmt(\"Unknown channel %X\", chID))\n\t\t}\n\t\treactor.Receive(chID, p, msgBytes)\n\t}\n\tonError := func(r interface{}) {\n\t\tp.Stop()\n\t\tonPeerError(p, r)\n\t}\n\tmconn := NewMConnection(conn, chDescs, onReceive, onError)\n\tp = &Peer{\n\t\toutbound: outbound,\n\t\tmconn: mconn,\n\t\tNodeInfo: peerNodeInfo,\n\t\tKey: peerNodeInfo.PubKey.KeyString(),\n\t\tData: NewCMap(),\n\t}\n\tp.BaseService = *NewBaseService(log, \"Peer\", p)\n\treturn p\n}",
"func NewAdapter(g *gce.Cloud) NetworkEndpointGroupCloud {\n\treturn &cloudProviderAdapter{\n\t\tc: g,\n\t\tnetworkURL: g.NetworkURL(),\n\t\tsubnetworkURL: g.SubnetworkURL(),\n\t}\n}",
"func NewNetwork(dockerClient *client.Client, cfg NetworkConfig) (out *Network, err error) {\n\tscopes.Framework.Infof(\"Creating Docker network %s\", cfg.Name)\n\tresp, err := dockerClient.NetworkCreate(context.Background(), cfg.Name, types.NetworkCreate{\n\t\tCheckDuplicate: true,\n\t\tLabels: cfg.Labels,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tscopes.Framework.Infof(\"Docker network %s created (ID=%s)\", cfg.Name, resp.ID)\n\n\tn := &Network{\n\t\tNetworkConfig: cfg,\n\t\tdockerClient: dockerClient,\n\t\tid: resp.ID,\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t_ = n.Close()\n\t\t}\n\t}()\n\n\t// Retrieve the subnet for the network.\n\tiresp, err := dockerClient.NetworkInspect(context.Background(), resp.ID, types.NetworkInspectOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif _, n.Subnet, err = net.ParseCIDR(iresp.IPAM.Config[0].Subnet); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn n, nil\n}",
"func NewNet() Net {\n\treturn Net{items: make(map[string]Page)}\n}",
"func NewProvider(config *ProviderConfig) (*Provider, error) {\n\tif err := validateConfig(config); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create logger\n\tif config.LogOutput == nil {\n\t\tconfig.LogOutput = os.Stderr\n\t}\n\tlogger := log.New(config.LogOutput, \"\", log.LstdFlags)\n\n\tp := &Provider{\n\t\tconfig: config,\n\t\tlogger: logger,\n\t\tshutdownCh: make(chan struct{}),\n\t}\n\tgo p.run()\n\treturn p, nil\n}",
"func New(clientset *clusterinfo.OpenShift, infraStatus *config.InfrastructureStatus) *Provider {\n\treturn &Provider{\n\t\toc: clientset,\n\t\tInfrastructureStatus: infraStatus,\n\t}\n}",
"func NewProvider(net network.StorageMarketNetwork,\n\tds datastore.Batching,\n\tfs filestore.FileStore,\n\tdagStore stores.DAGStoreWrapper,\n\tindexer provider.Interface,\n\tpieceStore piecestore.PieceStore,\n\tdataTransfer datatransfer.Manager,\n\tspn storagemarket.StorageProviderNode,\n\tminerAddress address.Address,\n\tstoredAsk StoredAsk,\n\tmeshCreator MeshCreator,\n\toptions ...StorageProviderOption,\n) (storagemarket.StorageProvider, error) {\n\th := &Provider{\n\t\tnet: net,\n\t\tmeshCreator: meshCreator,\n\t\tspn: spn,\n\t\tfs: fs,\n\t\tpieceStore: pieceStore,\n\t\tconns: connmanager.NewConnManager(),\n\t\tstoredAsk: storedAsk,\n\t\tactor: minerAddress,\n\t\tdataTransfer: dataTransfer,\n\t\tpubSub: pubsub.New(providerDispatcher),\n\t\treadyMgr: shared.NewReadyManager(),\n\t\tdagStore: dagStore,\n\t\tstores: stores.NewReadWriteBlockstores(),\n\t\tawaitTransferRestartTimeout: defaultAwaitRestartTimeout,\n\t\tindexProvider: indexer,\n\t\tmetadataForDeal: defaultMetadataFunc,\n\t}\n\tstorageMigrations, err := migrations.ProviderMigrations.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\th.deals, h.migrateDeals, err = newProviderStateMachine(\n\t\tds,\n\t\t&providerDealEnvironment{h},\n\t\th.dispatch,\n\t\tstorageMigrations,\n\t\tversioning.VersionKey(\"2\"),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\th.Configure(options...)\n\n\t// register a data transfer event handler -- this will send events to the state machines based on DT events\n\th.unsubDataTransfer = dataTransfer.SubscribeToEvents(dtutils.ProviderDataTransferSubscriber(h.deals))\n\n\tpph := &providerPushDeals{h}\n\terr = dataTransfer.RegisterVoucherType(requestvalidation.StorageDataTransferVoucherType, requestvalidation.NewUnifiedRequestValidator(pph, nil))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = dataTransfer.RegisterTransportConfigurer(requestvalidation.StorageDataTransferVoucherType, dtutils.TransportConfigurer(&providerStoreGetter{h}))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn h, nil\n}",
"func newNetwork(t *testing.T, cfg Config) *Network {\n\tt.Helper()\n\t// only one caller/test can create and use a network at a time\n\tt.Log(\"acquiring test network lock\")\n\tlock.Lock()\n\n\tbaseDir, err := ioutil.TempDir(t.TempDir(), cfg.ChainID)\n\trequire.NoError(t, err)\n\tt.Logf(\"created temporary directory: %s\", baseDir)\n\n\tnetwork := &Network{\n\t\tT: t,\n\t\tBaseDir: baseDir,\n\t\tValidators: make([]*Validator, cfg.NumValidators),\n\t\tConfig: cfg,\n\t}\n\n\tt.Log(\"preparing test network...\")\n\n\tmonikers := make([]string, cfg.NumValidators)\n\tnodeIDs := make([]string, cfg.NumValidators)\n\tvalPubKeys := make([]cryptotypes.PubKey, cfg.NumValidators)\n\n\tvar (\n\t\tgenAccounts []dclauthtypes.Account\n\t\tgenFiles []string\n\t)\n\n\tbuf := bufio.NewReader(os.Stdin)\n\n\t// generate private keys, node IDs, and initial transactions\n\tfor i := 0; i < cfg.NumValidators; i++ {\n\t\tappCfg := srvconfig.DefaultConfig()\n\t\tappCfg.Pruning = cfg.PruningStrategy\n\t\tappCfg.MinGasPrices = cfg.MinGasPrices\n\t\tappCfg.API.Enable = true\n\t\tappCfg.API.Swagger = false\n\t\tappCfg.Telemetry.Enabled = false\n\n\t\tctx := server.NewDefaultContext()\n\t\ttmCfg := ctx.Config\n\t\ttmCfg.Consensus.TimeoutCommit = cfg.TimeoutCommit\n\n\t\t// Only allow the first validator to expose an RPC, API and gRPC\n\t\t// server/client due to Tendermint in-process constraints.\n\t\tapiAddr := \"\"\n\t\ttmCfg.RPC.ListenAddress = \"\"\n\t\tappCfg.GRPC.Enable = false\n\t\tappCfg.GRPCWeb.Enable = false\n\t\tif i == 0 {\n\t\t\tapiListenAddr, _, err := server.FreeTCPAddr()\n\t\t\trequire.NoError(t, err)\n\t\t\tappCfg.API.Address = apiListenAddr\n\n\t\t\tapiURL, err := url.Parse(apiListenAddr)\n\t\t\trequire.NoError(t, err)\n\t\t\tapiAddr = \"http://\" + net.JoinHostPort(apiURL.Hostname(), apiURL.Port())\n\n\t\t\trpcAddr, _, err := server.FreeTCPAddr()\n\t\t\trequire.NoError(t, err)\n\t\t\ttmCfg.RPC.ListenAddress = rpcAddr\n\n\t\t\t_, grpcPort, err := server.FreeTCPAddr()\n\t\t\trequire.NoError(t, err)\n\t\t\tappCfg.GRPC.Address = fmt.Sprintf(\"0.0.0.0:%s\", grpcPort)\n\t\t\tappCfg.GRPC.Enable = true\n\n\t\t\t_, grpcWebPort, err := server.FreeTCPAddr()\n\t\t\trequire.NoError(t, err)\n\t\t\tappCfg.GRPCWeb.Address = fmt.Sprintf(\"0.0.0.0:%s\", grpcWebPort)\n\t\t\tappCfg.GRPCWeb.Enable = true\n\t\t}\n\n\t\tlogger := log.NewNopLogger()\n\t\tif cfg.EnableLogging {\n\t\t\tlogger = log.NewTMLogger(log.NewSyncWriter(os.Stdout))\n\t\t\tlogger, _ = tmflags.ParseLogLevel(\"info\", logger, tmcfg.DefaultLogLevel)\n\t\t}\n\n\t\tctx.Logger = logger\n\n\t\tnodeDirName := fmt.Sprintf(\"node%d\", i)\n\t\tnodeDir := filepath.Join(network.BaseDir, nodeDirName, \"simd\")\n\t\tclientDir := filepath.Join(network.BaseDir, nodeDirName, \"simcli\")\n\t\tgentxsDir := filepath.Join(network.BaseDir, \"gentxs\")\n\n\t\trequire.NoError(t, os.MkdirAll(filepath.Join(nodeDir, \"config\"), 0o755))\n\t\trequire.NoError(t, os.MkdirAll(clientDir, 0o755))\n\n\t\ttmCfg.SetRoot(nodeDir)\n\t\ttmCfg.Moniker = nodeDirName\n\t\tmonikers[i] = nodeDirName\n\n\t\tproxyAddr, _, err := server.FreeTCPAddr()\n\t\trequire.NoError(t, err)\n\t\ttmCfg.ProxyApp = proxyAddr\n\n\t\tp2pAddr, _, err := server.FreeTCPAddr()\n\t\trequire.NoError(t, err)\n\t\ttmCfg.P2P.ListenAddress = p2pAddr\n\t\ttmCfg.P2P.AddrBookStrict = false\n\t\ttmCfg.P2P.AllowDuplicateIP = true\n\n\t\tnodeID, pubKey, err := dclgenutil.InitializeNodeValidatorFiles(tmCfg)\n\t\trequire.NoError(t, err)\n\t\tnodeIDs[i] = nodeID\n\t\tvalPubKeys[i] = pubKey\n\n\t\tkb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, clientDir, buf, cfg.KeyringOptions...)\n\t\trequire.NoError(t, err)\n\n\t\tkeyringAlgos, _ := kb.SupportedAlgorithms()\n\t\talgo, err := keyring.NewSigningAlgoFromString(cfg.SigningAlgo, keyringAlgos)\n\t\trequire.NoError(t, err)\n\n\t\taddr, secret, err := server.GenerateSaveCoinKey(kb, nodeDirName, true, algo)\n\t\trequire.NoError(t, err)\n\n\t\tinfo := map[string]string{\"secret\": secret}\n\t\tinfoBz, err := json.Marshal(info)\n\t\trequire.NoError(t, err)\n\n\t\t// save private key seed words\n\t\trequire.NoError(t, writeFile(fmt.Sprintf(\"%v.json\", \"key_seed\"), clientDir, infoBz))\n\n\t\tgenFiles = append(genFiles, tmCfg.GenesisFile())\n\n\t\tbaseAccount := authtypes.NewBaseAccount(addr, nil, 0, 0)\n\t\taccount := dclauthtypes.NewAccount(\n\t\t\tbaseAccount,\n\t\t\t[]dclauthtypes.AccountRole{\n\t\t\t\tdclauthtypes.Vendor,\n\t\t\t\tdclauthtypes.CertificationCenter,\n\t\t\t\tdclauthtypes.Trustee,\n\t\t\t\tdclauthtypes.NodeAdmin,\n\t\t\t},\n\t\t\tnil,\n\t\t\tnil,\n\t\t\ttestconstants.Vid,\n\t\t)\n\t\tgenAccounts = append(genAccounts, *account)\n\n\t\trequire.NoError(t, err)\n\n\t\tdescription := validatortypes.NewDescription(nodeDirName, \"\", \"\", \"\")\n\n\t\tcreateValMsg, err := validatortypes.NewMsgCreateValidator(\n\t\t\tsdk.ValAddress(addr),\n\t\t\tvalPubKeys[i],\n\t\t\t&description,\n\t\t)\n\t\trequire.NoError(t, err)\n\n\t\tp2pURL, err := url.Parse(p2pAddr)\n\t\trequire.NoError(t, err)\n\n\t\tmemo := fmt.Sprintf(\"%s@%s:%s\", nodeIDs[i], p2pURL.Hostname(), p2pURL.Port())\n\t\tfee := sdk.NewCoins(sdk.NewCoin(fmt.Sprintf(\"%stoken\", nodeDirName), sdk.NewInt(0)))\n\t\ttxBuilder := cfg.TxConfig.NewTxBuilder()\n\t\trequire.NoError(t, txBuilder.SetMsgs(createValMsg))\n\t\ttxBuilder.SetFeeAmount(fee) // Arbitrary fee\n\t\ttxBuilder.SetGasLimit(1000000) // Need at least 100386\n\t\ttxBuilder.SetMemo(memo)\n\n\t\ttxFactory := tx.Factory{}\n\t\ttxFactory = txFactory.\n\t\t\tWithChainID(cfg.ChainID).\n\t\t\tWithMemo(memo).\n\t\t\tWithKeybase(kb).\n\t\t\tWithTxConfig(cfg.TxConfig)\n\n\t\terr = tx.Sign(txFactory, nodeDirName, txBuilder, true)\n\t\trequire.NoError(t, err)\n\n\t\ttxBz, err := cfg.TxConfig.TxJSONEncoder()(txBuilder.GetTx())\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, writeFile(fmt.Sprintf(\"%v.json\", nodeDirName), gentxsDir, txBz))\n\n\t\tsrvconfig.WriteConfigFile(filepath.Join(nodeDir, \"config/app.toml\"), appCfg)\n\n\t\tclientCtx := client.Context{}.\n\t\t\tWithKeyringDir(clientDir).\n\t\t\tWithKeyring(kb).\n\t\t\tWithHomeDir(tmCfg.RootDir).\n\t\t\tWithChainID(cfg.ChainID).\n\t\t\tWithInterfaceRegistry(cfg.InterfaceRegistry).\n\t\t\tWithCodec(cfg.Codec).\n\t\t\tWithLegacyAmino(cfg.LegacyAmino).\n\t\t\tWithTxConfig(cfg.TxConfig).\n\t\t\tWithAccountRetriever(cfg.AccountRetriever)\n\n\t\tnetwork.Validators[i] = &Validator{\n\t\t\tAppConfig: appCfg,\n\t\t\tClientCtx: clientCtx,\n\t\t\tCtx: ctx,\n\t\t\tDir: filepath.Join(network.BaseDir, nodeDirName),\n\t\t\tNodeID: nodeID,\n\t\t\tPubKey: pubKey,\n\t\t\tMoniker: nodeDirName,\n\t\t\tRPCAddress: tmCfg.RPC.ListenAddress,\n\t\t\tP2PAddress: tmCfg.P2P.ListenAddress,\n\t\t\tAPIAddress: apiAddr,\n\t\t\tAddress: addr,\n\t\t\tValAddress: sdk.ValAddress(addr),\n\t\t}\n\t}\n\n\trequire.NoError(t, initGenFiles(cfg, genAccounts, genFiles))\n\trequire.NoError(t, collectGenFiles(cfg, network.Validators, network.BaseDir))\n\n\tt.Log(\"starting test network...\")\n\tfor _, v := range network.Validators {\n\t\trequire.NoError(t, startInProcess(cfg, v))\n\t}\n\n\tt.Log(\"started test network\")\n\n\t// Ensure we cleanup incase any test was abruptly halted (e.g. SIGINT) as any\n\t// defer in a test would not be called.\n\tserver.TrapSignal(network.Cleanup)\n\n\treturn network\n}",
"func NewProvider(conf *Conf) (*Provider, error) {\n\tdb, err := openDBAndCheckFormat(conf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Provider{\n\t\tdb: db,\n\t\tdbHandles: make(map[string]*DBHandle),\n\t}, nil\n}",
"func NewProvider() (rootfs.Provider, error) {\n\treturn &provider{}, nil\n}",
"func NewProvider() *extblockpublisher.Provider {\n\treturn extblockpublisher.NewProvider()\n}",
"func IpNetwork_NewServer(s IpNetwork_Server, policy *server.Policy) *server.Server {\n\tc, _ := s.(server.Shutdowner)\n\treturn server.New(IpNetwork_Methods(nil, s), s, c, policy)\n}",
"func New() provider.Provider {\n\tp := newProvider()\n\n\treturn p\n}",
"func NewProvider() *Provider {\n\treturn &Provider{\n\t\tconfig: new(Config),\n\t\tmemoryDB: new(session.Dict),\n\t\texpiration: 0,\n\n\t\tstorePool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn new(Store)\n\t\t\t},\n\t\t},\n\t}\n}",
"func NewProvider(cfg Config) *Provider {\n\treturn &Provider{\n\t\tConfig: cfg,\n\t}\n}",
"func newNetworkDef() libvirtxml.Network {\n\tconst defNetworkXML = `\n\t\t<network>\n\t\t <name>default</name>\n\t\t <forward mode='nat'>\n\t\t <nat>\n\t\t <port start='1024' end='65535'/>\n\t\t </nat>\n\t\t </forward>\n\t\t</network>`\n\tif d, err := newDefNetworkFromXML(defNetworkXML); err != nil {\n\t\tpanic(fmt.Sprintf(\"Unexpected error while parsing default network definition: %s\", err))\n\t} else {\n\t\treturn d\n\t}\n}",
"func newNetClient() *http.Client {\n\tonce.Do(func() {\n\t\tvar netTransport = &http.Transport{\n\t\t\tDial: (&net.Dialer{\n\t\t\t\tTimeout: 15 * time.Second,\n\t\t\t}).Dial,\n\t\t\tTLSHandshakeTimeout: 8 * time.Second,\n\t\t\tExpectContinueTimeout: 8 * time.Second,\n\t\t\tResponseHeaderTimeout: 8 * time.Second,\n\t\t\tReadBufferSize: 8,\n\t\t}\n\t\tnetClient = &http.Client{\n\t\t\tTimeout: time.Second * 15,\n\t\t\tTransport: netTransport,\n\t\t}\n\t})\n\n\treturn netClient\n}",
"func NewNetworkManager(nsxtSpec *NSXTSpec,\n\tvcspec *VcenterSpec, vcclient *vcenter.Client,\n\tnsxNetworkProvisioner np.NsxNetworkProvisioner,\n\tloglevel LogLevel, optionalSpecs ...interface{}) (*networkManager, error) {\n\n\tlog := logrus.New()\n\tlog.Formatter = utcFormatter{logrus.TextFormatter{FullTimestamp: true}}\n\tlevel, err := logrus.ParseLevel(string(loglevel))\n\tif err != nil {\n\t\tdefaultLogLevel := logrus.InfoLevel\n\t\tlog.Warnf(\"Invalid log level %s, will fall back to %s\\n\", loglevel, defaultLogLevel.String())\n\t\tlog.SetLevel(defaultLogLevel)\n\t} else {\n\t\tlog.SetLevel(level)\n\t}\n\tlogEntry := log.WithField(\"pks-networking\", \"networkManager\")\n\tnsxNetworkProvisioner.SetLogger(logEntry)\n\tnm := &networkManager{\n\t\tnp: nsxNetworkProvisioner,\n\t\tvcp: vcp.NewVcenterProvisioner(vcclient, logEntry),\n\t\tnsxtSpec: nsxtSpec,\n\t\tt1RouterSpec: &T1RouterSpec{},\n\t\tlogicalSwitchSpec: &LogicalSwitchSpec{},\n\t\tipamSpec: &IPAMSpec{},\n\t\tvcSpec: vcspec,\n\t\tlog: logEntry,\n\t}\n\n\terr = populateNsxParams(nm)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, optionalSpec := range optionalSpecs {\n\t\tswitch t := optionalSpec.(type) {\n\t\tcase *T1RouterSpec:\n\t\t\tnm.t1RouterSpec = t\n\t\tcase *LogicalSwitchSpec:\n\t\t\tnm.logicalSwitchSpec = t\n\t\tcase *IPAMSpec:\n\t\t\tnm.ipamSpec = t\n\t\t}\n\t}\n\n\treturn nm, nil\n}",
"func newPeer(server *server, name string, connectionString string, heartbeatInterval time.Duration) *Peer {\n\treturn &Peer{\n\t\tserver: server,\n\t\tName: name,\n\t\tConnectionString: connectionString,\n\t\theartbeatInterval: heartbeatInterval,\n\t}\n}",
"func NewProvider(conf *pvtdatastorage.PrivateDataConfig, ledgerconfig *ledger.Config) (xstorageapi.PrivateDataProvider, error) {\n\tif config.GetPrivateDataStoreDBType() == config.CouchDBType {\n\t\tlogger.Info(\"Using CouchDB private data storage provider\")\n\n\t\treturn xpvtdatastorage.NewProvider(conf, ledgerconfig)\n\t}\n\n\tlogger.Info(\"Using default private data storage provider\")\n\n\treturn pvtdatastorage.NewProvider(conf)\n}",
"func NewNetDialer(connectTimeout, keepAlive time.Duration) *stdnet.Dialer {\n\treturn &net.Dialer{\n\t\tTimeout: connectTimeout,\n\t\tKeepAlive: keepAlive,\n\t}\n}",
"func New(homeDir string, c *config.ClusterConfig) (*ClusterProvider, error) {\n\n\tif c == nil {\n\t\treturn nil, errors.New(\"the config object needs to be initialized, got nil\")\n\t}\n\n\tvar spec InfrastructureSpec\n\n\tworkingDir, err := providers.CreateProviderDir(homeDir, c.ClusterName, c.Infrastructure.Provider.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = viper.UnmarshalKey(\"infrastructure.provider.spec\", &spec)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not unmarshal infrastructure provider spec to provider.InfrastructureSpec\")\n\t}\n\n\treturn &ClusterProvider{\n\t\tName: c.Infrastructure.Provider.Name,\n\t\tClusterName: c.ClusterName,\n\t\tWorkingDir: workingDir,\n\t\tSpec: &spec,\n\t}, nil\n}",
"func New(node *gossipnet.Node, eventsIn, eventsOut chan core.Event, eventsCustom chan core.CustomEvent, nodesToConnect int) Manager {\n\treturn Manager{\n\t\tnode: node,\n\t\teventsIn: eventsIn,\n\t\teventsOut: eventsOut,\n\t\teventsCustom: eventsCustom,\n\t\tnodesToConnect: nodesToConnect,\n\t}\n}",
"func NewProtocol() stack.NetworkProtocol {\r\n\treturn &protocol{}\r\n}",
"func New() NetworkClient {\n\treturn *new(NetworkClient)\n}",
"func NewNetwork(x int, n float64, a float64, act int, b float64, h int, r int, o int) Network{\n\tnet := Network{Lrate: n, Mom: a, Bias: b, Activation: act, Inputs: x, Outputs: o, Hidden: h}\n\tfor i := 0; i < r; i++ {\n\t\tif i == 0 {\n\t\t\tl := L.NewHidden(x, n, a, act, b, h)\n\t\t\tnet.HiddenLayers = append(net.HiddenLayers, l)\t\t\t\n\t\t} else {\n\t\t\tl := L.NewHidden(h, n, a, act, b, h)\t\n\t\t\tnet.HiddenLayers = append(net.HiddenLayers, l)\t\t\t\n\t\t}\n\t}\n\tnet.OutputLayer = L.NewOutput(h, n, a, act, b, o)\n\n\treturn net\n}",
"func newDNSOverTCPOrTLSTransport(\n\tdial DialContextFunc, network, address string, padding bool) *DNSOverTCPTransport {\n\treturn &DNSOverTCPTransport{\n\t\tdial: dial,\n\t\tdecoder: &DNSDecoderMiekg{},\n\t\taddress: address,\n\t\tnetwork: network,\n\t\trequiresPadding: padding,\n\t}\n}",
"func newNodes(c *Client) *nodes {\n\treturn &nodes{c}\n}",
"func NewProvider() *ProviderConfig {\n\tproviderConfig := &ProviderConfig{\n\t\tAlibaba: make(map[string]*models.AlibabaCloudSpec),\n\t\tAnexia: make(map[string]*models.AnexiaCloudSpec),\n\t\tAws: make(map[string]*models.AWSCloudSpec),\n\t\tAzure: make(map[string]*models.AzureCloudSpec),\n\t\tDigitalocean: make(map[string]*models.DigitaloceanCloudSpec),\n\t\tFake: make(map[string]*models.FakeCloudSpec),\n\t\tGcp: make(map[string]*models.GCPCloudSpec),\n\t\tHetzner: make(map[string]*models.HetznerCloudSpec),\n\t\tKubevirt: make(map[string]*models.KubevirtCloudSpec),\n\t\tOpenstack: make(map[string]*models.OpenstackCloudSpec),\n\t\tPacket: make(map[string]*models.PacketCloudSpec),\n\t\tVsphere: make(map[string]*models.VSphereCloudSpec),\n\t}\n\n\tproviderConfig.Alibaba[\"Alibaba\"] = newAlibabaCloudSpec()\n\tproviderConfig.Anexia[\"Anexia\"] = newAnexiaCloudSpec()\n\tproviderConfig.Aws[\"Aws\"] = newAWSCloudSpec()\n\tproviderConfig.Azure[\"Azure\"] = newAzureCloudSpec()\n\tproviderConfig.Digitalocean[\"Digitalocean\"] = newDigitaloceanCloudSpec()\n\tproviderConfig.Fake[\"Fake\"] = newFakeCloudSpec()\n\tproviderConfig.Gcp[\"Gcp\"] = newGCPCloudSpec()\n\tproviderConfig.Hetzner[\"Hetzner\"] = newHetznerCloudSpec()\n\tproviderConfig.Kubevirt[\"Kubevirt\"] = newKubevirtCloudSpec()\n\tproviderConfig.Openstack[\"Openstack\"] = newOpenstackCloudSpec()\n\tproviderConfig.Packet[\"Packet\"] = newPacketCloudSpec()\n\tproviderConfig.Vsphere[\"Vsphere\"] = newVSphereCloudSpec()\n\n\treturn providerConfig\n}",
"func NewNetworkClient(sess *ibmpisession.IBMPISession, instanceID string) *PowerVSNetwork {\n\tc := &PowerVSNetwork{\n\t\tserviceInstanceID: instanceID,\n\t}\n\tc.networkClient = instance.NewIBMPINetworkClient(context.Background(), sess, instanceID)\n\treturn c\n}",
"func NewNodesProviderFactory(cfg config.Config, configurationFilePath string) (*nodesProviderFactory, error) {\n\treturn &nodesProviderFactory{\n\t\tcfg: cfg,\n\t\tconfigurationFilePath: configurationFilePath,\n\t}, nil\n}",
"func newProvisioner(baseCtx context.Context, cl *restClient, callTimeout time.Duration) mode.Provisioner {\n\treturn provisioner{cl: cl, baseCtx: baseCtx, callTimeout: callTimeout}\n}",
"func New() *Provider {\n\treturn &Provider{clients: make(map[string]ClientVersionProvider)}\n}",
"func providerFactory(_ io.Reader) (cloudprovider.Interface, error) {\n\tlog := klogr.NewWithOptions(klogr.WithFormat(klogr.FormatKlog))\n\tc, err := loadConfig(envconfig.OsLookuper())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiUrl := katapult.DefaultURL\n\tif c.APIHost != \"\" {\n\t\tlog.Info(\"default API base URL overrided\",\n\t\t\t\"url\", c.APIHost)\n\t\tapiUrl, err = url.Parse(c.APIHost)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse provided api url: %w\", err)\n\t\t}\n\t}\n\n\trm, err := katapult.New(\n\t\tkatapult.WithAPIKey(c.APIKey),\n\t\tkatapult.WithBaseURL(apiUrl),\n\t\tkatapult.WithUserAgent(\"kce-ccm\"), // TODO: Add version.\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := core.New(rm)\n\n\treturn &provider{\n\t\tlog: log,\n\t\tkatapult: client,\n\t\tconfig: *c,\n\t\tloadBalancer: &loadBalancerManager{\n\t\t\tlog: log,\n\t\t\tconfig: *c,\n\t\t\tloadBalancerController: client.LoadBalancers,\n\t\t\tloadBalancerRuleController: client.LoadBalancerRules,\n\t\t},\n\t}, nil\n}",
"func newCommune(n int) *commune {\n\treturn &commune{ch: make(chan string, n)}\n}",
"func NewNetworkGrant(ctx *pulumi.Context,\n\tname string, args *NetworkGrantArgs, opts ...pulumi.ResourceOption) (*NetworkGrant, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.CcnId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'CcnId'\")\n\t}\n\tif args.CenId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'CenId'\")\n\t}\n\tif args.CenUid == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'CenUid'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource NetworkGrant\n\terr := ctx.RegisterResource(\"alicloud:cloudconnect/networkGrant:NetworkGrant\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func NewNetworkPacketCapture(ctx *pulumi.Context,\n\tname string, args *NetworkPacketCaptureArgs, opts ...pulumi.ResourceOption) (*NetworkPacketCapture, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.NetworkWatcherName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'NetworkWatcherName'\")\n\t}\n\tif args.ResourceGroupName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ResourceGroupName'\")\n\t}\n\tif args.StorageLocation == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'StorageLocation'\")\n\t}\n\tif args.TargetResourceId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'TargetResourceId'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource NetworkPacketCapture\n\terr := ctx.RegisterResource(\"azure:network/networkPacketCapture:NetworkPacketCapture\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func NewProvider(minerAddress address.Address,\n\tnode retrievalmarket.RetrievalProviderNode,\n\tsa retrievalmarket.SectorAccessor,\n\tnetwork rmnet.RetrievalMarketNetwork,\n\tpieceStore piecestore.PieceStore,\n\tdagStore stores.DAGStoreWrapper,\n\tdataTransfer datatransfer.Manager,\n\tds datastore.Batching,\n\tretrievalPricingFunc RetrievalPricingFunc,\n\topts ...RetrievalProviderOption,\n) (retrievalmarket.RetrievalProvider, error) {\n\n\tif retrievalPricingFunc == nil {\n\t\treturn nil, xerrors.New(\"retrievalPricingFunc is nil\")\n\t}\n\n\tp := &Provider{\n\t\tdataTransfer: dataTransfer,\n\t\tnode: node,\n\t\tsa: sa,\n\t\tnetwork: network,\n\t\tminerAddress: minerAddress,\n\t\tpieceStore: pieceStore,\n\t\tsubscribers: pubsub.New(providerDispatcher),\n\t\tsubQueryEvt: pubsub.New(queryEvtDispatcher),\n\t\treadyMgr: shared.NewReadyManager(),\n\t\tretrievalPricingFunc: retrievalPricingFunc,\n\t\tdagStore: dagStore,\n\t\tstores: stores.NewReadOnlyBlockstores(),\n\t}\n\n\taskStore, err := askstore.NewAskStore(namespace.Wrap(ds, datastore.NewKey(\"retrieval-ask\")), datastore.NewKey(\"latest\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.askStore = askStore\n\n\tretrievalMigrations, err := migrations.ProviderMigrations.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.stateMachines, p.migrateStateMachines, err = versionedfsm.NewVersionedFSM(ds, fsm.Parameters{\n\t\tEnvironment: &providerDealEnvironment{p},\n\t\tStateType: retrievalmarket.ProviderDealState{},\n\t\tStateKeyField: \"Status\",\n\t\tEvents: providerstates.ProviderEvents,\n\t\tStateEntryFuncs: providerstates.ProviderStateEntryFuncs,\n\t\tFinalityStates: providerstates.ProviderFinalityStates,\n\t\tNotifier: p.notifySubscribers,\n\t\tOptions: fsm.Options{\n\t\t\tConsumeAllEventsBeforeEntryFuncs: true,\n\t\t},\n\t}, retrievalMigrations, \"2\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.Configure(opts...)\n\tp.requestValidator = requestvalidation.NewProviderRequestValidator(&providerValidationEnvironment{p})\n\ttransportConfigurer := dtutils.TransportConfigurer(network.ID(), &providerStoreGetter{p})\n\n\terr = p.dataTransfer.RegisterVoucherType(retrievalmarket.DealProposalType, p.requestValidator)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = p.dataTransfer.RegisterVoucherType(retrievalmarket.DealPaymentType, p.requestValidator)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = p.dataTransfer.RegisterTransportConfigurer(retrievalmarket.DealProposalType, transportConfigurer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdataTransfer.SubscribeToEvents(dtutils.ProviderDataTransferSubscriber(p.stateMachines))\n\treturn p, nil\n}",
"func NewProvider(api *API, vin string, cache time.Duration) *Provider {\n\timpl := &Provider{\n\t\tchargerG: provider.Cached(func() (ChargerResponse, error) {\n\t\t\treturn api.Charger(vin)\n\t\t}, cache),\n\t\tstatusG: provider.Cached(func() (StatusResponse, error) {\n\t\t\treturn api.Status(vin)\n\t\t}, cache),\n\t\tclimateG: provider.Cached(func() (ClimaterResponse, error) {\n\t\t\treturn api.Climater(vin)\n\t\t}, cache),\n\t\tpositionG: provider.Cached(func() (PositionResponse, error) {\n\t\t\treturn api.Position(vin)\n\t\t}, cache),\n\t\taction: func(action, value string) error {\n\t\t\treturn api.Action(vin, action, value)\n\t\t},\n\t\trr: func() (RolesRights, error) {\n\t\t\treturn api.RolesRights(vin)\n\t\t},\n\t}\n\treturn impl\n}",
"func NewPortProvider(t testing.TB) *types.PortProvider {\n\treturn types.NewPortProvider(t)\n}",
"func NewServerNetwork(\n\tnet, laddr string,\n\thandler func(conn Conn, cmd Command),\n\taccept func(conn Conn) bool,\n\tclosed func(conn Conn, err error),\n) *Server {\n\tif handler == nil {\n\t\tpanic(\"handler is nil\")\n\t}\n\ts := newServer()\n\ts.net = net\n\ts.laddr = laddr\n\ts.handler = handler\n\ts.accept = accept\n\ts.closed = closed\n\treturn s\n}",
"func New(addrs string) (*Client, error) {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", addrs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\topts := &connectionOptions{remoteAddress: addr}\n\tconn, err := newConnection(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &Client{\n\t\tconn: conn,\n\t\tdebug: true,\n\t}\n\treturn client, nil\n}",
"func newMemoryTransport(network *MemoryNetwork, nodeID types.NodeID) *MemoryTransport {\n\tonce := &sync.Once{}\n\tcloseCh := make(chan struct{})\n\treturn &MemoryTransport{\n\t\tlogger: network.logger.With(\"local\", nodeID),\n\t\tnetwork: network,\n\t\tnodeID: nodeID,\n\t\tbufferSize: network.bufferSize,\n\t\tacceptCh: make(chan *MemoryConnection),\n\t\tcloseCh: closeCh,\n\t\tcloseFn: func() { once.Do(func() { close(closeCh) }) },\n\t}\n}",
"func NewNetGenerator(hosts, conns int, startIP string, distribution ConnectionsDistribution) *NetGenerator {\n\treturn &NetGenerator{\n\t\thosts: hosts,\n\t\tconnections: conns,\n\t\tstartIP: startIP,\n\t\tdistribution: distribution,\n\t}\n}",
"func NewProvider(expires time.Duration) *Provider {\n\treturn &Provider{list: list.New(), sessions: make(map[string]*list.Element, 0), databases: make([]Database, 0), Expires: expires}\n}",
"func New(device, addr string, port int) (*Transport, error) {\n return &Transport{\n device: device,\n addr: addr,\n port: port,\n sessions: make(map[string]*ssh.Session, 800),\n clients: make(map[string]*ssh.Client, 100),\n }, nil\n}",
"func NewNode(\n\tethereumChain eth.Handle,\n\tnetworkProvider net.Provider,\n\ttssConfig *tss.Config,\n) *Node {\n\treturn &Node{\n\t\tethereumChain: ethereumChain,\n\t\tnetworkProvider: networkProvider,\n\t\ttssConfig: tssConfig,\n\t}\n}",
"func New(addr string) (*Provider, error) {\n\tclient, err := statsd.New(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp := Provider{\n\t\tclient: client,\n\t\trate: 1,\n\t}\n\treturn &p, nil\n}",
"func New(c *Config) *Provider {\n\treturn &Provider{\n\t\tConfig: c,\n\t}\n}",
"func NewProvider(c Config) (checkpoint.Provider, func() error, error) {\n\tvar err error\n\tcachePath, mountPath := path.Join(defaultCCFSRoot, \"cache\"), path.Join(defaultCCFSRoot, \"mountpoint\")\n\tif c.CacheDirectory != \"\" {\n\t\tcachePath = c.CacheDirectory\n\t} else {\n\t\tc.CacheDirectory = cachePath\n\t}\n\tif c.Exec == \"\" {\n\t\tc.Exec = \"ccfs\"\n\t}\n\tif err = unix.Unmount(mountPath, unix.MNT_DETACH); err != nil && err != syscall.EINVAL && err != syscall.ENOENT {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to umount ccfs\")\n\t}\n\tif err = os.MkdirAll(cachePath, 0644); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif err = os.MkdirAll(mountPath, 0644); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tvar done func() error\n\tif done, err = mountCCFS(mountPath, c); err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to mount ccfs\")\n\t}\n\tp := &provider{\n\t\tmountpoint: mountPath,\n\t\trefs: map[string]int{},\n\t\tlastRefs: map[string]int{},\n\t\tconfig: c,\n\t}\n\tgo p.scan()\n\treturn p, done, nil\n}",
"func newClient(iface *net.Interface) (*client, error) {\n\t// TODO(reddaly): At least attempt to bind to the port required in the spec.\n\t// Create a IPv4 listener\n\tconn, err := NewConn(&Config{Zone: nil})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"[ERR] mdns: Failed to create client conn: %v\", err)\n\t}\n\n\tc := &client{\n\t\tconn: conn,\n\t\tclosedCh: make(chan struct{}),\n\t}\n\treturn c, nil\n}",
"func New(clientKey, secret, callbackURL string, scopes ...string) *Provider {\n\tp := &Provider{\n\t\tClientKey: clientKey,\n\t\tSecret: secret,\n\t\tCallbackURL: callbackURL,\n\t\tproviderName: \"wgtwo\",\n\t}\n\n\tp.config = newConfig(p, scopes)\n\treturn p\n}",
"func newPeer(host topology.Host, dialer client.PeerConnDialer) *peer {\n\treturn &peer{\n\t\thost: host,\n\t\tdialer: dialer,\n\t}\n}",
"func init() {\n\t// Providers backed by netstack.\n\tp := []provider{\n\t\t{\n\t\t\tfamily: linux.AF_INET,\n\t\t\tnetProto: ipv4.ProtocolNumber,\n\t\t},\n\t\t{\n\t\t\tfamily: linux.AF_INET6,\n\t\t\tnetProto: ipv6.ProtocolNumber,\n\t\t},\n\t\t{\n\t\t\tfamily: linux.AF_PACKET,\n\t\t},\n\t}\n\n\tfor i := range p {\n\t\tsocket.RegisterProvider(p[i].family, &p[i])\n\t}\n}"
] | [
"0.6622262",
"0.6615538",
"0.6613981",
"0.6489785",
"0.64802027",
"0.6450102",
"0.63853896",
"0.6382277",
"0.63313586",
"0.6251327",
"0.62496936",
"0.62088907",
"0.6165768",
"0.6136103",
"0.61203796",
"0.6116237",
"0.6043335",
"0.60329527",
"0.6020813",
"0.5976292",
"0.59749705",
"0.5929348",
"0.59270513",
"0.59155536",
"0.5898188",
"0.58810353",
"0.5866373",
"0.5865881",
"0.5861317",
"0.58401555",
"0.5823173",
"0.580975",
"0.5809726",
"0.58089596",
"0.5792264",
"0.5784794",
"0.57790184",
"0.5778983",
"0.5753778",
"0.5748105",
"0.57478195",
"0.57227725",
"0.5716987",
"0.56946635",
"0.56506056",
"0.5648722",
"0.56434226",
"0.56428176",
"0.5607893",
"0.5601518",
"0.5593273",
"0.55829144",
"0.55791986",
"0.5560388",
"0.55561817",
"0.55519336",
"0.55397624",
"0.5538467",
"0.55383205",
"0.55331755",
"0.5519693",
"0.55181545",
"0.55150807",
"0.54945755",
"0.54802644",
"0.5479653",
"0.5478376",
"0.5472733",
"0.5468186",
"0.5458778",
"0.5438837",
"0.5436705",
"0.5422596",
"0.54177713",
"0.541747",
"0.541632",
"0.5414724",
"0.5412531",
"0.54081357",
"0.5405551",
"0.5390748",
"0.53822416",
"0.53784025",
"0.5368758",
"0.5367117",
"0.5366754",
"0.5359435",
"0.53503036",
"0.53441846",
"0.5342918",
"0.53304636",
"0.53302526",
"0.5316656",
"0.53165334",
"0.5308075",
"0.52855",
"0.52662563",
"0.52641517",
"0.5263987",
"0.5255536"
] | 0.79331243 | 0 |
A handler suitable for events.NewEvent(). | func (n *NetImpl) eventHandler(handler interface{}, params ...interface{}) {
callback := handler.(func(_ *peering.RecvEvent))
recvEvent := params[0].(*peering.RecvEvent)
callback(recvEvent)
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func newEvent(name string, args ...interface{}) (*Event, error) {\n\tid, err := uuid.NewV4()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theader := &EventHeader{Id: id.String(), Version: ProtocolVersion}\n\n\te := Event{\n\t\tHeader: header,\n\t\tName: name,\n\t\tArgs: args,\n\t}\n\n\treturn &e, nil\n}",
"func hNewEvent(c echo.Context) error {\n\tvar e httpError\n\n\tif (len(c.FormValue(\"code\")) == 0) || (len(c.FormValue(\"title\")) == 0) {\n\t\treturn c.JSON(http.StatusNotAcceptable, \"input information is not valid\")\n\t}\n\tuserCODE := c.FormValue(\"code\")\n\n\t// read from token user id\n\tvar tokenUserID int64\n\ttokenUserID = 1\n\n\tu, errGet := blog.GetUserByCode(tokenUserID, userCODE)\n\tif errGet != nil {\n\t\te.TheError = \"user code \" + userCODE + \" not found.\"\n\t\treturn c.JSON(http.StatusNotFound, e)\n\t}\n\tvar ev Event\n\tev.OpenedByUserID = u.ID\n\tev.Contents = c.FormValue(\"content\")\n\tev.Title = c.FormValue(\"title\")\n\n\terrAdd := blog.AddEvent(&ev)\n\tif errAdd != nil {\n\t\te.TheError = errAdd.Error()\n\t\treturn c.JSON(http.StatusInternalServerError, e)\n\t}\n\tfname, errUpload := lowlevelUploadFile(c, u.ID, ev.ID)\n\tif errUpload != nil {\n\t\te.TheError = \"could not upload file: \" + errUpload.Error()\n\t\treturn c.JSON(http.StatusInternalServerError, e)\n\t}\n\te.TheError = \"OK\" + \" - \" + fname\n\treturn c.JSON(http.StatusOK, e)\n}",
"func NewEvent(\n\trkind,\n\trapiVersion,\n\trnamespace,\n\trname,\n\treason string,\n\tsource Source,\n\tmessage MsgKey,\n\targs ...interface{}) Info {\n\tmsgText, err := getEventMsg(message, args...)\n\tif err != nil {\n\t\tglog.Error(err)\n\t}\n\treturn Info{\n\t\tKind: rkind,\n\t\tName: rname,\n\t\tNamespace: rnamespace,\n\t\tReason: reason,\n\t\tSource: source,\n\t\tMessage: msgText,\n\t}\n}",
"func new_(e interface{}) func() Event {\n\ttyp := reflect.TypeOf(e)\n\treturn func() Event {\n\t\treturn reflect.New(typ).Interface().(Event)\n\t}\n}",
"func (n *EventReceiver) Event(eventName string) {\n\n}",
"func NewEvent(args interface{}) Event {\n\tea := reflect.Indirect(reflect.ValueOf(args))\n\treturn Event{\n\t\tName: ea.Type().Name(),\n\t\tAt: time.Now().UTC(),\n\t\tArgs: ea.Interface(),\n\t}\n}",
"func (w *Watcher) newEvent(name string, mask uint32) Event {\n\te := Event{Name: name}\n\tif mask&unix.IN_CREATE == unix.IN_CREATE || mask&unix.IN_MOVED_TO == unix.IN_MOVED_TO {\n\t\te.Op |= Create\n\t}\n\tif mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF || mask&unix.IN_DELETE == unix.IN_DELETE {\n\t\te.Op |= Remove\n\t}\n\tif mask&unix.IN_MODIFY == unix.IN_MODIFY {\n\t\te.Op |= Write\n\t}\n\tif mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF || mask&unix.IN_MOVED_FROM == unix.IN_MOVED_FROM {\n\t\te.Op |= Rename\n\t}\n\tif mask&unix.IN_ATTRIB == unix.IN_ATTRIB {\n\t\te.Op |= Chmod\n\t}\n\treturn e\n}",
"func NewEvent(data map[string]interface{}) (Event, error) {\n\treturn parseToEventType(data)\n}",
"func NotifyEventNew(buf []byte) xgb.Event {\n\tv := NotifyEvent{}\n\tb := 1 // don't read event number\n\n\tv.SubCode = buf[b]\n\tb += 1\n\n\tv.Sequence = xgb.Get16(buf[b:])\n\tb += 2\n\n\tv.U = NotifyDataUnion{}\n\tb += NotifyDataUnionRead(buf[b:], &v.U)\n\n\treturn v\n}",
"func newEvent(id string, img model.Image) Event {\n\treturn Event{\n\t\tSource: \"kyma-showcase\",\n\t\tSpecVersion: \"1.0\",\n\t\tEventTypeVersion: \"v1\",\n\t\tData: img.ID,\n\t\tId: id,\n\t\tDataContentType: \"application/json\",\n\t\tEventType: eventType,\n\t}\n}",
"func NewEvent(event interface{}, source string, sourcetype string, index string) (Event) {\n\thostname, _ := os.Hostname()\n\te := Event{Time: time.Now().Unix(), Host: hostname, Source: source, SourceType: sourcetype, Index: index, Event: event}\n\n\treturn e\n}",
"func New() Event {\n\treturn Event{}\n}",
"func (n *Node) HandleNewEventLocked(ev *roothash.Event) {\n\t// Nothing to do here.\n}",
"func newEvent(path string) Event {\n\te := Event{Path: path}\n\treturn e\n}",
"func (o *PluginDnsClient) OnEvent(msg string, a, b interface{}) {}",
"func NewEvent(action string, version int8, parent uuid.UUID, key []byte, data []byte) Event {\n\tid := uuid.Must(uuid.NewV4())\n\tif key == nil {\n\t\tkey = id.Bytes()\n\t}\n\n\t// Fix: unexpected end of JSON input\n\tif len(data) == 0 {\n\t\tdata = []byte(\"null\")\n\t}\n\n\tevent := Event{\n\t\tParent: parent,\n\t\tID: id,\n\t\tHeaders: make(map[string]string),\n\t\tAction: action,\n\t\tData: data,\n\t\tKey: key,\n\t\tStatus: StatusOK,\n\t\tVersion: version,\n\t\tCtx: context.Background(),\n\t}\n\n\treturn event\n}",
"func (w Wrapper) OnNewMessage(f NewMessageHandler) {\n\tw.longpoll.EventNew(4, func(i []interface{}) error {\n\t\tvar event NewMessage\n\t\tif err := event.parse(i); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tf(event)\n\n\t\treturn nil\n\t})\n}",
"func NewEventHandler(kind string, queue workqueue.Interface) cache.ResourceEventHandler {\n\thandler := cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tlogAndQueue(\"Add\", kind, queue, obj, nil)\n\t\t},\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\tlogAndQueue(\"Update\", kind, queue, new, old)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tlogAndQueue(\"Delete\", kind, queue, obj, nil)\n\t\t},\n\t}\n\treturn handler\n}",
"func NewEvent(ctx context.Context, acker Acknowledger, data map[string]interface{}) *Event {\n\tret := &Event{\n\t\tctx: ctx,\n\t\tacker: acker,\n\t\tdata: data,\n\t}\n\tret.convertData()\n\treturn ret\n}",
"func (n *NullEventReceiver) Event(eventName string) {\n}",
"func NewEvent() Event {\n\treturn Event{}\n}",
"func NewEvent(x, y float64, button, event string) Event {\n\treturn Event{\n\t\tPoint2: floatgeom.Point2{x, y},\n\t\tButton: button,\n\t\tEvent: event,\n\t}\n}",
"func NewEvent(x, y float64, button Button, event string) Event {\n\treturn Event{\n\t\tPoint2: floatgeom.Point2{x, y},\n\t\tButton: button,\n\t\tEvent: event,\n\t}\n}",
"func (s *BasemumpsListener) EnterNew_(ctx *New_Context) {}",
"func (m *MemAdmin) OnEvent(siteID string, ev admin.EventType) error {\n\tresp, ok := m.data[siteID]\n\tif !ok {\n\t\treturn fmt.Errorf(\"site %s not found\", siteID)\n\t}\n\tif ev == admin.EvCreate {\n\t\tresp.CountCreated++ // not a good idea, just for demo\n\t\tm.data[siteID] = resp\n\t}\n\treturn nil\n}",
"func HandleCreateEvent(w rest.ResponseWriter, req *rest.Request) {\n\tif err := RequireWriteKey(w, req); err != nil {\n\t\trest.Error(w, err.Error(), err.(StatusError).Code)\n\t\treturn\n\t}\n\n\tproject := currentProject(req)\n\tevent := req.PathParam(\"event_name\")\n\n\tvar data CreateSingleEventParams\n\tvar err error\n\tif err = eventData(req, &data); err != nil {\n\t\trest.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tevents := make(map[string][]interface{})\n\tevents[event] = []interface{}{data}\n\n\tresult, err := createEvent(project, event, data)\n\n\tif err != nil {\n\t\trest.Error(w, err.Error(), http.StatusBadRequest)\n\t} else {\n\t\tw.WriteJson(result)\n\t}\n}",
"func Handler(w http.ResponseWriter, r *http.Request) {\n\teventType := r.Header.Get(gitHubEventHeader)\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"failed to read the request body: %s\", err.Error())\n\t\thttp.Error(w, msg, http.StatusBadRequest)\n\t\treturn\n\t}\n\th, ok := eventHandlerMap[eventType]\n\n\tif !ok {\n\t\tlog.Printf(\"failed to handle event %s\\n\", eventType)\n\t\tw.Header().Set(\"Content-Type\", r.Header.Get(\"Content-Type\"))\n\t\tw.Write(body)\n\t\treturn\n\t}\n\n\tlog.Printf(\"handling event %s\\n\", eventType)\n\tnewBody, err := h(r, body)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"failed handling the event: %s\", err.Error())\n\t\thttp.Error(w, msg, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif len(newBody) > 0 {\n\t\tw.Header().Set(\"Content-Type\", r.Header.Get(\"Content-Type\"))\n\t\tw.Write(newBody)\n\t\treturn\n\t}\n\n\thttp.Error(w, \"failed interception\", http.StatusPreconditionFailed)\n}",
"func (a *Auditor) NewEvent(tenantID, userID, eventName, eventResult, resourceCategory, resourceType, resourceID, resourceName string, body string) {\n\ttenantName := tenantID\n\tuserName, err := cas.GetUserNameByID(userID)\n\tif err != nil {\n\t\tuserName = userID\n\t\tklog.Errorf(\"cannot get username with id %s: %+v\", userID, err)\n\t}\n\te := event{\n\t\tdata: AutoGenerated{\n\t\t\tTenantID: tenantID,\n\t\t\tTenantName: tenantName,\n\t\t\tUserID: userID,\n\t\t\tUserName: userName,\n\t\t\tRecordTime: time.Now().Format(\"2006-01-02 15:04:05\"),\n\t\t\tEventName: eventName,\n\t\t\tEventResult: eventResult,\n\t\t\tResourceCategory: resourceCategory,\n\t\t\tResourceType: resourceType,\n\t\t\tResourceID: resourceID,\n\t\t\tResourceName: resourceName,\n\t\t\tRequestBody: body,\n\t\t},\n\t\tretry: 2,\n\t}\n\tklog.V(5).Infof(\"new audit log: %+v\", e.data)\n\ta.queue <- e\n}",
"func AddNewEvent(event eventinfo.Info) {\n\teventList = append(eventList, event)\n}",
"func (o *IpfixNsPlugin) OnEvent(msg string, a, b interface{}) {}",
"func NewEvent(ctx *handlers.GatewayContext) EventI {\n\tstats := ctx.Stats.Clone(statsd.Prefix(\"api.event\"))\n\treturn &Event{\n\t\tEvent: helpers.NewEvent(ctx.Rabbit),\n\t\tBaseHandler: &handlers.BaseHandler{Stats: stats},\n\t}\n}",
"func (o *PluginDnsNs) OnEvent(msg string, a, b interface{}) {}",
"func (handler *Handler) Event(logEvent *event.Event) error {\n\thandler.mutex.Lock()\n\thandler.events = append(handler.events, logEvent)\n\thandler.mutex.Unlock()\n\treturn nil\n}",
"func New(eventType Type, srv server.Server, bootType, script string, params map[string]interface{}) Event {\n\tvar event Event\n\n\tevent.Type = eventType\n\tevent.Date = time.Now()\n\tevent.Server = srv\n\tevent.BootType = bootType\n\tevent.Script = script\n\tevent.Params = params\n\n\tevent.setMessage()\n\n\treturn event\n}",
"func New(name string, data M) *BasicEvent {\n\treturn NewBasic(name, data)\n}",
"func (w *Watcher) handleEvent(subsystem string) {\n cmd := NewCmd()\n\n switch subsystem {\n case \"mixer\":\n fallthrough\n case \"options\":\n fallthrough\n case \"player\":\n cmd.Cmd = \"Status\"\n case \"playlist\":\n cmd.Cmd = \"PlaylistInfo\"\n case \"stored_playlist\":\n cmd.Cmd = \"ListPlaylists\"\n case \"database\":\n cmd.Cmd = \"GetFiles\"\n default:\n return\n }\n w.cmd <- cmd\n}",
"func (engine *TcpEngin) HandleNewClient(onNewClient func(client *TcpClient)) {\r\n\tengine.onNewClientHandler = onNewClient\r\n}",
"func GitEventHandler(w http.ResponseWriter, r *http.Request) {\n\tevent_type := r.Header.Get(\"X-GitHub-Event\")\n\n\tif event_type == \"pull_request\" {\n\t\tpr_event := new(github.PullRequestEvent)\n\t\tjson.NewDecoder(r.Body).Decode(pr_event)\n\n\t\tif config.Config.Debug {\n\t\t\tlog.Printf(\"Event Type: %s, Created by: %s\\n\", event_type, pr_event.PullRequest.Base.User.Login)\n\t\t\tlog.Printf(\"Message: %s\\n\", r.Body)\n\t\t}\n\n\t\tgo clients.ProcessPullRequest(*pr_event)\n\t\tlog.Println(\"Handler exiting...\")\n\t} else {\n\t\tlog.Printf(\"Event %s not supported yet.\\n\", event_type)\n\t}\n}",
"func (h *Handler) EventHandle(etype string, name string, eventHandler EventHandler) {\n\tif eventHandler == nil {\n\t\tpanic(\"serfer: nil event handler\")\n\t}\n\tif !validEventType(etype) {\n\t\tpanic(fmt.Sprintf(\"serfer: unknown event type %q\", etype))\n\t}\n\t// The event type '*' is the same as an empty event type '' and the latest\n\t// should be used\n\tif etype == \"*\" {\n\t\tetype = \"\"\n\t}\n\t// TODO: Do we really want this? or overwrite the event or add another event with same name?\n\t// Only the default entry can be overwritten\n\t// if _, ok := h.entry[etype][name]; ok && len(etype) != 0 && len(name) != 0 {\n\t// \tpanic(fmt.Sprintf(\"serfer: multiple registrations for %s named %q\", etype, name))\n\t// }\n\tif h.entry == nil {\n\t\th.entry = newEntries()\n\t}\n\n\tvar ehs []EventHandler\n\tif _, ok := h.entry[etype][name]; ok {\n\t\tehs = append(h.entry[etype][name].h, eventHandler)\n\t} else {\n\t\tehs = []EventHandler{eventHandler}\n\t}\n\n\tif _, ok := h.entry[etype]; !ok {\n\t\th.entry[etype] = make(map[string]handlerEntry)\n\t}\n\th.entry[etype][name] = handlerEntry{\n\t\teventType: etype,\n\t\tname: name,\n\t\th: ehs,\n\t}\n}",
"func NewEvent(meta EventHandler) *Event {\n\treturn &Event{\n\t\tMetadata: meta,\n\t\teventResults: make(chan interface{}, 1),\n\t\tcancelled: make(chan struct{}),\n\t\tstats: eventStatistics{},\n\t}\n}",
"func StoreEventHandler(w http.ResponseWriter, r *http.Request) {\n\tvar incEvent models.Event\n\tlog.Println(\"Processing event: \", r.Body)\n\ttoken := r.Header.Get(\"CANARY_TOKEN\")\n\n\tproject := models.Project{}\n\tdatabase.DB.Where(\"token = ?\", token).\n\t\tFirst(&project)\n\tif project.Name == \"\" {\n\t\tlog.Println(\"Could not find project with token\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"Invalid Token\"))\n\t\treturn\n\t}\n\n\t// Obtain Event info from JSON\n\tdec := json.NewDecoder(r.Body)\n\terr := dec.Decode(&incEvent)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"Error decoding JSON\"))\n\t\treturn\n\t}\n\n\tincEvent.ProjectID = project.ID\n\n\t// Attempt to store the Event in the database\n\tevent, err := models.StoreEvent(&incEvent)\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"Error saving event\"))\n\t\treturn\n\t}\n\n\tlog.Println(\"Created new event: \", event.ID)\n\n\teventJson, err := json.Marshal(event)\n\tif err != nil {\n\t\tlog.Println(\"Error encoding event\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Send an awknowledge response\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(eventJson)\n\treturn\n}",
"func newEvent(values map[string]interface{}, machineId string) interface{} {\n\tswitch values[\"event\"].(string) {\n\n\tcase \"ping.offline\", \"ping.online\":\n\t\treturn HeartBeat{Event: values[\"event\"].(string),\n\t\t\tIp: values[\"ip\"].(string),\n\t\t\tMachineId: machineId}\n\n\tcase \"fs.removed\", \"fs.created\":\n\t\treturn FsSystem{Event: values[\"event\"].(string),\n\t\t\tVolume: values[\"volume\"].(string),\n\t\t\tType: values[\"type\"].(string),\n\t\t\tMachineId: machineId,\n\t\t\tIp: values[\"ip\"].(string)}\n\n\tcase \"disk.unplugged\":\n\t\treturn DiskUnplugged{Event: values[\"event\"].(string),\n\t\t\tUuid: values[\"uuid\"].(string),\n\t\t\tLocation: values[\"location\"].(string),\n\t\t\tDevName: values[\"dev_name\"].(string),\n\t\t\tMachineId: machineId,\n\t\t\tIp: values[\"ip\"].(string)}\n\n\tcase \"disk.plugged\", \"raid.created\", \"volume.created\", \"volume.removed\", \"raid.degraded\", \"raid.failed\", \"volume.failed\", \"volume.normal\", \"raid.normal\":\n\t\treturn DiskPlugged{Event: values[\"event\"].(string),\n\t\t\tUuid: values[\"uuid\"].(string),\n\t\t\tMachineId: machineId,\n\t\t\tIp: values[\"ip\"].(string)}\n\n\tcase \"raid.removed\":\n\t\tdisks := values[\"raid_disks\"].([]interface{})\n\t\tvar ones []string\n\t\tfor _, val := range disks {\n\t\t\tdisk := val.(string)\n\t\t\tones = append(ones, disk)\n\t\t}\n\n\t\treturn RaidRemove{Event: values[\"event\"].(string),\n\t\t\tUuid: values[\"uuid\"].(string),\n\t\t\tRaidDisks: ones,\n\t\t\tMachineId: machineId,\n\t\t\tIp: values[\"ip\"].(string)}\n\t}\n\treturn nil\n}",
"func (tr *Repository) NewEvent(t Transaction, eventType string, violations []string) es.Event {\n\ttime := time.Now()\n\n\tevent := es.Event{\n\t\tTimestamp: time,\n\t\tName: eventType,\n\t\tPayload: t,\n\t\tViolations: violations,\n\t}\n\n\treturn event\n}",
"func (h GenerateThumbAndBigShotsOnMediaImportedHandler) NewEvent() interface{} {\n\treturn &events.MediaImported{}\n}",
"func (o *PluginIgmpClient) OnEvent(msg string, a, b interface{}) {\n\n}",
"func NewEvent() *Event {\n\treturn &Event{c: make(chan struct{})}\n}",
"func NewEvent(status Status) Event {\n\treturn Event{\n\t\tStatus: status,\n\t\tTime: time.Now(),\n\t}\n}",
"func (d *DevClient) CreateEventHandler(systemKey, name string, data map[string]interface{}) (map[string]interface{}, error) {\n\treturn createEventHandler(d, _EVENTS_HDLRS_PREAMBLE+systemKey+\"/\"+name, data)\n}",
"func (o *SrlBfd) NewEvent(reason, message string) corev1.Event {\n\tt := metav1.Now()\n\treturn corev1.Event{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tGenerateName: reason + \"-\",\n\t\t\tNamespace: o.ObjectMeta.Namespace,\n\t\t},\n\t\tInvolvedObject: corev1.ObjectReference{\n\t\t\tKind: \"SrlBfd\",\n\t\t\tNamespace: o.Namespace,\n\t\t\tName: o.Name,\n\t\t\tUID: o.UID,\n\t\t\tAPIVersion: GroupVersion.String(),\n\t\t},\n\t\tReason: reason,\n\t\tMessage: message,\n\t\tSource: corev1.EventSource{\n\t\t\tComponent: \"srl-controller\",\n\t\t},\n\t\tFirstTimestamp: t,\n\t\tLastTimestamp: t,\n\t\tCount: 1,\n\t\tType: corev1.EventTypeNormal,\n\t\tReportingController: \"srlinux.henderiw.be/srl-controller\",\n\t}\n}",
"func eventHandler(evt *elemental.Event) {\n\n\tswitch evt.Identity {\n\n\tcase gaia.ExternalNetworkIdentity.Name:\n\n\t\te := gaia.NewExternalNetwork()\n\t\tif err := evt.Decode(&e); err != nil {\n\t\t\tzap.L().Error(\"Failed to decode event\", zap.Reflect(\"event\", evt))\n\t\t}\n\n\t\tfmt.Printf(\"External network name: %s type %s\\n\", e.Name, evt.Type)\n\n\tcase gaia.NetworkAccessPolicyIdentity.Name:\n\n\t\tp := gaia.NewNetworkAccessPolicy()\n\t\tif err := evt.Decode(&p); err != nil {\n\t\t\tzap.L().Error(\"Failed to decode event\", zap.Reflect(\"event\", evt))\n\t\t}\n\n\t\tfmt.Printf(\"Policy name: %s type %s\\n\", p.Name, evt.Type)\n\n\tdefault:\n\t\tzap.L().Error(\"Received event that was not subscribed\", zap.Reflect(\"event\", evt))\n\t}\n}",
"func NewEvent(msg string) *Event {\n\treturn &Event{\n\t\tCreated: time.Now(),\n\t\tDescription: msg,\n\t}\n}",
"func (a Application) Handler(event json.RawMessage, ctx *apex.Context) (interface{}, error) {\n\tlog.Println(string(event))\n\treq, err := ParseRequest(a.ID, bytes.NewReader(event))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := NewResponse()\n\n\tswitch req.Type() {\n\tcase \"LaunchRequest\":\n\t\tif a.LaunchHandler != nil {\n\t\t\ta.LaunchHandler(req, res)\n\t\t}\n\tcase \"IntentRequest\":\n\t\tif a.IntentHandler != nil {\n\t\t\ta.IntentHandler(req, res)\n\t\t}\n\tcase \"SessionEndedRequest\":\n\t\tif a.SessionEndedHandler != nil {\n\t\t\ta.SessionEndedHandler(req, res)\n\t\t}\n\tdefault:\n\t\treturn nil, errors.New(\"invalid request type\")\n\t}\n\n\treturn res, nil\n}",
"func (*HelloEvent) Op() ws.OpCode { return 8 }",
"func NewEventHandler(app *application, evt *v1.Event) EventHandler {\n\tkey := registryKey{APIVersion: evt.InvolvedObject.APIVersion, Kind: evt.InvolvedObject.Kind}\n\tfactory := handlerRegistry[key]\n\tif factory != nil {\n\t\tif handler := factory(app, evt); handler != nil {\n\t\t\treturn handler\n\t\t}\n\t}\n\treturn NewDefaultEventHandler(app, evt)\n}",
"func (h CreateMediaOnMediaImportedHandler) NewEvent() interface{} {\n\treturn &events.MediaImported{}\n}",
"func handleEvent(e *event) {\n\tswitch e.eType {\n\tcase Follow:\n\t\tfollow(e)\n\tcase Unfollow:\n\t\tunFollow(e)\n\tcase Broadcast:\n\t\tclients.Range(func(h *ClientHandler) {\n\t\t\th.Write(e)\n\t\t})\n\tcase PrivateMessage:\n\t\tif h, ok := clients.Get(e.to); ok {\n\t\t\th.Write(e)\n\t\t}\n\tcase StatusUpdate:\n\t\tupdateStatus(e)\n\tdefault:\n\t\tlog.Panicf(\"Could not recognize event type %v\", e.eType)\n\t}\n}",
"func (c *Client) On(event string, handler Handler) {\n\tc.handlers[event] = handler\n}",
"func (host *Server) NewEvent(reason, message string) corev1.Event {\n\tt := metav1.Now()\n\treturn corev1.Event{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tGenerateName: reason + \"-\",\n\t\t\tNamespace: host.ObjectMeta.Namespace,\n\t\t},\n\t\tInvolvedObject: corev1.ObjectReference{\n\t\t\tKind: \"Server\",\n\t\t\tNamespace: host.Namespace,\n\t\t\tName: host.Name,\n\t\t\tUID: host.UID,\n\t\t\tAPIVersion: SchemeGroupVersion.String(),\n\t\t},\n\t\tReason: reason,\n\t\tMessage: message,\n\t\tSource: corev1.EventSource{\n\t\t\tComponent: \"app-server-controller\",\n\t\t},\n\t\tFirstTimestamp: t,\n\t\tLastTimestamp: t,\n\t\tCount: 1,\n\t\tType: corev1.EventTypeNormal,\n\t\tReportingController: \"example.inc/server-controller\",\n\t\tRelated: host.Spec.ConsumerRef,\n\t}\n}",
"func (h HandlerFunc) Handle(e Event) { h(e) }",
"func createEvent(action string) *Event {\n\treturn &Event{\n\t\tID: uuid.Generate().String(),\n\t\tTimestamp: time.Now(),\n\t\tAction: action,\n\t}\n}",
"func (client *Client) handleEvent(event *Event) {\n\tsentCapEnd := false\n\n\t// Only use IRCv3 `server-time` to overwrite when requested. Frontends/dependents can still\n\t// get this information.\n\tif client.config.UseServerTime {\n\t\tif timeTag, ok := event.Tags[\"time\"]; ok {\n\t\t\tserverTime, err := time.Parse(time.RFC3339Nano, timeTag)\n\t\t\tif err == nil && serverTime.Year() > 2000 {\n\t\t\t\tevent.Time = serverTime\n\t\t\t}\n\t\t}\n\t}\n\n\t// For events that were created with targets, handle them now there now.\n\tfor _, target := range event.targets {\n\t\ttarget.Handle(event, client)\n\t}\n\n\tswitch event.name {\n\n\t// Ping Pong\n\tcase \"hook.tick\":\n\t\t{\n\t\t\tclient.mutex.RLock()\n\t\t\tlastSend := time.Since(client.lastSend)\n\t\t\tclient.mutex.RUnlock()\n\n\t\t\tif lastSend > time.Second*120 {\n\t\t\t\t_ = client.Sendf(\"PING :%x%x%x\", mathRand.Int63(), mathRand.Int63(), mathRand.Int63())\n\t\t\t}\n\t\t}\n\tcase \"packet.ping\":\n\t\t{\n\t\t\tmessage := \"PONG\"\n\t\t\tfor _, arg := range event.Args {\n\t\t\t\tmessage += \" \" + arg\n\t\t\t}\n\t\t\tif event.Text != \"\" {\n\t\t\t\tmessage += \" :\" + event.Text\n\t\t\t}\n\n\t\t\t_ = client.Send(message)\n\t\t}\n\n\t// Client Registration\n\tcase \"client.connect\":\n\t\t{\n\t\t\t// Clear enabled caps and initiate negotiation.\n\t\t\tclient.mutex.Lock()\n\t\t\tfor key := range client.capEnabled {\n\t\t\t\tdelete(client.capEnabled, key)\n\t\t\t}\n\t\t\tclient.mutex.Unlock()\n\t\t\t_ = client.Send(\"CAP LS 302\")\n\n\t\t\t// Send server password if configured.\n\t\t\tif client.config.Password != \"\" {\n\t\t\t\t_ = client.Sendf(\"PASS :%s\", client.config.Password)\n\t\t\t}\n\n\t\t\t// Reuse nick or get from config\n\t\t\tnick := client.config.Nick\n\t\t\tclient.mutex.RLock()\n\t\t\tif client.nick != \"\" {\n\t\t\t\tnick = client.nick\n\t\t\t}\n\t\t\tclient.mutex.RUnlock()\n\n\t\t\t// Clear connection-specific data\n\t\t\tclient.mutex.Lock()\n\t\t\tclient.nick = \"\"\n\t\t\tclient.user = \"\"\n\t\t\tclient.host = \"\"\n\t\t\tclient.capsRequested = client.capsRequested[:0]\n\t\t\tfor key := range client.capData {\n\t\t\t\tdelete(client.capData, key)\n\t\t\t}\n\t\t\tfor key := range client.capEnabled {\n\t\t\t\tdelete(client.capEnabled, key)\n\t\t\t}\n\t\t\tclient.mutex.Unlock()\n\n\t\t\t// Start registration.\n\t\t\t_ = client.Sendf(\"NICK %s\", nick)\n\t\t\t_ = client.Sendf(\"USER %s 8 * :%s\", client.config.User, client.config.RealName)\n\t\t}\n\n\t// Welcome message\n\tcase \"packet.001\":\n\t\t{\n\t\t\tclient.mutex.Lock()\n\t\t\tclient.nick = event.Args[0]\n\t\t\tclient.mutex.Unlock()\n\n\t\t\t// Send a WHO right away to gather enough client information for precise message cutting.\n\t\t\t_ = client.Sendf(\"WHO %s\", event.Args[0])\n\t\t}\n\n\t// Nick rotation\n\tcase \"packet.431\", \"packet.432\", \"packet.433\", \"packet.436\":\n\t\t{\n\t\t\tlockNickChange, _ := client.Value(\"internal.lockNickChange\").(bool)\n\n\t\t\t// Ignore if client is registered\n\t\t\tif client.Nick() != \"\" {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tnick := event.Args[1]\n\t\t\tnewNick := \"\"\n\n\t\t\t// \"AltN\" -> \"AltN+1\", ...\n\t\t\tprev := client.config.Nick\n\t\t\tfor _, alt := range client.config.Alternatives {\n\t\t\t\tif nick == prev {\n\t\t\t\t\tnewNick = alt\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tprev = alt\n\t\t\t}\n\n\t\t\tif newNick == \"\" {\n\t\t\t\t// \"LastAlt\" -> \"Nick23962\"\n\t\t\t\tnewNick = fmt.Sprintf(\"%s%05d\", client.config.Nick, mathRand.Int31n(99999))\n\t\t\t}\n\n\t\t\tif lockNickChange {\n\t\t\t\tclient.SetValue(\"internal.primedNickChange\", newNick)\n\t\t\t} else {\n\t\t\t\t_ = client.Sendf(\"NICK %s\", newNick)\n\t\t\t}\n\t\t}\n\n\tcase \"packet.nick\":\n\t\t{\n\t\t\tclient.handleInTargets(event.Nick, event)\n\n\t\t\tif event.Nick == client.nick {\n\t\t\t\tclient.SetValue(\"nick\", event.Arg(0))\n\t\t\t}\n\t\t}\n\n\t// ISupport\n\tcase \"packet.005\":\n\t\t{\n\t\t\tfor _, token := range event.Args[1:] {\n\t\t\t\tkvpair := strings.Split(token, \"=\")\n\n\t\t\t\tif len(kvpair) == 2 {\n\t\t\t\t\tclient.isupport.Set(kvpair[0], kvpair[1])\n\t\t\t\t} else {\n\t\t\t\t\tclient.isupport.Set(kvpair[0], \"\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t// Capability negotiation\n\tcase \"packet.cap\":\n\t\t{\n\t\t\tcapCommand := event.Args[1]\n\t\t\tcapTokens := strings.Split(event.Text, \" \")\n\n\t\t\tswitch capCommand {\n\t\t\tcase \"LS\":\n\t\t\t\t{\n\t\t\t\t\tclient.SetValue(\"internal.lockNickChange\", true)\n\n\t\t\t\t\tfor _, token := range capTokens {\n\t\t\t\t\t\tsplit := strings.SplitN(token, \"=\", 2)\n\t\t\t\t\t\tkey := split[0]\n\t\t\t\t\t\tif len(key) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif len(split) == 2 {\n\t\t\t\t\t\t\tclient.capData[key] = split[1]\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor i := range supportedCaps {\n\t\t\t\t\t\t\tif supportedCaps[i] == key {\n\t\t\t\t\t\t\t\tclient.mutex.Lock()\n\t\t\t\t\t\t\t\tclient.capsRequested = append(client.capsRequested, key)\n\t\t\t\t\t\t\t\tclient.mutex.Unlock()\n\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif len(event.Args) < 3 || event.Args[2] != \"*\" {\n\t\t\t\t\t\tclient.mutex.RLock()\n\t\t\t\t\t\trequestedCount := len(client.capsRequested)\n\t\t\t\t\t\tclient.mutex.RUnlock()\n\n\t\t\t\t\t\tif requestedCount > 0 {\n\t\t\t\t\t\t\tclient.mutex.RLock()\n\t\t\t\t\t\t\trequestedCaps := strings.Join(client.capsRequested, \" \")\n\t\t\t\t\t\t\tclient.mutex.RUnlock()\n\n\t\t\t\t\t\t\t_ = client.Send(\"CAP REQ :\" + requestedCaps)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsentCapEnd = true\n\t\t\t\t\t\t\t_ = client.Send(\"CAP END\")\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"ACK\":\n\t\t\t\t{\n\t\t\t\t\tfor _, token := range capTokens {\n\t\t\t\t\t\tclient.mutex.Lock()\n\t\t\t\t\t\tif !client.capEnabled[token] {\n\t\t\t\t\t\t\tclient.capEnabled[token] = true\n\t\t\t\t\t\t}\n\t\t\t\t\t\tclient.mutex.Unlock()\n\n\t\t\t\t\t\t// Special cases for supported tokens\n\t\t\t\t\t\tswitch token {\n\t\t\t\t\t\tcase \"sasl\":\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif client.config.SASL == nil {\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tmechanisms := strings.Split(client.capData[token], \",\")\n\t\t\t\t\t\t\t\tselectedMechanism := \"\"\n\t\t\t\t\t\t\t\tif len(mechanisms) == 0 || mechanisms[0] == \"\" {\n\t\t\t\t\t\t\t\t\tselectedMechanism = \"PLAIN\"\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfor _, mechanism := range mechanisms {\n\t\t\t\t\t\t\t\t\tif mechanism == \"PLAIN\" && selectedMechanism == \"\" {\n\t\t\t\t\t\t\t\t\t\tselectedMechanism = \"PLAIN\"\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t// TODO: Add better mechanisms\n\t\t\t\t\t\t\t\tif selectedMechanism != \"\" {\n\t\t\t\t\t\t\t\t\t_ = client.Sendf(\"AUTHENTICATE %s\", selectedMechanism)\n\t\t\t\t\t\t\t\t\tclient.SetValue(\"sasl.usingMethod\", \"PLAIN\")\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcase \"draft/languages\":\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif len(client.config.Languages) == 0 {\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t// draft/languages=15,en,~bs,~de,~el,~en-AU,~es,~fi,~fr-FR,~it,~no,~pl,~pt-BR,~ro,~tr-TR,~zh-CN\n\t\t\t\t\t\t\t\tlangData := strings.Split(client.capData[token], \",\")\n\t\t\t\t\t\t\t\tif len(langData) < 0 {\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tmaxCount, err := strconv.Atoi(langData[0])\n\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tlanguages := make([]string, 0, maxCount)\n\n\t\t\t\t\t\t\tLanguageLoop:\n\t\t\t\t\t\t\t\tfor _, lang := range client.config.Languages {\n\t\t\t\t\t\t\t\t\tfor _, lang2 := range langData[1:] {\n\t\t\t\t\t\t\t\t\t\tif strings.HasPrefix(lang2, \"~\") {\n\t\t\t\t\t\t\t\t\t\t\tlang2 = lang2[1:]\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tif strings.EqualFold(lang, lang2) {\n\t\t\t\t\t\t\t\t\t\t\tlanguages = append(languages, lang)\n\t\t\t\t\t\t\t\t\t\t\tif len(languages) >= maxCount {\n\t\t\t\t\t\t\t\t\t\t\t\tbreak LanguageLoop\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif len(languages) > 0 {\n\t\t\t\t\t\t\t\t\t_ = client.Send(\"LANGUAGE \" + strings.Join(languages, \" \"))\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif !client.Ready() {\n\t\t\t\t\t\tsentCapEnd = true\n\t\t\t\t\t\t_ = client.Send(\"CAP END\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"NAK\":\n\t\t\t\t{\n\t\t\t\t\t// Remove offenders\n\t\t\t\t\tfor _, token := range capTokens {\n\t\t\t\t\t\tclient.mutex.Lock()\n\t\t\t\t\t\tfor i := range client.capsRequested {\n\t\t\t\t\t\t\tif token == client.capsRequested[i] {\n\t\t\t\t\t\t\t\tclient.capsRequested = append(client.capsRequested[:i], client.capsRequested[i+1:]...)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tclient.mutex.Unlock()\n\t\t\t\t\t}\n\n\t\t\t\t\tclient.mutex.RLock()\n\t\t\t\t\trequestedCaps := strings.Join(client.capsRequested, \" \")\n\t\t\t\t\tclient.mutex.RUnlock()\n\n\t\t\t\t\t_ = client.Send(\"CAP REQ :\" + requestedCaps)\n\t\t\t\t}\n\t\t\tcase \"NEW\":\n\t\t\t\t{\n\t\t\t\t\trequests := make([]string, 0, len(capTokens))\n\n\t\t\t\t\tfor _, token := range capTokens {\n\t\t\t\t\t\tfor i := range supportedCaps {\n\t\t\t\t\t\t\tif supportedCaps[i] == token {\n\t\t\t\t\t\t\t\trequests = append(requests, token)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif len(requests) > 0 {\n\t\t\t\t\t\t_ = client.Send(\"CAP REQ :\" + strings.Join(requests, \" \"))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"DEL\":\n\t\t\t\t{\n\t\t\t\t\tfor _, token := range capTokens {\n\t\t\t\t\t\tclient.mutex.Lock()\n\t\t\t\t\t\tif client.capEnabled[token] {\n\t\t\t\t\t\t\tclient.capEnabled[token] = false\n\t\t\t\t\t\t}\n\t\t\t\t\t\tclient.mutex.Unlock()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t// SASL\n\tcase \"packet.authenticate\":\n\t\t{\n\t\t\tif event.Arg(0) != \"+\" {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tmethod, ok := client.Value(\"sasl.usingMethod\").(string)\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tswitch method {\n\t\t\tcase \"PLAIN\":\n\t\t\t\t{\n\t\t\t\t\tparts := [][]byte{\n\t\t\t\t\t\t[]byte(client.config.SASL.AuthenticationIdentity),\n\t\t\t\t\t\t[]byte(client.config.SASL.AuthorizationIdentity),\n\t\t\t\t\t\t[]byte(client.config.SASL.Password),\n\t\t\t\t\t}\n\t\t\t\t\tplainString := base64.StdEncoding.EncodeToString(bytes.Join(parts, []byte{0x00}))\n\n\t\t\t\t\t_ = client.Sendf(\"AUTHENTICATE %s\", plainString)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase \"packet.904\": // Auth failed\n\t\t{\n\t\t\t// Cancel authentication.\n\t\t\t_ = client.Sendf(\"AUTHENTICATE *\")\n\t\t\tclient.SetValue(\"sasl.usingMethod\", (interface{})(nil))\n\t\t}\n\tcase \"packet.903\", \"packet.906\": // Auth ended\n\t\t{\n\t\t\t// A bit dirty, but it'll get the nick rotation started again.\n\t\t\tif client.Nick() == \"\" {\n\t\t\t\t_ = client.Sendf(\"NICK %s\", client.config.Nick)\n\t\t\t}\n\t\t}\n\n\t// User/host detection\n\tcase \"packet.352\": // WHO reply\n\t\t{\n\t\t\t// Example args: test * ~irce 127.0.0.1 localhost.localnetwork Gissleh H :0 ...\n\t\t\tnick := event.Args[5]\n\t\t\tuser := event.Args[2]\n\t\t\thost := event.Args[3]\n\n\t\t\tif nick == client.nick {\n\t\t\t\tclient.mutex.Lock()\n\t\t\t\tclient.user = user\n\t\t\t\tclient.host = host\n\t\t\t\tclient.mutex.Unlock()\n\t\t\t}\n\t\t}\n\n\tcase \"packet.chghost\":\n\t\t{\n\t\t\tif event.Nick == client.nick {\n\t\t\t\tclient.mutex.Lock()\n\t\t\t\tclient.user = event.Args[1]\n\t\t\t\tclient.host = event.Args[2]\n\t\t\t\tclient.mutex.Unlock()\n\t\t\t}\n\n\t\t\t// This may be relevant in channels where the client resides.\n\t\t\tclient.handleInTargets(event.Nick, event)\n\t\t}\n\n\t// Channel join/leave/mode handling\n\tcase \"packet.join\":\n\t\t{\n\t\t\tvar channel *Channel\n\n\t\t\tif event.Nick == client.nick {\n\t\t\t\tchannel = &Channel{\n\t\t\t\t\tid: generateClientID(\"T\"),\n\t\t\t\t\tname: event.Arg(0),\n\t\t\t\t\tuserlist: list.New(&client.isupport),\n\t\t\t\t}\n\t\t\t\t_ = client.AddTarget(channel)\n\t\t\t} else {\n\t\t\t\tchannel = client.Channel(event.Arg(0))\n\t\t\t}\n\n\t\t\tclient.handleInTarget(channel, event)\n\t\t}\n\n\tcase \"packet.part\":\n\t\t{\n\t\t\tchannel := client.Channel(event.Arg(0))\n\t\t\tif channel == nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif event.Nick == client.nick {\n\t\t\t\tchannel.parted = true\n\t\t\t\t_, _ = client.RemoveTarget(channel)\n\t\t\t} else {\n\t\t\t\tclient.handleInTarget(channel, event)\n\t\t\t}\n\t\t}\n\n\tcase \"packet.kick\":\n\t\t{\n\t\t\tchannel := client.Channel(event.Arg(0))\n\t\t\tif channel == nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif event.Arg(1) == client.nick {\n\t\t\t\tchannel.parted = true\n\t\t\t\t_, _ = client.RemoveTarget(channel)\n\t\t\t} else {\n\t\t\t\tclient.handleInTarget(channel, event)\n\t\t\t}\n\t\t}\n\n\tcase \"packet.quit\":\n\t\t{\n\t\t\tclient.handleInTargets(event.Nick, event)\n\t\t}\n\n\tcase \"packet.353\": // NAMES\n\t\t{\n\t\t\tchannel := client.Channel(event.Arg(2))\n\t\t\tif channel != nil {\n\t\t\t\tclient.handleInTarget(channel, event)\n\t\t\t}\n\t\t}\n\n\tcase \"packet.366\": // End of NAMES\n\t\t{\n\t\t\tchannel := client.Channel(event.Arg(1))\n\t\t\tif channel != nil {\n\t\t\t\tclient.handleInTarget(channel, event)\n\t\t\t}\n\t\t}\n\n\tcase \"packet.invite\":\n\t\t{\n\t\t\tinviteeNick := event.Arg(0)\n\t\t\tchannelName := event.Arg(1)\n\t\t\tchannel := client.Channel(channelName)\n\n\t\t\tif client.config.AutoJoinInvites && inviteeNick == client.Nick() {\n\t\t\t\tif channel == nil {\n\t\t\t\t\tclient.Join(channelName)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Add channel target for rendering invite-notify invitations.\n\t\t\tif channel != nil {\n\t\t\t\tclient.handleInTarget(channel, event)\n\t\t\t}\n\t\t}\n\n\tcase \"packet.mode\":\n\t\t{\n\t\t\ttargetName := event.Arg(0)\n\n\t\t\tif client.isupport.IsChannel(targetName) {\n\t\t\t\tchannel := client.Channel(targetName)\n\t\t\t\tif channel != nil {\n\t\t\t\t\tclient.handleInTarget(channel, event)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t// Message parsing\n\tcase \"packet.privmsg\", \"ctcp.action\":\n\t\t{\n\t\t\t// Target the message\n\t\t\ttarget := Target(client.status)\n\t\t\ttargetName := event.Arg(0)\n\t\t\tif targetName == client.Nick() {\n\t\t\t\ttargetName = event.Nick\n\t\t\t}\n\n\t\t\tif event.Nick == client.nick || event.Arg(0) == client.nick {\n\t\t\t\tqueryTarget := client.Target(\"query\", targetName)\n\t\t\t\tif queryTarget == nil {\n\t\t\t\t\tquery := &Query{\n\t\t\t\t\t\tid: client.id,\n\t\t\t\t\t\tuser: list.User{\n\t\t\t\t\t\t\tNick: event.Nick,\n\t\t\t\t\t\t\tUser: event.User,\n\t\t\t\t\t\t\tHost: event.Host,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t\tif accountTag, ok := event.Tags[\"account\"]; ok {\n\t\t\t\t\t\tquery.user.Account = accountTag\n\t\t\t\t\t}\n\n\t\t\t\t\t_ = client.AddTarget(query)\n\t\t\t\t\tevent.RenderTags[\"spawned\"] = query.id\n\n\t\t\t\t\tqueryTarget = query\n\t\t\t\t}\n\n\t\t\t\ttarget = queryTarget\n\t\t\t} else {\n\t\t\t\tchannel := client.Channel(targetName)\n\t\t\t\tif channel != nil {\n\t\t\t\t\tif user, ok := channel.UserList().User(event.Nick); ok {\n\t\t\t\t\t\tevent.RenderTags[\"prefixedNick\"] = user.PrefixedNick\n\t\t\t\t\t}\n\n\t\t\t\t\ttarget = channel\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tclient.handleInTarget(target, event)\n\t\t}\n\n\tcase \"packet.notice\":\n\t\t{\n\t\t\t// Find channel target\n\t\t\ttargetName := event.Arg(0)\n\t\t\tif client.isupport.IsChannel(targetName) {\n\t\t\t\tchannel := client.Channel(targetName)\n\t\t\t\tif channel != nil {\n\t\t\t\t\tif user, ok := channel.UserList().User(event.Nick); ok {\n\t\t\t\t\t\tevent.RenderTags[\"prefixedNick\"] = user.PrefixedNick\n\t\t\t\t\t}\n\n\t\t\t\t\tclient.handleInTarget(channel, event)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Try to target by mentioned channel name.\n\t\t\t\tfor _, token := range strings.Fields(event.Text) {\n\t\t\t\t\tif client.isupport.IsChannel(token) {\n\t\t\t\t\t\tchannel := client.Channel(token)\n\t\t\t\t\t\tif channel == nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif user, ok := channel.UserList().User(event.Nick); ok {\n\t\t\t\t\t\t\tevent.RenderTags[\"prefixedNick\"] = user.PrefixedNick\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tclient.handleInTarget(channel, event)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Otherwise, it belongs in the status target\n\t\t\tif len(event.targets) == 0 {\n\t\t\t\tclient.status.Handle(event, client)\n\t\t\t\tclient.handleInTarget(client.status, event)\n\t\t\t}\n\t\t}\n\n\t// account-notify\n\tcase \"packet.account\":\n\t\t{\n\t\t\tclient.handleInTargets(event.Nick, event)\n\t\t}\n\n\t// away-notify\n\tcase \"packet.away\":\n\t\t{\n\t\t\tclient.handleInTargets(event.Nick, event)\n\t\t}\n\n\t// Auto-rejoin\n\tcase \"packet.376\", \"packet.422\":\n\t\t{\n\t\t\tclient.mutex.RLock()\n\t\t\tchannels := make([]string, 0, len(client.targets))\n\t\t\trejoinEvent := NewEvent(\"info\", \"rejoin\")\n\t\t\tfor _, target := range client.targets {\n\t\t\t\tif channel, ok := target.(*Channel); ok {\n\t\t\t\t\tchannels = append(channels, channel.Name())\n\n\t\t\t\t\trejoinEvent.targets = append(rejoinEvent.targets, target)\n\t\t\t\t}\n\t\t\t}\n\t\t\tclient.mutex.RUnlock()\n\n\t\t\tif len(channels) > 0 {\n\t\t\t\t_ = client.Sendf(\"JOIN %s\", strings.Join(channels, \",\"))\n\t\t\t\tclient.EmitNonBlocking(rejoinEvent)\n\t\t\t}\n\n\t\t\tclient.mutex.Lock()\n\t\t\tclient.ready = true\n\t\t\tclient.mutex.Unlock()\n\n\t\t\tclient.EmitNonBlocking(NewEvent(\"hook\", \"ready\"))\n\t\t}\n\t}\n\n\tif sentCapEnd {\n\t\tclient.SetValue(\"internal.lockNickChange\", false)\n\n\t\tif primedNick, _ := client.Value(\"internal.primedNickChange\").(string); primedNick != \"\" {\n\t\t\t_ = client.Sendf(\"NICK %s\", primedNick)\n\t\t}\n\t}\n\n\tif len(event.targets) == 0 {\n\t\tclient.handleInTarget(client.status, event)\n\t}\n\n\tclient.mutex.RLock()\n\tclientHandlers := client.handlers\n\tclient.mutex.RUnlock()\n\n\tfor _, handler := range clientHandlers {\n\t\thandler(event, client)\n\t}\n}",
"func NewEvent(id, eventType string, version int, payload []byte) *Event {\n\tpayloadStr := string(payload)\n\treturn &Event{\n\t\tAggregateID: id,\n\t\tEventType: eventType,\n\t\tVersion: version,\n\t\tEventAt: time.Now(),\n\t\tPayload: &payloadStr,\n\t}\n}",
"func newCallBackHandler() (raw.OnewayHandler, <-chan map[string]string) {\n\tserverCalledBack := make(chan map[string]string)\n\treturn func(ctx context.Context, body []byte) error {\n\t\tserverCalledBack <- extractBaggage(ctx)\n\t\treturn nil\n\t}, serverCalledBack\n}",
"func eventHandlerFunc(events chan<- interface{}, obj interface{}) {\n\tselect {\n\tcase events <- obj:\n\tdefault:\n\t}\n}",
"func eventHandlerFunc(events chan<- interface{}, obj interface{}) {\n\tselect {\n\tcase events <- obj:\n\tdefault:\n\t}\n}",
"func handleNewMessage(msg *arbor.ProtocolMessage, recents *RecentList, store *arbor.Store, broadcaster *Broadcaster) {\n\terr := msg.ChatMessage.AssignID()\n\tif err != nil {\n\t\tlog.Println(\"Error creating new message\", err)\n\t}\n\trecents.Add(msg.ChatMessage)\n\tstore.Add(msg.ChatMessage)\n\tbroadcaster.Send(msg)\n}",
"func (c *Client) handleEvent(m map[string]interface{}) {\n\tt := m[\"update-type\"].(string)\n\n\tswitch t {\n\tcase \"Heartbeat\":\n\n\t\tbreak\n\tcase \"SceneItemTransformChanged\":\n\n\t\tbreak\n\tcase \"MediaRestarted\":\n\n\t\tbreak\n\tcase \"MediaStarted\":\n\n\t\tbreak\n\tcase \"SceneItemVisibilityChanged\":\n\n\t\tbreak\n\tcase \"MediaEnded\":\n\n\t\tbreak\n\tcase \"SourceDestroyed\":\n\n\t\tbreak\n\tcase \"SceneItemSelected\":\n\n\t\tbreak\n\tcase \"SceneItemRemoved\":\n\n\t\tbreak\n\tcase \"SceneItemDeselected\":\n\n\t\tbreak\n\tdefault:\n\t\tglobal.LOG.Info(\"data\", zap.Any(\"m\", m))\n\t\tbreak\n\t}\n}",
"func newEventHandler(fn interface{}, configurators []EventConfigurator) *eventHandler {\n\te := &eventHandler{\n\t\tcallBack: reflect.ValueOf(fn),\n\t\tMutex: sync.Mutex{},\n\t}\n\t// config\n\tfor i := range configurators {\n\t\tconfigurators[i](e)\n\t}\n\treturn e\n}",
"func ScreenChangeNotifyEventNew(buf []byte) xgb.Event {\n\tv := ScreenChangeNotifyEvent{}\n\tb := 1 // don't read event number\n\n\tv.Rotation = buf[b]\n\tb += 1\n\n\tv.Sequence = xgb.Get16(buf[b:])\n\tb += 2\n\n\tv.Timestamp = xproto.Timestamp(xgb.Get32(buf[b:]))\n\tb += 4\n\n\tv.ConfigTimestamp = xproto.Timestamp(xgb.Get32(buf[b:]))\n\tb += 4\n\n\tv.Root = xproto.Window(xgb.Get32(buf[b:]))\n\tb += 4\n\n\tv.RequestWindow = xproto.Window(xgb.Get32(buf[b:]))\n\tb += 4\n\n\tv.SizeID = xgb.Get16(buf[b:])\n\tb += 2\n\n\tv.SubpixelOrder = xgb.Get16(buf[b:])\n\tb += 2\n\n\tv.Width = xgb.Get16(buf[b:])\n\tb += 2\n\n\tv.Height = xgb.Get16(buf[b:])\n\tb += 2\n\n\tv.Mwidth = xgb.Get16(buf[b:])\n\tb += 2\n\n\tv.Mheight = xgb.Get16(buf[b:])\n\tb += 2\n\n\treturn v\n}",
"func (h VoiceStateUpdateHandler) New() interface{} {\n\treturn &api.VoiceStateUpdateEvent{}\n}",
"func NewEvent(subject string, eventType EventType, obj interface{}) Event {\n\treturn eventImpl{\n\t\tsubject: subject,\n\t\ttime: time.Now(),\n\t\teventType: eventType,\n\t\tobject: obj,\n\t}\n}",
"func NewEventHandler(handlerType string) *EventHandler {\n\treturn &EventHandler{\n\t\tType: handlerType,\n\t\tEvents: []goevent.Event{},\n\t\tRecv: make(chan goevent.Event, 10),\n\t}\n}",
"func eventHandler(ctx context.Context, client ce.Client) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodPost {\n\t\t\thttp.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\n\t\t// TODO (@mgasch): support inbound rate limiting\n\n\t\tlog := logger.Get(ctx)\n\t\tb, err := io.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\tlog.Error(\"read body\", zap.Error(err))\n\t\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tvar event model.Payload\n\t\tif err = json.Unmarshal(b, &event); err != nil {\n\t\t\tlog.Error(\"could not decode harbor notification event\", zap.Error(err))\n\t\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tid := uuid.New().String()\n\t\tlog = log.With(zap.String(\"eventID\", id))\n\n\t\tlog.Debug(\"received request\", zap.String(\"request\", string(b)))\n\n\t\te := ce.NewEvent()\n\t\te.SetID(id)\n\t\te.SetSource(fmt.Sprintf(sourceFormat, os.Getenv(\"K_SERVICE\")))\n\t\te.SetSubject(event.Operator) // might be empty\n\n\t\t// sanity check\n\t\tif event.Type == \"\" {\n\t\t\tlog.Error(\"harbor event type must not be empty\", zap.String(\"type\", event.Type))\n\t\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tt := strings.ToLower(event.Type)\n\t\te.SetType(fmt.Sprintf(eventTypeFormat, t))\n\n\t\tts := time.Unix(event.OccurAt, 0)\n\t\te.SetTime(ts)\n\n\t\tif err = e.SetData(ce.ApplicationJSON, event); err != nil {\n\t\t\tlog.Error(\"could not set cloudevent data\", zap.Error(err))\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tctx = cectx.WithRetriesExponentialBackoff(ctx, retryDelay, retries)\n\t\tif err = client.Send(ctx, e); ce.IsUndelivered(err) || ce.IsNACK(err) {\n\t\t\tlog.Error(\"could not send cloudevent\", zap.Error(err), zap.String(\"event\", e.String()))\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Debug(\"successfully sent cloudevent\", zap.Any(\"event\", e))\n\t})\n}",
"func NewEvent(details EventDetails) (err error) {\n\tdbQuery := `\n\t\tWITH d AS (\n\t\t\tSELECT db_id\n\t\t\tFROM sqlite_databases\n\t\t\tWHERE user_id = (\n\t\t\t\t\tSELECT user_id\n\t\t\t\t\tFROM users\n\t\t\t\t\tWHERE lower(user_name) = lower($1)\n\t\t\t\t)\n\t\t\t\tAND folder = $2\n\t\t\t\tAND db_name = $3\n\t\t\t\tAND is_deleted = false\n\t\t)\n\t\tINSERT INTO events (db_id, event_type, event_data)\n\t\tVALUES ((SELECT db_id FROM d), $4, $5)`\n\t_, err = pdb.Exec(dbQuery, details.Owner, details.Folder, details.DBName, details.Type, details)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn\n}",
"func HandleEvent(data interface{}, api *slack.Client) {\n\tlogger.Log(logger.Debug, \"Event will be handled!\")\n\tswitch ev := data.(type) {\n\tcase *slack.HelloEvent:\n\t\tlogger.Log(logger.Debug, \"Hello event done!\")\n\n\tcase *slack.ConnectedEvent:\n\t\tlogger.Log(logger.Debug, fmt.Sprintf(\"Infos: %v\", ev.Info))\n\t\tlogger.Log(logger.Debug, fmt.Sprintf(\"Connection counter: %v\", ev.ConnectionCount))\n\n\tcase *slack.MessageEvent:\n\t\tgo HandleMessage(ev, api)\n\n\tcase *slack.PresenceChangeEvent:\n\t\tlogger.Log(logger.Debug, fmt.Sprintf(\"Presence Change: %v\", ev))\n\n\tcase *slack.LatencyReport:\n\t\tlogger.Log(logger.Debug, fmt.Sprintf(\"Current latency: %v\", ev.Value))\n\n\tcase *slack.RTMError:\n\t\tlogger.Log(logger.Warning, fmt.Sprintf(\"Error: %s\", ev.Error()))\n\n\tcase *slack.InvalidAuthEvent:\n\t\tlogger.Log(logger.Warning, \"Invalid credentials\")\n\t\treturn\n\n\tdefault:\n\t\tlogger.Log(logger.Debug, \"The Event is unknown!\")\n\t}\n}",
"func (fa *AuditLog) Event(ctx context.Context, ai auth.Subject, action centrald.AuditAction, oid models.ObjID, name models.ObjName, refID models.ObjIDMutable, err bool, msg string) {\n\targs := &Args{AI: ai, Action: action, ObjID: oid, Name: name, RefID: refID, Err: err, Message: msg}\n\tfa.Events = append(fa.Events, args)\n}",
"func (_m *Callbacks) EventCreated(sequence int64) {\n\t_m.Called(sequence)\n}",
"func (h *EventHandler) PushEvent(e *ListenerEvent) {\n\th.eventRecvCache.Set(e.Key(), e)\n\th.needHandle = true\n}",
"func NewEvent() *Event {\n\te := new(Event)\n\te.bubble = true\n\te.handled = false\n\treturn e\n}",
"func (s *Server) CreateEvent(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\n\tb, err := ioutil.ReadAll(r.Body)\n\tdefer r.Body.Close()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\tvar event Event\n\tif err = json.Unmarshal(b, &event); err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\teventUUID, err := uuid.NewUUID()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\teventID := eventUUID.String()\n\n\tevent.ID = eventID\n\n\terr1 := s.database.CreateEvent(ctx, &event)\n\tif httperr.HandleError(w, err, http.StatusInternalServerError) {\n\t\ts.logger.For(ctx).Error(\"request failed\", zap.Error(err1))\n\t\treturn\n\t}\n\n\tresponse := CreatePostResponse{\"success\"}\n\tjsonResponse, err := json.Marshal(response)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write(jsonResponse)\n}",
"func (c *Client) OnNewMessage(callback func(channel string, user User, message Message)) {\n\tc.onNewMessage = callback\n}",
"func New(secret string, h Func) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tb, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"reading body\")\n\t\t\tresponse.InternalServerError(w)\n\t\t\treturn\n\t\t}\n\n\t\tsignature := r.Header.Get(\"Stripe-Signature\")\n\t\te, err := webhook.ConstructEvent(b, signature, secret)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"constructing event\")\n\t\t\tresponse.InternalServerError(w)\n\t\t\treturn\n\t\t}\n\n\t\tctx := log.WithFields(log.Fields{\n\t\t\t\"event_id\": e.ID,\n\t\t\t\"event_type\": e.Type,\n\t\t})\n\n\t\tctx.Info(\"handling stripe event\")\n\t\tif err := h(&e); err != nil {\n\t\t\tctx.WithError(err).Error(\"handling stripe event\")\n\t\t\tresponse.InternalServerError(w)\n\t\t\treturn\n\t\t}\n\n\t\tctx.Info(\"handled stripe event\")\n\t\tresponse.OK(w)\n\t})\n}",
"func NewBaseEvent( e EEventType ) (event *BaseEvent, err error) {\n event = new(BaseEvent)\n\n // setting these to true will force serialisation\n event.part2JsonExtracted = true\n event.sysParamsExtracted = true\n event.execParamsExtracted = true\n event.verbose = Verbose // pick up the global flag\n\n err = event.SetEventType(e)\n return\n}",
"func (n *EventReceiver) Event(eventName string) {\n\tfmt.Fprintf(n.W, \"eventName %q\\n\", eventName)\n}",
"func IncomingEventGetHandler(ctx *gin.Context) {\n\tdatasource.StreamClient.Publish(config.Config.PubSub.EventName.NewIncomingRequest, []byte(\"new request came in\"))\n\tctx.JSON(http.StatusOK, gin.H{\"ok\": 1})\n}",
"func (e UserCreated) isEvent() {}",
"func (self *Server) RawEventToEvent(e) error {\n\n}",
"func NewEvent(_type string) *Event {\n\tev := new(Event)\n\tev.Type = _type\n\treturn ev\n}",
"func createVersionHandler(event *api.Event) error {\n\tlogdog.Infof(\"create version handler\")\n\n\topts := workerOptions.DeepCopy()\n\topts.Quota = Resource2Quota(event.Version.BuildResource, opts.Quota)\n\tworker, err := CloudController.Provision(string(event.EventID), opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = worker.Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// trigger after get an valid worker\n\ttriggerHooks(event, PostStartPhase)\n\n\t// set worker info to event\n\tevent.Worker = worker.GetWorkerInfo()\n\tSaveEventToEtcd(event)\n\tgo CheckWorkerTimeout(event)\n\n\twebhook := event.Service.Repository.Webhook\n\tif remote, err := remoteManager.FindRemote(webhook); webhook == api.GITHUB && err == nil {\n\t\tif err = remote.PostCommitStatus(&event.Service, &event.Version); err != nil {\n\t\t\tlogdog.Errorf(\"Unable to post commit status to github: %v\", err)\n\t\t}\n\t}\n\treturn nil\n}",
"func NewHandler(newEventStream NewEventStreamHandler) *Handler {\n\treturn NewHandlerBuffered(newEventStream, 0)\n}",
"func NewEventHandler(url string) EventHandler {\n\treturn EventHandler{\n\t\tclient: &http.Client{\n\t\t\tTimeout: 30 * time.Second,\n\t\t},\n\t\turl: url,\n\t}\n}",
"func derefEvent(e Event) Event {\n\tswitch e := e.(type) {\n\tcase *SwitchScenesEvent:\n\t\treturn *e\n\tcase *ScenesChangedEvent:\n\t\treturn *e\n\tcase *SceneCollectionChangedEvent:\n\t\treturn *e\n\tcase *SceneCollectionListChangedEvent:\n\t\treturn *e\n\tcase *SwitchTransitionEvent:\n\t\treturn *e\n\tcase *TransitionListChangedEvent:\n\t\treturn *e\n\tcase *TransitionDurationChangedEvent:\n\t\treturn *e\n\tcase *TransitionBeginEvent:\n\t\treturn *e\n\tcase *ProfileChangedEvent:\n\t\treturn *e\n\tcase *ProfileListChangedEvent:\n\t\treturn *e\n\tcase *StreamStartingEvent:\n\t\treturn *e\n\tcase *StreamStartedEvent:\n\t\treturn *e\n\tcase *StreamStoppingEvent:\n\t\treturn *e\n\tcase *StreamStoppedEvent:\n\t\treturn *e\n\tcase *StreamStatusEvent:\n\t\treturn *e\n\tcase *RecordingStartingEvent:\n\t\treturn *e\n\tcase *RecordingStartedEvent:\n\t\treturn *e\n\tcase *RecordingStoppingEvent:\n\t\treturn *e\n\tcase *RecordingStoppedEvent:\n\t\treturn *e\n\tcase *RecordingPausedEvent:\n\t\treturn *e\n\tcase *RecordingResumedEvent:\n\t\treturn *e\n\tcase *ReplayStartingEvent:\n\t\treturn *e\n\tcase *ReplayStartedEvent:\n\t\treturn *e\n\tcase *ReplayStoppingEvent:\n\t\treturn *e\n\tcase *ReplayStoppedEvent:\n\t\treturn *e\n\tcase *ExitingEvent:\n\t\treturn *e\n\tcase *HeartbeatEvent:\n\t\treturn *e\n\tcase *BroadcastCustomMessageEvent:\n\t\treturn *e\n\tcase *SourceCreatedEvent:\n\t\treturn *e\n\tcase *SourceDestroyedEvent:\n\t\treturn *e\n\tcase *SourceVolumeChangedEvent:\n\t\treturn *e\n\tcase *SourceMuteStateChangedEvent:\n\t\treturn *e\n\tcase *SourceAudioSyncOffsetChangedEvent:\n\t\treturn *e\n\tcase *SourceAudioMixersChangedEvent:\n\t\treturn *e\n\tcase *SourceRenamedEvent:\n\t\treturn *e\n\tcase *SourceFilterAddedEvent:\n\t\treturn *e\n\tcase *SourceFilterRemovedEvent:\n\t\treturn *e\n\tcase *SourceFilterVisibilityChangedEvent:\n\t\treturn *e\n\tcase *SourceFiltersReorderedEvent:\n\t\treturn *e\n\tcase *SourceOrderChangedEvent:\n\t\treturn *e\n\tcase *SceneItemAddedEvent:\n\t\treturn *e\n\tcase *SceneItemRemovedEvent:\n\t\treturn *e\n\tcase *SceneItemVisibilityChangedEvent:\n\t\treturn *e\n\tcase *SceneItemTransformChangedEvent:\n\t\treturn *e\n\tcase *SceneItemSelectedEvent:\n\t\treturn *e\n\tcase *SceneItemDeselectedEvent:\n\t\treturn *e\n\tcase *PreviewSceneChangedEvent:\n\t\treturn *e\n\tcase *StudioModeSwitchedEvent:\n\t\treturn *e\n\tdefault:\n\t\treturn nil\n\t}\n}",
"func ProcessEvent(ctx context.Context, event *greeter.HelloRequest) error {\n\tfmt.Printf(\"Got event with name %s\\n\", event.Name)\n\treturn nil\n}",
"func NewHandler(k Keeper) sdk.Handler {\n\treturn func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) {\n\t\tctx = ctx.WithEventManager(sdk.NewEventManager())\n\t\tswitch msg := msg.(type) {\n\t\tcase MsgCreate:\n\t\t\treturn handleMsgCreate(ctx, k, &msg)\n\t\tcase MsgDelete:\n\t\t\treturn handleMsgDelete(ctx, k, &msg)\n\t\tdefault:\n\t\t\treturn nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, \"unrecognized %s message type: %T\", types.ModuleName, msg)\n\t\t}\n\t}\n}",
"func NewEvent(timestampMs int64, message string) *Event {\n\tevent := &Event{\n\t\tInputLogEvent: &cloudwatchlogs.InputLogEvent{\n\t\t\tTimestamp: aws.Int64(timestampMs),\n\t\t\tMessage: aws.String(message)},\n\t}\n\treturn event\n}",
"func newCounterEvent(e *events.Envelope) *Event {\n\tvar m = e.GetCounterEvent()\n\tvar r = LabelSet{\n\t\t\"cf_origin\": \"firehose\",\n\t\t\"deployment\": e.GetDeployment(),\n\t\t\"event_type\": e.GetEventType().String(),\n\t\t\"job\": e.GetJob(),\n\t\t\"job_index\": e.GetIndex(),\n\t\t\"origin\": e.GetOrigin(),\n\t}\n\tmsg := fmt.Sprintf(\"%s (delta=%d, total=%d)\", m.GetName(), m.GetDelta(), m.GetTotal())\n\treturn &Event{\n\t\tLabels: r,\n\t\tMsg: msg,\n\t}\n}",
"func Event(ctx context.Context, msg string) {\n\teventInternal(ctx, false /* isErr */, true /* withTags */, msg)\n}",
"func (s *BasecluListener) EnterWhen_handler(ctx *When_handlerContext) {}",
"func NewEventHandler(region, lbID string, lbClient cloud.LoadBalance, k8sCli client.Client) *EventHandler {\n\treturn &EventHandler{\n\t\tctx: context.Background(),\n\t\tlbID: lbID,\n\t\tregion: region,\n\t\tlbClient: lbClient,\n\t\tk8sCli: k8sCli,\n\t\teventRecvCache: NewEventCache(),\n\t\teventDoingCache: NewEventCache(),\n\t}\n}",
"func (rp *Ringpop) HandleEvent(event interface{}) {\n\trp.emit(event)\n\n\tswitch event := event.(type) {\n\tcase swim.MemberlistChangesReceivedEvent:\n\t\tfor _, change := range event.Changes {\n\t\t\tstatus := change.Status\n\t\t\tif len(status) == 0 {\n\t\t\t\tstatus = \"unknown\"\n\t\t\t}\n\t\t\trp.statter.IncCounter(rp.getStatKey(\"membership-update.\"+status), nil, 1)\n\t\t}\n\n\tcase swim.MemberlistChangesAppliedEvent:\n\t\trp.statter.UpdateGauge(rp.getStatKey(\"changes.apply\"), nil, int64(len(event.Changes)))\n\t\trp.handleChanges(event.Changes)\n\n\tcase swim.FullSyncEvent:\n\t\trp.statter.IncCounter(rp.getStatKey(\"full-sync\"), nil, 1)\n\n\tcase swim.MaxPAdjustedEvent:\n\t\trp.statter.UpdateGauge(rp.getStatKey(\"max-p\"), nil, int64(event.NewPCount))\n\n\tcase swim.JoinReceiveEvent:\n\t\trp.statter.IncCounter(rp.getStatKey(\"join.recv\"), nil, 1)\n\n\tcase swim.JoinCompleteEvent:\n\t\trp.statter.IncCounter(rp.getStatKey(\"join.complete\"), nil, 1)\n\t\trp.statter.RecordTimer(rp.getStatKey(\"join\"), nil, event.Duration)\n\n\tcase swim.PingSendEvent:\n\t\trp.statter.IncCounter(rp.getStatKey(\"ping.send\"), nil, 1)\n\n\tcase swim.PingSendCompleteEvent:\n\t\trp.statter.RecordTimer(rp.getStatKey(\"ping\"), nil, event.Duration)\n\n\tcase swim.PingReceiveEvent:\n\t\trp.statter.IncCounter(rp.getStatKey(\"ping.recv\"), nil, 1)\n\n\tcase swim.PingRequestsSendEvent:\n\t\trp.statter.IncCounter(rp.getStatKey(\"ping-req.send\"), nil, int64(len(event.Peers)))\n\n\tcase swim.PingRequestsSendCompleteEvent:\n\t\trp.statter.RecordTimer(rp.getStatKey(\"ping-req\"), nil, event.Duration)\n\n\tcase swim.PingRequestReceiveEvent:\n\t\trp.statter.IncCounter(rp.getStatKey(\"ping-req.recv\"), nil, 1)\n\n\tcase swim.PingRequestPingEvent:\n\t\trp.statter.RecordTimer(rp.getStatKey(\"ping-req.ping\"), nil, event.Duration)\n\n\tcase swim.ProtocolDelayComputeEvent:\n\t\trp.statter.RecordTimer(rp.getStatKey(\"protocol.delay\"), nil, event.Duration)\n\n\tcase swim.ProtocolFrequencyEvent:\n\t\trp.statter.RecordTimer(rp.getStatKey(\"protocol.frequency\"), nil, event.Duration)\n\n\tcase swim.ChecksumComputeEvent:\n\t\trp.statter.RecordTimer(rp.getStatKey(\"compute-checksum\"), nil, event.Duration)\n\t\trp.statter.UpdateGauge(rp.getStatKey(\"checksum\"), nil, int64(event.Checksum))\n\t}\n}"
] | [
"0.64196146",
"0.62445056",
"0.6214184",
"0.60019845",
"0.6000841",
"0.596388",
"0.589543",
"0.5895286",
"0.586258",
"0.58605295",
"0.5860284",
"0.58493006",
"0.58306175",
"0.582499",
"0.5819328",
"0.5810497",
"0.5798203",
"0.5733531",
"0.5713068",
"0.5712544",
"0.5675144",
"0.56638557",
"0.5643813",
"0.5622251",
"0.560559",
"0.56050146",
"0.55886585",
"0.5588451",
"0.5584511",
"0.5580419",
"0.5573442",
"0.5555388",
"0.5554369",
"0.5552365",
"0.55493116",
"0.55319077",
"0.55149317",
"0.55093384",
"0.55073816",
"0.55037725",
"0.54855734",
"0.54850376",
"0.54723245",
"0.5467463",
"0.5462977",
"0.5457268",
"0.54513454",
"0.544723",
"0.54418993",
"0.5433069",
"0.54283476",
"0.5426868",
"0.54196227",
"0.54156405",
"0.54036576",
"0.5399365",
"0.5394097",
"0.5378959",
"0.53691787",
"0.53531426",
"0.53478736",
"0.5337025",
"0.533636",
"0.53291875",
"0.53291875",
"0.53231066",
"0.5317973",
"0.5317787",
"0.5311867",
"0.5306816",
"0.5292611",
"0.5283704",
"0.52789533",
"0.52763015",
"0.5258869",
"0.5256892",
"0.5253649",
"0.52469116",
"0.52401966",
"0.5233896",
"0.52290714",
"0.52289253",
"0.5226877",
"0.522392",
"0.5221746",
"0.52206624",
"0.52160156",
"0.52155554",
"0.52042943",
"0.51863205",
"0.5176889",
"0.5170217",
"0.5169313",
"0.51687783",
"0.51652294",
"0.51636934",
"0.51631516",
"0.5161991",
"0.5156809",
"0.5155605"
] | 0.548507 | 41 |
Run starts listening and communicating with the network. | func (n *NetImpl) Run(shutdownSignal <-chan struct{}) {
go n.connectOutboundLoop()
go n.connectInboundLoop()
<-shutdownSignal
n.log.Info("Closing all connections with peers...")
n.closeAll()
n.log.Info("Closing all connections with peers... done")
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func Run() {\n\tgo listen()\n}",
"func (srv *Server) Run() {\n\tsrv.StartListen()\n}",
"func Run(ctx context.Context, network, address string) error {\n\tlistener, err := net.Listen(network, address)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err := listener.Close(); err != nil {\n\t\t\tlog.Fatalf(\"Failed to close %s %s: %v\", network, address, err)\n\t\t}\n\t}()\n\n\tserver := grpc.NewServer()\n\tpb.RegisterEchoServiceServer(server, newEchoServer())\n\n\tgo func() {\n\t\tdefer server.GracefulStop()\n\t\t<-ctx.Done()\n\t}()\n\treturn server.Serve(listener)\n}",
"func (s *Server) Run() {\n\tvar l net.Listener\n\tvar err error\n\thost := s.ip+\":\"+s.port\n\tl, err = net.Listen(\"tcp\", host)\n\tif err != nil {\n\t\tlog.Fatal(\"Listen: %v\", err)\n\t}\n\tif s.connLimit > 0 {\n\t\tl = netutil.LimitListener(l, s.connLimit)\n\t}\n\n\terr = http.Serve(l, s)\n\tif err != nil {\n\t\tlog.Fatal(\"http.listenAndServe failed: %s\", err.Error())\n\t}\n\ts.l = l\n\treturn\n}",
"func (g *GRPC) Run() error {\n\tvar err error\n\tg.listener, err = net.Listen(connProtocol, fmt.Sprintf(\":%s\", g.port))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo g.serve()\n\treturn nil\n}",
"func (sl *Listener) Run(blocking bool) {\n\tl, err := net.Listen(\"tcp\", sl.addr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tsl.lis = l\n\tlog.Printf(\"Listening at %s\", sl.Addr())\n\n\tif !blocking {\n\t\tgo sl.acceptConns()\n\t\treturn\n\t}\n\n\tsl.acceptConns()\n}",
"func (s *Server) Run(addr string) (err error) {\n\ts.listener, err = net.Listen(network, addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.serve()\n}",
"func (c *Client) Run() error {\n\tc.generateClientID()\n\n\tlistener, err := net.Listen(\"tcp\", c.ListenAddr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to listen on %s: %s\", c.ListenAddr, err)\n\t}\n\n\tfmt.Println(\"Listening for incoming SOCKS connection...\")\n\t// accept local connections and tunnel them\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"Accept Err:\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tfmt.Println(\"new SOCKS conn\", conn.RemoteAddr().String())\n\n\t\tif !c.connected.IsSet() {\n\t\t\terr = c.connect()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Failed to connect to tunnel host:\", err)\n\t\t\t\tconn.Close()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// start watcher which closes when canceled\n\t\t\tgo c.watchCancel()\n\n\t\t\tc.connected.Set(true)\n\t\t}\n\n\t\tgo c.tunnelConn(conn)\n\t}\n}",
"func (s *Server) Run() {\n\ts.Config.set()\n\tfor {\n\t\tconn, err := s.Listener.Accept()\n\t\tif err != nil {\n\t\t\ts.Config.ErrorLog(\"fail to accept new connection: %s\", err)\n\t\t}\n\t\tgo s.handleConn(conn)\n\t}\n}",
"func (s *Server) Run() {\n\ts.connect()\n\tnewClientListener := make(chan *Client)\n\tbufListener := make(chan *Message)\n\tgo s.newClientListener(newClientListener)\n\tfor {\n\t\tselect {\n\t\tcase client := <-newClientListener:\n\t\t\tclient.server = s\n\t\t\ts.clients = append(s.clients, client)\n\t\t\tgo client.Listen(bufListener)\n\t\t\tlog.Println(\"Client connected, \" + strconv.Itoa(len(s.clients)) + \" active clients\")\n\t\tcase message := <-bufListener:\n\t\t\ts.messages = append(s.messages, message)\n\t\tdefault:\n\t\t\ts.timing()\n\t\t\ts.processMessages()\n\t\t}\n\t}\n}",
"func (s *server) Run(ctx context.Context) {\n\tif s.banner {\n\t\tfmt.Printf(\"%s\\n\\n\", config.Banner)\n\t}\n\n\tet, err := NewEchoTCP(s.address, s.verbose)\n\tif err != nil {\n\t\tlog.Fatal(err) // exit if creating EchoTCP is failed.\n\t}\n\tdefer et.listener.Close()\n\n\tfmt.Printf(\"server is started at %s\\n\", s.address)\n\tet.Run(ctx)\n}",
"func (s *Server) Run() error {\n\ttcpAddr, err := net.ResolveTCPAddr(\"tcp\", s.conf.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar listener net.Listener\n\tlistener, err = net.ListenTCP(\"tcp\", tcpAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif s.conf.TLSConfig != nil {\n\t\tlistener = tls.NewListener(listener, s.conf.TLSConfig)\n\t}\n\terr = s.Serve(listener)\n\treturn err\n}",
"func (s *Server) Run(port string) (err error) {\n\tlis, err := net.Listen(\"tcp\", port)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrv := grpc.NewServer()\n\tproto.RegisterNeuroServer(srv, s)\n\tfmt.Println(\"running\")\n\terr = srv.Serve(lis) // this will block\n\treturn err\n}",
"func (s *Server) Run(addr string) error {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\tlogInfo(\"%v Running failed: %v\", s.Handler.LogTag(), err)\n\t\treturn err\n\t}\n\ts.Listener = ln\n\ts.chStop = make(chan error)\n\tlogInfo(\"%v Running On: \\\"%v\\\"\", s.Handler.LogTag(), ln.Addr())\n\t// defer logInfo(\"%v Stopped\", s.Handler.LogTag())\n\treturn s.runLoop()\n}",
"func Run() error {\n\tgo StartServer()\n\n\tlis, err := net.Listen(\"tcp\", \":50051\")\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\n\ts := grpc.NewServer()\n\n\tklessapi.RegisterKlessAPIServer(s, &apiserver.APIServer{})\n\tif err := s.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %v\", err)\n\t}\n\treturn nil\n}",
"func Run() error {\n\tvar err error\n\n\ts := NewServer()\n\tport := \":1729\"\n\tfmt.Printf(\"Listening on %s...\\n\", port)\n\thttp.ListenAndServe(port, s)\n\n\treturn err\n}",
"func Run(ctx context.Context, port string) struct{} {\n\n\t//The server to get up\n\tli, err := net.Listen(\"tcp\", port)\n\tif err != nil {\n\t\tlog.Fatalf(\"Server stopped: %v\", err)\n\t}\n\n\t//Passing the server to grpc\n\ts := &Server{}\n\tgrpcServer := grpc.NewServer()\n\tsubscribe.RegisterSubscribeServiceServer(grpcServer, s)\n\tgrpcServer.Serve(li)\n\n\tfmt.Printf(\"Server up on port: %v\\n\", err)\n\treturn <-ctx.Done()\n}",
"func Run(ctx context.Context, network string, cfg *Config) error {\n\tlog.Infof(\"starting server on %s %s\", network, cfg.Address)\n\n\tlis, err := net.Listen(network, cfg.Address)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err := lis.Close(); err != nil {\n\t\t\tlog.Errorf(\"Failed to close %s %s: %v\", network, cfg.Address, err)\n\t\t}\n\t}()\n\n\ts := grpc.NewServer()\n\tserver, err := newOpenSavesServer(ctx, cfg.Cloud, cfg.Project, cfg.Bucket, cfg.Cache)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpb.RegisterOpenSavesServer(s, server)\n\treflection.Register(s)\n\n\treturn s.Serve(lis)\n}",
"func (s *Server) Run() error {\n\tpath := fmt.Sprintf(\"%s:%d\", s.host, s.port)\n\tlog.Printf(\"Starting %s server on: %s\", s.protocol, path)\n\n\tlistener, err := net.Listen(s.protocol, path)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// I usually use helper function, but don't want to call it only once.\n\tdefer func() {\n\t\tif err := listener.Close(); err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}() // dont want to loose possible error\n\n\t// Pass context for the graceful shutdown.\n\t// It's not relevant in this lab (and it could be done far better),\n\t// but it's the best practice in go to use ctx\n\ts.handleConnections(s.handleCancel(), listener)\n\n\treturn nil\n}",
"func Run() error {\n\tgo server.ListenAndServe()\n\t// TODO: Improve error handling\n\treturn nil\n}",
"func (s *Server) Run() error {\n\tlogging.Server(fmt.Sprintf(\"Starting %s Listener at %s:%d\", s.Protocol, s.Interface, s.Port))\n\n\ttime.Sleep(45 * time.Millisecond) // Sleep to allow the shell to start up\n\tif s.psk == \"reaper\" {\n\t\tfmt.Println()\n\t\tmessage(\"warn\", \"Listener was started using \\\"reaper\\\" as the Pre-Shared Key (PSK) allowing anyone\"+\n\t\t\t\" decrypt message traffic.\")\n\t\tmessage(\"note\", \"Consider changing the PSK by using the -psk command line flag.\")\n\t}\n\tmessage(\"note\", fmt.Sprintf(\"Starting %s listener on %s:%d\", s.Protocol, s.Interface, s.Port))\n\n\tif s.Protocol == \"h2\" {\n\t\tserver := s.Server.(*http.Server)\n\n\t\tdefer func() {\n\t\t\terr := server.Close()\n\t\t\tif err != nil {\n\t\t\t\tm := fmt.Sprintf(\"There was an error starting the %s server:\\r\\n%s\", s.Protocol, err.Error())\n\t\t\t\tlogging.Server(m)\n\t\t\t\tmessage(\"warn\", m)\n\t\t\t\treturn\n\t\t\t}\n\t\t}()\n\t\tgo logging.Server(server.ListenAndServeTLS(s.Certificate, s.Key).Error())\n\t\treturn nil\n\t} else if s.Protocol == \"hq\" {\n\t\tserver := s.Server.(*h2quic.Server)\n\n\t\tdefer func() {\n\t\t\terr := server.Close()\n\t\t\tif err != nil {\n\t\t\t\tm := fmt.Sprintf(\"There was an error starting the hq server:\\r\\n%s\", err.Error())\n\t\t\t\tlogging.Server(m)\n\t\t\t\tmessage(\"warn\", m)\n\t\t\t\treturn\n\t\t\t}\n\t\t}()\n\t\tgo logging.Server(server.ListenAndServeTLS(s.Certificate, s.Key).Error())\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"%s is an invalid server protocol\", s.Protocol)\n}",
"func (s *Server) Run() (chan *Message, error) {\n\ts.logger.Notice(\"Starting %v server...\", s.name)\n\ts.commsChan = make(chan *Message)\n\ts.killChan = make(chan bool)\n\tgo s.listenAndServe()\n\treturn s.commsChan, nil\n}",
"func (serv *BusServer) Run() {\n\tfor {\n\t\tconn, err := serv.listener.Accept()\n\n\t\t// error accepting; ignore this.\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// begin the connection goroutine.\n\t\tgo serv.handleConnection(conn)\n\n\t}\n}",
"func (app *App) Run() error {\n\tapp.Go(app.ServeOSC)\n\tapp.Go(app.run)\n\n\tapp.debugf(\"initialized connection laddr=%s raddr=%s\\n\", app.LocalAddr(), app.RemoteAddr())\n\n\treturn app.Wait()\n}",
"func (s *Service) Run() {\n\ts.acceptConnection()\n}",
"func (s *SamFSServer) Run() error {\n\tlis, err := net.Listen(\"tcp\", s.port)\n\tif err != nil {\n\t\tglog.Fatalf(\"falied to listen on port :: %s(err=%s)\", s.port, err.Error())\n\t\treturn err\n\t}\n\n\trand.Seed(time.Now().UnixNano())\n\ts.sessionID = rand.Int63()\n\tglog.Infof(\"starting new server with sessionID %d\", s.sessionID)\n\n\tgs := grpc.NewServer()\n\tpb.RegisterNFSServer(gs, s)\n\ts.grpcServer = gs\n\treturn gs.Serve(lis)\n}",
"func (s *Server) Run() error {\n\tbg := s.logger.Bg()\n\tlis, err := net.Listen(\"tcp\", s.hostPort)\n\n\tif err != nil {\n\t\tbg.Fatal(\"Unable to start server\", zap.Error(err))\n\t\treturn err\n\t}\n\n\tbg.Info(\"Starting\", zap.String(\"address\", \"tcp://\"+s.hostPort))\n\treturn s.Gs.Serve(lis)\n}",
"func (m *Server) Run() error {\n\tvar err error\n\n\tm.server, err = transport.Launch(m.url)\n\tif err != nil {\n\t\tklog.Errorf(\"Launch transport failed %v\", err)\n\t\treturn err\n\t}\n\n\tm.backend = broker.NewMemoryBackend()\n\tm.backend.SessionQueueSize = m.sessionQueueSize\n\n\tm.backend.Logger = func(event broker.LogEvent, client *broker.Client, pkt packet.Generic, msg *packet.Message, err error) {\n\t\tif event == broker.MessagePublished {\n\t\t\tif len(m.tree.Match(msg.Topic)) > 0 {\n\t\t\t\tm.onSubscribe(msg)\n\t\t\t}\n\t\t}\n\t}\n\n\tengine := broker.NewEngine(m.backend)\n\tengine.Accept(m.server)\n\n\treturn nil\n}",
"func (s *Server) Run(address string) error {\n\treturn s.routes.Listen(address)\n}",
"func (r *serverOneDotOne) Run() {\n\tr.state = RstateRunning\n\n\t// event handling is a NOP in this model\n\trxcallback := func(ev EventInterface) int {\n\t\tassert(r == ev.GetTarget())\n\t\tlog(LogVV, \"proc-ed\", ev.String())\n\t\treturn 0\n\t}\n\n\tgo func() {\n\t\tfor r.state == RstateRunning {\n\t\t\tr.receiveEnqueue()\n\t\t\ttime.Sleep(time.Microsecond)\n\t\t\tr.processPendingEvents(rxcallback)\n\t\t}\n\t}()\n}",
"func (p *Input) Run() {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tif !p.started {\n\t\tp.log.Info(\"Starting TCP input\")\n\t\terr := p.server.Start()\n\t\tif err != nil {\n\t\t\tp.log.Errorw(\"Error starting the TCP server\", \"error\", err)\n\t\t}\n\t\tp.started = true\n\t}\n}",
"func RunServer(model *Model) {\n\tln, err := net.Listen(\"tcp\", \":0\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer ln.Close()\n\n\tipAddress := GetOutboundIP()\n\t_, port, _ := net.SplitHostPort(ln.Addr().String())\n\tipAndPort := ipAddress + \":\" + port\n\n\tPrintStatus(\"Listening for connections on IP:port \" + ipAndPort)\n\t// register my own address in the address book\n\tmodel.RegisterMyAddress(ipAndPort)\n\t// connect to neighborhood\n\tConnectToNeighborhood(model)\n\t// broadcast presence\n\tgo model.BroadCastJson(MakePresent(ipAndPort))\n\n\t// listen\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tPrintStatus(\"Connection failed -> \" + err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tgo OnNewConnection(conn, model)\n\t}\n}",
"func (h *Handler) Run() {\n\tlog.Printf(\"Listening on %s\", h.Cfg.Server.Address)\n\tserver := &http.Server{\n\t\tHandler: getRouter(),\n\t\tAddr: h.Cfg.Server.Address,\n\t}\n\th.listenErrCh <- server.ListenAndServe()\n}",
"func (h *Server) Run() {\n\n\th.g.StartServer()\n}",
"func (s *Server) Run() {\n\tfor {\n\t\tselect {\n\t\tcase msg := <-s.broadcast:\n\t\t\tfor conn, m := range s.clients {\n\t\t\t\tm.Lock()\n\t\t\t\tconn.WriteMessage(websocket.TextMessage, msg)\n\t\t\t\tm.Unlock()\n\t\t\t}\n\t\tcase conn := <-s.add:\n\t\t\ts.clients[conn] = new(sync.Mutex)\n\t\t\tgo s.listen(conn)\n\t\tcase conn := <-s.del:\n\t\t\tif _, ok := s.clients[conn]; ok {\n\t\t\t\tdelete(s.clients, conn)\n\t\t\t}\n\t\t}\n\t}\n}",
"func (s *Server) Run() <-chan error {\n\tvar chErr chan error\n\tlog.Infoln(fmt.Sprintf(\"gRPC server has started at port %d\", s.port))\n\tgo func() {\n\t\tif err := s.server.Serve(s.listener); err != nil {\n\t\t\tchErr <- err\n\t\t}\n\t}()\n\treturn chErr\n}",
"func (t *Server) Run() {\n\tvar wg sync.WaitGroup\n\twg.Add(len(t.Ports))\n\n\tfor _, port := range t.Ports {\n\t\tgo func(port string, wg *sync.WaitGroup, rpt report.Reporter) {\n\t\t\tfmt.Printf(\"Listening on tcp port: %v\\n\", port)\n\t\t\tlisten, err := net.Listen(\"tcp\", \":\"+port)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\twg.Done()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor {\n\t\t\t\tconn, err := listen.Accept()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogrus.Fatalf(\"[tcp.go] listen.Accept error: %v\", err)\n\n\t\t\t\t\t// handle error\n\t\t\t\t}\n\t\t\t\tgo handleConnection(conn, rpt)\n\t\t\t}\n\t\t}(port, &wg, t.rpt)\n\t}\n\twg.Wait()\n\tlogrus.Println(\"TCP Server Stopped\")\n}",
"func (client *AMIClient) Run() {\n\tgo func() {\n\t\tfor {\n\t\t\tdata, err := readMessage(client.bufReader)\n\t\t\tif err != nil {\n\t\t\t\tswitch err {\n\t\t\t\tcase syscall.ECONNABORTED:\n\t\t\t\t\tfallthrough\n\t\t\t\tcase syscall.ECONNRESET:\n\t\t\t\t\tfallthrough\n\t\t\t\tcase syscall.ECONNREFUSED:\n\t\t\t\t\tfallthrough\n\t\t\t\tcase io.EOF:\n\t\t\t\t\tclient.NetError <- err\n\t\t\t\t\t<-client.waitNewConnection\n\t\t\t\tdefault:\n\t\t\t\t\tclient.Error <- err\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ev, err := newEvent(data); err != nil {\n\t\t\t\tif err != errNotEvent {\n\t\t\t\t\tclient.Error <- err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tclient.Events <- ev\n\t\t\t}\n\n\t\t\tif response, err := newResponse(data); err == nil {\n\t\t\t\tclient.notifyResponse(response)\n\t\t\t}\n\n\t\t}\n\t}()\n}",
"func (s *grpcServer) Run(ctx context.Context, ready func()) error {\n\tlogger := log.WithContext(ctx)\n\ts.server.Init(ctx, nil)\n\tlistener, err := net.Listen(\"tcp\", s.cfg.Address)\n\tif err != nil {\n\t\tlogger.WithError(err).WithField(\"address\", s.cfg.Address).Error(\"unable to listen tcp address\")\n\t\treturn err\n\t}\n\n\tlogger.Info(\"starting of grpc server...\")\n\ts.server.Init(ctx, nil)\n\tmaster.RegisterMasterServer(s.server.server, s.server)\n\tif err := s.server.server.Serve(listener); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func Run(p uint, s HandlerSpawner) {\n\t//Start listening for connections\n\tl, e := net.Listen(\"tcp\", \":\"+strconv.Itoa(int(p)))\n\tif e != nil {\n\t\tutil.Log(fmt.Errorf(\"error %q listening on port %d\", e, p), LOG_SERVER)\n\t\treturn\n\t}\n\tdefer l.Close()\n\tfor {\n\t\tif c, e := l.Accept(); e != nil {\n\t\t\tutil.Log(fmt.Errorf(\"error %q accepting connection\", e), LOG_SERVER)\n\t\t} else {\n\t\t\t//Spawn a handler for each new connection.\n\t\t\tgo func(cn net.Conn) {\n\t\t\t\th := s.Spawn()\n\t\t\t\th.Start(cn)\n\t\t\t}(c)\n\t\t}\n\t}\n}",
"func (s *Server) Run() {\n\tfor {\n\t\tconn, err := s.l.Accept()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Accept error: %v\\n\", err)\n\t\t} else {\n\t\t\tgo s.handlerConn(conn)\n\t\t}\n\t}\n}",
"func (c *Client) Run() (err error) {\n\t// boot\n\tif err = c.boot(); err != nil {\n\t\treturn\n\t}\n\n\t// read loop\n\tgo c.tunReadLoop()\n\t// write loop\n\tgo c.connReadLoop()\n\n\t// wait both loop done\n\t<-c.done\n\t<-c.done\n\n\treturn\n}",
"func (c *XDSClient) Run(ctx context.Context) error {\n\terr := c.run(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.handleRecv()\n}",
"func (s *Socket) Run() {\n\tfor {\n\t\tconn, err := s.listener.AcceptUnix()\n\t\tif err != nil {\n\t\t\ts.Logger.Printf(\"cannot accept: %s\\n\", err.Error())\n\t\t\tcontinue\n\t\t}\n\n\t\tgo s.Handler(conn)\n\t}\n}",
"func (s *Server) Run() {\n\tgo func() {\n\t\t// start serving\n\t\tif err := s.httpServer.ListenAndServe(); err != nil {\n\t\t\tlog.Errora(err)\n\t\t}\n\t}()\n}",
"func (n *Notary) Run() {\n\tn.Config.Log.Info(\"starting notary service\")\n\tn.Config.Chain.SubscribeForBlocks(n.blocksCh)\n\tn.mp.SubscribeForTransactions(n.reqCh)\n\tgo n.newTxCallbackLoop()\n\tfor {\n\t\tselect {\n\t\tcase <-n.stopCh:\n\t\t\tn.mp.UnsubscribeFromTransactions(n.reqCh)\n\t\t\tn.Config.Chain.UnsubscribeFromBlocks(n.blocksCh)\n\t\t\treturn\n\t\tcase event := <-n.reqCh:\n\t\t\tif req, ok := event.Data.(*payload.P2PNotaryRequest); ok {\n\t\t\t\tswitch event.Type {\n\t\t\t\tcase mempoolevent.TransactionAdded:\n\t\t\t\t\tn.OnNewRequest(req)\n\t\t\t\tcase mempoolevent.TransactionRemoved:\n\t\t\t\t\tn.OnRequestRemoval(req)\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-n.blocksCh:\n\t\t\t// new block was added, need to check for valid fallbacks\n\t\t\tn.PostPersist()\n\t\t}\n\t}\n}",
"func (ds *DiscoveryService) Run() {\n\tglog.Infof(\"Starting discovery service at %v\", ds.server.Addr)\n\tif err := ds.server.ListenAndServe(); err != nil {\n\t\tglog.Warning(err)\n\t}\n}",
"func Run(httpHandlers http.Handler, httpsHandlers http.Handler, s Server) {\n\tif s.UseHTTP && s.UseHTTPS {\n\t\tgo func() {\n\t\t\tstartHTTPS(httpsHandlers, s)\n\t\t}()\n\n\t\tstartHTTP(httpHandlers, s)\n\t} else if s.UseHTTP {\n\t\tstartHTTP(httpHandlers, s)\n\t} else if s.UseHTTPS {\n\t\tstartHTTPS(httpsHandlers, s)\n\t} else {\n\t\tlog.Println(\"Config file does not specify a listener to start\")\n\t}\n}",
"func (a *App) Run() {\n\tlog := a.log\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", a.host, a.port))\n\tif err != nil {\n\t\tlog.Panic(err.Error())\n\t}\n\tlog.Infof(\"events gateway listening on %s:%d\", a.host, a.port)\n\n\tvar opts []grpc.ServerOption\n\n\totelPropagator := otelgrpc.WithPropagators(otel.GetTextMapPropagator())\n\totelTracerProvider := otelgrpc.WithTracerProvider(otel.GetTracerProvider())\n\n\topts = append(opts, grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(\n\t\ta.metricsReporterInterceptor,\n\t\totelgrpc.UnaryServerInterceptor(otelTracerProvider, otelPropagator),\n\t)))\n\topts = append(opts, grpc.KeepaliveParams(keepalive.ServerParameters{\n\t\tMaxConnectionIdle: a.config.GetDuration(\"server.maxConnectionIdle\"),\n\t\tMaxConnectionAge: a.config.GetDuration(\"server.maxConnectionAge\"),\n\t\tMaxConnectionAgeGrace: a.config.GetDuration(\"server.maxConnectionAgeGrace\"),\n\t\tTime: a.config.GetDuration(\"server.Time\"),\n\t\tTimeout: a.config.GetDuration(\"server.Timeout\"),\n\t}))\n\ta.grpcServer = grpc.NewServer(opts...)\n\n\tpb.RegisterGRPCForwarderServer(a.grpcServer, a.Server)\n\tif err := a.grpcServer.Serve(listener); err != nil {\n\t\tlog.Panic(err.Error())\n\t}\n}",
"func Run() (*Server, error) {\n\tvar s Server\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.Address = string(addr.IP) + strconv.Itoa(addr.Port)\n\t_ = sshTestConfig()\n\n\t_, err = net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgo func(s *Server) {\n\t}(&s)\n\n\treturn &s, nil\n}",
"func (n *Ncd) Run() {\n\tn._start()\n}",
"func Run(port int, maxConnections int) {\n\t// Listen to incoming connections from clients\n\taddress := fmt.Sprint(\"localhost:\", port)\n\tlistener, err := net.Listen(\"tcp\", address)\n\tif err != nil {\n\t\tlog.Fatal(err) // Fatal is equivalent to Print() followed by a call to os.Exit(1).\n\t}\n\tfmt.Printf(\"Listening on address: %s\\n\", address)\n\n\t// Accept upto maxConnection connections\n\tvar connectionCount = 0\n\tfor connectionCount <= maxConnections {\n\t\t// listener.Accept blocks until an incoming connection request is made. A net.Conn object\n\t\t// representing the connection is returned\n\t\tconnection, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tconnectionCount++\n\n\t\t// Handle all incoming connection concurrently. Without 'go', only one client\n\t\t// is processed at a time since processConnection is a blocking operation that\n\t\t// returns only when the connection is terminated\n\t\tgo processConnection(connection)\n\t}\n}",
"func (api *API) Run() {\n\tapi.srv = &http.Server{Addr: \":\" + strconv.Itoa(api.port), Handler: api.Router}\n\n\t// Run listening for messages in background\n\tgo func() {\n\t\tapi.logger.Info().Msgf(\"Start listening at %d.\", api.port)\n\t\terr := api.srv.ListenAndServe()\n\n\t\tif err != nil && err == http.ErrServerClosed {\n\t\t\tapi.logger.Info().Msg(\"API Srv shut down gracefully\")\n\t\t} else {\n\t\t\tapi.logger.Fatal().Err(err).Msg(\"Failed serving.\")\n\t\t}\n\n\t\t// send the stop message\n\t\tapi.stopChan <- struct{}{}\n\t}()\n}",
"func (grpca Adapter) Run() {\n\tvar err error\n\tlisten, err := net.Listen(\"tcp\", \":9000\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to listen on port 9000 %v\", err)\n\t}\n\n\tarithmeticServiceServer := grpca\n\tgrpcServer := grpc.NewServer()\n\tpb.RegisterArithmeticServiceServer(grpcServer, arithmeticServiceServer)\n\tif err := grpcServer.Serve(listen); err != nil {\n\t\tlog.Fatalf(\"Failed to server gRPC over port 9000 %v\", err)\n\t}\n}",
"func (i *IRC) Run() {\n\ti.wg.Add(1)\n\tgo func() {\n\t\tdefer i.wg.Done()\n\t\ti.conn.Loop()\n\t}()\n}",
"func (serv *Server) Run(addr string) (err error) {\n\tdefer func() { debugPrintError(err) }()\n\n\tdebugPrint(\"Listening and serving HTTP on %s\\n\", addr)\n\terr = http.ListenAndServe(addr, serv)\n\treturn\n}",
"func (s *Server) Run() error {\n\treturn s.server.ListenAndServe()\n}",
"func (osc *OSC) Run() {\n\tlog.Info().Msg(\"Started goroutine\")\n\tdefer log.Info().Msg(\"Exit goroutine\")\n\n\tosc.server.Handle(\"/layer/address\", func(msg *xosc.Message) {\n\t\txosc.PrintMessage(msg)\n\t})\n\tosc.server.ListenAndServe()\n}",
"func (s *Server) Run() error {\n\n\tif err := s.init(); err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"QueryNode init done ...\")\n\n\tif err := s.start(); err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"QueryNode start done ...\")\n\treturn nil\n}",
"func (p *PerceptorService) Run() {\n\t// Create Dialer\n\td := &websocket.Dialer{\n\t\tReadBufferSize: 4096,\n\t\tWriteBufferSize: 4096,\n\t}\n\n\t// Attempt to connect to WS Service\n\tfor {\n\t\tconn, _, err := d.Dial(fmt.Sprintf(\"ws://%s\", p.addr), p.headers())\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"WS Connection Failure: %s\", err)\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\tReadLoop:\n\t\tfor {\n\t\t\tt, m, e := conn.ReadMessage()\n\t\t\t// On Error close the connection and break the loop\n\t\t\tif e != nil {\n\t\t\t\tlog.Errorf(\"WS Connection Lost: %s\", e)\n\t\t\t\tconn.Close()\n\t\t\t\tbreak ReadLoop\n\t\t\t}\n\n\t\t\tif t == websocket.TextMessage {\n\t\t\t\t// Put the message on the event channel\n\t\t\t\tlog.Debugf(\"Recived Message: %s\", m)\n\t\t\t\tp.channel <- m\n\t\t\t}\n\t\t}\n\t}\n}",
"func (c *Component) Run(ctx context.Context) error {\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", c.port))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to listen: %w\", err)\n\t}\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tc.srv.GracefulStop()\n\t}()\n\n\tslog.Debug(\"gRPC component listening\", slog.Int(\"port\", c.port))\n\treturn c.srv.Serve(lis)\n}",
"func (s *Server) Run(ctx context.Context, wg *sync.WaitGroup) {\n\tif err := s.Config.Validate(); err != nil {\n\t\tlog.Panicf(\"invalid server config: %s\\n\", err)\n\t}\n\n\thandler := &http.Server{\n\t\tHandler: s.Router,\n\t\tAddr: \":\" + strconv.Itoa(s.Config.Port),\n\t}\n\n\tstartServer(ctx, handler, wg)\n}",
"func Run(wg *sync.WaitGroup, ctl chan bool) {\n\tbroker.ctl = ctl\n\tbroker.wg = wg\n\tbroker.listen()\n}",
"func (srv *Server) Run() <-chan error {\n\terrs := make(chan error)\n\n\tgo func() {\n\t\tdefer close(errs)\n\t\tif err := srv.ListenAndServe(); err != nil {\n\t\t\terrs <- err\n\t\t}\n\t}()\n\n\treturn errs\n}",
"func (s *Server) Run() error {\n\tdefer s.logger.Sync()\n\tdefer s.redis.Close()\n\n\t// Create TCP listener\n\tl, err := net.Listen(\"tcp\", s.address)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Failed creating listener on %s\", s.address)\n\t}\n\n\t// Create HTTP Server\n\ts.server = &http.Server{\n\t\tHandler: s.router,\n\t\tReadTimeout: 10 * time.Second,\n\t\tWriteTimeout: 10 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\n\t// Creating tracer\n\tvar tracer ot.Tracer\n\tvar closer io.Closer\n\ttracer, closer, err = util.InitTracer(\"order\", s.logger)\n\tif err != nil {\n\t\ts.logger.Warnw(\"unable to initialize tracer\",\n\t\t\t\"error\", err,\n\t\t)\n\t} else {\n\t\tdefer closer.Close()\n\t\tot.SetGlobalTracer(tracer)\n\t}\n\n\t// Listening\n\tgo func() {\n\t\ts.logger.Infow(\"Server listening\",\n\t\t\t\"address\", s.address,\n\t\t\t\"endpoint\", s.endpoint,\n\t\t)\n\t\ts.logger.Fatal(s.server.Serve(l))\n\t}()\n\n\t// Buffered channel to receive a single os.Signal\n\tstop := make(chan os.Signal, 1)\n\tsignal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)\n\n\t// Blocking channel until interrupt occurs\n\t<-stop\n\ts.Stop()\n\n\treturn nil\n}",
"func (ui *GUI) Run() {\n\tlog.Infof(\"GUI served on port %v.\", ui.cfg.GUIPort)\n\n\tgo func() {\n\t\tif err := ui.server.ListenAndServeTLS(ui.cfg.TLSCertFile,\n\t\t\tui.cfg.TLSKeyFile); err != nil &&\n\t\t\terr != http.ErrServerClosed {\n\t\t\tlog.Error(err)\n\t\t}\n\t}()\n}",
"func (server Server) Run() error {\n\terr := server.supervisor.SpawnClient()\n\tif err != nil {\n\t\tserver.logger.Fatalf(\"Error in starting client: %s\", err)\n\t}\n\n\tgo listenForSMS(server.upstreamChannel, server.logger)\n\tserver.logger.Info(\"Listening for SMS\")\n\tserver.logger.Info(\"Starting Webserver\")\n\n\treturn server.webserver.Server.ListenAndServe()\n}",
"func Run(port int, ch chan []byte) error {\n\tpc, err := net.ListenPacket(\"udp\", \"0.0.0.0:\"+strconv.Itoa(port))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer pc.Close()\n\n\tbuffer := make([]byte, 1024)\n\tfor {\n\t\tnumBytes, _, err := pc.ReadFrom(buffer)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Got error: %v\\n\", err)\n\t\t\treturn err\n\t\t}\n\t\tch <- buffer[:numBytes]\n\t}\n\n\treturn nil\n}",
"func Run(addr string) {\n\tsrv, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer func() {\n\t\tlog.Println(\"Server shutting down.\")\n\t\terr := srv.Close()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n\n\tclients := make(map[string]*client.Client)\n\n\tmsg := make(chan command.Commander)\n\tdefer close(msg)\n\tadd := make(chan *client.Client)\n\tdefer close(add)\n\trm := make(chan *client.Client)\n\tdefer close(rm)\n\n\tgo acceptConnections(srv, rm, add, msg)\n\n\tvar shutdown = false\n\tfor {\n\t\tselect {\n\t\tcase cmd := <-msg:\n\t\t\tif cmd.Log() {\n\t\t\t\tlog.Printf(\"%s used %s\", cmd.Player().Name(), cmd.Name())\n\t\t\t}\n\t\t\tif cmd.Name() == \"shutdown\" {\n\t\t\t\tfor _, conn := range clients {\n\t\t\t\t\tgo func(conn *client.Client) {\n\t\t\t\t\t\tconn.Send(\"Server is shutting down.\")\n\t\t\t\t\t\tconn.Quit()\n\t\t\t\t\t}(conn)\n\t\t\t\t}\n\t\t\t\tshutdown = true\n\t\t\t}\n\t\t\tgo cmd.Exec()\n\t\tcase conn := <-add:\n\t\t\tclients[conn.Name()] = conn\n\t\tcase rmConn := <-rm:\n\t\t\tlog.Printf(\"%s disconnected\", rmConn.Name())\n\t\t\tdelete(clients, rmConn.Name())\n\t\t\tif shutdown && len(clients) == 0 {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}",
"func (network Network) Start() {\n\tsock, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", network.Port))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tglobal.Log(network.Name, fmt.Sprintf(\"Listening on %s.\", sock.Addr().String()))\n\n\tconnections := make(chan net.Conn)\n\tnetwork.Clients = make(map[*Connection]int)\n\tclientCount := 0\n\n\t// Networking loop for accepting connections, handled in a separate thread\n\tgo func() {\n\t\tfor {\n\t\t\tconn, err := sock.Accept()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tconnections <- conn\n\t\t}\n\t}()\n\n\t// Main networking loop for handling connections and setting up their listen loop\n\tfor {\n\t\tselect {\n\t\tcase conn := <-connections:\n\t\t\tglobal.Log(network.Name, fmt.Sprintf(\"Client connected from %s.\", conn.RemoteAddr()))\n\t\t\t_ = conn.SetDeadline(time.Time{})\n\n\t\t\tclient := &Connection{\n\t\t\t\tconn: conn,\n\t\t\t\twriteQueue: make(chan PacketResponse),\n\t\t\t}\n\t\t\tnetwork.Clients[client] = clientCount\n\t\t\tclientCount++\n\t\t\tclient.listen(network)\n\t\t}\n\t}\n}",
"func (a *API) Run() error {\n\treturn a.e.Start(a.addr)\n}",
"func (s *Server) Run() error {\n\n\tgo func() {\n\t\tizap.Logger.Info(\"Starting http server\", zap.String(\"address\", s.srv.Addr))\n\t\terr := s.srv.ListenAndServe()\n\t\tif err != nil && err != http.ErrServerClosed {\n\t\t\ts.Stop()\n\t\t}\n\t}()\n\n\treturn nil\n}",
"func (s *server) Run() error {\n\ts.logger.Info(\"starting http server\", logger.String(\"addr\", s.server.Addr))\n\ts.server.Handler = s.gin\n\t// Open listener.\n\ttrackedListener, err := conntrack.NewTrackedListener(\"tcp\", s.addr, s.r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.server.Serve(trackedListener)\n}",
"func (vs *VoterServer) Run() error {\n\tlistener, err := net.Listen(\"tcp\", vs.bindAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tRegisterVoterQueryServer(vs.grpcServer, vs)\n\treturn vs.grpcServer.Serve(listener)\n}",
"func (transport *IRCTransport) Run() {\n\tdefer transport.cleanUp()\n\n\t// Connect to server.\n\tif err := transport.connect(); err != nil {\n\t\ttransport.log.Fatalf(\"Error creating connection: \", err)\n\t}\n\n\t// Receiver loop.\n\tgo transport.receiverLoop()\n\n\t// Semaphore clearing ticker.\n\tticker := time.NewTicker(time.Second * time.Duration(transport.antiFloodDelay))\n\tdefer ticker.Stop()\n\tgo func() {\n\t\tfor range ticker.C {\n\t\t\ttransport.resetFloodSemaphore()\n\t\t}\n\t}()\n\n\t// Main loop.\n\tfor {\n\t\tselect {\n\t\tcase msg, ok := <-transport.messages:\n\t\t\tif ok {\n\t\t\t\t// Are there any handlers registered for this IRC event?\n\t\t\t\tif handlers, exists := transport.ircEventHandlers[msg.Command]; exists {\n\t\t\t\t\tfor _, handler := range handlers {\n\t\t\t\t\t\thandler(transport, msg)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\ttransport.log.Infof(\"IRC transport exiting...\")\n}",
"func (c *Client) Run() {\n\tlog.Printf(\"Starting client [%v]\\n\", c.network.NodeID())\n\n\tsig := make(chan os.Signal)\n\tsignal.Notify(sig, os.Interrupt)\n\n\tgo c.scanInputLoop()\n\tgo c.eventLoop()\n\n\t<-sig\n\tfmt.Fprintf(os.Stderr, \"\\n\")\n\tlog.Printf(\"Received interrupt, shutting down client [%v]\\n\", c.network.NodeID())\n}",
"func (s *Server) Run(addr string) error {\n\tsvr := s.prepare(addr)\n\ts.logger.Info(\"start server\")\n\treturn svr.ListenAndServe()\n}",
"func (s *Server) Run(ctx context.Context) {\n\tlog.Trace(\"Starting Eco server\")\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\ts.listener.Close()\n\t}()\n\n\ts.ctx = ctx\n\t// Start serving.\n\tlog.Infof(\"Eco server running\")\n\tfor {\n\t\tconn, err := s.listener.Accept()\n\t\tif err != nil {\n\t\t\tvar opErr *net.OpError\n\t\t\tif errors.As(err, &opErr) && strings.Contains(opErr.Error(), \"use of closed network connection\") {\n\t\t\t\t// Probably a normal shutdown\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Errorf(\"Accept error: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tif ctx.Err() != nil {\n\t\t\treturn\n\t\t}\n\t\tgo s.handleRequest(conn)\n\t}\n}",
"func (i *IRC) Run() error {\n\t// ensure that if the socket chan was marked as closed, we clean it up\n\tselect {\n\tcase <-i.socketDoneChan:\n\tdefault:\n\t}\n\n\tif err := i.Connect(); err != nil {\n\t\tif !errors.Is(err, ErrorIRCAlreadyConnected) {\n\t\t\ti.Connected.Set(false)\n\t\t}\n\n\t\treturn err\n\t}\n\n\tpingCtx, cancel := context.WithCancel(context.Background())\n\tgo i.pingLoop(pingCtx)\n\n\tdefer func() {\n\t\t// clean up\n\t\tcancel()\n\t\ti.lastPong.Set(time.Time{})\n\t\ti.lag.Set(time.Duration(0))\n\t\t_ = i.socket.Close()\n\t\ti.Connected.Set(false)\n\t}()\n\n\tselect {\n\tcase e := <-i.RawEvents.WaitForChan(\"ERROR\"):\n\t\tif !i.StopRequested.Get() {\n\t\t\treturn fmt.Errorf(\"IRC server sent us an ERROR line: %s\", strings.Join(event2RawEvent(e).Line.Params, \" \"))\n\t\t}\n\tcase <-i.socketDoneChan:\n\t\treturn fmt.Errorf(\"IRC socket closed\")\n\t}\n\n\treturn nil\n}",
"func (s *HttpServer) Run() {\n\n\tgo s.httpServer()\n\t<-s.quitChan\n}",
"func (nd Node) Run(nodeAddr string) error {\n\tpeerAddr, err := ParseNodeAddr(nodeAddr)\n\tif err != nil {\n\t\treturn error\n\t}\n\n\tversion, err := protocol.NewVersionMsg(\n\t\tnd.Network,\n\t\tpeerAddr.IP,\n\t\tpeerAddr.Port,\n\t)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmsgSerialized, err := binary.Marshal(version)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconn, err := net.Dial(\"tcp\", nodeAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\t_, err = conn.Write(msgSerialized)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo nd.monitorPeers()\n\t//go nd.mempool.Run() // TODO: uncomment\n\n\ttmp := make([]byte, protocol.MsgHeaderLength)\n\nloop:\n\tfor {\n\t\tn, err := conn.Read(tmp)\n\t\tif err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbreak loop\n\t\t}\n\n\t\tvar msgHeader protocol.MessageHeader\n\t\tif err := utils.DeserializeWithReader(&msgHeader, bytes.NewReader(tmp[:n])); err != nil {\n\t\t\tfmt.Errorf(\"invalide header: %+v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := msgHeader.Validate(); err != nil {\n\t\t\tfmt.Errorf(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tfmt.Printf(\"received message: %s\\n\", msgHeader.Command)\n\n\t\tswitch msgHeader.CommandString() {\n\t\tcase \"version\":\n\t\t\tif err := nd.handleVersion(&msgHeader, conn); err != nil {\n\t\t\t\tfmt.Errorf(\"failed to handle 'version': %+v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase \"verack\":\n\t\t\tif err := nd.handleVerack(&msgHeader, conn); err != nil {\n\t\t\t\tfmt.Errorf(\"failed to handler 'verack': %+v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase \"ping\":\n\t\t\tif err := nd.handlePing(&msgHeader, conn); err != nil {\n\t\t\t\tfmt.Errorf(\"failed to handle 'ping': %+v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase \"pong\":\n\t\t\tif err := nd.handlePong(&msgHeader, conn); err != nil {\n\t\t\t\tfmt.Errorf(\"failed to handle 'pong': %+v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase \"inv\":\n\t\t\t//if err := no.handleInv(&msgHeader, conn); err != nil {\n\t\t\t//\tfmt.Errorf(\"failed to handle 'inv': %+v\", err)\n\t\t\t//\tcontinue\n\t\t\t//}\n\t\tcase \"tx\":\n\t\t\tif err := no.handleTx(&msgHeader, conn); err != nil {\n\t\t\t\tfmt.Printf(\"failed to handle 'tx': %s\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}",
"func (net *Network) Listen() {\n\tfor addr, vm := range net.vms {\n\t\tgo net.listenAndRun(addr, vm)\n\t}\n\n\tgo net.routePackets()\n}",
"func Run(host string, port int) error {\n\tsrv := grpc.NewServer()\n\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", host, port))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tproto.RegisterBlockchainServer(srv, &server{\n\t\tblockchain: blockchain.NewBlockchain(),\n\t})\n\n\tlog.Println(fmt.Sprintf(\"Server listening on %s:%d\", host, port))\n\n\treturn srv.Serve(lis)\n}",
"func (client *Client) Run(done chan bool, ready chan bool) {\n\tif client.Config == nil {\n\t\tlog.Fatalln(\"nil Config struct for websocket Client -> make sure valid Config is accessible to websocket Client\")\n\t}\n\n\tch := &Channel{\n\t\tConnection: client.connection(),\n\t\tEventHandler: client.EventHandler,\n\t}\n\n\tclient.Channel = ch\n\n\tif !client.DisabledReader {\n\t\tgo ch.read()\n\t}\n\n\tready <- true\n\n\tlog.Printf(\"\\nconnected to %s\\n\", client.Config.WSURL)\n\n\t<-done\n\n\tlog.Println(\"reading stopped\")\n}",
"func Run(p ProtocolHandler, tunnelID string, brokerURL string) {\n\tdata := p.self()\n\n\terr := tunnel.Accept(data.tunnel, tunnelID, brokerURL)\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"accepting tunnel failed: \")\n\t} else {\n\t\tp.receive()\n\t}\n}",
"func (g *RESTFrontend) Run(port int) {\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", port))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tg.Listener = listener\n\tg.RunWithListener(listener)\n}",
"func (c *Client) Run() {\n\tfor {\n\t\tselect {\n\t\tcase conn := <-c.register:\n\t\t\tc.connections[conn] = true\n\t\t\tgo conn.writePump()\n\t\t\tgo conn.readPump()\n\t\tcase conn := <-c.unregister:\n\t\t\tif _, ok := c.connections[conn]; ok {\n\t\t\t\tdelete(c.connections, conn)\n\t\t\t\tclose(conn.send)\n\t\t\t\tif len(c.connections) <= 0 {\n\t\t\t\t\tc.hub.unregister <- c.id\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\tcase incomingMessage := <-c.outbox:\n\t\t\tc.hub.messages <- incomingMessage\n\t\tcase outcomingMessage := <-c.inbox:\n\t\t\tfor conn := range c.connections {\n\t\t\t\tmsgBytes, err := outcomingMessage.GetData()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"invalid message data\")\n\t\t\t\t} else {\n\t\t\t\t\tconn.send <- msgBytes\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n}",
"func (server *Server) Run(addr string) {\n\tlog.Println(\"Yinyo is ready and waiting.\")\n\tlog.Fatal(http.ListenAndServe(addr, server.router))\n}",
"func (s *Server) Run() error {\n\tif s.Port == 0 {\n\t\treturn fmt.Errorf(\"server port must be set\")\n\t}\n\n\ts.uuid = uuid.New().String()\n\n\topts := []grpc.ServerOption{\n\t\tgrpc.KeepaliveParams(keepalive.ServerParameters{\n\t\t\tTimeout: 120 * time.Second,\n\t\t}),\n\t\tgrpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{\n\t\t\tPermitWithoutStream: true,\n\t\t}),\n\t\tgrpc.UnaryInterceptor(\n\t\t\totgrpc.OpenTracingServerInterceptor(s.Tracer),\n\t\t),\n\t}\n\n\tif tlsopt := tls.GetServerOpt(); tlsopt != nil {\n\t\topts = append(opts, tlsopt)\n\t}\n\n\tsrv := grpc.NewServer(opts...)\n\tpb.RegisterSearchServer(srv, s)\n\n\t// init grpc clients\n\tif err := s.initGeoClient(\"srv-geo\"); err != nil {\n\t\treturn err\n\t}\n\tif err := s.initRateClient(\"srv-rate\"); err != nil {\n\t\treturn err\n\t}\n\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", s.Port))\n\tif err != nil {\n\t\tlog.Fatal().Msgf(\"failed to listen: %v\", err)\n\t}\n\n\t// register with consul\n\t// jsonFile, err := os.Open(\"config.json\")\n\t// if err != nil {\n\t// \tfmt.Println(err)\n\t// }\n\n\t// defer jsonFile.Close()\n\n\t// byteValue, _ := ioutil.ReadAll(jsonFile)\n\n\t// var result map[string]string\n\t// json.Unmarshal([]byte(byteValue), &result)\n\n\terr = s.Registry.Register(name, s.uuid, s.IpAddr, s.Port)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed register: %v\", err)\n\t}\n\tlog.Info().Msg(\"Successfully registered in consul\")\n\n\treturn srv.Serve(lis)\n}",
"func (mod *ModuleImpl) Run() {\n\tlog.Println(\"RUN - \", mod.Name)\n\tif mod.connectToHub() {\n\t\tmod.serve()\n\t}\n}",
"func (s *Server) Run() error {\n\ts.setRoutes()\n\n\thttpUrl := \":\" + strconv.Itoa(s.Config.HttpPort)\n\thttpsUrl := \":\" + strconv.Itoa(s.Config.HttpsPort)\n\ts.newServer(httpsUrl, httpUrl)\n\n\tgo s.httpServer.ListenAndServe()\n\treturn s.httpsServer.ListenAndServeTLS(s.Config.CertFile, s.Config.KeyFile)\n}",
"func (a *API) Run() error {\n\tlog.Infof(\"Serving '%s - %s' on address %s\", a.Title, a.Version, a.server.Addr)\n\tif a.config.InsecureHTTP {\n\t\treturn a.server.ListenAndServe()\n\t}\n\treturn a.server.ListenAndServeTLS(a.config.TLSCertFile, a.config.TLSKeyFile)\n}",
"func (server *Server) Run() {\n\tserver.goroutineWG.Add(1)\n\tgo server.run()\n}",
"func (s *MaplAdapter) Run(shutdown chan error) {\n\tshutdown <- s.server.Serve(s.listener)\n}",
"func Run(app Application) error {\n\tcfg := app.Config()\n\n\tconn, err := comm.NewgRPCClient(cfg.MasterAddress)\n\tif err != nil {\n\t\treturn err\n\t}\n\tappCli := types.NewApplicationClient(conn)\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\n\tif _, err := appCli.Ping(ctx, &types.Empty{}); err != nil {\n\t\treturn err\n\t}\n\n\tstream, err := appCli.Stream(context.Background())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor {\n\t\tstream.Recv()\n\n\t}\n\n\treturn nil\n}",
"func (app *Application) Run() {\n\tapp.Setup()\n\n\tapp.App.Listen(fmt.Sprintf(\"%s:%d\", app.Config.App.Host, app.Config.App.Port))\n}",
"func (s *Server) Run(addr string) {\n\tfmt.Println(\"Listening to port 8080\")\n\tlog.Fatal(http.ListenAndServe(addr, s.Router))\n}",
"func (s *serv) Start() {\n\ts.running = true\n\n\tsem := make(chan byte)\n\n\tgo func() {\n\t\t// Start listening\n\t\ts.listen()\n\t\tsem <- 0\n\t}()\n\n\tgo func() {\n\t\tfor {\n\t\t\tp := <-s.pks\n\t\t\t// Dispatch work\n\t\t\tswitch p.(type) {\n\t\t\tcase *network.MessagePacket:\n\t\t\t\t_ = p.(*network.MessagePacket)\n\t\t\tcase *network.ConnectionPacket:\n\t\t\t\t_ = p.(*network.ConnectionPacket)\n\t\t\tdefault:\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}()\n\n\t<-sem\n}",
"func (s *Server) Run() {\n\tfor _, hostRouter := range s.hostRouters {\n\t\ts.log.router.Info(\"Initializing router for address: %v\", hostRouter.addr)\n\t\thttp.ListenAndServe(hostRouter.addr, hostRouter)\n\t}\n}",
"func (s *Stock) Run(port int) error {\n\tsrv := grpc.NewServer(\n\t\tgrpc.UnaryInterceptor(\n\t\t\totgrpc.OpenTracingServerInterceptor(s.tracer),\n\t\t),\n\t)\n\n\tstock.RegisterStockServer(srv, s)\n\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", port))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to listen: %v\", err)\n\t}\n\n\treturn srv.Serve(lis)\n}",
"func (s *Server) Run() error {\n\t// start fetcher, reporter and doc generator in goroutines\n\tgo s.fetcher.Run()\n\tgo s.reporter.Run()\n\tgo s.docGenerator.Run()\n\n\t// start webserver\n\tlistenAddress := s.listenAddress\n\tif listenAddress == \"\" {\n\t\tlistenAddress = DefaultAddress\n\t}\n\n\tr := mux.NewRouter()\n\n\t// register ping api\n\tr.HandleFunc(\"/_ping\", pingHandler).Methods(\"GET\")\n\n\t// github webhook API\n\tr.HandleFunc(\"/events\", s.gitHubEventHandler).Methods(\"POST\")\n\n\t// travisCI webhook API\n\tr.HandleFunc(\"/ci_notifications\", s.ciNotificationHandler).Methods(\"POST\")\n\n\tlogrus.Infof(\"start http server on address %s\", listenAddress)\n\treturn http.ListenAndServe(listenAddress, r)\n}"
] | [
"0.8035995",
"0.7458488",
"0.740233",
"0.7321169",
"0.7313291",
"0.7302446",
"0.7264816",
"0.7233495",
"0.7167856",
"0.71663594",
"0.71529305",
"0.7130983",
"0.70620316",
"0.70493823",
"0.69689125",
"0.6966561",
"0.6934849",
"0.6929281",
"0.6922419",
"0.69180614",
"0.6911324",
"0.6905015",
"0.68926716",
"0.6888779",
"0.6847582",
"0.68377435",
"0.683735",
"0.67874175",
"0.6783839",
"0.6780581",
"0.6775947",
"0.67719924",
"0.6756353",
"0.67560863",
"0.6735783",
"0.67355186",
"0.67254025",
"0.67235243",
"0.67226833",
"0.6702668",
"0.6697702",
"0.668344",
"0.66720587",
"0.6671754",
"0.6660014",
"0.6648995",
"0.6641239",
"0.65809524",
"0.65800714",
"0.65702814",
"0.6558283",
"0.654898",
"0.65460795",
"0.6543609",
"0.65345436",
"0.653438",
"0.6528144",
"0.65254366",
"0.65172863",
"0.65162224",
"0.6516196",
"0.64987594",
"0.6497626",
"0.6492196",
"0.6485802",
"0.6476851",
"0.6476346",
"0.6456614",
"0.6454129",
"0.6453149",
"0.64500576",
"0.64444226",
"0.6441712",
"0.6439081",
"0.6424694",
"0.64146245",
"0.6406926",
"0.6406181",
"0.64055777",
"0.64021635",
"0.639468",
"0.6394601",
"0.63880163",
"0.638261",
"0.63615555",
"0.6354236",
"0.63509244",
"0.63472867",
"0.6338945",
"0.63371384",
"0.6335497",
"0.63346577",
"0.6325912",
"0.6324319",
"0.63225365",
"0.63224965",
"0.63183457",
"0.6314418",
"0.6312089",
"0.63016725",
"0.6301325"
] | 0.0 | -1 |
PeerByPubKey implements peering.NetworkProvider. NOTE: For now, only known nodes can be looked up by PubKey. | func (n *NetImpl) PeerByPubKey(peerPub kyber.Point) (peering.PeerSender, error) {
for i := range n.peers {
pk := n.peers[i].PubKey()
if pk != nil && pk.Equal(peerPub) {
return n.PeerByNetID(n.peers[i].NetID())
}
}
return nil, errors.New("known peer not found by pubKey")
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (c *peer) SearchByPubKey(server, pubKey string) (*api.Peer, error) {\n\t_, err := api.ParseKey(pubKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid pubkey, %v\", err)\n\t}\n\tpeerList, err := c.ListByServer(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, peer := range peerList {\n\t\tif peer.GetStatus() != api.PeerActive {\n\t\t\tcontinue\n\t\t}\n\t\tif peer.PublicKeyString() == pubKey {\n\t\t\treturn &peer, nil\n\t\t}\n\t}\n\treturn nil, nil\n}",
"func (server *OpencxServer) GetPeerFromPubkey(pubkey *koblitz.PublicKey) (peerIdx uint32, err error) {\n\n\tvar pubkey33 [33]byte\n\tcopy(pubkey33[:], pubkey.SerializeCompressed())\n\tlitAddr := lnutil.LitAdrFromPubkey(pubkey33)\n\n\t// until this is removed, this is good for our purposes\n\tif peerIdx, err = server.ExchangeNode.FindPeerIndexByAddress(litAddr); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}",
"func (nodeKey *NodeKey) PubKey() crypto.PubKey {\n\treturn nodeKey.PrivKey.PubKey()\n}",
"func searchPublicKey(p *onet.TreeNodeInstance, servID *network.ServerIdentity) kyber.Point {\n\tfor _, si := range p.Roster().List {\n\t\tif si.Equal(servID) {\n\t\t\treturn p.NodePublic(si)\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (mt *memoryTable) PubKey(addr string) (cipher.PubKey, bool) {\n\tpk, ok := mt.reverse[addr]\n\treturn pk, ok\n}",
"func (s *SshConnection) GrabPubKey() {\n\tsshConfig := &ssh.ClientConfig{\n\t\tHostKeyCallback: s.verifyHostCallback(false),\n\t}\n\t// ignore return values here. I'm using it just to trigger the\n\t// verifyHostCallback\n\tssh.Dial(\"tcp\", s.serverEndpoint.String(), sshConfig)\n}",
"func (n NodeID) Pubkey() (*ecdsa.PublicKey, error) {\n\tp := &ecdsa.PublicKey{Curve: crypto.S256(), X: new(big.Int), Y: new(big.Int)}\n\thalf := len(n) / 2\n\tp.X.SetBytes(n[:half])\n\tp.Y.SetBytes(n[half:])\n\tif !p.Curve.IsOnCurve(p.X, p.Y) {\n\t\treturn nil, errors.New(\"id is invalid secp256k1 curve point\")\n\t}\n\treturn p, nil\n}",
"func (t Trade) FindPubKey(user *User) (pubKey SCAddr, error errstack.E) {\n\ttp, err := t.FindParticipant(user)\n\tif err != nil {\n\t\treturn \"\", errstack.WrapAsInfF(err, \"Key not found\")\n\t}\n\treturn SCAddr(tp.PubKey), nil\n}",
"func (n *NetImpl) PubKey() kyber.Point {\n\treturn n.nodeKeyPair.Public\n}",
"func (p *pbft) getPubKey(nodeID string) []byte {\n\tkey, err := ioutil.ReadFile(\"Keys/\" + nodeID + \"/\" + nodeID + \"_RSA_PUB\")\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn key\n}",
"func (id NodesID) Pubkey() (*ecdsa.PublicKey, error) {\n\tp := &ecdsa.PublicKey{Curve: bgmcrypto.S256(), X: new(big.Int), Y: new(big.Int)}\n\thalf := len(id) / 2\n\tptr.X.SetBytes(id[:half])\n\tptr.Y.SetBytes(id[half:])\n\tif !ptr.Curve.IsOnCurve(ptr.X, ptr.Y) {\n\t\treturn nil, errors.New(\"id is invalid secp256k1 curve point\")\n\t}\n\treturn p, nil\n}",
"func (sc *SecretConnection) RemotePubKey() crypto.PubKey {\n\treturn sc.remPubKey\n}",
"func (_ResolverContract *ResolverContractCaller) Pubkey(opts *bind.CallOpts, node [32]byte) (struct {\n\tX [32]byte\n\tY [32]byte\n}, error) {\n\tret := new(struct {\n\t\tX [32]byte\n\t\tY [32]byte\n\t})\n\tout := ret\n\terr := _ResolverContract.contract.Call(opts, out, \"pubkey\", node)\n\treturn *ret, err\n}",
"func (c *ClientConn) RemotePK() cipher.PubKey { return c.remoteSrv }",
"func (_ResolverContract *ResolverContractCallerSession) Pubkey(node [32]byte) (struct {\n\tX [32]byte\n\tY [32]byte\n}, error) {\n\treturn _ResolverContract.Contract.Pubkey(&_ResolverContract.CallOpts, node)\n}",
"func GetUserPubKey(username string) (map[string]interface{}, error) {\n\ttargetUser, err := auth.NewUser(username, \"pass\")\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, errors.New(err.Error())\n\n\t}\n\n\tpubKey, err := targetUser.GetPublicKey()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, errors.New(\"No data found for : \" + username)\n\t}\n\n\tmarshalledPublicKey := x509.MarshalPKCS1PublicKey(pubKey)\n\n\treturn map[string]interface{}{\n\t\t\"publicKey\": marshalledPublicKey,\n\t}, nil\n\n}",
"func computePubKey(pubA, pubR [33]byte, msg []byte) ([33]byte, error) {\n\tvar returnValue [33]byte\n\n\t// Hardcode curve\n\tcurve := btcec.S256()\n\n\tA, err := btcec.ParsePubKey(pubA[:], curve)\n\tif err != nil {\n\t\treturn returnValue, err\n\t}\n\n\tR, err := btcec.ParsePubKey(pubR[:], curve)\n\tif err != nil {\n\t\treturn returnValue, err\n\t}\n\n\t// e = Hash(messageType, oraclePubQ)\n\tvar hashInput []byte\n\thashInput = append(msg, R.X.Bytes()...)\n\te := chainhash.HashB(hashInput)\n\n\tbigE := new(big.Int).SetBytes(e)\n\n\tif bigE.Cmp(curve.N) >= 0 {\n\t\treturn returnValue, fmt.Errorf(\"hash of (msg, pubR) too big\")\n\t}\n\n\t// e * B\n\tA.X, A.Y = curve.ScalarMult(A.X, A.Y, e)\n\n\tA.Y.Neg(A.Y)\n\n\tA.Y.Mod(A.Y, curve.P)\n\n\tP := new(btcec.PublicKey)\n\n\t// add to R\n\tP.X, P.Y = curve.Add(A.X, A.Y, R.X, R.Y)\n\tcopy(returnValue[:], P.SerializeCompressed())\n\treturn returnValue, nil\n}",
"func (_ResolverContract *ResolverContractSession) Pubkey(node [32]byte) (struct {\n\tX [32]byte\n\tY [32]byte\n}, error) {\n\treturn _ResolverContract.Contract.Pubkey(&_ResolverContract.CallOpts, node)\n}",
"func (gossiper *Gossiper) GetPublicKey(name string) *peersterCrypto.PublicPair {\n\tvar key *peersterCrypto.PublicPair\n\n\t// No blockChain initialised\n\tif gossiper.headBlock == nil {\n\t\treturn key\n\t}\n\n\tfound := false\n\tblockStruct := gossiper.headBlock\n\thasNext := true\n\n\tfor !found && hasNext {\n\t\tblock := blockStruct.Block\n\t\tfor _, transaction := range block.Transactions {\n\t\t\tif transaction.GetName() == name {\n\t\t\t\tfound = true\n\t\t\t\tkey = transaction.GetPublicKey()\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tblockStruct, hasNext = gossiper.blocksMap[hex.EncodeToString(block.PrevHash[:])]\n\t\t}\n\t}\n\n\treturn key\n}",
"func IDFromPubKey(pk ci.PubKey) (peer.ID, error) {\n\tb, err := pk.Bytes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thash, err := u.Hash(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn peer.ID(hash), nil\n}",
"func (a *managedAddress) ExportPubKey() string {\n\treturn hex.EncodeToString(a.pubKeyBytes())\n}",
"func (_Contract *ContractCaller) Pubkey(opts *bind.CallOpts, node [32]byte) (struct {\n\tX [32]byte\n\tY [32]byte\n}, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"pubkey\", node)\n\n\toutstruct := new(struct {\n\t\tX [32]byte\n\t\tY [32]byte\n\t})\n\n\toutstruct.X = out[0].([32]byte)\n\toutstruct.Y = out[1].([32]byte)\n\n\treturn *outstruct, err\n\n}",
"func TestFindPubKey(t *testing.T) {\n\tprivkey, err := crypto.GenerateKey()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tpubKey := privkey.Public().(*ecdsa.PublicKey)\n\tpubKeys := createPublicKeyList(3)\n\tpubKeys = append(pubKeys, pubKey)\n\tsig, err := Sign(message, pubKeys, privkey, 3)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tver := VerifySign(sig, message, pubKeys)\n\tif !ver {\n\t\tt.Error(\"Verify sign failed\")\n\t}\n\tcurve := pubKey.Curve\n\tmsgHash := sha3.Sum256(message)\n\tfor j := 0; j < len(pubKeys); j++ {\n\t\trx, ry := curve.ScalarMult(pubKeys[j].X, pubKeys[j].Y, msgHash[:])\n\t\tif sig.I.X.Cmp(rx) == 0 && sig.I.Y.Cmp(ry) == 0 {\n\t\t\tt.Errorf(\"Exploit! Found signing key: %d\\nX: %x\\nY: %x\\n\", j, rx, ry)\n\t\t}\n\t}\n}",
"func (n Node) PublicKey() p2pcrypto.PublicKey {\n\treturn n.pubKey\n}",
"func (a *managedAddress) PubKey() chainec.PublicKey {\n\treturn a.pubKey\n}",
"func (mph *MockPeerHandler) GetRemotePubKey(id peer2.ID) (libp2pcry.PubKey, error) {\n\treturn nil, nil\n}",
"func (s *SessionService) GetPubKey() (*PubKeyShare, error) {\n\tkey, e := ioutil.ReadFile(s.KeyPath + \".pub\")\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\thash, e := SSH.GetKeyHash(key)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tmnemonic, e := SSH.MakeMnemonic(key)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\n\tpk := PubKeyShare{\n\t\tKey: string(key),\n\t\tHash: base64.RawStdEncoding.EncodeToString(hash),\n\t\tMnemonic: mnemonic,\n\t}\n\treturn &pk, nil\n}",
"func (_Contract *ContractCallerSession) Pubkey(node [32]byte) (struct {\n\tX [32]byte\n\tY [32]byte\n}, error) {\n\treturn _Contract.Contract.Pubkey(&_Contract.CallOpts, node)\n}",
"func (c *MsgConnection) RemotePublicKey() p2pcrypto.PublicKey {\n\treturn c.remotePub\n}",
"func (_Contract *ContractSession) Pubkey(node [32]byte) (struct {\n\tX [32]byte\n\tY [32]byte\n}, error) {\n\treturn _Contract.Contract.Pubkey(&_Contract.CallOpts, node)\n}",
"func ReadPubKey(data []byte) (ssh.PublicKey, error) {\n\treadAuthd := func(data []byte) (ssh.PublicKey, error) {\n\t\tpub, _, _, _, err := ssh.ParseAuthorizedKey(data)\n\t\treturn pub, err\n\t}\n\n\tdecoded, err := base64.StdEncoding.DecodeString(string(data))\n\tif len(decoded) > 0 && err == nil {\n\t\tif pub, err := readAuthd(decoded); pub != nil && err == nil {\n\t\t\treturn pub, nil\n\t\t}\n\t\treturn ssh.ParsePublicKey(decoded)\n\t}\n\n\tif pub, err := readAuthd(data); pub != nil && err == nil {\n\t\treturn pub, nil\n\t}\n\treturn ssh.ParsePublicKey(data)\n}",
"func FromPubKey(b string) (*KeyPair, error) {\n\tdata, err := p2pCrypto.ConfigDecodeKey(b)\n\tif err == nil {\n\t\tv, err := p2pCrypto.UnmarshalEd25519PublicKey(data)\n\t\tif err == nil {\n\t\t\treturn &KeyPair{privKey: nil, pubKey: v}, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn nil, err\n}",
"func (c *convertCmd) userByPubKey(pubkey string) (*v1.AbridgedUser, error) {\n\turl := politeiaHost + \"/v1/users?publickey=\" + pubkey\n\tr, err := c.client.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Body.Close()\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar ur v1.UsersReply\n\terr = json.Unmarshal(body, &ur)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(ur.Users) == 0 {\n\t\treturn nil, fmt.Errorf(\"no user found for pubkey %v\", pubkey)\n\t}\n\n\treturn &ur.Users[0], nil\n}",
"func NewPubKey() *PubKey {\n\tp := new(PubKey)\n\tp.newClient()\n\tp.load()\n\treturn p\n}",
"func pubkeyFromSeckey(seckey []byte) []byte {\n\tif len(seckey) != 32 {\n\t\tlog.Panic(\"seckey length invalid\")\n\t}\n\n\tif secp.SeckeyIsValid(seckey) != 1 {\n\t\tlog.Panic(\"always ensure seckey is valid\")\n\t\treturn nil\n\t}\n\n\tvar pubkey []byte = secp.GeneratePublicKey(seckey) //always returns true\n\tif pubkey == nil {\n\t\tlog.Panic(\"ERROR: impossible, secp.BaseMultiply always returns true\")\n\t\treturn nil\n\t}\n\tif len(pubkey) != 33 {\n\t\tlog.Panic(\"ERROR: impossible, invalid pubkey length\")\n\t}\n\n\tif ret := secp.PubkeyIsValid(pubkey); ret != 1 {\n\t\tlog.Panic(\"ERROR: pubkey invald, ret=%s\", ret)\n\t\treturn nil\n\t}\n\n\tif ret := VerifyPubkey(pubkey); ret != 1 {\n\n\t\tlog.Printf(\"seckey= %s\", hex.EncodeToString(seckey))\n\t\tlog.Printf(\"pubkey= %s\", hex.EncodeToString(pubkey))\n\t\tlog.Panic(\"ERROR: pubkey verification failed, for deterministic. ret=%d\", ret)\n\t\treturn nil\n\t}\n\n\treturn pubkey\n}",
"func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) {\n\tkeyCounter++\n\tseed := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(seed, keyCounter)\n\n\tkey := ed25519.GenPrivKeyFromSecret(seed)\n\tpub := key.PubKey()\n\taddr := sdk.AccAddress(pub.Address())\n\treturn key, pub, addr\n}",
"func pubKeyAddrFromBytes(t *testing.T, pubKey []byte, params *chaincfg.Params) *btcutil.AddressPubKey {\n\tpubKeyAddr, err := btcutil.NewAddressPubKey(pubKey, params)\n\t_assert.NoError(t, err)\n\treturn pubKeyAddr\n}",
"func PublicKeyFromPvk(privateKey []byte) []byte {\n\tvar A edwards25519.ExtendedGroupElement\n\tvar hBytes [32]byte\n\tcopy(hBytes[:], privateKey)\n\tedwards25519.GeScalarMultBase(&A, &hBytes)\n\tvar publicKeyBytes [32]byte\n\tA.ToBytes(&publicKeyBytes)\n\n\treturn publicKeyBytes[:]\n}",
"func LoadPublicKeyPair(addr string) (*PublicKeyPair, error) {\n\tp := new(PublicKeyPair)\n\tp.spendKey = edwards25519.NewIdentityPoint()\n\tp.viewKey = edwards25519.NewIdentityPoint()\n\ta := base58.Decode(addr)\n\th := sha3.NewLegacyKeccak256()\n\th.Write(a[:len(a)-4])\n\ts := h.Sum(nil)\n\tif !utils.TestBytes(a[len(a)-4:], s[:4]) {\n\t\treturn nil, fmt.Errorf(\"address checksum fail\")\n\t}\n\tif _, err := p.spendKey.SetBytes(a[1:33]); err != nil {\n\t\treturn nil, err\n\t}\n\tif _, err := p.viewKey.SetBytes(a[33:65]); err != nil {\n\t\treturn nil, err\n\t}\n\treturn p, nil\n}",
"func computePubKeyResponse(pubKey cryptoproto.PublicKey, err *privvalproto.RemoteSignerError) proto.Message {\n\treturn &privvalproto.PubKeyResponse{\n\t\tPubKey: pubKey,\n\t\tError: err,\n\t}\n}",
"func NewPopulatedProtoPubKey(_ randyNet) *ProtoPubKey {\n\t_, k, _ := crypto.GenerateKeyPair(crypto.RSA, 512)\n\treturn &ProtoPubKey{PubKey: k}\n}",
"func TweakPubKey(pubKey *btcec.PublicKey, tweak []byte) *btcec.PublicKey {\n\n\tpath := getDerivationPathFromTweak(tweak) // get derivation path for tweak\n\n\t// set initial pubkey X/Y to current pubkey\n\tresX := pubKey.ToECDSA().X\n\tresY := pubKey.ToECDSA().Y\n\n\t// tweak pubkey for each path child\n\tfor _, pathChild := range path {\n\t\t// get tweaked pubkey\n\t\tresX, resY = tweakPubWithPathChild(pathChild, resX, resY)\n\t}\n\n\treturn (*btcec.PublicKey)(&ecdsa.PublicKey{btcec.S256(), resX, resY})\n}",
"func testOrderedPublicKeys() []cipher.PubKey {\n\t// add feeds\n\tpk1, _ := cipher.GenerateKeyPair()\n\tpk2, _ := cipher.GenerateKeyPair()\n\n\t// be sure that keys are not equal\n\tfor pk1 == pk2 {\n\t\tpk2, _ = cipher.GenerateKeyPair()\n\t}\n\n\t// oreder\n\tif bytes.Compare(pk2[:], pk1[:]) < 0 { // if pk2 < pk1\n\t\tpk1, pk2 = pk2, pk1 // swap\n\t}\n\n\treturn []cipher.PubKey{pk1, pk2}\n}",
"func (s *server) findPeer(peerKey *btcec.PublicKey) (*peer, error) {\n\tserializedIDKey := string(peerKey.SerializeCompressed())\n\n\ts.peersMtx.RLock()\n\tpeer := s.peersByPub[serializedIDKey]\n\ts.peersMtx.RUnlock()\n\n\tif peer == nil {\n\t\treturn nil, errors.New(\"Peer not found. Pubkey: \" +\n\t\t\tstring(peerKey.SerializeCompressed()))\n\t}\n\n\treturn peer, nil\n}",
"func pubkeyFromSeckey(seckey []byte) []byte {\n\tif len(seckey) != 32 {\n\t\tlog.Panic(\"seckey length invalid\")\n\t}\n\n\tif secp.SeckeyIsValid(seckey) != 1 {\n\t\tlog.Panic(\"always ensure seckey is valid\")\n\t\treturn nil\n\t}\n\n\tpubkey := secp.GeneratePublicKey(seckey)\n\tif pubkey == nil {\n\t\tlog.Panic(\"ERROR: impossible, secp.GeneratePublicKey should never fail\")\n\t\treturn nil\n\t}\n\tif len(pubkey) != 33 {\n\t\tlog.Panic(\"ERROR: impossible, invalid pubkey length\")\n\t}\n\n\tif ret := secp.PubkeyIsValid(pubkey); ret != 1 {\n\t\tlog.Panicf(\"ERROR: pubkey invald, ret=%d\", ret)\n\t\treturn nil\n\t}\n\n\tif ret := VerifyPubkey(pubkey); ret != 1 {\n\t\tlog.Printf(\"seckey=%s\\n\", hex.EncodeToString(seckey))\n\t\tlog.Printf(\"pubkey=%s\\n\", hex.EncodeToString(pubkey))\n\t\tlog.Panicf(\"ERROR: pubkey verification failed, for deterministic. ret=%d\", ret)\n\t\treturn nil\n\t}\n\n\treturn pubkey\n}",
"func (d *EditCandidatePublicKeyData) SetNewPubKey(key string) (*EditCandidatePublicKeyData, error) {\n\tnewPubKey, err := wallet.PublicKeyToHex(key)\n\tif err != nil {\n\t\treturn d, err\n\t}\n\tvar pubKey PublicKey\n\tcopy(pubKey[:], newPubKey)\n\td.NewPubKey = pubKey\n\treturn d, nil\n}",
"func PrivateKeyPublic(priv *rsa.PrivateKey,) crypto.PublicKey",
"func KeyTestPubAddr() (cryptotypes.PrivKey, cryptotypes.PubKey, sdk.AccAddress) {\n\tkey := secp256k1.GenPrivKey()\n\tpub := key.PubKey()\n\taddr := sdk.AccAddress(pub.Address())\n\treturn key, pub, addr\n}",
"func getPublicKey(priv interface{}) interface{} {\n\tswitch k := priv.(type) {\n\tcase *rsa.PrivateKey:\n\t\treturn &k.PublicKey\n\tcase *ecdsa.PrivateKey:\n\t\treturn &k.PublicKey\n\tdefault:\n\t\treturn nil\n\t}\n}",
"func (pb *PutBlock) ProducerPublicKey() crypto.PublicKey { return pb.SrcPubkey() }",
"func CmpPubKey(i, j *ecdsa.PublicKey) bool {\n\tif i.X.Cmp(j.X) != 0 {\n\t\treturn false\n\t}\n\n\tif i.Y.Cmp(j.Y) != 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}",
"func GetPubKey(s string) (cipher.PubKey, error) {\n\tb, e := hex.DecodeString(s)\n\tif e != nil || len(b) != len(cipher.PubKey{}) {\n\t\treturn cipher.PubKey{}, errors.New(\"invalid public key\")\n\t}\n\treturn cipher.NewPubKey(b), nil\n}",
"func ParsePubKey(pubKeyStr []byte) (key *PublicKey, err error) {\n\tpubkey := PublicKey{}\n\n\tif len(pubKeyStr) == 0 {\n\t\treturn nil, errors.New(\"pubkey string is empty\")\n\t}\n\n\tformat := pubKeyStr[0]\n\tybit := (format & 0x1) == 0x1\n\tformat &= ^byte(0x1)\n\n\tswitch len(pubKeyStr) {\n\tcase PubKeyBytesLenUncompressed:\n\t\tif format != pubKeyUncompressed && format != pubKeyHybrid {\n\t\t\treturn nil, fmt.Errorf(\"invalid magic in pubkey str: \"+\n\t\t\t\t\"%d\", pubKeyStr[0])\n\t\t}\n\n\t\tpubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33])\n\t\tpubkey.Y = new(big.Int).SetBytes(pubKeyStr[33:])\n\t\t// hybrid keys have extra information, make use of it.\n\t\tif format == pubKeyHybrid && ybit != isOdd(pubkey.Y) {\n\t\t\treturn nil, fmt.Errorf(\"ybit doesn't match oddness\")\n\t\t}\n\tcase PubKeyBytesLenCompressed:\n\t\t// format is 0x2 | solution, <X coordinate>\n\t\t// solution determines which solution of the curve we use.\n\t\t/// y^2 = x^3 + Curve.B\n\t\tif format != pubKeyCompressed {\n\t\t\treturn nil, fmt.Errorf(\"invalid magic in compressed \"+\n\t\t\t\t\"pubkey string: %d\", pubKeyStr[0])\n\t\t}\n\t\tpubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33])\n\t\tpubkey.Y, err = decompressPoint(pubkey.X, ybit)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tdefault: // wrong!\n\t\treturn nil, fmt.Errorf(\"invalid pub key length %d\",\n\t\t\tlen(pubKeyStr))\n\t}\n\n\tif pubkey.X.Cmp(secp256k1.Params().P) >= 0 {\n\t\treturn nil, fmt.Errorf(\"pubkey X parameter is >= to P\")\n\t}\n\tif pubkey.Y.Cmp(secp256k1.Params().P) >= 0 {\n\t\treturn nil, fmt.Errorf(\"pubkey Y parameter is >= to P\")\n\t}\n\tif !secp256k1.IsOnCurve(pubkey.X, pubkey.Y) {\n\t\treturn nil, fmt.Errorf(\"pubkey isn't on secp256k1 curve\")\n\t}\n\treturn &pubkey, nil\n}",
"func (x *X25519) SharedKey(peerPublicKey []byte) (sharedKey []byte, err error) {\n\tif len(peerPublicKey) != 32 {\n\t\treturn nil, errors.New(\"peer's public key's lenght is not 32\")\n\t}\n\n\tvar theirPublicKey [32]byte\n\tcopy(theirPublicKey[:], peerPublicKey)\n\tsharedKey, err = curve25519.X25519(x.privateKey[:], theirPublicKey[:])\n\treturn\n}",
"func (d *EditCandidatePublicKeyData) SetPubKey(key string) (*EditCandidatePublicKeyData, error) {\n\tpk, err := wallet.PublicKeyToHex(key)\n\tif err != nil {\n\t\treturn d, err\n\t}\n\tvar pubKey PublicKey\n\tcopy(pubKey[:], pk)\n\td.PubKey = pubKey\n\treturn d, nil\n}",
"func HashPubKey(pubKey []byte) []byte {\n\tpublicSHA256 := sha256.Sum256(pubKey)\n\tRIPEMD160Hasher := ripemd160.New()\n\t_, err := RIPEMD160Hasher.Write(publicSHA256[:])\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tpublicRIPEMD160 := RIPEMD160Hasher.Sum(nil)\n\treturn publicRIPEMD160\n}",
"func (ac *authenticatedConnection) RemotePublicKey() libp2pcrypto.PubKey {\n\treturn ac.remotePeerPublicKey\n}",
"func PubkeyFromPrivkey(privkey []byte) []byte {\n\tpair, err := noise.DH25519.GenerateKeypair(bytes.NewReader(privkey))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif !bytes.Equal(pair.Private, privkey) {\n\t\tpanic(\"privkey was not as expected\")\n\t}\n\treturn pair.Public\n}",
"func pubKeyHashAddrFromBytes(t *testing.T, pubKey []byte, params *chaincfg.Params) *btcutil.AddressPubKeyHash {\n\tpubKeyHash := btcutil.Hash160(pubKey)\n\tpubKeyHashAddr, err := btcutil.NewAddressPubKeyHash(pubKeyHash, params)\n\t_assert.NoError(t, err)\n\treturn pubKeyHashAddr\n}",
"func PubKeyFromBytes(data []byte) (PubKey, error) {\n\tkeyTypeByt := data[:KeyTypeBytLen]\n\tswitch string(keyTypeByt) {\n\tcase Sr25519Idx:\n\t\treturn SrPubKeyFromBytes(data[KeyTypeBytLen:]), nil\n\tcase Ed25519Idx:\n\t\treturn EdPubKeyFromBytes(data[KeyTypeBytLen:]), nil\n\tdefault:\n\t\treturn nil, NoKeyType\n\t}\n}",
"func (ec *EthereumChain) GetPublicKey(keepAddress common.Address) ([]uint8, error) {\n\tkeepContract, err := ec.getKeepContract(keepAddress)\n\tif err != nil {\n\t\treturn []uint8{}, err\n\t}\n\n\treturn keepContract.GetPublicKey()\n}",
"func readPublicKey(d *pluginsdk.ResourceData, pubKey interface{}) error {\n\tpubKeyBytes, err := x509.MarshalPKIXPublicKey(pubKey)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal public key error: %s\", err)\n\t}\n\tpubKeyPemBlock := &pem.Block{\n\t\tType: \"PUBLIC KEY\",\n\t\tBytes: pubKeyBytes,\n\t}\n\n\td.Set(\"public_key_pem\", string(pem.EncodeToMemory(pubKeyPemBlock)))\n\n\tsshPubKey, err := ssh.NewPublicKey(pubKey)\n\tif err == nil {\n\t\t// Not all EC types can be SSH keys, so we'll produce this only\n\t\t// if an appropriate type was selected.\n\t\tsshPubKeyBytes := ssh.MarshalAuthorizedKey(sshPubKey)\n\t\td.Set(\"public_key_openssh\", string(sshPubKeyBytes))\n\t} else {\n\t\td.Set(\"public_key_openssh\", \"\")\n\t}\n\treturn nil\n}",
"func (o ClusterNodeGroupOptionsOutput) NodePublicKey() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ClusterNodeGroupOptions) *string { return v.NodePublicKey }).(pulumi.StringPtrOutput)\n}",
"func HashPubKey(pubKey []byte) []byte {\n\tpublicSHA256 := sha256.Sum256(pubKey)\n\n\tRIPEMD160Hasher := ripemd160.New()\n\tif _, err := RIPEMD160Hasher.Write(publicSHA256[:]); err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tpublicRIPEMD160 := RIPEMD160Hasher.Sum(nil)\n\treturn publicRIPEMD160\n}",
"func KeyTestPubAddrSecp256R1(t *testing.T) (cryptotypes.PrivKey, cryptotypes.PubKey, sdk.AccAddress) {\n\tkey, err := secp256r1.GenPrivKey()\n\tassert.NilError(t, err)\n\tpub := key.PubKey()\n\taddr := sdk.AccAddress(pub.Address())\n\treturn key, pub, addr\n}",
"func (r *Resolver) PubKey() ([32]byte, [32]byte, error) {\n\tnameHash, err := NameHash(r.domain)\n\tif err != nil {\n\t\treturn [32]byte{}, [32]byte{}, err\n\t}\n\tres, err := r.Contract.Pubkey(nil, nameHash)\n\treturn res.X, res.Y, err\n}",
"func (r *Resolver) SetPubKey(opts *bind.TransactOpts, x [32]byte, y [32]byte) (*types.Transaction, error) {\n\tnameHash, err := NameHash(r.domain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.Contract.SetPubkey(opts, nameHash, x, y)\n}",
"func (privKey *YubiHsmPrivateKey) exportPubKey() error {\n\t// send getpubkey command\n\tcmd, err := commands.CreateGetPubKeyCommand(privKey.privKeyID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp, err := privKey.sessionMgr.SendEncryptedCommand(cmd)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t// parse public key from response\n\tparsedResp, matched := resp.(*commands.GetPubKeyResponse)\n\tif !matched {\n\t\treturn errors.New(\"Invalid response for exporting public key\")\n\t}\n\n\tif privKey.yubiHsmParams.PrivKeyType == YubiHsmPrivKeyTypeEd25519 {\n\t\terr = privKey.exportEd25519Pubkey(parsedResp.KeyData)\n\t} else {\n\t\terr = privKey.exportSecp256k1Pubkey(parsedResp.KeyData)\n\t}\n\n\treturn err\n}",
"func (k *Keypair) PublicKey() *PubKey {\n\tpub := new(PubKey)\n\tcopy(pub[:], k.pub[:])\n\treturn pub\n}",
"func (d *SetCandidateOffData) SetPubKey(key string) (*SetCandidateOffData, error) {\n\tpubKey, err := wallet.PublicKeyToHex(key)\n\tif err != nil {\n\t\treturn d, err\n\t}\n\tcopy(d.PubKey[:], pubKey)\n\treturn d, nil\n}",
"func BitcoinAddressFromPubKey(pubKey PubKey) BitcoinAddress {\n\treturn BitcoinAddress{\n\t\tVersion: 0,\n\t\tKey: BitcoinPubKeyRipemd160(pubKey),\n\t}\n}",
"func HashPubKey(pubKey []byte) []byte {\n\tpubKeyHash256 := sha256.Sum256(pubKey)\n\n\tRIPEMD160Hasher := ripemd160.New()\n\t_, err := RIPEMD160Hasher.Write(pubKeyHash256[:])\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\n\treturn RIPEMD160Hasher.Sum(nil)\n}",
"func ReadPubKey(path string) (crypto.PublicKey, error) {\n\traw, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor {\n\t\tblock, rest := pem.Decode(raw)\n\t\tif block == nil {\n\t\t\tbreak\n\t\t}\n\t\tif !strings.Contains(block.Type, \"CERTIFICATE\") {\n\t\t\tif strings.Contains(block.Type, \"RSA\") {\n\t\t\t\tkey, err := x509.ParsePKCS1PublicKey(block.Bytes)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Parsing error in x509.ParsePKCS1PublicKey: %v\", err)\n\t\t\t\t}\n\t\t\t\treturn key, nil\n\t\t\t}\n\t\t\tkey, err := x509.ParsePKIXPublicKey(block.Bytes)\n\t\t\tif err == nil {\n\t\t\t\tif key, ok := key.(crypto.PublicKey); ok {\n\t\t\t\t\treturn key, nil\n\t\t\t\t}\n\t\t\t\treturn nil, fmt.Errorf(\"found unknown public key type (%T) in PKIX wrapping\", key)\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\traw = rest\n\t}\n\treturn nil, fmt.Errorf(\"failed to parse public key\")\n}",
"func (rd *RootDomain) GetMemberByPublicKey(publicKey string) (*insolar.Reference, error) {\n\ttrimmedPublicKey := foundation.TrimPublicKey(publicKey)\n\ti := foundation.GetShardIndex(trimmedPublicKey, insolar.GenesisAmountPublicKeyShards)\n\tif i >= len(rd.PublicKeyShards) {\n\t\treturn nil, fmt.Errorf(\"incorrect shard index\")\n\t}\n\ts := pkshard.GetObject(rd.PublicKeyShards[i])\n\trefStr, err := s.GetRef(trimmedPublicKey)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get reference in shard\")\n\t}\n\tref, err := insolar.NewReferenceFromBase58(refStr)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"bad member reference for this public key\")\n\t}\n\n\treturn ref, nil\n}",
"func (s *State) ProducerNodePublicKeyExists(publicKey []byte) bool {\n\ts.mtx.RLock()\n\tkey := hex.EncodeToString(publicKey)\n\t_, ok := s.NodeOwnerKeys[key]\n\ts.mtx.RUnlock()\n\treturn ok\n}",
"func GetNodePositionByPublicKey(publicKey []byte) (int64, error) {\r\n\tmutex.RLock()\r\n\tdefer mutex.RUnlock()\r\n\r\n\tfor i, item := range nodesByPosition {\r\n\t\tif item.Stopped {\r\n\t\t\tif bytes.Equal(item.PublicKey, publicKey) {\r\n\t\t\t\treturn 0, errNodeDisabled\r\n\t\t\t}\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t\tif bytes.Equal(item.PublicKey, publicKey) {\r\n\t\t\treturn int64(i), nil\r\n\t\t}\r\n\t}\r\n\r\n\treturn 0, fmt.Errorf(\"Incorrect public key\")\r\n}",
"func GetNodePublicKeyByPosition(position int64) ([]byte, error) {\r\n\tmutex.RLock()\r\n\tdefer mutex.RUnlock()\r\n\tif int64(len(nodesByPosition)) <= position {\r\n\t\treturn nil, fmt.Errorf(\"incorrect position\")\r\n\t}\r\n\tnodeData, err := GetNodeByPosition(position)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\treturn nodeData.PublicKey, nil\r\n}",
"func PubKey(key []byte) ([]byte, error) {\n\tcmd := exec.Command(\"wg\", \"pubkey\")\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open pipe to stdin: %v\", err)\n\t}\n\n\tgo func() {\n\t\tdefer stdin.Close()\n\t\tstdin.Write(key)\n\t}()\n\n\tpublic, err := cmd.Output()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to generate public key: %v\", err)\n\t}\n\treturn bytes.Trim(public, \"\\n\"), nil\n}",
"func (priv *PrivateKey) Public() crypto.PublicKey",
"func (priv *PrivateKey) Public() crypto.PublicKey",
"func (nr NodeRecord) GetPublicKey() (string, error) {\n\treturn nr.Record.PublicKey, nil\n}",
"func getHostKey(opt *Options) (ssh.PublicKey, error) {\n\tvar reader io.Reader\n\n\tif opt.KnownHostsData != \"\" {\n\t\treader = strings.NewReader(opt.KnownHostsData)\n\t} else {\n\t\tfile, err := os.Open(opt.knownHostsFile()) //nolint:gosec\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer file.Close() //nolint:errcheck\n\n\t\treader = file\n\t}\n\n\tscanner := bufio.NewScanner(reader)\n\tfor scanner.Scan() {\n\t\t_, hosts, hostKey, _, _, err := ssh.ParseKnownHosts(scanner.Bytes())\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"error parsing %s\", scanner.Text())\n\t\t}\n\n\t\tif hostExists(opt.Host, hosts) {\n\t\t\treturn hostKey, nil\n\t\t}\n\t}\n\n\treturn nil, errors.Errorf(\"no hostkey found for %s\", opt.Host)\n}",
"func (a *Account) PublicKey() *PubKey {\n\tk := new(PubKey)\n\tcopy(k[:], a.pub[:])\n\treturn k\n}",
"func (r *Member) GetPublicKeyNoWait() {\n\tvar args [0]interface{}\n\n\tvar argsSerialized []byte\n\n\terr := proxyctx.Current.Serialize(args, &argsSerialized)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t_, err = proxyctx.Current.RouteCall(r.Reference, false, \"GetPublicKey\", argsSerialized)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}",
"func (k *key) getPublicKey() (*ecdsa.PublicKey, error) {\n\tby, err := base64.StdEncoding.DecodeString(k.PublicKeyB64)\n\tif err != nil {\n\t\treturn (*ecdsa.PublicKey)(nil), err\n\t}\n\n\tblockPub, _ := pem.Decode([]byte(by))\n\tgenericPublicKey, err := x509.ParsePKIXPublicKey(blockPub.Bytes)\n\tif err != nil {\n\t\treturn (*ecdsa.PublicKey)(nil), err\n\t}\n\n\treturn genericPublicKey.(*ecdsa.PublicKey), nil\n}",
"func (r *gorumsReplica) PublicKey() hotstuff.PublicKey {\n\treturn r.pubKey\n}",
"func PubkeyFromSeckey(seckey []byte) []byte {\n\t// This method must succeed\n\t// TODO; hash on fail\n\t// TODO: must match, result of private key from deterministic gen?\n\t// deterministic gen will always return a valid private key\n\tif len(seckey) != 32 {\n\t\tlog.Panic(\"PubkeyFromSeckey: invalid length\")\n\t}\n\n\tpubkey := pubkeyFromSeckey(seckey)\n\tif pubkey == nil {\n\t\tlog.Panic(\"ERRROR: impossible, pubkey generation failed\")\n\t\treturn nil\n\t}\n\tif ret := secp.PubkeyIsValid(pubkey); ret != 1 {\n\t\tlog.Panicf(\"ERROR: Pubkey invalid, ret=%d\", ret)\n\t\treturn nil\n\t}\n\n\treturn pubkey\n}",
"func (d Driver) PubKeyFromBytes(b []byte) (crypto.PubKey, error) {\n\tif len(b) != pubkeyBytesLen && len(b) != 33 {\n\t\treturn nil, errors.New(\"invalid pub key byte,must be 65 bytes\")\n\t}\n\tif len(b) == 33 {\n\t\tp, err := ethcrypto.DecompressPubkey(b)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tb = ethcrypto.FromECDSAPub(p)\n\t}\n\tvar pubKeyBytes [pubkeyBytesLen]byte\n\t//pubKeyBytes := new([pubkeyBytesLen]byte)\n\tcopy(pubKeyBytes[:], b[:])\n\treturn PubKeySecp256k1Eth(pubKeyBytes), nil\n}",
"func (s *State) getProducerKey(publicKey []byte) string {\n\tkey := hex.EncodeToString(publicKey)\n\n\t// If the given public key is node public key, get the producer's owner\n\t// public key.\n\tif owner, ok := s.NodeOwnerKeys[key]; ok {\n\t\treturn owner\n\t}\n\n\treturn key\n}",
"func (pv *ThresholdValidator) GetPubKey() (crypto.PubKey, error) {\n\treturn pv.pubkey, nil\n}",
"func (_BondedECDSAKeep *BondedECDSAKeepCaller) PublicKey(opts *bind.CallOpts) ([]byte, error) {\n\tvar (\n\t\tret0 = new([]byte)\n\t)\n\tout := ret0\n\terr := _BondedECDSAKeep.contract.Call(opts, out, \"publicKey\")\n\treturn *ret0, err\n}",
"func CalcAccountFromPubKey(pubKey types.PubKey) types.Address {\n\tsdk.Require(pubKey != nil && len(pubKey) == 32,\n\t\ttypes.ErrInvalidParameter, \"invalid pubKey\")\n\n\tpk := crypto.PubKeyEd25519FromBytes(pubKey)\n\treturn pk.Address(utChainID)\n}",
"func (server *OpencxServer) GetQchansByPeerParam(pubkey *koblitz.PublicKey, param *coinparam.Params) (qchans []*qln.Qchan, err error) {\n\n\t// get the peer idx\n\tvar peerIdx uint32\n\tif peerIdx, err = server.GetPeerFromPubkey(pubkey); err != nil {\n\t\treturn\n\t}\n\n\t// get the peer\n\tvar peer *lnp2p.Peer\n\tif peer = server.ExchangeNode.PeerMan.GetPeerByIdx(int32(peerIdx)); err != nil {\n\t\treturn\n\t}\n\n\t// lock this so we can be in peace\n\tserver.ExchangeNode.PeerMapMtx.Lock()\n\t// get the remote peer from the qchan\n\tvar remotePeer *qln.RemotePeer\n\tvar found bool\n\tif remotePeer, found = server.ExchangeNode.PeerMap[peer]; !found {\n\t\terr = fmt.Errorf(\"Could not find remote peer that peer manager is tracking, there's something wrong with the lit node\")\n\t\t// unlock because we have to before we return or else we deadlock\n\t\tserver.ExchangeNode.PeerMapMtx.Unlock()\n\t\treturn\n\t}\n\tserver.ExchangeNode.PeerMapMtx.Unlock()\n\n\t// populate qchans just to be safe -- this might not be necessary and makes this function very inefficient\n\tif err = server.ExchangeNode.PopulateQchanMap(remotePeer); err != nil {\n\t\treturn\n\t}\n\n\t// get qchans from peer\n\tfor _, qchan := range remotePeer.QCs {\n\t\t// if this is the same coin then return the idx\n\t\tif qchan.Coin() == param.HDCoinType {\n\t\t\tqchans = append(qchans, qchan)\n\t\t}\n\t}\n\n\treturn\n}",
"func (sk *PrivKey) PubKey() PubKey {\n\treturn PubKey{sk.PublicKey, nil}\n}",
"func PublicKey(pemkey []byte) (pub []byte, err error) {\n\tvar (\n\t\tpkey *rsa.PrivateKey\n\t)\n\n\tblk, _ := pem.Decode(pemkey) // assumes a single valid pem encoded key.\n\n\tif pkey, err = x509.ParsePKCS1PrivateKey(blk.Bytes); err != nil {\n\t\treturn pub, err\n\t}\n\n\treturn x509.MarshalPKCS1PublicKey(&pkey.PublicKey), nil\n}",
"func GetPublicKey(passphrase string, address string) (string, error) {\n\tkeys, err := GetPublicPrivateKey(passphrase, address)\n\n\treturn keys.PublicKey, err\n}",
"func PublicKeyOf(v interface{}) (interface{}, error) {\n\t// may be a silly idea, but if the user gave us a non-pointer value...\n\tvar ptr interface{}\n\tswitch v := v.(type) {\n\tcase rsa.PrivateKey:\n\t\tptr = &v\n\tcase rsa.PublicKey:\n\t\tptr = &v\n\tcase ecdsa.PrivateKey:\n\t\tptr = &v\n\tcase ecdsa.PublicKey:\n\t\tptr = &v\n\tdefault:\n\t\tptr = v\n\t}\n\n\tswitch x := ptr.(type) {\n\tcase *rsa.PrivateKey:\n\t\treturn &x.PublicKey, nil\n\tcase *rsa.PublicKey:\n\t\treturn x, nil\n\tcase *ecdsa.PrivateKey:\n\t\treturn &x.PublicKey, nil\n\tcase *ecdsa.PublicKey:\n\t\treturn x, nil\n\tcase []byte:\n\t\treturn x, nil\n\tdefault:\n\t\treturn nil, errors.Errorf(`invalid key type passed to PublicKeyOf (%T)`, v)\n\t}\n}",
"func (d *dht) search(ctx context.Context, pk types.PublicKey, stopshort bool) (types.PublicKey, net.Addr, error) {\n\t// If the search is for our own key then don't do anything\n\t// as we already know what our own coordinates are.\n\tif d.r.public.EqualTo(pk) && !stopshort {\n\t\treturn pk, &GreedyAddr{d.r.Coords()}, nil\n\t}\n\n\t// Each time we visit a node, we'll insert it into this\n\t// map. We specifically put our own key in here because\n\t// we shouldn't ever be directed back to ourselves as a\n\t// part of a search.\n\tvar visited map[types.PublicKey]struct{}\n\n\t// The nexthop function processes the next step of the\n\t// search by contacting the next hop. This is recursive\n\t// and will continue until either there are no branches\n\t// to follow or we've reached our destination.\n\tvar nexthop func(ctx context.Context, sc types.SwitchPorts, via, pk types.PublicKey) (types.PublicKey, types.SwitchPorts, error)\n\tnexthop = func(ctx context.Context, sc types.SwitchPorts, via, pk types.PublicKey) (types.PublicKey, types.SwitchPorts, error) {\n\t\t// Check that we haven't exceeded the supplied context.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn via, nil, ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\t// Check that we haven't already visited this node before.\n\t\t// If we have then we won't contact it again.\n\t\tif _, ok := visited[via]; ok {\n\t\t\treturn via, nil, fmt.Errorf(\"this node has already been visited\")\n\t\t}\n\n\t\t// Mark the node as visited.\n\t\tvisited[via] = struct{}{}\n\n\t\t// Send the request to the remote node. This will hopefully\n\t\t// return the node's own public key and a list of closer\n\t\t// nodes.\n\t\tpubkey, results, err := d.request(sc, pk)\n\t\tif err != nil {\n\t\t\treturn via, nil, fmt.Errorf(\"d.request: %w\", err)\n\t\t}\n\n\t\t// If the node's public key is equal to the public key that\n\t\t// we're looking for, then we've successfully completed the\n\t\t// search! Return the coordinates that we contacted.\n\t\tif pubkey.EqualTo(pk) {\n\t\t\treturn pubkey, sc, nil\n\t\t}\n\n\t\t// Sort the resulting closer nodes by distance to the key\n\t\t// that we're searching for. This means we'll try nodes that\n\t\t// are closer in keyspace first, to hopefully shorten the\n\t\t// path that the search takes as far as possible. This is\n\t\t// also important because it means that, if the remote node\n\t\t// tried to send us deliberately out of our way, that we\n\t\t// will not try those distant nodes until we've at least\n\t\t// tried better ones first.\n\t\tsort.SliceStable(results, func(i, j int) bool {\n\t\t\treturn util.DHTOrdered(pk, results[i].PublicKey, results[j].PublicKey)\n\t\t})\n\n\t\t// Process each of the results.\n\t\tfor _, result := range results {\n\t\t\tif result.PublicKey.EqualTo(pk) && stopshort {\n\t\t\t\treturn via, sc, nil\n\t\t\t}\n\n\t\t\tif k, c, err := nexthop(ctx, result.Coordinates.Copy(), result.PublicKey, pk); err == nil {\n\t\t\t\t// If there's no error then that means we've successfully\n\t\t\t\t// reached the destination node. Return the coordinates.\n\t\t\t\t// This will be passed back up the stack to the caller.\n\t\t\t\treturn k, c, nil\n\t\t\t}\n\t\t}\n\n\t\t// If we've reached this point then none of the nodes that\n\t\t// were given to us returned satisfactory results. It may\n\t\t// be because they didn't know any closer nodes, or they\n\t\t// timed out/just didn't respond in a timely fashion.\n\t\treturn via, nil, errors.New(\"search has reached dead end\")\n\t}\n\n\t// Start the search by looking at our own predecessor,\n\t// successor and finger table.\n\tinitial := d.table()\n\tsort.SliceStable(initial, func(i, j int) bool {\n\t\treturn util.DHTOrdered(pk, initial[i].PublicKey(), initial[j].PublicKey())\n\t})\n\tfor _, n := range initial {\n\t\t// Each time we start a search using one of our direct\n\t\t// neighbors, we'll reset the list of visited nodes. This\n\t\t// means that we don't accidentally kill searches based\n\t\t// on the results of a previous one. We insert our own\n\t\t// public key here so that if anyone refers us back to\n\t\t// ourselves, we will abort the search via that peer.\n\t\tvisited = map[types.PublicKey]struct{}{\n\t\t\td.r.public: {},\n\t\t}\n\n\t\t// Send the search via this peer. This is a recursive\n\t\t// function so will block until either the search fails\n\t\t// or completes. If the search fails, continue onto the\n\t\t// next peer and try that instead.\n\t\tkey, found, err := nexthop(ctx, n.Coordinates(), n.PublicKey(), pk)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// We successfully found the destination, so return the\n\t\t// greedy coordinates as a net.Addr.\n\t\treturn key, &GreedyAddr{found}, nil\n\t}\n\n\treturn types.PublicKey{}, nil, errors.New(\"search failed via all known nodes\")\n}",
"func (p PrivateKey) SharedKey(peerPublicKey []byte) ([]byte, error) {\n\tsharedKey, err := curve25519.X25519(p, peerPublicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn sharedKey, nil\n}",
"func (pk PrivateKey) PublicKey() hotstuff.PublicKey {\n\treturn pk.Public()\n}"
] | [
"0.6852779",
"0.6304922",
"0.60505444",
"0.5968123",
"0.59014976",
"0.5867466",
"0.5847692",
"0.5827551",
"0.58045566",
"0.5804077",
"0.56456894",
"0.56329596",
"0.5628264",
"0.5571481",
"0.5534679",
"0.5524534",
"0.5518396",
"0.5513245",
"0.5512424",
"0.55060214",
"0.55002284",
"0.5495705",
"0.54859626",
"0.5470002",
"0.54677993",
"0.5442215",
"0.54194844",
"0.5368112",
"0.53556144",
"0.53431606",
"0.533243",
"0.5323555",
"0.53183377",
"0.53151023",
"0.5299808",
"0.52916616",
"0.52846885",
"0.5277254",
"0.5259139",
"0.52512187",
"0.5238127",
"0.5230419",
"0.5212351",
"0.520746",
"0.52024657",
"0.5197012",
"0.5195666",
"0.5194902",
"0.51778996",
"0.51451087",
"0.51427656",
"0.51355",
"0.5130105",
"0.5129777",
"0.51209444",
"0.50957024",
"0.50940627",
"0.50828165",
"0.5080547",
"0.5080387",
"0.5079608",
"0.5078495",
"0.5070111",
"0.5063776",
"0.50583345",
"0.5054373",
"0.505354",
"0.50454867",
"0.504177",
"0.50344974",
"0.5029843",
"0.5028416",
"0.5025595",
"0.5020943",
"0.501662",
"0.50072634",
"0.50008637",
"0.4997744",
"0.4995395",
"0.4995395",
"0.49914992",
"0.49896806",
"0.49846113",
"0.49680427",
"0.496775",
"0.49668193",
"0.49636304",
"0.49615958",
"0.49610943",
"0.4957039",
"0.49468732",
"0.4946132",
"0.49401292",
"0.49256316",
"0.4916805",
"0.49033368",
"0.48985302",
"0.4897139",
"0.4894409",
"0.4892555"
] | 0.73772836 | 0 |
NetID implements peering.PeerSender for the Self() node. | func (n *NetImpl) NetID() string {
return n.myNetID
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (tracker *PeerTracker) Self() peer.ID {\n\treturn tracker.self\n}",
"func (s Keygen) SelfID() party.ID {\n\treturn s.selfID\n}",
"func (a *Agent) Self() *Peer {\n\treturn a.state.Self\n}",
"func Sender() send.Sender {\n\treturn std.Sender()\n}",
"func (p Peers) thisPeerRaftId() uint64 {\n\treturn uint64(p.thisPeer + 1)\n}",
"func Send(node *noise.Node, from kad.ID, code byte, data []byte, minBucketID int, maxBucketID int, seqNum byte, incrementSeqNum bool) {\n\terrChan := make(chan error)\n\t// TODO: maybe do a self node lookup here\n\tpeers, prefixLens := kad.Table(node).GetBroadcastPeers(minBucketID, maxBucketID)\n\tfor i, id := range peers {\n\t\t// fmt.Println(\"Peers ID: \", id)\n\t\tmsg := NewMessage(from, prefixLens[i], code, data)\n\t\t// If incrementSeqNum is true, then seqNum is ignored and broadcastSeqNum is used and incremented instead. incrementSeqNum should only be set to true when Send is Send is called by the \"from\" node (i.e. not an intermediate broadcast node).\n\t\tif incrementSeqNum {\n\t\t\tmsg.ChangeSeqNum(broadcastSeqNum)\n\t\t} else {\n\t\t\tmsg.ChangeSeqNum(seqNum)\n\t\t}\n\t\tgo broadcastThroughPeer(node, id.(kad.ID), msg, errChan)\n\t}\n\tif incrementSeqNum {\n\t\tbroadcastSeqNum++\n\t}\n\n\tnumPeers := uint32(len(peers))\n\tresponseCount := uint32(0)\n\tfor atomic.LoadUint32(&responseCount) < numPeers {\n\t\tselect {\n\t\tcase err := <-errChan:\n\t\t\tif err != nil {\n\t\t\t\tlog.Warn().Err(err)\n\t\t\t}\n\t\t\tatomic.AddUint32(&responseCount, 1)\n\t\t}\n\t}\n}",
"func PeerID() string {\n\treturn \"-UT3530-\" + Base62String(12)\n}",
"func (p *peer) ID() ID {\r\n\treturn p.nodeInfo.ID\r\n}",
"func SendToSender(\n\tcertificate *SelfSignedCert,\n\tport string,\n\ttimeoutDuration uint,\n) error {\n\tln, err := net.CreateTCPListener(port)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer ln.Close()\n\tconn, err := net.EstablishConn(ln, timeoutDuration)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\treturn net.SendMessage(certificate.Bytes, conn)\n}",
"func (e ScoreProposal) Sender() []byte {\n\treturn e.Identity\n}",
"func (p *Privmsg) IsFromSelf() bool {\n\t// if the from user is empty, then this is a self privmsg\n\treturn p.From == User{}\n}",
"func Self() string {\n\treturn naiveSelf()\n}",
"func (n *NetImpl) peeringID(remoteNetID string) string {\n\tif n.isInbound(remoteNetID) {\n\t\treturn remoteNetID + \"<\" + n.myNetID\n\t}\n\treturn n.myNetID + \"<\" + remoteNetID\n}",
"func (n *Node) Send(PubKey []byte, privKey ecdsa.PrivateKey, to string, amount float64) ([]byte, error) {\n\t// get pubkey of the wallet with \"from\" address\n\tif to == \"\" {\n\t\treturn nil, errors.New(\"Recipient address is not provided\")\n\t}\n\tw := wallet.Wallet{}\n\n\tif !w.ValidateAddress(to) {\n\t\treturn nil, errors.New(\"Recipient address is not valid\")\n\t}\n\n\ttx, err := n.GetTransactionsManager().CreateTransaction(PubKey, privKey, to, amount)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn.SendTransactionToAll(tx)\n\n\treturn tx.ID, nil\n}",
"func SelfShutdown(msg string) {\n\tselect {\n\tcase nodeSelfShutdown <- msg:\n\tdefault:\n\t}\n}",
"func (p *Peer) Name() string {\n\treturn p.m.LocalNode().Name\n}",
"func (gs *ShutdownHandler) SelfShutdown(msg string) {\n\tselect {\n\tcase gs.nodeSelfShutdown <- msg:\n\tdefault:\n\t}\n}",
"func (o *UsersLinks) SetSelf(v string) {\n\to.Self = &v\n}",
"func (p Proto) MyName() *PeerName {\n\treturn &PeerName{\n\t\tName: p.Name,\n\t\tPubKey: hex.EncodeToString(p.PubKey),\n\t}\n}",
"func (sm *SyncManager) SyncPeerID() uint64 {\n\treply := make(chan uint64)\n\tsm.msgChan <- getSyncPeerMsg{reply: reply}\n\treturn <-reply\n}",
"func (sm *SyncManager) SyncPeerID() uint64 {\n\treply := make(chan uint64)\n\tsm.msgChan <- getSyncPeerMsg{reply: reply}\n\treturn <-reply\n}",
"func (pi *PeerInfo) CodecEncodeSelf(enc *ucodec.Encoder) {\n\tb := pi.Block()\n\tenc.MustEncode(b)\n}",
"func (this *Protocol) GetMe() PeerId {\n\tifaces, err := net.Interfaces()\n\n\tif err != nil {\n\t\tLog.Warn.Println(err)\n\t}\n\n\tfor _, i := range ifaces {\n\t\taddrs, err := i.Addrs()\n\n\t\tif err == nil {\n\t\t\tfor _, addr := range addrs {\n\t\t\t\tswitch addr.(type) {\n\t\t\t\tcase *net.IPAddr:\n\t\t\t\t\treturn PeerId{Address: addr.String(), Port: this.port}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn PeerId{Address: \"127.0.0.1\", Port: this.port}\n}",
"func (c *Component) Self(ctx context.Context, s *live.Socket, event string, data interface{}) error {\n\treturn s.Self(ctx, c.Event(event), data)\n}",
"func (r *AccountDIDRegistry) GetSelfID() DID {\n\treturn r.GenesisAccountDID\n}",
"func (base *BaseProtocol) SendPeer(req *StreamRequest) error {\n\tstream, err := NewStream(base.Host, req.PeerID, req.MsgID...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer CloseStream(stream)\n\terr = WriteStream(req.Data, stream)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tCloseStream(stream)\n\treturn nil\n}",
"func (ac *authenticatedConnection) LocalPeer() peer.ID {\n\treturn ac.localPeerID\n}",
"func (i *Input) SenderKey() string {\n\treturn i.senderKey\n}",
"func (p *Peer) UID() uint64 {\n\thi := uint64(p.self.IPv4)\n\tlo := (uint64(p.self.Port) << 16) | uint64(uint16(p.initClusterVersion))\n\treturn (hi<<32 | lo)\n}",
"func (p *Peer) Name() string {\n\treturn p.name\n}",
"func (p *Peer) Name() string {\n\treturn p.name\n}",
"func (p *Peer) Name() string {\n\treturn p.name\n}",
"func (o *Links) SetSelf(v string) {\n\to.Self = v\n}",
"func (p *Peer) Name() string {\n\treturn p.mlist.LocalNode().Name\n}",
"func (c *Context) Self() *Pid {\n\treturn c.self\n}",
"func (s *State) SenderRatchetKey() ecc.ECPublicKeyable {\n\treturn s.senderChain.senderRatchetKeyPair.PublicKey()\n}",
"func NewSender(raw *tg.Client) *Sender {\n\treturn &Sender{\n\t\traw: raw,\n\t\trand: crypto.DefaultRand(),\n\t\tuploader: uploader.NewUploader(raw),\n\t\tresolver: peer.DefaultResolver(raw),\n\t}\n}",
"func (mph *MockPeerHandler) PeerID() string {\n\treturn \"\"\n}",
"func (p *peer) Send(chID byte, msgBytes []byte) bool {\r\n\tif !p.IsRunning() {\r\n\t\t// see Switch#Broadcast, where we fetch the list of peers and loop over\r\n\t\t// them - while we're looping, one peer may be removed and stopped.\r\n\t\treturn false\r\n\t} else if !p.hasChannel(chID) {\r\n\t\treturn false\r\n\t}\r\n\treturn p.mconn.Send(chID, msgBytes)\r\n}",
"func (p *Peer) ID() string {\n\treturn fmt.Sprintf(\"%s.%s\", p.Organization, p.Name)\n}",
"func (n *Node) Send(msg string) string {\n\tif (n.up == nil) {\n\t\tn.l.Printf(\"\\n sending:\\t%s\\n to:\\t\\tN/A\\n\", msg)\n\t\treturn \"\";\n\t}\n\tn.l.Printf(\"\\n sending:\\t%s\\n to:\\t\\t%s\\n\", msg, n.up.name)\n\treturn n.up.Listen(msg, n.name)\n}",
"func (sid *SessionID) EqualSender(b SessionID) bool {\n\tif bytes.Equal(sid.AddrSender.Bytes(), b.AddrSender.Bytes()) &&\n\t\tbytes.Equal(sid.NonceSender, b.NonceSender) &&\n\t\tbytes.Equal(sid.SidSenderPart, b.SidSenderPart) {\n\t\treturn true\n\t}\n\treturn false\n}",
"func (o *DashboardAllOfLinks) SetSelf(v string) {\n\to.Self = &v\n}",
"func (o NetworkAttachmentOutput) SelfLink() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *NetworkAttachment) pulumi.StringOutput { return v.SelfLink }).(pulumi.StringOutput)\n}",
"func (t *Transaction) Sender() util.Uint160 {\n\tif len(t.Signers) == 0 {\n\t\tpanic(\"transaction does not have signers\")\n\t}\n\treturn t.Signers[0].Account\n}",
"func (w *Wechaty) UserSelf() _interface.IContactSelf {\n\tuserID := w.puppet.SelfID()\n\treturn w.Contact().LoadSelf(userID)\n}",
"func (b *MessagesSendBuilder) PeerID(v int) *MessagesSendBuilder {\n\tb.Params[\"peer_id\"] = v\n\treturn b\n}",
"func GetSenderID(event *linebot.Event) string {\r\n\tswitch event.Source.Type {\r\n\tcase linebot.EventSourceTypeGroup:\r\n\t\treturn event.Source.GroupID\r\n\tcase linebot.EventSourceTypeRoom:\r\n\t\treturn event.Source.RoomID\r\n\tcase linebot.EventSourceTypeUser:\r\n\t\treturn event.Source.UserID\r\n\t}\r\n\tlog.Printf(\"Can not get sender id. type: %v\\n\", event.Source.Type)\r\n\treturn \"\"\r\n}",
"func (p *FakePeer) Identifier() string {\n\treturn p.id.Identifier()\n}",
"func (c *Chain) GetSelfVersion() uint64 {\n\treturn clienttypes.ParseChainID(c.ChainID())\n}",
"func (n *notifier) send(typ raftor.ClusterEventType, other *memberlist.Node) {\n\tn.n.Notify(raftor.ClusterChangeEvent{\n\t\tType: typ,\n\t\tMember: raftor.NewMember(n.hash(other), other.Meta),\n\t})\n}",
"func (nopBroadcaster) SendTo(*disco.Node, Message) error { return nil }",
"func NewSender() Sender {\n\treturn Sender{}\n}",
"func (s Keygen) SelfIndex() int {\n\treturn s.partyIDs.GetIndex(s.selfID)\n}",
"func (sid *SessionID) GenerateSenderPart(AddrSender types.Address) (err error) {\n\n\tif sid.Locked {\n\t\treturn fmt.Errorf(\"SessionId is locked for further changes\")\n\t}\n\n\tnonce, err := GenerateRandomNumber(sessionIDNonceSize)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsid.AddrSender = AddrSender\n\tsid.NonceSender = nonce\n\n\tsid.SidSenderPart = keystore.Keccak256(append(nonce, sid.AddrSender.Bytes()...))\n\treturn nil\n}",
"func Peer(target string) {\n\tserver.listen()\n\tserver.seenPeers[target] = struct{}{}\n\tserver.dial(target)\n\tserver.managePeers()\n}",
"func (p *FakePeer) Identifier() string {\n\treturn string(p.id)\n}",
"func (o NetworkAttachmentOutput) SelfLinkWithId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *NetworkAttachment) pulumi.StringOutput { return v.SelfLinkWithId }).(pulumi.StringOutput)\n}",
"func (h *Header) Sender() []byte {\n\treturn h.PubKeyBLS\n}",
"func (p *TCPPeer) id() uint32 {\n\treturn p.nonce\n}",
"func (s *State) SenderBaseKey() []byte {\n\tif s.senderBaseKey == nil {\n\t\treturn nil\n\t}\n\treturn s.senderBaseKey.Serialize()\n}",
"func (p *Preparer) SendIdentifier() error {\n\treturn p.Writer.SendIdentifier()\n}",
"func (bT *BitTorrent) GenPeerID() {\n\t// peerid := make([]byte, 20)\n\t// rand.Read(peerid)\n\tbT.PeerID = fmt.Sprintf(\"11111111111111111111\")\n}",
"func (n *Node) Send(msg string, toNode PPeer){\n\n wait, err := time.ParseDuration(\"3s\")\n Fatal(err)\n conn, err := net.DialTimeout(\"tcp\", toNode.GetAddr()+\":\"+toNode.GetPort(),wait)\n Fatal(err)\n buff := []byte(msg)\n fmt.Println(\"to send: %v\",msg)\n _,err2 := conn.Write(buff)\n Fatal(err2)\n defer conn.Close()\n\n}",
"func NewSender(accountManager eth.AccountManager) Sender {\n\treturn &sender{\n\t\taccountManager: accountManager,\n\t}\n}",
"func (c *Info) Self() string {\n\tc.RLock()\n\tself := c.SelfName\n\tc.RUnlock()\n\n\treturn self\n}",
"func (p *Pipe) AddSender() {\n\tp.senders++\n}",
"func sendUUIDToPlayer(id int64, client *Client) {\n\tmsg := protocol.CreatePlayerUUIDMessage(id)\n\tsendMessageToClient(msg, id)\n}",
"func (m *Manager) NodeName() ipfspeer.ID {\n\treturn m.self.NodeName()\n}",
"func (r *room) send(data interface{}, without proto.UID) {\n\tpeers := r.getPeers()\n\tfor id, p := range peers {\n\t\tif len(without) > 0 && id != without {\n\t\t\tif err := p.send(data); err != nil {\n\t\t\t\tlog.Errorf(\"send data to peer(%s) error: %v\", p.uid, err)\n\t\t\t}\n\t\t}\n\t}\n}",
"func NewNopSender() Sender {\n\treturn nopSenderInstance\n}",
"func (self *GateServer) RegisterSelfNet(handlerName string, HandlerFunc gorpc.HandlerNetFunc) {\n\tif self.IsRunning() {\n\t\tllog.Fatal(\"RegisterSelfNet error, igo has already started\")\n\t\treturn\n\t}\n\thandlerMap[handlerName] = \"GateServer\"\n\tself.RegisterGate(handlerName, HandlerFunc)\n}",
"func CloneSender(s send.Sender) {\n\tstd.CloneSender(s)\n}",
"func SetSender(s send.Sender) {\n\tstd.SetSender(s)\n}",
"func (u *User) SetSelf(value bool) {\n\tif value {\n\t\tu.Flags.Set(10)\n\t\tu.Self = true\n\t} else {\n\t\tu.Flags.Unset(10)\n\t\tu.Self = false\n\t}\n}",
"func TestGossipNoForwardSelf(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\n\tstopper := stop.NewStopper()\n\tdefer stopper.Stop(context.Background())\n\n\t// Shared cluster ID by all gossipers (this ensures that the gossipers\n\t// don't talk to servers from unrelated tests by accident).\n\tclusterID := uuid.MakeV4()\n\n\tlocal := startGossip(clusterID, 1, stopper, t, metric.NewRegistry())\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\t// Start one loopback client plus enough additional clients to fill the\n\t// incoming clients.\n\tpeers := []*Gossip{local}\n\tlocal.server.mu.Lock()\n\tmaxSize := local.server.mu.incoming.maxSize\n\tlocal.server.mu.Unlock()\n\tfor i := 0; i < maxSize; i++ {\n\t\tpeers = append(peers, startGossip(clusterID, roachpb.NodeID(i+2), stopper, t, metric.NewRegistry()))\n\t}\n\n\tfor _, peer := range peers {\n\t\tc := newClient(log.AmbientContext{Tracer: tracing.NewTracer()}, local.GetNodeAddr(), makeMetrics())\n\n\t\ttestutils.SucceedsSoon(t, func() error {\n\t\t\tconn, err := peer.rpcContext.GRPCUnvalidatedDial(c.addr.String()).Connect(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tstream, err := NewGossipClient(conn).Gossip(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := c.requestGossip(peer, stream); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Wait until the server responds, so we know we're connected.\n\t\t\t_, err = stream.Recv()\n\t\t\treturn err\n\t\t})\n\t}\n\n\tnumClients := len(peers) * 2\n\tdisconnectedCh := make(chan *client)\n\n\t// Start a few overflow peers and assert that they don't get forwarded to us\n\t// again.\n\tfor i := 0; i < numClients; i++ {\n\t\tlocal.server.mu.Lock()\n\t\tmaxSize := local.server.mu.incoming.maxSize\n\t\tlocal.server.mu.Unlock()\n\t\tpeer := startGossip(clusterID, roachpb.NodeID(i+maxSize+2), stopper, t, metric.NewRegistry())\n\n\t\tfor {\n\t\t\tlocalAddr := local.GetNodeAddr()\n\t\t\tc := newClient(log.AmbientContext{Tracer: tracing.NewTracer()}, localAddr, makeMetrics())\n\t\t\tpeer.mu.Lock()\n\t\t\tc.startLocked(peer, disconnectedCh, peer.rpcContext, stopper, peer.rpcContext.NewBreaker(\"\"))\n\t\t\tpeer.mu.Unlock()\n\n\t\t\tdisconnectedClient := <-disconnectedCh\n\t\t\tif disconnectedClient != c {\n\t\t\t\tt.Fatalf(\"expected %p to be disconnected, got %p\", c, disconnectedClient)\n\t\t\t} else if c.forwardAddr == nil {\n\t\t\t\t// Under high load, clients sometimes fail to connect for reasons\n\t\t\t\t// unrelated to the test, so we need to permit some.\n\t\t\t\tt.Logf(\"node #%d: got nil forwarding address\", peer.NodeID.Get())\n\t\t\t\tcontinue\n\t\t\t} else if *c.forwardAddr == *localAddr {\n\t\t\t\tt.Errorf(\"node #%d: got local's forwarding address\", peer.NodeID.Get())\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n}",
"func (c *Client) NodeID() uint64 { return c.nodeID }",
"func (h *Homebrew) Send(p *dmr.Packet) error {\n\tdata := buildData(p, h.ID)\n\tfor _, peer := range h.GetPeers() {\n\t\tif err := h.WriteToPeer(data, peer); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (*NotifyPeer) TypeID() uint32 {\n\treturn NotifyPeerTypeID\n}",
"func (s *Store) OurKeyID(ctx context.Context) string {\n\tfor _, r := range s.Recipients(ctx) {\n\t\tkl, err := s.crypto.FindIdentities(ctx, r)\n\t\tif err != nil || len(kl) < 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn kl[0]\n\t}\n\n\treturn \"\"\n}",
"func (s *State) SenderChainKey() session.ChainKeyable {\n\tchainKey := s.senderChain.chainKey\n\treturn chain.NewKey(kdf.DeriveSecrets, chainKey.Key(), chainKey.Index())\n}",
"func (m PublicMsg) RenderSelf(cfg UserConfig) string {\n\tif cfg.Theme == nil {\n\t\treturn fmt.Sprintf(\"[%s] %s\", m.from.Name(), m.body)\n\t}\n\treturn fmt.Sprintf(\"[%s] %s\", cfg.Theme.ColorName(m.from), m.body)\n}",
"func getSelfIP() string {\n\thost, _ := os.Hostname()\n\taddrs, _ := net.LookupIP(host)\n\tfor _, addr := range addrs {\n\t\tif ipv4 := addr.To4(); ipv4 != nil {\n\t\t\treturn ipv4.String()\n\t\t}\n\t}\n\treturn \"\"\n}",
"func (suite Suite) NewSender(pkR kem.PublicKey, info []byte) (*Sender, error) {\n\treturn &Sender{\n\t\tstate: state{Suite: suite, info: info},\n\t\tpkR: pkR,\n\t}, nil\n}",
"func Peer2PeerCCSend(client pb.WorkerClient, message []*pb.SimMessageStruct, id int) {\n\n\tfor len(message) > tools.RPCSendSize {\n\t\tslice := message[0:tools.RPCSendSize]\n\t\tmessage = message[tools.RPCSendSize:]\n\t\t_, err := client.SimSend(context.Background(), &pb.SimMessageRequest{Pair: slice})\n\t\tif err != nil {\n\t\t\tlog.Printf(\"send to %v error\\n\", id)\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tif len(message) != 0 {\n\t\t_, err := client.SimSend(context.Background(), &pb.SimMessageRequest{Pair: message})\n\t\tif err != nil {\n\t\t\tlog.Printf(\"send to %v error\\n\", id)\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}",
"func (n *Node) send(msg *message.Message) *NodeErr {\n\tif !n.IsConnected() {\n\t\t// Return an error if the current node is not connected\n\t\treturn ConnErr(\"node not connected\", nil)\n\t} else if msg.To == nil {\n\t\t// Return an error if no Message.To parameter is initialized\n\t\treturn InternalErr(\"no intended peer defined at provided message\", nil)\n\t}\n\n\tencMsg := msg.JSON()\n\tif encMsg == nil {\n\t\treturn ParseErr(\"error encoding message to JSON\", nil)\n\t}\n\tfor _, to := range msg.To {\n\t\tif !n.Members.Contains(to) {\n\t\t\t// Return an error if the current network does not contains the\n\t\t\t// Message.To peer provided\n\t\t\treturn ConnErr(\"target peer is not into the network\", nil)\n\t\t}\n\n\t\t// Encode message as a request and send it\n\t\treq, err := composeRequest(msg, to)\n\t\tif err != nil {\n\t\t\treturn ParseErr(\"error decoding request to message\", err)\n\t\t}\n\t\tif _, err := n.client.Do(req); err != nil {\n\t\t\treturn ConnErr(\"error trying to perform the request\", err)\n\t\t}\n\t}\n\treturn nil\n}",
"func NewSender(clusterInfo common.Cluster, index int64, queueLength int64, cmdbClient cmdb.ClientInterface) *Sender {\n\tqueue := make(chan PodEvent, queueLength)\n\treturn &Sender{\n\t\tclusterInfo: clusterInfo,\n\t\tindex: index,\n\t\tcmdbClient: cmdbClient,\n\t\tqueue: queue,\n\t}\n}",
"func Gossip_sender(b []byte, member MemberID) error {\n\tvar returnErr error\n\t// The message will be sent three times to promise followers can receive.\n\tfor i := 0; i < 3; i++ {\n\t\tconn, err := net.Dial(\"udp\", member.LocalIP+\":12345\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Gossip sending error\")\n\t\t}\n\t\tdefer conn.Close()\n\n\t\tconn.Write(b)\n\t\t// This avoids failures. If the other node doesn't reply in 0.03 second, it will temporarily be regarded as failed.\n\t\t// Once it succefully reply. Stop, I know you are alive.\n\t\tconn.SetReadDeadline(time.Now().Add(time.Millisecond * 30))\n\t\tbuf := make([]byte, 1024)\n\t\t_, err2 := conn.Read(buf)\n\n\t\tif err2 == nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturnErr = err2\n\t\t}\n\t\t// It will pause for 0.02 second in order to avoid a congestion.\n\t\ttime.Sleep(20 * time.Millisecond)\n\t}\n\treturn returnErr\n}",
"func (gs *GossipSenders) Sender(channelName string, makeGossipSender func(sender ProtocolSender, stop <-chan struct{}) *GossipSender) *GossipSender {\n\tgs.Lock()\n\tdefer gs.Unlock()\n\ts, found := gs.senders[channelName]\n\tif !found {\n\t\ts = makeGossipSender(gs.sender, gs.stop)\n\t\tgs.senders[channelName] = s\n\t}\n\treturn s\n}",
"func (c *Connection) Sender(addr string) (s Sender, err error) {\n\tsession, err := c.DefaultSession()\n\tif err != nil {\n\t\treturn Sender{}, err\n\t}\n\tresult := make(chan Sender)\n\tc.pump.Inject <- func() {\n\t\tlink := session.e.Sender(linkNames.Next())\n\t\tif link.IsNil() {\n\t\t\terr = session.e.Error()\n\t\t} else {\n\t\t\tlink.Target().SetAddress(addr)\n\t\t\t// FIXME aconway 2015-04-27: link options?\n\t\t\tlink.Open()\n\t\t}\n\t\tresult <- Sender{Link{c, link}}\n\t}\n\treturn <-result, err\n}",
"func (pc peerConn) ID() ID {\r\n\treturn PubKeyToID(pc.conn.(*tmconn.SecretConnection).RemotePubKey())\r\n}",
"func SendIDNEQ(v string) predicate.Block {\n\treturn predicate.Block(func(s *sql.Selector) {\n\t\ts.Where(sql.NEQ(s.C(FieldSendID), v))\n\t})\n}",
"func (f SingleWorkerID) Node() int64 {\n\treturn int64(f) & nodeMask >> nodeIdShift\n}",
"func NewSender(account accounts.Account, wallet accounts.Wallet, chainID *big.Int, client EthClient, txp GasPricer, interval time.Duration) *Sender {\n\treturn &Sender{\n\t\taccount: account,\n\t\twallet: wallet,\n\t\tchainID: chainID,\n\t\tclient: client,\n\t\ttxp: txp,\n\t\tsendInterval: interval,\n\t\tquit: make(chan struct{}),\n\t}\n}",
"func(peers *PeerList) Register(id int32) {\n\tpeers.mux.Lock()\n\tdefer peers.mux.Unlock()\n\tpeers.selfId = id\n\tfmt.Printf(\"SelfId=%v\\n\", id)\n}",
"func PeerLabel(fd uintptr) (string, error) {\n\treturn peerLabel(fd)\n}",
"func (peer *surveyorP) sender() {\n\tfor {\n\t\tif m := <-peer.q; m == nil {\n\t\t\tbreak\n\t\t} else {\n\t\t\tif peer.ep.SendMsg(m) != nil {\n\t\t\t\tm.Free()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}",
"func (sn *SelfNode) Sign(hash string) (string, error) {\n\t//return encryption.Sign(sn.privateKey, hash)\n\tsignScheme := zcncrypto.NewSignatureScheme(config.Configuration.SignatureScheme)\n\tif signScheme != nil {\n\t\terr := signScheme.SetPrivateKey(sn.wallet.Keys[0].PrivateKey)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn signScheme.Sign(hash)\n\t}\n\treturn \"\", common.NewError(\"invalid_signature_scheme\", \"Invalid signature scheme. Please check configuration\")\n}",
"func (m *MesosMessenger) Send(upid *upid.UPID, msg proto.Message) error {\n\tif upid.Equal(m.upid) {\n\t\treturn fmt.Errorf(\"Send the message to self\")\n\t}\n\tname := getMessageName(msg)\n\tlog.V(2).Infof(\"Sending message %v to %v\\n\", name, upid)\n\tm.encodingQueue <- &Message{upid, name, msg, nil}\n\treturn nil\n}",
"func (h *Homebrew) SendTG(p *dmr.Packet, peer *Peer) error {\n\tdata := buildData(p, h.ID)\n\tfor _, toPeer := range h.GetPeers() {\n\t\tif peer != nil && toPeer.ID == peer.ID { // skip self\n\t\t\tcontinue\n\t\t}\n\n\t\tif toPeer.TGID == p.DstID {\n\t\t\tlog.Debugf(\"Send TG%d -> %d\\n\", p.DstID, toPeer.ID)\n\t\t\tif err := h.WriteToPeer(data, toPeer); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (peer *peerImp) Equal(otherPeer Peer) bool {\n\treturn peer.id.Equal(otherPeer.GetID())\n}"
] | [
"0.6930513",
"0.64074606",
"0.63443226",
"0.57489425",
"0.5732687",
"0.5613707",
"0.55759853",
"0.5575605",
"0.5523199",
"0.5497619",
"0.5484814",
"0.54718083",
"0.54717785",
"0.5465559",
"0.5460933",
"0.54066104",
"0.5406515",
"0.53827614",
"0.5382286",
"0.5346614",
"0.5346614",
"0.5337081",
"0.5308806",
"0.5296137",
"0.52957094",
"0.5290653",
"0.5282359",
"0.5261395",
"0.52554744",
"0.52312106",
"0.52312106",
"0.52312106",
"0.52198505",
"0.521033",
"0.5193529",
"0.51895595",
"0.51810545",
"0.5158217",
"0.5150339",
"0.51441145",
"0.51333004",
"0.5111441",
"0.511093",
"0.50916463",
"0.5081613",
"0.50810707",
"0.50693107",
"0.5064279",
"0.50590974",
"0.5044415",
"0.5039423",
"0.5036912",
"0.5028548",
"0.5025059",
"0.50210303",
"0.5018395",
"0.5018253",
"0.50157106",
"0.50139713",
"0.5012454",
"0.4998578",
"0.49861723",
"0.49817255",
"0.49770603",
"0.49763137",
"0.49691778",
"0.49634135",
"0.49627078",
"0.49608052",
"0.49562398",
"0.49559486",
"0.49484962",
"0.49384654",
"0.49248815",
"0.49247113",
"0.49123433",
"0.49115306",
"0.49072832",
"0.48988128",
"0.48987105",
"0.4893665",
"0.48831776",
"0.48822972",
"0.48788396",
"0.4878325",
"0.4870703",
"0.4869833",
"0.4862733",
"0.48626927",
"0.48608473",
"0.48558858",
"0.48527187",
"0.4846515",
"0.4842748",
"0.48352078",
"0.48276094",
"0.48232597",
"0.48171708",
"0.4810743",
"0.4807266",
"0.48052567"
] | 0.0 | -1 |
PubKey implements peering.PeerSender for the Self() node. | func (n *NetImpl) PubKey() kyber.Point {
return n.nodeKeyPair.Public
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (sc *SecretConnection) RemotePubKey() crypto.PubKey {\n\treturn sc.remPubKey\n}",
"func (nodeKey *NodeKey) PubKey() crypto.PubKey {\n\treturn nodeKey.PrivKey.PubKey()\n}",
"func (a *managedAddress) ExportPubKey() string {\n\treturn hex.EncodeToString(a.pubKeyBytes())\n}",
"func (pb *PutBlock) ProducerPublicKey() crypto.PublicKey { return pb.SrcPubkey() }",
"func (obj *MessengerUser) PublicKey() (foundation.PublicKey, error) {\n\tproxyResult := /*pr4*/ C.vssq_messenger_user_public_key(obj.cCtx)\n\n\truntime.KeepAlive(obj)\n\n\treturn foundation.ImplementationWrapPublicKeyCopy(unsafe.Pointer(proxyResult)) /* r4.1 */\n}",
"func (k otherKey) Public() crypto.PublicKey {\n\treturn nil\n}",
"func (s *State) SenderRatchetKey() ecc.ECPublicKeyable {\n\treturn s.senderChain.senderRatchetKeyPair.PublicKey()\n}",
"func (s Sig) PublicKey() ([]byte, error) {\n\treturn nil, fmt.Errorf(\"not implemented\")\n}",
"func TstBasePubKey(pub1, pub2 *wire.PubKey) *SimplePubKey {\n\treturn &SimplePubKey{\n\t\theader: wire.NewObjectHeader(\n\t\t\t123123, // 0x1e0f3\n\t\t\ttime.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST)\n\t\t\twire.ObjectTypePubKey,\n\t\t\t2,\n\t\t\t1),\n\t\tdata: &PubKeyData{\n\t\t\tBehavior: 0,\n\t\t\tVerification: pub1,\n\t\t\tEncryption: pub2,\n\t\t},\n\t}\n}",
"func (_BondedECDSAKeep *BondedECDSAKeepCallerSession) PublicKey() ([]byte, error) {\n\treturn _BondedECDSAKeep.Contract.PublicKey(&_BondedECDSAKeep.CallOpts)\n}",
"func (s Keygen) SelfID() party.ID {\n\treturn s.selfID\n}",
"func (c *ClientConn) RemotePK() cipher.PubKey { return c.remoteSrv }",
"func GeneratePubKey(ctx *Context, seckey PrivKey) (int, []byte, error) {\n\tif len(seckey) != PrivateKeyLength {\n\t\treturn 0, nil, errors.New(PrivateKeySizeError)\n\t}\n\n\tvar pubkey = make([]byte, 64)\n\tvar pubkeyPtr *C.secp256k1_pubkey = (*C.secp256k1_pubkey)(unsafe.Pointer(&pubkey[0]))\n\n\tresult := int(C.secp256k1_ec_pubkey_create(ctx.ctx, pubkeyPtr, cBuf(seckey[:])))\n\tif result != 1 {\n\t\treturn result, nil, errors.New(PublicKeyCreateError)\n\t}\n\n\treturn result, pubkey, nil\n}",
"func (t Trade) FindPubKey(user *User) (pubKey SCAddr, error errstack.E) {\n\ttp, err := t.FindParticipant(user)\n\tif err != nil {\n\t\treturn \"\", errstack.WrapAsInfF(err, \"Key not found\")\n\t}\n\treturn SCAddr(tp.PubKey), nil\n}",
"func HashPubKey(pubKey []byte) []byte {\n\tpublicSHA256 := sha256.Sum256(pubKey)\n\tRIPEMD160Hasher := ripemd160.New()\n\t_, err := RIPEMD160Hasher.Write(publicSHA256[:])\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tpublicRIPEMD160 := RIPEMD160Hasher.Sum(nil)\n\treturn publicRIPEMD160\n}",
"func HashPubKey(pubKey []byte) []byte {\n\tpublicSHA256 := sha256.Sum256(pubKey)\n\n\tRIPEMD160Hasher := ripemd160.New()\n\tif _, err := RIPEMD160Hasher.Write(publicSHA256[:]); err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tpublicRIPEMD160 := RIPEMD160Hasher.Sum(nil)\n\treturn publicRIPEMD160\n}",
"func (pk PublicKey) Encode() []byte {\n\treturn pk.publicKey.Encode()\n}",
"func (n *Node) Send(PubKey []byte, privKey ecdsa.PrivateKey, to string, amount float64) ([]byte, error) {\n\t// get pubkey of the wallet with \"from\" address\n\tif to == \"\" {\n\t\treturn nil, errors.New(\"Recipient address is not provided\")\n\t}\n\tw := wallet.Wallet{}\n\n\tif !w.ValidateAddress(to) {\n\t\treturn nil, errors.New(\"Recipient address is not valid\")\n\t}\n\n\ttx, err := n.GetTransactionsManager().CreateTransaction(PubKey, privKey, to, amount)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn.SendTransactionToAll(tx)\n\n\treturn tx.ID, nil\n}",
"func (_BondedECDSAKeep *BondedECDSAKeepSession) PublicKey() ([]byte, error) {\n\treturn _BondedECDSAKeep.Contract.PublicKey(&_BondedECDSAKeep.CallOpts)\n}",
"func (a *Account) PublicKey() *PubKey {\n\tk := new(PubKey)\n\tcopy(k[:], a.pub[:])\n\treturn k\n}",
"func (s NativeSigner) PublicKey() ([]byte, error) {\n\tkeybuf := new(bytes.Buffer)\n\tif err := (*openpgp.Entity)(&s).Serialize(keybuf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn keybuf.Bytes(), nil\n}",
"func (s Keygen) PublicKey() *ecdsa.PublicKey {\n\treturn nil\n}",
"func (h *Header) Sender() []byte {\n\treturn h.PubKeyBLS\n}",
"func (ss StdSignature) GetPubKey() cryptotypes.PubKey {\n\treturn ss.PubKey\n}",
"func (pv *ThresholdValidator) GetPubKey() (crypto.PubKey, error) {\n\treturn pv.pubkey, nil\n}",
"func (pubKey *PubKey) AsTmPubKey() crypto.PubKey {\n\tvar pubkey tmsm2.PubKeySm2\n\tcopy(pubkey[:], pubKey.Key)\n\treturn pubkey\n}",
"func (n NodeID) Pubkey() (*ecdsa.PublicKey, error) {\n\tp := &ecdsa.PublicKey{Curve: crypto.S256(), X: new(big.Int), Y: new(big.Int)}\n\thalf := len(n) / 2\n\tp.X.SetBytes(n[:half])\n\tp.Y.SetBytes(n[half:])\n\tif !p.Curve.IsOnCurve(p.X, p.Y) {\n\t\treturn nil, errors.New(\"id is invalid secp256k1 curve point\")\n\t}\n\treturn p, nil\n}",
"func (c *publicKey) Encode() (*pb.PublicKey, error) {\n\tif c.ki == nil {\n\t\treturn nil, ErrPublicKeyCannotBeNil()\n\t}\n\n\tblob, err := crypto.MarshalPublicKey(c.ki)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpbuf := pb.PublicKey{Blob: blob}\n\n\treturn &pbuf, nil\n}",
"func HashPubKey(pubKey []byte) []byte {\n\tpubKeyHash256 := sha256.Sum256(pubKey)\n\n\tRIPEMD160Hasher := ripemd160.New()\n\t_, err := RIPEMD160Hasher.Write(pubKeyHash256[:])\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\n\treturn RIPEMD160Hasher.Sum(nil)\n}",
"func (privKey *YubiHsmPrivateKey) exportPubKey() error {\n\t// send getpubkey command\n\tcmd, err := commands.CreateGetPubKeyCommand(privKey.privKeyID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp, err := privKey.sessionMgr.SendEncryptedCommand(cmd)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t// parse public key from response\n\tparsedResp, matched := resp.(*commands.GetPubKeyResponse)\n\tif !matched {\n\t\treturn errors.New(\"Invalid response for exporting public key\")\n\t}\n\n\tif privKey.yubiHsmParams.PrivKeyType == YubiHsmPrivKeyTypeEd25519 {\n\t\terr = privKey.exportEd25519Pubkey(parsedResp.KeyData)\n\t} else {\n\t\terr = privKey.exportSecp256k1Pubkey(parsedResp.KeyData)\n\t}\n\n\treturn err\n}",
"func (_BondedECDSAKeep *BondedECDSAKeepCaller) PublicKey(opts *bind.CallOpts) ([]byte, error) {\n\tvar (\n\t\tret0 = new([]byte)\n\t)\n\tout := ret0\n\terr := _BondedECDSAKeep.contract.Call(opts, out, \"publicKey\")\n\treturn *ret0, err\n}",
"func (i *Input) SenderKey() string {\n\treturn i.senderKey\n}",
"func GeneratePubKey(privateKeyBytes []byte) ([]byte, error) {\n\tvar privateKeyBytes32 [size]byte\n\tfor i := 0; i < size; i++ {\n\t\tprivateKeyBytes32[i] = privateKeyBytes[i]\n\t}\n\tsecp256k1.Start()\n\tpublicKeyBytes, success := secp256k1.Pubkey_create(privateKeyBytes32, false)\n\tsecp256k1.Stop()\n\n\tif !success {\n\t\treturn []byte{}, fmt.Errorf(\"Failed to generate public key\")\n\t}\n\treturn publicKeyBytes, nil\n}",
"func (k *Keypair) PublicKey() *PubKey {\n\tpub := new(PubKey)\n\tcopy(pub[:], k.pub[:])\n\treturn pub\n}",
"func (r *Resolver) SetPubKey(opts *bind.TransactOpts, x [32]byte, y [32]byte) (*types.Transaction, error) {\n\tnameHash, err := NameHash(r.domain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.Contract.SetPubkey(opts, nameHash, x, y)\n}",
"func (pk *PublicKey) Key() string {\n\treturn string(pk.PublicKeyHex.Value)\n}",
"func (s *SshConnection) GrabPubKey() {\n\tsshConfig := &ssh.ClientConfig{\n\t\tHostKeyCallback: s.verifyHostCallback(false),\n\t}\n\t// ignore return values here. I'm using it just to trigger the\n\t// verifyHostCallback\n\tssh.Dial(\"tcp\", s.serverEndpoint.String(), sshConfig)\n}",
"func (n Node) PublicKey() p2pcrypto.PublicKey {\n\treturn n.pubKey\n}",
"func (pkv PublicKeyValidator) Validate(key string, value []byte) (err error) {\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"DHT: Received invalid value for key %s: %s\", key, err.Error())\n\t\t} else {\n\t\t\tlog.Infof(\"DHT: Received valid value for key %s\", key)\n\t\t}\n\t}()\n\n\tpeerID, err := pkv.getPeerID(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar publicKey pb.PublicKey\n\terr = proto.Unmarshal(value, &publicKey)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tsignatureKey, err := crypto.UnmarshalPublicKey(publicKey.SignatureKey)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif !peerID.MatchesPublicKey(signatureKey) {\n\t\treturn errors.New(ErrInvalidSenderSignature)\n\t}\n\n\tsignature := publicKey.Signature\n\n\tpublicKey.SignatureKey = nil\n\tpublicKey.Signature = nil\n\n\tsignedBytes, err := proto.Marshal(&publicKey)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tok, err := signatureKey.Verify(signedBytes, signature)\n\tif err != nil {\n\t\treturn errors.Wrap(err, ErrInvalidSenderSignature)\n\t}\n\tif !ok {\n\t\treturn errors.New(ErrInvalidSenderSignature)\n\t}\n\n\t// No need to validate that the point is on the curve because we only use\n\t// curve25519 for now which has twist security.\n\t// If we support more elliptic curves, we might need to check here that the\n\t// public key received is a valid curve point.\n\n\treturn nil\n}",
"func TweakPubKey(pubKey *btcec.PublicKey, tweak []byte) *btcec.PublicKey {\n\n\tpath := getDerivationPathFromTweak(tweak) // get derivation path for tweak\n\n\t// set initial pubkey X/Y to current pubkey\n\tresX := pubKey.ToECDSA().X\n\tresY := pubKey.ToECDSA().Y\n\n\t// tweak pubkey for each path child\n\tfor _, pathChild := range path {\n\t\t// get tweaked pubkey\n\t\tresX, resY = tweakPubWithPathChild(pathChild, resX, resY)\n\t}\n\n\treturn (*btcec.PublicKey)(&ecdsa.PublicKey{btcec.S256(), resX, resY})\n}",
"func CtxPubKey(ctx context.Context) (crypto.PubKey, error) {\n\tif identity, ok := ctx.Value(contextKeyIdentity).([]byte); ok {\n\t\treturn crypto.UnmarshalEd25519PublicKeyProto(identity)\n\t}\n\treturn nil, ErrIdentityNotFoundInContext\n}",
"func (a *managedAddress) PubKey() chainec.PublicKey {\n\treturn a.pubKey\n}",
"func ProcessPubKey(acc Account, sig StdSignature, simulate bool) (crypto.PubKey, sdk.Result) {\n\t// If pubkey is not known for account, set it from the StdSignature.\n\tpubKey := acc.GetPubKey()\n\tif simulate {\n\t\t// In simulate mode the transaction comes with no signatures, thus if the\n\t\t// account's pubkey is nil, both signature verification and gasKVStore.Set()\n\t\t// shall consume the largest amount, i.e. it takes more gas to verify\n\t\t// secp256k1 keys than ed25519 ones.\n\t\tif pubKey == nil {\n\t\t\treturn simSecp256k1Pubkey, sdk.Result{}\n\t\t}\n\n\t\treturn pubKey, sdk.Result{}\n\t}\n\n\tif pubKey == nil {\n\t\tpubKey = sig.PubKey\n\t\tif pubKey == nil {\n\t\t\treturn nil, sdk.ErrInvalidPubKey(\"PubKey not found\").Result()\n\t\t}\n\n\t\tif !bytes.Equal(pubKey.Address(), acc.GetAddress()) {\n\t\t\treturn nil, sdk.ErrInvalidPubKey(\n\t\t\t\tfmt.Sprintf(\"PubKey does not match Signer address %s\", acc.GetAddress())).Result()\n\t\t}\n\t}\n\n\treturn pubKey, sdk.Result{}\n}",
"func (n *NetImpl) PeerByPubKey(peerPub kyber.Point) (peering.PeerSender, error) {\n\tfor i := range n.peers {\n\t\tpk := n.peers[i].PubKey()\n\t\tif pk != nil && pk.Equal(peerPub) {\n\t\t\treturn n.PeerByNetID(n.peers[i].NetID())\n\t\t}\n\t}\n\treturn nil, errors.New(\"known peer not found by pubKey\")\n}",
"func (k *PrivateKeySECP256K1R) PublicKey() PublicKey {\n\tif k.pk == nil {\n\t\tk.pk = &PublicKeySECP256K1R{pk: k.sk.PubKey()}\n\t}\n\treturn k.pk\n}",
"func (priv *PrivateKey) Public() crypto.PublicKey",
"func (priv *PrivateKey) Public() crypto.PublicKey",
"func NewPubKey() *PubKey {\n\tp := new(PubKey)\n\tp.newClient()\n\tp.load()\n\treturn p\n}",
"func NewPopulatedProtoPubKey(_ randyNet) *ProtoPubKey {\n\t_, k, _ := crypto.GenerateKeyPair(crypto.RSA, 512)\n\treturn &ProtoPubKey{PubKey: k}\n}",
"func (*PubKey) Descriptor() ([]byte, []int) {\n\treturn file_signalling_proto_rawDescGZIP(), []int{0}\n}",
"func (id NodesID) Pubkey() (*ecdsa.PublicKey, error) {\n\tp := &ecdsa.PublicKey{Curve: bgmcrypto.S256(), X: new(big.Int), Y: new(big.Int)}\n\thalf := len(id) / 2\n\tptr.X.SetBytes(id[:half])\n\tptr.Y.SetBytes(id[half:])\n\tif !ptr.Curve.IsOnCurve(ptr.X, ptr.Y) {\n\t\treturn nil, errors.New(\"id is invalid secp256k1 curve point\")\n\t}\n\treturn p, nil\n}",
"func (o PlaybackKeyPairOutput) PublicKey() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PlaybackKeyPair) pulumi.StringOutput { return v.PublicKey }).(pulumi.StringOutput)\n}",
"func (party *EcdsaParty) EncPub() *paillier.PubKey {\n\treturn party.encpub\n}",
"func (mph *MockPeerHandler) GetRemotePubKey(id peer2.ID) (libp2pcry.PubKey, error) {\n\treturn nil, nil\n}",
"func (s *State) SenderBaseKey() []byte {\n\tif s.senderBaseKey == nil {\n\t\treturn nil\n\t}\n\treturn s.senderBaseKey.Serialize()\n}",
"func (kb *Keybase) ExportPubKey(name string) (armor string, err error) {\n\tkb.mx.Lock()\n\tdefer kb.mx.Unlock()\n\treturn kb.kb.ExportPubKey(name)\n}",
"func (c *MsgConnection) RemotePublicKey() p2pcrypto.PublicKey {\n\treturn c.remotePub\n}",
"func computePubKey(pubA, pubR [33]byte, msg []byte) ([33]byte, error) {\n\tvar returnValue [33]byte\n\n\t// Hardcode curve\n\tcurve := btcec.S256()\n\n\tA, err := btcec.ParsePubKey(pubA[:], curve)\n\tif err != nil {\n\t\treturn returnValue, err\n\t}\n\n\tR, err := btcec.ParsePubKey(pubR[:], curve)\n\tif err != nil {\n\t\treturn returnValue, err\n\t}\n\n\t// e = Hash(messageType, oraclePubQ)\n\tvar hashInput []byte\n\thashInput = append(msg, R.X.Bytes()...)\n\te := chainhash.HashB(hashInput)\n\n\tbigE := new(big.Int).SetBytes(e)\n\n\tif bigE.Cmp(curve.N) >= 0 {\n\t\treturn returnValue, fmt.Errorf(\"hash of (msg, pubR) too big\")\n\t}\n\n\t// e * B\n\tA.X, A.Y = curve.ScalarMult(A.X, A.Y, e)\n\n\tA.Y.Neg(A.Y)\n\n\tA.Y.Mod(A.Y, curve.P)\n\n\tP := new(btcec.PublicKey)\n\n\t// add to R\n\tP.X, P.Y = curve.Add(A.X, A.Y, R.X, R.Y)\n\tcopy(returnValue[:], P.SerializeCompressed())\n\treturn returnValue, nil\n}",
"func (a *Address) Encode(w io.Writer) error {\n\tpk, ok := a.PubKey.(*secp256k1.PubKey)\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"wrong type: %T\", a.PubKey))\n\t}\n\treturn cio.WriteBytesUint16(w, pk.Key)\n}",
"func (pubKey PubKeySecp256k1Eth) KeyString() string {\n\treturn fmt.Sprintf(\"%X\", pubKey[:])\n}",
"func (e ScoreProposal) Sender() []byte {\n\treturn e.Identity\n}",
"func (w *wrappedMultiSignerVerifier) PublicKey(opts ...signature.PublicKeyOption) (crypto.PublicKey, error) {\n\treturn w.signer.PublicKey(opts...)\n}",
"func (priv ECDHPrivate) PublicKey() ECDHPublic {\n\ttoret := make([]byte, ECDHKeyLength)\n\tC.crypto_scalarmult_base((*C.uchar)(&toret[0]),\n\t\t(*C.uchar)(&priv[0]))\n\treturn toret\n}",
"func (pk PrivateKey) PublicKey() hotstuff.PublicKey {\n\treturn pk.Public()\n}",
"func (*ZkPubKey) Descriptor() ([]byte, []int) {\n\treturn file_witness_proto_rawDescGZIP(), []int{2}\n}",
"func (x *X25519) SharedKey(peerPublicKey []byte) (sharedKey []byte, err error) {\n\tif len(peerPublicKey) != 32 {\n\t\treturn nil, errors.New(\"peer's public key's lenght is not 32\")\n\t}\n\n\tvar theirPublicKey [32]byte\n\tcopy(theirPublicKey[:], peerPublicKey)\n\tsharedKey, err = curve25519.X25519(x.privateKey[:], theirPublicKey[:])\n\treturn\n}",
"func (privKey PrivKeyEd25519) PubKey() PubKey {\n\tprivKeyBytes := [64]byte(privKey)\n\tinitialized := false\n\t// If the latter 32 bytes of the privkey are all zero, compute the pubkey\n\t// otherwise privkey is initialized and we can use the cached value inside\n\t// of the private key.\n\tfor _, v := range privKeyBytes[32:] {\n\t\tif v != 0 {\n\t\t\tinitialized = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif initialized {\n\t\tvar pubkeyBytes [32]byte\n\t\tcopy(pubkeyBytes[:], privKeyBytes[32:])\n\t\treturn PubKeyEd25519(pubkeyBytes)\n\t}\n\n\tpubBytes := *MakePublicKey(&privKeyBytes)\n\treturn PubKeyEd25519(pubBytes)\n}",
"func TstBaseGetPubKey() *GetPubKey {\n\treturn &GetPubKey{\n\t\theader: wire.NewObjectHeader(\n\t\t\t123123, // 0x1e0f3\n\t\t\ttime.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST)\n\t\t\twire.ObjectTypeGetPubKey,\n\t\t\t3,\n\t\t\t1),\n\t\tRipe: &hash.Ripe{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\tTag: nil,\n\t}\n}",
"func (obj *key) Key() rsa.PublicKey {\n\treturn obj.ky\n}",
"func (_Authority *AuthoritySession) MarkPubKeyAsUsed(pubKey string, sender common.Address) (*types.Transaction, error) {\n\treturn _Authority.Contract.MarkPubKeyAsUsed(&_Authority.TransactOpts, pubKey, sender)\n}",
"func (d Dispatcher) PublicKey() string {\n\treturn d.GetPubString()\n}",
"func (pubKey PubKeySecp256k1) KeyString() string {\n\treturn Fmt(\"%X\", pubKey[:])\n}",
"func (k *RSAPubKey) Key() crypto.PublicKey {\n\treturn k.key\n}",
"func (ac *authenticatedConnection) RemotePublicKey() libp2pcrypto.PubKey {\n\treturn ac.remotePeerPublicKey\n}",
"func (r GetPublicKeyRequest) Send(ctx context.Context) (*GetPublicKeyResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &GetPublicKeyResponse{\n\t\tGetPublicKeyOutput: r.Request.Data.(*GetPublicKeyOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}",
"func ToCmtPubKeyInterface(pk cryptotypes.PubKey) (cmtcrypto.PubKey, error) {\n\ttmProtoPk, err := ToCmtProtoPublicKey(pk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn encoding.PubKeyFromProto(tmProtoPk)\n}",
"func (s *SessionService) GetPubKey() (*PubKeyShare, error) {\n\tkey, e := ioutil.ReadFile(s.KeyPath + \".pub\")\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\thash, e := SSH.GetKeyHash(key)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tmnemonic, e := SSH.MakeMnemonic(key)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\n\tpk := PubKeyShare{\n\t\tKey: string(key),\n\t\tHash: base64.RawStdEncoding.EncodeToString(hash),\n\t\tMnemonic: mnemonic,\n\t}\n\treturn &pk, nil\n}",
"func (k *EdX25519Key) PublicKey() *EdX25519PublicKey {\n\treturn k.publicKey\n}",
"func PublicKey(priv keyconf.Key) (keyconf.Key, error) {\n\tif priv.Type != keyconf.PrivateKey {\n\t\treturn keyconf.Key{}, serrors.New(\"provided key is not a private key\", \"type\", priv.Type)\n\t}\n\traw, err := scrypto.GetPubKey(priv.Bytes, priv.Algorithm)\n\tif err != nil {\n\t\treturn keyconf.Key{}, serrors.WrapStr(\"error generating public key\", err)\n\t}\n\tkey := keyconf.Key{\n\t\tID: keyconf.ID{\n\t\t\tUsage: priv.Usage,\n\t\t\tIA: priv.IA,\n\t\t\tVersion: priv.Version,\n\t\t},\n\t\tType: keyconf.PublicKey,\n\t\tAlgorithm: priv.Algorithm,\n\t\tValidity: priv.Validity,\n\t\tBytes: raw,\n\t}\n\treturn key, nil\n}",
"func (priv *PKCS11PrivateKeyECDSA) Public() crypto.PublicKey {\n\treturn priv.key.PubKey\n}",
"func (x *X25519) PublicKey() []byte {\n\treturn x.publicKey[:]\n}",
"func (_Contract *ContractCallerSession) Pubkey(node [32]byte) (struct {\n\tX [32]byte\n\tY [32]byte\n}, error) {\n\treturn _Contract.Contract.Pubkey(&_Contract.CallOpts, node)\n}",
"func (sk *PrivKey) PubKey() PubKey {\n\treturn PubKey{sk.PublicKey, nil}\n}",
"func (k PublicKey) String() string {\n\treturn hexutil.Encode(k[:])\n}",
"func dcrm_genPubKey(msgprex string,account string,cointype string,ch chan interface{}, mode string,nonce string) {\n\n fmt.Println(\"========dcrm_genPubKey============\")\n\n wk,err := FindWorker(msgprex)\n if err != nil || wk == nil {\n\tres := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:no find worker\",Err:err}\n\tch <- res\n\treturn\n }\n id := wk.id\n \n GetEnodesInfo(wk.groupid)\n\n if int32(Enode_cnts) != int32(NodeCnt) {\n\tres := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:group is not ready\",Err:GetRetErr(ErrGroupNotReady)}\n\tch <- res\n\treturn\n }\n\n if types.IsDefaultED25519(cointype) {\n\tok2 := KeyGenerate_ed(msgprex,ch,id,cointype)\n\tif ok2 == false {\n\t return\n\t}\n\n\titertmp := workers[id].edpk.Front()\n\tif itertmp == nil {\n\t logs.Debug(\"get workers[id].edpk fail.\")\n\t res := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:get workers[id].edpk fail\",Err:GetRetErr(ErrGetGenPubkeyFail)}\n\t ch <- res\n\t return\n\t}\n\tsedpk := []byte(itertmp.Value.(string))\n\n\titertmp = workers[id].edsave.Front()\n\tif itertmp == nil {\n\t logs.Debug(\"get workers[id].edsave fail.\")\n\t res := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:get workers[id].edsave fail\",Err:GetRetErr(ErrGetGenSaveDataFail)}\n\t ch <- res\n\t return\n\t}\n\t\n\tsedsave := itertmp.Value.(string)\n\tpubs := &PubKeyData{Pub:string(sedpk),Save:sedsave,Nonce:\"0\",GroupId:wk.groupid,LimitNum:wk.limitnum,Mode:mode}\n\tepubs,err := Encode2(pubs)\n\tif err != nil {\n\t res := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:encode PubKeyData fail in req ed pubkey\",Err:err}\n\t ch <- res\n\t return\n\t}\n\t\n\tss,err := Compress([]byte(epubs))\n\tif err != nil {\n\t res := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:compress PubKeyData fail in req ed pubkey\",Err:err}\n\t ch <- res\n\t return\n\t}\n\n\t////TODO\n\tAllAccounts = append(AllAccounts,pubs)\n\t////////\n\n\tpubkeyhex := hex.EncodeToString(sedpk)\n\tfmt.Println(\"===============dcrm_genPubKey,pubkey = %s,nonce =%s ==================\",pubkeyhex,nonce)\n\t////save to db\n\t////add for req addr\n\t/*reqnonce,_,err := GetReqAddrNonce(account)\n\tif err != nil {\n\t reqnonce = \"0\"\n\t}\n\tSetReqAddrNonce(account,reqnonce)*/\n\tkey2 := Keccak256Hash([]byte(strings.ToLower(account))).Hex()\n\tkd := KeyData{Key:[]byte(key2),Data:nonce}\n\tPubKeyDataChan <-kd\n\n\t/////\n\tLdbPubKeyData[key2] = []byte(nonce)\n\t//key2 = Keccak256Hash([]byte(strings.ToLower(account+\":\"+\"LOCKOUT\"))).Hex()\n\t//LdbPubKeyData[key2] = []byte(\"0\")\n\t////\n\n\ttip,reply := AcceptReqAddr(account,cointype,wk.groupid,nonce,wk.limitnum,mode,true,\"true\",\"Success\",pubkeyhex,\"\",\"\",\"\")\n\tif reply != nil {\n\t res := RpcDcrmRes{Ret:\"\",Tip:tip,Err:fmt.Errorf(\"update req addr status error.\")}\n\t ch <- res\n\t return\n\t}\n \n\tif !strings.EqualFold(cointype, \"ALL\") {\n\t h := cryptocoins.NewCryptocoinHandler(cointype)\n\t if h == nil {\n\t\tres := RpcDcrmRes{Ret:\"\",Tip:\"cointype is not supported\",Err:fmt.Errorf(\"req addr fail,cointype is not supported.\")}\n\t\tch <- res\n\t\treturn\n\t }\n\n\t ctaddr, err := h.PublicKeyToAddress(pubkeyhex)\n\t if err != nil {\n\t\tres := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:get dcrm addr fail from pubkey:\"+pubkeyhex,Err:err}\n\t\tch <- res\n\t\treturn\n\t }\n\n\t //add for lockout\n\t kd = KeyData{Key:sedpk[:],Data:ss}\n\t PubKeyDataChan <-kd\n\t /////\n\t LdbPubKeyData[string(sedpk[:])] = []byte(ss)\n\t ////\n\n\t key := Keccak256Hash([]byte(strings.ToLower(account + \":\" + cointype))).Hex()\n\t kd = KeyData{Key:[]byte(key),Data:ss}\n\t PubKeyDataChan <-kd\n\t /////\n\t LdbPubKeyData[key] = []byte(ss)\n\t ////\n\n\t key = Keccak256Hash([]byte(strings.ToLower(ctaddr))).Hex()\n\t kd = KeyData{Key:[]byte(key),Data:ss}\n\t PubKeyDataChan <-kd\n\t /////\n\t LdbPubKeyData[key] = []byte(ss)\n\t ////\n\n\t /*lock.Lock()\n\t dir := GetDbDir()\n\t db,err := ethdb.NewLDBDatabase(dir, 0, 0)\n\t if err != nil { \n\t\tlock.Unlock()\n\t\tres := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:open level db fail\",Err:err}\n\t\tch <- res\n\t\treturn\n\t }\n\n\t h := cryptocoins.NewCryptocoinHandler(cointype)\n\t if h == nil {\n\t\tdb.Close()\n\t\tlock.Unlock()\n\t\tres := RpcDcrmRes{Ret:\"\",Tip:\"cointype is not supported\",Err:fmt.Errorf(\"req addr fail,cointype is not supported.\")}\n\t\tch <- res\n\t\treturn\n\t }\n\n\t ctaddr, err := h.PublicKeyToAddress(pubkeyhex)\n\t if err != nil {\n\t\tdb.Close()\n\t\tlock.Unlock()\n\t\tres := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:get dcrm addr fail from pubkey:\"+pubkeyhex,Err:err}\n\t\tch <- res\n\t\treturn\n\t }\n\n\t //add for lockout\n\t db.Put(sedpk[:],[]byte(ss))\n\t key := Keccak256Hash([]byte(strings.ToLower(account + \":\" + cointype))).Hex()\n\t db.Put([]byte(key),[]byte(ss))\n\t key = Keccak256Hash([]byte(strings.ToLower(ctaddr))).Hex()\n\t db.Put([]byte(key),[]byte(ss))\n\t db.Close()\n\t lock.Unlock()*/\n\t} else {\n\t kd = KeyData{Key:sedpk[:],Data:ss}\n\t PubKeyDataChan <-kd\n\t /////\n\t LdbPubKeyData[string(sedpk[:])] = []byte(ss)\n\t ////\n\n\t key := Keccak256Hash([]byte(strings.ToLower(account + \":\" + cointype))).Hex()\n\t kd = KeyData{Key:[]byte(key),Data:ss}\n\t PubKeyDataChan <-kd\n\t /////\n\t LdbPubKeyData[key] = []byte(ss)\n\t ////\n\n\t for _, ct := range cryptocoins.Cointypes {\n\t\tif strings.EqualFold(ct, \"ALL\") {\n\t\t continue\n\t\t}\n\n\t\th := cryptocoins.NewCryptocoinHandler(ct)\n\t\tif h == nil {\n\t\t continue\n\t\t}\n\t\tctaddr, err := h.PublicKeyToAddress(pubkeyhex)\n\t\tif err != nil {\n\t\t continue\n\t\t}\n\t\t\n\t\tkey = Keccak256Hash([]byte(strings.ToLower(ctaddr))).Hex()\n\t\tkd = KeyData{Key:[]byte(key),Data:ss}\n\t\tPubKeyDataChan <-kd\n\t\t/////\n\t\tLdbPubKeyData[key] = []byte(ss)\n\t\t////\n\t }\n\t \n\t /*lock.Lock()\n\t dir := GetDbDir()\n\t db,err := ethdb.NewLDBDatabase(dir, 0, 0)\n\t if err != nil { \n\t\tlock.Unlock()\n\t\tres := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:open level db fail\",Err:err}\n\t\tch <- res\n\t\treturn\n\t }\n\n\t //add for lockout\n\t db.Put(sedpk[:],[]byte(ss))\n\t key := Keccak256Hash([]byte(strings.ToLower(account + \":\" + cointype))).Hex()\n\t db.Put([]byte(key),[]byte(ss))\n\t \n\t for _, ct := range cryptocoins.Cointypes {\n\t\tif strings.EqualFold(ct, \"ALL\") {\n\t\t continue\n\t\t}\n\n\t\th := cryptocoins.NewCryptocoinHandler(ct)\n\t\tif h == nil {\n\t\t continue\n\t\t}\n\t\tctaddr, err := h.PublicKeyToAddress(pubkeyhex)\n\t\tif err != nil {\n\t\t continue\n\t\t}\n\t\t\n\t\tkey = Keccak256Hash([]byte(strings.ToLower(ctaddr))).Hex()\n\t\tdb.Put([]byte(key),[]byte(ss))\n\t }\n\n\t db.Close()\n\t lock.Unlock()\n\t */\n\t}\n\n\tres := RpcDcrmRes{Ret:pubkeyhex,Tip:\"\",Err:nil}\n\tch <- res\n\treturn\n }\n \n ok := KeyGenerate_ec2(msgprex,ch,id,cointype)\n if ok == false {\n\treturn\n }\n\n iter := workers[id].pkx.Front()\n if iter == nil {\n\tres := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:get pkx fail in req ec2 pubkey\",Err:GetRetErr(ErrGetGenPubkeyFail)}\n\tch <- res\n\treturn\n }\n spkx := iter.Value.(string)\n pkx := new(big.Int).SetBytes([]byte(spkx))\n iter = workers[id].pky.Front()\n if iter == nil {\n\tres := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:get pky fail in req ec2 pubkey\",Err:GetRetErr(ErrGetGenPubkeyFail)}\n\tch <- res\n\treturn\n }\n spky := iter.Value.(string)\n pky := new(big.Int).SetBytes([]byte(spky))\n ys := secp256k1.S256().Marshal(pkx,pky)\n\n iter = workers[id].save.Front()\n if iter == nil {\n\tres := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:get save data fail in req ec2 pubkey\",Err:GetRetErr(ErrGetGenSaveDataFail)}\n\tch <- res\n\treturn\n }\n save := iter.Value.(string)\n pubs := &PubKeyData{Pub:string(ys),Save:save,Nonce:\"0\",GroupId:wk.groupid,LimitNum:wk.limitnum,Mode:mode}\n epubs,err := Encode2(pubs)\n if err != nil {\n\tres := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:encode PubKeyData fail in req ec2 pubkey\",Err:err}\n\tch <- res\n\treturn\n }\n \n ss,err := Compress([]byte(epubs))\n if err != nil {\n\tres := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:compress PubKeyData fail in req ec2 pubkey\",Err:err}\n\tch <- res\n\treturn\n }\n \n ////TODO\n AllAccounts = append(AllAccounts,pubs)\n ////////\n\n pubkeyhex := hex.EncodeToString(ys)\n fmt.Println(\"===============dcrm_genPubKey,pubkey = %s,nonce =%s ==================\",pubkeyhex,nonce)\n //tip, err := StorePubAccount(wk.groupid, pubkeyhex, mode)\n //fmt.Printf(\"==== dcrm_genPubKey() ====, StorePubAccount tip: %v, err: %v\\n\", tip, err)\n ////save to db\n \n ////add for req addr\n /*reqnonce,_,err := GetReqAddrNonce(account)\n if err != nil {\n\treqnonce = \"0\"\n }\n SetReqAddrNonce(account,reqnonce)*/\n key2 := Keccak256Hash([]byte(strings.ToLower(account))).Hex()\n kd := KeyData{Key:[]byte(key2),Data:nonce}\n PubKeyDataChan <-kd\n /////\n LdbPubKeyData[key2] = []byte(nonce)\n //key2 = Keccak256Hash([]byte(strings.ToLower(account+\":\"+\"LOCKOUT\"))).Hex()\n //LdbPubKeyData[key2] = []byte(\"0\")\n ////\n\n tip,reply := AcceptReqAddr(account,cointype,wk.groupid,nonce,wk.limitnum,mode,true,\"true\",\"Success\",pubkeyhex,\"\",\"\",\"\")\n if reply != nil {\n\tres := RpcDcrmRes{Ret:\"\",Tip:tip,Err:fmt.Errorf(\"update req addr status error.\")}\n\tch <- res\n\treturn\n }\n\n if !strings.EqualFold(cointype, \"ALL\") {\n\th := cryptocoins.NewCryptocoinHandler(cointype)\n\tif h == nil {\n\t res := RpcDcrmRes{Ret:\"\",Tip:\"cointype is not supported\",Err:fmt.Errorf(\"req addr fail,cointype is not supported.\")}\n\t ch <- res\n\t return\n\t}\n\n\tctaddr, err := h.PublicKeyToAddress(pubkeyhex)\n\tif err != nil {\n\t res := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:get dcrm addr fail from pubkey:\"+pubkeyhex,Err:err}\n\t ch <- res\n\t return\n\t}\n\t\n\tkd = KeyData{Key:ys,Data:ss}\n\tPubKeyDataChan <-kd\n\t/////\n\tLdbPubKeyData[string(ys)] = []byte(ss)\n\t////\n\n\tkey := Keccak256Hash([]byte(strings.ToLower(account + \":\" + cointype))).Hex()\n\tkd = KeyData{Key:[]byte(key),Data:ss}\n\tPubKeyDataChan <-kd\n\t/////\n\tLdbPubKeyData[key] = []byte(ss)\n\t////\n\n\tkey = Keccak256Hash([]byte(strings.ToLower(ctaddr))).Hex()\n\tkd = KeyData{Key:[]byte(key),Data:ss}\n\tPubKeyDataChan <-kd\n\t/////\n\tLdbPubKeyData[key] = []byte(ss)\n\t////\n\n\t/*lock.Lock()\n\tdir := GetDbDir()\n\tdb,err := ethdb.NewLDBDatabase(dir, 0, 0)\n\tif err != nil { \n\t lock.Unlock()\n\t res := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:open level db fail\",Err:err}\n\t ch <- res\n\t return\n\t}\n\n\th := cryptocoins.NewCryptocoinHandler(cointype)\n\tif h == nil {\n\t db.Close()\n\t lock.Unlock()\n\t res := RpcDcrmRes{Ret:\"\",Tip:\"cointype is not supported\",Err:fmt.Errorf(\"req addr fail,cointype is not supported.\")}\n\t ch <- res\n\t return\n\t}\n\n\tctaddr, err := h.PublicKeyToAddress(pubkeyhex)\n\tif err != nil {\n\t db.Close()\n\t lock.Unlock()\n\t res := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:get dcrm addr fail from pubkey:\"+pubkeyhex,Err:err}\n\t ch <- res\n\t return\n\t}\n\n\t//add for lockout\n\tdb.Put(ys,[]byte(ss))\n\tkey := Keccak256Hash([]byte(strings.ToLower(account + \":\" + cointype))).Hex()\n\tdb.Put([]byte(key),[]byte(ss))\n\tkey = Keccak256Hash([]byte(strings.ToLower(ctaddr))).Hex()\n\tdb.Put([]byte(key),[]byte(ss))\n\tdb.Close()\n\tlock.Unlock()*/\n } else {\n\tkd = KeyData{Key:ys,Data:ss}\n\tPubKeyDataChan <-kd\n\t/////\n\tLdbPubKeyData[string(ys)] = []byte(ss)\n\t////\n\n\tkey := Keccak256Hash([]byte(strings.ToLower(account + \":\" + cointype))).Hex()\n\tkd = KeyData{Key:[]byte(key),Data:ss}\n\tPubKeyDataChan <-kd\n\t/////\n\tLdbPubKeyData[key] = []byte(ss)\n\t////\n\n\tfor _, ct := range cryptocoins.Cointypes {\n\t if strings.EqualFold(ct, \"ALL\") {\n\t\tcontinue\n\t }\n\n\t h := cryptocoins.NewCryptocoinHandler(ct)\n\t if h == nil {\n\t\tcontinue\n\t }\n\t ctaddr, err := h.PublicKeyToAddress(pubkeyhex)\n\t if err != nil {\n\t\tcontinue\n\t }\n\t \n\t key = Keccak256Hash([]byte(strings.ToLower(ctaddr))).Hex()\n\t kd = KeyData{Key:[]byte(key),Data:ss}\n\t PubKeyDataChan <-kd\n\t /////\n\t LdbPubKeyData[key] = []byte(ss)\n\t ////\n\t}\n\t/*lock.Lock()\n\tdir := GetDbDir()\n\tdb,err := ethdb.NewLDBDatabase(dir, 0, 0)\n\tif err != nil { \n\t lock.Unlock()\n\t res := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:open level db fail\",Err:err}\n\t ch <- res\n\t return\n\t}\n\n\t//add for lockout\n\tdb.Put(ys,[]byte(ss))\n\tkey := Keccak256Hash([]byte(strings.ToLower(account + \":\" + cointype))).Hex()\n\tdb.Put([]byte(key),[]byte(ss))\n key = Keccak256Hash([]byte(strings.ToLower(pubkeyhex))).Hex()\n db.Put([]byte(key),[]byte(ss))\n\t\n\tfor _, ct := range cryptocoins.Cointypes {\n\t if strings.EqualFold(ct, \"ALL\") {\n\t\tcontinue\n\t }\n\n\t h := cryptocoins.NewCryptocoinHandler(ct)\n\t if h == nil {\n\t\tcontinue\n\t }\n\t ctaddr, err := h.PublicKeyToAddress(pubkeyhex)\n\t if err != nil {\n\t\tcontinue\n\t }\n\t \n\t key = Keccak256Hash([]byte(strings.ToLower(ctaddr))).Hex()\n\t db.Put([]byte(key),[]byte(ss))\n\t}\n\n\tdb.Close()\n\tlock.Unlock()\n\t*/\n }\n \n res := RpcDcrmRes{Ret:pubkeyhex,Tip:\"\",Err:nil}\n ch <- res\n}",
"func computePubKeyResponse(pubKey cryptoproto.PublicKey, err *privvalproto.RemoteSignerError) proto.Message {\n\treturn &privvalproto.PubKeyResponse{\n\t\tPubKey: pubKey,\n\t\tError: err,\n\t}\n}",
"func (tracker *PeerTracker) Self() peer.ID {\n\treturn tracker.self\n}",
"func (p PrivateKey) PublicKey() (PublicKey, error) {\n\tpub, err := curve25519.X25519(p, curve25519.Basepoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pub, nil\n}",
"func (_Authority *AuthorityTransactor) MarkPubKeyAsUsed(opts *bind.TransactOpts, pubKey string, sender common.Address) (*types.Transaction, error) {\n\treturn _Authority.contract.Transact(opts, \"markPubKeyAsUsed\", pubKey, sender)\n}",
"func (_Authority *AuthorityTransactorSession) MarkPubKeyAsUsed(pubKey string, sender common.Address) (*types.Transaction, error) {\n\treturn _Authority.Contract.MarkPubKeyAsUsed(&_Authority.TransactOpts, pubKey, sender)\n}",
"func (r *gorumsReplica) PublicKey() hotstuff.PublicKey {\n\treturn r.pubKey\n}",
"func (p *PrivateKey) PublicKey() *ecdsa.PublicKey {\n\treturn &p.privateKey.PublicKey\n}",
"func (d *SetCandidateOffData) SetPubKey(key string) (*SetCandidateOffData, error) {\n\tpubKey, err := wallet.PublicKeyToHex(key)\n\tif err != nil {\n\t\treturn d, err\n\t}\n\tcopy(d.PubKey[:], pubKey)\n\treturn d, nil\n}",
"func (p *pbft) getPubKey(nodeID string) []byte {\n\tkey, err := ioutil.ReadFile(\"Keys/\" + nodeID + \"/\" + nodeID + \"_RSA_PUB\")\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn key\n}",
"func (o SshPublicKeyOutput) Key() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SshPublicKey) pulumi.StringOutput { return v.Key }).(pulumi.StringOutput)\n}",
"func sharedKey(priv, peerPub key) key {\n\tk := newKey()\n\tbox.Precompute(k, peerPub, priv)\n\treturn k\n}",
"func (x *Ed25519Credentials) PublicKey() PublicKey {\n\n\treturn PublicKey{\n\t\tAlgorithm: AlgorithmEd25519,\n\t\tPublic: base64.URLEncoding.EncodeToString(x.Public[:]),\n\t}\n\n}",
"func ProcessPubKey(acc exported.Account, sig Signature) (crypto.PubKey, sdkTypes.Result) {\n\tvar pubKey crypto.PubKey\n\tif acc != nil {\n\t\tpubKey = acc.GetPubKey()\n\t}\n\n\tif pubKey == nil {\n\n\t\treturn sig.PubKey, sdkTypes.Result{}\n\t}\n\tif acc != nil {\n\t\tcryptoPubKey := pubKey\n\t\tif cryptoPubKey == nil {\n\t\t\treturn nil, sdkTypes.ErrInvalidPubKey(\"PubKey not found\").Result()\n\t\t}\n\n\t\tif !bytes.Equal(cryptoPubKey.Address(), acc.GetAddress()) {\n\t\t\treturn nil, sdkTypes.ErrInvalidPubKey(\n\t\t\t\tfmt.Sprintf(\"PubKey does not match Signer address %s\", acc.GetAddress())).Result()\n\t\t}\n\n\t\treturn cryptoPubKey, sdkTypes.Result{}\n\t}\n\treturn nil, sdkTypes.Result{}\n}",
"func (a *managedAddress) pubKeyBytes() []byte {\n\tif a.compressed {\n\t\treturn a.pubKey.SerializeCompressed()\n\t}\n\treturn a.pubKey.SerializeUncompressed()\n}",
"func (kt KeyType) PublicKey() string {\n\treturn fmt.Sprintf(\"%s.pub\", kt.KeyBaseName)\n}"
] | [
"0.65247667",
"0.6334864",
"0.63003254",
"0.6092385",
"0.60858333",
"0.6013932",
"0.59953606",
"0.5993877",
"0.5970155",
"0.59666383",
"0.59521925",
"0.5949898",
"0.5941018",
"0.5934174",
"0.59061396",
"0.58937126",
"0.58631766",
"0.5860115",
"0.5859469",
"0.5856147",
"0.58517176",
"0.5848716",
"0.58299655",
"0.5829178",
"0.580796",
"0.57732964",
"0.57705003",
"0.575999",
"0.5758999",
"0.5741027",
"0.57360125",
"0.5729134",
"0.5728543",
"0.5720914",
"0.57057077",
"0.5691288",
"0.5686177",
"0.5677732",
"0.5677223",
"0.5669561",
"0.56676936",
"0.5666883",
"0.56539",
"0.56493264",
"0.5645223",
"0.56419337",
"0.56419337",
"0.5622874",
"0.56109846",
"0.56103086",
"0.5608093",
"0.5604676",
"0.55816877",
"0.5574968",
"0.5570139",
"0.5567665",
"0.55567676",
"0.55359614",
"0.55220056",
"0.55154115",
"0.5506585",
"0.5497159",
"0.5492543",
"0.54890776",
"0.54884064",
"0.54846686",
"0.5472344",
"0.5471922",
"0.547036",
"0.5466754",
"0.54663205",
"0.5464786",
"0.54528457",
"0.54487175",
"0.54469407",
"0.5442292",
"0.54396594",
"0.5437979",
"0.5433824",
"0.5426322",
"0.542524",
"0.54232574",
"0.5414692",
"0.54146016",
"0.5413345",
"0.5412743",
"0.54081786",
"0.54062635",
"0.54050255",
"0.54042023",
"0.540099",
"0.5400662",
"0.53952396",
"0.53928745",
"0.5392695",
"0.5387991",
"0.53867525",
"0.53786266",
"0.5371021",
"0.53677946"
] | 0.57888806 | 25 |
SendMsg implements peering.PeerSender for the Self() node. | func (n *NetImpl) SendMsg(msg *peering.PeerMessage) {
// Don't go via the network, if sending a message to self.
n.events.Trigger(&peering.RecvEvent{
From: n.Self(),
Msg: msg,
})
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (peer *Peer) SendMsg(msg *InternalMsg) error {\n\tselect {\n\tcase peer.sendChan <- msg:\n\t\treturn nil\n\tcase <-peer.quitChan:\n\t\treturn fmt.Errorf(\"peer %s have stopped\", peer.GetAddr().ToString())\n\t}\n}",
"func (coord *Coordinator) SendMsg(source, counterparty *TestChain, counterpartyClientID string, msg sdk.Msg) error {\n\treturn coord.SendMsgs(source, counterparty, counterpartyClientID, []sdk.Msg{msg})\n}",
"func (m *MesosMessenger) Send(upid *upid.UPID, msg proto.Message) error {\n\tif upid.Equal(m.upid) {\n\t\treturn fmt.Errorf(\"Send the message to self\")\n\t}\n\tname := getMessageName(msg)\n\tlog.V(2).Infof(\"Sending message %v to %v\\n\", name, upid)\n\tm.encodingQueue <- &Message{upid, name, msg, nil}\n\treturn nil\n}",
"func (n *Node) send(msg *message.Message) *NodeErr {\n\tif !n.IsConnected() {\n\t\t// Return an error if the current node is not connected\n\t\treturn ConnErr(\"node not connected\", nil)\n\t} else if msg.To == nil {\n\t\t// Return an error if no Message.To parameter is initialized\n\t\treturn InternalErr(\"no intended peer defined at provided message\", nil)\n\t}\n\n\tencMsg := msg.JSON()\n\tif encMsg == nil {\n\t\treturn ParseErr(\"error encoding message to JSON\", nil)\n\t}\n\tfor _, to := range msg.To {\n\t\tif !n.Members.Contains(to) {\n\t\t\t// Return an error if the current network does not contains the\n\t\t\t// Message.To peer provided\n\t\t\treturn ConnErr(\"target peer is not into the network\", nil)\n\t\t}\n\n\t\t// Encode message as a request and send it\n\t\treq, err := composeRequest(msg, to)\n\t\tif err != nil {\n\t\t\treturn ParseErr(\"error decoding request to message\", err)\n\t\t}\n\t\tif _, err := n.client.Do(req); err != nil {\n\t\t\treturn ConnErr(\"error trying to perform the request\", err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (n *Node) Send(msg string) string {\n\tif (n.up == nil) {\n\t\tn.l.Printf(\"\\n sending:\\t%s\\n to:\\t\\tN/A\\n\", msg)\n\t\treturn \"\";\n\t}\n\tn.l.Printf(\"\\n sending:\\t%s\\n to:\\t\\t%s\\n\", msg, n.up.name)\n\treturn n.up.Listen(msg, n.name)\n}",
"func (i *Info) SendMsg(msg Models.Message, dest string) error {\n\tconnOut, err := net.DialTimeout(\"tcp\", i.IP+\":\"+dest, time.Duration(10)*time.Second)\n\tif err != nil {\n\t\tif _, ok := err.(net.Error); ok {\n\t\t\tfmt.Printf(\"Couldn't send go to %s:%s \\n\", i.IP, dest)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := json.NewEncoder(connOut).Encode(&msg); err != nil {\n\t\tfmt.Printf(\"Couldn't enncode message %v \\n\", msg)\n\t\treturn err\n\t}\n\treturn nil\n}",
"func (s *ClientStream) SendMsg(m interface{}) error {\n\treturn s.writeMessage(m, false)\n}",
"func (s *socket) SendMsg(m *protocol.Message) error {\n\ts.Lock()\n\tbestEffort := s.bestEffort\n\ttq := nilQ\n\tif bestEffort {\n\t\ttq = closedQ\n\t} else if s.sendExpire > 0 {\n\t\ttq = time.After(s.sendExpire)\n\t}\n\tif s.closed {\n\t\ts.Unlock()\n\t\treturn protocol.ErrClosed\n\t}\n\tif s.failNoPeers && len(s.pipes) == 0 {\n\t\ts.Unlock()\n\t\treturn protocol.ErrNoPeers\n\t}\n\tpq := s.noPeerQ\n\ts.Unlock()\n\n\tselect {\n\tcase <-pq:\n\t\treturn protocol.ErrNoPeers\n\tcase s.sendQ <- m:\n\tcase <-s.closeQ:\n\t\treturn protocol.ErrClosed\n\tcase <-tq:\n\t\tif bestEffort {\n\t\t\tm.Free()\n\t\t\treturn nil\n\t\t}\n\t\treturn protocol.ErrSendTimeout\n\t}\n\n\ts.Lock()\n\ts.cv.Signal()\n\ts.Unlock()\n\treturn nil\n}",
"func SendMsg(miningConn MiningConn, message *Message) {\n\tminingConn.Enc.Encode(message)\n}",
"func (c *Connection) SendMsg(msg *Message) error {\n\tc.SetWriteDeadline(CalDeadline(10))\n\tencoder := gob.NewEncoder(c)\n\terr := encoder.Encode(&msg)\n\treturn err\n}",
"func (n *Network) SendMessage(message Message) (err error) {\n\t//syncMutex.Lock()\n\t//defer syncMutex.Unlock()\n\n\tif message.To == n.Myself.ID {\n\t\tn.ReceiveChan <- message\n\t\treturn nil\n\t}\n\n\tmessageByte, err := json.Marshal(message) //func(v interface{}) ([]byte, error)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn err\n\t}\n\tremoteConn := n.Connections[message.To]\n\tif remoteConn == nil {\n\t\t//fmt.Printf(\"Connection to node %d isnt present in n.Connections\\n\", message.To)\n\t\treturn fmt.Errorf(\"No TCP connection to node %d in Connection Table\", message.To)\n\t}\n\tif message.Type != \"Heartbeat\" { //Remove 1 to block printing of HB messages\n\t\t//fmt.Printf(\"SendMessage: From: %v (%d) To: %v (%d) Message: %v\\n\", remoteConn.LocalAddr(), n.Myself.ID, remoteConn.RemoteAddr(), message.To, message)\n\t}\n\t_, err = n.Connections[message.To].Write(messageByte)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\t//Assumes the connection is broken (write: broken pipe)\n\t\tn.CloseConn(n.Connections[message.To])\n\t\treturn err\n\t}\n\treturn err\n}",
"func (e *connectionedEndpoint) SendMsg(ctx context.Context, data [][]byte, c ControlMessages, to BoundEndpoint) (int64, func(), *syserr.Error) {\n\t// Stream sockets do not support specifying the endpoint. Seqpacket\n\t// sockets ignore the passed endpoint.\n\tif e.stype == linux.SOCK_STREAM && to != nil {\n\t\treturn 0, nil, syserr.ErrNotSupported\n\t}\n\treturn e.baseEndpoint.SendMsg(ctx, data, c, to)\n}",
"func SendMsg(\n\tr *rand.Rand, app *baseapp.BaseApp, ak authkeeper.AccountKeeper, bk bankkeeper.Keeper,\n\tmsg sdk.Msg, ctx sdk.Context, chainID string, gasValue uint64, privkeys []cryptotypes.PrivKey,\n) error {\n\taddr := msg.GetSigners()[0]\n\taccount := ak.GetAccount(ctx, addr)\n\tcoins := bk.SpendableCoins(ctx, account.GetAddress())\n\n\tfees, err := simtypes.RandomFees(r, ctx, coins)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttxGen := simappparams.MakeTestEncodingConfig().TxConfig\n\ttx, err := helpers.GenTx(\n\t\ttxGen,\n\t\t[]sdk.Msg{msg},\n\t\tfees,\n\t\tgasValue,\n\t\tchainID,\n\t\t[]uint64{account.GetAccountNumber()},\n\t\t[]uint64{account.GetSequence()},\n\t\tprivkeys...,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, _, err = app.Deliver(txGen.TxEncoder(), tx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func (c *Client) SendMsg(txt string) error {\n\n\t//encode message\n\tlog.Lvl3(\"Sending message : \", txt)\n\tmsg := gossiper.Message{\n\t\tText: txt,\n\t}\n\n\tpacketBytes, err := protobuf.Encode(&msg)\n\tif err != nil {\n\t\treturn err\n\n\t}\n\terr = c.SendBytes(packetBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func (c *Client) SendPrivateMsg(msg string, dest string, anonymous *bool, relayRate *float64, fullAnonimity *bool) {\n\ttoSend := gossiper.Message{\n\t\tText: msg,\n\t\tDestination: &dest,\n\t\tAnonymous: anonymous,\n\t}\n\n\tif *anonymous {\n\t\ttoSend.RelayRate = relayRate\n\t\ttoSend.FullAnonimity = fullAnonimity\n\t}\n\n\tpacketBytes, err := protobuf.Encode(&toSend)\n\tif err != nil {\n\t\tlog.Error(\"Error could not encode message : \", err)\n\t}\n\terr = c.SendBytes(packetBytes)\n\tif err != nil {\n\t\tlog.Error(\"Error could not send message : \", err)\n\t}\n\n\treturn\n\n}",
"func SendMsg(msg message.Messager, writer io.Writer) error {\n\tsendBuf := new(bytes.Buffer)\n\terr := msg.MarshalMessage(sendBuf)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = sendBuf.WriteTo(writer)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func (f *fakeDiskUpdateWatchServer) SendMsg(m interface{}) error { return nil }",
"func (c *TowerClient) sendMessage(peer wtserver.Peer, msg wtwire.Message) error {\n\t// Encode the next wire message into the buffer.\n\t// TODO(conner): use buffer pool\n\tvar b bytes.Buffer\n\t_, err := wtwire.WriteMessage(&b, msg, 0)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Unable to encode msg: %v\", err)\n\t\tlog.Errorf(\"Unable to send msg: %v\", err)\n\t\treturn err\n\t}\n\n\t// Set the write deadline for the connection, ensuring we drop the\n\t// connection if nothing is sent in a timely manner.\n\terr = peer.SetWriteDeadline(time.Now().Add(c.cfg.WriteTimeout))\n\tif err != nil {\n\t\terr = fmt.Errorf(\"unable to set write deadline: %v\", err)\n\t\tlog.Errorf(\"Unable to send msg: %v\", err)\n\t\treturn err\n\t}\n\n\tlogMessage(peer, msg, false)\n\n\t// Write out the full message to the remote peer.\n\t_, err = peer.Write(b.Bytes())\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to send msg: %v\", err)\n\t}\n\treturn err\n}",
"func (s *Switch) sendMessageImpl(ctx context.Context, peerPubKey p2pcrypto.PublicKey, protocol string, payload service.Data) error {\n\tvar err error\n\tvar conn net.Connection\n\n\tif s.discover.IsLocalAddress(&node.Info{ID: peerPubKey.Array()}) {\n\t\treturn errors.New(\"can't send message to self\")\n\t\t// TODO: if this is our neighbor it should be removed right now.\n\t}\n\n\tconn, err = s.cPool.GetConnectionIfExists(peerPubKey)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"peer not a neighbor or connection lost: %w\", err)\n\t}\n\n\tlogger := s.logger.WithContext(ctx).WithFields(\n\t\tlog.FieldNamed(\"from_id\", s.LocalNode().PublicKey()),\n\t\tlog.FieldNamed(\"peer_id\", conn.RemotePublicKey()))\n\n\tsession := conn.Session()\n\tif session == nil {\n\t\tlogger.Warning(\"failed to send message to peer, no valid session\")\n\t\treturn ErrNoSession\n\t}\n\n\tprotomessage := &ProtocolMessage{\n\t\tMetadata: &ProtocolMessageMetadata{\n\t\t\tNextProtocol: protocol, ClientVersion: config.ClientVersion,\n\t\t\tTimestamp: time.Now().Unix(), AuthPubkey: s.LocalNode().PublicKey().Bytes(),\n\t\t},\n\t\tPayload: nil,\n\t}\n\n\trealpayload, err := CreatePayload(payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprotomessage.Payload = realpayload\n\n\tdata, err := types.InterfaceToBytes(protomessage)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to encode signed message err: %w\", err)\n\t}\n\n\tfinal := session.SealMessage(data)\n\n\tif final == nil {\n\t\treturn errors.New(\"encryption failed\")\n\t}\n\n\t// Add context on the recipient, since it's lost in the sealed message\n\tctx = context.WithValue(ctx, log.PeerIDKey, conn.RemotePublicKey().String())\n\tif err := conn.Send(ctx, final); err != nil {\n\t\tlogger.With().Error(\"error sending direct message\", log.Err(err))\n\t\treturn err\n\t}\n\n\tlogger.Debug(\"direct message sent successfully\")\n\treturn nil\n}",
"func (c *JSONCodec) SendMsg(pack network.PackInf) (int, error) {\n\tmsg := pack.GetPackBody()\n\tt := reflect.TypeOf(msg)\n\tif t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\tvar out jsonMsg\n\tif name, ok := c.p.names[t]; ok {\n\t\tout.Head = name\n\t} else {\n\t\treturn 0, errors.New(\"unregisted json msg\")\n\t}\n\tout.Body = msg\n\terr := c.encoder.Encode(out)\n\n\treturn 0, err\n}",
"func SendMsg(msgChan chan MessageTask) {\n\tfor {\n\t\tmsgData := <-msgChan\n\t\ttarget, exist := connect.Pool.GetPlayer(msgData.Target)\n\t\tif !exist {\n\t\t\tlog.Println(\"Cannot find player connection: \", msgData.Target)\n\t\t\treturn\n\t\t}\n\t\tnetMsg := message.NetMessage{}\n\t\tmsg, err := json.Marshal(msgData.Msg)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Json encode message failed: \", err)\n\t\t\treturn\n\t\t}\n\t\tnetMsg.MsgName = msgData.Msg.MsgName()\n\t\tnetMsg.Data = string(msg)\n\t\tdata, err := json.Marshal(netMsg)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Encode net message error: \", err)\n\t\t\treturn\n\t\t}\n\t\t_, err = (*target.Conn).Write(data)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Send message failed: \", err)\n\t\t}\n\t}\n}",
"func (s *Server) sendMsg(pub [32]byte, msg []byte) error {\n\t// Find the transport matching the public key\n\ttr, err := s.connMgr.getTransport(pub)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttr.Write(msg)\n\n\treturn nil\n}",
"func (r *Room) Send(msg interface{}) {\n\tr.playerList.Iter(func(p player.Player) {\n\t\tp.Send(msg)\n\t})\n}",
"func (p *Player) Send(msg string) {\n\tp.Client.Out(msg)\n}",
"func (p *peer) Send(chID byte, msgBytes []byte) bool {\r\n\tif !p.IsRunning() {\r\n\t\t// see Switch#Broadcast, where we fetch the list of peers and loop over\r\n\t\t// them - while we're looping, one peer may be removed and stopped.\r\n\t\treturn false\r\n\t} else if !p.hasChannel(chID) {\r\n\t\treturn false\r\n\t}\r\n\treturn p.mconn.Send(chID, msgBytes)\r\n}",
"func (mgr *DataCheckMgr) SendMsg(msg *DataCheckMsg) error {\n\n\tblog.V(3).Infof(\"data checker: send an msg to datacheck manager\")\n\n\tselect {\n\tcase mgr.msgQueue <- msg:\n\tdefault:\n\t\tblog.Error(\"data checker: send an msg to datacheck manager fail\")\n\t\treturn fmt.Errorf(\"data checker: mgr queue is full now\")\n\t}\n\n\treturn nil\n}",
"func (p Peer) Send(m Msg, send bool) error {\n\tif !send {\n\t\treturn nil\n\t}\n\t//log.Print(\"Destination: \", p.addr, \":\", p.port)\n\t//log.Print(\"Msg: \", m)\n\tclient, err := net.Dial(\"udp\", p.addr+\":\"+p.port)\n\tif err != nil {\n\t\tlog.Println(\"Error Dialing Peer:\", err)\n\t\treturn err\n\t}\n\tenc := json.NewEncoder(client)\n\tif enc == nil {\n\t\tlog.Print(\"Encoder is nil\")\n\t\treturn errors.New(\"Encoder is nil\")\n\t}\n\treturn enc.Encode(m)\n}",
"func (ms *msgSender) SendMessage(ctx context.Context, p peer.ID, pmes *pb.Message) error {\n\tctx, _ = tag.New(ctx, kadmetrics.UpsertMessageType(pmes))\n\tdefer stats.Record(ctx, kadmetrics.SentMessages.M(1))\n\n\ts, err := ms.h.NewStream(ctx, p, ms.protocols...)\n\tif err != nil {\n\t\tstats.Record(ctx, kadmetrics.SentMessageErrors.M(1))\n\t\treturn err\n\t}\n\tdefer func() { _ = s.Close() }()\n\n\tif err = protoio.NewDelimitedWriter(s).WriteMsg(pmes); err != nil {\n\t\tstats.Record(ctx, kadmetrics.SentMessageErrors.M(1))\n\t\treturn err\n\t}\n\n\tstats.Record(ctx, kadmetrics.SentBytes.M(int64(pmes.Size())))\n\treturn nil\n}",
"func (w *BaseWebsocketClient) Send(msg base.MoneysocketMessage) error {\n\tif w.getConnection() == nil {\n\t\treturn errors.New(\"not currently connected\")\n\t}\n\tres, err := message.WireEncode(msg, w.SharedSeed())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn w.SendBin(res)\n}",
"func (n *P2P) SendMessage(ctx context.Context, msg Message, replies chan Message, pids ...peer.ID) error {\n\tfor _, pid := range pids {\n\t\tif pid.Pretty() == n.ID() {\n\t\t\tcontinue\n\t\t}\n\t\ts, err := n.host.NewStream(ctx, pid, n.cfg.ProtocolID())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer s.Close()\n\t\tws := WrapStream(s)\n\t\tgo n.streamHandler(ws, replies)\n\t\tif err := ws.Dispatch(msg); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif n.itf != nil {\n\t\t\tif err := n.itf.MessageSent(ws, msg); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}",
"func (p *DiscoveryProtocol) sendMsgToPeers(req *api.DiscoveryRequest, peerWhoSentMsg peer.ID) {\n\t// Excluded peers from sending a message\n\texcludedPeers := map[peer.ID]struct{}{}\n\texcludedPeers[p.p2pHost.ID()] = struct{}{} // Myself\n\texcludedPeers[peerWhoSentMsg] = struct{}{} // The peer who sent the message to the current node\n\n\t// Send message to peers\n\tfor _, neighbourID := range p.p2pHost.Peerstore().Peers() {\n\t\tif _, ok := excludedPeers[neighbourID]; !ok {\n\t\t\tgo sendMsg(p.p2pHost, neighbourID, req, protocol.ID(discoveryRequest))\n\t\t\tlog.Printf(\"%s: Discovery message to: %s was sent. Message Id: %s, Message: %s\",\n\t\t\t\tp.p2pHost.ID(), neighbourID, req.DiscoveryMsgData.MessageData.Id, req.Message)\n\t\t}\n\t}\n}",
"func sendmsg(s int, msg *unix.Msghdr, flags int) (n int, err error)",
"func (n *GossipNode) SendMessage(b []byte) error {\n\n\tn.Lock()\n\tdefer n.Unlock()\n\n\tif n.Conn == nil {\n\t\treturn errors.New(\"gossip node has not established a connection\")\n\t}\n\n\t_, err := n.Conn.Write(b)\n\treturn err\n}",
"func (this_node *Node) SendMessage(recvID int, amount int) {\n\tthis_node.canProceed.RLock()\n\tthis_node.canRecv.Lock()\n\tif amount > this_node.balance {\n\t\tfmt.Printf(\"ERR_SEND\\n\")\n\t} else {\n\t\tthis_node.outChannels[recvID] <- amount\n\t\tthis_node.balance -= amount\n\t}\n\tthis_node.canRecv.Unlock()\n\tthis_node.canProceed.RUnlock()\n}",
"func (sender *gobTCPSender) Send(msg []byte) error {\n\treturn sender.encoder.Encode(msg)\n}",
"func (c Conn) Send(msg smb.Message) error {\n\t// TODO: Determine whether net.Conn.Write returns a nil error for partial\n\t// writes.\n\t_, err := c.nc.Write(msg.Bytes())\n\treturn err\n}",
"func (p Producer) Send(msg Message) error {\n\tif msg.Topic == \"\" {\n\t\treturn errors.New(\"topic name is missing\")\n\t}\n\n\tb, err := json.Marshal(msg)\n\n\tif err != nil {\n\t\tlog.Printf(\"unable to marshal the value %s\\n\", err)\n\t}\n\n\t_, err = p.conn.Write(append(b, byte(constant.MsgEndIdent)))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func (hm *HM) send(dest, msgID uint8, msg interface{}) {\n\t// First encode the message\n\tvar buf bytes.Buffer\n\te := gob.NewEncoder(&buf)\n\tif err := e.Encode(msg); err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar mbuf []byte\n\tif hm.vecLog != nil {\n\t\tevent := \"Tx \" + msgName[msgID]\n\t\ttmp := make([]byte, buf.Len())\n\t\tbuf.Read(tmp[:])\n\t\tgobuf := hm.vecLog.PrepareSend(event, tmp)\n\t\tmbuf = make([]byte, 3+len(gobuf))\n\t\tmbuf[0], mbuf[1], mbuf[2] = dest, hm.pid, msgID\n\t\tcopy(mbuf[3:], gobuf)\n\t} else {\n\t\tmbuf = make([]byte, 3+buf.Len())\n\t\tmbuf[0], mbuf[1], mbuf[2] = dest, hm.pid, msgID\n\t\tbuf.Read(mbuf[3:])\n\t}\n\t// Prepend the dest id, msgType, and src id to the encoded gob\n\thm.LogMsg(\"Send[%d]:Msg[%s],%v\", dest, msgName[msgID], msg)\n\thm.txChan <- mbuf\n}",
"func sendMsg(useBase bool, baseCmd byte, cmd byte, msg proto.Message, conn *UniqueConnection) {\n\tdata, err := proto.Marshal(msg)\n\tif err != nil {\n\t\tTimeEncodedPrintln(\"marshaling error: \", err)\n\t\tlog.Fatal(\"marshaling error: \", err)\n\t}\n\tlength := int32(len(data)) + 1\n\n\tif useBase {\n\t\tlength = length + 1\n\t}\n\n\tif BYPASS_CONNECTION_SERVER {\n\t\tlength = length + 8\n\t}\n\n\tif DEBUG_SENDING_MESSAGE {\n\t\tTimeEncodedPrintln(\"sending message base length: \", length, \" command / command / message: \", baseCmd, cmd, msg)\n\t}\n\n\tbuf := new(bytes.Buffer)\n\n\tbinary.Write(buf, binary.LittleEndian, length)\n\tif useBase {\n\t\tbinary.Write(buf, binary.LittleEndian, baseCmd)\n\t}\n\n\tbinary.Write(buf, binary.LittleEndian, cmd)\n\tif BYPASS_CONNECTION_SERVER {\n\t\tif DEBUG_SENDING_MESSAGE {\n\t\t\tTimeEncodedPrintln(\"Send extra 8 bytes: \", conn.Identifier)\n\t\t}\n\t\tbinary.Write(buf, binary.LittleEndian, int64(conn.Identifier))\n\t}\n\tbuf.Write(data)\n\tn, err := conn.Connection.Write(buf.Bytes())\n\tif DEBUG_SENDING_MESSAGE {\n\t\tfmt.Println(\"Sent\", n, \"bytes\", \"encounter error:\", err)\n\t}\n}",
"func (n *Node) Send(msg string, toNode PPeer){\n\n wait, err := time.ParseDuration(\"3s\")\n Fatal(err)\n conn, err := net.DialTimeout(\"tcp\", toNode.GetAddr()+\":\"+toNode.GetPort(),wait)\n Fatal(err)\n buff := []byte(msg)\n fmt.Println(\"to send: %v\",msg)\n _,err2 := conn.Write(buff)\n Fatal(err2)\n defer conn.Close()\n\n}",
"func (r *Raft) sendMsg(m pb.Message) {\n\tr.msgs = append(r.msgs, m)\n}",
"func (w *Worker) Send(msg string) error {\n\tmsg_s := C.CString(string(msg))\n\tdefer C.free(unsafe.Pointer(msg_s))\n\n\tr := C.worker_send(w.cWorker, msg_s)\n\tif r != 0 {\n\t\terrStr := C.worker_last_exception(w.cWorker)\n\t\treturn errors.New(C.GoString(errStr))\n\t}\n\n\treturn nil\n}",
"func (consensus *Consensus) SendMessage(peer p2p.Peer, message []byte) {\n\thost.SendMessage(consensus.host, peer, message, nil)\n}",
"func (s *Sender) sendMsg(connID string, msg interface{}) error {\n\tdata, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.send(connID, data)\n}",
"func (s *datagramSocketImpl) SendMsg(_ fidl.Context, addr *fidlnet.SocketAddress, data []uint8, control socket.SendControlData, _ socket.SendMsgFlags) (socket.DatagramSocketSendMsgResult, error) {\n\tvar writeOpts tcpip.WriteOptions\n\tif addr != nil {\n\t\taddr, err := toTCPIPFullAddress(*addr)\n\t\tif err != nil {\n\t\t\treturn socket.DatagramSocketSendMsgResultWithErr(tcpipErrorToCode(&tcpip.ErrBadAddress{})), nil\n\t\t}\n\t\tif s.endpoint.netProto == ipv4.ProtocolNumber && len(addr.Addr) == header.IPv6AddressSize {\n\t\t\treturn socket.DatagramSocketSendMsgResultWithErr(tcpipErrorToCode(&tcpip.ErrAddressFamilyNotSupported{})), nil\n\t\t}\n\t\twriteOpts.To = &addr\n\t}\n\t// TODO(https://fxbug.dev/21106): do something with control.\n\t_ = control\n\tvar r bytes.Reader\n\tr.Reset(data)\n\tn, err := s.ep.Write(&r, writeOpts)\n\tif err != nil {\n\t\tif err := s.pending.update(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn socket.DatagramSocketSendMsgResultWithErr(tcpipErrorToCode(err)), nil\n\t}\n\treturn socket.DatagramSocketSendMsgResultWithResponse(socket.DatagramSocketSendMsgResponse{Len: n}), nil\n}",
"func SendMessage(host p2p.Host, p p2p.Peer, message []byte, lostPeer chan p2p.Peer) {\n\t// Construct normal p2p message\n\tcontent := ConstructP2pMessage(byte(0), message)\n\tgo send(host, p, content, lostPeer)\n}",
"func (self *Node) SendMessageToPeer(toPeer cipher.PubKey, contents []byte) (error, domain.RouteID) {\n\tdirectPeerID, localRouteID, sendRoutID, transport, err := self.findRouteToPeer(toPeer)\n\tif err != nil {\n\t\treturn err, NilRouteID\n\t}\n\n\tmessage := domain.UserMessage{\n\t\tMessageBase: domain.MessageBase{\n\t\t\tSendRouteID: sendRoutID,\n\t\t\tSendBack: false,\n\t\t\tFromPeerID: self.Config.PubKey,\n\t\t\tNonce: GenerateNonce(),\n\t\t},\n\t\tMessageID: (domain.MessageID)(uuid.NewV4()),\n\t\tIndex: 0,\n\t\tCount: 1,\n\t\tContents: contents,\n\t}\n\n\tserialized := self.serializer.SerializeMessage(message)\n\terr = transport.SendMessage(directPeerID, serialized)\n\tif err != nil {\n\t\treturn err, NilRouteID\n\t}\n\treturn nil, localRouteID\n}",
"func Send(node *noise.Node, from kad.ID, code byte, data []byte, minBucketID int, maxBucketID int, seqNum byte, incrementSeqNum bool) {\n\terrChan := make(chan error)\n\t// TODO: maybe do a self node lookup here\n\tpeers, prefixLens := kad.Table(node).GetBroadcastPeers(minBucketID, maxBucketID)\n\tfor i, id := range peers {\n\t\t// fmt.Println(\"Peers ID: \", id)\n\t\tmsg := NewMessage(from, prefixLens[i], code, data)\n\t\t// If incrementSeqNum is true, then seqNum is ignored and broadcastSeqNum is used and incremented instead. incrementSeqNum should only be set to true when Send is Send is called by the \"from\" node (i.e. not an intermediate broadcast node).\n\t\tif incrementSeqNum {\n\t\t\tmsg.ChangeSeqNum(broadcastSeqNum)\n\t\t} else {\n\t\t\tmsg.ChangeSeqNum(seqNum)\n\t\t}\n\t\tgo broadcastThroughPeer(node, id.(kad.ID), msg, errChan)\n\t}\n\tif incrementSeqNum {\n\t\tbroadcastSeqNum++\n\t}\n\n\tnumPeers := uint32(len(peers))\n\tresponseCount := uint32(0)\n\tfor atomic.LoadUint32(&responseCount) < numPeers {\n\t\tselect {\n\t\tcase err := <-errChan:\n\t\t\tif err != nil {\n\t\t\t\tlog.Warn().Err(err)\n\t\t\t}\n\t\t\tatomic.AddUint32(&responseCount, 1)\n\t\t}\n\t}\n}",
"func (net *MockNetwork) Send(msg []byte, to string) error {\n\tnet.Connexions[to] <- msg\n\treturn nil\n}",
"func (c *Conn) send(msg *pivo.Message) error {\n\tswitch msg.Type {\n\tcase pivo.IsBinaryMessage:\n\t\treturn c.write(websocket.BinaryMessage, msg.Data)\n\tcase pivo.IsTextMessage:\n\t\t// Default is to send text message\n\t}\n\treturn c.write(websocket.TextMessage, msg.Data)\n}",
"func (m *Manager) SendMessage(msgData []byte, to ...identity.ID) {\n\tmsg := &pb.Message{Data: msgData}\n\tm.send(marshal(msg), to...)\n}",
"func (ca *CoreAgent) Send(msg CoreAgentMessage) error {\n\tca.Lock()\n\tdefer ca.Unlock()\n\n\tif !ca.Connected {\n\t\treturn fmt.Errorf(\"Core Agent not connected\")\n\t}\n\n\tjsonBytes, err := msg.MarshalJSON()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tbinary.Write(buf, binary.BigEndian, uint32(len(jsonBytes)))\n\tca.Socket.Write(buf.Bytes())\n\tca.Socket.Write(jsonBytes)\n\treturn nil\n}",
"func (c *JSONCodec) SendRawMsg(data []byte) (int, error) {\n\tif c.conn == nil {\n\t\treturn 0, ErrFixHeadConnIsNull\n\t}\n\tif data != nil {\n\t\t_, err := c.conn.Write(data)\n\t\treturn len(data), err\n\t}\n\treturn 0, ErrFixHeadUnknownMsgInterface\n\n}",
"func (m *Member) Send(t msg.Type, n interface{}) {\n\tm.sendFunc(m, t, n)\n}",
"func (base *BaseProtocol) SendPeer(req *StreamRequest) error {\n\tstream, err := NewStream(base.Host, req.PeerID, req.MsgID...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer CloseStream(stream)\n\terr = WriteStream(req.Data, stream)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tCloseStream(stream)\n\treturn nil\n}",
"func (bs *BasicStream) SendMessage(opCode Opcode, data interface{}) error {\n\tglog.V(common.DEBUG).Infof(\"Sending msg %v to %v\", opCode, peer.IDHexEncode(bs.Stream.Conn().RemotePeer()))\n\tbs.el.Lock()\n\tdefer bs.el.Unlock()\n\tmsg := Msg{Op: opCode, Data: data}\n\treturn bs.encodeAndFlush(msg)\n}",
"func (s *streamMessageSender) SendMsg(ctx context.Context, msg bsmsg.BitSwapMessage) error {\n\treturn s.multiAttempt(ctx, func() error {\n\t\treturn s.send(ctx, msg)\n\t})\n}",
"func (s *Session) Send(msg fix.Messagable) error {\n\treturn fix.SendToTarget(msg, s.ID)\n}",
"func SendMessage(conn net.Conn, message msg.FromServer) {\n\tlog.Printf(\"SendMessage() to addr: %v Worker:%v\\n\", conn.RemoteAddr().String(), message.DstWorker)\n\toutBuf := Logger.PrepareSend(fmt.Sprintf(\"Sending-%v-Message\", msg.TypeStr(message.Type)), message)\n\t// log.Printf(\"%v\\n\", outBuf)\n\tvar msgSize uint16\n\tmsgSize = uint16(len(outBuf))\n\tsizeBuf := make([]byte, 2)\n\tbinary.LittleEndian.PutUint16(sizeBuf, uint16(msgSize))\n\toutBuf = append(sizeBuf, outBuf...)\n\tsize, err := conn.Write(outBuf)\n\tcheckErr(err)\n\tif size != len(outBuf) {\n\t\tlog.Fatal(\"size of message out != size written\")\n\t}\n}",
"func (f *Frontend) Send(msg FrontendMessage) error {\n\t_, err := f.w.Write(msg.Encode(nil))\n\treturn err\n}",
"func (s *Socket) WriteMsg() {\r\n\tfor {\r\n\t\tselect {\r\n\t\tcase data := <-s.WriteChan:\r\n\t\t\tpref := intToBytes(len(data))\r\n\t\t\tvar buffer bytes.Buffer\r\n\t\t\tbuffer.Write(pref)\r\n\t\t\tbuffer.Write(data)\r\n\t\t\t_, err := s.Conn.Write(buffer.Bytes())\r\n\t\t\tif err != nil {\r\n\t\t\t\tfmt.Println(\"Send Error,\", err)\r\n\t\t\t}\r\n\t\tcase <-s.Ctx.Done():\r\n\t\t\tfmt.Println(\"Quit WriteMsg()\")\r\n\t\t\treturn\r\n\t\t}\r\n\t}\r\n}",
"func (n Notification) SendMsg(summary, body string) (id uint32, err error) {\n\treturn notify(n.Name, summary, body, n.IconPath, 0, nil, n.Urgency.asHint(), n.timeoutInMS())\n}",
"func (self *SimulationEngine) send_message(msg MsgI, addr string) {\n\t\tconn, err := net.Dial(\"tcp\", addr)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Dial error, retrying..:\", err.Error())\n\t\t} else {\n\t\t\t// Encode and send data\n\t\t\tencoder := gob.NewEncoder(conn)\n\t\t\terr = encoder.Encode(&msg)\n\t\t\tfmt.Println(\"Mensaje: \", msg,\" enviado a: \", addr)\n\t\t\t// Close connection\n\t\t\tconn.Close()\n\t\t}\n}",
"func (sender *lengthPrefixTCPSender) Send(msg []byte) error {\n\tl := len(msg)\n\tif l > maxTCPMsgSize {\n\t\treturn fmt.Errorf(\"outgoing message exceeds maximum size: %d > %d\", l, maxTCPMsgSize)\n\t}\n\t// We copy the message so we can send it in a single Write\n\t// operation, thus making this thread-safe without locking.\n\tprefixedMsg := make([]byte, 4+l)\n\tbinary.BigEndian.PutUint32(prefixedMsg, uint32(l))\n\tcopy(prefixedMsg[4:], msg)\n\t_, err := sender.writer.Write(prefixedMsg)\n\treturn err\n}",
"func SendPrivMsg(message string, receiverID [32]byte) {\n\tkey := hex.EncodeToString(receiverID[:])\n\n\tciphertext, _ := Encrypt(MyPrivKey, &receiverID, []byte(message))\n\n\tcryptomsg := hex.EncodeToString(ciphertext)\n\n\tpkt := MeshPkt{TypePrivMsg, MySID}\n\tpayload := PrivMsgPkt{receiverID, int32(len(cryptomsg))}\n\n\tvar buffer bytes.Buffer\n\n\tbinary.Write(&buffer, binary.BigEndian, &pkt)\n\tbinary.Write(&buffer, binary.BigEndian, &payload)\n\tbuffer.WriteString(cryptomsg)\n\n\tsendPktToAddr(neighborhood[key].addr, buffer.Bytes())\n}",
"func SendMsg(summary, body string) (id uint32, err error) {\n\treturn note.SendMsg(summary, body)\n}",
"func (tp *Transport) Send(msg *sip.Msg) error {\n\tPopulateMessage(tp.Via, tp.Contact, msg)\n\thost, port, err := RouteMessage(tp.Via, tp.Contact, msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\taddr, err := net.ResolveUDPAddr(\"udp\", net.JoinHostPort(host, util.Portstr(port)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif msg.MaxForwards > 0 {\n\t\tmsg.MaxForwards--\n\t}\n\tts := time.Now()\n\taddTimestamp(msg, ts)\n\tvar b bytes.Buffer\n\tmsg.Append(&b)\n\tif *tracing {\n\t\ttrace(\"send\", b.Bytes(), addr)\n\t}\n\t_, err = tp.Sock.WriteTo(b.Bytes(), addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func (l *loggingServerStream) SendMsg(m interface{}) error {\n\terr := l.ServerStream.SendMsg(m)\n\tif l.li.LogStreamSendMsg {\n\t\tlogProtoMessageAsJSON(l.entry, m, status.Code(err), \"value\", \"StreamSend\")\n\t}\n\treturn err\n}",
"func (messenger *TCPMessenger) sendMessage(conn *net.TCPConn, msg Message) error {\r\n\t// Serialize the message\r\n\tmsgString, err := messenger.Encode(msg)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\t// log.Println(\"[DEBUG] Sending message: \" + msgString)\r\n\tio.Copy(conn, bytes.NewBufferString(msgString))\r\n\t//This is probably timing out, may beed to use a thread ppol\r\n\t//_, err = conn.Write([]byte(msgString))\r\n\treturn err\r\n}",
"func (u *UnityServer) SendMessage(msg string) {\n\tu.Logger.Debugf(\"Adding to outgoing: %v\", msg)\n\tu.outgoing <- msg\n}",
"func (p *ServerGatedServiceClient) SendMsg(project_id int32, key string, mtype int8, from int64, to int64, mid int64, message string) (r int32, err error) {\n\tif err = p.sendSendMsg(project_id, key, mtype, from, to, mid, message); err != nil {\n\t\treturn\n\t}\n\treturn p.recvSendMsg()\n}",
"func (conn *PeerConnection) send(payload string) {\n\tconn.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\tconn.ws.WriteMessage(websocket.TextMessage, []byte(payload))\n}",
"func (s *Session) Send(data []byte, peer net.Addr) error {\n\tmsg := bp.Alloc(len(data))\n\tcopy(msg, data)\n\n\tselect {\n\tcase <-s.closer:\n\t\treturn ErrSocketClosed\n\tcase s.writer <- rsData{msg, peer}:\n\t\treturn nil\n\tdefault:\n\t\tSysLog.Error(\"session sending queue is full and the message is droped;sessionid=%d\", s.id)\n\t\treturn ErrSendBuffIsFull\n\t}\n}",
"func (client *Client) sendMessage(msg interface{}) {\n\tstr, err := json.Marshal(msg)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\ts := string(str)\n\tmetrics.SendMessage(len(s))\n\tclient.socketTx <- s\n}",
"func (s *ClientState) send(msg MsgBody) error {\n\tb, err := json.Marshal(msg)\n\tif err != nil {\n\t\tlogError(\"could not marshal message: %s\", err)\n\t\treturn err\n\t}\n\tlogDebug(\"sending message\")\n\ts.ws.SetWriteDeadline(time.Now().Add(WEBSOCKET_WRITE_TIMEOUT))\n\terr = s.ws.WriteMessage(websocket.TextMessage, b)\n\tif err != nil {\n\t\tlogError(\"could not send message: %s\", err)\n\t\treturn err\n\t}\n\tlogDebug(\"sent: %s\", string(b))\n\treturn nil\n}",
"func (r *Raft) sendMsgLocally(m pb.Message) {\n\tr.Step(m)\n}",
"func (rn *RemoteNode) SendMessage(msg *protobuf.Message, hasReply bool) (<-chan *RemoteMessage, error) {\n\tif rn.IsStopped() {\n\t\treturn nil, errors.New(\"Remote node has stopped\")\n\t}\n\n\tif len(msg.MessageId) == 0 {\n\t\treturn nil, errors.New(\"Message ID is empty\")\n\t}\n\n\t_, found := rn.txMsgCache.Get(msg.MessageId)\n\tif found {\n\t\treturn nil, nil\n\t}\n\n\terr := rn.txMsgCache.Add(msg.MessageId, struct{}{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tselect {\n\tcase rn.txMsgChan <- msg:\n\tdefault:\n\t\treturn nil, errors.New(\"Tx msg chan full, discarding msg\")\n\t}\n\n\tif hasReply {\n\t\treturn rn.LocalNode.AllocReplyChan(msg.MessageId)\n\t}\n\n\treturn nil, nil\n}",
"func (kc *KClient) SendMSG(message *Message) (partition int32, offset int64, err error) {\n\tproducer, err := sarama.NewSyncProducerFromClient(kc.cl)\n\tif err != nil {\n\t\treturn\n\t}\n\tpartition, offset, err = producer.SendMessage(message.toSarama())\n\tproducer.Close()\n\treturn\n}",
"func (d *Device) Send(msg interface{}) error {\n\treturn d.conn.Send(msg)\n}",
"func (gs *ShutdownHandler) SelfShutdown(msg string) {\n\tselect {\n\tcase gs.nodeSelfShutdown <- msg:\n\tdefault:\n\t}\n}",
"func (self *Node) SendMessageToPeer(toPeer cipher.PubKey, contents []byte, reliably bool) (err error, routeId RouteId) {\n\tdirectPeer, localRouteId, sendId, transport, error := self.findRouteToPeer(toPeer, reliably)\n\tif error != nil {\n\t\treturn error, NilRouteId\n\t}\n\tbase := MessageBase{\n\t\tsendId,\n\t\tfalse, // Sending forward\n\t\tself.config.PubKey,\n\t\treliably,\n\t\tgenerateNonce(),\n\t}\n\tmessages := self.fragmentMessage(contents, directPeer, transport, base)\n\tfor _, message := range messages {\n\t\tserialized := self.serializer.SerializeMessage(message)\n\t\tsend_error := transport.SendMessage(directPeer, serialized)\n\t\tif send_error != nil {\n\t\t\treturn send_error, NilRouteId\n\t\t}\n\t}\n\treturn nil, localRouteId\n}",
"func sendMsg(conn *net.UDPConn, raddr net.UDPAddr, query interface{}) {\n\ttotalSent.Add(1)\n\tvar b bytes.Buffer\n\tif err := bencode.Marshal(&b, query); err != nil {\n\t\treturn\n\t}\n\tif n, err := conn.WriteToUDP(b.Bytes(), &raddr); err != nil {\n\t\tlogger.Infof(\"DHT: node write failed to %+v, error=%s\", raddr, err)\n\t} else {\n\t\ttotalWrittenBytes.Add(int64(n))\n\t}\n\treturn\n}",
"func (cl *UDPClient) Send(msg *Message, ns net.Addr) (n int, err error) {\n\tif ns == nil {\n\t\tns = cl.Addr\n\t}\n\n\traddr := ns.(*net.UDPAddr)\n\n\terr = cl.Conn.SetWriteDeadline(time.Now().Add(cl.Timeout))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tn, err = cl.Conn.WriteToUDP(msg.Packet, raddr)\n\n\treturn\n}",
"func (nopBroadcaster) SendTo(*disco.Node, Message) error { return nil }",
"func (c *Context) Send(to *Pid, message Message) {\n\tt := reflect.ValueOf(message).Type().Kind()\n\n\tif t == reflect.Ptr {\n\t\tpanic(\"Send cannot be called with a pointer to a Message\")\n\t}\n\n\tc.sendLock.Lock()\n\tdefer c.sendLock.Unlock()\n\n\tvar spanContext opentracing.SpanContext\n\tif c.span != nil {\n\t\tspanContext = c.span.Context()\n\t}\n\n\tdoSend(to, message, spanContext)\n}",
"func (sender *encryptedTCPSender) Send(msg []byte) error {\n\tsender.Lock()\n\tdefer sender.Unlock()\n\tencodedMsg := secretbox.Seal(nil, msg, &sender.state.nonce, sender.state.sessionKey)\n\tsender.state.advance()\n\treturn sender.sender.Send(encodedMsg)\n}",
"func (s *Server) iteratePeersWithSendMsg(msg *Message, send func(Peer, bool, []byte) error, peerOK func(Peer) bool) {\n\tvar deadN, peerN, sentN int\n\n\t// Get a copy of s.peers to avoid holding a lock while sending.\n\tpeers := s.getPeers(peerOK)\n\tpeerN = len(peers)\n\tif peerN == 0 {\n\t\treturn\n\t}\n\tmrand.Shuffle(peerN, func(i, j int) {\n\t\tpeers[i], peers[j] = peers[j], peers[i]\n\t})\n\tpkt, err := msg.Bytes()\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// If true, this node isn't counted any more, either it's dead or we\n\t// have already sent an Inv to it.\n\tfinished := make([]bool, peerN)\n\n\t// Try non-blocking sends first and only block if have to.\n\tfor _, blocking := range []bool{false, true} {\n\t\tfor i, peer := range peers {\n\t\t\t// Send to 2/3 of good peers.\n\t\t\tif 3*sentN >= 2*(peerN-deadN) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif finished[i] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr := send(peer, blocking, pkt)\n\t\t\tswitch err {\n\t\t\tcase nil:\n\t\t\t\tif msg.Command == CMDGetAddr {\n\t\t\t\t\tpeer.AddGetAddrSent()\n\t\t\t\t}\n\t\t\t\tsentN++\n\t\t\tcase errBusy: // Can be retried.\n\t\t\t\tcontinue\n\t\t\tdefault:\n\t\t\t\tdeadN++\n\t\t\t}\n\t\t\tfinished[i] = true\n\t\t}\n\t}\n}",
"func (s Sender) SendMessage(msg string) error {\n\tm := tgbotapi.NewMessage(*recipientChatID, fmt.Sprintf(messagePrefix, msg))\n\t_, err := s.bot.Send(m)\n\treturn err\n}",
"func (s *server) sendToPeer(target *btcec.PublicKey, msgs ...lnwire.Message) error {\n\terrChan := make(chan error, 1)\n\n\tmsgsToSend := make([]lnwire.Message, 0, len(msgs))\n\tmsgsToSend = append(msgsToSend, msgs...)\n\tsMsg := &sendReq{\n\t\ttarget: target,\n\t\tmsgs: msgsToSend,\n\t\terrChan: errChan,\n\t}\n\n\tselect {\n\tcase s.sendRequests <- sMsg:\n\tcase <-s.quit:\n\t\treturn errors.New(\"server shutting down\")\n\t}\n\n\tselect {\n\tcase err := <-errChan:\n\t\treturn err\n\tcase <-s.quit:\n\t\treturn errors.New(\"server shutting down\")\n\t}\n}",
"func (p *BoxPeer) SendMessageToPeer(code uint32, msg conv.Convertible, pid peer.ID) error {\n\n\tbody, err := conv.MarshalConvertible(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif c, ok := p.conns.Load(pid); ok {\n\t\tconn := c.(*Conn)\n\t\tif p.id.Pretty() == conn.remotePeer.Pretty() {\n\t\t\treturn ErrFailedToSendMessageToPeer\n\t\t}\n\t\t// go conn.Write(code, body)\n\t\tgo func(conn *Conn) {\n\t\t\tif err := conn.Write(code, body); err != nil {\n\t\t\t\tlogger.Errorf(\"Failed to send message to remote peer.Code: %X, Err: %v\", code, err)\n\t\t\t}\n\t\t}(conn)\n\t\treturn nil\n\t}\n\treturn ErrFailedToSendMessageToPeer\n}",
"func (s *Switch) SendMessage(ctx context.Context, peerPubkey p2pcrypto.PublicKey, protocol string, payload []byte) error {\n\treturn s.sendMessageImpl(ctx, peerPubkey, protocol, service.DataBytes{Payload: payload})\n}",
"func (sp *StreamPool) SendMessage(ctx context.Context, msg *p2pPb.AmperMessage, peers []peer.ID) error {\n\twg := sync.WaitGroup{}\n\tfor _, p := range peers {\n\t\twg.Add(1)\n\t\tgo func(p peer.ID) {\n\t\t\tdefer wg.Done()\n\t\t\terr := sp.sendMessage(ctx, msg, p)\n\t\t\tif err != nil {\n\t\t\t\tsp.log.Error(\"StreamPool SendMessage error\", \"peer\", p.Pretty())\n\t\t\t}\n\t\t}(p)\n\t}\n\twg.Wait()\n\treturn nil\n}",
"func (s *Server) SendMessage(message Message) {\n\ts.log(\"sending message\")\n\ts.RLock()\n\tfor c, open := range s.clients {\n\t\tif open {\n\t\t\tgo c.sendMessage(message)\n\t\t}\n\t}\n\ts.RUnlock()\n}",
"func (n *Network) SendMsgTo(msg Message, dst []int) {\n\tfor _, host := range dst {\n\t\tmsg.To = host\n\t\terr := n.SendMessage(msg)\n\t\tif err != nil {\n\t\t\tlog.Print(err) //Spams error message when connection not established - how to fix?\n\t\t\tcontinue\n\t\t}\n\t}\n}",
"func (s *MsgSender) Send(topic string, msg []byte) {\n\ts.Producer.Input() <- &sarama.ProducerMessage{Topic: topic, Key: nil, Value: sarama.StringEncoder(msg)}\n}",
"func Send(SendChan chan MessageRawTask) {\n\tfor {\n\t\tsendTask := <-SendChan\n\t\tlog.Printf(\"send message task: %v\\n\", sendTask)\n\n\t\ttarget, exist := connect.Pool.GetPlayer(sendTask.Target)\n\t\tif !exist {\n\t\t\tlog.Println(\"Cannot find player connection: \", sendTask.Target)\n\t\t\treturn\n\t\t}\n\n\t\t_, err := (*target.Conn).Write([]byte(sendTask.Msg))\n\t\tif err != nil {\n\t\t\tlog.Println(\"Send message failed: \", err)\n\t\t}\n\t}\n}",
"func SendMsg(kafka sarama.SyncProducer, sendTopic string, event interface{}) error {\n\tthisJson, err := json.Marshal(event)\n\tthisTopic := sendTopic\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmsgLog := &sarama.ProducerMessage{\n\t\tTopic: thisTopic,\n\t\tValue: sarama.StringEncoder(string(thisJson)),\n\t}\n\n\tpartition, offset, err := kafka.SendMessage(msgLog)\n\tif err != nil {\n\t\tfmt.Printf(\"Kafka error: %s\\n\", err)\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"Message is stored in topic %v, partition %d, offset %d\\n\",\n\t\tthisTopic, partition, offset)\n\n\treturn nil\n}",
"func (s *Sockets) SendToPlayer(name string, msg common.UpdateMessage) {\n\tsocket, ok := s.players[name]\n\tif !ok {\n\t\treturn\n\t}\n\tsocket.send(msg)\n}",
"func (ws *WrappedStream) SendMessage(msg Message) error {\n\terr := ws.enc.Encode(&msg)\n\t// Because output is buffered with bufio, we need to flush!\n\tws.w.Flush()\n\t// log.Debugf(\"%s '%s' -> %s\", ws.stream.Conn().LocalPeer(), msg.Type, ws.stream.Conn().RemotePeer())\n\treturn err\n}",
"func (a *Actor) Send(destPid Pid, cmd string, attr ...interface{}) (interface{}, error) {\n\tm := &Message{\n\t\tdestination: destPid,\n\t\tcmd: cmd,\n\t}\n\tm.SetAttrs(attr...)\n\ta.receiveChan <- m\n\ttimeout := make(chan bool, 1)\n\tgo func() {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\ttimeout <- true\n\t}()\n\tselect {\n\tcase <-timeout:\n\t\treturn nil, ErrTimeout\n\tcase result := <-a.sendChan:\n\t\tswitch result.(type) {\n\t\tcase ComplexResponse:\n\t\t\tcast := result.(ComplexResponse)\n\t\t\treturn cast.Response, cast.Err\n\t\tdefault:\n\t\t\treturn result, nil\n\t\t}\n\t}\n}"
] | [
"0.67609656",
"0.66726476",
"0.65107894",
"0.6427172",
"0.63538516",
"0.63124",
"0.6303708",
"0.62577486",
"0.62463313",
"0.6175123",
"0.61506647",
"0.61407936",
"0.6133639",
"0.612785",
"0.61269987",
"0.6120033",
"0.60922235",
"0.60864514",
"0.6082478",
"0.6081654",
"0.6069607",
"0.6028227",
"0.59940875",
"0.5993686",
"0.5982799",
"0.59514123",
"0.59422433",
"0.5934387",
"0.59188443",
"0.59167707",
"0.5916661",
"0.59112376",
"0.59079576",
"0.5890708",
"0.58852625",
"0.58837783",
"0.58810794",
"0.587313",
"0.5856242",
"0.5850447",
"0.58495265",
"0.5847937",
"0.5845102",
"0.5803903",
"0.5782735",
"0.5772455",
"0.5769204",
"0.57683647",
"0.57670677",
"0.5757522",
"0.57571477",
"0.5752716",
"0.57392865",
"0.57322145",
"0.5731647",
"0.5731343",
"0.57251775",
"0.5720489",
"0.57161605",
"0.57108265",
"0.57033074",
"0.56951845",
"0.5670453",
"0.56655616",
"0.56648254",
"0.5661703",
"0.5661006",
"0.56558126",
"0.56546843",
"0.5652367",
"0.5632481",
"0.56256515",
"0.5621556",
"0.5620455",
"0.5612216",
"0.5600077",
"0.5598598",
"0.5594199",
"0.5590021",
"0.55879086",
"0.55821973",
"0.5574966",
"0.55732393",
"0.55565614",
"0.55494803",
"0.5545383",
"0.5537048",
"0.55363065",
"0.5534546",
"0.5529879",
"0.55220366",
"0.55130947",
"0.5500343",
"0.5487128",
"0.54831636",
"0.54828626",
"0.5477928",
"0.5477842",
"0.54712456",
"0.54646164"
] | 0.74770045 | 0 |
IsAlive implements peering.PeerSender for the Self() node. | func (n *NetImpl) IsAlive() bool {
return true // This node is alive.
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (peer *peerImp) IsAlive() bool {\n\tif peer.typeCode < ExpiredPeerType {\n\t\t// If expiration time is past\n\t\tif peer.expires.Before(time.Now()) && peer.GetExpiresAt().After(time.Time{}) {\n\t\t\tpeer.typeCode = ExpiredPeerType\n\t\t\treturn false\n\t\t} else {\n\t\t\treturn true\n\t\t}\n\t} else {\n\t\t// If expiration time is not setted, set an instant of the past\n\t\tif peer.expires.Equal(time.Time{}) {\n\t\t\tpeer.expires = time.Now().Add(-time.Microsecond)\n\t\t}\n\t\treturn false\n\t}\n}",
"func (nc *NodeCaller) IsAlive(node string) bool {\n\t_, err := nc.isAlive(node, isAliveCall{})\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}",
"func (s State) IsAlive() bool {\n\treturn s == Alive\n}",
"func (f *FinagleRecord) IsAlive() bool {\n\treturn f.Status == statusAlive\n}",
"func (p *Player) IsAlive() bool {\n\treturn p.Hp > 0\n}",
"func (s *Service) IsAlive(w http.ResponseWriter, r *http.Request) {\n\tutils.ResponseWithJSON(w, http.StatusOK, \"alive\")\n}",
"func (p *Privmsg) IsFromSelf() bool {\n\t// if the from user is empty, then this is a self privmsg\n\treturn p.From == User{}\n}",
"func (c *ConsulClient) IsAlive(_ context.Context) (bool, error) {\n\thealth, _, err := c.client.Health().Checks(\"any\", nil)\n\treturn health.AggregatedStatus() == api.HealthPassing, err\n}",
"func (b *Bucket) IsAlive() bool {\n\tselect {\n\tcase <-b.ctx.Done():\n\t\treturn false\n\tdefault:\n\t\treturn true\n\t}\n}",
"func (s *Shot) IsAlive() bool {\n\treturn s.Lifecycles > 0\n}",
"func (s *Supervisor) IsAlive() (int, bool) {\n\tr, err := execCommand(s.name, []string{\"status\", s.service})\n\tif err != nil {\n\t\treturn -1, false\n\t}\n\treturn -1, strings.Contains(r, \"RUNNING\")\n}",
"func (this _PsCanary) IsAlive(processId int) bool {\n\tproc, err := this.os.FindProcess(processId)\n\tif nil != err {\n\t\treturn false\n\t}\n\n\tif err := proc.Signal(syscall.Signal(0)); nil != err {\n\t\treturn false\n\t}\n\treturn true\n}",
"func (del Delegation) IsSelfStake() bool {\n\treturn strings.EqualFold(del.Address.String(), del.ToStakerAddress.String())\n}",
"func (s *Server) isAlive(c net.Conn) bool {\n\tone := make([]byte, 1)\n\tif err := c.SetReadDeadline(time.Now().Add(time.Millisecond * 500)); err != nil {\n\t\tlog.Println(err)\n\n\t\treturn false\n\t}\n\n\t// client doesn't send anything, so it's fine to Read() instead of Peek()\n\tif _, err := c.Read(one); err == io.EOF {\n\t\treturn false\n\t}\n\n\treturn true\n}",
"func (a *Agent) Self() *Peer {\n\treturn a.state.Self\n}",
"func (node *hostNode) IsConnected() bool {\n\treturn node.PeersConnected() > 0\n}",
"func (d *GossipSystem) NotifyAlive(peer *memberlist.Node) error {\n\tmeta := &MetaData{}\n\tif err := json.Unmarshal(peer.Meta, meta); err != nil {\n\t\tglog.Warningf(\"unmarshal meta failed: %v\", err)\n\t\treturn fmt.Errorf(\"unmarshal meta failed: %v\", err)\n\t}\n\n\td.Lock()\n\tdefer d.Unlock()\n\n\t// reject those who is not the same group as us.\n\tif meta.Group != d.meta.Group {\n\t\treturn fmt.Errorf(\"unexpected gorup: %v\", meta.Group)\n\t}\n\treturn nil\n}",
"func (r RepositoryImpl) IsAlive() bool {\n\treturn r.conn.IsAlive()\n}",
"func (r RepositoryImpl) IsAlive() bool {\n\treturn r.conn.IsAlive()\n}",
"func (g *Grid) IsAlive(p Point) (bool, bool) {\n\tg.lock.RLock()\n\tdefer g.lock.RUnlock()\n\tif c, ok := g.set[p]; ok {\n\t\treturn c.Alive, ok\n\t}\n\treturn false, false\n}",
"func (o *Service) HasAlive() bool {\n\tif o != nil && o.Alive != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (gd *GossipDelegate) NotifyAlive(node *memberlist.Node) error {\n\tnodeName := gd.parseMemberlistNodeName(node.Name)\n\tif nodeName == gd.nodeId {\n\t\tgd.triggerStateEvent(types.SELF_ALIVE)\n\t\treturn nil\n\t}\n\n\tgd.updateGossipTs()\n\n\terr := gd.gossipChecks(node)\n\tif err != nil {\n\t\tgd.RemoveNode(types.NodeId(nodeName))\n\t\t// Do not add this node to the memberlist.\n\t\t// Returning a non-nil err value\n\t\treturn err\n\t}\n\n\tdiffNode, err := gd.GetLocalNodeInfo(types.NodeId(nodeName))\n\tif err == nil && diffNode.Status != types.NODE_STATUS_UP {\n\t\tgd.UpdateNodeStatus(types.NodeId(nodeName), types.NODE_STATUS_UP)\n\t\tgd.triggerStateEvent(types.NODE_ALIVE)\n\t} // else if err != nil -> A new node sending us data. We do not add node unless it is added\n\t// in our local map externally\n\treturn nil\n}",
"func (p *Peer) Connected() bool {\n\treturn atomic.LoadInt32(&p.connected) != 0 &&\n\t\tatomic.LoadInt32(&p.disconnect) == 0\n}",
"func (client *consulClient) IsAlive() bool {\n\tnetClient := http.Client{Timeout: time.Second * 10}\n\n\tresp, err := netClient.Get(client.consulUrl + consulStatusPath)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tif resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (u *Upstream) IsConnectedTo(serverPublicKey []byte) bool {\n\treturn u.client.IsConnectedTo(serverPublicKey)\n}",
"func (t *Target) GetAlive() (bool) {\n\tmutableMutex.Lock()\n defer mutableMutex.Unlock()\n\treturn t.alive\n}",
"func (a *Aliens) HasAlive() bool {\n\tfor _, alien := range *a {\n\t\tif alien.Status == AlienStatusLive {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}",
"func (w *Worker) Alive() bool {\n\tw.mu.RLock()\n\tret := w.alive\n\tw.mu.RUnlock()\n\n\treturn ret\n}",
"func (player *Player) Connected() bool {\n\treturn player.connected\n}",
"func isAlive(cell int) bool {\n\treturn cell == ALIVE\n}",
"func (m *Myself) IsRelayed() bool {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\treturn m.status == Port0 && m.relayServer != nil\n}",
"func (mph *MockPeerHandler) IsConnected(peerID string) bool {\n\treturn false\n}",
"func (p *FakePeer) Status() peer.Status {\n\tp.lock.RLock()\n\tdefer p.lock.RUnlock()\n\n\treturn p.status\n}",
"func (o *Service) GetAliveOk() (bool, bool) {\n\tif o == nil || o.Alive == nil {\n\t\tvar ret bool\n\t\treturn ret, false\n\t}\n\treturn *o.Alive, true\n}",
"func (proc *Proc) IsAlive() bool {\n\tdir := fmt.Sprintf(\"/proc/%d\", proc.GetPid())\n\t_, err := os.Stat(dir)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t\tlogger.Errorf(\"Error while checking process state: %s\", err)\n\t\treturn false\n\t}\n\treturn true\n}",
"func (p *peer) Send(chID byte, msgBytes []byte) bool {\r\n\tif !p.IsRunning() {\r\n\t\t// see Switch#Broadcast, where we fetch the list of peers and loop over\r\n\t\t// them - while we're looping, one peer may be removed and stopped.\r\n\t\treturn false\r\n\t} else if !p.hasChannel(chID) {\r\n\t\treturn false\r\n\t}\r\n\treturn p.mconn.Send(chID, msgBytes)\r\n}",
"func isAlive(db *gosql.DB, l *logger) bool {\n\t// The cluster might have just restarted, in which case the first call to db\n\t// might return an error. In fact, the first db.Ping() reliably returns an\n\t// error (but a db.Exec() only seldom returns an error). So, we're gonna\n\t// Ping() twice to allow connections to be re-established.\n\t_ = db.Ping()\n\tif err := db.Ping(); err != nil {\n\t\tl.Printf(\"isAlive returned err=%v (%T)\", err, err)\n\t} else {\n\t\treturn true\n\t}\n\treturn false\n}",
"func (o *Service) GetAlive() bool {\n\tif o == nil || o.Alive == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\treturn *o.Alive\n}",
"func (m *Memberlist) anyAlive() bool {\n\tm.nodeLock.RLock()\n\tdefer m.nodeLock.RUnlock()\n\tfor _, n := range m.nodes {\n\t\tif !n.DeadOrLeft() && n.Name != m.config.Name {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}",
"func (dc *DockerEnvContainer) IsAlive() bool {\n\treturn dc.isAlive\n}",
"func (p *Proxy) IsConnected() <-chan struct{} {\n\tfor p.webSocketClient == nil {\n\t\ttime.Sleep(50 * time.Millisecond)\n\t}\n\treturn p.webSocketClient.Connected()\n}",
"func (node *hostNode) ConnectedToPeer(id peer.ID) bool {\n\tconnectedness := node.host.Network().Connectedness(id)\n\treturn connectedness == network.Connected\n}",
"func IsAlive(w http.ResponseWriter, r *http.Request) {\n\tlogger.Trace(fmt.Sprintf(\"used to mask cc %v\", r))\n\t//logger.Trace(fmt.Sprintf(\"config data %v\", config))\n\tfmt.Fprintf(w, \"ok version 1.0\")\n}",
"func (d *DynamicSelect) IsAlive() bool {\n\treturn d.alive && !d.killHeard\n}",
"func (zk *ZookeeperMaster) CheckSelfNode() (bool, error) {\n\tif zk.client == nil {\n\t\treturn false, fmt.Errorf(\"zookeeper do not Init\")\n\t}\n\tchildren, _, err := zk.client.GetChildrenEx(zk.parentPath)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif len(children) == 0 {\n\t\treturn false, nil\n\t}\n\tfound := false\n\tfor _, node := range children {\n\t\tvar nodepath string\n\t\tif strings.HasSuffix(zk.parentPath, \"/\") {\n\t\t\tnodepath = zk.parentPath + node\n\t\t} else {\n\t\t\tnodepath = zk.parentPath + \"/\" + node\n\t\t}\n\t\tdata, _, err := zk.client.GetEx(nodepath)\n\t\tif err != nil {\n\t\t\tblog.Errorf(\"zookeeper master in check self node, get %s err, %s\", nodepath, err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tvar info bcstypes.ServerInfo\n\t\tif err := json.Unmarshal(data, &info); err != nil {\n\t\t\tblog.Warnf(\"zookeeper master in check self node parse %s json failed, %s\", nodepath, err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tif info.IP == zk.self.IP && info.Port == zk.self.Port && info.Pid == zk.self.Pid {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\treturn found, nil\n}",
"func (m *MsgPing) Follower(interfaces.IState) bool {\n\treturn true\n}",
"func (s *Server) Connected() bool {\n\treturn s.connection != nil\n}",
"func isServerAlive() bool{\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\treply, err := rpcCaller.HeartBeat(ctx, &pb.HeartBeatRequest{})\n\tif err == nil && reply.IsAlive{\n\t\tdebugPrint(\"Debug: Heartbeat to Primary Successful\")\n\n\t\t//Re-writing the FE servers global 'currentView' variable to make sure it matches with the Backend server\n\t\tcurrentView = int(reply.CurrentView)\n\t\treturn true\n\t} else {\n\t\tdebugPrint(\"Debug: Heartbeat to Primary Failed\")\n\t\t//TODO: Start View Change here\n\t\tviewchange := &pb.PromptViewChangeArgs{NewView:int32(currentView+1)}\n\t\tnewprimary := GetPrimary(currentView+1,len(peers))\n\t\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\t\tdefer cancel()\n\t\treply, err := peerRPC[newprimary].PromptViewChange(ctx, viewchange)\n\t\tif err==nil && reply.Success==true{\n\t\t\tcurrentView=currentView+1\n\t\t\trpcCaller = peerRPC[newprimary]\n\t\t\tprimaryServerIndex=newprimary\n\t\t\tfmt.Println(\"Debug: we have a new primary\")\n\t\t\treturn true\n\t\t}\n\n\t\t//TODO: the below return false can be changed to true (if view change is successful)\n\t\treturn false\n\t}\n\treturn false\n}",
"func (p *peer) IsPersistent() bool {\r\n\treturn p.peerConn.persistent\r\n}",
"func (p *peer) CanSend(chID byte) bool {\r\n\tif !p.IsRunning() {\r\n\t\treturn false\r\n\t}\r\n\treturn p.mconn.CanSend(chID)\r\n}",
"func (tracker *PeerTracker) Self() peer.ID {\n\treturn tracker.self\n}",
"func (peer *Peer) IsPersistent() bool {\n\tpeer.lock.RLock()\n\tdefer peer.lock.RUnlock()\n\treturn peer.persistent\n}",
"func (o *MacpoolPoolMemberAllOf) HasPeer() bool {\n\tif o != nil && o.Peer != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (client *client) IsConnectedTo(serverPublicKey []byte) bool {\n\treturn bytes.Equal(client.serverPublicKey, serverPublicKey)\n}",
"func (s *Scavenger) Alive() bool {\n\treturn atomic.LoadInt32(&s.status) == common.DaemonStatusStarted\n}",
"func (o *IppoolPoolMember) HasPeer() bool {\n\tif o != nil && o.Peer != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (transporter *IPCTransporter) IsConnected() bool {\n\treturn true\n}",
"func (e *EndpointCore) IsSelfConfigured() bool {\n\treturn e.MonitorType != \"\"\n}",
"func (w *Worker) Online() bool {\n\treturn w.s != nil\n}",
"func (u *UnityServer) Connected() bool {\n\treturn u.connected\n}",
"func (b *Base) IsConnected() bool {\n\treturn b.Connected\n}",
"func PingPeer() {\n\t// If the payload is not empty, the recipient MUST generate a PONG frame containing the same Data.\n}",
"func (r *Recorder) CheckSelf(){\n\tfor e:= r.eventList.Front(); e != nil; e = e.Next(){\n\t\tevent := e.Value.(*Event)\n\t\tswitch event.Type{\n\t\tcase \"ACKSEND\":\n\t\t\t// [ACKSEND] Cid <cid>, Publisher <peerid>, Receiver <peerid>\n\t\t\tr.checkPerSelf(event.Info[\"Receiver\"].(string))\n\t\tcase \"TKTRECV\":\n\t\t\t// [TKTRECV] Cid <cid>, Publisher <peerid>, Receiver <peerid>, TimeStamp <time>\n\t\t\tr.checkPerSelf(event.Info[\"Receiver\"].(string))\n\n\t\tcase \"TKTREJECT\", \"TKTACCEPT\":\n\t\t\t// [TKTREJECT] Cid <cid>, Publisher <peerid>, Receiver <peerid>, TimeStamp <time>\n\t\t\t// [TKTACCEPT] Cid <cid>, Publisher <peerid>, Receiver <peerid>, TimeStamp <time>\n\t\t\tr.checkPerSelf(event.Info[\"Receiver\"].(string))\n\n\t\tcase \"ACKRECV\":\n\t\t\t// [ACKRECV] Cid <cid>, Publisher <peerid>, Receiver <peerid>, Type <ACCEPT|CANCEL>\n\t\t\tr.checkPerSelf(event.Info[\"Publisher\"].(string))\n\t\t}\n\t}\n}",
"func (m *WebsocketRoutineManager) IsRunning() bool {\n\tif m == nil {\n\t\treturn false\n\t}\n\treturn atomic.LoadInt32(&m.state) == readyState\n}",
"func (u *Upstream) IsOK() bool {\n\treturn u.registered\n}",
"func (this *Protocol) ping(peerId PeerId) bool {\n\targs := &PingArgs{Me: this.GetMe()}\n\tvar reply PingReply\n\tsuccess := this.call(peerId, \"Ping\", args, &reply)\n\treturn success\n}",
"func (o *UsersLinks) HasSelf() bool {\n\tif o != nil && o.Self != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (s *Server) Alive() bool {\n\tif s.cmd == nil || s.cmd.Process == nil {\n\t\treturn false\n\t}\n\n\terr := s.cmd.Process.Signal(syscall.Signal(0))\n\treturn err == nil\n}",
"func (s State) Connected() bool {\n\treturn s == Connected\n}",
"func (this *Node) IsMe(nodeName string) bool {\n\treturn this.NodeInfo.Name == nodeName\n}",
"func (p *Peer) Inbound() bool {\n\treturn p.inbound\n}",
"func (b *Being) Alive() bool {\n\treturn !b.Dead\n}",
"func (s *Server) IsRunning() bool { return s.running }",
"func (rn *RemoteNode) IsReady() bool {\n\trn.readyLock.RLock()\n\tdefer rn.readyLock.RUnlock()\n\treturn rn.ready\n}",
"func (c *Checker) IsConnected() bool {\n\tc.Lock()\n\tdefer c.Unlock()\n\treturn c.connected\n}",
"func (client *client) IsConnected() bool {\n\treturn \"\" != client.address\n}",
"func (r *Runtime) IsConnected() bool { return r.isConnected }",
"func (p *Peer) Ready() bool {\n\treturn p != nil && p.AllowedIPs != nil && len(p.AllowedIPs) != 0 && p.PublicKey != nil\n}",
"func (p *FakePeer) Status() peer.Status {\n\treturn peer.Status{\n\t\tConnectionStatus: peer.Available,\n\t\tPendingRequestCount: 0,\n\t}\n}",
"func (throttler *Throttler) checkSelf(ctx context.Context, appName string, remoteAddr string, flags *CheckFlags) (checkResult *CheckResult) {\n\treturn throttler.checkStore(ctx, appName, selfStoreName, remoteAddr, flags)\n}",
"func (o *ResourcepoolPoolMember) HasPeer() bool {\n\tif o != nil && o.Peer != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (i *Inbound) IsRunning() bool {\n\treturn i.once.IsRunning()\n}",
"func (o *SvmPeerModifyAccepted) IsSuccess() bool {\n\treturn true\n}",
"func (c *Client) IsConnected() bool {\n\t// TODO: auto-select transport based on BMC capabilities\n\treturn c.isConnected()\n}",
"func (e *Ethereum) Ping() bool {\n\n\t_, err := e.GetBalance(BURN_ADDRESS)\n\tif err != nil {\n\t\tlog.Debug(err)\n\t\treturn false\n\t}\n\treturn true\n}",
"func (s State) IsOK() bool { return s == StateSending || s == StateSent || s == StateDelivered }",
"func (client *Client) Connected() bool {\n\treturn client.conn != nil\n}",
"func (bot *Engine) IsOnline() bool {\n\treturn bot.connectionManager.IsOnline()\n}",
"func (o *FcNeighborAllOf) HasPeerWwn() bool {\n\tif o != nil && o.PeerWwn != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (client *RPCConnection) IsConnected() bool {\n\treturn client.isConnected\n}",
"func (grid Grid) IsCellAlive(x, y int) bool {\n\tfor _, aliveCell := range grid.AliveCells {\n\t\tif aliveCell.X == x && aliveCell.Y == y {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}",
"func (ctn *Connection) IsConnected() bool {\n\treturn ctn.conn != nil\n}",
"func (ctn *Connection) IsConnected() bool {\n\treturn ctn.conn != nil\n}",
"func (b *Bot) getAlive() bool {\n\tif len(b.getCommands()) > 0 {\n\t\treturn true\n\t}\n\treturn false\n}",
"func (t *thing) IsConnected() bool {\n\treturn t.client != nil && t.client.IsConnected()\n}",
"func (c *Connection) IsConnected() bool {\n\treturn c.ws != nil\n}",
"func (p *StreamToSubStream) Connected() bool {\n\treturn p.In.Connected() && p.OutSubStream.Connected()\n}",
"func (l *LivenessTree) IsLive(address StateAddress) bool {\n\tnode := &l.nodes[address]\n\tlive := node.anyLive // Check descendants as well.\n\tfor p := node.parent; p != nil; p = p.parent {\n\t\tif p.timestamp > node.timestamp {\n\t\t\tnode = p\n\t\t\tlive = p.live // Ignore other descendants.\n\t\t}\n\t}\n\treturn live\n}",
"func (self *BaseActor) IsRunning() bool {\n\tself.mu.RLock()\n\tdefer self.mu.RUnlock()\n\n\treturn self.isRunning\n}",
"func (node *Node) IsOnline() bool {\n\tnode.Lock()\n\tallowNetwork := node.allowNetwork\n\tnode.Unlock()\n\treturn node.sh.IsUp() && allowNetwork\n}"
] | [
"0.69135827",
"0.6324429",
"0.61561835",
"0.614768",
"0.6056917",
"0.5928649",
"0.59161645",
"0.5823273",
"0.58170146",
"0.5738722",
"0.57205904",
"0.5680925",
"0.5670779",
"0.56538165",
"0.5652035",
"0.56459594",
"0.56048",
"0.5602353",
"0.5602353",
"0.55715513",
"0.5565453",
"0.554739",
"0.54372543",
"0.5436968",
"0.5420501",
"0.5411147",
"0.53715545",
"0.53628653",
"0.536286",
"0.5313478",
"0.53083366",
"0.5265547",
"0.52512157",
"0.5246329",
"0.52402335",
"0.5239972",
"0.52226895",
"0.5210931",
"0.51816124",
"0.517747",
"0.51724017",
"0.515551",
"0.511808",
"0.5106442",
"0.5065053",
"0.5055576",
"0.5046671",
"0.5044024",
"0.5030846",
"0.5030194",
"0.5023977",
"0.5014685",
"0.50137866",
"0.50065905",
"0.50035924",
"0.500044",
"0.49976635",
"0.49859458",
"0.49762425",
"0.49570608",
"0.49545184",
"0.49356177",
"0.49347377",
"0.49274135",
"0.49159178",
"0.49154574",
"0.49109197",
"0.49050277",
"0.48992363",
"0.48945746",
"0.4883702",
"0.4881555",
"0.48572093",
"0.48410758",
"0.48328662",
"0.48272216",
"0.4827213",
"0.48259172",
"0.48246986",
"0.48091918",
"0.47976997",
"0.47862357",
"0.47809774",
"0.47743788",
"0.47664747",
"0.47653648",
"0.47607884",
"0.47585028",
"0.47564712",
"0.475575",
"0.4751153",
"0.47502646",
"0.47502646",
"0.47450858",
"0.47449878",
"0.4741436",
"0.47406015",
"0.4738074",
"0.47285438",
"0.47217262"
] | 0.6839635 | 1 |
Await implements peering.PeerSender for the Self() node. | func (n *NetImpl) Await(timeout time.Duration) error {
return nil // This node is alive.
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (a *Agent) Self() *Peer {\n\treturn a.state.Self\n}",
"func (tracker *PeerTracker) Self() peer.ID {\n\treturn tracker.self\n}",
"func (peer *surveyorP) sender() {\n\tfor {\n\t\tif m := <-peer.q; m == nil {\n\t\t\tbreak\n\t\t} else {\n\t\t\tif peer.ep.SendMsg(m) != nil {\n\t\t\t\tm.Free()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}",
"func (t *SyncTransport) Wait() {}",
"func Sender() send.Sender {\n\treturn std.Sender()\n}",
"func (nopBroadcaster) SendAsync(Message) error { return nil }",
"func (r *Raft) electSelf() <-chan *RequestVoteResponse {\n\tr.peerLock.Lock()\n\tdefer r.peerLock.Unlock()\n\t// Create a response channel\n\trespCh := make(chan *RequestVoteResponse, len(r.peers)+1)\n\n\t// Get the last log\n\tvar lastLog Log\n\tif r.getLastLogIndex() > 0 {\n\t\tif err := r.logs.GetLog(r.lastLogIndex, &lastLog); err != nil {\n\t\t\tr.logE.Printf(\"Failed to get last log: %d %v\",\n\t\t\t\tr.getLastLogIndex(), err)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// Increment the term\n\tif err := r.setCurrentTerm(r.getCurrentTerm() + 1); err != nil {\n\t\tr.logE.Printf(\"Failed to update current term: %w\", err)\n\t\treturn nil\n\t}\n\n\t// Construct the request\n\treq := &RequestVoteRequest{\n\t\tTerm: r.getCurrentTerm(),\n\t\tCandidate: []byte(r.localAddr.String()),\n\t\tLastLogIndex: lastLog.Index,\n\t\tLastLogTerm: lastLog.Term,\n\t}\n\n\t// request peer for a vote\n\treqPeer := func(peer net.Addr) {\n\t\tresp := &RequestVoteResponse{\n\t\t\tGranted: false,\n\t\t}\n\t\terr := r.trans.RequestVote(peer, req, resp)\n\t\tif err != nil {\n\t\t\tr.logE.Printf(\"Failed to make RequestVote RPC to %v: %v\",\n\t\t\t\tpeer, err)\n\t\t\tresp.Term = req.Term\n\t\t\tresp.Granted = false\n\t\t}\n\t\trespCh <- resp\n\t}\n\n\t// For each peer, request a vote\n\tfor _, peer := range r.peers {\n\t\tgo reqPeer(peer)\n\t}\n\n\t// Persist a vote for ourselves\n\tif err := r.persistVote(req.Term, req.Candidate); err != nil {\n\t\tr.logE.Printf(\"Failed to persist vote : %w\", err)\n\t\treturn nil\n\t}\n\n\t// Include our own vote\n\trespCh <- &RequestVoteResponse{Term: req.Term, Granted: true}\n\treturn respCh\n}",
"func (base *BaseProtocol) SendPeer(req *StreamRequest) error {\n\tstream, err := NewStream(base.Host, req.PeerID, req.MsgID...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer CloseStream(stream)\n\terr = WriteStream(req.Data, stream)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tCloseStream(stream)\n\treturn nil\n}",
"func (client JobClient) SuspendSender(req *http.Request) (future JobSuspendFuture, err error) {\n var resp *http.Response\n resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))\n if err != nil {\n return\n }\n future.Future, err = azure.NewFutureFromResponse(resp)\n return\n }",
"func (gs *ShutdownHandler) SelfShutdown(msg string) {\n\tselect {\n\tcase gs.nodeSelfShutdown <- msg:\n\tdefault:\n\t}\n}",
"func Send(SendChan chan MessageRawTask) {\n\tfor {\n\t\tsendTask := <-SendChan\n\t\tlog.Printf(\"send message task: %v\\n\", sendTask)\n\n\t\ttarget, exist := connect.Pool.GetPlayer(sendTask.Target)\n\t\tif !exist {\n\t\t\tlog.Println(\"Cannot find player connection: \", sendTask.Target)\n\t\t\treturn\n\t\t}\n\n\t\t_, err := (*target.Conn).Write([]byte(sendTask.Msg))\n\t\tif err != nil {\n\t\t\tlog.Println(\"Send message failed: \", err)\n\t\t}\n\t}\n}",
"func SelfShutdown(msg string) {\n\tselect {\n\tcase nodeSelfShutdown <- msg:\n\tdefault:\n\t}\n}",
"func Send(node *noise.Node, from kad.ID, code byte, data []byte, minBucketID int, maxBucketID int, seqNum byte, incrementSeqNum bool) {\n\terrChan := make(chan error)\n\t// TODO: maybe do a self node lookup here\n\tpeers, prefixLens := kad.Table(node).GetBroadcastPeers(minBucketID, maxBucketID)\n\tfor i, id := range peers {\n\t\t// fmt.Println(\"Peers ID: \", id)\n\t\tmsg := NewMessage(from, prefixLens[i], code, data)\n\t\t// If incrementSeqNum is true, then seqNum is ignored and broadcastSeqNum is used and incremented instead. incrementSeqNum should only be set to true when Send is Send is called by the \"from\" node (i.e. not an intermediate broadcast node).\n\t\tif incrementSeqNum {\n\t\t\tmsg.ChangeSeqNum(broadcastSeqNum)\n\t\t} else {\n\t\t\tmsg.ChangeSeqNum(seqNum)\n\t\t}\n\t\tgo broadcastThroughPeer(node, id.(kad.ID), msg, errChan)\n\t}\n\tif incrementSeqNum {\n\t\tbroadcastSeqNum++\n\t}\n\n\tnumPeers := uint32(len(peers))\n\tresponseCount := uint32(0)\n\tfor atomic.LoadUint32(&responseCount) < numPeers {\n\t\tselect {\n\t\tcase err := <-errChan:\n\t\t\tif err != nil {\n\t\t\t\tlog.Warn().Err(err)\n\t\t\t}\n\t\t\tatomic.AddUint32(&responseCount, 1)\n\t\t}\n\t}\n}",
"func (s *SimpleServer) Await() {\n\tif s != nil {\n\t\ts.WaitGroup.Wait()\n\t}\n}",
"func (attendant *Attendant) Send(command string, args Args, kwargs KWArgs) error {\n\tif attendant.status != AttendantStopped {\n\t\treturn attendant.wrapper.Send(command, args, kwargs)\n\t} else {\n\t\treturn AttendantIsStopped(true)\n\t}\n}",
"func Peer(target string) {\n\tserver.listen()\n\tserver.seenPeers[target] = struct{}{}\n\tserver.dial(target)\n\tserver.managePeers()\n}",
"func (np *NodePromise) Send(nd Node) {\n\t// if promise has a value, don't fail it\n\tif np.err != nil || np.value != nil {\n\t\tpanic(\"already filled\")\n\t}\n\tnp.value = nd\n\tclose(np.done)\n}",
"func (c *Component) Self(ctx context.Context, s *live.Socket, event string, data interface{}) error {\n\treturn s.Self(ctx, c.Event(event), data)\n}",
"func (message *Message) Await() error {\n\tif message == nil {\n\t\treturn nil\n\t}\n\n\tmessage.mutex.RLock()\n\tdefer message.mutex.RUnlock()\n\t<-message.async\n\treturn message.result\n}",
"func TestGossipNoForwardSelf(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\n\tstopper := stop.NewStopper()\n\tdefer stopper.Stop(context.Background())\n\n\t// Shared cluster ID by all gossipers (this ensures that the gossipers\n\t// don't talk to servers from unrelated tests by accident).\n\tclusterID := uuid.MakeV4()\n\n\tlocal := startGossip(clusterID, 1, stopper, t, metric.NewRegistry())\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\t// Start one loopback client plus enough additional clients to fill the\n\t// incoming clients.\n\tpeers := []*Gossip{local}\n\tlocal.server.mu.Lock()\n\tmaxSize := local.server.mu.incoming.maxSize\n\tlocal.server.mu.Unlock()\n\tfor i := 0; i < maxSize; i++ {\n\t\tpeers = append(peers, startGossip(clusterID, roachpb.NodeID(i+2), stopper, t, metric.NewRegistry()))\n\t}\n\n\tfor _, peer := range peers {\n\t\tc := newClient(log.AmbientContext{Tracer: tracing.NewTracer()}, local.GetNodeAddr(), makeMetrics())\n\n\t\ttestutils.SucceedsSoon(t, func() error {\n\t\t\tconn, err := peer.rpcContext.GRPCUnvalidatedDial(c.addr.String()).Connect(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tstream, err := NewGossipClient(conn).Gossip(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := c.requestGossip(peer, stream); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Wait until the server responds, so we know we're connected.\n\t\t\t_, err = stream.Recv()\n\t\t\treturn err\n\t\t})\n\t}\n\n\tnumClients := len(peers) * 2\n\tdisconnectedCh := make(chan *client)\n\n\t// Start a few overflow peers and assert that they don't get forwarded to us\n\t// again.\n\tfor i := 0; i < numClients; i++ {\n\t\tlocal.server.mu.Lock()\n\t\tmaxSize := local.server.mu.incoming.maxSize\n\t\tlocal.server.mu.Unlock()\n\t\tpeer := startGossip(clusterID, roachpb.NodeID(i+maxSize+2), stopper, t, metric.NewRegistry())\n\n\t\tfor {\n\t\t\tlocalAddr := local.GetNodeAddr()\n\t\t\tc := newClient(log.AmbientContext{Tracer: tracing.NewTracer()}, localAddr, makeMetrics())\n\t\t\tpeer.mu.Lock()\n\t\t\tc.startLocked(peer, disconnectedCh, peer.rpcContext, stopper, peer.rpcContext.NewBreaker(\"\"))\n\t\t\tpeer.mu.Unlock()\n\n\t\t\tdisconnectedClient := <-disconnectedCh\n\t\t\tif disconnectedClient != c {\n\t\t\t\tt.Fatalf(\"expected %p to be disconnected, got %p\", c, disconnectedClient)\n\t\t\t} else if c.forwardAddr == nil {\n\t\t\t\t// Under high load, clients sometimes fail to connect for reasons\n\t\t\t\t// unrelated to the test, so we need to permit some.\n\t\t\t\tt.Logf(\"node #%d: got nil forwarding address\", peer.NodeID.Get())\n\t\t\t\tcontinue\n\t\t\t} else if *c.forwardAddr == *localAddr {\n\t\t\t\tt.Errorf(\"node #%d: got local's forwarding address\", peer.NodeID.Get())\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n}",
"func (b *Builder) ManagerSender() {\n\tfor {\n\t\tmes := <-b.outgoing\n\t\terr := b.enc.Encode(&mes)\n\t\tif err != nil {\n\t\t\tslog.Critical(err)\n\t\t\tpanic(\"Error!\")\n\t\t}\n\t}\n}",
"func (p *peer) Send(chID byte, msgBytes []byte) bool {\r\n\tif !p.IsRunning() {\r\n\t\t// see Switch#Broadcast, where we fetch the list of peers and loop over\r\n\t\t// them - while we're looping, one peer may be removed and stopped.\r\n\t\treturn false\r\n\t} else if !p.hasChannel(chID) {\r\n\t\treturn false\r\n\t}\r\n\treturn p.mconn.Send(chID, msgBytes)\r\n}",
"func (n *Node) Send(msg string, toNode PPeer){\n\n wait, err := time.ParseDuration(\"3s\")\n Fatal(err)\n conn, err := net.DialTimeout(\"tcp\", toNode.GetAddr()+\":\"+toNode.GetPort(),wait)\n Fatal(err)\n buff := []byte(msg)\n fmt.Println(\"to send: %v\",msg)\n _,err2 := conn.Write(buff)\n Fatal(err2)\n defer conn.Close()\n\n}",
"func SendGossipAsync(args *shared.GossipMsg, ip string, channel chan *rpc.Call) {\n\tclient, err := rpc.Dial(\"tcp\", ip+\":\"+RPCPORT)\n\n\tif err != nil {\n\t\tfmt.Println(\"SendGossipAsync: Message:\" + args.Msg + \" about \" + strconv.Itoa(args.Id) + \" to \" + ip + \" : connection Fail!\")\n\t\tchannel <- &rpc.Call{}\n\t\treturn\n\t}\n\tfmt.Println(\"SendGossipAsync: Message:\" + args.Msg + \" about \" + strconv.Itoa(args.Id) + \" to \" + ip + \" : connection success...\")\n\treply := &shared.GossipRpl{}\n\tgCall := client.Go(\"Gossip.RecGossip\", args, reply, channel)\n\tcheckErr(gCall.Error)\n}",
"func Gossip_sender(b []byte, member MemberID) error {\n\tvar returnErr error\n\t// The message will be sent three times to promise followers can receive.\n\tfor i := 0; i < 3; i++ {\n\t\tconn, err := net.Dial(\"udp\", member.LocalIP+\":12345\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Gossip sending error\")\n\t\t}\n\t\tdefer conn.Close()\n\n\t\tconn.Write(b)\n\t\t// This avoids failures. If the other node doesn't reply in 0.03 second, it will temporarily be regarded as failed.\n\t\t// Once it succefully reply. Stop, I know you are alive.\n\t\tconn.SetReadDeadline(time.Now().Add(time.Millisecond * 30))\n\t\tbuf := make([]byte, 1024)\n\t\t_, err2 := conn.Read(buf)\n\n\t\tif err2 == nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturnErr = err2\n\t\t}\n\t\t// It will pause for 0.02 second in order to avoid a congestion.\n\t\ttime.Sleep(20 * time.Millisecond)\n\t}\n\treturn returnErr\n}",
"func (n *Node) Send(msg string) string {\n\tif (n.up == nil) {\n\t\tn.l.Printf(\"\\n sending:\\t%s\\n to:\\t\\tN/A\\n\", msg)\n\t\treturn \"\";\n\t}\n\tn.l.Printf(\"\\n sending:\\t%s\\n to:\\t\\t%s\\n\", msg, n.up.name)\n\treturn n.up.Listen(msg, n.name)\n}",
"func (client BaseClient) ResolveSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n }",
"func Tell(playerId string, message message.IMessage) {\n\tMsgSendChan <- MessageTask{playerId, message}\n}",
"func (p *Privmsg) IsFromSelf() bool {\n\t// if the from user is empty, then this is a self privmsg\n\treturn p.From == User{}\n}",
"func (b *Builder) SendToManager(i interface{}) {\n\tb.outgoing <- i\n}",
"func NewSender(raw *tg.Client) *Sender {\n\treturn &Sender{\n\t\traw: raw,\n\t\trand: crypto.DefaultRand(),\n\t\tuploader: uploader.NewUploader(raw),\n\t\tresolver: peer.DefaultResolver(raw),\n\t}\n}",
"func (o *UsersLinks) SetSelf(v string) {\n\to.Self = &v\n}",
"func (client InfraRoleInstancesClient) PowerOnSender(req *http.Request) (future InfraRoleInstancesPowerOnFuture, err error) {\n\tsender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))\n\tfuture.Future = azure.NewFuture(req)\n\tfuture.req = req\n\t_, err = future.Done(sender)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = autorest.Respond(future.Response(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusInternalServerError))\n\treturn\n}",
"func (client AccountClient) UpdateSender(req *http.Request) (future AccountUpdateFuture, err error) {\n var resp *http.Response\n resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))\n if err != nil {\n return\n }\n future.Future, err = azure.NewFutureFromResponse(resp)\n return\n }",
"func (n *Node) send(msg *message.Message) *NodeErr {\n\tif !n.IsConnected() {\n\t\t// Return an error if the current node is not connected\n\t\treturn ConnErr(\"node not connected\", nil)\n\t} else if msg.To == nil {\n\t\t// Return an error if no Message.To parameter is initialized\n\t\treturn InternalErr(\"no intended peer defined at provided message\", nil)\n\t}\n\n\tencMsg := msg.JSON()\n\tif encMsg == nil {\n\t\treturn ParseErr(\"error encoding message to JSON\", nil)\n\t}\n\tfor _, to := range msg.To {\n\t\tif !n.Members.Contains(to) {\n\t\t\t// Return an error if the current network does not contains the\n\t\t\t// Message.To peer provided\n\t\t\treturn ConnErr(\"target peer is not into the network\", nil)\n\t\t}\n\n\t\t// Encode message as a request and send it\n\t\treq, err := composeRequest(msg, to)\n\t\tif err != nil {\n\t\t\treturn ParseErr(\"error decoding request to message\", err)\n\t\t}\n\t\tif _, err := n.client.Do(req); err != nil {\n\t\t\treturn ConnErr(\"error trying to perform the request\", err)\n\t\t}\n\t}\n\treturn nil\n}",
"func (client JobClient) SuspendSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}",
"func TellRaw(playerId string, msg string) {\n\tStrSendChan <- MessageRawTask{Target: playerId, Msg: msg}\n}",
"func (e ScoreProposal) Sender() []byte {\n\treturn e.Identity\n}",
"func (n *Node) Send(PubKey []byte, privKey ecdsa.PrivateKey, to string, amount float64) ([]byte, error) {\n\t// get pubkey of the wallet with \"from\" address\n\tif to == \"\" {\n\t\treturn nil, errors.New(\"Recipient address is not provided\")\n\t}\n\tw := wallet.Wallet{}\n\n\tif !w.ValidateAddress(to) {\n\t\treturn nil, errors.New(\"Recipient address is not valid\")\n\t}\n\n\ttx, err := n.GetTransactionsManager().CreateTransaction(PubKey, privKey, to, amount)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn.SendTransactionToAll(tx)\n\n\treturn tx.ID, nil\n}",
"func (s *JobCompletedSignal) Sender() string {\n\treturn s.sender\n}",
"func (b *bot) selfSaid(conn Connector, channel, message string, action bool) {\n\tmsg := msg.Message{\n\t\tUser: &b.me, // hack\n\t\tChannel: channel,\n\t\tBody: message,\n\t\tRaw: message, // hack\n\t\tAction: action,\n\t\tCommand: false,\n\t\tTime: time.Now(),\n\t\tHost: \"0.0.0.0\", // hack\n\t}\n\n\tfor _, name := range b.pluginOrdering {\n\t\tif b.runCallback(conn, b.plugins[name], SelfMessage, msg) {\n\t\t\treturn\n\t\t}\n\t}\n}",
"func (tr *Peer) Sync(ctx context.Context, target string,\n\treq *SyncRequest, resp *SyncResponse) error {\n\tif tr.isShutdown() {\n\t\treturn ErrTransportStopped\n\t}\n\n\ttr.wg.Add(1)\n\tdefer tr.wg.Done()\n\n\treturn tr.sync(ctx, target, req, resp)\n}",
"func (rf *Raft) send() {\n\n\tfor !rf.killed() {\n\n\t\trf.mu.Lock()\n\t\tif rf.IsLeader() && rf.canSend {\n\t\t\trf.canSend = false\n\t\t\trf.broadcast()\n\t\t}\n\t\trf.mu.Unlock()\n\n\t\ttime.Sleep(time.Millisecond * 5)\n\t}\n}",
"func (client DatabasesClient) PauseSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client,\n\t\treq,\n\t\tazure.DoPollForAsynchronous(client.PollingDelay))\n}",
"func (w *Wechaty) UserSelf() _interface.IContactSelf {\n\tuserID := w.puppet.SelfID()\n\treturn w.Contact().LoadSelf(userID)\n}",
"func (b *BotWorker) Send(cmd *protocol.Command) error {\n\tb.cmdOutChan <- cmd\n\t// FIXME: figure out what error to check\n\treturn nil\n}",
"func (o *Links) SetSelf(v string) {\n\to.Self = v\n}",
"func SendToSender(\n\tcertificate *SelfSignedCert,\n\tport string,\n\ttimeoutDuration uint,\n) error {\n\tln, err := net.CreateTCPListener(port)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer ln.Close()\n\tconn, err := net.EstablishConn(ln, timeoutDuration)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\treturn net.SendMessage(certificate.Bytes, conn)\n}",
"func (client InfraRoleInstancesClient) PowerOffSender(req *http.Request) (future InfraRoleInstancesPowerOffFuture, err error) {\n\tsender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))\n\tfuture.Future = azure.NewFuture(req)\n\tfuture.req = req\n\t_, err = future.Done(sender)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = autorest.Respond(future.Response(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusInternalServerError))\n\treturn\n}",
"func (f *Pub) Send(b interface{}) {\n\t// if b == nil { return }\n\tf.wg.Add(1)\n\tdefer f.wg.Done()\n\tf.op(f, nil, b)\n}",
"func (r Relationships) SelfRequestedBy() (data *jsons.Users, err error) {\n\tendp := NewEndpoint(RelationshipsSelfRequestedBy, r.API.query())\n\terr = r.API.Call(endp, &data)\n\n\treturn\n}",
"func (b *Bot) GetSelf(ctx context.Context) (*GetSelfResponse, error) {\n\tr, err := http.NewRequest(http.MethodGet, b.apiBaseURL+\"/self/get\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tq := r.URL.Query()\n\tr.URL.RawQuery = q.Encode()\n\n\thttpResp, err := b.doRequest(ctx, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &GetSelfResponse{}\n\terr = easyjson.UnmarshalFromReader(httpResp.Body, resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}",
"func SendFollowUp(id uint8, tMaster time.Time) {\n\t// Build message, encode and send\n\tmessage := FollowUpMessage{\n\t\tMessageCode: FollowUp,\n\t\tId: id,\n\t\tTime: tMaster.UnixNano() / int64(time.Microsecond),\n\t}\n\n\tencoded := encode(message)\n\tsendMulticast(encoded)\n}",
"func (mn *MockNetwork) Send(id string, data []byte) ([]byte, error) {\n\tif len(id) != 46 {\n\t\treturn nil, fmt.Errorf(\"AsyncSend: wrong id %s\", id)\n\t}\n\n\tmsg := &peermgr.Message{}\n\tif err := msg.Unmarshal(data); err != nil {\n\t\treturn nil, fmt.Errorf(\"Unmarshal message: %w\", err)\n\t}\n\n\tfor msgType := range peermgr.Message_Type_name {\n\t\tif msgType == int32(msg.GetType()) {\n\t\t\tretMsg := Message(peermgr.Message_ACK, true, []byte(id))\n\t\t\tretData, err := retMsg.Marshal()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Marshal message: %w\", err)\n\t\t\t}\n\t\t\treturn retData, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"Send: invalid message type\")\n}",
"func (c *Connection) Sender(addr string) (s Sender, err error) {\n\tsession, err := c.DefaultSession()\n\tif err != nil {\n\t\treturn Sender{}, err\n\t}\n\tresult := make(chan Sender)\n\tc.pump.Inject <- func() {\n\t\tlink := session.e.Sender(linkNames.Next())\n\t\tif link.IsNil() {\n\t\t\terr = session.e.Error()\n\t\t} else {\n\t\t\tlink.Target().SetAddress(addr)\n\t\t\t// FIXME aconway 2015-04-27: link options?\n\t\t\tlink.Open()\n\t\t}\n\t\tresult <- Sender{Link{c, link}}\n\t}\n\treturn <-result, err\n}",
"func (this *Client) AwaitConnect() {\n\tthis.getConsumerConnection().awaitConnection()\n\tthis.getPublisherConnection().awaitConnection()\n}",
"func (r *player) Send(ctx context.Context, msg core.Message) (core.Reply, error) {\n\tvar (\n\t\trep core.Reply\n\t\terr error\n\t)\n\n\tparcel, err := r.CreateParcel(ctx, msg)\n\tid := GetMessageHash(r.scheme, parcel)\n\n\t// Value from storageTape.\n\trep, err = r.tape.GetReply(ctx, id)\n\tif err == nil {\n\t\treturn rep, nil\n\t}\n\tif err == localstorage.ErrNotFound {\n\t\treturn nil, ErrNoReply\n\t} else {\n\t\treturn nil, err\n\t}\n\n\treturn rep, nil\n}",
"func (server *Server) SendPromiseRequest(req *rpc.PromiseRequest) *rpc.PromiseReply {\n\trpcStub := server.GetRpcStub(server.LeaderAddr)\n\n\treply, err := rpcStub.Promise(context.Background(), req, grpc.WaitForReady(true))\n\t//reply, err := rpcStub.Promise(context.Background(), req)\n\n\tif err != nil {\n\t\tlogger.Fatalf(\"Follower fails to send its fast-path accepted operaiton id = %s at idx = %d to \"+\n\t\t\t\"leader addr = %s error = %v\", req.Op.Id, req.Idx, server.LeaderAddr, err)\n\t}\n\n\treturn reply\n}",
"func (e *Engine) Sender() {\n\tfor msg := range e.SendChan {\n\t\tresponseMsg, err := e.Bot.Send(msg.Chattable)\n\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"engine: cannot send message: %s\", err.Error())\n\t\t}\n\n\t\tif msg.Report != nil {\n\t\t\tmsg.Report <- message.Response{\n\t\t\t\tMessage: responseMsg,\n\t\t\t\tError: err,\n\t\t\t}\n\t\t}\n\t}\n}",
"func (p *Peer) Name() string {\n\treturn p.m.LocalNode().Name\n}",
"func (h *Homebrew) Send(p *dmr.Packet) error {\n\tdata := buildData(p, h.ID)\n\tfor _, peer := range h.GetPeers() {\n\t\tif err := h.WriteToPeer(data, peer); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (h *Homebrew) SendTG(p *dmr.Packet, peer *Peer) error {\n\tdata := buildData(p, h.ID)\n\tfor _, toPeer := range h.GetPeers() {\n\t\tif peer != nil && toPeer.ID == peer.ID { // skip self\n\t\t\tcontinue\n\t\t}\n\n\t\tif toPeer.TGID == p.DstID {\n\t\t\tlog.Debugf(\"Send TG%d -> %d\\n\", p.DstID, toPeer.ID)\n\t\t\tif err := h.WriteToPeer(data, toPeer); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (c *Connection) sendWait() {\n\tfor {\n\t\tselect {\n\t\tcase m := <-c.Message:\n\t\t\tif c.state == Connected {\n\t\t\t\tc.conn.Write(m)\n\t\t\t}\n\t\t\tbreak\n\t\tdefault:\n\t\t\t// nothing to do\n\t\t}\n\t}\n}",
"func (r AcceptVpcPeeringConnectionRequest) Send(ctx context.Context) (*AcceptVpcPeeringConnectionResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &AcceptVpcPeeringConnectionResponse{\n\t\tAcceptVpcPeeringConnectionOutput: r.Request.Data.(*AcceptVpcPeeringConnectionOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}",
"func Self() string {\n\treturn naiveSelf()\n}",
"func (ac *authenticatedConnection) initiatorSendAct1(\n\tact1WireMessage []byte,\n\tinitiatorConnectionWriter protoio.WriteCloser,\n) error {\n\tsignedAct1Message, err := ac.localPeerPrivateKey.Sign(act1WireMessage)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tact1Envelope := &pb.HandshakeEnvelope{\n\t\tMessage: act1WireMessage,\n\t\tPeerID: []byte(ac.localPeerID),\n\t\tSignature: signedAct1Message,\n\t}\n\n\tif err := initiatorConnectionWriter.WriteMsg(act1Envelope); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func (p *Player) Send(msg string) {\n\tp.Client.Out(msg)\n}",
"func (c BackupInstancesClient) senderForSyncBackupInstance(ctx context.Context, req *http.Request) (future SyncBackupInstanceOperationResponse, err error) {\n\tvar resp *http.Response\n\tresp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfuture.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method)\n\treturn\n}",
"func (a *Actor) Send(destPid Pid, cmd string, attr ...interface{}) (interface{}, error) {\n\tm := &Message{\n\t\tdestination: destPid,\n\t\tcmd: cmd,\n\t}\n\tm.SetAttrs(attr...)\n\ta.receiveChan <- m\n\ttimeout := make(chan bool, 1)\n\tgo func() {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\ttimeout <- true\n\t}()\n\tselect {\n\tcase <-timeout:\n\t\treturn nil, ErrTimeout\n\tcase result := <-a.sendChan:\n\t\tswitch result.(type) {\n\t\tcase ComplexResponse:\n\t\t\tcast := result.(ComplexResponse)\n\t\t\treturn cast.Response, cast.Err\n\t\tdefault:\n\t\t\treturn result, nil\n\t\t}\n\t}\n}",
"func (_Erc777 *Erc777Transactor) Send(opts *bind.TransactOpts, recipient common.Address, amount *big.Int, data []byte) (*types.Transaction, error) {\n\treturn _Erc777.contract.Transact(opts, \"send\", recipient, amount, data)\n}",
"func (b *broker) Send(target string, msg Message) chan Reply {\n\treplyCh := make(chan Reply, 1)\n\t// handle ping requests\n\tif target == \"\" {\n\t\tcl, ok := b.cons.Client(msg.Sender)\n\t\tif ok {\n\t\t\treplyCh <- Reply{Error: NotFound}\n\t\t\treturn replyCh\n\t\t}\n\t\tcl.wake()\n\t\tb.cons.Update(cl) // todo: improve connections api\n\t\treplyCh <- Reply{}\n\t\treturn replyCh\n\t}\n\t// initiate async request with correlation id\n\tcl, ok := b.cons.Client(target)\n\tif !ok {\n\t\treplyCh <- Reply{Error: NotFound}\n\t\treturn replyCh\n\t}\n\tgo func() {\n\t\tmsg.CorrelationId = xid.New().String()\n\t\ttimer := time.NewTimer(defaultTimeout)\n\t\tselect {\n\t\tcase <-timer.C:\n\t\t\treplyCh <- Reply{Error: TimedOut}\n\t\tcase cl.dataChan <- msg:\n\t\t\ttimer.Stop()\n\t\t\tb.mu.Lock()\n\t\t\tb.waiting[msg.CorrelationId] = replyCh\n\t\t\tb.mu.Unlock()\n\t\t}\n\t}()\n\treturn replyCh\n}",
"func (p *FakePeer) Status() peer.Status {\n\tp.lock.RLock()\n\tdefer p.lock.RUnlock()\n\n\treturn p.status\n}",
"func (client JobClient) ResumeSender(req *http.Request) (future JobResumeFuture, err error) {\n var resp *http.Response\n resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))\n if err != nil {\n return\n }\n future.Future, err = azure.NewFutureFromResponse(resp)\n return\n }",
"func (sp *StreamPool) SendMessage(ctx context.Context, msg *p2pPb.AmperMessage, peers []peer.ID) error {\n\twg := sync.WaitGroup{}\n\tfor _, p := range peers {\n\t\twg.Add(1)\n\t\tgo func(p peer.ID) {\n\t\t\tdefer wg.Done()\n\t\t\terr := sp.sendMessage(ctx, msg, p)\n\t\t\tif err != nil {\n\t\t\t\tsp.log.Error(\"StreamPool SendMessage error\", \"peer\", p.Pretty())\n\t\t\t}\n\t\t}(p)\n\t}\n\twg.Wait()\n\treturn nil\n}",
"func (transport *Transport) Wait() {\n\ttransport.lock.Lock()\n\ttransport.lock.Unlock()\n}",
"func (request RpcRequest) Send() (response []byte, err error) {\n\n\tminers[request.Name].Client.ClientRequests <- request\n\tresponse = <-request.ResultChan\n\n\t/*\n\t * TODO:\n\t * Check the response for the status and if something\n\t * went wront create and error\n\t */\n\n\treturn response, nil\n}",
"func (m *MesosMessenger) Send(upid *upid.UPID, msg proto.Message) error {\n\tif upid.Equal(m.upid) {\n\t\treturn fmt.Errorf(\"Send the message to self\")\n\t}\n\tname := getMessageName(msg)\n\tlog.V(2).Infof(\"Sending message %v to %v\\n\", name, upid)\n\tm.encodingQueue <- &Message{upid, name, msg, nil}\n\treturn nil\n}",
"func (client JobClient) UpdateSender(req *http.Request) (future JobUpdateFuture, err error) {\n var resp *http.Response\n resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))\n if err != nil {\n return\n }\n future.Future, err = azure.NewFutureFromResponse(resp)\n return\n }",
"func (t *gRPCTransport) send() chan<- pb.Message {\n\treturn t.sendChan\n}",
"func (_Transfer *TransferTransactor) Send(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Transfer.contract.Transact(opts, \"send\")\n}",
"func (it *messageIterator) sender() {\n\tdefer it.wg.Done()\n\tdefer it.ackTicker.Stop()\n\tdefer it.nackTicker.Stop()\n\tdefer it.pingTicker.Stop()\n\tdefer func() {\n\t\tif it.ps != nil {\n\t\t\tit.ps.CloseSend()\n\t\t}\n\t}()\n\n\tdone := false\n\tfor !done {\n\t\tsendAcks := false\n\t\tsendNacks := false\n\t\tsendModAcks := false\n\t\tsendPing := false\n\n\t\tdl := it.ackDeadline()\n\n\t\tselect {\n\t\tcase <-it.failed:\n\t\t\t// Stream failed: nothing to do, so stop immediately.\n\t\t\treturn\n\n\t\tcase <-it.drained:\n\t\t\t// All outstanding messages have been marked done:\n\t\t\t// nothing left to do except make the final calls.\n\t\t\tit.mu.Lock()\n\t\t\tsendAcks = (len(it.pendingAcks) > 0)\n\t\t\tsendNacks = (len(it.pendingNacks) > 0)\n\t\t\t// No point in sending modacks.\n\t\t\tdone = true\n\n\t\tcase <-it.kaTick:\n\t\t\tit.mu.Lock()\n\t\t\tit.handleKeepAlives()\n\t\t\tsendModAcks = (len(it.pendingModAcks) > 0)\n\n\t\t\tnextTick := dl - gracePeriod\n\t\t\tif nextTick <= 0 {\n\t\t\t\t// If the deadline is <= gracePeriod, let's tick again halfway to\n\t\t\t\t// the deadline.\n\t\t\t\tnextTick = dl / 2\n\t\t\t}\n\t\t\tit.kaTick = time.After(nextTick)\n\n\t\tcase <-it.nackTicker.C:\n\t\t\tit.mu.Lock()\n\t\t\tsendNacks = (len(it.pendingNacks) > 0)\n\n\t\tcase <-it.ackTicker.C:\n\t\t\tit.mu.Lock()\n\t\t\tsendAcks = (len(it.pendingAcks) > 0)\n\n\t\tcase <-it.pingTicker.C:\n\t\t\tit.mu.Lock()\n\t\t\t// Ping only if we are processing messages via streaming.\n\t\t\tsendPing = !it.po.synchronous\n\t\t}\n\t\t// Lock is held here.\n\t\tvar acks, nacks, modAcks map[string]*AckResult\n\t\tif sendAcks {\n\t\t\tacks = it.pendingAcks\n\t\t\tit.pendingAcks = map[string]*AckResult{}\n\t\t}\n\t\tif sendNacks {\n\t\t\tnacks = it.pendingNacks\n\t\t\tit.pendingNacks = map[string]*AckResult{}\n\t\t}\n\t\tif sendModAcks {\n\t\t\tmodAcks = it.pendingModAcks\n\t\t\tit.pendingModAcks = map[string]*AckResult{}\n\t\t}\n\t\tit.mu.Unlock()\n\t\t// Make Ack and ModAck RPCs.\n\t\tif sendAcks {\n\t\t\tit.sendAck(acks)\n\t\t}\n\t\tif sendNacks {\n\t\t\t// Nack indicated by modifying the deadline to zero.\n\t\t\tit.sendModAck(nacks, 0, false)\n\t\t}\n\t\tif sendModAcks {\n\t\t\tit.sendModAck(modAcks, dl, true)\n\t\t}\n\t\tif sendPing {\n\t\t\tit.pingStream()\n\t\t}\n\t}\n}",
"func (pi *PeerInfo) CodecEncodeSelf(enc *ucodec.Encoder) {\n\tb := pi.Block()\n\tenc.MustEncode(b)\n}",
"func (p *Peer) Name() string {\n\treturn p.name\n}",
"func (p *Peer) Name() string {\n\treturn p.name\n}",
"func (p *Peer) Name() string {\n\treturn p.name\n}",
"func (base *BaseProtocol) SendRecvPeer(req *StreamRequest, resp types.Message) error {\n\n\tstream, err := NewStream(base.Host, req.PeerID, req.MsgID...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer CloseStream(stream)\n\terr = WriteStream(req.Data, stream)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ReadStream(resp, stream)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func (qq *QueryQueue) MaybeSend(p peer.Peer) {\n\tqq.mu.Lock()\n\tdefer qq.mu.Unlock()\n\tif !qq.closed {\n\t\tqq.Peers <- p\n\t}\n}",
"func (c *Constructor) findSender(\n\tctx context.Context,\n) (\n\tstring, // sender\n\t*big.Int, // balance\n\t*types.CoinIdentifier, // coin\n\terror,\n) {\n\tfor ctx.Err() == nil {\n\t\taddresses, err := c.helper.AllAddresses(ctx)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, nil, fmt.Errorf(\"%w: unable to get addresses\", err)\n\t\t}\n\n\t\tif len(addresses) == 0 { // create new and load\n\t\t\terr := c.generateNewAndRequest(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", nil, nil, fmt.Errorf(\"%w: unable to generate new and request\", err)\n\t\t\t}\n\n\t\t\tcontinue // we will exit on next loop\n\t\t}\n\n\t\tbestAddress, bestBalance, bestCoin, err := c.bestUnlockedSender(ctx, addresses)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, nil, fmt.Errorf(\"%w: unable to get best unlocked sender\", err)\n\t\t}\n\n\t\tif len(bestAddress) > 0 {\n\t\t\treturn bestAddress, bestBalance, bestCoin, nil\n\t\t}\n\n\t\tbroadcasts, err := c.helper.AllBroadcasts(ctx)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, nil, fmt.Errorf(\"%w: unable to get broadcasts\", err)\n\t\t}\n\n\t\tif len(broadcasts) > 0 {\n\t\t\t// This condition occurs when we are waiting for some\n\t\t\t// pending broadcast to complete before creating more\n\t\t\t// transactions.\n\n\t\t\ttime.Sleep(defaultSleepTime * time.Second)\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := c.generateNewAndRequest(ctx); err != nil {\n\t\t\treturn \"\", nil, nil, fmt.Errorf(\"%w: generate new address and request\", err)\n\t\t}\n\t}\n\n\treturn \"\", nil, nil, ctx.Err()\n}",
"func (t *Transfer) peerManager() {\n\tt.log.Debug(\"Started peerManager\")\n\tfor {\n\t\tselect {\n\t\tcase <-t.stopC:\n\t\t\treturn\n\t\tcase peers := <-t.peersC:\n\t\t\tfor _, p := range peers {\n\t\t\t\tt.log.Debugln(\"Peer:\", p)\n\t\t\t\t// TODO send all peers to connecter for now\n\t\t\t\tgo func(addr *net.TCPAddr) {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase t.peerC <- addr:\n\t\t\t\t\tcase <-t.stopC:\n\t\t\t\t\t}\n\t\t\t\t}(p)\n\t\t\t}\n\t\t}\n\t}\n}",
"func (nopBroadcaster) SendSync(Message) error { return nil }",
"func (k *Bot) Send(cmd commands.Command) {\n\tk.cmdChan <- cmd\n}",
"func (o *DashboardAllOfLinks) SetSelf(v string) {\n\to.Self = &v\n}",
"func (r *room) send(data interface{}, without proto.UID) {\n\tpeers := r.getPeers()\n\tfor id, p := range peers {\n\t\tif len(without) > 0 && id != without {\n\t\t\tif err := p.send(data); err != nil {\n\t\t\t\tlog.Errorf(\"send data to peer(%s) error: %v\", p.uid, err)\n\t\t\t}\n\t\t}\n\t}\n}",
"func (cs *ConsensusState) PeerGossipSleep() time.Duration {\n\treturn time.Duration(peerGossipSleepDuration.Load().(int32)) * time.Millisecond\n}",
"func (p Peer) Send(m Msg, send bool) error {\n\tif !send {\n\t\treturn nil\n\t}\n\t//log.Print(\"Destination: \", p.addr, \":\", p.port)\n\t//log.Print(\"Msg: \", m)\n\tclient, err := net.Dial(\"udp\", p.addr+\":\"+p.port)\n\tif err != nil {\n\t\tlog.Println(\"Error Dialing Peer:\", err)\n\t\treturn err\n\t}\n\tenc := json.NewEncoder(client)\n\tif enc == nil {\n\t\tlog.Print(\"Encoder is nil\")\n\t\treturn errors.New(\"Encoder is nil\")\n\t}\n\treturn enc.Encode(m)\n}",
"func (s *Stream) Send(res *discovery_v3.DiscoveryResponse) error {\n\tctx := s.Context()\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase s.resCh <- res:\n\t\treturn nil\n\t}\n}",
"func (m *Member) Send(t msg.Type, n interface{}) {\n\tm.sendFunc(m, t, n)\n}",
"func (rn *RemoteNode) tx() {\n\tvar msg *protobuf.Message\n\tvar buf []byte\n\tvar err error\n\tmsgLenBuf := make([]byte, msgLenBytes)\n\tkeepAliveTimer := time.NewTimer(keepAliveInterval)\n\n\tfor {\n\t\tif rn.IsStopped() {\n\t\t\tutil.StopTimer(keepAliveTimer)\n\t\t\treturn\n\t\t}\n\n\t\tselect {\n\t\tcase msg = <-rn.txMsgChan:\n\t\t\tbuf, err = proto.Marshal(msg)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif len(buf) > maxMsgSize {\n\t\t\t\tlog.Errorf(\"Msg size %d exceeds max msg size %d\", len(buf), maxMsgSize)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tbinary.BigEndian.PutUint32(msgLenBuf, uint32(len(buf)))\n\n\t\t\t_, err = rn.conn.Write(msgLenBuf)\n\t\t\tif err != nil {\n\t\t\t\trn.Stop(fmt.Errorf(\"Write to conn error: %s\", err))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, err = rn.conn.Write(buf)\n\t\t\tif err != nil {\n\t\t\t\trn.Stop(fmt.Errorf(\"Write to conn error: %s\", err))\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase <-keepAliveTimer.C:\n\t\t\trn.keepAlive()\n\t\t}\n\n\t\tutil.ResetTimer(keepAliveTimer, keepAliveInterval)\n\t}\n}",
"func (sm *SyncManager) DonePeer(peer *peer.Peer) {\n\t// Ignore if we are shutting down.\n\tif atomic.LoadInt32(&sm.shutdown) != 0 {\n\t\treturn\n\t}\n\n\tsm.msgChan <- &donePeerMsg{peer: peer}\n}",
"func (sm *SyncManager) DonePeer(peer *peer.Peer) {\n\t// Ignore if we are shutting down.\n\tif atomic.LoadInt32(&sm.shutdown) != 0 {\n\t\treturn\n\t}\n\n\tsm.msgChan <- &donePeerMsg{peer: peer}\n}"
] | [
"0.6654771",
"0.5959457",
"0.5752413",
"0.5594806",
"0.5436785",
"0.54338396",
"0.5349408",
"0.5328523",
"0.53178775",
"0.53116614",
"0.529583",
"0.5267855",
"0.52496123",
"0.5229283",
"0.52160597",
"0.5208682",
"0.51911575",
"0.5183598",
"0.517781",
"0.5142293",
"0.5130025",
"0.5123978",
"0.51184845",
"0.5103587",
"0.5081466",
"0.5068915",
"0.50580883",
"0.5051545",
"0.50176454",
"0.501314",
"0.5009097",
"0.499675",
"0.49938625",
"0.4989605",
"0.49857914",
"0.49857464",
"0.49795073",
"0.49691454",
"0.49662936",
"0.49560955",
"0.49534965",
"0.49530917",
"0.49478585",
"0.49281967",
"0.49207208",
"0.48964366",
"0.48959947",
"0.48913875",
"0.48860097",
"0.48500624",
"0.48454285",
"0.48406482",
"0.48334974",
"0.4826769",
"0.48200396",
"0.48174173",
"0.48136622",
"0.4812124",
"0.48119026",
"0.48106867",
"0.48085457",
"0.4802642",
"0.48006615",
"0.4791877",
"0.4791693",
"0.47836483",
"0.478173",
"0.47704965",
"0.47698504",
"0.47684214",
"0.47668967",
"0.47498935",
"0.47417864",
"0.47327274",
"0.47294614",
"0.47217286",
"0.47191674",
"0.4717373",
"0.47154418",
"0.47143027",
"0.47135133",
"0.47013196",
"0.46982265",
"0.46982265",
"0.46982265",
"0.46928483",
"0.4692595",
"0.4683288",
"0.4679247",
"0.46789664",
"0.46739516",
"0.4668252",
"0.46650147",
"0.46619537",
"0.4654565",
"0.46528816",
"0.4643578",
"0.46429962",
"0.46417892",
"0.46417892"
] | 0.5407962 | 6 |
Close implements peering.PeerSender for the Self() node. | func (n *NetImpl) Close() {
// We will con close the connection of the own node.
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (tr *Peer) Close() error {\n\tlogger := tr.logger.WithField(\"method\", \"Close\")\n\n\ttr.mtx.Lock()\n\tdefer tr.mtx.Unlock()\n\n\tif tr.shutdown {\n\t\treturn nil\n\t}\n\ttr.shutdown = true\n\n\t// Stop accepting new connections.\n\tif tr.server != nil {\n\t\tif err := tr.server.Close(); err != nil {\n\t\t\tlogger.Error(err)\n\t\t}\n\t}\n\n\t// Stop creating new connections.\n\ttr.clientProducer.Close()\n\n\t// Waiting for all outgoing connections to complete.\n\ttr.wg.Wait()\n\n\treturn nil\n}",
"func (c *sender) Close() {\n\tc.encoder.Close()\n}",
"func (fds SocketPair) PeerClose() {\n\tsyscall.Close(fds[peer])\n}",
"func (p *Peer) Close() {\n\tif !p.IsConnected() {\n\t\treturn\n\t}\n\tif !atomic.CompareAndSwapInt32(&p.connected, 1, 2) { //closing\n\t\treturn\n\t}\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\t<-done\n\t}()\n\tp.outQueue <- packet{use: packetUseForClose, content: nil, done: done}\n}",
"func (p *Peers) Close() {\n\tclose(p.exit)\n}",
"func (p *Peer) Close() {\n\n\tif p.closed {\n\t\treturn\n\t}\n\n\tif p.conn != nil {\n\t\tp.conn.Close()\n\t\tp.closed = true\n\t}\n}",
"func (a *Agent) Self() *Peer {\n\treturn a.state.Self\n}",
"func (r *Receiver) Close() error { return nil }",
"func SelfShutdown(msg string) {\n\tselect {\n\tcase nodeSelfShutdown <- msg:\n\tdefault:\n\t}\n}",
"func (tracker *PeerTracker) Self() peer.ID {\n\treturn tracker.self\n}",
"func (w *websocketPeer) Close() {\n\t// Tell sendHandler to exit, allowing it to finish sending any queued\n\t// messages. Do not close wr channel in case there are incoming messages\n\t// during close.\n\tw.wr <- nil\n\t<-w.writerDone\n\n\tcloseMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure,\n\t\t\"goodbye\")\n\n\t// Tell recvHandler to close.\n\tclose(w.closed)\n\n\t// Ignore errors since websocket may have been closed by other side first\n\t// in response to a goodbye message.\n\tw.conn.WriteControl(websocket.CloseMessage, closeMsg,\n\t\ttime.Now().Add(ctrlTimeout))\n\tw.conn.Close()\n}",
"func (fds SocketPair) Close() {\n\tfds.LocalClose()\n\tfds.PeerClose()\n}",
"func (p *peer) Close() {\n\tutils.GetLogger().With(\"host\", p.host.String()).Info(\"closing peer connection\")\n\t// waiting for on going operation with client connection\n\tp.Wait()\n\n\tp.Lock()\n\tdefer p.Unlock()\n\tif p.conn != nil && p.closeFn != nil {\n\t\terr := p.closeFn()\n\t\tif err != nil {\n\t\t\tutils.GetLogger().With(\"host\", p.host.String(), \"error\", err.Error()).Error(\"failed to close grpc connection\")\n\t\t}\n\t\tp.closed = true\n\t\tp.conn = nil\n\t}\n}",
"func (c *clientChan) sendClose() error {\n\treturn c.writePacket(marshal(msgChannelClose, channelCloseMsg{\n\t\tPeersId: c.peersId,\n\t}))\n}",
"func (gs *ShutdownHandler) SelfShutdown(msg string) {\n\tselect {\n\tcase gs.nodeSelfShutdown <- msg:\n\tdefault:\n\t}\n}",
"func (s *EventSender) Close() error {\n\tif s.client != nil {\n\t\treturn s.client.Close()\n\t}\n\treturn nil\n}",
"func (c *UDPChannel) Close() {\n\n}",
"func (ch *Channel) Close() {}",
"func (pc *PeerConnection) Close() {\n\tlog.Info(\"Closing peer connection\")\n\n\t// Cancel context to notify goroutines to exit.\n\tpc.cancel()\n}",
"func (s *Skeleton) SendClose(dst ServiceID, isForce bool) {\n\tsendNoEnc(s.s.getId(), dst, MSG_TYPE_CLOSE, 0, Cmd_None, isForce)\n}",
"func (r *RTCPeerConnection) Close() error {\n\tr.networkManager.Close()\n\treturn nil\n}",
"func (self *Echo_Client) Close() {\n\tself.cc.Close()\n}",
"func (h *Homebrew) Close() error {\n\th.mutex.Lock()\n\tdefer h.mutex.Unlock()\n\n\tif !h.Active() {\n\t\treturn nil\n\t}\n\n\tlog.Info(\"closing\")\n\n\t// Tell peers we're closing\nclosing:\n\tfor _, peer := range h.Peer {\n\t\tif peer.Status == AuthDone {\n\t\t\tif err := h.WriteToPeer(append(RepeaterClosing, peer.id...), peer); err != nil {\n\t\t\t\tbreak closing\n\t\t\t}\n\t\t}\n\t}\n\n\t// Kill keepalive goroutine\n\tif h.stop != nil {\n\t\tclose(h.stop)\n\t\th.stop = nil\n\t}\n\n\t// Kill listening socket\n\th.closed = true\n\treturn h.conn.Close()\n}",
"func (p *Peer) Close(timeout time.Duration) error {\n\terr := p.mlist.Leave(timeout)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclose(p.stopc)\n\treturn p.mlist.Shutdown()\n}",
"func (ps *peerSet) Close() {\n\tps.lock.Lock()\n\tdefer ps.lock.Unlock()\n\n\tfor _, p := range ps.peers {\n\t\tp.Disconnect(p2p.DiscQuitting)\n\t}\n\tps.closed = true\n}",
"func (c *Client) Close() {\n\t_, _ = c.Send(\"EXIT\")\n\tif c.connected {\n\t\tc.Socket.Close()\n\t}\n\tc.connected = false\n\treturn\n}",
"func (s *smtpSender) Close() error {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tif s.isOpen {\n\t\t// Always set the flag to false. Even if the sender fails to close.\n\t\ts.isOpen = false\n\n\t\tif err := s.sender.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (self *Client) close() {\n\t// TODO: Cleanly close connection to remote\n}",
"func (c *Client) Close() { c.streamLayer.Close() }",
"func (p *Player) Close() {\n\tp.chClose <- struct{}{}\n}",
"func (c *Client) Close() {}",
"func (c *Client) Close() {}",
"func (s *slave) Close() {\n\ts.exit <- struct{}{}\n}",
"func (s *Sink) Close() {\n\ts.ifOpen(func() { C.del_aubio_sink(s.s) })\n\ts.s = nil\n}",
"func (s *ClientStream) CloseSend() error {\n\treturn s.writeMessage(nil, true)\n}",
"func (closer *Closer) Close() {\n\tclose(closer.channel)\n}",
"func (node *Node) Close() {\n node.server.Close()\n return\n}",
"func (s *service) Close() {\n\tlogger.Debug(\"Closing peers ref...\")\n\ts.peersRef.Close()\n}",
"func (c *Component) Self(ctx context.Context, s *live.Socket, event string, data interface{}) error {\n\treturn s.Self(ctx, c.Event(event), data)\n}",
"func (c *Client) Close() {\n\tif c.closed {\n\t\treturn\n\t}\n\n\tc.closed = true\n\tc.ws.Close()\n\tclose(c.sent)\n\tif c.room != nil {\n\t\tc.room.unregister <- c\n\t}\n}",
"func (r *Receiver) Close() error {\n\t// TODO: Should this timeout? Close() take a context? Use one of the\n\t// other timeouts?\n\tctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)\n\tr.link.close(ctx)\n\tcancel()\n\treturn r.link.err\n}",
"func (this *syncProducerClient) Close() {\n\tlog.Trace(\"cluster[%s] closing kafka sync client: %d\", this.cluster, this.id)\n\n\t// will close the producer and the kafka tcp conn\n\tthis.SyncProducer.Close()\n\tthis.closed = true\n}",
"func (pi Peers) Close() {\n\tclose(pi.exit)\n}",
"func (mb *tcpTransporter) Close() error {\n\tmb.mu.Lock()\n\tdefer mb.mu.Unlock()\n\n\treturn mb.close()\n}",
"func (s *Sockets) Close() {\n\ts.close <- struct{}{}\n}",
"func (m *mockTCPEndpoint) Close() {\n\tm.impl.Close()\n\tm.notifyDone <- struct{}{}\n}",
"func (e *agentEndpoint) close() {\n\te.mutex.Lock()\n\tdefer func() {\n\t\t_ = recover()\n\t\te.mutex.Unlock()\n\t}()\n\tif e.isClosed {\n\t\treturn\n\t}\n\tif err := e.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseGoingAway, \"bye bye\")); err != nil {\n\t\tlogger.WithError(err).Errorf(\"error sending closing message to agent with id == %s\", e.id)\n\t}\n\te.isClosed = true\n}",
"func (party *EcdsaParty) Close() {\n\tparty.prv = nil\n\tparty.encprv = nil\n\tparty.k.SetInt64(0)\n\tparty.kinv.SetInt64(0)\n}",
"func (r *RTNL) Close() {\n\tif r.conn != nil {\n\t\tr.conn.Close()\n\t\tr.conn = nil\n\t}\n}",
"func (m *SinkNats) Close() error {\n\t//u.Debugf(\"%p SinkNats Close()\", m)\n\tif m.closed {\n\t\treturn nil\n\t}\n\tm.closed = true\n\t//inCh := m.MessageIn()\n\t// m.TaskBase.Close()\n\tm.tx.Close()\n\treturn m.TaskBase.Close()\n}",
"func (it *L2CrossDomainMessengerSentMessageIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}",
"func (c *Client) Close() {\n}",
"func (c *Client) Close() {\n}",
"func (t *Client) Close() error { return nil }",
"func (recv *receiver) Close() {\n\trecv.conn.Close()\n\tclose(recv.close)\n}",
"func (e *PacketEnd) Close() error {\n\treturn errors.New(\"Not Implemented\")\n}",
"func (s socket) Close() error {\n\ts.done <- true\n\treturn nil\n}",
"func (p *Plugin) Close() error {\n\tsocket := p.socket\n\tif socket == nil {\n\t\treturn errors.New(\"Socket is already closed\")\n\t}\n\tsessionID := p.sessions.getUniqueSessionID()\n\t_, err := socket.Write(archiveMessage(CloseClient, sessionID, nil))\n\tif err != nil {\n\t\tp.socket = nil\n\t\treturn err\n\t}\n\tmessage := p.sessions.receiveAndClose(sessionID)\n\terr = socket.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.socket = nil\n\tif message.Type != ResultOK {\n\t\treturn fmt.Errorf(\"Unregister error: '%s'\", p.pipeName)\n\t}\n\treturn nil\n}",
"func (s *Socket) Close() {\n\ts.Online = false\n\t(*s.conn).Close()\n}",
"func (c *client) close() {\n\tc.leave()\n\tc.Conn.Close()\n\tc.Message <- \"/quit\"\n}",
"func (i *invoker) Close() error {\n\ti.cancelPF()\n\n\t// Closing the local listener effectively closes the gRPC connection\n\tif err := i.listener.Close(); err != nil {\n\t\ti.conn.Close() // If we fail to close the listener, explicitly close the gRPC connection and ignore any error\n\t\treturn fmt.Errorf(\"failed to close local tcp port listener: %w\", err)\n\t}\n\n\treturn nil\n}",
"func (p *Producer) Close() error {\n\tp.sc.Log.Info(\"close %s\", p.id)\n\terrs := wrappers.Errs{}\n\tif p.writeBuffer != nil {\n\t\tp.writeBuffer.close()\n\t}\n\tif p.sock != nil {\n\t\terrs.Add(p.sock.Close())\n\t}\n\treturn errs.Err\n}",
"func (_m *Socket) Close() {\n\t_m.Called()\n}",
"func (self *SPC_Client) Close() {\n\tself.cc.Close()\n}",
"func (c *Client) Close() {\n\t// Wait for sender and receiver loops\n\tc.stopping.Add(2)\n\tc.cancel()\n\tc.stopping.Wait()\n\n\tclose(c.sendQueue)\n\tclose(c.receiveQueue)\n\tclose(c.errors)\n\n\tc.connection.Close()\n}",
"func (t *Transport) Close() error {\n\tif t.exitChan != nil {\n\t\tt.exitChan <- 1\n\t\t<-t.exitChan\n\t}\n\treturn nil\n}",
"func (p *pipe) Close() error {\n\tmsg := msg{\n\t\tdata: nil,\n\t\terr: io.EOF, // Indicates to the other side's Read function that session has ended.\n\t}\n\n\tselect {\n\tcase p.otherEnd.ch <- msg: // Sent msg to the other side's Read function.\n\t\treturn nil\n\tcase <-p.ctx.Done():\n\t\treturn p.ctx.Err()\n\t}\n}",
"func (l *Listener) Close() error {\n\t// XXX - should close on M3UA layer.\n\treturn l.sctpListener.Close()\n}",
"func (rr *RtcpReceiver) Close() {\n\trr.events <- rtcpReceiverEventTerminate{}\n\t<-rr.done\n}",
"func (s *Speaker) Close() error { return nil }",
"func (t *Topic) Close(ctx context.Context) error {\n\tctx, span := t.startSpanFromContext(ctx, \"sb.Topic.Close\")\n\tdefer span.End()\n\n\tif t.sender != nil {\n\t\terr := t.sender.Close(ctx)\n\t\tt.sender = nil\n\t\tif err != nil && !isConnectionClosed(err) {\n\t\t\ttab.For(ctx).Error(err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (self *SMTP_Client) Close() {\n\tself.cc.Close()\n}",
"func (self *Persistence_Client) Close() {\n\tself.cc.Close()\n}",
"func (c *Client) Close() {\n\tc.ec.Close()\n}",
"func (e *connectionedEndpoint) Close(ctx context.Context) {\n\tvar acceptedChan chan *connectionedEndpoint\n\te.Lock()\n\tvar (\n\t\tc ConnectedEndpoint\n\t\tr Receiver\n\t)\n\tswitch {\n\tcase e.Connected():\n\t\te.connected.CloseSend()\n\t\te.receiver.CloseRecv()\n\t\t// Still have unread data? If yes, we set this into the write\n\t\t// end so that the peer can get ECONNRESET) when it does read.\n\t\tif e.receiver.RecvQueuedSize() > 0 {\n\t\t\te.connected.CloseUnread()\n\t\t}\n\t\tc = e.connected\n\t\tr = e.receiver\n\t\te.connected = nil\n\t\te.receiver = nil\n\tcase e.isBound():\n\t\te.path = \"\"\n\tcase e.ListeningLocked():\n\t\tclose(e.acceptedChan)\n\t\tacceptedChan = e.acceptedChan\n\t\te.acceptedChan = nil\n\t\te.path = \"\"\n\t}\n\te.Unlock()\n\tif acceptedChan != nil {\n\t\tfor n := range acceptedChan {\n\t\t\tn.Close(ctx)\n\t\t}\n\t}\n\tif c != nil {\n\t\tc.CloseNotify()\n\t\tc.Release(ctx)\n\t}\n\te.ResetBoundSocketFD(ctx)\n\tif r != nil {\n\t\tr.CloseNotify()\n\t\tr.Release(ctx)\n\t}\n}",
"func (file *Remote) Close() error {\n\t_, err := file.client.Send(&Tclunk{\n\t\tFID: file.fid,\n\t})\n\treturn err\n}",
"func (p *TCPProxy) Close(c chan struct{}) {\n\tclose(c)\n}",
"func (clus *Cluster) Send_SIGQUIT_ETCD_AND_REMOVE_DATA_AND_STOP_AGENT() {\n\terr := clus.broadcast(rpcpb.Operation_SIGQUIT_ETCD_AND_REMOVE_DATA_AND_STOP_AGENT)\n\tif err != nil {\n\t\tclus.lg.Warn(\"destroying etcd/agents FAIL\", zap.Error(err))\n\t} else {\n\t\tclus.lg.Info(\"destroying etcd/agents PASS\")\n\t}\n\n\tfor i, conn := range clus.agentConns {\n\t\terr := conn.Close()\n\t\tclus.lg.Info(\"closed connection to agent\", zap.String(\"agent-address\", clus.Members[i].AgentAddr), zap.Error(err))\n\t}\n\n\tif clus.testerHTTPServer != nil {\n\t\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\t\terr := clus.testerHTTPServer.Shutdown(ctx)\n\t\tcancel()\n\t\tclus.lg.Info(\"closed tester HTTP server\", zap.String(\"tester-address\", clus.Tester.Addr), zap.Error(err))\n\t}\n}",
"func (n Node) Close() error {\n\treturn n.listener.Close()\n}",
"func (socket *SocketTLS) Close() {\n\t// Fire closing event\n\tlog.Noteln(socket.name + \" closing. Port \" + socket.port)\n\tsocket.eventChan <- SocketEvent{\n\t\tName: \"close\",\n\t\tData: nil,\n\t}\n\n\t// Close socket\n\tsocket.listen.Close()\n}",
"func (it *HasNoEtherOwnershipTransferredIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}",
"func (p *TCPPeer) disconnect() {\n\tp.conn.Close()\n\tclose(p.send)\n\tclose(p.receive)\n}",
"func (p *Listener) Close() error { return p.Listener.Close() }",
"func (tee *Tee) Close() {\n\ttee.primary.Close()\n\ttee.secondary.Close()\n}",
"func (t *SyncTransport) Close() error {\n\treturn nil\n}",
"func (pub *Publisher) Close() {\r\n\tif pub.chann != nil {\r\n\t\tpub.chann.Close()\r\n\t}\r\n\tif pub.conn != nil {\r\n\t\tpub.conn.Close()\r\n\t}\r\n}",
"func (c *client) Close() error { return c.c.Close() }",
"func (ec *Client) Close() {\n\tec.c.Close()\n}",
"func (*GenericFramework) PeerDisconnect(ctx *PeerContext) {}",
"func (recv *receiver) close() {\n\terr := recv.conn.Close()\n\tif err != nil {\n\t\tlog.Printf(\"receiver.close: %s\\n\", err)\n\t}\n}",
"func (self *File_Client) Close() {\n\tself.cc.Close()\n}",
"func (n *Node) Quit() <-chan struct{} {\n\treturn n.quitCh\n}",
"func (n *Node) Quit() <-chan struct{} {\n\treturn n.quitCh\n}",
"func (e *EthernetInterface) Close() {\n\tsyscall.Close(e.socket)\n}",
"func (node *hostNode) DisconnectPeer(p peer.ID) error {\n\treturn node.host.Network().ClosePeer(p)\n}",
"func (c *Connection) Close() error { return c.pump.Close() }",
"func (this *udp_listener) Close() error {\n\t/*\n\t\tif err := this.conn.Close(); nil != err {\n\t\t\treturn err\n\t\t}\n\t\tclose(this.signal)\n\t*/\n\tthis.stoped = true\n\treturn nil\n}",
"func (base *BaseProtocol) SendPeer(req *StreamRequest) error {\n\tstream, err := NewStream(base.Host, req.PeerID, req.MsgID...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer CloseStream(stream)\n\terr = WriteStream(req.Data, stream)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tCloseStream(stream)\n\treturn nil\n}",
"func (s *Stream) sendClose() error {\n\ts.controlHdrLock.Lock()\n\tdefer s.controlHdrLock.Unlock()\n\n\tflags := s.sendFlags()\n\tflags |= flagFIN\n\ts.controlHdr.encode(typeWindowUpdate, flags, s.id, 0)\n\tif err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func (f *Forward) Close() { f.OnShutdown() }"
] | [
"0.6355289",
"0.63209385",
"0.6301497",
"0.62527937",
"0.6245876",
"0.6187654",
"0.61459947",
"0.6142382",
"0.6051561",
"0.60481274",
"0.60054225",
"0.5954116",
"0.59416336",
"0.5882305",
"0.5876314",
"0.58515364",
"0.57807016",
"0.57110435",
"0.56865776",
"0.56845444",
"0.55614877",
"0.55076265",
"0.5500436",
"0.54733133",
"0.54718834",
"0.54572725",
"0.54394287",
"0.54212904",
"0.54139173",
"0.5409355",
"0.5407953",
"0.5407953",
"0.5397416",
"0.5390298",
"0.5369783",
"0.53639907",
"0.5363293",
"0.53610116",
"0.5332938",
"0.53141075",
"0.5312009",
"0.5310649",
"0.5304405",
"0.53040415",
"0.5300984",
"0.52946556",
"0.52919424",
"0.52764386",
"0.5274755",
"0.5272463",
"0.5271339",
"0.5267385",
"0.5267385",
"0.5267026",
"0.52516323",
"0.5242594",
"0.5242248",
"0.5238954",
"0.5232125",
"0.52313906",
"0.5229149",
"0.52272403",
"0.5227032",
"0.5219663",
"0.5211652",
"0.5206814",
"0.52039623",
"0.5203562",
"0.51954937",
"0.51945883",
"0.5189557",
"0.518439",
"0.51728654",
"0.51666975",
"0.51510984",
"0.514082",
"0.5139619",
"0.5134998",
"0.51333827",
"0.5127873",
"0.5125311",
"0.510604",
"0.5103478",
"0.5096657",
"0.50839865",
"0.50813824",
"0.50808465",
"0.50795233",
"0.50791234",
"0.5077439",
"0.50773066",
"0.5076705",
"0.5076705",
"0.50692534",
"0.5068231",
"0.50608075",
"0.5057421",
"0.5056414",
"0.5056156",
"0.505194"
] | 0.600045 | 11 |
That's a name of the pairing, equal on both ends. | func (n *NetImpl) peeringID(remoteNetID string) string {
if n.isInbound(remoteNetID) {
return remoteNetID + "<" + n.myNetID
}
return n.myNetID + "<" + remoteNetID
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (p Pair) Equal(pair Pair) bool {\n\treturn p.String() == pair.String()\n}",
"func (l *LabelPair) Equal(o *LabelPair) bool {\n\tswitch {\n\tcase l.Name != o.Name:\n\t\treturn false\n\tcase l.Value != o.Value:\n\t\treturn false\n\tdefault:\n\t\treturn true\n\t}\n}",
"func Pair(x, y interface{}) Node {\n\treturn Expr(\":\", x, y)\n}",
"func (p Pair) Equal(cPair Pair) bool {\n\treturn p.Base.Item == cPair.Base.Item && p.Quote.Item == cPair.Quote.Item\n}",
"func (p Pair) Equal(cPair Pair) bool {\n\treturn p.Base.Equal(cPair.Base) && p.Quote.Equal(cPair.Quote)\n}",
"func (p pair) Equal(e Equaler) bool {\n\treturn p == e.(pair)\n}",
"func Pair(arg1 TermT, arg2 TermT) TermT {\n\treturn TermT(C.yices_pair(C.term_t(arg1), C.term_t(arg2)))\n}",
"func testConnectionPair(t *testing.T, src, dst *Chain) {\n\ttestConnection(t, src, dst)\n\ttestConnection(t, dst, src)\n}",
"func (p Pair) Equal(v Pair) bool {\n\treturn bytes.Equal(p.Key, v.Key) && bytes.Equal(p.Value, v.Value)\n}",
"func (s SwapTokenPair) TokenPairName() string {\n\treturn s.BasePooledCoin.Denom + \"_\" + s.QuotePooledCoin.Denom\n}",
"func equalPairSlice(a, b []Pair) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}",
"func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool {}",
"func (p *Pair) Equals(pa Pair) bool {\n\tif p[0] == pa[0] && p[1] == pa[1] {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (inp ThingFrom) ThingPair() (out1, out2 ThingFrom) {\n\tcha1 := make(chan Thing)\n\tcha2 := make(chan Thing)\n\tgo inp.pairThing(cha1, cha2)\n\treturn cha1, cha2\n}",
"func (t *Table) Same(t2 *Table) bool {\n\treturn false\n}",
"func (b *Bluez) Pair(adapterName, deviceMac string) error {\n\treturn b.CallDevice(adapterName, deviceMac, \"Pair\", 0).Store()\n}",
"func (o DiskReplicaPairOutput) PairName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DiskReplicaPair) pulumi.StringPtrOutput { return v.PairName }).(pulumi.StringPtrOutput)\n}",
"func Pair(g1 *G1, g2 *G2) *GT {\n\treturn >{optimalAte(g2.p, g1.p)}\n}",
"func (p Pair) Swap() Pair {\n\tp.Base, p.Quote = p.Quote, p.Base\n\treturn p\n}",
"func main() {\n\temp1 := Employee{}\n\temp1.Name=\"Gowtham\"\n\n\temp2 := Employee{}\n\temp2.Name=\"Gowtham\"\n\n\tprintln(\"the emp1 and emp2 are equal ?\" , emp1 == emp2)\n}",
"func (m Mapping) equal(other Node) bool {\n\to, ok := other.(Mapping)\n\tif !ok || len(m.pairs) != len(o.pairs) || m.path != o.path {\n\t\treturn false\n\t}\n\tif m.pairs == nil || o.pairs == nil {\n\t\treturn m.pairs == nil && o.pairs == nil\n\t}\n\tfor k, v := range o.pairs {\n\t\tif !equal(m.pairs[k], v) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}",
"func Pair(children ...Element) *CompoundElement { return newCE(\"Pair\", children) }",
"func same(x int, y int) bool {\n\treturn find(x) == find(y)\n}",
"func Join(a, b Pair) Pair {\n\treturn nest{a, b}\n}",
"func testChannelPair(t *testing.T, src, dst *Chain) {\n\ttestChannel(t, src, dst)\n\ttestChannel(t, dst, src)\n}",
"func EqualsRefOfRenameTablePair(a, b *RenameTablePair) bool {\n\tif a == b {\n\t\treturn true\n\t}\n\tif a == nil || b == nil {\n\t\treturn false\n\t}\n\treturn EqualsTableName(a.FromTable, b.FromTable) &&\n\t\tEqualsTableName(a.ToTable, b.ToTable)\n}",
"func (b ButtonState) PairCheckSelf() (selfPair bool, maybeDouble bool) {\n\tif b.HasAll(ButtonsSLSR_L) || b.HasAll(ButtonsSLSR_R) {\n\t\treturn true, false\n\t}\n\tif b.HasAll(ButtonsLR) || b.HasAll(ButtonsZLZR) {\n\t\treturn true, false\n\t}\n\tif b.HasAny(ButtonsLZL) || b.HasAny(ButtonsRZR) {\n\t\treturn false, true\n\t}\n\treturn false, false\n}",
"func (p *StringPair) Exchange() {\n\tp.first, p.second = p.second, p.first\n}",
"func (DBM *DBManager) pair(sessionID int64, name string) (err error) {\n\tdatabasePointer, ok := DBM.databases.Load(name)\n\tif !ok {\n\t\treturn errors.New(\"Error pairing, Database isn't loaded or doesnt exist\")\n\t}\n\tDBM.paired.Store(sessionID, databasePointer)\n\treturn nil\n}",
"func (b *Base) Pair() currency.Pair {\n\treturn b.CurrencyPair\n}",
"func (p Pair) Swap() Pair {\n\treturn Pair{Base: p.Quote, Quote: p.Base}\n}",
"func Swap(a Pair) Pair {\n\tswitch a := a.(type) {\n\tcase nest:\n\t\treturn Join(a.Apep, a.Aten)\n\tdefault:\n\t\treturn Join(Apep(a), Aten(a))\n\t}\n}",
"func (a *Pair) Less (b *Pair) bool {\n return a.x < b.x\n}",
"func (a *Alphabet) PairLetter(b byte) (byte, error) {\n\tif a.isUnlimit {\n\t\treturn b, nil\n\t}\n\n\tif !a.IsValidLetter(b) {\n\t\treturn b, fmt.Errorf(\"invalid letter: %c\", b)\n\t}\n\tv, _ := a.pairLetters[b]\n\treturn v, nil\n}",
"func (p *SliceOfMap) Pair() (first, second *Object) {\n\tfirst, second = &Object{}, &Object{}\n\tif p == nil {\n\t\treturn\n\t}\n\tif len(*p) > 0 {\n\t\tfirst = p.At(0)\n\t}\n\tif len(*p) > 1 {\n\t\tsecond = p.At(1)\n\t}\n\treturn\n}",
"func (a joinedTable) equal(b joinedTable) bool {\n\treturn a.secondaryTable == b.secondaryTable && a.primaryColumn == b.primaryColumn && a.secondaryColumn == b.secondaryColumn\n}",
"func equals(p1, p2 *node) bool {\n\treturn p1.x == p2.x && p1.y == p2.y\n}",
"func (pair *eachPair) Equals(el interface {}) (bool) { \n other, ok := el.(*eachPair) \n if !ok { return false; }\n return pair == other\n}",
"func (b ButtonState) PairCheckDouble(b2 ButtonState) bool {\n\tif b.HasAny(ButtonsLZL) {\n\t\treturn b2.HasAny(ButtonsRZR)\n\t} else if b.HasAny(ButtonsRZR) {\n\t\treturn b2.HasAny(ButtonsLZL)\n\t}\n\treturn false\n}",
"func TestAtomicProposition_Equals1(t *testing.T) {\n\t// Constants\n\tap1 := AtomicProposition{Name: \"A\"}\n\tap2 := AtomicProposition{Name: \"B\"}\n\tap3 := AtomicProposition{Name: \"A\"}\n\n\tif ap1.Equals(ap2) {\n\t\tt.Errorf(\"ap1 (%v) is supposed to be different from ap2 (%v).\", ap1.Name, ap2.Name)\n\t}\n\n\tif !ap1.Equals(ap3) {\n\t\tt.Errorf(\"ap1 (%v) is supposed to be the same as ap3 (%v).\", ap1.Name, ap3.Name)\n\t}\n\n}",
"func (x *Secp256k1N) Eq(y *Secp256k1N) bool {\n\t// TODO: More efficient implementation/\n\tvar xNorm, yNorm = *x, *y\n\txNorm.Normalize()\n\tyNorm.Normalize()\n\treturn xNorm.limbs[0] == yNorm.limbs[0] &&\n\t\txNorm.limbs[1] == yNorm.limbs[1] &&\n\t\txNorm.limbs[2] == yNorm.limbs[2] &&\n\t\txNorm.limbs[3] == yNorm.limbs[3] &&\n\t\txNorm.limbs[4] == yNorm.limbs[4]\n}",
"func testClientPair(t *testing.T, src, dst *Chain) {\n\ttestClient(t, src, dst)\n\ttestClient(t, dst, src)\n}",
"func Same(s1, s2 Set) bool {\n\treturn *(*uintptr)(unsafe.Pointer(&s1)) == *(*uintptr)(unsafe.Pointer(&s2))\n}",
"func (t Torus) normPair(a, b Point) (Point, Point) {\n\ta = t.Norm(a)\n\tb.X = nearWrap(a.X, b.X, t.W)\n\tb.Y = nearWrap(a.Y, b.Y, t.H)\n\treturn a, b\n}",
"func swap(x string, y string) (string, string) {\n\treturn y, x\n}",
"func (p pair) string() string { // p is called the \"receiver\"\n return fmt.Sprintf(\"(%f, %f)\", p.x, p.y)\n}",
"func (n Name) Equal(other Name) bool {\n\treturn string(n) == string(other)\n}",
"func swap(x, y string) (string, string) {\n\treturn y, x\n}",
"func swap(x, y string) (string, string) {\n\treturn y, x\n}",
"func swap(x, y string) (string, string) {\n\treturn y, x\n}",
"func swap(x, y string) (string, string) {\n\treturn y, x\n}",
"func swap(x, y string) (string, string) {\n\treturn y, x\n}",
"func swap(x, y string) (string, string) {\n\treturn y, x\n}",
"func swap(x, y string) (string, string) {\n\treturn y, x\n}",
"func swap(a ,b string) (string,string) {\n\treturn b,a\n}",
"func NewPair(p *big.Int, g int64) (*big.Int, *big.Int) {\n\tprivateKey := PrivateKey(p)\n\tpublicKey := PublicKey(privateKey, p, g)\n\treturn privateKey, publicKey\n}",
"func (m *OrderedMap) Pairs() []KeyValue {\n\treturn m.kvs\n}",
"func check_two_pairs(hand []Card)bool{\r\n\tif hand[1].Rank == hand[2].Rank && hand[3].Rank == hand[4].Rank{\r\n\t\treturn true\r\n\t}\r\n\tif hand[0].Rank == hand[1].Rank && hand[3].Rank == hand[4].Rank{\r\n\t\treturn true\r\n\t}\r\n\tif hand[0].Rank == hand[1].Rank && hand[2].Rank == hand[3].Rank{\r\n\t\treturn true\r\n\t}\r\n\treturn false\r\n}",
"func (p *Pairs)Swap(i, j int) {\n\tp.pairs[i], p.pairs[j] = p.pairs[j], p.pairs[i]\n}",
"func equal(lhs, rhs semantic.Expression) semantic.Expression {\n\treturn &semantic.BinaryOp{Type: semantic.BoolType, LHS: lhs, Operator: ast.OpEQ, RHS: rhs}\n}",
"func (allPeers) InSameGroup(i, j int) bool { return true }",
"func swap(a, b string) (string, string) {\n\n\treturn b, a\n}",
"func sameNode(a, b *corev1.Node) bool {\n\treturn a.Name == b.Name\n}",
"func newPair() (pcOffer *PeerConnection, pcAnswer *PeerConnection, err error) {\n\tpca, err := NewPeerConnection(Configuration{})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpcb, err := NewPeerConnection(Configuration{})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn pca, pcb, nil\n}",
"func SwapPairs(head *ListNode) *ListNode {\n\tvar tail, pre, next *ListNode\n\tpre = head\n\tnext = head\n\tvar i int\n\tfor next != nil {\n\t\tif i%2 != 0 {\n\t\t\tpre.Next = next.Next\n\t\t\tnext.Next = pre\n\t\t\tif i == 1 {\n\t\t\t\thead = next\n\t\t\t}\n\t\t\tif tail != nil {\n\t\t\t\ttail.Next = next\n\t\t\t}\n\t\t\tnext = pre\n\t\t\tpre = pre.Next\n\t\t\ttail = next\n\t\t}\n\t\tnext = next.Next\n\t\ti++\n\t}\n\treturn head\n}",
"func (seq SeqEq[S, T]) Equal(a, b S) bool {\n\tseqA := a\n\tseqB := b\n\tfor !seq.Seq.IsVoid(seqA) && !seq.Seq.IsVoid(seqB) {\n\t\theadA := seq.Seq.Head(seqA)\n\t\theadB := seq.Seq.Head(seqB)\n\t\tif headA == nil || headB == nil || !seq.Eq.Equal(*headA, *headB) {\n\t\t\treturn false\n\t\t}\n\n\t\tseqA = seq.Seq.Tail(seqA)\n\t\tseqB = seq.Seq.Tail(seqB)\n\t}\n\n\treturn seq.Seq.IsVoid(seqA) && seq.Seq.IsVoid(seqB)\n}",
"func Equivalent(upstream, local Label) bool {\n\t// Ignore ID\n\tif upstream.Name != local.Name {\n\t\treturn false\n\t}\n\n\tupsHasColor := upstream.Color != nil\n\tlocHasColor := local.Color != nil\n\tif !locHasColor {\n\t\t// We don't care about the color locally\n\t\treturn true\n\t}\n\tif !upsHasColor {\n\t\t// Going to add the color.\n\t\treturn false\n\t}\n\t// Need to check if the color is the same\n\treturn *upstream.Color == *local.Color\n}",
"func swap(x, y string) (string, string) { // type of returned variables can be written in bracket\n\treturn y, x\n}",
"func (z *Float64) SetPair(a, b float64) *Float64 {\n\tz.l = a\n\tz.r = b\n\treturn z\n}",
"func NewPair(p *big.Int, g int64) (private, public *big.Int) {\n\tprivate = PrivateKey(p)\n\tpublic = PublicKey(private, p, g)\n\treturn\n}",
"func (z *Element22) Equal(x *Element22) bool {\n\treturn (z[21] == x[21]) && (z[20] == x[20]) && (z[19] == x[19]) && (z[18] == x[18]) && (z[17] == x[17]) && (z[16] == x[16]) && (z[15] == x[15]) && (z[14] == x[14]) && (z[13] == x[13]) && (z[12] == x[12]) && (z[11] == x[11]) && (z[10] == x[10]) && (z[9] == x[9]) && (z[8] == x[8]) && (z[7] == x[7]) && (z[6] == x[6]) && (z[5] == x[5]) && (z[4] == x[4]) && (z[3] == x[3]) && (z[2] == x[2]) && (z[1] == x[1]) && (z[0] == x[0])\n}",
"func alias(x, y nat) bool {\n\treturn cap(x) > 0 && cap(y) > 0 && &x[0:cap(x)][cap(x)-1] == &y[0:cap(y)][cap(y)-1]\n}",
"func (a *Alphabet) PairLetter(b byte) (byte, error) {\n\tif a.isUnlimit {\n\t\treturn b, nil\n\t}\n\tif int(b) >= len(a.pairLetters) {\n\t\treturn b, fmt.Errorf(\"seq: invalid letter: %c\", b)\n\t}\n\tp := a.pairLetters[b-'\\x00']\n\tif p == 0 {\n\t\treturn b, fmt.Errorf(\"seq: invalid letter: %c\", b)\n\t}\n\treturn p, nil\n}",
"func SameBrokers(\n\ta PartitionAssignment,\n\tb PartitionAssignment,\n) bool {\n\treturn util.SameElements(a.Replicas, b.Replicas)\n}",
"func (k *Key) Equal(other *Key) bool {\n\treturn k.IncompleteEqual(other) && (k.LastTok() == other.LastTok())\n}",
"func NewPair() (Socket, Socket) {\n\tca, cb := make(chan *message.Message), make(chan *message.Message)\n\tlk := &sync.Mutex{}\n\tclosedq := make(chan struct{})\n\tsa, sb := newPairSocket(ca, cb, lk, closedq), newPairSocket(cb, ca, lk, closedq)\n\tsa.peer = sb\n\tsb.peer = sa\n\n\treturn sa, sb\n}",
"func (this *Tuple) Eq(other *Tuple) bool {\n\tif this.Len() != other.Len() {\n\t\treturn false\n\t}\n\t//return reflect.DeepEqual(this.data, other.data)\n\tfor i := 0; i < this.Len(); i++ {\n\t\tlhsi, rhsi := this.Get(i), other.Get(i)\n\t\tif !TupleElemEq(lhsi, rhsi) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}",
"func NewPair(p *big.Int, g int64) (private, public *big.Int) {\n\tprivKey := PrivateKey(p)\n\tpubKey := PublicKey(privKey, p, g)\n\treturn privKey, pubKey\n}",
"func (this *Base) equals(other Piece) bool {\n\tif this.getName() != other.getName() {\n\t\treturn false\n\t}\n\n\tif this.getKanji() != other.getKanji() {\n\t\treturn false\n\t}\n\n\tif this.getColor() != other.getColor() {\n\t\treturn false\n\t}\n\n\treturn true\n}",
"func (side *Side) IsSame(sideInQuestion *Side) bool {\n\tif string(*side) == \"SELL\" && string(*sideInQuestion) == \"SELL\" {\n\t\treturn true\n\t}\n\tif string(*side) == \"BUY\" && string(*sideInQuestion) == \"BUY\" {\n\t\treturn true\n\t}\n\tif string(*side) == \"ZERO\" && string(*sideInQuestion) == \"ZERO\" {\n\t\treturn true\n\t}\n\treturn false\n}",
"func hashPair(data []int, value int) bool {\n\n\ts := set.New()\n\tsize := len(data)\n\tret := false\n\n\tfor i := 0; i < size; i++ {\n\t\tif s.Has(value - data[i]) {\n\t\t\tfmt.Println(\"The pair is:\", data[i], value-data[i])\n\t\t\tret = true\n\t\t} else {\n\t\t\ts.Insert(data[i])\n\t\t}\n\t}\n\treturn ret\n}",
"func TestPair(t *testing.T) {\n\tInitTest()\n\ts20.Init(ssid, pwd, m_id)\n\ts20s := s20.Pair()\n\tif len(s20s) != 0 {\n\t\tt.Fail()\n\t}\n}",
"func NewPair(base, counter Asset) Pair {\n\treturn Pair{\n\t\tBase: base,\n\t\tCounter: counter,\n\t}\n}",
"func (hm *HareMetadata) Equivocation(other *HareMetadata) bool {\n\treturn hm.Layer == other.Layer && hm.Round == other.Round && hm.MsgHash != other.MsgHash\n}",
"func networkTupleEquals(net1 networkTuple, net2 networkTuple) bool {\n\tif net1.ip == net2.ip && net1.netMask == net2.netMask {\n\t\treturn true\n\t}\n\treturn false\n}",
"func eq(x, y []string) bool {\n\t// NOTE: set equal\n\treturn sset.Equal(x, y)\n}",
"func (pfx Prefix) Equal(x Prefix) bool {\n\treturn pfx == x\n}",
"func (i ProjectIdentifier) equiv(j ProjectIdentifier) bool {\n\tif i.ProjectRoot != j.ProjectRoot {\n\t\treturn false\n\t}\n\tif i.NetworkName == j.NetworkName {\n\t\treturn true\n\t}\n\n\tif i.NetworkName != \"\" && j.NetworkName == \"\" {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func Same(n1, n2 External) bool {\n\tif n1 == nil && n2 == nil {\n\t\treturn true\n\t} else if n1 == nil || n2 == nil {\n\t\treturn false\n\t}\n\tif n1.Kind() != n2.Kind() {\n\t\treturn false\n\t}\n\ti1, ok := n1.(Node)\n\tif !ok {\n\t\t// first node is external, need to call SameAs on it\n\t\treturn n1.SameAs(n2)\n\t}\n\ti2, ok := n2.(Node)\n\tif !ok {\n\t\t// second node is external, need to call SameAs on it\n\t\treturn n2.SameAs(n1)\n\t}\n\t// fast path\n\tswitch i1 := i1.(type) {\n\tcase Object:\n\t\ti2, ok := i2.(Object)\n\t\tif !ok || len(i1) != len(i2) {\n\t\t\treturn false\n\t\t}\n\t\treturn pointerOf(i1) == pointerOf(i2)\n\tcase Array:\n\t\ti2, ok := i2.(Array)\n\t\tif !ok || len(i1) != len(i2) {\n\t\t\treturn false\n\t\t}\n\t\tif i1 == nil && i2 == nil {\n\t\t\treturn true\n\t\t} else if i1 == nil || i2 == nil {\n\t\t\treturn false\n\t\t} else if len(i1) == 0 {\n\t\t\treturn true\n\t\t}\n\t\treturn &i1[0] == &i2[0]\n\tcase Value:\n\t\ti2, ok := i2.(Value)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\treturn i1 == i2\n\t}\n\t// both nodes are internal - compare unique key\n\treturn UniqueKey(i1) == UniqueKey(i2)\n}",
"func (c *Comparison) IsSame() bool {\n\treturn c.First.Start.Equal(c.Second.Start) && c.First.End.Equal(c.Second.End)\n}",
"func (g *Graph) Equal(g2 *Graph, debug bool) bool {\n\n\t// Check the vertices\n\tkeys1 := g.listOfKeys()\n\tkeys2 := g2.listOfKeys()\n\n\tif !SlicesHaveSameElements(&keys1, &keys2) {\n\t\tif debug {\n\t\t\tlog.Println(\"Lists of keys are different\")\n\t\t\tlog.Printf(\"Keys1: %v\\n\", keys1)\n\t\t\tlog.Printf(\"Keys2: %v\\n\", keys2)\n\t\t}\n\t\treturn false\n\t}\n\n\t// Walk through each vertex and check its connections\n\tfor _, vertex := range keys1 {\n\t\tconns1 := g.Nodes[vertex]\n\t\tconns2 := g2.Nodes[vertex]\n\n\t\tif !SetsEqual(conns1, conns2) {\n\t\t\tif debug {\n\t\t\t\tlog.Printf(\"Connections different for vertex %v\", vertex)\n\t\t\t\tlog.Printf(\"Connections 1: %v\\n\", conns1)\n\t\t\t\tlog.Printf(\"Connections 2: %v\\n\", conns2)\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}",
"func (a *Activation) Equal(other *Activation) bool {\n\treturn a.actptr == other.actptr\n}",
"func (d Descriptor) Same(d2 Descriptor) bool {\n\tif d.Digest != d2.Digest || d.Size != d2.Size {\n\t\treturn false\n\t}\n\t// loosen the check on media type since this can be converted from a build\n\tif d.MediaType != d2.MediaType {\n\t\tif _, ok := mtToOCI[d.MediaType]; !ok {\n\t\t\treturn false\n\t\t} else if mtToOCI[d.MediaType] != mtToOCI[d2.MediaType] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}",
"func eq(x, y []string) bool {\n\t// NOTE: list equal, not set equal\n\treturn strs.Equal(x, y)\n}",
"func (f binaryEqualsFunc) name() name {\n\treturn binaryEquals\n}",
"func (l *Label) Equal(r *Label) bool {\n\treturn l == r || l.key == r.key\n}",
"func (kvp *KVPairs) IsEqual(other Expr) bool {\n\to, ok := other.(*KVPairs)\n\tif !ok {\n\t\treturn false\n\t}\n\tif kvp.SelfReferenced != o.SelfReferenced {\n\t\treturn false\n\t}\n\n\tif len(kvp.Pairs) != len(o.Pairs) {\n\t\treturn false\n\t}\n\n\tfor i := range kvp.Pairs {\n\t\tif kvp.Pairs[i].K != o.Pairs[i].K {\n\t\t\treturn false\n\t\t}\n\t\tif !Equal(kvp.Pairs[i].V, o.Pairs[i].V) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}",
"func same(x, y []string) bool {\n\txMap := make(map[string]int)\n\tyMap := make(map[string]int)\n\n\tfor _, xElem := range x {\n\t\txMap[xElem]++\n\t}\n\tfor _, yElem := range y {\n\t\tyMap[yElem]++\n\t}\n\n\tfor xMapKey, xMapVal := range xMap {\n\t\tif yMap[xMapKey] != xMapVal {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}",
"func EqualKeys(a, b VectorClock) bool {\n if len(a.Vector) != len(b.Vector) {\n return false\n }\n for k, _:= range a.Vector{\n _, exists := b.Vector[k]\n if exists == false{\n return false\n }\n }\n return true\n}",
"func ExampleSongComparison() {\n songA := gig.Song{ Name:\"My Heart Will Go On\", Rating:1 }\n songB := gig.Song{ Name:\"My Heart will Go On\", Rating:1 }\n sameSong := songA.CompareSong(&songB)\n if (sameSong) {\n fmt.Println(\"songA matches songB\")\n } else {\n fmt.Println(\"songA does not match songB\")\n }\n // Output:\n // songA does not match songB\n}",
"func (kt KeyToken) Equal(okt KeyToken) bool {\n\tif kt.Tok.IsKeyword() && kt.Key != \"\" {\n\t\treturn kt.Tok == okt.Tok && kt.Key == okt.Key\n\t}\n\treturn kt.Tok == okt.Tok\n}"
] | [
"0.6586491",
"0.64702517",
"0.638361",
"0.63350654",
"0.62906194",
"0.62117755",
"0.6142093",
"0.59811574",
"0.59172565",
"0.58246505",
"0.5794081",
"0.57475585",
"0.57271844",
"0.5688363",
"0.56602323",
"0.5655887",
"0.56194353",
"0.56139934",
"0.559652",
"0.55864394",
"0.5564981",
"0.55484897",
"0.5542892",
"0.5502842",
"0.5496321",
"0.5496104",
"0.54786396",
"0.5471113",
"0.5443867",
"0.5443072",
"0.54402626",
"0.54280645",
"0.54276055",
"0.5416191",
"0.54143584",
"0.5411715",
"0.5390875",
"0.5375175",
"0.5367818",
"0.5361251",
"0.5335166",
"0.533175",
"0.53295183",
"0.53173125",
"0.53054553",
"0.5300507",
"0.52817345",
"0.527896",
"0.527896",
"0.527896",
"0.527896",
"0.527896",
"0.527896",
"0.527896",
"0.52691895",
"0.5263247",
"0.5254701",
"0.524558",
"0.52342314",
"0.52307874",
"0.522731",
"0.5218288",
"0.5213079",
"0.5211793",
"0.52059954",
"0.5199372",
"0.5194732",
"0.5191907",
"0.51897216",
"0.5182179",
"0.5169469",
"0.5168449",
"0.5167773",
"0.51516837",
"0.51423454",
"0.5137402",
"0.5134843",
"0.51281023",
"0.51266295",
"0.5124321",
"0.5124217",
"0.512115",
"0.5117687",
"0.5092309",
"0.5089851",
"0.5081723",
"0.5076002",
"0.50547415",
"0.50317633",
"0.503151",
"0.5029013",
"0.5027659",
"0.5027492",
"0.5023108",
"0.50230265",
"0.50226",
"0.50224334",
"0.50207585",
"0.5020349",
"0.5015198",
"0.5014589"
] | 0.0 | -1 |
usePeer adds new connection to the peer pool if it already exists, returns existing. Return nil for for own netID connection added to the pool is picked by loops which will try to establish connection | func (n *NetImpl) usePeer(netID string) *peer {
if netID == n.myNetID {
// nil for itself
return nil // TODO: [KP] return self
}
n.peersMutex.Lock()
defer n.peersMutex.Unlock()
if peer, ok := n.peers[n.peeringID(netID)]; ok {
// existing peer
peer.numUsers++
return peer
}
// new peer
ret := newPeer(netID, n)
n.peers[ret.peeringID()] = ret
n.log.Debugf("added new peer id %s inbound = %v", ret.peeringID(), ret.IsInbound())
return ret
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func addPeer(peer Peer) {\n\t// iterate to find empty slot\n\tpeerListLock.Lock()\n\tfor i := 0; i < MaxPeers; i++ {\n\t\t// if peer IS dead\n\t\tif peerList[i].expirationTimer == 0 {\n\t\t\t// ensure proper port by generating again\n\t\t\tpeer.addr.Port = listeningPort\n\n\t\t\t// ensure expiration timer is reset\n\t\t\tpeer.expirationTimer = expirationDefault\n\n\t\t\t// put new peer in that slot and return\n\t\t\tpeerList[i] = peer\n\t\t\tpeerListLock.Unlock()\n\t\t\treturn\n\t\t}\n\t}\n\tpeerListLock.Unlock()\n}",
"func (bcR *BlockchainReactor) AddPeer(peer p2p.Peer) {\n\tp2p.SendEnvelopeShim(peer, p2p.Envelope{ //nolint: staticcheck\n\t\tChannelID: BlockchainChannel,\n\t\tMessage: &bcproto.StatusResponse{\n\t\t\tBase: bcR.store.Base(),\n\t\t\tHeight: bcR.store.Height(),\n\t\t},\n\t}, bcR.Logger)\n\t// it's OK if send fails. will try later in poolRoutine\n\n\t// peer is added to the pool once we receive the first\n\t// bcStatusResponseMessage from the peer and call pool.updatePeer()\n}",
"func (s *server) addPeer(p *peer) {\n\tif p == nil {\n\t\treturn\n\t}\n\n\t// Ignore new peers if we're shutting down.\n\tif atomic.LoadInt32(&s.shutdown) != 0 {\n\t\tp.Disconnect()\n\t\treturn\n\t}\n\n\t// Track the new peer in our indexes so we can quickly look it up either\n\t// according to its public key, or it's peer ID.\n\t// TODO(roasbeef): pipe all requests through to the\n\t// queryHandler/peerManager\n\ts.peersMtx.Lock()\n\n\tpubStr := string(p.addr.IdentityKey.SerializeCompressed())\n\n\ts.peersByID[p.id] = p\n\ts.peersByPub[pubStr] = p\n\n\tif p.inbound {\n\t\ts.inboundPeers[pubStr] = p\n\t} else {\n\t\ts.outboundPeers[pubStr] = p\n\t}\n\n\ts.peersMtx.Unlock()\n\n\t// Launch a goroutine to watch for the termination of this peer so we\n\t// can ensure all resources are properly cleaned up and if need be\n\t// connections are re-established.\n\tgo s.peerTerminationWatcher(p)\n\n\t// Once the peer has been added to our indexes, send a message to the\n\t// channel router so we can synchronize our view of the channel graph\n\t// with this new peer.\n\tgo s.discoverSrv.SynchronizeNode(p.addr.IdentityKey)\n}",
"func (s *server) handleConnectPeer(msg *connectPeerMsg) {\n\taddr := msg.addr\n\n\ttargetPub := string(msg.addr.IdentityKey.SerializeCompressed())\n\n\t// Ensure we're not already connected to this\n\t// peer.\n\ts.peersMtx.RLock()\n\tpeer, ok := s.peersByPub[targetPub]\n\tif ok {\n\t\ts.peersMtx.RUnlock()\n\t\tmsg.err <- fmt.Errorf(\"already connected to peer: %v\", peer)\n\t\treturn\n\t}\n\ts.peersMtx.RUnlock()\n\n\t// If there's already a pending connection request for this pubkey,\n\t// then we ignore this request to ensure we don't create a redundant\n\t// connection.\n\ts.pendingConnMtx.RLock()\n\tif _, ok := s.persistentConnReqs[targetPub]; ok {\n\t\ts.pendingConnMtx.RUnlock()\n\t\tmsg.err <- fmt.Errorf(\"connection attempt to %v is pending\",\n\t\t\taddr)\n\t\treturn\n\t}\n\ts.pendingConnMtx.RUnlock()\n\n\t// If there's not already a pending or active connection to this node,\n\t// then instruct the connection manager to attempt to establish a\n\t// persistent connection to the peer.\n\tsrvrLog.Debugf(\"Connecting to %v\", addr)\n\tif msg.persistent {\n\t\tgo s.connMgr.Connect(&connmgr.ConnReq{\n\t\t\tAddr: addr,\n\t\t\tPermanent: true,\n\t\t})\n\t\tmsg.err <- nil\n\t} else {\n\t\t// If we're not making a persistent connection, then we'll\n\t\t// attempt to connect o the target peer, returning an error\n\t\t// which indicates success of failure.\n\t\tgo func() {\n\t\t\t// Attempt to connect to the remote node. If the we\n\t\t\t// can't make the connection, or the crypto negotiation\n\t\t\t// breaks down, then return an error to the caller.\n\t\t\tconn, err := brontide.Dial(s.identityPriv, addr)\n\t\t\tif err != nil {\n\t\t\t\tmsg.err <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ts.outboundPeerConnected(nil, conn)\n\t\t\tmsg.err <- nil\n\t\t}()\n\t}\n}",
"func (pm *peerManager) addOutboundPeer(meta PeerMeta) bool {\n\taddrString := fmt.Sprintf(\"/ip4/%s/tcp/%d\", meta.IPAddress, meta.Port)\n\tvar peerAddr, err = ma.NewMultiaddr(addrString)\n\tif err != nil {\n\t\tpm.logger.Warn().Err(err).Str(\"addr\", addrString).Msg(\"invalid NPAddPeer address\")\n\t\treturn false\n\t}\n\tvar peerID = meta.ID\n\tpm.mutex.Lock()\n\tinboundPeer, ok := pm.remotePeers[peerID]\n\tif ok {\n\t\t// peer is already exist (and maybe inbound peer)\n\t\tpm.logger.Info().Str(LogPeerID, inboundPeer.meta.ID.Pretty()).Msg(\"Peer is already managed by peermanager\")\n\t\tif meta.Designated {\n\t\t\t// If remote peer was connected first. designated flag is not set yet.\n\t\t\tinboundPeer.meta.Designated = true\n\t\t}\n\t\tpm.mutex.Unlock()\n\t\treturn true\n\t}\n\tpm.mutex.Unlock()\n\n\tpm.Peerstore().AddAddr(peerID, peerAddr, meta.TTL())\n\tctx := context.Background()\n\ts, err := pm.NewStream(ctx, meta.ID, aergoP2PSub)\n\tif err != nil {\n\t\tpm.logger.Info().Err(err).Str(\"addr\", addrString).Str(LogPeerID, meta.ID.Pretty()).Str(LogProtoID, string(aergoP2PSub)).Msg(\"Error while get stream\")\n\t\treturn false\n\t}\n\n\trd := metric.NewReader(s)\n\twt := metric.NewWriter(s)\n\th := newHandshaker(pm, pm.actorServ, pm.logger, peerID)\n\trw, remoteStatus, err := h.handshakeOutboundPeerTimeout(rd, wt, defaultHandshakeTTL)\n\tif err != nil {\n\t\tpm.logger.Debug().Err(err).Str(LogPeerID, meta.ID.Pretty()).Msg(\"Failed to handshake\")\n\t\t//pm.sendGoAway(rw, \"Failed to handshake\")\n\t\ts.Close()\n\t\treturn false\n\t}\n\n\tpm.mutex.Lock()\n\tinboundPeer, ok = pm.remotePeers[peerID]\n\tif ok {\n\t\tif ComparePeerID(pm.selfMeta.ID, meta.ID) <= 0 {\n\t\t\tpm.logger.Info().Str(LogPeerID, inboundPeer.meta.ID.Pretty()).Msg(\"Inbound connection was already handshaked while handshaking outbound connection, and remote peer is higher priority so closing this outbound connection.\")\n\t\t\tpm.mutex.Unlock()\n\t\t\tpm.sendGoAway(rw, \"Already handshaked\")\n\t\t\ts.Close()\n\t\t\treturn true\n\t\t} else {\n\t\t\tpm.logger.Info().Str(LogPeerID, inboundPeer.meta.ID.Pretty()).Msg(\"Inbound connection was already handshaked while handshaking outbound connection, but local peer is higher priority so closing that inbound connection\")\n\t\t\t// disconnect lower valued connection\n\t\t\tpm.deletePeer(meta.ID)\n\t\t\tinboundPeer.stop()\n\t\t}\n\t}\n\n\t// update peer info to remote sent infor\n\tmeta = FromPeerAddress(remoteStatus.Sender)\n\n\toutboundPeer := newRemotePeer(meta, pm, pm.actorServ, pm.logger, pm.mf, pm.signer, rw)\n\t// insert Handlers\n\tpm.handlerFactory.insertHandlers(outboundPeer)\n\tgo outboundPeer.runPeer()\n\tpm.insertPeer(peerID, outboundPeer)\n\tpm.logger.Info().Str(LogPeerID, peerID.Pretty()).Str(\"addr\", net.ParseIP(meta.IPAddress).String()+\":\"+strconv.Itoa(int(meta.Port))).Msg(\"Outbound peer is added to peerService\")\n\toutboundPeer.metric = pm.mm.Add(peerID, rd, wt)\n\tpm.mutex.Unlock()\n\n\taddrs := pm.Peerstore().Addrs(peerID)\n\taddrStrs := make([]string, len(addrs))\n\tfor i, addr := range addrs {\n\t\taddrStrs[i] = addr.String()\n\t}\n\tpm.logger.Debug().Strs(\"addrs\", addrStrs).Str(LogPeerID, outboundPeer.meta.ID.Pretty()).Msg(\"addresses of peer\")\n\n\t// peer is ready\n\th.doInitialSync()\n\n\t// notice to p2pmanager that handshaking is finished\n\tpm.NotifyPeerHandshake(peerID)\n\n\treturn true\n}",
"func (e *Engine) initializePeer(peer Peer) {\n\tvar backOff = &backoff.ExponentialBackOff{\n\t\tInitialInterval: backoff.DefaultInitialInterval,\n\t\tRandomizationFactor: backoff.DefaultRandomizationFactor,\n\t\tMultiplier: backoff.DefaultMultiplier,\n\t\tMaxInterval: 5 * time.Second,\n\t\tMaxElapsedTime: time.Duration(0), //never stop\n\t\tStop: backoff.Stop,\n\t\tClock: backoff.SystemClock,\n\t}\n\toperation := func() error {\n\t\t_, err := e.openPeerConnection(e.wgPort, e.config.WgPrivateKey, peer)\n\t\te.peerMux.Lock()\n\t\tdefer e.peerMux.Unlock()\n\t\tif _, ok := e.conns[peer.WgPubKey]; !ok {\n\t\t\tlog.Infof(\"removing connection attempt with Peer: %v, not retrying\", peer.WgPubKey)\n\t\t\treturn nil\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlog.Warnln(err)\n\t\t\tlog.Warnln(\"retrying connection because of error: \", err.Error())\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\terr := backoff.Retry(operation, backOff)\n\tif err != nil {\n\t\t// should actually never happen\n\t\tpanic(err)\n\t}\n}",
"func (pm *peerManager) tryConnectPeers() {\n\tremained := pm.conf.NPMaxPeers - len(pm.remotePeers)\n\tfor ID, meta := range pm.peerPool {\n\t\tif _, found := pm.GetPeer(ID); found {\n\t\t\tdelete(pm.peerPool, ID)\n\t\t\tcontinue\n\t\t}\n\t\tif meta.IPAddress == \"\" || meta.Port == 0 {\n\t\t\tpm.logger.Warn().Str(LogPeerID, meta.ID.Pretty()).Str(\"addr\", meta.IPAddress).\n\t\t\t\tUint32(\"port\", meta.Port).Msg(\"Invalid peer meta informations\")\n\t\t\tcontinue\n\t\t}\n\t\t// in same go rountine.\n\t\tpm.addOutboundPeer(meta)\n\t\tremained--\n\t\tif remained <= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n}",
"func (s *PendingConnections) Add(peer pex.Peer) {\n\ts.Lock()\n\tdefer s.Unlock()\n\ts.value[peer.Addr] = peer\n}",
"func (epR *EventpoolReactor) AddPeer(peer p2p.Peer) {\n\tepR.ids.ReserveForPeer(peer)\n\tgo epR.broadcastEventsRoutine(peer)\n}",
"func newPeer(conn net.Conn, peerNodeInfo *types.NodeInfo, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{})) *Peer {\n\tvar p *Peer\n\tonReceive := func(chID byte, msgBytes []byte) {\n\t\treactor := reactorsByCh[chID]\n\t\tif reactor == nil {\n\t\t\tPanicSanity(Fmt(\"Unknown channel %X\", chID))\n\t\t}\n\t\treactor.Receive(chID, p, msgBytes)\n\t}\n\tonError := func(r interface{}) {\n\t\tp.Stop()\n\t\tonPeerError(p, r)\n\t}\n\tmconn := NewMConnection(conn, chDescs, onReceive, onError)\n\tp = &Peer{\n\t\toutbound: outbound,\n\t\tmconn: mconn,\n\t\tNodeInfo: peerNodeInfo,\n\t\tKey: peerNodeInfo.PubKey.KeyString(),\n\t\tData: NewCMap(),\n\t}\n\tp.BaseService = *NewBaseService(log, \"Peer\", p)\n\treturn p\n}",
"func (ps *PeerSet) Add(peer *Peer) error {\n\tps.mtx.Lock()\n\tdefer ps.mtx.Unlock()\n\tif ps.lookup[peer.Key] != nil {\n\t\treturn ErrSwitchDuplicatePeer\n\t}\n\n\t// ensure we havent maxed out connections for the peer's IP range yet\n\t// and update the IP range counters\n\tif !ps.incrIPRangeCounts(peer.Host) {\n\t\treturn ErrSwitchMaxPeersPerIPRange\n\t}\n\n\tindex := len(ps.list)\n\t// Appending is safe even with other goroutines\n\t// iterating over the ps.list slice.\n\tps.list = append(ps.list, peer)\n\tps.lookup[peer.Key] = &peerSetItem{peer, index}\n\treturn nil\n}",
"func newPeerClientConnection(block bool) (*grpc.ClientConn, error) {\n\treturn newPeerClientConnectionWithAddress(block, viper.GetString(\"service.cliaddress\"))\n}",
"func (o *IppoolPoolMember) SetPeer(v IppoolIpLeaseRelationship) {\n\to.Peer = &v\n}",
"func (s *TCPServer) registerPeer(conn *peerConn) bool {\n\tpeerAddr := conn.target\n\n\t// Abort registration if connection already exists\n\t_, duplicate := s.peers[peerAddr]\n\tif duplicate {\n\t\tlog.Printf(\"p2p server: peer already registered, %s\", peerAddr)\n\t\tconn.target = \"\"\n\t\tif strings.Compare(peerAddr, s.addr) > 0 {\n\t\t\tlog.Println(\"skipping \", peerAddr)\n\t\t} else {\n\t\t\tlog.Println(\"p2p server: closing \", peerAddr)\n\t\t\ts.removePeer(conn)\n\t\t}\n\t\treturn false\n\t}\n\n\tlog.Println(\"p2p server: registering peer \", peerAddr)\n\ts.seenPeers[conn.target] = struct{}{}\n\ts.peers[peerAddr] = conn\n\ts.targets = append(s.targets, peerAddr)\n\treturn true\n}",
"func (o *MacpoolPoolMemberAllOf) SetPeer(v MacpoolLeaseRelationship) {\n\to.Peer = &v\n}",
"func Peer(target string) {\n\tserver.listen()\n\tserver.seenPeers[target] = struct{}{}\n\tserver.dial(target)\n\tserver.managePeers()\n}",
"func (app *App) AddPeer(peerInfo peerstore.PeerInfo) error {\n\tctx, cancel := context.WithTimeout(context.Background(), peerConnectTimeout)\n\tdefer cancel()\n\treturn app.node.Connect(ctx, peerInfo)\n}",
"func (e *Engine) openPeerConnection(wgPort int, myKey wgtypes.Key, peer Peer) (*Connection, error) {\n\te.peerMux.Lock()\n\n\tremoteKey, _ := wgtypes.ParseKey(peer.WgPubKey)\n\tconnConfig := &ConnConfig{\n\t\tWgListenAddr: fmt.Sprintf(\"127.0.0.1:%d\", wgPort),\n\t\tWgPeerIP: e.config.WgAddr,\n\t\tWgIface: e.config.WgIface,\n\t\tWgAllowedIPs: peer.WgAllowedIps,\n\t\tWgKey: myKey,\n\t\tRemoteWgKey: remoteKey,\n\t\tStunTurnURLS: append(e.STUNs, e.TURNs...),\n\t\tiFaceBlackList: e.config.IFaceBlackList,\n\t}\n\n\tsignalOffer := func(uFrag string, pwd string) error {\n\t\treturn signalAuth(uFrag, pwd, myKey, remoteKey, e.signal, false)\n\t}\n\n\tsignalAnswer := func(uFrag string, pwd string) error {\n\t\treturn signalAuth(uFrag, pwd, myKey, remoteKey, e.signal, true)\n\t}\n\tsignalCandidate := func(candidate ice.Candidate) error {\n\t\treturn signalCandidate(candidate, myKey, remoteKey, e.signal)\n\t}\n\tconn := NewConnection(*connConfig, signalCandidate, signalOffer, signalAnswer)\n\te.conns[remoteKey.String()] = conn\n\te.peerMux.Unlock()\n\n\t// blocks until the connection is open (or timeout)\n\terr := conn.Open(PeerConnectionTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn conn, nil\n}",
"func (g *Gossiper) AddPeer(peerAddr *(net.UDPAddr)) {\n\tpeerConn, err := net.DialUDP(\"udp4\", nil, peerAddr)\n\tif err != nil {\n\t\tfmt.Printf(\"Error: could not connect to given peer: %v\", err)\n\t\tos.Exit(-1)\n\t}\n\tg.peers.AddPeer(peerAddr.String(), peerConn)\n\n\tg.newNodes = append(g.newNodes, peerAddr.String())\n}",
"func (fds SocketPair) PeerConn() (net.Conn, error) {\n\tfile := fds.PeerFile()\n\tdefer file.Close()\n\tconn, err := net.FileConn(file)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create net.Conn for %s[1]: %w\", fds.fileName(), err)\n\t}\n\treturn conn, nil\n}",
"func (c *RegionCache) NextPeer(id RegionVerID) {\n\t// A and B get the same region and current leader is 1, they both will pick\n\t// peer 2 as leader.\n\tregion := c.GetRegionByVerID(id)\n\tif region == nil {\n\t\treturn\n\t}\n\tif leader, err := region.NextPeer(); err != nil {\n\t\tc.mu.Lock()\n\t\tdelete(c.regions, id)\n\t\tc.mu.Unlock()\n\t} else {\n\t\tc.UpdateLeader(id, leader.GetId())\n\t}\n}",
"func (v *priorityClientPool) registerPeer(p *peer) {\n\tv.lock.Lock()\n\tdefer v.lock.Unlock()\n\n\tid := p.ID()\n\tc := v.clients[id]\n\tv.logger.Event(fmt.Sprintf(\"priorityClientPool: registerPeer cap=%d connected=%v, %x\", c.cap, c.connected, id.Bytes()))\n\tif c.connected {\n\t\treturn\n\t}\n\tif c.cap == 0 && v.child != nil {\n\t\tv.child.registerPeer(p)\n\t}\n\tif c.cap != 0 && v.totalConnectedCap+c.cap > v.totalCap {\n\t\tv.logger.Event(fmt.Sprintf(\"priorityClientPool: rejected, %x\", id.Bytes()))\n\t\tgo v.ps.Unregister(p.id)\n\t\treturn\n\t}\n\n\tc.connected = true\n\tc.peer = p\n\tv.clients[id] = c\n\tif c.cap != 0 {\n\t\tv.priorityCount++\n\t\tv.totalConnectedCap += c.cap\n\t\tv.logger.Event(fmt.Sprintf(\"priorityClientPool: accepted with %d capacity, %x\", c.cap, id.Bytes()))\n\t\tv.logTotalPriConn.Update(float64(v.totalConnectedCap))\n\t\tif v.child != nil {\n\t\t\tv.child.setLimits(v.maxPeers-v.priorityCount, v.totalCap-v.totalConnectedCap)\n\t\t}\n\t\tp.updateCapacity(c.cap)\n\t}\n}",
"func (o *ResourcepoolPoolMember) SetPeer(v ResourcepoolLeaseRelationship) {\n\to.Peer = &v\n}",
"func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq, inbound bool) {\n\tbrontideConn := conn.(*brontide.Conn)\n\tpeerAddr := &lnwire.NetAddress{\n\t\tIdentityKey: brontideConn.RemotePub(),\n\t\tAddress: conn.RemoteAddr().(*net.TCPAddr),\n\t\tChainNet: activeNetParams.Net,\n\t}\n\n\t// Now that we've established a connection, create a peer, and\n\t// it to the set of currently active peers.\n\tp, err := newPeer(conn, connReq, s, peerAddr, inbound)\n\tif err != nil {\n\t\tsrvrLog.Errorf(\"unable to create peer %v\", err)\n\t\treturn\n\t}\n\n\t// TODO(roasbeef): update IP address for link-node\n\t// * also mark last-seen, do it one single transaction?\n\n\t// Attempt to start the peer, if we're unable to do so, then disconnect\n\t// this peer.\n\tif err := p.Start(); err != nil {\n\t\tsrvrLog.Errorf(\"unable to start peer: %v\", err)\n\t\tp.Disconnect()\n\t\treturn\n\t}\n\n\ts.newPeers <- p\n}",
"func startPeer(t *testing.T, port uint) *Conn {\n\tconn := NewConn()\n\tgo monitor(conn.Err, t)\n\terr := conn.Listen(port)\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot start peer: %q\", err)\n\t\treturn nil\n\t}\n\treturn conn\n}",
"func newPeer(conn *peerConn, ps []Protocol) Peer {\n\tp := &peer{\n\t\tconn: conn,\n\t\tid: conn.id,\n\t\trw: conn.rw,\n\t\tlogger: conn.logger,\n\t\tps: ps,\n\t\tclose: make(chan struct{}),\n\t\tquit: make(chan struct{}),\n\t\tpsCh: make(chan MessageReader),\n\t}\n\tnow := time.Now()\n\tp.lastTime = now.Unix()\n\treturn p\n}",
"func (c *Client) connectToPeer(peer *Peer, torrent *Torrent) bool {\n\tpeerIP := peer.RemotePeerIP\n\tpeerPortNum := peer.RemotePeerPort\n\tinfohash := torrent.InfoHash\n\tcount := 0\n\n\tfor count < 1 {\n\t\tcount += 1\n\n\t\t// fmt.Println(\"Conducting handshake to : \", peerIP, \" : \", peerPortNum, \" ......\")\n\t\tconn, err := net.DialTimeout(\"tcp\", peerIP+\":\"+strconv.Itoa(int(peerPortNum)), time.Duration(1)*time.Second)\n\t\tif err != nil {\n\t\t\t// fmt.Println(\"ERROR IN PEER TCP HANDSHAKE : \", err)\n\t\t\tpeerPortNum += 1\n\t\t\tcontinue\n\t\t}\n\t\t// fmt.Println(\"---- tcp handshake complete.. starting peer handshake-----\")\n\n\t\t// Client transmit first message to server\n\t\tfirstMsg := createHandShakeMsg(\"BitTorrent protocol\", infohash, c.Id)\n\t\tconn.Write(firstMsg)\n\n\t\t//Recieve handshake\n\t\tlengthBuf := make([]byte, 1)\n\t\t_, err = conn.Read(lengthBuf)\n\t\tif err != nil {\n\t\t\tpeerPortNum += 1\n\t\t\tcontinue\n\t\t}\n\n\t\tstrLen := lengthBuf[0]\n\t\thandshakeLen := int(strLen) + 48\n\t\tbuf := make([]byte, handshakeLen)\n\t\t_, err = conn.Read(buf)\n\n\t\tif err != nil {\n\t\t\tpeerPortNum += 1\n\t\t\tcontinue\n\t\t}\n\n\t\trecvInfoHash := string(buf[8+strLen : 28+strLen])\n\t\trecvPeerId := string(buf[28+strLen:])\n\n\t\t//CHECK for inconsistent info hash or peer id\n\t\tif peer.RemotePeerId == \"\" {\n\t\t\tpeer.RemotePeerId = recvPeerId\n\t\t}\n\n\t\tif peer.RemotePeerId != recvPeerId || infohash != recvInfoHash {\n\t\t\tconn.Close()\n\t\t\tfmt.Println(\"incorrect handshake value in peer handshake \")\n\t\t\treturn false\n\t\t}\n\n\t\tpeer.Connection = &conn\n\n\t\tbitMapBuf := make([]byte, 4096)\n\t\tnumRecved := 0\n\t\tnumRecved, err = conn.Read(bitMapBuf)\n\n\t\tif err != nil && err != io.EOF {\n\t\t\tfmt.Println(\"error in reading bitmap of peer , error:\", err)\n\t\t\treturn false\n\t\t}\n\n\t\tbitMapBuf = bitMapBuf[0:numRecved]\n\t\tbitMapRecvLen := binary.BigEndian.Uint32(bitMapBuf[:4]) - 1\n\t\tif bitMapRecvLen == 0 {\n\t\t\treturn false\n\t\t}\n\n\t\tpeer.RemoteBitMap = bitMapBuf[5 : 5+bitMapRecvLen]\n\t\t// fmt.Println(bitMapBuf[5 : 5+bitMapRecvLen])\n\t\t// fmt.Println(\"handshake complete...\\n\\n\\n\")\n\t\treturn true\n\n\t}\n\n\treturn false\n}",
"func (s *server) AddPeer(name string, connectiongString string) error {\n\ts.debugln(\"server.peer.add: \", name, len(s.peers))\n\n\t// Do not allow peers to be added twice.\n\tif s.peers[name] != nil {\n\t\treturn nil\n\t}\n\n\t// Skip the Peer if it has the same name as the Server\n\tif s.name != name {\n\t\tpeer := newPeer(s, name, connectiongString, s.heartbeatInterval)\n\n\t\tif s.State() == Leader {\n\t\t\tpeer.startHeartbeat()\n\t\t}\n\n\t\ts.peers[peer.Name] = peer\n\n\t\t//s.DispatchEvent(newEvent(AddPeerEventType, name, nil))\n\t}\n\n\t// Write the configuration to file.\n\t//s.writeConf()\n\n\treturn nil\n}",
"func (gossiper *Gossiper) AddPeer(address string) {\n\tgossiper.peerMutex.Lock()\n\tgossiper.Peers = append(gossiper.Peers, address)\n\tgossiper.peerMutex.Unlock()\n\tgossiper.statusWaiting.Store(address, make(chan *messages.StatusPacket))\n\tgossiper.expected.Store(address, make(chan bool))\n}",
"func (a *Agent) AddPeers(ctx context.Context, p pool.Pool, num int) error {\n\tkind := \"\" // Any kind of node by default\n\tif !a.nodeInfo.IsFullNode {\n\t\t// Non-full-nodes need nodes of the same kind to peer with (light nodes)\n\t\tkind = a.nodeInfo.Kind.String()\n\t}\n\n\tlogger.Printf(\"Requesting more kind=%q peers from pool: %d\", kind, num)\n\tpeerResp, err := p.Peer(ctx, pool.PeerRequest{\n\t\tNum: num,\n\t\tKind: kind,\n\t})\n\tif err != nil && jsonrpc2.IsErrorCode(err, jsonrpc2.ErrCodeInternal) {\n\t\tif strings.HasPrefix(err.Error(), \"no available\") {\n\t\t\treturn ErrNoPeers\n\t\t} else {\n\t\t\t// This can happen if there are some incompatible agents on the\n\t\t\t// pool (e.g. outdated broken vipnode version)\n\t\t\tlogger.Printf(\"AddPeers RPC failed (possibly due to outdated agents on the pool): %s\", err)\n\t\t\t// We can't recover on this end. This should also yield errors on\n\t\t\t// the broken agents' side so hopefully they'll update soon.\n\t\t\treturn ErrNoPeers\n\t\t}\n\t} else if err != nil {\n\t\treturn AgentPoolError{err, \"Failed during pool peer request\"}\n\t}\n\tnodes := peerResp.Peers\n\tlogger.Printf(\"Received %d peer candidates from pool.\", len(nodes))\n\tfor _, node := range nodes {\n\t\tif err := a.EthNode.ConnectPeer(ctx, node.URI); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}",
"func savePeer(peer repository.Peer) {\n\tif peer.IpAddress == *nodeIp && peer.Port == *nodePort {\n\t\treturn\n\t}\n\tnodeKey := fmt.Sprintf(\"%v:%v\", *nodeIp, *nodePort)\n\tsqlRepository.SavePeer(nodeKey, peer.IpAddress, peer.Port)\n}",
"func (r *room) addPeer(p *peer) {\n\tr.Lock()\n\tdefer r.Unlock()\n\tr.peers[p.uid] = p\n}",
"func (r *room) addPeer(p *Peer) {\n\tr.Lock()\n\tdefer r.Unlock()\n\tr.peers[p.uid] = p\n}",
"func choosePeer(peers addresses, id peer.ID) (rpcclient.HighwayAddr, error) {\n\tcst := consistent.New()\n\tcst.NumberOfReplicas = 1000\n\tfor _, p := range peers {\n\t\tcst.Add(p.Libp2pAddr)\n\t}\n\n\tclosest, err := cst.Get(string(id))\n\tif err != nil {\n\t\treturn rpcclient.HighwayAddr{}, errors.Errorf(\"could not get consistent-hashing peer %v %v\", peers, id)\n\t}\n\n\tfor _, p := range peers {\n\t\tif p.Libp2pAddr == closest {\n\t\t\treturn p, nil\n\t\t}\n\t}\n\treturn rpcclient.HighwayAddr{}, errors.Errorf(\"could not find closest peer %v %v %v\", peers, id, closest)\n}",
"func (r *Replica) waitForPeerConnections(done chan bool) {\n\tvar b [4]byte\n\tbs := b[:4]\n\n\tvar err error\n\tlAddr := r.PeerAddrList[r.Id][strings.Index(r.PeerAddrList[r.Id], \":\"):]\n\tlog.Printf(\"Listening for peers on %s\\n\", lAddr)\n\tr.Listener, err = net.Listen(\"tcp\", lAddr)\n\tif err != nil {\n\t\tlog.Printf(\"Error listening to peer %d: %v\\n\", r.Id, err)\n\t\tos.Exit(1)\n\t}\n\n\tfor i := r.Id + 1; i < int32(r.N); i++ {\n\t\tconn, err := r.Listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error accepting connection from peer: %v\\n\",\n\t\t\t\terr)\n\t\t\tcontinue\n\t\t}\n\t\tdlog.Printf(\"Accepted connection from peer %s.\\n\", conn.RemoteAddr().String())\n\t\tif n, err := io.ReadFull(conn, bs); err != nil || n != len(bs) {\n\t\t\tlog.Printf(\"Error reading peer id: %v (%d bytes read)\\n\", err, n)\n\t\t\tcontinue\n\t\t}\n\t\tid := int32(binary.LittleEndian.Uint32(bs))\n\t\tif id <= r.Id || id >= int32(r.N) {\n\t\t\tlog.Fatalf(\"Read incorrect id %d from connecting peer\\n\", id)\n\t\t}\n\t\tlog.Printf(\"Peer sent %d as id (%d total peers).\\n\", id, len(r.Peers))\n\t\tr.Peers[id] = conn\n\t\tr.PeerReaders[id] = bufio.NewReader(conn)\n\t\tr.PeerWriters[id] = bufio.NewWriter(conn)\n\t\tr.Alive[id] = true\n\t\tlog.Printf(\"Successfully established connection with peer %d\\n\", id)\n\t}\n\n\tdone <- true\n}",
"func (g *Gateway) addPeer(p *peer) {\n\tg.peers[p.addr] = p\n\tg.addNode(p.addr)\n\tgo g.listenPeer(p)\n}",
"func (s *Swarm) dialPeer(ctx context.Context, p peer.ID) (*Conn, error) {\n\tlog.Debugw(\"dialing peer\", \"from\", s.local, \"to\", p)\n\terr := p.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif p == s.local {\n\t\treturn nil, ErrDialToSelf\n\t}\n\n\t// check if we already have an open (usable) connection first, or can't have a usable\n\t// connection.\n\tconn, err := s.bestAcceptableConnToPeer(ctx, p)\n\tif conn != nil || err != nil {\n\t\treturn conn, err\n\t}\n\n\tif s.gater != nil && !s.gater.InterceptPeerDial(p) {\n\t\tlog.Debugf(\"gater disallowed outbound connection to peer %s\", p.Pretty())\n\t\treturn nil, &DialError{Peer: p, Cause: ErrGaterDisallowedConnection}\n\t}\n\n\t// apply the DialPeer timeout\n\tctx, cancel := context.WithTimeout(ctx, network.GetDialPeerTimeout(ctx))\n\tdefer cancel()\n\n\tconn, err = s.dsync.Dial(ctx, p)\n\tif err == nil {\n\t\treturn conn, nil\n\t}\n\n\tlog.Debugf(\"network for %s finished dialing %s\", s.local, p)\n\n\tif ctx.Err() != nil {\n\t\t// Context error trumps any dial errors as it was likely the ultimate cause.\n\t\treturn nil, ctx.Err()\n\t}\n\n\tif s.ctx.Err() != nil {\n\t\t// Ok, so the swarm is shutting down.\n\t\treturn nil, ErrSwarmClosed\n\t}\n\n\treturn nil, err\n}",
"func newPeer(serverInfo *PeerCom, addr *common.NetAddress, outBound, persistent bool, msgChan chan<- *InternalMsg, conn net.Conn) *Peer {\n\tpeer := &Peer{\n\t\tPeerCom: PeerCom{\n\t\t\taddr: addr,\n\t\t\tpersistent: persistent,\n\t\t},\n\t\tserverInfo: serverInfo,\n\t\tinternalChan: make(chan message.Message),\n\t\tsendChan: make(chan *InternalMsg),\n\t\trecvChan: msgChan,\n\t\tquitChan: make(chan interface{}),\n\t\tknownMsgs: common.NewRingBuffer(1024),\n\t\tisRunning: 0,\n\t}\n\tpeer.outBound.Store(outBound)\n\tif !outBound && conn != nil {\n\t\tpeer.conn = NewPeerConn(conn, peer.internalChan)\n\t}\n\treturn peer\n}",
"func AddPeer(w http.ResponseWriter, r *http.Request) {\n\t// Connect to the peer\n\tvar newPeers peerStr\n\n\terr := json.NewDecoder(r.Body).Decode(&newPeers)\n\tif err != nil {\n\t\tlog.Println(\"AddPeer: could not decode peer\")\n\t}\n\tlog.Println(newPeers)\n\tlog.Printf(\"AddPeer: adding=%s\", newPeers.Peer)\n\n\tConnectToPeers(newPeers.Peer)\n}",
"func addPeer(rid proto.RID, peer *peer) {\n\tlog.Infof(\"AddPeer rid=%s uid=%s\", rid, peer.uid)\n\troom := getRoom(rid)\n\tif room == nil {\n\t\troom = newRoom(rid)\n\t}\n\troom.addPeer(peer)\n}",
"func newPeerClientConnectionWithAddress(block bool, peerAddress string) (*grpc.ClientConn, error) {\n\tif comm.TLSEnabledforService() {\n\t\treturn comm.NewClientConnectionWithAddress(peerAddress, block, true, comm.InitTLSForPeer())\n\t}\n\treturn comm.NewClientConnectionWithAddress(peerAddress, block, false, nil)\n}",
"func (peer *peerImp) AddUse() {\n\tpeer.useCounter++\n}",
"func addUniquePeer(peers []net.Addr, peer net.Addr) []net.Addr {\n\tif peerExists(peers, peer) {\n\t\treturn peers\n\t} else {\n\t\treturn append(peers, peer)\n\t}\n}",
"func (p *peer) AddPeersPeers() {\n\tdefer p.ms.Done() // it's a goroutine\n\n\tif strings.Index(p.Url, getPeersUrl) < 0 {\n\t\tlog.Println(\"Error: you can only addpeers with a\", getPeersUrl, \"request\")\n\t\treturn\n\t}\n\n\t////\n\t// Get remote meshping server publich state. This may take a while!\n\t// That's why this is a goroutine...\n\trm, err := FetchRemotePeer(p.Url, p.PeerIP)\n\tif err != nil {\n\t\treturn // FetchRemotePeer reported to log(stderr) already\n\t}\n\n\tif p.ms.Verbose() > 2 {\n\t\tlog.Println(\"Got a remote server's state:\")\n\t\tenc := json.NewEncoder(os.Stdout)\n\t\tenc.SetIndent(\"\", \" \")\n\t\t// No need to take a lock on the mutex\n\t\tif err := enc.Encode(rm); err != nil {\n\t\t\tclient.LogSentry(sentry.LevelWarning, \"Error converting remote state to json: %s\", err)\n\t\t}\n\t}\n\n\tfor _, rmp := range rm.Peers {\n\t\turl := rmp.Url\n\t\tip := rmp.PeerIP\n\t\tpeer := p.ms.FindPeer(url, ip)\n\t\tif peer != nil {\n\t\t\tif p.ms.Verbose() > 2 {\n\t\t\t\tlog.Println(\"peer\", url, ip, \"-- PeerAlreadyPresent\")\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Println(\"adding peer\", url, ip)\n\t\tpeer = p.ms.NewPeer(url, ip, p.Location)\n\t\tpeer.ms.Add() // for the Ping goroutine\n\t\tgo peer.Ping()\n\t}\n}",
"func TestAddPeer(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\tg := newTestingGateway(t)\n\tdefer g.Close()\n\n\tg.mu.Lock()\n\tdefer g.mu.Unlock()\n\tg.addPeer(&peer{\n\t\tPeer: modules.Peer{\n\t\t\tNetAddress: \"foo.com:123\",\n\t\t},\n\t\tsess: newClientStream(new(dummyConn), build.Version),\n\t})\n\tif len(g.peers) != 1 {\n\t\tt.Fatal(\"gateway did not add peer\")\n\t}\n}",
"func (s *Switch) addIncomingPeer(n p2pcrypto.PublicKey) error {\n\ts.inpeersMutex.RLock()\n\tamnt := len(s.inpeers)\n\t_, exist := s.inpeers[n]\n\ts.inpeersMutex.RUnlock()\n\n\tif amnt >= s.config.MaxInboundPeers {\n\t\t// todo: close connection with CPOOL\n\t\treturn errors.New(\"reached max connections\")\n\t}\n\n\ts.inpeersMutex.Lock()\n\ts.inpeers[n] = struct{}{}\n\ts.inpeersMutex.Unlock()\n\tif !exist {\n\t\ts.publishNewPeer(n)\n\t\ts.discover.Attempt(n) // or good?\n\t\tmetrics.InboundPeers.Add(1)\n\t}\n\treturn nil\n}",
"func (pm *ConfigManager) AddPeer(multiAddress multiaddr.Multiaddr, alias string) error {\n\tpm.peersLock.Lock()\n\tdefer pm.peersLock.Unlock()\n\n\tnewPeerAddrInfo, err := peer.AddrInfoFromP2pAddr(multiAddress)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, p := range pm.peers {\n\t\tmultiAddr, err := multiaddr.NewMultiaddr(p.MultiAddress)\n\t\tif err != nil {\n\t\t\t// ignore wrong values in the config file\n\t\t\tcontinue\n\t\t}\n\n\t\taddrInfo, err := peer.AddrInfoFromP2pAddr(multiAddr)\n\t\tif err != nil {\n\t\t\t// ignore wrong values in the config file\n\t\t\tcontinue\n\t\t}\n\n\t\tif addrInfo.ID == newPeerAddrInfo.ID {\n\t\t\treturn errors.New(\"peer already exists\")\n\t\t}\n\t}\n\n\t// no peer with the same ID found, add the new one\n\tpm.peers = append(pm.peers, &PeerConfig{\n\t\tMultiAddress: multiAddress.String(),\n\t\tAlias: alias,\n\t})\n\n\treturn pm.Store()\n}",
"func (m *Manager) AddPeer(peer *peer.Peer) error {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\tif !peer.IsAllowed() {\n\t\terrr := errors.New(\"denied\")\n\t\tlog.Println(errr)\n\t\treturn errr\n\t}\n\tif !peer.IsAllowed() || !m.peers.Add(peer) {\n\t\treturn nil\n\t}\n\treturn m.self.WritePeers(m.peers)\n}",
"func (peer *PeerConnection) addConnection(sock *NamedWebSocket) {\n\t// Add this websocket instance to Named WebSocket broadcast list\n\tsock.peers = append(sock.peers, peer)\n\n\t// Inform all control connections that we now own this peer connection\n\tfor _, control := range sock.controllers {\n\t\t// don't notify controller if its id matches the peer's id\n\t\tif control.id != peer.id {\n\t\t\tcontrol.send(\"connect\", control.id, peer.id, \"\")\n\t\t}\n\t}\n\n\t// Inform all proxy connections that we now own this peer connection\n\tfor _, proxy := range sock.proxies {\n\t\tif proxy.writeable {\n\t\t\tproxy.send(\"connect\", proxy.id, peer.id, \"\")\n\t\t}\n\t}\n\n\t// Start connection read/write pumps\n\tgo peer.writeConnectionPump(sock)\n\tgo peer.readConnectionPump(sock)\n}",
"func (c *Client) AddPeerToPeerStore(peerAddr string) (peer.ID, error) {\n\t// generate a multiformat address to connect to\n\t// /ip4/192.168.1.101/tcp/9999/ipfs/QmbtKadk9x6s56Wh226Wu84ZUc7xEe7AFgvm9bYUbrENDM\n\tipfsaddr, err := ma.NewMultiaddr(peerAddr)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// extract the ipfs peer id for the node\n\t// QmbtKadk9x6s56Wh226Wu84ZUc7xEe7AFgvm9bYUbrENDM\n\tpid, err := ipfsaddr.ValueForProtocol(ma.P_IPFS)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// decode the peerid\n\t// <peer.ID Qm*brENDM>\n\tpeerid, err := peer.IDB58Decode(pid)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// generate an ipfs based peer address address that we connect to\n\t// /ipfs/QmbtKadk9x6s56Wh226Wu84ZUc7xEe7AFgvm9bYUbrENDM\n\ttargetPeerAddr, err := ma.NewMultiaddr(\n\t\tfmt.Sprintf(\"/ipfs/%s\", pid),\n\t)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// generate a basic multiformat ip address to connect to\n\t// /ip4/192.168.1.101/tcp/9999\n\ttargetAddr := ipfsaddr.Decapsulate(targetPeerAddr)\n\t// add a properly formatted libp2p address to connect to\n\tc.Host.Peerstore().AddAddr(\n\t\tpeerid, targetAddr, pstore.PermanentAddrTTL,\n\t)\n\treturn peerid, nil\n}",
"func (p *Pool) addUsedClient() *ClientConn {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif p.poolSize >= p.opt.PoolSize {\n\t\treturn nil\n\t}\n\n\tconn, err := p.newClient()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil\n\t}\n\n\tp.poolSize++\n\tp.clients = append(p.clients, conn)\n\treturn conn\n}",
"func (rs *ReactorShim) AddPeer(peer Peer) {\n\tpeerID, err := PeerIDFromString(string(peer.ID()))\n\tif err != nil {\n\t\trs.Logger.Error(\"failed to add peer\", \"peer\", peer.ID(), \"err\", err)\n\t\treturn\n\t}\n\n\tselect {\n\tcase rs.PeerUpdates.updatesCh <- PeerUpdate{PeerID: peerID, Status: PeerStatusUp}:\n\t\trs.Logger.Debug(\"sent peer update\", \"reactor\", rs.Name, \"peer\", peerID.String(), \"status\", PeerStatusUp)\n\n\tcase <-rs.PeerUpdates.Done():\n\t\t// NOTE: We explicitly DO NOT close the PeerUpdatesCh's updateCh go channel.\n\t\t// This is because there may be numerous spawned goroutines that are\n\t\t// attempting to send on the updateCh go channel and when the reactor stops\n\t\t// we do not want to preemptively close the channel as that could result in\n\t\t// panics sending on a closed channel. This also means that reactors MUST\n\t\t// be certain there are NO listeners on the updateCh channel when closing or\n\t\t// stopping.\n\t}\n}",
"func (peer *Peer) Add(db *sql.DB) {\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tstmt, err := tx.Prepare(\"insert or replace into peer(ip, port, lastSeen) values(?, ?, ?)\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(peer.IP, peer.Port, peer.LastSeen)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttx.Commit()\n}",
"func (c *Client) NewPeer(payload string) bool {\n\tvar result bool\n\tif err := c.ClientRPC.Call(\"Server.NewPeer\", payload, &result); err != nil {\n\t\tlog.Println(err)\n\t}\n\treturn result\n}",
"func (h *clientHandler) runPeer(version uint, p *p2p.Peer, rw p2p.MsgReadWriter) error {\n\ttrusted := false\n\tif h.ulc != nil {\n\t\ttrusted = h.ulc.trusted(p.ID())\n\t}\n\tpeer := newPeer(int(version), h.backend.config.NetworkId, trusted, p, newMeteredMsgWriter(rw, int(version)))\n\tpeer.poolEntry = h.backend.serverPool.connect(peer, peer.Node())\n\tif peer.poolEntry == nil {\n\t\treturn p2p.DiscRequested\n\t}\n\th.wg.Add(1)\n\tdefer h.wg.Done()\n\terr := h.handle(peer)\n\th.backend.serverPool.disconnect(peer.poolEntry)\n\treturn err\n}",
"func (s *KVRaftService) AddPeer(peer string) {\n\trpcCmd := RpcCmd{\n\t\tOp: CmdJoin,\n\t\tValue: []byte(peer),\n\t}\n\trpcAddr := fmt.Sprintf(\"%s:%s\", ShCache.LeaderRpcAddr, ShCache.LeaderRpcPort)\n\ts.log.Println(\"[Join Raft RPC] rpcAddr:\", rpcAddr)\n\tdoJoin(rpcCmd, rpcAddr)\n\n}",
"func (o *ResourcepoolPoolMember) HasPeer() bool {\n\tif o != nil && o.Peer != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (s *Switch) getMorePeers(ctx context.Context, numpeers int) int {\n\tif numpeers == 0 {\n\t\treturn 0\n\t}\n\n\tlogger := s.logger.WithContext(ctx)\n\n\t// discovery should provide us with random peers to connect to\n\tnds := s.discover.SelectPeers(s.shutdownCtx, numpeers)\n\tndsLen := len(nds)\n\tif ndsLen == 0 {\n\t\tlogger.Debug(\"peer sampler returned nothing\")\n\t\t// this gets busy at start so we spare a second\n\t\treturn 0 // zero samples here so no reason to proceed\n\t}\n\n\ttype cnErr struct {\n\t\tn *node.Info\n\t\terr error\n\t}\n\n\tres := make(chan cnErr, numpeers)\n\n\t// Try a connection to each peer.\n\t// TODO: try splitting the load and don't connect to more than X at a time\n\tfor i := 0; i < ndsLen; i++ {\n\t\tif s.isShuttingDown() {\n\t\t\tbreak\n\t\t}\n\t\tnd := nds[i]\n\t\treportChan := res\n\t\ts.eg.Go(func() error {\n\t\t\tif nd.PublicKey() == s.lNode.PublicKey() {\n\t\t\t\treportChan <- cnErr{nd, errors.New(\"connection to self\")}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\ts.discover.Attempt(nd.PublicKey())\n\t\t\taddr := inet.TCPAddr{IP: inet.ParseIP(nd.IP.String()), Port: int(nd.ProtocolPort)}\n\t\t\t_, err := s.cPool.GetConnection(ctx, &addr, nd.PublicKey())\n\t\t\treportChan <- cnErr{nd, err}\n\t\t\treturn nil\n\t\t})\n\t}\n\n\ttotal, bad := 0, 0\n\ttm := time.NewTimer(s.connectingTimeout) // todo: configure\nloop:\n\tfor {\n\t\tselect {\n\t\t// NOTE: breaks here intentionally break the select and not the for loop\n\t\tcase cne := <-res:\n\t\t\ttotal++ // We count i every time to know when to close the channel\n\n\t\t\tif cne.err != nil {\n\t\t\t\tlogger.With().Debug(\"can't establish connection with sampled peer\",\n\t\t\t\t\tlog.FieldNamed(\"peer_id\", cne.n.PublicKey()),\n\t\t\t\t\tlog.Err(cne.err))\n\t\t\t\tbad++\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tpk := cne.n.PublicKey()\n\n\t\t\ts.inpeersMutex.Lock()\n\t\t\t_, ok := s.inpeers[pk]\n\t\t\ts.inpeersMutex.Unlock()\n\t\t\tif ok {\n\t\t\t\tlogger.With().Debug(\"not allowing peers from inbound to upgrade to outbound to prevent poisoning\",\n\t\t\t\t\tlog.FieldNamed(\"peer_id\", cne.n.PublicKey()))\n\t\t\t\tbad++\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\ts.outpeersMutex.Lock()\n\t\t\tif _, ok := s.outpeers[pk]; ok {\n\t\t\t\ts.outpeersMutex.Unlock()\n\t\t\t\tlogger.With().Debug(\"selected an already outbound peer, not counting peer\",\n\t\t\t\t\tlog.FieldNamed(\"peer_id\", cne.n.PublicKey()))\n\t\t\t\tbad++\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ts.outpeers[pk] = struct{}{}\n\t\t\ts.outpeersMutex.Unlock()\n\n\t\t\ts.discover.Good(cne.n.PublicKey())\n\t\t\ts.publishNewPeer(cne.n.PublicKey())\n\t\t\tmetrics.OutboundPeers.Add(1)\n\t\t\tlogger.With().Debug(\"added peer to peer list\",\n\t\t\t\tlog.FieldNamed(\"peer_id\", cne.n.PublicKey()))\n\t\tcase <-tm.C:\n\t\t\tbreak loop\n\t\tcase <-s.shutdownCtx.Done():\n\t\t\tbreak loop\n\t\t}\n\n\t\tif total == ndsLen {\n\t\t\tbreak loop\n\t\t}\n\t}\n\n\treturn total - bad\n}",
"func (o *MacpoolPoolMemberAllOf) HasPeer() bool {\n\tif o != nil && o.Peer != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (o *IppoolPoolMember) HasPeer() bool {\n\tif o != nil && o.Peer != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (this *Client) connectToPeer(msg *Message, conn net.Conn) error {\n\tthis.connections[msg.Author] = conn\n\tresponse := CreateMessage(MESSAGE_CONNECT, \"\", this.nick)\n\tresponse.SendTo(conn)\n\treturn nil\n}",
"func (sm *SyncManager) handleNewPeerMsg(peer *peer.Peer) {\n\t// Ignore if in the process of shutting down.\n\tif atomic.LoadInt32(&sm.shutdown) != 0 {\n\t\treturn\n\t}\n\n\tlog.Infof(\"New valid peer %s\", peer)\n\n\t// Initialize the peer state\n\tisSyncCandidate := sm.isSyncCandidate(peer)\n\tsm.peerStates[peer] = &peerSyncState{\n\t\tsyncCandidate: isSyncCandidate,\n\t\trequestedTxns: make(map[common.Uint256]struct{}),\n\t\trequestedBlocks: make(map[common.Uint256]struct{}),\n\t\tfpRate: fprate.NewFpRate(),\n\t}\n\n\tif isSyncCandidate {\n\t\t// Update bloom filter for the candidate peer.\n\t\tsm.pushBloomFilter(peer)\n\n\t\t// Start syncing by choosing the best candidate if needed.\n\t\tif sm.syncPeer == nil {\n\t\t\tsm.startSync()\n\t\t}\n\t}\n}",
"func MakePeer(addr, name string, public string) *Peer {\n var key big.Int\n m := maddr // TODO: Set a proper message here\n pub, success := key.SetString(public, 10)\n conn, or := net.Dial(\"tcp\", addr)\n\n if !e.Rr(or, false) && success {\n handshake(conn, pub, m)\n fmt.Println(\"Successfully connected to peer: \" + conn.RemoteAddr().String())\n return &Peer{conn, name, \"authsent\", addr, pub, m, \"\"}\n }\n\n return &Peer{conn, name, \"offline\", addr, pub, m, \"\"}\n}",
"func (sm *SyncManager) NewPeer(peer *peer.Peer) {\n\t// Ignore if we are shutting down.\n\tif atomic.LoadInt32(&sm.shutdown) != 0 {\n\t\treturn\n\t}\n\tsm.msgChan <- &newPeerMsg{peer: peer}\n}",
"func (sm *SyncManager) NewPeer(peer *peer.Peer) {\n\t// Ignore if we are shutting down.\n\tif atomic.LoadInt32(&sm.shutdown) != 0 {\n\t\treturn\n\t}\n\n\tsm.msgChan <- &newPeerMsg{peer: peer}\n}",
"func (pexR *PEXReactor) ensurePeers() {\n\tnumOutPeers, _, numDialing := pexR.Switch.NumPeers()\n\tnumToDial := minNumOutboundPeers - (numOutPeers + numDialing)\n\tlog.Info(\"Ensure peers\", \"numOutPeers\", numOutPeers, \"numDialing\", numDialing, \"numToDial\", numToDial)\n\tif numToDial <= 0 {\n\t\treturn\n\t}\n\ttoDial := NewCMap()\n\n\t// Try to pick numToDial addresses to dial.\n\t// TODO: improve logic.\n\tfor i := 0; i < numToDial; i++ {\n\t\tnewBias := MinInt(numOutPeers, 8)*10 + 10\n\t\tvar picked *NetAddress\n\t\t// Try to fetch a new peer 3 times.\n\t\t// This caps the maximum number of tries to 3 * numToDial.\n\t\tfor j := 0; j < 3; j++ {\n\t\t\ttry := pexR.book.PickAddress(newBias)\n\t\t\tif try == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\talreadySelected := toDial.Has(try.IP.String())\n\t\t\talreadyDialing := pexR.Switch.IsDialing(try)\n\t\t\talreadyConnected := pexR.Switch.Peers().Has(try.IP.String())\n\t\t\tif alreadySelected || alreadyDialing || alreadyConnected {\n\t\t\t\t/*\n\t\t\t\t\tlog.Info(\"Cannot dial address\", \"addr\", try,\n\t\t\t\t\t\t\"alreadySelected\", alreadySelected,\n\t\t\t\t\t\t\"alreadyDialing\", alreadyDialing,\n\t\t\t\t\t\t\"alreadyConnected\", alreadyConnected)\n\t\t\t\t*/\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tlog.Info(\"Will dial address\", \"addr\", try)\n\t\t\t\tpicked = try\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif picked == nil {\n\t\t\tcontinue\n\t\t}\n\t\ttoDial.Set(picked.IP.String(), picked)\n\t}\n\n\t// Dial picked addresses\n\tfor _, item := range toDial.Values() {\n\t\tgo func(picked *NetAddress) {\n\t\t\t_, err := pexR.Switch.DialPeerWithAddress(picked)\n\t\t\tif err != nil {\n\t\t\t\tpexR.book.MarkAttempt(picked)\n\t\t\t}\n\t\t}(item.(*NetAddress))\n\t}\n\n\t// If we need more addresses, pick a random peer and ask for more.\n\tif pexR.book.NeedMoreAddrs() {\n\t\tif peers := pexR.Switch.Peers().List(); len(peers) > 0 {\n\t\t\ti := rand.Int() % len(peers)\n\t\t\tpeer := peers[i]\n\t\t\tlog.Info(\"No addresses to dial. Sending pexRequest to random peer\", \"peer\", peer)\n\t\t\tpexR.RequestPEX(peer)\n\t\t}\n\t}\n}",
"func (state *State) AddPeer(address string) bool {\n\tstate.lock_peers.Lock()\n\tdefer state.lock_peers.Unlock()\n\tif _, ok := state.known_peers[address]; ok || address == \"\" {\n\t\treturn false\n\t} else {\n\t\tpeer, err := NewPeer(address)\n\t\tif err == nil {\n\t\t\tstate.known_peers[address] = peer\n\t\t\tstate.list_peers = append(state.list_peers, address)\n\t\t\tfor _, c := range state.addPeerChannels {\n\t\t\t\tc <- address\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n}",
"func (o *MacpoolPoolMemberAllOf) GetPeer() MacpoolLeaseRelationship {\n\tif o == nil || o.Peer == nil {\n\t\tvar ret MacpoolLeaseRelationship\n\t\treturn ret\n\t}\n\treturn *o.Peer\n}",
"func (s *Server) run() {\n\tgo s.runProto()\n\tfor {\n\t\tif s.PeerCount() < s.MinPeers {\n\t\t\ts.discovery.RequestRemote(s.AttemptConnPeers)\n\t\t}\n\t\tif s.discovery.PoolCount() < minPoolCount {\n\t\t\ts.broadcastHPMessage(NewMessage(CMDGetAddr, payload.NewNullPayload()))\n\t\t}\n\t\tselect {\n\t\tcase <-s.quit:\n\t\t\treturn\n\t\tcase p := <-s.register:\n\t\t\ts.lock.Lock()\n\t\t\ts.peers[p] = true\n\t\t\ts.lock.Unlock()\n\t\t\tpeerCount := s.PeerCount()\n\t\t\ts.log.Info(\"new peer connected\", zap.Stringer(\"addr\", p.RemoteAddr()), zap.Int(\"peerCount\", peerCount))\n\t\t\tif peerCount > s.MaxPeers {\n\t\t\t\ts.lock.RLock()\n\t\t\t\t// Pick a random peer and drop connection to it.\n\t\t\t\tfor peer := range s.peers {\n\t\t\t\t\t// It will send us unregister signal.\n\t\t\t\t\tgo peer.Disconnect(errMaxPeers)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ts.lock.RUnlock()\n\t\t\t}\n\t\t\tupdatePeersConnectedMetric(s.PeerCount())\n\n\t\tcase drop := <-s.unregister:\n\t\t\ts.lock.Lock()\n\t\t\tif s.peers[drop.peer] {\n\t\t\t\tdelete(s.peers, drop.peer)\n\t\t\t\ts.lock.Unlock()\n\t\t\t\ts.log.Warn(\"peer disconnected\",\n\t\t\t\t\tzap.Stringer(\"addr\", drop.peer.RemoteAddr()),\n\t\t\t\t\tzap.Error(drop.reason),\n\t\t\t\t\tzap.Int(\"peerCount\", s.PeerCount()))\n\t\t\t\taddr := drop.peer.PeerAddr().String()\n\t\t\t\tif drop.reason == errIdenticalID {\n\t\t\t\t\ts.discovery.RegisterBadAddr(addr)\n\t\t\t\t} else if drop.reason == errAlreadyConnected {\n\t\t\t\t\t// There is a race condition when peer can be disconnected twice for the this reason\n\t\t\t\t\t// which can lead to no connections to peer at all. Here we check for such a possibility.\n\t\t\t\t\tstillConnected := false\n\t\t\t\t\ts.lock.RLock()\n\t\t\t\t\tverDrop := drop.peer.Version()\n\t\t\t\t\taddr := drop.peer.PeerAddr().String()\n\t\t\t\t\tif verDrop != nil {\n\t\t\t\t\t\tfor peer := range s.peers {\n\t\t\t\t\t\t\tver := peer.Version()\n\t\t\t\t\t\t\t// Already connected, drop this connection.\n\t\t\t\t\t\t\tif ver != nil && ver.Nonce == verDrop.Nonce && peer.PeerAddr().String() == addr {\n\t\t\t\t\t\t\t\tstillConnected = true\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ts.lock.RUnlock()\n\t\t\t\t\tif !stillConnected {\n\t\t\t\t\t\ts.discovery.UnregisterConnectedAddr(addr)\n\t\t\t\t\t\ts.discovery.BackFill(addr)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\ts.discovery.UnregisterConnectedAddr(addr)\n\t\t\t\t\ts.discovery.BackFill(addr)\n\t\t\t\t}\n\t\t\t\tupdatePeersConnectedMetric(s.PeerCount())\n\t\t\t} else {\n\t\t\t\t// else the peer is already gone, which can happen\n\t\t\t\t// because we have two goroutines sending signals here\n\t\t\t\ts.lock.Unlock()\n\t\t\t}\n\t\t}\n\t}\n}",
"func newPeer(c PeerConfig, server *bgpServer) (*peer, error) {\n\tp := &peer{\n\t\tserver: server,\n\t\tconfig: &c,\n\t\taddr: c.PeerAddress,\n\t\tlocalAddr: c.LocalAddress,\n\t\tttl: c.TTL,\n\t\tpassive: c.Passive,\n\t\tpeerASN: c.PeerAS,\n\t\tlocalASN: c.LocalAS,\n\t\tfsms: make([]*FSM, 0),\n\t\treconnectInterval: c.ReconnectInterval,\n\t\tkeepaliveTime: c.KeepAlive,\n\t\tholdTime: c.HoldTime,\n\t\toptOpenParams: make([]packet.OptParam, 0),\n\t\trouteServerClient: c.RouteServerClient,\n\t\trouteReflectorClient: c.RouteReflectorClient,\n\t\tclusterID: c.RouteReflectorClusterID,\n\t\tpeerRoleEnabled: peerRoleEnabled(c.PeerRole),\n\t\tpeerRoleStrictMode: c.PeerRoleStrictMode,\n\t\tpeerRoleLocal: translatePeerRole(c.PeerRole),\n\t\tvrf: c.VRF,\n\t\tadjRIBInFactory: adjRIBInFactory{},\n\t}\n\n\tif c.IPv4 != nil {\n\t\tp.ipv4 = &peerAddressFamily{\n\t\t\trib: c.VRF.IPv4UnicastRIB(),\n\t\t\timportFilterChain: filterOrDefault(c.IPv4.ImportFilterChain),\n\t\t\texportFilterChain: filterOrDefault(c.IPv4.ExportFilterChain),\n\t\t\taddPathReceive: c.IPv4.AddPathRecv,\n\t\t\taddPathSend: c.IPv4.AddPathSend,\n\t\t}\n\n\t\tif p.ipv4.rib == nil {\n\t\t\treturn nil, fmt.Errorf(\"no RIB for IPv4 unicast configured\")\n\t\t}\n\t}\n\n\t// If we are a route reflector and no ClusterID was set, use our RouterID\n\tif p.routeReflectorClient && p.clusterID == 0 {\n\t\tp.clusterID = c.RouterID\n\t}\n\n\tcaps := make(packet.Capabilities, 0)\n\n\tcaps = append(caps, addPathCapabilities(c)...)\n\n\tcaps = append(caps, asn4Capability(c))\n\n\tif c.IPv4 != nil && c.AdvertiseIPv4MultiProtocol {\n\t\tcaps = append(caps, multiProtocolCapability(packet.AFIIPv4))\n\t\tp.ipv4MultiProtocolAdvertised = true\n\t}\n\n\tif c.IPv6 != nil {\n\t\tp.ipv6 = &peerAddressFamily{\n\t\t\trib: c.VRF.IPv6UnicastRIB(),\n\t\t\timportFilterChain: filterOrDefault(c.IPv6.ImportFilterChain),\n\t\t\texportFilterChain: filterOrDefault(c.IPv6.ExportFilterChain),\n\t\t\taddPathReceive: c.IPv6.AddPathRecv,\n\t\t\taddPathSend: c.IPv6.AddPathSend,\n\t\t}\n\t\tcaps = append(caps, multiProtocolCapability(packet.AFIIPv6))\n\n\t\tif p.ipv6.rib == nil {\n\t\t\treturn nil, fmt.Errorf(\"no RIB for IPv6 unicast configured\")\n\t\t}\n\t}\n\n\t// Activate Peer Role capability for eBGP neighbors if configured\n\tif p.localASN != p.peerASN && peerRoleEnabled(c.PeerRole) {\n\t\tcaps = append(caps, peerRoleCapability(c))\n\t}\n\n\tp.optOpenParams = append(p.optOpenParams, packet.OptParam{\n\t\tType: packet.CapabilitiesParamType,\n\t\tValue: caps,\n\t})\n\n\tif !p.passive {\n\t\tp.fsms = append(p.fsms, NewActiveFSM(p))\n\t}\n\n\treturn p, nil\n}",
"func (s *server) outboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {\n\ts.peersMtx.Lock()\n\tdefer s.peersMtx.Unlock()\n\n\tlocalPub := s.identityPriv.PubKey()\n\tnodePub := conn.(*brontide.Conn).RemotePub()\n\tpubStr := string(nodePub.SerializeCompressed())\n\n\t// If we already have an outbound connection to this peer, then ignore\n\t// this new connection.\n\tif _, ok := s.outboundPeers[pubStr]; ok {\n\t\tsrvrLog.Debugf(\"Ignoring duplicate outbound connection\")\n\t\tconn.Close()\n\t\treturn\n\t}\n\n\tif _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {\n\t\tsrvrLog.Debugf(\"Ignoring cancelled outbound connection\")\n\t\tconn.Close()\n\t\treturn\n\t}\n\n\tsrvrLog.Infof(\"Established connection to: %v\", conn.RemoteAddr())\n\n\t// As we've just established an outbound connection to this peer, we'll\n\t// cancel all other persistent connection requests and eliminate the\n\t// entry for this peer from the map.\n\ts.pendingConnMtx.Lock()\n\tif connReqs, ok := s.persistentConnReqs[pubStr]; ok {\n\t\tfor _, pConnReq := range connReqs {\n\t\t\tif pConnReq.ID() != connReq.ID() {\n\t\t\t\ts.connMgr.Remove(pConnReq.ID())\n\t\t\t}\n\t\t}\n\t\tdelete(s.persistentConnReqs, pubStr)\n\t}\n\ts.pendingConnMtx.Unlock()\n\n\t// If we already have an inbound connection from this peer, then we'll\n\t// check to see _which_ of our connections should be dropped.\n\tif connectedPeer, ok := s.peersByPub[pubStr]; ok {\n\t\t// If our (this) connection should be dropped, then we'll do\n\t\t// so, in order to ensure we don't have any duplicate\n\t\t// connections.\n\t\tif shouldDropLocalConnection(localPub, nodePub) {\n\t\t\tsrvrLog.Warnf(\"Established outbound connection to \"+\n\t\t\t\t\"peer %x, but already connected, dropping conn\",\n\t\t\t\tnodePub.SerializeCompressed())\n\t\t\ts.connMgr.Remove(connReq.ID())\n\t\t\tconn.Close()\n\t\t\treturn\n\t\t}\n\n\t\t// Otherwise, _their_ connection should be dropped. So we'll\n\t\t// disconnect the peer and send the now obsolete peer to the\n\t\t// server for garbage collection.\n\t\tsrvrLog.Debugf(\"Disconnecting stale connection to %v\",\n\t\t\tconnectedPeer)\n\t\tconnectedPeer.Disconnect()\n\t\ts.donePeers <- connectedPeer\n\t}\n\n\tgo s.peerConnected(conn, connReq, true)\n}",
"func newPeer(host topology.Host, dialer client.PeerConnDialer) *peer {\n\treturn &peer{\n\t\thost: host,\n\t\tdialer: dialer,\n\t}\n}",
"func newPeer(server *server, name string, connectionString string, heartbeatInterval time.Duration) *Peer {\n\treturn &Peer{\n\t\tserver: server,\n\t\tName: name,\n\t\tConnectionString: connectionString,\n\t\theartbeatInterval: heartbeatInterval,\n\t}\n}",
"func (m *Model) AddNetworkPeer(address string) bool {\n\tm.pMutex.Lock()\n\tdefer m.pMutex.Unlock()\n\n\tvalue, ok := m.peersList[address]\n\tm.peersList[address] = ok && value\n\treturn !ok\n}",
"func (s *Switch) publishNewPeer(peer p2pcrypto.PublicKey) {\n\ts.peerLock.RLock()\n\tfor _, p := range s.newPeerSub {\n\t\tselect {\n\t\tcase p <- peer:\n\t\tcase <-s.shutdownCtx.Done():\n\t\t}\n\t}\n\ts.peerLock.RUnlock()\n}",
"func (pr *PlumtreeRouter) AddPeer(pid peer.ID, ptoid protocol.ID) {\n\tpr.log.Debugf(\"PEERUP: Add new peer %s using %s\", pid, ptoid)\n\tpr.peers[pid] = ptoid\n}",
"func newConn(ctx context.Context, t *Transport, remoteMa ma.Multiaddr,\n\tremotePID peer.ID, inbound bool) (tpt.CapableConn, error) {\n\t// Creates a manet.Conn\n\tpr, pw := io.Pipe()\n\tconnCtx, cancel := context.WithCancel(gListener.ctx)\n\n\tmaconn := &Conn{\n\t\treadIn: pw,\n\t\treadOut: pr,\n\t\tlocalMa: gListener.localMa,\n\t\tremoteMa: remoteMa,\n\t\tctx: connCtx,\n\t\tcancel: cancel,\n\t}\n\n\t// Unlock gListener locked from discovery.go (HandlePeerFound)\n\tgListener.inUse.Done()\n\n\t// Stores the conn in connMap, will be deleted during conn.Close()\n\tconnMap.Store(maconn.RemoteAddr().String(), maconn)\n\n\t// Returns an upgraded CapableConn (muxed, addr filtered, secured, etc...)\n\tif inbound {\n\t\treturn t.upgrader.UpgradeInbound(ctx, t, maconn)\n\t}\n\treturn t.upgrader.UpgradeOutbound(ctx, t, maconn, remotePID)\n}",
"func (ids *eventpoolIDs) nextPeerID() uint16 {\n\tif len(ids.activeIDs) == maxActiveIDs {\n\t\tpanic(fmt.Sprintf(\"node has maximum %d active IDs and wanted to get one more\", maxActiveIDs))\n\t}\n\n\t_, idExists := ids.activeIDs[ids.nextID]\n\tfor idExists {\n\t\tids.nextID++\n\t\t_, idExists = ids.activeIDs[ids.nextID]\n\t}\n\tcurID := ids.nextID\n\tids.nextID++\n\treturn curID\n}",
"func NewPeer(conn net.Conn, name string) *Peer {\n\n\treturn &Peer{\n\t\tconn: conn, Name: name, closed: false,\n\t}\n}",
"func work(addr net.TCPAddr) {\n\t_, ok := peerConnected.LoadOrStore(addr.IP.String(), time.Now().Unix)\n\tif ok {\n\t\treturn\n\t}\n\tdefer func() {\n\t\tpeerConnected.Delete(addr.IP.String())\n\t}()\n\n\tconn, err := net.DialTCP(\"tcp\", nil, &addr)\n\tif err != nil {\n\t\t//msg := err.Error()\n\t\t//\"operation timed out\"\n\t\t//\"connection refused\"\n\t\t//\"no route to host\"\n\t\t//\"network is unreachable\"\n\t\t//\"can't assign requested address\"\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tstorage.P2PConnected(addr)\n\n\tlog.Logger.Info(\"p2p connected\", zap.String(\"ip\", addr.IP.String()))\n\n\tmsg := message.NewMainnetMessage(message.MsgTypeHand)\n\thand := message.Hand{\n\t\tVersion: 3,\n\t\tCapabilities: 15,\n\t\tNonce: uint64(time.Now().Unix()),\n\t\tTotalDifficulty: 0,\n\t\tUserAgent: \"\",\n\t\tGenesis: \"40adad0aec27797b48840aa9e00472015c21baea118ce7a2ff1a82c0f8f5bf82\",\n\t}\n\tmsg.Payload = hand.Payload()\n\n\t_, err = conn.Write(msg.Bytes())\n\tif err != nil {\n\t\tlog.Logger.Error(\"p2p write hand message\", zap.String(\"ip\", addr.IP.String()), zap.Error(err))\n\t\treturn\n\t}\n\n\ttPing := time.NewTicker(time.Second * 30)\n\tdefer tPing.Stop()\n\n\ttPeer := time.NewTicker(time.Minute * 10)\n\tdefer tPeer.Stop()\n\n\tfor {\n\t\ttime.Sleep(time.Second * 10)\n\t\tselect {\n\t\tcase _ = <-tPing.C:\n\t\t\tping := message.Ping{\n\t\t\t\tTotalDifficulty: 0,\n\t\t\t\tHeight: 0,\n\t\t\t}\n\t\t\tm := message.NewMainnetMessage(message.MsgTypePing)\n\t\t\tm.Payload = ping.Playload()\n\n\t\t\t_, err = conn.Write(m.Bytes())\n\t\t\tif err != nil {\n\t\t\t\tlog.Logger.Error(\"p2p write ping message\", zap.String(\"ip\", addr.IP.String()), zap.Error(err))\n\t\t\t\treturn\n\t\t\t}\n\t\tcase _ = <-tPeer.C:\n\t\t\tmask := [3]uint32{0x01, 0x02, 0x04}\n\t\t\tr := rand.New(rand.NewSource(time.Now().Unix()))\n\t\t\tget := message.GetPeerAddrs{\n\t\t\t\tCapabilities: mask[r.Intn(len(mask))],\n\t\t\t}\n\t\t\tmsg := message.NewMainnetMessage(message.MsgTypeGetPeerAddrs)\n\t\t\tmsg.Payload = get.Playload()\n\n\t\t\t_, err := conn.Write(msg.Bytes())\n\t\t\tif err != nil {\n\t\t\t\tlog.Logger.Error(\"p2p write getPeerAddrs message\", zap.String(\"ip\", addr.IP.String()), zap.Error(err))\n\t\t\t\treturn\n\t\t\t}\n\t\tdefault:\n\t\t\tvar magic1 uint8\n\t\t\tvar magic2 uint8\n\t\t\terr := binary.Read(conn, binary.BigEndian, &magic1)\n\t\t\tif err != nil {\n\t\t\t\tlog.Logger.Error(\"p2p read magic1\", zap.String(\"ip\", addr.IP.String()), zap.Error(err))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif magic1 != 97 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr = binary.Read(conn, binary.BigEndian, &magic2)\n\t\t\tif err != nil {\n\t\t\t\tlog.Logger.Error(\"p2p read magic2\", zap.String(\"ip\", addr.IP.String()), zap.Error(err))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif magic2 != 61 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar msg uint8\n\t\t\terr = binary.Read(conn, binary.BigEndian, &msg)\n\t\t\tif err != nil {\n\t\t\t\tlog.Logger.Error(\"p2p read msgType\", zap.String(\"ip\", addr.IP.String()), zap.Error(err))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar length uint64\n\t\t\terr = binary.Read(conn, binary.BigEndian, &length)\n\t\t\tif err != nil {\n\t\t\t\tlog.Logger.Error(\"p2p read length\", zap.String(\"ip\", addr.IP.String()), zap.Error(err))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tb := make([]byte, length, length)\n\t\t\terr = binary.Read(conn, binary.BigEndian, &b)\n\t\t\tif err != nil {\n\t\t\t\tlog.Logger.Error(\"p2p read palyload\", zap.String(\"ip\", addr.IP.String()), zap.Error(err))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tstorage.P2PConnecting(addr)\n\n\t\t\tif msg == 2 {\n\t\t\t\tshake, err := message.NewShake(b)\n\t\t\t\t// fmt.Printf(\"%#v\\n\", shake)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Logger.Error(\"p2p decode shake\", zap.String(\"ip\", addr.IP.String()), zap.Error(err))\n\t\t\t\t} else {\n\t\t\t\t\tlog.Logger.Debug(\"p2p receive shake\", zap.String(\"ip\", addr.IP.String()))\n\t\t\t\t\tstorage.ReceiveShake(addr, shake)\n\t\t\t\t}\n\t\t\t} else if msg == 4 {\n\t\t\t\tpong, err := message.NewPong(b)\n\t\t\t\t// fmt.Printf(\"%#v\\n\", pong)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Logger.Error(\"p2p decode pong\", zap.String(\"ip\", addr.IP.String()), zap.Error(err))\n\t\t\t\t} else {\n\t\t\t\t\tlog.Logger.Debug(\"p2p receive pong\", zap.String(\"ip\", addr.IP.String()))\n\t\t\t\t\tstorage.ReceivePong(addr, pong)\n\t\t\t\t}\n\t\t\t} else if msg == 6 {\n\t\t\t\tpeers, err := message.NewPeers(b)\n\t\t\t\t// fmt.Printf(\"%#v\\n\", p)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Logger.Error(\"p2p decode peers\", zap.String(\"ip\", addr.IP.String()), zap.Error(err))\n\t\t\t\t} else {\n\t\t\t\t\tlog.Logger.Debug(\"p2p receive peers\", zap.String(\"ip\", addr.IP.String()))\n\n\t\t\t\t\tfor _, p := range peers {\n\t\t\t\t\t\tif storage.IsPublicIP(p.IP) && p.Port > 0 {\n\t\t\t\t\t\t\tn := node{addr: p, lastSeen: time.Now().Unix()}\n\t\t\t\t\t\t\tpeerAll.Store(fmt.Sprintf(\"%s:%d\", p.IP, p.Port), n)\n\t\t\t\t\t\t\tstorage.AddPeer(p)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if msg == 8 {\n\t\t\t\theader, err := message.NewHeader(b)\n\t\t\t\t// fmt.Printf(\"%#v\\n\", header)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Logger.Error(\"p2p decode header\", zap.String(\"ip\", addr.IP.String()), zap.Error(err))\n\t\t\t\t} else {\n\t\t\t\t\tlog.Logger.Debug(\"p2p receive header\", zap.String(\"ip\", addr.IP.String()))\n\t\t\t\t\tstorage.ReceiveHeader(addr, header)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"func (c *Core) AddPeer(addr network.Address) error {\n\treturn c.server.AddPeer(addr)\n}",
"func (y *YggdrasilAdminAPI) AddPeer(uri string) ([]string, error) {\n\treq := fmt.Sprintf(`{\"keepalive\":true, \"request\":\"addpeer\", \"uri\":\"%s\"}`, uri)\n\tresp, err := y.execReq(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(string(resp.Response))\n\tadded := struct {\n\t\tAdded []string `json:\"added\"`\n\t}{}\n\tif err := json.Unmarshal(resp.Response, &added); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn added.Added, nil\n}",
"func (s *Service) RunPeer(orgName string, peer []config.Peers, projectPath string, i int,\n\terrChanPeer chan error, wgPeerDone chan bool) {\n\tctx := context.TODO()\n\tcfg, hostConfig := configPeer(peer, projectPath, orgName, i)\n\n\tresp, err := s.MyClient.ContainerCreate(ctx, cfg, hostConfig, nil,\n\t\tpeer[i].Name)\n\tif err != nil {\n\t\terrChanPeer <- errors.Wrap(err, \"ContainerCreate failed with error\")\n\t\treturn\n\t}\n\n\tlog.Println(\"ContainerCreate for peer response: \", resp)\n\n\terr = s.MyClient.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{})\n\tif err != nil {\n\t\terrChanPeer <- errors.Wrap(err, \"ContainerStart failed with error\")\n\t\treturn\n\t}\n\n\tlog.Println(\"ContainerStart for peer succeed.\")\n\n\twgPeerDone <- true\n}",
"func (o *MacpoolPoolMemberAllOf) GetPeerOk() (*MacpoolLeaseRelationship, bool) {\n\tif o == nil || o.Peer == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Peer, true\n}",
"func (t *Transfer) peerManager() {\n\tt.log.Debug(\"Started peerManager\")\n\tfor {\n\t\tselect {\n\t\tcase <-t.stopC:\n\t\t\treturn\n\t\tcase peers := <-t.peersC:\n\t\t\tfor _, p := range peers {\n\t\t\t\tt.log.Debugln(\"Peer:\", p)\n\t\t\t\t// TODO send all peers to connecter for now\n\t\t\t\tgo func(addr *net.TCPAddr) {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase t.peerC <- addr:\n\t\t\t\t\tcase <-t.stopC:\n\t\t\t\t\t}\n\t\t\t\t}(p)\n\t\t\t}\n\t\t}\n\t}\n}",
"func (c *connection) Connect(ip string, port int) (int, error) {\n\tvar err error\n\tvar tempConn net.Conn\n\ttempConn, err = net.DialTimeout(\"tcp\", fmt.Sprint(ip, \":\", port), time.Second*5)\n\tfor err != nil {\n\t\ttempConn, err = net.DialTimeout(\"tcp\", fmt.Sprint(ip, \":\", port), time.Second*5)\n\t}\n\tconn := tempConn.(*net.TCPConn)\n\tif err != nil {\n\t\tpanic(\"Couldnt dial the host: \" + err.Error())\n\t}\n\n\twrite(conn, []byte{0, 0, byte(c.myPort / 256), byte(c.myPort % 256)})\n\t//conn.SetReadDeadline(time.Now().Add(time.Second*5))\n\n\tmsg := read(conn)\n\tc.myId = int(msg[0])\n\tc.addPeer(c.myId, nil, 0)\n\totherId := int(msg[1])\n\tc.peers = make([]*peer, c.myId+1)\n\tc.addPeer(otherId, conn, port)\n\tj := 2\n\tfor j < len(msg) {\n\t\tid := int(msg[j])\n\t\tj++\n\t\tip, port, k := addrFromBytes(msg[j:])\n\t\tnewConn, err := net.Dial(\"tcp\", fmt.Sprint(ip, \":\", port))\n\t\tif err != nil {\n\t\t\tpanic(\"Got error when connecting to addr \" + fmt.Sprint(ip, \":\", port) + \": \" + err.Error())\n\t\t}\n\t\twrite(newConn, []byte{0, byte(c.myId), byte(c.myPort / 256), byte(c.myPort % 256)})\n\t\tc.addPeer(id, newConn.(*net.TCPConn), port)\n\t\tgo c.receive(c.peers[id])\n\t\tj += k\n\t}\n\tgo c.receive(c.peers[otherId])\n\treturn c.myId, nil\n}",
"func (sp *StreamPool) streamForPeer(p peer.ID) (*Stream, error) {\n\tif v, ok := sp.streams.Get(p.Pretty()); ok {\n\t\ts, _ := v.(*Stream)\n\t\tif s.valid() {\n\t\t\tif sp.no.srv.config.IsAuthentication && !s.auth() {\n\t\t\t\tsp.log.Warn(\"stream failed to be authenticated\")\n\t\t\t\treturn nil, ErrAuth\n\t\t\t}\n\t\t\treturn s, nil\n\t\t}\n\t}\n\n\ts, err := sp.no.host.NewStream(sp.no.ctx, p, AmperProtocolID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstr := sp.Add(s)\n\tif str == nil {\n\t\treturn nil, ErrAddStream\n\t}\n\treturn str, nil\n}",
"func (sm *SyncManager) handleNewPeerMsg(peer *peer.Peer) {\n\t// Ignore if in the process of shutting down.\n\tif atomic.LoadInt32(&sm.shutdown) != 0 {\n\t\treturn\n\t}\n\n\tlog.Infof(\"New valid peer %s\", peer)\n\n\t// Initialize the peer state\n\tisSyncCandidate := sm.isSyncCandidate(peer)\n\tsm.peerStates[peer] = &peerSyncState{\n\t\tsyncCandidate: isSyncCandidate,\n\t\trequestedTxns: make(map[common.Uint256]struct{}),\n\t\trequestedBlocks: make(map[common.Uint256]struct{}),\n\t\trequestedConfirmedBlocks: make(map[common.Uint256]struct{}),\n\t}\n\n\t// Start syncing by choosing the best candidate if needed.\n\tif isSyncCandidate && sm.syncPeer == nil {\n\t\tsm.startSync()\n\t}\n}",
"func (p *Peer) ConnectPeer(port string, id int) {\n\trequest := ConnectRequest{}\n\treply := ConnectReply{}\n\trequest.PeerID = p.PeerID\n\trequest.Port = p.Port\n\tcall(\"Peer.AcceptConnect\", &request, &reply, port)\n\tif reply.Accepted == false {\n\t\tfmt.Printf(\"Peer %v: Connection refused from Peer %v\\n\", p.PeerID, id)\n\t\treturn\n\t}\n\tp.peers[p.numPeers] = id\n\tp.numPeers = p.numPeers + 1\n\tfmt.Printf(\"Peer %v: Connected to Peer %v\\n\", p.PeerID, id)\n}",
"func newPair() (pcOffer *PeerConnection, pcAnswer *PeerConnection, err error) {\n\tpca, err := NewPeerConnection(Configuration{})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpcb, err := NewPeerConnection(Configuration{})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn pca, pcb, nil\n}",
"func AddOrUpdatePeer(p *Peer) error {\n\tjson, err := json.Marshal(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tidStr := p.ID.String()\n\n\tif err := context.Store.Put(peerPrefix+idStr, json, nil); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func (sp *StreamPool) Get(ctx xctx.XContext, peerId peer.ID) (*Stream, error) {\n\tif v, ok := sp.streams.Get(peerId.Pretty()); ok {\n\t\tif stream, ok := v.(*Stream); ok {\n\t\t\tif stream.Valid() {\n\t\t\t\treturn stream, nil\n\t\t\t} else {\n\t\t\t\tsp.DelStream(stream)\n\t\t\t\tctx.GetLog().Warn(\"stream not valid, create new stream\", \"peerId\", peerId)\n\t\t\t}\n\t\t}\n\t}\n\n\tsp.mutex.Lock()\n\tdefer sp.mutex.Unlock()\n\tif v, ok := sp.streams.Get(peerId.Pretty()); ok {\n\t\tif stream, ok := v.(*Stream); ok {\n\t\t\tif stream.Valid() {\n\t\t\t\treturn stream, nil\n\t\t\t} else {\n\t\t\t\tsp.DelStream(stream)\n\t\t\t\tctx.GetLog().Warn(\"stream not valid, create new stream\", \"peerId\", peerId)\n\t\t\t}\n\t\t}\n\t}\n\n\tnetStream, err := sp.srv.host.NewStream(sp.ctx, peerId, protocol.ID(protocolID))\n\tif err != nil {\n\t\tctx.GetLog().Warn(\"new net stream error\", \"peerId\", peerId, \"error\", err)\n\t\treturn nil, ErrNewStream\n\t}\n\n\treturn sp.NewStream(ctx, netStream)\n}",
"func (ps *PeerStore) Add(p *Peer) {\n\tps.lock.Lock()\n\tdefer ps.lock.Unlock()\n\tps.peers[p.ListenAddr] = p\n}",
"func (r *localRaft) addPeer(addr string) error {\n\tpeers, err := r.peerStore.Peers()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(peers) >= 3 {\n\t\treturn nil\n\t}\n\n\tif fut := r.raft.AddPeer(addr); fut.Error() != nil {\n\t\treturn fut.Error()\n\t}\n\treturn nil\n}",
"func (a *Agent) UpdatePeers(ctx context.Context, p pool.Pool) error {\n\tpeers, err := a.EthNode.Peers(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tblockNumber, err := a.EthNode.BlockNumber(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tupdate, err := p.Update(ctx, pool.UpdateRequest{\n\t\tPeerInfo: peers,\n\t\tBlockNumber: blockNumber,\n\t})\n\tif err != nil {\n\t\treturn AgentPoolError{err, \"Failed during pool update request\"}\n\t}\n\tvar balance store.Balance\n\tif a.BalanceCallback != nil && update.Balance != nil {\n\t\tbalance = *update.Balance\n\t\ta.BalanceCallback(balance)\n\t}\n\n\tlogger.Printf(\"Pool update: peers=%d active=%d invalid=%d block=%d balance=%s\", len(peers), len(update.ActivePeers), len(update.InvalidPeers), blockNumber, balance.String())\n\n\tif a.StrictPeers {\n\t\tlookup := make(map[string]string, len(update.ActivePeers))\n\t\tfor _, p := range update.ActivePeers {\n\t\t\turi, err := ethnode.ParseNodeURI(p)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Printf(\"Failed to parse active peer enode from pool %q: %s\", err, p)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlookup[uri.ID()] = uri.RemoteHost()\n\t\t}\n\n\t\t// Mark any non-active peers as invalid. These should be a superset of\n\t\t// the original update.InvalidPeers, so we truncate it first.\n\t\tupdate.InvalidPeers = update.InvalidPeers[:0]\n\t\tfor _, p := range peers {\n\t\t\turi, err := ethnode.ParseNodeURI(p.EnodeURI())\n\t\t\tif err != nil {\n\t\t\t\tlogger.Printf(\"Failed to parse peer enode %q: %s\", err, p.EnodeURI())\n\t\t\t} else if remoteAddr, ok := lookup[uri.ID()]; ok && uri.RemoteHost() == remoteAddr {\n\t\t\t\tcontinue // Local peer matching active peer on pool\n\t\t\t}\n\t\t\tupdate.InvalidPeers = append(update.InvalidPeers, p.EnodeURI())\n\t\t}\n\n\t\tif len(update.InvalidPeers) > 0 {\n\t\t\tlogger.Printf(\"Disconnecting from %d mismatched StrictPeers: %q\", len(update.InvalidPeers), update.InvalidPeers)\n\t\t}\n\t}\n\n\t// Disconnect from invalid peers\n\tvar errors []error\n\tfor _, p := range update.InvalidPeers {\n\t\tpeerID := p\n\t\tif uri, err := ethnode.ParseNodeURI(p); err != nil {\n\t\t\tlogger.Printf(\"Failed to parse invalid peer enode %q: %s\", err, p)\n\t\t} else {\n\t\t\tpeerID = uri.ID()\n\t\t}\n\t\tif err := a.EthNode.RemoveTrustedPeer(ctx, peerID); err != nil {\n\t\t\terrors = append(errors, err)\n\t\t}\n\t\tif err := a.EthNode.DisconnectPeer(ctx, peerID); err != nil {\n\t\t\terrors = append(errors, err)\n\t\t}\n\t}\n\n\t// Do we need more peers?\n\tif needMore := a.NumHosts - len(update.ActivePeers); needMore > 0 {\n\t\tif err := a.AddPeers(ctx, p, needMore); err == ErrNoPeers {\n\t\t\t// We can live without more peers for now, will try again next time\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif a.BlockNumberCallback != nil {\n\t\ta.BlockNumberCallback(blockNumber, update.LatestBlockNumber)\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn fmt.Errorf(\"failed to disconnect from invalid peers: %q\", errors)\n\t}\n\n\treturn nil\n}",
"func TestAcceptPeer(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\tg := newTestingGateway(t)\n\tdefer g.Close()\n\tg.mu.Lock()\n\tdefer g.mu.Unlock()\n\n\t// Add only unkickable peers.\n\tvar unkickablePeers []*peer\n\tfor i := 0; i < fullyConnectedThreshold+1; i++ {\n\t\taddr := modules.NetAddress(fmt.Sprintf(\"1.2.3.%d\", i))\n\t\tp := &peer{\n\t\t\tPeer: modules.Peer{\n\t\t\t\tNetAddress: addr,\n\t\t\t\tInbound: false,\n\t\t\t\tLocal: false,\n\t\t\t},\n\t\t\tsess: newClientStream(new(dummyConn), build.Version),\n\t\t}\n\t\tunkickablePeers = append(unkickablePeers, p)\n\t}\n\tfor i := 0; i < fullyConnectedThreshold+1; i++ {\n\t\taddr := modules.NetAddress(fmt.Sprintf(\"127.0.0.1:%d\", i))\n\t\tp := &peer{\n\t\t\tPeer: modules.Peer{\n\t\t\t\tNetAddress: addr,\n\t\t\t\tInbound: true,\n\t\t\t\tLocal: true,\n\t\t\t},\n\t\t\tsess: newClientStream(new(dummyConn), build.Version),\n\t\t}\n\t\tunkickablePeers = append(unkickablePeers, p)\n\t}\n\tfor _, p := range unkickablePeers {\n\t\tg.addPeer(p)\n\t}\n\n\t// Test that accepting another peer doesn't kick any of the peers.\n\tg.acceptPeer(&peer{\n\t\tPeer: modules.Peer{\n\t\t\tNetAddress: \"9.9.9.9\",\n\t\t\tInbound: true,\n\t\t},\n\t\tsess: newClientStream(new(dummyConn), build.Version),\n\t})\n\tfor _, p := range unkickablePeers {\n\t\tif _, exists := g.peers[p.NetAddress]; !exists {\n\t\t\tt.Error(\"accept peer kicked an outbound or local peer\")\n\t\t}\n\t}\n\n\t// Add a kickable peer.\n\tg.addPeer(&peer{\n\t\tPeer: modules.Peer{\n\t\t\tNetAddress: \"9.9.9.9\",\n\t\t\tInbound: true,\n\t\t},\n\t\tsess: newClientStream(new(dummyConn), build.Version),\n\t})\n\t// Test that accepting a local peer will kick a kickable peer.\n\tg.acceptPeer(&peer{\n\t\tPeer: modules.Peer{\n\t\t\tNetAddress: \"127.0.0.1:99\",\n\t\t\tInbound: true,\n\t\t\tLocal: true,\n\t\t},\n\t\tsess: newClientStream(new(dummyConn), build.Version),\n\t})\n\tif _, exists := g.peers[\"9.9.9.9\"]; exists {\n\t\tt.Error(\"acceptPeer didn't kick a peer to make room for a local peer\")\n\t}\n}",
"func Connect(pool ServerPool, spec db.Specifier) (db.DB, error) {\n\tpool.RLock()\n\n\tif db, ok := pool.Get(spec); ok {\n\t\t// The connection was found. Do we need to update it?\n\t\tif db.Spec().NeedsUpdate(spec) {\n\t\t\tpool.RUnlock()\n\t\t\tpool.Lock()\n\t\t\t// By now, someone else may have updated it already.\n\t\t\tif db.Spec().NeedsUpdate(spec) {\n\t\t\t\tif err := db.Update(spec); err != nil {\n\t\t\t\t\tpool.Unlock()\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tpool.Unlock()\n\t\t\tpool.RLock()\n\t\t}\n\t\tpool.RUnlock()\n\t\treturn db, nil\n\t}\n\tpool.RUnlock()\n\treturn insertNewDB(pool, spec)\n}",
"func (hpc *HashPeersCache) add(hash types.Hash32, peer p2p.Peer) {\n\tpeers, exists := hpc.get(hash)\n\tif !exists {\n\t\thpc.Cache.Add(hash, HashPeers{peer: {}})\n\t\treturn\n\t}\n\n\tpeers[peer] = struct{}{}\n\thpc.Cache.Add(hash, peers)\n}",
"func (pds *peerDistanceSorter) appendPeer(p peer.ID, pDhtId ID) {\n\tpds.peers = append(pds.peers, peerDistance{\n\t\tp: p,\n\t\tdistance: xor(pds.target, pDhtId),\n\t})\n}",
"func (o *IppoolPoolMember) GetPeerOk() (*IppoolIpLeaseRelationship, bool) {\n\tif o == nil || o.Peer == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Peer, true\n}"
] | [
"0.63651055",
"0.6346933",
"0.61724806",
"0.60970145",
"0.5954419",
"0.58891064",
"0.5875216",
"0.57784534",
"0.57277775",
"0.5723845",
"0.5675222",
"0.5628892",
"0.5594235",
"0.55870456",
"0.55768144",
"0.55506414",
"0.55485123",
"0.55432767",
"0.5533079",
"0.552113",
"0.5520603",
"0.551081",
"0.5496247",
"0.5494442",
"0.5474504",
"0.5473473",
"0.5467537",
"0.54626256",
"0.545485",
"0.5435388",
"0.542977",
"0.5419633",
"0.541148",
"0.53766066",
"0.53702015",
"0.53621024",
"0.5358947",
"0.5339034",
"0.5332485",
"0.53015345",
"0.52941376",
"0.52834517",
"0.5281989",
"0.52788186",
"0.52703375",
"0.524657",
"0.52383035",
"0.52284443",
"0.5227963",
"0.5226562",
"0.52226096",
"0.5212065",
"0.52049696",
"0.5199284",
"0.51918197",
"0.51911664",
"0.518741",
"0.5182588",
"0.5174762",
"0.5156527",
"0.51403695",
"0.5102407",
"0.50899875",
"0.5064391",
"0.5064305",
"0.5056963",
"0.5047675",
"0.5045268",
"0.5044675",
"0.50429076",
"0.50421995",
"0.50345606",
"0.5033178",
"0.5029838",
"0.50234514",
"0.5022516",
"0.49981362",
"0.4989874",
"0.4986421",
"0.49645218",
"0.49489447",
"0.49475244",
"0.49351326",
"0.4932473",
"0.49116042",
"0.49105716",
"0.49021986",
"0.49017447",
"0.48940983",
"0.48891896",
"0.48869744",
"0.48862335",
"0.48728913",
"0.487123",
"0.48666996",
"0.48643285",
"0.48597363",
"0.4859262",
"0.48501834",
"0.48445472"
] | 0.7487569 | 0 |
Str returns a string representation of the list state, used for debug purposes. | func (l *ListHT) Str() string {
l.mu.RLock()
defer l.mu.RUnlock()
var strs []string
for i := l.lt.first; i != nil; i = i.next {
strs = append(strs, fmt.Sprintf("%v->", i.val))
}
return strings.Join(strs, " ")
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (s State) String() string {\n\treturn [...]string{\n\t\t\"INIT\",\n\t\t\"READY\",\n\t\t\"USED\",\n\t\t\"DISABLED\",\n\t\t\"LOCKED\",\n\t\t\"ERROR\",\n\t\t\"CLONE\",\n\t\t\"DELETE\",\n\t\t\"USED_PERS\",\n\t\t\"LOCKED_USED\",\n\t\t\"LOCKED_USED_PERS\",\n\t}[s]\n}",
"func (x StrState) String() string {\n\treturn string(x)\n}",
"func (l *List) String() string {\n\tvar b strings.Builder\n\tb.WriteByte('[')\n\tb.WriteString(strconv.Itoa(l.Len))\n\tb.Write([]byte{']', ' ', '{'})\n\tfor curr := l.head; curr != nil; curr = curr.next {\n\t\tfmt.Fprint(&b, curr.Val)\n\t\tb.WriteByte(',')\n\t}\n\tb.WriteByte('}')\n\treturn b.String()\n}",
"func (l *List) String() string {\n\tif l == nil {\n\t\treturn \"nil\"\n\t}\n\tb := bytes.NewBuffer(nil)\n\tb.WriteString(\"[\")\n\ty := l\n\tfor {\n\t\tb.WriteString(fmt.Sprintf(\"%v\", y.val))\n\t\tif !y.End() {\n\t\t\tb.WriteString(\", \")\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t\ty = y.next\n\t}\n\tb.WriteString(\"]\")\n\n\treturn b.String()\n}",
"func (state *State) String() string {\n\tcs := C.StateToString(state.state)\n\tstr := C.GoString(cs)\n\tC.free(unsafe.Pointer(cs))\n\treturn str\n}",
"func (stream StreamOfStates) String() string {\n\tbuf := []string{}\n\tvar s *State\n\tfor stream != nil {\n\t\ts, stream = stream()\n\t\tbuf = append(buf, s.String())\n\t}\n\treturn \"(\" + strings.Join(buf, \" \") + \")\"\n}",
"func (s State) String() string {\n\tswitch s {\n\tcase StateRunning:\n\t\treturn \"R (running)\"\n\tcase StateSleeping:\n\t\treturn \"S (sleeping)\"\n\tcase StateDiskSleep:\n\t\treturn \"D (disk sleep)\"\n\tcase StateStopped:\n\t\treturn \"T (stopped)\"\n\tcase StateTracingStop:\n\t\treturn \"t (tracing stop)\"\n\tcase StateZombie:\n\t\treturn \"Z (zombie)\"\n\tcase StateDead:\n\t\treturn \"X (dead)\"\n\tdefault:\n\t\treturn \"? (unknown)\"\n\t}\n}",
"func (lst List) String() string {\n\titems := \"\"\n\tnode := lst.head\n\tcounter := Number(0)\n\tfor node != nil {\n\t\tif counter < lst.Len()-1 {\n\t\t\titems += fmt.Sprintf(\"%s \", node.value)\n\t\t} else {\n\t\t\titems += fmt.Sprint(node.value)\n\t\t}\n\t\tcounter++\n\t\tnode = node.next\n\t}\n\treturn fmt.Sprintf(\"(%s)\", items)\n}",
"func (ls *linestate) String() string {\n\treturn string(ls.buf)\n}",
"func (state State) String() string {\n\tif state < LOBBY || state > END {\n\t\treturn \"unknown state\"\n\t}\n\treturn states[state]\n}",
"func (s *State) String() string {\n\tif s.Running {\n\t\treturn fmt.Sprintf(\"Up %s\", HumanDuration(time.Now().Sub(s.StartedAt)))\n\t}\n\treturn fmt.Sprintf(\"Exit %d\", s.ExitCode)\n}",
"func (vl *ListValue) String() string {\n\treturn fmt.Sprintf(\"%v\", vl.list)\n}",
"func (this *List) String() string {\n\tes := make([]string, len(this.GetElems()))\n\tfor i, v := range this.GetElems() {\n\t\tes[i] = v.String()\n\t}\n\treturn this.Before.String() + listTypeToString(this.Type) + this.OpenCurly.String() + strings.Join(es, \"\") + this.CloseCurly.String()\n}",
"func (s *State) String() string {\n\tif s == nil {\n\t\treturn \"<nil>\"\n\t}\n\n\t// sort the modules by name for consistent output\n\tmodules := make([]string, 0, len(s.Modules))\n\tfor m := range s.Modules {\n\t\tmodules = append(modules, m)\n\t}\n\tsort.Strings(modules)\n\n\tvar buf bytes.Buffer\n\tfor _, name := range modules {\n\t\tm := s.Modules[name]\n\t\tmStr := m.testString()\n\n\t\t// If we're the root module, we just write the output directly.\n\t\tif m.Addr.IsRoot() {\n\t\t\tbuf.WriteString(mStr + \"\\n\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// We need to build out a string that resembles the not-quite-standard\n\t\t// format that terraform.State.String used to use, where there's a\n\t\t// \"module.\" prefix but then just a chain of all of the module names\n\t\t// without any further \"module.\" portions.\n\t\tbuf.WriteString(\"module\")\n\t\tfor _, step := range m.Addr {\n\t\t\tbuf.WriteByte('.')\n\t\t\tbuf.WriteString(step.Name)\n\t\t\tif step.InstanceKey != addrs.NoKey {\n\t\t\t\tbuf.WriteString(step.InstanceKey.String())\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(\":\\n\")\n\n\t\ts := bufio.NewScanner(strings.NewReader(mStr))\n\t\tfor s.Scan() {\n\t\t\ttext := s.Text()\n\t\t\tif text != \"\" {\n\t\t\t\ttext = \" \" + text\n\t\t\t}\n\n\t\t\tbuf.WriteString(fmt.Sprintf(\"%s\\n\", text))\n\t\t}\n\t}\n\n\treturn strings.TrimSpace(buf.String())\n}",
"func (l *List) String() string {\n\treturn fmt.Sprintf(\"%v\", l.entries)\n}",
"func (s LoadBalancerState) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (fs FifoState) String() string {\n\tswitch fs {\n\tcase FifoCreated:\n\t\treturn \"FIFO_CREATED\"\n\tcase FifoAllocated:\n\t\treturn \"FIFO_ALLOCATED\"\n\tdefault:\n\t\treturn \"FIFO_UNKNOWN_STATE\"\n\t}\n}",
"func (s EnvironmentState) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (l *List) String() string {\n\tvar s = \"\"\n\tfor curr := l.lastElement; ; curr = curr.Prev {\n\t\ts = fmt.Sprintf(\"%v\", curr.Value) + s\n\t\tif curr.Prev == nil {\n\t\t\treturn s\n\t\t}\n\t}\n}",
"func (list *List) String() string {\n\tstr := \"SinglyLinkedList\\n\"\n\tvalues := []string{}\n\tfor element := list.first; element != nil; element = element.next {\n\t\tvalues = append(values, fmt.Sprintf(\"%v\", element.value))\n\t}\n\tstr += strings.Join(values, \", \")\n\treturn str\n}",
"func (state MSCBaseState) String() string {\n\treturn fmt.Sprintf(\"{VpcAddress:0x%x Sid:0x%x BlockedSender:%s BlockedReceiver:%s Version:%s}\",\n\t\tstate.VpcAddress.Bytes(), state.Sid.Bytes(), state.BlockedSender, state.BlockedReceiver, state.Version)\n}",
"func (av AttributeState) String() string {\n\tswitch av {\n\tcase AttributeStateSys:\n\t\treturn \"sys\"\n\tcase AttributeStateSysChildren:\n\t\treturn \"sys_children\"\n\tcase AttributeStateSysMainThread:\n\t\treturn \"sys_main_thread\"\n\tcase AttributeStateUser:\n\t\treturn \"user\"\n\tcase AttributeStateUserChildren:\n\t\treturn \"user_children\"\n\tcase AttributeStateUserMainThread:\n\t\treturn \"user_main_thread\"\n\t}\n\treturn \"\"\n}",
"func (s ComponentState) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (stepList *StepList) String() string {\n\tresult := \"StepList:\\n\"\n\tfor s, step := range stepList.List {\n\t\tresult += fmt.Sprintf(\"%d: %#v\\n\", s+1, step)\n\t}\n\treturn result\n}",
"func (s InstancePatchState) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (us UserState) String() string { return string(us) }",
"func (l List) String() string {\n\tbuf := pool.AllocBuffer()\n\tdefer pool.ReleaseBuffer(buf)\n\tl.writeToBuffer(buf)\n\treturn buf.String()\n}",
"func (vl *ListerValue) String() string {\n\treturn fmt.Sprintf(\"%v\", vl.list)\n}",
"func (pl List) String() string {\n\treturn strings.Join(pl.names(), \", \")\n}",
"func (state JenkinsRunState) String() string {\n\treturn string(state)\n}",
"func (l *lockConcurrentList) String() string {\n\tl.mutex.RLock()\n\tdefer l.mutex.RUnlock()\n\treturn fmt.Sprint(l.list)\n}",
"func (lval *ListValue) String() string {\n\tbuf := new(strings.Builder)\n\tbuf.WriteByte('[')\n\tfor i, v := range lval.Values {\n\t\tif i > 0 {\n\t\t\tbuf.WriteString(\", \")\n\t\t}\n\t\tbuf.WriteString(v.String())\n\t}\n\tbuf.WriteByte(']')\n\treturn buf.String()\n}",
"func (s State) ToStr() string {\n\tif s.IsAlive() {\n\t\treturn \"Alive\"\n\t}\n\treturn \"Dead\"\n}",
"func (vl ListValue) String() string {\n\treturn fmt.Sprintf(\"%v\", []interface{}(vl))\n}",
"func (n *DSSNode) String() string {\n\treturn fmt.Sprintf(\"<-(%v)-[%d]\", n.Sym, n.State)\n}",
"func (s ServicePipelineState) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (l *LED) String() string {\n\ts, _ := l.State()\n\treturn fmt.Sprintf(\"%s\", s)\n}",
"func (l *LList) String() string {\n\tstr := \"\"\n\tcurr := l.head\n\n\tfor curr != nil {\n\t\tstr += strconv.Itoa(curr.val) + \" \"\n\t\tcurr = curr.next\n\t}\n\treturn strings.TrimRight(str, \" \")\n}",
"func (e ICAROUS_FMS_STATE) String() string {\n\tbyts, err := e.MarshalText()\n\tif err == nil {\n\t\treturn string(byts)\n\t}\n\treturn strconv.FormatInt(int64(e), 10)\n}",
"func (s WorkflowListItem) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s DeploymentState) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (ss SwapState) String() string {\n\tswitch ss {\n\tcase None:\n\t\treturn \"none\"\n\tcase Initiated:\n\t\treturn \"initiated\"\n\tcase Redeemed:\n\t\treturn \"redeemed\"\n\tcase Refunded:\n\t\treturn \"refunded\"\n\t}\n\treturn \"unknown\"\n}",
"func (state VPCState) String() string {\n\treturn fmt.Sprintf(\"{Id:0x%x Version:%s BlockedSender:%s BlockedReceiver:%s}\",\n\t\tstate.ID, state.Version.String(), state.BlockedSender, state.BlockedReceiver)\n}",
"func (list *LinkedList[T]) String() string {\n\tlist.key.RLock()\n\tdefer list.key.RUnlock()\n\n\tbuilder := bytes.NewBufferString(\"[\")\n\tcurrent := list.first\n\tfor i := 0; i < 15 && current != nil; i++ {\n\t\tbuilder.WriteString(fmt.Sprintf(\"%v \", current.payload))\n\t\tcurrent = current.next\n\t}\n\tif current == nil || current.next == nil {\n\t\tbuilder.Truncate(builder.Len() - 1)\n\t} else {\n\t\tbuilder.WriteString(\"...\")\n\t}\n\tbuilder.WriteRune(']')\n\treturn builder.String()\n}",
"func (l *ExprList) String() string {\n\tvar buf bytes.Buffer\n\tbuf.WriteString(\"(\")\n\tfor i, expr := range l.Exprs {\n\t\tif i != 0 {\n\t\t\tbuf.WriteString(\", \")\n\t\t}\n\t\tbuf.WriteString(expr.String())\n\t}\n\tbuf.WriteString(\")\")\n\treturn buf.String()\n}",
"func (l List) String() string {\n\ts := \"<start>\"\n\te := \"<end>\"\n\n\tif l.Root == nil {\n\t\ts = s + e\n\t}\n\n\tif l.Root != nil {\n\t\tn := l.Root\n\t\tfor n != nil {\n\t\t\tif n.Next == nil {\n\t\t\t\t// last one\n\t\t\t\ts = s + fmt.Sprintf(\"%v<end>\", n.Value)\n\t\t\t} else {\n\t\t\t\t// not last\n\t\t\t\ts = s + fmt.Sprintf(\"%v, \", n.Value)\n\t\t\t}\n\t\t\tn = n.Next\n\t\t}\n\t}\n\treturn s\n}",
"func (el EnvNameList) String() string {\n\tl := make([]string, 0, len(el))\n\n\tfor i, e := range el {\n\t\tl[i] = string(e)\n\t}\n\n\treturn strings.Join(l, \", \")\n}",
"func (l *List) String() string {\n\twords := make([]string, 0, 3*l.Len())\n\tfor e := l.Front(); e != nil; e = e.Next() {\n\t\twords = append(words, fmt.Sprint(e.Value))\n\t}\n\treturn \"(\" + strings.Join(words, \" \") + \")\"\n}",
"func (s RunListItem) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (l unitList) State() string {\n\tif len(l) == 0 {\n\t\treturn \"\"\n\t}\n\tstate := l[0].State\n\tfor i := 1; i < len(l); i++ {\n\t\tif l[i].State != state {\n\t\t\treturn \"\"\n\t\t}\n\t}\n\treturn state\n}",
"func (e MapStateEntry) String() string {\n\treturn fmt.Sprintf(\"ProxyPort=%d\", e.ProxyPort)\n}",
"func (s *StringList) String() string {\n\treturn fmt.Sprintf(\"%v\", *s)\n}",
"func (ltype *ListType) String() string {\n\treturn \"[\" + ltype.Type.String() + \"]\"\n}",
"func (i *IntList) String() string { return fmt.Sprintf(\"%v\", *i) }",
"func (me TFeatureListType) String() string { return xsdt.String(me).String() }",
"func (s InstancePatchStateFilter) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (l *SinglyLinkedList) String() string {\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"[\")\n\n\tif l.size != 0 && l.head.next != nil {\n\t\tfor node := l.head.next; node != nil; node = node.next {\n\t\t\tswitch v := node.Value.(type) {\n\t\t\tcase string:\n\t\t\t\tbuffer.WriteString(v)\n\t\t\tcase int:\n\t\t\t\tbuffer.WriteString(strconv.Itoa(v))\n\t\t\tcase float32:\n\t\t\tcase float64:\n\t\t\t\tbuffer.WriteString(fmt.Sprintf(\"%.2f\", v))\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Node's value isn't a string, int nor a float\")\n\t\t\t}\n\n\t\t\tif node.next != nil {\n\t\t\t\tbuffer.WriteString(\", \")\n\t\t\t}\n\t\t}\n\t}\n\n\tbuffer.WriteString(\"]\")\n\treturn buffer.String()\n}",
"func (cs *ConnectivityState) String() string {\n\tfor state, id := range connectivityStates {\n\t\tif id == cs.GetCurrentState() {\n\t\t\treturn state\n\t\t}\n\t}\n\n\treturn \"\"\n}",
"func (l HashChainLinkIdentityList) String() string {\n\tif len(l) == 0 {\n\t\treturn \"\"\n\t}\n\n\tvar b strings.Builder\n\tfor i, id := range l {\n\t\tb.WriteString(strconv.FormatInt(int64(i), 10))\n\t\tb.WriteString(\". Identity: \")\n\t\tb.WriteString(id.String())\n\t\tb.WriteString(\"\\n\")\n\t}\n\treturn b.String()\n}",
"func (s *SyncKeyList) String() string {\n\tstrs := make([]string, 0)\n\tfor _, v := range s.List {\n\t\tstrs = append(strs, strconv.Itoa(v.Key)+\"_\"+strconv.Itoa(v.Val))\n\t}\n\treturn strings.Join(strs, \"|\")\n}",
"func (r *RequestListIndex) String() string {\n\treturn fmt.Sprintf(\"id: %s, type: list index, key: %s\"+\n\t\t\", index: %d\", r.ID, r.Key, r.Index)\n}",
"func stateToString(i int) string {\n\tvar s string\n\tswitch {\n\tcase i == uUNKNOWN:\n\t\ts = \"UNKNOWN\"\n\tcase i == uINIT:\n\t\ts = \"INIT\"\n\tcase i == uREADY:\n\t\ts = \"READY\"\n\tcase i == uTEST:\n\t\ts = \"TEST\"\n\tcase i == uDONE:\n\t\ts = \"DONE\"\n\tcase i == uTERM:\n\t\ts = \"TERM\"\n\tdefault:\n\t\ts = \"<<unknown state>>\"\n\t}\n\treturn fmt.Sprintf(\"%d (%s)\", i, s)\n}",
"func (s LegacyStatus) String() string {\n\tss := []string(s)\n\tif len(ss) == 0 {\n\t\treturn \"\"\n\t}\n\n\treturn \"[\" + strings.Join(ss, \",\") + \"]\"\n}",
"func (stateID StateID) String() string {\n\treturn fmt.Sprintf(`%v`, stateID.LastAppHash)\n}",
"func (list *ArrayList[T]) String() string {\n\treturn fmt.Sprint(list.elems)\n}",
"func (l Slist) ToString() string {\n\ts := l.listToSlice()\n\treturn fmt.Sprint(s)\n}",
"func (ms *StatusImpl) String() string {\n\tms.mutex.Lock()\n\tdefer ms.mutex.Unlock()\n\n\treturn fmt.Sprintf(\"State=%s, Context=%d, Sys=%t\", ms.state, ms.context, ms.systemChannel)\n}",
"func (v *VList) String() string {\n\ts := \"(\"\n\tfor i, item := range v.value {\n\t\tif i > 0 {\n\t\t\ts += \" \"\n\t\t}\n\t\ts += item.String()\n\t}\n\treturn s + \")\"\n}",
"func (s SwapState) String() string {\n\tswitch s {\n\tcase StateInitiated:\n\t\treturn \"Initiated\"\n\n\tcase StatePreimageRevealed:\n\t\treturn \"PreimageRevealed\"\n\n\tcase StateHtlcPublished:\n\t\treturn \"HtlcPublished\"\n\n\tcase StateSuccess:\n\t\treturn \"Success\"\n\n\tcase StateFailOffchainPayments:\n\t\treturn \"FailOffchainPayments\"\n\n\tcase StateFailTimeout:\n\t\treturn \"FailTimeout\"\n\n\tcase StateFailSweepTimeout:\n\t\treturn \"FailSweepTimeout\"\n\n\tcase StateFailInsufficientValue:\n\t\treturn \"FailInsufficientValue\"\n\n\tcase StateFailTemporary:\n\t\treturn \"FailTemporary\"\n\n\tcase StateInvoiceSettled:\n\t\treturn \"InvoiceSettled\"\n\n\tcase StateFailIncorrectHtlcAmt:\n\t\treturn \"IncorrectHtlcAmt\"\n\n\tdefault:\n\t\treturn \"Unknown\"\n\t}\n}",
"func (s CellState) String() string {\n\tswitch s {\n\tcase Closed:\n\t\treturn \"Closed\"\n\n\tcase Opened:\n\t\treturn \"Opened\"\n\n\tcase Flagged:\n\t\treturn \"Flagged\"\n\n\tcase Exploded:\n\t\treturn \"Exploded\"\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unknown state is given: %d\", s))\n\n\t}\n}",
"func (st StateType) String() string {\n\tswitch st {\n\tcase StateConn:\n\t\treturn \"connection\"\n\tcase StateChan:\n\t\treturn \"channel\"\n\tdefault:\n\t\treturn \"invalid\"\n\t}\n}",
"func (p *ubDebugPayload) String() string {\n\treturn fmt.Sprintf(\"[%s][%s][%s][%s]\", formatFlags(p.flags), p.suffix, p.original, p.list)\n}",
"func (s serviceState) String() string {\n\tswitch s {\n\tcase StateStable: return \"stable\"\n\tcase StateOverThreshold: return \"over_threshold\"\n\tcase StateUnderThreshold: return \"under_threshold\"\n\tcase StateScaling: return \"scaling\"\n\tdefault: return \"unknown\"\n\t}\n}",
"func (s ConnectionState) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s *StateNotification) String() string {\n\tmetrics := []string{}\n\n\tfor k, v := range s.Metrics.Metrics {\n\t\tmetrics = append(metrics, fmt.Sprintf(\"%s=%0.3f\", k, v))\n\t}\n\n\treturn fmt.Sprintf(\"%s %s#%s metrics: %s\", s.Identity, s.Machine, s.Name, strings.Join(metrics, \", \"))\n}",
"func (s HandshakeAlreadyInStateException) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s ListItemsOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (me TitemIconStateType) String() string { return xsdt.String(me).String() }",
"func (s TxAttemptState) String() (str string) {\n\tif s < txAttemptStateCount {\n\t\treturn txAttemptStateStrings[s]\n\t}\n\treturn txAttemptStateStrings[0]\n}",
"func (this *LinkedList) String() string {\n\treturn fmt.Sprint(this.ToSlice())\n}",
"func (list List) String() string {\n\tbuilder := strings.Builder{}\n\n\tfor _, t := range list {\n\t\tbuilder.WriteString(t.String())\n\t}\n\n\treturn builder.String()\n}",
"func (t ContainerState) String() string {\n\tswitch t {\n\tcase ContainerStateUnknown:\n\t\treturn \"unknown\"\n\tcase ContainerStateConfigured:\n\t\treturn \"configured\"\n\tcase ContainerStateCreated:\n\t\treturn \"created\"\n\tcase ContainerStateRunning:\n\t\treturn \"running\"\n\tcase ContainerStateStopped:\n\t\treturn \"exited\"\n\tcase ContainerStatePaused:\n\t\treturn \"paused\"\n\t}\n\treturn \"bad state\"\n}",
"func (e E_OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv6_Addresses_Address_State_Status) String() string {\n\treturn ygot.EnumLogString(e, int64(e), \"E_OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv6_Addresses_Address_State_Status\")\n}",
"func (s FirewallDomainList) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (ps ProjectState) String() string {\n\tvar state string\n\n\tswitch ps {\n\tcase StateQueued:\n\t\tstate = \"queued\"\n\tcase StateProcessing:\n\t\tstate = \"processing\"\n\tcase StateSuccess:\n\t\tstate = \"success\"\n\tcase StateFailed:\n\t\tstate = \"failed\"\n\t}\n\n\treturn state\n}",
"func (f *ForkStateT) String() string {\n\tif _, ok := forkStrings[*f]; ok {\n\t\treturn forkStrings[*f]\n\t}\n\treturn \"\"\n}",
"func (s TaskListItem) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (state MSCBaseStateSigned) String() string {\n\treturn fmt.Sprintf(\"{MSCBaseState:%+v SignSender:0x%x SignReceiver:0x%x}\",\n\t\tstate.MSContractBaseState, state.SignSender, state.SignReceiver)\n}",
"func (ev *FSAEnv) String() string {\n\tnn := ev.NNext.Values[0]\n\tlbls := ev.NextLabels.Values[0:nn]\n\treturn fmt.Sprintf(\"S_%d_%v\", ev.AState.Cur, lbls)\n}",
"func (state Status) String() string {\n\t// declare an array of strings. operator counts how many items in the array (4)\n\tlistStatus := [...]string{\"Offline\", \"Online\", \"Warning\", \"Critical\"}\n\n\t// → `state`: It's one of the values of Status constants.\n\t// prevent panicking in case of `status` is out of range of Status\n\tif state < Offline || state > Critical {\n\t\treturn \"Unknown\"\n\t}\n\t// return the status string constant from the array above.\n\treturn listStatus[state]\n}",
"func (e E_OpenconfigInterfaces_Interfaces_Interface_State_OperStatus) String() string {\n\treturn ygot.EnumLogString(e, int64(e), \"E_OpenconfigInterfaces_Interfaces_Interface_State_OperStatus\")\n}",
"func (s State) String() string {\n\treturn StateAbbr[s]\n}",
"func (encl StoreEncryptionSpecList) String() string {\n\tvar buffer bytes.Buffer\n\tfor _, ss := range encl.Specs {\n\t\tfmt.Fprintf(&buffer, \"--%s=%s \", cliflagsccl.EnterpriseEncryption.Name, ss)\n\t}\n\t// Trim the extra space from the end if it exists.\n\tif l := buffer.Len(); l > 0 {\n\t\tbuffer.Truncate(l - 1)\n\t}\n\treturn buffer.String()\n}",
"func (s ExchangeState) String() string {\n\tswitch s {\n\tcase ExchangeStateDetected:\n\t\treturn \"Detected\"\n\tcase ExchangeStateTransferring:\n\t\treturn \"Transferring\"\n\tcase ExchangeStateTransferred:\n\t\treturn \"Transferred\"\n\tcase ExchangeStateInvalidTxData:\n\t\treturn \"InvalidTxData\"\n\tcase ExchangeStateFailed:\n\t\treturn \"Failed\"\n\tdefault:\n\t\treturn \"Unknown\"\n\t}\n}",
"func (tm *TuringMachine) ToString(step uint32) string {\n\tvar stateString string\n\tstateString = fmt.Sprintf(\"%4d [S%d] | \", step, tm.GetState())\n\tfor i, cell := range tm.GetTape().GetCell() {\n\t\tif i == int(tm.GetHeadPosition()) {\n\t\t\tstateString += fmt.Sprintf(\"<%s>|\", cell.GetSymbol())\n\t\t} else {\n\t\t\tstateString += fmt.Sprintf(\" %s |\", cell.GetSymbol())\n\t\t}\n\t}\n\treturn stateString\n}",
"func (m *StoreInstr) String() string {\n\treturn fmt.Sprintf(\"%s, %s\",\n\t\t(m.reg).String(),\n\t\t(m.value).String())\n}",
"func (s ChangeServerLifeCycleStateOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (me TitemIconStateEnumType) String() string { return xsdt.String(me).String() }",
"func (sll *SingleLinkedList) String() string {\n\t// Result string\n\tvar s string\n\n\t// First node\n\tn := sll.first\n\n\t// Loop through list\n\tfor {\n\t\t// Empty list\n\t\tif n == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif s == \"\" {\n\t\t\t// Prints first element\n\t\t\ts = fmt.Sprintf(\"%v\", n.value)\n\t\t} else {\n\t\t\t// Add more elements\n\t\t\ts = fmt.Sprintf(\"%v %v\", s, n.value)\n\t\t}\n\n\t\t// Next node\n\t\tn = n.next\n\t}\n\n\t// Add surrounding brackets\n\treturn fmt.Sprintf(\"[%v]\", s)\n}",
"func (s ReferenceListItem) String() string {\n\treturn awsutil.Prettify(s)\n}"
] | [
"0.72558296",
"0.6963321",
"0.67778015",
"0.677034",
"0.6744347",
"0.6727925",
"0.6664155",
"0.6655761",
"0.6649462",
"0.66395485",
"0.6633828",
"0.661118",
"0.6608794",
"0.6592846",
"0.6586459",
"0.6570095",
"0.6545046",
"0.65364397",
"0.6517469",
"0.65096736",
"0.65083003",
"0.6487348",
"0.64841676",
"0.6482919",
"0.6478324",
"0.6463934",
"0.6452272",
"0.64226973",
"0.64221585",
"0.6421258",
"0.64177024",
"0.64132464",
"0.6398785",
"0.63927376",
"0.63911825",
"0.6369903",
"0.63665813",
"0.63594246",
"0.63551754",
"0.63546616",
"0.6354321",
"0.6350655",
"0.633882",
"0.6317256",
"0.62828714",
"0.6264621",
"0.62631243",
"0.6260817",
"0.6243903",
"0.6225874",
"0.62188214",
"0.61855894",
"0.6180211",
"0.61687094",
"0.6160498",
"0.6158151",
"0.6154757",
"0.6144891",
"0.61410755",
"0.6134659",
"0.6131618",
"0.61215824",
"0.6119285",
"0.6117794",
"0.61049956",
"0.60935766",
"0.6083615",
"0.60747087",
"0.6068621",
"0.60681653",
"0.60668755",
"0.6059955",
"0.60584825",
"0.605734",
"0.6045205",
"0.60443425",
"0.60401016",
"0.6038961",
"0.60261756",
"0.60210603",
"0.60202056",
"0.60134065",
"0.6012109",
"0.60089374",
"0.60082084",
"0.600527",
"0.6003317",
"0.59790343",
"0.5964519",
"0.59640384",
"0.59476006",
"0.59370166",
"0.5935596",
"0.5931657",
"0.59169316",
"0.59094393",
"0.59082735",
"0.58918184",
"0.58900106",
"0.58796483"
] | 0.6183888 | 52 |
Len returns the list length. | func (l *ListHT) Len() uint64 {
return l.lt.len
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (l *List) Len() int {\n return l.size\n}",
"func (l *List) Len() int { return l.len }",
"func (sl *List) Len() int { return sl.len }",
"func (l *List) Len() int {\r\n\treturn l.length\r\n}",
"func (l *List) Len() int {\n\treturn l.size\n}",
"func (l List) Len() int {\n\treturn l.len\n}",
"func (p List) Len() int { return len(p) }",
"func (pl List) Len() int {\n\treturn len(pl)\n}",
"func (list *List) Len() int {\n\treturn len(list.data)\n}",
"func (lst List) Len() Number {\n\treturn Number(lst.len)\n}",
"func (l *SList) Len() int { return l.n }",
"func (l *List) Len() int {\n\treturn l.len\n}",
"func (l *List) Len() int {\n\treturn l.len\n}",
"func (l *List) Len() int {\n\treturn l.len\n}",
"func (l *List) Len() int {\n\tl.RLock()\n\tdefer l.RUnlock()\n\n\treturn l.length\n}",
"func (l List) Length() int {\n\treturn len(l)\n}",
"func (list List) Length() int {\n\treturn len(list)\n}",
"func (l *DList) Len() int { return l.n }",
"func (l *IntList) Len() int {\n\treturn int(atomic.LoadInt64(&l.length))\n}",
"func (list *TList) Len() int {\n\treturn list.list.Len()\n}",
"func (l *List) Length() int {\n\treturn len(l.items)\n}",
"func (list *DoublyLinkedList) Len() int {\n\treturn list.size\n}",
"func (l *SkipList) Len() int {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\n\treturn l.len\n}",
"func (l *List) Len() int {\n\treturn len(l.Source)\n}",
"func (s *SkipList) Len() int {\n\treturn s.length\n}",
"func (list VulnerabilityList) Len() int {\n\treturn len(list)\n}",
"func (l *List) Len() int {\n\ti := 1\n\ty := l\n\tfor !y.End() {\n\t\ti++\n\t\ty = y.next\n\t}\n\n\treturn i\n}",
"func (b *ListBuilder) Len() (int, error) {\n\tl, err := b.List()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn l.Len(), nil\n}",
"func (sl *genericSkipList) Len() int {\n\treturn sl.size\n}",
"func (b *ListBuilder) Len() (int, error) {\n\tl, err := b.List()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn l.Len(), nil\n}",
"func (r RuneList) Len() int {\n\treturn len(r)\n}",
"func (l *idList) Len() int { return l.len }",
"func (s SampleList) Len() int {\n\treturn len(s)\n}",
"func (this *List) Len() int {\n this.lock.RLock()\n this.lock.RUnlock()\n\n return len(this.counters)\n}",
"func (list IntList) Length() int {\n\treturn len(list)\n}",
"func (ll *LinkedList) Len() int {\n\treturn ll.length\n}",
"func (l DNA8List) Len() int { return len(l) }",
"func (o openList) Len() int {\n\treturn len(o)\n}",
"func (list elemlist) Len() int {\n\treturn len(list.elements)\n}",
"func (l *HandoffList) Len() int {\n\tif l == nil {\n\t\treturn 0\n\t}\n\treturn len(l.items)\n}",
"func (l *AddOnList) Len() int {\n\tif l == nil {\n\t\treturn 0\n\t}\n\treturn len(l.items)\n}",
"func (shortlist *Shortlist) Len() int {\n\tlength := 0\n\tfor _, entry := range shortlist.Entries {\n\t\tif entry != nil {\n\t\t\tlength++\n\t\t}\n\t}\n\treturn length\n}",
"func (m *Memberlist) Len() int {\n\treturn m.list.NumMembers()\n}",
"func (v VersionList) Len() int {\n\treturn len(v)\n}",
"func (l *CSPList) Len() int {\n\treturn len(l.ObjectList.Items)\n}",
"func (h *Strings) Len() int {\n\treturn len(h.list)\n}",
"func (ls *LookupList) Len() int {\n\treturn len(ls.Nodelist)\n}",
"func (ls *LookupList) Len() int {\n\treturn len(ls.Nodelist)\n}",
"func (I Twitlist) Len() int {\n\treturn len(I)\n}",
"func (t ReplicaList) Len() int {\n\treturn len(t)\n}",
"func (lru *LRU) Len() int {\n\treturn lru.list.Len()\n}",
"func (list linkedList) getLength() int {\n\treturn list.length\n}",
"func (l *HandlerList) Len() int {\n\treturn len(l.list)\n}",
"func (p *ZFSVolumeList) Len() int {\n\treturn len(p.List.Items)\n}",
"func (l List) Length() (length uint) {\n\tcurrent := l.Root\n\n\tfor current != nil {\n\t\tlength++\n\t\tcurrent = current.Next\n\t}\n\treturn\n}",
"func (stack *Stack) Len() int {\n\treturn stack.list.Len()\n}",
"func (list CategoryList) Len() int { return len(list) }",
"func (l *pqList) Len() int {\n\treturn len(l.Slice)\n}",
"func (l IntList) Length() int {\n\tvar cnt int\n\tfor _, _ = range l {\n\t\tcnt++\n\t}\n\treturn cnt\n}",
"func (l *List) Size() int {\n\treturn l.len\n}",
"func (fields List) Len() int {\n\tvar count int\n\tb := ptob(fields.p)\n\tvar i int\n\tfor {\n\t\tx, n := uvarint(b[i:])\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\t\tif useSharedNames {\n\t\t\ti += n\n\t\t} else {\n\t\t\ti += n + x\n\t\t}\n\t\tisdatakind := datakind(Kind(b[i]))\n\t\ti++\n\t\tif isdatakind {\n\t\t\tx, n = uvarint(b[i:])\n\t\t\ti += n + x\n\t\t}\n\t\tcount++\n\t}\n\treturn count\n}",
"func (list LinkedListNode) Len() (l int) {\n\tl = 0\n\tfor curr := &list; curr != nil; curr = curr.Next {\n\t\tl++\n\t}\n\treturn\n}",
"func (s *Store) Len(ctx context.Context) (int64, error) {\n\tvar nb int64\n\tif err := s.List(ctx, \"\", func(string) error {\n\t\tnb++\n\t\treturn nil\n\t}); err != nil {\n\t\treturn 0, err\n\t}\n\treturn nb, nil\n}",
"func (List *List) Length() int {\n\tlen := 0\n\ttraversingPtr := List.Head\n\n\tfor traversingPtr != nil {\n\t\tlen = len + 1\n\t\ttraversingPtr = traversingPtr.Next\n\t}\n\treturn len\n}",
"func (l *LDAPIdentityProviderList) Len() int {\n\tif l == nil {\n\t\treturn 0\n\t}\n\treturn len(l.items)\n}",
"func ListLength(head *Node) int {\n\trunner := head\n\tlength := 0\n\tfor runner != nil {\n\t\tlength++\n\t\trunner = runner.Next\n\t}\n\treturn length\n}",
"func (l ResolutionList) Len() int { return len(l) }",
"func (h *Header) Len()int {\r\n\treturn h.List.Len()\r\n}",
"func (arr *ArrayList) Len() uint32 {\n return arr.length\n}",
"func (ms *MultiKeySorter) Len() int {\n\treturn len(ms.List)\n}",
"func (a *Sortable) Len() int {\n\treturn len(a.List)\n}",
"func (a *Sortable) Len() int {\n\treturn len(a.List)\n}",
"func (a *Sortable) Len() int {\n\treturn len(a.List)\n}",
"func (l *AttributeList) Len() int { return l.length }",
"func (ls *ListStack) Len() int {\n\tif ls.threadSafe {\n\t\tls.lock.Lock()\n\t\tdefer ls.lock.Unlock()\n\t\treturn ls.backer.Len()\n\t}\n\n\treturn ls.backer.Len()\n}",
"func (s SkipList) Length() int {\n\treturn s.length\n}",
"func (intList *ConcurrentIntList) Len() int {\n\treturn int(atomic.LoadInt64(&intList.size))\n}",
"func (rules *Rules) Len() int {\n\treturn len(rules.list)\n}",
"func (list *LinkedList[T]) Length() uint {\n\tlist.key.RLock()\n\tdefer list.key.RUnlock()\n\n\treturn list.length\n}",
"func TestShouldGetListLength(t *testing.T) {\n\tlst := []int{1, 2, 3, 4, 5}\n\n\tl := Length(lst)\n\n\tassert.Equal(t, l, 5, \"List size should be 5\")\n}",
"func (c CountryList) Len() int {\n\treturn len(c)\n}",
"func (ms *MultiSorter) Len() int {\n\treturn len(ms.list)\n}",
"func (l *RangeList) Length() int {\n\treturn len(*l)\n}",
"func (l *List) Size() int {\n\treturn l.Len()\n}",
"func (opts *ListOpts) Len() int {\n return len((*opts.values))\n}",
"func (stack *ArrayStack) Len() int {\n\treturn stack.list.Len()\n}",
"func (l *PendingDeleteClusterList) Len() int {\n\tif l == nil {\n\t\treturn 0\n\t}\n\treturn len(l.items)\n}",
"func (l DriverInfoList) Len() int { return len(l) }",
"func (tsl TabletStatsList) Len() int {\n\treturn len(tsl)\n}",
"func (l *semaphoreList) length() int {\n\tl.RLock()\n\tdefer l.RUnlock()\n\tlength := len(l.list)\n\treturn length\n}",
"func (ls *LevelSlice) Len() int {\n\treturn ls.length\n}",
"func (a *EmergencyNumberList) GetLen() (len uint8) {}",
"func (storage *Storage) Len() (n int) {\n\tstorage.mutex.Lock()\n\tn = storage.lruList.Len()\n\tstorage.mutex.Unlock()\n\treturn\n}",
"func (d *babbleDictionary) GetListLength() int {\n\treturn len(d.sourceList)\n}",
"func (l *AddonStatusList) Len() int {\n\tif l == nil {\n\t\treturn 0\n\t}\n\treturn len(l.items)\n}",
"func (s *SliceOfInt64) Len() int {\n\treturn len(s.items)\n}",
"func (s *SliceOfInt32) Len() int {\n\treturn len(s.items)\n}",
"func (c *LRU) Len() int {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\treturn c.ll.Len()\n}",
"func (pl ParticipantList) Len() int {\n\treturn len(pl)\n}",
"func (l *errList) Len() int {\n\treturn l.len\n}"
] | [
"0.8686351",
"0.8667231",
"0.8586168",
"0.85807544",
"0.8553614",
"0.85223997",
"0.84929997",
"0.8474894",
"0.8421061",
"0.84064734",
"0.84041613",
"0.8403302",
"0.8403302",
"0.8403302",
"0.8389167",
"0.83514076",
"0.8346961",
"0.8311869",
"0.8201227",
"0.81657743",
"0.81590444",
"0.81539476",
"0.8118703",
"0.80973303",
"0.8089726",
"0.80799055",
"0.8074529",
"0.80558574",
"0.8041558",
"0.8034117",
"0.80270004",
"0.80057573",
"0.8005168",
"0.79810864",
"0.79710907",
"0.7967669",
"0.79428136",
"0.7939888",
"0.79390025",
"0.7917787",
"0.7899598",
"0.78789717",
"0.78686464",
"0.7847531",
"0.78387326",
"0.78127295",
"0.78068507",
"0.78068507",
"0.7801865",
"0.7789266",
"0.7788704",
"0.77873945",
"0.7747269",
"0.773574",
"0.77188456",
"0.7705076",
"0.77045166",
"0.77010006",
"0.77000785",
"0.7695996",
"0.7672319",
"0.7667443",
"0.7661695",
"0.7661376",
"0.7652335",
"0.7649169",
"0.7641091",
"0.76298696",
"0.7621986",
"0.7606858",
"0.7591956",
"0.7591956",
"0.7591956",
"0.75665134",
"0.75597537",
"0.7526624",
"0.75239813",
"0.7504443",
"0.7501889",
"0.7501006",
"0.7491792",
"0.7491472",
"0.7478235",
"0.7476998",
"0.74757683",
"0.74696475",
"0.74639773",
"0.74588954",
"0.7457267",
"0.7455696",
"0.7450019",
"0.7447857",
"0.7446672",
"0.7443447",
"0.7441026",
"0.74404097",
"0.7439739",
"0.74294776",
"0.74248296",
"0.7420175"
] | 0.79621387 | 36 |
Log records the occurence of command 'cmd' on the provided index. Writes are mapped as a new node on the underlying liked list, with a pointer to the newly inserted state update on the update list for its particular key. | func (l *ListHT) Log(cmd pb.Command) error {
l.mu.Lock()
defer l.mu.Unlock()
if cmd.Op != pb.Command_SET {
// TODO: treat 'l.first' attribution on GETs
l.last = cmd.Id
return l.mayTriggerReduce()
}
entry := &listEntry{
ind: cmd.Id,
key: cmd.Key,
}
// a write cmd always references a new state on the aux hash table
st := &State{
ind: cmd.Id,
cmd: cmd,
}
_, exists := (*l.aux)[cmd.Key]
if !exists {
(*l.aux)[cmd.Key] = &list{}
}
// add state to the list of updates in that particular key
lNode := (*l.aux)[cmd.Key].push(st)
entry.ptr = lNode
// adjust first structure index
if l.lt.tail == nil {
l.first = entry.ind
}
// insert new entry on the main list
l.lt.push(entry)
// adjust last index once inserted
l.last = cmd.Id
// immediately recovery entirely reduces the log to its minimal format
if l.config.Tick == Immediately {
return l.ReduceLog(l.first, l.last)
}
return l.mayTriggerReduce()
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (c *ClusterPodRunner) logInfoCmd(podName types.NamespacedName, command ...string) {\n\tvar sb strings.Builder\n\tfor i := 0; i < len(command); i++ {\n\t\tswitch command[i] {\n\t\tcase \"--password\", \"-w\":\n\t\t\tsb.WriteString(command[i])\n\t\t\tsb.WriteString(\" \")\n\t\t\tsb.WriteString(\"*******\")\n\t\t\ti++\n\t\tdefault:\n\t\t\tsb.WriteString(command[i])\n\t\t}\n\t\tsb.WriteString(\" \")\n\t}\n\tc.Log.Info(\"ExecInPod entry\", \"pod\", podName, \"command\", sb.String())\n}",
"func runLogIndexer() {\n\tfor {\n\t\tselect {\n\t\tcase e := <-mpdLogReader.AddEvent:\n\t\t\tlogrus.Infof(\"Add item event: %s\", e)\n\t\t\tattr := mpdClient.GetDatabaseItem(e)\n\n\t\t\tlogrus.Infof(\"Add item: %v\", attr)\n\n\t\t\tesClient.IndexBulk(e, Song{\n\t\t\t\tFile: e,\n\t\t\t\tDate: attr[\"date\"],\n\t\t\t\tDuration: attr[\"duration\"],\n\t\t\t\tComposer: attr[\"composer\"],\n\t\t\t\tAlbum: attr[\"album\"],\n\t\t\t\tTrack: attr[\"track\"],\n\t\t\t\tTitle: attr[\"title\"],\n\t\t\t\tArtist: attr[\"artist\"],\n\t\t\t\tGenre: attr[\"genre\"],\n\t\t\t})\n\t\tcase e := <-mpdLogReader.DeleteEvent:\n\t\t\tlogrus.Infof(\"Delete item event: %s\", e)\n\t\t\tesClient.DeleteBluk(e)\n\t\t}\n\t}\n}",
"func (r *Raft) AppendToLog_Leader(cmd []byte) {\n\tterm := r.currentTerm\n\tlogVal := LogVal{term, cmd, 0} //make object for log's value field with acks set to 0\n\t//fmt.Println(\"Before putting in log,\", logVal)\n\tr.myLog = append(r.myLog, logVal)\n\t//fmt.Println(\"I am:\", r.Myconfig.Id, \"Added cmd to my log\")\n\n\t//modify metadata after appending\n\t//fmt.Println(\"Metadata before appending,lastLogIndex,prevLogIndex,prevLogTerm\", r.myMetaData.lastLogIndex, r.myMetaData.prevLogIndex, r.myMetaData.prevLogTerm)\n\tlastLogIndex := r.myMetaData.lastLogIndex + 1\n\tr.myMetaData.prevLogIndex = r.myMetaData.lastLogIndex\n\tr.myMetaData.lastLogIndex = lastLogIndex\n\t//fmt.Println(r.myId(), \"Length of my log is\", len(r.myLog))\n\tif len(r.myLog) == 1 {\n\t\tr.myMetaData.prevLogTerm = r.myMetaData.prevLogTerm + 1 //as for empty log prevLogTerm is -2\n\n\t} else if len(r.myLog) > 1 { //explicit check, else would have sufficed too, just to eliminate len=0 possibility\n\t\tr.myMetaData.prevLogTerm = r.myLog[r.myMetaData.prevLogIndex].Term\n\t}\n\t//r.currentTerm = term\n\t//fmt.Println(\"I am leader, Appended to log, last index, its term is\", r.myMetaData.lastLogIndex, r.myLog[lastLogIndex].term)\n\t//fmt.Println(\"Metadata after appending,lastLogIndex,prevLogIndex,prevLogTerm\", r.myMetaData.lastLogIndex, r.myMetaData.prevLogIndex, r.myMetaData.prevLogTerm)\n\tr.setNextIndex_All() //Added-28 march for LogRepair\n\t//Write to disk\n\t//fmt.Println(r.myId(), \"In append_leader, appended to log\", string(cmd))\n\tr.WriteLogToDisk()\n\n}",
"func TestLogNewLog(t *testing.T) {\n\tpath := getLogPath()\n\tlog := NewLog()\n\tlog.AddCommandType(&TestCommand1{})\n\tlog.AddCommandType(&TestCommand2{})\n\tif err := log.Open(path); err != nil {\n\t\tt.Fatalf(\"Unable to open log: %v\", err)\n\t}\n\tdefer log.Close()\n\tdefer os.Remove(path)\n\t\n\tif err := log.Append(NewLogEntry(log, 1, 1, &TestCommand1{\"foo\", 20})); err != nil {\n\t\tt.Fatalf(\"Unable to append: %v\", err)\n\t}\n\tif err := log.Append(NewLogEntry(log, 2, 1, &TestCommand2{100})); err != nil {\n\t\tt.Fatalf(\"Unable to append: %v\", err)\n\t}\n\tif err := log.Append(NewLogEntry(log, 3, 2, &TestCommand1{\"bar\", 0})); err != nil {\n\t\tt.Fatalf(\"Unable to append: %v\", err)\n\t}\n\t\n\t// Partial commit.\n\tif err := log.SetCommitIndex(2); err != nil {\n\t\tt.Fatalf(\"Unable to partially commit: %v\", err)\n\t}\n\texpected := \n\t\t`cf4aab23 0000000000000001 0000000000000001 cmd_1 {\"val\":\"foo\",\"i\":20}`+\"\\n\" +\n\t\t`4c08d91f 0000000000000002 0000000000000001 cmd_2 {\"x\":100}`+\"\\n\"\n\tactual, _ := ioutil.ReadFile(path)\n\tif string(actual) != expected {\n\t\tt.Fatalf(\"Unexpected buffer:\\nexp:\\n%s\\ngot:\\n%s\", expected, string(actual))\n\t}\n\n\t// Full commit.\n\tif err := log.SetCommitIndex(3); err != nil {\n\t\tt.Fatalf(\"Unable to commit: %v\", err)\n\t}\n\texpected = \n\t\t`cf4aab23 0000000000000001 0000000000000001 cmd_1 {\"val\":\"foo\",\"i\":20}`+\"\\n\" +\n\t\t`4c08d91f 0000000000000002 0000000000000001 cmd_2 {\"x\":100}`+\"\\n\" +\n\t\t`6ac5807c 0000000000000003 0000000000000002 cmd_1 {\"val\":\"bar\",\"i\":0}`+\"\\n\"\n\tactual, _ = ioutil.ReadFile(path)\n\tif string(actual) != expected {\n\t\tt.Fatalf(\"Unexpected buffer:\\nexp:\\n%s\\ngot:\\n%s\", expected, string(actual))\n\t}\n}",
"func (s *sliding) memWrite(bufs []Update) {\n\t// pos is only for debugging\n\tvar pos = s.end()\n\tfor _, buf := range bufs {\n\t\t// remember most recent position for Blkno\n\t\toldpos, ok := s.posForAddr(buf.Addr)\n\t\tif ok && oldpos >= s.mutable {\n\t\t\tutil.DPrintf(5, \"memWrite: absorb %d pos %d old %d\\n\",\n\t\t\t\tbuf.Addr, pos, oldpos)\n\t\t\ts.update(oldpos, buf)\n\t\t} else {\n\t\t\tif ok {\n\t\t\t\tutil.DPrintf(5, \"memLogMap: replace %d pos %d old %d\\n\",\n\t\t\t\t\tbuf.Addr, pos, oldpos)\n\t\t\t} else {\n\t\t\t\tutil.DPrintf(5, \"memLogMap: add %d pos %d\\n\",\n\t\t\t\t\tbuf.Addr, pos)\n\t\t\t}\n\t\t\ts.append(buf)\n\t\t\tpos += 1\n\t\t}\n\t}\n}",
"func (s *dbStore) AddCmd(cmd string) (int, error) {\n\tvar (\n\t\tseq uint64\n\t\terr error\n\t)\n\terr = s.db.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(bucketCmd))\n\t\tseq, err = b.NextSequence()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn b.Put(marshalSeq(seq), []byte(cmd))\n\t})\n\treturn int(seq), err\n}",
"func writeIndexChanges(tx *bolt.Tx, changes map[string][]string, op indexOp) error {\n\tfor idxName, indexEntries := range changes {\n\t\tbucket := tx.Bucket([]byte(idxName))\n\t\tfor _, entry := range indexEntries {\n\t\t\tif err := op(bucket, []byte(entry)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}",
"func (client *Client) Write(cmd Command) error {\n\tf := cmd.Display\n\tif !cmd.IsValid(client) {\n\t\tf = cmd.Error\n\t} else {\n\t\tclient.commands[cmd.Name()] += 1\n\t}\n\t_, err := client.writer.Write(f())\n\tif err == nil {\n\t\tclient.writer.Flush()\n\t}\n\treturn err\n}",
"func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tindex := -1\n\tterm := int32(-1)\n\tisLeader := true\n\n\t_, isLeader = rf.GetState()\n\tif !isLeader {\n\t\treturn index, int(term), false\n\t}\n\n\t// TODO: take concurrent out-of-order commit to account\n\trf.stateLock.Lock()\n\tpreLogIndex := int32(0)\n\tpreLogTerm := int32(0)\n\tif len(rf.log) > 1 {\n\t\tpreLogIndex = int32(len(rf.log) - 1)\n\t\tpreLogTerm = rf.log[preLogIndex].Term\n\t}\n\tterm = rf.currentTerm\n\tnewEntry := LogEntry{\n\t\tCommand: command,\n\t\tTerm: term,\n\t}\n\trf.log = append(rf.log, newEntry)\n\t//rf.persist()\n\trf.matchIndex[rf.me] = int32(len(rf.log) - 1)\n\tDPrintf(\"[me : %v]start command: %v at index: %v\", rf.me, command, int32(len(rf.log) - 1))\n\tentries := []LogEntry{newEntry}\n\tappendReq := AppendEntriesRequest{\n\t\tTerm: rf.currentTerm,\n\t\tLeaderId: rf.me,\n\t\tPrevLogIndex: preLogIndex, // change\n\t\tPrevLogTerm: preLogTerm, // change\n\t\tEntries: entries,\n\t\tLeaderCommit: rf.commitIndex,\n\t}\n\trf.stateLock.Unlock()\n\n\tquorumAck := rf.quorumSendAppendEntries(appendReq)\n\tif !quorumAck {\n\t\treturn int(preLogIndex) + 1, int(term), true\n\t}\n\n\t// Your code here (2B).\n\treturn int(preLogIndex) + 1, int(term), isLeader\n}",
"func (eve *EVE) WriteCmd(offset, cmd int) int {\n\tif eve.Err != nil {\n\t\treturn 0\n\t}\n\treturn (offset + eve.Write32(RAM_CMD+offset, cmd)) & 4095\n}",
"func (p *progress) update(nodeIndex NodeIndex, index LogEntryIndex) {\n\tp.NextIndex[nodeIndex] = index + 1\n\tp.MatchIndex[nodeIndex] = index\n}",
"func (c *compiler) pushIndex(pos ast.Pos, opcode byte, idx int) int {\n\thigh, low := index(idx)\n\treturn c.push(pos, opcode, high, low)\n}",
"func (l *Log) LastCommandIndex() (uint64, error) {\n\tfi, li, err := l.Indexes()\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"get indexes: %s\", err)\n\t}\n\n\t// Check for empty log.\n\tif li == 0 {\n\t\treturn 0, nil\n\t}\n\n\tvar rl raft.Log\n\tfor i := li; i >= fi; i-- {\n\t\tif err := l.GetLog(i, &rl); err != nil {\n\t\t\treturn 0, fmt.Errorf(\"get log at index %d: %s\", i, err)\n\t\t}\n\t\tif rl.Type == raft.LogCommand {\n\t\t\treturn i, nil\n\t\t}\n\t}\n\treturn 0, nil\n}",
"func (r *RaftNode) executeLog() {\n\tfor r.commitIndex > r.lastApplied {\n\t\tr.lastApplied++\n\t\tr.StateMachine.apply(r.Log[r.lastApplied])\n\t}\n}",
"func (m *multiNode) Commit(index int64) {\n\tm.committed[index&m.mask] = int32(index >> m.shift)\n}",
"func (kv *ShardKV) addToLog(op Op) int {\n\tdone := false\n\tdecidedSeq := -1\n\tfor !done {\n\t\tseq := kv.px.Max() + 1\n\t\tkv.px.Start(seq, op)\n\n\t\tto := 10 * time.Millisecond\n\t\tfor {\n\t\t\tdecided, decidedOp := kv.px.Status(seq)\n\t\t\tif decided {\n\t\t\t\tif decidedOp.(Op).Id == op.Id {\n\t\t\t\t\tdone = true\n\t\t\t\t\tdecidedSeq = seq\n\t\t\t\t}\n\t\t\t\tkv.log[seq] = decidedOp.(Op)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(to)\n\t\t\tif to < 10 * time.Second {\n\t\t\t\tto *= 2\n\t\t\t}\n\t\t}\n\t}\n\treturn decidedSeq\n}",
"func indexWrite(key string, p *pkg) {\n\tlocker.Lock()\n\tdefer locker.Unlock()\n\n\tindexedPkgs[key] = p\n}",
"func (rw *ReadWrite) PutCmd(cmd commands.Command) *ReadWrite {\n\ttrace.ClientServer.Println(\">\", cmd)\n\trw.w.WriteByte(byte(cmd))\n\treturn rw\n}",
"func (r *RaftNode) updateCommitIndex() {\n\t// If there exists an N such that:\n\t// 1) N > commitIndex,\n\t// 2) a majority of matchIndex[i] >= N, and\n\t// 3) log[N].term == currentTerm\n\t// Then:\n\t// set commitIndex = N\n\tfor n := r.commitIndex + 1; n <= r.getLastLogIndex(); n++ {\n\t\tif r.Log[n].Term != r.CurrentTerm {\n\t\t\tif r.verbose {\n\t\t\t\tlog.Printf(\"commitIndex %d ineligible because of log entry %s\", n, r.Log[n].String())\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tpeersAtThisLevel := make(map[HostID]bool)\n\t\tfor hostID := range r.hosts {\n\t\t\tif hostID == r.id {\n\t\t\t\tpeersAtThisLevel[hostID] = true\n\t\t\t} else {\n\t\t\t\tpeersAtThisLevel[hostID] = r.matchIndex[hostID] >= n\n\t\t\t}\n\t\t}\n\t\tif haveMajority(peersAtThisLevel, \"COMMIT IDX\", r.verbose) {\n\t\t\tr.commitIndex = n\n\t\t}\n\t}\n}",
"func (sh *Shell) setTokenIndex(log *logrus.Entry, timeout time.Duration) (err error) {\n\n\tlog.Debugf(\"Setting token index for shell session output buffer control\")\n\n\t// Need two tokens to test, and two commands\n\ttoken, numericToken := randStringBytesRmndr(), rand.Int63()\n\ttestCmd := fmt.Sprintf(\"echo %d\", numericToken)\n\tcmd := fmt.Sprintf(testCmd+\";echo %s\\n\", token)\n\n\t// Send package\n\terr = sh.write([]byte(cmd), timeout)\n\tif err != nil {\n\t\tsh.Log.Error(err)\n\t\treturn\n\t}\n\n\t// Do the process in a goroutine and time it.\n\tdone := make(chan struct{})\n\tgo func(<-chan struct{}) {\n\t\tdefer close(done)\n\t\tselect {\n\t\tdefault:\n\t\t\t// Read all output until one/both tokens are found\n\t\t\toutput, err := sh.readCommandOuput(cmd, token, 0)\n\t\t\tif err != nil {\n\t\t\t\tsh.Log.Errorf(\"error when setting ouput token: %s\", err.Error())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\titems := strings.Split(output, \"\\n\") // Get all lines separately\n\t\t\tvar tokenLine string // check for the prompt line first\n\n\t\t\t// Edge case: the first string is the prompt, so we loop again\n\t\t\tif strings.TrimSpace(items[0]) == sh.prompt {\n\t\t\t\ttokenLine = items[1]\n\t\t\t} else {\n\t\t\t\ttokenLine = items[0]\n\t\t\t}\n\n\t\t\t// Depending on the outcome, we read 1/2 line on the conn, for clearing.\n\t\t\t_, _, err = sh.reader.ReadLine() // One is in common\n\t\t\tif err != nil {\n\t\t\t\tlog.Warnf(\"could not clear extra lines from conn after token setup\")\n\t\t\t}\n\n\t\t\tnb, err := strconv.Atoi(tokenLine)\n\t\t\tif nb == 0 && err != nil {\n\t\t\t\tsh.tokenIndex = 1\n\t\t\t\t_, _, err = sh.reader.ReadLine() // One is because we indeed have an echo\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warnf(\"could not clear extra lines from conn after token setup\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsh.tokenIndex = 0\n\t\t\t}\n\t\t\tsh.tokenSet = true\n\t\t\tsh.pendingToken = false // double check\n\t\tcase <-done:\n\t\t\treturn\n\t\t}\n\t}(done)\n\n\tselect {\n\tcase <-done:\n\t\tlog.Debugf(\"test output token done: tokenIndex = %d\", sh.tokenIndex)\n\t\treturn\n\tcase <-time.After(timeout):\n\t\tclose(done)\n\t\treturn fmt.Errorf(\"reading command result from conn stream timed out\")\n\t}\n}",
"func (c *testChain) recordPos(ident string, pos scanner.Position) {\n\tn := c.Nodes[ident]\n\tif n == nil {\n\t\tn = &testchainNode{Name: ident}\n\t}\n\n\tn.Uses = append(n.Uses, pos)\n\tc.Nodes[ident] = n\n}",
"func (kv *ShardKV) applyFromLog(decidedSeq int) Err {\n\tcurrent := kv.highestDone + 1\n\tvar err Err = OK\n\n\tfor current <= decidedSeq {\n\t\top, ok := kv.log[current]\n\t\tif !ok {\n\t\t\t//_, iok := kv.log[current]\n\t\t\t//log.Panicf(\"MISSING ENTRY after catchUp gid: %v me: %v current: %v iok: %v!!!!!\\n\", kv.gid, kv.me, current, iok)\n\t\t}\n\t\tif ok {\n\t\t\tif op.RequestType != NoOp {\n\t\t\t\tif op.RequestType == Get || op.RequestType == Put {\n\t\t\t\t\t// Make sure this is the correct group\n\t\t\t\t\tif (kv.currentConfig.Num != op.ClientConfigNum) || (kv.currentConfig.Shards[op.Shard] != kv.gid) {\n\t\t\t\t\t\terr = ErrWrongGroup\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Check for duplicate client request\n\t\t\t\t\t\tduplicate := false\n\t\t\t\t\t\t//highestLogged, ok := shardData.HighestReqIdLogged[op.ClientUuid]\n\t\t\t\t\t\t//if !ok || (ok && op.ReqId > highestLogged) {\n\t\t\t\t\t\t//\tlog.Printf(\"NOT Dup!! gid: %v me: %v key: %v shard: %v cur: %v oprid: %v type: %v cu: %v\\n\",\n\t\t\t\t\t\t//\t\tkv.gid, kv.me, op.Key, op.Shard, current, op.ReqId, op.RequestType, op.ClientUuid)\n\t\t\t\t\t\t//\tshardData.HighestReqIdLogged[op.ClientUuid] = op.ReqId\n\t\t\t\t\t\t//} else {\n\t\t\t\t\t\t//\tlog.Printf(\"Dup!! gid: %v me: %v key: %v shard: %v cur: %v oprid: %v highlog: %v cu: %v\\n\",\n\t\t\t\t\t\t//\t\tkv.gid, kv.me, op.Key, op.Shard, current, op.ReqId, highestLogged, op.ClientUuid)\n\t\t\t\t\t\t//\tduplicate = true\n\t\t\t\t\t\t//\terr = ErrDuplicate\n\t\t\t\t\t\t//}\n\t\t\t\t\t\t_, ok := kv.shardData[op.Shard].StoredReplies[op.ClientUuid]\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\tkv.shardData[op.Shard].StoredReplies[op.ClientUuid] = make(map[uint64]CachedReply)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t_, ok = kv.shardData[op.Shard].StoredReplies[op.ClientUuid][op.ReqId]\n\t\t\t\t\t\tif ok {\n\t\t\t\t\t\t\t//log.Printf(\"Dup!! gid: %v me: %v key: %v shard: %v cur: %v oprid: %v cu: %v\\n\",\n\t\t\t\t\t\t\t//\tkv.gid, kv.me, op.Key, op.Shard, current, op.ReqId, op.ClientUuid)\n\t\t\t\t\t\t\tduplicate = true\n\t\t\t\t\t\t\terr = ErrDuplicate\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif op.RequestType == Get {\n\t\t\t\t\t\t\t// Cache reply\n\t\t\t\t\t\t\t//_, ok = shardData.CachedReplies[op.ClientUuid]\n\t\t\t\t\t\t\t//if !ok {\n\t\t\t\t\t\t\t//\tkv.shardData[op.Shard].CachedReplies[op.ClientUuid] = make(map[string]CachedReply)\n\t\t\t\t\t\t\t//}\n\n\t\t\t\t\t\t\t//cachedReply, ok := shardData.CachedReplies[op.ClientUuid][op.Key]\n\t\t\t\t\t\t\t_, ok := kv.shardData[op.Shard].StoredReplies[op.ClientUuid][op.ReqId]\n\t\t\t\t\t\t\tif !ok { //|| (ok && op.ReqId > cachedReply.ReqId) {\n\t\t\t\t\t\t\t\tnewReply := CachedReply{}\n\t\t\t\t\t\t\t\tnewReply.ReqId = op.ReqId\n\t\t\t\t\t\t\t\tif value, ok := kv.shardData[op.Shard].Data[op.Key]; ok {\n\t\t\t\t\t\t\t\t\tnewReply.Found = true\n\t\t\t\t\t\t\t\t\tnewReply.Value = value\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tnewReply.Found = false\n\t\t\t\t\t\t\t\t\terr = ErrNoKey\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t//kv.shardData[op.Shard].CachedReplies[op.ClientUuid][op.Key] = newReply\n\t\t\t\t\t\t\t\tkv.shardData[op.Shard].StoredReplies[op.ClientUuid][op.ReqId] = newReply\n\t\t\t\t\t\t\t\terr = OK\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if op.RequestType == Put && !duplicate {\n\t\t\t\t\t\t\t//log.Printf(\"PUT executed gid: %v me: %v current: %v shard: %v key: %v val: %v view: %v reqid: %v\\n\",\n\t\t\t\t\t\t\t//\tkv.gid, kv.me, current, op.Shard, op.Key, op.Value, kv.currentConfig.Num, op.ReqId)\n\t\t\t\t\t\t\tnewReply := CachedReply{}\n\t\t\t\t\t\t\tnewReply.ReqId = op.ReqId\n\t\t\t\t\t\t\tkv.shardData[op.Shard].StoredReplies[op.ClientUuid][op.ReqId] = newReply\n\n\t\t\t\t\t\t\tkv.shardData[op.Shard].Data[op.Key] = op.Value\n\t\t\t\t\t\t\terr = OK\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif op.RequestType == Reconfig {\n\t\t\t\t\t\t//log.Printf(\"gid: %v me: %v RECONF opconfn: %v curr: %v changing: %v\\n\",\n\t\t\t\t\t\t//\tkv.gid, kv.me, op.ConfigNum, kv.currentConfig.Num, kv.changing)\n\t\t\t\t\t\tif op.ConfigNum == (kv.currentConfig.Num + 1) && !kv.changing {\n\t\t\t\t\t\t\tkv.changing = true\n\t\t\t\t\t\t\tnextConfig := kv.sm.Query(op.ConfigNum)\n\n\t\t\t\t\t\t\t// Can't serve unreceived shards yet\n\t\t\t\t\t\t\tdone := true\n\t\t\t\t\t\t\tif nextConfig.Num > 1 {\n\t\t\t\t\t\t\t\tfor i := 0; i < shardmaster.NShards; i++ {\n\t\t\t\t\t\t\t\t\tif nextConfig.Shards[i] == kv.gid && kv.currentConfig.Shards[i] != kv.gid {\n\t\t\t\t\t\t\t\t\t\tdone = false\n\t\t\t\t\t\t\t\t\t\tnextConfig.Shards[i] = -1\n\t\t\t\t\t\t\t\t\t} else if nextConfig.Shards[i] != kv.gid && kv.currentConfig.Shards[i] == kv.gid {\n\t\t\t\t\t\t\t\t\t\tcopiedShardData := copyShardData(*kv.shardData[i])\n\t\t\t\t\t\t\t\t\t\tnewOwners := make([]string, len(nextConfig.Groups[nextConfig.Shards[i]]))\n\t\t\t\t\t\t\t\t\t\tcopy(newOwners, nextConfig.Groups[nextConfig.Shards[i]])\n\t\t\t\t\t\t\t\t\t\tgo func(shard int, nextNum int, newO []string, copiedShardData ShardData) {\n\t\t\t\t\t\t\t\t\t\t\tkv.pushShard(shard, nextNum, newO, copiedShardData)\n\t\t\t\t\t\t\t\t\t\t}(i, nextConfig.Num, newOwners, copiedShardData)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif done {\n\t\t\t\t\t\t\t\tkv.changing = false\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tkv.currentConfig = nextConfig\n\t\t\t\t\t\t\t//log.Printf(\"gid: %v me: %v NEW CONFIG: %v changing: %v\\n\", kv.gid, kv.me, kv.currentConfig.Num, kv.changing)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if op.RequestType == ReceivedShard {\n\t\t\t\t\t\t//log.Printf(\"processing receivedshard gid: %v me: %v shard: %v op.conf: %v currnum: %v changin: %v shards: %v data: %v\\n\",\n\t\t\t\t\t\t//\tkv.gid, kv.me, op.Shard, op.ConfigNum, kv.currentConfig.Num, kv.changing, kv.currentConfig.Shards, op.ShardData.Data)\n\n\t\t\t\t\t\tif op.ConfigNum < kv.currentConfig.Num {\n\t\t\t\t\t\t\terr = ErrStopSending\n\t\t\t\t\t\t} else if op.ConfigNum > kv.currentConfig.Num {\n\t\t\t\t\t\t\terr = ErrFutureConfig\n\t\t\t\t\t\t} else if !kv.changing { // Must have same config num as current\n\t\t\t\t\t\t\terr = ErrStopSending\n\t\t\t\t\t\t} else if kv.currentConfig.Shards[op.Shard] == -1 {\n\t\t\t\t\t\t\t//log.Printf(\"using receivedshard gid: %v me: %v shard: %v op.conf: %v currnum: %v changin: %v shards: %v data: %v\\n\",\n\t\t\t\t\t\t\t//\tkv.gid, kv.me, op.Shard, op.ConfigNum, kv.currentConfig.Num, kv.changing, kv.currentConfig.Shards, op.ShardData.Data)\n\t\t\t\t\t\t\tcopiedData := copyShardData(op.ShardData)\n\t\t\t\t\t\t\tnewShardData := &ShardData{}\n\t\t\t\t\t\t\tnewShardData.Data = copiedData.Data\n\t\t\t\t\t\t\tnewShardData.CachedReplies = copiedData.CachedReplies\n\t\t\t\t\t\t\tnewShardData.StoredReplies = copiedData.StoredReplies\n\t\t\t\t\t\t\tnewShardData.HighestReqIdLogged = copiedData.HighestReqIdLogged\n\t\t\t\t\t\t\tkv.shardData[op.Shard] = newShardData\n\n\t\t\t\t\t\t\t// Begin serving\n\t\t\t\t\t\t\tkv.currentConfig.Shards[op.Shard] = kv.gid\n\n\t\t\t\t\t\t\tdone := true\n\t\t\t\t\t\t\tfor i := 0; i < shardmaster.NShards; i++ {\n\t\t\t\t\t\t\t\tif kv.currentConfig.Shards[i] == -1 {\n\t\t\t\t\t\t\t\t\tdone = false\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif done {\n\t\t\t\t\t\t\t\tkv.changing = false\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tdelete(kv.log, current)\n\t\t}\n\t\tcurrent++\n\t}\n\n\tkv.px.Done(decidedSeq)\n\tkv.highestDone = decidedSeq\n\treturn err\n}",
"func CommandLog(conf Config, ctx, query Query) error {\n\tif query.Text == \"\" {\n\t\treturn errors.New(\"Task description required\")\n\t}\n\n\tts, err := LoadTaskSet(conf.Repo, conf.IDsFile, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx.PrintContextDescription()\n\tquery = query.Merge(ctx)\n\ttask := Task{\n\t\tWritePending: true,\n\t\tStatus: STATUS_RESOLVED,\n\t\tSummary: query.Text,\n\t\tTags: query.Tags,\n\t\tProject: query.Project,\n\t\tPriority: query.Priority,\n\t\tResolved: time.Now(),\n\t}\n\ttask = ts.MustLoadTask(task)\n\tts.SavePendingChanges()\n\tMustGitCommit(conf.Repo, \"Logged %s\", task)\n\n\treturn nil\n}",
"func (mb *MetricsBuilder) RecordRedisCommandsDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricRedisCommands.recordDataPoint(mb.startTime, ts, val)\n}",
"func (r *Range) ReadWriteCmd(method string, args, reply interface{}) <-chan error {\n\tif r == nil {\n\t\tc := make(chan error, 1)\n\t\tc <- util.Errorf(\"invalid node specification\")\n\t\treturn c\n\t}\n\n\tlogEntry := &LogEntry{\n\t\tMethod: method,\n\t\tArgs: args,\n\t\tReply: reply,\n\t\tdone: make(chan error, 1),\n\t}\n\tr.pending <- logEntry\n\n\treturn logEntry.done\n}",
"func (c *rawConnection) Index(repo string, idx []FileInfo) {\n\tc.imut.Lock()\n\tvar msgType int\n\tif c.indexSent[repo] == nil {\n\t\t// This is the first time we send an index.\n\t\tmsgType = messageTypeIndex\n\n\t\tc.indexSent[repo] = make(map[string][2]int64)\n\t\tfor _, f := range idx {\n\t\t\tc.indexSent[repo][f.Name] = [2]int64{f.Modified, int64(f.Version)}\n\t\t}\n\t} else {\n\t\t// We have sent one full index. Only send updates now.\n\t\tmsgType = messageTypeIndexUpdate\n\t\tvar diff []FileInfo\n\t\tfor _, f := range idx {\n\t\t\tif vs, ok := c.indexSent[repo][f.Name]; !ok || f.Modified != vs[0] || int64(f.Version) != vs[1] {\n\t\t\t\tdiff = append(diff, f)\n\t\t\t\tc.indexSent[repo][f.Name] = [2]int64{f.Modified, int64(f.Version)}\n\t\t\t}\n\t\t}\n\t\tidx = diff\n\t}\n\tc.imut.Unlock()\n\n\tc.send(header{0, -1, msgType}, IndexMessage{repo, idx})\n}",
"func (node *Node) Submit(command interface{}) bool {\n\tnode.mu.Lock()\n\tdefer node.mu.Unlock()\n\n\tif node.state == leader {\n\t\tlogEntry := LogEntry{\n\t\t\tterm: node.currentTerm,\n\t\t\tCommand: command,\n\t\t}\n\t\tnode.log = append(node.log, logEntry)\n\t\tlog.Printf(\"Leader %d has receieved a command %+v\", node.id, logEntry)\n\t\treturn true\n\t}\n\treturn false\n}",
"func (r *Raft) AppendToLog_Follower(request AppendEntriesReq) {\n\tterm := request.term\n\tcmd := request.entries\n\tindex := request.prevLogIndex + 1\n\tlogVal := LogVal{term, cmd, 0} //make object for log's value field\n\n\tif len(r.myLog) == index {\n\t\tr.myLog = append(r.myLog, logVal) //when trying to add a new entry\n\t} else {\n\t\tr.myLog[index] = logVal //overwriting in case of log repair\n\t\t//fmt.Println(\"Overwiriting!!\")\n\t}\n\t//fmt.Println(r.myId(), \"Append to log\", string(cmd))\n\t//modify metadata after appending\n\t//r.myMetaData.lastLogIndex = r.myMetaData.lastLogIndex + 1\n\t//r.myMetaData.prevLogIndex = r.myMetaData.lastLogIndex\n\t//\tif len(r.myLog) == 1 {\n\t//\t\tr.myMetaData.prevLogTerm = r.myMetaData.prevLogTerm + 1\n\t//\t} else if len(r.myLog) > 1 {\n\t//\t\tr.myMetaData.prevLogTerm = r.myLog[r.myMetaData.prevLogIndex].Term\n\t//\t}\n\n\t//Changed on 4th april, above is wrong in case of overwriting of log\n\tr.myMetaData.lastLogIndex = index\n\tr.myMetaData.prevLogIndex = index - 1\n\tif index == 0 {\n\t\tr.myMetaData.prevLogTerm = r.myMetaData.prevLogTerm + 1 //or simple -1\n\t} else if index >= 1 {\n\t\tr.myMetaData.prevLogTerm = r.myLog[index-1].Term\n\t}\n\n\t//Update commit index\n\tleaderCI := float64(request.leaderCommitIndex)\n\tmyLI := float64(r.myMetaData.lastLogIndex)\n\tif request.leaderCommitIndex > r.myMetaData.commitIndex {\n\t\tif myLI == -1 { //REDUNDANT since Append to log will make sure it is never -1,also must not copy higher CI if self LI is -1\n\t\t\tr.myMetaData.commitIndex = int(leaderCI)\n\t\t} else {\n\t\t\tr.myMetaData.commitIndex = int(math.Min(leaderCI, myLI))\n\t\t}\n\t}\n\t//fmt.Println(r.myId(), \"My CI is:\", r.myMetaData.commitIndex)\n\tr.WriteLogToDisk()\n}",
"func (cfg *config) checkCommitted(index int, command interface{}) {\n\tfor i := 0; i < len(cfg.logs); i++ {\n\t\te, ok := cfg.logs[i][index]\n\t\tif ok {\n\t\t\tif !e.valid {\n\t\t\t\tlog.Fatalf(\"snapshot with index %d has value %v but server %d stores a dummy \"+\n\t\t\t\t\t\"entry for this index (snapshots are only created for indices with valid \"+\n\t\t\t\t\t\"commands)\", index, command, i)\n\t\t\t}\n\t\t\tif e.command != command {\n\t\t\t\tlog.Fatalf(\"snapshot with index %d has value %v but server %d stores command %v \"+\n\t\t\t\t\t\"for this index\", index, command, i, e.command)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Fatalf(\"no log entry has been found for snapshot index %d\", index)\n}",
"func (rf *Raft) Start(command interface{}) (int, int, bool) {\n index := -1\n term := -1\n isLeader := true\n\n rf.mu.Lock()\n isLeader = rf.state == \"Leader\"\n if isLeader {\n newEntry := Entry{}\n newEntry.Command = command\n newEntry.Term = rf.currentTerm\n\n index = rf.convertToGlobalViewIndex(len(rf.log))\n term = rf.currentTerm\n rf.log = append(rf.log, newEntry)\n\n rf.persist()\n //go rf.startAppendEntries()\n\n DLCPrintf(\"Leader (%d) append entries and now log is from %v to %v(index=%d in Raft Log view)\", rf.me, rf.log[1], rf.log[len(rf.log)-1], len(rf.log)-1)\n }\n rf.mu.Unlock()\n\n return index, term, isLeader\n}",
"func runIndex() {\n\n\t// check index flag is set (global flag but don't require it for all sub commands)\n\tif *indexDir == \"\" {\n\t\tfmt.Println(\"please specify a directory for the index files (--indexDir)\")\n\t\tos.Exit(1)\n\t}\n\n\t// set up profiling\n\tif *profiling == true {\n\t\tdefer profile.Start(profile.MemProfile, profile.ProfilePath(\"./\")).Stop()\n\t\t//defer profile.Start(profile.ProfilePath(\"./\")).Stop()\n\t}\n\n\t// start logging\n\tif *logFile != \"\" {\n\t\tlogFH := misc.StartLogging(*logFile)\n\t\tdefer logFH.Close()\n\t\tlog.SetOutput(logFH)\n\t} else {\n\t\tlog.SetOutput(os.Stdout)\n\t}\n\n\t// start the index sub command\n\tstart := time.Now()\n\tlog.Printf(\"i am groot (version %s)\", version.GetVersion())\n\tlog.Printf(\"starting the index subcommand\")\n\n\t// check the supplied files and then log some stuff\n\tlog.Printf(\"checking parameters...\")\n\tmisc.ErrorCheck(indexParamCheck())\n\tlog.Printf(\"\\tprocessors: %d\", *proc)\n\tlog.Printf(\"\\tk-mer size: %d\", *kmerSize)\n\tlog.Printf(\"\\tsketch size: %d\", *sketchSize)\n\tlog.Printf(\"\\tgraph window size: %d\", *windowSize)\n\tlog.Printf(\"\\tnum. partitions: %d\", *numPart)\n\tlog.Printf(\"\\tmax. K: %d\", *maxK)\n\tlog.Printf(\"\\tmax. sketch span: %d\", *maxSketchSpan)\n\n\t// record the runtime information for the index sub command\n\tinfo := &pipeline.Info{\n\t\tVersion: version.GetVersion(),\n\t\tKmerSize: *kmerSize,\n\t\tSketchSize: *sketchSize,\n\t\tWindowSize: *windowSize,\n\t\tNumPart: *numPart,\n\t\tMaxK: *maxK,\n\t\tMaxSketchSpan: *maxSketchSpan,\n\t\tIndexDir: *indexDir,\n\t}\n\n\t// create the pipeline\n\tlog.Printf(\"initialising indexing pipeline...\")\n\tindexingPipeline := pipeline.NewPipeline()\n\n\t// initialise processes\n\tlog.Printf(\"\\tinitialising the processes\")\n\tmsaConverter := pipeline.NewMSAconverter(info)\n\tgraphSketcher := pipeline.NewGraphSketcher(info)\n\tsketchIndexer := pipeline.NewSketchIndexer(info)\n\n\t// connect the pipeline processes\n\tlog.Printf(\"\\tconnecting data streams\")\n\tmsaConverter.Connect(msaList)\n\tgraphSketcher.Connect(msaConverter)\n\tsketchIndexer.Connect(graphSketcher)\n\n\t// submit each process to the pipeline and run it\n\tindexingPipeline.AddProcesses(msaConverter, graphSketcher, sketchIndexer)\n\tlog.Printf(\"\\tnumber of processes added to the indexing pipeline: %d\\n\", indexingPipeline.GetNumProcesses())\n\tlog.Print(\"creating graphs, sketching traversals and indexing...\")\n\tindexingPipeline.Run()\n\tlog.Printf(\"writing index files in \\\"%v\\\"...\", *indexDir)\n\tmisc.ErrorCheck(info.SaveDB(*indexDir + \"/groot.lshe\"))\n\tmisc.ErrorCheck(info.Dump(*indexDir + \"/groot.gg\"))\n\tlog.Printf(\"finished in %s\", time.Since(start))\n}",
"func logCommands(r cruntime.Manager, bs bootstrapper.Bootstrapper, cfg config.ClusterConfig, length int, follow bool) map[string]string {\n\tcmds := bs.LogCommands(cfg, bootstrapper.LogOptions{Lines: length, Follow: follow})\n\tpods := importantPods\n\taddonPods := enabledAddonPods(cfg)\n\tpods = append(pods, addonPods...)\n\tfor _, pod := range pods {\n\t\tids, err := r.ListContainers(cruntime.ListContainersOptions{Name: pod})\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to list containers for %q: %v\", pod, err)\n\t\t\tcontinue\n\t\t}\n\t\tklog.Infof(\"%d containers: %s\", len(ids), ids)\n\t\tif len(ids) == 0 {\n\t\t\tklog.Warningf(\"No container was found matching %q\", pod)\n\t\t\tcontinue\n\t\t}\n\t\tfor _, i := range ids {\n\t\t\tkey := fmt.Sprintf(\"%s [%s]\", pod, i)\n\t\t\tcmds[key] = r.ContainerLogCmd(i, length, follow)\n\t\t}\n\t}\n\tcmds[r.Name()] = r.SystemLogCmd(length)\n\tcmds[\"container status\"] = cruntime.ContainerStatusCommand()\n\n\treturn cmds\n}",
"func WriteMsg(ctx context.Context, crawlabIndex string, es *elastic.Client, when time.Time, msg string) error {\n\tvals := make(map[string]interface{})\n\tvals[\"@timestamp\"] = when.Format(time.RFC3339)\n\tvals[\"@msg\"] = msg\n\tuid := uuid.NewV4().String()\n\t_, err := es.Index().Index(crawlabIndex).Id(uid).BodyJson(vals).Refresh(\"wait_for\").Do(ctx)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\treturn err\n}",
"func (r *Raft) AppendToLog_Leader(cmd []byte) {\n\tTerm := r.myCV.CurrentTerm\n\tlogVal := LogVal{Term, cmd, 0} //make object for log's value field with acks set to 0\n\tr.MyLog = append(r.MyLog, logVal)\n\t//modify metaData after appending\n\tLastLogIndex := r.MyMetaData.LastLogIndex + 1\n\tr.MyMetaData.PrevLogIndex = r.MyMetaData.LastLogIndex\n\tr.MyMetaData.LastLogIndex = LastLogIndex\n\tif len(r.MyLog) == 1 {\n\t\tr.MyMetaData.PrevLogTerm = r.MyMetaData.PrevLogTerm + 1 //as for empty log PrevLogTerm is -2\n\n\t} else if len(r.MyLog) > 1 { //explicit check, else would have sufficed too, just to eliminate len=0 possibility\n\t\tr.MyMetaData.PrevLogTerm = r.MyLog[r.MyMetaData.PrevLogIndex].Term\n\t}\n\tr.setNextIndex_All() //Added-28 march for LogRepair\n\tr.WriteLogToDisk()\n\n}",
"func (kv *ShardKV) tick() {\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\n\t//log.Printf(\"TICK gid: %v me: %v changing: %v current: %v shards: %v\\n\", kv.gid, kv.me, kv.changing, kv.currentConfig.Num, kv.currentConfig.Shards)\n\tif !kv.changing {\n\t\tlatestConfig := kv.sm.Query(-1)\n\t\tif latestConfig.Num > kv.currentConfig.Num {\n\t\t\tnewOp := Op{}\n\t\t\tnewOp.RequestType = Reconfig\n\t\t\tnewOp.ConfigNum = kv.currentConfig.Num + 1\n\t\t\tnewOp.Id = generateUUID()\n\n\t\t\tdecidedSeq := kv.addToLog(newOp)\n\t\t\tkv.catchUp(decidedSeq)\n\t\t\tkv.applyFromLog(decidedSeq)\n\t\t}\n\t} else {\n\t\t\tnewOp := Op{}\n\t\t\tnewOp.RequestType = NoOp\n\t\t\tnewOp.Id = generateUUID()\n\t\t\tdecidedSeq := kv.addToLog(newOp)\n\t\t\tkv.catchUp(decidedSeq)\n\t\t\tkv.applyFromLog(decidedSeq)\n\t\t//max := kv.px.Max() - 1\n\t\t//if max > -1 {\n\t\t//\tkv.catchUp(max)\n\t\t//\tkv.applyFromLog(max)\n\t\t//}\n\t}\n}",
"func (s *Server) handleGetBlockByIndexCmd(p Peer, gbd *payload.GetBlockByIndex) error {\n\tcount := gbd.Count\n\tif gbd.Count < 0 || gbd.Count > payload.MaxHashesCount {\n\t\tcount = payload.MaxHashesCount\n\t}\n\tfor i := gbd.IndexStart; i < gbd.IndexStart+uint32(count); i++ {\n\t\thash := s.chain.GetHeaderHash(int(i))\n\t\tif hash.Equals(util.Uint256{}) {\n\t\t\tbreak\n\t\t}\n\t\tb, err := s.chain.GetBlock(hash)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tmsg := NewMessage(CMDBlock, b)\n\t\tif err = p.EnqueueP2PMessage(msg); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}",
"func writeCmd() {\n\twc, err := genWriteConfig()\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"bad write configuration: %v\", err)\n\t\treturn\n\t}\n\tevents, err := wc.generateEvents()\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"cannot generate events: %v\", err)\n\t\treturn\n\t}\n\tvestingData := wc.convertRelative(events)\n\tbz, err := marshalVestingData(vestingData)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"cannot marshal vesting data: %v\", err)\n\t\treturn\n\t}\n\tfmt.Println(string(bz))\n}",
"func (rf *Raft) writeApplyCh() {// {{{\n for {\n <-rf.cmtChan \n rf.mu.Lock()\n for i := rf.applyIdx + 1; i <= rf.cmtIdx; i++ {\n var newApplyMsg ApplyMsg\n newApplyMsg.Index = i \n newApplyMsg.Command = rf.log[i].Cmd\n rf.applyChan<- newApplyMsg \n rf.applyIdx = i \n rf.debug(\"Applied committed msg: cmtIdx=%v, applyIdx=%v\\n\", rf.cmtIdx, rf.applyIdx)\n }\n rf.mu.Unlock()\n }\n}",
"func (rf *Raft) Start(command interface{}) (int, int, bool) {\n lastLogIndex := 0\n isLeader := true\n \n // TODO WED: check corner cases with -1\n rf.mu.Lock()\n term := rf.currentTerm\n myId := rf.me\n if len(rf.log) > 0 {\n lastLogIndex = len(rf.log)\n //term = rf.log[index].Term \n }\n \n if rf.state != Leader || rf.killed() {\n return lastLogIndex-1, term, false\n }\n \n var oneEntry LogEntry\n oneEntry.Command = command\n oneEntry.Term = term\n \n rf.log = append(rf.log, oneEntry)\n rf.mu.Unlock()\n\n \n go func() {\n \n // Add a while loop. when successReply count greater than threhsold, commit. loop breaks when successReply is equal to peers\n // the for loop inside only iterates over the left peers.\n \n var localMu sync.Mutex\n \n isLeader := true\n committed := false\n successReplyCount := 0\n var receivedResponse []int\n receivedResponse = append(receivedResponse, myId)\n\n for isLeader {\n if rf.killed() {\n fmt.Printf(\"*** Peer %d term %d: Terminated. Closing all outstanding Append Entries calls to followers.\",myId, term)\n return \n }\n\n var args = AppendEntriesArgs {\n LeaderId: myId,\n }\n rf.mu.Lock()\n numPeers := len(rf.peers)\n rf.mu.Unlock()\n\n for id := 0; id < numPeers && isLeader; id++ {\n if (!find(receivedResponse,id)) {\n if lastLogIndex < rf.nextIndex[id] {\n successReplyCount++\n receivedResponse = append(receivedResponse,id)\n continue\n }\n var logEntries []LogEntry\n logEntries = append(logEntries,rf.log[(rf.nextIndex[id]):]...)\n args.LogEntries = logEntries\n args.PrevLogTerm = rf.log[rf.nextIndex[id]-1].Term\n args.PrevLogIndex = rf.nextIndex[id]-1\n args.LeaderTerm = rf.currentTerm\n args.LeaderCommitIndex = rf.commitIndex\n \n go func(serverId int) {\n var reply AppendEntriesReply\n ok:=rf.sendAppendEntries(serverId, &args, &reply)\n if !rf.CheckTerm(reply.CurrentTerm) {\n localMu.Lock()\n isLeader=false\n localMu.Unlock()\n } else if reply.Success && ok {\n localMu.Lock()\n successReplyCount++\n receivedResponse = append(receivedResponse,serverId)\n localMu.Unlock()\n rf.mu.Lock()\n if lastLogIndex >= rf.nextIndex[id] {\n rf.matchIndex[id]= lastLogIndex\n rf.nextIndex[id] = lastLogIndex + 1\n }\n rf.mu.Unlock()\n } else {\n rf.mu.Lock()\n rf.nextIndex[id]-- \n rf.mu.Unlock()\n }\n } (id)\n }\n }\n \n fmt.Printf(\"\\nsleeping before counting success replies\\n\")\n time.Sleep(time.Duration(RANDOM_TIMER_MIN*time.Millisecond))\n\n if !committed && isLeader {\n votesForIndex := 0\n N := math.MaxInt32\n rf.mu.Lock()\n for i := 0; i < numPeers; i++ {\n if rf.matchIndex[i] > rf.commitIndex {\n if rf.matchIndex[i] < N {\n N = rf.matchIndex[i]\n }\n votesForIndex++\n }\n }\n rf.mu.Unlock()\n\n\n if (votesForIndex > (numPeers/2)){ \n go func(){\n committed = true\n rf.mu.Lock()\n rf.commitIndex = N // Discuss: 3. should we use lock?\n rf.log[N].Term = rf.currentTerm\n if rf.commitIndex >= lastLogIndex {\n var oneApplyMsg ApplyMsg\n oneApplyMsg.CommandValid = true\n oneApplyMsg.CommandIndex = lastLogIndex\n oneApplyMsg.Command = command\n go func() {rf.applyCh <- oneApplyMsg} ()\n }\n rf.mu.Unlock()\n }()\n }\n } else if successReplyCount == numPeers {\n return\n } \n }\n } ()\n \n // Your code here (2B code).\n return lastLogIndex, term, isLeader\n}",
"func (c *Connection) Index(idx []FileInfo) {\n\tc.Lock()\n\tvar msgType int\n\tif c.indexSent == nil {\n\t\t// This is the first time we send an index.\n\t\tmsgType = messageTypeIndex\n\n\t\tc.indexSent = make(map[string]int64)\n\t\tfor _, f := range idx {\n\t\t\tc.indexSent[f.Name] = f.Modified\n\t\t}\n\t} else {\n\t\t// We have sent one full index. Only send updates now.\n\t\tmsgType = messageTypeIndexUpdate\n\t\tvar diff []FileInfo\n\t\tfor _, f := range idx {\n\t\t\tif modified, ok := c.indexSent[f.Name]; !ok || f.Modified != modified {\n\t\t\t\tdiff = append(diff, f)\n\t\t\t\tc.indexSent[f.Name] = f.Modified\n\t\t\t}\n\t\t}\n\t\tidx = diff\n\t}\n\n\tc.mwriter.writeHeader(header{0, c.nextId, msgType})\n\tc.mwriter.writeIndex(idx)\n\terr := c.flush()\n\tc.nextId = (c.nextId + 1) & 0xfff\n\tc.hasSentIndex = true\n\tc.Unlock()\n\n\tif err != nil {\n\t\tc.Close(err)\n\t\treturn\n\t} else if c.mwriter.err != nil {\n\t\tc.Close(c.mwriter.err)\n\t\treturn\n\t}\n}",
"func (x *Index) Write(w io.Writer) error",
"func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tindex := -1\n\tterm := -1\n\tisLeader := true\n\n\t// Your code here (2B).\n\tif rf.state == Leader {\n\t\tnewLogEntry := LogEntry{}\n\t\trf.mu.Lock()\n\t\tif rf.state == Leader {\n\t\t\tterm = rf.currentTerm\n\t\t\tnewLogEntry.Term = term\n\t\t\tnewLogEntry.Command = command\n\t\t\trf.log = append(rf.log, newLogEntry)\n\t\t\tindex = len(rf.log) - 1\n\t\t\t// update leader's matchIndex and nextIndex\n\t\t\trf.matchIndex[rf.me] = index\n\t\t\trf.nextIndex[rf.me] = index + 1\n\t\t\trf.persist()\n\t\t} else {\n\t\t\tDPrintf(\"Peer-%d, before lock, the state has changed to %d.\\n\", rf.me, rf.state)\n\t\t}\n\t\tif term != -1 {\n\t\t\tDPrintf(\"Peer-%d start to append %v to peers.\\n\", rf.me, command)\n\t\t\trequest := rf.createAppendEntriesRequest(index, index+1, term)\n\t\t\tappendProcess := func(server int) bool {\n\t\t\t\treply := new(AppendEntriesReply)\n\t\t\t\trf.sendAppendEntries(server, request, reply)\n\t\t\t\tok := rf.processAppendEntriesReply(index+1, reply)\n\t\t\t\tif ok {\n\t\t\t\t\tDPrintf(\"Peer-%d append log=%v to peer-%d successfully.\\n\", rf.me, request.Entries, server)\n\t\t\t\t} else {\n\t\t\t\t\tDPrintf(\"Peer-%d append log=%v to peer-%d failed.\\n\", rf.me, request.Entries, server)\n\t\t\t\t}\n\t\t\t\treturn ok\n\t\t\t}\n\t\t\tgo func() {\n\t\t\t\tok := rf.agreeWithServers(appendProcess)\n\t\t\t\tif ok {\n\t\t\t\t\t// if append successfully, update commit index.\n\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\tif index >= rf.commitIndex {\n\t\t\t\t\t\tDPrintf(\"Peer-%d set commit=%d, origin=%d.\", rf.me, index, rf.commitIndex)\n\t\t\t\t\t\trf.commitIndex = index\n\t\t\t\t\t} else {\n\t\t\t\t\t\tDPrintf(\"Peer-%d get a currentIndex=%d < commitIndex=%d, it can not be happend.\", rf.me, index, rf.commitIndex)\n\t\t\t\t\t}\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t} else {\n\t\t\t\t\tDPrintf(\"Peer-%d start agreement with servers failed. currentIndex=%d.\\n\", rf.me, index)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\trf.mu.Unlock()\n\t} else {\n\t\tisLeader = false\n\t}\n\treturn index, term, isLeader\n}",
"func (l *leader) applyCommitted() {\n\t// add all entries <=commitIndex & add only non-log entries at commitIndex+1\n\tvar prev, ne *newEntry = nil, l.neHead\n\tfor ne != nil {\n\t\tif ne.index <= l.commitIndex {\n\t\t\tprev, ne = ne, ne.next\n\t\t} else if ne.index == l.commitIndex+1 && !ne.isLogEntry() {\n\t\t\tprev, ne = ne, ne.next\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tvar head *newEntry\n\tif prev != nil {\n\t\thead = l.neHead\n\t\tprev.next = nil\n\t\tl.neHead = ne\n\t\tif l.neHead == nil {\n\t\t\tl.neTail = nil\n\t\t}\n\t}\n\n\tapply := fsmApply{head, l.log.ViewAt(l.log.PrevIndex(), l.commitIndex)}\n\tif trace {\n\t\tprintln(l, apply)\n\t}\n\tl.fsm.ch <- apply\n}",
"func (x *Index) Write(w io.Writer) error {}",
"func (mb *MetricsBuilder) RecordMysqlCommandsDataPoint(ts pcommon.Timestamp, inputVal string, commandAttributeValue AttributeCommand) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlCommands, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlCommands.recordDataPoint(mb.startTime, ts, val, commandAttributeValue.String())\n\treturn nil\n}",
"func (mb *MetricsBuilder) RecordRedisCmdCallsDataPoint(ts pcommon.Timestamp, val int64, cmdAttributeValue string) {\n\tmb.metricRedisCmdCalls.recordDataPoint(mb.startTime, ts, val, cmdAttributeValue)\n}",
"func (m *metricRedisCommands) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}",
"func (s *Basememcached_protocolListener) EnterIncrement_command(ctx *Increment_commandContext) {}",
"func (m *metricRedisCommandsProcessed) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}",
"func (rf *Raft) Start(command interface{}) (int, int, bool) {// {{{\n //fmt.Println(\"Start a command\")\n index := -1\n term, isLeader := rf.GetState()\n if isLeader {\n rf.mu.Lock()\n\t index = len(rf.log)\n rf.log = append(rf.log, LogEntry{Term: term, Cmd: command})\n //rf.matchIdx[rf.me] = len(rf.log) - 1\n rf.persist()\n rf.debug(\"Command appended to Log: idx=%v, cmd=%v\\n\", index, command)\n rf.mu.Unlock()\n }\n //fmt.Println(\"Start a command return\")\n\treturn index, term, isLeader\n}",
"func (e *Engine) Post(cmd Command) {\n\te.cmdStack.Push(cmd)\n}",
"func writer(ch <-chan Word, index *sync.Map, wg *sync.WaitGroup) {\n\tfor {\n\t\tif word, more := <-ch; more {\n\t\t\t// fmt.Printf(\"Writing: %s\\n\", word)\n\t\t\tseen, loaded := index.LoadOrStore(word.word, []int{word.index})\n\t\t\tif loaded && !contains(seen.([]int), word.index) {\n\t\t\t\tseen = append(seen.([]int), word.index)\n\t\t\t\tindex.Store(word.word, seen)\n\t\t\t}\n\t\t} else {\n\t\t\twg.Done()\n\t\t\treturn\n\t\t}\n\t}\n}",
"func (m *metricMysqlCommands) emit(metrics pmetric.MetricSlice) {\n\tif m.settings.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}",
"func (l *Log) Append(ctx context.Context, msg Message) error {\n\tdata, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar b pgx.Batch\n\tb.Queue(\"begin\")\n\tb.Queue(\"lock table switchover_log in exclusive mode\")\n\tb.Queue(\"insert into switchover_log (id, timestamp, data) values (coalesce((select max(id)+1 from switchover_log), 1), now(), $1)\", data)\n\tb.Queue(\"commit\")\n\tb.Queue(\"rollback\")\n\n\tconn, err := stdlib.AcquireConn(l.db)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer releaseConn(l.db, conn)\n\n\terr = conn.SendBatch(ctx, &b).Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func synchronize(self *State, index string) {\n\tprintln()\n\tprintln(\"*** Synchronized with index: \" + index + \" ***\")\n\tprintln(\"*** And value: \" + self.Proposition.ChosenValue.MakeSave() + \" ***\")\n\tprintln()\n\tWrite(self, self.Proposition.ChosenValue, \"files\")\n\tWrite(self, self.Proposition.ChosenValue, \"logs\")\n\tindexParts := strings.Split(index, \".\")\n\tintIndex, _ := strconv.Atoi(indexParts[0])\n\tself.Proposition.Clear(intIndex)\n}",
"func addIndexOp(bucket *bolt.Bucket, k []byte) error {\n\treturn bucket.Put(k, []byte{})\n}",
"func (rf *Raft) Start(command interface{}) (index int, term int, isLeader bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tisLeader = rf.state.Load() == leader\n\tif !isLeader {\n\t\treturn\n\t}\n\n\tterm = rf.currentTerm.Load().(int)\n\tindex = rf.logsLen()\n\trf.logs = append(rf.logs, Log{\n\t\tTerm: term,\n\t\tData: command,\n\t})\n\n\trf.nextIndex[rf.me] = index + 1\n\trf.matchIndex[rf.me] = index\n\trf.persist()\n\n\t// log.Printf(\"append log: new log %v\\n\", rf.logs)\n\n\treturn index + 1, term, isLeader\n}",
"func (s *sliding) append(u Update) {\n\tpos := s.start + LogPosition(len(s.log))\n\ts.log = append(s.log, u)\n\ts.addrPos[u.Addr] = pos\n}",
"func (c *RunCommand) Index() int {\n\treturn c.cmd.index\n}",
"func readtreeSaveIndex(c *Client, opt ReadTreeOptions, i *Index) error {\n\tif !opt.DryRun {\n\t\tif opt.IndexOutput == \"\" {\n\t\t\topt.IndexOutput = \"index\"\n\t\t}\n\t\tf, err := c.GitDir.Create(File(opt.IndexOutput))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\treturn i.WriteIndex(f)\n\t}\n\treturn nil\n}",
"func (p *plugin) cmdLog(w irc.ResponseWriter, r *irc.Request, params cmd.ParamList) {\n\tif params.Len() > 0 {\n\t\tp.profile.SetLogging(params.Bool(0))\n\t}\n\n\tif p.profile.Logging() {\n\t\tproto.PrivMsg(w, r.SenderName, TextLogEnabled)\n\t} else {\n\t\tproto.PrivMsg(w, r.SenderName, TextLogDisabled)\n\t}\n}",
"func (rf *Raft) StartAppendLog() {\n\tvar count int32 = 1\n\tfor i, _ := range rf.peers {\n\t\tif i == rf.me {\n\t\t\tcontinue\n\t\t}\n\t\tgo func(i int) {\n\t\t\tfor{\n\t\t\t\trf.mu.Lock()\n\t\t\t\t//fmt.Printf(\"follower %d lastlogindex: %v, nextIndex: %v\\n\",i, rf.GetPrevLogIndex(i), rf.nextIndex[i])\n\t\t\t\t//fmt.Print(\"sending log entries from leader %d to peer %d for term %d\\n\", rf.me, i, rf.currentTerm)\n\t\t\t\t//fmt.Print(\"nextIndex:%d\\n\", rf.nextIndex[i])\n\t\t\t\tif rf.state != Leader {\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\targs := AppendEntriesArgs{\n\t\t\t\t\tTerm: rf.currentTerm,\n\t\t\t\t\tLeaderId: rf.me,\n\t\t\t\t\tPrevLogIndex: rf.GetPrevLogIndex(i),\n\t\t\t\t\tPrevLogTerm: rf.GetPrevLogTerm(i),\n\t\t\t\t\tEntries: append(make([]LogEntry, 0), rf.logEntries[rf.nextIndex[i]:]...),\n\t\t\t\t\tLeaderCommit: rf.commitIndex,\n\t\t\t\t}\n\t\t\t\treply := AppendEntriesReply{}\n\t\t\t\trf.mu.Unlock()\n\t\t\t\tok := rf.sendAppendEntries(i, &args, &reply)\n\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\trf.mu.Lock()\n\t\t\t\tif rf.state != Leader {\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif reply.Term > rf.currentTerm {\n\t\t\t\t\trf.BeFollower(reply.Term)\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\tsend(rf.appendEntry)\n\t\t\t\t\t}()\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif reply.Success {\n\t\t\t\t\trf.matchIndex[i] = args.PrevLogIndex + len(args.Entries)\n\t\t\t\t\trf.nextIndex[i] = rf.matchIndex[i] + 1\n\t\t\t\t\t//fmt.Print(\"leader: %v, for peer %v, match index: %d, next index: %d, peers: %d\\n\", rf.me, i, rf.matchIndex[i], rf.nextIndex[i], len(rf.peers))\n\t\t\t\t\tatomic.AddInt32(&count, 1)\n\t\t\t\t\tif atomic.LoadInt32(&count) > int32(len(rf.peers)/2) {\n\t\t\t\t\t\t//fmt.Print(\"leader %d reach agreement\\n, args.prevlogindex:%d, len:%d\\n\", rf.me, args.PrevLogIndex, len(args.Entries))\n\t\t\t\t\t\trf.UpdateCommitIndex()\n\t\t\t\t\t}\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\treturn\n\t\t\t\t} else {\n\t\t\t\t\t//fmt.Printf(\"peer %d reset the next index from %d to %d\\n\", i, rf.nextIndex[i], rf.nextIndex[i]-1)\n\t\t\t\t\tif rf.nextIndex[i] > 0 {\n\t\t\t\t\t\trf.nextIndex[i]--\n\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t} else {\n\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t\t}\n\t\t}(i)\n\t}\n\n}",
"func (i *IndexBuilder) walk() error {\n\treturn i.g.CommitIter(func(branch string, c *git.Commit, tree *git.Tree, head bool) error {\n\t\tlog.Infof(\"Inspecting commit-id '%s/%s'\", branch, c.Id().String())\n\t\tvar chartDirs []string\n\t\tvar err error\n\t\tif head && branch == \"master\" {\n\t\t\tlog.Infof(\"HEAD: Retrieving all chart directories...\")\n\t\t\tchartDirs, err = i.listAllChartDirs()\n\t\t} else {\n\t\t\tchartDirs, err = i.listModifiedChartDirs(c, tree)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Debugf(\"Chart directories: '%v'\", chartDirs)\n\t\treturn i.inspectDirs(chartDirs, branch, c, head)\n\t})\n}",
"func (r *ring) NextWriteCmd() (one Completed, multi []Completed, ch chan RedisResult) {\n\tr.read1++\n\tp := r.read1 & r.mask\n\tn := &r.store[p]\n\tn.c1.L.Lock()\n\tif n.mark == 1 {\n\t\tone, multi, ch = n.one, n.multi, n.ch\n\t\tn.mark = 2\n\t} else {\n\t\tr.read1--\n\t}\n\tn.c1.L.Unlock()\n\treturn\n}",
"func (m *metricRedisRdbChangesSinceLastSave) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}",
"func (s *BaseMySqlParserListener) EnterIndexHint(ctx *IndexHintContext) {}",
"func appendMetric(metric *statepb.Metric, idx int32, value float64) {\n\tif l := int32(len(metric.Indices)); l == 0 || metric.Indices[l-2]+metric.Indices[l-1] != idx {\n\t\t// If we append V to idx 9 and metric.Indices = [3, 4] then the last filled index is 3+4-1=7\n\t\t// So that means we have holes in idx 7 and 8, so start a new group.\n\t\tmetric.Indices = append(metric.Indices, idx, 1)\n\t} else {\n\t\tmetric.Indices[l-1]++ // Expand the length of the current filled list\n\t}\n\tmetric.Values = append(metric.Values, value)\n}",
"func (b *raftBadger) Apply(l *raft.Log) interface{} {\n\tvar c command\n\tif err := json.Unmarshal(l.Data, &c); err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to unmarshal command: %s\", err.Error()))\n\t}\n\n\tswitch l.Type {\n\tcase raft.LogCommand:\n\t\tvar payload = command{}\n\t\tif err := json.Unmarshal(l.Data, &payload); err != nil {\n\t\t\tb.logger.Error(\"error un-marshaling payload\", \"cause\", hclog.Fmt(\"%v\", err.Error()))\n\t\t\treturn nil\n\t\t}\n\t\tswitch payload.Op {\n\t\tcase CMDREPLAY:\n\t\t\tif _, ok := payload.Value.(string); ok {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treplayStatus := []byte{0}\n\t\t\tif v, ok := payload.Value.(bool); ok {\n\t\t\t\tif v {\n\t\t\t\t\treplayStatus[0] = 1\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treplayStatus = payload.Value.([]byte)\n\t\t\t}\n\t\t\terr := b.SetRaw(replayKeyOf([]byte(payload.Store)), replayStatus)\n\t\t\treturn &RpcResponse{Error: err, Data: payload.Value}\n\t\tcase CMDSET:\n\t\t\t_, err := b.gs.Save(payload.Key, payload.Store, payload.Value)\n\t\t\treturn &RpcResponse{Error: err, Data: payload.Value}\n\t\tcase CMDMOD:\n\t\t\terr := b.gs.Update(payload.Key, payload.Store, payload.Value)\n\t\t\treturn &RpcResponse{Error: err, Data: payload.Value}\n\t\tcase CMDDEL:\n\t\t\terr := b.gs.Delete(payload.Key, payload.Store)\n\t\t\treturn &RpcResponse{Error: err, Data: nil}\n\t\tdefault:\n\t\t\tb.logger.Warn(\"Invalid Raft log command\", \"payload\", hclog.Fmt(\"%v\", payload.Op))\n\t\t}\n\t}\n\tb.logger.Info(\"Raft log command\", \"type\", hclog.Fmt(\"%v\", raft.LogCommand))\n\treturn nil\n}",
"func (m *metricMysqlIndexIoWaitCount) emit(metrics pmetric.MetricSlice) {\n\tif m.settings.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}",
"func (n *alterIndexNode) ReadingOwnWrites() {}",
"func (i *IndexCommand) Run(ctx context.Context, subcommandArgs []string) error {\n\toutputPath := i.flags.String(\"o\", \"Index.md\", \"Output path contained to the $JOURNAL_PATH.\")\n\tif !i.flags.Parsed() {\n\t\tif err := i.flags.Parse(subcommandArgs); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif *outputPath == \".\" {\n\t\t*outputPath = \"Index.md\"\n\t}\n\tindex, err := tagMap(i.options.JournalPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tkeys := sortedTagKeys(index)\n\tvar newIndex string\n\tfor _, tag := range keys {\n\t\tnewIndex += fmt.Sprintf(\"\\n* *%s* \", tag)\n\t\tmappedEntries := make([]string, len(index[tag]))\n\t\tmapper := func(entry string) string {\n\t\t\treturn fmt.Sprintf(\"[%s](%s)\", entry, entry)\n\t\t}\n\t\tfor i, entry := range index[tag] {\n\t\t\tmappedEntries[i] = mapper(entry)\n\t\t}\n\t\tnewIndex += strings.Join(mappedEntries, \", \")\n\t}\n\tindexPath := fmt.Sprintf(\"%s/%s\", i.options.JournalPath, path.Base(*outputPath))\n\treturn ioutil.WriteFile(indexPath, []byte(newIndex), 0644)\n}",
"func (kv *RaftKV) Apply(msg *raft.ApplyMsg) {\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\n\tvar args Op\n\targs = msg.Command.(Op)\n\tif kv.op_count[args.Client] >= args.Id {\n\t\tDPrintf(\"Duplicate operation\\n\")\n\t}else {\n\t\tswitch args.Type {\n\t\tcase OpPut:\n\t\t\tDPrintf(\"Put Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = args.Value\n\t\tcase OpAppend:\n\t\t\tDPrintf(\"Append Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = kv.data[args.Key] + args.Value\n\t\tdefault:\n\t\t}\n\t\tkv.op_count[args.Client] = args.Id\n\t}\n\n\t//DPrintf(\"@@@Index:%v len:%v content:%v\\n\", msg.Index, len(kv.pendingOps[msg.Index]), kv.pendingOps[msg.Index])\n\t//DPrintf(\"@@@kv.pendingOps[%v]:%v\\n\", msg.Index, kv.pendingOps[msg.Index])\n\tfor _, i := range kv.pendingOps[msg.Index] {\n\t\tif i.op.Client==args.Client && i.op.Id==args.Id {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <- true\n\t\t}else {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <-false\n\t\t}\n\t}\n\tdelete(kv.pendingOps, msg.Index)\n}",
"func (t *VLIntDbl) RedisInsertCmd(key string) string {\n\treturn \"LADD \" + key\n}",
"func (m *metricActiveDirectoryDsLdapBindLastSuccessfulTime) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}",
"func (m *metricRedisCmdCalls) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}",
"func Follow(r cruntime.Manager, bs bootstrapper.Bootstrapper, cfg config.ClusterConfig, cr logRunner, logOutput io.Writer) error {\n\tcs := []string{}\n\tfor _, v := range logCommands(r, bs, cfg, 0, true) {\n\t\tcs = append(cs, v+\" &\")\n\t}\n\tcs = append(cs, \"wait\")\n\n\tcmd := exec.Command(\"/bin/bash\", \"-c\", strings.Join(cs, \" \"))\n\tcmd.Stdout = logOutput\n\tcmd.Stderr = logOutput\n\tif _, err := cr.RunCmd(cmd); err != nil {\n\t\treturn errors.Wrapf(err, \"log follow\")\n\t}\n\treturn nil\n}",
"func (c *Controller) syncToStdout(key string) error {\n\tobj, exists, err := c.indexer.GetByKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !exists {\n\t\t// Below we will warm up our cache with a Pod, so that we will see a delete for one pod\n\t\tc.cf(true,key)\n\t\t\n\t} else {\n\t\tc.cf(false,obj)\n\t}\n\treturn nil\n}",
"func (logger *DiscardLogger) PrintCommand(sessionID string, command string, params string) {}",
"func (m *metricMysqlLogOperations) emit(metrics pmetric.MetricSlice) {\n\tif m.settings.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}",
"func (mb *MetricsBuilder) RecordRedisCommandsProcessedDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricRedisCommandsProcessed.recordDataPoint(mb.startTime, ts, val)\n}",
"func (t *VLInt) RedisInsertCmd(key string) string {\n\treturn \"LADD \" + key\n}",
"func DPosCBRecordCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"cbRecord\",\n\t\tShort: \"record cycle boundary info\",\n\t\tRun: recordCB,\n\t}\n\taddCBRecordCmdFlags(cmd)\n\treturn cmd\n}",
"func (dd *dictDecoder) writeMark(cnt int) {\n\tdd.wrPos += cnt\n}",
"func (mp *metaPartition) Apply(command []byte, index uint64) (resp interface{}, err error) {\n\tmsg := &MetaItem{}\n\tdefer func() {\n\t\tif err == nil {\n\t\t\tmp.uploadApplyID(index)\n\t\t}\n\t}()\n\tif err = msg.UnmarshalJson(command); err != nil {\n\t\treturn\n\t}\n\n\tswitch msg.Op {\n\tcase opFSMCreateInode:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif mp.config.Cursor < ino.Inode {\n\t\t\tmp.config.Cursor = ino.Inode\n\t\t}\n\t\tresp = mp.fsmCreateInode(ino)\n\tcase opFSMUnlinkInode:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmUnlinkInode(ino)\n\tcase opFSMUnlinkInodeBatch:\n\t\tinodes, err := InodeBatchUnmarshal(msg.V)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresp = mp.fsmUnlinkInodeBatch(inodes)\n\tcase opFSMExtentTruncate:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmExtentsTruncate(ino)\n\tcase opFSMCreateLinkInode:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmCreateLinkInode(ino)\n\tcase opFSMEvictInode:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmEvictInode(ino)\n\tcase opFSMEvictInodeBatch:\n\t\tinodes, err := InodeBatchUnmarshal(msg.V)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresp = mp.fsmBatchEvictInode(inodes)\n\tcase opFSMSetAttr:\n\t\treq := &SetattrRequest{}\n\t\terr = json.Unmarshal(msg.V, req)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\terr = mp.fsmSetAttr(req)\n\tcase opFSMCreateDentry:\n\t\tden := &Dentry{}\n\t\tif err = den.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmCreateDentry(den, false)\n\tcase opFSMDeleteDentry:\n\t\tden := &Dentry{}\n\t\tif err = den.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmDeleteDentry(den, false)\n\tcase opFSMDeleteDentryBatch:\n\t\tdb, err := DentryBatchUnmarshal(msg.V)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresp = mp.fsmBatchDeleteDentry(db)\n\tcase opFSMUpdateDentry:\n\t\tden := &Dentry{}\n\t\tif err = den.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmUpdateDentry(den)\n\tcase opFSMUpdatePartition:\n\t\treq := &UpdatePartitionReq{}\n\t\tif err = json.Unmarshal(msg.V, req); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp, err = mp.fsmUpdatePartition(req.End)\n\tcase opFSMExtentsAdd:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmAppendExtents(ino)\n\tcase opFSMExtentsAddWithCheck:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmAppendExtentsWithCheck(ino)\n\tcase opFSMStoreTick:\n\t\tinodeTree := mp.getInodeTree()\n\t\tdentryTree := mp.getDentryTree()\n\t\textendTree := mp.extendTree.GetTree()\n\t\tmultipartTree := mp.multipartTree.GetTree()\n\t\tmsg := &storeMsg{\n\t\t\tcommand: opFSMStoreTick,\n\t\t\tapplyIndex: index,\n\t\t\tinodeTree: inodeTree,\n\t\t\tdentryTree: dentryTree,\n\t\t\textendTree: extendTree,\n\t\t\tmultipartTree: multipartTree,\n\t\t}\n\t\tmp.storeChan <- msg\n\tcase opFSMInternalDeleteInode:\n\t\terr = mp.internalDelete(msg.V)\n\tcase opFSMInternalDeleteInodeBatch:\n\t\terr = mp.internalDeleteBatch(msg.V)\n\tcase opFSMInternalDelExtentFile:\n\t\terr = mp.delOldExtentFile(msg.V)\n\tcase opFSMInternalDelExtentCursor:\n\t\terr = mp.setExtentDeleteFileCursor(msg.V)\n\tcase opFSMSetXAttr:\n\t\tvar extend *Extend\n\t\tif extend, err = NewExtendFromBytes(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\terr = mp.fsmSetXAttr(extend)\n\tcase opFSMRemoveXAttr:\n\t\tvar extend *Extend\n\t\tif extend, err = NewExtendFromBytes(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\terr = mp.fsmRemoveXAttr(extend)\n\tcase opFSMCreateMultipart:\n\t\tvar multipart *Multipart\n\t\tmultipart = MultipartFromBytes(msg.V)\n\t\tresp = mp.fsmCreateMultipart(multipart)\n\tcase opFSMRemoveMultipart:\n\t\tvar multipart *Multipart\n\t\tmultipart = MultipartFromBytes(msg.V)\n\t\tresp = mp.fsmRemoveMultipart(multipart)\n\tcase opFSMAppendMultipart:\n\t\tvar multipart *Multipart\n\t\tmultipart = MultipartFromBytes(msg.V)\n\t\tresp = mp.fsmAppendMultipart(multipart)\n\tcase opFSMSyncCursor:\n\t\tvar cursor uint64\n\t\tcursor = binary.BigEndian.Uint64(msg.V)\n\t\tif cursor > mp.config.Cursor {\n\t\t\tmp.config.Cursor = cursor\n\t\t}\n\t}\n\n\treturn\n}",
"func (c *clientHooks) OnWrite(meta kgo.BrokerMetadata, key int16, bytesWritten int, writeWait, timeToWrite time.Duration, err error) {\n\tkeyName := kmsg.NameForKey(key)\n\tif keyName != \"OffsetCommit\" {\n\t\treturn\n\t}\n\n\t// c.logger.Info(\"hooks onWrite\",\n\t// \tzap.Duration(\"timeToWrite\", timeToWrite),\n\t// \tzap.NamedError(\"err\", err))\n}",
"func (s *dbStore) Cmd(seq int) (string, error) {\n\tvar cmd string\n\terr := s.db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(bucketCmd))\n\t\tv := b.Get(marshalSeq(uint64(seq)))\n\t\tif v == nil {\n\t\t\treturn ErrNoMatchingCmd\n\t\t}\n\t\tcmd = string(v)\n\t\treturn nil\n\t})\n\treturn cmd, err\n}",
"func (t *VLIntInt) RedisInsertCmd(key string) string {\n\treturn \"LADD \" + key\n}",
"func (t *VLStrInt) RedisInsertCmd(key string) string {\n\treturn \"LADD \" + key\n}",
"func (i *Index) Write(off uint32, pos uint64) error {\n\tif uint64(len(i.mmap)) < i.size+entWidth {\n\t\treturn lib.Wrap(io.EOF, \"Not enough space to append index data\")\n\t}\n\n\tenc.PutUint32(i.mmap[i.size:i.size+offWidth], off)\n\tenc.PutUint64(i.mmap[i.size+offWidth:i.size+entWidth], pos)\n\n\ti.size += entWidth\n\n\treturn nil\n}",
"func (kv *ShardKV) PutAppend(args *PutAppendArgs, reply *PutAppendReply) error {\n\t// Your code here.\n\t\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\n\tdelete(kv.records, args.Prev)\n\n\tDPrintf(\"%s Received %s, Key=%s,Value=%s\",kv.name,args.Op,args.Key,args.Value)\n\tDPrintf(\"ID=%v\",args.ID)\n\t\n\tif record, ok := kv.records[args.ID]; ok && record.Err==OK {\n\t // we have a record associate with this ID\n\t reply.Err = record.Err\n\n\t DPrintf(\"%s found an ID we have seen before,%s key=%s value=%s\",kv.name,args.Op,args.Key,args.Value)\n\t DPrintf(\"Err=%v\", reply.Err)\n\t return nil\n\t}\n\n//\tdelete(kv.records, args.Prev)\n\n\tvar v = Op{}\n\tv.ID = args.ID\n\tv.Type = args.Op\n\tv.Key = args.Key\n\tv.Value = args.Value\n\t\n\tseq := kv.Log(v)\n\tresult := kv.ReadLog(seq)\n\n\treply.Err = result.Err\n\treply.Done = args.ID\n\n\tkv.px.Done(seq)\n\tkv.seq = seq + 1\n\n\tnewRecord := Record{result.Value,result.Err}\n\tkv.records[args.ID] = &newRecord\n\n\treturn nil\n}",
"func SyncAllLog(log_conn Log_Conn ){\n\t//fmt.Println(\"Sync Called\")\n\tfor r.IsLeader==1{\n\t\tlogentry:=log_conn.Logentry\n\t\tconn:=log_conn.Conn\n\t\tbreakVariable:=false\n\t\tvar args *AppendRPCArgs\n\t\tvar heartBeat bool\n\t\tvar logentry1 LogEntry\n\t\t//var majority int\n\t\traft.AppendHeartbeat <- 1\n\t\tfor _,server := range r.ClusterConfigV.Servers {\n\t\t\tif server.Id != r.Id {\n\t\t\t\t// if Follower not having latast entry and Expected entry index is less or equal to current Log index \n\t\t\t\tif r.MatchIndex[server.Id] < (logentry.SequenceNumber) && r.NextIndex[server.Id] <= (logentry.SequenceNumber) { //&& r.MatchIndex[server.Id]!=0 && r.NextIndex[server.Id]!=0\n\t\t\t\t\tlogentry1=r.Log[r.NextIndex[server.Id]] // Next to send is entry at Next Index \n\t\t\t\t\t//majority = r.MatchIndex[server.Id] \n\t\t\t\t\tif logentry1.SequenceNumber >= 1 {\t\n\t\t\t\t\t\t\targs = &AppendRPCArgs {\n\t\t\t\t\t\t\tlogentry1.Term,\n\t\t\t\t\t\t\tr.LeaderId,\n\t\t\t\t\t\t\tlogentry1.SequenceNumber-1,\n\t\t\t\t\t\t\tr.Log[logentry1.SequenceNumber-1].Term,\n\t\t\t\t\t\t\tlogentry1,\n\t\t\t\t\t\t\tr.CommitIndex,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\targs = &AppendRPCArgs {\n\t\t\t\t\t\t\tlogentry1.Term,\n\t\t\t\t\t\t\tr.LeaderId,\n\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\tlogentry1.Term,\n\t\t\t\t\t\t\tlogentry1,\n\t\t\t\t\t\t\tr.CommitIndex,\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\theartBeat = false\n\t\t\t\t}else { // Else send normal heart beat to follower\n\t\t\t\t\targs = prepareHeartBeat()\n\t\t\t\t\theartBeat = true\n\t\t\t\t}// end of if else\n\t\t\t\t\tvar AppendAck_ch = make (chan int,1)\n\t\t\t\t\tif(heartBeat){ \n\t\t\t\t\t\tvar DummyChan = make (chan int,1)\n\t\t\t\t\t\tgo r.sendAppendRpc(server,args,DummyChan,false) // Dont wait on HeartBeat, heart Beat is Send\n\t\t\t\t\t}else{\n\t\t\t\t\t\t//fmt.Println(\"Sending SYnc for server \",server.Id,\" log \",logentry1.SequenceNumber)\n\t\t\t\t\t\tgo r.sendAppendRpc(server,args,AppendAck_ch,false) \n\t\t\t\t\t}\n\t\t\t\t\tif !heartBeat && -1 !=<-AppendAck_ch { // If Log Entry is send, wait for reply, If log entry is appended to follower\n\t\t\t\t\t\tmajorityCount:=0\n\t\t\t\t\t\tfor _,serverC:= range r.ClusterConfigV.Servers { // Check if log entry is in majority \n\t\t\t\t\t\t\tif serverC.Id !=r.Id && serverC.Id != server.Id && r.MatchIndex[serverC.Id] >= logentry1.SequenceNumber {//&& r.MatchIndex[serverC.Id] != 0 {\n\t\t\t\t\t\t\t\tmajorityCount++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// If Log entry is in majority and is not committed yet, commit the log entry and send it to input_ch for evaluation\n\t\t\t\t\t\tif majorityCount < len(r.ClusterConfigV.Servers)/2 && majorityCount+1 >len(r.ClusterConfigV.Servers)/2{\n\t\t\t\t\t\t\tr.Log[logentry1.SequenceNumber].IsCommitted=true\t\n\t\t\t\t\t\t\tr.CommitIndex=logentry1.SequenceNumber\n\t\t\t\t\t\t\tr.File.WriteString(strconv.Itoa(logentry1.Term)+\" \"+strconv.Itoa(logentry1.SequenceNumber)+\" \"+strings.TrimSpace(strings.Replace(string(logentry1.Command),\"\\n\",\" \",-1))+\" \"+\" \"+strconv.FormatBool(logentry1.IsCommitted))\n\t\t\t\t\t\t\tr.File.WriteString(\"\\t\\r\\n\");\n\t\t\t\t\t\t\tInput_ch <- Log_Conn{logentry1,conn}\n\t\t\t\t\t\t\tbreakVariable=true\n\t\t\t\t\t\t}else if majorityCount+1 >len(r.ClusterConfigV.Servers)/2 && logentry.SequenceNumber==logentry1.SequenceNumber {\n\t\t\t\t\t\t\t// if Log was already in majority and now all log is in majority no need to send more log entries\n\t\t\t\t\t\t\tbreakVariable=true\n\t\t\t\t\t\t}\n\t\t\t\t\t}// end of IF\n\t\t\t\t} // outer if\t\n\t\t\t}//inner for loop\n\t\t\tif breakVariable{\n\t\t\t\t\tbreak\n\t\t\t}\n\t\t\tmajorityCount:=0\n\t\t\tfor _,server:= range r.ClusterConfigV.Servers {\n\t\t\t\t\t\t//if i.Id !=raft.ServerId && i!=value && raft.matchIndex[i.Id] >majorityCheck {\n\t\t\t\tif server.Id !=r.Id && r.MatchIndex[server.Id] >= logentry.SequenceNumber {\n\t\t\t\t\t\tmajorityCount++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif majorityCount+1 >len(r.ClusterConfigV.Servers)/2 || r.IsLeader!=1{\n\t\t\t\t\tbreak\n\t\t\t\t}\t\t\n\t}//outer for loop\n\t//fmt.Println(\"Sync Exited\")\n}",
"func (t *VLIntStr) RedisInsertCmd(key string) string {\n\treturn \"LADD \" + key\n}",
"func (ng *Engine) Execute(cmd Command) ([]byte, error) {\n\tvar err error\n\n\tstore, err := ng.GetStore(cmd.Index, cmd.Database)\n\n\tif ng.debug {\n\t\tcmd.Println()\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twriter := store.Writer()\n\n\treader := store.Reader()\n\tdefer func() {\n\t\treader.Close()\n\t}()\n\n\tswitch cmd.Command {\n\tcase \"batch\":\n\t\twriter.StartBatch()\n\t\treturn nil, nil\n\tcase \"flushbatch\":\n\t\terr = writer.FlushBatch()\n\t\treturn nil, err\n\tcase \"set\":\n\t\terr = writer.Set(cmd.Key, cmd.Value)\n\t\treturn nil, err\n\tcase \"get\":\n\t\treturn reader.Get(cmd.Key)\n\tcase \"mergeset\":\n\t\tv := utils.BytesToUint64(cmd.Value)\n\t\treturn nil, writer.MergeSet(cmd.Key, v)\n\tcase \"delete\":\n\t\terr = writer.Delete(cmd.Key)\n\t\treturn nil, err\n\t}\n\n\treturn nil, errors.New(\"Failed to execute command.\")\n}",
"func (t *syncResult) record(w *bufio.Writer) {\n\n\tif t.err != nil {\n\t\tw.WriteString(fmt.Sprintf(\"%d,fail,false,%s,%s\\n\",\n\t\t\ttime.Now().Unix(), t.oldKey, strings.ReplaceAll(t.err.Error(), \"\\n\", \" \")))\n\t} else {\n\t\tw.WriteString(fmt.Sprintf(\"%d,ok,%t,%s\\n\",\n\t\t\ttime.Now().Unix(), t.verified, t.oldKey))\n\t}\n\n\tw.Flush()\n}",
"func (rf *Raft) Start(command interface{}) (int, int, bool) {\n rf.mu.Lock()\n defer rf.mu.Unlock()\n\n if rf.state != StateLeader {\n return nilIndex, nilIndex, false\n }\n\n // Your code here (2B).\n\n logLen := len(rf.log)\n index := logLen\n term := rf.currentTerm\n isLeader := true\n\n thisEntry := LogEntry{rf.currentTerm, command}\n rf.log = append(rf.log, thisEntry)\n rf.matchIndex[rf.me] = len(rf.log)\n\n rf.persist()\n\n // rf.print(\"Client start command %v\", command)\n\n return index, term, isLeader\n}",
"func (s *BaseCymbolListener) EnterIndex(ctx *IndexContext) {}",
"func (thread *Thread) OnAppend(ctx aero.Context, key string, index int, obj interface{}) {\n\tonAppend(thread, ctx, key, index, obj)\n}",
"func (st *insertStats) report(chain []*types.Block, index int, dirty common.StorageSize) {\n\t// Fetch the timings for the batch\n\tvar (\n\t\tnow = mclock.Now()\n\t\telapsed = time.Duration(now) - time.Duration(st.startTime)\n\t)\n\t// If we're at the last block of the batch or report period reached, log\n\tif index == len(chain)-1 || elapsed >= statsReportLimit {\n\t\t// Count the number of transactions in this segment\n\t\tvar txs int\n\t\tfor _, block := range chain[st.lastIndex : index+1] {\n\t\t\ttxs += len(block.Transactions())\n\t\t}\n\t\tend := chain[index]\n\n\t\t// Assemble the log context and send it to the logger\n\t\tcontext := []interface{}{\n\t\t\t\"blocks\", st.processed, \"txs\", txs, \"mgas\", float64(st.usedGas) / 1000000,\n\t\t\t\"elapsed\", common.PrettyDuration(elapsed), \"mgasps\", float64(st.usedGas) * 1000 / float64(elapsed),\n\t\t\t\"number\", end.Number(), \"hash\", end.Hash(),\n\t\t}\n\t\tif timestamp := time.Unix(int64(end.Time()), 0); time.Since(timestamp) > time.Minute {\n\t\t\tcontext = append(context, []interface{}{\"age\", common.PrettyAge(timestamp)}...)\n\t\t}\n\t\tcontext = append(context, []interface{}{\"dirty\", dirty}...)\n\n\t\tif st.queued > 0 {\n\t\t\tcontext = append(context, []interface{}{\"queued\", st.queued}...)\n\t\t}\n\t\tif st.ignored > 0 {\n\t\t\tcontext = append(context, []interface{}{\"ignored\", st.ignored}...)\n\t\t}\n\t\tlog.Info(\"Imported new chain segment\", context...)\n\n\t\t// Bump the stats reported to the next section\n\t\t*st = insertStats{startTime: now, lastIndex: index + 1}\n\t}\n}",
"func (a *RPC) AppendRPC(args *AppendRPCArgs, reply *AppendRPCReply) error {\n\t//raft.ElectionTimer_ch <- args.LeaderId //TODO\n\tr.ResetTimer() // Reset timer for election \n\tmutex.Lock() \t \n\tr.ResetTimer()\n var logIndex int \n if len(r.Log) > 0 { // If Log is not emtpy.. Initialised Log intex to last heighest log index\n \tlogIndex =len(r.Log)-1\n }else{ \n \tlogIndex =0 // Else Log index is 0\n }\n //fmt.Println(\"LogInedx \",logIndex,\" PrevLogIndex \",args.PrevLogIndex)\n\tif len(args.Entry.Command)!=0{ // If This request has actual logentry to append, else it is heartbeat. \n\t\t\n\t\tr.IsLeader=2 \t\t\t\t // Fall back to Follower state \n\t\tr.LeaderId=args.LeaderId\t // Update to current Leader id \n\t\tr.VotedFor=-1 \t\t\t // Election is over, No need to remember whome u voted for. \n\t\t\t\t\t\t\t\t\t// Thank god... Leader will keep remembering you periodaically :)\n \n\t\t \t if(args.Term < r.CurrentTerm) { // If this logentry has came from Previous Term.. Just Reject it. \n\t\t \treply.Reply=false\n\t\t } else if (logIndex <args.PrevLogIndex) { // log lagging behind, \n\t\t \treply.Reply=false // Set appened to false and \n\t\t reply.NextIndex=logIndex+1 // Set next expected log entry to Heighet log Index +1\n\t\t reply.MatchIndex=-1 \n\t\t r.CurrentTerm=args.Term\t\n\t\t } else if (logIndex > args.PrevLogIndex){ // log is ahead \n\t\t \t if (r.Log[args.PrevLogIndex].Term != args.PrevLogTerm) { // If previous log term does matches with leaders Previous log term \n\t\t \t \t\t\treply.Reply=false \n\t\t reply.NextIndex=args.PrevLogIndex // Set expected next log index to previous to do check matching\n\t\t \treply.MatchIndex = -1\n\t\t \tr.CurrentTerm=args.Term\t\n\t\t } else{ \t\t\t\t\t\t\t\t\t\t// Else Terms is matching, overwrite with log with new entry\n\t\t \t\tr.Log[args.PrevLogIndex+1]=args.Entry \n\t\t\t\t\t\t\treply.Reply=true\n\t\t \treply.MatchIndex=args.PrevLogIndex+1 // Match Index is set to added entry \n\t\t \treply.NextIndex=args.PrevLogIndex+2 // Expected Entry is next log entry after added entry\n\t\t \tr.CurrentTerm=args.Term\t\n\t\t \t//fmt.Println(\"Calling commit in logIndex>PrevLogIndex\")\n\t\t \tCommitCh <- CommitI_LogI{args.LeaderCommit,args.PrevLogIndex+1} // Send Commit index to commitCh to commit log entries, Commit only till newly added aentry\n\t\t }\n\t\t }else if(logIndex == args.PrevLogIndex) { // log is at same space\n\t\t \tif logIndex!=0 && (r.Log[logIndex].Term != args.PrevLogTerm) { // if log is not emtpy, and previous log tersm is matching\n\t\t reply.Reply=false \t\t\t\t\t\t\t\t\t// Reject the log entry \n\t\t reply.NextIndex=args.PrevLogIndex \n\t\t reply.MatchIndex = -1\n\t\t r.CurrentTerm=args.Term\t\n\t\t } else if len(r.Log)==0 && args.Entry.SequenceNumber==0{ // If log is empty and Recieved log entry index is 0, Add Entry\n\t\t \t\t\tr.Log=append(r.Log,args.Entry) \t\n\t\t \t\treply.Reply=true\n\t\t \t\treply.NextIndex=len(r.Log) \t\t\t\t\n\t\t \t\treply.MatchIndex=len(r.Log)-1\n\t\t \t\tr.CurrentTerm=args.Term\t\n\t\t \t\t//fmt.Println(\"Calling commit in logIndex=PrevLogIndex\")\n\t\t \t\tCommitCh <- CommitI_LogI{args.LeaderCommit,len(r.Log)-1}\n\t\t }else if len(r.Log)!=args.Entry.SequenceNumber{ // If log is empty and Recieved log entry index is not 0, Missmatch, Reject\n\t\t \t\t \t//r.Log=append(r.Log,args.Entry)\n\t\t \t\treply.Reply=false\n\t\t \t\treply.NextIndex=len(r.Log)\n\t\t \t\treply.MatchIndex=-1\n\t\t \t\tr.CurrentTerm=args.Term\t\n\t\t \t\t//fmt.Println(\"Calling commit in logIndex=PrevLogIndex\")\n\t\t \t\t//CommitCh <- CommitI_LogI{args.LeaderCommit,len(r.Log)-1}\n\t\t }else {\t\t\t\t\t\t\t\t\t\t\t// Previous log is matched , and this is new entry, add it to last of log\n\t\t \t\t\tr.Log=append(r.Log,args.Entry)\n\t\t \t\treply.Reply=true\n\t\t \t\treply.NextIndex=len(r.Log)\n\t\t \t\treply.MatchIndex=len(r.Log)-1\n\t\t \t\tr.CurrentTerm=args.Term\t\n\t\t \t\t//fmt.Println(\"Calling commit in logIndex=PrevLogIndex\")\n\t\t \t\tCommitCh <- CommitI_LogI{args.LeaderCommit,len(r.Log)-1}\n\t\t }\n\t\t }\n\t\t /* if len (args.Entry.Command)!=0{\n\t\t\t\tfmt.Println(\"Received append rpc for\",r.Id ,\" From \",args.LeaderId, \" Log size is \",logIndex, \" == \",args.PrevLogIndex,\" < \", args.Entry.SequenceNumber ,\" Commitindex \",r.CommitIndex,\" < \",args.LeaderCommit, \"added \",reply.Reply)\n\t\t\t}*/\n\tr.ResetTimer() // This is For precautionaru measure, as system was slow and it was taking more time, leading to expiry of timer\n\t\t\t\t\t// Before replying \t\n\t}else\n\t{\n\t\t/*\n\t\tThis part is same as above but only without actually aadding entries to log. Next index and match index is updated.\n\t\tand CommitCh is feed with commit Index entries\n\t\t*/\n\t\t//fmt.Println(\"Heart Beat recieved \",r.Id,\" \",\"LogInedx \" , len(r.Log)-1,\" PrevLogIndex \",args.PrevLogIndex)\n\t\t//fmt.Println(\"LogInedx \",logIndex,\" PrevLogIndex \",args.PrevLogIndex)\n\t\t if(r.CurrentTerm <= args.Term) { \n\t\t\t\tr.IsLeader=2\n\t\t\t\tr.LeaderId=args.LeaderId\t\n\t\t\t\tr.VotedFor=-1\n\t\t\t\tr.CurrentTerm=args.Term\t\n\t\t\t\tif(logIndex == args.PrevLogIndex && len(r.Log)==0){\n\t\t\t\t\treply.NextIndex=0\n\t\t\t\t\treply.MatchIndex=-1\n\t\t\t\t\t//fmt.Println(\"HeartBeat Recieved logIndex == args.PrevLogIndex && len(r.Log)==0\") \n\t\t\t\t}else if (logIndex <args.PrevLogIndex){\n\t\t\t\t\treply.NextIndex=logIndex+1\n\t\t\t\t\treply.MatchIndex=-1\n\t\t\t\t\t//fmt.Println(\"HeartBeat Recieved logIndex <args.PrevLogIndex\") \n\t\t\t\t}else if (logIndex >args.PrevLogIndex){\n\t\t\t\t\tif (r.Log[args.PrevLogIndex].Term != args.PrevLogTerm) {\n\t\t\t\t\t\treply.Reply=false \n\t\t reply.NextIndex=-1\n\t\t reply.MatchIndex = -1\n\t\t\t\t\t}else{\n\t\t\t\t\t\treply.Reply=true\n\t\t reply.MatchIndex=args.PrevLogIndex\n\t\t reply.NextIndex=args.PrevLogIndex+1\n\t\t CommitCh <- CommitI_LogI{args.LeaderCommit,args.PrevLogIndex+1}\n\t\t\t\t\t}\n\t\t\t\t}else if(logIndex == args.PrevLogIndex) {\n\t\t\t\t\t\tif logIndex!=0 && (r.Log[logIndex].Term != args.PrevLogTerm) {\n\t\t\t\t\t\t\t reply.Reply=false\n\t\t reply.NextIndex=-1\n\t\t reply.MatchIndex = -1\n\n\t\t }else{\n\t\t \treply.Reply=true\n\t\t reply.NextIndex=args.PrevLogIndex+1\n\t\t reply.MatchIndex=args.PrevLogIndex\n\t\t CommitCh <- CommitI_LogI{args.LeaderCommit,len(r.Log)-1}\n\t\t }\n\t\t\t\t\t}\n\t\t\t}\n\tr.ResetTimer()\n\t}\n mutex.Unlock()\n\treturn nil\n}",
"func (r *Redis) Index(i services.Consumable) error {\n\tvar (\n\t\tpipe = r.client.TxPipeline()\n\n\t\ttxByIDKey = redisIndexKeysTxByID(r.chainID.String(), i.ID())\n\t\ttxCountKey = redisIndexKeysTxCount(r.chainID.String())\n\t\trecentTxsKey = redisIndexKeysRecentTxs(r.chainID.String())\n\n\t\tctx, cancelFn = context.WithTimeout(context.Background(), redisTimeout)\n\t)\n\tdefer cancelFn()\n\n\tif err := pipe.Set(ctx, txByIDKey, i.Body(), 0).Err(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := pipe.Incr(ctx, txCountKey).Err(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := pipe.LPush(ctx, recentTxsKey, i.ID()).Err(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := pipe.LTrim(ctx, recentTxsKey, 0, redisRecentTxsSize-1).Err(); err != nil {\n\t\treturn err\n\t}\n\n\t_, err := pipe.Exec(ctx)\n\treturn err\n}"
] | [
"0.5331357",
"0.52084446",
"0.50618184",
"0.49568516",
"0.48745605",
"0.4864999",
"0.48493907",
"0.48244768",
"0.4761423",
"0.47521734",
"0.47235358",
"0.4694006",
"0.4692145",
"0.46897775",
"0.46831962",
"0.4679095",
"0.46720842",
"0.46662083",
"0.46185398",
"0.4608033",
"0.46009326",
"0.458687",
"0.45623696",
"0.45576504",
"0.454529",
"0.4543999",
"0.45417956",
"0.4539856",
"0.45267597",
"0.4523064",
"0.4501137",
"0.44827887",
"0.44504684",
"0.44450375",
"0.44433314",
"0.44345054",
"0.4434095",
"0.4424406",
"0.44198248",
"0.44107187",
"0.44033277",
"0.4394088",
"0.43563738",
"0.43383816",
"0.43223917",
"0.4321061",
"0.4306375",
"0.43055207",
"0.42980847",
"0.42880866",
"0.42835745",
"0.42830557",
"0.4282315",
"0.42769492",
"0.4256564",
"0.4249897",
"0.42284432",
"0.4214866",
"0.4207563",
"0.42070544",
"0.41974065",
"0.41940618",
"0.41919577",
"0.41903585",
"0.41834643",
"0.4180754",
"0.41781735",
"0.4177436",
"0.41743845",
"0.41742492",
"0.41739312",
"0.41736522",
"0.41624534",
"0.4155579",
"0.41541693",
"0.4149737",
"0.4145115",
"0.41425386",
"0.41343343",
"0.4122071",
"0.41210762",
"0.41208863",
"0.41193604",
"0.4117796",
"0.4117185",
"0.41128907",
"0.4107171",
"0.410674",
"0.41000086",
"0.40981078",
"0.40965375",
"0.40951878",
"0.4090279",
"0.40886572",
"0.40859196",
"0.40854806",
"0.40840343",
"0.408167",
"0.40809634",
"0.40808403"
] | 0.5920519 | 0 |
Recov returns a compacted log of commands, following the requested [p, n] interval if 'Delayed' reduce is configured. On different period configurations, the entire reduced log is always returned. On persistent configuration (i.e. 'inmem' false) the entire log is loaded and then unmarshaled, consider using 'RecovBytes' calls instead. | func (l *ListHT) Recov(p, n uint64) ([]pb.Command, error) {
if n < p {
return nil, errors.New("invalid interval request, 'n' must be >= 'p'")
}
l.mu.RLock()
defer l.mu.RUnlock()
if err := l.mayExecuteLazyReduce(p, n); err != nil {
return nil, err
}
return l.retrieveLog()
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (l *ListHT) RecovBytes(p, n uint64) ([]byte, error) {\n\tif n < p {\n\t\treturn nil, errors.New(\"invalid interval request, 'n' must be >= 'p'\")\n\t}\n\tl.mu.RLock()\n\tdefer l.mu.RUnlock()\n\n\tif err := l.mayExecuteLazyReduce(p, n); err != nil {\n\t\treturn nil, err\n\t}\n\treturn l.retrieveRawLog(p, n)\n}",
"func (st Status) Repr() string {\n\tvar sb strings.Builder\n\n\tsb.WriteString(fmt.Sprintf(\"> processing node %q\\n\", st.NodeName))\n\tsb.WriteString(fmt.Sprintf(\"> processing %d pods\\n\", len(st.Pods)))\n\tfor _, pod := range st.Pods {\n\t\tsb.WriteString(\"+ \" + pod.Namespace + \"/\" + pod.Name + \"\\n\")\n\t}\n\n\tsb.WriteString(\"= \" + st.FingerprintComputed + \"\\n\")\n\tif st.FingerprintExpected != \"\" {\n\t\tsb.WriteString(\"V \" + st.FingerprintExpected + \"\\n\")\n\t}\n\n\treturn sb.String()\n}",
"func RetainLogInterval(log *[]pb.Command, p, n uint64) []pb.Command {\n\tcmds := make([]pb.Command, 0, n-p)\n\n\t// TODO: Later improve retrieve algorithm, exploiting the pre-ordering of\n\t// commands based on c.Id. The idea is to simply identify the first and last\n\t// underlying indexes and return a subslice copy.\n\tfor _, c := range *log {\n\t\tif c.Id >= p && c.Id <= n {\n\t\t\tcmds = append(cmds, c)\n\t\t}\n\t}\n\treturn cmds\n}",
"func getCostEstimationLogs(ctx context.Context, client *tfe.Client, r *tfe.Run) error {\n\tif r.CostEstimate == nil {\n\t\treturn nil\n\t}\n\tmsgPrefix := \"Cost estimation\"\n\tstarted := time.Now()\n\tupdated := started\n\tfor i := 0; ; i++ {\n\t\t// select {\n\t\t// case <-stopCtx.Done():\n\t\t// \treturn stopCtx.Err()\n\t\t// case <-cancelCtx.Done():\n\t\t// \treturn cancelCtx.Err()\n\t\t// case <-time.After(backoff(backoffMin, backoffMax, i)):\n\t\t// }\n\n\t\t// Retrieve the cost estimate to get its current status.\n\t\tce, err := client.CostEstimates.Read(ctx, r.CostEstimate.ID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// If the run is canceled or errored, but the cost-estimate still has\n\t\t// no result, there is nothing further to render.\n\t\tif ce.Status != tfe.CostEstimateFinished {\n\t\t\tif r.Status == tfe.RunCanceled || r.Status == tfe.RunErrored {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\t// checking if i == 0 so as to avoid printing this starting horizontal-rule\n\t\t// every retry, and that it only prints it on the first (i=0) attempt.\n\t\tif i == 0 {\n\t\t\tfmt.Println(\"------------------------------------------------------------------------\")\n\t\t}\n\n\t\tswitch ce.Status {\n\t\tcase tfe.CostEstimateFinished:\n\t\t\tdelta, err := strconv.ParseFloat(ce.DeltaMonthlyCost, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tsign := \"+\"\n\t\t\tif delta < 0 {\n\t\t\t\tsign = \"-\"\n\t\t\t}\n\n\t\t\tdeltaRepr := strings.Replace(ce.DeltaMonthlyCost, \"-\", \"\", 1)\n\n\t\t\tfmt.Println(msgPrefix + \":\")\n\t\t\tfmt.Printf(\"Resources: %d of %d estimated\", ce.MatchedResourcesCount, ce.ResourcesCount)\n\t\t\tfmt.Printf(\" $%s/mo %s$%s\", ce.ProposedMonthlyCost, sign, deltaRepr)\n\n\t\t\tif len(r.PolicyChecks) == 0 && r.HasChanges {\n\t\t\t\tfmt.Println(\"------------------------------------------------------------------------\")\n\t\t\t}\n\n\t\t\t// if b.CLI != nil {\n\t\t\t// \tb.CLI.Output(b.Colorize().Color(msgPrefix + \":\"))\n\t\t\t// \tb.CLI.Output(b.Colorize().Color(fmt.Sprintf(\"Resources: %d of %d estimated\", ce.MatchedResourcesCount, ce.ResourcesCount)))\n\t\t\t// \tb.CLI.Output(b.Colorize().Color(fmt.Sprintf(\" $%s/mo %s$%s\", ce.ProposedMonthlyCost, sign, deltaRepr)))\n\n\t\t\t// \tif len(r.PolicyChecks) == 0 && r.HasChanges && op.Type == backend.OperationTypeApply {\n\t\t\t// \t\tb.CLI.Output(\"------------------------------------------------------------------------\")\n\t\t\t// \t}\n\t\t\t// }\n\n\t\t\treturn nil\n\t\tcase tfe.CostEstimatePending, tfe.CostEstimateQueued:\n\t\t\t// Check if 30 seconds have passed since the last update.\n\t\t\tcurrent := time.Now()\n\t\t\tif i == 0 || current.Sub(updated).Seconds() > 30 {\n\t\t\t\tupdated = current\n\t\t\t\telapsed := \"\"\n\n\t\t\t\t// Calculate and set the elapsed time.\n\t\t\t\tif i > 0 {\n\t\t\t\t\telapsed = fmt.Sprintf(\n\t\t\t\t\t\t\" (%s elapsed)\", current.Sub(started).Truncate(30*time.Second))\n\t\t\t\t}\n\t\t\t\tfmt.Println(msgPrefix + \":\")\n\t\t\t\tfmt.Println(\"Waiting for cost estimate to complete...\" + elapsed)\n\t\t\t}\n\t\t\tcontinue\n\t\tcase tfe.CostEstimateSkippedDueToTargeting:\n\t\t\tfmt.Println(msgPrefix + \":\")\n\t\t\tfmt.Println(\"Not available for this plan, because it was created with the -target option.\")\n\t\t\tfmt.Println(\"------------------------------------------------------------------------\")\n\t\t\treturn nil\n\t\tcase tfe.CostEstimateErrored:\n\t\t\tfmt.Println(msgPrefix + \" errored.\")\n\t\t\tfmt.Println(\"------------------------------------------------------------------------\")\n\t\t\treturn nil\n\t\tcase tfe.CostEstimateCanceled:\n\t\t\treturn errors.New(msgPrefix + \" canceled.\")\n\t\tdefault:\n\t\t\treturn errors.New(\"Unknown or unexpected cost estimate state: \" + string(ce.Status))\n\t\t}\n\t}\n}",
"func New(cfg *Config) (*CirconusMetrics, error) {\n\n\tif cfg == nil {\n\t\treturn nil, errors.New(\"invalid configuration (nil)\")\n\t}\n\n\tcm := &CirconusMetrics{\n\t\tcounters: make(map[string]uint64),\n\t\tcounterFuncs: make(map[string]func() uint64),\n\t\tgauges: make(map[string]interface{}),\n\t\tgaugeFuncs: make(map[string]func() int64),\n\t\thistograms: make(map[string]*Histogram),\n\t\ttext: make(map[string]string),\n\t\ttextFuncs: make(map[string]func() string),\n\t\tcustom: make(map[string]Metric),\n\t\tlastMetrics: &prevMetrics{},\n\t}\n\n\t// Logging\n\t{\n\t\tcm.Debug = cfg.Debug\n\t\tcm.DumpMetrics = cfg.DumpMetrics\n\t\tcm.Log = cfg.Log\n\n\t\tif (cm.Debug || cm.DumpMetrics) && cm.Log == nil {\n\t\t\tcm.Log = log.New(os.Stderr, \"\", log.LstdFlags)\n\t\t}\n\t\tif cm.Log == nil {\n\t\t\tcm.Log = log.New(ioutil.Discard, \"\", log.LstdFlags)\n\t\t}\n\t}\n\n\t// Flush Interval\n\t{\n\t\tfi := defaultFlushInterval\n\t\tif cfg.Interval != \"\" {\n\t\t\tfi = cfg.Interval\n\t\t}\n\n\t\tdur, err := time.ParseDuration(fi)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"parsing flush interval\")\n\t\t}\n\t\tcm.flushInterval = dur\n\t}\n\n\t// metric resets\n\n\tcm.resetCounters = true\n\tif cfg.ResetCounters != \"\" {\n\t\tsetting, err := strconv.ParseBool(cfg.ResetCounters)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"parsing reset counters\")\n\t\t}\n\t\tcm.resetCounters = setting\n\t}\n\n\tcm.resetGauges = true\n\tif cfg.ResetGauges != \"\" {\n\t\tsetting, err := strconv.ParseBool(cfg.ResetGauges)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"parsing reset gauges\")\n\t\t}\n\t\tcm.resetGauges = setting\n\t}\n\n\tcm.resetHistograms = true\n\tif cfg.ResetHistograms != \"\" {\n\t\tsetting, err := strconv.ParseBool(cfg.ResetHistograms)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"parsing reset histograms\")\n\t\t}\n\t\tcm.resetHistograms = setting\n\t}\n\n\tcm.resetText = true\n\tif cfg.ResetText != \"\" {\n\t\tsetting, err := strconv.ParseBool(cfg.ResetText)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"parsing reset text\")\n\t\t}\n\t\tcm.resetText = setting\n\t}\n\n\t// check manager\n\t{\n\t\tcfg.CheckManager.Debug = cm.Debug\n\t\tcfg.CheckManager.Log = cm.Log\n\n\t\tcheck, err := checkmgr.New(&cfg.CheckManager)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"creating new check manager\")\n\t\t}\n\t\tcm.check = check\n\t}\n\n\t// start initialization (serialized or background)\n\tif err := cm.check.Initialize(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// if automatic flush is enabled, start it.\n\t// NOTE: submit will jettison metrics until initialization has completed.\n\tif cm.flushInterval > time.Duration(0) {\n\t\tgo func() {\n\t\t\tfor range time.NewTicker(cm.flushInterval).C {\n\t\t\t\tcm.Flush()\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn cm, nil\n}",
"func Cumulative(ref string, metricType string, options ...Option) *Stackdriver {\n\treturn newMetric(ref, \"CUMULATIVE\", metricType, options...)\n}",
"func startContinuousLog(dir string, sleepCap time.Duration, restart func()) {\n\t// Create the folder for all of the profiling results.\n\terr := os.MkdirAll(dir, 0700)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\t// Continuously log statistics about the running Sia application.\n\tgo func() {\n\t\t// Create the logger.\n\t\tlog, err := persist.NewFileLogger(filepath.Join(dir, \"continuousStats.log\"))\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Stats logging failed:\", err)\n\t\t\treturn\n\t\t}\n\t\t// Collect statistics in an infinite loop.\n\t\tsleepTime := time.Second * 10\n\t\tfor {\n\t\t\t// Sleep for an exponential amount of time each iteration, this\n\t\t\t// keeps the size of the log small while still providing lots of\n\t\t\t// information.\n\t\t\trestart()\n\t\t\ttime.Sleep(sleepTime)\n\t\t\tsleepTime = time.Duration(1.2 * float64(sleepTime))\n\t\t\tif sleepCap != 0*time.Second && sleepTime > sleepCap {\n\t\t\t\tsleepTime = sleepCap\n\t\t\t}\n\t\t\tvar m runtime.MemStats\n\t\t\truntime.ReadMemStats(&m)\n\t\t\tlog.Printf(\"\\n\\tGoroutines: %v\\n\\tAlloc: %v\\n\\tTotalAlloc: %v\\n\\tHeapAlloc: %v\\n\\tHeapSys: %v\\n\", runtime.NumGoroutine(), m.Alloc, m.TotalAlloc, m.HeapAlloc, m.HeapSys)\n\t\t}\n\t}()\n}",
"func (a *agent) reconcile() {\n\treconcileStartTime := time.Now()\n\tr := reconciler.New(a.registry)\n\tstatus := r.Reconcile(a.ctx, a.currentState, a.intendedState)\n\ta.currentState = status.NewCurrentState\n\n\t// Update variables needed to resume reconciliation\n\t// after async operation(s).\n\tif status.AsyncOpsInProgress {\n\t\tlog.Debug(\"Some config operations continue in the background\")\n\t}\n\ta.cancelAsyncOps = status.CancelAsyncOps\n\ta.resumeReconciliation = status.ReadyToResume\n\ta.waitForAsyncOps = status.WaitForAsyncOps\n\n\t// Log every executed operation.\n\tfor _, opLog := range status.OperationLog {\n\t\tvar withErr string\n\t\tif opLog.Err != nil {\n\t\t\twithErr = fmt.Sprintf(\" with error: %v\", opLog.Err)\n\t\t}\n\t\tvar verb string\n\t\tif opLog.InProgress {\n\t\t\tverb = \"started async execution of\"\n\t\t} else {\n\t\t\tif opLog.StartTime.Before(reconcileStartTime) {\n\t\t\t\tverb = \"finalized async execution of\"\n\t\t\t} else {\n\t\t\t\t// synchronous operation\n\t\t\t\tverb = \"executed\"\n\t\t\t}\n\t\t}\n\t\tlog.Infof(\"State Reconciler %s %v for %v%s, content: %s\",\n\t\t\tverb, opLog.Operation, dg.Reference(opLog.Item),\n\t\t\twithErr, opLog.Item.String())\n\t}\n\n\t// Log transitions from no-error to error and vice-versa.\n\tvar failed, fixed []string\n\tfor _, opLog := range status.OperationLog {\n\t\titemRef := dg.Reference(opLog.Item)\n\t\tif opLog.Err != nil {\n\t\t\ta.failingItems[itemRef] = opLog.Err\n\t\t} else {\n\t\t\tdelete(a.failingItems, itemRef)\n\t\t}\n\t\tif opLog.PrevErr == nil && opLog.Err != nil {\n\t\t\tfailed = append(failed, fmt.Sprintf(\"%v (err: %v)\", itemRef, opLog.Err))\n\t\t}\n\t\tif opLog.PrevErr != nil && opLog.Err == nil {\n\t\t\tfixed = append(fixed, itemRef.String())\n\t\t}\n\t}\n\tif len(failed) > 0 {\n\t\tlog.Errorf(\"Newly failed config items: %s\",\n\t\t\tstrings.Join(failed, \", \"))\n\t}\n\tif len(fixed) > 0 {\n\t\tlog.Infof(\"Fixed config items: %s\",\n\t\t\tstrings.Join(fixed, \", \"))\n\t}\n}",
"func Recover(files []string) {\n\t//gurantee the time sequence is in right ordered\n\tsort.Slice(files, func(i, j int) bool {\n\t\treturn files[i] < files[j]\n\t})\n\n\t//read log items and recover them into DataItem\n\tdataJson := make([]logger.DataItem, 0)\n\tfor _, filename := range files {\n\t\tfile, err := os.Open(filename)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"file can't open\")\n\t\t}\n\n\t\tcontent, err := ioutil.ReadAll(file)\n\t\tif err != nil {\n\t\t\tlog.Println(\"file can't read\")\n\t\t}\n\n\t\titems := strings.Split(string(content), \"\\r\\n\")\n\t\tfor _, jsonitem := range items {\n\t\t\tdata := logger.DataItem{}\n\n\t\t\terr = json.Unmarshal([]byte(jsonitem), &data)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"unmarshal some data fail\")\n\t\t\t}\n\n\t\t\tdataJson = append(dataJson, data)\n\t\t}\n\t}\n\n\t//recover the dataset status\n\tfor _, data := range dataJson {\n\t\tif data.Commandtype == logger.SET {\n\t\t\tnow := time.Now().Unix()\n\t\t\tif now < data.Expire {\n\t\t\t\tstore.SetValue(data.Key, data.Value, time.Duration(data.Expire-now))\n\t\t\t}\n\t\t}\n\t}\n}",
"func recalcRecommit(minRecommit, prev time.Duration, target float64, inc bool) time.Duration {\n\tvar (\n\t\tprevF = float64(prev.Nanoseconds())\n\t\tnext float64\n\t)\n\tif inc {\n\t\tnext = prevF*(1-intervalAdjustRatio) + intervalAdjustRatio*(target+intervalAdjustBias)\n\t\tmax := float64(maxRecommitInterval.Nanoseconds())\n\t\tif next > max {\n\t\t\tnext = max\n\t\t}\n\t} else {\n\t\tnext = prevF*(1-intervalAdjustRatio) + intervalAdjustRatio*(target-intervalAdjustBias)\n\t\tmin := float64(minRecommit.Nanoseconds())\n\t\tif next < min {\n\t\t\tnext = min\n\t\t}\n\t}\n\treturn time.Duration(int64(next))\n}",
"func (r *ConfigAuditReportReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\t// your logic here\n\t// Fetch the ConfigAuditReport instance\n\tinstance := &aquasecurityv1alpha1.ConfigAuditReport{}\n\terr := r.Client.Get(context.TODO(), req.NamespacedName, instance)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// Request object not found, could have been deleted after reconcile request.\n\t\t\t// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.\n\t\t\t// Return and don't requeue\n\t\t\treturn reconcile.Result{}, nil\n\t\t}\n\t\t// Error reading the object - requeue the request.\n\t\treturn reconcile.Result{}, err\n\t}\n\n\tworkloadInfo, err := r.getWorkloadInfo(instance)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\t// if !instance.ObjectMeta.DeletionTimestamp.IsZero() {\n\t// \t// The object is not being deleted, so do nothing\n\t// \tlogger.Info(\"Remove the original report\")\n\t// \tlogger.Info(\"workloadInfo\")\n\t// \terr := r.removeReport(workloadInfo)\n\t// \tif err != nil {\n\t// \t\treturn reconcile.Result{}, err\n\t// \t}\n\t// \treturn reconcile.Result{}, nil\n\t// }\n\n\t// examine DeletionTimestamp to determine if object is under deletion\n\tif instance.ObjectMeta.DeletionTimestamp.IsZero() {\n\t\t// The object is not being deleted, so if it does not have our finalizer,\n\t\t// then lets add the finalizer and update the object. This is equivalent\n\t\t// registering our finalizer.\n\t\tif !containsString(instance.GetFinalizers(), finalizerName) {\n\t\t\taddFinalizer(instance, finalizerName)\n\t\t\tif err := r.Client.Update(context.TODO(), instance); err != nil {\n\t\t\t\treturn reconcile.Result{}, err\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// The object is being deleted\n\t\tif containsString(instance.GetFinalizers(), finalizerName) {\n\t\t\t// our finalizer is present, so lets handle any external dependency\n\t\t\tif err := r.removeReport(workloadInfo); err != nil {\n\t\t\t\t// if fail to delete the external dependency here, return with error\n\t\t\t\t// so that it can be retried\n\t\t\t\treturn reconcile.Result{}, err\n\t\t\t}\n\n\t\t\t// remove our finalizer from the list and update it.\n\t\t\tremoveFinalizer(instance, finalizerName)\n\t\t\tif err := r.Client.Update(context.TODO(), instance); err != nil {\n\t\t\t\treturn reconcile.Result{}, err\n\t\t\t}\n\t\t}\n\n\t\t// Stop reconciliation as the item is being deleted\n\t\treturn reconcile.Result{}, nil\n\t}\n\n\terr = r.generateReport(ctx, workloadInfo)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\treturn ctrl.Result{}, nil\n}",
"func (r *KonfigurationReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\treqLogger := log.FromContext(ctx)\n\treconcileStart := time.Now()\n\n\treqLogger.Info(\"Reconciling konfiguration\")\n\n\t// Look up the konfiguration that triggered this request\n\tkonfig := &konfigurationv1.Konfiguration{}\n\tif err := r.Client.Get(ctx, req.NamespacedName, konfig); err != nil {\n\t\t// Check if object was deleted\n\t\tif client.IgnoreNotFound(err) == nil {\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Record suspended status metric\n\tdefer r.recordSuspension(ctx, konfig)\n\n\t// Add our finalizer if it does not exist\n\tif !controllerutil.ContainsFinalizer(konfig, konfigurationv1.KonfigurationFinalizer) {\n\t\treqLogger.Info(\"Registering finalizer to Konfiguration\")\n\t\tcontrollerutil.AddFinalizer(konfig, konfigurationv1.KonfigurationFinalizer)\n\t\tif err := r.Update(ctx, konfig); err != nil {\n\t\t\treqLogger.Error(err, \"failed to register finalizer\")\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t}\n\n\t// Examine if the object is under deletion\n\tif !konfig.ObjectMeta.DeletionTimestamp.IsZero() {\n\t\treturn r.reconcileDelete(ctx, konfig)\n\t}\n\n\t// Check if the konfiguration is suspended\n\tif konfig.IsSuspended() {\n\t\treturn ctrl.Result{\n\t\t\tRequeueAfter: konfig.GetInterval(),\n\t\t}, nil\n\t}\n\n\t// Get the revision and the path we are going to operate on\n\trevision, path, clean, err := r.prepareSource(ctx, konfig)\n\tif err != nil {\n\t\tr.recordReadiness(ctx, konfig)\n\t\treturn ctrl.Result{\n\t\t\tRequeueAfter: konfig.GetRetryInterval(),\n\t\t}, nil\n\t}\n\tdefer clean()\n\n\t// Check if there are any dependencies and that they are all ready\n\tif err := r.checkDependencies(ctx, konfig); err != nil {\n\t\tif statusErr := konfig.SetNotReady(ctx, r.Client, konfigurationv1.NewStatusMeta(\n\t\t\trevision, meta.DependencyNotReadyReason, err.Error(),\n\t\t)); statusErr != nil {\n\t\t\treqLogger.Error(err, \"failed to update status for dependency not ready\")\n\t\t}\n\t\tmsg := fmt.Sprintf(\"Dependencies do not meet ready condition, retrying in %s\", r.dependencyRequeueDuration.String())\n\t\treqLogger.Info(msg)\n\t\tr.event(ctx, konfig, &EventData{\n\t\t\tRevision: revision,\n\t\t\tSeverity: events.EventSeverityInfo,\n\t\t\tMessage: msg,\n\t\t})\n\t\tr.recordReadiness(ctx, konfig)\n\t\treturn ctrl.Result{RequeueAfter: r.dependencyRequeueDuration}, nil\n\t}\n\n\t// record reconciliation duration\n\tif r.MetricsRecorder != nil {\n\t\tobjRef, err := reference.GetReference(r.Scheme, konfig)\n\t\tif err != nil {\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\tdefer r.MetricsRecorder.RecordDuration(*objRef, reconcileStart)\n\t}\n\n\t// set the status to progressing\n\tif err := konfig.SetProgressing(ctx, r.Client); err != nil {\n\t\treqLogger.Error(err, \"unable to update status to progressing\")\n\t\treturn ctrl.Result{Requeue: true}, err\n\t}\n\tr.recordReadiness(ctx, konfig)\n\n\t// Do reconciliation\n\tsnapshot, err := r.reconcile(ctx, konfig, revision, path)\n\tif err != nil {\n\t\treqLogger.Error(err, \"Error during reconciliation\")\n\t\tr.event(ctx, konfig, &EventData{\n\t\t\tRevision: revision,\n\t\t\tSeverity: events.EventSeverityError,\n\t\t\tMessage: err.Error(),\n\t\t})\n\t\treturn ctrl.Result{\n\t\t\tRequeueAfter: konfig.GetRetryInterval(),\n\t\t}, nil\n\t}\n\n\tupdated := konfig.Status.Snapshot == nil || snapshot.Checksum != konfig.Status.Snapshot.Checksum\n\n\t// Set the konfiguration as ready\n\tmsg := fmt.Sprintf(\"Applied revision: %s\", revision)\n\tif err := konfig.SetReady(ctx, r.Client, snapshot, konfigurationv1.NewStatusMeta(\n\t\trevision, meta.ReconciliationSucceededReason, msg),\n\t); err != nil {\n\t\treturn ctrl.Result{Requeue: true}, err\n\t}\n\n\treqLogger.Info(fmt.Sprintf(\"Reconcile finished, next run in %s\", konfig.GetInterval().String()), \"Revision\", revision)\n\n\tif updated {\n\t\tr.event(ctx, konfig, &EventData{\n\t\t\tRevision: revision,\n\t\t\tSeverity: events.EventSeverityInfo,\n\t\t\tMessage: \"Update Complete\",\n\t\t\tMetadata: map[string]string{\n\t\t\t\t\"commit_status\": \"update\",\n\t\t\t},\n\t\t})\n\t}\n\treturn ctrl.Result{\n\t\tRequeueAfter: konfig.GetInterval(),\n\t}, nil\n}",
"func logCommands(r cruntime.Manager, bs bootstrapper.Bootstrapper, cfg config.ClusterConfig, length int, follow bool) map[string]string {\n\tcmds := bs.LogCommands(cfg, bootstrapper.LogOptions{Lines: length, Follow: follow})\n\tpods := importantPods\n\taddonPods := enabledAddonPods(cfg)\n\tpods = append(pods, addonPods...)\n\tfor _, pod := range pods {\n\t\tids, err := r.ListContainers(cruntime.ListContainersOptions{Name: pod})\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to list containers for %q: %v\", pod, err)\n\t\t\tcontinue\n\t\t}\n\t\tklog.Infof(\"%d containers: %s\", len(ids), ids)\n\t\tif len(ids) == 0 {\n\t\t\tklog.Warningf(\"No container was found matching %q\", pod)\n\t\t\tcontinue\n\t\t}\n\t\tfor _, i := range ids {\n\t\t\tkey := fmt.Sprintf(\"%s [%s]\", pod, i)\n\t\t\tcmds[key] = r.ContainerLogCmd(i, length, follow)\n\t\t}\n\t}\n\tcmds[r.Name()] = r.SystemLogCmd(length)\n\tcmds[\"container status\"] = cruntime.ContainerStatusCommand()\n\n\treturn cmds\n}",
"func CMOVQOS(mr, r operand.Op) { ctx.CMOVQOS(mr, r) }",
"func (l *Log) Replay() <-chan (*schema.Mutation) {\n\tch := make(chan (*schema.Mutation), 1000)\n\tgo func() {\n\t\tf, err := os.OpenFile(l.filename, os.O_RDONLY, 0660)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdefer f.Close()\n\t\tdec := json.NewDecoder(f)\n\t\tfor {\n\t\t\tvar m schema.Mutation\n\t\t\tif err := dec.Decode(&m); err == io.EOF {\n\t\t\t\tbreak\n\t\t\t} else if err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tch <- &m\n\t\t}\n\t\tclose(ch)\n\t}()\n\treturn ch\n}",
"func TestTrimMeasurementHistory(t *testing.T) {\n\tf := newFixture(t)\n\tdefer f.Close()\n\tc, _, _ := f.newController(noResyncPeriodFunc)\n\n\tf.provider.On(\"GarbageCollect\", mock.Anything, mock.Anything, mock.Anything).Return(nil)\n\n\t{\n\t\trun := newRun()\n\t\terr := c.garbageCollectMeasurements(run, map[string]*v1alpha1.MeasurementRetention{}, 2)\n\t\tassert.Nil(t, err)\n\t\tassert.Len(t, run.Status.MetricResults[0].Measurements, 1)\n\t\tassert.Equal(t, \"1\", run.Status.MetricResults[0].Measurements[0].Value)\n\t\tassert.Len(t, run.Status.MetricResults[1].Measurements, 2)\n\t\tassert.Equal(t, \"2\", run.Status.MetricResults[1].Measurements[0].Value)\n\t\tassert.Equal(t, \"3\", run.Status.MetricResults[1].Measurements[1].Value)\n\t}\n\t{\n\t\trun := newRun()\n\t\terr := c.garbageCollectMeasurements(run, map[string]*v1alpha1.MeasurementRetention{}, 1)\n\t\tassert.Nil(t, err)\n\t\tassert.Len(t, run.Status.MetricResults[0].Measurements, 1)\n\t\tassert.Equal(t, \"1\", run.Status.MetricResults[0].Measurements[0].Value)\n\t\tassert.Len(t, run.Status.MetricResults[1].Measurements, 1)\n\t\tassert.Equal(t, \"3\", run.Status.MetricResults[1].Measurements[0].Value)\n\t}\n\t{\n\t\trun := newRun()\n\t\tvar measurementRetentionMetricsMap = map[string]*v1alpha1.MeasurementRetention{}\n\t\tmeasurementRetentionMetricsMap[\"metric2\"] = &v1alpha1.MeasurementRetention{MetricName: \"*\", Limit: 2}\n\t\terr := c.garbageCollectMeasurements(run, measurementRetentionMetricsMap, 1)\n\t\tassert.Nil(t, err)\n\t\tassert.Len(t, run.Status.MetricResults[0].Measurements, 1)\n\t\tassert.Equal(t, \"1\", run.Status.MetricResults[0].Measurements[0].Value)\n\t\tassert.Len(t, run.Status.MetricResults[1].Measurements, 2)\n\t\tassert.Equal(t, \"2\", run.Status.MetricResults[1].Measurements[0].Value)\n\t\tassert.Equal(t, \"3\", run.Status.MetricResults[1].Measurements[1].Value)\n\t}\n\t{\n\t\trun := newRun()\n\t\tvar measurementRetentionMetricsMap = map[string]*v1alpha1.MeasurementRetention{}\n\t\tmeasurementRetentionMetricsMap[\"metric2\"] = &v1alpha1.MeasurementRetention{MetricName: \"metric2\", Limit: 2}\n\t\terr := c.garbageCollectMeasurements(run, measurementRetentionMetricsMap, 1)\n\t\tassert.Nil(t, err)\n\t\tassert.Len(t, run.Status.MetricResults[0].Measurements, 1)\n\t\tassert.Equal(t, \"1\", run.Status.MetricResults[0].Measurements[0].Value)\n\t\tassert.Len(t, run.Status.MetricResults[1].Measurements, 2)\n\t\tassert.Equal(t, \"2\", run.Status.MetricResults[1].Measurements[0].Value)\n\t\tassert.Equal(t, \"3\", run.Status.MetricResults[1].Measurements[1].Value)\n\t}\n}",
"func (r *ConfigAuditReportReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\tlogger := log.FromContext(ctx)\n\n\t// your logic here\n\t// Fetch the ConfigAuditReport instance\n\tinstance := &aquasecurityv1alpha1.ConfigAuditReport{}\n\terr := r.Client.Get(context.TODO(), req.NamespacedName, instance)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// Request object not found, could have been deleted after reconcile request.\n\t\t\t// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.\n\t\t\t// Return and don't requeue\n\t\t\treturn reconcile.Result{}, nil\n\t\t}\n\t\t// Error reading the object - requeue the request.\n\t\treturn reconcile.Result{}, err\n\t}\n\n\tif !instance.ObjectMeta.DeletionTimestamp.IsZero() {\n\t\t// The object is not being deleted, so do nothing\n\t\treturn reconcile.Result{}, nil\n\t}\n\n\t// get owner of instance, maybe Replicaset, Pod .etc\n\tvar ownerType, ownerName string\n\tfor _, ref := range instance.GetOwnerReferences() {\n\t\townerType = ref.Kind\n\t\townerName = ref.Name\n\t\tbreak\n\t}\n\n\tcommand := r.buildCommand(ownerType, ownerName)\n\tlogger.Info(command)\n\t// try to run the command here: \"starboard get report deployment/nginx > nginx.deploy.html\"\n\tcmd := exec.Command(\"sh\", \"-c\", command)\n\tlogger.Info(\"Exporting report and waiting for it to finish...\")\n\terr = cmd.Run()\n\tif err != nil {\n\t\tlogger.Error(err, \"Exporting report finished with error\")\n\t\treturn reconcile.Result{}, err\n\t}\n\n\treturn ctrl.Result{}, nil\n}",
"func (s *Server) ReopenContainerLog(ctx context.Context, in *pb.ReopenContainerLogRequest) (*pb.ReopenContainerLogResponse, error) {\n\treturn nil, fmt.Errorf(\"not yet implemented\")\n}",
"func (p *panicsToLog) Cron(f func()) func() {\n\n\treturn func() {\n\t\t// Prevent panic error\n\t\tdefer func() {\n\t\t\tr := recover()\n\n\t\t\tif r != nil {\n\n\t\t\t\tstack := \"Stack:\\n\" + string(debug.Stack())\n\n\t\t\t\tlog.Println(r)\n\t\t\t\tlog.Println(stack)\n\t\t\t}\n\t\t}()\n\n\t\tf()\n\t}\n\n}",
"func Critical(format string, v ...interface{}) {\n\tmsg := fmt.Sprintf(\"[C]\"+format, v...)\n\tlog.Println(msg)\n}",
"func (l *LogReader) Refresh() *[][]string {\n\tfile, err := l.openLogFile()\n\tif err != nil {\n\t\treturn &[][]string{}\n\t}\n\tdefer file.Close()\n\n\tdata, offset := readLogFileFromOffsetUp(file, l.config.Seperator, l.Capacity, l.currentOffset[l.FileIndex] + l.Capacity)\n\tl.currentOffset[l.FileIndex] = offset\n\treturn data\n}",
"func BenchmarkRogger(b *testing.B) {\n\tSetLevel(DEBUG)\n\tbs := make([]byte, 1024)\n\tlongmsg := string(bs)\n\tlg := GetLogger(\"rogger\")\n\tlg.SetFileRoller(\"./logs\", 10, 100)\n\tfor i := 0; i < b.N; i++ {\n\t\tlg.Debug(\"debugxxxxxxxxxxxxxxxxxxxxxxxxxxx\")\n\t\tlg.Info(longmsg)\n\t\tlg.Warn(\"warn\")\n\t\tlg.Error(\"ERROR\")\n\t}\n\tFlushLogger()\n}",
"func makeReconfigureUndoLog(seq int, config shardmaster.Config) UndoInfo {\n return UndoInfo{IsReconfigure:true, Seq:seq, Config:config}\n}",
"func CMOVQCS(mr, r operand.Op) { ctx.CMOVQCS(mr, r) }",
"func (eval *evaluator) ReplicateLog(ctIn *Ciphertext, batchSize, n int, ctOut *Ciphertext) {\n\teval.InnerSumLog(ctIn, -batchSize, n, ctOut)\n}",
"func (s *Server) RotateLog() {\n\n\tif s.logch == nil {\n\t\treturn\n\t}\n\n\t// send empty msg as signal\n\ts.logch <- &Collect{}\n}",
"func CMOVQPS(mr, r operand.Op) { ctx.CMOVQPS(mr, r) }",
"func (m KernelModule) Remediate() (status CheckStatus, msg string, err error) {\n\treturn runCheck(m, \"remediate\")\n}",
"func (d *peerMsgHandler) handleCompactLogMsg(req *raft_cmdpb.RaftCmdRequest) *raft_cmdpb.RaftCmdResponse {\n\t// handle logGCCompact\n\t// construct response\n\tresponse := new(raft_cmdpb.CompactLogResponse)\n\tadminResponse := &raft_cmdpb.AdminResponse{\n\t\tCmdType: raft_cmdpb.AdminCmdType_CompactLog,\n\t\tCompactLog: response,\n\t}\n\tcmdResponse := raftAdminCmdResponse(adminResponse, d.Term(), nil)\n\t// check whether need to be compacted\n\tcompactIdx := req.AdminRequest.CompactLog.CompactIndex\n\tif d.peerStorage.applyState.TruncatedState.Index >= compactIdx {\n\t\tlog.Debugf(\"the log is already compacted\")\n\t\treturn cmdResponse\n\t}\n\tlog.Debugf(\"%s update compacted before, [%s]\", d.Tag, d.peerStorage.applyState.TruncatedState)\n\t// update state\n\tfirstIdx := d.peerStorage.updateMetaByLogCompact(req)\n\t// update memory log\n\td.RaftGroup.CompactMemoryLogEntries(req.AdminRequest.CompactLog.CompactIndex, req.AdminRequest.CompactLog.CompactTerm)\n\t// assign a asynchronously task\n\td.ctx.raftLogGCTaskSender <- &runner.RaftLogGCTask{\n\t\tRaftEngine: d.peerStorage.Engines.Raft,\n\t\tRegionID: d.regionId,\n\t\tStartIdx: firstIdx,\n\t\tEndIdx: compactIdx + 1,\n\t}\n\tlog.Debugf(\"%s update compacted, [%s]\", d.Tag, d.peerStorage.applyState.TruncatedState)\n\t// TODO seems this variable is useless\n\td.peer.LastCompactedIdx = compactIdx\n\t_, _ = d.peerStorage.Snapshot()\n\t// TODO there is no need to call snapshot now after log compact.\n\t// TODO when we figure out how to cache the snapshot, then we can think about this\n\t//snapshot, err := d.peerStorage.Snapshot()\n\t//if err == nil {\n\t//\t// update the LastSnapshot\n\t//\t// if the generated snapshot is earlier than the compact, regenerating\n\t//\tif compactIdx > snapshot.Metadata.Index {\n\t//\t\tlog.Debugf(\"%s call Snapshot.\", d.Tag)\n\t//\t\t_, _ = d.peerStorage.Snapshot()\n\t//\t}else{\n\t//\t\t// LastSnapshot only be updated when new snapshot index is greater than previous one\n\t//\t\td.RaftGroup.UpdateLastSnapshot(&snapshot)\n\t//\t}\n\t//} else {\n\t//\tlog.Errorf(\" %s snapshot is still generating when executing compactLog command.\", d.Tag)\n\t//}\n\treturn cmdResponse\n}",
"func (l *ListHT) ReduceLog(p, n uint64) error {\n\tcmds, err := ApplyReduceAlgo(l, l.config.Alg, p, n)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn l.updateLogState(cmds, p, n, false)\n}",
"func (req *Request) Repr() string {\n\treturn fmt.Sprintf(\"(REQ:%s)\", req.URL)\n}",
"func (r *ProcChaosReconciler) Reconcile(req ctrl.Request) (result ctrl.Result, err error) {\n\tlog := r.Log.WithValues(\"procchaos\", req.NamespacedName)\n\n\t// your logic here\n\n\tvar procChaos naglfarv1.ProcChaos\n\tif err = r.Get(r.Ctx, req.NamespacedName, &procChaos); err != nil {\n\t\tlog.Error(err, \"unable to fetch ProcChaos\")\n\n\t\t// we'll ignore not-found errors, since they can't be fixed by an immediate\n\t\t// requeue (we'll need to wait for a new notification), and we can get them\n\t\t// on deleted requests.\n\t\terr = client.IgnoreNotFound(err)\n\t\treturn\n\t}\n\n\tvar request naglfarv1.TestResourceRequest\n\tif err = r.Get(r.Ctx, types.NamespacedName{Namespace: req.Namespace, Name: procChaos.Spec.Request}, &request); err != nil {\n\t\tlog.Error(err, fmt.Sprintf(\"unable to fetch Request(%s)\", procChaos.Spec.Request))\n\t\terr = client.IgnoreNotFound(err)\n\t\treturn\n\t}\n\n\tif request.Status.State != naglfarv1.TestResourceRequestReady {\n\t\tlog.Info(fmt.Sprintf(\"Request(%s) not ready\", procChaos.Spec.Request))\n\t\tresult.Requeue = true\n\t\tresult.RequeueAfter = time.Second\n\t\treturn\n\t}\n\n\tvar kill = func(task *naglfarv1.ProcChaosTask, state *naglfarv1.ProcChaosState) (killErr error) {\n\t\tstate.KilledNode, killErr = r.killProc(log, task, &request)\n\t\tif killErr != nil {\n\t\t\treturn\n\t\t}\n\t\tstate.KilledTime = util.NewTime(time.Now())\n\t\treturn\n\t}\n\n\tif len(procChaos.Status.States) < len(procChaos.Spec.Tasks) {\n\t\tstate := new(naglfarv1.ProcChaosState)\n\t\ttask := procChaos.Spec.Tasks[len(procChaos.Status.States)]\n\t\tprocChaos.Status.States = append(procChaos.Status.States, state)\n\n\t\tif task.Period != \"\" {\n\t\t\tstate.KilledTime = util.NewTime(time.Now())\n\t\t} else if err = kill(task, state); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\terr = r.Status().Update(r.Ctx, &procChaos)\n\t\treturn\n\t}\n\n\tvar durations []time.Duration\n\tfor index, task := range procChaos.Spec.Tasks {\n\t\tif task.Period == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tstate := procChaos.Status.States[index]\n\t\tduration := task.Period.Unwrap() - time.Since(state.KilledTime.Unwrap())\n\t\tif duration <= 0 {\n\t\t\tif err = kill(task, state); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr = r.Status().Update(r.Ctx, &procChaos)\n\t\t\treturn\n\t\t}\n\t\tdurations = append(durations, duration)\n\t}\n\n\tminDuration := util.MinDuration(durations...)\n\n\tlog.Info(fmt.Sprintf(\"sleep for %s\", minDuration.String()))\n\tresult.Requeue = true\n\tresult.RequeueAfter = minDuration\n\treturn\n}",
"func (_CrToken *CrTokenFilterer) WatchReservesReduced(opts *bind.WatchOpts, sink chan<- *CrTokenReservesReduced) (event.Subscription, error) {\n\n\tlogs, sub, err := _CrToken.contract.WatchLogs(opts, \"ReservesReduced\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(CrTokenReservesReduced)\n\t\t\t\tif err := _CrToken.contract.UnpackLog(event, \"ReservesReduced\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}",
"func (r *CronJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error)",
"func (o *Options) Run() error {\n\terr := o.ValidateOptions()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"invalid options\")\n\t}\n\n\terr = o.GitStore.Setup()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to setup git store\")\n\t}\n\n\tgo func() {\n\t\terr := o.Web.Run()\n\t\tif err != nil {\n\t\t\tlogrus.WithError(err).Fatal(\"failed to serve http\")\n\t\t}\n\t}()\n\n\tticker := time.NewTicker(o.SyncDuration)\n\tquit := make(chan struct{})\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\toutput, err := o.DoSync()\n\t\t\t\tl := logrus.WithField(\"sync\", \"git\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tl = l.WithError(err)\n\t\t\t\t}\n\t\t\t\tl.Info(output)\n\n\t\t\tcase <-quit:\n\t\t\t\tticker.Stop()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tnamespace := o.Namespace\n\n\tlogrus.Infof(\"tailing logs of pods in namespace :%s\", namespace)\n\n\tctx := context.Background()\n\tkubeClient := o.KubeClient\n\n\to.Masker, err = masker.NewMasker(kubeClient, namespace, o.OperatorNamespace)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create masker\")\n\t}\n\n\tadded, removed, err := o.Watch(ctx, kubeClient.CoreV1().Pods(namespace), o.LabelSelector)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to set up watch\")\n\t}\n\n\ttails := make(map[string]*Tail)\n\n\tpodLogDir := filepath.Join(o.Dir, o.LogPath)\n\n\tgo func() {\n\t\tfor p := range added {\n\t\t\tid := p.GetID()\n\t\t\tif tails[id] != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttail := NewTail(o.Masker, podLogDir, p.Namespace, p.Pod, p.Container, p.App, o.Template, &TailOptions{\n\t\t\t\tTimestamps: o.Timestamps,\n\t\t\t\tSinceSeconds: int64(o.Since.Seconds()),\n\t\t\t\tExclude: o.Exclude,\n\t\t\t\tInclude: o.Include,\n\t\t\t\tNamespace: o.AllNamespaces,\n\t\t\t\tTailLines: o.TailLines,\n\t\t\t})\n\t\t\ttails[id] = tail\n\n\t\t\ttail.Start(ctx, kubeClient.CoreV1().Pods(p.Namespace))\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor p := range removed {\n\t\t\tid := p.GetID()\n\t\t\tif tails[id] == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttails[id].Close()\n\t\t\tdelete(tails, id)\n\t\t}\n\t}()\n\n\t<-ctx.Done()\n\n\treturn nil\n}",
"func CMOVQCC(mr, r operand.Op) { ctx.CMOVQCC(mr, r) }",
"func (p BaseLogCopy) Explain() string {\n\texplain := \"Collect New Relic log files (has overrides)\"\n\tif config.Flags.ShowOverrideHelp {\n\t\texplain += fmt.Sprintf(\"\\n%37s %s\", \" \", \"Override: logpath => set the path of the log file to collect (defaults to finding all logs)\")\n\t\texplain += fmt.Sprintf(\"\\n%37s %s\", \" \", \"Override: lastModifiedDate => in epochseconds, gathers logs newer than last modified date (defaults to now - 7 days)\")\n\t}\n\treturn explain\n}",
"func (f *RemoteRuntime) ReopenContainerLog(ctx context.Context, req *kubeapi.ReopenContainerLogRequest) (*kubeapi.ReopenContainerLogResponse, error) {\n\terr := f.RuntimeService.ReopenContainerLog(ctx, req.ContainerId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &kubeapi.ReopenContainerLogResponse{}, nil\n}",
"func POPCNTQ(mr, r operand.Op) { ctx.POPCNTQ(mr, r) }",
"func (_obj *Apichannels) Channels_getAdminLog(params *TLchannels_getAdminLog, _opt ...map[string]string) (ret Channels_AdminLogResults, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = params.WriteBlock(_os, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tvar _status map[string]string\n\tvar _context map[string]string\n\tif len(_opt) == 1 {\n\t\t_context = _opt[0]\n\t} else if len(_opt) == 2 {\n\t\t_context = _opt[0]\n\t\t_status = _opt[1]\n\t}\n\t_resp := new(requestf.ResponsePacket)\n\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"channels_getAdminLog\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\n\terr = ret.ReadBlock(_is, 0, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif len(_opt) == 1 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t} else if len(_opt) == 2 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t\tfor k := range _status {\n\t\t\tdelete(_status, k)\n\t\t}\n\t\tfor k, v := range _resp.Status {\n\t\t\t_status[k] = v\n\t\t}\n\n\t}\n\t_ = length\n\t_ = have\n\t_ = ty\n\treturn ret, nil\n}",
"func (r *AtReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\tlog := ctrllog.FromContext(ctx)\n\treqLogger := log.WithValues(\"namespace\", req.Namespace, \"at\", req.Name)\n\treqLogger.Info(\"=== Reconciling At\")\n\t// Fetch the At instance\n\tinstance := &cnatv1alpha1.At{}\n\terr := r.Get(context.TODO(), req.NamespacedName, instance)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// Request object not found, could have been deleted after reconcile request - return and don't requeue:\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\t\t// Error reading the object - requeue the request:\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// If no phase set, default to pending (the initial phase):\n\tif instance.Status.Phase == \"\" {\n\t\tinstance.Status.Phase = cnatv1alpha1.PhasePending\n\t}\n\n\t// Now let's make the main case distinction: implementing\n\t// the state diagram PENDING -> RUNNING -> DONE\n\tswitch instance.Status.Phase {\n\tcase cnatv1alpha1.PhasePending:\n\t\treqLogger.Info(\"Phase: PENDING\")\n\t\t// As long as we haven't executed the command yet, we need to check if it's time already to act:\n\t\treqLogger.Info(\"Checking schedule\", \"Target\", instance.Spec.Schedule)\n\t\t// Check if it's already time to execute the command with a tolerance of 2 seconds:\n\t\td, err := timeUntilSchedule(instance.Spec.Schedule)\n\t\tif err != nil {\n\t\t\treqLogger.Error(err, \"Schedule parsing failure\")\n\t\t\t// Error reading the schedule. Wait until it is fixed.\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\treqLogger.Info(\"Schedule parsing done\", \"diff\", fmt.Sprintf(\"%v\", d))\n\t\tif d > 0 {\n\t\t\t// Not yet time to execute the command, wait until the scheduled time\n\t\t\treturn reconcile.Result{RequeueAfter: d}, nil\n\t\t}\n\t\treqLogger.Info(\"It's time!\", \"Ready to execute\", instance.Spec.Command)\n\t\tinstance.Status.Phase = cnatv1alpha1.PhaseRunning\n\tcase cnatv1alpha1.PhaseRunning:\n\t\treqLogger.Info(\"Phase: RUNNING\")\n\t\tpod := newPodForCR(instance)\n\t\t// Set At instance as the owner and controller\n\t\tif err := controllerutil.SetControllerReference(instance, pod, r.Scheme); err != nil {\n\t\t\t// requeue with error\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\tfound := &corev1.Pod{}\n\t\terr = r.Get(context.TODO(), types.NamespacedName{Name: pod.Name, Namespace: pod.Namespace}, found)\n\t\t// Try to see if the pod already exists and if not\n\t\t// (which we expect) then create a one-shot pod as per spec:\n\t\tif err != nil && errors.IsNotFound(err) {\n\t\t\terr = r.Create(context.TODO(), pod)\n\t\t\tif err != nil {\n\t\t\t\t// requeue with error\n\t\t\t\treturn ctrl.Result{}, err\n\t\t\t}\n\t\t\treqLogger.Info(\"Pod launched\", \"name\", pod.Name)\n\t\t} else if err != nil {\n\t\t\t// requeue with error\n\t\t\treturn ctrl.Result{}, err\n\t\t} else if found.Status.Phase == corev1.PodFailed || found.Status.Phase == corev1.PodSucceeded {\n\t\t\treqLogger.Info(\"Container terminated\", \"reason\", found.Status.Reason, \"message\", found.Status.Message)\n\t\t\tinstance.Status.Phase = cnatv1alpha1.PhaseDone\n\t\t} else {\n\t\t\t// don't requeue because it will happen automatically when the pod status changes\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\tcase cnatv1alpha1.PhaseDone:\n\t\treqLogger.Info(\"Phase: DONE\")\n\t\treturn ctrl.Result{}, nil\n\tdefault:\n\t\treqLogger.Info(\"NOP\")\n\t\treturn ctrl.Result{}, nil\n\t}\n\n\t// Update the At instance, setting the status to the respective phase:\n\terr = r.Status().Update(context.TODO(), instance)\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Don't requeue. We should be reconcile because either the pod or the CR changes.\n\n\treturn ctrl.Result{}, nil\n}",
"func (r *Reporter) Crit(msg string, ctx ...interface{}) {\n\tif r.Logging != nil {\n\t\tr.Logging.Crit(msg, ctx...)\n\t}\n}",
"func (r *FlakeRegion) Culprits(cumProb float64, limit int) []Culprit {\n\tculprits := []Culprit{}\n\n\ttotal := 0.0\n\tfor t := r.First; t >= 0 && t > r.First-limit; t-- {\n\t\tp := r.StartedAt(t)\n\t\tculprits = append(culprits, Culprit{P: p, T: t})\n\t\ttotal += p\n\t\tif total > cumProb {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn culprits\n}",
"func (r *ReconcileReleaseManager) requeue(log logr.Logger, err error) (reconcile.Result, error) {\n\tif err != nil {\n\t\tlog.Error(err, \"An error occurred during reconciliation\")\n\t\treturn reconcile.Result{}, err\n\t}\n\tlog.Info(\"Requeuing\", \"duration\", r.config.RequeueAfter)\n\treturn reconcile.Result{RequeueAfter: r.config.RequeueAfter}, nil\n}",
"func (r *Reporter) Report() {\n\t//---------------------------------------------------\n\t// Report to console\n\t//---------------------------------------------------\n\tsort.Ints(r.nOrderPerSec)\n\tsort.Ints(r.nRequestPerSec)\n\tnOrderPerSecMax := MeanOfMaxFive(r.nOrderPerSec)\n\tnOrderPerSecMin := MeanOfMinFive(r.nOrderPerSec)\n\tnOrderPerSecMean := Mean(r.nOrderPerSec)\n\tnRequestPerSecMax := MeanOfMaxFive(r.nRequestPerSec)\n\tnRequestPerSecMin := MeanOfMinFive(r.nRequestPerSec)\n\tnRequestPerSecMean := Mean(r.nRequestPerSec)\n\tsort.Ints(r.nRequestPerSec)\n\tpayCostNanoseconds := []float64{}\n\tfor i := 0; i < len(r.payCosts); i++ {\n\t\tpayCostNanoseconds = append(payCostNanoseconds, float64(r.payCosts[i].Nanoseconds()))\n\t}\n\tsort.Float64s(payCostNanoseconds)\n\tmsTakenTotal := int(r.elapsed.Nanoseconds() / 1000000.0)\n\tmsPerOrder := MeanFloat64(payCostNanoseconds) / 1000000.0\n\tmsPerRequest := SumFloat64(payCostNanoseconds) / 1000000.0 / float64(r.nRequestOk)\n\t//---------------------------------------------------\n\t// Report to console\n\t//---------------------------------------------------\n\tfmt.Print(\"\\nStats\\n\")\n\tfmt.Printf(\"Concurrency level: %d\\n\", r.cocurrency)\n\tfmt.Printf(\"Time taken for tests: %dms\\n\", msTakenTotal)\n\tfmt.Printf(\"Complete requests: %d\\n\", r.nRequestOk)\n\tfmt.Printf(\"Failed requests: %d\\n\", r.nRequestErr)\n\tfmt.Printf(\"Complete orders: %d\\n\", r.nOrderOk)\n\tfmt.Printf(\"Failed orders: %d\\n\", r.nOrderErr)\n\tfmt.Printf(\"Time per request: %.2fms\\n\", msPerRequest)\n\tfmt.Printf(\"Time per order: %.2fms\\n\", msPerOrder)\n\tfmt.Printf(\"Request per second: %d (max) %d (min) %d(mean)\\n\", nRequestPerSecMax, nRequestPerSecMin, nRequestPerSecMean)\n\tfmt.Printf(\"Order per second: %d (max) %d (min) %d (mean)\\n\\n\", nOrderPerSecMax, nOrderPerSecMin, nOrderPerSecMean)\n\tfmt.Printf(\"Percentage of orders made within a certain time (ms)\\n\")\n\tif len(payCostNanoseconds) == 0 {\n\t\treturn\n\t}\n\tpercentages := []float64{10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 95.5, 96, 96.5, 97, 97.5, 98, 98.5, 99, 99.9, 99.99, 100}\n\tfor _, percentage := range percentages {\n\t\tidx := int(percentage * float64(len(payCostNanoseconds)) / float64(100.0))\n\t\tif idx > 0 {\n\t\t\tidx = idx - 1\n\t\t} else {\n\t\t\tidx = 0\n\t\t}\n\t\tpayCostNanosecond := payCostNanoseconds[idx]\n\t\tfmt.Printf(\"%.2f%%\\t%d ms\\n\", percentage, int(payCostNanosecond/1000000.0))\n\t}\n}",
"func CommandLog(conf Config, ctx, query Query) error {\n\tif query.Text == \"\" {\n\t\treturn errors.New(\"Task description required\")\n\t}\n\n\tts, err := LoadTaskSet(conf.Repo, conf.IDsFile, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx.PrintContextDescription()\n\tquery = query.Merge(ctx)\n\ttask := Task{\n\t\tWritePending: true,\n\t\tStatus: STATUS_RESOLVED,\n\t\tSummary: query.Text,\n\t\tTags: query.Tags,\n\t\tProject: query.Project,\n\t\tPriority: query.Priority,\n\t\tResolved: time.Now(),\n\t}\n\ttask = ts.MustLoadTask(task)\n\tts.SavePendingChanges()\n\tMustGitCommit(conf.Repo, \"Logged %s\", task)\n\n\treturn nil\n}",
"func Repl(mgr *proto.Manager, defaultCfg *proto.Configuration) {\n\tr := newRepl(mgr, defaultCfg)\n\n\tfmt.Println(help)\n\tfor {\n\t\tl, err := r.ReadLine()\n\t\tif errors.Is(err, io.EOF) {\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Failed to read line: %v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\targs, err := shlex.Split(l)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Failed to split command: %v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif len(args) < 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch args[0] {\n\t\tcase \"exit\":\n\t\t\tfallthrough\n\t\tcase \"quit\":\n\t\t\treturn\n\t\tcase \"help\":\n\t\t\tfmt.Println(help)\n\t\tcase \"rpc\":\n\t\t\tr.rpc(args[1:])\n\t\tcase \"qc\":\n\t\t\tr.qc(args[1:])\n\t\tcase \"cfg\":\n\t\t\tr.qcCfg(args[1:])\n\t\tcase \"mcast\":\n\t\t\tfallthrough\n\t\tcase \"multicast\":\n\t\t\tr.multicast(args[1:])\n\t\tcase \"nodes\":\n\t\t\tfmt.Println(\"Nodes: \")\n\t\t\tfor i, n := range mgr.Nodes() {\n\t\t\t\tfmt.Printf(\"%d: %s\\n\", i, n.Address())\n\t\t\t}\n\t\tdefault:\n\t\t\tfmt.Printf(\"Unknown command '%s'. Type 'help' to see available commands.\\n\", args[0])\n\t\t}\n\t}\n}",
"func Redoc(redoc *RedocOpts) Option {\n\treturn func(s *Service) {\n\t\ts.redoc = redoc\n\t}\n}",
"func (r *TerminalReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {\n\tif err := r.increaseCounterForNamespace(req.Namespace); err != nil {\n\t\tr.Log.Info(\"maximum parallel reconciles reached for namespace - requeuing the req\", \"namespace\", req.Namespace, \"name\", req.Name)\n\n\t\treturn ctrl.Result{\n\t\t\tRequeueAfter: wait.Jitter(time.Duration(int64(100*time.Millisecond)), 50), // requeue after 100ms - 5s\n\t\t}, nil\n\t}\n\n\tres, err := r.handleRequest(req)\n\n\tr.decreaseCounterForNamespace(req.Namespace)\n\n\treturn res, err\n}",
"func (p *Pod) TailLogs(ctx context.Context, opts *LogOptions) ([]LogChan, error) {\n\tfac, ok := ctx.Value(internal.KeyFactory).(*watch.Factory)\n\tif !ok {\n\t\treturn nil, errors.New(\"No factory in context\")\n\t}\n\to, err := fac.Get(p.gvr.String(), opts.Path, true, labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar po v1.Pod\n\tif err := runtime.DefaultUnstructuredConverter.FromUnstructured(o.(*unstructured.Unstructured).Object, &po); err != nil {\n\t\treturn nil, err\n\t}\n\tcoCounts := len(po.Spec.InitContainers) + len(po.Spec.Containers) + len(po.Spec.EphemeralContainers)\n\tif coCounts == 1 {\n\t\topts.SingleContainer = true\n\t}\n\n\touts := make([]LogChan, 0, coCounts)\n\tif co, ok := GetDefaultContainer(po.ObjectMeta, po.Spec); ok && !opts.AllContainers {\n\t\topts.DefaultContainer = co\n\t\treturn append(outs, tailLogs(ctx, p, opts)), nil\n\t}\n\tif opts.HasContainer() && !opts.AllContainers {\n\t\treturn append(outs, tailLogs(ctx, p, opts)), nil\n\t}\n\tfor _, co := range po.Spec.InitContainers {\n\t\to := opts.Clone()\n\t\to.Container = co.Name\n\t\touts = append(outs, tailLogs(ctx, p, o))\n\t}\n\tfor _, co := range po.Spec.Containers {\n\t\to := opts.Clone()\n\t\to.Container = co.Name\n\t\touts = append(outs, tailLogs(ctx, p, o))\n\t}\n\tfor _, co := range po.Spec.EphemeralContainers {\n\t\to := opts.Clone()\n\t\to.Container = co.Name\n\t\touts = append(outs, tailLogs(ctx, p, o))\n\t}\n\n\treturn outs, nil\n}",
"func (r *Reconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {\n\tctx := context.Background()\n\t_ = r.Log.WithValues(\"contour\", req.NamespacedName)\n\n\tr.Log.Info(\"reconciling\", \"request\", req)\n\n\t// Only proceed if we can get the state of contour.\n\tcontour := &operatorv1alpha1.Contour{}\n\tif err := r.Client.Get(ctx, req.NamespacedName, contour); err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// This means the contour was already deleted/finalized and there are\n\t\t\t// stale queue entries (or something edge triggering from a related\n\t\t\t// resource that got deleted async).\n\t\t\tr.Log.Info(\"contour not found; reconciliation will be skipped\", \"request\", req)\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\t\t// Error reading the object, so requeue the request.\n\t\treturn ctrl.Result{}, fmt.Errorf(\"failed to get contour %q: %w\", req, err)\n\t}\n\n\t// The contour is safe to process, so ensure current state matches desired state.\n\tdesired := contour.ObjectMeta.DeletionTimestamp.IsZero()\n\tif desired {\n\t\tswitch {\n\t\tcase contourFinalized(contour):\n\t\t\tif err := r.ensureContour(ctx, contour); err != nil {\n\t\t\t\tswitch e := err.(type) {\n\t\t\t\tcase retryable.Error:\n\t\t\t\t\tr.Log.Error(e, \"got retryable error; requeueing\", \"after\", e.After())\n\t\t\t\t\treturn ctrl.Result{RequeueAfter: e.After()}, nil\n\t\t\t\tdefault:\n\t\t\t\t\treturn ctrl.Result{}, err\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\t// Before doing anything with the contour, ensure it has a finalizer\n\t\t\t// so it can cleaned-up later.\n\t\t\tif err := r.ensureFinalizer(ctx, contour); err != nil {\n\t\t\t\treturn ctrl.Result{}, err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif err := r.ensureContourRemoved(ctx, contour); err != nil {\n\t\t\tswitch e := err.(type) {\n\t\t\tcase retryable.Error:\n\t\t\t\tr.Log.Error(e, \"got retryable error; requeueing\", \"after\", e.After())\n\t\t\t\treturn ctrl.Result{RequeueAfter: e.After()}, nil\n\t\t\tdefault:\n\t\t\t\treturn ctrl.Result{}, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ctrl.Result{}, nil\n}",
"func (s *Server) ReopenContainerLog(ctx context.Context, req *types.ReopenContainerLogRequest) error {\n\tc, err := s.GetContainerFromShortID(req.ContainerID)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"could not find container %s\", req.ContainerID)\n\t}\n\n\tif err := c.IsAlive(); err != nil {\n\t\treturn errors.Errorf(\"container is not created or running: %v\", err)\n\t}\n\n\tif err := s.ContainerServer.Runtime().ReopenContainerLog(c); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func (r *DastReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {\n\tctx := context.Background()\n\tlog := r.Log.WithValues(\"dast\", req.NamespacedName)\n\n\tvar dast securityv1alpha1.Dast\n\tif err := r.Get(ctx, req.NamespacedName, &dast); err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\t// we'll ignore not-found errors, since they can't be fixed by an immediate\n\t\t\t// requeue (we'll need to wait for a new notification), and we can get them\n\t\t\t// on deleted requests.\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\t\treturn ctrl.Result{}, err\n\t}\n\n\treconcilers := []resources.ComponentReconciler{\n\t\tzaproxy.New(r.Client, &dast),\n\t}\n\tif dast.Spec.Analyzer.Name != \"\" {\n\t\treconcilers = append(reconcilers, analyzer.New(r.Client, &dast))\n\t}\n\n\tfor _, rec := range reconcilers {\n\t\terr := rec.Reconcile(log)\n\t\tif err != nil {\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t}\n\treturn ctrl.Result{}, nil\n}",
"func GetCumulativeContentionTime(ctx context.Context) time.Duration {\n\tvar cumulativeContentionTime time.Duration\n\trecording := GetTraceData(ctx)\n\tif recording == nil {\n\t\treturn cumulativeContentionTime\n\t}\n\tvar ev roachpb.ContentionEvent\n\tfor i := range recording {\n\t\trecording[i].Structured(func(any *pbtypes.Any) {\n\t\t\tif !pbtypes.Is(any, &ev) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := pbtypes.UnmarshalAny(any, &ev); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcumulativeContentionTime += ev.Duration\n\t\t})\n\t}\n\treturn cumulativeContentionTime\n}",
"func ReloadConf() (time.Duration, error) {\n\tstart := time.Now()\n\tif CheckAndSetReloadProcess() == true {\n\t\tlog.Warnf(\"RELOADCONF: There is another reload process running while trying to reload at %s \", start.String())\n\t\treturn time.Since(start), fmt.Errorf(\"There is another reload process running.... please wait until finished \")\n\t}\n\n\tlog.Infof(\"RELOADCONF INIT: begin device Gather processes stop... at %s\", start.String())\n\tEnd()\n\n\tlog.Info(\"RELOADCONF: loading configuration Again...\")\n\tLoadConf()\n\tlog.Info(\"RELOADCONF: Starting all device processes again...\")\n\t// Initialize Devices in Runtime map\n\tDeviceProcessStart()\n\n\tlog.Infof(\"RELOADCONF END: Finished from %s to %s [Duration : %s]\", start.String(), time.Now().String(), time.Since(start).String())\n\tCheckAndUnSetReloadProcess()\n\n\treturn time.Since(start), nil\n}",
"func (r *Redis) Status(ctx context.Context) []sdk.MonitoringStatusLine {\n\tif err := r.store.Ping(); err != nil {\n\t\treturn []sdk.MonitoringStatusLine{{\n\t\t\tComponent: \"cache/log/ping\",\n\t\t\tValue: \"connect KO\",\n\t\t\tStatus: sdk.MonitoringStatusAlert,\n\t\t}}\n\t}\n\n\tdbsize, err := r.store.DBSize()\n\tif err != nil {\n\t\treturn []sdk.MonitoringStatusLine{{\n\t\t\tComponent: \"cache/log/redis_dbsize\",\n\t\t\tValue: fmt.Sprintf(\"ERROR while getting cache log db size: %v err:%v\", dbsize, err),\n\t\t\tStatus: sdk.MonitoringStatusAlert,\n\t\t}}\n\t}\n\tsize, err := r.Size()\n\tif err != nil {\n\t\treturn []sdk.MonitoringStatusLine{{\n\t\t\tComponent: \"cache/log/size\",\n\t\t\tValue: fmt.Sprintf(\"ERROR while getting cache log size: %v: err:%v\", size, err),\n\t\t\tStatus: sdk.MonitoringStatusAlert,\n\t\t}}\n\t}\n\tlen, err := r.Len()\n\tif err != nil {\n\t\treturn []sdk.MonitoringStatusLine{{\n\t\t\tComponent: \"cache/log/nb\",\n\t\t\tValue: fmt.Sprintf(\"ERROR while getting cache log nb elements: %v err:%v\", size, err),\n\t\t\tStatus: sdk.MonitoringStatusAlert,\n\t\t}}\n\t}\n\n\tstatusSize := sdk.MonitoringStatusOK\n\t// if size is > 10Mo than maxSize -> Warn\n\tif r.maxSize-size < -10000000 {\n\t\tstatusSize = sdk.MonitoringStatusWarn\n\t}\n\t// if size is > 20Mo than maxSize -> Warn\n\tif r.maxSize-size < -20000000 {\n\t\tstatusSize = sdk.MonitoringStatusAlert\n\t}\n\n\treturn []sdk.MonitoringStatusLine{\n\t\t{\n\t\t\tComponent: \"cache/log/redis_dbsize\",\n\t\t\tValue: fmt.Sprintf(\"%d keys\", dbsize),\n\t\t\tStatus: sdk.MonitoringStatusOK,\n\t\t},\n\t\t{\n\t\t\tComponent: \"cache/log/ping\",\n\t\t\tValue: \"connect OK\",\n\t\t\tStatus: sdk.MonitoringStatusOK,\n\t\t},\n\t\t{\n\t\t\tComponent: \"cache/log/items\",\n\t\t\tValue: fmt.Sprintf(\"%d\", len),\n\t\t\tStatus: sdk.MonitoringStatusOK,\n\t\t}, {\n\t\t\tComponent: \"cache/log/maxsize\",\n\t\t\tValue: fmt.Sprintf(\"%d octets\", r.maxSize),\n\t\t\tStatus: sdk.MonitoringStatusOK,\n\t\t},\n\t\t{\n\t\t\tComponent: \"cache/log/size\",\n\t\t\tValue: fmt.Sprintf(\"%d octets\", size),\n\t\t\tStatus: statusSize,\n\t\t},\n\t}\n}",
"func Test_NoStatusChangeOnStart(t *testing.T) {\n\tconst (\n\t\tresultName = \"copy_of_node_cpu_seconds_global\"\n\t\tsourceMetric = \"node_cpu_seconds_global\"\n\t)\n\n\tfor _, resolutionSecond := range []int{10, 30, 60} {\n\t\tt.Run(fmt.Sprintf(\"resolution=%d\", resolutionSecond), func(t *testing.T) {\n\t\t\tvar (\n\t\t\t\tresPoints []types.MetricPoint\n\t\t\t\tl sync.Mutex\n\t\t\t)\n\n\t\t\tstore := store.New(time.Hour, time.Hour)\n\t\t\treg, err := registry.New(registry.Option{\n\t\t\t\tPushPoint: pushFunction(func(ctx context.Context, points []types.MetricPoint) {\n\t\t\t\t\tl.Lock()\n\t\t\t\t\tdefer l.Unlock()\n\n\t\t\t\t\tresPoints = append(resPoints, points...)\n\t\t\t\t}),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tctx := context.Background()\n\t\t\tt0 := time.Now().Truncate(time.Second)\n\n\t\t\truleManager := newManager(ctx, store, defaultLinuxRecordingRules, t0)\n\n\t\t\tpromqlRules := []PromQLRule{\n\t\t\t\t{\n\t\t\t\t\tAlertingRuleID: \"509701d5-3cb0-449b-a858-0290f4dc3cff\",\n\t\t\t\t\tName: resultName,\n\t\t\t\t\tWarningQuery: fmt.Sprintf(\"%s > 0\", sourceMetric),\n\t\t\t\t\tWarningDelay: 5 * time.Minute,\n\t\t\t\t\tCriticalQuery: fmt.Sprintf(\"%s > 100\", sourceMetric),\n\t\t\t\t\tCriticalDelay: 5 * time.Minute,\n\t\t\t\t\tResolution: time.Duration(resolutionSecond) * time.Second,\n\t\t\t\t\tInstanceID: agentID,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\terr = ruleManager.RebuildPromQLRules(promqlRules)\n\t\t\tif err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\n\t\t\tid, err := reg.RegisterAppenderCallback(\n\t\t\t\tregistry.RegistrationOption{\n\t\t\t\t\tNoLabelsAlteration: true,\n\t\t\t\t\tDisablePeriodicGather: true,\n\t\t\t\t},\n\t\t\t\tregistry.AppenderRegistrationOption{},\n\t\t\t\truleManager,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tfor currentTime := t0; currentTime.Before(t0.Add(7 * time.Minute)); currentTime = currentTime.Add(time.Second * time.Duration(resolutionSecond)) {\n\t\t\t\tif !currentTime.Equal(t0) {\n\t\t\t\t\t// cpu_used need two gather to be calculated, skip first point.\n\t\t\t\t\tstore.PushPoints(context.Background(), []types.MetricPoint{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tPoint: types.Point{\n\t\t\t\t\t\t\t\tTime: currentTime,\n\t\t\t\t\t\t\t\tValue: 30,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\t\ttypes.LabelName: sourceMetric,\n\t\t\t\t\t\t\t\ttypes.LabelInstanceUUID: agentID,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\tif currentTime.Sub(t0) > 6*time.Minute {\n\t\t\t\t\tlogger.V(0).Printf(\"Number of points: %d\", len(resPoints))\n\t\t\t\t}\n\n\t\t\t\truleManager.now = func() time.Time { return currentTime }\n\t\t\t\treg.InternalRunScrape(ctx, currentTime, id)\n\t\t\t}\n\n\t\t\tvar hadResult bool\n\n\t\t\t// Manager should not create ok points since the metric is always in critical.\n\t\t\t// This test might be changed in the future if we implement a persistent store,\n\t\t\t// as it would allow to known the exact hold state of the Prometheus rule.\n\t\t\tfor _, p := range resPoints {\n\t\t\t\tif p.Labels[types.LabelName] != resultName {\n\t\t\t\t\tt.Errorf(\"unexpected point with labels: %v\", p.Labels)\n\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif p.Annotations.Status.CurrentStatus == types.StatusWarning {\n\t\t\t\t\thadResult = true\n\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tt.Errorf(\"point status = %v want %v\", p.Annotations.Status.CurrentStatus, types.StatusWarning)\n\t\t\t}\n\n\t\t\tif !hadResult {\n\t\t\t\tt.Errorf(\"rule never returned any points\")\n\t\t\t}\n\t\t})\n\t}\n}",
"func NewCoverageCommand(config *cnf.Config, logger *logrus.Logger) *cobra.Command {\n\tvar (\n\t\texclude []string\n\t\tlast time.Duration\n\t\tnoCache bool\n\t\treplMode bool\n\t)\n\n\tcommand := cobra.Command{\n\t\tUse: \"coverage\",\n\t\tShort: \"calculates metrics coverage by queries\",\n\t\tLong: \"Calculates metrics coverage by queries.\",\n\n\t\tPreRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif config.Grafana.URL == \"\" {\n\t\t\t\treturn errors.New(\"please provide Grafana API endpoint\")\n\t\t\t}\n\t\t\tif config.Grafana.Dashboard == \"\" {\n\t\t\t\treturn errors.New(\"please provide a dashboard unique identifier\")\n\t\t\t}\n\t\t\tif config.Graphite.URL == \"\" {\n\t\t\t\treturn errors.New(\"please provide Graphite API endpoint\")\n\t\t\t}\n\t\t\tif config.Graphite.Prefix == \"\" {\n\t\t\t\treturn errors.New(\"please provide metric prefix\")\n\t\t\t}\n\t\t\tif prefix := config.Graphite.Prefix; !model.Metric(prefix).Valid() {\n\t\t\t\treturn errors.Errorf(\"invalid metric prefix: %s; it must be simple, e.g. apps.services.name\", prefix)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tprinter := new(presenter.Printer)\n\t\t\tif err := printer.SetOutput(cmd.OutOrStdout()).SetFormat(config.Output.Format); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tprinter.SetPrefix(config.Graphite.Prefix)\n\n\t\t\tindicator := progress.New()\n\n\t\t\tvar (\n\t\t\t\tmetrics model.Metrics\n\t\t\t\tdashboard *model.Dashboard\n\t\t\t)\n\n\t\t\tg, ctx := errgroup.WithContext(cmd.Context())\n\t\t\tg.Go(func() error {\n\t\t\t\tvar provider cache.Graphite\n\t\t\t\tprovider, err := graphite.New(config.Graphite.URL, &http.Client{Timeout: config.Graphite.Timeout}, logger, indicator)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif !noCache {\n\t\t\t\t\tprovider = cache.Decorate(provider, afero.NewOsFs(), logger)\n\t\t\t\t}\n\n\t\t\t\tmetrics, err = provider.Fetch(ctx, config.Graphite.Prefix, last)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tmetrics = metrics.Exclude(new(model.Queries).Convert(exclude).MustMatchers()...)\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tg.Go(func() error {\n\t\t\t\tprovider, err := grafana.New(config.Grafana.URL, &http.Client{Timeout: config.Grafana.Timeout}, logger, indicator)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tdashboard, err = provider.Fetch(ctx, config.Grafana.Dashboard)\n\t\t\t\treturn err\n\t\t\t})\n\t\t\tif err := g.Wait(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tqueries, err := dashboard.Queries(model.Config{\n\t\t\t\tSkipRaw: false,\n\t\t\t\tSkipDuplicates: false,\n\t\t\t\tNeedSorting: true,\n\t\t\t\tUnpack: true,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treporter := model.NewCoverageReporter(queries)\n\n\t\t\tif !replMode {\n\t\t\t\tmetrics := metrics.Filter(config.FilterQuery().MustCompile()).Sort()\n\t\t\t\treturn printer.PrintCoverageReport(reporter.CoverageReport(metrics))\n\t\t\t}\n\t\t\tmetrics.Sort()\n\t\t\tprompt.New(\n\t\t\t\trepl.Prefix(config.Graphite.Prefix, repl.NewCoverageReportExecutor(metrics, reporter, printer, logger)),\n\t\t\t\trepl.NewMetricsCompleter(config.Graphite.Prefix, metrics),\n\t\t\t).Run()\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tflags := command.Flags()\n\tflags.StringArrayVar(&exclude, \"exclude\", nil, \"queries to exclude metrics from coverage, e.g. *.median\")\n\tflags.DurationVar(&last, \"last\", xtime.Day, \"the last interval to fetch\")\n\tflags.BoolVar(&noCache, \"no-cache\", false, \"disable caching\")\n\tflags.BoolVar(&replMode, \"repl\", false, \"enable repl mode\")\n\n\treturn &command\n}",
"func RunReconTool(data map[string][]float64, rawTimestamps []int64, vehicle *Vehicle, gpsTerrain, plotAll bool) (*AnalysisResult, error) {\n\tresult := AnalysisResult{}\n\trawTimestamps = RemoveSuspiciousZeros(data, rawTimestamps, vehicle.VSer)\n\tif len(rawTimestamps) < 2 {\n\t\treturn nil, fmt.Errorf(\"At least 2 data points required, found %d\", len(rawTimestamps))\n\t}\n\tif plotAll {\n\t\tresult.RawValues = data\n\t\tresult.RawTimestamps = rawTimestamps\n\t}\n\ttimeSeries := RemoveTimeOffsets(rawTimestamps)\n\tdt := timeSeries[1] - timeSeries[0]\n\tif dt == 0 {\n\t\treturn nil, fmt.Errorf(\"Invalid time data %v\", rawTimestamps)\n\t}\n\trpm := Average(data[\"Left_Wavesculptor_RPM\"], data[\"Right_Wavesculptor_RPM\"])\n\tbusVoltage := Average(data[\"Left_Bus_Voltage\"], data[\"Right_Bus_Voltage\"])\n\tbusCurrent := floats.AddTo(make([]float64, len(data[\"Left_Bus_Current\"])), data[\"Left_Bus_Current\"], data[\"Right_Bus_Current\"])\n\tsolarArrayVoltage := Average(data[\"Photon_Channel_0_Array_Voltage\"], data[\"Photon_Channel_1_Array_Voltage\"])\n\tsolarArrayCurrent := floats.AddTo(make([]float64, len(data[\"Photon_Channel_0_Array_Current\"])), data[\"Photon_Channel_0_Array_Current\"], data[\"Photon_Channel_1_Array_Current\"])\n\tbusPowerSeries := CalculateSeries(func(params ...float64) float64 {\n\t\treturn BusPower(params[0], params[1], params[2], params[3])\n\t}, data[\"Left_Bus_Voltage\"], data[\"Right_Bus_Voltage\"], data[\"Left_Bus_Current\"], data[\"Right_Bus_Current\"])\n\tresult.MaxTorque = vehicle.TMax\n\tresult.PackCapacity = vehicle.QMax\n\t// we keep telemetry from phase B as well, should probably use it\n\tphaseCurrentSeries := floats.AddTo(make([]float64, len(data[\"Left_Phase_C_Current\"])), data[\"Left_Phase_C_Current\"], data[\"Right_Phase_C_Current\"])\n\tvelocitySeries := CalculateSeries(func(params ...float64) float64 {\n\t\treturn Velocity(params[0], vehicle.RMot)\n\t}, rpm)\n\tdistanceSeries := RiemannSumIntegrate(velocitySeries, dt)\n\taccelerationSeries := Gradient(velocitySeries, dt)\n\tmotorTorqueSeries := CalculateSeries(func(params ...float64) float64 {\n\t\treturn MotorTorque(params[0], params[1], vehicle.TMax)\n\t}, rpm, phaseCurrentSeries)\n\tterrainAngleSeries := CalculateSeries(func(params ...float64) float64 {\n\t\treturn DeriveTerrainAngle(params[0], params[1], params[2], vehicle)\n\t}, motorTorqueSeries, velocitySeries, accelerationSeries)\n\tresultantForceSeries := CalculateSeries(func(params ...float64) float64 {\n\t\treturn ModeledMotorForce(params[0], params[1], params[2], vehicle)\n\t}, velocitySeries, accelerationSeries, terrainAngleSeries)\n\tmodelDerivedTorqueSeries := floats.ScaleTo(make([]float64, len(resultantForceSeries)), vehicle.RMot, resultantForceSeries)\n\tmotorControllerEfficiencySeries := CalculateSeries(func(params ...float64) float64 {\n\t\treturn MotorControllerEfficiency(params[0], params[1], meanIf(busPowerSeries, func(p float64) bool { return p > 0 }))\n\t}, phaseCurrentSeries, busVoltage)\n\tpackResistance, resistanceYIntercept, packUsedBmsCurrent, packUsedBusVoltage := PackResistanceRegression(data[\"BMS_Current\"], busVoltage)\n\tif math.IsNaN(packResistance) {\n\t\treturn nil, fmt.Errorf(\"Unable to calculate pack resistance, no nonzero bus voltage points\")\n\t}\n\tpackEfficiencySeries := CalculateSeries(func(params ...float64) float64 {\n\t\treturn PackEfficiency(params[0], params[1], packResistance)\n\t}, busCurrent, busPowerSeries)\n\tmotorEfficiencySeries := CalculateSeries(func(params ...float64) float64 {\n\t\treturn MotorEfficiency(params[0], params[1])\n\t}, busVoltage, motorTorqueSeries)\n\tdrivetrainEfficiencySeries := CalculateSeries(func(params ...float64) float64 {\n\t\treturn DrivetrainEfficiency(params[0], params[1], params[2])\n\t}, motorControllerEfficiencySeries, packEfficiencySeries, motorEfficiencySeries)\n\tmotorPowerSeries := CalculateSeries(func(params ...float64) float64 {\n\t\treturn MotorPower(params[0], params[1], params[2], params[3], vehicle)\n\t}, motorTorqueSeries, velocitySeries, phaseCurrentSeries, drivetrainEfficiencySeries)\n\tmodelDerivedPowerSeries := CalculateSeries(func(params ...float64) float64 {\n\t\treturn ModelDerivedPower(params[0], params[1], params[2])\n\t}, resultantForceSeries, velocitySeries, drivetrainEfficiencySeries)\n\tmodelDerivedCurrentSeries := CalculateSeries(func(params ...float64) float64 {\n\t\tif params[1] == 0 {\n\t\t\treturn 0\n\t\t}\n\t\treturn params[0] / params[1]\n\t}, modelDerivedPowerSeries, busVoltage)\n\tmoduleVoltages, maxMinDiff, maxModule, minModule := PackModuleVoltages(data, vehicle.VSer)\n\tmaxMode, _ := stat.Mode(maxModule, nil)\n\tminMode, _ := stat.Mode(minModule, nil)\n\tmoduleResistances := CalculateModuleResistances(data, vehicle.VSer)\n\tmeanModuleResistance, moduleStdDev := stat.MeanStdDev(moduleResistances, nil)\n\tsimulatedTotalChargeSeries := RiemannSumIntegrate(modelDerivedCurrentSeries, dt/3600)\n\tsimulatedNetChargeSeries := RiemannSumIntegrate(data[\"BMS_Current\"], dt/3600)\n\tmeasuredTotalChargeSeries := RiemannSumIntegrate(busCurrent, dt/3600)\n\tsolarPowerSeries := CalculatePower(solarArrayCurrent, solarArrayVoltage)\n\tmpptCurrent := CalculateSeries(func(params ...float64) float64 {\n\t\tif params[1] == 0 {\n\t\t\treturn 0\n\t\t}\n\t\treturn params[0] / params[1]\n\t}, solarPowerSeries, busVoltage)\n\tsolarChargeSeries := RiemannSumIntegrate(mpptCurrent, dt/3600)\n\tresult.VelocityMph = floats.ScaleTo(make([]float64, len(velocitySeries)), MetersPerSecondToMilesPerHour, velocitySeries)\n\tresult.DistanceMiles = floats.ScaleTo(make([]float64, len(distanceSeries)), MetersToMiles, distanceSeries)\n\tresult.TimeMinutes = floats.ScaleTo(make([]float64, len(timeSeries)), SecondsToMinutes, timeSeries)\n\tresult.Acceleration = accelerationSeries\n\tresult.MotorTorque = motorTorqueSeries\n\tresult.ModelDerivedTorque = modelDerivedTorqueSeries\n\tresult.MotorPower = motorPowerSeries\n\tresult.ModelDerivedMotorPower = modelDerivedPowerSeries\n\tresult.BusPower = busPowerSeries\n\tresult.SimulatedTotalCharge = simulatedTotalChargeSeries\n\tresult.SimulatedNetCharge = simulatedNetChargeSeries\n\tresult.MeasuredTotalCharge = measuredTotalChargeSeries\n\tresult.MeasuredNetCharge = floats.AddTo(make([]float64, len(data[\"Left_Charge_Consumed\"])), data[\"Left_Charge_Consumed\"], data[\"Right_Charge_Consumed\"])\n\tresult.BmsCurrent = packUsedBmsCurrent\n\tresult.BusVoltage = packUsedBusVoltage\n\tresult.PackResistance = packResistance\n\tresult.PackResistanceYIntercept = resistanceYIntercept\n\tresult.ModuleVoltages = moduleVoltages\n\tresult.ModuleMaxMinDifference = maxMinDiff\n\tresult.MaxModule = maxModule\n\tresult.MinModule = minModule\n\tresult.MaxModuleMode = maxMode\n\tresult.MinModuleMode = minMode\n\tresult.ModuleResistances = moduleResistances\n\tresult.MeanModuleResistance = meanModuleResistance\n\tresult.ModuleResistanceStandardDeviation = moduleStdDev\n\tresult.DrivetrainEfficiency = drivetrainEfficiencySeries\n\tresult.MotorEfficiency = motorEfficiencySeries\n\tresult.MotorControllerEfficiency = motorControllerEfficiencySeries\n\tresult.PackEfficiency = packEfficiencySeries\n\tresult.SolarArrayPower = solarPowerSeries\n\tresult.SolarArrayCharge = solarChargeSeries\n\tresult.PhaseCCurrent = phaseCurrentSeries\n\tresult.ThrottleCommand = data[\"Throttle\"]\n\tresult.RelativeXDisplacement = LatLongToRelativeDisplacement(data[\"GPS_Longitude\"])\n\tresult.RelativeYDisplacement = LatLongToRelativeDisplacement(data[\"GPS_Latitude\"])\n\treturn &result, nil\n}",
"func (_Bindings *BindingsFilterer) WatchReservesReduced(opts *bind.WatchOpts, sink chan<- *BindingsReservesReduced) (event.Subscription, error) {\n\n\tlogs, sub, err := _Bindings.contract.WatchLogs(opts, \"ReservesReduced\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(BindingsReservesReduced)\n\t\t\t\tif err := _Bindings.contract.UnpackLog(event, \"ReservesReduced\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}",
"func logNotification(env *task.Env, task *task.MessageTask, pdu *libcoap.Pdu) {\n log.Infof(\"Message Code: %v (%+v)\", pdu.Code, pdu.CoapCode())\n\n\tif pdu.Data == nil {\n\t\treturn\n }\n\n var err error\n var logStr string\n var req *libcoap.Pdu\n if task != nil {\n req = task.GetMessage()\n } else {\n req = nil\n }\n\n observe, err := pdu.GetOptionIntegerValue(libcoap.OptionObserve)\n if err != nil {\n log.WithError(err).Warn(\"Get observe option value failed.\")\n return\n }\n log.WithField(\"Observe Value:\", observe).Info(\"Notification Message\")\n\n\tmaxAgeRes := pdu.GetOptionStringValue(libcoap.OptionMaxage)\n\tif maxAgeRes != \"\" {\n\t\tlog.Infof(\"Max-Age Option: %v\", maxAgeRes)\n\t}\n\n log.Infof(\" Raw payload: %s\", pdu.Data)\n hex := hex.Dump(pdu.Data)\n\tlog.Infof(\" Raw payload hex: \\n%s\", hex)\n\n\t// Check if the response body data is a string message (not an object)\n\tif pdu.IsMessageResponse() {\n\t\tlog.Debugf(\"Server send notification with error message: %+v\", pdu.Data)\n\t\treturn\n\t}\n\n\tdec := codec.NewDecoder(bytes.NewReader(pdu.Data), dots_common.NewCborHandle())\n\n // Identify response is mitigation or session configuration by cbor data in heximal\n if strings.Contains(hex, string(libcoap.IETF_MITIGATION_SCOPE_HEX)) {\n var v messages.MitigationResponse\n err = dec.Decode(&v)\n logStr = v.String()\n env.UpdateCountMitigation(req, v, string(pdu.Token))\n log.Debugf(\"Request query with token as key in map: %+v\", env.GetAllRequestQuery())\n } else if strings.Contains(hex, string(libcoap.IETF_SESSION_CONFIGURATION_HEX)) {\n var v messages.ConfigurationResponse\n err = dec.Decode(&v)\n logStr = v.String()\n log.Debug(\"Receive session notification - Client update new values to system session configuration and restart ping task.\")\n\t\tRestartHeartBeatTask(pdu, env)\n\n\t\t// Not refresh session config in case session config task is nil (server send notification after reset by expired Max-age)\n\t\tsessionTask := env.SessionConfigTask()\n\t\tif sessionTask != nil {\n\t\t\tRefreshSessionConfig(pdu, env, sessionTask.MessageTask())\n\t\t}\n\t} else if strings.Contains(hex, string(libcoap.IETF_TELEMETRY_PRE_MITIGATION)) {\n var v messages.TelemetryPreMitigationResponse\n err = dec.Decode(&v)\n logStr = v.String()\n log.Debug(\"Receive telemetry pre-mitigation notification.\")\n }else {\n log.Warnf(\"Unknown notification is received.\")\n }\n\n if err != nil {\n log.WithError(err).Warn(\"CBOR Decode failed.\")\n return\n }\n log.Infof(\" CBOR decoded: %s\", logStr)\n}",
"func makeLog(size int) exec_func {\n\treturn func(pc *uint64, in *interpreter, ctx *callCtx) uint64 {\n\n\t\tstack := ctx.stack\n\t\tstack.Pop()\n\t\tstack.Pop()\n\t\tfor i := 0; i < size; i++ {\n\t\t\tstack.Pop()\n\t\t}\n\t\treturn 0\n\t}\n}",
"func CMOVQOC(mr, r operand.Op) { ctx.CMOVQOC(mr, r) }",
"func generateLogs(cmd *cobra.Command, args []string) {\n\tif linesTotal <= 0 {\n\t\tklog.Fatalf(\"Invalid total number of lines: %d\", linesTotal)\n\t}\n\n\tif duration <= 0 {\n\t\tklog.Fatalf(\"Invalid duration: %v\", duration)\n\t}\n\n\tdelay := duration / time.Duration(linesTotal)\n\n\tticker := time.NewTicker(delay)\n\tdefer ticker.Stop()\n\tfor id := 0; id < linesTotal; id++ {\n\t\tklog.Info(generateLogLine(id))\n\t\t<-ticker.C\n\t}\n}",
"func (px *Paxos) clog(dbg bool, funcname, format string, args ...interface{}) {\n\tif dbg {\n\t\tl1 := fmt.Sprintf(\"[%s] me:%d\\n\", funcname, px.me)\n\t\tl2 := fmt.Sprintf(\"....\"+format, args...)\n\t\tfmt.Println(l1 + l2)\n\t}\n}",
"func BenchmarkLogRotation(b *testing.B) {\n\n\ttests := []struct {\n\t\trotate bool\n\t\tcompress bool\n\t\tnumBytes int\n\t}{\n\t\t{rotate: false, compress: false, numBytes: 0},\n\t\t{rotate: false, compress: false, numBytes: 1024 * 1000}, // 1MB\n\t\t{rotate: false, compress: false, numBytes: 1024 * 100000}, // 100MB\n\t\t{rotate: true, compress: false, numBytes: 0},\n\t\t{rotate: true, compress: false, numBytes: 1024 * 1000}, // 1MB\n\t\t{rotate: true, compress: false, numBytes: 1024 * 100000}, // 100MB\n\t\t{rotate: true, compress: true, numBytes: 0},\n\t\t{rotate: true, compress: true, numBytes: 1024 * 1000}, // 1MB\n\t\t{rotate: true, compress: true, numBytes: 1024 * 100000}, // 100MB\n\t}\n\n\tfor _, test := range tests {\n\t\tb.Run(fmt.Sprintf(\"rotate:%t-compress:%t-bytes:%v\", test.rotate, test.compress, test.numBytes), func(bm *testing.B) {\n\t\t\tdata := make([]byte, test.numBytes)\n\t\t\t_, err := rand.Read(data)\n\t\t\trequire.NoError(bm, err)\n\n\t\t\tlogPath := b.TempDir()\n\t\t\tlogger := lumberjack.Logger{Filename: filepath.Join(logPath, \"output.log\"), Compress: test.compress}\n\n\t\t\tbm.ResetTimer()\n\t\t\tfor i := 0; i < bm.N; i++ {\n\t\t\t\t_, _ = logger.Write(data)\n\t\t\t\tif test.rotate {\n\t\t\t\t\t_ = logger.Rotate()\n\t\t\t\t}\n\t\t\t}\n\t\t\tbm.StopTimer()\n\n\t\t\t// Tidy up temp log files in a retry loop because\n\t\t\t// we can't remove temp dir while the async compression is still writing log files\n\t\t\tassert.NoError(bm, logger.Close())\n\t\t\terr, _ = RetryLoop(\"benchmark-logrotate-teardown\",\n\t\t\t\tfunc() (shouldRetry bool, err error, value interface{}) {\n\t\t\t\t\terr = os.RemoveAll(logPath)\n\t\t\t\t\treturn err != nil, err, nil\n\t\t\t\t},\n\t\t\t\tCreateDoublingSleeperFunc(3, 250),\n\t\t\t)\n\t\t\tassert.NoError(bm, err)\n\t\t})\n\t}\n\n}",
"func pmRCoreCycle() {\n\t//\n\tdefer rcore.CurrentExp.Say(rcore.CallSensor)\n\n\t//\n\ttol := []string{\"mtime\", \"cycle\", \"bolus\", \"infusion\"}\n\n\t// --------------------------------------------------------------------\n\t// load Redis record\n\tif rcore.EntityExpRecReload(tol) == false {\n\t\t//\n\t\tpanic(\"REDIS record not found\")\n\t}\n\n\t// ...\n\tvar _c = rcore.CurrentExp\n\n\t// --------------------------------------------------------------------\n\t// REDIS record -> SIMS (patmod simulation state)\n\trsims.UpdateFrom(_c)\n\n\t//\n\trsims = rsims.SimSteps(_c.Mtime)\n\n\t//\n\ttrec := rsims.Clone().SimStepsWhile(pmTotalRecoveryPredicate)\n\n\t// --------------------------------------------------------------------\n\t//\n\t_c.TOF = rsims.TOF0\n\t_c.PTC = 0\n\t_c.Cinp = rsims.YROC[1]\n\t_c.ConsumedTotal += rsims.BolusConsumptionML\n\t_c.RecoveryTime = (trec.Time - rsims.Time)\n\n\t//\n\tlog.Println(\"PMA; cycle: \", _c.Cycle, \"mtime\", _c.Mtime,\n\t\t\"rtime\", rsims.Time, \"bolus \", rsims.Bolus.Value, \" \", rsims.Bolus, \"ConsT \", _c.ConsumedTotal)\n\n\t//\n\trcore.CurrentExp.Save([]string{\"TOF\", \"PTC\", \"Cinp\", \"ConsumedTotal\", \"RecoveryTime\"}, false)\n}",
"func TestLogRecovery(t *testing.T) {\n\tpath := setupLog(\n\t\t`cf4aab23 0000000000000001 0000000000000001 cmd_1 {\"val\":\"foo\",\"i\":20}`+\"\\n\" +\n\t\t`4c08d91f 0000000000000002 0000000000000001 cmd_2 {\"x\":100}`+\"\\n\" +\n\t\t`6ac5807c 0000000000000003 00000000000`)\n\tlog := NewLog()\n\tlog.AddCommandType(&TestCommand1{})\n\tlog.AddCommandType(&TestCommand2{})\n\tif err := log.Open(path); err != nil {\n\t\tt.Fatalf(\"Unable to open log: %v\", err)\n\t}\n\tdefer log.Close()\n\tdefer os.Remove(path)\n\n\tif err := log.Append(NewLogEntry(log, 3, 2, &TestCommand1{\"bat\", -5})); err != nil {\n\t\tt.Fatalf(\"Unable to append: %v\", err)\n\t}\n\n\t// Validate existing log entries.\n\tif len(log.entries) != 3 {\n\t\tt.Fatalf(\"Expected 2 entries, got %d\", len(log.entries))\n\t}\n\tif !reflect.DeepEqual(log.entries[0], NewLogEntry(log, 1, 1, &TestCommand1{\"foo\", 20})) {\n\t\tt.Fatalf(\"Unexpected entry[0]: %v\", log.entries[0])\n\t}\n\tif !reflect.DeepEqual(log.entries[1], NewLogEntry(log, 2, 1, &TestCommand2{100})) {\n\t\tt.Fatalf(\"Unexpected entry[1]: %v\", log.entries[1])\n\t}\n\tif !reflect.DeepEqual(log.entries[2], NewLogEntry(log, 3, 2, &TestCommand1{\"bat\", -5})) {\n\t\tt.Fatalf(\"Unexpected entry[2]: %v\", log.entries[2])\n\t}\n\n\t// Validate precommit log contents.\n\texpected :=\n\t\t`cf4aab23 0000000000000001 0000000000000001 cmd_1 {\"val\":\"foo\",\"i\":20}`+\"\\n\" +\n\t\t`4c08d91f 0000000000000002 0000000000000001 cmd_2 {\"x\":100}`+\"\\n\"\n\tactual, _ := ioutil.ReadFile(path)\n\tif string(actual) != expected {\n\t\tt.Fatalf(\"Unexpected buffer:\\nexp:\\n%s\\ngot:\\n%s\", expected, string(actual))\n\t}\n\n\t// Validate committed log contents.\n\tif err := log.SetCommitIndex(3); err != nil {\n\t\tt.Fatalf(\"Unable to partially commit: %v\", err)\n\t}\n\texpected =\n\t\t`cf4aab23 0000000000000001 0000000000000001 cmd_1 {\"val\":\"foo\",\"i\":20}`+\"\\n\" +\n\t\t`4c08d91f 0000000000000002 0000000000000001 cmd_2 {\"x\":100}`+\"\\n\" +\n\t\t`3f3f884c 0000000000000003 0000000000000002 cmd_1 {\"val\":\"bat\",\"i\":-5}`+\"\\n\"\n\tactual, _ = ioutil.ReadFile(path)\n\tif string(actual) != expected {\n\t\tt.Fatalf(\"Unexpected buffer:\\nexp:\\n%s\\ngot:\\n%s\", expected, string(actual))\n\t}\n}",
"func (o QperfSpecClientConfigurationPodSchedulingTolerationsOutput) Effect() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingTolerations) *string { return v.Effect }).(pulumi.StringPtrOutput)\n}",
"func (o ApplicationStatusOutput) ReconciledAt() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatus) *string { return v.ReconciledAt }).(pulumi.StringPtrOutput)\n}",
"func (r *DatadogMonitorReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\treturn r.internal.Reconcile(ctx, req)\n}",
"func (_CrToken *CrTokenFilterer) ParseReservesReduced(log types.Log) (*CrTokenReservesReduced, error) {\n\tevent := new(CrTokenReservesReduced)\n\tif err := _CrToken.contract.UnpackLog(event, \"ReservesReduced\", log); err != nil {\n\t\treturn nil, err\n\t}\n\tevent.Raw = log\n\treturn event, nil\n}",
"func (r *remoteRuntimeService) ReopenContainerLog(ctx context.Context, containerID string) (err error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ReopenContainerLog\", \"containerID\", containerID, \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\tif _, err := r.runtimeClient.ReopenContainerLog(ctx, &runtimeapi.ReopenContainerLogRequest{ContainerId: containerID}); err != nil {\n\t\tklog.ErrorS(err, \"ReopenContainerLog from runtime service failed\", \"containerID\", containerID)\n\t\treturn err\n\t}\n\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ReopenContainerLog Response\", \"containerID\", containerID)\n\treturn nil\n}",
"func ReportCommand(cluster string, data hystrix.Data) {\n\tlog.WithField(\"cluster\", cluster).WithField(\"data\", data).Debug(\"reporting\")\n\n\tvar name = strings.ToLower(data.Name)\n\tvar group = strings.ToLower(data.Group)\n\n\tcommandCircuitOpen.WithLabelValues(cluster, name, group).Set(boolToFloat64(data.IsCircuitBreakerOpen))\n\tcommandErrorPercentage.WithLabelValues(cluster, name, group).Set(data.ErrorPercentage)\n\tcommandErrors.WithLabelValues(cluster, name, group).Set(data.ErrorCount)\n\tcommandRequests.WithLabelValues(cluster, name, group).Set(data.RequestCount)\n\tcommandConcurrentExecutions.WithLabelValues(cluster, name, group).Set(data.CurrentConcurrentExecutionCount)\n\tcommandMaxConcurrentExecutions.WithLabelValues(cluster, name, group).Set(data.RollingMaxConcurrentExecutionCount)\n\tcommandReportingHosts.WithLabelValues(cluster, name, group).Set(data.ReportingHosts)\n\n\tcommandRollingEvents.WithLabelValues(cluster, name, group, \"bad_request\").Set(data.RollingCountBadRequests)\n\tcommandRollingEvents.WithLabelValues(cluster, name, group, \"collapsed\").Set(data.RollingCountCollapsedRequests)\n\tcommandRollingEvents.WithLabelValues(cluster, name, group, \"emit\").Set(data.RollingCountEmit)\n\tcommandRollingEvents.WithLabelValues(cluster, name, group, \"exception_thrown\").Set(data.RollingCountExceptionsThrown)\n\tcommandRollingEvents.WithLabelValues(cluster, name, group, \"failure\").Set(data.RollingCountFailure)\n\tcommandRollingEvents.WithLabelValues(cluster, name, group, \"fallback_emit\").Set(data.RollingCountFallbackEmit)\n\tcommandRollingEvents.WithLabelValues(cluster, name, group, \"fallback_failure\").Set(data.RollingCountFallbackFailure)\n\tcommandRollingEvents.WithLabelValues(cluster, name, group, \"fallback_missing\").Set(data.RollingCountFallbackMissing)\n\tcommandRollingEvents.WithLabelValues(cluster, name, group, \"fallback_rejection\").Set(data.RollingCountFallbackRejection)\n\tcommandRollingEvents.WithLabelValues(cluster, name, group, \"fallback_success\").Set(data.RollingCountFallbackSuccess)\n\tcommandRollingEvents.WithLabelValues(cluster, name, group, \"response_from_cache\").Set(data.RollingCountResponsesFromCache)\n\tcommandRollingEvents.WithLabelValues(cluster, name, group, \"semaphore_rejected\").Set(data.RollingCountSemaphoreRejected)\n\tcommandRollingEvents.WithLabelValues(cluster, name, group, \"short_circuited\").Set(data.RollingCountShortCircuited)\n\tcommandRollingEvents.WithLabelValues(cluster, name, group, \"success\").Set(data.RollingCountSuccess)\n\tcommandRollingEvents.WithLabelValues(cluster, name, group, \"thread_pool_rejected\").Set(data.RollingCountThreadPoolRejected)\n\tcommandRollingEvents.WithLabelValues(cluster, name, group, \"timeout\").Set(data.RollingCountTimeout)\n\n\tlatencyTotal.WithLabelValues(cluster, name, group, \"0\").Set(data.LatencyTotal.L0)\n\tlatencyTotal.WithLabelValues(cluster, name, group, \"25\").Set(data.LatencyTotal.L25)\n\tlatencyTotal.WithLabelValues(cluster, name, group, \"50\").Set(data.LatencyTotal.L50)\n\tlatencyTotal.WithLabelValues(cluster, name, group, \"75\").Set(data.LatencyTotal.L75)\n\tlatencyTotal.WithLabelValues(cluster, name, group, \"90\").Set(data.LatencyTotal.L90)\n\tlatencyTotal.WithLabelValues(cluster, name, group, \"95\").Set(data.LatencyTotal.L95)\n\tlatencyTotal.WithLabelValues(cluster, name, group, \"99\").Set(data.LatencyTotal.L99)\n\tlatencyTotal.WithLabelValues(cluster, name, group, \"99.5\").Set(data.LatencyTotal.L995)\n\tlatencyTotal.WithLabelValues(cluster, name, group, \"100\").Set(data.LatencyTotal.L100)\n\tlatencyTotal.WithLabelValues(cluster, name, group, \"mean\").Set(data.LatencyTotalMean)\n\n\tlatencyExecute.WithLabelValues(cluster, name, group, \"0\").Set(data.LatencyExecute.L0)\n\tlatencyExecute.WithLabelValues(cluster, name, group, \"25\").Set(data.LatencyExecute.L25)\n\tlatencyExecute.WithLabelValues(cluster, name, group, \"50\").Set(data.LatencyExecute.L50)\n\tlatencyExecute.WithLabelValues(cluster, name, group, \"75\").Set(data.LatencyExecute.L75)\n\tlatencyExecute.WithLabelValues(cluster, name, group, \"90\").Set(data.LatencyExecute.L90)\n\tlatencyExecute.WithLabelValues(cluster, name, group, \"95\").Set(data.LatencyExecute.L95)\n\tlatencyExecute.WithLabelValues(cluster, name, group, \"99\").Set(data.LatencyExecute.L99)\n\tlatencyExecute.WithLabelValues(cluster, name, group, \"99.5\").Set(data.LatencyExecute.L995)\n\tlatencyExecute.WithLabelValues(cluster, name, group, \"100\").Set(data.LatencyExecute.L100)\n\tlatencyExecute.WithLabelValues(cluster, name, group, \"mean\").Set(data.LatencyExecuteMean)\n}",
"func (s SugaredLogger) Reconfigure(_ interface{}) {\n\ts.Warn(\"reconfigure is not implemented\", \"logger\", \"zap\")\n}",
"func TestCmdListContinuous(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"Skipping TestCmdListContinuous because Windows stdout capture doesn't work.\")\n\t}\n\n\tassert := asrt.New(t)\n\n\tt.Setenv(\"DDEV_DEBUG\", \"\")\n\t// Execute \"ddev list --continuous\"\n\tcmd := oexec.Command(DdevBin, \"list\", \"-j\", \"--continuous\")\n\tstdout, err := cmd.StdoutPipe()\n\tassert.NoError(err)\n\n\terr = cmd.Start()\n\tassert.NoError(err)\n\n\treader := bufio.NewReader(stdout)\n\n\tblob, err := reader.ReadBytes('\\n')\n\tassert.NoError(err)\n\tbyteCount := len(blob)\n\tblob = blob[:byteCount-1]\n\trequire.True(t, byteCount > 300, \"byteCount should have been >300 and was %v blob=%s\", byteCount, string(blob))\n\n\tf, err := unmarshalJSONLogs(string(blob))\n\trequire.NoError(t, err, \"Could not unmarshall blob, err=%v, content=%s\", err, blob)\n\n\tassert.NotEmpty(f[0][\"raw\"])\n\ttime1 := f[0][\"time\"]\n\tif len(f) > 1 {\n\t\tt.Logf(\"Expected just one line in initial read, but got %d lines instead\", len(f))\n\t}\n\n\ttime.Sleep(time.Millisecond * 1500)\n\n\t// Now read more from the pipe after resetting blob\n\tblob, err = reader.ReadBytes('\\n')\n\tbyteCount = len(blob)\n\tassert.NoError(err)\n\tblob = blob[:byteCount-1]\n\trequire.True(t, byteCount > 300, \"byteCount should have been >300 and was %v blob=%s\", byteCount, string(blob))\n\tf, err = unmarshalJSONLogs(string(blob))\n\trequire.NoError(t, err, \"Could not unmarshall blob, err=%v, content=%s\", err, blob)\n\tif len(f) > 1 {\n\t\tt.Logf(\"Expected just one line in second read, but got %d lines instead\", len(f))\n\t}\n\tassert.NotEmpty(f[0][\"raw\"]) // Just to make sure it's a list object\n\ttime2 := f[0][\"time\"]\n\tassert.NotEqual(time1, time2)\n\tassert.True(time2.(string) > time1.(string))\n\n\t// Kill the process we started.\n\terr = cmd.Process.Kill()\n\tassert.NoError(err)\n}",
"func (q *Query) LogReplay() *Query {\n\tq.q = q.q.LogReplay()\n\treturn q\n}",
"func CMOVQPL(mr, r operand.Op) { ctx.CMOVQPL(mr, r) }",
"func (l *Clog) Clean() error {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\n\tcleaned, err := l.cl.clean(l.segments)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.segments = cleaned\n\n\treturn nil\n}",
"func CMOVQLS(mr, r operand.Op) { ctx.CMOVQLS(mr, r) }",
"func printPerform(resultTimeStart time.Time, resultTimeEnd time.Time, msgCount int, msgByte int) {\n\n\tpt := resultTimeEnd.Sub(resultTimeStart).Seconds()\n\n\tstart_date := fmt.Sprintf(\"%02d-%02d %02d:%02d:%02d:%03d\", resultTimeStart.Month(), resultTimeStart.Day(), resultTimeStart.Hour(), resultTimeStart.Minute(), resultTimeStart.Second(), resultTimeStart.UnixNano()/1000000%1000)\n\tend_date := fmt.Sprintf(\"%02d-%02d %02d:%02d:%02d:%03d\", resultTimeEnd.Month(), resultTimeEnd.Day(), resultTimeEnd.Hour(), resultTimeEnd.Minute(), resultTimeEnd.Second(), resultTimeEnd.UnixNano()/1000000%1000)\n\n\tfmt.Println(\"-----------------------/ ------------------ / ---------------- / --------------- /---------------------/ \")\n\tfmt.Println(\" start.time / end.time / consumed.in.nMsg / Msg_count.sec / performancetime.sec /\")\n\tfmt.Println(\"---------------------/ ------------------ / ---------------- / --------------- /---------------------/ \")\n\ts := fmt.Sprintf(\" %14s / %14s / %16d / %15.2f / %20.4f \", start_date, end_date, msgCount, float64(msgCount)/pt, pt)\n\tfmt.Println(s)\n\tfmt.Println(\"-------------------/ ------------------ / ---------------- / --------------- /---------------------/ \")\n\tfmt.Println(\"Total Byte : \", msgByte)\n}",
"func (c ReplaceMisconfiguredPods) Reconcile(r *FoundationDBClusterReconciler, context ctx.Context, cluster *fdbtypes.FoundationDBCluster) *Requeue {\n\thasNewRemovals := false\n\n\tprocessGroups := make(map[string]*fdbtypes.ProcessGroupStatus)\n\tfor _, processGroup := range cluster.Status.ProcessGroups {\n\t\tprocessGroups[processGroup.ProcessGroupID] = processGroup\n\t}\n\n\tpvcs := &corev1.PersistentVolumeClaimList{}\n\terr := r.List(context, pvcs, internal.GetPodListOptions(cluster, \"\", \"\")...)\n\tif err != nil {\n\t\treturn &Requeue{Error: err}\n\t}\n\n\tfor _, pvc := range pvcs.Items {\n\t\tinstanceID := internal.GetInstanceIDFromMeta(pvc.ObjectMeta)\n\t\tprocessGroupStatus := processGroups[instanceID]\n\t\tif processGroupStatus == nil {\n\t\t\treturn &Requeue{Error: fmt.Errorf(\"unknown PVC %s in replace_misconfigured_pods\", instanceID)}\n\t\t}\n\n\t\tif processGroupStatus.Remove {\n\t\t\tcontinue\n\t\t}\n\n\t\tneedsNewRemoval, err := instanceNeedsRemovalForPVC(cluster, pvc)\n\t\tif err != nil {\n\t\t\treturn &Requeue{Error: err}\n\t\t}\n\t\tif needsNewRemoval {\n\t\t\tinstances, err := r.PodLifecycleManager.GetInstances(r, cluster, context, internal.GetSinglePodListOptions(cluster, instanceID)...)\n\t\t\tif err != nil {\n\t\t\t\treturn &Requeue{Error: err}\n\t\t\t}\n\n\t\t\tif len(instances) > 0 {\n\t\t\t\tprocessGroupStatus.Remove = true\n\t\t\t\thasNewRemovals = true\n\t\t\t}\n\t\t}\n\t}\n\n\tinstances, err := r.PodLifecycleManager.GetInstances(r, cluster, context, internal.GetPodListOptions(cluster, \"\", \"\")...)\n\tif err != nil {\n\t\treturn &Requeue{Error: err}\n\t}\n\n\tfor _, instance := range instances {\n\t\tprocessGroupStatus := processGroups[instance.GetInstanceID()]\n\t\tneedsRemoval, err := instanceNeedsRemoval(cluster, instance, processGroupStatus)\n\t\tif err != nil {\n\t\t\treturn &Requeue{Error: err}\n\t\t}\n\n\t\tif needsRemoval {\n\t\t\tprocessGroupStatus.Remove = true\n\t\t\thasNewRemovals = true\n\t\t}\n\t}\n\n\tif hasNewRemovals {\n\t\terr = r.Status().Update(context, cluster)\n\t\tif err != nil {\n\t\t\treturn &Requeue{Error: err}\n\t\t}\n\n\t\treturn &Requeue{Message: \"Removals have been updated in the cluster status\"}\n\t}\n\n\treturn nil\n}",
"func (r *CassandraRestoreReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {\n\tctx := context.Background()\n\t_ = r.Log.WithValues(\"cassandrarestore\", req.NamespacedName)\n\n\tinstance := &api.CassandraRestore{}\n\terr := r.Get(ctx, req.NamespacedName, instance)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\t\treturn ctrl.Result{RequeueAfter: 10 * time.Second}, err\n\t}\n\n\trestore := instance.DeepCopy()\n\n\tif len(restore.Status.RestoreKey) == 0 {\n\t\tif err = r.setRestoreKey(ctx, restore); err != nil {\n\t\t\tr.Log.Error(err, \"failed to set restore key\")\n\t\t\treturn ctrl.Result{RequeueAfter: 10 * time.Second}, err\n\t\t}\n\t}\n\n\t// See if the restore is already in progress\n\tif !restore.Status.StartTime.IsZero() {\n\t\tcassdcKey := types.NamespacedName{Namespace: req.Namespace, Name: restore.Spec.CassandraDatacenter.Name}\n\t\tcassdc := &cassdcapi.CassandraDatacenter{}\n\n\t\tif err = r.Get(ctx, cassdcKey, cassdc); err != nil {\n\t\t\t// TODO add some additional logging and/or generate an event if the error is not found\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\tr.Log.Error(err, \"cassandradatacenter not found\", \"CassandraDatacenter\", cassdcKey)\n\n\t\t\t\tpatch := client.MergeFrom(restore.DeepCopy())\n\t\t\t\trestore.Status.FinishTime = metav1.Now()\n\t\t\t\tif err = r.Status().Patch(ctx, restore, patch); err == nil {\n\t\t\t\t\treturn ctrl.Result{Requeue: false}, err\n\t\t\t\t} else {\n\t\t\t\t\tr.Log.Error(err, \"failed to patch status with end time\")\n\t\t\t\t\treturn ctrl.Result{RequeueAfter: 5 * time.Second}, err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tr.Log.Error(err, \"failed to get cassandradatacenter\", \"CassandraDatacenter\", cassdcKey)\n\t\t\t\treturn ctrl.Result{RequeueAfter: 10 * time.Second}, err\n\t\t\t}\n\t\t}\n\n\t\tif isCassdcReady(cassdc) {\n\t\t\tr.Log.Info(\"the cassandradatacenter has been restored and is ready\", \"CassandraDatacenter\", cassdcKey)\n\n\t\t\tpatch := client.MergeFrom(restore.DeepCopy())\n\t\t\trestore.Status.FinishTime = metav1.Now()\n\t\t\tif err = r.Status().Patch(ctx, restore, patch); err == nil {\n\t\t\t\treturn ctrl.Result{Requeue: false}, err\n\t\t\t} else {\n\t\t\t\tr.Log.Error(err, \"failed to patch status with end time\")\n\t\t\t\treturn ctrl.Result{RequeueAfter: 5 * time.Second}, err\n\t\t\t}\n\t\t}\n\n\t\t// TODO handle scenarios in which the CassandraDatacenter fails to become ready\n\n\t\treturn ctrl.Result{RequeueAfter: 5 * time.Second}, nil\n\t}\n\n\tbackupKey := types.NamespacedName{Namespace: req.Namespace, Name: restore.Spec.Backup}\n\tbackup := &api.CassandraBackup{}\n\n\tif err = r.Get(ctx, backupKey, backup); err != nil {\n\t\t// TODO add some additional logging and/or generate an event if the error is not found\n\t\tr.Log.Error(err, \"failed to get backup\", \"CassandraBackup\", backupKey)\n\t\treturn ctrl.Result{RequeueAfter: 10 * time.Second}, err\n\t}\n\n\tif restore.Spec.InPlace {\n\t\tr.Log.Info(\"performing in place restore\")\n\n\t\tcassdcKey := types.NamespacedName{Namespace: req.Namespace, Name: restore.Spec.CassandraDatacenter.Name}\n\t\tcassdc := &cassdcapi.CassandraDatacenter{}\n\n\t\tif err = r.Get(ctx, cassdcKey, cassdc); err != nil {\n\t\t\tr.Log.Error(err, \"failed to get cassandradatacenter\", \"CassandraDatacenter\", cassdcKey)\n\t\t\treturn ctrl.Result{RequeueAfter: 10 * time.Second}, err\n\t\t}\n\n\t\tcassdc = cassdc.DeepCopy()\n\n\t\tif err = setBackupNameInRestoreContainer(backup.Spec.Name, cassdc); err != nil {\n\t\t\tr.Log.Error(err, \"failed to set backup name in restore container\", \"CassandraDatacenter\", cassdcKey)\n\t\t\treturn ctrl.Result{RequeueAfter: 10 * time.Second}, err\n\t\t}\n\n\t\tif err = setRestoreKeyInRestoreContainer(restore.Status.RestoreKey, cassdc); err != nil {\n\t\t\tr.Log.Error(err, \"failed to set restore key in restore container\", \"CassandraDatacenter\", cassdcKey)\n\t\t\treturn ctrl.Result{RequeueAfter: 10 * time.Second}, err\n\t\t}\n\n\t\tpatch := client.MergeFrom(restore.DeepCopy())\n\t\trestore.Status.StartTime = metav1.Now()\n\t\tif err = r.Status().Patch(ctx, restore, patch); err != nil {\n\t\t\tr.Log.Error(err, \"fail to patch status with start time\")\n\t\t\treturn ctrl.Result{RequeueAfter: 5 * time.Second}, err\n\t\t}\n\n\t\tif err = r.Update(ctx, cassdc); err == nil {\n\t\t\tr.Log.Info(\"the cassandradatacenter has been updated and will be restarted\", \"CassandraDatacenter\", cassdcKey)\n\t\t\treturn ctrl.Result{RequeueAfter: 10 * time.Second}, err\n\t\t} else {\n\t\t\tr.Log.Error(err, \"failed to update the cassandradatacenter\", \"CassandraDatacenter\", cassdcKey)\n\t\t\treturn ctrl.Result{RequeueAfter: 10 * time.Second}, err\n\t\t}\n\t}\n\n\tr.Log.Info(\"restoring to new cassandradatacenter\")\n\n\tnewCassdc, err := buildNewCassandraDatacenter(restore, backup)\n\tif err != nil {\n\t\tr.Log.Error(err, \"failed to build new cassandradatacenter\")\n\t\treturn ctrl.Result{RequeueAfter: 10 * time.Second}, err\n\t}\n\n\tcassdcKey := types.NamespacedName{Namespace: newCassdc.Namespace, Name: newCassdc.Name}\n\n\tr.Log.Info(\"creating new cassandradatacenter\", \"CassandraDatacenter\", cassdcKey)\n\n\tif err = r.Create(ctx, newCassdc); err == nil {\n\t\tpatch := client.MergeFrom(restore.DeepCopy())\n\t\trestore.Status.StartTime = metav1.Now()\n\t\tif err = r.Status().Patch(ctx, restore, patch); err != nil {\n\t\t\tr.Log.Error(err, \"fail to patch status with start time\")\n\t\t\treturn ctrl.Result{RequeueAfter: 5 * time.Second}, err\n\t\t} else {\n\t\t\treturn ctrl.Result{RequeueAfter: 10 * time.Second}, err\n\t\t}\n\t} else {\n\t\tr.Log.Error(err, \"failed to create cassandradatacenter\", \"CassandraDatacenter\", cassdcKey)\n\t\treturn ctrl.Result{RequeueAfter: 30 * time.Second}, nil\n\t}\n}",
"func (f *FileCache) tailLog(rr *bufio.Reader) (b []byte, err error) {\n\tvar (\n\t\tt []byte\n\t)\n\t// peek magic\n\tfor {\n\t\tif b, err = rr.Peek(_logMagicSize); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif bytes.Equal(b, logMagic) {\n\t\t\tbreak\n\t\t}\n\t\trr.Discard(1)\n\t}\n\t// peek length\n\tif t, err = rr.Peek(_logHeadSize); err != nil {\n\t\tif err != io.EOF {\n\t\t\tlog.Error(\"rr.Peek(len:%d) error(%v)\", _logLenSize, err)\n\t\t}\n\t\treturn\n\t}\n\t// peek body\n\tl := int(binary.BigEndian.Uint32(t[_logMagicSize:_logHeadSize]))\n\tif t, err = rr.Peek(_logHeadSize + l); err != nil {\n\t\tif err != io.EOF {\n\t\t\tlog.Error(\"rr.Peek(%d) error(%v)\", l, err)\n\t\t}\n\t\treturn\n\t}\n\tb = t[_logHeadSize:]\n\trr.Discard(l + _logHeadSize)\n\treturn\n}",
"func CMOVQPC(mr, r operand.Op) { ctx.CMOVQPC(mr, r) }",
"func CriticalWithSkip(skip int, format string, v ...interface{}) {\n\tLog(skip+1, CRITICAL, format, v...)\n}",
"func RCLQ(ci, mr operand.Op) { ctx.RCLQ(ci, mr) }",
"func Critical(format string, v ...interface{}) {\n\tLog(1, CRITICAL, format, v...)\n}",
"func logUpdate(ch <-chan int, total int, msg string) {\n\tstart := time.Now()\n\ttimer := time.NewTimer(time.Minute)\n\tdefer timer.Stop()\n\tvar current int\n\tvar ok bool\n\tfor {\n\t\tselect {\n\t\tcase current, ok = <-ch:\n\t\t\tif !ok { // channel is closed\n\t\t\t\treturn\n\t\t\t}\n\t\tcase now := <-timer.C:\n\t\t\telapsed := now.Sub(start)\n\t\t\trate := elapsed / time.Duration(current)\n\t\t\teta := time.Duration(total-current) * rate\n\n\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\"current\": current,\n\t\t\t\t\"total\": total,\n\t\t\t\t\"percent\": (100 * current) / total,\n\t\t\t\t\"remain\": eta.Round(time.Minute),\n\t\t\t\t\"eta\": now.Add(eta).Round(time.Minute),\n\t\t\t}).Info(msg)\n\t\t\ttimer.Reset(time.Minute)\n\t\t}\n\t}\n}",
"func (this *AggregateBase) CumulateRemove(item, cumulative value.Value, context Context) (value.Value, error) {\n\treturn nil, fmt.Errorf(\"There is no %v.CumulateRemove().\", this.Name())\n}",
"func (d *Dumper) Run(ctx context.Context) error {\n\tdefer d.consumer.Close()\n\tdefer d.storage.Close()\n\n\tvar total, saved int\n\tvar firstMsg, lastMsg time.Time\n\tlastLog := time.Now()\n\n\tlogStats := func() {\n\t\tlog.Infof(\n\t\t\t\"Read messages from %s to %s (total %d, saved %d)\",\n\t\t\tfirstMsg.Local().Format(\"2006-01-02 15:04:05\"),\n\t\t\tlastMsg.Local().Format(\"2006-01-02 15:04:05\"),\n\t\t\ttotal, saved,\n\t\t)\n\t\tfirstMsg = time.Time{}\n\t\tlastMsg = time.Time{}\n\t\tlastLog = time.Now()\n\t}\n\tdefer logStats()\n\n\tfor {\n\t\tif ctx.Err() != nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tif time.Since(lastLog) > d.logPeriod {\n\t\t\tlogStats()\n\t\t}\n\n\t\tmsg, err := d.consumer.Read(ctx)\n\t\tif err == context.Canceled {\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to read message: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\ttotal++\n\n\t\tif msg.time.Before(firstMsg) || firstMsg.IsZero() {\n\t\t\tfirstMsg = msg.time\n\t\t}\n\t\tif msg.time.After(lastMsg) || lastMsg.IsZero() {\n\t\t\tlastMsg = msg.time\n\t\t}\n\n\t\tif !d.filter.Check(msg) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := d.storage.Save(msg); err != nil {\n\t\t\treturn fmt.Errorf(\"save message: %v\", err)\n\t\t}\n\t\tsaved++\n\t}\n}",
"func Log(client kclient.ClientInterface, componentName string, appName string, follow bool, command v1alpha2.Command) (io.ReadCloser, error) {\n\n\tpod, err := GetOnePod(client, componentName, appName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the component %s doesn't exist on the cluster\", componentName)\n\t}\n\n\tif pod.Status.Phase != corev1.PodRunning {\n\t\treturn nil, fmt.Errorf(\"unable to show logs, component is not in running state. current status=%v\", pod.Status.Phase)\n\t}\n\n\tcontainerName := command.Exec.Component\n\n\treturn client.GetPodLogs(pod.Name, containerName, follow)\n}",
"func recordGCDuration(duration time.Duration) {\n\tstorage.PromGCDurationMilliseconds.Observe(float64(duration.Nanoseconds()) / float64(time.Millisecond))\n}",
"func (r NopReporter) Recover(ctx context.Context) { _ = recover() }",
"func DebugcN(ctx context.Context, name, format string, v ...interface{}) {\n\tif logger, ok := mutil[name]; ok {\n\t\tlogger.Debugc(ctx, format, v...)\n\t}\n}",
"func (m *DeviceHealthScriptRunSummary) GetIssueRemediatedCumulativeDeviceCount()(*int32) {\n val, err := m.GetBackingStore().Get(\"issueRemediatedCumulativeDeviceCount\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}",
"func (r *raftLogGCTaskHandler) gcRaftLog(raftDb *badger.DB, regionId, startIdx, endIdx uint64) (uint64, error) {\n\t// Find the raft log idx range needed to be gc.\n\tfirstIdx := startIdx\n\tif firstIdx == 0 {\n\t\tfirstIdx = endIdx\n\t\terr := raftDb.View(func(txn *badger.Txn) error {\n\t\t\tstartKey := meta.RaftLogKey(regionId, 0)\n\t\t\tite := txn.NewIterator(badger.DefaultIteratorOptions)\n\t\t\tdefer ite.Close()\n\t\t\tif ite.Seek(startKey); ite.Valid() {\n\t\t\t\tvar err error\n\t\t\t\tif firstIdx, err = meta.RaftLogIndex(ite.Item().Key()); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tif firstIdx >= endIdx {\n\t\tlog.Infof(\"no need to gc, [regionId: %d]\", regionId)\n\t\treturn 0, nil\n\t}\n\n\traftWb := engine_util.WriteBatch{}\n\tfor idx := firstIdx; idx < endIdx; idx += 1 {\n\t\tkey := meta.RaftLogKey(regionId, idx)\n\t\traftWb.DeleteMeta(key)\n\t}\n\tif raftWb.Len() != 0 {\n\t\tif err := raftWb.WriteToDB(raftDb); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn endIdx - firstIdx, nil\n}",
"func (r *Reconciler) Reconcile(req reconcile.Request) (reconcile.Result, error) {\n\tlog := r.log.WithValues(\"request\", req)\n\tlog.Debug(\"Reconciling\")\n\n\tctx, cancel := context.WithTimeout(context.Background(), reconcileTimeout)\n\tdefer cancel()\n\n\ths := &v1alpha2.HealthScope{}\n\tif err := r.client.Get(ctx, req.NamespacedName, hs); err != nil {\n\t\treturn reconcile.Result{}, errors.Wrap(resource.IgnoreNotFound(err), errGetHealthScope)\n\t}\n\n\tinterval := longWait\n\tif hs.Spec.ProbeInterval != nil {\n\t\tinterval = time.Duration(*hs.Spec.ProbeInterval) * time.Second\n\t}\n\n\tif interval <= 0 {\n\t\tinterval = longWait\n\t}\n\n\tstart := time.Now()\n\n\tlog = log.WithValues(\"uid\", hs.GetUID(), \"version\", hs.GetResourceVersion())\n\n\thsStatus := r.GetScopeHealthStatus(ctx, hs)\n\tlog.Debug(\"Successfully ran health check\", \"scope\", hs.Name)\n\tr.record.Event(hs, event.Normal(reasonHealthCheck, \"Successfully ran health check\"))\n\n\telapsed := time.Since(start)\n\n\tif hsStatus.IsHealthy {\n\t\ths.Status.Health = \"healthy\"\n\t} else {\n\t\ths.Status.Health = \"unhealthy\"\n\t}\n\n\tdiagnosis, err := json.Marshal(hsStatus)\n\tif err != nil {\n\t\treturn reconcile.Result{}, errors.Wrap(err, errMarshalScopeDiagnosiis)\n\t}\n\n\t// sava diagnosis into status.conditions\n\t//TODO(roywang) is there a better way to show diagnosis\n\ths.SetConditions(v1alpha1.ReconcileSuccess().\n\t\tWithMessage(string(diagnosis)))\n\n\treturn reconcile.Result{RequeueAfter: interval - elapsed}, errors.Wrap(r.client.Status().Update(ctx, hs), errUpdateHealthScopeStatus)\n}",
"func PerCommandTracer(ctx context.Context) func(oldProcess func(cmd redis.Cmder) error) func(redis.Cmder) error {\n\treturn func(fn func(cmd redis.Cmder) error) func(redis.Cmder) error {\n\t\treturn func(cmd redis.Cmder) error {\n\t\t\t_, span := trace.StartSpan(ctx, fmt.Sprintf(\"redis-go/%s\", cmd.Name()))\n\t\t\tdefer span.End()\n\t\t\terr := fn(cmd)\n\t\t\tif err != nil {\n\t\t\t\tspan.SetStatus(trace.Status{Code: int32(trace.StatusCodeUnknown), Message: err.Error()})\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n}",
"func (self *ContainerCtx) GetContainerLog() {\n\n}"
] | [
"0.49208006",
"0.4722572",
"0.46637",
"0.4535993",
"0.44103763",
"0.42940488",
"0.42730057",
"0.42232832",
"0.4190888",
"0.41749713",
"0.41454777",
"0.41316202",
"0.4128051",
"0.4119966",
"0.41199565",
"0.4110273",
"0.40976158",
"0.40769556",
"0.40633926",
"0.404486",
"0.4020385",
"0.4017662",
"0.4003451",
"0.4002792",
"0.3999088",
"0.39965",
"0.39884007",
"0.3962555",
"0.39564845",
"0.39372966",
"0.3936362",
"0.3933878",
"0.3929654",
"0.39120573",
"0.391165",
"0.390573",
"0.38923812",
"0.3891505",
"0.38895127",
"0.38831732",
"0.38648435",
"0.3863738",
"0.38498646",
"0.3840073",
"0.38342452",
"0.3820709",
"0.38197216",
"0.3811998",
"0.38082528",
"0.38043782",
"0.38035896",
"0.38006276",
"0.37822196",
"0.37780574",
"0.37755066",
"0.37675214",
"0.37622446",
"0.37530148",
"0.37472048",
"0.37452212",
"0.37437055",
"0.3739149",
"0.37385157",
"0.37359744",
"0.37339804",
"0.37328854",
"0.37320384",
"0.37316194",
"0.37258193",
"0.37247586",
"0.37216368",
"0.37198606",
"0.37190324",
"0.3718529",
"0.37184304",
"0.3717642",
"0.37161916",
"0.37072232",
"0.37031925",
"0.3702285",
"0.37022594",
"0.37006932",
"0.36997333",
"0.3695849",
"0.3695604",
"0.3693802",
"0.3689366",
"0.3687353",
"0.36865684",
"0.36860433",
"0.36785343",
"0.36778465",
"0.36764795",
"0.3674867",
"0.36678964",
"0.3667249",
"0.3665623",
"0.36441627",
"0.36417055",
"0.36407924"
] | 0.70129484 | 0 |
RecovBytes returns an already serialized log, parsed from persistent storage or marshaled from the inmemory state. Its the most efficient approach on persistent configuration, avoiding an extra marshaling step during recovery. The command interpretation from the byte stream follows a simple slicing protocol, where the size of each command is binary encoded before the raw pbuff. | func (l *ListHT) RecovBytes(p, n uint64) ([]byte, error) {
if n < p {
return nil, errors.New("invalid interval request, 'n' must be >= 'p'")
}
l.mu.RLock()
defer l.mu.RUnlock()
if err := l.mayExecuteLazyReduce(p, n); err != nil {
return nil, err
}
return l.retrieveRawLog(p, n)
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (s *RawMessage) Bytes() []byte {\n\treturn s.Lines.Bytes()\n}",
"func (ev binlogEvent) dataBytes(f BinlogFormat) []byte {\n\tdata := ev.Bytes()[f.HeaderLength:]\n\tdata = data[0 : len(data)-BinlogCRC32ChecksumLen]\n\treturn data\n}",
"func FromBytes(b []byte) (*raft.Log, error) {\n\tvar l raft.Log\n\tif len(b) == 0 {\n\t\treturn nil, fmt.Errorf(\"invalid raft.Log message: 0 bytes\")\n\t}\n\tif b[0] == 'p' {\n\t\tvar p pb.RaftLog\n\t\tif err := proto.Unmarshal(b[1:], &p); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tl.Index = p.Index\n\t\tl.Term = p.Term\n\t\tl.Type = raft.LogType(p.Type)\n\t\tl.Data = p.Data\n\t\tl.Extensions = p.Extensions\n\t} else {\n\t\t// XXX(1.0): delete this branch, proto is used everywhere\n\t\tif err := json.Unmarshal(b, &l); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &l, nil\n}",
"func (v ResourceChange) Bytes() []byte {\n\tbuf := make([]byte, 28)\n\tb := 0\n\n\txgb.Put32(buf[b:], uint32(v.Timestamp))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Window))\n\tb += 4\n\n\tb += 20 // padding\n\n\treturn buf[:b]\n}",
"func (self *EV3Message) getBytes() []byte {\n\tself.commandSize = uint16(len(self.byteCodes)) + EV3MessageHeaderSize - 2 // 2 means commandSize = uint16 that should not be counted\n\tbuf := make([]byte, EV3MessageHeaderSize)\n\tbinary.LittleEndian.PutUint16(buf[0:], self.commandSize)\n\tbinary.LittleEndian.PutUint16(buf[2:], self.messageCount)\n\tbuf[4] = self.commandType\n\tbinary.LittleEndian.PutUint16(buf[5:], self.variablesReservation)\n\tbuf = append(buf, self.byteCodes...)\n\treturn buf\n}",
"func (self *EV3) receiveBytes() ([]byte, error) {\n\tif self.DebugOn == false {\n\t\t// Open port if not open yet\n\t\tif self.port == nil {\n\t\t\tconfig := &serial.Config{Name: self.PortName, Baud: self.PortBaud}\n\t\t\tvar err error\n\t\t\tself.port, err = serial.OpenPort(config)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Read size of following message\n\t\tbuf := make([]byte, 2)\n\t\tn, err := self.port.Read(buf)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t\treturn nil, err\n\t\t} else if n != len(buf) {\n\t\t\terr = errors.New(\"Too few bytes read: expected replay header\")\n\t\t\tlog.Fatal(err)\n\t\t\treturn nil, err\n\t\t}\n\t\treplySize := binary.LittleEndian.Uint16(buf)\n\n\t\t// Read message tail\n\t\tbufTail := make([]byte, replySize)\n\t\tn, err = self.port.Read(bufTail)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t\treturn nil, err\n\t\t} else if n != len(bufTail) {\n\t\t\terr = errors.New(\"Too few bytes read: expected replay tail\")\n\t\t\tlog.Fatal(err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Stitch and return\n\t\tbuf = append(buf, bufTail...)\n\t\tlog.Println(hex.EncodeToString(buf)) // DEBUG INFO\n\t\treturn buf, nil\n\t}\n\treturn make([]byte, 0), nil\n}",
"func (v CrtcChange) Bytes() []byte {\n\tbuf := make([]byte, 28)\n\tb := 0\n\n\txgb.Put32(buf[b:], uint32(v.Timestamp))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Window))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Crtc))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Mode))\n\tb += 4\n\n\txgb.Put16(buf[b:], v.Rotation)\n\tb += 2\n\n\tb += 2 // padding\n\n\txgb.Put16(buf[b:], uint16(v.X))\n\tb += 2\n\n\txgb.Put16(buf[b:], uint16(v.Y))\n\tb += 2\n\n\txgb.Put16(buf[b:], v.Width)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.Height)\n\tb += 2\n\n\treturn buf[:b]\n}",
"func (c ResponseCapture) Bytes() []byte {\n\treturn c.body.Bytes()\n}",
"func (t *target) recvCluMetaBytes(action string, body []byte, caller string) error {\n\tvar (\n\t\tcm cluMeta\n\t\terrs []error\n\t)\n\tif err := jsoniter.Unmarshal(body, &cm); err != nil {\n\t\treturn fmt.Errorf(cmn.FmtErrUnmarshal, t, \"clumeta\", cos.BHead(body), err)\n\t}\n\n\tdebug.Assert(cm.PrimeTime != 0, t.String()) // expecting\n\txreg.PrimeTime.Store(cm.PrimeTime)\n\txreg.MyTime.Store(time.Now().UnixNano())\n\n\tmsg := t.newAmsgStr(action, cm.BMD)\n\n\t// Config\n\tdebug.Assert(cm.Config != nil)\n\tif err := t.receiveConfig(cm.Config, msg, nil, caller); err != nil {\n\t\tif !isErrDowngrade(err) {\n\t\t\terrs = append(errs, err)\n\t\t\tnlog.Errorln(err)\n\t\t}\n\t} else {\n\t\tnlog.Infof(\"%s: recv-clumeta %s %s\", t, action, cm.Config)\n\t}\n\n\t// There's a window of time between:\n\t// a) target joining existing cluster and b) cluster starting to rebalance itself\n\t// The latter is driven by regMetasync (see regMetasync.go) distributing updated cluster map.\n\t// To handle incoming GETs within this window (which would typically take a few seconds or less)\n\t// we need to have the current cluster-wide regMetadata and the temporary gfn state:\n\treb.OnTimedGFN()\n\n\t// BMD\n\tif err := t.receiveBMD(cm.BMD, msg, nil /*ms payload */, bmdReg, caller, true /*silent*/); err != nil {\n\t\tif !isErrDowngrade(err) {\n\t\t\terrs = append(errs, err)\n\t\t\tnlog.Errorln(err)\n\t\t}\n\t} else {\n\t\tnlog.Infof(\"%s: recv-clumeta %s %s\", t, action, cm.BMD)\n\t}\n\t// Smap\n\tif err := t.receiveSmap(cm.Smap, msg, nil /*ms payload*/, caller, t.htrun.smapUpdatedCB); err != nil {\n\t\tif !isErrDowngrade(err) {\n\t\t\terrs = append(errs, err)\n\t\t\tnlog.Errorln(cmn.NewErrFailedTo(t, \"sync\", cm.Smap, err))\n\t\t}\n\t} else if cm.Smap != nil {\n\t\tnlog.Infof(\"%s: recv-clumeta %s %s\", t, action, cm.Smap)\n\t}\n\tswitch {\n\tcase errs == nil:\n\t\treturn nil\n\tcase len(errs) == 1:\n\t\treturn errs[0]\n\tdefault:\n\t\treturn cmn.NewErrFailedTo(t, action, \"clumeta\", errors.Join(errs...))\n\t}\n}",
"func (v OutputChange) Bytes() []byte {\n\tbuf := make([]byte, 28)\n\tb := 0\n\n\txgb.Put32(buf[b:], uint32(v.Timestamp))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.ConfigTimestamp))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Window))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Output))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Crtc))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Mode))\n\tb += 4\n\n\txgb.Put16(buf[b:], v.Rotation)\n\tb += 2\n\n\tbuf[b] = v.Connection\n\tb += 1\n\n\tbuf[b] = v.SubpixelOrder\n\tb += 1\n\n\treturn buf[:b]\n}",
"func TestLogRecovery(t *testing.T) {\n\tpath := setupLog(\n\t\t`cf4aab23 0000000000000001 0000000000000001 cmd_1 {\"val\":\"foo\",\"i\":20}`+\"\\n\" +\n\t\t`4c08d91f 0000000000000002 0000000000000001 cmd_2 {\"x\":100}`+\"\\n\" +\n\t\t`6ac5807c 0000000000000003 00000000000`)\n\tlog := NewLog()\n\tlog.AddCommandType(&TestCommand1{})\n\tlog.AddCommandType(&TestCommand2{})\n\tif err := log.Open(path); err != nil {\n\t\tt.Fatalf(\"Unable to open log: %v\", err)\n\t}\n\tdefer log.Close()\n\tdefer os.Remove(path)\n\n\tif err := log.Append(NewLogEntry(log, 3, 2, &TestCommand1{\"bat\", -5})); err != nil {\n\t\tt.Fatalf(\"Unable to append: %v\", err)\n\t}\n\n\t// Validate existing log entries.\n\tif len(log.entries) != 3 {\n\t\tt.Fatalf(\"Expected 2 entries, got %d\", len(log.entries))\n\t}\n\tif !reflect.DeepEqual(log.entries[0], NewLogEntry(log, 1, 1, &TestCommand1{\"foo\", 20})) {\n\t\tt.Fatalf(\"Unexpected entry[0]: %v\", log.entries[0])\n\t}\n\tif !reflect.DeepEqual(log.entries[1], NewLogEntry(log, 2, 1, &TestCommand2{100})) {\n\t\tt.Fatalf(\"Unexpected entry[1]: %v\", log.entries[1])\n\t}\n\tif !reflect.DeepEqual(log.entries[2], NewLogEntry(log, 3, 2, &TestCommand1{\"bat\", -5})) {\n\t\tt.Fatalf(\"Unexpected entry[2]: %v\", log.entries[2])\n\t}\n\n\t// Validate precommit log contents.\n\texpected :=\n\t\t`cf4aab23 0000000000000001 0000000000000001 cmd_1 {\"val\":\"foo\",\"i\":20}`+\"\\n\" +\n\t\t`4c08d91f 0000000000000002 0000000000000001 cmd_2 {\"x\":100}`+\"\\n\"\n\tactual, _ := ioutil.ReadFile(path)\n\tif string(actual) != expected {\n\t\tt.Fatalf(\"Unexpected buffer:\\nexp:\\n%s\\ngot:\\n%s\", expected, string(actual))\n\t}\n\n\t// Validate committed log contents.\n\tif err := log.SetCommitIndex(3); err != nil {\n\t\tt.Fatalf(\"Unable to partially commit: %v\", err)\n\t}\n\texpected =\n\t\t`cf4aab23 0000000000000001 0000000000000001 cmd_1 {\"val\":\"foo\",\"i\":20}`+\"\\n\" +\n\t\t`4c08d91f 0000000000000002 0000000000000001 cmd_2 {\"x\":100}`+\"\\n\" +\n\t\t`3f3f884c 0000000000000003 0000000000000002 cmd_1 {\"val\":\"bat\",\"i\":-5}`+\"\\n\"\n\tactual, _ = ioutil.ReadFile(path)\n\tif string(actual) != expected {\n\t\tt.Fatalf(\"Unexpected buffer:\\nexp:\\n%s\\ngot:\\n%s\", expected, string(actual))\n\t}\n}",
"func (l *Line) Bytes() []byte { return l.s }",
"func (r RawContractMessage) Bytes() []byte {\n\treturn r\n}",
"func RibFromBytes(b []byte) ([]*RIBMessage, error) {\n\tvar ribs []*RIBMessage\n\treader := bufio.NewReader(bytes.NewReader(b))\n\tfor {\n\t\tl, _, err := reader.ReadLine()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tr, err := RibEntryFromString(string(l))\n\t\tif err != nil {\n\t\t\treturn ribs, err\n\t\t}\n\t\tribs = append(ribs, r)\n\t}\n\n\treturn ribs, nil\n}",
"func (r *msgReader) readBytes(countI32 int32) []byte {\n\tif r.err != nil {\n\t\treturn nil\n\t}\n\n\tcount := int(countI32)\n\n\tif len(r.msgBody)-r.rp < count {\n\t\tr.fatal(errors.New(\"read past end of message\"))\n\t\treturn nil\n\t}\n\n\tb := r.msgBody[r.rp : r.rp+count]\n\tr.rp += count\n\n\tr.cr.KeepLast()\n\n\tif r.shouldLog(LogLevelTrace) {\n\t\tr.log(LogLevelTrace, \"msgReader.readBytes\", \"value\", b, r.msgType, \"rp\", r.rp)\n\t}\n\n\treturn b\n}",
"func (m LastDataMessage) Bytes() []byte {\n\tdlen := strconv.Itoa(len(m.Data))\n\tbytes := make([]byte, len(m.Err)+len(m.TID)+len(dlen)+len(m.Data)+4)\n\tvar i int\n\n\tbytes[i] = ']'\n\ti++\n\n\ti += copy(bytes[i:], m.Err)\n\tbytes[i] = '\\n'\n\ti++\n\n\ti += copy(bytes[i:], m.TID)\n\tbytes[i] = ' '\n\ti++\n\n\ti += copy(bytes[i:], dlen)\n\tbytes[i] = '\\n'\n\ti++\n\n\tcopy(bytes[i:], m.Data)\n\treturn bytes\n}",
"func (_LockProxy *LockProxyFilterer) ParseDebugBytes(log types.Log) (*LockProxyDebugBytes, error) {\n\tevent := new(LockProxyDebugBytes)\n\tif err := _LockProxy.contract.UnpackLog(event, \"DebugBytes\", log); err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}",
"func (b *Buffer) Bytes() []byte { return b.buf[:b.length] }",
"func (yp *YamlParser) readLineBytes() error {\n\tvar c uint\n\n\t// Clear read\n\typ.readCursor = 0\n\typ.readBytes = yp.readBytes[:0]\n\n\tfor {\n\t\tb, err := yp.reader.ReadByte()\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif b == '\\n' {\n\t\t\tc = uint(len(yp.readBytes))\n\n\t\t\t// Handle Windows' Line Endings\n\t\t\tif c > 1 && yp.readBytes[c-1] == '\\r' {\n\t\t\t\typ.readBytes = yp.readBytes[0 : c-1]\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\typ.readBytes = append(yp.readBytes, b)\n\t}\n\n\treturn nil\n}",
"func ReadBytes(r io.Reader, lenBuf []byte) (flag ControlFlag, m *Message, err error) {\n\t_, err = io.ReadAtLeast(r, lenBuf, 4)\n\tif err == io.EOF {\n\t\tflag = CloseChannel\n\t\treturn flag, NewMessage(CloseChannel, nil), err\n\t}\n\tsize := BytesToUint32(lenBuf)\n\tdata := make([]byte, int(size))\n\t_, err = io.ReadAtLeast(r, data, int(size))\n\tif err != nil || size == 0 {\n\t\treturn CloseChannel, NewMessage(CloseChannel, nil), err\n\t}\n\tmessage := LoadMessage(data)\n\t// println(\"read size:\", size, string(message.Data()), \".\")\n\treturn message.Flag(), message, nil\n}",
"func (w *Reflow) Bytes() []byte {\n\treturn w.buf.Bytes()\n}",
"func DecodeBytes(na ipld.NodeAssembler, src []byte) error {\n\tlog := new(types.Log)\n\tif err := rlp.DecodeBytes(src, log); err != nil {\n\t\treturn err\n\t}\n\treturn DecodeLog(na, *log)\n}",
"func (b *Buffer) LineBytes(n int) []byte {\n\tif n >= len(b.lines) {\n\t\treturn []byte{}\n\t}\n\treturn b.lines[n].data\n}",
"func (x *InvokeScriptResult_Call) GetArgsBytes() [][]byte {\n\tif x != nil {\n\t\treturn x.ArgsBytes\n\t}\n\treturn nil\n}",
"func (v ProviderChange) Bytes() []byte {\n\tbuf := make([]byte, 28)\n\tb := 0\n\n\txgb.Put32(buf[b:], uint32(v.Timestamp))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Window))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Provider))\n\tb += 4\n\n\tb += 16 // padding\n\n\treturn buf[:b]\n}",
"func (ev binlogEvent) Bytes() []byte {\n\treturn []byte(ev)\n}",
"func (f *Filter) PBytes() []byte {\n\tfilterData := make([]byte, len(f.filterNData)-3)\n\tfilterData[0] = f.p\n\tcopy(filterData[1:], f.filterNData[4:])\n\treturn filterData\n}",
"func (n NoopTCPReactor) NetlocBytes(_ context.Context, _ []byte) {}",
"func MessageFromBytes(bytes []byte) (result *Message, consumedBytes int, err error) {\n\tmarshalUtil := marshalutil.New(bytes)\n\tresult, err = MessageFromMarshalUtil(marshalUtil)\n\tif err != nil {\n\t\treturn\n\t}\n\tconsumedBytes = marshalUtil.ReadOffset()\n\n\tif len(bytes) != consumedBytes {\n\t\terr = xerrors.Errorf(\"consumed bytes %d not equal total bytes %d: %w\", consumedBytes, len(bytes), cerrors.ErrParseBytesFailed)\n\t}\n\treturn\n}",
"func (b *Buf) Bytes() []byte { return b.b }",
"func (s *stream) Reassembled(reassemblies []tcpassembly.Reassembly) {\n\tlog.Debugf(\"ressembled len: %d\", len(reassemblies))\n\tfor _, r := range reassemblies {\n\t\ts.buf = append(s.buf, r.Bytes...)\n\t\tfor {\n\t\t\tbodies, n, err := s.factory.decodeFunc(s.net, s.transport, s.buf)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debugf(\"unpack err: %+v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tusedBuf := s.buf[:n]\n\t\t\ts.buf = s.buf[n:]\n\n\t\t\tif len(bodies) == 0 {\n\t\t\t\tlog.Debugf(\"body is empty\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\trecord := &Record{\n\t\t\t\tType: RecordTypeTCP,\n\t\t\t\tBodies: bodies,\n\t\t\t\tNet: s.net,\n\t\t\t\tTransport: s.transport,\n\t\t\t\tSeen: r.Seen,\n\t\t\t\tBuffer: usedBuf,\n\t\t\t}\n\t\t\ts.factory.msgChan <- record\n\t\t}\n\t}\n}",
"func getStacktraceBytes() []byte {\n\tbuf := make([]byte, 1024)\n\tfor {\n\t\tn := runtime.Stack(buf, false)\n\t\tif n < len(buf) {\n\t\t\treturn buf[0:n]\n\t\t}\n\t\tbuf = make([]byte, 2*len(buf))\n\t}\n}",
"func Decode(r io.Reader) (*pb.Binlog, int64, error) {\n\tpayload, length, err := binlogfile.Decode(r)\n\tif err != nil {\n\t\treturn nil, 0, errors.Trace(err)\n\t}\n\n\tbinlog := &pb.Binlog{}\n\terr = binlog.Unmarshal(payload)\n\tif err != nil {\n\t\treturn nil, 0, errors.Trace(err)\n\t}\n\treturn binlog, length, nil\n}",
"func (p *PayloadFrame) Bytes() []byte {\n\tlen := len(p.data)\n\tbuf := make([]byte, FrameLengthFieldSize)\n\n\tappendFrameLength(buf, len)\n\tbuf = append(buf, p.data...)\n\treturn buf\n}",
"func (d *Decoder) Bytes() []byte {\n\tn := d.Varint()\n\tif n == 0 {\n\t\treturn nil\n\t}\n\tdata := make([]byte, n)\n\tnn, err := d.buf.Read(data)\n\tif int64(nn) != n || err != nil {\n\t\tlog.Panicf(\"unmarshalBytes: %d %d %v\", n, nn, err)\n\t}\n\treturn data\n}",
"func (cw *CapWriter) Bytes() []byte { return []byte(*cw) }",
"func (s *scratch) bytes() []byte { return s.data[0:s.fill] }",
"func ReadBytes(com Communicator, con *net.TCPConn, n int) string {\n\tgo util.Write(com.ILog(), \"Reading \"+strconv.Itoa(n)+\" bytes\\n\")\n\tr := make([]byte, n)\n\t_, err := con.Read(r)\n\tutil.Hand(com.ILog(), err, \"Error reading from connected port at \"+con.RemoteAddr().String(), \"Message (\"+string(r)+\") received from port at \"+con.RemoteAddr().String())\n\treturn string(r)\n}",
"func (s Status) Bytes() []byte {\n\tbuf := make([]byte, 20)\n\tbuf[0] = s.Inst0\n\tbuf[1] = s.Inst1\n\tbuf[2] = s.Inst2\n\tbuf[3] = s.Inst3\n\tbuf[4], buf[5] = fromU16(s.MemOP)\n\tbuf[6], buf[7] = fromU16(s.IY)\n\tbuf[8], buf[9] = fromU16(s.IX)\n\tbuf[10], buf[11] = fromU16(s.HL)\n\tbuf[12], buf[13] = fromU16(s.DE)\n\tbuf[14], buf[15] = fromU16(s.BC)\n\tbuf[16] = s.Flags\n\tbuf[17] = s.Accum\n\tbuf[18], buf[19] = fromU16(s.SP)\n\treturn buf\n}",
"func (m *OutMessage) Bytes() []byte {\n\tl := m.Len()\n\tsh := reflect.SliceHeader{\n\t\tData: uintptr(unsafe.Pointer(&m.header)),\n\t\tLen: l,\n\t\tCap: l,\n\t}\n\n\treturn *(*[]byte)(unsafe.Pointer(&sh))\n}",
"func cmdToBytes(cmd interface{}) []byte {\n\tvar buf bytes.Buffer\n\tenc := gob.NewEncoder(&buf)\n\tif err := enc.Encode(Command{Cmd: cmd}); nil != err {\n\t\tlog.Fatalf(\"failed to encode command: %s\", err)\n\t}\n\treturn buf.Bytes()\n}",
"func (n NoopTCPReactor) ClientBytes(_ context.Context, _ []byte) {}",
"func bytesReassemble(b []byte, piecesLengthArray []int64) (data []byte) {\n\tvar length = int64(len(piecesLengthArray))\n\tvar bytLength = int64(len(b))\n\tvar sum int64\n\tfor _, piecesLength := range piecesLengthArray {\n\t\tsum += piecesLength\n\t}\n\n\tif sum != bytLength {\n\t\tpanic(fmt.Errorf(\"byes sum is not matched with sum of piecesLengthArray, %d != %d\", bytLength, sum))\n\t}\n\tdata = make([]byte, bytLength)\n\tvar oldStart, start, subLength int64\n\n\tfor i := length - 1; i >= 0; i-- {\n\t\tsubLength = piecesLengthArray[i]\n\t\toldStart = bytLength - subLength\n\t\tcopy(data[start:start+subLength], b[oldStart:oldStart+subLength])\n\t\tstart += subLength\n\t\tbytLength -= subLength\n\t}\n\n\treturn data\n}",
"func (d *Decoder) RawBytes(data []byte) {\n\tn, err := d.buf.Read(data)\n\tif n != len(data) || err != nil {\n\t\tlog.Panicf(\"Decoder.RawBytes: %d %d %v\", n, len(data), err)\n\t}\n}",
"func (commit *Commit) Bytes() ([]byte, error) {\n\trequestBytes, err := proto.Marshal(commit.signedRequest)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshall SignedCommitStatusRequest protobuf: %w\", err)\n\t}\n\n\treturn requestBytes, nil\n}",
"func (mms *logMeasurements) bytes() int {\n\tvar b int\n\tfor k, v := range *mms {\n\t\tb += len(k)\n\t\tb += v.bytes()\n\t}\n\tb += int(unsafe.Sizeof(*mms))\n\treturn b\n}",
"func (c *cstr) Bytes() []byte {\n\thdr := &reflect.SliceHeader{\n\t\tData: uintptr(unsafe.Pointer(c.str.data)),\n\t\tLen: int(c.str.length),\n\t\tCap: int(c.str.length),\n\t}\n\treturn *(*[]byte)(unsafe.Pointer(hdr))\n}",
"func execmReaderReadContinuedLineBytes(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret, ret1 := args[0].(*textproto.Reader).ReadContinuedLineBytes()\n\tp.Ret(1, ret, ret1)\n}",
"func (n *Nats) ReadBytes() ([]byte, error) {\n\treturn nil, errors.New(\"nats provider does not support this method\")\n}",
"func (logEvent *Event) eventPayloadBytes() int {\n\treturn len(*logEvent.InputLogEvent.Message) + perEventHeaderBytes\n}",
"func (imr *InvokeMethodResponse) RawData() (r io.Reader) {\n\t// If the message has a data property, use that\n\tif imr.HasMessageData() {\n\t\t// HasMessageData() guarantees that the `imr.r.Message` and `imr.r.Message.Data` is not nil\n\t\treturn bytes.NewReader(imr.r.Message.Data.Value)\n\t}\n\n\treturn imr.replayableRequest.RawData()\n}",
"func (cl *Client) ExecBytes(cmd string, args ...interface{}) ([]byte, error) {\n\tvar b []byte\n\terr := cl.Conn(func(c *Conn) error {\n\t\tvar err error\n\t\tb, err = c.ExecBytes(cmd, args...)\n\t\treturn err\n\t})\n\treturn b, err\n}",
"func (p Packet) Bytes() []byte {\n\tlength := 1 + // opcode\n\t\t2 + // payload length in two bytes(uint16)\n\t\tlen(p.Payload) // length of the actual payload\n\n\tb := make([]byte, length)\n\tb[0] = byte(p.OpCode)\n\tb[1] = byte(len(p.Payload) >> 8)\n\tb[2] = byte(len(p.Payload))\n\n\tcopy(b[3:], p.Payload)\n\n\treturn b\n}",
"func (cb *codedBuffer) decodeRawBytes(alloc bool) (buf []byte, err error) {\n\tn, err := cb.decodeVarint()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnb := int(n)\n\tif nb < 0 {\n\t\treturn nil, fmt.Errorf(\"proto: bad byte length %d\", nb)\n\t}\n\tend := cb.index + nb\n\tif end < cb.index || end > len(cb.buf) {\n\t\treturn nil, io.ErrUnexpectedEOF\n\t}\n\n\tif !alloc {\n\t\tbuf = cb.buf[cb.index:end]\n\t\tcb.index = end\n\t\treturn\n\t}\n\n\tbuf = make([]byte, nb)\n\tcopy(buf, cb.buf[cb.index:])\n\tcb.index = end\n\treturn\n}",
"func ReadBytes(obj any, b []byte) error {\n\terr := toml.Unmarshal(b, obj)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\treturn nil\n}",
"func (msg MsgRagnarok) GetSignBytes() []byte {\n\treturn cosmos.MustSortJSON(ModuleCdc.MustMarshalJSON(msg))\n}",
"func (p *ReqPacket) Bytes() []byte {\r\n\tbuf := new(bytes.Buffer)\r\n\topcode := make([]byte, 2)\r\n\tbinary.BigEndian.PutUint16(opcode, p.GetType())\r\n\tbuf.Write(opcode)\r\n\tbuf.WriteString(p.Filename)\r\n\tbuf.WriteByte(0)\r\n\tbuf.WriteString(p.Mode)\r\n\tbuf.WriteByte(0)\r\n\tif p.BlockSize != 0 && p.BlockSize != 512 {\r\n\t\tbuf.WriteString(\"blksize\")\r\n\t\tbuf.WriteByte(0)\r\n\t\tbuf.WriteString(fmt.Sprint(p.BlockSize))\r\n\t\tbuf.WriteByte(0)\r\n\t}\r\n\treturn buf.Bytes()\r\n}",
"func unmarshalTradLog(rd io.Reader) ([]pb.Command, error) {\n\tcmds := make([]pb.Command, 0)\n\tfor j := 0; ; j++ {\n\t\tvar cmdLen int32\n\t\terr := binary.Read(rd, binary.BigEndian, &cmdLen)\n\t\tif err == io.EOF || err == io.ErrUnexpectedEOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\traw := make([]byte, cmdLen)\n\t\t_, err = rd.Read(raw)\n\t\tif err == io.EOF || err == io.ErrUnexpectedEOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tc := &pb.Command{}\n\t\terr = proto.Unmarshal(raw, c)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcmds = append(cmds, *c)\n\t}\n\treturn cmds, nil\n}",
"func (c *BinaryCodec) Bytes() []byte {\n return c.buf.Bytes()\n}",
"func (snapshot *DataSnapshot) Bytes() []byte {\n\treturn snapshot.raw\n}",
"func (c Command) Bytes(v ...interface{}) ([]byte, error) {\n\tstr := fmt.Sprintf(c.Prototype, v...)\n\tif strings.Contains(str, \"%!\") {\n\t\t// fmt.Printf(\"Arbiter: Malformed command: [%s] with args '%v'! I formed %q, which is incomplete\", c, v, str)\n\t\treturn []byte(str), ErrBytesArgs\n\t}\n\t//make sure whatever we stuffed matches the provided regexp\n\tif !c.CommandRegexp.MatchString(str) {\n\t\t// fmt.Printf(\"Malformed command: [%s] with args '%v'! I formed %q which does not match required regex %q\", c, v, str, c.CommandRegexp.String())\n\t\treturn []byte(str), ErrBytesFormat\n\t}\n\treturn []byte(str), nil\n\n}",
"func execmReaderReadDotBytes(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret, ret1 := args[0].(*textproto.Reader).ReadDotBytes()\n\tp.Ret(1, ret, ret1)\n}",
"func (reply Reply) Bytes() ([]byte, error) {\n\tresult, err := redis.Bytes(reply.data, reply.err)\n\tif err != nil {\n\t\treturn []byte{}, redisError(err)\n\t}\n\n\treturn result, nil\n}",
"func (s *ResponseModifier) ReadBytes() ([]byte, error) {\n\tbuf, err := ioutil.ReadAll(s.Response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.Bytes(buf)\n\treturn buf, nil\n}",
"func (s *Store) eventsFromBytes(data []byte) ([]core.Event, error) {\n\treturn s.eventcodec.EventsFromBytes(data)\n}",
"func ReceiveBytes(p PConn) ([]byte, error) {\n\tb := &bytesDecoder{}\n\terr := ReceiveInWriter(p, b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.buf, nil\n}",
"func (b *Buffer) bytes() []byte {\n\treturn b.data\n}",
"func (e *Event) packBytes() ([]byte, error) {\n\tdata := make([]interface{}, 2)\n\tdata[0] = e.Header\n\tdata[1] = e.Name\n\n\tfor _, a := range e.Args {\n\t\tdata = append(data, a)\n\t}\n\n\tvar buf []byte\n\n\tenc := codec.NewEncoderBytes(&buf, &mh)\n\tif err := enc.Encode(data); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf, nil\n}",
"func (msg MsgRevealSolution) GetSignBytes() []byte {\n\tbz := ModuleCdc.MustMarshalJSON(msg)\n\treturn sdk.MustSortJSON(bz)\n}",
"func CrtcChangeListBytes(buf []byte, list []CrtcChange) int {\n\tb := 0\n\tvar structBytes []byte\n\tfor _, item := range list {\n\t\tstructBytes = item.Bytes()\n\t\tcopy(buf[b:], structBytes)\n\t\tb += len(structBytes)\n\t}\n\treturn xgb.Pad(b)\n}",
"func (l *LeechedReadCloser) GetLog() []byte {\n\tif l.loggedBytesCount > 0 {\n\t\treturn l.data[:l.loggedBytesCount]\n\t}\n\treturn []byte(\"[Empty or not read by server]\")\n}",
"func (v Trigger) Bytes() []byte {\n\tbuf := make([]byte, 20)\n\tb := 0\n\n\txgb.Put32(buf[b:], uint32(v.Counter))\n\tb += 4\n\n\txgb.Put32(buf[b:], v.WaitType)\n\tb += 4\n\n\t{\n\t\tstructBytes := v.WaitValue.Bytes()\n\t\tcopy(buf[b:], structBytes)\n\t\tb += xgb.Pad(len(structBytes))\n\t}\n\n\txgb.Put32(buf[b:], v.TestType)\n\tb += 4\n\n\treturn buf\n}",
"func (l Line) Bytes() []byte {\n\treturn l.line\n}",
"func ReflowBytes(b []byte, limit int) []byte {\n\tf := NewReflow(limit)\n\t_, _ = f.Write(b)\n\tf.Close()\n\n\treturn f.Bytes()\n}",
"func (r *Rx) Bytes() []byte {\n\treturn r.p.buffer\n}",
"func (*GrpcLogRecord) Descriptor() ([]byte, []int) {\n\treturn file_gcp_observability_internal_logging_logging_proto_rawDescGZIP(), []int{0}\n}",
"func ReadBytes(data []byte) (Config, error) {\n\tc := Config{}\n\te := toml.Unmarshal(data, &c)\n\tif e == nil {\n\t\treturn c, nil\n\t}\n\terr := errors.Wrap(errUnmarshalConfigContent, e)\n\tif e := json.Unmarshal(data, &c); e != nil {\n\t\treturn c, errors.Wrap(err, e)\n\t}\n\treturn c, nil\n}",
"func (c app) ReceiveBytes(byt []byte) {\n\tvar dat []interface{}\n\n\tif err := json.Unmarshal(byt, &dat); err != nil {\n\t\tInfo(\"Unable to unmarshal json! Message: \", dat)\n\t} else {\n\t\tif m, err := c.serializer.deserializeString(dat); err == nil {\n\t\t\tc.in <- m\n\t\t} else {\n\t\t\tInfo(\"Unable to unmarshal json string! Message: \", m)\n\t\t}\n\t}\n}",
"func (s SequencerData) Raw() []byte {\n\treturn (&metaMessage{\n\t\tTyp: byteSequencerSpecific,\n\t\tData: s.Data(),\n\t}).Bytes()\n}",
"func Bytes() []byte {\n\treturn conf.Bytes()\n}",
"func (s *SOC) toBytes() []byte {\n\tbuf := bytes.NewBuffer(nil)\n\tbuf.Write(s.id)\n\tbuf.Write(s.signature)\n\tbuf.Write(s.chunk.Data())\n\treturn buf.Bytes()\n}",
"func execmReaderReadLineBytes(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret, ret1 := args[0].(*textproto.Reader).ReadLineBytes()\n\tp.Ret(1, ret, ret1)\n}",
"func (m FirstDataMessage) Bytes() []byte {\n\tdlen := strconv.Itoa(len(m.Data))\n\tbytes := make([]byte, len(m.Host)+len(m.TID)+len(dlen)+len(m.Data)+4)\n\tvar i int\n\n\tbytes[i] = '['\n\ti++\n\n\ti += copy(bytes[i:], m.Host)\n\tbytes[i] = '\\n'\n\ti++\n\n\ti += copy(bytes[i:], m.TID)\n\tbytes[i] = ' '\n\ti++\n\n\ti += copy(bytes[i:], dlen)\n\tbytes[i] = '\\n'\n\ti++\n\n\tcopy(bytes[i:], m.Data)\n\treturn bytes\n}",
"func (b *bloomFilter) bytes() []byte {\n\tif b == nil || b.BloomFilter == nil {\n\t\treturn nil\n\t}\n\tvar buf bytes.Buffer\n\t_, err := b.WriteTo(&buf)\n\tif err != nil {\n\t\tlogger.LogIf(GlobalContext, err)\n\t\treturn nil\n\t}\n\treturn buf.Bytes()\n}",
"func marshal(msgType uint8, msg interface{}) []byte {\n\tvar out []byte\n\tout = append(out, msgType)\n\n\tv := reflect.ValueOf(msg)\n\tstructType := v.Type()\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tfield := v.Field(i)\n\t\tt := field.Type()\n\t\tswitch t.Kind() {\n\t\tcase reflect.Bool:\n\t\t\tvar v uint8\n\t\t\tif field.Bool() {\n\t\t\t\tv = 1\n\t\t\t}\n\t\t\tout = append(out, v)\n\t\tcase reflect.Array:\n\t\t\tif t.Elem().Kind() != reflect.Uint8 {\n\t\t\t\tpanic(\"array of non-uint8\")\n\t\t\t}\n\t\t\tfor j := 0; j < t.Len(); j++ {\n\t\t\t\tout = append(out, byte(field.Index(j).Uint()))\n\t\t\t}\n\t\tcase reflect.Uint32:\n\t\t\tu32 := uint32(field.Uint())\n\t\t\tout = append(out, byte(u32>>24))\n\t\t\tout = append(out, byte(u32>>16))\n\t\t\tout = append(out, byte(u32>>8))\n\t\t\tout = append(out, byte(u32))\n\t\tcase reflect.String:\n\t\t\ts := field.String()\n\t\t\tout = append(out, byte(len(s)>>24))\n\t\t\tout = append(out, byte(len(s)>>16))\n\t\t\tout = append(out, byte(len(s)>>8))\n\t\t\tout = append(out, byte(len(s)))\n\t\t\tout = append(out, s...)\n\t\tcase reflect.Slice:\n\t\t\tswitch t.Elem().Kind() {\n\t\t\tcase reflect.Uint8:\n\t\t\t\tlength := field.Len()\n\t\t\t\tif structType.Field(i).Tag.Get(\"ssh\") != \"rest\" {\n\t\t\t\t\tout = append(out, byte(length>>24))\n\t\t\t\t\tout = append(out, byte(length>>16))\n\t\t\t\t\tout = append(out, byte(length>>8))\n\t\t\t\t\tout = append(out, byte(length))\n\t\t\t\t}\n\t\t\t\tfor j := 0; j < length; j++ {\n\t\t\t\t\tout = append(out, byte(field.Index(j).Uint()))\n\t\t\t\t}\n\t\t\tcase reflect.String:\n\t\t\t\tvar length int\n\t\t\t\tfor j := 0; j < field.Len(); j++ {\n\t\t\t\t\tif j != 0 {\n\t\t\t\t\t\tlength++ /* comma */\n\t\t\t\t\t}\n\t\t\t\t\tlength += len(field.Index(j).String())\n\t\t\t\t}\n\n\t\t\t\tout = append(out, byte(length>>24))\n\t\t\t\tout = append(out, byte(length>>16))\n\t\t\t\tout = append(out, byte(length>>8))\n\t\t\t\tout = append(out, byte(length))\n\t\t\t\tfor j := 0; j < field.Len(); j++ {\n\t\t\t\t\tif j != 0 {\n\t\t\t\t\t\tout = append(out, ',')\n\t\t\t\t\t}\n\t\t\t\t\tout = append(out, field.Index(j).String()...)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tpanic(\"slice of unknown type\")\n\t\t\t}\n\t\tcase reflect.Ptr:\n\t\t\tif t == bigIntType {\n\t\t\t\tvar n *big.Int\n\t\t\t\tnValue := reflect.ValueOf(&n)\n\t\t\t\tnValue.Elem().Set(field)\n\t\t\t\tneeded := intLength(n)\n\t\t\t\toldLength := len(out)\n\n\t\t\t\tif cap(out)-len(out) < needed {\n\t\t\t\t\tnewOut := make([]byte, len(out), 2*(len(out)+needed))\n\t\t\t\t\tcopy(newOut, out)\n\t\t\t\t\tout = newOut\n\t\t\t\t}\n\t\t\t\tout = out[:oldLength+needed]\n\t\t\t\tmarshalInt(out[oldLength:], n)\n\t\t\t} else {\n\t\t\t\tpanic(\"pointer to unknown type\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn out\n}",
"func (b *BaseImpl) R(off int) []byte {\n\tif len(b.Diffs) == 0 {\n\t\treturn b.readerR(off)\n\t}\n\n\tn, e := loncha.LastIndexOf(b.Diffs, func(i int) bool {\n\t\treturn b.Diffs[i].Offset <= off && off < (b.Diffs[i].Offset+len(b.Diffs[i].bytes))\n\t})\n\tif e == nil && n >= 0 {\n\t\treturn b.Diffs[n].bytes[(off - b.Diffs[n].Offset):]\n\t}\n\n\tif len(b.bytes) < off {\n\t\tLog(LOG_WARN, func() LogArgs {\n\t\t\treturn F(\"base.R(): remain offset=%d lenBuf()=%d \\n\",\n\t\t\t\toff, b.LenBuf())\n\t\t})\n\t}\n\n\treturn b.bytes[off:]\n}",
"func (b *Builder) Bytes() ([]byte, error) {\n\tif b.err != nil {\n\t\treturn nil, b.err\n\t}\n\treturn b.result[b.offset:], nil\n}",
"func (p *Buffer) Bytes() []byte { return p.buf }",
"func (b *buffer) bytes(n int) []byte {\n\tdata := b.unsafeBytes(n)\n\tif !b.shared {\n\t\treturn data\n\t}\n\t// TODO(kortschak): Replace this with bytes.Clone when available.\n\t// See https://github.com/golang/go/issues/45038 for bytes.Clone.\n\treturn append(data[:0:0], data...)\n}",
"func (n *NegotiateMessage) Bytes() []byte {\n\tpayloadLen := int(n.DomainNameFields.Len + n.WorkstationFields.Len)\n\n\tmessageBytes := make([]byte, 0, n.PayloadOffset+payloadLen)\n\tbuffer := bytes.NewBuffer(messageBytes)\n\tbuffer.Write(n.Signature)\n\tbinary.Write(buffer, binary.LittleEndian, n.MessageType)\n\tbinary.Write(buffer, binary.LittleEndian, n.NegotiateFlags)\n\n\tbuffer.Write(n.DomainNameFields.Bytes())\n\tbuffer.Write(n.WorkstationFields.Bytes())\n\tbuffer.Write(n.Version.Bytes())\n\n\tbuffer.Write(n.DomainNameFields.Payload)\n\tbuffer.Write(n.WorkstationFields.Payload)\n\n\treturn buffer.Bytes()\n}",
"func ResourceChangeListBytes(buf []byte, list []ResourceChange) int {\n\tb := 0\n\tvar structBytes []byte\n\tfor _, item := range list {\n\t\tstructBytes = item.Bytes()\n\t\tcopy(buf[b:], structBytes)\n\t\tb += len(structBytes)\n\t}\n\treturn xgb.Pad(b)\n}",
"func (r *Request) dumpCbor() []byte {\n\tvar buf []byte\n\te := codec.NewEncoderBytes(&buf, dots_common.NewCborHandle())\n\n\terr := e.Encode(r.Message)\n\tif err != nil {\n\t\tlog.Errorf(\"Error decoding %s\", err)\n\t}\n\treturn buf\n}",
"func ParseBytes(data []byte) ([]redis.Reply, error) {\n\tch := make(chan *Payload)\n\treader := bytes.NewReader(data)\n\tgo parse0(reader, ch)\n\tvar results []redis.Reply\n\tfor payload := range ch {\n\t\tif payload == nil {\n\t\t\treturn nil, errors.New(\"no reply\")\n\t\t}\n\t\tif payload.Err != nil {\n\t\t\tif payload.Err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn nil, payload.Err\n\t\t}\n\t\tresults = append(results, payload.Data)\n\t}\n\treturn results, nil\n}",
"func (v ScreenChangeNotifyEvent) Bytes() []byte {\n\tbuf := make([]byte, 32)\n\tb := 0\n\n\t// write event number\n\tbuf[b] = 0\n\tb += 1\n\n\tbuf[b] = v.Rotation\n\tb += 1\n\n\tb += 2 // skip sequence number\n\n\txgb.Put32(buf[b:], uint32(v.Timestamp))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.ConfigTimestamp))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Root))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.RequestWindow))\n\tb += 4\n\n\txgb.Put16(buf[b:], v.SizeID)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.SubpixelOrder)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.Width)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.Height)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.Mwidth)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.Mheight)\n\tb += 2\n\n\treturn buf\n}",
"func (r *RecBytes) Serialize() []byte {\n\tres := make([]byte, 0, len(r.Path)+len(r.Time)+len(r.Val)+3)\n\tres = append(res, r.Path...)\n\tres = append(res, ' ')\n\tres = append(res, r.Val...)\n\tres = append(res, ' ')\n\tres = append(res, r.Time...)\n\tres = append(res, '\\n')\n\n\treturn res\n}",
"func (h *proxyHandler) returnBytes(retval any, buf []byte) (replyBuf, error) {\n\tvar ret replyBuf\n\tpiper, f, err := h.allocPipe()\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tgo func() {\n\t\t// Signal completion when we return\n\t\tdefer f.wg.Done()\n\t\t_, err = io.Copy(f.w, bytes.NewReader(buf))\n\t\tif err != nil {\n\t\t\tf.err = err\n\t\t}\n\t}()\n\n\tret.value = retval\n\tret.fd = piper\n\tret.pipeid = uint32(f.w.Fd())\n\treturn ret, nil\n}",
"func (consensus *Consensus) constructCommittedMessage() ([]byte, *bls.Sign) {\n\tmessage := &msg_pb.Message{\n\t\tServiceType: msg_pb.ServiceType_CONSENSUS,\n\t\tType: msg_pb.MessageType_COMMITTED,\n\t\tRequest: &msg_pb.Message_Consensus{\n\t\t\tConsensus: &msg_pb.ConsensusRequest{},\n\t\t},\n\t}\n\n\tconsensusMsg := message.GetConsensus()\n\tconsensus.populateMessageFields(consensusMsg)\n\n\t//// Payload\n\tbuffer := bytes.NewBuffer([]byte{})\n\n\t// 96 bytes aggregated signature\n\taggSig := bls_cosi.AggregateSig(consensus.Decider.ReadAllSignatures(quorum.Commit))\n\tbuffer.Write(aggSig.Serialize())\n\n\t// Bitmap\n\tbuffer.Write(consensus.commitBitmap.Bitmap)\n\n\tconsensusMsg.Payload = buffer.Bytes()\n\t//// END Payload\n\n\tmarshaledMessage, err := consensus.signAndMarshalConsensusMessage(message)\n\tif err != nil {\n\t\tutils.Logger().Error().Err(err).Msg(\"Failed to sign and marshal the Committed message\")\n\t}\n\treturn proto.ConstructConsensusMessage(marshaledMessage), aggSig\n}",
"func (o DiagnosticFrontendRequestOutput) BodyBytes() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v DiagnosticFrontendRequest) *int { return v.BodyBytes }).(pulumi.IntPtrOutput)\n}",
"func (s *Stream) Raw() ([]byte, error) {\n\t// get the kind and size of encoded data s.r\n\tkind, size, err := s.Kind()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// if it is a single byte, the value is stored in s.byteval, therefore can be returned directly\n\tif kind == Byte {\n\t\ts.kind = -1 // re-initialize s.Kind\n\t\treturn []byte{s.byteval}, nil\n\t}\n\n\t// get the size of the string heads and make a byte slice with its' total length\n\t// which is data length + length of heads\n\tstart := headsize(size)\n\tbuf := make([]byte, uint64(start)+size)\n\n\t// stores the remaining data (data without headers) into buf\n\tif err := s.readFull(buf[start:]); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// based on data kind, place the headers in front of the buf\n\tif kind == String {\n\t\tputhead(buf, 0x80, 0xB7, size)\n\t} else {\n\t\tputhead(buf, 0xC0, 0xF7, size)\n\t}\n\treturn buf, nil\n}",
"func (*LogLine) Descriptor() ([]byte, []int) {\n\treturn file_orc8r_protos_magmad_proto_rawDescGZIP(), []int{13}\n}"
] | [
"0.52389896",
"0.5144103",
"0.50607276",
"0.49671805",
"0.49524936",
"0.49298233",
"0.4843156",
"0.4829514",
"0.48156932",
"0.47976077",
"0.47847566",
"0.47826695",
"0.47697",
"0.47467706",
"0.47122368",
"0.47065148",
"0.46898136",
"0.46788946",
"0.46786302",
"0.46746302",
"0.46698865",
"0.4666791",
"0.46508628",
"0.46226758",
"0.4614741",
"0.4603422",
"0.4594472",
"0.4573487",
"0.4541283",
"0.4534895",
"0.45294634",
"0.45287672",
"0.45067152",
"0.4492878",
"0.44820282",
"0.44687307",
"0.44677877",
"0.4464996",
"0.44648263",
"0.44629046",
"0.4461398",
"0.44610292",
"0.44528458",
"0.44341016",
"0.44222078",
"0.44220406",
"0.44195926",
"0.4413939",
"0.44082317",
"0.4393962",
"0.43919888",
"0.43916532",
"0.4387589",
"0.4386354",
"0.4350938",
"0.4340193",
"0.4336119",
"0.4334265",
"0.43327582",
"0.4330626",
"0.43303546",
"0.43301177",
"0.43300188",
"0.43283963",
"0.43237102",
"0.43200368",
"0.4317794",
"0.43168187",
"0.4314389",
"0.43122062",
"0.43037248",
"0.43008333",
"0.43002215",
"0.42920503",
"0.42886996",
"0.42883274",
"0.4284211",
"0.42836165",
"0.42833337",
"0.4278244",
"0.42776322",
"0.42771482",
"0.4276058",
"0.42744336",
"0.42736074",
"0.42655268",
"0.42634958",
"0.4262487",
"0.42607394",
"0.42532218",
"0.42522886",
"0.42515117",
"0.42495373",
"0.4245476",
"0.42418933",
"0.42405748",
"0.42368603",
"0.4236099",
"0.42339402",
"0.42302373"
] | 0.6060449 | 0 |
ReduceLog applies the configured reduce algorithm and updates the current log state. Must only be called within mutual exclusion scope. | func (l *ListHT) ReduceLog(p, n uint64) error {
cmds, err := ApplyReduceAlgo(l, l.config.Alg, p, n)
if err != nil {
return err
}
return l.updateLogState(cmds, p, n, false)
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func Reduce(r Reducer, d *datatransfer.Diff) (*datatransfer.Diff, error) {\n\tdiff := r.Reduce(d)\n\treturn diff, nil\n}",
"func (l *Logger) Log(entry workerutil.ExecutionLogEntry) {\n\tl.entries = append(l.entries, redact(entry, l.replacer))\n}",
"func (rf *Raft) TruncateLog(lastAppliedIndex int) {\n\trf.mu.Lock()\n\tif lastAppliedIndex <= rf.lastApplied && lastAppliedIndex >= rf.Log.LastIncludedLength {\n\t\trf.Log.LastIncludedTerm = rf.Log.Entries[lastAppliedIndex-rf.Log.LastIncludedLength].Term\n\t\trf.Log.Entries = rf.Log.Entries[(lastAppliedIndex - rf.Log.LastIncludedLength + 1):]\n\t\trf.Log.LastIncludedLength = lastAppliedIndex + 1\n\t}\n\trf.mu.Unlock()\n}",
"func (w *SimpleMapReduce) Reduce (reduceFn ReduceFn) *SimpleMapReduce {\n w.reduceFn = reduceFn\n return w\n}",
"func (parser *MarpaParser) earleyReduce(location int, item EarleyItem, term Term, trigger EarleyItem, nodes map[string]*SppfNode) {\n\ttoAH := parser.machine.Goto(item.state, term)\n\tif toAH > -1 {\n\t\tk := item.parent\n\t\tz := item.parseNode\n\t\tw := trigger.parseNode\n\t\ty := parser.MakeParseNode(term, k, location, z, w, nodes)\n\t\t/*fmt.Println(\"REDUCE\", y)\n\t\tif y != w {\n\t\t\tfmt.Println(\"w \", w)\n\t\t}\n\t\tif y != z {\n\t\t\tfmt.Println(\"z \", z)\n\t\t}*/\n\t\tparser.addEIM(location, toAH, item.parent, y)\n\t}\n}",
"func (z *Big) Reduce() *Big { return z.Context.Reduce(z) }",
"func (s *storage) clearLog() error {\n\tif err := s.log.Reset(s.snaps.index); err != nil {\n\t\treturn opError(err, \"Log.Reset(%d)\", s.snaps.index)\n\t}\n\tassert(s.log.LastIndex() == s.snaps.index)\n\tassert(s.log.PrevIndex() == s.snaps.index)\n\ts.lastLogIndex, s.lastLogTerm = s.snaps.index, s.snaps.term\n\treturn nil\n}",
"func (r *RaftNode) executeLog() {\n\tfor r.commitIndex > r.lastApplied {\n\t\tr.lastApplied++\n\t\tr.StateMachine.apply(r.Log[r.lastApplied])\n\t}\n}",
"func (w *Window) Reduce() interface{} {\n\treturn w.reducedAt(time.Now())\n}",
"func (rf *Raft) TrimLog(lastIncludedIndex int, lastIncludedTerm int) []byte {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\trf.lastIncludedIndex = lastIncludedIndex\n\trf.lastIncludedTerm = lastIncludedTerm\n\ttrimIdx := rf.getTrimmedLogIndex(rf.lastIncludedIndex)\n\tif trimIdx < len(rf.log) {\n\t\trf.log = rf.log[trimIdx+1:]\n\t} else {\n\t\trf.log = []LogEntry{}\n\t}\n\trf.Log(LogInfo, \"New Snapshot loaded.\\n - LastIncludedIndex\", lastIncludedIndex, \"\\n - LastIncludedTerm\", lastIncludedTerm, \"\\n - rf.log\", rf.log)\n\treturn rf.GetStateBytes(false)\n}",
"func (a *Aggregator) Log(l *logrus.Entry, round uint64, step uint8) {\n\ttarget := a.handler.Quorum(round)\n\n\tfor hash, sv := range a.voteSets {\n\t\ttotal := sv.Cluster.TotalOccurrences()\n\n\t\tl.WithField(\"hash\", util.StringifyBytes([]byte(hash))).\n\t\t\tWithField(\"total\", total).\n\t\t\tWithField(\"round\", round).\n\t\t\tWithField(\"step\", step).\n\t\t\tWithField(\"quorum_target\", target).Info()\n\t}\n}",
"func (a *AvgLogger) LogUpdate(workerID int, criticMSE anyvec.Numeric) {\n\tif avg := a.updateAvg.Add(a.Update, a.Creator, criticMSE); avg != nil {\n\t\ta.Logger.LogUpdate(workerID, avg)\n\t}\n}",
"func (s *StandardLogger) LogUpdate(workerID int, criticMSE anyvec.Numeric) {\n\tif s.Update {\n\t\tlog.Printf(\"update: worker=%d critic_mse=%f\", workerID, criticMSE)\n\t}\n}",
"func (statusCnf *StatusConfig) LogReaded(inode uint64, name string, readed uint64) {\n\tlogRecord := new(LogRecord)\n\tlogRecord.Inode = inode\n\tlogRecord.Readed = readed\n\tlogRecord.Name = name\n\tstatusCnf.LogMap[strconv.FormatUint(inode, 10)] = *logRecord\n}",
"func Reduce(elements []Value, memo Value, reductor BiMapper) Value {\n\tfor _, elem := range elements {\n\t\tmemo = reductor(memo, elem)\n\t}\n\treturn memo\n}",
"func (a *AvgLogger) LogRegularize(workerID int, term anyvec.Numeric) {\n\tif avg := a.regularizeAvg.Add(a.Regularize, a.Creator, term); avg != nil {\n\t\ta.Logger.LogRegularize(workerID, avg)\n\t}\n}",
"func (op *LogOp) ApplyTo(cstate consensus.State) (consensus.State, error) {\n\tstate, ok := cstate.(state.State)\n\tvar err error\n\tif !ok {\n\t\t// Should never be here\n\t\tpanic(\"received unexpected state type\")\n\t}\n\n\tswitch op.Type {\n\tcase LogOpPin:\n\t\targ := op.Cid.ToPin()\n\t\terr = state.Add(arg)\n\t\tif err != nil {\n\t\t\tgoto ROLLBACK\n\t\t}\n\t\t// Async, we let the PinTracker take care of any problems\n\t\top.rpcClient.Go(\"\",\n\t\t\t\"Cluster\",\n\t\t\t\"Track\",\n\t\t\targ.ToSerial(),\n\t\t\t&struct{}{},\n\t\t\tnil)\n\tcase LogOpUnpin:\n\t\targ := op.Cid.ToPin()\n\t\terr = state.Rm(arg.Cid)\n\t\tif err != nil {\n\t\t\tgoto ROLLBACK\n\t\t}\n\t\t// Async, we let the PinTracker take care of any problems\n\t\top.rpcClient.Go(\"\",\n\t\t\t\"Cluster\",\n\t\t\t\"Untrack\",\n\t\t\targ.ToSerial(),\n\t\t\t&struct{}{},\n\t\t\tnil)\n\tcase LogOpAddPeer:\n\t\taddr := op.Peer.ToMultiaddr()\n\t\top.rpcClient.Call(\"\",\n\t\t\t\"Cluster\",\n\t\t\t\"PeerManagerAddPeer\",\n\t\t\tapi.MultiaddrToSerial(addr),\n\t\t\t&struct{}{})\n\t\t// TODO rebalance ops\n\tcase LogOpRmPeer:\n\t\taddr := op.Peer.ToMultiaddr()\n\t\tpidstr, err := addr.ValueForProtocol(ma.P_IPFS)\n\t\tif err != nil {\n\t\t\tpanic(\"peer badly encoded\")\n\t\t}\n\t\tpid, err := peer.IDB58Decode(pidstr)\n\t\tif err != nil {\n\t\t\tpanic(\"could not decode a PID we ourselves encoded\")\n\t\t}\n\t\top.rpcClient.Call(\"\",\n\t\t\t\"Cluster\",\n\t\t\t\"PeerManagerRmPeer\",\n\t\t\tpid,\n\t\t\t&struct{}{})\n\t\t// TODO rebalance ops\n\tdefault:\n\t\tlogger.Error(\"unknown LogOp type. Ignoring\")\n\t}\n\treturn state, nil\n\nROLLBACK:\n\t// We failed to apply the operation to the state\n\t// and therefore we need to request a rollback to the\n\t// cluster to the previous state. This operation can only be performed\n\t// by the cluster leader.\n\tlogger.Error(\"Rollbacks are not implemented\")\n\treturn nil, errors.New(\"a rollback may be necessary. Reason: \" + err.Error())\n}",
"func (f *FSM) Apply(log *raft.Log) interface{} {\n\t// Lock the registry for the entire duration of the command\n\t// handlers. This is fine since no other write change can happen\n\t// anyways while we're running. This might slowdown a bit opening new\n\t// leader connections, but since application should be designed to open\n\t// their leaders once for all, it shouldn't be a problem in\n\t// practice. Read transactions are not be affected by the locking.\n\tf.registry.Lock()\n\tdefer f.registry.Unlock()\n\n\ttracer := f.registry.TracerFSM()\n\n\t// If we're being invoked in the context of a Methods replication hook\n\t// applying a log command, block execution of any log commands coming\n\t// on the wire from other leaders until the hook as completed.\n\tif f.registry.HookSyncPresent() && !f.registry.HookSyncMatches(log.Data) {\n\t\ttracer.Message(\"wait for methods hook to complete\")\n\t\t// This will temporarily release and re-acquire the registry lock.\n\t\tf.registry.HookSyncWait()\n\t}\n\n\terr := f.apply(tracer, log)\n\tif err != nil {\n\t\tif f.panicOnFailure {\n\t\t\ttracer.Panic(\"%v\", err)\n\t\t}\n\t\ttracer.Error(\"apply failed\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func (r *RollingPolicy) Reduce(f func(Iterator) float64) (val float64) {\n\tr.mu.RLock()\n\ttimespan := r.timespan()\n\tif count := r.size - timespan; count > 0 {\n\t\toffset := r.offset + timespan + 1\n\t\tif offset >= r.size {\n\t\t\toffset = offset - r.size\n\t\t}\n\t\tval = f(r.window.Iterator(offset, count))\n\t}\n\tr.mu.RUnlock()\n\treturn val\n}",
"func (r *RollingPolicy) Reduce(f func(Iterator) float64) (val float64) {\n\tr.mu.RLock()\n\ttimespan := r.timespan()\n\tif count := r.size - timespan; count > 0 {\n\t\toffset := r.offset + timespan + 1\n\t\tif offset >= r.size {\n\t\t\toffset = offset - r.size\n\t\t}\n\t\tval = f(r.window.Iterator(offset, count))\n\t}\n\tr.mu.RUnlock()\n\treturn val\n}",
"func (parser *MarpaParser) leoReduce(location int, item EarleyItem) {\n\ttoAH := parser.machine.Goto(item.state, item.symbol)\n\tif toAH > -1 {\n\t\t//fmt.Println(\"Leo reduction to\", item.parent, location)\n\t\tparser.addEIM(location, toAH, item.parent, nil)\n\t}\n}",
"func (s *Server) RotateLog() {\n\n\tif s.logch == nil {\n\t\treturn\n\t}\n\n\t// send empty msg as signal\n\ts.logch <- &Collect{}\n}",
"func Reduce(ss []string, initialAccumulator string, f AccumulatorFunc) string {\n\tif ss == nil {\n\t\treturn initialAccumulator\n\t}\n\tacc := initialAccumulator\n\tfor i, s := range ss {\n\t\tacc = f(acc, i, s)\n\t}\n\treturn acc\n}",
"func (m *Map) Reduce(\n\treduce func(map[interface{}]interface{}) interface{},\n\tjoin func(x, y interface{}) interface{},\n) interface{} {\n\tsplits := m.splits\n\t// NewMap ensures that len(splits) > 0\n\tresult := splits[0].reduce(reduce)\n\tfor i := 1; i < len(splits); i++ {\n\t\tresult = join(result, splits[i].reduce(reduce))\n\t}\n\treturn result\n}",
"func (doLog Log) Clear() (err error) {\n\tb := log.Clear()\n\treturn b.Do(doLog.ctxWithExecutor)\n}",
"func (l *ListHT) mayTriggerReduce() error {\n\tif l.config.Tick != Interval {\n\t\treturn nil\n\t}\n\tl.count++\n\tif l.count >= l.config.Period {\n\t\tl.count = 0\n\t\treturn l.ReduceLog(l.first, l.last)\n\t}\n\treturn nil\n}",
"func (s *StandardLogger) LogRegularize(workerID int, term anyvec.Numeric) {\n\tif s.Regularize {\n\t\tlog.Printf(\"regularize: worker=%d term=%v\", workerID, term)\n\t}\n}",
"func (packer *PixyPacker) Reduce(results jobqueue.Results) {\n\tutilsFile := path.Join(packer.outputDirectory, \"utils.go\")\n\terr := packer.compiler.SaveUtilities(utilsFile)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}",
"func (m *Master) DoneReduce(args *DoneReduceArgs, reply *DoneReduceReply) error {\n\tremainReduceMutex.Lock()\n\tm.remainReduceCount--\n\tm.reduces[args.Index].done = true\n\tlog.Print(\"[MASTER] after reduce, m.remainReduceCount: \" + strconv.Itoa(m.remainReduceCount))\n\tremainReduceMutex.Unlock()\n\treturn nil\n}",
"func ReduceErr(in interface{}, memo interface{}, fn reduceFnErr) (interface{}, error) {\n\tvar err error\n\tresult := memo\n\tval := reflect.ValueOf(in)\n\n\tfor i := 0; i < val.Len(); i++ {\n\t\tresult, err = fn(result, val.Index(i).Interface())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn result, nil\n}",
"func Reduce(key string, values []string) string {\n\t// some reduce tasks sleep for a long time; potentially seeing if\n\t// a worker will accidentally exit early\n\tif strings.Contains(key, \"sherlock\") || strings.Contains(key, \"tom\") {\n\t\ttime.Sleep(time.Duration(3 * time.Second))\n\t}\n\t// return the number of occurrences of this file.\n\treturn strconv.Itoa(len(values))\n}",
"func Reduce[ValT, AccumT any](\n\tslc []ValT,\n\tstart AccumT,\n\tfn func(AccumT, ValT) AccumT,\n) AccumT {\n\tret := start\n\tfor _, t := range slc {\n\t\tret = fn(ret, t)\n\t}\n\treturn ret\n}",
"func (r *RaftNode) mergeLogEntries(req *AppendEntriesRequest) (success bool) {\n\n\tr.leaderMutex.Lock()\n\tdefer r.leaderMutex.Unlock()\n\n\tentries := req.GetEntries()\n\n\t// if prevLogIndex is out of range, cannot merge\n\tif req.GetPrevLogIndex() < 0 || req.GetPrevLogIndex() > r.getLastLogIndex() {\n\t\tr.Out(\"MERGING: Couldn't find prev\")\n\t\treturn false\n\t}\n\n\t// if log doesn't contain entry at prevLogIndex with term PrevLogTerm, cannot merge\n\tfollowerPrevLog := r.getLogEntry(req.GetPrevLogIndex())\n\tif followerPrevLog.TermId != req.GetPrevLogTerm() {\n\t\tr.Out(\"MERGING: Couldn't find prevEntry with term = %d; index = %d\", req.GetPrevLogTerm(), req.GetPrevLogIndex())\n\t\treturn false\n\t}\n\n\t// if there are entries present, merge them\n\tif entries != nil && len(entries) != 0 {\n\t\tfor i := range entries {\n\t\t\t// index of where we would insert the new item\n\t\t\tinsertAt := uint64(i) + req.GetPrevLogIndex() + 1\n\t\t\tif entries[i].GetIndex() != insertAt {\n\t\t\t\tr.Error(\"Request doesn't have correct index!! State corrupted.\")\n\t\t\t}\n\t\t\tr.Out(\"Merging logs: adding %v\", entries[i])\n\t\t\tif insertAt <= r.getLastLogIndex() {\n\t\t\t\tr.truncateLog(insertAt)\n\t\t\t\tr.appendLogEntry(*entries[i])\n\t\t\t} else {\n\t\t\t\t// if we go past the end of the log (or remove entries above), keep appending\n\t\t\t\tr.appendLogEntry(*entries[i])\n\t\t\t}\n\t\t}\n\t}\n\n\t// apply all logEntries up until leader's commitIndex to statemachine\n\tif req.GetLeaderCommit() > r.commitIndex {\n\t\tnewCommitIndex := min(req.GetLeaderCommit(), r.getLastLogIndex())\n\t\t// start at +1 since commitIndex has already been committed\n\t\tfor i := r.commitIndex + 1; i <= newCommitIndex; i++ {\n\t\t\tentry := r.getLogEntry(i)\n\t\t\tr.Out(\"COMMITTING index=%v;term=%v\", entry.GetIndex(), entry.GetTermId())\n\t\t\tif entry.Type == CommandType_STATE_MACHINE_COMMAND {\n\t\t\t\tresponse, err := r.stateMachine.ApplyCommand(entry.Command, entry.Data)\n\t\t\t\tif err != nil {\n\t\t\t\t\tr.Error(\"State machine error: %v (response: %s)\", err, response)\n\t\t\t\t}\n\t\t\t}\n\t\t\tr.lastApplied = i\n\t\t}\n\t\tr.commitIndex = newCommitIndex\n\t}\n\n\tr.Verbose(\"Merge successful\")\n\treturn true\n}",
"func (m *Map) ReduceString(\n\treduce func(map[interface{}]interface{}) string,\n\tjoin func(x, y string) string,\n) string {\n\tsplits := m.splits\n\t// NewMap ensures that len(splits) > 0\n\tresult := splits[0].reduceString(reduce)\n\tfor i := 1; i < len(splits); i++ {\n\t\tresult = join(result, splits[i].reduceString(reduce))\n\t}\n\treturn result\n}",
"func (_Votes *VotesTransactor) ClearLog(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Votes.contract.Transact(opts, \"clearLog\")\n}",
"func (s *PersistentState) UpdateAndAppendLogFragile(elements []*rpc.LogEntry) {\n\tlg.Log.Debugf(\"old log: %s\", s.Log)\n\n\tfirstNewElementIndex := 0\n\n\t// remove all inconsistent elements\n\tfor i, element := range elements {\n\t\tif len(s.Log) > int(element.Index) {\n\t\t\tif element.Term != s.Log[element.Index].Term {\n\t\t\t\tfirstNewElementIndex = i\n\t\t\t\ts.Log = s.Log[:element.Index]\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tfirstNewElementIndex = i + 1\n\t\t\t}\n\t\t}\n\t}\n\n\t// add all new elements\n\tif firstNewElementIndex < len(elements) {\n\t\tlg.Log.Debugf(\"Adding following entries to log: %v\", elements[firstNewElementIndex:])\n\t\ts.Log = append(s.Log, elements[firstNewElementIndex:]...)\n\t}\n\n\tlg.Log.Debugf(\"new log: %s\", s.Log)\n}",
"func (s *set) Reduce(i *Term, f func(*Term, *Term) (*Term, error)) (*Term, error) {\n\terr := s.Iter(func(x *Term) error {\n\t\tvar err error\n\t\ti, err = f(i, x)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\treturn i, err\n}",
"func Reduce(input <-chan interface{}, f ReduceFn, initial ...interface{}) (interface{}, error) {\n\tvar init interface{}\n\tif len(initial) > 0 {\n\t\tinit = initial[0]\n\t} else {\n\t\tfor x := range input {\n\t\t\tinit = x\n\t\t\tbreak\n\t\t}\n\t}\n\n\tacc := init\n\n\tfor x := range input {\n\t\tv, err := f(acc, x)\n\t\tif err != nil {\n\t\t\treturn acc, err\n\t\t}\n\t\tacc = v\n\t}\n\n\treturn acc, nil\n}",
"func (l *listener) HandleLog(lb log.Broadcast) {\n\twas, err := lb.WasAlreadyConsumed()\n\tif err != nil {\n\t\tlogger.Errorw(\"DirectRequestListener: could not determine if log was already consumed\", \"error\", err)\n\t\treturn\n\t} else if was {\n\t\treturn\n\t}\n\n\tlogJobSpecID := lb.RawLog().Topics[1]\n\tif logJobSpecID == (common.Hash{}) || logJobSpecID != l.onChainJobSpecID {\n\t\tlogger.Debugw(\"Skipping Run for Log with wrong Job ID\", \"logJobSpecID\", logJobSpecID, \"actualJobID\", l.onChainJobSpecID)\n\t\treturn\n\t}\n\n\tlog := lb.DecodedLog()\n\tif log == nil || reflect.ValueOf(log).IsNil() {\n\t\tlogger.Error(\"HandleLog: ignoring nil value\")\n\t\treturn\n\t}\n\n\tswitch log := log.(type) {\n\tcase *oracle_wrapper.OracleOracleRequest:\n\t\tl.handleOracleRequest(log)\n\t\terr = lb.MarkConsumed()\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"Error marking log as consumed: %v\", err)\n\t\t}\n\tcase *oracle_wrapper.OracleCancelOracleRequest:\n\t\tl.handleCancelOracleRequest(log)\n\t\terr = lb.MarkConsumed()\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"Error marking log as consumed: %v\", err)\n\t\t}\n\n\tdefault:\n\t\tlogger.Warnf(\"unexpected log type %T\", log)\n\t}\n}",
"func CacheReduceOutput(res string, destFileName string) error {\n\tConfig.CreateDirIfNotExist(Config.ResultDir)\n\n\tfileDir := Config.ResultDir + \"/\" + destFileName\n\n\tfile, err := os.OpenFile(fileDir, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tfmt.Println(\"os.OpenFile() error\")\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\t//fmt.Println(\"Write to:\" + fileDir)\n\t_, err = file.WriteString(res)\n\n\t// os.Remove(fileDir)\n\n\treturn nil\n}",
"func (r *Raft) ApplyLog(log *pb.Log, timeout time.Duration) ApplyFuture {\n\tvar timer <-chan time.Time\n\tif timeout > 0 {\n\t\ttimer = time.After(timeout)\n\t}\n\n\t// Create a log future, no index or term yet\n\tf := &logFuture{\n\t\tlog: pb.Log{\n\t\t\tType: pb.LogType_COMMAND,\n\t\t\tData: log.Data,\n\t\t\tExtensions: log.Extensions,\n\t\t},\n\t}\n\tf.init()\n\n\tselect {\n\tcase <-timer:\n\t\treturn errorFuture{ErrEnqueueTimeout}\n\tcase <-r.shutdownCh:\n\t\treturn errorFuture{ErrRaftShutdown}\n\tcase r.applyCh <- f:\n\t\treturn f\n\t}\n}",
"func (d *GF255e) DecodeReduce(src []byte) *GF255e {\n\tgf_decodeReduce((*[4]uint64)(d), src, mq255e)\n\treturn d\n}",
"func Reduce(in interface{}, memo interface{}, fn reducef) interface{} {\n\tval := reflect.ValueOf(in)\n\n\tfor i := 0; i < val.Len(); i++ {\n\t\tmemo = fn(memo,val.Index(i).Interface())\n\t}\n\n\treturn memo\n}",
"func (q *QueuedOutput) Log(log *Log) {\n\tselect {\n\tcase <-q.ctx.Done():\n\t\treturn\n\tdefault:\n\t}\n\tif q.blocking != 0 {\n\t\tq.queue <- log\n\t\treturn\n\t}\n\tselect {\n\tcase q.queue <- log:\n\tdefault:\n\t\tif q.onQueueFull != nil && *q.onQueueFull != nil {\n\t\t\t(*q.onQueueFull)()\n\t\t}\n\t}\n}",
"func (f Frac) Reduce() Frac {\n\tif f.n == 0 {\n\t\treturn Frac{n: 0, d: 1}\n\t}\n\n\td := gcd(f.n, f.d)\n\n\tf1 := Frac{n: f.n / d, d: f.d / d}\n\n\tf1.normalizeSignage()\n\n\treturn f1\n}",
"func (self *State)Log(a any)any{\n self.IncOperations(self.coeff[\"log\"]+self.off[\"log\"])\n return wrap1(a,math.Log)\n}",
"func Reduce(series interface{}, reduceFunc interface{}, initial interface{}) (interface{}, error) {\n\treturn nil, ErrNotImplemented\n}",
"func (s VectOp) Reduce(f fs.ReduceOperator, identity float64) float64 {\n\tresult := identity\n\tfor _, val := range s {\n\t\tresult = f(val, result)\n\t}\n\treturn result\n}",
"func (qm *QuotaManager) WatchLog(local *custom.Local, treeID int64) {\n\tqm.mu.Lock()\n\tqm.unsequenced[treeID] = 0\n\tqm.mu.Unlock()\n\n\t// Spawn a goroutine to update the unsequenced count every so often.\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(10 * time.Second)\n\n\t\t\tsth, _, err := local.MostRecentRoot(treeID)\n\t\t\tif err == storage.ErrTreeNeedsInit {\n\t\t\t\tcontinue\n\t\t\t} else if err != nil {\n\t\t\t\tlog.Printf(\"error getting the most recent STH: treeID=%v: %v\", treeID, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcount, err := local.Unsequenced(treeID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"error getting the unsequenced count: treeID=%v: %v\", treeID, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tqm.TreeSize.WithLabelValues(fmt.Sprint(treeID)).Set(float64(sth.TreeSize))\n\t\t\tqm.UnsequencedLeaves.WithLabelValues(fmt.Sprint(treeID)).Set(float64(count))\n\n\t\t\tqm.mu.Lock()\n\t\t\tqm.unsequenced[treeID] = int64(count)\n\t\t\tqm.mu.Unlock()\n\t\t}\n\t}()\n}",
"func Test_Reduce_Large_Difference(t *testing.T) {\n\tvar hours []int = []int{6, 1, 7, 10, 2, 6, 1, 7, 10, 2, 6, 1, 7, 10, 2, 6, 1, 7, 10, 2, 6, 1, 7, 10, 2, 6, 1, 7, 10, 2, 6, 1, 7, 10, 2, 6, 1, 7, 10, 2, 6, 1, 7, 10, 2, 6, 1, 7, 10, 2, 6, 1, 7, 10, 2, 6, 1, 7, 10, 2, 6, 1, 7, 10, 2, 6, 1, 7, 10, 2, 6, 1, 7, 10, 2, 6, 1, 7, 10, 2, 6, 1, 7, 10, 2, 6, 1, 7, 10, 2}\n\tvar difference int = len(hours) - 31\n\n\tvar original_sum = core.Sum(hours)\n\n\tresult := reduce(hours, difference)\n\n\tvar result_sum = core.Sum(result)\n\n\tif original_sum != result_sum {\n\t\tt.Errorf(\"Total hours sum does not match.\")\n\t}\n}",
"func (e *Elog) Apply(t Texter) {\n\t// The log is applied back-to-front - this avoids disturbing the text ahead of the\n\t// current application point.\n\tfor i := len((*e).Log) - 1; i >= 1; i-- {\n\t\teo := (*e).Log[i]\n\t\tswitch eo.T {\n\t\tcase Replace:\n\t\t\tif tracelog {\n\t\t\t\tfmt.Printf(\"elog replace %d %d (%d %d)\\n\",\n\t\t\t\t\teo.q0, eo.q0+eo.nd, t.Q0(), t.Q1())\n\t\t\t}\n\t\t\ttq0, tq1 := t.Constrain(eo.q0, eo.q0+eo.nd)\n\t\t\tt.Delete(tq0, tq1, true)\n\t\t\tt.Insert(tq0, eo.r, true)\n\t\t\t// Mark selection\n\t\t\tif t.Q0() == eo.q0 && t.Q1() == eo.q0 {\n\t\t\t\tt.SetQ1(t.Q1() + len(eo.r))\n\t\t\t}\n\t\tcase Insert:\n\t\t\tif tracelog {\n\t\t\t\tfmt.Printf(\"elog insert %d %d (%d %d)\\n\",\n\t\t\t\t\teo.q0, eo.q0+len(eo.r), t.Q0(), t.Q1())\n\t\t\t}\n\t\t\ttq0, _ := t.Constrain(eo.q0, eo.q0)\n\t\t\tt.Insert(tq0, eo.r, true)\n\t\t\tif t.Q0() == eo.q0 && t.Q1() == eo.q0 {\n\t\t\t\tt.SetQ1(t.Q1() + len(eo.r))\n\t\t\t}\n\t\tcase Delete:\n\t\t\tif tracelog {\n\t\t\t\tfmt.Printf(\"elog delete %d %d (%d %d)\\n\",\n\t\t\t\t\teo.q0, eo.q0+len(eo.r), t.Q0(), t.Q1())\n\t\t\t}\n\t\t\ttq0, tq1 := t.Constrain(eo.q0, eo.q0+eo.nd)\n\t\t\tt.Delete(tq0, tq1, true)\n\t\t}\n\t}\n\t(*e).Term()\n}",
"func (f *FakeMounter) ResetLog() {\n\tf.mutex.Lock()\n\tdefer f.mutex.Unlock()\n\n\tf.log = []FakeAction{}\n}",
"func (s *Store) Reduce(events []core.Event) error {\n\tcodecActions, err := s.eventcodec.Reduce(\n\t\tevents,\n\t\ts.datastore,\n\t\tbaseKey,\n\t\tdefaultIndexFunc(s),\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tactions := make([]Action, len(codecActions))\n\tfor i, ca := range codecActions {\n\t\tvar actionType ActionType\n\t\tswitch codecActions[i].Type {\n\t\tcase core.Create:\n\t\t\tactionType = ActionCreate\n\t\tcase core.Save:\n\t\t\tactionType = ActionSave\n\t\tcase core.Delete:\n\t\t\tactionType = ActionDelete\n\t\tdefault:\n\t\t\tpanic(\"eventcodec action not recognized\")\n\t\t}\n\t\tactions[i] = Action{Model: ca.Model, Type: actionType, ID: ca.EntityID}\n\t}\n\ts.notifyStateChanged(actions)\n\n\treturn nil\n}",
"func Reduce[T any, R any](collection []T, accumulator func(R, T, int) R, initial R) R {\n\tfor i, item := range collection {\n\t\tinitial = accumulator(initial, item, i)\n\t}\n\n\treturn initial\n}",
"func (c *watchAggregator) SetLog(l log.Logger) {\n\tc.log = l\n}",
"func (eval *evaluator) ReplicateLog(ctIn *Ciphertext, batchSize, n int, ctOut *Ciphertext) {\n\teval.InnerSumLog(ctIn, -batchSize, n, ctOut)\n}",
"func (r *Raft) processLog(l *Log) {\n\tswitch l.Type {\n\tcase LogCommand:\n\t\tr.fsm.Apply(l.Data)\n\n\tcase LogAddPeer:\n\t\tpeer := r.trans.DecodePeer(l.Data)\n\n\t\t// Avoid adding ourself as a peer\n\t\tr.peerLock.Lock()\n\t\tif peer.String() != r.localAddr.String() {\n\t\t\tr.peers = addUniquePeer(r.peers, peer)\n\t\t}\n\t\t_ = r.peerStore.SetPeers(append([]net.Addr{r.localAddr}, r.peers...))\n\t\tr.peerLock.Unlock()\n\n\tcase LogRemovePeer:\n\t\tpeer := r.trans.DecodePeer(l.Data)\n\n\t\t// Removing ourself acts like removing all other peers\n\t\tr.peerLock.Lock()\n\t\tif peer.String() == r.localAddr.String() {\n\t\t\tr.peers = nil\n\t\t\tif r.conf.ShutdownOnRemove {\n\t\t\t\tr.logD.Printf(\"Removed ourself, shutting down\")\n\t\t\t\tr.Shutdown()\n\t\t\t} else {\n\t\t\t\tr.setState(Follower)\n\t\t\t}\n\t\t} else {\n\t\t\tr.peers = excludePeer(r.peers, peer)\n\t\t}\n\t\t_ = r.peerStore.SetPeers(append([]net.Addr{r.localAddr}, r.peers...))\n\t\tr.peerLock.Unlock()\n\n\tcase LogNoop:\n\t\t// Ignore the no-op\n\tdefault:\n\t\tr.logE.Printf(\"Got unrecognized log type: %#v\", l)\n\t}\n}",
"func (dd *DirectoryDiffMapReducer) Reduce(diff *datatransfer.Diff) *datatransfer.Diff {\n\to := datatransfer.NewDiff()\n\to.Insertions = diff.Insertions\n\to.Deletions = diff.Deletions\n\to.Total = diff.Total\n\n\tfor _, frmr := range diff.Rows {\n\t\tn := dd.Dirs\n\n\t\tif len(frmr.Segments) < n {\n\t\t\tn = len(frmr.Segments)\n\t\t}\n\n\t\tpath := bytes.Join(frmr.Segments[0:n], dd.Split)\n\n\t\ttrgt := o.GetRowByPath(path)\n\t\tif trgt == nil {\n\t\t\ttrgt = datatransfer.NewDiffRow()\n\t\t\ttrgt.FullPath = path\n\t\t\ttrgt.Segments = frmr.Segments[0:n]\n\n\t\t\to.AddRow(trgt)\n\t\t}\n\n\t\ttrgt.InheritDeltas(*frmr)\n\t}\n\n\treturn o\n}",
"func (th *TlfHistory) Recompute(loggedInUser string) (\n\twritersWhoNeedMore map[string]bool) {\n\tth.lock.Lock()\n\tdefer th.lock.Unlock()\n\t_, writersWhoNeedMore = th.recomputeLocked(loggedInUser)\n\treturn writersWhoNeedMore\n}",
"func Reduce(in interface{}, memo interface{}, fn reduceFn) interface{} {\n\tresult := memo\n\tval := reflect.ValueOf(in)\n\n\tfor i := 0; i < val.Len(); i++ {\n\t\tresult = fn(result, val.Index(i).Interface())\n\t}\n\n\treturn result\n}",
"func Reduce[I, A any](input <-chan I, reduceFunc func(accum A, element I) A) A {\n\tvar accum A\n\tfor element := range input {\n\t\taccum = reduceFunc(accum, element)\n\t}\n\n\treturn accum\n}",
"func (fsm *executorFSM) Apply(l *raft.Log) interface{} {\n fsm.mtx.Lock()\n defer fsm.mtx.Unlock()\n fsm.logger.Debug(\"Apply new log entry\")\n for {\n if !fsm.isSnapshotInProgress() {\n // we need not to return error but make it slow, wait until not anymore in progress\n break\n }\n fsm.logger.Error(\"cannot execute Apply because a snapshot is in progress\")\n time.Sleep(1 * time.Second)\n }\n if fsm.isSnapshotInProgress() {\n // we need not to return error but make it slow, wait until not anymore in progress\n fsm.logger.Error(\"Cannot accept new requests when snap shotting is in progress.\")\n return fmt.Errorf(\"Cannot accept new requests when snap shotting is in progress.\")\n }\n conn, err := fsm.executor.newConnection()\n if err != nil {\n return err\n }\n defer conn.Close()\n client := pb.NewJinaSingleDataRequestRPCClient(conn)\n dataRequestProto := &pb.DataRequestProto{}\n err = proto.Unmarshal(l.Data, dataRequestProto)\n if err != nil {\n fsm.logger.Error(\"Error while unmarshalling log into DataRequestProto\", \"error\", err)\n return err\n }\n\n response, err := client.ProcessSingleData(context.Background(), dataRequestProto)\n if err != nil {\n fsm.logger.Error(\"Error when calling Executor\", \"error\", err)\n return err\n }\n fsm.logger.Debug(\"Return Apply Log Response\")\n return response\n}",
"func (e *Encoder) SetLog(writer io.Writer) {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\n\tif writer != nil {\n\t\te.logger = wrapWriterLog(writer)\n\t\treturn\n\t}\n\n\tif e.logger != nil {\n\t\te.logger = nil\n\t}\n}",
"func Reduce(data []float64, mean float64, exponent float64) float64 {\r\n\treturn Accumulate(data, 0, func(a float64, b float64) float64 {\r\n\t\treturn a + math.Pow(b-mean, exponent)\r\n\t})\r\n}",
"func CollectiveReduce(scope *Scope, input tf.Output, group_size int64, group_key int64, instance_key int64, merge_op string, final_op string, subdiv_offsets []int64, optional ...CollectiveReduceAttr) (data tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{\"group_size\": group_size, \"group_key\": group_key, \"instance_key\": instance_key, \"merge_op\": merge_op, \"final_op\": final_op, \"subdiv_offsets\": subdiv_offsets}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"CollectiveReduce\",\n\t\tInput: []tf.Input{\n\t\t\tinput,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}",
"func (mdl *Model) Reduce(callback func(std.Value) bool) std.Value {\n\treturn nil\n}",
"func (s scope) Reduce() Expression { return s }",
"func ReduceVocab() {\n\tfmt.Fprintln(os.Stderr, \"ReduceVocab\")\n\tvar b int = 0\n\tfor a := 0; a < vocab_size; a++ {\n\t\tif vocab[a].cn > min_reduce {\n\t\t\tvocab[b].cn = vocab[a].cn\n\t\t\tvocab[b].char = vocab[a].char\n\t\t\tb++\n\t\t} else {\n\t\t\tvocab[a].char = 0\n\t\t}\n\t}\n\tvocab_size = b\n\tvocab_hash = map[rune]int{}\n\tfor a := 0; a < vocab_size; a++ {\n\t\t// Hash will be re-computed, as it is not actual\n\t\tvocab_hash[vocab[a].char] = a\n\t}\n\t// fflush(stdout);\n\tmin_reduce++\n}",
"func (rf *ReduceFunc) Reduce(mx *Ctx) *State {\n\treturn rf.Func(mx)\n}",
"func (f *fsm) Apply(rlog *raft.Log) interface{} {\n\tif rlog.Type != raft.LogCommand {\n\t\treturn nil\n\t}\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\tcmd := &pb.CommandLog{}\n\tif err := proto.Unmarshal(rlog.Data, cmd); err != nil {\n\t\treturn nil\n\t}\n\n\tf.l.Debug(\"apply wal\", \"command\", cmd.Type.String())\n\tswitch cmd.Type {\n\tcase pb.CommandLog_COMMAND_TYPE_SCHEDULE_JOB:\n\t\tcmdLog := &pb.CommandScheduleJob{}\n\t\tif err := proto.Unmarshal(cmd.Payload, cmdLog); err != nil {\n\t\t\treturn nil\n\t\t}\n\t\t// update local state\n\t\tfor _, id := range cmdLog.RunIds {\n\t\t\tif _, ok := f.state.Allocation[cmdLog.PeerId]; !ok {\n\t\t\t\tf.state.Allocation[cmdLog.PeerId] = set.NewHashSet()\n\t\t\t}\n\n\t\t\tf.state.Allocation[cmdLog.PeerId].Add(StateJob{\n\t\t\t\tUUID: id,\n\t\t\t\tStatus: models.RunStateAccepted.String(),\n\t\t\t})\n\t\t}\n\t\tf.l.Debug(\"updated state\", \"alloc state\", f.state.Allocation[cmdLog.PeerId])\n\tcase pb.CommandLog_COMMAND_TYPE_UPDATE_JOB:\n\t\tcmdLog := &pb.CommandUpdateJob{}\n\t\tif err := proto.Unmarshal(cmd.Payload, cmdLog); err != nil {\n\t\t\treturn nil\n\t\t}\n\t\t// update local state\n\t\tfor _, patch := range cmdLog.Patches {\n\t\t\tfor _, rawJobState := range f.state.Allocation[cmdLog.PeerId].Values() {\n\t\t\t\tjobState := rawJobState.(StateJob)\n\t\t\t\tif jobState.UUID == patch.RunId {\n\t\t\t\t\tf.state.Allocation[cmdLog.PeerId].Remove(jobState)\n\t\t\t\t\tjobState.Status = patch.Status\n\n\t\t\t\t\t// if run at terminating states, deallocate else update\n\t\t\t\t\tif patch.Status != models.RunStateFailed.String() &&\n\t\t\t\t\t\tpatch.Status != models.RunStateSuccess.String() {\n\t\t\t\t\t\tf.state.Allocation[cmdLog.PeerId].Add(jobState)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tf.l.Debug(\"updated state\", \"alloc state\", f.state.Allocation[cmdLog.PeerId])\n\tdefault:\n\t\t// ignore\n\t}\n\treturn nil\n}",
"func (log *logging) realign(maxname int) {\n\tif log.maxname != 0 && log.maxname == maxname {\n\t\treturn\n\t}\n\tif maxname == 0 {\n\t\tfor id, cfg := range log.configs {\n\t\t\tif !cfg.isEnabled() && !log.forced {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif length := len(log.sources[id]); length > maxname {\n\t\t\t\tmaxname = length\n\t\t\t}\n\t\t}\n\t}\n\tlog.maxname = maxname\n\tlog.active.SetSourceAlignment(maxname)\n}",
"func (kv *ShardKV) applyFromLog(decidedSeq int) Err {\n\tcurrent := kv.highestDone + 1\n\tvar err Err = OK\n\n\tfor current <= decidedSeq {\n\t\top, ok := kv.log[current]\n\t\tif !ok {\n\t\t\t//_, iok := kv.log[current]\n\t\t\t//log.Panicf(\"MISSING ENTRY after catchUp gid: %v me: %v current: %v iok: %v!!!!!\\n\", kv.gid, kv.me, current, iok)\n\t\t}\n\t\tif ok {\n\t\t\tif op.RequestType != NoOp {\n\t\t\t\tif op.RequestType == Get || op.RequestType == Put {\n\t\t\t\t\t// Make sure this is the correct group\n\t\t\t\t\tif (kv.currentConfig.Num != op.ClientConfigNum) || (kv.currentConfig.Shards[op.Shard] != kv.gid) {\n\t\t\t\t\t\terr = ErrWrongGroup\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Check for duplicate client request\n\t\t\t\t\t\tduplicate := false\n\t\t\t\t\t\t//highestLogged, ok := shardData.HighestReqIdLogged[op.ClientUuid]\n\t\t\t\t\t\t//if !ok || (ok && op.ReqId > highestLogged) {\n\t\t\t\t\t\t//\tlog.Printf(\"NOT Dup!! gid: %v me: %v key: %v shard: %v cur: %v oprid: %v type: %v cu: %v\\n\",\n\t\t\t\t\t\t//\t\tkv.gid, kv.me, op.Key, op.Shard, current, op.ReqId, op.RequestType, op.ClientUuid)\n\t\t\t\t\t\t//\tshardData.HighestReqIdLogged[op.ClientUuid] = op.ReqId\n\t\t\t\t\t\t//} else {\n\t\t\t\t\t\t//\tlog.Printf(\"Dup!! gid: %v me: %v key: %v shard: %v cur: %v oprid: %v highlog: %v cu: %v\\n\",\n\t\t\t\t\t\t//\t\tkv.gid, kv.me, op.Key, op.Shard, current, op.ReqId, highestLogged, op.ClientUuid)\n\t\t\t\t\t\t//\tduplicate = true\n\t\t\t\t\t\t//\terr = ErrDuplicate\n\t\t\t\t\t\t//}\n\t\t\t\t\t\t_, ok := kv.shardData[op.Shard].StoredReplies[op.ClientUuid]\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\tkv.shardData[op.Shard].StoredReplies[op.ClientUuid] = make(map[uint64]CachedReply)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t_, ok = kv.shardData[op.Shard].StoredReplies[op.ClientUuid][op.ReqId]\n\t\t\t\t\t\tif ok {\n\t\t\t\t\t\t\t//log.Printf(\"Dup!! gid: %v me: %v key: %v shard: %v cur: %v oprid: %v cu: %v\\n\",\n\t\t\t\t\t\t\t//\tkv.gid, kv.me, op.Key, op.Shard, current, op.ReqId, op.ClientUuid)\n\t\t\t\t\t\t\tduplicate = true\n\t\t\t\t\t\t\terr = ErrDuplicate\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif op.RequestType == Get {\n\t\t\t\t\t\t\t// Cache reply\n\t\t\t\t\t\t\t//_, ok = shardData.CachedReplies[op.ClientUuid]\n\t\t\t\t\t\t\t//if !ok {\n\t\t\t\t\t\t\t//\tkv.shardData[op.Shard].CachedReplies[op.ClientUuid] = make(map[string]CachedReply)\n\t\t\t\t\t\t\t//}\n\n\t\t\t\t\t\t\t//cachedReply, ok := shardData.CachedReplies[op.ClientUuid][op.Key]\n\t\t\t\t\t\t\t_, ok := kv.shardData[op.Shard].StoredReplies[op.ClientUuid][op.ReqId]\n\t\t\t\t\t\t\tif !ok { //|| (ok && op.ReqId > cachedReply.ReqId) {\n\t\t\t\t\t\t\t\tnewReply := CachedReply{}\n\t\t\t\t\t\t\t\tnewReply.ReqId = op.ReqId\n\t\t\t\t\t\t\t\tif value, ok := kv.shardData[op.Shard].Data[op.Key]; ok {\n\t\t\t\t\t\t\t\t\tnewReply.Found = true\n\t\t\t\t\t\t\t\t\tnewReply.Value = value\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tnewReply.Found = false\n\t\t\t\t\t\t\t\t\terr = ErrNoKey\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t//kv.shardData[op.Shard].CachedReplies[op.ClientUuid][op.Key] = newReply\n\t\t\t\t\t\t\t\tkv.shardData[op.Shard].StoredReplies[op.ClientUuid][op.ReqId] = newReply\n\t\t\t\t\t\t\t\terr = OK\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if op.RequestType == Put && !duplicate {\n\t\t\t\t\t\t\t//log.Printf(\"PUT executed gid: %v me: %v current: %v shard: %v key: %v val: %v view: %v reqid: %v\\n\",\n\t\t\t\t\t\t\t//\tkv.gid, kv.me, current, op.Shard, op.Key, op.Value, kv.currentConfig.Num, op.ReqId)\n\t\t\t\t\t\t\tnewReply := CachedReply{}\n\t\t\t\t\t\t\tnewReply.ReqId = op.ReqId\n\t\t\t\t\t\t\tkv.shardData[op.Shard].StoredReplies[op.ClientUuid][op.ReqId] = newReply\n\n\t\t\t\t\t\t\tkv.shardData[op.Shard].Data[op.Key] = op.Value\n\t\t\t\t\t\t\terr = OK\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif op.RequestType == Reconfig {\n\t\t\t\t\t\t//log.Printf(\"gid: %v me: %v RECONF opconfn: %v curr: %v changing: %v\\n\",\n\t\t\t\t\t\t//\tkv.gid, kv.me, op.ConfigNum, kv.currentConfig.Num, kv.changing)\n\t\t\t\t\t\tif op.ConfigNum == (kv.currentConfig.Num + 1) && !kv.changing {\n\t\t\t\t\t\t\tkv.changing = true\n\t\t\t\t\t\t\tnextConfig := kv.sm.Query(op.ConfigNum)\n\n\t\t\t\t\t\t\t// Can't serve unreceived shards yet\n\t\t\t\t\t\t\tdone := true\n\t\t\t\t\t\t\tif nextConfig.Num > 1 {\n\t\t\t\t\t\t\t\tfor i := 0; i < shardmaster.NShards; i++ {\n\t\t\t\t\t\t\t\t\tif nextConfig.Shards[i] == kv.gid && kv.currentConfig.Shards[i] != kv.gid {\n\t\t\t\t\t\t\t\t\t\tdone = false\n\t\t\t\t\t\t\t\t\t\tnextConfig.Shards[i] = -1\n\t\t\t\t\t\t\t\t\t} else if nextConfig.Shards[i] != kv.gid && kv.currentConfig.Shards[i] == kv.gid {\n\t\t\t\t\t\t\t\t\t\tcopiedShardData := copyShardData(*kv.shardData[i])\n\t\t\t\t\t\t\t\t\t\tnewOwners := make([]string, len(nextConfig.Groups[nextConfig.Shards[i]]))\n\t\t\t\t\t\t\t\t\t\tcopy(newOwners, nextConfig.Groups[nextConfig.Shards[i]])\n\t\t\t\t\t\t\t\t\t\tgo func(shard int, nextNum int, newO []string, copiedShardData ShardData) {\n\t\t\t\t\t\t\t\t\t\t\tkv.pushShard(shard, nextNum, newO, copiedShardData)\n\t\t\t\t\t\t\t\t\t\t}(i, nextConfig.Num, newOwners, copiedShardData)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif done {\n\t\t\t\t\t\t\t\tkv.changing = false\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tkv.currentConfig = nextConfig\n\t\t\t\t\t\t\t//log.Printf(\"gid: %v me: %v NEW CONFIG: %v changing: %v\\n\", kv.gid, kv.me, kv.currentConfig.Num, kv.changing)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if op.RequestType == ReceivedShard {\n\t\t\t\t\t\t//log.Printf(\"processing receivedshard gid: %v me: %v shard: %v op.conf: %v currnum: %v changin: %v shards: %v data: %v\\n\",\n\t\t\t\t\t\t//\tkv.gid, kv.me, op.Shard, op.ConfigNum, kv.currentConfig.Num, kv.changing, kv.currentConfig.Shards, op.ShardData.Data)\n\n\t\t\t\t\t\tif op.ConfigNum < kv.currentConfig.Num {\n\t\t\t\t\t\t\terr = ErrStopSending\n\t\t\t\t\t\t} else if op.ConfigNum > kv.currentConfig.Num {\n\t\t\t\t\t\t\terr = ErrFutureConfig\n\t\t\t\t\t\t} else if !kv.changing { // Must have same config num as current\n\t\t\t\t\t\t\terr = ErrStopSending\n\t\t\t\t\t\t} else if kv.currentConfig.Shards[op.Shard] == -1 {\n\t\t\t\t\t\t\t//log.Printf(\"using receivedshard gid: %v me: %v shard: %v op.conf: %v currnum: %v changin: %v shards: %v data: %v\\n\",\n\t\t\t\t\t\t\t//\tkv.gid, kv.me, op.Shard, op.ConfigNum, kv.currentConfig.Num, kv.changing, kv.currentConfig.Shards, op.ShardData.Data)\n\t\t\t\t\t\t\tcopiedData := copyShardData(op.ShardData)\n\t\t\t\t\t\t\tnewShardData := &ShardData{}\n\t\t\t\t\t\t\tnewShardData.Data = copiedData.Data\n\t\t\t\t\t\t\tnewShardData.CachedReplies = copiedData.CachedReplies\n\t\t\t\t\t\t\tnewShardData.StoredReplies = copiedData.StoredReplies\n\t\t\t\t\t\t\tnewShardData.HighestReqIdLogged = copiedData.HighestReqIdLogged\n\t\t\t\t\t\t\tkv.shardData[op.Shard] = newShardData\n\n\t\t\t\t\t\t\t// Begin serving\n\t\t\t\t\t\t\tkv.currentConfig.Shards[op.Shard] = kv.gid\n\n\t\t\t\t\t\t\tdone := true\n\t\t\t\t\t\t\tfor i := 0; i < shardmaster.NShards; i++ {\n\t\t\t\t\t\t\t\tif kv.currentConfig.Shards[i] == -1 {\n\t\t\t\t\t\t\t\t\tdone = false\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif done {\n\t\t\t\t\t\t\t\tkv.changing = false\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tdelete(kv.log, current)\n\t\t}\n\t\tcurrent++\n\t}\n\n\tkv.px.Done(decidedSeq)\n\tkv.highestDone = decidedSeq\n\treturn err\n}",
"func (l *OCLogger) Fire(e *logger.Entry) error {\n\t// Store all log messages to return back in the logging API\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\n\t// Append to log entries\n\tif len(l.Entries) > maxLogEntries {\n\t\tl.Entries = l.Entries[1:]\n\t}\n\tl.Entries = append(l.Entries, *e)\n\n\tif e.Level <= logger.WarnLevel {\n\t\tif len(l.Warnings) > maxLogEntries {\n\t\t\tl.Warnings = l.Warnings[1:]\n\t\t}\n\t\tl.Warnings = append(l.Warnings, *e)\n\t}\n\n\treturn nil\n}",
"func (m *Map) ParallelReduce(\n\treduce func(map[interface{}]interface{}) interface{},\n\tjoin func(x, y interface{}) interface{},\n) interface{} {\n\tvar recur func(splits []Split) interface{}\n\trecur = func(splits []Split) interface{} {\n\t\tif len(splits) < 2 {\n\t\t\t// NewMap and case 2 below ensure that len(splits) > 0\n\t\t\treturn splits[0].reduce(reduce)\n\t\t}\n\t\tvar left, right interface{}\n\t\tvar p interface{}\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(1)\n\t\tswitch len(splits) {\n\t\tcase 2:\n\t\t\tgo func() {\n\t\t\t\tdefer func() {\n\t\t\t\t\tp = internal.WrapPanic(recover())\n\t\t\t\t\twg.Done()\n\t\t\t\t}()\n\t\t\t\tright = splits[1].reduce(reduce)\n\t\t\t}()\n\t\t\tleft = splits[0].reduce(reduce)\n\t\tdefault:\n\t\t\thalf := len(splits) / 2\n\t\t\tgo func() {\n\t\t\t\tdefer func() {\n\t\t\t\t\tp = internal.WrapPanic(recover())\n\t\t\t\t\twg.Done()\n\t\t\t\t}()\n\t\t\t\tright = recur(splits[half:])\n\t\t\t}()\n\t\t\tleft = recur(splits[:half])\n\t\t}\n\t\twg.Wait()\n\t\tif p != nil {\n\t\t\tpanic(p)\n\t\t}\n\t\treturn join(left, right)\n\t}\n\treturn recur(m.splits)\n}",
"func Reduce(reducef func(string, []string) string, reduceTask Task, NMap int) {\n\tkva := make([]KeyValue, 0)\n\tfor i := 0; i < NMap; i++ {\n\t\toname := fmt.Sprintf(\"mr-%v-%v.json\", i, reduceTask.Index)\n\t\tf, err := os.Open(oname)\n\t\tdefer f.Close()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"cannot open %v\", oname)\n\t\t}\n\t\tdec := json.NewDecoder(f)\n\t\tfor {\n\t\t\tvar kv KeyValue\n\t\t\tif err := dec.Decode(&kv); err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tkva = append(kva, kv)\n\n\t\t}\n\t}\n\tsort.Sort(ByKey(kva))\n\toname := fmt.Sprintf(\"mr-out-%v\", reduceTask.Index)\n\tofile, _ := os.Create(oname)\n\n\ti := 0\n\tfor i < len(kva) {\n\t\tj := i + 1\n\t\tfor j < len(kva) && kva[j].Key == kva[i].Key {\n\t\t\tj++\n\t\t}\n\t\tvalues := []string{}\n\t\tfor k := i; k < j; k++ {\n\t\t\tvalues = append(values, kva[k].Value)\n\t\t}\n\t\toutput := reducef(kva[i].Key, values)\n\n\t\t// this is the correct format for each line of Reduce output.\n\t\tfmt.Fprintf(ofile, \"%v %v\\n\", kva[i].Key, output)\n\n\t\ti = j\n\t}\n\tofile.Close()\n}",
"func ProcessLogConfigChange(cm *ConfigManager) {\n\t//populate the ComponentLogController using NewComponentLogController\n\n\tcc, err := NewComponentLogController(cm)\n\tif err != nil {\n\t\tlog.Error(\"error\", err)\n\t}\n\n\tccGlobal, err := InitComponentConfig(\"global\", ConfigTypeLogLevel, cm)\n\tif err != nil {\n\t\tlog.Errorw(\"fail-to-create-component-config\", log.Fields{\"error\": err})\n\t}\n\tcc.globalConfig = ccGlobal\n\n\tccComponentName, err := InitComponentConfig(cc.ComponentName, ConfigTypeLogLevel, cm)\n\tif err != nil {\n\t\tlog.Errorw(\"fail-to-create-component-config\", log.Fields{\"error\": err})\n\t}\n\tcc.componentNameConfig = ccComponentName\n\n\t//call ProcessConfigChange and check for any changes to config\n\tcc.processLogConfig()\n}",
"func (in *EventLogger) Apply(err error) {\n\tif err != nil {\n\t\tin.Status.Error = err.Error()\n\t} else {\n\t\tin.Status.Error = \"\"\n\t}\n\tin.Status.LastProcessed = metav1.Now()\n\tin.Status.OperatorVersion = version.Version\n}",
"func (m *Mare) Log(trace bool) *Mare {\n\tm.trace = trace\n\treturn m\n}",
"func (d *peerMsgHandler) handleCompactLogMsg(req *raft_cmdpb.RaftCmdRequest) *raft_cmdpb.RaftCmdResponse {\n\t// handle logGCCompact\n\t// construct response\n\tresponse := new(raft_cmdpb.CompactLogResponse)\n\tadminResponse := &raft_cmdpb.AdminResponse{\n\t\tCmdType: raft_cmdpb.AdminCmdType_CompactLog,\n\t\tCompactLog: response,\n\t}\n\tcmdResponse := raftAdminCmdResponse(adminResponse, d.Term(), nil)\n\t// check whether need to be compacted\n\tcompactIdx := req.AdminRequest.CompactLog.CompactIndex\n\tif d.peerStorage.applyState.TruncatedState.Index >= compactIdx {\n\t\tlog.Debugf(\"the log is already compacted\")\n\t\treturn cmdResponse\n\t}\n\tlog.Debugf(\"%s update compacted before, [%s]\", d.Tag, d.peerStorage.applyState.TruncatedState)\n\t// update state\n\tfirstIdx := d.peerStorage.updateMetaByLogCompact(req)\n\t// update memory log\n\td.RaftGroup.CompactMemoryLogEntries(req.AdminRequest.CompactLog.CompactIndex, req.AdminRequest.CompactLog.CompactTerm)\n\t// assign a asynchronously task\n\td.ctx.raftLogGCTaskSender <- &runner.RaftLogGCTask{\n\t\tRaftEngine: d.peerStorage.Engines.Raft,\n\t\tRegionID: d.regionId,\n\t\tStartIdx: firstIdx,\n\t\tEndIdx: compactIdx + 1,\n\t}\n\tlog.Debugf(\"%s update compacted, [%s]\", d.Tag, d.peerStorage.applyState.TruncatedState)\n\t// TODO seems this variable is useless\n\td.peer.LastCompactedIdx = compactIdx\n\t_, _ = d.peerStorage.Snapshot()\n\t// TODO there is no need to call snapshot now after log compact.\n\t// TODO when we figure out how to cache the snapshot, then we can think about this\n\t//snapshot, err := d.peerStorage.Snapshot()\n\t//if err == nil {\n\t//\t// update the LastSnapshot\n\t//\t// if the generated snapshot is earlier than the compact, regenerating\n\t//\tif compactIdx > snapshot.Metadata.Index {\n\t//\t\tlog.Debugf(\"%s call Snapshot.\", d.Tag)\n\t//\t\t_, _ = d.peerStorage.Snapshot()\n\t//\t}else{\n\t//\t\t// LastSnapshot only be updated when new snapshot index is greater than previous one\n\t//\t\td.RaftGroup.UpdateLastSnapshot(&snapshot)\n\t//\t}\n\t//} else {\n\t//\tlog.Errorf(\" %s snapshot is still generating when executing compactLog command.\", d.Tag)\n\t//}\n\treturn cmdResponse\n}",
"func (r *Raft) AppendToLog_Follower(request AppendEntriesReq) {\n\tterm := request.term\n\tcmd := request.entries\n\tindex := request.prevLogIndex + 1\n\tlogVal := LogVal{term, cmd, 0} //make object for log's value field\n\n\tif len(r.myLog) == index {\n\t\tr.myLog = append(r.myLog, logVal) //when trying to add a new entry\n\t} else {\n\t\tr.myLog[index] = logVal //overwriting in case of log repair\n\t\t//fmt.Println(\"Overwiriting!!\")\n\t}\n\t//fmt.Println(r.myId(), \"Append to log\", string(cmd))\n\t//modify metadata after appending\n\t//r.myMetaData.lastLogIndex = r.myMetaData.lastLogIndex + 1\n\t//r.myMetaData.prevLogIndex = r.myMetaData.lastLogIndex\n\t//\tif len(r.myLog) == 1 {\n\t//\t\tr.myMetaData.prevLogTerm = r.myMetaData.prevLogTerm + 1\n\t//\t} else if len(r.myLog) > 1 {\n\t//\t\tr.myMetaData.prevLogTerm = r.myLog[r.myMetaData.prevLogIndex].Term\n\t//\t}\n\n\t//Changed on 4th april, above is wrong in case of overwriting of log\n\tr.myMetaData.lastLogIndex = index\n\tr.myMetaData.prevLogIndex = index - 1\n\tif index == 0 {\n\t\tr.myMetaData.prevLogTerm = r.myMetaData.prevLogTerm + 1 //or simple -1\n\t} else if index >= 1 {\n\t\tr.myMetaData.prevLogTerm = r.myLog[index-1].Term\n\t}\n\n\t//Update commit index\n\tleaderCI := float64(request.leaderCommitIndex)\n\tmyLI := float64(r.myMetaData.lastLogIndex)\n\tif request.leaderCommitIndex > r.myMetaData.commitIndex {\n\t\tif myLI == -1 { //REDUNDANT since Append to log will make sure it is never -1,also must not copy higher CI if self LI is -1\n\t\t\tr.myMetaData.commitIndex = int(leaderCI)\n\t\t} else {\n\t\t\tr.myMetaData.commitIndex = int(math.Min(leaderCI, myLI))\n\t\t}\n\t}\n\t//fmt.Println(r.myId(), \"My CI is:\", r.myMetaData.commitIndex)\n\tr.WriteLogToDisk()\n}",
"func (_Votes *VotesTransactorSession) ClearLog() (*types.Transaction, error) {\n\treturn _Votes.Contract.ClearLog(&_Votes.TransactOpts)\n}",
"func (e *Eval) LogSummary(log *log.Logger) {\n\tvar n int\n\ttype aggregate struct {\n\t\tN, Ncache int\n\t\tRuntime stats\n\t\tCPU, Memory, Disk, Temp stats\n\t\tRequested reflow.Resources\n\t}\n\tstats := map[string]aggregate{}\n\n\tfor v := e.root.Visitor(); v.Walk(); v.Visit() {\n\t\tif v.Parent != nil {\n\t\t\tv.Push(v.Parent)\n\t\t}\n\t\t// Skip nodes that were skipped due to caching.\n\t\tif v.State < Done {\n\t\t\tcontinue\n\t\t}\n\t\tswitch v.Op {\n\t\tcase Exec, Intern, Extern:\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\n\t\tident := v.Ident\n\t\tif ident == \"\" {\n\t\t\tident = \"?\"\n\t\t}\n\t\ta := stats[ident]\n\t\ta.N++\n\t\tif v.Cached {\n\t\t\ta.Ncache++\n\t\t}\n\t\tif len(v.RunInfo.Profile) == 0 {\n\t\t\tn++\n\t\t\tstats[ident] = a\n\t\t\tcontinue\n\t\t}\n\t\tif v.Op == Exec {\n\t\t\ta.CPU.Add(v.RunInfo.Profile[\"cpu\"].Mean)\n\t\t\ta.Memory.Add(v.RunInfo.Profile[\"mem\"].Max)\n\t\t\ta.Disk.Add(v.RunInfo.Profile[\"disk\"].Max)\n\t\t\ta.Temp.Add(v.RunInfo.Profile[\"tmp\"].Max)\n\t\t\ta.Requested = v.RunInfo.Resources\n\t\t}\n\t\tif d := v.RunInfo.Runtime.Minutes(); d > 0 {\n\t\t\ta.Runtime.Add(d)\n\t\t}\n\t\tn++\n\t\tstats[ident] = a\n\t}\n\tif n == 0 {\n\t\treturn\n\t}\n\tvar b bytes.Buffer\n\tfmt.Fprintf(&b, \"total n=%d time=%s\\n\", n, round(e.totalTime))\n\tvar tw tabwriter.Writer\n\ttw.Init(newPrefixWriter(&b, \"\\t\"), 4, 4, 1, ' ', 0)\n\tfmt.Fprintln(&tw, \"ident\\tn\\tncache\\truntime(m)\\tcpu\\tmem(GiB)\\tdisk(GiB)\\ttmp(GiB)\\trequested\")\n\tidents := make([]string, 0, len(stats))\n\tfor ident := range stats {\n\t\tidents = append(idents, ident)\n\t}\n\tsort.Strings(idents)\n\tvar warningIdents []string\n\tconst byteScale = 1.0 / (1 << 30)\n\tfor _, ident := range idents {\n\t\tstats := stats[ident]\n\t\tfmt.Fprintf(&tw, \"%s\\t%d\\t%d\", ident, stats.N, stats.Ncache)\n\t\tif stats.CPU.N() > 0 {\n\t\t\tfmt.Fprintf(&tw, \"\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\",\n\t\t\t\tstats.Runtime.Summary(\"%.0f\"),\n\t\t\t\tstats.CPU.Summary(\"%.1f\"),\n\t\t\t\tstats.Memory.SummaryScaled(\"%.1f\", byteScale),\n\t\t\t\tstats.Disk.SummaryScaled(\"%.1f\", byteScale),\n\t\t\t\tstats.Temp.SummaryScaled(\"%.1f\", byteScale),\n\t\t\t\tstats.Requested,\n\t\t\t)\n\t\t\treqMem, minMem := stats.Requested[\"mem\"], float64(minExecMemory)\n\t\t\tif memRatio := stats.Memory.Mean() / reqMem; memRatio <= memSuggestThreshold && reqMem > minMem {\n\t\t\t\twarningIdents = append(warningIdents, ident)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Fprint(&tw, \"\\t\\t\\t\\t\\t\")\n\t\t}\n\t\tfmt.Fprint(&tw, \"\\n\")\n\t}\n\tif len(warningIdents) > 0 {\n\t\tfmt.Fprintf(&tw, \"warning: reduce memory requirements for over-allocating execs: %s\", strings.Join(warningIdents, \", \"))\n\t}\n\ttw.Flush()\n\tlog.Printf(b.String())\n}",
"func (s *LogStore) logTruncationTarget() int {\n\treturn s.maxLogLengthInBytes / 2\n}",
"func (alog *AppLogger) Reuse(lg Logger) {\n\talog.pool.Put(lg)\n}",
"func (s *Swarm64) SetLinearInertiaReduce(\n\tnumofparticles int,\n\tdims int,\n\tcognative float64,\n\tsocial float64,\n\tvmax float64,\n\tminpositionstart float64,\n\tmaxpositionstart float64,\n\talphamax float64,\n\tinertiamax float64) {\n\ts.setswarm(s.mode.InertiaReduction(), numofparticles, dims, cognative, social, vmax, minpositionstart, maxpositionstart, alphamax, inertiamax)\n\n}",
"func (c *Clac) Log() error {\n\treturn c.applyFloat(1, func(vals []value.Value) (value.Value, error) {\n\t\treturn binary(value.Int(10), \"log\", vals[0])\n\t})\n}",
"func reduceSum(key string, values []interface{}, r *reducer) {\n\tvar n float64\n\tfor _, v := range values {\n\t\tn += v.(float64)\n\t}\n\tr.emit(key, n)\n}",
"func (r *Raft) LogRepair(response AppendEntriesResponse) {\n\tid := response.followerId\n\t//fmt.Println(\"In log repair for \", id)\n\tfailedIndex := r.myMetaData.nextIndexMap[id]\n\tvar nextIndex int\n\t//fmt.Println(\"Failed index is:\", failedIndex)\n\tif failedIndex != 0 {\n\t\tnextIndex = failedIndex - 1 //decrementing follower's nextIndex\n\n\t} else { //if nextIndex is 0 means, follower doesn't have first entry (of leader's log),so decrementing should not be done, so retry the same entry again!\n\t\tnextIndex = failedIndex\n\t}\n\t//Added--3:38-23 march\n\tr.myMetaData.nextIndexMap[id] = nextIndex\n\t//fmt.Println(\"I am\", response.followerId, \"My Old and new NI are\", failedIndex, nextIndex)\n\treturn\n}",
"func (c *Client) ClearLog() error {\n\treturn c.boolCall(\"supervisor.clearLog\")\n}",
"func (m *Mare) Reduce(reduceFunc func(a, b interface{}) interface{}) map[interface{}]interface{} {\n\tresults := make(map[interface{}]interface{})\n\n\tfor item := range m.mapOutChan {\n\t\tmapItem, present := results[item.Key]\n\t\tif present {\n\t\t\tif m.trace {\n\t\t\t\tlog.Printf(\"Reducing %v with %v for key %v\", mapItem, item.Value, item.Key)\n\t\t\t}\n\t\t\tresults[item.Key] = reduceFunc(mapItem, item.Value)\n\t\t} else {\n\t\t\tif m.trace {\n\t\t\t\tlog.Printf(\"Saving %v for key %v\", item.Value, item.Key)\n\t\t\t}\n\t\t\tresults[item.Key] = item.Value\n\t\t}\n\t}\n\n\treturn results\n}",
"func TestReduceErrs(t *testing.T) {\n\t// List all of all test cases to validate various cases of reduce errors.\n\ttestCases := []struct {\n\t\terrs []error\n\t\tignoredErrs []error\n\t\terr error\n\t}{\n\t\t// Validate if have reduced properly.\n\t\t{[]error{\n\t\t\terrDiskNotFound,\n\t\t\terrDiskNotFound,\n\t\t\terrDiskFull,\n\t\t}, []error{}, errXLReadQuorum},\n\t\t// Validate if have no consensus.\n\t\t{[]error{\n\t\t\terrDiskFull,\n\t\t\terrDiskNotFound,\n\t\t\tnil, nil,\n\t\t}, []error{}, errXLReadQuorum},\n\t\t// Validate if have consensus and errors ignored.\n\t\t{[]error{\n\t\t\terrVolumeNotFound,\n\t\t\terrVolumeNotFound,\n\t\t\terrVolumeNotFound,\n\t\t\terrVolumeNotFound,\n\t\t\terrVolumeNotFound,\n\t\t\terrDiskNotFound,\n\t\t\terrDiskNotFound,\n\t\t}, []error{errDiskNotFound}, errVolumeNotFound},\n\t\t{[]error{}, []error{}, errXLReadQuorum},\n\t\t{[]error{errFileNotFound, errFileNotFound, errFileNotFound,\n\t\t\terrFileNotFound, errFileNotFound, nil, nil, nil, nil, nil},\n\t\t\tnil, nil},\n\t}\n\t// Validates list of all the testcases for returning valid errors.\n\tfor i, testCase := range testCases {\n\t\tgotErr := reduceReadQuorumErrs(context.Background(), testCase.errs, testCase.ignoredErrs, 5)\n\t\tif gotErr != testCase.err {\n\t\t\tt.Errorf(\"Test %d : expected %s, got %s\", i+1, testCase.err, gotErr)\n\t\t}\n\t\tgotNewErr := reduceWriteQuorumErrs(context.Background(), testCase.errs, testCase.ignoredErrs, 6)\n\t\tif gotNewErr != errXLWriteQuorum {\n\t\t\tt.Errorf(\"Test %d : expected %s, got %s\", i+1, errXLWriteQuorum, gotErr)\n\t\t}\n\t}\n}",
"func (f ReduceFunc) Reduce(value [][]byte) (reduced [][]byte, err error) {\n\treturn f(value)\n}",
"func (mr MrImpl) Reduce(key string, values []string) string {\n\tcounter := 0\n\tfor _, v := range values {\n\t\tval, err := strconv.Atoi(v)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tcounter += val\n\t}\n\n\treturn fmt.Sprintf(\"%d\", counter)\n}",
"func Reduce(c Context, op string, v Value) Value {\n\t// We must be right associative; that is the grammar.\n\t// -/1 2 3 == 1-2-3 is 1-(2-3) not (1-2)-3. Answer: 2.\n\tswitch v := v.(type) {\n\tcase Int, BigInt, BigRat:\n\t\treturn v\n\tcase Vector:\n\t\tif len(v) == 0 {\n\t\t\treturn v\n\t\t}\n\t\tacc := v[len(v)-1]\n\t\tfor i := len(v) - 2; i >= 0; i-- {\n\t\t\tacc = c.EvalBinary(v[i], op, acc)\n\t\t}\n\t\treturn acc\n\tcase *Matrix:\n\t\tif v.Rank() < 2 {\n\t\t\tErrorf(\"shape for matrix is degenerate: %s\", NewIntVector(v.shape))\n\t\t}\n\t\tstride := v.shape[v.Rank()-1]\n\t\tif stride == 0 {\n\t\t\tErrorf(\"shape for matrix is degenerate: %s\", NewIntVector(v.shape))\n\t\t}\n\t\tshape := v.shape[:v.Rank()-1]\n\t\tdata := make(Vector, size(shape))\n\t\tindex := 0\n\t\tfor i := range data {\n\t\t\tpos := index + stride - 1\n\t\t\tacc := v.data[pos]\n\t\t\tpos--\n\t\t\tfor i := 1; i < stride; i++ {\n\t\t\t\tacc = c.EvalBinary(v.data[pos], op, acc)\n\t\t\t\tpos--\n\t\t\t}\n\t\t\tdata[i] = acc\n\t\t\tindex += stride\n\t\t}\n\t\tif len(shape) == 1 { // TODO: Matrix.shrink()?\n\t\t\treturn NewVector(data)\n\t\t}\n\t\treturn NewMatrix(shape, data)\n\t}\n\tErrorf(\"can't do reduce on %s\", whichType(v))\n\tpanic(\"not reached\")\n}",
"func (e *Elog) extend() {\n\t// Slightly too clever code: Double the slice if we're out,\n\t// adding the reservation for the new eo\n\tif cap((*e).Log) == len((*e).Log) {\n\t\tt := make([]ElogOperation, len((*e).Log), (cap((*e).Log)+1)*2)\n\t\tcopy(t, (*e).Log)\n\t\t(*e).Log = t\n\t}\n\t(*e).Log = (*e).Log[:len((*e).Log)+1]\n}",
"func (a *Adapter) PruneLogs() (err error) {\n\t// get listing of directory entries\n\tentries, err := ioutil.ReadDir(a.logdir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// limit to regular files that contain the appropriate file name\n\tfiles := []os.FileInfo{}\n\tfor _, entry := range entries {\n\t\tif entry.Mode().IsRegular() && strings.Contains(entry.Name(), a.filename) {\n\t\t\tfiles = append(files, entry)\n\t\t}\n\t}\n\n\t// sort files by modified date\n\tsort.Slice(files, func(i, j int) bool { return files[i].ModTime().Before(files[j].ModTime()) })\n\n\t// if there are more files than maxfilecount, attempt a prune\n\tif len(files) > a.maxfilecount {\n\t\t// grab all but last <maxfilecount> files\n\t\ttoPrune := files[0 : len(files)-a.maxfilecount]\n\n\t\t// remove files\n\t\tfor _, fi := range toPrune {\n\t\t\tos.Remove(a.logdir + fi.Name())\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (s *Wal) StoreLog(log *raft.Log) error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.buf = s.buf[:0]\n\ts.buf = appendLog(s.buf, log)\n\treturn s.log.Write(log.Index, s.buf)\n}",
"func (l *ListHT) Log(cmd pb.Command) error {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\n\tif cmd.Op != pb.Command_SET {\n\t\t// TODO: treat 'l.first' attribution on GETs\n\t\tl.last = cmd.Id\n\t\treturn l.mayTriggerReduce()\n\t}\n\n\tentry := &listEntry{\n\t\tind: cmd.Id,\n\t\tkey: cmd.Key,\n\t}\n\n\t// a write cmd always references a new state on the aux hash table\n\tst := &State{\n\t\tind: cmd.Id,\n\t\tcmd: cmd,\n\t}\n\n\t_, exists := (*l.aux)[cmd.Key]\n\tif !exists {\n\t\t(*l.aux)[cmd.Key] = &list{}\n\t}\n\n\t// add state to the list of updates in that particular key\n\tlNode := (*l.aux)[cmd.Key].push(st)\n\tentry.ptr = lNode\n\n\t// adjust first structure index\n\tif l.lt.tail == nil {\n\t\tl.first = entry.ind\n\t}\n\n\t// insert new entry on the main list\n\tl.lt.push(entry)\n\n\t// adjust last index once inserted\n\tl.last = cmd.Id\n\n\t// immediately recovery entirely reduces the log to its minimal format\n\tif l.config.Tick == Immediately {\n\t\treturn l.ReduceLog(l.first, l.last)\n\t}\n\treturn l.mayTriggerReduce()\n}",
"func (b *logEventBuffer) enqueue(id *big.Int, logs ...logpoller.Log) int {\n\tb.lock.Lock()\n\tdefer b.lock.Unlock()\n\n\tlggr := b.lggr.With(\"id\", id.String())\n\n\tmaxBlockLogs := int(b.maxBlockLogs)\n\tmaxUpkeepLogs := int(b.maxUpkeepLogsPerBlock)\n\n\tlatestBlock := b.latestBlockSeen()\n\tadded := 0\n\tfor _, log := range logs {\n\t\tif log.BlockNumber == 0 {\n\t\t\t// invalid log\n\t\t\tcontinue\n\t\t}\n\t\ti := b.blockNumberIndex(log.BlockNumber)\n\t\tblock, prevBlock := b.blocks[i].Reset(log.BlockNumber)\n\t\tif prevBlock > 0 {\n\t\t\tif prevBlock > log.BlockNumber {\n\t\t\t\tlggr.Debugw(\"Skipping old log\", \"currentBlock\", block.blockNumber, \"newBlock\", log.BlockNumber)\n\t\t\t\tcontinue\n\t\t\t} else if prevBlock < log.BlockNumber {\n\t\t\t\tlggr.Debugw(\"Overriding block\", \"prevBlock\", prevBlock, \"newBlock\", log.BlockNumber)\n\t\t\t}\n\t\t}\n\t\tif len(block.logs)+1 > maxBlockLogs {\n\t\t\tlggr.Debugw(\"Reached max logs number per block, dropping log\", \"blockNumber\", log.BlockNumber,\n\t\t\t\t\"blockHash\", log.BlockHash, \"txHash\", log.TxHash, \"logIndex\", log.LogIndex)\n\t\t\tcontinue\n\t\t}\n\t\tif has, upkeepLogs := block.Has(id, log); has {\n\t\t\t// lggr.Debugw(\"Skipping existing log\", \"blockNumber\", log.BlockNumber,\n\t\t\t// \t\"blockHash\", log.BlockHash, \"txHash\", log.TxHash, \"logIndex\", log.LogIndex)\n\t\t\tcontinue\n\t\t} else if upkeepLogs+1 > maxUpkeepLogs {\n\t\t\tlggr.Debugw(\"Reached max logs number per upkeep, dropping log\", \"blockNumber\", log.BlockNumber,\n\t\t\t\t\"blockHash\", log.BlockHash, \"txHash\", log.TxHash, \"logIndex\", log.LogIndex)\n\t\t\tcontinue\n\t\t}\n\t\t// lggr.Debugw(\"Adding log\", \"i\", i, \"blockBlock\", block.blockNumber, \"logBlock\", log.BlockNumber, \"id\", id)\n\t\tblock.logs = append(block.logs, fetchedLog{id: id, log: log})\n\t\tb.blocks[i] = block\n\t\tadded++\n\t\tif log.BlockNumber > latestBlock {\n\t\t\tlatestBlock = log.BlockNumber\n\t\t}\n\t}\n\n\tif latestBlock > b.latestBlockSeen() {\n\t\tatomic.StoreInt64(&b.latestBlock, latestBlock)\n\t}\n\tif added > 0 {\n\t\tlggr.Debugw(\"Added logs to buffer\", \"addedLogs\", added, \"latestBlock\", latestBlock)\n\t}\n\n\treturn added\n}",
"func (rf *Raft) CheckLogs() {\n\trf.mu.Lock()\n\tstate := rf.state\n\trf.mu.Unlock()\n\tfor state == LEADER {\n\t\t//DPrintf(\"CHECKLOGS ON NODE %d: logs %s\", rf.me, rf.logs)\n\t\t//appendChan := make(chan AppendResult, len(rf.peers))\n\t\tfor peerId := range rf.peers {\n\t\t\tif peerId == rf.me {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trf.mu.Lock()\n\t\t\tlogLen := len(rf.logs)\n\t\t\tnextIndex := rf.nextIndex[peerId]\n\t\t\trf.mu.Unlock()\n\t\t\tif logLen > nextIndex {\n\t\t\t\tgo func(peerId int) {\n\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\tprevLogIndex := rf.matchIndex[peerId]\n\t\t\t\t\tprevLogTerm := rf.logs[prevLogIndex].Term\n\t\t\t\t\targs := AppendEntriesArgs{rf.currentTerm, rf.me,\n\t\t\t\t\t\tprevLogIndex, prevLogTerm,\n\t\t\t\t\t\trf.logs[prevLogIndex+1:], rf.commitIndex}\n\t\t\t\t\t\t//DPrintf(\"[BEFOREAPPEND] ENTRIES %s PREV %d LOGS %s\", args.Entries, args.PrevLogIndex, rf.logs)\n\t\t\t\t\trepl := AppendResult{}\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\tfor rf.state == LEADER {\n\t\t\t\t\t\trf.sendAppendEntries(peerId, &args, &repl)\n\t\t\t\t\t\t//DPrintf(\"[CHECKAPPENDENTRIES REPLY]me: %d Term %d send to %d args: %s repl %s\", rf.me, rf.currentTerm, peerId, args, repl)\n\t\t\t\t\t\tif repl.Success && rf.state == LEADER{\n\t\t\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\t\t\trf.nextIndex[peerId] = args.PrevLogIndex + len(args.Entries) + 1\n\t\t\t\t\t\t\trf.matchIndex[peerId] = args.PrevLogIndex + len(args.Entries)\n\t\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\t\tif repl.Term > rf.currentTerm {\n\t\t\t\t\t\t\trf.currentTerm = repl.Term\n\t\t\t\t\t\t\trf.state = FOLLOWER\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif args.PrevLogIndex > 0 {\n\t\t\t\t\t\t\targs.PrevLogIndex -= 1\n\t\t\t\t\t\t\targs.PrevLogTerm = rf.logs[args.PrevLogIndex].Term\n\t\t\t\t\t\t\targs.Entries = rf.logs[args.PrevLogIndex+1:]\n\t\t\t\t\t\t}\n\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t}\n\t\t\t\t}(peerId)\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(time.Duration(50) * time.Millisecond)\n\t\t// sleep for a while\n\t}\n}"
] | [
"0.5075089",
"0.49460164",
"0.49356857",
"0.47467375",
"0.473514",
"0.47146904",
"0.47001198",
"0.46991852",
"0.46903268",
"0.4688328",
"0.46820307",
"0.46687987",
"0.4649529",
"0.4634635",
"0.46051317",
"0.45993727",
"0.45934755",
"0.45701504",
"0.4544734",
"0.4544734",
"0.4517894",
"0.45135212",
"0.45095995",
"0.44800442",
"0.44795474",
"0.44730628",
"0.44567087",
"0.44435042",
"0.4437625",
"0.44360983",
"0.44301108",
"0.44225758",
"0.44119555",
"0.4408752",
"0.44074285",
"0.4401075",
"0.43997177",
"0.43973964",
"0.43941",
"0.43879718",
"0.43874303",
"0.4377981",
"0.43597513",
"0.43475348",
"0.43435133",
"0.43418998",
"0.43405557",
"0.43339714",
"0.43322164",
"0.43291944",
"0.43174982",
"0.4315456",
"0.43088663",
"0.4299596",
"0.42937806",
"0.4291396",
"0.42866942",
"0.42744792",
"0.4271321",
"0.42670605",
"0.4253862",
"0.4245927",
"0.42278537",
"0.4225388",
"0.42246708",
"0.4212526",
"0.4211379",
"0.41891715",
"0.41869766",
"0.41850814",
"0.41816843",
"0.4180691",
"0.41797566",
"0.4174664",
"0.41674426",
"0.4163563",
"0.41460606",
"0.414042",
"0.41380152",
"0.4135027",
"0.41205478",
"0.4106195",
"0.41024658",
"0.40830654",
"0.4076651",
"0.40735972",
"0.40670893",
"0.406253",
"0.40613353",
"0.40603876",
"0.40573177",
"0.40562946",
"0.40466008",
"0.4045822",
"0.40434837",
"0.4040188",
"0.40394148",
"0.40361497",
"0.40331542",
"0.40290794"
] | 0.7170155 | 0 |
mayTriggerReduce possibly triggers the reduce algorithm based on config params (e.g. interval period reached). Must only be called within mutual exclusion scope. | func (l *ListHT) mayTriggerReduce() error {
if l.config.Tick != Interval {
return nil
}
l.count++
if l.count >= l.config.Period {
l.count = 0
return l.ReduceLog(l.first, l.last)
}
return nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (l *ListHT) mayExecuteLazyReduce(p, n uint64) error {\n\tif l.config.Tick == Delayed {\n\t\terr := l.ReduceLog(p, n)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t} else if l.config.Tick == Interval && !l.firstReduceExists() {\n\t\t// must reduce the entire structure, just the desired interval would\n\t\t// be incoherent with the Interval config\n\t\terr := l.ReduceLog(l.first, l.last)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}",
"func (mdl *Model) Reduce(callback func(std.Value) bool) std.Value {\n\treturn nil\n}",
"func isEligibleForExecution(sensor *v1alpha1.Sensor, logger *logrus.Logger) (bool, error) {\n\tif sensor.Spec.ErrorOnFailedRound && sensor.Status.TriggerCycleStatus == v1alpha1.TriggerCycleFailure {\n\t\treturn false, errors.Errorf(\"last trigger cycle was a failure and sensor policy is set to ErrorOnFailedRound, so won't process the triggers\")\n\t}\n\tif sensor.Spec.Circuit != \"\" && sensor.Spec.DependencyGroups != nil {\n\t\treturn dependencies.ResolveCircuit(sensor, logger)\n\t}\n\tif ok := sensor.AreAllNodesSuccess(v1alpha1.NodeTypeEventDependency); ok {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}",
"func (f *Function) CanReschedule() error {\n\tif f.RetryOptions == nil {\n\t\treturn ErrNoRetryOption\n\t}\n\n\tif f.RetryCount >= f.RetryOptions.RetryLimit {\n\t\treturn ErrRetryLimitExceded\n\t}\n\n\treturn nil\n}",
"func recalcRecommit(minRecommit, prev time.Duration, target float64, inc bool) time.Duration {\n\tvar (\n\t\tprevF = float64(prev.Nanoseconds())\n\t\tnext float64\n\t)\n\tif inc {\n\t\tnext = prevF*(1-intervalAdjustRatio) + intervalAdjustRatio*(target+intervalAdjustBias)\n\t\tmax := float64(maxRecommitInterval.Nanoseconds())\n\t\tif next > max {\n\t\t\tnext = max\n\t\t}\n\t} else {\n\t\tnext = prevF*(1-intervalAdjustRatio) + intervalAdjustRatio*(target-intervalAdjustBias)\n\t\tmin := float64(minRecommit.Nanoseconds())\n\t\tif next < min {\n\t\t\tnext = min\n\t\t}\n\t}\n\treturn time.Duration(int64(next))\n}",
"func (v *parameter) HasExclusiveMaximum() bool {\n\treturn v.exclusiveMaximum != nil\n}",
"func (m *Mode) IsGearChangeAllowed(as types.AngularSpeed) bool {\n\treturn !m.enabled || !uślizg.IsUślizg(as)\n}",
"func (s *Attempt_State) MustEvolve(newState Attempt_State) {\n\terr := s.Evolve(newState)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}",
"func (jm *JobManager) shouldTriggerListeners(t Task) bool {\n\tif typed, isTyped := t.(EventTriggerListenersProvider); isTyped {\n\t\treturn typed.ShouldTriggerListeners()\n\t}\n\n\treturn true\n}",
"func (e *SyncedEnforcer) Enforce(rvals ...interface{}) bool {\n\te.m.RLock()\n\tdefer e.m.RUnlock()\n\treturn e.Enforcer.Enforce(rvals...)\n}",
"func (fugs *FileUploadGlobalState) shouldUpload(fileid string) bool {\n\tfugs.mutex.Lock()\n\tdefer fugs.mutex.Unlock()\n\n\treturn fugs.ongoingOps[fileid]\n}",
"func (sec *sensorExecutionCtx) canExecuteTrigger(trigger v1alpha1.Trigger) bool {\n\tif trigger.Template.When == nil {\n\t\treturn true\n\t}\n\tif trigger.Template.When.Any != nil {\n\t\tfor _, group := range trigger.Template.When.Any {\n\t\t\tif status := sn.GetNodeByName(sec.sensor, group); status.Type == v1alpha1.NodeTypeDependencyGroup && status.Phase == v1alpha1.NodePhaseComplete {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\tif trigger.Template.When.All != nil {\n\t\tfor _, group := range trigger.Template.When.All {\n\t\t\tif status := sn.GetNodeByName(sec.sensor, group); status.Type == v1alpha1.NodeTypeDependencyGroup && status.Phase != v1alpha1.NodePhaseComplete {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\t}\n\treturn true\n}",
"func ExclusiveWork(value WorkFunc) ExclusiveOption {\n\treturn func(c *exclusiveConfig) { c.work = value }\n}",
"func (c *Job) canDo() {\n\tdiff := int64(time.Now().Sub(c.nextTime) / time.Millisecond /*1000000*/)\n\tif diff >= 0 {\n\t\tif c.unit == delay || c.timingMode == beforeExecuteTask {\n\t\t\tc.fiber.EnqueueWithTask(c.task)\n\t\t} else {\n\t\t\td := c.task.Run()\n\t\t\tc.nextTime = c.nextTime.Add(d)\n\t\t}\n\t\tswitch c.unit {\n\t\tcase delay:\n\t\t\treturn\n\t\tcase weeks:\n\t\t\tc.nextTime = c.nextTime.AddDate(0, 0, 7)\n\t\tcase days:\n\t\t\tc.nextTime = c.nextTime.AddDate(0, 0, int(c.interval))\n\t\tcase hours:\n\t\t\tc.nextTime = c.nextTime.Add(time.Duration(c.interval) * time.Hour)\n\t\tcase minutes:\n\t\t\tc.nextTime = c.nextTime.Add(time.Duration(c.interval) * time.Minute)\n\t\tcase seconds:\n\t\t\tc.nextTime = c.nextTime.Add(time.Duration(c.interval) * time.Second)\n\t\tcase milliseconds:\n\t\t\tc.nextTime = c.nextTime.Add(time.Duration(c.interval) * time.Millisecond)\n\t\t}\n\t}\n\n\tc.taskDisposer.Dispose()\n\tadjustTime := int64(c.nextTime.Sub(time.Now()) / time.Millisecond /*1000000*/)\n\tc.taskDisposer = c.fiber.Schedule(adjustTime, c.canDo)\n}",
"func (sec *sensorExecutionCtx) canProcessTriggers() (bool, error) {\n\tif sec.sensor.Spec.ErrorOnFailedRound && sec.sensor.Status.TriggerCycleStatus == v1alpha1.TriggerCycleFailure {\n\t\treturn false, fmt.Errorf(\"last trigger cycle was a failure and sensor policy is set to ErrorOnFailedRound, so won't process the triggers\")\n\t}\n\n\tif sec.sensor.Spec.DependencyGroups != nil {\n\t\tgroups := make(map[string]interface{}, len(sec.sensor.Spec.DependencyGroups))\n\tgroup:\n\t\tfor _, group := range sec.sensor.Spec.DependencyGroups {\n\t\t\tfor _, dependency := range group.Dependencies {\n\t\t\t\tif nodeStatus := sn.GetNodeByName(sec.sensor, dependency); nodeStatus.Phase != v1alpha1.NodePhaseComplete {\n\t\t\t\t\tgroups[group.Name] = false\n\t\t\t\t\tcontinue group\n\t\t\t\t}\n\t\t\t}\n\t\t\tsn.MarkNodePhase(sec.sensor, group.Name, v1alpha1.NodeTypeDependencyGroup, v1alpha1.NodePhaseComplete, nil, sec.log, \"dependency group is complete\")\n\t\t\tgroups[group.Name] = true\n\t\t}\n\n\t\texpression, err := govaluate.NewEvaluableExpression(sec.sensor.Spec.Circuit)\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"failed to create circuit expression. err: %+v\", err)\n\t\t}\n\n\t\tresult, err := expression.Evaluate(groups)\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"failed to evaluate circuit expression. err: %+v\", err)\n\t\t}\n\n\t\treturn result == true, err\n\t}\n\n\tif sec.sensor.AreAllNodesSuccess(v1alpha1.NodeTypeEventDependency) {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}",
"func canTrigger(config, decoded *deployapi.DeploymentConfig) (bool, []deployapi.DeploymentCause) {\n\tictCount, resolved := 0, 0\n\tvar causes []deployapi.DeploymentCause\n\n\tfor _, t := range config.Spec.Triggers {\n\t\tif t.Type != deployapi.DeploymentTriggerOnImageChange {\n\t\t\tcontinue\n\t\t}\n\t\tictCount++\n\n\t\t// If this is the initial deployment then we need to wait for the image change controller\n\t\t// to resolve the image inside the pod template.\n\t\tlastTriggered := t.ImageChangeParams.LastTriggeredImage\n\t\tif len(lastTriggered) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tresolved++\n\n\t\t// We need stronger checks in order to validate that this template\n\t\t// change is an image change. Look at the deserialized config's\n\t\t// triggers and compare with the present trigger.\n\t\tif !triggeredByDifferentImage(*t.ImageChangeParams, *decoded) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcauses = append(causes, deployapi.DeploymentCause{\n\t\t\tType: deployapi.DeploymentTriggerOnImageChange,\n\t\t\tImageTrigger: &deployapi.DeploymentCauseImageTrigger{\n\t\t\t\tFrom: kapi.ObjectReference{\n\t\t\t\t\tName: t.ImageChangeParams.From.Name,\n\t\t\t\t\tNamespace: t.ImageChangeParams.From.Namespace,\n\t\t\t\t\tKind: \"ImageStreamTag\",\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n\n\tif len(causes) == 0 {\n\t\tcauses = []deployapi.DeploymentCause{{Type: deployapi.DeploymentTriggerOnConfigChange}}\n\t}\n\n\treturn ictCount == resolved, causes\n}",
"func (ps Presubmit) TriggersConditionally() bool {\n\treturn ps.NeedsExplicitTrigger() || ps.RegexpChangeMatcher.CouldRun()\n}",
"func (r *ReminderV1) ShouldRun(current_time time.Time) bool {\n\tfor _, trigger := range r.Triggers {\n\t\tif trigger.ShouldRun(current_time) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}",
"func ReduceAnyValueToBool(in []AnyValue, memo bool, f func(bool, AnyValue) bool) bool {\n\tfor _, value := range in {\n\t\tmemo = f(memo, value)\n\t}\n\treturn memo\n}",
"func Reduce(key string, values []string) string {\n\t// some reduce tasks sleep for a long time; potentially seeing if\n\t// a worker will accidentally exit early\n\tif strings.Contains(key, \"sherlock\") || strings.Contains(key, \"tom\") {\n\t\ttime.Sleep(time.Duration(3 * time.Second))\n\t}\n\t// return the number of occurrences of this file.\n\treturn strconv.Itoa(len(values))\n}",
"func (w *SimpleMapReduce) Reduce (reduceFn ReduceFn) *SimpleMapReduce {\n w.reduceFn = reduceFn\n return w\n}",
"func (ld *logData) firstReduceExists() bool {\n\tif ld.config.Inmem {\n\t\treturn ld.recentLog != nil\n\t}\n\n\t// disk config, found any state file\n\t// TODO: verify if the found file has a matching interval?\n\tif _, exists := os.Stat(ld.config.Fname); exists == nil {\n\t\treturn true\n\t}\n\treturn false\n}",
"func (b *RateBarrier) Allow() bool {\n\treturn b.source[int(atomic.AddUint64(&b.op, 1))%b.base] < b.rate\n}",
"func (c *Controller) applyConfiguration(admin submarine.AdminInterface, cluster *rapi.SubmarineCluster) (bool, error) {\n\tglog.Info(\"applyConfiguration START\")\n\tdefer glog.Info(\"applyConfiguration STOP\")\n\n\tasChanged := false\n\n\t// expected replication factor and number of master nodes\n\tcReplicaFactor := *cluster.Spec.ReplicationFactor\n\tcNbMaster := *cluster.Spec.NumberOfMaster\n\t// Adapt, convert CR to structure in submarine package\n\trCluster, nodes, err := newSubmarineCluster(admin, cluster)\n\tif err != nil {\n\t\tglog.Errorf(\"Unable to create the SubmarineCluster view, error:%v\", err)\n\t\treturn false, err\n\t}\n\t// PodTemplate changes require rolling updates\n\tif needRollingUpdate(cluster) {\n\t\tif setRollingUpdateCondition(&cluster.Status, true) {\n\t\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\n\t\tglog.Info(\"applyConfiguration needRollingUpdate\")\n\t\treturn c.manageRollingUpdate(admin, cluster, rCluster, nodes)\n\t}\n\tif setRollingUpdateCondition(&cluster.Status, false) {\n\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\t// if the number of Pods is greater than expected\n\tif needLessPods(cluster) {\n\t\tif setRebalancingCondition(&cluster.Status, true) {\n\t\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\t\tglog.Info(\"applyConfiguration needLessPods\")\n\t\t// Configure Submarine cluster\n\t\treturn c.managePodScaleDown(admin, cluster, rCluster, nodes)\n\t}\n\t// If it is not a rolling update, modify the Condition\n\tif setRebalancingCondition(&cluster.Status, false) {\n\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\tclusterStatus := &cluster.Status.Cluster\n\tif (clusterStatus.NbPods - clusterStatus.NbSubmarineRunning) != 0 {\n\t\tglog.V(3).Infof(\"All pods not ready wait to be ready, nbPods: %d, nbPodsReady: %d\", clusterStatus.NbPods, clusterStatus.NbSubmarineRunning)\n\t\treturn false, err\n\t}\n\n\t// First, we define the new masters\n\t// Select the desired number of Masters and assign Hashslots to each Master. The Master will be distributed to different K8S nodes as much as possible\n\t// Set the cluster status to Calculating Rebalancing\n\tnewMasters, curMasters, allMaster, err := clustering.DispatchMasters(rCluster, nodes, cNbMaster, admin)\n\tif err != nil {\n\t\tglog.Errorf(\"Cannot dispatch slots to masters: %v\", err)\n\t\trCluster.Status = rapi.ClusterStatusError\n\t\treturn false, err\n\t}\n\t// If the number of new and old masters is not the same\n\tif len(newMasters) != len(curMasters) {\n\t\tasChanged = true\n\t}\n\n\t// Second select Node that is already a slave\n\tcurrentSlaveNodes := nodes.FilterByFunc(submarine.IsSlave)\n\n\t//New slaves are slaves which is currently a master with no slots\n\tnewSlave := nodes.FilterByFunc(func(nodeA *submarine.Node) bool {\n\t\tfor _, nodeB := range newMasters {\n\t\t\tif nodeA.ID == nodeB.ID {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tfor _, nodeB := range currentSlaveNodes {\n\t\t\tif nodeA.ID == nodeB.ID {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\n\t// Depending on whether we scale up or down, we will dispatch slaves before/after the dispatch of slots\n\tif cNbMaster < int32(len(curMasters)) {\n\t\t// this happens usually after a scale down of the cluster\n\t\t// we should dispatch slots before dispatching slaves\n\t\tif err := clustering.DispatchSlotToNewMasters(rCluster, admin, newMasters, curMasters, allMaster); err != nil {\n\t\t\tglog.Error(\"Unable to dispatch slot on new master, err:\", err)\n\t\t\treturn false, err\n\t\t}\n\n\t\t// assign master/slave roles\n\t\tnewSubmarineSlavesByMaster, bestEffort := clustering.PlaceSlaves(rCluster, newMasters, currentSlaveNodes, newSlave, cReplicaFactor)\n\t\tif bestEffort {\n\t\t\trCluster.NodesPlacement = rapi.NodesPlacementInfoBestEffort\n\t\t}\n\n\t\tif err := clustering.AttachingSlavesToMaster(rCluster, admin, newSubmarineSlavesByMaster); err != nil {\n\t\t\tglog.Error(\"Unable to dispatch slave on new master, err:\", err)\n\t\t\treturn false, err\n\t\t}\n\t} else {\n\t\t// We are scaling up the nbmaster or the nbmaster doesn't change.\n\t\t// assign master/slave roles\n\t\tnewSubmarineSlavesByMaster, bestEffort := clustering.PlaceSlaves(rCluster, newMasters, currentSlaveNodes, newSlave, cReplicaFactor)\n\t\tif bestEffort {\n\t\t\trCluster.NodesPlacement = rapi.NodesPlacementInfoBestEffort\n\t\t}\n\n\t\tif err := clustering.AttachingSlavesToMaster(rCluster, admin, newSubmarineSlavesByMaster); err != nil {\n\t\t\tglog.Error(\"Unable to dispatch slave on new master, err:\", err)\n\t\t\treturn false, err\n\t\t}\n\n\t\tif err := clustering.DispatchSlotToNewMasters(rCluster, admin, newMasters, curMasters, allMaster); err != nil {\n\t\t\tglog.Error(\"Unable to dispatch slot on new master, err:\", err)\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\tglog.V(4).Infof(\"new nodes status: \\n %v\", nodes)\n\n\t// Set the cluster status\n\trCluster.Status = rapi.ClusterStatusOK\n\t// wait a bit for the cluster to propagate configuration to reduce warning logs because of temporary inconsistency\n\ttime.Sleep(1 * time.Second)\n\treturn asChanged, nil\n}",
"func (f *Fuse) shouldRetry() bool {\n\tif f.retries > f.RetryThreshold {\n\t\tf.retries = 0\n\t\treturn true\n\t}\n\treturn false\n}",
"func (v *parameter) HasExclusiveMinimum() bool {\n\treturn v.exclusiveMinimum != nil\n}",
"func (s *Synchronizer) syncMonitors(_ context.Context, fullSync bool, onlyEssential bool) (updateThresholds bool, err error) {\n\t_ = onlyEssential\n\n\tif !s.option.Config.Blackbox.Enable {\n\t\t// prevent a tiny memory leak\n\t\ts.pendingMonitorsUpdate = nil\n\n\t\treturn false, nil\n\t}\n\n\ts.l.Lock()\n\n\tpendingMonitorsUpdate := s.pendingMonitorsUpdate\n\ts.pendingMonitorsUpdate = nil\n\t// 5 is definitely a random heuristic, but we consider more than five simultaneous updates as more\n\t// costly that a single full sync, due to the cost of updateMonitorManager()\n\tif len(pendingMonitorsUpdate) > 5 {\n\t\tfullSync = true\n\t\t// force metric synchronization\n\t\tif _, forceSync := s.forceSync[syncMethodMetric]; !forceSync {\n\t\t\ts.forceSync[syncMethodMetric] = false\n\t\t}\n\t}\n\n\ts.l.Unlock()\n\n\tif !fullSync && len(pendingMonitorsUpdate) == 0 {\n\t\treturn false, nil\n\t}\n\n\tvar monitors []bleemeoTypes.Monitor\n\n\tif fullSync {\n\t\tmonitors, err = s.getMonitorsFromAPI()\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t} else {\n\t\tmonitors, err = s.getListOfMonitorsFromAPI(pendingMonitorsUpdate)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\ts.option.Cache.SetMonitors(monitors)\n\n\tneedConfigUpdate := false\n\tconfigs := s.option.Cache.AccountConfigsByUUID()\n\n\tfor _, m := range monitors {\n\t\tif cfg, ok := configs[m.AccountConfig]; !ok {\n\t\t\tneedConfigUpdate = true\n\n\t\t\tbreak\n\t\t} else if _, ok := cfg.AgentConfigByName[bleemeoTypes.AgentTypeMonitor]; !ok {\n\t\t\tneedConfigUpdate = true\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif needConfigUpdate {\n\t\ts.l.Lock()\n\n\t\ts.forceSync[syncMethodAccountConfig] = true\n\n\t\ts.l.Unlock()\n\t}\n\n\treturn false, s.ApplyMonitorUpdate()\n}",
"func (b *bgpserver) performReconfigure() {\n\n\tif b.noUpdatesReady() {\n\t\t// last update happened before the last reconfigure\n\t\treturn\n\t}\n\n\tstart := time.Now()\n\n\t// these are the VIP addresses\n\t// get both the v4 and v6 to use in CheckConfigParity below\n\taddressesV4, addressesV6, err := b.ipLoopback.Get()\n\tif err != nil {\n\t\tb.metrics.Reconfigure(\"error\", time.Now().Sub(start))\n\t\tb.logger.Infof(\"unable to compare configurations with error %v\", err)\n\t\treturn\n\t}\n\n\t// splice together to compare against the internal state of configs\n\t// addresses is sorted within the CheckConfigParity function\n\taddresses := append(addressesV4, addressesV6...)\n\n\t// compare configurations and apply new IPVS rules if they're different\n\tsame, err := b.ipvs.CheckConfigParity(b.nodes, b.config, addresses, b.configReady())\n\tif err != nil {\n\t\tb.metrics.Reconfigure(\"error\", time.Now().Sub(start))\n\t\tb.logger.Infof(\"unable to compare configurations with error %v\", err)\n\t\treturn\n\t}\n\n\tif same {\n\t\tb.logger.Debug(\"parity same\")\n\t\tb.metrics.Reconfigure(\"noop\", time.Now().Sub(start))\n\t\treturn\n\t}\n\n\tb.logger.Debug(\"parity different, reconfiguring\")\n\tif err := b.configure(); err != nil {\n\t\tb.metrics.Reconfigure(\"critical\", time.Now().Sub(start))\n\t\tb.logger.Infof(\"unable to apply ipv4 configuration. %v\", err)\n\t\treturn\n\t}\n\n\tif err := b.configure6(); err != nil {\n\t\tb.metrics.Reconfigure(\"critical\", time.Now().Sub(start))\n\t\tb.logger.Infof(\"unable to apply ipv6 configuration. %v\", err)\n\t\treturn\n\t}\n\tb.metrics.Reconfigure(\"complete\", time.Now().Sub(start))\n}",
"func (ps Presubmit) NeedsExplicitTrigger() bool {\n\treturn !ps.AlwaysRun && !ps.RegexpChangeMatcher.CouldRun()\n}",
"func (ps Postsubmit) ShouldRun(baseRef string, changes ChangedFilesProvider) (bool, error) {\n\tif !ps.CouldRun(baseRef) {\n\t\treturn false, nil\n\t}\n\n\t// Consider `run_if_changed` or `skip_if_only_changed` rules.\n\tif determined, shouldRun, err := ps.RegexpChangeMatcher.ShouldRun(changes); err != nil {\n\t\treturn false, err\n\t} else if determined {\n\t\treturn shouldRun, nil\n\t}\n\n\t// At this point neither `run_if_changed` nor `skip_if_only_changed` were\n\t// set. We're left with 2 cases: (1) `always_run: ...` was provided\n\t// explicitly, or (2) this field was not defined in the job at all. In the\n\t// second case, we default to \"true\".\n\n\t// If the `always_run` field was explicitly set, return it.\n\tif ps.AlwaysRun != nil {\n\t\treturn *ps.AlwaysRun, nil\n\t}\n\n\t// Postsubmits default to always run. This is the case if `always_run` was\n\t// not explicitly set.\n\treturn true, nil\n}",
"func (o *LastMileAccelerationOptions) HasUaRestrict() bool {\n\tif o != nil && o.UaRestrict != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (s *SourceControl) ConfigureTriggers(state *FullTriggerState, reply *bool) error {\n\t// The old EdgeMulti* parameters are no longer used in the triggering code,\n\t// now being replaced with EMTState\n\t// for now we're maintaining backwards compatibility with the old RPC calls\n\t// so this is the point where we create an EMTState from the EdgeMulti* values\n\tif state.TriggerState.EdgeMulti && state.TriggerState.EMTState == (EMTState{}) {\n\t\tnewEMTState, err := state.TriggerState.EMTBackwardCompatibleRPCFields.toEMTState()\n\t\tif err != nil {\n\t\t\t*reply = false\n\t\t\treturn err\n\t\t}\n\t\tstate.TriggerState.EMTState = newEMTState\n\t}\n\tlog.Printf(\"Got ConfigureTriggers: %v\", spew.Sdump(state))\n\tf := func() {\n\t\terr := s.ActiveSource.ChangeTriggerState(state)\n\t\ts.broadcastTriggerState()\n\t\ts.queuedResults <- err\n\t}\n\terr := s.runLaterIfActive(f)\n\t*reply = (err == nil)\n\treturn err\n}",
"func (ps Presubmit) ShouldRun(baseRef string, changes ChangedFilesProvider, forced, defaults bool) (bool, error) {\n\tif !ps.CouldRun(baseRef) {\n\t\treturn false, nil\n\t}\n\tif ps.AlwaysRun {\n\t\treturn true, nil\n\t}\n\tif forced {\n\t\treturn true, nil\n\t}\n\tdetermined, shouldRun, err := ps.RegexpChangeMatcher.ShouldRun(changes)\n\treturn (determined && shouldRun) || defaults, err\n}",
"func (n *RemoveNewsroomWatchersTrigger) ShouldRun(collector *EventCollector,\n\tevent *model.Event) bool {\n\treturn event.EventType() == \"ListingRemoved\"\n}",
"func RequireConfig(logger *log.Context, val, name string) {\n\tif val == \"\" {\n\t\tLogFatal(logger, \"error\", fmt.Sprintf(\"config key '%s' not configured\", name))\n\t}\n}",
"func (m *ParameterMutator) ClearExclusiveMaximum() *ParameterMutator {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tm.proxy.exclusiveMaximum = nil\n\treturn m\n}",
"func (m *Map) SpeculativeReduce(\n\treduce func(map[interface{}]interface{}) (interface{}, bool),\n\tjoin func(x, y interface{}) (interface{}, bool),\n) (interface{}, bool) {\n\tvar recur func(splits []Split) (interface{}, bool)\n\trecur = func(splits []Split) (interface{}, bool) {\n\t\tif len(splits) < 2 {\n\t\t\t// NewMap and case 2 below ensure that len(splits) > 0\n\t\t\treturn splits[0].speculativeReduce(reduce)\n\t\t}\n\t\tvar left, right interface{}\n\t\tvar b0, b1 bool\n\t\tvar p interface{}\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(1)\n\t\tswitch len(splits) {\n\t\tcase 2:\n\t\t\tgo func() {\n\t\t\t\tdefer func() {\n\t\t\t\t\tp = internal.WrapPanic(recover())\n\t\t\t\t\twg.Done()\n\t\t\t\t}()\n\t\t\t\tright, b1 = splits[1].speculativeReduce(reduce)\n\t\t\t}()\n\t\t\tleft, b0 = splits[0].speculativeReduce(reduce)\n\t\tdefault:\n\t\t\thalf := len(splits) / 2\n\t\t\tgo func() {\n\t\t\t\tdefer func() {\n\t\t\t\t\tp = internal.WrapPanic(recover())\n\t\t\t\t\twg.Done()\n\t\t\t\t}()\n\t\t\t\tright, b1 = recur(splits[half:])\n\t\t\t}()\n\t\t\tleft, b0 = recur(splits[:half])\n\t\t}\n\t\tif b0 {\n\t\t\treturn left, true\n\t\t}\n\t\twg.Wait()\n\t\tif p != nil {\n\t\t\tpanic(p)\n\t\t}\n\t\tif b1 {\n\t\t\treturn right, true\n\t\t}\n\t\treturn join(left, right)\n\t}\n\treturn recur(m.splits)\n}",
"func MustMax(valueA gcv.Value, valueB gcv.Value) gcv.Value {\n\tval, err := Max(valueA, valueB)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn val\n}",
"func (n *AddNewsroomWatchersTrigger) ShouldRun(collector *EventCollector,\n\tevent *model.Event) bool {\n\treturn event.EventType() == \"Application\"\n}",
"func (uc *userConfig) IfConflict(maxReplicas int) bool {\n\tret := false\n\t// move_leaders\n\tfor i, l1 := range uc.cfg.Leaders.Leader {\n\t\tfor j, l2 := range uc.cfg.Leaders.Leader {\n\t\t\tif i < j {\n\t\t\t\tif (l1.KeyStart <= l2.KeyStart && l1.KeyEnd > l2.KeyStart) ||\n\t\t\t\t\t(l2.KeyStart <= l1.KeyStart && l2.KeyEnd > l1.KeyStart) {\n\t\t\t\t\tif ((l1.StartTime.Before(l2.StartTime) || l1.StartTime.Equal(l2.StartTime)) && \n\t\t\t\t\t\t\tl1.EndTime.After(l2.StartTime)) || \n\t\t\t\t\t\t((l2.StartTime.Before(l1.StartTime) || l2.StartTime.Equal(l1.StartTime)) && \n\t\t\t\t\t\t\tl2.EndTime.After(l1.StartTime)) {\n\t\t\t\t\t\tlog.Error(\"Key Range Conflict\", zap.Ints(\"Config Move-Leader Nums\", []int{i, j}))\n\t\t\t\t\t\tret = true\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// move_regions\n\tfor i, r1 := range uc.cfg.Regions.Region {\n\t\tfor j, r2 := range uc.cfg.Regions.Region {\n\t\t\tif i < j {\n\t\t\t\tif (r1.KeyStart <= r2.KeyStart && r1.KeyEnd > r2.KeyStart) ||\n\t\t\t\t\t(r2.KeyStart <= r1.KeyStart && r2.KeyEnd > r1.KeyStart) {\n\t\t\t\t\tif ((r1.StartTime.Before(r2.StartTime) || r1.StartTime.Equal(r2.StartTime)) &&\n\t\t\t\t\t\t\tr1.EndTime.After(r2.StartTime)) ||\n\t\t\t\t\t\t((r2.StartTime.Before(r1.StartTime) || r2.StartTime.Equal(r1.StartTime)) &&\n\t\t\t\t\t\t\tr2.EndTime.After(r1.StartTime)) {\n\t\t\t\t\t\tlog.Error(\"Key Range Conflict\", zap.Ints(\"Config Move-Region Nums\", []int{i, j}))\n\t\t\t\t\t\tret = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// store nums > max replicas\n\tfor i, r := range uc.cfg.Regions.Region {\n\t\tif len(r.Stores) > maxReplicas {\n\t\t\tlog.Error(\"the number of stores is beyond the max replicas\", zap.Int(\"Config Move-Region Nums\", i))\n\t\t\tret = true\n\t\t}\n\t}\n\treturn ret\n}",
"func (wes WhenExpressions) AllowsExecution() bool {\n\tfor _, we := range wes {\n\t\tif !we.isTrue() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}",
"func (w *worker) waitExcludeHost(host *chop.ChiHost) bool {\n\t// Check CHI settings\n\tswitch {\n\tcase host.GetCHI().IsReconcilingPolicyWait():\n\t\treturn true\n\tcase host.GetCHI().IsReconcilingPolicyNoWait():\n\t\treturn false\n\t}\n\n\t// Fallback to operator's settings\n\treturn w.c.chop.Config().ReconcileWaitExclude\n}",
"func (m *ParameterMutator) ExclusiveMaximum(v float64) *ParameterMutator {\n\tm.proxy.exclusiveMaximum = &v\n\treturn m\n}",
"func (parser *MarpaParser) earleyReduce(location int, item EarleyItem, term Term, trigger EarleyItem, nodes map[string]*SppfNode) {\n\ttoAH := parser.machine.Goto(item.state, term)\n\tif toAH > -1 {\n\t\tk := item.parent\n\t\tz := item.parseNode\n\t\tw := trigger.parseNode\n\t\ty := parser.MakeParseNode(term, k, location, z, w, nodes)\n\t\t/*fmt.Println(\"REDUCE\", y)\n\t\tif y != w {\n\t\t\tfmt.Println(\"w \", w)\n\t\t}\n\t\tif y != z {\n\t\t\tfmt.Println(\"z \", z)\n\t\t}*/\n\t\tparser.addEIM(location, toAH, item.parent, y)\n\t}\n}",
"func (c *VolumeController) shouldRestoreRecurringJobs(v *longhorn.Volume) bool {\n\tif v.Spec.FromBackup == \"\" || v.Spec.Standby || v.Status.RestoreInitiated {\n\t\treturn false\n\t}\n\n\tif v.Spec.RestoreVolumeRecurringJob == longhorn.RestoreVolumeRecurringJobEnabled {\n\t\treturn true\n\t}\n\n\tif v.Spec.RestoreVolumeRecurringJob == longhorn.RestoreVolumeRecurringJobDisabled {\n\t\treturn false\n\t}\n\n\t// Avoid recurring job restoration overrides the new recurring jobs added by users.\n\texistingJobs := datastore.MarshalLabelToVolumeRecurringJob(v.Labels)\n\tfor jobName, job := range existingJobs {\n\t\tif !job.IsGroup || jobName != longhorn.RecurringJobGroupDefault {\n\t\t\tc.logger.Warn(\"User already specified recurring jobs for this volume, cannot continue restoring recurring jobs from the backup volume labels\")\n\t\t\treturn false\n\t\t}\n\t}\n\n\trestoringRecurringJobs, err := c.ds.GetSettingAsBool(types.SettingNameRestoreVolumeRecurringJobs)\n\tif err != nil {\n\t\tc.logger.WithError(err).Warnf(\"Failed to get %v setting\", types.SettingNameRestoreVolumeRecurringJobs)\n\t}\n\n\treturn restoringRecurringJobs\n}",
"func RequiresReplaceIfConfigured() planmodifier.List {\n\treturn RequiresReplaceIf(\n\t\tfunc(_ context.Context, req planmodifier.ListRequest, resp *RequiresReplaceIfFuncResponse) {\n\t\t\tif req.ConfigValue.IsNull() {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tresp.RequiresReplace = true\n\t\t},\n\t\t\"If the value of this attribute is configured and changes, Terraform will destroy and recreate the resource.\",\n\t\t\"If the value of this attribute is configured and changes, Terraform will destroy and recreate the resource.\",\n\t)\n}",
"func (th *TlfHistory) Recompute(loggedInUser string) (\n\twritersWhoNeedMore map[string]bool) {\n\tth.lock.Lock()\n\tdefer th.lock.Unlock()\n\t_, writersWhoNeedMore = th.recomputeLocked(loggedInUser)\n\treturn writersWhoNeedMore\n}",
"func (g *Groovy) Ensure(filter func(name string) bool, updateGroovyScript func(groovyScript string) string) (requeue bool, err error) {\n\tsecret := &corev1.Secret{}\n\tif len(g.customization.Secret.Name) > 0 {\n\t\terr := g.k8sClient.Get(context.TODO(), types.NamespacedName{Name: g.customization.Secret.Name, Namespace: g.jenkins.ObjectMeta.Namespace}, secret)\n\t\tif err != nil {\n\t\t\treturn true, err\n\t\t}\n\t}\n\n\tfor _, configMapRef := range g.customization.Configurations {\n\t\tconfigMap := &corev1.ConfigMap{}\n\t\terr := g.k8sClient.Get(context.TODO(), types.NamespacedName{Name: configMapRef.Name, Namespace: g.jenkins.ObjectMeta.Namespace}, configMap)\n\t\tif err != nil {\n\t\t\treturn true, errors.WithStack(err)\n\t\t}\n\n\t\tvar names []string\n\t\tfor name := range configMap.Data {\n\t\t\tnames = append(names, name)\n\t\t}\n\t\tsort.Strings(names)\n\n\t\tfor _, name := range names {\n\t\t\tgroovyScript := updateGroovyScript(configMap.Data[name])\n\t\t\tif !filter(name) {\n\t\t\t\tg.logger.V(log.VDebug).Info(fmt.Sprintf(\"Skipping %s ConfigMap '%s' name '%s'\", g.configurationType, configMap.Name, name))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\thash := g.calculateCustomizationHash(*secret, name, groovyScript)\n\t\t\tif g.isGroovyScriptAlreadyApplied(configMap.Name, name, hash) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tg.logger.Info(fmt.Sprintf(\"%s ConfigMap '%s' name '%s' running groovy script\", g.configurationType, configMap.Name, name))\n\t\t\trequeue, err := g.EnsureSingle(configMap.Name, name, hash, groovyScript)\n\t\t\tif err != nil || requeue {\n\t\t\t\treturn requeue, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false, nil\n}",
"func (r *ReconcileFunction) Reconcile(request reconcile.Request) (reconcile.Result, error) {\n\tif r.config == nil || r.runtimeConfig == nil || time.Since(configUpdatedTime) > 30*time.Second {\n\t\tlogrus.Infof(\"Read GlobalConfig...\")\n\t\tr.configInit()\n\t\tlogrus.Infof(\"Read GlobalConfig Success\")\n\t} else {\n\t\tlogrus.Warn(\"Read GlobalConfig From Cache\")\n\t}\n\treqLogger := logrus.WithFields(logrus.Fields{\n\t\t\"Request.Namespace\": request.Namespace,\n\t\t\"Request.Name\": request.Name,\n\t})\n\tr.logger = reqLogger\n\treqLogger.Info(\"Reconciling Function\")\n\n\tinstance := &funceasyv1.Function{}\n\ttheRegexp := regexp.MustCompile(`^(\\w+)-(\\w+)$`)\n\tparams := theRegexp.FindStringSubmatch(request.Name)\n\tif params != nil {\n\t\tfunctionCRName := params[1]\n\t\terr := r.client.Get(context.TODO(), types.NamespacedName{\n\t\t\tNamespace: request.Namespace,\n\t\t\tName: functionCRName,\n\t\t}, instance)\n\t\tif err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\treturn reconcile.Result{}, nil\n\t\t\t}\n\t\t\treturn reconcile.Result{}, err\n\t\t}\n\t} else {\n\t\terr := r.client.Get(context.TODO(), request.NamespacedName, instance)\n\t\tif err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\treturn reconcile.Result{}, nil\n\t\t\t}\n\t\t\treturn reconcile.Result{}, err\n\t\t}\n\t}\n\n\tconfigMap, requeue, err := r.ensureConfigMap(instance)\n\tif requeue {\n\t\treturn reconcile.Result{Requeue: true}, err\n\t}\n\n\t_, requeue, err = r.ensureDeployment(instance)\n\tif requeue {\n\t\treturn reconcile.Result{Requeue: true}, err\n\t}\n\n\trequeue, err = r.ensureService(instance)\n\tif requeue {\n\t\treturn reconcile.Result{Requeue: true}, err\n\t}\n\n\trequeue, err = r.ensureHPA(instance)\n\tif requeue {\n\t\treturn reconcile.Result{Requeue: true}, err\n\t}\n\n\terr = r.checkUpdate(instance, configMap)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\terr = r.updateStatus(instance)\n\tif err != nil {\n\t\tr.logger.Warn(\"Failed Update Status -> Requeue \")\n\t\treturn reconcile.Result{Requeue: true}, nil\n\t}\n\n\treturn reconcile.Result{}, nil\n}",
"func (r *mutationStreamReader) checkAnySyncDue() bool {\n\n\tsyncDue := false\n\tr.queueMapLock.RLock()\nloop:\n\tfor bucket, _ := range r.bucketQueueMap {\n\t\tfor i := 0; i < r.numWorkers; i++ {\n\t\t\tr.streamWorkers[i].lock.Lock()\n\t\t\tif r.streamWorkers[i].bucketSyncDue[bucket] {\n\t\t\t\tsyncDue = true\n\t\t\t}\n\t\t\tr.streamWorkers[i].lock.Unlock()\n\t\t\tif syncDue {\n\t\t\t\tbreak loop\n\t\t\t}\n\t\t}\n\t}\n\tr.queueMapLock.RUnlock()\n\treturn syncDue\n}",
"func (m *Master) haveDone() bool {\n\tret := true\n\tt := time.Now().Unix()\n\tj := 0\n\tfor j < len(m.reduceTasks) {\n\t\tif m.reduceTasks[j].state == 1 {\n\t\t\tif t-m.reduceTasks[j].emittime >= TIMEOUT {\n\t\t\t\tm.reduceTasks[j].state = 0\n\t\t\t}\n\t\t}\n\t\tj++\n\t}\n\ti := 0\n\tfor _, reduceTask := range m.reduceTasks {\n\t\tif reduceTask.state == 0 {\n\t\t\tm.nextreducetask = i\n\t\t\tbreak\n\t\t}\n\t\ti++\n\t}\n\tfor _, reduceTask := range m.reduceTasks {\n\t\tif reduceTask.state != 2 {\n\t\t\tret = false\n\t\t\tbreak\n\t\t}\n\t}\n\tif ret {\n\t\tm.done = true\n\t}\n\treturn ret\n}",
"func (c *Context) WatchOnly() bool { return c.MyIndex < 0 || c.Config.WatchOnly() }",
"func (_m *HostMemoryManager) TriggerEviction() {\n\t_m.Called()\n}",
"func (_m *IProvider) Monitor(_a0 map[string]*model.WorkerConfig, _a1 []*message.Message) {\n\t_m.Called(_a0, _a1)\n}",
"func def_guard(bt *yboter,b *game.Board, r *game.Robot) game.Action {\n\tnearby_count := count_enermies_adj(b,r)\n\tswitch {\n\t\tcase (bt.self_prevHP[r.ID] - r.Health > 15):\n\t\t\tif r.Health >= nearby_count*10 {\n\t\t\t\treturn game.Action{Kind: game.Guard}\n\t\t\t}\n\t}\n return game.Action{Kind: game.Wait}\n}",
"func Cond(apply bool, options ...types.Option) types.Option {\n\tif apply {\n\t\treturn func(g *types.Cmd) {\n\t\t\tg.ApplyOptions(options...)\n\t\t}\n\t}\n\treturn NoOp\n}",
"func (rf *ReduceFunc) Reduce(mx *Ctx) *State {\n\treturn rf.Func(mx)\n}",
"func (m *Monitor) Configure(conf *Config) error {\n\tm.logger = log.WithFields(log.Fields{\"monitorType\": monitorType, \"monitorID\": conf.MonitorID})\n\n\tvar ctx context.Context\n\tctx, m.cancel = context.WithCancel(context.Background())\n\n\t// save shallow copy of conf to monitor for quick reference\n\tconfCopy := *conf\n\tm.conf = &confCopy\n\n\t// configure filters\n\tvar err error\n\tif len(m.conf.FSTypes) > 0 {\n\t\tm.fsTypes, err = filter.NewOverridableStringFilter(m.conf.FSTypes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// strip trailing / from HostFSPath so when we do string replacement later\n\t// we are left with a path starting at /\n\tm.hostFSPath = strings.TrimRight(m.conf.HostFSPath, \"/\")\n\n\t// configure filters\n\tif len(m.conf.MountPoints) > 0 {\n\t\tm.mountPoints, err = filter.NewOverridableStringFilter(m.conf.MountPoints)\n\t}\n\n\t// return an error if we can't set the filter\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm.sendModeDimension = m.conf.SendModeDimension\n\n\t// gather metrics on the specified interval\n\tutils.RunOnInterval(ctx, func() {\n\t\tm.emitDatapoints()\n\t}, time.Duration(m.conf.IntervalSeconds)*time.Second)\n\n\treturn nil\n}",
"func (e *hcEventsObserver) applyWithConfidence(ctx context.Context, height abi.ChainEpoch) {\n\tbyOrigH, ok := e.confQueue[height]\n\tif !ok {\n\t\treturn // no triggers at this height\n\t}\n\n\tfor origH, events := range byOrigH {\n\t\tfor _, event := range events {\n\t\t\tif event.called {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttrigger := e.triggers[event.trigger]\n\t\t\tif trigger.disabled {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tmore, err := trigger.handle(ctx, event.data, event.prevTipset, event.tipset, height)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"chain trigger (@H %d, triggered @ %d) failed: %s\", origH, height, err)\n\t\t\t\tcontinue // don't revert failed calls\n\t\t\t}\n\n\t\t\tevent.called = true\n\n\t\t\ttouts, ok := e.timeouts[trigger.timeout]\n\t\t\tif ok {\n\t\t\t\ttouts[event.trigger]++\n\t\t\t}\n\n\t\t\ttrigger.disabled = !more\n\t\t}\n\t}\n}",
"func (l *Logger) Dispatch(ctx context.Context, e Event) {\n\tif e == nil {\n\t\treturn\n\t}\n\tflag := e.GetFlag()\n\tif !l.IsEnabled(flag) {\n\t\treturn\n\t}\n\tif !l.Scopes.IsEnabled(GetPath(ctx)...) {\n\t\treturn\n\t}\n\n\tif !IsSkipTrigger(ctx) {\n\t\tvar filters map[string]Filter\n\t\tvar listeners map[string]*Worker\n\t\tl.Lock()\n\t\tif l.Filters != nil {\n\t\t\tif flagFilters, ok := l.Filters[flag]; ok {\n\t\t\t\tfilters = flagFilters\n\t\t\t}\n\t\t}\n\t\tif l.Listeners != nil {\n\t\t\tif flagListeners, ok := l.Listeners[flag]; ok {\n\t\t\t\tlisteners = flagListeners\n\t\t\t}\n\t\t}\n\t\tl.Unlock()\n\n\t\tvar shouldFilter bool\n\t\tfor _, filter := range filters {\n\t\t\te, shouldFilter = filter(ctx, e)\n\t\t\tif shouldFilter {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tfor _, listener := range listeners {\n\t\t\tlistener.Work <- EventWithContext{ctx, e}\n\t\t}\n\t}\n\n\tl.Write(ctx, e)\n}",
"func (j *Job) shouldRun() bool {\n\treturn time.Now().Unix() >= j.nextRun.Unix()\n}",
"func correctlyMitigatedEffects(de DisasterEffects, magResourceMult float64) bool {\n\tcorrect := true\n\tfor id, mag := range de.CommonPoolMitigated {\n\t\tcorrect = correct && (mag <= de.Absolute[id]*magResourceMult)\n\t}\n\treturn correct\n}",
"func (d *Device) doConfigure(cfg Configuration) (err error) {\n\n\t// Verify unit communication\n\tif !d.Connected() {\n\t\treturn errNotConnected\n\t}\n\n\t// Multipliers come from \"Table 3. Sensor characteristics\" of the datasheet * 1000\n\tswitch cfg.AccelRange {\n\tcase ACCEL_2G:\n\t\td.accelMultiplier = 61\n\tcase ACCEL_4G:\n\t\td.accelMultiplier = 122\n\tcase ACCEL_8G:\n\t\td.accelMultiplier = 244\n\tcase ACCEL_16G:\n\t\td.accelMultiplier = 732\n\t}\n\tswitch cfg.GyroRange {\n\tcase GYRO_250DPS:\n\t\td.gyroMultiplier = 8750\n\tcase GYRO_500DPS:\n\t\td.gyroMultiplier = 17500\n\tcase GYRO_2000DPS:\n\t\td.gyroMultiplier = 70000\n\t}\n\tswitch cfg.MagRange {\n\tcase MAG_4G:\n\t\td.magMultiplier = 14\n\tcase MAG_8G:\n\t\td.magMultiplier = 29\n\tcase MAG_12G:\n\t\td.magMultiplier = 43\n\tcase MAG_16G:\n\t\td.magMultiplier = 58\n\t}\n\n\tdata := d.buf[:1]\n\n\t// Configure accelerometer\n\t// Sample rate & measurement range\n\tdata[0] = uint8(cfg.AccelSampleRate)<<5 | uint8(cfg.AccelRange)<<3\n\terr = d.bus.WriteRegister(d.AccelAddress, CTRL_REG6_XL, data)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Configure gyroscope\n\t// Sample rate & measurement range\n\tdata[0] = uint8(cfg.GyroSampleRate)<<5 | uint8(cfg.GyroRange)<<3\n\terr = d.bus.WriteRegister(d.AccelAddress, CTRL_REG1_G, data)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Configure magnetometer\n\n\t// Temperature compensation enabled\n\t// High-performance mode XY axis\n\t// Sample rate\n\tdata[0] = 0b10000000 | 0b01000000 | uint8(cfg.MagSampleRate)<<2\n\terr = d.bus.WriteRegister(d.MagAddress, CTRL_REG1_M, data)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Measurement range\n\tdata[0] = uint8(cfg.MagRange) << 5\n\terr = d.bus.WriteRegister(d.MagAddress, CTRL_REG2_M, data)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Continuous-conversion mode\n\t// https://electronics.stackexchange.com/questions/237397/continuous-conversion-vs-single-conversion-mode\n\tdata[0] = 0b00000000\n\terr = d.bus.WriteRegister(d.MagAddress, CTRL_REG3_M, data)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// High-performance mode Z axis\n\tdata[0] = 0b00001000\n\terr = d.bus.WriteRegister(d.MagAddress, CTRL_REG4_M, data)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn nil\n}",
"func CumprodExclusive(value bool) CumprodAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"exclusive\"] = value\n\t}\n}",
"func (t *Trigger) needsDelay() (bool, time.Duration) {\n\tif t.params.MinInterval == time.Duration(0) {\n\t\treturn false, 0\n\t}\n\n\tsleepTime := time.Since(t.lastTrigger.Add(t.params.MinInterval))\n\treturn sleepTime < 0, sleepTime * -1\n}",
"func (bw *balancerWorker) allowBalance() bool {\n\tbw.RLock()\n\tbalanceCount := uint64(len(bw.balanceOperators))\n\tbw.RUnlock()\n\n\t// TODO: We should introduce more strategies to control\n\t// how many balance tasks at same time.\n\tif balanceCount >= bw.cfg.MaxBalanceCount {\n\t\treturn false\n\t}\n\n\treturn true\n}",
"func (w *Window) Reduce() interface{} {\n\treturn w.reducedAt(time.Now())\n}",
"func Restrict(roDirs, roFiles, rwDirs, rwFiles []string) error {\n\trulesetAttr := ll.RulesetAttr{\n\t\tHandledAccessFs: uint64(accessFSRoughlyRead | accessFSRoughlyWrite),\n\t}\n\tfd, err := ll.LandlockCreateRuleset(&rulesetAttr, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer syscall.Close(fd)\n\n\tif err := populateRuleset(fd, roDirs, accessFSRoughlyRead); err != nil {\n\t\treturn err\n\t}\n\tif err := populateRuleset(fd, roFiles, accessFSRoughlyRead&accessFile); err != nil {\n\t\treturn err\n\t}\n\tif err := populateRuleset(fd, rwDirs, accessFSRoughlyWrite); err != nil {\n\t\treturn err\n\t}\n\tif err := populateRuleset(fd, rwFiles, accessFSRoughlyWrite&accessFile); err != nil {\n\t\treturn err\n\t}\n\n\tif err := unix.Prctl(unix.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ll.LandlockRestrictSelf(fd, 0); err != nil {\n\t\treturn err\n\t}\n\t// xxx enable\n\treturn nil\n}",
"func ReduceBoolToAnyValue(in []bool, memo AnyValue, f func(AnyValue, bool) AnyValue) AnyValue {\n\tfor _, value := range in {\n\t\tmemo = f(memo, value)\n\t}\n\treturn memo\n}",
"func (l *ListHT) ReduceLog(p, n uint64) error {\n\tcmds, err := ApplyReduceAlgo(l, l.config.Alg, p, n)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn l.updateLogState(cmds, p, n, false)\n}",
"func (th *TlfHistory) Recompute() (writersWhoNeedMore map[string]bool) {\n\tth.lock.Lock()\n\tdefer th.lock.Unlock()\n\t_, writersWhoNeedMore = th.recomputeLocked()\n\treturn writersWhoNeedMore\n}",
"func (cc CollectionCache) reduce() {\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.Println(\"Panic Recovered at dbServices.collectionCache.reduce(): \", r)\n\t\t\treturn\n\t\t}\n\t}()\n\n\tcount := collectionCacheCount.Get()\n\n\tif count >= collectionCacheMaxCount { //Clear to 50%\n\n\t\tcountDown := count\n\n\t\tcollectionCache.Range(func(key interface{}, value interface{}) bool {\n\n\t\t\tgo cc.removeByKey(key)\n\n\t\t\tif countDown == 0 {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tcountDown--\n\n\t\t\treturn true\n\t\t})\n\t} else {\n\n\t\tstaleTime := time.Now().Add(-1 * time.Hour)\n\n\t\tcollectionCache.Range(func(key interface{}, value interface{}) bool {\n\n\t\t\tcv, parsed := value.(*CacheValue)\n\t\t\tif parsed && cv.lastUpdate.Get().Before(staleTime) {\n\t\t\t\tgo cc.removeByKey(key)\n\t\t\t}\n\n\t\t\treturn true\n\t\t})\n\n\t}\n\n}",
"func (kv *ShardKV) TryUpdateConfig () {\n\n kv.configMtx.Lock()\n curConfig := kv.config\n kv.configMtx.Unlock()\n\n newConfig := kv.mck.Query(curConfig.Num+1)\n if newConfig.Num == curConfig.Num+1 {\n if _, isLeader := kv.rf.GetState(); isLeader {\n recvFinished := false\n kv.configMtx.Lock()\n recvFinished = kv.shardToRecv.Empty() == true\n kv.configMtx.Unlock()\n\n if recvFinished {\n request := CfgChangeArgs{newConfig}\n kv.rf.Start(Op{Type: ReqCfgChange, ArgsCfgChange: request})\n }\n }\n }\n}",
"func (c config) EvalConcurrency() int { return c.evalConcurrency }",
"func (task *Task) IsDynamicGroupBasedTrigger() bool {\n\treturn task.IsDynamicGroupEnterTrigger() || task.IsDynamicGroupExitTrigger()\n}",
"func (cm *CostModel) CanCompute(start, end time.Time) bool {\n\treturn start.Before(time.Now())\n}",
"func (w *GitWatcher) doReconfigure(newState config.State) error {\n\tadditions, removals := task.DiffTargets(w.state.Targets, newState.Targets)\n\tw.state = newState\n\n\terr := w.watchTargets()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// out with the old, in with the new!\n\tw.executeTargets(removals, true)\n\tw.executeTargets(additions, false)\n\n\treturn nil\n}",
"func (kv *ShardKV) tick() {\n DPrintf(\"Server %s called tick function! Current max_config_in_log is %d\", kv.id, kv.max_config_in_log)\n kv.mu.Lock()\n defer kv.mu.Unlock()\n\n new_config := kv.sm.Query(-1)\n kv.max_config_in_log = int(math.Max(float64(kv.max_config_in_log), float64(kv.curr_config.Num)))\n if new_config.Num > kv.max_config_in_log { // change this to kv.max_config_in_log\n DPrintf2(\"Server %s Configuration is old! Putting configs from %d to %d in log\", kv.id, kv.max_config_in_log +1, new_config.Num)\n for config_num := kv.max_config_in_log +1; config_num <= new_config.Num; config_num++{\n kv.max_config_in_log = config_num\n kv.startReconfiguration(kv.sm.Query(config_num))\n } \n }\n // DPrintf(\"Server %s ending tick function\", kv.id)\n}",
"func (r Robot) Exclusive(tag string, queueTask bool) (success bool) {\n\tif r.exclusive {\n\t\t// TODO: make sure tag matches, or error! Note that it's legit and normal\n\t\t// to call Exclusive twice with the same tag name.\n\t\treturn true\n\t}\n\t_, plugin, job := getTask(r.currentTask)\n\tisPlugin := plugin != nil\n\tisJob := job != nil\n\tw := getLockedWorker(r.tid)\n\tns := r.nameSpace\n\t// The intent here is that simple tasks can only call exclusive in the\n\t// context of a job pipeline, which is the only case where r.nameSpace\n\t// is set.\n\tif !isPlugin && !isJob && queueTask && len(r.nameSpace) == 0 {\n\t\tr.Log(robot.Error, \"Exclusive called by job or task with queueing outside of job pipeline\")\n\t\treturn false\n\t}\n\tif len(ns) == 0 {\n\t\tw.Unlock()\n\t\tns = w.getNameSpace(r.currentTask)\n\t\tw.Lock()\n\t}\n\tdefer w.Unlock()\n\tif len(tag) > 0 {\n\t\ttag = \":\" + tag\n\t}\n\ttag = ns + tag\n\tw.exclusiveTag = tag\n\trunQueues.Lock()\n\t_, exists := runQueues.m[tag]\n\tif !exists {\n\t\t// Take the lock\n\t\tLog(robot.Debug, \"Exclusive lock '%s' immediately acquired in pipeline '%s', bot #%d\", tag, w.pipeName, w.id)\n\t\trunQueues.m[tag] = []chan struct{}{}\n\t\tw.exclusive = true\n\t\tsuccess = true\n\t\trunQueues.Unlock()\n\t\treturn\n\t}\n\trunQueues.Unlock()\n\t// Update state to indicate what to do after callTask()\n\tif queueTask {\n\t\tLog(robot.Debug, \"Worker #%d requesting queueing\", w.id)\n\t\tw.queueTask = true\n\t} else {\n\t\t// When a plugin requests Exclusive, it should handle false\n\t\tif plugin != nil {\n\t\t\tLog(robot.Debug, \"Worker #%d requesting abort, exclusive lock failed\", w.id)\n\t\t\tw.abortPipeline = true\n\t\t}\n\t}\n\treturn\n}",
"func (c *Controller) shouldSkipProcessingChange(change client.ChangeInfo, lastProjectSyncTime time.Time) bool {\n\trevision := change.Revisions[change.CurrentRevision]\n\tif revision.Created.After(lastProjectSyncTime) {\n\t\treturn false\n\t}\n\n\tfor _, message := range currentMessages(change, lastProjectSyncTime) {\n\t\tif c.messageContainsJobTriggeringCommand(message) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}",
"func Worker(mapf func(string, string) []KeyValue,\n\treducef func(string, []string) string) {\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tdelay := 0\n\tgo runMapTasks(mapf, delay, &wg)\n\twg.Add(1)\n\tgo runReduceTasks(reducef, delay, &wg)\n\n\twg.Wait()\n\t// fmt.Println(\"job completed\")\n}",
"func (whc *WebhookConfigController) reconcile(stopCh <-chan struct{}) {\n\tdefer whc.configWatcher.Close() // nolint: errcheck\n\n\t// Try to create the initial webhook configuration (if it doesn't\n\t// already exist). Setup a persistent monitor to reconcile the\n\t// configuration if the observed configuration doesn't match\n\t// the desired configuration.\n\tvar retryAfterSetup bool\n\tif err := whc.rebuildWebhookConfig(); err == nil {\n\t\tretryAfterSetup = whc.createOrUpdateWebhookConfig()\n\t}\n\twebhookChangedCh := whc.monitorWebhookChanges(stopCh)\n\n\t// use a timer to debounce file updates\n\tvar configTimerC <-chan time.Time\n\n\tif retryAfterSetup {\n\t\tconfigTimerC = time.After(retryUpdateAfterFailureTimeout)\n\t}\n\n\tvar retrying bool\n\tfor {\n\t\tselect {\n\t\tcase <-configTimerC:\n\t\t\tconfigTimerC = nil\n\n\t\t\t// rebuild the desired configuration and reconcile with the\n\t\t\t// existing configuration.\n\t\t\tif err := whc.rebuildWebhookConfig(); err == nil {\n\t\t\t\tif retry := whc.createOrUpdateWebhookConfig(); retry {\n\t\t\t\t\tconfigTimerC = time.After(retryUpdateAfterFailureTimeout)\n\t\t\t\t\tif !retrying {\n\t\t\t\t\t\tretrying = true\n\t\t\t\t\t\tlog.Infof(\"webhook create/update failed - retrying every %v until success\", retryUpdateAfterFailureTimeout)\n\t\t\t\t\t}\n\t\t\t\t} else if retrying {\n\t\t\t\t\tlog.Infof(\"Retried create/update succeeded\")\n\t\t\t\t\tretrying = false\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-webhookChangedCh:\n\t\t\tvar retry bool\n\t\t\tif whc.webhookParameters.EnableValidation {\n\t\t\t\t// reconcile the desired configuration\n\t\t\t\tif retry = whc.createOrUpdateWebhookConfig(); retry && !retrying {\n\t\t\t\t\tlog.Infof(\"webhook create/update failed - retrying every %v until success\", retryUpdateAfterFailureTimeout)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif retry = whc.deleteWebhookConfig(); retry && !retrying {\n\t\t\t\t\tlog.Infof(\"webhook delete failed - retrying every %v until success\", retryUpdateAfterFailureTimeout)\n\t\t\t\t}\n\t\t\t}\n\t\t\tretrying = retry\n\t\t\tif retry {\n\t\t\t\ttime.AfterFunc(retryUpdateAfterFailureTimeout, func() { webhookChangedCh <- struct{}{} })\n\t\t\t}\n\t\tcase event, more := <-whc.configWatcher.Event:\n\t\t\tif more && (event.IsModify() || event.IsCreate()) && configTimerC == nil {\n\t\t\t\tconfigTimerC = time.After(watchDebounceDelay)\n\t\t\t}\n\t\tcase err := <-whc.configWatcher.Error:\n\t\t\tscope.Errorf(\"configWatcher error: %v\", err)\n\t\tcase <-stopCh:\n\t\t\treturn\n\t\t}\n\t}\n}",
"func (v *parameter) ExclusiveMaximum() float64 {\n\tif !v.HasExclusiveMaximum() {\n\t\treturn 0\n\t}\n\treturn *v.exclusiveMaximum\n}",
"func (t *T) May(name string, f interface{}) bool {\n\tt.Helper()\n\treturn t.invokeLevel(requirement.May, name, f)\n}",
"func (jobstore *JobStore) controlledUserCheck(user string, delay int) bool {\n\tfor _, job := range jobstore.job {\n\t\tif user == job.scm.user {\n\t\t\t// Taking the current time for reference\n\t\t\tt := time.Now().UTC()\n\t\t\t// Computing the delay time for which the scheduling would be prevented\n\t\t\tdelayTime := t.Add(-time.Second * 20)\n\n\t\t\t// calculate the diff\n\t\t\tdiffTime := delayTime.Sub(job.time).Seconds()\n\t\t\tif diffTime < 20 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}",
"func (r *EventTrackerPolicyReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\t_ = log.FromContext(ctx)\n\n\tvar mutex = &sync.Mutex{}\n\tmutex.Lock()\n\n\tvar etp eventtrackerv1.EventTrackerPolicy\n\terr := r.Client.Get(context.Background(), req.NamespacedName, &etp)\n\tif errors.IsNotFound(err) {\n\t\tlogrus.Print(req.NamespacedName, \" not found\")\n\t\treturn ctrl.Result{}, nil\n\t} else if err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\tfor index, status := range etp.Statuses {\n\t\tif status.Result == utils.ConditionPassed && strings.ToLower(status.IsTriggered) == \"false\" {\n\t\t\tlogrus.Print(\"ResourceName: \" + status.ResourceName + \", WorkflowID: \" + status.WorkflowID)\n\t\t\tresponse, err := utils.SendRequest(status.WorkflowID)\n\t\t\tif err != nil {\n\t\t\t\treturn ctrl.Result{}, err\n\t\t\t}\n\n\t\t\tlogrus.Print(response)\n\n\t\t\tvar res apiResponse\n\t\t\terr = json.Unmarshal([]byte(response), &res)\n\t\t\tif err != nil {\n\t\t\t\treturn ctrl.Result{}, err\n\t\t\t}\n\n\t\t\tif res.Data.GitopsNotifer == \"Gitops Disabled\" {\n\t\t\t\tetp.Statuses[index].IsTriggered = \"false\"\n\t\t\t} else {\n\t\t\t\tetp.Statuses[index].IsTriggered = \"true\"\n\t\t\t}\n\t\t}\n\t}\n\n\terr = r.Client.Update(context.Background(), &etp)\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\tdefer mutex.Unlock()\n\n\treturn ctrl.Result{}, nil\n}",
"func (action *scheduleRoutineAction) CanHandle(build *v1.Build) bool {\n\treturn build.Status.Phase == v1.BuildPhaseScheduling\n}",
"func checkEventually(eval evaluator) error {\n\tpollInterval := time.Second\n\ttimeoutInterval := time.Second * 30\n\n\ttimer := time.Now()\n\ttimeout := time.After(timeoutInterval)\n\n\t// loop till we reach timeout interval\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(pollInterval):\n\t\t\terr := eval()\n\t\t\tif err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase <-timeout:\n\t\t\t// eveluate one last time\n\t\t\terr := eval()\n\t\t\tif err != nil {\n\t\t\t\t_, file, line, _ := runtime.Caller(1)\n\n\t\t\t\tlog.Errorf(\"%s:%d: Evaluator timed out after %v. Err: %v\", filepath.Base(file), line, time.Since(timer), err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\t}\n}",
"func (oo *OnuDeviceEntry) setReconcilingFlows(value bool) {\n\too.mutexReconcilingFlowsFlag.Lock()\n\too.reconcilingFlows = value\n\too.mutexReconcilingFlowsFlag.Unlock()\n}",
"func (r *RollingPolicy) Reduce(f func(Iterator) float64) (val float64) {\n\tr.mu.RLock()\n\ttimespan := r.timespan()\n\tif count := r.size - timespan; count > 0 {\n\t\toffset := r.offset + timespan + 1\n\t\tif offset >= r.size {\n\t\t\toffset = offset - r.size\n\t\t}\n\t\tval = f(r.window.Iterator(offset, count))\n\t}\n\tr.mu.RUnlock()\n\treturn val\n}",
"func (r *RollingPolicy) Reduce(f func(Iterator) float64) (val float64) {\n\tr.mu.RLock()\n\ttimespan := r.timespan()\n\tif count := r.size - timespan; count > 0 {\n\t\toffset := r.offset + timespan + 1\n\t\tif offset >= r.size {\n\t\t\toffset = offset - r.size\n\t\t}\n\t\tval = f(r.window.Iterator(offset, count))\n\t}\n\tr.mu.RUnlock()\n\treturn val\n}",
"func (p *sharedProcessor) shouldResync() bool {\n\tp.listenersLock.Lock()\n\tdefer p.listenersLock.Unlock()\n\n\tp.syncingListeners = []*processorListener{}\n\n\tresyncNeeded := false\n\tnow := p.clock.Now()\n\tfor _, listener := range p.listeners {\n\t\t// need to loop through all the listeners to see if they need to resync so we can prepare any\n\t\t// listeners that are going to be resyncing.\n\t\tif listener.shouldResync(now) {\n\t\t\tresyncNeeded = true\n\t\t\tp.syncingListeners = append(p.syncingListeners, listener)\n\t\t\tlistener.determineNextResync(now)\n\t\t}\n\t}\n\treturn resyncNeeded\n}",
"func Atomically(fn func(*Tx)) {\nretry:\n\t// run the transaction\n\ttx := &Tx{\n\t\treads: make(map[*Var]uint64),\n\t\twrites: make(map[*Var]interface{}),\n\t}\n\tif catchRetry(fn, tx) {\n\t\t// wait for one of the variables we read to change before retrying\n\t\ttx.wait()\n\t\tgoto retry\n\t}\n\t// verify the read log\n\tglobalLock.Lock()\n\tif !tx.verify() {\n\t\tglobalLock.Unlock()\n\t\tgoto retry\n\t}\n\t// commit the write log and broadcast that variables have changed\n\tif len(tx.writes) > 0 {\n\t\ttx.commit()\n\t\tglobalCond.Broadcast()\n\t}\n\tglobalLock.Unlock()\n}",
"func Worker(mapf func(string, string) []KeyValue,\n\treducef func(string, []string) string) {\n\n\trand.Seed(time.Now().UnixNano())\n\tfor true {\n\t\tmore := TryGetJob(mapf, reducef)\n\t\tif !more {\n\t\t\tbreak\n\t\t} else {\n\t\t\t//time.Sleep(time.Second)\n\t\t}\n\t}\n\n}",
"func (setting *DDLStrategySetting) IsAllowConcurrent() bool {\n\treturn setting.hasFlag(allowConcurrentFlag)\n}",
"func (p *OnuTcontProfile) CanSetMax() bool {\r\n\treturn p.TcontType == 5 || p.TcontType == 4 || p.TcontType == 3\r\n}",
"func Worker(mapf func(string, string) []KeyValue,\n\treducef func(string, []string) string) {\n\n\tfor {\n\t\tjob := askCoordinatorForJob()\n\t\tswitch typeAssertedJob := (*job).(type) {\n\t\t\tcase MapJob:\n\t\t\t\texecuteMapFunction(mapf, typeAssertedJob)\n\t\t\tcase ReduceJob:\n\t\t\t\texecuteReduceFunction(reducef, typeAssertedJob)\n\t\t\tdefault:\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t}\n\t}\n}",
"func (p *processorListener) shouldResync(now time.Time) bool {\n\tp.resyncLock.Lock()\n\tdefer p.resyncLock.Unlock()\n\n\tif p.resyncPeriod == 0 {\n\t\treturn false\n\t}\n\n\treturn now.After(p.nextResync) || now.Equal(p.nextResync)\n}",
"func TestPeriodicReconcilerRun(t *testing.T) {\n\tival := 5 * time.Hour\n\tfclock := clockwork.NewFakeClock()\n\tfes := &fakeEventStream{make(chan Event)}\n\tcalled := make(chan struct{})\n\trec := func() {\n\t\tgo func() {\n\t\t\tcalled <- struct{}{}\n\t\t}()\n\t}\n\tpr := &reconciler{\n\t\tival: ival,\n\t\trFunc: rec,\n\t\teStream: fes,\n\t\tclock: fclock,\n\t}\n\t// launch the PeriodicReconciler in the background\n\tprDone := make(chan struct{})\n\tstop := make(chan struct{})\n\tgo func() {\n\t\tpr.Run(stop)\n\t\tclose(prDone)\n\t}()\n\t// reconcile should have occurred once at start-up\n\tselect {\n\tcase <-called:\n\tcase <-time.After(time.Second):\n\t\tt.Fatalf(\"rFunc() not called at start-up as expected!\")\n\t}\n\t// no further reconciles yet expected\n\tselect {\n\tcase <-called:\n\t\tt.Fatalf(\"rFunc() called unexpectedly!\")\n\tdefault:\n\t}\n\t// now, send an event on the EventStream and ensure rFunc occurs\n\tfes.trigger()\n\tselect {\n\tcase <-called:\n\tcase <-time.After(time.Second):\n\t\tt.Fatalf(\"rFunc() not called after trigger!\")\n\t}\n\t// assert rFunc was only called once\n\tselect {\n\tcase <-called:\n\t\tt.Fatalf(\"rFunc() called unexpectedly!\")\n\tdefault:\n\t}\n\t// another event should work OK\n\tfes.trigger()\n\tselect {\n\tcase <-called:\n\tcase <-time.After(time.Second):\n\t\tt.Fatalf(\"rFunc() not called after trigger!\")\n\t}\n\t// again, assert rFunc was only called once\n\tselect {\n\tcase <-called:\n\t\tt.Fatalf(\"rFunc() called unexpectedly!\")\n\tdefault:\n\t}\n\t// now check that time changes have the expected effect\n\tfclock.Advance(2 * time.Hour)\n\tselect {\n\tcase <-called:\n\t\tt.Fatalf(\"rFunc() called unexpectedly!\")\n\tdefault:\n\t}\n\tfclock.Advance(3 * time.Hour)\n\tselect {\n\tcase <-called:\n\tcase <-time.After(time.Second):\n\t\tt.Fatalf(\"rFunc() not called after time event!\")\n\t}\n\n\t// stop the PeriodicReconciler\n\tclose(stop)\n\n\t// now, sending an event should do nothing\n\tfes.trigger()\n\tselect {\n\tcase <-called:\n\t\tt.Fatalf(\"rFunc() called unexpectedly!\")\n\tdefault:\n\t}\n\t// and nor should changes in time\n\tfclock.Advance(10 * time.Hour)\n\tselect {\n\tcase <-called:\n\t\tt.Fatalf(\"rFunc() called unexpectedly!\")\n\tdefault:\n\t}\n\t// and the PeriodicReconciler should have shut down\n\tselect {\n\tcase <-prDone:\n\tcase <-time.After(time.Second):\n\t\tt.Fatalf(\"PeriodicReconciler.Run did not return after stop signal!\")\n\t}\n}",
"func (m *Monitor) Configure(conf ConfigInterface) error {\n\tif m.configureOnceSync(conf); m.configErr == nil {\n\t\tm.readSendCloseAsync(conf)\n\t}\n\treturn m.configErr\n}"
] | [
"0.5413984",
"0.46630463",
"0.4448742",
"0.44076672",
"0.43434864",
"0.42755866",
"0.4248361",
"0.42376712",
"0.42334935",
"0.42306432",
"0.42261687",
"0.41939452",
"0.4186118",
"0.41249162",
"0.41090778",
"0.41057667",
"0.41016468",
"0.40720016",
"0.40647498",
"0.4054843",
"0.40535834",
"0.40459874",
"0.4024467",
"0.40040788",
"0.40019566",
"0.40015724",
"0.39979407",
"0.39882755",
"0.39784977",
"0.39716536",
"0.3966202",
"0.39647973",
"0.3939604",
"0.39375004",
"0.3926459",
"0.39260373",
"0.39234743",
"0.39220598",
"0.39182913",
"0.38919273",
"0.38846132",
"0.38835767",
"0.38783994",
"0.3872133",
"0.38642785",
"0.3855023",
"0.3854048",
"0.3852909",
"0.38467917",
"0.3844504",
"0.38426152",
"0.3842227",
"0.3838705",
"0.3837963",
"0.3837659",
"0.38354957",
"0.38299203",
"0.38263777",
"0.38195646",
"0.38187128",
"0.38172075",
"0.38133484",
"0.38083163",
"0.38040677",
"0.37990925",
"0.37971237",
"0.37929362",
"0.37862405",
"0.37805656",
"0.37801114",
"0.37789565",
"0.37768647",
"0.37766218",
"0.37753868",
"0.37710902",
"0.37696955",
"0.37679306",
"0.3760011",
"0.3758716",
"0.3756071",
"0.37545496",
"0.37474257",
"0.3745593",
"0.37437683",
"0.37353182",
"0.37336397",
"0.37323967",
"0.3729484",
"0.37293255",
"0.37237433",
"0.37237433",
"0.37222093",
"0.37172794",
"0.37167615",
"0.37098095",
"0.37095058",
"0.37068528",
"0.37032977",
"0.37015513",
"0.37013188"
] | 0.74861586 | 0 |
mayExecuteLazyReduce triggers a reduce procedure if delayed config is set or first 'config.Period' wasnt reached yet. | func (l *ListHT) mayExecuteLazyReduce(p, n uint64) error {
if l.config.Tick == Delayed {
err := l.ReduceLog(p, n)
if err != nil {
return err
}
} else if l.config.Tick == Interval && !l.firstReduceExists() {
// must reduce the entire structure, just the desired interval would
// be incoherent with the Interval config
err := l.ReduceLog(l.first, l.last)
if err != nil {
return err
}
}
return nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (l *ListHT) mayTriggerReduce() error {\n\tif l.config.Tick != Interval {\n\t\treturn nil\n\t}\n\tl.count++\n\tif l.count >= l.config.Period {\n\t\tl.count = 0\n\t\treturn l.ReduceLog(l.first, l.last)\n\t}\n\treturn nil\n}",
"func (ld *logData) firstReduceExists() bool {\n\tif ld.config.Inmem {\n\t\treturn ld.recentLog != nil\n\t}\n\n\t// disk config, found any state file\n\t// TODO: verify if the found file has a matching interval?\n\tif _, exists := os.Stat(ld.config.Fname); exists == nil {\n\t\treturn true\n\t}\n\treturn false\n}",
"func (c config) EvalConcurrency() int { return c.evalConcurrency }",
"func (rl *redisRateLimiter) loadDynamicConfig(ctx gocontext.Context, conn redis.Conn, name string, maxCalls *uint64, per *time.Duration) error {\n\tif rl.cacheExpiresAt != nil && rl.cacheExpiresAt.Before(time.Now()) {\n\t\trl.cachedMaxCalls = nil\n\t\trl.cachedDuration = nil\n\t}\n\n\t// load from cache\n\tif rl.cachedMaxCalls != nil || rl.cachedDuration != nil {\n\t\tif rl.cachedMaxCalls != nil {\n\t\t\t*maxCalls = *rl.cachedMaxCalls\n\t\t}\n\t\tif rl.cachedDuration != nil {\n\t\t\t*per = *rl.cachedDuration\n\t\t}\n\t\treturn nil\n\t}\n\n\t// load from redis\n\tkey := fmt.Sprintf(\"%s:%s:max_calls\", rl.prefix, name)\n\tdynMaxCalls, err := redis.Uint64(conn.Do(\"GET\", key))\n\tif err != nil && err != redis.ErrNil {\n\t\treturn err\n\t}\n\tif err != redis.ErrNil {\n\t\t*maxCalls = dynMaxCalls\n\t}\n\n\tkey = fmt.Sprintf(\"%s:%s:duration\", rl.prefix, name)\n\tdynDurationStr, err := redis.String(conn.Do(\"GET\", key))\n\tif err != nil && err != redis.ErrNil {\n\t\treturn err\n\t}\n\tif err != redis.ErrNil {\n\t\tdynDuration, err := time.ParseDuration(dynDurationStr)\n\t\tif err == nil {\n\t\t\t*per = dynDuration\n\t\t}\n\t}\n\n\texpires := time.Now().Add(time.Second * 10)\n\n\tlogger := context.LoggerFromContext(ctx).WithField(\"self\", \"ratelimit/redis\")\n\tlogger.WithFields(logrus.Fields{\n\t\t\"max_calls\": *maxCalls,\n\t\t\"duration\": *per,\n\t}).Info(\"refreshed dynamic config\")\n\n\trl.cachedMaxCalls = maxCalls\n\trl.cachedDuration = per\n\trl.cacheExpiresAt = &expires\n\n\treturn nil\n}",
"func recalcRecommit(minRecommit, prev time.Duration, target float64, inc bool) time.Duration {\n\tvar (\n\t\tprevF = float64(prev.Nanoseconds())\n\t\tnext float64\n\t)\n\tif inc {\n\t\tnext = prevF*(1-intervalAdjustRatio) + intervalAdjustRatio*(target+intervalAdjustBias)\n\t\tmax := float64(maxRecommitInterval.Nanoseconds())\n\t\tif next > max {\n\t\t\tnext = max\n\t\t}\n\t} else {\n\t\tnext = prevF*(1-intervalAdjustRatio) + intervalAdjustRatio*(target-intervalAdjustBias)\n\t\tmin := float64(minRecommit.Nanoseconds())\n\t\tif next < min {\n\t\t\tnext = min\n\t\t}\n\t}\n\treturn time.Duration(int64(next))\n}",
"func (cc CollectionCache) reduce() {\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.Println(\"Panic Recovered at dbServices.collectionCache.reduce(): \", r)\n\t\t\treturn\n\t\t}\n\t}()\n\n\tcount := collectionCacheCount.Get()\n\n\tif count >= collectionCacheMaxCount { //Clear to 50%\n\n\t\tcountDown := count\n\n\t\tcollectionCache.Range(func(key interface{}, value interface{}) bool {\n\n\t\t\tgo cc.removeByKey(key)\n\n\t\t\tif countDown == 0 {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tcountDown--\n\n\t\t\treturn true\n\t\t})\n\t} else {\n\n\t\tstaleTime := time.Now().Add(-1 * time.Hour)\n\n\t\tcollectionCache.Range(func(key interface{}, value interface{}) bool {\n\n\t\t\tcv, parsed := value.(*CacheValue)\n\t\t\tif parsed && cv.lastUpdate.Get().Before(staleTime) {\n\t\t\t\tgo cc.removeByKey(key)\n\t\t\t}\n\n\t\t\treturn true\n\t\t})\n\n\t}\n\n}",
"func (kv *ShardKV) tick() {\n DPrintf(\"Server %s called tick function! Current max_config_in_log is %d\", kv.id, kv.max_config_in_log)\n kv.mu.Lock()\n defer kv.mu.Unlock()\n\n new_config := kv.sm.Query(-1)\n kv.max_config_in_log = int(math.Max(float64(kv.max_config_in_log), float64(kv.curr_config.Num)))\n if new_config.Num > kv.max_config_in_log { // change this to kv.max_config_in_log\n DPrintf2(\"Server %s Configuration is old! Putting configs from %d to %d in log\", kv.id, kv.max_config_in_log +1, new_config.Num)\n for config_num := kv.max_config_in_log +1; config_num <= new_config.Num; config_num++{\n kv.max_config_in_log = config_num\n kv.startReconfiguration(kv.sm.Query(config_num))\n } \n }\n // DPrintf(\"Server %s ending tick function\", kv.id)\n}",
"func (c *Config) Eagerness() int {\n\tc.Mutex.RLock()\n\tdefer c.Mutex.RUnlock()\n\treturn c.Raw.Eagerness\n}",
"func (mdl *Model) Reduce(callback func(std.Value) bool) std.Value {\n\treturn nil\n}",
"func (p *procGen) doPrecomputaion(optIdx int, opt ir.Inst) bool {\n\tswitch opt.Type {\n\tcase ir.Add, ir.Sub, ir.Div, ir.Mult, ir.And, ir.Or, ir.Increment, ir.Decrement:\n\t\tif !p.valueKnown(opt.MutateOperand) {\n\t\t\treturn false\n\t\t}\n\t}\n\t// check if we would start doing precomputation again\n\tif opt.Type.InputOutput() && p.precompute[opt.Out()].precomputedOnce && !p.valueKnown(opt.Out()) {\n\t\treturn false\n\t}\n\tswitch opt.Type {\n\tcase ir.Assign:\n\t\tif !p.valueKnown(opt.Right()) {\n\t\t\tpanic(\"ice: input to assign not known at compile time\")\n\t\t}\n\t\tleft := opt.Left()\n\t\tright := opt.Right()\n\t\tp.precompute[left] = p.precompute[right]\n\tcase ir.Add:\n\t\tleft := opt.Left()\n\t\tright := opt.Right()\n\t\tprecomp := &p.precompute[left]\n\t\trightValue := p.getPrecomputedValue(right)\n\t\tswitch precomp.valueType {\n\t\tcase integer:\n\t\t\tprecomp.value += rightValue\n\t\tcase pointerRelativeToVar, pointerRelativeToStackBase:\n\t\t\tpointedToSize := p.typeTable[left].(typing.Pointer).ToWhat.Size()\n\t\t\tdelta := int64(pointedToSize) * rightValue\n\t\t\tif precomp.valueType == pointerRelativeToStackBase {\n\t\t\t\tprecomp.value += delta\n\t\t\t} else {\n\t\t\t\tp.relativePointers[precomp.value].offset += int(delta)\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(\"adding to an unsupported precomp value type \" + precomp.valueType.String())\n\t\t}\n\tcase ir.Sub:\n\t\tp.precompute[opt.Left()].value -= p.getPrecomputedValue(opt.Right())\n\tcase ir.Mult:\n\t\tp.precompute[opt.Left()].value *= p.getPrecomputedValue(opt.Right())\n\tcase ir.Div:\n\t\trightValue := p.getPrecomputedValue(opt.Right())\n\t\tif rightValue == 0 {\n\t\t\tpanic(parsing.ErrorFromNode(opt.GeneratedFrom, \"Divide by zero\"))\n\t\t}\n\t\tp.precompute[opt.Left()].value /= rightValue\n\tcase ir.Compare:\n\t\textra := opt.Extra.(ir.CompareExtra)\n\t\tif !(p.valueKnown(opt.ReadOperand) && p.valueKnown(extra.Right)) {\n\t\t\treturn false\n\t\t}\n\t\tp.precompute[extra.Out].valueType = integer\n\t\tp.precompute[extra.Out].value = p.evalCompare(&opt)\n\tcase ir.Increment:\n\t\tp.precompute[opt.Out()].value++\n\tcase ir.Decrement:\n\t\tp.precompute[opt.Out()].value--\n\tcase ir.Not:\n\t\tp.precompute[opt.Out()].valueType = integer\n\t\tif p.precompute[opt.In()].value == 0 {\n\t\t\tp.precompute[opt.Out()].value = 1\n\t\t} else {\n\t\t\tp.precompute[opt.Out()].value = 0\n\t\t}\n\tcase ir.And:\n\t\tp.precompute[opt.Left()].value &= p.getPrecomputedValue(opt.Right())\n\tcase ir.Or:\n\t\tp.precompute[opt.Left()].value |= p.getPrecomputedValue(opt.Right())\n\tcase ir.PeelStruct:\n\t\tin := opt.In()\n\t\tfieldName := opt.Extra.(string)\n\t\tswitch inType := p.typeTable[in].(type) {\n\t\tcase *typing.StructRecord:\n\t\t\t_, memberIsPointer := inType.Members[fieldName].Type.(typing.Pointer)\n\t\t\t// If it's a pointer we would need to do a load\n\t\t\tif memberIsPointer {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase typing.Pointer:\n\t\t\trecord := inType.ToWhat.(*typing.StructRecord)\n\t\t\t_, memberIsPointer := record.Members[fieldName].Type.(typing.Pointer)\n\t\t\t// If it's a pointer we would need to deference in. Can't do that at compile time.\n\t\t\tif memberIsPointer {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tfallthrough\n\tcase ir.StructMemberPtr:\n\t\t// as a special case, we can get here even if we don't know the value of in\n\t\tin := opt.In()\n\t\tout := opt.Out()\n\t\tswitch inType := p.typeTable[in].(type) {\n\t\tcase *typing.StructRecord:\n\t\t\tp.ensureStackOffsetValid(in)\n\t\t\tfieldName := opt.Extra.(string)\n\t\t\tmemberOffset := inType.Members[fieldName].Offset\n\t\t\tp.precompute[out].valueType = pointerRelativeToStackBase\n\t\t\tp.precompute[out].value = int64(-p.varStorage[in].rbpOffset + memberOffset)\n\t\t\tp.precompute[out].precomputedOnce = true\n\t\t\treturn true\n\t\tcase typing.String:\n\t\t\tfieldName := opt.Extra.(string)\n\t\t\toffset := 0\n\t\t\tif fieldName == \"data\" {\n\t\t\t\toffset = 8\n\t\t\t}\n\t\t\tp.precompute[out].valueType = pointerRelativeToVar\n\t\t\tp.precompute[out].value = p.addRelativePointer(in, offset)\n\t\t\tp.precompute[out].precomputedOnce = true\n\t\t\treturn true\n\t\tcase typing.Pointer:\n\t\t\trecord, pointerToStruct := inType.ToWhat.(*typing.StructRecord)\n\t\t\tif !pointerToStruct {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfieldName := opt.Extra.(string)\n\t\t\tmemberOffset := record.Members[fieldName].Offset\n\t\t\tprecomp := p.precompute[in]\n\t\t\tswitch precomp.valueType {\n\t\t\tcase pointerRelativeToVar:\n\t\t\t\trel := p.relativePointers[precomp.value]\n\t\t\t\tp.precompute[out].valueType = pointerRelativeToVar\n\t\t\t\tp.precompute[out].value = p.addRelativePointer(rel.baseVar, rel.offset+memberOffset)\n\t\t\t\tp.precompute[out].precomputedOnce = true\n\t\t\t\treturn true\n\t\t\tcase pointerRelativeToStackBase:\n\t\t\t\tp.precompute[out].valueType = pointerRelativeToStackBase\n\t\t\t\tp.precompute[out].value = precomp.value + int64(memberOffset)\n\t\t\t\tp.precompute[out].precomputedOnce = true\n\t\t\t\treturn true\n\t\t\tcase notKnownAtCompileTime:\n\t\t\t\tp.precompute[out].valueType = pointerRelativeToVar\n\t\t\t\tp.precompute[out].value = p.addRelativePointer(in, memberOffset)\n\t\t\t\tp.precompute[out].precomputedOnce = true\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}",
"func (kv *ShardKV) TryUpdateConfig () {\n\n kv.configMtx.Lock()\n curConfig := kv.config\n kv.configMtx.Unlock()\n\n newConfig := kv.mck.Query(curConfig.Num+1)\n if newConfig.Num == curConfig.Num+1 {\n if _, isLeader := kv.rf.GetState(); isLeader {\n recvFinished := false\n kv.configMtx.Lock()\n recvFinished = kv.shardToRecv.Empty() == true\n kv.configMtx.Unlock()\n\n if recvFinished {\n request := CfgChangeArgs{newConfig}\n kv.rf.Start(Op{Type: ReqCfgChange, ArgsCfgChange: request})\n }\n }\n }\n}",
"func (c *Job) canDo() {\n\tdiff := int64(time.Now().Sub(c.nextTime) / time.Millisecond /*1000000*/)\n\tif diff >= 0 {\n\t\tif c.unit == delay || c.timingMode == beforeExecuteTask {\n\t\t\tc.fiber.EnqueueWithTask(c.task)\n\t\t} else {\n\t\t\td := c.task.Run()\n\t\t\tc.nextTime = c.nextTime.Add(d)\n\t\t}\n\t\tswitch c.unit {\n\t\tcase delay:\n\t\t\treturn\n\t\tcase weeks:\n\t\t\tc.nextTime = c.nextTime.AddDate(0, 0, 7)\n\t\tcase days:\n\t\t\tc.nextTime = c.nextTime.AddDate(0, 0, int(c.interval))\n\t\tcase hours:\n\t\t\tc.nextTime = c.nextTime.Add(time.Duration(c.interval) * time.Hour)\n\t\tcase minutes:\n\t\t\tc.nextTime = c.nextTime.Add(time.Duration(c.interval) * time.Minute)\n\t\tcase seconds:\n\t\t\tc.nextTime = c.nextTime.Add(time.Duration(c.interval) * time.Second)\n\t\tcase milliseconds:\n\t\t\tc.nextTime = c.nextTime.Add(time.Duration(c.interval) * time.Millisecond)\n\t\t}\n\t}\n\n\tc.taskDisposer.Dispose()\n\tadjustTime := int64(c.nextTime.Sub(time.Now()) / time.Millisecond /*1000000*/)\n\tc.taskDisposer = c.fiber.Schedule(adjustTime, c.canDo)\n}",
"func (m *Master) initReduceTask() {\n\tm.Phase = Reduce\n\tfor i := 0; i < m.Reducenr; i++ {\n\t\ttask := Task{Type: Reduce, Idx: i}\n\t\tm.Undone[i] = task\n//\t\tlog.Printf(\"initReduceTask type:%d idx:%d\", task.Type, task.Idx)\n\t}\n}",
"func (ns *Namespace) LazyEnabled(clusterName string) bool {\n\tif len(ns.UserSidecar) > 0 {\n\t\treturn false\n\t}\n\n\treturn ns.Distribution[clusterName]\n}",
"func NoResyncPeriodFunc() time.Duration {\n\treturn 0\n}",
"func NoResyncPeriodFunc() time.Duration {\n\treturn 0\n}",
"func maybeCanAddDelayedCommand() bool {\n\treturn atomic.LoadUint32(&delayedCommandsFlushed) == 0\n}",
"func (c *config) ApplyWithoutParallel(ex *terraform.Executor) error {\n\tif err := c.terraformInitialize(ex); err != nil {\n\t\treturn fmt.Errorf(\"initializing Terraform configuration: %w\", err)\n\t}\n\n\treturn c.terraformSmartApply(ex, c.DNS, []string{terraform.WithoutParallelism})\n}",
"func (t *ResolvedPipelineRunTask) skipBecauseWhenExpressionsEvaluatedToFalse(facts *PipelineRunFacts) bool {\n\tif t.checkParentsDone(facts) {\n\t\tif !t.PipelineTask.WhenExpressions.AllowsExecution() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}",
"func (m *Map) SpeculativeReduce(\n\treduce func(map[interface{}]interface{}) (interface{}, bool),\n\tjoin func(x, y interface{}) (interface{}, bool),\n) (interface{}, bool) {\n\tvar recur func(splits []Split) (interface{}, bool)\n\trecur = func(splits []Split) (interface{}, bool) {\n\t\tif len(splits) < 2 {\n\t\t\t// NewMap and case 2 below ensure that len(splits) > 0\n\t\t\treturn splits[0].speculativeReduce(reduce)\n\t\t}\n\t\tvar left, right interface{}\n\t\tvar b0, b1 bool\n\t\tvar p interface{}\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(1)\n\t\tswitch len(splits) {\n\t\tcase 2:\n\t\t\tgo func() {\n\t\t\t\tdefer func() {\n\t\t\t\t\tp = internal.WrapPanic(recover())\n\t\t\t\t\twg.Done()\n\t\t\t\t}()\n\t\t\t\tright, b1 = splits[1].speculativeReduce(reduce)\n\t\t\t}()\n\t\t\tleft, b0 = splits[0].speculativeReduce(reduce)\n\t\tdefault:\n\t\t\thalf := len(splits) / 2\n\t\t\tgo func() {\n\t\t\t\tdefer func() {\n\t\t\t\t\tp = internal.WrapPanic(recover())\n\t\t\t\t\twg.Done()\n\t\t\t\t}()\n\t\t\t\tright, b1 = recur(splits[half:])\n\t\t\t}()\n\t\t\tleft, b0 = recur(splits[:half])\n\t\t}\n\t\tif b0 {\n\t\t\treturn left, true\n\t\t}\n\t\twg.Wait()\n\t\tif p != nil {\n\t\t\tpanic(p)\n\t\t}\n\t\tif b1 {\n\t\t\treturn right, true\n\t\t}\n\t\treturn join(left, right)\n\t}\n\treturn recur(m.splits)\n}",
"func (p *Partition) ProcConsumeResult(defHandler *flowctrl.RuleHandler, groupHandler *flowctrl.RuleHandler,\n\tfilterConsume bool, lastConsumed bool) int64 {\n\tdltTime := time.Now().UnixNano()/int64(time.Millisecond) - p.consumeData.time\n\tp.updateStrategyData(defHandler, groupHandler)\n\tp.lastConsumed = lastConsumed\n\tswitch p.consumeData.errCode {\n\tcase errs.RetSuccess, errs.RetErrNotFound:\n\t\tif p.consumeData.msgSize == 0 && p.consumeData.errCode != errs.RetSuccess {\n\t\t\tp.totalZeroCnt++\n\t\t} else {\n\t\t\tp.totalZeroCnt = 0\n\t\t}\n\t\tif p.totalZeroCnt > 0 {\n\t\t\tif groupHandler.GetMinZeroCnt() != math.MaxInt64 {\n\t\t\t\treturn groupHandler.GetCurFreqLimitTime(p.totalZeroCnt, p.consumeData.dltLimit) - dltTime\n\t\t\t} else {\n\t\t\t\treturn defHandler.GetCurFreqLimitTime(p.totalZeroCnt, p.consumeData.dltLimit) - dltTime\n\t\t\t}\n\t\t}\n\t\tif p.consumeData.escLimit {\n\t\t\treturn 0\n\t\t} else {\n\t\t\tif p.strategyData.curStageMsgSize >= p.flowCtrl.GetDataSizeLimit() ||\n\t\t\t\tp.strategyData.curSliceMsgSize >= p.strategyData.limitSliceMsgSize {\n\t\t\t\tif p.flowCtrl.GetFreqMsLimit() > p.consumeData.dltLimit {\n\t\t\t\t\treturn p.flowCtrl.GetFreqMsLimit() - dltTime\n\t\t\t\t}\n\t\t\t\treturn p.consumeData.dltLimit - dltTime\n\t\t\t}\n\t\t\tif p.consumeData.errCode == errs.RetSuccess {\n\t\t\t\tif filterConsume && p.freqCtrl.GetFreqMsLimit() >= 0 {\n\t\t\t\t\tif p.consumeData.requireSlow {\n\t\t\t\t\t\treturn p.freqCtrl.GetZeroCnt() - dltTime\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn p.freqCtrl.GetFreqMsLimit() - dltTime\n\t\t\t\t\t}\n\t\t\t\t} else if !filterConsume && p.freqCtrl.GetDataSizeLimit() >= 0 {\n\t\t\t\t\treturn p.freqCtrl.GetDataSizeLimit() - dltTime\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn p.consumeData.dltLimit - dltTime\n\t\t}\n\tdefault:\n\t\treturn p.consumeData.dltLimit - dltTime\n\t}\n}",
"func (th *TlfHistory) Recompute(loggedInUser string) (\n\twritersWhoNeedMore map[string]bool) {\n\tth.lock.Lock()\n\tdefer th.lock.Unlock()\n\t_, writersWhoNeedMore = th.recomputeLocked(loggedInUser)\n\treturn writersWhoNeedMore\n}",
"func (e *Eval) eval(ctx context.Context, f *Flow) (err error) {\n\t// Propagate errors immediately.\n\tfor _, dep := range f.Deps {\n\t\tif err := dep.Err; err != nil {\n\t\t\te.Mutate(f, err, Done)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// There is a little bit of concurrency trickery here: we must\n\t// modify Flow's state only after any modifications have been done,\n\t// in order to make sure we don't race with concurrent e.todos\n\t// (which may make subsequent Flows available for execution before\n\t// we have made the necessary modifications here). In effect,\n\t// f.State acts as a barrier: it is modified only by one routine\n\t// (the one invoking simplify), but may be read by many.\n\tbegin := time.Now()\n\tif f.Op != Val {\n\t\tdefer func() {\n\t\t\tif err != nil {\n\t\t\t\t// Don't print cancellation errors, since they are follow-on errors\n\t\t\t\t// from upstream ones that have already been reported.\n\t\t\t\t/*\n\t\t\t\t\tif !errors.Is(errors.E(errors.Canceled), err) {\n\t\t\t\t\t\te.Log.Errorf(\"eval %s runtime error: %v\", f.ExecString(false), err)\n\t\t\t\t\t}\n\t\t\t\t*/\n\t\t\t} else if f.State == Done && f.Op != K && f.Op != Kctx && f.Op != Coerce {\n\t\t\t\tf.Runtime = time.Since(begin)\n\t\t\t}\n\t\t}()\n\t}\n\n\t// TODO(swami): Remove this conditional panic.\n\t// Temporarily keeping this here to make sure nothing breaks.\n\tif f.Op.External() {\n\t\tpanic(fmt.Sprintf(\"unexpected external op: %s\", f))\n\t}\n\n\tswitch f.Op {\n\tcase Groupby:\n\t\tv := f.Deps[0].Value.(reflow.Fileset)\n\t\tgroups := map[string]reflow.Fileset{}\n\t\tfor path, file := range v.Map {\n\t\t\tidx := f.Re.FindStringSubmatch(path)\n\t\t\tif len(idx) != 2 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tv, ok := groups[idx[1]]\n\t\t\tif !ok {\n\t\t\t\tv = reflow.Fileset{Map: map[string]reflow.File{}}\n\t\t\t\tgroups[idx[1]] = v\n\t\t\t}\n\t\t\tv.Map[path] = file\n\t\t}\n\t\tkeys := make([]string, len(groups))\n\t\ti := 0\n\t\tfor k := range groups {\n\t\t\tkeys[i] = k\n\t\t\ti++\n\t\t}\n\t\tsort.Strings(keys)\n\t\tfs := reflow.Fileset{List: make([]reflow.Fileset, len(groups))}\n\t\tfor i, k := range keys {\n\t\t\tfs.List[i] = groups[k]\n\t\t}\n\t\te.Mutate(f, fs, Done)\n\tcase Map:\n\t\tv := f.Deps[0].Value.(reflow.Fileset)\n\t\tff := &Flow{\n\t\t\tOp: Merge,\n\t\t\tDeps: make([]*Flow, len(v.List)),\n\t\t}\n\t\tfor i := range v.List {\n\t\t\tff.Deps[i] = f.MapFunc(filesetFlow(v.List[i]))\n\t\t}\n\t\te.Mutate(f, Fork(ff), Init)\n\t\te.Mutate(f.Parent, Done)\n\tcase Collect:\n\t\tv := f.Deps[0].Value.(reflow.Fileset)\n\t\tfileset := map[string]reflow.File{}\n\t\tfor path, file := range v.Map {\n\t\t\tif !f.Re.MatchString(path) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdst := f.Re.ReplaceAllString(path, f.Repl)\n\t\t\tfileset[dst] = file\n\t\t}\n\t\te.Mutate(f, reflow.Fileset{Map: fileset}, Done)\n\tcase Merge:\n\t\tlist := make([]reflow.Fileset, len(f.Deps))\n\t\tfor i, dep := range f.Deps {\n\t\t\tlist[i] = dep.Value.(reflow.Fileset)\n\t\t}\n\t\te.Mutate(f, reflow.Fileset{List: list}, Done)\n\tcase Val:\n\t\te.Mutate(f, Done)\n\tcase Pullup:\n\t\tv := &reflow.Fileset{List: make([]reflow.Fileset, len(f.Deps))}\n\t\tfor i, dep := range f.Deps {\n\t\t\tv.List[i] = dep.Value.(reflow.Fileset)\n\t\t}\n\t\te.Mutate(f, v.Pullup(), Done)\n\tcase K:\n\t\tvs := make([]values.T, len(f.Deps))\n\t\tfor i, dep := range f.Deps {\n\t\t\tvs[i] = dep.Value\n\t\t}\n\n\t\tff := f.K(vs)\n\t\te.Mutate(f, Fork(ff), Init)\n\t\te.Mutate(f.Parent, Done)\n\tcase Kctx:\n\t\tvs := make([]values.T, len(f.Deps))\n\t\tfor i, dep := range f.Deps {\n\t\t\tvs[i] = dep.Value\n\t\t}\n\t\tff := f.Kctx(kCtx{ctx, e.Repository}, vs)\n\t\te.Mutate(f, Fork(ff), Init)\n\t\te.Mutate(f.Parent, Done)\n\tcase Coerce:\n\t\tif v, err := f.Coerce(f.Deps[0].Value); err != nil {\n\t\t\te.Mutate(f, err, Done)\n\t\t} else {\n\t\t\te.Mutate(f, Value{v}, Done)\n\t\t}\n\tcase Requirements:\n\t\te.Mutate(f, Value{f.Deps[0].Value}, Done)\n\tcase Data:\n\t\tif id, err := e.Repository.Put(ctx, bytes.NewReader(f.Data)); err != nil {\n\t\t\te.Mutate(f, err, Done)\n\t\t} else {\n\t\t\te.Mutate(f, reflow.Fileset{\n\t\t\t\tMap: map[string]reflow.File{\n\t\t\t\t\t\".\": {ID: id, Size: int64(len(f.Data))},\n\t\t\t\t},\n\t\t\t}, Done)\n\t\t}\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"bug %v\", f))\n\t}\n\n\tif !e.CacheMode.Writing() {\n\t\treturn nil\n\t}\n\t// We're currently pretty conservative in what we choose to cache:\n\t// we don't cache interns, nor error values. We should revisit this\n\t// in the future.\n\t// TODO(marius): it may be valuable to cache interns as well, since\n\t// they might be overfetched, and then wittled down later. It is\n\t// also extra protection for reproducibility, though ideally this will\n\t// be tackled by filesets.\n\te.cacheWriteAsync(ctx, f)\n\treturn nil\n}",
"func PREFETCHNTA(m operand.Op) { ctx.PREFETCHNTA(m) }",
"func (kv *ShardKV) waitForDecided(seq int) Op {\n\tto := 10 * time.Millisecond\n\tfor {\n\t\tstatus, v := kv.px.Status(seq)\n\t\tif status == paxos.Decided {\n\t\t\treturn v.(Op)\n\t\t}\n\t\ttime.Sleep(to)\n\t\tif to < 10*time.Second {\n\t\t\tto *= 2\n\t\t}\n\t}\n}",
"func isEligibleForExecution(sensor *v1alpha1.Sensor, logger *logrus.Logger) (bool, error) {\n\tif sensor.Spec.ErrorOnFailedRound && sensor.Status.TriggerCycleStatus == v1alpha1.TriggerCycleFailure {\n\t\treturn false, errors.Errorf(\"last trigger cycle was a failure and sensor policy is set to ErrorOnFailedRound, so won't process the triggers\")\n\t}\n\tif sensor.Spec.Circuit != \"\" && sensor.Spec.DependencyGroups != nil {\n\t\treturn dependencies.ResolveCircuit(sensor, logger)\n\t}\n\tif ok := sensor.AreAllNodesSuccess(v1alpha1.NodeTypeEventDependency); ok {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}",
"func (DummyStorage) NeedsThrottling() bool {\n\tpanic(\"MergeQuerier.NeedsThrottling() should never be called\")\n}",
"func (ct *ctrlerCtx) handleConfigurationSnapshotEventParallelWithNoResolver(evt *kvstore.WatchEvent) error {\n\tswitch tp := evt.Object.(type) {\n\tcase *cluster.ConfigurationSnapshot:\n\t\teobj := evt.Object.(*cluster.ConfigurationSnapshot)\n\t\tkind := \"ConfigurationSnapshot\"\n\n\t\tlog.Infof(\"Watcher: Got %s watch event(%s): {%+v}\", kind, evt.Type, eobj)\n\n\t\tct.Lock()\n\t\thandler, ok := ct.handlers[kind]\n\t\tct.Unlock()\n\t\tif !ok {\n\t\t\tct.logger.Fatalf(\"Cant find the handler for %s\", kind)\n\t\t}\n\t\tconfigurationsnapshotHandler := handler.(ConfigurationSnapshotHandler)\n\t\t// handle based on event type\n\t\tswitch evt.Type {\n\t\tcase kvstore.Created:\n\t\t\tfallthrough\n\t\tcase kvstore.Updated:\n\t\t\tworkFunc := func(ctx context.Context, ctrlCtx shardworkers.WorkObj) error {\n\t\t\t\tvar err error\n\t\t\t\tworkCtx := ctrlCtx.(*configurationsnapshotCtx)\n\t\t\t\teobj := workCtx.obj\n\t\t\t\tfobj, err := ct.getObject(kind, workCtx.GetKey())\n\t\t\t\tif err != nil {\n\t\t\t\t\tct.addObject(workCtx)\n\t\t\t\t\tct.stats.Counter(\"ConfigurationSnapshot_Created_Events\").Inc()\n\t\t\t\t\teobj.Lock()\n\t\t\t\t\terr = configurationsnapshotHandler.OnConfigurationSnapshotCreate(eobj)\n\t\t\t\t\teobj.Unlock()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tct.logger.Errorf(\"Error creating %s %+v. Err: %v\", kind, eobj.GetObjectMeta(), err)\n\t\t\t\t\t\tct.delObject(kind, workCtx.GetKey())\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tworkCtx = fobj.(*configurationsnapshotCtx)\n\t\t\t\t\tobj := workCtx.obj\n\t\t\t\t\tct.stats.Counter(\"ConfigurationSnapshot_Updated_Events\").Inc()\n\t\t\t\t\tobj.Lock()\n\t\t\t\t\tp := cluster.ConfigurationSnapshot{Spec: eobj.Spec,\n\t\t\t\t\t\tObjectMeta: eobj.ObjectMeta,\n\t\t\t\t\t\tTypeMeta: eobj.TypeMeta,\n\t\t\t\t\t\tStatus: eobj.Status}\n\n\t\t\t\t\terr = configurationsnapshotHandler.OnConfigurationSnapshotUpdate(obj, &p)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tct.logger.Errorf(\"Error creating %s %+v. Err: %v\", kind, obj.GetObjectMeta(), err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tworkCtx.obj.ConfigurationSnapshot = p\n\t\t\t\t\t}\n\t\t\t\t\tobj.Unlock()\n\t\t\t\t}\n\t\t\t\tworkCtx.SetWatchTs(evt.WatchTS)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tctrlCtx := &configurationsnapshotCtx{event: evt.Type, obj: &ConfigurationSnapshot{ConfigurationSnapshot: *eobj, ctrler: ct}}\n\t\t\tct.runFunction(\"ConfigurationSnapshot\", ctrlCtx, workFunc)\n\t\tcase kvstore.Deleted:\n\t\t\tworkFunc := func(ctx context.Context, ctrlCtx shardworkers.WorkObj) error {\n\t\t\t\tvar err error\n\t\t\t\tworkCtx := ctrlCtx.(*configurationsnapshotCtx)\n\t\t\t\teobj := workCtx.obj\n\t\t\t\tfobj, err := ct.findObject(kind, workCtx.GetKey())\n\t\t\t\tif err != nil {\n\t\t\t\t\tct.logger.Errorf(\"Object %s/%s not found durng delete. Err: %v\", kind, eobj.GetKey(), err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tobj := fobj.(*ConfigurationSnapshot)\n\t\t\t\tct.stats.Counter(\"ConfigurationSnapshot_Deleted_Events\").Inc()\n\t\t\t\tobj.Lock()\n\t\t\t\terr = configurationsnapshotHandler.OnConfigurationSnapshotDelete(obj)\n\t\t\t\tobj.Unlock()\n\t\t\t\tif err != nil {\n\t\t\t\t\tct.logger.Errorf(\"Error deleting %s: %+v. Err: %v\", kind, obj.GetObjectMeta(), err)\n\t\t\t\t}\n\t\t\t\tct.delObject(kind, workCtx.GetKey())\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tctrlCtx := &configurationsnapshotCtx{event: evt.Type, obj: &ConfigurationSnapshot{ConfigurationSnapshot: *eobj, ctrler: ct}}\n\t\t\tct.runFunction(\"ConfigurationSnapshot\", ctrlCtx, workFunc)\n\t\t}\n\tdefault:\n\t\tct.logger.Fatalf(\"API watcher Found object of invalid type: %v on ConfigurationSnapshot watch channel\", tp)\n\t}\n\n\treturn nil\n}",
"func (gp *GenginePool) UpdatePooledRulesIncremental(ruleStr string) error {\n\tgp.updateLock.Lock()\n\tdefer gp.updateLock.Unlock()\n\n\t//compile\n\tkci, e := getKc(ruleStr)\n\tif e != nil {\n\t\treturn e\n\t}\n\n\t//update main\n\tupdateIncremental(kci, gp.ruleBuilder)\n\n\t//update instance\n\tfor i := 0; i < int(gp.max); i++ {\n\t\tgp.rbSlice[i].Kc = gp.ruleBuilder.Kc\n\t}\n\n\tgp.clear = false\n\treturn nil\n}",
"func (l *Loader) EvaluateDependencies(c *ComponentNode) {\n\ttracer := l.tracer.Tracer(\"\")\n\n\tl.mut.RLock()\n\tdefer l.mut.RUnlock()\n\n\tl.cm.controllerEvaluation.Set(1)\n\tdefer l.cm.controllerEvaluation.Set(0)\n\tstart := time.Now()\n\n\tspanCtx, span := tracer.Start(context.Background(), \"GraphEvaluatePartial\", trace.WithSpanKind(trace.SpanKindInternal))\n\tspan.SetAttributes(attribute.String(\"initiator\", c.NodeID()))\n\tdefer span.End()\n\n\tlogger := log.With(l.log, \"trace_id\", span.SpanContext().TraceID())\n\tlevel.Info(logger).Log(\"msg\", \"starting partial graph evaluation\")\n\tdefer func() {\n\t\tspan.SetStatus(codes.Ok, \"\")\n\n\t\tduration := time.Since(start)\n\t\tlevel.Info(logger).Log(\"msg\", \"finished partial graph evaluation\", \"duration\", duration)\n\t\tl.cm.componentEvaluationTime.Observe(duration.Seconds())\n\t}()\n\n\t// Make sure we're in-sync with the current exports of c.\n\tl.cache.CacheExports(c.ID(), c.Exports())\n\n\t_ = dag.WalkReverse(l.graph, []dag.Node{c}, func(n dag.Node) error {\n\t\tif n == c {\n\t\t\t// Skip over the starting component; the starting component passed to\n\t\t\t// EvaluateDependencies had its exports changed and none of its input\n\t\t\t// arguments will need re-evaluation.\n\t\t\treturn nil\n\t\t}\n\n\t\t_, span := tracer.Start(spanCtx, \"EvaluateNode\", trace.WithSpanKind(trace.SpanKindInternal))\n\t\tspan.SetAttributes(attribute.String(\"node_id\", n.NodeID()))\n\t\tdefer span.End()\n\n\t\tstart := time.Now()\n\t\tdefer func() {\n\t\t\tlevel.Info(logger).Log(\"msg\", \"finished node evaluation\", \"node_id\", n.NodeID(), \"duration\", time.Since(start))\n\t\t}()\n\n\t\tvar err error\n\n\t\tswitch n := n.(type) {\n\t\tcase BlockNode:\n\t\t\terr = l.evaluate(logger, n)\n\t\t\tif exp, ok := n.(*ExportConfigNode); ok {\n\t\t\t\tl.cache.CacheModuleExportValue(exp.Label(), exp.Value())\n\t\t\t}\n\t\t}\n\n\t\t// We only use the error for updating the span status; we don't return the\n\t\t// error because we want to evaluate as many nodes as we can.\n\t\tif err != nil {\n\t\t\tspan.SetStatus(codes.Error, err.Error())\n\t\t} else {\n\t\t\tspan.SetStatus(codes.Ok, \"\")\n\t\t}\n\t\treturn nil\n\t})\n\n\tif l.globals.OnExportsChange != nil && l.cache.ExportChangeIndex() != l.moduleExportIndex {\n\t\tl.globals.OnExportsChange(l.cache.CreateModuleExports())\n\t\tl.moduleExportIndex = l.cache.ExportChangeIndex()\n\t}\n}",
"func Do(retryFunc func() error, config *Config) error {\n\tvar err error\n\tconfig.Logger.Infof(\"Job attempt: %d\", 1)\n\terr = retryFunc()\n\tif err == nil {\n\t\treturn nil\n\t}\n\tfor n := uint(1); n < config.Attempts; n++ {\n\t\tdelayTime := config.Delay * (1 << (n - 1))\n\t\ttime.Sleep((time.Duration)(delayTime) * config.Units)\n\t\tconfig.Logger.Infof(\"Job attempt: %d\", n+1)\n\t\terr = retryFunc()\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn err\n}",
"func (s *SimpleTask) Throttled() bool { return false }",
"func (u *comboUtility) Evaluate() float64 {\n\t// If the utility was reset, reevaluate it\n\tif u.reset {\n\t\tu.output = math.Min(1, math.Max(0, u.combinator(u.srcA.Evaluate(), u.srcB.Evaluate())))\n\t\tu.reset = false\n\t}\n\t// Return the currently set value\n\treturn u.output\n}",
"func (kv *ShardKV) tick() {\n kv.mu.Lock()\n defer kv.mu.Unlock()\n if kv.cur_config.Num!=kv.next_config.Num{\n return\n }\n query_num := kv.cur_config.Num+1\n config := kv.sm.Query(query_num)\n if config.Num == query_num {\n\n if val,ok := kv.config_started[config.Num];ok&&val{\n return\n }else{\n kv.config_started[config.Num] = true\n /*\n if kv.unreliable{\n fmt.Print(\"GID:\")\n fmt.Println(kv.gid)\n fmt.Print(\"me: \")\n fmt.Println(kv.me)\n fmt.Print(\"Config num: \")\n fmt.Println(config.Num)\n fmt.Println()\n }*/\n kv.Config(config)\n return\n }\n\n }\n return\n}",
"func (e *engine) calculateDelay(entityItem *entityMapItem) {\n\tentityItem.delay = entityItem.delay + e.getFailureRetryDelay()\n\tif entityItem.delay > e.getMaxRetryDelay() {\n\t\tentityItem.delay = e.getMaxRetryDelay()\n\t}\n}",
"func (d *WindowsDataplane) apply() {\n\t// Unset the needs-sync flag, a rescheduling kick will reset it later if something failed\n\td.dataplaneNeedsSync = false\n\n\t// Allow each of the managers to complete any deferred work.\n\tscheduleRetry := false\n\tfor _, mgr := range d.allManagers {\n\t\terr := mgr.CompleteDeferredWork()\n\t\tif err != nil {\n\t\t\t// schedule a retry\n\t\t\tlog.WithError(err).Warning(\"CompleteDeferredWork returned an error - scheduling a retry\")\n\t\t\tscheduleRetry = true\n\t\t}\n\t}\n\n\t// Set up any needed rescheduling kick.\n\tif d.reschedC != nil {\n\t\t// We have an active rescheduling timer, stop it so we can restart it with a\n\t\t// different timeout below if it is still needed.\n\t\tif !d.reschedTimer.Stop() {\n\t\t\t// Timer had already popped, drain its channel.\n\t\t\t<-d.reschedC\n\t\t}\n\t\t// Nil out our copy of the channel to record that the timer is inactive.\n\t\td.reschedC = nil\n\t}\n\n\tif scheduleRetry {\n\t\tif d.reschedTimer == nil {\n\t\t\t// First time, create the timer.\n\t\t\td.reschedTimer = time.NewTimer(reschedDelay)\n\t\t} else {\n\t\t\t// Have an existing timer, reset it.\n\t\t\td.reschedTimer.Reset(reschedDelay)\n\t\t}\n\n\t\td.reschedC = d.reschedTimer.C\n\t}\n}",
"func (r *TokenBucketLimiter) tryPreFetch() bool {\n\tif r.needFetch() {\n\t\t// try to get from redis\n\t\t// single flight\n\t\t_, err, _ := r.g.Do(r.key, func() (interface{}, error) {\n\t\t\tx, err := r.redisClient.EvalSha(\n\t\t\t\tcontext.Background(),\n\t\t\t\tr.scriptSHA1,\n\t\t\t\t[]string{r.key},\n\t\t\t\tr.throughputPerSec,\n\t\t\t\tr.batchSize,\n\t\t\t\tr.maxCapacity,\n\t\t\t).Result()\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tr.Lock()\n\t\t\tr.N += x.(int64)\n\t\t\tr.Unlock()\n\t\t\treturn r.N, nil\n\t\t})\n\t\tif err != nil {\n\t\t\tslog.Error(\"get token from redis:%v\", err)\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}",
"func PREFETCHT1(m operand.Op) { ctx.PREFETCHT1(m) }",
"func checkEventually(eval evaluator) error {\n\tpollInterval := time.Second\n\ttimeoutInterval := time.Second * 30\n\n\ttimer := time.Now()\n\ttimeout := time.After(timeoutInterval)\n\n\t// loop till we reach timeout interval\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(pollInterval):\n\t\t\terr := eval()\n\t\t\tif err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase <-timeout:\n\t\t\t// eveluate one last time\n\t\t\terr := eval()\n\t\t\tif err != nil {\n\t\t\t\t_, file, line, _ := runtime.Caller(1)\n\n\t\t\t\tlog.Errorf(\"%s:%d: Evaluator timed out after %v. Err: %v\", filepath.Base(file), line, time.Since(timer), err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\t}\n}",
"func (cc CollectionCache) manage() {\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.Println(\"Panic Recovered at dbServices.collectionCache.manage(): \", r)\n\t\t\treturn\n\t\t}\n\t}()\n\n\tfor {\n\t\tgo cc.reduce()\n\t\ttime.Sleep(time.Minute * collectionCacheManagementTime)\n\t}\n\n}",
"func (c *Conn) EnableDefensive(b bool) (bool, error) {\n\tif C.SQLITE_VERSION_NUMBER < 3026000 {\n\t\t// SQLITE_DBCONFIG_DEFENSIVE was added in SQLite 3.26.0:\n\t\t// https://github.com/sqlite/sqlite/commit/a296cda016dfcf81674b04c041637fa0a4f426ac\n\t\treturn false, errors.New(\"SQLITE_DBCONFIG_DEFENSIVE isn't present in the called SQLite library\")\n\t}\n\treturn c.queryOrSetEnableDbConfig(C.SQLITE_DBCONFIG_DEFENSIVE, btocint(b))\n}",
"func PREFETCHT0(m operand.Op) { ctx.PREFETCHT0(m) }",
"func TestPartitionReader__Lazy(t *testing.T) {\n\tengine, _ := open(nil)\n\tpart, _ := initPartition(\"test.partition\", engine)\n\n\tb := make([]byte, 100)\n\n\t// Fill to differentiate it from zero-allocated slices.\n\tfor i := 0; i < len(b); i++ {\n\t\tb[i] = 1\n\t}\n\n\tpart.Write(1, b)\n\tpart.Write(2, b)\n\tpart.Write(3, b)\n\n\t// Clear local cache\n\tpart.segments = make(map[uint64]*segment)\n\n\tr := part.Reader(0, 0)\n\tbuf := make([]byte, 10)\n\n\t// Track iterations\n\ti := 0\n\n\tfor {\n\t\tn, err := r.Read(buf)\n\n\t\t// One segment should be loaded every 10 iterations for this\n\t\t// size buffer.\n\t\tif i%10 == 0 {\n\t\t\tassert.Equal(t, i/10+1, len(part.segments))\n\t\t}\n\n\t\t// Nothing expected for this iteration\n\t\tif i == 30 && (err != io.EOF || n != 0) {\n\t\t\tt.Fatal(\"expected an EOF with zero bytes\")\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\n\t\tif n != len(buf) {\n\t\t\tt.Fatalf(\"expected only 10 bytes to be read, got %d\", n)\n\t\t}\n\n\t\ti += 1\n\t}\n}",
"func shouldRetry(c context.Context, a *model.Attempt, stat dm.AbnormalFinish_Status) (retry bool, err error) {\n\tif !stat.CouldRetry() {\n\t\treturn\n\t}\n\tq := model.QuestFromID(a.ID.Quest)\n\n\tif err = ds.Get(ds.WithoutTransaction(c), q); err != nil {\n\t\treturn\n\t}\n\tvar cur, max uint32\n\tswitch stat {\n\tcase dm.AbnormalFinish_FAILED:\n\t\tcur, max = a.RetryState.Failed, q.Desc.Meta.Retry.Failed\n\t\ta.RetryState.Failed++\n\tcase dm.AbnormalFinish_CRASHED:\n\t\tcur, max = a.RetryState.Crashed, q.Desc.Meta.Retry.Crashed\n\t\ta.RetryState.Crashed++\n\tcase dm.AbnormalFinish_EXPIRED:\n\t\tcur, max = a.RetryState.Expired, q.Desc.Meta.Retry.Expired\n\t\ta.RetryState.Expired++\n\tcase dm.AbnormalFinish_TIMED_OUT:\n\t\tcur, max = a.RetryState.TimedOut, q.Desc.Meta.Retry.TimedOut\n\t\ta.RetryState.TimedOut++\n\tdefault:\n\t\tpanic(fmt.Errorf(\"do not know how to retry %q\", stat))\n\t}\n\tretry = cur < max\n\treturn\n}",
"func (r *ExplainDataFrameAnalytics) AllowLazyStart(allowlazystart bool) *ExplainDataFrameAnalytics {\n\tr.req.AllowLazyStart = &allowlazystart\n\n\treturn r\n}",
"func (t ResolvedPipelineRunTask) HasRemainingRetries() bool {\n\tvar retriesDone int\n\tif t.IsCustomTask() {\n\t\tif t.Run == nil {\n\t\t\treturn true\n\t\t}\n\t\tretriesDone = len(t.Run.Status.RetriesStatus)\n\t} else {\n\t\tif t.TaskRun == nil {\n\t\t\treturn true\n\t\t}\n\t\tretriesDone = len(t.TaskRun.Status.RetriesStatus)\n\t}\n\treturn retriesDone < t.PipelineTask.Retries\n}",
"func (ils *idleLimitStrategy) idleCountMinFulfilled() bool {\n\tmin := ils.config.Machine.GetIdleCountMin()\n\n\t// When IdleScaleFactor is in use, there is a risk that with no executed jobs\n\t// the desired number of Idle machines to maintain will also evaluate to 0.\n\t// This could cause in removing all Idle machines. In that case Runner would\n\t// stop asking for new jobs (with IdleCount > 0 Runner doesn't ask for jobs\n\t// if there is no Idle machines awaiting to be used). And without new jobs using\n\t// some machines, the IdleScaleFactor would be constantly evaluated to 0.\n\t// This would lock the Runner in a state where no job can't be started because\n\t// no machines are in Idle, and no machines are in Idle because no jobs are started.\n\t//\n\t// Therefore, in case when IdleScaleFactor is greater than 0 and IdleCountMin\n\t// was not defined or intentionally set to 0, it will be forced to be at least\n\t// 1. So that there is at least one Idle machine that can handle a job and allow\n\t// the IdleScaleFactor to bring more of them later.\n\tif ils.config.Machine.GetIdleScaleFactor() > 0 && min < 1 {\n\t\tmin = 1\n\t}\n\n\treturn ils.data.Available() >= min\n}",
"func Atomically(fn func(*Tx)) {\nretry:\n\t// run the transaction\n\ttx := &Tx{\n\t\treads: make(map[*Var]uint64),\n\t\twrites: make(map[*Var]interface{}),\n\t}\n\tif catchRetry(fn, tx) {\n\t\t// wait for one of the variables we read to change before retrying\n\t\ttx.wait()\n\t\tgoto retry\n\t}\n\t// verify the read log\n\tglobalLock.Lock()\n\tif !tx.verify() {\n\t\tglobalLock.Unlock()\n\t\tgoto retry\n\t}\n\t// commit the write log and broadcast that variables have changed\n\tif len(tx.writes) > 0 {\n\t\ttx.commit()\n\t\tglobalCond.Broadcast()\n\t}\n\tglobalLock.Unlock()\n}",
"func (f *Fuse) shouldRetry() bool {\n\tif f.retries > f.RetryThreshold {\n\t\tf.retries = 0\n\t\treturn true\n\t}\n\treturn false\n}",
"func (plugin *SchedProbPlugin) Compute(_, noOfNodes, noOfSched float64) interfaces.ComputeResult{\r\n\r\n p := calProb(noOfNodes,noOfSched)\r\n\r\n if (p > plugin.threshold){\r\n return interfaces.DoNotScale\r\n }else{\r\n return interfaces.ScaleDown\r\n }\r\n\r\n}",
"func (e *Eval) Do(ctx context.Context) error {\n\tdefer func() {\n\t\tif e.DotWriter != nil && e.flowgraph != nil {\n\t\t\tb, err := dot.Marshal(e.flowgraph, fmt.Sprintf(\"reflow flowgraph %v\", e.EvalConfig.RunID.ID()), \"\", \"\")\n\t\t\tif err != nil {\n\t\t\t\te.Log.Debugf(\"err dot marshal: %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t_, err = e.DotWriter.Write(b)\n\t\t\tif err != nil {\n\t\t\t\te.Log.Debugf(\"err writing dot file: %v\", err)\n\t\t\t}\n\t\t}\n\t}()\n\te.Log.Printf(\"evaluating with configuration: %s\", e.EvalConfig)\n\te.begin = time.Now()\n\tdefer func() {\n\t\te.totalTime = time.Since(e.begin)\n\t}()\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\te.ticker = time.NewTicker(10 * time.Second)\n\tdefer e.ticker.Stop()\n\n\troot := e.root\n\te.roots.Push(root)\n\te.printDeps(root, false)\n\n\tvar (\n\t\ttodo FlowVisitor\n\t\ttasks []*sched.Task // The set of tasks to be submitted after this iteration.\n\t\tflows []*Flow // The set of flows corresponding to the tasks to be submitted after this iteration.\n\t)\n\tfor root.State != Done {\n\t\tif root.Digest().IsZero() {\n\t\t\tpanic(\"invalid flow, zero digest: \" + root.DebugString())\n\t\t}\n\n\t\t// This is the meat of the evaluation: we gather Flows that are\n\t\t// ready (until steady state), and then execute this batch. At the\n\t\t// end of each iteration, we wait for one task to complete, and\n\t\t// gather any new Flows that have become ready.\n\n\t\tnroots := len(e.roots.q)\n\t\ttodo.Reset()\n\t\tvisited := make(flowOnce)\n\t\tfor e.roots.Walk() {\n\t\t\te.todo(e.roots.Flow, visited, &todo)\n\t\t}\n\t\te.roots.Reset()\n\t\te.Trace.Debugf(\"todo %d from %d roots\", len(todo.q), nroots)\n\n\t\t// LookupFlows consists of all the flows that need to be looked in the cache in this round of flow scheduling.\n\t\tvar lookupFlows []*Flow\n\tdequeue:\n\t\tfor todo.Walk() {\n\t\t\tf := todo.Flow\n\t\t\te.printDeps(f, true)\n\t\t\tif e.pending.Pending(f) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif f.Op == Exec {\n\t\t\t\tif f.Resources[\"mem\"] < minExecMemory {\n\t\t\t\t\tf.Resources[\"mem\"] = minExecMemory\n\t\t\t\t}\n\t\t\t\tif f.Resources[\"cpu\"] < minExecCPU {\n\t\t\t\t\tf.Resources[\"cpu\"] = minExecCPU\n\t\t\t\t}\n\t\t\t}\n\t\t\tif e.ImageMap != nil && f.OriginalImage == \"\" {\n\t\t\t\tf.OriginalImage = f.Image\n\t\t\t\tif img, ok := e.ImageMap[f.Image]; ok {\n\t\t\t\t\tf.Image = img\n\t\t\t\t}\n\t\t\t}\n\t\t\tif e.Snapshotter != nil && f.Op == Intern && f.State == Ready && !f.MustIntern {\n\t\t\t\t// In this case we don't display status, since we're not doing\n\t\t\t\t// any appreciable work here, and it's confusing to the user.\n\t\t\t\te.Mutate(f, Running, NoStatus)\n\t\t\t\te.pending.Add(f)\n\t\t\t\te.step(f, func(f *Flow) error {\n\t\t\t\t\tfs, err := e.Snapshotter.Snapshot(ctx, f.URL.String())\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\te.Log.Printf(\"must intern %q: resolve: %v\", f.URL, err)\n\t\t\t\t\t\te.Mutate(f, Ready, MustIntern)\n\t\t\t\t\t} else {\n\t\t\t\t\t\te.Mutate(f, fs, Done)\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t\tcontinue dequeue\n\t\t\t} else if f.Op.External() && f.State == Ready {\n\t\t\t\t// If we're using a scheduler, then we can skip transfer, and\n\t\t\t\t// submit directly to the scheduler.\n\t\t\t\te.Mutate(f, NeedSubmit)\n\t\t\t}\n\n\t\t\tswitch f.State {\n\t\t\tcase NeedLookup:\n\t\t\t\t// TODO(marius): we should perform batch lookups\n\t\t\t\t// as the underyling APIs (e.g., to DynamoDB) do not\n\t\t\t\t// bundle requests automatically.\n\t\t\t\te.Mutate(f, Lookup)\n\t\t\t\te.pending.Add(f)\n\t\t\t\tlookupFlows = append(lookupFlows, f)\n\t\t\tcase Ready:\n\t\t\t\tstate := Running\n\t\t\t\tif f.Op.External() {\n\t\t\t\t\tstate = Execing\n\t\t\t\t}\n\t\t\t\te.Mutate(f, state, SetReserved(f.Resources))\n\t\t\t\te.pending.Add(f)\n\t\t\t\te.step(f, func(f *Flow) error { return e.eval(ctx, f) })\n\t\t\tcase NeedSubmit:\n\t\t\t\tvar err *errors.Error\n\t\t\t\t// Propagate errors immediately. We have to do this manually\n\t\t\t\t// here since we're not going through the evaluator.\n\t\t\t\tfor _, dep := range f.Deps {\n\t\t\t\t\tif err = dep.Err; err != nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\te.pending.Add(f)\n\t\t\t\tif err != nil {\n\t\t\t\t\tgo func(err *errors.Error) {\n\t\t\t\t\t\te.Mutate(f, err, Done)\n\t\t\t\t\t\te.returnch <- f\n\t\t\t\t\t}(err)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\te.Mutate(f, Execing, SetReserved(f.Resources))\n\t\t\t\ttask := e.newTask(f)\n\t\t\t\ttasks = append(tasks, task)\n\t\t\t\tflows = append(flows, f)\n\t\t\t\te.step(f, func(f *Flow) error {\n\t\t\t\t\tif err := e.taskWait(ctx, f, task); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tfor retries := 0; retries < maxTaskRetries && task.Result.Err != nil; retries++ {\n\t\t\t\t\t\tvar (\n\t\t\t\t\t\t\tretry bool\n\t\t\t\t\t\t\tresources reflow.Resources\n\t\t\t\t\t\t\tretryType, msg string\n\t\t\t\t\t\t)\n\t\t\t\t\t\tswitch {\n\t\t\t\t\t\t// task.Result.Err should be non-nil here (due to for loop cond)\n\t\t\t\t\t\tcase !errors.Is(errors.OOM, task.Result.Err) && f.Reserved[\"mem\"] < f.Resources[\"mem\"]:\n\t\t\t\t\t\t\t// The Predictor can lower a task's memory requirements and cause a non-OOM memory error. This is\n\t\t\t\t\t\t\t// because the linux OOM killer does not catch all OOM errors. In order to prevent such an error from\n\t\t\t\t\t\t\t// causing a reflow program to fail, assume that if the Predictor lowers the memory of a task and\n\t\t\t\t\t\t\t// that task returns a non-OOM error, the task should be retried with its original resources.\n\t\t\t\t\t\t\tretry, retryType, resources = true, \"Predictor\", f.Resources\n\t\t\t\t\t\t\tmsg = fmt.Sprintf(\"non-OOM error, switch from predicted (%s) to default (%s) memory\", data.Size(f.Reserved[\"mem\"]), data.Size(f.Resources[\"mem\"]))\n\t\t\t\t\t\tcase errors.Is(errors.OOM, task.Result.Err):\n\t\t\t\t\t\t\t// Retry OOMs with adjusted resources.\n\t\t\t\t\t\t\tretry, retryType, resources = true, \"OOM\", oomAdjust(f.Resources, task.Config.Resources)\n\t\t\t\t\t\t\tmsg = fmt.Sprintf(\"%v of memory\", data.Size(resources[\"mem\"]))\n\t\t\t\t\t\tcase errors.Is(errors.Temporary, task.Result.Err):\n\t\t\t\t\t\t\t// Retry Temporary.\n\t\t\t\t\t\t\tretry, retryType, resources = true, \"Temporary\", f.Reserved\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif retry {\n\t\t\t\t\t\t\tmsg += fmt.Sprintf(\"(%v/%v) due to error: %s\", retries+1, maxTaskRetries, task.Result.Err)\n\t\t\t\t\t\t\tvar err error\n\t\t\t\t\t\t\tif task, err = e.retryTask(ctx, f, resources, retryType, msg); err != nil {\n\t\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// Write to the cache only if a task was successfully completed.\n\t\t\t\t\tif e.CacheMode.Writing() && task.Err == nil && task.Result.Err == nil {\n\t\t\t\t\t\te.cacheWriteAsync(ctx, f)\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tif len(lookupFlows) > 0 {\n\t\t\tgo e.batchLookup(ctx, lookupFlows...)\n\t\t}\n\t\te.Log.Debugf(\"pending: tasks %d (yet to submit), lookup %d, running %d\", len(tasks), e.pending.NState(Lookup), e.pending.NState(Running))\n\t\t// Delay task submission until we have gathered all potential tasks\n\t\t// that can be scheduled concurrently. This is represented by the\n\t\t// set of tasks that are currently either performing cache lookups\n\t\t// (Lookup) or else are undergoing local evaluation (Running). This\n\t\t// helps the scheduler better allocate underlying resources since\n\t\t// we always submit the largest available working set.\n\t\tif e.Scheduler != nil && len(tasks) > 0 && e.pending.NState(Lookup)+e.pending.NState(Running) == 0 {\n\t\t\te.reviseResources(ctx, tasks, flows)\n\t\t\te.Scheduler.Submit(tasks...)\n\t\t\ttasks = tasks[:0]\n\t\t\tflows = flows[:0]\n\t\t}\n\t\tif root.State == Done {\n\t\t\tbreak\n\t\t}\n\t\tif e.pending.N() == 0 && root.State != Done {\n\t\t\tvar states [Max][]*Flow\n\t\t\tfor v := e.root.Visitor(); v.Walk(); v.Visit() {\n\t\t\t\tstates[v.State] = append(states[v.State], v.Flow)\n\t\t\t}\n\t\t\tvar s [Max]string\n\t\t\tfor i := range states {\n\t\t\t\tn, tasks := accumulate(states[i])\n\t\t\t\ts[i] = fmt.Sprintf(\"%s:%d<%s>\", State(i).Name(), n, tasks)\n\t\t\t}\n\t\t\te.Log.Printf(\"pending %d\", e.pending.N())\n\t\t\te.Log.Printf(\"eval %s\", strings.Join(s[:], \" \"))\n\t\t\tpanic(\"scheduler is stuck\")\n\t\t}\n\t\tif err := e.wait(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// In the case of error, we return immediately. On success, we flush\n\t// all pending tasks so that all logs are properly displayed. We\n\t// also perform another collection, so that the executor may be\n\t// archived without data.\n\tif root.Err != nil {\n\t\treturn nil\n\t}\n\tfor e.pending.N() > 0 {\n\t\tif err := e.wait(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor _, f := range e.needLog {\n\t\te.LogFlow(ctx, f)\n\t}\n\te.needLog = nil\n\treturn nil\n}",
"func (this *DatastoreOperations) ScheduleFlushIfNeeded(state *DatastoreState, maxDelay int64) {\n\t// If a flush is already scheduled\n\tif state.FlushScheduler.FlushScheduled() {\n\t\t// Return immediately\n\t\treturn\n\t}\n\n\tflushIfNeeded := func() {\n\t\tstartTime := MonoUnixTimeMilli()\n\n\t\tdidFlush, err := state.FlushScheduler.EnsureFlush(state.File, time.Duration(maxDelay)*time.Millisecond)\n\t\tif err == nil {\n\t\t\tif !didFlush {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Log a success message\n\t\t\tthis.ParentServer.Logf(1, \"Flushed datastore '%s' %dms after written\", this.Name, MonoUnixTimeMilli()-startTime)\n\t\t} else { // Otherwise,\n\t\t\t// Log a failure message\n\t\t\tthis.ParentServer.Logf(1, \"Error flushing datastore '%s'. %s\", this.Name, err.Error())\n\t\t}\n\t}\n\n\t// If maximum delay is 0\n\tif maxDelay == 0 {\n\t\t// Flush synchronously\n\t\tflushIfNeeded()\n\t} else { // Otherwise\n\t\t// Flush asynchonously\n\t\t//\n\t\t// Increment the reference count to ensure the file isn't closed before or while the goroutine\n\t\t// executes\n\t\tstate.Increment()\n\n\t\tgo func() {\n\t\t\tflushIfNeeded()\n\n\t\t\t// Decrement the reference count\n\t\t\tstate.Decrement()\n\t\t}()\n\t}\n}",
"func (config *generator) Get() [][2]int64 {\n\tutil.Logf(\"Pod Config with Internal Computation (using multiples of %v) = %+v\\n\", multipleOf, config)\n\ttotalAds := computeTotalAds(*config)\n\ttimeForEachSlot := computeTimeForEachAdSlot(*config, totalAds)\n\n\tconfig.Slots = make([][2]int64, totalAds)\n\tconfig.slotsWithZeroTime = new(int64)\n\t*config.slotsWithZeroTime = totalAds\n\tutil.Logf(\"Plotted Ad Slots / Impressions of size = %v\\n\", len(config.Slots))\n\t// iterate over total time till it is < cfg.RequestedPodMaxDuration\n\ttime := int64(0)\n\tutil.Logf(\"Started allocating durations to each Ad Slot / Impression\\n\")\n\tfillZeroSlotsOnPriority := true\n\tnoOfZeroSlotsFilledByLastRun := int64(0)\n\t*config.totalSlotTime = 0\n\tfor time < config.requested.podMaxDuration {\n\t\tadjustedTime, slotsFull := config.addTime(timeForEachSlot, fillZeroSlotsOnPriority)\n\t\ttime += adjustedTime\n\t\ttimeForEachSlot = computeTimeLeastValue(config.requested.podMaxDuration-time, config.requested.slotMaxDuration-timeForEachSlot)\n\t\tif slotsFull {\n\t\t\tutil.Logf(\"All slots are full of their capacity. validating slots\\n\")\n\t\t\tbreak\n\t\t}\n\n\t\t// instruct for filling zero capacity slots on priority if\n\t\t// 1. shouldAdjustSlotWithZeroDuration returns true\n\t\t// 2. there are slots with 0 duration\n\t\t// 3. there is at least ont slot with zero duration filled by last iteration\n\t\tfillZeroSlotsOnPriority = false\n\t\tnoOfZeroSlotsFilledByLastRun = *config.slotsWithZeroTime - noOfZeroSlotsFilledByLastRun\n\t\tif config.shouldAdjustSlotWithZeroDuration() && *config.slotsWithZeroTime > 0 && noOfZeroSlotsFilledByLastRun > 0 {\n\t\t\tfillZeroSlotsOnPriority = true\n\t\t}\n\t}\n\tutil.Logf(\"Completed allocating durations to each Ad Slot / Impression\\n\")\n\n\t// validate slots\n\tconfig.validateSlots()\n\n\t// log free time if present to stats server\n\t// also check algoritm computed the no. of ads\n\tif config.requested.podMaxDuration-time > 0 && len(config.Slots) > 0 {\n\t\tconfig.freeTime = config.requested.podMaxDuration - time\n\t\tutil.Logf(\"TO STATS SERVER : Free Time not allocated %v sec\", config.freeTime)\n\t}\n\n\tutil.Logf(\"\\nTotal Impressions = %v, Total Allocated Time = %v sec (out of %v sec, Max Pod Duration)\\n%v\", len(config.Slots), *config.totalSlotTime, config.requested.podMaxDuration, config.Slots)\n\treturn config.Slots\n}",
"func (s *Service) tooQuickly() error {\n\tif s.rateLimit == 0 {\n\t\treturn nil\n\t}\n\tif s.starts < s.rateLimit {\n\t\treturn nil\n\t}\n\n\t// If we've restarted more than n times in the last period,\n\t// then rate limit us.\n\tidx := (s.starts - 1) % s.rateLimit\n\tend := s.startTimes[idx]\n\tif time.Now().Before(end.Add(s.ratePeriod)) {\n\n\t\t// Log it if not already done.\n\t\tif !s.rateLog {\n\t\t\ts.logf(\"Service %s restarting too quickly\", s.Name())\n\t\t}\n\t\t// And we uncoditionally mark this to note cool down.\n\t\ts.rateLog = true\n\t\treturn ErrRateLimited\n\t}\n\n\t// If we haven't restarted recently too quickly, we're done.\n\tif !s.rateLog {\n\t\t// Not in cool down mode.\n\t\treturn nil\n\t}\n\n\t// Check to see if cool down from prior rate limit is expired.\n\tidx = (s.starts - 2) % s.rateLimit\n\tend = s.startTimes[idx]\n\tif time.Now().Before(end.Add(s.ratePeriod)) {\n\t\treturn ErrRateLimited\n\t}\n\n\t// All cool downs expired.\n\ts.rateLog = false\n\treturn nil\n}",
"func ResourceApplyProximalGradientDescentUseLocking(value bool) ResourceApplyProximalGradientDescentAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"use_locking\"] = value\n\t}\n}",
"func (fc *appendFlowControl) reset(res *resolution, nowMillis int64) {\n\t*fc = appendFlowControl{\n\t\tmaxRate: res.journalSpec.MaxAppendRate,\n\t\tbalance: fc.balance, // Keep prior balance.\n\t\tlastMillis: fc.lastMillis, // Keep prior lastMillis.\n\n\t\tinvalidateCh: res.invalidateCh,\n\t\tchunkCh: make(chan appendChunk, 8),\n\t}\n\n\t// Constrain |maxRate| by the global flag setting.\n\tif MaxAppendRate != 0 && MaxAppendRate < fc.maxRate {\n\t\tfc.maxRate = MaxAppendRate\n\t}\n\t// Initialization case? Allow an initial burst of |maxRate| bytes\n\tif fc.lastMillis == 0 {\n\t\tfc.balance = fc.maxRate * int64(flowControlBurstFactor) / int64(time.Second)\n\t\tfc.lastMillis = nowMillis\n\t} else {\n\t\t_ = fc.onTick(nowMillis)\n\t}\n\t// Allow an initial delay of |MinAppendRate| bytes.\n\tfc.minRate = MinAppendRate\n\tfc.spent = MinAppendRate * int64(flowControlBurstFactor) / int64(time.Second)\n}",
"func (ms *MetricSet) Fetch(report mb.ReporterV2) {\n\tneedsStateUpdate := time.Since(ms.lastState) > ms.config.effectiveStatePeriod()\n\tif needsStateUpdate || ms.cache.IsEmpty() {\n\t\tms.log.Debugf(\"State update needed (needsStateUpdate=%v, cache.IsEmpty()=%v)\", needsStateUpdate, ms.cache.IsEmpty())\n\t\terr := ms.reportState(report)\n\t\tif err != nil {\n\t\t\tms.log.Error(err)\n\t\t\treport.Error(err)\n\t\t}\n\t\tms.log.Debugf(\"Next state update by %v\", ms.lastState.Add(ms.config.effectiveStatePeriod()))\n\t}\n\n\terr := ms.reportChanges(report)\n\tif err != nil {\n\t\tms.log.Error(err)\n\t\treport.Error(err)\n\t}\n}",
"func refineRetentionConfiguration(ctx context.Context, store *basestore.Store, repositoryID int, maxAgeForNonStaleBranches, maxAgeForNonStaleTags time.Duration) (_, _ time.Duration, err error) {\n\trows, err := store.Query(ctx, sqlf.Sprintf(retentionConfigurationQuery, repositoryID))\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\tdefer func() { err = basestore.CloseRows(rows, err) }()\n\n\tfor rows.Next() {\n\t\tvar v1, v2 int\n\t\tif err := rows.Scan(&v1, &v2); err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\n\t\tmaxAgeForNonStaleBranches = time.Second * time.Duration(v1)\n\t\tmaxAgeForNonStaleTags = time.Second * time.Duration(v2)\n\t}\n\n\treturn maxAgeForNonStaleBranches, maxAgeForNonStaleTags, nil\n}",
"func (m *Master) haveDone() bool {\n\tret := true\n\tt := time.Now().Unix()\n\tj := 0\n\tfor j < len(m.reduceTasks) {\n\t\tif m.reduceTasks[j].state == 1 {\n\t\t\tif t-m.reduceTasks[j].emittime >= TIMEOUT {\n\t\t\t\tm.reduceTasks[j].state = 0\n\t\t\t}\n\t\t}\n\t\tj++\n\t}\n\ti := 0\n\tfor _, reduceTask := range m.reduceTasks {\n\t\tif reduceTask.state == 0 {\n\t\t\tm.nextreducetask = i\n\t\t\tbreak\n\t\t}\n\t\ti++\n\t}\n\tfor _, reduceTask := range m.reduceTasks {\n\t\tif reduceTask.state != 2 {\n\t\t\tret = false\n\t\t\tbreak\n\t\t}\n\t}\n\tif ret {\n\t\tm.done = true\n\t}\n\treturn ret\n}",
"func (ct *ctrlerCtx) handleDSCProfileEventParallelWithNoResolver(evt *kvstore.WatchEvent) error {\n\tswitch tp := evt.Object.(type) {\n\tcase *cluster.DSCProfile:\n\t\teobj := evt.Object.(*cluster.DSCProfile)\n\t\tkind := \"DSCProfile\"\n\n\t\tlog.Infof(\"Watcher: Got %s watch event(%s): {%+v}\", kind, evt.Type, eobj)\n\n\t\tct.Lock()\n\t\thandler, ok := ct.handlers[kind]\n\t\tct.Unlock()\n\t\tif !ok {\n\t\t\tct.logger.Fatalf(\"Cant find the handler for %s\", kind)\n\t\t}\n\t\tdscprofileHandler := handler.(DSCProfileHandler)\n\t\t// handle based on event type\n\t\tswitch evt.Type {\n\t\tcase kvstore.Created:\n\t\t\tfallthrough\n\t\tcase kvstore.Updated:\n\t\t\tworkFunc := func(ctx context.Context, ctrlCtx shardworkers.WorkObj) error {\n\t\t\t\tvar err error\n\t\t\t\tworkCtx := ctrlCtx.(*dscprofileCtx)\n\t\t\t\teobj := workCtx.obj\n\t\t\t\tfobj, err := ct.getObject(kind, workCtx.GetKey())\n\t\t\t\tif err != nil {\n\t\t\t\t\tct.addObject(workCtx)\n\t\t\t\t\tct.stats.Counter(\"DSCProfile_Created_Events\").Inc()\n\t\t\t\t\teobj.Lock()\n\t\t\t\t\terr = dscprofileHandler.OnDSCProfileCreate(eobj)\n\t\t\t\t\teobj.Unlock()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tct.logger.Errorf(\"Error creating %s %+v. Err: %v\", kind, eobj.GetObjectMeta(), err)\n\t\t\t\t\t\tct.delObject(kind, workCtx.GetKey())\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tworkCtx = fobj.(*dscprofileCtx)\n\t\t\t\t\tobj := workCtx.obj\n\t\t\t\t\tct.stats.Counter(\"DSCProfile_Updated_Events\").Inc()\n\t\t\t\t\tobj.Lock()\n\t\t\t\t\tp := cluster.DSCProfile{Spec: eobj.Spec,\n\t\t\t\t\t\tObjectMeta: eobj.ObjectMeta,\n\t\t\t\t\t\tTypeMeta: eobj.TypeMeta,\n\t\t\t\t\t\tStatus: eobj.Status}\n\n\t\t\t\t\terr = dscprofileHandler.OnDSCProfileUpdate(obj, &p)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tct.logger.Errorf(\"Error creating %s %+v. Err: %v\", kind, obj.GetObjectMeta(), err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tworkCtx.obj.DSCProfile = p\n\t\t\t\t\t}\n\t\t\t\t\tobj.Unlock()\n\t\t\t\t}\n\t\t\t\tworkCtx.SetWatchTs(evt.WatchTS)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tctrlCtx := &dscprofileCtx{event: evt.Type, obj: &DSCProfile{DSCProfile: *eobj, ctrler: ct}}\n\t\t\tct.runFunction(\"DSCProfile\", ctrlCtx, workFunc)\n\t\tcase kvstore.Deleted:\n\t\t\tworkFunc := func(ctx context.Context, ctrlCtx shardworkers.WorkObj) error {\n\t\t\t\tvar err error\n\t\t\t\tworkCtx := ctrlCtx.(*dscprofileCtx)\n\t\t\t\teobj := workCtx.obj\n\t\t\t\tfobj, err := ct.findObject(kind, workCtx.GetKey())\n\t\t\t\tif err != nil {\n\t\t\t\t\tct.logger.Errorf(\"Object %s/%s not found durng delete. Err: %v\", kind, eobj.GetKey(), err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tobj := fobj.(*DSCProfile)\n\t\t\t\tct.stats.Counter(\"DSCProfile_Deleted_Events\").Inc()\n\t\t\t\tobj.Lock()\n\t\t\t\terr = dscprofileHandler.OnDSCProfileDelete(obj)\n\t\t\t\tobj.Unlock()\n\t\t\t\tif err != nil {\n\t\t\t\t\tct.logger.Errorf(\"Error deleting %s: %+v. Err: %v\", kind, obj.GetObjectMeta(), err)\n\t\t\t\t}\n\t\t\t\tct.delObject(kind, workCtx.GetKey())\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tctrlCtx := &dscprofileCtx{event: evt.Type, obj: &DSCProfile{DSCProfile: *eobj, ctrler: ct}}\n\t\t\tct.runFunction(\"DSCProfile\", ctrlCtx, workFunc)\n\t\t}\n\tdefault:\n\t\tct.logger.Fatalf(\"API watcher Found object of invalid type: %v on DSCProfile watch channel\", tp)\n\t}\n\n\treturn nil\n}",
"func (s *sink) maybeDrain() {\n\tif s.cl.cfg.manualFlushing && atomic.LoadInt32(&s.cl.producer.flushing) == 0 {\n\t\treturn\n\t}\n\tif s.drainState.maybeBegin() {\n\t\tgo s.drain()\n\t}\n}",
"func (b *Backend) DoSkip() bool {\n\tcounter := atomic.AddInt32(&b.skipCounter, -1)\n\tif counter < math.MaxInt32 {\n\t\t// Reset the counter\n\t\tif old := atomic.SwapInt32(&b.skipCounter, 0); old > 0 {\n\t\t\tatomic.CompareAndSwapInt32(&b.skipCounter, 0, old)\n\t\t}\n\t}\n\treturn counter >= 0\n}",
"func daemonSetProgressing(ds *appsv1.DaemonSet, allowHung bool) bool {\n\tstatus := ds.Status\n\n\t// Copy-pasted from status_manager: Determine if a DaemonSet is progressing\n\tprogressing := (status.UpdatedNumberScheduled < status.DesiredNumberScheduled ||\n\t\tstatus.NumberUnavailable > 0 ||\n\t\tstatus.NumberAvailable == 0 ||\n\t\tds.Generation > status.ObservedGeneration)\n\n\ts := \"progressing\"\n\tif !progressing {\n\t\ts = \"complete\"\n\t}\n\tklog.V(2).Infof(\"daemonset %s/%s rollout %s; %d/%d scheduled; %d unavailable; %d available; generation %d -> %d\",\n\t\tds.Namespace, ds.Name, s, status.UpdatedNumberScheduled, status.DesiredNumberScheduled,\n\t\tstatus.NumberUnavailable, status.NumberAvailable, ds.Generation, status.ObservedGeneration)\n\n\tif !progressing {\n\t\tklog.V(2).Infof(\"daemonset %s/%s rollout complete\", ds.Namespace, ds.Name)\n\t\treturn false\n\t}\n\n\t// If we're hung, but max(90% of nodes, 1) have been updated, then act as if not progressing\n\tif allowHung {\n\t\t_, hung := ds.GetAnnotations()[names.RolloutHungAnnotation]\n\t\tmaxBehind := int(math.Max(1, math.Floor(float64(status.DesiredNumberScheduled)*0.1)))\n\t\tnumBehind := int(status.DesiredNumberScheduled - status.UpdatedNumberScheduled)\n\t\tif hung && numBehind <= maxBehind {\n\t\t\tklog.Warningf(\"daemonset %s/%s rollout seems to have hung with %d/%d behind, force-continuing\", ds.Namespace, ds.Name, numBehind, status.DesiredNumberScheduled)\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}",
"func (p *NeuParallel) compute() bool {\n\tfor _, r := range p.rumap {\n\t\tif r.stopped {\n\t\t\treturn false\n\t\t}\n\t}\n\tp.step++\n\tp.nextround.Unlock()\n\tp.cond.Broadcast()\n\tp.wg.Wait() // ===================>>> TrainStep by NeuRunner(s)\n\tp.nextround.Lock()\n\tp.wg.Add(len(p.rumap))\n\treturn true\n}",
"func (o *FieldArrayPoolOptions) RefillHighWatermark() float64 { return o.refillHighWatermark }",
"func (pr *Progress) maybeDecrTo(rejected, last uint64) bool {\n\tif pr.State == ProgressStateReplicate {\n\t\t// the rejection must be stale if the progress has matched and \"rejected\"\n\t\t// is smaller than \"match\".\n\t\tif rejected <= pr.Match {\n\t\t\treturn false\n\t\t}\n\t\t// directly decrease next to match + 1\n\t\tpr.Next = pr.Match + 1\n\t\treturn true\n\t}\n\n\t// the rejection must be stale if \"rejected\" does not match next - 1\n\tif pr.Next-1 != rejected {\n\t\treturn false\n\t}\n\n\tif pr.Next = min(rejected, last+1); pr.Next < 1 {\n\t\tpr.Next = 1\n\t}\n\tpr.resume()\n\treturn true\n}",
"func (e *StrategyExecutor) Execute(prev, curr, succ *releaseInfo) (bool, []StrategyPatch, []ReleaseStrategyStateTransition) {\n\tisHead, hasTail := succ == nil, prev != nil\n\n\t// There is no really a point in making any changes until the successor\n\t// has completed it's transition, therefore we're hoilding off and aborting\n\t// the pipeline execution. An alternative to this approach could be to make\n\t// an autonomous move purely based on the picture of the world. But due to\n\t// the limited visilibility of what's happening to the successor (as it\n\t// might be following it's successor) it could be that a preliminary action\n\t// would create more noise than help really.\n\tif !isHead {\n\t\tif !releaseutil.ReleaseAchievedTargetStep(succ.release) {\n\t\t\treturn false, nil, nil\n\t\t}\n\t}\n\n\t// This pre-fill is super important, otherwise conditions will be sorted\n\t// in a wrong order and corresponding patches will override wrong\n\t// conditions.\n\tvar releaseStrategyConditions []shipper.ReleaseStrategyCondition\n\tif curr.release.Status.Strategy != nil {\n\t\treleaseStrategyConditions = curr.release.Status.Strategy.Conditions\n\t}\n\tcond := conditions.NewStrategyConditions(releaseStrategyConditions...)\n\n\t// the last step is slightly special from others: at this moment shipper\n\t// is no longer waiting for a command but marks a release as complete.\n\tisLastStep := int(e.step) == len(e.strategy.Steps)-1\n\t// The reason because isHead is not included in the extra set is mainly\n\t// because the pipeline is picking up 2 distinct tuples of releases\n\t// (curr+succ) and (prev+curr), therefore isHead is supposed to be\n\t// calculated by enforcers.\n\textra := Extra{\n\t\tInitiator: curr.release,\n\t\tIsLastStep: isLastStep,\n\t\tHasTail: hasTail,\n\t}\n\n\tpipeline := NewPipeline()\n\tif isHead {\n\t\tpipeline.Enqueue(genInstallationEnforcer(curr, nil))\n\t}\n\tpipeline.Enqueue(genCapacityEnforcer(curr, succ))\n\tpipeline.Enqueue(genTrafficEnforcer(curr, succ))\n\n\tif isHead {\n\t\tif hasTail {\n\t\t\tpipeline.Enqueue(genTrafficEnforcer(prev, curr))\n\t\t\tpipeline.Enqueue(genCapacityEnforcer(prev, curr))\n\t\t}\n\t\tpipeline.Enqueue(genReleaseStrategyStateEnforcer(curr, nil))\n\t}\n\n\treturn pipeline.Process(e.strategy, e.step, extra, cond)\n}",
"func (t *taskContext) calculateAndReportProgress(ctx context.Context) (err error) {\n\t// Manage contention on the ReclusteringRun row by only periodically\n\t// reporting progress.\n\tif clock.Now(ctx).After(t.nextReportDue) {\n\t\tprogress, err := calculateProgress(t.task, t.currentChunkID)\n\t\tif err != nil {\n\t\t\treturn errors.Annotate(err, \"calculate progress\").Err()\n\t\t}\n\n\t\terr = t.updateProgress(ctx, progress)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tt.nextReportDue = t.nextReportDue.Add(ProgressInterval)\n\t}\n\treturn nil\n}",
"func CumprodExclusive(value bool) CumprodAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"exclusive\"] = value\n\t}\n}",
"func (c Config) BestEffort() Config {\n\tcfg := c\n\tcfg.bestEffort = true\n\treturn cfg\n}",
"func (th *TlfHistory) Recompute() (writersWhoNeedMore map[string]bool) {\n\tth.lock.Lock()\n\tdefer th.lock.Unlock()\n\t_, writersWhoNeedMore = th.recomputeLocked()\n\treturn writersWhoNeedMore\n}",
"func (s *SketchLimiter) SketchState() LoadState {\n\tif s.current == LoadStateNone {\n\t\treturn LoadStateNone\n\t}\n\treturn s.current\n\twhile()\n\ts.m.RLock(), s.m.RUnlock()\n\tdefer s.m.RUnlock(), s.m.RLock()\n\treturn s.current, nil //s.state.State()\n}\n)\n\n// Collect the Sketch statistics and ufidelate the lineGraph state\nfunc (s *SketchLimiter) Collect(stats *fidelpb.SketchStats) {\n\ts.m.Lock()\n\tdefer s.m.Unlock()\n\n\tlog.Debug(\"collected statistics\", zap.Reflect(\"stats\", stats))\n\ts.state.Collect((*StatEntry)(stats))\n\n\tstate := s.state.State()\n\tratePeerAdd := s.calculateRate(Sketchlimit.AddPeer, state)\n\tratePeerRemove := s.calculateRate(Sketchlimit.RemovePeer, state)\n\n\tif ratePeerAdd > 0 || ratePeerRemove > 0 {\n\t\tif ratePeerAdd > 0 {\n\t\t\ts.opt.SetAllSketchsLimit(Sketchlimit.AddPeer, ratePeerAdd)\n\t\t\tlog.Info(\"change Sketch region add limit for lineGraph\", zap.Stringer(\"state\", state), zap.Float64(\"rate\", ratePeerAdd))\n\t\t}\n\t\tif ratePeerRemove > 0 {\n\t\t\ts.opt.SetAllSketchsLimit(Sketchlimit.RemovePeer, ratePeerRemove)\n\t\t\tlog.Info(\"change Sketch region remove limit for lineGraph\", zap.Stringer(\"state\", state), zap.Float64(\"rate\", ratePeerRemove))\n\t\t}\n\t\ts.current = state\n\t\tcollectLineGraphStateCurrent(state)\n\t}\n}",
"func (p *sharedProcessor) shouldResync() bool {\n\tp.listenersLock.Lock()\n\tdefer p.listenersLock.Unlock()\n\n\tp.syncingListeners = []*processorListener{}\n\n\tresyncNeeded := false\n\tnow := p.clock.Now()\n\tfor _, listener := range p.listeners {\n\t\t// need to loop through all the listeners to see if they need to resync so we can prepare any\n\t\t// listeners that are going to be resyncing.\n\t\tif listener.shouldResync(now) {\n\t\t\tresyncNeeded = true\n\t\t\tp.syncingListeners = append(p.syncingListeners, listener)\n\t\t\tlistener.determineNextResync(now)\n\t\t}\n\t}\n\treturn resyncNeeded\n}",
"func canScaleAfterDelay(logger logr.Logger, isBackoff bool, wasOutOfBounds autoscalingv2.HorizontalPodAutoscalerCondition, decisionDelay int32) bool {\n\t// feature is disabled\n\tif decisionDelay == 0 {\n\t\treturn !isBackoff\n\t}\n\n\tnow := metav1.Now()\n\tscaleDelay := decisionDelay - int32(now.Sub(wasOutOfBounds.LastTransitionTime.Time).Seconds())\n\tif scaleDelay > 0 || wasOutOfBounds.Status != corev1.ConditionTrue {\n\t\tlogger.Info(\"Will not scale: value has not been out of bounds for long enough\", \"time_left\", scaleDelay)\n\t\treturn false\n\t}\n\treturn !isBackoff\n}",
"func (*configureExecutor) PreCheck(ctx context.Context) error {\n\treturn nil\n}",
"func (s *State) flushIfNeeded(c context.Context, state *tsmon.State, settings *tsmonSettings) {\n\tnow := clock.Now(c)\n\tflushTime := now.Add(-time.Duration(settings.FlushIntervalSec) * time.Second)\n\n\t// Most of the time the flush is not needed and we can get away with\n\t// lightweight RLock.\n\ts.lock.RLock()\n\tskip := s.flushingNow || s.lastFlushed.After(flushTime)\n\ts.lock.RUnlock()\n\tif skip {\n\t\treturn\n\t}\n\n\t// Need to flush. Update flushingNow. Redo the check under write lock.\n\ts.lock.Lock()\n\tskip = s.flushingNow || s.lastFlushed.After(flushTime)\n\tif !skip {\n\t\ts.flushingNow = true\n\t}\n\ts.lock.Unlock()\n\tif skip {\n\t\treturn\n\t}\n\n\t// Report per-process statistic, like memory stats.\n\tcollectProcessMetrics(c, settings)\n\n\t// Unset 'flushingNow' no matter what (even on panics). Update 'lastFlushed'\n\t// only on successful flush. Unsuccessful flush thus will be retried ASAP.\n\tsuccess := false\n\tdefer func() {\n\t\ts.lock.Lock()\n\t\ts.flushingNow = false\n\t\tif success {\n\t\t\ts.lastFlushed = now\n\t\t}\n\t\ts.lock.Unlock()\n\t}()\n\n\t// The flush must be fast. Limit it with by some timeout.\n\tc, _ = clock.WithTimeout(c, flushTimeout)\n\tif err := s.updateInstanceEntityAndFlush(c, state, settings); err != nil {\n\t\tlogging.Errorf(c, \"Failed to flush tsmon metrics: %s\", err)\n\t} else {\n\t\tsuccess = true\n\t}\n}",
"func cacheConfiguration() {\n\tif err := CacheConfiguration(); err != nil {\n\t\tcommLogger.Errorf(\"Execution continues after CacheConfiguration() failure : %s\", err)\n\t}\n}",
"func (j *jobCache) PauseUntilAtLeast(t time.Time) {\n\tj.pauseFn() //cancel the context\n\tj.expires = t\n\tgo func() {\n\t\tdur := t.Sub(time.Now())\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-time.After(dur):\n\t\t\t\terr := j.refreshStore()\n\t\t\t\tif err == nil {\n\t\t\t\t\tctx, cf := context.WithCancel(context.Background())\n\t\t\t\t\tj.pauseFn = cf\n\t\t\t\t\tgo j.maintain(ctx)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase <-j.ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}",
"func (r *RollingPolicy) Reduce(f func(Iterator) float64) (val float64) {\n\tr.mu.RLock()\n\ttimespan := r.timespan()\n\tif count := r.size - timespan; count > 0 {\n\t\toffset := r.offset + timespan + 1\n\t\tif offset >= r.size {\n\t\t\toffset = offset - r.size\n\t\t}\n\t\tval = f(r.window.Iterator(offset, count))\n\t}\n\tr.mu.RUnlock()\n\treturn val\n}",
"func (r *RollingPolicy) Reduce(f func(Iterator) float64) (val float64) {\n\tr.mu.RLock()\n\ttimespan := r.timespan()\n\tif count := r.size - timespan; count > 0 {\n\t\toffset := r.offset + timespan + 1\n\t\tif offset >= r.size {\n\t\t\toffset = offset - r.size\n\t\t}\n\t\tval = f(r.window.Iterator(offset, count))\n\t}\n\tr.mu.RUnlock()\n\treturn val\n}",
"func (l *Lock) do(ctx context.Context, f DoFunc, d time.Duration) error {\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tif r != ErrNotHeld {\n\t\t\t\tl.Unlock(ctx)\n\t\t\t}\n\t\t}\n\t\tcancel()\n\t}()\n\n\t_, err := l.Lock(ctx, d)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tif r != ErrNotHeld {\n\t\t\t\t\tl.Unlock(ctx)\n\t\t\t\t}\n\t\t\t\tcancel()\n\t\t\t}\n\t\t}()\n\n\t\tt := time.NewTicker(d * 4 / 5) // 80% of d\n\t\tdefer t.Stop()\n\t\tfor range t.C {\n\t\t\tselect {\n\t\t\tdefault:\n\t\t\t\tif err := l.Extend(ctx, d); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = f(ctx)\n\tif ctx.Err() == context.Canceled {\n\t\treturn err\n\t}\n\n\tl.Unlock(ctx)\n\treturn err\n}",
"func (n *ParDo) postInvoke() error {\n\tif n.cache != nil {\n\t\tfor _, s := range n.cache.sideinput {\n\t\t\tif err := s.Reset(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}",
"func (m *Map) SpeculativeReduceInt(\n\treduce func(map[interface{}]interface{}) (int, bool),\n\tjoin func(x, y int) (int, bool),\n) (int, bool) {\n\tvar recur func(splits []Split) (int, bool)\n\trecur = func(splits []Split) (int, bool) {\n\t\tif len(splits) < 2 {\n\t\t\t// NewMap and case 2 below ensure that len(splits) > 0\n\t\t\treturn splits[0].speculativeReduceInt(reduce)\n\t\t}\n\t\tvar left, right int\n\t\tvar b0, b1 bool\n\t\tvar p interface{}\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(1)\n\t\tswitch len(splits) {\n\t\tcase 2:\n\t\t\tgo func() {\n\t\t\t\tdefer func() {\n\t\t\t\t\tp = internal.WrapPanic(recover())\n\t\t\t\t\twg.Done()\n\t\t\t\t}()\n\t\t\t\tright, b1 = splits[1].speculativeReduceInt(reduce)\n\t\t\t}()\n\t\t\tleft, b0 = splits[0].speculativeReduceInt(reduce)\n\t\tdefault:\n\t\t\thalf := len(splits) / 2\n\t\t\tgo func() {\n\t\t\t\tdefer func() {\n\t\t\t\t\tp = internal.WrapPanic(recover())\n\t\t\t\t\twg.Done()\n\t\t\t\t}()\n\t\t\t\tright, b1 = recur(splits[half:])\n\t\t\t}()\n\t\t\tleft, b0 = recur(splits[:half])\n\t\t}\n\t\tif b0 {\n\t\t\treturn left, true\n\t\t}\n\t\twg.Wait()\n\t\tif p != nil {\n\t\t\tpanic(p)\n\t\t}\n\t\tif b1 {\n\t\t\treturn right, true\n\t\t}\n\t\treturn join(left, right)\n\t}\n\treturn recur(m.splits)\n}",
"func (c *Configuration) Set() error {\n\tif c.SplitMax == 0 {\n\t\tcore.SplitMax = defaultSplitMax\n\t} else {\n\t\tcore.SplitMax = c.SplitMax\n\t}\n\tif c.PeekMax == 0 {\n\t\tcore.NextMax = defaultPeekMax\n\t} else {\n\t\tcore.NextMax = c.PeekMax\n\t}\n\tif c.StringMax == 0 {\n\t\tstrings.StringMax = defaultStringMax\n\t} else {\n\t\tstrings.StringMax = c.StringMax\n\t}\n\n\t// First, reenable all interpolators and transforms\n\tfor k := range disabledInterpolators {\n\t\tdisabledInterpolators[k].Register()\n\t}\n\tfor k := range disabledTransforms {\n\t\tdisabledTransforms[k].Register()\n\t}\n\n\t// Now, we set up the disabled and enabled transforms/interpolators\n\tpipescript.RegistryLock.Lock()\n\tdefer pipescript.RegistryLock.Unlock()\n\n\tinterpolator.RegistryLock.Lock()\n\tdefer interpolator.RegistryLock.Unlock()\n\n\t// Reset the disabled lists\n\tdisabledInterpolators = make([]interpolator.Interpolator, 0, len(c.DisableInterpolators))\n\tdisabledTransforms = make([]pipescript.Transform, 0, len(c.DisableTransforms))\n\n\t// Put the disabled transforms/interpolators on the disabled lists\n\tfor k := range c.DisableInterpolators {\n\t\ti, ok := interpolator.InterpolatorRegistry[c.DisableInterpolators[k]]\n\t\tif ok {\n\t\t\tdisabledInterpolators = append(disabledInterpolators, i)\n\t\t\tdelete(interpolator.InterpolatorRegistry, c.DisableInterpolators[k])\n\t\t}\n\t}\n\tfor k := range c.DisableTransforms {\n\t\ti, ok := pipescript.TransformRegistry[c.DisableTransforms[k]]\n\t\tif ok {\n\t\t\tdisabledTransforms = append(disabledTransforms, i)\n\t\t\tdelete(pipescript.TransformRegistry, c.DisableTransforms[k])\n\t\t}\n\t}\n\n\treturn nil\n}",
"func Maybe(fn func(s State)) {\n\t// check if simulation is enabled\n\tif atomic.LoadInt32(&enabled) == 0 {\n\t\t// execute in normal state\n\t\tfn(&noop{})\n\t\treturn\n\t}\n\n\t// execute in simulated state\n\tfn(defaultState)\n}",
"func (e *Eval) todo(f *Flow, visited flowOnce, v *FlowVisitor) {\n\tif f == nil || !visited.Visit(f) {\n\t\treturn\n\t}\n\tfor _, dep := range f.Deps {\n\t\tif dep.ExecDepIncorrectCacheKeyBug {\n\t\t\t// If the dependency was affected by the bug, then so is the parent.\n\t\t\tf.ExecDepIncorrectCacheKeyBug = true\n\t\t\tbreak\n\t\t}\n\t}\n\tswitch f.State {\n\tcase Init:\n\t\tf.Pending = make(map[*Flow]bool)\n\t\tfor _, dep := range f.Deps {\n\t\t\tif dep.State != Done {\n\t\t\t\tf.Pending[dep] = true\n\t\t\t\tdep.Dirty = append(dep.Dirty, f)\n\t\t\t}\n\t\t}\n\t\tswitch f.Op {\n\t\tcase Intern, Exec:\n\t\t\tif !e.BottomUp && e.CacheMode.Reading() && !e.dirty(f) {\n\t\t\t\tv.Push(f)\n\t\t\t\te.Mutate(f, NeedLookup)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\te.Mutate(f, TODO)\n\t\tfallthrough\n\tcase TODO:\n\t\tfor _, dep := range f.Deps {\n\t\t\te.todo(dep, visited, v)\n\t\t}\n\t\t// In the case of multiple dependencies, we short-circuit\n\t\t// computation on error. This is because we want to return early,\n\t\t// in case it can be dealt with (e.g., by restarting evaluation).\n\t\tfor _, dep := range f.Deps {\n\t\t\tif dep == nil {\n\t\t\t\tpanic(fmt.Sprintf(\"op %s n %d\", f.Op, len(f.Deps)))\n\t\t\t}\n\t\t\tif dep.State == Done && dep.Err != nil {\n\t\t\t\te.Mutate(f, Ready)\n\t\t\t\tv.Push(f)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tfor _, dep := range f.Deps {\n\t\t\tif dep.State != Done {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\t// The node is ready to run. This is done according to the evaluator's mode.\n\t\tswitch f.Op {\n\t\tcase Intern, Exec, Extern:\n\t\t\t// We're ready to run. If we're in bottom up mode, this means we're ready\n\t\t\t// for our cache lookup.\n\t\t\tif e.BottomUp && e.CacheMode.Reading() {\n\t\t\t\te.Mutate(f, NeedLookup)\n\t\t\t} else {\n\t\t\t\te.Mutate(f, Ready)\n\t\t\t}\n\t\tdefault:\n\t\t\t// Other nodes can be computed immediately,\n\t\t\t// and do not need access to the objects.\n\t\t\te.Mutate(f, Ready)\n\t\t}\n\t\tv.Push(f)\n\tdefault:\n\t\tv.Push(f)\n\t}\n}",
"func fetchLoopParams(ctx context.Context) {\n\t// Note: these are eventually controlled through /admin/portal/archivist.\n\tset := coordinator.GetSettings(ctx)\n\tloopM.Lock()\n\tdefer loopM.Unlock()\n\tif set.ArchivistBatchSize != 0 {\n\t\tloop.batchSize = set.ArchivistBatchSize\n\t}\n\tif set.ArchivistLeaseTime != 0 {\n\t\tloop.deadline = set.ArchivistLeaseTime\n\t}\n\tlogging.Debugf(ctx, \"loop settings: batchSize:%d, leastTime:%s\", loop.batchSize, loop.deadline)\n}",
"func WaitUntilConfigured() Option {\n\treturn func(o *config) error {\n\t\to.waitUntilConfigured = true\n\t\treturn nil\n\t}\n}",
"func (l *Loader) evaluate(logger log.Logger, bn BlockNode) error {\n\tectx := l.cache.BuildContext()\n\terr := bn.Evaluate(ectx)\n\n\tswitch c := bn.(type) {\n\tcase *ComponentNode:\n\t\t// Always update the cache both the arguments and exports, since both might\n\t\t// change when a component gets re-evaluated. We also want to cache the arguments and exports in case of an error\n\t\tl.cache.CacheArguments(c.ID(), c.Arguments())\n\t\tl.cache.CacheExports(c.ID(), c.Exports())\n\tcase *ArgumentConfigNode:\n\t\tif _, found := l.cache.moduleArguments[c.Label()]; !found {\n\t\t\tif c.Optional() {\n\t\t\t\tl.cache.CacheModuleArgument(c.Label(), c.Default())\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"missing required argument %q to module\", c.Label())\n\t\t\t}\n\t\t}\n\t}\n\n\tif err != nil {\n\t\tlevel.Error(logger).Log(\"msg\", \"failed to evaluate config\", \"node\", bn.NodeID(), \"err\", err)\n\t\treturn err\n\t}\n\treturn nil\n}",
"func (m *metricActiveDirectoryDsSecurityDescriptorPropagationsEventQueued) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}",
"func (mt *ModelType) shouldLoadProdModelRLocked() bool {\n\treturn mt.prod.model == nil || mt.prod.lastUpdate.Before(time.Now().Add(-outOfDateModelTimeout))\n}",
"func defaultOr(latestPoll *metav1.Time, pollingInterval time.Duration, creationTimestamp time.Time, now time.Time) time.Duration {\n\tif latestPoll.IsZero() {\n\t\tlatestPoll = &metav1.Time{Time: creationTimestamp}\n\t}\n\n\tremaining := latestPoll.Add(pollingInterval).Sub(now)\n\t// sync ahead of the default interval in the case where now + default sync is after the last sync plus the interval\n\tif remaining < queueinformer.DefaultResyncPeriod {\n\t\treturn remaining\n\t}\n\t// return the default sync period otherwise: the next sync cycle will check again\n\treturn queueinformer.DefaultResyncPeriod\n}",
"func (m *SecurityProfileManager) tryAutolearn(profile *SecurityProfile, event *model.Event) EventFilteringProfileState {\n\tvar nodeType activity_tree.NodeGenerationType\n\tvar profileState EventFilteringProfileState\n\n\tprofile.eventTypeStateLock.Lock()\n\tdefer profile.eventTypeStateLock.Unlock()\n\teventState, ok := profile.eventTypeState[event.GetEventType()]\n\tif !ok {\n\t\teventState = &EventTypeState{\n\t\t\tlastAnomalyNano: profile.loadedNano,\n\t\t\tstate: NoProfile,\n\t\t}\n\t\tprofile.eventTypeState[event.GetEventType()] = eventState\n\t} else if eventState.state == UnstableEventType {\n\t\t// If for the given event type we already are on UnstableEventType, just return\n\t\t// (once reached, this state is immutable)\n\t\tm.incrementEventFilteringStat(event.GetEventType(), UnstableEventType, NA)\n\t\treturn UnstableEventType\n\t}\n\n\t// check if we are at the beginning of a workload lifetime\n\tif event.ResolveEventTime().Sub(time.Unix(0, int64(event.ContainerContext.CreatedAt))) < m.config.RuntimeSecurity.AnomalyDetectionWorkloadWarmupPeriod {\n\t\tnodeType = activity_tree.WorkloadWarmup\n\t\tprofileState = WorkloadWarmup\n\t} else {\n\t\t// If for the given event type we already are on StableEventType (and outside of the warmup period), just return\n\t\tif eventState.state == StableEventType {\n\t\t\treturn StableEventType\n\t\t}\n\n\t\t// did we reached the stable state time limit ?\n\t\tif time.Duration(event.TimestampRaw-eventState.lastAnomalyNano) >= m.config.RuntimeSecurity.GetAnomalyDetectionMinimumStablePeriod(event.GetEventType()) {\n\t\t\teventState.state = StableEventType\n\t\t\t// call the activity dump manager to stop dumping workloads from the current profile selector\n\t\t\tif m.activityDumpManager != nil {\n\t\t\t\tm.activityDumpManager.StopDumpsWithSelector(profile.selector)\n\t\t\t}\n\t\t\treturn StableEventType\n\t\t}\n\n\t\t// did we reached the unstable time limit ?\n\t\tif time.Duration(event.TimestampRaw-profile.loadedNano) >= m.config.RuntimeSecurity.AnomalyDetectionUnstableProfileTimeThreshold {\n\t\t\teventState.state = UnstableEventType\n\t\t\treturn UnstableEventType\n\t\t}\n\n\t\tnodeType = activity_tree.ProfileDrift\n\t\tprofileState = AutoLearning\n\t}\n\n\t// check if the unstable size limit was reached\n\tif profile.ActivityTree.Stats.ApproximateSize() >= m.config.RuntimeSecurity.AnomalyDetectionUnstableProfileSizeThreshold {\n\t\t// for each event type we want to reach either the StableEventType or UnstableEventType states, even\n\t\t// if we already reach the AnomalyDetectionUnstableProfileSizeThreshold. That's why we have to keep\n\t\t// rearming the lastAnomalyNano timer based on if it's something new or not.\n\t\tfound, err := profile.ActivityTree.Contains(event, nodeType, m.resolvers)\n\t\tif err != nil {\n\t\t\tm.incrementEventFilteringStat(event.GetEventType(), NoProfile, NA)\n\t\t\treturn NoProfile\n\t\t} else if !found {\n\t\t\teventState.lastAnomalyNano = event.TimestampRaw\n\t\t} else if profileState == WorkloadWarmup {\n\t\t\t// if it's NOT something's new AND we are on container warmup period, just pretend\n\t\t\t// we are in learning/warmup phase (as we know, this event is already present on the profile)\n\t\t\treturn WorkloadWarmup\n\t\t}\n\t\treturn ProfileAtMaxSize\n\t}\n\n\t// here we are either in AutoLearning or WorkloadWarmup\n\t// try to insert the event in the profile\n\tnewEntry, err := profile.ActivityTree.Insert(event, nodeType, m.resolvers)\n\tif err != nil {\n\t\tm.incrementEventFilteringStat(event.GetEventType(), NoProfile, NA)\n\t\treturn NoProfile\n\t} else if newEntry {\n\t\teventState.lastAnomalyNano = event.TimestampRaw\n\t\tm.incrementEventFilteringStat(event.GetEventType(), profileState, NotInProfile)\n\t} else { // no newEntry\n\t\tm.incrementEventFilteringStat(event.GetEventType(), profileState, InProfile)\n\t}\n\treturn profileState\n}",
"func (b *Backend) ForcePromotionAfter() time.Duration {\n\tb.mu.RLock()\n\tret := b.mu.forcePromotionAfter\n\tb.mu.RUnlock()\n\treturn ret\n}",
"func (dm *depositManager) shouldProcess() bool {\n\treturn len(dm.pendingHeights) >= 1\n}",
"func (j *Job) Immediately() *Job {\n\tj.nextRun = time.Now().Add(-time.Minute)\n\treturn j\n}",
"func (m *Map) SpeculativeOr(predicate func(map[interface{}]interface{}) bool) bool {\n\tsplits := m.splits\n\treturn speculative.RangeOr(0, len(splits), 0, func(low, high int) bool {\n\t\tfor i := low; i < high; i++ {\n\t\t\tif ok := splits[i].predicate(predicate); ok {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t})\n}",
"func (bw *balancerWorker) allowBalance() bool {\n\tbw.RLock()\n\tbalanceCount := uint64(len(bw.balanceOperators))\n\tbw.RUnlock()\n\n\t// TODO: We should introduce more strategies to control\n\t// how many balance tasks at same time.\n\tif balanceCount >= bw.cfg.MaxBalanceCount {\n\t\treturn false\n\t}\n\n\treturn true\n}",
"func (f *Processor) Overloaded() bool {\n\treturn f.unorderedInserters.TasksCount() > f.cfg.MaxTasks()*3/4 ||\n\t\tf.orderedInserter.TasksCount() > f.cfg.MaxTasks()*3/4\n}",
"func DeferPartialQueryFailures() QueryOption {\n\treturn func(q *queryOptions) error {\n\t\tq.requestProperties.Options[DeferPartialQueryFailuresValue] = true\n\t\treturn nil\n\t}\n}"
] | [
"0.6423354",
"0.49406",
"0.4496993",
"0.4447092",
"0.43298352",
"0.43181613",
"0.43068022",
"0.4300131",
"0.4292118",
"0.4264112",
"0.4226407",
"0.42227906",
"0.42169753",
"0.4163023",
"0.4156544",
"0.4156544",
"0.41485885",
"0.4072473",
"0.40516493",
"0.40512535",
"0.4048316",
"0.40288234",
"0.40125006",
"0.3972757",
"0.3967048",
"0.39629406",
"0.39361736",
"0.39360464",
"0.39354888",
"0.39346868",
"0.39346042",
"0.3931613",
"0.39275777",
"0.39134517",
"0.39061487",
"0.38941857",
"0.38893393",
"0.38881156",
"0.3886753",
"0.38848123",
"0.38741902",
"0.38646254",
"0.38592327",
"0.38589698",
"0.38556114",
"0.38511786",
"0.38479742",
"0.38462254",
"0.38458166",
"0.3843643",
"0.38408333",
"0.38352627",
"0.3833865",
"0.3830703",
"0.3829318",
"0.38265997",
"0.38241833",
"0.38228723",
"0.3821705",
"0.38204348",
"0.38176936",
"0.38174695",
"0.3816851",
"0.38125843",
"0.3809091",
"0.38066044",
"0.3805458",
"0.3796462",
"0.37875098",
"0.37843883",
"0.37779477",
"0.37708288",
"0.3770197",
"0.376519",
"0.3757162",
"0.3755528",
"0.3753811",
"0.3752171",
"0.37519094",
"0.37519094",
"0.37484482",
"0.37462634",
"0.37443608",
"0.37382182",
"0.37372425",
"0.37347743",
"0.37297225",
"0.37280625",
"0.37279764",
"0.3725484",
"0.37234765",
"0.37211296",
"0.37193337",
"0.37192187",
"0.37185338",
"0.37124568",
"0.3712179",
"0.37088016",
"0.37085602",
"0.37078306"
] | 0.76615536 | 0 |
Authorize decides whether a given request should be allowed or denied. The evaluation logic follows these rules: By default, all requests are denied. An explicit allow overrides this default. An explicit deny overrides any allows. The order in which the policies are evaluated has no effect on the outcome of the evaluation. All policies are evaluated, and the result is always that the request is either allowed or denied. | func Authorize(policies []*policy.Policy, action string, object orn.ORN, _context map[string]string) error {
finalEffect := denyAction // By default deny
for _, policy := range policies {
for _, statement := range policy.Statements {
// TODO: @gearnode Add context support when policy object support condition
// The context should be evaluate at the last check to avoid
// long evaluation on not matching statement.
currentEffect := evalStatement(statement, object, action)
// Explicit deny (stop the evaluation)
// No allow can override an deny action.
if currentEffect == denyAction {
return ErrAccessDenied
}
// Explicit allow (modify the result effect and don't break the evaluation).
// Next statement can deny this statement allow.
if currentEffect == allowAction {
finalEffect = allowAction
}
}
}
if finalEffect == allowAction {
return nil
}
return ErrAccessDenied
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (a authorizer) Authorize(ctx context.Context, id bakery.Identity, ops []bakery.Op) (allowed []bool, caveats []checkers.Caveat, err error) {\n\tallowed = make([]bool, len(ops))\n\tfor i := range allowed {\n\t\tallowed[i] = true\n\t}\n\tcaveats = []checkers.Caveat{{\n\t\tLocation: a.thirdPartyLocation,\n\t\tCondition: \"access-allowed\",\n\t}}\n\treturn\n}",
"func (a Authorizers) Authorize(r *http.Request, config *EndpointConfig) (err error) {\n\tcheck := []string{}\n\tfor _, an := range config.Authorizers {\n\t\tcheck = append(check, an)\n\t}\n\tfor _, an := range config.Methods[r.Method].Authorizers {\n\t\tcheck = append(check, an)\n\t}\n\n\tfor _, an := range check {\n\t\tauthorizer := a[an]\n\t\tif err = authorizer.Authorize(r); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}",
"func (h *GrantCheck) HandleAuthorize(ar *osin.AuthorizeRequest, resp *osin.Response, w http.ResponseWriter) (bool, error) {\n\n\t// Requests must already be authorized before we will check grants\n\tif !ar.Authorized {\n\t\treturn false, nil\n\t}\n\n\t// Reset request to unauthorized until we verify the grant\n\tar.Authorized = false\n\n\tuser, ok := ar.UserData.(user.Info)\n\tif !ok || user == nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"the provided user data is not a user.Info object: %#v\", user))\n\t\tresp.SetError(\"server_error\", \"\")\n\t\treturn false, nil\n\t}\n\n\tclient, ok := ar.Client.GetUserData().(*oauthapi.OAuthClient)\n\tif !ok || client == nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"the provided client is not an *api.OAuthClient object: %#v\", client))\n\t\tresp.SetError(\"server_error\", \"\")\n\t\treturn false, nil\n\t}\n\n\t// Normalize the scope request, and ensure all tokens contain a scope\n\tscopes := scope.Split(ar.Scope)\n\tif len(scopes) == 0 {\n\t\tscopes = append(scopes, scopeauthorizer.UserFull)\n\t}\n\tar.Scope = scope.Join(scopes)\n\n\t// Validate the requested scopes\n\tif scopeErrors := validation.ValidateScopes(scopes, nil); len(scopeErrors) > 0 {\n\t\tresp.SetError(\"invalid_scope\", scopeErrors.ToAggregate().Error())\n\t\treturn false, nil\n\t}\n\n\tinvalidScopes := sets.NewString()\n\tfor _, scope := range scopes {\n\t\tif err := scopeauthorizer.ValidateScopeRestrictions(client, scope); err != nil {\n\t\t\tinvalidScopes.Insert(scope)\n\t\t}\n\t}\n\tif len(invalidScopes) > 0 {\n\t\tresp.SetError(\"access_denied\", fmt.Sprintf(\"scope denied: %s\", strings.Join(invalidScopes.List(), \" \")))\n\t\treturn false, nil\n\t}\n\n\tgrant := &api.Grant{\n\t\tClient: ar.Client,\n\t\tScope: ar.Scope,\n\t\tExpiration: int64(ar.Expiration),\n\t\tRedirectURI: ar.RedirectUri,\n\t}\n\n\t// Check if the user has already authorized this grant\n\tauthorized, err := h.check.HasAuthorizedClient(user, grant)\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\tresp.SetError(\"server_error\", \"\")\n\t\treturn false, nil\n\t}\n\tif authorized {\n\t\tar.Authorized = true\n\t\treturn false, nil\n\t}\n\n\t// React to an unauthorized grant\n\tauthorized, handled, err := h.handler.GrantNeeded(user, grant, w, ar.HttpRequest)\n\tif authorized {\n\t\tar.Authorized = true\n\t}\n\treturn handled, err\n}",
"func Authorize(obj string, act string, enforcer *casbin.Enforcer) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\t// Get current user/subject\n\t\tsub, existed := c.Get(\"userID\")\n\t\tif !existed {\n\t\t\tc.AbortWithStatusJSON(401, gin.H{\"msg\": \"User hasn't logged in yet\"})\n\t\t\treturn\n\t\t}\n\n\t\t// Load policy from Database\n\t\terr := enforcer.LoadPolicy()\n\t\tif err != nil {\n\t\t\tc.AbortWithStatusJSON(500, gin.H{\"msg\": \"Failed to load policy from DB\"})\n\t\t\treturn\n\t\t}\n\n\t\t// Casbin enforces policy\n\t\tok, err := enforcer.Enforce(fmt.Sprint(sub), obj, act)\n\n\t\tif err != nil {\n\t\t\tc.AbortWithStatusJSON(500, gin.H{\"msg\": \"Error occurred when authorizing user\"})\n\t\t\treturn\n\t\t}\n\n\t\tif !ok {\n\t\t\tc.AbortWithStatusJSON(403, gin.H{\"msg\": \"You are not authorized\"})\n\t\t\treturn\n\t\t}\n\t\tc.Next()\n\t}\n}",
"func (a Authorizer) Authorize(rw http.ResponseWriter, req *http.Request) error {\n\treturn nil\n}",
"func (a Authorizer) Authorize(rw http.ResponseWriter, req *http.Request) error {\n\treturn nil\n}",
"func Authorize(accessToken string) (bool, error) {\n\tctx := context.Background()\n\n\t// Define a simple policy.\n\tmodule := `\n\t\tpackage example\n\n\t\tdefault allow = false\n\n\t\tallow {\n\t\t\ttk := io.jwt.decode(input.token)\n\t\t\tgroups := tk[1][\"wlcg.groups\"][_]\n\t\t\tgroups == \"/escape/cms\"\n\t\t}\n\t`\n\n\t// Compile the module. The keys are used as identifiers in error messages.\n\tcompiler, err := ast.CompileModules(map[string]string{\n\t\t\"example.rego\": module,\n\t})\n\n\t// Create a new query that uses the compiled policy from above.\n\trego := rego.New(\n\t\trego.Query(\"data.example.allow\"),\n\t\trego.Compiler(compiler),\n\t\trego.Input(\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"token\": accessToken,\n\t\t\t},\n\t\t),\n\t)\n\t// Run evaluation.\n\trs, err := rego.Eval(ctx)\n\n\tif err != nil {\n\t\t// Handle error.\n\t\treturn false, err\n\t}\n\n\treturn rs[0].Expressions[0].Value.(bool), nil\n}",
"func (c *Admission) authorize(ctx context.Context, review *admission.AdmissionReview) error {\n\t// @check if the review is for something we can process\n\tobject, err := decodeObject(review.Request.Kind.Kind, review)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t\t\"id\": utils.GetTRX(ctx),\n\t\t\t\"name\": review.Request.Name,\n\t\t\t\"namespace\": review.Request.Namespace,\n\t\t}).Errorf(\"unable to decode object for review\")\n\n\t\treturn err\n\t}\n\n\t// @step: attempt to get the object authorized\n\tdenied, reason, err := c.authorizeResource(ctx, object, review.Request.Kind)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t\t\"id\": utils.GetTRX(ctx),\n\t\t\t\"name\": review.Request.Name,\n\t\t\t\"namespace\": review.Request.Namespace,\n\t\t}).Errorf(\"unable to handle admission review\")\n\n\t\treturn err\n\t}\n\n\t// @check if the object was rejected\n\tif denied {\n\t\tadmissionTotalMetric.WithLabelValues(actionDenied).Inc()\n\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": reason,\n\t\t\t\"group\": review.Request.Kind.Group,\n\t\t\t\"id\": utils.GetTRX(ctx),\n\t\t\t\"kind\": review.Request.Kind.Kind,\n\t\t\t\"name\": review.Request.Name,\n\t\t\t\"namespace\": review.Request.Namespace,\n\t\t\t\"uid\": review.Request.UserInfo.UID,\n\t\t\t\"user\": review.Request.UserInfo.Username,\n\t\t\t\"version\": review.Request.Kind.Version,\n\t\t}).Warn(\"authorization for object execution denied\")\n\n\t\treview.Response = &admission.AdmissionResponse{\n\t\t\tAllowed: false,\n\t\t\tResult: &metav1.Status{\n\t\t\t\tCode: http.StatusForbidden,\n\t\t\t\tMessage: reason,\n\t\t\t\tReason: metav1.StatusReasonForbidden,\n\t\t\t\tStatus: metav1.StatusFailure,\n\t\t\t},\n\t\t}\n\n\t\t// @step: log the denial is required\n\t\tgo c.events.Send(&api.Event{\n\t\t\tDetail: reason,\n\t\t\tObject: object,\n\t\t\tReview: review.Request,\n\t\t})\n\n\t\treturn nil\n\t}\n\n\tadmissionTotalMetric.WithLabelValues(actionAccepted).Inc()\n\n\treview.Response = &admission.AdmissionResponse{Allowed: true}\n\n\tlog.WithFields(log.Fields{\n\t\t\"group\": review.Request.Kind.Group,\n\t\t\"id\": utils.GetTRX(ctx),\n\t\t\"kind\": review.Request.Kind.Kind,\n\t\t\"name\": review.Request.Name,\n\t\t\"namespace\": review.Request.Namespace,\n\t\t\"uid\": review.Request.UserInfo.UID,\n\t\t\"user\": review.Request.UserInfo.Username,\n\t\t\"version\": review.Request.Kind.Version,\n\t}).Info(\"object has been authorized for execution\")\n\n\treturn nil\n}",
"func (s *Service) IsAccessAllowed(r *AccessRequest)(bool) {\n\t// TODO: Sort on importance of policy\n\tsort.SliceStable(s.Policies, func(i, j int) bool {return s.Policies[i].Id < s.Policies[j].Id})\n\n\tlog.Printf(\"Checking policy for user=%s, groups=%s, access=%s, location=%s\\n\",\n\t\tr.User, r.UserGroups, r.AccessType, r.Resource.Location)\n\n\tallowed := false\n\tresourceMatch := false\n\n\tfor _, p := range s.Policies {\n\t\t// match resource\n\t\tfor _, v := range p.Resources {\n\t\t\tfor _, bucketName := range v.Values {\n\t\t\t\tif v.IsRecursive {\n\t\t\t\t\tbucketName += \"*\"\n\t\t\t\t}\n\t\t\t\tif glob.Glob(bucketName, r.Resource.Location) {\n\t\t\t\t\tresourceMatch = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlog.Printf(\"Policy id=%d, name=%s, resource_match=%s\\n\", p.Id, p.Name, resourceMatch)\n\n\t\tif !resourceMatch {\n\t\t\tcontinue\n\t\t}\n\n\t\t// We have a resource match\n\n\t\tlog.Printf(\"Checking allow policy items=%d\\n\", len(p.PolicyItems))\n\t\tfor _, item := range p.PolicyItems {\n\t\t\t// user first\n\t\t\tallowed = hasAccess([]string{r.User}, item.Users, item.Accesses, r.AccessType, r.User == r.Resource.Owner)\n\n\t\t\t// groups\n\t\t\tif !allowed {\n\t\t\t\tallowed = hasAccess(r.UserGroups, item.Groups, item.Accesses, r.AccessType, false)\n\t\t\t}\n\n\t\t\t// conditions\n\t\t\tif allowed {\n\t\t\t\tlog.Printf(\"Checking allow policy conditions\\n\")\n\t\t\t\tfound := false\n\t\t\t\tfor _, condition := range item.Conditions {\n\t\t\t\t\tvar err error\n\t\t\t\t\terr, found = condition.isInCondition(r)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Printf(\"Error checking condition=%s err=%s\\n\", condition, err)\n\t\t\t\t\t}\n\t\t\t\t\tif found {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !found && len(item.Conditions) > 0 {\n\t\t\t\t\tlog.Printf(\"policyItem=%s conditions not met\\n\", item)\n\t\t\t\t\tallowed = false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// TODO: check exceptions\n\t\t}\n\n\t\tlog.Printf(\"Checking deny policy items=%d\\n\", len(p.DenyPolicyItems))\n\n\t\tfor _, item := range p.DenyPolicyItems {\n\t\t\t// allowed signals denial\n\t\t\tallowed = !hasAccess([]string{r.User}, item.Users, item.Accesses, r.AccessType, r.User == r.Resource.Owner)\n\n\t\t\t// groups\n\t\t\tif allowed {\n\t\t\t\tallowed = !hasAccess(r.UserGroups, item.Groups, item.Accesses, r.AccessType, false)\n\t\t\t}\n\n\t\t\t// conditions\n\t\t\tif !allowed {\n\t\t\t\tlog.Printf(\"Checking deny policy conditions\\n\")\n\t\t\t\tfound := false\n\t\t\t\tfor _, condition := range item.Conditions {\n\t\t\t\t\t_, found = condition.isInCondition(r)\n\t\t\t\t\tif found {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !found && len(item.Conditions) > 0 {\n\t\t\t\t\tallowed = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// TODO: check exceptions\n\t\t}\n\n\t\t// if we got here we had a resource match\n\t\tbreak\n\t}\n\n\treturn allowed\n}",
"func (context *Context) Allow(actType ActionType) bool {\n\tif actType == NetworkAccessFlag {\n\t\treturn !context.DenyNetworkAccess\n\t}\n\treturn false\n}",
"func Authorize(w http.ResponseWriter, r *http.Request, authorizer Authorizer) {\n\tauthReq, err := ParseAuthorizeRequest(r, authorizer.Decoder())\n\tif err != nil {\n\t\tAuthRequestError(w, r, authReq, err, authorizer.Encoder())\n\t\treturn\n\t}\n\tif authReq.RequestParam != \"\" && authorizer.RequestObjectSupported() {\n\t\tauthReq, err = ParseRequestObject(r.Context(), authReq, authorizer.Storage(), authorizer.Issuer())\n\t\tif err != nil {\n\t\t\tAuthRequestError(w, r, authReq, err, authorizer.Encoder())\n\t\t\treturn\n\t\t}\n\t}\n\tvalidation := ValidateAuthRequest\n\tif validater, ok := authorizer.(AuthorizeValidator); ok {\n\t\tvalidation = validater.ValidateAuthRequest\n\t}\n\tuserID, err := validation(r.Context(), authReq, authorizer.Storage(), authorizer.IDTokenHintVerifier())\n\tif err != nil {\n\t\tAuthRequestError(w, r, authReq, err, authorizer.Encoder())\n\t\treturn\n\t}\n\tif authReq.RequestParam != \"\" {\n\t\tAuthRequestError(w, r, authReq, oidc.ErrRequestNotSupported(), authorizer.Encoder())\n\t\treturn\n\t}\n\treq, err := authorizer.Storage().CreateAuthRequest(r.Context(), authReq, userID)\n\tif err != nil {\n\t\tAuthRequestError(w, r, authReq, oidc.DefaultToServerError(err, \"unable to save auth request\"), authorizer.Encoder())\n\t\treturn\n\t}\n\tclient, err := authorizer.Storage().GetClientByClientID(r.Context(), req.GetClientID())\n\tif err != nil {\n\t\tAuthRequestError(w, r, req, oidc.DefaultToServerError(err, \"unable to retrieve client by id\"), authorizer.Encoder())\n\t\treturn\n\t}\n\tRedirectToLogin(req.GetID(), client, w, r)\n}",
"func (ma *MockAuthorizer) Authorize(r *http.Request) bool {\n\treturn ma.Called(r).Bool(0)\n}",
"func (r *policyEnforcer) Authorized(cx *PolicyContext, pod *api.PodSpec) error {\n\tglog.Infof(\"validating the pod spec, namespace: %s\", cx.Namespace)\n\tfor i, p := range r.policies.Items {\n\t\t// step: check if the policy matches\n\t\tif match := p.Matches(cx); !match {\n\t\t\tcontinue\n\t\t}\n\t\tglog.V(10).Infof(\"matched the %d policy, namespace: %s in the list\", i,\n\t\t\tstrings.Join(p.Namespaces,\",\"))\n\n\t\t// step: check for conflicts\n\t\tif err := p.Spec.Conflicts(pod); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbreak\n\t}\n\n\treturn nil\n}",
"func (pm *PolicyMap) Allow(id uint32, dport uint16, proto u8proto.U8proto, trafficDirection trafficdirection.TrafficDirection, authType uint8, proxyPort uint16) error {\n\tkey := newKey(id, dport, proto, trafficDirection)\n\treturn pm.AllowKey(key, authType, proxyPort)\n}",
"func (p *DefaultPolicy) AllowAccess() bool {\n\treturn p.Effect == AllowAccess\n}",
"func (c Client) Authorize(scope ...string) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tauthURI := c.getAuthorizeURI(scope)\n\n\t\thttp.Redirect(w, r, authURI.String(), 302)\n\t}\n}",
"func (m *Server) Authorize(ctx context.Context, input *protoMessages.AuthorizeRequest) (f *protoMessages.AuthorizeResponse, _ error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tf = &protoMessages.AuthorizeResponse{\n\t\t\t\tError: &protoMessages.Error{\n\t\t\t\t\tMsg: fmt.Sprintf(\"%v\", r),\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}()\n\treq, err := protodriver.MakeAuthorizeInput(input)\n\tif err == nil {\n\t\tvar resp bool\n\t\tresp, err = m.AuthorizeHandler.Handle(req)\n\t\tif err == nil {\n\t\t\tf = protodriver.MakeAuthorizeResponse(resp)\n\t\t}\n\t}\n\tif err != nil {\n\t\tf = &protoMessages.AuthorizeResponse{\n\t\t\tError: &protoMessages.Error{\n\t\t\t\tMsg: err.Error(),\n\t\t\t},\n\t\t}\n\t}\n\treturn\n}",
"func (auth *Authorize) Authorize(u *User) bool {\n\tvar responseType string\n\tswitch auth.responseType {\n\tcase Token:\n\t\tresponseType = \"token\"\n\tcase Code:\n\t\tresponseType = \"code\"\n\tdefault:\n\t\tresponseType = \"unknown\"\n\t}\n\n\t// If the responseType is \"token\", username and password is needed.\n\tvar postParam map[string][]string\n\tif auth.responseType == Token {\n\t\tpostParam = url.Values{\"username\": {u.username}, \"password\": {u.password}}\n\t}\n\n\trequestURL, err := url.Parse(authorizeURL)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tgetParam := url.Values{\"client_id\": {auth.clientId}, \"response_type\": {responseType}, \"redirect_uri\": {auth.redirectURI}}\n\trequestURL.RawQuery = getParam.Encode()\n\n\t_, err = http.PostForm(requestURL.String(), postParam)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn ping()\n}",
"func (a *Authorizer) CanAuthorizeRequest(r *http.Request) bool {\n\treturn security.GetBearerTokenFromHeader(r.Header.Get(oAuth2Header)) != \"\"\n}",
"func IsAuthorized(ruleGetter PolicyRuleGetter, ar *Request) (bool, error) {\n\n\t// Get all the PolicyRules that apply to the user in the given namespace\n\trules, err := ruleGetter.GetApplicableRules(ar.User, ar.Groups, ar.Action.Namespace)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tlog.Printf(\"Applicable rules for user '%s', groups: '%v' in namespace '%s': %v\", ar.User, ar.Groups, ar.Action.Namespace, rules)\n\n\t// Depending on the request, we might be validating access to an API resource, or to\n\t// a \"NonResource\" URL.\n\tvar validateRule RuleValidator = isResourceActionAllowed\n\tif ar.Action.NonResourceURL != \"\" {\n\t\tvalidateRule = isNonResourceAccessAllowed\n\t}\n\n\t// Find a rule that allows the requested action\n\tfor _, r := range rules {\n\t\tif validateRule(r, ar.Action) {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}",
"func (authorizer Authorizer) Authorize(r *http.Request, i interface{}) error {\n\treturn authorizer(r, i)\n}",
"func (h *HTTPGuard) Allowed(req *http.Request) error {\n\tif !h.NetworkEnabled {\n\t\treturn ErrNtwkDisabled\n\t}\n\treturn nil\n}",
"func (h *authorizationHandler) Authorize(ctx context.Context, sub, res, path, op string) error {\n\n\tacl, err := h.resolver.ResolveSecret(ctx, sub)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn acl.CheckAuthorized(ctx, res, path, op)\n}",
"func IsAuthorize(s string) bool {\n\tswitch s {\n\tcase\n\t\t\"all\",\n\t\t\"authorize\":\n\t\treturn true\n\t}\n\treturn false\n}",
"func (c *Admission) authorizeResource(ctx context.Context, object metav1.Object, kind metav1.GroupVersionKind) (bool, string, error) {\n\t// @step: create a authorization context\n\tcx := &api.Context{\n\t\tCache: c.resourceCache,\n\t\tClient: c.client,\n\t\tGroup: kind,\n\t\tObject: object,\n\t\tPrefix: c.config.ControllerName,\n\t}\n\n\t// @step: iterate the authorizers and fail on first refusal\n\tfor i, provider := range c.providers {\n\t\tvar namespace *v1.Namespace\n\n\t\tif object.GetNamespace() != \"\" {\n\t\t\tn, err := utils.GetCachedNamespace(c.client, c.resourceCache, object.GetNamespace())\n\t\t\tif err != nil {\n\t\t\t\treturn false, \"\", err\n\t\t\t}\n\t\t\tnamespace = n\n\t\t}\n\n\t\t// @check if this authorizer is listening to this type\n\t\tif !provider.FilterOn().Matched(kind, namespace) {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"group\": kind.Group,\n\t\t\t\t\"id\": utils.GetTRX(ctx),\n\t\t\t\t\"kind\": kind.Kind,\n\t\t\t\t\"namespace\": object.GetNamespace(),\n\t\t\t\t\"provider\": provider.Name(),\n\t\t\t}).Debug(\"provider is not filtering on this object\")\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// @step: pass the object into the provider for authorization\n\t\terrs := func() field.ErrorList {\n\t\t\tnow := time.Now()\n\t\t\t// @metric record the time taken per provider\n\t\t\tdefer admissionAuthorizerLatencyMetric.WithLabelValues(provider.Name(), fmt.Sprintf(\"%d\", i)).Observe(time.Since(now).Seconds())\n\n\t\t\treturn provider.Admit(ctx, cx)\n\t\t}()\n\n\t\t// @check if we found any error from the provider\n\t\tif len(errs) > 0 {\n\t\t\tadmissionAuthorizerActionMetric.WithLabelValues(provider.Name(), actionDenied).Inc()\n\n\t\t\t// @check if it's an internal provider error and whether we should skip them\n\t\t\tskipme := false\n\t\t\tfor _, x := range errs {\n\t\t\t\tif x.Type == field.ErrorTypeInternal {\n\t\t\t\t\t// @check if the provider is asking as to ignore internal failures\n\t\t\t\t\tif provider.FilterOn().IgnoreOnFailure {\n\t\t\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\t\t\"error\": x.Detail,\n\t\t\t\t\t\t\t\"group\": kind.Group,\n\t\t\t\t\t\t\t\"id\": utils.GetTRX(ctx),\n\t\t\t\t\t\t\t\"kind\": kind.Kind,\n\t\t\t\t\t\t\t\"name\": object.GetGenerateName(),\n\t\t\t\t\t\t\t\"namespace\": object.GetNamespace(),\n\t\t\t\t\t\t}).Error(\"internal provider error, skipping the provider result\")\n\n\t\t\t\t\t\tskipme = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif skipme {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar reasons []string\n\t\t\tfor _, x := range errs {\n\t\t\t\treasons = append(reasons, fmt.Sprintf(\"%s=%v : %s\", x.Field, x.BadValue, x.Detail))\n\t\t\t}\n\n\t\t\treturn true, strings.Join(reasons, \",\"), nil\n\t\t}\n\n\t\tadmissionAuthorizerActionMetric.WithLabelValues(provider.Name(), actionAccepted)\n\t}\n\n\treturn false, \"\", nil\n}",
"func (a CasbinAuthorizer) Authorize(lgr zerolog.Logger, sub user.User, obj string, act string) error {\n\n\tconst (\n\t\tmoviesPath string = \"/api/v1/movies\"\n\t\tloggerPath string = \"/api/v1/logger\"\n\t)\n\n\tif strings.HasPrefix(obj, moviesPath) {\n\t\tobj = moviesPath\n\t} else if strings.HasPrefix(obj, loggerPath) {\n\t\tobj = loggerPath\n\t} else {\n\t\treturn errs.NewUnauthorizedError(errors.New(fmt.Sprintf(\"user %s does not have %s permission for %s\", sub.Email, act, obj)))\n\t}\n\n\tif (act == http.MethodGet) {\n\t\tact = \"read\"\n\t} else {\n\t\tact = \"write\"\n\t}\n\tauthorized := a.Enforcer.Enforce(sub.Email, obj, act)\n\tif authorized {\n\t\tlgr.Debug().Str(\"sub\", sub.Email).Str(\"obj\", obj).Str(\"act\", act).Msgf(\"Authorized (sub: %s, obj: %s, act: %s)\", sub.Email, obj, act)\n\t\treturn nil\n\t}\n\n\tlgr.Info().Str(\"sub\", sub.Email).Str(\"obj\", obj).Str(\"act\", act).Msgf(\"Unauthorized (sub: %s, obj: %s, act: %s)\", sub.Email, obj, act)\n\n\t// \"In summary, a 401 Unauthorized response should be used for missing or\n\t// bad authentication, and a 403 Forbidden response should be used afterwards,\n\t// when the user is authenticated but isn’t authorized to perform the\n\t// requested operation on the given resource.\"\n\t// If the user has gotten here, they have gotten through authentication\n\t// but do have the right access, this they are Unauthorized\n\treturn errs.NewUnauthorizedError(errors.New(fmt.Sprintf(\"user %s does not have %s permission for %s\", sub.Email, act, obj)))\n}",
"func (f AuthorizeHandlerFunc) Handle(input driver.AuthorizeInput) (bool, error) {\n\treturn f(input)\n}",
"func (p *plugin) cmdAuthorize(w irc.ResponseWriter, r *irc.Request, params cmd.ParamList) {\n\tp.profile.WhitelistAdd(params.String(0))\n\tproto.PrivMsg(w, r.SenderName, TextAuthorizeDisplay, params.String(0))\n}",
"func (analytics *Analytics) Authorize(ctx aero.Context, action string) error {\n\treturn AuthorizeIfLoggedIn(ctx)\n}",
"func (m *Client) Authorize(input driver.AuthorizeInput) (f driver.AuthorizeOutput) {\n\treq, err := protodriver.MakeAuthorizeRequest(input)\n\tif err == nil {\n\t\tvar resp *protoMessages.AuthorizeResponse\n\t\tresp, err = m.Client.Authorize(context.Background(), req)\n\t\tif err == nil {\n\t\t\tf = protodriver.MakeAuthorizeOutput(resp)\n\t\t}\n\t}\n\tif err != nil {\n\t\tf.Error = &driver.Error{Message: err.Error()}\n\t}\n\treturn\n}",
"func (act *AuthorizeAction) Do() error {\n\t// authorize.\n\tif errCode, errMsg := act.authorize(); errCode != pbcommon.ErrCode_E_OK {\n\t\treturn act.Err(errCode, errMsg)\n\t}\n\treturn nil\n}",
"func Authorize(req *http.Request, r render.Render, db *sql.DB) {\n\tapikey := req.URL.Query().Get(PARAM_API_KEY)\n\n\tif apikey == \"\" {\n\t\tSendErrorAsJSON(403, \"Not Authorized - Missing API Key\", r)\n\t} else {\n\t\tif CheckAPIKeyValid(apikey, db) {\n\t\t\treturn\n\t\t} else {\n\t\t\tSendErrorAsJSON(403, \"Not Authorized - Invalid API Key\", r)\n\t\t}\n\t}\n}",
"func (auth *Authorization) Authorize(handler http.Handler) http.Handler {\n\treturn auth.middleware.Handler(handler)\n}",
"func Authorize(s Server) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tswitch rtype := r.FormValue(\"response_type\"); rtype {\n\t\tcase \"code\":\n\t\t\turi, params := authorizeCode(s, w, r)\n\t\t\tif uri != \"\" || params != nil {\n\t\t\t\tRedirect(w, uri, params)\n\t\t\t}\n\t\tdefault:\n\t\t\tclient, uri := clientRedirectURI(s, w, r)\n\t\t\tif client != nil && uri != \"\" {\n\t\t\t\tRedirect(w, uri, Params{\n\t\t\t\t\t\"state\": r.FormValue(\"state\"),\n\t\t\t\t\t\"error\": \"unsupported_response_type\",\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t})\n}",
"func (self application) Authorize(f action, roles ...string) action {\n\treturn func(ctx *Context) error {\n\t\ttokenString, err := ctx.ReadCookie(config.ACCESS_TOKEN_NAME)\n\t\tif err != nil && err != http.ErrNoCookie {\n\t\t\tself.Logger.Error(fmt.Sprintf(\"%+v\\n\", err))\n\t\t\treturn NewErrUnauthorized()\n\t\t}\n\n\t\tif err == http.ErrNoCookie {\n\t\t\ttokenString = ctx.Request.Header.Get(config.AUTHORZIATION_NAME)\n\t\t\tif tokenString == \"\" {\n\t\t\t\treturn NewErrUnauthorized()\n\t\t\t}\n\t\t}\n\n\t\tkeyfunc := func(token *jwt.Token) (interface{}, error) {\n\t\t\treturn self.Config.JWT.Secret, nil\n\t\t}\n\t\tclaims := &Claims{}\n\t\ttoken, err := jwt.ParseWithClaims(tokenString, claims, keyfunc)\n\t\tif err != nil {\n\t\t\tself.Logger.Error(fmt.Sprintf(\"%+v\\n\", err))\n\t\t\treturn NewErrUnauthorized()\n\t\t}\n\n\t\tif !token.Valid {\n\t\t\troles, err := self.RefreshToken(ctx)\n\t\t\tif err == NewErrUnauthorized() {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tself.Logger.Error(fmt.Sprintf(\"%+v\\n\", err))\n\t\t\t\treturn NewErrUnauthorized()\n\t\t\t}\n\t\t\tclaims.Roles = roles\n\t\t}\n\n\t\tdoNext := false\n\t\textBreak := false\n\t\tif len(roles) > 0 {\n\t\t\tfor _, role := range roles {\n\t\t\t\tfor _, userRole := range claims.Roles {\n\t\t\t\t\tif role == userRole {\n\t\t\t\t\t\tdoNext = true\n\t\t\t\t\t\textBreak = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif extBreak {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !doNext {\n\t\t\t\treturn NewErrForbidden()\n\t\t\t}\n\t\t}\n\n\t\treturn f(ctx)\n\t}\n}",
"func (h *HttpAuthorizer) Authorize(r *http.Request) (err error) {\n\n\t// prepare data for template interpolation\n\tdata := map[string]interface{}{\n\t\t\"username\": \"phonkee\",\n\t\t\"password\": \"password\",\n\t}\n\n\tvar (\n\t\turl, method, body string\n\t)\n\n\turl, err = h.config.RenderURL(data)\n\tmethod, err = h.config.RenderMethod(data)\n\tbody, err = h.config.RenderData(data)\n\n\tvar (\n\t\tresponse *http.Response\n\t)\n\n\t// use Requester\n\tif _, response, err = NewRequester().DoNew(method, url, strings.NewReader(body)); err != nil {\n\t\treturn err\n\t}\n\n\tif response.StatusCode != http.StatusOK {\n\t\treturn ErrUnauthorized\n\t}\n\n\treturn\n}",
"func Authorize(requiredRole string) func(http.Handler) http.Handler {\n\trequiredRole = strings.ToLower(requiredRole)\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tctx := r.Context()\n\n\t\t\tclaims, err := GetJWTClaims(ctx)\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Check role inside of an array of roles in access token claims.\n\t\t\tvar role bool\n\t\t\tfor _, userRole := range claims.User_roles {\n\t\t\t\tif strings.EqualFold(requiredRole, userRole) {\n\t\t\t\t\trole = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !role {\n\t\t\t\ts := fmt.Sprintf(\n\t\t\t\t\t\"you are not authorized for that action; get roles: %v, expected: %s\",\n\t\t\t\t\tclaims.User_roles,\n\t\t\t\t\trequiredRole,\n\t\t\t\t)\n\t\t\t\thttp.Error(w, s, http.StatusUnauthorized)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n}",
"func (rh *RequestHandler) Authorize(w http.ResponseWriter, r *http.Request) {\n\trequest := &bridge.AuthorizeRequest{}\n\terr := helpers.FromRequest(r, request)\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\thelpers.Write(w, helpers.InvalidParameterError)\n\t\treturn\n\t}\n\n\terr = helpers.Validate(request, rh.Config.Assets, rh.Config.Accounts.IssuingAccountID)\n\tif err != nil {\n\t\tswitch err := err.(type) {\n\t\tcase *helpers.ErrorResponse:\n\t\t\thelpers.Write(w, err)\n\t\tdefault:\n\t\t\tlog.Error(err)\n\t\t\thelpers.Write(w, helpers.InternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tvar sourceAccount *string\n\tif rh.Config.Accounts.IssuingAccountID != \"\" {\n\t\tsourceAccount = &rh.Config.Accounts.IssuingAccountID\n\t}\n\n\tallowTrustOp := bridge.AllowTrustOperationBody{\n\t\tSource: sourceAccount,\n\t\tAuthorize: true,\n\t\tTrustor: request.AccountID,\n\t\tAssetCode: request.AssetCode,\n\t}\n\n\toperationBuilder := allowTrustOp.Build()\n\n\tsubmitResponse, err := rh.TransactionSubmitter.SubmitTransaction(\n\t\tnil,\n\t\trh.Config.Accounts.AuthorizingSeed,\n\t\t[]txnbuild.Operation{operationBuilder},\n\t\tnil,\n\t)\n\n\tjsonEncoder := json.NewEncoder(w)\n\n\tif err != nil {\n\t\therr, isHorizonError := err.(*hc.Error)\n\t\tif !isHorizonError {\n\t\t\tlog.WithFields(log.Fields{\"err\": err}).Error(\"Error submitting transaction\")\n\t\t\thelpers.Write(w, helpers.InternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tw.WriteHeader(herr.Problem.Status)\n\t\terr = jsonEncoder.Encode(herr.Problem)\n\t\tif err != nil {\n\t\t\tlog.WithFields(log.Fields{\"err\": err}).Error(\"Error encoding response\")\n\t\t\thelpers.Write(w, helpers.InternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\treturn\n\t}\n\n\terr = jsonEncoder.Encode(submitResponse)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"err\": err}).Error(\"Error encoding response\")\n\t\thelpers.Write(w, helpers.InternalServerError)\n\t\treturn\n\t}\n}",
"func (ca *cachingAuthorizer) Authorize(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error) {\n\tserializableAttributes := authorizer.AttributesRecord{\n\t\tVerb: a.GetVerb(),\n\t\tNamespace: a.GetNamespace(),\n\t\tAPIGroup: a.GetAPIGroup(),\n\t\tAPIVersion: a.GetAPIVersion(),\n\t\tResource: a.GetResource(),\n\t\tSubresource: a.GetSubresource(),\n\t\tName: a.GetName(),\n\t\tResourceRequest: a.IsResourceRequest(),\n\t\tPath: a.GetPath(),\n\t}\n\n\tif u := a.GetUser(); u != nil {\n\t\tdi := &user.DefaultInfo{\n\t\t\tName: u.GetName(),\n\t\t\tUID: u.GetUID(),\n\t\t}\n\n\t\t// Differently-ordered groups or extras could cause otherwise-equivalent checks to\n\t\t// have distinct cache keys.\n\t\tif groups := u.GetGroups(); len(groups) > 0 {\n\t\t\tdi.Groups = make([]string, len(groups))\n\t\t\tcopy(di.Groups, groups)\n\t\t\tsort.Strings(di.Groups)\n\t\t}\n\n\t\tif extra := u.GetExtra(); len(extra) > 0 {\n\t\t\tdi.Extra = make(map[string][]string, len(extra))\n\t\t\tfor k, vs := range extra {\n\t\t\t\tvdupe := make([]string, len(vs))\n\t\t\t\tcopy(vdupe, vs)\n\t\t\t\tsort.Strings(vdupe)\n\t\t\t\tdi.Extra[k] = vdupe\n\t\t\t}\n\t\t}\n\n\t\tserializableAttributes.User = di\n\t}\n\n\tvar b strings.Builder\n\tif err := json.NewEncoder(&b).Encode(serializableAttributes); err != nil {\n\t\treturn authorizer.DecisionNoOpinion, \"\", err\n\t}\n\tkey := b.String()\n\n\tif cached, ok := ca.decisions[key]; ok {\n\t\treturn cached.authorized, cached.reason, cached.err\n\t}\n\n\tauthorized, reason, err := ca.authorizer.Authorize(ctx, a)\n\n\tca.decisions[key] = authzResult{\n\t\tauthorized: authorized,\n\t\treason: reason,\n\t\terr: err,\n\t}\n\n\treturn authorized, reason, err\n}",
"func AuthoriserAllowAll(id, key string) bool {\n\treturn true\n}",
"func Authorize(next http.Handler, jwtSigningKey, apiKey string) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\thttputil.Authorize(w, r, jwtSigningKey, apiKey, next)\n\t})\n}",
"func (a *testAuthzMod) Authorize(sess *wamp.Session, msg wamp.Message) (bool, error) {\n\tcount, _ := wamp.AsInt64(sess.Details[\"count\"])\n\tcount++\n\tsess.Details[\"count\"] = count\n\tsess.Details[\"foo\"] = \"bar\"\n\tdelete(sess.Details, \"xyzzy\")\n\treturn true, nil\n}",
"func (b *BasicAuthorizer) Authorize(r *http.Request) (err error) {\n\tvar username, password string\n\n\tif username, password, err = b.GetBasicAuth(r); err != nil {\n\t\treturn\n\t}\n\n\tif username != b.config.Username || password != b.config.Password {\n\t\treturn ErrUnauthorized\n\t}\n\n\treturn\n}",
"func (c *ReviewPermissionChecker) CanReviewRequest(req types.AccessRequest) (bool, error) {\n\t// TODO(fspmarshall): Refactor this to improve readability when\n\t// adding role subselection support.\n\n\t// user cannot review their own request\n\tif c.User.GetName() == req.GetUser() {\n\t\treturn false, nil\n\t}\n\n\t// method allocates new array if an override has already been\n\t// called, so get the role list once in advance.\n\trequestedRoles := req.GetOriginalRoles()\n\n\tparser, err := NewJSONBoolParser(reviewPermissionContext{\n\t\tReviewer: reviewAuthorContext{\n\t\t\tRoles: c.User.GetRoles(),\n\t\t\tTraits: c.User.GetTraits(),\n\t\t},\n\t\tRequest: reviewRequestContext{\n\t\t\tRoles: requestedRoles,\n\t\t\tReason: req.GetRequestReason(),\n\t\t\tSystemAnnotations: req.GetSystemAnnotations(),\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn false, trace.Wrap(err)\n\t}\n\n\t// check all denial rules first.\n\tfor expr, denyMatchers := range c.Roles.DenyReview {\n\t\t// if predicate is non-empty, it must match\n\t\tif expr != \"\" {\n\t\t\tmatch, err := parser.EvalBoolPredicate(expr)\n\t\t\tif err != nil {\n\t\t\t\treturn false, trace.Wrap(err)\n\t\t\t}\n\t\t\tif !match {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tfor _, role := range requestedRoles {\n\t\t\tfor _, deny := range denyMatchers {\n\t\t\t\tif deny.Match(role) {\n\t\t\t\t\t// short-circuit on first denial\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// needsAllow tracks the list of roles which still need to match an allow directive\n\t// in order for the request to be reviewable. we need to perform a deep copy here\n\t// since we perform a filter-in-place when we find a matching allow directive.\n\tneedsAllow := make([]string, len(requestedRoles))\n\tcopy(needsAllow, requestedRoles)\n\nOuter:\n\tfor expr, allowMatchers := range c.Roles.AllowReview {\n\t\t// if predicate is non-empty, it must match.\n\t\tif expr != \"\" {\n\t\t\tmatch, err := parser.EvalBoolPredicate(expr)\n\t\t\tif err != nil {\n\t\t\t\treturn false, trace.Wrap(err)\n\t\t\t}\n\t\t\tif !match {\n\t\t\t\tcontinue Outer\n\t\t\t}\n\t\t}\n\n\t\t// unmatched collects unmatched roles for our filter-in-place operation.\n\t\tunmatched := needsAllow[:0]\n\n\tMatchRoles:\n\t\tfor _, role := range needsAllow {\n\t\t\tfor _, allow := range allowMatchers {\n\t\t\t\tif allow.Match(role) {\n\t\t\t\t\t// role matched this allow directive, and will be filtered out\n\t\t\t\t\tcontinue MatchRoles\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// still unmatched, this role will continue to be part of\n\t\t\t// the needsAllow list next iteration.\n\t\t\tunmatched = append(unmatched, role)\n\t\t}\n\n\t\t// finalize our filter-in-place\n\t\tneedsAllow = unmatched\n\n\t\tif len(needsAllow) == 0 {\n\t\t\t// all roles have matched an allow directive, no further\n\t\t\t// processing is required.\n\t\t\tbreak Outer\n\t\t}\n\t}\n\n\treturn len(needsAllow) == 0, nil\n}",
"func Authorize(res http.ResponseWriter, req *http.Request) {\n\n\tvar (\n\t\tuserModel models.User\n\t\terrorResponse response.Error\n\t\tsuccessResponse response.Success\n\t\tidentity = regexp.MustCompile(\"^\" + config.EmailRegex + \"$\")\n\t\tauthorize userRequest.Authorize\n\t\terror error\n\t)\n\terror = json.NewDecoder(req.Body).Decode(&authorize)\n\tif error != nil {\n\t\terrorResponse.Code = http.StatusBadRequest\n\t\terrorResponse.Error = config.InvalidRequest\n\t\thelpers.SetResponse(res, http.StatusBadRequest, errorResponse)\n\t\treturn\n\t}\n\terror = authorize.Validate()\n\tif error != nil {\n\t\terrorResponse.Code = http.StatusBadRequest\n\t\terrorResponse.Error = helpers.FormatError(error.Error())\n\t\thelpers.SetResponse(res, http.StatusBadRequest, errorResponse)\n\t\treturn\n\t}\n\tuser := userModel.Check(authorize.Identity)\n\tuser.OTP, _ = strconv.ParseInt(helpers.GenerateOtp(6), 10, 64)\n\tuser.OtpValidity = time.Now().Unix()\n\tif identity.MatchString(authorize.Identity) {\n\t\tuser.Email = &authorize.Identity\n\t\tuser.OtpType = \"authorizeEmail\"\n\t\tsuccessResponse.Msg = strings.Replace(config.AuthorizeMsg, \"identity\", \"email \"+helpers.MaskEmail(authorize.Identity), -1)\n\t} else {\n\t\tuser.PhoneNumber = &authorize.Identity\n\t\tuser.OtpType = \"authorizePhone\"\n\t\tsuccessResponse.Msg = strings.Replace(config.AuthorizeMsg, \"identity\", \"mobile \"+helpers.MaskNumber(authorize.Identity), -1)\n\t}\n\tif user.ID > 0 {\n\t\terror = userModel.UpdateDetail()\n\t} else {\n\t\tuser, error = userModel.Authorize()\n\t}\n\ttoken, error := helpers.GenerateToken(user.ID)\n\tif error != nil {\n\t\terrorResponse.Code = http.StatusServiceUnavailable\n\t\terrorResponse.Error = config.ServiceUnavailable\n\t\thelpers.SetResponse(res, http.StatusServiceUnavailable, errorResponse)\n\t\treturn\n\t}\n\tresponse := make(map[string]interface{})\n\tresponse[\"authorizationToken\"] = token\n\tsuccessResponse.Code = http.StatusOK\n\tsuccessResponse.Data = response\n\thelpers.SetResponse(res, http.StatusOK, successResponse)\n}",
"func (al *AnomalyDetectionLimiter) Allow(event Event) bool {\n\treturn al.limiter.Allow(event.GetWorkloadID())\n}",
"func (act *CreateAction) Authorize() error {\n\tif errCode, errMsg := act.authorize(); errCode != pbcommon.ErrCode_E_OK {\n\t\treturn act.Err(errCode, errMsg)\n\t}\n\treturn nil\n}",
"func (policy Policy) IsAllowed(args Args) bool {\n\t// Check all deny statements. If any one statement denies, return false.\n\tfor _, statement := range policy.Statements {\n\t\tif statement.Effect == Deny {\n\t\t\tif !statement.IsAllowed(args) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\t// For owner, its allowed by default.\n\tif args.IsOwner {\n\t\treturn true\n\t}\n\n\t// Check all allow statements. If any one statement allows, return true.\n\tfor _, statement := range policy.Statements {\n\t\tif statement.Effect == Allow {\n\t\t\tif statement.IsAllowed(args) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}",
"func Authorize(w http.ResponseWriter, r *http.Request, p *models.PluginContext) {\n\tuserID := r.Header.Get(\"Mattermost-User-ID\")\n\tif userID == \"\" {\n\t\thttp.Error(w, \"Not authorized\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\toauthConfig := p.OauthConfig\n\n\tstate := fmt.Sprintf(\"%v_%v\", model.NewId()[0:15], userID)\n\n\tp.API.KVSet(state, []byte(state))\n\n\turl := oauthConfig.AuthCodeURL(state, oauth2.AccessTypeOffline)\n\n\tmlog.Info(\"Authorize Url: \" + url)\n\n\thttp.Redirect(w, r, url, http.StatusPermanentRedirect)\n}",
"func authorize(name string) error {\n\tif distro.Get() == distro.Synology {\n\t\treturn authorizeSynology(name)\n\t}\n\treturn nil\n}",
"func (thread *Thread) Authorize(ctx aero.Context, action string) error {\n\tif !ctx.HasSession() {\n\t\treturn errors.New(\"Neither logged in nor in session\")\n\t}\n\n\tif action == \"edit\" {\n\t\tuser := GetUserFromContext(ctx)\n\n\t\tif thread.CreatedBy != user.ID && user.Role != \"admin\" {\n\t\t\treturn errors.New(\"Can't edit the threads of other users\")\n\t\t}\n\t}\n\n\treturn nil\n}",
"func Authorize(next buffalo.Handler) buffalo.Handler {\n\treturn func(c buffalo.Context) error {\n\t\tif uid := c.Session().Get(\"current_user_id\"); uid == nil {\n\t\t\tc.Flash().Add(\"danger\", \"You must be authorized to see that page\")\n\t\t\treturn c.Redirect(302, \"/\")\n\t\t}\n\t\treturn next(c)\n\t}\n}",
"func (statement Statement) IsAllowed(args authorizer.Args) bool {\n\tcheck := func() bool {\n\t\tif !statement.Actions.Match(args.Action) {\n\t\t\treturn false\n\t\t}\n\n\t\tif !statement.Resources.Match(args.Resource) {\n\t\t\treturn false\n\t\t}\n\n\t\treturn true\n\t}\n\n\treturn statement.Effect.IsAllowed(check())\n}",
"func (a *authorizer) Authorize(method string, r model.Role) bool {\n\tswitch method {\n\tcase \"/pipe.api.service.webservice.WebService/AddEnvironment\":\n\t\treturn isAdmin(r)\n\tcase \"/pipe.api.service.webservice.WebService/UpdateEnvironmentDesc\":\n\t\treturn isAdmin(r)\n\tcase \"/pipe.api.service.webservice.WebService/RegisterPiped\":\n\t\treturn isAdmin(r)\n\tcase \"/pipe.api.service.webservice.WebService/RecreatePipedKey\":\n\t\treturn isAdmin(r)\n\tcase \"/pipe.api.service.webservice.WebService/EnablePiped\":\n\t\treturn isAdmin(r)\n\tcase \"/pipe.api.service.webservice.WebService/DisablePiped\":\n\t\treturn isAdmin(r)\n\tcase \"/pipe.api.service.webservice.WebService/AddApplication\":\n\t\treturn isAdmin(r)\n\tcase \"/pipe.api.service.webservice.WebService/EnableApplication\":\n\t\treturn isAdmin(r)\n\tcase \"/pipe.api.service.webservice.WebService/DisableApplication\":\n\t\treturn isAdmin(r)\n\tcase \"/pipe.api.service.webservice.WebService/UpdateProjectStaticAdmin\":\n\t\treturn isAdmin(r)\n\tcase \"/pipe.api.service.webservice.WebService/EnableStaticAdmin\":\n\t\treturn isAdmin(r)\n\tcase \"/pipe.api.service.webservice.WebService/DisableStaticAdmin\":\n\t\treturn isAdmin(r)\n\tcase \"/pipe.api.service.webservice.WebService/UpdateProjectSSOConfig\":\n\t\treturn isAdmin(r)\n\tcase \"/pipe.api.service.webservice.WebService/UpdateProjectRBACConfig\":\n\t\treturn isAdmin(r)\n\tcase \"/pipe.api.service.webservice.WebService/SyncApplication\":\n\t\treturn isAdmin(r) || isEditor(r)\n\tcase \"/pipe.api.service.webservice.WebService/CancelDeployment\":\n\t\treturn isAdmin(r) || isEditor(r)\n\tcase \"/pipe.api.service.webservice.WebService/ApproveStage\":\n\t\treturn isAdmin(r) || isEditor(r)\n\tcase \"/pipe.api.service.webservice.WebService/GenerateApplicationSealedSecret\":\n\t\treturn isAdmin(r) || isEditor(r)\n\tcase \"/pipe.api.service.webservice.WebService/GetApplicationLiveState\":\n\t\treturn isAdmin(r) || isEditor(r) || isViewer(r)\n\tcase \"/pipe.api.service.webservice.WebService/GetProject\":\n\t\treturn isAdmin(r) || isEditor(r) || isViewer(r)\n\tcase \"/pipe.api.service.webservice.WebService/GetCommand\":\n\t\treturn isAdmin(r) || isEditor(r) || isViewer(r)\n\tcase \"/pipe.api.service.webservice.WebService/ListDeploymentConfigTemplates\":\n\t\treturn isAdmin(r) || isEditor(r) || isViewer(r)\n\tcase \"/pipe.api.service.webservice.WebService/ListEnvironments\":\n\t\treturn isAdmin(r) || isEditor(r) || isViewer(r)\n\tcase \"/pipe.api.service.webservice.WebService/ListPipeds\":\n\t\treturn isAdmin(r) || isEditor(r) || isViewer(r)\n\tcase \"/pipe.api.service.webservice.WebService/GetPiped\":\n\t\treturn isAdmin(r) || isEditor(r) || isViewer(r)\n\tcase \"/pipe.api.service.webservice.WebService/ListApplications\":\n\t\treturn isAdmin(r) || isEditor(r) || isViewer(r)\n\tcase \"/pipe.api.service.webservice.WebService/GetApplication\":\n\t\treturn isAdmin(r) || isEditor(r) || isViewer(r)\n\tcase \"/pipe.api.service.webservice.WebService/ListDeployments\":\n\t\treturn isAdmin(r) || isEditor(r) || isViewer(r)\n\tcase \"/pipe.api.service.webservice.WebService/GetDeployment\":\n\t\treturn isAdmin(r) || isEditor(r) || isViewer(r)\n\tcase \"/pipe.api.service.webservice.WebService/GetStageLog\":\n\t\treturn isAdmin(r) || isEditor(r) || isViewer(r)\n\tcase \"/pipe.api.service.webservice.WebService/GetMe\":\n\t\treturn isAdmin(r) || isEditor(r) || isViewer(r)\n\t}\n\treturn false\n}",
"func Authorize(w http.ResponseWriter, r *http.Request) {\n\n\tauthRequest := &models.AuthorizeRequestBody{}\n\tif !authRequest.Validate(w, r) {\n\t\treturn\n\t}\n\tauthcode := authRequest.GenerateAuthCode(w)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\n\tresponse := map[string]interface{}{\"data\": map[string]interface{}{\n\t\t\"authorization_code\": authcode.Code,\n\t\t\"expires_at\": authcode.ExpiresAt,\n\t}, \"status\": 1}\n\tjson.NewEncoder(w).Encode(response)\n}",
"func (company *Company) Authorize(ctx aero.Context, action string) error {\n\tuser := GetUserFromContext(ctx)\n\n\tif user == nil {\n\t\treturn errors.New(\"Not logged in\")\n\t}\n\n\tif user.Role != \"editor\" && user.Role != \"admin\" {\n\t\treturn errors.New(\"Insufficient permissions\")\n\t}\n\n\treturn nil\n}",
"func (p *Policy) Evaluate(c *Context) (allow bool, match bool, err error) {\n\tfor _, statement := range p.Statements {\n\t\tstatementMatch, err := statement.match(c)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif statementMatch {\n\t\t\tmatch = true\n\t\t\tif statement.Effect == Deny {\n\t\t\t\tallow = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif statement.Effect == Allow {\n\t\t\t\tallow = true\n\t\t\t}\n\t\t}\n\t}\n\treturn allow, match, err\n}",
"func (authClient *AuthClient) Authorize(guildID, userID, command, action string) bool {\n\treturn true\n}",
"func (client *CheckoutComClient) Authorize(request *sleet.AuthorizationRequest) (*sleet.AuthorizationResponse, error) {\n\treturn client.AuthorizeWithContext(context.TODO(), request)\n}",
"func (a *Authorizer) Authorize(ctx context.Context, attrs *authorization.Attributes) (bool, error) {\n\tif attrs != nil {\n\t\tlogger = logger.WithFields(logrus.Fields{\n\t\t\t\"zz_request\": map[string]string{\n\t\t\t\t\"apiGroup\": attrs.APIGroup,\n\t\t\t\t\"apiVersion\": attrs.APIVersion,\n\t\t\t\t\"namespace\": attrs.Namespace,\n\t\t\t\t\"resource\": attrs.Resource,\n\t\t\t\t\"resourceName\": attrs.ResourceName,\n\t\t\t\t\"username\": attrs.User.Username,\n\t\t\t\t\"verb\": attrs.Verb,\n\t\t\t},\n\t\t})\n\t}\n\n\t// Get cluster roles binding\n\tclusterRoleBindings, err := a.Store.ListClusterRoleBindings(ctx, &store.SelectionPredicate{})\n\tif err != nil {\n\t\tswitch err := err.(type) {\n\t\tcase *store.ErrNotFound:\n\t\t\t// No ClusterRoleBindings founds, let's continue with the RoleBindings\n\t\t\tlogger.WithError(err).Debug(\"no ClusterRoleBindings found\")\n\t\tdefault:\n\t\t\tlogger.WithError(err).Warning(\"could not retrieve the ClusterRoleBindings\")\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\t// Inspect each cluster role binding\n\tfor _, clusterRoleBinding := range clusterRoleBindings {\n\t\tbindingName := clusterRoleBinding.Name\n\n\t\t// Verify if this cluster role binding matches our user\n\t\tif !matchesUser(attrs.User, clusterRoleBinding.Subjects) {\n\t\t\tlogger.Debugf(\"the user is not a subject of the ClusterRoleBinding %s\", bindingName)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Get the RoleRef that matched our user\n\t\trules, err := a.getRoleReferencerules(ctx, clusterRoleBinding.RoleRef)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\t// Loop through the rules\n\t\tfor _, rule := range rules {\n\t\t\t// Verify if this rule applies to our request\n\t\t\tallowed, reason := ruleAllows(attrs, rule)\n\t\t\tif allowed {\n\t\t\t\tlogger.Debugf(\"request authorized by the ClusterRoleBinding %s\", bindingName)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tlogger.Tracef(\"%s by rule %+v\", reason, rule)\n\t\t}\n\t\tlogger.Debugf(\"could not authorize the request with the ClusterRoleBinding %s\",\n\t\t\tbindingName,\n\t\t)\n\t\tlogger.Debugf(\"could not authorize the request with any ClusterRoleBindings\")\n\t}\n\n\t// None of the cluster roles authorized our request. Let's try with roles\n\t// First, make sure we have a namespace\n\tif len(attrs.Namespace) > 0 {\n\t\t// Get roles binding\n\t\troleBindings, err := a.Store.ListRoleBindings(ctx, &store.SelectionPredicate{})\n\t\tif err != nil {\n\t\t\tswitch err := err.(type) {\n\t\t\tcase *store.ErrNotFound:\n\t\t\t\t// No ClusterRoleBindings founds, let's continue with the RoleBindings\n\t\t\t\tlogger.WithError(err).Debug(\"no RoleBindings found\")\n\t\t\tdefault:\n\t\t\t\tlogger.WithError(err).Warning(\"could not retrieve the ClusterRoleBindings\")\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\n\t\t// Inspect each role binding\n\t\tfor _, roleBinding := range roleBindings {\n\t\t\tbindingName := roleBinding.Name\n\n\t\t\t// Verify if this role binding matches our user\n\t\t\tif !matchesUser(attrs.User, roleBinding.Subjects) {\n\t\t\t\tlogger.Debugf(\"the user is not a subject of the RoleBinding %s\", bindingName)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Get the RoleRef that matched our user\n\t\t\trules, err := a.getRoleReferencerules(ctx, roleBinding.RoleRef)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\t// Loop through the rules\n\t\t\tfor _, rule := range rules {\n\t\t\t\t// Verify if this rule applies to our request\n\t\t\t\tallowed, reason := ruleAllows(attrs, rule)\n\t\t\t\tif allowed {\n\t\t\t\t\tlogger.Debugf(\"request authorized by the RoleBinding %s\", bindingName)\n\t\t\t\t\treturn true, nil\n\t\t\t\t}\n\t\t\t\tlogger.Tracef(\"%s by rule %+v\", reason, rule)\n\t\t\t}\n\t\t\tlogger.Debugf(\"could not authorize the request with the RoleBinding %s\",\n\t\t\t\tbindingName,\n\t\t\t)\n\t\t}\n\t\tlogger.Debugf(\"could not authorize the request with any RoleBindings\")\n\t}\n\n\tlogger.Debugf(\"unauthorized request\")\n\treturn false, nil\n}",
"func (auth *Authorize) AuthorizeApp(checkFunc func() bool) bool {\n\t// If ping function shows that user not login, authorize failed.\n\tif !auth.Authorize(nil) {\n\t\treturn false\n\t}\n\n\tif checkFunc == nil {\n\t\treturn true\n\t}\n\n\treturn checkFunc()\n}",
"func (a *action) Authorize(authorize *mixTy.MixAuthorizeAction) (*types.Receipt, error) {\n\n\texecer, symbol := mixTy.GetAssetExecSymbol(a.api.GetConfig(), authorize.AssetExec, authorize.AssetSymbol)\n\tinput, err := a.authorizePubInputs(execer, symbol, authorize.ProofInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//zk-proof校验\n\terr = zkProofVerify(a.db, authorize.ProofInfo, mixTy.VerifyType_AUTHORIZE)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treceipt := &types.Receipt{Ty: types.ExecOk}\n\tauthNullHash := input.AuthorizeHash.GetWitnessValue(ecc.BN254)\n\tr := makeReceipt(calcAuthorizeHashKey(authNullHash.String()), mixTy.TyLogAuthorizeSet, &mixTy.ExistValue{Nullifier: authNullHash.String(), Exist: true})\n\tmergeReceipt(receipt, r)\n\tauthSpendHash := input.AuthorizeSpendHash.GetWitnessValue(ecc.BN254)\n\tr = makeReceipt(calcAuthorizeSpendHashKey(authSpendHash.String()), mixTy.TyLogAuthorizeSpendSet, &mixTy.ExistValue{Nullifier: authSpendHash.String(), Exist: true})\n\tmergeReceipt(receipt, r)\n\n\treturn receipt, nil\n\n}",
"func (client *StripeClient) Authorize(request *sleet.AuthorizationRequest) (*sleet.AuthorizationResponse, error) {\n\treturn client.AuthorizeWithContext(context.TODO(), request)\n}",
"func authorize(ctx context.Context) error {\n\t// Fetch Bearer token\n\t// In case it is provided and is correct, consider auth completed\n\t_, err := fetchJWTToken(ctx)\n\n\treturn err\n}",
"func (a Authentic) AuthorizeMW(h buffalo.Handler) buffalo.Handler {\n\treturn func(c buffalo.Context) error {\n\t\tif a.app.Env == \"test\" {\n\t\t\treturn h(c)\n\t\t}\n\n\t\tuserID := c.Session().Get(SessionField)\n\t\tif userID == nil {\n\t\t\tc.Flash().Set(\"warning\", []string{\"Need to login first.\"})\n\t\t\treturn c.Redirect(http.StatusSeeOther, a.Config.LoginPath)\n\t\t}\n\n\t\tuser, err := a.provider.FindByID(userID)\n\n\t\tif err != nil || user == nil {\n\t\t\tc.Flash().Set(\"warning\", []string{\"Need to login first.\"})\n\t\t\treturn c.Redirect(http.StatusSeeOther, a.Config.LoginPath)\n\t\t}\n\n\t\treturn h(c)\n\t}\n}",
"func (ba *BasicAuth) Authorize(req *restful.Request) (authorized bool) {\n\tlog.Debug(\"verifying Basic Auth\")\n\tusername, password, ok := req.Request.BasicAuth()\n\tif ok && username == ba.username && password == ba.password {\n\t\tlog.Debug(\"failed to verify using Basic Auth\")\n\t\tauthorized = true\n\t}\n\treturn\n}",
"func TestAuthorize(t *testing.T) {\n\t// TODO(r0mant): Implement this.\n\tt.Skip(\"Not implemented\")\n}",
"func (rl *RateLimiter) Allow(ruleID string, event Event) bool {\n\trl.RLock()\n\tdefer rl.RUnlock()\n\n\tlimiter, ok := rl.limiters[ruleID]\n\tif !ok {\n\t\treturn false\n\t}\n\treturn limiter.Allow(event)\n}",
"func WrapAuthorize(hfn http.Handler, routeName string) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\turlValues := r.URL.Query()\n\n\t\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\t\trefRoles := gorillaContext.Get(r, \"auth_roles\").([]string)\n\t\tserviceToken := gorillaContext.Get(r, \"auth_service_token\").(string)\n\n\t\t// Check first if service token is used\n\t\tif serviceToken != \"\" && serviceToken == urlValues.Get(\"key\") {\n\t\t\thfn.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tif auth.Authorize(routeName, refRoles, refStr) {\n\t\t\thfn.ServeHTTP(w, r)\n\t\t} else {\n\t\t\terr := APIErrorForbidden()\n\t\t\trespondErr(w, err)\n\t\t}\n\t})\n}",
"func Authorize(c *fiber.Ctx) {\n\tauthHeader := c.Get(\"Authorization\")\n\ttoken := strings.TrimPrefix(authHeader, \"Bearer \")\n\n\tplayerID, err := auth.GetPlayerIDFromAccessToken(token)\n\tif err != nil {\n\t\tfmt.Printf(\"Player token (%s) parse error: %s\\n\", token, err)\n\t\tc.SendStatus(403)\n\t\tc.JSON(utils.FormatErrors(err))\n\t\treturn\n\t}\n\n\t// add playerID to context\n\tc.Locals(\"playerID\", playerID)\n\tc.Locals(\"token\", token)\n\tc.Next(nil)\n}",
"func (s *prometheusruleWebhook) Authorized(request admissionctl.Request) admissionctl.Response {\n\treturn s.authorized(request)\n}",
"func (c *RestController) Authorize(w http.ResponseWriter, r *http.Request) {\n\tvar req BasicOauth2Request\n\tif err := c.Decode(r, &req, net.NewDecodeOptions(true, true, false, true)); err != nil {\n\t\tc.Error(w, err)\n\t\treturn\n\t}\n\tif id, secret, hasAuth := r.BasicAuth(); hasAuth {\n\t\treq.ClientID = id\n\t\treq.ClientSecret = secret\n\t}\n\tres, err := c.service.Authorize(r.Context(), &req)\n\tif err != nil {\n\t\tc.Error(w, err)\n\t\treturn\n\t}\n\tif len(req.RedirectURI) > 0 {\n\t\tnr, _ := http.NewRequest(\"GET\", req.RedirectURI, nil)\n\t\tc.URL(nr, res)\n\t\thttp.Redirect(w, nr, nr.URL.String(), http.StatusFound)\n\t\treturn\n\t}\n\tc.JSON(w, res, http.StatusOK)\n}",
"func Authorize(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\n\t// Get token from request\n\ttoken, err := request.ParseFromRequestWithClaims(r, request.OAuth2Extractor, &AppClaims{}, func(token *jwt.Token) (interface{}, error) {\n\t\t// since we only use the one private key to sign the tokens,\n\t\t// we also only use its public counter part to verify\n\t\treturn verifyKey, nil\n\t})\n\n\tif err != nil {\n\t\tswitch err.(type) {\n\n\t\tcase *jwt.ValidationError: // JWT validation error\n\t\t\tvErr := err.(*jwt.ValidationError)\n\n\t\t\tswitch vErr.Errors {\n\t\t\tcase jwt.ValidationErrorExpired: //JWT expired\n\t\t\t\tutils.DisplayAppError(\n\t\t\t\t\tw,\n\t\t\t\t\terr,\n\t\t\t\t\t\"Access Token is expired, get a new Token\",\n\t\t\t\t\t401,\n\t\t\t\t)\n\t\t\t\treturn\n\n\t\t\tdefault:\n\t\t\t\tutils.DisplayAppError(w,\n\t\t\t\t\terr,\n\t\t\t\t\t\"Error while parsing the Access Token!\",\n\t\t\t\t\t500,\n\t\t\t\t)\n\t\t\t\treturn\n\t\t\t}\n\n\t\tdefault:\n\t\t\tutils.DisplayAppError(w,\n\t\t\t\terr,\n\t\t\t\t\"Error while parsing Access Token!\",\n\t\t\t\t500)\n\t\t\treturn\n\t\t}\n\n\t}\n\tif token.Valid {\n\t\t// Using context: https://joeshaw.org/revisiting-context-and-http-handler-for-go-17/\n\t\tcontextWithUserEmail := context.WithValue(r.Context(), ContextUserEmailKey, token.Claims.(*AppClaims).CurrentUserEmail)\n\t\tnext.ServeHTTP(w, r.WithContext(contextWithUserEmail))\n\t} else {\n\t\tutils.DisplayAppError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"Invalid Access Token\",\n\t\t\t401,\n\t\t)\n\t}\n}",
"func (b *userBiz) Authorize(user web.User, h web.HandlerInfo) bool {\n\tif au, ok := user.(*model.AuthUser); ok {\n\t\treturn au.IsAllowed(h.Name())\n\t}\n\treturn false\n}",
"func (a *GithubAuth) AuthorizeOrForbid(h http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tuser := a.User(r)\n\t\tif user == nil || user.IsMemberOfOrg == false {\n\t\t\thttp.Error(w, \"Please authenticate\", http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\th.ServeHTTP(w, r)\n\t}\n\treturn http.HandlerFunc(fn)\n}",
"func isActionAllowed(messageName protoreflect.Name, attributeName protoreflect.Name, act action, trace []string) bool {\n\n\tlog.Debugf(\"Received %s, %s, %v, %+v\", messageName, attributeName, act, trace)\n\tlog.Debugf(\"Policies file was parsed as %+v\", loaded_policies)\n\n\t// if policies don't exist or is empty, assume action is allowed\n\t// for backwards-compatibility purposes.\n\tif loaded_policies == nil || len(loaded_policies) == 0 {\n\t\treturn true\n\t}\n\n\tkey := fmt.Sprintf(\"%s.%s\", strings.Title(string(messageName)), strings.Title(string(attributeName)))\n\tlog.Debugf(\"Converting %s, %s to %s\", messageName, attributeName, key)\n\n\tif conditions, ok := loaded_policies[key]; ok {\n\n\t\tlog.Debugf(\"Found all conditions for %s: %+v\", key, conditions)\n\n\t\tchosen_condition := conditions.CopyConditions\n\t\tswitch act {\n\t\tcase copying:\n\t\t\tchosen_condition = conditions.CopyConditions\n\t\tcase printing:\n\t\t\tchosen_condition = conditions.PrintConditions\n\t\tcase modifying:\n\t\t\tchosen_condition = conditions.ModifyConditions\n\t\t}\n\n\t\tlog.Debugf(\"Because %+v was chosen for action, using specific condition for that action: %+v\", act, chosen_condition)\n\n\t\tif chosen_condition == nil {\n\t\t\treturn true\n\t\t}\n\n\t\tfor _, condition := range *chosen_condition {\n\t\t\tlog.Debugf(\"Considering %+v\", condition)\n\t\t\tif matches(condition.If, trace) {\n\t\t\t\tlog.Debugf(\"Accepted %+v\", condition)\n\t\t\t\treturn condition.Allowed\n\t\t\t}\n\t\t}\n\n\t\treturn false\n\t}\n\n\t// if there is no policy for this key at all, the action is allowed.\n\tlog.Debugf(\"No corresponding policy for %s in policy file at GRPC_PRIVACY_POLICY_LOCATION was found\", key)\n\treturn true\n}",
"func (api *API) authorizeRequest() gin.HandlerFunc {\n\treturn func(ctx *gin.Context) {\n\t\t// Extract the bearer token\n\t\theaderTokenString, err := extractBearerToken(ctx)\n\t\tif api.check(err, ctx, http.StatusUnauthorized) {\n\t\t\treturn\n\t\t}\n\n\t\t// Construct the actual token which is needed to get the correct\n\t\t// token from the database because with this \"headerToken\" can a\n\t\t// connection with the Google API be established. This connection\n\t\t// is how we obtain the sub, which is then used to lookup the\n\t\t// correct token in the Postgres database.\n\t\theaderToken := oauth2.Token{AccessToken: headerTokenString}\n\n\t\t// Get user info to obtain the sub\n\t\tu, err := api.getUserInfo(&headerToken)\n\t\tif api.check(err, ctx) {\n\t\t\treturn\n\t\t}\n\t\t// Query the database to get the token, given the sub\n\t\tcorrectToken, err := api.database.GetToken(u.Sub)\n\t\tif api.check(err, ctx) {\n\t\t\treturn\n\t\t}\n\n\t\t// Check if the token provided in the authorization header equals the\n\t\t// token from the database. If an only if this is true will the user\n\t\t// gain authorization to the protected resources.\n\t\tif headerTokenString != correctToken {\n\t\t\tapi.log.Infof(errUnauthorized.Error())\n\t\t\tapi.check(errUnauthorized, ctx, http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tctx.Next()\n\t}\n}",
"func AuthorizeAgent(c *gin.Context) {\n\tsecret := c.MustGet(\"agent\").(string)\n\tif secret == \"\" {\n\t\tc.String(401, \"invalid or empty token.\")\n\t\treturn\n\t}\n\n\tparsed, err := token.ParseRequest(c.Request, func(t *token.Token) (string, error) {\n\t\treturn secret, nil\n\t})\n\tif err != nil {\n\t\tc.String(500, \"invalid or empty token. %s\", err)\n\t\tc.Abort()\n\t} else if parsed.Kind != token.AgentToken {\n\t\tc.String(403, \"invalid token. please use an agent token\")\n\t\tc.Abort()\n\t} else {\n\t\tc.Next()\n\t}\n}",
"func (s *Server) requestAuthorized(c echo.Context, perm, tgtOwner string) error {\n\tclaims := getClaims(c)\n\treqOwner := claims[\"user\"].(string)\n\n\tpset := make(map[string]struct{})\n\tfor _, p := range claims[\"permissions\"].([]interface{}) {\n\t\tpset[strings.ToLower(p.(string))] = struct{}{}\n\t}\n\n\tnet := c.Param(\"id\")\n\n\t// Make checks for the individual nodes of the permissions\n\t// checks below. This still winds up being O(N) and is much\n\t// easier to read than a clever loop.\n\t_, netAny := pset[net+\":*\"]\n\t_, netExact := pset[net+\":\"+perm]\n\t_, netSudo := pset[net+\":sudo\"]\n\t_, anyAny := pset[\"*:*\"]\n\t_, anyExact := pset[\"*:\"+perm]\n\t_, anySudo := pset[\"*:sudo\"]\n\n\thasPerm := netAny || netExact || anyAny || anyExact\n\thasSudo := netAny || anyAny || netSudo || anySudo\n\n\t// Now we can perform the permissions check. If the user has\n\t// any permission on any network, or any on the specific one\n\t// that satisfies the check right away. Failing that we check\n\t// that they have the permission and optionally if they\n\t// require sudo.\n\tif hasPerm && (reqOwner == tgtOwner || hasSudo) {\n\t\treturn nil\n\t}\n\n\t// Anything but the above and the request isn't authorized.\n\treturn errors.New(\"requestor unqualified\")\n}",
"func (act *RollbackAction) Authorize() error {\n\tif errCode, errMsg := act.authorize(); errCode != pbcommon.ErrCode_E_OK {\n\t\treturn act.Err(errCode, errMsg)\n\t}\n\treturn nil\n}",
"func IsAuthorized(endpoint func(w http.ResponseWriter, r *http.Request)) http.Handler {\n\t//return http.Handler type\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tswitch r.Method {\n\t\t//handle GET requests\n\t\tcase \"GET\":\n\t\t\t//check if cookie exists\n\t\t\tif r.Header[\"Cookie\"] != nil {\n\t\t\t\t//get cookie from request header, 6: takes out \"Token=\" string which causes int64 error\n\t\t\t\tcookieBody := r.Header.Get(\"Cookie\")[6:]\n\t\t\t\t//parse cookie body and check token, 2nd param is a function which returns the signingKey\n\t\t\t\ttoken, parseErr := jwt.Parse(cookieBody, func(token *jwt.Token) (interface{}, error) {\n\t\t\t\t\t//handle err\n\t\t\t\t\tif _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\n\t\t\t\t\t\treturn nil, errors.New(\"Unauthorized\")\n\t\t\t\t\t}\n\n\t\t\t\t\t//return signing key to parse\n\t\t\t\t\treturn mySigningKey, nil\n\t\t\t\t})\n\n\t\t\t\t//handle err\n\t\t\t\tif parseErr != nil || !token.Valid {\n\t\t\t\t\tw.WriteHeader(403)\n\t\t\t\t\tw.Write([]byte(\"Unauthorized\"))\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t//Authorized, 200 response and serve endpoint\n\t\t\t\tw.WriteHeader(200)\n\t\t\t\tw.Write([]byte(\"Access granted\\n\"))\n\t\t\t\tendpoint(w, r)\n\t\t\t\treturn\n\n\t\t\t}\n\t\t\t//if no cookie, user does not have access\n\t\t\tw.WriteHeader(403)\n\t\t\tw.Write([]byte(\"Unauthorized\"))\n\t\t\treturn\n\n\t\t//ignore all other request methods\n\t\tdefault:\n\t\t\tw.WriteHeader(401)\n\t\t\tw.Write([]byte(\"Bad request\"))\n\t\t\treturn\n\t\t}\n\t})\n}",
"func (l Login) Authorize() {\n\t// Check if AccessToken is present\n\ttokenPresent := l.config.checkAccessToken()\n\tif tokenPresent {\n\t\t// Verify if token works.\n\t\terr := l.test()\n\t\tif err != nil {\n\t\t\tl.loginAsIntegration()\n\t\t} else { // Success!\n\t\t\treturn\n\t\t}\n\t} else { // AccessToken not present\n\t\tl.loginAsIntegration()\n\t}\n}",
"func (authService *AuthService) authorized(dbClient DBClient, sessionToken *apitypes.SessionToken,\n\tactionMask []bool, resourceId string) (bool, error) {\n\n\t/* Rules:\n\t\n\tA party can access a resource if the party,\n\t\thas an ACL entry for the resource; or,\n\t\tthe resource belongs to a repo or realm for which the party has an ACL entry.\n\t\n\tIn this context, a user is a party if the user is explicitly the party or if\n\tthe user belongs to a group that is explicitly the party.\n\t\n\tGroups may not belong to other groups.\n\t\n\tThe user must have the required access mode (CreateIn, Read, Write, Exec, Delete).\n\tNo access mode implies any other access mode.\n\tThe access modes have the following meanings:\n\t\tCreateIn - The party can create resources that will be owned by the target resource.\n\t\tRead - The party can obtain the contents of the target resource.\n\t\tWrite - The party can modify the contents of the target resource.\n\t\tExec - The party can compel SafeHarbor to perform the actions specified by\n\t\t\tthe target resource (e.g., execute a Dockerfile).\n\t\tDelete - The party can Delete the target resource.\n\t*/\n\t\n\tif sessionToken == nil { return false, utilities.ConstructServerError(\"No session token\") }\n\t\n\t// Identify the user.\n\tvar userId string = sessionToken.AuthenticatedUserid\n\tfmt.Println(\"userid=\", userId)\n\tvar user User\n\tvar err error\n\tuser, err = dbClient.dbGetUserByUserId(userId)\n\tif user == nil {\n\t\treturn false, utilities.ConstructServerError(\"user object cannot be identified from user id \" + userId)\n\t}\n\t\n\t// Special case: Allow user all capabilities for their own user object.\n\tif user.getId() == resourceId { return true, nil }\n\n\t// Verify that at most one field of the actionMask is true.\n\tvar nTrue = 0\n\tfor _, b := range actionMask {\n\t\tif b {\n\t\t\tif nTrue == 1 {\n\t\t\t\treturn false, utilities.ConstructUserError(\"More than one field in mask may not be true\")\n\t\t\t}\n\t\t\tnTrue++\n\t\t}\n\t}\n\t\n\t// Check if the user or a group that the user belongs to has the permission\n\t// that is specified by the actionMask.\n\tvar party Party = user // start with the user.\n\tvar resource Resource\n\tresource, err = dbClient.getResource(resourceId)\n\tif err != nil { return false, err }\n\tif resource == nil {\n\t\treturn false, utilities.ConstructUserError(\"Resource with Id \" + resourceId + \" not found\")\n\t}\n\tvar groupIds []string = user.getGroupIds()\n\tvar groupIndex = -1\n\tfor { // the user, and then each group that the user belongs to...\n\t\t// See if the party (user or group) has an ACL entry for the resource.\n\t\tvar partyCanAccessResourceDirectoy bool\n\t\tpartyCanAccessResourceDirectoy, err =\n\t\t\tauthService.partyHasAccess(dbClient, party, actionMask, resource)\n\t\tif err != nil { return false, err }\n\t\tif partyCanAccessResourceDirectoy { return true, nil }\n\t\t\n\t\t// See if any of the party's parent resources have access.\n\t\tvar parentId string = resource.getParentId()\n\t\tif parentId != \"\" {\n\t\t\tvar parent Resource\n\t\t\tparent, err = dbClient.getResource(parentId)\n\t\t\tif err != nil { return false, err }\n\t\t\tvar parentHasAccess bool\n\t\t\tparentHasAccess, err = authService.partyHasAccess(dbClient, party, actionMask, parent)\n\t\t\tif err != nil { return false, err }\n\t\t\tif parentHasAccess { return true, nil }\n\t\t}\n\t\t\n\t\tgroupIndex++\n\t\tif groupIndex == len(groupIds) { return false, nil }\n\t\tvar err error\n\t\tparty, err = dbClient.getParty(groupIds[groupIndex]) // check next group\n\t\tif err != nil { return false, err }\n\t}\n\treturn false, nil // no access rights found\n}",
"func (m Manager) IsAuthorized(u *common.User, actions map[string]string) bool {\n\n\treturn m.Authorization.IsAuthorized(u, actions)\n}",
"func (c *Config) Authorize(ctx context.Context, uid string, state string) (*APIResponse, error) {\n\tv := url.Values{}\n\tv.Add(\"client_id\", c.clientID)\n\tv.Add(\"client_secret\", c.clientSecret)\n\tv.Add(\"uid\", uid)\n\tv.Add(\"state\", state)\n\n\treturn c.request(ctx, \"/api_neauth\", nil, v)\n}",
"func Authorize(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\t// Get token from request\n\t// El extractor podría ser: request.AuthorizationHeaderExtractor o tal vez el personalizado TokenFromAuthHeader\n\ttoken, err := request.ParseFromRequestWithClaims(r, request.OAuth2Extractor, &models.AppClaims{}, func(token *jwt.Token) (interface{}, error) {\n\t\t// Como solo tenemos una llave pública, la devolvemos\n\t\treturn verifyKey, nil\n\t})\n\tif err != nil {\n\t\tswitch err.(type) {\n\t\tcase *jwt.ValidationError:\n\t\t\tvErr := err.(*jwt.ValidationError)\n\t\t\tswitch vErr.Errors {\n\t\t\tcase jwt.ValidationErrorExpired:\n\t\t\t\tDisplayError(w, err, \"Su token ha expirado, por favor vuelva a ingresar\", 401)\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tDisplayError(w, err, \"Error en el token de acceso.\", 500)\n\t\t\t\treturn\n\t\t\t}\n\t\tdefault:\n\t\t\tDisplayError(w, err, \"Error al procesar el token.\", 500)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif token.Valid {\n\t\tcontext.Set(r, \"user\", token.Claims.(*models.AppClaims).User)\n\t\tcontext.Set(r, \"scopes\", token.Claims.(*models.AppClaims).Scopes)\n\t\tnext(w, r)\n\t} else {\n\t\tDisplayError(w, err, \"Token de acceso inválido.\", 401)\n\t}\n}",
"func IsAllowed(ctx context.Context, req *http.Request, subject string, aclContext AccessContext) error {\n\twarden := ctx.Value(ladonWardenKey)\n\n\tif warden == nil {\n\t\treturn fmt.Errorf(\"not ACL protected\")\n\t}\n\n\tladonWarden, ok := warden.(ladon.Warden)\n\tif !ok {\n\t\treturn fmt.Errorf(\"warden is not ladon.Warden\")\n\t}\n\n\treturn ladonWarden.IsAllowed(toLadonRequest(req, subject, aclContext))\n}",
"func Allow(mode PermissionMode, roles ...string) *Permission {\n\treturn role.Allow(mode, roles...)\n}",
"func Authorize(c *gin.Context) {\n\n\tsess := models.NewSession(ginject.Deps(c))\n\n\tif err := c.Bind(sess); err != nil {\n\t\tc.AbortWithStatus(400)\n\t\treturn\n\t}\n\n\tsess.Store()\n\n\tc.Header(\"Cache-Control\", \"no-cache, no-store, must-revalidate\")\n\tc.Header(\"Pragma\", \"no-cache\")\n\tc.Header(\"Expires\", \"0\")\n\tc.Redirect(http.StatusTemporaryRedirect, \"/gui/login?sess=\"+sess.GetSessionID())\n}",
"func (c *Client) Authorize(payload *TokenRequestPayload) (string, error) {\n\tresp, err := c.RequestAuthorization(payload)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar (\n\t\tstatus string\n\t\ttrackId = resp.Result.TrackID\n\t\tappToken = resp.Result.AppToken\n\t)\n\tfor {\n\t\tresp, err := c.TrackAuthorizationProgress(trackId)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tstatus = resp.Result.Status\n\t\tif status != \"pending\" {\n\t\t\tbreak\n\t\t}\n\n\t\ttime.Sleep(2 * time.Second)\n\t}\n\n\tif status != \"granted\" {\n\t\treturn \"\", fmt.Errorf(\"invalid authorization status: %s\", status)\n\t}\n\n\tc.SetApp(payload.AppID, appToken, payload.AppVersion)\n\n\treturn appToken, nil\n}",
"func (l *Limiter) Allow(ctx context.Context) (func(rate.Op), error) {\n\tvar (\n\t\tdone func(time.Time, rate.Op)\n\t\terr error\n\t\tok bool\n\t)\n\tif done, ok = l.rate.Acquire(); !ok {\n\t\t// NOTE exceed max inflight, use queue\n\t\tif err = l.queue.Push(ctx); err != nil {\n\t\t\tdone(time.Time{}, rate.Ignore)\n\t\t\treturn func(rate.Op) {}, err\n\t\t}\n\t}\n\tstart := time.Now()\n\treturn func(op rate.Op) {\n\t\tdone(start, op)\n\t\tl.queue.Pop()\n\t}, nil\n}",
"func (self *AuthFilter) authorize(name string, req *http.Request) (*http.Cookie, bool) {\n\tif self.verify != nil && self.verify(name, req) {\n\t\treturn nil, true\n\t}\n\n\treq = self.stripReservedHeaders(req)\n\treq, cookie := self.insertSessionInfo(req)\n\tif self.sign != nil {\n\t\tself.sign(name, req)\n\t}\n\n\treturn cookie, cookie != nil\n}",
"func (_DelegatableDai *DelegatableDaiSession) Allowed(arg0 common.Address, arg1 common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.Allowed(&_DelegatableDai.CallOpts, arg0, arg1)\n}",
"func Authorized() runtime.Authorizer {\n\treturn runtime.AuthorizerFunc(func(_ *http.Request, _ interface{}) error { return nil })\n}",
"func Authorize(ee engine.Exchange) sknet.HandlerFunc {\n\treturn func(c *sknet.Context) {\n\t\tvar (\n\t\t\treq pp.EncryptReq\n\t\t\trlt *pp.EmptyRes\n\t\t)\n\n\t\tfor {\n\t\t\tif c.BindJSON(&req) == nil {\n\t\t\t\t// validate pubkey.\n\t\t\t\tif err := validatePubkey(req.GetPubkey()); err != nil {\n\t\t\t\t\tlogger.Error(err.Error())\n\t\t\t\t\trlt = pp.MakeErrResWithCode(pp.ErrCode_WrongPubkey)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tpubkey, err := cipher.PubKeyFromHex(req.GetPubkey())\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(err.Error())\n\t\t\t\t\trlt = pp.MakeErrResWithCode(pp.ErrCode_WrongPubkey)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tkey := cipher.ECDH(pubkey, ee.GetServPrivKey())\n\t\t\t\tdata, err := cipher.Chacha20Decrypt(req.GetEncryptdata(), key, req.GetNonce())\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(err.Error())\n\t\t\t\t\trlt = pp.MakeErrResWithCode(pp.ErrCode_UnAuthorized)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tok, err := regexp.MatchString(`^\\{.*\\}$`, string(data))\n\t\t\t\tif err != nil || !ok {\n\t\t\t\t\tlogger.Error(err.Error())\n\t\t\t\t\trlt = pp.MakeErrResWithCode(pp.ErrCode_UnAuthorized)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tc.Set(\"rawdata\", data)\n\n\t\t\t\tc.Next()\n\n\t\t\t\trsp, exist := c.Get(\"response\")\n\t\t\t\tif exist {\n\t\t\t\t\t// encrypt the response.\n\t\t\t\t\tencData, nonce, err := pp.Encrypt(rsp, pubkey.Hex(), ee.GetServPrivKey().Hex())\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\n\t\t\t\t\t// encryptData, nonce := mustEncryptRes(cliPubkey, ee.GetServPrivKey(), rsp)\n\t\t\t\t\tres := pp.EncryptRes{\n\t\t\t\t\t\tResult: pp.MakeResultWithCode(pp.ErrCode_Success),\n\t\t\t\t\t\tEncryptdata: encData,\n\t\t\t\t\t\tNonce: nonce,\n\t\t\t\t\t}\n\t\t\t\t\tc.JSON(res)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\trlt = pp.MakeErrRes(errors.New(\"bad request\"))\n\t\t\tbreak\n\t\t}\n\t\tc.JSON(rlt)\n\t}\n}",
"func PolicyValidate(action, path string, auth Authorization, policies []*Policy) (foundPolicy *Policy, foundRole *Role) {\n\tfor _, policy := range policies {\n\t\tif role := policy.match(action, path, auth); role != nil {\n\t\t\tif policy.IsDeny() {\n\t\t\t\treturn nil, nil\n\t\t\t} else if foundPolicy == nil {\n\t\t\t\tfoundPolicy = policy\n\t\t\t\tfoundRole = role\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}",
"func Authorizer(userService userService, jwtService jwtService) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\taccessToken := extractToken(c)\n\t\tif accessToken == EmptyToken {\n\t\t\tabort(c, http.StatusBadRequest, \"Authorization header is missing or empty\")\n\t\t} else {\n\t\t\tparseJwt, err := jwtService.ParseJwt(accessToken)\n\n\t\t\tif err != nil {\n\t\t\t\tabort(c, http.StatusBadRequest, err.Error())\n\t\t\t} else if err := userVerification(c, parseJwt, userService); err != nil {\n\t\t\t\tabort(c, http.StatusUnauthorized, \"Unauthorized\")\n\t\t\t}\n\t\t}\n\t}\n}",
"func (_DelegatableDai *DelegatableDaiCallerSession) Allowed(arg0 common.Address, arg1 common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.Allowed(&_DelegatableDai.CallOpts, arg0, arg1)\n}",
"func (l *StdLimiter) Allow(_ Event) bool {\n\tif l.rateLimiter.Allow() {\n\t\tl.allowed.Inc()\n\t\treturn true\n\t}\n\tl.dropped.Inc()\n\n\treturn false\n}",
"func (pc *Client) Authorize(authorization string) error {\n\terr := pc.sendMessage(&messages.Authorize{messages.TYPE_AUTHORIZE, authorization})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = pc.wait(messages.TYPE_AUTHORIZATION_OK)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"
] | [
"0.6413004",
"0.6292569",
"0.62202144",
"0.6180543",
"0.615048",
"0.615048",
"0.6113354",
"0.5892276",
"0.5881849",
"0.58794814",
"0.58151233",
"0.5797083",
"0.57949835",
"0.5784094",
"0.5773111",
"0.5698953",
"0.5696385",
"0.56498677",
"0.562726",
"0.55743754",
"0.5565258",
"0.55276793",
"0.552395",
"0.55109525",
"0.5492619",
"0.54838717",
"0.5465157",
"0.546196",
"0.54391456",
"0.54117584",
"0.53703827",
"0.5367941",
"0.533878",
"0.5335869",
"0.53097683",
"0.53007615",
"0.52952886",
"0.525465",
"0.5251723",
"0.52510387",
"0.5250692",
"0.5248811",
"0.5235004",
"0.52331567",
"0.52084106",
"0.51954305",
"0.5185188",
"0.51785916",
"0.51763296",
"0.5173484",
"0.51715976",
"0.516647",
"0.51633126",
"0.51593524",
"0.5149917",
"0.5149806",
"0.5142214",
"0.5140136",
"0.5136813",
"0.51330173",
"0.51321673",
"0.51172525",
"0.51026666",
"0.509427",
"0.5081115",
"0.5078902",
"0.5065156",
"0.506253",
"0.50425076",
"0.5041818",
"0.5034143",
"0.502873",
"0.5010239",
"0.5004898",
"0.500135",
"0.49977776",
"0.49799037",
"0.49719843",
"0.49702743",
"0.49676335",
"0.49649182",
"0.4948439",
"0.49484086",
"0.4945862",
"0.49435183",
"0.49425808",
"0.49390483",
"0.49245137",
"0.49213213",
"0.49182504",
"0.49118507",
"0.49066362",
"0.4903591",
"0.48901397",
"0.48887134",
"0.48874724",
"0.48861933",
"0.488486",
"0.48847017",
"0.48755187"
] | 0.7368123 | 0 |
FPDF_CloseDocument closes the references, releases the resources. | func (p *PdfiumImplementation) FPDF_CloseDocument(request *requests.FPDF_CloseDocument) (*responses.FPDF_CloseDocument, error) {
p.Lock()
defer p.Unlock()
nativeDocument, err := p.getDocumentHandle(request.Document)
if err != nil {
return nil, err
}
err = nativeDocument.Close()
if err != nil {
return nil, err
}
delete(p.documentRefs, nativeDocument.nativeRef)
return &responses.FPDF_CloseDocument{}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (x *PDFDocument) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (f *Footer) Close() error {\n\tf.DecRef()\n\treturn nil\n}",
"func (x *FzDocument) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (a *PDFApiService) ClosePDF(ctx _context.Context, pdfCloseDocumentParameters PdfCloseDocumentParameters) (PdfCloseDocumentResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue PdfCloseDocumentResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/pdf/ClosePDF\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json-patch+json\", \"application/json\", \"text/json\", \"application/_*+json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &pdfCloseDocumentParameters\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v PdfCloseDocumentResponse\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}",
"func (x *FzDocumentWriter) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzDocumentHandler) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (p *PdfiumImplementation) FPDF_ClosePage(request *requests.FPDF_ClosePage) (*responses.FPDF_ClosePage, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageRef, err := p.getPageHandle(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpageRef.Close()\n\tdelete(p.pageRefs, request.Page)\n\n\t// Remove page reference from document.\n\tdocumentHandle, err := p.getDocumentHandle(pageRef.documentRef)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdelete(documentHandle.pageRefs, request.Page)\n\n\treturn &responses.FPDF_ClosePage{}, nil\n}",
"func (x *PDFDocEvent) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (*XMLDocument) Close() {\n\tmacro.Rewrite(\"$_.close()\")\n}",
"func (x *PDFXref) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (s *Basegff3Listener) ExitDocument(ctx *DocumentContext) {}",
"func (p *PdfiumImplementation) FPDFLink_CloseWebLinks(request *requests.FPDFLink_CloseWebLinks) (*responses.FPDFLink_CloseWebLinks, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageLinkhandle, err := p.getPageLinkHandle(request.PageLink)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdocumentHandle, err := p.getDocumentHandle(pageLinkhandle.documentRef)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tC.FPDFLink_CloseWebLinks(pageLinkhandle.handle)\n\n\t// Cleanup refs\n\tdelete(p.pageLinkRefs, pageLinkhandle.nativeRef)\n\tdelete(documentHandle.pageLinkRefs, pageLinkhandle.nativeRef)\n\n\treturn &responses.FPDFLink_CloseWebLinks{}, nil\n}",
"func (p *PdfiumImplementation) FPDFText_ClosePage(request *requests.FPDFText_ClosePage) (*responses.FPDFText_ClosePage, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\ttextPageHandle, err := p.getTextPageHandle(request.TextPage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdocumentHandle, err := p.getDocumentHandle(textPageHandle.documentRef)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tC.FPDFText_ClosePage(textPageHandle.handle)\n\n\t// Cleanup refs\n\tdelete(p.textPageRefs, textPageHandle.nativeRef)\n\tdelete(documentHandle.textPageRefs, textPageHandle.nativeRef)\n\n\treturn &responses.FPDFText_ClosePage{}, nil\n}",
"func (p *bytesViewer) Close() error { return nil }",
"func (f *Font) Close() {\n\tC.TTF_CloseFont(f.f)\n\tf.f = nil\n}",
"func (f *factory) Close() error {\n\tif f.closed.CAS(false, true) {\n\t\tf.mutex.Lock()\n\t\tdefer f.mutex.Unlock()\n\n\t\tfor _, page := range f.pages {\n\t\t\tif err := page.Close(); err != nil {\n\t\t\t\tpageLogger.Error(\"close mapped page data err\",\n\t\t\t\t\tlogger.String(\"path\", f.path), logger.Error(err))\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}",
"func (x *PDFPage) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFMailDocEvent) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (d *Detector) Close() {\n\tC.fvad_free(d.fvad)\n\td.fvad = nil\n}",
"func (doc *Doc) Close() {\n\tdoc.resp.Body.Close()\n}",
"func (d *Document) Close() {\n\tdefaultPool.Put(d)\n}",
"func (x *PDFXrefSubsec) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFCsi) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (m *wasiSnapshotPreview1Impl) fdClose(pfd wasiFd) (err wasiErrno) {\n\tf, err := m.files.acquireFile(pfd, 0)\n\tif err != wasiErrnoSuccess {\n\t\treturn err\n\t}\n\tdefer m.files.releaseFile(pfd, f)\n\n\tif err := f.f.Close(); err != nil {\n\t\treturn fileErrno(err)\n\t}\n\n\tf.open = false\n\treturn wasiErrnoSuccess\n}",
"func (x *PDFFontDesc) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzDocumentHandlerContext) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (w *writer) Close() error {\n\tfor name, file := range w.files {\n\t\tif file != nil {\n\t\t\tfile.Close()\n\t\t\tdelete(w.files, name)\n\t\t}\n\t}\n\treturn nil\n}",
"func (xs *Stylesheet) Close() {\n\tif xs.ptr != nil {\n\t\tC.free_style(&xs.ptr)\n\t\txs.ptr = nil\n\t}\n}",
"func (x *PDFXrefEntry) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (p *PdfiumImplementation) FPDFText_FindClose(request *requests.FPDFText_FindClose) (*responses.FPDFText_FindClose, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tsearchHandle, err := p.getSearchHandle(request.Search)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdocumentHandle, err := p.getDocumentHandle(searchHandle.documentRef)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tC.FPDFText_FindClose(searchHandle.handle)\n\n\t// Cleanup refs\n\tdelete(p.searchRefs, searchHandle.nativeRef)\n\tdelete(documentHandle.searchRefs, searchHandle.nativeRef)\n\n\treturn &responses.FPDFText_FindClose{}, nil\n}",
"func (dv DomVisit) Close() {\n\tif dv.badFile != nil {\n\t\terr := dv.badFile.Close()\n\t\tcheck(err)\n\t}\n}",
"func (x *PDFWidget) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (w *Writer) Close() error {\n\tif _, err := io.WriteString(w.w, \"</table:table>\\n</office:spreadsheet></office:body></office:document-content>\"); err != nil {\n\t\treturn err\n\t}\n\tif err := w.bw.Flush(); err != nil {\n\t\treturn err\n\t}\n\tif err := w.zw.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := w.bzw.Flush(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func FileClose(f *os.File,) error",
"func (x *PDFDaInfo) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func freeDocPtr(xmlHandler *XmlHandler) {\n\tif xmlHandler.docPtr != nil {\n\t\tC.xmlFreeDoc(xmlHandler.docPtr)\n\t}\n}",
"func (x *PDFPattern) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFRange) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFXobject) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (s *SimPDF) Finish(fileOutput string) {\n\tif internal.ValidateFilePath(fileOutput) {\n\t\tinternal.MoveFilePath(fileOutput, fileOutput+\".bak\")\n\t}\n\ts.PDF.OutputFileAndClose(fileOutput)\n}",
"func (it *BaseContentSpaceCreateLibraryIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}",
"func (x *PDFAnnot) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (f *FilesTarget) Close() error {\n\treturn nil\n}",
"func (ff failingFile) Close() error {\n\treturn nil\n}",
"func (x *PDFObj) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFProcessor) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFWriteOptions) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFXrange) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFSigner) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFHotspot) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (r *MMapRef) Close() error { return r.DecRef() }",
"func (p *Packer) Close() error {\n\tp.writeFooter()\n\treturn p.outFile.Close()\n}",
"func (x *FzText) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFCmap) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (w *Reflow) Close() error {\n\tw.addWord()\n\treturn nil\n}",
"func (x *PDFLaunchUrlEvent) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (it *BaseLibraryContentObjectDeletedIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}",
"func (x *FzStextPage) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFJs) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFDesignatedName) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFUnsavedSig) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFRevPageMap) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (rf *reverseFile) Release() {\n\trf.fd.Close()\n}",
"func (x *PDFPortfolioSchema) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (cfp *FsPool) Close() error {\n\tif cfp.reader != nil {\n\t\terr := cfp.reader.Close()\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\n\t\tcfp.reader = nil\n\t\tcfp.fileIndex = -1\n\t}\n\n\treturn nil\n}",
"func (x *PDFSubmitEvent) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzXml) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (b *bookMark) close() error {\n\treturn b.file.Close()\n}",
"func (q *queue) Close() {\n\tif q.closed.CAS(false, true) {\n\t\tq.rwMutex.RLock()\n\t\tdefer q.rwMutex.RUnlock()\n\n\t\tq.notEmpty.Broadcast()\n\n\t\tif q.dataPageFct != nil {\n\t\t\tif err := q.dataPageFct.Close(); err != nil {\n\t\t\t\tqueueLogger.Error(\"close data page factory error\",\n\t\t\t\t\tlogger.String(\"queue\", q.dirPath), logger.Error(err))\n\t\t\t}\n\t\t}\n\n\t\tif q.indexPageFct != nil {\n\t\t\tif err := q.indexPageFct.Close(); err != nil {\n\t\t\t\tqueueLogger.Error(\"close index page factory error\",\n\t\t\t\t\tlogger.String(\"queue\", q.dirPath), logger.Error(err))\n\t\t\t}\n\t\t}\n\n\t\tif q.metaPageFct != nil {\n\t\t\tif err := q.metaPageFct.Close(); err != nil {\n\t\t\t\tqueueLogger.Error(\"close meta page factory error\",\n\t\t\t\t\tlogger.String(\"queue\", q.dirPath), logger.Error(err))\n\t\t\t}\n\t\t}\n\t}\n}",
"func(this*Window)Close()error{\n\n\n/*23:*/\n\n\n//line goacme.w:312\n\nfor _,v:=range this.files{\nv.Close()\n}\n\n\n\n/*:23*/\n\n\n\n/*31:*/\n\n\n//line goacme.w:396\n\nif this.next!=nil{\nthis.next.prev= this.prev\n}\nif this.prev!=nil{\nthis.prev.next= this.next\n}\nif fwin==this{\nfwin= this.next\n}\nif lwin==this{\nlwin= this.prev\n}\n\n\n\n/*:31*/\n\n\n//line goacme.w:190\n\nreturn nil\n}",
"func (ddw *downloadWriter) Close() error {\n\tddw.mu.Lock()\n\tif ddw.closed {\n\t\tddw.mu.Unlock()\n\t\treturn errClosedStream\n\t}\n\tddw.closed = true\n\tfor i := range ddw.writeSignals {\n\t\tddw.writeSignals[i].Unlock()\n\t}\n\tddw.mu.Unlock()\n\treturn nil\n}",
"func (w *FormSerializationWriter) Close() error {\n\tw.writer = make([]string, 0)\n\treturn nil\n}",
"func (x *PDFMrange) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (f *FileBlob) Free() {\n\tf.blob = nil\n}",
"func (it *BaseLibraryContentObjectCreatedIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}",
"func (fr *FormatReaders) Close() (rtnerr error) {\n\tvar err error\n\tfor i := len(fr.readers) - 1; i >= 0; i-- {\n\t\terr = fr.readers[i].rdr.Close()\n\t\tif err != nil {\n\t\t\trtnerr = err // tracking last error\n\t\t}\n\t}\n\treturn rtnerr\n}",
"func (x *PDFUiEvent) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func Close() {\n\tglobalBufferSize = 0\n\tglobalSoundBuffer.Release()\n\tglobalPrimarySoundBuffer.Release()\n\tglobalDirectSoundObject.Release()\n}",
"func (x *FzFont) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFPortfolio) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (it *BucketDeleteFileIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}",
"func (ff *File) Close() error {\n\treturn nil\n}",
"func (it *BaseContentSpaceSetFactoryIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}",
"func (it *BaseLibraryVersionDeleteIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}",
"func (c *Definition) Close() error {\n\treturn nil\n}",
"func (b *RFCTextReader) Close() (err error) {\n\treturn b.fp.Close()\n}",
"func (x *FzPage) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (it *DospaymentLogRecordServiceFeeIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}",
"func (it *DospaymentLogClaimGuardianFeeIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}",
"func (r *ImageRef) Close() {\n\tr.lock.Lock()\n\n\tif r.image != nil {\n\t\tclearImage(r.image)\n\t\tr.image = nil\n\t}\n\n\tr.buf = nil\n\n\tr.lock.Unlock()\n}",
"func (x *FzTextSpan) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (xlsxw *XLSXWriter) Close(ctx context.Context) error {\n\tif xlsxw.closer != nil {\n\t\terrFl := xlsxw.bWr.Flush()\n\t\terrCl := xlsxw.closer.Close()\n\t\txlsxw.closer = nil\n\n\t\tif errCl != nil {\n\t\t\treturn errCl\n\t\t}\n\n\t\treturn errFl\n\t}\n\treturn errors.New(\"already closed\")\n\n}",
"func (r *XmlReader) Close() {\n\t// TODO: implement\n}",
"func (x *FzBandWriter) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (c FinalOutput) Close() {}",
"func (it *DospaymentLogRefundServiceFeeIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}",
"func (x *FzZipWriter) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (f *File) Close() {\n\tf.handleConcatenatedFiles()\n\tif f.AddInitPy {\n\t\tif err := f.AddInitPyFiles(); err != nil {\n\t\t\tlog.Fatalf(\"%s\", err)\n\t\t}\n\t}\n\tif err := f.w.Close(); err != nil {\n\t\tlog.Fatalf(\"Failed to finalise zip file: %s\", err)\n\t}\n\tif err := f.f.Close(); err != nil {\n\t\tlog.Fatalf(\"Failed to close file: %s\", err)\n\t}\n}",
"func (it *DospaymentLogChargeServiceFeeIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}",
"func (x *FzDocument) Ref() *C.fz_document {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.fz_document)(unsafe.Pointer(x))\n}"
] | [
"0.65311474",
"0.62416846",
"0.6237712",
"0.6122228",
"0.59698606",
"0.5922102",
"0.59170103",
"0.58661354",
"0.58297205",
"0.5796815",
"0.5761358",
"0.5754477",
"0.5621453",
"0.56127256",
"0.5612088",
"0.55945224",
"0.55742735",
"0.5561048",
"0.5556309",
"0.5467746",
"0.5445313",
"0.54276764",
"0.53831214",
"0.5378524",
"0.53508055",
"0.53173894",
"0.530385",
"0.5275133",
"0.52690446",
"0.5261585",
"0.5248509",
"0.52240014",
"0.52029055",
"0.5193905",
"0.51924294",
"0.51832277",
"0.5173394",
"0.5162265",
"0.51097673",
"0.51017755",
"0.50908446",
"0.5076766",
"0.50624615",
"0.5050242",
"0.50475264",
"0.5032276",
"0.5026569",
"0.50253695",
"0.5016121",
"0.50085646",
"0.5007586",
"0.4995034",
"0.4992039",
"0.4987204",
"0.4985384",
"0.49799573",
"0.49791574",
"0.49790323",
"0.49781597",
"0.49755377",
"0.49743924",
"0.49690303",
"0.49558148",
"0.49497128",
"0.493927",
"0.49368382",
"0.49020356",
"0.4896043",
"0.4889647",
"0.48835963",
"0.4877791",
"0.48637807",
"0.48636913",
"0.48557243",
"0.4850617",
"0.48496145",
"0.48424825",
"0.48423988",
"0.48420337",
"0.48416683",
"0.48253855",
"0.4819718",
"0.48102716",
"0.4808436",
"0.48025927",
"0.48017508",
"0.4799355",
"0.47938505",
"0.47922024",
"0.4771407",
"0.47575992",
"0.47495887",
"0.474191",
"0.47409153",
"0.47400585",
"0.4738312",
"0.4735944",
"0.4734441",
"0.47324234",
"0.47303513"
] | 0.7135864 | 0 |
FPDF_SetSandBoxPolicy set the policy for the sandbox environment. | func (p *PdfiumImplementation) FPDF_SetSandBoxPolicy(request *requests.FPDF_SetSandBoxPolicy) (*responses.FPDF_SetSandBoxPolicy, error) {
p.Lock()
defer p.Unlock()
enable := C.int(0)
if request.Enable {
enable = C.int(1)
}
C.FPDF_SetSandBoxPolicy(C.FPDF_DWORD(request.Policy), enable)
return &responses.FPDF_SetSandBoxPolicy{}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func SetPolicy(w http.ResponseWriter, policy Policy, domain string) {\n\tb, err := json.Marshal(policy)\n\tif err != nil {\n\t\tb, err = json.Marshal(defaultPolicy)\n\t}\n\tpath := \"/\"\n\thttpOnly := false\n\tset(w, cookiesPolicyCookieKey, string(b), domain, path, maxAgeOneYear, http.SameSiteLaxMode, httpOnly)\n}",
"func (m *BookingBusiness) SetSchedulingPolicy(value BookingSchedulingPolicyable)() {\n err := m.GetBackingStore().Set(\"schedulingPolicy\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (_PermInterface *PermInterfaceTransactor) SetPolicy(opts *bind.TransactOpts, _nwAdminOrg string, _nwAdminRole string, _oAdminRole string) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"setPolicy\", _nwAdminOrg, _nwAdminRole, _oAdminRole)\n}",
"func (m *InformationProtection) SetPolicy(value InformationProtectionPolicyable)() {\n err := m.GetBackingStore().Set(\"policy\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (win *Window) SetPolicy(allowShrink, allowGrow, autoShrink int) {\n\twin.Candy().Guify(\"gtk_window_set_policy\", win, allowShrink, allowGrow, autoShrink)\n}",
"func (s *Sanitizer) SetPolicy(name string, policy *bluemonday.Policy) {\n\ts.policy[name] = policy\n}",
"func (sys *IAMSys) PolicyDBSet(name, policy string) error {\n\tobjectAPI := newObjectLayerFn()\n\tif objectAPI == nil {\n\t\treturn errServerNotInitialized\n\t}\n\n\tsys.Lock()\n\tdefer sys.Unlock()\n\n\treturn sys.policyDBSet(objectAPI, name, policy, false)\n}",
"func (s *peerRESTServer) SetBucketPolicyHandler(w http.ResponseWriter, r *http.Request) {\n\tif !s.IsValid(w, r) {\n\t\ts.writeErrorResponse(w, errors.New(\"Invalid request\"))\n\t\treturn\n\t}\n\n\tvars := mux.Vars(r)\n\tbucketName := vars[peerRESTBucket]\n\tif bucketName == \"\" {\n\t\ts.writeErrorResponse(w, errors.New(\"Bucket name is missing\"))\n\t\treturn\n\t}\n\tvar policyData policy.Policy\n\tif r.ContentLength < 0 {\n\t\ts.writeErrorResponse(w, errInvalidArgument)\n\t\treturn\n\t}\n\n\terr := gob.NewDecoder(r.Body).Decode(&policyData)\n\tif err != nil {\n\t\ts.writeErrorResponse(w, err)\n\t\treturn\n\t}\n\tglobalPolicySys.Set(bucketName, policyData)\n\tw.(http.Flusher).Flush()\n}",
"func (o *NewLoyaltyProgram) SetSandbox(v bool) {\n\to.Sandbox = v\n}",
"func (sys *IAMSys) SetPolicy(policyName string, p iampolicy.Policy) error {\n\tobjectAPI := newObjectLayerFn()\n\tif objectAPI == nil {\n\t\treturn errServerNotInitialized\n\t}\n\n\tif p.IsEmpty() || policyName == \"\" {\n\t\treturn errInvalidArgument\n\t}\n\n\tpath := getPolicyDocPath(policyName)\n\tvar err error\n\tif globalEtcdClient != nil {\n\t\terr = saveIAMConfigItemEtcd(context.Background(), p, path)\n\t} else {\n\t\terr = saveIAMConfigItem(objectAPI, p, path)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsys.Lock()\n\tdefer sys.Unlock()\n\n\tsys.iamPolicyDocsMap[policyName] = p\n\n\treturn nil\n}",
"func (sys *IAMSys) policyDBSet(objectAPI ObjectLayer, name, policy string, isSTS bool) error {\n\tif name == \"\" || policy == \"\" {\n\t\treturn errInvalidArgument\n\t}\n\n\tif _, ok := sys.iamUsersMap[name]; !ok {\n\t\treturn errNoSuchUser\n\t}\n\n\t_, ok := sys.iamPolicyDocsMap[policy]\n\tif !ok {\n\t\treturn errNoSuchPolicy\n\t}\n\n\tmp := newMappedPolicy(policy)\n\t_, ok = sys.iamUsersMap[name]\n\tif !ok {\n\t\treturn errNoSuchUser\n\t}\n\tvar err error\n\tmappingPath := getMappedPolicyPath(name, isSTS)\n\tif globalEtcdClient != nil {\n\t\terr = saveIAMConfigItemEtcd(context.Background(), mp, mappingPath)\n\t} else {\n\t\terr = saveIAMConfigItem(objectAPI, mp, mappingPath)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tsys.iamUserPolicyMap[name] = mp\n\treturn nil\n}",
"func (ps *PolicyStore) SetPolicy(p *Policy) error {\n\tdefer metrics.MeasureSince([]string{\"policy\", \"set_policy\"}, time.Now())\n\tif p.Name == \"\" {\n\t\treturn fmt.Errorf(\"policy name missing\")\n\t}\n\tif strutil.StrListContains(immutablePolicies, p.Name) {\n\t\treturn fmt.Errorf(\"cannot update %s policy\", p.Name)\n\t}\n\n\treturn ps.setPolicyInternal(p)\n}",
"func (_PermInterface *PermInterfaceSession) SetPolicy(_nwAdminOrg string, _nwAdminRole string, _oAdminRole string) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.SetPolicy(&_PermInterface.TransactOpts, _nwAdminOrg, _nwAdminRole, _oAdminRole)\n}",
"func (o *BlockBasedTableOptions) SetFilterPolicy(fp *FilterPolicy) {\n\tC.rocksdb_block_based_options_set_filter_policy(o.c, fp.policy)\n\to.fp = fp.policy\n}",
"func postPolicy(value string) PostOption {\n\treturn setMultipartField(\"policy\", value)\n}",
"func setPolicy(crmService *cloudresourcemanager.Service, projectID string, policy *cloudresourcemanager.Policy) {\n\n\tctx := context.Background()\n\n\tctx, cancel := context.WithTimeout(ctx, time.Second*10)\n\tdefer cancel()\n\trequest := new(cloudresourcemanager.SetIamPolicyRequest)\n\trequest.Policy = policy\n\tpolicy, err := crmService.Projects.SetIamPolicy(projectID, request).Do()\n\tif err != nil {\n\t\tlog.Fatalf(\"Projects.SetIamPolicy: %v\", err)\n\t}\n}",
"func newPolicy() *Policy {\n\tp := &Policy{ContractMD: *interop.NewContractMD(policyName)}\n\n\tp.ContractID = policyContractID\n\tp.Manifest.Features |= smartcontract.HasStorage\n\n\tdesc := newDescriptor(\"getMaxTransactionsPerBlock\", smartcontract.IntegerType)\n\tmd := newMethodAndPrice(p.getMaxTransactionsPerBlock, 1000000, smartcontract.AllowStates)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"getMaxBlockSize\", smartcontract.IntegerType)\n\tmd = newMethodAndPrice(p.getMaxBlockSize, 1000000, smartcontract.AllowStates)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"getFeePerByte\", smartcontract.IntegerType)\n\tmd = newMethodAndPrice(p.getFeePerByte, 1000000, smartcontract.AllowStates)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"getBlockedAccounts\", smartcontract.ArrayType)\n\tmd = newMethodAndPrice(p.getBlockedAccounts, 1000000, smartcontract.AllowStates)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"getMaxBlockSystemFee\", smartcontract.IntegerType)\n\tmd = newMethodAndPrice(p.getMaxBlockSystemFee, 1000000, smartcontract.AllowStates)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"setMaxBlockSize\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"value\", smartcontract.IntegerType))\n\tmd = newMethodAndPrice(p.setMaxBlockSize, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"setMaxTransactionsPerBlock\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"value\", smartcontract.IntegerType))\n\tmd = newMethodAndPrice(p.setMaxTransactionsPerBlock, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"setFeePerByte\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"value\", smartcontract.IntegerType))\n\tmd = newMethodAndPrice(p.setFeePerByte, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"setMaxBlockSystemFee\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"value\", smartcontract.IntegerType))\n\tmd = newMethodAndPrice(p.setMaxBlockSystemFee, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"blockAccount\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"account\", smartcontract.Hash160Type))\n\tmd = newMethodAndPrice(p.blockAccount, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"unblockAccount\", smartcontract.BoolType,\n\t\tmanifest.NewParameter(\"account\", smartcontract.Hash160Type))\n\tmd = newMethodAndPrice(p.unblockAccount, 3000000, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"name\", smartcontract.StringType)\n\tmd = newMethodAndPrice(nameMethod(policyName), 0, smartcontract.NoneFlag)\n\tp.AddMethod(md, desc, true)\n\n\tdesc = newDescriptor(\"onPersist\", smartcontract.VoidType)\n\tmd = newMethodAndPrice(getOnPersistWrapper(p.OnPersist), 0, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\n\tdesc = newDescriptor(\"postPersist\", smartcontract.VoidType)\n\tmd = newMethodAndPrice(getOnPersistWrapper(postPersistBase), 0, smartcontract.AllowModifyStates)\n\tp.AddMethod(md, desc, false)\n\treturn p\n}",
"func (_PermInterface *PermInterfaceTransactorSession) SetPolicy(_nwAdminOrg string, _nwAdminRole string, _oAdminRole string) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.SetPolicy(&_PermInterface.TransactOpts, _nwAdminOrg, _nwAdminRole, _oAdminRole)\n}",
"func (m *GroupPolicyDefinition) SetPolicyType(value *GroupPolicyType)() {\n err := m.GetBackingStore().Set(\"policyType\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (swagger *MgwSwagger) SetSandboxEndpoints(sandboxEndpoints []Endpoint) {\n\tswagger.sandboxEndpoints = generateEndpointCluster(constants.SandClustersConfigNamePrefix, sandboxEndpoints, constants.LoadBalance)\n}",
"func (b *ChaincodeDataBuilder) Policy(value string) *ChaincodeDataBuilder {\n\tb.policy = value\n\treturn b\n}",
"func TestPutBucketPolicyHandler(t *testing.T) {\n\tExecObjectLayerAPITest(t, testPutBucketPolicyHandler, []string{\"PutBucketPolicy\"})\n}",
"func (c *Client) SetPolicyOverride(override bool) {\n\tc.modifyLock.Lock()\n\tdefer c.modifyLock.Unlock()\n\tc.policyOverride = override\n}",
"func StackPolicyBody(policyBody string) func(*cfn.UpdateStackInput) {\n\treturn func(params *cfn.UpdateStackInput) {\n\t\tparams.StackPolicyBody = aws.String(policyBody)\n\t}\n}",
"func (c *Client) SetPolicy(ctx context.Context, p *Policy) (*Policy, error) {\n\tcurrentPolicy, err := c.GetPolicy(ctx, p.Resource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.Etag = currentPolicy.Etag\n\tp.Version = p.Resource.IAMPolicyVersion()\n\tm, err := p.Encode()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb, err := json.Marshal(m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := dcl.SendRequest(ctx, c.Config, \"POST\", p.Resource.SetPolicyURL(c.Config.BasePath), bytes.NewBuffer(b), c.Config.RetryProvider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Response.Body.Close()\n\trespB, err := ioutil.ReadAll(resp.Response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(respB, p)\n\treturn p, err\n}",
"func (m *DeviceCompliancePolicySettingStateSummary) SetPolicyType(value *string)() {\n err := m.GetBackingStore().Set(\"policyType\", value)\n if err != nil {\n panic(err)\n }\n}",
"func NewStsPolicy()(*StsPolicy) {\n m := &StsPolicy{\n PolicyBase: *NewPolicyBase(),\n }\n odataTypeValue := \"#microsoft.graph.stsPolicy\";\n m.SetOdataType(&odataTypeValue);\n return m\n}",
"func (m *DeviceHealthAttestationState) SetDataExcutionPolicy(value *string)() {\n err := m.GetBackingStore().Set(\"dataExcutionPolicy\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (a *API) SetTestMode(t bool) {\n\ta.Sandbox = t\n}",
"func (c *ContainerClient) SetAccessPolicy(ctx context.Context, o *ContainerSetAccessPolicyOptions) (ContainerSetAccessPolicyResponse, error) {\n\taccessPolicy, mac, lac := o.format()\n\tresp, err := c.client.SetAccessPolicy(ctx, accessPolicy, mac, lac)\n\n\treturn toContainerSetAccessPolicyResponse(resp), handleError(err)\n}",
"func (l *client) NewSandbox() *Sandbox {\n\ts := &Sandbox{}\n\ts.client = l\n\ts.Config = make(map[string]string)\n\ts.NetworkConfig.Mode = NetworkNone\n\ts.NetworkConfig.ModeData = make(map[string]string)\n\n\treturn s\n}",
"func (policy *PolicySvc) SetConfig(config common.ServiceConfig) error {\n\t// TODO this is a copy-paste of topology service, to refactor\n\tlog.Println(config)\n\tpolicy.config = config\n\t//\tstoreConfig := config.ServiceSpecific[\"store\"].(map[string]interface{})\n\tlog.Printf(\"Policy port: %d\", config.Common.Api.Port)\n\tpolicy.store = policyStore{}\n\tstoreConfig := config.ServiceSpecific[\"store\"].(map[string]interface{})\n\tpolicy.store.ServiceStore = &policy.store\n\treturn policy.store.SetConfig(storeConfig)\n}",
"func PolicyPOST(g *gin.Context) {\n\tpolicy := g.PostForm(\"policy\")\n\tif policy == model.POLICY_UPLOAD || policy == model.POLICY_SAVE {\n\t\tconf.VISUAL_NAVIGATION_MOD_POLICY = policy\n\t\tg.JSON(http.StatusOK, gin.H{\"messge\": \"OK\"})\n\t\treturn\n\t}\n\tg.JSON(http.StatusInternalServerError, gin.H{\"message\": fmt.Sprintf(\"policy %s not support\", policy)})\n}",
"func (_mr *MockECRAPIMockRecorder) SetRepositoryPolicy(arg0 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCall(_mr.mock, \"SetRepositoryPolicy\", arg0)\n}",
"func Test_BucketPolicySample_1(t *testing.T) {\n\tsc := NewS3()\n\terr := sc.PutObject(TEST_BUCKET, TEST_KEY, TEST_VALUE)\n\tif err != nil {\n\t\tt.Fatal(\"PutObject err:\", err)\n\t}\n\n\t//Anonymous to get\n\turl := \"http://\" + *sc.Client.Config.Endpoint + string(os.PathSeparator) + TEST_BUCKET + string(os.PathSeparator) + TEST_KEY\n\tstatusCode, _, err := HTTPRequestToGetObject(url)\n\tif err != nil {\n\t\tt.Fatal(\"GetObject err:\", err)\n\t}\n\t//StatusCode should be AccessDenied\n\tif statusCode != http.StatusForbidden {\n\t\tt.Fatal(\"StatusCode should be AccessDenied(403), but the code is:\", statusCode)\n\t}\n\n\terr = sc.PutBucketPolicy(TEST_BUCKET, GetObjectPolicy_1)\n\tif err != nil {\n\t\tt.Fatal(\"PutBucketPolicy err:\", err)\n\t}\n\n\tpolicy, err := sc.GetBucketPolicy(TEST_BUCKET)\n\tif err != nil {\n\t\tt.Fatal(\"GetBucketPolicy err:\", err)\n\t}\n\tt.Log(\"Bucket policy:\", Format(policy))\n\n\t// After set policy\n\tstatusCode, data, err := HTTPRequestToGetObject(url)\n\tif err != nil {\n\t\tt.Fatal(\"GetObject err:\", err)\n\t}\n\t//StatusCode should be STATUS_OK\n\tif statusCode != http.StatusOK {\n\t\tt.Fatal(\"StatusCode should be STATUS_OK(200), but the code is:\", statusCode)\n\t}\n\tt.Log(\"Get object value:\", string(data))\n\n\terr = sc.DeleteBucketPolicy(TEST_BUCKET)\n\tif err != nil {\n\t\tt.Fatal(\"DeleteBucketPolicy err:\", err)\n\t}\n\n\t//After delete policy\n\tstatusCode, _, err = HTTPRequestToGetObject(url)\n\tif err != nil {\n\t\tt.Fatal(\"GetObject err:\", err)\n\t}\n\t//StatusCode should be AccessDenied\n\tif statusCode != http.StatusForbidden {\n\t\tt.Fatal(\"StatusCode should be AccessDenied(403), but the code is:\", statusCode)\n\t}\n\n\terr = sc.DeleteObject(TEST_BUCKET, TEST_KEY)\n\tif err != nil {\n\t\tt.Fatal(\"DeleteObject err:\", err)\n\t}\n}",
"func mainAdminPolicySet(ctx *cli.Context) error {\n\tcheckAdminPolicySetSyntax(ctx)\n\n\tconsole.SetColor(\"PolicyMessage\", color.New(color.FgGreen))\n\tconsole.SetColor(\"Policy\", color.New(color.FgBlue))\n\n\t// Get the alias parameter from cli\n\targs := ctx.Args()\n\taliasedURL := args.Get(0)\n\tpolicyName := args.Get(1)\n\tentityArg := args.Get(2)\n\n\tuserOrGroup, isGroup, e1 := parseEntityArg(entityArg)\n\tfatalIf(probe.NewError(e1).Trace(args...), \"Bad last argument\")\n\n\t// Create a new MinIO Admin Client\n\tclient, err := newAdminClient(aliasedURL)\n\tfatalIf(err, \"Unable to initialize admin connection.\")\n\n\te := client.SetPolicy(policyName, userOrGroup, isGroup)\n\n\tif e == nil {\n\t\tprintMsg(userPolicyMessage{\n\t\t\top: \"set\",\n\t\t\tPolicy: policyName,\n\t\t\tUserOrGroup: userOrGroup,\n\t\t\tIsGroup: isGroup,\n\t\t})\n\t} else {\n\t\tfatalIf(probe.NewError(e), \"Cannot set the policy\")\n\t}\n\treturn nil\n}",
"func TestPolicyWithoutConfig(t *testing.T) {\n\tt.Skip(\"Skip test that is causing unrelated tests to fail - pulumi/pulumi#4149\")\n\n\te := ptesting.NewEnvironment(t)\n\tdefer func() {\n\t\tif !t.Failed() {\n\t\t\te.DeleteEnvironment()\n\t\t}\n\t}()\n\n\t// Confirm we have credentials.\n\tif os.Getenv(\"PULUMI_ACCESS_TOKEN\") == \"\" {\n\t\tt.Fatal(\"PULUMI_ACCESS_TOKEN not found, aborting tests.\")\n\t}\n\n\tname, _ := e.RunCommand(\"pulumi\", \"whoami\")\n\torgName := strings.TrimSpace(name)\n\n\t// Pack and push a Policy Pack for the organization.\n\tpolicyPackName := fmt.Sprintf(\"%s-%x\", \"test-policy-pack\", time.Now().UnixNano())\n\te.ImportDirectory(\"policy_pack_wo_config\")\n\te.RunCommand(\"yarn\", \"install\")\n\tt.Setenv(\"TEST_POLICY_PACK\", policyPackName)\n\n\t// Publish the Policy Pack twice.\n\te.RunCommand(\"pulumi\", \"policy\", \"publish\", orgName)\n\te.RunCommand(\"pulumi\", \"policy\", \"publish\", orgName)\n\n\t// Check the policy ls commands.\n\tpacksOutput, _ := e.RunCommand(\"pulumi\", \"policy\", \"ls\", \"--json\")\n\tvar packs []policyPacksJSON\n\tassertJSON(e, packsOutput, &packs)\n\n\tgroupsOutput, _ := e.RunCommand(\"pulumi\", \"policy\", \"group\", \"ls\", \"--json\")\n\tvar groups []policyGroupsJSON\n\tassertJSON(e, groupsOutput, &groups)\n\n\t// Enable, Disable and then Delete the Policy Pack.\n\te.RunCommand(\"pulumi\", \"policy\", \"enable\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName), \"1\")\n\te.RunCommand(\"pulumi\", \"policy\", \"disable\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName), \"--version=1\")\n\n\t// Enable and Disable without specifying the version number.\n\te.RunCommand(\"pulumi\", \"policy\", \"enable\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName), \"latest\")\n\te.RunCommand(\"pulumi\", \"policy\", \"disable\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName))\n\n\te.RunCommand(\"pulumi\", \"policy\", \"rm\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName), \"1\")\n\te.RunCommand(\"pulumi\", \"policy\", \"rm\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName), \"all\")\n}",
"func SetMemPolicy(mode int, nodemask Bitmask) error {\n\treturn syscall.ENOSYS\n}",
"func (m *InformationProtection) SetSensitivityPolicySettings(value SensitivityPolicySettingsable)() {\n err := m.GetBackingStore().Set(\"sensitivityPolicySettings\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *GovernancePolicy) SetBackingStore(value ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStore)() {\n m.backingStore = value\n}",
"func (policy *Policy) SetSecret(sectype int, secret []byte) error {\n\terr := tspiError(C.Tspi_Policy_SetSecret(policy.handle, (C.TSS_FLAG)(sectype), (C.UINT32)(len(secret)), (*C.BYTE)(&secret[0])))\n\treturn err\n}",
"func (m *DeviceHealthAttestationState) SetSecureBootConfigurationPolicyFingerPrint(value *string)() {\n err := m.GetBackingStore().Set(\"secureBootConfigurationPolicyFingerPrint\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (_mr *MockECRAPIMockRecorder) SetRepositoryPolicyWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\t_s := append([]interface{}{arg0, arg1}, arg2...)\n\treturn _mr.mock.ctrl.RecordCall(_mr.mock, \"SetRepositoryPolicyWithContext\", _s...)\n}",
"func SandboxConfig(ocispec specs.Spec, runtime RuntimeConfig, bundlePath, cid string, detach, systemdCgroup bool) (vc.SandboxConfig, error) {\n\tcontainerConfig, err := ContainerConfig(ocispec, bundlePath, cid, detach)\n\tif err != nil {\n\t\treturn vc.SandboxConfig{}, err\n\t}\n\n\tshmSize, err := getShmSize(containerConfig)\n\tif err != nil {\n\t\treturn vc.SandboxConfig{}, err\n\t}\n\n\tnetworkConfig, err := networkConfig(ocispec, runtime)\n\tif err != nil {\n\t\treturn vc.SandboxConfig{}, err\n\t}\n\n\tsandboxConfig := vc.SandboxConfig{\n\t\tID: cid,\n\n\t\tHostname: ocispec.Hostname,\n\n\t\tHypervisorType: runtime.HypervisorType,\n\t\tHypervisorConfig: runtime.HypervisorConfig,\n\n\t\tAgentConfig: runtime.AgentConfig,\n\n\t\tNetworkConfig: networkConfig,\n\n\t\tContainers: []vc.ContainerConfig{containerConfig},\n\n\t\tAnnotations: map[string]string{\n\t\t\tvcAnnotations.BundlePathKey: bundlePath,\n\t\t},\n\n\t\tSandboxResources: vc.SandboxResourceSizing{\n\t\t\tWorkloadCPUs: runtime.SandboxCPUs,\n\t\t\tWorkloadMemMB: runtime.SandboxMemMB,\n\t\t},\n\n\t\tStaticResourceMgmt: runtime.StaticSandboxResourceMgmt,\n\n\t\tShmSize: shmSize,\n\n\t\tVfioMode: runtime.VfioMode,\n\n\t\tSystemdCgroup: systemdCgroup,\n\n\t\tSandboxCgroupOnly: runtime.SandboxCgroupOnly,\n\t\tSandboxBindMounts: runtime.SandboxBindMounts,\n\n\t\tDisableGuestSeccomp: runtime.DisableGuestSeccomp,\n\n\t\tGuestSeLinuxLabel: runtime.GuestSeLinuxLabel,\n\n\t\tExperimental: runtime.Experimental,\n\t}\n\n\tif err := addAnnotations(ocispec, &sandboxConfig, runtime); err != nil {\n\t\treturn vc.SandboxConfig{}, err\n\t}\n\n\t// If we are utilizing static resource management for the sandbox, ensure that the hypervisor is started\n\t// with the base number of CPU/memory (which is equal to the default CPU/memory specified for the runtime\n\t// configuration or annotations) as well as any specified workload resources.\n\tif sandboxConfig.StaticResourceMgmt {\n\t\tsandboxConfig.SandboxResources.BaseCPUs = sandboxConfig.HypervisorConfig.NumVCPUs\n\t\tsandboxConfig.SandboxResources.BaseMemMB = sandboxConfig.HypervisorConfig.MemorySize\n\n\t\tsandboxConfig.HypervisorConfig.NumVCPUs += sandboxConfig.SandboxResources.WorkloadCPUs\n\t\tsandboxConfig.HypervisorConfig.MemorySize += sandboxConfig.SandboxResources.WorkloadMemMB\n\n\t\tociLog.WithFields(logrus.Fields{\n\t\t\t\"workload cpu\": sandboxConfig.SandboxResources.WorkloadCPUs,\n\t\t\t\"default cpu\": sandboxConfig.SandboxResources.BaseCPUs,\n\t\t\t\"workload mem in MB\": sandboxConfig.SandboxResources.WorkloadMemMB,\n\t\t\t\"default mem\": sandboxConfig.SandboxResources.BaseMemMB,\n\t\t}).Debugf(\"static resources set\")\n\n\t}\n\n\treturn sandboxConfig, nil\n}",
"func (m *DeviceHealthAttestationState) SetCodeIntegrityPolicy(value *string)() {\n err := m.GetBackingStore().Set(\"codeIntegrityPolicy\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (c *Config) IsSandboxmode() bool { return c.sandboxMode }",
"func (*API) RunPodSandbox(context.Context, *sstore.Sandbox) error {\n\treturn nil\n}",
"func testPutBucketPolicyHandler(obj ObjectLayer, instanceType, bucketName string, apiRouter http.Handler,\n\tcredentials auth.Credentials, t *testing.T) {\n\n\tbucketName1 := fmt.Sprintf(\"%s-1\", bucketName)\n\tif err := obj.MakeBucketWithLocation(context.Background(), bucketName1, \"\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// template for constructing HTTP request body for PUT bucket policy.\n\tbucketPolicyTemplate := `{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\"],\"Resource\":[\"arn:aws:s3:::%s\"]},{\"Sid\":\"\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::%s/this*\"]}]}`\n\n\t// test cases with sample input and expected output.\n\ttestCases := []struct {\n\t\tbucketName string\n\t\t// bucket policy to be set,\n\t\t// set as request body.\n\t\tbucketPolicyReader io.ReadSeeker\n\t\t// length in bytes of the bucket policy being set.\n\t\tpolicyLen int\n\t\taccessKey string\n\t\tsecretKey string\n\t\t// expected Response.\n\t\texpectedRespStatus int\n\t}{\n\t\t// Test case - 1.\n\t\t{\n\t\t\tbucketName: bucketName,\n\t\t\tbucketPolicyReader: bytes.NewReader([]byte(fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName))),\n\n\t\t\tpolicyLen: len(fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName)),\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusNoContent,\n\t\t},\n\t\t// Test case - 2.\n\t\t// Setting the content length to be more than max allowed size.\n\t\t// Expecting StatusBadRequest (400).\n\t\t{\n\t\t\tbucketName: bucketName,\n\t\t\tbucketPolicyReader: bytes.NewReader([]byte(fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName))),\n\n\t\t\tpolicyLen: maxAccessPolicySize + 1,\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusBadRequest,\n\t\t},\n\t\t// Test case - 3.\n\t\t// Case with content-length of the HTTP request set to 0.\n\t\t// Expecting the HTTP response status to be StatusLengthRequired (411).\n\t\t{\n\t\t\tbucketName: bucketName,\n\t\t\tbucketPolicyReader: bytes.NewReader([]byte(fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName))),\n\n\t\t\tpolicyLen: 0,\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusLengthRequired,\n\t\t},\n\t\t// Test case - 4.\n\t\t// setting the readSeeker to `nil`, bucket policy parser will fail.\n\t\t{\n\t\t\tbucketName: bucketName,\n\t\t\tbucketPolicyReader: nil,\n\n\t\t\tpolicyLen: 10,\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusBadRequest,\n\t\t},\n\t\t// Test case - 5.\n\t\t// setting the keys to be empty.\n\t\t// Expecting statusForbidden.\n\t\t{\n\t\t\tbucketName: bucketName,\n\t\t\tbucketPolicyReader: nil,\n\n\t\t\tpolicyLen: 10,\n\t\t\taccessKey: \"\",\n\t\t\tsecretKey: \"\",\n\t\t\texpectedRespStatus: http.StatusForbidden,\n\t\t},\n\t\t// Test case - 6.\n\t\t// setting an invalid bucket policy.\n\t\t// the bucket policy parser will fail.\n\t\t{\n\t\t\tbucketName: bucketName,\n\t\t\tbucketPolicyReader: bytes.NewReader([]byte(\"dummy-policy\")),\n\n\t\t\tpolicyLen: len([]byte(\"dummy-policy\")),\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusBadRequest,\n\t\t},\n\t\t// Test case - 7.\n\t\t// Different bucket name used in the HTTP request and the policy string.\n\t\t// checkBucketPolicyResources should fail.\n\t\t{\n\t\t\tbucketName: bucketName1,\n\t\t\tbucketPolicyReader: bytes.NewReader([]byte(fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName))),\n\n\t\t\tpolicyLen: len(fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName)),\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusBadRequest,\n\t\t},\n\t\t// Test case - 8.\n\t\t// non-existent bucket is used.\n\t\t// writing BucketPolicy should fail.\n\t\t// should result is 500 InternalServerError.\n\t\t{\n\t\t\tbucketName: \"non-existent-bucket\",\n\t\t\tbucketPolicyReader: bytes.NewReader([]byte(fmt.Sprintf(bucketPolicyTemplate, \"non-existent-bucket\", \"non-existent-bucket\"))),\n\n\t\t\tpolicyLen: len(fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName)),\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusNotFound,\n\t\t},\n\t\t// Test case - 9.\n\t\t// invalid bucket name is used.\n\t\t// writing BucketPolicy should fail.\n\t\t// should result is 400 StatusBadRequest.\n\t\t{\n\t\t\tbucketName: \".invalid-bucket\",\n\t\t\tbucketPolicyReader: bytes.NewReader([]byte(fmt.Sprintf(bucketPolicyTemplate, \".invalid-bucket\", \".invalid-bucket\"))),\n\n\t\t\tpolicyLen: len(fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName)),\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusBadRequest,\n\t\t},\n\t}\n\n\t// Iterating over the test cases, calling the function under test and asserting the response.\n\tfor i, testCase := range testCases {\n\t\t// obtain the put bucket policy request body.\n\t\t// initialize HTTP NewRecorder, this records any mutations to response writer inside the handler.\n\t\trecV4 := httptest.NewRecorder()\n\t\t// construct HTTP request for PUT bucket policy endpoint.\n\t\treqV4, err := newTestSignedRequestV4(\"PUT\", getPutPolicyURL(\"\", testCase.bucketName),\n\t\t\tint64(testCase.policyLen), testCase.bucketPolicyReader, testCase.accessKey, testCase.secretKey)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %d: %s: Failed to create HTTP request for PutBucketPolicyHandler: <ERROR> %v\", i+1, instanceType, err)\n\t\t}\n\t\t// Since `apiRouter` satisfies `http.Handler` it has a ServeHTTP to execute the logic ofthe handler.\n\t\t// Call the ServeHTTP to execute the handler.\n\t\tapiRouter.ServeHTTP(recV4, reqV4)\n\t\tif recV4.Code != testCase.expectedRespStatus {\n\t\t\tt.Errorf(\"Test %d: %s: Expected the response status to be `%d`, but instead found `%d`\", i+1, instanceType, testCase.expectedRespStatus, recV4.Code)\n\t\t}\n\t\t// initialize HTTP NewRecorder, this records any mutations to response writer inside the handler.\n\t\trecV2 := httptest.NewRecorder()\n\t\t// construct HTTP request for PUT bucket policy endpoint.\n\t\treqV2, err := newTestSignedRequestV2(\"PUT\", getPutPolicyURL(\"\", testCase.bucketName),\n\t\t\tint64(testCase.policyLen), testCase.bucketPolicyReader, testCase.accessKey, testCase.secretKey)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %d: %s: Failed to create HTTP request for PutBucketPolicyHandler: <ERROR> %v\", i+1, instanceType, err)\n\t\t}\n\t\t// Since `apiRouter` satisfies `http.Handler` it has a ServeHTTP to execute the logic ofthe handler.\n\t\t// Call the ServeHTTP to execute the handler.\n\t\tapiRouter.ServeHTTP(recV2, reqV2)\n\t\tif recV2.Code != testCase.expectedRespStatus {\n\t\t\tt.Errorf(\"Test %d: %s: Expected the response status to be `%d`, but instead found `%d`\", i+1, instanceType, testCase.expectedRespStatus, recV2.Code)\n\t\t}\n\t}\n\n\t// Test for Anonymous/unsigned http request.\n\t// Bucket policy related functions doesn't support anonymous requests, setting policies shouldn't make a difference.\n\tbucketPolicyStr := fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName)\n\t// create unsigned HTTP request for PutBucketPolicyHandler.\n\tanonReq, err := newTestRequest(\"PUT\", getPutPolicyURL(\"\", bucketName),\n\t\tint64(len(bucketPolicyStr)), bytes.NewReader([]byte(bucketPolicyStr)))\n\n\tif err != nil {\n\t\tt.Fatalf(\"Minio %s: Failed to create an anonymous request for bucket \\\"%s\\\": <ERROR> %v\",\n\t\t\tinstanceType, bucketName, err)\n\t}\n\n\t// ExecObjectLayerAPIAnonTest - Calls the HTTP API handler using the anonymous request, validates the ErrAccessDeniedResponse,\n\t// sets the bucket policy using the policy statement generated from `getWriteOnlyObjectStatement` so that the\n\t// unsigned request goes through and its validated again.\n\tExecObjectLayerAPIAnonTest(t, obj, \"PutBucketPolicyHandler\", bucketName, \"\", instanceType, apiRouter, anonReq, getWriteOnlyObjectStatement)\n\n\t// HTTP request for testing when `objectLayer` is set to `nil`.\n\t// There is no need to use an existing bucket and valid input for creating the request\n\t// since the `objectLayer==nil` check is performed before any other checks inside the handlers.\n\t// The only aim is to generate an HTTP request in a way that the relevant/registered end point is evoked/called.\n\tnilBucket := \"dummy-bucket\"\n\n\tnilReq, err := newTestSignedRequestV4(\"PUT\", getPutPolicyURL(\"\", nilBucket),\n\t\t0, nil, \"\", \"\")\n\n\tif err != nil {\n\t\tt.Errorf(\"Minio %s: Failed to create HTTP request for testing the response when object Layer is set to `nil`.\", instanceType)\n\t}\n\t// execute the object layer set to `nil` test.\n\t// `ExecObjectLayerAPINilTest` manages the operation.\n\tExecObjectLayerAPINilTest(t, nilBucket, \"\", instanceType, apiRouter, nilReq)\n\n}",
"func TestPolicyWithConfig(t *testing.T) {\n\tt.Skip(\"Skip test that is causing unrelated tests to fail - pulumi/pulumi#4149\")\n\n\te := ptesting.NewEnvironment(t)\n\tdefer func() {\n\t\tif !t.Failed() {\n\t\t\te.DeleteEnvironment()\n\t\t}\n\t}()\n\n\t// Confirm we have credentials.\n\tif os.Getenv(\"PULUMI_ACCESS_TOKEN\") == \"\" {\n\t\tt.Fatal(\"PULUMI_ACCESS_TOKEN not found, aborting tests.\")\n\t}\n\n\tname, _ := e.RunCommand(\"pulumi\", \"whoami\")\n\torgName := strings.TrimSpace(name)\n\t// Pack and push a Policy Pack for the organization.\n\tpolicyPackName := fmt.Sprintf(\"%s-%x\", \"test-policy-pack\", time.Now().UnixNano())\n\te.ImportDirectory(\"policy_pack_w_config\")\n\te.RunCommand(\"yarn\", \"install\")\n\tt.Setenv(\"TEST_POLICY_PACK\", policyPackName)\n\n\t// Publish the Policy Pack twice.\n\tpublishPolicyPackWithVersion(e, orgName, `\"0.0.1\"`)\n\tpublishPolicyPackWithVersion(e, orgName, `\"0.0.2\"`)\n\n\t// Check the policy ls commands.\n\tpacksOutput, _ := e.RunCommand(\"pulumi\", \"policy\", \"ls\", \"--json\")\n\tvar packs []policyPacksJSON\n\tassertJSON(e, packsOutput, &packs)\n\n\tgroupsOutput, _ := e.RunCommand(\"pulumi\", \"policy\", \"group\", \"ls\", \"--json\")\n\tvar groups []policyGroupsJSON\n\tassertJSON(e, groupsOutput, &groups)\n\n\t// Enable, Disable and then Delete the Policy Pack.\n\te.RunCommand(\"pulumi\", \"policy\", \"enable\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName), \"0.0.1\")\n\n\t// Validate Policy Pack Configuration.\n\te.RunCommand(\"pulumi\", \"policy\", \"validate-config\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName),\n\t\t\"--config=configs/valid-config.json\", \"0.0.1\")\n\t// Valid config, but no version specified.\n\te.RunCommandExpectError(\"pulumi\", \"policy\", \"validate-config\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName),\n\t\t\"--config=configs/config.json\")\n\t// Invalid configs\n\te.RunCommandExpectError(\"pulumi\", \"policy\", \"validate-config\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName),\n\t\t\"--config=configs/invalid-config.json\", \"0.0.1\")\n\t// Invalid - missing required property.\n\te.RunCommandExpectError(\"pulumi\", \"policy\", \"validate-config\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName),\n\t\t\"--config=configs/invalid-required-prop.json\", \"0.0.1\")\n\t// Required config flag not present.\n\te.RunCommandExpectError(\"pulumi\", \"policy\", \"validate-config\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName))\n\te.RunCommandExpectError(\"pulumi\", \"policy\", \"validate-config\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName),\n\t\t\"--config\", \"0.0.1\")\n\n\t// Enable Policy Pack with Configuration.\n\te.RunCommand(\"pulumi\", \"policy\", \"enable\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName),\n\t\t\"--config=configs/valid-config.json\", \"0.0.1\")\n\te.RunCommandExpectError(\"pulumi\", \"policy\", \"enable\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName),\n\t\t\"--config=configs/invalid-config.json\", \"0.0.1\")\n\n\t// Disable Policy Pack specifying version.\n\te.RunCommand(\"pulumi\", \"policy\", \"disable\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName), \"--version=0.0.1\")\n\n\t// Enable and Disable without specifying the version number.\n\te.RunCommand(\"pulumi\", \"policy\", \"enable\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName), \"latest\")\n\te.RunCommand(\"pulumi\", \"policy\", \"disable\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName))\n\n\te.RunCommand(\"pulumi\", \"policy\", \"rm\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName), \"0.0.1\")\n\te.RunCommand(\"pulumi\", \"policy\", \"rm\", fmt.Sprintf(\"%s/%s\", orgName, policyPackName), \"all\")\n}",
"func (m *GovernancePolicy) SetNotificationPolicy(value GovernanceNotificationPolicyable)() {\n err := m.GetBackingStore().Set(\"notificationPolicy\", value)\n if err != nil {\n panic(err)\n }\n}",
"func BusinessNewPolicy() {\n\t// get message printer\n\tmsgPrinter := i18n.GetMessagePrinter()\n\n\tvar business_policy_template = []string{\n\t\t`{`,\n\t\t` \"label\": \"\", /* ` + msgPrinter.Sprintf(\"Deployment policy label.\") + ` */`,\n\t\t` \"description\": \"\", /* ` + msgPrinter.Sprintf(\"Deployment policy description.\") + ` */`,\n\t\t` \"service\": { `,\n\t\t` \"name\": \"\", /* ` + msgPrinter.Sprintf(\"The name of the service.\") + ` */`,\n\t\t` \"org\": \"\", /* ` + msgPrinter.Sprintf(\"The org of the service.\") + ` */`,\n\t\t` \"arch\": \"\", /* ` + msgPrinter.Sprintf(\"Set to '*' to use services of any hardware architecture.\") + ` */`,\n\t\t` \"serviceVersions\": [ /* ` + msgPrinter.Sprintf(\"A list of service versions.\") + ` */`,\n\t\t` {`,\n\t\t` \"version\": \"\",`,\n\t\t` \"priority\":{}`,\n\t\t` }`,\n\t\t` ]`,\n\t\t` },`,\n\t\t` \"properties\": [ /* ` + msgPrinter.Sprintf(\"A list of policy properties that describe the service being deployed.\") + ` */`,\n\t\t` {`,\n\t\t` \"name\": \"\",`,\n\t\t` \"value\": null`,\n\t\t` }`,\n\t\t` ],`,\n\t\t` \"constraints\": [ /* ` + msgPrinter.Sprintf(\"A list of constraint expressions of the form <property name> <operator> <property value>,\") + ` */`,\n\t\t` /* ` + msgPrinter.Sprintf(\"separated by boolean operators AND (&&) or OR (||).\") + `*/`,\n\t\t` \"myproperty == myvalue\" `,\n\t\t` ], `,\n\t\t` \"userInput\": [ /* ` + msgPrinter.Sprintf(\"A list of userInput variables to set when the service runs, listed by service.\") + ` */`,\n\t\t` { `,\n\t\t` \"serviceOrgid\": \"\", /* ` + msgPrinter.Sprintf(\"The org of the service.\") + ` */`,\n\t\t` \"serviceUrl\": \"\", /* ` + msgPrinter.Sprintf(\"The name of the service.\") + ` */`,\n\t\t` \"serviceVersionRange\": \"\", /* ` + msgPrinter.Sprintf(\"The service version range to which these variables should be applied.\") + ` */`,\n\t\t` \"inputs\": [ /* ` + msgPrinter.Sprintf(\"The input variables to be set.\") + `*/`,\n\t\t` {`,\n\t\t` \"name\": \"\",`,\n\t\t` \"value\": null`,\n\t\t` }`,\n\t\t` ]`,\n\t\t` }`,\n\t\t` ]`,\n\t\t`}`,\n\t}\n\n\tfor _, s := range business_policy_template {\n\t\tfmt.Println(s)\n\t}\n}",
"func WriteSandboxDescription(destination string, sd SandboxDescription) error {\n\tsd.DbDeployerVersion = VersionDef\n\tsd.Timestamp = time.Now().Format(time.UnixDate)\n\tsd.CommandLine = strings.Join(CommandLineArgs, \" \")\n\tb, err := json.MarshalIndent(sd, \" \", \"\\t\")\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"error encoding sandbox description\")\n\t}\n\tjsonString := string(b)\n\tfilename := path.Join(destination, globals.SandboxDescriptionName)\n\treturn WriteString(jsonString, filename)\n}",
"func setCrossDomainPolicy(h http.Handler) http.Handler {\n\treturn crossDomainPolicy{handler: h}\n}",
"func (c *sandboxes) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Sandbox, err error) {\n\tresult = &v1.Sandbox{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"sandboxes\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}",
"func (km *KeyValueMap) SetPolicy(policy string) {\n\t(*km)[kmPolicy] = policy\n}",
"func setSourceIamPolicy(w io.Writer, sourceName string, user string) error {\n\t// sourceName := \"organizations/111122222444/sources/1234\"\n\t// user := \"someuser@some_domain.com\n\t// Instantiate a context and a security service client to make API calls.\n\tctx := context.Background()\n\tclient, err := securitycenter.NewClient(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"securitycenter.NewClient: %w\", err)\n\t}\n\tdefer client.Close() // Closing the client safely cleans up background resources.\n\n\t// Retrieve the existing policy so we can update only a specific\n\t// field.\n\texisting, err := client.GetIamPolicy(ctx, &iam.GetIamPolicyRequest{\n\t\tResource: sourceName,\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"GetIamPolicy(%s): %w\", sourceName, err)\n\t}\n\n\treq := &iam.SetIamPolicyRequest{\n\t\tResource: sourceName,\n\t\tPolicy: &iam.Policy{\n\t\t\t// Enables partial update of existing policy\n\t\t\tEtag: existing.Etag,\n\t\t\tBindings: []*iam.Binding{{\n\t\t\t\tRole: \"roles/securitycenter.findingsEditor\",\n\t\t\t\t// New IAM Binding for the user.\n\t\t\t\tMembers: []string{fmt.Sprintf(\"user:%s\", user)},\n\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tpolicy, err := client.SetIamPolicy(ctx, req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"SetIamPolicy(%s, %v): %w\", sourceName, req.Policy, err)\n\t}\n\n\tfmt.Fprint(w, \"Bindings:\\n\")\n\tfor _, binding := range policy.Bindings {\n\t\tfor _, member := range binding.Members {\n\t\t\tfmt.Fprintf(w, \"Principal: %s Role: %s\\n\", member, binding.Role)\n\t\t}\n\t}\n\treturn nil\n}",
"func (m *AospDeviceOwnerDeviceConfiguration) SetCameraBlocked(value *bool)() {\n err := m.GetBackingStore().Set(\"cameraBlocked\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *StsPolicy) SetIsOrganizationDefault(value *bool)() {\n m.isOrganizationDefault = value\n}",
"func BusinessUpdatePolicy(org string, credToUse string, policyName string, filePath string) {\n\n\t//check for ExchangeUrl early on\n\tvar exchUrl = cliutils.GetExchangeUrl()\n\n\tcliutils.SetWhetherUsingApiKey(credToUse)\n\tvar polOrg string\n\tpolOrg, policyName = cliutils.TrimOrg(org, policyName)\n\n\t// get message printer\n\tmsgPrinter := i18n.GetMessagePrinter()\n\n\t//Read in the file\n\tattribute := cliconfig.ReadJsonFileWithLocalConfig(filePath)\n\n\t//verify that the policy exists\n\tvar exchangePolicy exchange.GetBusinessPolicyResponse\n\thttpCode := cliutils.ExchangeGet(\"Exchange\", exchUrl, \"orgs/\"+polOrg+\"/business/policies\"+cliutils.AddSlash(policyName), cliutils.OrgAndCreds(org, credToUse), []int{200, 404}, &exchangePolicy)\n\tif httpCode == 404 {\n\t\tcliutils.Fatal(cliutils.NOT_FOUND, msgPrinter.Sprintf(\"Policy %s not found in org %s\", policyName, polOrg))\n\t}\n\n\tfindPatchType := make(map[string]interface{})\n\n\tjson.Unmarshal([]byte(attribute), &findPatchType)\n\n\tif _, ok := findPatchType[\"service\"]; ok {\n\t\tpatch := make(map[string]businesspolicy.ServiceRef)\n\t\terr := json.Unmarshal([]byte(attribute), &patch)\n\t\tif err != nil {\n\t\t\tcliutils.Fatal(cliutils.JSON_PARSING_ERROR, msgPrinter.Sprintf(\"failed to unmarshal attribute input %s: %v\", attribute, err))\n\t\t}\n\t\tmsgPrinter.Printf(\"Updating Policy %v/%v in the Horizon Exchange and re-evaluating all agreements based on this deployment policy. Existing agreements might be cancelled and re-negotiated.\", polOrg, policyName)\n\t\tmsgPrinter.Println()\n\t\tcliutils.ExchangePutPost(\"Exchange\", http.MethodPatch, exchUrl, \"orgs/\"+polOrg+\"/business/policies\"+cliutils.AddSlash(policyName), cliutils.OrgAndCreds(org, credToUse), []int{201}, patch, nil)\n\t\tmsgPrinter.Printf(\"Policy %v/%v updated in the Horizon Exchange\", polOrg, policyName)\n\t\tmsgPrinter.Println()\n\t} else if _, ok := findPatchType[\"properties\"]; ok {\n\t\tvar newValue externalpolicy.PropertyList\n\t\tpatch := make(map[string]externalpolicy.PropertyList)\n\t\terr := json.Unmarshal([]byte(attribute), &patch)\n\t\tif err != nil {\n\t\t\tcliutils.Fatal(cliutils.JSON_PARSING_ERROR, msgPrinter.Sprintf(\"failed to unmarshal attribute input %s: %v\", attribute, err))\n\t\t}\n\t\tnewValue = patch[\"properties\"]\n\t\terr = newValue.Validate()\n\t\tif err != nil {\n\t\t\tcliutils.Fatal(cliutils.CLI_INPUT_ERROR, msgPrinter.Sprintf(\"Invalid format for properties: %v\", err))\n\t\t}\n\t\tpatch[\"properties\"] = newValue\n\t\tmsgPrinter.Printf(\"Updating Policy %v/%v in the Horizon Exchange and re-evaluating all agreements based on this deployment policy. Existing agreements might be cancelled and re-negotiated.\", polOrg, policyName)\n\t\tmsgPrinter.Println()\n\t\tcliutils.ExchangePutPost(\"Exchange\", http.MethodPatch, exchUrl, \"orgs/\"+polOrg+\"/business/policies\"+cliutils.AddSlash(policyName), cliutils.OrgAndCreds(org, credToUse), []int{201}, patch, nil)\n\t\tmsgPrinter.Printf(\"Policy %v/%v updated in the Horizon Exchange\", polOrg, policyName)\n\t\tmsgPrinter.Println()\n\t} else if _, ok := findPatchType[\"constraints\"]; ok {\n\t\tvar newValue externalpolicy.ConstraintExpression\n\t\tpatch := make(map[string]externalpolicy.ConstraintExpression)\n\t\terr := json.Unmarshal([]byte(attribute), &patch)\n\t\tif err != nil {\n\t\t\tcliutils.Fatal(cliutils.JSON_PARSING_ERROR, msgPrinter.Sprintf(\"failed to unmarshal attribute input %s: %v\", attribute, err))\n\t\t}\n\t\t_, err = newValue.Validate()\n\t\tif err != nil {\n\t\t\tcliutils.Fatal(cliutils.CLI_INPUT_ERROR, msgPrinter.Sprintf(\"Invalid format for constraints: %v\", err))\n\t\t}\n\t\tnewValue = patch[\"constraints\"]\n\t\tmsgPrinter.Printf(\"Updating Policy %v/%v in the Horizon Exchange and re-evaluating all agreements based on this deployment policy. Existing agreements might be cancelled and re-negotiated.\", polOrg, policyName)\n\t\tmsgPrinter.Println()\n\t\tcliutils.ExchangePutPost(\"Exchange\", http.MethodPatch, exchUrl, \"orgs/\"+polOrg+\"/business/policies\"+cliutils.AddSlash(policyName), cliutils.OrgAndCreds(org, credToUse), []int{201}, patch, nil)\n\t\tmsgPrinter.Printf(\"Policy %v/%v updated in the Horizon Exchange\", polOrg, policyName)\n\t\tmsgPrinter.Println()\n\t} else if _, ok := findPatchType[\"userInput\"]; ok {\n\t\tpatch := make(map[string][]policy.UserInput)\n\t\terr := json.Unmarshal([]byte(attribute), &patch)\n\t\tif err != nil {\n\t\t\tcliutils.Fatal(cliutils.JSON_PARSING_ERROR, msgPrinter.Sprintf(\"failed to unmarshal attribute input %s: %v\", attribute, err))\n\t\t}\n\t\tcliutils.ExchangePutPost(\"Exchange\", http.MethodPatch, exchUrl, \"orgs/\"+polOrg+\"/business/policies\"+cliutils.AddSlash(policyName), cliutils.OrgAndCreds(org, credToUse), []int{201}, patch, nil)\n\t\tmsgPrinter.Printf(\"Updating Policy %v/%v in the Horizon Exchange and re-evaluating all agreements based on this deployment policy. Existing agreements might be cancelled and re-negotiated.\", polOrg, policyName)\n\t\tmsgPrinter.Println()\n\t\tmsgPrinter.Printf(\"Policy %v/%v updated in the Horizon Exchange\", polOrg, policyName)\n\t\tmsgPrinter.Println()\n\t} else {\n\t\t_, ok := findPatchType[\"label\"]\n\t\t_, ok2 := findPatchType[\"description\"]\n\t\tif ok || ok2 {\n\t\t\tpatch := make(map[string]string)\n\t\t\terr := json.Unmarshal([]byte(attribute), &patch)\n\t\t\tif err != nil {\n\t\t\t\tcliutils.Fatal(cliutils.JSON_PARSING_ERROR, msgPrinter.Sprintf(\"failed to unmarshal attribute input %s: %v\", attribute, err))\n\t\t\t}\n\t\t\tmsgPrinter.Printf(\"Updating Policy %v/%v in the Horizon Exchange and re-evaluating all agreements based on this deployment policy. Existing agreements might be cancelled and re-negotiated.\", polOrg, policyName)\n\t\t\tmsgPrinter.Println()\n\t\t\tcliutils.ExchangePutPost(\"Exchange\", http.MethodPatch, exchUrl, \"orgs/\"+polOrg+\"/business/policies\"+cliutils.AddSlash(policyName), cliutils.OrgAndCreds(org, credToUse), []int{201}, patch, nil)\n\t\t\tmsgPrinter.Printf(\"Policy %v/%v updated in the Horizon Exchange\", polOrg, policyName)\n\t\t\tmsgPrinter.Println()\n\t\t} else {\n\t\t\tcliutils.Fatal(cliutils.CLI_INPUT_ERROR, msgPrinter.Sprintf(\"Deployment policy attribute to be updated is not found in the input file. Supported attributes are: label, description, service, properties, constraints, and userInput.\"))\n\t\t}\n\t}\n}",
"func (m *GroupPolicyDefinition) SetVersion(value *string)() {\n err := m.GetBackingStore().Set(\"version\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (o *VolumeExportAttributesType) SetPolicy(newValue string) *VolumeExportAttributesType {\n\to.PolicyPtr = &newValue\n\treturn o\n}",
"func (m *StsPolicy) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.PolicyBase.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAppliesTo() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAppliesTo())\n err = writer.WriteCollectionOfObjectValues(\"appliesTo\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetDefinition() != nil {\n err = writer.WriteCollectionOfStringValues(\"definition\", m.GetDefinition())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isOrganizationDefault\", m.GetIsOrganizationDefault())\n if err != nil {\n return err\n }\n }\n return nil\n}",
"func (c *ConfigManager) Set(id ResourceIdentifier, policy []pomeriumconfig.Policy) {\n\tlogger.V(1).Info(\"setting policy for resource\", \"id\", id)\n\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\tc.policyList[id] = policy\n\tlogger.Info(\"set policy for resource\", \"id\", id)\n\tc.pendingSave = true\n}",
"func (cxa *CasbinXormAdapter) SavePolicy(model model.Model) (err error) {\n\t//policy_definition\n\tfor ptype, ast := range model[\"p\"] {\n\t\tfor _, policy := range ast.Policy {\n\t\t\tif err = cxa.mergePolicy(\"p\", ptype, policy); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\t//role_definition\n\tfor ptype, ast := range model[\"g\"] {\n\t\tfor _, policy := range ast.Policy {\n\t\t\tif err = cxa.mergePolicy(\"g\", ptype, policy); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}",
"func (m *ReportRoot) SetSecurity(value SecurityReportsRootable)() {\n err := m.GetBackingStore().Set(\"security\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (o *SnapmirrorCreateRequest) SetPolicy(newValue string) *SnapmirrorCreateRequest {\n\to.PolicyPtr = &newValue\n\treturn o\n}",
"func SetHeaders(w http.ResponseWriter, nonce string) {\n\t// Content security policy\n\tcsp := []string{\n\t\tfmt.Sprintf(\"script-src '%s' 'self'\", nonce),\n\t\t\"worker-src 'self' blob:\", // No single quotes around blob:\n\t}\n\tw.Header().Set(\"Content-Security-Policy\", strings.Join(csp, \"; \"))\n}",
"func setOAS2policies(swagger *openapi2.T, authPolicy string, configuration map[string]interface{}) ([]byte, error) {\n\t// remove existing security\n\tswagger.SecurityDefinitions = make(map[string]*openapi2.SecurityScheme)\n\tswitch authPolicy {\n\tcase apic.Apikey:\n\n\t\tdesc := anypoint.DescClienCred\n\t\tif configuration[anypoint.CredOrigin] != nil {\n\t\t\tdesc += configuration[anypoint.CredOrigin].(string)\n\t\t}\n\n\t\tss := openapi2.SecurityScheme{\n\t\t\tType: anypoint.ApiKey,\n\t\t\tName: anypoint.Authorization,\n\t\t\tIn: anypoint.Header,\n\t\t\tDescription: desc,\n\t\t}\n\n\t\tsd := map[string]*openapi2.SecurityScheme{\n\t\t\tanypoint.ClientID: &ss,\n\t\t}\n\t\tswagger.SecurityDefinitions = sd\n\n\tcase apic.Oauth:\n\t\tvar tokenUrl string\n\t\tscopes := make(map[string]string)\n\n\t\tif configuration[anypoint.TokenUrl] != nil {\n\t\t\ttokenUrl = configuration[anypoint.TokenUrl].(string)\n\t\t}\n\n\t\tif configuration[anypoint.Scopes] != nil {\n\t\t\tscopes[anypoint.Scopes] = configuration[anypoint.Scopes].(string)\n\t\t}\n\n\t\tssp := openapi2.SecurityScheme{\n\t\t\tDescription: anypoint.DescOauth2,\n\t\t\tType: anypoint.Oauth2,\n\t\t\tFlow: anypoint.AccessCode,\n\t\t\tTokenURL: tokenUrl,\n\t\t\tAuthorizationURL: tokenUrl,\n\t\t\tScopes: scopes,\n\t\t}\n\n\t\tsd := map[string]*openapi2.SecurityScheme{\n\t\t\tanypoint.Oauth2: &ssp,\n\t\t}\n\n\t\tswagger.SecurityDefinitions = sd\n\t}\n\t// return sc, agenterrors.New(1161, anypoint.ErrAuthNotSupported)\n\treturn json.Marshal(swagger)\n}",
"func (m *AospDeviceOwnerDeviceConfiguration) SetScreenCaptureBlocked(value *bool)() {\n err := m.GetBackingStore().Set(\"screenCaptureBlocked\", value)\n if err != nil {\n panic(err)\n }\n}",
"func WithPostPolicy(policy privacy.Policy) PolicyOption {\n\treturn func(policies *policies) {\n\t\tpolicies.post = policy\n\t}\n}",
"func TestGetBucketPolicyHandler(t *testing.T) {\n\tExecObjectLayerAPITest(t, testGetBucketPolicyHandler, []string{\"PutBucketPolicy\", \"GetBucketPolicy\"})\n}",
"func (c *container) SetPrivileged() error {\n\tif c.config == nil {\n\t\treturn nil\n\t}\n\tif c.config.Linux == nil {\n\t\treturn nil\n\t}\n\tif c.config.Linux.SecurityContext == nil {\n\t\treturn nil\n\t}\n\n\tif c.sboxConfig == nil {\n\t\treturn nil\n\t}\n\n\tif c.sboxConfig.Linux == nil {\n\t\treturn nil\n\t}\n\n\tif c.sboxConfig.Linux.SecurityContext == nil {\n\t\treturn nil\n\t}\n\n\tif c.config.Linux.SecurityContext.Privileged {\n\t\tif !c.sboxConfig.Linux.SecurityContext.Privileged {\n\t\t\treturn errors.New(\"no privileged container allowed in sandbox\")\n\t\t}\n\t\tc.privileged = true\n\t}\n\treturn nil\n}",
"func (w *Wallet) SetPlain(psw, content string) (err error) {\n\n\taesBytes, err := crypto.AESEncrypt(util.Slice(content), passWd)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tw.CipherContent = base64.StdEncoding.EncodeToString(aesBytes)\n\n\taesBytes, err = crypto.AESEncrypt(util.Slice(psw), passWd)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tw.CipherPSW = base64.StdEncoding.EncodeToString(aesBytes)\n\treturn\n}",
"func (c *criContainerdService) RunPodSandbox(ctx context.Context, r *runtime.RunPodSandboxRequest) (retRes *runtime.RunPodSandboxResponse, retErr error) {\n\tglog.V(2).Infof(\"RunPodSandbox with config %+v\", r.GetConfig())\n\tdefer func() {\n\t\tif retErr == nil {\n\t\t\tglog.V(2).Infof(\"RunPodSandbox returns sandbox id %q\", retRes.GetPodSandboxId())\n\t\t}\n\t}()\n\n\tconfig := r.GetConfig()\n\n\t// Generate unique id and name for the sandbox and reserve the name.\n\tid := generateID()\n\tname := makeSandboxName(config.GetMetadata())\n\t// Reserve the sandbox name to avoid concurrent `RunPodSandbox` request starting the\n\t// same sandbox.\n\tif err := c.sandboxNameIndex.Reserve(name, id); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to reserve sandbox name %q: %v\", name, err)\n\t}\n\tdefer func() {\n\t\t// Release the name if the function returns with an error.\n\t\tif retErr != nil {\n\t\t\tc.sandboxNameIndex.ReleaseByName(name)\n\t\t}\n\t}()\n\n\t// Create initial internal sandbox object.\n\tsandbox := sandboxstore.Sandbox{\n\t\tMetadata: sandboxstore.Metadata{\n\t\t\tID: id,\n\t\t\tName: name,\n\t\t\tConfig: config,\n\t\t},\n\t}\n\n\t// Ensure sandbox container image snapshot.\n\timage, err := c.ensureImageExists(ctx, c.sandboxImage)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get sandbox image %q: %v\", defaultSandboxImage, err)\n\t}\n\trootfsMounts, err := c.snapshotService.View(ctx, id, image.ChainID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to prepare sandbox rootfs %q: %v\", image.ChainID, err)\n\t}\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\tif err := c.snapshotService.Remove(ctx, id); err != nil {\n\t\t\t\tglog.Errorf(\"Failed to remove sandbox container snapshot %q: %v\", id, err)\n\t\t\t}\n\t\t}\n\t}()\n\tvar rootfs []*types.Mount\n\tfor _, m := range rootfsMounts {\n\t\trootfs = append(rootfs, &types.Mount{\n\t\t\tType: m.Type,\n\t\t\tSource: m.Source,\n\t\t\tOptions: m.Options,\n\t\t})\n\t}\n\n\t// Create sandbox container.\n\tspec, err := c.generateSandboxContainerSpec(id, config, image.Config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to generate sandbox container spec: %v\", err)\n\t}\n\trawSpec, err := json.Marshal(spec)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal oci spec %+v: %v\", spec, err)\n\t}\n\tglog.V(4).Infof(\"Sandbox container spec: %+v\", spec)\n\tif _, err = c.containerService.Create(ctx, containers.Container{\n\t\tID: id,\n\t\t// TODO(random-liu): Checkpoint metadata into container labels.\n\t\tImage: image.ID,\n\t\tRuntime: containers.RuntimeInfo{Name: defaultRuntime},\n\t\tSpec: &prototypes.Any{\n\t\t\tTypeUrl: runtimespec.Version,\n\t\t\tValue: rawSpec,\n\t\t},\n\t\tRootFS: id,\n\t}); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create containerd container: %v\", err)\n\t}\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\tif err := c.containerService.Delete(ctx, id); err != nil {\n\t\t\t\tglog.Errorf(\"Failed to delete containerd container%q: %v\", id, err)\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Create sandbox container root directory.\n\t// Prepare streaming named pipe.\n\tsandboxRootDir := getSandboxRootDir(c.rootDir, id)\n\tif err := c.os.MkdirAll(sandboxRootDir, 0755); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create sandbox root directory %q: %v\",\n\t\t\tsandboxRootDir, err)\n\t}\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\t// Cleanup the sandbox root directory.\n\t\t\tif err := c.os.RemoveAll(sandboxRootDir); err != nil {\n\t\t\t\tglog.Errorf(\"Failed to remove sandbox root directory %q: %v\",\n\t\t\t\t\tsandboxRootDir, err)\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Discard sandbox container output because we don't care about it.\n\t_, stdout, stderr := getStreamingPipes(sandboxRootDir)\n\t_, stdoutPipe, stderrPipe, err := c.prepareStreamingPipes(ctx, \"\", stdout, stderr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to prepare streaming pipes: %v\", err)\n\t}\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\tstdoutPipe.Close()\n\t\t\tstderrPipe.Close()\n\t\t}\n\t}()\n\tif err := c.agentFactory.NewSandboxLogger(stdoutPipe).Start(); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to start sandbox stdout logger: %v\", err)\n\t}\n\tif err := c.agentFactory.NewSandboxLogger(stderrPipe).Start(); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to start sandbox stderr logger: %v\", err)\n\t}\n\n\t// Setup sandbox /dev/shm, /etc/hosts and /etc/resolv.conf.\n\tif err = c.setupSandboxFiles(sandboxRootDir, config); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to setup sandbox files: %v\", err)\n\t}\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\tif err = c.unmountSandboxFiles(sandboxRootDir, config); err != nil {\n\t\t\t\tglog.Errorf(\"Failed to unmount sandbox files in %q: %v\",\n\t\t\t\t\tsandboxRootDir, err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tcreateOpts := &tasks.CreateTaskRequest{\n\t\tContainerID: id,\n\t\tRootfs: rootfs,\n\t\t// No stdin for sandbox container.\n\t\tStdout: stdout,\n\t\tStderr: stderr,\n\t}\n\t// Create sandbox task in containerd.\n\tglog.V(5).Infof(\"Create sandbox container (id=%q, name=%q) with options %+v.\",\n\t\tid, name, createOpts)\n\tcreateResp, err := c.taskService.Create(ctx, createOpts)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create sandbox container %q: %v\",\n\t\t\tid, err)\n\t}\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\t// Cleanup the sandbox container if an error is returned.\n\t\t\tif err := c.stopSandboxContainer(ctx, id); err != nil {\n\t\t\t\tglog.Errorf(\"Failed to delete sandbox container %q: %v\", id, err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tsandbox.Pid = createResp.Pid\n\tsandbox.NetNS = getNetworkNamespace(createResp.Pid)\n\tif !config.GetLinux().GetSecurityContext().GetNamespaceOptions().GetHostNetwork() {\n\t\t// Setup network for sandbox.\n\t\t// TODO(random-liu): [P2] Replace with permanent network namespace.\n\t\tpodName := config.GetMetadata().GetName()\n\t\tif err = c.netPlugin.SetUpPod(sandbox.NetNS, config.GetMetadata().GetNamespace(), podName, id); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to setup network for sandbox %q: %v\", id, err)\n\t\t}\n\t\tdefer func() {\n\t\t\tif retErr != nil {\n\t\t\t\t// Teardown network if an error is returned.\n\t\t\t\tif err := c.netPlugin.TearDownPod(sandbox.NetNS, config.GetMetadata().GetNamespace(), podName, id); err != nil {\n\t\t\t\t\tglog.Errorf(\"failed to destroy network for sandbox %q: %v\", id, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\t// Start sandbox container in containerd.\n\tif _, err := c.taskService.Start(ctx, &tasks.StartTaskRequest{ContainerID: id}); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to start sandbox container %q: %v\",\n\t\t\tid, err)\n\t}\n\n\t// Add sandbox into sandbox store.\n\tsandbox.CreatedAt = time.Now().UnixNano()\n\tif err := c.sandboxStore.Add(sandbox); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to add sandbox %+v into store: %v\", sandbox, err)\n\t}\n\n\treturn &runtime.RunPodSandboxResponse{PodSandboxId: id}, nil\n}",
"func (m *DeviceHealthAttestationState) SetTestSigning(value *string)() {\n err := m.GetBackingStore().Set(\"testSigning\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (rc *ResourceConfig) SetPolicy(policy Policy) {\n\ttoFind := nameRef{\n\t\tName: policy.Name,\n\t\tPartition: policy.Partition,\n\t}\n\tfound := false\n\tfor _, polName := range rc.Virtual.Policies {\n\t\tif reflect.DeepEqual(toFind, polName) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\trc.Virtual.Policies = append(rc.Virtual.Policies, toFind)\n\t}\n\tfor i, pol := range rc.Policies {\n\t\tif pol.Name == policy.Name && pol.Partition == policy.Partition {\n\t\t\trc.Policies[i] = policy\n\t\t\treturn\n\t\t}\n\t}\n\trc.Policies = append(rc.Policies, policy)\n}",
"func StackPolicyURL(URL string) func(*cfn.UpdateStackInput) {\n\treturn func(params *cfn.UpdateStackInput) {\n\t\tparams.StackPolicyURL = aws.String(URL)\n\t}\n}",
"func (m *StsPolicy) SetDefinition(value []string)() {\n m.definition = value\n}",
"func EnsureSecurityPolicy(cloud *gce.Cloud, sp utils.ServicePort, be *composite.BackendService) error {\n\tvar desiredPolicyName string\n\tif sp.BackendConfig.Spec.SecurityPolicy != nil {\n\t\tdesiredPolicyName = sp.BackendConfig.Spec.SecurityPolicy.Name\n\t} else {\n\t\tdesiredPolicyName = \"\"\n\t}\n\n\texistingPolicyName, err := utils.KeyName(be.SecurityPolicy)\n\t// The parser returns error for empty values.\n\tif be.SecurityPolicy != \"\" && err != nil {\n\t\treturn err\n\t}\n\n\tif existingPolicyName == desiredPolicyName {\n\t\treturn nil\n\t}\n\n\tif be.Scope != meta.Global {\n\t\treturn fmt.Errorf(\"cloud armor security policies not supported for %s backend service %s\", be.Scope, be.Name)\n\t}\n\n\tklog.V(2).Infof(\"Set security policy in backend service %s (%s:%s) to %q\", be.Name, sp.ID.Service.String(), sp.ID.Port.String(), desiredPolicyName)\n\tif err := composite.SetSecurityPolicy(cloud, be, desiredPolicyName); err != nil {\n\t\treturn fmt.Errorf(\"failed to set security policy %q for backend service %s (%s:%s): %v\", desiredPolicyName, be.Name, sp.ID.Service.String(), sp.ID.Port.String(), err)\n\t}\n\treturn nil\n}",
"func (s defaultStore) Set(bucketName string, acls authz.ACLList) error {\n\ts.policies[bucketName] = acls\n\treturn nil\n}",
"func NewPolicy(statements []Statement) *Policy {\n\tif statements == nil {\n\t\tstatements = []Statement{}\n\t}\n\n\treturn &Policy{\n\t\tVersion: Version,\n\t\tStatements: statements,\n\t}\n}",
"func (a *Adapter) SavePolicy(model model.Model) error {\n\treturn errors.New(\"not implemented\")\n}",
"func BucketPolicy(bucketName string, roleName string) (json.RawMessage, error) {\n\tswitch roleName {\n\tcase \"admin\":\n\t\treturn []byte(fmt.Sprintf(`{\n\t\t\t\"Version\": \"2012-10-17\",\n\t\t\t\"Statement\": [{\n\t\t\t\t\"Effect\": \"Allow\",\n\t\t\t\t\"Action\": [\n\t\t\t\t\t\"s3:*\"\n\t\t\t\t],\n\t\t\t\t\"Resource\": [\n\t\t\t\t\t\"arn:aws:s3:::%s/*\"\n\t\t\t\t]\n\t\t\t}]\n\t\t}`, bucketName)), nil\n\tcase \"read-only\":\n\t\treturn []byte(fmt.Sprintf(`{\n\t\t\t\"Version\": \"2012-10-17\",\n\t\t\t\"Statement\": [{\n\t\t\t\t\"Effect\": \"Allow\",\n\t\t\t\t\"Action\": [\n\t\t\t\t\t\"s3:ListBucket\",\n\t\t\t\t\t\"s3:GetBucketLocation\",\n\t\t\t\t\t\"s3:GetObject\",\n\t\t\t\t\t\"s3:GetObjectVersion\"\n\t\t\t\t],\n\t\t\t\t\"Resource\": [\n\t\t\t\t\t\"arn:aws:s3:::%s/*\"\n\t\t\t\t]\n\t\t\t}]\n\t\t}`, bucketName)), nil\n\t}\n\n\treturn nil, fmt.Errorf(\"Invalid key role\")\n}",
"func (c *Client) SetIamPolicy(ctx context.Context, source string, policy *iampb.Policy) (*iampb.Policy, error) {\n\tif c.dryRun {\n\t\tc.log.Info(\"(dry-run) SetIamPolicy\", \"source\", source)\n\t\treturn policy, nil\n\t}\n\treq := &iampb.SetIamPolicyRequest{\n\t\tPolicy: policy,\n\t\tResource: source,\n\t}\n\tctx, cancel := context.WithTimeout(ctx, c.timeout)\n\tdefer cancel()\n\treturn c.client.SetIamPolicy(ctx, req)\n}",
"func (m *DeviceManagementSettings) SetSecureByDefault(value *bool)() {\n err := m.GetBackingStore().Set(\"secureByDefault\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (mg *Object) SetManagementPolicy(r xpv1.ManagementPolicy) {}",
"func (m *AndroidCompliancePolicy) SetSecurityDisableUsbDebugging(value *bool)() {\n err := m.GetBackingStore().Set(\"securityDisableUsbDebugging\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (j *AuroraJob) SlaPolicy(policy *aurora.SlaPolicy) Job {\n\tj.jobConfig.TaskConfig.SlaPolicy = policy\n\n\treturn j\n}",
"func (m *AccessPackageAssignment) SetAssignmentPolicy(value AccessPackageAssignmentPolicyable)() {\n m.assignmentPolicy = value\n}",
"func (f *FortiWebClient) CreateServerPolicy(name,\n\tvirtualServer,\n\tprotectedHostnames,\n\thttpService,\n\thttpsService,\n\tprotectionProfile,\n\tcomments string,\n\tdeployment deploymentMode,\n\thalfOpenThreshold int,\n\tclientRealIP,\n\tsynCookie,\n\thttpRedirectHTTPS,\n\tmonitorMode,\n\turlCaseSensitivity bool) error {\n\n\tbody := map[string]interface{}{\n\t\t\"name\": f.SafeName(name),\n\t\t\"depInMode\": deployment,\n\t\t\"disdmode\": \"HTTP Content Routing\",\n\t\t\"virtualServer\": f.SafeName(virtualServer),\n\t\t\"HTTPService\": httpService,\n\t\t\"HTTPSService\": httpsService,\n\t\t\"clientRealIP\": clientRealIP,\n\t\t\"halfopenThresh\": halfOpenThreshold,\n\t\t\"syncookie\": synCookie,\n\t\t\"hRedirectoHttps\": httpRedirectHTTPS,\n\t\t\"MonitorMode\": monitorMode,\n\t\t\"URLCaseSensitivity\": urlCaseSensitivity,\n\t\t\"comments\": comments,\n\t\t\"enable\": true,\n\t\t\"status\": \"run\"}\n\n\tif protectedHostnames != \"\" {\n\t\tbody[\"protectedHostnames\"] = protectedHostnames\n\t}\n\n\tif protectionProfile != \"\" {\n\t\tbody[\"protectionProfile\"] = protectionProfile\n\t}\n\n\tif deployment == HTTPContentRouting {\n\t\tbody[\"disdmode\"] = \"HTTP Content Routing\"\n\t} else {\n\t\tbody[\"disdmode\"] = \"Single Server/Server Pool\"\n\t}\n\n\tjsonByte, err := json.Marshal(body)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error in json data: %s\\n\", err)\n\t\treturn err\n\t}\n\n\tresponse, error := f.DoPost(\"api/v1.0/Policy/ServerPolicy/ServerPolicy/\", string(jsonByte))\n\n\tif error != nil {\n\t\tfmt.Printf(\"The HTTP request failed with error %s\\n\", error)\n\t\treturn error\n\t}\n\tif response != nil && response.StatusCode != 200 {\n\t\tfmt.Printf(\"The HTTP request failed with HTTP code: %d, %s\\n\", response.StatusCode, response.Status)\n\t}\n\n\treturn nil\n}",
"func (m *AndroidCompliancePolicy) SetSecurityRequireCompanyPortalAppIntegrity(value *bool)() {\n err := m.GetBackingStore().Set(\"securityRequireCompanyPortalAppIntegrity\", value)\n if err != nil {\n panic(err)\n }\n}",
"func WithAllow(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, policyTypeContextKey{}, allowType)\n}",
"func (m *AospDeviceOwnerDeviceConfiguration) SetStorageBlockUsbFileTransfer(value *bool)() {\n err := m.GetBackingStore().Set(\"storageBlockUsbFileTransfer\", value)\n if err != nil {\n panic(err)\n }\n}",
"func GenerateBucketPolicyInstance(in v1alpha1.BucketPolicyParameters, sp *storage.Policy) {\n\tsp.Bindings = make([]*storage.PolicyBindings, len(in.Policy.Bindings))\n\tfor i, v := range in.Policy.Bindings {\n\t\tsp.Bindings[i] = &storage.PolicyBindings{}\n\t\tif v.Condition != nil {\n\t\t\tsp.Bindings[i].Condition = &storage.Expr{\n\t\t\t\tDescription: gcp.StringValue(v.Condition.Description),\n\t\t\t\tExpression: v.Condition.Expression,\n\t\t\t\tLocation: gcp.StringValue(v.Condition.Location),\n\t\t\t\tTitle: gcp.StringValue(v.Condition.Title),\n\t\t\t}\n\t\t}\n\t\tsp.Bindings[i].Members = make([]string, len(v.Members))\n\t\tcopy(sp.Bindings[i].Members, v.Members)\n\t\tsp.Bindings[i].Role = v.Role\n\t}\n\tsp.Version = iamv1alpha1.PolicyVersion\n}",
"func (l *Client) NewSandbox() *Sandbox {\n\ts := &Sandbox{}\n\ts.client = l\n\treturn s\n}",
"func testGetBucketPolicyHandler(obj ObjectLayer, instanceType, bucketName string, apiRouter http.Handler,\n\tcredentials auth.Credentials, t *testing.T) {\n\t// template for constructing HTTP request body for PUT bucket policy.\n\tbucketPolicyTemplate := `{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\"],\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Resource\":[\"arn:aws:s3:::%s\"],\"Sid\":\"\"},{\"Action\":[\"s3:GetObject\"],\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Resource\":[\"arn:aws:s3:::%s/this*\"],\"Sid\":\"\"}]}`\n\n\t// Writing bucket policy before running test on GetBucketPolicy.\n\tputTestPolicies := []struct {\n\t\tbucketName string\n\t\taccessKey string\n\t\tsecretKey string\n\t\t// expected Response.\n\t\texpectedRespStatus int\n\t}{\n\t\t{bucketName, credentials.AccessKey, credentials.SecretKey, http.StatusNoContent},\n\t}\n\n\t// Iterating over the cases and writing the bucket policy.\n\t// its required to write the policies first before running tests on GetBucketPolicy.\n\tfor i, testPolicy := range putTestPolicies {\n\t\t// obtain the put bucket policy request body.\n\t\tbucketPolicyStr := fmt.Sprintf(bucketPolicyTemplate, testPolicy.bucketName, testPolicy.bucketName)\n\t\t// initialize HTTP NewRecorder, this records any mutations to response writer inside the handler.\n\t\trecV4 := httptest.NewRecorder()\n\t\t// construct HTTP request for PUT bucket policy endpoint.\n\t\treqV4, err := newTestSignedRequestV4(\"PUT\", getPutPolicyURL(\"\", testPolicy.bucketName),\n\t\t\tint64(len(bucketPolicyStr)), bytes.NewReader([]byte(bucketPolicyStr)), testPolicy.accessKey, testPolicy.secretKey)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %d: Failed to create HTTP request for PutBucketPolicyHandler: <ERROR> %v\", i+1, err)\n\t\t}\n\t\t// Since `apiRouter` satisfies `http.Handler` it has a ServeHTTP to execute the logic ofthe handler.\n\t\t// Call the ServeHTTP to execute the handler.\n\t\tapiRouter.ServeHTTP(recV4, reqV4)\n\t\tif recV4.Code != testPolicy.expectedRespStatus {\n\t\t\tt.Fatalf(\"Case %d: Expected the response status to be `%d`, but instead found `%d`\", i+1, testPolicy.expectedRespStatus, recV4.Code)\n\t\t}\n\t\t// initialize HTTP NewRecorder, this records any mutations to response writer inside the handler.\n\t\trecV2 := httptest.NewRecorder()\n\t\t// construct HTTP request for PUT bucket policy endpoint.\n\t\treqV2, err := newTestSignedRequestV2(\"PUT\", getPutPolicyURL(\"\", testPolicy.bucketName),\n\t\t\tint64(len(bucketPolicyStr)), bytes.NewReader([]byte(bucketPolicyStr)), testPolicy.accessKey, testPolicy.secretKey)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %d: Failed to create HTTP request for PutBucketPolicyHandler: <ERROR> %v\", i+1, err)\n\t\t}\n\t\t// Since `apiRouter` satisfies `http.Handler` it has a ServeHTTP to execute the logic ofthe handler.\n\t\t// Call the ServeHTTP to execute the handler.\n\t\tapiRouter.ServeHTTP(recV2, reqV2)\n\t\tif recV2.Code != testPolicy.expectedRespStatus {\n\t\t\tt.Fatalf(\"Case %d: Expected the response status to be `%d`, but instead found `%d`\", i+1, testPolicy.expectedRespStatus, recV2.Code)\n\t\t}\n\t}\n\n\t// test cases with inputs and expected result for GetBucketPolicyHandler.\n\ttestCases := []struct {\n\t\tbucketName string\n\t\taccessKey string\n\t\tsecretKey string\n\t\t// expected output.\n\t\texpectedBucketPolicy string\n\t\texpectedRespStatus int\n\t}{\n\t\t// Test case - 1.\n\t\t// Case which valid inputs, expected to return success status of 200OK.\n\t\t{\n\t\t\tbucketName: bucketName,\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedBucketPolicy: bucketPolicyTemplate,\n\t\t\texpectedRespStatus: http.StatusOK,\n\t\t},\n\t\t// Test case - 2.\n\t\t// Case with non-existent bucket name.\n\t\t{\n\t\t\tbucketName: \"non-existent-bucket\",\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedBucketPolicy: bucketPolicyTemplate,\n\t\t\texpectedRespStatus: http.StatusNotFound,\n\t\t},\n\t\t// Test case - 3.\n\t\t// Case with invalid bucket name.\n\t\t{\n\t\t\tbucketName: \".invalid-bucket-name\",\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedBucketPolicy: \"\",\n\t\t\texpectedRespStatus: http.StatusBadRequest,\n\t\t},\n\t}\n\t// Iterating over the cases, fetching the policy and validating the response.\n\tfor i, testCase := range testCases {\n\t\t// expected bucket policy json string.\n\t\texpectedBucketPolicyStr := fmt.Sprintf(testCase.expectedBucketPolicy, testCase.bucketName, testCase.bucketName)\n\t\t// initialize HTTP NewRecorder, this records any mutations to response writer inside the handler.\n\t\trecV4 := httptest.NewRecorder()\n\t\t// construct HTTP request for PUT bucket policy endpoint.\n\t\treqV4, err := newTestSignedRequestV4(\"GET\", getGetPolicyURL(\"\", testCase.bucketName),\n\t\t\t0, nil, testCase.accessKey, testCase.secretKey)\n\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %d: Failed to create HTTP request for GetBucketPolicyHandler: <ERROR> %v\", i+1, err)\n\t\t}\n\t\t// Since `apiRouter` satisfies `http.Handler` it has a ServeHTTP to execute the logic of the handler.\n\t\t// Call the ServeHTTP to execute the handler, GetBucketPolicyHandler handles the request.\n\t\tapiRouter.ServeHTTP(recV4, reqV4)\n\t\t// Assert the response code with the expected status.\n\t\tif recV4.Code != testCase.expectedRespStatus {\n\t\t\tt.Fatalf(\"Case %d: Expected the response status to be `%d`, but instead found `%d`\", i+1, testCase.expectedRespStatus, recV4.Code)\n\t\t}\n\t\t// read the response body.\n\t\tbucketPolicyReadBuf, err := ioutil.ReadAll(recV4.Body)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %d: %s: Failed parsing response body: <ERROR> %v\", i+1, instanceType, err)\n\t\t}\n\n\t\tif recV4.Code != testCase.expectedRespStatus {\n\t\t\t// Verify whether the bucket policy fetched is same as the one inserted.\n\t\t\tif expectedBucketPolicyStr != string(bucketPolicyReadBuf) {\n\t\t\t\tt.Errorf(\"Test %d: %s: Bucket policy differs from expected value.\", i+1, instanceType)\n\t\t\t}\n\t\t}\n\t\t// initialize HTTP NewRecorder, this records any mutations to response writer inside the handler.\n\t\trecV2 := httptest.NewRecorder()\n\t\t// construct HTTP request for PUT bucket policy endpoint.\n\t\treqV2, err := newTestSignedRequestV2(\"GET\", getGetPolicyURL(\"\", testCase.bucketName),\n\t\t\t0, nil, testCase.accessKey, testCase.secretKey)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %d: Failed to create HTTP request for GetBucketPolicyHandler: <ERROR> %v\", i+1, err)\n\t\t}\n\t\t// Since `apiRouter` satisfies `http.Handler` it has a ServeHTTP to execute the logic of the handler.\n\t\t// Call the ServeHTTP to execute the handler, GetBucketPolicyHandler handles the request.\n\t\tapiRouter.ServeHTTP(recV2, reqV2)\n\t\t// Assert the response code with the expected status.\n\t\tif recV2.Code != testCase.expectedRespStatus {\n\t\t\tt.Fatalf(\"Case %d: Expected the response status to be `%d`, but instead found `%d`\", i+1, testCase.expectedRespStatus, recV2.Code)\n\t\t}\n\t\t// read the response body.\n\t\tbucketPolicyReadBuf, err = ioutil.ReadAll(recV2.Body)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %d: %s: Failed parsing response body: <ERROR> %v\", i+1, instanceType, err)\n\t\t}\n\t\tif recV2.Code == http.StatusOK {\n\t\t\t// Verify whether the bucket policy fetched is same as the one inserted.\n\t\t\tif expectedBucketPolicyStr != string(bucketPolicyReadBuf) {\n\t\t\t\tt.Errorf(\"Test %d: %s: Bucket policy differs from expected value.\", i+1, instanceType)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Test for Anonymous/unsigned http request.\n\t// Bucket policy related functions doesn't support anonymous requests, setting policies shouldn't make a difference.\n\t// create unsigned HTTP request for PutBucketPolicyHandler.\n\tanonReq, err := newTestRequest(\"GET\", getPutPolicyURL(\"\", bucketName), 0, nil)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Minio %s: Failed to create an anonymous request for bucket \\\"%s\\\": <ERROR> %v\",\n\t\t\tinstanceType, bucketName, err)\n\t}\n\n\t// ExecObjectLayerAPIAnonTest - Calls the HTTP API handler using the anonymous request, validates the ErrAccessDeniedResponse,\n\t// sets the bucket policy using the policy statement generated from `getWriteOnlyObjectStatement` so that the\n\t// unsigned request goes through and its validated again.\n\tExecObjectLayerAPIAnonTest(t, obj, \"GetBucketPolicyHandler\", bucketName, \"\", instanceType, apiRouter, anonReq, getReadOnlyObjectStatement)\n\n\t// HTTP request for testing when `objectLayer` is set to `nil`.\n\t// There is no need to use an existing bucket and valid input for creating the request\n\t// since the `objectLayer==nil` check is performed before any other checks inside the handlers.\n\t// The only aim is to generate an HTTP request in a way that the relevant/registered end point is evoked/called.\n\tnilBucket := \"dummy-bucket\"\n\n\tnilReq, err := newTestSignedRequestV4(\"GET\", getGetPolicyURL(\"\", nilBucket),\n\t\t0, nil, \"\", \"\")\n\n\tif err != nil {\n\t\tt.Errorf(\"Minio %s: Failed to create HTTP request for testing the response when object Layer is set to `nil`.\", instanceType)\n\t}\n\t// execute the object layer set to `nil` test.\n\t// `ExecObjectLayerAPINilTest` manages the operation.\n\tExecObjectLayerAPINilTest(t, nilBucket, \"\", instanceType, apiRouter, nilReq)\n}",
"func (c *Core) setupPolicyStore() error {\n\t// Create a sub-view\n\tview := c.systemBarrierView.SubView(policySubPath)\n\n\t// Create the policy store\n\tc.policyStore = NewPolicyStore(view, &dynamicSystemView{core: c})\n\n\t// Ensure that the default policy exists, and if not, create it\n\tpolicy, err := c.policyStore.GetPolicy(\"default\")\n\tif err != nil {\n\t\treturn errwrap.Wrapf(\"error fetching default policy from store: {{err}}\", err)\n\t}\n\tif policy == nil {\n\t\terr := c.policyStore.createDefaultPolicy()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Ensure that the cubbyhole response wrapping policy exists\n\tpolicy, err = c.policyStore.GetPolicy(responseWrappingPolicyName)\n\tif err != nil {\n\t\treturn errwrap.Wrapf(\"error fetching response-wrapping policy from store: {{err}}\", err)\n\t}\n\tif policy == nil || policy.Raw != responseWrappingPolicy {\n\t\terr := c.policyStore.createResponseWrappingPolicy()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (adapter *Adapter) SavePolicy(cmodel casbinModel.Model) error {\n\tcasbinRules := make([]model.CasbinRule, 0)\n\tfor pType, ast := range cmodel[\"p\"] {\n\t\tfor _, rule := range ast.Policy {\n\t\t\tcasbinRule := model.NewCasbinRuleFromPTypeAndRule(pType, rule)\n\t\t\tcasbinRules = append(casbinRules, casbinRule)\n\t\t}\n\t}\n\tfor pType, ast := range cmodel[\"g\"] {\n\t\tfor _, rule := range ast.Policy {\n\t\t\tcasbinRule := model.NewCasbinRuleFromPTypeAndRule(pType, rule)\n\t\t\tcasbinRules = append(casbinRules, casbinRule)\n\t\t}\n\t}\n\tif err := adapter.casbinRuleRepository.ReplaceAllCasbinRules(casbinRules); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func TestSetPolicyEntrust(t *testing.T) {\n\n\tpolicyName := test.RandAppName() + \"\\\\\" + test.RandCitName()\n\tconn := getTestConnector(ctx.CloudZone)\n\tconn.verbose = true\n\n\terr := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})\n\n\tif err != nil {\n\t\tt.Fatalf(\"%s\", err)\n\t}\n\n\tspecification := test.GetCloudPolicySpecification()\n\t//change default CA to Entrust\n\tcaName := os.Getenv(\"CLOUD_ENTRUST_CA_NAME\")\n\tspecification.Policy.CertificateAuthority = &caName\n\n\t_, err = conn.SetPolicy(policyName, specification)\n\n\tif err != nil {\n\t\tt.Fatalf(\"%s\", err)\n\t}\n\n\tps, err := conn.GetPolicy(policyName)\n\n\tif ps.Policy.CertificateAuthority == nil || *(ps.Policy.CertificateAuthority) == \"\" {\n\t\tt.Fatalf(\"venafi policy doesn't have a certificate authority\")\n\t}\n\tif *(ps.Policy.CertificateAuthority) != *(specification.Policy.CertificateAuthority) {\n\t\tt.Fatalf(\"certificate authority value doesn't match, get: %s but expected: %s\", *(ps.Policy.CertificateAuthority), *(specification.Policy.CertificateAuthority))\n\t}\n\n}",
"func (d *DSP) SetBypass(bypass bool) error {\n\tres := C.FMOD_DSP_SetBypass(d.cptr, getBool(bypass))\n\treturn errs[res]\n}"
] | [
"0.5637117",
"0.5554631",
"0.551012",
"0.54839694",
"0.54407215",
"0.53919464",
"0.5366824",
"0.53610384",
"0.5315325",
"0.5181745",
"0.50174683",
"0.49613714",
"0.4930448",
"0.4927257",
"0.48779342",
"0.48582906",
"0.48470354",
"0.4819258",
"0.4802531",
"0.47860077",
"0.4782081",
"0.47769654",
"0.47643143",
"0.47598207",
"0.4751404",
"0.47146934",
"0.46922812",
"0.4691073",
"0.46538678",
"0.46402237",
"0.46192297",
"0.46139088",
"0.45906618",
"0.4584578",
"0.45738295",
"0.4558015",
"0.4527097",
"0.45095083",
"0.4508855",
"0.44957635",
"0.44846627",
"0.44812858",
"0.44807947",
"0.44682044",
"0.44599444",
"0.44573376",
"0.44467494",
"0.44277814",
"0.4411057",
"0.44074747",
"0.44015548",
"0.44000974",
"0.4373507",
"0.43710932",
"0.4365147",
"0.43571627",
"0.43473697",
"0.4340822",
"0.43328953",
"0.4330294",
"0.43243298",
"0.43182573",
"0.4314707",
"0.4306612",
"0.42997906",
"0.42941",
"0.42873487",
"0.42873353",
"0.42857227",
"0.428479",
"0.42752004",
"0.42741972",
"0.4273899",
"0.42700392",
"0.42664185",
"0.4264054",
"0.4252898",
"0.42508933",
"0.42501375",
"0.42499638",
"0.42415383",
"0.4239083",
"0.4228496",
"0.4227304",
"0.42233807",
"0.42206872",
"0.42194957",
"0.42194262",
"0.42146507",
"0.42095459",
"0.42021957",
"0.41937548",
"0.4190572",
"0.4180216",
"0.41798478",
"0.4164848",
"0.4157465",
"0.4145386",
"0.41393533",
"0.41373718"
] | 0.82821447 | 0 |
FPDF_LoadPage loads a page and returns a reference. | func (p *PdfiumImplementation) FPDF_LoadPage(request *requests.FPDF_LoadPage) (*responses.FPDF_LoadPage, error) {
p.Lock()
defer p.Unlock()
documentHandle, err := p.getDocumentHandle(request.Document)
if err != nil {
return nil, err
}
pageObject := C.FPDF_LoadPage(documentHandle.handle, C.int(request.Index))
if pageObject == nil {
return nil, pdfium_errors.ErrPage
}
pageHandle := p.registerPage(pageObject, request.Index, documentHandle)
return &responses.FPDF_LoadPage{
Page: pageHandle.nativeRef,
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (p *PdfiumImplementation) FPDFText_LoadPage(request *requests.FPDFText_LoadPage) (*responses.FPDFText_LoadPage, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttextPage := C.FPDFText_LoadPage(pageHandle.handle)\n\tif textPage == nil {\n\t\treturn nil, errors.New(\"could not load text page\")\n\t}\n\n\tdocumentHandle, err := p.getDocumentHandle(pageHandle.documentRef)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttextPageHandle := p.registerTextPage(textPage, documentHandle)\n\n\treturn &responses.FPDFText_LoadPage{\n\t\tTextPage: textPageHandle.nativeRef,\n\t}, nil\n}",
"func loadPage(title string) (*Page, error) {\r\n\tfilename := title\r\n\t//this will read the file givin it's name returning the Body that's a slice of bytes and a error\r\n\tbody, err := ioutil.ReadFile(filename)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\treturn &Page{Title: title, Body: body}, nil\r\n}",
"func loadPage(title string) (*Page, error) {\n\tfilename := \"data/\" + title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Page{Title: title, Body: body}, nil\n}",
"func LoadPage() {\n\tb, _ := ioutil.ReadFile(\"./web/index.html\")\n\tPage = string(b)\n}",
"func loadPage(title string) (*Page, error) {\n\tfilename := \"./pages/\" + title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\tlist := fetchPageList()\n\tif err != nil {\n\t\tlog.Println(\"loadPage() error: \", err)\n\t\treturn nil, err\n\t}\n\treturn &Page{Title: title, Body: body, List: list}, nil\n}",
"func loadPage(title string) (*Page, error) {\n\tfilename := title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\t// Use the blank identifier \"_\" to throw away unused return values.\n\t// Error handling. err == nil implies successfully loaded page.\n\tif err != nil {\n\t\treturn nil, err \t// Error to be handled by the caller.\n\t}\n\treturn &Page{Title: title, Body: body}, nil\n}",
"func loadPage(title string) (*Page, error) {\n\tfilename := title + \".txt\"\n\tbody, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Page{Title: title, Body: body}, nil\n}",
"func loadPage(title string) (*Page, error){\r\n\tfilename := title + \".txt\"\r\n\tbody, err := ioutil.ReadFile(filename)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\treturn &Page{Title: title, Body: body}, nil\r\n}",
"func LoadPage(pth string) error {\n log(dtalog.DBG, \"LoadPage(%q) called\", pth)\n f, err := os.Open(pth)\n if err != nil {\n log(dtalog.ERR, \"LoadPath(%q): error opening file: %s\", pth, err)\n return err\n }\n defer f.Close()\n \n npagep := &Page{ Path: pth, Stale: time.Now().Add(StalePageLife),\n Stuff: make(map[string]string), }\n \n dcdr := json.NewDecoder(f)\n \n var raw interface{}\n var raw_slice []interface{}\n for dcdr.More() {\n err = dcdr.Decode(&raw)\n if err != nil {\n log(dtalog.WRN, \"LoadPath(%q): decoding error: %s\", pth, err)\n continue\n }\n raw_slice = raw.([]interface{})\n npagep.Stuff[raw_slice[0].(string)] = raw_slice[1].(string)\n }\n \n Pages[pth] = npagep\n return nil\n}",
"func (page *Page) Load() (e error) {\n\tfmt.Print(\".\")\n\tif body, err := page.Fetch(); err != nil {\n\t\te = err\n\t} else {\n\t\tif body != nil {\n\t\t\tpage.Parse(body)\n\t\t}\n\t}\n\tpage.Site.WaitGroup.Done()\n\treturn\n}",
"func loadPage(file string) (*Page, error) {\n\tfilename := filepath.Join(pagesDir, file+\".txt\")\n\tbody, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tingredients, instructions := parseRecipe(body)\n\n\tp := &Page{\n\t\tTitle: convertFilenameToTitle(file),\n\t\tFilename: filepath.Base(file),\n\t\tIngredients: template.HTML(ingredients),\n\t\tInstructions: template.HTML(instructions)}\n\n\treturn p, nil\n}",
"func (x *PDFPage) Ref() *C.pdf_page {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_page)(unsafe.Pointer(x))\n}",
"func loadPage(title string) (*Page, error) {\n filename := title + \".html\"\n body, _err := ioutil.ReadFile(filename)\n if err != nil {\n return nil, err\n }\n return &Page{Title: title, Boby: body}, nil\n}",
"func (f *factory) loadPages() error {\n\tfileNames, err := listDirFunc(f.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(fileNames) == 0 {\n\t\t// page file not exist\n\t\treturn nil\n\t}\n\n\tfor _, fn := range fileNames {\n\t\tseqNumStr := fn[0 : strings.Index(fn, pageSuffix)-1]\n\t\tseq, err := strconv.ParseInt(seqNumStr, 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = f.AcquirePage(seq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}",
"func loadPage(pn string, r *http.Request) (*Page, error) {\n\tdata := &Page{\n\t\tPageName: pn,\n\t}\n\n\t/* Get user name for filling in template too */\n\tsesh, _ := store.Get(r, \"loginSession\")\n\tuname, ok := sesh.Values[\"username\"].(string)\n\tif !ok {\n\t\treturn nil, &ClientSafeError{Msg: \"invalid username\"}\n\t}\n\tdata.Username = uname\n\t/* get user's role */\n\trole, err := getRoleNum(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tswitch role {\n\tcase FACILITATOR:\n\t\tdata.Role = \"Facilitator\"\n\t\tdata.Messages, err = getNotifications(data.Username)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase TEACHER:\n\t\tdata.Role = \"Teacher\"\n\tcase ADMIN:\n\t\tdata.Role = \"Admin\"\n\tdefault:\n\t\treturn nil, &ClientSafeError{Msg: \"insufficient access rights\"}\n\t}\n\n\treturn data, nil\n}",
"func (x *FzPage) Ref() *C.fz_page {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.fz_page)(unsafe.Pointer(x))\n}",
"func LoadPage(link UnstartedURL, host string, result chan URLResult, unstarted *unstartedURLs) {\n\tvar req *http.Request\n\tvar err error\n\tif link.URL.Host == host {\n\t\treq, err = http.NewRequest(\"GET\", link.URL.String(), nil)\n\t} else {\n\t\treq, err = http.NewRequest(\"HEAD\", link.URL.String(), nil)\n\t}\n\n\tif err != nil {\n\t\tresult <- URLResult{link.URL, link.Source, 0, err.Error()}\n\t\treturn\n\t}\n\n\treq.Header.Set(\"User-Agent\", \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:55.0) Gecko/20100101 Firefox/55.0\")\n\n\tvar client http.Client\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\tresult <- URLResult{link.URL, link.Source, 0, err.Error()}\n\t\treturn\n\t}\n\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\n\tdefer resp.Body.Close()\n\n\tvar body string\n\tif link.URL.Host == host && strings.Contains(contentType, \"html\") {\n\t\trawBody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tresult <- URLResult{link.URL, link.Source, 0, err.Error()}\n\t\t\treturn\n\t\t}\n\t\tbody = string(rawBody)\n\t\tfor _, v := range ExtractLinks(body, link.URL) {\n\t\t\tunstarted.append(UnstartedURL{URL: v, Source: link.URL})\n\t\t}\n\t}\n\n\tresult <- URLResult{link.URL, link.Source, resp.StatusCode, \"\"}\n}",
"func loadPage(title string) (*PageTablature, error) {\n filename := \"tablatures/\"+ title + \".txt\"\n body, err := ioutil.ReadFile(filename)\n if err != nil {\n return nil, err\n }\n return &PageTablature{Titre: title, Tab: body}, nil\n}",
"func loadPage(url string) (*Page) {\n var httpClient = &http.Client{\n Timeout: time.Second * 2200,\n }\n resp, err := httpClient.Get(url)\n if err != nil {\n syslog.Critf(\"Step1 load page error: %s\", err)\n fmt.Println(\"Step1 load page error\", err)\n return &Page{Body: []byte{0}}\n }\n body, err := ioutil.ReadAll(resp.Body)\n return &Page{Body: body}\n}",
"func (l *HTTPGetLoader) Load(p string) (io.ReadCloser, error) {\n\tres, err := l.client.Get(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// TODO: Check content type\n\tif res.StatusCode < 200 || res.StatusCode > 299 {\n\t\treturn res.Body, errors.New(\"failed to load page\")\n\t}\n\treturn res.Body, err\n}",
"func LoadPage(c *fiber.Ctx, login string, roles []int) error {\n\tquerypack.INFO.Roles = roles\n\tquerypack.INFO.Login = login\n\tquerypack.INFO.LoggedIn = true\n\tc.Method(\"GET\")\n\tc.Path(querypack.INFO.URL)\n\tquerypack.AddCookie(c)\n\treturn c.Next()\n}",
"func (x *PDFPage) PassRef() *C.pdf_page {\n\tif x == nil {\n\t\tx = (*PDFPage)(allocPDFPageMemory(1))\n\t}\n\treturn (*C.pdf_page)(unsafe.Pointer(x))\n}",
"func NewPDFPageRef(ref unsafe.Pointer) *PDFPage {\n\treturn (*PDFPage)(ref)\n}",
"func CreatePage(\n\txRefTable *model.XRefTable,\n\tparentPageIndRef types.IndirectRef,\n\tp *model.Page,\n\tfonts model.FontMap) (*types.IndirectRef, types.Dict, error) {\n\n\tpageDict := types.Dict(\n\t\tmap[string]types.Object{\n\t\t\t\"Type\": types.Name(\"Page\"),\n\t\t\t\"Parent\": parentPageIndRef,\n\t\t\t\"MediaBox\": p.MediaBox.Array(),\n\t\t\t\"CropBox\": p.CropBox.Array(),\n\t\t},\n\t)\n\n\terr := addPageResources(xRefTable, pageDict, *p, fonts)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tir, err := xRefTable.StreamDictIndRef(p.Buf.Bytes())\n\tif err != nil {\n\t\treturn nil, pageDict, err\n\t}\n\tpageDict.Insert(\"Contents\", *ir)\n\n\tpageDictIndRef, err := xRefTable.IndRefForNewObject(pageDict)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif len(p.AnnotTabs) == 0 && len(p.Annots) == 0 && len(p.LinkAnnots) == 0 {\n\t\treturn pageDictIndRef, pageDict, nil\n\t}\n\n\tif err := setAnnotationParentsAndFields(xRefTable, p, *pageDictIndRef); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tarr, err := mergeAnnotations(nil, p.Annots, p.AnnotTabs)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfor _, la := range p.LinkAnnots {\n\t\td, err := la.RenderDict(xRefTable, *pageDictIndRef)\n\t\tif err != nil {\n\t\t\treturn nil, nil, &json.UnsupportedTypeError{}\n\t\t}\n\t\tir, err := xRefTable.IndRefForNewObject(d)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tarr = append(arr, *ir)\n\t}\n\n\tpageDict[\"Annots\"] = arr\n\n\treturn pageDictIndRef, pageDict, err\n}",
"func (x *FzStextPage) Ref() *C.fz_stext_page {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.fz_stext_page)(unsafe.Pointer(x))\n}",
"func (f Impl) AddPage() {\n\tf.GoPdf.AddPage()\n}",
"func loadPage(ctx context.Context, cs ash.ConnSource, url string) (*chrome.Conn, error) {\n\tctx, st := timing.Start(ctx, \"load_page\")\n\tdefer st.End()\n\n\tconn, err := cs.NewConn(ctx, url)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to open %v\", url)\n\t}\n\treturn conn, err\n}",
"func TestLoadPage(t *testing.T) {\n\tmembers := member.GetMembers()\n\tbooks := book.GetBook()\n\n\tpage := loadPage(members, books)\n\n\tif len(page.Members) < 1 || len(page.Books) < 1 {\n\t\tt.Errorf(\"Page did not load based on data.\")\n\t} else {\n\t\tfmt.Println(\"index.go Func loadPage PASS\")\n\t}\n}",
"func LoadFromPDFFile(filePath string) (*FieldData, error) {\n\tf, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\treturn LoadFromPDF(f)\n}",
"func (s *PageStore) Load(pageID PageID) (*Page, error) {\n\ts.Lock()\n\tdefer s.Unlock()\n\tcacheID, alreadyInCache := s.lookup[pageID]\n\tif alreadyInCache {\n\t\treturn &s.cache[cacheID], nil\n\t}\n\tcacheID, noMoreSpace := s.nextFreeCacheSlot()\n\tif noMoreSpace {\n\t\treturn nil, ErrPageCacheFull\n\t}\n\terr := s.loadPage(pageID, cacheID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &s.cache[pageID], nil\n}",
"func (loader *VueLoader) LoadVuePage(w io.Writer, pageTitle string, rootComponent string) {\n\tif loader.Config.CompileEveryRequest {\n\t\tif err := loader.compile(); err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t}\n\terr := loader.layoutTemplate.Execute(w, vuePage{\n\t\tTitle: pageTitle,\n\t\tRootElement: template.HTML(rootComponent),\n\t\tScripts: template.HTML(loader.compiledScripts),\n\t\tStyles: template.HTML(loader.compiledStyles),\n\t\tTemplates: template.HTML(loader.compiledHTML),\n\t})\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}",
"func (parser *PdfParser) loadXrefs() (*PdfObjectDictionary, error) {\n\tparser.xrefs.ObjectMap = make(map[int]XrefObject)\n\tparser.objstms = make(objectStreams)\n\n\t// Get the file size.\n\tfSize, err := parser.rs.Seek(0, io.SeekEnd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcommon.Log.Trace(\"fsize: %d\", fSize)\n\tparser.fileSize = fSize\n\n\t// Seek the EOF marker.\n\terr = parser.seekToEOFMarker(fSize)\n\tif err != nil {\n\t\tcommon.Log.Debug(\"Failed seek to eof marker: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t// Look for startxref and get the xref offset.\n\tcurOffset, err := parser.rs.Seek(0, io.SeekCurrent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Seek 64 bytes (numBytes) back from EOF marker start.\n\tvar numBytes int64 = 64\n\toffset := curOffset - numBytes\n\tif offset < 0 {\n\t\toffset = 0\n\t}\n\t_, err = parser.rs.Seek(offset, io.SeekStart)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb2 := make([]byte, numBytes)\n\t_, err = parser.rs.Read(b2)\n\tif err != nil {\n\t\tcommon.Log.Debug(\"Failed reading while looking for startxref: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tresult := reStartXref.FindStringSubmatch(string(b2))\n\tif len(result) < 2 {\n\t\tcommon.Log.Debug(\"Error: startxref not found!\")\n\t\treturn nil, errors.New(\"startxref not found\")\n\t}\n\tif len(result) > 2 {\n\t\tcommon.Log.Debug(\"ERROR: Multiple startxref (%s)!\", b2)\n\t\treturn nil, errors.New(\"multiple startxref entries?\")\n\t}\n\toffsetXref, _ := strconv.ParseInt(result[1], 10, 64)\n\tcommon.Log.Trace(\"startxref at %d\", offsetXref)\n\n\tif offsetXref > fSize {\n\t\tcommon.Log.Debug(\"ERROR: Xref offset outside of file\")\n\t\tcommon.Log.Debug(\"Attempting repair\")\n\t\toffsetXref, err = parser.repairLocateXref()\n\t\tif err != nil {\n\t\t\tcommon.Log.Debug(\"ERROR: Repair attempt failed (%s)\")\n\t\t\treturn nil, err\n\t\t}\n\t}\n\t// Read the xref.\n\tparser.rs.Seek(int64(offsetXref), io.SeekStart)\n\tparser.reader = bufio.NewReader(parser.rs)\n\n\ttrailerDict, err := parser.parseXref()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check the XrefStm object also from the trailer.\n\txx := trailerDict.Get(\"XRefStm\")\n\tif xx != nil {\n\t\txo, ok := xx.(*PdfObjectInteger)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"XRefStm != int\")\n\t\t}\n\t\t_, err = parser.parseXrefStream(xo)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Load old objects also. Only if not already specified.\n\tvar prevList []int64\n\tintInSlice := func(val int64, list []int64) bool {\n\t\tfor _, b := range list {\n\t\t\tif b == val {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t// Load any Previous xref tables (old versions), which can\n\t// refer to objects also.\n\txx = trailerDict.Get(\"Prev\")\n\tfor xx != nil {\n\t\tprevInt, ok := xx.(*PdfObjectInteger)\n\t\tif !ok {\n\t\t\t// For compatibility: If Prev is invalid, just go with whatever xrefs are loaded already.\n\t\t\t// i.e. not returning an error. A debug message is logged.\n\t\t\tcommon.Log.Debug(\"Invalid Prev reference: Not a *PdfObjectInteger (%T)\", xx)\n\t\t\treturn trailerDict, nil\n\t\t}\n\n\t\toff := *prevInt\n\t\tcommon.Log.Trace(\"Another Prev xref table object at %d\", off)\n\n\t\t// Can be either regular table, or an xref object...\n\t\tparser.rs.Seek(int64(off), os.SEEK_SET)\n\t\tparser.reader = bufio.NewReader(parser.rs)\n\n\t\tptrailerDict, err := parser.parseXref()\n\t\tif err != nil {\n\t\t\tcommon.Log.Debug(\"Warning: Error - Failed loading another (Prev) trailer\")\n\t\t\tcommon.Log.Debug(\"Attempting to continue by ignoring it\")\n\t\t\tbreak\n\t\t}\n\n\t\txx = ptrailerDict.Get(\"Prev\")\n\t\tif xx != nil {\n\t\t\tprevoff := *(xx.(*PdfObjectInteger))\n\t\t\tif intInSlice(int64(prevoff), prevList) {\n\t\t\t\t// Prevent circular reference!\n\t\t\t\tcommon.Log.Debug(\"Preventing circular xref referencing\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tprevList = append(prevList, int64(prevoff))\n\t\t}\n\t}\n\n\treturn trailerDict, nil\n}",
"func (obj *LineFile) loadIndexPage(indexPageNumber int) {\n\tindexFilePath := obj.getIndexFilePath(indexPageNumber)\n\tfile, err := os.Open(indexFilePath)\n\tobj.checkError(err)\n\tr := bufio.NewReader(file)\n\tbytes, err := obj.readLine(r)\n\tobj.checkError(err)\n\tjsonString := ConvertBytesToString(bytes)\n\tobj.indexPage = ConvertStringTointArray(jsonString)\n\tobj.currentIndexPage = indexPageNumber\n\tfile.Close()\n}",
"func GetPage(w http.ResponseWriter, r *http.Request) {\n\tresponse := services.LoadPage(r)\n\n\trender.Status(r, response.Code)\n\trender.JSON(w, r, response)\n}",
"func (a *PDFApiService) LoadDocumentAsPDF(ctx _context.Context, pdfLoadDocumentFromByteArrayParameters PdfLoadDocumentFromByteArrayParameters) (PdfLoadDocumentResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue PdfLoadDocumentResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/pdf/LoadDocument\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json-patch+json\", \"application/json\", \"text/json\", \"application/_*+json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &pdfLoadDocumentFromByteArrayParameters\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v PdfLoadDocumentResponse\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}",
"func (f *FaxService) GetPage(ctx context.Context, data url.Values) (*FaxPage, error) {\n\treturn f.GetPageIterator(data).Next(ctx)\n}",
"func (x *FzPage) PassRef() *C.fz_page {\n\tif x == nil {\n\t\tx = (*FzPage)(allocFzPageMemory(1))\n\t}\n\treturn (*C.fz_page)(unsafe.Pointer(x))\n}",
"func readPage(db *Database, pageNum uint32) (*page, error) {\n\tif pageNum == NULL_POINTER_PAGE {\n\t\treturn nil, errors.New(\"nullpointer exception\")\n\t}\n\n\tbuffer, err := db.getPageBytes(pageNum)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpageHead, data, err := deserializePage(buffer, db.useEncryption, db.dbHead.masterKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &page{db, pageNum, pageHead, data}, nil\n}",
"func (m *Ints) Load(addr uint) (int, error) {\n\tif err := m.checkLimit(addr, \"load\"); err != nil {\n\t\treturn 0, err\n\t}\n\n\tif m.PageSize == 0 || len(m.pages) == 0 {\n\t\treturn 0, nil\n\t}\n\n\tpageID := m.findPage(addr)\n\tbase := m.bases[pageID]\n\tpage := m.pages[pageID]\n\tif i := int(addr) - int(base); 0 <= i && i < len(page) {\n\t\treturn page[i], nil\n\t}\n\n\treturn 0, nil\n}",
"func (p *PdfiumImplementation) FPDF_RenderPage(request *requests.FPDF_RenderPage) (*responses.FPDF_RenderPage, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thdc, ok := request.DC.(C.HDC)\n\tif !ok {\n\t\treturn nil, errors.New(\"DC is not of type C.HDC\")\n\t}\n\n\tC.FPDF_RenderPage(hdc, pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.int(request.Flags))\n\n\treturn &responses.FPDF_RenderPage{}, nil\n}",
"func (m *PageManager) loadPageIDs(fileSize int64) error {\n\tidBuf := make([]byte, 4)\n\tfor i := int64(0); i < fileSize; i += page.Size {\n\t\t_, err := m.file.ReadAt(idBuf, i)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"read at %v: %w\", i, err)\n\t\t}\n\t\tid := page.DecodeID(idBuf)\n\t\tif _, ok := m.pageOffsets[id]; ok {\n\t\t\treturn fmt.Errorf(\"duplicate page id %v\", id)\n\t\t}\n\t\tm.pageOffsets[id] = i\n\t}\n\treturn nil\n}",
"func NewPage(in php_serialize.PhpArray) (Page, error) {\n\tentries := make([]EntryRef, 0)\n\n\tfor key, val := range in[\"entries\"].(php_serialize.PhpArray) {\n\t\tentries = append(entries, NewEntryRef(php_serialize.PhpValueString(key), php_serialize.PhpValueString(val)))\n\t}\n\n\treturn Page{\n\t\tTotal: php_serialize.PhpValueInt64(in[\"total\"]),\n\t\tPerpage: php_serialize.PhpValueInt64(in[\"perpage\"]),\n\t\tEntries: entries,\n\t}, nil\n}",
"func (l Util) LoadTTF(p string, size float64) (font.Face, error) {\n\tbytes, err := l.ReadFile(l.path(p))\n\tif err != nil {\n\t\treturn nil, ErrNotOnDisc.Args(\"ttf\").Wrap(err)\n\t}\n\n\tfont, err := truetype.Parse(bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn truetype.NewFace(font, &truetype.Options{\n\t\tSize: size,\n\t\tGlyphCacheEntries: 1,\n\t}), nil\n}",
"func (tx *Tx) Page(userName, pageName []byte) (*Page, error) {\n\tp := &Page{\n\t\tTx: tx,\n\t\tUser: userName,\n\t\tName: pageName,\n\t}\n\n\treturn p, p.Load()\n}",
"func GetDesc(pagePath, ref string) string {\n log(dtalog.DBG, \"GetDesc(%q, %q) called\", pagePath, ref)\n var pgp *Page\n var ok bool\n if pgp, ok = Pages[pagePath]; !ok {\n err := LoadPage(pagePath)\n if err != nil {\n log(dtalog.ERR, \"GetDesc(%q, %q): Error in LoadPage(): %s\",\n pagePath, ref, err)\n }\n pgp = Pages[pagePath]\n }\n \n pgp.Stale = time.Now().Add(StalePageLife)\n dscr := pgp.Stuff[ref]\n return dscr\n}",
"func LoadFromPDF(rs io.ReadSeeker) (*FieldData, error) {\n\tpdfReader, err := model.NewPdfReader(rs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif pdfReader.AcroForm == nil {\n\t\treturn nil, nil\n\t}\n\n\tvar fieldvals []fieldValue\n\tfields := pdfReader.AcroForm.AllFields()\n\tfor _, f := range fields {\n\t\tvar options []string\n\t\toptMap := make(map[string]struct{})\n\n\t\tname, err := f.FullName()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif t, ok := f.V.(*core.PdfObjectString); ok {\n\t\t\tfieldvals = append(fieldvals, fieldValue{\n\t\t\t\tName: name,\n\t\t\t\tValue: t.Decoded(),\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\n\t\tvar val string\n\t\tfor _, wa := range f.Annotations {\n\t\t\tstate, found := core.GetName(wa.AS)\n\t\t\tif found {\n\t\t\t\tval = state.String()\n\t\t\t}\n\n\t\t\t// Options are the keys in the N/D dictionaries in the AP appearance dict.\n\t\t\tapDict, has := core.GetDict(wa.AP)\n\t\t\tif !has {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnDict, _ := core.GetDict(apDict.Get(\"N\"))\n\t\t\tfor _, key := range nDict.Keys() {\n\t\t\t\tkeystr := key.String()\n\t\t\t\tif _, has := optMap[keystr]; !has {\n\t\t\t\t\toptions = append(options, keystr)\n\t\t\t\t\toptMap[keystr] = struct{}{}\n\t\t\t\t}\n\t\t\t}\n\t\t\tdDict, _ := core.GetDict(apDict.Get(\"D\"))\n\t\t\tfor _, key := range dDict.Keys() {\n\t\t\t\tkeystr := key.String()\n\t\t\t\tif _, has := optMap[keystr]; !has {\n\t\t\t\t\toptions = append(options, keystr)\n\t\t\t\t\toptMap[keystr] = struct{}{}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfval := fieldValue{\n\t\t\tName: name,\n\t\t\tValue: val,\n\t\t\tOptions: options,\n\t\t}\n\t\tfieldvals = append(fieldvals, fval)\n\t}\n\n\tfdata := FieldData{\n\t\tvalues: fieldvals,\n\t}\n\n\treturn &fdata, nil\n}",
"func LoadPageChunk(params []byte) map[string]vars.PageChunk {\n\tpath := \"/loadPageChunk\"\n\tdata := notionAPI(params, path)\n\n\tConvertData := make(map[string]vars.PageChunk)\n\terr := json.Unmarshal(data, &ConvertData)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn ConvertData\n}",
"func (c *Client) LoadPageChunk(pageID string, chunkNo int, cur *cursor) (*LoadPageChunkResponse, error) {\n\t// emulating notion's website api usage: 50 items on first request,\n\t// 30 on subsequent requests\n\tlimit := 30\n\tapiURL := \"/api/v3/loadPageChunk\"\n\tif cur == nil {\n\t\tcur = &cursor{\n\t\t\t// to mimic browser api which sends empty array for this argment\n\t\t\tStack: make([][]stack, 0),\n\t\t}\n\t\tlimit = 50\n\t}\n\treq := &loadPageChunkRequest{\n\t\tPageID: pageID,\n\t\tChunkNumber: chunkNo,\n\t\tLimit: limit,\n\t\tCursor: *cur,\n\t\tVerticalColumns: false,\n\t}\n\tvar rsp LoadPageChunkResponse\n\tvar err error\n\trsp.RawJSON, err = doNotionAPI(c, apiURL, req, &rsp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rsp, nil\n}",
"func LoadFont(pfbfilename string, afmfilename string) (*Type1, error) {\n\tpfbfilenameWithoutExt := trimSuffix(pfbfilename)\n\tpossiblePFBFilenames := []string{pfbfilename, pfbfilenameWithoutExt + \".PFB\", pfbfilenameWithoutExt + \".pfb\"}\n\n\tpossibleAFMFilenames := []string{}\n\tif afmfilename == \"\" {\n\t\t// Let's try to find a suitable AFM file\n\t\tpossibleAFMFilenames = append(possibleAFMFilenames, pfbfilenameWithoutExt+\".AFM\")\n\t\tpossibleAFMFilenames = append(possibleAFMFilenames, pfbfilenameWithoutExt+\".afm\")\n\t} else {\n\t\tpossibleAFMFilenames = append(possibleAFMFilenames, afmfilename)\n\t}\n\n\tpfb, err := tryOpen(possiblePFBFilenames)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer pfb.Close()\n\tt := &Type1{}\n\tt.ParsePFB(pfb)\n\n\tafm, err := tryOpen(possibleAFMFilenames)\n\tif err == nil {\n\t\tt.ParseAFM(afm)\n\t}\n\tafm.Close()\n\treturn t, nil\n}",
"func NewPDFPage() *PDFPage {\n\treturn (*PDFPage)(allocPDFPageMemory(1))\n}",
"func (p *PaginatedResult) load(ctx context.Context, r paginatedRequest) error {\n\tp.basePath = path.Dir(r.path)\n\tp.firstLink = (&url.URL{\n\t\tPath: r.path,\n\t\tRawPath: r.rawPath,\n\t\tRawQuery: r.params.Encode(),\n\t}).String()\n\tp.query = r.query\n\treturn p.First(ctx)\n}",
"func (m *PageManager) ReadPage(id page.ID) (*page.Page, error) {\n\toffset, ok := m.pageOffsets[id]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"no offset for page %v\", id)\n\t}\n\n\tdata := make([]byte, page.Size)\n\t_, err := m.file.ReadAt(data, offset)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"read at: %w\", err)\n\t}\n\tp, err := page.Load(data)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"load: %w\", err)\n\t}\n\treturn p, nil\n}",
"func LoadRegisterPage(w http.ResponseWriter, r *http.Request) {\n\tutils.RunTemplate(w, \"register.html\", nil)\n}",
"func LoadUserPage(w http.ResponseWriter, r *http.Request) {\n\tparameters := mux.Vars(r)\n\tuserID, err := strconv.ParseUint(parameters[\"userId\"], 10, 64)\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusBadRequest, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\tcookie, _ := cookies.Read(r)\n\tuserIDLogged, _ := strconv.ParseUint(cookie[\"id\"], 10, 64)\n\n\tuser, err := models.SearchCompleteUser(userID, r)\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\tif userID == userIDLogged {\n\t\thttp.Redirect(w, r, \"/profile\", 302)\n\t\treturn\n\t}\n\n\tutils.RunTemplate(w, \"user.html\", struct {\n\t\tUser models.User\n\t\tUserLoggedID uint64\n\t}{\n\t\tUser: user,\n\t\tUserLoggedID: userIDLogged,\n\t})\n}",
"func loadFile() (*models.Page, error) {\n\tfilename := path.Join(\"logs\", \"log.txt\")\n\tbody, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &models.Page{Body: template.HTML(body)}, nil\n}",
"func NewFzPageRef(ref unsafe.Pointer) *FzPage {\n\treturn (*FzPage)(ref)\n}",
"func (x *FzStextPage) PassRef() *C.fz_stext_page {\n\tif x == nil {\n\t\tx = (*FzStextPage)(allocFzStextPageMemory(1))\n\t}\n\treturn (*C.fz_stext_page)(unsafe.Pointer(x))\n}",
"func (f *DefaultFactory) pageFromHTTPResponse(ctx context.Context, url *url.URL, resp *http.Response, options ...interface{}) (Content, error) {\n\tresult := new(Page)\n\tresult.MetaPropertyTags = make(map[string]interface{})\n\tresult.TargetURL = url\n\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\tif len(contentType) > 0 {\n\t\tvar err error\n\t\tresult.PageType, err = NewPageType(url, contentType)\n\t\tif err != nil {\n\t\t\treturn result, err\n\t\t}\n\t\tif result.IsHTML() && (f.detectRedirectsInHTMLContent(ctx, url) || f.parseMetaDataInHTMLContent(ctx, url)) {\n\t\t\tresult.parsePageMetaData(ctx, url, resp)\n\t\t\tresult.HTMLParsed = true\n\t\t\tresult.valid = true\n\t\t\treturn result, nil\n\t\t}\n\t}\n\n\tvar attachmentCreator FileAttachmentCreator\n\tfor _, option := range options {\n\t\tif instance, ok := option.(FileAttachmentCreator); ok {\n\t\t\tattachmentCreator = instance\n\t\t}\n\t}\n\tif f.FileAttachmentCreator != nil {\n\t\tattachmentCreator = f.FileAttachmentCreator\n\t}\n\n\tif attachmentCreator != nil {\n\t\tok, attachment, err := DownloadFileFromHTTPResp(ctx, attachmentCreator, url, resp, result.PageType)\n\t\tif err != nil {\n\t\t\tif f.ContentDownloaderErrorPolicy != nil {\n\t\t\t\tif f.ContentDownloaderErrorPolicy.StopOnDownloadError(ctx, url, result.PageType, err) {\n\t\t\t\t\treturn result, err\n\t\t\t\t}\n\t\t\t}\n\t\t} else if ok && attachment != nil {\n\t\t\tresult.DownloadedAttachment = attachment\n\t\t}\n\t}\n\n\tresult.valid = true\n\treturn result, nil\n}",
"func (c *Client) RetrievePage(url string) (*Page, error) {\n\t//Trim leading slash if necessary\n\tif url[0] == '/' {\n\t\turl = url[1:]\n\t}\n\n\t//All urls must start with YC root (or test)\n\turlForReq := fmt.Sprintf(\"%s/%s\", c.RootUrl, url)\n\treq, err := http.NewRequest(\"GET\", urlForReq, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating request for url %s: %v\", url, err)\n\t}\n\n\tdoc, err := c.doReq(req)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error doing request:\\n\\t %v\", err)\n\t}\n\n\t//Get all the trs with subtext for children then go back one (for the first row)\n\trows := doc.Find(\".subtext\").ParentsFilteredUntil(\"tr\", \"tbody\").Prev()\n\n\tp := NewPage(url)\n\n\t//Get the next url\n\tif nextUrl, found := doc.Find(\"td.title\").Last().Find(\"a\").Attr(\"href\"); found {\n\t\tp.NextUrl = nextUrl\n\t} else {\n\t\treturn nil, fmt.Errorf(\"Could not retreive next hackernews page. Time to go outside?\")\n\t}\n\n\t//Make sure NextUrl doesn't start with forward slash\n\tfor len(p.NextUrl) > 0 && p.NextUrl[0] == '/' {\n\t\tp.NextUrl = p.NextUrl[1:]\n\t}\n\n\t//Parse articles\n\trows.Each(func(i int, row *goquery.Selection) {\n\t\tar := Article{\n\t\t\tRank: len(p.Articles) + i,\n\t\t}\n\n\t\ttitle := row.Find(\".title\").Eq(1)\n\t\tlink := title.Find(\"a\").First()\n\n\t\tar.Title = html.UnescapeString(link.Text())\n\n\t\tif url, exists := link.Attr(\"href\"); exists {\n\t\t\tar.Url = url\n\t\t}\n\n\t\t//Rows are used in pairs currently\n\t\trow = row.Next()\n\n\t\trow.Find(\"span\").Each(func(i int, s *goquery.Selection) {\n\t\t\tif karma, err := strconv.Atoi(strings.Split(s.Text(), \" \")[0]); err == nil {\n\t\t\t\tar.Karma = karma\n\t\t\t}\n\n\t\t\tif idSt, exists := s.Attr(\"id\"); exists {\n\t\t\t\tif id, err := strconv.Atoi(strings.Split(idSt, \"_\")[1]); err == nil {\n\t\t\t\t\tar.Id = id\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\tsub := row.Find(\"td.subtext\")\n\t\tt := html.UnescapeString(sub.Text())\n\n\t\t//We can ignore the error safely here\n\t\tar.Created, _ = parseCreated(t)\n\n\t\t//Get the username\n\t\tar.User = html.UnescapeString(sub.Find(\"a\").First().Text())\n\n\t\t//Get number of comments\n\t\tcomStr := strings.Split(sub.Find(\"a\").Last().Text(), \" \")[0]\n\n\t\tif comNum, err := strconv.Atoi(comStr); err == nil {\n\t\t\tar.NumComments = comNum\n\t\t}\n\n\t\tp.Articles = append(p.Articles, &ar)\n\t})\n\n\treturn p, nil\n}",
"func LoadPtr(ptr interface{}, fn string, f DataFmt) error {\n\tif _, err := os.Stat(fn); os.IsNotExist(err) {\n\t\treturn errors.New(\"file doesn't exist\")\n\t}\n\n\tb, err := ioutil.ReadFile(fn)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := UnmarshalPtr(ptr, b, f); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func Load(fn string, f DataFmt) (interface{}, error) {\n\tif _, err := os.Stat(fn); os.IsNotExist(err) {\n\t\treturn nil, errors.New(\"file doesn't exist\")\n\t}\n\n\tb, err := ioutil.ReadFile(fn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td, err := Unmarshal(b, f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn d, nil\n}",
"func (n DotReference) Load(block *ir.BasicBlock, s *Scope, c *Compiler) *ir.InstLoad {\n\ttarget := n.Alloca(s, c).(*ir.InstGetElementPtr)\n\ttarget.Typ = types.NewPointer(n.Type(s, c))\n\treturn block.NewLoad(target)\n}",
"func (f *factory) AcquirePage(index int64) (MappedPage, error) {\n\tf.mutex.Lock()\n\tdefer f.mutex.Unlock()\n\n\tif f.closed.Load() {\n\t\treturn nil, errFactoryClosed\n\t}\n\n\tpage, ok := f.pages[index]\n\tif ok {\n\t\treturn page, nil\n\t}\n\n\tpage, err := NewMappedPage(f.pageFileName(index), f.pageSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tf.pages[index] = page\n\tf.size.Add(int64(f.pageSize))\n\n\treturn page, nil\n}",
"func (c *ChunkRef) Load(ps []datastore.Property) error {\n\treturn datastore.LoadStruct(c, ps)\n}",
"func (x *PDFObj) Ref() *C.pdf_obj {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_obj)(unsafe.Pointer(x))\n}",
"func ReadPdf(pdffile []byte) (*PdfData, error) {\n\tbyteReader := bytes.NewReader(pdffile)\n\tpdfReader, err := pdf.NewReader(byteReader, byteReader.Size())\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"pdf.NewReader(...) fail\")\n\t}\n\treturn unmarshal(pdfReader)\n}",
"func getPage(url string) (body io.ReadCloser) {\n\t// Retrieve the page\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Fatalf(\"Response Error: %v\", err)\n\t}\n\tresp.Close = true\n\tbody = resp.Body\n\treturn\n}",
"func ParsePdf(fileName string) (*PdfInfo, error) {\n\tpdfInfo := PdfInfo{}\n\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\tlogError(err)\n\t\treturn &pdfInfo, err\n\t}\n\n\tdefer file.Close()\n\n\tversion, err := readPdfInfoVersion(file)\n\tif err != nil {\n\t\tlogError(err)\n\t\treturn &pdfInfo, err\n\t}\n\n\tpdfInfo.PdfVersion = version\n\n\tpdfInfo.PagesCount = countPages(file)\n\n\terr = readXrefOffset(file, &pdfInfo)\n\tif err != nil {\n\t\tlogError(err)\n\t\treturn &pdfInfo, err\n\t}\n\n\tgetTrailerSection(file, &pdfInfo)\n\n\t// original xref\n\terr, parsedXref, trailerSection := readXrefBlock(file, pdfInfo.OriginalXrefOffset, true)\n\tif err != nil {\n\t\tlogError(err)\n\t\treturn &pdfInfo, err\n\t}\n\tpdfInfo.XrefTable = append(pdfInfo.XrefTable, parsedXref)\n\tpdfInfo.AdditionalTrailerSection = append(pdfInfo.AdditionalTrailerSection, trailerSection)\n\n\treadAllXrefSections(file, &pdfInfo, pdfInfo.OriginalTrailerSection.Prev)\n\n\tif trailerSection != nil {\n\t\treadAllXrefSections(file, &pdfInfo, trailerSection.Prev)\n\t}\n\n\troot := findRootObject(&pdfInfo, file)\n\tif root == nil {\n\t\terr = cannotFindRootObject\n\t\tlogError(err)\n\t\treturn &pdfInfo, nil\n\t}\n\tpdfInfo.Root = *root\n\n\tinfo := searchInfoSection(&pdfInfo, file)\n\tif info == nil {\n\t\terr = cannotFindInfoObject\n\t\tlogError(err)\n\t\treturn &pdfInfo, nil\n\t}\n\tpdfInfo.Info = *info\n\n\tmeta, err := findMetadataObject(&pdfInfo, file)\n\tlogError(err)\n\tif meta != nil {\n\t\tpdfInfo.Metadata = *meta\n\t}\n\n\treturn &pdfInfo, nil\n}",
"func (x *PDFRevPageMap) Ref() *C.pdf_rev_page_map {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_rev_page_map)(unsafe.Pointer(x))\n}",
"func (fb *FlowBuilder) Load(rawData []byte) *FlowBuilder {\n\tfb.flow = flow.New()\n\tfb.flow.UseRegistry(fb.registry)\n\n\tdoc := &FlowDocument{[]Node{}, []Link{}, []Trigger{}}\n\tlog.Println(\"Loading document from:\", string(rawData))\n\terr := json.Unmarshal(rawData, doc)\n\tif err != nil {\n\t\tfb.Err = err\n\t\treturn fb\n\t}\n\n\tfb.Doc = doc\n\n\treturn fb\n}",
"func (x *PDFDocument) Ref() *C.pdf_document {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_document)(unsafe.Pointer(x))\n}",
"func (f *DefaultFactory) PageFromURL(ctx context.Context, origURLtext string, options ...interface{}) (Content, error) {\n\tif len(origURLtext) == 0 {\n\t\treturn nil, targetURLIsBlankError(xerrors.Caller(xErrorsFrameCaller))\n\t}\n\n\t// Use the standard Go HTTP library method to retrieve the Content; the default will automatically follow redirects (e.g. HTTP redirects)\n\thttpClient := f.httpClient(ctx)\n\treq, reqErr := http.NewRequest(http.MethodGet, origURLtext, nil)\n\tif reqErr != nil {\n\t\treturn nil, xerrors.Errorf(\"Unable to create HTTP request: %w\", reqErr)\n\t}\n\tf.prepareHTTPRequest(ctx, httpClient, req)\n\tresp, getErr := httpClient.Do(req)\n\tif getErr != nil {\n\t\treturn nil, xerrors.Errorf(\"Unable to execute HTTP GET request: %w\", getErr)\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\treturn nil, &InvalidHTTPRespStatusCodeError{\n\t\t\tURL: origURLtext,\n\t\t\tHTTPStatusCode: resp.StatusCode,\n\t\t\tFrame: xerrors.Caller(xErrorsFrameCaller)}\n\t}\n\n\treturn f.pageFromHTTPResponse(ctx, resp.Request.URL, resp, options...)\n}",
"func Page(c *fiber.Ctx) {\n\tShopID := c.Params(\"shop_id\")\n\tuserID := userIDF(c.Get(\"token\"))\n\tvar PageFromSQL PageSQL\n\tvar PagePointer PagesPointer\n\tvar response PageInformation\n\n\tErrorPage := sq.Select(\n\t\t\"active\",\n\t\t\"template_type\",\n\t\t\"style_sheets\",\n\t\t\"active_days\",\n\t\t\"images_days\",\n\t\t\"offers_active\",\n\t\t\"accept_card_active\",\n\t\t\"subdomain\",\n\t\t\"domain\",\n\t\t\"shop.shop_id\",\n\t\t\"pages_id\",\n\t\t\"type_charge\",\n\t\t\"shop_name\",\n\t\t\"description\",\n\t\t\"cover_image\",\n\t\t\"logo\",\n\t\t\"shop.user_id\",\n\t).\n\t\tFrom(\"pages\").\n\t\tLeftJoin(\"plans_pay on pages.shop_id = plans_pay.shop_id\").\n\t\tLeftJoin(\"shop on pages.shop_id = shop.shop_id\").\n\t\tWhere(\"pages.shop_id = ? AND shop.user_id = ?\", ShopID, userID).\n\t\tRunWith(database).\n\t\tQueryRow().\n\t\tScan(\n\t\t\t&PageFromSQL.Active,\n\t\t\t&PageFromSQL.TemplateType,\n\t\t\t&PageFromSQL.StyleSheets,\n\t\t\t&PageFromSQL.ActiveDays,\n\t\t\t&PageFromSQL.ImagesDays,\n\t\t\t&PageFromSQL.OffersActive,\n\t\t\t&PageFromSQL.AcceptCardActive,\n\t\t\t&PageFromSQL.Subdomain,\n\t\t\t&PageFromSQL.Domain,\n\t\t\t&PageFromSQL.ShopID,\n\t\t\t&PageFromSQL.PagesID,\n\t\t\t&PageFromSQL.TypeCharge,\n\t\t\t&PageFromSQL.ShopName,\n\t\t\t&PageFromSQL.Description,\n\t\t\t&PageFromSQL.CoverImage,\n\t\t\t&PageFromSQL.Logo,\n\t\t\t&PageFromSQL.UserID,\n\t\t)\n\n\tif ErrorPage != nil {\n\t\tfmt.Println(ErrorPage, \"Error get page\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with get page\"})\n\t\tc.SendStatus(400)\n\t\treturn\n\t}\n\n\tActive, _ := strconv.Atoi(PageFromSQL.Active.String)\n\tPagePointer.Active = Active\n\tTemplateType, _ := strconv.Atoi(PageFromSQL.TemplateType.String)\n\tPagePointer.TemplateType = TemplateType\n\tStyleSheets, _ := strconv.Atoi(PageFromSQL.StyleSheets.String)\n\tPagePointer.StyleSheets = StyleSheets\n\tActiveDays, _ := strconv.Atoi(PageFromSQL.ActiveDays.String)\n\tPagePointer.ActiveDays = ActiveDays\n\tImagesDays, _ := strconv.Atoi(PageFromSQL.ImagesDays.String)\n\tPagePointer.ImagesDays = ImagesDays\n\tOffersActive, _ := strconv.Atoi(PageFromSQL.OffersActive.String)\n\tPagePointer.OffersActive = OffersActive\n\tAcceptCardActive, _ := strconv.Atoi(PageFromSQL.AcceptCardActive.String)\n\tPagePointer.AcceptCardActive = AcceptCardActive\n\tPagePointer.Subdomain = &PageFromSQL.Subdomain.String\n\tPagePointer.Domain = &PageFromSQL.Domain.String\n\tPagePointer.ShopID = &PageFromSQL.ShopID.String\n\tPagePointer.PagesID = &PageFromSQL.PagesID.String\n\tPagePointer.TypeCharge = &PageFromSQL.TypeCharge.String\n\tPagePointer.ShopName = &PageFromSQL.ShopName.String\n\tPagePointer.Description = &PageFromSQL.Description.String\n\tPagePointer.CoverImage = &PageFromSQL.CoverImage.String\n\tPagePointer.Logo = &PageFromSQL.Logo.String\n\tPagePointer.UserID = &PageFromSQL.UserID.String\n\n\tresponse.Page = PagePointer\n\tUserID := *PagePointer.UserID\n\tif UserID == userID {\n\t\tc.JSON(response)\n\t} else {\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Not is owner or active shop\"})\n\t}\n}",
"func GetPDFPage(pdfName string, imageName string, pageNum int) error {\n\n\tabsPath, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tInpath := filepath.Join(absPath, \"input\", pdfName)\n\tOutpath := filepath.Join(absPath, \"output\")\n\n\tif _, err := os.Stat(Outpath); os.IsNotExist(err) {\n\t\tlog.Println(\"Output dir not found. Creating at \", Outpath)\n\t\tos.Mkdir(Outpath, os.ModePerm)\n\t}\n\n\timagick.Initialize()\n\tdefer imagick.Terminate()\n\n\tmw := imagick.NewMagickWand()\n\tdefer mw.Destroy()\n\n\tif err := mw.SetResolution(72, 72); err != nil {\n\t\treturn err\n\t}\n\n\t// Load the image file into imagick\n\tif err := mw.ReadImage(Inpath); err != nil {\n\t\treturn err\n\t}\n\n\tmw.SetIteratorIndex(pageNum - 1)\n\n\t// Set any compression (100 = max quality)\n\tif err := mw.SetCompressionQuality(100); err != nil {\n\t\treturn err\n\t}\n\n\t// Convert into JPG\n\tif err := mw.SetFormat(\"jpg\"); err != nil {\n\t\treturn err\n\t}\n\n\t// Save File\n\treturn mw.WriteImage(filepath.Join(Outpath, imageName))\n}",
"func UpdatePage(xRefTable *model.XRefTable, dIndRef types.IndirectRef, d, res types.Dict, p *model.Page, fonts model.FontMap) error {\n\n\t// TODO Account for existing page rotation.\n\n\terr := updatePageResources(xRefTable, d, res, *p, fonts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = xRefTable.AppendContent(d, p.Buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(p.AnnotTabs) == 0 && len(p.Annots) == 0 && len(p.LinkAnnots) == 0 {\n\t\treturn nil\n\t}\n\n\tif err := setAnnotationParentsAndFields(xRefTable, p, dIndRef); err != nil {\n\t\treturn err\n\t}\n\n\tannots, err := xRefTable.DereferenceArray(d[\"Annots\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tarr, err := mergeAnnotations(annots, p.Annots, p.AnnotTabs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, la := range p.LinkAnnots {\n\t\td, err := la.RenderDict(xRefTable, dIndRef)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tir, err := xRefTable.IndRefForNewObject(d)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tarr = append(arr, *ir)\n\t}\n\n\td[\"Annots\"] = arr\n\n\treturn nil\n}",
"func (o *Range) GetPage() gdnative.Real {\n\t//log.Println(\"Calling Range.GetPage()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"Range\", \"get_page\")\n\n\t// Call the parent method.\n\t// float\n\tretPtr := gdnative.NewEmptyReal()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewRealFromPointer(retPtr)\n\treturn ret\n}",
"func (client *ClientImpl) AddPage(ctx context.Context, args AddPageArgs) (*Page, error) {\n\tif args.Page == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.Page\"}\n\t}\n\trouteValues := make(map[string]string)\n\tif args.ProcessId == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.ProcessId\"}\n\t}\n\trouteValues[\"processId\"] = (*args.ProcessId).String()\n\tif args.WitRefName == nil || *args.WitRefName == \"\" {\n\t\treturn nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: \"args.WitRefName\"}\n\t}\n\trouteValues[\"witRefName\"] = *args.WitRefName\n\n\tbody, marshalErr := json.Marshal(*args.Page)\n\tif marshalErr != nil {\n\t\treturn nil, marshalErr\n\t}\n\tlocationId, _ := uuid.Parse(\"1cc7b29f-6697-4d9d-b0a1-2650d3e1d584\")\n\tresp, err := client.Client.Send(ctx, http.MethodPost, locationId, \"6.0-preview.1\", routeValues, nil, bytes.NewReader(body), \"application/json\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue Page\n\terr = client.Client.UnmarshalBody(resp, &responseValue)\n\treturn &responseValue, err\n}",
"func (g *Generator) loadTemplate(t *template.Template, tmplPath string) (*template.Template, error) {\n\t// Make the filepath relative to the filemap.\n\ttmplPath = g.FileMap.relative(tmplPath)[0]\n\n\t// Determine the open function.\n\treadFile := g.ReadFile\n\tif readFile == nil {\n\t\treadFile = ioutil.ReadFile\n\t}\n\n\t// Read the file.\n\tdata, err := readFile(tmplPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a new template and parse.\n\t_, name := path.Split(tmplPath)\n\treturn t.New(name).Parse(string(data))\n}",
"func Loader(url string) (*goquery.Document, error) {\n\tres, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer res.Body.Close()\n\tif res.StatusCode == 404 {\n\t\tfmt.Println(\"Workout is not available.\")\n\t\tos.Exit(404)\n\t}\n\n\tdoc, err := goquery.NewDocumentFromReader(res.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn doc, err\n}",
"func (fw *FireWriter) Load(ctx context.Context, uuid string) (*Record, report.Span) {\n\tctx, cancel := context.WithTimeout(ctx, fw.Timeout)\n\tdefer cancel()\n\n\tspan := report.StartSpan(\"firestore.load\").Field(\"uuid\", uuid)\n\n\tdoc, err := fw.Collection.Doc(uuid).Get(ctx)\n\tif err != nil {\n\t\tif status.Code(err) == codes.NotFound {\n\t\t\t// in this case the document simply does not exist so\n\t\t\t// return a nil pointer to indicate this and no span\n\t\t\t// error\n\t\t\treturn nil, span.End()\n\t\t}\n\t\treturn nil, span.End(err)\n\t}\n\tvar record Record\n\tif err := doc.DataTo(&record); err != nil {\n\t\t// in this case assume that the data has changed format or\n\t\t// similar and this is not an error in so much as an indication\n\t\t// to re-write.\n\t\tspan = span.Field(\"corruption\", err.Error())\n\t\treturn nil, span.End()\n\t}\n\treturn &record, span.End()\n}",
"func (p *PdfiumImplementation) FPDFPage_Flatten(request *requests.FPDFPage_Flatten) (*responses.FPDFPage_Flatten, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tflattenPageResult := C.FPDFPage_Flatten(pageHandle.handle, C.int(request.Usage))\n\n\treturn &responses.FPDFPage_Flatten{\n\t\tPage: pageHandle.index,\n\t\tResult: responses.FPDFPage_FlattenResult(flattenPageResult),\n\t}, nil\n}",
"func Load(path string, object interface{}) error {\n\tfile, err := os.Open(path)\n\tdefer file.Close()\n\tif err != nil {\n\t\tlog.Error(\"Was not able to open file\", \"path\", path, \"error\", err)\n\t\treturn err\n\t}\n\tdecoder := gob.NewDecoder(file)\n\terr = decoder.Decode(object)\n\tif err != nil {\n\t\tlog.Error(\"Was not able to decode file.\", \"path\", path, \"error\", err)\n\t}\n\treturn err\n}",
"func (a *PDFApiService) LoadDocumentAsPDFMultipart(ctx _context.Context, fileData *os.File, localVarOptionals *LoadDocumentAsPDFMultipartOpts) (PdfLoadDocumentResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue PdfLoadDocumentResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/pdf/LoadDocumentAsPDFMultipart\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"multipart/form-data\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarFormFileName = \"fileData\"\n\tlocalVarFile := fileData\n\tif localVarFile != nil {\n\t\tfbs, _ := _ioutil.ReadAll(localVarFile)\n\t\tlocalVarFileBytes = fbs\n\t\tlocalVarFileName = localVarFile.Name()\n\t\tlocalVarFile.Close()\n\t}\n\tif localVarOptionals != nil && localVarOptionals.LoadDocumentParameters.IsSet() {\n\t\tparamJson, err := parameterToJson(localVarOptionals.LoadDocumentParameters.Value())\n\t\tif err != nil {\n\t\t\treturn localVarReturnValue, nil, err\n\t\t}\n\t\tlocalVarFormParams.Add(\"loadDocumentParameters\", paramJson)\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v PdfLoadDocumentResponse\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}",
"func Load(data []byte) (*File, error) {\n\treturn loadData(data)\n}",
"func (p *atomicMSpanPointer) Load() *mspan {\n\treturn (*mspan)(p.p.Load())\n}",
"func main() {\n\tp1 := &gowiki.Page{Title: \"TestPage\", Body: []byte(\"This is a sample Page.\")}\n\tp1.Save()\n\tp2, _ := gowiki.LoadPage(\"TestPage\")\n\tfmt.Println(string(p2.Body))\n}",
"func (s *SimPDF) NewPage(page models.Pages) {\n\ts.Page = page\n\ts.PDF.AddPageFormat(page.ToPDFOrientation(), gofpdf.SizeType{Wd: page.Width, Ht: page.Height})\n}",
"func (p *PdfiumImplementation) FPDF_GetPageWidth(request *requests.FPDF_GetPageWidth) (*responses.FPDF_GetPageWidth, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twidth := C.FPDF_GetPageWidth(pageHandle.handle)\n\n\treturn &responses.FPDF_GetPageWidth{\n\t\tPage: pageHandle.index,\n\t\tWidth: float64(width),\n\t}, nil\n}",
"func (x *PDFProcessor) Ref() *C.pdf_processor {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_processor)(unsafe.Pointer(x))\n}",
"func (b *Builder) Load(ty protocol.Type, addr value.Pointer) {\n\tif !addr.IsValid() {\n\t\tpanic(fmt.Errorf(\"Pointer address %v is not valid\", addr))\n\t}\n\tb.pushStack(ty)\n\tb.instructions = append(b.instructions, asm.Load{\n\t\tDataType: ty,\n\t\tSource: b.remap(addr),\n\t})\n}",
"func buildPage(dir, fileName string) Page {\n\tp := _buildPage(dir, fileName)\n\tmeta, err := loadMeta(p.FullPath)\n\tif err != nil {\n\t\tdie(\"Failed to load meta from file (%s), err: (%s)\", p.FullPath, err)\n\t}\n\tp.Meta = meta\n\treturn p\n}",
"func LoadFont(path string) (*truetype.Font, error) {\n bytes, errRead := ioutil.ReadFile(path)\n if errRead != nil {\n return nil, errRead\n }\n\n font, errParse := freetype.ParseFont(bytes)\n\n return font, errParse\n}",
"func (d *Drawer) load() error {\n\tdata, err := ioutil.ReadFile(d.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(data) > 0 {\n\t\tvar payload interface{}\n\t\tpayload, err = d.serializer.Deserialize(data)\n\t\tif !isPointer(payload) {\n\t\t\tpanic(NonPointerErr)\n\t\t}\n\t\td.payload = payload\n\t} else {\n\t\td.payload = nil\n\t}\n\treturn err\n}",
"func (p *PdfiumImplementation) FPDF_PageToDevice(request *requests.FPDF_PageToDevice) (*responses.FPDF_PageToDevice, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdeviceX := C.int(0)\n\tdeviceY := C.int(0)\n\n\tsuccess := C.FPDF_PageToDevice(pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.double(request.PageX), C.double(request.PageY), &deviceX, &deviceY)\n\tif int(success) == 0 {\n\t\treturn nil, errors.New(\"could not calculate from page to device\")\n\t}\n\n\treturn &responses.FPDF_PageToDevice{\n\t\tDeviceX: int(deviceX),\n\t\tDeviceY: int(deviceY),\n\t}, nil\n}",
"func deserializePage(data []byte, encrypted bool, masterKey []byte) (*pageHead, []byte, error) {\n\theadBytes := data[:PAGE_HEAD_SIZE-IV_SIZE]\n\tivBytes := data[PAGE_HEAD_SIZE-IV_SIZE : PAGE_HEAD_SIZE]\n\tdataBytes := data[PAGE_HEAD_SIZE:]\n\tif !encrypted {\n\t\treturn deserializePageHead(headBytes), dataBytes, nil\n\t}\n\n\tdecHead, err := util.DecryptCFB(headBytes, ivBytes, masterKey, false)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdecData, err := util.DecryptCFB(dataBytes, ivBytes, masterKey, false)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn deserializePageHead(decHead), decData, nil\n}",
"func (r *RMFileInfo) PageIterate() (pageNo, pdfPageNo int, inserted, isTemplate bool, reader *io.ReadSeeker) {\n\tpageNo = r.thisPageNo\n\tr.thisPageNo++\n\n\t// if there is only a template, always return the first page\n\tif r.pdfPath == \"\" {\n\t\tpdfPageNo = 0\n\t\tisTemplate = true\n\t\treader = &r.templateReader\n\t\treturn\n\t}\n\n\t// older remarkable bundles don't report inserted pages; ignore\n\thasRedir := func() bool { return len(r.RedirectionPageMap) > 0 }()\n\n\t// return the template if this is an inserted page\n\tif hasRedir && r.RedirectionPageMap[pageNo] == -1 {\n\t\tpdfPageNo = 0\n\t\tinserted = true\n\t\tisTemplate = true\n\t\treader = &r.templateReader\n\t\treturn\n\t}\n\n\t// remaining target is the annotated file\n\treader = &r.pdfReader\n\n\t// if the annotated pdf has inserted pages, calculate the offset of\n\t// the original pdf to use\n\tif hasRedir && r.PageCount != r.OriginalPageCount {\n\t\tpdfPageNo = pageNo\n\t\tfor i := 0; i <= pageNo; i++ {\n\t\t\tif r.RedirectionPageMap[i] == -1 {\n\t\t\t\tpdfPageNo--\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\t// fall through: the annotated pdf has no inserted pages\n\tpdfPageNo = pageNo\n\treturn\n\n}",
"func LoadEditPage(w http.ResponseWriter, r *http.Request) {\n\tparameters := mux.Vars(r)\n\tpublicationID, err := strconv.ParseUint(parameters[\"publicationId\"], 10, 64)\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusBadRequest, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\turl := fmt.Sprintf(\"%s/publications/%d\", config.APIURL, publicationID)\n\tresponse, err := requests.RequestsWithAuthentication(r, http.MethodGet, url, nil)\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\n\tif response.StatusCode >= 400 {\n\t\tresponses.TreatStatusCode(w, response)\n\t\treturn\n\t}\n\n\tvar publication models.Publication\n\tif err = json.NewDecoder(response.Body).Decode(&publication); err != nil {\n\t\tresponses.JSON(w, http.StatusUnprocessableEntity, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\tutils.RunTemplate(w, \"edit-publication.html\", publication)\n}",
"func (p *PdfiumImplementation) FPDF_GetPageHeight(request *requests.FPDF_GetPageHeight) (*responses.FPDF_GetPageHeight, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theight := C.FPDF_GetPageHeight(pageHandle.handle)\n\n\treturn &responses.FPDF_GetPageHeight{\n\t\tPage: pageHandle.index,\n\t\tHeight: float64(height),\n\t}, nil\n}",
"func NewPage(pathToDir string) (*Page, error) {\n\tallFiles, err := ioutil.ReadDir(pathToDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar mdFile, modtime string\n\tfor _, f := range allFiles {\n\t\tif path.Ext(f.Name()) == \".md\" {\n\t\t\tmdFile = path.Join(pathToDir, f.Name())\n\t\t\tmodtime = DateFormat(f.ModTime())\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif mdFile == \"\" {\n\t\treturn nil, ErrMarkdownMissing\n\t}\n\n\tbuf, err := ioutil.ReadFile(mdFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpage := &Page{\n\t\tID: path.Base(pathToDir),\n\t\tPublished: modtime,\n\t}\n\n\ttitle := rePageTitle.FindSubmatch(buf)\n\tif title == nil {\n\t\treturn nil, ErrPageMissingTitle\n\t}\n\tpage.Title = string(title[1])\n\t// remove the blog's title from the markdown\n\tbuf = bytes.Replace(buf, append(title[0], []byte(\"\\n\\n\")...), nil, 1)\n\n\tdesc := rePageDesc.FindSubmatch(buf)\n\tif desc == nil {\n\t\treturn nil, ErrPageMissingDesc\n\t}\n\tpage.Desc = string(desc[1])\n\t// remove the blog's description from the markdown\n\tbuf = bytes.Replace(buf, append(desc[0], []byte(\"\\n\\n\")...), nil, 1)\n\n\timages := rePageImages.FindAllSubmatch(buf, -1)\n\tif images != nil {\n\t\tpage.Images = make(map[string]*Image, len(images))\n\n\t\tfor i := range images {\n\t\t\torigName := string(images[i][1])\n\t\t\t// skip any \"hot linked\" images\n\t\t\tif strings.HasPrefix(origName, \"http\") {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif _, exists := page.Images[origName]; exists == false {\n\t\t\t\timg, err := NewImage(path.Join(pathToDir, origName))\n\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tpage.Images[origName] = img\n\t\t\t\tbuf = bytes.Replace(buf, []byte(origName), []byte(img.URL()), -1)\n\t\t\t}\n\t\t}\n\t}\n\n\ttags := rePageTags.FindAllSubmatch(buf, -1)\n\tif tags == nil {\n\t\treturn nil, ErrPageMissingTags\n\t}\n\n\tfor i := range tags {\n\t\tt := bytes.Split(tags[i][1], []byte(\",\"))\n\t\tfor _, tag := range t {\n\t\t\tpage.Tags = append(page.Tags, strings.ToLower(string(tag)))\n\t\t}\n\t}\n\n\tpage.buffer = buf\n\n\treturn page, nil\n}",
"func (l *Container) AddPage(lines []*line.Line, pagination *Pagination, r *colly.Response) {\n\tmux.Lock()\n\tdefer mux.Unlock()\n\n\tcurrentPage := 1\n\tif pagination != nil {\n\t\tcurrentPage = pagination.Current\n\t}\n\n\tl.Data[currentPage] = lines\n}"
] | [
"0.6464095",
"0.6436409",
"0.6112568",
"0.61096996",
"0.61042666",
"0.607902",
"0.6069582",
"0.59660184",
"0.5950949",
"0.5822402",
"0.5804378",
"0.5703693",
"0.56582296",
"0.5496194",
"0.5469633",
"0.5447506",
"0.5422935",
"0.53451717",
"0.5252272",
"0.52036107",
"0.5165741",
"0.5120743",
"0.51174504",
"0.51094985",
"0.5082353",
"0.505334",
"0.49588382",
"0.49501425",
"0.488691",
"0.48859254",
"0.48235765",
"0.4795401",
"0.47743618",
"0.47312945",
"0.4728668",
"0.46976516",
"0.46919936",
"0.46786225",
"0.46400815",
"0.46338147",
"0.46149135",
"0.4595903",
"0.45760396",
"0.4570972",
"0.45686865",
"0.45532843",
"0.4536912",
"0.45312977",
"0.45227098",
"0.45091373",
"0.44843337",
"0.44750586",
"0.44741076",
"0.4470887",
"0.4460266",
"0.4457311",
"0.44449985",
"0.44369185",
"0.44364116",
"0.44141713",
"0.441071",
"0.44074637",
"0.44062448",
"0.44029403",
"0.44019178",
"0.4393992",
"0.43811154",
"0.43672788",
"0.43638664",
"0.43606114",
"0.4359749",
"0.43584946",
"0.43382943",
"0.43372133",
"0.433219",
"0.43302232",
"0.4327652",
"0.4323063",
"0.4318827",
"0.43140972",
"0.4310763",
"0.4304072",
"0.42965093",
"0.42884833",
"0.42862642",
"0.42851013",
"0.42681992",
"0.42571187",
"0.4253616",
"0.4234173",
"0.4232893",
"0.42314696",
"0.42310995",
"0.42267007",
"0.42210743",
"0.4220286",
"0.42151833",
"0.4208125",
"0.42073277",
"0.42049533"
] | 0.72359073 | 0 |
FPDF_ClosePage unloads a page by reference. | func (p *PdfiumImplementation) FPDF_ClosePage(request *requests.FPDF_ClosePage) (*responses.FPDF_ClosePage, error) {
p.Lock()
defer p.Unlock()
pageRef, err := p.getPageHandle(request.Page)
if err != nil {
return nil, err
}
pageRef.Close()
delete(p.pageRefs, request.Page)
// Remove page reference from document.
documentHandle, err := p.getDocumentHandle(pageRef.documentRef)
if err != nil {
return nil, err
}
delete(documentHandle.pageRefs, request.Page)
return &responses.FPDF_ClosePage{}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (x *PDFPage) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (p *PdfiumImplementation) FPDFText_ClosePage(request *requests.FPDFText_ClosePage) (*responses.FPDFText_ClosePage, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\ttextPageHandle, err := p.getTextPageHandle(request.TextPage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdocumentHandle, err := p.getDocumentHandle(textPageHandle.documentRef)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tC.FPDFText_ClosePage(textPageHandle.handle)\n\n\t// Cleanup refs\n\tdelete(p.textPageRefs, textPageHandle.nativeRef)\n\tdelete(documentHandle.textPageRefs, textPageHandle.nativeRef)\n\n\treturn &responses.FPDFText_ClosePage{}, nil\n}",
"func (p *Page) close() error {\n\tio.Copy(ioutil.Discard, p.body)\n\treturn p.body.Close()\n}",
"func (x *FzStextPage) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzPage) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (f *Footer) Close() error {\n\tf.DecRef()\n\treturn nil\n}",
"func (x *PDFRevPageMap) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (f *factory) Close() error {\n\tif f.closed.CAS(false, true) {\n\t\tf.mutex.Lock()\n\t\tdefer f.mutex.Unlock()\n\n\t\tfor _, page := range f.pages {\n\t\t\tif err := page.Close(); err != nil {\n\t\t\t\tpageLogger.Error(\"close mapped page data err\",\n\t\t\t\t\tlogger.String(\"path\", f.path), logger.Error(err))\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}",
"func (page *Page) Close() error {\n\tif err := page.stream.Close(); err != nil {\n\t\treturn errors.Wrap(err, \"failed to close Page stream\")\n\t}\n\tpage.closed = true\n\treturn nil\n}",
"func (f *Font) Close() {\n\tC.TTF_CloseFont(f.f)\n\tf.f = nil\n}",
"func (x *PDFDocEvent) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFDocument) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (p *PdfiumImplementation) FPDF_CloseDocument(request *requests.FPDF_CloseDocument) (*responses.FPDF_CloseDocument, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tnativeDocument, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = nativeDocument.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelete(p.documentRefs, nativeDocument.nativeRef)\n\n\treturn &responses.FPDF_CloseDocument{}, nil\n}",
"func (x *PDFXref) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (p *bytesViewer) Close() error { return nil }",
"func (d *Detector) Close() {\n\tC.fvad_free(d.fvad)\n\td.fvad = nil\n}",
"func (x *PDFUnsavedSig) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFXrefEntry) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFRange) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (f *FileBlob) Free() {\n\tf.blob = nil\n}",
"func (masterPage *MasterPage) CloseCurrentPage() {\n\tpopped := masterPage.subPages.Pop()\n\tif popped {\n\t\tmasterPage.ParentWindow().Reload()\n\t}\n}",
"func (x *PDFWidget) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFMailDocEvent) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFHotspot) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (a *PDFApiService) ClosePDF(ctx _context.Context, pdfCloseDocumentParameters PdfCloseDocumentParameters) (PdfCloseDocumentResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue PdfCloseDocumentResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/pdf/ClosePDF\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json-patch+json\", \"application/json\", \"text/json\", \"application/_*+json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &pdfCloseDocumentParameters\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v PdfCloseDocumentResponse\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}",
"func (masterPage *MasterPage) ClosePagesAfter(keepPageID string) {\n\tpopped := masterPage.subPages.PopAfter(func(page Page) bool {\n\t\treturn page.ID() == keepPageID\n\t})\n\tif popped {\n\t\tmasterPage.ParentWindow().Reload()\n\t}\n}",
"func (a *PDFApiService) ClearPage(ctx _context.Context, pdfClearPageParameters PdfClearPageParameters) (PdfClearPageResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue PdfClearPageResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/pdf/ClearPage\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json-patch+json\", \"application/json\", \"text/json\", \"application/_*+json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &pdfClearPageParameters\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v PdfClearPageResponse\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}",
"func (x *PDFGstate) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzDocumentHandler) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (r *MMapRef) Close() error { return r.DecRef() }",
"func (x *FzDocument) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (dv DomVisit) Close() {\n\tif dv.badFile != nil {\n\t\terr := dv.badFile.Close()\n\t\tcheck(err)\n\t}\n}",
"func (x *PDFSubmitEvent) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (f *Footer) DecRef() {\n\tf.m.Lock()\n\tf.refs--\n\tif f.refs <= 0 {\n\t\tf.SegmentLocs.DecRef()\n\t\tf.SegmentLocs = nil\n\t\tf.ss = nil\n\t}\n\tf.m.Unlock()\n}",
"func (x *PDFXrefSubsec) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFMrange) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFLaunchUrlEvent) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (a *PDFApiService) DeletePage(ctx _context.Context, pdfDeletePageParameters PdfDeletePageParameters) (PdfDeletePageResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue PdfDeletePageResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/pdf/DeletePage\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json-patch+json\", \"application/json\", \"text/json\", \"application/_*+json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &pdfDeletePageParameters\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v PdfDeletePageResponse\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}",
"func (x *PDFCmap) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFUiEvent) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func FileClose(f *os.File,) error",
"func (x *FzPage) Ref() *C.fz_page {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.fz_page)(unsafe.Pointer(x))\n}",
"func (masterPage *MasterPage) CloseAllPages() {\n\tmasterPage.subPages.Reset()\n\tmasterPage.ParentWindow().Reload()\n}",
"func (p *PdfiumImplementation) FPDFLink_CloseWebLinks(request *requests.FPDFLink_CloseWebLinks) (*responses.FPDFLink_CloseWebLinks, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageLinkhandle, err := p.getPageLinkHandle(request.PageLink)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdocumentHandle, err := p.getDocumentHandle(pageLinkhandle.documentRef)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tC.FPDFLink_CloseWebLinks(pageLinkhandle.handle)\n\n\t// Cleanup refs\n\tdelete(p.pageLinkRefs, pageLinkhandle.nativeRef)\n\tdelete(documentHandle.pageLinkRefs, pageLinkhandle.nativeRef)\n\n\treturn &responses.FPDFLink_CloseWebLinks{}, nil\n}",
"func (x *PDFAnnot) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFGraftMap) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFXrange) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func frameFinalizer(f *Frame) {\n\truntime.SetFinalizer(f, func(f *Frame) { gobject.Unref(f) })\n}",
"func (x *PDFCsi) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func closeFile(f *os.File) {\n\t_ = f.Close()\n}",
"func (x *PDFProcessor) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (p *Page) ClosePath() {\n\tfmt.Fprint(p.contents, \"h \")\n}",
"func (x *PDFDaInfo) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFXobject) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (s *PageStore) Free(id PageID) error {\n\tcurrentFirstFreePage := s.header.freeList\n\tpage, err := s.Load(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Clear the buffer.\n\tfor i := 0; i < PageSize; i++ {\n\t\tpage.Buf[i] = 0\n\t}\n\tfree := freePage{\n\t\tPage: page,\n\t\tnextFreePage: currentFirstFreePage,\n\t}\n\tfree.toBuffer()\n\terr = s.Write(free.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.header.freeList = uint32(id) * PageSize\n\ts.header.toBuffer()\n\treturn s.Write(free.ID)\n}",
"func (x *FzTextSpan) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func UnpublishPage(encodedPublishedPagePath string) (errorResp *net.NxfsResponse) {\n\n\t// decode path\n\tdecodedPath, errResponse := nxfsfiles.DecodePath(encodedPublishedPagePath)\n\tif errResponse != nil {\n\t\treturn errResponse\n\t}\n\n\tsuffixedPage := addPageSuffix(decodedPath)\n\tpublishedPageFullPath := nxfsfiles.RelativizeToPublishedPageFolder(suffixedPage)\n\n\tif _, implResponse := nxfsfiles.GetFileInfoIfPathExistOrErrorResponse(publishedPageFullPath); nil != implResponse {\n\t\treturn implResponse\n\t}\n\n\tif implResponse := nxfsfiles.DeleteFile(publishedPageFullPath); implResponse != nil {\n\t\treturn implResponse\n\t}\n\n\treturn nil\n}",
"func (xs *Stylesheet) Close() {\n\tif xs.ptr != nil {\n\t\tC.free_style(&xs.ptr)\n\t\txs.ptr = nil\n\t}\n}",
"func (x *FzDocumentWriter) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (f *Frame) Close() error {\n\treturn nil\n}",
"func (x *PDFAlertEvent) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (s *Basegff3Listener) ExitDocument(ctx *DocumentContext) {}",
"func (x *PDFJsEvent) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFPortfolio) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (b *Bytes) Close() error {\n\tif b.p != nil {\n\t\tPut(b.p)\n\t\tb.p = nil\n\t}\n\treturn nil\n}",
"func (x *PDFPage) Ref() *C.pdf_page {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_page)(unsafe.Pointer(x))\n}",
"func (f *factory) TruncatePages(index int64) {\n\tf.mutex.Lock()\n\tdefer f.mutex.Unlock()\n\n\tif f.closed.Load() {\n\t\treturn\n\t}\n\n\tfor pageID := range f.pages {\n\t\tif pageID < index {\n\t\t\tif page, ok := f.pages[pageID]; ok {\n\t\t\t\tif err := page.Close(); err != nil {\n\t\t\t\t\tf.logger.Warn(\"close page failure\",\n\t\t\t\t\t\tlogger.String(\"path\", f.path), logger.Any(\"page\", pageID), logger.Error(err))\n\t\t\t\t}\n\t\t\t\tif err := removeFileFunc(f.pageFileName(pageID)); err != nil {\n\t\t\t\t\tf.logger.Warn(\"remove page failure\",\n\t\t\t\t\t\tlogger.String(\"path\", f.path), logger.Any(\"page\", pageID), logger.Error(err))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tdelete(f.pages, pageID)\n\t\t\t\tf.size.Sub(int64(f.pageSize))\n\n\t\t\t\tf.logger.Info(\"remove page successfully\",\n\t\t\t\t\tlogger.String(\"path\", f.path), logger.Any(\"page\", pageID))\n\t\t\t}\n\t\t}\n\t}\n}",
"func (m *model) unloadDocument() []tea.Cmd {\n\tm.state = stateShowStash\n\tm.stash.viewState = stashStateReady\n\tm.pager.unload()\n\tm.pager.showHelp = false\n\n\tvar batch []tea.Cmd\n\tif m.pager.viewport.HighPerformanceRendering {\n\t\tbatch = append(batch, tea.ClearScrollArea)\n\t}\n\n\tif !m.stash.shouldSpin() {\n\t\tbatch = append(batch, m.stash.spinner.Tick)\n\t}\n\treturn batch\n}",
"func TestSurgery_ClearPage(t *testing.T) {\n\tpageSize := 4096\n\tdb := btesting.MustCreateDBWithOption(t, &bolt.Options{PageSize: pageSize})\n\tsrcPath := db.Path()\n\n\t// Insert some sample data\n\tt.Log(\"Insert some sample data\")\n\terr := db.Fill([]byte(\"data\"), 1, 20,\n\t\tfunc(tx int, k int) []byte { return []byte(fmt.Sprintf(\"%04d\", k)) },\n\t\tfunc(tx int, k int) []byte { return make([]byte, 10) },\n\t)\n\trequire.NoError(t, err)\n\n\tdefer requireDBNoChange(t, dbData(t, srcPath), srcPath)\n\n\t// clear page 3\n\tt.Log(\"clear page 3\")\n\tdstPath := filepath.Join(t.TempDir(), \"dstdb\")\n\tm := NewMain()\n\terr = m.Run(\"surgery\", \"clear-page\", srcPath, dstPath, \"3\")\n\trequire.NoError(t, err)\n\n\t// The page 2 should have exactly the same data as page 3.\n\tt.Log(\"Verify result\")\n\tdstPageId3Data := readPage(t, dstPath, 3, pageSize)\n\n\tp := common.LoadPage(dstPageId3Data)\n\tassert.Equal(t, uint16(0), p.Count())\n\tassert.Equal(t, uint32(0), p.Overflow())\n}",
"func (m *wasiSnapshotPreview1Impl) fdClose(pfd wasiFd) (err wasiErrno) {\n\tf, err := m.files.acquireFile(pfd, 0)\n\tif err != wasiErrnoSuccess {\n\t\treturn err\n\t}\n\tdefer m.files.releaseFile(pfd, f)\n\n\tif err := f.f.Close(); err != nil {\n\t\treturn fileErrno(err)\n\t}\n\n\tf.open = false\n\treturn wasiErrnoSuccess\n}",
"func (x *PDFWriteOptions) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func freeDownload(download *C.Download) {\n\tif download == nil {\n\t\treturn\n\t}\n\tdefer C.free(unsafe.Pointer(download))\n\tdefer universe.Del(download._handle)\n\n\tdown, ok := universe.Get(download._handle).(*Download)\n\tif !ok {\n\t\treturn\n\t}\n\n\tdown.cancel()\n\t// in case we haven't already closed the download\n\t_ = down.download.Close()\n\t// TODO: log error when we didn't close manually and the close returns an error\n}",
"func (b *bookMark) close() error {\n\treturn b.file.Close()\n}",
"func (x *PDFJs) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFPattern) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFSigner) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (r *ImageRef) Close() {\n\tr.lock.Lock()\n\n\tif r.image != nil {\n\t\tclearImage(r.image)\n\t\tr.image = nil\n\t}\n\n\tr.buf = nil\n\n\tr.lock.Unlock()\n}",
"func (rf *reverseFile) Release() {\n\trf.fd.Close()\n}",
"func ReleaseWriter(qw *Writer) {\n\thw := qw.e.w.(*htmlEscapeWriter)\n\thw.w = nil\n\tqw.e.Reset()\n\tqw.e.w = hw\n\n\tqw.n.Reset()\n\n\twriterPool.Put(qw)\n}",
"func (x *FzStextPage) Ref() *C.fz_stext_page {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.fz_stext_page)(unsafe.Pointer(x))\n}",
"func scrolledWindowFinalizer(sw *ScrolledWindow) {\n\truntime.SetFinalizer(sw, func(sw *ScrolledWindow) { gobject.Unref(sw) })\n}",
"func (a *PDFApiService) RemovePageFormFields(ctx _context.Context, pdfRemovePageFormFieldsParameters PdfRemovePageFormFieldsParameters) (PdfRemovePageFormFieldsResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue PdfRemovePageFormFieldsResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/pdf/RemovePageFormFields\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json-patch+json\", \"application/json\", \"text/json\", \"application/_*+json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &pdfRemovePageFormFieldsParameters\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v PdfRemovePageFormFieldsResponse\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}",
"func (x *PDFHmtx) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (tex *Image) Free() {\n\tC.sfSprite_destroy(tex.sprite)\n\tC.sfTexture_destroy(tex.tex)\n}",
"func (x *PDFCrypt) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFObj) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (s *SimPDF) Finish(fileOutput string) {\n\tif internal.ValidateFilePath(fileOutput) {\n\t\tinternal.MoveFilePath(fileOutput, fileOutput+\".bak\")\n\t}\n\ts.PDF.OutputFileAndClose(fileOutput)\n}",
"func CloseResponse(response *http.Response) {\n\t_, _ = ioutil.ReadAll(response.Body)\n\tresponse.Body.Close()\n}",
"func (p *Page) MustClose() {\n\tp.e(p.Close())\n}",
"func freeDocPtr(xmlHandler *XmlHandler) {\n\tif xmlHandler.docPtr != nil {\n\t\tC.xmlFreeDoc(xmlHandler.docPtr)\n\t}\n}",
"func scrollbarFinalizer(sb *Scrollbar) {\n\truntime.SetFinalizer(sb, func(sb *Scrollbar) { gobject.Unref(sb) })\n}",
"func (rndr *Renderer) Close() error {\n\treturn nil\n}",
"func (x *FzDocumentHandlerContext) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (pager *pager) decrement(pointer int) {\n\tpage := pager.findPage(pointer)\n\tpageAddress := pageAddress(pointer, pager.pagesize)\n\tpage[pageAddress]--\n}",
"func UpdatePage(xRefTable *model.XRefTable, dIndRef types.IndirectRef, d, res types.Dict, p *model.Page, fonts model.FontMap) error {\n\n\t// TODO Account for existing page rotation.\n\n\terr := updatePageResources(xRefTable, d, res, *p, fonts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = xRefTable.AppendContent(d, p.Buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(p.AnnotTabs) == 0 && len(p.Annots) == 0 && len(p.LinkAnnots) == 0 {\n\t\treturn nil\n\t}\n\n\tif err := setAnnotationParentsAndFields(xRefTable, p, dIndRef); err != nil {\n\t\treturn err\n\t}\n\n\tannots, err := xRefTable.DereferenceArray(d[\"Annots\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tarr, err := mergeAnnotations(annots, p.Annots, p.AnnotTabs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, la := range p.LinkAnnots {\n\t\td, err := la.RenderDict(xRefTable, dIndRef)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tir, err := xRefTable.IndRefForNewObject(d)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tarr = append(arr, *ir)\n\t}\n\n\td[\"Annots\"] = arr\n\n\treturn nil\n}",
"func (lo *LuaObject) Close() {\n lo.L.Unref(lua.LUA_REGISTRYINDEX, lo.Ref)\n}",
"func (it *DelegateProfileFieldDeprecatedIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}",
"func (p *MessagePartition) releaseIndexfile(fileId uint64, file *os.File) {\n\tfile.Close()\n}",
"func (x *File) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (m *Metadata) Close() error {\n\tC.FreeMetadata((*C.Metadata)(unsafe.Pointer(m)))\n\treturn nil\n}"
] | [
"0.61916494",
"0.600281",
"0.5971603",
"0.59144455",
"0.588961",
"0.57575464",
"0.5566419",
"0.5441137",
"0.5406568",
"0.53081375",
"0.52970517",
"0.52884954",
"0.5284704",
"0.5260184",
"0.5249672",
"0.5191246",
"0.5187431",
"0.51822066",
"0.51296",
"0.5123408",
"0.50979996",
"0.50795704",
"0.50513774",
"0.50210696",
"0.5008069",
"0.4974296",
"0.4973705",
"0.49671343",
"0.4961959",
"0.49439955",
"0.4942103",
"0.49289703",
"0.4927136",
"0.49243355",
"0.49087784",
"0.48669574",
"0.48522606",
"0.4843158",
"0.48390836",
"0.48346832",
"0.48285204",
"0.48124138",
"0.48122707",
"0.4812018",
"0.48093024",
"0.4790913",
"0.4785397",
"0.47694582",
"0.47683018",
"0.47495526",
"0.47373503",
"0.47269523",
"0.47095937",
"0.4699757",
"0.46992588",
"0.46986508",
"0.46885285",
"0.4670977",
"0.4657113",
"0.4651717",
"0.46509588",
"0.464605",
"0.46329787",
"0.46264207",
"0.46235475",
"0.46095318",
"0.4607242",
"0.4597376",
"0.45960265",
"0.4594067",
"0.45906985",
"0.4588407",
"0.45807746",
"0.4579481",
"0.45672664",
"0.45563528",
"0.4542027",
"0.4525032",
"0.45225367",
"0.4513626",
"0.4506198",
"0.450436",
"0.44978133",
"0.44910106",
"0.44783035",
"0.4475322",
"0.44672507",
"0.4463984",
"0.4457867",
"0.44509003",
"0.44467333",
"0.44465572",
"0.4443804",
"0.44286177",
"0.44285673",
"0.44144982",
"0.44109815",
"0.4409085",
"0.4397759",
"0.438713"
] | 0.7370641 | 0 |
FPDF_GetFileVersion returns the version of the PDF file. | func (p *PdfiumImplementation) FPDF_GetFileVersion(request *requests.FPDF_GetFileVersion) (*responses.FPDF_GetFileVersion, error) {
p.Lock()
defer p.Unlock()
documentHandle, err := p.getDocumentHandle(request.Document)
if err != nil {
return nil, err
}
fileVersion := C.int(0)
success := C.FPDF_GetFileVersion(documentHandle.handle, &fileVersion)
if int(success) == 0 {
return nil, errors.New("could not get file version")
}
return &responses.FPDF_GetFileVersion{
FileVersion: int(fileVersion),
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (parser *PdfParser) PdfVersion() Version {\n\treturn parser.version\n}",
"func GetFileVersion(depth int) (string, error) {\n\n\t// Get the current working directory.\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Start with the current dir, and step up through the parents.\n\tfor i := 0; i <= depth; i++ {\n\t\tfor _, name := range []string{\".version\", \"VERSION\"} {\n\t\t\tdata, err := ioutil.ReadFile(path.Join(dir, name))\n\t\t\tif err == nil {\n\t\t\t\ttext := string(data)\n\t\t\t\tv := strings.Split(text, \"\\n\")[0]\n\t\t\t\treturn v, nil\n\t\t\t}\n\t\t}\n\t\tif dir == \"/\" {\n\t\t\treturn \"\", fmt.Errorf(\"cannot find .version file\")\n\t\t}\n\t\tdir = filepath.Dir(dir)\n\t}\n\n\treturn \"\", fmt.Errorf(\"no .version file\")\n\n}",
"func (parser *PdfParser) parsePdfVersion() (int, int, error) {\n\tvar offset int64 = 20\n\tb := make([]byte, offset)\n\tparser.rs.Seek(0, os.SEEK_SET)\n\tparser.rs.Read(b)\n\n\t// Try matching the PDF version at the start of the file, within the\n\t// first 20 bytes. If the PDF version is not found, search for it\n\t// starting from the top of the file.\n\tvar err error\n\tvar major, minor int\n\n\tif match := rePdfVersion.FindStringSubmatch(string(b)); len(match) < 3 {\n\t\tif major, minor, err = parser.seekPdfVersionTopDown(); err != nil {\n\t\t\tcommon.Log.Debug(\"Failed recovery - unable to find version\")\n\t\t\treturn 0, 0, err\n\t\t}\n\n\t\t// Create a new offset reader that ignores the invalid data before\n\t\t// the PDF version. Sets reader offset at the start of the PDF\n\t\t// version string.\n\t\tparser.rs, err = newOffsetReader(parser.rs, parser.GetFileOffset()-8)\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\t} else {\n\t\tif major, err = strconv.Atoi(match[1]); err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\t\tif minor, err = strconv.Atoi(match[2]); err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\n\t\t// Reset parser reader offset.\n\t\tparser.SetFileOffset(0)\n\t}\n\tparser.reader = bufio.NewReader(parser.rs)\n\n\tcommon.Log.Debug(\"Pdf version %d.%d\", major, minor)\n\treturn major, minor, nil\n}",
"func (c *CWebP) Version() (string, error) {\n\treturn version(c.BinWrapper)\n}",
"func (t *Typeface) Version() string {\n\tif t.URL == nil {\n\t\treturn \"\"\n\t}\n\n\tif t.URL.RawQuery != \"\" {\n\t\t// /l/font?kit=L0xhDFMnlVwD4h3Lt9JWnbX3jG-2X3LAI18&skey=ea73fc1e1d1dfd9a&v=v10#Domine\n\t\treturn t.URL.Query().Get(\"v\")\n\t}\n\n\tpathParts := strings.Split(t.URL.Path, \"/\")\n\tif !strings.HasPrefix(pathParts[len(pathParts)-2], \"v\") {\n\t\treturn \"\"\n\t}\n\treturn pathParts[len(pathParts)-2]\n}",
"func detectHistoryFileVersion(b []byte) (int, error) {\n\t// peek a file header\n\tvar header FileHeader\n\terr := json.Unmarshal(b, &header)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn header.Version, nil\n}",
"func (pl PageList) Version() string {\n\treturn pl.rawResponse.Header.Get(\"x-ms-version\")\n}",
"func Version(frame wdte.Frame, args ...wdte.Func) wdte.Func {\n\tframe = frame.Sub(\"version\")\n\n\tinfo, ok := debug.ReadBuildInfo()\n\tif !ok {\n\t\treturn wdte.Error{\n\t\t\tErr: ErrNoBuildInfo,\n\t\t\tFrame: frame,\n\t\t}\n\t}\n\n\tfor _, dep := range info.Deps {\n\t\tif dep.Path != \"github.com/DeedleFake/wdte\" {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn wdte.String(dep.Version)\n\t}\n\n\treturn wdte.Error{\n\t\tErr: ErrDepNotFound,\n\t\tFrame: frame,\n\t}\n}",
"func (h Header) Version() byte {\n\treturn h[1]\n}",
"func (dr downloadResponse) Version() string {\n\treturn dr.rawResponse.Header.Get(\"x-ms-version\")\n}",
"func (ssp StorageServiceProperties) Version() string {\n\treturn ssp.rawResponse.Header.Get(\"x-ms-version\")\n}",
"func (d Document) Version() int { return d.version }",
"func Version() string {\n\treturn getData().Version\n}",
"func (pbcr PageBlobsCreateResponse) Version() string {\n\treturn pbcr.rawResponse.Header.Get(\"x-ms-version\")\n}",
"func (h *ResourceHeader) GetVersion() string {\n\treturn h.Version\n}",
"func GetVersion() string {\n\treturn version.GetVersion()\n}",
"func (o *DeviceResourceVersionValueWeb) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}",
"func (o *HyperflexServerFirmwareVersionEntryAllOf) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}",
"func (_BaseContentFactory *BaseContentFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseContentFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}",
"func GetVersion() string {\n\treturn version\n}",
"func GetVersion() string {\n\treturn version\n}",
"func (pbcpr PageBlobsClearPagesResponse) Version() string {\n\treturn pbcpr.rawResponse.Header.Get(\"x-ms-version\")\n}",
"func (_BaseContentFactoryExt *BaseContentFactoryExtCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseContentFactoryExt.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}",
"func (factory *Factory) GetFDBVersion() fdbv1beta2.Version {\n\treturn factory.singleton.fdbVersion\n}",
"func (i DbInfo) Version() (string, error) {\n\tversion, _, _, err := i.Parse()\n\n\treturn version, err\n}",
"func Version() int {\n\treturn int(C.Pa_GetVersion())\n}",
"func (pbcir PageBlobsCopyIncrementalResponse) Version() string {\n\treturn pbcir.rawResponse.Header.Get(\"x-ms-version\")\n}",
"func (_BaseLibraryFactory *BaseLibraryFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseLibraryFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}",
"func (_SimpleMultiSig *SimpleMultiSigCaller) GetVersion(opts *bind.CallOpts) (string, error) {\n\tvar (\n\t\tret0 = new(string)\n\t)\n\tout := ret0\n\terr := _SimpleMultiSig.contract.Call(opts, out, \"getVersion\")\n\treturn *ret0, err\n}",
"func Version() string {\n\tapi := C.Create()\n\tdefer C.Free(api)\n\tversion := C.Version(api)\n\treturn C.GoString(version)\n}",
"func (bgpr BlobsGetPropertiesResponse) Version() string {\n\treturn bgpr.rawResponse.Header.Get(\"x-ms-version\")\n}",
"func (d *Diag) Version() string {\n\treturn bufToString(d.SzVersionString[:])\n}",
"func getVersion() string {\n\tslurp, err := ioutil.ReadFile(filepath.Join(camRoot, \"VERSION\"))\n\tif err == nil {\n\t\treturn strings.TrimSpace(string(slurp))\n\t}\n\treturn gitVersion()\n}",
"func (pbupr PageBlobsUploadPagesResponse) Version() string {\n\treturn pbupr.rawResponse.Header.Get(\"x-ms-version\")\n}",
"func (si SignedIdentifiers) Version() string {\n\treturn si.rawResponse.Header.Get(\"x-ms-version\")\n}",
"func Version() (version string) {\n\treturn GetVersion()\n}",
"func GetVersion() string {\n\treturn Version\n}",
"func GetVersion() string {\n\treturn Version\n}",
"func (o VirtualDatabaseSpecDatasourcesPropertiesValueFromFieldRefPtrOutput) ApiVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *VirtualDatabaseSpecDatasourcesPropertiesValueFromFieldRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ApiVersion\n\t}).(pulumi.StringPtrOutput)\n}",
"func GetComposeFileVersion(file string, defaultVersion ComposeFileVersion) ComposeFileVersion {\n\tversion, _, err := parseComposeFile(file)\n\tif err != nil {\n\t\tlogrus.Debugf(\"error parsing compose file found at %q, returning defaultVersion: %q, err: %q\", file, defaultVersion, err)\n\t\treturn defaultVersion\n\t}\n\n\tif version == unknown {\n\t\tlogrus.Debugf(\"could not determine compospe version from file %q, returning defaultVersion: %q\", file, defaultVersion)\n\t\treturn defaultVersion\n\t}\n\treturn version\n}",
"func (_BaseFactory *BaseFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}",
"func (o VirtualDatabaseSpecEnvValueFromFieldRefPtrOutput) ApiVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *VirtualDatabaseSpecEnvValueFromFieldRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ApiVersion\n\t}).(pulumi.StringPtrOutput)\n}",
"func GetVersion() string {\n\tif len(Version) == 0 {\n\t\treturn \"dev\"\n\t}\n\treturn Version\n}",
"func GetVersion() string {\n\tif len(Version) == 0 {\n\t\treturn \"dev\"\n\t}\n\treturn Version\n}",
"func (dr DownloadResponse) Version() string {\n\treturn dr.dr.XMsVersion()\n}",
"func (b *Binary) Version() string {\n\treturn b.version\n}",
"func (p *PdfiumImplementation) FPDF_GetSecurityHandlerRevision(request *requests.FPDF_GetSecurityHandlerRevision) (*responses.FPDF_GetSecurityHandlerRevision, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsecurityHandlerRevision := C.FPDF_GetSecurityHandlerRevision(documentHandle.handle)\n\n\treturn &responses.FPDF_GetSecurityHandlerRevision{\n\t\tSecurityHandlerRevision: int(securityHandlerRevision),\n\t}, nil\n}",
"func (b *BumpFile) Version() string {\n\treturn b.curver.Version()\n}",
"func (p *PdfiumImplementation) FPDF_SaveWithVersion(request *requests.FPDF_SaveWithVersion) (*responses.FPDF_SaveWithVersion, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twriter := C.FPDF_FILEWRITE{}\n\twriter.version = 1\n\n\t// Set the Go callback through cgo.\n\tC.FPDF_FILEWRITE_SET_WRITE_BLOCK(&writer)\n\n\tvar fileBuf *bytes.Buffer\n\tvar curFile *os.File\n\tif request.FileWriter != nil {\n\t\tcurrentWriter = request.FileWriter\n\t} else if request.FilePath != nil {\n\t\tnewFile, err := os.Create(*request.FilePath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcurrentWriter = newFile\n\t\tcurFile = newFile\n\t} else {\n\t\tfileBuf = &bytes.Buffer{}\n\t\tcurrentWriter = fileBuf\n\t}\n\n\tdefer func() {\n\t\t// Always remove writer.\n\t\tcurrentWriter = nil\n\n\t\tif curFile != nil {\n\t\t\tcurFile.Close()\n\t\t}\n\t}()\n\n\tvar success C.int\n\tif request.FileVersion == 0 {\n\t\tsuccess = C.FPDF_SaveAsCopy(documentHandle.handle, &writer, C.ulong(request.Flags))\n\t} else {\n\t\tsuccess = C.FPDF_SaveWithVersion(documentHandle.handle, &writer, C.ulong(request.Flags), C.int(request.FileVersion))\n\t}\n\n\tif int(success) == 0 {\n\t\treturn nil, errors.New(\"save of document failed\")\n\t}\n\n\tresp := &responses.FPDF_SaveWithVersion{}\n\tif request.FilePath != nil {\n\t\tresp.FilePath = request.FilePath\n\t}\n\n\tif fileBuf != nil {\n\t\tpdfContent := fileBuf.Bytes()\n\t\tresp.FileBytes = &pdfContent\n\t}\n\n\treturn resp, nil\n}",
"func GetVersion() string {\n\treturn VersionString\n}",
"func VersionNumber() int {\n\treturn int(C.LZ4_versionNumber())\n}",
"func (o VirtualDatabaseSpecBuildEnvValueFromFieldRefPtrOutput) ApiVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *VirtualDatabaseSpecBuildEnvValueFromFieldRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ApiVersion\n\t}).(pulumi.StringPtrOutput)\n}",
"func GetVersion() string {\n\n\tcwd, _ := os.Getwd()\n\tcurrentFolderPathList := strings.Split(cwd, \"/\")\n\tlenFolder := len(currentFolderPathList)\n\tcurrFolder := currentFolderPathList[lenFolder-1]\n\n\tversionInformation := strings.Split(currFolder, \"-\")\n\n\t// In case we are not executing in the install directory, return\n\t// the version present in versionMetadata.json.\n\tif len(versionInformation) < 3 {\n\n\t\tviper.SetConfigName(\"version_metadata.json\")\n\t\tviper.SetConfigType(\"json\")\n\t\tviper.AddConfigPath(\".\")\n\t\terr := viper.ReadInConfig()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tversionNumber := fmt.Sprint(viper.Get(\"version_number\"))\n\t\tbuildNumber := fmt.Sprint(viper.Get(\"build_number\"))\n\n\t\tversion := versionNumber + \"-\" + buildNumber\n\n\t\treturn version\n\n\t}\n\n\tversionNumber := versionInformation[1]\n\tbuildNumber := versionInformation[2]\n\n\tversion := versionNumber + \"-\" + buildNumber\n\n\treturn version\n}",
"func (bdr BlobsDeleteResponse) Version() string {\n\treturn bdr.rawResponse.Header.Get(\"x-ms-version\")\n}",
"func (_PlasmaFramework *PlasmaFrameworkCaller) GetVersion(opts *bind.CallOpts) (string, error) {\n\tvar (\n\t\tret0 = new(string)\n\t)\n\tout := ret0\n\terr := _PlasmaFramework.contract.Call(opts, out, \"getVersion\")\n\treturn *ret0, err\n}",
"func (o *VirtualizationIweHost) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}",
"func (m *PrintConnector) GetAppVersion()(*string) {\n val, err := m.GetBackingStore().Get(\"appVersion\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (oo *OnuDeviceEntry) GetPersVersion() string {\n\too.MutexPersOnuConfig.RLock()\n\tdefer oo.MutexPersOnuConfig.RUnlock()\n\tvalue := oo.SOnuPersistentData.PersVersion\n\treturn value\n}",
"func Version() string {\n\treturn versionNumber\n}",
"func (entry *Entry) GetVersion() int {\n\tversion := 1\n\tif entry.Sys != nil {\n\t\tversion = entry.Sys.Version\n\t}\n\n\treturn version\n}",
"func (entry *Entry) GetVersion() int {\n\tversion := 1\n\tif entry.Sys != nil {\n\t\tversion = entry.Sys.Version\n\t}\n\n\treturn version\n}",
"func (v *VCard) Version() string {\n\treturn v.getFirstPropertySingleString(\"version\")\n}",
"func (o *ApplianceImageBundleAllOf) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}",
"func (o ArgoCDSpecDexPtrOutput) Version() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDSpecDex) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Version\n\t}).(pulumi.StringPtrOutput)\n}",
"func (a Asset) version() string {\n\tvar versionRegexp = regexp.MustCompile(`^v\\d+`)\n\tversion := a.Version\n\tif version == 0 &&\n\t\ta.Config.URL.ForceVersion &&\n\t\tfilepath.Dir(a.PublicID) != \".\" &&\n\t\t!isURL(a.PublicID) &&\n\t\t!versionRegexp.MatchString(a.PublicID) {\n\t\tversion = 1\n\t}\n\n\tif version != 0 {\n\t\treturn fmt.Sprintf(\"v%d\", version)\n\t}\n\n\treturn \"\"\n}",
"func (o *NiaapiNewReleaseDetailAllOf) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}",
"func Version() string {\n\treturn C.GoString(C.yices_version)\n}",
"func (m *GroupPolicyDefinition) GetVersion()(*string) {\n val, err := m.GetBackingStore().Get(\"version\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (_BaseLibrary *BaseLibraryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseLibrary.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}",
"func (pbusnr PageBlobsUpdateSequenceNumberResponse) Version() string {\n\treturn pbusnr.rawResponse.Header.Get(\"x-ms-version\")\n}",
"func (o ArgoCDSpecDexOutput) Version() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDSpecDex) *string { return v.Version }).(pulumi.StringPtrOutput)\n}",
"func (o ArgoCDExportSpecPtrOutput) Version() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDExportSpec) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Version\n\t}).(pulumi.StringPtrOutput)\n}",
"func (pr LocalPackageReference) Version() string {\n\treturn pr.version\n}",
"func (o ArgoCDExportSpecOutput) Version() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDExportSpec) *string { return v.Version }).(pulumi.StringPtrOutput)\n}",
"func GetVersion() string {\n\treturn __VERSION__\n}",
"func (bur BlobsUndeleteResponse) Version() string {\n\treturn bur.rawResponse.Header.Get(\"x-ms-version\")\n}",
"func (m *ZebraFotaArtifact) GetPatchVersion()(*string) {\n val, err := m.GetBackingStore().Get(\"patchVersion\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (o *SoftwareTechs) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}",
"func (m *ComponentInformation) GetVersion() int {\n\tif m.HasExtensionFieldValues {\n\t\treturn 2\n\t}\n\n\treturn 1\n}",
"func (d Dispatcher) Version() (string, error) {\n\theight, err := d.GetBC().GetLatestHeight()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\thashes, err := d.GetBC().GetBlockHashesHex()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tversionBytes, err := helpers.Serialize(NewVersion(GizoVersion, height, hashes))\n\treturn string(versionBytes), nil\n}",
"func (_SimpleMultiSig *SimpleMultiSigCallerSession) GetVersion() (string, error) {\n\treturn _SimpleMultiSig.Contract.GetVersion(&_SimpleMultiSig.CallOpts)\n}",
"func (bcsr BlobsCreateSnapshotResponse) Version() string {\n\treturn bcsr.rawResponse.Header.Get(\"x-ms-version\")\n}",
"func (d *DirectHash) GetVersion() (Version, error) {\n\trv, err := d.GetRawVersion()\n\tif err != nil {\n\t\treturn Version{}, err\n\t}\n\tv := Version{\n\t\tVersionHash: rv.Hash,\n\t\tBranch: d.ReleaseBranch,\n\t}\n\treturn v, nil\n}",
"func Version() string {\n\treturn fmt.Sprint(\"C v1.2\", \"->\", d.Version())\n}",
"func Version() string {\n\tp := C.sqlite3_libversion()\n\treturn C.GoString(p)\n}",
"func versionOf(url *url.URL) (string, error) {\n\tpathParts := strings.FieldsFunc(url.Path, isURLPathSeparator)\n\n\tfor _, p := range pathParts {\n\t\tif versionRegex.MatchString(p) {\n\t\t\treturn p, nil\n\t\t}\n\t}\n\n\t// No version found, that's fine\n\treturn \"\", nil\n}",
"func (_Bridge *BridgeCaller) GetVersion(opts *bind.CallOpts) (string, error) {\n\tvar (\n\t\tret0 = new(string)\n\t)\n\tout := ret0\n\terr := _Bridge.contract.Call(opts, out, \"getVersion\")\n\treturn *ret0, err\n}",
"func Version(ctx context.Context, args values.Object) (values.Value, error) {\n\tbi, ok := readBuildInfo()\n\tif !ok {\n\t\treturn nil, errBuildInfoNotPresent\n\t}\n\n\t// Find the module in the build info.\n\tvar m debug.Module\n\tif bi.Main.Path == modulePath {\n\t\tm = bi.Main\n\t} else {\n\t\tfor _, dep := range bi.Deps {\n\t\t\tif dep.Path == modulePath {\n\t\t\t\tm = *dep\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Retrieve the version from the module.\n\tv := m.Version\n\tif m.Replace != nil {\n\t\t// If the module has been replaced, take the version from it.\n\t\tv = m.Replace.Version\n\t}\n\treturn values.NewString(v), nil\n}",
"func (abcr AppendBlobsCreateResponse) Version() string {\n\treturn abcr.rawResponse.Header.Get(\"x-ms-version\")\n}",
"func (m *AppVulnerabilityTask) GetAppVersion()(*string) {\n val, err := m.GetBackingStore().Get(\"appVersion\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (_BaseContent *BaseContentCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseContent.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}",
"func pathVersion(dir string, de fs.DirEntry, info fs.FileInfo) (string, bool) {\n\treturn \"\", false\n}",
"func (factory *Factory) GetFDBVersionAsString() string {\n\treturn factory.options.fdbVersion\n}",
"func (_Content *ContentCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _Content.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}",
"func (_LvRecording *LvRecordingCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _LvRecording.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}",
"func (brlr BlobsReleaseLeaseResponse) Version() string {\n\treturn brlr.rawResponse.Header.Get(\"x-ms-version\")\n}",
"func _getFileVersionIndex(id uint64, publisherName string, link string) (uint64, bool) {\n\tbook := _getBook(id)\n\n\t// search for the publisher\n\tindex, _ := _getPublisherIndex(id, publisherName)\n\tfor i, v := range(book.Publishers[index].FileVersions){\n\t\tif v.Link == link {\n\t\t\treturn uint64(i), true\n\t\t}\n\t}\n\n\t// version not found\n\treturn 0, false\n}",
"func GetVersion() DWORD {\n\tret1 := syscall3(getVersion, 0,\n\t\t0,\n\t\t0,\n\t\t0)\n\treturn DWORD(ret1)\n}",
"func (p Plugin) GetVersion() string {\n\treturn Version\n}",
"func VersionString() string {\n\treturn C.GoString(C.LZ4_versionString())\n}"
] | [
"0.6183621",
"0.6116802",
"0.5834047",
"0.57677853",
"0.55777127",
"0.54613817",
"0.5442866",
"0.53666663",
"0.53574127",
"0.5290645",
"0.5290284",
"0.52807444",
"0.52800405",
"0.52633536",
"0.5253596",
"0.5251473",
"0.5241522",
"0.5225384",
"0.5214525",
"0.5198343",
"0.5198343",
"0.519439",
"0.5188285",
"0.5180523",
"0.5178258",
"0.5172316",
"0.5172001",
"0.51666665",
"0.5164561",
"0.51614344",
"0.5158027",
"0.515462",
"0.5152879",
"0.5152392",
"0.51518995",
"0.51485896",
"0.513169",
"0.513169",
"0.5119065",
"0.51149815",
"0.5111602",
"0.51100844",
"0.5105997",
"0.5105997",
"0.51050717",
"0.51010394",
"0.5096345",
"0.50822043",
"0.5080847",
"0.5070789",
"0.5070384",
"0.50701016",
"0.5069867",
"0.5065144",
"0.5058392",
"0.50546896",
"0.5047387",
"0.5043477",
"0.5027859",
"0.50268763",
"0.50268763",
"0.5020717",
"0.5016579",
"0.5007745",
"0.49980298",
"0.49964583",
"0.4996398",
"0.497579",
"0.49725562",
"0.49668112",
"0.496081",
"0.49598902",
"0.4959247",
"0.49573743",
"0.49561566",
"0.49547878",
"0.4953836",
"0.49526373",
"0.4949862",
"0.49458632",
"0.49440753",
"0.49403715",
"0.493978",
"0.49333358",
"0.4929421",
"0.49268654",
"0.49239528",
"0.49238205",
"0.49237314",
"0.49235767",
"0.49222073",
"0.49158323",
"0.4912498",
"0.491182",
"0.49112555",
"0.4909013",
"0.4905513",
"0.49051958",
"0.49027056",
"0.49023637"
] | 0.7765313 | 0 |
FPDF_GetDocPermissions returns the permissions of the PDF. | func (p *PdfiumImplementation) FPDF_GetDocPermissions(request *requests.FPDF_GetDocPermissions) (*responses.FPDF_GetDocPermissions, error) {
p.Lock()
defer p.Unlock()
documentHandle, err := p.getDocumentHandle(request.Document)
if err != nil {
return nil, err
}
permissions := C.FPDF_GetDocPermissions(documentHandle.handle)
docPermissions := &responses.FPDF_GetDocPermissions{
DocPermissions: uint32(permissions),
}
PrintDocument := uint32(1 << 2)
ModifyContents := uint32(1 << 3)
CopyOrExtractText := uint32(1 << 4)
AddOrModifyTextAnnotations := uint32(1 << 5)
FillInExistingInteractiveFormFields := uint32(1 << 8)
ExtractTextAndGraphics := uint32(1 << 9)
AssembleDocument := uint32(1 << 10)
PrintDocumentAsFaithfulDigitalCopy := uint32(1 << 11)
hasPermission := func(permission uint32) bool {
if docPermissions.DocPermissions&permission > 0 {
return true
}
return false
}
docPermissions.PrintDocument = hasPermission(PrintDocument)
docPermissions.ModifyContents = hasPermission(ModifyContents)
docPermissions.CopyOrExtractText = hasPermission(CopyOrExtractText)
docPermissions.AddOrModifyTextAnnotations = hasPermission(AddOrModifyTextAnnotations)
docPermissions.FillInInteractiveFormFields = hasPermission(AddOrModifyTextAnnotations)
docPermissions.FillInExistingInteractiveFormFields = hasPermission(FillInExistingInteractiveFormFields)
docPermissions.ExtractTextAndGraphics = hasPermission(ExtractTextAndGraphics)
docPermissions.AssembleDocument = hasPermission(AssembleDocument)
docPermissions.PrintDocumentAsFaithfulDigitalCopy = hasPermission(PrintDocumentAsFaithfulDigitalCopy)
// Calculated permissions
docPermissions.CreateOrModifyInteractiveFormFields = docPermissions.ModifyContents && docPermissions.AddOrModifyTextAnnotations
return docPermissions, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (r *Document) Permissions() pulumi.Output {\n\treturn r.s.State[\"permissions\"]\n}",
"func (l *License) GetPermissions() []string {\n\tif l == nil || l.Permissions == nil {\n\t\treturn nil\n\t}\n\treturn *l.Permissions\n}",
"func (r *Repository) GetPermissions() map[string]bool {\n\tif r == nil || r.Permissions == nil {\n\t\treturn map[string]bool{}\n\t}\n\treturn *r.Permissions\n}",
"func (o LookupPermissionsResultOutput) Permissions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupPermissionsResult) []string { return v.Permissions }).(pulumi.StringArrayOutput)\n}",
"func (o ObjectCopyGrantOutput) Permissions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ObjectCopyGrant) []string { return v.Permissions }).(pulumi.StringArrayOutput)\n}",
"func (p *SASQueryParameters) Permissions() string {\n\treturn p.permissions\n}",
"func (m *Manager) GetPermissions(ctx context.Context, params model.RequestParams) (int, interface{}, error) {\n\thookResponse := m.integrationMan.InvokeHook(ctx, params)\n\tif hookResponse.CheckResponse() {\n\t\tif err := hookResponse.Error(); err != nil {\n\t\t\treturn hookResponse.Status(), nil, err\n\t\t}\n\n\t\treturn hookResponse.Status(), hookResponse.Result(), nil\n\t}\n\n\treturn http.StatusOK, []interface{}{map[string]interface{}{\"project\": \"*\", \"resource\": \"*\", \"verb\": \"*\"}}, nil\n}",
"func (o *PatchedUpdateWorkspaceInvitation) GetPermissions() string {\n\tif o == nil || IsNil(o.Permissions) {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Permissions\n}",
"func (o RuleOutput) Permissions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v Rule) []string { return v.Permissions }).(pulumi.StringArrayOutput)\n}",
"func (o BucketGrantOutput) Permissions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v BucketGrant) []string { return v.Permissions }).(pulumi.StringArrayOutput)\n}",
"func (u *User) GetPermissions() map[string]bool {\n\tif u == nil || u.Permissions == nil {\n\t\treturn map[string]bool{}\n\t}\n\treturn *u.Permissions\n}",
"func (o RuleResponseOutput) Permissions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v RuleResponse) []string { return v.Permissions }).(pulumi.StringArrayOutput)\n}",
"func (p *FileInf) getPermissionsList(u *url.URL) error {\n\tq := u.Query()\n\tq.Set(\"pageSize\", \"100\")\n\tq.Set(\"fields\", \"kind,nextPageToken,permissions\")\n\tu.RawQuery = q.Encode()\n\tr := &RequestParams{\n\t\tMethod: \"GET\",\n\t\tAPIURL: u.String(),\n\t\tData: nil,\n\t\tAccesstoken: p.Accesstoken,\n\t\tDtime: 30,\n\t}\n\tp.reqAndGetRawResponse(r)\n\treturn nil\n}",
"func (o *InlineResponse20027Person) GetPermissions() InlineResponse20027PersonPermissions {\n\tif o == nil || o.Permissions == nil {\n\t\tvar ret InlineResponse20027PersonPermissions\n\t\treturn ret\n\t}\n\treturn *o.Permissions\n}",
"func (p *FileInf) getPermissions(u *url.URL) error {\n\tu.Path = path.Join(u.Path, p.PermissionInfo.PermissionID)\n\tq := u.Query()\n\tq.Set(\"fields\", \"allowFileDiscovery,deleted,displayName,domain,emailAddress,expirationTime,id,kind,photoLink,role,teamDrivePermissionDetails,type\")\n\tu.RawQuery = q.Encode()\n\tr := &RequestParams{\n\t\tMethod: \"GET\",\n\t\tAPIURL: u.String(),\n\t\tData: nil,\n\t\tAccesstoken: p.Accesstoken,\n\t\tDtime: 30,\n\t}\n\tp.reqAndGetRawResponse(r)\n\treturn nil\n}",
"func (o BucketV2GrantOutput) Permissions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v BucketV2Grant) []string { return v.Permissions }).(pulumi.StringArrayOutput)\n}",
"func (r *Router) GetFilePermissions(c *gin.Context) {\n\treqUser := user.ExtractRequestUser(c)\n\tif reqUser == nil {\n\t\tc.AbortWithStatus(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tfileID := c.Param(ParamFileID)\n\tif fileID == \"\" {\n\t\tc.AbortWithStatus(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif role, _ := r.HandleUserFilePermission(c, fileID, GetFilePermissionsRole); role == \"\" {\n\t\treturn\n\t}\n\n\tpermissions, err := GetFilePermissions(c.Request.Context(), fileID, r.permissionClient(), r.fileClient())\n\tif err != nil {\n\t\thttpStatusCode := gwruntime.HTTPStatusFromCode(status.Code(err))\n\t\tloggermiddleware.LogError(r.logger, c.AbortWithError(httpStatusCode, err))\n\n\t\treturn\n\t}\n\n\t// Get File's metadata for its owner.\n\tfile, err := r.fileClient().GetFileByID(c.Request.Context(), &fpb.GetByFileByIDRequest{Id: fileID})\n\tif err != nil {\n\t\thttpStatusCode := gwruntime.HTTPStatusFromCode(status.Code(err))\n\t\tloggermiddleware.LogError(r.logger, c.AbortWithError(httpStatusCode, err))\n\n\t\treturn\n\t}\n\n\tfilteredOwnerPermissions := make([]Permission, 0, len(permissions))\n\tfor i := 0; i < len(permissions); i++ {\n\t\tif permissions[i].UserID != file.GetOwnerID() {\n\t\t\tfilteredOwnerPermissions = append(filteredOwnerPermissions, permissions[i])\n\t\t}\n\t}\n\n\tpermissions = filteredOwnerPermissions\n\n\tc.JSON(http.StatusOK, permissions)\n}",
"func (_Storage *StorageCallerSession) Permissions(arg0 uint8) (*big.Int, error) {\n\treturn _Storage.Contract.Permissions(&_Storage.CallOpts, arg0)\n}",
"func (gppr GetPathPropertiesResponse) XMsPermissions() string {\n\treturn gppr.rawResponse.Header.Get(\"x-ms-permissions\")\n}",
"func (_Bucket *BucketCallerSession) GetPermission(_fileId *big.Int, _entity common.Address) (struct {\n\tWrite bool\n\tRead bool\n}, error) {\n\treturn _Bucket.Contract.GetPermission(&_Bucket.CallOpts, _fileId, _entity)\n}",
"func Permissions(m os.FileMode) string {\n\tvar buf [32]byte // Mode is uint32.\n\tw := 0\n\n\tconst rwx = \"rwxrwxrwx\"\n\tfor i, c := range rwx {\n\t\tif m&(1<<uint(8-i)) != 0 {\n\t\t\tbuf[w] = byte(c)\n\t\t} else {\n\t\t\tbuf[w] = '-'\n\t\t}\n\t\tw++\n\t}\n\treturn string(buf[:w])\n}",
"func (o *Authorization) GetPermissionsOk() (*[]Permission, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Permissions, true\n}",
"func (o *IdentityTestIAMPermissionsResponse) GetPermissions() []string {\n\tif o == nil || o.Permissions == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.Permissions\n}",
"func (c *V1) GetPermissions(path string, username *string) (\n\tread, list bool,\n\tpossibleRead, possibleList bool,\n\trealm string, err error) {\n\tif err = c.EnsureInit(); err != nil {\n\t\treturn false, false, false, false, \"\", err\n\t}\n\n\tperms, maxPerms, realm := c.perPathConfigsReader.getPermissions(path, username)\n\treturn perms.read, perms.list, maxPerms.read, maxPerms.list, realm, nil\n}",
"func (_Storage *StorageCaller) Permissions(opts *bind.CallOpts, arg0 uint8) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Storage.contract.Call(opts, out, \"permissions\", arg0)\n\treturn *ret0, err\n}",
"func GetPermissions(c *gin.Context) {\n\tresult := service.GetPermissions()\n\n\tif len(*result) == 0 {\n\t\tc.JSON(404, nil)\n\t} else {\n\t\tc.JSON(200, result)\n\t}\n}",
"func (o *Authorization) GetPermissions() []Permission {\n\tif o == nil {\n\t\tvar ret []Permission\n\t\treturn ret\n\t}\n\n\treturn o.Permissions\n}",
"func (o *os) GetGrantedPermissions() gdnative.PoolStringArray {\n\to.ensureSingleton()\n\t//log.Println(\"Calling _OS.GetGrantedPermissions()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"_OS\", \"get_granted_permissions\")\n\n\t// Call the parent method.\n\t// PoolStringArray\n\tretPtr := gdnative.NewEmptyPoolStringArray()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewPoolStringArrayFromPointer(retPtr)\n\treturn ret\n}",
"func (_Bucket *BucketSession) GetPermission(_fileId *big.Int, _entity common.Address) (struct {\n\tWrite bool\n\tRead bool\n}, error) {\n\treturn _Bucket.Contract.GetPermission(&_Bucket.CallOpts, _fileId, _entity)\n}",
"func (o *ReportingTaskEntity) GetPermissions() PermissionsDTO {\n\tif o == nil || o.Permissions == nil {\n\t\tvar ret PermissionsDTO\n\t\treturn ret\n\t}\n\treturn *o.Permissions\n}",
"func (i *Installation) GetPermissions() *InstallationPermissions {\n\tif i == nil {\n\t\treturn nil\n\t}\n\treturn i.Permissions\n}",
"func (o *InlineResponse20027Person) GetPermissionsOk() (*InlineResponse20027PersonPermissions, bool) {\n\tif o == nil || o.Permissions == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Permissions, true\n}",
"func (ag ContrailAccessGetter) GetPermissions(ctx context.Context, typeName, uuid string) *rbac.PermType2 {\n\tobject, err := services.GetObject(ctx, ag.readService, typeName, uuid)\n\tif err != nil {\n\t\t// TODO(dfurman): return error instead\n\t\tag.log.WithError(err).WithFields(logrus.Fields{\n\t\t\t\"type-name\": typeName,\n\t\t\t\"uuid\": uuid,\n\t\t}).Debug(\"Failed to retrieve object from read service\")\n\t\treturn nil\n\t}\n\n\tobjectWithPerms2, ok := object.(hasPerms2)\n\tif !ok {\n\t\t// TODO(dfurman): return error instead\n\t\tag.log.WithFields(logrus.Fields{\n\t\t\t\"type-name\": typeName,\n\t\t\t\"uuid\": uuid,\n\t\t}).Debug(\"Object does not contain Perms2 needed for RBAC\")\n\t\treturn nil\n\t}\n\treturn objectWithPerms2.GetPerms2().ToRBAC()\n}",
"func (_Storage *StorageSession) Permissions(arg0 uint8) (*big.Int, error) {\n\treturn _Storage.Contract.Permissions(&_Storage.CallOpts, arg0)\n}",
"func (App) Permissions() []evo.Permission { return []evo.Permission{} }",
"func (r *RepositoryInvitation) GetPermissions() string {\n\tif r == nil || r.Permissions == nil {\n\t\treturn \"\"\n\t}\n\treturn *r.Permissions\n}",
"func (_Bucket *BucketCaller) GetPermission(opts *bind.CallOpts, _fileId *big.Int, _entity common.Address) (struct {\n\tWrite bool\n\tRead bool\n}, error) {\n\tret := new(struct {\n\t\tWrite bool\n\t\tRead bool\n\t})\n\tout := ret\n\terr := _Bucket.contract.Call(opts, out, \"getPermission\", _fileId, _entity)\n\treturn *ret, err\n}",
"func (o *Port) Permissions(info *bambou.FetchingInfo) (PermissionsList, *bambou.Error) {\n\n\tvar list PermissionsList\n\terr := bambou.CurrentSession().FetchChildren(o, PermissionIdentity, &list, info)\n\treturn list, err\n}",
"func (o *PatchedUpdateWorkspaceInvitation) GetPermissionsOk() (*string, bool) {\n\tif o == nil || IsNil(o.Permissions) {\n\t\treturn nil, false\n\t}\n\treturn o.Permissions, true\n}",
"func (_PermInterface *PermInterfaceCallerSession) GetPermissionsImpl() (common.Address, error) {\n\treturn _PermInterface.Contract.GetPermissionsImpl(&_PermInterface.CallOpts)\n}",
"func (m *MockSubRepoPermissionChecker) Permissions(v0 context.Context, v1 int32, v2 RepoContent) (Perms, error) {\n\tr0, r1 := m.PermissionsFunc.nextHook()(v0, v1, v2)\n\tm.PermissionsFunc.appendCall(SubRepoPermissionCheckerPermissionsFuncCall{v0, v1, v2, r0, r1})\n\treturn r0, r1\n}",
"func (k Key) Permissions() uint32 {\n\treturn uint32(k[12])<<24 | uint32(k[13])<<16 | uint32(k[14])<<8 | uint32(k[15])\n}",
"func (_PermInterface *PermInterfaceSession) GetPermissionsImpl() (common.Address, error) {\n\treturn _PermInterface.Contract.GetPermissionsImpl(&_PermInterface.CallOpts)\n}",
"func (r *Resolver) Permissions() PermissionsResolver { return &permissionsResolver{r} }",
"func (p *Permission) ListPermissions() revel.Result {\n\tperms := []models.Permission{}\n\tapp.DB.Find(&perms)\n\treturn util.AppResponse{200, \"success\", perms}\n}",
"func (o StorageAccountKeyResponseOutput) Permissions() pulumi.StringOutput {\n\treturn o.ApplyT(func(v StorageAccountKeyResponse) string { return v.Permissions }).(pulumi.StringOutput)\n}",
"func (p *FileInf) ManagePermissions() *FileInf {\n\tvar err error\n\tu, err := p.getURL()\n\tif p.PermissionInfo.FileID != \"\" {\n\t\tif p.PermissionInfo.PermissionID == \"\" {\n\t\t\tif (p.PermissionInfo.Create && !p.PermissionInfo.Delete) || (p.PermissionInfo.CreateObject != \"\" && p.PermissionInfo.DeleteObject == \"\" && p.PermissionInfo.UpdateObject == \"\") {\n\t\t\t\terr = p.createPermissions(u)\n\t\t\t} else {\n\t\t\t\terr = p.getPermissionsList(u)\n\t\t\t}\n\t\t} else {\n\t\t\tif (!p.PermissionInfo.Create && p.PermissionInfo.Delete) || (p.PermissionInfo.CreateObject == \"\" && p.PermissionInfo.DeleteObject != \"\" && p.PermissionInfo.UpdateObject == \"\") {\n\t\t\t\terr = p.deletePermissions(u)\n\t\t\t} else {\n\t\t\t\terr = p.getPermissions(u)\n\t\t\t}\n\t\t}\n\t} else {\n\t\terr = fmt.Errorf(\"Invalid options. Please check HELP using $ ggsrun p --help\")\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\treturn p\n}",
"func (d Document) Permissions__Form() string {\n\t// Initialize u variable that calls the User model\n\tu := uadmin.User{}\n\n\t// Get the user record based on an assigned ID\n\tuadmin.Get(&u, \"id = ?\", 1)\n\n\t// Initialize read, add, edit and delete that gets the permission for a\n\t// specific user based on an assigned ID\n\tr, a, e, del := d.GetPermissions(u)\n\n\t// Returns the permission status\n\treturn fmt.Sprintf(\"Read: %v Add: %v, Edit: %v, Delete: %v\", r, a, e, del)\n}",
"func (bc *BaseController) GetPermissionList() (error, []*dream.Permission) {\n\n\tresult, err := dream.GetPermissionList(bc.DB)\n\tif err != nil {\n\t\treturn ServiceErr, nil\n\t}\n\treturn nil, result\n}",
"func (o *ReportingTaskEntity) GetOperatePermissions() PermissionsDTO {\n\tif o == nil || o.OperatePermissions == nil {\n\t\tvar ret PermissionsDTO\n\t\treturn ret\n\t}\n\treturn *o.OperatePermissions\n}",
"func (o *ControllerConfigurationEntity) GetPermissions() PermissionsDTO {\n\tif o == nil || o.Permissions == nil {\n\t\tvar ret PermissionsDTO\n\t\treturn ret\n\t}\n\treturn *o.Permissions\n}",
"func (o *InlineResponse20027Person) SetPermissions(v InlineResponse20027PersonPermissions) {\n\to.Permissions = &v\n}",
"func (o *ReportingTaskEntity) GetPermissionsOk() (*PermissionsDTO, bool) {\n\tif o == nil || o.Permissions == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Permissions, true\n}",
"func (r MemRegion) Permissions() Permissions {\n\treturn r.perms\n}",
"func (o *AggregatedDomain) Permissions(info *bambou.FetchingInfo) (PermissionsList, *bambou.Error) {\n\n\tvar list PermissionsList\n\terr := bambou.CurrentSession().FetchChildren(o, PermissionIdentity, &list, info)\n\treturn list, err\n}",
"func (s *DatabaseLFTagPolicyAndPermissions) SetPermissions(v []*string) *DatabaseLFTagPolicyAndPermissions {\n\ts.Permissions = v\n\treturn s\n}",
"func (e *Enforcer) GetPermissionsForUser(user string) [][]string {\n\treturn e.GetFilteredPolicy(0, user)\n}",
"func (o *IdentityTestIAMPermissionsResponse) GetPermissionsOk() (*[]string, bool) {\n\tif o == nil || o.Permissions == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Permissions, true\n}",
"func (n *NameServiceCache) GetUserPermissions(user string, kg fred.KeygroupName) (map[fred.Method]struct{}, error) {\n\treturn n.regularNase.GetUserPermissions(user, kg)\n}",
"func (s *TableLFTagPolicyAndPermissions) SetPermissions(v []*string) *TableLFTagPolicyAndPermissions {\n\ts.Permissions = v\n\treturn s\n}",
"func (c Client) Update(input *UpdateDocumentPermissionsInput) (*UpdateDocumentPermissionsResponse, error) {\n\treturn c.UpdateWithContext(context.Background(), input)\n}",
"func (_PermInterface *PermInterfaceCaller) GetPermissionsImpl(opts *bind.CallOpts) (common.Address, error) {\n\tvar out []interface{}\n\terr := _PermInterface.contract.Call(opts, &out, \"getPermissionsImpl\")\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}",
"func (o KafkaAclOutput) Permission() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *KafkaAcl) pulumi.StringOutput { return v.Permission }).(pulumi.StringOutput)\n}",
"func (u Usr) Permission(fname string) int {\n\tif len(fname) == 0 {\n\t\treturn NO_READ\n\t}\n\tif fname[0] != '/' {\n\t\tfname = \"/\" + fname\n\t}\n\n\tlongest := \"\"\n\tres := CAN_EDIT\n\tfor k, v := range u.Paths {\n\t\tif k == fname {\n\t\t\treturn v\n\t\t}\n\t\tif len(k) <= len(longest) {\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.HasPrefix(fname, k) {\n\t\t\tcontinue\n\t\t}\n\t\tif k[len(k)-1] != '/' && fname[len(k)] != '/' {\n\t\t\tcontinue\n\t\t}\n\t\tlongest = k\n\t\tres = v\n\t}\n\treturn res\n}",
"func (a *IAMApiService) GetResourcePermissions(ctx context.Context, rid string) (IamaclPermissions, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue IamaclPermissions\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/acs/api/v1/acls/{rid}/permissions\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"rid\"+\"}\", fmt.Sprintf(\"%v\", rid), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v IamaclPermissions\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 0 {\n\t\t\tvar v IamError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}",
"func (*ExistingRoleRelationships_Permissions) Descriptor() ([]byte, []int) {\n\treturn file_protodef_user_user_proto_rawDescGZIP(), []int{14, 0}\n}",
"func (n *NamespaceController) ListPermissions(ctx context.Context, request *nodepb.ListPermissionsRequest) (response *nodepb.ListPermissionsResponse, err error) {\n\n\tlog := n.Log.Named(\"List Permissions Controller\")\n\t//Added logging\n\tlog.Debug(\"Function Invoked\", zap.String(\"Namespace\", request.Namespace))\n\n\tpermissions, err := n.Repo.ListPermissionsInNamespace(ctx, request.Namespace)\n\tif err != nil {\n\t\t//Added logging\n\t\tlog.Error(\"Failed to list Permissions\", zap.Error(err))\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\t//Added logging\n\tlog.Debug(\"List Permissions successful\")\n\treturn &nodepb.ListPermissionsResponse{Permissions: permissions}, nil\n}",
"func (x DashboardEntity) GetPermissions() DashboardPermissions {\n\treturn x.Permissions\n}",
"func (o *ReportingTaskEntity) SetPermissions(v PermissionsDTO) {\n\to.Permissions = &v\n}",
"func (a *Account) GetAppPermissions(userID uint) (AccountGetAppPermissionsResponse, error) {\n\tparams := map[string]string{\"user_id\": fmt.Sprint(userID) }\n\tresp, err := a.vk.Request(\"account.getAppPermissions\", params)\n\tif err != nil {\n\t\treturn AccountGetAppPermissionsResponse{}, err\n\t}\n\n\tpermBits, err := strconv.ParseUint(string(resp), 10, 64)\n\tif err != nil {\n\t\treturn AccountGetAppPermissionsResponse{}, err\n\t}\n\n\tperm := AccountGetAppPermissionsResponse{}\n\n\tperm.Notify = permBits¬ifyBit != 0\n\tperm.Friends = permBits&friendsBit != 0\n\tperm.Photos = permBits&photosBit != 0\n\tperm.Audio = permBits&audioBit != 0\n\tperm.Video = permBits&videoBit != 0\n\tperm.Pages = permBits&pagesBit != 0\n\tperm.Status = permBits&statusBit != 0\n\tperm.Notes = permBits¬esBit != 0\n\tperm.Messages = permBits&messagesBit != 0\n\tperm.Wall = permBits&wallBit != 0\n\tperm.Ads = permBits&adsBit != 0\n\tperm.Offline = permBits&offlineBit != 0\n\tperm.Docs = permBits&docsBit != 0\n\tperm.Groups = permBits&groupsBit != 0\n\tperm.Notifications = permBits¬ificationsBit != 0\n\tperm.Stats = permBits&statsBit != 0\n\tperm.Email = permBits&emailBit != 0\n\tperm.Market = permBits&marketBit != 0\n\n\treturn perm, nil\n}",
"func (parser *PdfParser) CheckAccessRights(password []byte) (bool, security.Permissions, error) {\n\t// Also build the encryption/decryption key.\n\tif parser.crypter == nil {\n\t\t// If the crypter is not set, the file is not encrypted and we can assume full access permissions.\n\t\treturn true, security.PermOwner, nil\n\t}\n\treturn parser.crypter.checkAccessRights(password)\n}",
"func (o *ControllerConfigurationEntity) GetPermissionsOk() (*PermissionsDTO, bool) {\n\tif o == nil || o.Permissions == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Permissions, true\n}",
"func (o *PatchedUpdateWorkspaceInvitation) SetPermissions(v string) {\n\to.Permissions = &v\n}",
"func (this *managerStruct) Permissions(name string) ([]string, error) {\n\tthis.mutex.RLock()\n\tid := this.getUserId(name)\n\n\t/*\n\t * Check if we have a user with the name provided to us.\n\t */\n\tif id < 0 {\n\t\tthis.mutex.RUnlock()\n\t\treturn nil, fmt.Errorf(\"User '%s' does not exist.\", name)\n\t} else {\n\t\tusers := this.users\n\t\tuser := users[id]\n\t\tpermissions := user.permissions\n\t\tnumPermissions := len(permissions)\n\t\tpermissionsCopy := make([]string, numPermissions)\n\t\tcopy(permissionsCopy, permissions)\n\t\tthis.mutex.RUnlock()\n\t\treturn permissionsCopy, nil\n\t}\n\n}",
"func fmtPermissions(perm []bool) string {\n\tbuf := make([]byte, len(perm))\n\tfor i := range perm {\n\t\tif perm[i] {\n\t\t\tbuf[i] = 't'\n\t\t} else {\n\t\t\tbuf[i] = 'f'\n\t\t}\n\t}\n\treturn string(buf)\n}",
"func (x DashboardEntityOutline) GetPermissions() DashboardEntityPermissions {\n\treturn x.Permissions\n}",
"func ResourceBuildFolderPermissions() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceBuildFolderPermissionsCreateOrUpdate,\n\t\tRead: resourceBuildFolderPermissionsRead,\n\t\tUpdate: resourceBuildFolderPermissionsCreateOrUpdate,\n\t\tDelete: resourceBuildFolderPermissionsDelete,\n\t\tSchema: securityhelper.CreatePermissionResourceSchema(map[string]*schema.Schema{\n\t\t\t\"project_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tValidateFunc: validation.IsUUID,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"path\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t}),\n\t}\n}",
"func (o *IdentityTestIAMPermissionsResponse) SetPermissions(v []string) {\n\to.Permissions = &v\n}",
"func (e *SyncedEnforcer) GetPermissionsForUser(user string) [][]string {\n\te.m.RLock()\n\tdefer e.m.RUnlock()\n\treturn e.Enforcer.GetPermissionsForUser(user)\n}",
"func sslCertificatePermissions(cert, key os.FileInfo) {}",
"func sslCertificatePermissions(cert, key os.FileInfo) {}",
"func (g guildMemberQueryBuilder) GetPermissions() (PermissionBit, error) {\n\tmember, err := g.Get()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn member.GetPermissions(g.ctx, g.client)\n}",
"func getFilePerm(fpath string) {\n\n\tfileInfo, err := os.Stat(fpath)\n\n\t// check if there is an error\n\tif err != nil {\n\n\t\t// check if error is file does not exist\n\t\tif os.IsNotExist(err) {\n\t\t\tfmt.Println(\"File does not exist.\")\n\t\t}\n\n\t}\n\n\tmode := fileInfo.Mode()\n\n\tfmt.Println(fileInfo, \"mode is \", mode)\n}",
"func (c *Client) NewDocumentPermissionsPaginator() *DocumentPermissionsPaginator {\n\treturn c.NewDocumentPermissionsPaginatorWithOptions(nil)\n}",
"func (e UserEdges) PermissionsOrErr() ([]*Permission, error) {\n\tif e.loadedTypes[4] {\n\t\treturn e.Permissions, nil\n\t}\n\treturn nil, &NotLoadedError{edge: \"permissions\"}\n}",
"func GetPrincipalPermissions(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *PrincipalPermissionsState, opts ...pulumi.ResourceOption) (*PrincipalPermissions, error) {\n\tvar resource PrincipalPermissions\n\terr := ctx.ReadResource(\"aws-native:lakeformation:PrincipalPermissions\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func NewPermissions(cfg config.GDPR, tcf2Config TCF2ConfigReader, vendorIDs map[openrtb_ext.BidderName]uint16, fetcher VendorListFetcher) Permissions {\n\tif !cfg.Enabled {\n\t\treturn &AlwaysAllow{}\n\t}\n\n\tpermissionsImpl := &permissionsImpl{\n\t\tfetchVendorList: fetcher,\n\t\tgdprDefaultValue: cfg.DefaultValue,\n\t\thostVendorID: cfg.HostVendorID,\n\t\tnonStandardPublishers: cfg.NonStandardPublisherMap,\n\t\tcfg: tcf2Config,\n\t\tvendorIDs: vendorIDs,\n\t}\n\n\tif cfg.HostVendorID == 0 {\n\t\treturn &AllowHostCookies{\n\t\t\tpermissionsImpl: permissionsImpl,\n\t\t}\n\t}\n\n\treturn permissionsImpl\n}",
"func (v Account) GetAppPermissions(params AccountGetAppPermissionsParams) (AccountGetAppPermissionsResponse, error) {\n\tr, err := v.API.Request(\"account.getAppPermissions\", params)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar resp AccountGetAppPermissionsResponse\n\n\tvar cnv int\n\tcnv, err = strconv.Atoi(string(r))\n\tresp = AccountGetAppPermissionsResponse(cnv)\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn resp, nil\n}",
"func (s *TemplateService) ListTemplatePermissions(p *ListTemplatePermissionsParams) (*ListTemplatePermissionsResponse, error) {\n\tresp, err := s.cs.newRequest(\"listTemplatePermissions\", p.toURLValues())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r ListTemplatePermissionsResponse\n\tif err := json.Unmarshal(resp, &r); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &r, nil\n}",
"func GetFilePermissions(ctx context.Context,\n\tfileID string,\n\tpermissionClient ppb.PermissionClient,\n\tfileClient fpb.FileServiceClient) ([]Permission, error) {\n\tpermissionsMap := make(map[string]Permission, 1)\n\tpermissions := make([]Permission, 0, 1)\n\tcurrentFileID := fileID\n\n\tfor {\n\t\tpermissionsRequest := &ppb.GetFilePermissionsRequest{FileID: currentFileID}\n\t\tpermissionsResponse, err := permissionClient.GetFilePermissions(ctx, permissionsRequest)\n\t\tif err != nil && status.Code(err) != codes.NotFound {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcurrentFile, err := fileClient.GetFileByID(ctx, &fpb.GetByFileByIDRequest{Id: currentFileID})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, permission := range permissionsResponse.GetPermissions() {\n\t\t\tif _, ok := permissionsMap[permission.GetUserID()]; !ok {\n\t\t\t\tuserRole := Permission{\n\t\t\t\t\tUserID: permission.GetUserID(),\n\t\t\t\t\tRole: permission.GetRole().String(),\n\t\t\t\t\tFileID: currentFileID,\n\t\t\t\t\tCreator: permission.GetCreator(),\n\t\t\t\t}\n\t\t\t\tpermissionsMap[permission.GetUserID()] = userRole\n\t\t\t\tpermissions = append(permissions, userRole)\n\t\t\t}\n\t\t}\n\n\t\tif currentFile.GetParent() == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tcurrentFileID = currentFile.GetParent()\n\t}\n\n\treturn permissions, nil\n}",
"func (m *RoleDefinition) GetRolePermissions()([]RolePermissionable) {\n return m.rolePermissions\n}",
"func (u *User) PermissionsMap() map[string]struct{} {\n\tpermissionsMap := make(map[string]struct{})\n\tfor _, v := range u.Permissions {\n\t\tpermissionsMap[v] = struct{}{}\n\t}\n\n\treturn permissionsMap\n}",
"func (client *ClientImpl) HasPermissions(ctx context.Context, args HasPermissionsArgs) (*[]bool, error) {\n\trouteValues := make(map[string]string)\n\tif args.SecurityNamespaceId == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.SecurityNamespaceId\"}\n\t}\n\trouteValues[\"securityNamespaceId\"] = (*args.SecurityNamespaceId).String()\n\tif args.Permissions != nil {\n\t\trouteValues[\"permissions\"] = strconv.Itoa(*args.Permissions)\n\t}\n\n\tqueryParams := url.Values{}\n\tif args.Tokens != nil {\n\t\tqueryParams.Add(\"tokens\", *args.Tokens)\n\t}\n\tif args.AlwaysAllowAdministrators != nil {\n\t\tqueryParams.Add(\"alwaysAllowAdministrators\", strconv.FormatBool(*args.AlwaysAllowAdministrators))\n\t}\n\tif args.Delimiter != nil {\n\t\tqueryParams.Add(\"delimiter\", *args.Delimiter)\n\t}\n\tlocationId, _ := uuid.Parse(\"dd3b8bd6-c7fc-4cbd-929a-933d9c011c9d\")\n\tresp, err := client.Client.Send(ctx, http.MethodGet, locationId, \"7.1-preview.2\", routeValues, queryParams, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue []bool\n\terr = client.Client.UnmarshalCollectionBody(resp, &responseValue)\n\treturn &responseValue, err\n}",
"func (o *os) RequestPermissions() gdnative.Bool {\n\to.ensureSingleton()\n\t//log.Println(\"Calling _OS.RequestPermissions()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"_OS\", \"request_permissions\")\n\n\t// Call the parent method.\n\t// bool\n\tretPtr := gdnative.NewEmptyBool()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewBoolFromPointer(retPtr)\n\treturn ret\n}",
"func (o *FileversionFileversion) GetPrivacy() PayloadUserGroups {\n\tif o == nil || o.Privacy == nil {\n\t\tvar ret PayloadUserGroups\n\t\treturn ret\n\t}\n\treturn *o.Privacy\n}",
"func (n *Node) ReadUserPermissions(ctx context.Context, u *userpb.User) (ap provider.ResourcePermissions, err error) {\n\t// check if the current user is the owner\n\to, err := n.Owner()\n\tif err != nil {\n\t\t// TODO check if a parent folder has the owner set?\n\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Msg(\"could not determine owner, returning default permissions\")\n\t\treturn NoPermissions(), err\n\t}\n\tif o.OpaqueId == \"\" {\n\t\t// this happens for root nodes in the storage. the extended attributes are set to emptystring to indicate: no owner\n\t\t// TODO what if no owner is set but grants are present?\n\t\treturn NoOwnerPermissions(), nil\n\t}\n\tif utils.UserEqual(u.Id, o) {\n\t\tappctx.GetLogger(ctx).Debug().Interface(\"node\", n).Msg(\"user is owner, returning owner permissions\")\n\t\treturn OwnerPermissions(), nil\n\t}\n\n\tap = provider.ResourcePermissions{}\n\n\t// for an efficient group lookup convert the list of groups to a map\n\t// groups are just strings ... groupnames ... or group ids ??? AAARGH !!!\n\tgroupsMap := make(map[string]bool, len(u.Groups))\n\tfor i := range u.Groups {\n\t\tgroupsMap[u.Groups[i]] = true\n\t}\n\n\tvar g *provider.Grant\n\n\t// we read all grantees from the node\n\tvar grantees []string\n\tif grantees, err = n.ListGrantees(ctx); err != nil {\n\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Msg(\"error listing grantees\")\n\t\treturn NoPermissions(), err\n\t}\n\n\t// instead of making n getxattr syscalls we are going to list the acls and filter them here\n\t// we have two options here:\n\t// 1. we can start iterating over the acls / grants on the node or\n\t// 2. we can iterate over the number of groups\n\t// The current implementation tries to be defensive for cases where users have hundreds or thousands of groups, so we iterate over the existing acls.\n\tuserace := xattrs.GrantPrefix + xattrs.UserAcePrefix + u.Id.OpaqueId\n\tuserFound := false\n\tfor i := range grantees {\n\t\tswitch {\n\t\t// we only need to find the user once\n\t\tcase !userFound && grantees[i] == userace:\n\t\t\tg, err = n.ReadGrant(ctx, grantees[i])\n\t\tcase strings.HasPrefix(grantees[i], xattrs.GrantPrefix+xattrs.GroupAcePrefix): // only check group grantees\n\t\t\tgr := strings.TrimPrefix(grantees[i], xattrs.GrantPrefix+xattrs.GroupAcePrefix)\n\t\t\tif groupsMap[gr] {\n\t\t\t\tg, err = n.ReadGrant(ctx, grantees[i])\n\t\t\t} else {\n\t\t\t\t// no need to check attribute\n\t\t\t\tcontinue\n\t\t\t}\n\t\tdefault:\n\t\t\t// no need to check attribute\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch {\n\t\tcase err == nil:\n\t\t\tAddPermissions(&ap, g.GetPermissions())\n\t\tcase isAttrUnset(err):\n\t\t\terr = nil\n\t\t\tappctx.GetLogger(ctx).Error().Interface(\"node\", n).Str(\"grant\", grantees[i]).Interface(\"grantees\", grantees).Msg(\"grant vanished from node after listing\")\n\t\t\t// continue with next segment\n\t\tdefault:\n\t\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Str(\"grant\", grantees[i]).Msg(\"error reading permissions\")\n\t\t\t// continue with next segment\n\t\t}\n\t}\n\n\tappctx.GetLogger(ctx).Debug().Interface(\"permissions\", ap).Interface(\"node\", n).Interface(\"user\", u).Msg(\"returning aggregated permissions\")\n\treturn ap, nil\n}",
"func (o *ReportingTaskEntity) GetOperatePermissionsOk() (*PermissionsDTO, bool) {\n\tif o == nil || o.OperatePermissions == nil {\n\t\treturn nil, false\n\t}\n\treturn o.OperatePermissions, true\n}",
"func Get() *Permissions {\n\tif globalPermissions == nil {\n\t\treturn &Default\n\t}\n\treturn globalPermissions.Get()\n}",
"func (as *AclStatus) Permission() *hdfs.FsPermissionProto {\n\treturn as.aclStatus.GetPermission()\n}",
"func (a *IAMApiService) GetGroupPermissions(ctx context.Context, gid string) (IamGroupPermissions, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue IamGroupPermissions\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/acs/api/v1/groups/{gid}/permissions\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"gid\"+\"}\", fmt.Sprintf(\"%v\", gid), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v IamGroupPermissions\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 0 {\n\t\t\tvar v IamError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}"
] | [
"0.7281624",
"0.65242743",
"0.60750824",
"0.5972209",
"0.59515566",
"0.59360224",
"0.59296775",
"0.59185153",
"0.5899833",
"0.5878543",
"0.58722395",
"0.5862485",
"0.584586",
"0.58343047",
"0.58208025",
"0.5801718",
"0.5666553",
"0.5662679",
"0.5644805",
"0.5616024",
"0.56025326",
"0.56024075",
"0.558971",
"0.55691963",
"0.5557733",
"0.55410904",
"0.55115765",
"0.5495895",
"0.5495461",
"0.54901034",
"0.54869753",
"0.54775006",
"0.5454607",
"0.5454427",
"0.54427314",
"0.54405665",
"0.54373753",
"0.5433891",
"0.5430489",
"0.54260254",
"0.5410341",
"0.5399092",
"0.53963846",
"0.538853",
"0.5375728",
"0.53461224",
"0.5335183",
"0.53256226",
"0.529345",
"0.52762675",
"0.525813",
"0.5226758",
"0.5195532",
"0.51735383",
"0.5163733",
"0.51491404",
"0.5141585",
"0.51295763",
"0.512861",
"0.5100511",
"0.50992996",
"0.5069148",
"0.50567776",
"0.50547814",
"0.5039064",
"0.5027294",
"0.5013295",
"0.50093293",
"0.50070304",
"0.5005801",
"0.49950066",
"0.49938512",
"0.49936494",
"0.49924663",
"0.49740168",
"0.49699777",
"0.4962907",
"0.49403405",
"0.49362096",
"0.49139866",
"0.49139866",
"0.49085274",
"0.48710495",
"0.4869268",
"0.48667726",
"0.48654228",
"0.48619497",
"0.48566997",
"0.48414478",
"0.48352528",
"0.4831734",
"0.48314354",
"0.48304617",
"0.48176822",
"0.47935423",
"0.47897843",
"0.47855362",
"0.47781378",
"0.4774061",
"0.47702423"
] | 0.80400366 | 0 |
FPDF_GetSecurityHandlerRevision returns the revision number of security handlers of the file. | func (p *PdfiumImplementation) FPDF_GetSecurityHandlerRevision(request *requests.FPDF_GetSecurityHandlerRevision) (*responses.FPDF_GetSecurityHandlerRevision, error) {
p.Lock()
defer p.Unlock()
documentHandle, err := p.getDocumentHandle(request.Document)
if err != nil {
return nil, err
}
securityHandlerRevision := C.FPDF_GetSecurityHandlerRevision(documentHandle.handle)
return &responses.FPDF_GetSecurityHandlerRevision{
SecurityHandlerRevision: int(securityHandlerRevision),
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func getRevision(sd []byte) BYTE {\n\tif len(sd) < 1 {\n\t\treturn 0\n\t}\n\n\t// SECURITY_DESCRIPTOR_RELATIVE.Revision.\n\treturn BYTE(sd[0])\n}",
"func (m *SQLIgnoreStore) Revision() int64 {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\treturn m.revision\n}",
"func (m *msgHandler) Version() uint32 {\n\tm.owner.mu.Lock()\n\tdefer m.owner.mu.Unlock()\n\treturn m.owner.version\n}",
"func (resp *BytesWatchDelResp) GetRevision() int64 {\n\treturn resp.rev\n}",
"func GetVersionHandler(ctx context.Context, r *http.Request) (interface{}, error) {\n\treturn &Response{\n\t\tVersion: Version,\n\t\tDateBuild: DateBuild,\n\t\tGitHash: GitHash,\n\t}, nil\n}",
"func (s *SharedMemory) Revision() int {\n\treturn int(s.shmem.dwRevision)\n}",
"func (m *DigicamControl) GetVersion() int {\n\tif m.HasExtensionFieldValues {\n\t\treturn 2\n\t}\n\n\treturn 1\n}",
"func handlerVersions(handler ResourceHandler) []string {\n\treturn versions([]ResourceHandler{handler})\n}",
"func GetWebhookRevision(wh admitv1.MutatingWebhookConfiguration) (string, error) {\n\tif tagName, ok := wh.ObjectMeta.Labels[label.IoIstioRev.Name]; ok {\n\t\treturn tagName, nil\n\t}\n\treturn \"\", fmt.Errorf(\"could not extract tag revision from webhook\")\n}",
"func (t Trailer) GetSignatureLength() (v int, err quickfix.MessageRejectError) {\n\tvar f field.SignatureLengthField\n\tif err = t.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}",
"func GetIndexOfSigner(promise *cAPI.Promise, hash []byte) (uint32, error) {\n\tfor i, h := range promise.Context.Signers {\n\t\tif bytes.Equal(h, hash) {\n\t\t\treturn uint32(i), nil\n\t\t}\n\t}\n\treturn 0, errors.New(\"Signer's hash couldn't be matched\")\n}",
"func detectHistoryFileVersion(b []byte) (int, error) {\n\t// peek a file header\n\tvar header FileHeader\n\terr := json.Unmarshal(b, &header)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn header.Version, nil\n}",
"func (resp *BytesWatchPutResp) GetRevision() int64 {\n\treturn resp.rev\n}",
"func (m *BrowserSiteList) GetRevision()(*string) {\n val, err := m.GetBackingStore().Get(\"revision\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (p *ProvisionTokenV2) GetRevision() string {\n\treturn p.Metadata.GetRevision()\n}",
"func GetVersionHandler() http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tversionInfo := GetInfo()\n\n\t\tif jsonVersionInfo, err := json.Marshal(versionInfo); err != nil {\n\t\t\tlog.Error().Err(err).Msgf(\"Error marshaling version info struct: %+v\", versionInfo)\n\t\t} else {\n\t\t\t_, _ = fmt.Fprint(w, string(jsonVersionInfo))\n\t\t}\n\t})\n}",
"func sthForRevision(revision int64) int64 {\n\treturn revision + 1\n}",
"func (s *chainScore) Ex_getRevision() (int64, error) {\n\tif err := s.tryChargeCall(false); err != nil {\n\t\treturn 0, err\n\t}\n\tas := s.cc.GetAccountState(state.SystemID)\n\treturn scoredb.NewVarDB(as, state.VarRevision).Int64(), nil\n}",
"func (m MarketDataSnapshotFullRefresh) GetSecurityID() (v string, err quickfix.MessageRejectError) {\n\tvar f field.SecurityIDField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}",
"func (m Message) GetSecurityResponseID(f *field.SecurityResponseIDField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}",
"func vcsRevision() string {\n\tbi, ok := debug.ReadBuildInfo()\n\tif !ok {\n\t\treturn \"\"\n\t}\n\tfor _, s := range bi.Settings {\n\t\tif s.Key == \"vcs.revision\" {\n\t\t\treturn s.Value[:9]\n\t\t}\n\t}\n\n\treturn \"\"\n}",
"func (entry *Entry) GetVersion() int {\n\tversion := 1\n\tif entry.Sys != nil {\n\t\tversion = entry.Sys.Version\n\t}\n\n\treturn version\n}",
"func (entry *Entry) GetVersion() int {\n\tversion := 1\n\tif entry.Sys != nil {\n\t\tversion = entry.Sys.Version\n\t}\n\n\treturn version\n}",
"func (m *ComponentInformation) GetVersion() int {\n\tif m.HasExtensionFieldValues {\n\t\treturn 2\n\t}\n\n\treturn 1\n}",
"func (o *MicrosoftGraphWindows10CompliancePolicy) GetVersion() int32 {\n\tif o == nil || o.Version == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Version\n}",
"func (o *SSHAuthorizationPolicy) Version() int {\n\n\treturn 1\n}",
"func (this *activitiesStruct) Revision() uint64 {\n\tthis.mutex.RLock()\n\trev := this.revision\n\tthis.mutex.RUnlock()\n\treturn rev\n}",
"func (m *GroupPolicyDefinition) GetVersion()(*string) {\n val, err := m.GetBackingStore().Get(\"version\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (reg *defaultRegistry) GetLastRevisionForPolicy(policyGen runtime.Generation) (*engine.Revision, error) {\n\t// TODO: this method is slow, needs indexes\n\tvar revision *engine.Revision\n\terr := reg.store.Find(engine.TypeRevision.Kind, &revision, store.WithKey(engine.RevisionKey), store.WithWhereEq(\"PolicyGen\", policyGen), store.WithGetLast())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn revision, nil\n}",
"func (o *SparseSSHAuthorizationPolicy) Version() int {\n\n\treturn 1\n}",
"func (r *CSAKeyResolver) Version() int32 {\n\treturn int32(r.key.Version)\n}",
"func (m *_BVLCSecureBVLL) GetSecurityWrapper() []byte {\n\treturn m.SecurityWrapper\n}",
"func GetRevision() string {\n\tv := Map[\"revision\"]\n\treturn v\n}",
"func (h Header) Version() byte {\n\treturn h[1]\n}",
"func (m Message) GetUnderlyingSecurityID(f *field.UnderlyingSecurityIDField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}",
"func (m Message) GetUnderlyingSecurityID(f *field.UnderlyingSecurityIDField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}",
"func (i *Info) DocRev() uint8 {\n\tif i.Entry64 != nil {\n\t\treturn i.Entry64.SMBIOSDocRev\n\t}\n\treturn 0\n}",
"func (this *Device) GetRevision() (uint32, error) {\n\t// Return cached version\n\tif this.revision != GENCMD_REVISION_NONE {\n\t\treturn this.revision, nil\n\t}\n\n\t// Get embedded memory\n\totp, err := this.GetOTP()\n\tif err != nil {\n\t\treturn GENCMD_REVISION_NONE, err\n\t}\n\n\t// Cache and return revision number\n\tthis.revision = uint32(otp[GENCMD_OTP_DUMP_REVISION])\n\treturn this.revision, nil\n}",
"func (ref ostreeReference) signaturePath(index int) string {\n\treturn filepath.Join(\"manifest\", fmt.Sprintf(\"signature-%d\", index+1))\n}",
"func (r *GetResponseBody) GetSignature() *refs.Signature {\n\tif r != nil {\n\t\treturn r.sig\n\t}\n\n\treturn nil\n}",
"func getHandlerIndex(handler NotificationHandler, handlers []NotificationHandler) (int, error) {\n\tfor i, h := range handlers {\n\t\tif reflect.DeepEqual(h, handler) {\n\t\t\treturn i, nil\n\t\t}\n\t}\n\treturn -1, fmt.Errorf(\"handler not found\")\n}",
"func (s *SharedMemory) Signature() string {\n\treturn util.DecodeCharPtr(unsafe.Pointer(&s.shmem.dwSignature), C.sizeof_DWORD)\n}",
"func (m Message) SecurityResponseID() (*field.SecurityResponseIDField, quickfix.MessageRejectError) {\n\tf := &field.SecurityResponseIDField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}",
"func RevisionListHandlers(h hprinters.PrintHandler) {\n\tRevisionColumnDefinitions := []metav1beta1.TableColumnDefinition{\n\t\t{Name: \"Namespace\", Type: \"string\", Description: \"Namespace of the Knative service\", Priority: 0},\n\t\t{Name: \"Name\", Type: \"string\", Description: \"Name of the revision.\", Priority: 1},\n\t\t{Name: \"Service\", Type: \"string\", Description: \"Name of the Knative service.\", Priority: 1},\n\t\t{Name: \"Traffic\", Type: \"string\", Description: \"Percentage of traffic assigned to this revision.\", Priority: 1},\n\t\t{Name: \"Tags\", Type: \"string\", Description: \"Set of tags assigned to this revision.\", Priority: 1},\n\t\t{Name: \"Generation\", Type: \"string\", Description: \"Generation of the revision\", Priority: 1},\n\t\t{Name: \"Age\", Type: \"string\", Description: \"Age of the revision.\", Priority: 1},\n\t\t{Name: \"Conditions\", Type: \"string\", Description: \"Conditions describing statuses of the revision.\", Priority: 1},\n\t\t{Name: \"Ready\", Type: \"string\", Description: \"Ready condition status of the revision.\", Priority: 1},\n\t\t{Name: \"Reason\", Type: \"string\", Description: \"Reason for non-ready condition of the revision.\", Priority: 1},\n\t}\n\th.TableHandler(RevisionColumnDefinitions, printRevision)\n\th.TableHandler(RevisionColumnDefinitions, printRevisionList)\n}",
"func (s *DatabaseServerV3) GetRevision() string {\n\treturn s.Metadata.GetRevision()\n}",
"func (m CrossOrderCancelReplaceRequest) GetSecurityID() (v string, err quickfix.MessageRejectError) {\n\tvar f field.SecurityIDField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}",
"func (m Message) GetSecurityID(f *field.SecurityIDField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}",
"func (m Message) GetSecurityID(f *field.SecurityIDField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}",
"func (m Message) GetSecurityID(f *field.SecurityIDField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}",
"func (m Message) GetSecurityID(f *field.SecurityIDField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}",
"func (ecs *ECS) GetRevisionNumber(taskDefinitionArn string) string {\n\tcontents := strings.Split(taskDefinitionArn, \":\")\n\treturn contents[len(contents)-1]\n}",
"func (m *ManagedAppPolicy) GetVersion()(*string) {\n return m.version\n}",
"func (_LvStreamRightsHolder *LvStreamRightsHolderCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _LvStreamRightsHolder.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}",
"func getPluginSignatureState(log log.Logger, plugin *PluginBase) PluginSignature {\n\tlog.Debug(\"Getting signature state of plugin\", \"plugin\", plugin.Id)\n\tmanifestPath := path.Join(plugin.PluginDir, \"MANIFEST.txt\")\n\n\tbyteValue, err := ioutil.ReadFile(manifestPath)\n\tif err != nil || len(byteValue) < 10 {\n\t\treturn PluginSignatureUnsigned\n\t}\n\n\tmanifest, err := readPluginManifest(byteValue)\n\tif err != nil {\n\t\treturn PluginSignatureInvalid\n\t}\n\n\t// Make sure the versions all match\n\tif manifest.Plugin != plugin.Id || manifest.Version != plugin.Info.Version {\n\t\treturn PluginSignatureModified\n\t}\n\n\t// Verify the manifest contents\n\tlog.Debug(\"Verifying contents of plugin manifest\", \"plugin\", plugin.Id)\n\tfor p, hash := range manifest.Files {\n\t\t// Open the file\n\t\tfp := path.Join(plugin.PluginDir, p)\n\t\tf, err := os.Open(fp)\n\t\tif err != nil {\n\t\t\treturn PluginSignatureModified\n\t\t}\n\t\tdefer f.Close()\n\n\t\th := sha256.New()\n\t\tif _, err := io.Copy(h, f); err != nil {\n\t\t\tlog.Warn(\"Couldn't read plugin file\", \"plugin\", plugin.Id, \"filename\", fp)\n\t\t\treturn PluginSignatureModified\n\t\t}\n\t\tsum := hex.EncodeToString(h.Sum(nil))\n\t\tif sum != hash {\n\t\t\tlog.Warn(\"Plugin file's signature has been modified versus manifest\", \"plugin\", plugin.Id, \"filename\", fp)\n\t\t\treturn PluginSignatureModified\n\t\t}\n\t}\n\n\t// Everything OK\n\treturn PluginSignatureValid\n}",
"func HashControllerRevision(revision *apps.ControllerRevision, probe *int32) string {\n\thf := fnv.New32()\n\tif len(revision.Data.Raw) > 0 {\n\t\thf.Write(revision.Data.Raw)\n\t}\n\tif revision.Data.Object != nil {\n\t\thashutil.DeepHashObject(hf, revision.Data.Object)\n\t}\n\tif probe != nil {\n\t\thf.Write([]byte(strconv.FormatInt(int64(*probe), 10)))\n\t}\n\treturn rand.SafeEncodeString(fmt.Sprint(hf.Sum32()))\n}",
"func GetRevision(ctx context.Context) string {\n\tsv, ok := ctx.Value(ctxKeyRevision).(string)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\n\treturn sv\n}",
"func (x *XmlInfo) Revision() string {\n\treturn x.Enter.Commit.Revision\n}",
"func (_PBridge *PBridgeCaller) SignatureLength(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _PBridge.contract.Call(opts, &out, \"signatureLength\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}",
"func (_PBridge *PBridgeCallerSession) SignatureLength() (*big.Int, error) {\n\treturn _PBridge.Contract.SignatureLength(&_PBridge.CallOpts)\n}",
"func maxRevision(histories []*apps.ControllerRevision) int64 {\n\tmax := int64(0)\n\tfor _, history := range histories {\n\t\tif history.Revision > max {\n\t\t\tmax = history.Revision\n\t\t}\n\t}\n\treturn max\n}",
"func (r *repoManager) LastRollRev() string {\n\tr.infoMtx.RLock()\n\tdefer r.infoMtx.RUnlock()\n\treturn r.lastRollRev\n}",
"func (sid SourceID) RevID() string {\n\treturn sid.Version.Meta\n}",
"func (tx *Tx) Revision() uint64 {\n\treturn tx.revision\n}",
"func (s *AppServerV3) GetRevision() string {\n\treturn s.Metadata.GetRevision()\n}",
"func (policy *StorageAccounts_ManagementPolicy_Spec) OriginalVersion() string {\n\treturn GroupVersion.Version\n}",
"func (i *Info) GetSMBIOSDocRev() uint8 {\n\tif i.Entry64 != nil {\n\t\treturn i.Entry64.SMBIOSDocRev\n\t}\n\treturn 0\n}",
"func (m Message) UnderlyingSecurityID() (*field.UnderlyingSecurityIDField, quickfix.MessageRejectError) {\n\tf := &field.UnderlyingSecurityIDField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}",
"func (m Message) UnderlyingSecurityID() (*field.UnderlyingSecurityIDField, quickfix.MessageRejectError) {\n\tf := &field.UnderlyingSecurityIDField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}",
"func (o StorageClusterSpecPtrOutput) RevisionHistoryLimit() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *StorageClusterSpec) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.RevisionHistoryLimit\n\t}).(pulumi.IntPtrOutput)\n}",
"func (o *DhcpRangeDataData) GetServerVersion() string {\n\tif o == nil || o.ServerVersion == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ServerVersion\n}",
"func (m *DeviceHealthAttestationState) GetBootAppSecurityVersion()(*string) {\n val, err := m.GetBackingStore().Get(\"bootAppSecurityVersion\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func GetSigStyle(filename string) (PsSigStyle, bool) {\n\tstyle, ok := psExtMap[filepath.Ext(filename)]\n\treturn style, ok\n}",
"func (o StorageClusterSpecOutput) RevisionHistoryLimit() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v StorageClusterSpec) *int { return v.RevisionHistoryLimit }).(pulumi.IntPtrOutput)\n}",
"func (*PolicyfileRevisions) Descriptor() ([]byte, []int) {\n\treturn file_interservice_infra_proxy_request_policyfiles_proto_rawDescGZIP(), []int{3}\n}",
"func getSignature(r io.Reader, patterns []string) int {\n\tkdk := bufio.NewReader(r)\n\tre := compileRegex(patterns)\n\n\tindices := re.FindReaderSubmatchIndex(kdk)\n\n\t// the array is effectively start/end tuples\n\t// with the first two tuple representing the whole regex\n\t// and outer parens. indices[4] = pattern[0].start\n\tfor i := 4; i < len(indices); i += 2 {\n\t\tif indices[i] > -1 {\n\t\t\treturn (i - 4) / 2\n\t\t}\n\t}\n\treturn -1\n}",
"func (c *Config) SecurityLevel() int {\n\tval, ok := c.backend.Lookup(\"client.BCCSP.security.level\")\n\tif !ok {\n\t\treturn defLevel\n\t}\n\treturn cast.ToInt(val)\n}",
"func (o ApplicationSpecPtrOutput) RevisionHistoryLimit() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationSpec) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.RevisionHistoryLimit\n\t}).(pulumi.IntPtrOutput)\n}",
"func (h *Handler) RestoreHandler(snapshot []byte) (stateHash []byte, err error) {\n return []byte{}, nil\n}",
"func (s *StickerSet) GetThumbVersion() (value int, ok bool) {\n\tif s == nil {\n\t\treturn\n\t}\n\tif !s.Flags.Has(4) {\n\t\treturn value, false\n\t}\n\treturn s.ThumbVersion, true\n}",
"func (p *PdfiumImplementation) FPDF_GetFileVersion(request *requests.FPDF_GetFileVersion) (*responses.FPDF_GetFileVersion, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfileVersion := C.int(0)\n\n\tsuccess := C.FPDF_GetFileVersion(documentHandle.handle, &fileVersion)\n\tif int(success) == 0 {\n\t\treturn nil, errors.New(\"could not get file version\")\n\t}\n\n\treturn &responses.FPDF_GetFileVersion{\n\t\tFileVersion: int(fileVersion),\n\t}, nil\n}",
"func (*SignatureHelpClientCapabilities_SignatureInformation) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{114, 0}\n}",
"func (h *ResourceHeader) GetVersion() string {\n\treturn h.Version\n}",
"func (*CapabilityStatement_Rest_Security) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_r5_core_resources_capability_statement_proto_rawDescGZIP(), []int{0, 7, 1}\n}",
"func (m Message) GetSecurityReportID(f *field.SecurityReportIDField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}",
"func (s *SecureValueErrorReverseSide) GetFileHash() (value []byte) {\n\tif s == nil {\n\t\treturn\n\t}\n\treturn s.FileHash\n}",
"func (b Binding) Signature() (ret string) {\n\tret = b.ValidationString()\n\tif receivesBinaryContent(b) {\n\t\tret = \":\" + ret\n\t}\n\treturn\n}",
"func (r *RedirectNode) RightFD() int { return r.rmap.rfd }",
"func (client *ContainerAppsDiagnosticsClient) getRevisionHandleResponse(resp *http.Response) (ContainerAppsDiagnosticsClientGetRevisionResponse, error) {\n\tresult := ContainerAppsDiagnosticsClientGetRevisionResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.Revision); err != nil {\n\t\treturn ContainerAppsDiagnosticsClientGetRevisionResponse{}, err\n\t}\n\treturn result, nil\n}",
"func (tr *SQLTrigger) GetTerraformSchemaVersion() int {\n\treturn 0\n}",
"func (o ApplicationSpecOutput) RevisionHistoryLimit() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ApplicationSpec) *int { return v.RevisionHistoryLimit }).(pulumi.IntPtrOutput)\n}",
"func (o *SparseImageVulnerability) Version() int {\n\n\treturn 1\n}",
"func (fdf ExfatFileDirectoryEntry) SecondaryCount() uint8 {\n\treturn fdf.SecondaryCountRaw\n}",
"func (o *DeviceStatusTrigger) GetVersion() int32 {\n\tif o == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\n\treturn o.Version\n}",
"func (s *AgentServiceServer) VerifySecurityHandle(ctx context.Context, handle *pb.SecurityHandle) (*pb.SecurityReply, error) {\n\taction := &pb.SecurityRequest{\n\t\tAction: pb.AuthAction_AUTH_GET,\n\t\tData: &pb.SecurityRequest_Handle{handle},\n\t}\n\n\tresult, err := s.client.SecurityAction(context.Background(), action)\n\treturn result, err\n}",
"func (o *EntityWatchlistScreeningSearchTerms) GetVersion() int32 {\n\tif o == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\n\treturn o.Version\n}",
"func (*CMsgPageSecurity) Descriptor() ([]byte, []int) {\n\treturn file_steam_htmlmessages_proto_rawDescGZIP(), []int{47}\n}",
"func getValidAuditFileHeaderFooterVal(event string, headerFooterTag string) string {\n\tval := getEventHeaderVal(event, headerFooterTag)\n\tswitch {\n\tcase strings.HasPrefix(event, SchemaVersionHeader):\n\t\tif val == \"\" {\n\t\t\tval = eventLogInst.schemaVersion // Current schema version\n\t\t}\n\t}\n\treturn val\n}",
"func (o FioSpecVolumeVolumeSourceGitRepoPtrOutput) Revision() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSourceGitRepo) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Revision\n\t}).(pulumi.StringPtrOutput)\n}",
"func GetResponseSignature(response types.ProxyResponse) (string, string) {\n\t// Get Response Hash\n\tresponseHash := GetBlake2bHash(response.Response)\n\n\t// Generate json to be signed\n\tsign := new(types.ResponseSign)\n\tsign.Chainid = response.Chainid\n\tsign.Block = response.Block\n\tsign.Blocktime = response.Blocktime\n\tsign.Timestamp = response.Timestamp\n\tsign.Response = responseHash\n\tsignBytes, err := json.Marshal(sign)\n\tif err != nil {\n\t\treturn \"\", responseHash\n\t}\n\n\t// Get Signature\n\tsignature, err := config.Config.PrivKey.Sign(signBytes)\n\tif err != nil {\n\t\treturn \"\", responseHash\n\t}\n\n\treturn base64.StdEncoding.EncodeToString([]byte(signature)), responseHash\n}",
"func (o FioSpecVolumeVolumeSourceGitRepoOutput) Revision() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceGitRepo) *string { return v.Revision }).(pulumi.StringPtrOutput)\n}"
] | [
"0.5865406",
"0.48710278",
"0.48261127",
"0.47314197",
"0.46639752",
"0.4650029",
"0.45746568",
"0.45682356",
"0.45626837",
"0.45309928",
"0.4529698",
"0.45008165",
"0.44898537",
"0.44825384",
"0.4471004",
"0.44587272",
"0.44384384",
"0.44162482",
"0.44106174",
"0.4400474",
"0.43860734",
"0.4369323",
"0.4369323",
"0.4360427",
"0.43539265",
"0.4349766",
"0.43413842",
"0.43204525",
"0.43198735",
"0.4300698",
"0.42985803",
"0.42875677",
"0.42740253",
"0.4267964",
"0.4254687",
"0.4254687",
"0.42518532",
"0.4250748",
"0.42503816",
"0.42359668",
"0.42316753",
"0.42252713",
"0.42218968",
"0.42129347",
"0.42051494",
"0.41961554",
"0.4194324",
"0.4194324",
"0.4194324",
"0.4194324",
"0.41896135",
"0.4180671",
"0.41652113",
"0.41478834",
"0.41457245",
"0.41425174",
"0.4129726",
"0.41173258",
"0.41136995",
"0.41102883",
"0.4109516",
"0.40978032",
"0.4092166",
"0.40766275",
"0.40765205",
"0.40736565",
"0.4072722",
"0.4072722",
"0.40722805",
"0.40718216",
"0.4062932",
"0.40624177",
"0.4053894",
"0.40494916",
"0.40478188",
"0.4043898",
"0.40399662",
"0.40398973",
"0.40363255",
"0.4035922",
"0.40347522",
"0.4030228",
"0.40272737",
"0.40265438",
"0.40262505",
"0.4025248",
"0.40248248",
"0.40155312",
"0.401533",
"0.4013111",
"0.40095475",
"0.4004876",
"0.40022928",
"0.4000078",
"0.39999083",
"0.39996985",
"0.39984193",
"0.39958054",
"0.3994214",
"0.39857176"
] | 0.80261445 | 0 |
FPDF_GetPageCount counts the amount of pages. | func (p *PdfiumImplementation) FPDF_GetPageCount(request *requests.FPDF_GetPageCount) (*responses.FPDF_GetPageCount, error) {
p.Lock()
defer p.Unlock()
documentHandle, err := p.getDocumentHandle(request.Document)
if err != nil {
return nil, err
}
return &responses.FPDF_GetPageCount{
PageCount: int(C.FPDF_GetPageCount(documentHandle.handle)),
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (pi *PageInfo) PageCount() int {\n\tif pi.StartPage != 0 && pi.EndPage != 0 {\n\t\tcount := pi.EndPage - pi.StartPage\n\t\tif count > 0 {\n\t\t\treturn count\n\t\t}\n\t}\n\treturn 0\n}",
"func (p *Pagination) NumPages() uint {\n\treturn maxuint(1, uint(math.Ceil(float64(p.total)/float64(p.PerPage))))\n}",
"func (o OffsetPaginator) PageCount() uint {\n\tif o.Count == 0 {\n\t\treturn 1\n\t}\n\n\treturn uint(math.Ceil(float64(o.Count) / float64(o.Limit)))\n}",
"func (t *Tab) NumPages() int {\n\treturn len(t.children)\n}",
"func (p *Pagination) NumberOfPages() int {\n\treturn int(math.Ceil(float64(p.NumberOfItems()) / float64(p.ItemsPerPage())))\n}",
"func (p *Paginator) NumberOfPages() int {\n\treturn int(math.Ceil(float64(p.NumberOfItems()) / float64(p.ItemsPerPage())))\n}",
"func pageCount(numPages int32, page int32) int32 {\n\tvar pageTurns int32\n\t// determine pageTurns from front\n\tfromFront := (page) / 2\n\t// page Turns from back\n\tfromBack := (numPages - page) / 2\n\tif fromFront < fromBack {\n\t\tpageTurns = fromFront\n\t} else {\n\t\tpageTurns = fromBack\n\t}\n\t// Special cases\n\t// if numPages is an even number and looking for the page before last page, only one turn is required\n\tif numPages%2 == 0 && page == numPages-1 && fromFront != 0 {\n\t\tpageTurns = 1\n\t}\n\treturn pageTurns\n}",
"func (p *Pagination) pages() int {\n\treturn int(math.Ceil(float64(p.Total) / float64(p.Limit)))\n}",
"func (r *ImageRef) Pages() int {\n\t// libvips uses the same attribute (n_pages) to represent the number of pyramid layers in JP2K\n\t// as we interpret the attribute as frames and JP2K does not support animation we override this with 1\n\tif r.format == ImageTypeJP2K {\n\t\treturn 1\n\t}\n\n\treturn vipsGetImageNPages(r.image)\n}",
"func pagecount(size uint32) uint32 {\n\tnpage := size >> PageBits\n\tif size&(PageSize-1) != 0 {\n\t\tnpage++\n\t}\n\treturn npage\n}",
"func (p *PageStats) GetTotalPages() int {\n\tif p == nil || p.TotalPages == nil {\n\t\treturn 0\n\t}\n\treturn *p.TotalPages\n}",
"func calcTotalPages(totalCount, limit int64) int64 {\n\ttotalPages := int64(0)\n\tif totalCount != 0 && limit != 0 {\n\t\tif totalCount%limit > 0 {\n\t\t\ttotalPages = totalCount/limit + 1\n\t\t} else {\n\t\t\ttotalPages = totalCount / limit\n\t\t}\n\t}\n\treturn totalPages\n}",
"func (p *Pagination) TotalPages() int {\n\tif p.Total == 0 {\n\t\treturn 1\n\t}\n\tif p.Total%p.PageSize == 0 {\n\t\treturn p.Total / p.PageSize\n\t}\n\treturn p.Total/p.PageSize + 1\n}",
"func (r *ImageRef) GetPages() int {\n\treturn r.Pages()\n}",
"func (*offsetPageInfoImpl) TotalCount(p graphql.ResolveParams) (int, error) {\n\tpage := p.Source.(offsetPageInfo)\n\treturn page.totalCount, nil\n}",
"func (o *ViewMetaPage) GetCount() int32 {\n\tif o == nil || o.Count == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Count\n}",
"func Calcpages(onpage, count int) int {\n\tif onpage == 0 {\n\t\treturn 0\n\t}\n\ti := count / onpage\n\tif math.Mod(float64(count), float64(onpage)) > 0 {\n\t\ti++\n\t}\n\treturn i\n}",
"func (p *Pagination) NumberOfItems() int {\n\treturn p.numberOfItems\n}",
"func (vInfo *ZSetValues) calculatePagesCount() (int, error) {\n\tconn, err := connector.GetByName(vInfo.key.serverName, vInfo.key.dbNum)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tcount := 0\n\tif vInfo.query.Mask == \"*\" {\n\t\tr, err := conn.Do(\"ZCARD\", vInfo.key.key)\n\t\tcount, err = redis.Int(r, err)\n\t} else {\n\t\tif !vInfo.valuesLoaded {\n\t\t\terr = vInfo.loadValues()\n\t\t}\n\t\tcount = vInfo.totalValuesCount\n\t}\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn getValuesPagesCount(count, vInfo.query.PageSize), nil\n}",
"func (m *Pagination) GetTotalPages() int32 {\n\tif m != nil {\n\t\treturn m.TotalPages\n\t}\n\treturn 0\n}",
"func (p *Pagination) CurrentPageCount() uint {\n\treturn minuint((p.total - p.Offset()), p.PerPage)\n}",
"func (o *PolicyItemsPage) GetTotalCount() int32 {\n\tif o == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\n\treturn o.TotalCount\n}",
"func GetPageAndCount(r *http.Request, offset bool) (int, int) {\n\tp64, err := strconv.ParseInt(r.URL.Query().Get(\"p\"), 10, 0)\n\tp := int(p64)\n\tif err != nil || p < 1 {\n\t\tp = 1\n\t}\n\n\tc64, err := strconv.ParseInt(r.URL.Query().Get(\"c\"), 10, 0)\n\tc := int(c64)\n\tif err != nil || c > config.Config.Page.MaxPerPage || c < config.Config.Page.MinPerPage {\n\t\tc = config.Config.Page.PerPage\n\t}\n\n\tif offset {\n\t\t// If i need to make it to offset model then do it here\n\t\tp = (p - 1) * c\n\t}\n\n\treturn p, c\n}",
"func countPagesCrawled(api *API, siteName, siteURL string) int {\n\tvar pagesCount = 0\n\t// location of the pages count script wrt localgoogoo root dir\n\tvar path = \"/php/get_pages_count.php\"\n\n\tvar urlString = fmt.Sprintf(\"%s%s?sitename=%s&siteurl=%s\", api.BaseURL, path, siteName, siteURL)\n\n\t// make request\n\tresp, err := api.Client.Get(urlString)\n\tif err != nil {\n\t\treturn pagesCount\n\t}\n\n\t// read in response\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn pagesCount\n\t}\n\tdefer resp.Body.Close()\n\n\t// convert response to integers\n\tv, err := strconv.Atoi(string(body))\n\tif err != nil {\n\t\treturn pagesCount\n\t}\n\n\treturn v\n}",
"func (pump *Pump) HistoryPageCount() int {\n\tdata := pump.Execute(historyPageCount)\n\tif pump.Error() != nil {\n\t\te, ok := pump.Error().(InvalidCommandError)\n\t\tif ok && e.PumpError == CommandRefused && pump.Family() == 12 {\n\t\t\tpump.SetError(nil)\n\t\t\treturn Max512HistoryPages\n\t\t}\n\t\treturn 0\n\t}\n\tif len(data) < 5 || data[0] != 4 {\n\t\tpump.BadResponse(historyPageCount, data)\n\t\treturn 0\n\t}\n\tpage := fourByteUint(data[1:5])\n\tif page == 0 {\n\t\t// Pumps can return 0 when first turned on.\n\t\treturn 1\n\t}\n\tif page > MaxHistoryPages {\n\t\tpage = MaxHistoryPages\n\t}\n\treturn int(page)\n}",
"func (p *PdfiumImplementation) FPDF_GetPageWidth(request *requests.FPDF_GetPageWidth) (*responses.FPDF_GetPageWidth, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twidth := C.FPDF_GetPageWidth(pageHandle.handle)\n\n\treturn &responses.FPDF_GetPageWidth{\n\t\tPage: pageHandle.index,\n\t\tWidth: float64(width),\n\t}, nil\n}",
"func (p *Paginator) NumberOfItems() int {\n\treturn p.numberOfItems\n}",
"func (s *API) NumberOfPagesInTradeHistory(start, end time.Time, tradesPerPage int, apiType int) int {\n\trowcount := 0\n\tif apiType == tradeHistoryTypeLoadEarnings {\n\t\tq := s.db.Model(&lendings.Lending{}).Where(\"close between ? and ?\", start, end)\n\t\tq.Order(\"close desc\").Count(&rowcount)\n\n\t} else {\n\t\tq := s.db.Model(&exchanges.Exchange{}).Where(\"date between ? and ?\", start, end)\n\t\tswitch apiType {\n\t\tcase tradeHistoryTypeBuysOnly:\n\t\t\tq = q.Where(\"type = ?\", exchanges.ExchangeBuy)\n\t\tcase tradeHistoryTypeSellsOnly:\n\t\t\tq = q.Where(\"type = ?\", exchanges.ExchangeSell)\n\t\tcase tradeHistoryTypeBuysAndSells:\n\t\t}\n\t\tq.Order(\"date desc\").Count(&rowcount)\n\t}\n\n\tif rowcount == 0 {\n\t\treturn 0\n\t}\n\tpage := ((rowcount - 1) / tradesPerPage) + 1\n\treturn page\n}",
"func fn_get__amount_pages(_c_amount_pages chan int) {\n\n\tres := fn_get__http()\n\n\tdefer res.Body.Close()\n\n\tdoc, err := goquery.NewDocumentFromReader(res.Body)\n\n\tfn_check__error(err)\n\n\t// first page + extra pages\n\tint_pages := doc.Find(\".tplPagination > ul a\").Length() + 1\n\n\t_c_amount_pages <- int_pages\n}",
"func (o *PaginationPageInfo) GetTotalCount() string {\n\tif o == nil || o.TotalCount == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.TotalCount\n}",
"func GetPhotoPageAmount(username string) int {\n\tphotos := *GetAllPhotosByUser(username)\n\ttotal := len(photos)\n\tif total == 0 {\n\t\treturn 0\n\t}\n\tamount := total / 9\n\tif total == 9 {\n\t\treturn 1\n\t}\n\treturn amount + 1\n}",
"func (p *Pagination) Pages() []int {\n\ts := make([]int, 0, p.NumberOfPages())\n\n\tfor i := 1; i <= p.NumberOfPages(); i++ {\n\t\ts = append(s, i)\n\t}\n\n\treturn s\n}",
"func GetPageSize() uint64 {\n\tpanic(\"not implemented\")\n}",
"func (p *PageViews) Count() (count int64) {\n\tp.Lock()\n\tcount = p.count\n\tp.Unlock()\n\treturn count\n}",
"func GetNumberOfPosts(isPage bool, published bool) (int64, error) {\n\tsession := postSession.Clone()\n\n\tvar err error\n\tvar cnt int\n\tif published {\n\t\tcnt, err = session.DB(DBName).C(\"posts\").Find(bson.M{\"ispage\": isPage, \"ispublished\": true}).Count()\n\t} else {\n\t\tcnt, err = session.DB(DBName).C(\"posts\").Find(bson.M{\"ispage\": isPage}).Count()\n\t}\n\n\treturn int64(cnt), err\n}",
"func (current OffsetPageBase) getPageSize() (int, error) {\n\tvar pageSize int\n\n\tswitch pb := current.Body.(type) {\n\tcase map[string]interface{}:\n\t\tfor k, v := range pb {\n\t\t\t// ignore xxx_links\n\t\t\tif !strings.HasSuffix(k, \"links\") {\n\t\t\t\t// check the field's type. we only want []interface{} (which is really []map[string]interface{})\n\t\t\t\tswitch vt := v.(type) {\n\t\t\t\tcase []interface{}:\n\t\t\t\t\tpageSize = len(vt)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase []interface{}:\n\t\tpageSize = len(pb)\n\tdefault:\n\t\terr := golangsdk.ErrUnexpectedType{}\n\t\terr.Expected = \"map[string]interface{}/[]interface{}\"\n\t\terr.Actual = fmt.Sprintf(\"%T\", pb)\n\t\treturn 0, err\n\t}\n\n\treturn pageSize, nil\n}",
"func (p *Paginator) Pages() []int {\n\ts := make([]int, 0, p.NumberOfPages())\n\n\tfor i := 1; i <= p.NumberOfPages(); i++ {\n\t\ts = append(s, i)\n\t}\n\n\treturn s\n}",
"func (p Page) Len() int { return len(p) }",
"func (_m *UserRepositoryI) PagesCount(dbI database.Interface, perPage int) (int, error) {\n\tret := _m.Called(dbI, perPage)\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func(database.Interface, int) int); ok {\n\t\tr0 = rf(dbI, perPage)\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(database.Interface, int) error); ok {\n\t\tr1 = rf(dbI, perPage)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}",
"func GetEpubsNumberOfPages(db XODB) ([]*EpubsNumberOfPages, error) {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `SELECT LEFT(RIGHT(oee.source, 18), 13) AS isbn, COUNT(ol.*) as number_of_pages ` +\n\t\t`FROM otx_epub_epub oee INNER JOIN occurrence_location ol on oee.document_ptr_id = ol.document_id ` +\n\t\t`GROUP BY isbn ` +\n\t\t`ORDER BY isbn`\n\n\t// run query\n\tXOLog(sqlstr)\n\tq, err := db.Query(sqlstr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer q.Close()\n\n\t// load results\n\tres := []*EpubsNumberOfPages{}\n\tfor q.Next() {\n\t\tenop := EpubsNumberOfPages{}\n\n\t\t// scan\n\t\terr = q.Scan(&enop.Isbn, &enop.NumberOfPages)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tres = append(res, &enop)\n\t}\n\n\treturn res, nil\n}",
"func (o *PaginationDataResponse) GetPageSize() float32 {\n\tif o == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\n\treturn o.PageSize\n}",
"func (_p *ArticlePage) buildPageCount() error {\n\tcount, err := ArticleCountWhere(_p.WhereString, _p.WhereParams...)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_p.TotalItems = count\n\tif _p.PerPage == 0 {\n\t\t_p.PerPage = 10\n\t}\n\t_p.TotalPages = int(math.Ceil(float64(_p.TotalItems) / float64(_p.PerPage)))\n\treturn nil\n}",
"func (r *ImageRef) GetPageHeight() int {\n\treturn vipsGetPageHeight(r.image)\n}",
"func (p *PdfiumImplementation) FPDFLink_CountWebLinks(request *requests.FPDFLink_CountWebLinks) (*responses.FPDFLink_CountWebLinks, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageLinkhandle, err := p.getPageLinkHandle(request.PageLink)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcount := C.FPDFLink_CountWebLinks(pageLinkhandle.handle)\n\n\treturn &responses.FPDFLink_CountWebLinks{\n\t\tCount: int(count),\n\t}, nil\n}",
"func (p *Pagination) ItemsPerPage() int {\n\treturn p.itemsPerPage\n}",
"func (m *PrinterDefaults) GetPagesPerSheet()(*int32) {\n val, err := m.GetBackingStore().Get(\"pagesPerSheet\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}",
"func (o *PaginationProperties) GetReturnedCount() int32 {\n\tif o == nil || o.ReturnedCount == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.ReturnedCount\n}",
"func GetTotalPageLimitOffset(page, totalCount int) (int, int, int) {\n\tlimit := 10\n\toffset := (page - 1) * limit\n\ttotalPages := (totalCount / limit) + 1\n\treturn limit, offset, totalPages\n}",
"func (p *Paginator) PageNums() int {\n\tif p.pageNums != 0 {\n\t\treturn p.pageNums\n\t}\n\tpageNums := math.Ceil(float64(p.nums) / float64(p.PerPageNums))\n\tif p.MaxPages > 0 {\n\t\tpageNums = math.Min(pageNums, float64(p.MaxPages))\n\t}\n\tp.pageNums = int(pageNums)\n\treturn p.pageNums\n}",
"func (o *PointsRetentionOptions) GetCount() int32 {\n\tif o == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\n\treturn o.Count\n}",
"func (e *stackScriptPaginated) pageNumber() int {\n\treturn e.Page\n}",
"func (r *ImageRef) PageHeight() int {\n\treturn vipsGetPageHeight(r.image)\n}",
"func (f *Face) NumFaces() int {\n\treturn int(f.handle.num_faces)\n}",
"func (p *PdfiumImplementation) FPDFLink_CountRects(request *requests.FPDFLink_CountRects) (*responses.FPDFLink_CountRects, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageLinkhandle, err := p.getPageLinkHandle(request.PageLink)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcount := C.FPDFLink_CountRects(pageLinkhandle.handle, C.int(request.Index))\n\n\treturn &responses.FPDFLink_CountRects{\n\t\tCount: int(count),\n\t}, nil\n}",
"func (it *TopicIterator) PageSize() int {\n\treturn int(it.pageSize)\n}",
"func (p *PdfiumImplementation) FPDF_GetPageHeight(request *requests.FPDF_GetPageHeight) (*responses.FPDF_GetPageHeight, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theight := C.FPDF_GetPageHeight(pageHandle.handle)\n\n\treturn &responses.FPDF_GetPageHeight{\n\t\tPage: pageHandle.index,\n\t\tHeight: float64(height),\n\t}, nil\n}",
"func (pb *PageBuffer) PageNo() int {\n return pb.page_no\n}",
"func (p *Paginator) HasPages() bool {\n\treturn p.PageNums() > 1\n}",
"func Getpagesize() int",
"func paging(start, length, totalCount int) (int, int) {\n\tif length == 0 {\n\t\tlength = 20\n\t}\n\n\tstart = totalCount - start - length\n\tif start < 0 {\n\t\tlength += start\n\t\tstart = 0\n\t}\n\treturn start, length\n}",
"func (u *UserResultsPage) setTotalPages(p int) {\n\tu.TotalPages = p\n}",
"func (p *Pager) GetPages() (*PagingResponse, error) {\n\n\tcount, err := p.fetcher.Count(p.Condition)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.totalCount = count\n\n\tpageCount := p.GetPageCount()\n\tif pageCount == 0 {\n\t\treturn p.formatResponse(PageFetchResult{}, PageFetchResult{}, PageFetchResult{}), nil\n\t}\n\tif p.page > pageCount {\n\t\treturn nil, fmt.Errorf(\"page is out of range. page range is 1-%v\", pageCount)\n\t}\n\n\t// active と sides に相当する範囲をまとめて取得する\n\tlimit, offset := p.GetActiveAndSidesLimit()\n\tactiveAndSides := make(PageFetchResult, 0, limit)\n\tfetchActiveInput := &PageFetchInput{\n\t\tLimit: limit,\n\t\tOffset: offset,\n\t\tOrders: p.Orders,\n\t}\n\terr = p.fetcher.FetchPage(p.Condition, fetchActiveInput, &activeAndSides)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// 最初のページが範囲外の場合は取得する\n\tfirst := make(PageFetchResult, 0, p.limit)\n\tif p.StartPageIndex() > 0 {\n\t\tfetchFirstInput := &PageFetchInput{\n\t\t\tLimit: p.limit,\n\t\t\tOffset: 0,\n\t\t\tOrders: p.Orders,\n\t\t}\n\t\terr = p.fetcher.FetchPage(p.Condition, fetchFirstInput, &first)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// 最後のページが範囲外の場合は取得する\n\tlast := make(PageFetchResult, 0, p.limit)\n\tif p.StartPageIndex()+(p.sidePagingCount*2) < p.LastPageIndex() {\n\n\t\tfetchLastInput := &PageFetchInput{\n\t\t\tLimit: p.limit,\n\t\t\tOffset: p.LastPageIndex() * p.limit,\n\t\t\tOrders: p.Orders,\n\t\t}\n\t\terr = p.fetcher.FetchPage(p.Condition, fetchLastInput, &last)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn p.formatResponse(first, activeAndSides, last), nil\n}",
"func (p *Page) Size() int {\n\treturn p.LineSize() * p.UnreadLines()\n}",
"func TotalCount(resp *http.Response) int {\n\tif resp == nil {\n\t\treturn 0\n\t}\n\n\ttotalCountHeader := resp.Header.Get(totalCountHeaderKey)\n\ttotalCount, err := strconv.ParseInt(totalCountHeader, 10, 64)\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\treturn int(totalCount)\n}",
"func (a *AdminStats) GetPages() *PageStats {\n\tif a == nil {\n\t\treturn nil\n\t}\n\treturn a.Pages\n}",
"func (i *Info) CalculatePages(itemTotal int) {\n\ti.TotalPages = itemTotal / i.PerPage\n\tfor x, val := range showing {\n\t\tif itemTotal == val && x < len(showing) {\n\t\t\ti.ShowResults = showing[:x]\n\t\t}\n\t\tif itemTotal > val && x+2 < len(showing) {\n\t\t\ti.ShowResults = showing[:x+2]\n\t\t}\n\t}\n\tif itemTotal%i.PerPage != 0 {\n\t\ti.TotalPages++\n\t}\n\tmaxshow := 5\n\tif maxshow > i.TotalPages {\n\t\tmaxshow = i.TotalPages\n\t}\n\tarr := make([]int, maxshow+2)\n\tif i.Page > 1 {\n\t\tarr[0] = i.Page - 1\n\t}\n\tif i.Page < i.TotalPages {\n\t\tarr[maxshow+1] = i.Page + 1\n\t}\n\tfor pi := 0; pi < maxshow; pi++ {\n\t\tif i.Page <= i.TotalPages-maxshow+1 {\n\t\t\tarr[pi+1] = pi + i.Page\n\t\t} else {\n\t\t\tarr[pi+1] = i.TotalPages - maxshow + pi + 1\n\t\t}\n\t}\n\n\ti.Pages = arr\n\n}",
"func GetPDFPages(inPath string, outPath string, frames []parser.Section) error {\n\n\tif _, err := os.Stat(outPath); os.IsNotExist(err) {\n\t\tlog.Println(\"Output dir not found. Creating at \", outPath)\n\t\terr := os.Mkdir(outPath, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"[PDF Extractor] %s\", err)\n\t\t}\n\t}\n\n\timagick.Initialize()\n\tdefer imagick.Terminate()\n\n\tmw := imagick.NewMagickWand()\n\tdefer mw.Destroy()\n\n\tif err := mw.SetResolution(300, 300); err != nil {\n\t\treturn err\n\t}\n\n\t// Load the image file into imagick\n\tif err := mw.ReadImage(inPath); err != nil {\n\t\treturn err\n\t}\n\n\t// fmt.Println(mw.GetNumberImages())\n\n\t// Set any compression (100 = max quality)\n\tif err := mw.SetCompressionQuality(100); err != nil {\n\t\treturn err\n\t}\n\n\tif err := mw.SetFormat(\"jpg\"); err != nil {\n\t\treturn err\n\t}\n\tvar err error\n\tfor _, frame := range frames {\n\n\t\tmw.SetIteratorIndex(frame.Page - 1)\n\n\t\t// if err := mw.SetImageFormat(\"jpeg\"); err != nil {\n\t\t// \treturn err\n\t\t// }\n\n\t\t// Save File\n\t\terr = mw.WriteImage(filepath.Join(outPath, frame.FrameSrc.ImageSrc))\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%s [PDF extraction: page: %d, loc: %s, to %s] \", err, frame.Page, inPath, filepath.Join(outPath, frame.FrameSrc.ImageSrc))\n\t\t}\n\n\t}\n\treturn nil\n}",
"func (psg PagesGroup) Len() int {\n\tl := 0\n\tfor _, pg := range psg {\n\t\tl += len(pg.Pages)\n\t}\n\treturn l\n}",
"func TestGetPageSize(t *testing.T) {\n\tcases := []struct {\n\t\toffset, total, limit, expected int64\n\t\tname string\n\t}{\n\t\t{1, 0, 50, 0, \"no results\"},\n\t\t{1, 1, 50, 1, \"first partial page\"},\n\t\t{1, 50, 50, 50, \"first full page\"},\n\t\t{2, 100, 50, 50, \"second page full\"},\n\t\t{2, 51, 50, 1, \"last partial page\"},\n\t}\n\tfor _, tt := range cases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tactual := getPageSize(tt.offset, tt.total, tt.limit)\n\t\t\tassert.Equal(t, tt.expected, actual, \"actual didn't match expected\")\n\t\t})\n\t}\n}",
"func (f *FoundChatMessages) GetTotalCount() (value int32) {\n\tif f == nil {\n\t\treturn\n\t}\n\treturn f.TotalCount\n}",
"func (o *PaginationPageInfo) HasTotalCount() bool {\n\tif o != nil && o.TotalCount != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (p *Paginator) ItemsPerPage() int {\n\treturn p.itemsPerPage\n}",
"func (db *DataBase) GetUsersPageAmount(perPage int) (amount int, err error) {\n\tsqlStatement := `SELECT count(1) FROM Player`\n\trow := db.Db.QueryRow(sqlStatement)\n\tif err = row.Scan(&amount); err != nil {\n\t\treturn\n\t}\n\n\tif amount > db.PageUsers {\n\t\tamount = db.PageUsers\n\t}\n\tif perPage == 0 {\n\t\tperPage = 1\n\t}\n\tamount = int(math.Ceil(float64(amount) / float64(perPage)))\n\treturn\n}",
"func (p *PdfiumImplementation) FPDF_GetPageSizeByIndex(request *requests.FPDF_GetPageSizeByIndex) (*responses.FPDF_GetPageSizeByIndex, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twidth := C.double(0)\n\theight := C.double(0)\n\n\tresult := C.FPDF_GetPageSizeByIndex(documentHandle.handle, C.int(request.Index), &width, &height)\n\tif int(result) == 0 {\n\t\treturn nil, errors.New(\"could not load page size by index\")\n\t}\n\n\treturn &responses.FPDF_GetPageSizeByIndex{\n\t\tPage: request.Index,\n\t\tWidth: float64(width),\n\t\tHeight: float64(height),\n\t}, nil\n}",
"func (p *Paginator) Page() int {\n\tif p.page != 0 {\n\t\treturn p.page\n\t}\n\tif p.Request.Form == nil {\n\t\tp.Request.ParseForm()\n\t}\n\tp.page, _ = strconv.Atoi(p.Request.Form.Get(\"p\"))\n\tif p.page > p.PageNums() {\n\t\tp.page = p.PageNums()\n\t}\n\tif p.page <= 0 {\n\t\tp.page = 1\n\t}\n\treturn p.page\n}",
"func (p *PdfiumImplementation) FPDF_VIEWERREF_GetNumCopies(request *requests.FPDF_VIEWERREF_GetNumCopies) (*responses.FPDF_VIEWERREF_GetNumCopies, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnumCopies := C.FPDF_VIEWERREF_GetNumCopies(documentHandle.handle)\n\treturn &responses.FPDF_VIEWERREF_GetNumCopies{\n\t\tNumCopies: int(numCopies),\n\t}, nil\n}",
"func (p *PdfiumImplementation) FPDFText_CountRects(request *requests.FPDFText_CountRects) (*responses.FPDFText_CountRects, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\ttextPageHandle, err := p.getTextPageHandle(request.TextPage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcount := C.FPDFText_CountRects(textPageHandle.handle, C.int(request.StartIndex), C.int(request.Count))\n\treturn &responses.FPDFText_CountRects{\n\t\tCount: int(count),\n\t}, nil\n}",
"func (p *Pagination) Page(total int) (from int, to int) {\n\tif p.Num == 0 {\n\t\tp.Num = 1\n\t}\n\tif p.Size == 0 {\n\t\tp.Size = DefaultSize\n\t}\n\n\tif total == 0 || total < p.Size*(p.Num-1) {\n\t\treturn\n\t}\n\tif total <= p.Size {\n\t\treturn 1, total\n\t}\n\tfrom = (p.Num-1)*p.Size + 1\n\tif (total - from + 1) < p.Size {\n\t\treturn from, total\n\t}\n\treturn from, from + p.Size - 1\n}",
"func (obj *Doc) ForwardCount(ctx context.Context) (int, error) {\n\tresult := &struct {\n\t\tReturn int `json:\"qReturn\"`\n\t}{}\n\terr := obj.RPC(ctx, \"ForwardCount\", result)\n\treturn result.Return, err\n}",
"func (r *Reader) PageSize(numOfRecs int) *Reader {\n\tif r.XMLName.Local == readByQueryXMLName.Local {\n\t\tr.MaxRecs = numOfRecs\n\t}\n\treturn r\n}",
"func (o *PaginationDataResponse) GetPage() float32 {\n\tif o == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\n\treturn o.Page\n}",
"func PRepCount() float64 {\n\tpReps.Mutex.Lock()\n\tcount := len(pReps.PReps)\n\tpReps.Mutex.Unlock()\n\treturn float64(count)\n}",
"func (o *ViewMetaPage) GetPageSize() int32 {\n\tif o == nil || o.PageSize == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.PageSize\n}",
"func (o OffsetPaginator) Page() uint {\n\tif o.Count == 0 {\n\t\treturn 1\n\t}\n\n\treturn uint(math.Ceil(float64(o.Offset)/float64(o.Limit))) + 1\n}",
"func (geom Geometry) PointCount() int {\n\tcount := C.OGR_G_GetPointCount(geom.cval)\n\treturn int(count)\n}",
"func (p *PdfiumImplementation) FPDFText_CountChars(request *requests.FPDFText_CountChars) (*responses.FPDFText_CountChars, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\ttextPageHandle, err := p.getTextPageHandle(request.TextPage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcharCount := C.FPDFText_CountChars(textPageHandle.handle)\n\tif int(charCount) == -1 {\n\t\treturn nil, errors.New(\"could not get char count\")\n\t}\n\n\treturn &responses.FPDFText_CountChars{\n\t\tCount: int(charCount),\n\t}, nil\n}",
"func (*offsetPageInfoImpl) PartialCount(p graphql.ResolveParams) (bool, error) {\n\tpage := p.Source.(offsetPageInfo)\n\treturn page.partialCount, nil\n}",
"func (rra *RoundRobinArchive) PointCount() int {\n\treturn len(rra.dps)\n}",
"func (o AccessCustomPageOutput) AppCount() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *AccessCustomPage) pulumi.IntPtrOutput { return v.AppCount }).(pulumi.IntPtrOutput)\n}",
"func (o *MicrosoftGraphMailSearchFolder) GetChildFolderCount() int32 {\n\tif o == nil || o.ChildFolderCount == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.ChildFolderCount\n}",
"func (f *ProgressNotice) ByteCount() int {\n\treturn 8 + f.User.ByteCount()\n}",
"func (e *linodeImagePaginated) pageNumber() int {\n\treturn e.Page\n}",
"func (s *MessagesSearchCounter) GetCount() (value int) {\n\tif s == nil {\n\t\treturn\n\t}\n\treturn s.Count\n}",
"func (m *Page) GetPageNumber() int32 {\n\tif m != nil {\n\t\treturn m.PageNumber\n\t}\n\treturn 0\n}",
"func (g *NgGrid) GetPageNumber() int64 {\n\tif g.PageNumber == 0 {\n\t\tg.PageNumber = 1\n\t}\n\treturn g.PageNumber\n}",
"func (p *Pagination) Total() uint {\n\treturn p.total\n}",
"func (p *PostingsList) Count() uint64 {\n\tvar n, e uint64\n\tif p.normBits1Hit != 0 {\n\t\tn = 1\n\t\tif p.except != nil && p.except.Contains(uint32(p.docNum1Hit)) {\n\t\t\te = 1\n\t\t}\n\t} else if p.postings != nil {\n\t\tn = p.postings.GetCardinality()\n\t\tif p.except != nil {\n\t\t\te = p.postings.AndCardinality(p.except)\n\t\t}\n\t}\n\treturn n - e\n}",
"func (this *RectangleShape) GetPointCount() uint {\n\treturn uint(C.sfRectangleShape_getPointCount(this.cptr))\n}",
"func (s *Srt) GetCount() int {\n\treturn s.count\n}",
"func (o *ViewMetaPage) SetCount(v int32) {\n\to.Count = &v\n}"
] | [
"0.76611865",
"0.6928234",
"0.67353827",
"0.6632952",
"0.6614523",
"0.6594917",
"0.6519151",
"0.6449557",
"0.62487954",
"0.6076024",
"0.5972401",
"0.59684604",
"0.59374714",
"0.5882277",
"0.5748166",
"0.5721702",
"0.57014704",
"0.56623805",
"0.56411016",
"0.56012404",
"0.56009597",
"0.5518937",
"0.54722106",
"0.54048395",
"0.5399325",
"0.5362644",
"0.5350456",
"0.5349645",
"0.53184086",
"0.52891916",
"0.5285473",
"0.52850336",
"0.52785444",
"0.52776265",
"0.52683526",
"0.5256748",
"0.5256571",
"0.5253334",
"0.5214821",
"0.5201301",
"0.5176086",
"0.51645136",
"0.51473314",
"0.51452357",
"0.51277703",
"0.51140696",
"0.51098204",
"0.5104618",
"0.50989103",
"0.50796896",
"0.50419086",
"0.5026311",
"0.5020765",
"0.5016229",
"0.4989732",
"0.49818707",
"0.49625662",
"0.4950931",
"0.49447134",
"0.4942584",
"0.49415842",
"0.4937076",
"0.49318528",
"0.49227598",
"0.49196744",
"0.4916436",
"0.49141592",
"0.49082974",
"0.49076802",
"0.49036956",
"0.49009275",
"0.48988092",
"0.48852494",
"0.48786765",
"0.48681527",
"0.4862009",
"0.48510316",
"0.48190486",
"0.48161352",
"0.4808251",
"0.47987983",
"0.47953203",
"0.47942096",
"0.47940597",
"0.47934255",
"0.47870582",
"0.47856635",
"0.47849625",
"0.47696817",
"0.47684616",
"0.4765965",
"0.47542194",
"0.47524047",
"0.47517374",
"0.47487277",
"0.47475234",
"0.47449595",
"0.473642",
"0.47363213",
"0.4736198"
] | 0.73498696 | 1 |
FPDF_GetPageWidth returns the width of a page. | func (p *PdfiumImplementation) FPDF_GetPageWidth(request *requests.FPDF_GetPageWidth) (*responses.FPDF_GetPageWidth, error) {
p.Lock()
defer p.Unlock()
pageHandle, err := p.loadPage(request.Page)
if err != nil {
return nil, err
}
width := C.FPDF_GetPageWidth(pageHandle.handle)
return &responses.FPDF_GetPageWidth{
Page: pageHandle.index,
Width: float64(width),
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (s *SimPDF) Width() float64 {\n\tif s.Page.IsLandscape {\n\t\treturn s.Page.Height\n\t}\n\treturn s.Page.Width\n}",
"func (s *PageLayout) Width() float64 {\n\treturn s.width\n}",
"func (rect *PdfRectangle) Width() float64 {\n\treturn math.Abs(rect.Urx - rect.Llx)\n}",
"func getContentWidth(pdf *gofpdf.Fpdf) float64 {\n\tmarginL, _, marginR, _ := pdf.GetMargins()\n\tpageW, _ := pdf.GetPageSize()\n\twidth := pageW - marginL - marginR\n\treturn width\n}",
"func (pc PieChart) GetWidth() int {\n\tif pc.Width == 0 {\n\t\treturn DefaultChartWidth\n\t}\n\treturn pc.Width\n}",
"func (p *Picture) GetWidth() int {\r\n\treturn p.pixelWidth\r\n}",
"func (image *JPGImage) GetWidth() float32 {\n\treturn float32(image.width)\n}",
"func (pi *PageInfo) PageCount() int {\n\tif pi.StartPage != 0 && pi.EndPage != 0 {\n\t\tcount := pi.EndPage - pi.StartPage\n\t\tif count > 0 {\n\t\t\treturn count\n\t\t}\n\t}\n\treturn 0\n}",
"func (o *TileBounds) GetWidth() int32 {\n\tif o == nil || o.Width == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Width\n}",
"func (t *Link) GetWidth() (v int64) {\n\treturn *t.width.nonNegativeInteger\n\n}",
"func (tex *Image) Width() int {\n\tsize := C.sfTexture_getSize(tex.tex)\n\treturn int(size.x)\n}",
"func (o *WorkbookChart) GetWidth() AnyOfnumberstringstring {\n\tif o == nil || o.Width == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret\n\t}\n\treturn *o.Width\n}",
"func (info *ImageInfoType) Width() float64 {\n\treturn info.w / (info.scale * info.dpi / 72)\n}",
"func Width() int {\n\tws, err := getWinsize()\n\n\tif err != nil {\n\t\treturn -1\n\t}\n\n\treturn int(ws.Col)\n}",
"func (o *FileInfoThumbnail) GetWidth() int32 {\n\tif o == nil || o.Width == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Width\n}",
"func (p *Page) Size() int {\n\treturn p.LineSize() * p.UnreadLines()\n}",
"func (win *Window) Width() int {\n\tsize := C.sfRenderWindow_getSize(win.win)\n\treturn int(size.x)\n}",
"func (image *Image2D) GetWidth() int {\n\treturn image.width\n}",
"func (a *Animation) GetWidth() float64 {\n\tif a == nil || a.Width == nil {\n\t\treturn 0.0\n\t}\n\treturn *a.Width\n}",
"func (b *BaseElement) GetWidth() int32 {\n\treturn b.w\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetWidth(request *requests.FPDFBitmap_GetWidth) (*responses.FPDFBitmap_GetWidth, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twidth := C.FPDFBitmap_GetWidth(bitmapHandle.handle)\n\treturn &responses.FPDFBitmap_GetWidth{\n\t\tWidth: int(width),\n\t}, nil\n}",
"func (r *ImageRef) Width() int {\n\treturn int(r.image.Xsize)\n}",
"func (s *SimPDF) StringWidth(text string) float64 {\n\treturn s.PDF.GetStringWidth(text)\n}",
"func (r Rectangle) Width() float64 {\n\treturn r.Max.X - r.Min.X\n}",
"func (s *ImageSpec) Width() int {\n\tret := int(C.ImageSpec_width(s.ptr))\n\truntime.KeepAlive(s)\n\treturn ret\n}",
"func (rc Rectangle) Width() int {\n\treturn rc.Right - rc.Left\n}",
"func (t Texture3D) GetWidth() int32 {\n\treturn t.width\n}",
"func (w *Window) Width() int {\n\treturn int(C.ANativeWindow_getWidth(w.cptr()))\n}",
"func (t *Text) Width(takable, taken float64) float64 {\n\tt.UpdateParagraph(takable)\n\tif t.Align != txt.Left {\n\t\treturn t.Paragraph.Width * t.Scl.X\n\t}\n\treturn t.Bounds().W() * t.Scl.X\n}",
"func (num *number) Width() int {\n\treturn num.size * 3 / 4\n}",
"func (self *TraitPixbuf) GetWidth() (return__ int) {\n\tvar __cgo__return__ C.int\n\t__cgo__return__ = C.gdk_pixbuf_get_width(self.CPointer)\n\treturn__ = int(__cgo__return__)\n\treturn\n}",
"func (mw *MagickWand) Width() uint {\n\treturn mw.GetImageWidth()\n}",
"func (p *Pagination) NumberOfPages() int {\n\treturn int(math.Ceil(float64(p.NumberOfItems()) / float64(p.ItemsPerPage())))\n}",
"func (b *Bound) Width() float64 {\n\treturn b.ne.X() - b.sw.X()\n}",
"func (s Spritesheet) Width() float32 {\n\treturn s.texture.Width() / float32(s.CellWidth)\n}",
"func (b *Bitmap) Width() int {\n\treturn int(b.handle.width)\n}",
"func Pwidth(wp, cw, defval float64) float64 {\n\tif wp == 0 {\n\t\treturn defval\n\t}\n\treturn (wp / 100) * cw\n}",
"func (p *Paginator) NumberOfPages() int {\n\treturn int(math.Ceil(float64(p.NumberOfItems()) / float64(p.ItemsPerPage())))\n}",
"func (o GoogleCloudRetailV2alphaImageResponseOutput) Width() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaImageResponse) int { return v.Width }).(pulumi.IntOutput)\n}",
"func (dim *Dimensions) Width() int64 {\n\treturn dim.width\n}",
"func (a *Asset) GetWidth() float64 {\n\tif a == nil || a.Width == nil {\n\t\treturn 0.0\n\t}\n\treturn *a.Width\n}",
"func (c RelativeConstraint) GetWidth() float32 {\n\treturn c.op(c.parent().GetWidth(), c.constant)\n}",
"func (o GoogleCloudRetailV2alphaImageOutput) Width() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaImage) *int { return v.Width }).(pulumi.IntPtrOutput)\n}",
"func (screen *GameScreen) Width() int {\n\treturn screen.screenSize.Width\n}",
"func (p *Pagination) NumPages() uint {\n\treturn maxuint(1, uint(math.Ceil(float64(p.total)/float64(p.PerPage))))\n}",
"func getWidth() int {\n\tstdoutFd := int(wrappedstreams.Stdout().Fd())\n\tstderrFd := int(wrappedstreams.Stderr().Fd())\n\n\tw := getWidthFd(stdoutFd)\n\tif w < 0 {\n\t\tw = getWidthFd(stderrFd)\n\t}\n\n\treturn w\n}",
"func (w *Window) Width() int {\n\treturn w.width\n}",
"func (s *CountMinSketch) Width() uint {\n\treturn s.w\n}",
"func (me *Image) Width() int {\n\treturn int(me.img.w)\n}",
"func (image *Image) Width() int {\n\treturn image.width\n}",
"func pagecount(size uint32) uint32 {\n\tnpage := size >> PageBits\n\tif size&(PageSize-1) != 0 {\n\t\tnpage++\n\t}\n\treturn npage\n}",
"func (spr *Sprite) Width() int32 {\n\n\treturn spr.width\n}",
"func (b *BoundingBox2D) width() float64 {\n\n\treturn b.upperCorner.X - b.lowerCorner.X\n}",
"func (c *Canvas) Width() int {\n\treturn c.maxCorner.X - c.minCorner.X + 1\n}",
"func (pb *Bar) Width() (width int) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\twidth = defaultBarWidth\n\t\t}\n\t}()\n\tpb.mu.RLock()\n\twidth = pb.width\n\tmaxWidth := pb.maxWidth\n\tpb.mu.RUnlock()\n\tif width <= 0 {\n\t\tvar err error\n\t\tif width, err = terminalWidth(); err != nil {\n\t\t\treturn defaultBarWidth\n\t\t}\n\t}\n\tif maxWidth > 0 && width > maxWidth {\n\t\twidth = maxWidth\n\t}\n\treturn\n}",
"func (t *Texture) GetWidth() uint16 {\n\treturn t.width\n}",
"func (o *ViewMetaPage) GetPageSize() int32 {\n\tif o == nil || o.PageSize == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.PageSize\n}",
"func (m *PrinterDefaults) GetPagesPerSheet()(*int32) {\n val, err := m.GetBackingStore().Get(\"pagesPerSheet\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}",
"func (t *Track) Width() int {\n\treturn t.width\n}",
"func (m *Page) GetPageNumber() int32 {\n\tif m != nil {\n\t\treturn m.PageNumber\n\t}\n\treturn 0\n}",
"func (p *Pagination) pages() int {\n\treturn int(math.Ceil(float64(p.Total) / float64(p.Limit)))\n}",
"func (p *PdfiumImplementation) FPDF_GetPageCount(request *requests.FPDF_GetPageCount) (*responses.FPDF_GetPageCount, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &responses.FPDF_GetPageCount{\n\t\tPageCount: int(C.FPDF_GetPageCount(documentHandle.handle)),\n\t}, nil\n}",
"func (o DashboardFreeFormLayoutElementOutput) Width() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DashboardFreeFormLayoutElement) string { return v.Width }).(pulumi.StringOutput)\n}",
"func (s *ImageSpec) TileWidth() int {\n\tret := int(C.ImageSpec_tile_width(s.ptr))\n\truntime.KeepAlive(s)\n\treturn ret\n}",
"func (f *Font) BytesWidth(b []byte) int {\n\tf.lock()\n\tdefer f.unlock()\n\treturn stringnwidth(f, \"\", b, nil)\n}",
"func (self *TraitPixbufAnimation) GetWidth() (return__ int) {\n\tvar __cgo__return__ C.int\n\t__cgo__return__ = C.gdk_pixbuf_animation_get_width(self.CPointer)\n\treturn__ = int(__cgo__return__)\n\treturn\n}",
"func (d *DecimalAlign) Width() string {\n\t// width is number of digits either side of value and\n\t// 0.5ch on either side to allow for overlap in the browser\n\treturn fmt.Sprintf(\"%dch\", d.lp+d.rp+1)\n}",
"func (v *Pixbuf) GetWidth() int {\n\treturn int(C.gdk_pixbuf_get_width(v.Native()))\n}",
"func (m Model) GetWidth() int {\n\treturn m.Width\n}",
"func (g Grid) PixelWidth() int32 {\n\treturn int32(g.width) * g.cellSize\n}",
"func (bm Blendmap) Width() float32 {\n\treturn bm.Map.width\n}",
"func (xs *Sheet) GetPrintFit() (wPages int, hPages int) {\n\txs.xb.lib.NewProc(\"xlSheetGetPrintFitW\").\n\t\tCall(xs.self, I_P(&wPages), I_P(&hPages))\n\treturn wPages, hPages\n}",
"func (r *ImageRef) GetPageHeight() int {\n\treturn vipsGetPageHeight(r.image)\n}",
"func (size *BitmapSize) Width() int16 {\n\treturn int16(size.handle.width)\n}",
"func (i *InputInlineQueryResultDocument) GetThumbnailWidth() (value int32) {\n\tif i == nil {\n\t\treturn\n\t}\n\treturn i.ThumbnailWidth\n}",
"func (b *BinP1D) XWidth() float64 {\n\treturn b.xrange.Max - b.xrange.Min\n}",
"func Width() (int, error) {\n\tws := &struct {\n\t\tRow uint16\n\t\tCol uint16\n\t\tXpixel uint16\n\t\tYpixel uint16\n\t}{}\n\n\tretCode, _, errno := syscall.Syscall(syscall.SYS_IOCTL,\n\t\tuintptr(syscall.Stdin),\n\t\tuintptr(syscall.TIOCGWINSZ),\n\t\tuintptr(unsafe.Pointer(ws)),\n\t)\n\n\tif int(retCode) == -1 {\n\t\treturn -1, errno\n\t}\n\n\treturn int(ws.Col), nil\n}",
"func pageCount(numPages int32, page int32) int32 {\n\tvar pageTurns int32\n\t// determine pageTurns from front\n\tfromFront := (page) / 2\n\t// page Turns from back\n\tfromBack := (numPages - page) / 2\n\tif fromFront < fromBack {\n\t\tpageTurns = fromFront\n\t} else {\n\t\tpageTurns = fromBack\n\t}\n\t// Special cases\n\t// if numPages is an even number and looking for the page before last page, only one turn is required\n\tif numPages%2 == 0 && page == numPages-1 && fromFront != 0 {\n\t\tpageTurns = 1\n\t}\n\treturn pageTurns\n}",
"func (t *Tab) NumPages() int {\n\treturn len(t.children)\n}",
"func (m *ModuleBase) Width(takable, taken float64) float64 {\n\treturn taken\n}",
"func (p *PageStats) GetTotalPages() int {\n\tif p == nil || p.TotalPages == nil {\n\t\treturn 0\n\t}\n\treturn *p.TotalPages\n}",
"func (g Grid) Width() int {\n\treturn g.width\n}",
"func (s *Surface) TextWidth(text string) float64 {\n\treturn s.Ctx.Call(\"measureText\", text).Get(\"width\").Float()\n}",
"func (f *Framebuffer) Width() int { return f.fb.Bounds().Max.X }",
"func (f String) Width() int {\n\treturn f.W\n}",
"func (e Event) GetResizeWidth() int {\n\treturn int(C.caca_get_event_resize_width(e.Ev))\n}",
"func (s Spec) Width() float64 {\n\treturn s.SpecWidth\n}",
"func (i *InputInlineQueryResultContact) GetThumbnailWidth() (value int32) {\n\tif i == nil {\n\t\treturn\n\t}\n\treturn i.ThumbnailWidth\n}",
"func (is ImageSurface) Width() int {\n\treturn is.width\n}",
"func GetPageSize() uint64 {\n\tpanic(\"not implemented\")\n}",
"func (n *node) width() int32 {\n\t// find two non-nil nodes\n\tfor i := 0; i < 8; i++ {\n\t\tif n.leafs[i] != nil && n.leafs[i].Center() != nil {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tif n.leafs[j] != nil && n.leafs[j].Center() != nil {\n\t\t\t\t\tp1, p2 := n.leafs[i].Center(), n.leafs[j].Center()\n\t\t\t\t\t// calculate non-zero difference in one of the dimensions (any)\n\t\t\t\t\txwidth := math.Abs(float64(p1.X - p2.X))\n\t\t\t\t\tif xwidth > 0 {\n\t\t\t\t\t\treturn int32(xwidth)\n\t\t\t\t\t}\n\t\t\t\t\tywidth := math.Abs(float64(p1.Y - p2.Y))\n\t\t\t\t\tif ywidth > 0 {\n\t\t\t\t\t\treturn int32(xwidth)\n\t\t\t\t\t}\n\t\t\t\t\tzwidth := math.Abs(float64(p1.Z - p2.Z))\n\t\t\t\t\tif zwidth > 0 {\n\t\t\t\t\t\treturn int32(xwidth)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 0\n}",
"func (o DashboardTableFieldOptionOutput) Width() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DashboardTableFieldOption) *string { return v.Width }).(pulumi.StringPtrOutput)\n}",
"func (s *SubsetFontObj) GlyphIndexToPdfWidth(glyphIndex uint) uint {\n\n\tnumberOfHMetrics := s.ttfp.NumberOfHMetrics()\n\tunitsPerEm := s.ttfp.UnitsPerEm()\n\tif glyphIndex >= numberOfHMetrics {\n\t\tglyphIndex = numberOfHMetrics - 1\n\t}\n\n\twidth := s.ttfp.Widths()[glyphIndex]\n\tif unitsPerEm == 1000 {\n\t\treturn width\n\t}\n\treturn width * 1000 / unitsPerEm\n}",
"func GetRenderbufferWidth(target GLEnum) int32 {\n\tvar params int32\n\tgl.GetRenderbufferParameteriv(uint32(target), gl.RENDERBUFFER_WIDTH, ¶ms)\n\treturn params\n}",
"func (b *Bound) GeoWidth(haversine ...bool) float64 {\n\tc := b.Center()\n\n\tA := &Point{b.sw[0], c[1]}\n\tB := &Point{b.ne[0], c[1]}\n\n\treturn A.GeoDistanceFrom(B, yesHaversine(haversine))\n}",
"func (s *DetectedProperties) SetWidth(v int64) *DetectedProperties {\n\ts.Width = &v\n\treturn s\n}",
"func (w *WidgetImplement) Width() int {\n\treturn w.w\n}",
"func (o *PaginationDataResponse) GetPage() float32 {\n\tif o == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\n\treturn o.Page\n}",
"func GxPhysicalWidth(value float64) *SimpleElement { return newSEFloat(\"gx:physicalWidth\", value) }",
"func GetApproximateTextWidth(text string, fontSize int) float64 {\n\tsize := 0.0\n\tfSize := float64(fontSize)\n\tif fontSize == 0 {\n\t\tfSize = 14.0 // default font size on ons site\n\t}\n\tspacing := SpaceBetweenCharacters * fSize // allow for some spacing between letters\n\tfor _, runeValue := range text {\n\t\truneSize, ok := characterWidths[runeValue]\n\t\tif ok {\n\t\t\truneSize = fSize * runeSize\n\t\t} else { // unknown character - assume it's quite wide\n\t\t\truneSize = fSize * 0.8\n\t\t}\n\t\tsize += runeSize + spacing\n\t}\n\treturn size\n}"
] | [
"0.68268335",
"0.6421836",
"0.5914204",
"0.5807707",
"0.55022496",
"0.544037",
"0.5413612",
"0.53919953",
"0.5316465",
"0.5278834",
"0.5216647",
"0.51815784",
"0.51778597",
"0.50841653",
"0.5076024",
"0.5070863",
"0.5038836",
"0.5031669",
"0.5025274",
"0.50153464",
"0.49955416",
"0.49929538",
"0.49810687",
"0.49641755",
"0.49497318",
"0.4916646",
"0.4909578",
"0.4897289",
"0.48743737",
"0.48597106",
"0.4851166",
"0.48397684",
"0.48308444",
"0.48202878",
"0.47982505",
"0.47927833",
"0.47789463",
"0.47749513",
"0.47721434",
"0.47560394",
"0.47538188",
"0.4749744",
"0.47460464",
"0.47422212",
"0.4727575",
"0.4714611",
"0.47061077",
"0.46849933",
"0.46794987",
"0.46599957",
"0.46471643",
"0.46466666",
"0.46453795",
"0.4634965",
"0.4616072",
"0.4608037",
"0.4605328",
"0.46029532",
"0.45858204",
"0.45777598",
"0.45772785",
"0.45739454",
"0.45677835",
"0.45655876",
"0.45558277",
"0.45542452",
"0.45371646",
"0.4534605",
"0.45041347",
"0.4492154",
"0.44896126",
"0.44755048",
"0.44753948",
"0.4472643",
"0.44678378",
"0.44599214",
"0.4453661",
"0.44479695",
"0.44322985",
"0.44062653",
"0.4400694",
"0.4399551",
"0.43994847",
"0.4395822",
"0.43717116",
"0.43697196",
"0.43660992",
"0.4352811",
"0.4331007",
"0.43259075",
"0.4319586",
"0.43177697",
"0.43133748",
"0.43107563",
"0.43066794",
"0.42889598",
"0.4287961",
"0.4282369",
"0.4280551",
"0.42668644"
] | 0.7393069 | 0 |
FPDF_GetPageHeight returns the height of a page. | func (p *PdfiumImplementation) FPDF_GetPageHeight(request *requests.FPDF_GetPageHeight) (*responses.FPDF_GetPageHeight, error) {
p.Lock()
defer p.Unlock()
pageHandle, err := p.loadPage(request.Page)
if err != nil {
return nil, err
}
height := C.FPDF_GetPageHeight(pageHandle.handle)
return &responses.FPDF_GetPageHeight{
Page: pageHandle.index,
Height: float64(height),
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (r *ImageRef) GetPageHeight() int {\n\treturn vipsGetPageHeight(r.image)\n}",
"func (r *ImageRef) PageHeight() int {\n\treturn vipsGetPageHeight(r.image)\n}",
"func (s *SimPDF) Height() float64 {\n\tif s.Page.IsLandscape {\n\t\treturn s.Page.Width\n\t}\n\treturn s.Page.Height\n}",
"func (s *PageLayout) Height() float64 {\n\treturn s.height\n}",
"func (rect *PdfRectangle) Height() float64 {\n\treturn math.Abs(rect.Ury - rect.Lly)\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetHeight(request *requests.FPDFBitmap_GetHeight) (*responses.FPDFBitmap_GetHeight, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theight := C.FPDFBitmap_GetHeight(bitmapHandle.handle)\n\treturn &responses.FPDFBitmap_GetHeight{\n\t\tHeight: int(height),\n\t}, nil\n}",
"func (p *Picture) GetHeight() int {\r\n\treturn p.pixelHeight\r\n}",
"func (image *JPGImage) GetHeight() float32 {\n\treturn float32(image.height)\n}",
"func (t *Link) GetHeight() (v int64) {\n\treturn *t.height.nonNegativeInteger\n\n}",
"func (info *ImageInfoType) Height() float64 {\n\treturn info.h / (info.scale * info.dpi / 72)\n}",
"func (win *Window) Height() int {\n\tsize := C.sfRenderWindow_getSize(win.win)\n\treturn int(size.y)\n}",
"func GetHeight() int {\n\treturn viper.GetInt(FlagHeight)\n}",
"func Height() int {\n\tws, err := getWinsize()\n\tif err != nil {\n\t\treturn -1\n\t}\n\treturn int(ws.Row)\n}",
"func (tex *Image) Height() int {\n\tsize := C.sfTexture_getSize(tex.tex)\n\treturn int(size.y)\n}",
"func (f *Face) Height() int {\n\treturn f.ypixels(int(f.handle.height))\n}",
"func (f *Font) Height() int { return int(C.TTF_FontHeight(f.f)) }",
"func (w *SVGWriter) Height() int {\n\treturn int(float64(w.Width()) * w.ViewBoxHeight() / w.ViewBoxWidth())\n}",
"func GetHeight(hostURL string, hostPort int) *bytes.Buffer {\n\treturn makeGetRequest(\"getheight\", hostURL, hostPort)\n}",
"func (o *FileInfoThumbnail) GetHeight() int32 {\n\tif o == nil || o.Height == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Height\n}",
"func (image *Image2D) GetHeight() int {\n\treturn image.height\n}",
"func (r *ImageRef) Height() int {\n\treturn int(r.image.Ysize)\n}",
"func (w *Window) Height() int {\n\treturn int(C.ANativeWindow_getHeight(w.cptr()))\n}",
"func (pc PieChart) GetHeight() int {\n\tif pc.Height == 0 {\n\t\treturn DefaultChartWidth\n\t}\n\treturn pc.Height\n}",
"func (a *Animation) GetHeight() float64 {\n\tif a == nil || a.Height == nil {\n\t\treturn 0.0\n\t}\n\treturn *a.Height\n}",
"func (o *WorkbookChart) GetHeight() AnyOfnumberstringstring {\n\tif o == nil || o.Height == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret\n\t}\n\treturn *o.Height\n}",
"func (rc Rectangle) Height() int {\n\treturn rc.Bottom - rc.Top\n}",
"func (o GoogleCloudRetailV2alphaImageOutput) Height() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaImage) *int { return v.Height }).(pulumi.IntPtrOutput)\n}",
"func (g *Grid) GetHeight() int {\n\treturn g.Height\n}",
"func (o *TileBounds) GetHeight() int32 {\n\tif o == nil || o.Height == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Height\n}",
"func (o DashboardFreeFormLayoutElementOutput) Height() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DashboardFreeFormLayoutElement) string { return v.Height }).(pulumi.StringOutput)\n}",
"func (num *number) Height() int {\n\tvar res = num.size * 4 / 5\n\n\tif res%2 == 0 {\n\t\treturn res + 1\n\t}\n\n\treturn res\n}",
"func getHeight() int {\n\tfor {\n\t\theight := go50.GetInt(\"Height: \")\n\t\tif height > 0 && height < 24 {\n\t\t\treturn height\n\t\t}\n\t}\n}",
"func (env *Environment) getHeight(latestHeight int64, heightPtr *int64) (int64, error) {\n\tif heightPtr != nil {\n\t\theight := *heightPtr\n\t\tif height <= 0 {\n\t\t\treturn 0, fmt.Errorf(\"%w (requested height: %d)\", coretypes.ErrZeroOrNegativeHeight, height)\n\t\t}\n\t\tif height > latestHeight {\n\t\t\treturn 0, fmt.Errorf(\"%w (requested height: %d, blockchain height: %d)\",\n\t\t\t\tcoretypes.ErrHeightExceedsChainHead, height, latestHeight)\n\t\t}\n\t\tbase := env.BlockStore.Base()\n\t\tif height < base {\n\t\t\treturn 0, fmt.Errorf(\"%w (requested height: %d, base height: %d)\", coretypes.ErrHeightNotAvailable, height, base)\n\t\t}\n\t\treturn height, nil\n\t}\n\treturn latestHeight, nil\n}",
"func Height() uint64 {\n\n\tglobalData.RLock()\n\tdefer globalData.RUnlock()\n\n\treturn globalData.height\n}",
"func (b *BaseElement) GetHeight() int32 {\n\treturn b.h\n}",
"func (r Rectangle) Height() float64 {\n\treturn r.Max.Y - r.Min.Y\n}",
"func (f *Framebuffer) Height() int { return f.fb.Bounds().Max.Y }",
"func (o DashboardSectionStylePtrOutput) Height() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DashboardSectionStyle) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Height\n\t}).(pulumi.StringPtrOutput)\n}",
"func (commit *Commit) GetHeight() int64 {\n\treturn commit.Height\n}",
"func (commit *Commit) GetHeight() int64 {\n\treturn commit.Height\n}",
"func GetHeight(ctx Context) (int64, bool) {\n\tval, ok := ctx.Value(contextKeyHeight).(int64)\n\treturn val, ok\n}",
"func (self *TraitPixbuf) GetHeight() (return__ int) {\n\tvar __cgo__return__ C.int\n\t__cgo__return__ = C.gdk_pixbuf_get_height(self.CPointer)\n\treturn__ = int(__cgo__return__)\n\treturn\n}",
"func (o GoogleCloudRetailV2alphaImageResponseOutput) Height() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaImageResponse) int { return v.Height }).(pulumi.IntOutput)\n}",
"func (b *BoundingBox2D) height() float64 {\n\n\treturn b.upperCorner.Y - b.lowerCorner.Y\n}",
"func (bp RPCBlockProvider) GetBlockHeight() int {\r\n\tvar block int\r\n\terr := bp.Client.Call(\"BlockPropagationHandler.GetBlockHeight\", 0, &block)\r\n\tif err != nil {\r\n\t\tlog.Print(err)\r\n\t}\r\n\treturn block\r\n}",
"func (pgb *ChainDB) GetHeight() (int64, error) {\n\tctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)\n\tdefer cancel()\n\theight, _, _, err := RetrieveBestBlockHeight(ctx, pgb.db)\n\t// If the blocks table is empty, set height to -1.\n\tbb := int64(height)\n\tif err == sql.ErrNoRows {\n\t\tbb = -1\n\t}\n\treturn bb, pgb.replaceCancelError(err)\n}",
"func (c *DataCache) GetHeight() uint32 {\n\tc.mtx.RLock()\n\tdefer c.mtx.RUnlock()\n\treturn c.height\n}",
"func (b *Bound) Height() float64 {\n\treturn b.ne.Y() - b.sw.Y()\n}",
"func (s *ImageSpec) Height() int {\n\tret := int(C.ImageSpec_height(s.ptr))\n\truntime.KeepAlive(s)\n\treturn ret\n}",
"func (image *Image) Height() int {\n\treturn image.height\n}",
"func (lc *FilChain) GetHeight(ctx context.Context) (uint64, error) {\n\th, err := lc.api.ChainHead(ctx)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"get head from lotus node: %s\", err)\n\t}\n\treturn uint64(h.Height()), nil\n}",
"func (w *Window) Height() int {\n\treturn w.height\n}",
"func (p *Page) Size() int {\n\treturn p.LineSize() * p.UnreadLines()\n}",
"func (v *Pixbuf) GetHeight() int {\n\treturn int(C.gdk_pixbuf_get_height(v.Native()))\n}",
"func (screen *GameScreen) Height() int {\n\treturn screen.screenSize.Height\n}",
"func (t *Texture) GetHeight() uint16 {\n\treturn t.height\n}",
"func (pi *PageInfo) PageCount() int {\n\tif pi.StartPage != 0 && pi.EndPage != 0 {\n\t\tcount := pi.EndPage - pi.StartPage\n\t\tif count > 0 {\n\t\t\treturn count\n\t\t}\n\t}\n\treturn 0\n}",
"func (size *BitmapSize) Height() int16 {\n\treturn int16(size.handle.height)\n}",
"func (p *PdfiumImplementation) FPDF_GetPageCount(request *requests.FPDF_GetPageCount) (*responses.FPDF_GetPageCount, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &responses.FPDF_GetPageCount{\n\t\tPageCount: int(C.FPDF_GetPageCount(documentHandle.handle)),\n\t}, nil\n}",
"func (o DashboardLegendOptionsPtrOutput) Height() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DashboardLegendOptions) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Height\n\t}).(pulumi.StringPtrOutput)\n}",
"func (h *HeightCache) GetHeight() (height uint64) {\n\th.RLock()\n\theight = h.height\n\th.RUnlock()\n\treturn\n}",
"func (o *ViewMetaPage) GetPageSize() int32 {\n\tif o == nil || o.PageSize == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.PageSize\n}",
"func (c *Canvas) fontHeight(font *Font) (height int, err error) {\n\terr = c.withFontAndTextColor(font, 0, func() error {\n\t\tvar size win.SIZE\n\t\tif !win.GetTextExtentPoint32(c.hdc, gM, 2, &size) {\n\t\t\treturn newError(\"GetTextExtentPoint32 failed\")\n\t\t}\n\n\t\theight = int(size.CY)\n\t\tif height == 0 {\n\t\t\treturn newError(\"invalid font height\")\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn\n}",
"func (o DashboardSectionStyleOutput) Height() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DashboardSectionStyle) *string { return v.Height }).(pulumi.StringPtrOutput)\n}",
"func (ws *workingSet) Height() (uint64, error) {\n\treturn ws.height, nil\n}",
"func (me *Image) Height() int {\n\treturn int(me.img.h)\n}",
"func (self *TraitPixbufAnimation) GetHeight() (return__ int) {\n\tvar __cgo__return__ C.int\n\t__cgo__return__ = C.gdk_pixbuf_animation_get_height(self.CPointer)\n\treturn__ = int(__cgo__return__)\n\treturn\n}",
"func GetRenderbufferHeight(target GLEnum) int32 {\n\tvar params int32\n\tgl.GetRenderbufferParameteriv(uint32(target), gl.RENDERBUFFER_HEIGHT, ¶ms)\n\treturn params\n}",
"func (a *Asset) GetHeight() float64 {\n\tif a == nil || a.Height == nil {\n\t\treturn 0.0\n\t}\n\treturn *a.Height\n}",
"func getHeight(latestHeight int64, heightPtr *int64) (int64, error) {\n\tif heightPtr != nil {\n\t\theight := *heightPtr\n\t\tif height <= 0 {\n\t\t\treturn 0, fmt.Errorf(\"height must be greater than 0, but got %d\", height)\n\t\t}\n\t\tif height > latestHeight {\n\t\t\treturn 0, fmt.Errorf(\"height %d must be less than or equal to the current blockchain height %d\",\n\t\t\t\theight, latestHeight)\n\t\t}\n\t\tbase := env.BlockStore.Base()\n\t\tif height < base {\n\t\t\treturn 0, fmt.Errorf(\"height %d is not available, lowest height is %d\",\n\t\t\t\theight, base)\n\t\t}\n\t\treturn height, nil\n\t}\n\treturn latestHeight, nil\n}",
"func (r *renderer) Height() int {\n\t// TODO(knz): Support multi-line items, e.g. identifiers\n\t// containing a newline character.\n\treturn 1\n}",
"func (t Texture3D) GetHeight() int32 {\n\treturn t.height\n}",
"func (o *PaginationDataResponse) GetPage() float32 {\n\tif o == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\n\treturn o.Page\n}",
"func (c *Canvas) Height() int {\n\treturn c.maxCorner.Y - c.minCorner.Y + 1\n}",
"func (o *os) GetVirtualKeyboardHeight() gdnative.Int {\n\to.ensureSingleton()\n\t//log.Println(\"Calling _OS.GetVirtualKeyboardHeight()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"_OS\", \"get_virtual_keyboard_height\")\n\n\t// Call the parent method.\n\t// int\n\tretPtr := gdnative.NewEmptyInt()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewIntFromPointer(retPtr)\n\treturn ret\n}",
"func (mw *MagickWand) Height() uint {\n\treturn mw.GetImageHeight()\n}",
"func (bm Blendmap) Height() float32 {\n\treturn bm.Map.height\n}",
"func (u *Upstream) GetHeight() uint64 {\n\treturn u.blockHeight\n}",
"func (g Grid) Height() int {\n\treturn g.height\n}",
"func (r *ImageRef) SetPageHeight(height int) error {\n\tout, err := vipsCopyImage(r.image)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvipsSetPageHeight(out, height)\n\n\tr.setImage(out)\n\treturn nil\n}",
"func (t *Text) Height(takable, taken float64) float64 {\n\treturn t.Bounds().H() * t.Scl.Y\n}",
"func GetPageSize() uint64 {\n\tpanic(\"not implemented\")\n}",
"func (lc *LotusChain) GetHeight(ctx context.Context) (uint64, error) {\n\th, err := lc.api.ChainHead(ctx)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"get head from lotus node: %s\", err)\n\t}\n\treturn uint64(h.Height()), nil\n}",
"func (o DashboardLegendOptionsOutput) Height() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DashboardLegendOptions) *string { return v.Height }).(pulumi.StringPtrOutput)\n}",
"func (m *Model) GetHeight() int {\n\treturn m.height\n}",
"func (commit *Commit) Height() int64 {\n\tif len(commit.Precommits) == 0 {\n\t\treturn 0\n\t}\n\treturn commit.FirstPrecommit().Vote.Height\n}",
"func (t *Tree) Height() int {\n\tif t == nil || t.Root == nil {\n\t\treturn 0\n\t}\n\treturn t.Root.height()\n}",
"func (g *Graph) Height() uint64 {\n\tg.RLock()\n\theight := g.height\n\tg.RUnlock()\n\n\treturn height\n}",
"func (lc *LedgerCommitter) LedgerHeight() (uint64, error) {\n\tinfo, err := lc.GetBlockchainInfo()\n\tif err != nil {\n\t\tlogger.Errorf(\"Cannot get blockchain info, %s\", info)\n\t\treturn 0, err\n\t}\n\n\treturn info.Height, nil\n}",
"func (p *PdfiumImplementation) FPDF_GetPageWidth(request *requests.FPDF_GetPageWidth) (*responses.FPDF_GetPageWidth, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twidth := C.FPDF_GetPageWidth(pageHandle.handle)\n\n\treturn &responses.FPDF_GetPageWidth{\n\t\tPage: pageHandle.index,\n\t\tWidth: float64(width),\n\t}, nil\n}",
"func (is ImageSurface) Height() int {\n\treturn is.height\n}",
"func (c *Config) MaxHeight() int {\n\tc.Mutex.RLock()\n\tdefer c.Mutex.RUnlock()\n\treturn c.Raw.MaxHeight\n}",
"func (dim *Dimensions) Height() int64 {\n\treturn dim.height\n}",
"func GetProcessedHeight(clientStore sdk.KVStore, height exported.Height) (exported.Height, bool) {\n\tkey := ProcessedHeightKey(height)\n\tbz := clientStore.Get(key)\n\tif bz == nil {\n\t\treturn nil, false\n\t}\n\tprocessedHeight, err := clienttypes.ParseHeight(string(bz))\n\tif err != nil {\n\t\treturn nil, false\n\t}\n\treturn processedHeight, true\n}",
"func (spr *Sprite) Height() int32 {\n\n\treturn spr.height\n}",
"func (tree *BinaryTree) Height() int {\n\treturn len(tree.LevelOrderTraversel())\n}",
"func (rt *recvTxOut) Height() int32 {\n\theight := int32(-1)\n\tif rt.block != nil {\n\t\theight = rt.block.Height\n\t}\n\treturn height\n}",
"func (t *BinaryTree) Height() (int, error) {\n\tif t.root == nil {\n\t\treturn 0, errors.New(\"Tree is empty\")\n\t}\n\n\tvar maxHeight func(bnode *bnode) int\n\n\tmaxHeight = func(bnode *bnode) int {\n\t\tif bnode == nil {\n\t\t\treturn 0\n\t\t}\n\t\tlHeight := maxHeight(bnode.left)\n\t\trHeight := maxHeight(bnode.right)\n\n\t\tif lHeight > rHeight {\n\t\t\treturn lHeight + 1\n\t\t}\n\t\treturn rHeight + 1\n\t}\n\tresult := maxHeight(t.root)\n\treturn result, nil\n}",
"func (s *TXPoolServer) getHeight() uint32 {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\treturn s.height\n}",
"func (s *SkipList) getHeight() uint32 {\n\t// Height can be modified concurrently, so we need to load it atomically.\n\treturn atomic.LoadUint32(&s.height)\n}"
] | [
"0.80015534",
"0.7671814",
"0.72434413",
"0.69377315",
"0.65516835",
"0.5921592",
"0.5857785",
"0.585174",
"0.5675027",
"0.567384",
"0.566665",
"0.5640857",
"0.5638242",
"0.5615698",
"0.560533",
"0.55968744",
"0.55466133",
"0.5519078",
"0.54490036",
"0.54160684",
"0.5409262",
"0.53963095",
"0.53852046",
"0.53798014",
"0.5362457",
"0.5319482",
"0.5314868",
"0.53134954",
"0.53083605",
"0.5299612",
"0.5296634",
"0.5283556",
"0.5281888",
"0.5280614",
"0.52701455",
"0.5252712",
"0.52468306",
"0.5230397",
"0.52168846",
"0.52168846",
"0.52113837",
"0.5193416",
"0.5183174",
"0.5172137",
"0.51639104",
"0.5150825",
"0.514325",
"0.51416755",
"0.5134977",
"0.5131569",
"0.5126115",
"0.50970846",
"0.5095247",
"0.5094767",
"0.5089492",
"0.50826246",
"0.50580573",
"0.50562674",
"0.50474566",
"0.5043296",
"0.5031367",
"0.50300604",
"0.5011412",
"0.50089496",
"0.50077224",
"0.50010604",
"0.5000151",
"0.49981743",
"0.49966535",
"0.49693164",
"0.4968906",
"0.4967816",
"0.49240965",
"0.49220327",
"0.49179003",
"0.49133942",
"0.49051762",
"0.48894104",
"0.48801497",
"0.48642248",
"0.48620117",
"0.48500407",
"0.48487502",
"0.48441398",
"0.4838231",
"0.4835912",
"0.48351145",
"0.48305628",
"0.4820716",
"0.4809885",
"0.48069513",
"0.48035958",
"0.47936568",
"0.47886187",
"0.47857708",
"0.47810218",
"0.4773436",
"0.47723946",
"0.47597164",
"0.47513488"
] | 0.77575934 | 1 |
FPDF_GetPageSizeByIndex returns the size of a page by the page index. | func (p *PdfiumImplementation) FPDF_GetPageSizeByIndex(request *requests.FPDF_GetPageSizeByIndex) (*responses.FPDF_GetPageSizeByIndex, error) {
p.Lock()
defer p.Unlock()
documentHandle, err := p.getDocumentHandle(request.Document)
if err != nil {
return nil, err
}
width := C.double(0)
height := C.double(0)
result := C.FPDF_GetPageSizeByIndex(documentHandle.handle, C.int(request.Index), &width, &height)
if int(result) == 0 {
return nil, errors.New("could not load page size by index")
}
return &responses.FPDF_GetPageSizeByIndex{
Page: request.Index,
Width: float64(width),
Height: float64(height),
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func GetPageSize() uint64 {\n\tpanic(\"not implemented\")\n}",
"func Getpagesize() int",
"func (o *ViewMetaPage) GetPageSize() int32 {\n\tif o == nil || o.PageSize == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.PageSize\n}",
"func (g *NgGrid) GetPageSize() int64 {\n\tif g.PageSize <= 0 {\n\t\tg.PageSize = 10\n\t}\n\treturn g.PageSize\n}",
"func TestGetPageSize(t *testing.T) {\n\tcases := []struct {\n\t\toffset, total, limit, expected int64\n\t\tname string\n\t}{\n\t\t{1, 0, 50, 0, \"no results\"},\n\t\t{1, 1, 50, 1, \"first partial page\"},\n\t\t{1, 50, 50, 50, \"first full page\"},\n\t\t{2, 100, 50, 50, \"second page full\"},\n\t\t{2, 51, 50, 1, \"last partial page\"},\n\t}\n\tfor _, tt := range cases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tactual := getPageSize(tt.offset, tt.total, tt.limit)\n\t\t\tassert.Equal(t, tt.expected, actual, \"actual didn't match expected\")\n\t\t})\n\t}\n}",
"func (o *Ga4ghSearchRnaQuantificationsRequest) GetPageSize() int32 {\n\tif o == nil || o.PageSize == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.PageSize\n}",
"func (o *PaginationDataResponse) GetPageSize() float32 {\n\tif o == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\n\treturn o.PageSize\n}",
"func (o *ExtensionMonitoringConfigurationsList) GetPageSize() int32 {\n\tif o == nil || o.PageSize == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.PageSize\n}",
"func ExamplePdfMaroto_GetPageSize() {\n\tm := pdf.NewMaroto(consts.Portrait, consts.A4)\n\n\t// Get\n\twidth, height := m.GetPageSize()\n\tfmt.Println(width)\n\tfmt.Println(height)\n\n\t// Do more things and save...\n}",
"func getPageSize(args []string) (uint, error) {\n\tpageSizeArgIndex := core.IndexOf(args, \"-x\")\n\tif pageSizeArgIndex > 0 {\n\t\tif pageSizeArgIndex+1 >= len(args) {\n\t\t\treturn 0, errors.New(\"Expected value after '-x'\")\n\t\t}\n\t\tpageSizeStr := args[pageSizeArgIndex+1]\n\n\t\tpageSize, err := strconv.ParseUint(pageSizeStr, 10, 32)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tif pageSize < 50 {\n\t\t\tpageSize = 50\n\t\t}\n\t\treturn uint(pageSize), nil\n\t}\n\n\treturn core.DefaultPageSize, nil\n}",
"func (current OffsetPageBase) getPageSize() (int, error) {\n\tvar pageSize int\n\n\tswitch pb := current.Body.(type) {\n\tcase map[string]interface{}:\n\t\tfor k, v := range pb {\n\t\t\t// ignore xxx_links\n\t\t\tif !strings.HasSuffix(k, \"links\") {\n\t\t\t\t// check the field's type. we only want []interface{} (which is really []map[string]interface{})\n\t\t\t\tswitch vt := v.(type) {\n\t\t\t\tcase []interface{}:\n\t\t\t\t\tpageSize = len(vt)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase []interface{}:\n\t\tpageSize = len(pb)\n\tdefault:\n\t\terr := golangsdk.ErrUnexpectedType{}\n\t\terr.Expected = \"map[string]interface{}/[]interface{}\"\n\t\terr.Actual = fmt.Sprintf(\"%T\", pb)\n\t\treturn 0, err\n\t}\n\n\treturn pageSize, nil\n}",
"func (it *TopicIterator) PageSize() int {\n\treturn int(it.pageSize)\n}",
"func (it *StringIterator) PageSize() int {\n\treturn int(it.pageSize)\n}",
"func (m *PrinterDefaults) GetPagesPerSheet()(*int32) {\n val, err := m.GetBackingStore().Get(\"pagesPerSheet\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}",
"func (indexer Indexer) GetIndexSize() int {\n\tindex := *indexer.GetIndex()\n\tsize := 8 * len(index)\n\tfor _, postings := range index {\n\t\tsize += 16 * len(postings)\n\t}\n\tkb := int(math.Pow(2, 10))\n\tsize = int(size / kb)\n\treturn size\n}",
"func (p *PdfiumImplementation) FPDF_GetPageCount(request *requests.FPDF_GetPageCount) (*responses.FPDF_GetPageCount, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &responses.FPDF_GetPageCount{\n\t\tPageCount: int(C.FPDF_GetPageCount(documentHandle.handle)),\n\t}, nil\n}",
"func (p *Pager) LastPageIndex() int {\n\tif p.totalCount < 1 || p.limit == 0 {\n\t\treturn 0\n\t}\n\n\t// calculate the last page index\n\tlastPageIndex := (p.totalCount - 1) / p.limit\n\treturn lastPageIndex\n}",
"func (f *factory) GetPage(index int64) (MappedPage, bool) {\n\tf.mutex.RLock()\n\tdefer f.mutex.RUnlock()\n\n\tpage, ok := f.pages[index]\n\treturn page, ok\n}",
"func OffsetToPage(offset, size int) int {\n\treturn (offset / size) + 1\n}",
"func (db *DB) getPageSize() (int, error) {\n\tvar (\n\t\tmeta0CanRead, meta1CanRead bool\n\t)\n\n\t// Read the first meta page to determine the page size.\n\tif pgSize, canRead, err := db.getPageSizeFromFirstMeta(); err != nil {\n\t\t// We cannot read the page size from page 0, but can read page 0.\n\t\tmeta0CanRead = canRead\n\t} else {\n\t\treturn pgSize, nil\n\t}\n\n\t// Read the second meta page to determine the page size.\n\tif pgSize, canRead, err := db.getPageSizeFromSecondMeta(); err != nil {\n\t\t// We cannot read the page size from page 1, but can read page 1.\n\t\tmeta1CanRead = canRead\n\t} else {\n\t\treturn pgSize, nil\n\t}\n\n\t// If we can't read the page size from both pages, but can read\n\t// either page, then we assume it's the same as the OS or the one\n\t// given, since that's how the page size was chosen in the first place.\n\t//\n\t// If both pages are invalid, and (this OS uses a different page size\n\t// from what the database was created with or the given page size is\n\t// different from what the database was created with), then we are out\n\t// of luck and cannot access the database.\n\tif meta0CanRead || meta1CanRead {\n\t\treturn db.pageSize, nil\n\t}\n\n\treturn 0, ErrInvalid\n}",
"func (g *NgGrid) GetPageNumber() int64 {\n\tif g.PageNumber == 0 {\n\t\tg.PageNumber = 1\n\t}\n\treturn g.PageNumber\n}",
"func (p *Paginator) NumberOfPages() int {\n\treturn int(math.Ceil(float64(p.NumberOfItems()) / float64(p.ItemsPerPage())))\n}",
"func (r *Reader) PageSize(numOfRecs int) *Reader {\n\tif r.XMLName.Local == readByQueryXMLName.Local {\n\t\tr.MaxRecs = numOfRecs\n\t}\n\treturn r\n}",
"func TestPageSize(t *testing.T) {\n\tvar tests = []struct {\n\t\tliteral string\n\t\tvalue PageSize\n\t}{\n\t\t{\"A4\", A4},\n\t\t{\"letter\", Letter},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(mkname(test.literal), func(t *testing.T) {\n\t\t\tvar p PageSize\n\t\t\terr := p.Set(test.literal)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"expected err == nil, got %q\", err)\n\t\t\t}\n\t\t\tif p != test.value {\n\t\t\t\tt.Errorf(\"got %q, want %q\", p, test.value)\n\t\t\t}\n\t\t})\n\t}\n}",
"func (pi *PageInfo) PageCount() int {\n\tif pi.StartPage != 0 && pi.EndPage != 0 {\n\t\tcount := pi.EndPage - pi.StartPage\n\t\tif count > 0 {\n\t\t\treturn count\n\t\t}\n\t}\n\treturn 0\n}",
"func (pb *PageBuffer) PageNo() int {\n return pb.page_no\n}",
"func (p *Pagination) NumPages() uint {\n\treturn maxuint(1, uint(math.Ceil(float64(p.total)/float64(p.PerPage))))\n}",
"func (p *Pagination) NumberOfPages() int {\n\treturn int(math.Ceil(float64(p.NumberOfItems()) / float64(p.ItemsPerPage())))\n}",
"func (p *Page) Size() int {\n\treturn p.LineSize() * p.UnreadLines()\n}",
"func (db *DB) getPageSizeFromFirstMeta() (int, bool, error) {\n\tvar buf [0x1000]byte\n\tvar metaCanRead bool\n\tif bw, err := db.file.ReadAt(buf[:], 0); err == nil && bw == len(buf) {\n\t\tmetaCanRead = true\n\t\tif m := db.pageInBuffer(buf[:], 0).meta(); m.validate() == nil {\n\t\t\treturn int(m.pageSize), metaCanRead, nil\n\t\t}\n\t}\n\treturn 0, metaCanRead, ErrInvalid\n}",
"func (p *PdfiumImplementation) FPDFText_GetFontSize(request *requests.FPDFText_GetFontSize) (*responses.FPDFText_GetFontSize, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\ttextPageHandle, err := p.getTextPageHandle(request.TextPage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfontSize := C.FPDFText_GetFontSize(textPageHandle.handle, C.int(request.Index))\n\treturn &responses.FPDFText_GetFontSize{\n\t\tIndex: request.Index,\n\t\tFontSize: float64(fontSize),\n\t}, nil\n}",
"func (p *PdfiumImplementation) FPDF_GetPageWidth(request *requests.FPDF_GetPageWidth) (*responses.FPDF_GetPageWidth, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twidth := C.FPDF_GetPageWidth(pageHandle.handle)\n\n\treturn &responses.FPDF_GetPageWidth{\n\t\tPage: pageHandle.index,\n\t\tWidth: float64(width),\n\t}, nil\n}",
"func (ps *PrimeStore) GetByIndex(nth uint64) (n uint64) {\n\tdefer Tracer(NewTrace(\"GetByIndex\"))\n\n\tn = 0\n\tif nth < ps.base || nth >= (ps.base+ps.count) {\n\t\tlog.Print(\"out of range.\", nth, \" \", ps)\n\t\treturn\n\t}\n\n\tn = ps.index[nth-ps.base]\n\treturn\n}",
"func (o OffsetPaginator) Page() uint {\n\tif o.Count == 0 {\n\t\treturn 1\n\t}\n\n\treturn uint(math.Ceil(float64(o.Offset)/float64(o.Limit))) + 1\n}",
"func (p *Pagination) Page(total int) (from int, to int) {\n\tif p.Num == 0 {\n\t\tp.Num = 1\n\t}\n\tif p.Size == 0 {\n\t\tp.Size = DefaultSize\n\t}\n\n\tif total == 0 || total < p.Size*(p.Num-1) {\n\t\treturn\n\t}\n\tif total <= p.Size {\n\t\treturn 1, total\n\t}\n\tfrom = (p.Num-1)*p.Size + 1\n\tif (total - from + 1) < p.Size {\n\t\treturn from, total\n\t}\n\treturn from, from + p.Size - 1\n}",
"func (o *ViewMetaPage) GetPageSizeOk() (*int32, bool) {\n\tif o == nil || o.PageSize == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PageSize, true\n}",
"func (t *Tab) NumPages() int {\n\treturn len(t.children)\n}",
"func (p *Pagination) pages() int {\n\treturn int(math.Ceil(float64(p.Total) / float64(p.Limit)))\n}",
"func (o OffsetPaginator) PageCount() uint {\n\tif o.Count == 0 {\n\t\treturn 1\n\t}\n\n\treturn uint(math.Ceil(float64(o.Count) / float64(o.Limit)))\n}",
"func (p *PageStats) GetTotalPages() int {\n\tif p == nil || p.TotalPages == nil {\n\t\treturn 0\n\t}\n\treturn *p.TotalPages\n}",
"func SetIndexPageSize(dbo Database, pageSize int) error {\n\tdb := dbo.(*database)\n\tsql := db.getRawDB()\n\t_, err := sql.Exec(`insert into fts(fts, rank) values(\"pgsz\", ?)`, pageSize)\n\treturn err\n}",
"func (xs *Sheet) GetVerPageBreak(index int) int {\n\ttmp, _, _ := xs.xb.lib.NewProc(\"xlSheetGetVerPageBreakW\").\n\t\tCall(xs.self, I(index))\n\treturn int(tmp)\n}",
"func (o *ExtensionMonitoringConfigurationsList) SetPageSize(v int32) {\n\to.PageSize = &v\n}",
"func (s *SubsetFontObj) GlyphIndexToPdfWidth(glyphIndex uint) uint {\n\n\tnumberOfHMetrics := s.ttfp.NumberOfHMetrics()\n\tunitsPerEm := s.ttfp.UnitsPerEm()\n\tif glyphIndex >= numberOfHMetrics {\n\t\tglyphIndex = numberOfHMetrics - 1\n\t}\n\n\twidth := s.ttfp.Widths()[glyphIndex]\n\tif unitsPerEm == 1000 {\n\t\treturn width\n\t}\n\treturn width * 1000 / unitsPerEm\n}",
"func (o *PaginationDataResponse) GetPageSizeOk() (*float32, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.PageSize, true\n}",
"func (r *ImageRef) GetPageHeight() int {\n\treturn vipsGetPageHeight(r.image)\n}",
"func (m *PrinterDefaults) GetFitPdfToPage()(*bool) {\n val, err := m.GetBackingStore().Get(\"fitPdfToPage\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}",
"func (this Pager) GetPageRange(pageIndex int) (result Int2) {\r\n\tresult.X = pageIndex * this.PageSize\r\n\tresult.Y = result.X + this.PageSize\r\n\treturn\r\n}",
"func (p *Pagination) NumberOfItems() int {\n\treturn p.numberOfItems\n}",
"func (p *PdfiumImplementation) FPDF_GetPageHeight(request *requests.FPDF_GetPageHeight) (*responses.FPDF_GetPageHeight, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theight := C.FPDF_GetPageHeight(pageHandle.handle)\n\n\treturn &responses.FPDF_GetPageHeight{\n\t\tPage: pageHandle.index,\n\t\tHeight: float64(height),\n\t}, nil\n}",
"func (o *Ga4ghSearchRnaQuantificationsRequest) GetPageSizeOk() (int32, bool) {\n\tif o == nil || o.PageSize == nil {\n\t\tvar ret int32\n\t\treturn ret, false\n\t}\n\treturn *o.PageSize, true\n}",
"func (e *stackScriptPaginated) pageNumber() int {\n\treturn e.Page\n}",
"func (o *ExtensionMonitoringConfigurationsList) GetPageSizeOk() (*int32, bool) {\n\tif o == nil || o.PageSize == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PageSize, true\n}",
"func (r *ImageRef) Pages() int {\n\t// libvips uses the same attribute (n_pages) to represent the number of pyramid layers in JP2K\n\t// as we interpret the attribute as frames and JP2K does not support animation we override this with 1\n\tif r.format == ImageTypeJP2K {\n\t\treturn 1\n\t}\n\n\treturn vipsGetImageNPages(r.image)\n}",
"func (p *Paginator) Page() int {\n\tif p.page != 0 {\n\t\treturn p.page\n\t}\n\tif p.Request.Form == nil {\n\t\tp.Request.ParseForm()\n\t}\n\tp.page, _ = strconv.Atoi(p.Request.Form.Get(\"p\"))\n\tif p.page > p.PageNums() {\n\t\tp.page = p.PageNums()\n\t}\n\tif p.page <= 0 {\n\t\tp.page = 1\n\t}\n\treturn p.page\n}",
"func MaxPageSize(m int) func(*ParquetWriter) error {\n\treturn func(p *ParquetWriter) error {\n\t\tp.max = m\n\t\treturn nil\n\t}\n}",
"func (p *Paginator) NumberOfItems() int {\n\treturn p.numberOfItems\n}",
"func pagecount(size uint32) uint32 {\n\tnpage := size >> PageBits\n\tif size&(PageSize-1) != 0 {\n\t\tnpage++\n\t}\n\treturn npage\n}",
"func (_Casper *CasperSession) Index() (*big.Int, error) {\n\treturn _Casper.Contract.Index(&_Casper.CallOpts)\n}",
"func (g *NgGrid) Limit() int64 {\n\treturn g.GetPageSize()\n}",
"func (c *ProjectsLocationsProcessesRunsListCall) PageSize(pageSize int64) *ProjectsLocationsProcessesRunsListCall {\n\tc.urlParams_.Set(\"pageSize\", fmt.Sprint(pageSize))\n\treturn c\n}",
"func (o *ViewMetaPage) SetPageSize(v int32) {\n\to.PageSize = &v\n}",
"func (p *Pagination) ItemsPerPage() int {\n\treturn p.itemsPerPage\n}",
"func (r *ImageRef) PageHeight() int {\n\treturn vipsGetPageHeight(r.image)\n}",
"func (o *PaginationDataResponse) SetPageSize(v float32) {\n\to.PageSize = v\n}",
"func pageAddress(pointer int, pagesize int) int {\n\tpageAddress := pointer % pagesize\n\tif pageAddress < 0 {\n\t\treturn pagesize + pageAddress\n\t}\n\treturn pageAddress\n}",
"func (p *Pagination) TotalPages() int {\n\tif p.Total == 0 {\n\t\treturn 1\n\t}\n\tif p.Total%p.PageSize == 0 {\n\t\treturn p.Total / p.PageSize\n\t}\n\treturn p.Total/p.PageSize + 1\n}",
"func optimalPageSize(opts optimalPageSizeOpts) int {\n\tpageSize := 15\n\tif opts.terminalHeight != 0 {\n\t\tpageSize = opts.terminalHeight\n\t} else if _, height, err := term.GetSize(0); err == nil {\n\t\tpageSize = height\n\t}\n\tif pageSize > opts.nopts {\n\t\tpageSize = opts.nopts\n\t}\n\tconst buffer = 5\n\tif pageSize > buffer {\n\t\tpageSize = pageSize - buffer\n\t}\n\treturn pageSize\n}",
"func (c *ProjectsLocationsProcessesRunsLineageEventsListCall) PageSize(pageSize int64) *ProjectsLocationsProcessesRunsLineageEventsListCall {\n\tc.urlParams_.Set(\"pageSize\", fmt.Sprint(pageSize))\n\treturn c\n}",
"func (p *Paginator) ItemsPerPage() int {\n\treturn p.itemsPerPage\n}",
"func paging(start, length, totalCount int) (int, int) {\n\tif length == 0 {\n\t\tlength = 20\n\t}\n\n\tstart = totalCount - start - length\n\tif start < 0 {\n\t\tlength += start\n\t\tstart = 0\n\t}\n\treturn start, length\n}",
"func (o *GetPaymentsParams) SetPageSize(pageSize *int64) {\n\to.PageSize = pageSize\n}",
"func (it *TopicIterator) SetPageSize(pageSize int) {\n\tif pageSize > math.MaxInt32 {\n\t\tpageSize = math.MaxInt32\n\t}\n\tit.pageSize = int32(pageSize)\n}",
"func GetPDFPage(pdfName string, imageName string, pageNum int) error {\n\n\tabsPath, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tInpath := filepath.Join(absPath, \"input\", pdfName)\n\tOutpath := filepath.Join(absPath, \"output\")\n\n\tif _, err := os.Stat(Outpath); os.IsNotExist(err) {\n\t\tlog.Println(\"Output dir not found. Creating at \", Outpath)\n\t\tos.Mkdir(Outpath, os.ModePerm)\n\t}\n\n\timagick.Initialize()\n\tdefer imagick.Terminate()\n\n\tmw := imagick.NewMagickWand()\n\tdefer mw.Destroy()\n\n\tif err := mw.SetResolution(72, 72); err != nil {\n\t\treturn err\n\t}\n\n\t// Load the image file into imagick\n\tif err := mw.ReadImage(Inpath); err != nil {\n\t\treturn err\n\t}\n\n\tmw.SetIteratorIndex(pageNum - 1)\n\n\t// Set any compression (100 = max quality)\n\tif err := mw.SetCompressionQuality(100); err != nil {\n\t\treturn err\n\t}\n\n\t// Convert into JPG\n\tif err := mw.SetFormat(\"jpg\"); err != nil {\n\t\treturn err\n\t}\n\n\t// Save File\n\treturn mw.WriteImage(filepath.Join(Outpath, imageName))\n}",
"func (p *Pagination) SimplePage() (from int, to int) {\n\tif p.Num == 0 || p.Size == 0 {\n\t\tp.Num, p.Size = 1, DefaultSize\n\t}\n\tfrom = (p.Num-1)*p.Size + 1\n\tto = from + p.Size - 1\n\treturn\n}",
"func (c *IndexingDatasourcesItemsListCall) PageSize(pageSize int64) *IndexingDatasourcesItemsListCall {\n\tc.urlParams_.Set(\"pageSize\", fmt.Sprint(pageSize))\n\treturn c\n}",
"func (c *IndexingDatasourcesItemsListCall) PageSize(pageSize int64) *IndexingDatasourcesItemsListCall {\n\tc.urlParams_.Set(\"pageSize\", fmt.Sprint(pageSize))\n\treturn c\n}",
"func GetPDFPages(inPath string, outPath string, frames []parser.Section) error {\n\n\tif _, err := os.Stat(outPath); os.IsNotExist(err) {\n\t\tlog.Println(\"Output dir not found. Creating at \", outPath)\n\t\terr := os.Mkdir(outPath, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"[PDF Extractor] %s\", err)\n\t\t}\n\t}\n\n\timagick.Initialize()\n\tdefer imagick.Terminate()\n\n\tmw := imagick.NewMagickWand()\n\tdefer mw.Destroy()\n\n\tif err := mw.SetResolution(300, 300); err != nil {\n\t\treturn err\n\t}\n\n\t// Load the image file into imagick\n\tif err := mw.ReadImage(inPath); err != nil {\n\t\treturn err\n\t}\n\n\t// fmt.Println(mw.GetNumberImages())\n\n\t// Set any compression (100 = max quality)\n\tif err := mw.SetCompressionQuality(100); err != nil {\n\t\treturn err\n\t}\n\n\tif err := mw.SetFormat(\"jpg\"); err != nil {\n\t\treturn err\n\t}\n\tvar err error\n\tfor _, frame := range frames {\n\n\t\tmw.SetIteratorIndex(frame.Page - 1)\n\n\t\t// if err := mw.SetImageFormat(\"jpeg\"); err != nil {\n\t\t// \treturn err\n\t\t// }\n\n\t\t// Save File\n\t\terr = mw.WriteImage(filepath.Join(outPath, frame.FrameSrc.ImageSrc))\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%s [PDF extraction: page: %d, loc: %s, to %s] \", err, frame.Page, inPath, filepath.Join(outPath, frame.FrameSrc.ImageSrc))\n\t\t}\n\n\t}\n\treturn nil\n}",
"func (s *SimPDF) Height() float64 {\n\tif s.Page.IsLandscape {\n\t\treturn s.Page.Width\n\t}\n\treturn s.Page.Height\n}",
"func (m *Page) GetPageNumber() int32 {\n\tif m != nil {\n\t\treturn m.PageNumber\n\t}\n\treturn 0\n}",
"func (f *File) GetChunkMapByIndex() []uint64 {\n\treturn f.meta.getChunkMapByIndex()\n}",
"func (r *ImageRef) GetPages() int {\n\treturn r.Pages()\n}",
"func (c *PropertiesIosAppDataStreamsListCall) PageSize(pageSize int64) *PropertiesIosAppDataStreamsListCall {\n\tc.urlParams_.Set(\"pageSize\", fmt.Sprint(pageSize))\n\treturn c\n}",
"func (me *XsdGoPkgHasElem_PageSizesequenceGetReviewableHITsRequestschema_PageSize_XsdtInt_) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_PageSizesequenceGetReviewableHITsRequestschema_PageSize_XsdtInt_; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}",
"func (c *PropertiesWebDataStreamsListCall) PageSize(pageSize int64) *PropertiesWebDataStreamsListCall {\n\tc.urlParams_.Set(\"pageSize\", fmt.Sprint(pageSize))\n\treturn c\n}",
"func (xs *Sheet) GetHorPageBreak(index int) int {\n\ttmp, _, _ := xs.xb.lib.NewProc(\"xlSheetGetHorPageBreakW\").\n\t\tCall(xs.self, I(index))\n\treturn int(tmp)\n}",
"func (c *ProjectsLocationsDataExchangesListingsListCall) PageSize(pageSize int64) *ProjectsLocationsDataExchangesListingsListCall {\n\tc.urlParams_.Set(\"pageSize\", fmt.Sprint(pageSize))\n\treturn c\n}",
"func PageSize(n int) ListOption {\n\tif n < 0 {\n\t\tn = 0\n\t}\n\treturn pageSizeOpt(n)\n}",
"func (ref *UIElement) LineForIndex(index int32) int32 {\n\ta := cfstr(LayoutSizeForScreenSizeParameterizedAttribute)\n\tdefer C.CFRelease(C.CFTypeRef(a))\n\tcfNumber := C.CFNumberCreate(nil, C.kCFNumberSInt32Type, unsafe.Pointer(&index))\n\tdefer C.CFRelease(C.CFTypeRef(cfNumber))\n\tvar value C.CFTypeRef\n\tC.AXUIElementCopyParameterizedAttributeValue(ref.obj, a, cfNumber, &value)\n\tret := convertCFType(value)\n\to, ok := ret.(int32)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn o\n}",
"func (e *linodeImagePaginated) pageNumber() int {\n\treturn e.Page\n}",
"func (_DelegateProfile *DelegateProfileSession) GetFieldByIndex(_idx *big.Int) (struct {\n\tName string\n\tVerifier common.Address\n\tDeprecated bool\n}, error) {\n\treturn _DelegateProfile.Contract.GetFieldByIndex(&_DelegateProfile.CallOpts, _idx)\n}",
"func (p *Pagination) CurrentPageCount() uint {\n\treturn minuint((p.total - p.Offset()), p.PerPage)\n}",
"func (_Casper *CasperCallerSession) Index() (*big.Int, error) {\n\treturn _Casper.Contract.Index(&_Casper.CallOpts)\n}",
"func (cfp *FsPool) GetSize(fileIndex int64) int64 {\n\treturn cfp.container.Files[fileIndex].Size\n}",
"func PageToOffset(page, size int) int {\n\treturn (page - 1) * size\n}",
"func (e *linodeTypePaginated) pageNumber() int {\n\treturn e.Page\n}",
"func (_DelegateProfile *DelegateProfileCaller) GetFieldByIndex(opts *bind.CallOpts, _idx *big.Int) (struct {\n\tName string\n\tVerifier common.Address\n\tDeprecated bool\n}, error) {\n\tret := new(struct {\n\t\tName string\n\t\tVerifier common.Address\n\t\tDeprecated bool\n\t})\n\tout := ret\n\terr := _DelegateProfile.contract.Call(opts, out, \"getFieldByIndex\", _idx)\n\treturn *ret, err\n}",
"func (c *InspectResultsFindingsListCall) PageSize(pageSize int64) *InspectResultsFindingsListCall {\n\tc.urlParams_.Set(\"pageSize\", fmt.Sprint(pageSize))\n\treturn c\n}",
"func (c *ProjectsLocationsProcessesListCall) PageSize(pageSize int64) *ProjectsLocationsProcessesListCall {\n\tc.urlParams_.Set(\"pageSize\", fmt.Sprint(pageSize))\n\treturn c\n}",
"func (g *getProductsFilter) SetPageSize(size int) *getProductsFilter {\n\t(*g)[\"page[size]\"] = strconv.Itoa(size)\n\treturn g\n}"
] | [
"0.61567366",
"0.59240234",
"0.5838695",
"0.5586188",
"0.54202515",
"0.5387969",
"0.53836745",
"0.5373222",
"0.5279372",
"0.5135162",
"0.50262505",
"0.5000638",
"0.4902227",
"0.48936746",
"0.48466572",
"0.4810993",
"0.475164",
"0.47418535",
"0.4731543",
"0.47187537",
"0.46888658",
"0.4655979",
"0.46289617",
"0.46045673",
"0.4593579",
"0.4593291",
"0.4590091",
"0.4580876",
"0.45793653",
"0.4578419",
"0.45759326",
"0.4556537",
"0.45465565",
"0.4511999",
"0.4472575",
"0.44416073",
"0.43998268",
"0.43950486",
"0.43936026",
"0.43873337",
"0.4372127",
"0.4346229",
"0.43224764",
"0.43113512",
"0.4305349",
"0.4298818",
"0.42899415",
"0.42734244",
"0.42701894",
"0.42697015",
"0.4254094",
"0.4243972",
"0.4241669",
"0.423129",
"0.423002",
"0.4225491",
"0.4195386",
"0.41917074",
"0.417833",
"0.41757962",
"0.41673943",
"0.4159723",
"0.41539595",
"0.41479203",
"0.41430154",
"0.41314575",
"0.41301173",
"0.41045436",
"0.40992305",
"0.40977865",
"0.40973583",
"0.4092771",
"0.40853953",
"0.4080433",
"0.40775138",
"0.40693042",
"0.40693042",
"0.40621498",
"0.4050622",
"0.40425634",
"0.40361583",
"0.40331706",
"0.4030587",
"0.40277585",
"0.4023437",
"0.4023003",
"0.4020583",
"0.4020136",
"0.40200958",
"0.40183878",
"0.4006867",
"0.40029198",
"0.39892462",
"0.39865792",
"0.3985547",
"0.39842212",
"0.39832705",
"0.39792562",
"0.39654145",
"0.39629623"
] | 0.81275624 | 0 |
FPDF_RenderPageBitmap renders contents of a page to a device independent bitmap. | func (p *PdfiumImplementation) FPDF_RenderPageBitmap(request *requests.FPDF_RenderPageBitmap) (*responses.FPDF_RenderPageBitmap, error) {
p.Lock()
defer p.Unlock()
pageHandle, err := p.loadPage(request.Page)
if err != nil {
return nil, err
}
bitmapHandle, err := p.getBitmapHandle(request.Bitmap)
if err != nil {
return nil, err
}
C.FPDF_RenderPageBitmap(bitmapHandle.handle, pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.int(request.Flags))
return &responses.FPDF_RenderPageBitmap{}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (p *PdfiumImplementation) FPDF_RenderPageBitmapWithMatrix(request *requests.FPDF_RenderPageBitmapWithMatrix) (*responses.FPDF_RenderPageBitmapWithMatrix, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmatrix := C.FS_MATRIX{\n\t\ta: C.float(request.Matrix.A),\n\t\tb: C.float(request.Matrix.B),\n\t\tc: C.float(request.Matrix.C),\n\t\td: C.float(request.Matrix.D),\n\t\te: C.float(request.Matrix.E),\n\t\tf: C.float(request.Matrix.F),\n\t}\n\n\tclipping := C.FS_RECTF{\n\t\tleft: C.float(request.Clipping.Left),\n\t\ttop: C.float(request.Clipping.Top),\n\t\tright: C.float(request.Clipping.Right),\n\t\tbottom: C.float(request.Clipping.Bottom),\n\t}\n\n\tC.FPDF_RenderPageBitmapWithMatrix(bitmapHandle.handle, pageHandle.handle, &matrix, &clipping, C.int(request.Flags))\n\n\treturn &responses.FPDF_RenderPageBitmapWithMatrix{}, nil\n}",
"func (blk *Block) drawToPage(page *model.PdfPage) error {\n\n\t// TODO(gunnsth): Appears very wasteful to do this all the time.\n\t// Possibly create another wrapper around model.PdfPage (creator.page) which can keep track of whether\n\t// this has already been done.\n\n\t// Check if Page contents are wrapped - if not wrap it.\n\tcontent, err := page.GetAllContentStreams()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontentParser := contentstream.NewContentStreamParser(content)\n\tops, err := contentParser.Parse()\n\tif err != nil {\n\t\treturn err\n\t}\n\tops.WrapIfNeeded()\n\n\t// Ensure resource dictionaries are available.\n\tif page.Resources == nil {\n\t\tpage.Resources = model.NewPdfPageResources()\n\t}\n\n\t// Merge the contents into ops.\n\terr = mergeContents(ops, page.Resources, blk.contents, blk.resources)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Merge resources for blocks which were created from pages.\n\t// Necessary for adding resources which do not appear in the block contents.\n\tif err = mergeResources(blk.resources, page.Resources); err != nil {\n\t\treturn err\n\t}\n\n\terr = page.SetContentStreams([]string{string(ops.Bytes())}, core.NewFlateEncoder())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Add block annotations to the page.\n\tfor _, annotation := range blk.annotations {\n\t\tpage.AddAnnotation(annotation)\n\t}\n\n\treturn nil\n}",
"func RenderPage(tpl template.Template, tplData interface{}, outPath string) {\n\t// Create file\n\toutFile, err := os.Create(outPath)\n\tif err != nil {\n\t\tFatal(err.Error())\n\t}\n\tdefer func() {\n\t\toutFile.Close()\n\t}()\n\tdefer wg.Done()\n\t// Template render\n\terr = tpl.Execute(outFile, tplData)\n\tif err != nil {\n\t\tFatal(err.Error())\n\t}\n}",
"func (p *PdfiumImplementation) FPDF_RenderPage(request *requests.FPDF_RenderPage) (*responses.FPDF_RenderPage, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thdc, ok := request.DC.(C.HDC)\n\tif !ok {\n\t\treturn nil, errors.New(\"DC is not of type C.HDC\")\n\t}\n\n\tC.FPDF_RenderPage(hdc, pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.int(request.Flags))\n\n\treturn &responses.FPDF_RenderPage{}, nil\n}",
"func renderPage(w io.Writer, name string, pageData PageData) {\n\trenderTemplate(w, name, pageData)\n}",
"func (m *display) BitmapDrawFile(col, row int, filename string) (int, error) {\n\tfile, err1 := os.Open(filename)\n\tif err1 != nil {\n\t\treturn 0, err1\n\t}\n\n\tb := make([]byte,1024)\n\tn2, err2 := file.Read(b)\n\tif err2 != nil {\n\t\treturn 0, err2\n\t}\n\n\tdata := []byte{0xFE, 0x64}\n\tdata = append(data, byte(col))\n\tdata = append(data, byte(row))\n\tdata = append(data, b[:n2]...)\n\tfmt.Printf(\"data: %v, \\nlen: %v\\n\", data, len(data))\n\n\n\tn3 := m.Send(data)\n\treturn n3, nil\n}",
"func (m *display) BitmapDraw(col, row, id int) (int) {\n\tdata := []byte{0xFE, 0x62}\n\tidb := make([]byte, 2)\n\tbinary.LittleEndian.PutUint16(idb, uint16(id))\n\tdata = append(data, idb...)\n\tdata = append(data, byte(col))\n\tdata = append(data, byte(row))\n\t//fmt.Printf(\"data: % X, \\nlen: %v\\n\", data, len(data))\n\n\tn3 := m.Send(data)\n\treturn n3\n}",
"func (p *PdfiumImplementation) FPDFBitmap_Create(request *requests.FPDFBitmap_Create) (*responses.FPDFBitmap_Create, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmap := C.FPDFBitmap_Create(C.int(request.Width), C.int(request.Height), C.int(request.Alpha))\n\tbitmapHandle := p.registerBitmap(bitmap)\n\n\treturn &responses.FPDFBitmap_Create{\n\t\tBitmap: bitmapHandle.nativeRef,\n\t}, nil\n}",
"func RenderPage(c *fiber.Ctx, filename string, bind fiber.Map) {\n\tfp := &mustache.FileProvider{\n\t\tPaths: []string{\"\", \"/src/http/views/\"},\n\t\tExtensions: []string{\"\", \".mustache\"},\n\t}\n\n\tlayoutTmpl, err := mustache.ParseFilePartials(file(\"layout\"), fp)\n\tif err != nil {\n\t\tc.SendStatus(500)\n\t\tc.SendString(err.Error())\n\t\treturn\n\t}\n\n\ttmpl, err := mustache.ParseFilePartials(file(filename), fp)\n\tif err != nil {\n\t\tc.SendStatus(500)\n\t\tc.SendString(err.Error())\n\t\treturn\n\t}\n\n\thtml, err := tmpl.RenderInLayout(layoutTmpl, bind)\n\tif err != nil {\n\t\tc.SendStatus(500)\n\t\tc.SendString(err.Error())\n\t\treturn\n\t}\n\n\tc.Set(\"Content-Type\", \"text/html\")\n\tc.SendString(html)\n}",
"func renderPage(w http.ResponseWriter, tmpl string, data interface{}) {\n\tif err := templates.ExecuteTemplate(w, tmpl, data); err != nil {\n\t\tfmt.Fprintf(w, \"Error %v\", err)\n\t}\n}",
"func (p *PostingsIterator) ActualBitmap() *roaring.Bitmap {\n\treturn p.ActualBM\n}",
"func (self templateEngine) genBoardPage(prefix, frontend, newsgroup string, page int, outfile string, db Database) {\n // get the board model\n board := self.obtainBoard(prefix, frontend, newsgroup, db)\n // update the board page\n board = board.Update(page, db)\n if page >= len(board) {\n log.Println(\"board page should not exist\", newsgroup, \"page\", page)\n return\n }\n // render it\n wr, err := OpenFileWriter(outfile)\n if err == nil {\n updateLinkCacheForBoard(board[page])\n board[page].RenderTo(wr)\n wr.Close()\n log.Println(\"wrote file\", outfile)\n } else {\n log.Println(\"error generating board page\", page, \"for\", newsgroup, err)\n }\n // save it\n self.groups[newsgroup] = board\n}",
"func (c *Canvas) DrawBitmapPart(bmp *Bitmap, dst, src Rectangle) error {\n\treturn c.DrawBitmapPartWithOpacityPixels(bmp, dst, src, 0xff)\n}",
"func PostingsIteratorFromBitmap(bm *roaring.Bitmap,\n\tincludeFreqNorm, includeLocs bool) (segment.PostingsIterator, error) {\n\treturn &PostingsIterator{\n\t\tActualBM: bm,\n\t\tActual: bm.Iterator(),\n\t\tincludeFreqNorm: includeFreqNorm,\n\t\tincludeLocs: includeLocs,\n\t}, nil\n}",
"func (p *PdfiumImplementation) FPDFBitmap_CreateEx(request *requests.FPDFBitmap_CreateEx) (*responses.FPDFBitmap_CreateEx, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tvar pointer unsafe.Pointer\n\tif request.Buffer != nil {\n\t\tpointer = unsafe.Pointer(&request.Buffer[0])\n\t} else if request.Pointer != nil {\n\t\tv, ok := request.Pointer.(unsafe.Pointer)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"request.Pointer is not of type unsafe.Pointer\")\n\t\t}\n\n\t\tpointer = v\n\t}\n\n\tbitmap := C.FPDFBitmap_CreateEx(C.int(request.Width), C.int(request.Height), C.int(request.Format), pointer, C.int(request.Stride))\n\tbitmapHandle := p.registerBitmap(bitmap)\n\n\treturn &responses.FPDFBitmap_CreateEx{\n\t\tBitmap: bitmapHandle.nativeRef,\n\t}, nil\n}",
"func Render(mem *memory.Bank) *image.RGBA {\n\t// Top border\n\tfor pixel := 0; pixel < 4*width*BorderTop; pixel += 4 {\n\t\tborder := findBorderColour(pixelT[pixel/4])\n\t\timg.Pix[pixel] = border[0]\n\t\timg.Pix[pixel+1] = border[1]\n\t\timg.Pix[pixel+2] = border[2]\n\t}\n\n\t// Main screen and left/right border\n\tfor line, addr := range lines {\n\t\tpx := 4 * (width*(line+BorderTop) + BorderLeft)\n\n\t\t// Left border\n\t\tfor left := px - 4*BorderLeft; left < px; left += 4 {\n\t\t\tborder := findBorderColour(pixelT[left/4])\n\t\t\timg.Pix[left] = border[0]\n\t\t\timg.Pix[left+1] = border[1]\n\t\t\timg.Pix[left+2] = border[2]\n\t\t}\n\t\t// Right border\n\t\tfor right := px + 4*256; right < px+4*256+4*BorderRight; right += 4 {\n\t\t\tborder := findBorderColour(pixelT[right/4])\n\t\t\timg.Pix[right] = border[0]\n\t\t\timg.Pix[right+1] = border[1]\n\t\t\timg.Pix[right+2] = border[2]\n\t\t}\n\n\t\t// Centre\n\t\tfor col := 0; col < 32; col++ {\n\t\t\tattr := mem[0x5800+32*(line/8)+col-0x4000]\n\t\t\tcell := mem[addr+col-0x4000]\n\t\t\tfor _, bit := range []byte{0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01} {\n\t\t\t\tvar colour []byte\n\t\t\t\tflash := attr&0x80 != 0 && frame >= 32\n\t\t\t\ton := cell&bit != 0\n\t\t\t\tif on != flash {\n\t\t\t\t\tcolour = inkPalette[attr&0b01000111]\n\t\t\t\t} else {\n\t\t\t\t\tcolour = paperPalette[attr&0b01111000]\n\t\t\t\t}\n\t\t\t\timg.Pix[px] = colour[0]\n\t\t\t\timg.Pix[px+1] = colour[1]\n\t\t\t\timg.Pix[px+2] = colour[2]\n\t\t\t\tpx += 4\n\t\t\t}\n\t\t}\n\t}\n\n\t// Bottom border\n\tfor px := 4 * width * (BorderTop + 192); px < 4*width*(height); px += 4 {\n\t\tborder := findBorderColour(pixelT[px/4])\n\t\timg.Pix[px] = border[0]\n\t\timg.Pix[px+1] = border[1]\n\t\timg.Pix[px+2] = border[2]\n\t}\n\n\t// Can safely drop recorded states\n\tresetBorderStates()\n\n\t// Keep frame count for the \"flash\" attribute\n\tframe += 1\n\tif frame > 50 {\n\t\tframe = 1\n\t}\n\n\treturn img\n}",
"func writeBitmap(file *os.File, index int64, bitMap []byte) {\n\tfile.Seek(index, 0)\n\t//Empezamos el proceso de guardar en binario la data en memoria del struct\n\tvar binaryDisc bytes.Buffer\n\tbinary.Write(&binaryDisc, binary.BigEndian, &bitMap)\n\twriteNextBytes(file, binaryDisc.Bytes())\n}",
"func PageFile(name, version, size string, path, links, lines []string) *Renderer {\n\treturn &Renderer{\n\t\tfilenames: []string{\n\t\t\t\"templates/layout.html\",\n\t\t\t\"templates/logo.html\",\n\t\t\t\"templates/pages/file.html\",\n\t\t},\n\t\tcontext: struct {\n\t\t\tPackage string\n\t\t\tVersion string\n\t\t\tSize string\n\t\t\tPath []string\n\t\t\tPathLinks []string\n\t\t\tLines []string\n\t\t}{\n\t\t\tPackage: name,\n\t\t\tVersion: version,\n\t\t\tSize: size,\n\t\t\tPath: path,\n\t\t\tPathLinks: links,\n\t\t\tLines: append([]string{\"\"}, lines...),\n\t\t},\n\t}\n}",
"func (ui *Plot) Screenshot() {\n\tui.canvas.SetPaintMode(walk.PaintNormal)\n\tdefer func() {\n\t\tui.canvas.SetPaintMode(walk.PaintBuffered)\n\t}()\n\tif hbmp, err := hBitmapFromWindow(ui.canvas); err != nil {\n\t\treturn\n\t} else {\n\t\t// TODO: do we need the mainwindow?\n\t\thBitmapToClipboard(ui.canvas, hbmp)\n\t}\n}",
"func (m *PageManager) RunPage(ctx context.Context, buf *bytes.Buffer) (headers map[string]string, httpErrCode int) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tswitch v := r.(type) {\n\t\t\tcase error:\n\t\t\t\terr := newRunError(ctx, v)\n\t\t\t\tm.makeErrorResponse(ctx, err, \"\", buf)\n\t\t\tcase string:\n\t\t\t\terr := newRunError(ctx, v)\n\t\t\t\tm.makeErrorResponse(ctx, err, \"\", buf)\n\t\t\tcase *HttpError:\t// A kind of http panic that just returns a response code and headers\n\t\t\t\theaders = v.headers\n\t\t\t\thttpErrCode = v.errCode\n\t\t\tdefault:\n\t\t\t\terr := newRunError(ctx, fmt.Errorf(\"unknown package error: %v\", r))\n\t\t\t\tm.makeErrorResponse(ctx, err, \"\", buf)\n\t\t\t}\n\t\t}\n\t}()\n\n\tpage, isNew := m.getPage(ctx)\n\n\tdefer m.cleanup(page)\n\tpage.renderStatus = PageIsRendering\n\tlog.FrameworkDebugf(\"Page started rendering %s, %s\", page.stateId, GetContext(ctx))\n\n\terr := page.runPage(ctx, buf, isNew)\n\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tvar html = buf.String() // copy current html\n\t\tbuf.Reset()\n\t\tm.makeErrorResponse(ctx, newRunError(ctx, err), html, buf)\n\t\treturn\n\t}\n\treturn page.responseHeader, page.responseError\n}",
"func (p *PdfiumImplementation) FPDFBitmap_FillRect(request *requests.FPDFBitmap_FillRect) (*responses.FPDFBitmap_FillRect, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tC.FPDFBitmap_FillRect(bitmapHandle.handle, C.int(request.Left), C.int(request.Top), C.int(request.Width), C.int(request.Height), C.ulong(request.Color))\n\n\treturn &responses.FPDFBitmap_FillRect{}, nil\n}",
"func GetPDFPage(pdfName string, imageName string, pageNum int) error {\n\n\tabsPath, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tInpath := filepath.Join(absPath, \"input\", pdfName)\n\tOutpath := filepath.Join(absPath, \"output\")\n\n\tif _, err := os.Stat(Outpath); os.IsNotExist(err) {\n\t\tlog.Println(\"Output dir not found. Creating at \", Outpath)\n\t\tos.Mkdir(Outpath, os.ModePerm)\n\t}\n\n\timagick.Initialize()\n\tdefer imagick.Terminate()\n\n\tmw := imagick.NewMagickWand()\n\tdefer mw.Destroy()\n\n\tif err := mw.SetResolution(72, 72); err != nil {\n\t\treturn err\n\t}\n\n\t// Load the image file into imagick\n\tif err := mw.ReadImage(Inpath); err != nil {\n\t\treturn err\n\t}\n\n\tmw.SetIteratorIndex(pageNum - 1)\n\n\t// Set any compression (100 = max quality)\n\tif err := mw.SetCompressionQuality(100); err != nil {\n\t\treturn err\n\t}\n\n\t// Convert into JPG\n\tif err := mw.SetFormat(\"jpg\"); err != nil {\n\t\treturn err\n\t}\n\n\t// Save File\n\treturn mw.WriteImage(filepath.Join(Outpath, imageName))\n}",
"func renderPage(ctx *Context, path, tpl string, data interface{}) error {\n\tif err := filesystem.CreateDir(path, true); err != nil {\n\t\treturn err\n\t}\n\n\thandle, err := filesystem.CreateFile(filepath.Join(path, indexFile))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttplPath := filepath.Join(ctx.TemplateDir, tpl)\n\treturn template.Render(tplPath, data, handle)\n}",
"func (p *PdfiumImplementation) FPDF_PageToDevice(request *requests.FPDF_PageToDevice) (*responses.FPDF_PageToDevice, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdeviceX := C.int(0)\n\tdeviceY := C.int(0)\n\n\tsuccess := C.FPDF_PageToDevice(pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.double(request.PageX), C.double(request.PageY), &deviceX, &deviceY)\n\tif int(success) == 0 {\n\t\treturn nil, errors.New(\"could not calculate from page to device\")\n\t}\n\n\treturn &responses.FPDF_PageToDevice{\n\t\tDeviceX: int(deviceX),\n\t\tDeviceY: int(deviceY),\n\t}, nil\n}",
"func (w *dewindow) realpaint(buf *demodel.CharBuffer, viewport *viewer.Viewport) {\n\tw.Lock()\n\tdefer w.Unlock()\n\n\tdefer func() {\n\t\tw.painting = false\n\t}()\n\tw.painting = true\n\n\tif w.buffer == nil {\n\t\treturn\n\t}\n\tdst := w.buffer.RGBA()\n\n\t// Fill the buffer with the window background colour before\n\t// drawing the web page on top of it.\n\t// This should logically be in the viewport code itself, but importing\n\t// kbmap to switch on the mode sentinals would result in a cyclical\n\t// import.\n\tif viewport.BackgroundMode != viewer.StableBackground {\n\t\tswitch viewport.GetKeyboardMode() {\n\t\tcase kbmap.InsertMode:\n\t\t\tdraw.Draw(dst, dst.Bounds(), &image.Uniform{renderer.InsertBackground}, image.ZP, draw.Src)\n\t\tcase kbmap.DeleteMode:\n\t\t\tdraw.Draw(dst, dst.Bounds(), &image.Uniform{renderer.DeleteBackground}, image.ZP, draw.Src)\n\t\tdefault:\n\t\t\tdraw.Draw(dst, dst.Bounds(), &image.Uniform{renderer.NormalBackground}, image.ZP, draw.Src)\n\t\t}\n\t} else {\n\t\tdraw.Draw(dst, dst.Bounds(), &image.Uniform{renderer.NormalBackground}, image.ZP, draw.Src)\n\t}\n\n\ts := w.sz.Size()\n\n\tcontentBounds := dst.Bounds()\n\ttagBounds := tagSize\n\t// ensure that the tag takes no more than half the window, so that the content doesn't get\n\t// drowned out by commands that output more to stderr than they should.\n\tif wHeight := s.Y; tagBounds.Max.Y > wHeight/2 {\n\t\ttagBounds.Max.Y = wHeight / 2\n\t}\n\tcontentBounds.Min.Y = tagBounds.Max.Y\n\n\ttagline.RenderInto(dst.SubImage(image.Rectangle{image.ZP, image.Point{s.X, tagBounds.Max.Y}}).(*image.RGBA), buf.Tagline, clipRectangle(w.sz, viewport))\n\tviewport.RenderInto(dst.SubImage(image.Rectangle{image.Point{0, tagBounds.Max.Y}, s}).(*image.RGBA), buf, clipRectangle(w.sz, viewport))\n\n\tw.Upload(image.Point{0, 0}, w.buffer, dst.Bounds())\n\tw.Publish()\n\treturn\n}",
"func (render *Renderer_impl)Mmap( m *Mapped_resource, buf *Buffer, mm Map_mode) fundations.Result{\n\n}",
"func (r ApiGetBitlinksByGroupRequest) Page(page int32) ApiGetBitlinksByGroupRequest {\n\tr.page = &page\n\treturn r\n}",
"func (c *Render) GoPage(w http.ResponseWriter, r *http.Request, view string, data interface{}) error {\n\ttmpl, err := template.ParseFiles(fmt.Sprintf(\"%s/views/%s.page.tmpl\", c.RootPath, view))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttd := &TemplateData{}\n\tif data != nil {\n\t\ttd = data.(*TemplateData)\n\t}\n\n\terr = tmpl.Execute(w, &td)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func CreatePage(\n\txRefTable *model.XRefTable,\n\tparentPageIndRef types.IndirectRef,\n\tp *model.Page,\n\tfonts model.FontMap) (*types.IndirectRef, types.Dict, error) {\n\n\tpageDict := types.Dict(\n\t\tmap[string]types.Object{\n\t\t\t\"Type\": types.Name(\"Page\"),\n\t\t\t\"Parent\": parentPageIndRef,\n\t\t\t\"MediaBox\": p.MediaBox.Array(),\n\t\t\t\"CropBox\": p.CropBox.Array(),\n\t\t},\n\t)\n\n\terr := addPageResources(xRefTable, pageDict, *p, fonts)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tir, err := xRefTable.StreamDictIndRef(p.Buf.Bytes())\n\tif err != nil {\n\t\treturn nil, pageDict, err\n\t}\n\tpageDict.Insert(\"Contents\", *ir)\n\n\tpageDictIndRef, err := xRefTable.IndRefForNewObject(pageDict)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif len(p.AnnotTabs) == 0 && len(p.Annots) == 0 && len(p.LinkAnnots) == 0 {\n\t\treturn pageDictIndRef, pageDict, nil\n\t}\n\n\tif err := setAnnotationParentsAndFields(xRefTable, p, *pageDictIndRef); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tarr, err := mergeAnnotations(nil, p.Annots, p.AnnotTabs)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfor _, la := range p.LinkAnnots {\n\t\td, err := la.RenderDict(xRefTable, *pageDictIndRef)\n\t\tif err != nil {\n\t\t\treturn nil, nil, &json.UnsupportedTypeError{}\n\t\t}\n\t\tir, err := xRefTable.IndRefForNewObject(d)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tarr = append(arr, *ir)\n\t}\n\n\tpageDict[\"Annots\"] = arr\n\n\treturn pageDictIndRef, pageDict, err\n}",
"func (tpl *Template) RenderBytes(ctx ...interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\terr := tpl.Run(&buf, ctx...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}",
"func writePage(w http.ResponseWriter, basePath, pageName string, page interface{}) {\n\tbuf := new(bytes.Buffer)\n\tcontent := template.Must(template.ParseFiles(basePath + pageName))\n\n\terr := content.Execute(buf, page)\n\tgohtypes.PanicIfError(\"Unable to load page\", http.StatusInternalServerError, err)\n\n\t_, err = w.Write(buf.Bytes())\n\tgohtypes.PanicIfError(\"Unable to render\", http.StatusInternalServerError, err)\n}",
"func (d *Device) DrawRGBBitmap8(x, y int16, data []uint8, w, h int16) error {\n\tk, i := d.Size()\n\tif x < 0 || y < 0 || w <= 0 || h <= 0 ||\n\t\tx >= k || (x+w) > k || y >= i || (y+h) > i {\n\t\treturn errOutOfBounds\n\t}\n\td.startWrite()\n\td.setWindow(x, y, w, h)\n\td.bus.Tx(data, nil)\n\td.endWrite()\n\treturn nil\n}",
"func (p *PdfiumImplementation) FPDFBitmap_Destroy(request *requests.FPDFBitmap_Destroy) (*responses.FPDFBitmap_Destroy, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tC.FPDFBitmap_Destroy(bitmapHandle.handle)\n\n\tdelete(p.bitmapRefs, bitmapHandle.nativeRef)\n\n\treturn &responses.FPDFBitmap_Destroy{}, nil\n}",
"func NewPage(mediaBox, cropBox *types.Rectangle) Page {\n\treturn Page{\n\t\tMediaBox: mediaBox,\n\t\tCropBox: cropBox,\n\t\tFm: FontMap{},\n\t\tIm: ImageMap{},\n\t\tAnnotTabs: map[int]FieldAnnotation{},\n\t\tBuf: new(bytes.Buffer)}\n}",
"func (pb *PageBuffer) PageNo() int {\n return pb.page_no\n}",
"func (c *Camera) Render(world, screen *ebiten.Image) error {\n\treturn screen.DrawImage(world, &ebiten.DrawImageOptions{\n\t\tGeoM: c.worldMatrix(),\n\t})\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetBuffer(request *requests.FPDFBitmap_GetBuffer) (*responses.FPDFBitmap_GetBuffer, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We need to calculate the buffer size, this is stride (bytes per bitmap line) * height.\n\tstride := C.FPDFBitmap_GetStride(bitmapHandle.handle)\n\theight := C.FPDFBitmap_GetHeight(bitmapHandle.handle)\n\tsize := int(stride * height)\n\n\t// The pointer to the first byte of the bitmap buffer.\n\tbuffer := C.FPDFBitmap_GetBuffer(bitmapHandle.handle)\n\n\t// We create a Go slice backed by a C array (without copying the original data).\n\tdata := unsafe.Slice((*byte)(unsafe.Pointer(buffer)), uint64(size))\n\n\treturn &responses.FPDFBitmap_GetBuffer{\n\t\tBuffer: data,\n\t}, nil\n}",
"func render(w http.ResponseWriter, context PageContext) {\n\tfuncMap := template.FuncMap{\n\t\t\"title\": strings.Title,\n\t\t\"HumanizeBytes\": HumanizeBytes,\n\t\t\"HumanizeBigBytes\": HumanizeBigBytes,\n\t\t\"CommifyFloat\": CommifyFloat,\n\t\t\"Float2Int\": IntFromFloat64,\n\t\t\"OkToBool\": OkToBool,\n\t\t\"tableflip\": func() string { return \"(╯°□°)╯︵ ┻━┻\" },\n\t}\n\tcontext.Static = STATIC_URL\n\ttmpl_list := getTemplateList(context.ViewTemplate)\n\t/*\n\t\tt, err := template.ParseFiles(tmpl_list...)\n\t\tif err != nil {\n\t\t\tlog.Print(\"template parsing error: \", err)\n\t\t}\n\t*/\n\tt := template.Must(template.New(\"base.html\").Funcs(funcMap).ParseFiles(tmpl_list...))\n\terr := t.Execute(w, context)\n\tif err != nil {\n\t\tlog.Print(\"template executing error: \", err)\n\t}\n}",
"func drawBackground(image *image.RGBA, mem *GBMem) *image.RGBA {\n\tfor x := 0; x < MapWidth; x++ {\n\t\tfor y := 0; y < MapHeight; y++ {\n\t\t\t// get tile index\n\t\t\ttileIndex := mem.read(uint16(VRAMBackgroundMap + x + (y * MapHeight)))\n\n\t\t\t// get pixels corresponding to tile index\n\t\t\tpixels := tileToPixel(tileIndex, mem)\n\n\t\t\t// draw pixels\n\t\t\tdrawTilePixels(image, pixels, x, y)\n\t\t}\n\t}\n\treturn image\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetStride(request *requests.FPDFBitmap_GetStride) (*responses.FPDFBitmap_GetStride, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstride := C.FPDFBitmap_GetStride(bitmapHandle.handle)\n\treturn &responses.FPDFBitmap_GetStride{\n\t\tStride: int(stride),\n\t}, nil\n}",
"func (app *application) render(res http.ResponseWriter, req *http.Request, pageName string, tmplData *Templates) {\n\ttmpl, ok := app.templateCache[pageName]\n\tif !ok {\n\t\tapp.serverError(res, fmt.Errorf(\"the page %s is not found\", pageName))\n\t\treturn\n\t}\n\n\tbuf := new(bytes.Buffer)\n\terr := tmpl.Execute(buf, app.addDefault(tmplData, req))\n\tif err != nil {\n\t\tapp.serverError(res, err)\n\t\treturn\n\t}\n\n\tbuf.WriteTo(res)\n}",
"func GetPDFPages(inPath string, outPath string, frames []parser.Section) error {\n\n\tif _, err := os.Stat(outPath); os.IsNotExist(err) {\n\t\tlog.Println(\"Output dir not found. Creating at \", outPath)\n\t\terr := os.Mkdir(outPath, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"[PDF Extractor] %s\", err)\n\t\t}\n\t}\n\n\timagick.Initialize()\n\tdefer imagick.Terminate()\n\n\tmw := imagick.NewMagickWand()\n\tdefer mw.Destroy()\n\n\tif err := mw.SetResolution(300, 300); err != nil {\n\t\treturn err\n\t}\n\n\t// Load the image file into imagick\n\tif err := mw.ReadImage(inPath); err != nil {\n\t\treturn err\n\t}\n\n\t// fmt.Println(mw.GetNumberImages())\n\n\t// Set any compression (100 = max quality)\n\tif err := mw.SetCompressionQuality(100); err != nil {\n\t\treturn err\n\t}\n\n\tif err := mw.SetFormat(\"jpg\"); err != nil {\n\t\treturn err\n\t}\n\tvar err error\n\tfor _, frame := range frames {\n\n\t\tmw.SetIteratorIndex(frame.Page - 1)\n\n\t\t// if err := mw.SetImageFormat(\"jpeg\"); err != nil {\n\t\t// \treturn err\n\t\t// }\n\n\t\t// Save File\n\t\terr = mw.WriteImage(filepath.Join(outPath, frame.FrameSrc.ImageSrc))\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%s [PDF extraction: page: %d, loc: %s, to %s] \", err, frame.Page, inPath, filepath.Join(outPath, frame.FrameSrc.ImageSrc))\n\t\t}\n\n\t}\n\treturn nil\n}",
"func (db *DB) pageInBuffer(b []byte, id pgid) *page {\n\treturn (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)]))\n}",
"func (g *Game) Draw(screen *ebiten.Image){\n\tProcessRenderers(g, screen)\n}",
"func NewPageBuffer(aSlice interface{}, desiredPageNo int) *PageBuffer {\n return newPageBuffer(\n sliceValue(aSlice, false),\n desiredPageNo,\n valueHandler{})\n}",
"func (m *PageManager) WritePage(p *page.Page) error {\n\toffset, ok := m.pageOffsets[p.ID()]\n\t// if there's no offset for the page present yet, append it at the end of\n\t// the page\n\tif !ok {\n\t\tinfo, err := m.file.Stat()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"stat: %w\", err)\n\t\t}\n\t\toffset = info.Size()\n\t\tm.pageOffsets[p.ID()] = offset\n\t}\n\n\tdata := p.CopyOfData()\n\t_, err := m.file.WriteAt(data, offset)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"write at: %w\", err)\n\t}\n\tif err := m.file.Sync(); err != nil {\n\t\treturn fmt.Errorf(\"sync: %w\", err)\n\t}\n\treturn nil\n}",
"func (m *GameMap) Render(gameCamera *camera.GameCamera, newCameraX, newCameraY int) {\n\n\tgameCamera.MoveCamera(newCameraX, newCameraY, m.Width, m.Height)\n\n\tfor x := 0; x < gameCamera.Width; x++ {\n\t\tfor y := 0; y < gameCamera.Height; y++ {\n\n\t\t\tmapX, mapY := gameCamera.X+x, gameCamera.Y+y\n\n\t\t\tif mapX < 0 {\n\t\t\t\tmapX = 0\n\t\t\t}\n\n\t\t\tif mapY < 0 {\n\t\t\t\tmapY = 0\n\t\t\t}\n\n\t\t\ttile := m.Tiles[mapX][mapY]\n\t\t\tcamX, camY := gameCamera.ToCameraCoordinates(mapX, mapY)\n\n\t\t\t// Print the tile, if it meets the following criteria:\n\t\t\t// 1. Its visible or explored\n\t\t\t// 2. It hasn't been printed yet. This will prevent over printing due to camera conversion\n\t\t\tif tile.Visible {\n\t\t\t\tui.PrintGlyph(camX, camY, tile.Glyph, \"\", 0)\n\t\t\t} else if tile.Explored {\n\t\t\t\tui.PrintGlyph(camX, camY, tile.Glyph, \"\", 0, true)\n\t\t\t}\n\t\t}\n\t}\n}",
"func filePage(w http.ResponseWriter, req *http.Request, filename string, perm *permissions.Permissions, mimereader *mime.MimeReader, luapool *lStatePool) {\n\t// Mimetypes\n\text := path.Ext(filename)\n\t// Markdown pages are handled differently\n\tif ext == \".md\" {\n\t\tw.Header().Add(\"Content-Type\", \"text/html\")\n\t\tb, err := ioutil.ReadFile(filename)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(w, \"Unable to read %s: %s\", filename, err)\n\t\t\treturn\n\t\t}\n\t\tmarkdownBody := string(blackfriday.MarkdownCommon(b))\n\t\tfmt.Fprint(w, markdownPage(filename, markdownBody))\n\t\treturn\n\t} else if ext == \".lua\" {\n\t\tif err := runLua(w, req, filename, perm, luapool); err != nil {\n\t\t\t// Print the Lua error message to the browser\n\t\t\tfmt.Fprint(w, err)\n\t\t}\n\t\treturn\n\t}\n\t// Set the correct Content-Type\n\tmimereader.SetHeader(w, ext)\n\t// Write to the ResponseWriter, from the File\n\tfile, err := os.Open(filename)\n\tdefer file.Close()\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Can't open %s: %s\", filename, err)\n\t}\n\t// Serve the file\n\tio.Copy(w, file)\n\treturn\n}",
"func (is *MenuPage) Render(mainWindowSurface *sdl.Surface) {\n\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetFormat(request *requests.FPDFBitmap_GetFormat) (*responses.FPDFBitmap_GetFormat, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tformat := C.FPDFBitmap_GetFormat(bitmapHandle.handle)\n\n\treturn &responses.FPDFBitmap_GetFormat{\n\t\tFormat: enums.FPDF_BITMAP_FORMAT(format),\n\t}, nil\n}",
"func TestGetMemPages(t *testing.T) {\n\ttype testcase struct {\n\t\tname string\n\t\tmr *MemoryReader\n\t\tstart uint64\n\t\tend uint64\n\t\texpectedError error\n\t}\n\n\tpid, err := getTestImgPID()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Create a temporary empty memory pages file for testing\n\ttmpFilePath := filepath.Join(os.TempDir(), \"pages-0.img\")\n\ttmpFile, err := os.Create(tmpFilePath)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdefer func() {\n\t\ttmpFile.Close()\n\t\tif err := os.Remove(tmpFile.Name()); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\tmr, err := NewMemoryReader(testImgsDir, pid, sysPageSize)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ttestCases := []testcase{\n\t\t{\n\t\t\tname: \"Zero memory area size\",\n\t\t\tmr: &MemoryReader{\n\t\t\t\tcheckpointDir: testImgsDir,\n\t\t\t\tpid: pid,\n\t\t\t\tpageSize: sysPageSize,\n\t\t\t\tpagesID: mr.pagesID,\n\t\t\t\tpagemapEntries: mr.GetPagemapEntries(),\n\t\t\t},\n\t\t\tstart: 0,\n\t\t\tend: 0,\n\t\t\texpectedError: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"Valid pagemap entry 1\",\n\t\t\tmr: &MemoryReader{\n\t\t\t\tcheckpointDir: testImgsDir,\n\t\t\t\tpid: pid,\n\t\t\t\tpageSize: sysPageSize,\n\t\t\t\tpagesID: mr.pagesID,\n\t\t\t\tpagemapEntries: mr.GetPagemapEntries(),\n\t\t\t},\n\t\t\tstart: mr.pagemapEntries[0].GetVaddr(),\n\t\t\tend: mr.pagemapEntries[0].GetVaddr() + uint64(uint32(sysPageSize)*mr.pagemapEntries[0].GetNrPages()),\n\t\t\texpectedError: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"Valid pagemap entry 2\",\n\t\t\tmr: &MemoryReader{\n\t\t\t\tcheckpointDir: testImgsDir,\n\t\t\t\tpid: pid,\n\t\t\t\tpageSize: sysPageSize,\n\t\t\t\tpagesID: mr.pagesID,\n\t\t\t\tpagemapEntries: mr.GetPagemapEntries(),\n\t\t\t},\n\t\t\tstart: mr.pagemapEntries[1].GetVaddr(),\n\t\t\tend: mr.pagemapEntries[1].GetVaddr() + uint64(uint32(sysPageSize)*mr.pagemapEntries[1].GetNrPages()),\n\t\t\texpectedError: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"Invalid pages file\",\n\t\t\tmr: &MemoryReader{\n\t\t\t\tcheckpointDir: testImgsDir,\n\t\t\t\tpid: pid,\n\t\t\t\tpageSize: sysPageSize,\n\t\t\t\tpagesID: mr.pagesID + 1,\n\t\t\t\tpagemapEntries: mr.GetPagemapEntries(),\n\t\t\t},\n\t\t\tstart: mr.pagemapEntries[0].GetVaddr(),\n\t\t\tend: mr.pagemapEntries[0].GetVaddr() + uint64(uint32(sysPageSize)*mr.pagemapEntries[0].GetNrPages()),\n\t\t\texpectedError: errors.New(\"no such file or directory\"),\n\t\t},\n\t\t{\n\t\t\tname: \"Empty pages file\",\n\t\t\tmr: &MemoryReader{\n\t\t\t\tcheckpointDir: os.TempDir(),\n\t\t\t\tpid: pid,\n\t\t\t\tpageSize: sysPageSize,\n\t\t\t\tpagesID: 0,\n\t\t\t\tpagemapEntries: mr.GetPagemapEntries(),\n\t\t\t},\n\t\t\tstart: mr.pagemapEntries[1].GetVaddr(),\n\t\t\tend: mr.pagemapEntries[1].GetVaddr() + uint64(uint32(sysPageSize)*mr.pagemapEntries[1].GetNrPages()),\n\t\t\texpectedError: errors.New(\"EOF\"),\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tbuff, err := tc.mr.GetMemPages(tc.start, tc.end)\n\t\t\tif err != nil && tc.expectedError != nil {\n\t\t\t\tif !strings.Contains(err.Error(), tc.expectedError.Error()) {\n\t\t\t\t\tt.Errorf(\"Expected error: %v, got error: %v\", tc.expectedError, err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif tc.expectedError == nil && buff == nil {\n\t\t\t\tt.Errorf(\"Returned memory chunk is expected to be non-empty\")\n\t\t\t}\n\t\t})\n\t}\n}",
"func (a *World) Render(p *pic.Pic) *World {\n\th, w := p.H, p.W\n\tfh, fw := float64(h), float64(w)\n\tcx := vec.New(fw*a.Ratio/fh, 0, 0)\n\tcy := vec.Mult(vec.Norm(vec.Cross(cx, a.Cam.Direct)), a.Ratio)\n\tsample := a.Sample / 4\n\tinv := 1.0 / float64(sample)\n\n\tfmt.Printf(\"w: %v, h: %v, sample: %v, actual sample: %v, thread: %v, cpu: %v\\n\", w, h, a.Sample, sample*4, a.Thread, a.Core)\n\tbar := pb.StartNew(h * w)\n\tbar.SetRefreshRate(1000 * time.Millisecond)\n\n\truntime.GOMAXPROCS(a.Core)\n\tch := make(chan renderData, a.Thread)\n\twg := sync.WaitGroup{}\n\twg.Add(a.Thread)\n\n\tfor tid := 0; tid < a.Thread; tid++ {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tdata, ok := <-ch\n\t\t\t\tif !ok {\n\t\t\t\t\twg.Done()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tsum, x, y := data.sum, data.x, data.y\n\t\t\t\tfor sy := 0.0; sy < 2.0; sy++ {\n\t\t\t\t\tfor sx := 0.0; sx < 2.0; sx++ {\n\t\t\t\t\t\tc := vec.NewZero()\n\t\t\t\t\t\tfor sp := 0; sp < sample; sp++ {\n\t\t\t\t\t\t\tccx := vec.Mult(cx, ((sx+0.5+gend())/2.0+x)/fw-0.5)\n\t\t\t\t\t\t\tccy := vec.Mult(cy, ((sy+0.5+gend())/2.0+y)/fh-0.5)\n\t\t\t\t\t\t\td := vec.Add(vec.Add(ccx, ccy), a.Cam.Direct)\n\t\t\t\t\t\t\tr := ray.New(vec.Add(a.Cam.Origin, vec.Mult(d, 130)), vec.Norm(d))\n\t\t\t\t\t\t\tc.Add(vec.Mult(a.trace(r, 0), inv))\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsum.Add(vec.Mult(vec.New(pic.Clamp(c.X), pic.Clamp(c.Y), pic.Clamp(c.Z)), 0.25))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbar.Add(1)\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor y := 0; y < h; y++ {\n\t\tfor x := 0; x < w; x++ {\n\t\t\tch <- renderData{\n\t\t\t\tsum: &p.C[(h-y-1)*w+x],\n\t\t\t\tx: float64(x),\n\t\t\t\ty: float64(y),\n\t\t\t}\n\t\t}\n\t}\n\n\tclose(ch)\n\twg.Wait()\n\n\tbar.FinishPrint(\"Rendering completed\")\n\treturn a\n}",
"func (db *DB) pageInBuffer(b []byte, id pgid) *page {\n\t// offset := id*sizeof(PageSize)\n\t// size := PageSize\n\t// res := (*page)b[offset...offset+size]\n\treturn (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)]))\n}",
"func (b *OGame) PostPageContent(vals, payload url.Values) ([]byte, error) {\n\treturn b.WithPriority(taskRunner.Normal).PostPageContent(vals, payload)\n}",
"func (v *mandelbrotViewer) Draw(screen *ebiten.Image) {\n\tscreen.ReplacePixels(v.screenBuffer)\n\tv.debugPrint(screen)\n}",
"func (mr *MockPdfServiceServerMockRecorder) InternalRasterizePdf(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InternalRasterizePdf\", reflect.TypeOf((*MockPdfServiceServer)(nil).InternalRasterizePdf), arg0, arg1)\n}",
"func (b *OGame) GetPageContent(vals url.Values) ([]byte, error) {\n\treturn b.WithPriority(taskRunner.Normal).GetPageContent(vals)\n}",
"func (p *PageData) Render() ([]byte, error) {\n\tf, err := data.Assets.Open(\"/template.html\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttmpData := &bytes.Buffer{}\n\tio.Copy(tmpData, f)\n\n\tt, err := template.New(\"Markdown Processing\").Parse(tmpData.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuf := &bytes.Buffer{}\n\terr = t.Execute(buf, p)\n\treturn buf.Bytes(), err\n}",
"func (r renderer) Image(out *bytes.Buffer, link []byte, title []byte, alt []byte) {}",
"func (p *PdfiumImplementation) FPDFPage_Flatten(request *requests.FPDFPage_Flatten) (*responses.FPDFPage_Flatten, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tflattenPageResult := C.FPDFPage_Flatten(pageHandle.handle, C.int(request.Usage))\n\n\treturn &responses.FPDFPage_Flatten{\n\t\tPage: pageHandle.index,\n\t\tResult: responses.FPDFPage_FlattenResult(flattenPageResult),\n\t}, nil\n}",
"func (db *DB) page(id pgid) *page {\n\t// buffer := db.data[]\n\t// offset := id*sizeof(PageSize)\n\t// addr := &db.data[offset]\n\t// p := (*page)addr\n\t//\n\t// return p\n\tpos := id * pgid(db.pageSize)\n\treturn (*page)(unsafe.Pointer(&db.data[pos]))\n}",
"func (this *domainController) Page(ctx *context.Context) {\n\tdefer hret.HttpPanic()\n\n\tif !hrpc.BasicAuth(ctx.Request) {\n\t\thret.Error(ctx.ResponseWriter, 403, i18n.NoAuth(ctx.Request))\n\t\treturn\n\t}\n\n\trst, err := groupcache.GetStaticFile(\"DomainPage\")\n\tif err != nil {\n\t\thret.Error(ctx.ResponseWriter, 404, i18n.Get(ctx.Request, \"as_of_date_page_not_exist\"))\n\t\treturn\n\t}\n\n\tctx.ResponseWriter.Write(rst)\n}",
"func allocPDFPageMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFPageValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func renderHTMLPage(w http.ResponseWriter, r *http.Request, content []byte) {\n w.Header().Set(\"Content-Type\", \"text/html\")\n w.Write(content)\n}",
"func (mr *MockPdfServiceClientMockRecorder) InternalRasterizePdf(ctx, in interface{}, opts ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx, in}, opts...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InternalRasterizePdf\", reflect.TypeOf((*MockPdfServiceClient)(nil).InternalRasterizePdf), varargs...)\n}",
"func (p *PdfiumImplementation) FPDF_DeviceToPage(request *requests.FPDF_DeviceToPage) (*responses.FPDF_DeviceToPage, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpageX := C.double(0)\n\tpageY := C.double(0)\n\n\tsuccess := C.FPDF_DeviceToPage(pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.int(request.DeviceX), C.int(request.DeviceY), &pageX, &pageY)\n\tif int(success) == 0 {\n\t\treturn nil, errors.New(\"could not calculate from device to page\")\n\t}\n\n\treturn &responses.FPDF_DeviceToPage{\n\t\tPageX: float64(pageX),\n\t\tPageY: float64(pageY),\n\t}, nil\n}",
"func (self *Graphics) _renderCanvas(renderSession *RenderSession) {\n self.Object.Call(\"_renderCanvas\", renderSession)\n}",
"func allocPDFRevPageMapMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFRevPageMapValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func RenderURL(url string, width int) (image.Image, error) {\n\tpage, err := tryOpenPage(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpage.MustWaitLoad().MustWaitIdle()\n\tpage.Timeout(time.Second * IdleRequestTimeout).MustWaitRequestIdle()()\n\n\tdefer page.Close()\n\n\treturn screenshotPage(page, width)\n}",
"func RenderHTML(html string, width int) (image.Image, error) {\n\tpage, err := tryOpenPage(\"data:text/html,\" + url.PathEscape(html))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpage.MustWaitLoad().MustWaitIdle()\n\tpage.Timeout(time.Second * IdleRequestTimeout).MustWaitRequestIdle()()\n\n\tdefer page.Close()\n\n\treturn screenshotPage(page, width)\n}",
"func (b *Buffer) Dump() {\n\ts := *b.screen\n\traster := canvas.NewRasterFromImage(b.context.Image())\n\ts.SetContent(raster)\n}",
"func Draw(screen, image *ebiten.Image, px, py int) {\n\tDrawWithOp(screen, image, px, py, nil)\n}",
"func renderPDF(vb []Visit) gopdf.GoPdf {\n\tdoc := gopdf.GoPdf{}\n\tdoc.Start(gopdf.Config{ PageSize: *gopdf.PageSizeA4 })\n\tdoc.AddPage()\n\terr := doc.AddTTFFont(\"Roboto\", \"./assets/Roboto-Regular.ttf\")\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t}\n\n\tdoc.SetTextColor(getForegroundColor())\n\n\toffsetY := 25\n\n\tfor i,v := range vb {\n\t\toffsetX := 8\n\t\tif i%2 == 1 {\n\t\t\toffsetX = 300\n\t\t}\n\t\tif i%2 == 0 && i != 0 {\n\t\t\toffsetY += 175\n\t\t}\n\t\tdoc.SetX(float64(offsetX))\n\t\tdoc.SetY(float64(offsetY))\n\t\tif err := doc.SetFont(\"Roboto\", \"\", 36); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err := doc.Cell(nil, v.Visitor.LastName); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tdoc.Br(40)\n\t\tdoc.SetX(float64(offsetX))\n\t\tif err := doc.SetFont(\"Roboto\", \"\", 24); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err := doc.Cell(nil, v.Visitor.FirstName); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tdoc.Br(40)\n\t\tdoc.SetX(float64(offsetX))\n\t\tif err := doc.SetFont(\"Roboto\", \"\", 12); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tdoc.Line(float64(offsetX),float64(offsetY + 87), float64(offsetX + 250), float64(offsetY + 87) )\n\t\tdoc.Text(v.Visitor.Company)\n\t\tdoc.Br(24)\n\t\tdoc.SetX(float64(offsetX))\n\t\tdoc.Text(\"Supervisor: \" + v.Supervisor.DisplayName)\n\t\tdoc.Br(18)\n\t\tdoc.SetX(float64(offsetX))\n\t\tt,_ := time.Parse(\"2006-01-02\", v.Date)\n\t\tdoc.Text(\"Gültig am: \" + t.Format(\"02.01.2006\"))\n\t\tdoc.SetFont(\"Roboto\", \"\", 8)\n\t\tdoc.Br(12)\n\t\tdoc.SetX(float64(offsetX))\n\n\t\tdoc.Text(\"Dieses Badge muss jederzeit gut sichtbar getragen werden.\")\n\t}\n\n\tdoc.SetLineType(\"dashed\")\n\tdoc.Line(290, 0, 290, 1500)\n\tdoc.Line(0, 175, 1500, 175)\n\tdoc.Line(0, 350, 1500, 350)\n\tdoc.Line(0, 525, 1500, 525)\n\tdoc.Line(0, 700, 1500, 700)\n\treturn doc\n}",
"func (self *GameObjectCreator) BitmapText(x int, y int, font string) *BitmapText{\n return &BitmapText{self.Object.Call(\"bitmapText\", x, y, font)}\n}",
"func getBitmap(file *os.File, index int64, size int64) []byte {\n\tbitMap := make([]byte, size)\n\tfile.Seek(index, 0)\n\t//Se obtiene la data del archivo binarios\n\tdata := readNextBytes(file, size)\n\tbuffer := bytes.NewBuffer(data)\n\t//Se asigna al mbr declarado para leer la informacion de ese disco\n\terr := binary.Read(buffer, binary.BigEndian, &bitMap)\n\tif err != nil {\n\t\tlog.Fatal(\"binary.Read failed\", err)\n\t}\n\treturn bitMap\n}",
"func TestPageMarshalling(t *testing.T) {\n\tt.Skip(\"not implemented\")\n}",
"func Page(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tp, err := strconv.ParseUint(ps.ByName(\"page\"), 10, 8)\n\tif err != nil {\n\t\thttp.NotFound(w, r)\n\t}\n\tdata, err := newPageData(uint8(p))\n\tif err != nil {\n\t\thttp.NotFound(w, r)\n\t}\n\terr = t.ExecuteTemplate(w, \"index\", data)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}",
"func (p *Page) MustScreenshotFullPage(toFile ...string) []byte {\n\tbin, err := p.Screenshot(true, nil)\n\tp.e(err)\n\tp.e(saveFile(saveFileTypeScreenshot, bin, toFile))\n\treturn bin\n}",
"func NewPageWithBg(mediaBox *types.Rectangle, c color.SimpleColor) Page {\n\tp := Page{MediaBox: mediaBox, Fm: FontMap{}, Im: ImageMap{}, Buf: new(bytes.Buffer)}\n\tdraw.FillRectNoBorder(p.Buf, mediaBox, c)\n\treturn p\n}",
"func (blk *Block) GeneratePageBlocks(ctx DrawContext) ([]*Block, DrawContext, error) {\n\tcc := contentstream.NewContentCreator()\n\n\t// Position block.\n\tblkWidth, blkHeight := blk.Width(), blk.Height()\n\tif blk.positioning.isRelative() {\n\t\t// Relative. Draw at current ctx.X, ctx.Y position.\n\t\tcc.Translate(ctx.X, ctx.PageHeight-ctx.Y-blkHeight)\n\t} else {\n\t\t// Absolute. Draw at blk.xPos, blk.yPos position.\n\t\tcc.Translate(blk.xPos, ctx.PageHeight-blk.yPos-blkHeight)\n\t}\n\n\t// Rotate block.\n\trotatedHeight := blkHeight\n\tif blk.angle != 0 {\n\t\t// Make the rotation about the center of the block.\n\t\tcc.Translate(blkWidth/2, blkHeight/2)\n\t\tcc.RotateDeg(blk.angle)\n\t\tcc.Translate(-blkWidth/2, -blkHeight/2)\n\n\t\t_, rotatedHeight = blk.RotatedSize()\n\t}\n\n\tif blk.positioning.isRelative() {\n\t\tctx.Y += rotatedHeight\n\t}\n\n\tdup := blk.duplicate()\n\tcontents := append(*cc.Operations(), *dup.contents...)\n\tcontents.WrapIfNeeded()\n\tdup.contents = &contents\n\n\treturn []*Block{dup}, ctx, nil\n}",
"func (t *TabView) Draw(screen *ebiten.Image) {\n\tt.Screens.DrawFuncs[t.CurrentTab](screen)\n\tt.TabBtns.Draw(screen)\n}",
"func (site *Site) renderPages() error {\n\troot := site.Pages[\"\"]\n\n\tfor _, page := range site.Pages {\n\t\tnav := buildNav(root, page)\n\t\tnav.Active = root == page // override index.md active\n\n\t\tdata := PageData{\n\t\t\tNav: nav,\n\t\t\tFront: &page.FrontMatter,\n\t\t\tPage: page,\n\t\t}\n\n\t\tvar buf bytes.Buffer\n\t\tif page.Template != \"\" {\n\t\t\tsiteTempl, err := site.BaseTemplate.Clone()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"template clone failed: %w\", err)\n\t\t\t}\n\t\t\tt, err := siteTempl.Parse(string(page.Template))\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"template parse failed: %w\", err)\n\t\t\t}\n\t\t\tif err := t.ExecuteTemplate(&buf, \"root\", data); err != nil {\n\t\t\t\treturn fmt.Errorf(\"template failed: %w\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tif err := site.Template.ExecuteTemplate(&buf, \"root\", data); err != nil {\n\t\t\t\treturn fmt.Errorf(\"template failed: %w\", err)\n\t\t\t}\n\t\t}\n\t\tpage.Rendered = buf.Bytes()\n\n\t\tif page.RSS {\n\t\t\tvar err error\n\t\t\tpage.RenderedRSS, err = site.renderRSS(data)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"rss rendering failed: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}",
"func (d *Downloader) DownloadPage(page *backends.Page, index int, output string) error {\n\tvar (\n\t\terr error\n\t\tresp *http.Response\n\t)\n\n\tpagePath := path.Join(output, strconv.Itoa(index))\n\n\tfor i := 0; i < 10; i++ {\n\t\timageURL, err := d.Backend.PageImageURL(page)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// resp, err := d.Client.Get(imageURL, make([]int, 1))\n\t\tresp, err = d.Client.Get(imageURL, []int{200})\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar extension string\n\tif len(extension) == 0 {\n\t\tcontentType := resp.Header.Get(\"content-type\")\n\t\tif len(contentType) > 0 {\n\t\t\tmatches := regexpImageContentType.FindStringSubmatch(contentType)\n\t\t\tif matches != nil {\n\t\t\t\textension = matches[1]\n\t\t\t}\n\t\t}\n\t}\n\tif len(extension) > 0 {\n\t\tif extension == \"jpeg\" {\n\t\t\textension = \"jpg\"\n\t\t}\n\t\tpagePath += \".\" + extension\n\t}\n\n\terr = os.MkdirAll(filepath.Dir(pagePath), 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(pagePath, data, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func BuildPage(htmlTemplate string, bingoBoard BingoBoard) *bytes.Buffer {\n\tvar bodyBuffer bytes.Buffer\n\tt := template.New(\"template\")\n\tvar templates = template.Must(t.Parse(htmlTemplate))\n\ttemplates.Execute(&bodyBuffer, bingoBoard)\n\treturn &bodyBuffer\n}",
"func (b *Bitmaps) GetBitmap(i int) (*Bitmap, error) {\n\tconst processName = \"GetBitmap\"\n\tif b == nil {\n\t\treturn nil, errors.Error(processName, \"provided nil Bitmaps\")\n\t}\n\tif i > len(b.Values)-1 {\n\t\treturn nil, errors.Errorf(processName, \"index: '%d' out of range\", i)\n\t}\n\treturn b.Values[i], nil\n}",
"func (dst *Image) Bytes(pt image.Point, src *Image, sp image.Point, f *Font, b []byte) image.Point {\n\tdst.Display.mu.Lock()\n\tdefer dst.Display.mu.Unlock()\n\treturn _string(dst, pt, src, sp, f, \"\", b, nil, dst.Clipr, nil, image.ZP, SoverD)\n}",
"func (self *TileSprite) _renderCanvas(renderSession *RenderSession) {\n self.Object.Call(\"_renderCanvas\", renderSession)\n}",
"func (a *PDFApiService) DrawImage(ctx _context.Context, pdfDrawImageParameters PdfDrawImageParameters) (PdfDrawImageResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue PdfDrawImageResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/pdf/DrawImage\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json-patch+json\", \"application/json\", \"text/json\", \"application/_*+json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &pdfDrawImageParameters\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v PdfDrawImageResponse\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}",
"func (blk *Block) Draw(d Drawable) error {\n\tctx := DrawContext{}\n\tctx.Width = blk.width\n\tctx.Height = blk.height\n\tctx.PageWidth = blk.width\n\tctx.PageHeight = blk.height\n\tctx.X = 0 // Upper left corner of block\n\tctx.Y = 0\n\n\tblocks, _, err := d.GeneratePageBlocks(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(blocks) != 1 {\n\t\treturn errors.New(\"too many output blocks\")\n\t}\n\n\tfor _, newBlock := range blocks {\n\t\tif err := blk.mergeBlocks(newBlock); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (pp *PostProcessor) EndRender() {\n\t// Now resolve multisampled color-buffer into intermediate FBO to store to texture\n\tgl.BindFramebuffer(gl.READ_FRAMEBUFFER, pp.msFrameBuffer)\n\tgl.BindFramebuffer(gl.DRAW_FRAMEBUFFER, pp.frameBuffer)\n\tgl.BlitFramebuffer(0, 0, int32(pp.width), int32(pp.height), 0, 0, int32(pp.width), int32(pp.height), gl.COLOR_BUFFER_BIT, gl.NEAREST)\n\tgl.BindFramebuffer(gl.FRAMEBUFFER, 0) // Binds both READ and WRITE framebuffer to default framebuffer\n}",
"func (b *Bill) drawBankDetails() {\n\tb.pdf.Ln(20)\n\tb.pdf.SetFont(b.config.Business.SerifFont, \"B\", 14)\n\tb.darkText()\n\tb.pdf.Cell(40, 0, \"Payment Details\")\n\tb.pdf.Ln(5)\n\tb.pdf.SetFont(b.config.Business.SerifFont, \"\", 8)\n\theaders := []string{\n\t\t\"Pay By\", \"Bank Name\", \"Address\", \"Account Type (checking/Savings)\",\n\t\t\"IBAN (international)\", \"Sort Code (International)\",\n\t}\n\n\tb.pdf.SetDrawColor(64, 64, 64)\n\tb.lightFillColor()\n\tfor i, v := range b.config.Bank.Strings() {\n\t\tb.whiteText()\n\t\tb.pdf.SetFont(b.config.Business.SerifFont, \"B\", 10)\n\t\tb.pdf.CellFormat(60, 5, headers[i], \"1\", 0, \"R\", true, 0, \"\")\n\t\tb.blackText()\n\t\tb.pdf.SetFont(b.config.Business.SerifFont, \"\", 10)\n\t\tb.pdf.CellFormat(100, 5, v, \"1\", 0, \"L\", false, 0, \"\")\n\t\tb.pdf.Ln(5)\n\t}\n}",
"func (r *RMFileInfo) PageIterate() (pageNo, pdfPageNo int, inserted, isTemplate bool, reader *io.ReadSeeker) {\n\tpageNo = r.thisPageNo\n\tr.thisPageNo++\n\n\t// if there is only a template, always return the first page\n\tif r.pdfPath == \"\" {\n\t\tpdfPageNo = 0\n\t\tisTemplate = true\n\t\treader = &r.templateReader\n\t\treturn\n\t}\n\n\t// older remarkable bundles don't report inserted pages; ignore\n\thasRedir := func() bool { return len(r.RedirectionPageMap) > 0 }()\n\n\t// return the template if this is an inserted page\n\tif hasRedir && r.RedirectionPageMap[pageNo] == -1 {\n\t\tpdfPageNo = 0\n\t\tinserted = true\n\t\tisTemplate = true\n\t\treader = &r.templateReader\n\t\treturn\n\t}\n\n\t// remaining target is the annotated file\n\treader = &r.pdfReader\n\n\t// if the annotated pdf has inserted pages, calculate the offset of\n\t// the original pdf to use\n\tif hasRedir && r.PageCount != r.OriginalPageCount {\n\t\tpdfPageNo = pageNo\n\t\tfor i := 0; i <= pageNo; i++ {\n\t\t\tif r.RedirectionPageMap[i] == -1 {\n\t\t\t\tpdfPageNo--\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\t// fall through: the annotated pdf has no inserted pages\n\tpdfPageNo = pageNo\n\treturn\n\n}",
"func renderTemplateBytes(name string, data interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tif err := Tmpl.Render(&buf, name, data); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}",
"func renderTemplateBytes(name string, data interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tif err := Tmpl.Render(&buf, name, data); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}",
"func (db *DB) page(id pgid) *page {\n\tpos := id * pgid(db.pageSize)\n\treturn (*page)(unsafe.Pointer(&db.data[pos]))\n}",
"func (tm *Term) NextPage() error {\n\tif tm.Tail {\n\t\ttm.RowOff = ints.MinInt(tm.RowOff+tm.RowsPer, 0)\n\t\ttm.RowOff = ints.MaxInt(tm.RowOff, tm.RowsPer-tm.MaxRows)\n\t} else {\n\t\ttm.RowSt = ints.MinInt(tm.RowSt+tm.RowsPer, tm.MaxRows-tm.RowsPer)\n\t\ttm.RowSt = ints.MaxInt(tm.RowSt, 0)\n\t}\n\treturn tm.Draw()\n}",
"func MapViewOfFile(hFileMappingObject HANDLE, dwDesiredAccess DWORD, dwFileOffsetHigh DWORD, dwFileOffsetLow DWORD, dwNumberOfBytesToMap SIZE_T) LPVOID {\n\tret1 := syscall6(mapViewOfFile, 5,\n\t\tuintptr(hFileMappingObject),\n\t\tuintptr(dwDesiredAccess),\n\t\tuintptr(dwFileOffsetHigh),\n\t\tuintptr(dwFileOffsetLow),\n\t\tuintptr(dwNumberOfBytesToMap),\n\t\t0)\n\treturn (LPVOID)(unsafe.Pointer(ret1))\n}",
"func (fx *fx) Render(t float64) image.Image {\n\tconst (\n\t\tDecimalPointLog = 16\n\t\tDecimalMul = 1 << DecimalPointLog\n\t)\n\t// tt is our reverse zoom as 16.16 fixed point\n\ttt := int(t * t * 12 * DecimalMul)\n\n\txMask := (1 << fx.logW) - 1\n\tyMask := (1 << fx.logH) - 1\n\n\t// Center of zoom (screen space)\n\tcenterX, centerY := renderWidth/2, renderHeight/2\n\t// Store the reverse transformation for the center of screen.\n\tx0 := -tt * centerX\n\ty0 := -tt * centerY\n\n\t// Center on texture (texture space)\n\ttexCenterX, texCenterY := 173, 106\n\tx0 += texCenterX * DecimalMul\n\ty0 += texCenterY * DecimalMul\n\n\tfor y, line := range fx.lines {\n\t\tsrcY := ((y0 + y*tt) >> DecimalPointLog) & yMask\n\t\t// Pre-shift, so srcY is offset for x=0 at our line.\n\t\tsrcY <<= fx.logW\n\t\tfor x := range line {\n\t\t\tsrcX := ((x0 + x*tt) >> DecimalPointLog) & xMask\n\t\t\tline[x] = fx.img.Pix[srcX+srcY]\n\t\t}\n\t}\n\treturn fx.draw\n}",
"func (p *Plasma) Draw(screen *ebiten.Image) {\r\n\tscreen.ReplacePixels(p.buffer)\r\n}",
"func (enc *JBIG2Encoder) AddPageImage(img *JBIG2Image, settings *JBIG2EncoderSettings) (err error) {\n\tconst processName = \"JBIG2Document.AddPageImage\"\n\tif enc == nil {\n\t\treturn errors.Error(processName, \"JBIG2Document is nil\")\n\t}\n\tif settings == nil {\n\t\tsettings = &enc.DefaultPageSettings\n\t}\n\tif enc.d == nil {\n\t\tenc.d = document.InitEncodeDocument(settings.FileMode)\n\t}\n\n\tif err = settings.Validate(); err != nil {\n\t\treturn errors.Wrap(err, processName, \"\")\n\t}\n\n\t// convert input 'img' to the bitmap.Bitmap\n\tb, err := img.toBitmap()\n\tif err != nil {\n\t\treturn errors.Wrap(err, processName, \"\")\n\t}\n\n\tswitch settings.Compression {\n\tcase JB2Generic:\n\t\tif err = enc.d.AddGenericPage(b, settings.DuplicatedLinesRemoval); err != nil {\n\t\t\treturn errors.Wrap(err, processName, \"\")\n\t\t}\n\tcase JB2SymbolCorrelation:\n\t\treturn errors.Error(processName, \"symbol correlation encoding not implemented yet\")\n\tcase JB2SymbolRankHaus:\n\t\treturn errors.Error(processName, \"symbol rank haus encoding not implemented yet\")\n\tdefault:\n\t\treturn errors.Error(processName, \"provided invalid compression\")\n\t}\n\treturn nil\n}"
] | [
"0.66721916",
"0.52410096",
"0.52291584",
"0.5094461",
"0.507071",
"0.49661854",
"0.4927769",
"0.48994374",
"0.4880387",
"0.47937164",
"0.4765311",
"0.46550494",
"0.46420583",
"0.46353447",
"0.46072868",
"0.45891804",
"0.4574606",
"0.4531817",
"0.45033225",
"0.44624874",
"0.44423625",
"0.4421358",
"0.44213167",
"0.4410716",
"0.43676174",
"0.43242157",
"0.4305905",
"0.42975757",
"0.42949727",
"0.4282053",
"0.42252183",
"0.42154786",
"0.42058906",
"0.41946262",
"0.4183774",
"0.41603953",
"0.41478324",
"0.41446978",
"0.41416258",
"0.41295424",
"0.41265264",
"0.41225958",
"0.41187194",
"0.410603",
"0.4098331",
"0.4080251",
"0.4073781",
"0.40707254",
"0.4038118",
"0.40371367",
"0.4037031",
"0.4032922",
"0.3997896",
"0.39966488",
"0.39715514",
"0.39715",
"0.3970015",
"0.39695877",
"0.3968232",
"0.3964701",
"0.39510623",
"0.39469802",
"0.39439347",
"0.39395493",
"0.3929953",
"0.39259806",
"0.3924561",
"0.39192095",
"0.39113113",
"0.39088547",
"0.39070478",
"0.3907019",
"0.38809365",
"0.3871964",
"0.3852629",
"0.3847261",
"0.3842035",
"0.38370398",
"0.3833588",
"0.38318902",
"0.38300246",
"0.3829629",
"0.38272622",
"0.3821424",
"0.38107914",
"0.38092804",
"0.38080662",
"0.38067654",
"0.38036013",
"0.38011497",
"0.37929115",
"0.37858114",
"0.37855893",
"0.37855893",
"0.3776581",
"0.3773996",
"0.37678134",
"0.37647697",
"0.3764735",
"0.37594166"
] | 0.76119304 | 0 |
FPDF_RenderPageBitmapWithMatrix renders contents of a page to a device independent bitmap. | func (p *PdfiumImplementation) FPDF_RenderPageBitmapWithMatrix(request *requests.FPDF_RenderPageBitmapWithMatrix) (*responses.FPDF_RenderPageBitmapWithMatrix, error) {
p.Lock()
defer p.Unlock()
pageHandle, err := p.loadPage(request.Page)
if err != nil {
return nil, err
}
bitmapHandle, err := p.getBitmapHandle(request.Bitmap)
if err != nil {
return nil, err
}
matrix := C.FS_MATRIX{
a: C.float(request.Matrix.A),
b: C.float(request.Matrix.B),
c: C.float(request.Matrix.C),
d: C.float(request.Matrix.D),
e: C.float(request.Matrix.E),
f: C.float(request.Matrix.F),
}
clipping := C.FS_RECTF{
left: C.float(request.Clipping.Left),
top: C.float(request.Clipping.Top),
right: C.float(request.Clipping.Right),
bottom: C.float(request.Clipping.Bottom),
}
C.FPDF_RenderPageBitmapWithMatrix(bitmapHandle.handle, pageHandle.handle, &matrix, &clipping, C.int(request.Flags))
return &responses.FPDF_RenderPageBitmapWithMatrix{}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (p *PdfiumImplementation) FPDF_RenderPageBitmap(request *requests.FPDF_RenderPageBitmap) (*responses.FPDF_RenderPageBitmap, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tC.FPDF_RenderPageBitmap(bitmapHandle.handle, pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.int(request.Flags))\n\n\treturn &responses.FPDF_RenderPageBitmap{}, nil\n}",
"func (render *Renderer_impl)Mmap( m *Mapped_resource, buf *Buffer, mm Map_mode) fundations.Result{\n\n}",
"func (p *PdfiumImplementation) FPDFBitmap_Create(request *requests.FPDFBitmap_Create) (*responses.FPDFBitmap_Create, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmap := C.FPDFBitmap_Create(C.int(request.Width), C.int(request.Height), C.int(request.Alpha))\n\tbitmapHandle := p.registerBitmap(bitmap)\n\n\treturn &responses.FPDFBitmap_Create{\n\t\tBitmap: bitmapHandle.nativeRef,\n\t}, nil\n}",
"func (m *display) BitmapDraw(col, row, id int) (int) {\n\tdata := []byte{0xFE, 0x62}\n\tidb := make([]byte, 2)\n\tbinary.LittleEndian.PutUint16(idb, uint16(id))\n\tdata = append(data, idb...)\n\tdata = append(data, byte(col))\n\tdata = append(data, byte(row))\n\t//fmt.Printf(\"data: % X, \\nlen: %v\\n\", data, len(data))\n\n\tn3 := m.Send(data)\n\treturn n3\n}",
"func (m *display) BitmapDrawFile(col, row int, filename string) (int, error) {\n\tfile, err1 := os.Open(filename)\n\tif err1 != nil {\n\t\treturn 0, err1\n\t}\n\n\tb := make([]byte,1024)\n\tn2, err2 := file.Read(b)\n\tif err2 != nil {\n\t\treturn 0, err2\n\t}\n\n\tdata := []byte{0xFE, 0x64}\n\tdata = append(data, byte(col))\n\tdata = append(data, byte(row))\n\tdata = append(data, b[:n2]...)\n\tfmt.Printf(\"data: %v, \\nlen: %v\\n\", data, len(data))\n\n\n\tn3 := m.Send(data)\n\treturn n3, nil\n}",
"func writeBitmap(file *os.File, index int64, bitMap []byte) {\n\tfile.Seek(index, 0)\n\t//Empezamos el proceso de guardar en binario la data en memoria del struct\n\tvar binaryDisc bytes.Buffer\n\tbinary.Write(&binaryDisc, binary.BigEndian, &bitMap)\n\twriteNextBytes(file, binaryDisc.Bytes())\n}",
"func Render(mem *memory.Bank) *image.RGBA {\n\t// Top border\n\tfor pixel := 0; pixel < 4*width*BorderTop; pixel += 4 {\n\t\tborder := findBorderColour(pixelT[pixel/4])\n\t\timg.Pix[pixel] = border[0]\n\t\timg.Pix[pixel+1] = border[1]\n\t\timg.Pix[pixel+2] = border[2]\n\t}\n\n\t// Main screen and left/right border\n\tfor line, addr := range lines {\n\t\tpx := 4 * (width*(line+BorderTop) + BorderLeft)\n\n\t\t// Left border\n\t\tfor left := px - 4*BorderLeft; left < px; left += 4 {\n\t\t\tborder := findBorderColour(pixelT[left/4])\n\t\t\timg.Pix[left] = border[0]\n\t\t\timg.Pix[left+1] = border[1]\n\t\t\timg.Pix[left+2] = border[2]\n\t\t}\n\t\t// Right border\n\t\tfor right := px + 4*256; right < px+4*256+4*BorderRight; right += 4 {\n\t\t\tborder := findBorderColour(pixelT[right/4])\n\t\t\timg.Pix[right] = border[0]\n\t\t\timg.Pix[right+1] = border[1]\n\t\t\timg.Pix[right+2] = border[2]\n\t\t}\n\n\t\t// Centre\n\t\tfor col := 0; col < 32; col++ {\n\t\t\tattr := mem[0x5800+32*(line/8)+col-0x4000]\n\t\t\tcell := mem[addr+col-0x4000]\n\t\t\tfor _, bit := range []byte{0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01} {\n\t\t\t\tvar colour []byte\n\t\t\t\tflash := attr&0x80 != 0 && frame >= 32\n\t\t\t\ton := cell&bit != 0\n\t\t\t\tif on != flash {\n\t\t\t\t\tcolour = inkPalette[attr&0b01000111]\n\t\t\t\t} else {\n\t\t\t\t\tcolour = paperPalette[attr&0b01111000]\n\t\t\t\t}\n\t\t\t\timg.Pix[px] = colour[0]\n\t\t\t\timg.Pix[px+1] = colour[1]\n\t\t\t\timg.Pix[px+2] = colour[2]\n\t\t\t\tpx += 4\n\t\t\t}\n\t\t}\n\t}\n\n\t// Bottom border\n\tfor px := 4 * width * (BorderTop + 192); px < 4*width*(height); px += 4 {\n\t\tborder := findBorderColour(pixelT[px/4])\n\t\timg.Pix[px] = border[0]\n\t\timg.Pix[px+1] = border[1]\n\t\timg.Pix[px+2] = border[2]\n\t}\n\n\t// Can safely drop recorded states\n\tresetBorderStates()\n\n\t// Keep frame count for the \"flash\" attribute\n\tframe += 1\n\tif frame > 50 {\n\t\tframe = 1\n\t}\n\n\treturn img\n}",
"func PostingsIteratorFromBitmap(bm *roaring.Bitmap,\n\tincludeFreqNorm, includeLocs bool) (segment.PostingsIterator, error) {\n\treturn &PostingsIterator{\n\t\tActualBM: bm,\n\t\tActual: bm.Iterator(),\n\t\tincludeFreqNorm: includeFreqNorm,\n\t\tincludeLocs: includeLocs,\n\t}, nil\n}",
"func (p *PostingsIterator) ActualBitmap() *roaring.Bitmap {\n\treturn p.ActualBM\n}",
"func (p *PdfiumImplementation) FPDFBitmap_CreateEx(request *requests.FPDFBitmap_CreateEx) (*responses.FPDFBitmap_CreateEx, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tvar pointer unsafe.Pointer\n\tif request.Buffer != nil {\n\t\tpointer = unsafe.Pointer(&request.Buffer[0])\n\t} else if request.Pointer != nil {\n\t\tv, ok := request.Pointer.(unsafe.Pointer)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"request.Pointer is not of type unsafe.Pointer\")\n\t\t}\n\n\t\tpointer = v\n\t}\n\n\tbitmap := C.FPDFBitmap_CreateEx(C.int(request.Width), C.int(request.Height), C.int(request.Format), pointer, C.int(request.Stride))\n\tbitmapHandle := p.registerBitmap(bitmap)\n\n\treturn &responses.FPDFBitmap_CreateEx{\n\t\tBitmap: bitmapHandle.nativeRef,\n\t}, nil\n}",
"func (renderer *SimpleMatrixRenderer) Render() {\n\trenderer.renderCharacter(\"\\n\")\n\n\tfor row := 0; row < renderer.Matrix.Height; row++ {\n\t\tfor col := 0; col < renderer.Matrix.Width; col++ {\n\t\t\tif !renderer.Matrix.IsFieldOccupied(row, col) {\n\t\t\t\trenderer.renderUnoccupiedField()\n\t\t\t} else {\n\t\t\t\trenderer.renderOccupiedFieldAtCurrentCursorPos(row, col)\n\t\t\t}\n\t\t}\n\n\t\trenderer.renderCharacter(\"\\n\")\n\t}\n\n\trenderer.renderCharacter(\"\\n\")\n}",
"func (self templateEngine) genBoardPage(prefix, frontend, newsgroup string, page int, outfile string, db Database) {\n // get the board model\n board := self.obtainBoard(prefix, frontend, newsgroup, db)\n // update the board page\n board = board.Update(page, db)\n if page >= len(board) {\n log.Println(\"board page should not exist\", newsgroup, \"page\", page)\n return\n }\n // render it\n wr, err := OpenFileWriter(outfile)\n if err == nil {\n updateLinkCacheForBoard(board[page])\n board[page].RenderTo(wr)\n wr.Close()\n log.Println(\"wrote file\", outfile)\n } else {\n log.Println(\"error generating board page\", page, \"for\", newsgroup, err)\n }\n // save it\n self.groups[newsgroup] = board\n}",
"func (blk *Block) drawToPage(page *model.PdfPage) error {\n\n\t// TODO(gunnsth): Appears very wasteful to do this all the time.\n\t// Possibly create another wrapper around model.PdfPage (creator.page) which can keep track of whether\n\t// this has already been done.\n\n\t// Check if Page contents are wrapped - if not wrap it.\n\tcontent, err := page.GetAllContentStreams()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontentParser := contentstream.NewContentStreamParser(content)\n\tops, err := contentParser.Parse()\n\tif err != nil {\n\t\treturn err\n\t}\n\tops.WrapIfNeeded()\n\n\t// Ensure resource dictionaries are available.\n\tif page.Resources == nil {\n\t\tpage.Resources = model.NewPdfPageResources()\n\t}\n\n\t// Merge the contents into ops.\n\terr = mergeContents(ops, page.Resources, blk.contents, blk.resources)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Merge resources for blocks which were created from pages.\n\t// Necessary for adding resources which do not appear in the block contents.\n\tif err = mergeResources(blk.resources, page.Resources); err != nil {\n\t\treturn err\n\t}\n\n\terr = page.SetContentStreams([]string{string(ops.Bytes())}, core.NewFlateEncoder())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Add block annotations to the page.\n\tfor _, annotation := range blk.annotations {\n\t\tpage.AddAnnotation(annotation)\n\t}\n\n\treturn nil\n}",
"func (ui *Plot) Screenshot() {\n\tui.canvas.SetPaintMode(walk.PaintNormal)\n\tdefer func() {\n\t\tui.canvas.SetPaintMode(walk.PaintBuffered)\n\t}()\n\tif hbmp, err := hBitmapFromWindow(ui.canvas); err != nil {\n\t\treturn\n\t} else {\n\t\t// TODO: do we need the mainwindow?\n\t\thBitmapToClipboard(ui.canvas, hbmp)\n\t}\n}",
"func (p *PdfiumImplementation) FPDFBitmap_FillRect(request *requests.FPDFBitmap_FillRect) (*responses.FPDFBitmap_FillRect, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tC.FPDFBitmap_FillRect(bitmapHandle.handle, C.int(request.Left), C.int(request.Top), C.int(request.Width), C.int(request.Height), C.ulong(request.Color))\n\n\treturn &responses.FPDFBitmap_FillRect{}, nil\n}",
"func myVisualiseMatrix(world [][]byte, ImageWidth, ImageHeight int) {\n\tfor i := 0; i < ImageHeight; i++ {\n\t\tfor j := 0; j < ImageWidth; j++ {\n\t\t\tfmt.Print(world[i][j])\n\t\t}\n\t\tfmt.Println()\n\t}\n}",
"func (imd *IMDraw) SetMatrix(m pixel.Matrix) {\n\timd.matrix = m\n\timd.batch.SetMatrix(imd.matrix)\n}",
"func (m *GameMap) Render(gameCamera *camera.GameCamera, newCameraX, newCameraY int) {\n\n\tgameCamera.MoveCamera(newCameraX, newCameraY, m.Width, m.Height)\n\n\tfor x := 0; x < gameCamera.Width; x++ {\n\t\tfor y := 0; y < gameCamera.Height; y++ {\n\n\t\t\tmapX, mapY := gameCamera.X+x, gameCamera.Y+y\n\n\t\t\tif mapX < 0 {\n\t\t\t\tmapX = 0\n\t\t\t}\n\n\t\t\tif mapY < 0 {\n\t\t\t\tmapY = 0\n\t\t\t}\n\n\t\t\ttile := m.Tiles[mapX][mapY]\n\t\t\tcamX, camY := gameCamera.ToCameraCoordinates(mapX, mapY)\n\n\t\t\t// Print the tile, if it meets the following criteria:\n\t\t\t// 1. Its visible or explored\n\t\t\t// 2. It hasn't been printed yet. This will prevent over printing due to camera conversion\n\t\t\tif tile.Visible {\n\t\t\t\tui.PrintGlyph(camX, camY, tile.Glyph, \"\", 0)\n\t\t\t} else if tile.Explored {\n\t\t\t\tui.PrintGlyph(camX, camY, tile.Glyph, \"\", 0, true)\n\t\t\t}\n\t\t}\n\t}\n}",
"func allocPDFRevPageMapMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFRevPageMapValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (d *Device) DrawRGBBitmap8(x, y int16, data []uint8, w, h int16) error {\n\tk, i := d.Size()\n\tif x < 0 || y < 0 || w <= 0 || h <= 0 ||\n\t\tx >= k || (x+w) > k || y >= i || (y+h) > i {\n\t\treturn errOutOfBounds\n\t}\n\td.startWrite()\n\td.setWindow(x, y, w, h)\n\td.bus.Tx(data, nil)\n\td.endWrite()\n\treturn nil\n}",
"func TestGetMemPages(t *testing.T) {\n\ttype testcase struct {\n\t\tname string\n\t\tmr *MemoryReader\n\t\tstart uint64\n\t\tend uint64\n\t\texpectedError error\n\t}\n\n\tpid, err := getTestImgPID()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Create a temporary empty memory pages file for testing\n\ttmpFilePath := filepath.Join(os.TempDir(), \"pages-0.img\")\n\ttmpFile, err := os.Create(tmpFilePath)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdefer func() {\n\t\ttmpFile.Close()\n\t\tif err := os.Remove(tmpFile.Name()); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\tmr, err := NewMemoryReader(testImgsDir, pid, sysPageSize)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ttestCases := []testcase{\n\t\t{\n\t\t\tname: \"Zero memory area size\",\n\t\t\tmr: &MemoryReader{\n\t\t\t\tcheckpointDir: testImgsDir,\n\t\t\t\tpid: pid,\n\t\t\t\tpageSize: sysPageSize,\n\t\t\t\tpagesID: mr.pagesID,\n\t\t\t\tpagemapEntries: mr.GetPagemapEntries(),\n\t\t\t},\n\t\t\tstart: 0,\n\t\t\tend: 0,\n\t\t\texpectedError: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"Valid pagemap entry 1\",\n\t\t\tmr: &MemoryReader{\n\t\t\t\tcheckpointDir: testImgsDir,\n\t\t\t\tpid: pid,\n\t\t\t\tpageSize: sysPageSize,\n\t\t\t\tpagesID: mr.pagesID,\n\t\t\t\tpagemapEntries: mr.GetPagemapEntries(),\n\t\t\t},\n\t\t\tstart: mr.pagemapEntries[0].GetVaddr(),\n\t\t\tend: mr.pagemapEntries[0].GetVaddr() + uint64(uint32(sysPageSize)*mr.pagemapEntries[0].GetNrPages()),\n\t\t\texpectedError: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"Valid pagemap entry 2\",\n\t\t\tmr: &MemoryReader{\n\t\t\t\tcheckpointDir: testImgsDir,\n\t\t\t\tpid: pid,\n\t\t\t\tpageSize: sysPageSize,\n\t\t\t\tpagesID: mr.pagesID,\n\t\t\t\tpagemapEntries: mr.GetPagemapEntries(),\n\t\t\t},\n\t\t\tstart: mr.pagemapEntries[1].GetVaddr(),\n\t\t\tend: mr.pagemapEntries[1].GetVaddr() + uint64(uint32(sysPageSize)*mr.pagemapEntries[1].GetNrPages()),\n\t\t\texpectedError: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"Invalid pages file\",\n\t\t\tmr: &MemoryReader{\n\t\t\t\tcheckpointDir: testImgsDir,\n\t\t\t\tpid: pid,\n\t\t\t\tpageSize: sysPageSize,\n\t\t\t\tpagesID: mr.pagesID + 1,\n\t\t\t\tpagemapEntries: mr.GetPagemapEntries(),\n\t\t\t},\n\t\t\tstart: mr.pagemapEntries[0].GetVaddr(),\n\t\t\tend: mr.pagemapEntries[0].GetVaddr() + uint64(uint32(sysPageSize)*mr.pagemapEntries[0].GetNrPages()),\n\t\t\texpectedError: errors.New(\"no such file or directory\"),\n\t\t},\n\t\t{\n\t\t\tname: \"Empty pages file\",\n\t\t\tmr: &MemoryReader{\n\t\t\t\tcheckpointDir: os.TempDir(),\n\t\t\t\tpid: pid,\n\t\t\t\tpageSize: sysPageSize,\n\t\t\t\tpagesID: 0,\n\t\t\t\tpagemapEntries: mr.GetPagemapEntries(),\n\t\t\t},\n\t\t\tstart: mr.pagemapEntries[1].GetVaddr(),\n\t\t\tend: mr.pagemapEntries[1].GetVaddr() + uint64(uint32(sysPageSize)*mr.pagemapEntries[1].GetNrPages()),\n\t\t\texpectedError: errors.New(\"EOF\"),\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tbuff, err := tc.mr.GetMemPages(tc.start, tc.end)\n\t\t\tif err != nil && tc.expectedError != nil {\n\t\t\t\tif !strings.Contains(err.Error(), tc.expectedError.Error()) {\n\t\t\t\t\tt.Errorf(\"Expected error: %v, got error: %v\", tc.expectedError, err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif tc.expectedError == nil && buff == nil {\n\t\t\t\tt.Errorf(\"Returned memory chunk is expected to be non-empty\")\n\t\t\t}\n\t\t})\n\t}\n}",
"func (p *PdfiumImplementation) FPDFBitmap_Destroy(request *requests.FPDFBitmap_Destroy) (*responses.FPDFBitmap_Destroy, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tC.FPDFBitmap_Destroy(bitmapHandle.handle)\n\n\tdelete(p.bitmapRefs, bitmapHandle.nativeRef)\n\n\treturn &responses.FPDFBitmap_Destroy{}, nil\n}",
"func RenderPage(tpl template.Template, tplData interface{}, outPath string) {\n\t// Create file\n\toutFile, err := os.Create(outPath)\n\tif err != nil {\n\t\tFatal(err.Error())\n\t}\n\tdefer func() {\n\t\toutFile.Close()\n\t}()\n\tdefer wg.Done()\n\t// Template render\n\terr = tpl.Execute(outFile, tplData)\n\tif err != nil {\n\t\tFatal(err.Error())\n\t}\n}",
"func (c *Camera) Render(world, screen *ebiten.Image) error {\n\treturn screen.DrawImage(world, &ebiten.DrawImageOptions{\n\t\tGeoM: c.worldMatrix(),\n\t})\n}",
"func (p *PdfiumImplementation) FPDF_PageToDevice(request *requests.FPDF_PageToDevice) (*responses.FPDF_PageToDevice, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdeviceX := C.int(0)\n\tdeviceY := C.int(0)\n\n\tsuccess := C.FPDF_PageToDevice(pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.double(request.PageX), C.double(request.PageY), &deviceX, &deviceY)\n\tif int(success) == 0 {\n\t\treturn nil, errors.New(\"could not calculate from page to device\")\n\t}\n\n\treturn &responses.FPDF_PageToDevice{\n\t\tDeviceX: int(deviceX),\n\t\tDeviceY: int(deviceY),\n\t}, nil\n}",
"func FrameBuffer(m rv.RenderModel) {\n\tframebuffer(m)\n}",
"func (v *mandelbrotViewer) Draw(screen *ebiten.Image) {\n\tscreen.ReplacePixels(v.screenBuffer)\n\tv.debugPrint(screen)\n}",
"func memoryMap(path string) (*os.File, mmap.MMap, []uint32, error) {\n\tfile, err := os.OpenFile(path, os.O_RDONLY, 0644)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tmem, buffer, err := memoryMapFile(file, false)\n\tif err != nil {\n\t\tfile.Close()\n\t\treturn nil, nil, nil, err\n\t}\n\tfor i, magic := range dumpMagic {\n\t\tif buffer[i] != magic {\n\t\t\tmem.Unmap()\n\t\t\tfile.Close()\n\t\t\treturn nil, nil, nil, ErrInvalidDumpMagic\n\t\t}\n\t}\n\treturn file, mem, buffer[len(dumpMagic):], err\n}",
"func memoryMap(path string) (*os.File, mmap.MMap, []uint32, error) {\n\tfile, err := os.OpenFile(path, os.O_RDONLY, 0644)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tmem, buffer, err := memoryMapFile(file, false)\n\tif err != nil {\n\t\tfile.Close()\n\t\treturn nil, nil, nil, err\n\t}\n\tfor i, magic := range dumpMagic {\n\t\tif buffer[i] != magic {\n\t\t\tmem.Unmap()\n\t\t\tfile.Close()\n\t\t\treturn nil, nil, nil, ErrInvalidDumpMagic\n\t\t}\n\t}\n\treturn file, mem, buffer[len(dumpMagic):], err\n}",
"func CompositorTransferFromImageBitmapOrientation(ctx context.Context, s *testing.State) {\n\tserver := httptest.NewServer(http.FileServer(s.DataFileSystem()))\n\tdefer server.Close()\n\tcr := s.FixtValue().(*chrome.Chrome)\n\n\ttconn, err := cr.TestAPIConn(ctx)\n\tif err != nil {\n\t\ts.Fatal(\"Failed to connect to test API: \", err)\n\t}\n\n\tif err := graphics.RotateDisplayToLandscapePrimary(ctx, tconn); err != nil {\n\t\ts.Fatal(\"Failed to set display to landscape-primary orientation: \", err)\n\t}\n\n\turl := path.Join(server.URL, \"transfer-from-image-bitmap.html\")\n\tconn, err := cr.NewConn(ctx, url)\n\tif err != nil {\n\t\ts.Fatalf(\"Failed to open %v: %v\", url, err)\n\t}\n\tdefer conn.Close()\n\tif err := conn.Call(ctx, nil, \"executeDraw\"); err != nil {\n\t\ts.Fatal(\"Failed to execute drawing function\")\n\t}\n\n\tkb, err := input.Keyboard(ctx)\n\tif err != nil {\n\t\ts.Fatal(\"Failed to initialize the keyboard writer: \", err)\n\t}\n\tdefer kb.Close()\n\n\t// screenshotCanvas requests a fullscreen view of the specified element, takes a screenshot,\n\t// and returns the resulting image.\n\tscreenshotCanvas := func(id string) (image.Image, error) {\n\t\tif err := conn.Call(ctx, nil, \"setFullscreenEventListener\", id); err != nil {\n\t\t\treturn nil, errors.Wrapf(err,\n\t\t\t\t\"failed to set fullscreen event listener on element %v\", id)\n\t\t}\n\t\tif err := kb.Type(ctx, \"f\"); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to inject the 'f' key\")\n\t\t}\n\t\t// Wait for the fullscreen transition to complete and for the escape message to\n\t\t// disappear before taking the screenshot.\n\t\tif err := testing.Sleep(ctx, delayToScreenshot); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to sleep prior to taking screenshot\")\n\t\t}\n\t\tsshotPath := filepath.Join(s.OutDir(), fmt.Sprintf(\"%v.png\", id))\n\t\tif err := screenshot.Capture(ctx, sshotPath); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to capture screenshot of element %v\",\n\t\t\t\tid)\n\t\t}\n\t\tf, err := os.Open(sshotPath)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to open %v\", sshotPath)\n\t\t}\n\t\tdefer f.Close()\n\t\timg, _, err := image.Decode(f)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to decode %v\", sshotPath)\n\t\t}\n\t\treturn img, nil\n\t}\n\n\tparams := s.Param().(params)\n\texpectedImg, err := screenshotCanvas(params.expectedID)\n\tif err != nil {\n\t\ts.Fatalf(\"Failed to screenshot canvas %v: %v\", params.expectedID, err)\n\t}\n\tresultImg, err := screenshotCanvas(params.resultID)\n\tif err != nil {\n\t\ts.Fatalf(\"Failed to screenshot canvas %v: %v\", params.resultID, err)\n\t}\n\n\tif expectedImg.Bounds() != resultImg.Bounds() {\n\t\ts.Fatalf(\"Mismatched image bounds: Expected %v, Actual %v\", expectedImg.Bounds(),\n\t\t\tresultImg.Bounds())\n\t}\n\n\t// Compare colors of pixels from within each image quadrant to verify orientation. Note that\n\t// on non-square displays, the screenshots will have black margins. Correct for this by\n\t// positioning each sample relative to the image center, offset by 1/4 of the smaller image\n\t// dimension (which should generally be height in landscape mode).\n\twidth := expectedImg.Bounds().Dx()\n\theight := expectedImg.Bounds().Dy()\n\tcX := width / 2\n\tcY := height / 2\n\toffset := height / 4\n\tif width < height {\n\t\toffset = width / 4\n\t}\n\tsamples := []image.Point{\n\t\t{cX - offset, cY - offset},\n\t\t{cX - offset, cY + offset},\n\t\t{cX + offset, cY - offset},\n\t\t{cX + offset, cY + offset},\n\t}\n\n\tfor i, sample := range samples {\n\t\treferenceColor := params.referenceColors[i]\n\t\texpectedColor := expectedImg.At(sample.X, sample.Y)\n\t\tif expectedColor != referenceColor {\n\t\t\ts.Errorf(\"Expected image did not match reference color at (%d, %d): \"+\n\t\t\t\t\"Expected %v, Actual %v\",\n\t\t\t\tsample.X, sample.Y, referenceColor, expectedColor)\n\t\t\tcontinue\n\t\t}\n\t\tresultColor := resultImg.At(sample.X, sample.Y)\n\t\tif expectedColor != resultColor {\n\t\t\ts.Errorf(\"Mismatched colors at (%d, %d): Expected %v, Actual %v\", sample.X,\n\t\t\t\tsample.Y, expectedColor, resultColor)\n\t\t}\n\t}\n}",
"func memoryMapFile(file *os.File, write bool) (mmap.MMap, []uint32, error) {\n\t// Try to memory map the file\n\tflag := mmap.RDONLY\n\tif write {\n\t\tflag = mmap.RDWR\n\t}\n\tmem, err := mmap.Map(file, flag, 0)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\t// Yay, we managed to memory map the file, here be dragons\n\theader := *(*reflect.SliceHeader)(unsafe.Pointer(&mem))\n\theader.Len /= 4\n\theader.Cap /= 4\n\n\treturn mem, *(*[]uint32)(unsafe.Pointer(&header)), nil\n}",
"func memoryMapFile(file *os.File, write bool) (mmap.MMap, []uint32, error) {\n\t// Try to memory map the file\n\tflag := mmap.RDONLY\n\tif write {\n\t\tflag = mmap.RDWR\n\t}\n\tmem, err := mmap.Map(file, flag, 0)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\t// Yay, we managed to memory map the file, here be dragons\n\theader := *(*reflect.SliceHeader)(unsafe.Pointer(&mem))\n\theader.Len /= 4\n\theader.Cap /= 4\n\n\treturn mem, *(*[]uint32)(unsafe.Pointer(&header)), nil\n}",
"func (bc *BC) dmEncoder(file io.Writer, txt string) error {\n\n\t// Encode qr code\n\tqr, err := datamatrix.Encode(txt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Scale to size w x h\n\tqr, err = barcode.Scale(qr, bc.w, bc.h)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t// encode as png to io.Writer\n\treturn png.Encode(file, qr)\n}",
"func (c *Canvas) SetMatrix(m pixel.Matrix) {\n\tfor i := range m {\n\t\tc.mat[i] = float32(m[i])\n\t}\n}",
"func GetPDFPage(pdfName string, imageName string, pageNum int) error {\n\n\tabsPath, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tInpath := filepath.Join(absPath, \"input\", pdfName)\n\tOutpath := filepath.Join(absPath, \"output\")\n\n\tif _, err := os.Stat(Outpath); os.IsNotExist(err) {\n\t\tlog.Println(\"Output dir not found. Creating at \", Outpath)\n\t\tos.Mkdir(Outpath, os.ModePerm)\n\t}\n\n\timagick.Initialize()\n\tdefer imagick.Terminate()\n\n\tmw := imagick.NewMagickWand()\n\tdefer mw.Destroy()\n\n\tif err := mw.SetResolution(72, 72); err != nil {\n\t\treturn err\n\t}\n\n\t// Load the image file into imagick\n\tif err := mw.ReadImage(Inpath); err != nil {\n\t\treturn err\n\t}\n\n\tmw.SetIteratorIndex(pageNum - 1)\n\n\t// Set any compression (100 = max quality)\n\tif err := mw.SetCompressionQuality(100); err != nil {\n\t\treturn err\n\t}\n\n\t// Convert into JPG\n\tif err := mw.SetFormat(\"jpg\"); err != nil {\n\t\treturn err\n\t}\n\n\t// Save File\n\treturn mw.WriteImage(filepath.Join(Outpath, imageName))\n}",
"func (c *Canvas) DrawBitmapPart(bmp *Bitmap, dst, src Rectangle) error {\n\treturn c.DrawBitmapPartWithOpacityPixels(bmp, dst, src, 0xff)\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetBuffer(request *requests.FPDFBitmap_GetBuffer) (*responses.FPDFBitmap_GetBuffer, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We need to calculate the buffer size, this is stride (bytes per bitmap line) * height.\n\tstride := C.FPDFBitmap_GetStride(bitmapHandle.handle)\n\theight := C.FPDFBitmap_GetHeight(bitmapHandle.handle)\n\tsize := int(stride * height)\n\n\t// The pointer to the first byte of the bitmap buffer.\n\tbuffer := C.FPDFBitmap_GetBuffer(bitmapHandle.handle)\n\n\t// We create a Go slice backed by a C array (without copying the original data).\n\tdata := unsafe.Slice((*byte)(unsafe.Pointer(buffer)), uint64(size))\n\n\treturn &responses.FPDFBitmap_GetBuffer{\n\t\tBuffer: data,\n\t}, nil\n}",
"func (b *Builder) MapMemory(rng memory.Range) {\n\tif ty := b.peekStack().ty; ty != protocol.Type_AbsolutePointer {\n\t\tpanic(fmt.Errorf(\"MapMemory can only map to absolute pointers. Got type: %v\", ty))\n\t}\n\n\t// Allocate memory to hold the target mapped base address.\n\t// Do not release the memory as it may be used during frame loop.\n\ttarget := b.AllocateMemory(uint64(b.memoryLayout.GetPointer().GetSize()))\n\tb.Store(target)\n\n\ts := rng.Span()\n\ti := interval.Merge(&b.mappedMemory, s, false)\n\tif b.mappedMemory[i].Span() != s {\n\t\tpanic(fmt.Errorf(\"MapMemory range (%v) collides with existing mapped range (%v)\",\n\t\t\trng, b.mappedMemory[i]))\n\t}\n\n\tb.mappedMemory[i].Target = target\n}",
"func (m *marshalerMessage) addBitmap(marsh MarshalerBitmap, tag tags) {\n\tm.Bitmaps = append(m.Bitmaps, isoMarshalerBitmap{MarshalerBitmap: marsh, tags: tag})\n}",
"func NewPage(mediaBox, cropBox *types.Rectangle) Page {\n\treturn Page{\n\t\tMediaBox: mediaBox,\n\t\tCropBox: cropBox,\n\t\tFm: FontMap{},\n\t\tIm: ImageMap{},\n\t\tAnnotTabs: map[int]FieldAnnotation{},\n\t\tBuf: new(bytes.Buffer)}\n}",
"func (b *Buffer) Dump() {\n\ts := *b.screen\n\traster := canvas.NewRasterFromImage(b.context.Image())\n\ts.SetContent(raster)\n}",
"func WriteMatrix(pattern []rune, text []rune, matrix [][]int, writer io.Writer) {\n\tfmt.Fprintf(writer, \" \")\n\tfor _, textRune := range text {\n\t\tfmt.Fprintf(writer, \" %c\", textRune)\n\t}\n\tfmt.Fprintf(writer, \"\\n\")\n\tfmt.Fprintf(writer, \" %2d\", matrix[0][0])\n\tfor j := range text {\n\t\tfmt.Fprintf(writer, \" %2d\", matrix[0][j+1])\n\t}\n\tfmt.Fprintf(writer, \"\\n\")\n\tfor i, patternRune := range pattern {\n\t\tfmt.Fprintf(writer, \"%c %2d\", patternRune, matrix[i+1][0])\n\t\tfor j := range text {\n\t\t\tfmt.Fprintf(writer, \" %2d\", matrix[i+1][j+1])\n\t\t}\n\t\tfmt.Fprintf(writer, \"\\n\")\n\t}\n\n}",
"func encodePBM(w io.Writer, img image.Image, opts *EncodeOptions) error {\n\t// Write the PBM header.\n\tif opts.Plain {\n\t\tfmt.Fprintln(w, \"P1\")\n\t} else {\n\t\tfmt.Fprintln(w, \"P4\")\n\t}\n\tfor _, cmt := range opts.Comments {\n\t\tcmt = strings.Replace(cmt, \"\\n\", \" \", -1)\n\t\tcmt = strings.Replace(cmt, \"\\r\", \" \", -1)\n\t\tfmt.Fprintf(w, \"# %s\\n\", cmt)\n\t}\n\trect := img.Bounds()\n\twidth := rect.Max.X - rect.Min.X\n\theight := rect.Max.Y - rect.Min.Y\n\tfmt.Fprintf(w, \"%d %d\\n\", width, height)\n\n\t// Write the PBM data.\n\treturn encodeBWData(w, img, opts)\n}",
"func allocPDFPageMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFPageValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func drawBackground(image *image.RGBA, mem *GBMem) *image.RGBA {\n\tfor x := 0; x < MapWidth; x++ {\n\t\tfor y := 0; y < MapHeight; y++ {\n\t\t\t// get tile index\n\t\t\ttileIndex := mem.read(uint16(VRAMBackgroundMap + x + (y * MapHeight)))\n\n\t\t\t// get pixels corresponding to tile index\n\t\t\tpixels := tileToPixel(tileIndex, mem)\n\n\t\t\t// draw pixels\n\t\t\tdrawTilePixels(image, pixels, x, y)\n\t\t}\n\t}\n\treturn image\n}",
"func renderPage(w io.Writer, name string, pageData PageData) {\n\trenderTemplate(w, name, pageData)\n}",
"func RenderPage(c *fiber.Ctx, filename string, bind fiber.Map) {\n\tfp := &mustache.FileProvider{\n\t\tPaths: []string{\"\", \"/src/http/views/\"},\n\t\tExtensions: []string{\"\", \".mustache\"},\n\t}\n\n\tlayoutTmpl, err := mustache.ParseFilePartials(file(\"layout\"), fp)\n\tif err != nil {\n\t\tc.SendStatus(500)\n\t\tc.SendString(err.Error())\n\t\treturn\n\t}\n\n\ttmpl, err := mustache.ParseFilePartials(file(filename), fp)\n\tif err != nil {\n\t\tc.SendStatus(500)\n\t\tc.SendString(err.Error())\n\t\treturn\n\t}\n\n\thtml, err := tmpl.RenderInLayout(layoutTmpl, bind)\n\tif err != nil {\n\t\tc.SendStatus(500)\n\t\tc.SendString(err.Error())\n\t\treturn\n\t}\n\n\tc.Set(\"Content-Type\", \"text/html\")\n\tc.SendString(html)\n}",
"func (r ApiGetBitlinksByGroupRequest) Page(page int32) ApiGetBitlinksByGroupRequest {\n\tr.page = &page\n\treturn r\n}",
"func PrintMatrixBuffer(m TransposableMatrix) {\n\n\tsl := m.Slots()\n\tfor k1, ssl := range sl {\n\t\thasCont := false\n\t\tfor k2, slot := range ssl {\n\t\t\tif slot.AmX != nil {\n\t\t\t\tpf(\"%v-%v: %v%v |\", k1, k2, slot.AmX.Cols, slot.AmX.Rows)\n\t\t\t\thasCont = true\n\t\t\t}\n\t\t}\n\t\tif hasCont == true {\n\t\t\tpf(\"\\n\")\n\t\t}\n\t}\n\n}",
"func (b *Bitmap) ToImage() image.Image {\n\timg := image.NewGray(image.Rect(0, 0, b.Width-1, b.Height-1))\n\tfor x := 0; x < b.Width; x++ {\n\t\tfor y := 0; y < b.Height; y++ {\n\t\t\tc := color.Black\n\t\t\tif b.GetPixel(x, y) {\n\t\t\t\tc = color.White\n\t\t\t}\n\t\t\timg.Set(x, y, c)\n\t\t}\n\t}\n\treturn img\n}",
"func allocPDFCmapMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFCmapValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (m *Matrix) Draw(canvas *drawing.Canvas, strat Strategy) {\n\tpath := canvas.GetContext()\n\tpath.SetFillColor(color.RGBA{0xaa, 0xaa, 0xaa, 0xff})\n\tpath.SetStrokeColor(color.RGBA{0x99, 0x99, 0x99, 0xff})\n\tpath.SetLineWidth(2)\n\tdrawing.DrawSquare(0.0, 0.0, 1.0, 1.0, path)\n\tlog.Info(\"filling the background of the image, this might take some seconds\")\n\tpath.FillStroke()\n\tm.drawSquares(canvas, strat)\n}",
"func MatrixFrustum(left, right, bottom, top, near, far float32) Matrix {\n\tvar result Matrix\n\n\trl := right - left\n\ttb := top - bottom\n\tfn := far - near\n\n\tresult.M0 = (near * 2.0) / rl\n\tresult.M1 = 0.0\n\tresult.M2 = 0.0\n\tresult.M3 = 0.0\n\n\tresult.M4 = 0.0\n\tresult.M5 = (near * 2.0) / tb\n\tresult.M6 = 0.0\n\tresult.M7 = 0.0\n\n\tresult.M8 = right + left/rl\n\tresult.M9 = top + bottom/tb\n\tresult.M10 = -(far + near) / fn\n\tresult.M11 = -1.0\n\n\tresult.M12 = 0.0\n\tresult.M13 = 0.0\n\tresult.M14 = -(far * near * 2.0) / fn\n\tresult.M15 = 0.0\n\n\treturn result\n}",
"func (_m *HostMemoryManager) ReportManagedObject(table string, shard int, batchID int, columnID int, bytes int64) {\n\t_m.Called(table, shard, batchID, columnID, bytes)\n}",
"func allocPDFGraftMapMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFGraftMapValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (d *Drawer) DrawMap(ctx *gg.Context) error {\n\n\tsz := ctx.Height()\n\tyCounter := 0\n\txCounter := 0\n\tdrawCounter := 0\n\tdrawLimit := math.Pow(float64(sz/squareSize), float64(2))\n\n\tfor i := 0; drawCounter <= int(drawLimit); i += squareSize {\n\t\tdrawCounter++\n\t\tpickColour(ctx, i)\n\n\t\tdrawRectangle(ctx, dimensions{\n\t\t\tx: float64(xCounter),\n\t\t\ty: float64(yCounter),\n\t\t\tw: float64(squareSize),\n\t\t\th: float64(squareSize),\n\t\t})\n\n\t\txCounter += squareSize\n\n\t\tif drawCounter%(sz/squareSize) == 0 {\n\t\t\tyCounter += squareSize\n\t\t\txCounter = 0\n\t\t}\n\t}\n\n\terr := ctx.SavePNG(\"out.png\")\n\treturn err\n}",
"func GetPDFPages(inPath string, outPath string, frames []parser.Section) error {\n\n\tif _, err := os.Stat(outPath); os.IsNotExist(err) {\n\t\tlog.Println(\"Output dir not found. Creating at \", outPath)\n\t\terr := os.Mkdir(outPath, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"[PDF Extractor] %s\", err)\n\t\t}\n\t}\n\n\timagick.Initialize()\n\tdefer imagick.Terminate()\n\n\tmw := imagick.NewMagickWand()\n\tdefer mw.Destroy()\n\n\tif err := mw.SetResolution(300, 300); err != nil {\n\t\treturn err\n\t}\n\n\t// Load the image file into imagick\n\tif err := mw.ReadImage(inPath); err != nil {\n\t\treturn err\n\t}\n\n\t// fmt.Println(mw.GetNumberImages())\n\n\t// Set any compression (100 = max quality)\n\tif err := mw.SetCompressionQuality(100); err != nil {\n\t\treturn err\n\t}\n\n\tif err := mw.SetFormat(\"jpg\"); err != nil {\n\t\treturn err\n\t}\n\tvar err error\n\tfor _, frame := range frames {\n\n\t\tmw.SetIteratorIndex(frame.Page - 1)\n\n\t\t// if err := mw.SetImageFormat(\"jpeg\"); err != nil {\n\t\t// \treturn err\n\t\t// }\n\n\t\t// Save File\n\t\terr = mw.WriteImage(filepath.Join(outPath, frame.FrameSrc.ImageSrc))\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%s [PDF extraction: page: %d, loc: %s, to %s] \", err, frame.Page, inPath, filepath.Join(outPath, frame.FrameSrc.ImageSrc))\n\t\t}\n\n\t}\n\treturn nil\n}",
"func (p *Process) MemoryMaps(grouped bool) (*[]MemoryMapsStat, error) {\n\treturn p.MemoryMapsWithContext(context.Background(), grouped)\n}",
"func PdfToImage(w io.Writer, r io.Reader, contentType, size string) error {\n\tsrc := temp.NewMemorySlurper(\"PdfToImage-src-\")\n\tdefer src.Close()\n\tdst := temp.NewMemorySlurper(\"PdfToImage-dst-\")\n\tdefer dst.Close()\n\n\tvar err error\n\tif err = PdfToImageCairo(dst, io.TeeReader(r, src), contentType, size); err == nil {\n\t\t_, err = io.Copy(w, dst)\n\t\treturn err\n\t}\n\tlogger.Error(\"msg\", \"PdfToImageCairo\", \"error\", err)\n\treturn PdfToImageGm(w, io.MultiReader(src, r), contentType, size)\n}",
"func (a *World) Render(p *pic.Pic) *World {\n\th, w := p.H, p.W\n\tfh, fw := float64(h), float64(w)\n\tcx := vec.New(fw*a.Ratio/fh, 0, 0)\n\tcy := vec.Mult(vec.Norm(vec.Cross(cx, a.Cam.Direct)), a.Ratio)\n\tsample := a.Sample / 4\n\tinv := 1.0 / float64(sample)\n\n\tfmt.Printf(\"w: %v, h: %v, sample: %v, actual sample: %v, thread: %v, cpu: %v\\n\", w, h, a.Sample, sample*4, a.Thread, a.Core)\n\tbar := pb.StartNew(h * w)\n\tbar.SetRefreshRate(1000 * time.Millisecond)\n\n\truntime.GOMAXPROCS(a.Core)\n\tch := make(chan renderData, a.Thread)\n\twg := sync.WaitGroup{}\n\twg.Add(a.Thread)\n\n\tfor tid := 0; tid < a.Thread; tid++ {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tdata, ok := <-ch\n\t\t\t\tif !ok {\n\t\t\t\t\twg.Done()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tsum, x, y := data.sum, data.x, data.y\n\t\t\t\tfor sy := 0.0; sy < 2.0; sy++ {\n\t\t\t\t\tfor sx := 0.0; sx < 2.0; sx++ {\n\t\t\t\t\t\tc := vec.NewZero()\n\t\t\t\t\t\tfor sp := 0; sp < sample; sp++ {\n\t\t\t\t\t\t\tccx := vec.Mult(cx, ((sx+0.5+gend())/2.0+x)/fw-0.5)\n\t\t\t\t\t\t\tccy := vec.Mult(cy, ((sy+0.5+gend())/2.0+y)/fh-0.5)\n\t\t\t\t\t\t\td := vec.Add(vec.Add(ccx, ccy), a.Cam.Direct)\n\t\t\t\t\t\t\tr := ray.New(vec.Add(a.Cam.Origin, vec.Mult(d, 130)), vec.Norm(d))\n\t\t\t\t\t\t\tc.Add(vec.Mult(a.trace(r, 0), inv))\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsum.Add(vec.Mult(vec.New(pic.Clamp(c.X), pic.Clamp(c.Y), pic.Clamp(c.Z)), 0.25))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbar.Add(1)\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor y := 0; y < h; y++ {\n\t\tfor x := 0; x < w; x++ {\n\t\t\tch <- renderData{\n\t\t\t\tsum: &p.C[(h-y-1)*w+x],\n\t\t\t\tx: float64(x),\n\t\t\t\ty: float64(y),\n\t\t\t}\n\t\t}\n\t}\n\n\tclose(ch)\n\twg.Wait()\n\n\tbar.FinishPrint(\"Rendering completed\")\n\treturn a\n}",
"func MapBuffer(target uint32, access uint32) unsafe.Pointer {\n\tret := C.glowMapBuffer(gpMapBuffer, (C.GLenum)(target), (C.GLenum)(access))\n\treturn (unsafe.Pointer)(ret)\n}",
"func MapBuffer(target uint32, access uint32) unsafe.Pointer {\n\tret := C.glowMapBuffer(gpMapBuffer, (C.GLenum)(target), (C.GLenum)(access))\n\treturn (unsafe.Pointer)(ret)\n}",
"func Render(c *Camera, w *world.World) (*canvas.Canvas, error) {\n\timage := canvas.NewCanvas(c.horizontalSizeInPixels, c.verticalSizeInPixels)\n\n\t// For each pixel of the camera\n\tfor y := 0; y < c.verticalSizeInPixels; y++ {\n\t\tfor x := 0; x < c.horizontalSizeInPixels; x++ {\n\t\t\t// Compute the ray for the current pixel\n\t\t\tr, err := RayForPixel(c, x, y)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t// Intersect the ray with the world to get the color at the intersection\n\t\t\tc, err := world.ColorAt(w, r)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t// Write the color to the canvas at the current pixel\n\t\t\terr = image.WritePixel(x, y, *c)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn image, nil\n}",
"func (b *Bitmaps) GetBitmap(i int) (*Bitmap, error) {\n\tconst processName = \"GetBitmap\"\n\tif b == nil {\n\t\treturn nil, errors.Error(processName, \"provided nil Bitmaps\")\n\t}\n\tif i > len(b.Values)-1 {\n\t\treturn nil, errors.Errorf(processName, \"index: '%d' out of range\", i)\n\t}\n\treturn b.Values[i], nil\n}",
"func (p *PdfiumImplementation) FPDF_RenderPage(request *requests.FPDF_RenderPage) (*responses.FPDF_RenderPage, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thdc, ok := request.DC.(C.HDC)\n\tif !ok {\n\t\treturn nil, errors.New(\"DC is not of type C.HDC\")\n\t}\n\n\tC.FPDF_RenderPage(hdc, pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.int(request.Flags))\n\n\treturn &responses.FPDF_RenderPage{}, nil\n}",
"func allocPDFWidgetMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFWidgetValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (mbc *MBC1) WriteMemory(address uint16, value byte) {\n\tif address < 0x2000 {\n\t\t// Any value with 0x0a in the lower 4 bits enables RAM and other values disable it\n\t\tmbc.ramEnabled = value&0x0f == 0x0a\n\t} else if address < 0x4000 {\n\t\t// Set lower bits for ROM bank number\n\t\tbank := (mbc.romBankNumber & 0xe0) | (value & 0x1f)\n\t\tmbc.selectRomBank(bank)\n\t} else if address < 0x6000 {\n\t\t// Select RAM bank or set higher bits for ROM bank number\n\t\tif mbc.romBanking {\n\t\t\tbank := (mbc.romBankNumber & 0x1f) | (value & 0xe0)\n\t\t\tmbc.selectRomBank(bank)\n\t\t} else {\n\t\t\tmbc.selectRamBank(value & 0x03)\n\t\t}\n\t} else if address < 0x8000 {\n\t\t// Select ROM/RAM banking mode\n\t\tmbc.romBanking = value&1 == 0\n\t\tif mbc.romBanking {\n\t\t\tmbc.selectRamBank(0)\n\t\t} else {\n\t\t\tmbc.selectRomBank(mbc.romBankNumber & 0x1f)\n\t\t}\n\t} else if address >= 0xa000 && address < 0xc000 {\n\t\t// Write to RAM\n\t\tif mbc.ramEnabled {\n\t\t\tmbc.ram[mbc.mapAddressToRam(address)] = value\n\t\t}\n\t}\n}",
"func debugPrintMatrix(matrix ImageMatrix) {\n\tfor x, rows := range matrix {\n\t\tfor y, colour := range rows {\n\t\t\tfmt.Printf(\"x:%v y:%v colour:%v\\n\", x, y, colour)\n\t\t}\n\t}\n}",
"func (t *Transform) Matrix(a, b, c, d, e, f float64) {\n\tout := fmt.Sprintf(\"matrix(%g,%g,%g,%g,%g,%g)\", a, b, c, d, e, f)\n\n\tt.transforms = append(t.transforms, out)\n}",
"func renderPage(w http.ResponseWriter, tmpl string, data interface{}) {\n\tif err := templates.ExecuteTemplate(w, tmpl, data); err != nil {\n\t\tfmt.Fprintf(w, \"Error %v\", err)\n\t}\n}",
"func (b *Bitmaps) AddBitmap(bm *Bitmap) {\n\tb.Values = append(b.Values, bm)\n}",
"func (b *Bitmap) Image() (image.Image, error) {\n\t// TODO Support the other pixel modes\n\tswitch b.PixelMode() {\n\tcase PixelModeNone, PixelModeMono, PixelModeGray2, PixelModeGray4, PixelModeLCD, PixelModeLCDV:\n\t\treturn nil, ErrUnsupportedPixelMode\n\tcase PixelModeBGRA:\n\t\treturn b.NRGBA()\n\tcase PixelModeGray:\n\t\treturn b.GrayImage()\n\t}\n\treturn nil, ErrUnsupportedPixelMode\n}",
"func (c *Container) setBitmap(bitmap []uint64) {\n\tif c == nil || c.frozen() {\n\t\tpanic(\"setBitmap on nil or frozen container\")\n\t}\n\tif roaringParanoia {\n\t\tif c.typeID != ContainerBitmap {\n\t\t\tpanic(\"attempt to write non-bitmap's bitmap\")\n\t\t}\n\t}\n\tif len(bitmap) != 1024 {\n\t\tpanic(fmt.Sprintf(\"illegal bitmap length %v\", len(bitmap)))\n\t}\n\tc.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&bitmap[0])), bitmapN, bitmapN\n\tc.flags &^= flagPristine\n}",
"func (mm *atmanMemoryManager) allocPage(page vaddr) {\n\tvar (\n\t\tl4offset = page.pageTableOffset(pageTableLevel4)\n\t\tl3offset = page.pageTableOffset(pageTableLevel3)\n\t\tl2offset = page.pageTableOffset(pageTableLevel2)\n\t\tl1offset = page.pageTableOffset(pageTableLevel1)\n\t)\n\n\tl4 := mm.l4\n\tl3pte := l4.Get(l4offset)\n\n\tif !l3pte.hasFlag(xenPageTablePresent) {\n\t\tpfn := mm.physAllocPage()\n\t\tl3pte = mm.writePte(mm.l4PFN, l4offset, pfn, PTE_PAGE_TABLE_FLAGS|xenPageTableWritable)\n\t}\n\n\tl3 := mm.getPageTable(-1, -1, l4offset)\n\tl2pte := l3.Get(l3offset)\n\n\tif !l2pte.hasFlag(xenPageTablePresent) {\n\t\tpfn := mm.physAllocPage()\n\t\tl2pte = mm.writePte(l3pte.pfn(), l3offset, pfn, PTE_PAGE_TABLE_FLAGS|xenPageTableWritable)\n\t}\n\n\tl2 := mm.getPageTable(-1, l4offset, l3offset)\n\tl1pte := l2.Get(l2offset)\n\n\tif !l1pte.hasFlag(xenPageTablePresent) {\n\t\tpfn := mm.physAllocPage()\n\t\tl1pte = mm.writePte(l2pte.pfn(), l2offset, pfn, PTE_PAGE_TABLE_FLAGS|xenPageTableWritable)\n\t}\n\n\tpagepfn := mm.physAllocPage()\n\tmm.writePte(l1pte.pfn(), l1offset, pagepfn, PTE_PAGE_FLAGS)\n\n\t// ensure page is writable\n\t*(*uintptr)(unsafe.Pointer(page)) = 0x0\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetStride(request *requests.FPDFBitmap_GetStride) (*responses.FPDFBitmap_GetStride, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstride := C.FPDFBitmap_GetStride(bitmapHandle.handle)\n\treturn &responses.FPDFBitmap_GetStride{\n\t\tStride: int(stride),\n\t}, nil\n}",
"func allocPDFHmtxMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFHmtxValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (montage *Montage) DrawImageIntoLayout(layout *ImagePlacement, imageData []byte) error {\n\t// var m runtime.MemStats\n\t// runtime.ReadMemStats(&m)\n\t// logger.Info(\"drawImageOfTopic entry Memory: \", m.Alloc)\n\n\tbuffer := bytes.NewBuffer(imageData)\n\t// Decode takes 85% of all cpu: https://github.com/golang/go/issues/24499\n\timg, imageType, err := image.Decode(buffer)\n\n\tif err != nil {\n\t\tlogrus.Errorf(\"montage.DrawImageIntoLayout: Failed decoding image '%s' for montage '%s': %s\",\n\t\t\tlayout.Source, montage.Config.Name, err)\n\t\treturn err\n\t}\n\tlogrus.Debugf(\"montage.DrawImageIntoLayout: Image of layout %s of type %s decoded\", layout.Source, imageType)\n\terr = montage.drawImage(img, layout)\n\treturn err\n}",
"func getBitmap(file *os.File, index int64, size int64) []byte {\n\tbitMap := make([]byte, size)\n\tfile.Seek(index, 0)\n\t//Se obtiene la data del archivo binarios\n\tdata := readNextBytes(file, size)\n\tbuffer := bytes.NewBuffer(data)\n\t//Se asigna al mbr declarado para leer la informacion de ese disco\n\terr := binary.Read(buffer, binary.BigEndian, &bitMap)\n\tif err != nil {\n\t\tlog.Fatal(\"binary.Read failed\", err)\n\t}\n\treturn bitMap\n}",
"func allocFzBitmapMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzBitmapValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetFormat(request *requests.FPDFBitmap_GetFormat) (*responses.FPDFBitmap_GetFormat, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tformat := C.FPDFBitmap_GetFormat(bitmapHandle.handle)\n\n\treturn &responses.FPDFBitmap_GetFormat{\n\t\tFormat: enums.FPDF_BITMAP_FORMAT(format),\n\t}, nil\n}",
"func tileToPixel(tileIndex uint8, mem *GBMem) [TileHeight][TileWidth]color.RGBA {\n\tvar pixels [TileHeight][TileWidth]color.RGBA\n\tfor y := 0; y < TileHeight; y++ {\n\t\tvar line [TileWidth]color.RGBA\n\t\tlsb := mem.vram[int(tileIndex)*16+2*y]\n\t\thsb := mem.vram[int(tileIndex)*16+2*y+1]\n\n\t\tfor x := 0; x < TileWidth; x++ {\n\t\t\tline[TileWidth-1-x] = paletteMap[compositePixel(lsb, hsb, uint8(x))]\n\t\t}\n\t\tpixels[y] = line\n\t}\n\treturn pixels\n}",
"func MapViewOfFile(hFileMappingObject HANDLE, dwDesiredAccess DWORD, dwFileOffsetHigh DWORD, dwFileOffsetLow DWORD, dwNumberOfBytesToMap SIZE_T) LPVOID {\n\tret1 := syscall6(mapViewOfFile, 5,\n\t\tuintptr(hFileMappingObject),\n\t\tuintptr(dwDesiredAccess),\n\t\tuintptr(dwFileOffsetHigh),\n\t\tuintptr(dwFileOffsetLow),\n\t\tuintptr(dwNumberOfBytesToMap),\n\t\t0)\n\treturn (LPVOID)(unsafe.Pointer(ret1))\n}",
"func TestMemoryLayout(t *testing.T) {\n\tm4 := M4{\n\t\t11, 12, 13, 14,\n\t\t21, 22, 23, 24,\n\t\t31, 32, 33, 34,\n\t\t41, 42, 43, 44}\n\toneFloat := uint64(unsafe.Sizeof(m4.X0))\n\tfourFloats := oneFloat * 4\n\tmema, _ := strconv.ParseUint(fmt.Sprintf(\"%d\", &(m4.X0)), 0, 64)\n\tmemb, _ := strconv.ParseUint(fmt.Sprintf(\"%d\", &(m4.Y0)), 0, 64) // next value.\n\tif memb-mema != oneFloat {\n\t\tt.Errorf(\"Next value should be %d bytes. Was %d\", oneFloat, memb-mema)\n\t}\n\tmemc, _ := strconv.ParseUint(fmt.Sprintf(\"%d\", &(m4.X1)), 0, 64) // next row.\n\tif memc-mema != fourFloats {\n\t\tt.Errorf(\"Next row should be %d bytes. Was %d\", fourFloats, memc-mema)\n\t}\n}",
"func (b *XMobileBackend) GetImageData(x, y, w, h int) *image.RGBA {\n\tb.activate()\n\n\tif x < 0 {\n\t\tw += x\n\t\tx = 0\n\t}\n\tif y < 0 {\n\t\th += y\n\t\ty = 0\n\t}\n\tif w > b.w {\n\t\tw = b.w\n\t}\n\tif h > b.h {\n\t\th = b.h\n\t}\n\n\tvar vp [4]int32\n\tb.glctx.GetIntegerv(vp[:], gl.VIEWPORT)\n\n\tsize := int(vp[2] * vp[3] * 3)\n\tif len(b.imageBuf) < size {\n\t\tb.imageBuf = make([]byte, size)\n\t}\n\tb.glctx.ReadPixels(b.imageBuf[0:], int(vp[0]), int(vp[1]), int(vp[2]), int(vp[3]), gl.RGB, gl.UNSIGNED_BYTE)\n\n\trgba := image.NewRGBA(image.Rect(x, y, x+w, y+h))\n\tfor cy := y; cy < y+h; cy++ {\n\t\tbp := (int(vp[3])-h+cy)*int(vp[2])*3 + x*3\n\t\tfor cx := x; cx < x+w; cx++ {\n\t\t\trgba.SetRGBA(cx, y+h-1-cy, color.RGBA{R: b.imageBuf[bp], G: b.imageBuf[bp+1], B: b.imageBuf[bp+2], A: 255})\n\t\t\tbp += 3\n\t\t}\n\t}\n\treturn rgba\n}",
"func allocFzStextPageMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzStextPageValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func VerifyGraphicsMemory(ctx context.Context, payload func() error, backend Backend, sizes []Size) (err error) {\n\ttesting.ContextLogf(ctx, \"Cooling down %v after log in\", coolDownTimeAfterLogin)\n\tif err := testing.Sleep(ctx, coolDownTimeAfterLogin); err != nil {\n\t\treturn errors.Wrap(err, \"error while cooling down after log in\")\n\t}\n\n\tvar roundedSizes []Size\n\tfor _, size := range sizes {\n\t\troundedSizes = append(roundedSizes, Size{Width: backend.Round(size.Width), Height: backend.Round(size.Height)})\n\t}\n\n\tif len(sizes) == 1 {\n\t\treturn compareGraphicsMemoryBeforeAfter(ctx, payload, backend, roundedSizes[0].Width, roundedSizes[0].Height)\n\t}\n\treturn monitorGraphicsMemoryDuring(ctx, payload, backend, roundedSizes, maxGraphicsObjects)\n}",
"func PageFile(name, version, size string, path, links, lines []string) *Renderer {\n\treturn &Renderer{\n\t\tfilenames: []string{\n\t\t\t\"templates/layout.html\",\n\t\t\t\"templates/logo.html\",\n\t\t\t\"templates/pages/file.html\",\n\t\t},\n\t\tcontext: struct {\n\t\t\tPackage string\n\t\t\tVersion string\n\t\t\tSize string\n\t\t\tPath []string\n\t\t\tPathLinks []string\n\t\t\tLines []string\n\t\t}{\n\t\t\tPackage: name,\n\t\t\tVersion: version,\n\t\t\tSize: size,\n\t\t\tPath: path,\n\t\t\tPathLinks: links,\n\t\t\tLines: append([]string{\"\"}, lines...),\n\t\t},\n\t}\n}",
"func allocPDFMrangeMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFMrangeValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (r Virtual_Guest) GetMemoryMetricImageByDate(startDateTime *datatypes.Time, endDateTime *datatypes.Time) (resp datatypes.Container_Bandwidth_GraphOutputs, err error) {\n\tparams := []interface{}{\n\t\tstartDateTime,\n\t\tendDateTime,\n\t}\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getMemoryMetricImageByDate\", params, &r.Options, &resp)\n\treturn\n}",
"func (p *PdfiumImplementation) FPDF_DeviceToPage(request *requests.FPDF_DeviceToPage) (*responses.FPDF_DeviceToPage, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpageX := C.double(0)\n\tpageY := C.double(0)\n\n\tsuccess := C.FPDF_DeviceToPage(pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.int(request.DeviceX), C.int(request.DeviceY), &pageX, &pageY)\n\tif int(success) == 0 {\n\t\treturn nil, errors.New(\"could not calculate from device to page\")\n\t}\n\n\treturn &responses.FPDF_DeviceToPage{\n\t\tPageX: float64(pageX),\n\t\tPageY: float64(pageY),\n\t}, nil\n}",
"func newBitmap(size int) *bitmap {\n\tdiv, mod := size/8, size%8\n\tif mod > 0 {\n\t\tdiv++\n\t}\n\treturn &bitmap{size, make([]byte, div)}\n}",
"func (w *dewindow) realpaint(buf *demodel.CharBuffer, viewport *viewer.Viewport) {\n\tw.Lock()\n\tdefer w.Unlock()\n\n\tdefer func() {\n\t\tw.painting = false\n\t}()\n\tw.painting = true\n\n\tif w.buffer == nil {\n\t\treturn\n\t}\n\tdst := w.buffer.RGBA()\n\n\t// Fill the buffer with the window background colour before\n\t// drawing the web page on top of it.\n\t// This should logically be in the viewport code itself, but importing\n\t// kbmap to switch on the mode sentinals would result in a cyclical\n\t// import.\n\tif viewport.BackgroundMode != viewer.StableBackground {\n\t\tswitch viewport.GetKeyboardMode() {\n\t\tcase kbmap.InsertMode:\n\t\t\tdraw.Draw(dst, dst.Bounds(), &image.Uniform{renderer.InsertBackground}, image.ZP, draw.Src)\n\t\tcase kbmap.DeleteMode:\n\t\t\tdraw.Draw(dst, dst.Bounds(), &image.Uniform{renderer.DeleteBackground}, image.ZP, draw.Src)\n\t\tdefault:\n\t\t\tdraw.Draw(dst, dst.Bounds(), &image.Uniform{renderer.NormalBackground}, image.ZP, draw.Src)\n\t\t}\n\t} else {\n\t\tdraw.Draw(dst, dst.Bounds(), &image.Uniform{renderer.NormalBackground}, image.ZP, draw.Src)\n\t}\n\n\ts := w.sz.Size()\n\n\tcontentBounds := dst.Bounds()\n\ttagBounds := tagSize\n\t// ensure that the tag takes no more than half the window, so that the content doesn't get\n\t// drowned out by commands that output more to stderr than they should.\n\tif wHeight := s.Y; tagBounds.Max.Y > wHeight/2 {\n\t\ttagBounds.Max.Y = wHeight / 2\n\t}\n\tcontentBounds.Min.Y = tagBounds.Max.Y\n\n\ttagline.RenderInto(dst.SubImage(image.Rectangle{image.ZP, image.Point{s.X, tagBounds.Max.Y}}).(*image.RGBA), buf.Tagline, clipRectangle(w.sz, viewport))\n\tviewport.RenderInto(dst.SubImage(image.Rectangle{image.Point{0, tagBounds.Max.Y}, s}).(*image.RGBA), buf, clipRectangle(w.sz, viewport))\n\n\tw.Upload(image.Point{0, 0}, w.buffer, dst.Bounds())\n\tw.Publish()\n\treturn\n}",
"func MapBuffer(target uint32, access uint32) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpMapBuffer, 2, uintptr(target), uintptr(access), 0)\n\treturn (unsafe.Pointer)(ret)\n}",
"func (i *image) imageToDraw(bit img.Rectangle, rect img.Rectangle) img.Rectangle {\n\tcenter := i.center(bit)\n\tret := img.ZR\n\tret.Min.X, ret.Max.X = i.converMapCoord(rect.Min.X, center.X)\n\tret.Min.Y, ret.Max.Y = i.converMapCoord(rect.Min.Y, center.Y)\n\treturn ret\n}",
"func (b *Buddy) BlockAllocationBitmap() []byte {\n\treturn b.blockAllocationBitmap\n}",
"func memAlloc(v unsafe.Pointer, n uintptr) unsafe.Pointer {\n\trequiredPages := uint64(round(n, _PAGESIZE) / _PAGESIZE)\n\n\treturn _atman_mm.allocPages(v, requiredPages)\n}",
"func (c *Canvas) ToPPM(writer io.Writer, goTemplate string) error {\n\tif writer == nil {\n\t\treturn errors.New(\"writer must not be nil\")\n\t}\n\n\tfuncMap := template.FuncMap{\n\t\t\"pixels\": writePPMPixels,\n\t}\n\n\ttmpl, err := template.New(ppmID).Funcs(funcMap).Parse(goTemplate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = tmpl.Execute(writer, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func ImageToPdfGm(w io.Writer, r io.Reader, contentType string) error {\n\t//log.Printf(\"converting image %s to %s\", contentType, destfn)\n\timgtyp := \"\"\n\tif false && contentType != \"\" {\n\t\timgtyp = contentType[strings.Index(contentType, \"/\")+1:] + \":\"\n\t}\n\n\tcmd := exec.Command(*ConfGm, \"convert\", imgtyp+\"-\", \"pdf:-\")\n\t// cmd.Stdin = io.TeeReader(r, os.Stderr)\n\tcmd.Stdin = r\n\tcmd.Stdout = w\n\terrout := bytes.NewBuffer(nil)\n\tcmd.Stderr = errout\n\tlogger.Debug(\"msg\", \"ImageToPdfGm calls\", \"command\", cmd)\n\terr := runWithTimeout(cmd)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"gm convert exited %s while converting %s: %s\",\n\t\t\terr, r, errout.Bytes())\n\t}\n\tif len(errout.Bytes()) > 0 {\n\t\tlogger.Warn(\"msg\", \"gm convert\", \"r\", r, \"stderr\", errout.String())\n\t}\n\treturn nil\n}",
"func memoryMapAndGenerate(path string, size uint64, generator func(buffer []uint32)) (*os.File, mmap.MMap, []uint32, error) {\n\t// Ensure the data folder exists\n\tif err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\t// Create a huge temporary empty file to fill with data\n\ttemp := path + \".\" + strconv.Itoa(rand.Int())\n\n\tdump, err := os.Create(temp)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tif err = dump.Truncate(int64(len(dumpMagic))*4 + int64(size)); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\t// Memory map the file for writing and fill it with the generator\n\tmem, buffer, err := memoryMapFile(dump, true)\n\tif err != nil {\n\t\tdump.Close()\n\t\treturn nil, nil, nil, err\n\t}\n\tcopy(buffer, dumpMagic)\n\n\tdata := buffer[len(dumpMagic):]\n\tgenerator(data)\n\n\tif err := mem.Unmap(); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tif err := dump.Close(); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tif err := os.Rename(temp, path); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\treturn memoryMap(path)\n}",
"func memoryMapAndGenerate(path string, size uint64, generator func(buffer []uint32)) (*os.File, mmap.MMap, []uint32, error) {\n\t// Ensure the data folder exists\n\tif err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\t// Create a huge temporary empty file to fill with data\n\ttemp := path + \".\" + strconv.Itoa(rand.Int())\n\n\tdump, err := os.Create(temp)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tif err = dump.Truncate(int64(len(dumpMagic))*4 + int64(size)); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\t// Memory map the file for writing and fill it with the generator\n\tmem, buffer, err := memoryMapFile(dump, true)\n\tif err != nil {\n\t\tdump.Close()\n\t\treturn nil, nil, nil, err\n\t}\n\tcopy(buffer, dumpMagic)\n\n\tdata := buffer[len(dumpMagic):]\n\tgenerator(data)\n\n\tif err := mem.Unmap(); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tif err := dump.Close(); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tif err := os.Rename(temp, path); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\treturn memoryMap(path)\n}"
] | [
"0.6724567",
"0.49573916",
"0.47340837",
"0.4624455",
"0.457245",
"0.45523685",
"0.45123872",
"0.45005557",
"0.44440153",
"0.4428556",
"0.44049704",
"0.4388476",
"0.43511838",
"0.4336304",
"0.4282355",
"0.4279812",
"0.42640758",
"0.42201537",
"0.41629943",
"0.41538098",
"0.4152851",
"0.41374055",
"0.41370764",
"0.41265863",
"0.41168094",
"0.40669417",
"0.40528795",
"0.4040639",
"0.4040639",
"0.40387347",
"0.40320894",
"0.40320894",
"0.4026953",
"0.40219995",
"0.4020436",
"0.40169755",
"0.4007112",
"0.3982699",
"0.39648464",
"0.3954528",
"0.39533788",
"0.39456162",
"0.39399487",
"0.39356473",
"0.39165005",
"0.3913616",
"0.38917542",
"0.3891586",
"0.388973",
"0.38848197",
"0.38829333",
"0.38740286",
"0.38614544",
"0.386047",
"0.38596016",
"0.38571447",
"0.38468018",
"0.3838166",
"0.3828819",
"0.3820207",
"0.3813128",
"0.3813128",
"0.38112095",
"0.37979853",
"0.3790812",
"0.37891975",
"0.37842086",
"0.37804824",
"0.37796757",
"0.37739283",
"0.37728506",
"0.37719837",
"0.376449",
"0.37609205",
"0.3759537",
"0.37528718",
"0.37497276",
"0.37446877",
"0.37417936",
"0.37391403",
"0.37266514",
"0.37209636",
"0.3720769",
"0.37176242",
"0.370073",
"0.36918426",
"0.369036",
"0.36900532",
"0.36879063",
"0.36786565",
"0.36782748",
"0.3672383",
"0.36633283",
"0.366169",
"0.3658162",
"0.36568618",
"0.36565396",
"0.36564103",
"0.36558145",
"0.36558145"
] | 0.78535616 | 0 |
FPDF_DeviceToPage converts the screen coordinates of a point to page coordinates. The page coordinate system has its origin at the leftbottom corner of the page, with the Xaxis on the bottom going to the right, and the Yaxis on the left side going up. NOTE: this coordinate system can be altered when you zoom, scroll, or rotate a page, however, a point on the page should always have the same coordinate values in the page coordinate system. The device coordinate system is device dependent. For screen device, its origin is at the lefttop corner of the window. However this origin can be altered by the Windows coordinate transformation utilities. You must make sure the start_x, start_y, size_x, size_y and rotate parameters have exactly same values as you used in the FPDF_RenderPage() function call. | func (p *PdfiumImplementation) FPDF_DeviceToPage(request *requests.FPDF_DeviceToPage) (*responses.FPDF_DeviceToPage, error) {
p.Lock()
defer p.Unlock()
pageHandle, err := p.loadPage(request.Page)
if err != nil {
return nil, err
}
pageX := C.double(0)
pageY := C.double(0)
success := C.FPDF_DeviceToPage(pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.int(request.DeviceX), C.int(request.DeviceY), &pageX, &pageY)
if int(success) == 0 {
return nil, errors.New("could not calculate from device to page")
}
return &responses.FPDF_DeviceToPage{
PageX: float64(pageX),
PageY: float64(pageY),
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (p *PdfiumImplementation) FPDF_PageToDevice(request *requests.FPDF_PageToDevice) (*responses.FPDF_PageToDevice, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdeviceX := C.int(0)\n\tdeviceY := C.int(0)\n\n\tsuccess := C.FPDF_PageToDevice(pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.double(request.PageX), C.double(request.PageY), &deviceX, &deviceY)\n\tif int(success) == 0 {\n\t\treturn nil, errors.New(\"could not calculate from page to device\")\n\t}\n\n\treturn &responses.FPDF_PageToDevice{\n\t\tDeviceX: int(deviceX),\n\t\tDeviceY: int(deviceY),\n\t}, nil\n}",
"func (p *PdfiumImplementation) FPDF_RenderPage(request *requests.FPDF_RenderPage) (*responses.FPDF_RenderPage, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thdc, ok := request.DC.(C.HDC)\n\tif !ok {\n\t\treturn nil, errors.New(\"DC is not of type C.HDC\")\n\t}\n\n\tC.FPDF_RenderPage(hdc, pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.int(request.Flags))\n\n\treturn &responses.FPDF_RenderPage{}, nil\n}",
"func OffsetToPage(offset, size int) int {\n\treturn (offset / size) + 1\n}",
"func canvasToViewPort(x, y float64, c Canvas) Vector {\n\tfw, fh := float64(c.Width()), float64(c.Height())\n\treturn Vector{(x - fw/2) / fw, (y - fh/2) / fh, 1}\n}",
"func (m *PrinterDefaults) SetFitPdfToPage(value *bool)() {\n err := m.GetBackingStore().Set(\"fitPdfToPage\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *PrinterDefaults) GetFitPdfToPage()(*bool) {\n val, err := m.GetBackingStore().Get(\"fitPdfToPage\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}",
"func (s *SimPDF) SetPage(pageType string, isLandscape bool) {\n\tswitch p := strings.ToLower(pageType); p {\n\tcase \"letter\":\n\t\ts.Page = defaults.Letter\n\tcase \"legal\":\n\t\ts.Page = defaults.Legal\n\tcase \"tabloid\":\n\t\ts.Page = defaults.Tabloid\n\tcase \"ledger\":\n\t\ts.Page = defaults.Ledger\n\tcase \"ansi\":\n\t\ts.Page = defaults.AnsiA\n\tcase \"a1\":\n\t\ts.Page = defaults.A1\n\tcase \"a2\":\n\t\ts.Page = defaults.A2\n\tcase \"a3\":\n\t\ts.Page = defaults.A3\n\tcase \"a4\":\n\t\ts.Page = defaults.A4\n\tcase \"a5\":\n\t\ts.Page = defaults.A5\n\tdefault:\n\t\ts.Page = defaults.Letter\n\t}\n\ts.Page.IsLandscape = isLandscape\n}",
"func (ref *UIElement) ScreenPointForLayoutPoint(p Point) Point {\n\treturn ref.pointForPointAttr(ScreenPointForLayoutPointParameterizedAttribute, p)\n}",
"func GetPDFPage(pdfName string, imageName string, pageNum int) error {\n\n\tabsPath, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tInpath := filepath.Join(absPath, \"input\", pdfName)\n\tOutpath := filepath.Join(absPath, \"output\")\n\n\tif _, err := os.Stat(Outpath); os.IsNotExist(err) {\n\t\tlog.Println(\"Output dir not found. Creating at \", Outpath)\n\t\tos.Mkdir(Outpath, os.ModePerm)\n\t}\n\n\timagick.Initialize()\n\tdefer imagick.Terminate()\n\n\tmw := imagick.NewMagickWand()\n\tdefer mw.Destroy()\n\n\tif err := mw.SetResolution(72, 72); err != nil {\n\t\treturn err\n\t}\n\n\t// Load the image file into imagick\n\tif err := mw.ReadImage(Inpath); err != nil {\n\t\treturn err\n\t}\n\n\tmw.SetIteratorIndex(pageNum - 1)\n\n\t// Set any compression (100 = max quality)\n\tif err := mw.SetCompressionQuality(100); err != nil {\n\t\treturn err\n\t}\n\n\t// Convert into JPG\n\tif err := mw.SetFormat(\"jpg\"); err != nil {\n\t\treturn err\n\t}\n\n\t// Save File\n\treturn mw.WriteImage(filepath.Join(Outpath, imageName))\n}",
"func NewPDFPage() *PDFPage {\n\treturn (*PDFPage)(allocPDFPageMemory(1))\n}",
"func (p *PdfiumImplementation) FPDF_RenderPageBitmap(request *requests.FPDF_RenderPageBitmap) (*responses.FPDF_RenderPageBitmap, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tC.FPDF_RenderPageBitmap(bitmapHandle.handle, pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.int(request.Flags))\n\n\treturn &responses.FPDF_RenderPageBitmap{}, nil\n}",
"func (od OutlineDest) ToPdfObject() core.PdfObject {\n\treturn core.MakeArray(\n\t\tcore.MakeInteger(od.Page),\n\t\tcore.MakeName(\"XYZ\"),\n\t\tcore.MakeFloat(od.X),\n\t\tcore.MakeFloat(od.Y),\n\t\tcore.MakeFloat(0),\n\t)\n}",
"func (f *Fpdf) PointConvert(pt float64) (u float64) {\n\treturn pt / f.k\n}",
"func allocPDFPageMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFPageValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (db *DB) page(id pgid) *page {\n\t// buffer := db.data[]\n\t// offset := id*sizeof(PageSize)\n\t// addr := &db.data[offset]\n\t// p := (*page)addr\n\t//\n\t// return p\n\tpos := id * pgid(db.pageSize)\n\treturn (*page)(unsafe.Pointer(&db.data[pos]))\n}",
"func (s *SimPDF) NewPage(page models.Pages) {\n\ts.Page = page\n\ts.PDF.AddPageFormat(page.ToPDFOrientation(), gofpdf.SizeType{Wd: page.Width, Ht: page.Height})\n}",
"func (p *PdfiumImplementation) FPDF_RenderPageBitmapWithMatrix(request *requests.FPDF_RenderPageBitmapWithMatrix) (*responses.FPDF_RenderPageBitmapWithMatrix, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmatrix := C.FS_MATRIX{\n\t\ta: C.float(request.Matrix.A),\n\t\tb: C.float(request.Matrix.B),\n\t\tc: C.float(request.Matrix.C),\n\t\td: C.float(request.Matrix.D),\n\t\te: C.float(request.Matrix.E),\n\t\tf: C.float(request.Matrix.F),\n\t}\n\n\tclipping := C.FS_RECTF{\n\t\tleft: C.float(request.Clipping.Left),\n\t\ttop: C.float(request.Clipping.Top),\n\t\tright: C.float(request.Clipping.Right),\n\t\tbottom: C.float(request.Clipping.Bottom),\n\t}\n\n\tC.FPDF_RenderPageBitmapWithMatrix(bitmapHandle.handle, pageHandle.handle, &matrix, &clipping, C.int(request.Flags))\n\n\treturn &responses.FPDF_RenderPageBitmapWithMatrix{}, nil\n}",
"func (f *Fpdf) PointToUnitConvert(pt float64) (u float64) {\n\treturn pt / f.k\n}",
"func (rect *PdfRectangle) ToPdfObject() core.PdfObject {\n\treturn core.MakeArray(\n\t\tcore.MakeFloat(rect.Llx),\n\t\tcore.MakeFloat(rect.Lly),\n\t\tcore.MakeFloat(rect.Urx),\n\t\tcore.MakeFloat(rect.Ury),\n\t)\n}",
"func PageFromAddress(virtAddr uintptr) Page {\n\treturn Page((virtAddr & ^(uintptr(PageSize - 1))) >> PageShift)\n}",
"func PageToOffset(page, size int) int {\n\treturn (page - 1) * size\n}",
"func (f *Fpdf) UnitToPointConvert(u float64) (pt float64) {\n\treturn u * f.k\n}",
"func (p *Pagination) Page(total int) (from int, to int) {\n\tif p.Num == 0 {\n\t\tp.Num = 1\n\t}\n\tif p.Size == 0 {\n\t\tp.Size = DefaultSize\n\t}\n\n\tif total == 0 || total < p.Size*(p.Num-1) {\n\t\treturn\n\t}\n\tif total <= p.Size {\n\t\treturn 1, total\n\t}\n\tfrom = (p.Num-1)*p.Size + 1\n\tif (total - from + 1) < p.Size {\n\t\treturn from, total\n\t}\n\treturn from, from + p.Size - 1\n}",
"func (db *DB) page(id pgid) *page {\n\tpos := id * pgid(db.pageSize)\n\treturn (*page)(unsafe.Pointer(&db.data[pos]))\n}",
"func (p *Page) MoveTo(x, y float64) {\n\tfmt.Fprint(p.contents, x, y, \" m \")\n}",
"func pageAddress(pointer int, pagesize int) int {\n\tpageAddress := pointer % pagesize\n\tif pageAddress < 0 {\n\t\treturn pagesize + pageAddress\n\t}\n\treturn pageAddress\n}",
"func (ref *UIElement) LayoutPointForScreenPoint(p Point) Point {\n\treturn ref.pointForPointAttr(LayoutPointForScreenPointParameterizedAttribute, p)\n}",
"func (s *SimPDF) Start(pageType string, isLandscape bool, styles []models.Styles, margin models.Margins, customFontDirectory string) {\n\ts.SetPage(pageType, isLandscape)\n\ts.Style = styles\n\ts.Margin = margin\n\ts.init(customFontDirectory)\n\ts.AddMargins(s.Margin)\n}",
"func ScreenXY(value Vec2) *SimpleElement { return newSEVec2(\"screenXY\", value) }",
"func (dw *DrawingWand) Point(x, y float64) {\n\tC.DrawPoint(dw.dw, C.double(x), C.double(y))\n}",
"func (o *GetOutagesParams) SetPage(page float64) {\n\to.Page = page\n}",
"func CreatePage(\n\txRefTable *model.XRefTable,\n\tparentPageIndRef types.IndirectRef,\n\tp *model.Page,\n\tfonts model.FontMap) (*types.IndirectRef, types.Dict, error) {\n\n\tpageDict := types.Dict(\n\t\tmap[string]types.Object{\n\t\t\t\"Type\": types.Name(\"Page\"),\n\t\t\t\"Parent\": parentPageIndRef,\n\t\t\t\"MediaBox\": p.MediaBox.Array(),\n\t\t\t\"CropBox\": p.CropBox.Array(),\n\t\t},\n\t)\n\n\terr := addPageResources(xRefTable, pageDict, *p, fonts)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tir, err := xRefTable.StreamDictIndRef(p.Buf.Bytes())\n\tif err != nil {\n\t\treturn nil, pageDict, err\n\t}\n\tpageDict.Insert(\"Contents\", *ir)\n\n\tpageDictIndRef, err := xRefTable.IndRefForNewObject(pageDict)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif len(p.AnnotTabs) == 0 && len(p.Annots) == 0 && len(p.LinkAnnots) == 0 {\n\t\treturn pageDictIndRef, pageDict, nil\n\t}\n\n\tif err := setAnnotationParentsAndFields(xRefTable, p, *pageDictIndRef); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tarr, err := mergeAnnotations(nil, p.Annots, p.AnnotTabs)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfor _, la := range p.LinkAnnots {\n\t\td, err := la.RenderDict(xRefTable, *pageDictIndRef)\n\t\tif err != nil {\n\t\t\treturn nil, nil, &json.UnsupportedTypeError{}\n\t\t}\n\t\tir, err := xRefTable.IndRefForNewObject(d)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tarr = append(arr, *ir)\n\t}\n\n\tpageDict[\"Annots\"] = arr\n\n\treturn pageDictIndRef, pageDict, err\n}",
"func NewPDFPageRef(ref unsafe.Pointer) *PDFPage {\n\treturn (*PDFPage)(ref)\n}",
"func (s *Screen) Size() Point { return Point{X: s.width, Y: len(s.current) / s.width} }",
"func (p *PDF) Move(xDelta, yDelta float64) {\n\tp.x, p.y = p.x+xDelta, p.y+yDelta\n\tp.fpdf.MoveTo(p.x, p.y)\n}",
"func NewPageLayout(orientation, unit string, width, height float64) (s *PageLayout, e error) {\n\tif orientation == \"\" {\n\t\torientation = \"L\"\n\t}\n\n\tif unit == \"\" {\n\t\tunit = \"mm\"\n\t}\n\n\tif width <= 0 {\n\t\te = errors.New(\"The width of the page needs to be bigger than 0.\")\n\t\treturn\n\t}\n\n\tif height <= 0 {\n\t\te = errors.New(\"The height of the page needs to be bigger than 0.\")\n\t\treturn\n\t}\n\n\ts = &PageLayout{\n\t\torientation: orientation,\n\t\tunit: unit,\n\t\twidth: width,\n\t\theight: height,\n\t}\n\treturn\n}",
"func (obj *Device) SetViewport(v VIEWPORT) Error {\n\tret, _, _ := syscall.Syscall(\n\t\tobj.vtbl.SetViewport,\n\t\t2,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(unsafe.Pointer(&v)),\n\t\t0,\n\t)\n\treturn toErr(ret)\n}",
"func Page(page, size int) *Pager {\n\treturn &Pager{p: page, s: size}\n}",
"func (d *Doc) SetPosition(x, y float64) {\n\td.GoPdf.SetX(x)\n\td.currentX = x\n\td.GoPdf.SetY(y)\n\td.currentY = y\n}",
"func (a *PDFApiService) MovePage(ctx _context.Context, pdfMovePageParameters PdfMovePageParameters) (PdfMovePageResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue PdfMovePageResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/pdf/MovePage\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json-patch+json\", \"application/json\", \"text/json\", \"application/_*+json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &pdfMovePageParameters\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v PdfMovePageResponse\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}",
"func (blk *Block) drawToPage(page *model.PdfPage) error {\n\n\t// TODO(gunnsth): Appears very wasteful to do this all the time.\n\t// Possibly create another wrapper around model.PdfPage (creator.page) which can keep track of whether\n\t// this has already been done.\n\n\t// Check if Page contents are wrapped - if not wrap it.\n\tcontent, err := page.GetAllContentStreams()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontentParser := contentstream.NewContentStreamParser(content)\n\tops, err := contentParser.Parse()\n\tif err != nil {\n\t\treturn err\n\t}\n\tops.WrapIfNeeded()\n\n\t// Ensure resource dictionaries are available.\n\tif page.Resources == nil {\n\t\tpage.Resources = model.NewPdfPageResources()\n\t}\n\n\t// Merge the contents into ops.\n\terr = mergeContents(ops, page.Resources, blk.contents, blk.resources)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Merge resources for blocks which were created from pages.\n\t// Necessary for adding resources which do not appear in the block contents.\n\tif err = mergeResources(blk.resources, page.Resources); err != nil {\n\t\treturn err\n\t}\n\n\terr = page.SetContentStreams([]string{string(ops.Bytes())}, core.NewFlateEncoder())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Add block annotations to the page.\n\tfor _, annotation := range blk.annotations {\n\t\tpage.AddAnnotation(annotation)\n\t}\n\n\treturn nil\n}",
"func (self *Pages) ToBytes() uint {\n\treturn uint(self.ToUint32()) * WasmPageSize\n}",
"func Pages(step int, length int) []Page {\n\tif step <= 0 {\n\t\tpanic(\"Step must be a positive number.\")\n\t}\n\tif length < 0 {\n\t\tpanic(\"Step must be a positive number.\")\n\t}\n\n\tpagesNum := int(math.Ceil(float64(length) / float64(step)))\n\tpages := make([]Page, pagesNum)\n\tfor i := 0; i < pagesNum; i++ {\n\t\tpages[i].From = i * step\n\t\tpages[i].To = (i + 1) * step\n\t}\n\tif pagesNum > 0 {\n\t\tpages[pagesNum-1].To = length\n\t}\n\treturn pages\n}",
"func (c Page) Page() revel.Result {\n\n\tc.RenderArgs[\"Site\"] = site.Site\n\n\t// Create PageData\n\tpdata := site.LoadPage(c.Params.Route.Get(\"section\"), c.Params.Route.Get(\"page\"))\n\tc.RenderArgs[\"Page\"] = pdata\n\n\tif pdata.Error != nil {\n\t\treturn c.NotFound(\"missing secton\")\n\t}\n\n\tc.RenderArgs[\"Section\"] = site.Site.Sections[pdata.Section]\n\n\treturn c.Render()\n\n}",
"func (a *PDFApiService) ScalePage(ctx _context.Context, pdfScalePageParameters PdfScalePageParameters) (PdfScalePageResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue PdfScalePageResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/pdf/ScalePage\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json-patch+json\", \"application/json\", \"text/json\", \"application/_*+json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &pdfScalePageParameters\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v PdfScalePageResponse\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}",
"func PrintToPDF(v Datum, cookies map[string]string, path string) error {\n\n\tname := utils.FileName(v.Title, \"pdf\")\n\n\tfilename := filepath.Join(path, name)\n\tfmt.Printf(\"正在生成文件:【\\033[37;1m%s\\033[0m】 \", name)\n\n\t_, exist, err := utils.FileSize(filename)\n\n\tif err != nil {\n\t\tfmt.Printf(\"\\033[31;1m%s, err=%v\\033[0m\\n\", \"失败1\", err)\n\t\treturn err\n\t}\n\n\tif exist {\n\t\tfmt.Printf(\"\\033[33;1m%s\\033[0m\\n\", \"已存在\")\n\t\treturn nil\n\t}\n\n\terr = utils.ColumnPrintToPDF(v.ID, filename, cookies)\n\n\tif err != nil {\n\t\tfmt.Printf(\"\\033[31;1m%s, err=%v\\033[0m\\n\", \"失败2\", err)\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"\\033[32;1m%s\\033[0m\\n\", \"完成\")\n\n\treturn nil\n}",
"func (mm *atmanMemoryManager) allocPage(page vaddr) {\n\tvar (\n\t\tl4offset = page.pageTableOffset(pageTableLevel4)\n\t\tl3offset = page.pageTableOffset(pageTableLevel3)\n\t\tl2offset = page.pageTableOffset(pageTableLevel2)\n\t\tl1offset = page.pageTableOffset(pageTableLevel1)\n\t)\n\n\tl4 := mm.l4\n\tl3pte := l4.Get(l4offset)\n\n\tif !l3pte.hasFlag(xenPageTablePresent) {\n\t\tpfn := mm.physAllocPage()\n\t\tl3pte = mm.writePte(mm.l4PFN, l4offset, pfn, PTE_PAGE_TABLE_FLAGS|xenPageTableWritable)\n\t}\n\n\tl3 := mm.getPageTable(-1, -1, l4offset)\n\tl2pte := l3.Get(l3offset)\n\n\tif !l2pte.hasFlag(xenPageTablePresent) {\n\t\tpfn := mm.physAllocPage()\n\t\tl2pte = mm.writePte(l3pte.pfn(), l3offset, pfn, PTE_PAGE_TABLE_FLAGS|xenPageTableWritable)\n\t}\n\n\tl2 := mm.getPageTable(-1, l4offset, l3offset)\n\tl1pte := l2.Get(l2offset)\n\n\tif !l1pte.hasFlag(xenPageTablePresent) {\n\t\tpfn := mm.physAllocPage()\n\t\tl1pte = mm.writePte(l2pte.pfn(), l2offset, pfn, PTE_PAGE_TABLE_FLAGS|xenPageTableWritable)\n\t}\n\n\tpagepfn := mm.physAllocPage()\n\tmm.writePte(l1pte.pfn(), l1offset, pagepfn, PTE_PAGE_FLAGS)\n\n\t// ensure page is writable\n\t*(*uintptr)(unsafe.Pointer(page)) = 0x0\n}",
"func SetViewport(x Int, y Int, width Sizei, height Sizei) {\n\tcx, _ := (C.GLint)(x), cgoAllocsUnknown\n\tcy, _ := (C.GLint)(y), cgoAllocsUnknown\n\tcwidth, _ := (C.GLsizei)(width), cgoAllocsUnknown\n\tcheight, _ := (C.GLsizei)(height), cgoAllocsUnknown\n\tC.glViewport(cx, cy, cwidth, cheight)\n}",
"func Page(c *fiber.Ctx) {\n\tShopID := c.Params(\"shop_id\")\n\tuserID := userIDF(c.Get(\"token\"))\n\tvar PageFromSQL PageSQL\n\tvar PagePointer PagesPointer\n\tvar response PageInformation\n\n\tErrorPage := sq.Select(\n\t\t\"active\",\n\t\t\"template_type\",\n\t\t\"style_sheets\",\n\t\t\"active_days\",\n\t\t\"images_days\",\n\t\t\"offers_active\",\n\t\t\"accept_card_active\",\n\t\t\"subdomain\",\n\t\t\"domain\",\n\t\t\"shop.shop_id\",\n\t\t\"pages_id\",\n\t\t\"type_charge\",\n\t\t\"shop_name\",\n\t\t\"description\",\n\t\t\"cover_image\",\n\t\t\"logo\",\n\t\t\"shop.user_id\",\n\t).\n\t\tFrom(\"pages\").\n\t\tLeftJoin(\"plans_pay on pages.shop_id = plans_pay.shop_id\").\n\t\tLeftJoin(\"shop on pages.shop_id = shop.shop_id\").\n\t\tWhere(\"pages.shop_id = ? AND shop.user_id = ?\", ShopID, userID).\n\t\tRunWith(database).\n\t\tQueryRow().\n\t\tScan(\n\t\t\t&PageFromSQL.Active,\n\t\t\t&PageFromSQL.TemplateType,\n\t\t\t&PageFromSQL.StyleSheets,\n\t\t\t&PageFromSQL.ActiveDays,\n\t\t\t&PageFromSQL.ImagesDays,\n\t\t\t&PageFromSQL.OffersActive,\n\t\t\t&PageFromSQL.AcceptCardActive,\n\t\t\t&PageFromSQL.Subdomain,\n\t\t\t&PageFromSQL.Domain,\n\t\t\t&PageFromSQL.ShopID,\n\t\t\t&PageFromSQL.PagesID,\n\t\t\t&PageFromSQL.TypeCharge,\n\t\t\t&PageFromSQL.ShopName,\n\t\t\t&PageFromSQL.Description,\n\t\t\t&PageFromSQL.CoverImage,\n\t\t\t&PageFromSQL.Logo,\n\t\t\t&PageFromSQL.UserID,\n\t\t)\n\n\tif ErrorPage != nil {\n\t\tfmt.Println(ErrorPage, \"Error get page\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with get page\"})\n\t\tc.SendStatus(400)\n\t\treturn\n\t}\n\n\tActive, _ := strconv.Atoi(PageFromSQL.Active.String)\n\tPagePointer.Active = Active\n\tTemplateType, _ := strconv.Atoi(PageFromSQL.TemplateType.String)\n\tPagePointer.TemplateType = TemplateType\n\tStyleSheets, _ := strconv.Atoi(PageFromSQL.StyleSheets.String)\n\tPagePointer.StyleSheets = StyleSheets\n\tActiveDays, _ := strconv.Atoi(PageFromSQL.ActiveDays.String)\n\tPagePointer.ActiveDays = ActiveDays\n\tImagesDays, _ := strconv.Atoi(PageFromSQL.ImagesDays.String)\n\tPagePointer.ImagesDays = ImagesDays\n\tOffersActive, _ := strconv.Atoi(PageFromSQL.OffersActive.String)\n\tPagePointer.OffersActive = OffersActive\n\tAcceptCardActive, _ := strconv.Atoi(PageFromSQL.AcceptCardActive.String)\n\tPagePointer.AcceptCardActive = AcceptCardActive\n\tPagePointer.Subdomain = &PageFromSQL.Subdomain.String\n\tPagePointer.Domain = &PageFromSQL.Domain.String\n\tPagePointer.ShopID = &PageFromSQL.ShopID.String\n\tPagePointer.PagesID = &PageFromSQL.PagesID.String\n\tPagePointer.TypeCharge = &PageFromSQL.TypeCharge.String\n\tPagePointer.ShopName = &PageFromSQL.ShopName.String\n\tPagePointer.Description = &PageFromSQL.Description.String\n\tPagePointer.CoverImage = &PageFromSQL.CoverImage.String\n\tPagePointer.Logo = &PageFromSQL.Logo.String\n\tPagePointer.UserID = &PageFromSQL.UserID.String\n\n\tresponse.Page = PagePointer\n\tUserID := *PagePointer.UserID\n\tif UserID == userID {\n\t\tc.JSON(response)\n\t} else {\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Not is owner or active shop\"})\n\t}\n}",
"func (o *Range) GetPage() gdnative.Real {\n\t//log.Println(\"Calling Range.GetPage()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"Range\", \"get_page\")\n\n\t// Call the parent method.\n\t// float\n\tretPtr := gdnative.NewEmptyReal()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewRealFromPointer(retPtr)\n\treturn ret\n}",
"func PageFile(name, version, size string, path, links, lines []string) *Renderer {\n\treturn &Renderer{\n\t\tfilenames: []string{\n\t\t\t\"templates/layout.html\",\n\t\t\t\"templates/logo.html\",\n\t\t\t\"templates/pages/file.html\",\n\t\t},\n\t\tcontext: struct {\n\t\t\tPackage string\n\t\t\tVersion string\n\t\t\tSize string\n\t\t\tPath []string\n\t\t\tPathLinks []string\n\t\t\tLines []string\n\t\t}{\n\t\t\tPackage: name,\n\t\t\tVersion: version,\n\t\t\tSize: size,\n\t\t\tPath: path,\n\t\t\tPathLinks: links,\n\t\t\tLines: append([]string{\"\"}, lines...),\n\t\t},\n\t}\n}",
"func NewPage(mediaBox, cropBox *types.Rectangle) Page {\n\treturn Page{\n\t\tMediaBox: mediaBox,\n\t\tCropBox: cropBox,\n\t\tFm: FontMap{},\n\t\tIm: ImageMap{},\n\t\tAnnotTabs: map[int]FieldAnnotation{},\n\t\tBuf: new(bytes.Buffer)}\n}",
"func (c *Camera) ScreenToWorld(posX, posY int) (float64, float64) {\n\tinverseMatrix := c.worldMatrix()\n\tif inverseMatrix.IsInvertible() {\n\t\tinverseMatrix.Invert()\n\t\treturn inverseMatrix.Apply(float64(posX), float64(posY))\n\t}\n\t// When scaling it can happend that matrix is not invertable\n\treturn math.NaN(), math.NaN()\n}",
"func (p *Page) Translate(x, y float64) {\n\tfmt.Fprintf(p.contents, \"1 0 0 1 %g %g cm \", x, y)\n}",
"func (c *Camera) OnScreenPoint(x, y float64) (int, int, bool) {\n\tvar sx, sy int\n\tvar onScreenX, onScreenY bool\n\tsx = int((x-c.lookAtX)*c.zoom + float64(c.screenW)/2.0)\n\tsy = int((c.lookAtY-y)*c.zoom + float64(c.screenH)/2.0)\n\n\tif x < c.sLeft {\n\t\tonScreenX = false\n\t} else if x > c.sRight {\n\t\tonScreenX = false\n\t} else {\n\t\tonScreenX = true\n\t}\n\n\tif y > c.sTop {\n\t\tonScreenY = false\n\t} else if y < c.sBottom {\n\t\tonScreenY = false\n\t} else {\n\t\tonScreenY = true\n\t}\n\treturn sx, sy, onScreenX && onScreenY\n}",
"func Pt(x, y int) Point {\n\treturn Point{X:x, Y:y}\n}",
"func (x *PDFPage) PassRef() *C.pdf_page {\n\tif x == nil {\n\t\tx = (*PDFPage)(allocPDFPageMemory(1))\n\t}\n\treturn (*C.pdf_page)(unsafe.Pointer(x))\n}",
"func (p *Page) MustPDF(toFile ...string) []byte {\n\tr, err := p.PDF(&proto.PagePrintToPDF{})\n\tp.e(err)\n\tbin, err := ioutil.ReadAll(r)\n\tp.e(err)\n\n\tp.e(saveFile(saveFileTypePDF, bin, toFile))\n\treturn bin\n}",
"func ExamplePdfMaroto_GetCurrentPage() {\n\tm := pdf.NewMaroto(consts.Portrait, consts.A4)\n\n\t// Index here will be 0.\n\t_ = m.GetCurrentPage()\n\n\t// Add Rows, Cols and Components.\n\n\t// Index here will not be 0.\n\t_ = m.GetCurrentPage()\n\n\t// Do more things and save...\n}",
"func (f *Face) Pt(pt, dpi int) error {\n\theight := C.FT_F26Dot6(pt << 6)\n\tres := C.FT_UInt(dpi)\n\terrno := C.FT_Set_Char_Size(f.handle, 0, height, res, res)\n\tif errno != 0 {\n\t\treturn fmt.Errorf(\"freetype2: %s\", errstr(errno))\n\t}\n\treturn nil\n}",
"func (p Point2D) ToPoint() Point {\n\treturn Point{p.X, p.Y, 0}\n}",
"func coreRatioViewport(fbWidth int, fbHeight int) (x, y, w, h float32) {\n\t// Scale the content to fit in the viewport.\n\tfbw := float32(fbWidth)\n\tfbh := float32(fbHeight)\n\n\t// NXEngine workaround\n\taspectRatio := float32(Geom.AspectRatio)\n\tif aspectRatio == 0 {\n\t\taspectRatio = float32(Geom.BaseWidth) / float32(Geom.BaseHeight)\n\t}\n\n\th = fbh\n\tw = fbh * aspectRatio\n\tif w > fbw {\n\t\th = fbw / aspectRatio\n\t\tw = fbw\n\t}\n\n\t// Place the content in the middle of the window.\n\tx = (fbw - w) / 2\n\ty = (fbh - h) / 2\n\n\tva := vertexArray(x, y, w, h, 1.0)\n\tgl.BindBuffer(gl.ARRAY_BUFFER, vbo)\n\tgl.BufferData(gl.ARRAY_BUFFER, len(va)*4, gl.Ptr(va), gl.STATIC_DRAW)\n\n\treturn\n}",
"func RenderPage(tpl template.Template, tplData interface{}, outPath string) {\n\t// Create file\n\toutFile, err := os.Create(outPath)\n\tif err != nil {\n\t\tFatal(err.Error())\n\t}\n\tdefer func() {\n\t\toutFile.Close()\n\t}()\n\tdefer wg.Done()\n\t// Template render\n\terr = tpl.Execute(outFile, tplData)\n\tif err != nil {\n\t\tFatal(err.Error())\n\t}\n}",
"func (db *DB) pageInBuffer(b []byte, id pgid) *page {\n\t// offset := id*sizeof(PageSize)\n\t// size := PageSize\n\t// res := (*page)b[offset...offset+size]\n\treturn (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)]))\n}",
"func wmPageZoom(ctx context.Context, tconn *chrome.TestConn, a *arc.ARC, d *ui.Device) error {\n\tact, err := arc.NewActivity(a, wm.Pkg24, wm.ResizableLandscapeActivity)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer act.Close()\n\tif err := act.StartWithDefaultOptions(ctx, tconn); err != nil {\n\t\treturn err\n\t}\n\tdefer act.Stop(ctx, tconn)\n\n\tif err := wm.WaitUntilActivityIsReady(ctx, tconn, act, d); err != nil {\n\t\treturn err\n\t}\n\n\tzoom, err := settings.DefaultZoom(ctx, tconn)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttesting.ContextLog(ctx, \"Default zoom is: \", zoom)\n\n\tboundsOld, err := act.WindowBounds(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttesting.ContextLogf(ctx, \"Window bounds before changing page zoom: %+v\", boundsOld)\n\n\tbutton := d.Object(ui.PackageName(act.PackageName()),\n\t\tui.ClassName(\"android.widget.Button\"),\n\t\tui.ID(\"org.chromium.arc.testapp.windowmanager:id/button_show\"))\n\tif err := button.WaitForExists(ctx, 10*time.Second); err != nil {\n\t\treturn err\n\t}\n\tbuttonBoundsOld, err := button.GetBounds(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttesting.ContextLogf(ctx, \"Button bounds before changing page zoom: %+v\", buttonBoundsOld)\n\n\t// Chrome has zoom factors that go from 0.25x to 5x. But Android only supports zoom factors\n\t// from 0.8x to 1.5x. Android clamps values that are outside the valid range. E.g: a 2.0 zoom factor\n\t// will be \"transformed\" to 1.5x in Android.\n\tconst zoomFactor = 1.5\n\ttesting.ContextLog(ctx, \"Setting page zoom to \", zoomFactor)\n\tif err := settings.SetDefaultZoom(ctx, tconn, zoomFactor); err != nil {\n\t\treturn err\n\t}\n\t// Be nice and restore default zoom on exit.\n\tdefer settings.SetDefaultZoom(ctx, tconn, zoom)\n\n\tif zoom, err := settings.DefaultZoom(ctx, tconn); err != nil {\n\t\treturn err\n\t} else if zoom != zoomFactor {\n\t\t// Checking that zoomFactor got applied correctly and was not converted to any another value.\n\t\treturn errors.Errorf(\"unexpected zoom value: got %f, want %f\", zoom, zoomFactor)\n\t}\n\n\t// After changing the zoom factor, the Android window size should remain the same.\n\t// But the content should be adjusted to the new zoom factor.\n\treturn testing.Poll(ctx, func(ctx context.Context) error {\n\t\tboundsNew, err := act.WindowBounds(ctx)\n\t\tif err != nil {\n\t\t\treturn testing.PollBreak(err)\n\t\t}\n\t\tif boundsNew != boundsOld {\n\t\t\treturn errors.Errorf(\"invalid window bounds: got %v, want %v\", boundsNew, boundsOld)\n\t\t}\n\n\t\tbuttonBoundsNew, err := button.GetBounds(ctx)\n\t\tif err != nil {\n\t\t\treturn testing.PollBreak(err)\n\t\t}\n\n\t\t// Widget size should be bigger by zoomFactor +/- some error margin to deal with rounding issues.\n\t\tconst errorMargin = zoomFactor * 0.1\n\t\twIncrease := float64(buttonBoundsNew.Width) / float64(buttonBoundsOld.Width)\n\t\thIncrease := float64(buttonBoundsNew.Height) / float64(buttonBoundsOld.Height)\n\n\t\tif math.Abs(wIncrease-zoomFactor) > errorMargin {\n\t\t\treturn errors.Errorf(\"invalid button width increase: got %v; want value in [%v, %v] range\",\n\t\t\t\twIncrease, zoomFactor-errorMargin, zoomFactor+errorMargin)\n\t\t}\n\n\t\tif math.Abs(hIncrease-zoomFactor) > errorMargin {\n\t\t\treturn errors.Errorf(\"invalid button height increase: got %v; want value in [%v, %v] range\",\n\t\t\t\thIncrease, zoomFactor-errorMargin, zoomFactor+errorMargin)\n\t\t}\n\t\treturn nil\n\t}, &testing.PollOptions{Timeout: 10 * time.Second})\n}",
"func (c *Camera) Viewport() (x float32, y float32, width float32, height float32) {\n\tif c.x > 0 {\n\t\tx = float32(c.x) / float32(c.windowWidth)\n\t}\n\tif c.y > 0 {\n\t\ty = float32(c.y) / float32(c.worldHeight)\n\t}\n\n\tratio := math32.Min(\n\t\tfloat32(c.windowWidth)/float32(c.worldWidth),\n\t\tfloat32(c.windowHeight)/float32(c.worldHeight),\n\t)\n\twidth, height = c.relativeToWindowSize(ratio, ratio)\n\twidth /= float32(c.width) / float32(c.worldWidth)\n\theight /= float32(c.height) / float32(c.worldHeight)\n\treturn x, y, width, height\n}",
"func (c *Context) PointToFixed(x float64) fixed.Int26_6 {\n\treturn fixed.Int26_6(x * float64(c.dpi) * (64.0 / 72.0))\n}",
"func Page(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tp, err := strconv.ParseUint(ps.ByName(\"page\"), 10, 8)\n\tif err != nil {\n\t\thttp.NotFound(w, r)\n\t}\n\tdata, err := newPageData(uint8(p))\n\tif err != nil {\n\t\thttp.NotFound(w, r)\n\t}\n\terr = t.ExecuteTemplate(w, \"index\", data)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}",
"func NewScreen(out io.Writer, size Point) *Screen {\n\treturn &Screen{\n\t\tconsole: out, width: size.X,\n\t\tcurrent: make([]Cell, size.X*size.Y),\n\t\tneedsRedraw: true,\n\t}\n}",
"func (db *DB) pageInBuffer(b []byte, id pgid) *page {\n\treturn (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)]))\n}",
"func (obj *Device) GetViewport() (v VIEWPORT, err Error) {\n\tret, _, _ := syscall.Syscall(\n\t\tobj.vtbl.GetViewport,\n\t\t2,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(unsafe.Pointer(&v)),\n\t\t0,\n\t)\n\terr = toErr(ret)\n\treturn\n}",
"func (p *GetDevicePositionHistoryPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*GetDevicePositionHistoryOutput, error) {\n\tif !p.HasMorePages() {\n\t\treturn nil, fmt.Errorf(\"no more pages available\")\n\t}\n\n\tparams := *p.params\n\tparams.NextToken = p.nextToken\n\n\tresult, err := p.client.GetDevicePositionHistory(ctx, ¶ms, optFns...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.firstPage = false\n\n\tprevToken := p.nextToken\n\tp.nextToken = result.NextToken\n\n\tif p.options.StopOnDuplicateToken && prevToken != nil && p.nextToken != nil && *prevToken == *p.nextToken {\n\t\tp.nextToken = nil\n\t}\n\n\treturn result, nil\n}",
"func (o *GetReceiptsParams) SetPage(page *int32) {\n\to.Page = page\n}",
"func (x *PDFPage) Ref() *C.pdf_page {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_page)(unsafe.Pointer(x))\n}",
"func (p *PdfiumImplementation) FPDF_VIEWERREF_GetPrintPageRange(request *requests.FPDF_VIEWERREF_GetPrintPageRange) (*responses.FPDF_VIEWERREF_GetPrintPageRange, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpageRange := C.FPDF_VIEWERREF_GetPrintPageRange(documentHandle.handle)\n\tpageRangeHandle := p.registerPageRange(pageRange, documentHandle)\n\n\treturn &responses.FPDF_VIEWERREF_GetPrintPageRange{\n\t\tPageRange: pageRangeHandle.nativeRef,\n\t}, nil\n}",
"func (pager *pager) findPage(pointer int) page {\n\tpageIndex := pointer % pager.pagesize\n\tmyPage, ok := pager.pageMap[pageIndex]\n\tif ok {\n\t\treturn myPage\n\t}\n\tnewPage := page(make([]uint8, pager.pagesize, pager.pagesize))\n\tpager.pageMap[pageIndex] = newPage\n\treturn newPage\n}",
"func allocPDFProcessorMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFProcessorValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (p *Pagination) SimplePage() (from int, to int) {\n\tif p.Num == 0 || p.Size == 0 {\n\t\tp.Num, p.Size = 1, DefaultSize\n\t}\n\tfrom = (p.Num-1)*p.Size + 1\n\tto = from + p.Size - 1\n\treturn\n}",
"func PlotPoint(x, y gb.UINT8) {}",
"func (q *Query) Page(page, page_size int) *Query {\n\tif page < 1 || page_size < 1 {\n\t\tlogrus.Warn(\"illegal page or page_size: \", page, \", \", page_size)\n\t\treturn q\n\t}\n\tq.offset = (page - 1) * page_size\n\tq.limit = page_size\n\treturn q\n}",
"func (o *CreateDashboardRenderTaskParams) SetPdfLandscape(pdfLandscape *bool) {\n\to.PdfLandscape = pdfLandscape\n}",
"func (m *PageManager) WritePage(p *page.Page) error {\n\toffset, ok := m.pageOffsets[p.ID()]\n\t// if there's no offset for the page present yet, append it at the end of\n\t// the page\n\tif !ok {\n\t\tinfo, err := m.file.Stat()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"stat: %w\", err)\n\t\t}\n\t\toffset = info.Size()\n\t\tm.pageOffsets[p.ID()] = offset\n\t}\n\n\tdata := p.CopyOfData()\n\t_, err := m.file.WriteAt(data, offset)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"write at: %w\", err)\n\t}\n\tif err := m.file.Sync(); err != nil {\n\t\treturn fmt.Errorf(\"sync: %w\", err)\n\t}\n\treturn nil\n}",
"func (o *ResolveBatchParams) SetPage(page *int32) {\n\to.Page = page\n}",
"func (a *PDFApiService) DetectPageOrientation(ctx _context.Context, pdfDetectPageOrientationParameters PdfDetectPageOrientationParameters) (PdfDetectPageOrientationResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue PdfDetectPageOrientationResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/pdf/DetectPageOrientation\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json-patch+json\", \"application/json\", \"text/json\", \"application/_*+json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &pdfDetectPageOrientationParameters\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v PdfDetectPageOrientationResponse\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}",
"func (o *GetAuditEventsParams) SetPage(page *int32) {\n\to.Page = page\n}",
"func ExamplePdfMaroto_GetPageSize() {\n\tm := pdf.NewMaroto(consts.Portrait, consts.A4)\n\n\t// Get\n\twidth, height := m.GetPageSize()\n\tfmt.Println(width)\n\tfmt.Println(height)\n\n\t// Do more things and save...\n}",
"func GetPDFPages(inPath string, outPath string, frames []parser.Section) error {\n\n\tif _, err := os.Stat(outPath); os.IsNotExist(err) {\n\t\tlog.Println(\"Output dir not found. Creating at \", outPath)\n\t\terr := os.Mkdir(outPath, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"[PDF Extractor] %s\", err)\n\t\t}\n\t}\n\n\timagick.Initialize()\n\tdefer imagick.Terminate()\n\n\tmw := imagick.NewMagickWand()\n\tdefer mw.Destroy()\n\n\tif err := mw.SetResolution(300, 300); err != nil {\n\t\treturn err\n\t}\n\n\t// Load the image file into imagick\n\tif err := mw.ReadImage(inPath); err != nil {\n\t\treturn err\n\t}\n\n\t// fmt.Println(mw.GetNumberImages())\n\n\t// Set any compression (100 = max quality)\n\tif err := mw.SetCompressionQuality(100); err != nil {\n\t\treturn err\n\t}\n\n\tif err := mw.SetFormat(\"jpg\"); err != nil {\n\t\treturn err\n\t}\n\tvar err error\n\tfor _, frame := range frames {\n\n\t\tmw.SetIteratorIndex(frame.Page - 1)\n\n\t\t// if err := mw.SetImageFormat(\"jpeg\"); err != nil {\n\t\t// \treturn err\n\t\t// }\n\n\t\t// Save File\n\t\terr = mw.WriteImage(filepath.Join(outPath, frame.FrameSrc.ImageSrc))\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%s [PDF extraction: page: %d, loc: %s, to %s] \", err, frame.Page, inPath, filepath.Join(outPath, frame.FrameSrc.ImageSrc))\n\t\t}\n\n\t}\n\treturn nil\n}",
"func (f Page) Address() uintptr {\n\treturn uintptr(f << PageShift)\n}",
"func Pt(x, y int) Point {\n\treturn Point{x, y}\n}",
"func pageAlign(pos int64) int64 {\n\trem := pos % int64(STORE_PAGE_SIZE)\n\tif rem != 0 {\n\t\treturn pos + int64(STORE_PAGE_SIZE) - rem\n\t}\n\treturn pos\n}",
"func (view *View) plot_xy(x, y float32) {\n\tsx, sy := world2screen(x, y)\n\tview.renderer.DrawPoint(sx, sy)\n}",
"func Pt(x, y float64) Point {\n\treturn Point{x, y}\n}",
"func NUpFromPDF(ctx *model.Context, selectedPages types.IntSet, nup *model.NUp) error {\n\tvar mb *types.Rectangle\n\tif nup.PageDim == nil {\n\t\t// No page dimensions specified, use cropBox of page 1 as mediaBox(=cropBox).\n\t\tconsolidateRes := false\n\t\td, _, inhPAttrs, err := ctx.PageDict(1, consolidateRes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif d == nil {\n\t\t\treturn errors.Errorf(\"unknown page number: %d\\n\", 1)\n\t\t}\n\n\t\tcropBox := inhPAttrs.MediaBox\n\t\tif inhPAttrs.CropBox != nil {\n\t\t\tcropBox = inhPAttrs.CropBox\n\t\t}\n\n\t\t// Account for existing rotation.\n\t\tif inhPAttrs.Rotate != 0 {\n\t\t\tif types.IntMemberOf(inhPAttrs.Rotate, []int{+90, -90, +270, -270}) {\n\t\t\t\tw := cropBox.Width()\n\t\t\t\tcropBox.UR.X = cropBox.LL.X + cropBox.Height()\n\t\t\t\tcropBox.UR.Y = cropBox.LL.Y + w\n\t\t\t}\n\t\t}\n\n\t\tmb = cropBox\n\t} else {\n\t\tmb = types.RectForDim(nup.PageDim.Width, nup.PageDim.Height)\n\t}\n\n\tif nup.PageGrid {\n\t\tmb.UR.X = mb.LL.X + float64(nup.Grid.Width)*mb.Width()\n\t\tmb.UR.Y = mb.LL.Y + float64(nup.Grid.Height)*mb.Height()\n\t}\n\n\tpagesDict := types.Dict(\n\t\tmap[string]types.Object{\n\t\t\t\"Type\": types.Name(\"Pages\"),\n\t\t\t\"Count\": types.Integer(0),\n\t\t\t\"MediaBox\": mb.Array(),\n\t\t},\n\t)\n\n\tpagesIndRef, err := ctx.IndRefForNewObject(pagesDict)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnup.PageDim = &types.Dim{Width: mb.Width(), Height: mb.Height()}\n\n\tif err = nupPages(ctx, selectedPages, nup, pagesDict, pagesIndRef); err != nil {\n\t\treturn err\n\t}\n\n\t// Replace original pagesDict.\n\trootDict, err := ctx.Catalog()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trootDict.Update(\"Pages\", *pagesIndRef)\n\n\treturn nil\n}",
"func (o *Origin1) SetPage(v PageType) {\n\to.Page = v\n}",
"func paginate(size int, limit, page uint32) (uint32, uint32) {\n\tif page == 0 {\n\t\tpage = 1\n\t}\n\toffset := (page - 1) * limit\n\tstart, end := offset, uint32(size)\n\tif start >= end {\n\t\treturn 0, 0\n\t}\n\tif limit > 0 && start+limit < end {\n\t\tend = start + limit\n\t}\n\treturn start, end\n}",
"func (debugging *debuggingOpenGL) Viewport(x int32, y int32, width int32, height int32) {\n\tdebugging.recordEntry(\"Viewport\", x, y, width, height)\n\tdebugging.gl.Viewport(x, y, width, height)\n\tdebugging.recordExit(\"Viewport\")\n}",
"func (t *Points) Start(a *app.App) {\n\n\t// Create axes helper\n\taxes := helper.NewAxes(2)\n\ta.Scene().Add(axes)\n\n\t// Creates geometry\n\tgeom := geometry.NewGeometry()\n\tpositions := math32.NewArrayF32(0, 0)\n\tpositions.Append(\n\t\t1, 1, 1,\n\t\t1, 1, -1,\n\t\t-1, 1, -1,\n\t\t-1, 1, 1,\n\t\t1, -1, 1,\n\t\t1, -1, -1,\n\t\t-1, -1, -1,\n\t\t-1, -1, 1,\n\t\t0, 1, 0,\n\t\t0, 0, -1,\n\t\t0, -1, 0,\n\t\t1, 0, 0,\n\t\t-1, 0, 0,\n\t\t0, 0, 1,\n\t\t0, 0, 0,\n\t)\n\tgeom.AddVBO(gls.NewVBO(positions).AddAttrib(gls.VertexPosition))\n\tpositions = nil // Positions cannot be used after transfering to VBO\n\n\t// Creates point material\n\tmat := material.NewPoint(&math32.Color{0, 0, 0})\n\tmat.SetSize(50)\n\n\t// Creates points mesh\n\tmesh := graphic.NewPoints(geom, mat)\n\tmesh.SetScale(1, 1, 1)\n\ta.Scene().Add(mesh)\n}",
"func renderPDF(vb []Visit) gopdf.GoPdf {\n\tdoc := gopdf.GoPdf{}\n\tdoc.Start(gopdf.Config{ PageSize: *gopdf.PageSizeA4 })\n\tdoc.AddPage()\n\terr := doc.AddTTFFont(\"Roboto\", \"./assets/Roboto-Regular.ttf\")\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t}\n\n\tdoc.SetTextColor(getForegroundColor())\n\n\toffsetY := 25\n\n\tfor i,v := range vb {\n\t\toffsetX := 8\n\t\tif i%2 == 1 {\n\t\t\toffsetX = 300\n\t\t}\n\t\tif i%2 == 0 && i != 0 {\n\t\t\toffsetY += 175\n\t\t}\n\t\tdoc.SetX(float64(offsetX))\n\t\tdoc.SetY(float64(offsetY))\n\t\tif err := doc.SetFont(\"Roboto\", \"\", 36); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err := doc.Cell(nil, v.Visitor.LastName); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tdoc.Br(40)\n\t\tdoc.SetX(float64(offsetX))\n\t\tif err := doc.SetFont(\"Roboto\", \"\", 24); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err := doc.Cell(nil, v.Visitor.FirstName); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tdoc.Br(40)\n\t\tdoc.SetX(float64(offsetX))\n\t\tif err := doc.SetFont(\"Roboto\", \"\", 12); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tdoc.Line(float64(offsetX),float64(offsetY + 87), float64(offsetX + 250), float64(offsetY + 87) )\n\t\tdoc.Text(v.Visitor.Company)\n\t\tdoc.Br(24)\n\t\tdoc.SetX(float64(offsetX))\n\t\tdoc.Text(\"Supervisor: \" + v.Supervisor.DisplayName)\n\t\tdoc.Br(18)\n\t\tdoc.SetX(float64(offsetX))\n\t\tt,_ := time.Parse(\"2006-01-02\", v.Date)\n\t\tdoc.Text(\"Gültig am: \" + t.Format(\"02.01.2006\"))\n\t\tdoc.SetFont(\"Roboto\", \"\", 8)\n\t\tdoc.Br(12)\n\t\tdoc.SetX(float64(offsetX))\n\n\t\tdoc.Text(\"Dieses Badge muss jederzeit gut sichtbar getragen werden.\")\n\t}\n\n\tdoc.SetLineType(\"dashed\")\n\tdoc.Line(290, 0, 290, 1500)\n\tdoc.Line(0, 175, 1500, 175)\n\tdoc.Line(0, 350, 1500, 350)\n\tdoc.Line(0, 525, 1500, 525)\n\tdoc.Line(0, 700, 1500, 700)\n\treturn doc\n}",
"func (doc *Document) PageInfo() PageInfo {\n\tpi := PageInfo{RawMessage: doc.Page}\n\tparts := strings.Split(doc.Page, \"-\")\n\tif len(parts) != 2 {\n\t\treturn pi\n\t}\n\tspage, err := strconv.Atoi(parts[0])\n\tif err != nil {\n\t\treturn pi\n\t}\n\tpi.StartPage = spage\n\n\tepage, err := strconv.Atoi(parts[1])\n\tif err != nil {\n\t\treturn pi\n\t}\n\tpi.EndPage = epage\n\treturn pi\n}",
"func Pt(x, y int) fixed.Point26_6 {\n\treturn fixed.Point26_6{\n\t\tX: fixed.Int26_6(x << 6),\n\t\tY: fixed.Int26_6(y << 6),\n\t}\n}"
] | [
"0.68322295",
"0.54504824",
"0.53615063",
"0.51897484",
"0.5179409",
"0.49859002",
"0.4969339",
"0.48631442",
"0.48464602",
"0.4841728",
"0.48271185",
"0.47658938",
"0.47479692",
"0.4696169",
"0.4672267",
"0.46034908",
"0.45791924",
"0.45598286",
"0.4549689",
"0.45429602",
"0.45425376",
"0.44922334",
"0.44862726",
"0.4472382",
"0.44448465",
"0.44006497",
"0.43928087",
"0.4377692",
"0.43688843",
"0.4358801",
"0.43437868",
"0.43245804",
"0.4285059",
"0.42796588",
"0.42726874",
"0.42649755",
"0.42635664",
"0.42589098",
"0.42562124",
"0.423657",
"0.42159688",
"0.4203702",
"0.4197498",
"0.41939822",
"0.41864148",
"0.4174167",
"0.41683853",
"0.4167989",
"0.41643217",
"0.4150478",
"0.41459405",
"0.4141686",
"0.41407466",
"0.41313285",
"0.4125133",
"0.41075805",
"0.4101344",
"0.4099001",
"0.40810865",
"0.40791944",
"0.40777755",
"0.40768436",
"0.40732166",
"0.40693069",
"0.4067288",
"0.4057956",
"0.40571347",
"0.405275",
"0.40424716",
"0.404194",
"0.40299955",
"0.40238813",
"0.4019442",
"0.40154102",
"0.40074393",
"0.40010595",
"0.39992014",
"0.39987198",
"0.399452",
"0.39913312",
"0.39892864",
"0.39768404",
"0.3974261",
"0.3970721",
"0.39692843",
"0.39670867",
"0.3963673",
"0.3962796",
"0.39598593",
"0.39535245",
"0.39532056",
"0.39491126",
"0.39383784",
"0.39374843",
"0.39320302",
"0.39233795",
"0.3920092",
"0.39087886",
"0.39080065",
"0.39048198"
] | 0.71718436 | 0 |
FPDF_PageToDevice converts the page coordinates of a point to screen coordinates. See comments for FPDF_DeviceToPage(). | func (p *PdfiumImplementation) FPDF_PageToDevice(request *requests.FPDF_PageToDevice) (*responses.FPDF_PageToDevice, error) {
p.Lock()
defer p.Unlock()
pageHandle, err := p.loadPage(request.Page)
if err != nil {
return nil, err
}
deviceX := C.int(0)
deviceY := C.int(0)
success := C.FPDF_PageToDevice(pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.double(request.PageX), C.double(request.PageY), &deviceX, &deviceY)
if int(success) == 0 {
return nil, errors.New("could not calculate from page to device")
}
return &responses.FPDF_PageToDevice{
DeviceX: int(deviceX),
DeviceY: int(deviceY),
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (p *PdfiumImplementation) FPDF_DeviceToPage(request *requests.FPDF_DeviceToPage) (*responses.FPDF_DeviceToPage, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpageX := C.double(0)\n\tpageY := C.double(0)\n\n\tsuccess := C.FPDF_DeviceToPage(pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.int(request.DeviceX), C.int(request.DeviceY), &pageX, &pageY)\n\tif int(success) == 0 {\n\t\treturn nil, errors.New(\"could not calculate from device to page\")\n\t}\n\n\treturn &responses.FPDF_DeviceToPage{\n\t\tPageX: float64(pageX),\n\t\tPageY: float64(pageY),\n\t}, nil\n}",
"func (ref *UIElement) ScreenPointForLayoutPoint(p Point) Point {\n\treturn ref.pointForPointAttr(ScreenPointForLayoutPointParameterizedAttribute, p)\n}",
"func (f *Fpdf) PointConvert(pt float64) (u float64) {\n\treturn pt / f.k\n}",
"func (c *Camera) OnScreenPoint(x, y float64) (int, int, bool) {\n\tvar sx, sy int\n\tvar onScreenX, onScreenY bool\n\tsx = int((x-c.lookAtX)*c.zoom + float64(c.screenW)/2.0)\n\tsy = int((c.lookAtY-y)*c.zoom + float64(c.screenH)/2.0)\n\n\tif x < c.sLeft {\n\t\tonScreenX = false\n\t} else if x > c.sRight {\n\t\tonScreenX = false\n\t} else {\n\t\tonScreenX = true\n\t}\n\n\tif y > c.sTop {\n\t\tonScreenY = false\n\t} else if y < c.sBottom {\n\t\tonScreenY = false\n\t} else {\n\t\tonScreenY = true\n\t}\n\treturn sx, sy, onScreenX && onScreenY\n}",
"func canvasToViewPort(x, y float64, c Canvas) Vector {\n\tfw, fh := float64(c.Width()), float64(c.Height())\n\treturn Vector{(x - fw/2) / fw, (y - fh/2) / fh, 1}\n}",
"func OffsetToPage(offset, size int) int {\n\treturn (offset / size) + 1\n}",
"func ScreenXY(value Vec2) *SimpleElement { return newSEVec2(\"screenXY\", value) }",
"func (dw *DrawingWand) Point(x, y float64) {\n\tC.DrawPoint(dw.dw, C.double(x), C.double(y))\n}",
"func (f *Fpdf) UnitToPointConvert(u float64) (pt float64) {\n\treturn u * f.k\n}",
"func (f *Fpdf) PointToUnitConvert(pt float64) (u float64) {\n\treturn pt / f.k\n}",
"func (ref *UIElement) LayoutPointForScreenPoint(p Point) Point {\n\treturn ref.pointForPointAttr(LayoutPointForScreenPointParameterizedAttribute, p)\n}",
"func (c *Context) PointToFixed(x float64) fixed.Int26_6 {\n\treturn fixed.Int26_6(x * float64(c.dpi) * (64.0 / 72.0))\n}",
"func allocPDFPageMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFPageValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func PlotPoint(x, y gb.UINT8) {}",
"func pageAddress(pointer int, pagesize int) int {\n\tpageAddress := pointer % pagesize\n\tif pageAddress < 0 {\n\t\treturn pagesize + pageAddress\n\t}\n\treturn pageAddress\n}",
"func (p Point2D) ToPoint() Point {\n\treturn Point{p.X, p.Y, 0}\n}",
"func (c *Camera) ScreenToWorld(posX, posY int) (float64, float64) {\n\tinverseMatrix := c.worldMatrix()\n\tif inverseMatrix.IsInvertible() {\n\t\tinverseMatrix.Invert()\n\t\treturn inverseMatrix.Apply(float64(posX), float64(posY))\n\t}\n\t// When scaling it can happend that matrix is not invertable\n\treturn math.NaN(), math.NaN()\n}",
"func PageToOffset(page, size int) int {\n\treturn (page - 1) * size\n}",
"func pointToFixed(point image.Point) fixed.Point26_6 {\n\treturn freetype.Pt(point.X, point.Y)\n}",
"func Pt(x, y int) fixed.Point26_6 {\n\treturn fixed.Point26_6{\n\t\tX: fixed.Int26_6(x << 6),\n\t\tY: fixed.Int26_6(y << 6),\n\t}\n}",
"func (od OutlineDest) ToPdfObject() core.PdfObject {\n\treturn core.MakeArray(\n\t\tcore.MakeInteger(od.Page),\n\t\tcore.MakeName(\"XYZ\"),\n\t\tcore.MakeFloat(od.X),\n\t\tcore.MakeFloat(od.Y),\n\t\tcore.MakeFloat(0),\n\t)\n}",
"func (p *PdfiumImplementation) FPDF_RenderPage(request *requests.FPDF_RenderPage) (*responses.FPDF_RenderPage, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thdc, ok := request.DC.(C.HDC)\n\tif !ok {\n\t\treturn nil, errors.New(\"DC is not of type C.HDC\")\n\t}\n\n\tC.FPDF_RenderPage(hdc, pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.int(request.Flags))\n\n\treturn &responses.FPDF_RenderPage{}, nil\n}",
"func GetPDFPage(pdfName string, imageName string, pageNum int) error {\n\n\tabsPath, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tInpath := filepath.Join(absPath, \"input\", pdfName)\n\tOutpath := filepath.Join(absPath, \"output\")\n\n\tif _, err := os.Stat(Outpath); os.IsNotExist(err) {\n\t\tlog.Println(\"Output dir not found. Creating at \", Outpath)\n\t\tos.Mkdir(Outpath, os.ModePerm)\n\t}\n\n\timagick.Initialize()\n\tdefer imagick.Terminate()\n\n\tmw := imagick.NewMagickWand()\n\tdefer mw.Destroy()\n\n\tif err := mw.SetResolution(72, 72); err != nil {\n\t\treturn err\n\t}\n\n\t// Load the image file into imagick\n\tif err := mw.ReadImage(Inpath); err != nil {\n\t\treturn err\n\t}\n\n\tmw.SetIteratorIndex(pageNum - 1)\n\n\t// Set any compression (100 = max quality)\n\tif err := mw.SetCompressionQuality(100); err != nil {\n\t\treturn err\n\t}\n\n\t// Convert into JPG\n\tif err := mw.SetFormat(\"jpg\"); err != nil {\n\t\treturn err\n\t}\n\n\t// Save File\n\treturn mw.WriteImage(filepath.Join(Outpath, imageName))\n}",
"func (view *View) plot_xy(x, y float32) {\n\tsx, sy := world2screen(x, y)\n\tview.renderer.DrawPoint(sx, sy)\n}",
"func (m *PrinterDefaults) GetFitPdfToPage()(*bool) {\n val, err := m.GetBackingStore().Get(\"fitPdfToPage\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}",
"func (f Page) Address() uintptr {\n\treturn uintptr(f << PageShift)\n}",
"func Pt(x, y int) Point {\n\treturn Point{X:x, Y:y}\n}",
"func (m *PrinterDefaults) SetFitPdfToPage(value *bool)() {\n err := m.GetBackingStore().Set(\"fitPdfToPage\", value)\n if err != nil {\n panic(err)\n }\n}",
"func Pt(x, y float64) Point {\n\treturn Point{x, y}\n}",
"func world2screen(wx, wy float32) (sx, sy int) {\n\tsx = int((wx * pixel_per_meter) + (float32(WINDOW_X) / 2.0))\n\tsy = int((-wy * pixel_per_meter) + (float32(WINDOW_Y) / 2.0))\n\treturn\n}",
"func PageFromAddress(virtAddr uintptr) Page {\n\treturn Page((virtAddr & ^(uintptr(PageSize - 1))) >> PageShift)\n}",
"func PointXY(x, y float64) Point {\n\treturn Pt(x, y)\n}",
"func (f *Face) Pt(pt, dpi int) error {\n\theight := C.FT_F26Dot6(pt << 6)\n\tres := C.FT_UInt(dpi)\n\terrno := C.FT_Set_Char_Size(f.handle, 0, height, res, res)\n\tif errno != 0 {\n\t\treturn fmt.Errorf(\"freetype2: %s\", errstr(errno))\n\t}\n\treturn nil\n}",
"func (c *Capsule) PointSDF(coord Coord) (Coord, float64) {\n\tvar p Coord\n\tres := c.genericSDF(coord, nil, &p)\n\treturn p, res\n}",
"func Pt(x, y int) Point {\n\treturn Point{x, y}\n}",
"func (db *DB) page(id pgid) *page {\n\t// buffer := db.data[]\n\t// offset := id*sizeof(PageSize)\n\t// addr := &db.data[offset]\n\t// p := (*page)addr\n\t//\n\t// return p\n\tpos := id * pgid(db.pageSize)\n\treturn (*page)(unsafe.Pointer(&db.data[pos]))\n}",
"func (p *Pin) Pt() (x, y float64) { return p.x, p.y }",
"func (p *PdfiumImplementation) FPDF_RenderPageBitmapWithMatrix(request *requests.FPDF_RenderPageBitmapWithMatrix) (*responses.FPDF_RenderPageBitmapWithMatrix, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmatrix := C.FS_MATRIX{\n\t\ta: C.float(request.Matrix.A),\n\t\tb: C.float(request.Matrix.B),\n\t\tc: C.float(request.Matrix.C),\n\t\td: C.float(request.Matrix.D),\n\t\te: C.float(request.Matrix.E),\n\t\tf: C.float(request.Matrix.F),\n\t}\n\n\tclipping := C.FS_RECTF{\n\t\tleft: C.float(request.Clipping.Left),\n\t\ttop: C.float(request.Clipping.Top),\n\t\tright: C.float(request.Clipping.Right),\n\t\tbottom: C.float(request.Clipping.Bottom),\n\t}\n\n\tC.FPDF_RenderPageBitmapWithMatrix(bitmapHandle.handle, pageHandle.handle, &matrix, &clipping, C.int(request.Flags))\n\n\treturn &responses.FPDF_RenderPageBitmapWithMatrix{}, nil\n}",
"func (p Point) ToPoint2D() Point2D {\n\treturn Point2D{p.X, p.Y}\n}",
"func (t *Triangle) PointSDF(c Coord) (Coord, float64) {\n\tvar p Coord\n\tres := t.genericSDF(c, nil, &p, nil)\n\treturn p, res\n}",
"func (joint Joint) ScreenCoords() (int, int) {\n\n\tif joint.joint == nil {\n\t\tpanic(\"cannot get the screen coordinates of a nil Joint object\")\n\t}\n\n\treturn int(joint.joint.screen_x), int(joint.joint.screen_y)\n}",
"func ListPageNoDevice(pageNo, pageSize int) []Device {\n\tvar dev []Device\n\n\tDB.Model(&Device{}).Order(\"id asc\").Limit(pageSize).Offset((pageNo - 1) * pageSize).Find(&dev)\n\n\treturn dev\n}",
"func (p PointI) ToPoint2DCentered() Point2D {\n\treturn Point2D{float32(p.X) + 0.5, float32(p.Y) + 0.5}\n}",
"func allocPDFProcessorMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFProcessorValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func fpt(p image.Point) f32.Point {\n\treturn f32.Point{\n\t\tX: float32(p.X), Y: float32(p.Y),\n\t}\n}",
"func Epd42(orientation Orientation, spiAddress, reset, dc, busy string, renderOpts ...RenderOpts) (display Display, err error) {\n\n\twidth := 400\n\theight := 300\n\n\tvar renderOpt RenderOpts\n\tif len(renderOpts) == 0 {\n\t\t// We know that using the default font\n\t\t// will work, so no need to handle error\n\t\trenderer, _ := NewFlexRenderEngine(11, 72)\n\t\trenderOpt = RenderOpts{\n\t\t\tRenderer: renderer,\n\t\t\tTemplate: TplDefaultAuto,\n\t\t}\n\t} else {\n\t\trenderOpt = renderOpts[0]\n\t}\n\n\tbase := epd{\n\t\tRendererOpts: renderOpt,\n\t\twidth: width,\n\t\theight: height,\n\t\torientation: orientation,\n\t\tdriver: SpiGpioDriver(),\n\t}\n\n\tsepd := smallEpd{\n\t\tepd: base,\n\t\tRESET: reset,\n\t\tDC: dc,\n\t\tBUSY: busy,\n\t\tSPIAddress: spiAddress,\n\t}\n\n\terr = sepd.init()\n\n\treturn sepd, err\n\n}",
"func (db *DB) page(id pgid) *page {\n\tpos := id * pgid(db.pageSize)\n\treturn (*page)(unsafe.Pointer(&db.data[pos]))\n}",
"func (p *PdfiumImplementation) FPDF_RenderPageBitmap(request *requests.FPDF_RenderPageBitmap) (*responses.FPDF_RenderPageBitmap, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tC.FPDF_RenderPageBitmap(bitmapHandle.handle, pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.int(request.Flags))\n\n\treturn &responses.FPDF_RenderPageBitmap{}, nil\n}",
"func allocPDFVmtxMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFVmtxValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func wmPageZoom(ctx context.Context, tconn *chrome.TestConn, a *arc.ARC, d *ui.Device) error {\n\tact, err := arc.NewActivity(a, wm.Pkg24, wm.ResizableLandscapeActivity)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer act.Close()\n\tif err := act.StartWithDefaultOptions(ctx, tconn); err != nil {\n\t\treturn err\n\t}\n\tdefer act.Stop(ctx, tconn)\n\n\tif err := wm.WaitUntilActivityIsReady(ctx, tconn, act, d); err != nil {\n\t\treturn err\n\t}\n\n\tzoom, err := settings.DefaultZoom(ctx, tconn)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttesting.ContextLog(ctx, \"Default zoom is: \", zoom)\n\n\tboundsOld, err := act.WindowBounds(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttesting.ContextLogf(ctx, \"Window bounds before changing page zoom: %+v\", boundsOld)\n\n\tbutton := d.Object(ui.PackageName(act.PackageName()),\n\t\tui.ClassName(\"android.widget.Button\"),\n\t\tui.ID(\"org.chromium.arc.testapp.windowmanager:id/button_show\"))\n\tif err := button.WaitForExists(ctx, 10*time.Second); err != nil {\n\t\treturn err\n\t}\n\tbuttonBoundsOld, err := button.GetBounds(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttesting.ContextLogf(ctx, \"Button bounds before changing page zoom: %+v\", buttonBoundsOld)\n\n\t// Chrome has zoom factors that go from 0.25x to 5x. But Android only supports zoom factors\n\t// from 0.8x to 1.5x. Android clamps values that are outside the valid range. E.g: a 2.0 zoom factor\n\t// will be \"transformed\" to 1.5x in Android.\n\tconst zoomFactor = 1.5\n\ttesting.ContextLog(ctx, \"Setting page zoom to \", zoomFactor)\n\tif err := settings.SetDefaultZoom(ctx, tconn, zoomFactor); err != nil {\n\t\treturn err\n\t}\n\t// Be nice and restore default zoom on exit.\n\tdefer settings.SetDefaultZoom(ctx, tconn, zoom)\n\n\tif zoom, err := settings.DefaultZoom(ctx, tconn); err != nil {\n\t\treturn err\n\t} else if zoom != zoomFactor {\n\t\t// Checking that zoomFactor got applied correctly and was not converted to any another value.\n\t\treturn errors.Errorf(\"unexpected zoom value: got %f, want %f\", zoom, zoomFactor)\n\t}\n\n\t// After changing the zoom factor, the Android window size should remain the same.\n\t// But the content should be adjusted to the new zoom factor.\n\treturn testing.Poll(ctx, func(ctx context.Context) error {\n\t\tboundsNew, err := act.WindowBounds(ctx)\n\t\tif err != nil {\n\t\t\treturn testing.PollBreak(err)\n\t\t}\n\t\tif boundsNew != boundsOld {\n\t\t\treturn errors.Errorf(\"invalid window bounds: got %v, want %v\", boundsNew, boundsOld)\n\t\t}\n\n\t\tbuttonBoundsNew, err := button.GetBounds(ctx)\n\t\tif err != nil {\n\t\t\treturn testing.PollBreak(err)\n\t\t}\n\n\t\t// Widget size should be bigger by zoomFactor +/- some error margin to deal with rounding issues.\n\t\tconst errorMargin = zoomFactor * 0.1\n\t\twIncrease := float64(buttonBoundsNew.Width) / float64(buttonBoundsOld.Width)\n\t\thIncrease := float64(buttonBoundsNew.Height) / float64(buttonBoundsOld.Height)\n\n\t\tif math.Abs(wIncrease-zoomFactor) > errorMargin {\n\t\t\treturn errors.Errorf(\"invalid button width increase: got %v; want value in [%v, %v] range\",\n\t\t\t\twIncrease, zoomFactor-errorMargin, zoomFactor+errorMargin)\n\t\t}\n\n\t\tif math.Abs(hIncrease-zoomFactor) > errorMargin {\n\t\t\treturn errors.Errorf(\"invalid button height increase: got %v; want value in [%v, %v] range\",\n\t\t\t\thIncrease, zoomFactor-errorMargin, zoomFactor+errorMargin)\n\t\t}\n\t\treturn nil\n\t}, &testing.PollOptions{Timeout: 10 * time.Second})\n}",
"func allocPDFRangeMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFRangeValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func FogCoordPointer(xtype uint32, stride int32, pointer unsafe.Pointer) {\n\tsyscall.Syscall(gpFogCoordPointer, 3, uintptr(xtype), uintptr(stride), uintptr(pointer))\n}",
"func (r *Rect) PointSDF(c Coord) (Coord, float64) {\n\tvar p Coord\n\tres := r.genericSDF(c, nil, &p)\n\treturn p, res\n}",
"func (a *allocator) PhysicalFor(ptes *pagetables.PTEs) uintptr {\n\tvirtual := a.base.PhysicalFor(ptes)\n\tphysical, _, ok := translateToPhysical(virtual)\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"PhysicalFor failed for %p\", ptes)) // escapes: panic.\n\t}\n\treturn physical\n}",
"func pxToMM(px float64) float64 {\n\treturn mmPerPixel * px\n}",
"func (obj *Device) SetViewport(v VIEWPORT) Error {\n\tret, _, _ := syscall.Syscall(\n\t\tobj.vtbl.SetViewport,\n\t\t2,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(unsafe.Pointer(&v)),\n\t\t0,\n\t)\n\treturn toErr(ret)\n}",
"func (win *window) Pixel(pt image.Point) {\n\txwin.PolyPoint(xgb.CoordModeOrigin, win.id, win.gc, []xgb.Point{xgb.Point{int16(pt.X), int16(pt.Y)}})\n}",
"func (m *Memory) moveToPhysicalMemory(p *Page, indexInVm int) {\n\n\t// Remove page from virtual memory\n\tm.VirtualMemory = remove(m.VirtualMemory, indexInVm)\n\n\t// if there is an empty space, put page in empty space\n\tif cap(m.PhysicalMemory)-len(m.PhysicalMemory) > 0 {\n\t\tm.PhysicalMemory = append(m.PhysicalMemory, p)\n\n\t\t// Always add new entry to page table and remove old entry if replaced\n\t\tm.PageTable[p.PageID] = len(m.PhysicalMemory) - 1\n\t}\n\n\t// if there isn't an empty space, run a replace procedure\n\n\t// Find victim page\n\ti, victimPage := m.findVictim(p.ProcID)\n\tif i == -1 {\n\t\treturn\n\t}\n\n\t// Fill victim page's spot\n\tm.PhysicalMemory[i] = p\n\n\t// Always add new entry to page table and remove old entry if replaced\n\tm.PageTable[p.PageID] = i\n\tdelete(m.PageTable, victimPage.PageID)\n\n\t// move victim page to virtual memory\n\tm.VirtualMemory = append(m.VirtualMemory, victimPage)\n}",
"func allocPDFHotspotMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFHotspotValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func coreRatioViewport(fbWidth int, fbHeight int) (x, y, w, h float32) {\n\t// Scale the content to fit in the viewport.\n\tfbw := float32(fbWidth)\n\tfbh := float32(fbHeight)\n\n\t// NXEngine workaround\n\taspectRatio := float32(Geom.AspectRatio)\n\tif aspectRatio == 0 {\n\t\taspectRatio = float32(Geom.BaseWidth) / float32(Geom.BaseHeight)\n\t}\n\n\th = fbh\n\tw = fbh * aspectRatio\n\tif w > fbw {\n\t\th = fbw / aspectRatio\n\t\tw = fbw\n\t}\n\n\t// Place the content in the middle of the window.\n\tx = (fbw - w) / 2\n\ty = (fbh - h) / 2\n\n\tva := vertexArray(x, y, w, h, 1.0)\n\tgl.BindBuffer(gl.ARRAY_BUFFER, vbo)\n\tgl.BufferData(gl.ARRAY_BUFFER, len(va)*4, gl.Ptr(va), gl.STATIC_DRAW)\n\n\treturn\n}",
"func (c *Camera) Viewport() (x float32, y float32, width float32, height float32) {\n\tif c.x > 0 {\n\t\tx = float32(c.x) / float32(c.windowWidth)\n\t}\n\tif c.y > 0 {\n\t\ty = float32(c.y) / float32(c.worldHeight)\n\t}\n\n\tratio := math32.Min(\n\t\tfloat32(c.windowWidth)/float32(c.worldWidth),\n\t\tfloat32(c.windowHeight)/float32(c.worldHeight),\n\t)\n\twidth, height = c.relativeToWindowSize(ratio, ratio)\n\twidth /= float32(c.width) / float32(c.worldWidth)\n\theight /= float32(c.height) / float32(c.worldHeight)\n\treturn x, y, width, height\n}",
"func (o InstancePropertiesOutput) DisplayDevice() DisplayDevicePtrOutput {\n\treturn o.ApplyT(func(v InstanceProperties) *DisplayDevice { return v.DisplayDevice }).(DisplayDevicePtrOutput)\n}",
"func (pager *pager) findPage(pointer int) page {\n\tpageIndex := pointer % pager.pagesize\n\tmyPage, ok := pager.pageMap[pageIndex]\n\tif ok {\n\t\treturn myPage\n\t}\n\tnewPage := page(make([]uint8, pager.pagesize, pager.pagesize))\n\tpager.pageMap[pageIndex] = newPage\n\treturn newPage\n}",
"func (p *Page) LineTo(x, y float64) {\n\tfmt.Fprint(p.contents, x, y, \" l \")\n}",
"func (c *TrackController) Pageview(ctx *app.PageviewTrackContext) error {\n\t_, ok, err := c.PropertyStorage.Get(ctx.Payload.System.PropertyToken.String())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !ok {\n\t\treturn ctx.NotFound()\n\t}\n\n\ttags := map[string]string{\n\t\t\"category\": model.CategoryPageview,\n\t}\n\tvalues := map[string]interface{}{}\n\n\tvar measurement string\n\tswitch ctx.Payload.Action {\n\tcase model.ActionPageviewLoad:\n\t\ttags[\"action\"] = model.ActionPageviewLoad\n\t\tmeasurement = model.TablePageviews\n\tcase model.ActionPageviewTimespent:\n\t\ttags[\"action\"] = model.ActionPageviewTimespent\n\t\tmeasurement = model.TableTimespent\n\t\tif ctx.Payload.Timespent != nil {\n\t\t\tvalues[\"timespent\"] = ctx.Payload.Timespent.Seconds\n\t\t\ttags[\"unload\"] = \"0\"\n\t\t\tif ctx.Payload.Timespent.Unload != nil && *ctx.Payload.Timespent.Unload {\n\t\t\t\ttags[\"unload\"] = \"1\"\n\t\t\t}\n\t\t}\n\tdefault:\n\t\treturn ctx.BadRequest(fmt.Errorf(\"incorrect pageview action [%s]\", ctx.Payload.Action))\n\t}\n\n\tif ctx.Payload.Article != nil {\n\t\ttags[model.FlagArticle] = \"1\"\n\t\tat, av := articleValues(ctx.Payload.Article)\n\t\tfor key, tag := range at {\n\t\t\ttags[key] = tag\n\t\t}\n\t\tfor key, val := range av {\n\t\t\tvalues[key] = val\n\t\t}\n\t} else {\n\t\ttags[model.FlagArticle] = \"0\"\n\t}\n\n\tif err := c.pushInternal(ctx.Payload.System, ctx.Payload.User, measurement, tags, values); err != nil {\n\t\treturn err\n\t}\n\treturn ctx.Accepted()\n}",
"func TexCoordPointer(size int32, xtype uint32, stride int32, pointer unsafe.Pointer) {\n\tsyscall.Syscall6(gpTexCoordPointer, 4, uintptr(size), uintptr(xtype), uintptr(stride), uintptr(pointer), 0, 0)\n}",
"func (p *PdfiumImplementation) FPDFPage_Flatten(request *requests.FPDFPage_Flatten) (*responses.FPDFPage_Flatten, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tflattenPageResult := C.FPDFPage_Flatten(pageHandle.handle, C.int(request.Usage))\n\n\treturn &responses.FPDFPage_Flatten{\n\t\tPage: pageHandle.index,\n\t\tResult: responses.FPDFPage_FlattenResult(flattenPageResult),\n\t}, nil\n}",
"func translateVirtualAddressToPhysicalAddress(addr uint16) (int, int, error) {\n\tbinary := fmt.Sprintf(\"%016b \\n\", addr)\n\tpageNumber, err := strconv.ParseInt(binary[0:4], 2, 64)\n\tif err != nil {\n\t\treturn -1, -1, err\n\n\t}\n\toffset, err := strconv.ParseInt(binary[4:16], 2, 64)\n\tif err != nil {\n\t\treturn -1, -1, err\n\t}\n\treturn int(pageNumber), int(offset), nil\n\n}",
"func allocFzStextPageMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzStextPageValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (p PointI) ToPoint2D() Point2D {\n\treturn Point2D{float32(p.X), float32(p.Y)}\n}",
"func (s *SimPDF) SetPage(pageType string, isLandscape bool) {\n\tswitch p := strings.ToLower(pageType); p {\n\tcase \"letter\":\n\t\ts.Page = defaults.Letter\n\tcase \"legal\":\n\t\ts.Page = defaults.Legal\n\tcase \"tabloid\":\n\t\ts.Page = defaults.Tabloid\n\tcase \"ledger\":\n\t\ts.Page = defaults.Ledger\n\tcase \"ansi\":\n\t\ts.Page = defaults.AnsiA\n\tcase \"a1\":\n\t\ts.Page = defaults.A1\n\tcase \"a2\":\n\t\ts.Page = defaults.A2\n\tcase \"a3\":\n\t\ts.Page = defaults.A3\n\tcase \"a4\":\n\t\ts.Page = defaults.A4\n\tcase \"a5\":\n\t\ts.Page = defaults.A5\n\tdefault:\n\t\ts.Page = defaults.Letter\n\t}\n\ts.Page.IsLandscape = isLandscape\n}",
"func Example23() {\n\tf, err := os.Create(\"Example_23.pdf\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tw := bufio.NewWriter(f)\n\n\tpdf := pdfjet.NewPDF(w, compliance.PDF15)\n\n\tfont := pdfjet.NewCoreFont(pdf, corefont.Helvetica())\n\n\tf, err = os.Open(\"fonts/Droid/DroidSerif-Regular.ttf.stream\")\n\treader := bufio.NewReader(f)\n\tfont2 := pdfjet.NewFontStream1(pdf, reader)\n\n\tf, err = os.Open(\"fonts/Droid/DroidSansMono.ttf.stream\")\n\treader = bufio.NewReader(f)\n\tfont3 := pdfjet.NewFontStream1(pdf, reader)\n\n\tf, err = os.Open(\"images/ee-map.png\")\n\treader = bufio.NewReader(f)\n\timage := pdfjet.NewImage(pdf, reader, imagetype.PNG)\n\tf.Close()\n\n\tpage := pdfjet.NewPage(pdf, letter.Portrait, true)\n\n\tflag := pdfjet.NewBoxAt(85.0, 85.0, 64.0, 32.0)\n\n\tpath := pdfjet.NewPath()\n\n\tpath.Add(pdfjet.NewPoint(13.0, 0.0))\n\tpath.Add(pdfjet.NewPoint(15.5, 4.5))\n\n\tpath.Add(pdfjet.NewPoint(18.0, 3.5))\n\tpath.Add(pdfjet.NewControlPoint(15.5, 13.5))\n\tpath.Add(pdfjet.NewControlPoint(15.5, 13.5))\n\tpath.Add(pdfjet.NewPoint(20.5, 7.5))\n\n\tpath.Add(pdfjet.NewPoint(21.0, 9.5))\n\tpath.Add(pdfjet.NewPoint(25.0, 9.0))\n\tpath.Add(pdfjet.NewPoint(24.0, 13.0))\n\tpath.Add(pdfjet.NewPoint(25.5, 14.0))\n\tpath.Add(pdfjet.NewPoint(19.0, 19.0))\n\tpath.Add(pdfjet.NewPoint(20.0, 21.5))\n\tpath.Add(pdfjet.NewPoint(13.5, 20.5))\n\tpath.Add(pdfjet.NewPoint(13.5, 27.0))\n\tpath.Add(pdfjet.NewPoint(12.5, 27.0))\n\tpath.Add(pdfjet.NewPoint(12.5, 20.5))\n\tpath.Add(pdfjet.NewPoint(6.0, 21.5))\n\tpath.Add(pdfjet.NewPoint(7.0, 19.0))\n\tpath.Add(pdfjet.NewPoint(0.5, 14.0))\n\tpath.Add(pdfjet.NewPoint(2.0, 13.0))\n\tpath.Add(pdfjet.NewPoint(1.0, 9.0))\n\tpath.Add(pdfjet.NewPoint(5.0, 9.5))\n\n\tpath.Add(pdfjet.NewPoint(5.5, 7.5))\n\tpath.Add(pdfjet.NewControlPoint(10.5, 13.5))\n\tpath.Add(pdfjet.NewControlPoint(10.5, 13.5))\n\tpath.Add(pdfjet.NewPoint(8.0, 3.5))\n\n\tpath.Add(pdfjet.NewPoint(10.5, 4.5))\n\tpath.SetClosePath(true)\n\tpath.SetColor(color.Red)\n\tpath.SetFillShape(true)\n\tpath.PlaceIn(flag, 19.0, 3.0)\n\n\tpath.DrawOn(page)\n\n\tbox := pdfjet.NewBox()\n\tbox.SetSize(16.0, 32.0)\n\tbox.SetColor(color.Red)\n\tbox.SetFillShape(true)\n\tbox.PlaceIn(flag, 0.0, 0.0)\n\tbox.DrawOn(page)\n\tbox.PlaceIn(flag, 48.0, 0.0)\n\tbox.DrawOn(page)\n\n\tpath.ScaleBy(15.0)\n\tpath.SetFillShape(false)\n\txy := path.DrawOn(page)\n\n\tbox = pdfjet.NewBox()\n\tbox.SetLocation(xy[0], xy[1])\n\tbox.SetSize(20.0, 20.0)\n\tbox.DrawOn(page)\n\n\tfont.SetSize(24.0)\n\ttextField := pdfjet.NewTextLine(font, \"Hello, World!\")\n\ttextField.SetLocation(300.0, 300.0)\n\ttextField.SetColor(color.Blanchedalmond)\n\ttextField.DrawOn(page)\n\n\tfont2.SetSize(24.0)\n\ttextField2 := pdfjet.NewTextLine(font2, \"This is great!\")\n\ttextField2.SetLocation(400.0, 400.0)\n\ttextField2.SetColor(color.Blue)\n\ttextField2.SetStrikeout(true)\n\ttextField2.SetUnderline(true)\n\ttextField2.DrawOn(page)\n\n\tfont2.SetSize(14.0)\n\ttextField2 = pdfjet.NewTextLine(font2, \"This is great!\")\n\ttextField2.SetLocation(400.0, 500.0)\n\ttextField2.SetColor(color.Blue)\n\ttextField2.DrawOn(page)\n\n\tfont3.SetSize(24.0)\n\ttextField2 = pdfjet.NewTextLine(font3, \"This is great!\")\n\ttextField2.SetLocation(400.0, 600.0)\n\ttextField2.SetColor(color.Blue)\n\ttextField2.DrawOn(page)\n\n\timage.SetLocation(100.0, 500.0)\n\timage.ScaleBy(0.5)\n\timage.DrawOn(page)\n\n\tpdf.Complete()\n\n\tf.Close()\n}",
"func (p *GetDevicePositionHistoryPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*GetDevicePositionHistoryOutput, error) {\n\tif !p.HasMorePages() {\n\t\treturn nil, fmt.Errorf(\"no more pages available\")\n\t}\n\n\tparams := *p.params\n\tparams.NextToken = p.nextToken\n\n\tresult, err := p.client.GetDevicePositionHistory(ctx, ¶ms, optFns...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.firstPage = false\n\n\tprevToken := p.nextToken\n\tp.nextToken = result.NextToken\n\n\tif p.options.StopOnDuplicateToken && prevToken != nil && p.nextToken != nil && *prevToken == *p.nextToken {\n\t\tp.nextToken = nil\n\t}\n\n\treturn result, nil\n}",
"func NewPDFPage() *PDFPage {\n\treturn (*PDFPage)(allocPDFPageMemory(1))\n}",
"func allocPDFDocumentMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFDocumentValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (tv *TextView) PixelToCursor(pt image.Point) TextPos {\n\tif tv.NLines == 0 {\n\t\treturn TextPosZero\n\t}\n\tsty := &tv.Sty\n\tyoff := float32(tv.WinBBox.Min.Y)\n\tstln := tv.FirstVisibleLine(0)\n\tcln := stln\n\tfls := tv.CharStartPos(TextPos{Ln: stln}).Y - yoff\n\tif pt.Y < int(mat32.Floor(fls)) {\n\t\tcln = stln\n\t} else if pt.Y > tv.WinBBox.Max.Y {\n\t\tcln = tv.NLines - 1\n\t} else {\n\t\tgot := false\n\t\tfor ln := stln; ln < tv.NLines; ln++ {\n\t\t\tls := tv.CharStartPos(TextPos{Ln: ln}).Y - yoff\n\t\t\tes := ls\n\t\t\tes += mat32.Max(tv.Renders[ln].Size.Y, tv.LineHeight)\n\t\t\tif pt.Y >= int(mat32.Floor(ls)) && pt.Y < int(mat32.Ceil(es)) {\n\t\t\t\tgot = true\n\t\t\t\tcln = ln\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !got {\n\t\t\tcln = tv.NLines - 1\n\t\t}\n\t}\n\t// fmt.Printf(\"cln: %v pt: %v\\n\", cln, pt)\n\tlnsz := tv.Buf.LineLen(cln)\n\tif lnsz == 0 {\n\t\treturn TextPos{Ln: cln, Ch: 0}\n\t}\n\txoff := float32(tv.WinBBox.Min.X)\n\tscrl := tv.WinBBox.Min.X - tv.ObjBBox.Min.X\n\tnolno := pt.X - int(tv.LineNoOff)\n\tsc := int(float32(nolno+scrl) / sty.Font.Face.Metrics.Ch)\n\tsc -= sc / 4\n\tsc = ints.MaxInt(0, sc)\n\tcch := sc\n\n\tsi := 0\n\tspoff := 0\n\tnspan := len(tv.Renders[cln].Spans)\n\tlstY := tv.CharStartPos(TextPos{Ln: cln}).Y - yoff\n\tif nspan > 1 {\n\t\tsi = int((float32(pt.Y) - lstY) / tv.LineHeight)\n\t\tsi = ints.MinInt(si, nspan-1)\n\t\tsi = ints.MaxInt(si, 0)\n\t\tfor i := 0; i < si; i++ {\n\t\t\tspoff += len(tv.Renders[cln].Spans[i].Text)\n\t\t}\n\t\t// fmt.Printf(\"si: %v spoff: %v\\n\", si, spoff)\n\t}\n\n\tri := sc\n\trsz := len(tv.Renders[cln].Spans[si].Text)\n\tif rsz == 0 {\n\t\treturn TextPos{Ln: cln, Ch: spoff}\n\t}\n\t// fmt.Printf(\"sc: %v rsz: %v\\n\", sc, rsz)\n\n\tc, _ := tv.Renders[cln].SpanPosToRuneIdx(si, rsz-1) // end\n\trsp := mat32.Floor(tv.CharStartPos(TextPos{Ln: cln, Ch: c}).X - xoff)\n\trep := mat32.Ceil(tv.CharEndPos(TextPos{Ln: cln, Ch: c}).X - xoff)\n\tif int(rep) < pt.X { // end of line\n\t\tif si == nspan-1 {\n\t\t\tc++\n\t\t}\n\t\treturn TextPos{Ln: cln, Ch: c}\n\t}\n\n\ttooBig := false\n\tgot := false\n\tif ri < rsz {\n\t\tfor rii := ri; rii < rsz; rii++ {\n\t\t\tc, _ := tv.Renders[cln].SpanPosToRuneIdx(si, rii)\n\t\t\trsp = mat32.Floor(tv.CharStartPos(TextPos{Ln: cln, Ch: c}).X - xoff)\n\t\t\trep = mat32.Ceil(tv.CharEndPos(TextPos{Ln: cln, Ch: c}).X - xoff)\n\t\t\t// fmt.Printf(\"trying c: %v for pt: %v xoff: %v rsp: %v, rep: %v\\n\", c, pt, xoff, rsp, rep)\n\t\t\tif pt.X >= int(rsp) && pt.X < int(rep) {\n\t\t\t\tcch = c\n\t\t\t\tgot = true\n\t\t\t\t// fmt.Printf(\"got cch: %v for pt: %v rsp: %v, rep: %v\\n\", cch, pt, rsp, rep)\n\t\t\t\tbreak\n\t\t\t} else if int(rep) > pt.X {\n\t\t\t\tcch = c\n\t\t\t\ttooBig = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else {\n\t\ttooBig = true\n\t}\n\tif !got && tooBig {\n\t\tri = rsz - 1\n\t\t// fmt.Printf(\"too big: %v\\n\", ri)\n\t\tfor rii := ri; rii >= 0; rii-- {\n\t\t\tc, _ := tv.Renders[cln].SpanPosToRuneIdx(si, rii)\n\t\t\trsp := mat32.Floor(tv.CharStartPos(TextPos{Ln: cln, Ch: c}).X - xoff)\n\t\t\trep := mat32.Ceil(tv.CharEndPos(TextPos{Ln: cln, Ch: c}).X - xoff)\n\t\t\t// fmt.Printf(\"too big: trying c: %v for pt: %v rsp: %v, rep: %v\\n\", c, pt, rsp, rep)\n\t\t\tif pt.X >= int(rsp) && pt.X < int(rep) {\n\t\t\t\tgot = true\n\t\t\t\tcch = c\n\t\t\t\t// fmt.Printf(\"got cch: %v for pt: %v rsp: %v, rep: %v\\n\", cch, pt, rsp, rep)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn TextPos{Ln: cln, Ch: cch}\n}",
"func (mm *atmanMemoryManager) allocPage(page vaddr) {\n\tvar (\n\t\tl4offset = page.pageTableOffset(pageTableLevel4)\n\t\tl3offset = page.pageTableOffset(pageTableLevel3)\n\t\tl2offset = page.pageTableOffset(pageTableLevel2)\n\t\tl1offset = page.pageTableOffset(pageTableLevel1)\n\t)\n\n\tl4 := mm.l4\n\tl3pte := l4.Get(l4offset)\n\n\tif !l3pte.hasFlag(xenPageTablePresent) {\n\t\tpfn := mm.physAllocPage()\n\t\tl3pte = mm.writePte(mm.l4PFN, l4offset, pfn, PTE_PAGE_TABLE_FLAGS|xenPageTableWritable)\n\t}\n\n\tl3 := mm.getPageTable(-1, -1, l4offset)\n\tl2pte := l3.Get(l3offset)\n\n\tif !l2pte.hasFlag(xenPageTablePresent) {\n\t\tpfn := mm.physAllocPage()\n\t\tl2pte = mm.writePte(l3pte.pfn(), l3offset, pfn, PTE_PAGE_TABLE_FLAGS|xenPageTableWritable)\n\t}\n\n\tl2 := mm.getPageTable(-1, l4offset, l3offset)\n\tl1pte := l2.Get(l2offset)\n\n\tif !l1pte.hasFlag(xenPageTablePresent) {\n\t\tpfn := mm.physAllocPage()\n\t\tl1pte = mm.writePte(l2pte.pfn(), l2offset, pfn, PTE_PAGE_TABLE_FLAGS|xenPageTableWritable)\n\t}\n\n\tpagepfn := mm.physAllocPage()\n\tmm.writePte(l1pte.pfn(), l1offset, pagepfn, PTE_PAGE_FLAGS)\n\n\t// ensure page is writable\n\t*(*uintptr)(unsafe.Pointer(page)) = 0x0\n}",
"func (s *SimPDF) NewPage(page models.Pages) {\n\ts.Page = page\n\ts.PDF.AddPageFormat(page.ToPDFOrientation(), gofpdf.SizeType{Wd: page.Width, Ht: page.Height})\n}",
"func (obj *Device) GetViewport() (v VIEWPORT, err Error) {\n\tret, _, _ := syscall.Syscall(\n\t\tobj.vtbl.GetViewport,\n\t\t2,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(unsafe.Pointer(&v)),\n\t\t0,\n\t)\n\terr = toErr(ret)\n\treturn\n}",
"func (o InstancePropertiesPtrOutput) DisplayDevice() DisplayDevicePtrOutput {\n\treturn o.ApplyT(func(v *InstanceProperties) *DisplayDevice {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.DisplayDevice\n\t}).(DisplayDevicePtrOutput)\n}",
"func allocPDFCmapMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFCmapValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func NewPtrPageBuffer(aSlice interface{}, desiredPageNo int) *PageBuffer {\n aSliceValue := sliceValue(aSlice, true)\n return newPageBuffer(\n aSliceValue,\n desiredPageNo,\n overwriteNilPtrHandler{\n creater: newCreaterFunc(nil, aSliceValue.Type())})\n}",
"func allocPDFDocEventMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFDocEventValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (ds *DrawStack) DrawToScreen(world draw.Image, view *intgeom.Point2, w, h int) {\n\tfor _, a := range ds.as {\n\t\t// If we had concurrent operations, we'd do it here\n\t\t// in that case each draw call would return to us something\n\t\t// to composite onto the window / world\n\t\ta.DrawToScreen(world, view, w, h)\n\t}\n}",
"func SetViewport(x Int, y Int, width Sizei, height Sizei) {\n\tcx, _ := (C.GLint)(x), cgoAllocsUnknown\n\tcy, _ := (C.GLint)(y), cgoAllocsUnknown\n\tcwidth, _ := (C.GLsizei)(width), cgoAllocsUnknown\n\tcheight, _ := (C.GLsizei)(height), cgoAllocsUnknown\n\tC.glViewport(cx, cy, cwidth, cheight)\n}",
"func (p PointI) ToPoint() Point {\n\treturn Point{float32(p.X), float32(p.Y), 0}\n}",
"func (s *service) SetDevicePosition(ctx context.Context, uid models.UID, ip string) error {\n\tipParsed := net.ParseIP(ip)\n\tposition, err := s.locator.GetPosition(ipParsed)\n\tif err != nil {\n\t\tlogrus.\n\t\t\tWithError(err).\n\t\t\tWithFields(logrus.Fields{\n\t\t\t\t\"uid\": uid,\n\t\t\t\t\"ip\": ip,\n\t\t\t}).Error(\"Failed to get device's position\")\n\t}\n\n\tdevicePosition := models.DevicePosition{\n\t\tLongitude: position.Longitude,\n\t\tLatitude: position.Latitude,\n\t}\n\n\terr = s.store.DeviceSetPosition(ctx, uid, devicePosition)\n\tif err != nil {\n\t\tlogrus.\n\t\t\tWithError(err).\n\t\t\tWithFields(logrus.Fields{\n\t\t\t\t\"uid\": uid,\n\t\t\t\t\"ip\": ip,\n\t\t\t}).Error(\"Failed to set device's position to database\")\n\n\t\treturn err\n\t}\n\tlogrus.WithFields(logrus.Fields{\n\t\t\"uid\": uid,\n\t\t\"ip\": ip,\n\t\t\"position\": position,\n\t}).Debug(\"Success to set device's position\")\n\n\treturn nil\n}",
"func FogCoordPointer(xtype uint32, stride int32, pointer unsafe.Pointer) {\n C.glowFogCoordPointer(gpFogCoordPointer, (C.GLenum)(xtype), (C.GLsizei)(stride), pointer)\n}",
"func NUpFromPDF(ctx *model.Context, selectedPages types.IntSet, nup *model.NUp) error {\n\tvar mb *types.Rectangle\n\tif nup.PageDim == nil {\n\t\t// No page dimensions specified, use cropBox of page 1 as mediaBox(=cropBox).\n\t\tconsolidateRes := false\n\t\td, _, inhPAttrs, err := ctx.PageDict(1, consolidateRes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif d == nil {\n\t\t\treturn errors.Errorf(\"unknown page number: %d\\n\", 1)\n\t\t}\n\n\t\tcropBox := inhPAttrs.MediaBox\n\t\tif inhPAttrs.CropBox != nil {\n\t\t\tcropBox = inhPAttrs.CropBox\n\t\t}\n\n\t\t// Account for existing rotation.\n\t\tif inhPAttrs.Rotate != 0 {\n\t\t\tif types.IntMemberOf(inhPAttrs.Rotate, []int{+90, -90, +270, -270}) {\n\t\t\t\tw := cropBox.Width()\n\t\t\t\tcropBox.UR.X = cropBox.LL.X + cropBox.Height()\n\t\t\t\tcropBox.UR.Y = cropBox.LL.Y + w\n\t\t\t}\n\t\t}\n\n\t\tmb = cropBox\n\t} else {\n\t\tmb = types.RectForDim(nup.PageDim.Width, nup.PageDim.Height)\n\t}\n\n\tif nup.PageGrid {\n\t\tmb.UR.X = mb.LL.X + float64(nup.Grid.Width)*mb.Width()\n\t\tmb.UR.Y = mb.LL.Y + float64(nup.Grid.Height)*mb.Height()\n\t}\n\n\tpagesDict := types.Dict(\n\t\tmap[string]types.Object{\n\t\t\t\"Type\": types.Name(\"Pages\"),\n\t\t\t\"Count\": types.Integer(0),\n\t\t\t\"MediaBox\": mb.Array(),\n\t\t},\n\t)\n\n\tpagesIndRef, err := ctx.IndRefForNewObject(pagesDict)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnup.PageDim = &types.Dim{Width: mb.Width(), Height: mb.Height()}\n\n\tif err = nupPages(ctx, selectedPages, nup, pagesDict, pagesIndRef); err != nil {\n\t\treturn err\n\t}\n\n\t// Replace original pagesDict.\n\trootDict, err := ctx.Catalog()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trootDict.Update(\"Pages\", *pagesIndRef)\n\n\treturn nil\n}",
"func allocPDFXrangeMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFXrangeValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func FogCoordPointer(xtype uint32, stride int32, pointer unsafe.Pointer) {\n\tC.glowFogCoordPointer(gpFogCoordPointer, (C.GLenum)(xtype), (C.GLsizei)(stride), pointer)\n}",
"func (m *IntPointORM) ToPB(ctx context.Context) (IntPoint, error) {\n\tto := IntPoint{}\n\tvar err error\n\tif prehook, ok := interface{}(m).(IntPointWithBeforeToPB); ok {\n\t\tif err = prehook.BeforeToPB(ctx, &to); err != nil {\n\t\t\treturn to, err\n\t\t}\n\t}\n\tto.Id = m.Id\n\tto.X = m.X\n\tto.Y = m.Y\n\tif posthook, ok := interface{}(m).(IntPointWithAfterToPB); ok {\n\t\terr = posthook.AfterToPB(ctx, &to)\n\t}\n\treturn to, err\n}",
"func FrameFromAddress(physAddr uintptr) Frame {\n\treturn Frame((physAddr & ^(uintptr(PageSize - 1))) >> PageShift)\n}",
"func ToFixedPoint(x, y float32) fixed.Point26_6 {\n\treturn fixed.Point26_6{X: ToFixed(x), Y: ToFixed(y)}\n}",
"func (p *PDF) Move(xDelta, yDelta float64) {\n\tp.x, p.y = p.x+xDelta, p.y+yDelta\n\tp.fpdf.MoveTo(p.x, p.y)\n}",
"func (obj *Device) SetCursorPosition(x int, y int, flags uint32) {\n\tsyscall.Syscall6(\n\t\tobj.vtbl.SetCursorPosition,\n\t\t4,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(x),\n\t\tuintptr(y),\n\t\tuintptr(flags),\n\t\t0,\n\t\t0,\n\t)\n}",
"func Viewport(x int, y int, width int, height int) {\n\tC.glViewport(C.GLint(x), C.GLint(y), C.GLsizei(width), C.GLsizei(height))\n}",
"func allocFzPageMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzPageValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (pager *pager) setValue(pointer int, value uint8) {\n\tpage := pager.findPage(pointer)\n\tpageAddress := pageAddress(pointer, pager.pagesize)\n\tpage[pageAddress] = value\n}",
"func (p *Page) MoveTo(x, y float64) {\n\tfmt.Fprint(p.contents, x, y, \" m \")\n}"
] | [
"0.68169916",
"0.5332848",
"0.5289199",
"0.5216343",
"0.51495874",
"0.49680805",
"0.49320528",
"0.4886728",
"0.48845625",
"0.4864202",
"0.4847036",
"0.4754407",
"0.4682643",
"0.4673133",
"0.46712962",
"0.465961",
"0.46372196",
"0.46210748",
"0.46112153",
"0.45833147",
"0.455776",
"0.4553104",
"0.45445657",
"0.4514586",
"0.44592965",
"0.44566023",
"0.44440997",
"0.4436587",
"0.44360554",
"0.44335222",
"0.44304302",
"0.44262838",
"0.44177547",
"0.44089478",
"0.43884298",
"0.4379376",
"0.43693516",
"0.43337166",
"0.43334678",
"0.4314765",
"0.42804685",
"0.42597765",
"0.42532063",
"0.4230845",
"0.42094597",
"0.4207727",
"0.41923985",
"0.4189357",
"0.41865832",
"0.4169557",
"0.4157605",
"0.41399375",
"0.4130332",
"0.41275746",
"0.41212004",
"0.41197097",
"0.41158903",
"0.41109487",
"0.4107064",
"0.40985015",
"0.40881363",
"0.4069877",
"0.40658677",
"0.4062358",
"0.40607694",
"0.40605444",
"0.40598023",
"0.40595722",
"0.40568447",
"0.4056483",
"0.40484476",
"0.40467867",
"0.40421885",
"0.40370563",
"0.40289932",
"0.40205342",
"0.40153882",
"0.40126893",
"0.40123495",
"0.4008827",
"0.40033343",
"0.40023047",
"0.39991212",
"0.39941934",
"0.39927244",
"0.39921197",
"0.39830664",
"0.398148",
"0.39807755",
"0.39796978",
"0.39792752",
"0.39648417",
"0.39587092",
"0.39576918",
"0.3950689",
"0.39374",
"0.39359254",
"0.39334452",
"0.39313135",
"0.39311987"
] | 0.7368943 | 0 |
FPDFBitmap_Create Create a device independent bitmap (FXDIB). | func (p *PdfiumImplementation) FPDFBitmap_Create(request *requests.FPDFBitmap_Create) (*responses.FPDFBitmap_Create, error) {
p.Lock()
defer p.Unlock()
bitmap := C.FPDFBitmap_Create(C.int(request.Width), C.int(request.Height), C.int(request.Alpha))
bitmapHandle := p.registerBitmap(bitmap)
return &responses.FPDFBitmap_Create{
Bitmap: bitmapHandle.nativeRef,
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (p *PdfiumImplementation) FPDFBitmap_CreateEx(request *requests.FPDFBitmap_CreateEx) (*responses.FPDFBitmap_CreateEx, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tvar pointer unsafe.Pointer\n\tif request.Buffer != nil {\n\t\tpointer = unsafe.Pointer(&request.Buffer[0])\n\t} else if request.Pointer != nil {\n\t\tv, ok := request.Pointer.(unsafe.Pointer)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"request.Pointer is not of type unsafe.Pointer\")\n\t\t}\n\n\t\tpointer = v\n\t}\n\n\tbitmap := C.FPDFBitmap_CreateEx(C.int(request.Width), C.int(request.Height), C.int(request.Format), pointer, C.int(request.Stride))\n\tbitmapHandle := p.registerBitmap(bitmap)\n\n\treturn &responses.FPDFBitmap_CreateEx{\n\t\tBitmap: bitmapHandle.nativeRef,\n\t}, nil\n}",
"func NewBitmap(fn Name) (*Bitmap, error) {\n\t// Each font is hard-coded into the binary as a slice of bytes.\n\tinfo, err := fontInfo(fn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Which is then decoded.\n\tpngImage, err := png.Decode(bytes.NewReader(info.byts))\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"font %+v\", fn)\n\t}\n\n\tebiImage := ebiten.NewImageFromImage(pngImage)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"font %+v\", fn)\n\t}\n\n\treturn &Bitmap{\n\t\timg: ebiImage,\n\t\tsize: info.size,\n\t\tmask: info.mask,\n\t\tsubmap: make(map[rune]*Glyph),\n\t}, nil\n}",
"func NewFzBitmap() *FzBitmap {\n\treturn (*FzBitmap)(allocFzBitmapMemory(1))\n}",
"func NewFzBitmapRef(ref unsafe.Pointer) *FzBitmap {\n\treturn (*FzBitmap)(ref)\n}",
"func (f *DynamicDiskBlockFactory) GetBitmapFactory() *bitmap.Factory {\n\treturn f.bitmapFactory\n}",
"func allocFzBitmapMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzBitmapValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func New(width, height int) *Bitmap {\n\tbm := &Bitmap{\n\t\tWidth: width,\n\t\tHeight: height,\n\t\tRowStride: (width + 7) >> 3,\n\t}\n\tbm.Data = make([]byte, height*bm.RowStride)\n\n\treturn bm\n}",
"func newBitmap(size int) *bitmap {\n\tdiv, mod := size/8, size%8\n\tif mod > 0 {\n\t\tdiv++\n\t}\n\treturn &bitmap{size, make([]byte, div)}\n}",
"func WndProc(hwnd syscall.Handle, msg uint32, wparam, lparam uintptr) (rc uintptr) {\n\t_ = make([]int, 100000)\n\tswitch msg {\n\tcase wingui.WM_CREATE:\n\t\thdc := wingui.GetDC(hwnd)\n\t\thdcWndBuffer = wingui.CreateCompatibleDC(hdc)\n\t\twndBufferHeader = wingui.CreateCompatibleBitmap(hdc, 600, 800)\n\t\twingui.GetObject(wndBufferHeader, unsafe.Sizeof(wndBuffer), uintptr(unsafe.Pointer(&wndBuffer)))\n\t\twingui.SelectObject(hdcWndBuffer, wndBufferHeader)\n\n\t\tvar bmp_header wingui.BITMAPINFOHEADER\n\t\tbmp_header.Size = uint32(unsafe.Sizeof(bmp_header))\n\t\tbmp_header.Width = 600\n\t\tbmp_header.Height = 800\n\t\tbmp_header.SizeImage = 0 // the api says this must be 0 for BI_RGB images\n\t\tbmp_header.Compression = wingui.BI_RGB\n\t\tbmp_header.BitCount = 32\n\t\tbmp_header.Planes = 1\n\t\tbmp_header.XPelsPerMeter = 0\n\t\tbmp_header.YPelsPerMeter = 0\n\t\tbmp_header.ClrUsed = 0\n\t\tbmp_header.ClrImportant = 0\n\t\t//bitmap info\n\t\tvar bmpinfo wingui.BITMAPINFO\n\t\tbmpinfo.Colors[0].Blue = 0\n\t\tbmpinfo.Colors[0].Green = 0\n\t\tbmpinfo.Colors[0].Red = 0\n\t\tbmpinfo.Colors[0].Reserved = 0\n\t\tbmpinfo.Header = bmp_header\n\t\twndBufferHeader = wingui.CreateDIBSection(hdc, &bmpinfo, wingui.DIB_RGB_COLORS, uintptr(unsafe.Pointer(&ppvBits)), 0, 0)\n\t\twingui.GetObject(wndBufferHeader, unsafe.Sizeof(wndBufferHeader), uintptr(unsafe.Pointer(&wndBuffer)))\n\t\thdcWndBuffer = wingui.CreateCompatibleDC(hdc)\n\t\twingui.SelectObject(hdcWndBuffer, wndBufferHeader)\n\n\t\tpixel := (*[600 * 800 * 4]uint8)(unsafe.Pointer(ppvBits))\n\t\tpixelSlice := pixel[:]\n\t\tbackBuffer = &image.RGBA{pixelSlice, 4*600, image.Rect(0, 0, 600, 800)}\n\t\tfmt.Println(\"Create windows\")\n\t\trc = wingui.DefWindowProc(hwnd, msg, wparam, lparam)\n\tcase wingui.WM_COMMAND:\n\t\tswitch syscall.Handle(lparam) {\n\t\tdefault:\n\t\t\trc = wingui.DefWindowProc(hwnd, msg, wparam, lparam)\n\t\t}\n\tcase wingui.WM_PAINT:\n\t\tvar ps wingui.PAINTSTRUCT\n\t\thdc := wingui.BeginPaint(hwnd, &ps)\n\t\tt := time.Now()\n\t\tgc := draw2d.NewGraphicContext(backBuffer)\n\t\t/*gc.SetFillColor(color.RGBA{0xFF, 0xFF, 0xFF, 0xFF})\n\t\tgc.Clear()*/\n\t\tfor i := 0; i < len(backBuffer.Pix); i+=1 {\n\t\t\tbackBuffer.Pix[i] = 0xff\n\t\t}\n\t\tgc.Save()\n\t\t//gc.Translate(0, -380)\n\t\tDrawTiger(gc)\n\t\tgc.Restore()\n\t\t// back buf in\n\t\tvar tmp uint8\n\t\tfor i := 0; i < len(backBuffer.Pix); i+=4 {\n\t\t\ttmp = backBuffer.Pix[i]\n\t\t\tbackBuffer.Pix[i] = backBuffer.Pix[i+2]\n\t\t\tbackBuffer.Pix[i+2] = tmp\n\t\t}\n\t\twingui.BitBlt(hdc, 0, 0, int(wndBuffer.Width), int(wndBuffer.Height), hdcWndBuffer, 0, 0, wingui.SRCCOPY)\n\t\twingui.EndPaint(hwnd, &ps)\n\t\trc = wingui.DefWindowProc(hwnd, msg, wparam, lparam)\n\t\tdt := time.Now().Sub(t)\n\t\tfmt.Printf(\"Redraw in : %f ms\\n\", float64(dt)*1e-6)\n\tcase wingui.WM_CLOSE:\n\t\twingui.DestroyWindow(hwnd)\n\tcase wingui.WM_DESTROY:\n\t\twingui.PostQuitMessage(0)\n\tdefault:\n\t\trc = wingui.DefWindowProc(hwnd, msg, wparam, lparam)\n\t}\n\treturn\n}",
"func (p *PdfiumImplementation) FPDFBitmap_Destroy(request *requests.FPDFBitmap_Destroy) (*responses.FPDFBitmap_Destroy, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tC.FPDFBitmap_Destroy(bitmapHandle.handle)\n\n\tdelete(p.bitmapRefs, bitmapHandle.nativeRef)\n\n\treturn &responses.FPDFBitmap_Destroy{}, nil\n}",
"func allocFzPixmapMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzPixmapValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func allocFzPixmapImageMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzPixmapImageValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func newBitmapFromBytes(data []byte) *bitmap {\n\tbitmap := newBitmap(len(data) * 8)\n\tcopy(bitmap.data, data)\n\treturn bitmap\n}",
"func allocFzDrawOptionsMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzDrawOptionsValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func NewFzPixmapRef(ref unsafe.Pointer) *FzPixmap {\n\tif ref == nil {\n\t\treturn nil\n\t}\n\tobj := new(FzPixmap)\n\tobj.ref7c1a1ba1 = (*C.fz_pixmap)(unsafe.Pointer(ref))\n\treturn obj\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetBuffer(request *requests.FPDFBitmap_GetBuffer) (*responses.FPDFBitmap_GetBuffer, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We need to calculate the buffer size, this is stride (bytes per bitmap line) * height.\n\tstride := C.FPDFBitmap_GetStride(bitmapHandle.handle)\n\theight := C.FPDFBitmap_GetHeight(bitmapHandle.handle)\n\tsize := int(stride * height)\n\n\t// The pointer to the first byte of the bitmap buffer.\n\tbuffer := C.FPDFBitmap_GetBuffer(bitmapHandle.handle)\n\n\t// We create a Go slice backed by a C array (without copying the original data).\n\tdata := unsafe.Slice((*byte)(unsafe.Pointer(buffer)), uint64(size))\n\n\treturn &responses.FPDFBitmap_GetBuffer{\n\t\tBuffer: data,\n\t}, nil\n}",
"func CreateImageBufferI3D(hDC unsafe.Pointer, dwSize unsafe.Pointer, uFlags unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpCreateImageBufferI3D, 3, uintptr(hDC), uintptr(dwSize), uintptr(uFlags))\n\treturn (unsafe.Pointer)(ret)\n}",
"func CreatePbufferEXT(hDC unsafe.Pointer, iPixelFormat unsafe.Pointer, iWidth unsafe.Pointer, iHeight unsafe.Pointer, piAttribList unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall6(gpCreatePbufferEXT, 5, uintptr(hDC), uintptr(iPixelFormat), uintptr(iWidth), uintptr(iHeight), uintptr(piAttribList), 0)\n\treturn (unsafe.Pointer)(ret)\n}",
"func CreatePbufferARB(hDC unsafe.Pointer, iPixelFormat unsafe.Pointer, iWidth unsafe.Pointer, iHeight unsafe.Pointer, piAttribList unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall6(gpCreatePbufferARB, 5, uintptr(hDC), uintptr(iPixelFormat), uintptr(iWidth), uintptr(iHeight), uintptr(piAttribList), 0)\n\treturn (unsafe.Pointer)(ret)\n}",
"func captureWithGDI(path string) {\n\thdcWindow := w32.GetDC(0)\n\thdcMemDC := w32.CreateCompatibleDC(hdcWindow)\n\tif hdcMemDC == 0 {\n\t\tpanic(\"CreateCompatibleDC has failed\")\n\t}\n\n\theight := w32.GetSystemMetrics(w32.SM_CYVIRTUALSCREEN)\n\twidth := w32.GetSystemMetrics(w32.SM_CXVIRTUALSCREEN)\n\n\thbmScreen := w32.CreateCompatibleBitmap(\n\t\thdcWindow,\n\t\twidth,\n\t\theight,\n\t)\n\tif hbmScreen == 0 {\n\t\tpanic(\"CreateCompatibleBitmap Failed\")\n\t}\n\n\tw32.SelectObject(hdcMemDC, w32.HGDIOBJ(hbmScreen))\n\tif !w32.BitBlt(hdcMemDC,\n\t\t0, 0,\n\t\twidth, height,\n\t\thdcWindow,\n\t\t0, 0,\n\t\tw32.SRCCOPY) {\n\t\tpanic(\"BitBlt has failed\")\n\t}\n\n\tvar bmpScreen w32.BITMAP\n\tw32.GetObject(\n\t\tw32.HGDIOBJ(hbmScreen),\n\t\tuintptr(binary.Size(bmpScreen)),\n\t\tunsafe.Pointer(&bmpScreen),\n\t)\n\n\tvar bmfHeader w32.BITMAPFILEHEADER\n\tvar bi w32.BITMAPINFOHEADER\n\tbi.BiSize = uint32(binary.Size(bi))\n\tbi.BiWidth = bmpScreen.BmWidth\n\tbi.BiHeight = bmpScreen.BmHeight\n\tbi.BiPlanes = 1\n\tbi.BiBitCount = 32\n\tbi.BiCompression = w32.BI_RGB\n\tbi.BiSizeImage = 0\n\tbi.BiXPelsPerMeter = 0\n\tbi.BiYPelsPerMeter = 0\n\tbi.BiClrUsed = 0\n\tbi.BiClrImportant = 0\n\n\tdwBmpSize := uint32(((bmpScreen.BmWidth*int32(bi.BiBitCount) + 31) / 32) * 4 * bmpScreen.BmHeight)\n\tcolorData := make([]byte, dwBmpSize)\n\tw32.GetDIBits(\n\t\thdcWindow,\n\t\thbmScreen,\n\t\t0,\n\t\tuint(bmpScreen.BmHeight),\n\t\tunsafe.Pointer(&colorData[0]),\n\t\t(*w32.BITMAPINFO)(unsafe.Pointer(&bi)),\n\t\tw32.DIB_RGB_COLORS,\n\t)\n\n\tbmfHeader.BfOffBits = uint32(binary.Size(bmfHeader) + binary.Size(bi))\n\tbmfHeader.BfSize = dwBmpSize + uint32(binary.Size(bmfHeader)+binary.Size(bi))\n\tbmfHeader.BfType = 0x4D42\n\n\tf, err := os.Create(path)\n\tcheck(err)\n\tdefer f.Close()\n\n\tcheck(binary.Write(f, binary.LittleEndian, bmfHeader))\n\tcheck(binary.Write(f, binary.LittleEndian, bi))\n\t_, err = f.Write(colorData)\n\tcheck(err)\n\n\tw32.DeleteObject(w32.HGDIOBJ(hbmScreen))\n\tw32.DeleteObject(w32.HGDIOBJ(hdcMemDC))\n\tw32.ReleaseDC(0, hdcWindow)\n}",
"func allocFzBandWriterMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzBandWriterValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func NewFramebuffer(w, h int) *Framebuffer {\n\treturn &Framebuffer{\n\t\tfb: image.NewRGBA(image.Rectangle{image.Point{0, 0}, image.Point{w, h}}),\n\t}\n}",
"func NewPDFObj() *PDFObj {\n\treturn (*PDFObj)(allocPDFObjMemory(1))\n}",
"func New(title string, x, y, width, height int) Device { return newDevice(title, x, y, width, height) }",
"func allocFzImageMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzImageValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func NewBMP280(dev *i2c.Dev) (*BMP, error) {\n\tbmp := &BMP{\n\t\tdevice: dev,\n\t\ttempCalibration: make([]calibrationData, 3),\n\t\tpressCalibration: make([]calibrationData, 9),\n\t\tlastTemperatureMeasurement: math.NaN(),\n\t}\n\n\terr := bmp.Init()\n\treturn bmp, err\n}",
"func createFB(tex wasm.WebGLTexture) wasm.WebGLFramebuffer {\n\tfb := gl.CreateFramebuffer()\n\tgl.BindFramebuffer(wasm.FRAMEBUFFER, fb)\n\tgl.FramebufferTexture2D(wasm.FRAMEBUFFER, wasm.COLOR_ATTACHMENT0, wasm.TEXTURE_2D, tex, 0)\n\treturn fb\n}",
"func allocFzFontMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzFontValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (p *PdfiumImplementation) FPDFBitmap_FillRect(request *requests.FPDFBitmap_FillRect) (*responses.FPDFBitmap_FillRect, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tC.FPDFBitmap_FillRect(bitmapHandle.handle, C.int(request.Left), C.int(request.Top), C.int(request.Width), C.int(request.Height), C.ulong(request.Color))\n\n\treturn &responses.FPDFBitmap_FillRect{}, nil\n}",
"func allocPDFOcgDescriptorMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFOcgDescriptorValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (x *FzPixmap) Deref() {\n\tif x.ref7c1a1ba1 == nil {\n\t\treturn\n\t}\n\tx.Storable = *(*FzStorable)(unsafe.Pointer(&x.ref7c1a1ba1.storable))\n\tx.X = (int32)(x.ref7c1a1ba1.x)\n\tx.Y = (int32)(x.ref7c1a1ba1.y)\n\tx.W = (int32)(x.ref7c1a1ba1.w)\n\tx.H = (int32)(x.ref7c1a1ba1.h)\n\tx.N = (byte)(x.ref7c1a1ba1.n)\n\tx.S = (byte)(x.ref7c1a1ba1.s)\n\tx.Alpha = (byte)(x.ref7c1a1ba1.alpha)\n\tx.Flags = (byte)(x.ref7c1a1ba1.flags)\n\tx.Stride = (int32)(x.ref7c1a1ba1.stride)\n\tx.Seps = (*FzSeparations)(unsafe.Pointer(x.ref7c1a1ba1.seps))\n\tx.Xres = (int32)(x.ref7c1a1ba1.xres)\n\tx.Yres = (int32)(x.ref7c1a1ba1.yres)\n\tx.Colorspace = (*FzColorspace)(unsafe.Pointer(x.ref7c1a1ba1.colorspace))\n\thxff73280 := (*sliceHeader)(unsafe.Pointer(&x.Samples))\n\thxff73280.Data = uintptr(unsafe.Pointer(x.ref7c1a1ba1.samples))\n\thxff73280.Cap = 0x7fffffff\n\t// hxff73280.Len = ?\n\n}",
"func CreateImage(d []Drawer, g GlobalConfig) {\n\t// Setup()\n\n\t// 先进行图片加载\n\t// TODO: 需要观察图片是否被正确加载\n\tprepareImage(d)\n\n\tfmt.Println(\"create image\", len(d), g)\n\n\tc := Canvas{canvas.New(g.Width, g.Height)}\n\n\tctx := canvas.NewContext(c)\n\n\t// to draw a red background\n\tctx.SetFillColor(color.RGBA{0xff, 0x00, 0x00, 0xff})\n\tctx.DrawPath(0, 0, canvas.Rectangle(g.Width, g.Height))\n\n\t// 对*canvas.Draw函数传入绘图数据\n\tc.Draw(d)\n\n\t// SavePNG的第二个参数是canvas导出时放大的倍数\n\t// 尽量导出2x或者3x的尺寸,但坐标是1x的,需要更多测试\n\tc.WriteFile(g.FileName, rasterizer.PNGWriter(1.0))\n\n\tfmt.Println(\"draw_data_finish\", len(d))\n}",
"func CreatePng(filename string, f ComplexFunc, n int) (err error) {\n\t//create the file that will hold the image\n\tfile, err := os.Create(filename)\n\t//check for errors.\n\tif err != nil {\n\t\treturn\n\t}\n\t//when evertyhing else in this method is finished - close file\n\tdefer file.Close()\n\t//make the return variable by encoding the file using the function f and size n\n\terr = png.Encode(file, Julia(f, n))\n\n\treturn\n}",
"func allocPDFFontDescMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFFontDescValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (x *FzBitmap) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func allocFzDeviceMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzDeviceValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (obj *Device) CreateRenderTarget(\n\twidth uint,\n\theight uint,\n\tformat FORMAT,\n\tmultiSample MULTISAMPLE_TYPE,\n\tmultisampleQuality uint32,\n\tlockable bool,\n\tsharedHandle uintptr,\n) (*Surface, Error) {\n\tvar surface *Surface\n\tret, _, _ := syscall.Syscall9(\n\t\tobj.vtbl.CreateRenderTarget,\n\t\t9,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(width),\n\t\tuintptr(height),\n\t\tuintptr(format),\n\t\tuintptr(multiSample),\n\t\tuintptr(multisampleQuality),\n\t\tuintptrBool(lockable),\n\t\tuintptr(unsafe.Pointer(&surface)),\n\t\tsharedHandle,\n\t)\n\treturn surface, toErr(ret)\n}",
"func NewPDFFontDesc() *PDFFontDesc {\n\treturn (*PDFFontDesc)(allocPDFFontDescMemory(1))\n}",
"func (im *imageContrller) Create24MacbethChart(path, filename string) bool {\n\tstatus := false\n\n\tif path != \"\" && filename != \"\" {\n\t\t// initialize directory handler\n\t\tdirHandler := util.NewDirectoryHandler()\n\t\tioHandler := util.NewIOUtil() // initialize IO handler\n\n\t\t// get file names from directory path\n\t\tfiles, names := dirHandler.GetFileListInDirectory(path)\n\n\t\t// make patch Data Map\n\t\tpatchDataMap := make(map[string]image.Image, 0)\n\t\tfor index := 0; index < len(files); index++ {\n\t\t\tpatchDataMap[names[index]] = ioHandler.ReadImageFile(files[index])\n\t\t}\n\n\t\twidth := patchDataMap[\"Black\"].Bounds().Size().X\n\t\theight := patchDataMap[\"Black\"].Bounds().Size().Y\n\n\t\t// canvas\n\t\tcanvas := im.makeCanvas(width, height)\n\n\t\t// point calculator\n\t\tfor index := 0; index < 24; index++ {\n\n\t\t\t// calculate start and end point\n\t\t\tstart, end := im.pointCalculator(index, width, height)\n\t\t\tsrcRect := image.Rectangle{start, end}\n\n\t\t\t// create image\n\t\t\tdraw.Draw(canvas, srcRect, patchDataMap[im.returnPatchNameString(index)], image.Pt(0, 0), draw.Over)\n\t\t}\n\n\t\t// stream out final image\n\t\tif canvas != nil {\n\t\t\tif ioHandler.StreamOutPNGFile(path, filename, canvas) {\n\t\t\t\tstatus = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn status\n}",
"func CreateIconBytes(address string) []byte {\n\toptions := NewBuildOption(address)\n\tdata := createImageData(options.size)\n\treturn createImage(data, options.color, options.bgColor, options.spotColor, 16)\n}",
"func NewFzPixmapImageRef(ref unsafe.Pointer) *FzPixmapImage {\n\treturn (*FzPixmapImage)(ref)\n}",
"func allocFzColorConverterMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzColorConverterValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func allocFzFontFlagsMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzFontFlagsValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (self *GameObjectCreator) BitmapData4O(width int, height int, key string, addToCache bool) *BitmapData{\n return &BitmapData{self.Object.Call(\"bitmapData\", width, height, key, addToCache)}\n}",
"func packSFzPixmap(v []FzPixmap, ptr0 *C.fz_pixmap) {\n\tconst m = 0x7fffffff\n\tfor i0 := range v {\n\t\tptr1 := (*(*[m / sizeOfFzPixmapValue]C.fz_pixmap)(unsafe.Pointer(ptr0)))[i0]\n\t\tv[i0] = *NewFzPixmapRef(unsafe.Pointer(&ptr1))\n\t}\n}",
"func (x *FzBitmap) Ref() *C.fz_bitmap {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.fz_bitmap)(unsafe.Pointer(x))\n}",
"func newScreenFramebuffer(context *context, width, height int) *framebuffer {\n\treturn &framebuffer{\n\t\tnative: context.getScreenFramebuffer(),\n\t\twidth: width,\n\t\theight: height,\n\t}\n}",
"func CreatePicture(camera *Camera, width int, height int) *Picture {\r\n\tp := &Picture{\r\n\t\tpixelWidth: width,\r\n\t\tpixelHeight: height,\r\n\t\tpixelWidthDistance: camera.GetWidth() / float64(width),\r\n\t\tpixelHeightDistance: camera.GetHeight() / float64(height),\r\n\t\tcamera: camera}\r\n\r\n\treturn p\r\n}",
"func allocFzFontContextMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzFontContextValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (p *PhidgetDigitalOutput) Create() {\n\tC.PhidgetDigitalOutput_create(&p.handle)\n\tp.rawHandle(unsafe.Pointer(p.handle))\n}",
"func packSSFzPixmap(v [][]FzPixmap, ptr0 **C.fz_pixmap) {\n\tconst m = 0x7fffffff\n\tfor i0 := range v {\n\t\tptr1 := (*(*[m / sizeOfPtr]*C.fz_pixmap)(unsafe.Pointer(ptr0)))[i0]\n\t\tfor i1 := range v[i0] {\n\t\t\tptr2 := (*(*[m / sizeOfFzPixmapValue]C.fz_pixmap)(unsafe.Pointer(ptr1)))[i1]\n\t\t\tv[i0][i1] = *NewFzPixmapRef(unsafe.Pointer(&ptr2))\n\t\t}\n\t}\n}",
"func newImageFromNative(obj unsafe.Pointer) interface{} {\n\tim := &Image{}\n\tim.object = C.to_GtkImage(obj)\n\n\tif gobject.IsObjectFloating(im) {\n\t\tgobject.RefSink(im)\n\t} else {\n\t\tgobject.Ref(im)\n\t}\n\tim.Widget = NewWidget(obj)\n\timageFinalizer(im)\n\n\treturn im\n}",
"func CreateImage(width int, height int, background color.RGBA) *image.RGBA {\n\trect := image.Rect(0, 0, width, height)\n\timg := image.NewRGBA(rect)\n\tdraw.Draw(img, img.Bounds(), &image.Uniform{C: background}, image.ZP, draw.Src)\n\n\treturn img\n}",
"func InitWithProcAddrFunc(getProcAddr func(name string) unsafe.Pointer) error {\n\tgpChoosePixelFormat = (C.GPCHOOSEPIXELFORMAT)(getProcAddr(\"ChoosePixelFormat\"))\n\tif gpChoosePixelFormat == nil {\n\t\treturn errors.New(\"ChoosePixelFormat\")\n\t}\n\tgpDescribePixelFormat = (C.GPDESCRIBEPIXELFORMAT)(getProcAddr(\"DescribePixelFormat\"))\n\tif gpDescribePixelFormat == nil {\n\t\treturn errors.New(\"DescribePixelFormat\")\n\t}\n\tgpGetEnhMetaFilePixelFormat = (C.GPGETENHMETAFILEPIXELFORMAT)(getProcAddr(\"GetEnhMetaFilePixelFormat\"))\n\tif gpGetEnhMetaFilePixelFormat == nil {\n\t\treturn errors.New(\"GetEnhMetaFilePixelFormat\")\n\t}\n\tgpGetPixelFormat = (C.GPGETPIXELFORMAT)(getProcAddr(\"GetPixelFormat\"))\n\tif gpGetPixelFormat == nil {\n\t\treturn errors.New(\"GetPixelFormat\")\n\t}\n\tgpSetPixelFormat = (C.GPSETPIXELFORMAT)(getProcAddr(\"SetPixelFormat\"))\n\tif gpSetPixelFormat == nil {\n\t\treturn errors.New(\"SetPixelFormat\")\n\t}\n\tgpSwapBuffers = (C.GPSWAPBUFFERS)(getProcAddr(\"SwapBuffers\"))\n\tif gpSwapBuffers == nil {\n\t\treturn errors.New(\"SwapBuffers\")\n\t}\n\tgpAllocateMemoryNV = (C.GPALLOCATEMEMORYNV)(getProcAddr(\"wglAllocateMemoryNV\"))\n\tgpAssociateImageBufferEventsI3D = (C.GPASSOCIATEIMAGEBUFFEREVENTSI3D)(getProcAddr(\"wglAssociateImageBufferEventsI3D\"))\n\tgpBeginFrameTrackingI3D = (C.GPBEGINFRAMETRACKINGI3D)(getProcAddr(\"wglBeginFrameTrackingI3D\"))\n\tgpBindDisplayColorTableEXT = (C.GPBINDDISPLAYCOLORTABLEEXT)(getProcAddr(\"wglBindDisplayColorTableEXT\"))\n\tgpBindSwapBarrierNV = (C.GPBINDSWAPBARRIERNV)(getProcAddr(\"wglBindSwapBarrierNV\"))\n\tgpBindTexImageARB = (C.GPBINDTEXIMAGEARB)(getProcAddr(\"wglBindTexImageARB\"))\n\tgpBindVideoCaptureDeviceNV = (C.GPBINDVIDEOCAPTUREDEVICENV)(getProcAddr(\"wglBindVideoCaptureDeviceNV\"))\n\tgpBindVideoDeviceNV = (C.GPBINDVIDEODEVICENV)(getProcAddr(\"wglBindVideoDeviceNV\"))\n\tgpBindVideoImageNV = (C.GPBINDVIDEOIMAGENV)(getProcAddr(\"wglBindVideoImageNV\"))\n\tgpBlitContextFramebufferAMD = (C.GPBLITCONTEXTFRAMEBUFFERAMD)(getProcAddr(\"wglBlitContextFramebufferAMD\"))\n\tgpChoosePixelFormatARB = (C.GPCHOOSEPIXELFORMATARB)(getProcAddr(\"wglChoosePixelFormatARB\"))\n\tgpChoosePixelFormatEXT = (C.GPCHOOSEPIXELFORMATEXT)(getProcAddr(\"wglChoosePixelFormatEXT\"))\n\tgpCopyContext = (C.GPCOPYCONTEXT)(getProcAddr(\"wglCopyContext\"))\n\tif gpCopyContext == nil {\n\t\treturn errors.New(\"wglCopyContext\")\n\t}\n\tgpCopyImageSubDataNV = (C.GPCOPYIMAGESUBDATANV)(getProcAddr(\"wglCopyImageSubDataNV\"))\n\tgpCreateAffinityDCNV = (C.GPCREATEAFFINITYDCNV)(getProcAddr(\"wglCreateAffinityDCNV\"))\n\tgpCreateAssociatedContextAMD = (C.GPCREATEASSOCIATEDCONTEXTAMD)(getProcAddr(\"wglCreateAssociatedContextAMD\"))\n\tgpCreateAssociatedContextAttribsAMD = (C.GPCREATEASSOCIATEDCONTEXTATTRIBSAMD)(getProcAddr(\"wglCreateAssociatedContextAttribsAMD\"))\n\tgpCreateBufferRegionARB = (C.GPCREATEBUFFERREGIONARB)(getProcAddr(\"wglCreateBufferRegionARB\"))\n\tgpCreateContext = (C.GPCREATECONTEXT)(getProcAddr(\"wglCreateContext\"))\n\tif gpCreateContext == nil {\n\t\treturn errors.New(\"wglCreateContext\")\n\t}\n\tgpCreateContextAttribsARB = (C.GPCREATECONTEXTATTRIBSARB)(getProcAddr(\"wglCreateContextAttribsARB\"))\n\tgpCreateDisplayColorTableEXT = (C.GPCREATEDISPLAYCOLORTABLEEXT)(getProcAddr(\"wglCreateDisplayColorTableEXT\"))\n\tgpCreateImageBufferI3D = (C.GPCREATEIMAGEBUFFERI3D)(getProcAddr(\"wglCreateImageBufferI3D\"))\n\tgpCreateLayerContext = (C.GPCREATELAYERCONTEXT)(getProcAddr(\"wglCreateLayerContext\"))\n\tif gpCreateLayerContext == nil {\n\t\treturn errors.New(\"wglCreateLayerContext\")\n\t}\n\tgpCreatePbufferARB = (C.GPCREATEPBUFFERARB)(getProcAddr(\"wglCreatePbufferARB\"))\n\tgpCreatePbufferEXT = (C.GPCREATEPBUFFEREXT)(getProcAddr(\"wglCreatePbufferEXT\"))\n\tgpDXCloseDeviceNV = (C.GPDXCLOSEDEVICENV)(getProcAddr(\"wglDXCloseDeviceNV\"))\n\tgpDXLockObjectsNV = (C.GPDXLOCKOBJECTSNV)(getProcAddr(\"wglDXLockObjectsNV\"))\n\tgpDXObjectAccessNV = (C.GPDXOBJECTACCESSNV)(getProcAddr(\"wglDXObjectAccessNV\"))\n\tgpDXOpenDeviceNV = (C.GPDXOPENDEVICENV)(getProcAddr(\"wglDXOpenDeviceNV\"))\n\tgpDXRegisterObjectNV = (C.GPDXREGISTEROBJECTNV)(getProcAddr(\"wglDXRegisterObjectNV\"))\n\tgpDXSetResourceShareHandleNV = (C.GPDXSETRESOURCESHAREHANDLENV)(getProcAddr(\"wglDXSetResourceShareHandleNV\"))\n\tgpDXUnlockObjectsNV = (C.GPDXUNLOCKOBJECTSNV)(getProcAddr(\"wglDXUnlockObjectsNV\"))\n\tgpDXUnregisterObjectNV = (C.GPDXUNREGISTEROBJECTNV)(getProcAddr(\"wglDXUnregisterObjectNV\"))\n\tgpDelayBeforeSwapNV = (C.GPDELAYBEFORESWAPNV)(getProcAddr(\"wglDelayBeforeSwapNV\"))\n\tgpDeleteAssociatedContextAMD = (C.GPDELETEASSOCIATEDCONTEXTAMD)(getProcAddr(\"wglDeleteAssociatedContextAMD\"))\n\tgpDeleteBufferRegionARB = (C.GPDELETEBUFFERREGIONARB)(getProcAddr(\"wglDeleteBufferRegionARB\"))\n\tgpDeleteContext = (C.GPDELETECONTEXT)(getProcAddr(\"wglDeleteContext\"))\n\tif gpDeleteContext == nil {\n\t\treturn errors.New(\"wglDeleteContext\")\n\t}\n\tgpDeleteDCNV = (C.GPDELETEDCNV)(getProcAddr(\"wglDeleteDCNV\"))\n\tgpDescribeLayerPlane = (C.GPDESCRIBELAYERPLANE)(getProcAddr(\"wglDescribeLayerPlane\"))\n\tif gpDescribeLayerPlane == nil {\n\t\treturn errors.New(\"wglDescribeLayerPlane\")\n\t}\n\tgpDestroyDisplayColorTableEXT = (C.GPDESTROYDISPLAYCOLORTABLEEXT)(getProcAddr(\"wglDestroyDisplayColorTableEXT\"))\n\tgpDestroyImageBufferI3D = (C.GPDESTROYIMAGEBUFFERI3D)(getProcAddr(\"wglDestroyImageBufferI3D\"))\n\tgpDestroyPbufferARB = (C.GPDESTROYPBUFFERARB)(getProcAddr(\"wglDestroyPbufferARB\"))\n\tgpDestroyPbufferEXT = (C.GPDESTROYPBUFFEREXT)(getProcAddr(\"wglDestroyPbufferEXT\"))\n\tgpDisableFrameLockI3D = (C.GPDISABLEFRAMELOCKI3D)(getProcAddr(\"wglDisableFrameLockI3D\"))\n\tgpDisableGenlockI3D = (C.GPDISABLEGENLOCKI3D)(getProcAddr(\"wglDisableGenlockI3D\"))\n\tgpEnableFrameLockI3D = (C.GPENABLEFRAMELOCKI3D)(getProcAddr(\"wglEnableFrameLockI3D\"))\n\tgpEnableGenlockI3D = (C.GPENABLEGENLOCKI3D)(getProcAddr(\"wglEnableGenlockI3D\"))\n\tgpEndFrameTrackingI3D = (C.GPENDFRAMETRACKINGI3D)(getProcAddr(\"wglEndFrameTrackingI3D\"))\n\tgpEnumGpuDevicesNV = (C.GPENUMGPUDEVICESNV)(getProcAddr(\"wglEnumGpuDevicesNV\"))\n\tgpEnumGpusFromAffinityDCNV = (C.GPENUMGPUSFROMAFFINITYDCNV)(getProcAddr(\"wglEnumGpusFromAffinityDCNV\"))\n\tgpEnumGpusNV = (C.GPENUMGPUSNV)(getProcAddr(\"wglEnumGpusNV\"))\n\tgpEnumerateVideoCaptureDevicesNV = (C.GPENUMERATEVIDEOCAPTUREDEVICESNV)(getProcAddr(\"wglEnumerateVideoCaptureDevicesNV\"))\n\tgpEnumerateVideoDevicesNV = (C.GPENUMERATEVIDEODEVICESNV)(getProcAddr(\"wglEnumerateVideoDevicesNV\"))\n\tgpFreeMemoryNV = (C.GPFREEMEMORYNV)(getProcAddr(\"wglFreeMemoryNV\"))\n\tgpGenlockSampleRateI3D = (C.GPGENLOCKSAMPLERATEI3D)(getProcAddr(\"wglGenlockSampleRateI3D\"))\n\tgpGenlockSourceDelayI3D = (C.GPGENLOCKSOURCEDELAYI3D)(getProcAddr(\"wglGenlockSourceDelayI3D\"))\n\tgpGenlockSourceEdgeI3D = (C.GPGENLOCKSOURCEEDGEI3D)(getProcAddr(\"wglGenlockSourceEdgeI3D\"))\n\tgpGenlockSourceI3D = (C.GPGENLOCKSOURCEI3D)(getProcAddr(\"wglGenlockSourceI3D\"))\n\tgpGetContextGPUIDAMD = (C.GPGETCONTEXTGPUIDAMD)(getProcAddr(\"wglGetContextGPUIDAMD\"))\n\tgpGetCurrentAssociatedContextAMD = (C.GPGETCURRENTASSOCIATEDCONTEXTAMD)(getProcAddr(\"wglGetCurrentAssociatedContextAMD\"))\n\tgpGetCurrentContext = (C.GPGETCURRENTCONTEXT)(getProcAddr(\"wglGetCurrentContext\"))\n\tif gpGetCurrentContext == nil {\n\t\treturn errors.New(\"wglGetCurrentContext\")\n\t}\n\tgpGetCurrentDC = (C.GPGETCURRENTDC)(getProcAddr(\"wglGetCurrentDC\"))\n\tif gpGetCurrentDC == nil {\n\t\treturn errors.New(\"wglGetCurrentDC\")\n\t}\n\tgpGetCurrentReadDCARB = (C.GPGETCURRENTREADDCARB)(getProcAddr(\"wglGetCurrentReadDCARB\"))\n\tgpGetCurrentReadDCEXT = (C.GPGETCURRENTREADDCEXT)(getProcAddr(\"wglGetCurrentReadDCEXT\"))\n\tgpGetDigitalVideoParametersI3D = (C.GPGETDIGITALVIDEOPARAMETERSI3D)(getProcAddr(\"wglGetDigitalVideoParametersI3D\"))\n\tgpGetExtensionsStringARB = (C.GPGETEXTENSIONSSTRINGARB)(getProcAddr(\"wglGetExtensionsStringARB\"))\n\tgpGetExtensionsStringEXT = (C.GPGETEXTENSIONSSTRINGEXT)(getProcAddr(\"wglGetExtensionsStringEXT\"))\n\tgpGetFrameUsageI3D = (C.GPGETFRAMEUSAGEI3D)(getProcAddr(\"wglGetFrameUsageI3D\"))\n\tgpGetGPUIDsAMD = (C.GPGETGPUIDSAMD)(getProcAddr(\"wglGetGPUIDsAMD\"))\n\tgpGetGPUInfoAMD = (C.GPGETGPUINFOAMD)(getProcAddr(\"wglGetGPUInfoAMD\"))\n\tgpGetGammaTableI3D = (C.GPGETGAMMATABLEI3D)(getProcAddr(\"wglGetGammaTableI3D\"))\n\tgpGetGammaTableParametersI3D = (C.GPGETGAMMATABLEPARAMETERSI3D)(getProcAddr(\"wglGetGammaTableParametersI3D\"))\n\tgpGetGenlockSampleRateI3D = (C.GPGETGENLOCKSAMPLERATEI3D)(getProcAddr(\"wglGetGenlockSampleRateI3D\"))\n\tgpGetGenlockSourceDelayI3D = (C.GPGETGENLOCKSOURCEDELAYI3D)(getProcAddr(\"wglGetGenlockSourceDelayI3D\"))\n\tgpGetGenlockSourceEdgeI3D = (C.GPGETGENLOCKSOURCEEDGEI3D)(getProcAddr(\"wglGetGenlockSourceEdgeI3D\"))\n\tgpGetGenlockSourceI3D = (C.GPGETGENLOCKSOURCEI3D)(getProcAddr(\"wglGetGenlockSourceI3D\"))\n\tgpGetLayerPaletteEntries = (C.GPGETLAYERPALETTEENTRIES)(getProcAddr(\"wglGetLayerPaletteEntries\"))\n\tif gpGetLayerPaletteEntries == nil {\n\t\treturn errors.New(\"wglGetLayerPaletteEntries\")\n\t}\n\tgpGetMscRateOML = (C.GPGETMSCRATEOML)(getProcAddr(\"wglGetMscRateOML\"))\n\tgpGetPbufferDCARB = (C.GPGETPBUFFERDCARB)(getProcAddr(\"wglGetPbufferDCARB\"))\n\tgpGetPbufferDCEXT = (C.GPGETPBUFFERDCEXT)(getProcAddr(\"wglGetPbufferDCEXT\"))\n\tgpGetPixelFormatAttribfvARB = (C.GPGETPIXELFORMATATTRIBFVARB)(getProcAddr(\"wglGetPixelFormatAttribfvARB\"))\n\tgpGetPixelFormatAttribfvEXT = (C.GPGETPIXELFORMATATTRIBFVEXT)(getProcAddr(\"wglGetPixelFormatAttribfvEXT\"))\n\tgpGetPixelFormatAttribivARB = (C.GPGETPIXELFORMATATTRIBIVARB)(getProcAddr(\"wglGetPixelFormatAttribivARB\"))\n\tgpGetPixelFormatAttribivEXT = (C.GPGETPIXELFORMATATTRIBIVEXT)(getProcAddr(\"wglGetPixelFormatAttribivEXT\"))\n\tgpGetProcAddress = (C.GPGETPROCADDRESS)(getProcAddr(\"wglGetProcAddress\"))\n\tif gpGetProcAddress == nil {\n\t\treturn errors.New(\"wglGetProcAddress\")\n\t}\n\tgpGetSwapIntervalEXT = (C.GPGETSWAPINTERVALEXT)(getProcAddr(\"wglGetSwapIntervalEXT\"))\n\tgpGetSyncValuesOML = (C.GPGETSYNCVALUESOML)(getProcAddr(\"wglGetSyncValuesOML\"))\n\tgpGetVideoDeviceNV = (C.GPGETVIDEODEVICENV)(getProcAddr(\"wglGetVideoDeviceNV\"))\n\tgpGetVideoInfoNV = (C.GPGETVIDEOINFONV)(getProcAddr(\"wglGetVideoInfoNV\"))\n\tgpIsEnabledFrameLockI3D = (C.GPISENABLEDFRAMELOCKI3D)(getProcAddr(\"wglIsEnabledFrameLockI3D\"))\n\tgpIsEnabledGenlockI3D = (C.GPISENABLEDGENLOCKI3D)(getProcAddr(\"wglIsEnabledGenlockI3D\"))\n\tgpJoinSwapGroupNV = (C.GPJOINSWAPGROUPNV)(getProcAddr(\"wglJoinSwapGroupNV\"))\n\tgpLoadDisplayColorTableEXT = (C.GPLOADDISPLAYCOLORTABLEEXT)(getProcAddr(\"wglLoadDisplayColorTableEXT\"))\n\tgpLockVideoCaptureDeviceNV = (C.GPLOCKVIDEOCAPTUREDEVICENV)(getProcAddr(\"wglLockVideoCaptureDeviceNV\"))\n\tgpMakeAssociatedContextCurrentAMD = (C.GPMAKEASSOCIATEDCONTEXTCURRENTAMD)(getProcAddr(\"wglMakeAssociatedContextCurrentAMD\"))\n\tgpMakeContextCurrentARB = (C.GPMAKECONTEXTCURRENTARB)(getProcAddr(\"wglMakeContextCurrentARB\"))\n\tgpMakeContextCurrentEXT = (C.GPMAKECONTEXTCURRENTEXT)(getProcAddr(\"wglMakeContextCurrentEXT\"))\n\tgpMakeCurrent = (C.GPMAKECURRENT)(getProcAddr(\"wglMakeCurrent\"))\n\tif gpMakeCurrent == nil {\n\t\treturn errors.New(\"wglMakeCurrent\")\n\t}\n\tgpQueryCurrentContextNV = (C.GPQUERYCURRENTCONTEXTNV)(getProcAddr(\"wglQueryCurrentContextNV\"))\n\tgpQueryFrameCountNV = (C.GPQUERYFRAMECOUNTNV)(getProcAddr(\"wglQueryFrameCountNV\"))\n\tgpQueryFrameLockMasterI3D = (C.GPQUERYFRAMELOCKMASTERI3D)(getProcAddr(\"wglQueryFrameLockMasterI3D\"))\n\tgpQueryFrameTrackingI3D = (C.GPQUERYFRAMETRACKINGI3D)(getProcAddr(\"wglQueryFrameTrackingI3D\"))\n\tgpQueryGenlockMaxSourceDelayI3D = (C.GPQUERYGENLOCKMAXSOURCEDELAYI3D)(getProcAddr(\"wglQueryGenlockMaxSourceDelayI3D\"))\n\tgpQueryMaxSwapGroupsNV = (C.GPQUERYMAXSWAPGROUPSNV)(getProcAddr(\"wglQueryMaxSwapGroupsNV\"))\n\tgpQueryPbufferARB = (C.GPQUERYPBUFFERARB)(getProcAddr(\"wglQueryPbufferARB\"))\n\tgpQueryPbufferEXT = (C.GPQUERYPBUFFEREXT)(getProcAddr(\"wglQueryPbufferEXT\"))\n\tgpQuerySwapGroupNV = (C.GPQUERYSWAPGROUPNV)(getProcAddr(\"wglQuerySwapGroupNV\"))\n\tgpQueryVideoCaptureDeviceNV = (C.GPQUERYVIDEOCAPTUREDEVICENV)(getProcAddr(\"wglQueryVideoCaptureDeviceNV\"))\n\tgpRealizeLayerPalette = (C.GPREALIZELAYERPALETTE)(getProcAddr(\"wglRealizeLayerPalette\"))\n\tif gpRealizeLayerPalette == nil {\n\t\treturn errors.New(\"wglRealizeLayerPalette\")\n\t}\n\tgpReleaseImageBufferEventsI3D = (C.GPRELEASEIMAGEBUFFEREVENTSI3D)(getProcAddr(\"wglReleaseImageBufferEventsI3D\"))\n\tgpReleasePbufferDCARB = (C.GPRELEASEPBUFFERDCARB)(getProcAddr(\"wglReleasePbufferDCARB\"))\n\tgpReleasePbufferDCEXT = (C.GPRELEASEPBUFFERDCEXT)(getProcAddr(\"wglReleasePbufferDCEXT\"))\n\tgpReleaseTexImageARB = (C.GPRELEASETEXIMAGEARB)(getProcAddr(\"wglReleaseTexImageARB\"))\n\tgpReleaseVideoCaptureDeviceNV = (C.GPRELEASEVIDEOCAPTUREDEVICENV)(getProcAddr(\"wglReleaseVideoCaptureDeviceNV\"))\n\tgpReleaseVideoDeviceNV = (C.GPRELEASEVIDEODEVICENV)(getProcAddr(\"wglReleaseVideoDeviceNV\"))\n\tgpReleaseVideoImageNV = (C.GPRELEASEVIDEOIMAGENV)(getProcAddr(\"wglReleaseVideoImageNV\"))\n\tgpResetFrameCountNV = (C.GPRESETFRAMECOUNTNV)(getProcAddr(\"wglResetFrameCountNV\"))\n\tgpRestoreBufferRegionARB = (C.GPRESTOREBUFFERREGIONARB)(getProcAddr(\"wglRestoreBufferRegionARB\"))\n\tgpSaveBufferRegionARB = (C.GPSAVEBUFFERREGIONARB)(getProcAddr(\"wglSaveBufferRegionARB\"))\n\tgpSendPbufferToVideoNV = (C.GPSENDPBUFFERTOVIDEONV)(getProcAddr(\"wglSendPbufferToVideoNV\"))\n\tgpSetDigitalVideoParametersI3D = (C.GPSETDIGITALVIDEOPARAMETERSI3D)(getProcAddr(\"wglSetDigitalVideoParametersI3D\"))\n\tgpSetGammaTableI3D = (C.GPSETGAMMATABLEI3D)(getProcAddr(\"wglSetGammaTableI3D\"))\n\tgpSetGammaTableParametersI3D = (C.GPSETGAMMATABLEPARAMETERSI3D)(getProcAddr(\"wglSetGammaTableParametersI3D\"))\n\tgpSetLayerPaletteEntries = (C.GPSETLAYERPALETTEENTRIES)(getProcAddr(\"wglSetLayerPaletteEntries\"))\n\tif gpSetLayerPaletteEntries == nil {\n\t\treturn errors.New(\"wglSetLayerPaletteEntries\")\n\t}\n\tgpSetPbufferAttribARB = (C.GPSETPBUFFERATTRIBARB)(getProcAddr(\"wglSetPbufferAttribARB\"))\n\tgpSetStereoEmitterState3DL = (C.GPSETSTEREOEMITTERSTATE3DL)(getProcAddr(\"wglSetStereoEmitterState3DL\"))\n\tgpShareLists = (C.GPSHARELISTS)(getProcAddr(\"wglShareLists\"))\n\tif gpShareLists == nil {\n\t\treturn errors.New(\"wglShareLists\")\n\t}\n\tgpSwapBuffersMscOML = (C.GPSWAPBUFFERSMSCOML)(getProcAddr(\"wglSwapBuffersMscOML\"))\n\tgpSwapIntervalEXT = (C.GPSWAPINTERVALEXT)(getProcAddr(\"wglSwapIntervalEXT\"))\n\tgpSwapLayerBuffers = (C.GPSWAPLAYERBUFFERS)(getProcAddr(\"wglSwapLayerBuffers\"))\n\tif gpSwapLayerBuffers == nil {\n\t\treturn errors.New(\"wglSwapLayerBuffers\")\n\t}\n\tgpSwapLayerBuffersMscOML = (C.GPSWAPLAYERBUFFERSMSCOML)(getProcAddr(\"wglSwapLayerBuffersMscOML\"))\n\tgpUseFontBitmaps = (C.GPUSEFONTBITMAPS)(getProcAddr(\"wglUseFontBitmaps\"))\n\tif gpUseFontBitmaps == nil {\n\t\treturn errors.New(\"wglUseFontBitmaps\")\n\t}\n\tgpUseFontBitmapsA = (C.GPUSEFONTBITMAPSA)(getProcAddr(\"wglUseFontBitmapsA\"))\n\tif gpUseFontBitmapsA == nil {\n\t\treturn errors.New(\"wglUseFontBitmapsA\")\n\t}\n\tgpUseFontBitmapsW = (C.GPUSEFONTBITMAPSW)(getProcAddr(\"wglUseFontBitmapsW\"))\n\tif gpUseFontBitmapsW == nil {\n\t\treturn errors.New(\"wglUseFontBitmapsW\")\n\t}\n\tgpUseFontOutlines = (C.GPUSEFONTOUTLINES)(getProcAddr(\"wglUseFontOutlines\"))\n\tif gpUseFontOutlines == nil {\n\t\treturn errors.New(\"wglUseFontOutlines\")\n\t}\n\tgpUseFontOutlinesA = (C.GPUSEFONTOUTLINESA)(getProcAddr(\"wglUseFontOutlinesA\"))\n\tif gpUseFontOutlinesA == nil {\n\t\treturn errors.New(\"wglUseFontOutlinesA\")\n\t}\n\tgpUseFontOutlinesW = (C.GPUSEFONTOUTLINESW)(getProcAddr(\"wglUseFontOutlinesW\"))\n\tif gpUseFontOutlinesW == nil {\n\t\treturn errors.New(\"wglUseFontOutlinesW\")\n\t}\n\tgpWaitForMscOML = (C.GPWAITFORMSCOML)(getProcAddr(\"wglWaitForMscOML\"))\n\tgpWaitForSbcOML = (C.GPWAITFORSBCOML)(getProcAddr(\"wglWaitForSbcOML\"))\n\treturn nil\n}",
"func allocPPDFObjMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPPDFObjValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func CreateFramebuffer() Framebuffer {\n\tvar b Framebuffer\n\tgl.GenFramebuffers(1, &b.Value)\n\treturn b\n}",
"func New(pic pixel.Picture) *IMDraw {\n\ttri := &pixel.TrianglesData{}\n\tim := &IMDraw{\n\t\ttri: tri,\n\t\tbatch: pixel.NewBatch(tri, pic),\n\t}\n\tim.SetMatrix(pixel.IM)\n\tim.SetColorMask(pixel.Alpha(1))\n\tim.Reset()\n\treturn im\n}",
"func newFontBytes(owner *Manager, fontBytes []byte, scaleInt int, glyphs string) (f *Font, e error) {\n\tf = new(Font)\n\tscale := fixed.I(scaleInt)\n\n\t// allocate the location map\n\tf.locations = make(map[rune]runeData)\n\n\t// parse the truetype font data\n\tttfData, err := ft.ParseFont(fontBytes)\n\tif err != nil {\n\t\treturn f, fmt.Errorf(\"Failed to prase the truetype font data.\\n%v\", err)\n\t}\n\n\tf.opts.Size = float64(scaleInt)\n\tf.face = truetype.NewFace(ttfData, &f.opts)\n\n\t// this may have negative components, but get the bounds for the font\n\tglyphBounds := ttfData.Bounds(scale)\n\n\t// width and height are getting +2 here since the glyph will be buffered by a\n\t// pixel in the texture\n\tglyphDimensions := glyphBounds.Max.Sub(glyphBounds.Min)\n\tglyphWidth := fixedInt26ToFloat(glyphDimensions.X)\n\tglyphHeight := fixedInt26ToFloat(glyphDimensions.Y)\n\tglyphCeilWidth := int(math.Ceil(float64(glyphWidth)))\n\tglyphCeilHeight := int(math.Ceil(float64(glyphHeight)))\n\n\t// create the buffer image used to draw the glyphs\n\tglyphRect := image.Rect(0, 0, glyphCeilWidth, glyphCeilHeight)\n\tglyphImg := image.NewRGBA(glyphRect)\n\n\t// calculate the area needed for the font texture\n\tvar fontTexSize = 2\n\tminAreaNeeded := (glyphCeilWidth) * (glyphCeilHeight) * len(glyphs)\n\tfor (fontTexSize * fontTexSize) < minAreaNeeded {\n\t\tfontTexSize *= 2\n\t\tif fontTexSize > 2048 {\n\t\t\treturn f, fmt.Errorf(\"Font texture was going to exceed 2048x2048 and that's currently not supported.\")\n\t\t}\n\t}\n\n\t// create the font image\n\tfontImgRect := image.Rect(0, 0, fontTexSize, fontTexSize)\n\tfontImg := image.NewRGBA(fontImgRect)\n\n\t// the number of glyphs\n\tfontRowSize := fontTexSize / glyphCeilWidth\n\n\t// create the freetype context\n\tc := ft.NewContext()\n\tc.SetDPI(72)\n\tc.SetFont(ttfData)\n\tc.SetFontSize(float64(scaleInt))\n\tc.SetClip(glyphImg.Bounds())\n\tc.SetDst(glyphImg)\n\tc.SetSrc(image.White)\n\n\t// NOTE: always disabled for now since it causes a stack overflow error\n\t//c.SetHinting(imgfont.HintingFull)\n\n\tvar fx, fy int\n\tfor _, ch := range glyphs {\n\t\tindex := ttfData.Index(ch)\n\t\tmetricH := ttfData.HMetric(scale, index)\n\t\tmetricV := ttfData.VMetric(scale, index)\n\n\t\tfxGW := fx * glyphCeilWidth\n\t\tfyGH := fy * glyphCeilHeight\n\n\t\tf.locations[ch] = runeData{\n\t\t\tfxGW, fyGH,\n\t\t\tfixedInt26ToFloat(metricH.AdvanceWidth), fixedInt26ToFloat(metricH.LeftSideBearing),\n\t\t\tfixedInt26ToFloat(metricV.AdvanceHeight), fixedInt26ToFloat(metricV.TopSideBearing),\n\t\t\tfloat32(fxGW) / float32(fontTexSize), (float32(fyGH) + glyphHeight) / float32(fontTexSize),\n\t\t\t(float32(fxGW) + glyphWidth) / float32(fontTexSize), float32(fyGH) / float32(fontTexSize),\n\t\t}\n\n\t\tpt := ft.Pt(1, 1+int(c.PointToFixed(float64(scaleInt))>>6))\n\t\t_, err := c.DrawString(string(ch), pt)\n\t\tif err != nil {\n\t\t\treturn f, fmt.Errorf(\"Freetype returned an error while drawing a glyph: %v.\", err)\n\t\t}\n\n\t\t// copy the glyph image into the font image\n\t\tfor subY := 0; subY < glyphCeilHeight; subY++ {\n\t\t\tfor subX := 0; subX < glyphCeilWidth; subX++ {\n\t\t\t\tglyphRGBA := glyphImg.RGBAAt(subX, subY)\n\t\t\t\tfontImg.SetRGBA((fxGW)+subX, (fyGH)+subY, glyphRGBA)\n\t\t\t}\n\t\t}\n\n\t\t// erase the glyph image buffer\n\t\tdraw.Draw(glyphImg, glyphImg.Bounds(), image.Transparent, image.ZP, draw.Src)\n\n\t\t// adjust the pointers into the font image\n\t\tfx++\n\t\tif fx > fontRowSize {\n\t\t\tfx = 0\n\t\t\tfy++\n\t\t}\n\n\t}\n\n\t// set the white point\n\tfontImg.SetRGBA(fontTexSize-1, fontTexSize-1, color.RGBA{R: 255, G: 255, B: 255, A: 255})\n\n\t// buffer the font image into an OpenGL texture\n\tf.Glyphs = glyphs\n\tf.TextureSize = fontTexSize\n\tf.GlyphWidth = glyphWidth\n\tf.GlyphHeight = glyphHeight\n\tf.Owner = owner\n\tf.Texture = f.loadRGBAToTexture(fontImg.Pix, int32(fontImg.Rect.Max.X))\n\n\treturn\n}",
"func (self *GameObjectCreator) BitmapData1O(width int) *BitmapData{\n return &BitmapData{self.Object.Call(\"bitmapData\", width)}\n}",
"func (obj *Device) CreateOffscreenPlainSurface(\n\twidth uint,\n\theight uint,\n\tformat FORMAT,\n\tpool POOL,\n\tsharedHandle uintptr,\n) (*Surface, Error) {\n\tvar surface *Surface\n\tret, _, _ := syscall.Syscall9(\n\t\tobj.vtbl.CreateOffscreenPlainSurface,\n\t\t7,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(width),\n\t\tuintptr(height),\n\t\tuintptr(format),\n\t\tuintptr(pool),\n\t\tuintptr(unsafe.Pointer(&surface)),\n\t\tsharedHandle,\n\t\t0,\n\t\t0,\n\t)\n\treturn surface, toErr(ret)\n}",
"func UseFontBitmaps(hDC unsafe.Pointer, first unsafe.Pointer, count unsafe.Pointer, listBase unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall6(gpUseFontBitmaps, 4, uintptr(hDC), uintptr(first), uintptr(count), uintptr(listBase), 0, 0)\n\treturn (unsafe.Pointer)(ret)\n}",
"func allocFzColorParamsMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzColorParamsValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func allocPDFFunctionMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFFunctionValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (p *PdfiumImplementation) FPDF_RenderPageBitmap(request *requests.FPDF_RenderPageBitmap) (*responses.FPDF_RenderPageBitmap, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tC.FPDF_RenderPageBitmap(bitmapHandle.handle, pageHandle.handle, C.int(request.StartX), C.int(request.StartY), C.int(request.SizeX), C.int(request.SizeY), C.int(request.Rotate), C.int(request.Flags))\n\n\treturn &responses.FPDF_RenderPageBitmap{}, nil\n}",
"func Create_pdf(informations map[string]string, acc loader.Account_Informations) ([]string, error) {\n\tvar err error\n\tvar file_path string\n\tfile_path = Create_folder(acc.Fax_email_connection_host.String, acc.Fax_email_connection_username.String)\n\n\tpdf := gofpdf.New(\"P\", \"pt\", \"A4\", \"\")\n\tpdf.SetAutoPageBreak(true, 40)\n\tpdf.SetMargins(30, 0, 30)\n\ttestText := \"tly with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\"\n\tpdf.SetFooterFunc(func() {\n\t\tpdf.SetY(-25)\n\t\tpdf.SetFont(\"times\", \"I\", 8)\n\t\tpdf.CellFormat(0, 10, testText,\n\t\t\t\"\", 1, \"C\", false, 0, \"\")\n\t})\n\tpdf.AddPage()\n\n\tpdf.SetTopMargin(30)\n\tpdf.SetFont(\"times\", \"\", 10)\n\tpdf.Image((\"./test_logos/logo_test.png\"), 30, 30, 180, 70, false, \"\", 0, \"\")\n\tpdf.Image((\"./test_logos/cover_test.png\"), 450, 30, 120, 70, false, \"\", 0, \"\")\n\n\t//display umlaute in right form\n\ttr := pdf.UnicodeTranslatorFromDescriptor(\"\")\n\tpdf.Ln(20)\n\tpdf.SetX(100)\n\tpdf.SetY(150)\n\ttext := \"FROM: \" + informations[\"from\"]\n\tpdf.Cell(10, 10, tr(text))\n\n\tpdf.SetX(100)\n\tpdf.SetY(200)\n\ttext = \"TO: \" + informations[\"to\"]\n\tpdf.Cell(10, 10, tr(text))\n\n\tpdf.SetX(20)\n\tpdf.SetY(250)\n\ttext = \"SUBJECT: \" + informations[\"subject\"]\n\tpdf.Cell(10, 10, tr(text))\n\tpdf.SetX(30)\n\tpdf.SetY(300)\n\tpdf.SetFont(\"times\", \"\", 12)\n\tpdf.MultiCell(0, 20, tr(informations[\"message\"]), \"0\", \"\", false)\n\n\tpage_count := pdf.PageCount()\n\tfor i := 0; i <= page_count; i++ {\n\t\tfmt.Println(\"pagecount: \", pdf.PageCount())\n\t\tpdf.SetPage(i)\n\t\t//other way doesn't work\n\t\tif pdf.PageCount() == 1 {\n\t\t\tpdf.Line(30, 290, 565.28, 290)\n\t\t\tpdf.Line(30, 290, 30, 800)\n\t\t\tpdf.Line(565.28, 290, 565.28, 800)\n\t\t\tpdf.Line(30, 800, 565.28, 800)\n\t\t} else {\n\t\t\tif i == 1 {\n\t\t\t\tpdf.Line(30, 290, 565.28, 290)\n\t\t\t\tpdf.Line(30, 290, 30, 800)\n\t\t\t\tpdf.Line(565.28, 290, 565.28, 800)\n\t\t\t\tpdf.Line(30, 800, 565.28, 800)\n\n\t\t\t} else {\n\t\t\t\tpdf.Line(30, 30, 565.28, 30)\n\t\t\t\tpdf.Line(30, 30, 30, 800)\n\t\t\t\tpdf.Line(565.28, 30, 565.28, 800)\n\t\t\t\tpdf.Line(30, 800, 565.28, 800)\n\n\t\t\t}\n\t\t}\n\n\t}\n\n\t//create uuid for unique pdf name (temp file - later this file will be removed because of a merge with other files)\n\tuuid, _ := uuid.NewV4()\n\ttmp_filename := uuid.String() + \".pdf\"\n\tresult := []string{}\n\tresult = append(result, file_path, tmp_filename)\n\tfile_path += \"/\" + tmp_filename\n\terr = pdf.OutputFileAndClose(file_path)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"[create_pdf] failed to store created message pdf: \\n%v\", err)\n\t}\n\treturn result, nil\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetFormat(request *requests.FPDFBitmap_GetFormat) (*responses.FPDFBitmap_GetFormat, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tformat := C.FPDFBitmap_GetFormat(bitmapHandle.handle)\n\n\treturn &responses.FPDFBitmap_GetFormat{\n\t\tFormat: enums.FPDF_BITMAP_FORMAT(format),\n\t}, nil\n}",
"func allocFzGlyphMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzGlyphValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func New(bus embd.I2CBus) *HDC100x {\n\t//\tInitialize by setting the config register:\n\tbus.WriteBytes(hdc1000Address, []byte{hdc1000ConfigRegister})\n\n\t//\tReturn a new object\n\treturn &HDC100x{Bus: bus}\n}",
"func NewWithData(width, height int, data []byte) *Bitmap {\n\tbm := New(width, height)\n\tbm.Data = data\n\treturn bm\n}",
"func Open(filename string) (*FrameBuffer, error) {\n\tvar cFilename *C.char\n\tcFilename = C.CString(filename)\n\tdefer C.free(unsafe.Pointer(cFilename))\n\tvar info C.fb_info_t\n\tcErr := C.initfb(cFilename, &info)\n\tif cErr != 0 {\n\t\treturn nil, InitErr\n\t}\n\n\treturn &FrameBuffer{\n\t\tbuf: make([]byte, info.fix_info.smem_len),\n\t\t// XXX: this is theoretically problematic; xres/yres are\n\t\t// uint32, so if we're dealing with a *huge* display, this\n\t\t// could overflow. image.Point expects int though, so we're\n\t\t// kinda stuck. fortunately displays that are greater than 2\n\t\t// million pixels in one dimension don't exist, and probably\n\t\t// never will unless we decide we need a retina display the\n\t\t// size of a football field or something.\n\t\tw: int(info.var_info.xres),\n\t\th: int(info.var_info.yres),\n\t\tfile: os.NewFile(uintptr(info.fd), filename)}, nil\n}",
"func New(s screen.Screen, w, h vg.Length) (*Canvas, error) {\n\tww := w / vg.Inch * vg.Length(vgimg.DefaultDPI)\n\thh := h / vg.Inch * vg.Length(vgimg.DefaultDPI)\n\tsize := image.Pt(int(ww+0.5), int(hh+0.5))\n\timg := draw.Image(image.NewRGBA(image.Rect(0, 0, size.X, size.Y)))\n\tcc := vgimg.NewWith(vgimg.UseImage(img))\n\n\twin, err := s.NewWindow(&screen.NewWindowOptions{\n\t\tWidth: size.X,\n\t\tHeight: size.Y,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuf, err := s.NewBuffer(size)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Canvas{\n\t\twin: win,\n\t\tbuf: buf,\n\t\tCanvas: cc,\n\t\timg: img,\n\t}, nil\n}",
"func (f *FDTable) init() {\n\tf.initNoLeakCheck()\n\tf.InitRefs()\n\tf.fdBitmap = bitmap.New(uint32(math.MaxUint16))\n}",
"func (x *FzBitmap) PassRef() *C.fz_bitmap {\n\tif x == nil {\n\t\tx = (*FzBitmap)(allocFzBitmapMemory(1))\n\t}\n\treturn (*C.fz_bitmap)(unsafe.Pointer(x))\n}",
"func newDevice(title string, x, y, width, height int) *device {\n\td := &device{}\n\td.os = newNativeOs()\n\td.os.createDisplay(title, x, y, width, height)\n\td.os.createShell()\n\tdepthBufferBits, alphaBits := 24, 8 // resonable defaults\n\td.os.createContext(depthBufferBits, alphaBits)\n\td.pressed = newInput(d.os)\n\treturn d\n}",
"func createImage(w, h int) image.Image {\n\t// create a RGBA image from the sensor\n\tpixels := image.NewRGBA(image.Rect(0, 0, w, h))\n\tn := 0\n\tfor _, i := range grid {\n\t\tcolor := colors[getColorIndex(i)]\n\t\tpixels.Pix[n] = getR(color)\n\t\tpixels.Pix[n+1] = getG(color)\n\t\tpixels.Pix[n+2] = getB(color)\n\t\tpixels.Pix[n+3] = 0xFF // we don't need to use this\n\t\tn = n + 4\n\t}\n\tdest := resize.Resize(360, 0, pixels, resize.Lanczos3)\n\treturn dest\n}",
"func allocFzRectMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzRectValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func allocFzColorspaceMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzColorspaceValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func appNumOnUNetBaseCreate(baseID uuid.UUID) *types.Bitmap {\n\tif appNumOnUNetBaseGet(baseID) == nil {\n\t\tlog.Functionf(\"appNumOnUNetBaseCreate (%s)\", baseID.String())\n\t\tappNumBase[baseID.String()] = new(types.Bitmap)\n\t}\n\treturn appNumOnUNetBaseGet(baseID)\n}",
"func Create(height, width int, log *zap.Logger) {\n\tm := mapgen.New(width, height, mapgen.Biome{\n\t\tvbcore.BlockWaterSeed,\n\t\tvbcore.BlockLightDirtSeed,\n\t\tvbcore.BlockGrassSeed,\n\t\tvbcore.BlockTreeSeed,\n\t\tvbcore.BlockLightMountainSeed,\n\t\tvbcore.BlockMountainSeed,\n\t})\n\n\tvar img *image.RGBA\n\timg = image.NewRGBA(image.Rect(0, 0, width*10, height*10))\n\n\tfor y := 0; y < len(m); y++ {\n\t\tfor x := 0; x < len(m[y]); x++ {\n\t\t\tcol := resolveClr(m[y][x])\n\t\t\tfor yy := 10 * y; yy < 10*y+10; yy++ {\n\t\t\t\tfor xx := 10 * x; xx < 10*x+10; xx++ {\n\t\t\t\t\timg.Set(xx, yy, col)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfilename := \"temp_map\"\n\tdir := \"vbmapg\"\n\n\t// create dir if not exists\n\tif _, err := os.Stat(dir); os.IsNotExist(err) {\n\t\terr := os.Mkdir(dir, os.ModePerm)\n\t\tif err != nil {\n\t\t\tlog.Error(\"gen: Unable to create dir\", zap.Error(err))\n\t\t}\n\t}\n\n\t// clear directory\n\terr := removeContent(dir)\n\tif err != nil {\n\t\tlog.Error(\"gen: Unable to remove content of dir\", zap.String(\"dir\", dir), zap.Error(err))\n\t}\n\n\toutput, err := os.Create(path.Join(dir, filename+\".jpg\"))\n\tif err != nil {\n\t\tlog.Error(\"gen: Unable to create file\", zap.String(\"filename\", filename), zap.Error(err))\n\t\treturn\n\t}\n\tdefer output.Close()\n\n\terr = jpeg.Encode(output, img, &jpeg.Options{Quality: jpeg.DefaultQuality})\n\tif err != nil {\n\t\tlog.Error(\"gen: Unable to create image\", zap.Error(err))\n\t\treturn\n\t}\n\n\tmatrix := make([][]string, height)\n\tfor i := 0; i < height; i++ {\n\t\tmatrix[i] = make([]string, width)\n\t}\n\n\tfor y := 0; y < len(m); y++ {\n\t\tfor x := 0; x < len(m[y]); x++ {\n\t\t\tcol := resolveClr(m[y][x])\n\t\t\tswitch col {\n\t\t\tcase vbcore.BlockWaterClr:\n\t\t\t\tmatrix[y][x] = vbcore.BlockWater\n\t\t\tcase vbcore.BlockLightDirtClr:\n\t\t\t\tmatrix[y][x] = vbcore.BlockLightDirt\n\t\t\tcase vbcore.BlockGrassClr:\n\t\t\t\tmatrix[y][x] = vbcore.BlockGrass\n\t\t\tcase vbcore.BlockTreeClr:\n\t\t\t\tmatrix[y][x] = vbcore.BlockTree\n\t\t\tcase vbcore.BlockLightMountainClr:\n\t\t\t\tmatrix[y][x] = vbcore.BlockLightMountain\n\t\t\tcase vbcore.BlockMountainClr:\n\t\t\t\tmatrix[y][x] = vbcore.BlockMountain\n\t\t\t}\n\t\t}\n\t}\n\n\tdata, err := json.Marshal(matrix)\n\tif err != nil {\n\t\tlog.Warn(\"unable to marshal matrix\", zap.Error(err))\n\t}\n\n\tioutil.WriteFile(path.Join(dir, filename+\".json\"), data, 0644)\n}",
"func allocFzShadeMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzShadeValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func NewPDFOcgDescriptor() *PDFOcgDescriptor {\n\treturn (*PDFOcgDescriptor)(allocPDFOcgDescriptorMemory(1))\n}",
"func allocFzCmmInstanceMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzCmmInstanceValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func allocPDFDaInfoMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFDaInfoValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func allocPFzPixmapMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPFzPixmapValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func CreateDisplay(cv *Canvas) (Display, error) {\n\tvar cPtr *C.struct_caca_display\n\n\tvar err error\n\n\tif cv != nil {\n\t\tcPtr, err = C.caca_create_display(cv.Cv)\n\t} else {\n\t\tcPtr, err = C.caca_create_display(nil)\n\t}\n\n\tif cPtr == nil {\n\t\treturn Display{}, err\n\t}\n\n\treturn Display{Dp: cPtr}, nil\n}",
"func allocPFzFontMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPFzFontValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func allocPDFObjMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFObjValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func CreateDCTImageObject(xRefTable *XRefTable, buf []byte, w, h, bpc int, cs string) (*types.StreamDict, error) {\n\tsd := &types.StreamDict{\n\t\tDict: types.Dict(\n\t\t\tmap[string]types.Object{\n\t\t\t\t\"Type\": types.Name(\"XObject\"),\n\t\t\t\t\"Subtype\": types.Name(\"Image\"),\n\t\t\t\t\"Width\": types.Integer(w),\n\t\t\t\t\"Height\": types.Integer(h),\n\t\t\t\t\"BitsPerComponent\": types.Integer(bpc),\n\t\t\t\t\"ColorSpace\": types.Name(cs),\n\t\t\t},\n\t\t),\n\t\tContent: buf,\n\t\tFilterPipeline: nil,\n\t}\n\n\tif cs == DeviceCMYKCS {\n\t\tsd.Insert(\"Decode\", types.NewIntegerArray(1, 0, 1, 0, 1, 0, 1, 0))\n\t}\n\n\tif w < 1000 || h < 1000 {\n\t\tsd.Insert(\"Interpolate\", types.Boolean(true))\n\t}\n\n\tsd.InsertName(\"Filter\", filter.DCT)\n\n\t// Calling Encode without FilterPipeline ensures an encoded stream in sd.Raw.\n\tif err := sd.Encode(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsd.Content = nil\n\n\tsd.FilterPipeline = []types.PDFFilter{{Name: filter.DCT, DecodeParms: nil}}\n\n\treturn sd, nil\n}",
"func (x *FzPixmap) Free() {\n\tif x != nil && x.allocs7c1a1ba1 != nil {\n\t\tx.allocs7c1a1ba1.(*cgoAllocMap).Free()\n\t\tx.ref7c1a1ba1 = nil\n\t}\n}",
"func drawBackground(image *image.RGBA, mem *GBMem) *image.RGBA {\n\tfor x := 0; x < MapWidth; x++ {\n\t\tfor y := 0; y < MapHeight; y++ {\n\t\t\t// get tile index\n\t\t\ttileIndex := mem.read(uint16(VRAMBackgroundMap + x + (y * MapHeight)))\n\n\t\t\t// get pixels corresponding to tile index\n\t\t\tpixels := tileToPixel(tileIndex, mem)\n\n\t\t\t// draw pixels\n\t\t\tdrawTilePixels(image, pixels, x, y)\n\t\t}\n\t}\n\treturn image\n}",
"func (self *GameObjectCreator) BitmapData2O(width int, height int) *BitmapData{\n return &BitmapData{self.Object.Call(\"bitmapData\", width, height)}\n}",
"func (*DarwinProvider) CreateGrabber(screen Screen, fps int, bitrate int) (Grabber, error) {\n\treturn &DarwinGrabber {\n\t\tscreen: screen,\n\t\tfps: fps,\n\t\tbitrate: bitrate,\n\t\tframes: make(chan *image.RGBA),\n\t\tstop: make(chan struct{}),\n\t\tevents: make(chan Event),\n\t}, nil\n}",
"func allocFzColorspaceContextMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzColorspaceContextValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func CreateBlankImage(dest string, size resource.Quantity, preallocate bool) error {\n\tklog.V(1).Infof(\"creating raw image with size %s, preallocation %v\", size.String(), preallocate)\n\treturn qemuIterface.CreateBlankImage(dest, size, preallocate)\n}",
"func InitWithProcAddrFunc(getProcAddr func(name string) unsafe.Pointer) error {\n\tgpChoosePixelFormat = uintptr(getProcAddr(\"ChoosePixelFormat\"))\n\tif gpChoosePixelFormat == 0 {\n\t\treturn errors.New(\"ChoosePixelFormat\")\n\t}\n\tgpDescribePixelFormat = uintptr(getProcAddr(\"DescribePixelFormat\"))\n\tif gpDescribePixelFormat == 0 {\n\t\treturn errors.New(\"DescribePixelFormat\")\n\t}\n\tgpGetEnhMetaFilePixelFormat = uintptr(getProcAddr(\"GetEnhMetaFilePixelFormat\"))\n\tif gpGetEnhMetaFilePixelFormat == 0 {\n\t\treturn errors.New(\"GetEnhMetaFilePixelFormat\")\n\t}\n\tgpGetPixelFormat = uintptr(getProcAddr(\"GetPixelFormat\"))\n\tif gpGetPixelFormat == 0 {\n\t\treturn errors.New(\"GetPixelFormat\")\n\t}\n\tgpSetPixelFormat = uintptr(getProcAddr(\"SetPixelFormat\"))\n\tif gpSetPixelFormat == 0 {\n\t\treturn errors.New(\"SetPixelFormat\")\n\t}\n\tgpSwapBuffers = uintptr(getProcAddr(\"SwapBuffers\"))\n\tif gpSwapBuffers == 0 {\n\t\treturn errors.New(\"SwapBuffers\")\n\t}\n\tgpAllocateMemoryNV = uintptr(getProcAddr(\"wglAllocateMemoryNV\"))\n\tgpAssociateImageBufferEventsI3D = uintptr(getProcAddr(\"wglAssociateImageBufferEventsI3D\"))\n\tgpBeginFrameTrackingI3D = uintptr(getProcAddr(\"wglBeginFrameTrackingI3D\"))\n\tgpBindDisplayColorTableEXT = uintptr(getProcAddr(\"wglBindDisplayColorTableEXT\"))\n\tgpBindSwapBarrierNV = uintptr(getProcAddr(\"wglBindSwapBarrierNV\"))\n\tgpBindTexImageARB = uintptr(getProcAddr(\"wglBindTexImageARB\"))\n\tgpBindVideoCaptureDeviceNV = uintptr(getProcAddr(\"wglBindVideoCaptureDeviceNV\"))\n\tgpBindVideoDeviceNV = uintptr(getProcAddr(\"wglBindVideoDeviceNV\"))\n\tgpBindVideoImageNV = uintptr(getProcAddr(\"wglBindVideoImageNV\"))\n\tgpBlitContextFramebufferAMD = uintptr(getProcAddr(\"wglBlitContextFramebufferAMD\"))\n\tgpChoosePixelFormatARB = uintptr(getProcAddr(\"wglChoosePixelFormatARB\"))\n\tgpChoosePixelFormatEXT = uintptr(getProcAddr(\"wglChoosePixelFormatEXT\"))\n\tgpCopyContext = uintptr(getProcAddr(\"wglCopyContext\"))\n\tif gpCopyContext == 0 {\n\t\treturn errors.New(\"wglCopyContext\")\n\t}\n\tgpCopyImageSubDataNV = uintptr(getProcAddr(\"wglCopyImageSubDataNV\"))\n\tgpCreateAffinityDCNV = uintptr(getProcAddr(\"wglCreateAffinityDCNV\"))\n\tgpCreateAssociatedContextAMD = uintptr(getProcAddr(\"wglCreateAssociatedContextAMD\"))\n\tgpCreateAssociatedContextAttribsAMD = uintptr(getProcAddr(\"wglCreateAssociatedContextAttribsAMD\"))\n\tgpCreateBufferRegionARB = uintptr(getProcAddr(\"wglCreateBufferRegionARB\"))\n\tgpCreateContext = uintptr(getProcAddr(\"wglCreateContext\"))\n\tif gpCreateContext == 0 {\n\t\treturn errors.New(\"wglCreateContext\")\n\t}\n\tgpCreateContextAttribsARB = uintptr(getProcAddr(\"wglCreateContextAttribsARB\"))\n\tgpCreateDisplayColorTableEXT = uintptr(getProcAddr(\"wglCreateDisplayColorTableEXT\"))\n\tgpCreateImageBufferI3D = uintptr(getProcAddr(\"wglCreateImageBufferI3D\"))\n\tgpCreateLayerContext = uintptr(getProcAddr(\"wglCreateLayerContext\"))\n\tif gpCreateLayerContext == 0 {\n\t\treturn errors.New(\"wglCreateLayerContext\")\n\t}\n\tgpCreatePbufferARB = uintptr(getProcAddr(\"wglCreatePbufferARB\"))\n\tgpCreatePbufferEXT = uintptr(getProcAddr(\"wglCreatePbufferEXT\"))\n\tgpDXCloseDeviceNV = uintptr(getProcAddr(\"wglDXCloseDeviceNV\"))\n\tgpDXLockObjectsNV = uintptr(getProcAddr(\"wglDXLockObjectsNV\"))\n\tgpDXObjectAccessNV = uintptr(getProcAddr(\"wglDXObjectAccessNV\"))\n\tgpDXOpenDeviceNV = uintptr(getProcAddr(\"wglDXOpenDeviceNV\"))\n\tgpDXRegisterObjectNV = uintptr(getProcAddr(\"wglDXRegisterObjectNV\"))\n\tgpDXSetResourceShareHandleNV = uintptr(getProcAddr(\"wglDXSetResourceShareHandleNV\"))\n\tgpDXUnlockObjectsNV = uintptr(getProcAddr(\"wglDXUnlockObjectsNV\"))\n\tgpDXUnregisterObjectNV = uintptr(getProcAddr(\"wglDXUnregisterObjectNV\"))\n\tgpDelayBeforeSwapNV = uintptr(getProcAddr(\"wglDelayBeforeSwapNV\"))\n\tgpDeleteAssociatedContextAMD = uintptr(getProcAddr(\"wglDeleteAssociatedContextAMD\"))\n\tgpDeleteBufferRegionARB = uintptr(getProcAddr(\"wglDeleteBufferRegionARB\"))\n\tgpDeleteContext = uintptr(getProcAddr(\"wglDeleteContext\"))\n\tif gpDeleteContext == 0 {\n\t\treturn errors.New(\"wglDeleteContext\")\n\t}\n\tgpDeleteDCNV = uintptr(getProcAddr(\"wglDeleteDCNV\"))\n\tgpDescribeLayerPlane = uintptr(getProcAddr(\"wglDescribeLayerPlane\"))\n\tif gpDescribeLayerPlane == 0 {\n\t\treturn errors.New(\"wglDescribeLayerPlane\")\n\t}\n\tgpDestroyDisplayColorTableEXT = uintptr(getProcAddr(\"wglDestroyDisplayColorTableEXT\"))\n\tgpDestroyImageBufferI3D = uintptr(getProcAddr(\"wglDestroyImageBufferI3D\"))\n\tgpDestroyPbufferARB = uintptr(getProcAddr(\"wglDestroyPbufferARB\"))\n\tgpDestroyPbufferEXT = uintptr(getProcAddr(\"wglDestroyPbufferEXT\"))\n\tgpDisableFrameLockI3D = uintptr(getProcAddr(\"wglDisableFrameLockI3D\"))\n\tgpDisableGenlockI3D = uintptr(getProcAddr(\"wglDisableGenlockI3D\"))\n\tgpEnableFrameLockI3D = uintptr(getProcAddr(\"wglEnableFrameLockI3D\"))\n\tgpEnableGenlockI3D = uintptr(getProcAddr(\"wglEnableGenlockI3D\"))\n\tgpEndFrameTrackingI3D = uintptr(getProcAddr(\"wglEndFrameTrackingI3D\"))\n\tgpEnumGpuDevicesNV = uintptr(getProcAddr(\"wglEnumGpuDevicesNV\"))\n\tgpEnumGpusFromAffinityDCNV = uintptr(getProcAddr(\"wglEnumGpusFromAffinityDCNV\"))\n\tgpEnumGpusNV = uintptr(getProcAddr(\"wglEnumGpusNV\"))\n\tgpEnumerateVideoCaptureDevicesNV = uintptr(getProcAddr(\"wglEnumerateVideoCaptureDevicesNV\"))\n\tgpEnumerateVideoDevicesNV = uintptr(getProcAddr(\"wglEnumerateVideoDevicesNV\"))\n\tgpFreeMemoryNV = uintptr(getProcAddr(\"wglFreeMemoryNV\"))\n\tgpGenlockSampleRateI3D = uintptr(getProcAddr(\"wglGenlockSampleRateI3D\"))\n\tgpGenlockSourceDelayI3D = uintptr(getProcAddr(\"wglGenlockSourceDelayI3D\"))\n\tgpGenlockSourceEdgeI3D = uintptr(getProcAddr(\"wglGenlockSourceEdgeI3D\"))\n\tgpGenlockSourceI3D = uintptr(getProcAddr(\"wglGenlockSourceI3D\"))\n\tgpGetContextGPUIDAMD = uintptr(getProcAddr(\"wglGetContextGPUIDAMD\"))\n\tgpGetCurrentAssociatedContextAMD = uintptr(getProcAddr(\"wglGetCurrentAssociatedContextAMD\"))\n\tgpGetCurrentContext = uintptr(getProcAddr(\"wglGetCurrentContext\"))\n\tif gpGetCurrentContext == 0 {\n\t\treturn errors.New(\"wglGetCurrentContext\")\n\t}\n\tgpGetCurrentDC = uintptr(getProcAddr(\"wglGetCurrentDC\"))\n\tif gpGetCurrentDC == 0 {\n\t\treturn errors.New(\"wglGetCurrentDC\")\n\t}\n\tgpGetCurrentReadDCARB = uintptr(getProcAddr(\"wglGetCurrentReadDCARB\"))\n\tgpGetCurrentReadDCEXT = uintptr(getProcAddr(\"wglGetCurrentReadDCEXT\"))\n\tgpGetDigitalVideoParametersI3D = uintptr(getProcAddr(\"wglGetDigitalVideoParametersI3D\"))\n\tgpGetExtensionsStringARB = uintptr(getProcAddr(\"wglGetExtensionsStringARB\"))\n\tgpGetExtensionsStringEXT = uintptr(getProcAddr(\"wglGetExtensionsStringEXT\"))\n\tgpGetFrameUsageI3D = uintptr(getProcAddr(\"wglGetFrameUsageI3D\"))\n\tgpGetGPUIDsAMD = uintptr(getProcAddr(\"wglGetGPUIDsAMD\"))\n\tgpGetGPUInfoAMD = uintptr(getProcAddr(\"wglGetGPUInfoAMD\"))\n\tgpGetGammaTableI3D = uintptr(getProcAddr(\"wglGetGammaTableI3D\"))\n\tgpGetGammaTableParametersI3D = uintptr(getProcAddr(\"wglGetGammaTableParametersI3D\"))\n\tgpGetGenlockSampleRateI3D = uintptr(getProcAddr(\"wglGetGenlockSampleRateI3D\"))\n\tgpGetGenlockSourceDelayI3D = uintptr(getProcAddr(\"wglGetGenlockSourceDelayI3D\"))\n\tgpGetGenlockSourceEdgeI3D = uintptr(getProcAddr(\"wglGetGenlockSourceEdgeI3D\"))\n\tgpGetGenlockSourceI3D = uintptr(getProcAddr(\"wglGetGenlockSourceI3D\"))\n\tgpGetLayerPaletteEntries = uintptr(getProcAddr(\"wglGetLayerPaletteEntries\"))\n\tif gpGetLayerPaletteEntries == 0 {\n\t\treturn errors.New(\"wglGetLayerPaletteEntries\")\n\t}\n\tgpGetMscRateOML = uintptr(getProcAddr(\"wglGetMscRateOML\"))\n\tgpGetPbufferDCARB = uintptr(getProcAddr(\"wglGetPbufferDCARB\"))\n\tgpGetPbufferDCEXT = uintptr(getProcAddr(\"wglGetPbufferDCEXT\"))\n\tgpGetPixelFormatAttribfvARB = uintptr(getProcAddr(\"wglGetPixelFormatAttribfvARB\"))\n\tgpGetPixelFormatAttribfvEXT = uintptr(getProcAddr(\"wglGetPixelFormatAttribfvEXT\"))\n\tgpGetPixelFormatAttribivARB = uintptr(getProcAddr(\"wglGetPixelFormatAttribivARB\"))\n\tgpGetPixelFormatAttribivEXT = uintptr(getProcAddr(\"wglGetPixelFormatAttribivEXT\"))\n\tgpGetProcAddress = uintptr(getProcAddr(\"wglGetProcAddress\"))\n\tif gpGetProcAddress == 0 {\n\t\treturn errors.New(\"wglGetProcAddress\")\n\t}\n\tgpGetSwapIntervalEXT = uintptr(getProcAddr(\"wglGetSwapIntervalEXT\"))\n\tgpGetSyncValuesOML = uintptr(getProcAddr(\"wglGetSyncValuesOML\"))\n\tgpGetVideoDeviceNV = uintptr(getProcAddr(\"wglGetVideoDeviceNV\"))\n\tgpGetVideoInfoNV = uintptr(getProcAddr(\"wglGetVideoInfoNV\"))\n\tgpIsEnabledFrameLockI3D = uintptr(getProcAddr(\"wglIsEnabledFrameLockI3D\"))\n\tgpIsEnabledGenlockI3D = uintptr(getProcAddr(\"wglIsEnabledGenlockI3D\"))\n\tgpJoinSwapGroupNV = uintptr(getProcAddr(\"wglJoinSwapGroupNV\"))\n\tgpLoadDisplayColorTableEXT = uintptr(getProcAddr(\"wglLoadDisplayColorTableEXT\"))\n\tgpLockVideoCaptureDeviceNV = uintptr(getProcAddr(\"wglLockVideoCaptureDeviceNV\"))\n\tgpMakeAssociatedContextCurrentAMD = uintptr(getProcAddr(\"wglMakeAssociatedContextCurrentAMD\"))\n\tgpMakeContextCurrentARB = uintptr(getProcAddr(\"wglMakeContextCurrentARB\"))\n\tgpMakeContextCurrentEXT = uintptr(getProcAddr(\"wglMakeContextCurrentEXT\"))\n\tgpMakeCurrent = uintptr(getProcAddr(\"wglMakeCurrent\"))\n\tif gpMakeCurrent == 0 {\n\t\treturn errors.New(\"wglMakeCurrent\")\n\t}\n\tgpQueryCurrentContextNV = uintptr(getProcAddr(\"wglQueryCurrentContextNV\"))\n\tgpQueryFrameCountNV = uintptr(getProcAddr(\"wglQueryFrameCountNV\"))\n\tgpQueryFrameLockMasterI3D = uintptr(getProcAddr(\"wglQueryFrameLockMasterI3D\"))\n\tgpQueryFrameTrackingI3D = uintptr(getProcAddr(\"wglQueryFrameTrackingI3D\"))\n\tgpQueryGenlockMaxSourceDelayI3D = uintptr(getProcAddr(\"wglQueryGenlockMaxSourceDelayI3D\"))\n\tgpQueryMaxSwapGroupsNV = uintptr(getProcAddr(\"wglQueryMaxSwapGroupsNV\"))\n\tgpQueryPbufferARB = uintptr(getProcAddr(\"wglQueryPbufferARB\"))\n\tgpQueryPbufferEXT = uintptr(getProcAddr(\"wglQueryPbufferEXT\"))\n\tgpQuerySwapGroupNV = uintptr(getProcAddr(\"wglQuerySwapGroupNV\"))\n\tgpQueryVideoCaptureDeviceNV = uintptr(getProcAddr(\"wglQueryVideoCaptureDeviceNV\"))\n\tgpRealizeLayerPalette = uintptr(getProcAddr(\"wglRealizeLayerPalette\"))\n\tif gpRealizeLayerPalette == 0 {\n\t\treturn errors.New(\"wglRealizeLayerPalette\")\n\t}\n\tgpReleaseImageBufferEventsI3D = uintptr(getProcAddr(\"wglReleaseImageBufferEventsI3D\"))\n\tgpReleasePbufferDCARB = uintptr(getProcAddr(\"wglReleasePbufferDCARB\"))\n\tgpReleasePbufferDCEXT = uintptr(getProcAddr(\"wglReleasePbufferDCEXT\"))\n\tgpReleaseTexImageARB = uintptr(getProcAddr(\"wglReleaseTexImageARB\"))\n\tgpReleaseVideoCaptureDeviceNV = uintptr(getProcAddr(\"wglReleaseVideoCaptureDeviceNV\"))\n\tgpReleaseVideoDeviceNV = uintptr(getProcAddr(\"wglReleaseVideoDeviceNV\"))\n\tgpReleaseVideoImageNV = uintptr(getProcAddr(\"wglReleaseVideoImageNV\"))\n\tgpResetFrameCountNV = uintptr(getProcAddr(\"wglResetFrameCountNV\"))\n\tgpRestoreBufferRegionARB = uintptr(getProcAddr(\"wglRestoreBufferRegionARB\"))\n\tgpSaveBufferRegionARB = uintptr(getProcAddr(\"wglSaveBufferRegionARB\"))\n\tgpSendPbufferToVideoNV = uintptr(getProcAddr(\"wglSendPbufferToVideoNV\"))\n\tgpSetDigitalVideoParametersI3D = uintptr(getProcAddr(\"wglSetDigitalVideoParametersI3D\"))\n\tgpSetGammaTableI3D = uintptr(getProcAddr(\"wglSetGammaTableI3D\"))\n\tgpSetGammaTableParametersI3D = uintptr(getProcAddr(\"wglSetGammaTableParametersI3D\"))\n\tgpSetLayerPaletteEntries = uintptr(getProcAddr(\"wglSetLayerPaletteEntries\"))\n\tif gpSetLayerPaletteEntries == 0 {\n\t\treturn errors.New(\"wglSetLayerPaletteEntries\")\n\t}\n\tgpSetPbufferAttribARB = uintptr(getProcAddr(\"wglSetPbufferAttribARB\"))\n\tgpSetStereoEmitterState3DL = uintptr(getProcAddr(\"wglSetStereoEmitterState3DL\"))\n\tgpShareLists = uintptr(getProcAddr(\"wglShareLists\"))\n\tif gpShareLists == 0 {\n\t\treturn errors.New(\"wglShareLists\")\n\t}\n\tgpSwapBuffersMscOML = uintptr(getProcAddr(\"wglSwapBuffersMscOML\"))\n\tgpSwapIntervalEXT = uintptr(getProcAddr(\"wglSwapIntervalEXT\"))\n\tgpSwapLayerBuffers = uintptr(getProcAddr(\"wglSwapLayerBuffers\"))\n\tif gpSwapLayerBuffers == 0 {\n\t\treturn errors.New(\"wglSwapLayerBuffers\")\n\t}\n\tgpSwapLayerBuffersMscOML = uintptr(getProcAddr(\"wglSwapLayerBuffersMscOML\"))\n\tgpUseFontBitmaps = uintptr(getProcAddr(\"wglUseFontBitmapsW\"))\n\tif gpUseFontBitmaps == 0 {\n\t\treturn errors.New(\"wglUseFontBitmaps\")\n\t}\n\tgpUseFontOutlines = uintptr(getProcAddr(\"wglUseFontOutlinesW\"))\n\tif gpUseFontOutlines == 0 {\n\t\treturn errors.New(\"wglUseFontOutlines\")\n\t}\n\tgpWaitForMscOML = uintptr(getProcAddr(\"wglWaitForMscOML\"))\n\tgpWaitForSbcOML = uintptr(getProcAddr(\"wglWaitForSbcOML\"))\n\treturn nil\n}",
"func (obj *Device) CreatePixelShaderFromBytes(code []byte) (*PixelShader, Error) {\n\treturn obj.CreatePixelShader(uintptr(unsafe.Pointer(&code[0])))\n}",
"func allocFzPclOptionsMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzPclOptionsValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func LoadFontBitmap(image *Image, charset string, charPerLines, noLines int) *Font {\n\tf := &Font{\n\t\tcharset: charset,\n\t\tglyphs: make(map[rune]Glyph, len(charset)),\n\t\tSpacing: 0,\n\t\tkerner: &monoSpacedKerner{},\n\t\ttexture: image.CreateTexture(),\n\t}\n\n\timageWidth := float32(image.Width())\n\timageHeight := float32(image.Height())\n\tgwidth := imageWidth / float32(charPerLines)\n\tgheight := imageHeight / float32(noLines)\n\n\t//Why is this inconsistent. Its even a different type. Its like saying this array is a byte array, until you walk it, then its a rune array\n\t//for i, c := range charset {\n\t//\tif rune(charset[i]) == c {\n\t//\t\tlog.Println(i, c, \" <- MATCH\")\n\t//\t} else {\n\t//\t\tlog.Println(i, c, \" <- DIFFERENT?\")\n\t//\t}\n\t//}\n\n\tx := float32(0)\n\ty := float32(0)\n\tfor i := range charset {\n\n\t\t//Get the rune and map it\n\t\tf.glyphs[rune(charset[i])] = Glyph{\n\t\t\tAtlas: Rectangle{(x * gwidth), (y * gheight), gwidth, gheight},\n\t\t\tAdvance: gwidth,\n\t\t\tAscent: 0,\n\t\t\tDescent: 0,\n\t\t}\n\n\t\t//increment and reset if requried\n\t\tx++\n\t\tif x >= float32(charPerLines) {\n\t\t\tx = 0\n\t\t\ty++\n\t\t}\n\t}\n\n\treturn f\n}",
"func allocFzPageMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzPageValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func allocFzDisplayListMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzDisplayListValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}"
] | [
"0.71049416",
"0.61413354",
"0.60597026",
"0.5832008",
"0.55958384",
"0.5463785",
"0.52714014",
"0.5267745",
"0.5231697",
"0.510129",
"0.50961006",
"0.50673234",
"0.5042559",
"0.50136966",
"0.49160862",
"0.4912569",
"0.48916736",
"0.48377025",
"0.48359215",
"0.48348254",
"0.480084",
"0.47630838",
"0.47088268",
"0.4701308",
"0.46963114",
"0.4679746",
"0.46682656",
"0.46556896",
"0.46506485",
"0.46477863",
"0.46396175",
"0.46391904",
"0.46343383",
"0.46200427",
"0.4586912",
"0.4579303",
"0.45738512",
"0.4572734",
"0.45684686",
"0.4554406",
"0.45515546",
"0.45386067",
"0.45340878",
"0.45304045",
"0.4528866",
"0.45187443",
"0.44991806",
"0.44949958",
"0.44906685",
"0.44819957",
"0.44675338",
"0.44655746",
"0.445529",
"0.4438922",
"0.44218135",
"0.441942",
"0.44190967",
"0.44172898",
"0.44170463",
"0.4416838",
"0.43969336",
"0.43911466",
"0.43862215",
"0.43817076",
"0.43813953",
"0.4376664",
"0.43716967",
"0.43689087",
"0.4365713",
"0.4365531",
"0.43636408",
"0.43631575",
"0.43611264",
"0.4360337",
"0.43597817",
"0.43587258",
"0.43562773",
"0.435435",
"0.43439972",
"0.433945",
"0.43381217",
"0.4334827",
"0.43314254",
"0.43292743",
"0.43284404",
"0.43258974",
"0.43231693",
"0.43205655",
"0.43189067",
"0.43174854",
"0.43131468",
"0.4299824",
"0.4298337",
"0.42978367",
"0.42969105",
"0.42887044",
"0.42856926",
"0.4280592",
"0.42759195",
"0.42637035"
] | 0.76134765 | 0 |
FPDFBitmap_CreateEx Create a device independent bitmap (FXDIB) with an external buffer. Similar to FPDFBitmap_Create function, but allows for more formats and an external buffer is supported. The bitmap created by this function can be used in any place that a FPDF_BITMAP handle is required. If an external buffer is used, then the caller should destroy the buffer. FPDFBitmap_Destroy() will not destroy the buffer. It is recommended to use FPDFBitmap_GetStride() to get the stride value. Not supported on multithreaded usage. | func (p *PdfiumImplementation) FPDFBitmap_CreateEx(request *requests.FPDFBitmap_CreateEx) (*responses.FPDFBitmap_CreateEx, error) {
p.Lock()
defer p.Unlock()
var pointer unsafe.Pointer
if request.Buffer != nil {
pointer = unsafe.Pointer(&request.Buffer[0])
} else if request.Pointer != nil {
v, ok := request.Pointer.(unsafe.Pointer)
if !ok {
return nil, errors.New("request.Pointer is not of type unsafe.Pointer")
}
pointer = v
}
bitmap := C.FPDFBitmap_CreateEx(C.int(request.Width), C.int(request.Height), C.int(request.Format), pointer, C.int(request.Stride))
bitmapHandle := p.registerBitmap(bitmap)
return &responses.FPDFBitmap_CreateEx{
Bitmap: bitmapHandle.nativeRef,
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (p *PdfiumImplementation) FPDFBitmap_Create(request *requests.FPDFBitmap_Create) (*responses.FPDFBitmap_Create, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmap := C.FPDFBitmap_Create(C.int(request.Width), C.int(request.Height), C.int(request.Alpha))\n\tbitmapHandle := p.registerBitmap(bitmap)\n\n\treturn &responses.FPDFBitmap_Create{\n\t\tBitmap: bitmapHandle.nativeRef,\n\t}, nil\n}",
"func NewFzBitmapRef(ref unsafe.Pointer) *FzBitmap {\n\treturn (*FzBitmap)(ref)\n}",
"func NewFzBitmap() *FzBitmap {\n\treturn (*FzBitmap)(allocFzBitmapMemory(1))\n}",
"func CreatePbufferEXT(hDC unsafe.Pointer, iPixelFormat unsafe.Pointer, iWidth unsafe.Pointer, iHeight unsafe.Pointer, piAttribList unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall6(gpCreatePbufferEXT, 5, uintptr(hDC), uintptr(iPixelFormat), uintptr(iWidth), uintptr(iHeight), uintptr(piAttribList), 0)\n\treturn (unsafe.Pointer)(ret)\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetBuffer(request *requests.FPDFBitmap_GetBuffer) (*responses.FPDFBitmap_GetBuffer, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We need to calculate the buffer size, this is stride (bytes per bitmap line) * height.\n\tstride := C.FPDFBitmap_GetStride(bitmapHandle.handle)\n\theight := C.FPDFBitmap_GetHeight(bitmapHandle.handle)\n\tsize := int(stride * height)\n\n\t// The pointer to the first byte of the bitmap buffer.\n\tbuffer := C.FPDFBitmap_GetBuffer(bitmapHandle.handle)\n\n\t// We create a Go slice backed by a C array (without copying the original data).\n\tdata := unsafe.Slice((*byte)(unsafe.Pointer(buffer)), uint64(size))\n\n\treturn &responses.FPDFBitmap_GetBuffer{\n\t\tBuffer: data,\n\t}, nil\n}",
"func CreateImageBufferI3D(hDC unsafe.Pointer, dwSize unsafe.Pointer, uFlags unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpCreateImageBufferI3D, 3, uintptr(hDC), uintptr(dwSize), uintptr(uFlags))\n\treturn (unsafe.Pointer)(ret)\n}",
"func CreatePbufferARB(hDC unsafe.Pointer, iPixelFormat unsafe.Pointer, iWidth unsafe.Pointer, iHeight unsafe.Pointer, piAttribList unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall6(gpCreatePbufferARB, 5, uintptr(hDC), uintptr(iPixelFormat), uintptr(iWidth), uintptr(iHeight), uintptr(piAttribList), 0)\n\treturn (unsafe.Pointer)(ret)\n}",
"func NewBitmap(fn Name) (*Bitmap, error) {\n\t// Each font is hard-coded into the binary as a slice of bytes.\n\tinfo, err := fontInfo(fn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Which is then decoded.\n\tpngImage, err := png.Decode(bytes.NewReader(info.byts))\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"font %+v\", fn)\n\t}\n\n\tebiImage := ebiten.NewImageFromImage(pngImage)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"font %+v\", fn)\n\t}\n\n\treturn &Bitmap{\n\t\timg: ebiImage,\n\t\tsize: info.size,\n\t\tmask: info.mask,\n\t\tsubmap: make(map[rune]*Glyph),\n\t}, nil\n}",
"func New(width, height int) *Bitmap {\n\tbm := &Bitmap{\n\t\tWidth: width,\n\t\tHeight: height,\n\t\tRowStride: (width + 7) >> 3,\n\t}\n\tbm.Data = make([]byte, height*bm.RowStride)\n\n\treturn bm\n}",
"func allocFzBitmapMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzBitmapValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func NewFzBufferRef(ref unsafe.Pointer) *FzBuffer {\n\treturn (*FzBuffer)(ref)\n}",
"func WndProc(hwnd syscall.Handle, msg uint32, wparam, lparam uintptr) (rc uintptr) {\n\t_ = make([]int, 100000)\n\tswitch msg {\n\tcase wingui.WM_CREATE:\n\t\thdc := wingui.GetDC(hwnd)\n\t\thdcWndBuffer = wingui.CreateCompatibleDC(hdc)\n\t\twndBufferHeader = wingui.CreateCompatibleBitmap(hdc, 600, 800)\n\t\twingui.GetObject(wndBufferHeader, unsafe.Sizeof(wndBuffer), uintptr(unsafe.Pointer(&wndBuffer)))\n\t\twingui.SelectObject(hdcWndBuffer, wndBufferHeader)\n\n\t\tvar bmp_header wingui.BITMAPINFOHEADER\n\t\tbmp_header.Size = uint32(unsafe.Sizeof(bmp_header))\n\t\tbmp_header.Width = 600\n\t\tbmp_header.Height = 800\n\t\tbmp_header.SizeImage = 0 // the api says this must be 0 for BI_RGB images\n\t\tbmp_header.Compression = wingui.BI_RGB\n\t\tbmp_header.BitCount = 32\n\t\tbmp_header.Planes = 1\n\t\tbmp_header.XPelsPerMeter = 0\n\t\tbmp_header.YPelsPerMeter = 0\n\t\tbmp_header.ClrUsed = 0\n\t\tbmp_header.ClrImportant = 0\n\t\t//bitmap info\n\t\tvar bmpinfo wingui.BITMAPINFO\n\t\tbmpinfo.Colors[0].Blue = 0\n\t\tbmpinfo.Colors[0].Green = 0\n\t\tbmpinfo.Colors[0].Red = 0\n\t\tbmpinfo.Colors[0].Reserved = 0\n\t\tbmpinfo.Header = bmp_header\n\t\twndBufferHeader = wingui.CreateDIBSection(hdc, &bmpinfo, wingui.DIB_RGB_COLORS, uintptr(unsafe.Pointer(&ppvBits)), 0, 0)\n\t\twingui.GetObject(wndBufferHeader, unsafe.Sizeof(wndBufferHeader), uintptr(unsafe.Pointer(&wndBuffer)))\n\t\thdcWndBuffer = wingui.CreateCompatibleDC(hdc)\n\t\twingui.SelectObject(hdcWndBuffer, wndBufferHeader)\n\n\t\tpixel := (*[600 * 800 * 4]uint8)(unsafe.Pointer(ppvBits))\n\t\tpixelSlice := pixel[:]\n\t\tbackBuffer = &image.RGBA{pixelSlice, 4*600, image.Rect(0, 0, 600, 800)}\n\t\tfmt.Println(\"Create windows\")\n\t\trc = wingui.DefWindowProc(hwnd, msg, wparam, lparam)\n\tcase wingui.WM_COMMAND:\n\t\tswitch syscall.Handle(lparam) {\n\t\tdefault:\n\t\t\trc = wingui.DefWindowProc(hwnd, msg, wparam, lparam)\n\t\t}\n\tcase wingui.WM_PAINT:\n\t\tvar ps wingui.PAINTSTRUCT\n\t\thdc := wingui.BeginPaint(hwnd, &ps)\n\t\tt := time.Now()\n\t\tgc := draw2d.NewGraphicContext(backBuffer)\n\t\t/*gc.SetFillColor(color.RGBA{0xFF, 0xFF, 0xFF, 0xFF})\n\t\tgc.Clear()*/\n\t\tfor i := 0; i < len(backBuffer.Pix); i+=1 {\n\t\t\tbackBuffer.Pix[i] = 0xff\n\t\t}\n\t\tgc.Save()\n\t\t//gc.Translate(0, -380)\n\t\tDrawTiger(gc)\n\t\tgc.Restore()\n\t\t// back buf in\n\t\tvar tmp uint8\n\t\tfor i := 0; i < len(backBuffer.Pix); i+=4 {\n\t\t\ttmp = backBuffer.Pix[i]\n\t\t\tbackBuffer.Pix[i] = backBuffer.Pix[i+2]\n\t\t\tbackBuffer.Pix[i+2] = tmp\n\t\t}\n\t\twingui.BitBlt(hdc, 0, 0, int(wndBuffer.Width), int(wndBuffer.Height), hdcWndBuffer, 0, 0, wingui.SRCCOPY)\n\t\twingui.EndPaint(hwnd, &ps)\n\t\trc = wingui.DefWindowProc(hwnd, msg, wparam, lparam)\n\t\tdt := time.Now().Sub(t)\n\t\tfmt.Printf(\"Redraw in : %f ms\\n\", float64(dt)*1e-6)\n\tcase wingui.WM_CLOSE:\n\t\twingui.DestroyWindow(hwnd)\n\tcase wingui.WM_DESTROY:\n\t\twingui.PostQuitMessage(0)\n\tdefault:\n\t\trc = wingui.DefWindowProc(hwnd, msg, wparam, lparam)\n\t}\n\treturn\n}",
"func NewDirectByteBuffer(env *C.JNIEnv, address unsafe.Pointer, capacity C.jlong) C.jobject {\n\treturn C._GoJniNewDirectByteBuffer(env, address, capacity)\n}",
"func (p *PdfiumImplementation) FPDFBitmap_Destroy(request *requests.FPDFBitmap_Destroy) (*responses.FPDFBitmap_Destroy, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tC.FPDFBitmap_Destroy(bitmapHandle.handle)\n\n\tdelete(p.bitmapRefs, bitmapHandle.nativeRef)\n\n\treturn &responses.FPDFBitmap_Destroy{}, nil\n}",
"func NewFzBuffer() *FzBuffer {\n\treturn (*FzBuffer)(allocFzBufferMemory(1))\n}",
"func CreateBuffer() Buffer {\n\tvar b Buffer\n\tgl.GenBuffers(1, &b.Value)\n\treturn b\n}",
"func (x *FzBitmap) Ref() *C.fz_bitmap {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.fz_bitmap)(unsafe.Pointer(x))\n}",
"func (f *DynamicDiskBlockFactory) GetBitmapFactory() *bitmap.Factory {\n\treturn f.bitmapFactory\n}",
"func allocFzBandWriterMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzBandWriterValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func CreateBufferRegionARB(hDC unsafe.Pointer, iLayerPlane unsafe.Pointer, uType unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpCreateBufferRegionARB, 3, uintptr(hDC), uintptr(iLayerPlane), uintptr(uType))\n\treturn (unsafe.Pointer)(ret)\n}",
"func NewFzPixmapRef(ref unsafe.Pointer) *FzPixmap {\n\tif ref == nil {\n\t\treturn nil\n\t}\n\tobj := new(FzPixmap)\n\tobj.ref7c1a1ba1 = (*C.fz_pixmap)(unsafe.Pointer(ref))\n\treturn obj\n}",
"func (s *ShmPool) CreateBuffer(id *Buffer, offset int32, width int32, height int32, stride int32, format uint32) {\n sendrequest(s, \"wl_shm_pool_create_buffer\", id, offset, width, height, stride, format)\n}",
"func NewBMP280(dev *i2c.Dev) (*BMP, error) {\n\tbmp := &BMP{\n\t\tdevice: dev,\n\t\ttempCalibration: make([]calibrationData, 3),\n\t\tpressCalibration: make([]calibrationData, 9),\n\t\tlastTemperatureMeasurement: math.NaN(),\n\t}\n\n\terr := bmp.Init()\n\treturn bmp, err\n}",
"func allocFzBufferMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzBufferValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (obj *Device) CreateRenderTarget(\n\twidth uint,\n\theight uint,\n\tformat FORMAT,\n\tmultiSample MULTISAMPLE_TYPE,\n\tmultisampleQuality uint32,\n\tlockable bool,\n\tsharedHandle uintptr,\n) (*Surface, Error) {\n\tvar surface *Surface\n\tret, _, _ := syscall.Syscall9(\n\t\tobj.vtbl.CreateRenderTarget,\n\t\t9,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(width),\n\t\tuintptr(height),\n\t\tuintptr(format),\n\t\tuintptr(multiSample),\n\t\tuintptr(multisampleQuality),\n\t\tuintptrBool(lockable),\n\t\tuintptr(unsafe.Pointer(&surface)),\n\t\tsharedHandle,\n\t)\n\treturn surface, toErr(ret)\n}",
"func allocFzPixmapMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzPixmapValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func NewImageBuf() *ImageBuf {\n\tbuf := C.ImageBuf_New()\n\treturn newImageBuf(buf)\n}",
"func newBitmap(size int) *bitmap {\n\tdiv, mod := size/8, size%8\n\tif mod > 0 {\n\t\tdiv++\n\t}\n\treturn &bitmap{size, make([]byte, div)}\n}",
"func CreateFramebuffer() Framebuffer {\n\tvar b Framebuffer\n\tgl.GenFramebuffers(1, &b.Value)\n\treturn b\n}",
"func allocFzPixmapImageMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzPixmapImageValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func NewBuffer() Buffer {\n\treturn Buffer{\n\t\tCellMap: make(map[image.Point]Cell),\n\t\tArea: image.Rectangle{}}\n}",
"func InitWithProcAddrFunc(getProcAddr func(name string) unsafe.Pointer) error {\n\tgpChoosePixelFormat = (C.GPCHOOSEPIXELFORMAT)(getProcAddr(\"ChoosePixelFormat\"))\n\tif gpChoosePixelFormat == nil {\n\t\treturn errors.New(\"ChoosePixelFormat\")\n\t}\n\tgpDescribePixelFormat = (C.GPDESCRIBEPIXELFORMAT)(getProcAddr(\"DescribePixelFormat\"))\n\tif gpDescribePixelFormat == nil {\n\t\treturn errors.New(\"DescribePixelFormat\")\n\t}\n\tgpGetEnhMetaFilePixelFormat = (C.GPGETENHMETAFILEPIXELFORMAT)(getProcAddr(\"GetEnhMetaFilePixelFormat\"))\n\tif gpGetEnhMetaFilePixelFormat == nil {\n\t\treturn errors.New(\"GetEnhMetaFilePixelFormat\")\n\t}\n\tgpGetPixelFormat = (C.GPGETPIXELFORMAT)(getProcAddr(\"GetPixelFormat\"))\n\tif gpGetPixelFormat == nil {\n\t\treturn errors.New(\"GetPixelFormat\")\n\t}\n\tgpSetPixelFormat = (C.GPSETPIXELFORMAT)(getProcAddr(\"SetPixelFormat\"))\n\tif gpSetPixelFormat == nil {\n\t\treturn errors.New(\"SetPixelFormat\")\n\t}\n\tgpSwapBuffers = (C.GPSWAPBUFFERS)(getProcAddr(\"SwapBuffers\"))\n\tif gpSwapBuffers == nil {\n\t\treturn errors.New(\"SwapBuffers\")\n\t}\n\tgpAllocateMemoryNV = (C.GPALLOCATEMEMORYNV)(getProcAddr(\"wglAllocateMemoryNV\"))\n\tgpAssociateImageBufferEventsI3D = (C.GPASSOCIATEIMAGEBUFFEREVENTSI3D)(getProcAddr(\"wglAssociateImageBufferEventsI3D\"))\n\tgpBeginFrameTrackingI3D = (C.GPBEGINFRAMETRACKINGI3D)(getProcAddr(\"wglBeginFrameTrackingI3D\"))\n\tgpBindDisplayColorTableEXT = (C.GPBINDDISPLAYCOLORTABLEEXT)(getProcAddr(\"wglBindDisplayColorTableEXT\"))\n\tgpBindSwapBarrierNV = (C.GPBINDSWAPBARRIERNV)(getProcAddr(\"wglBindSwapBarrierNV\"))\n\tgpBindTexImageARB = (C.GPBINDTEXIMAGEARB)(getProcAddr(\"wglBindTexImageARB\"))\n\tgpBindVideoCaptureDeviceNV = (C.GPBINDVIDEOCAPTUREDEVICENV)(getProcAddr(\"wglBindVideoCaptureDeviceNV\"))\n\tgpBindVideoDeviceNV = (C.GPBINDVIDEODEVICENV)(getProcAddr(\"wglBindVideoDeviceNV\"))\n\tgpBindVideoImageNV = (C.GPBINDVIDEOIMAGENV)(getProcAddr(\"wglBindVideoImageNV\"))\n\tgpBlitContextFramebufferAMD = (C.GPBLITCONTEXTFRAMEBUFFERAMD)(getProcAddr(\"wglBlitContextFramebufferAMD\"))\n\tgpChoosePixelFormatARB = (C.GPCHOOSEPIXELFORMATARB)(getProcAddr(\"wglChoosePixelFormatARB\"))\n\tgpChoosePixelFormatEXT = (C.GPCHOOSEPIXELFORMATEXT)(getProcAddr(\"wglChoosePixelFormatEXT\"))\n\tgpCopyContext = (C.GPCOPYCONTEXT)(getProcAddr(\"wglCopyContext\"))\n\tif gpCopyContext == nil {\n\t\treturn errors.New(\"wglCopyContext\")\n\t}\n\tgpCopyImageSubDataNV = (C.GPCOPYIMAGESUBDATANV)(getProcAddr(\"wglCopyImageSubDataNV\"))\n\tgpCreateAffinityDCNV = (C.GPCREATEAFFINITYDCNV)(getProcAddr(\"wglCreateAffinityDCNV\"))\n\tgpCreateAssociatedContextAMD = (C.GPCREATEASSOCIATEDCONTEXTAMD)(getProcAddr(\"wglCreateAssociatedContextAMD\"))\n\tgpCreateAssociatedContextAttribsAMD = (C.GPCREATEASSOCIATEDCONTEXTATTRIBSAMD)(getProcAddr(\"wglCreateAssociatedContextAttribsAMD\"))\n\tgpCreateBufferRegionARB = (C.GPCREATEBUFFERREGIONARB)(getProcAddr(\"wglCreateBufferRegionARB\"))\n\tgpCreateContext = (C.GPCREATECONTEXT)(getProcAddr(\"wglCreateContext\"))\n\tif gpCreateContext == nil {\n\t\treturn errors.New(\"wglCreateContext\")\n\t}\n\tgpCreateContextAttribsARB = (C.GPCREATECONTEXTATTRIBSARB)(getProcAddr(\"wglCreateContextAttribsARB\"))\n\tgpCreateDisplayColorTableEXT = (C.GPCREATEDISPLAYCOLORTABLEEXT)(getProcAddr(\"wglCreateDisplayColorTableEXT\"))\n\tgpCreateImageBufferI3D = (C.GPCREATEIMAGEBUFFERI3D)(getProcAddr(\"wglCreateImageBufferI3D\"))\n\tgpCreateLayerContext = (C.GPCREATELAYERCONTEXT)(getProcAddr(\"wglCreateLayerContext\"))\n\tif gpCreateLayerContext == nil {\n\t\treturn errors.New(\"wglCreateLayerContext\")\n\t}\n\tgpCreatePbufferARB = (C.GPCREATEPBUFFERARB)(getProcAddr(\"wglCreatePbufferARB\"))\n\tgpCreatePbufferEXT = (C.GPCREATEPBUFFEREXT)(getProcAddr(\"wglCreatePbufferEXT\"))\n\tgpDXCloseDeviceNV = (C.GPDXCLOSEDEVICENV)(getProcAddr(\"wglDXCloseDeviceNV\"))\n\tgpDXLockObjectsNV = (C.GPDXLOCKOBJECTSNV)(getProcAddr(\"wglDXLockObjectsNV\"))\n\tgpDXObjectAccessNV = (C.GPDXOBJECTACCESSNV)(getProcAddr(\"wglDXObjectAccessNV\"))\n\tgpDXOpenDeviceNV = (C.GPDXOPENDEVICENV)(getProcAddr(\"wglDXOpenDeviceNV\"))\n\tgpDXRegisterObjectNV = (C.GPDXREGISTEROBJECTNV)(getProcAddr(\"wglDXRegisterObjectNV\"))\n\tgpDXSetResourceShareHandleNV = (C.GPDXSETRESOURCESHAREHANDLENV)(getProcAddr(\"wglDXSetResourceShareHandleNV\"))\n\tgpDXUnlockObjectsNV = (C.GPDXUNLOCKOBJECTSNV)(getProcAddr(\"wglDXUnlockObjectsNV\"))\n\tgpDXUnregisterObjectNV = (C.GPDXUNREGISTEROBJECTNV)(getProcAddr(\"wglDXUnregisterObjectNV\"))\n\tgpDelayBeforeSwapNV = (C.GPDELAYBEFORESWAPNV)(getProcAddr(\"wglDelayBeforeSwapNV\"))\n\tgpDeleteAssociatedContextAMD = (C.GPDELETEASSOCIATEDCONTEXTAMD)(getProcAddr(\"wglDeleteAssociatedContextAMD\"))\n\tgpDeleteBufferRegionARB = (C.GPDELETEBUFFERREGIONARB)(getProcAddr(\"wglDeleteBufferRegionARB\"))\n\tgpDeleteContext = (C.GPDELETECONTEXT)(getProcAddr(\"wglDeleteContext\"))\n\tif gpDeleteContext == nil {\n\t\treturn errors.New(\"wglDeleteContext\")\n\t}\n\tgpDeleteDCNV = (C.GPDELETEDCNV)(getProcAddr(\"wglDeleteDCNV\"))\n\tgpDescribeLayerPlane = (C.GPDESCRIBELAYERPLANE)(getProcAddr(\"wglDescribeLayerPlane\"))\n\tif gpDescribeLayerPlane == nil {\n\t\treturn errors.New(\"wglDescribeLayerPlane\")\n\t}\n\tgpDestroyDisplayColorTableEXT = (C.GPDESTROYDISPLAYCOLORTABLEEXT)(getProcAddr(\"wglDestroyDisplayColorTableEXT\"))\n\tgpDestroyImageBufferI3D = (C.GPDESTROYIMAGEBUFFERI3D)(getProcAddr(\"wglDestroyImageBufferI3D\"))\n\tgpDestroyPbufferARB = (C.GPDESTROYPBUFFERARB)(getProcAddr(\"wglDestroyPbufferARB\"))\n\tgpDestroyPbufferEXT = (C.GPDESTROYPBUFFEREXT)(getProcAddr(\"wglDestroyPbufferEXT\"))\n\tgpDisableFrameLockI3D = (C.GPDISABLEFRAMELOCKI3D)(getProcAddr(\"wglDisableFrameLockI3D\"))\n\tgpDisableGenlockI3D = (C.GPDISABLEGENLOCKI3D)(getProcAddr(\"wglDisableGenlockI3D\"))\n\tgpEnableFrameLockI3D = (C.GPENABLEFRAMELOCKI3D)(getProcAddr(\"wglEnableFrameLockI3D\"))\n\tgpEnableGenlockI3D = (C.GPENABLEGENLOCKI3D)(getProcAddr(\"wglEnableGenlockI3D\"))\n\tgpEndFrameTrackingI3D = (C.GPENDFRAMETRACKINGI3D)(getProcAddr(\"wglEndFrameTrackingI3D\"))\n\tgpEnumGpuDevicesNV = (C.GPENUMGPUDEVICESNV)(getProcAddr(\"wglEnumGpuDevicesNV\"))\n\tgpEnumGpusFromAffinityDCNV = (C.GPENUMGPUSFROMAFFINITYDCNV)(getProcAddr(\"wglEnumGpusFromAffinityDCNV\"))\n\tgpEnumGpusNV = (C.GPENUMGPUSNV)(getProcAddr(\"wglEnumGpusNV\"))\n\tgpEnumerateVideoCaptureDevicesNV = (C.GPENUMERATEVIDEOCAPTUREDEVICESNV)(getProcAddr(\"wglEnumerateVideoCaptureDevicesNV\"))\n\tgpEnumerateVideoDevicesNV = (C.GPENUMERATEVIDEODEVICESNV)(getProcAddr(\"wglEnumerateVideoDevicesNV\"))\n\tgpFreeMemoryNV = (C.GPFREEMEMORYNV)(getProcAddr(\"wglFreeMemoryNV\"))\n\tgpGenlockSampleRateI3D = (C.GPGENLOCKSAMPLERATEI3D)(getProcAddr(\"wglGenlockSampleRateI3D\"))\n\tgpGenlockSourceDelayI3D = (C.GPGENLOCKSOURCEDELAYI3D)(getProcAddr(\"wglGenlockSourceDelayI3D\"))\n\tgpGenlockSourceEdgeI3D = (C.GPGENLOCKSOURCEEDGEI3D)(getProcAddr(\"wglGenlockSourceEdgeI3D\"))\n\tgpGenlockSourceI3D = (C.GPGENLOCKSOURCEI3D)(getProcAddr(\"wglGenlockSourceI3D\"))\n\tgpGetContextGPUIDAMD = (C.GPGETCONTEXTGPUIDAMD)(getProcAddr(\"wglGetContextGPUIDAMD\"))\n\tgpGetCurrentAssociatedContextAMD = (C.GPGETCURRENTASSOCIATEDCONTEXTAMD)(getProcAddr(\"wglGetCurrentAssociatedContextAMD\"))\n\tgpGetCurrentContext = (C.GPGETCURRENTCONTEXT)(getProcAddr(\"wglGetCurrentContext\"))\n\tif gpGetCurrentContext == nil {\n\t\treturn errors.New(\"wglGetCurrentContext\")\n\t}\n\tgpGetCurrentDC = (C.GPGETCURRENTDC)(getProcAddr(\"wglGetCurrentDC\"))\n\tif gpGetCurrentDC == nil {\n\t\treturn errors.New(\"wglGetCurrentDC\")\n\t}\n\tgpGetCurrentReadDCARB = (C.GPGETCURRENTREADDCARB)(getProcAddr(\"wglGetCurrentReadDCARB\"))\n\tgpGetCurrentReadDCEXT = (C.GPGETCURRENTREADDCEXT)(getProcAddr(\"wglGetCurrentReadDCEXT\"))\n\tgpGetDigitalVideoParametersI3D = (C.GPGETDIGITALVIDEOPARAMETERSI3D)(getProcAddr(\"wglGetDigitalVideoParametersI3D\"))\n\tgpGetExtensionsStringARB = (C.GPGETEXTENSIONSSTRINGARB)(getProcAddr(\"wglGetExtensionsStringARB\"))\n\tgpGetExtensionsStringEXT = (C.GPGETEXTENSIONSSTRINGEXT)(getProcAddr(\"wglGetExtensionsStringEXT\"))\n\tgpGetFrameUsageI3D = (C.GPGETFRAMEUSAGEI3D)(getProcAddr(\"wglGetFrameUsageI3D\"))\n\tgpGetGPUIDsAMD = (C.GPGETGPUIDSAMD)(getProcAddr(\"wglGetGPUIDsAMD\"))\n\tgpGetGPUInfoAMD = (C.GPGETGPUINFOAMD)(getProcAddr(\"wglGetGPUInfoAMD\"))\n\tgpGetGammaTableI3D = (C.GPGETGAMMATABLEI3D)(getProcAddr(\"wglGetGammaTableI3D\"))\n\tgpGetGammaTableParametersI3D = (C.GPGETGAMMATABLEPARAMETERSI3D)(getProcAddr(\"wglGetGammaTableParametersI3D\"))\n\tgpGetGenlockSampleRateI3D = (C.GPGETGENLOCKSAMPLERATEI3D)(getProcAddr(\"wglGetGenlockSampleRateI3D\"))\n\tgpGetGenlockSourceDelayI3D = (C.GPGETGENLOCKSOURCEDELAYI3D)(getProcAddr(\"wglGetGenlockSourceDelayI3D\"))\n\tgpGetGenlockSourceEdgeI3D = (C.GPGETGENLOCKSOURCEEDGEI3D)(getProcAddr(\"wglGetGenlockSourceEdgeI3D\"))\n\tgpGetGenlockSourceI3D = (C.GPGETGENLOCKSOURCEI3D)(getProcAddr(\"wglGetGenlockSourceI3D\"))\n\tgpGetLayerPaletteEntries = (C.GPGETLAYERPALETTEENTRIES)(getProcAddr(\"wglGetLayerPaletteEntries\"))\n\tif gpGetLayerPaletteEntries == nil {\n\t\treturn errors.New(\"wglGetLayerPaletteEntries\")\n\t}\n\tgpGetMscRateOML = (C.GPGETMSCRATEOML)(getProcAddr(\"wglGetMscRateOML\"))\n\tgpGetPbufferDCARB = (C.GPGETPBUFFERDCARB)(getProcAddr(\"wglGetPbufferDCARB\"))\n\tgpGetPbufferDCEXT = (C.GPGETPBUFFERDCEXT)(getProcAddr(\"wglGetPbufferDCEXT\"))\n\tgpGetPixelFormatAttribfvARB = (C.GPGETPIXELFORMATATTRIBFVARB)(getProcAddr(\"wglGetPixelFormatAttribfvARB\"))\n\tgpGetPixelFormatAttribfvEXT = (C.GPGETPIXELFORMATATTRIBFVEXT)(getProcAddr(\"wglGetPixelFormatAttribfvEXT\"))\n\tgpGetPixelFormatAttribivARB = (C.GPGETPIXELFORMATATTRIBIVARB)(getProcAddr(\"wglGetPixelFormatAttribivARB\"))\n\tgpGetPixelFormatAttribivEXT = (C.GPGETPIXELFORMATATTRIBIVEXT)(getProcAddr(\"wglGetPixelFormatAttribivEXT\"))\n\tgpGetProcAddress = (C.GPGETPROCADDRESS)(getProcAddr(\"wglGetProcAddress\"))\n\tif gpGetProcAddress == nil {\n\t\treturn errors.New(\"wglGetProcAddress\")\n\t}\n\tgpGetSwapIntervalEXT = (C.GPGETSWAPINTERVALEXT)(getProcAddr(\"wglGetSwapIntervalEXT\"))\n\tgpGetSyncValuesOML = (C.GPGETSYNCVALUESOML)(getProcAddr(\"wglGetSyncValuesOML\"))\n\tgpGetVideoDeviceNV = (C.GPGETVIDEODEVICENV)(getProcAddr(\"wglGetVideoDeviceNV\"))\n\tgpGetVideoInfoNV = (C.GPGETVIDEOINFONV)(getProcAddr(\"wglGetVideoInfoNV\"))\n\tgpIsEnabledFrameLockI3D = (C.GPISENABLEDFRAMELOCKI3D)(getProcAddr(\"wglIsEnabledFrameLockI3D\"))\n\tgpIsEnabledGenlockI3D = (C.GPISENABLEDGENLOCKI3D)(getProcAddr(\"wglIsEnabledGenlockI3D\"))\n\tgpJoinSwapGroupNV = (C.GPJOINSWAPGROUPNV)(getProcAddr(\"wglJoinSwapGroupNV\"))\n\tgpLoadDisplayColorTableEXT = (C.GPLOADDISPLAYCOLORTABLEEXT)(getProcAddr(\"wglLoadDisplayColorTableEXT\"))\n\tgpLockVideoCaptureDeviceNV = (C.GPLOCKVIDEOCAPTUREDEVICENV)(getProcAddr(\"wglLockVideoCaptureDeviceNV\"))\n\tgpMakeAssociatedContextCurrentAMD = (C.GPMAKEASSOCIATEDCONTEXTCURRENTAMD)(getProcAddr(\"wglMakeAssociatedContextCurrentAMD\"))\n\tgpMakeContextCurrentARB = (C.GPMAKECONTEXTCURRENTARB)(getProcAddr(\"wglMakeContextCurrentARB\"))\n\tgpMakeContextCurrentEXT = (C.GPMAKECONTEXTCURRENTEXT)(getProcAddr(\"wglMakeContextCurrentEXT\"))\n\tgpMakeCurrent = (C.GPMAKECURRENT)(getProcAddr(\"wglMakeCurrent\"))\n\tif gpMakeCurrent == nil {\n\t\treturn errors.New(\"wglMakeCurrent\")\n\t}\n\tgpQueryCurrentContextNV = (C.GPQUERYCURRENTCONTEXTNV)(getProcAddr(\"wglQueryCurrentContextNV\"))\n\tgpQueryFrameCountNV = (C.GPQUERYFRAMECOUNTNV)(getProcAddr(\"wglQueryFrameCountNV\"))\n\tgpQueryFrameLockMasterI3D = (C.GPQUERYFRAMELOCKMASTERI3D)(getProcAddr(\"wglQueryFrameLockMasterI3D\"))\n\tgpQueryFrameTrackingI3D = (C.GPQUERYFRAMETRACKINGI3D)(getProcAddr(\"wglQueryFrameTrackingI3D\"))\n\tgpQueryGenlockMaxSourceDelayI3D = (C.GPQUERYGENLOCKMAXSOURCEDELAYI3D)(getProcAddr(\"wglQueryGenlockMaxSourceDelayI3D\"))\n\tgpQueryMaxSwapGroupsNV = (C.GPQUERYMAXSWAPGROUPSNV)(getProcAddr(\"wglQueryMaxSwapGroupsNV\"))\n\tgpQueryPbufferARB = (C.GPQUERYPBUFFERARB)(getProcAddr(\"wglQueryPbufferARB\"))\n\tgpQueryPbufferEXT = (C.GPQUERYPBUFFEREXT)(getProcAddr(\"wglQueryPbufferEXT\"))\n\tgpQuerySwapGroupNV = (C.GPQUERYSWAPGROUPNV)(getProcAddr(\"wglQuerySwapGroupNV\"))\n\tgpQueryVideoCaptureDeviceNV = (C.GPQUERYVIDEOCAPTUREDEVICENV)(getProcAddr(\"wglQueryVideoCaptureDeviceNV\"))\n\tgpRealizeLayerPalette = (C.GPREALIZELAYERPALETTE)(getProcAddr(\"wglRealizeLayerPalette\"))\n\tif gpRealizeLayerPalette == nil {\n\t\treturn errors.New(\"wglRealizeLayerPalette\")\n\t}\n\tgpReleaseImageBufferEventsI3D = (C.GPRELEASEIMAGEBUFFEREVENTSI3D)(getProcAddr(\"wglReleaseImageBufferEventsI3D\"))\n\tgpReleasePbufferDCARB = (C.GPRELEASEPBUFFERDCARB)(getProcAddr(\"wglReleasePbufferDCARB\"))\n\tgpReleasePbufferDCEXT = (C.GPRELEASEPBUFFERDCEXT)(getProcAddr(\"wglReleasePbufferDCEXT\"))\n\tgpReleaseTexImageARB = (C.GPRELEASETEXIMAGEARB)(getProcAddr(\"wglReleaseTexImageARB\"))\n\tgpReleaseVideoCaptureDeviceNV = (C.GPRELEASEVIDEOCAPTUREDEVICENV)(getProcAddr(\"wglReleaseVideoCaptureDeviceNV\"))\n\tgpReleaseVideoDeviceNV = (C.GPRELEASEVIDEODEVICENV)(getProcAddr(\"wglReleaseVideoDeviceNV\"))\n\tgpReleaseVideoImageNV = (C.GPRELEASEVIDEOIMAGENV)(getProcAddr(\"wglReleaseVideoImageNV\"))\n\tgpResetFrameCountNV = (C.GPRESETFRAMECOUNTNV)(getProcAddr(\"wglResetFrameCountNV\"))\n\tgpRestoreBufferRegionARB = (C.GPRESTOREBUFFERREGIONARB)(getProcAddr(\"wglRestoreBufferRegionARB\"))\n\tgpSaveBufferRegionARB = (C.GPSAVEBUFFERREGIONARB)(getProcAddr(\"wglSaveBufferRegionARB\"))\n\tgpSendPbufferToVideoNV = (C.GPSENDPBUFFERTOVIDEONV)(getProcAddr(\"wglSendPbufferToVideoNV\"))\n\tgpSetDigitalVideoParametersI3D = (C.GPSETDIGITALVIDEOPARAMETERSI3D)(getProcAddr(\"wglSetDigitalVideoParametersI3D\"))\n\tgpSetGammaTableI3D = (C.GPSETGAMMATABLEI3D)(getProcAddr(\"wglSetGammaTableI3D\"))\n\tgpSetGammaTableParametersI3D = (C.GPSETGAMMATABLEPARAMETERSI3D)(getProcAddr(\"wglSetGammaTableParametersI3D\"))\n\tgpSetLayerPaletteEntries = (C.GPSETLAYERPALETTEENTRIES)(getProcAddr(\"wglSetLayerPaletteEntries\"))\n\tif gpSetLayerPaletteEntries == nil {\n\t\treturn errors.New(\"wglSetLayerPaletteEntries\")\n\t}\n\tgpSetPbufferAttribARB = (C.GPSETPBUFFERATTRIBARB)(getProcAddr(\"wglSetPbufferAttribARB\"))\n\tgpSetStereoEmitterState3DL = (C.GPSETSTEREOEMITTERSTATE3DL)(getProcAddr(\"wglSetStereoEmitterState3DL\"))\n\tgpShareLists = (C.GPSHARELISTS)(getProcAddr(\"wglShareLists\"))\n\tif gpShareLists == nil {\n\t\treturn errors.New(\"wglShareLists\")\n\t}\n\tgpSwapBuffersMscOML = (C.GPSWAPBUFFERSMSCOML)(getProcAddr(\"wglSwapBuffersMscOML\"))\n\tgpSwapIntervalEXT = (C.GPSWAPINTERVALEXT)(getProcAddr(\"wglSwapIntervalEXT\"))\n\tgpSwapLayerBuffers = (C.GPSWAPLAYERBUFFERS)(getProcAddr(\"wglSwapLayerBuffers\"))\n\tif gpSwapLayerBuffers == nil {\n\t\treturn errors.New(\"wglSwapLayerBuffers\")\n\t}\n\tgpSwapLayerBuffersMscOML = (C.GPSWAPLAYERBUFFERSMSCOML)(getProcAddr(\"wglSwapLayerBuffersMscOML\"))\n\tgpUseFontBitmaps = (C.GPUSEFONTBITMAPS)(getProcAddr(\"wglUseFontBitmaps\"))\n\tif gpUseFontBitmaps == nil {\n\t\treturn errors.New(\"wglUseFontBitmaps\")\n\t}\n\tgpUseFontBitmapsA = (C.GPUSEFONTBITMAPSA)(getProcAddr(\"wglUseFontBitmapsA\"))\n\tif gpUseFontBitmapsA == nil {\n\t\treturn errors.New(\"wglUseFontBitmapsA\")\n\t}\n\tgpUseFontBitmapsW = (C.GPUSEFONTBITMAPSW)(getProcAddr(\"wglUseFontBitmapsW\"))\n\tif gpUseFontBitmapsW == nil {\n\t\treturn errors.New(\"wglUseFontBitmapsW\")\n\t}\n\tgpUseFontOutlines = (C.GPUSEFONTOUTLINES)(getProcAddr(\"wglUseFontOutlines\"))\n\tif gpUseFontOutlines == nil {\n\t\treturn errors.New(\"wglUseFontOutlines\")\n\t}\n\tgpUseFontOutlinesA = (C.GPUSEFONTOUTLINESA)(getProcAddr(\"wglUseFontOutlinesA\"))\n\tif gpUseFontOutlinesA == nil {\n\t\treturn errors.New(\"wglUseFontOutlinesA\")\n\t}\n\tgpUseFontOutlinesW = (C.GPUSEFONTOUTLINESW)(getProcAddr(\"wglUseFontOutlinesW\"))\n\tif gpUseFontOutlinesW == nil {\n\t\treturn errors.New(\"wglUseFontOutlinesW\")\n\t}\n\tgpWaitForMscOML = (C.GPWAITFORMSCOML)(getProcAddr(\"wglWaitForMscOML\"))\n\tgpWaitForSbcOML = (C.GPWAITFORSBCOML)(getProcAddr(\"wglWaitForSbcOML\"))\n\treturn nil\n}",
"func allocFzColorConverterMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzColorConverterValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (x *FzPixmap) Deref() {\n\tif x.ref7c1a1ba1 == nil {\n\t\treturn\n\t}\n\tx.Storable = *(*FzStorable)(unsafe.Pointer(&x.ref7c1a1ba1.storable))\n\tx.X = (int32)(x.ref7c1a1ba1.x)\n\tx.Y = (int32)(x.ref7c1a1ba1.y)\n\tx.W = (int32)(x.ref7c1a1ba1.w)\n\tx.H = (int32)(x.ref7c1a1ba1.h)\n\tx.N = (byte)(x.ref7c1a1ba1.n)\n\tx.S = (byte)(x.ref7c1a1ba1.s)\n\tx.Alpha = (byte)(x.ref7c1a1ba1.alpha)\n\tx.Flags = (byte)(x.ref7c1a1ba1.flags)\n\tx.Stride = (int32)(x.ref7c1a1ba1.stride)\n\tx.Seps = (*FzSeparations)(unsafe.Pointer(x.ref7c1a1ba1.seps))\n\tx.Xres = (int32)(x.ref7c1a1ba1.xres)\n\tx.Yres = (int32)(x.ref7c1a1ba1.yres)\n\tx.Colorspace = (*FzColorspace)(unsafe.Pointer(x.ref7c1a1ba1.colorspace))\n\thxff73280 := (*sliceHeader)(unsafe.Pointer(&x.Samples))\n\thxff73280.Data = uintptr(unsafe.Pointer(x.ref7c1a1ba1.samples))\n\thxff73280.Cap = 0x7fffffff\n\t// hxff73280.Len = ?\n\n}",
"func (obj *Device) CreateIndexBuffer(\n\tlength uint,\n\tusage uint32,\n\tformat FORMAT,\n\tpool POOL,\n\tsharedHandle uintptr,\n) (*IndexBuffer, Error) {\n\tvar buf *IndexBuffer\n\tret, _, _ := syscall.Syscall9(\n\t\tobj.vtbl.CreateIndexBuffer,\n\t\t7,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(length),\n\t\tuintptr(usage),\n\t\tuintptr(format),\n\t\tuintptr(pool),\n\t\tuintptr(unsafe.Pointer(&buf)),\n\t\tsharedHandle,\n\t\t0,\n\t\t0,\n\t)\n\treturn buf, toErr(ret)\n}",
"func NewBuffer(inp []byte) *ByteBuffer {\n\tif inp == nil {\n\t\tinp = make([]byte, 0, 512)\n\t}\n\treturn &ByteBuffer{Buffer: bytes.NewBuffer(inp)}\n}",
"func allocFzImageMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzImageValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func NewFramebuffer(w, h int) *Framebuffer {\n\treturn &Framebuffer{\n\t\tfb: image.NewRGBA(image.Rectangle{image.Point{0, 0}, image.Point{w, h}}),\n\t}\n}",
"func (x *FzBitmap) PassRef() *C.fz_bitmap {\n\tif x == nil {\n\t\tx = (*FzBitmap)(allocFzBitmapMemory(1))\n\t}\n\treturn (*C.fz_bitmap)(unsafe.Pointer(x))\n}",
"func (x *FzBitmap) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (b *Bitmap) Buffer() []byte {\n\tl := b.Rows() * b.Pitch()\n\treturn C.GoBytes(unsafe.Pointer(b.handle.buffer), C.int(l))\n}",
"func allocPFzBufferMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPFzBufferValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func NewFzImageRef(ref unsafe.Pointer) *FzImage {\n\treturn (*FzImage)(ref)\n}",
"func NewFilledBuffer(x0, y0, x1, y1 int, ch rune, fg, bg Attribute) Buffer {\n\tbuf := NewBuffer()\n\tbuf.Area.Min = image.Pt(x0, y0)\n\tbuf.Area.Max = image.Pt(x1, y1)\n\n\tfor x := buf.Area.Min.X; x < buf.Area.Max.X; x++ {\n\t\tfor y := buf.Area.Min.Y; y < buf.Area.Max.Y; y++ {\n\t\t\tbuf.Set(x, y, Cell{ch, fg, bg})\n\t\t}\n\t}\n\treturn buf\n}",
"func allocFzColorParamsMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzColorParamsValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func qr_decoder_get_image_buffer(p _QrDecoderHandle) *_IplImage {\n\tv := C.qr_decoder_get_image_buffer(C.QrDecoderHandle(p))\n\treturn (*_IplImage)(v)\n}",
"func allocFzDrawOptionsMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzDrawOptionsValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func allocFzGlyphMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzGlyphValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func InitWithProcAddrFunc(getProcAddr func(name string) unsafe.Pointer) error {\n\tgpChoosePixelFormat = uintptr(getProcAddr(\"ChoosePixelFormat\"))\n\tif gpChoosePixelFormat == 0 {\n\t\treturn errors.New(\"ChoosePixelFormat\")\n\t}\n\tgpDescribePixelFormat = uintptr(getProcAddr(\"DescribePixelFormat\"))\n\tif gpDescribePixelFormat == 0 {\n\t\treturn errors.New(\"DescribePixelFormat\")\n\t}\n\tgpGetEnhMetaFilePixelFormat = uintptr(getProcAddr(\"GetEnhMetaFilePixelFormat\"))\n\tif gpGetEnhMetaFilePixelFormat == 0 {\n\t\treturn errors.New(\"GetEnhMetaFilePixelFormat\")\n\t}\n\tgpGetPixelFormat = uintptr(getProcAddr(\"GetPixelFormat\"))\n\tif gpGetPixelFormat == 0 {\n\t\treturn errors.New(\"GetPixelFormat\")\n\t}\n\tgpSetPixelFormat = uintptr(getProcAddr(\"SetPixelFormat\"))\n\tif gpSetPixelFormat == 0 {\n\t\treturn errors.New(\"SetPixelFormat\")\n\t}\n\tgpSwapBuffers = uintptr(getProcAddr(\"SwapBuffers\"))\n\tif gpSwapBuffers == 0 {\n\t\treturn errors.New(\"SwapBuffers\")\n\t}\n\tgpAllocateMemoryNV = uintptr(getProcAddr(\"wglAllocateMemoryNV\"))\n\tgpAssociateImageBufferEventsI3D = uintptr(getProcAddr(\"wglAssociateImageBufferEventsI3D\"))\n\tgpBeginFrameTrackingI3D = uintptr(getProcAddr(\"wglBeginFrameTrackingI3D\"))\n\tgpBindDisplayColorTableEXT = uintptr(getProcAddr(\"wglBindDisplayColorTableEXT\"))\n\tgpBindSwapBarrierNV = uintptr(getProcAddr(\"wglBindSwapBarrierNV\"))\n\tgpBindTexImageARB = uintptr(getProcAddr(\"wglBindTexImageARB\"))\n\tgpBindVideoCaptureDeviceNV = uintptr(getProcAddr(\"wglBindVideoCaptureDeviceNV\"))\n\tgpBindVideoDeviceNV = uintptr(getProcAddr(\"wglBindVideoDeviceNV\"))\n\tgpBindVideoImageNV = uintptr(getProcAddr(\"wglBindVideoImageNV\"))\n\tgpBlitContextFramebufferAMD = uintptr(getProcAddr(\"wglBlitContextFramebufferAMD\"))\n\tgpChoosePixelFormatARB = uintptr(getProcAddr(\"wglChoosePixelFormatARB\"))\n\tgpChoosePixelFormatEXT = uintptr(getProcAddr(\"wglChoosePixelFormatEXT\"))\n\tgpCopyContext = uintptr(getProcAddr(\"wglCopyContext\"))\n\tif gpCopyContext == 0 {\n\t\treturn errors.New(\"wglCopyContext\")\n\t}\n\tgpCopyImageSubDataNV = uintptr(getProcAddr(\"wglCopyImageSubDataNV\"))\n\tgpCreateAffinityDCNV = uintptr(getProcAddr(\"wglCreateAffinityDCNV\"))\n\tgpCreateAssociatedContextAMD = uintptr(getProcAddr(\"wglCreateAssociatedContextAMD\"))\n\tgpCreateAssociatedContextAttribsAMD = uintptr(getProcAddr(\"wglCreateAssociatedContextAttribsAMD\"))\n\tgpCreateBufferRegionARB = uintptr(getProcAddr(\"wglCreateBufferRegionARB\"))\n\tgpCreateContext = uintptr(getProcAddr(\"wglCreateContext\"))\n\tif gpCreateContext == 0 {\n\t\treturn errors.New(\"wglCreateContext\")\n\t}\n\tgpCreateContextAttribsARB = uintptr(getProcAddr(\"wglCreateContextAttribsARB\"))\n\tgpCreateDisplayColorTableEXT = uintptr(getProcAddr(\"wglCreateDisplayColorTableEXT\"))\n\tgpCreateImageBufferI3D = uintptr(getProcAddr(\"wglCreateImageBufferI3D\"))\n\tgpCreateLayerContext = uintptr(getProcAddr(\"wglCreateLayerContext\"))\n\tif gpCreateLayerContext == 0 {\n\t\treturn errors.New(\"wglCreateLayerContext\")\n\t}\n\tgpCreatePbufferARB = uintptr(getProcAddr(\"wglCreatePbufferARB\"))\n\tgpCreatePbufferEXT = uintptr(getProcAddr(\"wglCreatePbufferEXT\"))\n\tgpDXCloseDeviceNV = uintptr(getProcAddr(\"wglDXCloseDeviceNV\"))\n\tgpDXLockObjectsNV = uintptr(getProcAddr(\"wglDXLockObjectsNV\"))\n\tgpDXObjectAccessNV = uintptr(getProcAddr(\"wglDXObjectAccessNV\"))\n\tgpDXOpenDeviceNV = uintptr(getProcAddr(\"wglDXOpenDeviceNV\"))\n\tgpDXRegisterObjectNV = uintptr(getProcAddr(\"wglDXRegisterObjectNV\"))\n\tgpDXSetResourceShareHandleNV = uintptr(getProcAddr(\"wglDXSetResourceShareHandleNV\"))\n\tgpDXUnlockObjectsNV = uintptr(getProcAddr(\"wglDXUnlockObjectsNV\"))\n\tgpDXUnregisterObjectNV = uintptr(getProcAddr(\"wglDXUnregisterObjectNV\"))\n\tgpDelayBeforeSwapNV = uintptr(getProcAddr(\"wglDelayBeforeSwapNV\"))\n\tgpDeleteAssociatedContextAMD = uintptr(getProcAddr(\"wglDeleteAssociatedContextAMD\"))\n\tgpDeleteBufferRegionARB = uintptr(getProcAddr(\"wglDeleteBufferRegionARB\"))\n\tgpDeleteContext = uintptr(getProcAddr(\"wglDeleteContext\"))\n\tif gpDeleteContext == 0 {\n\t\treturn errors.New(\"wglDeleteContext\")\n\t}\n\tgpDeleteDCNV = uintptr(getProcAddr(\"wglDeleteDCNV\"))\n\tgpDescribeLayerPlane = uintptr(getProcAddr(\"wglDescribeLayerPlane\"))\n\tif gpDescribeLayerPlane == 0 {\n\t\treturn errors.New(\"wglDescribeLayerPlane\")\n\t}\n\tgpDestroyDisplayColorTableEXT = uintptr(getProcAddr(\"wglDestroyDisplayColorTableEXT\"))\n\tgpDestroyImageBufferI3D = uintptr(getProcAddr(\"wglDestroyImageBufferI3D\"))\n\tgpDestroyPbufferARB = uintptr(getProcAddr(\"wglDestroyPbufferARB\"))\n\tgpDestroyPbufferEXT = uintptr(getProcAddr(\"wglDestroyPbufferEXT\"))\n\tgpDisableFrameLockI3D = uintptr(getProcAddr(\"wglDisableFrameLockI3D\"))\n\tgpDisableGenlockI3D = uintptr(getProcAddr(\"wglDisableGenlockI3D\"))\n\tgpEnableFrameLockI3D = uintptr(getProcAddr(\"wglEnableFrameLockI3D\"))\n\tgpEnableGenlockI3D = uintptr(getProcAddr(\"wglEnableGenlockI3D\"))\n\tgpEndFrameTrackingI3D = uintptr(getProcAddr(\"wglEndFrameTrackingI3D\"))\n\tgpEnumGpuDevicesNV = uintptr(getProcAddr(\"wglEnumGpuDevicesNV\"))\n\tgpEnumGpusFromAffinityDCNV = uintptr(getProcAddr(\"wglEnumGpusFromAffinityDCNV\"))\n\tgpEnumGpusNV = uintptr(getProcAddr(\"wglEnumGpusNV\"))\n\tgpEnumerateVideoCaptureDevicesNV = uintptr(getProcAddr(\"wglEnumerateVideoCaptureDevicesNV\"))\n\tgpEnumerateVideoDevicesNV = uintptr(getProcAddr(\"wglEnumerateVideoDevicesNV\"))\n\tgpFreeMemoryNV = uintptr(getProcAddr(\"wglFreeMemoryNV\"))\n\tgpGenlockSampleRateI3D = uintptr(getProcAddr(\"wglGenlockSampleRateI3D\"))\n\tgpGenlockSourceDelayI3D = uintptr(getProcAddr(\"wglGenlockSourceDelayI3D\"))\n\tgpGenlockSourceEdgeI3D = uintptr(getProcAddr(\"wglGenlockSourceEdgeI3D\"))\n\tgpGenlockSourceI3D = uintptr(getProcAddr(\"wglGenlockSourceI3D\"))\n\tgpGetContextGPUIDAMD = uintptr(getProcAddr(\"wglGetContextGPUIDAMD\"))\n\tgpGetCurrentAssociatedContextAMD = uintptr(getProcAddr(\"wglGetCurrentAssociatedContextAMD\"))\n\tgpGetCurrentContext = uintptr(getProcAddr(\"wglGetCurrentContext\"))\n\tif gpGetCurrentContext == 0 {\n\t\treturn errors.New(\"wglGetCurrentContext\")\n\t}\n\tgpGetCurrentDC = uintptr(getProcAddr(\"wglGetCurrentDC\"))\n\tif gpGetCurrentDC == 0 {\n\t\treturn errors.New(\"wglGetCurrentDC\")\n\t}\n\tgpGetCurrentReadDCARB = uintptr(getProcAddr(\"wglGetCurrentReadDCARB\"))\n\tgpGetCurrentReadDCEXT = uintptr(getProcAddr(\"wglGetCurrentReadDCEXT\"))\n\tgpGetDigitalVideoParametersI3D = uintptr(getProcAddr(\"wglGetDigitalVideoParametersI3D\"))\n\tgpGetExtensionsStringARB = uintptr(getProcAddr(\"wglGetExtensionsStringARB\"))\n\tgpGetExtensionsStringEXT = uintptr(getProcAddr(\"wglGetExtensionsStringEXT\"))\n\tgpGetFrameUsageI3D = uintptr(getProcAddr(\"wglGetFrameUsageI3D\"))\n\tgpGetGPUIDsAMD = uintptr(getProcAddr(\"wglGetGPUIDsAMD\"))\n\tgpGetGPUInfoAMD = uintptr(getProcAddr(\"wglGetGPUInfoAMD\"))\n\tgpGetGammaTableI3D = uintptr(getProcAddr(\"wglGetGammaTableI3D\"))\n\tgpGetGammaTableParametersI3D = uintptr(getProcAddr(\"wglGetGammaTableParametersI3D\"))\n\tgpGetGenlockSampleRateI3D = uintptr(getProcAddr(\"wglGetGenlockSampleRateI3D\"))\n\tgpGetGenlockSourceDelayI3D = uintptr(getProcAddr(\"wglGetGenlockSourceDelayI3D\"))\n\tgpGetGenlockSourceEdgeI3D = uintptr(getProcAddr(\"wglGetGenlockSourceEdgeI3D\"))\n\tgpGetGenlockSourceI3D = uintptr(getProcAddr(\"wglGetGenlockSourceI3D\"))\n\tgpGetLayerPaletteEntries = uintptr(getProcAddr(\"wglGetLayerPaletteEntries\"))\n\tif gpGetLayerPaletteEntries == 0 {\n\t\treturn errors.New(\"wglGetLayerPaletteEntries\")\n\t}\n\tgpGetMscRateOML = uintptr(getProcAddr(\"wglGetMscRateOML\"))\n\tgpGetPbufferDCARB = uintptr(getProcAddr(\"wglGetPbufferDCARB\"))\n\tgpGetPbufferDCEXT = uintptr(getProcAddr(\"wglGetPbufferDCEXT\"))\n\tgpGetPixelFormatAttribfvARB = uintptr(getProcAddr(\"wglGetPixelFormatAttribfvARB\"))\n\tgpGetPixelFormatAttribfvEXT = uintptr(getProcAddr(\"wglGetPixelFormatAttribfvEXT\"))\n\tgpGetPixelFormatAttribivARB = uintptr(getProcAddr(\"wglGetPixelFormatAttribivARB\"))\n\tgpGetPixelFormatAttribivEXT = uintptr(getProcAddr(\"wglGetPixelFormatAttribivEXT\"))\n\tgpGetProcAddress = uintptr(getProcAddr(\"wglGetProcAddress\"))\n\tif gpGetProcAddress == 0 {\n\t\treturn errors.New(\"wglGetProcAddress\")\n\t}\n\tgpGetSwapIntervalEXT = uintptr(getProcAddr(\"wglGetSwapIntervalEXT\"))\n\tgpGetSyncValuesOML = uintptr(getProcAddr(\"wglGetSyncValuesOML\"))\n\tgpGetVideoDeviceNV = uintptr(getProcAddr(\"wglGetVideoDeviceNV\"))\n\tgpGetVideoInfoNV = uintptr(getProcAddr(\"wglGetVideoInfoNV\"))\n\tgpIsEnabledFrameLockI3D = uintptr(getProcAddr(\"wglIsEnabledFrameLockI3D\"))\n\tgpIsEnabledGenlockI3D = uintptr(getProcAddr(\"wglIsEnabledGenlockI3D\"))\n\tgpJoinSwapGroupNV = uintptr(getProcAddr(\"wglJoinSwapGroupNV\"))\n\tgpLoadDisplayColorTableEXT = uintptr(getProcAddr(\"wglLoadDisplayColorTableEXT\"))\n\tgpLockVideoCaptureDeviceNV = uintptr(getProcAddr(\"wglLockVideoCaptureDeviceNV\"))\n\tgpMakeAssociatedContextCurrentAMD = uintptr(getProcAddr(\"wglMakeAssociatedContextCurrentAMD\"))\n\tgpMakeContextCurrentARB = uintptr(getProcAddr(\"wglMakeContextCurrentARB\"))\n\tgpMakeContextCurrentEXT = uintptr(getProcAddr(\"wglMakeContextCurrentEXT\"))\n\tgpMakeCurrent = uintptr(getProcAddr(\"wglMakeCurrent\"))\n\tif gpMakeCurrent == 0 {\n\t\treturn errors.New(\"wglMakeCurrent\")\n\t}\n\tgpQueryCurrentContextNV = uintptr(getProcAddr(\"wglQueryCurrentContextNV\"))\n\tgpQueryFrameCountNV = uintptr(getProcAddr(\"wglQueryFrameCountNV\"))\n\tgpQueryFrameLockMasterI3D = uintptr(getProcAddr(\"wglQueryFrameLockMasterI3D\"))\n\tgpQueryFrameTrackingI3D = uintptr(getProcAddr(\"wglQueryFrameTrackingI3D\"))\n\tgpQueryGenlockMaxSourceDelayI3D = uintptr(getProcAddr(\"wglQueryGenlockMaxSourceDelayI3D\"))\n\tgpQueryMaxSwapGroupsNV = uintptr(getProcAddr(\"wglQueryMaxSwapGroupsNV\"))\n\tgpQueryPbufferARB = uintptr(getProcAddr(\"wglQueryPbufferARB\"))\n\tgpQueryPbufferEXT = uintptr(getProcAddr(\"wglQueryPbufferEXT\"))\n\tgpQuerySwapGroupNV = uintptr(getProcAddr(\"wglQuerySwapGroupNV\"))\n\tgpQueryVideoCaptureDeviceNV = uintptr(getProcAddr(\"wglQueryVideoCaptureDeviceNV\"))\n\tgpRealizeLayerPalette = uintptr(getProcAddr(\"wglRealizeLayerPalette\"))\n\tif gpRealizeLayerPalette == 0 {\n\t\treturn errors.New(\"wglRealizeLayerPalette\")\n\t}\n\tgpReleaseImageBufferEventsI3D = uintptr(getProcAddr(\"wglReleaseImageBufferEventsI3D\"))\n\tgpReleasePbufferDCARB = uintptr(getProcAddr(\"wglReleasePbufferDCARB\"))\n\tgpReleasePbufferDCEXT = uintptr(getProcAddr(\"wglReleasePbufferDCEXT\"))\n\tgpReleaseTexImageARB = uintptr(getProcAddr(\"wglReleaseTexImageARB\"))\n\tgpReleaseVideoCaptureDeviceNV = uintptr(getProcAddr(\"wglReleaseVideoCaptureDeviceNV\"))\n\tgpReleaseVideoDeviceNV = uintptr(getProcAddr(\"wglReleaseVideoDeviceNV\"))\n\tgpReleaseVideoImageNV = uintptr(getProcAddr(\"wglReleaseVideoImageNV\"))\n\tgpResetFrameCountNV = uintptr(getProcAddr(\"wglResetFrameCountNV\"))\n\tgpRestoreBufferRegionARB = uintptr(getProcAddr(\"wglRestoreBufferRegionARB\"))\n\tgpSaveBufferRegionARB = uintptr(getProcAddr(\"wglSaveBufferRegionARB\"))\n\tgpSendPbufferToVideoNV = uintptr(getProcAddr(\"wglSendPbufferToVideoNV\"))\n\tgpSetDigitalVideoParametersI3D = uintptr(getProcAddr(\"wglSetDigitalVideoParametersI3D\"))\n\tgpSetGammaTableI3D = uintptr(getProcAddr(\"wglSetGammaTableI3D\"))\n\tgpSetGammaTableParametersI3D = uintptr(getProcAddr(\"wglSetGammaTableParametersI3D\"))\n\tgpSetLayerPaletteEntries = uintptr(getProcAddr(\"wglSetLayerPaletteEntries\"))\n\tif gpSetLayerPaletteEntries == 0 {\n\t\treturn errors.New(\"wglSetLayerPaletteEntries\")\n\t}\n\tgpSetPbufferAttribARB = uintptr(getProcAddr(\"wglSetPbufferAttribARB\"))\n\tgpSetStereoEmitterState3DL = uintptr(getProcAddr(\"wglSetStereoEmitterState3DL\"))\n\tgpShareLists = uintptr(getProcAddr(\"wglShareLists\"))\n\tif gpShareLists == 0 {\n\t\treturn errors.New(\"wglShareLists\")\n\t}\n\tgpSwapBuffersMscOML = uintptr(getProcAddr(\"wglSwapBuffersMscOML\"))\n\tgpSwapIntervalEXT = uintptr(getProcAddr(\"wglSwapIntervalEXT\"))\n\tgpSwapLayerBuffers = uintptr(getProcAddr(\"wglSwapLayerBuffers\"))\n\tif gpSwapLayerBuffers == 0 {\n\t\treturn errors.New(\"wglSwapLayerBuffers\")\n\t}\n\tgpSwapLayerBuffersMscOML = uintptr(getProcAddr(\"wglSwapLayerBuffersMscOML\"))\n\tgpUseFontBitmaps = uintptr(getProcAddr(\"wglUseFontBitmapsW\"))\n\tif gpUseFontBitmaps == 0 {\n\t\treturn errors.New(\"wglUseFontBitmaps\")\n\t}\n\tgpUseFontOutlines = uintptr(getProcAddr(\"wglUseFontOutlinesW\"))\n\tif gpUseFontOutlines == 0 {\n\t\treturn errors.New(\"wglUseFontOutlines\")\n\t}\n\tgpWaitForMscOML = uintptr(getProcAddr(\"wglWaitForMscOML\"))\n\tgpWaitForSbcOML = uintptr(getProcAddr(\"wglWaitForSbcOML\"))\n\treturn nil\n}",
"func NewWithData(width, height int, data []byte) *Bitmap {\n\tbm := New(width, height)\n\tbm.Data = data\n\treturn bm\n}",
"func NewByteBuffer(buf []byte) *ByteBuffer {\n\treturn &ByteBuffer{\n\t\tbuf: buf,\n\t}\n}",
"func NewImageFromBuffer(buf []byte) (*ImageRef, error) {\n\treturn LoadImageFromBuffer(buf, nil)\n}",
"func (b *defaultByteBuffer) NewBuffer() ByteBuffer {\n\treturn NewWriterBuffer(256)\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetStride(request *requests.FPDFBitmap_GetStride) (*responses.FPDFBitmap_GetStride, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstride := C.FPDFBitmap_GetStride(bitmapHandle.handle)\n\treturn &responses.FPDFBitmap_GetStride{\n\t\tStride: int(stride),\n\t}, nil\n}",
"func NewFzGlyphRef(ref unsafe.Pointer) *FzGlyph {\n\treturn (*FzGlyph)(ref)\n}",
"func NewFzBandWriterRef(ref unsafe.Pointer) *FzBandWriter {\n\treturn (*FzBandWriter)(ref)\n}",
"func NewAttachedBytes(buffer []byte, offset int, size int) *Buffer {\n result := NewEmptyBuffer()\n result.AttachBytes(buffer, offset, size)\n return result\n}",
"func NewImageBufSpec(spec *ImageSpec) (*ImageBuf, error) {\n\tbuf := newImageBuf(C.ImageBuf_New_Spec(spec.ptr))\n\truntime.KeepAlive(spec)\n\terr := buf.LastError()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf, nil\n}",
"func NewAttachedBuffer(buffer *Buffer) *Buffer {\n result := NewEmptyBuffer()\n result.AttachBuffer(buffer)\n return result\n}",
"func New(w, h int) *Buffer {\n\tb := &Buffer{\n\t\tWidth: w,\n\t\tHeight: h,\n\t\tCursor: NewCursor(0, 0),\n\t\tTiles: make([]*Tile, w*h),\n\t}\n\tb.Resize(w, h)\n\treturn b\n}",
"func allocFzDeviceMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzDeviceValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func createBuffer() *bytes.Buffer {\n\tbuf := bytes.Buffer{}\n\treturn &buf\n}",
"func GetPbufferDCARB(hPbuffer unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpGetPbufferDCARB, 1, uintptr(hPbuffer), 0, 0)\n\treturn (unsafe.Pointer)(ret)\n}",
"func allocFzFontFlagsMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzFontFlagsValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func NewFzPixmapImageRef(ref unsafe.Pointer) *FzPixmapImage {\n\treturn (*FzPixmapImage)(ref)\n}",
"func CreateImageResource(xRefTable *XRefTable, r io.Reader, gray, sepia bool) (*types.IndirectRef, int, int, error) {\n\tsd, w, h, err := CreateImageStreamDict(xRefTable, r, gray, sepia)\n\tif err != nil {\n\t\treturn nil, 0, 0, err\n\t}\n\tindRef, err := xRefTable.IndRefForNewObject(*sd)\n\treturn indRef, w, h, err\n}",
"func allocFzFontMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzFontValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func allocFzRectMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzRectValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (x *FzBuffer) Ref() *C.fz_buffer {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.fz_buffer)(unsafe.Pointer(x))\n}",
"func allocFzFontContextMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzFontContextValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func allocFzGlyphCacheMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzGlyphCacheValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (obj *Device) CreateVertexBuffer(\n\tlength uint,\n\tusage uint32,\n\tfvf uint32,\n\tpool POOL,\n\tsharedHandle uintptr,\n) (*VertexBuffer, Error) {\n\tvar buf *VertexBuffer\n\tret, _, _ := syscall.Syscall9(\n\t\tobj.vtbl.CreateVertexBuffer,\n\t\t7,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(length),\n\t\tuintptr(usage),\n\t\tuintptr(fvf),\n\t\tuintptr(pool),\n\t\tuintptr(unsafe.Pointer(&buf)),\n\t\tsharedHandle,\n\t\t0,\n\t\t0,\n\t)\n\treturn buf, toErr(ret)\n}",
"func allocFzAnnotMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzAnnotValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func allocFzCmmInstanceMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzCmmInstanceValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func NewBMP280WithConfig(dev *i2c.Dev, cfg *Configuration) (*BMP, error) {\n\n\tbmp := &BMP{\n\t\tdevice: dev,\n\t\tconfig: cfg,\n\t\ttempCalibration: make([]calibrationData, 3),\n\t\tpressCalibration: make([]calibrationData, 9),\n\t\tlastTemperatureMeasurement: math.NaN(),\n\t}\n\n\tif err := bmp.SetConfiguration(cfg); err != nil {\n\t\treturn bmp, err\n\t}\n\n\terr := bmp.Init()\n\treturn bmp, err\n}",
"func AcquireByteBuffer() *ByteBuffer {\n\tv := byteBufferPool.Get()\n\tif v == nil {\n\t\treturn &ByteBuffer{\n\t\t\tB: make([]byte, 0, defaultByteBufferSize),\n\t\t}\n\t}\n\treturn v.(*ByteBuffer)\n}",
"func GetDirectBufferAddress(env *C.JNIEnv, buf C.jobject) unsafe.Pointer {\n\treturn C._GoJniGetDirectBufferAddress(env, buf)\n}",
"func allocFzColorspaceMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzColorspaceValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func allocFzColorspaceContextMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzColorspaceContextValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func allocPDFOcgDescriptorMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFOcgDescriptorValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func UseFontBitmaps(hDC unsafe.Pointer, first unsafe.Pointer, count unsafe.Pointer, listBase unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall6(gpUseFontBitmaps, 4, uintptr(hDC), uintptr(first), uintptr(count), uintptr(listBase), 0, 0)\n\treturn (unsafe.Pointer)(ret)\n}",
"func (bm Bitmap) Free(off uint64) {\n\tblockIndex := off / ItemsPerBitmap\n\tbyteIndex := (off / 8) % 4096\n\tbitIndex := off % 8\n\tbm[blockIndex][byteIndex] = bm[blockIndex][byteIndex] & ^(1 << bitIndex)\n}",
"func CreateDCTImageObject(xRefTable *XRefTable, buf []byte, w, h, bpc int, cs string) (*types.StreamDict, error) {\n\tsd := &types.StreamDict{\n\t\tDict: types.Dict(\n\t\t\tmap[string]types.Object{\n\t\t\t\t\"Type\": types.Name(\"XObject\"),\n\t\t\t\t\"Subtype\": types.Name(\"Image\"),\n\t\t\t\t\"Width\": types.Integer(w),\n\t\t\t\t\"Height\": types.Integer(h),\n\t\t\t\t\"BitsPerComponent\": types.Integer(bpc),\n\t\t\t\t\"ColorSpace\": types.Name(cs),\n\t\t\t},\n\t\t),\n\t\tContent: buf,\n\t\tFilterPipeline: nil,\n\t}\n\n\tif cs == DeviceCMYKCS {\n\t\tsd.Insert(\"Decode\", types.NewIntegerArray(1, 0, 1, 0, 1, 0, 1, 0))\n\t}\n\n\tif w < 1000 || h < 1000 {\n\t\tsd.Insert(\"Interpolate\", types.Boolean(true))\n\t}\n\n\tsd.InsertName(\"Filter\", filter.DCT)\n\n\t// Calling Encode without FilterPipeline ensures an encoded stream in sd.Raw.\n\tif err := sd.Encode(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsd.Content = nil\n\n\tsd.FilterPipeline = []types.PDFFilter{{Name: filter.DCT, DecodeParms: nil}}\n\n\treturn sd, nil\n}",
"func allocFzCompressedBufferMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzCompressedBufferValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func allocPFzPixmapMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPFzPixmapValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func newBitmapFromBytes(data []byte) *bitmap {\n\tbitmap := newBitmap(len(data) * 8)\n\tcopy(bitmap.data, data)\n\treturn bitmap\n}",
"func New(w, h int, s *fyne.Window) Buffer {\n\tcontext := gg.NewContext(w, h)\n\treturn Buffer{w, h, s, context}\n}",
"func allocFzPageMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzPageValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func newFramebufferFromTexture(context *context, texture textureNative, width, height int) (*framebuffer, error) {\n\tnative, err := context.newFramebuffer(texture)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &framebuffer{\n\t\tnative: native,\n\t\twidth: width,\n\t\theight: height,\n\t}, nil\n}",
"func createFB(tex wasm.WebGLTexture) wasm.WebGLFramebuffer {\n\tfb := gl.CreateFramebuffer()\n\tgl.BindFramebuffer(wasm.FRAMEBUFFER, fb)\n\tgl.FramebufferTexture2D(wasm.FRAMEBUFFER, wasm.COLOR_ATTACHMENT0, wasm.TEXTURE_2D, tex, 0)\n\treturn fb\n}",
"func NewThumbnailFromBuffer(buf []byte, width, height int, crop Interesting) (*ImageRef, error) {\n\treturn LoadThumbnailFromBuffer(buf, width, height, crop, SizeBoth, nil)\n}",
"func allocFzHalftoneMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFzHalftoneValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func QueryPbufferARB(hPbuffer unsafe.Pointer, iAttribute unsafe.Pointer, piValue unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpQueryPbufferARB, 3, uintptr(hPbuffer), uintptr(iAttribute), uintptr(piValue))\n\treturn (unsafe.Pointer)(ret)\n}",
"func allocPDFHotspotMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFHotspotValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func New() (*Library, error) {\n\tlib := &Library{}\n\terrno := C.FT_Init_FreeType(&lib.handle)\n\tif errno != 0 {\n\t\treturn lib, fmt.Errorf(\"freetype2: %s\", errstr(errno))\n\t}\n\truntime.SetFinalizer(lib, (*Library).release)\n\treturn lib, nil\n}",
"func allocPDFObjMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFObjValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func NewPDFObj() *PDFObj {\n\treturn (*PDFObj)(allocPDFObjMemory(1))\n}",
"func CreateRenderbuffer() Renderbuffer {\n\tvar b Renderbuffer\n\tgl.GenRenderbuffers(1, &b.Value)\n\treturn b\n}",
"func AcquireByteBuffer() *ByteBuffer {\n\tv := byteBufferPool.Get()\n\tif v == nil {\n\t\treturn &ByteBuffer{}\n\t}\n\treturn v.(*ByteBuffer)\n}",
"func NewFzDeviceRef(ref unsafe.Pointer) *FzDevice {\n\treturn (*FzDevice)(ref)\n}"
] | [
"0.6790848",
"0.6164236",
"0.5898479",
"0.58465135",
"0.5841064",
"0.56201357",
"0.561315",
"0.5524258",
"0.53567016",
"0.5328848",
"0.49656948",
"0.49555525",
"0.49421835",
"0.48581567",
"0.48405558",
"0.47972837",
"0.47484767",
"0.47479987",
"0.47454888",
"0.4722671",
"0.47026542",
"0.4696133",
"0.46814206",
"0.46651235",
"0.46499598",
"0.4648122",
"0.4642108",
"0.4582962",
"0.45807105",
"0.45557246",
"0.45142683",
"0.44794348",
"0.44635898",
"0.4462929",
"0.44595158",
"0.44429293",
"0.4426287",
"0.44234803",
"0.44186014",
"0.4416003",
"0.44146323",
"0.43824401",
"0.4382347",
"0.43709308",
"0.43487352",
"0.43467253",
"0.43410107",
"0.4338307",
"0.43322617",
"0.43312612",
"0.42983717",
"0.42898774",
"0.42759153",
"0.42685536",
"0.42677188",
"0.4264397",
"0.42590022",
"0.42573616",
"0.42346206",
"0.42335683",
"0.422949",
"0.42251",
"0.42008242",
"0.4197304",
"0.419127",
"0.4186743",
"0.4186468",
"0.4174169",
"0.41599324",
"0.41593185",
"0.41561648",
"0.41561157",
"0.41551107",
"0.4145672",
"0.4141902",
"0.41287982",
"0.4113347",
"0.40997708",
"0.409677",
"0.4094055",
"0.40858012",
"0.40841436",
"0.4079819",
"0.40628898",
"0.40625834",
"0.4062068",
"0.40616152",
"0.40595177",
"0.4051407",
"0.40510944",
"0.4049526",
"0.40432787",
"0.4039307",
"0.4031849",
"0.4030937",
"0.40301475",
"0.40278178",
"0.40270314",
"0.40178162",
"0.40162963"
] | 0.74379617 | 0 |
FPDFBitmap_GetFormat returns the format of the bitmap. Only formats supported by FPDFBitmap_CreateEx are supported by this function. | func (p *PdfiumImplementation) FPDFBitmap_GetFormat(request *requests.FPDFBitmap_GetFormat) (*responses.FPDFBitmap_GetFormat, error) {
p.Lock()
defer p.Unlock()
bitmapHandle, err := p.getBitmapHandle(request.Bitmap)
if err != nil {
return nil, err
}
format := C.FPDFBitmap_GetFormat(bitmapHandle.handle)
return &responses.FPDFBitmap_GetFormat{
Format: enums.FPDF_BITMAP_FORMAT(format),
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (is ImageSurface) Format() Format {\n\treturn is.format\n}",
"func (self *TraitPixbufLoader) GetFormat() (return__ *C.GdkPixbufFormat) {\n\treturn__ = C.gdk_pixbuf_loader_get_format(self.CPointer)\n\treturn\n}",
"func (f v4l2Format) getPixFormat() PixFormat {\n\tpixfmt := (*PixFormat)(unsafe.Pointer(&f.fmt[0]))\n\treturn *pixfmt\n}",
"func (o *WorkbookChart) GetFormatOk() (AnyOfmicrosoftGraphWorkbookChartAreaFormat, bool) {\n\tif o == nil || o.Format == nil {\n\t\tvar ret AnyOfmicrosoftGraphWorkbookChartAreaFormat\n\t\treturn ret, false\n\t}\n\treturn *o.Format, true\n}",
"func (p *BW) Format() Format {\n\treturn PBM\n}",
"func (r *ImageRef) Format() ImageType {\n\treturn r.format\n}",
"func (pstFile *File) GetFormatType() (string, error) {\n\tformatType, err := pstFile.Read(2, 10)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tswitch binary.LittleEndian.Uint16(formatType) {\n\tcase 14:\n\t\treturn FormatTypeANSI, nil\n\tcase 15:\n\t\treturn FormatTypeANSI, nil\n\tcase 21:\n\t\treturn FormatTypeUnicode, nil\n\tcase 23:\n\t\treturn FormatTypeUnicode, nil\n\tcase 36:\n\t\treturn FormatTypeUnicode4k, nil\n\tdefault:\n\t\treturn \"\", errors.New(\"unsupported format type\")\n\t}\n}",
"func (o *WorkbookChart) GetFormat() AnyOfmicrosoftGraphWorkbookChartAreaFormat {\n\tif o == nil || o.Format == nil {\n\t\tvar ret AnyOfmicrosoftGraphWorkbookChartAreaFormat\n\t\treturn ret\n\t}\n\treturn *o.Format\n}",
"func (bfo *BaseFormatOutput) GetFormat() string {\n\treturn bfo.FormatType\n}",
"func (t *ConvertTransform) GetFormat() ConvertTransformFormat {\n\tif t.Format != nil {\n\t\treturn *t.Format\n\t}\n\treturn ConvertTransformFormatNone\n}",
"func (f *DynamicDiskBlockFactory) GetBitmapFactory() *bitmap.Factory {\n\treturn f.bitmapFactory\n}",
"func (b *block) GetFormat() Format {\n\t// Verify checksum.\n\tvar p parser\n\tvalue := p.parseOctal(b.V7().Chksum())\n\tchksum1, chksum2 := b.ComputeChecksum()\n\tif p.err != nil || (value != chksum1 && value != chksum2) {\n\t\treturn FormatUnknown\n\t}\n\n\t// Guess the magic values.\n\tmagic := string(b.USTAR().Magic())\n\tversion := string(b.USTAR().Version())\n\ttrailer := string(b.STAR().Trailer())\n\tswitch {\n\tcase magic == magicUSTAR && trailer == trailerSTAR:\n\t\treturn formatSTAR\n\tcase magic == magicUSTAR:\n\t\treturn FormatUSTAR | FormatPAX\n\tcase magic == magicGNU && version == versionGNU:\n\t\treturn FormatGNU\n\tdefault:\n\t\treturn formatV7\n\t}\n}",
"func (s *ImageSpec) Format() TypeDesc {\n\tret := (TypeDesc)(C.ImageSpec_format(s.ptr))\n\truntime.KeepAlive(s)\n\treturn ret\n}",
"func (mw *MagickWand) Format() string {\n\treturn mw.GetImageFormat()\n}",
"func getImageFormat(filename string) (string, error) {\n\tmime, _, err := mimetype.DetectFile(filename)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"can't detect image's type\")\n\t} else {\n\t\treturn mime, nil\n\t}\n}",
"func (m *WorkbookChartTitle) GetFormat()(WorkbookChartTitleFormatable) {\n val, err := m.GetBackingStore().Get(\"format\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(WorkbookChartTitleFormatable)\n }\n return nil\n}",
"func (r *ImageRef) BandFormat() BandFormat {\n\treturn BandFormat(int(r.image.BandFmt))\n}",
"func (c *Sound) GetFormat() int {\n\treturn c.Format\n}",
"func GetFormat(src string) (Format, bool) {\n\t// is it a filename with an extension?\n\ttmp := filepath.Ext(src)\n\tisFile := true\n\t// fmt.Println(\"tmp\", tmp)\n\tif tmp == \"\" {\n\t\ttmp = src\n\t\tisFile = false\n\t}\n\n\tswitch tmp {\n\tcase \"\":\n\t\treturn FormatUnknown, isFile\n\n\tcase \"FZP\", \"fzp\", \".FZP\", \".fzp\":\n\t\treturn FormatFzp, isFile\n\n\tcase \"JSON\", \"json\", \".JSON\", \".json\":\n\t\treturn FormatJSON, isFile\n\n\tcase \"YAML\", \"yaml\", \"yml\", \".YAML\", \".yaml\", \".yml\":\n\t\treturn FormatYAML, isFile\n\n\tdefault:\n\t\treturn FormatNotSupported, isFile\n\t}\n}",
"func (b *Bitmap) PixelMode() int {\n\treturn int(b.handle.pixel_mode)\n}",
"func (ml MetalLayer) PixelFormat() mtl.PixelFormat {\n\treturn mtl.PixelFormat(C.MetalLayer_PixelFormat(ml.metalLayer))\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetBuffer(request *requests.FPDFBitmap_GetBuffer) (*responses.FPDFBitmap_GetBuffer, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We need to calculate the buffer size, this is stride (bytes per bitmap line) * height.\n\tstride := C.FPDFBitmap_GetStride(bitmapHandle.handle)\n\theight := C.FPDFBitmap_GetHeight(bitmapHandle.handle)\n\tsize := int(stride * height)\n\n\t// The pointer to the first byte of the bitmap buffer.\n\tbuffer := C.FPDFBitmap_GetBuffer(bitmapHandle.handle)\n\n\t// We create a Go slice backed by a C array (without copying the original data).\n\tdata := unsafe.Slice((*byte)(unsafe.Pointer(buffer)), uint64(size))\n\n\treturn &responses.FPDFBitmap_GetBuffer{\n\t\tBuffer: data,\n\t}, nil\n}",
"func (p *PdfiumImplementation) FPDFBitmap_Create(request *requests.FPDFBitmap_Create) (*responses.FPDFBitmap_Create, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmap := C.FPDFBitmap_Create(C.int(request.Width), C.int(request.Height), C.int(request.Alpha))\n\tbitmapHandle := p.registerBitmap(bitmap)\n\n\treturn &responses.FPDFBitmap_Create{\n\t\tBitmap: bitmapHandle.nativeRef,\n\t}, nil\n}",
"func (w *Window) Format() int {\n\treturn int(C.ANativeWindow_getFormat(w.cptr()))\n}",
"func (sh *ServerPropertiesHandle) GetFormat() int {\n\treturn sh.Format\n}",
"func (x *FileAccessLog) GetFormat() string {\n\tif x, ok := x.GetAccessLogFormat().(*FileAccessLog_Format); ok {\n\t\treturn x.Format\n\t}\n\treturn \"\"\n}",
"func (m *WorkbookChartTitle) GetFormat()(WorkbookChartTitleFormatable) {\n return m.format\n}",
"func GetFormats() map[string]string {\n\treturn formats\n}",
"func determineFormat(channels int) int {\n\tswitch channels {\n\tcase 1:\n\t\treturn gl.RED\n\tcase 2:\n\t\treturn gl.RG\n\tcase 3:\n\t\treturn gl.RGB\n\tcase 4:\n\t\treturn gl.RGBA\n\t}\n\treturn gl.RGBA\n}",
"func GetPixelFormat(hdc unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpGetPixelFormat, 1, uintptr(hdc), 0, 0)\n\treturn (unsafe.Pointer)(ret)\n}",
"func GetPixFormat(fd uintptr) (PixFormat, error) {\n\tformat := v4l2Format{StreamType: BufTypeVideoCapture}\n\tif err := Send(fd, VidiocGetFormat, uintptr(unsafe.Pointer(&format))); err != nil {\n\t\tswitch {\n\t\tcase errors.Is(err, ErrorUnsupported):\n\t\t\treturn PixFormat{}, fmt.Errorf(\"pix format: unsupported: %w\", err)\n\t\tdefault:\n\t\t\treturn PixFormat{}, fmt.Errorf(\"pix format failed: %w\", err)\n\t\t}\n\t}\n\n\treturn format.getPixFormat(), nil\n}",
"func (o *MultiMesh) GetTransformFormat() MultiMeshTransformFormat {\n\t//log.Println(\"Calling MultiMesh.GetTransformFormat()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"MultiMesh\", \"get_transform_format\")\n\n\t// Call the parent method.\n\t// enum.MultiMesh::TransformFormat\n\tretPtr := gdnative.NewEmptyInt()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewIntFromPointer(retPtr)\n\treturn MultiMeshTransformFormat(ret)\n}",
"func (p *PostingsIterator) ActualBitmap() *roaring.Bitmap {\n\treturn p.ActualBM\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetHeight(request *requests.FPDFBitmap_GetHeight) (*responses.FPDFBitmap_GetHeight, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theight := C.FPDFBitmap_GetHeight(bitmapHandle.handle)\n\treturn &responses.FPDFBitmap_GetHeight{\n\t\tHeight: int(height),\n\t}, nil\n}",
"func DeviceManagementReportFileFormatPPdf() *DeviceManagementReportFileFormat {\n\tv := DeviceManagementReportFileFormatVPdf\n\treturn &v\n}",
"func (b *Bitmaps) GetBitmap(i int) (*Bitmap, error) {\n\tconst processName = \"GetBitmap\"\n\tif b == nil {\n\t\treturn nil, errors.Error(processName, \"provided nil Bitmaps\")\n\t}\n\tif i > len(b.Values)-1 {\n\t\treturn nil, errors.Errorf(processName, \"index: '%d' out of range\", i)\n\t}\n\treturn b.Values[i], nil\n}",
"func (o *CommitOptions) GetFormat() string {\n\tif o.Format == nil {\n\t\tvar z string\n\t\treturn z\n\t}\n\treturn *o.Format\n}",
"func (p *PdfiumImplementation) FPDFBitmap_CreateEx(request *requests.FPDFBitmap_CreateEx) (*responses.FPDFBitmap_CreateEx, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tvar pointer unsafe.Pointer\n\tif request.Buffer != nil {\n\t\tpointer = unsafe.Pointer(&request.Buffer[0])\n\t} else if request.Pointer != nil {\n\t\tv, ok := request.Pointer.(unsafe.Pointer)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"request.Pointer is not of type unsafe.Pointer\")\n\t\t}\n\n\t\tpointer = v\n\t}\n\n\tbitmap := C.FPDFBitmap_CreateEx(C.int(request.Width), C.int(request.Height), C.int(request.Format), pointer, C.int(request.Stride))\n\tbitmapHandle := p.registerBitmap(bitmap)\n\n\treturn &responses.FPDFBitmap_CreateEx{\n\t\tBitmap: bitmapHandle.nativeRef,\n\t}, nil\n}",
"func (p *Provider) GetDataFormat() (string, error) {\n\tf, err := p.GetDBHandle(internalDBName).Get(formatVersionKey)\n\treturn string(f), err\n}",
"func (fr *Frame) Format() string {\n\t// Check whether field 11 is the CI\n\t// If field 11 a CI field it's frame format B\n\tciFieldFormatB := fr.getHexValue(11)\n\tif ciFieldFormatB == \"51\" || ciFieldFormatB == \"71\" || ciFieldFormatB == \"72\" || ciFieldFormatB == \"78\" || ciFieldFormatB == \"7A\" || ciFieldFormatB == \"81\" {\n\t\treturn \"B\"\n\t}\n\n\t// Quick'n dirty: Assume A for everything else\n\treturn \"A\"\n}",
"func getBitmap(file *os.File, index int64, size int64) []byte {\n\tbitMap := make([]byte, size)\n\tfile.Seek(index, 0)\n\t//Se obtiene la data del archivo binarios\n\tdata := readNextBytes(file, size)\n\tbuffer := bytes.NewBuffer(data)\n\t//Se asigna al mbr declarado para leer la informacion de ese disco\n\terr := binary.Read(buffer, binary.BigEndian, &bitMap)\n\tif err != nil {\n\t\tlog.Fatal(\"binary.Read failed\", err)\n\t}\n\treturn bitMap\n}",
"func (API) GetFramebufferAttachmentInfo(state *api.State, thread uint64, attachment api.FramebufferAttachment) (width, height, index uint32, format *image.Format, err error) {\n\treturn 0, 0, 0, nil, fmt.Errorf(\"GVR does not support framebuffers\")\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetStride(request *requests.FPDFBitmap_GetStride) (*responses.FPDFBitmap_GetStride, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstride := C.FPDFBitmap_GetStride(bitmapHandle.handle)\n\treturn &responses.FPDFBitmap_GetStride{\n\t\tStride: int(stride),\n\t}, nil\n}",
"func (o FaqOutput) FileFormat() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Faq) pulumi.StringPtrOutput { return v.FileFormat }).(pulumi.StringPtrOutput)\n}",
"func (b *Bitmap) Image() (image.Image, error) {\n\t// TODO Support the other pixel modes\n\tswitch b.PixelMode() {\n\tcase PixelModeNone, PixelModeMono, PixelModeGray2, PixelModeGray4, PixelModeLCD, PixelModeLCDV:\n\t\treturn nil, ErrUnsupportedPixelMode\n\tcase PixelModeBGRA:\n\t\treturn b.NRGBA()\n\tcase PixelModeGray:\n\t\treturn b.GrayImage()\n\t}\n\treturn nil, ErrUnsupportedPixelMode\n}",
"func DescribePixelFormat(hdc unsafe.Pointer, ipfd unsafe.Pointer, cjpfd unsafe.Pointer, ppfd unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall6(gpDescribePixelFormat, 4, uintptr(hdc), uintptr(ipfd), uintptr(cjpfd), uintptr(ppfd), 0, 0)\n\treturn (unsafe.Pointer)(ret)\n}",
"func (i *ImageBuf) FileFormatName() string {\n\tret := C.GoString(C.ImageBuf_file_format_name(i.ptr))\n\truntime.KeepAlive(i)\n\treturn ret\n}",
"func (o *V1VirusDatasetRequest) GetFormatOk() (*V1TableFormat, bool) {\n\tif o == nil || o.Format == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Format, true\n}",
"func getImageInfo(image_path string) (w int, h int, kind string, err error) {\n\timf, err := os.Open(image_path)\n\tif err != nil {\n\t\treturn 0, 0, \"\", err\n\t}\n\tdefer imf.Close()\n\n\tconfig, kind, err := image.DecodeConfig(imf)\n\tif err != nil {\n\t\treturn 0, 0, \"\", err\n\t}\n\n\treturn config.Width, config.Height, kind, nil\n}",
"func (ts *Typefaces) Format() []string {\n\tresult := []string{}\n\tfor _, v := range ts.Fonts {\n\t\tif v.Format == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !isUniqueString(result, v.Format) {\n\t\t\tcontinue\n\t\t}\n\n\t\tresult = append(result, v.Format)\n\t}\n\treturn result\n}",
"func (o *TelemetryDruidScanRequestAllOf) GetResultFormat() string {\n\tif o == nil || o.ResultFormat == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ResultFormat\n}",
"func GetEnhMetaFilePixelFormat(hemf unsafe.Pointer, ppfd unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpGetEnhMetaFilePixelFormat, 2, uintptr(hemf), uintptr(ppfd), 0)\n\treturn (unsafe.Pointer)(ret)\n}",
"func NewBitmap(fn Name) (*Bitmap, error) {\n\t// Each font is hard-coded into the binary as a slice of bytes.\n\tinfo, err := fontInfo(fn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Which is then decoded.\n\tpngImage, err := png.Decode(bytes.NewReader(info.byts))\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"font %+v\", fn)\n\t}\n\n\tebiImage := ebiten.NewImageFromImage(pngImage)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"font %+v\", fn)\n\t}\n\n\treturn &Bitmap{\n\t\timg: ebiImage,\n\t\tsize: info.size,\n\t\tmask: info.mask,\n\t\tsubmap: make(map[rune]*Glyph),\n\t}, nil\n}",
"func (c *Container) isBitmap() bool {\n\tif c == nil {\n\t\tpanic(\"calling isBitmap on nil container\")\n\t}\n\treturn c.typeID == ContainerBitmap\n}",
"func PixelFormatFromString(i string) PixelFormat {\n\tswitch i {\n\tcase \"bgr24\":\n\t\treturn AV_PIX_FMT_BGR24\n\tcase \"rgb24\":\n\t\treturn AV_PIX_FMT_RGB24\n\tcase \"rgba\":\n\t\treturn AV_PIX_FMT_RGBA\n\tcase \"yuv420p\":\n\t\treturn AV_PIX_FMT_YUV420P\n\tcase \"yuva420p\":\n\t\treturn AV_PIX_FMT_YUVA420P\n\tcase \"yuvj420p\":\n\t\treturn AV_PIX_FMT_YUVJ420P\n\tdefault:\n\t\treturn -1\n\t}\n}",
"func (r *ImageRef) OriginalFormat() ImageType {\n\treturn r.originalFormat\n}",
"func Format() audio.Format {\n\treturn format\n}",
"func (o *V1VirusDatasetRequest) GetFormat() V1TableFormat {\n\tif o == nil || o.Format == nil {\n\t\tvar ret V1TableFormat\n\t\treturn ret\n\t}\n\treturn *o.Format\n}",
"func (wb *Workbook) GetFormatByIndex(index int) record.Format {\n\treturn wb.formats[index]\n}",
"func GetMimeType(imageFormat string) (string, error) {\n\tswitch imageFormat {\n\tcase \"png\":\n\t\treturn \"image/png\", nil\n\tcase \"gif\":\n\t\treturn \"image/gif\", nil\n\tcase \"jpg\":\n\tcase \"jpeg\":\n\t\treturn \"image/jpeg\", nil\n\t}\n\treturn \"\", fmt.Errorf(\"Unknown image format: \", imageFormat)\n}",
"func (ExfatAllocationBitmapDirectoryEntry) TypeName() string {\n\treturn \"AllocationBitmap\"\n}",
"func (sb *spdkBackend) Format(req storage.BdevFormatRequest) (resp *storage.BdevFormatResponse, err error) {\n\tsb.log.Debugf(\"spdk backend format (bindings call): %+v\", req)\n\n\t// TODO (DAOS-3844): Kick off device formats in parallel?\n\tswitch req.Properties.Class {\n\tcase storage.ClassFile:\n\t\treturn sb.formatAioFile(&req)\n\tcase storage.ClassKdev:\n\t\treturn sb.formatKdev(&req)\n\tcase storage.ClassNvme:\n\t\treturn sb.formatNvme(&req)\n\tdefault:\n\t\treturn nil, FaultFormatUnknownClass(req.Properties.Class.String())\n\t}\n}",
"func (this *fileStruct) SampleFormat() uint16 {\n\treturn this.sampleFormat\n}",
"func GetNowDataBaseFormat() string {\n\treturn GetNow().Format(API_DB_LAYOUT)\n}",
"func (i *ImageBuf) ReadFormatCallback(force bool, convert TypeDesc, progress *ProgressCallback) error {\n\tvar cbk unsafe.Pointer\n\tif progress != nil {\n\t\tcbk = unsafe.Pointer(progress)\n\t}\n\n\tok := C.ImageBuf_read(i.ptr, 0, 0, C.bool(force), C.TypeDesc(convert), cbk)\n\tif !bool(ok) {\n\t\treturn i.LastError()\n\t}\n\truntime.KeepAlive(i)\n\truntime.KeepAlive(progress)\n\n\treturn nil\n}",
"func getOutputFormat() string {\n\tformat := outputFormat\n\tif format != string(component.JSONOutputType) && format != string(component.YAMLOutputType) {\n\t\t// For table output, we want to force the list table format for this part\n\t\tformat = string(component.ListTableOutputType)\n\t}\n\treturn format\n}",
"func (me piecePriority) BitmapPriority() int {\n\treturn -int(me)\n}",
"func checkMobMapImgFormat(p *page.Params, imgFormat string) (ok bool) {\n\tif imgFormat == \"\" {\n\t\treturn true\n\t}\n\n\tfor _, v := range imgFormats {\n\t\tif v == imgFormat {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tp.ErrorMsg = template.HTML(`Invalid <span class=\"code\">Mobile Map image format</span>!`)\n\n\treturn false\n}",
"func (o *WorkbookChart) HasFormat() bool {\n\tif o != nil && o.Format != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func registerImageFormats() {\n syncLock.Do(func() {\n image.RegisterFormat(\"jpeg\", \"jpeg\", jpeg.Decode, jpeg.DecodeConfig)\n image.RegisterFormat(\"png\", \"png\", png.Decode, png.DecodeConfig)\n })\n}",
"func (a *PhonebookAccess1) GetFixedImageSize() (bool, error) {\n\tv, err := a.GetProperty(\"FixedImageSize\")\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn v.Value().(bool), nil\n}",
"func (cache *Cache) BitmapGet(next uint16) (bool, uint16, uint16) {\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\treturn cache.bitmap.get(next)\n}",
"func (task *ParseTask) GetFormats(content []byte) ([]wisply.Formater, error) {\n\ttask.addContent(\"formats\")\n\tformats, err := task.remote.GetFormats(content)\n\tnumber := strconv.Itoa(len(formats))\n\ttask.finishRequest(err, \"Success. \"+number+\" `formats` has been identified\")\n\n\treturn formats, err\n}",
"func (d *DSP) ChannelFormat() (ChannelMask, int, SpeakerMode, error) {\n\tvar channelmask C.FMOD_CHANNELMASK\n\tvar numchannels C.int\n\tvar source_speakermode C.FMOD_SPEAKERMODE\n\tres := C.FMOD_DSP_GetChannelFormat(d.cptr, &channelmask, &numchannels, &source_speakermode)\n\treturn ChannelMask(channelmask), int(numchannels), SpeakerMode(source_speakermode), errs[res]\n}",
"func SupportedDataFormats() []DataFormat {\n\treturn []DataFormat{\n\t\tCBORDataFormat,\n\t\tJSONDataFormat,\n\t\tCSVDataFormat,\n\t\tXLSXDataFormat,\n\t\tNDJSONDataFormat,\n\t}\n}",
"func (w *Writer) Format() audio.Format {\n\treturn w.fmt\n}",
"func GetRenderbufferInternalFormat(target GLEnum) GLEnum {\n\tvar params int32\n\tgl.GetRenderbufferParameteriv(uint32(target), gl.RENDERBUFFER_INTERNAL_FORMAT, ¶ms)\n\treturn GLEnum(params)\n}",
"func (p *PdfiumImplementation) FPDFBitmap_Destroy(request *requests.FPDFBitmap_Destroy) (*responses.FPDFBitmap_Destroy, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tC.FPDFBitmap_Destroy(bitmapHandle.handle)\n\n\tdelete(p.bitmapRefs, bitmapHandle.nativeRef)\n\n\treturn &responses.FPDFBitmap_Destroy{}, nil\n}",
"func (o *Ratio32) GetBOk() (*uint32, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.B, true\n}",
"func DetectFormat(filePath string) (*FormatInfo, error) {\n\treturn detectFormat(filePath, ENCAPSULATION_NONE, true)\n}",
"func (b *Buddy) BlockAllocationBitmap() []byte {\n\treturn b.blockAllocationBitmap\n}",
"func GetShaderPrecisionFormat(shadertype uint32, precisiontype uint32, xrange *int32, precision *int32) {\n\tsyscall.Syscall6(gpGetShaderPrecisionFormat, 4, uintptr(shadertype), uintptr(precisiontype), uintptr(unsafe.Pointer(xrange)), uintptr(unsafe.Pointer(precision)), 0, 0)\n}",
"func (m *IosDeviceFeaturesConfiguration) GetWallpaperImage()(MimeContentable) {\n val, err := m.GetBackingStore().Get(\"wallpaperImage\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(MimeContentable)\n }\n return nil\n}",
"func GetShaderPrecisionFormat(shadertype, precisiontype Enum) (rangeLow, rangeHigh, precision int) {\n\tlog.Println(\"GetShaderPrecisionFormat: not yet tested (TODO: remove this after it's confirmed to work. Your feedback is welcome.)\")\n\tvar cRange [2]int32\n\tvar cPrecision int32\n\n\tgl.GetShaderPrecisionFormat(uint32(shadertype), uint32(precisiontype), &cRange[0], &cPrecision)\n\treturn int(cRange[0]), int(cRange[1]), int(cPrecision)\n}",
"func (i *InputThemeSettings) GetWallpaper() (value InputWallPaperClass, ok bool) {\n\tif i == nil {\n\t\treturn\n\t}\n\tif !i.Flags.Has(1) {\n\t\treturn value, false\n\t}\n\treturn i.Wallpaper, true\n}",
"func LoadFontBitmap(image *Image, charset string, charPerLines, noLines int) *Font {\n\tf := &Font{\n\t\tcharset: charset,\n\t\tglyphs: make(map[rune]Glyph, len(charset)),\n\t\tSpacing: 0,\n\t\tkerner: &monoSpacedKerner{},\n\t\ttexture: image.CreateTexture(),\n\t}\n\n\timageWidth := float32(image.Width())\n\timageHeight := float32(image.Height())\n\tgwidth := imageWidth / float32(charPerLines)\n\tgheight := imageHeight / float32(noLines)\n\n\t//Why is this inconsistent. Its even a different type. Its like saying this array is a byte array, until you walk it, then its a rune array\n\t//for i, c := range charset {\n\t//\tif rune(charset[i]) == c {\n\t//\t\tlog.Println(i, c, \" <- MATCH\")\n\t//\t} else {\n\t//\t\tlog.Println(i, c, \" <- DIFFERENT?\")\n\t//\t}\n\t//}\n\n\tx := float32(0)\n\ty := float32(0)\n\tfor i := range charset {\n\n\t\t//Get the rune and map it\n\t\tf.glyphs[rune(charset[i])] = Glyph{\n\t\t\tAtlas: Rectangle{(x * gwidth), (y * gheight), gwidth, gheight},\n\t\t\tAdvance: gwidth,\n\t\t\tAscent: 0,\n\t\t\tDescent: 0,\n\t\t}\n\n\t\t//increment and reset if requried\n\t\tx++\n\t\tif x >= float32(charPerLines) {\n\t\t\tx = 0\n\t\t\ty++\n\t\t}\n\t}\n\n\treturn f\n}",
"func (pmp *PngMediaParser) LooksLikeFormat(data []byte) bool {\n return bytes.Compare(data[:len(PngSignature)], PngSignature[:]) == 0\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetWidth(request *requests.FPDFBitmap_GetWidth) (*responses.FPDFBitmap_GetWidth, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twidth := C.FPDFBitmap_GetWidth(bitmapHandle.handle)\n\treturn &responses.FPDFBitmap_GetWidth{\n\t\tWidth: int(width),\n\t}, nil\n}",
"func (size *BitmapSize) Height() int16 {\n\treturn int16(size.handle.height)\n}",
"func DecodeConfig(r io.Reader) (config image.Config, err error) {\n\t// We only support those BMP images that are a BITMAPFILEHEADER\n\t// immediately followed by a BITMAPINFOHEADER.\n\tconst (\n\t\tfileHeaderLen = 14\n\t\tinfoHeaderLen = 40\n\t)\n\tvar b [1024]byte\n\tif _, err = io.ReadFull(r, b[:fileHeaderLen+infoHeaderLen]); err != nil {\n\t\treturn\n\t}\n\tif string(b[:2]) != \"BM\" {\n\t\terr = errors.New(\"bmp: invalid format\")\n\t\treturn\n\t}\n\toffset := readUint32(b[10:14])\n\tif readUint32(b[14:18]) != infoHeaderLen {\n\t\terr = ErrUnsupported\n\t\treturn\n\t}\n\twidth := int(readUint32(b[18:22]))\n\theight := int(readUint32(b[22:26]))\n\tif width < 0 || height < 0 {\n\t\terr = ErrUnsupported\n\t\treturn\n\t}\n\t// We only support 1 plane, 8 or 24 bits per pixel and no compression.\n\tplanes, bpp, compression := readUint16(b[26:28]), readUint16(b[28:30]), readUint32(b[30:34])\n\tif planes != 1 || compression != 0 {\n\t\terr = ErrUnsupported\n\t\treturn\n\t}\n\tswitch bpp {\n\tcase 8:\n\t\tif offset != fileHeaderLen+infoHeaderLen+256*4 {\n\t\t\terr = ErrUnsupported\n\t\t\treturn\n\t\t}\n\t\t_, err = io.ReadFull(r, b[:256*4])\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tpcm := make(color.Palette, 256)\n\t\tfor i := range pcm {\n\t\t\t// BMP images are stored in BGR order rather than RGB order.\n\t\t\t// Every 4th byte is padding.\n\t\t\tpcm[i] = color.RGBA{b[4*i+2], b[4*i+1], b[4*i+0], 0xFF}\n\t\t}\n\t\treturn image.Config{ColorModel: pcm, Width: width, Height: height}, nil\n\tcase 24:\n\t\tif offset != fileHeaderLen+infoHeaderLen {\n\t\t\terr = ErrUnsupported\n\t\t\treturn\n\t\t}\n\t\treturn image.Config{ColorModel: color.RGBAModel, Width: width, Height: height}, nil\n\t}\n\terr = ErrUnsupported\n\treturn\n}",
"func (s *StickerSet) GetStickerFormat() (value StickerFormatClass) {\n\tif s == nil {\n\t\treturn\n\t}\n\treturn s.StickerFormat\n}",
"func (o *AutoscalerResourceLimitsGPULimit) GetType() (value string, ok bool) {\n\tok = o != nil && o.bitmap_&2 != 0\n\tif ok {\n\t\tvalue = o.type_\n\t}\n\treturn\n}",
"func (pipe *pipe) SampleFormat() SampleFormat {\n\treturn pipe.format\n}",
"func ChoosePixelFormatARB(hdc unsafe.Pointer, piAttribIList unsafe.Pointer, pfAttribFList unsafe.Pointer, nMaxFormats unsafe.Pointer, piFormats unsafe.Pointer, nNumFormats unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall6(gpChoosePixelFormatARB, 6, uintptr(hdc), uintptr(piAttribIList), uintptr(pfAttribFList), uintptr(nMaxFormats), uintptr(piFormats), uintptr(nNumFormats))\n\treturn (unsafe.Pointer)(ret)\n}",
"func (job *Job) GetValidFormat() (string, error) {\n\tformat := strings.Trim(strings.ToLower(filepath.Ext(job.RunOptions.OutputFileName)), \".\")\n\tswitch {\n\tcase job.RunOptions.OutputFileName == \"\": //no outputfile specified, assume one html per each inputfile\n\t\tformat = \"html\"\n\tcase format == \"\": //outputfile specified but without an extension, return an error\n\t\treturn \"\", fmt.Errorf(\"must specify an extension for output file : %s\", job.RunOptions.OutputFileName)\n\tcase format == \"html\": //if an html outputfile is specified, currently >1 input file are not allowed\n\t\tif len(job.RunOptions.InputFileNames) > 1 {\n\t\t\treturn \"\", fmt.Errorf(\"merging generated html files into one html file is not supported\")\n\t\t}\n\tcase format == \"docx\": //any number of inputfiles is acceptable\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"unsupported output format: %s\", format)\n\t}\n\treturn format, nil\n}",
"func (p *btrfsPool) FsType() string {\n\treturn \"btrfs\"\n}",
"func NewFzBitmapRef(ref unsafe.Pointer) *FzBitmap {\n\treturn (*FzBitmap)(ref)\n}",
"func (dw *DrawingWand) GetFillRule() FillRule {\n\treturn FillRule(C.MagickDrawGetFillRule(dw.dw))\n}",
"func (dw *DrawingWand) GetFontFamily() string {\n\tcsfamily := C.MagickDrawGetFontFamily(dw.dw)\n\tdefer C.MagickRelinquishMemory(unsafe.Pointer(csfamily))\n\treturn C.GoString(csfamily)\n}",
"func GetPixelFormatAttribfvARB(hdc unsafe.Pointer, iPixelFormat unsafe.Pointer, iLayerPlane unsafe.Pointer, nAttributes unsafe.Pointer, piAttributes unsafe.Pointer, pfValues unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall6(gpGetPixelFormatAttribfvARB, 6, uintptr(hdc), uintptr(iPixelFormat), uintptr(iLayerPlane), uintptr(nAttributes), uintptr(piAttributes), uintptr(pfValues))\n\treturn (unsafe.Pointer)(ret)\n}"
] | [
"0.63094467",
"0.6114141",
"0.59529185",
"0.5815685",
"0.57419527",
"0.5739513",
"0.5727841",
"0.5699316",
"0.5468866",
"0.5393432",
"0.5382743",
"0.53703755",
"0.53322226",
"0.5302335",
"0.5235728",
"0.51931506",
"0.5190145",
"0.5149247",
"0.51159865",
"0.5110581",
"0.5072763",
"0.5022012",
"0.5008282",
"0.49534613",
"0.4923168",
"0.49225962",
"0.4911907",
"0.4901167",
"0.48729655",
"0.48587638",
"0.48415202",
"0.4833342",
"0.48306525",
"0.48267075",
"0.48096362",
"0.4777142",
"0.4670753",
"0.4613123",
"0.45795652",
"0.45575625",
"0.4541438",
"0.4538866",
"0.4522553",
"0.44678336",
"0.4443071",
"0.44399667",
"0.44336134",
"0.44301248",
"0.44173992",
"0.4386091",
"0.4362218",
"0.4347289",
"0.4345113",
"0.4339775",
"0.43397525",
"0.4337282",
"0.43242437",
"0.43235928",
"0.43016046",
"0.43005776",
"0.4295915",
"0.42801404",
"0.4264211",
"0.42551404",
"0.42507422",
"0.42473453",
"0.42415103",
"0.42403245",
"0.423761",
"0.42353702",
"0.42247847",
"0.42187098",
"0.42024896",
"0.41823256",
"0.41784024",
"0.41736668",
"0.41705495",
"0.41617647",
"0.41389424",
"0.41231903",
"0.41173673",
"0.41150576",
"0.41019008",
"0.41017717",
"0.4097369",
"0.4096772",
"0.40942177",
"0.4076636",
"0.4076628",
"0.4076323",
"0.40707967",
"0.40610322",
"0.40609357",
"0.4054932",
"0.40504432",
"0.4044193",
"0.40398073",
"0.40372744",
"0.4036175",
"0.40316713"
] | 0.79110163 | 0 |
FPDFBitmap_FillRect fills a rectangle in a bitmap. This function sets the color and (optionally) alpha value in the specified region of the bitmap. NOTE: If the alpha channel is used, this function does NOT composite the background with the source color, instead the background will be replaced by the source color and the alpha. If the alpha channel is not used, the alpha parameter is ignored. | func (p *PdfiumImplementation) FPDFBitmap_FillRect(request *requests.FPDFBitmap_FillRect) (*responses.FPDFBitmap_FillRect, error) {
p.Lock()
defer p.Unlock()
bitmapHandle, err := p.getBitmapHandle(request.Bitmap)
if err != nil {
return nil, err
}
C.FPDFBitmap_FillRect(bitmapHandle.handle, C.int(request.Left), C.int(request.Top), C.int(request.Width), C.int(request.Height), C.ulong(request.Color))
return &responses.FPDFBitmap_FillRect{}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (c *Canvas) FillRectangle(brush Brush, bounds Rectangle) error {\n\treturn c.rectangle(brush, nullPenSingleton, bounds, 1)\n}",
"func (cv *Canvas) FillRect(x, y, w, h float64) {\n\tp0 := cv.tf(vec{x, y})\n\tp1 := cv.tf(vec{x, y + h})\n\tp2 := cv.tf(vec{x + w, y + h})\n\tp3 := cv.tf(vec{x + w, y})\n\n\tdata := [4][2]float64{{p0[0], p0[1]}, {p1[0], p1[1]}, {p2[0], p2[1]}, {p3[0], p3[1]}}\n\n\tcv.drawShadow(data[:], nil, false)\n\n\tstl := cv.backendFillStyle(&cv.state.fill, 1)\n\tcv.b.Fill(&stl, data[:], false)\n}",
"func (r Rectangle) Fill(renderer Renderer, color api.RGBA) {\n\trenderer.FillRect(r.Transformation(), color)\n}",
"func (d *Device) FillRectangle(x, y, width, height int16, c color.RGBA) error {\n\td.startWrite()\n\terr := d.fillRectangle(x, y, width, height, c)\n\td.endWrite()\n\treturn err\n}",
"func (fb *FrameBuffer) Fill(rect _core.Rect, c color.Color) {\n\tfor i := rect.Min.Y; i < rect.Max.Y; i++ {\n\t\tfor j := rect.Min.X; j < rect.Max.X; j++ {\n\t\t\tfb.SetColorAt(int(j), int(i), c)\n\t\t}\n\t}\n}",
"func (style fillStyle) Rect(canvas *pdf.Canvas, rect pdf.Rectangle) {\n\tvar path pdf.Path\n\tpath.Rectangle(rect)\n\n\tcanvas.SetColor(style.R, style.G, style.B)\n\tcanvas.Fill(&path)\n}",
"func (pg *Polygon) Fill(c color.Color) {\n\t// Reset the rgba of the polygon\n\tbounds := pg.r.Bounds()\n\trect := image.Rect(0, 0, bounds.Max.X, bounds.Max.Y)\n\trgba := image.NewRGBA(rect)\n\tminx := pg.Rect2.Min.X()\n\tminy := pg.Rect2.Min.Y()\n\tfor x := 0; x < bounds.Max.X; x++ {\n\t\tfor y := 0; y < bounds.Max.Y; y++ {\n\t\t\tif pg.Contains(float64(x)+minx, float64(y)+miny) {\n\t\t\t\trgba.Set(x, y, c)\n\t\t\t}\n\t\t}\n\t}\n\tpg.r = rgba\n}",
"func (c *Canvas) FillRectanglePixels(brush Brush, bounds Rectangle) error {\n\treturn c.rectanglePixels(brush, nullPenSingleton, bounds, 1)\n}",
"func (c *Canvas) GradientFillRectangle(color1, color2 Color, orientation Orientation, bounds Rectangle) error {\n\treturn c.GradientFillRectanglePixels(color1, color2, orientation, RectangleFrom96DPI(bounds, c.DPI()))\n}",
"func (c *Canvas) FillRoundedRectangle(brush Brush, bounds Rectangle, ellipseSize Size) error {\n\treturn c.roundedRectangle(brush, nullPenSingleton, bounds, ellipseSize, 1)\n}",
"func (this *RectangleShape) SetFillColor(color Color) {\n\tC.sfRectangleShape_setFillColor(this.cptr, color.toC())\n}",
"func (w *windowImpl) Fill(dr image.Rectangle, src color.Color, op draw.Op) {\n\tpanic(\"not implemented\") // TODO: Implement\n}",
"func (d *Draw) RectByFill(r Rect, thickness int32, colorBorder, colorInner sdl.Color) {\n\td.setColor(colorBorder)\n\td.renderer.FillRect(r.SDLRect())\n\n\td.setColor(colorInner)\n\td.renderer.FillRect(&sdl.Rect{\n\t\tX: r.X + thickness,\n\t\tY: r.Y + thickness,\n\t\tW: r.W - 2*thickness,\n\t\tH: r.H - 2*thickness,\n\t})\n}",
"func (c *Canvas) FillRoundedRectanglePixels(brush Brush, bounds Rectangle, ellipseSize Size) error {\n\treturn c.roundedRectanglePixels(brush, nullPenSingleton, bounds, ellipseSize, 1)\n}",
"func (obj *Device) ColorFill(\n\tsurface *Surface,\n\trect *RECT,\n\tcolor COLOR,\n) Error {\n\tret, _, _ := syscall.Syscall6(\n\t\tobj.vtbl.ColorFill,\n\t\t4,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(unsafe.Pointer(surface)),\n\t\tuintptr(unsafe.Pointer(rect)),\n\t\tuintptr(color),\n\t\t0,\n\t\t0,\n\t)\n\treturn toErr(ret)\n}",
"func (m RGBImage) Fill(vl RGB) {\n\tl := m.Area()\n\tfor i := 0; i < l; i++ {\n\t\tm.Pixels[i] = vl\n\t}\n}",
"func regionFill(x, y, w, h openvg.VGfloat, color string) {\n\topenvg.FillColor(color)\n\topenvg.Rect(x, y, w, h)\n\topenvg.FillColor(textcolor)\n}",
"func (r *ImageRef) DrawRect(ink ColorRGBA, left int, top int, width int, height int, fill bool) error {\n\terr := vipsDrawRect(r.image, ink, left, top, width, height, fill)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func (c *Canvas) GradientFillRectanglePixels(color1, color2 Color, orientation Orientation, bounds Rectangle) error {\n\tvertices := [2]win.TRIVERTEX{\n\t\t{\n\t\t\tX: int32(bounds.X),\n\t\t\tY: int32(bounds.Y),\n\t\t\tRed: uint16(color1.R()) * 256,\n\t\t\tGreen: uint16(color1.G()) * 256,\n\t\t\tBlue: uint16(color1.B()) * 256,\n\t\t\tAlpha: 0,\n\t\t}, {\n\t\t\tX: int32(bounds.X + bounds.Width),\n\t\t\tY: int32(bounds.Y + bounds.Height),\n\t\t\tRed: uint16(color2.R()) * 256,\n\t\t\tGreen: uint16(color2.G()) * 256,\n\t\t\tBlue: uint16(color2.B()) * 256,\n\t\t\tAlpha: 0,\n\t\t},\n\t}\n\n\tindices := win.GRADIENT_RECT{\n\t\tUpperLeft: 0,\n\t\tLowerRight: 1,\n\t}\n\n\tvar o uint32\n\tif orientation == Vertical {\n\t\to = 1\n\t}\n\n\tif !win.GradientFill(c.hdc, &vertices[0], 2, unsafe.Pointer(&indices), 1, o) {\n\t\treturn newError(\"GradientFill failed\")\n\t}\n\n\treturn nil\n}",
"func (cons *VgaTextConsole) Fill(x, y, width, height uint32, fg, bg uint8) {\n\tvar (\n\t\tclr = (((uint16(bg) << 4) | uint16(fg)) << 8) | cons.clearChar\n\t\trowOffset, colOffset uint32\n\t)\n\n\t// clip rectangle\n\tif x == 0 {\n\t\tx = 1\n\t} else if x >= cons.width {\n\t\tx = cons.width\n\t}\n\n\tif y == 0 {\n\t\ty = 1\n\t} else if y >= cons.height {\n\t\ty = cons.height\n\t}\n\n\tif x+width-1 > cons.width {\n\t\twidth = cons.width - x + 1\n\t}\n\n\tif y+height-1 > cons.height {\n\t\theight = cons.height - y + 1\n\t}\n\n\trowOffset = ((y - 1) * cons.width) + (x - 1)\n\tfor ; height > 0; height, rowOffset = height-1, rowOffset+cons.width {\n\t\tfor colOffset = rowOffset; colOffset < rowOffset+width; colOffset++ {\n\t\t\tcons.fb[colOffset] = clr\n\t\t}\n\t}\n}",
"func (p *Page) FillRGB(r, g, b float64) {\n\tfmt.Fprint(p.contents, r, g, b, \" rg \")\n}",
"func (el *Fill) Rect() {}",
"func (b Buffer) Fill(ch rune, fg, bg Attribute) {\n\tfor x := b.Area.Min.X; x < b.Area.Max.X; x++ {\n\t\tfor y := b.Area.Min.Y; y < b.Area.Max.Y; y++ {\n\t\t\tb.Set(x, y, Cell{ch, fg, bg})\n\t\t}\n\t}\n}",
"func (c *Canvas) DrawBitmapWithOpacityPixels(bmp *Bitmap, bounds Rectangle, opacity byte) error {\n\tif bmp == nil {\n\t\treturn newError(\"bmp cannot be nil\")\n\t}\n\n\treturn bmp.alphaBlend(c.hdc, bounds, opacity)\n}",
"func (m GrayImage) Fill(vl byte) {\n\tl := m.Area()\n\tfor i := 0; i < l; i++ {\n\t\tm.Pixels[i] = vl\n\t}\n}",
"func (win *window) Rectangle(rect image.Rectangle, fill bool) {\n\tr := xgb.Rectangle{\n\t\tX: int16(rect.Min.X),\n\t\tY: int16(rect.Min.Y),\n\t\tWidth: uint16(rect.Dx()),\n\t\tHeight: uint16(rect.Dy()),\n\t}\n\tif fill {\n\t\txwin.PolyFillRectangle(win.id, win.gc, []xgb.Rectangle{r})\n\t}\n\txwin.PolyRectangle(win.id, win.gc, []xgb.Rectangle{r})\n}",
"func (plot Plot) Fill(col color.RGBA) {\n\tif bgCache == nil || bgCache.Bounds() != plot.Bounds() || bgColor != col {\n\t\tbgCache = background(plot.Bounds(), col)\n\t\tbgColor = col\n\t}\n\tcopy(plot.Pix, bgCache.Pix)\n}",
"func (c *Canvas) DrawBitmapPartWithOpacityPixels(bmp *Bitmap, dst, src Rectangle, opacity byte) error {\n\tif bmp == nil {\n\t\treturn newError(\"bmp cannot be nil\")\n\t}\n\n\treturn bmp.alphaBlendPart(c.hdc, dst, src, opacity)\n}",
"func (c *Canvas) DrawBitmapWithOpacity(bmp *Bitmap, bounds Rectangle, opacity byte) error {\n\treturn c.DrawBitmapWithOpacityPixels(bmp, RectangleFrom96DPI(bounds, c.DPI()), opacity)\n}",
"func (dw *DrawingWand) SetFillOpacity(opacity float64) {\n\tC.DrawSetFillOpacity(dw.dw, C.double(opacity))\n}",
"func (self *Graphics) BeginFill(color int, alpha int) *Graphics{\n return &Graphics{self.Object.Call(\"beginFill\", color, alpha)}\n}",
"func background(r, g, b int) {\n\tcanvas.Rect(0, 0, canvasWidth, canvasHeight, canvas.RGB(r, g, b))\n}",
"func createBoxFillWriter(rect rect, colour termbox.Attribute) AttributeWriter {\n\treturn func(fg, bg termbox.Attribute, point point) (termbox.Attribute, termbox.Attribute) {\n\t\tif rect.PointWithinRect(point) {\n\t\t\treturn fg, colour\n\t\t} else {\n\t\t\treturn fg, bg\n\t\t}\n\t}\n}",
"func (c *Canvas) DrawBitmapPart(bmp *Bitmap, dst, src Rectangle) error {\n\treturn c.DrawBitmapPartWithOpacityPixels(bmp, dst, src, 0xff)\n}",
"func drawRedRect(ops *op.Ops) {\n\tdefer clip.Rect{Max: image.Pt(100, 100)}.Push(ops).Pop()\n\tpaint.ColorOp{Color: color.NRGBA{R: 0x80, A: 0xFF}}.Add(ops)\n\tpaint.PaintOp{}.Add(ops)\n}",
"func (pic *Picture) Fill(contour DrawableContour) {\n\tpendiam := pic.currentPen.diameter\n\tpic.surface.AddContour(contour, pendiam, nil, pic.currentColor)\n}",
"func fill(pix []byte, c color.RGBA) {\n\tfor i := 0; i < len(pix); i += 4 {\n\t\tpix[i] = c.R\n\t\tpix[i+1] = c.G\n\t\tpix[i+2] = c.B\n\t\tpix[i+3] = c.A\n\t}\n}",
"func (d *Device) FillRectangleWithBuffer(x, y, width, height int16, buffer []color.RGBA) error {\n\ti, j := d.Size()\n\tif x < 0 || y < 0 || width <= 0 || height <= 0 ||\n\t\tx >= i || (x+width) > i || y >= j || (y+height) > j {\n\t\treturn errors.New(\"rectangle coordinates outside display area\")\n\t}\n\tif int32(width)*int32(height) != int32(len(buffer)) {\n\t\treturn errors.New(\"buffer length does not match with rectangle size\")\n\t}\n\td.startWrite()\n\td.setWindow(x, y, width, height)\n\n\tk := int32(width) * int32(height)\n\tdata := make([]uint8, d.batchLength*2)\n\toffset := int32(0)\n\tfor k > 0 {\n\t\tfor i := int32(0); i < d.batchLength; i++ {\n\t\t\tif offset+i < int32(len(buffer)) {\n\t\t\t\tc565 := RGBATo565(buffer[offset+i])\n\t\t\t\tc1 := uint8(c565 >> 8)\n\t\t\t\tc2 := uint8(c565)\n\t\t\t\tdata[i*2] = c1\n\t\t\t\tdata[i*2+1] = c2\n\t\t\t}\n\t\t}\n\t\t// The DC pin is already set to data in the setWindow call, so we don't\n\t\t// have to set it here.\n\t\tif k >= d.batchLength {\n\t\t\td.bus.Tx(data, nil)\n\t\t} else {\n\t\t\td.bus.Tx(data[:k*2], nil)\n\t\t}\n\t\tk -= d.batchLength\n\t\toffset += d.batchLength\n\t}\n\td.endWrite()\n\treturn nil\n}",
"func (c *Canvas) DrawBitmapPartWithOpacity(bmp *Bitmap, dst, src Rectangle, opacity byte) error {\n\tdpi := c.DPI()\n\treturn c.DrawBitmapPartWithOpacityPixels(bmp, RectangleFrom96DPI(dst, dpi), RectangleFrom96DPI(src, dpi), opacity)\n}",
"func DrawRect(img *ebiten.Image, bounds vec2.Rect, clr color.Color) {\n\trectImg, _ := ebiten.NewImage(\n\t\tint(bounds.Width()),\n\t\tint(bounds.Height()),\n\t\tebiten.FilterDefault,\n\t)\n\tfor x := 0; x < int(bounds.Width()); x++ {\n\t\trectImg.Set(x, 0, clr)\n\t\trectImg.Set(x, int(bounds.Height())-1, clr)\n\t}\n\tfor y := 0; y < int(bounds.Height()); y++ {\n\t\trectImg.Set(0, y, clr)\n\t\trectImg.Set(int(bounds.Width())-1, y, clr)\n\t}\n\timg.DrawImage(rectImg, &ebiten.DrawImageOptions{\n\t\tGeoM: ebiten.TranslateGeo(bounds.X(), bounds.Y()),\n\t})\n}",
"func PaintFill(image [][]rune, row, col int, newColor rune) {\n\tpaintFillHelper(image, row, col, image[row][col], newColor)\n}",
"func (self *TraitPixbuf) Fill(pixel uint32) {\n\tC.gdk_pixbuf_fill(self.CPointer, C.guint32(pixel))\n\treturn\n}",
"func (m IntGrayImage) Fill(vl int) {\n\tl := m.Area()\n\tfor i := 0; i < l; i++ {\n\t\tm.Pixels[i] = vl\n\t}\n}",
"func (c *Canvas) DrawRectangle(pen Pen, bounds Rectangle) error {\n\treturn c.rectangle(nullBrushSingleton, pen, bounds, 0)\n}",
"func (pic *Picture) FillDraw(contour DrawableContour) {\n\tpendiam := pic.currentPen.diameter\n\tpic.surface.SetOption(pic.currentPen.style)\n\tpic.surface.AddContour(contour, pendiam, pic.currentColor, pic.currentColor)\n}",
"func (this *RectangleShape) GetFillColor() (color Color) {\n\tcolor.fromC(C.sfRectangleShape_getFillColor(this.cptr))\n\treturn\n}",
"func (a *PixelSubArray) fillBetween(xl, xr, y int) {\n\tyRow := y - a.yStart\n\txByteL := xl/8 - a.xStartByte\n\txByteR := xr/8 - a.xStartByte\n\n\t// Fill in the partial bits on left\n\txBit := uint8(xl % 8)\n\tfor i := xBit; i < 8; i++ {\n\t\ta.bytes[yRow][xByteL] |= (1 << i)\n\t}\n\n\t// Fill in the partial bits on right\n\txBit = uint8(xr % 8)\n\tfor i := xBit; i < 255; i-- {\n\t\ta.bytes[yRow][xByteR] |= (1 << i)\n\t}\n\n\t// Fill in bytes in between\n\tfor i := xByteL + 1; i < xByteR; i++ {\n\t\ta.bytes[yRow][i] |= 0xFF\n\t}\n}",
"func (pg *Polygon) FillInverse(c color.Color) {\n\tbounds := pg.r.Bounds()\n\trect := image.Rect(0, 0, bounds.Max.X, bounds.Max.Y)\n\trgba := image.NewRGBA(rect)\n\tfor x := 0; x < bounds.Max.X; x++ {\n\t\tfor y := 0; y < bounds.Max.Y; y++ {\n\t\t\tif !pg.ConvexContains(float64(x), float64(y)) {\n\t\t\t\trgba.Set(x, y, c)\n\t\t\t}\n\t\t}\n\t}\n\tpg.r = rgba\n}",
"func NewFilledBuffer(x0, y0, x1, y1 int, ch rune, fg, bg Attribute) Buffer {\n\tbuf := NewBuffer()\n\tbuf.Area.Min = image.Pt(x0, y0)\n\tbuf.Area.Max = image.Pt(x1, y1)\n\n\tfor x := buf.Area.Min.X; x < buf.Area.Max.X; x++ {\n\t\tfor y := buf.Area.Min.Y; y < buf.Area.Max.Y; y++ {\n\t\t\tbuf.Set(x, y, Cell{ch, fg, bg})\n\t\t}\n\t}\n\treturn buf\n}",
"func (c *Canvas) rectangle(brush Brush, pen Pen, bounds Rectangle, sizeCorrection int) error {\n\treturn c.rectanglePixels(brush, pen, RectangleFrom96DPI(bounds, c.DPI()), sizeCorrection)\n}",
"func (c *Canvas) Rect(x, y, w, h float64, color color.RGBA) {\n\tx, y = dimen(x, y, c.Width, c.Height)\n\tw = pct(w, float64(c.Width))\n\th = pct(h, float64(c.Height))\n\tAbsCornerRect(c.Container, int(x-(w/2)), int(y-(h/2)), int(w), int(h), color)\n}",
"func (cv *Canvas) ClearRect(x, y, w, h float64) {\n\tp0 := cv.tf(vec{x, y})\n\tp1 := cv.tf(vec{x, y + h})\n\tp2 := cv.tf(vec{x + w, y + h})\n\tp3 := cv.tf(vec{x + w, y})\n\tdata := [4][2]float64{{p0[0], p0[1]}, {p1[0], p1[1]}, {p2[0], p2[1]}, {p3[0], p3[1]}}\n\n\tcv.b.Clear(data)\n}",
"func (slot *fyFlexboxRow) Fill(area frenyard.Area2i, vertical bool) {\n\tfor k := range slot.area {\n\t\tif !vertical {\n\t\t\t// Rows perpendicular to X\n\t\t\tslot.area[k].X = area.X\n\t\t} else {\n\t\t\t// Rows perpendicular to Y\n\t\t\tslot.area[k].Y = area.Y\n\t\t}\n\t}\n\tslot.fullArea = area\n}",
"func DrawRect(m draw.Image, x1, y1, x2, y2 int) {\n\tDrawHLine(m, x1, y1, x2)\n\tDrawHLine(m, x1, y2, x2)\n\tDrawVLine(m, x1, y1, y2)\n\tDrawVLine(m, x2, y1, y2)\n}",
"func (dw *DrawingWand) SetFillColor(fillWand *PixelWand) {\n\tC.MagickDrawSetFillColor(dw.dw, fillWand.pw)\n}",
"func (s *Surface) DrawRect(t DrawType, r geo.Rect) {\n\ts.Ctx.Call(string(t)+\"Rect\", math.Floor(r.X), math.Floor(r.Y), math.Floor(r.W), math.Floor(r.H))\n}",
"func drawOverlappingRectangles(ops *op.Ops) {\n\t// Draw a red rectangle.\n\tcl := clip.Rect{Max: image.Pt(100, 50)}.Push(ops)\n\tpaint.ColorOp{Color: color.NRGBA{R: 0x80, A: 0xFF}}.Add(ops)\n\tpaint.PaintOp{}.Add(ops)\n\tcl.Pop()\n\n\t// Draw a green rectangle.\n\tcl = clip.Rect{Max: image.Pt(50, 100)}.Push(ops)\n\tpaint.ColorOp{Color: color.NRGBA{G: 0x80, A: 0xFF}}.Add(ops)\n\tpaint.PaintOp{}.Add(ops)\n\tcl.Pop()\n}",
"func (cv *Canvas) Fill() {\n\tcv.fillPath(&cv.path, matIdentity())\n}",
"func (c *Canvas) FillEllipse(brush Brush, bounds Rectangle) error {\n\treturn c.ellipse(brush, nullPenSingleton, bounds, 1)\n}",
"func RoundedRectangle(path draw2d.PathBuilder, x1, y1, x2, y2, arcWidth, arcHeight float64) {\n\tarcWidth = arcWidth / 2\n\tarcHeight = arcHeight / 2\n\tpath.MoveTo(x1, y1+arcHeight)\n\tpath.QuadCurveTo(x1, y1, x1+arcWidth, y1)\n\tpath.LineTo(x2-arcWidth, y1)\n\tpath.QuadCurveTo(x2, y1, x2, y1+arcHeight)\n\tpath.LineTo(x2, y2-arcHeight)\n\tpath.QuadCurveTo(x2, y2, x2-arcWidth, y2)\n\tpath.LineTo(x1+arcWidth, y2)\n\tpath.QuadCurveTo(x1, y2, x1, y2-arcHeight)\n\tpath.Close()\n}",
"func (b *bookie) Fill(ctx context.Context, rangeID roachpb.RangeID) bool {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\t// Lookup the reservation.\n\tres, ok := b.mu.reservationsByRangeID[rangeID]\n\tif !ok {\n\t\tif log.V(2) {\n\t\t\tlog.Infof(ctx, \"[r%d] reservation not found\", rangeID)\n\t\t}\n\t\treturn false\n\t}\n\n\tb.fillReservationLocked(ctx, res)\n\treturn true\n}",
"func (s *Surface) ClearRect(r geo.Rect) {\n\ts.Ctx.Call(\"clearRect\", math.Floor(r.X), math.Floor(r.Y), math.Floor(r.W), math.Floor(r.H))\n}",
"func fill(b *Board, t TileColor) {\n\tfor y := 0; y < BOARD_HEIGHT; y++ {\n\t\tfor x := 0; x < BOARD_WIDTH; x++ {\n\t\t\tb.SetTile(t, x, y)\n\t\t}\n\t}\n}",
"func strokeRect(ops *op.Ops) {\n\tconst r = 10\n\tbounds := image.Rect(20, 20, 80, 80)\n\trrect := clip.RRect{Rect: bounds, SE: r, SW: r, NW: r, NE: r}\n\tpaint.FillShape(ops, red,\n\t\tclip.Stroke{\n\t\t\tPath: rrect.Path(ops),\n\t\t\tWidth: 4,\n\t\t}.Op(),\n\t)\n}",
"func (self *Graphics) SetFillAlphaA(member int) {\n self.Object.Set(\"fillAlpha\", member)\n}",
"func (c *canvasRenderer) Fill(fill Fill) {\n\tc.fillPath(c.canvasPath, fill)\n}",
"func DrawRect(screen *ebiten.Image, rect *resolv.Rectangle, color color.Color) {\n\tx, y := float64(rect.X)+1, float64(rect.Y)\n\tw, h := float64(rect.W)-1, float64(rect.H)-1\n\tebitenutil.DrawLine(screen, x, y, x, y+h+1, color)\n\tebitenutil.DrawLine(screen, x+w, y, x+w, y+h, color)\n\n\tebitenutil.DrawLine(screen, x, y, x+w, y, color)\n\tebitenutil.DrawLine(screen, x, y+h, x+w, y+h, color)\n}",
"func (obj *Device) StretchRect(\n\tsourceSurface *Surface,\n\tsourceRect *RECT,\n\tdestSurface *Surface,\n\tdestRect *RECT,\n\tfilter TEXTUREFILTERTYPE,\n) Error {\n\tret, _, _ := syscall.Syscall6(\n\t\tobj.vtbl.StretchRect,\n\t\t6,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(unsafe.Pointer(sourceSurface)),\n\t\tuintptr(unsafe.Pointer(sourceRect)),\n\t\tuintptr(unsafe.Pointer(destSurface)),\n\t\tuintptr(unsafe.Pointer(destRect)),\n\t\tuintptr(filter),\n\t)\n\treturn toErr(ret)\n}",
"func AbsRect(cont *fyne.Container, x, y, w, h int, color color.RGBA) {\n\tfx, fy, fw, fh := float32(x), float32(y), float32(w), float32(h)\n\tr := &canvas.Rectangle{FillColor: color}\n\tr.Move(fyne.Position{X: fx - (fw / 2), Y: fy - (fh / 2)})\n\tr.Resize(fyne.Size{Width: fw, Height: fh})\n\tcont.AddObject(r)\n}",
"func Rect(img *image.RGBA, x1, y1, x2, y2, width int, col color.Color) {\n\tfor i := 0; i < width; i++ {\n\t\tHLine(img, x1, y1+i, x2, col)\n\t\tHLine(img, x1, y2+i, x2, col)\n\t\tVLine(img, x1+i, y1, y2, col)\n\t\tVLine(img, x2+i, y1, y2, col)\n\t}\n}",
"func rect(img *image.NRGBA, x1, y1, x2, y2 int, col color.Color) {\r\n\thLine(img, x1, y1, x2, col)\r\n\thLine(img, x1, y2, x2, col)\r\n\tvLine(img, x1, y1, y2, col)\r\n\tvLine(img, x2, y1, y2, col)\r\n}",
"func (a *HighlightRectArgs) SetColor(color dom.RGBA) *HighlightRectArgs {\n\ta.Color = &color\n\treturn a\n}",
"func fillPolygon(c vg.Canvas, clr color.Color, pts []vg.Point) {\n\tif len(pts) == 0 {\n\t\treturn\n\t}\n\n\tc.SetColor(clr)\n\tp := make(vg.Path, 0, len(pts)+1)\n\tp.Move(pts[0])\n\tfor _, pt := range pts[1:] {\n\t\tp.Line(pt)\n\t}\n\tp.Close()\n\tc.Fill(p)\n}",
"func (canvas *Canvas) Fill(p *Path) {\n\tio.Copy(canvas.contents, &p.buf)\n\twriteCommand(canvas.contents, \"f\")\n}",
"func (gd Grid) Fill(c Cell) {\n\tif gd.Ug == nil {\n\t\treturn\n\t}\n\tw := gd.Rg.Max.X - gd.Rg.Min.X\n\tswitch {\n\tcase w >= 8:\n\t\tgd.fillcp(c)\n\tcase w == 1:\n\t\tgd.fillv(c)\n\tdefault:\n\t\tgd.fill(c)\n\t}\n}",
"func iRect(x, y, w, h int, color color.RGBA) *canvas.Rectangle {\n\tfx, fy, fw, fh := float32(x), float32(y), float32(w), float32(h)\n\tr := &canvas.Rectangle{FillColor: color}\n\tr.Move(fyne.Position{X: fx - (fw / 2), Y: fy - (fh / 2)})\n\tr.Resize(fyne.Size{Width: fw, Height: fh})\n\treturn r\n}",
"func NewRectangle(min pixel.Vec, max pixel.Vec, color color.Color) *imdraw.IMDraw {\n\trect := imdraw.New(nil)\n\n\trect.Color = color\n\trect.Push(min)\n\trect.Push(pixel.V(max.X, min.Y))\n\trect.Push(max)\n\trect.Push(pixel.V(min.X, max.Y))\n\trect.Polygon(0)\n\n\treturn rect\n}",
"func (imd *IMDraw) Rectangle(thickness float64) {\n\tif thickness == 0 {\n\t\timd.fillRectangle()\n\t} else {\n\t\timd.outlineRectangle(thickness)\n\t}\n}",
"func (p *P1D) Fill(x, y, w float64) {\n\tp.bng.fill(x, y, w)\n}",
"func (svgp *SvgPath) SetFillColor(clr color.Color) {\n\tsvgp.fillerColor = clr\n}",
"func (c *Canvas) DrawColorMask(t pixel.Target, matrix pixel.Matrix, mask color.Color) {\n\tc.sprite.DrawColorMask(t, matrix, mask)\n}",
"func (c *Canvas) DrawRoundedRectangle(pen Pen, bounds Rectangle, ellipseSize Size) error {\n\treturn c.roundedRectangle(nullBrushSingleton, pen, bounds, ellipseSize, 0)\n}",
"func (f *Framebuffer) Paint(r vnclib.Rectangle, colors []vnclib.Color) {\n\tif glog.V(4) {\n\t\tglog.Info(venuelib.FnNameWithArgs(r.String(), \"colors\"))\n\t}\n\t// TODO(kward): Implement double or triple buffering to reduce paint\n\t// interference.\n\tfor x := 0; x < int(r.Width); x++ {\n\t\tfor y := 0; y < int(r.Height); y++ {\n\t\t\tc := colors[x+y*int(r.Width)]\n\t\t\tf.fb.SetRGBA(x+int(r.X), y+int(r.Y), color.RGBA{uint8(c.R), uint8(c.G), uint8(c.B), 255})\n\t\t}\n\t}\n}",
"func (style strokeStyle) Rect(canvas *pdf.Canvas, rect pdf.Rectangle) {\n\tvar path pdf.Path\n\tpath.Rectangle(rect)\n\n\tcanvas.SetLineWidth(style.LineWidth)\n\tcanvas.SetStrokeColor(style.R, style.G, style.B)\n\tcanvas.Stroke(&path)\n}",
"func (win *Window) Fill(c color.Color) {\n\tC.sfRenderWindow_clear(win.win, sfmlColor(c))\n}",
"func (c *Canvas) DrawRectanglePixels(pen Pen, bounds Rectangle) error {\n\treturn c.rectanglePixels(nullBrushSingleton, pen, bounds, 0)\n}",
"func ColorMask(red, green, blue, alpha bool) {\n\tgl.ColorMask(red, green, blue, alpha)\n}",
"func (m *Matrix) SetFocusRect(r *Rectangle) {\n\tm.focus = r\n}",
"func (tb *Textbox) Fill(u rune) error {\n\tif !utf8.ValidRune(u) {\n\t\treturn errors.New(\"invalid rune\")\n\t}\n\n\tfor i := range tb.pixels {\n\t\ttb.pixels[i] = u\n\t}\n\treturn nil\n}",
"func AbsCornerRect(cont *fyne.Container, x, y, w, h int, color color.RGBA) {\n\tfx, fy, fw, fh := float32(x), float32(y), float32(w), float32(h)\n\tr := &canvas.Rectangle{FillColor: color}\n\tr.Move(fyne.Position{X: fx, Y: fy})\n\tr.Resize(fyne.Size{Width: fw, Height: fh})\n\tcont.AddObject(r)\n}",
"func paintFill(image [][]string, c string, y, x int) [][]string {\n\t//range check\n\tif y > len(image)-1 {\n\t\treturn image\n\t}\n\tif x > len(image[y])-1 {\n\t\treturn image\n\t}\n\t//dupe color check\n\tif image[y][x] == c {\n\t\treturn image\n\t}\n\t//identify origin color\n\torig := image[y][x]\n\t//color origin\n\tmImage := image\n\tmImage[y][x] = c\n\t//check for valid left\n\tif x > 0 && mImage[y][x-1] == orig {\n\t\tmImage = paintFill(mImage, c, y, x-1)\n\t}\n\t//check for valid right\n\tif x < len(mImage[y])-1 && mImage[y][x+1] == orig {\n\t\tmImage = paintFill(mImage, c, y, x+1)\n\t}\n\t//check for valid up\n\tif y > 0 && mImage[y-1][x] == orig {\n\t\tmImage = paintFill(mImage, c, y-1, x)\n\t}\n\t//check for valid down\n\tif y < len(mImage)-1 && mImage[y+1][x] == orig {\n\t\tmImage = paintFill(mImage, c, y+1, x)\n\t}\n\treturn mImage\n}",
"func frect(r image.Rectangle) f32.Rectangle {\n\treturn f32.Rectangle{\n\t\tMin: fpt(r.Min), Max: fpt(r.Max),\n\t}\n}",
"func (native *OpenGL) ColorMask(red bool, green bool, blue bool, alpha bool) {\n\tgl.ColorMask(red, green, blue, alpha)\n}",
"func (s *Screen) ProcessRect(input string) error {\n\tmatch := RectangleRegexp.FindStringSubmatch(input)\n\tif len(match) == 0 {\n\t\treturn fmt.Errorf(\"Failed regexp for rectangle: %s\", input)\n\t}\n\n\t// Turn the regexp matches into ints.\n\tvalues, err := advent.StringsToInts(match[1:])\n\tif err != nil {\n\t\treturn err\n\t}\n\twidth, height := values[0], values[1]\n\n\t// Fill in the pixels.\n\tfor x := 0; x < width; x++ {\n\t\tfor y := 0; y < height; y++ {\n\t\t\terr := s.Light(x, y)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (ele *ELEMENT) FillStyle(eval string) *ELEMENT { return ele.Attr(\"fillStyle\", eval) }",
"func (dw *DrawingWand) Rectangle(x1, y1, x2, y2 float64) {\n\tC.MagickDrawRectangle(dw.dw, C.double(x1), C.double(y1), C.double(x2), C.double(y2))\n}",
"func ColorMask(red Boolean, green Boolean, blue Boolean, alpha Boolean) {\n\tcred, _ := (C.GLboolean)(red), cgoAllocsUnknown\n\tcgreen, _ := (C.GLboolean)(green), cgoAllocsUnknown\n\tcblue, _ := (C.GLboolean)(blue), cgoAllocsUnknown\n\tcalpha, _ := (C.GLboolean)(alpha), cgoAllocsUnknown\n\tC.glColorMask(cred, cgreen, cblue, calpha)\n}",
"func (c *Canvas) DrawRoundedRectanglePixels(pen Pen, bounds Rectangle, ellipseSize Size) error {\n\treturn c.roundedRectanglePixels(nullBrushSingleton, pen, bounds, ellipseSize, 0)\n}",
"func Rect(path Path, x1, y1, x2, y2 float64) {\r\n\tpath.MoveTo(x1, y1)\r\n\tpath.LineTo(x2, y1)\r\n\tpath.LineTo(x2, y2)\r\n\tpath.LineTo(x1, y2)\r\n\tpath.Close()\r\n}",
"func (w *SVGWriter) Rect(x, y, width, height float64) {\n\tw.RectWithClass(x, y, width, height, \"\")\n}"
] | [
"0.6653222",
"0.6444132",
"0.62075186",
"0.6203206",
"0.60877097",
"0.5924585",
"0.5884623",
"0.5672627",
"0.5578452",
"0.5522598",
"0.5451546",
"0.5416682",
"0.5286218",
"0.5254311",
"0.52429575",
"0.5235257",
"0.52313817",
"0.5211918",
"0.51892614",
"0.51853544",
"0.5097211",
"0.5069888",
"0.5045094",
"0.49825808",
"0.4969351",
"0.4928698",
"0.49159694",
"0.4903225",
"0.48887825",
"0.48869148",
"0.48819426",
"0.48618573",
"0.48515344",
"0.48479074",
"0.47874206",
"0.4760078",
"0.47248802",
"0.47016943",
"0.4695241",
"0.46900672",
"0.46851984",
"0.4684088",
"0.46137133",
"0.45687106",
"0.44830897",
"0.44706225",
"0.44220883",
"0.44127297",
"0.43864733",
"0.43846115",
"0.43794018",
"0.43641487",
"0.436203",
"0.43451533",
"0.43283",
"0.4302652",
"0.42841667",
"0.4261016",
"0.42540962",
"0.42325807",
"0.4225337",
"0.42115834",
"0.42072713",
"0.4198378",
"0.41974613",
"0.41943496",
"0.4190003",
"0.4179134",
"0.41656876",
"0.41451338",
"0.41244447",
"0.4119382",
"0.41125983",
"0.41120338",
"0.4104669",
"0.40719676",
"0.40503657",
"0.4030631",
"0.40270984",
"0.40113568",
"0.40069503",
"0.39979714",
"0.39932305",
"0.39922887",
"0.39915258",
"0.397544",
"0.39551157",
"0.39413318",
"0.39378348",
"0.3928082",
"0.39227688",
"0.39066765",
"0.38978562",
"0.38846567",
"0.38833573",
"0.38683912",
"0.386325",
"0.38581103",
"0.38384044",
"0.38353306"
] | 0.68327314 | 0 |
FPDFBitmap_GetBuffer returns the data buffer of a bitmap. The stride may be more than width number of bytes per pixel Applications can use this function to get the bitmap buffer pointer, then manipulate any color and/or alpha values for any pixels in the bitmap. Use FPDFBitmap_GetFormat() to find out the format of the data. | func (p *PdfiumImplementation) FPDFBitmap_GetBuffer(request *requests.FPDFBitmap_GetBuffer) (*responses.FPDFBitmap_GetBuffer, error) {
p.Lock()
defer p.Unlock()
bitmapHandle, err := p.getBitmapHandle(request.Bitmap)
if err != nil {
return nil, err
}
// We need to calculate the buffer size, this is stride (bytes per bitmap line) * height.
stride := C.FPDFBitmap_GetStride(bitmapHandle.handle)
height := C.FPDFBitmap_GetHeight(bitmapHandle.handle)
size := int(stride * height)
// The pointer to the first byte of the bitmap buffer.
buffer := C.FPDFBitmap_GetBuffer(bitmapHandle.handle)
// We create a Go slice backed by a C array (without copying the original data).
data := unsafe.Slice((*byte)(unsafe.Pointer(buffer)), uint64(size))
return &responses.FPDFBitmap_GetBuffer{
Buffer: data,
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (b *Bitmap) Buffer() []byte {\n\tl := b.Rows() * b.Pitch()\n\treturn C.GoBytes(unsafe.Pointer(b.handle.buffer), C.int(l))\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetStride(request *requests.FPDFBitmap_GetStride) (*responses.FPDFBitmap_GetStride, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstride := C.FPDFBitmap_GetStride(bitmapHandle.handle)\n\treturn &responses.FPDFBitmap_GetStride{\n\t\tStride: int(stride),\n\t}, nil\n}",
"func qr_decoder_get_image_buffer(p _QrDecoderHandle) *_IplImage {\n\tv := C.qr_decoder_get_image_buffer(C.QrDecoderHandle(p))\n\treturn (*_IplImage)(v)\n}",
"func Getbuf() (_ Buf, wr *Bwr) { //nolint:golint\n\twr = bufPool.Get().(*Bwr)\n\treturn wr.b, wr\n}",
"func (native *OpenGL) BufferData(target uint32, size int, data interface{}, usage uint32) {\n\tdataPtr, isPtr := data.(unsafe.Pointer)\n\tif isPtr {\n\t\tgl.BufferData(target, size, dataPtr, usage)\n\t} else {\n\t\tgl.BufferData(target, size, gl.Ptr(data), usage)\n\t}\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetFormat(request *requests.FPDFBitmap_GetFormat) (*responses.FPDFBitmap_GetFormat, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tformat := C.FPDFBitmap_GetFormat(bitmapHandle.handle)\n\n\treturn &responses.FPDFBitmap_GetFormat{\n\t\tFormat: enums.FPDF_BITMAP_FORMAT(format),\n\t}, nil\n}",
"func GetPbufferDCARB(hPbuffer unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpGetPbufferDCARB, 1, uintptr(hPbuffer), 0, 0)\n\treturn (unsafe.Pointer)(ret)\n}",
"func NewBipBuffer(size uint32) *bipbuf_t {\n\treturn &bipbuf_t{\n\t\tsize:size,\n\t\ta_start:0,\n\t\ta_end:0,\n\t\tb_end:0,\n\t\tb_inuse:false,\n\t\tdata:make([]byte, size, size),\n\t}\n}",
"func QueryPbufferARB(hPbuffer unsafe.Pointer, iAttribute unsafe.Pointer, piValue unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpQueryPbufferARB, 3, uintptr(hPbuffer), uintptr(iAttribute), uintptr(piValue))\n\treturn (unsafe.Pointer)(ret)\n}",
"func GetBufferSubData(target uint32, offset int, size int, data unsafe.Pointer) {\n\tC.glowGetBufferSubData(gpGetBufferSubData, (C.GLenum)(target), (C.GLintptr)(offset), (C.GLsizeiptr)(size), data)\n}",
"func GetBufferSubData(target uint32, offset int, size int, data unsafe.Pointer) {\n\tC.glowGetBufferSubData(gpGetBufferSubData, (C.GLenum)(target), (C.GLintptr)(offset), (C.GLsizeiptr)(size), data)\n}",
"func BufferData(target Enum, size Sizeiptr, data unsafe.Pointer, usage Enum) {\n\tctarget, _ := (C.GLenum)(target), cgoAllocsUnknown\n\tcsize, _ := (C.GLsizeiptr)(size), cgoAllocsUnknown\n\tcdata, _ := (unsafe.Pointer)(unsafe.Pointer(data)), cgoAllocsUnknown\n\tcusage, _ := (C.GLenum)(usage), cgoAllocsUnknown\n\tC.glBufferData(ctarget, csize, cdata, cusage)\n}",
"func GetBuffer() *bytes.Buffer {\n\tbuf := bufPool.Get().(*bytes.Buffer)\n\tbuf.Reset()\n\treturn buf\n}",
"func (b *XMobileBackend) GetImageData(x, y, w, h int) *image.RGBA {\n\tb.activate()\n\n\tif x < 0 {\n\t\tw += x\n\t\tx = 0\n\t}\n\tif y < 0 {\n\t\th += y\n\t\ty = 0\n\t}\n\tif w > b.w {\n\t\tw = b.w\n\t}\n\tif h > b.h {\n\t\th = b.h\n\t}\n\n\tvar vp [4]int32\n\tb.glctx.GetIntegerv(vp[:], gl.VIEWPORT)\n\n\tsize := int(vp[2] * vp[3] * 3)\n\tif len(b.imageBuf) < size {\n\t\tb.imageBuf = make([]byte, size)\n\t}\n\tb.glctx.ReadPixels(b.imageBuf[0:], int(vp[0]), int(vp[1]), int(vp[2]), int(vp[3]), gl.RGB, gl.UNSIGNED_BYTE)\n\n\trgba := image.NewRGBA(image.Rect(x, y, x+w, y+h))\n\tfor cy := y; cy < y+h; cy++ {\n\t\tbp := (int(vp[3])-h+cy)*int(vp[2])*3 + x*3\n\t\tfor cx := x; cx < x+w; cx++ {\n\t\t\trgba.SetRGBA(cx, y+h-1-cy, color.RGBA{R: b.imageBuf[bp], G: b.imageBuf[bp+1], B: b.imageBuf[bp+2], A: 255})\n\t\t\tbp += 3\n\t\t}\n\t}\n\treturn rgba\n}",
"func (b *Bitmaps) GetBitmap(i int) (*Bitmap, error) {\n\tconst processName = \"GetBitmap\"\n\tif b == nil {\n\t\treturn nil, errors.Error(processName, \"provided nil Bitmaps\")\n\t}\n\tif i > len(b.Values)-1 {\n\t\treturn nil, errors.Errorf(processName, \"index: '%d' out of range\", i)\n\t}\n\treturn b.Values[i], nil\n}",
"func BufferData(target uint32, size int, data unsafe.Pointer, usage uint32) {\n\tsyscall.Syscall6(gpBufferData, 4, uintptr(target), uintptr(size), uintptr(data), uintptr(usage), 0, 0)\n}",
"func GetBytesBuffer(size int) *bytes.Buffer {\n\tswitch {\n\n\tcase size > 0 && size <= 256:\n\t\treturn GetBytesBuffer256()\n\n\tcase size > 256 && size <= 512:\n\t\treturn GetBytesBuffer512()\n\n\tcase size > 512 && size <= 1024:\n\t\treturn GetBytesBuffer1K()\n\n\tcase size > 1024 && size <= 2048:\n\t\treturn GetBytesBuffer2K()\n\n\tcase size > 2048 && size <= 4096:\n\t\treturn GetBytesBuffer4K()\n\n\tcase size > 4096 && size <= 8192:\n\t\treturn GetBytesBuffer8K()\n\n\tcase size > 8192 && size <= 16384:\n\t\treturn GetBytesBuffer16K()\n\n\tcase size > 16384 && size <= 32768:\n\t\treturn GetBytesBuffer32K()\n\n\tcase size > 32768 && size <= 65536:\n\t\treturn GetBytesBuffer64K()\n\n\tcase size > 65536 && size <= 131072:\n\t\treturn GetBytesBuffer128K()\n\n\tcase size > 131072 && size <= 262144:\n\t\treturn GetBytesBuffer256K()\n\n\tcase size > 262144 && size <= 524288:\n\t\treturn GetBytesBuffer512K()\n\n\tcase size > 524288 && size <= 1048576:\n\t\treturn GetBytesBuffer1M()\n\n\tcase size > 1048576 && size <= 2097152:\n\t\treturn GetBytesBuffer2M()\n\n\tcase size > 2097152 && size <= 4194304:\n\t\treturn GetBytesBuffer4M()\n\n\tcase size > 4194304 && size <= 8388608:\n\t\treturn GetBytesBuffer8M()\n\n\tcase size > 8388608 && size <= 16777216:\n\t\treturn GetBytesBuffer16M()\n\n\tdefault:\n\t\treturn bytes.NewBuffer(make([]byte, size))\n\t}\n}",
"func (bp *bufferPool) getBuffer() *buffer {\n\tbp.lock.Lock()\n\tb := bp.freeList\n\tif b != nil {\n\t\tbp.freeList = b.next\n\t\tbp.freeBufNum--\n\t}\n\tbp.lock.Unlock()\n\n\tif b == nil {\n\t\tb = new(buffer)\n\t\tb.Grow(512)\n\t} else {\n\t\tb.next = nil\n\t\tb.Reset()\n\t}\n\treturn b\n}",
"func (self Source) GetBuffer() (buffer Buffer) {\n\treturn Buffer(self.Geti(AlBuffer))\n}",
"func (mr *GoMockDiskStorageMockRecorder) GetBuffer() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetBuffer\", reflect.TypeOf((*GoMockDiskStorage)(nil).GetBuffer))\n}",
"func BufferData(target uint32, size int, data unsafe.Pointer, usage uint32) {\n\tC.glowBufferData(gpBufferData, (C.GLenum)(target), (C.GLsizeiptr)(size), data, (C.GLenum)(usage))\n}",
"func BufferData(target uint32, size int, data unsafe.Pointer, usage uint32) {\n\tC.glowBufferData(gpBufferData, (C.GLenum)(target), (C.GLsizeiptr)(size), data, (C.GLenum)(usage))\n}",
"func GetBufferSubData(target uint32, offset int, size int, data unsafe.Pointer) {\n\tsyscall.Syscall6(gpGetBufferSubData, 4, uintptr(target), uintptr(offset), uintptr(size), uintptr(data), 0, 0)\n}",
"func (cache *Cache) BitmapGet(next uint16) (bool, uint16, uint16) {\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\treturn cache.bitmap.get(next)\n}",
"func (p *movingAverageProcessor) getBufferData(index int, namespace string) interface{} {\n\n\treturn p.movingAverageMap[namespace].movingAverageBuf[index]\n}",
"func getBuffer() *bytes.Buffer {\n\treturn bufferPool.Get().(*bytes.Buffer)\n}",
"func BufferData(target uint32, size int, data unsafe.Pointer, usage uint32) {\n C.glowBufferData(gpBufferData, (C.GLenum)(target), (C.GLsizeiptr)(size), data, (C.GLenum)(usage))\n}",
"func GetBuffer() *bytes.Buffer {\n\treturn defaultPool.pool.Get().(*bytes.Buffer)\n}",
"func (p Point) Buffer() *Buffer {\n\treturn p.buffer\n}",
"func (obj *Device) GetBackBuffer(\n\tswapChain uint,\n\tbackBuffer uint,\n\ttyp BACKBUFFER_TYPE,\n) (*Surface, Error) {\n\tvar surface *Surface\n\tret, _, _ := syscall.Syscall6(\n\t\tobj.vtbl.GetBackBuffer,\n\t\t5,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(swapChain),\n\t\tuintptr(backBuffer),\n\t\tuintptr(typ),\n\t\tuintptr(unsafe.Pointer(&surface)),\n\t\t0,\n\t)\n\treturn surface, toErr(ret)\n}",
"func NewBuffer() Buffer {\n\treturn Buffer{\n\t\tCellMap: make(map[image.Point]Cell),\n\t\tArea: image.Rectangle{}}\n}",
"func GetBytesBuffer() *bytes.Buffer {\n\tbuf := defaultPool.Get().(*bytes.Buffer)\n\tbufCap := buf.Cap()\n\tif bufCap >= minBufCap && bufCap <= maxBufCap && poolObjectNumber.Load() > 0 {\n\t\tpoolObjectNumber.Dec()\n\t}\n\n\treturn buf\n}",
"func New(width, height int) *Bitmap {\n\tbm := &Bitmap{\n\t\tWidth: width,\n\t\tHeight: height,\n\t\tRowStride: (width + 7) >> 3,\n\t}\n\tbm.Data = make([]byte, height*bm.RowStride)\n\n\treturn bm\n}",
"func GetBytesBuffer32K() *bytes.Buffer {\n\tif b := getb32K(); b != nil {\n\t\treturn b\n\t}\n\tif p := get32K(); p != nil {\n\t\treturn bytes.NewBuffer(internal.Puts(p))\n\t}\n\treturn bytes.NewBuffer(make([]byte, 32768))\n}",
"func GetBuffer() Buffer {\n\treturn pool.get()\n}",
"func BufferData(target Enum, src []byte, usage Enum) {\n\tgl.BufferData(uint32(target), int(len(src)), gl.Ptr(&src[0]), uint32(usage))\n}",
"func getBitmap(file *os.File, index int64, size int64) []byte {\n\tbitMap := make([]byte, size)\n\tfile.Seek(index, 0)\n\t//Se obtiene la data del archivo binarios\n\tdata := readNextBytes(file, size)\n\tbuffer := bytes.NewBuffer(data)\n\t//Se asigna al mbr declarado para leer la informacion de ese disco\n\terr := binary.Read(buffer, binary.BigEndian, &bitMap)\n\tif err != nil {\n\t\tlog.Fatal(\"binary.Read failed\", err)\n\t}\n\treturn bitMap\n}",
"func GetBufferSubData(target uint32, offset int, size int, data unsafe.Pointer) {\n C.glowGetBufferSubData(gpGetBufferSubData, (C.GLenum)(target), (C.GLintptr)(offset), (C.GLsizeiptr)(size), data)\n}",
"func (debugging *debuggingOpenGL) BufferData(target uint32, size int, data interface{}, usage uint32) {\n\tdebugging.recordEntry(\"BufferData\", target, size, data, usage)\n\tdebugging.gl.BufferData(target, size, data, usage)\n\tdebugging.recordExit(\"BufferData\")\n}",
"func GetBuffer() *Buffer {\n\tfreeListMu.Lock()\n\tb := freeList\n\tif b != nil {\n\t\tfreeList = b.next\n\t\tfreeListLen--\n\t}\n\tfreeListMu.Unlock()\n\tif b == nil {\n\t\tb = new(Buffer)\n\t} else {\n\t\tb.next = nil\n\t\tb.Reset()\n\t}\n\treturn b\n}",
"func GetBytesBuffer512() *bytes.Buffer {\n\tif b := getb512(); b != nil {\n\t\treturn b\n\t}\n\tif p := get512(); p != nil {\n\t\treturn bytes.NewBuffer(internal.Puts(p))\n\t}\n\treturn bytes.NewBuffer(make([]byte, 512))\n}",
"func (g *GLTF) loadBuffer(bufIdx int) ([]byte, error) {\n\n\t// Check if provided buffer index is valid\n\tif bufIdx < 0 || bufIdx >= len(g.Buffers) {\n\t\treturn nil, fmt.Errorf(\"invalid buffer index\")\n\t}\n\tbufData := &g.Buffers[bufIdx]\n\t// Return cached if available\n\tif bufData.cache != nil {\n\t\tlog.Debug(\"Fetching Buffer %d (cached)\", bufIdx)\n\t\treturn bufData.cache, nil\n\t}\n\tlog.Debug(\"Loading Buffer %d\", bufIdx)\n\n\t// If buffer URI use the chunk data field\n\tif bufData.Uri == \"\" {\n\t\treturn g.data, nil\n\t}\n\n\t// Checks if buffer URI is a data URI\n\tvar data []byte\n\tvar err error\n\tif isDataURL(bufData.Uri) {\n\t\tdata, err = loadDataURL(bufData.Uri)\n\t} else {\n\t\t// Try to load buffer from file\n\t\tdata, err = g.loadFileBytes(bufData.Uri)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Checks data length\n\tif len(data) != bufData.ByteLength {\n\t\treturn nil, fmt.Errorf(\"buffer:%d read data length:%d expected:%d\", bufIdx, len(data), bufData.ByteLength)\n\t}\n\t// Cache buffer data\n\tg.Buffers[bufIdx].cache = data\n\tlog.Debug(\"cache data:%v\", len(bufData.cache))\n\treturn data, nil\n}",
"func (d *decoder) buffer() []byte {\n\tif d.buf == nil {\n\t\td.buf = make([]byte, 8)\n\t}\n\treturn d.buf\n}",
"func (p Plane) GetBuffers() ObjectBuffers {\n\treturn p.buffers\n}",
"func CreatePbufferARB(hDC unsafe.Pointer, iPixelFormat unsafe.Pointer, iWidth unsafe.Pointer, iHeight unsafe.Pointer, piAttribList unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall6(gpCreatePbufferARB, 5, uintptr(hDC), uintptr(iPixelFormat), uintptr(iWidth), uintptr(iHeight), uintptr(piAttribList), 0)\n\treturn (unsafe.Pointer)(ret)\n}",
"func GetBufferParameteriv(target uint32, pname uint32, params *int32) {\n\tC.glowGetBufferParameteriv(gpGetBufferParameteriv, (C.GLenum)(target), (C.GLenum)(pname), (*C.GLint)(unsafe.Pointer(params)))\n}",
"func GetBufferParameteriv(target uint32, pname uint32, params *int32) {\n\tC.glowGetBufferParameteriv(gpGetBufferParameteriv, (C.GLenum)(target), (C.GLenum)(pname), (*C.GLint)(unsafe.Pointer(params)))\n}",
"func (self *StreamDecoder) Buffered() io.Reader {\n return bytes.NewReader(self.buf[self.scanp:])\n}",
"func GetBytesBuffer2K() *bytes.Buffer {\n\tif b := getb2K(); b != nil {\n\t\treturn b\n\t}\n\tif p := get2K(); p != nil {\n\t\treturn bytes.NewBuffer(internal.Puts(p))\n\t}\n\treturn bytes.NewBuffer(make([]byte, 2048))\n}",
"func GetBytesBuffer1K() *bytes.Buffer {\n\tif b := getb1K(); b != nil {\n\t\treturn b\n\t}\n\tif p := get1K(); p != nil {\n\t\treturn bytes.NewBuffer(internal.Puts(p))\n\t}\n\treturn bytes.NewBuffer(make([]byte, 1024))\n}",
"func (b *mpgBuff) BufferSize() int {\n\treturn b.size\n}",
"func GetBytesBuffer1M() *bytes.Buffer {\n\tif b := getb1M(); b != nil {\n\t\treturn b\n\t}\n\tif p := get1M(); p != nil {\n\t\treturn bytes.NewBuffer(internal.Puts(p))\n\t}\n\treturn bytes.NewBuffer(make([]byte, 1048576))\n}",
"func GetDirectBufferAddress(env *C.JNIEnv, buf C.jobject) unsafe.Pointer {\n\treturn C._GoJniGetDirectBufferAddress(env, buf)\n}",
"func (p *PostingsIterator) ActualBitmap() *roaring.Bitmap {\n\treturn p.ActualBM\n}",
"func BlitFramebuffer(srcX0 int32, srcY0 int32, srcX1 int32, srcY1 int32, dstX0 int32, dstY0 int32, dstX1 int32, dstY1 int32, mask uint32, filter uint32) {\n\tsyscall.Syscall12(gpBlitFramebuffer, 10, uintptr(srcX0), uintptr(srcY0), uintptr(srcX1), uintptr(srcY1), uintptr(dstX0), uintptr(dstY0), uintptr(dstX1), uintptr(dstY1), uintptr(mask), uintptr(filter), 0, 0)\n}",
"func GetBytesBuffer8K() *bytes.Buffer {\n\tif b := getb8K(); b != nil {\n\t\treturn b\n\t}\n\tif p := get8K(); p != nil {\n\t\treturn bytes.NewBuffer(internal.Puts(p))\n\t}\n\treturn bytes.NewBuffer(make([]byte, 8192))\n}",
"func GetBufferParameteriv(target uint32, pname uint32, params *int32) {\n\tsyscall.Syscall(gpGetBufferParameteriv, 3, uintptr(target), uintptr(pname), uintptr(unsafe.Pointer(params)))\n}",
"func GetBytesBuffer2M() *bytes.Buffer {\n\tif b := getb2M(); b != nil {\n\t\treturn b\n\t}\n\tif p := get2M(); p != nil {\n\t\treturn bytes.NewBuffer(internal.Puts(p))\n\t}\n\treturn bytes.NewBuffer(make([]byte, 2097152))\n}",
"func (w *Writer) Buffer() []byte {\n\tif w.err != nil {\n\t\treturn nil\n\t}\n\treturn append([]byte(nil), w.b...)\n}",
"func (gl *WebGL) BufferData(target GLEnum, data interface{}, usage GLEnum) {\n\tvalues := sliceToTypedArray(data)\n\tgl.context.Call(\"bufferData\", target, values, usage)\n}",
"func getPalettesBufferPointer() *uint8 {\n\treturn &palettes[0]\n}",
"func (b *defaultByteBuffer) NewBuffer() ByteBuffer {\n\treturn NewWriterBuffer(256)\n}",
"func GetBufferPointerv(target uint32, pname uint32, params *unsafe.Pointer) {\n\tC.glowGetBufferPointerv(gpGetBufferPointerv, (C.GLenum)(target), (C.GLenum)(pname), params)\n}",
"func GetBufferPointerv(target uint32, pname uint32, params *unsafe.Pointer) {\n\tC.glowGetBufferPointerv(gpGetBufferPointerv, (C.GLenum)(target), (C.GLenum)(pname), params)\n}",
"func GetBuf() *Buffer {\n\tbuf := bufferPool.Get().(*Buffer)\n\tbuf.Reset()\n\treturn buf\n}",
"func GetBytesBuffer8M() *bytes.Buffer {\n\tif b := getb8M(); b != nil {\n\t\treturn b\n\t}\n\tif p := get8M(); p != nil {\n\t\treturn bytes.NewBuffer(internal.Puts(p))\n\t}\n\treturn bytes.NewBuffer(make([]byte, 8388608))\n}",
"func GetBufferPointerv(target uint32, pname uint32, params *unsafe.Pointer) {\n\tsyscall.Syscall(gpGetBufferPointerv, 3, uintptr(target), uintptr(pname), uintptr(unsafe.Pointer(params)))\n}",
"func (bufferP *BufferPool) Get(size int) (data []byte, err error) {\n\tif size == util.PacketHeaderSize {\n\t\tatomic.AddInt64(&headBuffersCount, 1)\n\t\tid := atomic.AddUint64(&headBufAllocId, 1)\n\t\treturn bufferP.getHead(id), nil\n\t} else if size == util.BlockSize {\n\t\tatomic.AddInt64(&normalBuffersCount, 1)\n\t\tid := atomic.AddUint64(&normalBufAllocId, 1)\n\t\treturn bufferP.getNoraml(id), nil\n\t} else if size == util.DefaultTinySizeLimit {\n\t\tatomic.AddInt64(&tinyBuffersCount, 1)\n\t\treturn bufferP.tinyPool.Get().([]byte), nil\n\t}\n\treturn nil, fmt.Errorf(\"can only support 45 or 65536 bytes\")\n}",
"func (f *DynamicDiskBlockFactory) GetBitmapFactory() *bitmap.Factory {\n\treturn f.bitmapFactory\n}",
"func GetBufferPointerv(target uint32, pname uint32, params *unsafe.Pointer) {\n C.glowGetBufferPointerv(gpGetBufferPointerv, (C.GLenum)(target), (C.GLenum)(pname), params)\n}",
"func NewBuffer(m []byte, skip, size int64) (*Buffer, error) {\n\tb := &Buffer{\n\t\toffset: skip,\n\t\tsize: size,\n\t\tdata: m,\n\t}\n\treturn b, nil\n}",
"func NewWithData(width, height int, data []byte) *Bitmap {\n\tbm := New(width, height)\n\tbm.Data = data\n\treturn bm\n}",
"func WndProc(hwnd syscall.Handle, msg uint32, wparam, lparam uintptr) (rc uintptr) {\n\t_ = make([]int, 100000)\n\tswitch msg {\n\tcase wingui.WM_CREATE:\n\t\thdc := wingui.GetDC(hwnd)\n\t\thdcWndBuffer = wingui.CreateCompatibleDC(hdc)\n\t\twndBufferHeader = wingui.CreateCompatibleBitmap(hdc, 600, 800)\n\t\twingui.GetObject(wndBufferHeader, unsafe.Sizeof(wndBuffer), uintptr(unsafe.Pointer(&wndBuffer)))\n\t\twingui.SelectObject(hdcWndBuffer, wndBufferHeader)\n\n\t\tvar bmp_header wingui.BITMAPINFOHEADER\n\t\tbmp_header.Size = uint32(unsafe.Sizeof(bmp_header))\n\t\tbmp_header.Width = 600\n\t\tbmp_header.Height = 800\n\t\tbmp_header.SizeImage = 0 // the api says this must be 0 for BI_RGB images\n\t\tbmp_header.Compression = wingui.BI_RGB\n\t\tbmp_header.BitCount = 32\n\t\tbmp_header.Planes = 1\n\t\tbmp_header.XPelsPerMeter = 0\n\t\tbmp_header.YPelsPerMeter = 0\n\t\tbmp_header.ClrUsed = 0\n\t\tbmp_header.ClrImportant = 0\n\t\t//bitmap info\n\t\tvar bmpinfo wingui.BITMAPINFO\n\t\tbmpinfo.Colors[0].Blue = 0\n\t\tbmpinfo.Colors[0].Green = 0\n\t\tbmpinfo.Colors[0].Red = 0\n\t\tbmpinfo.Colors[0].Reserved = 0\n\t\tbmpinfo.Header = bmp_header\n\t\twndBufferHeader = wingui.CreateDIBSection(hdc, &bmpinfo, wingui.DIB_RGB_COLORS, uintptr(unsafe.Pointer(&ppvBits)), 0, 0)\n\t\twingui.GetObject(wndBufferHeader, unsafe.Sizeof(wndBufferHeader), uintptr(unsafe.Pointer(&wndBuffer)))\n\t\thdcWndBuffer = wingui.CreateCompatibleDC(hdc)\n\t\twingui.SelectObject(hdcWndBuffer, wndBufferHeader)\n\n\t\tpixel := (*[600 * 800 * 4]uint8)(unsafe.Pointer(ppvBits))\n\t\tpixelSlice := pixel[:]\n\t\tbackBuffer = &image.RGBA{pixelSlice, 4*600, image.Rect(0, 0, 600, 800)}\n\t\tfmt.Println(\"Create windows\")\n\t\trc = wingui.DefWindowProc(hwnd, msg, wparam, lparam)\n\tcase wingui.WM_COMMAND:\n\t\tswitch syscall.Handle(lparam) {\n\t\tdefault:\n\t\t\trc = wingui.DefWindowProc(hwnd, msg, wparam, lparam)\n\t\t}\n\tcase wingui.WM_PAINT:\n\t\tvar ps wingui.PAINTSTRUCT\n\t\thdc := wingui.BeginPaint(hwnd, &ps)\n\t\tt := time.Now()\n\t\tgc := draw2d.NewGraphicContext(backBuffer)\n\t\t/*gc.SetFillColor(color.RGBA{0xFF, 0xFF, 0xFF, 0xFF})\n\t\tgc.Clear()*/\n\t\tfor i := 0; i < len(backBuffer.Pix); i+=1 {\n\t\t\tbackBuffer.Pix[i] = 0xff\n\t\t}\n\t\tgc.Save()\n\t\t//gc.Translate(0, -380)\n\t\tDrawTiger(gc)\n\t\tgc.Restore()\n\t\t// back buf in\n\t\tvar tmp uint8\n\t\tfor i := 0; i < len(backBuffer.Pix); i+=4 {\n\t\t\ttmp = backBuffer.Pix[i]\n\t\t\tbackBuffer.Pix[i] = backBuffer.Pix[i+2]\n\t\t\tbackBuffer.Pix[i+2] = tmp\n\t\t}\n\t\twingui.BitBlt(hdc, 0, 0, int(wndBuffer.Width), int(wndBuffer.Height), hdcWndBuffer, 0, 0, wingui.SRCCOPY)\n\t\twingui.EndPaint(hwnd, &ps)\n\t\trc = wingui.DefWindowProc(hwnd, msg, wparam, lparam)\n\t\tdt := time.Now().Sub(t)\n\t\tfmt.Printf(\"Redraw in : %f ms\\n\", float64(dt)*1e-6)\n\tcase wingui.WM_CLOSE:\n\t\twingui.DestroyWindow(hwnd)\n\tcase wingui.WM_DESTROY:\n\t\twingui.PostQuitMessage(0)\n\tdefault:\n\t\trc = wingui.DefWindowProc(hwnd, msg, wparam, lparam)\n\t}\n\treturn\n}",
"func (pk PacketBufferPtr) ToBuffer() buffer.Buffer {\n\tb := pk.buf.Clone()\n\tb.TrimFront(int64(pk.headerOffset()))\n\treturn b\n}",
"func (_ BufferPtrPool2M) Get() *[]byte {\n\treturn GetBytesSlicePtr2M()\n}",
"func GetBytesBuffer512K() *bytes.Buffer {\n\tif b := getb512K(); b != nil {\n\t\treturn b\n\t}\n\tif p := get512K(); p != nil {\n\t\treturn bytes.NewBuffer(internal.Puts(p))\n\t}\n\treturn bytes.NewBuffer(make([]byte, 524288))\n}",
"func NewBuffer(inp []byte) *ByteBuffer {\n\tif inp == nil {\n\t\tinp = make([]byte, 0, 512)\n\t}\n\treturn &ByteBuffer{Buffer: bytes.NewBuffer(inp)}\n}",
"func (image *Image2D) GetDataPointer() unsafe.Pointer {\n\treturn gl.Ptr(image.data)\n}",
"func (_ BufferPtrPool2K) Get() *[]byte {\n\treturn GetBytesSlicePtr2K()\n}",
"func GetBufferParameteriv(target Enum, pname Enum, params []Int) {\n\tctarget, _ := (C.GLenum)(target), cgoAllocsUnknown\n\tcpname, _ := (C.GLenum)(pname), cgoAllocsUnknown\n\tcparams, _ := (*C.GLint)(unsafe.Pointer((*sliceHeader)(unsafe.Pointer(¶ms)).Data)), cgoAllocsUnknown\n\tC.glGetBufferParameteriv(ctarget, cpname, cparams)\n}",
"func (bp *BufferPool) Get() *bytes.Buffer {\n\treturn bp.Pool.Get().(*bytes.Buffer)\n}",
"func NewBufferBytes(data []byte) *Buffer {\n\treturn &Buffer{refCount: 0, buf: data, length: len(data)}\n}",
"func (b *Bitmap) GetUnpaddedData() ([]byte, error) {\n\tpadding := uint(b.Width & 0x07)\n\tif padding == 0 {\n\t\treturn b.Data, nil\n\t}\n\n\tsize := b.Width * b.Height\n\tif size%8 != 0 {\n\t\tsize >>= 3\n\t\tsize++\n\t} else {\n\t\tsize >>= 3\n\t}\n\n\tdata := make([]byte, size)\n\tw := writer.NewMSB(data)\n\n\tfor y := 0; y < b.Height; y++ {\n\t\t// btIndex is the byte index per row.\n\t\tfor btIndex := 0; btIndex < b.RowStride; btIndex++ {\n\t\t\tbt := b.Data[y*b.RowStride+btIndex]\n\t\t\tif btIndex != b.RowStride-1 {\n\t\t\t\terr := w.WriteByte(bt)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor i := uint(0); i < padding; i++ {\n\t\t\t\terr := w.WriteBit(int(bt >> (7 - i) & 0x01))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn data, nil\n}",
"func (_ BufferPtrPool1M) Get() *[]byte {\n\treturn GetBytesSlicePtr1M()\n}",
"func (p *BufferBucketPool) Get() *BufferBucket {\n\treturn p.pool.Get().(*BufferBucket)\n}",
"func (al *AudioListener) getBuffer() []gumble.AudioPacket {\n\tal.Lock()\n\tdefer al.Unlock()\n\n\tbuf := al.buffer\n\tal.buffer = nil\n\treturn buf\n}",
"func NewBatchBuffer() *BatchBuffer {\n\treturn &BatchBuffer{\n\t\tbuffer: make([]coldata.Batch, 0, 2),\n\t}\n}",
"func (s *ShmPool) CreateBuffer(id *Buffer, offset int32, width int32, height int32, stride int32, format uint32) {\n sendrequest(s, \"wl_shm_pool_create_buffer\", id, offset, width, height, stride, format)\n}",
"func (d *Device) FillRectangleWithBuffer(x, y, width, height int16, buffer []color.RGBA) error {\n\ti, j := d.Size()\n\tif x < 0 || y < 0 || width <= 0 || height <= 0 ||\n\t\tx >= i || (x+width) > i || y >= j || (y+height) > j {\n\t\treturn errors.New(\"rectangle coordinates outside display area\")\n\t}\n\tif int32(width)*int32(height) != int32(len(buffer)) {\n\t\treturn errors.New(\"buffer length does not match with rectangle size\")\n\t}\n\td.startWrite()\n\td.setWindow(x, y, width, height)\n\n\tk := int32(width) * int32(height)\n\tdata := make([]uint8, d.batchLength*2)\n\toffset := int32(0)\n\tfor k > 0 {\n\t\tfor i := int32(0); i < d.batchLength; i++ {\n\t\t\tif offset+i < int32(len(buffer)) {\n\t\t\t\tc565 := RGBATo565(buffer[offset+i])\n\t\t\t\tc1 := uint8(c565 >> 8)\n\t\t\t\tc2 := uint8(c565)\n\t\t\t\tdata[i*2] = c1\n\t\t\t\tdata[i*2+1] = c2\n\t\t\t}\n\t\t}\n\t\t// The DC pin is already set to data in the setWindow call, so we don't\n\t\t// have to set it here.\n\t\tif k >= d.batchLength {\n\t\t\td.bus.Tx(data, nil)\n\t\t} else {\n\t\t\td.bus.Tx(data[:k*2], nil)\n\t\t}\n\t\tk -= d.batchLength\n\t\toffset += d.batchLength\n\t}\n\td.endWrite()\n\treturn nil\n}",
"func (native *OpenGL) BlitFramebuffer(srcX0 int32, srcY0 int32, srcX1 int32, srcY1 int32, dstX0 int32, dstY0 int32, dstX1 int32, dstY1 int32, mask uint32, filter uint32) {\n\tgl.BlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter)\n}",
"func NewBuffer() Buffer {\n\treturn &buffer{}\n}",
"func (_ BufferPtrPool1K) Get() *[]byte {\n\treturn GetBytesSlicePtr1K()\n}",
"func (m *Magic) Buffer(data []byte) (string, error) {\n\tif m.ptr == nil {\n\t\treturn \"\", ConnectionError\n\t}\n\n\tptr := unsafe.Pointer(&data)\n\tsz := C.size_t(len(data))\n\tcr := C.magic_buffer(m.ptr, ptr, sz)\n\n\tif cr == nil {\n\t\treturn \"\", m.check()\n\t}\n\n\tr := C.GoString(cr)\n\tC.free(unsafe.Pointer(cr))\n\treturn r, nil\n}",
"func (p *Pool) NewBuffer() *Buffer {\n\treturn &Buffer{pool: p, bufs: make([][]byte, 0, 128), curBufIdx: -1}\n}",
"func NewBuffer() *Buffer {\n\treturn NewBufferWithSize(initialSize)\n}",
"func (_ BufferPtrPool8M) Get() *[]byte {\n\treturn GetBytesSlicePtr8M()\n}",
"func getBuf(size int) *[]byte {\n\tx := bufPool.Get()\n\tif x == nil {\n\t\tb := make([]byte, size)\n\t\treturn &b\n\t}\n\tbuf := x.(*[]byte)\n\tif cap(*buf) < size {\n\t\tb := make([]byte, size)\n\t\treturn &b\n\t}\n\t*buf = (*buf)[:size]\n\treturn buf\n}",
"func (c *Config) GetAutoscalerBufferMemory() string {\n\treturn c.member.GetString(varAutoscalerBufferMemory)\n}",
"func (v Chunk) Buffer() arrow.TableBuffer {\n\treturn v.buf\n}",
"func (obj *Device) GetFrontBufferData(swapChain uint, destSurface *Surface) Error {\n\tret, _, _ := syscall.Syscall(\n\t\tobj.vtbl.GetFrontBufferData,\n\t\t3,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(swapChain),\n\t\tuintptr(unsafe.Pointer(destSurface)),\n\t)\n\treturn toErr(ret)\n}"
] | [
"0.684168",
"0.5579585",
"0.5473083",
"0.52115667",
"0.515712",
"0.51270646",
"0.5036525",
"0.4980289",
"0.496555",
"0.49458572",
"0.49458572",
"0.49199474",
"0.49134034",
"0.49064565",
"0.4896894",
"0.4888703",
"0.48815328",
"0.48749244",
"0.4873812",
"0.4872395",
"0.48722273",
"0.48722273",
"0.48331514",
"0.48275143",
"0.4822682",
"0.4815861",
"0.48124507",
"0.48095852",
"0.4805458",
"0.47973895",
"0.476886",
"0.47601748",
"0.475858",
"0.4757758",
"0.47539335",
"0.4736355",
"0.47287512",
"0.47268558",
"0.47236067",
"0.47209144",
"0.47114518",
"0.46875012",
"0.468159",
"0.46752542",
"0.4661347",
"0.46612734",
"0.46612734",
"0.46500078",
"0.46469846",
"0.46436155",
"0.46389875",
"0.4634768",
"0.46317136",
"0.46072674",
"0.46060148",
"0.46032655",
"0.45929724",
"0.4587547",
"0.458282",
"0.45824564",
"0.45821637",
"0.45809725",
"0.45780915",
"0.45780915",
"0.45678133",
"0.45497006",
"0.4543616",
"0.45391905",
"0.453205",
"0.45312086",
"0.45255527",
"0.4525495",
"0.45209458",
"0.45040438",
"0.45001727",
"0.4492785",
"0.44921932",
"0.44804522",
"0.4454094",
"0.4449206",
"0.44484133",
"0.44483674",
"0.44440946",
"0.44431326",
"0.4442537",
"0.44386244",
"0.44369435",
"0.4435113",
"0.44308135",
"0.44251075",
"0.44185606",
"0.4414956",
"0.4410498",
"0.44023824",
"0.44018474",
"0.43976268",
"0.43967226",
"0.43949398",
"0.43912905",
"0.43908077"
] | 0.80363727 | 0 |
FPDFBitmap_GetWidth returns the width of a bitmap. | func (p *PdfiumImplementation) FPDFBitmap_GetWidth(request *requests.FPDFBitmap_GetWidth) (*responses.FPDFBitmap_GetWidth, error) {
p.Lock()
defer p.Unlock()
bitmapHandle, err := p.getBitmapHandle(request.Bitmap)
if err != nil {
return nil, err
}
width := C.FPDFBitmap_GetWidth(bitmapHandle.handle)
return &responses.FPDFBitmap_GetWidth{
Width: int(width),
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (b *Bitmap) Width() int {\n\treturn int(b.handle.width)\n}",
"func (p *Picture) GetWidth() int {\r\n\treturn p.pixelWidth\r\n}",
"func (size *BitmapSize) Width() int16 {\n\treturn int16(size.handle.width)\n}",
"func (r *ImageRef) Width() int {\n\treturn int(r.image.Xsize)\n}",
"func (image *Image2D) GetWidth() int {\n\treturn image.width\n}",
"func (info *ImageInfoType) Width() float64 {\n\treturn info.w / (info.scale * info.dpi / 72)\n}",
"func (image *JPGImage) GetWidth() float32 {\n\treturn float32(image.width)\n}",
"func (s *ImageSpec) Width() int {\n\tret := int(C.ImageSpec_width(s.ptr))\n\truntime.KeepAlive(s)\n\treturn ret\n}",
"func (self *TraitPixbuf) GetWidth() (return__ int) {\n\tvar __cgo__return__ C.int\n\t__cgo__return__ = C.gdk_pixbuf_get_width(self.CPointer)\n\treturn__ = int(__cgo__return__)\n\treturn\n}",
"func (me *Image) Width() int {\n\treturn int(me.img.w)\n}",
"func (tex *Image) Width() int {\n\tsize := C.sfTexture_getSize(tex.tex)\n\treturn int(size.x)\n}",
"func (v *Pixbuf) GetWidth() int {\n\treturn int(C.gdk_pixbuf_get_width(v.Native()))\n}",
"func (is ImageSurface) Width() int {\n\treturn is.width\n}",
"func (o GoogleCloudRetailV2alphaImageOutput) Width() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaImage) *int { return v.Width }).(pulumi.IntPtrOutput)\n}",
"func (o *FileInfoThumbnail) GetWidth() int32 {\n\tif o == nil || o.Width == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Width\n}",
"func (image *Image) Width() int {\n\treturn image.width\n}",
"func (bm Blendmap) Width() float32 {\n\treturn bm.Map.width\n}",
"func (o *TileBounds) GetWidth() int32 {\n\tif o == nil || o.Width == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Width\n}",
"func (a *Asset) GetWidth() float64 {\n\tif a == nil || a.Width == nil {\n\t\treturn 0.0\n\t}\n\treturn *a.Width\n}",
"func (rect *PdfRectangle) Width() float64 {\n\treturn math.Abs(rect.Urx - rect.Llx)\n}",
"func (mw *MagickWand) Width() uint {\n\treturn mw.GetImageWidth()\n}",
"func (s *CountMinSketch) Width() uint {\n\treturn s.w\n}",
"func (b *BaseElement) GetWidth() int32 {\n\treturn b.w\n}",
"func (self *TraitPixbufAnimation) GetWidth() (return__ int) {\n\tvar __cgo__return__ C.int\n\t__cgo__return__ = C.gdk_pixbuf_animation_get_width(self.CPointer)\n\treturn__ = int(__cgo__return__)\n\treturn\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetStride(request *requests.FPDFBitmap_GetStride) (*responses.FPDFBitmap_GetStride, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstride := C.FPDFBitmap_GetStride(bitmapHandle.handle)\n\treturn &responses.FPDFBitmap_GetStride{\n\t\tStride: int(stride),\n\t}, nil\n}",
"func Width() int {\n\tws, err := getWinsize()\n\n\tif err != nil {\n\t\treturn -1\n\t}\n\n\treturn int(ws.Col)\n}",
"func (rc Rectangle) Width() int {\n\treturn rc.Right - rc.Left\n}",
"func (f *Framebuffer) Width() int { return f.fb.Bounds().Max.X }",
"func (a *Animation) GetWidth() float64 {\n\tif a == nil || a.Width == nil {\n\t\treturn 0.0\n\t}\n\treturn *a.Width\n}",
"func (bm Bitmap) Len() int {\n\treturn len(bm) * 32\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetHeight(request *requests.FPDFBitmap_GetHeight) (*responses.FPDFBitmap_GetHeight, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theight := C.FPDFBitmap_GetHeight(bitmapHandle.handle)\n\treturn &responses.FPDFBitmap_GetHeight{\n\t\tHeight: int(height),\n\t}, nil\n}",
"func (pc PieChart) GetWidth() int {\n\tif pc.Width == 0 {\n\t\treturn DefaultChartWidth\n\t}\n\treturn pc.Width\n}",
"func (r Rectangle) Width() float64 {\n\treturn r.Max.X - r.Min.X\n}",
"func (s *ImageSpec) TileWidth() int {\n\tret := int(C.ImageSpec_tile_width(s.ptr))\n\truntime.KeepAlive(s)\n\treturn ret\n}",
"func (num *number) Width() int {\n\treturn num.size * 3 / 4\n}",
"func (t *Texture) GetWidth() uint16 {\n\treturn t.width\n}",
"func (dim *Dimensions) Width() int64 {\n\treturn dim.width\n}",
"func (o *WorkbookChart) GetWidth() AnyOfnumberstringstring {\n\tif o == nil || o.Width == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret\n\t}\n\treturn *o.Width\n}",
"func getWidth() int {\n\tstdoutFd := int(wrappedstreams.Stdout().Fd())\n\tstderrFd := int(wrappedstreams.Stderr().Fd())\n\n\tw := getWidthFd(stdoutFd)\n\tif w < 0 {\n\t\tw = getWidthFd(stderrFd)\n\t}\n\n\treturn w\n}",
"func (c *Canvas) Width() int {\n\treturn c.maxCorner.X - c.minCorner.X + 1\n}",
"func (t *Link) GetWidth() (v int64) {\n\treturn *t.width.nonNegativeInteger\n\n}",
"func (s Spritesheet) Width() float32 {\n\treturn s.texture.Width() / float32(s.CellWidth)\n}",
"func (s *SimPDF) Width() float64 {\n\tif s.Page.IsLandscape {\n\t\treturn s.Page.Height\n\t}\n\treturn s.Page.Width\n}",
"func (b *BoundingBox2D) width() float64 {\n\n\treturn b.upperCorner.X - b.lowerCorner.X\n}",
"func (spr *Sprite) Width() int32 {\n\n\treturn spr.width\n}",
"func (o GoogleCloudRetailV2alphaImageResponseOutput) Width() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaImageResponse) int { return v.Width }).(pulumi.IntOutput)\n}",
"func (t Texture3D) GetWidth() int32 {\n\treturn t.width\n}",
"func (i *InputInlineQueryResultPhoto) GetPhotoWidth() (value int32) {\n\tif i == nil {\n\t\treturn\n\t}\n\treturn i.PhotoWidth\n}",
"func (i *InputInlineQueryResultContact) GetThumbnailWidth() (value int32) {\n\tif i == nil {\n\t\treturn\n\t}\n\treturn i.ThumbnailWidth\n}",
"func (g Grid) PixelWidth() int32 {\n\treturn int32(g.width) * g.cellSize\n}",
"func (b *Bound) Width() float64 {\n\treturn b.ne.X() - b.sw.X()\n}",
"func (o *TileBounds) GetWidthOk() (*int32, bool) {\n\tif o == nil || o.Width == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Width, true\n}",
"func Width() (int, error) {\n\tws := &struct {\n\t\tRow uint16\n\t\tCol uint16\n\t\tXpixel uint16\n\t\tYpixel uint16\n\t}{}\n\n\tretCode, _, errno := syscall.Syscall(syscall.SYS_IOCTL,\n\t\tuintptr(syscall.Stdin),\n\t\tuintptr(syscall.TIOCGWINSZ),\n\t\tuintptr(unsafe.Pointer(ws)),\n\t)\n\n\tif int(retCode) == -1 {\n\t\treturn -1, errno\n\t}\n\n\treturn int(ws.Col), nil\n}",
"func (m *Matrix) Width() int {\n\treturn -1\n}",
"func (matrix *CosineLabeledMatrix) Width() int {\n\treturn len(matrix.Label)\n}",
"func (o *FileInfoThumbnail) GetWidthOk() (*int32, bool) {\n\tif o == nil || o.Width == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Width, true\n}",
"func (s *PageLayout) Width() float64 {\n\treturn s.width\n}",
"func (t *Track) Width() int {\n\treturn t.width\n}",
"func (o *WorkbookChart) GetWidthOk() (AnyOfnumberstringstring, bool) {\n\tif o == nil || o.Width == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret, false\n\t}\n\treturn *o.Width, true\n}",
"func (b *BoolMatrixLinear) Width() int {\n\treturn b.width\n}",
"func (c RelativeConstraint) GetWidth() float32 {\n\treturn c.op(c.parent().GetWidth(), c.constant)\n}",
"func (win *Window) Width() int {\n\tsize := C.sfRenderWindow_getSize(win.win)\n\treturn int(size.x)\n}",
"func (m *BoolMatrix) Width() int {\n\treturn m.width\n}",
"func pixelBufferLength(bytesPerPixel int, r Rectangle, imageTypeName string) int {\n\ttotalLength := mul3NonNeg(bytesPerPixel, r.Dx(), r.Dy())\n\tif totalLength < 0 {\n\t\tpanic(\"image: New\" + imageTypeName + \" Rectangle has huge or negative dimensions\")\n\t}\n\treturn totalLength\n}",
"func (w *Window) Width() int {\n\treturn int(C.ANativeWindow_getWidth(w.cptr()))\n}",
"func (p *PdfiumImplementation) FPDF_GetPageWidth(request *requests.FPDF_GetPageWidth) (*responses.FPDF_GetPageWidth, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twidth := C.FPDF_GetPageWidth(pageHandle.handle)\n\n\treturn &responses.FPDF_GetPageWidth{\n\t\tPage: pageHandle.index,\n\t\tWidth: float64(width),\n\t}, nil\n}",
"func (b *Bitmap) Rows() int {\n\treturn int(b.handle.rows)\n}",
"func (screen *GameScreen) Width() int {\n\treturn screen.screenSize.Width\n}",
"func GetRenderbufferWidth(target GLEnum) int32 {\n\tvar params int32\n\tgl.GetRenderbufferParameteriv(uint32(target), gl.RENDERBUFFER_WIDTH, ¶ms)\n\treturn params\n}",
"func (m BoolMatrix) Width() int64 { return m.w }",
"func (sprite *Sprite) Width() int {\n\treturn 16\n}",
"func (b *AppendOnlyBufferedBatch) Width() int {\n\treturn b.batch.Width()\n}",
"func (size *BitmapSize) Size() int64 {\n\treturn int64(size.handle.size)\n}",
"func (i *InputInlineQueryResultDocument) GetThumbnailWidth() (value int32) {\n\tif i == nil {\n\t\treturn\n\t}\n\treturn i.ThumbnailWidth\n}",
"func (f *Font) BytesWidth(b []byte) int {\n\tf.lock()\n\tdefer f.unlock()\n\treturn stringnwidth(f, \"\", b, nil)\n}",
"func (i *InputInlineQueryResultLocation) GetThumbnailWidth() (value int32) {\n\tif i == nil {\n\t\treturn\n\t}\n\treturn i.ThumbnailWidth\n}",
"func (m Model) GetWidth() int {\n\treturn m.Width\n}",
"func (blk *Block) Width() float64 {\n\treturn blk.width\n}",
"func (w *WidgetImplement) Width() int {\n\treturn w.w\n}",
"func (s Spec) Width() float64 {\n\treturn s.SpecWidth\n}",
"func (m *ModuleBase) Width(takable, taken float64) float64 {\n\treturn taken\n}",
"func (g *GitStatusWidget) GetWidth() int {\n\treturn g.renderer.GetWidth()\n}",
"func (n *node) width() int32 {\n\t// find two non-nil nodes\n\tfor i := 0; i < 8; i++ {\n\t\tif n.leafs[i] != nil && n.leafs[i].Center() != nil {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tif n.leafs[j] != nil && n.leafs[j].Center() != nil {\n\t\t\t\t\tp1, p2 := n.leafs[i].Center(), n.leafs[j].Center()\n\t\t\t\t\t// calculate non-zero difference in one of the dimensions (any)\n\t\t\t\t\txwidth := math.Abs(float64(p1.X - p2.X))\n\t\t\t\t\tif xwidth > 0 {\n\t\t\t\t\t\treturn int32(xwidth)\n\t\t\t\t\t}\n\t\t\t\t\tywidth := math.Abs(float64(p1.Y - p2.Y))\n\t\t\t\t\tif ywidth > 0 {\n\t\t\t\t\t\treturn int32(xwidth)\n\t\t\t\t\t}\n\t\t\t\t\tzwidth := math.Abs(float64(p1.Z - p2.Z))\n\t\t\t\t\tif zwidth > 0 {\n\t\t\t\t\t\treturn int32(xwidth)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 0\n}",
"func (self *TraitPixbuf) GetByteLength() (return__ int64) {\n\tvar __cgo__return__ C.gsize\n\t__cgo__return__ = C.gdk_pixbuf_get_byte_length(self.CPointer)\n\treturn__ = int64(__cgo__return__)\n\treturn\n}",
"func (i *InputInlineQueryResultArticle) GetThumbnailWidth() (value int32) {\n\tif i == nil {\n\t\treturn\n\t}\n\treturn i.ThumbnailWidth\n}",
"func (w *Window) Width() int {\n\treturn w.width\n}",
"func (b *BinP1D) XWidth() float64 {\n\treturn b.xrange.Max - b.xrange.Min\n}",
"func (o *V0037DiagRpcm) GetCount() int32 {\n\tif o == nil || o.Count == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Count\n}",
"func (s *ImageSpec) FullWidth() int {\n\tret := int(C.ImageSpec_full_width(s.ptr))\n\truntime.KeepAlive(s)\n\treturn ret\n}",
"func getWidthFd(stdoutFd int) int {\n\tws := &winsize{}\n\tretCode, _, errno := syscall.Syscall(syscall.SYS_IOCTL,\n\t\tuintptr(stdoutFd),\n\t\tuintptr(syscall.TIOCGWINSZ),\n\t\tuintptr(unsafe.Pointer(ws)))\n\n\tif int(retCode) == -1 {\n\t\t_ = errno\n\t\treturn -1\n\t}\n\n\treturn int(ws.Col)\n}",
"func getContentWidth(pdf *gofpdf.Fpdf) float64 {\n\tmarginL, _, marginR, _ := pdf.GetMargins()\n\tpageW, _ := pdf.GetPageSize()\n\twidth := pageW - marginL - marginR\n\treturn width\n}",
"func (pb *Bar) Width() (width int) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\twidth = defaultBarWidth\n\t\t}\n\t}()\n\tpb.mu.RLock()\n\twidth = pb.width\n\tmaxWidth := pb.maxWidth\n\tpb.mu.RUnlock()\n\tif width <= 0 {\n\t\tvar err error\n\t\tif width, err = terminalWidth(); err != nil {\n\t\t\treturn defaultBarWidth\n\t\t}\n\t}\n\tif maxWidth > 0 && width > maxWidth {\n\t\twidth = maxWidth\n\t}\n\treturn\n}",
"func (d *DFT) BinWidth() int {\n\tif d == nil {\n\t\treturn 0\n\t}\n\tif d._binWidth > 0 {\n\t\treturn d._binWidth\n\t}\n\td._binWidth = (d.SampleRate / 2) / len(d.Coefs)\n\treturn d._binWidth\n}",
"func (e Event) GetResizeWidth() int {\n\treturn int(C.caca_get_event_resize_width(e.Ev))\n}",
"func (b *Bitmaps) CountPixels() *basic.NumSlice {\n\tns := &basic.NumSlice{}\n\tfor _, bm := range b.Values {\n\t\tns.AddInt(bm.CountPixels())\n\t}\n\treturn ns\n}",
"func (g Grid) Width() int {\n\treturn g.width\n}",
"func AvgWidth(b1, b2, bTot Bucket) float64 {\n\treturn b2.Max - b1.Min\n}",
"func GetBandWidth() float64 {\n\turl := \"http://169.231.235.221/sedgtomayhem.txt\"\n\tlines := \"10\"\n\t//fmt.Printf(\"Tailing http endpoint : %s\\n\", url)\n\n\tcmd := \"curl \" + url + \" | tail -\" + lines\n\tout, err := exec.Command(\"bash\", \"-c\", cmd).Output()\n\tif err != nil {\n\t\tprintln(err.Error())\n\t\treturn 0\n\t}\n\t// Use reverse scanner to capture the last nonzero bandwidth\n\tscanner := reverse.NewScanner(strings.NewReader(string(out)))\n\tvar (\n\t\tlastLine string\n\t\tbandWidth float64\n\t)\n\tfor scanner.Scan() {\n\t\tlastLine = scanner.Text()\n\t\tfields := strings.Fields(lastLine)\n\t\tbandWidth, err = strconv.ParseFloat(fields[0], 64)\n\t\tif err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\tif bandWidth > 0.0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif bandWidth <= 0.0 {\n\t\tfmt.Println(\"The bandwidth zeroed out! Simulate on average 70.7916 !\")\n\t\tbandWidth = 70.7916\n\t}\n\treturn bandWidth\n}",
"func (self *Graphics) Width() int{\n return self.Object.Get(\"width\").Int()\n}",
"func (l *label) GetFieldWidth() int {\n\treturn 0\n}"
] | [
"0.76084745",
"0.68951255",
"0.66357315",
"0.66190416",
"0.6554075",
"0.65434545",
"0.64942837",
"0.63843596",
"0.634525",
"0.6341199",
"0.62462854",
"0.62294286",
"0.617959",
"0.6177848",
"0.61363554",
"0.61173654",
"0.6069323",
"0.60453403",
"0.60182947",
"0.6011932",
"0.5994543",
"0.5923918",
"0.5860254",
"0.5833483",
"0.5811669",
"0.5783268",
"0.57760733",
"0.57690066",
"0.5742432",
"0.57193923",
"0.56340516",
"0.56217885",
"0.5603009",
"0.5575835",
"0.5575629",
"0.5569908",
"0.5562879",
"0.55490875",
"0.5545021",
"0.55381936",
"0.5527947",
"0.55021465",
"0.5496386",
"0.54932326",
"0.5479943",
"0.54766494",
"0.5474708",
"0.54667854",
"0.54596764",
"0.5449134",
"0.54053664",
"0.5380933",
"0.53261846",
"0.53028166",
"0.53013086",
"0.5287997",
"0.52420026",
"0.51774645",
"0.5163777",
"0.51608497",
"0.5134742",
"0.5126965",
"0.51237607",
"0.51159143",
"0.5103739",
"0.50971824",
"0.50569326",
"0.5028233",
"0.50059056",
"0.49967182",
"0.49877715",
"0.4983653",
"0.49834037",
"0.49805078",
"0.4967768",
"0.49610406",
"0.49598986",
"0.49085438",
"0.4908021",
"0.48680162",
"0.48570007",
"0.48359388",
"0.48073417",
"0.4800816",
"0.4796413",
"0.47893733",
"0.47653764",
"0.47632506",
"0.47534785",
"0.47482488",
"0.47461662",
"0.47159293",
"0.4713405",
"0.4693924",
"0.46841308",
"0.46696967",
"0.466775",
"0.46394247",
"0.46342757",
"0.46310142"
] | 0.7980471 | 0 |
FPDFBitmap_GetHeight returns the height of a bitmap. | func (p *PdfiumImplementation) FPDFBitmap_GetHeight(request *requests.FPDFBitmap_GetHeight) (*responses.FPDFBitmap_GetHeight, error) {
p.Lock()
defer p.Unlock()
bitmapHandle, err := p.getBitmapHandle(request.Bitmap)
if err != nil {
return nil, err
}
height := C.FPDFBitmap_GetHeight(bitmapHandle.handle)
return &responses.FPDFBitmap_GetHeight{
Height: int(height),
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (size *BitmapSize) Height() int16 {\n\treturn int16(size.handle.height)\n}",
"func (p *Picture) GetHeight() int {\r\n\treturn p.pixelHeight\r\n}",
"func (r *ImageRef) Height() int {\n\treturn int(r.image.Ysize)\n}",
"func (info *ImageInfoType) Height() float64 {\n\treturn info.h / (info.scale * info.dpi / 72)\n}",
"func (o GoogleCloudRetailV2alphaImageOutput) Height() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaImage) *int { return v.Height }).(pulumi.IntPtrOutput)\n}",
"func (image *Image2D) GetHeight() int {\n\treturn image.height\n}",
"func (image *JPGImage) GetHeight() float32 {\n\treturn float32(image.height)\n}",
"func (is ImageSurface) Height() int {\n\treturn is.height\n}",
"func (me *Image) Height() int {\n\treturn int(me.img.h)\n}",
"func (v *Pixbuf) GetHeight() int {\n\treturn int(C.gdk_pixbuf_get_height(v.Native()))\n}",
"func (self *TraitPixbuf) GetHeight() (return__ int) {\n\tvar __cgo__return__ C.int\n\t__cgo__return__ = C.gdk_pixbuf_get_height(self.CPointer)\n\treturn__ = int(__cgo__return__)\n\treturn\n}",
"func (o *FileInfoThumbnail) GetHeight() int32 {\n\tif o == nil || o.Height == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Height\n}",
"func (s *ImageSpec) Height() int {\n\tret := int(C.ImageSpec_height(s.ptr))\n\truntime.KeepAlive(s)\n\treturn ret\n}",
"func (bm Blendmap) Height() float32 {\n\treturn bm.Map.height\n}",
"func (tex *Image) Height() int {\n\tsize := C.sfTexture_getSize(tex.tex)\n\treturn int(size.y)\n}",
"func (image *Image) Height() int {\n\treturn image.height\n}",
"func (f *Face) Height() int {\n\treturn f.ypixels(int(f.handle.height))\n}",
"func (r *ImageRef) GetPageHeight() int {\n\treturn vipsGetPageHeight(r.image)\n}",
"func (rect *PdfRectangle) Height() float64 {\n\treturn math.Abs(rect.Ury - rect.Lly)\n}",
"func (mw *MagickWand) Height() uint {\n\treturn mw.GetImageHeight()\n}",
"func (f *Framebuffer) Height() int { return f.fb.Bounds().Max.Y }",
"func (r *ImageRef) PageHeight() int {\n\treturn vipsGetPageHeight(r.image)\n}",
"func (b *BaseElement) GetHeight() int32 {\n\treturn b.h\n}",
"func (o *TileBounds) GetHeight() int32 {\n\tif o == nil || o.Height == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Height\n}",
"func (o GoogleCloudRetailV2alphaImageResponseOutput) Height() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaImageResponse) int { return v.Height }).(pulumi.IntOutput)\n}",
"func (rc Rectangle) Height() int {\n\treturn rc.Bottom - rc.Top\n}",
"func (self *TraitPixbufAnimation) GetHeight() (return__ int) {\n\tvar __cgo__return__ C.int\n\t__cgo__return__ = C.gdk_pixbuf_animation_get_height(self.CPointer)\n\treturn__ = int(__cgo__return__)\n\treturn\n}",
"func (a *Asset) GetHeight() float64 {\n\tif a == nil || a.Height == nil {\n\t\treturn 0.0\n\t}\n\treturn *a.Height\n}",
"func (t *Texture) GetHeight() uint16 {\n\treturn t.height\n}",
"func getHeight() int {\n\tfor {\n\t\theight := go50.GetInt(\"Height: \")\n\t\tif height > 0 && height < 24 {\n\t\t\treturn height\n\t\t}\n\t}\n}",
"func GetHeight(ctx Context) (int64, bool) {\n\tval, ok := ctx.Value(contextKeyHeight).(int64)\n\treturn val, ok\n}",
"func Height() int {\n\tws, err := getWinsize()\n\tif err != nil {\n\t\treturn -1\n\t}\n\treturn int(ws.Row)\n}",
"func (dim *Dimensions) Height() int64 {\n\treturn dim.height\n}",
"func GetHeight() int {\n\treturn viper.GetInt(FlagHeight)\n}",
"func (c *DataCache) GetHeight() uint32 {\n\tc.mtx.RLock()\n\tdefer c.mtx.RUnlock()\n\treturn c.height\n}",
"func (r Rectangle) Height() float64 {\n\treturn r.Max.Y - r.Min.Y\n}",
"func (m BoolMatrix) Height() int64 { return m.h }",
"func (t *Link) GetHeight() (v int64) {\n\treturn *t.height.nonNegativeInteger\n\n}",
"func (s *SimPDF) Height() float64 {\n\tif s.Page.IsLandscape {\n\t\treturn s.Page.Width\n\t}\n\treturn s.Page.Height\n}",
"func (m *Matrix) Height() int {\n\treturn -1\n}",
"func (pc PieChart) GetHeight() int {\n\tif pc.Height == 0 {\n\t\treturn DefaultChartWidth\n\t}\n\treturn pc.Height\n}",
"func (b *BoundingBox2D) height() float64 {\n\n\treturn b.upperCorner.Y - b.lowerCorner.Y\n}",
"func (bm Bitmap) Len() int {\n\treturn len(bm) * 32\n}",
"func (spr *Sprite) Height() int32 {\n\n\treturn spr.height\n}",
"func (o *WorkbookChart) GetHeight() AnyOfnumberstringstring {\n\tif o == nil || o.Height == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret\n\t}\n\treturn *o.Height\n}",
"func (a *Animation) GetHeight() float64 {\n\tif a == nil || a.Height == nil {\n\t\treturn 0.0\n\t}\n\treturn *a.Height\n}",
"func (num *number) Height() int {\n\tvar res = num.size * 4 / 5\n\n\tif res%2 == 0 {\n\t\treturn res + 1\n\t}\n\n\treturn res\n}",
"func (data *Data) GetCntMinMaxHeight() (int, int, int, error) {\n\tdb, err := data.openDb()\n\tdefer data.closeDb(db)\n\tif err != nil {\n\t\tlog.Printf(\"data.openDb Error : %+v\", err)\n\t\treturn -1, -1, -1, err\n\t}\n\tvar cnt int\n\terr = db.QueryRow(\"SELECT COUNT(hash) FROM headers\").Scan(&cnt)\n\tif err != nil {\n\t\tlog.Printf(\"db.QueryRow Error : %+v\", err)\n\t\treturn -1, -1, -1, err\n\t}\n\tif cnt == 0 {\n\t\treturn cnt, -1, -1, nil\n\t}\n\tvar max int\n\tvar min int\n\terr = db.QueryRow(\"SELECT MIN(height), MAX(height) FROM headers\").Scan(&min, &max)\n\tif err != nil {\n\t\tlog.Printf(\"db.QueryRow Error : %+v\", err)\n\t\treturn -1, -1, -1, err\n\t}\n\treturn cnt, min, max, nil\n}",
"func (s *ImageSpec) TileHeight() int {\n\tret := int(C.ImageSpec_tile_height(s.ptr))\n\truntime.KeepAlive(s)\n\treturn ret\n}",
"func (i *InputInlineQueryResultPhoto) GetPhotoHeight() (value int32) {\n\tif i == nil {\n\t\treturn\n\t}\n\treturn i.PhotoHeight\n}",
"func Height() uint64 {\n\n\tglobalData.RLock()\n\tdefer globalData.RUnlock()\n\n\treturn globalData.height\n}",
"func (s *PageLayout) Height() float64 {\n\treturn s.height\n}",
"func (win *Window) Height() int {\n\tsize := C.sfRenderWindow_getSize(win.win)\n\treturn int(size.y)\n}",
"func (o *FileInfoThumbnail) GetHeightOk() (*int32, bool) {\n\tif o == nil || o.Height == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Height, true\n}",
"func (f *Font) Height() int { return int(C.TTF_FontHeight(f.f)) }",
"func GetHeight(hostURL string, hostPort int) *bytes.Buffer {\n\treturn makeGetRequest(\"getheight\", hostURL, hostPort)\n}",
"func (b *Bound) Height() float64 {\n\treturn b.ne.Y() - b.sw.Y()\n}",
"func (lc *FilChain) GetHeight(ctx context.Context) (uint64, error) {\n\th, err := lc.api.ChainHead(ctx)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"get head from lotus node: %s\", err)\n\t}\n\treturn uint64(h.Height()), nil\n}",
"func (s Spritesheet) Height() float32 {\n\treturn s.texture.Height() / float32(s.CellHeight)\n}",
"func (p *PdfiumImplementation) FPDF_GetPageHeight(request *requests.FPDF_GetPageHeight) (*responses.FPDF_GetPageHeight, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageHandle, err := p.loadPage(request.Page)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theight := C.FPDF_GetPageHeight(pageHandle.handle)\n\n\treturn &responses.FPDF_GetPageHeight{\n\t\tPage: pageHandle.index,\n\t\tHeight: float64(height),\n\t}, nil\n}",
"func (o *WorkbookChart) GetHeightOk() (AnyOfnumberstringstring, bool) {\n\tif o == nil || o.Height == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret, false\n\t}\n\treturn *o.Height, true\n}",
"func (g *Grid) GetHeight() int {\n\treturn g.Height\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetWidth(request *requests.FPDFBitmap_GetWidth) (*responses.FPDFBitmap_GetWidth, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twidth := C.FPDFBitmap_GetWidth(bitmapHandle.handle)\n\treturn &responses.FPDFBitmap_GetWidth{\n\t\tWidth: int(width),\n\t}, nil\n}",
"func (w *SVGWriter) Height() int {\n\treturn int(float64(w.Width()) * w.ViewBoxHeight() / w.ViewBoxWidth())\n}",
"func (g Grid) PixelHeight() int32 {\n\treturn int32(g.height) * g.cellSize\n}",
"func (bfx *bloomfilterIndexer) Height() (uint64, error) {\n\th, err := bfx.flusher.KVStoreWithBuffer().Get(RangeBloomFilterNamespace, []byte(CurrentHeightKey))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn byteutil.BytesToUint64(h), nil\n}",
"func (w *Window) Height() int {\n\treturn int(C.ANativeWindow_getHeight(w.cptr()))\n}",
"func (o *TileBounds) GetHeightOk() (*int32, bool) {\n\tif o == nil || o.Height == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Height, true\n}",
"func (c *Canvas) Height() int {\n\treturn c.maxCorner.Y - c.minCorner.Y + 1\n}",
"func (size *BitmapSize) Size() int64 {\n\treturn int64(size.handle.size)\n}",
"func (w *WidgetImplement) Height() int {\n\treturn w.h\n}",
"func (t *BinaryTree) Height() (int, error) {\n\tif t.root == nil {\n\t\treturn 0, errors.New(\"Tree is empty\")\n\t}\n\n\tvar maxHeight func(bnode *bnode) int\n\n\tmaxHeight = func(bnode *bnode) int {\n\t\tif bnode == nil {\n\t\t\treturn 0\n\t\t}\n\t\tlHeight := maxHeight(bnode.left)\n\t\trHeight := maxHeight(bnode.right)\n\n\t\tif lHeight > rHeight {\n\t\t\treturn lHeight + 1\n\t\t}\n\t\treturn rHeight + 1\n\t}\n\tresult := maxHeight(t.root)\n\treturn result, nil\n}",
"func (env *Environment) getHeight(latestHeight int64, heightPtr *int64) (int64, error) {\n\tif heightPtr != nil {\n\t\theight := *heightPtr\n\t\tif height <= 0 {\n\t\t\treturn 0, fmt.Errorf(\"%w (requested height: %d)\", coretypes.ErrZeroOrNegativeHeight, height)\n\t\t}\n\t\tif height > latestHeight {\n\t\t\treturn 0, fmt.Errorf(\"%w (requested height: %d, blockchain height: %d)\",\n\t\t\t\tcoretypes.ErrHeightExceedsChainHead, height, latestHeight)\n\t\t}\n\t\tbase := env.BlockStore.Base()\n\t\tif height < base {\n\t\t\treturn 0, fmt.Errorf(\"%w (requested height: %d, base height: %d)\", coretypes.ErrHeightNotAvailable, height, base)\n\t\t}\n\t\treturn height, nil\n\t}\n\treturn latestHeight, nil\n}",
"func (ws *workingSet) Height() (uint64, error) {\n\treturn ws.height, nil\n}",
"func (rt *recvTxOut) Height() int32 {\n\theight := int32(-1)\n\tif rt.block != nil {\n\t\theight = rt.block.Height\n\t}\n\treturn height\n}",
"func (i *InputInlineQueryResultContact) GetThumbnailHeight() (value int32) {\n\tif i == nil {\n\t\treturn\n\t}\n\treturn i.ThumbnailHeight\n}",
"func (t Texture3D) GetHeight() int32 {\n\treturn t.height\n}",
"func (self *TraitPixbuf) GetByteLength() (return__ int64) {\n\tvar __cgo__return__ C.gsize\n\t__cgo__return__ = C.gdk_pixbuf_get_byte_length(self.CPointer)\n\treturn__ = int64(__cgo__return__)\n\treturn\n}",
"func (h *HeightCache) GetHeight() (height uint64) {\n\th.RLock()\n\theight = h.height\n\th.RUnlock()\n\treturn\n}",
"func (s *SkipList) getHeight() uint32 {\n\t// Height can be modified concurrently, so we need to load it atomically.\n\treturn atomic.LoadUint32(&s.height)\n}",
"func (root *TreeNode) getHeight() int64 {\n\tif root != nil {\n\t\treturn root.height\n\t}\n\treturn -1\n}",
"func (sprite *Sprite) Height() int {\n\treturn 16\n}",
"func (pgb *ChainDB) GetHeight() (int64, error) {\n\tctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)\n\tdefer cancel()\n\theight, _, _, err := RetrieveBestBlockHeight(ctx, pgb.db)\n\t// If the blocks table is empty, set height to -1.\n\tbb := int64(height)\n\tif err == sql.ErrNoRows {\n\t\tbb = -1\n\t}\n\treturn bb, pgb.replaceCancelError(err)\n}",
"func (t *RBT) Height() int {\n\treturn 0\n}",
"func (t *Track) Height() int {\n\treturn t.height\n}",
"func (r *renderer) Height() int {\n\t// TODO(knz): Support multi-line items, e.g. identifiers\n\t// containing a newline character.\n\treturn 1\n}",
"func getHeight(latestHeight int64, heightPtr *int64) (int64, error) {\n\tif heightPtr != nil {\n\t\theight := *heightPtr\n\t\tif height <= 0 {\n\t\t\treturn 0, fmt.Errorf(\"height must be greater than 0, but got %d\", height)\n\t\t}\n\t\tif height > latestHeight {\n\t\t\treturn 0, fmt.Errorf(\"height %d must be less than or equal to the current blockchain height %d\",\n\t\t\t\theight, latestHeight)\n\t\t}\n\t\tbase := env.BlockStore.Base()\n\t\tif height < base {\n\t\t\treturn 0, fmt.Errorf(\"height %d is not available, lowest height is %d\",\n\t\t\t\theight, base)\n\t\t}\n\t\treturn height, nil\n\t}\n\treturn latestHeight, nil\n}",
"func (u *Upstream) GetHeight() uint64 {\n\treturn u.blockHeight\n}",
"func (m *Model) GetHeight() int {\n\treturn m.height\n}",
"func (o DashboardFreeFormLayoutElementOutput) Height() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DashboardFreeFormLayoutElement) string { return v.Height }).(pulumi.StringOutput)\n}",
"func (o DashboardSectionStylePtrOutput) Height() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DashboardSectionStyle) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Height\n\t}).(pulumi.StringPtrOutput)\n}",
"func (screen *GameScreen) Height() int {\n\treturn screen.screenSize.Height\n}",
"func (l *Label) height() int8 {\n if (l == nil) {\n return int8(-1)\n }\n return int8(l.h)\n}",
"func getImageDimensions(imagePath string) (int, int) {\n file, err := os.Open(imagePath)\n if err != nil {\n fmt.Fprintf(os.Stderr, \"%v\\n\", err)\n }\n defer file.Close()\n imageConfig, _, err := image.DecodeConfig(file)\n if err != nil {\n fmt.Fprintf(os.Stderr, \"%s: %v\\n\", imagePath, err)\n }\n return imageConfig.Width, imageConfig.Height\n}",
"func (pb *PutBlock) Height() uint64 { return pb.height }",
"func (g *Graph) Height() uint64 {\n\tg.RLock()\n\theight := g.height\n\tg.RUnlock()\n\n\treturn height\n}",
"func (bn BlockNumber) TmHeight() *int64 {\n\tif bn < 0 {\n\t\treturn nil\n\t} else if bn == EthEarliestBlockNumber {\n\t\tvar firstHeight int64 = 0\n\t\treturn &firstHeight\n\t}\n\n\theight := bn.Int64()\n\treturn &height\n}",
"func (o DashboardLegendOptionsPtrOutput) Height() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DashboardLegendOptions) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Height\n\t}).(pulumi.StringPtrOutput)\n}",
"func GetRenderbufferHeight(target GLEnum) int32 {\n\tvar params int32\n\tgl.GetRenderbufferParameteriv(uint32(target), gl.RENDERBUFFER_HEIGHT, ¶ms)\n\treturn params\n}",
"func (tree *BinaryTree) Height() int {\n\treturn len(tree.LevelOrderTraversel())\n}"
] | [
"0.70232034",
"0.6861557",
"0.6771859",
"0.675743",
"0.6638518",
"0.6587529",
"0.6424647",
"0.6424015",
"0.6400868",
"0.62682945",
"0.6255568",
"0.6255069",
"0.6250484",
"0.623152",
"0.6226616",
"0.62080526",
"0.6121466",
"0.6080347",
"0.6022829",
"0.60007775",
"0.59861654",
"0.5963879",
"0.5884944",
"0.58063656",
"0.57886565",
"0.57777554",
"0.5742517",
"0.5739407",
"0.5707538",
"0.56895113",
"0.5677883",
"0.5672205",
"0.5647302",
"0.56290126",
"0.561413",
"0.5592755",
"0.5591378",
"0.5565349",
"0.55645937",
"0.55440533",
"0.55375814",
"0.5512234",
"0.5505287",
"0.55045563",
"0.5504363",
"0.5501836",
"0.5494495",
"0.5488315",
"0.5474701",
"0.54688543",
"0.5418686",
"0.54015315",
"0.5399963",
"0.53997225",
"0.53757757",
"0.5364491",
"0.5359643",
"0.5359629",
"0.53437895",
"0.53258395",
"0.5320761",
"0.5301272",
"0.53009474",
"0.529931",
"0.52946335",
"0.52838576",
"0.5275358",
"0.52655023",
"0.5252228",
"0.5242328",
"0.5231096",
"0.5216888",
"0.52075773",
"0.52065223",
"0.51924485",
"0.5189024",
"0.51492447",
"0.51421964",
"0.51353496",
"0.5114796",
"0.5104982",
"0.5104645",
"0.5101726",
"0.5093085",
"0.5082873",
"0.50815666",
"0.50690883",
"0.50674266",
"0.5064973",
"0.5062584",
"0.5061604",
"0.50455636",
"0.50412315",
"0.5037582",
"0.5015902",
"0.501483",
"0.5008598",
"0.5002075",
"0.49984208",
"0.499375"
] | 0.8092238 | 0 |
FPDFBitmap_GetStride returns the number of bytes for each line in the bitmap buffer. | func (p *PdfiumImplementation) FPDFBitmap_GetStride(request *requests.FPDFBitmap_GetStride) (*responses.FPDFBitmap_GetStride, error) {
p.Lock()
defer p.Unlock()
bitmapHandle, err := p.getBitmapHandle(request.Bitmap)
if err != nil {
return nil, err
}
stride := C.FPDFBitmap_GetStride(bitmapHandle.handle)
return &responses.FPDFBitmap_GetStride{
Stride: int(stride),
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (vbl *VertexLayout) stride() int {\n\tsize := 0\n\tfor _, i := range vbl.layout {\n\t\tsize += i.getByteSize()\n\t}\n\n\treturn size\n}",
"func (s *ImageSpec) ScanlineBytes(native bool) int {\n\tret := int(C.ImageSpec_scanline_bytes(s.ptr, C.bool(native)))\n\truntime.KeepAlive(s)\n\treturn ret\n}",
"func (self *TraitPixbuf) GetRowstride() (return__ int) {\n\tvar __cgo__return__ C.int\n\t__cgo__return__ = C.gdk_pixbuf_get_rowstride(self.CPointer)\n\treturn__ = int(__cgo__return__)\n\treturn\n}",
"func (b *Bitmap) Rows() int {\n\treturn int(b.handle.rows)\n}",
"func pixelBufferLength(bytesPerPixel int, r Rectangle, imageTypeName string) int {\n\ttotalLength := mul3NonNeg(bytesPerPixel, r.Dx(), r.Dy())\n\tif totalLength < 0 {\n\t\tpanic(\"image: New\" + imageTypeName + \" Rectangle has huge or negative dimensions\")\n\t}\n\treturn totalLength\n}",
"func (b *Bitmap) Width() int {\n\treturn int(b.handle.width)\n}",
"func (b *AppendOnlyBufferedBatch) Width() int {\n\treturn b.batch.Width()\n}",
"func (bm Bitmap) Len() int {\n\treturn len(bm) * 32\n}",
"func (b *Buffer) Len() int {\n\treturn b.Width * b.Height\n}",
"func (is ImageSurface) Stride() int {\n\treturn is.stride\n}",
"func (b *Bitmap) Buffer() []byte {\n\tl := b.Rows() * b.Pitch()\n\treturn C.GoBytes(unsafe.Pointer(b.handle.buffer), C.int(l))\n}",
"func GetBuffLen() (uint64, uint64, uint64) {\n\treturn rbmd001map.Len(), rbmd002map.Len(), rbmd004map.Len()\n}",
"func (f *Font) BytesWidth(b []byte) int {\n\tf.lock()\n\tdefer f.unlock()\n\treturn stringnwidth(f, \"\", b, nil)\n}",
"func (m *ScreenMode) BytesPerPixel() int {\n\treturn m.bytesPerPixel\n}",
"func (b *Buffer) getNumOfVisibleRows () int {\n visibleRows := b.rowsOffset + (b.maxVisibleRows - b.reservedRows)\n\n if visibleRows > len(b.rows) {\n visibleRows = len(b.rows)\n }\n\n return visibleRows\n}",
"func (image *Image2D) GetWidth() int {\n\treturn image.width\n}",
"func (p *Picture) GetWidth() int {\r\n\treturn p.pixelWidth\r\n}",
"func (b *Bitmap) GetByteIndex(x, y int) int {\n\treturn y*b.RowStride + (x >> 3)\n}",
"func (size *BitmapSize) Width() int16 {\n\treturn int16(size.handle.width)\n}",
"func (self *TraitPixbuf) GetByteLength() (return__ int64) {\n\tvar __cgo__return__ C.gsize\n\t__cgo__return__ = C.gdk_pixbuf_get_byte_length(self.CPointer)\n\treturn__ = int64(__cgo__return__)\n\treturn\n}",
"func (m *Mapper) NumLines() int {\n\treturn len(m.offsets) - 1\n}",
"func (fw *Writer) NumRows() int { return fw.nrows }",
"func (p *PixelLine) Len() int {\n\treturn p.len\n}",
"func (pi *PixelIterator) GetIteratorRow() int {\n\tret := int(C.PixelGetIteratorRow(pi.pi))\n\truntime.KeepAlive(pi)\n\treturn ret\n}",
"func (s *ImageSpec) Width() int {\n\tret := int(C.ImageSpec_width(s.ptr))\n\truntime.KeepAlive(s)\n\treturn ret\n}",
"func lineCounter(r io.Reader) (int, error) {\n\tbuf := make([]byte, 32*1024)\n\tcount := 0\n\tlineSep := []byte{'\\n'}\n\tvar lastByte byte\n\tlastByte = '\\n'\n\n\tfor {\n\t\tc, err := r.Read(buf)\n\t\tif c > 0 {\n\t\t\tlastByte = buf[c-1]\n\t\t}\n\t\tcount += bytes.Count(buf[:c], lineSep)\n\n\t\tswitch {\n\t\tcase err == io.EOF:\n\t\t\tif lastByte != '\\n' {\n\t\t\t\tlog.Warn(fmt.Sprintf(\"Last byte in buffer is '%v'\", lastByte))\n\t\t\t\tcount += 1\n\t\t\t}\n\t\t\treturn count, nil\n\n\t\tcase err != nil:\n\t\t\treturn count, err\n\t\t}\n\t}\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetWidth(request *requests.FPDFBitmap_GetWidth) (*responses.FPDFBitmap_GetWidth, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twidth := C.FPDFBitmap_GetWidth(bitmapHandle.handle)\n\treturn &responses.FPDFBitmap_GetWidth{\n\t\tWidth: int(width),\n\t}, nil\n}",
"func GetPixels(img image.Image, rowPitch int) ([]uint8, error) {\n\tnewImg := image.NewRGBA(img.Bounds())\n\tif rowPitch <= 4*img.Bounds().Dy() {\n\t\t// apply the proposed row pitch only if supported,\n\t\t// as we're using only optimal textures.\n\t\tnewImg.Stride = rowPitch\n\t}\n\tdraw.Draw(newImg, newImg.Bounds(), img, image.ZP, draw.Src)\n\treturn newImg.Pix, nil\n}",
"func (b *ByteBuffer) GetReadBytes() int64 {\n\treturn int64(b.off)\n}",
"func (s *ImageSpec) PixelBytes(native bool) int {\n\tret := int(C.ImageSpec_pixel_bytes(s.ptr, C.bool(native)))\n\truntime.KeepAlive(s)\n\treturn ret\n}",
"func (v Binary) Len(width int) int {\n\tw := dataWidth(width)\n\tl := v.size / int64(w)\n\tif v.size%int64(w) > 0 {\n\t\tl++\n\t}\n\treturn int(l)\n}",
"func LineCounter(r io.Reader) (int, error) {\n buf := make([]byte, 32*1024)\n count := 0\n lineSep := []byte{'\\n'}\n\n for {\n c, err := r.Read(buf)\n count = count + bytes.Count(buf[:c], lineSep)\n switch {\n case err == io.EOF:\n return count, nil\n case err != nil:\n return count, err\n }\n }\n}",
"func (g Grid) PixelWidth() int32 {\n\treturn int32(g.width) * g.cellSize\n}",
"func (spriteBatch *SpriteBatch) GetBufferSize() int {\n\treturn spriteBatch.size\n}",
"func GetEncodedBlocksLen(inputLen int, k, m uint8) (outputLen int) {\n\toutputLen = GetEncodedBlockLen(inputLen, k) * int(k+m)\n\treturn outputLen\n}",
"func (o GoogleCloudRetailV2alphaImageOutput) Width() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaImage) *int { return v.Width }).(pulumi.IntPtrOutput)\n}",
"func (rect *PdfRectangle) Width() float64 {\n\treturn math.Abs(rect.Urx - rect.Llx)\n}",
"func (s *CountMinSketch) Width() uint {\n\treturn s.w\n}",
"func GetBytesSlicePtr4K() *[]byte {\n\tif p := get4K(); p != nil {\n\t\treturn p\n\t}\n\tif b := getb4K(); b != nil {\n\t\tp := internal.Bb2bs(b)\n\t\treturn internal.Gets(p)\n\t}\n\tp := make([]byte, 4096)\n\treturn &p\n}",
"func (r *ImageRef) Width() int {\n\treturn int(r.image.Xsize)\n}",
"func GetBytesSlicePtr32K() *[]byte {\n\tif p := get32K(); p != nil {\n\t\treturn p\n\t}\n\tif b := getb32K(); b != nil {\n\t\tp := internal.Bb2bs(b)\n\t\treturn internal.Gets(p)\n\t}\n\tp := make([]byte, 32768)\n\treturn &p\n}",
"func (w *writer) chunkCount(b []byte) int {\n\tlenB := len(b)\n\tif lenB <= w.chunkSize {\n\t\treturn 1\n\t}\n\n\treturn len(b)/w.chunkDataSize + 1\n}",
"func GetDirectBufferCapacity(env *C.JNIEnv, buf C.jobject) C.jlong {\n\treturn C._GoJniGetDirectBufferCapacity(env, buf)\n}",
"func lineCounter(r io.Reader) (int, error) {\n\tbuf := make([]byte, 32*1024)\n\tcount := 0\n\tlineSep := []byte{'\\n'}\n\n\tfor {\n\t\tc, err := r.Read(buf)\n\t\tcount += bytes.Count(buf[:c], lineSep)\n\n\t\tswitch {\n\t\tcase err == io.EOF:\n\t\t\treturn count, nil\n\n\t\tcase err != nil:\n\t\t\treturn count, err\n\t\t}\n\t}\n}",
"func lineCounter(r io.Reader) (int, error) {\n\tbuf := make([]byte, 32*1024)\n\tcount := 0\n\tlineSep := []byte{'\\n'}\n\n\tfor {\n\t\tc, err := r.Read(buf)\n\t\tcount += bytes.Count(buf[:c], lineSep)\n\n\t\tswitch {\n\t\tcase err == io.EOF:\n\t\t\treturn count, nil\n\n\t\tcase err != nil:\n\t\t\treturn count, err\n\t\t}\n\t}\n}",
"func (self *TraitPixbuf) GetWidth() (return__ int) {\n\tvar __cgo__return__ C.int\n\t__cgo__return__ = C.gdk_pixbuf_get_width(self.CPointer)\n\treturn__ = int(__cgo__return__)\n\treturn\n}",
"func (g GenericBackend) ReadFramebufferCount(ctx context.Context, width, height int) (framebuffers int, e error) {\n\tf, err := os.Open(fmt.Sprintf(genericFramebufferFilePattern, g.index))\n\tif err != nil {\n\t\treturn framebuffers, errors.Wrap(err, \"failed to open dri file\")\n\t}\n\n\ttext, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn framebuffers, errors.Wrap(err, \"failed to read dri file\")\n\t}\n\tlines := strings.Split(string(text), \"\\n\")\n\tfor _, line := range lines {\n\t\t// The line we're looking for looks like \"...size=1920x1080\"\n\t\tvar fbWidth, fbHeight int\n\t\tif _, err := fmt.Sscanf(line, \" size=%dx%d\", &fbWidth, &fbHeight); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif fbWidth == width && fbHeight == height {\n\t\t\tframebuffers++\n\t\t}\n\t}\n\treturn\n}",
"func (f *Framebuffer) Width() int { return f.fb.Bounds().Max.X }",
"func GetBytesSlicePtr4M() *[]byte {\n\tif p := get4M(); p != nil {\n\t\treturn p\n\t}\n\tif b := getb4M(); b != nil {\n\t\tp := internal.Bb2bs(b)\n\t\treturn internal.Gets(p)\n\t}\n\tp := make([]byte, 4194304)\n\treturn &p\n}",
"func (c *StepLookbackAccumulator) BufferStepCount() int {\n\treturn len(c.unconsumed)\n}",
"func (b *FixedBuffer) Len() int {\n\treturn b.w - b.r\n}",
"func (m *GetBufferResponse) GetNumLinesAboveScreen() int64 {\n\tif m != nil && m.NumLinesAboveScreen != nil {\n\t\treturn *m.NumLinesAboveScreen\n\t}\n\treturn 0\n}",
"func (bm Blendmap) Width() float32 {\n\treturn bm.Map.width\n}",
"func (v *Pixbuf) GetWidth() int {\n\treturn int(C.gdk_pixbuf_get_width(v.Native()))\n}",
"func GetBytesBuffer32K() *bytes.Buffer {\n\tif b := getb32K(); b != nil {\n\t\treturn b\n\t}\n\tif p := get32K(); p != nil {\n\t\treturn bytes.NewBuffer(internal.Puts(p))\n\t}\n\treturn bytes.NewBuffer(make([]byte, 32768))\n}",
"func (t *Decoder) Skip() (boundary int, err error) {\n\t// var i int\n\tfor {\n\t\tif len(t.window) < t.minimum {\n\t\t\t// try to refill the buffer when window gets small\n\t\t\tif err = t.fillBuffer(); err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\treturn 0, nil // swallow io.EOF\n\t\t\t\t}\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t}\n\n\t\t// try to detect a boundary and keep going if you do\n\t\ti := 0\n\t\tfor ; i < len(t.window); i++ {\n\t\t\tif t.window[i] == telomereMarkByte {\n\t\t\t\tboundary++\n\t\t\t\tif boundary > t.maximum {\n\t\t\t\t\tt.window = t.window[i:]\n\t\t\t\t\treturn 0, errors.New(\"maximum telomere length exceeded\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tt.window = t.window[i:]\n\t\t\t\treturn boundary, nil\n\t\t\t}\n\t\t}\n\t\tt.window = t.window[i:]\n\t}\n}",
"func (s *SeriesIDSet) Bytes() int {\n\tvar b int\n\ts.RLock()\n\tb += 24 // mu RWMutex is 24 bytes\n\tb += int(unsafe.Sizeof(s.bitmap)) + int(s.bitmap.GetSizeInBytes())\n\ts.RUnlock()\n\treturn b\n}",
"func (me *Image) Width() int {\n\treturn int(me.img.w)\n}",
"func (p *PdfiumImplementation) FPDFBitmap_GetBuffer(request *requests.FPDFBitmap_GetBuffer) (*responses.FPDFBitmap_GetBuffer, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmapHandle, err := p.getBitmapHandle(request.Bitmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We need to calculate the buffer size, this is stride (bytes per bitmap line) * height.\n\tstride := C.FPDFBitmap_GetStride(bitmapHandle.handle)\n\theight := C.FPDFBitmap_GetHeight(bitmapHandle.handle)\n\tsize := int(stride * height)\n\n\t// The pointer to the first byte of the bitmap buffer.\n\tbuffer := C.FPDFBitmap_GetBuffer(bitmapHandle.handle)\n\n\t// We create a Go slice backed by a C array (without copying the original data).\n\tdata := unsafe.Slice((*byte)(unsafe.Pointer(buffer)), uint64(size))\n\n\treturn &responses.FPDFBitmap_GetBuffer{\n\t\tBuffer: data,\n\t}, nil\n}",
"func LineCount(r io.Reader, skipEmpty bool) int {\n\tif r == nil {\n\t\treturn -1\n\t}\n\n\tsc := bufio.NewScanner(r)\n\tvar i int\n\n\tif skipEmpty {\n\t\tfor sc.Scan() {\n\t\t\tif len(sc.Bytes()) > 0 {\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tif sc.Err() != nil {\n\t\t\treturn -1\n\t\t}\n\n\t\treturn i\n\t}\n\n\tfor i = 0; sc.Scan(); i++ {\n\t}\n\n\treturn i\n}",
"func (info *ImageInfoType) Width() float64 {\n\treturn info.w / (info.scale * info.dpi / 72)\n}",
"func calculateBuffers(blocks uint64) (buffers uint64) {\n\tbuffers = blocks / NBufferBlocks\n\tif blocks%NBufferBlocks != 0 {\n\t\tbuffers++\n\t}\n\treturn\n}",
"func calculateBufferSize(blocks uint64) uint64 {\n\tif nbb := NBufferBlocks; blocks < nbb {\n\t\treturn blocks\n\t} else {\n\t\treturn nbb\n\t}\n}",
"func (rc Rectangle) Width() int {\n\treturn rc.Right - rc.Left\n}",
"func (da *DoubleArray) AllocBytes() int {\n\treturn da.ArrayLen()*8 + da.TailLen()\n}",
"func (b *BoolMatrixLinear) Width() int {\n\treturn b.width\n}",
"func (w *Writer) BitsBuffered() uint {\n\treturn 8 - w.free\n}",
"func (pk PacketBufferPtr) Size() int {\n\treturn int(pk.buf.Size()) - pk.headerOffset()\n}",
"func (b *Buffer) LinesNum() int {\n\treturn len(b.lines)\n}",
"func (b *Buffer) Size() (w int, h int) {\n\tvar l int\n\tl = b.Len()\n\tw = b.Width\n\tif w > 0 {\n\t\th = 1 + ((l - 1) / w)\n\t}\n\treturn\n}",
"func (filterdev *NetworkTap) BufLen() (int, error) {\n\tvar buflen int\n\t_, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(filterdev.device.Fd()), syscall.BIOCGBLEN, uintptr(unsafe.Pointer(&buflen)))\n\tif err != 0 {\n\t\treturn 0, syscall.Errno(err)\n\t}\n\treturn buflen, nil\n}",
"func (b *Bound) Width() float64 {\n\treturn b.ne.X() - b.sw.X()\n}",
"func (self *TraitPixbuf) GetBitsPerSample() (return__ int) {\n\tvar __cgo__return__ C.int\n\t__cgo__return__ = C.gdk_pixbuf_get_bits_per_sample(self.CPointer)\n\treturn__ = int(__cgo__return__)\n\treturn\n}",
"func (b *BaseElement) GetWidth() int32 {\n\treturn b.w\n}",
"func (r BenchmarkResult) AllocedBytesPerOp() int64 {}",
"func (w *LDRWrapper) Size() int {\n\treturn w.Bounds().Dx() * w.Bounds().Dy()\n}",
"func GetBufioReader32K(pr io.Reader) *bufio.Reader {\n\tif r := getr32K(); r != nil {\n\t\tr.Reset(pr)\n\t\treturn r\n\t}\n\treturn bufio.NewReaderSize(pr, 32768)\n}",
"func (br *BandwidthMeter) BytesRead() (bytes uint64) {\n bytes = br.bytesRead\n return\n}",
"func LineCount(fileName string) (int, error) {\n\tbuf := make([]byte, 32*1024)\n\tcount := 0\n\tlineSep := []byte{'\\n'}\n\n\tfile, err := os.Open(fileName)\n\tdefer file.Close()\n\tif err != nil {\n\t\treturn count, err\n\t}\n\n\tfor {\n\t\tc, err := file.Read(buf)\n\t\tcount += bytes.Count(buf[:c], lineSep)\n\n\t\tswitch {\n\t\tcase err == io.EOF:\n\t\t\tif count <= 0 {\n\t\t\t\treturn 1, errors.New(\"no newline found\")\n\t\t\t} else {\n\t\t\t\treturn count, nil\n\t\t\t}\n\n\t\tcase err != nil:\n\t\t\treturn count, err\n\t\t}\n\t}\n}",
"func (d *Dataset) Size() int64 {\n\tsize := int64(0)\n\tfor _, block := range d.blocks {\n\t\tsize += block.size\n\t}\n\n\treturn size\n}",
"func CountBufioBytesReadbuf(rd io.Reader) (int, int, error) {\n\t// wrap the reader in a buffer\n\tbr := bufio.NewReader(rd)\n\n\tvar found bool\n\twords := map[string]int{}\n\tcount := 0\n\tword := []rune{}\n\n\tbuf := make([]byte, 1)\n\tfor {\n\t\tr, err := readRuneBuf(br, buf)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn -1, -1, fmt.Errorf(\"error reading: %v\", err)\n\t\t}\n\n\t\tif unicode.IsSpace(r) && found {\n\t\t\tfound = false\n\t\t\tc := words[string(word)]\n\t\t\tc++\n\t\t\twords[string(word)] = c\n\t\t\tword = word[:0]\n\t\t\tcount++\n\t\t}\n\t\tfound = unicode.IsLetter(r)\n\t\tif found {\n\t\t\tword = append(word, r)\n\t\t}\n\t}\n\treturn count, len(words), nil\n}",
"func GetPbufferDCARB(hPbuffer unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpGetPbufferDCARB, 1, uintptr(hPbuffer), 0, 0)\n\treturn (unsafe.Pointer)(ret)\n}",
"func (g I915Backend) ReadFramebufferCount(ctx context.Context, width, height int) (framebuffers int, e error) {\n\tf, err := os.Open(i915FramebufferFile)\n\tif err != nil {\n\t\treturn framebuffers, errors.Wrap(err, \"failed to open dri file\")\n\t}\n\ttext, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn framebuffers, errors.Wrap(err, \"failed to read dri file\")\n\t}\n\tlines := strings.Split(string(text), \"\\n\")\n\tfor _, line := range lines {\n\t\t// The line we're looking for looks like \"user size: 1920 x 1080,...\"\n\t\tvar fbWidth, fbHeight int\n\t\tif _, err := fmt.Sscanf(line, \"user size: %d x %d\", &fbWidth, &fbHeight); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif fbWidth == width && fbHeight == height {\n\t\t\tframebuffers++\n\t\t}\n\t}\n\treturn\n}",
"func (record) RecordCount(b []byte) int {\n\treturn len(b) / recordLength\n}",
"func (b RecordBuffer) NumRecordsInBuffer() int {\n\treturn len(b.recordsInBuffer)\n}",
"func (w *WasiIoVec) GetBufLen() int {\n\treturn int(w.buf_len)\n}",
"func GetRenderbufferWidth(target GLEnum) int32 {\n\tvar params int32\n\tgl.GetRenderbufferParameteriv(uint32(target), gl.RENDERBUFFER_WIDTH, ¶ms)\n\treturn params\n}",
"func (int32DecoderTraits) BytesRequired(n int) int {\n\treturn arrow.Int32Traits.BytesRequired(n)\n}",
"func BpfBuflen(fd int) (int, error) {\n\tvar l int\n\terr := ioctlPtr(fd, BIOCGBLEN, unsafe.Pointer(&l))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn l, nil\n}",
"func (t *Link) GetWidth() (v int64) {\n\treturn *t.width.nonNegativeInteger\n\n}",
"func (t *Pointer) Size() int32 { return 4 }",
"func (b *BoundingBox2D) width() float64 {\n\n\treturn b.upperCorner.X - b.lowerCorner.X\n}",
"func (p *decoded) BytesPerSample() int {\n\treturn 2\n}",
"func (is ImageSurface) Width() int {\n\treturn is.width\n}",
"func (tex *Image) Width() int {\n\tsize := C.sfTexture_getSize(tex.tex)\n\treturn int(size.x)\n}",
"func (s *Screen) LitCount() int {\n\tvar count int\n\tfor _, y := range s.Pixels {\n\t\tfor _, x := range y {\n\t\t\tif x {\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\t}\n\treturn count\n}",
"func dataSize( num_of_items []uint32 ) ( size uint32 ) {\n\tsize = 1\n\n\tfor i := 1; i<len(num_of_items); i++ {\n\t\tsize *= num_of_items[i]\n\t}\n\treturn size\n}",
"func (f *UserPlaneIPResourceInformationFields) MarshalLen() int {\n\tl := 1\n\tif (f.Flags>>2)&0x07 != 0 {\n\t\tl++\n\t}\n\tif has1stBit(f.Flags) {\n\t\tl += 4\n\t}\n\tif has2ndBit(f.Flags) {\n\t\tl += 16\n\t}\n\tif has6thBit(f.Flags) {\n\t\tl += len([]byte(f.NetworkInstance))\n\t}\n\tif has7thBit(f.Flags) {\n\t\tl++\n\t}\n\n\treturn l\n}",
"func numBytesInBitArray(numBits int) int {\n\treturn (numBits + 7) / 8\n}",
"func (s *ImageSpec) PixelBytesChans(chanBegin, chanEnd int, native bool) int {\n\tret := int(C.ImageSpec_pixel_bytes_chans(s.ptr, C.int(chanBegin), C.int(chanEnd), C.bool(native)))\n\truntime.KeepAlive(s)\n\treturn ret\n}"
] | [
"0.6088118",
"0.59626645",
"0.5704243",
"0.5594352",
"0.5502523",
"0.5381243",
"0.5297692",
"0.5105462",
"0.5099829",
"0.5019606",
"0.48991513",
"0.48558936",
"0.48393288",
"0.48221815",
"0.47466347",
"0.47275874",
"0.47216058",
"0.47103858",
"0.46817186",
"0.46253756",
"0.46211195",
"0.4619731",
"0.4616672",
"0.4615288",
"0.46060938",
"0.45927685",
"0.45886016",
"0.45541492",
"0.4512673",
"0.4505411",
"0.45011562",
"0.44919324",
"0.44761756",
"0.4467229",
"0.4462177",
"0.44283617",
"0.44050592",
"0.43997133",
"0.43994862",
"0.4391183",
"0.4389149",
"0.43765476",
"0.43711084",
"0.4369579",
"0.4369579",
"0.4356769",
"0.43519956",
"0.4351194",
"0.4347387",
"0.43444547",
"0.43359926",
"0.43333122",
"0.43257505",
"0.4324932",
"0.4306047",
"0.4294288",
"0.42941043",
"0.42772862",
"0.42713305",
"0.42711785",
"0.42625204",
"0.42608002",
"0.42414504",
"0.424081",
"0.42406505",
"0.42382422",
"0.4238158",
"0.4229529",
"0.42293325",
"0.42265773",
"0.42130184",
"0.4211773",
"0.42114294",
"0.42099196",
"0.4209356",
"0.42093122",
"0.4207199",
"0.42030394",
"0.4196332",
"0.41863155",
"0.418486",
"0.4179497",
"0.4175767",
"0.41756332",
"0.41720685",
"0.41649583",
"0.41540307",
"0.41535285",
"0.41514733",
"0.41450927",
"0.4130194",
"0.41228288",
"0.41223356",
"0.41156334",
"0.41072756",
"0.41055974",
"0.40999115",
"0.40964556",
"0.4094794",
"0.40941733"
] | 0.7062016 | 0 |
FPDFBitmap_Destroy destroys a bitmap and release all related buffers. This function will not destroy any external buffers provided when the bitmap was created. | func (p *PdfiumImplementation) FPDFBitmap_Destroy(request *requests.FPDFBitmap_Destroy) (*responses.FPDFBitmap_Destroy, error) {
p.Lock()
defer p.Unlock()
bitmapHandle, err := p.getBitmapHandle(request.Bitmap)
if err != nil {
return nil, err
}
C.FPDFBitmap_Destroy(bitmapHandle.handle)
delete(p.bitmapRefs, bitmapHandle.nativeRef)
return &responses.FPDFBitmap_Destroy{}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (x *FzBitmap) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzPixmap) Free() {\n\tif x != nil && x.allocs7c1a1ba1 != nil {\n\t\tx.allocs7c1a1ba1.(*cgoAllocMap).Free()\n\t\tx.ref7c1a1ba1 = nil\n\t}\n}",
"func (i *ImageBuf) Destroy() {\n\truntime.SetFinalizer(i, nil)\n\tdeleteImageBuf(i)\n}",
"func (x *FzPixmapImage) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzImage) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (tex *Image) Free() {\n\tC.sfSprite_destroy(tex.sprite)\n\tC.sfTexture_destroy(tex.tex)\n}",
"func (bm Bitmap) Free(off uint64) {\n\tblockIndex := off / ItemsPerBitmap\n\tbyteIndex := (off / 8) % 4096\n\tbitIndex := off % 8\n\tbm[blockIndex][byteIndex] = bm[blockIndex][byteIndex] & ^(1 << bitIndex)\n}",
"func (x *PDFCmap) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzBuffer) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFPattern) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (f *FileBlob) Free() {\n\tf.blob = nil\n}",
"func (x *FzCompressedImage) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFGraftMap) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (b *Buffer) Destroy() {\n\tfor _, buf := range b.bufs {\n\t\tb.pool.release(buf)\n\t}\n\tb.bufs = nil\n}",
"func (x *FzColorParams) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (enc *Encoder) FreeMemory() {\n\tfor i := 0; i < len(enc.pointerSlice); i++ {\n\t\tC.free(enc.pointerSlice[i])\n\t}\n}",
"func (x *FzColorConverter) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzGlyphCache) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzBandWriter) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFRevPageMap) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzCmmInstance) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (jbobject *UnsafeMemoryMemoryAllocator) Free(a UnsafeMemoryMemoryBlockInterface) {\n\tconv_a := javabind.NewGoToJavaCallable()\n\tif err := conv_a.Convert(a); err != nil {\n\t\tpanic(err)\n\t}\n\t_, err := jbobject.CallMethod(javabind.GetEnv(), \"free\", javabind.Void, conv_a.Value().Cast(\"org/apache/spark/unsafe/memory/MemoryBlock\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tconv_a.CleanUp()\n\n}",
"func (x *FzRect) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzCompressedBuffer) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzCompressionParams) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzFontContext) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFFontDesc) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzFont) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzColorspace) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFProcessor) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzColorspaceContext) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzFontFlags) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFOcgDescriptor) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFLayerConfig) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzDrawOptions) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (pw *PixelWand) Destroy() {\n\tif pw.pw == nil {\n\t\treturn\n\t}\n\n\tpw.init.Do(func() {\n\t\tpw.pw = C.DestroyPixelWand(pw.pw)\n\t\trelinquishMemory(unsafe.Pointer(pw.pw))\n\t\truntime.SetFinalizer(pw, nil)\n\t\tpw.pw = nil\n\n\t\tpw.DecreaseCount()\n\t})\n}",
"func (pi *PixelIterator) Destroy() {\n\tif pi.pi == nil {\n\t\treturn\n\t}\n\n\tpi.init.Do(func() {\n\t\tpi.pi = C.DestroyPixelIterator(pi.pi)\n\t\trelinquishMemory(unsafe.Pointer(pi.pi))\n\t\truntime.SetFinalizer(pi, nil)\n\t\tpi.pi = nil\n\n\t\tpi.DecreaseCount()\n\t})\n}",
"func (x *FzScaleCache) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (ctx *Context) Free() {\n\tC.avfilter_free((*C.struct_AVFilterContext)(ctx))\n}",
"func (x *PDFHmtx) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzShaperData) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzOutputContext) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFLexbufLarge) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFWidget) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzGlyph) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFDaInfo) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func ReleaseByteBuffer(bb *ByteBuffer) {\n\tbb.Reset()\n\tbyteBufferPool.Put(bb)\n}",
"func (x *FzAnnot) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func DestroyPbufferARB(hPbuffer unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpDestroyPbufferARB, 1, uintptr(hPbuffer), 0, 0)\n\treturn (unsafe.Pointer)(ret)\n}",
"func (x *FzCmmEngine) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzMatrix) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFCrypt) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFAnnot) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzStream) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFHotspot) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (z *Writer) freeBuffers() {\n\t// Put the buffer back into the pool, if any.\n\tputBuffer(z.Header.BlockMaxSize, z.data)\n\tz.data = nil\n}",
"func (x *ImVec2) Free() {\n\tif x != nil && x.allocs74e98a33 != nil {\n\t\tx.allocs74e98a33.(*cgoAllocMap).Free()\n\t\tx.ref74e98a33 = nil\n\t}\n}",
"func (x *FzOutput) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFLexbuf) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzCalColorspace) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzStyleContext) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func FreeMem() {\n\tdebug.FreeOSMemory()\n}",
"func (grabber *Grabber) Dispose() {\n\tDeleteDC(grabber.memDC)\n\tDeleteObject(HGDIOBJ(grabber.bmp))\n\tReleaseDC(0, grabber.winDC)\n}",
"func (p *PdfiumImplementation) FPDFBitmap_Create(request *requests.FPDFBitmap_Create) (*responses.FPDFBitmap_Create, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tbitmap := C.FPDFBitmap_Create(C.int(request.Width), C.int(request.Height), C.int(request.Alpha))\n\tbitmapHandle := p.registerBitmap(bitmap)\n\n\treturn &responses.FPDFBitmap_Create{\n\t\tBitmap: bitmapHandle.nativeRef,\n\t}, nil\n}",
"func (x *FzDevice) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFObj) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzZipWriter) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzPage) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzShade) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzDeviceContainerStack) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzContext) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzIrect) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFXobject) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFVmtx) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFWriteOptions) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func freeBuffer(buf *bytes.Buffer) {\n\tbuf.Reset()\n\tbufferPool.Put(buf)\n}",
"func (x *FzXml) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzIcclink) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFPage) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzSha512) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzAllocContext) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func Free() error {\n\treturn boolToError(C.BASS_Free())\n}",
"func (app *DockApp) Destroy() {\n\tapp.img.Destroy()\n\tapp.win.Destroy()\n}",
"func (x *FzLink) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (b *BufferManager) FreeBuffer(peer *PeerSession) {\n\tpeer.buffers = nil\n\tb.freeIndex.Enqueue(peer.bufferOffst)\n}",
"func (dw *DrawingWand) Destroy() {\n\tif dw.dw == nil {\n\t\treturn\n\t}\n\n\tdw.init.Do(func() {\n\t\tC.DestroyDrawingWand(dw.dw)\n\t\tdw.dw = nil\n\t\tdw.DecreaseCount()\n\t})\n}",
"func (device *Device) Destroy() {\n\n\tC.freenect_close_device(device.device)\n}",
"func (x *FzDisplayList) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzLocksContext) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (f *Frame) Free() {\n\tif f.cPtrAVFrame != nil {\n\t\tC.av_frame_free(&f.cPtrAVFrame)\n\t}\n}",
"func (x *FzDefaultColorspaces) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *PDFDocument) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzIdContext) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzDocument) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzText) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (decoder *Decoder) Destroy() {\n\tC.NvPipe_Destroy(decoder.dec)\n\tdecoder = nil\n}",
"func (x *FzArchive) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (x *FzPoint) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}",
"func (b *GoGLBackendOffscreen) Delete() {\n\tgl.DeleteTextures(1, &b.offscrBuf.tex)\n\tgl.DeleteFramebuffers(1, &b.offscrBuf.frameBuf)\n\tgl.DeleteRenderbuffers(1, &b.offscrBuf.renderStencilBuf)\n}",
"func PktMbufFree(m *Mbuf) {\n\tC.rte_pktmbuf_free(mbuf(m))\n}"
] | [
"0.67980623",
"0.6542155",
"0.63555765",
"0.6270414",
"0.6094892",
"0.58055216",
"0.5733272",
"0.5728931",
"0.564955",
"0.5646917",
"0.56409085",
"0.5639362",
"0.5598265",
"0.55946285",
"0.5586792",
"0.5534845",
"0.5513404",
"0.54599005",
"0.5458431",
"0.54170954",
"0.54149467",
"0.54038125",
"0.5393844",
"0.5364574",
"0.53640485",
"0.53627044",
"0.5360147",
"0.53467554",
"0.5341274",
"0.53394544",
"0.53259355",
"0.5317891",
"0.53145915",
"0.5299469",
"0.52959085",
"0.5289562",
"0.5278953",
"0.52643454",
"0.52514803",
"0.52492166",
"0.5234061",
"0.5233401",
"0.5233115",
"0.52316827",
"0.5225193",
"0.52235144",
"0.522232",
"0.52100897",
"0.52050775",
"0.520273",
"0.51922435",
"0.5191973",
"0.51901984",
"0.5185818",
"0.51807964",
"0.51780367",
"0.5161775",
"0.51573354",
"0.5154967",
"0.51505446",
"0.51465744",
"0.51436985",
"0.5134752",
"0.51204205",
"0.51179355",
"0.51177627",
"0.51155275",
"0.510749",
"0.5103119",
"0.50883824",
"0.5087344",
"0.50855476",
"0.5064776",
"0.5057556",
"0.5049211",
"0.50459677",
"0.50279224",
"0.50224066",
"0.5019268",
"0.5010999",
"0.500052",
"0.49999905",
"0.49980438",
"0.49948663",
"0.4993434",
"0.49864882",
"0.4981683",
"0.49778193",
"0.49710438",
"0.49648982",
"0.49624363",
"0.4961731",
"0.49598986",
"0.49578726",
"0.4956261",
"0.4954245",
"0.49500707",
"0.49460948",
"0.49451837",
"0.49347216"
] | 0.77414143 | 0 |
FPDF_VIEWERREF_GetPrintScaling returns whether the PDF document prefers to be scaled or not. | func (p *PdfiumImplementation) FPDF_VIEWERREF_GetPrintScaling(request *requests.FPDF_VIEWERREF_GetPrintScaling) (*responses.FPDF_VIEWERREF_GetPrintScaling, error) {
p.Lock()
defer p.Unlock()
documentHandle, err := p.getDocumentHandle(request.Document)
if err != nil {
return nil, err
}
printScaling := C.FPDF_VIEWERREF_GetPrintScaling(documentHandle.handle)
return &responses.FPDF_VIEWERREF_GetPrintScaling{
PreferPrintScaling: int(printScaling) == 1,
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (m *PrinterDefaults) GetScaling()(*PrintScaling) {\n val, err := m.GetBackingStore().Get(\"scaling\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*PrintScaling)\n }\n return nil\n}",
"func (m *PrinterDefaults) GetFitPdfToPage()(*bool) {\n val, err := m.GetBackingStore().Get(\"fitPdfToPage\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}",
"func (this *Transformable) GetScale() (scale Vector2f) {\n\tscale.fromC(C.sfTransformable_getScale(this.cptr))\n\treturn\n}",
"func (m *PrinterDefaults) SetScaling(value *PrintScaling)() {\n err := m.GetBackingStore().Set(\"scaling\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m Matrix3) IsScale() bool {\n\treturn m[0][1] == 0 && m[1][0] == 0 && m.IsAffine()\n}",
"func (r Virtual_Guest) GetScaledFlag() (resp bool, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getScaledFlag\", nil, &r.Options, &resp)\n\treturn\n}",
"func (m *PrinterDefaults) GetQuality()(*PrintQuality) {\n val, err := m.GetBackingStore().Get(\"quality\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*PrintQuality)\n }\n return nil\n}",
"func (o AiFeatureStoreOnlineServingConfigPtrOutput) Scaling() AiFeatureStoreOnlineServingConfigScalingPtrOutput {\n\treturn o.ApplyT(func(v *AiFeatureStoreOnlineServingConfig) *AiFeatureStoreOnlineServingConfigScaling {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Scaling\n\t}).(AiFeatureStoreOnlineServingConfigScalingPtrOutput)\n}",
"func (this *RectangleShape) GetScale() (scale Vector2f) {\n\tscale.fromC(C.sfRectangleShape_getScale(this.cptr))\n\treturn\n}",
"func (f *Font) GetCurrentScale() float32 {\n\t_, uiHeight := f.Owner.GetResolution()\n\tdesignHeight := f.Owner.GetDesignHeight()\n\treturn float32(uiHeight) / float32(designHeight)\n}",
"func (o AiFeatureStoreOnlineServingConfigOutput) Scaling() AiFeatureStoreOnlineServingConfigScalingPtrOutput {\n\treturn o.ApplyT(func(v AiFeatureStoreOnlineServingConfig) *AiFeatureStoreOnlineServingConfigScaling { return v.Scaling }).(AiFeatureStoreOnlineServingConfigScalingPtrOutput)\n}",
"func (t *TextureTranform) ScaleOrDefault() [2]float32 {\n\tif t.Scale == emptyScale {\n\t\treturn DefaultScale\n\t}\n\treturn t.Scale\n}",
"func (o LookupServicePlanResultOutput) PerSiteScalingEnabled() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v LookupServicePlanResult) bool { return v.PerSiteScalingEnabled }).(pulumi.BoolOutput)\n}",
"func (t *Transform) GetScale() *Vector {\n\treturn t.Scale\n}",
"func (w *GlfwWindow) GetScale() (x float64, y float64) {\n\n\treturn w.scaleX, w.scaleY\n}",
"func (me TxsdAnimateTransformTypeType) IsScale() bool { return me.String() == \"scale\" }",
"func (me TxsdPresentationAttributesFontSpecificationFontStretch) IsNarrower() bool {\n\treturn me.String() == \"narrower\"\n}",
"func (s *font) GetScaleFactor() (scaleFactor float64) {\n\treturn s.scaleFactor\n}",
"func (m *PrinterDefaults) GetDpi()(*int32) {\n val, err := m.GetBackingStore().Get(\"dpi\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}",
"func (me TAttlistArticlePubModel) IsPrint() bool { return me.String() == \"Print\" }",
"func (xs *Sheet) GetPrintFit() (wPages int, hPages int) {\n\txs.xb.lib.NewProc(\"xlSheetGetPrintFitW\").\n\t\tCall(xs.self, I_P(&wPages), I_P(&hPages))\n\treturn wPages, hPages\n}",
"func (me TxsdPresentationAttributesFontSpecificationFontStretch) IsWider() bool {\n\treturn me.String() == \"wider\"\n}",
"func (me XsdGoPkgHasElem_Scale) ScaleDefault() xsdt.Double {\r\n\tvar x = new(xsdt.Double)\r\n\tx.Set(\"1.0\")\r\n\treturn *x\r\n}",
"func (me TxsdPresentationAttributesGraphicsTextRendering) IsGeometricPrecision() bool {\n\treturn me.String() == \"geometricPrecision\"\n}",
"func (self Text) GetScale() (x, y float32) {\n\tv := C.sfText_getScale(self.Cref)\n\treturn float32(v.x), float32(v.y)\n}",
"func (me TxsdPresentationAttributesFontSpecificationFontStretch) IsNormal() bool {\n\treturn me.String() == \"normal\"\n}",
"func (o ElastigroupScalingTargetPolicyOutput) MaxCapacityPerScale() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingTargetPolicy) *string { return v.MaxCapacityPerScale }).(pulumi.StringPtrOutput)\n}",
"func (wm Watermark) isPDF() bool {\n\treturn wm.Mode == WMPDF\n}",
"func (me TxsdPresentationAttributesGraphicsShapeRendering) IsGeometricPrecision() bool {\n\treturn me.String() == \"geometricPrecision\"\n}",
"func (me XsdGoPkgHasElems_Scale) ScaleDefault() xsdt.Double {\r\n\tvar x = new(xsdt.Double)\r\n\tx.Set(\"1.0\")\r\n\treturn *x\r\n}",
"func (o *PostWebhook) GetPrRescoped() bool {\n\tif o == nil || o.PrRescoped == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\treturn *o.PrRescoped\n}",
"func (o *AudioStreamPlayer) GetPitchScale() gdnative.Real {\n\t//log.Println(\"Calling AudioStreamPlayer.GetPitchScale()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"AudioStreamPlayer\", \"get_pitch_scale\")\n\n\t// Call the parent method.\n\t// float\n\tretPtr := gdnative.NewEmptyReal()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewRealFromPointer(retPtr)\n\treturn ret\n}",
"func (me TxsdPresentationAttributesColorColorRendering) IsOptimizeQuality() bool {\n\treturn me.String() == \"optimizeQuality\"\n}",
"func (r *ScaledObjectReconciler) checkTargetResourceIsScalable(logger logr.Logger, scaledObject *kedav1alpha1.ScaledObject) (kedav1alpha1.GroupVersionKindResource, error) {\n\tgvkr, err := kedautil.ParseGVKR(r.restMapper, scaledObject.Spec.ScaleTargetRef.APIVersion, scaledObject.Spec.ScaleTargetRef.Kind)\n\tif err != nil {\n\t\tlogger.Error(err, \"Failed to parse Group, Version, Kind, Resource\", \"apiVersion\", scaledObject.Spec.ScaleTargetRef.APIVersion, \"kind\", scaledObject.Spec.ScaleTargetRef.Kind)\n\t\treturn gvkr, err\n\t}\n\tgvkString := gvkr.GVKString()\n\tlogger.V(1).Info(\"Parsed Group, Version, Kind, Resource\", \"GVK\", gvkString, \"Resource\", gvkr.Resource)\n\n\t// let's try to detect /scale subresource\n\tscale, errScale := (*r.scaleClient).Scales(scaledObject.Namespace).Get(context.TODO(), gvkr.GroupResource(), scaledObject.Spec.ScaleTargetRef.Name, metav1.GetOptions{})\n\tif errScale != nil {\n\t\t// not able to get /scale subresource -> let's check if the resource even exist in the cluster\n\t\tunstruct := &unstructured.Unstructured{}\n\t\tunstruct.SetGroupVersionKind(gvkr.GroupVersionKind())\n\t\tif err := r.Client.Get(context.TODO(), client.ObjectKey{Namespace: scaledObject.Namespace, Name: scaledObject.Spec.ScaleTargetRef.Name}, unstruct); err != nil {\n\t\t\t// resource doesn't exist\n\t\t\tlogger.Error(err, \"Target resource doesn't exist\", \"resource\", gvkString, \"name\", scaledObject.Spec.ScaleTargetRef.Name)\n\t\t\treturn gvkr, err\n\t\t}\n\t\t// resource exist but doesn't expose /scale subresource\n\t\tlogger.Error(errScale, \"Target resource doesn't expose /scale subresource\", \"resource\", gvkString, \"name\", scaledObject.Spec.ScaleTargetRef.Name)\n\t\treturn gvkr, errScale\n\t}\n\n\t// if it is not already present in ScaledObject Status:\n\t// - store discovered GVK and GVKR\n\t// - store original scaleTarget's replica count (before scaling with KEDA)\n\tif scaledObject.Status.ScaleTargetKind != gvkString || scaledObject.Status.OriginalReplicaCount == nil {\n\t\tstatus := scaledObject.Status.DeepCopy()\n\t\tif scaledObject.Status.ScaleTargetKind != gvkString {\n\t\t\tstatus.ScaleTargetKind = gvkString\n\t\t\tstatus.ScaleTargetGVKR = &gvkr\n\t\t}\n\t\tif scaledObject.Status.OriginalReplicaCount == nil {\n\t\t\tstatus.OriginalReplicaCount = &scale.Spec.Replicas\n\t\t}\n\n\t\tif err := kedacontrollerutil.UpdateScaledObjectStatus(r.Client, logger, scaledObject, status); err != nil {\n\t\t\treturn gvkr, err\n\t\t}\n\t\tlogger.Info(\"Detected resource targeted for scaling\", \"resource\", gvkString, \"name\", scaledObject.Spec.ScaleTargetRef.Name)\n\t}\n\n\treturn gvkr, nil\n}",
"func (tt *telloTrackT) deriveScale() (scale float32) {\n\tscale = 1.0 // minimum scale value\n\tif tt.maxX > scale {\n\t\tscale = tt.maxX\n\t}\n\tif -tt.minX > scale {\n\t\tscale = -tt.minX\n\t}\n\tif tt.maxY > scale {\n\t\tscale = tt.maxY\n\t}\n\tif -tt.minY > scale {\n\t\tscale = -tt.minY\n\t}\n\tscale = float32(math.Ceil(float64(scale)))\n\treturn scale\n}",
"func (o *DynamicFont) GetUseMipmaps() gdnative.Bool {\n\t//log.Println(\"Calling DynamicFont.GetUseMipmaps()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"DynamicFont\", \"get_use_mipmaps\")\n\n\t// Call the parent method.\n\t// bool\n\tretPtr := gdnative.NewEmptyBool()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewBoolFromPointer(retPtr)\n\treturn ret\n}",
"func (me TxsdViewTypeZoomAndPan) IsMagnify() bool { return me.String() == \"magnify\" }",
"func (p *PdfiumImplementation) FPDF_VIEWERREF_GetPrintPageRange(request *requests.FPDF_VIEWERREF_GetPrintPageRange) (*responses.FPDF_VIEWERREF_GetPrintPageRange, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpageRange := C.FPDF_VIEWERREF_GetPrintPageRange(documentHandle.handle)\n\tpageRangeHandle := p.registerPageRange(pageRange, documentHandle)\n\n\treturn &responses.FPDF_VIEWERREF_GetPrintPageRange{\n\t\tPageRange: pageRangeHandle.nativeRef,\n\t}, nil\n}",
"func (s *CreateUserSettingsInput) SetPrintAllowed(v string) *CreateUserSettingsInput {\n\ts.PrintAllowed = &v\n\treturn s\n}",
"func (chords Chords) EligibleScales() Scales {\n\tnotes := chords.Uniques().SortedOnRoots().RootNotes()\n\treturn EligibleScalesForNotes(notes)\n}",
"func (pas *PodAutoscalerStatus) GetDesiredScale() int32 {\n\tif pas.DesiredScale != nil {\n\t\treturn *pas.DesiredScale\n\t}\n\treturn -1\n}",
"func (c Capabilities) HasPrinterSupport(gvk schema.GroupVersionKind) bool {\n\treturn includesGVK(gvk, c.SupportsPrinterConfig) ||\n\t\tincludesGVK(gvk, c.SupportsPrinterStatus) ||\n\t\tincludesGVK(gvk, c.SupportsPrinterItems)\n}",
"func (s *UpdateUserSettingsInput) SetPrintAllowed(v string) *UpdateUserSettingsInput {\n\ts.PrintAllowed = &v\n\treturn s\n}",
"func (pa *PodAutoscaler) ActivationScale() (int32, bool) {\n\treturn pa.annotationInt32(autoscaling.ActivationScale)\n}",
"func (o OceanLaunchSpecOutput) RestrictScaleDown() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v *OceanLaunchSpec) pulumi.BoolOutput { return v.RestrictScaleDown }).(pulumi.BoolOutput)\n}",
"func (me TxsdTextPathTypeMethod) IsStretch() bool { return me.String() == \"stretch\" }",
"func (s *UserSettings) SetPrintAllowed(v string) *UserSettings {\n\ts.PrintAllowed = &v\n\treturn s\n}",
"func (o HorizontalPodAutoscalerSpecOutput) ScaleTargetRef() CrossVersionObjectReferenceOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerSpec) CrossVersionObjectReference { return v.ScaleTargetRef }).(CrossVersionObjectReferenceOutput)\n}",
"func (o HorizontalPodAutoscalerSpecOutput) ScaleTargetRef() CrossVersionObjectReferenceOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerSpec) CrossVersionObjectReference { return v.ScaleTargetRef }).(CrossVersionObjectReferenceOutput)\n}",
"func (s *UserSettingsSummary) SetPrintAllowed(v string) *UserSettingsSummary {\n\ts.PrintAllowed = &v\n\treturn s\n}",
"func (pas *PodAutoscalerStatus) GetActualScale() int32 {\n\tif pas.ActualScale != nil {\n\t\treturn *pas.ActualScale\n\t}\n\treturn -1\n}",
"func (pa *PodAutoscaler) ScaleBounds(asConfig *autoscalerconfig.Config) (int32, int32) {\n\tvar min int32\n\tif pa.Spec.Reachability != ReachabilityUnreachable {\n\t\tmin = asConfig.MinScale\n\t\tif paMin, ok := pa.annotationInt32(autoscaling.MinScaleAnnotation); ok {\n\t\t\tmin = paMin\n\t\t}\n\t}\n\n\tmax := asConfig.MaxScale\n\tif paMax, ok := pa.annotationInt32(autoscaling.MaxScaleAnnotation); ok {\n\t\tmax = paMax\n\t}\n\n\treturn min, max\n}",
"func (o *FitToPage) getSheetPrOption(pr *xlsxSheetPr) {\n\t// Excel default: false\n\tif pr == nil || pr.PageSetUpPr == nil {\n\t\t*o = false\n\t\treturn\n\t}\n\t*o = FitToPage(pr.PageSetUpPr.FitToPage)\n}",
"func (o *DynamicFont) GetUseFilter() gdnative.Bool {\n\t//log.Println(\"Calling DynamicFont.GetUseFilter()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"DynamicFont\", \"get_use_filter\")\n\n\t// Call the parent method.\n\t// bool\n\tretPtr := gdnative.NewEmptyBool()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewBoolFromPointer(retPtr)\n\treturn ret\n}",
"func (w *windowImpl) Scale(dr image.Rectangle, src screen.Texture, sr image.Rectangle, op draw.Op, opts *screen.DrawOptions) {\n\tpanic(\"not implemented\") // TODO: Implement\n}",
"func (filter *Saturation) IsScalable() {\n}",
"func (self *Graphics) FixedToCamera() bool{\n return self.Object.Get(\"fixedToCamera\").Bool()\n}",
"func (o ArgoCDSpecServerAutoscaleHpaPtrOutput) ScaleTargetRef() ArgoCDSpecServerAutoscaleHpaScaleTargetRefPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDSpecServerAutoscaleHpa) *ArgoCDSpecServerAutoscaleHpaScaleTargetRef {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.ScaleTargetRef\n\t}).(ArgoCDSpecServerAutoscaleHpaScaleTargetRefPtrOutput)\n}",
"func (me TxsdViewTypeZoomAndPan) IsZoom() bool { return me.String() == \"zoom\" }",
"func (o ScalingConfigOutput) ScalingFactor() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v ScalingConfig) *float64 { return v.ScalingFactor }).(pulumi.Float64PtrOutput)\n}",
"func (m *PrinterDefaults) SetFitPdfToPage(value *bool)() {\n err := m.GetBackingStore().Set(\"fitPdfToPage\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (o ArgoCDSpecServerAutoscaleHpaOutput) ScaleTargetRef() ArgoCDSpecServerAutoscaleHpaScaleTargetRefOutput {\n\treturn o.ApplyT(func(v ArgoCDSpecServerAutoscaleHpa) ArgoCDSpecServerAutoscaleHpaScaleTargetRef {\n\t\treturn v.ScaleTargetRef\n\t}).(ArgoCDSpecServerAutoscaleHpaScaleTargetRefOutput)\n}",
"func (a *PhonebookAccess1) GetFixedImageSize() (bool, error) {\n\tv, err := a.GetProperty(\"FixedImageSize\")\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn v.Value().(bool), nil\n}",
"func (dl *DiffuseLight) ScatteringPDF(r ray.Ray, hr *hitrecord.HitRecord, scattered ray.Ray) float64 {\n\treturn 0\n}",
"func scaling() gs.CSSRule {\n\treturn gs.S(\"code\",\n\t\tgs.S(\"&,kbd\",\n\t\t\tgs.S(\"&,samp\",\n\t\t\t\tgs.P(\"font-family\", \"monospace, monospace;\"),\n\t\t\t\tgs.P(\"font-size\", \"1em\"),\n\t\t\t),\n\t\t),\n\t)\n}",
"func (o *AutoscalerResourceLimitsGPULimit) GetRange() (value *ResourceRange, ok bool) {\n\tok = o != nil && o.bitmap_&1 != 0\n\tif ok {\n\t\tvalue = o.range_\n\t}\n\treturn\n}",
"func (o ScalingConfigResponseOutput) ScalingFactor() pulumi.Float64Output {\n\treturn o.ApplyT(func(v ScalingConfigResponse) float64 { return v.ScalingFactor }).(pulumi.Float64Output)\n}",
"func (f *Face) FixedWidth() bool {\n\treturn f.handle.face_flags&C.FT_FACE_FLAG_FIXED_WIDTH != 0\n}",
"func (b *Base) Scale(w http.ResponseWriter, r *http.Request) {\n\tb.log.Printf(\"%s %s -> %s\", r.Method, r.URL.Path, r.RemoteAddr)\n\n\tsOptions, pOptions, kOptions, oOptions := render.SetDefaultScaleOptions()\n\n\tpv := render.PageVars{\n\t\tTitle: \"Practice Scales and Arpeggios\", // default scale initially displayed is A Major\n\t\tScalearp: \"Scale\",\n\t\tPitch: \"Major\",\n\t\tKey: \"A\",\n\t\tScaleImgPath: \"img/scale/major/a1.png\",\n\t\tGifPath: \"\",\n\t\tAudioPath: \"mp3/scale/major/a1.mp3\",\n\t\tAudioPath2: \"mp3/drone/a1.mp3\",\n\t\tLeftLabel: \"Listen to Major scale\",\n\t\tRightLabel: \"Listen to Drone\",\n\t\tScaleOptions: sOptions,\n\t\tPitchOptions: pOptions,\n\t\tKeyOptions: kOptions,\n\t\tOctaveOptions: oOptions,\n\t}\n\n\tif err := render.Render(w, \"scale.html\", pv); err != nil {\n\t\tb.log.Printf(\"%s %s -> %s : ERROR : %v\", r.Method, r.URL.Path, r.RemoteAddr, err)\n\t\treturn\n\t}\n}",
"func (ct *Ciphertext) ScalingFactor() float64 {\n\treturn ct.Scale\n}",
"func (f *Font) Bounds(scale int32) Bounds {\n\tb := f.bounds\n\tb.XMin = f.scale(scale * b.XMin)\n\tb.YMin = f.scale(scale * b.YMin)\n\tb.XMax = f.scale(scale * b.XMax)\n\tb.YMax = f.scale(scale * b.YMax)\n\treturn b\n}",
"func (ac *Activity) Resizable(ctx context.Context) (bool, error) {\n\ttask, err := ac.getTaskInfo(ctx)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"could not get task info\")\n\t}\n\treturn task.resizable, nil\n}",
"func (me TAttlistJournalIssueCitedMedium) IsPrint() bool { return me.String() == \"Print\" }",
"func (self *ComponentScaleMinMax) ScaleMax() *Point{\n return &Point{self.Object.Get(\"scaleMax\")}\n}",
"func (dw *DrawingWand) GetFontStretch() StretchType {\n\treturn StretchType(C.MagickDrawGetFontStretch(dw.dw))\n}",
"func (a *ReplaySnapshotArgs) SetScale(scale float64) *ReplaySnapshotArgs {\n\ta.Scale = &scale\n\treturn a\n}",
"func (o *Published) getSheetPrOption(pr *xlsxSheetPr) {\n\tif pr == nil {\n\t\t*o = true\n\t\treturn\n\t}\n\t*o = Published(defaultTrue(pr.Published))\n}",
"func (f *JSONYamlPrintFlags) ToPrinter(outputFormat string) (printers.ResourcePrinter, error) {\n\tvar printer printers.ResourcePrinter\n\n\toutputFormat = strings.ToLower(outputFormat)\n\tswitch outputFormat {\n\tcase \"json\":\n\t\tprinter = &printers.JSONPrinter{}\n\tcase \"yaml\":\n\t\tprinter = &printers.YAMLPrinter{}\n\tdefault:\n\t\treturn nil, NoCompatiblePrinterError{OutputFormat: &outputFormat, AllowedFormats: f.AllowedFormats()}\n\t}\n\n\tif !f.ShowManagedFields {\n\t\tprinter = &printers.OmitManagedFieldsPrinter{Delegate: printer}\n\t}\n\treturn printer, nil\n}",
"func (o AutoscalingPolicyScaleInControlOutput) MaxScaledInReplicas() FixedOrPercentPtrOutput {\n\treturn o.ApplyT(func(v AutoscalingPolicyScaleInControl) *FixedOrPercent { return v.MaxScaledInReplicas }).(FixedOrPercentPtrOutput)\n}",
"func (me TxsdPresentationAttributesFontSpecificationFontVariant) IsNormal() bool {\n\treturn me.String() == \"normal\"\n}",
"func (r *ScaledObjectReconciler) scaledObjectGenerationChanged(logger logr.Logger, scaledObject *kedav1alpha1.ScaledObject) (bool, error) {\n\tkey, err := cache.MetaNamespaceKeyFunc(scaledObject)\n\tif err != nil {\n\t\tlogger.Error(err, \"Error getting key for scaledObject\")\n\t\treturn true, err\n\t}\n\n\tvalue, loaded := r.scaledObjectsGenerations.Load(key)\n\tif loaded {\n\t\tgeneration := value.(int64)\n\t\tif generation == scaledObject.Generation {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn true, nil\n}",
"func (c *jsiiProxy_CfnElasticLoadBalancerAttachment) ShouldSynthesize() *bool {\n\tvar returns *bool\n\n\t_jsii_.Invoke(\n\t\tc,\n\t\t\"shouldSynthesize\",\n\t\tnil, // no parameters\n\t\t&returns,\n\t)\n\n\treturn returns\n}",
"func (me TxsdPresentationAttributesFontSpecificationFontWeight) Is100() bool {\n\treturn me.String() == \"100\"\n}",
"func IsPrintQR(ctx context.Context) bool {\n\tbv, ok := ctx.Value(ctxKeyPrintQR).(bool)\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn bv\n}",
"func (o BackendOutput) CapacityScaler() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v Backend) *float64 { return v.CapacityScaler }).(pulumi.Float64PtrOutput)\n}",
"func (s *scaleDecider) needScale() bool {\n\tlastUpdated := s.lastProviderUpdated\n\tif lastUpdated.Before(s.lastSchedulerUpdated) {\n\t\tlastUpdated = s.lastSchedulerUpdated\n\t}\n\n\tnow := time.Now()\n\tif now.After(s.lastProvision.Add(minRetryInterval)) ||\n\t\ts.lastProvision.Before(lastUpdated.Add(s.maxStartingPeriod)) ||\n\t\ts.lastProvision.Before(lastUpdated.Add(s.maxIdlePeriod)) ||\n\t\ts.lastProvision.Before(lastUpdated.Add(s.maxDisconnectPeriod)) {\n\t\ts.lastProvision = now\n\t\treturn true\n\t}\n\treturn false\n}",
"func (me TxsdPresentationAttributesFontSpecificationFontStretch) IsCondensed() bool {\n\treturn me.String() == \"condensed\"\n}",
"func (t *Transform) Scale() lmath.Vec3 {\n\tt.access.RLock()\n\ts := t.scale\n\tt.access.RUnlock()\n\treturn s\n}",
"func (o IopingSpecVolumeVolumeSourceScaleIOPtrOutput) ReadOnly() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSourceScaleIO) *bool {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ReadOnly\n\t}).(pulumi.BoolPtrOutput)\n}",
"func (me TxsdPresentationAttributesFontSpecificationFontWeight) IsNormal() bool {\n\treturn me.String() == \"normal\"\n}",
"func (me TxsdPresentationAttributesGraphicsDisplay) IsInherit() bool { return me.String() == \"inherit\" }",
"func (r *Policy) ScalableDimension() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"scalableDimension\"])\n}",
"func IsHighDPIEnabled() bool {\n\treturn highDPI\n}",
"func (f *FieldSet) TypePrecisionScale(idx int) (int64, int64, bool) {\n\treturn f.fields[idx].typePrecisionScale()\n}",
"func (o HorizontalPodAutoscalerSpecPatchOutput) ScaleTargetRef() CrossVersionObjectReferencePatchPtrOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerSpecPatch) *CrossVersionObjectReferencePatch { return v.ScaleTargetRef }).(CrossVersionObjectReferencePatchPtrOutput)\n}",
"func (o HorizontalPodAutoscalerSpecPatchOutput) ScaleTargetRef() CrossVersionObjectReferencePatchPtrOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerSpecPatch) *CrossVersionObjectReferencePatch { return v.ScaleTargetRef }).(CrossVersionObjectReferencePatchPtrOutput)\n}",
"func (o IopingSpecVolumeVolumeSourceScaleIOOutput) ReadOnly() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceScaleIO) *bool { return v.ReadOnly }).(pulumi.BoolPtrOutput)\n}",
"func (me TxsdPresentationAttributesGraphicsTextRendering) IsOptimizeLegibility() bool {\n\treturn me.String() == \"optimizeLegibility\"\n}",
"func (o BackendResponseOutput) CapacityScaler() pulumi.Float64Output {\n\treturn o.ApplyT(func(v BackendResponse) float64 { return v.CapacityScaler }).(pulumi.Float64Output)\n}",
"func (o HorizontalPodAutoscalerSpecPatchPtrOutput) ScaleTargetRef() CrossVersionObjectReferencePatchPtrOutput {\n\treturn o.ApplyT(func(v *HorizontalPodAutoscalerSpecPatch) *CrossVersionObjectReferencePatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ScaleTargetRef\n\t}).(CrossVersionObjectReferencePatchPtrOutput)\n}"
] | [
"0.5937887",
"0.53119326",
"0.49370494",
"0.48624572",
"0.4850825",
"0.47848567",
"0.47563654",
"0.47103876",
"0.4699239",
"0.46504104",
"0.4641048",
"0.45929652",
"0.45642596",
"0.45539945",
"0.45089963",
"0.44986412",
"0.44425946",
"0.44190153",
"0.43677485",
"0.43300453",
"0.4299438",
"0.42911023",
"0.42814654",
"0.42773712",
"0.42673156",
"0.42315587",
"0.4228139",
"0.4203926",
"0.4201337",
"0.41983694",
"0.41934693",
"0.41546512",
"0.4120308",
"0.4117802",
"0.40998328",
"0.40927142",
"0.40814564",
"0.40747774",
"0.4006368",
"0.40054485",
"0.3995094",
"0.39849228",
"0.39823425",
"0.39773822",
"0.39732313",
"0.3964456",
"0.39628637",
"0.39624646",
"0.39624646",
"0.39597914",
"0.39597914",
"0.39526168",
"0.39512008",
"0.39476755",
"0.3941227",
"0.39392525",
"0.39305803",
"0.39253023",
"0.39113683",
"0.39097667",
"0.39094928",
"0.39090267",
"0.38963374",
"0.38895103",
"0.38762376",
"0.3870476",
"0.38679877",
"0.38638115",
"0.38527006",
"0.3849639",
"0.3848998",
"0.38421813",
"0.38413736",
"0.38406852",
"0.38399318",
"0.38366365",
"0.3833598",
"0.3817859",
"0.38137385",
"0.38037392",
"0.38032585",
"0.3802643",
"0.38013637",
"0.37908244",
"0.37897533",
"0.37884635",
"0.37863955",
"0.3783302",
"0.37763646",
"0.37733945",
"0.37730718",
"0.37726033",
"0.37704065",
"0.37673384",
"0.37659797",
"0.37659797",
"0.37639502",
"0.37597832",
"0.3759072",
"0.37545764"
] | 0.746301 | 0 |
FPDF_VIEWERREF_GetNumCopies returns the number of copies to be printed. | func (p *PdfiumImplementation) FPDF_VIEWERREF_GetNumCopies(request *requests.FPDF_VIEWERREF_GetNumCopies) (*responses.FPDF_VIEWERREF_GetNumCopies, error) {
p.Lock()
defer p.Unlock()
documentHandle, err := p.getDocumentHandle(request.Document)
if err != nil {
return nil, err
}
numCopies := C.FPDF_VIEWERREF_GetNumCopies(documentHandle.handle)
return &responses.FPDF_VIEWERREF_GetNumCopies{
NumCopies: int(numCopies),
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func theBookHasCopies(copies int) error {\n\tassert.Equal(&t, int64(copies), BookStock.Copies, \"copies are not equal\")\n\treturn t.err\n}",
"func (s *singleCapture) NumCapturedLines() int {\n\tif lines := s.CapturedLines(); lines != nil {\n\t\treturn len(lines)\n\t}\n\treturn 0\n}",
"func (r BundleReferencesCollection) Len() int {\n\treturn len(r)\n}",
"func (m *PrinterDefaults) GetCopiesPerJob()(*int32) {\n val, err := m.GetBackingStore().Get(\"copiesPerJob\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}",
"func (l *PackageRefList) Len() int {\n\treturn len(l.Refs)\n}",
"func (p *Proc) NumInstances() (int, error) {\n\tsp, err := p.GetSnapshot().FastForward()\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\trevs, err := sp.Getdir(p.dir.Prefix(\"instances\"))\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\ttotal := 0\n\n\tfor _, rev := range revs {\n\t\tsize, _, err := sp.Stat(p.dir.Prefix(\"instances\", rev), &sp.Rev)\n\t\tif err != nil {\n\t\t\treturn -1, err\n\t\t}\n\t\ttotal += size\n\t}\n\treturn total, nil\n}",
"func (c *testCapture) Length() int {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\treturn len(c.captured)\n}",
"func (t *Link) PreviewLen() (l int) {\n\treturn len(t.preview)\n\n}",
"func (p *PdfiumImplementation) FPDF_CountNamedDests(request *requests.FPDF_CountNamedDests) (*responses.FPDF_CountNamedDests, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcount := C.FPDF_CountNamedDests(documentHandle.handle)\n\treturn &responses.FPDF_CountNamedDests{\n\t\tCount: uint64(count),\n\t}, nil\n}",
"func (ms Span) DroppedLinksCount() uint32 {\n\treturn ms.orig.DroppedLinksCount\n}",
"func (o *VolumeSnapshotAttributesType) SnapshotCount() int {\n\tvar r int\n\tif o.SnapshotCountPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.SnapshotCountPtr\n\treturn r\n}",
"func (dst Proxies) Len() int { return len(dst) }",
"func (d *VolumeDriver) getRefCount(vol string) uint {\n\tif d.refCounts.IsInitialized() != true {\n\t\treturn 1\n\t}\n\treturn d.refCounts.GetCount(vol)\n}",
"func (s *MemoryStore) NumSubscriptions() int {\n\ts.subsMux.RLock()\n\tdefer s.subsMux.RUnlock()\n\n\treturn len(s.subscriptions)\n}",
"func (s *Slicer) NumMaterials() int {\n\tif s.irmf == nil {\n\t\treturn 0\n\t}\n\treturn len(s.irmf.Materials)\n}",
"func (s LifecyclerRPC) Copies(version string, flagValues map[string]interface{}) ([]string, error) {\n\tvar resp []string\n\terr := s.client.Call(\"Plugin.Copies\", HostOpts{Version: version, FlagValues: flagValues}, &resp)\n\treturn resp, err\n}",
"func (sc *snapshotInfoContainer) Len() int {\n\treturn sc.snapshotList.Len()\n}",
"func (s *RecallSourceSorter) Len() int {\n return len(s.recall_source)\n}",
"func (p Page) Len() int { return len(p) }",
"func (r *RolloutSet) NumSteps() int {\n\tvar count int\n\tfor _, seq := range r.Rewards {\n\t\tcount += len(seq)\n\t}\n\treturn count\n}",
"func (psc *PubSubChannel) NumSubscriptions() int {\n psc.subsMutex.RLock()\n defer psc.subsMutex.RUnlock()\n return len(psc.subscriptions)\n}",
"func (pp *Pubcomp) Len() int {\n\treturn identifiedLen()\n}",
"func (bh browserHistory) Len() int { return len(bh.Records) }",
"func (pp *Pubrec) Len() int {\n\treturn identifiedLen()\n}",
"func (r ProjectReferential) Len() int {\n\treturn len(r)\n}",
"func (r *ImageRef) GetPages() int {\n\treturn r.Pages()\n}",
"func (s *Store) NumLines() int {\n\treturn len(s.lines)\n}",
"func (p *PdfiumImplementation) FPDF_VIEWERREF_GetDuplex(request *requests.FPDF_VIEWERREF_GetDuplex) (*responses.FPDF_VIEWERREF_GetDuplex, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tduplexType := C.FPDF_VIEWERREF_GetDuplex(documentHandle.handle)\n\treturn &responses.FPDF_VIEWERREF_GetDuplex{\n\t\tDuplexType: enums.FPDF_DUPLEXTYPE(duplexType),\n\t}, nil\n}",
"func (ms *MultiSorter) Len() int {\n\treturn len(ms.films)\n}",
"func (pp *Pubrel) Len() int {\n\treturn identifiedLen()\n}",
"func (r *ImageRef) Pages() int {\n\t// libvips uses the same attribute (n_pages) to represent the number of pyramid layers in JP2K\n\t// as we interpret the attribute as frames and JP2K does not support animation we override this with 1\n\tif r.format == ImageTypeJP2K {\n\t\treturn 1\n\t}\n\n\treturn vipsGetImageNPages(r.image)\n}",
"func (o ScanRunPtrOutput) UrlsTestedCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.UrlsTestedCount\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o ScanRunPtrOutput) UrlsTestedCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.UrlsTestedCount\n\t}).(pulumi.StringPtrOutput)\n}",
"func (p *PdfiumImplementation) FPDF_VIEWERREF_GetPrintPageRange(request *requests.FPDF_VIEWERREF_GetPrintPageRange) (*responses.FPDF_VIEWERREF_GetPrintPageRange, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpageRange := C.FPDF_VIEWERREF_GetPrintPageRange(documentHandle.handle)\n\tpageRangeHandle := p.registerPageRange(pageRange, documentHandle)\n\n\treturn &responses.FPDF_VIEWERREF_GetPrintPageRange{\n\t\tPageRange: pageRangeHandle.nativeRef,\n\t}, nil\n}",
"func (ps *MemProfiles) Len() int {\n\treturn len(ps.internal)\n}",
"func (psg PagesGroup) Len() int {\n\tl := 0\n\tfor _, pg := range psg {\n\t\tl += len(pg.Pages)\n\t}\n\treturn l\n}",
"func (g *GooglePubSub) NumPublishersRunning() int {\n\tg.publishMutex.Lock()\n\tnumPubs := g.numRunningPublish\n\tg.publishMutex.Unlock()\n\treturn numPubs\n}",
"func (b book) Len() int {\n return len(b)\n}",
"func (s papertrailsByName) Len() int { return len(s) }",
"func (o ScanRunOutput) UrlsTestedCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.UrlsTestedCount }).(pulumi.StringPtrOutput)\n}",
"func (o ScanRunOutput) UrlsTestedCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.UrlsTestedCount }).(pulumi.StringPtrOutput)\n}",
"func (attr *Attribute) CountReferenceTypes() int {\n\treturn len(attr.referenceTypes)\n}",
"func (s *outputSorter) Len() int {\n\treturn len(s.averages)\n}",
"func (ns *Namespace) GetNumOriginalObjects(gvk schema.GroupVersionKind) int {\n\treturn len(ns.originalObjects[gvk])\n}",
"func (r *CyclicPoly) Len() int {\n\treturn cap(r.p)\n}",
"func (o ScanRunPtrOutput) UrlsCrawledCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.UrlsCrawledCount\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o ScanRunPtrOutput) UrlsCrawledCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.UrlsCrawledCount\n\t}).(pulumi.StringPtrOutput)\n}",
"func (f *Face) NumFaces() int {\n\treturn int(f.handle.num_faces)\n}",
"func (r Remapping) NumFiles() uint32 {\n\treturn uint32(C.clang_remap_getNumFiles(r.c))\n}",
"func NumPosrefTerms() uint32 {\n\treturn uint32(C.yices_num_posref_terms())\n}",
"func (r *Release) DownloadCount() int {\n\tcount := 0\n\tfor _, a := range r.Assets {\n\t\tcount += a.Count\n\t}\n\treturn count\n}",
"func PRepCount() float64 {\n\tpReps.Mutex.Lock()\n\tcount := len(pReps.PReps)\n\tpReps.Mutex.Unlock()\n\treturn float64(count)\n}",
"func (v CollectRewards) Copy() StakeMsg {\n\tv1 := v\n\treturn v1\n}",
"func (e *Editor) NumLines() int {\n\te.makeValid()\n\treturn len(e.lines)\n}",
"func (m *PrinterDefaults) SetCopiesPerJob(value *int32)() {\n err := m.GetBackingStore().Set(\"copiesPerJob\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (pi Peers) PeerCount() uint64 {\n\tpeers := pi.snapshot.Load().([]Peer)\n\treturn uint64(len(peers))\n}",
"func (t *Tab) NumPages() int {\n\treturn len(t.children)\n}",
"func (bg *Backgrounder) Count() int {\n\treturn bg.count\n}",
"func (o BackupOutput) ReferencingBackups() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Backup) pulumi.StringArrayOutput { return v.ReferencingBackups }).(pulumi.StringArrayOutput)\n}",
"func (n Interviews) Len() int {\n\treturn len(n)\n}",
"func (f Forwarder) ConnectionCount() int {\n\treturn f.connections\n}",
"func (o AutoSnapshotPolicyOutput) CopiedSnapshotsRetentionDays() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *AutoSnapshotPolicy) pulumi.IntPtrOutput { return v.CopiedSnapshotsRetentionDays }).(pulumi.IntPtrOutput)\n}",
"func (f Fetcher) printLinkCount() {\n\tdoc, err := goquery.NewDocumentFromReader(f.resp.Body)\n\tcheck(err)\n\tc := len(doc.Find(\"a\").Nodes)\n\tfmt.Printf(\"Link count: %d\\n\", c)\n}",
"func (o ScanRunOutput) UrlsCrawledCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.UrlsCrawledCount }).(pulumi.StringPtrOutput)\n}",
"func (o ScanRunOutput) UrlsCrawledCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.UrlsCrawledCount }).(pulumi.StringPtrOutput)\n}",
"func (self *SAMFile) RefLengths() []uint32 {\n\th := self.header()\n\tif h == nil {\n\t\treturn nil\n\t}\n\treturn h.targetLengths()\n}",
"func (p *PdfiumImplementation) FPDFLink_CountWebLinks(request *requests.FPDFLink_CountWebLinks) (*responses.FPDFLink_CountWebLinks, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageLinkhandle, err := p.getPageLinkHandle(request.PageLink)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcount := C.FPDFLink_CountWebLinks(pageLinkhandle.handle)\n\n\treturn &responses.FPDFLink_CountWebLinks{\n\t\tCount: int(count),\n\t}, nil\n}",
"func (s Snapshot) Count() int64 {\n\treturn s.count\n}",
"func (c CatalogVersionCollection) Len() int {\n\treturn len(c)\n}",
"func (p *Plugin) GetRefCount() int {\n\tp.mu.RLock()\n\tdefer p.mu.RUnlock()\n\n\treturn p.refCount\n}",
"func ColorCount() int {\n\treturn palette.count\n}",
"func (ms *multiSorter) Len() int {\n\treturn len(ms.vsrecs)\n}",
"func (sm SetMatches) Len() int {\n\treturn len(sm.matches)\n}",
"func (w *WorkBook) NumSheets() int {\n\treturn len(w.sheets)\n}",
"func (self *Glob) NumWildcards() int {\n\treturn len(self.wildcardPositions)\n}",
"func (l *sampleList) Len() int { return len(l.samples) - len(l.free) }",
"func (records *Records) NumRecords() int {\n\treturn len(records.Passwords)\n}",
"func (n *NumFreqSlice) Len() int {\n\treturn len(*n)\n}",
"func (me *XHasElems_NumberOfReferences) Walk() (err error) {\n\tif fn := WalkHandlers.XHasElems_NumberOfReferences; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}",
"func (d *Release) Replicate() int {\n\tsize := 0\n\tfor _, dest := range d.to {\n\t\tswitch dest.(type) {\n\t\tcase *devNull:\n\t\tdefault:\n\t\t\tsize++\n\t\t}\n\t}\n\treturn size\n}",
"func (o BucketLifecycleRuleItemConditionPtrOutput) NumNewerVersions() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *BucketLifecycleRuleItemCondition) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.NumNewerVersions\n\t}).(pulumi.IntPtrOutput)\n}",
"func(peers *PeerList) Copy() map[string]int32 {\n\tpeers.mux.Lock()\n\tdefer peers.mux.Unlock()\n\treturn peers.peerMap\n}",
"func numRookCaptures(board [][]byte) int {\n\tvar y, x int\nFIND_ROOK:\n\tfor y = range board {\n\t\tfor x = range board[y] {\n\t\t\tif board[y][x] == 'R' {\n\t\t\t\tbreak FIND_ROOK\n\t\t\t}\n\t\t}\n\t}\n\tvar count int\n\tfor _, dir := range [][2]int{[2]int{-1, 0}, [2]int{0, 1}, [2]int{1, 0}, [2]int{0, -1}} {\n\t\tfor yy, xx := y+dir[0], x+dir[1]; yy >= 0 && yy < 8 && xx >= 0 && xx < 8; yy, xx = yy+dir[0], xx+dir[1] {\n\t\t\tif board[yy][xx] == 'B' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif board[yy][xx] == 'p' {\n\t\t\t\tcount++\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn count\n}",
"func (c *Comics) Len() int {\n\treturn len(c.comics)\n}",
"func (o ScanRunResponsePtrOutput) UrlsTestedCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRunResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.UrlsTestedCount\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o BucketLifecycleRuleConditionOutput) NumNewerVersions() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v BucketLifecycleRuleCondition) *int { return v.NumNewerVersions }).(pulumi.IntPtrOutput)\n}",
"func (ms *multiSorter) Len() int {\n\treturn len(ms.processos)\n}",
"func (f *DestRequest) ByteCount() int {\n\treturn 1 + f.User.ByteCount()\n}",
"func (o ScanRunResponsePtrOutput) UrlsCrawledCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRunResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.UrlsCrawledCount\n\t}).(pulumi.StringPtrOutput)\n}",
"func (c *Curl) NumRounds() int {\n\treturn int(c.rounds)\n}",
"func (agent *Agent) NumReplicas() int {\n\troutingInfo := agent.routingInfo.Get()\n\tif routingInfo == nil {\n\t\treturn 0\n\t}\n\n\tif routingInfo.vbMap == nil {\n\t\treturn 0\n\t}\n\n\treturn routingInfo.vbMap.NumReplicas()\n}",
"func (o ApplicationSpecRolloutplanPtrOutput) NumBatches() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationSpecRolloutplan) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.NumBatches\n\t}).(pulumi.IntPtrOutput)\n}",
"func (p *PdfiumImplementation) FPDFLink_CountRects(request *requests.FPDFLink_CountRects) (*responses.FPDFLink_CountRects, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageLinkhandle, err := p.getPageLinkHandle(request.PageLink)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcount := C.FPDFLink_CountRects(pageLinkhandle.handle, C.int(request.Index))\n\n\treturn &responses.FPDFLink_CountRects{\n\t\tCount: int(count),\n\t}, nil\n}",
"func (a *Anim) NumFrames() int {\n\ta.access.RLock()\n\tnumFrames := len(a.frames)\n\ta.access.RUnlock()\n\treturn numFrames\n}",
"func (g *GooglePubSub) NumSubscribersRunning() int {\n\tg.subscribeMutex.Lock()\n\tnumSubs := g.numRunningSubscribe\n\tg.subscribeMutex.Unlock()\n\treturn numSubs\n}",
"func (m *Vulnerability) GetReferences()([]Hyperlinkable) {\n val, err := m.GetBackingStore().Get(\"references\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]Hyperlinkable)\n }\n return nil\n}",
"func (m *copyState) getCount() uint64 {\n\treturn atomic.LoadUint64(&m.count)\n}",
"func (s *Slicer) NumZSlices() int {\n\treturn int(0.5 + (s.irmf.Max[2]-s.irmf.Min[2])/s.deltaZ)\n}",
"func (dst Workers) Len() int { return len(dst) }",
"func (b *Buffer) LinesNum() int {\n\treturn len(b.lines)\n}"
] | [
"0.53606635",
"0.50743496",
"0.4884697",
"0.46197453",
"0.45984438",
"0.4580568",
"0.4561211",
"0.450162",
"0.44836405",
"0.44615006",
"0.44529742",
"0.4427664",
"0.44089642",
"0.43953532",
"0.43831533",
"0.43800184",
"0.43733284",
"0.43616185",
"0.43501094",
"0.4328822",
"0.43209463",
"0.42953724",
"0.42882034",
"0.42626983",
"0.42616275",
"0.42525566",
"0.42478514",
"0.42464608",
"0.42434102",
"0.42373392",
"0.42154232",
"0.4211936",
"0.4211936",
"0.42075646",
"0.4207549",
"0.4196116",
"0.41951287",
"0.4188046",
"0.41853055",
"0.41839424",
"0.41839424",
"0.41821575",
"0.41670078",
"0.41665962",
"0.41642436",
"0.41623807",
"0.41623807",
"0.41622156",
"0.41536152",
"0.4145471",
"0.41385838",
"0.4131231",
"0.41281816",
"0.41208512",
"0.4105498",
"0.41003773",
"0.40948644",
"0.40943277",
"0.4081279",
"0.40702516",
"0.4067479",
"0.40647542",
"0.40575063",
"0.40573424",
"0.40573424",
"0.4050281",
"0.40499333",
"0.4046135",
"0.4039593",
"0.40364984",
"0.40274602",
"0.40263504",
"0.40250072",
"0.40214637",
"0.40212357",
"0.4010207",
"0.40068385",
"0.40019837",
"0.39929456",
"0.39916342",
"0.39913186",
"0.39900798",
"0.39889726",
"0.39864153",
"0.39836025",
"0.3983518",
"0.39830357",
"0.39767626",
"0.39730328",
"0.39721382",
"0.39720818",
"0.39714956",
"0.3968114",
"0.39661634",
"0.39648232",
"0.39630368",
"0.39606285",
"0.395543",
"0.39542112",
"0.39510804"
] | 0.8110711 | 0 |
FPDF_VIEWERREF_GetPrintPageRange returns the page numbers to initialize print dialog box when file is printed. | func (p *PdfiumImplementation) FPDF_VIEWERREF_GetPrintPageRange(request *requests.FPDF_VIEWERREF_GetPrintPageRange) (*responses.FPDF_VIEWERREF_GetPrintPageRange, error) {
p.Lock()
defer p.Unlock()
documentHandle, err := p.getDocumentHandle(request.Document)
if err != nil {
return nil, err
}
pageRange := C.FPDF_VIEWERREF_GetPrintPageRange(documentHandle.handle)
pageRangeHandle := p.registerPageRange(pageRange, documentHandle)
return &responses.FPDF_VIEWERREF_GetPrintPageRange{
PageRange: pageRangeHandle.nativeRef,
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (this Pager) GetPageRange(pageIndex int) (result Int2) {\r\n\tresult.X = pageIndex * this.PageSize\r\n\tresult.Y = result.X + this.PageSize\r\n\treturn\r\n}",
"func (m *PrinterDefaults) GetPagesPerSheet()(*int32) {\n val, err := m.GetBackingStore().Get(\"pagesPerSheet\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}",
"func (r *ImageRef) GetPages() int {\n\treturn r.Pages()\n}",
"func NewPDFRangeRef(ref unsafe.Pointer) *PDFRange {\n\treturn (*PDFRange)(ref)\n}",
"func NewPDFRange() *PDFRange {\n\treturn (*PDFRange)(allocPDFRangeMemory(1))\n}",
"func (xs *Sheet) GetPrintFit() (wPages int, hPages int) {\n\txs.xb.lib.NewProc(\"xlSheetGetPrintFitW\").\n\t\tCall(xs.self, I_P(&wPages), I_P(&hPages))\n\treturn wPages, hPages\n}",
"func pageRange(p *params, n int) (int, int) {\n\tif p.Count == 0 && p.Offset == 0 {\n\t\treturn 0, n\n\t}\n\tif p.Count < 0 {\n\t\t// Items from the back of the array, like Python arrays. Do a postive mod n.\n\t\treturn (((n + p.Count) % n) + n) % n, n\n\t}\n\tstart := p.Offset\n\tif start < 0 {\n\t\tstart = 0\n\t}\n\tif p.Count == 0 { // No count specified. Just take the offset parameter.\n\t\treturn start, n\n\t}\n\tend := start + p.Count\n\tif end > n {\n\t\tend = n\n\t}\n\treturn start, end\n}",
"func (p *PdfiumImplementation) FPDF_VIEWERREF_GetPrintScaling(request *requests.FPDF_VIEWERREF_GetPrintScaling) (*responses.FPDF_VIEWERREF_GetPrintScaling, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprintScaling := C.FPDF_VIEWERREF_GetPrintScaling(documentHandle.handle)\n\treturn &responses.FPDF_VIEWERREF_GetPrintScaling{\n\t\tPreferPrintScaling: int(printScaling) == 1,\n\t}, nil\n}",
"func NewPDFXrangeRef(ref unsafe.Pointer) *PDFXrange {\n\treturn (*PDFXrange)(ref)\n}",
"func (r *ImageRef) Pages() int {\n\t// libvips uses the same attribute (n_pages) to represent the number of pyramid layers in JP2K\n\t// as we interpret the attribute as frames and JP2K does not support animation we override this with 1\n\tif r.format == ImageTypeJP2K {\n\t\treturn 1\n\t}\n\n\treturn vipsGetImageNPages(r.image)\n}",
"func (m *PrinterDefaults) GetFitPdfToPage()(*bool) {\n val, err := m.GetBackingStore().Get(\"fitPdfToPage\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}",
"func (b *Blob) GetPageRanges(options *GetPageRangesOptions) (GetPageRangesResponse, error) {\n\tparams := url.Values{\"comp\": {\"pagelist\"}}\n\theaders := b.Container.bsc.client.getStandardHeaders()\n\n\tif options != nil {\n\t\tparams = addTimeout(params, options.Timeout)\n\t\tparams = addSnapshot(params, options.Snapshot)\n\t\tif options.PreviousSnapshot != nil {\n\t\t\tparams.Add(\"prevsnapshot\", timeRFC3339Formatted(*options.PreviousSnapshot))\n\t\t}\n\t\tif options.Range != nil {\n\t\t\theaders[\"Range\"] = options.Range.String()\n\t\t}\n\t\theaders = mergeHeaders(headers, headersFromStruct(*options))\n\t}\n\turi := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params)\n\n\tvar out GetPageRangesResponse\n\tresp, err := b.Container.bsc.client.exec(http.MethodGet, uri, headers, nil, b.Container.bsc.auth)\n\tif err != nil {\n\t\treturn out, err\n\t}\n\tdefer drainRespBody(resp)\n\n\tif err = checkRespCode(resp, []int{http.StatusOK}); err != nil {\n\t\treturn out, err\n\t}\n\terr = xmlUnmarshal(resp.Body, &out)\n\treturn out, err\n}",
"func NewPDFMrangeRef(ref unsafe.Pointer) *PDFMrange {\n\treturn (*PDFMrange)(ref)\n}",
"func allocPDFRangeMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFRangeValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (o RouterAdvertisedIpRangeOutput) Range() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RouterAdvertisedIpRange) *string { return v.Range }).(pulumi.StringPtrOutput)\n}",
"func (o *Range) GetPage() gdnative.Real {\n\t//log.Println(\"Calling Range.GetPage()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"Range\", \"get_page\")\n\n\t// Call the parent method.\n\t// float\n\tretPtr := gdnative.NewEmptyReal()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewRealFromPointer(retPtr)\n\treturn ret\n}",
"func (p *Paginator) PageNums() int {\n\tif p.pageNums != 0 {\n\t\treturn p.pageNums\n\t}\n\tpageNums := math.Ceil(float64(p.nums) / float64(p.PerPageNums))\n\tif p.MaxPages > 0 {\n\t\tpageNums = math.Min(pageNums, float64(p.MaxPages))\n\t}\n\tp.pageNums = int(pageNums)\n\treturn p.pageNums\n}",
"func (x *PDFRange) Ref() *C.pdf_range {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_range)(unsafe.Pointer(x))\n}",
"func allocPDFXrangeMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFXrangeValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (p *PdfiumImplementation) FPDF_VIEWERREF_GetNumCopies(request *requests.FPDF_VIEWERREF_GetNumCopies) (*responses.FPDF_VIEWERREF_GetNumCopies, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnumCopies := C.FPDF_VIEWERREF_GetNumCopies(documentHandle.handle)\n\treturn &responses.FPDF_VIEWERREF_GetNumCopies{\n\t\tNumCopies: int(numCopies),\n\t}, nil\n}",
"func (o TableExternalDataConfigurationGoogleSheetsOptionsPtrOutput) Range() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TableExternalDataConfigurationGoogleSheetsOptions) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Range\n\t}).(pulumi.StringPtrOutput)\n}",
"func NewPDFXrange() *PDFXrange {\n\treturn (*PDFXrange)(allocPDFXrangeMemory(1))\n}",
"func (xs *Sheet) PrintArea() (rowFirst int, rowLast int, colFirst int, colLast int) {\n\txs.xb.lib.NewProc(\"xlSheetPrintAreaW\").\n\t\tCall(xs.self, I_P(&rowFirst), I_P(&rowLast), I_P(&colFirst), I_P(&colLast))\n\treturn int(rowFirst), int(rowLast), int(colFirst), int(colLast)\n}",
"func NewPDFMrange() *PDFMrange {\n\treturn (*PDFMrange)(allocPDFMrangeMemory(1))\n}",
"func pageAddress(pointer int, pagesize int) int {\n\tpageAddress := pointer % pagesize\n\tif pageAddress < 0 {\n\t\treturn pagesize + pageAddress\n\t}\n\treturn pageAddress\n}",
"func (ip insertedPages) insertedPageNumbers() string {\n\tvar s []string\n\tfor _, n := range ip.insertedPageNos() {\n\t\ts = append(s, strconv.Itoa(n))\n\t}\n\to := strings.Join(s, \" and \")\n\tn := strings.Count(o, \" and \")\n\tif n > 1 {\n\t\to = strings.Replace(o, \" and \", \", \", n-1)\n\t}\n\treturn o\n}",
"func (pb *PageBuffer) PageNo() int {\n return pb.page_no\n}",
"func (o TableExternalDataConfigurationGoogleSheetsOptionsOutput) Range() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v TableExternalDataConfigurationGoogleSheetsOptions) *string { return v.Range }).(pulumi.StringPtrOutput)\n}",
"func (m *PrinterDefaults) SetPagesPerSheet(value *int32)() {\n err := m.GetBackingStore().Set(\"pagesPerSheet\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (o RouterAdvertisedIpRangeResponseOutput) Range() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RouterAdvertisedIpRangeResponse) string { return v.Range }).(pulumi.StringOutput)\n}",
"func (pagination *Pagination) Range(r Range) *Pagination {\n\tpagination.driver.Range(r)\n\treturn pagination\n}",
"func GetPageSize() uint64 {\n\tpanic(\"not implemented\")\n}",
"func GetPDFPages(inPath string, outPath string, frames []parser.Section) error {\n\n\tif _, err := os.Stat(outPath); os.IsNotExist(err) {\n\t\tlog.Println(\"Output dir not found. Creating at \", outPath)\n\t\terr := os.Mkdir(outPath, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"[PDF Extractor] %s\", err)\n\t\t}\n\t}\n\n\timagick.Initialize()\n\tdefer imagick.Terminate()\n\n\tmw := imagick.NewMagickWand()\n\tdefer mw.Destroy()\n\n\tif err := mw.SetResolution(300, 300); err != nil {\n\t\treturn err\n\t}\n\n\t// Load the image file into imagick\n\tif err := mw.ReadImage(inPath); err != nil {\n\t\treturn err\n\t}\n\n\t// fmt.Println(mw.GetNumberImages())\n\n\t// Set any compression (100 = max quality)\n\tif err := mw.SetCompressionQuality(100); err != nil {\n\t\treturn err\n\t}\n\n\tif err := mw.SetFormat(\"jpg\"); err != nil {\n\t\treturn err\n\t}\n\tvar err error\n\tfor _, frame := range frames {\n\n\t\tmw.SetIteratorIndex(frame.Page - 1)\n\n\t\t// if err := mw.SetImageFormat(\"jpeg\"); err != nil {\n\t\t// \treturn err\n\t\t// }\n\n\t\t// Save File\n\t\terr = mw.WriteImage(filepath.Join(outPath, frame.FrameSrc.ImageSrc))\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%s [PDF extraction: page: %d, loc: %s, to %s] \", err, frame.Page, inPath, filepath.Join(outPath, frame.FrameSrc.ImageSrc))\n\t\t}\n\n\t}\n\treturn nil\n}",
"func (o *AutoscalerResourceLimitsGPULimit) GetRange() (value *ResourceRange, ok bool) {\n\tok = o != nil && o.bitmap_&1 != 0\n\tif ok {\n\t\tvalue = o.range_\n\t}\n\treturn\n}",
"func (o RouterInterfaceOutput) IpRange() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RouterInterface) *string { return v.IpRange }).(pulumi.StringPtrOutput)\n}",
"func calPageList(p, maxPageNum int) []*page {\n\tlistSize := 15\n\thls := listSize / 2\n\tpl := make([]*page, 0, listSize)\n\n\tstart, end := p-hls, p+hls\n\tif p < hls+1 {\n\t\tstart, end = 1, listSize\n\t}\n\n\tif end > maxPageNum {\n\t\tend = maxPageNum\n\t}\n\n\tfor i := start; i <= end; i++ {\n\t\tpl = append(pl, &page{\n\t\t\tIsActive: i == p,\n\t\t\tPageNum: i,\n\t\t})\n\t}\n\treturn pl\n}",
"func PaginationWithRange(start, end uint64) *PaginationOption {\n\treturn Pagination(start, end-start+1)\n}",
"func allocPDFMrangeMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFMrangeValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (v *IconView) GetVisibleRange() (*TreePath, *TreePath) {\n\tvar (\n\t\tcpathStart, cpathEnd *C.GtkTreePath\n\t\tpathStart, pathEnd *TreePath\n\t)\n\n\tC.gtk_icon_view_get_visible_range(v.native(), &cpathStart, &cpathEnd)\n\n\tif cpathStart != nil {\n\t\tpathStart = &TreePath{cpathStart}\n\t\truntime.SetFinalizer(pathStart, func(v *TreePath) { glib.FinalizerStrategy(v.free) })\n\t}\n\n\tif cpathEnd != nil {\n\t\tpathEnd = &TreePath{cpathEnd}\n\t\truntime.SetFinalizer(pathEnd, func(v *TreePath) { glib.FinalizerStrategy(v.free) })\n\t}\n\n\treturn pathStart, pathEnd\n}",
"func (ref *UIElement) RTFForRange(r Range) []byte {\n\ta := cfstr(RTFForRangeParameterizedAttribute)\n\tdefer C.CFRelease(C.CFTypeRef(a))\n\n\tcfRange := C.CFRangeMake(C.CFIndex(r.Location), C.CFIndex(r.Length))\n\taxRangeValue := C.AXValueCreate(C.kAXValueTypeCFRange, unsafe.Pointer(&cfRange))\n\tdefer C.CFRelease(C.CFTypeRef(axRangeValue))\n\tvar value C.CFTypeRef\n\tC.AXUIElementCopyParameterizedAttributeValue(ref.obj, a, axRangeValue, &value)\n\tif value == nil {\n\t\treturn []byte{}\n\t}\n\tdefer C.CFRelease(value)\n\tif C.CFGetTypeID(value) != C.CFDataGetTypeID() {\n\t\treturn []byte{}\n\t}\n\tlength := int(C.CFDataGetLength(C.CFDataRef(value)))\n\tdata := make([]byte, length)\n\tptr := uintptr(unsafe.Pointer(C.CFDataGetBytePtr(C.CFDataRef(value))))\n\tfor i := 0; i < length; i++ {\n\t\tdata[i] = byte(*(*C.UInt8)(unsafe.Pointer(ptr)))\n\t\tptr = ptr + 1\n\t}\n\treturn data\n}",
"func (x *PDFMrange) Ref() *C.pdf_mrange {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_mrange)(unsafe.Pointer(x))\n}",
"func (t *Tab) NumPages() int {\n\treturn len(t.children)\n}",
"func (pb *Pbar) SetPrintNumbers(arg string) {\n\tif arg == \"percent\" || arg == \"%\" {\n\t\tpb.printNumbers = 2\n\t} else if arg == \"ratio\" || arg == \"numeric\" || arg == \"/\" || arg == \"fraction\" {\n\t\tpb.printNumbers = 1\n\t} else {\n\t\tpb.printNumbers = 0\n\t}\n}",
"func GetRangeLimit() int {\n\treturn 25\n}",
"func (x *PDFXrange) Ref() *C.pdf_xrange {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_xrange)(unsafe.Pointer(x))\n}",
"func (pb PageBlobURL) GetPageRanges(ctx context.Context, offset int64, count int64, ac BlobAccessConditions) (*PageList, error) {\n\tifModifiedSince, ifUnmodifiedSince, ifMatchETag, ifNoneMatchETag := ac.ModifiedAccessConditions.pointers()\n\treturn pb.pbClient.GetPageRanges(ctx, nil, nil,\n\t\thttpRange{offset: offset, count: count}.pointers(),\n\t\tac.LeaseAccessConditions.pointers(),\n\t\tifModifiedSince, ifUnmodifiedSince, ifMatchETag, ifNoneMatchETag,\n\t\tnil, // Blob ifTags\n\t\tnil)\n}",
"func (ser *Series) PrintRange(first, last int) {\n\tser.WriteRange(os.Stdout, first, last)\n}",
"func BookletFromPDF(ctx *model.Context, selectedPages types.IntSet, nup *model.NUp) error {\n\tn := int(nup.Grid.Width * nup.Grid.Height)\n\tif !(n == 2 || n == 4) {\n\t\treturn fmt.Errorf(\"pdfcpu: booklet must have n={2,4} pages per sheet, got %d\", n)\n\t}\n\n\tvar mb *types.Rectangle\n\n\tif nup.PageDim == nil {\n\t\tnup.PageDim = types.PaperSize[nup.PageSize]\n\t}\n\n\tmb = types.RectForDim(nup.PageDim.Width, nup.PageDim.Height)\n\n\tpagesDict := types.Dict(\n\t\tmap[string]types.Object{\n\t\t\t\"Type\": types.Name(\"Pages\"),\n\t\t\t\"Count\": types.Integer(0),\n\t\t\t\"MediaBox\": mb.Array(),\n\t\t},\n\t)\n\n\tpagesIndRef, err := ctx.IndRefForNewObject(pagesDict)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnup.PageDim = &types.Dim{Width: mb.Width(), Height: mb.Height()}\n\n\tif nup.MultiFolio {\n\t\tpages := types.IntSet{}\n\t\tfor _, i := range sortSelectedPages(selectedPages) {\n\t\t\tpages[i] = true\n\t\t\tif len(pages) == 4*nup.FolioSize {\n\t\t\t\tif err = bookletPages(ctx, pages, nup, pagesDict, pagesIndRef); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tpages = types.IntSet{}\n\t\t\t}\n\t\t}\n\t\tif len(pages) > 0 {\n\t\t\tif err = bookletPages(ctx, pages, nup, pagesDict, pagesIndRef); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\tif err = bookletPages(ctx, selectedPages, nup, pagesDict, pagesIndRef); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Replace original pagesDict.\n\trootDict, err := ctx.Catalog()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trootDict.Update(\"Pages\", *pagesIndRef)\n\treturn nil\n}",
"func (p *Paginator) Pages() []int {\n\ts := make([]int, 0, p.NumberOfPages())\n\n\tfor i := 1; i <= p.NumberOfPages(); i++ {\n\t\ts = append(s, i)\n\t}\n\n\treturn s\n}",
"func (r *RMFileInfo) PageIterate() (pageNo, pdfPageNo int, inserted, isTemplate bool, reader *io.ReadSeeker) {\n\tpageNo = r.thisPageNo\n\tr.thisPageNo++\n\n\t// if there is only a template, always return the first page\n\tif r.pdfPath == \"\" {\n\t\tpdfPageNo = 0\n\t\tisTemplate = true\n\t\treader = &r.templateReader\n\t\treturn\n\t}\n\n\t// older remarkable bundles don't report inserted pages; ignore\n\thasRedir := func() bool { return len(r.RedirectionPageMap) > 0 }()\n\n\t// return the template if this is an inserted page\n\tif hasRedir && r.RedirectionPageMap[pageNo] == -1 {\n\t\tpdfPageNo = 0\n\t\tinserted = true\n\t\tisTemplate = true\n\t\treader = &r.templateReader\n\t\treturn\n\t}\n\n\t// remaining target is the annotated file\n\treader = &r.pdfReader\n\n\t// if the annotated pdf has inserted pages, calculate the offset of\n\t// the original pdf to use\n\tif hasRedir && r.PageCount != r.OriginalPageCount {\n\t\tpdfPageNo = pageNo\n\t\tfor i := 0; i <= pageNo; i++ {\n\t\t\tif r.RedirectionPageMap[i] == -1 {\n\t\t\t\tpdfPageNo--\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\t// fall through: the annotated pdf has no inserted pages\n\tpdfPageNo = pageNo\n\treturn\n\n}",
"func (_this *FontFace) UnicodeRange() string {\n\tvar ret string\n\tvalue := _this.Value_JS.Get(\"unicodeRange\")\n\tret = (value).String()\n\treturn ret\n}",
"func (o PublicAdvertisedPrefixPublicDelegatedPrefixResponseOutput) IpRange() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PublicAdvertisedPrefixPublicDelegatedPrefixResponse) string { return v.IpRange }).(pulumi.StringOutput)\n}",
"func (jobImpl *JobImpl) Range() int64 {\n\treturn jobImpl.rangeImpl\n}",
"func parsePageOpts(maxPageSize int, pa core.PageArgs) (first, last int, after, before primitive.ObjectID, err error) {\n\t// Validate first.\n\tif pa.First != nil {\n\t\tif *pa.First < 0 {\n\t\t\treturn 0, 0, primitive.NilObjectID, primitive.NilObjectID, fmt.Errorf(\"invalid 'first' field value: %v\", pa.First)\n\t\t}\n\t\tif maxPageSize <= *pa.First {\n\t\t\tfirst = maxPageSize\n\t\t} else {\n\t\t\tfirst = *pa.First\n\t\t}\n\t}\n\n\t// Validate last.\n\tif pa.Last != nil {\n\t\tif *pa.Last < 0 {\n\t\t\treturn 0, 0, primitive.NilObjectID, primitive.NilObjectID, fmt.Errorf(\"invalid 'last' field value: %v\", pa.Last)\n\t\t}\n\t\tif maxPageSize <= *pa.Last {\n\t\t\tlast = maxPageSize\n\t\t} else {\n\t\t\tlast = *pa.Last\n\t\t}\n\t}\n\n\t// If neither first nor last were supplied, return maxPageSize elements.\n\tif first == 0 && last == 0 {\n\t\tfirst = maxPageSize\n\t}\n\n\t// Validate after.\n\tif pa.After != nil {\n\t\tafter, err = primitive.ObjectIDFromHex(*pa.After)\n\t\tif err != nil {\n\t\t\treturn 0, 0, primitive.NilObjectID, primitive.NilObjectID, fmt.Errorf(\"invalid 'after' field value: %v\", err)\n\t\t}\n\t}\n\n\t// Validate before.\n\tif pa.Before != nil {\n\t\tbefore, err = primitive.ObjectIDFromHex(*pa.Before)\n\t\tif err != nil {\n\t\t\treturn 0, 0, primitive.NilObjectID, primitive.NilObjectID, fmt.Errorf(\"invalid 'before' field value: %v\", err)\n\t\t}\n\t}\n\n\treturn first, last, after, before, nil\n}",
"func (p *Pagination) pages() int {\n\treturn int(math.Ceil(float64(p.Total) / float64(p.Limit)))\n}",
"func (pb PageBlobURL) GetPageRangesDiff(ctx context.Context, offset int64, count int64, prevSnapshot string, ac BlobAccessConditions) (*PageList, error) {\n\tifModifiedSince, ifUnmodifiedSince, ifMatchETag, ifNoneMatchETag := ac.ModifiedAccessConditions.pointers()\n\treturn pb.pbClient.GetPageRangesDiff(ctx, nil, nil, &prevSnapshot,\n\t\tnil, // Get managed disk diff\n\t\thttpRange{offset: offset, count: count}.pointers(),\n\t\tac.LeaseAccessConditions.pointers(),\n\t\tifModifiedSince, ifUnmodifiedSince, ifMatchETag, ifNoneMatchETag,\n\t\tnil, // Blob ifTags\n\t\tnil)\n}",
"func (p *Pagination) Pages() []int {\n\ts := make([]int, 0, p.NumberOfPages())\n\n\tfor i := 1; i <= p.NumberOfPages(); i++ {\n\t\ts = append(s, i)\n\t}\n\n\treturn s\n}",
"func (o *AutoscalerResourceLimitsGPULimit) Range() *ResourceRange {\n\tif o != nil && o.bitmap_&1 != 0 {\n\t\treturn o.range_\n\t}\n\treturn nil\n}",
"func allocPDFRevPageMapMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFRevPageMapValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func (gppr GetPathPropertiesResponse) ContentRange() string {\n\treturn gppr.rawResponse.Header.Get(\"Content-Range\")\n}",
"func (o RouterInterfaceResponseOutput) IpRange() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RouterInterfaceResponse) string { return v.IpRange }).(pulumi.StringOutput)\n}",
"func (xs *Sheet) SetPrintArea(rowFirst int, rowLast int, colFirst int, colLast int) {\n\txs.xb.lib.NewProc(\"xlSheetSetPrintAreaW\").\n\t\tCall(xs.self, I(rowFirst), I(rowLast), I(colFirst), I(colLast))\n}",
"func OffsetToPage(offset, size int) int {\n\treturn (offset / size) + 1\n}",
"func (s PortRange) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Begin != nil {\n\t\tv := *s.Begin\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Begin\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.End != nil {\n\t\tv := *s.End\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"End\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}",
"func (ref *UIElement) BoundsForRange(r Range) Rect {\n\ta := cfstr(BoundsForRangeParameterizedAttribute)\n\tdefer C.CFRelease(C.CFTypeRef(a))\n\tcfRange := C.CFRangeMake(C.CFIndex(r.Location), C.CFIndex(r.Length))\n\taxRangeValue := C.AXValueCreate(C.kAXValueTypeCFRange, unsafe.Pointer(&cfRange))\n\tdefer C.CFRelease(C.CFTypeRef(axRangeValue))\n\tvar value C.CFTypeRef\n\tC.AXUIElementCopyParameterizedAttributeValue(ref.obj, a, axRangeValue, &value)\n\tret := convertCFType(value)\n\to, ok := ret.(Rect)\n\tif !ok {\n\t\treturn Rect{Point{0, 0}, Size{0, 0}}\n\t}\n\treturn o\n}",
"func (v *Provider) Range() (int64, error) {\n\tres, err := v.apiG()\n\n\tif res, ok := res.(Response); err == nil && ok {\n\t\treturn int64(res.Data.Attributes.RangeHvacOff), nil\n\t}\n\n\treturn 0, err\n}",
"func PortRangeGenerator() gopter.Gen {\n\tif portRangeGenerator != nil {\n\t\treturn portRangeGenerator\n\t}\n\n\tgenerators := make(map[string]gopter.Gen)\n\tAddIndependentPropertyGeneratorsForPortRange(generators)\n\tportRangeGenerator = gen.Struct(reflect.TypeOf(PortRange{}), generators)\n\n\treturn portRangeGenerator\n}",
"func (p Pointer) Range(s uint64) Range {\n\treturn Range{Base: p.Address, Size: s}\n}",
"func (x *fastReflection_ValidatorCurrentRewardsRecord) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.ValidatorAddress != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.ValidatorAddress)\n\t\tif !f(fd_ValidatorCurrentRewardsRecord_validator_address, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.Rewards != nil {\n\t\tvalue := protoreflect.ValueOfMessage(x.Rewards.ProtoReflect())\n\t\tif !f(fd_ValidatorCurrentRewardsRecord_rewards, value) {\n\t\t\treturn\n\t\t}\n\t}\n}",
"func PrintIPRange(ipRanges []*crimson.IPRange, format FormatType, skipHeader bool) {\n\tlines, err := FormatIPRange(ipRanges, format, skipHeader)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"ERROR: %s\", err)\n\t\treturn\n\t}\n\tfor _, s := range lines {\n\t\tfmt.Println(s)\n\t}\n}",
"func (p *PageMarginRight) getPageMargins(pm *xlsxPageMargins) {\n\t// Excel default: 0.7\n\tif pm == nil || pm.Right == 0 {\n\t\t*p = 0.7\n\t\treturn\n\t}\n\t*p = PageMarginRight(pm.Right)\n}",
"func (e *linodeImagePaginated) pageNumber() int {\n\treturn e.Page\n}",
"func (x *fastReflection_MsgDepositValidatorRewardsPoolResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n}",
"func (p *Pagination) NumPages() uint {\n\treturn maxuint(1, uint(math.Ceil(float64(p.total)/float64(p.PerPage))))\n}",
"func fun4(po *PageOptions, totalpages int64) string {\n\tvar rs = \"\"\n\trs += getHeader(po, totalpages)\n\trs += \"<a href='\" + po.Href + \"&\" + po.ParamName + \"=\" + strconv.Itoa(1) + \"'>\" + strconv.Itoa(1) + \"</a>\"\n\trs += \"<a href=''>...</a>\"\n\tfor i := totalpages - po.LinkItemCount; i <= totalpages; i++ {\n\t\tif po.Currentpage != i {\n\t\t\trs += \"<a href='\" + po.Href + \"&\" + po.ParamName + \"=\" + strconv.Itoa(int(i)) + \"'>\" + strconv.Itoa(int(i)) + \"</a>\"\n\t\t} else {\n\t\t\t//rs += \"<span class=\\\"current\\\">\" + strconv.Itoa(int(i)) + \"</span>\"\n\t\t\t//<span class=\\\"fk\\\"><i class=\\\"pic\\\"></i></span>\n\t\t\trs += \"<strong><span class=\\\"pc\\\">\" + strconv.Itoa(int(i)) + \"</span></strong>\"\n\t\t}\n\t}\n\trs += getFooter(po, totalpages)\n\treturn rs\n\n}",
"func (r *RMFileInfo) InsertedPages() string {\n\treturn r.insertedPages.insertedPageNumbers()\n}",
"func (p *PageMarginLeft) getPageMargins(pm *xlsxPageMargins) {\n\t// Excel default: 0.7\n\tif pm == nil || pm.Left == 0 {\n\t\t*p = 0.7\n\t\treturn\n\t}\n\t*p = PageMarginLeft(pm.Left)\n}",
"func (c *ProjectsLocationsOsPolicyAssignmentsListRevisionsCall) Pages(ctx context.Context, f func(*ListOSPolicyAssignmentRevisionsResponse) error) error {\n\tc.ctx_ = ctx\n\tdefer c.PageToken(c.urlParams_.Get(\"pageToken\")) // reset paging to original point\n\tfor {\n\t\tx, err := c.Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := f(x); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif x.NextPageToken == \"\" {\n\t\t\treturn nil\n\t\t}\n\t\tc.PageToken(x.NextPageToken)\n\t}\n}",
"func getRange(min, max int) int {\n\treturn max * min\n}",
"func (rect *PdfRectangle) ToPdfObject() core.PdfObject {\n\treturn core.MakeArray(\n\t\tcore.MakeFloat(rect.Llx),\n\t\tcore.MakeFloat(rect.Lly),\n\t\tcore.MakeFloat(rect.Urx),\n\t\tcore.MakeFloat(rect.Ury),\n\t)\n}",
"func Page(n int) ListOption {\n\tif n < 0 {\n\t\tn = 1\n\t}\n\treturn pageNumOpt(n)\n}",
"func DrawRangeElements(mode uint32, start uint32, end uint32, count int32, xtype uint32, indices unsafe.Pointer) {\n\tsyscall.Syscall6(gpDrawRangeElements, 6, uintptr(mode), uintptr(start), uintptr(end), uintptr(count), uintptr(xtype), uintptr(indices))\n}",
"func (g *NgGrid) GetPageNumber() int64 {\n\tif g.PageNumber == 0 {\n\t\tg.PageNumber = 1\n\t}\n\treturn g.PageNumber\n}",
"func (e *linodeRegionPaginated) pageNumber() int {\n\treturn e.Page\n}",
"func (p *PdfiumImplementation) FPDFLink_GetRect(request *requests.FPDFLink_GetRect) (*responses.FPDFLink_GetRect, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageLinkhandle, err := p.getPageLinkHandle(request.PageLink)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tleft := C.double(0)\n\ttop := C.double(0)\n\tright := C.double(0)\n\tbottom := C.double(0)\n\n\tsuccess := C.FPDFLink_GetRect(pageLinkhandle.handle, C.int(request.Index), C.int(request.RectIndex), &left, &top, &right, &bottom)\n\tif int(success) == 0 {\n\t\treturn nil, errors.New(\"could not get rect\")\n\t}\n\n\treturn &responses.FPDFLink_GetRect{\n\t\tIndex: request.Index,\n\t\tRectIndex: request.RectIndex,\n\t\tLeft: float64(left),\n\t\tTop: float64(top),\n\t\tRight: float64(right),\n\t\tBottom: float64(bottom),\n\t}, nil\n}",
"func (p *Pagination) Page(total int) (from int, to int) {\n\tif p.Num == 0 {\n\t\tp.Num = 1\n\t}\n\tif p.Size == 0 {\n\t\tp.Size = DefaultSize\n\t}\n\n\tif total == 0 || total < p.Size*(p.Num-1) {\n\t\treturn\n\t}\n\tif total <= p.Size {\n\t\treturn 1, total\n\t}\n\tfrom = (p.Num-1)*p.Size + 1\n\tif (total - from + 1) < p.Size {\n\t\treturn from, total\n\t}\n\treturn from, from + p.Size - 1\n}",
"func (ref *UIElement) RangeForPosition(p Point) Range {\n\ta := cfstr(RangeForPositionParameterizedAttribute)\n\tdefer C.CFRelease(C.CFTypeRef(a))\n\tcfPoint := C.CGPointMake(C.CGFloat(p.X), C.CGFloat(p.Y))\n\taxPointValue := C.AXValueCreate(C.kAXValueTypeCGPoint, unsafe.Pointer(&cfPoint))\n\tdefer C.CFRelease(C.CFTypeRef(axPointValue))\n\tvar value C.CFTypeRef\n\tC.AXUIElementCopyParameterizedAttributeValue(ref.obj, a, axPointValue, &value)\n\tret := convertCFType(value)\n\to, ok := ret.(Range)\n\tif !ok {\n\t\treturn Range{0, 0}\n\t}\n\treturn o\n}",
"func releaseOverflowPages(\n\tlist regionList,\n\tmaxPages uint, endMarker PageID,\n) (regionList, uint) {\n\toverflowStart, overflowEnd := PageID(maxPages), endMarker\n\tif maxPages == 0 || overflowStart >= overflowEnd {\n\t\treturn list, 0\n\t}\n\n\tvar freed uint\n\tfor i := len(list) - 1; i != -1; i-- {\n\t\tstart, end := list[i].Range()\n\t\tif end < overflowEnd {\n\t\t\tbreak\n\t\t}\n\n\t\tif start < overflowStart {\n\t\t\t// split\n\t\t\tlist[i].count = uint32(overflowStart - start)\n\t\t\tfreed += uint(end - overflowStart)\n\t\t\toverflowEnd = overflowStart\n\t\t} else {\n\t\t\t// remove range\n\t\t\toverflowEnd = start\n\t\t\tfreed += uint(list[i].count)\n\t\t\tlist = list[:i]\n\t\t}\n\t}\n\n\tif len(list) == 0 {\n\t\tlist = nil\n\t}\n\treturn list, freed\n}",
"func dumpmemrange(data unsafe.Pointer, len uintptr) {\n\tdumpint(uint64(len))\n\tdwrite(data, len)\n}",
"func allocPDFPageMemory(n int) unsafe.Pointer {\n\tmem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPDFPageValue))\n\tif err != nil {\n\t\tpanic(\"memory alloc error: \" + err.Error())\n\t}\n\treturn mem\n}",
"func getPageInfo(first, last int, pr pageResult) ([]bson.RawValue, core.PageInfo, error) {\n\trvs := pr.Results\n\tvar pi core.PageInfo\n\n\t// Determine whether there is a next page.\n\tif first != 0 && len(rvs) > first {\n\t\tif last <= 0 {\n\t\t\tpi.HasNextPage = true\n\t\t}\n\t\trvs = rvs[:first]\n\t}\n\n\t// Determine whether there is a previous page.\n\tif last != 0 && len(rvs) > last {\n\t\tif first <= 0 {\n\t\t\tpi.HasPreviousPage = true\n\t\t}\n\t\trvs = rvs[len(rvs)-last:]\n\t}\n\n\tif len(rvs) > 0 {\n\t\t// Get cursor value of first result.\n\t\tsc, err := getCursor(rvs[0])\n\t\tif err != nil {\n\t\t\treturn nil, core.PageInfo{}, err\n\t\t}\n\t\tpi.StartCursor = &sc\n\n\t\t// Get cursor value of last result.\n\t\tec, err := getCursor(rvs[len(rvs)-1])\n\t\tif err != nil {\n\t\t\treturn nil, core.PageInfo{}, err\n\t\t}\n\t\tpi.EndCursor = &ec\n\t}\n\n\treturn rvs, pi, nil\n}",
"func (eps *EPS) Bounds() (box image.Rectangle) {\n\t// TODO exploit the z-curve to do better and/or cache/pre-compute\n\tit := eps.Iter()\n\tfor it.Next() {\n\t\tif i := it.ID() - 1; eps.ix.flg[i]&epsDef != 0 {\n\t\t\tbox.Min = eps.pt[i]\n\t\t\tbox.Max = box.Min.Add(image.Pt(1, 1))\n\t\t\tbreak\n\t\t}\n\t}\n\tfor it.Next() {\n\t\tif i := it.ID() - 1; eps.ix.flg[i]&epsDef != 0 {\n\t\t\tbox = rectangle.Capture(box, eps.pt[i])\n\t\t}\n\t}\n\treturn box\n}",
"func (e *stackScriptPaginated) pageNumber() int {\n\treturn e.Page\n}",
"func (p Page) Len() int { return len(p) }",
"func (p *PageMarginBottom) getPageMargins(pm *xlsxPageMargins) {\n\t// Excel default: 0.75\n\tif pm == nil || pm.Bottom == 0 {\n\t\t*p = 0.75\n\t\treturn\n\t}\n\t*p = PageMarginBottom(pm.Bottom)\n}",
"func NUpFromPDF(ctx *model.Context, selectedPages types.IntSet, nup *model.NUp) error {\n\tvar mb *types.Rectangle\n\tif nup.PageDim == nil {\n\t\t// No page dimensions specified, use cropBox of page 1 as mediaBox(=cropBox).\n\t\tconsolidateRes := false\n\t\td, _, inhPAttrs, err := ctx.PageDict(1, consolidateRes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif d == nil {\n\t\t\treturn errors.Errorf(\"unknown page number: %d\\n\", 1)\n\t\t}\n\n\t\tcropBox := inhPAttrs.MediaBox\n\t\tif inhPAttrs.CropBox != nil {\n\t\t\tcropBox = inhPAttrs.CropBox\n\t\t}\n\n\t\t// Account for existing rotation.\n\t\tif inhPAttrs.Rotate != 0 {\n\t\t\tif types.IntMemberOf(inhPAttrs.Rotate, []int{+90, -90, +270, -270}) {\n\t\t\t\tw := cropBox.Width()\n\t\t\t\tcropBox.UR.X = cropBox.LL.X + cropBox.Height()\n\t\t\t\tcropBox.UR.Y = cropBox.LL.Y + w\n\t\t\t}\n\t\t}\n\n\t\tmb = cropBox\n\t} else {\n\t\tmb = types.RectForDim(nup.PageDim.Width, nup.PageDim.Height)\n\t}\n\n\tif nup.PageGrid {\n\t\tmb.UR.X = mb.LL.X + float64(nup.Grid.Width)*mb.Width()\n\t\tmb.UR.Y = mb.LL.Y + float64(nup.Grid.Height)*mb.Height()\n\t}\n\n\tpagesDict := types.Dict(\n\t\tmap[string]types.Object{\n\t\t\t\"Type\": types.Name(\"Pages\"),\n\t\t\t\"Count\": types.Integer(0),\n\t\t\t\"MediaBox\": mb.Array(),\n\t\t},\n\t)\n\n\tpagesIndRef, err := ctx.IndRefForNewObject(pagesDict)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnup.PageDim = &types.Dim{Width: mb.Width(), Height: mb.Height()}\n\n\tif err = nupPages(ctx, selectedPages, nup, pagesDict, pagesIndRef); err != nil {\n\t\treturn err\n\t}\n\n\t// Replace original pagesDict.\n\trootDict, err := ctx.Catalog()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trootDict.Update(\"Pages\", *pagesIndRef)\n\n\treturn nil\n}",
"func (l *Libvirt) NodeAllocPages(PageSizes []uint32, PageCounts []uint64, StartCell int32, CellCount uint32, Flags NodeAllocPagesFlags) (rRet int32, err error) {\n\tvar buf []byte\n\n\targs := NodeAllocPagesArgs {\n\t\tPageSizes: PageSizes,\n\t\tPageCounts: PageCounts,\n\t\tStartCell: StartCell,\n\t\tCellCount: CellCount,\n\t\tFlags: Flags,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar r response\n\tr, err = l.requestStream(347, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Ret: int32\n\t_, err = dec.Decode(&rRet)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}",
"func (obj *Global) GetSupportedCodePagesRaw(ctx context.Context) (json.RawMessage, error) {\n\tresult := &struct {\n\t\tCodePages json.RawMessage `json:\"qCodePages\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetSupportedCodePages\", result)\n\treturn result.CodePages, err\n}",
"func pageOffset(pos, pageSize int64) int64 {\n\trem := pos % pageSize\n\tif rem != 0 {\n\t\treturn pos - rem\n\t}\n\treturn pos\n}",
"func pageOffset(pos, pageSize int64) int64 {\n\trem := pos % pageSize\n\tif rem != 0 {\n\t\treturn pos - rem\n\t}\n\treturn pos\n}"
] | [
"0.58847",
"0.51974595",
"0.5171531",
"0.506692",
"0.5052536",
"0.5038135",
"0.5016974",
"0.48983243",
"0.4861181",
"0.48284626",
"0.4810458",
"0.4792606",
"0.47350785",
"0.4689154",
"0.46735016",
"0.4640726",
"0.46318024",
"0.46059665",
"0.45694393",
"0.45591092",
"0.45568103",
"0.4539482",
"0.4532114",
"0.45074174",
"0.45047548",
"0.44780543",
"0.44233605",
"0.44073468",
"0.44039214",
"0.43577272",
"0.4333161",
"0.43114862",
"0.43064317",
"0.42838556",
"0.42647284",
"0.42569548",
"0.4245741",
"0.42318818",
"0.4223672",
"0.41905653",
"0.41835144",
"0.41773683",
"0.4176197",
"0.4172686",
"0.41627166",
"0.41620284",
"0.41603246",
"0.41569132",
"0.41470724",
"0.41430968",
"0.4141599",
"0.4140221",
"0.41266972",
"0.41196218",
"0.41192606",
"0.41118017",
"0.41096112",
"0.41041073",
"0.40941074",
"0.40634754",
"0.4054803",
"0.40492114",
"0.40485507",
"0.4044025",
"0.4040639",
"0.40236232",
"0.40232965",
"0.4017608",
"0.40077513",
"0.40054625",
"0.4004652",
"0.40018192",
"0.39944357",
"0.3989068",
"0.39834386",
"0.39827928",
"0.39801073",
"0.39755407",
"0.39740467",
"0.3972218",
"0.39635164",
"0.394902",
"0.39457297",
"0.394543",
"0.39398596",
"0.39392608",
"0.39380404",
"0.39378005",
"0.39253405",
"0.39247143",
"0.3917791",
"0.39158276",
"0.3915408",
"0.39110568",
"0.3909362",
"0.3898218",
"0.38974938",
"0.38920167",
"0.3889195",
"0.3889195"
] | 0.75883263 | 0 |
FPDF_VIEWERREF_GetDuplex returns the paper handling option to be used when printing from the print dialog. | func (p *PdfiumImplementation) FPDF_VIEWERREF_GetDuplex(request *requests.FPDF_VIEWERREF_GetDuplex) (*responses.FPDF_VIEWERREF_GetDuplex, error) {
p.Lock()
defer p.Unlock()
documentHandle, err := p.getDocumentHandle(request.Document)
if err != nil {
return nil, err
}
duplexType := C.FPDF_VIEWERREF_GetDuplex(documentHandle.handle)
return &responses.FPDF_VIEWERREF_GetDuplex{
DuplexType: enums.FPDF_DUPLEXTYPE(duplexType),
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (m *PrinterDefaults) GetDuplexMode()(*PrintDuplexMode) {\n val, err := m.GetBackingStore().Get(\"duplexMode\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*PrintDuplexMode)\n }\n return nil\n}",
"func (p *PdfiumImplementation) FPDF_VIEWERREF_GetPrintScaling(request *requests.FPDF_VIEWERREF_GetPrintScaling) (*responses.FPDF_VIEWERREF_GetPrintScaling, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprintScaling := C.FPDF_VIEWERREF_GetPrintScaling(documentHandle.handle)\n\treturn &responses.FPDF_VIEWERREF_GetPrintScaling{\n\t\tPreferPrintScaling: int(printScaling) == 1,\n\t}, nil\n}",
"func (m *PrinterDefaults) SetDuplexMode(value *PrintDuplexMode)() {\n err := m.GetBackingStore().Set(\"duplexMode\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (x *PDFWriteOptions) Ref() *C.pdf_write_options {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_write_options)(unsafe.Pointer(x))\n}",
"func (p *PdfiumImplementation) FPDF_VIEWERREF_GetPrintPageRange(request *requests.FPDF_VIEWERREF_GetPrintPageRange) (*responses.FPDF_VIEWERREF_GetPrintPageRange, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpageRange := C.FPDF_VIEWERREF_GetPrintPageRange(documentHandle.handle)\n\tpageRangeHandle := p.registerPageRange(pageRange, documentHandle)\n\n\treturn &responses.FPDF_VIEWERREF_GetPrintPageRange{\n\t\tPageRange: pageRangeHandle.nativeRef,\n\t}, nil\n}",
"func (o *Published) getSheetPrOption(pr *xlsxSheetPr) {\n\tif pr == nil {\n\t\t*o = true\n\t\treturn\n\t}\n\t*o = Published(defaultTrue(pr.Published))\n}",
"func (x *PDFWriteOptions) PassRef() *C.pdf_write_options {\n\tif x == nil {\n\t\tx = (*PDFWriteOptions)(allocPDFWriteOptionsMemory(1))\n\t}\n\treturn (*C.pdf_write_options)(unsafe.Pointer(x))\n}",
"func (o *EnableFormatConditionsCalculation) getSheetPrOption(pr *xlsxSheetPr) {\n\tif pr == nil {\n\t\t*o = true\n\t\treturn\n\t}\n\t*o = EnableFormatConditionsCalculation(defaultTrue(pr.EnableFormatConditionsCalculation))\n}",
"func (processor *Processor) GetPaper(paperID string) (model.Paper, error) {\n\tgo func() {\n\t\tprocessor.gotPaper <- paperID\n\t}()\n\n\tpaper := <-processor.paper\n\tif paper == nil {\n\t\treturn nil, internal.ErrNotFound\n\t}\n\treturn paper, nil\n}",
"func (x *FzDrawOptions) Ref() *C.fz_draw_options {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.fz_draw_options)(unsafe.Pointer(x))\n}",
"func (x *FzPwgOptions) Ref() *C.fz_pwg_options {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.fz_pwg_options)(unsafe.Pointer(x))\n}",
"func (o *AutoPageBreaks) getSheetPrOption(pr *xlsxSheetPr) {\n\t// Excel default: false\n\tif pr == nil || pr.PageSetUpPr == nil {\n\t\t*o = false\n\t\treturn\n\t}\n\t*o = AutoPageBreaks(pr.PageSetUpPr.AutoPageBreaks)\n}",
"func (x *PDFPattern) Ref() *C.pdf_pattern {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_pattern)(unsafe.Pointer(x))\n}",
"func (x *PDFDesignatedName) PassRef() *C.pdf_designated_name {\n\tif x == nil {\n\t\tx = (*PDFDesignatedName)(allocPDFDesignatedNameMemory(1))\n\t}\n\treturn (*C.pdf_designated_name)(unsafe.Pointer(x))\n}",
"func (x *FzPclOptions) Ref() *C.fz_pcl_options {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.fz_pcl_options)(unsafe.Pointer(x))\n}",
"func (x *PDFDesignatedName) Ref() *C.pdf_designated_name {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_designated_name)(unsafe.Pointer(x))\n}",
"func (x *PDFPortfolioSchema) PassRef() *C.pdf_portfolio_schema {\n\tif x == nil {\n\t\tx = (*PDFPortfolioSchema)(allocPDFPortfolioSchemaMemory(1))\n\t}\n\treturn (*C.pdf_portfolio_schema)(unsafe.Pointer(x))\n}",
"func (x *PDFPattern) PassRef() *C.pdf_pattern {\n\tif x == nil {\n\t\tx = (*PDFPattern)(allocPDFPatternMemory(1))\n\t}\n\treturn (*C.pdf_pattern)(unsafe.Pointer(x))\n}",
"func (o SecurityPolicyRuleOutput) Preview() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v SecurityPolicyRule) *bool { return v.Preview }).(pulumi.BoolPtrOutput)\n}",
"func (x *FzDrawOptions) PassRef() *C.fz_draw_options {\n\tif x == nil {\n\t\tx = (*FzDrawOptions)(allocFzDrawOptionsMemory(1))\n\t}\n\treturn (*C.fz_draw_options)(unsafe.Pointer(x))\n}",
"func (x *FzPclOptions) PassRef() *C.fz_pcl_options {\n\tif x == nil {\n\t\tx = (*FzPclOptions)(allocFzPclOptionsMemory(1))\n\t}\n\treturn (*C.fz_pcl_options)(unsafe.Pointer(x))\n}",
"func (o *FitToPage) getSheetPrOption(pr *xlsxSheetPr) {\n\t// Excel default: false\n\tif pr == nil || pr.PageSetUpPr == nil {\n\t\t*o = false\n\t\treturn\n\t}\n\t*o = FitToPage(pr.PageSetUpPr.FitToPage)\n}",
"func (x *PDFProcessor) PassRef() *C.pdf_processor {\n\tif x == nil {\n\t\tx = (*PDFProcessor)(allocPDFProcessorMemory(1))\n\t}\n\treturn (*C.pdf_processor)(unsafe.Pointer(x))\n}",
"func (x *PDFLayerConfigUi) PassRef() *C.pdf_layer_config_ui {\n\tif x == nil {\n\t\tx = (*PDFLayerConfigUi)(allocPDFLayerConfigUiMemory(1))\n\t}\n\treturn (*C.pdf_layer_config_ui)(unsafe.Pointer(x))\n}",
"func (p *PdfiumImplementation) FPDF_VIEWERREF_GetNumCopies(request *requests.FPDF_VIEWERREF_GetNumCopies) (*responses.FPDF_VIEWERREF_GetNumCopies, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnumCopies := C.FPDF_VIEWERREF_GetNumCopies(documentHandle.handle)\n\treturn &responses.FPDF_VIEWERREF_GetNumCopies{\n\t\tNumCopies: int(numCopies),\n\t}, nil\n}",
"func (x *PDFLayerConfig) Ref() *C.pdf_layer_config {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_layer_config)(unsafe.Pointer(x))\n}",
"func (x *PDFProcessor) Ref() *C.pdf_processor {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_processor)(unsafe.Pointer(x))\n}",
"func (m *PrinterCreateOperation) GetPrinter()(Printerable) {\n return m.printer\n}",
"func (m *PrinterDefaults) GetFitPdfToPage()(*bool) {\n val, err := m.GetBackingStore().Get(\"fitPdfToPage\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}",
"func (x *PDFWidget) PassRef() *C.pdf_widget {\n\tif x == nil {\n\t\tx = (*PDFWidget)(allocPDFWidgetMemory(1))\n\t}\n\treturn (*C.pdf_widget)(unsafe.Pointer(x))\n}",
"func (x *PDFPortfolio) PassRef() *C.pdf_portfolio {\n\tif x == nil {\n\t\tx = (*PDFPortfolio)(allocPDFPortfolioMemory(1))\n\t}\n\treturn (*C.pdf_portfolio)(unsafe.Pointer(x))\n}",
"func (o Published) setSheetPrOption(pr *xlsxSheetPr) {\n\tpr.Published = boolPtr(bool(o))\n}",
"func NewPDFWriteOptionsRef(ref unsafe.Pointer) *PDFWriteOptions {\n\treturn (*PDFWriteOptions)(ref)\n}",
"func NewPDFProcessorRef(ref unsafe.Pointer) *PDFProcessor {\n\treturn (*PDFProcessor)(ref)\n}",
"func (x *FzPwgOptions) PassRef() *C.fz_pwg_options {\n\tif x == nil {\n\t\tx = (*FzPwgOptions)(allocFzPwgOptionsMemory(1))\n\t}\n\treturn (*C.fz_pwg_options)(unsafe.Pointer(x))\n}",
"func (x *PDFLayerConfig) PassRef() *C.pdf_layer_config {\n\tif x == nil {\n\t\tx = (*PDFLayerConfig)(allocPDFLayerConfigMemory(1))\n\t}\n\treturn (*C.pdf_layer_config)(unsafe.Pointer(x))\n}",
"func (x *PDFLayerConfigUi) Ref() *C.pdf_layer_config_ui {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_layer_config_ui)(unsafe.Pointer(x))\n}",
"func (o JobSpecPtrOutput) ManualSelector() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v JobSpec) *bool { return v.ManualSelector }).(pulumi.BoolPtrOutput)\n}",
"func (x *PDFOcgDescriptor) PassRef() *C.pdf_ocg_descriptor {\n\tif x == nil {\n\t\tx = (*PDFOcgDescriptor)(allocPDFOcgDescriptorMemory(1))\n\t}\n\treturn (*C.pdf_ocg_descriptor)(unsafe.Pointer(x))\n}",
"func (x *PDFPortfolioSchema) Ref() *C.pdf_portfolio_schema {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_portfolio_schema)(unsafe.Pointer(x))\n}",
"func FIPSEnabled() bool { return true }",
"func (o *EditorPlugin) SetForceDrawOverForwardingEnabled() {\n\t//log.Println(\"Calling EditorPlugin.SetForceDrawOverForwardingEnabled()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"EditorPlugin\", \"set_force_draw_over_forwarding_enabled\")\n\n\t// Call the parent method.\n\t// void\n\tretPtr := gdnative.NewEmptyVoid()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n}",
"func (o *OutlineSummaryBelow) getSheetPrOption(pr *xlsxSheetPr) {\n\t// Excel default: true\n\tif pr == nil || pr.OutlinePr == nil {\n\t\t*o = true\n\t\treturn\n\t}\n\t*o = OutlineSummaryBelow(defaultTrue(&pr.OutlinePr.SummaryBelow))\n}",
"func ReportPrinter(w io.Writer, minPriority int8, colors bool) func(r reports.Report) error {\n\tvar pal *palette\n\tif colors {\n\t\tpal = &colored\n\t} else {\n\t\tpal = ¬colored\n\t}\n\n\tif w == nil {\n\t\tw = os.Stdout\n\t}\n\n\treturn func(r reports.Report) error {\n\t\tprintReport(r, w, minPriority, pal)\n\t\treturn nil\n\t}\n}",
"func (e E_OpenconfigInterfaces_Interfaces_Interface_Ethernet_Config_DuplexMode) String() string {\n\treturn ygot.EnumLogString(e, int64(e), \"E_OpenconfigInterfaces_Interfaces_Interface_Ethernet_Config_DuplexMode\")\n}",
"func (m *PrinterCreateOperation) GetPrinter()(Printerable) {\n val, err := m.GetBackingStore().Get(\"printer\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(Printerable)\n }\n return nil\n}",
"func (o *PostWebhook) GetPrReopened() bool {\n\tif o == nil || o.PrReopened == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\treturn *o.PrReopened\n}",
"func (o JobSpecOutput) ManualSelector() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v JobSpec) *bool { return v.ManualSelector }).(pulumi.BoolPtrOutput)\n}",
"func (x *PDFPortfolio) Ref() *C.pdf_portfolio {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_portfolio)(unsafe.Pointer(x))\n}",
"func (x *PDFDocument) PassRef() *C.pdf_document {\n\tif x == nil {\n\t\tx = (*PDFDocument)(allocPDFDocumentMemory(1))\n\t}\n\treturn (*C.pdf_document)(unsafe.Pointer(x))\n}",
"func Ref(name string) *Pattern {\n\treturn Seq(\n\t\t&IOpenCall{name},\n\t)\n}",
"func (x *FzDocumentHandler) PassRef() *C.fz_document_handler {\n\tif x == nil {\n\t\tx = (*FzDocumentHandler)(allocFzDocumentHandlerMemory(1))\n\t}\n\treturn (*C.fz_document_handler)(unsafe.Pointer(x))\n}",
"func (x *PDFFunction) PassRef() *C.pdf_function {\n\tif x == nil {\n\t\tx = (*PDFFunction)(allocPDFFunctionMemory(1))\n\t}\n\treturn (*C.pdf_function)(unsafe.Pointer(x))\n}",
"func (m *PrintJobStatus) GetIsAcquiredByPrinter()(*bool) {\n return m.isAcquiredByPrinter\n}",
"func (x *PDFObj) PassRef() *C.pdf_obj {\n\tif x == nil {\n\t\tx = (*PDFObj)(allocPDFObjMemory(1))\n\t}\n\treturn (*C.pdf_obj)(unsafe.Pointer(x))\n}",
"func (x *FzBandWriter) Ref() *C.fz_band_writer {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.fz_band_writer)(unsafe.Pointer(x))\n}",
"func (mod Chromium) PDF(ctx context.Context, logger *zap.Logger, URL, outputPath string, options Options) error {\n\tdebug := debugLogger{logger: logger.Named(\"browser\")}\n\tuserProfileDirPath := gotenberg.NewDirPath()\n\n\targs := append(chromedp.DefaultExecAllocatorOptions[:],\n\t\tchromedp.CombinedOutput(debug),\n\t\tchromedp.ExecPath(mod.binPath),\n\t\tchromedp.NoSandbox,\n\t\t// See:\n\t\t// https://github.com/gotenberg/gotenberg/issues/327\n\t\t// https://github.com/chromedp/chromedp/issues/904\n\t\tchromedp.DisableGPU,\n\t\t// See:\n\t\t// https://github.com/puppeteer/puppeteer/issues/661\n\t\t// https://github.com/puppeteer/puppeteer/issues/2410\n\t\tchromedp.Flag(\"font-render-hinting\", \"none\"),\n\t\tchromedp.UserDataDir(userProfileDirPath),\n\t)\n\n\tif mod.userAgent != \"\" && options.UserAgent == \"\" {\n\t\t// Deprecated.\n\t\targs = append(args, chromedp.UserAgent(mod.userAgent))\n\t}\n\n\tif mod.incognito {\n\t\targs = append(args, chromedp.Flag(\"incognito\", mod.incognito))\n\t}\n\n\tif mod.allowInsecureLocalhost {\n\t\t// See https://github.com/gotenberg/gotenberg/issues/488.\n\t\targs = append(args, chromedp.Flag(\"allow-insecure-localhost\", true))\n\t}\n\n\tif mod.ignoreCertificateErrors {\n\t\targs = append(args, chromedp.IgnoreCertErrors)\n\t}\n\n\tif mod.disableWebSecurity {\n\t\targs = append(args, chromedp.Flag(\"disable-web-security\", true))\n\t}\n\n\tif mod.allowFileAccessFromFiles {\n\t\t// See https://github.com/gotenberg/gotenberg/issues/356.\n\t\targs = append(args, chromedp.Flag(\"allow-file-access-from-files\", true))\n\t}\n\n\tif mod.hostResolverRules != \"\" {\n\t\t// See https://github.com/gotenberg/gotenberg/issues/488.\n\t\targs = append(args, chromedp.Flag(\"host-resolver-rules\", mod.hostResolverRules))\n\t}\n\n\tif mod.proxyServer != \"\" {\n\t\t// See https://github.com/gotenberg/gotenberg/issues/376.\n\t\targs = append(args, chromedp.ProxyServer(mod.proxyServer))\n\t}\n\n\tif options.UserAgent != \"\" {\n\t\targs = append(args, chromedp.UserAgent(options.UserAgent))\n\t}\n\n\t// See https://github.com/gotenberg/gotenberg/issues/524.\n\tdeadline, ok := ctx.Deadline()\n\tif !ok {\n\t\treturn errors.New(\"context has no deadline\")\n\t}\n\n\targs = append(args, chromedp.WSURLReadTimeout(time.Until(deadline)))\n\n\tallocatorCtx, cancel := chromedp.NewExecAllocator(ctx, args...)\n\tdefer cancel()\n\n\ttaskCtx, cancel := chromedp.NewContext(allocatorCtx,\n\t\tchromedp.WithDebugf(debug.Printf),\n\t)\n\tdefer cancel()\n\n\t// We validate the \"main\" URL against our allow / deny lists.\n\tif !mod.allowList.MatchString(URL) {\n\t\treturn fmt.Errorf(\"'%s' does not match the expression from the allowed list: %w\", URL, ErrURLNotAuthorized)\n\t}\n\n\tif mod.denyList.String() != \"\" && mod.denyList.MatchString(URL) {\n\t\treturn fmt.Errorf(\"'%s' matches the expression from the denied list: %w\", URL, ErrURLNotAuthorized)\n\t}\n\n\tvar (\n\t\tconsoleExceptions error\n\t\tconsoleExceptionsMu sync.RWMutex\n\t)\n\n\tprintToPDF := func(URL string, options Options, outputPath string) chromedp.Tasks {\n\t\t// We validate the underlying requests against our allow / deny lists.\n\t\t// If a request does not pass the validation, we make it fail.\n\t\tlistenForEventRequestPaused(taskCtx, logger, mod.allowList, mod.denyList)\n\n\t\t// See https://github.com/gotenberg/gotenberg/issues/262.\n\t\tif options.FailOnConsoleExceptions && !mod.disableJavaScript {\n\t\t\tlistenForEventExceptionThrown(taskCtx, logger, &consoleExceptions, &consoleExceptionsMu)\n\t\t}\n\n\t\treturn chromedp.Tasks{\n\t\t\tnetwork.Enable(),\n\t\t\tfetch.Enable(),\n\t\t\truntime.Enable(),\n\t\t\tchromedp.ActionFunc(func(ctx context.Context) error {\n\t\t\t\t// See https://github.com/gotenberg/gotenberg/issues/175.\n\t\t\t\tif !mod.disableJavaScript {\n\t\t\t\t\tlogger.Debug(\"JavaScript not disabled\")\n\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tlogger.Debug(\"disable JavaScript\")\n\n\t\t\t\terr := emulation.SetScriptExecutionDisabled(true).Do(ctx)\n\t\t\t\tif err == nil {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\treturn fmt.Errorf(\"disable JavaScript: %w\", err)\n\t\t\t}),\n\t\t\tchromedp.ActionFunc(func(ctx context.Context) error {\n\t\t\t\tif len(options.ExtraHTTPHeaders) == 0 {\n\t\t\t\t\tlogger.Debug(\"no extra HTTP headers\")\n\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tlogger.Debug(fmt.Sprintf(\"extra HTTP headers: %+v\", options.ExtraHTTPHeaders))\n\n\t\t\t\theaders := make(network.Headers, len(options.ExtraHTTPHeaders))\n\t\t\t\tfor key, value := range options.ExtraHTTPHeaders {\n\t\t\t\t\theaders[key] = value\n\t\t\t\t}\n\n\t\t\t\terr := network.SetExtraHTTPHeaders(headers).Do(ctx)\n\t\t\t\tif err == nil {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\treturn fmt.Errorf(\"set extra HTTP headers: %w\", err)\n\t\t\t}),\n\t\t\tchromedp.ActionFunc(func(ctx context.Context) error {\n\t\t\t\tlogger.Debug(fmt.Sprintf(\"navigate to '%s'\", URL))\n\n\t\t\t\t_, _, _, err := page.Navigate(URL).Do(ctx)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"navigate to '%s': %w\", URL, err)\n\t\t\t\t}\n\n\t\t\t\terr = runBatch(\n\t\t\t\t\tctx,\n\t\t\t\t\twaitForEventDomContentEventFired(ctx, logger),\n\t\t\t\t\twaitForEventLoadEventFired(ctx, logger),\n\t\t\t\t\twaitForEventNetworkIdle(ctx, logger),\n\t\t\t\t\twaitForEventLoadingFinished(ctx, logger),\n\t\t\t\t)\n\n\t\t\t\tif err == nil {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\treturn fmt.Errorf(\"wait for events: %w\", err)\n\t\t\t}),\n\t\t\tchromedp.ActionFunc(func(ctx context.Context) error {\n\t\t\t\t// See https://github.com/gotenberg/gotenberg/issues/226.\n\t\t\t\tif !options.OmitBackground {\n\t\t\t\t\tlogger.Debug(\"default white background not hidden\")\n\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tif !options.PrintBackground {\n\t\t\t\t\t// See https://github.com/chromedp/chromedp/issues/1179#issuecomment-1284794416.\n\t\t\t\t\treturn fmt.Errorf(\"validate omit background: %w\", ErrOmitBackgroundWithoutPrintBackground)\n\t\t\t\t}\n\n\t\t\t\tlogger.Debug(\"hide default white background\")\n\n\t\t\t\terr := emulation.SetDefaultBackgroundColorOverride().WithColor(\n\t\t\t\t\t&cdp.RGBA{\n\t\t\t\t\t\tR: 0,\n\t\t\t\t\t\tG: 0,\n\t\t\t\t\t\tB: 0,\n\t\t\t\t\t\tA: 0,\n\t\t\t\t\t}).Do(ctx)\n\n\t\t\t\tif err == nil {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\treturn fmt.Errorf(\"hide default white background: %w\", err)\n\t\t\t}),\n\t\t\tchromedp.ActionFunc(func(ctx context.Context) error {\n\t\t\t\t// See:\n\t\t\t\t// https://github.com/gotenberg/gotenberg/issues/354\n\t\t\t\t// https://github.com/puppeteer/puppeteer/issues/2685\n\t\t\t\t// https://github.com/chromedp/chromedp/issues/520\n\t\t\t\tscript := `\n(() => {\n\tconst css = 'html { -webkit-print-color-adjust: exact !important; }';\n\n\tconst style = document.createElement('style');\n\tstyle.type = 'text/css';\n\tstyle.appendChild(document.createTextNode(css));\n\tdocument.head.appendChild(style);\n})();\n`\n\n\t\t\t\tevaluate := chromedp.Evaluate(script, nil)\n\t\t\t\terr := evaluate.Do(ctx)\n\n\t\t\t\tif err == nil {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\treturn fmt.Errorf(\"add CSS for exact colors: %w\", err)\n\t\t\t}),\n\t\t\tchromedp.ActionFunc(func(ctx context.Context) error {\n\t\t\t\tif len(options.ExtraLinkTags) == 0 {\n\t\t\t\t\tlogger.Debug(\"no extra link tags\")\n\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tlogger.Debug(fmt.Sprintf(\"extra link tags: %+v\", options.ExtraLinkTags))\n\n\t\t\t\taddLinkTag := func(i int, linkTag LinkTag) func() error {\n\t\t\t\t\treturn func() error {\n\t\t\t\t\t\tscript := `\n(() => {\n\tconst link = document.createElement('link');\n\tlink.href = '%s';\n\tlink.rel = 'stylesheet'\n\tdocument.head.appendChild(link);\n})();\n`\n\n\t\t\t\t\t\tevaluate := chromedp.Evaluate(fmt.Sprintf(script, linkTag.Href), nil)\n\t\t\t\t\t\terr := evaluate.Do(ctx)\n\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn fmt.Errorf(\"add extra link tag %d: %w\", i, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\teg, _ := errgroup.WithContext(ctx)\n\n\t\t\t\tfor i, linkTag := range options.ExtraLinkTags {\n\t\t\t\t\teg.Go(addLinkTag(i, linkTag))\n\t\t\t\t}\n\n\t\t\t\terr := eg.Wait()\n\t\t\t\tif err == nil {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\treturn fmt.Errorf(\"add extra link tags: %w\", err)\n\t\t\t}),\n\t\t\tchromedp.ActionFunc(func(ctx context.Context) error {\n\t\t\t\tif options.EmulatedMediaType == \"\" {\n\t\t\t\t\tlogger.Debug(\"no emulated media type\")\n\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tif options.EmulatedMediaType != \"screen\" && options.EmulatedMediaType != \"print\" {\n\t\t\t\t\treturn fmt.Errorf(\"validate emulated media type '%s': %w\", options.EmulatedMediaType, ErrInvalidEmulatedMediaType)\n\t\t\t\t}\n\n\t\t\t\tlogger.Debug(fmt.Sprintf(\"emulate media type '%s'\", options.EmulatedMediaType))\n\n\t\t\t\temulatedMedia := emulation.SetEmulatedMedia()\n\n\t\t\t\terr := emulatedMedia.WithMedia(options.EmulatedMediaType).Do(ctx)\n\t\t\t\tif err == nil {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\treturn fmt.Errorf(\"emulate media type '%s': %w\", options.EmulatedMediaType, err)\n\t\t\t}),\n\t\t\tchromedp.ActionFunc(func(ctx context.Context) error {\n\t\t\t\tif mod.disableJavaScript {\n\t\t\t\t\tlogger.Debug(\"JavaScript disabled, skipping extra script tags\")\n\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tif len(options.ExtraScriptTags) == 0 {\n\t\t\t\t\tlogger.Debug(\"no extra script tags\")\n\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tlogger.Debug(fmt.Sprintf(\"extra script tags: %+v\", options.ExtraScriptTags))\n\n\t\t\t\taddScriptTag := func(i int, scriptTag ScriptTag) func() error {\n\t\t\t\t\treturn func() error {\n\t\t\t\t\t\tscript := `\n(() => {\n\tconst script = document.createElement('script');\n\tscript.src = '%s';\n\tdocument.head.appendChild(script);\n})();\n`\n\n\t\t\t\t\t\tevaluate := chromedp.Evaluate(fmt.Sprintf(script, scriptTag.Src), nil)\n\t\t\t\t\t\terr := evaluate.Do(ctx)\n\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn fmt.Errorf(\"add extra script tag %d: %w\", i, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\teg, _ := errgroup.WithContext(ctx)\n\n\t\t\t\tfor i, scriptTag := range options.ExtraScriptTags {\n\t\t\t\t\teg.Go(addScriptTag(i, scriptTag))\n\t\t\t\t}\n\n\t\t\t\terr := eg.Wait()\n\t\t\t\tif err == nil {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\treturn fmt.Errorf(\"add extra script tags: %w\", err)\n\t\t\t}),\n\t\t\tchromedp.ActionFunc(func(ctx context.Context) error {\n\t\t\t\tif mod.disableJavaScript {\n\t\t\t\t\tlogger.Debug(\"JavaScript disabled, skipping wait delay\")\n\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tif options.WaitDelay <= 0 {\n\t\t\t\t\tlogger.Debug(\"no wait delay\")\n\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\t// We wait for a given amount of time so that JavaScript\n\t\t\t\t// scripts have a chance to finish before printing the page\n\t\t\t\t// to PDF.\n\t\t\t\tlogger.Debug(fmt.Sprintf(\"wait '%s' before print\", options.WaitDelay))\n\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn fmt.Errorf(\"wait delay: %w\", ctx.Err())\n\t\t\t\tcase <-time.After(options.WaitDelay):\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}),\n\t\t\tchromedp.ActionFunc(func(ctx context.Context) error {\n\t\t\t\tif mod.disableJavaScript {\n\t\t\t\t\tlogger.Debug(\"JavaScript disabled, skipping wait for window status / wait for expression\")\n\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tif options.WaitWindowStatus == \"\" && options.WaitForExpression == \"\" {\n\t\t\t\t\tlogger.Debug(\"no wait for window status nor wait for expression\")\n\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tevaluate := func(expression string) error {\n\t\t\t\t\t// We wait until the evaluation of the expression is true or\n\t\t\t\t\t// until the context is done.\n\t\t\t\t\tlogger.Debug(fmt.Sprintf(\"wait until '%s' is true before print\", expression))\n\n\t\t\t\t\tticker := time.NewTicker(time.Duration(100) * time.Millisecond)\n\n\t\t\t\t\tfor {\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t\t\tticker.Stop()\n\n\t\t\t\t\t\t\treturn fmt.Errorf(\"context done while evaluating '%s': %w\", expression, ctx.Err())\n\t\t\t\t\t\tcase <-ticker.C:\n\t\t\t\t\t\t\tvar ok bool\n\n\t\t\t\t\t\t\tevaluate := chromedp.Evaluate(expression, &ok)\n\t\t\t\t\t\t\terr := evaluate.Do(ctx)\n\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\treturn fmt.Errorf(\"evaluate: %v: %w\", err, ErrInvalidEvaluationExpression)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ok {\n\t\t\t\t\t\t\t\tticker.Stop()\n\n\t\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif options.WaitWindowStatus != \"\" {\n\t\t\t\t\tlogger.Warn(\"option 'WaitWindowStatus' is deprecated; prefer 'WaitForExpression' instead\")\n\n\t\t\t\t\terr := evaluate(fmt.Sprintf(\"window.status === '%s'\", options.WaitWindowStatus))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"wait for window.status === '%s': %w\", options.WaitWindowStatus, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif options.WaitForExpression != \"\" {\n\t\t\t\t\terr := evaluate(options.WaitForExpression)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"wait for expression '%s': %w\", options.WaitForExpression, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}),\n\t\t\tchromedp.ActionFunc(func(ctx context.Context) error {\n\t\t\t\tprintToPDF := page.PrintToPDF().\n\t\t\t\t\tWithTransferMode(page.PrintToPDFTransferModeReturnAsStream).\n\t\t\t\t\tWithLandscape(options.Landscape).\n\t\t\t\t\tWithPrintBackground(options.PrintBackground).\n\t\t\t\t\tWithScale(options.Scale).\n\t\t\t\t\tWithPaperWidth(options.PaperWidth).\n\t\t\t\t\tWithPaperHeight(options.PaperHeight).\n\t\t\t\t\tWithMarginTop(options.MarginTop).\n\t\t\t\t\tWithMarginBottom(options.MarginBottom).\n\t\t\t\t\tWithMarginLeft(options.MarginLeft).\n\t\t\t\t\tWithMarginRight(options.MarginRight).\n\t\t\t\t\tWithPageRanges(options.PageRanges).\n\t\t\t\t\tWithPreferCSSPageSize(options.PreferCSSPageSize)\n\n\t\t\t\thasCustomHeaderFooter := options.HeaderTemplate != DefaultOptions().HeaderTemplate ||\n\t\t\t\t\toptions.FooterTemplate != DefaultOptions().FooterTemplate\n\n\t\t\t\tif !hasCustomHeaderFooter {\n\t\t\t\t\tlogger.Debug(\"no custom header nor footer\")\n\n\t\t\t\t\tprintToPDF = printToPDF.WithDisplayHeaderFooter(false)\n\t\t\t\t} else {\n\t\t\t\t\tlogger.Debug(\"with custom header and/or footer\")\n\n\t\t\t\t\tprintToPDF = printToPDF.\n\t\t\t\t\t\tWithDisplayHeaderFooter(true).\n\t\t\t\t\t\tWithHeaderTemplate(options.HeaderTemplate).\n\t\t\t\t\t\tWithFooterTemplate(options.FooterTemplate)\n\t\t\t\t}\n\n\t\t\t\tlogger.Debug(fmt.Sprintf(\"print to PDF with: %+v\", printToPDF))\n\n\t\t\t\t_, stream, err := printToPDF.Do(ctx)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"print to PDF: %w\", err)\n\t\t\t\t}\n\n\t\t\t\treader := &streamReader{\n\t\t\t\t\tctx: ctx,\n\t\t\t\t\thandle: stream,\n\t\t\t\t\tr: nil,\n\t\t\t\t\tpos: 0,\n\t\t\t\t\teof: false,\n\t\t\t\t}\n\n\t\t\t\tdefer func() {\n\t\t\t\t\terr := reader.Close()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogger.Error(fmt.Sprintf(\"close reader: %s\", err))\n\t\t\t\t\t}\n\t\t\t\t}()\n\n\t\t\t\tfile, err := os.OpenFile(outputPath, os.O_CREATE|os.O_WRONLY, 0600)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"open output path: %w\", err)\n\t\t\t\t}\n\n\t\t\t\tdefer func() {\n\t\t\t\t\terr := file.Close()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogger.Error(fmt.Sprintf(\"close output path: %s\", err))\n\t\t\t\t\t}\n\t\t\t\t}()\n\n\t\t\t\tbuffer := bufio.NewReader(reader)\n\n\t\t\t\t_, err = buffer.WriteTo(file)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"write result to output path: %w\", err)\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}),\n\t\t}\n\t}\n\n\tactiveInstancesCountMu.Lock()\n\tactiveInstancesCount += 1\n\tactiveInstancesCountMu.Unlock()\n\n\terr := chromedp.Run(taskCtx, printToPDF(URL, options, outputPath))\n\n\tactiveInstancesCountMu.Lock()\n\tactiveInstancesCount -= 1\n\tactiveInstancesCountMu.Unlock()\n\n\t// Always remove the user profile directory created by Chromium.\n\tgo func() {\n\t\tlogger.Debug(fmt.Sprintf(\"remove user profile directory '%s'\", userProfileDirPath))\n\n\t\terr := os.RemoveAll(userProfileDirPath)\n\t\tif err != nil {\n\t\t\tlogger.Error(fmt.Sprintf(\"remove user profile directory: %s\", err))\n\t\t}\n\t}()\n\n\tif err != nil {\n\t\terrMessage := err.Error()\n\n\t\tif strings.Contains(errMessage, \"Show invalid printer settings error (-32000)\") {\n\t\t\treturn ErrInvalidPrinterSettings\n\t\t}\n\n\t\tif strings.Contains(errMessage, \"Page range syntax error\") {\n\t\t\treturn ErrPageRangesSyntaxError\n\t\t}\n\n\t\tif strings.Contains(errMessage, \"rpcc: message too large\") {\n\t\t\treturn ErrRpccMessageTooLarge\n\t\t}\n\n\t\t// See https://github.com/gotenberg/gotenberg/issues/633.\n\t\tif strings.Contains(errMessage, \"chrome failed to start\") {\n\t\t\tfailedStartsCountMu.Lock()\n\t\t\tfailedStartsCount += 1\n\t\t\tfailedStartsCountMu.Unlock()\n\t\t}\n\n\t\treturn fmt.Errorf(\"chromium PDF: %w\", err)\n\t}\n\n\t// See https://github.com/gotenberg/gotenberg/issues/633.\n\tfailedStartsCountMu.Lock()\n\tfailedStartsCount = 0\n\tfailedStartsCountMu.Unlock()\n\n\t// See https://github.com/gotenberg/gotenberg/issues/262.\n\tconsoleExceptionsMu.RLock()\n\tdefer consoleExceptionsMu.RUnlock()\n\n\tif consoleExceptions != nil {\n\t\treturn fmt.Errorf(\"%v: %w\", consoleExceptions, ErrConsoleExceptions)\n\t}\n\n\treturn nil\n}",
"func (o ServiceHostnameConfigurationDeveloperPortalOutput) Thumbprint() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ServiceHostnameConfigurationDeveloperPortal) *string { return v.Thumbprint }).(pulumi.StringPtrOutput)\n}",
"func (x *PDFFunction) Ref() *C.pdf_function {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_function)(unsafe.Pointer(x))\n}",
"func (x *PDFXrange) PassRef() *C.pdf_xrange {\n\tif x == nil {\n\t\tx = (*PDFXrange)(allocPDFXrangeMemory(1))\n\t}\n\treturn (*C.pdf_xrange)(unsafe.Pointer(x))\n}",
"func JWTExtractorFxOption() fx.Option {\n\treturn fx.Provide(constructors.DefaultJWTTokenExtractor)\n}",
"func (x *FzPixmap) Ref() *C.fz_pixmap {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn x.ref7c1a1ba1\n}",
"func (c Capabilities) HasPrinterSupport(gvk schema.GroupVersionKind) bool {\n\treturn includesGVK(gvk, c.SupportsPrinterConfig) ||\n\t\tincludesGVK(gvk, c.SupportsPrinterStatus) ||\n\t\tincludesGVK(gvk, c.SupportsPrinterItems)\n}",
"func (o *PostWebhook) SetPrReopened(v bool) {\n\to.PrReopened = &v\n}",
"func (o FioSpecVolumeVolumeSourcePtrOutput) DownwardAPI() FioSpecVolumeVolumeSourceDownwardAPIPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSource) *FioSpecVolumeVolumeSourceDownwardAPI {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.DownwardAPI\n\t}).(FioSpecVolumeVolumeSourceDownwardAPIPtrOutput)\n}",
"func (me TAttlistArticlePubModel) IsPrint() bool { return me.String() == \"Print\" }",
"func (client *Client) GetOfficePreviewURL(request *GetOfficePreviewURLRequest) (response *GetOfficePreviewURLResponse, err error) {\n\tresponse = CreateGetOfficePreviewURLResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}",
"func (m *PrinterDefaults) GetQuality()(*PrintQuality) {\n val, err := m.GetBackingStore().Get(\"quality\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*PrintQuality)\n }\n return nil\n}",
"func (x *PDFWidget) Ref() *C.pdf_widget {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_widget)(unsafe.Pointer(x))\n}",
"func (x *PDFHotspot) Ref() *C.pdf_hotspot {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_hotspot)(unsafe.Pointer(x))\n}",
"func (m PolicyMode) Pointer() *PolicyMode {\n\treturn &m\n}",
"func (o EnableFormatConditionsCalculation) setSheetPrOption(pr *xlsxSheetPr) {\n\tpr.EnableFormatConditionsCalculation = boolPtr(bool(o))\n}",
"func (o VirtualDatabaseSpecDatasourcesPropertiesValueFromPtrOutput) FieldRef() VirtualDatabaseSpecDatasourcesPropertiesValueFromFieldRefPtrOutput {\n\treturn o.ApplyT(func(v *VirtualDatabaseSpecDatasourcesPropertiesValueFrom) *VirtualDatabaseSpecDatasourcesPropertiesValueFromFieldRef {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.FieldRef\n\t}).(VirtualDatabaseSpecDatasourcesPropertiesValueFromFieldRefPtrOutput)\n}",
"func (p *Proxy) configureReaperDispatcher(d osc.Dispatcher) error {\n\tp._state.mu.Lock()\n\tdefer p._state.mu.Unlock()\n\n\tfor rPfx, mapping := range p._state.trackMap.reaper {\n\t\trPfx := rPfx\n\t\tmapping := mapping\n\t\tfor rSfx, tt := range reaperX32StripMap {\n\t\t\trSfx := rSfx\n\t\t\ttt := tt\n\t\t\ttt.state = &p._state\n\t\t\ttt.nameHints = p.nameHints\n\n\t\t\treaAddr := fmt.Sprintf(\"/%s/%s\", rPfx, rSfx)\n\t\t\tif err := d.AddMsgHandler(reaAddr, func(msg *osc.Message) {\n\t\t\t\tglog.V(2).Infof(\"R-> %s %v\", reaAddr, msg.Arguments)\n\t\t\t\tmsgs, err := tt.Apply(mapping, *msg)\n\t\t\t\tif err != nil {\n\t\t\t\t\tglog.Errorf(\"%s: failed to handle message: %v\", reaAddr, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tp.sendMessagesToX32(msgs)\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tfor fxIdx := int32(0); fxIdx < 10; fxIdx++ {\n\t\t\tfxIdx := fxIdx\n\t\t\tfxNameAddr := fmt.Sprintf(\"/%s/fx/%d/name\", rPfx, fxIdx)\n\t\t\tif err := d.AddMsgHandler(fxNameAddr, func(msg *osc.Message) {\n\t\t\t\tmapping.mu.Lock()\n\t\t\t\tdefer mapping.mu.Unlock()\n\n\t\t\t\tname, ok := msg.Arguments[0].(string)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tname = strings.TrimSpace(name)\n\t\t\t\tif len(name) == 0 {\n\t\t\t\t\t//TODO handle different plugins for each FX type\n\t\t\t\t\tp._state.removeFx(rPfx, fxIdx)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif strings.Contains(name, p.fxPlugName) {\n\t\t\t\t\tpt, ok := p.fxPlugParams[name]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tglog.Infof(\"Unknown plug %q\", name)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tglog.Infof(\"Using %q at %d for FX on %s\", name, fxIdx, mapping.reaperPrefix)\n\t\t\t\t\t//TODO handle different plugins for each FX type\n\t\t\t\t\tmapping.fxMap.eq = &fxInstance{vstIndex: fxIdx, params: &pt}\n\t\t\t\t\tmapping.fxMap.gate = &fxInstance{vstIndex: fxIdx, params: &pt}\n\t\t\t\t\tmapping.fxMap.dyn = &fxInstance{vstIndex: fxIdx, params: &pt}\n\t\t\t\t}\n\t\t\t}); err != nil {\n\t\t\t\tglog.Infof(\"failed to register catcher func\")\n\t\t\t}\n\n\t\t\tfor fxAddr, ttFxTemplate := range reaperX32StripFXMap {\n\t\t\t\tfxAddr := fxAddr\n\n\t\t\t\treaFxAddrTemplate := fmt.Sprintf(\"/%s/%s\", rPfx, fxAddr)\n\t\t\t\t// TODO: 4 for most things, 6 for bus\n\t\t\t\tfor paramIdx := 1; paramIdx <= 300; paramIdx++ {\n\t\t\t\t\tttFx := ttFxTemplate\n\t\t\t\t\tttFx.state = &p._state\n\t\t\t\t\tttFx.nameHints = p.nameHints\n\t\t\t\t\t//ttFx.target = fmt.Sprintf(ttFx.target, i)\n\n\t\t\t\t\treaFxAddr := fmt.Sprintf(reaFxAddrTemplate, fxIdx, paramIdx)\n\t\t\t\t\terr := d.AddMsgHandler(reaFxAddr, func(msg *osc.Message) {\n\t\t\t\t\t\tmsgs, err := ttFx.Apply(mapping, *msg)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t//glog.Errorf(\"%s: failed to handle message: %v\", reaFxAddr, err)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tp.sendMessagesToX32(msgs)\n\t\t\t\t\t})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tglog.Errorf(\"%s: failed to add handler: %v\", reaFxAddr, err)\n\t\t\t\t\t}\n\t\t\t\t} // paramIdx\n\t\t\t} // fxIdx\n\t\t}\n\t}\n\n\t/*\n\t\tfor fxIdx := 0; fxIdx < 10; fxIdx++ {\n\t\t\tfor paramIdx := 0; paramIdx < 300; paramIdx++ {\n\t\t\t\tif err := d.AddMsgHandler(fmt.Sprintf(\"/fx/%d/fxparam/%d/name\", fxIdx, paramIdx), p.nameHandler); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t*/\n\treturn nil\n}",
"func (x *PDFHotspot) PassRef() *C.pdf_hotspot {\n\tif x == nil {\n\t\tx = (*PDFHotspot)(allocPDFHotspotMemory(1))\n\t}\n\treturn (*C.pdf_hotspot)(unsafe.Pointer(x))\n}",
"func (o CertificateDescriptionResponsePtrOutput) ThumbprintSecondary() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *CertificateDescriptionResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ThumbprintSecondary\n\t}).(pulumi.StringPtrOutput)\n}",
"func (wfpssc WaitForPrimarySwapSafetyCheck) AsWaitForPrimarySwapSafetyCheck() (*WaitForPrimarySwapSafetyCheck, bool) {\n\treturn &wfpssc, true\n}",
"func (o IopingSpecVolumeVolumeSourcePtrOutput) DownwardAPI() IopingSpecVolumeVolumeSourceDownwardAPIPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSource) *IopingSpecVolumeVolumeSourceDownwardAPI {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.DownwardAPI\n\t}).(IopingSpecVolumeVolumeSourceDownwardAPIPtrOutput)\n}",
"func enablePointerCapture(ctx context.Context, tconn *chrome.TestConn) error {\n\t// Click on the capture_view using the ui mouse. This ensures that the Ash window is in focus.\n\t// We cannot use UI Automator to click on the capture_view because that does not guarantee the\n\t// window is in focus in Ash as there could be something like a pop-up notification that\n\t// actually has focus.\n\tw, err := ash.GetARCAppWindowInfo(ctx, tconn, motioninput.Package)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get ARC app window info\")\n\t}\n\n\tcenter := w.BoundsInRoot.CenterPoint()\n\tif err := mouse.Click(tconn, center, mouse.LeftButton)(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to click in the app window to enable pointer capture\")\n\t}\n\treturn nil\n}",
"func (o *CodeName) getSheetPrOption(pr *xlsxSheetPr) {\n\tif pr == nil {\n\t\t*o = \"\"\n\t\treturn\n\t}\n\t*o = CodeName(pr.CodeName)\n}",
"func (o SecurityPolicyRuleResponseOutput) Preview() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v SecurityPolicyRuleResponse) bool { return v.Preview }).(pulumi.BoolOutput)\n}",
"func (x *FzBandWriter) PassRef() *C.fz_band_writer {\n\tif x == nil {\n\t\tx = (*FzBandWriter)(allocFzBandWriterMemory(1))\n\t}\n\treturn (*C.fz_band_writer)(unsafe.Pointer(x))\n}",
"func (x *PDFDaInfo) Ref() *C.pdf_da_info {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_da_info)(unsafe.Pointer(x))\n}",
"func (x *PDFOcgDescriptor) Ref() *C.pdf_ocg_descriptor {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_ocg_descriptor)(unsafe.Pointer(x))\n}",
"func (dpv DoublePropertyValue) AsDoublePropertyValue() (*DoublePropertyValue, bool) {\n\treturn &dpv, true\n}",
"func qr_decoder_open() _QrDecoderHandle {\n\tp := C.qr_decoder_open()\n\treturn _QrDecoderHandle(p)\n}",
"func (x *PDFMrange) PassRef() *C.pdf_mrange {\n\tif x == nil {\n\t\tx = (*PDFMrange)(allocPDFMrangeMemory(1))\n\t}\n\treturn (*C.pdf_mrange)(unsafe.Pointer(x))\n}",
"func (o CertificateDescriptionResponsePtrOutput) Thumbprint() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *CertificateDescriptionResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Thumbprint\n\t}).(pulumi.StringPtrOutput)\n}",
"func IsPrintQR(ctx context.Context) bool {\n\tbv, ok := ctx.Value(ctxKeyPrintQR).(bool)\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn bv\n}",
"func (x *PDFDaInfo) PassRef() *C.pdf_da_info {\n\tif x == nil {\n\t\tx = (*PDFDaInfo)(allocPDFDaInfoMemory(1))\n\t}\n\treturn (*C.pdf_da_info)(unsafe.Pointer(x))\n}",
"func (pfw *ProtocolFilterWrapper) Refer(url *common.URL) protocol.Invoker {\n\tif pfw.protocol == nil {\n\t\tpfw.protocol = extension.GetProtocol(url.Protocol)\n\t}\n\tinvoker := pfw.protocol.Refer(url)\n\tif invoker == nil {\n\t\treturn nil\n\t}\n\treturn BuildInvokerChain(invoker, constant.ReferenceFilterKey)\n}",
"func (x *PDFRange) PassRef() *C.pdf_range {\n\tif x == nil {\n\t\tx = (*PDFRange)(allocPDFRangeMemory(1))\n\t}\n\treturn (*C.pdf_range)(unsafe.Pointer(x))\n}",
"func (m *PrinterDefaults) GetColorMode()(*PrintColorMode) {\n val, err := m.GetBackingStore().Get(\"colorMode\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*PrintColorMode)\n }\n return nil\n}",
"func (x *PDFXobject) PassRef() *C.pdf_xobject {\n\tif x == nil {\n\t\tx = (*PDFXobject)(allocPDFXobjectMemory(1))\n\t}\n\treturn (*C.pdf_xobject)(unsafe.Pointer(x))\n}",
"func (E_OpenconfigInterfaces_Interfaces_Interface_Ethernet_State_NegotiatedDuplexMode) IsYANGGoEnum() {}",
"func (E_OpenconfigInterfaces_Interfaces_Interface_Ethernet_State_NegotiatedDuplexMode) IsYANGGoEnum() {}",
"func enableMultiplex(enable bool) option.ClientOption {\n\treturn &enableMultiplexSetting{useMultiplex: enable}\n}",
"func (o FioSpecVolumeVolumeSourceOutput) DownwardAPI() FioSpecVolumeVolumeSourceDownwardAPIPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSource) *FioSpecVolumeVolumeSourceDownwardAPI { return v.DownwardAPI }).(FioSpecVolumeVolumeSourceDownwardAPIPtrOutput)\n}",
"func NewPDFDesignatedNameRef(ref unsafe.Pointer) *PDFDesignatedName {\n\treturn (*PDFDesignatedName)(ref)\n}",
"func (x *FzPixmap) Deref() {\n\tif x.ref7c1a1ba1 == nil {\n\t\treturn\n\t}\n\tx.Storable = *(*FzStorable)(unsafe.Pointer(&x.ref7c1a1ba1.storable))\n\tx.X = (int32)(x.ref7c1a1ba1.x)\n\tx.Y = (int32)(x.ref7c1a1ba1.y)\n\tx.W = (int32)(x.ref7c1a1ba1.w)\n\tx.H = (int32)(x.ref7c1a1ba1.h)\n\tx.N = (byte)(x.ref7c1a1ba1.n)\n\tx.S = (byte)(x.ref7c1a1ba1.s)\n\tx.Alpha = (byte)(x.ref7c1a1ba1.alpha)\n\tx.Flags = (byte)(x.ref7c1a1ba1.flags)\n\tx.Stride = (int32)(x.ref7c1a1ba1.stride)\n\tx.Seps = (*FzSeparations)(unsafe.Pointer(x.ref7c1a1ba1.seps))\n\tx.Xres = (int32)(x.ref7c1a1ba1.xres)\n\tx.Yres = (int32)(x.ref7c1a1ba1.yres)\n\tx.Colorspace = (*FzColorspace)(unsafe.Pointer(x.ref7c1a1ba1.colorspace))\n\thxff73280 := (*sliceHeader)(unsafe.Pointer(&x.Samples))\n\thxff73280.Data = uintptr(unsafe.Pointer(x.ref7c1a1ba1.samples))\n\thxff73280.Cap = 0x7fffffff\n\t// hxff73280.Len = ?\n\n}"
] | [
"0.6527826",
"0.5840567",
"0.5794656",
"0.46665835",
"0.46610054",
"0.44047865",
"0.43198338",
"0.42863533",
"0.42855078",
"0.42596072",
"0.4219133",
"0.42097571",
"0.42007443",
"0.4173926",
"0.4162407",
"0.4153775",
"0.41489148",
"0.41416436",
"0.4106965",
"0.41067177",
"0.40665138",
"0.40648842",
"0.4062861",
"0.4052147",
"0.40434393",
"0.4037669",
"0.4015985",
"0.4009515",
"0.3990971",
"0.39462736",
"0.39204314",
"0.39103287",
"0.39076623",
"0.38893467",
"0.38889346",
"0.38850722",
"0.38818184",
"0.38649166",
"0.3857989",
"0.38552144",
"0.38465413",
"0.38447577",
"0.38401642",
"0.38357896",
"0.3816809",
"0.38107422",
"0.38090965",
"0.3804676",
"0.38008264",
"0.38006425",
"0.37750295",
"0.37604016",
"0.37569463",
"0.37548935",
"0.3747457",
"0.3746352",
"0.37429306",
"0.3739374",
"0.3729209",
"0.37223983",
"0.37196478",
"0.3706912",
"0.37064937",
"0.36958915",
"0.369281",
"0.36825684",
"0.36794832",
"0.36785412",
"0.36759096",
"0.36744997",
"0.36709088",
"0.3666703",
"0.3664661",
"0.36630332",
"0.36623934",
"0.36609903",
"0.36586016",
"0.3655485",
"0.3650645",
"0.36431515",
"0.3636844",
"0.36326066",
"0.36305502",
"0.36275423",
"0.36143732",
"0.36140224",
"0.36109576",
"0.3605376",
"0.3603839",
"0.360217",
"0.36021414",
"0.36017537",
"0.3600006",
"0.35995755",
"0.3593539",
"0.3593539",
"0.35878843",
"0.358654",
"0.35864332",
"0.35839772"
] | 0.6977152 | 0 |
FPDF_VIEWERREF_GetName returns the contents for a viewer ref, with a given key. The value must be of type "name". | func (p *PdfiumImplementation) FPDF_VIEWERREF_GetName(request *requests.FPDF_VIEWERREF_GetName) (*responses.FPDF_VIEWERREF_GetName, error) {
p.Lock()
defer p.Unlock()
documentHandle, err := p.getDocumentHandle(request.Document)
if err != nil {
return nil, err
}
cstr := C.CString(request.Key)
defer C.free(unsafe.Pointer(cstr))
// First get the metadata length.
nameSize := C.FPDF_VIEWERREF_GetName(documentHandle.handle, cstr, nil, 0)
if nameSize == 0 {
return nil, errors.New("could not get name")
}
charData := make([]byte, uint64(nameSize))
C.FPDF_VIEWERREF_GetName(documentHandle.handle, cstr, (*C.char)(unsafe.Pointer(&charData[0])), C.ulong(len(charData)))
return &responses.FPDF_VIEWERREF_GetName{
Value: string(charData[:len(charData)-1]), // Remove nil terminator
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (i *ImageManifest) RefName() string {\n\treturn i.Annotations[\"org.opencontainers.image.ref.name\"]\n}",
"func (a *DeliveryArtifact) RefName() string {\n\tif a.Reference != \"\" {\n\t\treturn a.Reference\n\t}\n\treturn a.Name\n}",
"func (o VirtualDatabaseSpecDatasourcesPropertiesValueFromSecretKeyRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecDatasourcesPropertiesValueFromSecretKeyRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (l *LargeFile) GetRefName() string {\n\tif l == nil || l.RefName == nil {\n\t\treturn \"\"\n\t}\n\treturn *l.RefName\n}",
"func (ipr *Ipref) Name() string { return \"ipref\" }",
"func (o VirtualDatabaseSpecEnvValueFromSecretKeyRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecEnvValueFromSecretKeyRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o VirtualDatabaseSpecDatasourcesPropertiesValueFromSecretKeyRefPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *VirtualDatabaseSpecDatasourcesPropertiesValueFromSecretKeyRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o VirtualDatabaseSpecBuildEnvValueFromSecretKeyRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecBuildEnvValueFromSecretKeyRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (reader *embedFileReader) Name() string {\n\treturn reader.name\n}",
"func (d UserData) Ref() string {\n\tval := d.ModelData.Get(models.NewFieldName(\"Ref\", \"ref\"))\n\tif !d.Has(models.NewFieldName(\"Ref\", \"ref\")) {\n\t\treturn *new(string)\n\t}\n\treturn val.(string)\n}",
"func (o VirtualDatabaseSpecDatasourcesPropertiesValueFromConfigMapKeyRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecDatasourcesPropertiesValueFromConfigMapKeyRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (x *PDFDesignatedName) Ref() *C.pdf_designated_name {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_designated_name)(unsafe.Pointer(x))\n}",
"func (o VirtualDatabaseSpecEnvValueFromSecretKeyRefPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *VirtualDatabaseSpecEnvValueFromSecretKeyRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o VirtualDatabaseSpecBuildEnvValueFromSecretKeyRefPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *VirtualDatabaseSpecBuildEnvValueFromSecretKeyRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o BuildRunSpecBuildRefPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildRunSpecBuildRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o *ContentProviderReadDetailed) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}",
"func Fgetv(fname string, sname string) string {\n\tpname := \"\"\n\tif Fexists(fname, sname) {\n\t\tif Fmember(fframes[fname][sname+\",facets\"], \"ref\") {\n\t\t\tfname2 := fframes[fname][sname+\",ref\"][0]\n\t\t\tif Fmember(fframes[fname][sname+\",facets\"], \"ifref\") {\n\t\t\t\tfmethods[Getval(fframes[fname][sname+\",ifref\"])](fname)\n\t\t\t}\n\t\t\tpname = Fgetv(fname2, sname)\n\t\t} else {\n\t\t\tif Fmember(fframes[fname][sname+\",facets\"], \"value\") {\n\t\t\t\tif Fmember(fframes[fname][sname+\",facets\"], \"ifgetv\") {\n\t\t\t\t\tfmethods[Getval(fframes[fname][sname+\",ifgetv\"])](fname)\n\t\t\t\t}\n\t\t\t\tpname = Getval(fframes[fname][sname+\",value\"])\n\t\t\t}\n\t\t}\n\t}\n\treturn pname\n}",
"func (o LookupOpenZfsSnapshotResultOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupOpenZfsSnapshotResult) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o ParamRefPatchOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ParamRefPatch) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o FioSpecVolumeVolumeSourceCinderSecretRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceCinderSecretRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o CrossVersionObjectReferencePatchOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v CrossVersionObjectReferencePatch) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o CrossVersionObjectReferencePatchOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v CrossVersionObjectReferencePatch) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o IopingSpecVolumeVolumeSourceCinderSecretRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceCinderSecretRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o CrossVersionObjectReferenceOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CrossVersionObjectReference) string { return v.Name }).(pulumi.StringOutput)\n}",
"func (o CrossVersionObjectReferenceOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CrossVersionObjectReference) string { return v.Name }).(pulumi.StringOutput)\n}",
"func (o BuildRunSpecBuildRefOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BuildRunSpecBuildRef) string { return v.Name }).(pulumi.StringOutput)\n}",
"func (o VirtualDatabaseSpecBuildEnvValueFromConfigMapKeyRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecBuildEnvValueFromConfigMapKeyRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (d *Document) Name() string { return d.Document.DocumentName }",
"func (o VirtualDatabaseSpecEnvValueFromConfigMapKeyRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecEnvValueFromConfigMapKeyRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o MachineInstanceSpecResourceRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MachineInstanceSpecResourceRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o *View) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}",
"func (o VirtualDatabaseSpecDatasourcesPropertiesValueFromConfigMapKeyRefPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *VirtualDatabaseSpecDatasourcesPropertiesValueFromConfigMapKeyRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (p *GetField) Name() string { return p.name }",
"func (o BuildStrategySpecBuildStepsEnvValueFromSecretKeyRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsEnvValueFromSecretKeyRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (v *View) ViewName() string { return v.viewName }",
"func (o ReleaseLinkOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ReleaseLink) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}",
"func (o LookupDocumentResultOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupDocumentResult) string { return v.Name }).(pulumi.StringOutput)\n}",
"func (o VirtualDatabaseSpecBuildEnvValueFromConfigMapKeyRefPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *VirtualDatabaseSpecBuildEnvValueFromConfigMapKeyRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (fe *fileEntry) Name() string { return fe.name }",
"func (m *AttachmentItem) GetName()(*string) {\n return m.name\n}",
"func (o VirtualDatabaseSpecEnvValueFromConfigMapKeyRefPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *VirtualDatabaseSpecEnvValueFromConfigMapKeyRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o LookupInstanceAttachmentResultOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupInstanceAttachmentResult) string { return v.Name }).(pulumi.StringOutput)\n}",
"func (o BuildStrategySpecBuildStepsEnvValueFromSecretKeyRefPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildStrategySpecBuildStepsEnvValueFromSecretKeyRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o MachineInstanceSpecResourceRefPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *MachineInstanceSpecResourceRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (v *VCard) Name() string {\n\treturn v.getFirstPropertySingleString(\"fn\")\n}",
"func (v Var) Ref() string {\n\treturn string(v)\n}",
"func (m *ChatMessageAttachment) GetName()(*string) {\n val, err := m.GetBackingStore().Get(\"name\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (o FioSpecVolumeVolumeSourceCinderSecretRefPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSourceCinderSecretRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o ContainerResourceMetricSourcePatchOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ContainerResourceMetricSourcePatch) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o ContainerResourceMetricSourcePatchOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ContainerResourceMetricSourcePatch) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (r *ReleaseAsset) GetName() string {\n\tif r == nil || r.Name == nil {\n\t\treturn \"\"\n\t}\n\treturn *r.Name\n}",
"func (o ApplicationSpecRolloutplanCanarymetricTemplaterefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationSpecRolloutplanCanarymetricTemplateref) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o ClusterBuildStrategySpecBuildStepsEnvValueFromSecretKeyRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ClusterBuildStrategySpecBuildStepsEnvValueFromSecretKeyRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o BuildStrategySpecBuildStepsEnvValueFromConfigMapKeyRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsEnvValueFromConfigMapKeyRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o ParamRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ParamRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o LookupApiKeyResultOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupApiKeyResult) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (t *Link) GetNameString(index int) (v string) {\n\treturn *t.name[index].stringName\n\n}",
"func (o *DnsViewparamDataData) GetViewName() string {\n\tif o == nil || o.ViewName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ViewName\n}",
"func (o IopingSpecVolumeVolumeSourceCinderSecretRefPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSourceCinderSecretRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (v *nicerButSlowerFilmListViewType) Name() string {\n\treturn v.s.SQLName\n}",
"func (o ClusterBuildStrategySpecBuildStepsEnvValueFromSecretKeyRefPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ClusterBuildStrategySpecBuildStepsEnvValueFromSecretKeyRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (v *View) Name() string {\n\treturn v.name\n}",
"func (v *View) Name() string {\n\treturn v.name\n}",
"func (o DataProviderOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DataProvider) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o ResourceMetricSourcePatchOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourceMetricSourcePatch) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o ResourceMetricSourcePatchOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourceMetricSourcePatch) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (re *Records) Name() string { return \"records\" }",
"func (o ApplicationSpecSourceHelmOutput) ReleaseName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationSpecSourceHelm) *string { return v.ReleaseName }).(pulumi.StringPtrOutput)\n}",
"func Fgetr(fname, sname string) string {\n\tif Fexistrx(fname, sname) {\n\t\tif Fmember(fframes[fname][sname+\",facets\"], \"ifgetr\") {\n\t\t\tfmethods[Getval(fframes[fname][sname+\",ifgetr\"])](fname)\n\t\t}\n\t\treturn Getval(fframes[fname][sname+\",ref\"])\n\t} else {\n\t\treturn \"\"\n\t}\n}",
"func (o *Ga4ghFeature) GetReferenceName() string {\n\tif o == nil || o.ReferenceName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ReferenceName\n}",
"func (o *SiteMapReadDetailed) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}",
"func (o *DisplayInfo) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}",
"func (o BuildStrategySpecBuildStepsEnvValueFromConfigMapKeyRefPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildStrategySpecBuildStepsEnvValueFromConfigMapKeyRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o *ContentProvider2) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}",
"func ImageName(ref types.ImageReference) string {\n\treturn ref.Transport().Name() + \":\" + ref.StringWithinTransport()\n}",
"func LinkName(value string) *SimpleElement { return newSEString(\"linkName\", value) }",
"func GetTagFromNamedRef(ref distreference.Named) string {\n\tvar tag string\n\tswitch x := ref.(type) {\n\tcase distreference.Digested:\n\t\ttag = x.Digest().String()\n\tcase distreference.NamedTagged:\n\t\ttag = x.Tag()\n\tdefault:\n\t\ttag = \"latest\"\n\t}\n\treturn tag\n}",
"func (o FioSpecVolumeVolumeSourceRbdSecretRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceRbdSecretRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (e *ObservableEditableBuffer) Name() string {\n\treturn e.details.Name\n}",
"func (o LookupImageResultOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupImageResult) string { return v.Name }).(pulumi.StringOutput)\n}",
"func getImageName(w http.ResponseWriter, r *http.Request, parms martini.Params) {\r\n\tid, _ := strconv.ParseInt(parms[\"id\"], 10, 64)\r\n\tvar img CRImage\r\n\timage := img.Querylog(id)\r\n\t// name := image.ImageName + \":\" + strconv.Itoa(image.Tag)\r\n\t// log.Println(name)\r\n\t// fullName := imageFullName{fullname: name}\r\n\tif err := json.NewEncoder(w).Encode(image); err != nil {\r\n\t\tlogger.Error(err)\r\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\r\n\t}\r\n}",
"func (o CrossVersionObjectReferencePtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *CrossVersionObjectReference) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o CrossVersionObjectReferencePtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *CrossVersionObjectReference) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o LookupSharedImageResultOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSharedImageResult) string { return v.Name }).(pulumi.StringOutput)\n}",
"func (v *actorInfoViewType) Name() string {\n\treturn v.s.SQLName\n}",
"func (n *FileEntry) GetName() string {\n\treturn \" \" + n.name\n}",
"func (o ReleaseOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Release) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}",
"func (r *Reference) Name() ReferenceName {\n\treturn r.n\n}",
"func (o *MicrosoftGraphItemReference) GetName() string {\n\tif o == nil || o.Name == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Name\n}",
"func (o FioSpecVolumeVolumeSourceRbdSecretRefPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSourceRbdSecretRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o *DnsZoneDataData) GetViewName() string {\n\tif o == nil || o.ViewName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ViewName\n}",
"func (pn *PitchNamer) Name(pitch PitchClass) string {\n\treturn pn.lookup[pitch.value]\n}",
"func (o ClusterBuildStrategySpecBuildStepsEnvValueFromConfigMapKeyRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ClusterBuildStrategySpecBuildStepsEnvValueFromConfigMapKeyRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o IopingSpecVolumeVolumeSourceRbdSecretRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceRbdSecretRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o LookupStreamingImageResultOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupStreamingImageResult) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o LookupDocumentResultOutput) VersionName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupDocumentResult) *string { return v.VersionName }).(pulumi.StringPtrOutput)\n}",
"func (v *VRF) Name() string {\n\treturn v.name\n}",
"func (o ParamRefPatchPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ParamRefPatch) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o *KanbanViewView) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}",
"func (o SnapshotOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Snapshot) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}"
] | [
"0.5724464",
"0.5515739",
"0.54866725",
"0.5364599",
"0.529247",
"0.5243815",
"0.524049",
"0.5189564",
"0.51889986",
"0.5126752",
"0.5115203",
"0.51086044",
"0.5105943",
"0.51052994",
"0.50926965",
"0.50921535",
"0.508804",
"0.50820345",
"0.5078626",
"0.50758404",
"0.50431806",
"0.50431806",
"0.5043026",
"0.5042616",
"0.5042616",
"0.50271463",
"0.50083876",
"0.498026",
"0.49780747",
"0.4974555",
"0.49699548",
"0.4966988",
"0.49637792",
"0.4956303",
"0.49544227",
"0.49538177",
"0.49352863",
"0.49335918",
"0.49112037",
"0.49106348",
"0.48989394",
"0.4891397",
"0.48867765",
"0.48805442",
"0.48750895",
"0.4861129",
"0.48605576",
"0.48535305",
"0.48446307",
"0.48446307",
"0.48445475",
"0.48432323",
"0.48352173",
"0.48071298",
"0.48069242",
"0.4802763",
"0.47991338",
"0.47949928",
"0.4787531",
"0.47821155",
"0.47738856",
"0.4772355",
"0.4772355",
"0.47706443",
"0.47685736",
"0.47685736",
"0.4768264",
"0.47522846",
"0.4751926",
"0.4751267",
"0.47501478",
"0.47475204",
"0.47472507",
"0.47447503",
"0.4744327",
"0.47389472",
"0.4738674",
"0.47336653",
"0.47054932",
"0.47032267",
"0.47027308",
"0.4701066",
"0.4701066",
"0.47002342",
"0.4698202",
"0.46956497",
"0.46907154",
"0.46805567",
"0.4674596",
"0.4672712",
"0.46707657",
"0.46658185",
"0.46649286",
"0.46642268",
"0.46592024",
"0.46589002",
"0.46552488",
"0.46533498",
"0.46526363",
"0.4651661"
] | 0.7710307 | 0 |
FPDF_CountNamedDests returns the count of named destinations in the PDF document. | func (p *PdfiumImplementation) FPDF_CountNamedDests(request *requests.FPDF_CountNamedDests) (*responses.FPDF_CountNamedDests, error) {
p.Lock()
defer p.Unlock()
documentHandle, err := p.getDocumentHandle(request.Document)
if err != nil {
return nil, err
}
count := C.FPDF_CountNamedDests(documentHandle.handle)
return &responses.FPDF_CountNamedDests{
Count: uint64(count),
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (out *Out) DestinationCount() int {\n\treturn out.node.OutNeighborCount()\n}",
"func (g fixedNameGenerator) Count() int {\n\treturn len(g.names)\n}",
"func (p *PdfiumImplementation) FPDF_GetNamedDest(request *requests.FPDF_GetNamedDest) (*responses.FPDF_GetNamedDest, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbufLen := C.long(0)\n\n\t// First get the name length.\n\tC.FPDF_GetNamedDest(documentHandle.handle, C.int(request.Index), nil, &bufLen)\n\tif int64(bufLen) <= 0 {\n\t\treturn nil, errors.New(\"could not get name of named dest\")\n\t}\n\n\tcharData := make([]byte, int64(bufLen))\n\tdest := C.FPDF_GetNamedDest(documentHandle.handle, C.int(request.Index), unsafe.Pointer(&charData[0]), &bufLen)\n\n\ttransformedText, err := p.transformUTF16LEToUTF8(charData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdestHandle := p.registerDest(dest, documentHandle)\n\treturn &responses.FPDF_GetNamedDest{\n\t\tDest: destHandle.nativeRef,\n\t\tName: transformedText,\n\t}, nil\n}",
"func (p *PdfiumImplementation) FPDF_GetNamedDestByName(request *requests.FPDF_GetNamedDestByName) (*responses.FPDF_GetNamedDestByName, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcstr := C.CString(request.Name)\n\tdefer C.free(unsafe.Pointer(cstr))\n\n\tdest := C.FPDF_GetNamedDestByName(documentHandle.handle, cstr)\n\tif dest == nil {\n\t\treturn nil, errors.New(\"could not get named dest by name\")\n\t}\n\n\tdestHandle := p.registerDest(dest, documentHandle)\n\treturn &responses.FPDF_GetNamedDestByName{\n\t\tDest: destHandle.nativeRef,\n\t}, nil\n}",
"func (dd DegreeDistribution) Count(n int) int {\n\tc, exists := dd.Relationships[n]\n\tif !exists {\n\t\treturn 0\n\t}\n\n\treturn len(c)\n}",
"func (f *Sink) Count() int {\n\treturn len(f.endpoints)\n}",
"func countTargets(sc *config.SafeConfig, target string) (count int) {\n\tcount = 0\n\tfor _, v := range sc.Cfg.Targets {\n\t\tif strings.Contains(strings.ToUpper(v.Type), strings.ToUpper(target)) {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}",
"func (_TransferProxyRegistry *TransferProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _TransferProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}",
"func (w WaysMapping) Count() int {\n\treturn len(w)\n}",
"func (o ScanRunOutput) UrlsTestedCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.UrlsTestedCount }).(pulumi.StringPtrOutput)\n}",
"func (o ScanRunOutput) UrlsTestedCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.UrlsTestedCount }).(pulumi.StringPtrOutput)\n}",
"func (h Handler) destinationIndex(name string) int {\n\tfor i, dest := range h.Destinations {\n\t\tif dest == name {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}",
"func (q destinationRankQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count destination_rank rows\")\n\t}\n\n\treturn count, nil\n}",
"func CountValidPassports(in string) int {\n\tfmt.Printf(\"\\n\\nInput:\\n%+v\\n\", in)\n\trecords := parseCollection(in)\n\tvalidCount := 0\n\tfor _, record := range records {\n\t\tpassportRecord, errs := createPassport(record)\n\t\terrs = append(errs, validatePassportRecord(passportRecord)...)\n\t\tif len(errs) == 0 {\n\t\t\tvalidCount++\n\t\t}\n\t\tfmt.Printf(\"Record: %+v, Passport valid? %t\\n\", passportRecord, len(errs) == 0)\n\t}\n\treturn validCount\n}",
"func (s papertrailsByName) Len() int { return len(s) }",
"func (o ScanRunPtrOutput) UrlsTestedCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.UrlsTestedCount\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o ScanRunPtrOutput) UrlsTestedCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.UrlsTestedCount\n\t}).(pulumi.StringPtrOutput)\n}",
"func (r *KubeRunner) CountOfEDS(name, ns string) int {\n\ts := RunCMD(fmt.Sprintf(\"istioctl pc endpoints -n %s %s\", ns, name))\n\tcds := strings.Split(s, \"\\n\")\n\n\treturn len(cds) - 1 // remove header\n}",
"func (_OwnerProxyRegistry *OwnerProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _OwnerProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}",
"func (jr *JourneyResults) Count() int {\n\treturn len(jr.Journeys)\n}",
"func Count(s string) int {\n\t// write the code for this func\n\treturn len(strings.Fields(s))\n}",
"func (o DataCollectionRuleOutput) Destinations() DataCollectionRuleDestinationsOutput {\n\treturn o.ApplyT(func(v *DataCollectionRule) DataCollectionRuleDestinationsOutput { return v.Destinations }).(DataCollectionRuleDestinationsOutput)\n}",
"func (o ScanRunResponsePtrOutput) UrlsTestedCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRunResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.UrlsTestedCount\n\t}).(pulumi.StringPtrOutput)\n}",
"func Count(s string) int {\n\txs := strings.Fields(s)\n\treturn len(xs)\n}",
"func Count(s string) int {\n\txs := strings.Fields(s)\n\treturn len(xs)\n}",
"func (c *Comparator) Counts(scanPath string) (int, int) {\n\tvar dirCount = 0\n\tvar fileCount = 0\n\terr := filepath.Walk(scanPath,\n\t\tfunc(path string, info os.FileInfo, err error) error {\n\n\t\t\tif !c.suitableCheck(path, info.Name()) {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif info.IsDir() {\n\t\t\t\tdirCount++\n\t\t\t} else {\n\t\t\t\tfileCount++\n\t\t\t}\n\n\t\t\treturn err\n\t\t})\n\n\tif err != nil {\n\n\t\tlog.Println(err)\n\t}\n\n\treturn dirCount, fileCount\n}",
"func (p *PostingsList) Count() uint64 {\n\tvar n, e uint64\n\tif p.normBits1Hit != 0 {\n\t\tn = 1\n\t\tif p.except != nil && p.except.Contains(uint32(p.docNum1Hit)) {\n\t\t\te = 1\n\t\t}\n\t} else if p.postings != nil {\n\t\tn = p.postings.GetCardinality()\n\t\tif p.except != nil {\n\t\t\te = p.postings.AndCardinality(p.except)\n\t\t}\n\t}\n\treturn n - e\n}",
"func Count(str string, pattern string) int {\n\treturn xstrings.Count(str, pattern)\n}",
"func (StringService) Count(s string) int {\n\treturn len(s)\n}",
"func (d *Dnsfilter) Count() int {\n\treturn len(d.storage)\n}",
"func (d *DeltaStrSet) Count() int {\n\treturn len(d.items)\n}",
"func (db *PSQL) CountOrganizations() (int, error) {\n\treturn 0, nil\n}",
"func (s *OrderShippingAddressService) Count(ctx context.Context, orderID int, params *OrderShippingAddressListParams) (int, *http.Response, error) {\n\tvar cnt count\n\tapiError := new(APIError)\n\n\tresp, err := performRequest(ctx, s.sling.New().Get(fmt.Sprintf(\"%d/shipping_addresses/count\", orderID)).QueryStruct(params), s.httpClient, &cnt, apiError)\n\treturn cnt.Count, resp, relevantError(err, *apiError)\n}",
"func (o ScanRunPtrOutput) UrlsCrawledCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.UrlsCrawledCount\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o ScanRunPtrOutput) UrlsCrawledCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.UrlsCrawledCount\n\t}).(pulumi.StringPtrOutput)\n}",
"func countDirectSigners(data signing.SignatureData) int {\n\tswitch data := data.(type) {\n\tcase *signing.SingleSignatureData:\n\t\tif data.SignMode == signing.SignMode_SIGN_MODE_DIRECT {\n\t\t\treturn 1\n\t\t}\n\n\t\treturn 0\n\tcase *signing.MultiSignatureData:\n\t\tdirectSigners := 0\n\t\tfor _, d := range data.Signatures {\n\t\t\tdirectSigners += countDirectSigners(d)\n\t\t}\n\n\t\treturn directSigners\n\tdefault:\n\t\tpanic(\"unreachable case\")\n\t}\n}",
"func (o ScanRunResponseOutput) UrlsTestedCount() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ScanRunResponse) string { return v.UrlsTestedCount }).(pulumi.StringOutput)\n}",
"func (o ScanRunResponseOutput) UrlsTestedCount() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ScanRunResponse) string { return v.UrlsTestedCount }).(pulumi.StringOutput)\n}",
"func AddCount(name string) {\n\tif count == nil {\n\t\tcount = make(map[string]int)\n\t}\n\tif _, exists := count[name]; exists {\n\t\tcount[name]++\n\t} else {\n\t\tcount[name] = 1\n\t}\n}",
"func CountRedirections(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"GET COUNT\")\n\turlKey := mux.Vars(r)[urlKeyPattern]\n\tcount, status := NewDao(shortURLCountDbPath).FindByKey(urlKey)\n\n\tif status == NotFound {\n\t\tsendJSON(w, http.StatusNotFound, genericResponse{\"URL key not found\"})\n\t\treturn\n\t}\n\n\tif status == Error {\n\t\tlog.Println(\"Internal Server Error\")\n\t\tsendJSON(w, http.StatusInternalServerError, genericResponse{\"Internal Server Error\"})\n\t\treturn\n\t}\n\n\tintCount := 0\n\n\tif count != \"\" {\n\t\tintCount, _ = strconv.Atoi(count)\n\t}\n\n\tmessage := fmt.Sprintf(\"Redirections count for %s: %s\", urlKey, count)\n\tlog.Println(message)\n\n\tsendJSON(w, http.StatusOK, redirectionsCountResponse{intCount})\n}",
"func (m *MockExtensionStore) CountPublishers(v0 context.Context, v1 stores.PublishersListOptions) (int, error) {\n\tr0, r1 := m.CountPublishersFunc.nextHook()(v0, v1)\n\tm.CountPublishersFunc.appendCall(ExtensionStoreCountPublishersFuncCall{v0, v1, r0, r1})\n\treturn r0, r1\n}",
"func Count(s string) int {\n\treturn utf8.RuneCountInString(s)\n}",
"func (d *DistributedBackupDescriptor) Count() int {\n\tcount := 0\n\tfor _, desc := range d.Nodes {\n\t\tcount += len(desc.Classes)\n\t}\n\treturn count\n}",
"func (ns NfLogs) Count() int {\n\tactive := 0\n\tfor _, nflog := range ns {\n\t\tif nflog != nil {\n\t\t\tactive++\n\t\t}\n\t}\n\treturn active\n}",
"func (s MemoryStorage) Count(q Query) (int, error) {\n\tfmt.Println(\"LEN\", len(s.bookmarks))\n\treturn len(s.bookmarks), nil\n}",
"func (vs *Viewers) Viewers(channelName string) int {\n\tvs.lock.Lock()\n\tdefer vs.lock.Unlock()\n\tdefer util.TimeElapsed(time.Now(), \"Viewers\")\n\n\tcount, exists := vs.views[channelName]\n\tif exists {\n\t\treturn count\n\t}\n\treturn 0 // Not found in views map = 0 zaps\n}",
"func (e *Enumeration) DNSNamesRemaining() int {\n\te.metricsLock.RLock()\n\tdefer e.metricsLock.RUnlock()\n\n\treturn e.dnsNamesRemaining\n}",
"func (m ConcurrentRoomInfoMap) Count() int {\n\tcount := 0\n\tfor i := 0; i < shardCount; i++ {\n\t\tshard := m[i]\n\t\tshard.RLock()\n\t\tcount += len(shard.items)\n\t\tshard.RUnlock()\n\t}\n\treturn count\n}",
"func (o ScanRunOutput) UrlsCrawledCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.UrlsCrawledCount }).(pulumi.StringPtrOutput)\n}",
"func (o ScanRunOutput) UrlsCrawledCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.UrlsCrawledCount }).(pulumi.StringPtrOutput)\n}",
"func (m *ConcurrentMap) Count() int {\n\tcount := 0\n\tfor i := 0; i < SHARD_COUNT; i++ {\n\t\tshard := m.shards[i]\n\t\tshard.RLock()\n\t\tcount += len(shard.items)\n\t\tshard.RUnlock()\n\t}\n\treturn count\n}",
"func (self *Glob) NumWildcards() int {\n\treturn len(self.wildcardPositions)\n}",
"func (c *Client) ListDestinations(srcName string) (Destinations, error) {\n\tvar d Destinations\n\tdata, err := c.doRequest(http.MethodGet,\n\t\tfmt.Sprintf(\"%s/%s/%s/%s/%s\",\n\t\t\tWorkspacesEndpoint, c.workspace, SourceEndpoint, srcName, DestinationEndpoint),\n\t\tnil)\n\tif err != nil {\n\t\treturn d, err\n\t}\n\terr = json.Unmarshal(data, &d)\n\tif err != nil {\n\t\treturn d, errors.Wrap(err, \"failed to unmarshal destinations response\")\n\t}\n\n\treturn d, nil\n}",
"func (f *DestRequest) ByteCount() int {\n\treturn 1 + f.User.ByteCount()\n}",
"func CounterByNameSlice(files *[]string,\n\tf func(filename string) (int64, error)) (*map[string]int64, int64, []error) {\n\tcountMap := make(map[string]int64)\n\terrs := []error{}\n\n\tif len(*files) == 0 {\n\t\treturn &countMap, 0, nil\n\t}\n\tvar wg sync.WaitGroup\n\tvar total int64\n\tvar lock sync.Mutex\n\twg.Add(len(*files))\n\tfor i := range *files {\n\t\tgo func(i int64) {\n\t\t\tc, err := f((*files)[i])\n\t\t\tif err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t} else {\n\t\t\t\tlock.Lock()\n\t\t\t\tcountMap[(*files)[i]] = c\n\t\t\t\tlock.Unlock()\n\t\t\t\ttotal = total + c\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(int64(i))\n\t}\n\twg.Wait()\n\tsslice := []string{}\n\tfor key := range countMap {\n\t\tsslice = append(sslice, key)\n\t}\n\tsort.Strings(sslice)\n\tfor _, v := range sslice {\n\t\tfmt.Printf(\"%d\\t%s\\n\", countMap[v], v)\n\t}\n\tif len(sslice) > 0 {\n\t\tfmt.Printf(\"%d\\ttotal\\n\", total)\n\t}\n\treturn &countMap, total, errs\n}",
"func (m *ConcurrentMap) Count() int {\n\tcount := 0\n\tfor i := 0; i < SHARD_COUNT; i++ {\n\t\tshard := m.Shareds[i]\n\t\tshard.RLock()\n\t\tcount += len(shard.items)\n\t\tshard.RUnlock()\n\t}\n\treturn count\n}",
"func (p *Protocol) NumDelegates() uint64 {\n\treturn p.numDelegates\n}",
"func (p *PdfiumImplementation) FPDFLink_CountWebLinks(request *requests.FPDFLink_CountWebLinks) (*responses.FPDFLink_CountWebLinks, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tpageLinkhandle, err := p.getPageLinkHandle(request.PageLink)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcount := C.FPDFLink_CountWebLinks(pageLinkhandle.handle)\n\n\treturn &responses.FPDFLink_CountWebLinks{\n\t\tCount: int(count),\n\t}, nil\n}",
"func Count(name string, usage string) *int {\n\treturn CommandLine.CountP(name, \"\", usage)\n}",
"func Count(file *os.File) {\n\tdoc, err := html.Parse(file)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"findlinks1: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tp := make(map[string]int)\n\n\tfor k, v := range count(p, doc) {\n\t\tfmt.Println(k, v)\n\t}\n}",
"func (s *MemoryStore) NumSubscriptions() int {\n\ts.subsMux.RLock()\n\tdefer s.subsMux.RUnlock()\n\n\treturn len(s.subscriptions)\n}",
"func (g *GooglePubSub) NumPublishersRunning() int {\n\tg.publishMutex.Lock()\n\tnumPubs := g.numRunningPublish\n\tg.publishMutex.Unlock()\n\treturn numPubs\n}",
"func (o *TransactionSplit) HasDestinationName() bool {\n\tif o != nil && o.DestinationName.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (o CommonLanguageSettingsResponseOutput) Destinations() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v CommonLanguageSettingsResponse) []string { return v.Destinations }).(pulumi.StringArrayOutput)\n}",
"func (psg PagesGroup) Len() int {\n\tl := 0\n\tfor _, pg := range psg {\n\t\tl += len(pg.Pages)\n\t}\n\treturn l\n}",
"func (state *StateConditions) Count() int {\n\tcount := 0\n\tif state.Exit != nil {\n\t\tcount++\n\t}\n\tif state.Timeout != nil {\n\t\tcount++\n\t}\n\tcount += len(state.FileMonitors)\n\tcount += len(state.Outputs)\n\treturn count\n}",
"func (o LookupWirelessDeviceResultOutput) DestinationName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupWirelessDeviceResult) *string { return v.DestinationName }).(pulumi.StringPtrOutput)\n}",
"func (d DNA) Counts() (Histogram, error) {\n\tvalidNucleotides := \"ACGT\"\n\tif d != \"\" && regexp.MustCompile(\"[^\"+validNucleotides+\"]\").MatchString(string(d)) {\n\t\treturn nil, errors.New(\"invalid nucleotides\")\n\t}\n\tvar h Histogram = make(map[rune]int)\n\tfor _, char := range validNucleotides {\n\t\th[char] = strings.Count(string(d), string(char))\n\t}\n\treturn h, nil\n}",
"func (o ScanRunResponsePtrOutput) UrlsCrawledCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRunResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.UrlsCrawledCount\n\t}).(pulumi.StringPtrOutput)\n}",
"func (ac *AddressCache) NumAddresses() int {\n\tac.mtx.RLock()\n\tdefer ac.mtx.RUnlock()\n\treturn len(ac.a)\n}",
"func (s SourcesAndDest) Dest() string {\n\treturn s[len(s)-1]\n}",
"func (s *Stentor) Count() int {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\treturn len(s.subscribers)\n}",
"func (mr *MockSnapshotMockRecorder) Destinations() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Destinations\", reflect.TypeOf((*MockSnapshot)(nil).Destinations))\n}",
"func (r *KubeRunner) CountOfCDS(name, ns string) int {\n\ts := RunCMD(fmt.Sprintf(\"istioctl pc cluster -n %s %s\", ns, name))\n\tcds := strings.Split(s, \"\\n\")\n\n\treturn len(cds) - 1 // remove header\n}",
"func (ps *peerStore) Count(infoHash InfoHash) int {\n\tset := ps.Set(infoHash)\n\tif set == nil {\n\t\treturn 0\n\t}\n\n\treturn set.Size()\n}",
"func (q sourceQuery) Count() (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"mdbmdbmodels: failed to count sources rows\")\n\t}\n\n\treturn count, nil\n}",
"func (c *Client) CountWorkspaceTemplates(namespace string) (count int, err error) {\n\terr = sb.Select(\"count(*)\").\n\t\tFrom(\"workspace_templates wt\").\n\t\tWhere(sq.Eq{\n\t\t\t\"wt.namespace\": namespace,\n\t\t\t\"wt.is_archived\": false,\n\t\t}).\n\t\tRunWith(c.DB).\n\t\tQueryRow().\n\t\tScan(&count)\n\n\treturn\n}",
"func (d DNA) Counts() (Histogram, error) {\n\tvar h Histogram = newHistogram()\n\tfor _, n := range d {\n\t\tif _, ok := h[n]; ok {\n\t\t\th[n]++\n\t\t} else {\n\t\t\treturn h, errInvalidNucleotide\n\t\t}\n\t}\n\treturn h, nil\n}",
"func (s *AssociationSummary) SetDestinationName(v string) *AssociationSummary {\n\ts.DestinationName = &v\n\treturn s\n}",
"func (dst Hosts) Len() int { return len(dst) }",
"func (ms Span) DroppedLinksCount() uint32 {\n\treturn ms.orig.DroppedLinksCount\n}",
"func (t *TrafficReferrer) GetCount() int {\n\tif t == nil || t.Count == nil {\n\t\treturn 0\n\t}\n\treturn *t.Count\n}",
"func (o *StatsAppliancesListAllOf) HasPortalCount() bool {\n\tif o != nil && o.PortalCount != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func TileCounts(available string) (counts map[byte]int) {\n\tcounts = make(map[byte]int)\n\tfor _, c := range strings.ToUpper(available) {\n\t\tcounts[byte(c)]++\n\t}\n\treturn\n}",
"func (r *Release) DownloadCount() int {\n\tcount := 0\n\tfor _, a := range r.Assets {\n\t\tcount += a.Count\n\t}\n\treturn count\n}",
"func (d DNA) Counts() (histogram Histogram, err error) {\n\thistogram = Histogram{'A': 0, 'C': 0, 'G': 0, 'T': 0}\n\n\tfor _, rune := range d {\n\t\tif _, ok := histogram[rune]; !ok {\n\t\t\treturn histogram, errors.New(\"Invalid nucleotide\")\n\t\t}\n\t\thistogram[rune] += 1\n\t}\n\n\treturn histogram, nil\n}",
"func (s *String) Count() int {\n\treturn len(s.s)\n}",
"func (d DNA) Counts() (Histogram, error) {\n\tvar h Histogram = Histogram{\n\t\t'A': 0,\n\t\t'C': 0,\n\t\t'T': 0,\n\t\t'G': 0,\n\t}\n\n\tfor _, e := range d {\n\t\tif _, ok := h[e]; !ok {\n\t\t\treturn Histogram{}, fmt.Errorf(\"invalid aminoacid: %v\", e)\n\t\t}\n\t\th[e]++\n\t}\n\n\treturn h, nil\n}",
"func (pns *ProcessNameSorter) Len() int {\n\treturn len(pns.processes)\n}",
"func linkCount(f *gdrive.File, numSubDirs int) int {\n\tlinks := len(f.Parents) + numSubDirs\n\t// If this is a directory, the '.' counts as an additional link\n\tif f.MimeType == driveFolderMimeType {\n\t\tlinks++\n\t}\n\treturn links\n}",
"func (c *CoderFirestore) ShardsCount(ctx context.Context) (int, error) {\n\treturn c.shardsCount(ctx)\n}",
"func (fm *FileMapMutex) Count() (size int) {\n\tfm.mu.RLock()\n\tdefer fm.mu.RUnlock()\n\treturn len(fm.Files)\n}",
"func (o RuleCompliancePtrOutput) Count() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *RuleCompliance) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Count\n\t}).(pulumi.IntPtrOutput)\n}",
"func (o VirtualHubRouteTableRouteOutput) Destinations() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *VirtualHubRouteTableRoute) pulumi.StringArrayOutput { return v.Destinations }).(pulumi.StringArrayOutput)\n}",
"func GetDestinationManagerMapLen() int {\n\tdestinationManagerMapMutex.RLock()\n\tdefer destinationManagerMapMutex.RUnlock()\n\treturn len(destinationManagerMap)\n}",
"func (o NamedPartitionSchemeDescriptionOutput) Count() pulumi.IntOutput {\n\treturn o.ApplyT(func(v NamedPartitionSchemeDescription) int { return v.Count }).(pulumi.IntOutput)\n}",
"func AnnotationCounts(uuid string) int {\n\treturn uuidcounts.Get(uuid)\n}",
"func (vs *Variables) Count() int {\n\treturn len(vs.n)\n}",
"func (q *DeferredQuery) Count() (int, error) {\n\topt := mopt.Count()\n\tfilter := q.Filter\n\tif filter == nil {\n\t\tfilter = bson.D{}\n\t}\n\tc, err := q.Coll.CountDocuments(nil, filter, opt)\n\treturn int(c), err\n}",
"func NumOfDataEntries(db *sql.DB, name string) (int, error) {\n\tscript := fmt.Sprintf(\"SELECT count(*) FROM %v;\", name)\n\tvar num int\n\terr := db.QueryRow(script).Scan(&num)\n\treturn num, err\n}"
] | [
"0.56745064",
"0.5392558",
"0.5008388",
"0.49131483",
"0.4897058",
"0.488123",
"0.48665354",
"0.48562744",
"0.47940367",
"0.4780095",
"0.4780095",
"0.47726828",
"0.4733118",
"0.4723217",
"0.47088015",
"0.46778384",
"0.46778384",
"0.465871",
"0.4636263",
"0.462229",
"0.45574346",
"0.4541087",
"0.45371413",
"0.45343894",
"0.45343894",
"0.44968116",
"0.4481998",
"0.44786018",
"0.44692665",
"0.44663465",
"0.4443608",
"0.4443209",
"0.44134945",
"0.43925178",
"0.43925178",
"0.43869027",
"0.43828526",
"0.43828526",
"0.43776104",
"0.43713352",
"0.4369951",
"0.43613812",
"0.43563354",
"0.4345005",
"0.43419844",
"0.43407756",
"0.43289468",
"0.43266612",
"0.43142143",
"0.43142143",
"0.4308802",
"0.42931762",
"0.4284845",
"0.4281879",
"0.4271326",
"0.42695364",
"0.42635977",
"0.42611653",
"0.42567295",
"0.4243499",
"0.42427474",
"0.42379892",
"0.4234071",
"0.4231808",
"0.4230583",
"0.42285365",
"0.42238122",
"0.42212698",
"0.42191583",
"0.42170173",
"0.42136204",
"0.42125046",
"0.420667",
"0.41938716",
"0.41808707",
"0.41752595",
"0.41728055",
"0.41682792",
"0.41660562",
"0.41549873",
"0.41529524",
"0.41501084",
"0.41425273",
"0.41413027",
"0.41371393",
"0.41339555",
"0.41310477",
"0.41258693",
"0.41247553",
"0.41244516",
"0.41150194",
"0.41133475",
"0.41125914",
"0.41067135",
"0.41034138",
"0.41006535",
"0.40990847",
"0.40946516",
"0.4094185",
"0.40898088"
] | 0.88831776 | 0 |
FPDF_GetNamedDestByName returns the destination handle for the given name. | func (p *PdfiumImplementation) FPDF_GetNamedDestByName(request *requests.FPDF_GetNamedDestByName) (*responses.FPDF_GetNamedDestByName, error) {
p.Lock()
defer p.Unlock()
documentHandle, err := p.getDocumentHandle(request.Document)
if err != nil {
return nil, err
}
cstr := C.CString(request.Name)
defer C.free(unsafe.Pointer(cstr))
dest := C.FPDF_GetNamedDestByName(documentHandle.handle, cstr)
if dest == nil {
return nil, errors.New("could not get named dest by name")
}
destHandle := p.registerDest(dest, documentHandle)
return &responses.FPDF_GetNamedDestByName{
Dest: destHandle.nativeRef,
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (p *PdfiumImplementation) FPDF_GetNamedDest(request *requests.FPDF_GetNamedDest) (*responses.FPDF_GetNamedDest, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbufLen := C.long(0)\n\n\t// First get the name length.\n\tC.FPDF_GetNamedDest(documentHandle.handle, C.int(request.Index), nil, &bufLen)\n\tif int64(bufLen) <= 0 {\n\t\treturn nil, errors.New(\"could not get name of named dest\")\n\t}\n\n\tcharData := make([]byte, int64(bufLen))\n\tdest := C.FPDF_GetNamedDest(documentHandle.handle, C.int(request.Index), unsafe.Pointer(&charData[0]), &bufLen)\n\n\ttransformedText, err := p.transformUTF16LEToUTF8(charData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdestHandle := p.registerDest(dest, documentHandle)\n\treturn &responses.FPDF_GetNamedDest{\n\t\tDest: destHandle.nativeRef,\n\t\tName: transformedText,\n\t}, nil\n}",
"func (o LookupWirelessDeviceResultOutput) DestinationName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupWirelessDeviceResult) *string { return v.DestinationName }).(pulumi.StringPtrOutput)\n}",
"func (o WirelessDeviceImportTaskOutput) DestinationName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *WirelessDeviceImportTask) pulumi.StringOutput { return v.DestinationName }).(pulumi.StringOutput)\n}",
"func (o ApplicationSpecDestinationPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationSpecDestination) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o AppProjectSpecDestinationsOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AppProjectSpecDestinations) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o ApplicationSpecDestinationOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationSpecDestination) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (m *SmsLogRow) GetDestinationName()(*string) {\n val, err := m.GetBackingStore().Get(\"destinationName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (o *TransactionSplit) GetDestinationName() string {\n\tif o == nil || o.DestinationName.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DestinationName.Get()\n}",
"func (s *AssociationSummary) SetDestinationName(v string) *AssociationSummary {\n\ts.DestinationName = &v\n\treturn s\n}",
"func (s *StartAnnotationImportJobInput) SetDestinationName(v string) *StartAnnotationImportJobInput {\n\ts.DestinationName = &v\n\treturn s\n}",
"func (s *VariantImportJobItem) SetDestinationName(v string) *VariantImportJobItem {\n\ts.DestinationName = &v\n\treturn s\n}",
"func (s *GetVariantImportJobOutput) SetDestinationName(v string) *GetVariantImportJobOutput {\n\ts.DestinationName = &v\n\treturn s\n}",
"func (s *StartVariantImportJobInput) SetDestinationName(v string) *StartVariantImportJobInput {\n\ts.DestinationName = &v\n\treturn s\n}",
"func (s *AnnotationImportJobItem) SetDestinationName(v string) *AnnotationImportJobItem {\n\ts.DestinationName = &v\n\treturn s\n}",
"func (inst Instance) GetPortalFromName(name string) (Portal, error) {\n\tfor _, p := range inst.portals {\n\t\tif p.name == name {\n\t\t\treturn p, nil\n\t\t}\n\t}\n\n\treturn Portal{}, fmt.Errorf(\"No portal with that name\")\n}",
"func (o ApplicationStatusSyncComparedToDestinationPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationStatusSyncComparedToDestination) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (s *GetAnnotationImportJobOutput) SetDestinationName(v string) *GetAnnotationImportJobOutput {\n\ts.DestinationName = &v\n\treturn s\n}",
"func (o *TransactionSplit) SetDestinationName(v string) {\n\to.DestinationName.Set(&v)\n}",
"func (o ArgoCDExportSpecStoragePvcDataSourcePtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDExportSpecStoragePvcDataSource) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o ApplicationStatusSyncComparedToDestinationOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusSyncComparedToDestination) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o NamedPortOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v NamedPort) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (h Handler) destinationIndex(name string) int {\n\tfor i, dest := range h.Destinations {\n\t\tif dest == name {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}",
"func (l *LogSink) Name() string {\n\treturn l.Sink\n}",
"func (d *Download) Name() string {\n\n\t// Avoid returning different path at runtime.\n\tif d.name == \"\" {\n\n\t\tfileName := d.Dest\n\n\t\t// Set default file name.\n\t\tif fileName == \"\" {\n\n\t\t\t// Content disposition name.\n\t\t\tfileName = d.info.Name\n\n\t\t\t// if name invalid get name from url.\n\t\t\tif fileName == \"\" {\n\t\t\t\tfileName = GetFilename(d.URL)\n\t\t\t}\n\t\t}\n\n\t\td.name = filepath.Join(d.Dir, fileName)\n\t}\n\n\treturn d.name\n}",
"func (m *SmsLogRow) SetDestinationName(value *string)() {\n err := m.GetBackingStore().Set(\"destinationName\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (o FolderSinkOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FolderSink) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}",
"func (dr *DestRules) ByName(s Service) []*istioClientNet.DestinationRule {\n\tns, ok := dr.name[s.Namespace]\n\tif !ok {\n\t\treturn []*istioClientNet.DestinationRule{}\n\t}\n\tres, ok := ns[s.Name]\n\tif !ok {\n\t\treturn []*istioClientNet.DestinationRule{}\n\t}\n\treturn res\n}",
"func (_options *CreateDestinationOptions) SetName(name string) *CreateDestinationOptions {\n\t_options.Name = core.StringPtr(name)\n\treturn _options\n}",
"func (o PublisherPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Publisher) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (p *PdfiumImplementation) FPDF_CountNamedDests(request *requests.FPDF_CountNamedDests) (*responses.FPDF_CountNamedDests, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcount := C.FPDF_CountNamedDests(documentHandle.handle)\n\treturn &responses.FPDF_CountNamedDests{\n\t\tCount: uint64(count),\n\t}, nil\n}",
"func (o GatewayLocationDataPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *GatewayLocationData) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (b *Bucket) DownloadToStreamByName(ctx context.Context, name string, w io.Writer, opts ...*options.NameOptions) (int64, error) {\n\t// open stream\n\tstream, err := b.OpenDownloadStreamByName(ctx, name, opts...)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// copy data\n\tn, err := io.Copy(w, stream)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn n, nil\n}",
"func (o *TransactionSplit) GetDestinationNameOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.DestinationName.Get(), o.DestinationName.IsSet()\n}",
"func (o *EmsDestinationDeleteParams) WithName(name string) *EmsDestinationDeleteParams {\n\to.SetName(name)\n\treturn o\n}",
"func (o LookupOrganizationSinkResultOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupOrganizationSinkResult) string { return v.Name }).(pulumi.StringOutput)\n}",
"func (c *Client) GetDestination(srcName string, destName string) (Destination, error) {\n\tvar d Destination\n\tdata, err := c.doRequest(http.MethodGet,\n\t\tfmt.Sprintf(\"%s/%s/%s/%s/%s/%s\",\n\t\t\tWorkspacesEndpoint, c.workspace, SourceEndpoint, srcName, DestinationEndpoint, destName),\n\t\tnil)\n\tif err != nil {\n\t\treturn d, err\n\t}\n\terr = json.Unmarshal(data, &d)\n\tif err != nil {\n\t\treturn d, errors.Wrap(err, \"failed to unmarshal destination response\")\n\t}\n\n\treturn d, nil\n}",
"func (o AnalyticsConfigurationStorageClassAnalysisDataExportPtrOutput) Destination() AnalyticsConfigurationStorageClassAnalysisDataExportDestinationPtrOutput {\n\treturn o.ApplyT(func(v *AnalyticsConfigurationStorageClassAnalysisDataExport) *AnalyticsConfigurationStorageClassAnalysisDataExportDestination {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Destination\n\t}).(AnalyticsConfigurationStorageClassAnalysisDataExportDestinationPtrOutput)\n}",
"func (o PublisherOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v Publisher) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (ft *FileTuple) GetDest() string {\n\treturn ft.dest\n}",
"func (s SourcesAndDest) Dest() string {\n\treturn s[len(s)-1]\n}",
"func (o ApplicationOperationSyncSourceHelmPtrOutput) ReleaseName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationOperationSyncSourceHelm) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ReleaseName\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o JobExtractPtrOutput) DestinationFormat() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *JobExtract) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.DestinationFormat\n\t}).(pulumi.StringPtrOutput)\n}",
"func (h HeaderV2) DestAddr() net.Addr { return h.Dest }",
"func (o OutputConfigPtrOutput) Destination() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *OutputConfig) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Destination\n\t}).(pulumi.StringPtrOutput)\n}",
"func (dm *DestinationMixin) GetDestination() (bot.Destination, error) {\n\tif dm.Directory != nil {\n\t\treturn dm.Directory, nil\n\t}\n\n\tif dm.Memory != nil {\n\t\treturn dm.Memory, nil\n\t}\n\n\treturn nil, trace.BadParameter(\"no valid destination exists\")\n}",
"func (o BuildStrategySpecBuildStepsPortsOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsPorts) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o *EmsDestinationDeleteParams) SetName(name string) {\n\to.Name = name\n}",
"func (o HTTP2HealthCheckPtrOutput) PortName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *HTTP2HealthCheck) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PortName\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o LookupStreamingImageResultOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupStreamingImageResult) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o TransferJobTransferSpecPtrOutput) SinkAgentPoolName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TransferJobTransferSpec) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.SinkAgentPoolName\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o TransferJobTransferSpecOutput) SinkAgentPoolName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v TransferJobTransferSpec) *string { return v.SinkAgentPoolName }).(pulumi.StringPtrOutput)\n}",
"func (o ResourceMetricSourcePtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourceMetricSource) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o ResourceMetricSourcePtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourceMetricSource) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o ApplicationSpecSourceHelmPtrOutput) ReleaseName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationSpecSourceHelm) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ReleaseName\n\t}).(pulumi.StringPtrOutput)\n}",
"func (b *Bucket) DownloadToStreamByName(filename string, stream io.Writer, opts ...*options.NameOptions) (int64, error) {\n\tds, err := b.OpenDownloadStreamByName(filename, opts...)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn b.downloadToStream(ds, stream)\n}",
"func (o ApplicationOperationSyncSourceHelmOutput) ReleaseName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationOperationSyncSourceHelm) *string { return v.ReleaseName }).(pulumi.StringPtrOutput)\n}",
"func getByName(name string) gpio.PinIO {\n\tif p, ok := byName[0][name]; ok {\n\t\treturn p\n\t}\n\tif p, ok := byName[1][name]; ok {\n\t\treturn p\n\t}\n\tif p, ok := byAlias[name]; ok {\n\t\tif p.PinIO == nil {\n\t\t\tif p.PinIO = getByName(p.dest); p.PinIO == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn p\n\t}\n\tif i, err := strconv.Atoi(name); err == nil {\n\t\treturn getByNumber(i)\n\t}\n\treturn nil\n}",
"func (o TargetGroupPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TargetGroup) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o FioSpecVolumeVolumeSourceProjectedSourcesSecretOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceProjectedSourcesSecret) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (dr *DestRules) AddByName(s Service, rule *istioClientNet.DestinationRule) {\n\tnamespace, ok := dr.name[s.Namespace]\n\tif !ok {\n\t\tnamespace = make(destRulesByNameMap)\n\t\tdr.name[s.Namespace] = namespace\n\t}\n\tname, _ := namespace[s.Name]\n\tnamespace[s.Name] = append(name, rule)\n}",
"func (o DatasourcePtrOutput) ResourceName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Datasource) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ResourceName\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o SSLHealthCheckPtrOutput) PortName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *SSLHealthCheck) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PortName\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o *TransactionSplit) HasDestinationName() bool {\n\tif o != nil && o.DestinationName.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (o VirtualDatabaseSpecDatasourcesPropertiesValueFromSecretKeyRefPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *VirtualDatabaseSpecDatasourcesPropertiesValueFromSecretKeyRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (j Job) Dest() string {\n\tif j.Load == nil {\n\t\treturn \"\"\n\t}\n\tif j.DestTable != \"\" {\n\t\treturn j.DestTable\n\t}\n\treturn j.Load.DestinationTable.DatasetId + shared.PathElementSeparator + j.Load.DestinationTable.TableId\n}",
"func (c *D) Name() string {\n\tif len(c.Args) > 0 {\n\t\treturn c.Args[0]\n\t}\n\treturn c.Path\n}",
"func (o GRPCHealthCheckPtrOutput) PortName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *GRPCHealthCheck) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PortName\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o ArgoCDExportSpecStoragePvcDataSourceOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ArgoCDExportSpecStoragePvcDataSource) string { return v.Name }).(pulumi.StringOutput)\n}",
"func (m *_DF1SymbolMessageFrame) GetDestinationAddress() uint8 {\n\treturn m.DestinationAddress\n}",
"func (d *galleryDocument) Dest() (string, error) {\n\trelpath, err := filepath.Rel(\"src\", d.localPath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\n\t\t\t\"can't get relpath for photo `%s`: %w\",\n\t\t\td.localPath,\n\t\t\terr,\n\t\t)\n\t}\n\n\treturn fmt.Sprintf(\"%s.html\", relpath), nil\n}",
"func (o LookupOpenZfsSnapshotResultOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupOpenZfsSnapshotResult) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o FioSpecVolumeVolumeSourceProjectedSourcesSecretPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSourceProjectedSourcesSecret) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (ts TaskSpec) OutputByName(name string) (TaskOutputSpec, bool) {\n\tfor _, x := range ts.Outputs {\n\t\tif x.Name == name {\n\t\t\treturn x, true\n\t\t}\n\t}\n\treturn TaskOutputSpec{}, false\n}",
"func (o TCPHealthCheckPtrOutput) PortName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TCPHealthCheck) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PortName\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o IopingSpecVolumeVolumeSourceProjectedSourcesSecretOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceProjectedSourcesSecret) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func OutByName(portName string) (out Out, err error) {\n\tdrv := Get()\n\tif drv == nil {\n\t\treturn nil, fmt.Errorf(\"no driver registered\")\n\t}\n\treturn openOut(drv, -1, portName)\n}",
"func (o ApplicationStatusOperationStateSyncResultSourceHelmPtrOutput) ReleaseName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationStatusOperationStateSyncResultSourceHelm) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ReleaseName\n\t}).(pulumi.StringPtrOutput)\n}",
"func (m *CopyToDefaultContentLocationPostRequestBody) GetDestinationFileName()(*string) {\n return m.destinationFileName\n}",
"func (_options *UpdateDestinationOptions) SetName(name string) *UpdateDestinationOptions {\n\t_options.Name = core.StringPtr(name)\n\treturn _options\n}",
"func (o PersistenceProfileDstAddrOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PersistenceProfileDstAddr) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}",
"func (f *SAMDGClientForwarder) Destination() string {\n\treturn f.addr.Base32()\n}",
"func (o RegistryTaskBaseImageTriggerPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *RegistryTaskBaseImageTrigger) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o ApplicationStatusSyncComparedToSourceHelmPtrOutput) ReleaseName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationStatusSyncComparedToSourceHelm) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ReleaseName\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o DrillSpecImagePtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DrillSpecImage) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o DataProviderPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DataProvider) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (d *DestinationClient) GetInstanceDestination(name string) (Destination, error) {\n\n\tvar retval Destination\n\tvar errResponse ErrorMessage\n\n\tresponse, err := d.restyClient.R().\n\t\tSetResult(&retval).\n\t\tSetError(&errResponse).\n\t\tSetPathParams(map[string]string{\n\t\t\t\"name\": name,\n\t\t}).\n\t\tGet(\"/instanceDestinations/{name}\")\n\n\tif err != nil {\n\t\treturn retval, err\n\t}\n\tif response.StatusCode() != 200 {\n\t\terrResponse.statusCode = response.StatusCode()\n\t\treturn retval, errResponse\n\t}\n\treturn retval, nil\n}",
"func (o HTTP2HealthCheckOutput) PortName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v HTTP2HealthCheck) *string { return v.PortName }).(pulumi.StringPtrOutput)\n}",
"func (o ExportOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Export) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}",
"func (o IopingSpecVolumeVolumeSourceProjectedSourcesSecretPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSourceProjectedSourcesSecret) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o StreamProcessorOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *StreamProcessor) pulumi.StringPtrOutput { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o *ExportData) GetStreamName() string {\n\treturn \"\"\n}",
"func (f *File) RuleNamed(name string) *Rule {\n\tall := f.rules(func(rule *Rule) bool {\n\t\treturn rule.Name() == name\n\t})\n\tif len(all) != 1 {\n\t\treturn nil\n\t}\n\treturn all[0]\n}",
"func GetStatsByName(t *testing.T, ing ingress.Instance, statsName string) (int, error) {\n\tgatewayStats, err := ing.ProxyStats()\n\tif err == nil {\n\t\tsdsUpdates, hasSdsStats := gatewayStats[statsName]\n\t\tif hasSdsStats {\n\t\t\treturn sdsUpdates, nil\n\t\t}\n\t}\n\treturn 0, fmt.Errorf(\"unable to get ingress gateway proxy sds stats: %v\", err)\n}",
"func (o VirtualDatabaseSpecDatasourcesPropertiesValueFromSecretKeyRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecDatasourcesPropertiesValueFromSecretKeyRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o OutputConfigResponsePtrOutput) Destination() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *OutputConfigResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Destination\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o BuildStrategySpecBuildStepsEnvValueFromSecretKeyRefPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildStrategySpecBuildStepsEnvValueFromSecretKeyRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o MustGatherSpecServiceAccountRefPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *MustGatherSpecServiceAccountRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (h *InputHost) checkDestination(ctx thrift.Context, path string) (string, shared.DestinationType, metrics.ErrorClass, error) {\n\t// talk to metadata\n\tmGetRequest := shared.ReadDestinationRequest{Path: common.StringPtr(path)}\n\tdestDesc, err := h.mClient.ReadDestination(ctx, &mGetRequest)\n\tif err != nil {\n\t\terrC, newErr := common.ConvertDownstreamErrors(h.logger, err)\n\t\treturn \"\", shared.DestinationType_UNKNOWN, errC, newErr\n\t}\n\n\t// Make sure destDesc cannot be nil\n\tif destDesc == nil {\n\t\terrMsg := fmt.Sprintf(\"unable to get destination description from metadata for dst=%v\", path)\n\t\terrC, newErr := common.ConvertDownstreamErrors(h.logger, &cherami.BadRequestError{Message: errMsg})\n\t\treturn \"\", shared.DestinationType_UNKNOWN, errC, newErr\n\t}\n\n\t// Now make sure the destination is writable\n\tif !h.isDestinationWritable(destDesc) {\n\t\terrMsg := fmt.Sprintf(\"Destination is not writable, dst=%v, status=%v\", path, destDesc.GetStatus())\n\t\terrC, newErr := common.ConvertDownstreamErrors(h.logger, &cherami.BadRequestError{Message: errMsg})\n\t\treturn \"\", shared.DestinationType_UNKNOWN, errC, newErr\n\t}\n\n\treturn destDesc.GetDestinationUUID(), destDesc.GetType(), metrics.NoError, nil\n}",
"func (o StreamOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Stream) pulumi.StringPtrOutput { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o LookupTaskTemplateResultOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupTaskTemplateResult) *string { return v.Name }).(pulumi.StringPtrOutput)\n}"
] | [
"0.76602274",
"0.66063476",
"0.6095394",
"0.58752173",
"0.57497704",
"0.57336354",
"0.57000506",
"0.55712354",
"0.5561159",
"0.54068255",
"0.53856766",
"0.5378346",
"0.53776425",
"0.5371427",
"0.53491807",
"0.5339053",
"0.53359973",
"0.52345806",
"0.52331024",
"0.51694286",
"0.5148957",
"0.50515497",
"0.5050103",
"0.503646",
"0.5034496",
"0.5007406",
"0.49992916",
"0.48825517",
"0.48809382",
"0.48748106",
"0.48488232",
"0.48370665",
"0.483262",
"0.47827116",
"0.47806057",
"0.47781035",
"0.47747946",
"0.47738472",
"0.4765922",
"0.47584155",
"0.47581095",
"0.47414884",
"0.4725375",
"0.4717801",
"0.47099137",
"0.4702713",
"0.4702459",
"0.46994415",
"0.46988657",
"0.4688158",
"0.4674533",
"0.46669403",
"0.46669403",
"0.46655464",
"0.4661657",
"0.46598738",
"0.46584037",
"0.46578547",
"0.46512562",
"0.46498156",
"0.46384552",
"0.46368676",
"0.46341544",
"0.46335468",
"0.46315342",
"0.4628433",
"0.46277377",
"0.4619511",
"0.46193483",
"0.46078926",
"0.460254",
"0.4601786",
"0.46001604",
"0.459503",
"0.4594918",
"0.45913967",
"0.4589324",
"0.45756257",
"0.45737755",
"0.45733812",
"0.45729095",
"0.45685193",
"0.45608678",
"0.45563957",
"0.4555833",
"0.45555368",
"0.45532855",
"0.45527562",
"0.45477083",
"0.45453143",
"0.45446372",
"0.45411628",
"0.45394924",
"0.4539355",
"0.45370883",
"0.45335376",
"0.45213997",
"0.45191377",
"0.45118836",
"0.45108378"
] | 0.8045243 | 0 |
FPDF_GetNamedDest returns the named destination by index. | func (p *PdfiumImplementation) FPDF_GetNamedDest(request *requests.FPDF_GetNamedDest) (*responses.FPDF_GetNamedDest, error) {
p.Lock()
defer p.Unlock()
documentHandle, err := p.getDocumentHandle(request.Document)
if err != nil {
return nil, err
}
bufLen := C.long(0)
// First get the name length.
C.FPDF_GetNamedDest(documentHandle.handle, C.int(request.Index), nil, &bufLen)
if int64(bufLen) <= 0 {
return nil, errors.New("could not get name of named dest")
}
charData := make([]byte, int64(bufLen))
dest := C.FPDF_GetNamedDest(documentHandle.handle, C.int(request.Index), unsafe.Pointer(&charData[0]), &bufLen)
transformedText, err := p.transformUTF16LEToUTF8(charData)
if err != nil {
return nil, err
}
destHandle := p.registerDest(dest, documentHandle)
return &responses.FPDF_GetNamedDest{
Dest: destHandle.nativeRef,
Name: transformedText,
}, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (p *PdfiumImplementation) FPDF_GetNamedDestByName(request *requests.FPDF_GetNamedDestByName) (*responses.FPDF_GetNamedDestByName, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcstr := C.CString(request.Name)\n\tdefer C.free(unsafe.Pointer(cstr))\n\n\tdest := C.FPDF_GetNamedDestByName(documentHandle.handle, cstr)\n\tif dest == nil {\n\t\treturn nil, errors.New(\"could not get named dest by name\")\n\t}\n\n\tdestHandle := p.registerDest(dest, documentHandle)\n\treturn &responses.FPDF_GetNamedDestByName{\n\t\tDest: destHandle.nativeRef,\n\t}, nil\n}",
"func (h Handler) destinationIndex(name string) int {\n\tfor i, dest := range h.Destinations {\n\t\tif dest == name {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}",
"func (o LookupWirelessDeviceResultOutput) DestinationName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupWirelessDeviceResult) *string { return v.DestinationName }).(pulumi.StringPtrOutput)\n}",
"func (o WirelessDeviceImportTaskOutput) DestinationName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *WirelessDeviceImportTask) pulumi.StringOutput { return v.DestinationName }).(pulumi.StringOutput)\n}",
"func (s SourcesAndDest) Dest() string {\n\treturn s[len(s)-1]\n}",
"func (m *SmsLogRow) GetDestinationName()(*string) {\n val, err := m.GetBackingStore().Get(\"destinationName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (ft *FileTuple) GetDest() string {\n\treturn ft.dest\n}",
"func (o *TransactionSplit) GetDestinationName() string {\n\tif o == nil || o.DestinationName.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DestinationName.Get()\n}",
"func (c *Client) GetDestination(srcName string, destName string) (Destination, error) {\n\tvar d Destination\n\tdata, err := c.doRequest(http.MethodGet,\n\t\tfmt.Sprintf(\"%s/%s/%s/%s/%s/%s\",\n\t\t\tWorkspacesEndpoint, c.workspace, SourceEndpoint, srcName, DestinationEndpoint, destName),\n\t\tnil)\n\tif err != nil {\n\t\treturn d, err\n\t}\n\terr = json.Unmarshal(data, &d)\n\tif err != nil {\n\t\treturn d, errors.Wrap(err, \"failed to unmarshal destination response\")\n\t}\n\n\treturn d, nil\n}",
"func (j Job) Dest() string {\n\tif j.Load == nil {\n\t\treturn \"\"\n\t}\n\tif j.DestTable != \"\" {\n\t\treturn j.DestTable\n\t}\n\treturn j.Load.DestinationTable.DatasetId + shared.PathElementSeparator + j.Load.DestinationTable.TableId\n}",
"func (o *PluginMount) GetDestination() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Destination\n}",
"func (o AppProjectSpecDestinationsOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AppProjectSpecDestinations) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (i *Index) GetDst(dstID DstID) (Dst, bool) {\n\tfor _, dst := range i.Dsts {\n\t\tif dst.DstID == dstID {\n\t\t\treturn dst, true\n\t\t}\n\t}\n\treturn Dst{}, false\n}",
"func (k *PolicyKey) GetDestPort() uint16 {\n\treturn byteorder.NetworkToHost16(k.DestPortNetwork)\n}",
"func (dm *DestinationMixin) GetDestination() (bot.Destination, error) {\n\tif dm.Directory != nil {\n\t\treturn dm.Directory, nil\n\t}\n\n\tif dm.Memory != nil {\n\t\treturn dm.Memory, nil\n\t}\n\n\treturn nil, trace.BadParameter(\"no valid destination exists\")\n}",
"func (o ApplicationSpecDestinationOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationSpecDestination) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (self *Script) getOutputIdxByName(name string) int {\n for i, def := range self.OutputDefs {\n if def.Name == name {\n return i\n }\n }\n return -1\n}",
"func (p *PdfiumImplementation) FPDF_CountNamedDests(request *requests.FPDF_CountNamedDests) (*responses.FPDF_CountNamedDests, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tdocumentHandle, err := p.getDocumentHandle(request.Document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcount := C.FPDF_CountNamedDests(documentHandle.handle)\n\treturn &responses.FPDF_CountNamedDests{\n\t\tCount: uint64(count),\n\t}, nil\n}",
"func (o ApplicationSpecDestinationPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationSpecDestination) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (d *galleryDocument) Dest() (string, error) {\n\trelpath, err := filepath.Rel(\"src\", d.localPath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\n\t\t\t\"can't get relpath for photo `%s`: %w\",\n\t\t\td.localPath,\n\t\t\terr,\n\t\t)\n\t}\n\n\treturn fmt.Sprintf(\"%s.html\", relpath), nil\n}",
"func (f *SAMDGClientForwarder) Destination() string {\n\treturn f.addr.Base32()\n}",
"func getDestination(config *api.Config) string {\n\tdestination := config.Destination\n\tif len(destination) == 0 {\n\t\tdestination = defaultDestination\n\t}\n\treturn destination\n}",
"func (ack *TLCAck) GetDestination() string {\n\treturn ack.Destination\n}",
"func (eventNotifications *EventNotificationsV1) GetDestination(getDestinationOptions *GetDestinationOptions) (result *Destination, response *core.DetailedResponse, err error) {\n\treturn eventNotifications.GetDestinationWithContext(context.Background(), getDestinationOptions)\n}",
"func (o DiskReplicaPairOutput) DestinationDiskId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DiskReplicaPair) pulumi.StringOutput { return v.DestinationDiskId }).(pulumi.StringOutput)\n}",
"func (inst Instance) GetPortalFromName(name string) (Portal, error) {\n\tfor _, p := range inst.portals {\n\t\tif p.name == name {\n\t\t\treturn p, nil\n\t\t}\n\t}\n\n\treturn Portal{}, fmt.Errorf(\"No portal with that name\")\n}",
"func (h HeaderV2) DestAddr() net.Addr { return h.Dest }",
"func (o FolderSinkOutput) Destination() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FolderSink) pulumi.StringOutput { return v.Destination }).(pulumi.StringOutput)\n}",
"func (m *_DF1SymbolMessageFrame) GetDestinationAddress() uint8 {\n\treturn m.DestinationAddress\n}",
"func (o AnalyticsConfigurationStorageClassAnalysisDataExportPtrOutput) Destination() AnalyticsConfigurationStorageClassAnalysisDataExportDestinationPtrOutput {\n\treturn o.ApplyT(func(v *AnalyticsConfigurationStorageClassAnalysisDataExport) *AnalyticsConfigurationStorageClassAnalysisDataExportDestination {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Destination\n\t}).(AnalyticsConfigurationStorageClassAnalysisDataExportDestinationPtrOutput)\n}",
"func (o JobExtractPtrOutput) DestinationFormat() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *JobExtract) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.DestinationFormat\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o FolderSinkOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FolderSink) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}",
"func (o OutputConfigPtrOutput) Destination() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *OutputConfig) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Destination\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o LookupServiceIntegrationResultOutput) DestinationServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupServiceIntegrationResult) string { return v.DestinationServiceName }).(pulumi.StringOutput)\n}",
"func (o *PluginMount) GetDestinationOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Destination, true\n}",
"func (l *Locator) DestDir() string {\n\treturn l.dest\n}",
"func (m *CopyToDefaultContentLocationPostRequestBody) GetDestinationFileName()(*string) {\n return m.destinationFileName\n}",
"func (o AnalyticsConfigurationStorageClassAnalysisDataExportOutput) Destination() AnalyticsConfigurationStorageClassAnalysisDataExportDestinationOutput {\n\treturn o.ApplyT(func(v AnalyticsConfigurationStorageClassAnalysisDataExport) AnalyticsConfigurationStorageClassAnalysisDataExportDestination {\n\t\treturn v.Destination\n\t}).(AnalyticsConfigurationStorageClassAnalysisDataExportDestinationOutput)\n}",
"func ResolveDestination(dest string) *net.TCPAddr {\n\ti := strings.LastIndex(dest, \":\") // important so [::1]:port works\n\tif i < 0 {\n\t\tlog.Errf(\"Destination '%s' is not host:port format\", dest)\n\t\treturn nil\n\t}\n\thost := dest[0:i]\n\tport := dest[i+1:]\n\treturn Resolve(host, port)\n}",
"func (o *TransactionSplit) GetDestinationId() string {\n\tif o == nil || o.DestinationId.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn *o.DestinationId.Get()\n}",
"func GetDestPath(c domain.CLIContext) string {\n\treturn c.String(destPathKey)\n}",
"func (u User) Destination() string {\n\treturn strconv.Itoa(u.ID)\n}",
"func (r *RoleMerge) GetDestination() uint64 {\n\treturn r.Destination\n}",
"func (o ArgoCDExportSpecStoragePvcDataSourcePtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDExportSpecStoragePvcDataSource) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func getListenerImportDest(indexParams string) (cbgt.Dest, error) {\n\n\tvar outerParams struct {\n\t\tParams string `json:\"params\"`\n\t}\n\terr := base.JSONUnmarshal([]byte(indexParams), &outerParams)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error unmarshalling cbgt index params outer: %w\", err)\n\t}\n\n\tvar sgIndexParams base.SGFeedIndexParams\n\terr = base.JSONUnmarshal([]byte(outerParams.Params), &sgIndexParams)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error unmarshalling dbname from cbgt index params: %w\", err)\n\t}\n\n\tbase.DebugfCtx(context.TODO(), base.KeyDCP, \"Fetching listener import dest for %v\", base.MD(sgIndexParams.DestKey))\n\tdestFactory, fetchErr := base.FetchDestFactory(sgIndexParams.DestKey)\n\tif fetchErr != nil {\n\t\treturn nil, fmt.Errorf(\"error retrieving listener for indexParams %v: %v\", indexParams, fetchErr)\n\t}\n\treturn destFactory()\n}",
"func (o JobExtractOutput) DestinationFormat() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobExtract) *string { return v.DestinationFormat }).(pulumi.StringPtrOutput)\n}",
"func (o HTTP2HealthCheckPtrOutput) PortName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *HTTP2HealthCheck) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PortName\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o OutputConfigOutput) Destination() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v OutputConfig) *string { return v.Destination }).(pulumi.StringPtrOutput)\n}",
"func (l *LogSink) Name() string {\n\treturn l.Sink\n}",
"func (l *Locator) DestPkg() string {\n\treturn l.destPkg\n}",
"func (o ApplicationStatusSyncComparedToDestinationOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusSyncComparedToDestination) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o LookupOrganizationSinkResultOutput) Destination() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupOrganizationSinkResult) string { return v.Destination }).(pulumi.StringOutput)\n}",
"func (t ConnTuple) DestEndpoint() string {\n\treturn net.JoinHostPort(t.DestAddress().String(), strconv.Itoa(int(t.Dport)))\n}",
"func (o *TransactionSplit) GetDestinationNameOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.DestinationName.Get(), o.DestinationName.IsSet()\n}",
"func (o HTTP2HealthCheckOutput) PortName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v HTTP2HealthCheck) *string { return v.PortName }).(pulumi.StringPtrOutput)\n}",
"func (m *SendRequest) GetDestString() string {\n\tif m != nil {\n\t\treturn m.DestString\n\t}\n\treturn \"\"\n}",
"func (m *SendRequest) GetDestString() string {\n\tif m != nil {\n\t\treturn m.DestString\n\t}\n\treturn \"\"\n}",
"func (m *SendRequest) GetDestString() string {\n\tif m != nil {\n\t\treturn m.DestString\n\t}\n\treturn \"\"\n}",
"func (m *SendRequest) GetDestString() string {\n\tif m != nil {\n\t\treturn m.DestString\n\t}\n\treturn \"\"\n}",
"func (m *SendRequest) GetDestString() string {\n\tif m != nil {\n\t\treturn m.DestString\n\t}\n\treturn \"\"\n}",
"func (o NamedPortOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v NamedPort) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o DiskReplicaPairOutput) DestinationZoneId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DiskReplicaPair) pulumi.StringOutput { return v.DestinationZoneId }).(pulumi.StringOutput)\n}",
"func (o ApplicationStatusSyncComparedToDestinationPtrOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationStatusSyncComparedToDestination) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Name\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o LookupServiceIntegrationResultOutput) DestinationEndpointId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupServiceIntegrationResult) string { return v.DestinationEndpointId }).(pulumi.StringOutput)\n}",
"func DecodeDestination(dst cty.Value) map[string]interface{} {\n\tdstRef := dst.GetAttr(\"ref\")\n\tout := map[string]interface{}{\n\t\t\"apiVersion\": dstRef.GetAttr(\"apiVersion\").AsString(),\n\t\t\"kind\": dstRef.GetAttr(\"kind\").AsString(),\n\t\t\"name\": dstRef.GetAttr(\"name\").AsString(),\n\t}\n\n\treturn out\n}",
"func (req *connectivityRequestBody) GetDestinationResourceID() string {\n\treturn req.Destination[connectivityResourceID]\n}",
"func (o OutputConfigResponsePtrOutput) Destination() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *OutputConfigResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Destination\n\t}).(pulumi.StringPtrOutput)\n}",
"func (o *TransactionSplit) GetDestinationIban() string {\n\tif o == nil || o.DestinationIban.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DestinationIban.Get()\n}",
"func (d *DestinationClient) GetInstanceDestination(name string) (Destination, error) {\n\n\tvar retval Destination\n\tvar errResponse ErrorMessage\n\n\tresponse, err := d.restyClient.R().\n\t\tSetResult(&retval).\n\t\tSetError(&errResponse).\n\t\tSetPathParams(map[string]string{\n\t\t\t\"name\": name,\n\t\t}).\n\t\tGet(\"/instanceDestinations/{name}\")\n\n\tif err != nil {\n\t\treturn retval, err\n\t}\n\tif response.StatusCode() != 200 {\n\t\terrResponse.statusCode = response.StatusCode()\n\t\treturn retval, errResponse\n\t}\n\treturn retval, nil\n}",
"func (req *connectivityRequestBody) GetDestinationPort() uint {\n\tvalue, err := strconv.ParseUint(req.Destination[connectivityPort], 10, 32)\n\tif err != nil {\n\t\tvalue = 0\n\t}\n\treturn uint(value)\n}",
"func (r *FirehoseDeliveryStream) Destination() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"destination\"])\n}",
"func (h *InputHost) checkDestination(ctx thrift.Context, path string) (string, shared.DestinationType, metrics.ErrorClass, error) {\n\t// talk to metadata\n\tmGetRequest := shared.ReadDestinationRequest{Path: common.StringPtr(path)}\n\tdestDesc, err := h.mClient.ReadDestination(ctx, &mGetRequest)\n\tif err != nil {\n\t\terrC, newErr := common.ConvertDownstreamErrors(h.logger, err)\n\t\treturn \"\", shared.DestinationType_UNKNOWN, errC, newErr\n\t}\n\n\t// Make sure destDesc cannot be nil\n\tif destDesc == nil {\n\t\terrMsg := fmt.Sprintf(\"unable to get destination description from metadata for dst=%v\", path)\n\t\terrC, newErr := common.ConvertDownstreamErrors(h.logger, &cherami.BadRequestError{Message: errMsg})\n\t\treturn \"\", shared.DestinationType_UNKNOWN, errC, newErr\n\t}\n\n\t// Now make sure the destination is writable\n\tif !h.isDestinationWritable(destDesc) {\n\t\terrMsg := fmt.Sprintf(\"Destination is not writable, dst=%v, status=%v\", path, destDesc.GetStatus())\n\t\terrC, newErr := common.ConvertDownstreamErrors(h.logger, &cherami.BadRequestError{Message: errMsg})\n\t\treturn \"\", shared.DestinationType_UNKNOWN, errC, newErr\n\t}\n\n\treturn destDesc.GetDestinationUUID(), destDesc.GetType(), metrics.NoError, nil\n}",
"func (s *AssociationSummary) SetDestinationName(v string) *AssociationSummary {\n\ts.DestinationName = &v\n\treturn s\n}",
"func (o ArgoCDExportSpecStoragePvcDataSourceOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ArgoCDExportSpecStoragePvcDataSource) string { return v.Name }).(pulumi.StringOutput)\n}",
"func (o LookupConnectivityTestResultOutput) Destination() EndpointResponseOutput {\n\treturn o.ApplyT(func(v LookupConnectivityTestResult) EndpointResponse { return v.Destination }).(EndpointResponseOutput)\n}",
"func NewDestination(apiVersion, kind, name string) cty.Value {\n\treturn cty.ObjectVal(map[string]cty.Value{\n\t\t\"ref\": cty.ObjectVal(map[string]cty.Value{\n\t\t\t\"apiVersion\": cty.StringVal(apiVersion),\n\t\t\t\"kind\": cty.StringVal(kind),\n\t\t\t\"name\": cty.StringVal(name),\n\t\t}),\n\t\t\"uri\": cty.NullVal(cty.String),\n\t})\n}",
"func (m *SmsLogRow) GetDestinationNumber()(*string) {\n val, err := m.GetBackingStore().Get(\"destinationNumber\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (c *Client) DescribeApiDestination(ctx context.Context, params *DescribeApiDestinationInput, optFns ...func(*Options)) (*DescribeApiDestinationOutput, error) {\n\tif params == nil {\n\t\tparams = &DescribeApiDestinationInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"DescribeApiDestination\", params, optFns, addOperationDescribeApiDestinationMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*DescribeApiDestinationOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}",
"func (o HTTP2HealthCheckResponsePtrOutput) PortName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *HTTP2HealthCheckResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.PortName\n\t}).(pulumi.StringPtrOutput)\n}",
"func (s *HttpSender) Destination() string {\n\treturn s.endpoint\n}",
"func (o FioSpecVolumeVolumeSourceProjectedSourcesSecretOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceProjectedSourcesSecret) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (o BuildStrategySpecBuildStepsPortsOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsPorts) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (p *PortForwardDelete) ActionName() string {\n\treturn \"overview/stopPortForward\"\n}",
"func (r *Replicator) ReadDestination(ctx thrift.Context, getRequest *shared.ReadDestinationRequest) (*shared.DestinationDescription, error) {\n\treturn r.metaClient.ReadDestination(ctx, getRequest)\n}",
"func (o LookupOrganizationSinkResultOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupOrganizationSinkResult) string { return v.Name }).(pulumi.StringOutput)\n}",
"func (c *MulticastController) IsDest(grpIP net.IP) bool {\n\treturn c.memberTable.get(grpIP)\n}",
"func (d *DataPacket) SourceName() string {\n\ti := 44 //the ending index for the string, because it is 0 terminated\n\tfor i < 108 && d.data[i] != 0 {\n\t\ti++\n\t}\n\treturn string(d.data[44:i])\n}",
"func (o SSLHealthCheckPtrOutput) PortName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *SSLHealthCheck) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PortName\n\t}).(pulumi.StringPtrOutput)\n}",
"func PdhLookupPerfNameByIndex(MachineName string, idx uint32) (string, error) {\n\tvar (\n\t\tmachine uintptr\n\t\tNameBuffer [4096]uint16\n\t\tNameBufferSize = uint32(4096)\n\t)\n\n\tif len(MachineName) != 0 {\n\t\tm, _ := syscall.UTF16PtrFromString(MachineName)\n\t\tmachine = uintptr(unsafe.Pointer(m))\n\t}\n\n\tr, _, _ := procPdhLookupPerfNameByIndex.Call(\n\t\tmachine, // local machine\n\t\tuintptr(idx),\n\t\tuintptr(unsafe.Pointer(&NameBuffer[0])),\n\t\tuintptr(unsafe.Pointer(&NameBufferSize)))\n\n\tif r != 0 {\n\t\treturn \"\", errors.New(codeText[r])\n\t}\n\n\treturn syscall.UTF16ToString(NameBuffer[:]), nil\n}",
"func (o *DestinationRank) Destination(mods ...qm.QueryMod) destinationQuery {\n\tqueryMods := []qm.QueryMod{\n\t\tqm.Where(\"\\\"id\\\" = ?\", o.DestinationID),\n\t}\n\n\tqueryMods = append(queryMods, mods...)\n\n\tquery := Destinations(queryMods...)\n\tqueries.SetFrom(query.Query, \"\\\"destination\\\"\")\n\n\treturn query\n}",
"func DestinationAddr(req *http.Request) (string, int) {\n\thost, strport := splitHost(req.URL.Host)\n\tvar port int\n\tif strport != \"\" {\n\t\tport, _ = strconv.Atoi(strport)\n\t} else {\n\t\tport = SchemeDefaultPort(req.URL.Scheme)\n\t}\n\treturn host, port\n}",
"func (s *AnnotationImportJobItem) SetDestinationName(v string) *AnnotationImportJobItem {\n\ts.DestinationName = &v\n\treturn s\n}",
"func (index *spdIndex) LookupName(idx uint32) (name string, metadata *ipsec.SecurityPolicyDatabases_SPD, exists bool) {\n\tname, meta, exists := index.mapping.LookupName(idx)\n\tif exists {\n\t\tmetadata = index.castMetadata(meta)\n\t}\n\treturn name, metadata, exists\n}",
"func (s *Site) DestDir() string {\n\tif filepath.IsAbs(s.cfg.Destination) {\n\t\treturn s.cfg.Destination\n\t}\n\treturn filepath.Join(s.cfg.Source, s.cfg.Destination)\n}",
"func DestDensity(mat Material, normal, source, dest model3d.Coord3D) float64 {\n\tif a, ok := mat.(AsymMaterial); ok {\n\t\treturn a.DestDensity(normal, source, dest)\n\t} else {\n\t\treturn mat.SourceDensity(normal, dest.Scale(-1), source.Scale(-1))\n\t}\n}",
"func (m *SmsLogRow) SetDestinationName(value *string)() {\n err := m.GetBackingStore().Set(\"destinationName\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (o IopingSpecVolumeVolumeSourceProjectedSourcesSecretOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceProjectedSourcesSecret) *string { return v.Name }).(pulumi.StringPtrOutput)\n}",
"func (c Chat) Destination() string {\n\tret := \"@\" + c.Username\n\tif c.Type != \"channel\" {\n\t\tret = strconv.FormatInt(c.ID, 10)\n\t}\n\treturn ret\n}",
"func (client *WANDSLLinkConfig1) GetDestinationAddress() (NewDestinationAddress string, err error) {\n\treturn client.GetDestinationAddressCtx(context.Background())\n}",
"func (e Edge) DestNodeID() uint64 {\n\tif e.Source != nil {\n\t\treturn e.Destination.ID\n\t} else {\n\t\treturn e.destNodeID\n\t}\n}"
] | [
"0.71764874",
"0.64417017",
"0.61401474",
"0.58218557",
"0.5689246",
"0.5645741",
"0.56405646",
"0.5421518",
"0.53618604",
"0.53404903",
"0.52962935",
"0.52716345",
"0.52392423",
"0.51928115",
"0.5148217",
"0.51150817",
"0.51141936",
"0.51099056",
"0.5099393",
"0.5069328",
"0.50231993",
"0.5004376",
"0.49856943",
"0.4985106",
"0.4981665",
"0.49751875",
"0.4964956",
"0.4948279",
"0.49338794",
"0.49073032",
"0.4895753",
"0.48848704",
"0.48594922",
"0.48484373",
"0.48328853",
"0.4832041",
"0.4827178",
"0.48251948",
"0.4818042",
"0.479768",
"0.47680187",
"0.47483292",
"0.47355098",
"0.4730364",
"0.47148496",
"0.47110865",
"0.46960136",
"0.46947405",
"0.4676099",
"0.46660486",
"0.46576363",
"0.46563885",
"0.46563816",
"0.4655424",
"0.46535203",
"0.4638412",
"0.4638412",
"0.4638412",
"0.4638412",
"0.4638412",
"0.46300322",
"0.46197283",
"0.461233",
"0.46045327",
"0.45978546",
"0.45864525",
"0.45848852",
"0.45638603",
"0.45602462",
"0.45486286",
"0.45378026",
"0.45361528",
"0.45201734",
"0.45136148",
"0.45089313",
"0.45074147",
"0.45034656",
"0.4455973",
"0.44446415",
"0.4431525",
"0.44284508",
"0.4418844",
"0.44141296",
"0.44077793",
"0.439519",
"0.43824574",
"0.4378674",
"0.4378474",
"0.4372192",
"0.4370124",
"0.43664777",
"0.43659434",
"0.4362155",
"0.4360427",
"0.4353473",
"0.43486953",
"0.43482682",
"0.43466973",
"0.434551",
"0.43410352"
] | 0.76940525 | 0 |
/ simpleHillClimbing searches the solution space linearly as the fitness improves, until the fitness worsens instead, returning the index of the first best solution found. size is the length of the problem space. fitness(i) is a function that calculates the fitness for index i. compare(a,b) is a function that evaluates if the fitness has improved or worsened; a positive result means improved, negative means worsened, zero means no change. | func simpleHillClimbing(size int, fitness func(i int)int, compare func(a, b int)int) (int, error) {
bestIndex := 0
value := fitness(bestIndex)
newValue := value
for i := 0; i < size; i++ {
newValue = fitness(i)
check := compare(value, newValue)
switch {
case check < 0:
return bestIndex, nil
case check > 0:
bestIndex = i
value = newValue
}
}
return fitness(size - 1), fmt.Errorf("did not find optimum within first %v solutions", size)
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func fitness(hyp [cityCount]int) (fitness int) {\n\tfor i := 0; i < len(hyp)-1; i++ {\n\t\tx, y := hyp[i], hyp[i+1]\n\t\tfitness -= getDistance(x, y)\n\t}\n\n\tfitness -= getDistance(hyp[len(hyp)-1], hyp[0]) //Return home from last city\n\n\treturn fitness\n}",
"func shortestPathRisk(grid [][]int, gridExpansion int) int {\n\ttargetRow, targetCol := gridTarget(grid, gridExpansion)\n\tvisited := make(map[string]struct{})\n\tpq := make(PriorityQueue, 0)\n\theap.Init(&pq)\n\theap.Push(&pq, &Item{\n\t\tcoords: []int{0, 0},\n\t})\n\n\tfor len(pq) >= 1 {\n\t\t// take elem\n\t\tcurrP := heap.Pop(&pq).(*Item)\n\n\t\tvisited[keyS(currP.coords[0], currP.coords[1])] = struct{}{}\n\t\t// fmt.Printf(\"visited %d, %d\\n\", currP.coords[0], currP.coords[1])\n\n\t\tif currP.coords[0] == targetRow && currP.coords[1] == targetCol {\n\t\t\treturn currP.costSoFar\n\t\t}\n\n\t\t// find all possible positions and push them to the Q\n\t\trow := currP.coords[0]\n\t\tcol := currP.coords[1]\n\t\tfor _, c := range [][]int{\n\t\t\t{row - 1, col},\n\t\t\t{row, col + 1},\n\t\t\t{row + 1, col},\n\t\t\t{row, col - 1},\n\t\t} {\n\t\t\tif _, ok := visited[keyS(c[0], c[1])]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\trisk, err := gridVal(grid, gridExpansion, c[0], c[1])\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tnewPos := &Item{\n\t\t\t\tcoords: c,\n\t\t\t\tcostSoFar: currP.costSoFar + risk,\n\t\t\t\tpriority: currP.costSoFar + risk + heuristicCost(c[0], c[1], targetRow, targetCol),\n\t\t\t}\n\n\t\t\theap.Push(&pq, newPos)\n\t\t}\n\t}\n\n\treturn 0\n}",
"func scoreACell(x int, y int, myX int, myY int, bombsOnTheFloor []Bomb, myReach int, floor [WIDTH][HEIGHT]int) Cell {\n if (myX != x || myY != y) { // I'm not already standing here\n if !canIBeHere(x, y, 1, bombsOnTheFloor, floor) {return Cell{score: WALL_SCORE, distance: TOO_FAR}} // cannot move to here next turn\n }\n moves, maybe := canIGoToThere(myX, myY, myX, myY, x, y, SEARCH_DEPTH_LIMIT, bombsOnTheFloor, floor)\n if !maybe {return Cell{score: WALL_SCORE, distance: TOO_FAR}} // cannot get here, even after multiple turns\n if willIDieHere(x, y, bombsOnTheFloor, floor) {return Cell{score: DANGER_SCORE, distance: TOO_FAR}} // does not account for time left on the bomb, could optimize here rather than walling it off\n score := 0\n for i := 0; i < myReach; i++ {\n if x+i < WIDTH && floor[x+i][y] >= BOX {score++}\n if x-i > 0 && floor[x-i][y] >= BOX {score++}\n if y+i < HEIGHT && floor[x][y+i] >= BOX {score++}\n if y-i > 0 && floor[x][y-i] >= BOX {score++}\n }\n if floor[x][y] > BOX {score++} // there's an item in the box\n return Cell{score: score, distance: moves}\n}",
"func (s *solution) SmallestUnreachable() int {\n\t// Write your code here\n\tpowerSetHelper := func (original []int) [][]int {\n\t\tpowerSetSize := int(math.Pow(2, float64(len(original))))\n\t\tresult := make([][]int, 0, powerSetSize)\n\n\t\tvar index int\n\t\tfor index < powerSetSize {\n\t\tvar subSet []int\n\n\t\tfor j, elem := range original {\n\t\tif index& (1 << uint(j)) > 0 {\n\t\tsubSet = append(subSet, elem)\n\t}\n\t}\n\t\tresult = append(result, subSet)\n\t\tindex++\n\t}\n\t\treturn result\n\t}\n\n\n\tnbills := s.GetNumBills()\n\tfmt.Println(\"number of bills\", nbills)\n\tbills := make([]int, nbills)\n\tfor i := 0; i < nbills ; i++ {\n\t\tbills[i] = s.GetBill(i)\n\t}\n\tfmt.Println(\"Bills\", bills)\n\tprice := s.GetPrice()\n\tfmt.Println(\"Price\", price)\n\tpayment := s.GetPayment()\n\tfmt.Println(\"payment\", payment)\n\tdiff := payment - price\n\tfmt.Println(\"diff\", diff)\n\n\tp := powerSetHelper(bills)\n\tmax := 0\n\tmaxIndex := -1\n\tfor i,v := range p {\n\t\tsum := 0\n\t\tfor _,b := range v {\n\t\t\tsum += b\n\t\t}\n\t\tif sum > max {\n\t\t\tmax = sum\n\t\t\tmaxIndex = i\n\t\t}\n\t}\n\tfmt.Println(p[maxIndex])\n\n\treturn diff - max\n}",
"func heuristic(goal *maze.CellIndex, current *maze.CellIndex) uint64 {\n\treturn uint64((goal.Row-current.Row)*(goal.Row-current.Row) + (goal.Col-current.Col)*(goal.Col-current.Col))\n}",
"func Solve(sizeBucketOne,\n\tsizeBucketTwo,\n\tgoalAmount int,\n\tstartBucket string) (goalBucket string,\n\tnumSteps,\n\totherBucketLevel int,\n\te error) {\n\n\tif sizeBucketOne == 0 || sizeBucketTwo == 0 {\n\t\treturn \"\", 0, 0, errors.New(\"invalid bucket size\")\n\t}\n\n\tif goalAmount == 0 {\n\t\treturn \"\", 0, 0, errors.New(\"invalid goal amount\")\n\t}\n\n\tif startBucket != \"one\" && startBucket != \"two\" {\n\t\treturn \"\", 0, 0, errors.New(\"invalid start bucket name\")\n\t}\n\n\tvar moves int\n\tvar lastPoured bool\n\n\tbucketOne := bucket{\n\t\tname: \"one\",\n\t\tsize: sizeBucketOne,\n\t}\n\n\tbucketTwo := bucket{\n\t\tname: \"two\",\n\t\tsize: sizeBucketTwo,\n\t}\n\n\tif startBucket == \"one\" {\n\t\tfillBucket(&bucketOne, &moves, &lastPoured)\n\t\tif goalAmount == bucketTwo.size {\n\t\t\tfillBucket(&bucketTwo, &moves, &lastPoured)\n\t\t\treturn bucketTwo.name, moves, bucketOne.current, nil\n\t\t}\n\t}\n\n\tif startBucket == \"two\" {\n\t\tfillBucket(&bucketTwo, &moves, &lastPoured)\n\t\tif goalAmount == bucketOne.size {\n\t\t\tfillBucket(&bucketOne, &moves, &lastPoured)\n\t\t\treturn bucketOne.name, moves, bucketTwo.current, nil\n\t\t}\n\t}\n\n\tfor goalAmount != bucketOne.current && goalAmount != bucketTwo.current {\n\t\tif bucketOne.current != 0 && bucketTwo.current != bucketTwo.size && !lastPoured {\n\t\t\tpourBucket(&bucketOne, &bucketTwo, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\t\tif bucketTwo.current != 0 && bucketOne.current != bucketOne.size && !lastPoured {\n\t\t\tpourBucket(&bucketTwo, &bucketOne, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\n\t\tif bucketOne.current == bucketOne.size && bucketTwo.current != 0 {\n\t\t\temptyBucket(&bucketOne, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\n\t\tif bucketTwo.current == bucketTwo.size && bucketOne.current != 0 {\n\t\t\temptyBucket(&bucketTwo, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\n\t\tif bucketOne.current == 0 && bucketTwo.size-bucketTwo.current != 0 {\n\t\t\tfillBucket(&bucketOne, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\n\t\tif bucketTwo.current == 0 && bucketOne.size-bucketOne.current != 0 {\n\t\t\tfillBucket(&bucketTwo, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\n\t\treturn \"\", 0, 0, errors.New(\"no solution\")\n\n\t}\n\n\tif goalAmount == bucketOne.current {\n\t\treturn bucketOne.name, moves, bucketTwo.current, nil\n\t}\n\n\tif goalAmount == bucketTwo.current {\n\t\treturn bucketTwo.name, moves, bucketOne.current, nil\n\t}\n\n\treturn \"\", 0, 0, errors.New(\"no solution\")\n\n}",
"func solution(knows func(a int, b int) bool) func(n int) int {\n\treturn func(n int) int {\n\t\ts := &stack{}\n\t\tfor i := 0; i< n; i++ {\n\t\t\ts.push(i)\n\t\t}\n\n\t\t//push them all on stack.\n\t\t//Selectively knock off one by one using one comparision.\n\t\t//if a knows b -> a cant be celebrity but b potentially is.\n\t\t//push b or a accordingly.\n\n\t\t//At the end - have on element left over due eleminations, this may\n\t\t//maynot be the celeb. Do one round of validation before declaring.\n\t\tfor len(*s) > 1 {\n\t\t\ta := s.pop()\n\t\t\tb := s.pop()\n\n\t\t\tif knows(a, b) {\n\t\t\t\ts.push(b)\n\t\t\t} else {\n\t\t\t\ts.push(a)\n\t\t\t}\n\t\t}\n\n\t\tfmt.Printf(\"length: %v\\n\", len(*s))\n\t\t//at this point we expect only one element in stack.\n\t\tc := s.pop()\n\n\n\n\t\t//double check if c is the celebrity.\n\t\tfor i:=0; i< n;i++ {\n\t\t\tif i != c && (knows(c, i) || !knows(i, c)) {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t}\n\t\treturn c\n\t}\n}",
"func getBest(population []Organism) Organism {\r\n\tbest := 0.0\r\n\tindex := 0\r\n\tfor i := 0; i < len(population); i++ {\r\n\t\tif population[i].Fitness > best {\r\n\t\t\tindex = i\r\n\t\t\tbest = population[i].Fitness\r\n\t\t}\r\n\t}\r\n\treturn population[index]\r\n}",
"func brute_force_worker(points [][]float64, ind_chan chan []int, results chan []int) {\n\tmin_inds := make([]int, len(points))\n\tvar min_len float64 = math.Inf(1)\n\t// keep pulling until it's over\n\tfor {\n\t\tinds, ok := <-ind_chan\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tcur_len := PathLengthInds(points, inds)\n\t\t// find the winner\n\t\tif cur_len < min_len {\n\t\t\tmin_len = cur_len\n\t\t\tcopy(min_inds, inds)\n\t\t}\n\t}\n\n\tresults <- min_inds\n}",
"func (pp Points) LocalBeamSearch(k int, iterations int) PointsSolution {\r\n\tvar solution PointsSolution\r\n\r\n\t// Bounds and default values\r\n\tif k < 1 || k > 200 {\r\n\t\tk = 200\r\n\t}\r\n\r\n\tif iterations < 1 || iterations > 3000 {\r\n\t\titerations = 2000\r\n\t}\r\n\r\n\tbest := make(chan Points)\r\n\r\n\t// Each point will perform hill climbing in its neighbourhood\r\n\troutine := func(pp Points) {\r\n\r\n\t\tfor i := 0; i < iterations; i += 1 {\r\n\t\t\tpp2 := pp.Neighbour()\r\n\t\t\tif pp2.Len() < pp.Len() {\r\n\t\t\t\tcopy(pp, pp2)\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tbest <- pp\r\n\t}\r\n\r\n\t// Select k random points and perform hill climbing concurrently\r\n\tfor i := 0; i < k; i++ {\r\n\t\tgo routine(pp.Random())\r\n\t}\r\n\r\n\tfor i := 0; i < k; i++ {\r\n\t\tkeep := make(Points, len(pp))\r\n\t\tcopy(keep, <-best)\r\n\t\tsolution = append(solution, keep)\r\n\t}\r\n\r\n\t// Send every solution found for visualization\r\n\tsort.Sort(solution)\r\n\r\n\treturn solution\r\n}",
"func fitnessTester(f PricingProblem, seed int64) {\n\trand.Seed(seed)\n\n\tprices := make([]float64, numberOfGoods)\n\tnewPrices := make([]float64, numberOfGoods)\n\n\tfor i := 0; i < numberOfGoods; i++ {\n\t\tprices[i] = rand.Float64() * 10\n\t}\n\n\tbestRevenue := f.evaluate(prices)\n\tnewRevenue := 0.0\n\n\tfor i := 0; i < 100; i++ {\n\t\t// fmt.Printf(\"Best revenue so far: %v\\n\", bestRevenue)\n\n\t\t// Generate more!\n\t\tfor j := 0; j < numberOfGoods; j++ {\n\t\t\tnewPrices[j] = rand.Float64() * 10\n\t\t}\n\n\t\tnewRevenue = f.evaluate(newPrices)\n\t\tif newRevenue > bestRevenue {\n\t\t\tfor j := 0; j < len(prices); j++ {\n\t\t\t\tprices[j] = newPrices[j]\n\t\t\t}\n\t\t\tbestRevenue = newRevenue\n\t\t}\n\t}\n\n\tfmt.Printf(\"Prices: %v\\nFinal best revenue: %v\", prices, bestRevenue)\n}",
"func TestSmall(t *testing.T) {\n\titems := []Item{\n\t\tItem{Sig: []float64{0, 0}, ID: \"57\"},\n\t\tItem{Sig: []float64{1, 1}, ID: \"28\"},\n\t\tItem{Sig: []float64{2, 2}, ID: \"48\"},\n\t\tItem{Sig: []float64{3, 3}, ID: \"42\"},\n\t}\n\n\ttarget := []float64{5, 5}\n\n\titemsCopy := make([]Item, len(items))\n\tcopy(itemsCopy, items)\n\n\tvp := New(itemsCopy)\n\n\tcoords1, distances1 := vp.Search(target, 3)\n\tcoords2, distances2 := nearestNeighbours(target, items, 3)\n\n\tt.Logf(\"Coords 1: %+v Distances %+v \\n\", coords1, distances1)\n\tt.Logf(\"Coords 2: %+v Distances %+v \\n\", coords2, distances2)\n\n}",
"func (d *Organism) calcFitness(target []byte) {\r\n\tscore := 0\r\n\tfor i := 0; i < len(d.DNA); i++ {\r\n\t\tif d.DNA[i] == target[i] {\r\n\t\t\tscore++\r\n\t\t}\r\n\t}\r\n\td.Fitness = float64(score) / float64(len(d.DNA))\r\n\treturn\r\n}",
"func minCostClimbingStairs(cost []int) int {\n\tn := len(cost)\n\tsums := make([]int, n)\n\tfor i, c := range cost {\n\t\tif i >= 2 {\n\t\t\tif sums[i-1] < sums[i-2] {\n\t\t\t\tsums[i] = sums[i-1] + c\n\t\t\t} else {\n\t\t\t\tsums[i] = sums[i-2] + c\n\t\t\t}\n\t\t} else {\n\t\t\tsums[i] = c\n\t\t}\n\t}\n\n\tif sums[n-2] < sums[n-1] {\n\t\treturn sums[n-2]\n\t}\n\n\treturn sums[n-1]\n}",
"func main() {\n\tmedianFinder := Constructor()\n\tmedianFinder.AddNum(40)\n\tmedianFinder.AddNum(12)\n\tmedianFinder.AddNum(16)\n\tmedianFinder.AddNum(14)\n\tmedianFinder.AddNum(35)\n\tmedianFinder.AddNum(19)\n\tmedianFinder.AddNum(34)\n\tmedianFinder.AddNum(35)\n\tmedianFinder.AddNum(28)\n\tmedianFinder.AddNum(35)\n\tmedianFinder.AddNum(26)\n\tmedianFinder.AddNum(6)\n\tmedianFinder.AddNum(8)\n\tmedianFinder.AddNum(2)\n\tmedianFinder.AddNum(14)\n\tmedianFinder.AddNum(25)\n\tmedianFinder.AddNum(25)\n\tmedianFinder.AddNum(4)\n\tmedianFinder.AddNum(33)\n\tmedianFinder.AddNum(18)\n\tmedianFinder.AddNum(10)\n\tmedianFinder.AddNum(14)\n\tfmt.Println(medianFinder.FindMedian())\n\n\tfmt.Println(bigHeapifyFromUp([]int{6, 19, 26, 12, 16, 14}, 0, 5))\n}",
"func HillClimbing(MakeGenome GenomeMaker) GA {\n\tvar ga = GA{\n\t\tMakeGenome: MakeGenome,\n\t\tTopology: Topology{\n\t\t\tNPopulations: 1,\n\t\t\tNIndividuals: 1,\n\t\t},\n\t\tModel: ModMutationOnly{\n\t\t\tNChosen: 1,\n\t\t\tSelector: SelElitism{},\n\t\t\tStrict: true,\n\t\t},\n\t}\n\tga.Initialize()\n\treturn ga\n}",
"func MakeOptimalMove(b *Board) {\n\taiPlayer := b.NextPlayer()\n\tbranch_evals := func() []Player {\n\t\tout := []Player{}\n\t\tfor _, branch := range b.possibleMoves() {\n\t\t\tout = append(out, branch.score())\n\t\t}\n\t\treturn out\n\t}()\n\n\tvar choice Player\n\tswitch aiPlayer {\n\tcase Player1:\n\t\tif playerInList(Player1, branch_evals) {\n\t\t\tchoice = Player1\n\t\t} else if playerInList(NoPlayer, branch_evals) {\n\t\t\tchoice = NoPlayer\n\t\t} else {\n\t\t\tchoice = Player2\n\t\t}\n\tcase Player2:\n\t\tif playerInList(Player2, branch_evals) {\n\t\t\tchoice = Player2\n\t\t} else if playerInList(NoPlayer, branch_evals) {\n\t\t\tchoice = NoPlayer\n\t\t} else {\n\t\t\tchoice = Player1\n\t\t}\n\t}\n\tfor i, sq := range b.possibleMoves() {\n\t\tif sq.score() == choice {\n\t\t\tb.Set(b.vacantSquares()[i])\n\t\t\treturn\n\t\t}\n\t}\n}",
"func searchBestOpenings(x, y *int) {\n bestPathLen := 0\n bestTurnCnt := 0\n bestStart := 2\n bestFinish := 2\n saveDelay := getInt(&delay) // don't print updates while solving for best openings\n setInt(&delay, 0)\n\n for i := 0; i < width; i++ {\n for j := 0; j < width; j++ {\n start := 2*(i + 1)\n finish := 2*(j + 1)\n *x = start\n *y = finish\n if getMaze(getInt(&begX), start - 1) != wall && getMaze(getInt(&begX), start + 1) != wall {; continue; }\n if getMaze(getInt(&endX), finish - 1) != wall && getMaze(getInt(&endX), finish + 1) != wall {; continue; }\n createOpenings(x, y)\n solveMaze(x, y)\n if getInt(&pathLen) > bestPathLen ||\n (getInt(&pathLen) == bestPathLen &&\n getInt(&turnCnt) > bestTurnCnt) {\n bestStart = start\n bestFinish = finish\n bestTurnCnt = getInt(&turnCnt)\n bestPathLen = getInt(&pathLen)\n setInt(&solveLength, getInt(&pathLen))\n }\n restoreMaze()\n deleteOpenings()\n incInt(&numSolves)\n }\n }\n addInt(&sumsolveLength, getInt(&solveLength))\n if viewFlag {\n setInt(&delay, saveDelay) // only restore delay value if view solve flag is set\n }\n *x = bestStart\n *y = bestFinish\n createOpenings(x, y)\n}",
"func (h *hashRing) FindBucketGivenSize(key uint64, size int) int {\n\treturn int(jump.Hash(key, size))\n}",
"func minimumMoves(grid []string, startX int32, startY int32, goalX int32, goalY int32) int32 {\n\t// Make 2D slice\n\tresult := make([][]int32, len(grid))\n\tfor i := 0; i < len(grid); i++ {\n\t\tresult[i] = make([]int32, len(grid))\n\t}\n\n\tresult[startX][startY] = 0\n\txy := XY{startX, startY, \"horizontal\"}\n\tqueue = append(queue, xy)\n\txy2 := XY{startX, startY, \"Veritical\"}\n\tqueue = append(queue, xy2)\n\n\tfor {\n\t\tif len(queue) == 0 {\n\t\t\tbreak\n\t\t} else if len(queue) > 0 && queue[0].HV == \"horizontal\" {\n\t\t\tresult = Veritical(grid, result, queue[0].X, queue[0].Y)\n\t\t\tqueue = queue[1:]\n\t\t} else if len(queue) > 0 && queue[0].HV == \"Veritical\" {\n\t\t\tresult = Horizontal(grid, result, queue[0].X, queue[0].Y)\n\t\t\tqueue = queue[1:]\n\t\t}\n\t}\n\n\treturn result[goalX][goalY]\n}",
"func BFS(mat [][]int, startPos Position, state State, searchVal, maxDepth int) BFSResult {\n\tres := BFSResult{foodDepth: maxDepth, nearestSnakeDepth: maxDepth}\n\tqueue := list.New()\n\tqueue.PushBack(BFSNode{startPos, 1})\n\tmatrix := duplicateMatrix(mat)\n\t//fmt.Println(matrix)\n\tfor queue.Len() > 0 {\n\t\t// Get next element\n\t\tcurr := queue.Front()\n\t\tnode := curr.Value.(BFSNode)\n\t\tpos := node.pos\n\t\tqueue.Remove(curr)\n\n\t\t// Max depth reached\n\t\tif node.depth > maxDepth { break }\n\n\t\t// Test for in bounds\n\t\tif !isPositionInBounds(pos, state) { continue }\n\n\t\t// Don't look at the same value\n\t\tif matrix[pos.y][pos.x] == 1 { continue }\n\n\t\t// Test if we found closest enemy position\n\t\tif res.nearestSnakeDepth == maxDepth {\n\t\t\tif matrix[pos.y][pos.x] == 2 {\n\t\t\t\tres.nearestSnakeDepth = int(math.Abs(float64(pos.x) - float64(startPos.x)))\n\t\t\t\tres.nearestSnakeDepth = int(math.Abs(float64(pos.y) - float64(startPos.y)))\n\t\t\t}\n\t\t}\n\n\t\tif !isValidPosition(pos, state) { continue }\n\n\t\t// Test if we found the closes food position\n\t\tif res.foodDepth == maxDepth {\n\t\t\tif matrix[pos.y][pos.x] == 3 {\n\t\t\t\tres.foodDepth = int(math.Abs(float64(pos.x) - float64(startPos.x)))\n\t\t\t\tres.foodDepth += int(math.Abs(float64(pos.y) - float64(startPos.y)))\n\t\t\t}\n\t\t}\n\n\t\t// Mark as visited\n\t\tmatrix[pos.y][pos.x] = 1\n\n\t\t// Add next elements to queue\n\t\taddPositionsToQueue(queue, matrix, pos, state, node.depth + 1)\n\n\t\t// Update max depth\n\t\tif node.depth + 1 > res.emptySpaceDepth {\n\t\t\tres.emptySpaceDepth = node.depth + 1\n\t\t}\n\t}\n\n\treturn res\n}",
"func optimizeWorker(startIdx int, recipeesPtr *[]Recipee, currentOptimum int, fixedCalories bool) int {\n\trecipees := *recipeesPtr\n\n\tconst maxTeaspoons = 100\n\tconst fixedCaloriesAmount = 500\n\tnVariables := len(recipees)\n\tif startIdx >= nVariables-1 {\n\t\ttotalTeaspoon := 0\n\t\tfor i := 0; i < nVariables-1; i++ {\n\t\t\ttotalTeaspoon += recipees[i].teaspoons\n\t\t}\n\t\tif totalTeaspoon > maxTeaspoons {\n\t\t\treturn -math.MaxInt64\n\t\t}\n\t\trecipees[startIdx].teaspoons = maxTeaspoons - totalTeaspoon\n\n\t\tmix := mixRecipees(recipeesPtr)\n\t\tif fixedCalories && mix.calories != fixedCaloriesAmount {\n\t\t\treturn -math.MaxInt64\n\t\t}\n\t\treturn evaluate(mix)\n\t}\n\n\tcurrentLocalOptimum := 0\n\tfor i := startIdx; i < nVariables-1; i++ {\n\t\tfor t := 0; t < maxTeaspoons; t++ {\n\t\t\trecipees[i].teaspoons = t\n\t\t\tcurrentLocalOptimum = optimizeWorker(startIdx+1, recipeesPtr, currentOptimum, fixedCalories)\n\n\t\t\ttotalTeaspoon := 0\n\t\t\tfor _, r := range recipees {\n\t\t\t\ttotalTeaspoon += r.teaspoons\n\t\t\t}\n\t\t\tif totalTeaspoon > maxTeaspoons {\n\t\t\t\t//fmt.Printf(\"%*s i(%d) t(%2d) totTsp(%d) <-- %v\\n\", 2*(startIdx+1), \"*\", i, t, totalTeaspoon, recipees)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif currentLocalOptimum > currentOptimum {\n\t\t\t\tfor j := startIdx; j < nVariables; j++ {\n\t\t\t\t\trecipees[j].optimalTeaspons = recipees[j].teaspoons\n\t\t\t\t}\n\t\t\t\t// if startIdx == 0 {\n\t\t\t\t// \tfmt.Printf(\"%*s i(%d) t(%2d) *NEW obj(%12d) > %12d <-- %v\\n\", startIdx+1, \"*\", i, t, currentLocalOptimum, currentOptimum, recipees)\n\t\t\t\t// }\n\n\t\t\t\tcurrentOptimum = currentLocalOptimum\n\t\t\t} else {\n\t\t\t\t// if startIdx == 0 {\n\t\t\t\t// \tfmt.Printf(\"%*s i(%d) t(%d) obj(%d) <= %d <-- %v\\n\", startIdx+1, \"*\", i, t, currentLocalOptimum, currentOptimum, recipees)\n\t\t\t\t// }\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := startIdx; i < nVariables; i++ {\n\t\trecipees[i].teaspoons = recipees[i].optimalTeaspons\n\t}\n\treturn currentOptimum\n}",
"func main() {\n\t// 1, 7, 2, 3, 8, 1, 1 : collide two max stones : 7, 8 here remaining 1 . 1 will added\n\t// 1, 2, 3, 1, 1, 1 : collide 3 and 2 and remaining 1 will be added\n\t// 1, 1, 1, 1, 1 : collide 1, 1 nothing will be added\n\t// 1 1 1 : collide 1 and 1 nothing will be added\n\t// 1 will be answer\n\ta := []int{1, 7, 2, 3, 8, 1, 1}\n\n\t/*\n\t\t// this works too\n\t\th := &IntHeap{}\n\t\theap.Init(h)\n\t\tfor _, item := range a {\n\t\t\theap.Push(h, item)\n\t\t}\n\t*/\n\n\thh := IntHeap(a)\n\th := &hh\n\theap.Init(h)\n\tfor h.Len() >= 2 {\n\t\telement1 := heap.Pop(h)\n\t\telement2 := heap.Pop(h)\n\t\titem1 := element1.(int)\n\t\titem2 := element2.(int)\n\n\t\tfmt.Println(\"item1 popped=\", item1)\n\t\tfmt.Println(\"item2 popped=\", item2)\n\n\t\tif item1 > item2 {\n\t\t\theap.Push(h, item1-item2)\n\t\t}\n\t}\n\tif h.Len() > 0 {\n\t\tfmt.Println(\"answer=\", heap.Pop(h))\n\t} else {\n\t\tfmt.Println(\"answer is empty\")\n\t}\n\n}",
"func BestSquare(size int) (nrow, ncol int) {\n\tnrow = -1 // not found\n\tncol = -1 // not found\n\tfor x := 1; x <= size; x++ {\n\t\tif (x * x) >= size {\n\t\t\tif (x * x) == size {\n\t\t\t\tnrow = x\n\t\t\t\tncol = x\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor y := x; y >= 1; y-- {\n\t\t\t\tif (x * y) == size {\n\t\t\t\t\tnrow = x\n\t\t\t\t\tncol = y\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}",
"func GAsFitnessMessure(g *GAs) {\n\tfor i := 0; i < g.Option.PopSize; i++ {\n\t\tf := g.Option.Fitness(&g.Population[i])\n\t\tg.Fitness[i] = f\n\t}\n\ti := FindArgMax(g.Fitness)\n\tif g.Generation == 0 || g.Fitness[i] > g.BestIndividualFieness {\n\t\tg.BestIndividual = g.Population[i].Copy()\n\t\tg.BestIndividualFieness = g.Fitness[i]\n\t}\n\tif g.Option.MaintainTheBestIndividual {\n\t\ti := FindArgMin(g.Fitness)\n\t\tg.Population[i] = g.BestIndividual.Copy()\n\t\tg.Fitness[i] = g.BestIndividualFieness\n\t}\n}",
"func (c *Float64sCache) index(size int) int {\n\tindex := -1\n\tfor i := range c.ps {\n\t\tif c.ps[i].size < size {\n\t\t\tcontinue\n\t\t}\n\t\tif c.ps[i].size == size {\n\t\t\tindex = i\n\t\t}\n\t\tbreak\n\t}\n\treturn index\n}",
"func solution(knows func(a int, b int) bool) func(n int) int {\n\treturn func(n int) int {\n\t\ti := 0\n\t\tj := 0\n\n\t\tindeg := make([]int, n)\n\n\t\tfor i = 0; i < n; i++ {\n\t\t\tfor j = 0; j< n; j++ {\n\t\t\t\tif knows(i, j) && i != j{\n\t\t\t\t\tindeg[i]--\n\t\t\t\t\tindeg[j]++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor index, val := range indeg {\n\t\t\tif val == n-1 {\n\t\t\t\treturn index\n\t\t\t}\n\t\t}\n\n\t\treturn -1\n\t}\n}",
"func Minimax(state TSState, engine TSEngine) (float64, Move) {\n return minimaxHelper(state, engine, math.Inf(-1), math.Inf(1))\n}",
"func minimumBribes(q []int32) {\n\tvar bribes = 0\n\n\t// Iterate from the last element\n\tfor i := int32(len(q) - 1); i >= 0; i-- {\n\n\t\t// Since the original array was a sorted number array of 1 to n with interval of 1,\n\t\t// For example:\n\t\t// In Test Case of {2, 5, 1, 3, 4}\n\t\t// The element 5 (with original position of 5, index of 4) can only be placed up to position 3, index of 2\n\t\t// On this case, element 5 is placed on index 1 or position 2, so we need to find whether the position is valid or not\n\t\t// KEY: The difference must not be greater than 2\n\t\t// So, we substract the current position (which is array index + 1) from the current value, which is 5\n\t\t// and the difference = 5 - (1 + 1) = 5 - 2 = 3, indicated that there was an invalid move\n\t\tif q[i]-int32(i+1) > 2 {\n\t\t\tfmt.Println(\"Too chaotic\")\n\t\t\treturn\n\t\t}\n\n\t\t// Here, we need to find out how many briberies were happened, knowing that the bribery limit is 2.\n\t\t// So, we need to ensure that the two queue number in front of the current number is always lower than the current number.\n\t\t// For example:\n\t\t//\n\t\t// Under the Test Case of {2, 1, 5, 3, 4}\n\t\t// Let's say we are checking the first element from the back, which is 4.\n\t\t// We expect that the two people in front of number 4 has lower number\n\t\tvar max int32\n\t\t// i: 4 -> Is 0 >= 4 - 2? false, then max = 2\n\t\t// i: 3 -> Is 0 >= 3 - 2? false, then max = 1\n\t\t// i: 2 -> Is 0 >= 5 - 2? false, then max = 3\n\t\t// i: 1 -> Is 0 >= 1 - 2? true, then max = 0\n\t\t// i: 0 -> Is 0 >= 0 - 2? true, then max = 0\n\n\t\t// To prevent looping from negative index\n\t\tif 0 >= q[i]-2 {\n\t\t\tmax = 0\n\t\t} else {\n\t\t\tmax = q[i] - 2\n\t\t}\n\n\t\t// Loop through the ranged specification\n\t\t// The first element from the back is 4, and the two in front of it is 2.\n\t\t// We start from the 2nd index element.\n\t\t// The element at 2nd index is 5, and 5 is greater than the element at 4th index which is 4.\n\t\t// This indicated that number 5 had bribed number 4.\n\t\t// On the next step, the 3rd index contains number 3, and 3 is lower than 4. That means no bribery happened.\n\t\t//\n\t\t// Then we check the second element from the back, which is 3.\n\t\t// The second element from the back is placed at 3rd index position, so we loop through 1st index position.\n\t\t// The element at 1st index is 1, and 1 is not greater than 3. No bribery happened.\n\t\t// Then we check the element at 2nd index, which is 5. 5 is greater than 3, that means 5 had bribed 3.\n\t\tfor j := max; j < i; j++ {\n\t\t\t// max: 2; i: 4\n\t\t\t// 5 > 4? true, bribes++\n\t\t\t// 3 > 4? false\n\t\t\t//\n\t\t\t// max: 1; i: 3\n\t\t\t// 1 > 3? false\n\t\t\t// 5 > 3? true, bribes++\n\t\t\t//\n\t\t\t// max: 3; i: 2\n\t\t\t// no checking\n\t\t\t//\n\t\t\t// max: 0; i: 1\n\t\t\t// 2 > 1? true, bribes++\n\t\t\t//\n\t\t\t// max: 0; i: 0\n\t\t\t// no checking\n\n\t\t\tif q[j] > q[i] {\n\t\t\t\tbribes++\n\t\t\t}\n\t\t}\n\t}\n\t// Expected result: 3\n\tfmt.Println(bribes)\n}",
"func findCheapestPrice(n int, flights [][]int, src int, dst int, K int) int {\n \n}",
"func (self *BRA) buildSolution (path []*Node, dists [][]int, value int, cnode *Node) (Solution, int, int){\n\n\t// Init the part of the solution that remains the same\n\tindex := int((1 - self.beta) * float64(len(path)))\n\tsol := path[:index]\n\tval, del := evaluate(sol, dists, value, cnode)\n\n\t// Init options and current node\n\tvar currentNode Node = *cnode\n\tvar newNode Node\n\toptions := path[index:]\n\n\t// Execute a greedy construction of the new solution\n\tfor len(options) > 0 {\n\t\t// Sort options for increasing cost (i.e., arrival + delay)\n\t\tsort.Slice(options, func (i int, j int) bool {\n\t\t\treturn options[i].Cost(currentNode, dists, val) < options[j].Cost(currentNode, dists, val)\n\t\t})\n\n\t\t// Pick a new node using a quasi-geometric\n\t\tpos := self.biased_random_selection(len(options))\n\t\tnewNode = *options[pos]\n\n\t\t// Pick the best and make it current node\n\t\tval = int(math.Max(float64(val + dists[currentNode.id][newNode.id]), float64(newNode.open)))\n\t\tdel += int(math.Max(0, float64(val - newNode.close)))\n\t\tsol = append(sol, options[pos])\n\t\tcurrentNode = newNode\n\t\toptions = append(options[:pos], options[pos + 1:]...)\n\t}\n\t// Return the new solution\n\treturn sol, val, del\n}",
"func minSideJumps(obstacles []int) int {\n\tvar lanes [4][]int\n\tfor i, v := range obstacles {\n\t\tlanes[v] = append(lanes[v], i)\n\t}\n\n\tlane := 2\n\tr := 0\n\tvar nextObsIndexes [4]int\n\n\tfor i := 0; i < len(obstacles)-1; i++ {\n\t\tcur := obstacles[i]\n\t\tnextObsIndexes[cur]++\n\t\tnext := obstacles[i+1]\n\t\tif next != lane {\n\t\t\tcontinue\n\t\t}\n\n\t\tr++\n\t\tdistance := math.MinInt32\n\t\tfor v := 1; v <= 3; v++ {\n\t\t\tif v == lane || cur == v {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tj := nextObsIndexes[v]\n\t\t\tif j >= len(lanes[v]) {\n\t\t\t\treturn r\n\t\t\t}\n\n\t\t\tif lanes[v][j]-i > distance {\n\t\t\t\tdistance = lanes[v][j] - i\n\t\t\t\tlane = v\n\t\t\t}\n\t\t}\n\t}\n\n\treturn r\n}",
"func (f *FibonacciHeap) consolidate() {\n\tvar used = make([]*Node, f.size) //We use a slice to track collisions in node.degree\n\tused[f.min.degree] = f.min\n\tcur := f.min.right\n\n\tfor used[cur.degree] != cur { //We always go right, so if we placed something to slice, made a lap, and nothing changed, consolidation is finished\n\t\tf.updateMin(cur)\n\t\tif used[cur.degree] == nil { //If yet no other node with same degree recorder - record current\n\t\t\tused[cur.degree] = cur\n\t\t\tcur = cur.right\n\t\t} else {\n\n\t\t\tbusy := used[cur.degree]\n\t\t\tfather, son := cur, busy\n\t\t\tif busy.key.LessThen(cur.key) { //make father point to lighter node, son to heavier one\n\t\t\t\tfather, son = son, father\n\t\t\t} else if father.key.EqualsTo(son.key) { //make sure f.min is always father\n\t\t\t\tif son == f.min {\n\t\t\t\t\tfather, son = son, father\n\t\t\t\t}\n\t\t\t}\n\t\t\tson.left.right = son.right\n\t\t\tson.right.left = son.left //cut the son from his local linked-list\n\n\t\t\tnext := cur.right //remember next to be right from current cur, it can change later\n\n\t\t\tif father.child == nil { //If father has no children - son is the first\n\t\t\t\tfather.child = son\n\t\t\t\tson.left, son.right = son, son\n\t\t\t} else { //else integrate son into children linked-list\n\t\t\t\tson.left, son.right = father.child, father.child.right\n\t\t\t\tfather.child.right.left = son\n\t\t\t\tfather.child.right = son\n\t\t\t}\n\n\t\t\tused[cur.degree] = nil\n\t\t\tson.parent = father\n\t\t\tfather.degree++\n\t\t\tcur = next\n\t\t}\n\t\tf.updateMin(cur)\n\t}\n\n}",
"func (n node) Heuristic() int {\n\treturn selectedHeuristic(n.state)\n}",
"func FindMinOptimalSubset(tree Tree, bound int) (float64, []*Node) {\n\tn := tree.UpdateSizes()\n\tdp := make([][]float64, n+1)\n\tpred := make([][]bool, n+1)\n\tfor i := 0; i <= n; i++ {\n\t\tdp[i] = make([]float64, bound+1)\n\t\tpred[i] = make([]bool, bound+1)\n\t\tfor j := 0; j < len(dp[i]); j++ {\n\t\t\tdp[i][j] = 1\n\t\t}\n\t}\n\n\ti := 1\n\tnodesInOrder := []*Node{nil}\n\tvar buildDP func(*Node)\n\tbuildDP = func(node *Node) {\n\t\tfor _, child := range node.Children {\n\t\t\tbuildDP(child)\n\t\t}\n\n\t\tfor w := 0; w <= bound; w++ {\n\t\t\tif w - node.Weight >= 0 && node.Profit * dp[i-1][w-node.Weight] < dp[i-node.Size][w] {\n\t\t\t\tpred[i][w] = true\n\t\t\t\tdp[i][w] = node.Profit * dp[i-1][w-node.Weight]\n\t\t\t} else {\n\t\t\t\tpred[i][w] = false\n\t\t\t\tdp[i][w] = dp[i-node.Size][w]\n\t\t\t}\n\t\t}\n\n\t\tnodesInOrder = append(nodesInOrder, node)\n\t\ti++\n\t}\n\tbuildDP(tree.Root)\n\n\toptimalSubset := []*Node{}\n\ti = n\n\tw := bound\n\tfor i > 0 {\n\t\tcurrentNode := nodesInOrder[i]\n\t\tif pred[i][w] == true {\n\t\t\toptimalSubset = append(optimalSubset, currentNode)\n\t\t\tw -= currentNode.Weight\n\t\t\ti--;\n\t\t} else {\n\t\t\ti -= currentNode.Size;\n\t\t}\n\t}\n\n\treturn dp[n][bound], optimalSubset\n}",
"func (pop Population) SortFitness() {\n\tsort.Slice(pop, func(i, j int) bool {\n\t\treturn pop[i].Fitness < pop[j].Fitness\n\t})\n}",
"func main() {\n\tres := countGrowth([]int{20, 30, 10, 12, 14, 5, 25, 26, 29, 30, 15, 12})\n\tfmt.Println(\"Result: \", res)\n}",
"func Minimax(depth int, mygame game.Game, playerNum int) int {\n\tpotentialMoves := make(map[int]int) //maps column # of move to the \"score\"\n\totherplayer := int(math.Abs(float64(1 - playerNum)))\n\n\tfor move := 0; move < 7; move++ {\n\t\tif mygame.IsValidMove(move) {\n\t\t\ttemp := mygame\n\t\t\ttemp.MakeMove(playerNum, move)\n\t\t\t//assign value to each move based on what other player is expected to do\n\t\t\tpotentialMoves[move] = -traverse(depth-1, temp, otherplayer)\n\t\t}\n\t}\n\tscore := -999999999999\n\tvar output int\n\t//Maximise our score OR maximise our minimum losses\n\t//hence name minimax\n\tfor key, value := range potentialMoves {\n\t\tif value > score {\n\t\t\tscore = value\n\t\t\toutput = key\n\t\t}\n\t}\n\tfmt.Printf(\"The associated score value is %d\", score)\n\tfmt.Println()\n\tfmt.Print(\"choose col #\")\n\tfmt.Println(output)\n\treturn output\n}",
"func solveKnapsack(weights []*big.Int, s *big.Int) []byte {\n\tzero := big.NewInt(0)\n\tsolution := make([]byte, len(weights))\n\tsolutionIdx := len(weights) - 1\n\n\tvar solve func([]*big.Int, *big.Int, *big.Int)\n\tsolve = func(remainingWeights []*big.Int, sumOfRemainingWeights *big.Int, target *big.Int) {\n\t\tif len(remainingWeights) == 0 || target.Cmp(zero) == 0 {\n\t\t\treturn\n\t\t}\n\t\tlast := remainingWeights[len(remainingWeights)-1]\n\t\tweightsWithoutLast := remainingWeights[:len(remainingWeights)-1]\n\t\tsumWithoutLast := new(big.Int).Sub(sumOfRemainingWeights, last)\n\n\t\tif target.Cmp(sumWithoutLast) > 0 {\n\t\t\tsolution[solutionIdx] = 1\n\t\t\tsolutionIdx--\n\t\t\tsolve(weightsWithoutLast, sumWithoutLast, target.Sub(target, last))\n\t\t} else {\n\t\t\tsolution[solutionIdx] = 0\n\t\t\tsolutionIdx--\n\t\t\tsolve(weightsWithoutLast, sumWithoutLast, target)\n\t\t}\n\t}\n\tsolve(weights, sum(weights), s)\n\treturn solution\n}",
"func shortestBridge(grid [][]int) int {\n\tm := len(grid)\n\tn := len(grid[0])\n\tvar islands [][]int // 2 slice of locations of 2 islands\n\n\tvar collect func(x, y int, r *[]int)\n\tcollect = func(x, y int, r *[]int) {\n\t\tgrid[y][x] = 0\n\t\t*r = append(*r, x, y)\n\t\tif 0 <= x-1 && grid[y][x-1] == 1 {\n\t\t\tcollect(x-1, y, r)\n\t\t}\n\n\t\tif n > x+1 && grid[y][x+1] == 1 {\n\t\t\tcollect(x+1, y, r)\n\t\t}\n\n\t\tif 0 <= y-1 && grid[y-1][x] == 1 {\n\t\t\tcollect(x, y-1, r)\n\t\t}\n\n\t\tif m > y+1 && grid[y+1][x] == 1 {\n\t\t\tcollect(x, y+1, r)\n\t\t}\n\t}\n\n\tfor y := 0; y < m; y++ {\n\t\tfor x := 0; x < n; x++ {\n\t\t\tif grid[y][x] == 1 {\n\t\t\t\tvar xys []int\n\t\t\t\tcollect(x, y, &xys)\n\t\t\t\tislands = append(islands, xys)\n\t\t\t}\n\t\t}\n\t}\n\n\ta, b := islands[0], islands[1]\n\tbest := math.MaxInt32\n\tfor i := 0; i < len(a) && best > 1; i += 2 {\n\t\tx1, y1 := a[i], a[i+1]\n\t\tfor j := 0; j < len(b) && best > 1; j += 2 {\n\t\t\tx2, y2 := b[j], b[j+1]\n\t\t\td := abs(x2-x1) + abs(y2-y1) - 1\n\t\t\tif d < best {\n\t\t\t\tbest = d\n\t\t\t}\n\t\t}\n\t}\n\treturn best\n}",
"func firstGE(nums []int, target int) int {\n\n\tif nums[0] >= target {\n\t\treturn 0\n\t}\n\tvar start = 0\n\tvar end = len(nums)\n\tfor start+1 < end {\n\t\tvar mid = start + (end-start)/2\n\t\tif nums[mid] >= target {\n\t\t\tend = mid\n\t\t} else {\n\t\t\tstart = mid\n\t\t}\n\t}\n\treturn end\n}",
"func SimpleGridCalculator(blocksize uint32, size uint32) uint32 {\n\treturn (blocksize + size - 1) - blocksize\n}",
"func evaluate(board [8][8]int, player int) float32 {\n\tvar score float32\n\n\t//Created a grid of relative score values for each cell\n\t//Based on Reversi strategy\n\t//Corners are stable and valuable, but adjacent cells can lead to losing a corner\n\t//Edge pieces are somewhat stable and valuable otherwise\n\t//Cells 2 away from corner facilitate corner capturing\n\t//All other tiles are weighted at 1\n\n\tcellValue := [][]int{\n\t\t{50, -20, 10, 5, 5, 10, -20, 50},\n\t\t{-20, -20, 1, 1, 1, 1, -20, -20},\n\t\t{10, 1, 5, 1, 1, 5, 1, 10},\n\t\t{5, 1, 1, 1, 1, 1, 1, 5},\n\t\t{5, 1, 1, 1, 1, 1, 1, 5},\n\t\t{10, 1, 5, 1, 1, 5, 1, 10},\n\t\t{-20, -20, 1, 1, 1, 1, -20, -20},\n\t\t{50, -20, 10, 5, 5, 10, -20, 50},\n\t}\n\n\t//Coin Parity\n\tvar pScore float32\n\tvar pCoin float32\n\tvar oCoin float32\n\n\t//Score player and opponent cell\n\tfor i := 0; i < 8; i++ {\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tif board[i][j] == player {\n\t\t\t\tpCoin += float32(cellValue[i][j])\n\t\t\t} else if board[i][j] == enemy(player) {\n\t\t\t\toCoin += float32(cellValue[i][j])\n\t\t\t}\n\t\t}\n\t}\n\n\t//Parity score is difference in scores over total score\n\tpScore = (pCoin - oCoin) / (pCoin + oCoin)\n\n\t//Difference in Mobility\n\t//Create games assuming board state and turn to calculate size of valid moves\n\tvar mScore float32\n\n\tpMob := createGame(board, player)\n\toMob := createGame(board, enemy(player))\n\n\tplayerMobility := len(pMob.validMoves)\n\tenemyMobility := len(oMob.validMoves)\n\n\tswitch{\n\tcase playerMobility > enemyMobility:\n\t\tmScore = float32(playerMobility)/float32(playerMobility + enemyMobility)\n\tcase enemyMobility > playerMobility:\n\t\tmScore = -float32(enemyMobility)/float32(playerMobility + enemyMobility)\n\tdefault:\n\t\tmScore = 0\n\t}\n\n\t//fmt.Printf(\"Parity:%v Mobility:%v\\n\", pScore, mScore)\n\t//Total evaluated score\n\tscore = (pScore * 500) + (mScore * 600)\n\n\treturn score\n}",
"func dijstra(g adjList, n int, s int, e int) ([]int, []int) {\n\t// g - adjacency list of a weighted graph\n\t// n - the number of nodes in the graph\n\t// s - the index of the starting node ( 0 <= s < n )\n\t// e - the index of the end node ( 0 <= e < n )\n\tvisited := make([]bool, n)\n\tdistance := make([]int, n)\n\n\t// keep track of the previous node we took\n\t// to get to the current node\n\tprevious := make([]int, n)\n\n\tfor i := range visited {\n\t\tvisited[i] = false\n\t}\n\n\tfor i := range distance {\n\t\tdistance[i] = math.MaxInt64\n\t}\n\n\tdistance[s] = 0\n\t// Set Min option to true for minheap\n\tminheap := pqueue.NewHeap(pqueue.Options{\n\t\tMin: true,\n\t})\n\n\tminheap.InsertPriority(string(s), 0)\n\n\tfor minheap.Length() != 0 {\n\n\t\tstringAtIndex, min := minheap.Poll()\n\t\tintegerAtIndex, _ := strconv.Atoi(stringAtIndex)\n\n\t\t// current node is integerAtIndex\n\t\tvisited[integerAtIndex] = true\n\n\t\t// optimization to ignore stale index\n\t\t// (index, min_dis) pair\n\t\tif distance[integerAtIndex] < min {\n\t\t\tcontinue\n\t\t}\n\n\t\t// loop through all the neighbours of\n\t\t// the current node\n\t\tcn := g[integerAtIndex].head\n\t\tfor cn != nil {\n\n\t\t\tif visited[cn.vertex] {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tnewdist := distance[integerAtIndex] + cn.weight\n\t\t\tif newdist < distance[cn.vertex] {\n\t\t\t\tprevious[cn.vertex] = integerAtIndex\n\t\t\t\tdistance[cn.vertex] = newdist\n\t\t\t\tminheap.InsertPriority(strconv.Itoa(cn.vertex), newdist)\n\t\t\t}\n\n\t\t\tif cn.next == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcn = cn.next\n\t\t}\n\n\t\t// Optimise here to stop early.\n\t\tif integerAtIndex == e {\n\t\t\treturn distance, previous\n\t\t}\n\n\t}\n\treturn distance, previous\n}",
"func MinHeapify(a []int, used, i int) {\n\tfor {\n\t\tmin := i // record the min position\n\t\tif i*2 <= used && a[i] > a[i*2] {\n\t\t\tmin = i * 2\n\t\t}\n\n\t\tif i*2+1 <= used && a[min] > a[i*2+1] {\n\t\t\tmin = i*2 + 1\n\t\t}\n\n\t\tif min == i {\n\t\t\tbreak\n\t\t}\n\n\t\ta[i], a[min] = a[min], a[i]\n\n\t\ti = min\n\t}\n}",
"func find_min_working(workers map[int]int) int {\n min := math.MaxInt32\n for i := 0; i < 5; i++ {\n if workers[i] > 0 && workers[i] < min{\n min = workers[i]\n }\n }\n return min\n}",
"func (e *Election) Bucklin(k int) int {\n\tres := make(map[int]int)\n\ttotal := 0\n\tfor _, v := range e.V {\n\t\tfor i := 0; i < k; i++ {\n\t\t\tres[v.C[strconv.Itoa(i)]] += v.W\n\t\t}\n\t\ttotal += v.W\n\t}\n\tm := total / 2\n\n\tfor i := 0; i < e.N; i++ {\n\t\tif res[i] > m {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}",
"func (blk Block) MineRange(start uint64, end uint64, workers uint64, chunks uint64) MiningResult {\n\tvar noResult, myResult MiningResult\n\tqueue := work_queue.Create(uint(workers), uint(chunks))\n\tlength := uint64(math.Ceil(float64((end - start) / chunks) + 0.0001))\n\n\tfor i := start; i < end; i+= length {\n\t\tmineWorker := miningWorker{i, i + length, blk}\n\t\tqueue.Enqueue(mineWorker)\n\t\t//fmt.Println(i, i+length)\n\t}\n\n\t//fmt.Printf(\"type of queue %T, value of queue %v\", queue, queue)\n\t//fmt.Println(len(queue.Jobs))\n\t//fmt.Println(len(queue.Results))\n\n\n\tfor i := range queue.Results {\n\t\ttemp := i // channel of interface{} type\n\t\t//MiningResult(temp) would not work, but type assert would\n\t\tmyResult = temp.(MiningResult)\n\t\tif (myResult.Found == true) {\n\t\t\tqueue.Shutdown()\n\t\t\t//fmt.Println(\"got something\")\n\t\t\treturn myResult\n\t\t}\n\t}\n\tqueue.Shutdown()\n\tfmt.Println(\"freed\")\n\treturn noResult\n}",
"func main() {\n\tvar N int\n\tfmt.Scan(&N)\n\n\thorses := make([]int, N)\n\tfor i := 0; i < N; i++ {\n\t\tfmt.Scan(&(horses[i]))\n\t}\n\n\tsort.Ints(horses)\n\n\tminD := 10*1000*1000\n\tfor i := 0; i < N-1; i++ {\n\t\tif dist := horses[i+1]-horses[i]; dist < minD {\n\t\t\tminD = dist\n\t\t}\n\t}\n\t// fmt.Fprintln(os.Stderr, \"Debug messages...\")\n\tfmt.Println(minD)// Write answer to stdout\n}",
"func minKnightMoves(ex int, ey int) int {\r\n\tif ex == 0 && ey == 0 {\r\n\t\treturn 0\r\n\t}\r\n\tq := [][]int{}\r\n\tq = append(q, []int{0, 0})\r\n\tdir := [][]int{{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, 2}, {-2, 1}, {-1, -2}, {-2, -1}}\r\n\tsteps := 0\r\n\tseen := map[int]map[int]bool{0: map[int]bool{0: true}}\r\n\t// BFS loop\r\n\tfor len(q) > 0 {\r\n\t\tsteps++\r\n\t\tn := len(q)\r\n\t\tfor i := 0; i < n; i++ {\r\n\t\t\tt := q[0]\r\n\t\t\tq = q[1:]\r\n\t\t\tfor _, d := range dir {\r\n\t\t\t\tnx := t[0] + d[0]\r\n\t\t\t\tny := t[1] + d[1]\r\n\t\t\t\tif nx == ex && ny == ey {\r\n\t\t\t\t\treturn steps\r\n\t\t\t\t}\r\n\t\t\t\tif _, exists := seen[nx]; !exists {\r\n\t\t\t\t\tseen[nx] = map[int]bool{}\r\n\t\t\t\t}\r\n\t\t\t\tif _, exists := seen[nx][ny]; !exists &&\r\n\t\t\t\t\t(nx*ex >= 0 && ny*ey >= 0 || steps < 3) {\r\n\t\t\t\t\tseen[nx][ny] = true\r\n\t\t\t\t\tq = append(q, []int{nx, ny})\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn -1\r\n}",
"func interactiveSolution(testCases, numberOfElem, queryThreshold int) {\n\n}",
"func anneal() board {\n\tb := randomboard()\n\tbbest := make(board, len(b))\n\te, ebest := 100., 100. // unattainably high\n\tfor i := 0; i < n; i++ {\n\t\tx, y := swappair(b)\n\t\tb[x], b[y] = b[y], b[x]\n\t\tif enew := energy(b); enew < e || rand.Float64() < math.Exp((e-enew)/temp(i)) {\n\t\t\tif e = enew; e < ebest {\n\t\t\t\tcopy(bbest, b)\n\t\t\t\tebest = e\n\t\t\t}\n\t\t} else {\n\t\t\tb[x], b[y] = b[y], b[x]\n\t\t}\n\t\tif i%10000 == 0 {\n\t\t\tfmt.Println()\n\t\t\tfmt.Println(i, temp(i), ebest, e)\n\t\t\tfmt.Println(distance(bbest), penalty(bbest), path(bbest))\n\t\t\tfmt.Println(standarddist(bbest), standardpen(bbest), standardpath(bbest))\n\t\t\tdisplay(bbest)\n\t\t}\n\t}\n\treturn bbest\n}",
"func main() {\n\trand.Seed(time.Now().UTC().UnixNano())\n\n\tfor i := 0; i < count_pop; i++ {\n\t\tpopulation[i] = make([]int, len_pop)\n\t\tfor j := 0; j < len_pop; j++ {\n\t\t\tpopulation[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\tfor i := 0; i < len_pop; i++ {\n\t\tweight[i] = rand.Intn(10)\n\t}\n\n\tfmt.Println(\"Weight: \", weight, \"\\n\")\n\n\tfor i := 0; i < count_pop; i++ {\n\t\tfmt.Printf(\"[%d] - %v\\n\", i, population[i])\n\t}\n\n\tvar best_pos, cur int\n\tfmt.Println(\"\\nTop scores: \\n\")\n\n\tfmt.Println(\"Weight: \", weight, \"\\n\")\n\tfor i := 0; i < 5; i++ {\n\t\tpos := rand.Intn(count_pop)\n\t\tcur = find_sum(pos)\n\n\t\tif cur >= best_pos {\n\t\t\tbest_pos = cur\n\t\t\tfmt.Printf(\"[%d] -\\t%v - [%d] - Best in the current step (%d)\\n\", pos, population[pos], best_pos, best_pos)\n\t\t} else {\n\t\t\tfmt.Printf(\"[%d] -\\t%v - [%d] - Best in the current step (%d)\\n\", cur, population[cur], find_sum(cur), best_pos)\n\t\t}\n\t}\n}",
"func jump(nums []int) int {\n\tif len(nums) <= 1 {\n\t\treturn 0\n\t}\n\n\tvar maxIdx, i, step int\n\tfor i < len(nums)-1 {\n\t\tnextIdx, tmpIdx := 0, 0\n\t\tfor j := 0; j < nums[i]; j++ {\n\t\t\ttmpIdx = i + j + 1\n\t\t\tif tmpIdx < len(nums) && tmpIdx+nums[tmpIdx] > maxIdx {\n\t\t\t\tmaxIdx = tmpIdx + nums[tmpIdx]\n\t\t\t\tnextIdx = tmpIdx\n\t\t\t}\n\t\t\tif tmpIdx == len(nums)-1 {\n\t\t\t\tnextIdx = tmpIdx\n\t\t\t}\n\t\t}\n\n\t\ti = nextIdx\n\t\tstep++\n\t}\n\n\treturn step\n}",
"func (b *Board) nextGeneration() int {\n\tnextGrid := make([][]CellState, len(b.Grid))\n\tfor i := 0; i < len(b.Grid); i++ {\n\t\tnextGrid[i] = make([]CellState, len(b.Grid[0]))\n\t}\n\n\tvar livingCells int\n\tfor i := 0; i < len(b.Grid); i++ {\n\t\tfor j := 0; j < len(b.Grid[0]); j++ {\n\t\t\tvalue := b.Grid[i][j]\n\t\t\tneighbours := b.countNeighbours(i, j)\n\t\t\tif value == dead && containsInt(b.Game.Rule.Born, neighbours) {\n\t\t\t\tnextGrid[i][j] = alive\n\t\t\t} else if value == 1 && !containsInt(b.Game.Rule.Survives, neighbours) {\n\t\t\t\tnextGrid[i][j] = dead\n\t\t\t} else {\n\t\t\t\tnextGrid[i][j] = value\n\t\t\t}\n\n\t\t\tif nextGrid[i][j] == alive {\n\t\t\t\tlivingCells++\n\t\t\t}\n\t\t}\n\t}\n\n\tb.Grid = nextGrid\n\treturn livingCells\n}",
"func jump(nums []int) int {\n\tif len(nums) <= 1 {\n\t\treturn 0\n\t}\n\tdp := make([]int, len(nums), len(nums))\n\tdp[0] = 0\n\tfor i := 1; i < len(dp); i++ {\n\t\tdp[i] = math.MaxInt64 // assume 64 bit server\n\t}\n\n\tfor i := 1; i < len(nums); i++ {\n\t\tfor j := 0; j < i; j++ {\n\t\t\tif dp[j] != math.MaxInt64 && nums[j] + j >= i {\n\t\t\t\tdp[i] = utils.Min(dp[i], dp[j]+1)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[len(dp)-1]\n}",
"func solveAlgo6(g Solver, l *Line) {\n\t//l.print(\"solveAlgo6\")\n\trsg := l.getUnsolvedRanges()\n\n\tfor _, r := range rsg {\n\t\tcs := l.getPotentialCluesForRange(r)\n\n\t\tlongest := 0\n\t\tisFound, step := l.getStepToNextBlank(r, false)\n\t\tif isFound {\n\t\t\tisFound = false\n\t\t\tfor _, c := range cs {\n\t\t\t\tif c.index < l.ce {\n\t\t\t\t\tnext := l.clues[c.index+1]\n\t\t\t\t\tif step <= c.length-r.length() || step > next.length {\n\t\t\t\t\t\tisFound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlongest = max(longest, c.length-r.length())\n\t\t\t}\n\t\t\t//if we didn't find anyone, we can blank taking into account the longest trail\n\t\t\tif len(cs) > 1 && !isFound {\n\t\t\t\tfor i := longest + 1; i <= step; i++ {\n\t\t\t\t\tg.SetValue(l.squares[r.max+i], BLANK)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlongest = 0\n\t\tisFound, step = l.getStepToNextBlank(r, true)\n\t\tif isFound {\n\t\t\tisFound = false\n\t\t\tfor _, c := range cs {\n\t\t\t\tif c.index > l.cb {\n\t\t\t\t\tprevious := l.clues[c.index-1]\n\t\t\t\t\tif step <= c.length-r.length() || step > previous.length {\n\t\t\t\t\t\tisFound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlongest = max(longest, c.length-r.length())\n\t\t\t}\n\t\t\t//if we didn't find anyone, we can blank taking into account the longest trail\n\t\t\tif len(cs) > 1 && !isFound {\n\t\t\t\tfor i := longest + 1; i <= step; i++ {\n\t\t\t\t\tg.SetValue(l.squares[r.min-i], BLANK)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"func (eng *Engine) search(depth, estimated int32) int32 {\n\t// this method only implements aspiration windows\n\t//\n\t// the gradual widening algorithm is the one used by RobboLito\n\t// and Stockfish and it is explained here:\n\t// http://www.talkchess.com/forum/viewtopic.php?topic_view=threads&p=499768&t=46624\n\tγ, δ := estimated, int32(initialAspirationWindow)\n\tα, β := max(γ-δ, -InfinityScore), min(γ+δ, InfinityScore)\n\tscore := estimated\n\n\tif depth < 4 {\n\t\t// disable aspiration window for very low search depths\n\t\tα, β = -InfinityScore, +InfinityScore\n\t}\n\n\tfor !eng.stopped {\n\t\t// at root a non-null move is required, cannot prune based on null-move\n\t\tscore = eng.searchTree(α, β, depth)\n\t\tif score <= α {\n\t\t\tα = max(α-δ, -InfinityScore)\n\t\t\tδ += δ / 2\n\t\t} else if score >= β {\n\t\t\tβ = min(β+δ, InfinityScore)\n\t\t\tδ += δ / 2\n\t\t} else {\n\t\t\treturn score\n\t\t}\n\t}\n\n\treturn score\n}",
"func ScaledSearch(minX, maxX, minY, maxY, minZ, maxZ, scale int, bots []Nanobot) []Score {\n\tscores := make([]Score, 0)\n\tfor x := minX; x <= maxX; x += scale {\n\t\tfor y := minY; y <= maxY; y += scale {\n\t\t\tfor z:= minZ; z <= maxZ; z += scale {\n\t\t\t\tscore := CubeScore(x, y, z, scale, bots)\n\t\t\t\tscores = append(scores, Score{x, y, z, scale, score})\n\t\t\t}\n\t\t}\n\t}\n\t// Sort by score\n\tsort.Slice(scores, func (i, j int) bool { return scores[i].score > scores[j].score})\n\treturn scores\n}",
"func (c *Collatz) Execute() {\n\tif c.Number <= minimum {\n\t\treturn\n\t}\n\n\tc.Steps = 0\n\tc.HailStones = make([]float64, maxIterations)\n\tc.HailStones[0] = float64(c.Number)\n\n\tx := 0\n\n\tfor c.HailStones[x] > minimum && x < maxIterations {\n\t\tc.HailStones[x+1] = c.Calculate(c.HailStones[x])\n\t\tx++\n\t}\n\n\tc.HailStones = c.HailStones[1 : x+1]\n\n\tc.Steps = len(c.HailStones)\n}",
"func d14pickBranch(rect *d14rectT, node *d14nodeT) int {\n\tvar firstTime bool = true\n\tvar increase float64\n\tvar bestIncr float64 = -1\n\tvar area float64\n\tvar bestArea float64\n\tvar best int\n\tvar tempRect d14rectT\n\n\tfor index := 0; index < node.count; index++ {\n\t\tcurRect := &node.branch[index].rect\n\t\tarea = d14calcRectVolume(curRect)\n\t\ttempRect = d14combineRect(rect, curRect)\n\t\tincrease = d14calcRectVolume(&tempRect) - area\n\t\tif (increase < bestIncr) || firstTime {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t\tfirstTime = false\n\t\t} else if (increase == bestIncr) && (area < bestArea) {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t}\n\t}\n\treturn best\n}",
"func (board *Board) MinMulti(player *Player, depth *int8, parentsBestScore *float32) float32 {\n\tbestScore := bestMax\n\t//\tvar bestMove Move\n\tplayerMoves := board.LegalMovesForPlayer(*player)\n\tscoreChan := make(chan ScoredMove)\n\tstopChan := make(chan struct{})\n\tnewDepth := *depth - 1\n\t//var bestMove Move\n\n\tif board.IsGameOverForPlayer(player, &playerMoves) {\n\t\treturn winMax\n\t}\n\n\tif newDepth == 0 {\n\t\treturn board.GetWeightedScoreForPlayer(player)\n\t}\n\n\tfor _, move := range playerMoves {\n\t\tboardCopy := *board\n\t\tboardCopy.MakeMoveAndGetTakenPiece(&move)\n\n\t\tscoredMove := ScoredMove{move: move}\n\t\tgo func() {\n\t\t\tcurScore := boardCopy.MaxMulti(player.Opponent(), &newDepth, &bestScore, stopChan, len(playerMoves))\n\t\t\tscoredMove.score = curScore\n\t\t\tscoreChan <- scoredMove\n\t\t}()\n\t}\n\n\tfor i := 0; i < len(playerMoves); i++ {\n\n\t\tcur := <-scoreChan\n\t\t/*if debug {\n\t\t\tfmt.Print(\"NumGoRoutines: \")\n\t\t\tfmt.Println(runtime.NumGoroutine())\n\t\t}*/\n\n\t\tif cur.score < bestScore {\n\t\t\tbestScore = cur.score\n\t\t\t//bestMove = cur.move\n\t\t}\n\n\t\t// alpha-beta pruning\n\t\tif cur.score < *parentsBestScore {\n\t\t\t/*if debug {\n\t\t\t\tfmt.Printf(\"Stopping goRoutines because curScore %f is less than parents best score %f\\n\", bestScore, *parentsBestScore)\n\t\t\t\tfmt.Print(\"NumGoRoutines: \")\n\t\t\t\tfmt.Println(runtime.NumGoroutine())\n\t\t\t}*/\n\t\t\tclose(stopChan) // Send message to all the goRoutines to tell them to stop. We don't care about their output now\n\t\t\treturn bestScore\n\t\t}\n\t}\n\n\t/*if debug {\n\t\tfmt.Printf(\"MIN%d: Found bestscore %f moves left %d with move %s \\n\", depth, bestScore, len(playerMoves), bestMove.ToString())\n\t}*/\n\n\treturn bestScore\n}",
"func dfs_minSideJumps(obstacles []int, l int, pos int, line int, memo [][3]int) int {\n\tif pos == l-1 {\n\t\treturn 0\n\t}\n\tif memo[pos][line-1] != 0 {\n\t\treturn memo[pos][line-1]\n\t}\n\tif obstacles[pos+1] == line {\n\t\tvar res int = 2147483647\n\t\tfor i := 1; i <= 3; i++ {\n\t\t\tif i != line && obstacles[pos] != i {\n\t\t\t\tsteps := dfs_minSideJumps(obstacles, l, pos+1, i, memo)\n\t\t\t\tif steps != 2147483647 {\n\t\t\t\t\tres = min_int(res, 1+steps)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tmemo[pos][line-1] = res\n\t} else {\n\t\tmemo[pos][line-1] = dfs_minSideJumps(obstacles, l, pos+1, line, memo)\n\t}\n\treturn memo[pos][line-1]\n}",
"func slink(n int, d func(int, int) float64) *AggloResult {\n\t// Implementation copied from paper, pardon the crap names.\n\tm := make([]float64, n) // Distance of i'th element from elements/clusters.\n\tpi := make([]int, n) // Index of first merge target of each element.\n\tlambda := make([]float64, n) // Distance of first merge target of each element.\n\n\tlambda[0] = math.MaxFloat64\n\n\tfor i := 1; i < n; i++ {\n\t\tpi[i] = i\n\t\tlambda[i] = math.MaxFloat64\n\n\t\tfor j := 0; j < i; j++ {\n\t\t\tm[j] = d(i, j)\n\t\t}\n\n\t\tfor j := 0; j < i; j++ {\n\t\t\tif m[j] <= lambda[j] {\n\t\t\t\tm[pi[j]] = math.Min(m[pi[j]], lambda[j])\n\t\t\t\tlambda[j] = m[j]\n\t\t\t\tpi[j] = i\n\t\t\t} else {\n\t\t\t\tm[pi[j]] = math.Min(m[pi[j]], m[j])\n\t\t\t}\n\t\t}\n\n\t\tfor j := 0; j < i; j++ {\n\t\t\tif lambda[j] >= lambda[pi[j]] {\n\t\t\t\tpi[j] = i\n\t\t\t}\n\t\t}\n\t}\n\n\treturn newAggloResult(pi, lambda)\n}",
"func oscillate(resolution int, fitness func(i int)int, compare func(a, b int)int) (int, error) {\n\tindex := 0\n\tvalue := fitness(index)\n\tnewValue := value\n\n\tfor {\n\t\tfor compare(value, newValue) >= 0 {\n\t\t\tvalue = newValue\n\t\t\tindex += resolution\n\t\t\tnewValue = fitness(index)\n\t\t}\n\t\tif util.AbsInt(resolution) > 1 {\n\t\t\tresolution = -(resolution / 2)\n\t\t\tvalue = newValue\n\t\t} else {\n\t\t\treturn index - resolution, nil\n\t\t}\n\t}\n}",
"func search() {\n\tvar lowerMatchedList = list.New() // the list which stores the lower-matched index\n\tfor i := 0; i < indexSize; i++ { // scan each index item (lower)\n\t\tvar isMatched bool = false\n\t\tfor j := 0; j < 32/blockSize; j++ { // scan each block\n\t\t\tfor k := 0; k < int(subIndexSize); k++ { // scan all the blocks which their tags are the same as the query's\n\t\t\t\tif index[i].blockCipher[j].subIndex[queryCipher.lower.blockCipher[j].subIndex][k] == 100 { // if all the items with the same sub-index in one block have been checked\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttargetItem := index[i].blockCipher[j].subIndex[queryCipher.lower.blockCipher[j].subIndex][k] // get the item's index\n\n\t\t\t\t// perform the hash operation to check if this item is matched by the query lower-bound block\n\t\t\t\tk1Byte := F(new(big.Int).SetBytes(queryCipher.lower.blockCipher[j].cipher), index[i].gamma)\n\t\t\t\tk2Byte := index[i].blockCipher[j].ciphers[targetItem]\n\n\t\t\t\tif bytes.Equal(k1Byte, k2Byte) {\n\t\t\t\t\tisMatched = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif isMatched == true { // if one item in a block matches, the whole index item matches\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif isMatched == true { // lowerMatchedList will store all the indexes' positions which match the lower-bound\n\t\t\tlowerMatchedList.PushBack(i)\n\t\t}\n\t}\n\n\tfor e := lowerMatchedList.Front(); e != nil; e = e.Next() { // find which one matches the upper bound from the list whose item matches the lower bound\n\t\tvar (\n\t\t\ti = e.Value.(int)\n\t\t\tisMatched bool = false\n\t\t)\n\t\tfor j := 0; j < 32/blockSize; j++ { // scan each block\n\t\t\tfor k := 0; k < int(subIndexSize); k++ { // scan all the blocks which their tags are the same as the query's\n\t\t\t\tif index[i].blockCipher[j].subIndex[queryCipher.upper.blockCipher[j].subIndex][k] == 100 { // if all the items with the same sub-index in one block have been checked\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttargetItem := index[i].blockCipher[j].subIndex[queryCipher.upper.blockCipher[j].subIndex][k] // get the item's index\n\n\t\t\t\t// perform the hash operation to check if this item is matched by the query lower-bound block\n\t\t\t\tk1Byte := F(new(big.Int).SetBytes(queryCipher.upper.blockCipher[j].cipher), index[i].gamma)\n\t\t\t\tk2Byte := index[i].blockCipher[j].ciphers[targetItem]\n\n\t\t\t\tif bytes.Equal(k1Byte, k2Byte) {\n\t\t\t\t\tisMatched = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif isMatched == true { // if one item in a block matches, the whole index item matches\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif isMatched == true { // insert the matched index into the result list\n\t\t\tres.PushBack(index[i].note)\n\t\t}\n\t}\n}",
"func (t *data) SteppingStoneMethod(initfname string) {\n //declare variablesS\n\tMax := 0\n var shift []deliver = nil\n shifting := deliverzero\n\t\n\t//for each supply\n for p := 0; p < len(t.supply); p++ {\n\t\t//for each demand\n for q := 0; q < len(t.demand); q++ {\n\t\t\t//if element is Zero\n if t.set[p][q] == deliverzero {\n\t\t\t\t//test that element to minimize cost\n\t\t\t\ttest := deliver{0, t.cost_data[p][q], p, q}\n\t\t\t\t\n\t\t\t\t//declare variables\n\t\t\t\tpath := t.marginalpath(test)\n\t\t\t\tchange := 0\n\t\t\t\toptimal := int(math.MaxInt32)\n\t\t\t\tcopy := deliverzero\n\t\t\t\tflag := true\n\t\t\t\t\n\t\t\t\t//for each path\n\t\t\t\tfor _, s := range path {\n\t\t\t\t\t\n\t\t\t\t\t//true\n\t\t\t\t\tif flag {\n\t\t\t\t\t\tchange += s.Cost\n\t\t\t\t\t}else {\n\t\t\t\t\t\tchange -= s.Cost\n\t\t\t\t\t\t//if cost is minimized\n\t\t\t\t\t\tif s.n < optimal {\n\t\t\t\t\t\t\tcopy = s\n\t\t\t\t\t\t\toptimal = s.n\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tflag = !flag\n\t\t\t\t}\n\t\t\t\t//if change is less than maximum\n\t\t\t\tif change < Max {\n\t\t\t\t\tshift = path\n\t\t\t\t\tshifting = copy\n\t\t\t\t\tMax = change\n\t\t\t\t}\n\t\t\t}\n\t\t}\n }\n\t//if shift is not Zero\n if shift != nil {\n q := shifting.n\n flag := true\n\t\t//for each shift\n for _, s := range shift {\n\t\t\t//true\n if flag {\n s.n += q\n }else {\n s.n -= q\n }\n if s.n == 0 {\n t.set[s.p][s.q] = deliverzero\n } else {\n t.set[s.p][s.q] = s\n }\n flag = !flag\n }\n\t\t//apply Stepping Store Method till no more optimal solution can be found\n t.SteppingStoneMethod(initfname)\n }\n}",
"func (a *DepthFirst) findGoal(e environments.Environment) (environments.Node, error) {\n\t// if nothing in queue/frontier, then it is impossible\n\t// to find the goal node\n\tfor a.queue.Len() > 0 {\n\t\ta.iterations++\n\t\tcurrentNode := heap.Pop(a.queue).(environments.Node)\n\n\t\tif e.IsGoalNode(currentNode) {\n\t\t\treturn currentNode, nil\n\t\t}\n\n\t\tfor _, child := range currentNode.Children() {\n\t\t\tchildIdx, inQueue := a.queue.NodeIndexes[child.Name()]\n\t\t\tprevDepth, seenPrev := a.depth[child.Name()]\n\t\t\tcurrDepth := a.depth[currentNode.Name()] + 1\n\n\t\t\tif seenPrev && prevDepth < currDepth {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !inQueue {\n\t\t\t\ta.depth[child.Name()] = currDepth\n\t\t\t\t// new node, just add it\n\t\t\t\theap.Push(a.queue, child)\n\t\t\t} else {\n\t\t\t\ta.depth[child.Name()] = currDepth\n\t\t\t\t// we found a new route to the node. let's\n\t\t\t\t// update the depth and fix its placement in the\n\t\t\t\t// queue\n\t\t\t\ta.queue.Frontier[childIdx] = child\n\t\t\t\theap.Fix(a.queue, childIdx)\n\t\t\t}\n\t\t}\n\n\t}\n\treturn nil, fmt.Errorf(\"frontier is empty; searched entire space, but could not find goal state\")\n}",
"func d17pickBranch(rect *d17rectT, node *d17nodeT) int {\n\tvar firstTime bool = true\n\tvar increase float64\n\tvar bestIncr float64 = -1\n\tvar area float64\n\tvar bestArea float64\n\tvar best int\n\tvar tempRect d17rectT\n\n\tfor index := 0; index < node.count; index++ {\n\t\tcurRect := &node.branch[index].rect\n\t\tarea = d17calcRectVolume(curRect)\n\t\ttempRect = d17combineRect(rect, curRect)\n\t\tincrease = d17calcRectVolume(&tempRect) - area\n\t\tif (increase < bestIncr) || firstTime {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t\tfirstTime = false\n\t\t} else if (increase == bestIncr) && (area < bestArea) {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t}\n\t}\n\treturn best\n}",
"func (gossiper *Gossiper) getHighestFit(confirmedGossips []*packets.TLCMessage) (*packets.TLCMessage, int) {\n\tmaxFit := float32(0)\n\tvar maxGossip *packets.TLCMessage\n\tindex := 0\n\tfor i, gossip := range confirmedGossips {\n\t\tif gossip.Fitness > maxFit {\n\t\t\tmaxGossip = gossip\n\t\t\tmaxFit = gossip.Fitness\n\t\t\tindex = i\n\t\t}\n\t}\n\treturn maxGossip, index\n}",
"func d2pickBranch(rect *d2rectT, node *d2nodeT) int {\n\tvar firstTime bool = true\n\tvar increase float64\n\tvar bestIncr float64 = -1\n\tvar area float64\n\tvar bestArea float64\n\tvar best int\n\tvar tempRect d2rectT\n\n\tfor index := 0; index < node.count; index++ {\n\t\tcurRect := &node.branch[index].rect\n\t\tarea = d2calcRectVolume(curRect)\n\t\ttempRect = d2combineRect(rect, curRect)\n\t\tincrease = d2calcRectVolume(&tempRect) - area\n\t\tif (increase < bestIncr) || firstTime {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t\tfirstTime = false\n\t\t} else if (increase == bestIncr) && (area < bestArea) {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t}\n\t}\n\treturn best\n}",
"func (s *Supermarket) calculateOpenCheckout() {\n\tnumOfCurrentCustomers := len(s.customers)\n\tnumOfOpenCheckouts := len(s.checkoutOpen)\n\tcalculationOfThreshold := int(math.Ceil(float64(numOfCurrentCustomers) / MaxCustomersPerCheckout))\n\n\t// Ensure at least 1 checkout stays open\n\tif numOfCurrentCustomers == 0 && s.openStatus {\n\t\treturn\n\t}\n\n\tif len(s.checkoutOpen) == 1 {\n\t\tif s.checkoutOpen[0].isSeniorCheckout {\n\t\t\ts.checkoutOpen[0].isSeniorCheckout = false\n\t\t}\n\n\t\tif s.checkoutOpen[0].tenOrLess {\n\t\t\ts.checkoutOpen[0].tenOrLess = false\n\t\t}\n\t}\n\n\t// Calculate threshold for opening a checkout\n\tif calculationOfThreshold > numOfOpenCheckouts {\n\t\t// If there are no more checkouts to open\n\t\tif len(s.checkoutClosed) == 0 {\n\t\t\treturn\n\t\t}\n\n\t\t// Open first checkout in closed checkout slice\n\t\ts.checkoutClosed[0].open()\n\t\ts.checkoutOpen = append(s.checkoutOpen, s.checkoutClosed[0])\n\t\ts.checkoutClosed = s.checkoutClosed[1:]\n\n\t\tcheckoutChangeStatusChan <- 1\n\n\t\treturn\n\t}\n\n\t// Calculate threshold for closing a checkout\n\tif calculationOfThreshold < numOfOpenCheckouts {\n\t\tif len(s.checkoutOpen) == 1 && s.openStatus {\n\t\t\treturn\n\t\t}\n\n\t\t// Choose best checkout to close\n\t\tcheckout, pos := s.chooseCheckout(0, false)\n\t\tif pos < 0 {\n\t\t\treturn\n\t\t}\n\t\tcheckout.close()\n\t\ts.checkoutClosed = append(s.checkoutClosed, checkout)\n\t\ts.checkoutOpen = append(s.checkoutOpen[0:pos], s.checkoutOpen[pos+1:]...)\n\n\t\tcheckoutChangeStatusChan <- -1\n\n\t\treturn\n\t}\n}",
"func (idx *Index) Breaches(feature *geojson.WOFFeature) ([]*geojson.WOFSpatial, error) {\n\n\tclipping, err := feature.EnSpatialize()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbreaches := make([]*geojson.WOFSpatial, 0)\n\tbounds := clipping.Bounds()\n\tresults := idx.GetIntersectsByRect(bounds)\n\n\t// idx.Logger.Info(\"possible results for %v : %d\", bounds, len(results))\n\n\tif len(results) > 0 {\n\n\t\tt1 := time.Now()\n\n\t\tclipping_polys := feature.GeomToPolygons()\n\t\tidx.Logger.Debug(\"compare %d polys from clipping against %d possible subjects\", len(clipping_polys), len(results))\n\n\t\t// See what's going on here? We are *not* relying on the standard Inflate method\n\t\t// but rather bucketing all the WOFSpatials by their WOF ID (this is because the\n\t\t// (WOF) rtree package indexes the bounding boxes of individual polygons on the\n\t\t// geom rather than the bounding box of the set of polygons) which we we will\n\t\t// loop over below (20151130/thisisaaronland)\n\n\t\tinflated := make(map[int][]*geojson.WOFSpatial)\n\n\t\tfor _, r := range results {\n\n\t\t\twof := r.(*geojson.WOFSpatial)\n\t\t\twofid := wof.Id\n\n\t\t\t_, ok := inflated[wofid]\n\n\t\t\tpossible := make([]*geojson.WOFSpatial, 0)\n\n\t\t\tif ok {\n\t\t\t\tpossible = inflated[wofid]\n\t\t\t}\n\n\t\t\tpossible = append(possible, wof)\n\t\t\tinflated[wofid] = possible\n\t\t}\n\n\t\tfor wofid, possible := range inflated {\n\n\t\t\tif wofid == feature.WOFId() {\n\t\t\t\tidx.Logger.Debug(\"%d can not breach itself, skipping\", wofid)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Despite the notes about goroutines and yak-shaving below this is probably\n\t\t\t// a pretty good place to do things concurrently (21051130/thisisaaronland)\n\n\t\t\tsubject_polys, err := idx.LoadPolygons(possible[0])\n\n\t\t\tif err != nil {\n\t\t\t\tidx.Logger.Warning(\"Unable to load polygons for ID %d, because %v\", wofid, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tidx.Logger.Debug(\"testing %d with %d possible candidates\", wofid, len(possible))\n\n\t\t\t// Note to self: it turns out that goroutine-ing these operations is yak-shaving\n\t\t\t// and often slower (20151130/thisisaaronland)\n\n\t\t\tfor i, subject := range possible {\n\n\t\t\t\tidx.Logger.Debug(\"testing %d (offset %d) with candidate %d\", wofid, subject.Offset, i)\n\n\t\t\t\ttest_polys := make([]*geojson.WOFPolygon, 0)\n\n\t\t\t\tif subject.Offset == -1 {\n\t\t\t\t\ttest_polys = subject_polys\n\t\t\t\t} else {\n\t\t\t\t\ttest_polys = append(test_polys, subject_polys[subject.Offset])\n\t\t\t\t}\n\n\t\t\t\tintersects, err := idx.Intersects(clipping_polys, test_polys)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tidx.Logger.Error(\"Failed to determine intersection, because %v\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif intersects {\n\t\t\t\t\tbreaches = append(breaches, subject)\n\t\t\t\t\tidx.Logger.Debug(\"determined that %d breaches after %d/%d iterations\", wofid, i, len(possible))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\tt2 := time.Since(t1)\n\t\tidx.Logger.Debug(\"time to test %d possible results: %v\", len(results), t2)\n\t}\n\n\treturn breaches, nil\n}",
"func (lc *localChain) MarkNewHeaviest(\n\tancestor [32]uint8,\n\tcurrentBest []uint8,\n\tnewBest []uint8,\n\tlimit *big.Int,\n) error {\n\tpanic(\"not implemented yet\")\n}",
"func calcShortestPath(maze [][]Vertex) int {\n\tvar currVertex, destination, lastVertex *Vertex\n\tfinished := false\n\t\n\tcurrVertex = findCheapestOpenVertex(maze[0:])\t// Finds the starting point \"S\"\n\t\n\tfor !finished {\t\t\t\t\t\t// Keeps looping until the optimal path to the exit is found\n\t\tcurrVertex.isOpen = false\t\t// Marks analyzed vertex as visited, so as to not visit it again\n\t\tif currVertex.cellChar == \"G\" {\t// Set the finished flag, if the optimal route to exit is found\n\t\t\tdestination = currVertex\n\t\t\tfinished = true\n\t\t}\n\t\t\n\t\tupdateTouchingVertices(currVertex, maze[0:])\t// Calculates the costs of adjacent vertices\n\t\t\n\t\tcurrVertex = findCheapestOpenVertex(maze[0:])\t// Analyzes the next cheapest vertex\n\t}\n\t\n\tlastVertex = &maze[destination.lastVertexRow][destination.lastVertexCol]\t// Jumps to the last visited vertex from the exit vertex\n\tfinished = false\t// Resets the flag, so that it can be used in the upcoming loop\n\tfor !finished {\t\t// Keep looping\tuntil the optimal path is drawn\n\t\tif lastVertex.cellChar != \"S\" && lastVertex.cellChar != \"G\" {\n\t\t\tlastVertex.cellChar = \"*\"\n\t\t}\n\t\t\n\t\tif lastVertex.lastVertexRow != -1 || lastVertex.lastVertexCol != -1 {\t\t// If not the starting vertex\n\t\t\tlastVertex = &maze[lastVertex.lastVertexRow][lastVertex.lastVertexCol]\t// Jump to the previous vertex\n\t\t} else {\n\t\t\tfinished = true\n\t\t}\n\t}\n\t\n\treturn destination.cost\n}",
"func d8pickBranch(rect *d8rectT, node *d8nodeT) int {\n\tvar firstTime bool = true\n\tvar increase float64\n\tvar bestIncr float64 = -1\n\tvar area float64\n\tvar bestArea float64\n\tvar best int\n\tvar tempRect d8rectT\n\n\tfor index := 0; index < node.count; index++ {\n\t\tcurRect := &node.branch[index].rect\n\t\tarea = d8calcRectVolume(curRect)\n\t\ttempRect = d8combineRect(rect, curRect)\n\t\tincrease = d8calcRectVolume(&tempRect) - area\n\t\tif (increase < bestIncr) || firstTime {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t\tfirstTime = false\n\t\t} else if (increase == bestIncr) && (area < bestArea) {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t}\n\t}\n\treturn best\n}",
"func d5pickBranch(rect *d5rectT, node *d5nodeT) int {\n\tvar firstTime bool = true\n\tvar increase float64\n\tvar bestIncr float64 = -1\n\tvar area float64\n\tvar bestArea float64\n\tvar best int\n\tvar tempRect d5rectT\n\n\tfor index := 0; index < node.count; index++ {\n\t\tcurRect := &node.branch[index].rect\n\t\tarea = d5calcRectVolume(curRect)\n\t\ttempRect = d5combineRect(rect, curRect)\n\t\tincrease = d5calcRectVolume(&tempRect) - area\n\t\tif (increase < bestIncr) || firstTime {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t\tfirstTime = false\n\t\t} else if (increase == bestIncr) && (area < bestArea) {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t}\n\t}\n\treturn best\n}",
"func problem51() int {\n\tn := 56995 // given in the description as a member of a 7-prime family\n\tfor {\n\t\tif tools.IsPrime(n) && isSmallestMember(n) {\n\t\t\treturn n\n\t\t}\n\t\tn++\n\t}\n}",
"func (p *Population) CalculateFitness() {\n\tp.previousFitness = p.Fitness\n\tp.Fitness = 0\n\n\tfor _, i := range p.individuals {\n\t\tgo func(i *individual) {\n\t\t\tp.fitnessWg.Add(1)\n\t\t\ti.calculateFitness()\n\t\t\tp.fitnessChan <- i.fitness\n\t\t}(i)\n\t}\n\n\tp.fitnessWg.Wait()\n}",
"func d9pickBranch(rect *d9rectT, node *d9nodeT) int {\n\tvar firstTime bool = true\n\tvar increase float64\n\tvar bestIncr float64 = -1\n\tvar area float64\n\tvar bestArea float64\n\tvar best int\n\tvar tempRect d9rectT\n\n\tfor index := 0; index < node.count; index++ {\n\t\tcurRect := &node.branch[index].rect\n\t\tarea = d9calcRectVolume(curRect)\n\t\ttempRect = d9combineRect(rect, curRect)\n\t\tincrease = d9calcRectVolume(&tempRect) - area\n\t\tif (increase < bestIncr) || firstTime {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t\tfirstTime = false\n\t\t} else if (increase == bestIncr) && (area < bestArea) {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t}\n\t}\n\treturn best\n}",
"func smallestDistancePair(nums []int, k int) int {\n \n}",
"func MapRankToScore(rank, size int) float64 { return float64(size - rank) }",
"func d7pickBranch(rect *d7rectT, node *d7nodeT) int {\n\tvar firstTime bool = true\n\tvar increase float64\n\tvar bestIncr float64 = -1\n\tvar area float64\n\tvar bestArea float64\n\tvar best int\n\tvar tempRect d7rectT\n\n\tfor index := 0; index < node.count; index++ {\n\t\tcurRect := &node.branch[index].rect\n\t\tarea = d7calcRectVolume(curRect)\n\t\ttempRect = d7combineRect(rect, curRect)\n\t\tincrease = d7calcRectVolume(&tempRect) - area\n\t\tif (increase < bestIncr) || firstTime {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t\tfirstTime = false\n\t\t} else if (increase == bestIncr) && (area < bestArea) {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t}\n\t}\n\treturn best\n}",
"func d6pickBranch(rect *d6rectT, node *d6nodeT) int {\n\tvar firstTime bool = true\n\tvar increase float64\n\tvar bestIncr float64 = -1\n\tvar area float64\n\tvar bestArea float64\n\tvar best int\n\tvar tempRect d6rectT\n\n\tfor index := 0; index < node.count; index++ {\n\t\tcurRect := &node.branch[index].rect\n\t\tarea = d6calcRectVolume(curRect)\n\t\ttempRect = d6combineRect(rect, curRect)\n\t\tincrease = d6calcRectVolume(&tempRect) - area\n\t\tif (increase < bestIncr) || firstTime {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t\tfirstTime = false\n\t\t} else if (increase == bestIncr) && (area < bestArea) {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t}\n\t}\n\treturn best\n}",
"func minHeapify(array []int, i int) {\n\tsmallest := i\n\n\tl := left(i)\n\tr := right(i)\n\n\tif l < len(array) && array[l] < array[i] {\n\t\tsmallest = l\n\t}\n\n\tif r < len(array) && array[r] < array[smallest] {\n\t\tsmallest = r\n\t}\n\n\tif i != smallest {\n\t\tarray[i], array[smallest] = array[smallest], array[i]\n\t\tminHeapify(array, smallest)\n\t}\n}",
"func findCheapestOpenVertex(maze [][]Vertex) *Vertex {\n\tvar returnVertex Vertex\n\tvar returnPointer *Vertex\n\n\tfor row := 0; row < len(maze); row++ {\n\t\tfor col := 0; col < len(maze[row]); col++ {\n\t\t\t// If it's not a wall (\"#\") and it hasn't been visited and it has been an adjacent vertex to one of the visited vertices\n\t\t\tif maze[row][col].cellChar != \"#\" && maze[row][col].isOpen && maze[row][col].cost >= 0 {\n\t\t\t\tif returnVertex == (Vertex{}) {\t\t// The first vertex to meet the conditions is set as the return vertex\n\t\t\t\t\treturnPointer = &maze[row][col]\t// Pointer to the vertex in the maze\n\t\t\t\t\treturnVertex = *returnPointer\t// Contents in the vertex (its struct)\n\t\t\t\t} else if maze[row][col].cost < returnVertex.cost {\t// If the costs are lower than the first vertex, then replace the return vertex\n\t\t\t\t\treturnPointer = &maze[row][col]\t// Pointer to the vertex in the maze\n\t\t\t\t\treturnVertex = *returnPointer\t// Contents in the vertex (its struct)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn returnPointer\n}",
"func climbingLeaderboard(scores []int64, alice []int64) []int64 {\n\tvar scores_ []int64\n\tm := make(map[int64]bool)\n\tfor _, val := range scores {\n\t\tif _, ok := m[val]; !ok {\n\t\t\tm[val] = true\n\t\t\tscores_ = append(scores_, val)\n\t\t}\n\t}\n\n\tvar index []int64\n\tn := int64(len(scores_)) - 1\n\tfor _, val := range alice {\n\t\tfor n >= 0 {\n\t\t\tif val >= scores_[n] {\n\t\t\t\tn = n - 1\n\t\t\t} else {\n\t\t\t\tindex = append(index, n+2)\n\t\t\t\tfmt.Println(n + 2)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif n < 0 {\n\t\t\tindex = append(index, 1)\n\t\t\tfmt.Println(1)\n\t\t}\n\t}\n\tfmt.Println(index)\n\treturn index\n\n}",
"func (s *Switch) probe_neighbours( target *string, commence, conclude, inc_cap int64, usr *string, usr_max int64 ) ( found *Switch, cap_trip bool ) {\n\tvar (\n\t\tfsw\t*Switch\t\t\t// next neighbour switch (through link)\n\t)\n\n\tfound = nil\n\tcap_trip = false\n\n\t//fmt.Printf( \"\\n\\nsearching neighbours of (%s) for %s\\n\", s.To_str(), *target )\n\tfor i := 0; i < s.lidx; i++ {\n\t\tif s != fsw {\n \t\t\thas_room, err := s.links[i].Has_capacity( commence, conclude, inc_cap, usr, usr_max )\n\t\t\tif has_room {\n\t\t\t\tfsw = s.links[i].forward\t\t\t\t// at the switch on the other side of the link\n\t\t\t\tif (fsw.Flags & tegu.SWFL_VISITED) == 0 {\n\t\t\t\t\tobj_sheep.Baa( 3, \"switch:probe_neigbour: following link %d -- has capacity to (%s) and NOT visited\", i, fsw.To_str() )\n\t\t\t\t\tif s.Cost + s.links[i].Cost < fsw.Cost {\n\t\t\t\t\t\t//fmt.Printf( \"\\tsetting cost: %d\\n\", s.Cost + s.links[i].Cost )\n\t\t\t\t\t\tfsw.Cost = s.Cost + s.links[i].Cost\n\t\t\t\t\t\tfsw.Prev = s\t\t\t\t\t\t\t\t// shortest path to this node is through s\n\t\t\t\t\t\tfsw.Plink = i\t\t\t\t\t\t\t\t// using its ith link\n\t\t\t\t\t}\n\t\n\t\t\t\t\tobj_sheep.Baa( 3, \"compare: (%s) (%s)\", *target, *(fsw.Get_id()) )\n\t\t\t\t\tif fsw.Has_host( target ) || *(fsw.Get_id()) == *target {\t\t\t// target is attahced to this switch, or the target is a swtich that is the forward switch\n\t\t\t\t\t\tfsw.Prev = s\n\t\t\t\t\t\tfsw.Plink = i\n\t\t\t\t\t\tfound = fsw\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tobj_sheep.Baa( 2, \"no capacity on link: %s\", err )\n\t\t\t\tcap_trip = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}",
"func solveProblem(from, to int, pos int, c chan bool) {\n\tfromPos := getCeilPos(from)\n\ttoPos := getCeilPos(to)\n\tif almostPrime[fromPos] < from {\n\t\tfromPos += 1\n\t}\n\tif toPos+1 < len(almostPrime) && almostPrime[toPos+1] == to {\n\t\ttoPos += 1\n\t}\n\n\tif fromPos == toPos && almostPrime[fromPos] != from {\n\t\taddSolution(pos, \"0\", c)\n\t\treturn\n\t}\n\t//fmt.Println(\"Search\", from, to, fromPos, toPos, almostPrime[fromPos:toPos+1])\n\n\taddSolution(pos, fmt.Sprintf(\"%d\", len(almostPrime[fromPos:toPos+1])), c)\n}",
"func (bh* BinomialHeap) Size() int {\n return bh.size\n}",
"func d20pickBranch(rect *d20rectT, node *d20nodeT) int {\n\tvar firstTime bool = true\n\tvar increase float64\n\tvar bestIncr float64 = -1\n\tvar area float64\n\tvar bestArea float64\n\tvar best int\n\tvar tempRect d20rectT\n\n\tfor index := 0; index < node.count; index++ {\n\t\tcurRect := &node.branch[index].rect\n\t\tarea = d20calcRectVolume(curRect)\n\t\ttempRect = d20combineRect(rect, curRect)\n\t\tincrease = d20calcRectVolume(&tempRect) - area\n\t\tif (increase < bestIncr) || firstTime {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t\tfirstTime = false\n\t\t} else if (increase == bestIncr) && (area < bestArea) {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t}\n\t}\n\treturn best\n}",
"func findJudge(n int, trust [][]int) int {\n\tif n == 1 {\n\t\treturn 1\n\t}\n\ttrusteeH := map[int]int{}\n\ttrustSrcH := map[int]int{}\n\n\tfor _, t := range trust {\n\t\ttrustSrcH[t[0]]++\n\t\ttrusteeH[t[1]]++\n\t}\n\tfmt.Println(\"_--->tree\", trusteeH)\n\tfmt.Println(\"---->trs\", trustSrcH)\n\n\tnM1 := n - 1\n\tfor k := range trusteeH {\n\t\tif trusteeH[k] == nM1 && trustSrcH[k] == 0 {\n\t\t\treturn k\n\t\t}\n\t}\n\n\treturn -1\n}",
"func pickWay(p []float64) int {\n\tvar sum float64\n\tfor _, j := range p {\n\t\tsum += j\n\t}\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\trn := r.Float64() * sum\n\tsum = 0\n\tfor i, j := range p {\n\t\tif rn > sum && rn < sum+j {\n\t\t\treturn i\n\t\t}\n\t\tsum += j\n\t}\n\treturn -1\n}",
"func findNearNeighbor(x []float64, y []float64, points map[int]int, start int) int {\n neighbor := 0\n smDist := 10000000.0\n\n // Loop through all yet visited points to find out the cloesest point to current point.\n for i := 1; i < len(points); i++ {\n if (i != start) && (points[i] != 0) {\n sqSum := math.Pow(x[i] - x[start], 2) + math.Pow(y[i] - y[start], 2)\n dist := math.Sqrt(sqSum)\n if dist < smDist {\n neighbor = i\n smDist = dist\n }\n }\n }\n return neighbor\n}",
"func find(gs []*Geodesic, v Vector, minDistSq float64, start int) int {\n\tgs0 := gs[0]\n\tnextStart := start\n\tneighbors := gs0.Faces[start].Neighbors\n\tfor _, n := range neighbors {\n\t\tiDistSq := DistSq(gs0.Centers[n], v)\n\t\tif iDistSq < minDistSq {\n\t\t\tminDistSq = iDistSq\n\t\t\tnextStart = n\n\t\t}\n\t}\n\n\tif len(gs) == 1 {\n\t\t// There's a bug related to correctly classifying the neighbor of a\n\t\t// pentagon face, so this corrects for that.\n\t\tif nextStart == start {\n\t\t\treturn nextStart\n\t\t}\n\t\treturn find(gs, v, minDistSq, nextStart)\n\t}\n\n\treturn find(gs[1:], v, minDistSq, nextStart)\n}",
"func FindPath(mp Graph, start, end Node) ([]Node, error) {\n\tmapCapacity := int(end - start)\n\tif mapCapacity < 0 {\n\t\tmapCapacity = -mapCapacity\n\t}\n\tif mapCapacity > maxDefaultMapCapacity {\n\t\tmapCapacity = maxDefaultMapCapacity\n\t}\n\t// The open list is ordered by the sum of current cost + heuristic cost\n\tstate := newState(mapCapacity)\n\t// Add the start node to the openlist\n\tpCost, err := mp.HeuristicCost(start, end)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstate.addNodeInfo(&nodeInfo{\n\t\tnode: start,\n\t\tparent: -1,\n\t\tcost: 0.0,\n\t\tpredictedCost: float32(pCost),\n\t})\n\n\tedgeSlice := make([]Edge, 0, 8)\n\tfor {\n\t\tcurrent := state.popBest()\n\t\tif current == nil {\n\t\t\treturn nil, ErrImpossible\n\t\t}\n\t\tif current.node == end {\n\t\t\t// If we reached the end node then we know the optimal path. Traverse\n\t\t\t// it (backwards) and return an array of node IDs.\n\t\t\treturn state.pathToNode(current), nil\n\t\t}\n\t\tif current.cost >= state.maxCost {\n\t\t\tcontinue\n\t\t}\n\t\tif dbg, ok := mp.(Debug); ok {\n\t\t\tdbg.VisitedNode(current.node, current.parent, float64(current.cost), float64(current.predictedCost))\n\t\t}\n\t\tneighbors, err := mp.Neighbors(current.node, edgeSlice[:0])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, edge := range neighbors {\n\t\t\t// Don't try go backwards\n\t\t\tif edge.Node == current.parent {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Cost for the neighbor node is the current cost plus the\n\t\t\t// cost to get to that node.\n\t\t\tcost := current.cost + float32(edge.Cost)\n\n\t\t\tni := state.info[edge.Node]\n\t\t\tif ni == nil {\n\t\t\t\t// We haven't seen this node so add it to the open list.\n\t\t\t\tpCost, err := mp.HeuristicCost(edge.Node, end)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tni = &nodeInfo{\n\t\t\t\t\tnode: edge.Node,\n\t\t\t\t\tparent: current.node,\n\t\t\t\t\tcost: cost,\n\t\t\t\t\tpredictedCost: float32(pCost),\n\t\t\t\t}\n\t\t\t\tstate.addNodeInfo(ni)\n\t\t\t} else if cost < ni.cost {\n\t\t\t\t// We've seen this node and the current path is cheaper\n\t\t\t\t// so update the changed info and add it to the open list\n\t\t\t\t// (replacing if necessary).\n\t\t\t\tni.parent = current.node\n\t\t\t\tni.cost = cost\n\t\t\t\tif ni.index >= 0 {\n\t\t\t\t\tstate.updateNodeInfo(ni)\n\t\t\t\t} else {\n\t\t\t\t\tstate.addNodeInfo(ni)\n\t\t\t\t}\n\t\t\t} else if edge.Node == end {\n\t\t\t\tif cost < state.maxCost {\n\t\t\t\t\tstate.maxCost = cost\n\t\t\t\t}\n\t\t\t\tif pp, ok := mp.(PossiblePath); ok {\n\t\t\t\t\tpath := append(state.pathToNode(current), end)\n\t\t\t\t\tpp.PossiblePath(path, float64(cost))\n\t\t\t\t}\n\t\t\t\tni = nil\n\t\t\t}\n\t\t\tif ni != nil && edge.Node == end {\n\t\t\t\tif cost < state.maxCost {\n\t\t\t\t\tstate.maxCost = cost\n\t\t\t\t}\n\t\t\t\tif pp, ok := mp.(PossiblePath); ok {\n\t\t\t\t\tpp.PossiblePath(state.pathToNode(ni), float64(ni.cost))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"func ConcurrentSearch(root *Node, policies []GamePolicy, duration time.Duration) Decision {\n\tif root == nil {\n\t\t// TODO: error handling\n\t\tpanic(\"no root\")\n\t}\n\n\t// All possible first moves are expanded.\n\ttree := GrowTree(root)\n\n\tdone := make(chan struct{})\n\ttimeout := make(chan bool)\n\n\t// Start the countdown asap: the search must return a decision\n\t// in the given time frame. A late decision is as bad as an\n\t// illegal move, it's disqualifying.\n\tgo func() {\n\t\ttime.Sleep(duration)\n\t\tclose(timeout)\n\t}()\n\n\t// Prepare pipelines (channels and goroutines launchers).\n\tpositions := make(chan job, samplers)\n\twalk := func(count int) {\n\t\tvar wg sync.WaitGroup\n\n\t\twg.Add(count)\n\t\tfor i := 0; i < count; i++ {\n\t\t\tgo func() {\n\t\t\t\twalker(done, tree, positions)\n\t\t\t\twg.Done()\n\t\t\t}()\n\t\t}\n\n\t\tgo func() {\n\t\t\twg.Wait()\n\t\t\tclose(positions)\n\t\t}()\n\t}\n\n\toutcomes := make(chan job, samplers)\n\tsample := func(count int) {\n\t\tvar wg sync.WaitGroup\n\n\t\twg.Add(count)\n\t\tfor i := 0; i < count; i++ {\n\t\t\tgo func() {\n\t\t\t\tsampler(done, policies, positions, outcomes)\n\t\t\t\twg.Done()\n\t\t\t}()\n\t\t}\n\n\t\tgo func() {\n\t\t\twg.Wait()\n\t\t\tclose(outcomes)\n\t\t}()\n\t}\n\n\tupdate := func(count int) {\n\t\tfor i := 0; i < count; i++ {\n\t\t\tgo func() {\n\t\t\t\tupdater(done, outcomes)\n\t\t\t}()\n\t\t}\n\t}\n\n\t// Launch!\n\tgo update(updaters)\n\tgo sample(samplers)\n\tgo walk(walkers)\n\n\t// Wait for either timeout or solution\n\tfor {\n\t\tselect {\n\t\tcase <-timeout:\n\t\t\tgoto conclusion\n\t\tdefault:\n\t\t\tif root.IsSolved() {\n\t\t\t\tgoto conclusion\n\t\t\t}\n\t\t\truntime.Gosched()\n\t\t}\n\t}\n\n\t// Broadcast termination message (done) to all goroutines\n\t// and return the best sequence found so far.\nconclusion:\n\tclose(done)\n\treturn tree.Best()\n}",
"func AStarWithJump(matrix [][]uint8, start Node, goal Node, hchoice int) (*Path, error) {\n\n\tcameFrom := make(map[Node]Node)\n\tvisited := make(map[Node]bool)\n\tweightMap := make(map[Node]float64)\n\n\topen := &aStarQueue{indexOf: make(map[Node]int)}\n\n\theap.Push(open, aStarNode{node: start, gscore: 0, fscore: heuristic(&start, &goal, 1)})\n\tfor open.Len() != 0 {\n\t\tu := heap.Pop(open).(aStarNode)\n\t\tuNode := u.node\n\n\t\tif uNode.row == goal.row && uNode.col == goal.col {\n\t\t\tbreak\n\t\t}\n\n\t\tvisited[uNode] = true\n\t\tto := identifySuccessors(uNode, cameFrom, matrix, goal)\n\t\tfor _, v := range to {\n\t\t\tif _, exist := visited[v]; exist {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tw := weight(&uNode, &v, 1)\n\t\t\tg := u.gscore + w\n\t\t\tif n, exist := open.node(&v); !exist {\n\t\t\t\theap.Push(open, aStarNode{node: v, gscore: g, fscore: g + heuristic(&v, &goal, 1)})\n\t\t\t} else if g < n.gscore {\n\t\t\t\topen.update(v, g, g+heuristic(&v, &goal, 1))\n\t\t\t}\n\t\t\tcameFrom[v] = uNode\n\t\t\tweightMap[v] = w\n\t\t}\n\t}\n\tpathNodes := make([]Node, 0)\n\n\tif _, exist := cameFrom[goal]; !exist {\n\t\treturn nil, fmt.Errorf(\"destination not reacheable from source\")\n\t}\n\tcur := goal\n\ttotalWeight := 0.0\n\n\tfor {\n\t\tpathNodes = append(pathNodes, cur)\n\t\tweight, _ := weightMap[cur]\n\t\ttotalWeight += weight\n\t\tnext, exist := cameFrom[cur]\n\t\tif !exist {\n\t\t\tbreak\n\t\t}\n\t\tcur = next\n\t}\n\n\t//reversing to get path from start to end\n\treturn &Path{getReverse(pathNodes), totalWeight}, nil\n\n}",
"func (ship Ship) Navigate(target Entity, gameMap Map) string {\n\tob := gameMap.ObstaclesBetween(ship.Entity, target)\n\n\tif !ob {\n\t\treturn ship.NavigateBasic(target, gameMap)\n\t}\n\n\tx0 := math.Min(ship.X, target.X)\n\tx2 := math.Max(ship.X, target.X)\n\ty0 := math.Min(ship.Y, target.Y)\n\ty2 := math.Max(ship.Y, target.Y)\n\n\tdx := (x2 - x0) / 5\n\tdy := (y2 - y0) / 5\n\tbestdist := 1000.0\n\tbestTarget := target\n\n\tfor x1 := x0; x1 <= x2; x1 += dx {\n\t\tfor y1 := y0; y1 <= y2; y1 += dy {\n\t\t\tintermediateTarget := Entity{\n\t\t\t\tX: x1,\n\t\t\t\tY: y1,\n\t\t\t\tRadius: 0,\n\t\t\t\tHealth: 0,\n\t\t\t\tOwner: 0,\n\t\t\t\tID: -1,\n\t\t\t}\n\t\t\tob1 := gameMap.ObstaclesBetween(ship.Entity, intermediateTarget)\n\t\t\tif !ob1 {\n\t\t\t\tob2 := gameMap.ObstaclesBetween(intermediateTarget, target)\n\t\t\t\tif !ob2 {\n\t\t\t\t\ttotdist := math.Sqrt(math.Pow(x1-x0, 2)+math.Pow(y1-y0, 2)) + math.Sqrt(math.Pow(x1-x2, 2)+math.Pow(y1-y2, 2))\n\t\t\t\t\tif totdist < bestdist {\n\t\t\t\t\t\tbestdist = totdist\n\t\t\t\t\t\tbestTarget = intermediateTarget\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ship.NavigateBasic(bestTarget, gameMap)\n}",
"func main() {\n\tg, nodesMap := graphLineByLine()\n\n\tstart := nodesMap[\"shiny gold\"]\n\tcount := 0\n\tgraph.BFS(g, start, func(v, w int, _ int64) {\n\t\t//fmt.Println(v, \"to\", w)\n\t\tcount++\n\n\t})\n\n\tfmt.Println(count)\n}"
] | [
"0.5610046",
"0.5548879",
"0.53170174",
"0.5241419",
"0.514508",
"0.5143495",
"0.512722",
"0.51111203",
"0.5079949",
"0.49803877",
"0.49717847",
"0.4870646",
"0.48665398",
"0.484932",
"0.48467213",
"0.48344237",
"0.48255503",
"0.48043612",
"0.47443485",
"0.4719135",
"0.4696799",
"0.46528387",
"0.46486455",
"0.46285853",
"0.4595048",
"0.4589147",
"0.4586293",
"0.45793235",
"0.45605922",
"0.45567855",
"0.45473176",
"0.45425785",
"0.45412397",
"0.45377156",
"0.4536779",
"0.45322853",
"0.4521072",
"0.45141783",
"0.45127577",
"0.45088577",
"0.4500211",
"0.44978833",
"0.44929308",
"0.44913316",
"0.44845057",
"0.44814628",
"0.44699106",
"0.44673267",
"0.44595844",
"0.4457522",
"0.4454761",
"0.44462168",
"0.4433374",
"0.44203314",
"0.44118458",
"0.44053572",
"0.44026005",
"0.4400257",
"0.43964428",
"0.43956742",
"0.43946958",
"0.43936324",
"0.4391807",
"0.43866432",
"0.43855113",
"0.43852544",
"0.43844277",
"0.43829307",
"0.4380854",
"0.43802813",
"0.43760428",
"0.43741155",
"0.43738195",
"0.43731278",
"0.43666497",
"0.43623453",
"0.43590444",
"0.4356525",
"0.43494415",
"0.43490273",
"0.43472856",
"0.43452662",
"0.43436974",
"0.4341782",
"0.4337232",
"0.43344963",
"0.43339142",
"0.43317708",
"0.4330662",
"0.43303734",
"0.43279824",
"0.43203148",
"0.43162698",
"0.43156433",
"0.4311414",
"0.43112016",
"0.4309889",
"0.43053067",
"0.4298748",
"0.42942125"
] | 0.86635447 | 0 |
/ oscillate searches forwards and backwards with a resolution that decays exponentially, switching direction each time the fitness gets worse between two consecutive points. Once the resolution is at its minimum and the inflection point is encountered again, the solution has been found. | func oscillate(resolution int, fitness func(i int)int, compare func(a, b int)int) (int, error) {
index := 0
value := fitness(index)
newValue := value
for {
for compare(value, newValue) >= 0 {
value = newValue
index += resolution
newValue = fitness(index)
}
if util.AbsInt(resolution) > 1 {
resolution = -(resolution / 2)
value = newValue
} else {
return index - resolution, nil
}
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func searchBestOpenings(x, y *int) {\n bestPathLen := 0\n bestTurnCnt := 0\n bestStart := 2\n bestFinish := 2\n saveDelay := getInt(&delay) // don't print updates while solving for best openings\n setInt(&delay, 0)\n\n for i := 0; i < width; i++ {\n for j := 0; j < width; j++ {\n start := 2*(i + 1)\n finish := 2*(j + 1)\n *x = start\n *y = finish\n if getMaze(getInt(&begX), start - 1) != wall && getMaze(getInt(&begX), start + 1) != wall {; continue; }\n if getMaze(getInt(&endX), finish - 1) != wall && getMaze(getInt(&endX), finish + 1) != wall {; continue; }\n createOpenings(x, y)\n solveMaze(x, y)\n if getInt(&pathLen) > bestPathLen ||\n (getInt(&pathLen) == bestPathLen &&\n getInt(&turnCnt) > bestTurnCnt) {\n bestStart = start\n bestFinish = finish\n bestTurnCnt = getInt(&turnCnt)\n bestPathLen = getInt(&pathLen)\n setInt(&solveLength, getInt(&pathLen))\n }\n restoreMaze()\n deleteOpenings()\n incInt(&numSolves)\n }\n }\n addInt(&sumsolveLength, getInt(&solveLength))\n if viewFlag {\n setInt(&delay, saveDelay) // only restore delay value if view solve flag is set\n }\n *x = bestStart\n *y = bestFinish\n createOpenings(x, y)\n}",
"func (eng *Engine) search(depth, estimated int32) int32 {\n\t// this method only implements aspiration windows\n\t//\n\t// the gradual widening algorithm is the one used by RobboLito\n\t// and Stockfish and it is explained here:\n\t// http://www.talkchess.com/forum/viewtopic.php?topic_view=threads&p=499768&t=46624\n\tγ, δ := estimated, int32(initialAspirationWindow)\n\tα, β := max(γ-δ, -InfinityScore), min(γ+δ, InfinityScore)\n\tscore := estimated\n\n\tif depth < 4 {\n\t\t// disable aspiration window for very low search depths\n\t\tα, β = -InfinityScore, +InfinityScore\n\t}\n\n\tfor !eng.stopped {\n\t\t// at root a non-null move is required, cannot prune based on null-move\n\t\tscore = eng.searchTree(α, β, depth)\n\t\tif score <= α {\n\t\t\tα = max(α-δ, -InfinityScore)\n\t\t\tδ += δ / 2\n\t\t} else if score >= β {\n\t\t\tβ = min(β+δ, InfinityScore)\n\t\t\tδ += δ / 2\n\t\t} else {\n\t\t\treturn score\n\t\t}\n\t}\n\n\treturn score\n}",
"func findRoute(x []float64, y []float64, arraySize int) {\n \n // Randomly generate a start point.\n startpoint := rand.Intn(arraySize) + 1\n\n // Create an array to save the order of points to visit as the solution.\n solutionRoute := make([]int, arraySize + 1)\n solutionRoute[1] = startpoint\n\n // Create a map to store the points which have not been visited yet.\n unvisitedPoints := make(map[int]int)\n for l := 0; l <= arraySize; l++ {\n unvisitedPoints[l] = l\n }\n unvisitedPoints[startpoint] = 0\n\n // Find the cloesest point to the current one and go to that point, and repeat.\n for k := 2; k <= arraySize; k++ {\n nearNeighbor := findNearNeighbor(x, y, unvisitedPoints, startpoint)\n solutionRoute[k] = nearNeighbor\n startpoint = nearNeighbor\n unvisitedPoints[nearNeighbor] = 0\n }\n printResult(solutionRoute)\n}",
"func (pp Points) LocalBeamSearch(k int, iterations int) PointsSolution {\r\n\tvar solution PointsSolution\r\n\r\n\t// Bounds and default values\r\n\tif k < 1 || k > 200 {\r\n\t\tk = 200\r\n\t}\r\n\r\n\tif iterations < 1 || iterations > 3000 {\r\n\t\titerations = 2000\r\n\t}\r\n\r\n\tbest := make(chan Points)\r\n\r\n\t// Each point will perform hill climbing in its neighbourhood\r\n\troutine := func(pp Points) {\r\n\r\n\t\tfor i := 0; i < iterations; i += 1 {\r\n\t\t\tpp2 := pp.Neighbour()\r\n\t\t\tif pp2.Len() < pp.Len() {\r\n\t\t\t\tcopy(pp, pp2)\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tbest <- pp\r\n\t}\r\n\r\n\t// Select k random points and perform hill climbing concurrently\r\n\tfor i := 0; i < k; i++ {\r\n\t\tgo routine(pp.Random())\r\n\t}\r\n\r\n\tfor i := 0; i < k; i++ {\r\n\t\tkeep := make(Points, len(pp))\r\n\t\tcopy(keep, <-best)\r\n\t\tsolution = append(solution, keep)\r\n\t}\r\n\r\n\t// Send every solution found for visualization\r\n\tsort.Sort(solution)\r\n\r\n\treturn solution\r\n}",
"func solve(x, y int) {\n if !followPath(&x, &y) {\n backTrackPath(&x, &y)\n }\n finishChan <- struct{}{}\n}",
"func findNearNeighbor(x []float64, y []float64, points map[int]int, start int) int {\n neighbor := 0\n smDist := 10000000.0\n\n // Loop through all yet visited points to find out the cloesest point to current point.\n for i := 1; i < len(points); i++ {\n if (i != start) && (points[i] != 0) {\n sqSum := math.Pow(x[i] - x[start], 2) + math.Pow(y[i] - y[start], 2)\n dist := math.Sqrt(sqSum)\n if dist < smDist {\n neighbor = i\n smDist = dist\n }\n }\n }\n return neighbor\n}",
"func bisection(f func(float64) float64, xl, xu, tol float64) float64 {\n\n\tvar x0, x1, x2, f0, f1, f2 float64\n\n\t// Try to find a bracket.\n\tsuccess := false\n\tx0, x2 = xl, xu\n\tx1 = (x0 + x2) / 2\n\tf1 = f(x1)\n\tfor k := 0; k < 100; k++ {\n\n\t\t// TODO recomputing some values here\n\t\tf0 = f(x0)\n\t\tf1 = f(x1)\n\t\tf2 = f(x2)\n\n\t\tif f1 < f0 && f1 < f2 {\n\t\t\tsuccess = true\n\t\t\tbreak\n\t\t}\n\n\t\tif f0 > f1 && f1 > f2 {\n\t\t\t// Slide right\n\t\t\tx0 = x1\n\t\t\tx1 = x2\n\t\t\tx2 += 1.5 * (x1 - x0)\n\t\t\tcontinue\n\t\t}\n\n\t\tif f0 < f1 && f1 < f2 {\n\t\t\t// Slide left\n\t\t\tx1 = x0\n\t\t\tx2 = x1\n\t\t\tx0 -= 1.5 * (x2 - x1)\n\t\t\tcontinue\n\t\t}\n\n\t\tx0 = x1 - 2*(x1-x0)\n\t\tx2 = x1 + 2*(x2-x1)\n\t}\n\n\tif !success {\n\t\tfmt.Printf(\"Did not find bracket...\\n\")\n\t\tif f0 < f1 && f0 < f2 {\n\t\t\treturn x0\n\t\t} else if f1 < f0 && f1 < f2 {\n\t\t\treturn x1\n\t\t} else {\n\t\t\treturn x2\n\t\t}\n\t}\n\n\titer := 0\n\tfor x2-x0 > tol {\n\t\titer++\n\t\tif x1-x0 > x2-x1 {\n\t\t\txx := (x0 + x1) / 2\n\t\t\tff := f(xx)\n\t\t\tif ff < f1 {\n\t\t\t\tx2 = x1\n\t\t\t\tx1, f1 = xx, ff\n\t\t\t} else {\n\t\t\t\tx0 = xx\n\t\t\t}\n\t\t} else {\n\t\t\txx := (x1 + x2) / 2\n\t\t\tff := f(xx)\n\t\t\tif ff < f1 {\n\t\t\t\tx0 = x1\n\t\t\t\tx1, f1 = xx, ff\n\t\t\t} else {\n\t\t\t\tx2 = xx\n\t\t\t}\n\t\t}\n\t}\n\n\treturn x1\n}",
"func find(gs []*Geodesic, v Vector, minDistSq float64, start int) int {\n\tgs0 := gs[0]\n\tnextStart := start\n\tneighbors := gs0.Faces[start].Neighbors\n\tfor _, n := range neighbors {\n\t\tiDistSq := DistSq(gs0.Centers[n], v)\n\t\tif iDistSq < minDistSq {\n\t\t\tminDistSq = iDistSq\n\t\t\tnextStart = n\n\t\t}\n\t}\n\n\tif len(gs) == 1 {\n\t\t// There's a bug related to correctly classifying the neighbor of a\n\t\t// pentagon face, so this corrects for that.\n\t\tif nextStart == start {\n\t\t\treturn nextStart\n\t\t}\n\t\treturn find(gs, v, minDistSq, nextStart)\n\t}\n\n\treturn find(gs[1:], v, minDistSq, nextStart)\n}",
"func Cube_bisection(x float64) float64 {\n var count, temp, high, low, ans, pos float64\n\n pos = math.Abs(x)\n high = pos\n low = 0\n for {\n count += 1\n if high>low {\n ans = (high + low)/2\n }\n if ans == temp {\n if pos != x {\n ans = -ans\n }\n fmt.Println(count)\n return ans\n }\n temp = ans\n if (math.Pow(ans, 3) > pos) {\n high = ans\n } else {\n low = ans\n }\n //fmt.Println(ans)\n }\n}",
"func linesearch(f fn, X []float64, dir []float64) (float64, []float64) {\n\ta, b := 0.0, 1.0\n\tX0 := X\n\n\t// X will always be our current location\n\t// y will be current minimum of f (always at X)\n\ty := f(X)\n\n\tfor {\n\t\t// fibonacci update\n\t\ta, b = b, a + b\n\n\t\t// scale epsilon by fibonacci value\n\t\talpha := -b * 1e-3\n\n\t\t// search down parameter space in given direction\n\t\tX1 := matrix.VecAdd(X0, matrix.VecScale(alpha, dir))\n\t\ty1 := f(X1)\n\n\t\t// update min values or quit\n\t\tif y1 < y {\n\t\t\ty = y1\n\t\t\tX = X1\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn y, X\n}",
"func (i *iteration) solve() error {\n\tfor cellIndex := i.index; ; cellIndex++ {\n\t\tcell := i.cells[cellIndex]\n\t\tif cell.fixed {\n\t\t\tcontinue\n\t\t}\n\t\ti.index = cellIndex\n\n\t\tnextValue, err := i.findNextValue(cell, i.minValue)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ti.minValue = nextValue\n\t\tcell.value = nextValue\n\t\treturn nil\n\t}\n}",
"func (eng *Engine) searchQuiescence(α, β int32) int32 {\n\teng.Stats.Nodes++\n\n\tentry := eng.retrieveHash()\n\tif score := int32(entry.score); isInBounds(entry.kind, α, β, score) {\n\t\treturn score\n\t}\n\n\tstatic := eng.cachedScore(&entry)\n\tif static >= β {\n\t\t// stand pat if the static score is already a cut-off\n\t\teng.updateHash(failedHigh|hasStatic, 0, static, entry.move, static)\n\t\treturn static\n\t}\n\n\tpos := eng.Position\n\tus := pos.Us()\n\tinCheck := pos.IsChecked(us)\n\tlocalα := max(α, static)\n\tbestMove := entry.move\n\n\teng.stack.GenerateMoves(Violent, NullMove)\n\tfor move := eng.stack.PopMove(); move != NullMove; move = eng.stack.PopMove() {\n\t\t// prune futile moves that would anyway result in a stand-pat at that next depth\n\t\tif !inCheck && isFutile(pos, static, α, futilityMargin, move) ||\n\t\t\t!inCheck && seeSign(pos, move) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// discard illegal or losing captures\n\t\teng.DoMove(move)\n\t\tif eng.Position.IsChecked(us) {\n\t\t\teng.UndoMove()\n\t\t\tcontinue\n\t\t}\n\t\tscore := -eng.searchQuiescence(-β, -localα)\n\t\teng.UndoMove()\n\n\t\tif score >= β {\n\t\t\teng.updateHash(failedHigh|hasStatic, 0, score, move, static)\n\t\t\treturn score\n\t\t}\n\t\tif score > localα {\n\t\t\tlocalα = score\n\t\t\tbestMove = move\n\t\t}\n\t}\n\n\teng.updateHash(getBound(α, β, localα)|hasStatic, 0, localα, bestMove, static)\n\treturn localα\n}",
"func (s Solver) Solve(x, y float64, toCover common.Path) float64 {\n\tif len(toCover) == 0 {\n\t\treturn 0\n\t}\n\tpoints := map[point]bool{}\n\t// This is inefficient but I want to be able to do reference comparison later\n\t// Oh, and hashing. Mostly hashing\n\tfor _, x := range toCover {\n\t\tfor _, p := range s.points {\n\t\t\tif x.X == p.x && x.Y == p.y {\n\t\t\t\tpoints[p] = true\n\t\t\t}\n\t\t}\n\t}\n\tstart := point{x: x, y: y}\n\tlist := make([]pointDistance, len(points)) // distances list for starting point\n\tvar i int\n\tfor p := range points {\n\t\tlist[i] = start.getPointDistance(p)\n\t\ti++\n\t}\n\tsort.Sort(byDistance(list))\n\tvar covered = map[point]bool{}\n\tvar current = list[0]\n\tvar distance float64\n\t// Is this bad form? It makes things simpler to write\nbegin:\n\tdistance += current.distance\n\tcovered[current.point] = true\n\tvar p pointDistance\n\tfor _, p = range s.distances[current.point] {\n\t\tif !covered[p.point] && points[p.point] {\n\t\t\tcurrent = p\n\t\t\tgoto begin\n\t\t}\n\t}\n\n\treturn distance\n}",
"func solution(knows func(a int, b int) bool) func(n int) int {\n\treturn func(n int) int {\n\t\ti := 0\n\t\tj := 0\n\n\t\tindeg := make([]int, n)\n\n\t\tfor i = 0; i < n; i++ {\n\t\t\tfor j = 0; j< n; j++ {\n\t\t\t\tif knows(i, j) && i != j{\n\t\t\t\t\tindeg[i]--\n\t\t\t\t\tindeg[j]++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor index, val := range indeg {\n\t\t\tif val == n-1 {\n\t\t\t\treturn index\n\t\t\t}\n\t\t}\n\n\t\treturn -1\n\t}\n}",
"func solveAlgo7(g Solver, l *Line) {\n\t//l.print(\"solveAlgo7\")\n\trsg := l.getUnsolvedRanges()\n\n\tfor _, r := range rsg {\n\t\tcs := l.getPotentialCluesForRange(r)\n\n\t\tshortest := l.length\n\t\tisFound, step := l.getStepToNextBlank(r, false)\n\t\tif isFound {\n\t\t\tisFound = false\n\t\t\tfor _, c := range cs {\n\t\t\t\tif c.length <= step+r.length() {\n\t\t\t\t\t//fmt.Printf(\"Canceling... Clue(n:%d,b:%d,e:%d,l:%d)\\n\", c.index+1, c.begin+1, c.end+1, c.length)\n\t\t\t\t\tisFound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tshortest = min(shortest, c.length-step-r.length())\n\t\t\t}\n\t\t\t//if we didn't find anyone, we can fill taking into account the shortest trail\n\t\t\tif !isFound {\n\t\t\t\tfor i := 0; i < shortest; i++ {\n\t\t\t\t\tg.SetValue(l.squares[r.min-i-1], 2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tshortest = l.length\n\t\tisFound, step = l.getStepToNextBlank(r, true)\n\t\tif isFound {\n\t\t\tisFound = false\n\t\t\tfor _, c := range cs {\n\t\t\t\tif c.length <= step+r.length() {\n\t\t\t\t\t//fmt.Printf(\"Canceling... Clue(n:%d,b:%d,e:%d,l:%d)\\n\", c.index+1, c.begin+1, c.end+1, c.length)\n\t\t\t\t\tisFound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tshortest = min(shortest, c.length-step-r.length())\n\t\t\t}\n\t\t\t//if we didn't find anyone, we can fill taking into account the shortest trail\n\t\t\tif !isFound {\n\t\t\t\tfor i := 0; i < shortest; i++ {\n\t\t\t\t\tg.SetValue(l.squares[r.max+i+1], FILLED)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"func simpleHillClimbing(size int, fitness func(i int)int, compare func(a, b int)int) (int, error) {\n\tbestIndex := 0\n\tvalue := fitness(bestIndex)\n\tnewValue := value\n\n\tfor i := 0; i < size; i++ {\n\t\tnewValue = fitness(i)\n\t\tcheck := compare(value, newValue)\n\t\tswitch {\n\t\tcase check < 0:\n\t\t\treturn bestIndex, nil\n\t\tcase check > 0:\n\t\t\tbestIndex = i\n\t\t\tvalue = newValue\n\t\t}\n\t}\n\n\treturn fitness(size - 1), fmt.Errorf(\"did not find optimum within first %v solutions\", size)\n}",
"func OptDrillSpeed(machine *vm.Machine, feedrate float64, rapid bool) {\n\tvar (\n\t\tlast vector.Vector\n\t\tnpos []vm.Position = make([]vm.Position, 0)\n\t\tdrillStack []vm.Position = make([]vm.Position, 0)\n\t)\n\n\tfastDrill := func(pos vm.Position) (vm.Position, vm.Position, bool) {\n\t\tvar depth float64\n\t\tvar found bool\n\t\tfor _, m := range drillStack {\n\t\t\tif m.X == pos.X && m.Y == pos.Y {\n\t\t\t\tif m.Z < depth {\n\t\t\t\t\tdepth = m.Z\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdrillStack = append(drillStack, pos)\n\n\t\tif found {\n\t\t\tif pos.Z >= depth { // We have drilled all of it, so just rapid all the way\n\t\t\t\tif rapid {\n\t\t\t\t\tpos.State.MoveMode = vm.MoveModeRapid\n\t\t\t\t} else {\n\t\t\t\t\tpos.State.Feedrate = feedrate\n\t\t\t\t}\n\t\t\t\treturn pos, pos, false\n\t\t\t} else { // Can only rapid some of the way\n\t\t\t\tp := pos\n\t\t\t\tp.Z = depth\n\n\t\t\t\tif rapid {\n\t\t\t\t\tp.State.MoveMode = vm.MoveModeRapid\n\t\t\t\t} else {\n\t\t\t\t\tp.State.Feedrate = feedrate\n\t\t\t\t}\n\t\t\t\treturn p, pos, true\n\t\t\t}\n\t\t} else {\n\t\t\treturn pos, pos, false\n\t\t}\n\t}\n\n\tfor _, m := range machine.Positions {\n\t\tif m.X == last.X && m.Y == last.Y && m.Z < last.Z && m.State.MoveMode == vm.MoveModeLinear {\n\t\t\tposn, poso, shouldinsert := fastDrill(m)\n\t\t\tif shouldinsert {\n\t\t\t\tnpos = append(npos, posn)\n\t\t\t}\n\t\t\tnpos = append(npos, poso)\n\t\t} else {\n\t\t\tnpos = append(npos, m)\n\t\t}\n\t\tlast = m.Vector()\n\t}\n\tmachine.Positions = npos\n}",
"func findRoutes(x int64, y int64) *big.Int {\n\troutes := big.NewInt(0)\n\troutes = routes.Mul(factorial(x), factorial(y))\n\treturn routes.Div(factorial(x+y), routes)\n}",
"func waitUntilStagnate(targetSpeed float64) {\n\tspeed1 := getCurrentSpeed()\n\tpause()\n\tspeed2 := getCurrentSpeed()\n\tfor math.Abs(speed2-speed1) > .01 {\n\t\tspeed1 = speed2\n\t\tpause()\n\t\tspeed2 = getCurrentSpeed()\n\n\t\t//If target passed, break out so that don't accelerate the wrong way\n\t\tif (speed2-speed1 > 0) && speed2 > float64(targetSpeed) ||\n\t\t\t(speed2-speed1 < 0) && speed2 < float64(targetSpeed) {\n\t\t\tbreak\n\t\t}\n\t}\n}",
"func search81(nums []int, target int) bool {\n\tif len(nums) == 0 {\n\t\treturn false\n\t}\n\tleft, right := 0, len(nums)-1\nquiries:\n\tfor left < right {\n\t\tmid := left + (right-left)/2\n\t\tif nums[mid] > nums[right] {\n\t\t\tleft = mid + 1\n\t\t} else if nums[mid] < nums[right] {\n\t\t\tright = mid\n\t\t} else {\n\t\t\t// handle special case when the value of mid is equal to the right value\n\t\t\tfor _, v := range nums[mid : right+1] { // [3, 1, 1, 1, 1], [2, 2, 2, 0, 2, 2]\n\t\t\t\tif v != nums[mid] {\n\t\t\t\t\tleft = mid + 1\n\t\t\t\t\tcontinue quiries\n\t\t\t\t}\n\t\t\t}\n\t\t\tright = mid\n\t\t}\n\t}\n\n\tpivot := left\n\tleft, right = 0, len(nums)-1\n\tif target >= nums[pivot] && target <= nums[right] {\n\t\tleft = pivot\n\t} else {\n\t\tright = pivot - 1\n\t}\n\n\tfor left <= right {\n\t\tmid := left + (right-left)/2\n\t\tif target > nums[mid] {\n\t\t\tleft = mid + 1\n\t\t} else if target < nums[mid] {\n\t\t\tright = mid - 1\n\t\t} else {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}",
"func (n *nearestPointAccumulator) consider(candidate Point) {\n\ttargetXY, ok := n.target.XY()\n\tif !ok {\n\t\treturn\n\t}\n\tcandidateXY, ok := candidate.XY()\n\tif !ok {\n\t\treturn\n\t}\n\n\tdelta := targetXY.Sub(candidateXY)\n\tcandidateDist := delta.lengthSq()\n\tif n.point.IsEmpty() || candidateDist < n.dist {\n\t\tn.dist = candidateDist\n\t\tn.point = candidate\n\t}\n}",
"func shortestBridge(grid [][]int) int {\n\tm := len(grid)\n\tn := len(grid[0])\n\tvar islands [][]int // 2 slice of locations of 2 islands\n\n\tvar collect func(x, y int, r *[]int)\n\tcollect = func(x, y int, r *[]int) {\n\t\tgrid[y][x] = 0\n\t\t*r = append(*r, x, y)\n\t\tif 0 <= x-1 && grid[y][x-1] == 1 {\n\t\t\tcollect(x-1, y, r)\n\t\t}\n\n\t\tif n > x+1 && grid[y][x+1] == 1 {\n\t\t\tcollect(x+1, y, r)\n\t\t}\n\n\t\tif 0 <= y-1 && grid[y-1][x] == 1 {\n\t\t\tcollect(x, y-1, r)\n\t\t}\n\n\t\tif m > y+1 && grid[y+1][x] == 1 {\n\t\t\tcollect(x, y+1, r)\n\t\t}\n\t}\n\n\tfor y := 0; y < m; y++ {\n\t\tfor x := 0; x < n; x++ {\n\t\t\tif grid[y][x] == 1 {\n\t\t\t\tvar xys []int\n\t\t\t\tcollect(x, y, &xys)\n\t\t\t\tislands = append(islands, xys)\n\t\t\t}\n\t\t}\n\t}\n\n\ta, b := islands[0], islands[1]\n\tbest := math.MaxInt32\n\tfor i := 0; i < len(a) && best > 1; i += 2 {\n\t\tx1, y1 := a[i], a[i+1]\n\t\tfor j := 0; j < len(b) && best > 1; j += 2 {\n\t\t\tx2, y2 := b[j], b[j+1]\n\t\t\td := abs(x2-x1) + abs(y2-y1) - 1\n\t\t\tif d < best {\n\t\t\t\tbest = d\n\t\t\t}\n\t\t}\n\t}\n\treturn best\n}",
"func (a Ant) Paso() {\n //Primero calculamos el valor aleatorio q\n q := a.random.Float64()\n //Calculamos el valor RN poara todos los vertices \n rnvalues := a.GetVertexesRNValue() \n //sumrnValues nos rive para guardar la suma de los valores rn de todos los vertices\n sumrnValues := 0.0\n //maxrnvalue nos srive para guardar el valor maximo de los valores rn\n maxrnValue := 0.0\n //indexmasrnValue nos sirve para guardar el indice del vertice con el valor rn maximo\n indexmaxrnValue := -1 \n count := 0;\n //Dentro de este ciclo calculamos sumrnValues, maxrnValue y indexmaxrnValue\n for count < len(rnvalues) {\n //fmt.Printf(\"IndexV: %d RN: %f\\n\", count, rnvalues[count])\n if maxrnValue <= rnvalues[count] {\n maxrnValue = rnvalues[count]\n indexmaxrnValue = count\n }\n sumrnValues = sumrnValues + rnvalues[count]\n count = count+1\n } \n\n\n //Si el q es menor al valor dado q0 entonces vamos a agregar a la solucion el vertice con indice indexmaxrnValue\n //Actualzamos la feromona de manera local para el mismo vertice, y por ulitmo para ese vertice aremos a todas\n //Las aristas que inciden en el con valor 0\n if q < a.q0{\n //fmt.Printf(\"Feromona antes: %f\\n\", (*(*a.graph).vertexes)[indexmaxrnValue].pheromone)\n a.AgregaASolucion(indexmaxrnValue)\n a.ActualizaFeromonaLocalmente(indexmaxrnValue)\n (*a.graph).FullEdgesTo0ForVertex(indexmaxrnValue)\n //fmt.Printf(\"Se agrego %d\\n\", indexmaxrnValue)\n //fmt.Printf(\"Feromona Despues: %f\\n\", (*(*a.graph).vertexes)[indexmaxrnValue].pheromone)\n //a.PrintSolution()\n\n //Si q no es menor al valor dado q0\n }else{\n //Mientras que no da un paso la hormiga haremos lo sigueinte\n dioPaso := false\n for dioPaso != true{\n //Calculamos un indice de los vertices de manera aleatoria\n randomIndex := rand.Intn(len(rnvalues))\n //Calcualmos la probabilidad (como en el pdf) que la hormiga de un paso a este vertice\n indexProb := (rnvalues[randomIndex]/sumrnValues)\n //Calculamos otro numero aletaorioa entre 0 y 1\n randonNumber := a.random.Float64()\n //fmt.Printf(\"Random Index: %d indexProb: %f RandomNumber: %f\\n\", randomIndex, indexProb, randonNumber)\n //Si el numeor aleatorio calculado es menor o igual a la probabilidad de que la hormiga diera el paso a ese vertice\n //Entonces damos el paso a ese vertice\n //Vamos a agregar a la solucion el vertice con indice randomIndex\n //Actualzamos la feromona de manera local para el mismo vertice, y por ulitmo para ese vertice aremos a todas\n //Las aristas que inciden en el con valor 0\n if randonNumber <= indexProb{\n a.AgregaASolucion(randomIndex)\n a.ActualizaFeromonaLocalmente(randomIndex)\n (*a.graph).FullEdgesTo0ForVertex(randomIndex)\n //fmt.Printf(\"Se agrego %d\\n\", randomIndex)\n //Si damos el paso entonces hacemos este fvalor true de tal manera que esta fucnion se detendra\n dioPaso = true\n }\n }\n }\n //fmt.Printf(\"%f\\n\", q)\n //fmt.Printf(\"%t q=%f < %f=q0\\n\", q < a.q0, q, a.q0)\n}",
"func chooseLift(currentFloors *CurrentFloors, dest int) int {\n\tavailableLifts := 0\n\tchosenLift := -1\n\tvar destDiff float64\n\tfor i := 0; i < len(currentFloors.Current); i++ {\n\t\tif currentFloors.Current[i] == -1 {\n\t\t\tcontinue\n\t\t} else if availableLifts < 1 {\n\t\t\tavailableLifts += 1\n\t\t\tdestDiff = math.Abs(float64(dest - currentFloors.Current[i]))\n\t\t\tchosenLift = i+1\n\t\t} else if math.Abs(float64(dest - currentFloors.Current[i])) < destDiff {\n\t\t\tchosenLift = i+1\n\t\t}\n\t}\n\treturn chosenLift\n}",
"func (graph *Graph) VanillaTurnRestrictedShortestPath(source, target int64) (float64, []int64) {\n\n\tif source == target {\n\t\treturn 0, []int64{source}\n\t}\n\tvar ok bool\n\n\tif source, ok = graph.mapping[source]; !ok {\n\t\tlog.Println(\"No such source\")\n\t\treturn -1.0, nil\n\t}\n\tif target, ok = graph.mapping[target]; !ok {\n\t\tlog.Println(\"No such target\")\n\t\treturn -1.0, nil\n\t}\n\n\t// create vertex set Q\n\tQ := &minHeap{}\n\n\t// dist[source] ← 0\n\tdistance := make(map[int64]float64, len(graph.Vertices))\n\tdistance[source] = 0\n\n\t// prev[v] ← UNDEFINED\n\tprev := make(map[int64]int64, len(graph.Vertices))\n\t// st := time.Now()\n\t// for each vertex v in Graph:\n\tfor i := range graph.Vertices {\n\t\t// if v ≠ source:\n\t\tif graph.Vertices[i].vertexNum != source {\n\t\t\t// dist[v] = INFINITY\n\t\t\tdistance[graph.Vertices[i].vertexNum] = Infinity\n\t\t}\n\t\t// prev[v] ← UNDEFINED\n\t\t// nothing here\n\t}\n\tQ.add_with_priority(graph.Vertices[source].vertexNum, distance[graph.Vertices[source].vertexNum])\n\theap.Init(Q)\n\tprevNodeID := int64(-1)\n\t// while Q is not empty:\n\tfor Q.Len() != 0 {\n\t\t// u ← Q.extract_min()\n\t\tu := heap.Pop(Q).(*minHeapVertex)\n\t\tdestinationRestrictionID := int64(-1)\n\t\tif restrictions, ok := graph.restrictions[prevNodeID]; ok {\n\t\t\t// found some restrictions\n\t\t\tdestinationRestrictionID = restrictions[u.id]\n\t\t}\n\n\t\t// if u == target:\n\t\tif u.id == target {\n\t\t\t// break\n\t\t\tbreak\n\t\t}\n\n\t\tvertexList := graph.Vertices[u.id].outIncidentEdges\n\n\t\t// for each neighbor v of u:\n\t\tfor v := range vertexList {\n\t\t\tneighbor := vertexList[v].vertexID\n\t\t\tif v1, ok1 := graph.shortcuts[u.id]; ok1 {\n\t\t\t\tif _, ok2 := v1[neighbor]; ok2 {\n\t\t\t\t\t// Ignore shortcut\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif neighbor == destinationRestrictionID {\n\t\t\t\t// If there is a turn restriction\n\t\t\t\tdistance[u.id] = Infinity\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcost := vertexList[v].weight\n\t\t\t// alt ← dist[u] + length(u, v)\n\t\t\talt := distance[u.id] + cost\n\t\t\t// if alt < dist[v]\n\t\t\tif distance[neighbor] > alt {\n\t\t\t\t// dist[v] ← alt\n\t\t\t\tdistance[neighbor] = alt\n\t\t\t\t// prev[v] ← u\n\t\t\t\tprev[neighbor] = u.id\n\t\t\t\t// Q.decrease_priority(v, alt)\n\t\t\t\t// Q.decrease_priority(v, alt)\n\t\t\t\tQ.add_with_priority(neighbor, alt)\n\t\t\t}\n\t\t}\n\n\t\tprevNodeID = u.id\n\t\t// heap.Init(Q)\n\t}\n\n\t// path = []\n\tvar path []int64\n\t// u = target\n\tu := target\n\n\t// while prev[u] is defined:\n\tfor {\n\t\tif _, ok := prev[u]; !ok {\n\t\t\tbreak\n\t\t}\n\t\t// path.push_front(u)\n\t\ttemp := make([]int64, len(path)+1)\n\t\ttemp[0] = u\n\t\tcopy(temp[1:], path)\n\t\tpath = temp\n\n\t\t// u = prev[u]\n\t\tu = prev[u]\n\t}\n\n\ttemp := make([]int64, len(path)+1)\n\ttemp[0] = source\n\tcopy(temp[1:], path)\n\tpath = temp\n\n\tusersLabelsPath := make([]int64, len(path))\n\tfor e := 0; e < len(usersLabelsPath); e++ {\n\t\tusersLabelsPath[e] = graph.Vertices[path[e]].Label\n\t}\n\n\treturn distance[target], usersLabelsPath\n}",
"func artificialImmuneSystem(noOfGoods int, p PricingProblem, seed int64) (bestPrices []float64, bestRevenue float64) {\n\t// fmt.Printf(\"Starting Artificial Immune System\\n\")\n\n\trand.Seed(seed)\n\n\tstart := time.Now()\n\n\tvar population []Prices\n\n\t// Init population with random routes and Eval the routes.\n\tpopulation = generateRandomPopulation(noOfGoods, aispopSize, p)\n\n\t// Repeat until terminating condition (executeTime)\n\tfor {\n\t\t// Cloning\n\t\t// Create cloneSizeFactor amount of copies of each route in the population\n\t\tvar clonePool []Prices\n\t\tfor j := 0; j < len(population); j++ {\n\t\t\tfor k := 0; k < cloneSizeFactor; k++ {\n\t\t\t\tcurrentClone := Prices{}\n\t\t\t\tcurrentClone.revenue = population[j].revenue\n\t\t\t\tcurrentClone.prices = make([]float64, len(population[j].prices))\n\t\t\t\tcopy(currentClone.prices, population[j].prices)\n\t\t\t\tclonePool = append(clonePool, currentClone)\n\t\t\t}\n\t\t}\n\n\t\t// Mutation\n\t\t// For each clone in the pool:\n\t\t// \t1. Choose a random hotspot\n\t\t// \t2. Calc the length of section based on its fitness comapred to the best\n\t\t// 3. Reverse the section selected and place back into route\n\t\tfor j := 0; j < len(clonePool); j++ {\n\t\t\t// Random hotspot\n\t\t\tstart := rand.Intn(len(clonePool[j].prices))\n\n\t\t\tsize := len(clonePool[j].prices)\n\n\t\t\t// length = routeLength * exp(-p*f/fBest)\n\t\t\tinv := math.Exp(-0.5 * (clonePool[j].revenue / bestFitness))\n\t\t\tlengthFloat := inv * float64(size)\n\t\t\tlength := int(lengthFloat)\n\n\t\t\t// Reverse the section\n\t\t\tvar tmp []float64\n\t\t\tfor k := 0; k < length; k++ {\n\t\t\t\ttmp = append(tmp, clonePool[j].prices[(k+start)%size])\n\t\t\t}\n\n\t\t\tfor k := 0; k < length; k++ {\n\t\t\t\tclonePool[j].prices[(k+start)%size] = tmp[len(tmp)-(k+1)]\n\t\t\t}\n\n\t\t\t// Get the new cost of the clone\n\t\t\tclonePool[j].revenue = p.evaluate(clonePool[j].prices)\n\t\t}\n\n\t\t// Selection\n\t\t// 1. Combine the population and clone pool\n\t\t// 2. Sort the population by fitness\n\t\t// 3. Remove worst routes to get back to population size\n\n\t\t// Combine clones and original population\n\t\tpopulation = append(population, clonePool...)\n\n\t\t//Sort by fitness\n\t\tsort.SliceStable(population, func(i, j int) bool { return population[i].revenue > population[j].revenue })\n\n\t\t// Remove the worst routes\n\t\tpopulation = population[:aispopSize]\n\n\t\t// Metadynamics\n\t\t// Swap the worst kth routes with new random routes\n\t\tfor j := 1; j <= replacementSize; j++ {\n\t\t\tvar currentPrices Prices\n\t\t\tcurrentPrices.prices = randomPrices(noOfGoods)\n\t\t\tcurrentPrices.revenue = p.evaluate(currentPrices.prices)\n\t\t\tpopulation[len(population)-j] = currentPrices\n\t\t}\n\n\t\tbestPrices = population[0].prices\n\t\tbestRevenue = population[0].revenue\n\n\t\t// Check if ran out of time\n\t\tnow := time.Now()\n\t\tif now.Sub(start).Seconds() >= executeTime {\n\t\t\tfmt.Printf(\"\\tExecute Time Acheived\\n\")\n\t\t\tbreak\n\t\t}\n\t}\n\treturn\n}",
"func findNearest(schedules []window.Schedule) window.Schedule {\n\tvar next window.Schedule\n\tnow := time.Now()\n\tfor _, s := range schedules {\n\t\t// prefer an open schedule\n\t\tif s.IsOpen() {\n\t\t\tnext = s\n\t\t\tbreak\n\t\t}\n\t\t// Evaluate the next, closest closed schedule\n\t\tif next.Opens.IsZero() {\n\t\t\tnext = s\n\t\t\tcontinue\n\t\t}\n\t\tbestOpens := next.Opens.Sub(now).Seconds()\n\t\tthisOpens := s.Opens.Sub(now).Seconds()\n\t\t// New schedule in future, current in the past\n\t\tif thisOpens > 0 && bestOpens < 0 {\n\t\t\tnext = s\n\t\t}\n\t\t// Both schedules in the future, new schedule closer to now\n\t\tif thisOpens >= 0 && bestOpens >= 0 && thisOpens < bestOpens {\n\t\t\tnext = s\n\t\t}\n\t\t// Both schedules in the past, new schedule closer to now\n\t\tif thisOpens < 0 && bestOpens < 0 && thisOpens > bestOpens {\n\t\t\tnext = s\n\t\t}\n\t}\n\treturn next\n}",
"func SPBF(g *gs.Graph, src, dst *gs.Vertex) (string, bool) {\n\tsrc.StampD = 0\n\n\t// for each vertex u ∈ g.V\n\tvertices := g.GetVertices()\n\tfor _, vtx := range *vertices {\n\t\tif vtx == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// relax\n\t\tedges := g.GetEdges()\n\t\tfor _, edge := range *edges {\n\t\t\tif edge == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ta := edge.(*gs.Edge).Dst.StampD\n\t\t\tb := edge.(*gs.Edge).Src.StampD\n\t\t\tc := edge.(*gs.Edge).Weight\n\n\t\t\tif a > b+int64(c) {\n\t\t\t\tedge.(*gs.Edge).Dst.StampD = b + int64(c)\n\t\t\t}\n\n\t\t\t// Update Prev\n\t\t\tif edge.(*gs.Edge).Dst.Prev.Len() == 0 {\n\t\t\t\tedge.(*gs.Edge).Dst.Prev.PushBack(edge.(*gs.Edge).Src)\n\t\t\t} else {\n\t\t\t\tex := false\n\t\t\t\tpvs := edge.(*gs.Edge).Dst.Prev\n\t\t\t\tfor _, v := range *pvs {\n\t\t\t\t\tif v == nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t// if fmt.Sprintf(\"%v\", v.(*gs.Vertex).ID) == fmt.Sprintf(\"%v\", edge.(*gs.Edge).Src.ID) {\n\t\t\t\t\tif v.(*gs.Vertex) == edge.(*gs.Edge).Src {\n\t\t\t\t\t\tex = true\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif ex == false {\n\t\t\t\t\tedge.(*gs.Edge).Dst.Prev.PushBack(edge.(*gs.Edge).Src)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tedges := g.GetEdges()\n\tfor _, edge := range *edges {\n\t\tif edge == nil {\n\t\t\tcontinue\n\t\t}\n\t\ta := edge.(*gs.Edge).Dst.StampD\n\t\tb := edge.(*gs.Edge).Src.StampD\n\t\tc := edge.(*gs.Edge).Weight\n\n\t\tif a > b+int64(c) {\n\t\t\treturn \"There is negative weighted cycle (No Shortest Path)\", false\n\t\t}\n\t}\n\tresult := slice.NewSequence()\n\tTrackSPBF(g, src, dst, dst, result)\n\n\tvar rs string\n\tfor _, v := range *result {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\trs += fmt.Sprintf(\"%v(=%v) → \", v.(*gs.Vertex).ID, v.(*gs.Vertex).StampD)\n\t}\n\n\treturn rs[:len(rs)-5], true\n}",
"func jump(nums []int) int {\n\n\tn := len(nums)\n\tif n <= 1 {\n\t\treturn 0\n\t}\n\t//当前位置可达最远距离\n\tfar := 0\n\t//上一跳最远距离,到达该位置时,进行下一跳,跳至下一个位置最远距离\n\tend := 0\n\tstep := 0\n\tfor i := 0; i < n-1; i++ {\n\t\tif i+nums[i] > far {\n\t\t\tfar = i + nums[i]\n\t\t}\n\t\tif i == end {\n\t\t\tend = far\n\t\t\tstep++\n\t\t}\n\t}\n\t//判断最远距离是否到达终点\n\tif far < n-1 {\n\t\treturn -1\n\t}\n\treturn step\n}",
"func (s *Switch) probe_neighbours( target *string, commence, conclude, inc_cap int64, usr *string, usr_max int64 ) ( found *Switch, cap_trip bool ) {\n\tvar (\n\t\tfsw\t*Switch\t\t\t// next neighbour switch (through link)\n\t)\n\n\tfound = nil\n\tcap_trip = false\n\n\t//fmt.Printf( \"\\n\\nsearching neighbours of (%s) for %s\\n\", s.To_str(), *target )\n\tfor i := 0; i < s.lidx; i++ {\n\t\tif s != fsw {\n \t\t\thas_room, err := s.links[i].Has_capacity( commence, conclude, inc_cap, usr, usr_max )\n\t\t\tif has_room {\n\t\t\t\tfsw = s.links[i].forward\t\t\t\t// at the switch on the other side of the link\n\t\t\t\tif (fsw.Flags & tegu.SWFL_VISITED) == 0 {\n\t\t\t\t\tobj_sheep.Baa( 3, \"switch:probe_neigbour: following link %d -- has capacity to (%s) and NOT visited\", i, fsw.To_str() )\n\t\t\t\t\tif s.Cost + s.links[i].Cost < fsw.Cost {\n\t\t\t\t\t\t//fmt.Printf( \"\\tsetting cost: %d\\n\", s.Cost + s.links[i].Cost )\n\t\t\t\t\t\tfsw.Cost = s.Cost + s.links[i].Cost\n\t\t\t\t\t\tfsw.Prev = s\t\t\t\t\t\t\t\t// shortest path to this node is through s\n\t\t\t\t\t\tfsw.Plink = i\t\t\t\t\t\t\t\t// using its ith link\n\t\t\t\t\t}\n\t\n\t\t\t\t\tobj_sheep.Baa( 3, \"compare: (%s) (%s)\", *target, *(fsw.Get_id()) )\n\t\t\t\t\tif fsw.Has_host( target ) || *(fsw.Get_id()) == *target {\t\t\t// target is attahced to this switch, or the target is a swtich that is the forward switch\n\t\t\t\t\t\tfsw.Prev = s\n\t\t\t\t\t\tfsw.Plink = i\n\t\t\t\t\t\tfound = fsw\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tobj_sheep.Baa( 2, \"no capacity on link: %s\", err )\n\t\t\t\tcap_trip = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}",
"func Find(gs []*Geodesic, v Vector) int {\n\tif len(gs) == 1 {\n\t\treturn NaiveFind(gs[0], v)\n\t}\n\n\tgs0 := gs[0]\n\n\tstart := 0\n\tminDistSq := math.MaxFloat64\n\tif v.Z > 0 {\n\t\t// We are in the northern hemisphere, so we can disregard all southern\n\t\t// faces.\n\t\t// Start from the north pole at index 0.\n\t\tminDistSq = DistSq(gs0.Centers[start], v)\n\t\tfor i := 1; i <= 5; i++ {\n\t\t\tiDistSq := DistSq(gs0.Centers[i], v)\n\t\t\tif iDistSq < minDistSq {\n\t\t\t\tminDistSq = iDistSq\n\t\t\t\tstart = i\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// We are in the southern hemisphere, so we can disregard all northern\n\t\t// faces.\n\t\t// Start from the south pole at index 11.\n\t\tstart = 11\n\t\tminDistSq = DistSq(gs0.Centers[start], v)\n\t\tfor i := 6; i <= 10; i++ {\n\t\t\tiDistSq := DistSq(gs0.Centers[i], v)\n\t\t\tif iDistSq < minDistSq {\n\t\t\t\tminDistSq = iDistSq\n\t\t\t\tstart = i\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(gs) == 1 {\n\t\treturn start\n\t}\n\n\treturn find(gs[1:], v, minDistSq, start)\n}",
"func Solve(start int, vers int, edges [][]int) ([]int, error) {\n\td := make([]int, vers)\n\tfor i := range d {\n\t\td[i] = 1e15\n\t}\n\td[start] = 0\n\n\tvers--\n\tfor i := 0; i < vers; i++ {\n\t\tfor _, v := range edges {\n\t\t\tfrom, to, cost := v[0], v[1], v[2]\n\t\t\tif d[from]+cost >= d[to] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\td[to] = d[from] + cost\n\t\t}\n\t}\n\n\tfor _, v := range edges {\n\t\tfrom, to, cost := v[0], v[1], v[2]\n\t\tif d[from]+cost < d[to] {\n\t\t\treturn nil, fmt.Errorf(\"negative cycle\")\n\t\t}\n\t}\n\treturn d, nil\n}",
"func brute_force_worker(points [][]float64, ind_chan chan []int, results chan []int) {\n\tmin_inds := make([]int, len(points))\n\tvar min_len float64 = math.Inf(1)\n\t// keep pulling until it's over\n\tfor {\n\t\tinds, ok := <-ind_chan\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tcur_len := PathLengthInds(points, inds)\n\t\t// find the winner\n\t\tif cur_len < min_len {\n\t\t\tmin_len = cur_len\n\t\t\tcopy(min_inds, inds)\n\t\t}\n\t}\n\n\tresults <- min_inds\n}",
"func (ship Ship) Navigate(target Entity, gameMap Map) string {\n\tob := gameMap.ObstaclesBetween(ship.Entity, target)\n\n\tif !ob {\n\t\treturn ship.NavigateBasic(target, gameMap)\n\t}\n\n\tx0 := math.Min(ship.X, target.X)\n\tx2 := math.Max(ship.X, target.X)\n\ty0 := math.Min(ship.Y, target.Y)\n\ty2 := math.Max(ship.Y, target.Y)\n\n\tdx := (x2 - x0) / 5\n\tdy := (y2 - y0) / 5\n\tbestdist := 1000.0\n\tbestTarget := target\n\n\tfor x1 := x0; x1 <= x2; x1 += dx {\n\t\tfor y1 := y0; y1 <= y2; y1 += dy {\n\t\t\tintermediateTarget := Entity{\n\t\t\t\tX: x1,\n\t\t\t\tY: y1,\n\t\t\t\tRadius: 0,\n\t\t\t\tHealth: 0,\n\t\t\t\tOwner: 0,\n\t\t\t\tID: -1,\n\t\t\t}\n\t\t\tob1 := gameMap.ObstaclesBetween(ship.Entity, intermediateTarget)\n\t\t\tif !ob1 {\n\t\t\t\tob2 := gameMap.ObstaclesBetween(intermediateTarget, target)\n\t\t\t\tif !ob2 {\n\t\t\t\t\ttotdist := math.Sqrt(math.Pow(x1-x0, 2)+math.Pow(y1-y0, 2)) + math.Sqrt(math.Pow(x1-x2, 2)+math.Pow(y1-y2, 2))\n\t\t\t\t\tif totdist < bestdist {\n\t\t\t\t\t\tbestdist = totdist\n\t\t\t\t\t\tbestTarget = intermediateTarget\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ship.NavigateBasic(bestTarget, gameMap)\n}",
"func minKnightMoves(ex int, ey int) int {\r\n\tif ex == 0 && ey == 0 {\r\n\t\treturn 0\r\n\t}\r\n\tq := [][]int{}\r\n\tq = append(q, []int{0, 0})\r\n\tdir := [][]int{{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, 2}, {-2, 1}, {-1, -2}, {-2, -1}}\r\n\tsteps := 0\r\n\tseen := map[int]map[int]bool{0: map[int]bool{0: true}}\r\n\t// BFS loop\r\n\tfor len(q) > 0 {\r\n\t\tsteps++\r\n\t\tn := len(q)\r\n\t\tfor i := 0; i < n; i++ {\r\n\t\t\tt := q[0]\r\n\t\t\tq = q[1:]\r\n\t\t\tfor _, d := range dir {\r\n\t\t\t\tnx := t[0] + d[0]\r\n\t\t\t\tny := t[1] + d[1]\r\n\t\t\t\tif nx == ex && ny == ey {\r\n\t\t\t\t\treturn steps\r\n\t\t\t\t}\r\n\t\t\t\tif _, exists := seen[nx]; !exists {\r\n\t\t\t\t\tseen[nx] = map[int]bool{}\r\n\t\t\t\t}\r\n\t\t\t\tif _, exists := seen[nx][ny]; !exists &&\r\n\t\t\t\t\t(nx*ex >= 0 && ny*ey >= 0 || steps < 3) {\r\n\t\t\t\t\tseen[nx][ny] = true\r\n\t\t\t\t\tq = append(q, []int{nx, ny})\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn -1\r\n}",
"func spfa(s int, t int)(bool){\n\tgPre = make([]int, nodeNum) // initialize gPre\n\tfor i:=0; i<len(gPre); i ++ {\n\t\tgPre[i] = -1 // default -1\n\t}\n\n\tgPath = make([]int, nodeNum) // initialize gPath\n\tfor i:=0; i<len(gPath); i ++ {\n\t\tgPath[i] = -1 // default -1\n\t}\n\n\tgDist = make([]int, nodeNum) // initialize gDist\n\tfor i:=0; i<len(gDist); i ++ {\n\t\tgDist[i] = int(^uint(0) >> 1) // default INT_MAX\n\t}\n\n\tgDist[s] = 0\n\tQ := list.New() // Q is the loose queue, it record all node , from which the min cost to another node may change\n\tQ.PushBack(s)\n\tfor Q.Len() > 0 {\n\t\tu_element := Q.Front()\n\t\tQ.Remove(u_element)\n\t\tu, err := u_element.Value.(int)\n\t\tif(!err){\n\t\t\tpanic(err)\n\t\t}\n\t\tfor e := gHead[u]; e != -1; e = gEdges[e].next { // visit all edges has node u as their src node\n\t\t\tv := gEdges[e].to\n\t\t\tif gEdges[e].vol > 0 && gDist[u]+gEdges[e].cost < gDist[v] { // if edge e has availiable capacity and node v's current min cost is more than that from node u to v\n\t\t\t\tgDist[v] = gDist[u] + gEdges[e].cost // update node v's min cost\n\t\t\t\tgPre[v] = u\n\t\t\t\tgPath[v] = e\n\t\t\t\tQ.PushBack(v) // because v's min cost has changed, so we need to check if the nodes that node v can reach can change its min cost\n\t\t\t}\n\t\t}\n\t}\n\n\tif gPre[t] == -1 {\n\t\treturn false\n\t}\n\treturn true\n\n}",
"func FindPath(mp Graph, start, end Node) ([]Node, error) {\n\tmapCapacity := int(end - start)\n\tif mapCapacity < 0 {\n\t\tmapCapacity = -mapCapacity\n\t}\n\tif mapCapacity > maxDefaultMapCapacity {\n\t\tmapCapacity = maxDefaultMapCapacity\n\t}\n\t// The open list is ordered by the sum of current cost + heuristic cost\n\tstate := newState(mapCapacity)\n\t// Add the start node to the openlist\n\tpCost, err := mp.HeuristicCost(start, end)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstate.addNodeInfo(&nodeInfo{\n\t\tnode: start,\n\t\tparent: -1,\n\t\tcost: 0.0,\n\t\tpredictedCost: float32(pCost),\n\t})\n\n\tedgeSlice := make([]Edge, 0, 8)\n\tfor {\n\t\tcurrent := state.popBest()\n\t\tif current == nil {\n\t\t\treturn nil, ErrImpossible\n\t\t}\n\t\tif current.node == end {\n\t\t\t// If we reached the end node then we know the optimal path. Traverse\n\t\t\t// it (backwards) and return an array of node IDs.\n\t\t\treturn state.pathToNode(current), nil\n\t\t}\n\t\tif current.cost >= state.maxCost {\n\t\t\tcontinue\n\t\t}\n\t\tif dbg, ok := mp.(Debug); ok {\n\t\t\tdbg.VisitedNode(current.node, current.parent, float64(current.cost), float64(current.predictedCost))\n\t\t}\n\t\tneighbors, err := mp.Neighbors(current.node, edgeSlice[:0])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, edge := range neighbors {\n\t\t\t// Don't try go backwards\n\t\t\tif edge.Node == current.parent {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Cost for the neighbor node is the current cost plus the\n\t\t\t// cost to get to that node.\n\t\t\tcost := current.cost + float32(edge.Cost)\n\n\t\t\tni := state.info[edge.Node]\n\t\t\tif ni == nil {\n\t\t\t\t// We haven't seen this node so add it to the open list.\n\t\t\t\tpCost, err := mp.HeuristicCost(edge.Node, end)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tni = &nodeInfo{\n\t\t\t\t\tnode: edge.Node,\n\t\t\t\t\tparent: current.node,\n\t\t\t\t\tcost: cost,\n\t\t\t\t\tpredictedCost: float32(pCost),\n\t\t\t\t}\n\t\t\t\tstate.addNodeInfo(ni)\n\t\t\t} else if cost < ni.cost {\n\t\t\t\t// We've seen this node and the current path is cheaper\n\t\t\t\t// so update the changed info and add it to the open list\n\t\t\t\t// (replacing if necessary).\n\t\t\t\tni.parent = current.node\n\t\t\t\tni.cost = cost\n\t\t\t\tif ni.index >= 0 {\n\t\t\t\t\tstate.updateNodeInfo(ni)\n\t\t\t\t} else {\n\t\t\t\t\tstate.addNodeInfo(ni)\n\t\t\t\t}\n\t\t\t} else if edge.Node == end {\n\t\t\t\tif cost < state.maxCost {\n\t\t\t\t\tstate.maxCost = cost\n\t\t\t\t}\n\t\t\t\tif pp, ok := mp.(PossiblePath); ok {\n\t\t\t\t\tpath := append(state.pathToNode(current), end)\n\t\t\t\t\tpp.PossiblePath(path, float64(cost))\n\t\t\t\t}\n\t\t\t\tni = nil\n\t\t\t}\n\t\t\tif ni != nil && edge.Node == end {\n\t\t\t\tif cost < state.maxCost {\n\t\t\t\t\tstate.maxCost = cost\n\t\t\t\t}\n\t\t\t\tif pp, ok := mp.(PossiblePath); ok {\n\t\t\t\t\tpp.PossiblePath(state.pathToNode(ni), float64(ni.cost))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"func TravelingSalesmanBruteForce(graph Graph, branchAndBound bool) float64 {\n\n // ----------------------------------------------\n // check pre-requirements\n // ----------------------------------------------\n\n // get the number of vertices\n num := int(graph.GetVertices().Count())\n\n // this algorithm only works with 5 to 15 vertices\n if num <= 4 || num > tsbfMax {\n return 0\n }\n\n // ----------------------------------------------\n // preparations\n // ----------------------------------------------\n\n // we access this one often, so better calculate it only once\n lastVertex := num - 1\n\n // use own vertex structure that has an index which refers to its position in the vertices array\n // it also contains an array to each other position containing the distance between the vertices\n type vertex struct {\n graphLib.VertexInterface\n index int\n distances [tsbfMax]float64\n }\n\n // create vertices and calculate distance once here instead of doing it multiple times later\n var vertices [tsbfMax]*vertex\n for i, v := range graph.GetVertices().All() {\n\n // create vertex\n vertices[i] = &vertex{\n VertexInterface: v,\n index: i,\n }\n\n // add distances for all previously created vertices\n for j, v2 := range vertices[:i] {\n w := graph.getWeightBetween(v, v2.VertexInterface)\n // make the distances two-way\n vertices[i].distances[j] = w\n v2.distances[i] = w\n }\n\n }\n\n // the shortest circle's length will be stored in here\n length := math.MaxFloat64\n\n // ----------------------------------------------\n // build helpers\n // ----------------------------------------------\n // There will be 2 different helpers:\n // * The intermediate helper will be called recursively and ...\n // ... creates all possible permutations of the remaining vertices.\n // * The end helper will be called at the end of the recursion and ...\n // ... updates the length variable if a new shortest circle was found.\n // ----------------------------------------------\n\n // there will be 2 different helper functions. both will be stored in this array\n var helpers [tsbfMax - 2]func(int, *vertex, *vertex, float64)\n\n // end helper\n helpers[num - 3] = func(n int, front, end *vertex, currentLength float64) {\n rest0index := vertices[n].index\n l := currentLength + front.distances[rest0index] + end.distances[rest0index]\n if l < length {\n length = l\n }\n }\n\n // intermediate helper\n for i := num - 4; i >= 1; i-- {\n if branchAndBound {\n // when using branch and bound, check the length on each recursion level\n // abort if already longer than the shortest known circle\n helpers[i] = func(n int, front, end *vertex, currentLength float64) {\n\n n1, rest0, rest0Temp, frontDist, weightTmp := n + 1, vertices[n], (*vertex)(nil), &front.distances, 0.0\n next := helpers[n]\n\n // when not changing the order\n weightTmp = currentLength + frontDist[rest0.index]\n if weightTmp < length {\n next(n1, rest0, end, weightTmp)\n }\n\n // combinations of changing the order\n for i := n1; i < lastVertex; i++ {\n\n // change order\n rest0Temp, vertices[i] = vertices[i], rest0\n\n // recursion\n weightTmp = currentLength + frontDist[rest0Temp.index]\n if weightTmp < length {\n next(n1, rest0Temp, end, weightTmp)\n }\n\n // change back\n vertices[i] = rest0Temp\n }\n }\n } else {\n helpers[i] = func(n int, front, end *vertex, currentLength float64) {\n\n n1, rest0, rest0Temp, frontDist := n + 1, vertices[n], (*vertex)(nil), &front.distances\n next := helpers[n]\n\n // when not changing the order\n next(n1, rest0, end, currentLength + frontDist[rest0.index])\n\n // combinations of changing the order\n for i := n1; i < lastVertex; i++ {\n\n // change order\n rest0Temp, vertices[i] = vertices[i], rest0\n\n // recursion\n next(n1, rest0Temp, end, currentLength + frontDist[rest0Temp.index])\n\n // change back\n vertices[i] = rest0Temp\n }\n }\n }\n }\n\n // ----------------------------------------------\n // Strategy\n // ----------------------------------------------\n // 1. Pick 0 as start vertex.\n // 2. Pick every _set_ of two vertices and put one left and one right of the start vertex\n // 3. Use every permutation of the remaining vertices to close the circle and calculate the length.\n // Use recursion for the permutation.\n // ----------------------------------------------\n\n // ----------------------------------------------\n // 1. Pick 0 as start vertex.\n // ----------------------------------------------\n startDist := vertices[0].distances\n\n // ----------------------------------------------\n // 2. Pick every _set_ of two vertices and put one left and one right of the start vertex\n // ----------------------------------------------\n\n // when swapping vertices, use this variables for the front and end to read from (faster than array access)\n rest0, end := vertices[1], vertices[lastVertex]\n\n // when swapping vertices, use this variables for the front and end to write to (faster than array access)\n var rest0Temp, endTemp *vertex\n\n // select first element of the set\n for i := 1; i < lastVertex; i++ {\n\n // swap. we do not actually need to swap, ...\n // ... because on the next recursion levels only the indexes 2 upwards are accessed\n rest0Temp, vertices[i] = vertices[i], rest0\n\n // select second element of the set that is greater than the first one\n for j := i + 1; j <= lastVertex; j++ {\n\n // swap. we do not actually need to swap, ...\n // ... because on the next recursion levels the last vertex is never accessed\n endTemp, vertices[j] = vertices[j], end\n\n // ----------------------------------------------\n // 3. Use every permutation of the remaining vertices to close the circle and calculate the length.\n // ----------------------------------------------\n helpers[1](2, rest0Temp, endTemp, startDist[i] + startDist[j])\n\n // swap back. since we did not really swap above, this is as simple as an assignment\n vertices[j] = endTemp\n }\n\n // swap back. since we did not really swap above, this is as simple as an assignment\n vertices[i] = rest0Temp\n }\n\n // returns the length of the shortest hamilton circle\n return length\n}",
"func interpolationSearch(x int, arr []int) int {\r\n\r\n\t//sort array\r\n\tsort.Ints(arr)\r\n\r\n\tfmt.Printf(\"Sorted: %v, arr lenght:%d\\n\", arr, len(arr))\r\n\r\n\tif len(arr) != 0 {\r\n\r\n\t\tmiddle :=\r\n\t\t\t((x - arr[0]) * (len(arr) - 0)) / (arr[len(arr)-1] -\r\n\t\t\t\tarr[0])\r\n\r\n\t\tfmt.Printf(\"middle:%d\\n\", middle)\r\n\r\n\t\tif arr[middle] == x {\r\n\t\t\tfmt.Printf(\"Finded!, value: %d\\n\", arr[middle])\r\n\t\t\treturn arr[middle]\r\n\t\t}\r\n\r\n\t\t//if middle is greater than x\r\n\t\tif x < arr[middle] {\r\n\t\t\treturn binarySearch(x, arr[0:middle])\r\n\t\t}\r\n\r\n\t\t//if middle is less than x\r\n\t\tif x > arr[middle] {\r\n\t\t\treturn binarySearch(x, arr[middle:len(arr)])\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tfmt.Printf(\"Cannot find: %d\\n\", x)\r\n\treturn -1\r\n\r\n}",
"func solve2(input string) string {\n\tg := makeGrid(input)\n\td := g.GetDelayToMinimalDelayIntersection()\n\treturn fmt.Sprintf(\"%d\", d)\n}",
"func halfSolutionPath(links map[string]string, objective, start string) []string {\n if start == objective {\n return []string{}\n } else {\n next := links[start]\n return append(halfSolutionPath(links, objective, next), next)\n }\n}",
"func BFS(mat [][]int, startPos Position, state State, searchVal, maxDepth int) BFSResult {\n\tres := BFSResult{foodDepth: maxDepth, nearestSnakeDepth: maxDepth}\n\tqueue := list.New()\n\tqueue.PushBack(BFSNode{startPos, 1})\n\tmatrix := duplicateMatrix(mat)\n\t//fmt.Println(matrix)\n\tfor queue.Len() > 0 {\n\t\t// Get next element\n\t\tcurr := queue.Front()\n\t\tnode := curr.Value.(BFSNode)\n\t\tpos := node.pos\n\t\tqueue.Remove(curr)\n\n\t\t// Max depth reached\n\t\tif node.depth > maxDepth { break }\n\n\t\t// Test for in bounds\n\t\tif !isPositionInBounds(pos, state) { continue }\n\n\t\t// Don't look at the same value\n\t\tif matrix[pos.y][pos.x] == 1 { continue }\n\n\t\t// Test if we found closest enemy position\n\t\tif res.nearestSnakeDepth == maxDepth {\n\t\t\tif matrix[pos.y][pos.x] == 2 {\n\t\t\t\tres.nearestSnakeDepth = int(math.Abs(float64(pos.x) - float64(startPos.x)))\n\t\t\t\tres.nearestSnakeDepth = int(math.Abs(float64(pos.y) - float64(startPos.y)))\n\t\t\t}\n\t\t}\n\n\t\tif !isValidPosition(pos, state) { continue }\n\n\t\t// Test if we found the closes food position\n\t\tif res.foodDepth == maxDepth {\n\t\t\tif matrix[pos.y][pos.x] == 3 {\n\t\t\t\tres.foodDepth = int(math.Abs(float64(pos.x) - float64(startPos.x)))\n\t\t\t\tres.foodDepth += int(math.Abs(float64(pos.y) - float64(startPos.y)))\n\t\t\t}\n\t\t}\n\n\t\t// Mark as visited\n\t\tmatrix[pos.y][pos.x] = 1\n\n\t\t// Add next elements to queue\n\t\taddPositionsToQueue(queue, matrix, pos, state, node.depth + 1)\n\n\t\t// Update max depth\n\t\tif node.depth + 1 > res.emptySpaceDepth {\n\t\t\tres.emptySpaceDepth = node.depth + 1\n\t\t}\n\t}\n\n\treturn res\n}",
"func (iter *Iterator) tick(i, min int, delta []*vcache) (ok bool, err error) {\n\tnext := make([]*vcache, i)\n\n\t// The biggest outer loop is walking backwards over iter.In[i]\n\tx := len(iter.in[i])\n\tfor x > 0 {\n\t\tj := iter.in[i][x-1]\n\n\t\tif j <= min {\n\t\t\treturn false, iter.restore(next, i)\n\t\t} else if iter.blacklist[j] {\n\t\t\tx--\n\t\t\tcontinue\n\t\t}\n\n\t\tv := iter.variables[j]\n\n\t\tself := v.save()\n\n\t\tif v.value = v.Next(); v.value == NIL {\n\t\t\t// That sucks. Now we need to restore the value\n\t\t\t// that was changed and decrement x.\n\t\t\tv.value = v.Seek(self.ID)\n\t\t\tx--\n\t\t} else {\n\t\t\t// We got a non-nil value for v, so now we\n\t\t\t// propagate between j and i, then crawl forward\n\t\t\t// over the indices in iter.Out[q] that are less than i\n\t\t\t// and seek to their new values.\n\n\t\t\t// Propagate up to but not including i\n\t\t\tif err = iter.push(v, j, i); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Fantastic. Now that we've propagated the value we found for v,\n\t\t\t// we start \"the crawl\" from j to i, seeking to the new satisfying root\n\t\t\t// and recursing on tick when necessary.\n\t\t\tcursor := j\n\t\t\titer.blacklist[j] = true\n\t\t\tfor _, k := range iter.out[j] {\n\t\t\t\tif k >= i {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw := iter.variables[k]\n\n\t\t\t\tif next[k] == nil {\n\t\t\t\t\tnext[k] = w.save()\n\t\t\t\t}\n\n\t\t\t\td := make([]*vcache, k)\n\n\t\t\t\t// Here we keep seeking and ticking until we have a real value.\n\t\t\t\tfor w.value = w.Seek(w.root); w.value == NIL; w.value = w.Seek(w.root) {\n\t\t\t\t\tif ok, err = iter.tick(k, min, d); err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t} else if ok {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err = iter.restore(d, i); err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif w.value == NIL {\n\t\t\t\t\t// We were unable to complete the crawl.\n\t\t\t\t\t// We've already reset our state.\n\t\t\t\t\t// This is how far we got:\n\t\t\t\t\tcursor = k + 1\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\t// We got a real value for w! Now we propagate the affected values\n\t\t\t\t// through i and stash them into next if they're not there already,\n\t\t\t\t// and then continue with the tick-crawl.\n\t\t\t\terr = iter.push(w, k, i)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tfor l, saved := range d {\n\t\t\t\t\tif saved != nil {\n\t\t\t\t\t\terr = iter.push(iter.variables[l], l, i)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif next[l] == nil {\n\t\t\t\t\t\t\tnext[l] = saved\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// We need to *unset* the blacklist after recursing.\n\t\t\t// Variables are only blacklisted when they appear as\n\t\t\t// a parent in the call stack - they might be visited\n\t\t\t// twice as siblings in the call tree, etc.\n\t\t\titer.blacklist[j] = false\n\n\t\t\tif cursor == j {\n\t\t\t\t// Hooray!\n\t\t\t\t// Now here we need to push every affected value\n\t\t\t\t// through to the rest of the domain\n\t\t\t\t// delta[j] = self\n\t\t\t\tnext[j] = self\n\t\t\t\tfor l, saved := range next {\n\t\t\t\t\tif saved != nil {\n\t\t\t\t\t\tif delta[l] == nil {\n\t\t\t\t\t\t\tdelta[l] = saved\n\t\t\t\t\t\t}\n\t\t\t\t\t\terr = iter.push(iter.variables[l], i, iter.Len())\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true, nil\n\t\t\t}\n\n\t\t\t// This means we reset (all) those affected to their previous state\n\t\t\terr = iter.restore(next, i)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}",
"func (h changepointHeuristic) isChangepointPossibleWithNext(nextPositionCounts counts) bool {\n\tconsider := false\n\tif nextPositionCounts.Runs > 0 {\n\t\t// Detect expected-to-unexpected transition (or vica-versa).\n\t\taddingUnexpectedRuns := nextPositionCounts.HasUnexpected > 0\n\t\taddingExpectedRuns := (nextPositionCounts.Runs - nextPositionCounts.HasUnexpected) > 0\n\t\tconsider = consider || addingUnexpectedRuns && h.addedExpectedRuns\n\t\tconsider = consider || addingExpectedRuns && h.addedUnexpectedRuns\n\t}\n\tif nextPositionCounts.Retried > 0 {\n\t\t// Detect expected-to-unexpected transition in the result\n\t\t// after retries (or vica-versa).\n\t\taddingUnexpectedAfterRetry := nextPositionCounts.UnexpectedAfterRetry > 0\n\t\taddingExpectedAfterRetry := (nextPositionCounts.Retried - nextPositionCounts.UnexpectedAfterRetry) > 0\n\t\tconsider = consider || addingUnexpectedAfterRetry && h.addedExpectedAfterRetry\n\t\tconsider = consider || addingExpectedAfterRetry && h.addedUnexpectedAfterRetry\n\t}\n\treturn consider\n}",
"func (p *pathFinder) act(maze [][]*MazeCell) *pathFinder {\n\tvar tried_north, tried_south, tried_east, tried_west bool\n\tvar new_finder *pathFinder\n\tvar dir int\n\tmax_x := len(maze) - 1\n\tmax_y := len(maze[0]) - 1\n\n\tfor !(tried_north && tried_south && tried_east && tried_west) {\n\t\tdir = rand.Intn(4)\n\t\tacted := false\n\n\t\tswitch dir {\n\t\tcase NORTH:\n\t\t\tif !tried_north {\n\t\t\t\ttried_north = true\n\t\t\t\tif p.y < max_y && !maze[p.x][p.y+1].visited {\n\t\t\t\t\tmaze[p.x][p.y].N = false\n\t\t\t\t\tmaze[p.x][p.y+1].S = false\n\t\t\t\t\tmaze[p.x][p.y+1].visited = true\n\t\t\t\t\tp.y++\n\t\t\t\t\tacted = true\n\t\t\t\t}\n\t\t\t}\n\t\tcase SOUTH:\n\t\t\tif !tried_south {\n\t\t\t\ttried_south = true\n\t\t\t\tif p.y > 0 && !maze[p.x][p.y-1].visited {\n\t\t\t\t\tmaze[p.x][p.y].S = false\n\t\t\t\t\tmaze[p.x][p.y-1].N = false\n\t\t\t\t\tmaze[p.x][p.y-1].visited = true\n\t\t\t\t\tp.y--\n\t\t\t\t\tacted = true\n\t\t\t\t}\n\t\t\t}\n\t\tcase EAST:\n\t\t\tif !tried_east {\n\t\t\t\ttried_east = true\n\t\t\t\tif p.x < max_x && !maze[p.x+1][p.y].visited {\n\t\t\t\t\tmaze[p.x][p.y].E = false\n\t\t\t\t\tmaze[p.x+1][p.y].W = false\n\t\t\t\t\tmaze[p.x+1][p.y].visited = true\n\t\t\t\t\tp.x++\n\t\t\t\t\tacted = true\n\t\t\t\t}\n\t\t\t}\n\t\tcase WEST:\n\t\t\tif !tried_west {\n\t\t\t\ttried_west = true\n\t\t\t\tif p.x > 0 && !maze[p.x-1][p.y].visited {\n\t\t\t\t\tmaze[p.x][p.y].W = false\n\t\t\t\t\tmaze[p.x-1][p.y].E = false\n\t\t\t\t\tmaze[p.x-1][p.y].visited = true\n\t\t\t\t\tp.x--\n\t\t\t\t\tacted = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif acted {\n\t\t\tif rand.Float64() <= SPAWN_RATE {\n\t\t\t\tnew_finder = new(pathFinder)\n\t\t\t\tnew_finder.x = p.x\n\t\t\t\tnew_finder.y = p.y\n\t\t\t}\n\t\t\treturn new_finder\n\t\t}\n\t}\n\n\tp.dead = true\n\treturn nil\n}",
"func Solution(A []int) int {\n\t// write your code in Go 1.4\n\tvar peakIndex []int\n\t// var currentFlags int\n\tfor i, val := range A {\n\t\tif i == 0 || i == len(A)-1 {\n\t\t\tcontinue\n\t\t} else if val > A[i-1] && val > A[i+1] {\n\t\t\tfmt.Printf(\"masuk sini val %v\\n\", val)\n\t\t\tpeakIndex = append(peakIndex, i)\n\t\t}\n\t}\n\tk := len(peakIndex)\n\tif k == 0 {\n\t\treturn 0\n\t}\n\tfmt.Printf(\"peakIndex %v\\n\", peakIndex)\n\treturn k\n}",
"func fitness(hyp [cityCount]int) (fitness int) {\n\tfor i := 0; i < len(hyp)-1; i++ {\n\t\tx, y := hyp[i], hyp[i+1]\n\t\tfitness -= getDistance(x, y)\n\t}\n\n\tfitness -= getDistance(hyp[len(hyp)-1], hyp[0]) //Return home from last city\n\n\treturn fitness\n}",
"func (of *Offspring) RelativeFitness() float64 {\n\treturn float64(of.Fitness) / float64( of.MaxFitness() )\n}",
"func dstech(n int, a, b, eig *mat.Vector, tol float64, work *mat.Vector) (info int) {\n\tvar emin, eps, lower, mx, tuppr, unflep, upper, zero float64\n\tvar bpnt, count, i, isub, j, numl, numu, tpnt int\n\n\tzero = 0.0\n\n\t// Check input parameters\n\tinfo = 0\n\tif n == 0 {\n\t\treturn\n\t}\n\tif n < 0 {\n\t\tinfo = -1\n\t\treturn\n\t}\n\tif tol < zero {\n\t\tinfo = -5\n\t\treturn\n\t}\n\n\t// Get machine constants\n\teps = golapack.Dlamch(Epsilon) * golapack.Dlamch(Base)\n\tunflep = golapack.Dlamch(SafeMinimum) / eps\n\teps = tol * eps\n\n\t// Compute maximum absolute eigenvalue, error tolerance\n\tmx = math.Abs(eig.Get(0))\n\tfor i = 2; i <= n; i++ {\n\t\tmx = math.Max(mx, math.Abs(eig.Get(i-1)))\n\t}\n\teps = math.Max(eps*mx, unflep)\n\n\t// Sort eigenvalues from EIG into WORK\n\tfor i = 1; i <= n; i++ {\n\t\twork.Set(i-1, eig.Get(i-1))\n\t}\n\tfor i = 1; i <= n-1; i++ {\n\t\tisub = 1\n\t\temin = work.Get(0)\n\t\tfor j = 2; j <= n+1-i; j++ {\n\t\t\tif work.Get(j-1) < emin {\n\t\t\t\tisub = j\n\t\t\t\temin = work.Get(j - 1)\n\t\t\t}\n\t\t}\n\t\tif isub != n+1-i {\n\t\t\twork.Set(isub-1, work.Get(n+1-i-1))\n\t\t\twork.Set(n+1-i-1, emin)\n\t\t}\n\t}\n\n\t// TPNT points to singular value at right endpoint of interval\n\t// BPNT points to singular value at left endpoint of interval\n\ttpnt = 1\n\tbpnt = 1\n\n\t// Begin loop over all intervals\nlabel50:\n\t;\n\tupper = work.Get(tpnt-1) + eps\n\tlower = work.Get(bpnt-1) - eps\n\n\t// Begin loop merging overlapping intervals\nlabel60:\n\t;\n\tif bpnt == n {\n\t\tgoto label70\n\t}\n\ttuppr = work.Get(bpnt) + eps\n\tif tuppr < lower {\n\t\tgoto label70\n\t}\n\n\t// Merge\n\tbpnt = bpnt + 1\n\tlower = work.Get(bpnt-1) - eps\n\tgoto label60\nlabel70:\n\t;\n\n\t// Count singular values in interval [ LOWER, UPPER ]\n\tnuml = dstect(n, a, b, lower)\n\tnumu = dstect(n, a, b, upper)\n\tcount = numu - numl\n\tif count != bpnt-tpnt+1 {\n\t\t// Wrong number of singular values in interval\n\t\tinfo = tpnt\n\t\treturn\n\t}\n\ttpnt = bpnt + 1\n\tbpnt = tpnt\n\tif tpnt <= n {\n\t\tgoto label50\n\t}\n\n\treturn\n}",
"func heuristic(goal *maze.CellIndex, current *maze.CellIndex) uint64 {\n\treturn uint64((goal.Row-current.Row)*(goal.Row-current.Row) + (goal.Col-current.Col)*(goal.Col-current.Col))\n}",
"func (d *Dijkstra) Search() {\n\td.frontier[d.source] = graphEdge{From: d.source, To: d.source} // source node is special\n\td.cost[d.source] = 0\n\tpq := NewIndexedPriorityQueueMin(d.cost)\n\tpq.Insert(d.source)\n\n\tfor !pq.IsEmpty() {\n\t\tidx, err := pq.Pop()\n\t\tif err != nil {\n\t\t\td.err = err\n\t\t\treturn\n\t\t}\n\n\t\tedge := d.frontier[idx]\n\t\td.spt[idx] = edge\n\t\ti := edge.To\n\n\t\tif i == d.target {\n\t\t\treturn\n\t\t}\n\n\t\tfor _, e := range d.graph.edges[i] {\n\t\t\tnewCost := d.cost[i] + e.Cost\n\t\t\tt := e.To\n\t\t\tif _, ok := d.frontier[t]; !ok {\n\t\t\t\td.frontier[t] = e\n\t\t\t\td.cost[t] = newCost\n\t\t\t\tpq.Insert(t)\n\t\t\t} else if newCost < d.cost[t] {\n\t\t\t\tif _, ok := d.spt[t]; !ok {\n\t\t\t\t\td.frontier[t] = e\n\t\t\t\t\td.cost[t] = newCost\n\t\t\t\t\tpq.ChangePriority(t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"func (e *edm) calc() int {\n\tnormalize(e.z)\n\n\te.bestStat = math.Inf(-1)\n\te.tau = e.delta\n\ttau2 := 2 * e.delta\n\n\td := medianResolution(len(e.z))\n\te.ta = NewIntervalTree(d)\n\te.tb = NewIntervalTree(d)\n\te.tab = NewIntervalTree(d)\n\n\tfor i := 0; i < e.tau; i++ {\n\t\tfor j := i + 1; j < e.tau; j++ {\n\t\t\te.ta.Insert(e.z[i] - e.z[j])\n\t\t}\n\t}\n\n\tfor i := e.tau; i < tau2; i++ {\n\t\tfor j := i + 1; j < tau2; j++ {\n\t\t\te.tb.Insert(e.z[i] - e.z[j])\n\t\t}\n\t}\n\n\tfor i := 0; i < e.tau; i++ {\n\t\tfor j := e.tau; j < tau2; j++ {\n\t\t\te.tab.Insert(e.z[i] - e.z[j])\n\t\t}\n\t}\n\n\ttau2 += 1\n\tfor ; tau2 < len(e.z)+1; tau2++ {\n\t\te.tb.Insert(e.z[tau2-1] - e.z[tau2-2])\n\t\te.stat(tau2)\n\t}\n\n\tforward := false\n\tfor e.tau < len(e.z)-e.delta {\n\t\tif forward {\n\t\t\te.forwardUpdate()\n\t\t} else {\n\t\t\te.backwardUpdate()\n\t\t}\n\t\tforward = !forward\n\t}\n\n\treturn e.bestIdx\n}",
"func pickWay(p []float64) int {\n\tvar sum float64\n\tfor _, j := range p {\n\t\tsum += j\n\t}\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\trn := r.Float64() * sum\n\tsum = 0\n\tfor i, j := range p {\n\t\tif rn > sum && rn < sum+j {\n\t\t\treturn i\n\t\t}\n\t\tsum += j\n\t}\n\treturn -1\n}",
"func solveAlgo6(g Solver, l *Line) {\n\t//l.print(\"solveAlgo6\")\n\trsg := l.getUnsolvedRanges()\n\n\tfor _, r := range rsg {\n\t\tcs := l.getPotentialCluesForRange(r)\n\n\t\tlongest := 0\n\t\tisFound, step := l.getStepToNextBlank(r, false)\n\t\tif isFound {\n\t\t\tisFound = false\n\t\t\tfor _, c := range cs {\n\t\t\t\tif c.index < l.ce {\n\t\t\t\t\tnext := l.clues[c.index+1]\n\t\t\t\t\tif step <= c.length-r.length() || step > next.length {\n\t\t\t\t\t\tisFound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlongest = max(longest, c.length-r.length())\n\t\t\t}\n\t\t\t//if we didn't find anyone, we can blank taking into account the longest trail\n\t\t\tif len(cs) > 1 && !isFound {\n\t\t\t\tfor i := longest + 1; i <= step; i++ {\n\t\t\t\t\tg.SetValue(l.squares[r.max+i], BLANK)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlongest = 0\n\t\tisFound, step = l.getStepToNextBlank(r, true)\n\t\tif isFound {\n\t\t\tisFound = false\n\t\t\tfor _, c := range cs {\n\t\t\t\tif c.index > l.cb {\n\t\t\t\t\tprevious := l.clues[c.index-1]\n\t\t\t\t\tif step <= c.length-r.length() || step > previous.length {\n\t\t\t\t\t\tisFound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlongest = max(longest, c.length-r.length())\n\t\t\t}\n\t\t\t//if we didn't find anyone, we can blank taking into account the longest trail\n\t\t\tif len(cs) > 1 && !isFound {\n\t\t\t\tfor i := longest + 1; i <= step; i++ {\n\t\t\t\t\tg.SetValue(l.squares[r.min-i], BLANK)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"func inverseQuadraticInterpolation(iterator calcInverseIterator, fAx, fAy, fBx, fBy float64) float64 {\n\tfYEps := 1.0e-307\n\tfXEps := 2.22045e-016\n\tfPx, fPy, fQx, fQy, fRx, fRy := fAx, fAy, fBx, fBy, fAx, fAy\n\tfSx := 0.5 * (fAx + fBx)\n\tbHasToInterpolate := true\n\tnCount := 0\n\tfor nCount < 500 && math.Abs(fRy) > fYEps && (fBx-fAx) > math.Max(math.Abs(fAx), math.Abs(fBx))*fXEps {\n\t\tif bHasToInterpolate {\n\t\t\tif fPy != fQy && fQy != fRy && fRy != fPy {\n\t\t\t\tfSx = fPx*fRy*fQy/(fRy-fPy)/(fQy-fPy) + fRx*fQy*fPy/(fQy-fRy)/(fPy-fRy) +\n\t\t\t\t\tfQx*fPy*fRy/(fPy-fQy)/(fRy-fQy)\n\t\t\t\tbHasToInterpolate = (fAx < fSx) && (fSx < fBx)\n\t\t\t} else {\n\t\t\t\tbHasToInterpolate = false\n\t\t\t}\n\t\t}\n\t\tif !bHasToInterpolate {\n\t\t\tfSx = 0.5 * (fAx + fBx)\n\t\t\tfQx, fQy = fBx, fBy\n\t\t\tbHasToInterpolate = true\n\t\t}\n\t\tfPx, fQx, fRx, fPy, fQy = fQx, fRx, fSx, fQy, fRy\n\t\tfRy = iterator.callBack(fSx)\n\t\tif hasChangeOfSign(fAy, fRy) {\n\t\t\tfBx, fBy = fRx, fRy\n\t\t} else {\n\t\t\tfAx, fAy = fRx, fRy\n\t\t}\n\t\tbHasToInterpolate = bHasToInterpolate && (math.Abs(fRy)*2 <= math.Abs(fQy))\n\t\tnCount++\n\t}\n\treturn fRx\n}",
"func Solve(from, to, temp *Tower, n int) {\n\tif n < 1 {\n\t\treturn\n\t}\n\tif n == 1 {\n\t\tto.push(from.pop())\n\t\treturn\n\t}\n\tSolve(from, temp, to, n-1)\n\tSolve(from, to, temp, 1)\n\tSolve(temp, to, from, n-1)\n}",
"func simpsons_adaptive(start float64, end float64, steps int, f func(float64) float64) float64 {\n\t//\tepsilon := 1.0 / math.Pow(2, float64(steps))\n\tepsilon := 10e-8\n\tmid := (start + end) / 2\n\th := end - start\n\tf_start := f(start)\n\tf_end := f(end)\n\tf_mid := f(mid)\n\tS := (h / 6) * (f_start + 4*f_mid + f_end)\n\treturn simpsons_adaptive_helper(f, start, end, epsilon, S, f_start, f_mid, f_end, steps)\n}",
"func (o *Brent) Min(xa, xb float64) (xAtMin float64) {\n\n\t// check\n\tif xb < xa {\n\t\tchk.Panic(\"xa(%g) must be smaller than xb(%g)\", xa, xb)\n\t}\n\n\t// first step: always gold section\n\tv := xa + o.gsr*(xb-xa)\n\tfv := o.ffcn(v)\n\to.NumFeval = 1\n\to.NumJeval = 0\n\tx, w, fx, fw := v, v, fv, fv\n\n\t// solve\n\tvar rng float64 // range over which the minimum is seeked for\n\tvar midRng float64 // middle range\n\tvar tolAct float64 // actual tolerance\n\tvar newStep float64 // step at one iteration\n\tvar tmp float64 // temporary\n\tvar p, q, t, ft float64 // auxiliary\n\tfor o.NumIter = 0; o.NumIter < o.MaxIt; o.NumIter++ {\n\n\t\t// auxiliary variables\n\t\trng = xb - xa\n\t\tmidRng = (xa + xb) / 2.0\n\t\ttolAct = o.sqeps*math.Abs(x) + o.Tol/3.0\n\n\t\t// converged?\n\t\tif o.Verbose {\n\t\t\tio.Pf(\"%4d%23.15e%23.15e%23.15e\\n\", o.NumIter, x, fx, math.Abs(x-midRng)+rng/2.0)\n\t\t}\n\t\tif math.Abs(x-midRng)+rng/2.0 <= 2.0*tolAct {\n\t\t\treturn x\n\t\t}\n\n\t\t// Obtain the gold section step\n\t\ttmp = xa - x\n\t\tif x < midRng {\n\t\t\ttmp = xb - x\n\t\t}\n\t\tnewStep = o.gsr * tmp\n\n\t\t// decide if the interpolation can be tried\n\t\tif math.Abs(x-w) >= tolAct { // if x and w are distinct interpolation may be tried\n\n\t\t\tt = (x - w) * (fx - fv)\n\t\t\tq = (x - v) * (fx - fw)\n\t\t\tp = (x-v)*q - (x-w)*t\n\t\t\tq = 2.0 * (q - t)\n\n\t\t\tif q > 0.0 { // q was calculated with the op positive sign; make q positive and assign possible minus to p\n\t\t\t\tp = -p\n\t\t\t} else {\n\t\t\t\tq = -q\n\t\t\t}\n\n\t\t\t// x+p/q falls in [a,b] not too close to a and b, and isn't too large\n\t\t\tif math.Abs(p) < math.Abs(newStep*q) && p > q*(xa-x+2.0*tolAct) && p < q*(xb-x-2.0*tolAct) {\n\t\t\t\tnewStep = p / q // it is accepted\n\t\t\t\t// if p/q is too large then the gold section procedure can reduce [a,b] rng to more extent\n\t\t\t}\n\t\t}\n\n\t\t// adjust the step to be not less than tolerance\n\t\tif math.Abs(newStep) < tolAct {\n\t\t\tif newStep > 0.0 {\n\t\t\t\tnewStep = tolAct\n\t\t\t} else {\n\t\t\t\tnewStep = -tolAct\n\t\t\t}\n\t\t}\n\n\t\t// obtain the next approximation to min and reduce the enveloping rng\n\t\tt = x + newStep // tentative point for the min */\n\t\tft = o.ffcn(t)\n\t\to.NumFeval++\n\n\t\t// t is a better approximation\n\t\tif ft <= fx {\n\t\t\tif t < x { // reduce the range so that t would fall within it\n\t\t\t\txb = x\n\t\t\t} else {\n\t\t\t\txa = x\n\t\t\t}\n\t\t\t// assign the best approx to x\n\t\t\tv = w\n\t\t\tw = x\n\t\t\tx = t\n\t\t\tfv = fw\n\t\t\tfw = fx\n\t\t\tfx = ft\n\n\t\t\t// x remains the better approx\n\t\t} else {\n\t\t\tif t < x { // reduce the range enclosing x\n\t\t\t\txa = t\n\t\t\t} else {\n\t\t\t\txb = t\n\t\t\t}\n\t\t\tif ft <= fw || w == x {\n\t\t\t\tv = w\n\t\t\t\tw = t\n\t\t\t\tfv = fw\n\t\t\t\tfw = ft\n\t\t\t} else if ft <= fv || v == x || v == w {\n\t\t\t\tv = t\n\t\t\t\tfv = ft\n\t\t\t}\n\t\t}\n\t}\n\n\t// did not converge\n\tchk.Panic(\"fail to converge after %d iterations\", o.NumIter)\n\treturn\n}",
"func findDirections(x, y int, length *int, value int, directions []dirTable) int {\n num := 0\n numChecks := 0\n if value != wall || (getMaze(x, y) == path && setCell(x, y, check, noUpdate, *length, numChecks)) {\n minLength := [4]int {*length, *length, *length, *length}\n len := *length\n for {\n setInt(&dspLength, len)\n dirLength := [4]int {len, len, len, len}\n offset := rand.Intn(4)\n for i := 0; i < 4; i++ {\n dir := &stdDirection[(i + offset) % 4]\n num += look(dir.heading, x, y, dir.x, dir.y, num, value, directions, &dirLength[i] , &minLength[i], &numChecks)\n }\n if num > 0 || len < 0 {\n break\n }\n minLength := min( min(minLength[0], minLength[1]), min(minLength[2], minLength[3]) )\n if minLength <= 0 {\n minLength = 1\n }\n len -= minLength\n }\n if len == *length && len < getInt(&depth) {\n len++\n }\n *length = len\n if getMaze(x, y) == check {\n setMaze(x, y, path)\n }\n }\n if getInt(&maxChecks) < numChecks {\n setInt(&maxChecks , numChecks)\n }\n return (num);\n}",
"func solve2(input string) string {\n\tg := parseGrid(input)\n\t// let's \"set\" the sand entry so the bounds shift.\n\tseed := pos{x: 500, y: 0}\n\n\tg.Set(seed.x, seed.y, '+')\n\n\t// now we find the y bound and put a piece there to extend the \"in bounds\" grid to the floor.\n\t_, _, _, y := g.Bounds()\n\n\tfloor := y + 2\n\tg.Set(seed.x, floor, '=')\n\t// for x := seed.x - 100; x <= seed.x+100; x++ {\n\t// \tg.Set(x, floor, '=')\n\t// }\n\n\ti := 0\n\tfor {\n\t\t// if i%10 == 0 {\n\t\t// \tfmt.Println(\"Iteration:\", i, \"Floor level:\", floor)\n\t\t// \taoc.PrintByteGrid(g, nil)\n\t\t// }\n\t\t// we don't care about OOB, here.\n\t\tdropSand(g, pos{x: 500, y: 0}, floor)\n\t\ti++\n\t\tif b, _ := g.At(seed.x, seed.y); b == 'o' {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn fmt.Sprint(i)\n}",
"func SMS(DataA DiffData, LowerA, UpperA int, DataB DiffData, LowerB, UpperB int, DownVector []int, UpVector []int) SMSRD {\n\n\tMAX := DataA.Length + DataB.Length + 1\n\n\tDownK := LowerA - LowerB // the k-line to start the forward search\n\tUpK := UpperA - UpperB // the k-line to start the reverse search\n\n\tDelta := (UpperA - LowerA) - (UpperB - LowerB)\n\toddDelta := (Delta & 1) != 0\n\n\t// The vectors in the publication accepts negative indexes. the vectors implemented here are 0-based\n\t// and are access using a specific offset: UpOffset UpVector and DownOffset for DownVektor\n\tDownOffset := MAX - DownK\n\tUpOffset := MAX - UpK\n\n\tMaxD := ((UpperA - LowerA + UpperB - LowerB) / 2) + 1\n\n\t// Debug.Write(2, \"SMS\", String.Format(\"Search the box: A[{0}-{1}] to B[{2}-{3}]\", LowerA, UpperA, LowerB, UpperB))\n\n\t// init vectors\n\tDownVector[DownOffset+DownK+1] = LowerA\n\tUpVector[UpOffset+UpK-1] = UpperA\n\n\tfor D := 0; D <= MaxD; D++ {\n\n\t\t// Extend the forward path.\n\t\tfor k := DownK - D; k <= DownK+D; k += 2 {\n\t\t\t// Debug.Write(0, \"SMS\", \"extend forward path \" + k.ToString())\n\n\t\t\t// find the only or better starting point\n\t\t\tvar x, y int\n\t\t\tif k == DownK-D {\n\t\t\t\tx = DownVector[DownOffset+k+1] // down\n\t\t\t} else {\n\t\t\t\tx = DownVector[DownOffset+k-1] + 1 // a step to the right\n\t\t\t\tif (k < DownK+D) && (DownVector[DownOffset+k+1] >= x) {\n\t\t\t\t\tx = DownVector[DownOffset+k+1] // down\n\t\t\t\t}\n\t\t\t}\n\t\t\ty = x - k\n\n\t\t\t// find the end of the furthest reaching forward D-path in diagonal k.\n\t\t\tfor x < UpperA && (y < UpperB) && (DataA.data[x] == DataB.data[y]) {\n\t\t\t\tx++\n\t\t\t\ty++\n\t\t\t}\n\t\t\tDownVector[DownOffset+k] = x\n\n\t\t\t// overlap ?\n\t\t\tif oddDelta && (UpK-D < k) && (k < UpK+D) {\n\t\t\t\tif UpVector[UpOffset+k] <= DownVector[DownOffset+k] {\n\t\t\t\t\treturn SMSRD{\n\t\t\t\t\t\tx: DownVector[DownOffset+k],\n\t\t\t\t\t\ty: DownVector[DownOffset+k] - k,\n\t\t\t\t\t}\n\t\t\t\t} // if\n\t\t\t} // if\n\n\t\t} // for k\n\n\t\t// Extend the reverse path.\n\t\tfor k := UpK - D; k <= UpK+D; k += 2 {\n\t\t\t// Debug.Write(0, \"SMS\", \"extend reverse path \" + k.ToString())\n\n\t\t\t// find the only or better starting point\n\t\t\tvar x, y int\n\t\t\tif k == UpK+D {\n\t\t\t\tx = UpVector[UpOffset+k-1] // up\n\t\t\t} else {\n\t\t\t\tx = UpVector[UpOffset+k+1] - 1 // left\n\t\t\t\tif (k > UpK-D) && (UpVector[UpOffset+k-1] < x) {\n\t\t\t\t\tx = UpVector[UpOffset+k-1] // up\n\t\t\t\t}\n\t\t\t} // if\n\t\t\ty = x - k\n\n\t\t\tfor x > LowerA && (y > LowerB) && (DataA.data[x-1] == DataB.data[y-1]) {\n\t\t\t\tx--\n\t\t\t\ty-- // diagonal\n\t\t\t}\n\t\t\tUpVector[UpOffset+k] = x\n\n\t\t\t// overlap ?\n\t\t\tif !oddDelta && (DownK-D <= k) && (k <= DownK+D) {\n\t\t\t\tif UpVector[UpOffset+k] <= DownVector[DownOffset+k] {\n\t\t\t\t\t// ret.u = UpVector[UpOffset + k] // 2002.09.20: no need for 2 points\n\t\t\t\t\t// ret.v = UpVector[UpOffset + k] - k\n\t\t\t\t\treturn SMSRD{\n\t\t\t\t\t\tx: DownVector[DownOffset+k],\n\t\t\t\t\t\ty: DownVector[DownOffset+k] - k,\n\t\t\t\t\t}\n\t\t\t\t} // if\n\t\t\t} // if\n\n\t\t} // for k\n\n\t} // for D\n\n\tpanic(\"the algorithm should never come here.\")\n}",
"func (m *Map) Fit(p []coordinates.Point) coordinates.Vector {\n\tprediction := p[0].Origin\n\tbestFit := prediction\n\tbestScore := 0\n\tfor x := prediction.X - 10; x <= prediction.X+10; x++ {\n\t\tfor y := prediction.Y - 10; y <= prediction.Y+10; y++ {\n\t\t\tguess := coordinates.Vector{X: x, Y: y}\n\t\t\tscore := 0\n\t\t\tfor _, pp := range p {\n\t\t\t\tpp.Origin = guess\n\t\t\t\tv := pp.ToVector()\n\n\t\t\t\tif odds := m.grid.Get(v); odds != nil {\n\t\t\t\t\tif odds.Probability() > 0.99 {\n\t\t\t\t\t\tscore++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif score > bestScore {\n\t\t\t\tbestScore = score\n\t\t\t\tbestFit = guess\n\t\t\t}\n\t\t}\n\t}\n\treturn bestFit\n}",
"func Turn(start, dest, vel float64) float64 {\n\td := dest - start\n\tif math.Abs(d) < vel {\n\t\treturn dest\n\t}\n\n\tif d > 0 {\n\t\tif d > math.Pi {\n\t\t\tstart -= vel\n\t\t} else {\n\t\t\tstart += vel\n\t\t}\n\t} else {\n\t\tif d < -math.Pi {\n\t\t\tstart += vel\n\t\t} else {\n\t\t\tstart -= vel\n\t\t}\n\t}\n\n\treturn start\n}",
"func FindFittest(offs OffspringSlice) (int, *Offspring) {\n\tmaxFitnessFound := 0\n\tfittest := 0\n\tfor i, currOff := range offs {\n\t\tif currOff.Overman() {\n\t\t\treturn i, currOff\n\t\t}\n\n\t\tif currOff.Fitness > maxFitnessFound {\n\t\t\tmaxFitnessFound = currOff.Fitness\n\t\t\tfittest = i;\n\t\t}\n\t}\n\n\treturn fittest, offs[fittest];\n}",
"func performIteration(r *reactor, nStartNeutrons int, previousFissionLocations []FissionLocation) ([]Vector, float64) {\n\t//fmt.Println(previousFissionLocations)\n\tns := make([]Neutron, nStartNeutrons)\n\n\tindex := 0\n\tvar location Vector\n\tfor i := 0; i < len(previousFissionLocations); i++ {\n\t\tfor x := 0; x < previousFissionLocations[i].numberNeutronsProduced; x++ {\n\t\t\tlocation = previousFissionLocations[i].location\n\t\t\tns[index] = newNeutron(location, r)\n\t\t\tindex += 1\n\t\t}\n\t}\n\n\tvar numberNeutronsFree = 0\n\tvar fissionLocations []Vector\n\tvar numberNeutronsProduced float64 = 0\n\tfor {\n\t\tfor i := 0; i < len(ns); i++ {\n\t\t\tif ns[i].isFree {\n\t\t\t\tnumberNeutronsFree += 1\n\t\t\t\tns[i].move()\n\t\t\t\tif ns[i].medium == empty {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif ns[i].state == fissionU235 {\n\t\t\t\t\tnumberNeutronsProduced += 2.5 // TODO: Change when doing thermal (2.43) / fast (2.50)\n\t\t\t\t\tfissionLocations = append(fissionLocations, ns[i].positionVector) // TODO: Change when doing fast\n\t\t\t\t}\n\t\t\t\tif ns[i].state == fissionU238 {\n\t\t\t\t\tnumberNeutronsProduced += 2.46 // TODO: Change when doing thermal (0) / fast (2.46)\n\t\t\t\t\tfissionLocations = append(fissionLocations, ns[i].positionVector) // TODO: Change when doing thermal\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif numberNeutronsFree == 0 {\n\t\t\tbreak\n\t\t}\n\t\tnumberNeutronsFree = 0\n\t}\n\treturn fissionLocations, numberNeutronsProduced\n}",
"func (s *State) reaches(result map[*State]bool) {\n\tpush := func(l *list.List, s *State){\n\t\tl.PushBack(s);\n\t}\n\tpop := func(l *list.List) *State{\n\t\telement := l.Front()\n\t\tl.Remove(element)\n\t\treturn element.Value.(*State)\n\t}\n\n\tvisited := make(map[*State]bool)\n\tqueue := list.New()\n\t\n\tpush(queue, s)\n\tvisited[s] = true\n\tfor queue.Len() > 0 {\n\t\tstate := pop(queue)\n\t\tresult[state] = true\n\n\t\tfor nextState := range state.epsTransition {\n\t\t\tif !visited[nextState] {\n\t\t\t\tpush(queue, nextState)\n\t\t\t\tvisited[nextState] = true\n\t\t\t}\n\t\t}\n\t}\n}",
"func rising(arr []float64, len int) bool {\n\n\t// Add deffajult value as 3\n\tflag := false\n\tcurrVal := arr[0]\n\n\tfor _, val := range arr[1:] {\n\t\tlen--\n\t\tif len != 0 {\n\t\t\tif currVal > val {\n\t\t\t\tflag = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t\tbreak\n\t}\n\treturn flag\n\n}",
"func optiPenalty(pp *privPath, i, j int, opttolerance float64, convc []int, areac []float64) (res opti, err error) {\n\tm := len(pp.Curve.segm)\n\n\t// check convexity, corner-freeness, and maximum bend < 179 degrees\n\n\tif i == j { // sanity - a full loop can never be an opticurve\n\t\terr = fmt.Errorf(\"full loop can never be an opticurve\")\n\t\treturn\n\t}\n\n\tk := i\n\ti1 := mod(i+1, m)\n\tk1 := mod(k+1, m)\n\tconv := convc[k1]\n\tif conv == 0 {\n\t\terr = fmt.Errorf(\"conv is zero\")\n\t\treturn\n\t}\n\td := ddist(pp.Curve.segm[i].vertex, pp.Curve.segm[i1].vertex)\n\tfor k := k1; k != j; k = k1 {\n\t\tk1 = mod(k+1, m)\n\t\tk2 := mod(k+2, m)\n\t\tif convc[k1] != conv {\n\t\t\terr = fmt.Errorf(\"convc != conv\")\n\t\t\treturn\n\t\t}\n\t\tif int(signf(cprod(pp.Curve.segm[i].vertex, pp.Curve.segm[i1].vertex, pp.Curve.segm[k1].vertex, pp.Curve.segm[k2].vertex))) != conv {\n\t\t\terr = fmt.Errorf(\"sign 1\")\n\t\t\treturn\n\t\t}\n\t\tif iprod1(pp.Curve.segm[i].vertex, pp.Curve.segm[i1].vertex, pp.Curve.segm[k1].vertex, pp.Curve.segm[k2].vertex) < d*ddist(pp.Curve.segm[k1].vertex, pp.Curve.segm[k2].vertex)*cCOS179 {\n\t\t\terr = fmt.Errorf(\"iprod1\")\n\t\t\treturn\n\t\t}\n\t}\n\n\t// the curve we're working in:\n\tp0 := pp.Curve.segm[mod(i, m)].Pnt[2]\n\tp1 := pp.Curve.segm[mod(i+1, m)].vertex\n\tp2 := pp.Curve.segm[mod(j, m)].vertex\n\tp3 := pp.Curve.segm[mod(j, m)].Pnt[2]\n\n\t// determine its area\n\tarea := areac[j] - areac[i]\n\tarea -= dpara(pp.Curve.segm[0].vertex, pp.Curve.segm[i].Pnt[2], pp.Curve.segm[j].Pnt[2]) / 2\n\tif i >= j {\n\t\tarea += areac[m]\n\t}\n\n\t// \t find intersection o of p0p1 and p2p3. Let t,s such that o =\n\t// \t interval(t,p0,p1) = interval(s,p3,p2). Let A be the area of the\n\t// \t triangle (p0,o,p3).\n\n\tA1 := dpara(p0, p1, p2)\n\tA2 := dpara(p0, p1, p3)\n\tA3 := dpara(p0, p2, p3)\n\t// A4 = dpara(p1, p2, p3)\n\tA4 := A1 + A3 - A2\n\n\tif A2 == A1 { // this should never happen\n\t\terr = fmt.Errorf(\"A2 vs A1\")\n\t\treturn\n\t}\n\n\tt := A3 / (A3 - A4)\n\ts := A2 / (A2 - A1)\n\tA := A2 * t / 2.0\n\n\tif A == 0.0 { // this should never happen\n\t\terr = fmt.Errorf(\"A == 0\")\n\t\treturn\n\t}\n\n\tR := area / A // relative area\n\talpha := 2 - math.Sqrt(4-R/0.3) // overall alpha for p0-o-p3 curve\n\n\tres.c[0] = interval(t*alpha, p0, p1)\n\tres.c[1] = interval(s*alpha, p3, p2)\n\tres.alpha = alpha\n\tres.t = t\n\tres.s = s\n\n\tp1 = res.c[0]\n\tp2 = res.c[1] // the proposed curve is now (p0,p1,p2,p3)\n\n\tres.pen = 0\n\n\t// calculate penalty\n\t// check tangency with edges\n\tfor k = mod(i+1, m); k != j; k = k1 {\n\t\tk1 = mod(k+1, m)\n\t\tt = tangent(p0, p1, p2, p3, pp.Curve.segm[k].vertex, pp.Curve.segm[k1].vertex)\n\t\tif t < -0.5 {\n\t\t\terr = fmt.Errorf(\"t < -0.5\")\n\t\t\treturn\n\t\t}\n\t\tpt := bezier(t, p0, p1, p2, p3)\n\t\td = ddist(pp.Curve.segm[k].vertex, pp.Curve.segm[k1].vertex)\n\t\tif d == 0.0 { // this should never happen\n\t\t\terr = fmt.Errorf(\"d == 0\")\n\t\t\treturn\n\t\t}\n\t\td1 := dpara(pp.Curve.segm[k].vertex, pp.Curve.segm[k1].vertex, pt) / d\n\t\tif fabs(d1) > opttolerance {\n\t\t\terr = fmt.Errorf(\"tollerance\")\n\t\t\treturn\n\t\t}\n\t\tif iprod(pp.Curve.segm[k].vertex, pp.Curve.segm[k1].vertex, pt) < 0 || iprod(pp.Curve.segm[k1].vertex, pp.Curve.segm[k].vertex, pt) < 0 {\n\t\t\terr = fmt.Errorf(\"prods\")\n\t\t\treturn\n\t\t}\n\t\tres.pen += d1 * d1\n\t}\n\n\t// check corners\n\tfor k = i; k != j; k = k1 {\n\t\tk1 = mod(k+1, m)\n\t\tt = tangent(p0, p1, p2, p3, pp.Curve.segm[k].Pnt[2], pp.Curve.segm[k1].Pnt[2])\n\t\tif t < -0.5 {\n\t\t\terr = fmt.Errorf(\"t < -0.5 s\")\n\t\t\treturn\n\t\t}\n\t\tpt := bezier(t, p0, p1, p2, p3)\n\t\td = ddist(pp.Curve.segm[k].Pnt[2], pp.Curve.segm[k1].Pnt[2])\n\t\tif d == 0.0 { // this should never happen\n\t\t\terr = fmt.Errorf(\"d == 0 s\")\n\t\t\treturn\n\t\t}\n\t\td1 := dpara(pp.Curve.segm[k].Pnt[2], pp.Curve.segm[k1].Pnt[2], pt) / d\n\t\td2 := dpara(pp.Curve.segm[k].Pnt[2], pp.Curve.segm[k1].Pnt[2], pp.Curve.segm[k1].vertex) / d\n\t\td2 *= 0.75 * pp.Curve.segm[k1].alpha\n\t\tif d2 < 0 {\n\t\t\td1 = -d1\n\t\t\td2 = -d2\n\t\t}\n\t\tif d1 < d2-opttolerance {\n\t\t\terr = fmt.Errorf(\"tolerance 2\")\n\t\t\treturn\n\t\t}\n\t\tif d1 < d2 {\n\t\t\tres.pen += (d1 - d2) * (d1 - d2)\n\t\t}\n\t}\n\n\treturn\n}",
"func (self *BRA) buildSolution (path []*Node, dists [][]int, value int, cnode *Node) (Solution, int, int){\n\n\t// Init the part of the solution that remains the same\n\tindex := int((1 - self.beta) * float64(len(path)))\n\tsol := path[:index]\n\tval, del := evaluate(sol, dists, value, cnode)\n\n\t// Init options and current node\n\tvar currentNode Node = *cnode\n\tvar newNode Node\n\toptions := path[index:]\n\n\t// Execute a greedy construction of the new solution\n\tfor len(options) > 0 {\n\t\t// Sort options for increasing cost (i.e., arrival + delay)\n\t\tsort.Slice(options, func (i int, j int) bool {\n\t\t\treturn options[i].Cost(currentNode, dists, val) < options[j].Cost(currentNode, dists, val)\n\t\t})\n\n\t\t// Pick a new node using a quasi-geometric\n\t\tpos := self.biased_random_selection(len(options))\n\t\tnewNode = *options[pos]\n\n\t\t// Pick the best and make it current node\n\t\tval = int(math.Max(float64(val + dists[currentNode.id][newNode.id]), float64(newNode.open)))\n\t\tdel += int(math.Max(0, float64(val - newNode.close)))\n\t\tsol = append(sol, options[pos])\n\t\tcurrentNode = newNode\n\t\toptions = append(options[:pos], options[pos + 1:]...)\n\t}\n\t// Return the new solution\n\treturn sol, val, del\n}",
"func createCandidates(series []float64, candidates []ChangePoint, index int) []ChangePoint {\n\tif len(candidates) == 0 {\n\t\twinQs, _ := QHat(series)\n\t\twinIndexMax, winMaxQs := ExtractQ(winQs)\n\n\t\tcandidate := ChangePoint{\n\t\t\tIndex: winIndexMax,\n\t\t\tQ: winMaxQs,\n\t\t\tOrder: 0,\n\t\t\tWindow: Window{Start: 0, End: len(series)},\n\t\t}\n\t\tcandidates = append(candidates, candidate)\n\t} else {\n\t\tfound := 0\n\t\tfor i, current := range candidates {\n\t\t\tif current.Index == index {\n\t\t\t\tfound = i\n\t\t\t}\n\t\t}\n\n\t\tstart := candidates[found].Start\n\t\tend := candidates[found].End\n\n\t\tbuffer := series[start:index]\n\n\t\twinQs, _ := QHat(buffer)\n\t\twinIndexMax, winMaxQs := ExtractQ(winQs)\n\t\tcandidates[found].Index = winIndexMax + start\n\t\tcandidates[found].Q = winMaxQs\n\t\tcandidates[found].Start = start\n\t\tcandidates[found].End = index\n\n\t\tbuffer = series[index:end]\n\t\twinQs, _ = QHat(buffer)\n\t\twinIndexMax, winMaxQs = ExtractQ(winQs)\n\t\tcandidate := ChangePoint{\n\t\t\tIndex: winIndexMax + index,\n\t\t\tQ: winMaxQs,\n\t\t\tWindow: Window{Start: index, End: end},\n\t\t}\n\t\tcandidates = append(candidates, candidate)\n\n\t\tsort.Slice(candidates[:], func(i, j int) bool {\n\t\t\treturn candidates[i].Q < candidates[j].Q\n\t\t})\n\t}\n\treturn candidates\n}",
"func wBfs(startNode *node) *node {\n\tvar bfsQueue []*node\n\tbfsQueue = append(bfsQueue, startNode)\n\tcurrNode := startNode\n\tvar endNode *node\n\tfor currNode.nodeType != \"end\" {\n\t\tcurrNode.visited = true\n\t\t//Sorting the weight array of the current node se the cheapest nodes are scanned first\n\t\tstart := 0\n\t\tfor i := 0; i < len(currNode.weights); i++ {\n\t\t\tmin := currNode.weights[start]\n\t\t\tminPos := start\n\t\t\tfor i := start; i < len(currNode.weights); i++ {\n\t\t\t\tnewMin := currNode.weights[i]\n\t\t\t\tif newMin < min {\n\t\t\t\t\tmin = newMin\n\t\t\t\t\tminPos = i\n\t\t\t\t}\n\t\t\t}\n\t\t\t//Swap the min and start in weight and adjacentNodes arrays\n\t\t\tcurrNode.weights[minPos] = currNode.weights[start]\n\t\t\tcurrNode.weights[start] = min\n\n\t\t\thelper := currNode.adjacentNodes[minPos]\n\t\t\tcurrNode.adjacentNodes[minPos] = currNode.adjacentNodes[start]\n\t\t\tcurrNode.adjacentNodes[start] = helper\n\n\t\t\tstart++\n\t\t}\n\t\tfor i := 0; i < len(currNode.adjacentNodes); i++ {\n\t\t\tif !currNode.adjacentNodes[i].visited {\n\t\t\t\tbfsQueue = append(bfsQueue, currNode.adjacentNodes[i])\n\t\t\t\tcurrNode.adjacentNodes[i].parrent = currNode\n\t\t\t}\n\t\t}\n\t\tcurrNode = bfsQueue[1]\n\t\tbfsQueue = bfsQueue[1:]\n\n\t\tif currNode.nodeType == \"end\" {\n\t\t\tendNode = currNode\n\t\t\tbreak\n\t\t}\n\t}\n\treturn endNode\n}",
"func followPath(x, y *int) bool {\n directions := make([]dirTable, 4, 4)\n lastDir := 0\n length := -1\n setCell(*x, *y, solved, noUpdate, 0, 0)\n for getInt(&begX) <= *x && *x <= getInt(&endX) {\n num := findDirections(*x, *y, &length, path, directions)\n if num == 0 {\n break\n }\n followDir(x, y, directions[0], lastDir)\n if threads > 1 && num > 1 && getBool(&solvedFlag) == false {\n for i := 1; i < num; i++ {\n incInt(&numThreads)\n followDir(x, y, directions[i], lastDir)\n go solve(*x + directions[i].x, *y + directions[i].y)\n }\n }\n *x += directions[0].x\n *y += directions[0].y\n }\n if *x > getInt(&endX) {\n setBool(&solvedFlag, true)\n return true\n } else {\n return false\n }\n}",
"func GAsFitnessMessure(g *GAs) {\n\tfor i := 0; i < g.Option.PopSize; i++ {\n\t\tf := g.Option.Fitness(&g.Population[i])\n\t\tg.Fitness[i] = f\n\t}\n\ti := FindArgMax(g.Fitness)\n\tif g.Generation == 0 || g.Fitness[i] > g.BestIndividualFieness {\n\t\tg.BestIndividual = g.Population[i].Copy()\n\t\tg.BestIndividualFieness = g.Fitness[i]\n\t}\n\tif g.Option.MaintainTheBestIndividual {\n\t\ti := FindArgMin(g.Fitness)\n\t\tg.Population[i] = g.BestIndividual.Copy()\n\t\tg.Fitness[i] = g.BestIndividualFieness\n\t}\n}",
"func (i *BaseInhabitant) NextStep(relWatcher cr.RelativeWatcher) (int, int) {\n\ti.days++\n\t// iterate over fields to find enemy\n\tfor rH := 2; rH >= -2; rH-- {\n\t\tfor rW := 2; rW >= -2; rW-- {\n\t\t\tif rH == 0 && rW == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif i.IsEnemy(relWatcher(rH, rW)) {\n\t\t\t\t// found enemy, trying to find safe field\n\t\t\t\tisHPositive := rH >= 0\n\t\t\t\tisWPositive := rW >= 0\n\t\t\t\tvar nextH, nextW int\n\n\t\t\t\tif isHPositive && rH != 0 {\n\t\t\t\t\tnextH = -1\n\t\t\t\t} else if !isHPositive && rH != 0 {\n\t\t\t\t\tnextH = 1\n\t\t\t\t}\n\n\t\t\t\tif isWPositive && rW != 0 {\n\t\t\t\t\tnextW = -1\n\t\t\t\t} else if !isWPositive && rW != 0 {\n\t\t\t\t\tnextW = 1\n\t\t\t\t}\n\n\t\t\t\tif i.IsSafeField(relWatcher, nextH, nextW) {\n\t\t\t\t\treturn nextH, nextW\n\t\t\t\t}\n\t\t\t\t// try find safe place\n\n\t\t\t\tif rH == 0 && i.IsSafeField(relWatcher, -1, nextW) {\n\t\t\t\t\treturn -1, nextW\n\t\t\t\t}\n\n\t\t\t\tif rH == 0 && i.IsSafeField(relWatcher, 1, nextW) {\n\t\t\t\t\treturn 1, nextW\n\t\t\t\t}\n\n\t\t\t\tif rW == 0 && i.IsSafeField(relWatcher, nextH, -1) {\n\t\t\t\t\treturn nextH, -1\n\t\t\t\t}\n\n\t\t\t\tif rW == 0 && i.IsSafeField(relWatcher, nextH, 1) {\n\t\t\t\t\treturn nextH, 1\n\t\t\t\t}\n\n\t\t\t\tif isHPositive && i.IsSafeField(relWatcher, nextH, nextW-1) {\n\t\t\t\t\treturn nextH, nextW - 1\n\t\t\t\t}\n\n\t\t\t\tif isHPositive && i.IsSafeField(relWatcher, nextH, nextW+1) {\n\t\t\t\t\treturn nextH, nextW + 1\n\t\t\t\t}\n\n\t\t\t\tif isWPositive && i.IsSafeField(relWatcher, nextH-1, nextW) {\n\t\t\t\t\treturn nextH - 1, nextW\n\t\t\t\t}\n\n\t\t\t\tif isHPositive && i.IsSafeField(relWatcher, nextH+1, nextW) {\n\t\t\t\t\treturn nextH + 1, nextW\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn rand.Intn(i.maxMove+i.maxMove+1) - i.maxMove, rand.Intn(i.maxMove+i.maxMove+1) - i.maxMove\n}",
"func randomWalker(client protobuf.SGMSServiceClient, entityId string, startLocation, stdDeltas, max protobuf.Location) {\n\n\tr := rand.New(rand.NewSource(time.Now().UTC().UnixNano()))\n\n\tvar courseDelta float64\n\tcourseDelta = r.NormFloat64()*0.05 + 0.1\n\tif r.NormFloat64() > 0.0 {\n\t\tcourseDelta *= -1.0\n\t}\n\n\tlocation := startLocation\n\n\tfor {\n\t\t// calculate new location based on last location plus some bias based on the initial velocity and direction\n\n\t\tlocation.Course = float64(math.Mod(float64(location.Course)+(r.NormFloat64()*float64(stdDeltas.Course))+courseDelta, 360.))\n\t\tif math.Abs(float64(location.Velocity)) > float64(max.Velocity) {\n\t\t\tlocation.Velocity += float64(math.Abs(r.NormFloat64()*float64(stdDeltas.Velocity)) * -1.)\n\t\t} else {\n\t\t\tlocation.Velocity += float64(r.NormFloat64()) * stdDeltas.Velocity\n\n\t\t}\n\t\tlocation.Latitude += math.Sin(float64(location.Course)) * float64(location.Velocity)\n\t\tlocation.Longitude += math.Cos(float64(location.Course)) * float64(location.Velocity)\n\t\tlocation.Accuracy = 10.0\n\n\t\tcommon.SendLocation(client, entityId, time.Now().UTC(), location)\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}",
"func ConcurrentSearch(root *Node, policies []GamePolicy, duration time.Duration) Decision {\n\tif root == nil {\n\t\t// TODO: error handling\n\t\tpanic(\"no root\")\n\t}\n\n\t// All possible first moves are expanded.\n\ttree := GrowTree(root)\n\n\tdone := make(chan struct{})\n\ttimeout := make(chan bool)\n\n\t// Start the countdown asap: the search must return a decision\n\t// in the given time frame. A late decision is as bad as an\n\t// illegal move, it's disqualifying.\n\tgo func() {\n\t\ttime.Sleep(duration)\n\t\tclose(timeout)\n\t}()\n\n\t// Prepare pipelines (channels and goroutines launchers).\n\tpositions := make(chan job, samplers)\n\twalk := func(count int) {\n\t\tvar wg sync.WaitGroup\n\n\t\twg.Add(count)\n\t\tfor i := 0; i < count; i++ {\n\t\t\tgo func() {\n\t\t\t\twalker(done, tree, positions)\n\t\t\t\twg.Done()\n\t\t\t}()\n\t\t}\n\n\t\tgo func() {\n\t\t\twg.Wait()\n\t\t\tclose(positions)\n\t\t}()\n\t}\n\n\toutcomes := make(chan job, samplers)\n\tsample := func(count int) {\n\t\tvar wg sync.WaitGroup\n\n\t\twg.Add(count)\n\t\tfor i := 0; i < count; i++ {\n\t\t\tgo func() {\n\t\t\t\tsampler(done, policies, positions, outcomes)\n\t\t\t\twg.Done()\n\t\t\t}()\n\t\t}\n\n\t\tgo func() {\n\t\t\twg.Wait()\n\t\t\tclose(outcomes)\n\t\t}()\n\t}\n\n\tupdate := func(count int) {\n\t\tfor i := 0; i < count; i++ {\n\t\t\tgo func() {\n\t\t\t\tupdater(done, outcomes)\n\t\t\t}()\n\t\t}\n\t}\n\n\t// Launch!\n\tgo update(updaters)\n\tgo sample(samplers)\n\tgo walk(walkers)\n\n\t// Wait for either timeout or solution\n\tfor {\n\t\tselect {\n\t\tcase <-timeout:\n\t\t\tgoto conclusion\n\t\tdefault:\n\t\t\tif root.IsSolved() {\n\t\t\t\tgoto conclusion\n\t\t\t}\n\t\t\truntime.Gosched()\n\t\t}\n\t}\n\n\t// Broadcast termination message (done) to all goroutines\n\t// and return the best sequence found so far.\nconclusion:\n\tclose(done)\n\treturn tree.Best()\n}",
"func (d *DStarLite) Step() bool {\n\t/*\n\t procedure Main()\n\t {32”} while (s_start != s_goal)\n\t {33”} // if (rhs(s_start) = ∞) then there is no known path\n\t {34”} s_start = argmin s'∈Succ(s_start)(c(s_start, s') + g(s'));\n\t*/\n\tif d.s.ID() == d.t.ID() {\n\t\treturn false\n\t}\n\tif math.IsInf(d.s.rhs, 1) {\n\t\treturn false\n\t}\n\n\t// We use rhs comparison to break ties\n\t// between coequally weighted nodes.\n\trhs := math.Inf(1)\n\tmin := math.Inf(1)\n\n\tvar next *dStarLiteNode\n\tdsid := d.s.ID()\n\tto := d.model.From(dsid)\n\tfor to.Next() {\n\t\ts := to.Node().(*dStarLiteNode)\n\t\tw := edgeWeight(d.model.Weight, dsid, s.ID()) + s.g\n\t\tif w < min || (w == min && s.rhs < rhs) {\n\t\t\tnext = s\n\t\t\tmin = w\n\t\t\trhs = s.rhs\n\t\t}\n\t}\n\td.s = next\n\n\t/*\n\t procedure Main()\n\t {35”} Move to s_start;\n\t*/\n\treturn true\n}",
"func (g *Graph) FindPath(startPoint, endPoint, currentStop int) {\n\tif g.Stack.Len() > 4 {\n\t\treturn\n\t}\n\tif n := g.Stack.Front(); n != nil {\n\t\tif currentStop == endPoint && g.Stack.Len() == 4 {\n\t\t\tg.Q7++\n\n\t\t}\n\t}\n\tfor i := 0; i < matrix_size; i++ {\n\t\tif g.Matrix[currentStop][i] != 0 {\n\t\t\tg.Stack.PushFront(i)\n\t\t\tg.FindPath(startPoint, endPoint, i)\n\t\t}\n\t}\n}",
"func PeakDetect(vals []float64, delta float64) ([]int, []float64, []int, []float64) {\n\tminx := make([]int, 0, 0)\n\tmaxx := make([]int, 0, 0)\n\tminvals := make([]float64, 0, 0)\n\tmaxvals := make([]float64, 0, 0)\n\n\txvals := make([]int, len(vals), len(vals))\n\tfor i := 0; i < len(vals); i++ {\n\t\txvals[i] = i\n\t}\n\n\tif delta < 0 {\n\t\treturn minx, minvals, maxx, maxvals\n\t}\n\n\tmn := math.Inf(1)\n\tmx := math.Inf(-1)\n\tmnpos := int(math.NaN())\n\tmxpos := int(math.NaN())\n\n\tlookForMax := true\n\n\tfor i, val := range vals {\n\t\tif val > mx {\n\t\t\tmx = val\n\t\t\tmxpos = i\n\t\t}\n\t\tif val < mn {\n\t\t\tmn = val\n\t\t\tmnpos = i\n\t\t}\n\n\t\tif lookForMax {\n\t\t\tif val < mx-delta {\n\t\t\t\tmaxx = append(maxx, mxpos)\n\t\t\t\tmaxvals = append(maxvals, mx)\n\n\t\t\t\tmn = val\n\t\t\t\tmnpos = i\n\t\t\t\tlookForMax = false\n\t\t\t}\n\t\t} else {\n\t\t\tif val > mn+delta {\n\t\t\t\tminx = append(minx, mnpos)\n\t\t\t\tminvals = append(minvals, mn)\n\n\t\t\t\tmx = val\n\t\t\t\tmxpos = i\n\t\t\t\tlookForMax = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn minx, minvals, maxx, maxvals\n}",
"func Solve(sizeBucketOne,\n\tsizeBucketTwo,\n\tgoalAmount int,\n\tstartBucket string) (goalBucket string,\n\tnumSteps,\n\totherBucketLevel int,\n\te error) {\n\n\tif sizeBucketOne == 0 || sizeBucketTwo == 0 {\n\t\treturn \"\", 0, 0, errors.New(\"invalid bucket size\")\n\t}\n\n\tif goalAmount == 0 {\n\t\treturn \"\", 0, 0, errors.New(\"invalid goal amount\")\n\t}\n\n\tif startBucket != \"one\" && startBucket != \"two\" {\n\t\treturn \"\", 0, 0, errors.New(\"invalid start bucket name\")\n\t}\n\n\tvar moves int\n\tvar lastPoured bool\n\n\tbucketOne := bucket{\n\t\tname: \"one\",\n\t\tsize: sizeBucketOne,\n\t}\n\n\tbucketTwo := bucket{\n\t\tname: \"two\",\n\t\tsize: sizeBucketTwo,\n\t}\n\n\tif startBucket == \"one\" {\n\t\tfillBucket(&bucketOne, &moves, &lastPoured)\n\t\tif goalAmount == bucketTwo.size {\n\t\t\tfillBucket(&bucketTwo, &moves, &lastPoured)\n\t\t\treturn bucketTwo.name, moves, bucketOne.current, nil\n\t\t}\n\t}\n\n\tif startBucket == \"two\" {\n\t\tfillBucket(&bucketTwo, &moves, &lastPoured)\n\t\tif goalAmount == bucketOne.size {\n\t\t\tfillBucket(&bucketOne, &moves, &lastPoured)\n\t\t\treturn bucketOne.name, moves, bucketTwo.current, nil\n\t\t}\n\t}\n\n\tfor goalAmount != bucketOne.current && goalAmount != bucketTwo.current {\n\t\tif bucketOne.current != 0 && bucketTwo.current != bucketTwo.size && !lastPoured {\n\t\t\tpourBucket(&bucketOne, &bucketTwo, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\t\tif bucketTwo.current != 0 && bucketOne.current != bucketOne.size && !lastPoured {\n\t\t\tpourBucket(&bucketTwo, &bucketOne, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\n\t\tif bucketOne.current == bucketOne.size && bucketTwo.current != 0 {\n\t\t\temptyBucket(&bucketOne, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\n\t\tif bucketTwo.current == bucketTwo.size && bucketOne.current != 0 {\n\t\t\temptyBucket(&bucketTwo, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\n\t\tif bucketOne.current == 0 && bucketTwo.size-bucketTwo.current != 0 {\n\t\t\tfillBucket(&bucketOne, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\n\t\tif bucketTwo.current == 0 && bucketOne.size-bucketOne.current != 0 {\n\t\t\tfillBucket(&bucketTwo, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\n\t\treturn \"\", 0, 0, errors.New(\"no solution\")\n\n\t}\n\n\tif goalAmount == bucketOne.current {\n\t\treturn bucketOne.name, moves, bucketTwo.current, nil\n\t}\n\n\tif goalAmount == bucketTwo.current {\n\t\treturn bucketTwo.name, moves, bucketOne.current, nil\n\t}\n\n\treturn \"\", 0, 0, errors.New(\"no solution\")\n\n}",
"func findRescuePathLength(caveDepth, targetX, targetY int, cavePlan cavePlanType) (int, cavePlanType) {\n\tgraphMap := make(graphMapType)\n\tstartTorchKey := graphItemKeyType{0, 0, TORCH}\n\tstartTorch := graphItemType{&startTorchKey, 0, -1, nil, false}\n\tpq := make(priorityQueue, 1)\n\tpq[0] = &startTorch\n\tgraphMap[startTorchKey] = &startTorch\n\theap.Init(&pq)\n\n\tfor len(pq) > 0 {\n\t\thead := heap.Pop(&pq).(*graphItemType)\n\t\thead.processed = true\n\t\t// If target reached return distance\n\t\tif head.x == targetX && head.y == targetY && head.tool == TORCH {\n\t\t\treturn head.dist, cavePlan\n\t\t}\n\t\t// Left\n\t\tif head.x > 0 && cavePlan[head.y][head.x-1].erosion != head.tool {\n\t\t\tcreateGraphItem(head.x-1, head.y, head.tool, head.dist+1, &pq, &graphMap, head)\n\t\t}\n\t\t// Up\n\t\tif head.y > 0 && cavePlan[head.y-1][head.x].erosion != head.tool {\n\t\t\tcreateGraphItem(head.x, head.y-1, head.tool, head.dist+1, &pq, &graphMap, head)\n\t\t}\n\t\t// Generate additional cave plan if required\n\t\tif head.x == len(cavePlan[head.y])-1 {\n\t\t\tcavePlan = addColumn(caveDepth, targetX, targetY, cavePlan)\n\t\t}\n\t\tif head.y == len(cavePlan)-1 {\n\t\t\tcavePlan = addRow(caveDepth, targetX, targetY, cavePlan)\n\t\t}\n\t\t// Right\n\t\tif cavePlan[head.y][head.x+1].erosion != head.tool {\n\t\t\tcreateGraphItem(head.x+1, head.y, head.tool, head.dist+1, &pq, &graphMap, head)\n\t\t}\n\t\t// Down\n\t\tif cavePlan[head.y+1][head.x].erosion != head.tool {\n\t\t\tcreateGraphItem(head.x, head.y+1, head.tool, head.dist+1, &pq, &graphMap, head)\n\t\t}\n\t\t// Change the tool operation is also one of options\n\t\tnewTool := (head.tool + 1) % 3\n\t\tif newTool == cavePlan[head.y][head.x].erosion {\n\t\t\tnewTool = (newTool + 1) % 3\n\t\t}\n\t\tcreateGraphItem(head.x, head.y, newTool, head.dist+7, &pq, &graphMap, head)\n\t}\n\treturn -1, cavePlan\n}",
"func createNearestNeighborTour(cities []City) Tour {\n cityMap := make(map[uint64]City)\n for _, city := range cities[1:] {\n cityMap[city.Id] = city\n }\n\n var t Tour\n firstCity := cities[0]\n curCity := firstCity\n t.Cities = append(t.Cities, curCity)\n nearestNeighbor := cities[1]\n minDistance := curCity.Distance(nearestNeighbor)\n for len(cityMap) > 0 {\n for _, city := range cityMap {\n curDistance := curCity.Distance(city)\n if curDistance == minDistance {\n /*\n * use city with highest id as next city, else this function\n * behaves differently on every call, because range on a\n * map iterates differently\n */\n if city.Id > nearestNeighbor.Id {\n nearestNeighbor = city\n }\n } else if curDistance < minDistance {\n nearestNeighbor = city\n minDistance = curDistance\n }\n }\n curCity = nearestNeighbor\n delete(cityMap, curCity.Id)\n t.Cities = append(t.Cities, curCity)\n t.Length += minDistance\n minDistance = math.MaxUint64\n }\n t.Cities = append(t.Cities, firstCity)\n t.Length += nearestNeighbor.Distance(firstCity)\n\n return t\n}",
"func filterPoints(start, end *node) *node {\n\tif start == nil {\n\t\treturn start\n\t}\n\tif end == nil {\n\t\tend = start\n\t}\n\tp := start\n\tagain := false\n\tfor {\n\t\tagain = false\n\t\tif !p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) == 0.0) {\n\t\t\tremoveNode(p)\n\t\t\tend = p.prev\n\t\t\tp = p.prev\n\t\t\tif p == p.next {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tagain = true\n\t\t} else {\n\t\t\tp = p.next\n\t\t}\n\t\tif !again && p == end {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn end\n}",
"func search(nums []int, target int) int {\n\tif len(nums) == 0 {\n\t\treturn -1\n\t}\n\tfmt.Println(nums)\n\n\tlow := 0\n\thigh := len(nums) - 1\n\n\tfor low < high {\n\t\tmid := (low + high) / 2\n\t\t//case 1 mid == target\n\t\tif nums[mid] == target {\n\t\t\treturn mid\n\t\t}\n\n\t\tfmt.Println(\"low: \", low, \"hi\", high, \"nums[mid]: \", nums[mid], \"mid: \", mid, \"a[low]\", nums[low])\n\n\t\t// target < a[mid], which can be on either side.\n\t\t// so how to decide which side to go???\n\t\t//case 2, if a[mid] < a[high], then we know a[mid....high]\n\t\t// is sorted. so, just call BS on a\n\t\tif nums[mid] < nums[high] {\n\t\t\t// target in a[mid...high]\n\t\t\tif target >= nums[mid] && target <= nums[high] {\n\t\t\t\tlow = mid\n\t\t\t} else if target >= nums[low] {\n\t\t\t\t//target in a[low...mid-1]\n\t\t\t\thigh = mid - 1\n\t\t\t}\n\t\t\t//\tcontinue\n\t\t}\n\t\t//case 3, if a[mid] > a[low], then we know the a[low....mid] is sorted\n\t\tif nums[mid] > nums[low] {\n\t\t\tif target <= nums[mid] && target >= nums[low] {\n\t\t\t\thigh = mid - 1\n\t\t\t} else if target <= nums[high] {\n\t\t\t\tlow = mid + 1\n\t\t\t} else {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t}\n\t\tif high == low && nums[high] == target {\n\t\t\treturn high\n\t\t}\n\t}\n\treturn -1\n}",
"func solution(knows func(a int, b int) bool) func(n int) int {\n\treturn func(n int) int {\n\t\ts := &stack{}\n\t\tfor i := 0; i< n; i++ {\n\t\t\ts.push(i)\n\t\t}\n\n\t\t//push them all on stack.\n\t\t//Selectively knock off one by one using one comparision.\n\t\t//if a knows b -> a cant be celebrity but b potentially is.\n\t\t//push b or a accordingly.\n\n\t\t//At the end - have on element left over due eleminations, this may\n\t\t//maynot be the celeb. Do one round of validation before declaring.\n\t\tfor len(*s) > 1 {\n\t\t\ta := s.pop()\n\t\t\tb := s.pop()\n\n\t\t\tif knows(a, b) {\n\t\t\t\ts.push(b)\n\t\t\t} else {\n\t\t\t\ts.push(a)\n\t\t\t}\n\t\t}\n\n\t\tfmt.Printf(\"length: %v\\n\", len(*s))\n\t\t//at this point we expect only one element in stack.\n\t\tc := s.pop()\n\n\n\n\t\t//double check if c is the celebrity.\n\t\tfor i:=0; i< n;i++ {\n\t\t\tif i != c && (knows(c, i) || !knows(i, c)) {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t}\n\t\treturn c\n\t}\n}",
"func findGiverReceiver(p []int) ([]int, bool) {\n\t// start from back and look for intersection\n\ts := p[len(p)-1] // smallest\n\tsi := len(p) - 1 // smallest index\n\n\tfor i := len(p) - 2; i >= 1; i-- {\n\t\tif p[i] != s {\n\t\t\tsi = i + 1\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor i := (si - 1); i >= 1; i-- {\n\t\tif (p[i] - p[si]) >= 2 {\n\t\t\treturn []int{i, si}, true\n\t\t}\n\t}\n\n\treturn []int{}, false\n}",
"func computeMove(move []float64, minIdx int, A mat.Matrix, ab *mat.Dense, xb []float64, nonBasicIdx []int) error {\n\t// Find ae.\n\tcol := mat.Col(nil, nonBasicIdx[minIdx], A)\n\taCol := mat.NewVecDense(len(col), col)\n\n\t// d = - Ab^-1 Ae\n\tnb, _ := ab.Dims()\n\td := make([]float64, nb)\n\tdVec := mat.NewVecDense(nb, d)\n\terr := dVec.SolveVec(ab, aCol)\n\tif err != nil {\n\t\treturn ErrLinSolve\n\t}\n\tfloats.Scale(-1, d)\n\n\tfor i, v := range d {\n\t\tif math.Abs(v) < dRoundTol {\n\t\t\td[i] = 0\n\t\t}\n\t}\n\n\t// If no di < 0, then problem is unbounded.\n\tif floats.Min(d) >= 0 {\n\t\treturn ErrUnbounded\n\t}\n\n\t// move = bhat_i / - d_i, assuming d is negative.\n\tbHat := xb // ab^-1 b\n\tfor i, v := range d {\n\t\tif v >= 0 {\n\t\t\tmove[i] = math.Inf(1)\n\t\t} else {\n\t\t\tmove[i] = bHat[i] / math.Abs(v)\n\t\t}\n\t}\n\treturn nil\n}",
"func (d *DStarLite) findShortestPath() {\n\t/*\n\t procedure ComputeShortestPath()\n\t {10”} while (U.TopKey() < CalculateKey(s_start) OR rhs(s_start) > g(s_start))\n\t {11”} u = U.Top();\n\t {12”} k_old = U.TopKey();\n\t {13”} k_new = CalculateKey(u);\n\t {14”} if(k_old < k_new)\n\t {15”} U.Update(u, k_new);\n\t {16”} else if (g(u) > rhs(u))\n\t {17”} g(u) = rhs(u);\n\t {18”} U.Remove(u);\n\t {19”} for all s ∈ Pred(u)\n\t {20”} if (s != s_goal) rhs(s) = min(rhs(s), c(s, u) + g(u));\n\t {21”} UpdateVertex(s);\n\t {22”} else\n\t {23”} g_old = g(u);\n\t {24”} g(u) = ∞;\n\t {25”} for all s ∈ Pred(u) ∪ {u}\n\t {26”} if (rhs(s) = c(s, u) + g_old)\n\t {27”} if (s != s_goal) rhs(s) = min s'∈Succ(s)(c(s, s') + g(s'));\n\t {28”} UpdateVertex(s);\n\t*/\n\tfor d.queue.Len() != 0 { // We use d.queue.Len since d.queue does not return an infinite key when empty.\n\t\tu := d.queue.top()\n\t\tif !u.key.less(d.keyFor(d.s)) && d.s.rhs <= d.s.g {\n\t\t\tbreak\n\t\t}\n\t\tuid := u.ID()\n\t\tswitch kNew := d.keyFor(u); {\n\t\tcase u.key.less(kNew):\n\t\t\td.queue.update(u, kNew)\n\t\tcase u.g > u.rhs:\n\t\t\tu.g = u.rhs\n\t\t\td.queue.remove(u)\n\t\t\tfrom := d.model.To(uid)\n\t\t\tfor from.Next() {\n\t\t\t\ts := from.Node().(*dStarLiteNode)\n\t\t\t\tsid := s.ID()\n\t\t\t\tif sid != d.t.ID() {\n\t\t\t\t\ts.rhs = math.Min(s.rhs, edgeWeight(d.model.Weight, sid, uid)+u.g)\n\t\t\t\t}\n\t\t\t\td.update(s)\n\t\t\t}\n\t\tdefault:\n\t\t\tgOld := u.g\n\t\t\tu.g = math.Inf(1)\n\t\t\tfor _, _s := range append(graph.NodesOf(d.model.To(uid)), u) {\n\t\t\t\ts := _s.(*dStarLiteNode)\n\t\t\t\tsid := s.ID()\n\t\t\t\tif s.rhs == edgeWeight(d.model.Weight, sid, uid)+gOld {\n\t\t\t\t\tif s.ID() != d.t.ID() {\n\t\t\t\t\t\ts.rhs = math.Inf(1)\n\t\t\t\t\t\tto := d.model.From(sid)\n\t\t\t\t\t\tfor to.Next() {\n\t\t\t\t\t\t\tt := to.Node()\n\t\t\t\t\t\t\ttid := t.ID()\n\t\t\t\t\t\t\ts.rhs = math.Min(s.rhs, edgeWeight(d.model.Weight, sid, tid)+t.(*dStarLiteNode).g)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\td.update(s)\n\t\t\t}\n\t\t}\n\t}\n}",
"func main() {\n\tfmt.Println(maxDistToClosest([]int{1, 0, 0, 0, 1, 0, 1}))\n\tfmt.Println(maxDistToClosest([]int{1, 0, 0, 0}))\n\tfmt.Println(maxDistToClosest([]int{0, 0, 0, 1}))\n}",
"func shortestPathRisk(grid [][]int, gridExpansion int) int {\n\ttargetRow, targetCol := gridTarget(grid, gridExpansion)\n\tvisited := make(map[string]struct{})\n\tpq := make(PriorityQueue, 0)\n\theap.Init(&pq)\n\theap.Push(&pq, &Item{\n\t\tcoords: []int{0, 0},\n\t})\n\n\tfor len(pq) >= 1 {\n\t\t// take elem\n\t\tcurrP := heap.Pop(&pq).(*Item)\n\n\t\tvisited[keyS(currP.coords[0], currP.coords[1])] = struct{}{}\n\t\t// fmt.Printf(\"visited %d, %d\\n\", currP.coords[0], currP.coords[1])\n\n\t\tif currP.coords[0] == targetRow && currP.coords[1] == targetCol {\n\t\t\treturn currP.costSoFar\n\t\t}\n\n\t\t// find all possible positions and push them to the Q\n\t\trow := currP.coords[0]\n\t\tcol := currP.coords[1]\n\t\tfor _, c := range [][]int{\n\t\t\t{row - 1, col},\n\t\t\t{row, col + 1},\n\t\t\t{row + 1, col},\n\t\t\t{row, col - 1},\n\t\t} {\n\t\t\tif _, ok := visited[keyS(c[0], c[1])]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\trisk, err := gridVal(grid, gridExpansion, c[0], c[1])\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tnewPos := &Item{\n\t\t\t\tcoords: c,\n\t\t\t\tcostSoFar: currP.costSoFar + risk,\n\t\t\t\tpriority: currP.costSoFar + risk + heuristicCost(c[0], c[1], targetRow, targetCol),\n\t\t\t}\n\n\t\t\theap.Push(&pq, newPos)\n\t\t}\n\t}\n\n\treturn 0\n}",
"func (l *Level) FindPath(start, end math.Point, cost func(*Level, math.Point) int) (path Path, ok bool) {\n\tpath = make(Path, 0, 100)\n\tif !start.In(l) || !end.In(l) || l.At(start).Feature.Solid || l.At(end).Feature.Solid {\n\t\treturn path, false\n\t}\n\n\tif start == end {\n\t\treturn path, true\n\t}\n\n\t// PQ\n\tdist := dists{start: 0}\n\tprev := map[math.Point]math.Point{}\n\ttodo := &dijkstraQ{&unvisited{p: start, dist: dist}}\n\theap.Init(todo)\n\n\tfor todo.Len() != 0 {\n\t\tcur := heap.Pop(todo).(*unvisited).p\n\t\tcurdist := dist[cur]\n\t\tif cur == end {\n\t\t\tbreak\n\t\t}\n\n\t\t// Get neighbouring points.\n\t\tneighbors := l.Around(cur)\n\n\t\t// Figure out which neighbours we should even bother checking (e.g.\n\t\t// walls are a bad idea at the moment. We don't have Kemenrauko.\n\t\tfor _, n := range neighbors {\n\t\t\tif !patheligible(n) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnpos := n.Pos\n\t\t\td := dist.get(npos)\n\n\t\t\taltdist := curdist + cost(l, npos)\n\t\t\tif altdist < d {\n\t\t\t\tdist[npos] = altdist\n\t\t\t\tprev[npos] = cur\n\t\t\t\theap.Push(todo, &unvisited{p: npos, dist: dist})\n\t\t\t}\n\t\t}\n\t}\n\n\t// Trace path, which will give us the route in reverse.\n\tpathcur := end\n\tfor {\n\t\tnext, ok := prev[pathcur]\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tpath = append(path, pathcur)\n\t\tpathcur = next\n\t}\n\n\t// Put the path in order.\n\tfor i, l := 0, len(path); i < l/2; i++ {\n\t\tpath[i], path[l-i-1] = path[l-i-1], path[i]\n\t}\n\n\t// We didn't find any path. Let the caller know via 'ok', since this\n\t// distinguishes the situation where you tried to pathfind to yourself.\n\tif len(path) == 0 {\n\t\treturn path, false\n\t}\n\treturn path, true\n}",
"func findDelta(first, second float64) float64 {\n\tif first == 0 {\n\t\treturn 0\n\t}\n\treturn second / first\n}",
"func firstdecision(gconfig Kiai.GameConfig) {\n\t\n\tif turn.X <= gconfig.Width / 2 && turn.Y < gconfig.Height / 2 { //Be careful, this method favours the top left corner due to int variables rounding the results of the division to lower limit.\n\t\tpath = 1 \n\t}\n\tif turn.X >= gconfig.Width / 2 && turn.Y < gconfig.Height / 2 {\n\t\tpath = 2 \n\t}\n\tif turn.X >= gconfig.Width / 2 && turn.Y > gconfig.Height / 2 {\n\t\tpath = 3 \n\t}\n\tif turn.X <= gconfig.Width / 2 && turn.Y > gconfig.Height / 2 {\n\t\tpath = 4 \n\t}\n\t\n\tstart = true\n}",
"func nelderMeadOptimize(f func([]float64) float64, start [][]float64, cf func([]float64)) ([]float64, int, int) {\n\tconst (\n\t\tkMax = 1000 // arbitrarily chosen value for now\n\t\tε = 0.000001 // Stopping criterion point\n\t\tα = 1.0\n\t\tβ = 0.5\n\t\tγ = 2.0\n\t)\n\n\t// point is the type of points in ℝ^n\n\ttype point []float64\n\n\t// simplex is the type used to represent a simplex\n\ttype simplex []point\n\n\tevaluations := 0\n\teval := func(f func([]float64) float64, p point) float64 {\n\t\tevaluations++\n\t\treturn f(p)\n\t}\n\n\t// sub perform point subtraction\n\tsub := func(x point, y point) point {\n\t\tr := make(point, len(x))\n\t\tfor i := range y {\n\t\t\tr[i] = x[i] - y[i]\n\t\t}\n\t\treturn r\n\t}\n\n\t// add perform point addition\n\tadd := func(x point, y point) point {\n\t\tr := make(point, len(x))\n\t\tfor i := range y {\n\t\t\tr[i] = x[i] + y[i]\n\t\t}\n\t\treturn r\n\t}\n\n\t// scale multiplies a point by a scalar\n\tscale := func(p point, scalar float64) point {\n\t\tr := make(point, len(p))\n\t\tfor i := range r {\n\t\t\tr[i] = scalar * p[i]\n\t\t}\n\t\treturn r\n\t}\n\n\t// centroid calculates the centroid of a simplex of one dimensionality lower by omitting a point\n\tcentroid := func(s simplex, omit int) point {\n\t\tr := make(point, len(s[0]))\n\t\tfor i := range r {\n\t\t\tc := 0.0\n\t\t\tfor j := range s {\n\t\t\t\tif j == omit {\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tc += s[j][i]\n\t\t\t\t}\n\t\t\t}\n\t\t\tr[i] = c / float64((len(s) - 1))\n\t\t}\n\t\treturn r\n\t}\n\n\tn := len(start)\n\tc := len(start[0])\n\tpoints := make([]point, 0)\n\tfv := make([]float64, n)\n\n\tfor _, p := range start {\n\t\tpoints = append(points, point(p))\n\t}\n\tsx := simplex(points)\n\tif n != c+1 {\n\t\tpanic(\"Can't optimize with too few starting points\")\n\t}\n\n\t// Set up initial values\n\tfor i := range fv {\n\t\tif cf != nil {\n\t\t\tcf(sx[i])\n\t\t}\n\t\tfv[i] = eval(f, sx[i])\n\t}\n\n\tk := 0\n\tfor ; k < kMax; k++ {\n\t\t// Find the largest index\n\t\tvg := 0\n\t\tfor i := range fv {\n\t\t\tif fv[i] > fv[vg] {\n\t\t\t\tvg = i\n\t\t\t}\n\t\t}\n\n\t\t// Find the smallest index\n\t\tvs := 0\n\t\tfor i := range fv {\n\t\t\tif fv[i] < fv[vs] {\n\t\t\t\tvs = i\n\t\t\t}\n\t\t}\n\n\t\t// Second largest index\n\t\tvh := vs\n\t\tfor i := range fv {\n\t\t\tif fv[i] > fv[vh] && fv[i] < fv[vg] {\n\t\t\t\tvh = i\n\t\t\t}\n\t\t}\n\n\t\tvm := centroid(sx, vg)\n\n\t\tvr := add(vm, scale(sub(vm, sx[vg]), α))\n\t\tif cf != nil {\n\t\t\tcf(vr)\n\t\t}\n\t\tfr := eval(f, vr)\n\n\t\tif fr < fv[vh] && fr >= fv[vs] {\n\t\t\t// Replace\n\t\t\tfv[vg] = fr\n\t\t\tsx[vg] = vr\n\t\t}\n\n\t\t// Investigate a step further\n\t\tif fr < fv[vs] {\n\t\t\tve := add(vm, scale(sub(vr, vm), γ))\n\t\t\tif cf != nil {\n\t\t\t\tcf(ve)\n\t\t\t}\n\n\t\t\tfe := eval(f, ve)\n\n\t\t\tif fe < fr {\n\t\t\t\tsx[vg] = ve\n\t\t\t\tfv[vg] = fe\n\t\t\t} else {\n\t\t\t\tsx[vg] = vr\n\t\t\t\tfv[vg] = fr\n\t\t\t}\n\t\t}\n\n\t\t// Check contraction\n\t\tif fr >= fv[vh] {\n\t\t\tvar vc point\n\t\t\tvar fc float64\n\t\t\tif fr < fv[vg] && fr >= fv[vh] {\n\t\t\t\t// Outside contraction\n\t\t\t\tvc = add(vm, scale(sub(vr, vm), β))\n\t\t\t} else {\n\t\t\t\t// Inside contraction\n\t\t\t\tvc = sub(vm, scale(sub(vm, sx[vg]), β))\n\t\t\t}\n\n\t\t\tif cf != nil {\n\t\t\t\tcf(vc)\n\t\t\t}\n\t\t\tfc = eval(f, vc)\n\n\t\t\tif fc < fv[vg] {\n\t\t\t\tsx[vg] = vc\n\t\t\t\tfv[vg] = fc\n\t\t\t} else {\n\t\t\t\tfor i := range sx {\n\t\t\t\t\tif i != vs {\n\t\t\t\t\t\tsx[i] = add(sx[vs], scale(sub(sx[i], sx[vs]), β))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif cf != nil {\n\t\t\t\t\tcf(sx[vg])\n\t\t\t\t}\n\t\t\t\tfv[vg] = eval(f, sx[vg])\n\n\t\t\t\tif cf != nil {\n\t\t\t\t\tcf(sx[vh])\n\t\t\t\t}\n\t\t\t\tfv[vh] = eval(f, sx[vh])\n\t\t\t}\n\t\t}\n\n\t\tfsum := 0.0\n\t\tfor _, v := range fv {\n\t\t\tfsum += v\n\t\t}\n\n\t\tfavg := fsum / float64(len(fv))\n\n\t\ts := 0.0\n\t\tfor _, v := range fv {\n\t\t\ts += math.Pow(v-favg, 2.0)\n\t\t}\n\n\t\ts = s * (1.0 / (float64(len(fv)) + 1.0))\n\t\ts = math.Sqrt(s)\n\t\tif s < ε {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tvs := 0\n\tfor i := range fv {\n\t\tif fv[i] < fv[vs] {\n\t\t\tvs = i\n\t\t}\n\t}\n\n\treturn sx[vs], k, evaluations\n}",
"func explore(m *Maze, code string, ms int) {\n\t// the recursion is to keep going until you are blocked in all directions.\n\t// then backtrack until you get an option and if we run out of backtrack\n\t// and options, then we are done.\n\tpg := intcode.New(code)\n\tx, y := 0, 0\n\n\tpath := &Path{\n\t\tprev: nil,\n\t\treturnDirection: nowhere,\n\t}\n\n\tupdatePosition := func(d Direction) {\n\t\tswitch d {\n\t\tcase nowhere:\n\t\tcase north:\n\t\t\tx--\n\t\tcase south:\n\t\t\tx++\n\t\tcase west:\n\t\t\ty--\n\t\tcase east:\n\t\t\ty++\n\t\t}\n\t}\n\n\tpg.RunAsync()\n\n\tfor {\n\t\tif ms > 0 {\n\t\t\ttime.Sleep(time.Duration(ms) * time.Millisecond)\n\t\t\tfmt.Println(\"\\x1b[2JX\", x, \"Y\", y, \"D\", m.Unexplored(x, y))\n\t\t\tfmt.Println(m)\n\t\t}\n\t\tnextDirection := m.Unexplored(x, y)\n\t\tif nextDirection == nowhere {\n\t\t\t// need to backtrack\n\t\t\tif path.prev == nil {\n\t\t\t\t// nowhere to go!\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// tell it to go back\n\t\t\tpg.Input <- func() int64 {\n\t\t\t\treturn int64(path.returnDirection)\n\t\t\t}\n\t\t\t<-pg.Output // ignore output\n\t\t\tupdatePosition(path.returnDirection)\n\t\t\tpath = path.prev\n\t\t\tcontinue\n\t\t}\n\t\t// not a back track\n\t\tpg.Input <- func() int64 {\n\t\t\treturn int64(nextDirection)\n\t\t}\n\n\t\t// fine\n\t\t// now read new position\n\t\tout := <-pg.Output\n\t\tback := reverse(nextDirection)\n\t\tupdatePosition(nextDirection)\n\t\tswitch Response(out) {\n\t\tcase hit_nothing:\n\t\t\t// empty space\n\t\t\tm.Explore(x, y, empty)\n\t\t\tpath = &Path{\n\t\t\t\tprev: path,\n\t\t\t\treturnDirection: back,\n\t\t\t}\n\t\tcase hit_wall:\n\t\t\t// don't move\n\t\t\tm.Explore(x, y, wall)\n\t\t\tupdatePosition(back)\n\t\tcase hit_oxygen:\n\t\t\tm.Explore(x, y, oxygen)\n\t\t\tm.oxygen = [2]int{x, y}\n\t\t\tpath = &Path{\n\t\t\t\tprev: path,\n\t\t\t\treturnDirection: back,\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(\"bad output!\")\n\t\t}\n\t}\n}",
"func Fiore(t *terrapin.Terrapin, lung float64, liv int) {\n for i := 0; i < 3; i++ {\n if liv == 0 {\n t.Forward(lung)\n return\n }\n Fiore(t, lung, liv - 1)\n t.Left(math.Pi / 3.0)\n Fiore(t, lung, liv - 1)\n t.Right(math.Pi - math.Pi / 3.0)\n Fiore(t, lung, liv - 1)\n t.Left(math.Pi / 3.0)\n Fiore(t, lung, liv - 1)\n t.Right(2.0 * math.Pi / 3.0)\n }\n\n}",
"func (o *LineSearch) zoom(fini, gini, alo, ahi, flo, fhi float64) (a, f float64) {\n\n\t// auxiliary\n\tglo := o.G(alo)\n\tvar g, aprev, fprev float64\n\tvar interpOk bool\n\tvar da, achk, bchk, dchk float64\n\tvar err error\n\n\t// iterations\n\tfor o.NumIterZoom = 0; o.NumIterZoom < o.MaxItZoom; o.NumIterZoom++ {\n\n\t\t// variables for checking range\n\t\tda = ahi - alo\n\t\tachk, bchk = alo, ahi\n\t\tif da < 0 {\n\t\t\tachk, bchk = ahi, alo\n\t\t}\n\n\t\t// cubic interpolation because we have previous values and the gap=ahi-alo is not small\n\t\tinterpOk = false\n\t\tif o.NumIterZoom > 0 {\n\t\t\ta = cubicmin(alo, flo, glo, ahi, fhi, aprev, fprev)\n\t\t\tdchk = o.CoefCubic * da\n\t\t\tif a >= achk+dchk && a <= bchk-dchk { // accept only if a didn't change much\n\t\t\t\tinterpOk = true\n\t\t\t}\n\t\t}\n\n\t\t// quadratic interpolation and the gap=ahi-alo is not small\n\t\tif !interpOk {\n\t\t\terr = o.interp2.Fit2pointsD(alo, flo, ahi, fhi, alo, glo)\n\t\t\tif err == nil {\n\t\t\t\ta, _ = o.interp2.Optimum()\n\t\t\t\tdchk = o.CoefQuad * da\n\t\t\t\tif a >= achk+dchk && a <= bchk-dchk { // accept only if a didn't change much\n\t\t\t\t\tinterpOk = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// bi-section because interpolation failed or the gap is too small\n\t\tif !interpOk {\n\t\t\ta = alo + 0.5*(ahi-alo)\n\t\t}\n\n\t\t// evaluate F\n\t\tf = o.F(a)\n\n\t\t// update\n\t\tif f > fini+o.Coef1*a*gini || f >= flo {\n\t\t\taprev = ahi\n\t\t\tfprev = fhi\n\t\t\tahi = a\n\t\t\tfhi = f\n\t\t} else {\n\n\t\t\t// evaluate G\n\t\t\tg = o.G(a)\n\n\t\t\t// exit condition\n\t\t\tif math.Abs(g) <= -o.Coef2*gini {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// swap hi;lo\n\t\t\tif g*(ahi-alo) >= 0 {\n\t\t\t\taprev = ahi\n\t\t\t\tfprev = fhi\n\t\t\t\tahi = alo\n\t\t\t\tfhi = flo\n\t\t\t} else {\n\t\t\t\taprev = alo\n\t\t\t\tfprev = flo\n\t\t\t}\n\n\t\t\t// next 'lo' values\n\t\t\talo = a\n\t\t\tflo = f\n\t\t\tglo = g\n\t\t}\n\t}\n\n\t// failure\n\tchk.Panic(\"zoom did not converge after %d iterations\\n\", o.NumIterZoom)\n\treturn\n}",
"func solveProblem(from, to int, pos int, c chan bool) {\n\tfromPos := getCeilPos(from)\n\ttoPos := getCeilPos(to)\n\tif almostPrime[fromPos] < from {\n\t\tfromPos += 1\n\t}\n\tif toPos+1 < len(almostPrime) && almostPrime[toPos+1] == to {\n\t\ttoPos += 1\n\t}\n\n\tif fromPos == toPos && almostPrime[fromPos] != from {\n\t\taddSolution(pos, \"0\", c)\n\t\treturn\n\t}\n\t//fmt.Println(\"Search\", from, to, fromPos, toPos, almostPrime[fromPos:toPos+1])\n\n\taddSolution(pos, fmt.Sprintf(\"%d\", len(almostPrime[fromPos:toPos+1])), c)\n}",
"func optimise(sigSize int, jsThresh float64) (int, int, float64, float64) {\n\toptimumK, optimumL := 0, 0\n\tfp, fn := 0.0, 0.0\n\tminError := math.MaxFloat64\n\tfor l := 1; l <= sigSize; l++ {\n\t\tfor k := 1; k <= sigSize; k++ {\n\t\t\tif l*k > sigSize {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcurrFp := probFalsePositive(l, k, jsThresh, 0.01)\n\t\t\tcurrFn := probFalseNegative(l, k, jsThresh, 0.01)\n\t\t\tcurrErr := currFn + currFp\n\t\t\tif minError > currErr {\n\t\t\t\tminError = currErr\n\t\t\t\toptimumK = k\n\t\t\t\toptimumL = l\n\t\t\t\tfp = currFp\n\t\t\t\tfn = currFn\n\t\t\t}\n\t\t}\n\t}\n\treturn optimumK, optimumL, fp, fn\n}",
"func (level *Level) bresenhum(start Pos, end Pos) {\n\tsteep := math.Abs(float64(end.Y-start.Y)) > math.Abs(float64(end.X-start.X)) // Is the line steep or not?\n\t// Swap the x and y for start and end\n\tif steep {\n\t\tstart.X, start.Y = start.Y, start.X\n\t\tend.X, end.Y = end.Y, end.X\n\t}\n\n\tdeltaY := int32(math.Abs(float64(end.Y - start.Y)))\n\n\tvar err int32\n\ty := start.Y\n\tvar ystep int32 = 1 // How far we are stepping when err is above threshold\n\tif start.Y >= end.Y {\n\t\tystep = -1 // Reverse it when we step\n\t}\n\t// Are we on the left or right side of graph\n\tif start.X > end.X {\n\t\tdeltaX := start.X - end.X // We know start.X will be larger than end.X\n\t\t// Count down so lines extend FROM the player, not TO\n\t\tfor x := start.X; x > end.X; x-- {\n\t\t\tvar pos Pos\n\t\t\tif steep {\n\t\t\t\tpos = Pos{y, x} // If we are steep, x and y will be swapped\n\t\t\t} else {\n\t\t\t\tpos = Pos{x, y}\n\t\t\t}\n\t\t\tlevel.Map[pos.Y][pos.X].Visible = true\n\t\t\tlevel.Map[pos.Y][pos.X].Seen = true\n\t\t\tif !canSeeThrough(level, pos) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr += deltaY\n\t\t\tif 2*err >= deltaX {\n\t\t\t\ty += ystep // Go up or down depending on the direction of our line\n\t\t\t\terr -= deltaX\n\t\t\t}\n\t\t}\n\t} else {\n\t\tdeltaX := end.X - start.X // We know start.X will be larger than end.X\n\t\tfor x := start.X; x < end.X; x++ {\n\t\t\tvar pos Pos\n\t\t\tif steep {\n\t\t\t\tpos = Pos{y, x} // If we are steep, x and y will be swapped\n\t\t\t} else {\n\t\t\t\tpos = Pos{x, y}\n\t\t\t}\n\t\t\tlevel.Map[pos.Y][pos.X].Visible = true\n\t\t\tlevel.Map[pos.Y][pos.X].Seen = true\n\t\t\tif !canSeeThrough(level, pos) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr += deltaY\n\t\t\tif 2*err >= deltaX {\n\t\t\t\ty += ystep // Go up or down depending on the direction of our line\n\t\t\t\terr -= deltaX\n\t\t\t}\n\t\t}\n\t}\n}"
] | [
"0.5926744",
"0.5688977",
"0.56450564",
"0.56370515",
"0.55542666",
"0.5544013",
"0.548007",
"0.5270841",
"0.5153565",
"0.5151094",
"0.51392984",
"0.5100291",
"0.5080389",
"0.49591163",
"0.4958202",
"0.4937103",
"0.4911481",
"0.48834258",
"0.48780674",
"0.48676497",
"0.48641607",
"0.48526883",
"0.48386508",
"0.4827587",
"0.48272634",
"0.47854927",
"0.47774625",
"0.47762194",
"0.4767676",
"0.47636157",
"0.47594962",
"0.47593868",
"0.47564608",
"0.4755353",
"0.47520792",
"0.47410518",
"0.47409242",
"0.47097787",
"0.47066563",
"0.46820268",
"0.46773162",
"0.46650273",
"0.46622735",
"0.465116",
"0.46423885",
"0.46384233",
"0.46340874",
"0.46316066",
"0.46303317",
"0.46292213",
"0.4625063",
"0.46185565",
"0.46184853",
"0.46150464",
"0.46144882",
"0.4610788",
"0.46071705",
"0.45960015",
"0.4595631",
"0.4591816",
"0.45903537",
"0.4587396",
"0.45863315",
"0.4582561",
"0.45776847",
"0.4576539",
"0.45738855",
"0.45716485",
"0.4570875",
"0.45575425",
"0.4556792",
"0.45555767",
"0.4553902",
"0.455201",
"0.45504642",
"0.45500508",
"0.4547639",
"0.45472777",
"0.45472437",
"0.45351192",
"0.45317575",
"0.45309108",
"0.45279676",
"0.45276195",
"0.45223162",
"0.45111728",
"0.45081523",
"0.45023298",
"0.45010057",
"0.45000973",
"0.4498315",
"0.44968054",
"0.44943982",
"0.44917154",
"0.44898546",
"0.4487381",
"0.4487035",
"0.44847772",
"0.4482999",
"0.44793668"
] | 0.61704475 | 0 |
setupConfigHandlers adds the specific handlers for /config endpoints | func setupConfigHandlers(r *mux.Router) {
r.HandleFunc("/config", settingshttp.Server.GetFullSystemProbeConfig(getAggregatedNamespaces()...)).Methods("GET")
r.HandleFunc("/config/list-runtime", settingshttp.Server.ListConfigurable).Methods("GET")
r.HandleFunc("/config/{setting}", settingshttp.Server.GetValue).Methods("GET")
r.HandleFunc("/config/{setting}", settingshttp.Server.SetValue).Methods("POST")
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func SetupHandlers() {\n\tif config.Development() {\n\t\thttp.HandleFunc(\"/_hash\", common.Recover(encryption.HashHandler))\n\t\thttp.HandleFunc(\"/_sign\", common.Recover(common.ToJSONResponse(encryption.SignHandler)))\n\t\thttp.HandleFunc(updateConfigURL, common.Recover(ConfigUpdateHandler))\n\t\thttp.HandleFunc(updateConfigAllURL, common.Recover(ConfigUpdateAllHandler))\n\t}\n}",
"func ConfigHandler(o *Options) {\n\thooksRegistry, hooksHandler := o.HooksFactory.NewRegistryAndHandler(o.M)\n\t//TODO: GET SoAProvider, it is currently nil\n\n\to.APIRouter.Handle(\"/hook\", o.Authenticate.ThenFunc(hooksRegistry.UpdateRegistry))\n\to.APIRouter.Handle(\"/hooks\", o.Authenticate.ThenFunc(hooksRegistry.GetRegistry))\n\n\tselfURL := &url.URL{\n\t\tScheme: o.Scheme,\n\t\tHost: o.Host,\n\t}\n\n\t//Initialize must take the router without any prefixes\n\to.HooksFactory.Initialize(o.RootRouter, selfURL, o.SoAProvider, hooksHandler, o.Log, o.M, time.Now)\n}",
"func setuphandlers() {\n\thttp.HandleFunc(\"/\", rootHandler)\n\thttp.HandleFunc(\"/status\", statusHandler)\n\thttp.HandleFunc(\"/stats\", statsHandler)\n\thttp.HandleFunc(\"/request\", requestHandler)\n}",
"func setupHandlers() error {\n\treturn pluginRegistry.Do(func(plugin core.Pluginer) error {\n\t\tfor _, url := range plugin.URLs() {\n\t\t\tif err := url.Register(Context.Router, middlewares); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t}\n\t\treturn nil\n\t})\n}",
"func InstallHandlers(r *router.Router, middleware router.MiddlewareChain) {\n\tcronMiddleware := middleware.Extend(gaemiddleware.RequireCron)\n\tr.GET(\"/internal/cron/import-config\", cronMiddleware, importHandler)\n}",
"func InstallHandlers(r *router.Router, base router.MiddlewareChain) {\n\tr.GET(\"/auth/api/v1/server/certificates\", base, certsHandler)\n\tr.GET(\"/auth/api/v1/server/info\", base, infoHandler)\n\tr.GET(\"/auth/api/v1/server/client_id\", base, clientIDHandler)\n}",
"func (a *Api) SetHandlers(prefix string, rtr *mux.Router) {\n\t//Health checks and metrics\n\trtr.Handle(\"/metrics\", promhttp.Handler())\n\trtr.HandleFunc(\"/status\", a.GetStatus).Methods(\"GET\")\n\n\t//User management methods\n\trtr.HandleFunc(\"/users\", a.GetUsers).Methods(\"GET\")\n\n\trtr.Handle(\"/user\", varsHandler(a.GetUserInfo)).Methods(\"GET\")\n\trtr.Handle(\"/user/{userid}\", varsHandler(a.GetUserInfo)).Methods(\"GET\")\n\trtr.HandleFunc(\"/user\", a.CreateUser).Methods(\"POST\")\n\trtr.Handle(\"/user\", varsHandler(a.UpdateUser)).Methods(\"PUT\")\n\trtr.Handle(\"/user/{userid}\", varsHandler(a.UpdateUser)).Methods(\"PUT\")\n\trtr.Handle(\"/user/{userid}\", varsHandler(a.DeleteUser)).Methods(\"DELETE\")\n\n\t//Login and token management methods\n\trtr.HandleFunc(\"/login\", a.Login).Methods(\"POST\")\n\trtr.HandleFunc(\"/logout\", a.Logout).Methods(\"POST\")\n\trtr.HandleFunc(\"/login\", a.RefreshSession).Methods(\"GET\")\n\trtr.HandleFunc(\"/serverlogin\", a.ServerLogin).Methods(\"POST\")\n\trtr.Handle(\"/token/{token}\", varsHandler(a.ServerCheckToken)).Methods(\"GET\")\n\n}",
"func (svc *ProductHTTP) SetupHandlers(e *seaman.Engine) {\n\tsvc.setupGetProducts(e) // api\n\tsvc.setupGetProduct(e) // api\n}",
"func ConfigHandler(c *Options) {\n\topts := []kithttp.ServerOption{\n\t\tkithttp.ServerBefore(common.Capture),\n\t\tkithttp.ServerErrorEncoder(common.ErrorLogEncoder(c.Log, encodeError)),\n\t\tkithttp.ServerFinalizer(common.TransactionLogging(c.Log)),\n\t}\n\n\tstatHandler := kithttp.NewServer(\n\t\tmakeStatEndpoint(c.S),\n\t\tdecodeRequest,\n\t\tencodeResponse,\n\t\topts...,\n\t)\n\n\tc.APIRouter.Handle(\"/device/{deviceid}/stat\", c.Authenticate.Then(common.Welcome(statHandler))).\n\t\tMethods(http.MethodGet)\n}",
"func InitHandlers(mux *http.ServeMux) {\n\tmux.HandleFunc(\"/\", withHeaders(withRequestLog(runtimeHandler)))\n\tmux.HandleFunc(nethttp.HealthCheckPath, withRequestLog(withKubeletProbeHeaderCheck))\n}",
"func RegisterConfigServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server ConfigServiceServer) error {\n\n\tmux.Handle(\"GET\", pattern_ConfigService_GetConfig_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_ConfigService_GetConfig_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_GetConfig_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"PUT\", pattern_ConfigService_SetConfig_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_ConfigService_SetConfig_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_SetConfig_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"GET\", pattern_ConfigService_GetToken_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_ConfigService_GetToken_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_GetToken_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"GET\", pattern_ConfigService_GetDefaultToken_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_ConfigService_GetDefaultToken_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_GetDefaultToken_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"POST\", pattern_ConfigService_CreateTokenType_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_ConfigService_CreateTokenType_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_CreateTokenType_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"GET\", pattern_ConfigService_GetTokenType_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_ConfigService_GetTokenType_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_GetTokenType_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"GET\", pattern_ConfigService_ListTokenTypes_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_ConfigService_ListTokenTypes_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_ListTokenTypes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"PUT\", pattern_ConfigService_UpdateTokenType_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_ConfigService_UpdateTokenType_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_UpdateTokenType_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"DELETE\", pattern_ConfigService_DeleteTokenType_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_ConfigService_DeleteTokenType_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_DeleteTokenType_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"GET\", pattern_ConfigService_GetTokenGroups_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_ConfigService_GetTokenGroups_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_GetTokenGroups_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"POST\", pattern_ConfigService_CreateTokenGroup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_ConfigService_CreateTokenGroup_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_CreateTokenGroup_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"GET\", pattern_ConfigService_GetTokenGroup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_ConfigService_GetTokenGroup_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_GetTokenGroup_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"DELETE\", pattern_ConfigService_DeleteTokenGroup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_ConfigService_DeleteTokenGroup_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_DeleteTokenGroup_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\treturn nil\n}",
"func (api *API) configRoutes(r *gin.Engine) {\n\tr.GET(\"/ping\", func(c *gin.Context) { api.pingCtrl.Ping(c) })\n\tr.GET(\"/messages/:id\", func(c *gin.Context) { api.msgCtrl.Get(c) })\n}",
"func SetupHandlers(r *mux.Router) {\n\t//object operations\n\tr.HandleFunc(\"/v1/file/upload/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithConnection(UploadHandler))))\n\tr.HandleFunc(\"/v1/file/download/{allocation}\", common.UserRateLimit(common.ToByteStream(WithConnection(DownloadHandler)))).Methods(\"POST\")\n\tr.HandleFunc(\"/v1/file/rename/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithConnection(RenameHandler))))\n\tr.HandleFunc(\"/v1/file/copy/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithConnection(CopyHandler))))\n\tr.HandleFunc(\"/v1/file/attributes/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithConnection(UpdateAttributesHandler))))\n\tr.HandleFunc(\"/v1/dir/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithConnection(CreateDirHandler)))).Methods(\"POST\")\n\tr.HandleFunc(\"/v1/dir/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithConnection(CreateDirHandler)))).Methods(\"DELETE\")\n\tr.HandleFunc(\"/v1/dir/rename/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithConnection(CreateDirHandler)))).Methods(\"POST\")\n\n\tr.HandleFunc(\"/v1/connection/commit/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithConnection(CommitHandler))))\n\tr.HandleFunc(\"/v1/file/commitmetatxn/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithConnection(CommitMetaTxnHandler))))\n\tr.HandleFunc(\"/v1/file/collaborator/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithConnection(CollaboratorHandler))))\n\tr.HandleFunc(\"/v1/file/calculatehash/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithConnection(CalculateHashHandler))))\n\n\t//object info related apis\n\tr.HandleFunc(\"/allocation\", common.UserRateLimit(common.ToJSONResponse(WithConnection(AllocationHandler))))\n\tr.HandleFunc(\"/v1/file/meta/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithReadOnlyConnection(FileMetaHandler))))\n\tr.HandleFunc(\"/v1/file/stats/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithReadOnlyConnection(FileStatsHandler))))\n\tr.HandleFunc(\"/v1/file/list/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithReadOnlyConnection(ListHandler))))\n\tr.HandleFunc(\"/v1/file/objectpath/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithReadOnlyConnection(ObjectPathHandler))))\n\tr.HandleFunc(\"/v1/file/referencepath/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithReadOnlyConnection(ReferencePathHandler))))\n\tr.HandleFunc(\"/v1/file/objecttree/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithReadOnlyConnection(ObjectTreeHandler))))\n\tr.HandleFunc(\"/v1/file/refs/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithReadOnlyConnection(RefsHandler)))).Methods(\"GET\")\n\t//admin related\n\tr.HandleFunc(\"/_debug\", common.UserRateLimit(common.ToJSONResponse(DumpGoRoutines)))\n\tr.HandleFunc(\"/_config\", common.UserRateLimit(common.ToJSONResponse(GetConfig)))\n\tr.HandleFunc(\"/_stats\", common.UserRateLimit(stats.StatsHandler))\n\tr.HandleFunc(\"/_statsJSON\", common.UserRateLimit(common.ToJSONResponse(stats.StatsJSONHandler)))\n\tr.HandleFunc(\"/_cleanupdisk\", common.UserRateLimit(common.ToJSONResponse(WithReadOnlyConnection(CleanupDiskHandler))))\n\tr.HandleFunc(\"/getstats\", common.UserRateLimit(common.ToJSONResponse(stats.GetStatsHandler)))\n\n\t//marketplace related\n\tr.HandleFunc(\"/v1/marketplace/shareinfo/{allocation}\", common.UserRateLimit(common.ToJSONResponse(WithConnection(MarketPlaceShareInfoHandler))))\n}",
"func TestSetConfigHandler(t *testing.T) {\n\tadminTestBed, err := prepareAdminXLTestBed()\n\tif err != nil {\n\t\tt.Fatal(\"Failed to initialize a single node XL backend for admin handler tests.\")\n\t}\n\tdefer adminTestBed.TearDown()\n\n\t// Initialize admin peers to make admin RPC calls.\n\tglobalMinioAddr = \"127.0.0.1:9000\"\n\tinitGlobalAdminPeers(mustGetNewEndpointList(\"http://127.0.0.1:9000/d1\"))\n\n\t// SetConfigHandler restarts minio setup - need to start a\n\t// signal receiver to receive on globalServiceSignalCh.\n\tgo testServiceSignalReceiver(restartCmd, t)\n\n\t// Prepare query params for set-config mgmt REST API.\n\tqueryVal := url.Values{}\n\tqueryVal.Set(\"config\", \"\")\n\n\treq, err := buildAdminRequest(queryVal, \"set\", http.MethodPut, int64(len(configJSON)),\n\t\tbytes.NewReader(configJSON))\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to construct get-config object request - %v\", err)\n\t}\n\n\trec := httptest.NewRecorder()\n\tadminTestBed.mux.ServeHTTP(rec, req)\n\tif rec.Code != http.StatusOK {\n\t\tt.Errorf(\"Expected to succeed but failed with %d\", rec.Code)\n\t}\n\n\tresult := setConfigResult{}\n\terr = json.NewDecoder(rec.Body).Decode(&result)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to decode set config result json %v\", err)\n\t}\n\n\tif !result.Status {\n\t\tt.Error(\"Expected set-config to succeed, but failed\")\n\t}\n}",
"func SetupRoutes(engine *gin.Engine) {\n\tENABLE_SWAGGER := configs.Envs[\"ENABLE_SWAGGER\"]\n\tif ENABLE_SWAGGER == \"true\" {\n\t\tengine.GET(\"/swagger/*any\", ginSwagger.WrapHandler(swaggerFiles.Handler))\n\t}\n\n\tfor _, controller := range routes.GetRoutes() {\n\t\tengine.Handle(controller.Method, controller.Path, controller.Handler)\n\t} // setup routes\n}",
"func SetupHandlers(ctx context.Context) {\n\thttp.Handle(\"/version\", VersionHandler(ctx))\n}",
"func InstallHandlers(r *router.Router, bm router.MiddlewareChain) {\n\ttmpl := prepareTemplates(\"templates\")\n\n\tm := bm.Extend(\n\t\ttemplates.WithTemplates(tmpl),\n\t\tauth.Authenticate(\n\t\t\tserver.UsersAPIAuthMethod{},\n\t\t\t&server.OAuth2Method{\n\t\t\t\tScopes: []string{server.EmailScope},\n\t\t\t},\n\t\t),\n\t)\n\tm = m.Extend(hasAccess)\n\n\tr.GET(\"/\", m, indexPage)\n\tr.GET(\"/assigner/:AssignerID\", m, assignerPage)\n\tr.GET(\"/assigner/:AssignerID/task/:TaskID\", m, taskPage)\n}",
"func (api *APIServer) httpConfigHandler(w http.ResponseWriter, r *http.Request) {\n\tconfig := api.config\n\tconfig.ClickHouse.Password = \"***\"\n\tconfig.API.Password = \"***\"\n\tconfig.S3.SecretKey = \"***\"\n\tconfig.GCS.CredentialsJSON = \"***\"\n\tconfig.COS.SecretKey = \"***\"\n\tconfig.FTP.Password = \"***\"\n\tbody, err := yaml.Marshal(&config)\n\tif err != nil {\n\t\twriteError(w, http.StatusInternalServerError, \"config\", err)\n\t}\n\tw.Header().Set(\"Content-Type\", \"text/plain; charset=UTF-8\")\n\tw.Header().Set(\"Cache-Control\", \"no-store, no-cache, must-revalidate\")\n\tw.Header().Set(\"Pragma\", \"no-cache\")\n\tfmt.Fprintln(w, string(body))\n}",
"func (s *Server) setupEndpoints(r *chi.Mux) {\n\tr.Route(\"/api/v1\", func(r chi.Router) {\n\t\tr.Route(\"/users\", func(r chi.Router) {\n\n\t\t})\n\t})\n}",
"func InitHandlers(services *Services) *gin.Engine {\n\n\trouter := gin.Default()\n\n\thandler.InitUserHandler(router, handler.UserHandlerConfig{\n\t\tUserService: services.UserService,\n\t\tAuthService: services.AuthService,\n\t})\n\thandler.InitAuthHandler(router, handler.AuthHandlerConfig{\n\t\tAuthService: services.AuthService,\n\t})\n\n\thandler.InitStatusAndRoleHandler(router)\n\n\treturn router\n}",
"func InstallHandlers(r *httprouter.Router, base middleware.Base, cfg Config) {\n\ttmpl := prepareTemplates(cfg.TemplatesPath)\n\n\twrap := func(h middleware.Handler) httprouter.Handle {\n\t\th = auth.Authenticate(h)\n\t\th = templates.WithTemplates(h, tmpl)\n\t\th = middleware.WithContextValue(h, configContextKey(0), &cfg)\n\t\treturn base(h)\n\t}\n\n\tr.GET(\"/\", wrap(indexPage))\n\tr.GET(\"/jobs/:ProjectID\", wrap(projectPage))\n\tr.GET(\"/jobs/:ProjectID/:JobID\", wrap(jobPage))\n\tr.GET(\"/jobs/:ProjectID/:JobID/:InvID\", wrap(invocationPage))\n\n\t// All POST forms must be protected with XSRF token.\n\tr.POST(\"/actions/runJob/:ProjectID/:JobID\", wrap(xsrf.WithTokenCheck(runJobAction)))\n\tr.POST(\"/actions/pauseJob/:ProjectID/:JobID\", wrap(xsrf.WithTokenCheck(pauseJobAction)))\n\tr.POST(\"/actions/resumeJob/:ProjectID/:JobID\", wrap(xsrf.WithTokenCheck(resumeJobAction)))\n\tr.POST(\"/actions/abortInvocation/:ProjectID/:JobID/:InvID\", wrap(xsrf.WithTokenCheck(abortInvocationAction)))\n}",
"func setup(c *caddy.Controller) error {\n\tconfig, err := NewConfigFromCaddy(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thttpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {\n\t\treturn NewHandler(next, config)\n\t})\n\n\treturn nil\n}",
"func (ws *WebServer) registerHandlers() {\n\t// --------------------------------\n\t// AVAILABLE WITHOUT AUTH\n\n\tws.router.Use(\n\t\tws.addHeaders, ws.optionsHandler,\n\t\tws.handlerFiles, ws.handleMetrics)\n\n\tws.router.Get(\"/ota\", ws.handlerGetOta)\n\n\timagestore := ws.router.Group(\"/imagestore\")\n\timagestore.\n\t\tGet(\"/<id>\", ws.handlerGetImage)\n\n\tutils := ws.router.Group(\"/api/util\")\n\tutils.\n\t\tGet(`/color/<hexcode:[\\da-fA-F]{6,8}>`, ws.handlerGetColor)\n\tutils.\n\t\tGet(\"/commands\", ws.handlerGetCommands)\n\tutils.\n\t\tGet(\"/landingpageinfo\", ws.handlerGetLandingPageInfo)\n\n\tws.router.Get(\"/invite\", ws.handlerGetInvite)\n\n\t// --------------------------------\n\t// ONLY AVAILABLE AFTER AUTH\n\n\tws.router.Get(endpointLogInWithDC, ws.dcoauth.HandlerInit)\n\tws.router.Get(endpointAuthCB, ws.dcoauth.HandlerCallback)\n\n\tws.router.Use(ws.auth.checkAuth)\n\tif !util.DevModeEnabled {\n\t\tws.router.Use(ws.af.Handler)\n\t}\n\n\tapi := ws.router.Group(\"/api\")\n\tapi.\n\t\tGet(\"/me\", ws.af.SessionSetHandler, ws.handlerGetMe)\n\tapi.\n\t\tPost(\"/logout\", ws.auth.LogOutHandler)\n\tapi.\n\t\tGet(\"/sysinfo\", ws.handlerGetSystemInfo)\n\n\tsettings := api.Group(\"/settings\")\n\tsettings.\n\t\tGet(\"/presence\", ws.handlerGetPresence).\n\t\tPost(ws.handlerPostPresence)\n\tsettings.\n\t\tGet(\"/noguildinvite\", ws.handlerGetInviteSettings).\n\t\tPost(ws.handlerPostInviteSettings)\n\n\tguilds := api.Group(\"/guilds\")\n\tguilds.\n\t\tGet(\"\", ws.handlerGuildsGet)\n\n\tguild := guilds.Group(\"/<guildid:[0-9]+>\")\n\tguild.\n\t\tGet(\"\", ws.handlerGuildsGetGuild)\n\tguild.\n\t\tGet(\"/permissions\", ws.handlerGetGuildPermissions).\n\t\tPost(ws.handlerPostGuildPermissions)\n\tguild.\n\t\tGet(\"/members\", ws.handlerGetGuildMembers)\n\tguild.\n\t\tPost(\"/inviteblock\", ws.handlerPostGuildInviteBlock)\n\tguild.\n\t\tGet(\"/scoreboard\", ws.handlerGetGuildScoreboard)\n\tguild.\n\t\tGet(\"/antiraid/joinlog\", ws.handlerGetGuildAntiraidJoinlog).\n\t\tDelete(ws.handlerDeleteGuildAntiraidJoinlog)\n\n\tguildUnbanRequests := guild.Group(\"/unbanrequests\")\n\tguildUnbanRequests.\n\t\tGet(\"\", ws.handlerGetGuildUnbanrequests)\n\tguildUnbanRequests.\n\t\tGet(\"/count\", ws.handlerGetGuildUnbanrequestsCount)\n\tguildUnbanRequests.\n\t\tGet(\"/<id:[0-9]+>\", ws.handlerGetGuildUnbanrequest).\n\t\tPost(ws.handlerPostGuildUnbanrequest)\n\n\tguildSettings := guild.Group(\"/settings\")\n\tguildSettings.\n\t\tGet(\"/karma\", ws.handlerGetGuildSettingsKarma).\n\t\tPost(ws.handlerPostGuildSettingsKarma)\n\tguildSettings.\n\t\tGet(\"/antiraid\", ws.handlerGetGuildSettingsAntiraid).\n\t\tPost(ws.handlerPostGuildSettingsAntiraid)\n\n\tguildSettingsKarmaBlocklist := guildSettings.Group(\"/karma/blocklist\")\n\tguildSettingsKarmaBlocklist.\n\t\tGet(\"\", ws.handlerGetGuildSettingsKarmaBlocklist)\n\tguildSettingsKarmaBlocklist.\n\t\tPut(\"/<memberid>\", ws.handlerPutGuildSettingsKarmaBlocklist).\n\t\tDelete(ws.handlerDeleteGuildSettingsKarmaBlocklist)\n\n\tguild.\n\t\tGet(\"/settings\", ws.handlerGetGuildSettings).\n\t\tPost(ws.handlerPostGuildSettings)\n\n\tguildReports := guild.Group(\"/reports\")\n\tguildReports.\n\t\tGet(\"\", ws.handlerGetReports)\n\tguildReports.\n\t\tGet(\"/count\", ws.handlerGetReportsCount)\n\n\tguildBackups := guild.Group(\"/backups\")\n\tguildBackups.\n\t\tGet(\"\", ws.handlerGetGuildBackups)\n\tguildBackups.\n\t\tPost(\"/toggle\", ws.handlerPostGuildBackupsToggle)\n\tguildBackups.\n\t\tGet(\"/<backupid:[0-9]+>/download\", ws.handlerGetGuildBackupDownload)\n\n\tmember := guilds.Group(\"/<guildid:[0-9]+>/<memberid:[0-9]+>\")\n\tmember.\n\t\tGet(\"\", ws.handlerGuildsGetMember)\n\tmember.\n\t\tGet(\"/permissions\", ws.handlerGetMemberPermissions)\n\tmember.\n\t\tGet(\"/permissions/allowed\", ws.handlerGetMemberPermissionsAllowed)\n\tmember.\n\t\tPost(\"/kick\", ws.handlerPostGuildMemberKick)\n\tmember.\n\t\tPost(\"/ban\", ws.handlerPostGuildMemberBan)\n\tmember.\n\t\tPost(\"/mute\", ws.handlerPostGuildMemberMute)\n\tmember.\n\t\tPost(\"/unmute\", ws.handlerPostGuildMemberUnmute)\n\tmember.\n\t\tGet(\"/unbanrequests\", ws.handlerGetGuildMemberUnbanrequests)\n\n\tmemberReports := member.Group(\"/reports\")\n\tmemberReports.\n\t\tGet(\"\", ws.handlerGetReports).\n\t\tPost(ws.handlerPostGuildMemberReport)\n\tmemberReports.\n\t\tGet(\"/count\", ws.handlerGetReportsCount)\n\n\treports := api.Group(\"/reports\")\n\treport := reports.Group(\"/<id:[0-9]+>\")\n\treport.\n\t\tGet(\"\", ws.handlerGetReport)\n\treport.\n\t\tPost(\"/revoke\", ws.handlerPostReportRevoke)\n\n\tunbanReqeusts := api.Group(\"/unbanrequests\")\n\tunbanReqeusts.\n\t\tGet(\"\", ws.handlerGetUnbanrequest).\n\t\tPost(ws.handlerPostUnbanrequest)\n\tunbanReqeusts.\n\t\tGet(\"/bannedguilds\", ws.handlerGetUnbanrequestBannedguilds)\n\n\tapi.\n\t\tGet(\"/token\", ws.handlerGetToken).\n\t\tPost(ws.handlerPostToken).\n\t\tDelete(ws.handlerDeleteToken)\n\n\tusersettings := api.Group(\"/usersettings\")\n\tusersettings.\n\t\tGet(\"/ota\", ws.handlerGetUsersettingsOta).\n\t\tPost(ws.handlerPostUsersettingsOta)\n}",
"func (h *Handlers) SetupRoutes(mux *mux.Router) {\n\tmux.HandleFunc(\"/api/product-categories/new\", productCategoryHandlerLogging.Httplog((auth.ValidateToken(h.handleAddProductCategory, authServer)))).Methods(\"POST\")\n\tmux.HandleFunc(\"/api/product-categories\", productCategoryHandlerLogging.Httplog((auth.ValidateToken(h.handleGetProductCategory, authServer)))).Methods(\"GET\")\n\tmux.HandleFunc(\"/api/product-categories/{id}\", productCategoryHandlerLogging.Httplog((auth.ValidateToken(h.handleUpdateProductCategory, authServer)))).Methods(\"PUT\")\n\tmux.HandleFunc(\"/api/product-categories/{id}\", productCategoryHandlerLogging.Httplog((auth.ValidateToken(h.handleDeleteProductCategory, authServer)))).Methods(\"DELETE\")\n}",
"func (s *Server) configureRoutes() {\n\tif !s.authDisabled {\n\t\ts.Routes.AddOrUpdateConfigItem.Use(s.Routes.AddOrUpdateConfigItem.Auth)\n\t\ts.Routes.CreateCluster.Use(s.Routes.CreateCluster.Auth)\n\t\ts.Routes.CreateInfrastructureAccount.Use(s.Routes.CreateInfrastructureAccount.Auth)\n\t\ts.Routes.CreateOrUpdateNodePool.Use(s.Routes.CreateOrUpdateNodePool.Auth)\n\t\ts.Routes.DeleteCluster.Use(s.Routes.DeleteCluster.Auth)\n\t\ts.Routes.DeleteConfigItem.Use(s.Routes.DeleteConfigItem.Auth)\n\t\ts.Routes.DeleteNodePool.Use(s.Routes.DeleteNodePool.Auth)\n\t\ts.Routes.GetCluster.Use(s.Routes.GetCluster.Auth)\n\t\ts.Routes.GetInfrastructureAccount.Use(s.Routes.GetInfrastructureAccount.Auth)\n\t\ts.Routes.ListClusters.Use(s.Routes.ListClusters.Auth)\n\t\ts.Routes.ListInfrastructureAccounts.Use(s.Routes.ListInfrastructureAccounts.Auth)\n\t\ts.Routes.ListNodePools.Use(s.Routes.ListNodePools.Auth)\n\t\ts.Routes.UpdateCluster.Use(s.Routes.UpdateCluster.Auth)\n\t\ts.Routes.UpdateInfrastructureAccount.Use(s.Routes.UpdateInfrastructureAccount.Auth)\n\t}\n\n\t// setup all service routes after the authenticate middleware has been\n\t// initialized.\n\ts.Routes.AddOrUpdateConfigItem.PUT(ginizePath(\"/kubernetes-clusters/{cluster_id}/config-items/{config_key}\"), config_items.AddOrUpdateConfigItemEndpoint(s.service.AddOrUpdateConfigItem))\n\ts.Routes.CreateCluster.POST(ginizePath(\"/kubernetes-clusters\"), clusters.CreateClusterEndpoint(s.service.CreateCluster))\n\ts.Routes.CreateInfrastructureAccount.POST(ginizePath(\"/infrastructure-accounts\"), infrastructure_accounts.CreateInfrastructureAccountEndpoint(s.service.CreateInfrastructureAccount))\n\ts.Routes.CreateOrUpdateNodePool.PUT(ginizePath(\"/kubernetes-clusters/{cluster_id}/node-pools/{node_pool_name}\"), node_pools.CreateOrUpdateNodePoolEndpoint(s.service.CreateOrUpdateNodePool))\n\ts.Routes.DeleteCluster.DELETE(ginizePath(\"/kubernetes-clusters/{cluster_id}\"), clusters.DeleteClusterEndpoint(s.service.DeleteCluster))\n\ts.Routes.DeleteConfigItem.DELETE(ginizePath(\"/kubernetes-clusters/{cluster_id}/config-items/{config_key}\"), config_items.DeleteConfigItemEndpoint(s.service.DeleteConfigItem))\n\ts.Routes.DeleteNodePool.DELETE(ginizePath(\"/kubernetes-clusters/{cluster_id}/node-pools/{node_pool_name}\"), node_pools.DeleteNodePoolEndpoint(s.service.DeleteNodePool))\n\ts.Routes.GetCluster.GET(ginizePath(\"/kubernetes-clusters/{cluster_id}\"), clusters.GetClusterEndpoint(s.service.GetCluster))\n\ts.Routes.GetInfrastructureAccount.GET(ginizePath(\"/infrastructure-accounts/{account_id}\"), infrastructure_accounts.GetInfrastructureAccountEndpoint(s.service.GetInfrastructureAccount))\n\ts.Routes.ListClusters.GET(ginizePath(\"/kubernetes-clusters\"), clusters.ListClustersEndpoint(s.service.ListClusters))\n\ts.Routes.ListInfrastructureAccounts.GET(ginizePath(\"/infrastructure-accounts\"), infrastructure_accounts.ListInfrastructureAccountsEndpoint(s.service.ListInfrastructureAccounts))\n\ts.Routes.ListNodePools.GET(ginizePath(\"/kubernetes-clusters/{cluster_id}/node-pools\"), node_pools.ListNodePoolsEndpoint(s.service.ListNodePools))\n\ts.Routes.UpdateCluster.PATCH(ginizePath(\"/kubernetes-clusters/{cluster_id}\"), clusters.UpdateClusterEndpoint(s.service.UpdateCluster))\n\ts.Routes.UpdateInfrastructureAccount.PATCH(ginizePath(\"/infrastructure-accounts/{account_id}\"), infrastructure_accounts.UpdateInfrastructureAccountEndpoint(s.service.UpdateInfrastructureAccount))\n}",
"func Setup(ctx context.Context, r *mux.Router, cfg *config.Config, hc health.HealthCheck) {\n\tlog.Event(ctx, \"adding routes\")\n\tr.StrictSlash(true).Path(\"/health\").HandlerFunc(hc.Handler)\n\tr.StrictSlash(true).Path(\"/helloworld\").Methods(\"GET\").HandlerFunc(handlers.HelloWorld(*cfg))\n}",
"func setupConfig(config map[string]interface{}) {\n\tfor key, value := range config {\n\t\tviper.Set(key, value)\n\t}\n\tif !viper.GetBool(\"Debug\") {\n\t\tgin.SetMode(gin.ReleaseMode)\n\t}\n\tlogging.Initialize()\n\tlog = logging.GetLogger(\"init\")\n}",
"func (s *Server) ConfigHandler(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase http.MethodPost:\n\t\t// copy current config, this allows for setting only a subset of the whole config\n\t\tvar cfg regenbox.Config = s.Regenbox.Config()\n\t\terr := json.NewDecoder(r.Body).Decode(&cfg)\n\t\tif err != nil {\n\t\t\tlog.Println(\"error decoding json:\", err)\n\t\t\thttp.Error(w, \"couldn't decode provided json\", http.StatusUnprocessableEntity)\n\t\t\treturn\n\t\t}\n\n\t\tif !s.Regenbox.Stopped() {\n\t\t\thttp.Error(w, \"regenbox must be stopped first\", http.StatusNotAcceptable)\n\t\t\treturn\n\t\t}\n\t\terr = s.Regenbox.SetConfig(&cfg)\n\t\tif err != nil {\n\t\t\tlog.Println(\"error setting config:\", err)\n\t\t\thttp.Error(w, \"error setting config (internal)\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\t// save newly set config - todo ? huston we have design issues\n\t\t//err = util.WriteTomlFile(cfg, s.cfg)\n\t\t//if err != nil {\n\t\t//\tlog.Println(\"error writing config:\", err)\n\t\t//}\n\t\tbreak\n\tcase http.MethodGet:\n\t\tbreak\n\tdefault:\n\t\thttp.Error(w, fmt.Sprintf(\"unexpected http-method (%s)\", r.Method), http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\t// encode regenbox config regardless of http method\n\tw.WriteHeader(200)\n\t_ = json.NewEncoder(w).Encode(s.Regenbox.Config())\n\treturn\n}",
"func GetHandleConfig(actions chan Action, responses chan ActionResponse) http.HandlerFunc {\n\t// I return the handler, decorated with the list of endpoints\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t// I get the agent name from the query...\n\t\tvars := mux.Vars(r)\n\t\tagentName := vars[\"agentName\"]\n\t\t// ... and I add a new action to process\n\t\tactions <- Action{\n\t\t\tType: ActionConfig,\n\t\t\tPayload: agentName,\n\t\t}\n\t\t// I get the response and I return it\n\t\twriteActionResponse(w, <-responses)\n\t}\n}",
"func ListenAndServeConfig(c *Config) error {\r\n\twg := sync.WaitGroup{}\r\n\r\n\t// Initializing the pool before hand in case one server\r\n\t// Gets a request as soon as it's served\r\n\tpoolSize := 0\r\n\tfor _, s := range c.Servers {\r\n\t\tfor _, ser := range s.Services {\r\n\t\t\tif ser.MaxCon == 0 {\r\n\t\t\t\tpoolSize += defaultProxyPoolCapacity\r\n\t\t\t} else {\r\n\t\t\t\tpoolSize += ser.MaxCon\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tlogDebug(\"Pool size is\", poolSize)\r\n\tproxyPool = NewProxyPool(poolSize)\r\n\r\n\twg.Add(len(c.Servers))\r\n\tfor _, s := range c.Servers {\r\n\t\tp, err := NewPylon(&s)\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t\thealthRoute := defaultHealthRoute\r\n\t\tif s.HealthRoute != \"\" {\r\n\t\t\thealthRoute = s.HealthRoute\r\n\t\t}\r\n\t\tgo func() {\r\n\t\t\tdefer wg.Done()\r\n\t\t\tserve(p, s.Port, healthRoute)\r\n\t\t}()\r\n\t}\r\n\twg.Wait()\r\n\treturn nil\r\n}",
"func SetUpRouteHandlers() *mux.Router {\n\trouter := mux.NewRouter()\n\trouter.Handle(\"/metrics\", promhttp.Handler())\n\trouter.HandleFunc(\"/snippets\", GetSnippetsEndpoint).Methods(\"GET\")\n\trouter.HandleFunc(\"/snippet/{id}\", GetSnippetEndpoint).Methods(\"GET\")\n\trouter.HandleFunc(\"/snippet/\", CreateSnippetEndpoint).Methods(\"POST\")\n\trouter.HandleFunc(\"/snippet/{id}\", DeleteSnippetEndpoint).Methods(\"DELETE\")\n\trouter.HandleFunc(\"/status\", StatusHandler).Methods(\"GET\")\n\treturn router\n}",
"func SetupRoutes(apiBasePath string) {\n\thandleProducts := http.HandlerFunc(productsHandler)\n\thandleProduct := http.HandlerFunc(productHandler)\n\thttp.Handle(\"/websocket\",websocket.Handler(productSocket))\n\thttp.Handle(fmt.Sprintf(\"%s/%s\", apiBasePath, productsBasePath), cors.MiddlewareHandler(handleProducts))\n\thttp.Handle(fmt.Sprintf(\"%s/%s/\", apiBasePath, productsBasePath), cors.MiddlewareHandler(handleProduct))\n\n}",
"func InitHandlers() {\n\thttp.HandleFunc(routes.DedupURI, loghttp.Adapter(dedupHTTP))\n}",
"func (s *Server) registerHandlers() {\n\ts.mux.Use(s.cors, s.middleware)\n\ts.registerHandler(newCAInfoEndpoint(s))\n\ts.registerHandler(newRegisterEndpoint(s))\n\ts.registerHandler(newEnrollEndpoint(s))\n\ts.registerHandler(newIdemixEnrollEndpoint(s))\n\ts.registerHandler(newIdemixCRIEndpoint(s))\n\ts.registerHandler(newReenrollEndpoint(s))\n\ts.registerHandler(newRevokeEndpoint(s))\n\ts.registerHandler(newGenCRLEndpoint(s))\n\ts.registerHandler(newIdentitiesStreamingEndpoint(s))\n\ts.registerHandler(newIdentitiesEndpoint(s))\n\ts.registerHandler(newAffiliationsStreamingEndpoint(s))\n\ts.registerHandler(newAffiliationsEndpoint(s))\n\ts.registerHandler(newCertificateEndpoint(s))\n}",
"func registerHandlers() Option {\n\treturn optionFunc(func(c *config) {\n\t\tmux := http.NewServeMux()\n\t\tfor pattern, h := range c.handlers {\n\t\t\tmux.Handle(pattern, h)\n\t\t}\n\t\tc.httpServer.Handler = mux\n\t})\n}",
"func SetHandlers(s *http.ServeMux) {\n\tnotificationRequestPool = &sync.Pool{\n\t\tNew: func() interface{} {\n\t\t\treturn new(sendManyRequest)\n\t\t},\n\t}\n\ts.HandleFunc(\"/json\", jsonHandler)\n\ts.HandleFunc(\"/send\", sendHandler)\n\ts.HandleFunc(\"/sendMany\", sendManyHandler)\n\ts.HandleFunc(\"/home\", homeHandler)\n\n}",
"func (a *Application) SetupPaths() {\n\tif config.Debug {\n\t\t// standard go profiling support\n\t\thttp2.RegisterPrefixHandler(\"/debug/pprof/\", http.HandlerFunc(pprof.Index))\n\t\thttp2.RegisterPrefixHandler(\"/debug/pprof/cmdline\", http.HandlerFunc(pprof.Cmdline))\n\t\thttp2.RegisterPrefixHandler(\"/debug/pprof/profile\", http.HandlerFunc(pprof.Profile))\n\t\thttp2.RegisterPrefixHandler(\"/debug/pprof/symbol\", http.HandlerFunc(pprof.Symbol))\n\t\thttp2.RegisterPrefixHandler(\"/debug/pprof/trace\", http.HandlerFunc(pprof.Trace))\n\t}\n\n\tif config.WebsocketMessengerPrefix != \"\" {\n\t\thttp2.RegisterPrefixHandler(config.WebsocketMessengerPrefix, http.HandlerFunc(WebsocketMessengerHandler))\n\t}\n}",
"func v2HandlersSetup(muxRouter *mux.Router,\n\tstate dockerstate.TaskEngineState,\n\tecsClient api.ECSClient,\n\tstatsEngine stats.Engine,\n\tcluster string,\n\tcredentialsManager credentials.Manager,\n\tauditLogger auditinterface.AuditLogger,\n\tavailabilityZone string,\n\tcontainerInstanceArn string) {\n\tmuxRouter.HandleFunc(tmdsv2.CredentialsPath, tmdsv2.CredentialsHandler(credentialsManager, auditLogger))\n\tmuxRouter.HandleFunc(v2.ContainerMetadataPath, v2.TaskContainerMetadataHandler(state, ecsClient, cluster, availabilityZone, containerInstanceArn, false))\n\tmuxRouter.HandleFunc(v2.TaskMetadataPath, v2.TaskContainerMetadataHandler(state, ecsClient, cluster, availabilityZone, containerInstanceArn, false))\n\tmuxRouter.HandleFunc(v2.TaskWithTagsMetadataPath, v2.TaskContainerMetadataHandler(state, ecsClient, cluster, availabilityZone, containerInstanceArn, true))\n\tmuxRouter.HandleFunc(v2.TaskMetadataPathWithSlash, v2.TaskContainerMetadataHandler(state, ecsClient, cluster, availabilityZone, containerInstanceArn, false))\n\tmuxRouter.HandleFunc(v2.TaskWithTagsMetadataPathWithSlash, v2.TaskContainerMetadataHandler(state, ecsClient, cluster, availabilityZone, containerInstanceArn, true))\n\tmuxRouter.HandleFunc(v2.ContainerStatsPath, v2.TaskContainerStatsHandler(state, statsEngine))\n\tmuxRouter.HandleFunc(v2.TaskStatsPath, v2.TaskContainerStatsHandler(state, statsEngine))\n\tmuxRouter.HandleFunc(v2.TaskStatsPathWithSlash, v2.TaskContainerStatsHandler(state, statsEngine))\n}",
"func RegisterSSConfigHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {\n\tclient := NewSSConfigClient(conn)\n\n\tmux.Handle(\"POST\", pattern_SSConfig_Test_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(ctx)\n\t\tdefer cancel()\n\t\tif cn, ok := w.(http.CloseNotifier); ok {\n\t\t\tgo func(done <-chan struct{}, closed <-chan bool) {\n\t\t\t\tselect {\n\t\t\t\tcase <-done:\n\t\t\t\tcase <-closed:\n\t\t\t\t\tcancel()\n\t\t\t\t}\n\t\t\t}(ctx.Done(), cn.CloseNotify())\n\t\t}\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_SSConfig_Test_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_SSConfig_Test_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"POST\", pattern_SSConfig_GetSSConfig_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(ctx)\n\t\tdefer cancel()\n\t\tif cn, ok := w.(http.CloseNotifier); ok {\n\t\t\tgo func(done <-chan struct{}, closed <-chan bool) {\n\t\t\t\tselect {\n\t\t\t\tcase <-done:\n\t\t\t\tcase <-closed:\n\t\t\t\t\tcancel()\n\t\t\t\t}\n\t\t\t}(ctx.Done(), cn.CloseNotify())\n\t\t}\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_SSConfig_GetSSConfig_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_SSConfig_GetSSConfig_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"POST\", pattern_SSConfig_GetSSLineList_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(ctx)\n\t\tdefer cancel()\n\t\tif cn, ok := w.(http.CloseNotifier); ok {\n\t\t\tgo func(done <-chan struct{}, closed <-chan bool) {\n\t\t\t\tselect {\n\t\t\t\tcase <-done:\n\t\t\t\tcase <-closed:\n\t\t\t\t\tcancel()\n\t\t\t\t}\n\t\t\t}(ctx.Done(), cn.CloseNotify())\n\t\t}\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_SSConfig_GetSSLineList_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_SSConfig_GetSSLineList_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"POST\", pattern_SSConfig_GetSSLineConfig_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(ctx)\n\t\tdefer cancel()\n\t\tif cn, ok := w.(http.CloseNotifier); ok {\n\t\t\tgo func(done <-chan struct{}, closed <-chan bool) {\n\t\t\t\tselect {\n\t\t\t\tcase <-done:\n\t\t\t\tcase <-closed:\n\t\t\t\t\tcancel()\n\t\t\t\t}\n\t\t\t}(ctx.Done(), cn.CloseNotify())\n\t\t}\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_SSConfig_GetSSLineConfig_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_SSConfig_GetSSLineConfig_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"POST\", pattern_SSConfig_GetSSURL_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(ctx)\n\t\tdefer cancel()\n\t\tif cn, ok := w.(http.CloseNotifier); ok {\n\t\t\tgo func(done <-chan struct{}, closed <-chan bool) {\n\t\t\t\tselect {\n\t\t\t\tcase <-done:\n\t\t\t\tcase <-closed:\n\t\t\t\t\tcancel()\n\t\t\t\t}\n\t\t\t}(ctx.Done(), cn.CloseNotify())\n\t\t}\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_SSConfig_GetSSURL_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_SSConfig_GetSSURL_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\treturn nil\n}",
"func (api *APIServer) setupAPIServer(config Config) *http.Server {\n\tr := mux.NewRouter()\n\tr.Use(api.basicAuthMidleware)\n\tr.HandleFunc(\"/\", api.httpRootHandler).Methods(\"GET\")\n\n\tr.HandleFunc(\"/backup/tables\", api.httpTablesHandler).Methods(\"GET\")\n\tr.HandleFunc(\"/backup/list\", api.httpListHandler).Methods(\"GET\")\n\tr.HandleFunc(\"/backup/create\", api.httpCreateHandler).Methods(\"POST\")\n\tr.HandleFunc(\"/backup/clean\", api.httpCleanHandler).Methods(\"POST\")\n\tr.HandleFunc(\"/backup/freeze\", api.httpFreezeHandler).Methods(\"POST\")\n\tr.HandleFunc(\"/backup/upload/{name}\", api.httpUploadHandler).Methods(\"POST\")\n\tr.HandleFunc(\"/backup/download/{name}\", api.httpDownloadHandler).Methods(\"POST\")\n\tr.HandleFunc(\"/backup/restore/{name}\", api.httpRestoreHandler).Methods(\"POST\")\n\tr.HandleFunc(\"/backup/delete/{where}/{name}\", api.httpDeleteHandler).Methods(\"POST\")\n\tr.HandleFunc(\"/backup/config/default\", httpConfigDefaultHandler).Methods(\"GET\")\n\tr.HandleFunc(\"/backup/config\", api.httpConfigHandler).Methods(\"GET\")\n\tr.HandleFunc(\"/backup/config\", api.httpConfigUpdateHandler).Methods(\"POST\")\n\tr.HandleFunc(\"/backup/status\", api.httpBackupStatusHandler).Methods(\"GET\")\n\n\tr.HandleFunc(\"/integration/actions\", api.integrationBackupLog).Methods(\"GET\")\n\tr.HandleFunc(\"/integration/list\", api.httpListHandler).Methods(\"GET\")\n\n\tr.HandleFunc(\"/integration/actions\", api.integrationPost).Methods(\"POST\")\n\n\tvar routes []string\n\tr.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {\n\t\tt, err := route.GetPathTemplate()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\troutes = append(routes, t)\n\t\treturn nil\n\t})\n\tapi.routes = routes\n\tregisterMetricsHandlers(r, config.API.EnableMetrics, config.API.EnablePprof)\n\n\tsrv := &http.Server{\n\t\tAddr: config.API.ListenAddr,\n\t\tHandler: r,\n\t}\n\treturn srv\n}",
"func (h *Handlers) SetupRoutes(mux *http.ServeMux) {\n\tmux.HandleFunc(\"/\", h.Logger(h.Home))\n}",
"func RegisterConfigServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client ConfigServiceClient) error {\n\n\tmux.Handle(\"GET\", pattern_ConfigService_GetConfig_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_ConfigService_GetConfig_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_GetConfig_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"PUT\", pattern_ConfigService_SetConfig_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_ConfigService_SetConfig_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_SetConfig_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"GET\", pattern_ConfigService_GetToken_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_ConfigService_GetToken_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_GetToken_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"GET\", pattern_ConfigService_GetDefaultToken_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_ConfigService_GetDefaultToken_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_GetDefaultToken_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"POST\", pattern_ConfigService_CreateTokenType_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_ConfigService_CreateTokenType_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_CreateTokenType_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"GET\", pattern_ConfigService_GetTokenType_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_ConfigService_GetTokenType_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_GetTokenType_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"GET\", pattern_ConfigService_ListTokenTypes_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_ConfigService_ListTokenTypes_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_ListTokenTypes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"PUT\", pattern_ConfigService_UpdateTokenType_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_ConfigService_UpdateTokenType_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_UpdateTokenType_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"DELETE\", pattern_ConfigService_DeleteTokenType_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_ConfigService_DeleteTokenType_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_DeleteTokenType_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"GET\", pattern_ConfigService_GetTokenGroups_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_ConfigService_GetTokenGroups_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_GetTokenGroups_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"POST\", pattern_ConfigService_CreateTokenGroup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_ConfigService_CreateTokenGroup_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_CreateTokenGroup_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"GET\", pattern_ConfigService_GetTokenGroup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_ConfigService_GetTokenGroup_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_GetTokenGroup_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"DELETE\", pattern_ConfigService_DeleteTokenGroup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_ConfigService_DeleteTokenGroup_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_ConfigService_DeleteTokenGroup_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\treturn nil\n}",
"func GetConfigHandler(w http.ResponseWriter, r *http.Request) {\n\thttp.ServeFile(w, r, \"swagger.json\")\n}",
"func RegisterDebugConfigRoutes(dbgSrv *debug.Server, runtimeConfig *config.Config) {\n\tdbgSrv.Route(\"/config/list.{format:(json|yaml|text)}\", func(r *http.Request) (interface{}, error) {\n\t\tformat := debug.FormatFromRequest(r)\n\t\tif format == \"text\" {\n\t\t\treturn runtimeConfig.String(), nil\n\t\t}\n\t\treturn runtimeConfig.List(), nil\n\t})\n\n\tdbgSrv.RoutePOST(\"/config/set\", func(r *http.Request) (interface{}, error) {\n\t\tname := r.PostForm.Get(\"name\")\n\t\tif name == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"'name' parameter is required\")\n\t\t}\n\t\tif !runtimeConfig.Has(name) {\n\t\t\treturn nil, fmt.Errorf(\"unknown runtime parameter '%s'\", name)\n\t\t}\n\n\t\tvalue := r.PostForm.Get(\"value\")\n\t\tif name == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"'value' parameter is required\")\n\t\t}\n\n\t\tvar duration time.Duration\n\t\tvar err error\n\t\tdurationStr := r.PostForm.Get(\"duration\")\n\t\tif durationStr != \"\" {\n\t\t\tduration, err = time.ParseDuration(durationStr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"parse duration: %v\", err)\n\t\t\t}\n\t\t}\n\t\tif duration == 0 {\n\t\t\truntimeConfig.Set(name, value)\n\t\t} else {\n\t\t\truntimeConfig.SetTemporarily(name, value, duration)\n\t\t}\n\t\treturn nil, runtimeConfig.LastError(name)\n\t})\n}",
"func (a *API) SetHandlers(prefix string, rtr *mux.Router) {\n\n\ta.setHandlers(prefix+\"/v1\", rtr)\n\n\trtr.HandleFunc(\"/export/{userID}\", a.middleware(a.exportController.ExportData, true, \"userID\")).Methods(http.MethodGet)\n\n\t// v0 routes:\n\trtr.HandleFunc(\"/status\", a.getStatus).Methods(http.MethodGet)\n}",
"func (m *SDMock) SetupHandlers() {\n\theaders := make(map[string]string)\n\trawHeaders, err := os.ReadFile(filepath.Join(\"testdata\", m.directory, \"headers.yml\"))\n\trequire.NoError(m.t, err)\n\tyaml.Unmarshal(rawHeaders, &headers)\n\n\tprefix := \"/\"\n\tif v, ok := headers[\"Api-Version\"]; ok {\n\t\tprefix += \"v\" + v + \"/\"\n\t}\n\n\tfor _, path := range []string{\"_ping\", \"networks/\", \"services/\", \"nodes/\", \"nodes\", \"services\", \"tasks\", \"containers/\"} {\n\t\tp := path\n\t\thandler := prefix + p\n\t\tif p == \"_ping\" {\n\t\t\thandler = \"/\" + p\n\t\t}\n\t\tm.Mux.HandleFunc(handler, func(w http.ResponseWriter, r *http.Request) {\n\t\t\t// The discovery should only call each API endpoint once.\n\t\t\tm.calls[r.RequestURI]++\n\t\t\tif m.calls[r.RequestURI] != 1 {\n\t\t\t\tw.WriteHeader(http.StatusTooManyRequests)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor k, v := range headers {\n\t\t\t\tw.Header().Add(k, v)\n\t\t\t}\n\t\t\tparts := strings.Split(r.RequestURI, \"/\")\n\t\t\tvar f string\n\t\t\tif strings.HasSuffix(p, \"/\") {\n\t\t\t\tf = filepath.Join(p[:len(p)-1], strutil.SanitizeLabelName(parts[len(parts)-1]))\n\t\t\t} else {\n\t\t\t\tquery := strings.Split(parts[len(parts)-1], \"?\")\n\t\t\t\tf = query[0] + \".json\"\n\t\t\t\tif len(query) == 2 {\n\t\t\t\t\th := sha1.New()\n\t\t\t\t\th.Write([]byte(query[1]))\n\t\t\t\t\t// Avoing long filenames for Windows.\n\t\t\t\t\tf += \"__\" + base64.URLEncoding.EncodeToString(h.Sum(nil))[:10]\n\t\t\t\t}\n\t\t\t}\n\t\t\tif response, err := os.ReadFile(filepath.Join(\"testdata\", m.directory, f+\".json\")); err == nil {\n\t\t\t\tw.Header().Add(\"content-type\", \"application/json\")\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t\tw.Write(response)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif response, err := os.ReadFile(filepath.Join(\"testdata\", m.directory, f)); err == nil {\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t\tw.Write(response)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t})\n\t}\n}",
"func (h *HandlersApp01sqVendor) SetupHandlers(mux *http.ServeMux) {\n\n\tlog.Printf(\"\\thndlrVendor.SetupHandlers()\\n\")\n\n\tmux.HandleFunc(\"/Vendor/list/first\", h.ListFirst)\n\tmux.HandleFunc(\"/Vendor\", h.ListFirst)\n\tmux.HandleFunc(\"/Vendor/list/last\", h.ListLast)\n\tmux.HandleFunc(\"/Vendor/list/next\", h.ListNext)\n\tmux.HandleFunc(\"/Vendor/list/prev\", h.ListPrev)\n\tmux.HandleFunc(\"/Vendor/delete\", h.RowDelete)\n\tmux.HandleFunc(\"/Vendor/empty\", h.RowEmpty)\n\tmux.HandleFunc(\"/Vendor/find\", h.RowFind)\n\tmux.HandleFunc(\"/Vendor/first\", h.RowFirst)\n\tmux.HandleFunc(\"/Vendor/form\", h.RowForm)\n\tmux.HandleFunc(\"/Vendor/insert\", h.RowInsert)\n\tmux.HandleFunc(\"/Vendor/last\", h.RowLast)\n\tmux.HandleFunc(\"/Vendor/next\", h.RowNext)\n\tmux.HandleFunc(\"/Vendor/prev\", h.RowPrev)\n\tmux.HandleFunc(\"/Vendor/show\", h.RowShow)\n\tmux.HandleFunc(\"/Vendor/update\", h.RowUpdate)\n\tmux.HandleFunc(\"/Vendor/table/create\", h.TableCreate)\n\tmux.HandleFunc(\"/Vendor/table/load/csv\", h.TableLoadCSV)\n\tmux.HandleFunc(\"/Vendor/table/load/test\", h.TableLoadTestData)\n\tmux.HandleFunc(\"/Vendor/table/save/csv\", h.TableSaveCSV)\n\n\tlog.Printf(\"\\tend of hndlrVendor.SetupHandlers()\\n\")\n\n}",
"func SetConfig() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tc.Set(\"CorsOrigin\", \"*\")\n\t\tc.Set(\"Verbose\", true)\n\t\tc.Next()\n\t}\n}",
"func initApiHandlers(router *itineris.ApiRouter) {\n\trouter.SetHandler(\"pgsqlListDepartments\", apiListDepartments)\n\trouter.SetHandler(\"pgsqlCreateDepartment\", apiCreateDepartment)\n\trouter.SetHandler(\"pgsqlGetDepartment\", apiGetDepartment)\n\trouter.SetHandler(\"pgsqlUpdateDepartment\", apiUpdateDepartment)\n\trouter.SetHandler(\"pgsqlDeleteDepartment\", apiDeleteDepartment)\n}",
"func HandleSetEventingConfig(adminMan *admin.Manager, syncMan *syncman.Manager) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Get the JWT token from header\n\t\ttoken := utils.GetTokenFromHeader(r)\n\n\t\tvars := mux.Vars(r)\n\t\tprojectID := vars[\"project\"]\n\n\t\tdefer utils.CloseTheCloser(r.Body)\n\n\t\tctx, cancel := context.WithTimeout(r.Context(), time.Duration(utils.DefaultContextTime)*time.Second)\n\t\tdefer cancel()\n\n\t\t// Check if the request is authorised\n\t\treqParams, err := adminMan.IsTokenValid(ctx, token, \"eventing-config\", \"modify\", map[string]string{\"project\": projectID})\n\t\tif err != nil {\n\t\t\t_ = helpers.Response.SendErrorResponse(ctx, w, http.StatusUnauthorized, err)\n\t\t\treturn\n\t\t}\n\n\t\tc := new(config.Eventing)\n\t\t_ = json.NewDecoder(r.Body).Decode(c)\n\n\t\treqParams = utils.ExtractRequestParams(r, reqParams, c)\n\t\tstatus, err := syncMan.SetEventingConfig(ctx, projectID, c.DBAlias, c.Enabled, reqParams)\n\t\tif err != nil {\n\t\t\t_ = helpers.Response.SendErrorResponse(ctx, w, status, err)\n\t\t\treturn\n\t\t}\n\n\t\t_ = helpers.Response.SendOkayResponse(ctx, status, w)\n\t}\n}",
"func setupRoutes(srv *echo.Echo, s *controller) *echo.Echo {\n\n\tpingroute.NewRouter(s.pingController, srv).RegisterRoutes()\n\tuserroute.NewRouter(s.userController, srv).RegisterRoutes()\n\tuploadroute.NewRouter(s.uploadController, srv).RegisterRoutes()\n\thealthcheckroute.NewRouter(s.healthcheckController, srv).RegisterRoutes()\n\n\treturn srv\n}",
"func InitHandlers(e *echo.Echo) error {\n\t// Define prefix\n\tp := \"/api/\" + gaia.APIVersion + \"/\"\n\n\t// --- Register handlers at echo instance ---\n\n\t// Users\n\te.POST(p+\"login\", UserLogin)\n\te.GET(p+\"users\", UserGetAll)\n\te.POST(p+\"user/password\", UserChangePassword)\n\te.DELETE(p+\"user/:username\", UserDelete)\n\te.GET(p+\"user/:username/permissions\", UserGetPermissions)\n\te.PUT(p+\"user/:username/permissions\", UserPutPermissions)\n\te.POST(p+\"user\", UserAdd)\n\te.PUT(p+\"user/:username/reset-trigger-token\", UserResetTriggerToken)\n\n\tperms := e.Group(p + \"permission\")\n\tperms.GET(\"\", PermissionGetAll)\n\n\t// Pipelines\n\te.POST(p+\"pipeline\", CreatePipeline)\n\te.POST(p+\"pipeline/gitlsremote\", PipelineGitLSRemote)\n\te.GET(p+\"pipeline/name\", PipelineNameAvailable)\n\te.POST(p+\"pipeline/githook\", GitWebHook)\n\te.GET(p+\"pipeline/created\", CreatePipelineGetAll)\n\te.GET(p+\"pipeline\", PipelineGetAll)\n\te.GET(p+\"pipeline/:pipelineid\", PipelineGet)\n\te.PUT(p+\"pipeline/:pipelineid\", PipelineUpdate)\n\te.DELETE(p+\"pipeline/:pipelineid\", PipelineDelete)\n\te.POST(p+\"pipeline/:pipelineid/start\", PipelineStart)\n\te.POST(p+\"pipeline/:pipelineid/:pipelinetoken/trigger\", PipelineTrigger)\n\te.PUT(p+\"pipeline/:pipelineid/reset-trigger-token\", PipelineResetToken)\n\te.GET(p+\"pipeline/latest\", PipelineGetAllWithLatestRun)\n\te.POST(p+\"pipeline/periodicschedules\", PipelineCheckPeriodicSchedules)\n\n\t// Settings\n\te.POST(p+\"settings/poll/on\", SettingsPollOn)\n\te.POST(p+\"settings/poll/off\", SettingsPollOff)\n\te.GET(p+\"settings/poll\", SettingsPollGet)\n\n\t// PipelineRun\n\te.POST(p+\"pipelinerun/:pipelineid/:runid/stop\", PipelineStop)\n\te.GET(p+\"pipelinerun/:pipelineid/:runid\", PipelineRunGet)\n\te.GET(p+\"pipelinerun/:pipelineid\", PipelineGetAllRuns)\n\te.GET(p+\"pipelinerun/:pipelineid/latest\", PipelineGetLatestRun)\n\te.GET(p+\"pipelinerun/:pipelineid/:runid/log\", GetJobLogs)\n\n\t// Secrets\n\te.GET(p+\"secrets\", ListSecrets)\n\te.DELETE(p+\"secret/:key\", RemoveSecret)\n\te.POST(p+\"secret\", SetSecret)\n\te.PUT(p+\"secret/update\", SetSecret)\n\n\t// Worker\n\te.GET(p+\"worker/secret\", GetWorkerRegisterSecret)\n\te.POST(p+\"worker/register\", RegisterWorker)\n\te.GET(p+\"worker/status\", GetWorkerStatusOverview)\n\te.GET(p+\"worker\", GetWorker)\n\te.DELETE(p+\"worker/:workerid\", DeregisterWorker)\n\te.POST(p+\"worker/secret\", ResetWorkerRegisterSecret)\n\n\t// Middleware\n\te.Use(middleware.Recover())\n\t//e.Use(middleware.Logger())\n\te.Use(middleware.BodyLimit(\"32M\"))\n\te.Use(AuthMiddleware(&AuthConfig{\n\t\tRoleCategories: rolehelper.DefaultUserRoles,\n\t}))\n\n\t// Extra options\n\te.HideBanner = true\n\n\t// Are we in production mode?\n\tif !gaia.Cfg.DevMode {\n\t\tstaticAssets, err := rice.FindBox(\"../frontend/dist\")\n\t\tif err != nil {\n\t\t\tgaia.Cfg.Logger.Error(\"Cannot find assets in production mode.\")\n\t\t\treturn err\n\t\t}\n\n\t\t// Register handler for static assets\n\t\tassetHandler := http.FileServer(staticAssets.HTTPBox())\n\t\te.GET(\"/\", echo.WrapHandler(assetHandler))\n\t\te.GET(\"/favicon.ico\", echo.WrapHandler(assetHandler))\n\t\te.GET(\"/css/*\", echo.WrapHandler(http.StripPrefix(\"/\", assetHandler)))\n\t\te.GET(\"/js/*\", echo.WrapHandler(http.StripPrefix(\"/\", assetHandler)))\n\t\te.GET(\"/fonts/*\", echo.WrapHandler(http.StripPrefix(\"/\", assetHandler)))\n\t\te.GET(\"/img/*\", echo.WrapHandler(http.StripPrefix(\"/\", assetHandler)))\n\t}\n\n\t// Setup ignored vault keys which cannot be modified directly via the Vault API\n\tignoredVaultKeys = make([]string, 0, 1)\n\tignoredVaultKeys = append(ignoredVaultKeys, gaia.WorkerRegisterKey)\n\n\treturn nil\n}",
"func (s *GaiaHandler) InitHandlers(e *echo.Echo) error {\n\t// Define prefix\n\tp := \"/api/\" + gaia.APIVersion + \"/\"\n\n\t// --- Register handlers at echo instance ---\n\n\t// API router group.\n\tapiGrp := e.Group(p)\n\n\t// API router group with auth middleware.\n\tapiAuthGrp := e.Group(p, AuthMiddleware(&AuthConfig{\n\t\tRoleCategories: rolehelper.DefaultUserRoles,\n\t}))\n\n\t// Endpoints for Gaia primary instance\n\tif gaia.Cfg.Mode == gaia.ModeServer {\n\t\t// Users\n\t\tapiGrp.POST(\"login\", UserLogin)\n\n\t\tapiAuthGrp.GET(\"users\", UserGetAll)\n\t\tapiAuthGrp.POST(\"user/password\", UserChangePassword)\n\t\tapiAuthGrp.DELETE(\"user/:username\", UserDelete)\n\t\tapiAuthGrp.GET(\"user/:username/permissions\", UserGetPermissions)\n\t\tapiAuthGrp.PUT(\"user/:username/permissions\", UserPutPermissions)\n\t\tapiAuthGrp.POST(\"user\", UserAdd)\n\t\tapiAuthGrp.PUT(\"user/:username/reset-trigger-token\", UserResetTriggerToken)\n\n\t\tapiAuthGrp.GET(\"permission\", PermissionGetAll)\n\n\t\t// Pipelines\n\t\t// Create pipeline provider\n\t\tpipelineProvider := pipelines.NewPipelineProvider(pipelines.Dependencies{\n\t\t\tScheduler: s.deps.Scheduler,\n\t\t\tPipelineService: s.deps.PipelineService,\n\t\t})\n\t\tapiAuthGrp.POST(\"pipeline\", pipelineProvider.CreatePipeline)\n\t\tapiAuthGrp.POST(\"pipeline/gitlsremote\", pipelineProvider.PipelineGitLSRemote)\n\t\tapiAuthGrp.GET(\"pipeline/name\", pipelineProvider.PipelineNameAvailable)\n\t\tapiAuthGrp.GET(\"pipeline/created\", pipelineProvider.CreatePipelineGetAll)\n\t\tapiAuthGrp.GET(\"pipeline\", pipelineProvider.PipelineGetAll)\n\t\tapiAuthGrp.GET(\"pipeline/:pipelineid\", pipelineProvider.PipelineGet)\n\t\tapiAuthGrp.PUT(\"pipeline/:pipelineid\", pipelineProvider.PipelineUpdate)\n\t\tapiAuthGrp.DELETE(\"pipeline/:pipelineid\", pipelineProvider.PipelineDelete)\n\t\tapiAuthGrp.POST(\"pipeline/:pipelineid/start\", pipelineProvider.PipelineStart)\n\t\tapiAuthGrp.PUT(\"pipeline/:pipelineid/reset-trigger-token\", pipelineProvider.PipelineResetToken)\n\t\tapiAuthGrp.GET(\"pipeline/latest\", pipelineProvider.PipelineGetAllWithLatestRun)\n\t\tapiAuthGrp.POST(\"pipeline/periodicschedules\", pipelineProvider.PipelineCheckPeriodicSchedules)\n\t\tapiGrp.POST(\"pipeline/githook\", GitWebHook)\n\t\tapiGrp.POST(\"pipeline/:pipelineid/:pipelinetoken/trigger\", pipelineProvider.PipelineTrigger)\n\n\t\t// Settings\n\t\tapiAuthGrp.POST(\"settings/poll/on\", SettingsPollOn)\n\t\tapiAuthGrp.POST(\"settings/poll/off\", SettingsPollOff)\n\t\tapiAuthGrp.GET(\"settings/poll\", SettingsPollGet)\n\n\t\t// PipelineRun\n\t\tapiAuthGrp.POST(\"pipelinerun/:pipelineid/:runid/stop\", pipelineProvider.PipelineStop)\n\t\tapiAuthGrp.GET(\"pipelinerun/:pipelineid/:runid\", pipelineProvider.PipelineRunGet)\n\t\tapiAuthGrp.GET(\"pipelinerun/:pipelineid\", pipelineProvider.PipelineGetAllRuns)\n\t\tapiAuthGrp.GET(\"pipelinerun/:pipelineid/latest\", pipelineProvider.PipelineGetLatestRun)\n\t\tapiAuthGrp.GET(\"pipelinerun/:pipelineid/:runid/log\", pipelineProvider.GetJobLogs)\n\n\t\t// Secrets\n\t\tapiAuthGrp.GET(\"secrets\", ListSecrets)\n\t\tapiAuthGrp.DELETE(\"secret/:key\", RemoveSecret)\n\t\tapiAuthGrp.POST(\"secret\", SetSecret)\n\t\tapiAuthGrp.PUT(\"secret/update\", SetSecret)\n\t}\n\n\t// Worker\n\t// initialize the worker provider\n\tworkerProvider := workers.NewWorkerProvider(workers.Dependencies{\n\t\tScheduler: s.deps.Scheduler,\n\t\tCertificate: s.deps.Certificate,\n\t})\n\tapiAuthGrp.GET(\"worker/secret\", workerProvider.GetWorkerRegisterSecret)\n\tapiAuthGrp.GET(\"worker/status\", workerProvider.GetWorkerStatusOverview)\n\tapiAuthGrp.GET(\"worker\", workerProvider.GetWorker)\n\tapiAuthGrp.DELETE(\"worker/:workerid\", workerProvider.DeregisterWorker)\n\tapiAuthGrp.POST(\"worker/secret\", workerProvider.ResetWorkerRegisterSecret)\n\tapiGrp.POST(\"worker/register\", workerProvider.RegisterWorker)\n\n\t// Middleware\n\te.Use(middleware.Recover())\n\t// e.Use(middleware.Logger())\n\te.Use(middleware.BodyLimit(\"32M\"))\n\n\t// Extra options\n\te.HideBanner = true\n\n\t// Are we in production mode?\n\tif !gaia.Cfg.DevMode {\n\t\tstaticAssets, err := rice.FindBox(\"../frontend/dist\")\n\t\tif err != nil {\n\t\t\tgaia.Cfg.Logger.Error(\"Cannot find assets in production mode.\")\n\t\t\treturn err\n\t\t}\n\n\t\t// Register handler for static assets\n\t\tassetHandler := http.FileServer(staticAssets.HTTPBox())\n\t\te.GET(\"/\", echo.WrapHandler(assetHandler))\n\t\te.GET(\"/favicon.ico\", echo.WrapHandler(assetHandler))\n\t\te.GET(\"/css/*\", echo.WrapHandler(http.StripPrefix(\"/\", assetHandler)))\n\t\te.GET(\"/js/*\", echo.WrapHandler(http.StripPrefix(\"/\", assetHandler)))\n\t\te.GET(\"/fonts/*\", echo.WrapHandler(http.StripPrefix(\"/\", assetHandler)))\n\t\te.GET(\"/img/*\", echo.WrapHandler(http.StripPrefix(\"/\", assetHandler)))\n\t}\n\n\t// Setup ignored vault keys which cannot be modified directly via the Vault API\n\tignoredVaultKeys = make([]string, 0, 1)\n\tignoredVaultKeys = append(ignoredVaultKeys, gaia.WorkerRegisterKey)\n\n\treturn nil\n}",
"func SetupRoutes(apiBasePath string) {\n\tusersHandler := http.HandlerFunc(handleUsers)\n\tuserHandler := http.HandlerFunc(handleUser)\n\thttp.Handle(fmt.Sprintf(\"%s/%s\", apiBasePath, userPath), cors.Middleware(usersHandler))\n\thttp.Handle(fmt.Sprintf(\"%s/%s/\", apiBasePath, userPath), cors.Middleware(userHandler))\n}",
"func (h *Handler) SetHandlers() {\n\th.Router.GET(\"/\", func(c echo.Context) error {\n\t\treturn c.String(http.StatusOK, \"DUSS ka dum!\")\n\t})\n\n\th.Router.GET(\"/:shortUrl\", func(c echo.Context) error {\n\t\treturn getLongURL(h, c)\n\t})\n\n\th.Router.POST(\"/shorten\", func(c echo.Context) error {\n\t\treturn cutShort(h, c)\n\t})\n}",
"func ConfigRouter() http.Handler {\r\n\tr := chi.NewRouter()\r\n\tr.Use(CORSMiddleware())\r\n\r\n\tr.Get(\"/\", handleGetConfig)\r\n\tr.Put(\"/\", handleEditConfig)\r\n\r\n\treturn r\r\n}",
"func SetupRoutesWithMiddlewares(r *mux.Router) *mux.Router {\n\tfor _, route := range Load() {\n\t\tif route.AuthRequired {\n\t\t\tr.HandleFunc(route.URI,\n\t\t\t\tmiddlewares.SetMiddlewareLogger(\n\t\t\t\t\tmiddlewares.SetMiddlewareJSON(\n\t\t\t\t\t\tmiddlewares.SetMiddlewareAuthentication(route.Handler),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t).Methods(route.Method)\n\t\t} else {\n\t\t\tr.HandleFunc(route.URI,\n\t\t\t\tmiddlewares.SetMiddlewareLogger(\n\t\t\t\t\tmiddlewares.SetMiddlewareJSON(route.Handler),\n\t\t\t\t),\n\t\t\t).Methods(route.Method)\n\t\t}\n\t}\n\n\treturn r\n}",
"func (api *API) setupRoutes() error {\n\tvar (\n\t\tconnLimit int\n\t\terr error\n\t)\n\tif api.cfg.API.Connection.Limit == \"\" {\n\t\tconnLimit = 50\n\t} else {\n\t\t// setup the connection limit\n\t\tconnLimit, err = strconv.Atoi(api.cfg.API.Connection.Limit)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// ensure we have valid cors configuration, otherwise default to allow all\n\tvar allowedOrigins []string\n\tif len(api.cfg.API.Connection.CORS.AllowedOrigins) > 0 {\n\t\tallowedOrigins = api.cfg.API.Connection.CORS.AllowedOrigins\n\t}\n\t// set up defaults\n\tapi.r.Use(\n\t\t// allows for automatic xss removal\n\t\t// greater than what can be configured with HTTP Headers\n\t\txssMdlwr.RemoveXss(),\n\t\t// rate limiting\n\t\tlimit.MaxAllowed(connLimit),\n\t\t// security middleware\n\t\tmiddleware.NewSecWare(dev),\n\t\t// cors middleware\n\t\tmiddleware.CORSMiddleware(dev, allowedOrigins),\n\t\t// request id middleware\n\t\tmiddleware.RequestID(),\n\t\t// stats middleware\n\t\tstats.RequestStats())\n\n\t// set up middleware\n\tginjwt := middleware.JwtConfigGenerate(api.cfg.JWT.Key, api.cfg.JWT.Realm, api.dbm.DB, api.l)\n\tauthware := []gin.HandlerFunc{ginjwt.MiddlewareFunc()}\n\n\t// V2 API\n\tv2 := api.r.Group(\"/v2\")\n\n\t// system checks used to verify the integrity of our services\n\tsystemChecks := v2.Group(\"/systems\")\n\t{\n\t\tsystemChecks.GET(\"/check\", api.SystemsCheck)\n\t}\n\n\t// authless account recovery routes\n\tforgot := v2.Group(\"/forgot\")\n\t{\n\t\tforgot.POST(\"/username\", api.forgotUserName)\n\t\tforgot.POST(\"/password\", api.resetPassword)\n\t}\n\n\t// authentication\n\tauth := v2.Group(\"/auth\")\n\t{\n\t\tauth.POST(\"/register\", api.registerUserAccount)\n\t\tauth.POST(\"/login\", ginjwt.LoginHandler)\n\t\tauth.GET(\"/refresh\", ginjwt.RefreshHandler)\n\t}\n\n\t// statistics\n\tstatistics := v2.Group(\"/statistics\").Use(authware...)\n\t{\n\t\tstatistics.GET(\"/stats\", api.getStats)\n\t}\n\n\t// lens search engine\n\tlens := v2.Group(\"/lens\")\n\t{\n\t\tlens.POST(\"/index\", api.submitIndexRequest)\n\t\t// only allow registered users to search\n\t\tlens.POST(\"/search\", api.submitSearchRequest)\n\t}\n\n\t// payments\n\tpayments := v2.Group(\"/payments\", authware...)\n\t{\n\t\tdash := payments.Group(\"/dash\")\n\t\t{\n\t\t\tdash.POST(\"/create\", api.CreateDashPayment)\n\t\t}\n\t\teth := payments.Group(\"/eth\")\n\t\t{\n\t\t\teth.POST(\"/request\", api.RequestSignedPaymentMessage)\n\t\t\teth.POST(\"/confirm\", api.ConfirmETHPayment)\n\t\t}\n\t\tbch := payments.Group(\"/bch\")\n\t\t{\n\t\t\tbch.POST(\"/create\", api.createBchPayment)\n\t\t\tbch.POST(\"/confirm\", api.confirmBchPayment)\n\t\t}\n\t\tstripe := payments.Group(\"/stripe\")\n\t\t{\n\t\t\tstripe.POST(\"/charge\", api.stripeCharge)\n\t\t}\n\t\tpayments.GET(\"/status/:number\", api.getPaymentStatus)\n\t}\n\n\t// accounts\n\taccount := v2.Group(\"/account\")\n\t{\n\t\ttoken := account.Group(\"/token\", authware...)\n\t\t{\n\t\t\ttoken.GET(\"/username\", api.getUserFromToken)\n\t\t}\n\t\tpassword := account.Group(\"/password\", authware...)\n\t\t{\n\t\t\tpassword.POST(\"/change\", api.changeAccountPassword)\n\t\t}\n\t\tkey := account.Group(\"/key\", authware...)\n\t\t{\n\t\t\tkey.GET(\"/export/:name\", api.exportKey)\n\t\t\tipfs := key.Group(\"/ipfs\")\n\t\t\t{\n\t\t\t\tipfs.GET(\"/get\", api.getIPFSKeyNamesForAuthUser)\n\t\t\t\tipfs.POST(\"/new\", api.createIPFSKey)\n\t\t\t}\n\t\t}\n\t\tcredits := account.Group(\"/credits\", authware...)\n\t\t{\n\t\t\tcredits.GET(\"/available\", api.getCredits)\n\t\t}\n\t\temail := account.Group(\"/email\")\n\t\t{\n\t\t\t// auth-less account email routes\n\t\t\ttoken := email.Group(\"/verify\")\n\t\t\t{\n\t\t\t\ttoken.GET(\"/:user/:token\", api.verifyEmailAddress)\n\t\t\t}\n\t\t\t// authenticatoin email routes\n\t\t\tauth := email.Use(authware...)\n\t\t\t{\n\t\t\t\tauth.POST(\"/forgot\", api.forgotEmail)\n\t\t\t}\n\t\t}\n\t\tauth := account.Use(authware...)\n\t\t{\n\t\t\t// used to upgrade account to light tier\n\t\t\tauth.POST(\"/upgrade\", api.upgradeAccount)\n\t\t\tauth.GET(\"/usage\", api.usageData)\n\t\t}\n\t}\n\n\t// ipfs routes\n\tipfs := v2.Group(\"/ipfs\", authware...)\n\t{\n\t\t// public ipfs routes\n\t\tpublic := ipfs.Group(\"/public\")\n\t\t{\n\t\t\t// pinning routes\n\t\t\tpin := public.Group(\"/pin\")\n\t\t\t{\n\t\t\t\tpin.POST(\"/:hash\", api.pinHashLocally)\n\t\t\t\tpin.POST(\"/:hash/extend\", api.extendPin)\n\t\t\t}\n\t\t\t// file upload routes\n\t\t\tfile := public.Group(\"/file\")\n\t\t\t{\n\t\t\t\tfile.POST(\"/add\", api.addFile)\n\t\t\t\tfile.POST(\"/add/directory\", api.uploadDirectory)\n\t\t\t}\n\t\t\t// pubsub routes\n\t\t\tpubsub := public.Group(\"/pubsub\")\n\t\t\t{\n\t\t\t\tpubsub.POST(\"/publish/:topic\", api.ipfsPubSubPublish)\n\t\t\t}\n\t\t\t// general routes\n\t\t\tpublic.GET(\"/stat/:hash\", api.getObjectStatForIpfs)\n\t\t\tpublic.GET(\"/dag/:hash\", api.getDagObject)\n\t\t}\n\n\t\t// private ipfs routes\n\t\tprivate := ipfs.Group(\"/private\")\n\t\t{\n\t\t\t// network management routes\n\t\t\tprivate.GET(\"/networks\", api.getAuthorizedPrivateNetworks)\n\t\t\tnetwork := private.Group(\"/network\")\n\t\t\t{\n\t\t\t\tusers := network.Group(\"/users\")\n\t\t\t\t{\n\t\t\t\t\tusers.DELETE(\"/remove\", api.removeUsersFromNetwork)\n\t\t\t\t\tusers.POST(\"/add\", api.addUsersToNetwork)\n\t\t\t\t}\n\t\t\t\towners := network.Group(\"/owners\")\n\t\t\t\t{\n\t\t\t\t\towners.POST(\"/add\", api.addOwnersToNetwork)\n\t\t\t\t}\n\t\t\t\tnetwork.GET(\"/:name\", api.getIPFSPrivateNetworkByName)\n\t\t\t\tnetwork.POST(\"/new\", api.createIPFSNetwork)\n\t\t\t\tnetwork.POST(\"/stop\", api.stopIPFSPrivateNetwork)\n\t\t\t\tnetwork.POST(\"/start\", api.startIPFSPrivateNetwork)\n\t\t\t\tnetwork.DELETE(\"/remove\", api.removeIPFSPrivateNetwork)\n\t\t\t}\n\t\t\t// pinning routes\n\t\t\tpin := private.Group(\"/pin\")\n\t\t\t{\n\t\t\t\tpin.POST(\"/:hash\", api.pinToHostedIPFSNetwork)\n\t\t\t\tpin.GET(\"/check/:hash/:networkName\", api.checkLocalNodeForPinForHostedIPFSNetwork)\n\t\t\t}\n\t\t\t// file upload routes\n\t\t\tfile := private.Group(\"/file\")\n\t\t\t{\n\t\t\t\tfile.POST(\"/add\", api.addFileToHostedIPFSNetwork)\n\t\t\t}\n\t\t\t// pubsub routes\n\t\t\tpubsub := private.Group(\"/pubsub\")\n\t\t\t{\n\t\t\t\tpubsub.POST(\"/publish/:topic\", api.ipfsPubSubPublishToHostedIPFSNetwork)\n\t\t\t}\n\t\t\t// object stat route\n\t\t\tprivate.GET(\"/stat/:hash/:networkName\", api.getObjectStatForIpfsForHostedIPFSNetwork)\n\t\t\t// general routes\n\t\t\tprivate.GET(\"/dag/:hash/:networkName\", api.getDagObjectForHostedIPFSNetwork)\n\t\t\tprivate.GET(\"/uploads/:networkName\", api.getUploadsByNetworkName)\n\t\t}\n\t\t// utility routes\n\t\tutils := ipfs.Group(\"/utils\")\n\t\t{\n\t\t\t// generic download\n\t\t\tutils.POST(\"/download/:hash\", api.downloadContentHash)\n\t\t\tlaser := utils.Group(\"/laser\")\n\t\t\t{\n\t\t\t\tlaser.POST(\"/beam\", api.beamContent)\n\t\t\t}\n\t\t}\n\t}\n\n\t// ipns\n\tipns := v2.Group(\"/ipns\", authware...)\n\t{\n\t\t// public ipns routes\n\t\tpublic := ipns.Group(\"/public\")\n\t\t{\n\t\t\tpublic.POST(\"/publish/details\", api.publishToIPNSDetails)\n\t\t\t// used to handle pinning of IPNS records on public ipfs\n\t\t\t// this involves first resolving the record, parsing it\n\t\t\t// and extracting the hash to pin\n\t\t\tpublic.POST(\"/pin\", api.pinIPNSHash)\n\t\t}\n\t\t// general routes\n\t\tipns.GET(\"/records\", api.getIPNSRecordsPublishedByUser)\n\t}\n\n\t// database\n\tdatabase := v2.Group(\"/database\", authware...)\n\t{\n\t\tdatabase.GET(\"/uploads\", api.getUploadsForUser)\n\t\tdatabase.GET(\"/uploads/encrypted\", api.getEncryptedUploadsForUser)\n\t}\n\n\t// frontend\n\tfrontend := v2.Group(\"/frontend\", authware...)\n\t{\n\t\tcost := frontend.Group(\"/cost\")\n\t\t{\n\t\t\tcalculate := cost.Group(\"/calculate\")\n\t\t\t{\n\t\t\t\tcalculate.GET(\"/:hash/:hold_time\", api.calculatePinCost)\n\t\t\t\tcalculate.POST(\"/file\", api.calculateFileCost)\n\t\t\t}\n\t\t}\n\t}\n\n\tapi.l.Info(\"Routes initialized\")\n\treturn nil\n}",
"func (a *API) RegisterRoutes(r *mux.Router) {\n\tfor _, route := range []struct {\n\t\tname, method, path string\n\t\thandler http.HandlerFunc\n\t}{\n\t\t{\"get_config\", \"GET\", \"/api/v1/config\", a.getConfig},\n\t\t{\"set_config\", \"POST\", \"/api/v1/config\", a.setConfig},\n\t\t{\"deactivate_config\", \"DELETE\", \"/api/v1/config/deactivate\", a.deactivateConfig},\n\t\t{\"restore_config\", \"POST\", \"/api/v1/config/restore\", a.restoreConfig},\n\t} {\n\t\tr.Handle(route.path, route.handler).Methods(route.method).Name(route.name)\n\t}\n}",
"func AddHandlers(r *mux.Router) {\n\t// GET hyperledger fabric status.\n\tr.HandleFunc(\"/fabric/status\", StatusHandler).Methods(http.MethodGet, http.MethodOptions)\n\n\t// POST hyperledger fabric channel.\n\tr.HandleFunc(\"/fabric/channel\", ChannelHandler).Methods(http.MethodPost, http.MethodOptions)\n\n}",
"func (srv *AppServer) SetupRoutes() error {\n\tvar err error\n\tsrv.routesSetup.Do(func() {\n\n\t\t// /status is something you should always have in any of your services,\n\t\t// please leave it as is.\n\t\tsrv.router.HandleFunc(\"/status\", srv.HandleStatus()).Queries(\"format\", \"{format:(?:json|yaml)}\").\n\t\t\tName(\"status\").\n\t\t\tMethods(\"GET\")\n\n\t\t// ADD YOUR OWN ROUTES HERE\n\t\tsrv.router.HandleFunc(\"/topology\", srv.HandleTopology()).\n\t\t\tName(\"topology\").\n\t\t\tMethods(\"GET\")\n\t})\n\treturn err\n}",
"func GetConfigHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tconfigName := ps.ByName(\"config\")\n\n\tconfiguration, err := ubus.UciGetConfig(uci.ConfigType(configName))\n\tif err != nil {\n\t\trend.JSON(w, http.StatusOK, map[string]string{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\trend.JSON(w, http.StatusOK, configuration)\n}",
"func RegisterAppConfigsHandlerServer(ctx context.Context, mux *runtime.ServeMux, server AppConfigsServer) error {\n\n\tmux.Handle(\"POST\", pattern_AppConfigs_Create_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_AppConfigs_Create_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_AppConfigs_Create_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"GET\", pattern_AppConfigs_Read_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_AppConfigs_Read_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_AppConfigs_Read_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"PUT\", pattern_AppConfigs_Update_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_AppConfigs_Update_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_AppConfigs_Update_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"PATCH\", pattern_AppConfigs_Update_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_AppConfigs_Update_1(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_AppConfigs_Update_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"DELETE\", pattern_AppConfigs_Delete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_AppConfigs_Delete_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_AppConfigs_Delete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"GET\", pattern_AppConfigs_List_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_AppConfigs_List_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_AppConfigs_List_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\treturn nil\n}",
"func (c *Operation) registerHandler() {\n\t// Add more protocol endpoints here to expose them as controller API endpoints\n\tc.handlers = []Handler{\n\t\tsupport.NewHTTPHandler(login, http.MethodGet, c.login),\n\t\tsupport.NewHTTPHandler(settings, http.MethodGet, c.settings),\n\t\tsupport.NewHTTPHandler(getCreditScore, http.MethodGet, c.getCreditScore),\n\t\tsupport.NewHTTPHandler(callback, http.MethodGet, c.callback),\n\t\tsupport.NewHTTPHandler(oidcRedirectPath, http.MethodGet, c.oidcRedirect),\n\n\t\t// issuer rest apis (html decoupled)\n\t\tsupport.NewHTTPHandler(authPath, http.MethodGet, c.auth),\n\t\tsupport.NewHTTPHandler(searchPath, http.MethodGet, c.search),\n\t\tsupport.NewHTTPHandler(verifyDIDAuthPath, http.MethodPost, c.verifyDIDAuthHandler),\n\t\tsupport.NewHTTPHandler(createCredentialPath, http.MethodPost, c.createCredentialHandler),\n\t\tsupport.NewHTTPHandler(generateCredentialPath, http.MethodPost, c.generateCredentialHandler),\n\n\t\t// chapi\n\t\tsupport.NewHTTPHandler(revoke, http.MethodPost, c.revokeVC),\n\t\tsupport.NewHTTPHandler(generate, http.MethodPost, c.generateVC),\n\n\t\t// didcomm\n\t\tsupport.NewHTTPHandler(didcommToken, http.MethodPost, c.didcommTokenHandler),\n\t\tsupport.NewHTTPHandler(didcommCallback, http.MethodGet, c.didcommCallbackHandler),\n\t\tsupport.NewHTTPHandler(didcommCredential, http.MethodPost, c.didcommCredentialHandler),\n\t\tsupport.NewHTTPHandler(didcommAssuranceData, http.MethodPost, c.didcommAssuraceHandler),\n\n\t\tsupport.NewHTTPHandler(didcommInit, http.MethodGet, c.initiateDIDCommConnection),\n\t\tsupport.NewHTTPHandler(didcommUserEndpoint, http.MethodGet, c.getIDHandler),\n\n\t\t// oidc\n\t\tsupport.NewHTTPHandler(oauth2GetRequestPath, http.MethodGet, c.createOIDCRequest),\n\t\tsupport.NewHTTPHandler(oauth2CallbackPath, http.MethodGet, c.handleOIDCCallback),\n\n\t\t// JSON-LD contexts API\n\t\tsupport.NewHTTPHandler(jsonldcontextrest.AddContextPath, http.MethodPost, c.addJSONLDContextHandler),\n\t}\n}",
"func (self *CentralBooking) InstallHandlers(router *mux.Router) {\n router.\n Methods(\"POST\").\n Path(\"/register/instance\").\n HandlerFunc(self.RegisterInstance)\n\n // apeing vault\n router.\n Methods(\"GET\").\n Path(\"/sys/health\").\n HandlerFunc(self.CheckHealth)\n}",
"func Setup(cfg *viper.Viper, svc *Services) *Handlers {\n\th := &Handlers{\n\t\tcfg: cfg,\n\t\tsvc: svc,\n\t\tmetrics: setupMetrics(),\n\t\tlogger: log.With().Str(\"handlers\", \"root\").Logger(),\n\n\t\tOrganizations: org.NewHandlers(svc.OrganizationManager),\n\t\tUsers: user.NewHandlers(svc.UserManager, cfg),\n\t\tPackages: pkg.NewHandlers(svc.PackageManager),\n\t\tChartRepositories: chartrepo.NewHandlers(svc.ChartRepositoryManager),\n\t\tStatic: static.NewHandlers(cfg, svc.ImageStore),\n\t}\n\th.setupRouter()\n\th.setupBotRouter()\n\treturn h\n}",
"func SetupRoutes() {\n\tplatformsHandler := http.HandlerFunc(handlePlatforms)\n\n\thttp.Handle(\"/platforms\", platformsHandler)\n}",
"func v4HandlersSetup(muxRouter *mux.Router,\n\tstate dockerstate.TaskEngineState,\n\tecsClient api.ECSClient,\n\tstatsEngine stats.Engine,\n\tcluster string,\n\tavailabilityZone string,\n\tvpcID string,\n\tcontainerInstanceArn string,\n\ttmdsAgentState *v4.TMDSAgentState,\n\tmetricsFactory metrics.EntryFactory,\n) {\n\tmuxRouter.HandleFunc(tmdsv4.ContainerMetadataPath(), tmdsv4.ContainerMetadataHandler(tmdsAgentState, metricsFactory))\n\tmuxRouter.HandleFunc(tmdsv4.TaskMetadataPath(), tmdsv4.TaskMetadataHandler(tmdsAgentState, metricsFactory))\n\tmuxRouter.HandleFunc(tmdsv4.TaskMetadataWithTagsPath(), tmdsv4.TaskMetadataWithTagsHandler(tmdsAgentState, metricsFactory))\n\tmuxRouter.HandleFunc(tmdsv4.ContainerStatsPath(), tmdsv4.ContainerStatsHandler(tmdsAgentState, metricsFactory))\n\tmuxRouter.HandleFunc(tmdsv4.TaskStatsPath(), tmdsv4.TaskStatsHandler(tmdsAgentState, metricsFactory))\n\tmuxRouter.HandleFunc(v4.ContainerAssociationsPath, v4.ContainerAssociationsHandler(state))\n\tmuxRouter.HandleFunc(v4.ContainerAssociationPathWithSlash, v4.ContainerAssociationHandler(state))\n\tmuxRouter.HandleFunc(v4.ContainerAssociationPath, v4.ContainerAssociationHandler(state))\n}",
"func ConfigureAndServe(initializer Intializer) {\n\tSetup()\n\n\tengine.configuration = &Configuration{}\n\tinitializer.Configure(engine.configuration)\n\n\tinitializer.RegisterAdapters(ModelManager())\n\tinitializer.RegisterCollections(ModelManager())\n\tinitializer.RegisterControllers(ControllerManager())\n\tinitializer.RegisterViews(ViewManager())\n\n\tinitializer.BeforeServe()\n\n\tControllerManager().Serve(engine.configuration.port, engine.configuration.httpHandler)\n}",
"func (a *App) setupRoutes() {\n\t// Adds a simple shared secret check\n\tauth := AddAuth(a.secretHash)\n\t// Adds logging\n\tlog := AddLog(a.Logger)\n\t// Adds self identity header\n\tself := AddIdentity(a.eventID)\n\t// Adds parent identity header\n\tparent := AddIdentity(a.parentEventID)\n\n\t// GET /meta\n\t// Returns all metadata currently stored as part of this chain\n\tgetMeta := http.HandlerFunc(a.GetAllMeta)\n\ta.Router.Handle(\"/meta\", log(auth(getMeta))).Methods(http.MethodGet)\n\n\t// GET /parent/meta\n\t// Returns only metadata stored by the parent of this module\n\tgetParentMeta := http.HandlerFunc(a.GetMetaByID)\n\ta.Router.Handle(\"/parent/meta\", log(auth(parent(getParentMeta)))).Methods(http.MethodGet)\n\n\t// PUT /self/meta\n\t// Stores metadata against this modules meta store\n\tupdateSelfMeta := http.HandlerFunc(a.UpdateMeta)\n\ta.Router.Handle(\"/self/meta\", log(auth(updateSelfMeta))).Methods(http.MethodPut)\n\n\t// GET /self/meta\n\t// Returns the metadata currently in this modules meta store\n\tgetSelfMeta := http.HandlerFunc(a.GetMetaByID)\n\ta.Router.Handle(\"/self/meta\", log(auth(self(getSelfMeta)))).Methods(http.MethodGet)\n\n\t// GET /parent/blob\n\t// Returns a named blob from the parent's blob store\n\tgetParentBlob := http.HandlerFunc(a.GetBlob)\n\ta.Router.Handle(\"/parent/blob\", log(auth(parent(getParentBlob)))).Methods(http.MethodGet)\n\n\t// GET /self/blob\n\t// Returns a named blob from this modules blob store\n\tgetSelfBlob := http.HandlerFunc(a.GetBlob)\n\ta.Router.Handle(\"/self/blob\", log(auth(self(getSelfBlob)))).Methods(http.MethodGet)\n\n\t// PUT /self/blob\n\t// Stores a blob in this modules blob store\n\taddSelfBlob := http.HandlerFunc(a.CreateBlob)\n\ta.Router.Handle(\"/self/blob\", log(auth(self(addSelfBlob)))).Methods(http.MethodPut)\n\n\t// DELETE /self/blob\n\t// Deletes a named blob from this modules blob store\n\tdeleteSelfBlobs := http.HandlerFunc(a.DeleteBlobs)\n\ta.Router.Handle(\"/self/blob\", log(auth(self(deleteSelfBlobs)))).Methods(http.MethodDelete)\n\n\t// GET /self/blobs\n\t// Returns a list of blobs currently stored in this modules blob store\n\tlistSelfBlobs := http.HandlerFunc(a.ListBlobs)\n\ta.Router.Handle(\"/self/blobs\", log(auth(self(listSelfBlobs)))).Methods(http.MethodGet)\n\n\t// POST /events\n\t// Publishes a new event to the messaging system\n\tpublishEventHandler := http.HandlerFunc(a.Publish)\n\ta.Router.Handle(\"/events\", log(auth(publishEventHandler))).Methods(http.MethodPost)\n}",
"func Config(r *mux.Router) *mux.Router {\n\troutes := accountRoutes\n\troutes = append(routes, loginRoute, transferRoutes[1], transferRoutes[0])\n\tfor _, route := range routes {\n\n\t\tif route.AuthRequired {\n\t\t\tr.HandleFunc(route.Url, middlewares.Logger(middlewares.Auth(route.Function))).Methods(route.Method)\n\t\t} else {\n\t\t\tr.HandleFunc(route.Url, route.Function).Methods(route.Method)\n\t\t}\n\t}\n\tfmt.Println(\"rotas configuradas\")\n\treturn r\n}",
"func (s *server) ScrapeConfigsHandler(w http.ResponseWriter, r *http.Request) {\n\tconfigs := s.discoveryManager.GetScrapeConfigs()\n\tconfigBytes, err := yaml2.Marshal(configs)\n\tif err != nil {\n\t\ts.errorHandler(w, err)\n\t}\n\tjsonConfig, err := yaml.YAMLToJSON(configBytes)\n\tif err != nil {\n\t\ts.errorHandler(w, err)\n\t}\n\t// We don't use the jsonHandler method because we don't want our bytes to be re-encoded\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t_, err = w.Write(jsonConfig)\n\tif err != nil {\n\t\ts.errorHandler(w, err)\n\t}\n}",
"func (server *WebServer) setupRoutes() {\n\n\t// Fetch credentials\n\tcredPath := path.Join(path.Dir(os.Args[0]), \"credentials.json\")\n\tcreds, err := parseCredsFile(credPath)\n\tif err != nil {\n\t\tlog.Printf(\"Unable to parse credentials file. %v\\n\", err)\n\t\treturn\n\t}\n\n\t// Setup routes\n\tserver.router = mux.NewRouter()\n\tauthMiddleware := basicAuth(creds)\n\tserver.router.Use(authMiddleware)\n\tserver.router.HandleFunc(\"/monitors\", server.handleGetMonitors)\n\tserver.router.HandleFunc(\"/ws/{address}/{screen}\", server.handleWebsocket)\n\t// server.router.HandleFunc(\"/monitors/{address}/{screen}\", server.handleScreenshot)\n\tserver.router.PathPrefix(\"/\").Handler(http.StripPrefix(\"/\", http.FileServer(http.Dir(\"./ui/build\"))))\n}",
"func IndexConfigHandler(cfg *config.ApiConfig) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t// TODO(toru): Write a middleware that does this.\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t\tif err := json.NewEncoder(w).Encode(cfg); err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\t}\n}",
"func configMiddleware(args map[string]interface{}) echo.MiddlewareFunc {\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\tfor k, v := range args {\n\t\t\t\tc.Set(k, v)\n\t\t\t}\n\t\t\treturn next(c)\n\t\t}\n\t}\n}",
"func SetupRoutes(app *fiber.App) {\n\t// AUTH route\n\tapp.Post(\"/api/v1/login\", handlers.Login)\n\tapp.Post(\"/api/v1/Register\", handlers.Register)\n\n\t// User route\n\tapp.Get(\"api/v1/users\", middlewares.Protected(), handlers.GetAllUsers)\n\tapp.Get(\"api/v1/user/:id\", middlewares.Protected(), handlers.GetUserByID)\n\tapp.Put(\"api/v1/user/:id\", middlewares.Protected(), handlers.UpdateUserByID)\n\tapp.Delete(\"api/v1/user/:id\", middlewares.Protected(), handlers.DeleteUserByID)\n}",
"func CreateEndpointHandlers(lbc *controller.LoadBalancerController) cache.ResourceEventHandlerFuncs {\n\treturn cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tendpoint := obj.(*api_v1.Endpoints)\n\t\t\tlog.Printf(\"Adding endpoints: %v\", endpoint.Name)\n\t\t\tlbc.AddSyncQueue(obj)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tendpoint, isEndpoint := obj.(*api_v1.Endpoints)\n\t\t\tif !isEndpoint {\n\t\t\t\tdeletedState, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\t\t\tif !ok {\n\t\t\t\t\tlog.Printf(\"Error received unexpected object: %v\", obj)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tendpoint, ok = deletedState.Obj.(*api_v1.Endpoints)\n\t\t\t\tif !ok {\n\t\t\t\t\tlog.Printf(\"Error DeletedFinalStateUnknown contained non-Endpoints object: %v\", deletedState.Obj)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tlog.Printf(\"Removing endpoints: %v\", endpoint.Name)\n\t\t\tlbc.AddSyncQueue(obj)\n\t\t},\n\t\tUpdateFunc: func(old, cur interface{}) {\n\t\t\tif !reflect.DeepEqual(old, cur) {\n\t\t\t\tlog.Printf(\"Endpoints %v changed, syncing\", cur.(*api_v1.Endpoints).Name)\n\t\t\t\tlbc.AddSyncQueue(cur)\n\t\t\t}\n\t\t},\n\t}\n}",
"func (srv *WebServer) setupMux() {\n\thttp.HandleFunc(\"/\", srv.logResponse(srv.handleStatus)) // GET.\n\thttp.HandleFunc(\"/vehiclestore/status\", srv.logResponse(srv.handleStoreStatus)) // GET.\n\thttp.HandleFunc(\"/lookup\", srv.logResponse(srv.handleLookup)) // GET.\n\thttp.HandleFunc(\"/vehicle\", srv.logResponse(srv.handleVehicle)) // PATCH.\n}",
"func RegisterConfigServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {\n\treturn RegisterConfigServiceHandlerClient(ctx, mux, NewConfigServiceClient(conn))\n}",
"func NewHandlers(cfg *Config) *Handlers {\n\thnd := &Handlers{}\n\thnd.cfg = cfg\n\n\treturn hnd\n}",
"func (h *HomeHandlers) SetupRoutes(mux *http.ServeMux) {\n\t// and now here we can call our middleware\n\tmux.HandleFunc(\"/\", h.Logger(h.home))\n}",
"func initHTTPHandlers() {\n\thttp.Handle(\"/\", handlerWrapper(handleMain))\n\thttp.Handle(\"/bug\", handlerWrapper(handleBug))\n\thttp.Handle(\"/text\", handlerWrapper(handleText))\n\thttp.Handle(\"/admin\", handlerWrapper(handleAdmin))\n\thttp.Handle(\"/x/.config\", handlerWrapper(handleTextX(textKernelConfig)))\n\thttp.Handle(\"/x/log.txt\", handlerWrapper(handleTextX(textCrashLog)))\n\thttp.Handle(\"/x/report.txt\", handlerWrapper(handleTextX(textCrashReport)))\n\thttp.Handle(\"/x/repro.syz\", handlerWrapper(handleTextX(textReproSyz)))\n\thttp.Handle(\"/x/repro.c\", handlerWrapper(handleTextX(textReproC)))\n\thttp.Handle(\"/x/patch.diff\", handlerWrapper(handleTextX(textPatch)))\n\thttp.Handle(\"/x/bisect.txt\", handlerWrapper(handleTextX(textLog)))\n\thttp.Handle(\"/x/error.txt\", handlerWrapper(handleTextX(textError)))\n\thttp.Handle(\"/x/minfo.txt\", handlerWrapper(handleTextX(textMachineInfo)))\n\tfor ns := range config.Namespaces {\n\t\thttp.Handle(\"/\"+ns, handlerWrapper(handleMain))\n\t\thttp.Handle(\"/\"+ns+\"/fixed\", handlerWrapper(handleFixed))\n\t\thttp.Handle(\"/\"+ns+\"/invalid\", handlerWrapper(handleInvalid))\n\t\thttp.Handle(\"/\"+ns+\"/graph/bugs\", handlerWrapper(handleKernelHealthGraph))\n\t\thttp.Handle(\"/\"+ns+\"/graph/lifetimes\", handlerWrapper(handleGraphLifetimes))\n\t\thttp.Handle(\"/\"+ns+\"/graph/fuzzing\", handlerWrapper(handleGraphFuzzing))\n\t\thttp.Handle(\"/\"+ns+\"/graph/crashes\", handlerWrapper(handleGraphCrashes))\n\t\thttp.Handle(\"/\"+ns+\"/repos\", handlerWrapper(handleRepos))\n\t\thttp.Handle(\"/\"+ns+\"/bug-stats\", handlerWrapper(handleBugStats))\n\t\thttp.Handle(\"/\"+ns+\"/subsystems\", handlerWrapper(handleSubsystemsList))\n\t\thttp.Handle(\"/\"+ns+\"/s/\", handlerWrapper(handleSubsystemPage))\n\t}\n\thttp.HandleFunc(\"/cron/cache_update\", cacheUpdate)\n\thttp.HandleFunc(\"/cron/deprecate_assets\", handleDeprecateAssets)\n\thttp.HandleFunc(\"/cron/refresh_subsystems\", handleRefreshSubsystems)\n\thttp.HandleFunc(\"/cron/subsystem_reports\", handleSubsystemReports)\n}",
"func (h *Handler) SetupRoutes() {\n\tfmt.Println(\"Setting up routes.\")\n\th.Router = mux.NewRouter()\n\n\th.Router.HandleFunc(\"/api/comment\", h.GetAllComments).Methods(\"GET\")\n\th.Router.HandleFunc(\"/api/comment\", h.PostComment).Methods(\"POST\")\n\th.Router.HandleFunc(\"/api/comment/{id}\", h.GetComment).Methods(\"GET\")\n\th.Router.HandleFunc(\"/api/comment/{id}\", h.DeleteComment).Methods(\"DELETE\")\n\th.Router.HandleFunc(\"/api/comment/{id}\", h.UpdateComment).Methods(\"PUT\")\n\n\th.Router.HandleFunc(\"/api/health\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintf(w, \"OK\")\n\t})\n}",
"func HandleGetEventingConfig(adminMan *admin.Manager, syncMan *syncman.Manager) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Get the JWT token from header\n\t\ttoken := utils.GetTokenFromHeader(r)\n\n\t\t// get project id from url\n\t\tvars := mux.Vars(r)\n\t\tprojectID := vars[\"project\"]\n\n\t\tctx, cancel := context.WithTimeout(r.Context(), time.Duration(utils.DefaultContextTime)*time.Second)\n\t\tdefer cancel()\n\n\t\t// Check if the request is authorised\n\t\treqParams, err := adminMan.IsTokenValid(ctx, token, \"eventing-config\", \"read\", map[string]string{\"project\": projectID})\n\t\tif err != nil {\n\t\t\t_ = helpers.Response.SendErrorResponse(ctx, w, http.StatusUnauthorized, err)\n\t\t\treturn\n\t\t}\n\n\t\t// get project config\n\t\treqParams = utils.ExtractRequestParams(r, reqParams, nil)\n\n\t\tstatus, e, err := syncMan.GetEventingConfig(ctx, projectID, reqParams)\n\t\tif err != nil {\n\t\t\t_ = helpers.Response.SendErrorResponse(ctx, w, status, err)\n\t\t\treturn\n\t\t}\n\n\t\t_ = helpers.Response.SendResponse(ctx, w, status, model.Response{Result: []interface{}{e}})\n\t}\n}",
"func (c *Client) SetupHandlers() {\n\tc.SubscribeAllDeviceMessages()\n}",
"func (h *Handler) SetupRoutes() {\n\tfmt.Println(\"Setting Up Routes\")\n\th.Router = mux.NewRouter()\n\n\th.Router.HandleFunc(\"/api/comment\", h.GetAllComments).Methods(\"GET\")\n\th.Router.HandleFunc(\"/api/comment\", h.PostComment).Methods(\"POST\")\n\th.Router.HandleFunc(\"/api/comment/{id}\", h.GetComment).Methods(\"GET\")\n\th.Router.HandleFunc(\"/api/comment/{id}\", h.UpdateComment).Methods(\"PUT\")\n\th.Router.HandleFunc(\"/api/comment/{id}\", h.DeleteComment).Methods(\"DELETE\")\n\n\th.Router.HandleFunc(\"/api/health\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tif err := json.NewEncoder(w).Encode(Response{Message: \"I am alive!\"}); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t})\n}",
"func (c *Config) Handler() func(string, []string) error {\n\tif c.Add {\n\t\treturn addKubeconfig\n\t}\n\tif c.Set {\n\t\treturn setKubeconfig\n\t}\n\tif c.List {\n\t\treturn listKubeconfigs\n\t}\n\tif c.Remove {\n\t\treturn removeKubeconfig\n\t}\n\n\treturn func(string, []string) error { return nil }\n}",
"func (c *Config) RegisterHandlers(path string) error {\n\tcfg := &oauth2.Config{\n\t\tClientID: c.ClientID,\n\t\tClientSecret: c.ClientSecret,\n\t\tEndpoint: github.Endpoint,\n\t\tRedirectURL: c.RedirectURI,\n\t\tScopes: []string{\"user:email\"},\n\t}\n\thttp.HandleFunc(path, loginHandler(cfg))\n\tr, err := url.Parse(c.RedirectURI)\n\tif err != nil {\n\t\treturn err\n\t}\n\thttp.HandleFunc(r.Path, loginReturnHandler(cfg))\n\thttp.HandleFunc(c.LogoutPath, logoutHandler)\n\treturn nil\n}",
"func (h *Handler) SetupRoutes() {\n\tfmt.Println(\"Setting Up Routes\")\n\th.Router = mux.NewRouter()\n\n\th.Router.HandleFunc(\"/api/comments\", h.GetAllComments).Methods(http.MethodGet)\n\th.Router.HandleFunc(\"/api/comments\", h.PostComment).Methods(http.MethodPost)\n\th.Router.HandleFunc(\"/api/comments/{id}\", h.GetComment).Methods(http.MethodGet)\n\th.Router.HandleFunc(\"/api/comments/{id}\", h.UpdateComment).Methods(http.MethodPut)\n\th.Router.HandleFunc(\"/api/comments/{id}\", h.DeleteComment).Methods(http.MethodDelete)\n\n\th.Router.HandleFunc(\"/api/health\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tresponse := Response{\n\t\t\tMessage: \"I'm alive\",\n\t\t}\n\t\tjson, err := json.Marshal(response)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tw.Write(json)\n\t})\n}",
"func SetupCommandHandlers() {\n\tRegisterCommandHandler(\"stop\", HandleStopCommand)\n\tRegisterCommandHandler(\"kick\", HandleKickCommand)\n\tRegisterCommandHandler(\"config\", HandleConfigCommand)\n\tRegisterCommandHandler(\"send\", HandleSendCommand)\n\tRegisterCommandHandler(\"op\", HandleOpCommand)\n\tRegisterCommandHandler(\"deop\", HandleDeopCommand)\n\tRegisterCommandHandler(\"players\", HandlePlayersCommand)\n\tRegisterCommandHandler(\"godmode\", HandleGodmodeCommand)\n\n\tAllowClientCommand(\"debug\")\n\tAllowClientCommand(\"noclip\")\n\tAllowClientCommand(\"kill\")\n}",
"func (api *API) configUserHandler() service.Handler {\n\treturn func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\t\treturn service.WriteJSON(w, sdk.ConfigUser{\n\t\t\tURLUI: api.Config.URL.UI,\n\t\t\tURLAPI: api.Config.URL.API,\n\t\t}, http.StatusOK)\n\t}\n}",
"func ServeConfig(s *Site) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tfmt.Fprint(w, s.Config)\n\t}\n}",
"func InstallHandlers(r *router.Router, base router.MiddlewareChain, adminAuth auth.Method) {\n\ttmpl := &templates.Bundle{\n\t\tLoader: templates.AssetsLoader(assets.Assets()),\n\t\tDefaultTemplate: \"base\",\n\t\tFuncMap: template.FuncMap{\n\t\t\t\"includeCSS\": func(name string) template.CSS { return template.CSS(assets.GetAsset(name)) },\n\t\t\t\"includeJS\": func(name string) template.JS { return template.JS(assets.GetAsset(name)) },\n\t\t},\n\t\tDefaultArgs: func(c context.Context, e *templates.Extra) (templates.Args, error) {\n\t\t\tlogoutURL, err := auth.LogoutURL(c, \"/\")\n\t\t\tif err != nil && err != auth.ErrNoUsersAPI {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn templates.Args{\n\t\t\t\t\"Email\": auth.CurrentUser(c).Email,\n\t\t\t\t\"LogoutURL\": logoutURL,\n\t\t\t}, nil\n\t\t},\n\t}\n\n\tadminDB := adminBypassDB{\n\t\tauthdb.ErroringDB{\n\t\t\tError: errors.New(\"admin: unexpected call to authdb.DB on admin page\"),\n\t\t},\n\t}\n\n\trr := r.Subrouter(\"/admin/portal\")\n\trr.Use(base.Extend(\n\t\ttemplates.WithTemplates(tmpl),\n\t\tadminDB.install,\n\t\tauth.Authenticate(adminAuth),\n\t\tadminAutologin,\n\t))\n\n\trr.GET(\"\", nil, indexPage)\n\trr.GET(\"/:PageKey\", nil, portalPageGET)\n\trr.POST(\"/:PageKey\", router.NewMiddlewareChain(xsrf.WithTokenCheck), portalPagePOST)\n\trr.GET(\"/:PageKey/:ActionID\", nil, portalActionGETPOST)\n\trr.POST(\"/:PageKey/:ActionID\", router.NewMiddlewareChain(xsrf.WithTokenCheck), portalActionGETPOST)\n}",
"func TestGetConfigHandler(t *testing.T) {\n\tadminTestBed, err := prepareAdminXLTestBed()\n\tif err != nil {\n\t\tt.Fatal(\"Failed to initialize a single node XL backend for admin handler tests.\")\n\t}\n\tdefer adminTestBed.TearDown()\n\n\t// Initialize admin peers to make admin RPC calls.\n\tglobalMinioAddr = \"127.0.0.1:9000\"\n\tinitGlobalAdminPeers(mustGetNewEndpointList(\"http://127.0.0.1:9000/d1\"))\n\n\t// Prepare query params for get-config mgmt REST API.\n\tqueryVal := url.Values{}\n\tqueryVal.Set(\"config\", \"\")\n\n\treq, err := buildAdminRequest(queryVal, \"get\", http.MethodGet, 0, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to construct get-config object request - %v\", err)\n\t}\n\n\trec := httptest.NewRecorder()\n\tadminTestBed.mux.ServeHTTP(rec, req)\n\tif rec.Code != http.StatusOK {\n\t\tt.Errorf(\"Expected to succeed but failed with %d\", rec.Code)\n\t}\n\n}",
"func (app *App) setup(cfgPath string) error {\n\tif err := app.LoadConfig(cfgPath); err != nil {\n\t\treturn err\n\t}\n\tif err := app.ConnectDb(); err != nil {\n\t\treturn err\n\t}\n\tif err := app.ParseTemplates(); err != nil {\n\t\treturn err\n\t}\n\tapp.SetRoutes()\n\tapp.InitSession()\n\tapp.Notifier = &service.Notifier{app.Config}\n\treturn nil\n}",
"func RegisterHandlers(router EchoRouter, si ServerInterface) {\n\tRegisterHandlersWithBaseURL(router, si, \"\")\n}",
"func RegisterHandlers(router EchoRouter, si ServerInterface) {\n\tRegisterHandlersWithBaseURL(router, si, \"\")\n}",
"func RegisterHandlers(router EchoRouter, si ServerInterface) {\n\tRegisterHandlersWithBaseURL(router, si, \"\")\n}",
"func RegisterHandlers(router EchoRouter, si ServerInterface) {\n\tRegisterHandlersWithBaseURL(router, si, \"\")\n}",
"func RegisterHandlers(router EchoRouter, si ServerInterface) {\n\tRegisterHandlersWithBaseURL(router, si, \"\")\n}"
] | [
"0.733393",
"0.7146994",
"0.6848298",
"0.68481696",
"0.649023",
"0.6450655",
"0.63600093",
"0.628516",
"0.6273937",
"0.62633467",
"0.62538534",
"0.6226915",
"0.6214841",
"0.620422",
"0.61968184",
"0.6184763",
"0.61802924",
"0.61763644",
"0.6123434",
"0.6119582",
"0.61045104",
"0.60900646",
"0.6074267",
"0.60638523",
"0.60623074",
"0.6043753",
"0.6042783",
"0.6031881",
"0.6022805",
"0.60204107",
"0.60160357",
"0.5984327",
"0.59794164",
"0.5969387",
"0.5969189",
"0.59578",
"0.5945455",
"0.5941691",
"0.5905019",
"0.5901747",
"0.589259",
"0.58831024",
"0.5874247",
"0.58734787",
"0.5859308",
"0.5858795",
"0.58413225",
"0.58406484",
"0.5821177",
"0.5796938",
"0.57922864",
"0.57795006",
"0.57741207",
"0.57675195",
"0.57666063",
"0.5755252",
"0.57505804",
"0.5744932",
"0.5739692",
"0.5738388",
"0.5728623",
"0.5712728",
"0.5711568",
"0.570777",
"0.57044023",
"0.57003146",
"0.5688689",
"0.56839544",
"0.56619775",
"0.56450284",
"0.5644001",
"0.5641614",
"0.56414455",
"0.5639643",
"0.56384796",
"0.5616834",
"0.5606801",
"0.56066144",
"0.5600582",
"0.56001514",
"0.5596548",
"0.55791473",
"0.55611515",
"0.55607533",
"0.5550635",
"0.55505913",
"0.55491054",
"0.5544283",
"0.55397624",
"0.55278987",
"0.55243784",
"0.5522405",
"0.55220556",
"0.55170745",
"0.5504197",
"0.54995483",
"0.54995483",
"0.54995483",
"0.54995483",
"0.54995483"
] | 0.8645846 | 0 |
Encode ConsumerRunningInfo to byte array | func (c *ConsumerRunningInfo) Encode() (jsonByte []byte, err error) {
mqTableJsonStr := "{"
first := true
var keyJson []byte
var valueJson []byte
for key, value := range c.MqTable {
keyJson, err = json.Marshal(key)
if err != nil {
return
}
valueJson, err = json.Marshal(value)
if err != nil {
return
}
if first == false {
mqTableJsonStr = mqTableJsonStr + ","
}
mqTableJsonStr = mqTableJsonStr + string(keyJson) + ":" + string(valueJson)
first = false
}
mqTableJsonStr = mqTableJsonStr + "}"
var propertiesJson []byte
propertiesJson, err = json.Marshal(c.Properties)
if err != nil {
return
}
jsonByte = c.formatEncode("\"properties\"", string(propertiesJson), "\"mqTable\"", string(mqTableJsonStr))
return
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (topicInfo TopicInfo) ToBytes() []byte {\n\tdata, err := protobuf.Marshal(topicInfo._ToProtobuf())\n\tif err != nil {\n\t\treturn make([]byte, 0)\n\t}\n\n\treturn data\n}",
"func (params ConsensusParamsInfo) Bytes() []byte {\n\treturn ser.MustEncodeToBytes(params)\n}",
"func (cw *CapWriter) Bytes() []byte { return []byte(*cw) }",
"func cmdToBytes(cmd interface{}) []byte {\n\tvar buf bytes.Buffer\n\tenc := gob.NewEncoder(&buf)\n\tif err := enc.Encode(Command{Cmd: cmd}); nil != err {\n\t\tlog.Fatalf(\"failed to encode command: %s\", err)\n\t}\n\treturn buf.Bytes()\n}",
"func (v ProviderChange) Bytes() []byte {\n\tbuf := make([]byte, 28)\n\tb := 0\n\n\txgb.Put32(buf[b:], uint32(v.Timestamp))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Window))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Provider))\n\tb += 4\n\n\tb += 16 // padding\n\n\treturn buf[:b]\n}",
"func EncodeInfo(info *SegmentInfo) ([]byte, error) {\n\t// marshal the data into protobuf format\n\tdata, err := proto.Marshal(info)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not marshal segment info\")\n\t}\n\n\t// write the size of the data to a new buffer\n\tsizebytes := make([]byte, 4)\n\tbinary.LittleEndian.PutUint32(sizebytes, uint32(len(data)))\n\tbuf := bytes.NewBuffer(sizebytes)\n\n\t// write the data to the buffer\n\t_, err = buf.Write(data)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not write data to buffer\")\n\t}\n\n\treturn buf.Bytes(), nil\n}",
"func (s *SOC) toBytes() []byte {\n\tbuf := bytes.NewBuffer(nil)\n\tbuf.Write(s.id)\n\tbuf.Write(s.signature)\n\tbuf.Write(s.chunk.Data())\n\treturn buf.Bytes()\n}",
"func (v ModeInfo) Bytes() []byte {\n\tbuf := make([]byte, 32)\n\tb := 0\n\n\txgb.Put32(buf[b:], v.Id)\n\tb += 4\n\n\txgb.Put16(buf[b:], v.Width)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.Height)\n\tb += 2\n\n\txgb.Put32(buf[b:], v.DotClock)\n\tb += 4\n\n\txgb.Put16(buf[b:], v.HsyncStart)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.HsyncEnd)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.Htotal)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.Hskew)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.VsyncStart)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.VsyncEnd)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.Vtotal)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.NameLen)\n\tb += 2\n\n\txgb.Put32(buf[b:], v.ModeFlags)\n\tb += 4\n\n\treturn buf[:b]\n}",
"func (p *Poll) EncodeToByte() []byte {\n\tb, _ := json.Marshal(p)\n\treturn b\n}",
"func (e *Encoder) Bytes() []byte { return e.buf }",
"func (c *encdecContext) marshal() ([]byte, error) {\n\tvar b cryptobyte.Builder\n\tb.AddUint16(uint16(c.suite.kemID))\n\tb.AddUint16(uint16(c.suite.kdfID))\n\tb.AddUint16(uint16(c.suite.aeadID))\n\tb.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {\n\t\tb.AddBytes(c.exporterSecret)\n\t})\n\tb.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {\n\t\tb.AddBytes(c.key)\n\t})\n\tb.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {\n\t\tb.AddBytes(c.baseNonce)\n\t})\n\tb.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {\n\t\tb.AddBytes(c.sequenceNumber)\n\t})\n\treturn b.Bytes()\n}",
"func (b *BinlogEvent) ToByte() []byte {\n\treturn b.Value.RawData\n}",
"func (v CounterNotifyEvent) Bytes() []byte {\n\tbuf := make([]byte, 32)\n\tb := 0\n\n\t// write event number\n\tbuf[b] = 0\n\tb += 1\n\n\tbuf[b] = v.Kind\n\tb += 1\n\n\tb += 2 // skip sequence number\n\n\txgb.Put32(buf[b:], uint32(v.Counter))\n\tb += 4\n\n\t{\n\t\tstructBytes := v.WaitValue.Bytes()\n\t\tcopy(buf[b:], structBytes)\n\t\tb += xgb.Pad(len(structBytes))\n\t}\n\n\t{\n\t\tstructBytes := v.CounterValue.Bytes()\n\t\tcopy(buf[b:], structBytes)\n\t\tb += xgb.Pad(len(structBytes))\n\t}\n\n\txgb.Put32(buf[b:], uint32(v.Timestamp))\n\tb += 4\n\n\txgb.Put16(buf[b:], v.Count)\n\tb += 2\n\n\tif v.Destroyed {\n\t\tbuf[b] = 1\n\t} else {\n\t\tbuf[b] = 0\n\t}\n\tb += 1\n\n\tb += 1 // padding\n\n\treturn buf\n}",
"func (r *RatchetState) Marshall() []byte {\n\to := make([]byte, 136)\n\tbinary.BigEndian.PutUint64(o, r.counter)\n\tcopy(o[8:], r.static[:])\n\tcopy(o[40:], r.dynamic[:])\n\tcopy(o[72:], r.privateKey[:])\n\tcopy(o[104:], r.PublicKey[:])\n\treturn o\n}",
"func (w *shardWorker) encodeData(val interface{}) ([]byte, error) {\n\t// Reusing encoders gave issues\n\tencoder := gob.NewEncoder(w.buffer)\n\n\terr := encoder.Encode(val)\n\tif err != nil {\n\t\tw.buffer.Reset()\n\t\treturn nil, err\n\t}\n\n\tencoded := make([]byte, w.buffer.Len())\n\t_, err = w.buffer.Read(encoded)\n\n\tw.buffer.Reset()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn encoded, nil\n}",
"func SyncMapToByte(input sync.Map) []byte {\n\tbuffer := make([]byte, 1024)\n\tsendtable := make(map[string]membership)\n\tinput.Range(func(key, value interface{}) bool {\n\t\tnewkey := fmt.Sprintf(\"%v\", key)\n\t\tnewvalue := value.(membership)\n\t\tsendtable[newkey] = newvalue\n\t\treturn true\n\t})\n\tbuffer, _ = json.Marshal(sendtable)\n\treturn buffer\n}",
"func (c *CloseConsumer) Encode() (*api.BaseCommand, error) {\n\t// prepare close consumer command\n\tcloseConsumer := &api.CommandCloseConsumer{}\n\n\t// set fields\n\tcloseConsumer.ConsumerId = proto.Uint64(c.CID)\n\tcloseConsumer.RequestId = proto.Uint64(c.RID)\n\n\t// prepare base command\n\tbase := &api.BaseCommand{\n\t\tType: getType(api.BaseCommand_CLOSE_CONSUMER),\n\t\tCloseConsumer: closeConsumer,\n\t}\n\n\treturn base, nil\n}",
"func (t TraceID) Bytes() [16]byte {\n\treturn data.TraceID(t).Bytes()\n}",
"func (e *Event) packBytes() ([]byte, error) {\n\tdata := make([]interface{}, 2)\n\tdata[0] = e.Header\n\tdata[1] = e.Name\n\n\tfor _, a := range e.Args {\n\t\tdata = append(data, a)\n\t}\n\n\tvar buf []byte\n\n\tenc := codec.NewEncoderBytes(&buf, &mh)\n\tif err := enc.Encode(data); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf, nil\n}",
"func marshal(msgType uint8, msg interface{}) []byte {\n\tvar out []byte\n\tout = append(out, msgType)\n\n\tv := reflect.ValueOf(msg)\n\tstructType := v.Type()\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tfield := v.Field(i)\n\t\tt := field.Type()\n\t\tswitch t.Kind() {\n\t\tcase reflect.Bool:\n\t\t\tvar v uint8\n\t\t\tif field.Bool() {\n\t\t\t\tv = 1\n\t\t\t}\n\t\t\tout = append(out, v)\n\t\tcase reflect.Array:\n\t\t\tif t.Elem().Kind() != reflect.Uint8 {\n\t\t\t\tpanic(\"array of non-uint8\")\n\t\t\t}\n\t\t\tfor j := 0; j < t.Len(); j++ {\n\t\t\t\tout = append(out, byte(field.Index(j).Uint()))\n\t\t\t}\n\t\tcase reflect.Uint32:\n\t\t\tu32 := uint32(field.Uint())\n\t\t\tout = append(out, byte(u32>>24))\n\t\t\tout = append(out, byte(u32>>16))\n\t\t\tout = append(out, byte(u32>>8))\n\t\t\tout = append(out, byte(u32))\n\t\tcase reflect.String:\n\t\t\ts := field.String()\n\t\t\tout = append(out, byte(len(s)>>24))\n\t\t\tout = append(out, byte(len(s)>>16))\n\t\t\tout = append(out, byte(len(s)>>8))\n\t\t\tout = append(out, byte(len(s)))\n\t\t\tout = append(out, s...)\n\t\tcase reflect.Slice:\n\t\t\tswitch t.Elem().Kind() {\n\t\t\tcase reflect.Uint8:\n\t\t\t\tlength := field.Len()\n\t\t\t\tif structType.Field(i).Tag.Get(\"ssh\") != \"rest\" {\n\t\t\t\t\tout = append(out, byte(length>>24))\n\t\t\t\t\tout = append(out, byte(length>>16))\n\t\t\t\t\tout = append(out, byte(length>>8))\n\t\t\t\t\tout = append(out, byte(length))\n\t\t\t\t}\n\t\t\t\tfor j := 0; j < length; j++ {\n\t\t\t\t\tout = append(out, byte(field.Index(j).Uint()))\n\t\t\t\t}\n\t\t\tcase reflect.String:\n\t\t\t\tvar length int\n\t\t\t\tfor j := 0; j < field.Len(); j++ {\n\t\t\t\t\tif j != 0 {\n\t\t\t\t\t\tlength++ /* comma */\n\t\t\t\t\t}\n\t\t\t\t\tlength += len(field.Index(j).String())\n\t\t\t\t}\n\n\t\t\t\tout = append(out, byte(length>>24))\n\t\t\t\tout = append(out, byte(length>>16))\n\t\t\t\tout = append(out, byte(length>>8))\n\t\t\t\tout = append(out, byte(length))\n\t\t\t\tfor j := 0; j < field.Len(); j++ {\n\t\t\t\t\tif j != 0 {\n\t\t\t\t\t\tout = append(out, ',')\n\t\t\t\t\t}\n\t\t\t\t\tout = append(out, field.Index(j).String()...)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tpanic(\"slice of unknown type\")\n\t\t\t}\n\t\tcase reflect.Ptr:\n\t\t\tif t == bigIntType {\n\t\t\t\tvar n *big.Int\n\t\t\t\tnValue := reflect.ValueOf(&n)\n\t\t\t\tnValue.Elem().Set(field)\n\t\t\t\tneeded := intLength(n)\n\t\t\t\toldLength := len(out)\n\n\t\t\t\tif cap(out)-len(out) < needed {\n\t\t\t\t\tnewOut := make([]byte, len(out), 2*(len(out)+needed))\n\t\t\t\t\tcopy(newOut, out)\n\t\t\t\t\tout = newOut\n\t\t\t\t}\n\t\t\t\tout = out[:oldLength+needed]\n\t\t\t\tmarshalInt(out[oldLength:], n)\n\t\t\t} else {\n\t\t\t\tpanic(\"pointer to unknown type\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn out\n}",
"func main() {\n\n\tfmt.Println(\"Buf test application ver 0.0.1\")\n\n\ttype data struct {\n\t\tq byte\n\t\tb [3]byte\n\t\tq2 byte\n\t\tm uint32\n\t}\n\n\tmyData := data{1, [3]byte{2, 3, 4}, 5, 0x01287353}\n\n\tstdoutDumper := hex.Dumper(os.Stdout)\n\n\tbuf := new(bytes.Buffer)\n\tle := binary.LittleEndian\n\tbinary.Write(buf, le, myData)\n\n\tfmt.Printf(\"buf: %v\\n\", buf.Bytes())\n\tstdoutDumper.Write(buf.Bytes())\n\tfmt.Printf(\"\\n\")\n}",
"func (v NotifyEvent) Bytes() []byte {\n\tbuf := make([]byte, 32)\n\tb := 0\n\n\t// write event number\n\tbuf[b] = 1\n\tb += 1\n\n\tbuf[b] = v.SubCode\n\tb += 1\n\n\tb += 2 // skip sequence number\n\n\t{\n\t\tunionBytes := v.U.Bytes()\n\t\tcopy(buf[b:], unionBytes)\n\t\tb += len(unionBytes)\n\t}\n\n\treturn buf\n}",
"func Bytes() []byte {\n\treturn conf.Bytes()\n}",
"func (v ScreenChangeNotifyEvent) Bytes() []byte {\n\tbuf := make([]byte, 32)\n\tb := 0\n\n\t// write event number\n\tbuf[b] = 0\n\tb += 1\n\n\tbuf[b] = v.Rotation\n\tb += 1\n\n\tb += 2 // skip sequence number\n\n\txgb.Put32(buf[b:], uint32(v.Timestamp))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.ConfigTimestamp))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Root))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.RequestWindow))\n\tb += 4\n\n\txgb.Put16(buf[b:], v.SizeID)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.SubpixelOrder)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.Width)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.Height)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.Mwidth)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.Mheight)\n\tb += 2\n\n\treturn buf\n}",
"func (b *ByteEvent) ToByte() []byte {\n\treturn b.Value\n}",
"func (e *Event) Bytes() []byte {\n\tif e.encoded == nil {\n\t\tvar err error\n\t\tprunedData := make(map[string]interface{})\n\t\tfor key, value := range e.data {\n\t\t\tif key == \"@metadata\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tprunedData[key] = value\n\t\t}\n\t\tif e.encoded, err = json.Marshal(prunedData); err != nil {\n\t\t\te.encoded = []byte(\"{\\\"tags\\\":[\\\"_encode_failure\\\"]}\")\n\t\t}\n\t}\n\treturn e.encoded\n}",
"func (m *AnnounceDisposed) Pack() []byte {\n\tvar err error\n\tbuf := new(bytes.Buffer)\n\terr = m.WriteCmdStructToBuf(buf)\n\t//err = binary.Write(buf, binary.LittleEndian, m.CmdID)\n\t_, err = buf.Write(m.Lock.AsBytes())\n\t_, err = buf.Write(m.ChannelIdentifier[:])\n\terr = binary.Write(buf, binary.BigEndian, m.OpenBlockNumber)\n\t// 2019-03 添加错误码及错误信息\n\terrCode := int32(m.ErrorCode)\n\terr = binary.Write(buf, binary.BigEndian, errCode)\n\terrorMsgBytes := utils.StringToBytes(m.ErrorMsg)\n\terrorMsgBytesLen := int32(len(errorMsgBytes))\n\terr = binary.Write(buf, binary.BigEndian, errorMsgBytesLen)\n\tif errorMsgBytesLen > 0 {\n\t\t_, err = buf.Write(errorMsgBytes)\n\t}\n\t_, err = buf.Write(m.Signature)\n\tif err != nil {\n\t\tlog.Crit(fmt.Sprintf(\"pack AnnounceDisposed err %s\", err))\n\t}\n\treturn buf.Bytes()\n}",
"func (fd FileDescriptor) toBytes() []byte {\n\tbuf := make([]byte, 0x27)\n\tbuf[0] = fd.TypeAndNameLength\n\tcopyBytes(buf[1:0x10], fd.FileName[:])\n\tbuf[0x10] = fd.FileType\n\tbinary.LittleEndian.PutUint16(buf[0x11:0x13], fd.KeyPointer)\n\tbinary.LittleEndian.PutUint16(buf[0x13:0x15], fd.BlocksUsed)\n\tcopyBytes(buf[0x15:0x18], fd.EOF[:])\n\tcopyBytes(buf[0x18:0x1c], fd.Creation.toBytes())\n\tbuf[0x1c] = fd.Version\n\tbuf[0x1d] = fd.MinVersion\n\tbuf[0x1e] = byte(fd.Access)\n\tbinary.LittleEndian.PutUint16(buf[0x1f:0x21], fd.AuxType)\n\tcopyBytes(buf[0x21:0x25], fd.LastMod.toBytes())\n\tbinary.LittleEndian.PutUint16(buf[0x25:0x27], fd.HeaderPointer)\n\treturn buf\n}",
"func (status NewStatus) Bytes() []byte {\n\treturn ser.MustEncodeToBytes(status)\n}",
"func SerializerToBytes(value interface{}) ([]byte, error) {\n\tbyte, err := json.Marshal(value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn byte, nil\n}",
"func gobInfoEncode(gob *storage.GobInfo) ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\tgobEnc := realgob.NewEncoder(buf)\n\terr := gobEnc.Encode(gob)\n\treturn buf.Bytes(), err\n}",
"func (r *Request) dumpCbor() []byte {\n\tvar buf []byte\n\te := codec.NewEncoderBytes(&buf, dots_common.NewCborHandle())\n\n\terr := e.Encode(r.Message)\n\tif err != nil {\n\t\tlog.Errorf(\"Error decoding %s\", err)\n\t}\n\treturn buf\n}",
"func (space *Space) ToByte() []byte {\n\traw, _ := json.Marshal(space)\n\treturn raw\n}",
"func Marshal(val interface{}) ([]byte, error) {}",
"func encodeMulticastAnnounceBytes() []byte {\n\tnameBytes := []byte(GetClusterName())\n\tnameBytesLen := len(nameBytes)\n\n\tif nameBytesLen > 0xFF {\n\t\tpanic(\"Cluster name too long: \" +\n\t\t\tstrconv.FormatInt(int64(nameBytesLen), 10) +\n\t\t\t\" bytes (max 254)\")\n\t}\n\n\tmsg := newMessage(verbPing, thisHost, currentHeartbeat)\n\tmsgBytes := msg.encode()\n\tmsgBytesLen := len(msgBytes)\n\n\ttotalByteCount := 1 + nameBytesLen + msgBytesLen\n\n\tbytes := make([]byte, totalByteCount, totalByteCount)\n\n\t// Add name length byte\n\tbytes[0] = byte(nameBytesLen)\n\n\t// Copy the name bytes\n\tcopy(bytes[1:nameBytesLen+1], nameBytes)\n\n\t// Copy the message proper\n\tcopy(bytes[nameBytesLen+1:totalByteCount], msgBytes)\n\n\treturn bytes\n}",
"func (self *EV3Message) getBytes() []byte {\n\tself.commandSize = uint16(len(self.byteCodes)) + EV3MessageHeaderSize - 2 // 2 means commandSize = uint16 that should not be counted\n\tbuf := make([]byte, EV3MessageHeaderSize)\n\tbinary.LittleEndian.PutUint16(buf[0:], self.commandSize)\n\tbinary.LittleEndian.PutUint16(buf[2:], self.messageCount)\n\tbuf[4] = self.commandType\n\tbinary.LittleEndian.PutUint16(buf[5:], self.variablesReservation)\n\tbuf = append(buf, self.byteCodes...)\n\treturn buf\n}",
"func (msg MsgCreateIndex) GetSignBytes() []byte {\n return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg))\n}",
"func timeToByteArr(timeVal int64) []byte {\n\tbuff := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(buff, uint64(timeVal))\n\n\treturn buff\n\n}",
"func ToBytes(inter interface{}) []byte {\n\treqBodyBytes := new(bytes.Buffer)\n\tjson.NewEncoder(reqBodyBytes).Encode(inter)\n\tfmt.Println(reqBodyBytes.Bytes()) // this is the []byte\n\tfmt.Println(string(reqBodyBytes.Bytes())) // converted back to show it's your original object\n\treturn reqBodyBytes.Bytes()\n}",
"func (ack NonFungibleTokenPacketAcknowledgement) GetBytes() []byte {\n\treturn sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(ack))\n}",
"func (s StatsKey) Bytes() []byte {\n\treturn append([]byte(nil), beamStatsKeyBytes...)\n}",
"func (v OutputChange) Bytes() []byte {\n\tbuf := make([]byte, 28)\n\tb := 0\n\n\txgb.Put32(buf[b:], uint32(v.Timestamp))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.ConfigTimestamp))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Window))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Output))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Crtc))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Mode))\n\tb += 4\n\n\txgb.Put16(buf[b:], v.Rotation)\n\tb += 2\n\n\tbuf[b] = v.Connection\n\tb += 1\n\n\tbuf[b] = v.SubpixelOrder\n\tb += 1\n\n\treturn buf[:b]\n}",
"func (v Event) Bytes() []byte {\n\tbuf := make([]byte, 32)\n\tb := 0\n\n\tb += 32 // padding\n\n\treturn buf[:b]\n}",
"func (e *Encoder) Bytes() []byte {\n\treturn e.out\n}",
"func (v Systemcounter) Bytes() []byte {\n\tbuf := make([]byte, (14 + xgb.Pad((int(v.NameLen) * 1))))\n\tb := 0\n\n\txgb.Put32(buf[b:], uint32(v.Counter))\n\tb += 4\n\n\t{\n\t\tstructBytes := v.Resolution.Bytes()\n\t\tcopy(buf[b:], structBytes)\n\t\tb += xgb.Pad(len(structBytes))\n\t}\n\n\txgb.Put16(buf[b:], v.NameLen)\n\tb += 2\n\n\tcopy(buf[b:], v.Name[:v.NameLen])\n\tb += xgb.Pad(int(v.NameLen))\n\n\treturn buf\n}",
"func encode(ch channel.Sender, v interface{}) (int, error) {\n\tbits, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn len(bits), ch.Send(bits)\n}",
"func ProviderChangeListBytes(buf []byte, list []ProviderChange) int {\n\tb := 0\n\tvar structBytes []byte\n\tfor _, item := range list {\n\t\tstructBytes = item.Bytes()\n\t\tcopy(buf[b:], structBytes)\n\t\tb += len(structBytes)\n\t}\n\treturn xgb.Pad(b)\n}",
"func (f SingleWorkerID) Bytes() []byte {\n\treturn []byte(f.String())\n}",
"func (id NodeID) Bytes() []byte { return id[:] }",
"func (t ControlledShutdownRequest) Encode(e *Encoder, version int16) {\n\te.PutInt32(t.BrokerId) // BrokerId\n\tif version >= 2 {\n\t\te.PutInt64(t.BrokerEpoch) // BrokerEpoch\n\t}\n}",
"func ValueToBytes(codec acodec.Codec, v interface{}) []byte {\n\tif v == nil {\n\t\treturn nil\n\t}\n\tvar (\n\t\terr error\n\t\tdata []byte\n\t)\n\tswitch vt := v.(type) {\n\tcase []byte:\n\t\tdata = vt\n\tcase *[]byte:\n\t\tdata = *vt\n\tcase string:\n\t\tdata = StrToBytes(vt)\n\tcase *string:\n\t\tdata = StrToBytes(*vt)\n\tcase error:\n\t\tdata = StrToBytes(vt.Error())\n\tcase *error:\n\t\tdata = StrToBytes((*vt).Error())\n\tdefault:\n\t\tif codec == nil {\n\t\t\tcodec = acodec.DefaultCodec\n\t\t}\n\t\tdata, err = codec.Marshal(vt)\n\t\tif err != nil {\n\t\t\tlog.Error(\"ValueToBytes: %v\", err)\n\t\t}\n\t}\n\n\treturn data\n}",
"func (v ResourceChange) Bytes() []byte {\n\tbuf := make([]byte, 28)\n\tb := 0\n\n\txgb.Put32(buf[b:], uint32(v.Timestamp))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Window))\n\tb += 4\n\n\tb += 20 // padding\n\n\treturn buf[:b]\n}",
"func Marshal(curve elliptic.Curve, x, y *big.Int) []byte",
"func itob(v int) []byte {\n b := make([]byte, 8)\n binary.BigEndian.PutUint64(b, uint64(v))\n return b\n}",
"func itob(v int) []byte {\n b := make([]byte, 8)\n binary.BigEndian.PutUint64(b, uint64(v))\n return b\n}",
"func (v ProviderProperty) Bytes() []byte {\n\tbuf := make([]byte, 28)\n\tb := 0\n\n\txgb.Put32(buf[b:], uint32(v.Window))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Provider))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Atom))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Timestamp))\n\tb += 4\n\n\tbuf[b] = v.State\n\tb += 1\n\n\tb += 11 // padding\n\n\treturn buf[:b]\n}",
"func numberToBytes(n interface{}) []byte {\n\tswitch i := n.(type) {\n\tcase uint64:\n\t\tb := make([]byte, 8)\n\t\tbinary.LittleEndian.PutUint64(b, i)\n\t\treturn b\n\tcase uint32:\n\t\tb := make([]byte, 4)\n\t\tbinary.LittleEndian.PutUint32(b, i)\n\t\treturn b\n\tcase uint16:\n\t\tb := make([]byte, 2)\n\t\tbinary.LittleEndian.PutUint16(b, i)\n\t\treturn b\n\tcase uint8:\n\t\tb := []byte{byte(i)}\n\t\treturn b\n\tdefault:\n\t\tpanic(errors.New(\"Unsupported type\"))\n\t}\n}",
"func (u *msg_COVID) MarshalBinary() ([]byte, error) {\n\treturn json.Marshal(u)\n}",
"func (t OffsetCommitResponse) Encode(e *Encoder, version int16) {\n\tif version >= 3 {\n\t\te.PutInt32(t.ThrottleTimeMs) // ThrottleTimeMs\n\t}\n\t// Topics\n\tlen1 := len(t.Topics)\n\te.PutArrayLength(len1)\n\tfor i := 0; i < len1; i++ {\n\t\tt.Topics[i].Encode(e, version)\n\t}\n}",
"func ConfigMapAsBytes(cm *corev1.ConfigMap) ([]byte, error) {\n\treturn runtime.Encode(coreEncoder, cm)\n}",
"func (w *ByteWriter) Bytes() []byte { return w.buffer }",
"func (v AlarmNotifyEvent) Bytes() []byte {\n\tbuf := make([]byte, 32)\n\tb := 0\n\n\t// write event number\n\tbuf[b] = 1\n\tb += 1\n\n\tbuf[b] = v.Kind\n\tb += 1\n\n\tb += 2 // skip sequence number\n\n\txgb.Put32(buf[b:], uint32(v.Alarm))\n\tb += 4\n\n\t{\n\t\tstructBytes := v.CounterValue.Bytes()\n\t\tcopy(buf[b:], structBytes)\n\t\tb += xgb.Pad(len(structBytes))\n\t}\n\n\t{\n\t\tstructBytes := v.AlarmValue.Bytes()\n\t\tcopy(buf[b:], structBytes)\n\t\tb += xgb.Pad(len(structBytes))\n\t}\n\n\txgb.Put32(buf[b:], uint32(v.Timestamp))\n\tb += 4\n\n\tbuf[b] = v.State\n\tb += 1\n\n\tb += 3 // padding\n\n\treturn buf\n}",
"func (t OffsetCommitRequestPartition8) Encode(e *Encoder, version int16) {\n\te.PutInt32(t.PartitionIndex) // PartitionIndex\n\te.PutInt64(t.CommittedOffset) // CommittedOffset\n\tif version >= 6 {\n\t\te.PutInt32(t.CommittedLeaderEpoch) // CommittedLeaderEpoch\n\t}\n\te.PutString(t.CommittedMetadata) // CommittedMetadata\n}",
"func (t TxnOffsetCommitResponse) Encode(e *Encoder, version int16) {\n\te.PutInt32(t.ThrottleTimeMs) // ThrottleTimeMs\n\t// Topics\n\tlen1 := len(t.Topics)\n\te.PutArrayLength(len1)\n\tfor i := 0; i < len1; i++ {\n\t\tt.Topics[i].Encode(e, version)\n\t}\n}",
"func toByteArray(data interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tenc := gob.NewEncoder(&buf)\n\terr := enc.Encode(data)\n\tif err != nil {\n\t\treturn nil, err\n\t} else {\n\t\treturn buf.Bytes(), nil\n\t}\n}",
"func (v CrtcChange) Bytes() []byte {\n\tbuf := make([]byte, 28)\n\tb := 0\n\n\txgb.Put32(buf[b:], uint32(v.Timestamp))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Window))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Crtc))\n\tb += 4\n\n\txgb.Put32(buf[b:], uint32(v.Mode))\n\tb += 4\n\n\txgb.Put16(buf[b:], v.Rotation)\n\tb += 2\n\n\tb += 2 // padding\n\n\txgb.Put16(buf[b:], uint16(v.X))\n\tb += 2\n\n\txgb.Put16(buf[b:], uint16(v.Y))\n\tb += 2\n\n\txgb.Put16(buf[b:], v.Width)\n\tb += 2\n\n\txgb.Put16(buf[b:], v.Height)\n\tb += 2\n\n\treturn buf[:b]\n}",
"func (e Event) Bytes() []byte {\n\treturn bigendian.Uint32ToBytes(uint32(e))\n}",
"func (id *Identity) Bytes() []byte { return id[:] }",
"func (valInfo *ValidatorsInfo) Bytes() []byte {\n\treturn ser.MustEncodeToBytes(valInfo)\n}",
"func processMsg(msg *sarama.ConsumerMessage) {\n\tvar str interface{}\n\tif err := json.Unmarshal(msg.Value, &str); err != nil {\n\t}\n\ts, _ := json.MarshalIndent(str, \"\", \" \")\n\n\tfmt.Printf(\"Offset: %d Key: %s\\n\", msg.Offset, msg.Key)\n\tfmt.Printf(\"%s\\n\", s)\n\tfmt.Printf(\"-----\\n\")\n}",
"func getBytes(key interface{}) ([]byte, error) {\n\treturn json.Marshal(&key)\n}",
"func (sd *PrivateDescriptor) encode() ([]byte, error) {\n\tlength := sd.length()\n\n\t// add 2 bytes to contain splice_descriptor_tag & descriptor_length\n\tbuf := make([]byte, length+2)\n\tiow := iobit.NewWriter(buf)\n\tiow.PutUint32(8, sd.PrivateTag)\n\tiow.PutUint32(8, uint32(length))\n\tiow.PutUint32(32, sd.Identifier)\n\t_, err := iow.Write(sd.PrivateBytes)\n\tif err != nil {\n\t\treturn buf, err\n\t}\n\terr = iow.Flush()\n\n\treturn buf, err\n}",
"func toBytes(bytes, value int) []byte {\n\tswitch bytes {\n\tcase 1:\n\t\treturn []byte{byte(value)}\n\tcase 2:\n\t\treturn []byte{byte(value), byte(value >> 8)}\n\tdefault:\n\t\treturn []byte{byte(value), byte(value >> 8), byte(value >> 16), byte(value >> 24)}\n\t}\n}",
"func ToByteArr(v interface{}) (result []byte) {\n\tresult = []byte(\"\")\n\tif v == nil {\n\t\treturn result\n\t}\n\n\tswitch v := v.(type) {\n\tcase string:\n\t\tresult = []byte(v)\n\tcase int:\n\t\tresult = []byte(strconv.Itoa(v))\n\tcase int64:\n\t\tresult = []byte(strconv.FormatInt(v, 10))\n\tcase bool:\n\t\tresult = []byte(strconv.FormatBool(v))\n\tcase float64:\n\t\tresult = []byte(strconv.FormatFloat(v, 'E', -1, 64))\n\tcase []uint8:\n\t\tresult = v\n\tdefault:\n\t\tresultJSON, err := json.Marshal(v)\n\t\tif err == nil {\n\t\t\tresult = resultJSON\n\t\t} else {\n\t\t\tlog.Println(\"func ToByteArr\", err)\n\t\t}\n\t}\n\n\treturn result\n}",
"func ExportAsBytes(insta *goinsta.Instagram) ([]byte, error) {\n\tbuffer := &bytes.Buffer{}\n\terr := goinsta.Export(insta, buffer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buffer.Bytes(), nil\n}",
"func (v Trigger) Bytes() []byte {\n\tbuf := make([]byte, 20)\n\tb := 0\n\n\txgb.Put32(buf[b:], uint32(v.Counter))\n\tb += 4\n\n\txgb.Put32(buf[b:], v.WaitType)\n\tb += 4\n\n\t{\n\t\tstructBytes := v.WaitValue.Bytes()\n\t\tcopy(buf[b:], structBytes)\n\t\tb += xgb.Pad(len(structBytes))\n\t}\n\n\txgb.Put32(buf[b:], v.TestType)\n\tb += 4\n\n\treturn buf\n}",
"func (privKey PrivKeyEd25519) Bytes() []byte {\n\treturn cdc.MustMarshalBinaryBare(privKey)\n}",
"func B64EncodeByteToStr(inputBytes []byte) string {\r\n\treturn base64.StdEncoding.EncodeToString(inputBytes)\r\n}",
"func publicKeyToBytes(pub interface{}) []byte {\r\n\tvar b []byte\r\n\tswitch k := pub.(type) {\r\n\tcase *rsa.PublicKey:\r\n\t\tb = k.N.Bytes()\r\n\tcase *dsa.PublicKey:\r\n\t\tb = k.Y.Bytes()\r\n\tcase *ecdsa.PublicKey:\r\n\t\tb = append(k.X.Bytes(), k.Y.Bytes()...)\r\n\t}\r\n\treturn b\r\n}",
"func (t OffsetCommitRequestTopic8) Encode(e *Encoder, version int16) {\n\te.PutString(t.Name) // Name\n\t// Partitions\n\tlen1 := len(t.Partitions)\n\te.PutArrayLength(len1)\n\tfor i := 0; i < len1; i++ {\n\t\tt.Partitions[i].Encode(e, version)\n\t}\n}",
"func (c *Configuration) Serialize() []byte {\n\tb := make([]byte, confLength)\n\tb[0] = byte(c.Group)\n\tb[1] = byte(c.KDF)\n\tb[2] = byte(c.MAC)\n\tb[3] = byte(c.Hash)\n\tb[4] = byte(c.MHF)\n\tb[5] = byte(c.Mode)\n\tb[6] = encoding.I2OSP(c.NonceLen, 1)[0]\n\n\treturn b\n}",
"func byteEncoder(e *encodeState, v reflect.Value) error {\n\tval := v.Uint()\n\tsz := e.size\n\th := sz / 8.0\n\tfactor := .2\n\tblkH := h * (1 - factor)\n\tmargin := h * (factor / 2)\n\n\tfor y := sz - h; y > 0; y -= h {\n\t\tbit := val % 2\n\t\tif bit == 1 {\n\t\t\tr := e.Rect(margin, y-margin, sz-margin, blkH)\n\t\t\tr.Style.Set(\"stroke-width\", \"0\")\n\t\t\tr.Style.Set(\"fill\", \"black\")\n\t\t}\n\t\tval = val >> 1\n\t\tif val == 0 {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (cfg frozenConfig) Marshal(val interface{}) ([]byte, error) {\n return encoder.Encode(val, cfg.encoderOpts)\n}",
"func (b Beacon) Bytes() []byte {\n\treturn b[:]\n}",
"func (e *ProgramChangeEvent) Serialize() []byte {\n\tbs := []byte{}\n\tbs = append(bs, constant.ProgramChange+e.channel)\n\tbs = append(bs, byte(e.program))\n\n\treturn bs\n}",
"func (t OffsetCommitResponseTopic8) Encode(e *Encoder, version int16) {\n\te.PutString(t.Name) // Name\n\t// Partitions\n\tlen1 := len(t.Partitions)\n\te.PutArrayLength(len1)\n\tfor i := 0; i < len1; i++ {\n\t\tt.Partitions[i].Encode(e, version)\n\t}\n}",
"func (this *SIPMessage) EncodeAsBytes() []byte {\n\treturn []byte(this.String())\n}",
"func (j *PeerInfo) MarshalJSONBuf(buf fflib.EncodingBuffer) error {\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn nil\n\t}\n\tvar err error\n\tvar obj []byte\n\t_ = obj\n\t_ = err\n\tbuf.WriteString(`{\"addr\":`)\n\tfflib.WriteJsonString(buf, string(j.Addr))\n\tbuf.WriteString(`,\"addrlocal\":`)\n\tfflib.WriteJsonString(buf, string(j.AddrLocal))\n\tbuf.WriteString(`,\"rpc-port\":`)\n\tfflib.FormatBits2(buf, uint64(j.RPCPort), 10, j.RPCPort < 0)\n\tbuf.WriteString(`,\"services\":`)\n\tfflib.FormatBits2(buf, uint64(j.Services), 10, j.Services < 0)\n\tbuf.WriteString(`,\"lastsend\":`)\n\tfflib.FormatBits2(buf, uint64(j.LastSend), 10, false)\n\tbuf.WriteString(`,\"lastrecv\":`)\n\tfflib.FormatBits2(buf, uint64(j.LastRecv), 10, false)\n\tbuf.WriteString(`,\"bytessent\":`)\n\tfflib.FormatBits2(buf, uint64(j.BytesSent), 10, false)\n\tbuf.WriteString(`,\"bytesrecv\":`)\n\tfflib.FormatBits2(buf, uint64(j.BytesRecv), 10, false)\n\tbuf.WriteString(`,\"conntime\":`)\n\n\t{\n\n\t\tobj, err = j.Conntime.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbuf.Write(obj)\n\n\t}\n\tbuf.WriteString(`,\"version\":`)\n\tfflib.WriteJsonString(buf, string(j.Version))\n\tbuf.WriteString(`,\"subver\":`)\n\tfflib.WriteJsonString(buf, string(j.Subver))\n\tif j.Inbound {\n\t\tbuf.WriteString(`,\"inbound\":true`)\n\t} else {\n\t\tbuf.WriteString(`,\"inbound\":false`)\n\t}\n\tbuf.WriteString(`,\"firewall_status\":`)\n\tfflib.WriteJsonString(buf, string(j.FirewallStatus))\n\tbuf.WriteString(`,\"fc_git_revision_sha\":`)\n\tfflib.WriteJsonString(buf, string(j.FCGitRevisionSha))\n\tbuf.WriteString(`,\"fc_git_revision_unix_timestamp\":`)\n\n\t{\n\n\t\tobj, err = j.FCGitRevisionUnixTimestamp.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbuf.Write(obj)\n\n\t}\n\tbuf.WriteString(`,\"fc_git_revision_age\":`)\n\tfflib.WriteJsonString(buf, string(j.FCGitRevisionAge))\n\tbuf.WriteString(`,\"platform\":`)\n\tfflib.WriteJsonString(buf, string(j.Platform))\n\tbuf.WriteString(`,\"current_head_block\":`)\n\tfflib.WriteJsonString(buf, string(j.CurrentHeadBlock))\n\tbuf.WriteString(`,\"current_head_block_number\":`)\n\tfflib.FormatBits2(buf, uint64(j.CurrentHeadBlockNumber), 10, false)\n\tbuf.WriteString(`,\"current_head_block_time\":`)\n\n\t{\n\n\t\tobj, err = j.CurrentHeadBlockTime.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbuf.Write(obj)\n\n\t}\n\tbuf.WriteByte('}')\n\treturn nil\n}",
"func createNewSessionDataBytes(guid string) []byte {\n\tjsonStr, err := json.Marshal(map[string]string{ \"guid\": guid })\n\tif err != nil {\n\t\tlogger.Error(fmt.Sprintf(\"Failed to create JSON info for session for GUID %s: %s\", guid, err.Error()))\n\t\treturn nil\n\t}\n\treturn []byte(jsonStr)\n}",
"func (s Status) Bytes() []byte {\n\tbuf := make([]byte, 20)\n\tbuf[0] = s.Inst0\n\tbuf[1] = s.Inst1\n\tbuf[2] = s.Inst2\n\tbuf[3] = s.Inst3\n\tbuf[4], buf[5] = fromU16(s.MemOP)\n\tbuf[6], buf[7] = fromU16(s.IY)\n\tbuf[8], buf[9] = fromU16(s.IX)\n\tbuf[10], buf[11] = fromU16(s.HL)\n\tbuf[12], buf[13] = fromU16(s.DE)\n\tbuf[14], buf[15] = fromU16(s.BC)\n\tbuf[16] = s.Flags\n\tbuf[17] = s.Accum\n\tbuf[18], buf[19] = fromU16(s.SP)\n\treturn buf\n}",
"func (k *Key) ToBytes() []byte {\n\tbuf := &bytes.Buffer{}\n\tbuf.Write(encoding.Uint16ToBytes(k.DBIndex))\n\tbuf.WriteByte(k.MetaType)\n\tbuf.Write(k.Name)\n\treturn buf.Bytes()\n}",
"func (c *BinaryCodec) Bytes() []byte {\n return c.buf.Bytes()\n}",
"func (pubKey PubKeyEd25519) Bytes() []byte {\n\tbz, err := cdc.MarshalBinaryBare(pubKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn bz\n}",
"func (t TDigest) AsBytes() ([]byte, error) {\n\tbuffer := new(bytes.Buffer)\n\n\terr := binary.Write(buffer, endianess, smallEncoding)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = binary.Write(buffer, endianess, t.compression)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = binary.Write(buffer, endianess, int32(t.summary.Len()))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar x float64\n\tt.summary.ForEach(func(mean float64, count uint32) bool {\n\t\tdelta := mean - x\n\t\tx = mean\n\t\terr = binary.Write(buffer, endianess, float32(delta))\n\n\t\treturn err == nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tt.summary.ForEach(func(mean float64, count uint32) bool {\n\t\terr = encodeUint(buffer, count)\n\t\treturn err == nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buffer.Bytes(), nil\n}",
"func (b *Booking) Marshal() []byte {\n\n bnLen, _ := hex.DecodeString(fmt.Sprintf(\"%02x\", len(b.BookerName)))\n facLen, _ := hex.DecodeString(fmt.Sprintf(\"%02x\", len(b.Fac)))\n\n payload := bnLen\n payload = append(payload, []byte(b.BookerName)...)\n payload = append(payload, []byte(b.Start.ToBytes())...) // 7 bytes\n payload = append(payload, []byte(b.End.ToBytes())...) // 7 bytes\n payload = append(payload, facLen...)\n payload = append(payload, []byte(b.Fac)...)\n payload = append(payload, []byte(b.ConfirmationID)...)\n hdr := messagesocket.CreateBookingDetailHeader(uint16(len(payload)))\n\n return append(hdr, payload...)\n}",
"func (tx *CommandValidatorChange) SignableBytes() []byte {\n\treturn sbOf(tx)\n}",
"func (t OffsetFetchRequestTopic9) Encode(e *Encoder, version int16) {\n\te.PutString(t.Name) // Name\n\te.PutInt32Array(t.PartitionIndexes) // PartitionIndexes\n}",
"func (b *Buf) Bytes() []byte { return b.b }",
"func (tx *Notify) SignableBytes() []byte {\n\treturn sbOf(tx)\n}",
"func itob(v int) []byte {\n\tb := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(b, uint64(v))\n\treturn b\n}"
] | [
"0.5658311",
"0.51520276",
"0.4936131",
"0.49118227",
"0.48802206",
"0.48266935",
"0.48195493",
"0.48085403",
"0.47663084",
"0.4762395",
"0.47209847",
"0.46909267",
"0.46779102",
"0.46542034",
"0.46265787",
"0.45813623",
"0.45811573",
"0.45682436",
"0.45654944",
"0.4558911",
"0.45488444",
"0.45344493",
"0.4529349",
"0.45220688",
"0.45098373",
"0.450484",
"0.44983596",
"0.44981524",
"0.4488459",
"0.44850338",
"0.4460701",
"0.44586435",
"0.44516328",
"0.44484982",
"0.44473198",
"0.44426948",
"0.44357",
"0.4426725",
"0.44203505",
"0.441849",
"0.4407602",
"0.44059947",
"0.44035697",
"0.44022742",
"0.44019815",
"0.43985057",
"0.43805927",
"0.4378518",
"0.43785015",
"0.43769392",
"0.4365589",
"0.43646172",
"0.4364194",
"0.43557486",
"0.43557486",
"0.4353586",
"0.4346637",
"0.43393737",
"0.43391082",
"0.43376276",
"0.43315446",
"0.43280855",
"0.43220064",
"0.4321889",
"0.43089247",
"0.43063557",
"0.43024206",
"0.42941543",
"0.42903203",
"0.42836726",
"0.42811945",
"0.4275576",
"0.42723307",
"0.42671543",
"0.42659768",
"0.4262519",
"0.4262454",
"0.42618313",
"0.42610747",
"0.4258276",
"0.42577517",
"0.42576537",
"0.42512614",
"0.42510027",
"0.42467013",
"0.4244478",
"0.42436144",
"0.42423457",
"0.42390934",
"0.423882",
"0.42386764",
"0.42306858",
"0.42244",
"0.42240512",
"0.42230642",
"0.42216346",
"0.42209643",
"0.42168987",
"0.42133972",
"0.42117557"
] | 0.6440572 | 0 |
Write writes a new merchant on DB | func (m *MerchantDataBase) Write(merchant *model.Merchant) error {
statements := []*pipelineStmt{
m.service.newPipelineStmt("INSERT INTO merchants VALUES ($1)", merchant.ID),
}
_, err := m.service.withTransaction(m.service.GetConnection(), func(tx DBTransaction) (*sql.Rows, error) {
_, err := m.service.runPipeline(tx, statements...)
return nil, err
})
if err != nil {
return errors.Wrap(err, "error writing merchant")
}
return nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (uc MerchantController) CreateMerchant(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\n\t//Verify JWT\n\t//tokenIsValid, msgError := auth.ValidateToken(r)\n\t//if tokenIsValid {\n\t//New Merchant from modelsnd\n\tm := models.Merchant{}\n\t// Populate the Merchant data\n\tjson.NewDecoder(r.Body).Decode(&m)\n\t// Add an ObjectId\n\tm.ID = bson.NewObjectId()\n\tvalidated, ValidationMsg := rules.ValidateInsetion(&m)\n\n\tif validated {\n\t\trules.FindSegment(&m)\n\t\tm.Active = true\n\t\t// Insert the Merchant to the mongo\n\t\tuc.session.DB(common.AppSettings.DBName).C(\"Merchant\").Insert(m)\n\t\tlog.Println(\"Inserting Merchant \", m.Name)\n\t\t// Marshal provided interface into JSON structure\n\t\tmj, _ := json.Marshal(m)\n\t\t// Write content-type, statuscode, payload\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusCreated)\n\t\tfmt.Fprintf(w, \"%s\", mj)\n\t} else {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprint(w, ValidationMsg)\n\t}\n\n}",
"func InsertMerchant(db database.MerchantsInterface) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tmerchant := models.Merchant{}\n\n\t\tbody, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\tWriteResponse(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\terr = json.Unmarshal(body, &merchant)\n\t\tif err != nil {\n\t\t\tWriteResponse(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tres, err := db.Insert(merchant)\n\t\tif err != nil {\n\t\t\tWriteResponse(w, http.StatusBadGateway, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tWriteResponse(w, http.StatusOK, res)\n\t}\n}",
"func CreateMerchant(w http.ResponseWriter, r *http.Request) {\n\tvar Merchant CreateM\n\terr := json.NewDecoder(r.Body).Decode(&Merchant)\n\tif err != nil {\n\t\tlogger.Logger().Error(\"Failed to decode JSON\", zap.Error(err))\n\t}\n\tlog.Println(Merchant.DisplayName)\n\tWriteJSON(w, 200, &Merchant, nil)\n}",
"func createMerchant(args []string) {\n\n\tmerchantRepo := merchant.NewRepository(persistence.GetGormClient())\n\tmerchantSVC := merchant.NewMerchantService(merchantRepo)\n\terr := merchantSVC.CreateMerchant(context.Background(), args)\n\tif err != nil {\n\t\tswitch err.Error() {\n\t\tcase \"ERROR: duplicate key value violates unique constraint \\\"merchant_pkey\\\" (SQLSTATE 23505)\":\n\t\t\tfmt.Println(constants.CreateMerchantDuplicateIDErr)\n\t\tcase \"ERROR: duplicate key value violates unique constraint \\\"merchant_email_unique\\\" (SQLSTATE 23505)\":\n\t\t\tfmt.Println(constants.CreateMerchantDuplicateEmailErr)\n\t\tdefault:\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\tfmt.Println(\"Successfully added merchant with name: \" + args[0])\n}",
"func CreateMerchant(svc *psql.PSQL) func(w http.ResponseWriter, r *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\tvar merchant model.Merchant\n\n\t\tunmarshalErr := UnmarshalBody(r, &merchant)\n\t\tif unmarshalErr != nil {\n\t\t\tHandleError(w, unmarshalErr)\n\t\t\treturn\n\t\t}\n\n\t\tout, err := middleware.CreateMerchant(svc, &merchant)\n\t\tif err != nil {\n\t\t\tHandleError(w, err)\n\t\t\treturn\n\t\t}\n\n\t\tCreatedResponseWithBody(w, out)\n\n\t\treturn\n\n\t}\n}",
"func (t *ManageMerchant) createMerchant(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\r\n\tvar err error\r\n\tif len(args) != 10 {\r\n\t\terrMsg := \"{ \\\"message\\\" : \\\"Incorrect number of arguments. Expecting 10\\\", \\\"code\\\" : \\\"503\\\"}\"\r\n\t\terr = stub.SetEvent(\"errEvent\", []byte(errMsg))\r\n\t\tif err != nil {\r\n\t\t\treturn nil, err\r\n\t\t} \r\n\t\treturn nil, nil\r\n\t}\r\n\tfmt.Println(\"start createMerchant\")\r\n\tmerchantID := args[0]\r\n\tmerchantUserName := args[1]\r\n\tmerchantName := args[2]\r\n\tmerchantIndustry := args[3]\r\n\tindustryColor := args[4]\r\n\tpointsPerDollarSpent := args[5]\r\n\texchangeRate := args[6]\r\n\tpurchaseBalance := args[7]\r\n\tmerchantCurrency := args[8]\r\n\tmerchantCU_date := args[9]\r\n\tmerchantAsBytes, err := stub.GetState(merchantID)\r\n\tif err != nil {\r\n\t\treturn nil, errors.New(\"Failed to get Merchant merchantID\")\r\n\t}\r\n\tres := Merchant{}\r\n\tjson.Unmarshal(merchantAsBytes, &res)\r\n\tfmt.Print(\"res: \")\r\n\tfmt.Println(res)\r\n\tif res.MerchantID == merchantID{\r\n\t\tfmt.Println(\"This Merchant arleady exists: \" + merchantID)\r\n\t\tfmt.Println(res);\r\n\t\terrMsg := \"{ \\\"message\\\" : \\\"This Merchant arleady exists\\\", \\\"code\\\" : \\\"503\\\"}\"\r\n\t\terr := stub.SetEvent(\"errEvent\", []byte(errMsg))\r\n\t\tif err != nil {\r\n\t\t\treturn nil, err\r\n\t\t} \r\n\t\treturn nil, nil\t\t\t\t//all stop a Merchant by this name exists\r\n\t}\r\n\t//build the Merchant json string manually\r\n\tmerchant_json := \t`{`+\r\n\t\t`\"merchantId\": \"` + merchantID + `\" , `+\r\n\t\t`\"merchantUserName\": \"` + merchantUserName + `\" , `+\r\n\t\t`\"merchantName\": \"` + merchantName + `\" , `+\r\n\t\t`\"merchantIndustry\": \"` + merchantIndustry + `\" , `+ \r\n\t\t`\"industryColor\": \"` + industryColor + `\" , `+\r\n\t\t`\"pointsPerDollarSpent\": \"` + pointsPerDollarSpent + `\" , `+ \r\n\t\t`\"exchangeRate\": \"` + exchangeRate + `\" , `+ \r\n\t\t`\"purchaseBalance\": \"` + purchaseBalance + `\" , `+\r\n\t\t`\"merchantCurrency\": \"` + merchantCurrency + `\" , `+\r\n\t\t`\"merchantCU_date\": \"` + merchantCU_date + `\" `+ \r\n\t`}`\r\n\tfmt.Println(\"merchant_json: \" + merchant_json)\r\n\tfmt.Print(\"merchant_json in bytes array: \")\r\n\tfmt.Println([]byte(merchant_json))\r\n\terr = stub.PutState(merchantID, []byte(merchant_json))\t\t//store Merchant with merchantId as key\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\t//get the Merchant index\r\n\tmerchantIndexAsBytes, err := stub.GetState(MerchantIndexStr)\r\n\tif err != nil {\r\n\t\treturn nil, errors.New(\"Failed to get Merchant index\")\r\n\t}\r\n\tvar merchantIndex []string\r\n\tjson.Unmarshal(merchantIndexAsBytes, &merchantIndex)\t\t\t\t\t\t\t//un stringify it aka JSON.parse()\r\n\t\r\n\t//append\r\n\tmerchantIndex = append(merchantIndex, merchantID)\t\t\t\t\t\t\t\t\t//add Merchant merchantID to index list\r\n\tfmt.Println(\"! Merchant index after appending merchantID: \", merchantIndex)\r\n\tjsonAsBytes, _ := json.Marshal(merchantIndex)\r\n\tfmt.Print(\"jsonAsBytes: \")\r\n\tfmt.Println(jsonAsBytes)\r\n\terr = stub.PutState(MerchantIndexStr, jsonAsBytes)\t\t\t\t\t\t//store name of Merchant\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\ttosend := \"{ \\\"merchantID\\\" : \\\"\"+merchantID+\"\\\", \\\"message\\\" : \\\"Merchant created succcessfully\\\", \\\"code\\\" : \\\"200\\\"}\"\r\n\terr = stub.SetEvent(\"evtsender\", []byte(tosend))\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t} \r\n\r\n\tfmt.Println(\"end createMerchant\")\r\n\treturn nil, nil\r\n}",
"func (c Client) createMerchant(body io.Reader) (*Merchant, error) {\n\treq, err := http.NewRequest(\"POST\", c.getURL(\"/merchants\"), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar marshalled map[string]*Merchant\n\terr = c.executeRequestAndMarshal(req, &marshalled)\n\treturn marshalled[\"merchant\"], err\n}",
"func (bi *Blockchainidentifier) SaveTransaction(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r.RemoteAddr + \" POST /transactions/new\")\n\n\tvar t transaction\n\n\terr := json.NewDecoder(r.Body).Decode(&t)\n\tif err != nil {\n\t\thttp.Error(w, \"ERROR: \"+err.Error(), 500)\n\t\treturn\n\t}\n\n\tif bi.isValid(t) == false {\n\t\thttp.Error(w, \"ERROR: Missing values in transaction\", 400)\n\t\treturn\n\t}\n\n\tt.Timestamp = time.Now().UTC().Format(\"2006-01-02 15:04:05\")\n\n\tnewblockindex := bi.newTransaction(t)\n\n\tresponseMessage := map[string]string{\n\t\t\"message\": \"Transaction will be added in Block#\" + strconv.Itoa(newblockindex),\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.WriteHeader(http.StatusCreated)\n\tjson.NewEncoder(w).Encode(responseMessage)\n}",
"func (c Client) CreateMerchant(dto MerchantCreateDTO) (*Merchant, error) {\n\tb, err := json.Marshal(dto)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.createMerchant(bytes.NewBuffer(b))\n}",
"func (p *Payment) Save(db XODB) error {\n\tif p.Exists() {\n\t\treturn p.Update(db)\n\t}\n\n\treturn p.Insert(db)\n}",
"func (t *ManageMerchant) updateMerchant(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\r\n\tvar err error\r\n\tfmt.Println(\"Updating Merchant\")\r\n\tif len(args) != 9 {\r\n\t\terrMsg := \"{ \\\"message\\\" : \\\"Incorrect number of arguments. Expecting 9\\\", \\\"code\\\" : \\\"503\\\"}\"\r\n\t\terr = stub.SetEvent(\"errEvent\", []byte(errMsg))\r\n\t\tif err != nil {\r\n\t\t\treturn nil, err\r\n\t\t} \r\n\t\treturn nil, nil\r\n\t}\r\n\t// set merchantId\r\n\tmerchantId := args[0]\r\n\tmerchantAsBytes, err := stub.GetState(merchantId)\t\t\t\t\t\t\t\t\t//get the Merchant for the specified merchant from chaincode state\r\n\tif err != nil {\r\n\t\terrMsg := \"{ \\\"message\\\" : \\\"Failed to get state for \" + merchantId + \"\\\", \\\"code\\\" : \\\"503\\\"}\"\r\n\t\terr = stub.SetEvent(\"errEvent\", []byte(errMsg))\r\n\t\tif err != nil {\r\n\t\t\treturn nil, err\r\n\t\t} \r\n\t\treturn nil, nil\r\n\t}\r\n\tres := Merchant{}\r\n\tjson.Unmarshal(merchantAsBytes, &res)\r\n\tif res.MerchantID == merchantId{\r\n\t\tfmt.Println(\"Merchant found with merchantId : \" + merchantId)\r\n\t\t//fmt.Println(res);\r\n\t\tres.MerchantUserName = args[1]\r\n\t\tres.MerchantName = args[2]\r\n\t\tres.MerchantIndustry = args[3]\r\n\t\tres.IndustryColor = args[4]\r\n\t\tres.PointsPerDollarSpent = args[5]\r\n\t\tres.ExchangeRate = args[6]\r\n\t\tres.PurchaseBalance = args[7]\r\n\t\tres.MerchantCurrency = args[8]\r\n\t\tres.MerchantCU_date = args[9]\r\n\t}else{\r\n\t\terrMsg := \"{ \\\"message\\\" : \\\"\"+ merchantId+ \" Not Found.\\\", \\\"code\\\" : \\\"503\\\"}\"\r\n\t\terr = stub.SetEvent(\"errEvent\", []byte(errMsg))\r\n\t\tif err != nil {\r\n\t\t\treturn nil, err\r\n\t\t} \r\n\t\treturn nil, nil\r\n\t}\r\n\t\r\n\t//build the Merchant json string manually\r\n\torder := \t`{`+\r\n\t\t`\"merchantID\": \"` + res.MerchantID + `\" , `+\r\n\t\t`\"merchantUserName\": \"` + res.MerchantUserName + `\" , `+\r\n\t\t`\"merchantName\": \"` + res.MerchantName + `\" , `+\r\n\t\t`\"merchantIndustry\": \"` + res.MerchantIndustry + `\" , `+ \r\n\t\t`\"industryColor\": \"` + res.IndustryColor + `\" , `+\r\n\t\t`\"pointsPerDollarSpent\": \"` + res.PointsPerDollarSpent + `\" , `+\r\n\t\t`\"exchangeRate\": \"` + res.ExchangeRate + `\" , `+ \r\n\t\t`\"purchaseBalance\": \"` + res.PurchaseBalance + `\" , `+ \r\n\t\t`\"merchantCurrency\": \"` + res.MerchantCurrency + `\" , `+\r\n\t\t`\"merchantCU_date\": \"` + res.MerchantCU_date + `\" `+ \r\n\t\t`}`\r\n\terr = stub.PutState(merchantId, []byte(order))\t\t\t\t\t\t//store Merchant with id as key\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\ttosend := \"{ \\\"merchantId\\\" : \\\"\"+merchantId+\"\\\", \\\"message\\\" : \\\"Merchant details updated succcessfully\\\", \\\"code\\\" : \\\"200\\\"}\"\r\n\terr = stub.SetEvent(\"evtsender\", []byte(tosend))\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t} \r\n\r\n\tfmt.Println(\"Merchant details updated succcessfully\")\r\n\treturn nil, nil\r\n}",
"func (c Client) updateMerchant(id string, body io.Reader) error {\n\tpath := fmt.Sprintf(\"/merchants/%s\", id)\n\treq, err := http.NewRequest(\"PUT\", c.getURL(path), body)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn c.executeRequestAndMarshal(req, nil)\n}",
"func (w *Wallet) put(s *aklib.DBConfig) error {\n\treturn s.DB.Update(func(txn *badger.Txn) error {\n\t\treturn db.Put(txn, []byte(w.AccountName), w, db.HeaderWallet)\n\t})\n}",
"func addTransaction(db meddler.DB, lender *User, debtor *User, amount int, expense *Expense) (*Transaction, error) {\n trans := new(Transaction)\n trans.LenderId = lender.Id\n trans.DebtorId = debtor.Id\n trans.Amount = amount\n trans.Date = expense.Date\n trans.ExpenseId = expense.Id\n\n err := meddler.Insert(db, \"transactions\", trans)\n if err != nil {\n return nil, err\n }\n\n lender.UpdateBalance(db, amount)\n debtor.UpdateBalance(db, -amount)\n\n return trans, nil\n}",
"func (client *Client) WriteTransaction(write TransactionCallback) error {\n\n\t// Start write transaction.\n\tif tx, err := client.Db.Begin(true); err != nil {\n\t\treturn errors.WithStack(err)\n\t} else {\n\t\tsuccess := false\n\t\tdefer DeferRollback(tx, &success)\n\n\t\tif err = write(tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err = tx.Commit(); err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t} else {\n\t\t\tsuccess = true\n\t\t\treturn nil\n\t\t}\n\t}\n}",
"func (wAPI WalletAPI) Save() error {\n\t_, _, err := wAPI.sendRequest(\n\t\t\"PUT\",\n\t\twAPI.Host+\":\"+wAPI.Port+\"/save\",\n\t\t\"\",\n\t)\n\n\treturn err\n}",
"func Store(w http.ResponseWriter, r *http.Request) {\n\tc := flight.Context(w, r)\n\n\t//if !c.FormValid(\"name\") {\n\t//\tCreate(w, r)\n\t//\treturn\n\t//}\n\n\tif !u.IsPositiveInteger(r.FormValue(\"amount\")) {\n\t\tc.FlashNotice(\"Enter valid amount\")\n\t\tCreate(w, r)\n\t\treturn\n\t}\n\n\t_, err := code.Create(c.DB, r.FormValue(\"amount\"), r.FormValue(\"details\"))\n\tif err != nil {\n\t\tc.FlashErrorGeneric(err)\n\t\tCreate(w, r)\n\t\treturn\n\t}\n\n\tc.FlashSuccess(\"Item added.\")\n\tc.Redirect(uri)\n}",
"func (c Client) UpdateMerchant(id string, dto MerchantUpdateDTO) error {\n\tb, err := json.Marshal(dto)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.updateMerchant(id, bytes.NewBuffer(b))\n}",
"func (this *DBHandler) StoreWpa(wpa *Wpa) {\n\tif ! this.isWpaUniqe(wpa.name) {\n\t\tlog.Info(fmt.Sprintf(\"Wpa (%s) already exists, ignoring.\", wpa.name))\n\t\treturn\n\t}\n\n\ttx, err := this.db.Begin()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tstmt, err := tx.Prepare(\"insert into wpa(id, name, bssid) values(null, ?, ?)\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer stmt.Close()\n\t_, err = stmt.Exec(wpa.name, wpa.bssid)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\ttx.Commit()\n}",
"func (u *Usecase) Write(dvice *Device) (id int, err error) {\n\tvar (\n\t\texchanging\t\tbool\n\t\told\t\t\tint\n\t\tlatestExchangeExpiresAt time.Time\n\t\tuserDevices\t\tint\n\t)\n\n\tif err = u.validFields(dvice); err != nil {\n\t\treturn\n\t}\n\n\tif exchanging, old, err = u.user.IsExchanging(dvice.User); err != nil {\n\t\treturn\n\t}\n\n\tif latestExchangeExpiresAt, err = u.user.LatestExchangeExpiresAt(dvice.User); err != nil {\n\t\treturn\n\t}\n\n\tif userDevices, err = u.user.CountDevices(dvice.User); err != nil {\n\t\treturn\n\t}\n\n\tif err = dvice.Valid(userDevices, exchanging, latestExchangeExpiresAt); err != nil {\n\t\treturn\n\t}\n\n\tif exchanging {\n\t\tid, err = u.repo.Exchange(&Device{ID: old}, dvice)\n\t\treturn\n\t}\n\n\tid, err = u.repo.Write(dvice)\n\n\treturn\n}",
"func (c *MySQLClient) Insert(p *purchase.Purchase) error {\n\tif p.ID != 0 {\n\t\treturn fmt.Errorf(\"purchase cannot have a preexisting ID\")\n\t}\n\n\tvar err error\n\tvar buyBytes, sellBytes []byte\n\tif p.BuyOrder != nil {\n\t\tbuyBytes, err = json.Marshal(p.BuyOrder)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to marshal buy order: %v\", err)\n\t\t}\n\t}\n\tif p.SellOrder != nil {\n\t\tsellBytes, err = json.Marshal(p.SellOrder)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to marshal sell order: %v\", err)\n\t\t}\n\t}\n\n\tquery := `INSERT INTO trader_one(buy_order, sell_order) VALUES (?, ?)`\n\tctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancelFunc()\n\tstmt, err := c.db.PrepareContext(ctx, query)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to prepare SQL statement: %v\", err)\n\t}\n\tdefer stmt.Close()\n\n\tres, err := stmt.ExecContext(ctx, jsonString(buyBytes), jsonString(sellBytes))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to insert row: %v\", err)\n\t}\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to find new ID: %v\", err)\n\t}\n\tp.ID = id\n\treturn nil\n}",
"func (payment *PayPalPayment) Save() {\n\tDB.Set(\"PayPalPayment\", payment.ID, payment)\n}",
"func write(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tvar receipt Receipt\n\tvar err error\n\tfmt.Println(\"starting write\")\n\n\tif len(args[0]) == 0 {\n\t\treturn shim.Error(\"wrong arguments\")\n\t}\n\n\treceiptJson := []byte(args[0])\n\terr = json.Unmarshal(receiptJson, &receipt)\n\tif err != nil {\n\t\tfmt.Println(\"json is wrong,json is: \" + args[0])\n\t\treturn shim.Error(err.Error())\n\t}\n\n\t//check if new owner exists\n\towner, err := getOwner(stub, receipt.OwnerRelation.Id)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to find owner - \" + owner.Id)\n\t\treturn shim.Error(err.Error())\n\t}\n\n\t//check if new receipt exists\n\terr = checkReceipt(stub, receipt.Id)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to create receipt - \" + receipt.Id)\n\t\treturn shim.Error(err.Error())\n\t}\n\n\terr = stub.PutState(receipt.Id, receiptJson) //write the variable into the ledger\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tfmt.Println(\"- end write\")\n\treturn shim.Success(nil)\n}",
"func (c Client) createTransaction(merchantID string, body io.Reader) (*TransactionID, error) {\n\tpath := fmt.Sprintf(\"/merchants/%s/transactions\", merchantID)\n\treq, err := http.NewRequest(\"POST\", c.getURL(path), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar marshalled map[string]*TransactionID\n\treturn marshalled[\"transaction\"], c.executeRequestAndMarshal(req, &marshalled)\n}",
"func (ps *Store) Write(ctx context.Context, entity datastore.Entity) error {\n\tc := GetCon(ctx)\n\temd := entity.GetEntityMetadata()\n\tjson := datastore.ToJSON(entity).String()\n\terr := c.Query(getJSONInsert(emd.GetName()), json).Exec()\n\treturn err\n}",
"func (uc MerchantController) GetMerchant(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\n\t//Verify JWT\n\t//tokenIsValid, msgError := auth.ValidateToken(r)\n\n\t//if tokenIsValid {uc\n\t//Get parameter id\n\tid := p.ByName(\"id\")\n\n\t// Verify id is ObjectId\n\tif !bson.IsObjectIdHex(id) {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprint(w, \"Invalid ID\")\n\t\treturn\n\t}\n\n\t//Get the verified ID\n\tidMongo := bson.ObjectIdHex(id)\n\t//New Merchant from models\n\tm := models.Merchant{}\n\n\t// Fetch Merchant\n\tif err := uc.session.DB(common.AppSettings.DBName).C(\"Merchant\").FindId(idMongo).One(&m); err != nil {\n\t\tif fmt.Sprint(err) == \"not found\" {\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t} else {\n\t\t\tlog.Fatal(\"Erro ao buscar o usuário\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tprintln(\"BUSCOU = \", m.ID)\n\n\tuj, _ := json.Marshal(m)\n\t// Write content-type, statuscode, payload\n\tw.Header().Set(\"Content\t\tuj, _ := json.Marshal(u) -Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprintf(w, \"%s\", uj)\n\t// } else {\n\t// \t//If Token was reject\n\t// \tw.WriteHeader(http.StatusUnautCPFhorized)\n\t// \tfmt.Fprint(w, msgError)\n\t// }\n}",
"func (sl sale) Save(sale entities.Sales) {\n\tcollection := clientDB.Database(\"cashback\").Collection(\"sales\")\n\n\tctx, cancel := context.WithCancel(ctxDB)\n\tdefer cancel()\n\n\t_, err := collection.InsertOne(ctx, sale)\n\ttools.FatalError(err, \"Error to save effected sale\")\n}",
"func (env *Env) CreatePayment(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"POST payment\")\n\n\ttx := &model.TX{}\n\terr := render.DecodeJSON(r.Body, &tx)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error deserialising payment: %v\\n\", err)\n\t\trender.Status(r, http.StatusBadRequest)\n\t\trender.JSON(w, r, err)\n\t\treturn\n\t}\n\n\ttx, err = env.db.CreateTX(*tx)\n\tif err != nil {\n\t\tlog.Printf(\"Error creating payment: %v\\n\", err)\n\t\trender.Status(r, http.StatusMethodNotAllowed)\n\t\trender.JSON(w, r, err)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n}",
"func (s *PaymentStorage) Create(\n\tctx context.Context,\n\tid aggregate.ID,\n\tversion transaction.Version,\n\torganisationID transaction.OrganisationID,\n\tattributes interface{},\n) error {\n\tlogger := log.FromContext(ctx)\n\n\tquery := `INSERT INTO %[1]s (id, version, organisation_id, attributes) VALUES ($1, $2, $3, $4)`\n\tquery = fmt.Sprintf(query, s.table)\n\n\tif logger != nil {\n\t\tlogger.Debugf(\"exec in transaction sql %s, values %+v\", query, []interface{}{\n\t\t\tid,\n\t\t\tversion,\n\t\t\torganisationID,\n\t\t\tattributes,\n\t\t})\n\t}\n\n\treturn execInTransaction(s.db, func(tx *sqlx.Tx) error {\n\t\t_, err := tx.ExecContext(ctx, query, id, version, organisationID, attributes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n}",
"func (c Client) addAppToMerchant(merchantID string, appID string) error {\n\tdata := []byte(fmt.Sprintf(`{\"appId\":\"%s\"}`, appID))\n\tpath := fmt.Sprintf(\"/merchants/%s/apps\", merchantID)\n\treq, err := http.NewRequest(\"POST\", c.getURL(path), bytes.NewBuffer(data))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.executeRequestAndMarshal(req, nil)\n}",
"func (model *Trade) Write() error {\n\tstart := time.Now()\n\tcsm := model.buildCsm()\n\terr := executor.WriteCSM(*csm, true)\n\tmodel.WriteTime = time.Since(start)\n\tif err != nil {\n\t\tlog.Error(\"Failed to write trades for %s (%+v)\", model.Key(), err)\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func WriteBlock(chain uint64, data []byte) error {\n\tkey := runtime.GetHash(data)\n\texist := runtime.DbExist(dbBlockData{}, chain, key)\n\tif exist {\n\t\treturn nil\n\t}\n\n\treturn runtime.AdminDbSet(dbBlockData{}, chain, key, data, 2<<50)\n}",
"func saveBlockChainToDb(chain BlockChain) error {\r\n\tdb := gofiledb.GetClient()\r\n\treturn db.SetStruct(\"blockchain\", \"blockchain_v1\", chain)\r\n}",
"func writeToStore() {\n\tf, err := os.OpenFile(DBFile, os.O_APPEND|os.O_WRONLY, 0600)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer f.Close()\n\tif _, err := f.WriteString(strings.Join(passGenerator(), \"\") + \",\" + createSecrets() + \"\\n\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}",
"func (pmt *Payment) Create(db *bolt.DB) error {\n\terr := db.Update(func(tx *bolt.Tx) error {\n\t\tbkt, err := fetchPaymentBucket(tx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tb, err := json.Marshal(pmt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tid := paymentID(pmt.Height, pmt.CreatedOn, pmt.Account)\n\t\treturn bkt.Put(id, b)\n\t})\n\treturn err\n}",
"func (s *CqlStore) Write(item Item) error {\n\tif item.IsEmpty() {\n\t\treturn NewEmptyItemError()\n\t}\n\tif s.session == nil {\n\t\treturn NewStoreClosedError()\n\t}\n\tb, err := json.Marshal(item.Contents)\n\tif err != nil {\n\t\treturn NewItemMarshallError(err)\n\t}\n\terr = s.session.Query(\"insert into items (id, updated, status, type, name, contents) values(?,now(),?,?,?,?)\",\n\t\tIDToString(item.ID), \"ALIVE\", item.Type, item.Name, string(b)).Exec()\n\tif err != nil {\n\t\treturn errors.Wrap(err, 0)\n\t}\n\treturn nil\n}",
"func (a *paymentUsecase) Store(c context.Context, m *models.Payment) (*models.Payment, error) {\n\tctx, cancel := context.WithTimeout(c, a.contextTimeout)\n\tdefer cancel()\n\n\tif existedPayment, _ := a.GetByPaymentID(ctx, m.PaymentID); existedPayment != nil {\n\t\treturn nil, models.ErrConflict\n\t}\n\n\tid, err := a.repo.Store(ctx, m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm.ID = id\n\treturn m, nil\n}",
"func handleWriteBlock(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar m model.Message\n\n\t// Decode http request into message struct\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&m); err != nil {\n\t\trespondWithJSON(w, r, http.StatusBadRequest, r.Body)\n\t\treturn\n\t}\n\n\t// checks if the password is correct\n\t// if !authenticate(m.Password) {\n\t// \trespondWithJSON(w, r, http.StatusUnauthorized, r.Body)\n\t// }\n\n\tdefer r.Body.Close()\n\n\t//ensure atomicity when creating new block\n\tvar mutex = &sync.Mutex{}\n\tmutex.Lock()\n\tnewBlock := blockchainhelpers.GenerateBlock(model.Blockchain[len(model.Blockchain)-1], m.BPM)\n\tmutex.Unlock()\n\n\tif blockchainhelpers.IsBlockValid(newBlock, model.Blockchain[len(model.Blockchain)-1]) {\n\t\tmodel.Blockchain = append(model.Blockchain, newBlock)\n\t\tspew.Dump(model.Blockchain)\n\t}\n\n\trespondWithJSON(w, r, http.StatusCreated, newBlock)\n\n}",
"func (db *Database) SaveWriter(w io.Writer, passphrase string) error {\n\t// new random values\n\tsalt, err := utils.SecureRandBytes(saltLen)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb1, err := utils.SecureRandBytes(b1Len)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb2, err := utils.SecureRandBytes(b2Len)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb3, err := utils.SecureRandBytes(b3Len)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb4, err := utils.SecureRandBytes(b4Len)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tiv, err := utils.SecureRandBytes(ivLen)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// create a digest of all the record data.\n\thm := hmac.New(sha256.New, append(b3, b4...))\n\n\tvar records bytes.Buffer\n\tif err = appendFields(hm, &records, db.header.fields); err != nil {\n\t\treturn IOError.Wrap(err)\n\t}\n\tfor _, record := range db.records {\n\t\tif err = appendFields(hm, &records, record.fields); err != nil {\n\t\t\treturn IOError.Wrap(err)\n\t\t}\n\t}\n\n\t// generate encryption key\n\tpkey, phash := makeKey(passphrase, salt, hashIterations)\n\n\t// encrypt keys\n\tkey_cipher, err := twofish.NewCipher(pkey)\n\tif err != nil {\n\t\treturn Error.New(\"unable to create key cipher: %s\", err)\n\t}\n\n\t// encrypt records\n\trecords_cipher, err := twofish.NewCipher(append(b1, b2...))\n\tif err != nil {\n\t\treturn Error.New(\"unable to create records cipher: %s\", err)\n\t}\n\trecords_encrypter := cipher.NewCBCEncrypter(records_cipher, iv)\n\n\traw_records := records.Bytes()\n\trecords_encrypter.CryptBlocks(raw_records, raw_records)\n\n\tkey_cipher.Encrypt(b1, b1)\n\tkey_cipher.Encrypt(b2, b2)\n\tkey_cipher.Encrypt(b3, b3)\n\tkey_cipher.Encrypt(b4, b4)\n\n\t// write it all out\n\t_, err = w.Write([]byte(v3Tag))\n\tif err != nil {\n\t\treturn IOError.Wrap(err)\n\t}\n\n\t_, err = w.Write(salt)\n\tif err != nil {\n\t\treturn IOError.Wrap(err)\n\t}\n\n\terr = binary.Write(w, binary.LittleEndian, hashIterations)\n\tif err != nil {\n\t\treturn IOError.Wrap(err)\n\t}\n\n\t_, err = w.Write(phash)\n\tif err != nil {\n\t\treturn IOError.Wrap(err)\n\t}\n\n\t_, err = w.Write(b1)\n\tif err != nil {\n\t\treturn IOError.Wrap(err)\n\t}\n\n\t_, err = w.Write(b2)\n\tif err != nil {\n\t\treturn IOError.Wrap(err)\n\t}\n\n\t_, err = w.Write(b3)\n\tif err != nil {\n\t\treturn IOError.Wrap(err)\n\t}\n\n\t_, err = w.Write(b4)\n\tif err != nil {\n\t\treturn IOError.Wrap(err)\n\t}\n\n\t_, err = w.Write(iv)\n\tif err != nil {\n\t\treturn IOError.Wrap(err)\n\t}\n\n\t_, err = w.Write(raw_records)\n\tif err != nil {\n\t\treturn IOError.Wrap(err)\n\t}\n\n\t_, err = w.Write([]byte(v3EOF))\n\tif err != nil {\n\t\treturn IOError.Wrap(err)\n\t}\n\n\t_, err = w.Write(hm.Sum(nil))\n\tif err != nil {\n\t\treturn IOError.Wrap(err)\n\t}\n\n\treturn nil\n}",
"func (m *Merchant) Update() *MerchantUpdateOne {\n\treturn (&MerchantClient{config: m.config}).UpdateOne(m)\n}",
"func (a *userMerchantHandler) CreateUserMerchant(c echo.Context) error {\n\tc.Request().Header.Set(\"Access-Control-Allow-Headers\", \"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization\")\n\tc.Response().Header().Set(\"Access-Control-Allow-Headers\", \"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization\")\n\ttoken := c.Request().Header.Get(\"Authorization\")\n\n\tif token == \"\" {\n\t\treturn c.JSON(http.StatusUnauthorized, models.ErrUnAuthorize)\n\t}\n\tmerchantCommand := models.NewCommandUserMerchant{\n\t\tId: c.FormValue(\"id\"),\n\t\tFullName: c.FormValue(\"full_name\"),\n\t\tEmail: c.FormValue(\"email\"),\n\t\tPassword: c.FormValue(\"password\"),\n\t\tPhoneNumber : c.FormValue(\"phone_number\"),\n\t\tMerchantId:c.FormValue(\"merchant_id\"),\n\t}\n\tif ok, err := isRequestValid(&merchantCommand); !ok {\n\t\treturn c.JSON(http.StatusBadRequest, err.Error())\n\t}\n\tctx := c.Request().Context()\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tresponse,error := a.userMerchantUsecase.Create(ctx, &merchantCommand, token)\n\n\tif error != nil {\n\t\treturn c.JSON(getStatusCode(error), ResponseError{Message: error.Error()})\n\t}\n\treturn c.JSON(http.StatusOK, response)\n}",
"func (h *Handler) SendSecret(\n transaction *entityApi.Transaction,\n companyChainID string,\n certificateUuid string,\n) (*entityApi.TransactionStatus, error) {\n data, err := json.Marshal(transaction)\n\n if err != nil {\n return nil, err\n }\n\n return h.SendTransaction(fmt.Sprintf(secretCertifyRoute, companyChainID, certificateUuid), data)\n}",
"func (cs *CreditStore) SaveCredit(credit Credit) error {\n\tconn, err := cs.OpenDB(context.Background()) // Abrimos conexión con la config principal.\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer conn.Close(context.Background())\n\t_, err = conn.Exec(\n\t\tcontext.Background(),\n\t\t`call insert_credit($1, $2, $3, $4, $5)`,\n\t\tcredit.Investment, credit.Credit_type_300, credit.Credit_type_500, credit.Credit_type_700, credit.Successful)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func (c *cacheableStoreMock) Write() error {\n\treturn c.err\n}",
"func (h *CustomerHandler) setCustomer(r res.CallRequest) {\n\t// Create a store write transaction.\n\ttxn := h.CustomerStore.Write(r.PathParam(\"id\"))\n\tdefer txn.Close()\n\n\t// Get customer value from store\n\tv, err := txn.Value()\n\tif err != nil {\n\t\tr.Error(err)\n\t\treturn\n\t}\n\tcustomer := v.(Customer)\n\n\t// Parse parameters\n\tvar p struct {\n\t\tName *string `json:\"name\"`\n\t\tEmail *string `json:\"email\"`\n\t\tCountry *string `json:\"country\"`\n\t}\n\tr.ParseParams(&p)\n\n\t// Set the provided fields\n\tif p.Name != nil {\n\t\tcustomer.Name = *p.Name\n\t}\n\tif p.Email != nil {\n\t\tcustomer.Email = *p.Email\n\t}\n\tif p.Country != nil {\n\t\tcustomer.Country = *p.Country\n\t}\n\n\t// Trim and validate fields\n\terr = customer.TrimAndValidate()\n\tif err != nil {\n\t\tr.Error(err)\n\t\treturn\n\t}\n\n\t// Update customer in store.\n\t// This will produce a change event and a customers query collection event,\n\t// if any indexed fields were updated.\n\terr = txn.Update(customer)\n\tif err != nil {\n\t\tr.Error(err)\n\t\treturn\n\t}\n\n\t// Send success response\n\tr.OK(nil)\n}",
"func (f *FakeClient) Insert(p *purchase.Purchase) error {\n\treturn nil\n}",
"func (bc *BoltClient) Set(name string) error {\n\t// id := uuid.NewV4().String()\n\tidUUIDObj, err := uuid.NewV4()\n\tif err != nil {\n\t\treturn err\n\t}\n\tid := idUUIDObj.Bytes()\n\n\t// acc := Account{\n\t// \tID: id,\n\t// \tName: name,\n\t// }\n\t// jsonBytes, _ := json.Marshal(acc)\n\terr = bc.boltDB.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(bc.BucketName))\n\t\t// err := b.Put([]byte(name), jsonBytes)\n\t\terr := b.Put([]byte(name), id)\n\t\treturn err\n\t})\n\treturn err\n}",
"func (c *Customer) Save(ctx context.Context, db DB) error {\n\tif c.Exists() {\n\t\treturn c.Update(ctx, db)\n\t}\n\treturn c.Insert(ctx, db)\n}",
"func (t *Transaction) Store() error {\n\terr := database.DB.Create(&t).Error\n\treturn err\n}",
"func(db *Persistence) CreateNewApplication(appName, description, redirect string,\n trimName bool) error {\n\n log.Debug(\"adding new application to datbase...\")\n appId := uuid.New()\n\n query := `INSERT INTO applications(application_id,application_name,description,\n redirect_url,trim_app_name) VALUES($1,$2,$3,$4,$5)`\n _, err := db.Session.Exec(context.Background(), query, appId, appName, description,\n redirect, trimName)\n return err\n}",
"func paymentCreate(service payment.UseCase) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer r.Body.Close()\n\t\tvar p *entity.Payment\n\t\terr := json.NewDecoder(r.Body).Decode(&p)\n\t\tif err != nil {\n\t\t\trespondWithError(w, http.StatusBadRequest, \"Invalid request payload\")\n\t\t\treturn\n\t\t}\n\t\tp.ID, err = service.Store(p)\n\t\tif err != nil {\n\t\t\trespondWithError(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\t\trespondWithJSON(w, http.StatusCreated, p)\n\t})\n}",
"func (m *mahasiswaUsecase) Store(c context.Context, dm *domain.Mahasiswa) (err error) {\n\tctx, cancel := context.WithTimeout(c, m.contextTimeout)\n\tdefer cancel()\n\t\n\t// Cek jika ada NIM yg sama\n\texistedMahasiswa, _ := m.GetByNIM(ctx, dm.Nim)\n\tif existedMahasiswa != (domain.Mahasiswa{}) {\n\t\treturn domain.ErrConflict\n\t}\n\n\terr = m.mahasiswaRepo.Store(ctx, dm)\n\treturn\n}",
"func (s *PostgresWalletStorage) StoreTransaction(transaction *types.Transaction) (*types.Transaction, error) {\n\tvar existingTransaction *types.Transaction\n\tvar err error\n\n\ttxIsNew := true\n\n\tif transaction.ID != uuid.Nil {\n\t\texistingTransaction, err = s.GetTransactionByID(transaction.ID)\n\t\tswitch err {\n\t\tcase nil: // tx already in database\n\t\t\ttxIsNew = false\n\t\tcase sql.ErrNoRows: // new tx\n\t\tdefault:\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif txIsNew && transaction.Hash != \"\" {\n\t\texistingTransaction, err = s.GetTransactionByHashDirectionAndAddress(transaction)\n\t\tswitch err {\n\t\tcase nil: // tx already in database\n\t\t\ttxIsNew = false\n\t\tcase sql.ErrNoRows: // new tx\n\t\tdefault:\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif !txIsNew {\n\t\t_, err := s.db.Exec(`UPDATE transactions SET hash = $1, block_hash = $2,\n\t\t\tconfirmations = $3, status = $4 WHERE id = $5`,\n\t\t\ttransaction.Hash,\n\t\t\ttransaction.BlockHash,\n\t\t\ttransaction.Confirmations,\n\t\t\ttransaction.Status.String(),\n\t\t\texistingTransaction.ID,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Update of tx data in DB failed: %s. Tx %#v\",\n\t\t\t\terr, transaction)\n\t\t}\n\t\texistingTransaction.Update(transaction)\n\t\treturn existingTransaction, nil\n\t}\n\n\tif transaction.ID == uuid.Nil {\n\t\tif transaction.Direction == types.OutgoingDirection {\n\t\t\tlog.Printf(\n\t\t\t\t\"Warning: generating new id for new unseen outgoing tx. \"+\n\t\t\t\t\t\"This should not happen because outgoing transactions are\"+\n\t\t\t\t\t\" generated by us. Tx: %v\",\n\t\t\t\ttransaction,\n\t\t\t)\n\t\t\tdebug.PrintStack()\n\t\t}\n\t\ttransaction.ID = uuid.Must(uuid.NewV4())\n\t}\n\tmetainfoJSON, err := json.Marshal(transaction.Metainfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tquery := fmt.Sprintf(`INSERT INTO transactions (%s)\n\t\t\tVALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)`,\n\t\ttransactionFields,\n\t)\n\t_, err = s.db.Exec(\n\t\tquery,\n\t\ttransaction.ID,\n\t\ttransaction.Hash,\n\t\ttransaction.BlockHash,\n\t\ttransaction.Confirmations,\n\t\ttransaction.Address,\n\t\ttransaction.Direction.String(),\n\t\ttransaction.Status.String(),\n\t\ttransaction.Amount,\n\t\tstring(metainfoJSON),\n\t\ttransaction.Fee,\n\t\ttransaction.FeeType.String(),\n\t\ttransaction.ColdStorage,\n\t\ttransaction.ReportedConfirmations,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to insert new tx into DB: %s. Tx %#v\",\n\t\t\terr, transaction)\n\t}\n\treturn transaction, nil\n}",
"func (pmt *Payment) Update(db *bolt.DB) error {\n\treturn pmt.Create(db)\n}",
"func (transmission *Transmission) Save(context DatabaseService) error {\n\tvar err error\n\tif transmission.ID == 0 {\n\t\terr = context.Insert(transmission)\n\t} else {\n\t\terr = context.Update(transmission)\n\t}\n\n\treturn err\n}",
"func (repo *trepo) SaveTransaction(id uint64, data string) {\n\trepo.transactions[id] = data\n}",
"func (h *TransactionHandler) sendTransaction(userbank_id int, transaction_id int, totalAmount int) error {\r\n\tjsonW := &SendTransaction{\r\n\t\tUserBankID: userbank_id,\r\n\t\tTransactionID: transaction_id,\r\n\t\tAmount: totalAmount,\r\n\t}\r\n\r\n\tjsonR, _ := json.Marshal(jsonW)\r\n\tjsonStr := []byte(string(jsonR))\r\n\r\n\treq, _ := http.NewRequest(\"POST\", h.Config.BankAPIUrl+\"/transaction\", bytes.NewBuffer(jsonStr))\r\n\treq.Header.Set(\"Content-Type\", \"application/json\")\r\n\r\n\tclient := &http.Client{}\r\n\t_, err2 := client.Do(req)\r\n\r\n\tif err2 != nil {\r\n\t\treturn errors.New(\"Gagal menghubungkan ke server 2\")\r\n\t}\r\n\r\n\treturn nil\r\n}",
"func (s *service) Create(p *Payment) error {\n\tp.ID = uuid.NewV4().String()\n\treturn s.persist(p)\n}",
"func update(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tvar receipt Receipt\n\tvar err error\n\tfmt.Println(\"starting write\")\n\n\tif len(args[0]) == 0 {\n\t\treturn shim.Error(\"wrong arguments\")\n\t}\n\n\treceiptJson := []byte(args[0])\n\terr = json.Unmarshal(receiptJson, &receipt)\n\tif err != nil {\n\t\tfmt.Println(\"json is wrong,json is: \" + args[0])\n\t\treturn shim.Error(err.Error())\n\t}\n\n\t//check if new owner exists\n\towner, err := getOwner(stub, receipt.OwnerRelation.Id)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to find owner - \" + owner.Id)\n\t\treturn shim.Error(err.Error())\n\t}\n\n\terr = stub.PutState(receipt.Id, receiptJson) //write the variable into the ledger\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tfmt.Println(\"- end write\")\n\treturn shim.Success(nil)\n}",
"func (uc MerchantController) InactivateMerchant(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\n\t// Get parameter id\n\tid := p.ByName(\"id\")\n\n\t// Verify id is ObjectId\n\tif !bson.IsObjectIdHex(id) {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprint(w, \"Invalid ID\")\n\t\treturn\n\t}\n\n\t// Get verified parameter id\n\tidMongo := bson.ObjectIdHex(id)\n\tchange := bson.M{\"$set\": bson.M{\"active\": false}}\n\n\t// Remove Merchant\n\tif err := uc.session.DB(common.AppSettings.DBName).C(\"Merchant\").UpdateId(idMongo, change); err != nil {\n\t\tif fmt.Sprint(err) == \"not found\" {\n\t\t\tprintln(\"TESTE RICARDO - Não encontrou!!!\")\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t} else {\n\t\t\tlog.Fatal(\"Erro ao desativar o usuário\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\t// Write status\n\tw.WriteHeader(200)\n}",
"func (store *InMemoryStore) Create(payment *api.Payment) error {\n\tif payment.ID == \"\" {\n\t\tpayment.ID = uuid.New().String()\n\t}\n\tstore.lock.Lock()\n\tdefer store.lock.Unlock()\n\n\tstore.data[payment.ID] = payment\n\n\treturn nil\n}",
"func CreateCustomer(tx db.Tx, w http.ResponseWriter, r *http.Request) {\n\tif r.FormValue(\"auth\") != config.Get(\"galaAPIKey\") {\n\t\thttp.Error(w, \"401 Unauthorized\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\tname, email, card := r.FormValue(\"name\"), r.FormValue(\"email\"), r.FormValue(\"card\")\n\tcustomer, pmtmeth, desc, problem := stripe.CreateCustomer(name, email, card)\n\tif problem != \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tio.WriteString(w, problem)\n\t\treturn\n\t}\n\tif customer == \"\" {\n\t\thttp.Error(w, \"500 Internal Server Error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tjw := new(jwriter.Writer)\n\tjw.RawString(`{\"customer\":`)\n\tjw.String(customer)\n\tjw.RawString(`,\"method\":`)\n\tjw.String(pmtmeth)\n\tjw.RawString(`,\"description\":`)\n\tjw.String(desc)\n\tjw.RawByte('}')\n\tjw.DumpTo(w)\n}",
"func Write(inType SimpleDbType, dbMgr *mgr.DBConn) SimpleDbType {\n\tdb := dbMgr.Open()\n\tsqlStatement := \"INSERT INTO test_table (name, number) VALUES ($1, $2) RETURNING id\"\n\tid := 0\n\t// Do the insert and query for the ID\n\terr := db.QueryRow(sqlStatement, inType.Name, inType.Number).Scan(&id)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn Read(int32(id), dbMgr)\n}",
"func addPayment(c *gin.Context) {\n\tpaymentsDB, err := setup(paymentsStorage)\n\n\t//connect to db\n\tif err != nil {\n\t\tlogHandler.Error(\"problem connecting to database\", log.Fields{\"dbname\": paymentsStorage.Cfg.Db, \"func\": \"addPayment\"})\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": \"Problem connecting to db\"})\n\t\treturn\n\t}\n\tdefer paymentsDB.Close()\n\n\tvar p storage.Payments\n\terr = c.BindJSON(&p)\n\n\terr = paymentsDB.CreatePayment(&p)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": \"Could not add a payment\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"status\": \"success\", \"message\": \"Payment created\"})\n}",
"func (s *Shop) Save() (*Shop, error) {\n\tif err := DB.Create(&s).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn s, nil\n}",
"func (t *Driver) Write(col string, key string, i interface{}) error {\n err := t.TryCreateTable(col)\n if err != nil {\n return err\n }\n \n raw, err := json.MarshalIndent(i, \"\", \"\\t\")\n if err != nil {\n return err\n }\n \n xxh := xxhash.Sum64(append(raw, []byte(key)...))\n \n /// FIXME: Table name should be escaped.\n _, err = t.DB().Execute(fmt.Sprintf(\"INSERT INTO `%s` (id, j, xxh) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE j=?, xxh=?\", t.TableName(col)), key, raw, xxh, raw, xxh)\n \n if t.AfterUpdateFunc != nil {\n t.AfterUpdateFunc(col, key, i)\n }\n \n return err\n}",
"func (env *Env) UpdatePayment(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"PUT payment\")\n\n\ttx := &model.TX{}\n\terr := render.DecodeJSON(r.Body, &tx)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error deserialising payment: %v\\n\", err)\n\t\trender.Status(r, http.StatusBadRequest)\n\t\trender.JSON(w, r, err)\n\t\treturn\n\t}\n\n\t// First try and update\n\ttxUpdate, err := env.db.UpdateTX(*tx)\n\n\t// Update success\n\tif err == nil {\n\t\trender.Status(r, http.StatusOK)\n\t\trender.JSON(w, r, txUpdate)\n\t\treturn\n\t}\n\n\t// It's ok not to find the transaction to update\n\tif _, ok := err.(*model.TXNotFound); !ok {\n\t\tlog.Printf(\"Error updating payment: %v\\n\", err)\n\t\trender.Status(r, http.StatusMethodNotAllowed)\n\t\trender.JSON(w, r, err)\n\t\treturn\n\t}\n\ttx, err = env.db.CreateTX(*tx)\n\tif err != nil {\n\t\tlog.Printf(\"Error creating payment: %v\\n\", err)\n\t\trender.Status(r, http.StatusMethodNotAllowed)\n\t\trender.JSON(w, r, err)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n}",
"func (c *Collection) Write(tx *sql.Tx, dialect SQLDialect) (sql.Result, error) {\n\tstatement := dialect.InsertStatement(`collection (id, title, volume, publication_year, edition, collector_id, oclc, lccn, isbn)\n\tVALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`)\n\tfmt.Println(c)\n\treturn tx.Exec(\n\t\tstatement,\n\t\tc.ID,\n\t\tc.Title,\n\t\tc.Volume,\n\t\tc.PublicationYear,\n\t\tc.Edition,\n\t\tc.CollectorID,\n\t\tc.OCLC,\n\t\tc.LCCN,\n\t\tc.ISBN,\n\t)\n}",
"func send(\n\tclient *http.Client,\n\tappservice config.ApplicationService,\n\ttxnID int,\n\ttransaction []byte,\n) (err error) {\n\t// PUT a transaction to our AS\n\t// https://matrix.org/docs/spec/application_service/r0.1.2#put-matrix-app-v1-transactions-txnid\n\taddress := fmt.Sprintf(\"%s/transactions/%d?access_token=%s\", appservice.URL, txnID, url.QueryEscape(appservice.HSToken))\n\treq, err := http.NewRequest(\"PUT\", address, bytes.NewBuffer(transaction))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer checkNamedErr(resp.Body.Close, &err)\n\n\t// Check the AS received the events correctly\n\tif resp.StatusCode != http.StatusOK {\n\t\t// TODO: Handle non-200 error codes from application services\n\t\treturn fmt.Errorf(\"non-OK status code %d returned from AS\", resp.StatusCode)\n\t}\n\n\treturn nil\n}",
"func(r *PaymentBDRepository)AddPayment(userIDHex string, payment models.Payment)(models.Payment,error){\n\n\tvar response models.Payment\n\tuser := models.User{}\n\n\tpayment.Status = core.StatusActive\n/*\n\tvar queryFind = bson.M{\n\t\t\"_id\": bson.ObjectId(userIDHex),\n\t\t\"payments\": bson.M{ \n\t\t\t\"$elemMatch\": bson.M{ \n\t\t\t\t\"card_number\": payment.CardNumber,\n\t\t\t\t},\n\t\t},\n\t}\n*/\n\tvar queryAdd = bson.M{ \n\t\t\t\"$addToSet\": bson.M{ \n\t\t\t\t\"payments\": payment,\n\t\t\t},\n\t}\n/*\n\tvar queryUpdate = bson.M{\n\t\t\"$set\":bson.M{\n\t\t\t\"payment\": bson.M{\n\t\t\t\t\"payment_type\":\"credit_card\",\n\t\t\t\t\"card_number\": \"xxxxxxxxxxxxxxxx\",\n\t\t\t\t\"cvv\":\"xxx\",\n\t\t\t\t\"end_date\": \"01/19\",\n\t\t\t\t\"user_name\": nil,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\t*/\n\n\tsession ,err := mgo.Dial(core.DBUrl)\n\tif err!=nil{\n\t\tfmt.Printf(\"AddPayment error session %s \\n\",err)\n\t\treturn response,err\n\t}\n/*\n\t// Find user with payment in DB\n\terr = session.DB(core.DBName).C(user.GetDocumentName()).FindId(bson.ObjectId(userIDHex)).One(&user)\n\tif err != nil{\n\t\tfmt.Printf(\"AddPayment: Error Finding user %s \\n\",err.Error())\n\t\treturn response,err\n\t}\n\t*/\n\n\t// Appends payment in user model\n\terr = session.DB(core.DBName).C(user.GetDocumentName()).UpdateId(bson.ObjectIdHex(userIDHex),queryAdd)\n\tif err != nil{\n\t\tfmt.Printf(\"AddPayment: Error updating %s \\n\",err.Error())\n\t\treturn response,err\n\t}\n\n\tdefer session.Close()\n\n\treturn payment,nil\n}",
"func CreateTransaction(resp http.ResponseWriter, req *http.Request) {\n\tresp.Header().Add(\"Content-Type\", \"application/json\")\n\tvar transaction domain.Transaction\n\tdecoder := json.NewDecoder(req.Body)\n\n\terr := decoder.Decode(&transaction)\n\n\tif err != nil {\n\t\thttp.Error(resp, \"Bad Request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tapiErr := service.CreateTransaction(transaction)\n\n\tif apiErr != nil {\n\t\tresp.WriteHeader(http.StatusInternalServerError)\n\t\tencoder := json.NewEncoder(resp)\n\t\tencoder.Encode(apiErr)\n\t}\n\n\tresp.WriteHeader(http.StatusOK)\n\n\tjsonValue, _ := json.Marshal(utils.AppMsgs{http.StatusOK, \"Transaction was recorded\"})\n\n\tresp.Write(jsonValue)\n\n}",
"func (w *InfluxDbWriter) Write(batch influxdb_client.BatchPoints) error {\n\t// Write to the DB\n\tstart := time.Now()\n\terr := w.client.Write(batch)\n\telapsed := time.Since(start).Seconds()\n\tif err != nil {\n\t\tlog.Println(\"DB write failed after:\", elapsed, \"seconds\")\n\t\treturn err\n\t}\n\t// Only track write delay for successes\n\tlog.Println(\"DB write completed in:\", elapsed, \"seconds\")\n\t// TODO(dmar): Log rate of `db_write_delay`\n\treturn nil\n}",
"func Write(ctx context.Context, store storage.Store, txn storage.Transaction) error {\n\n\tif err := storage.MakeDir(ctx, store, txn, versionPath); err != nil {\n\t\treturn err\n\t}\n\n\treturn store.Write(ctx, txn, storage.AddOp, versionPath, map[string]interface{}{\n\t\t\"version\": version.Version,\n\t\t\"build_commit\": version.Vcs,\n\t\t\"build_timestamp\": version.Timestamp,\n\t\t\"build_hostname\": version.Hostname,\n\t})\n}",
"func (fs *FactorySale) Save(ctx context.Context) error {\n\tif fs.Exists() {\n\t\treturn fs.Update(ctx)\n\t}\n\n\treturn fs.Insert(ctx)\n}",
"func (w Wallet) Send(to string, amount uint, utxoSetPath string) error {\n\treturn nil\n}",
"func (token *Token) Save(db *sqlx.DB) {\n\n\tif strings.TrimSpace(token.AccessToken) == \"\" || strings.TrimSpace(token.RefreshToken) == \"\" || token.RefreshTokenExpiry == 0 || token.AccessTokenExpiry == 0 || strings.TrimSpace(token.DeviceID) == \"\" || strings.TrimSpace(token.MacAddress) == \"\" || strings.TrimSpace(token.APIKey) == \"\" || token.Status == 0{\n\t\tfmt.Println(\"Missing Fields from tokens\")\n\t\treturn\n\t}\n\t\n\tif strings.TrimSpace(token.ID) == \"\" {\n\t\ttoken.ID, _ = shortid.Generate()\n\t}\n\t\n\tsql := \"INSERT INTO tokens(id,access_token, access_token_time, access_token_expiry, user_id, status, api_key, refresh_token, refresh_token_time, refresh_token_expiry, device_id, mac_address) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)\"\n\n\t_, err := db.Exec(sql,\n\t\ttoken.ID,\n\t\ttoken.AccessToken,\n\t\ttoken.AccessTokenTime,\n\t\ttoken.AccessTokenExpiry,\n\t\ttoken.UserID,\n\t\ttoken.Status,\n\t\ttoken.APIKey,\n\t\ttoken.RefreshToken,\n\t\ttoken.RefreshTokenTime,\n\t\ttoken.RefreshTokenExpiry,\n\t\ttoken.DeviceID,\n\t\ttoken.MacAddress,\n\t)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}",
"func (suite *MainIntegrationSuite) TestWriteBlockToTestDB() {\n\t// Create a DBClient that will be using the test tables.\n\ttestDBClient, err := dbclient.New(\n\t\tdbclient.DBPort(injector.PostgresPort()),\n\t\tdbclient.DBName(injector.PostgresDBName()),\n\t\tdbclient.DBUser(injector.PostgresUserName()),\n\t\tdbclient.DBHost(injector.PostgresDomain()),\n\t\tdbclient.DBPassword(injector.PostgresPassword()),\n\t\tdbclient.PostgresClient(),\n\t\tdbclient.Test())\n\n\t// Connect to the DB.\n\terr = testDBClient.Connect()\n\tdefer testDBClient.Close()\n\tsuite.NoError(err, \"There should be no error when connecting to the Test DB.\")\n\n\t// Write a block to the DB.\n\tblock := testutils.Block506664\n\terr = testDBClient.WriteBlock(block)\n\tsuite.NoError(err, \"There should be no error writing block to db\")\n}",
"func CreateProduct(w http.ResponseWriter, r *http.Request) {\n var p dynamodbservice.Product\n w.Header().Add(\"Content-Type\", \"application/json\")\n if err := json.NewDecoder(r.Body).Decode(&p); err != nil {\n http.Error(w, err.Error(), http.StatusBadRequest)\n return\n }\n\n defer r.Body.Close()\n\n if err := dynamodbservice.Items.AddProduct(p); err != nil {\n http.Error(w, err.Error(), http.StatusInternalServerError)\n return\n }\n\n w.WriteHeader(http.StatusCreated)\n json.NewEncoder(w).Encode(p)\n}",
"func (tp *TxPool) AddTransactionToDatabaseMempool(txHash *common.Hash, txDesc TxDesc) error {\n\ttx := txDesc.Desc.Tx\n\ttempDesc := TempDesc{\n\t\tStartTime: txDesc.StartTime,\n\t\tIsPushMessage: txDesc.IsFowardMessage,\n\t\tHeight: txDesc.Desc.Height,\n\t\tFee: txDesc.Desc.Fee,\n\t\tFeePerKB: txDesc.Desc.FeePerKB,\n\t}\n\tswitch tx.GetType() {\n\t//==================For PRV Transfer Only\n\tcase common.TxNormalType:\n\t\t{\n\t\t\tnormalTx := tx.(*transaction.Tx)\n\t\t\tvalueTx, err := json.Marshal(normalTx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvalueDesc, err := json.Marshal(tempDesc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = tp.config.DataBaseMempool.AddTransaction(txHash, common.TxNormalType, valueTx, valueDesc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t//==================For PRV & TxCustomToken Transfer\n\tcase common.TxCustomTokenType:\n\t\t{\n\t\t\tcustomTokenTx := tx.(*transaction.TxCustomToken)\n\t\t\tvalueTx, err := json.Marshal(customTokenTx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvalueDesc, err := json.Marshal(tempDesc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = tp.config.DataBaseMempool.AddTransaction(txHash, common.TxCustomTokenType, valueTx, valueDesc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\tcase common.TxCustomTokenPrivacyType:\n\t\t{\n\t\t\tcustomTokenPrivacyTx := tx.(*transaction.TxCustomTokenPrivacy)\n\t\t\tvalueTx, err := json.Marshal(customTokenPrivacyTx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvalueDesc, err := json.Marshal(tempDesc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = tp.config.DataBaseMempool.AddTransaction(txHash, common.TxCustomTokenPrivacyType, valueTx, valueDesc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}",
"func (server *StorageServer) Write(ctx context.Context, message *pb.WriteRequest) (*pb.WriteResponse, error) {\n\twasmResponse := server.callWasm(\"store_data\", message, &pb.WriteResponse{})\n\treturn wasmResponse.(*pb.WriteResponse), nil\n}",
"func WriteCoin(slug string, v interface{}, d interface{}) bool {\n\tdc := mod.Cache{Data: d}\n\treturn DB.Write(cfg.Web+\"/coins\", slug, v) == nil &&\n\t\tDB.Write(cfg.Web+\"/data/\"+slug, \"info\", dc) == nil\n}",
"func (m *Meme) Save(db XODB) error {\n\tif m.Exists() {\n\t\treturn m.Update(db)\n\t}\n\n\treturn m.Insert(db)\n}",
"func (c *changeTrackerDB) WriteTxn(idx uint64) *txn {\n\tt := &txn{\n\t\tTxn: c.memdb.Txn(true),\n\t\tIndex: idx,\n\t\tpublish: c.publish,\n\t\tmsgType: structs.IgnoreUnknownTypeFlag, // The zero value of structs.MessageType is noderegistration.\n\t}\n\tt.Txn.TrackChanges()\n\treturn t\n}",
"func (c *Client) Store(agmi models.AgencyMonthlyInfo) error {\n\tif err := c.Db.Store(agmi); err != nil {\n\t\treturn fmt.Errorf(\"Store() error: %q\", err)\n\t}\n\treturn nil\n}",
"func Save(gw Gateway) (*mgo.ChangeInfo, error) {\n\treturn collection().UpsertId(gw.MAC, gw)\n}",
"func (item *Item) commit() {\n\tDB.Where(\"id = ?\", item.ID).FirstOrCreate(&item)\n\tDB.Model(item).Update(&item)\n}",
"func (c *Client) CreateWallet(userId, walletName, adminId string) (wal Wallet, err error) {\n\tresp, err := req.Post(c.url+\"/usermanager/api/v1/wallets\", c.header, req.BodyJSON(struct {\n\t\tUserId string `json:\"user_id\"`\n\t\tWalletName string `json:\"wallet_name\"`\n\t\tAdminId string `json:\"admin_id\"`\n\t}{userId, walletName, adminId}))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.Response().StatusCode >= 300 {\n\t\tvar reqErr Error\n\t\tresp.ToJSON(&reqErr)\n\t\terr = reqErr\n\t\treturn\n\t}\n\terr = resp.ToJSON(&wal)\n\twal.Client = c\n\treturn\n}",
"func TransactionUpdate(c *gin.Context) {\n\tvar t models.Transaction\n\tvar newT models.Transaction\n\n\tif database.DBCon.First(&t, c.Param(\"id\")).RecordNotFound() {\n\t\tc.AbortWithError(http.StatusNotFound, appError.RecordNotFound).\n\t\t\tSetMeta(appError.RecordNotFound)\n\t\treturn\n\t}\n\n\t// Ensure current user is creator of transaction\n\tif t.CreatorID != c.Keys[\"CurrentUserID\"].(uint) {\n\t\tc.AbortWithError(appError.InsufficientPermission.Status, appError.InsufficientPermission).\n\t\t\tSetMeta(appError.InsufficientPermission)\n\t\treturn\n\t}\n\n\tbuffer, err := ioutil.ReadAll(c.Request.Body)\n\n\tif err != nil {\n\t\tc.AbortWithError(http.StatusNotAcceptable, err)\n\t}\n\n\terr2 := jsonapi.Unmarshal(buffer, &newT)\n\n\tif err2 != nil {\n\t\tc.AbortWithError(http.StatusInternalServerError, err).\n\t\t\tSetMeta(appError.JSONParseFailure)\n\t\treturn\n\t}\n\n\tt.Type = newT.Type\n\tt.Amount = newT.Amount\n\tt.Memo = newT.Memo\n\tt.RecipientID = newT.RecipientID\n\tt.SenderID = newT.SenderID\n\n\t// Validate our new transaction\n\tisValid, errApp := t.Validate()\n\n\tif isValid == false {\n\t\tc.AbortWithError(errApp.Status, errApp).\n\t\t\tSetMeta(errApp)\n\t\treturn\n\t}\n\n\tdatabase.DBCon.Save(&t)\n\n\tdatabase.DBCon.First(&t.Recipient, t.RecipientID)\n\tdatabase.DBCon.First(&t.Sender, t.SenderID)\n\tdatabase.DBCon.First(&t.Creator, t.CreatorID)\n\n\tdata, err := jsonapi.Marshal(&t)\n\n\tif err != nil {\n\t\tc.AbortWithError(http.StatusInternalServerError, err).\n\t\t\tSetMeta(appError.JSONParseFailure)\n\t\treturn\n\t}\n\n\tc.Data(http.StatusOK, \"application/vnd.api+json\", data)\n}",
"func storeSerialNumber(app *AppContext) error {\n\tlog.Debugf(\"Storing serial number: %d\", app.serialNumber)\n\terr := app.burnerLogDB.Update(func(tx *bolt.Tx) error {\n\t\terr := tx.Bucket([]byte(\"serial\")).Put([]byte(\"serial\"), []byte(strconv.Itoa(app.serialNumber)))\n\t\treturn errors.Wrap(err, \"storeSerialNumber:Put\")\n\t})\n\treturn errors.Wrap(err, \"storeSerialNumber:Update\")\n}",
"func (gt GtwyMgr) Set(ctx context.Context, appcontext, remoteAddress string) error {\n\tif EnvDebugOn {\n\t\tlblog.LogEvent(\"GtwyMgr\", \"Set\", \"info\", \"start\")\n\t}\n\n\tglst := &Gateway{AppContext: appcontext, RemoteAddress: remoteAddress}\n\n\tky, err := gt.newKey(ctx, gt.bc.GetConfigValue(ctx, \"EnvGtwayDsNamespace\"), gt.bc.GetConfigValue(ctx, \"EnvGtwayDsKind\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttx, err := gt.ds.NewTransaction(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := tx.Put(ky, glst); err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\tif _, err = tx.Commit(); err != nil {\n\t\treturn err\n\t}\n\n\tif EnvDebugOn {\n\t\tlblog.LogEvent(\"GtwyMgr\", \"Set\", \"info\", \"end\")\n\t}\n\treturn nil\n}",
"func (s *MockStore) Write(collection, id, value string) error {\n\tc, ok := s.Data[collection]\n\tif ok {\n\t\tc[id] = value\n\t} else {\n\t\tc = map[string]string{id: value}\n\t\tif s.Data == nil {\n\t\t\ts.Data = map[string]map[string]string{collection: c}\n\t\t} else {\n\t\t\ts.Data[collection] = c\n\t\t}\n\t}\n\treturn nil\n}",
"func postToDB(conn connectors.Clients, msg *kafka.Message) error {\n\n\tvar data *schema.IOTPaaS\n\n\tif msg != nil {\n\n\t\terrs := json.Unmarshal(msg.Value, &data)\n\t\tif errs != nil {\n\t\t\tconn.Error(\"postToDB unmarshalling format %v\", errs)\n\t\t\treturn errs\n\t\t}\n\n\t\t_, err := conn.Set(data.Id, string(msg.Value), -1)\n\t\tif err != nil {\n\t\t\tconn.Error(fmt.Sprintf(\"Could not insert schema into redis %v\", err))\n\t\t\treturn err\n\t\t}\n\n\t\t// all good :)\n\t\treturn nil\n\n\t} else {\n\t\tconn.Info(\"Message data is nil\")\n\t\treturn nil\n\t}\n}",
"func (dao *AccountDao) Save(acc *AccountEntity) error {\r\n\tstmt, err := dao.Prepare(accountInsertStmt)\r\n\tif err != nil {\r\n\t\tlogs.Error(\"account save err0:\", err, \"[\", accountInsertStmt, \"]\")\r\n\t\treturn err\r\n\t}\r\n\tdefer stmt.Close()\r\n\r\n\tvar defaultVal = []interface{}{\r\n\t\tacc.Id,\r\n\t\tacc.Name,\r\n\t\tacc.Email,\r\n\t\tacc.Pwd,\r\n\t\t\"sdk data\",\r\n\t\t\"\",\r\n\t\t\"\",\r\n\r\n\t\t// \"\",\r\n\t\t// 0,\r\n\t\t// 0,\r\n\t\t// \"\",\r\n\t\t// \"\",\r\n\t\t// 0,\r\n\t\t// \"\",\r\n\t\t// 0,\r\n\t\t// 0,\r\n\t\t// \"\",\r\n\t\t// \"\",\r\n\t\t// \"\",\r\n\t\t// \"\",\r\n\t\t// 0,\r\n\t\t// 0,\r\n\t}\r\n\r\n\tres, err := stmt.Exec(defaultVal...)\r\n\tif err != nil {\r\n\t\tlogs.Error(\"account save err1:\", err)\r\n\t\treturn err\r\n\t}\r\n\r\n\tid, err := res.LastInsertId()\r\n\tif err != nil {\r\n\t\tlogs.Error(\"account save err2:\", err)\r\n\t\treturn err\r\n\t}\r\n\t// logs.Debug(\"new account id:\", id)\r\n\tacc.Id = id\r\n\r\n\treturn nil\r\n}",
"func (cs *CustStoreSqlite) AddTransaction(\n id string,\n customerId string,\n loadAmountCents int64,\n time time.Time,\n accepted bool,\n) error {\n // Check transaction id\n isDuplicate, err := cs.isDuplicate(id, customerId)\n if err != nil {\n return err\n }\n if isDuplicate {\n return custstore.DuplicateError\n }\n // Add to transactions\n err = cs.addTransaction(id, customerId, loadAmountCents, time, accepted)\n return err\n}",
"func (s *MySQLStore) Write(id string, ticket *AuthenticationResponse) error {\n\n\ts.mu.Lock()\n\n\tjsonTicket, err := json.Marshal(ticket)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnow := database.GetNullTime(time.Now(), time.UTC)\n\n\tts := MySQLTicketStore{\n\t\tID: id,\n\t\tData: string(jsonTicket),\n\t\tUpdated: now,\n\t\tCreated: now,\n\t}\n\n\tsql := `INSERT INTO tickets (t_id, t_data, t_created, t_updated) \n\t\t\tVALUES (:t_id, :t_data, :t_created, :t_updated)`\n\n\t_, err = s.DB.ExecNamed(sql, ts)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.mu.Unlock()\n\treturn nil\n}",
"func (c *GormController) Commit() revel.Result {\n if c.Txn == nil {\n return nil\n }\n c.Txn.Commit()\n if err := c.Txn.Error; err != nil && err != sql.ErrTxDone {\n panic(err)\n }\n c.Txn = nil\n return nil\n}",
"func (s *BlockStore) Write(b *block.Block) error {\n\terr := os.MkdirAll(s.RootDir, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfilename := s.filename(b.Hash)\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tdata, err := json.Marshal(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = f.Write(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func (*txDriver) Commit() error { return nil }",
"func (*txDriver) Commit() error { return nil }",
"func (suite *MainIntegrationSuite) TestWriteMultipleTXs() {\n\t// Create a controller to write to the DB using the test tables.\n\tvar testDBClient dbclient.Controller\n\ttestDBClient, err := dbclient.New(\n\t\tdbclient.DBPort(injector.PostgresPort()),\n\t\tdbclient.DBName(injector.PostgresDBName()),\n\t\tdbclient.DBUser(injector.PostgresUserName()),\n\t\tdbclient.DBHost(injector.PostgresDomain()),\n\t\tdbclient.DBPassword(injector.PostgresPassword()),\n\t\tdbclient.PostgresClient(),\n\t\tdbclient.Test())\n\n\t// Connect to the DB.\n\terr = testDBClient.Connect()\n\tdefer testDBClient.Close()\n\tsuite.NoError(err, \"There should be no error connecting to the DB\")\n\n\t// Create a node Controller to communicate with a Blockchain Node.\n\tvar nodeClient nodeclient.Controller\n\tnodeClient = nodeclient.New(\n\t\tinjector.DefaultHTTPClient(),\n\t\tinjector.BTCDomain(),\n\t\tinjector.BTCUsername(),\n\t\tinjector.BTCPassword())\n\n\t// Retrieve a Block\n\tblock := testutils.Block506664\n\ttxs := block.TX\n\n\t// Write the Block to the db\n\terr = testDBClient.WriteBlock(block)\n\tsuite.NoError(err, \"Should be able to write block to the db\")\n\n\t// Write 10 transactions to the DB.\n\tfor i, hash := range txs {\n\t\t// Break early, this block has +1000 plus txs.\n\t\tif i == 10 {\n\t\t\tbreak\n\t\t}\n\n\t\t// Request GetTransaction from the node.\n\t\ttx, err := nodeClient.GetTransaction(hash)\n\t\tsuite.NoError(err, \"There should be no error when connecting to the Test DB.\")\n\n\t\t// Add blockhash to transaction.\n\t\ttx.Blockhash = block.Hash\n\n\t\t// Write the retrieved transaction to the transaction table.\n\t\terr = testDBClient.WriteTransaction(tx)\n\t\tsuite.NoError(err, \"There should be no error writing transaction\")\n\n\t\t// Loop over each input in the transaction.\n\t\tfor _, input := range tx.Vin {\n\t\t\t// Write the transaction inputs to the inputs table.\n\t\t\terr = testDBClient.WriteInput(tx.Hash, input)\n\t\t\tsuite.NoError(err, \"There should be no error writing inputs to the db.\")\n\t\t}\n\n\t\t// Loop over each output in the transaction.\n\t\tfor _, output := range tx.Vout {\n\t\t\t// Write the transaction outputs to the outputs table.\n\t\t\terr = testDBClient.WriteOutput(tx.Hash, output)\n\t\t\tsuite.NoError(err, \"There should be no error writing outputs to the db.\")\n\t\t}\n\t}\n}"
] | [
"0.69322854",
"0.65002394",
"0.6095077",
"0.5989846",
"0.5886029",
"0.56237036",
"0.55960226",
"0.5582377",
"0.5465436",
"0.5442849",
"0.54265124",
"0.5409076",
"0.53300565",
"0.5279641",
"0.5218372",
"0.5182961",
"0.5181565",
"0.51810443",
"0.5138971",
"0.5135842",
"0.50768644",
"0.506315",
"0.5039914",
"0.5021285",
"0.50038755",
"0.5000784",
"0.49922964",
"0.4989513",
"0.49879715",
"0.49559757",
"0.49384454",
"0.49106956",
"0.490016",
"0.48976815",
"0.48940772",
"0.4850304",
"0.48453677",
"0.48447526",
"0.48315078",
"0.4821897",
"0.48197573",
"0.48062366",
"0.48059237",
"0.47804782",
"0.47736284",
"0.47725663",
"0.47500023",
"0.4746356",
"0.47438985",
"0.47361246",
"0.47325072",
"0.47316056",
"0.47299317",
"0.4727445",
"0.47273588",
"0.4719965",
"0.47174612",
"0.47143868",
"0.47122762",
"0.47042966",
"0.46971497",
"0.46917477",
"0.46768612",
"0.4667393",
"0.46653315",
"0.46604648",
"0.46573308",
"0.465629",
"0.46554106",
"0.46441945",
"0.46380603",
"0.4626625",
"0.4617817",
"0.46076885",
"0.4607414",
"0.46055654",
"0.46038613",
"0.460094",
"0.45989132",
"0.45942464",
"0.45933476",
"0.45879534",
"0.45877048",
"0.45866522",
"0.45812854",
"0.45804787",
"0.45760724",
"0.45701683",
"0.4554897",
"0.45431525",
"0.45422673",
"0.45407516",
"0.45353985",
"0.4533847",
"0.45304653",
"0.45294553",
"0.4517917",
"0.45064232",
"0.45064232",
"0.4506401"
] | 0.778587 | 0 |
CToF converts a Celsius temp to Fahrenheit | func CToF(c Celsius) Fahrenheit {
return Fahrenheit(c*9/5 + 32)
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }",
"func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }",
"func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }",
"func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }",
"func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }",
"func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }",
"func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }",
"func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }",
"func FToC(f Fahrenheit) Celsius { return Celsius((f - 32.0) * 5.0 / 9.0) }",
"func FToC(f Farenheit) Celsius { return Celsius((f - 32) * 5 / 9) }",
"func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }",
"func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }",
"func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }",
"func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }",
"func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }",
"func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }",
"func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }",
"func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }",
"func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9.0/5.0 + 32.0) }",
"func CToF(c Celsius) Farenheit { return Farenheit(c*9/5 + 32) }",
"func FToC(f Fahrenheit) Celsius {\n\treturn Celsius((f - 32) / 1.8)\n}",
"func FToC(f Fahrenheit) Celsius {\n\treturn Celsius((f - 32) * 5 / 9)\n}",
"func FToC(f Fahrenheit) Celsius {\n\treturn Celsius((f - 32) * 5 / 9)\n}",
"func FToC(f Fahrenheit) Celsius {\n\treturn Celsius((f - 32) * 5 / 9)\n}",
"func FToC(f Fahrenheit) Celsius {\n\tif f <= AbsoluteZeroF {\n\t\treturn AbsoluteZeroC\n\t}\n\treturn Celsius((f - 32) * 5 / 9)\n}",
"func CToF(c Celsius) Fahrenheit {\n\tif c <= AbsoluteZeroC {\n\t\treturn AbsoluteZeroF\n\t}\n\treturn Fahrenheit(c*9/5 + 32)\n}",
"func CToF(c Celsius) Fahrenheit {\n\treturn Fahrenheit(c*1.8 + 32)\n}",
"func toFahrenheit(t Celsius) Fahrenheit {\n\n\tvar temp Fahrenheit\n\tvar tt float32\n\ttt = (float32(t) * 1.8) + float32(32)\n\ttemp = Fahrenheit(tt)\n\treturn temp\n\n}",
"func CtoF(t float32) float32 {\n\treturn (t*9/5 + 32)\n}",
"func (c Celsius) ToF() Fahrenheit {\n\treturn CToF(c)\n}",
"func (f Fahrenheit) ToC() Celsius {\n\treturn FToC(f)\n}",
"func (c Celcious) Fahrenheit() Fahrenheit {\n\treturn Fahrenheit((c * 1.8) + 32)\n}",
"func (kh kelvinHandler) ToFahrenheit(temp float64) float64 {\n\treturn (kh.ToCelsius(temp) * fahrenheitMultiplier) + FahrenheitBase\n}",
"func (f Fahrenheit) Celsius() Celsius {\n\treturn Celsius((float32(f) - 32) * float32(5) / float32(9))\n}",
"func (c Celsius) Fahrenheit() Fahrenheit {\n\treturn Fahrenheit((float32(c) * 1.8) + 32)\n}",
"func DisplayFToC() {\n\tconst freezingF, boilingF = 32.0, 212.0\n\tfmt.Printf(\"%g°F = %g°C\\n\", freezingF, fToC(freezingF)) // 32°F = 0°C\n\tfmt.Printf(\"%g°F = %g°C\\n\", boilingF, fToC(boilingF)) // 212°F = 100°C\n}",
"func KToF(k Kelvin) Fahrenheit { return CToF(KToC(k)) }",
"func (f Fahrenheit) Celcious() Celcious {\n\treturn Celcious((f - 32) / 1.8)\n}",
"func (t Temperature) Fahrenheit() float64 {\n\treturn float64(t)\n}",
"func (t Temperature) Celsius() float64 {\n\treturn (t.Fahrenheit() - 32.0) * 5.0 / 9.0\n}",
"func (c ConversionHandler) ConvertCtoF(writer http.ResponseWriter, request *http.Request) {\n\tresult, err := decodeRequest(request)\n\n\tif err != nil {\n\t\thandleError(writer, err)\n\t\treturn\n\t}\n\n\tfahrenheit := convert.CelsiusToFahrenheit(convert.Celsius(result))\n\tformatAndSendResponse(writer, \"Fahrenheit\", fahrenheit.String())\n}",
"func kToFToC(rowNum int) (col1, col2, col3 string, kColor, fColor, cColor int) {\n\tk := kelvin(rowNum * 5)\n\tf := k.fahrenheit()\n\tc := k.celsius()\n\tcol1 = fmt.Sprintf(tempFmt, k)\n\tcol2 = fmt.Sprintf(tempFmt, f)\n\tcol3 = fmt.Sprintf(tempFmt, c)\n\tkColor = k.color()\n\tfColor = f.color()\n\tcColor = c.color()\n\treturn col1, col2, col3, kColor, fColor, cColor\n}",
"func (c ConversionHandler) ConvertFtoC(writer http.ResponseWriter, request *http.Request) {\n\tresult, err := decodeRequest(request)\n\n\tif err != nil {\n\t\thandleError(writer, err)\n\t\treturn\n\t}\n\n\tcelsius := convert.FahrenheitToCelsius(convert.Fahrenheit(result))\n\tformatAndSendResponse(writer, \"Celsius\", celsius.String())\n}",
"func (nch *NvmeHealth) TempF() float32 {\n\treturn (nch.TempC() * (9.0 / 5.0)) + 32.0\n}",
"func convertFtoc() {\n\tconst freezingF, boilingF = 32.0, 212.0\n\n\tfmt.Printf(\"%gF = %gC\\n\", freezingF, ftoc(freezingF)) //\"32F = 0C\"\t\n\tfmt.Printf(\"%gF = %gC\\n\", boilingF, ftoc(boilingF)) //\"212F\" = 100C\"\n\n}",
"func (c *Channel) TempF() int {\n\treturn int(c.temp)\n}",
"func Fahrenheit(f float64) Temperature {\n\treturn Temperature(f)\n}",
"func (t *Temp) F() int {\n\ttemp := math.Floor(float64(*t)*9/5) + 32\n\tif temp < 0 {\n\t\treturn int(temp - 1.0)\n\t}\n\treturn int(temp)\n}",
"func TempFromF(f int) Temp {\n\tc := math.Floor(float64((f - 32)) / 1.8)\n\treturn Temp(c)\n\n}",
"func Celsius(c float64) Temperature {\n\treturn Temperature(c*1.8 + 32.0)\n}",
"func KToC(k Kelvin) Celsius { return Celsius(k - 273.15) }",
"func KToC(k Kelvin) Celsius { return Celsius(k + 273.15) }",
"func KToF(k Kelvin) Fahrenheit { return Fahrenheit((k-273.15)*9.0/5.0 + 32.0) }",
"func main() {\n\tvar tempFahrenheit, tempCelsius float32\n\n\tfmt.Println(\"Enter temperature in Fahrenheit(F): \")\n\tfmt.Scanln(&tempFahrenheit)\n\ttempCelsius = (tempFahrenheit - 32) * (5.0 / 9)\n\tfmt.Println(\"The temperature in Celsius(C) is: \", tempCelsius)\n\n}",
"func (kh kelvinHandler) ToCelsius(temp float64) float64 {\n\treturn temp - KelvinBase\n}",
"func KtoF(k Kalvin) Fahrenheit {\n\tif k < AbsoluteZeroK {\n\t\tpanic(\"Your input cannot be below absolute zero.\")\n\t}\n\n\t// Conversation formula\n\t// (t°K - 273.15) * 9/5 + 32\n\treturn Fahrenheit(round((float64(k)-273.15)*1.8+32, 100))\n}",
"func FToK(f Fahrenheit) Kelvin { return Kelvin(((f - 32.0) * 5.0 / 9.0) + 273.15) }",
"func (f Fahrenheit) Fahrenheit() Fahrenheit {\n\treturn f\n}",
"func (nch *NvmeHealth) TempC() float32 {\n\treturn float32(nch.Temperature) - 273.15\n}",
"func KToF(k Kelvin) Fahrenheit {\n\tif k <= AbsoluteZeroK {\n\t\treturn AbsoluteZeroF\n\t}\n\treturn Fahrenheit(k*9/5) + AbsoluteZeroF\n}",
"func main() {\n\tfmt.Println(\"The program converts temperature from Celsius to Fahrenheit.\")\n\tfmt.Println(\"Enter the temperature in Celsius: \")\n\tvar x float64\n\tfmt.Scan(&x)\n\tx = x*9/5 + 32\n\tfmt.Println(\"The temperature in Fahrenheit:\", x)\n\n}",
"func KToF(k Kelvin) Fahrenheit {\n\treturn Fahrenheit(k*9/5 - 459.67)\n}",
"func franc(f int) *Money {\n\treturn &Money{\n\t\tamount: f,\n\t\tcurrency: \"CHF\",\n\t}\n}",
"func CgoFal03(t float64) float64 {\n\tvar cF C.double\n\tcF = C.iauFal03(C.double(t))\n\treturn float64(cF)\n}",
"func (this *Device) GetCoreTemperatureCelcius() (float64, error) {\n\t// retrieve value as text\n\tvalue, err := this.GeneralCommand(GENCMD_MEASURE_TEMP)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\n\t// Find value within text\n\tmatch := REGEXP_TEMP.FindStringSubmatch(value)\n\tif len(match) != 2 {\n\t\treturn 0.0, this.log.Error(\"Bad Response from %v\", GENCMD_MEASURE_TEMP)\n\t}\n\n\t// Convert to float64\n\tvalue2, err := strconv.ParseFloat(match[1], 64)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\n\t// Return value as float64\n\treturn value2, nil\n}",
"func (c *Channel) TempC() int {\n\treturn f2c(int(c.temp))\n}",
"func (cti CubicThousandthInch) ToCubicFeet() CubicFeet {\n\tcubicThousandthInchPerCubicFoot := thousandthInchPerFoot * thousandthInchPerFoot * thousandthInchPerFoot\n\treturn CubicFeet(float64(cti) / float64(cubicThousandthInchPerCubicFoot))\n}",
"func MtoFT(d Meter) Feet {\n\treturn Feet(d / 3.28084)\n}",
"func main() {\n fmt.Print(\"fahrenheit grades: \")\n var far float64\n fmt.Scanf(\"%f\", &far)\n // formula: c = (f-32) * 5/9\n celsius := ((far - 32) * 5 ) / 9\n fmt.Println(\"Celsius:\", celsius)\n}",
"func KToC(k Kelvin) Celsius {\n\treturn Celsius(k - 273.15)\n}",
"func (o Cos) F(t float64, x []float64) float64 {\n\treturn o.a*math.Cos(o.b*t) + o.c\n}",
"func KtoC(k Kalvin) Celsius {\n\tif k < AbsoluteZeroK {\n\t\tpanic(\"Your input cannot be below absolute zero.\")\n\t}\n\n\t// Conversation formula\n\t// t°K - 273.15\n\treturn Celsius(round(float64(k)-273.15, 100))\n}",
"func (h *MPU6050Driver) convertToCelsius() {\n\th.Temperature = (h.Temperature + 12412) / 340\n}",
"func (c Celsius) Celsius() Celsius {\n\treturn c\n}",
"func FToK(f Fahrenheit) Kelvin {\n\tif f <= AbsoluteZeroF {\n\t\treturn AbsoluteZeroK\n\t}\n\treturn Kelvin((f - AbsoluteZeroF) * 5 / 9)\n}",
"func MToF(m Meter) Feet { return Feet(m / 0.3048) }",
"func convertTemperature(fromUOM, toUOM string, value float64) float64 {\n\tfromUOM = resolveTemperatureSynonyms(fromUOM)\n\ttoUOM = resolveTemperatureSynonyms(toUOM)\n\tif fromUOM == toUOM {\n\t\treturn value\n\t}\n\t// convert to Kelvin\n\tswitch fromUOM {\n\tcase \"F\":\n\t\tvalue = (value-32)/1.8 + 273.15\n\tcase \"C\":\n\t\tvalue += 273.15\n\tcase \"Rank\":\n\t\tvalue /= 1.8\n\tcase \"Reau\":\n\t\tvalue = value*1.25 + 273.15\n\t}\n\t// convert from Kelvin\n\tswitch toUOM {\n\tcase \"F\":\n\t\tvalue = (value-273.15)*1.8 + 32\n\tcase \"C\":\n\t\tvalue -= 273.15\n\tcase \"Rank\":\n\t\tvalue *= 1.8\n\tcase \"Reau\":\n\t\tvalue = (value - 273.15) * 0.8\n\t}\n\treturn value\n}",
"func (k Kelvin) Celcious() Celcious {\n\treturn Celcious(k - 273.15)\n}",
"func KToC(k Kelvin) Celsius {\n\tif k <= AbsoluteZeroK {\n\t\treturn AbsoluteZeroC\n\t}\n\treturn Celsius(k) + AbsoluteZeroC\n}",
"func MToF(m Meter) Foot { return Foot(m / 0.3048) }",
"func KToC(k Kelvin) Celsius {\n\treturn Celsius(k + Kelvin(AbsoluteZeroC))\n}",
"func MToF(m Meters) Feet {\n\treturn Feet(m * 3.2808)\n}",
"func adcToTemperature(adc int16) float64 {\n\treturn float64(adc)*0.3125e-3*10.0 - 20.0\n}",
"func CToK(c Celsius) Kelvin { return Kelvin(c - 273.15) }",
"func FToK(f Fahrenheit) Kelvin {\n\treturn Kelvin((f + 459.67) * 5 / 9)\n}",
"func (n *TemperatureSensorNtcConf) getTemp(rntc float64) float64 {\n\t// 1/T = 1/T0 + 1/B * ln(R/R0)\n\t//\n\t// B/T = B/T0 + ln(R/R0) = k, B/T0 = r\n\t// T = B/k, Tc = T - 273\n\n\tk := n.r + math.Log(rntc/n.R0)\n\treturn n.B/k - kelvinOffset\n}",
"func CgoFapa03(t float64) float64 {\n\tvar cF C.double\n\tcF = C.iauFapa03(C.double(t))\n\treturn float64(cF)\n}",
"func (p *CubicPolynomial) f0(t float64) float64 {\n\treturn p.a + t*(p.b+t*(p.c+p.d*t))\n}",
"func CToK(c Celsius) Kelvin { return Kelvin(c + 273.15) }",
"func (p *CubicPolynomial) f2(t float64) float64 {\n\treturn 2*p.c + 6*p.d*t\n}",
"func kelvinToCelsius(k float64) float64 {\n\tk -= 273.15\n\treturn k\n}",
"func getCNTFRQ() TSCValue",
"func (k kelvin) celsius() celsius {\n\treturn celsius(k - 273.15)\n}",
"func kelvinToCelsius(k kelvin) celsius {\n\t// type must be converted before return\n\treturn celsius(k - 273.15)\n}",
"func TestExample_one(t *testing.T) {\n\tgot := BoilingC - FreezingC\n\twant := Celcius(100)\n\tif got != want {\n\t\tt.Fatalf(\"want %g, got %g\", want, got)\n\t}\n\tt.Logf(\"%g\\n\", got) // \"100\" °C\n\tboilingF := CToF(BoilingC)\n\tt.Logf(\"%g\\n\", boilingF-CToF(FreezingC)) // \"180\" °F\n\t/*\n\t\tfmt.Printf(\"%g\\n\", boilingF-FreezingC) // compile error: type mismatch\n\t*/\n}",
"func (c Celsius) String() string {\n\treturn fmt.Sprintf(\"%.2f C\", float32(c))\n}",
"func (m *Money) Setfc(f float64, currency string) *Money {\n\tfDPf := f * DPf\n\tr := int64(f * DPf)\n\treturn m.Setc(Rnd(r, fDPf-float64(r)), currency)\n}"
] | [
"0.86657584",
"0.86657584",
"0.86657584",
"0.86657584",
"0.86657584",
"0.86657584",
"0.86657584",
"0.86657584",
"0.86615694",
"0.85506606",
"0.8520838",
"0.8520838",
"0.8520838",
"0.8520838",
"0.8520838",
"0.8520838",
"0.8520838",
"0.8520838",
"0.8475397",
"0.84366554",
"0.83993685",
"0.8362628",
"0.8362628",
"0.8362628",
"0.83297735",
"0.8039754",
"0.7997179",
"0.7977784",
"0.7743619",
"0.7739328",
"0.74812174",
"0.7255182",
"0.7006308",
"0.69721115",
"0.6948382",
"0.69084984",
"0.6896579",
"0.68188053",
"0.6800237",
"0.678964",
"0.6785051",
"0.67328596",
"0.67219",
"0.6689426",
"0.66847444",
"0.6635613",
"0.6618907",
"0.66055995",
"0.6591299",
"0.65899175",
"0.6518334",
"0.6510441",
"0.6422568",
"0.63494545",
"0.62543637",
"0.6205182",
"0.6187203",
"0.61790603",
"0.61765224",
"0.613309",
"0.61300254",
"0.6098016",
"0.60658455",
"0.6051169",
"0.60103256",
"0.5993509",
"0.5931471",
"0.5908518",
"0.5899432",
"0.5896467",
"0.5885275",
"0.5869756",
"0.58569884",
"0.5845996",
"0.5825139",
"0.5816988",
"0.5804724",
"0.5794402",
"0.57924986",
"0.57755226",
"0.5754146",
"0.5720345",
"0.56542456",
"0.56407773",
"0.56276506",
"0.56236327",
"0.5618446",
"0.56006336",
"0.5597531",
"0.5576852",
"0.55748266",
"0.55560154",
"0.55517733",
"0.5547882",
"0.5449117",
"0.54399097",
"0.54301316"
] | 0.7976048 | 31 |
MustRemoveFile tries to delete the file path from the local file system. On error a message is logged. | func MustRemoveFile(path string, logger *zap.Logger) {
logger.Debug("Removing file", zap.String("path", path))
if err := os.Remove(path); err != nil {
// there's not a lot we can do here
logger.Error("Failed to remove file", zap.String("path", path), zap.Error(err))
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (_m *OSIOAPI) MustRemove(filename string) {\n\t_m.Called(filename)\n}",
"func removeFile(path string) bool {\n\tif err := os.RemoveAll(path); nil != err {\n\t\tlogger.Errorf(\"Removes [%s] failed: [%s]\", path, err.Error())\n\n\t\treturn false\n\t}\n\n\tlogger.Tracef(\"Removed [%s]\", path)\n\n\treturn true\n}",
"func assertFileRemoved(t *testing.T, message string, name string) {\n\tt.Helper()\n\tfor i := 0; i < 100; i++ {\n\t\tif _, err := os.Stat(name); err != nil {\n\t\t\treturn // File removed\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\tt.Fatalf(\"File %s was never removed. %s\", name, message)\n}",
"func deleteFile( filename string) {\n // createFile() // use the createFile first, then delete file\n checkExistence(filename)\n err := os.Remove(filename)\n u.ErrNil(err, \"Unable to remove testfile1.txt\")\n log.Printf(\"Deleted %s\", filename)\n}",
"func (h testHelper) deleteFile(filename string) {\n\terr := os.Remove(filename)\n\tif err != nil {\n\t\th.Error(err)\n\t}\n}",
"func removeFile(fname string) error {\n\tif err := os.Remove(fname); (err != nil) && !os.IsNotExist(err) {\n\t\treturn errors.Wrapf(err, \"remove %v\", fname)\n\t}\n\treturn nil\n}",
"func removeSafely(pathToFile string) {\n\terr := os.Remove(pathToFile)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}",
"func checkAndDelete(fileName string) error {\n\tfi, err := os.Stat(fileName)\n\tif err == nil {\n\t\tif fi.Mode().IsRegular() {\n\t\t\t// delete it\n\t\t\treturn os.Remove(fileName)\n\t\t} else {\n\t\t\treturn errors.New(\"output file exists and is not a regular file\")\n\t\t}\n\t}\n\t// err != nil\n\tif os.IsNotExist(err) {\n\t\treturn nil\n\t}\n\treturn err\n}",
"func FileDelete(filename string) error {\n\tif FileExists(filename) {\n\t\tDebug(fmt.Sprintf(\"FileRemove %s\", filename))\n\n\t\terr := os.Remove(filename)\n\t\tif Error(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}",
"func removeLocalFile(file string) error {\n\tvar err error\n\ttargetFile := getTargetPath(file)\n\tfmt.Println(targetFile)\n\tif _, err = os.Stat(targetFile); os.IsNotExist(err) {\n\t\treturn err\n\t}\n\terr = os.Remove(targetFile)\n\treturn err\n}",
"func removeFile(n string) {\n\terr := os.Remove(n)\n\tif err != nil {\n\t\tglog.Fatal(\"CleanupFiles \", err)\n\t}\n}",
"func removeFile() {\n\terr := os.Remove(fileName)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t} else {\n\t\tfmt.Println(\"File removed.\")\n\t}\n}",
"func removeIfFile(uri string) {\n\tu, err := url.Parse(uri)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif u.Scheme != \"file\" {\n\t\treturn\n\t}\n\n\tos.Remove(u.Path)\n}",
"func removeFile(filename string) {\n\tfileInfo, _ := os.Stat(filename)\n\t// Does the file exist? If it's nil, it doesn't.\n\tif fileInfo == nil {\n\t\treturn\n\t}\n\n\t// is the file a directory? Then we want to use the directory removal\n\tif fileInfo.IsDir() {\n\t\tif err := os.RemoveAll(filename); err != nil && !os.IsNotExist(err) {\n\t\t\tutils.Checkerror(err)\n\t\t}\n\t\t// if not, we'll use the normal file removal\n\t} else {\n\t\tif err := os.Remove(filename); err != nil && !os.IsNotExist(err) {\n\t\t\tutils.Checkerror(err)\n\t\t}\n\t}\n}",
"func LogFileRemove(baseFileName string) error {\n\terr := os.Remove(logFileName(baseFileName))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn os.Remove(metaFileName(baseFileName))\n}",
"func deleteFile(path string) error {\n\tif _, err := os.Stat(path); err != nil {\n\t\t// return nil if file doesn't exist\n\t\treturn nil\n\t}\n\treturn os.Remove(path)\n}",
"func DeleteFile(f string) bool {\n\tif _, err := os.Stat(f); os.IsNotExist(err) {\n\t\treturn true\n\t}\n\n\tif err := os.Remove(f); err != nil {\n\t\treturn false\n\t}\n\n\treturn true\n}",
"func removeFileSilently(name string) {\n\t_ = os.Remove(name)\n}",
"func Remove(ctx context.Context, filePath string) error {\n\tif err := os.Remove(filePath); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func (m *FileSystem) Remove(file string) error {\n\tret := m.ctrl.Call(m, \"Remove\", file)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}",
"func DeleteFile(path string) {\n\t// check if file exist first.\n\tfmt.Println(path)\n\tif path == \".\" {\n\t\treturn\n\t}\n\tif _, err := os.Stat(path); !os.IsNotExist(err) {\n\t\terr := os.Remove(path)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}",
"func TestIsValid2(t *testing.T) {\n\tfileName := \"test.txt\"\n\tos.Create(fileName)\n\tfilePath := filepath.Join(CurrentDir, fileName)\n\tIsValid(filePath)\n\tos.Remove(filePath)\n}",
"func TestIsValid2(t *testing.T) {\n\tfileName := \"test.txt\"\n\tos.Create(fileName)\n\tfilePath := filepath.Join(CurrentDir, fileName)\n\tIsValid(filePath)\n\tos.Remove(filePath)\n}",
"func (s *mockFSServer) Remove(ctx context.Context, r *proto.RemoveRequest) (*proto.RemoveResponse, error) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\tif _, ok := s.filesCreated[r.Path]; ok {\n\t\tdelete(s.filesCreated, r.Path)\n\t\treturn new(proto.RemoveResponse), nil\n\t}\n\treturn nil, os.ErrNotExist\n}",
"func RemoveFile(filename string) error {\n\tif _, err := os.Stat(filename); err == nil {\n\t\terr := os.Remove(filename)\n\t\tif err != nil {\n\t\t\tprint.Error(err)\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\treturn errors.New(\"File not found\")\n\t}\n\treturn nil\n}",
"func (f FileManager) Remove(path string) error {\n\tif f.Exists(path) {\n\t\treturn os.Remove(path)\n\t}\n\treturn nil\n}",
"func DeleteFile(path string) error {\n\tif PathExist(path) {\n\t\tif IsDir(path) {\n\t\t\treturn errors.Errorf(\"delete file %s: not a regular file\", path)\n\t\t}\n\n\t\treturn os.Remove(path)\n\t}\n\n\treturn nil\n}",
"func DeleteFile(file string) {\n\tfmt.Println(\"delete: \" + file)\n\terr := os.RemoveAll(file)\n\tCheckTestSetupMalfunction(err)\n}",
"func (fs *Fs) RemoveFile(name string) bool {\n\terr := os.Remove(name)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}",
"func (p *TempFileProc) Remove() error {\n\t// only remove the directory if it is a subdir of the default temp dir.\n\tif p.Dir != os.TempDir() {\n\t\tos.RemoveAll(p.Dir)\n\t}\n\t// otherwise just remove the file\n\treturn os.RemoveAll(p.FullPath())\n}",
"func RemoveFile(path string) {\n\tf, err := os.Stat(path)\n\tif err != nil {\n\t\treturn // file probably not exist.\n\t}\n\tif f.IsDir() {\n\t\tlog.Printf(\"RemoveFile called for dir; path=%s\\n\", path)\n\t\treturn // Don't delete dir\n\t}\n\tif err := os.Remove(path); err != nil {\n\t\tlog.Printf(\"RemoveFile failed; path=%s; err=%v\\n\", path, err)\n\t}\n}",
"func (s storage) RemoveFile(filepath string) error {\n\treturn os.Remove(filepath)\n}",
"func (u *UserFile) Remove() {\n\tos.Remove(u.getFilename())\n\treturn\n}",
"func DeleteFile(path string) {\n\tvar err = os.Remove(path)\n\tif err != nil {\n\t\tlog.Printf(\"File not deleted\")\n\t}\n}",
"func verifyFileNotExist(t *testing.T, fileName string) {\n\t_, err := os.Stat(fileName)\n\n\tif err == nil {\n\t\tt.Error(\"Expected error because file should not exist.\")\n\t}\n}",
"func RemoveFile(path string) error {\n\tif err := os.Remove(path); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func (fileSystem *FileSystem) RemoveFile(fileName string) {\n\n\tfor idx, fcb := range (*fileSystem).Directory.FCBArray {\n\n\t\tif fcb.ContainsValidData && (fcb.getFileName() == fileName) {\n\t\t\t// We found the file so we have to mark the fcb as invalid\n\t\t\t// AND the blocks of data as free\n\t\t\t// And modify metadata information\n\t\t\t(*fileSystem).Directory.FCBArray[idx].ContainsValidData = false\n\n\t\t\t// Setting the data blocks as free\n\t\t\tnumberOfBlocks := uint8(math.Ceil(float64(fcb.FileSize) / float64(dataBlockSize)))\n\t\t\tfor i := uint8(0); i < numberOfBlocks; i++ {\n\t\t\t\t(*fileSystem).Directory.FreeDataBlockArray[fcb.StartingBlockID+i] = true\n\t\t\t}\n\n\t\t\t// Set directory number of files in system\n\t\t\t(*fileSystem).Directory.Metadata.NumberOfFilesStored--\n\t\t\tfmt.Printf(\"Sucessfully removed %s from file system\\n\", fileName)\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Println(\"File does not exist in filesystem. Nothing to delete.\")\n\n}",
"func CleanupTempFile(t *testing.T, fileName string) {\n\terr := os.Remove(fileName)\n\tif err != nil {\n\t\tt.Logf(\"Could not remove temp file: %v. Err: %v\\n\", fileName, err)\n\t}\n}",
"func (_m *MockDraOp) RemoveFile(id string) error {\n\tret := _m.ctrl.Call(_m, \"RemoveFile\", id)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}",
"func DeleteFile(src string) error {\n\n\t//проверяем доступ к файлу\n\tf, err := os.OpenFile(src, os.O_RDWR, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = f.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//удаляем\n\terr = os.Remove(src)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\t//log.WithFields(logrus.Fields{\"src\": src, \"dst\": dst, \"err\": err}).Warn(\"Файл перемещён, но удалить его не получилось: удалён кем-то ещё.\")\n\t\t\tfmt.Printf(\"Файлa %s не существует, (неправильное имя или удалён кем-то ещё).\", src)\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"%s - удалить не получилось. %v\", src, err)\n\t}\n\treturn nil\n}",
"func Remove(file string) {\n\tknownFiles[file] = false\n\tdelete(allFiles, file)\n}",
"func DeleteFile(fileName string) (err error) {\n\tif fileName != \"\" {\n\t\texists, err := FileExists(fileName)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not check if file exists %s due to %s\", fileName, err)\n\t\t}\n\n\t\tif exists {\n\t\t\terr = os.Remove(fileName)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"Could not remove file due to %s\", fileName)\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"filename is not valid\")\n\t}\n\treturn nil\n}",
"func (_mr *MockDraOpMockRecorder) RemoveFile(arg0 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"RemoveFile\", reflect.TypeOf((*MockDraOp)(nil).RemoveFile), arg0)\n}",
"func (file *File) Remove() error {\n\treturn os.Remove(file.Path())\n}",
"func TestDirCreateAndRemoveFile(t *testing.T) {\n\trun.skipIfNoFUSE(t)\n\n\trun.mkdir(t, \"dir\")\n\trun.createFile(t, \"dir/file\", \"potato\")\n\trun.checkDir(t, \"dir/|dir/file 6\")\n\n\t// Check we can't delete a directory with stuff in\n\terr := run.os.Remove(run.path(\"dir\"))\n\tassert.Error(t, err, \"file exists\")\n\n\t// Now delete file\n\trun.rm(t, \"dir/file\")\n\n\trun.checkDir(t, \"dir/\")\n\trun.rmdir(t, \"dir\")\n\trun.checkDir(t, \"\")\n}",
"func (h FileHandler) Remove(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\thash := vars[\"filehash\"]\n\n\tfilepath := getHashedFilepath(h.staticDir, hash)\n\n\tif exist := h.fs.Exist(filepath); !exist {\n\t\th.sendBadRequestError(w, \"file with that name doesn`t exist\")\n\t\treturn\n\t}\n\n\tif err := h.fs.RemoveFile(getHashedFilepath(h.staticDir, hash)); err != nil {\n\t\th.sendInternalError(w, \"removing file failed\")\n\t\treturn\n\t}\n\n\tw.Write([]byte(\"ok\"))\n}",
"func (f LocalFS) Remove() error {\n\t// extra security check to ensure we only remove a directory that looks like a plugin\n\tif _, err := os.Stat(filepath.Join(f.basePath, \"plugin.json\")); os.IsNotExist(err) {\n\t\tif _, err = os.Stat(filepath.Join(f.basePath, \"dist/plugin.json\")); os.IsNotExist(err) {\n\t\t\treturn ErrUninstallInvalidPluginDir\n\t\t}\n\t}\n\treturn os.RemoveAll(f.basePath)\n}",
"func TestLogsFileRemove(t *testing.T) {\n\tmultilineWaitPeriod = 10 * time.Millisecond\n\tlogEntryString := \"anything\"\n\ttmpfile, err := createTempFile(\"\", \"\")\n\tdefer os.Remove(tmpfile.Name())\n\trequire.NoError(t, err)\n\n\t_, err = tmpfile.WriteString(logEntryString + \"\\n\")\n\trequire.NoError(t, err)\n\n\ttt := NewLogFile()\n\ttt.Log = TestLogger{t}\n\ttt.FileConfig = []FileConfig{{FilePath: tmpfile.Name(), FromBeginning: true}}\n\ttt.FileConfig[0].init()\n\ttt.started = true\n\n\tlsrcs := tt.FindLogSrc()\n\tif len(lsrcs) != 1 {\n\t\tt.Fatalf(\"%v log src was returned when 1 should be available\", len(lsrcs))\n\t}\n\n\tts := lsrcs[0].(*tailerSrc)\n\tts.outputFn = func(e logs.LogEvent) {}\n\n\tgo func() {\n\t\ttime.Sleep(500 * time.Millisecond)\n\t\tif err := os.Remove(tmpfile.Name()); err != nil {\n\t\t\tt.Errorf(\"Failed to remove tmp file '%v': %v\", tmpfile.Name(), err)\n\t\t}\n\t}()\n\n\tstopped := make(chan struct{})\n\tgo func() {\n\t\tts.runTail()\n\t\tclose(stopped)\n\t}()\n\n\tselect {\n\tcase <-time.After(1 * time.Second):\n\t\tt.Errorf(\"tailerSrc should have stopped after tile is removed\")\n\tcase <-stopped:\n\t}\n\n\ttt.Stop()\n}",
"func deleteDevfile(devfile string) {\n\tif util.CheckPathExists(devfile) {\n\t\t_ = os.Remove(devfile)\n\t}\n}",
"func runRemove(sysLogFileName string) error {\n\n\tvar accept string\n\tfmt.Printf(\"Remove will now start, cannot be cancelled and undone!\\nconfirm (y/n)\\n\\n\")\n\t_, err := fmt.Scanln(&accept)\n\tif accept == \"y\" && err == nil {\n\t\tsysLogFile, err := os.OpenFile(sysLogFileName, os.O_RDWR, 0755)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tscanner := bufio.NewScanner(sysLogFile)\n\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\t\t\ts := strings.Split(line, \"<separator>\")\n\t\t\tsource, dest := s[0], s[1]\n\n\t\t\terr = os.Remove(source)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = os.Remove(dest)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tmessage(0, \"[runRemove] Successfully removed\", source, dest)\n\t\t}\n\t\terr = sysLogFile.Truncate(0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = sysLogFile.Seek(0, 0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = sysLogFile.Close()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmessage(0, \"[runRemove]\")\n\t}\n\treturn nil\n}",
"func remove(destination string) (err error) {\n err = os.Remove(destination)\n return\n}",
"func SafeRMF(path string) error {\n\t// TODO: add safety checks\n\n\treturn os.RemoveAll(path)\n}",
"func (suite *fileTestSuite) TestFileDeleteSingle() {\n\tfileName := suite.testPath + \"/multi0\"\n\tf, err := os.Create(fileName)\n\tsuite.Equal(nil, err)\n\tf.Close()\n\tsuite.fileTestCleanup([]string{fileName})\n}",
"func (s *FileStore) removeImageIfItsNotNeeded(name, keepData string) (bool, error) {\n\tlinkFileName := s.linkFileName(name)\n\tswitch _, err := os.Lstat(linkFileName); {\n\tcase err == nil:\n\t\tdest, err := os.Readlink(linkFileName)\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"error reading link %q: %v\", linkFileName, err)\n\t\t}\n\t\tdestName := filepath.Base(dest)\n\t\tif destName == keepData {\n\t\t\treturn false, nil\n\t\t}\n\t\tif err := os.Remove(linkFileName); err != nil {\n\t\t\treturn false, fmt.Errorf(\"can't remove %q: %v\", linkFileName, err)\n\t\t}\n\t\treturn true, s.removeIfUnreferenced(destName)\n\tcase os.IsNotExist(err):\n\t\treturn true, nil\n\tdefault:\n\t\treturn false, fmt.Errorf(\"can't stat %q: %v\", linkFileName, err)\n\t}\n}",
"func deleteTempFile(filename string) {\n\t_ = os.Remove(filename)\n}",
"func (s *sshClient) RemoveFile(log zerolog.Logger, filePath string) error {\n\tif _, err := s.Run(log, fmt.Sprintf(\"sudo rm -f %s\", filePath), \"\", true); err != nil {\n\t\treturn maskAny(err)\n\t}\n\treturn nil\n}",
"func DeleteFile(path string) (err error) {\n\t// delete file\n\terr = os.Remove(path)\n\treturn\n}",
"func Remove(path string, plaintext_path string, usr_info []string) string {\n\terr := os.Remove(path)\n\tif err != nil {\n\t\treturn ErrorMessage(\"remove\", plaintext_path)\n\t}\n\treturn \"\"\n}",
"func (f File) RemoveFile() error {\n\tpw := Password{Title: f.Title, Password: f.Password} // Password Struct\n\terr := pw.GetFileName() // Reading FileName from Password\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// filepath\n\tfp := path.Join(FileLoc, pw.FileName)\n\n\t// Removing file\n\terr = os.Remove(fp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func deleteFiles(path string, info os.FileInfo, err error) error {\n\tif err == nil && !info.IsDir() && strings.Contains(path, covTmpFile) {\n\t\tos.Remove(path)\n\t}\n\treturn nil\n}",
"func (m *MinikubeRunner) Remove(f assets.CopyableFile) error {\n\t_, err := m.SSH(fmt.Sprintf(\"rm -rf %s\", filepath.Join(f.GetTargetDir(), f.GetTargetName())))\n\treturn err\n}",
"func (fs *FileSystem) Remove(name string) error {\n\tlogger.Println(\"Remove\", name)\n\tname = normalizePath(name)\n\n\t_, err := fs.open(name)\n\tif err != nil {\n\t\treturn err\n\t\t// &os.PathError{Op: \"remove\", Path: name, Err: os.ErrNotExist}\n\t}\n\n\tfs.Lock()\n\tdefer fs.Unlock()\n\n\tdelete(fs.data, name)\n\n\tif err := fs.deleteFileData(name); err != nil {\n\t\treturn &os.PathError{Op: \"remove\", Path: name, Err: err}\n\t}\n\n\treturn nil\n}",
"func (_DappboxManager *DappboxManagerTransactor) RemoveFile(opts *bind.TransactOpts, dappboxAddress common.Address, fileNameMD5 string, fileNameSHA256 string, fileNameSHA1 string, folderAddress common.Address) (*types.Transaction, error) {\n\treturn _DappboxManager.contract.Transact(opts, \"RemoveFile\", dappboxAddress, fileNameMD5, fileNameSHA256, fileNameSHA1, folderAddress)\n}",
"func DeleteIfExists(filepath string) (ok bool) {\n\n\tif _, err := os.Stat(filepath); os.IsNotExist(err) {\n\t\treturn false\n\t} else {\n\n\t\terr := os.RemoveAll(filepath)\n\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\n\t\treturn true\n\t}\n\n}",
"func (file PIDFile) Remove() error {\n\tif err := os.Remove(file.path); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func Remove(file *File) error {\n\treturn RemoveCtx(context.Background(), file)\n}",
"func _file_delete(call otto.FunctionCall) otto.Value {\n\tpath, _ := call.Argument(0).ToString()\n\n\terr := os.RemoveAll(path)\n\tif err != nil {\n\t\tjsThrow(call, err)\n\t}\n\treturn otto.Value{}\n}",
"func (cl *Client) Remove(remoteFile string) (err error) {\n\tvar (\n\t\tlogp = \"Remove\"\n\t\treq = cl.generatePacket()\n\t\tpayload = req.fxpRemove(remoteFile)\n\t)\n\n\tres, err := cl.send(payload)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: %w\", logp, err)\n\t}\n\tif res.kind != packetKindFxpStatus {\n\t\treturn errUnexpectedResponse(packetKindFxpStatus, res.kind)\n\t}\n\tif res.code != statusCodeOK {\n\t\treturn handleStatusCode(res.code, res.message)\n\t}\n\n\treturn nil\n}",
"func DeleteFile(path string) (err error) {\n\treturn os.Remove(path)\n}",
"func removeFile(zipFileName string) error {\n\terr := os.Remove(zipFileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func cleanupTempFile(f *os.File) {\n\tif f == nil {\n\t\treturn\n\t}\n\tf.Close()\n\tos.Remove(f.Name())\n}",
"func (v *VolumePublishManager) DeleteFailedUpgradeTrackingFile(ctx context.Context, file os.FileInfo) {\n\tfilename := path.Join(config.VolumeTrackingInfoPath, file.Name())\n\n\tif strings.Contains(file.Name(), \"tmp\") {\n\t\t_, err := fileDeleter(ctx, filename, \"tmp volume tracking file\")\n\t\tif err != nil {\n\t\t\tLogc(ctx).WithField(\"filename\", filename).Warn(\"Could not delete temporary volume tracking file.\")\n\t\t}\n\t}\n}",
"func deletePemFile() {\n\terr := os.Remove(FILE)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n}",
"func (m *Model) checkRemove() error {\n\tremoveDir := m.RootPath + \"/\" + shared.TINZENITEDIR + \"/\" + shared.REMOVEDIR\n\tallRemovals, err := ioutil.ReadDir(removeDir)\n\tif err != nil {\n\t\tm.log(\"reading all removals failed\")\n\t\treturn err\n\t}\n\t// check for each removal\n\tfor _, stat := range allRemovals {\n\t\t// update removal stats and write own peer to them\n\t\terr = m.UpdateRemovalDir(stat.Name(), m.SelfID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// check if we can complete the removal\n\t\terr := m.completeTrackedRemoval(stat.Name())\n\t\tif err != nil {\n\t\t\t// notify of error but don't stop, rest can still be checked\n\t\t\tm.log(\"completeTrackedRemoval:\", err.Error())\n\t\t}\n\t\t// warn of possible orphans\n\t\tif time.Since(stat.ModTime()) > removalTimeout {\n\t\t\tm.warn(\"Removal may be orphaned! \", stat.Name())\n\t\t\t/*TODO this may be called even if it has just been removed... do better logic!\n\t\t\tAlso: is there something we can do in this case?*/\n\t\t}\n\t\t// warn of possibly unapplied removals:\n\t\tsubPath, err := m.GetSubPath(stat.Name())\n\t\t// if err just skip the check (can happen if the file has been removed, so ok)\n\t\tif err == nil && m.IsTracked(m.RootPath+\"/\"+subPath) {\n\t\t\tm.warn(\"Removal may be unapplied!\", subPath)\n\t\t}\n\t}\n\t// also remove old local remove notifies:\n\tlocalDir := m.RootPath + \"/\" + shared.TINZENITEDIR + \"/\" + shared.LOCALDIR + \"/\" + shared.REMOVESTOREDIR\n\tallLocals, err := ioutil.ReadDir(localDir)\n\tif err != nil {\n\t\tm.log(\"reading of local remove notifies failed!\")\n\t\treturn err\n\t}\n\tfor _, stat := range allLocals {\n\t\tif time.Since(stat.ModTime()) > removalLocal {\n\t\t\t// remove notify\n\t\t\terr := os.Remove(localDir + \"/\" + stat.Name())\n\t\t\tif err != nil {\n\t\t\t\tm.warn(\"Failed to remove notify object:\", err.Error())\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}",
"func (s *SSHRunner) Remove(f assets.CopyableFile) error {\n\tdst := path.Join(f.GetTargetDir(), f.GetTargetName())\n\tklog.Infof(\"rm: %s\", dst)\n\n\tsess, err := s.session()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"getting ssh session\")\n\t}\n\n\tdefer sess.Close()\n\treturn sess.Run(fmt.Sprintf(\"sudo rm %s\", dst))\n}",
"func (s *Local) Remove(path string) error {\n\tfullpath := filepath.Join(s.dir, path)\n\n\tif err := os.Remove(fullpath); err != nil {\n\t\treturn fmt.Errorf(\"failed to remove a file (%q): %v\", fullpath, err)\n\t}\n\n\treturn nil\n}",
"func (app *application) deleteFile(filePath string) error {\n\terr := os.Remove(filePath[22:])\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func (u *User) RemoveFile(tx *pop.Connection) error {\n\treturn removeFile(tx, u)\n}",
"func (w *Watcher) doRemove(name string) {\n\tdelete(w.names, name)\n\n\tfi, ok := w.files[name]\n\tif !ok {\n\t\treturn // not exists anymore\n\t}\n\n\t// remove itself\n\tdelete(w.files, name)\n\n\tif !fi.IsDir() {\n\t\t// not a directory, return\n\t\treturn\n\t}\n\n\tfor fp := range w.files {\n\t\t// remove all files in this directory\n\t\tif filepath.Dir(fp) == name {\n\t\t\tdelete(w.files, fp)\n\t\t}\n\t}\n}",
"func (m *Attachment) Remove() error {\n\treturn core.DeleteFile(m.PATH)\n}",
"func (tfb *TempFileBlock) Remove() error {\n\treturn os.Remove(tfb.TempFile)\n}",
"func Remove(arg string) {\n\tif arg != \"\" {\n\t\terr := os.Remove(arg)\n\t\tutils.Check(err)\n\t} else {\n\t\tutils.CliErrorln(\"Filename must be included for remove command\") // If this function name changes,\n\t\t// CHANGE THIS STRING ERROR TOO\n\t}\n}",
"func DeleteFile(path string) error {\n\treturn os.Remove(path)\n}",
"func RemoveFileHandler(w http.ResponseWriter, r *http.Request) {\n\thttpSession, _ := session.HTTPSession.Get(r, session.CookieName)\n\tif httpSession.IsNew {\n\t\thttp.Error(w, \"Forbidden\", http.StatusForbidden)\n\n\t\treturn\n\t}\n\tuid := httpSession.Values[\"uid\"].(string)\n\n\tresult := gulu.Ret.NewResult()\n\tdefer gulu.Ret.RetResult(w, r, result)\n\n\tvar args map[string]interface{}\n\n\tif err := json.NewDecoder(r.Body).Decode(&args); err != nil {\n\t\tlogger.Error(err)\n\t\tresult.Code = -1\n\n\t\treturn\n\t}\n\n\tpath := args[\"path\"].(string)\n\n\tif gulu.Go.IsAPI(path) || !session.CanAccess(uid, path) {\n\t\thttp.Error(w, \"Forbidden\", http.StatusForbidden)\n\n\t\treturn\n\t}\n\n\tsid := args[\"sid\"].(string)\n\n\twSession := session.WideSessions.Get(sid)\n\n\tif !removeFile(path) {\n\t\tresult.Code = -1\n\n\t\twSession.EventQueue.Queue <- &event.Event{Code: event.EvtCodeServerInternalError, Sid: sid,\n\t\t\tData: \"can't remove file \" + path}\n\n\t\treturn\n\t}\n\n\tlogger.Debugf(\"Removed a file [%s] by user [%s]\", path, wSession.UserId)\n}",
"func remove(path string) {\n\tif err := os.RemoveAll(path); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}",
"func DeleteTxt(path string, args...string) bool {\n\tif checkPath(path, args) == false {\n\t\tlogging.Error(errors.New(\"invalid path\"))\n\t\treturn false\n\t}\n\terr := os.Remove(path)\n\tif err != nil {\n\t\tlogging.Error(err)\n\t\treturn false\n\t}\n\treturn true\n}",
"func (f *File) Delete() {\n\tif f.path != \"\" {\n\t\tos.Remove(f.path)\n\t}\n}",
"func emptyFile(path string, target os.FileInfo, testMode bool) error {\n\n\t// header message\n\tfmt.Println(magB(\"\\n:: File:\"), path)\n\tfmt.Println(magB(\"Targeted Size\\tUnit\\t Item\"))\n\n\t//? Maybe add a new age speciffic to files?\n\t// get the age in config\n\tdays := viper.GetInt(\"duration\")\n\n\t// check the age\n\ttimeDiff := time.Now().Sub(target.ModTime()).Hours()\n\n\t// infos\n\tsize, unit := FormatSize(float64(target.Size()))\n\n\tvar msg string\n\n\tif timeDiff >= float64(days*24) {\n\n\t\tif testMode {\n\t\t\t// Test mode, don't delete\n\t\t\t// TODO: Improve\n\t\t\tmsg = fmt.Sprintln(redB(\"YES\\t \"), color.HiCyanString(fmt.Sprintf(\"%v\\t%s\", size, unit)), \"\\t\", path+target.Name())\n\t\t} else {\n\t\t\t// Actual deletion\n\t\t\tif err := os.Truncate(path, 0); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tmsg = fmt.Sprintln(redB(\"DONE\\t \"), color.HiCyanString(fmt.Sprintf(\"%v\\t%s\", size, unit)), \"\\t\", path+target.Name())\n\t\t}\n\t} else {\n\t\tmsg = fmt.Sprintln(greenB(\"NOPE\\t \"), color.HiCyanString(fmt.Sprintf(\"%v\\t%s\", size, unit)), \"\\t\", path+target.Name())\n\t}\n\n\tfmt.Println(msg)\n\n\treturn nil\n}",
"func (d *DB) DeleteFile(path string) error {\n\tvar err = os.Remove(path)\n\tfmt.Println(\"==> done deleting file -> \" + path)\n\treturn err\n}",
"func RemoveConfigFile() {\n\tpath := GetUserConfigPath()\n\n\terr := os.Remove(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn\n\t\t}\n\t}\n\tExpect(err).ShouldNot(HaveOccurred())\n}",
"func DeleteFile(location string) error {\n\tif err := os.Remove(location); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func DeleteFile(uri string) error {\n\terr := os.Remove(uri)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func mustWriteFile(path string, data []byte) {\n\tlog.Printf(\"creating %q\", path)\n\tif err := ioutil.WriteFile(path, data, 0644); err != nil {\n\t\tpanic(err)\n\t}\n}",
"func (f *FileWatcher) Remove(path string) error {\n\t// Clean the file path\n\tpath = filepath.Clean(path)\n\n\t// TODO: Also remove recursive added directory paths added with Add!\n\n\treturn f.watcher.Remove(path)\n}",
"func TestDeleteFile(t *testing.T) {\n\tif testing.Short() && !build.VLONG {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\t// Create filesystem.\n\troot := filepath.Join(testDir(t.Name()), \"fs-root\")\n\tfs := newTestFileSystem(root)\n\t// Add a file to the root dir.\n\tsp := newSiaPath(\"foo\")\n\tfs.addTestSiaFile(sp)\n\t// Open the file.\n\tsf, err := fs.OpenSiaFile(sp)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// File shouldn't be deleted yet.\n\tif sf.Deleted() {\n\t\tt.Fatal(\"foo is deleted before calling delete\")\n\t}\n\t// Delete it using the filesystem.\n\tif err := fs.DeleteFile(sp); err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// Check that the open instance is marked as deleted.\n\tif !sf.Deleted() {\n\t\tt.Fatal(\"foo should be marked as deleted but wasn't\")\n\t}\n\t// Check that we can't open another instance of foo and that we can't create\n\t// a new file at the same path.\n\tif _, err := fs.OpenSiaFile(sp); !errors.Contains(err, ErrNotExist) {\n\t\tt.Fatal(\"err should be ErrNotExist but was:\", err)\n\t}\n\tif err := fs.addTestSiaFileWithErr(sp); err != nil {\n\t\tt.Fatal(\"err should be nil but was:\", err)\n\t}\n}",
"func (m *Model) localRemove(path *shared.RelativePath) error {\n\t// get stin for notify\n\tstin, exists := m.StaticInfos[path.SubPath()]\n\tif !exists {\n\t\tm.log(\"LocalRemove: stin is missing!\")\n\t\treturn shared.ErrIllegalFileState\n\t}\n\t// sanity check\n\tif m.IsRemoved(stin.Identification) {\n\t\t// shouldn't happen but let's be sure; warn at least\n\t\tm.warn(\"LocalRemove: file removal already begun!\")\n\t}\n\t// direct remove (removes file/dir AND from m.Tracked and m.Static)\n\terr := m.directRemove(path)\n\tif err != nil {\n\t\tm.log(\"LocalRemove: failed to directly remove file!\")\n\t\treturn err\n\t}\n\t// write peers to check and own peer to done\n\terr = m.UpdateRemovalDir(stin.Identification, m.SelfID)\n\tif err != nil {\n\t\tm.log(\"failed to update removal dir for\", stin.Identification)\n\t\treturn err\n\t}\n\t// update removal dir here so that creations etc are sent before notify below!\n\terr = m.updateLocal(m.RootPath + \"/\" + shared.TINZENITEDIR + \"/\" + shared.REMOVEDIR + \"/\" + stin.Identification)\n\tif err != nil {\n\t\tm.warn(\"partial update on local remove failed!\")\n\t\t// but continue on because the changes will be synchronized later then anyway\n\t}\n\t// update version\n\tstin.Version.Increase(m.SelfID)\n\t// send notify\n\tnotifyObj := &shared.ObjectInfo{\n\t\tIdentification: stin.Identification,\n\t\tName: path.LastElement(),\n\t\tPath: path.SubPath(),\n\t\tContent: stin.Content,\n\t\tVersion: stin.Version,\n\t\tDirectory: stin.Directory}\n\tm.notify(shared.OpRemove, notifyObj)\n\treturn nil\n}",
"func (fs *Mysqlfs) Remove(filename string) error {\n\treturn fs.storage.RemoveFile(filename)\n}",
"func (suite TestSuite) RemoveErr() error {\n\tif err := os.Remove(suite.Name + \".err\"); err != nil && !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func deleteFile(ctx context.Context, baseDir, hash, extension string) error {\n\t// Verify object exists.\n\tfilepath := getPathByHash(ctx, baseDir, hash, extension)\n\n\treturn os.Remove(filepath)\n}",
"func (storage *B2Storage) DeleteFile(threadIndex int, filePath string) (err error) {\n\n if strings.HasSuffix(filePath, \".fsl\") {\n filePath = filePath[:len(filePath) - len(\".fsl\")]\n entries, err := storage.clients[threadIndex].ListFileNames(filePath, true, true)\n if err != nil {\n return err\n }\n\n toBeDeleted := false\n\n for _, entry := range entries {\n if entry.FileName != filePath || (!toBeDeleted && entry.Action != \"hide\" ) {\n continue\n }\n\n toBeDeleted = true\n\n err = storage.clients[threadIndex].DeleteFile(filePath, entry.FileID)\n if err != nil {\n return err\n }\n }\n\n return nil\n\n } else {\n entries, err := storage.clients[threadIndex].ListFileNames(filePath, true, false)\n if err != nil {\n return err\n }\n\n if len(entries) == 0 {\n return nil\n }\n return storage.clients[threadIndex].DeleteFile(filePath, entries[0].FileID)\n }\n}"
] | [
"0.6685234",
"0.658453",
"0.65203536",
"0.64907736",
"0.6155414",
"0.6140909",
"0.61387414",
"0.59828866",
"0.5904099",
"0.5857852",
"0.5846338",
"0.5840637",
"0.5813969",
"0.5797557",
"0.57663894",
"0.57592773",
"0.57434434",
"0.57216614",
"0.5706215",
"0.57027507",
"0.56904334",
"0.56624734",
"0.56624734",
"0.56285733",
"0.5616874",
"0.56071067",
"0.5605711",
"0.55899286",
"0.5563946",
"0.55583894",
"0.5557834",
"0.5556607",
"0.5546524",
"0.5526474",
"0.5520127",
"0.5502609",
"0.5488262",
"0.54779744",
"0.5455997",
"0.54558337",
"0.540429",
"0.5398834",
"0.53891313",
"0.5388073",
"0.5366916",
"0.5359035",
"0.53264743",
"0.5314935",
"0.53098935",
"0.530772",
"0.5299657",
"0.5296673",
"0.52949715",
"0.5294945",
"0.5285895",
"0.52806425",
"0.526132",
"0.5260275",
"0.5258817",
"0.52584654",
"0.5253511",
"0.5240902",
"0.5236714",
"0.522779",
"0.5226931",
"0.5218221",
"0.5212068",
"0.5195539",
"0.51859355",
"0.518016",
"0.5171409",
"0.5166968",
"0.5159974",
"0.5158922",
"0.51553184",
"0.51284504",
"0.512679",
"0.51238286",
"0.5120446",
"0.5118901",
"0.5106398",
"0.51042974",
"0.5088291",
"0.5086531",
"0.5086069",
"0.50681627",
"0.5067018",
"0.50646275",
"0.50637734",
"0.50596064",
"0.5055084",
"0.50467616",
"0.50415355",
"0.50305754",
"0.50292504",
"0.5012793",
"0.501018",
"0.5007172",
"0.49913463",
"0.49881813"
] | 0.74494314 | 0 |
IsObjectCompressed returns true iff path is of a compressed, i.e., contains a .lz4 extension | func IsObjectCompressed(path string) bool {
return path[len(path)-len(lz4.Extension):] == lz4.Extension
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (ms *memoryStorer) IsCompressed() bool {\n\treturn true\n}",
"func IsCompressed(id uint8) bool {\n\treturn id >= 20\n}",
"func IsCompressed(msg []byte) bool {\n\treturn msg[0]&compressionMask != 0\n}",
"func IsCompressed(proof *CommitmentProof) bool {\n\treturn proof.GetCompressed() != nil\n}",
"func (info TrackInfo) IsCompressed() bool {\n\t// bit 31 - data is compressed\n\treturn info&0x80000000 != 0\n}",
"func IsObjectDirectory(path string) bool {\n\treturn path[len(path)-len(DirectoryExtension):] == DirectoryExtension\n}",
"func IsObjectPath(path string) bool {\n\t//TODO add support for domain style paths when the domain support is going to be merged\n\tparts := strings.SplitN(strings.Trim(path, \"/\"), \"/\", 2)\n\treturn len(parts) == 2 && parts[1] != \"\"\n}",
"func IsCompressedWriteResourceName(name string) bool {\n\treturn strings.Contains(name, \"compressed-blobs/zstd\")\n}",
"func isGzipped(b []byte) bool {\n\treturn b[0] == 0x1f && b[1] == 0x8b\n}",
"func (c *Client) IsCompress() bool {\n\treturn c.isCompressed\n}",
"func isPathToPrecompiledObjectFile(path string) bool {\n\treturn strings.Count(path, string(os.PathSeparator)) == separatorsNumber && !isDir(path)\n}",
"func IsZip(filepath string) bool {\n\tf, err := os.Open(filepath)\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer f.Close()\n\n\tbuf := make([]byte, 4)\n\tif n, err := f.Read(buf); err != nil || n < 4 {\n\t\treturn false\n\t}\n\n\treturn bytes.Equal(buf, []byte(\"PK\\x03\\x04\"))\n}",
"func isTarSz(tarszPath string) bool {\n\tf, err := os.Open(tarszPath)\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer f.Close()\n\n\tszr := snappy.NewReader(f)\n\tbuf := make([]byte, tarBlockSize)\n\tn, err := szr.Read(buf)\n\tif err != nil || n < tarBlockSize {\n\t\treturn false\n\t}\n\n\treturn hasTarHeader(buf)\n}",
"func isTarXz(tarxzPath string) bool {\n\tf, err := os.Open(tarxzPath)\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer f.Close()\n\n\txzr, err := xz.NewReader(f)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tbuf := make([]byte, tarBlockSize)\n\tn, err := xzr.Read(buf)\n\tif err != nil || n < tarBlockSize {\n\t\treturn false\n\t}\n\n\treturn hasTarHeader(buf)\n}",
"func IsGzip(b []byte) bool {\n\tif len(b) < 2 {\n\t\treturn false\n\t}\n\treturn b[0] == 0x1f && b[1] == 0x8b\n}",
"func GetMsgCompressedFlag(header uint64) bool {\n return (header & (1 << msgCompressedOffset)) != 0\n}",
"func (cmp Compressor) Compress(path string) error {\n compressedPath := path + \".lz4\"\n\n err := exec.Command(cmp.lz4Path, path, compressedPath).Run()\n if err != nil {\n return err\n }\n\n return os.Remove(path)\n}",
"func isZipped(fname string) bool {\n\treturn filepath.Ext(fname) == \".zip\"\n}",
"func isArchiveFormatZip(archivePath string) error {\n\treadCloser, err := zip.OpenReader(archivePath)\n\tif err == nil {\n\t\t_ = readCloser.Close()\n\t}\n\treturn err\n}",
"func extension(path string) (bool, string, bool, error) {\n\tif f, err := os.Stat(path + CompressedExt); err == nil && f.IsDir() == false {\n\t\treturn true, path + CompressedExt, true, nil\n\t} else if os.IsNotExist(err) {\n\t\treturn false, path + NormalExt, false, nil\n\t} else {\n\t\treturn false, \"\", false, err\n\t}\n}",
"func (a *scriptAddress) Compressed() bool {\n\treturn false\n}",
"func isMultipartObject(storage StorageAPI, bucket, object string) bool {\n\t_, err := storage.StatFile(bucket, pathJoin(object, multipartMetaFile))\n\tif err != nil {\n\t\tif err == errFileNotFound {\n\t\t\treturn false\n\t\t}\n\t\terrorIf(err, \"Failed to stat file \"+bucket+pathJoin(object, multipartMetaFile))\n\t\treturn false\n\t}\n\treturn true\n}",
"func DetectCompression(source []byte) Compression {\n\tfor compression, m := range map[Compression][]byte{\n\t\tBzip2: {0x42, 0x5A, 0x68},\n\t\tGzip: {0x1F, 0x8B, 0x08},\n\t\tXz: {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00},\n\t} {\n\t\tif len(source) < len(m) {\n\t\t\tcontinue\n\t\t}\n\t\tif bytes.Equal(m, source[:len(m)]) {\n\t\t\treturn compression\n\t\t}\n\t}\n\treturn Uncompressed\n}",
"func (a *managedAddress) Compressed() bool {\n\treturn a.compressed\n}",
"func CompressionByID(id uint16) (Compression, bool) {\n\tc, ok := compressions[id]\n\tif !ok {\n\t\tc = DefaultCompression\n\t}\n\treturn c, ok\n}",
"func (resp *Response) IsGzipped() bool {\n\tcontentEncoding := resp.Header.Get(\"Content-Encoding\")\n\tcontentEncoding = strings.TrimSpace(strings.ToLower(contentEncoding))\n\treturn contentEncoding == \"gzip\"\n}",
"func isObject(file os.FileInfo) bool {\n\treturn !file.IsDir() && strings.HasSuffix(file.Name(), \".cql\")\n}",
"func isZip(fileName string, log *logrus.Logger) bool {\n\tz, err := ioutil.ReadFile(fileName)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn false\n\t}\n\n\t// these are the 3 magic numbers for different zip types\n\tzipMagic := [4]byte{0x50, 0x4B, 0x03, 0x04} // PK..\n\temptyZip := [4]byte{0x50, 0x4B, 0x05, 0x06} // empty zip\n\tspannedZip := [4]byte{0x50, 0x4B, 0x07, 0x08} // spanned zip\n\n\t// get the 4 byte array to compare with the header\n\tzipHdr := [4]byte{z[0], z[1], z[2], z[3]}\n\n\tswitch {\n\tcase zipHdr == zipMagic:\n\t\treturn true\n\tcase zipHdr == emptyZip:\n\t\tlog.Error(\"empty zip found\")\n\t\treturn false\n\tcase zipHdr == spannedZip:\n\t\tlog.Error(\"spanned zip found\")\n\t\treturn false\n\tdefault:\n\t\tlog.Error(\"unknown file format found\")\n\t\treturn false\n\t}\n}",
"func (j JO) IsObject(path ...string) (bool, error) {\n\treturn IsObject(j, path...)\n}",
"func compress(file_path string) error {\n\n\tfile, err := os.Open(file_path)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer file.Close()\n\n\tnewFile, err := os.Create(file_path + \".gz\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer newFile.Close()\n\n\tgzipOut := gzip.NewWriter(newFile)\n\n\t_, err = io.Copy(newFile, file)\n\n\tgzipOut.Close()\n\n\treturn err\n\n}",
"func IsZipFile(value string) bool {\n\tvalue = strings.ToLower(value)\n\tif strings.HasSuffix(value, \".zip\") {\n\t\treturn true\n\t}\n\treturn false\n}",
"func isOCCompressedValidElement(e *yang.Entry) bool {\n\tswitch {\n\tcase hasOnlyChild(e) && children(e)[0].IsList():\n\t\t// This is a surrounding container for a list which is removed from the\n\t\t// structure.\n\t\treturn false\n\tcase isRoot(e):\n\t\t// This is a top-level module within the goyang structure, so is not output.\n\t\treturn false\n\tcase isConfigState(e):\n\t\t// This is a container that is called config or state, which is removed from\n\t\t// a compressed OpenConfig schema.\n\t\treturn false\n\tcase isChoiceOrCase(e):\n\t\t// This is a choice or case node that is removed from the overall schema\n\t\t// so code generation does not occur for it.\n\t\treturn false\n\t}\n\treturn true\n}",
"func didCompress(input []byte) bool {\n\tvar output bytes.Buffer\n\n\tw := zlib.NewWriter(&output)\n\t_, err := w.Write(input)\n\tw.Close()\n\n\treturn err == nil && len(input) > output.Len()\n}",
"func ShouldBeCompressed(recoveryFlag int) bool {\n\treturn recoveryFlag >= 31\n}",
"func (fa FileAttributes) IsArchive() bool {\n\treturn fa&32 > 0\n}",
"func DecodeCompressedCompressionType(value string) DecodeCompressedAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"compression_type\"] = value\n\t}\n}",
"func wantsCompressedResponse(httpRequest *http.Request, httpWriter http.ResponseWriter) (bool, string) {\n\tif contentEncoding := httpWriter.Header().Get(HEADER_ContentEncoding); contentEncoding != \"\" {\n\t\treturn false, \"\"\n\t}\n\theader := httpRequest.Header.Get(HEADER_AcceptEncoding)\n\tgi := strings.Index(header, ENCODING_GZIP)\n\tzi := strings.Index(header, ENCODING_DEFLATE)\n\t// use in order of appearance\n\tif gi == -1 {\n\t\treturn zi != -1, ENCODING_DEFLATE\n\t} else if zi == -1 {\n\t\treturn gi != -1, ENCODING_GZIP\n\t} else {\n\t\tif gi < zi {\n\t\t\treturn true, ENCODING_GZIP\n\t\t}\n\t\treturn true, ENCODING_DEFLATE\n\t}\n}",
"func isJSONFile(path string) bool {\n\treturn strings.ToLower(filepath.Ext(path)) == \".json\"\n}",
"func (c *Client) SupportCompress(mech string) (bool, error) {\n\treturn c.client.Support(Capability + \"=\" + mech)\n}",
"func (me TdtypeType) IsPath() bool { return me.String() == \"path\" }",
"func isEncryptedObject(headers http.Header) bool {\n\tencrptedKey := headers.Get(oss.HTTPHeaderOssMetaPrefix + OssClientSideEncryptionKey)\n\treturn len(encrptedKey) > 0\n}",
"func (toneAnalyzer *ToneAnalyzerV3) GetEnableGzipCompression() bool {\n\treturn toneAnalyzer.Service.GetEnableGzipCompression()\n}",
"func (o *Object) isFile() bool {\n\treturn !strings.HasSuffix(o.Key, \"/\")\n}",
"func (file *GalangFile) IsJSONFile(path string) bool {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tlogs.Error(err)\n\t\treturn false\n\t}\n\treturn file.IsJSONByte(b)\n}",
"func Test(contentType string) bool {\n\tdbMatched := false\n\n\texts, err := mime.ExtensionsByType(contentType)\n\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tfor _, ext := range exts {\n\t\t// all exts returned by mime.ExtensionsByType are always\n\t\t// start with \".\"\n\t\tif entry, ok := mimedb.DB[ext[1:]]; ok {\n\t\t\tdbMatched = true\n\n\t\t\tif entry.Compressible {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\tif !dbMatched && compressibleTypeRegExp.MatchString(contentType) {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (sdk Sdk) IsArchived() bool {\n\treturn sdk.archiveFile() != \"\"\n}",
"func (v Var) Compression() (shuffle, deflate bool, deflateLevel int, err error) {\n\tvar (\n\t\tcShuffle C.int\n\t\tcDeflate C.int\n\t\tcDeflateLevel C.int\n\t)\n\terr = newError(C.nc_inq_var_deflate(C.int(v.ds), v.id, &cShuffle, &cDeflate, &cDeflateLevel))\n\treturn cShuffle != 0, cDeflate != 0, int(cDeflateLevel), err\n}",
"func (o *LastMileAccelerationOptions) HasCompressionLevel() bool {\n\tif o != nil && o.CompressionLevel != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (w *RotateWriter) compress(source string) (err error) {\n\t// Read uncompressed file.\n\trawfile, err := os.Open(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer rawfile.Close()\n\n\t// Calculate the buffer size.\n\tinfo, _ := rawfile.Stat()\n\trawbytes := make([]byte, info.Size())\n\n\t// Read rawfile content into buffer.\n\tbuffer := bufio.NewReader(rawfile)\n\t_, err = buffer.Read(rawbytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar buf bytes.Buffer\n\twriter := gzip.NewWriter(&buf)\n\twriter.Write(rawbytes)\n\twriter.Close()\n\n\terr = ioutil.WriteFile(source+\".gz\", buf.Bytes(), info.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Remove uncompressed.\n\tgo os.Remove(source)\n\n\treturn nil\n}",
"func S3Path(path string) bool {\n\treturn s3path(path)\n}",
"func (d *DefaultCompress) Compressible(contentType string, contentLength int) bool {\n\tif contentLength > 0 && contentLength <= 1024 {\n\t\treturn false\n\t}\n\treturn contentType != \"\"\n}",
"func needsConversion(mediaType string, compressionType compression.Type) (bool, error) {\n\tswitch compressionType {\n\tcase compression.Uncompressed:\n\t\tif !images.IsLayerType(mediaType) || compression.FromMediaType(mediaType) == compression.Uncompressed {\n\t\t\treturn false, nil\n\t\t}\n\tcase compression.Gzip:\n\t\tif !images.IsLayerType(mediaType) || compression.FromMediaType(mediaType) == compression.Gzip {\n\t\t\treturn false, nil\n\t\t}\n\tcase compression.Zstd:\n\t\tif !images.IsLayerType(mediaType) || compression.FromMediaType(mediaType) == compression.Zstd {\n\t\t\treturn false, nil\n\t\t}\n\tcase compression.EStargz:\n\t\tif !images.IsLayerType(mediaType) {\n\t\t\treturn false, nil\n\t\t}\n\tdefault:\n\t\treturn false, fmt.Errorf(\"unknown compression type during conversion: %q\", compressionType)\n\t}\n\treturn true, nil\n}",
"func isTarBz2(tarbz2Path string) bool {\r\n\tf, err := os.Open(tarbz2Path)\r\n\tif err != nil {\r\n\t\treturn false\r\n\t}\r\n\tdefer f.Close()\r\n\r\n\tbz2r, err := bzip2.NewReader(f, nil)\r\n\tif err != nil {\r\n\t\treturn false\r\n\t}\r\n\tdefer bz2r.Close()\r\n\r\n\tbuf := make([]byte, tarBlockSize)\r\n\tn, err := bz2r.Read(buf)\r\n\tif err != nil || n < tarBlockSize {\r\n\t\treturn false\r\n\t}\r\n\r\n\treturn hasTarHeader(buf)\r\n}",
"func (s *BasePlSqlParserListener) EnterLob_compression_clause(ctx *Lob_compression_clauseContext) {}",
"func Compress(inPath string, tmpDir string) (string, error) {\n\t// create a temporary file with a unique name compress it -- multiple files\n\t// are named 000: pg_notify/0000, pg_subtrans/0000\n\toutFile, err := ioutil.TempFile(tmpDir, \"pgCarpenter.\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// open input file\n\tinFile, err := os.Open(inPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// we open this for read only, and this process exists after a finite (short)\n\t// period of time; there's no need to throw an error if closing it fails\n\tdefer inFile.Close()\n\n\t// buffer read from the input file and lz4 writer\n\tr := bufio.NewReader(inFile)\n\tw := lz4.NewWriter(outFile)\n\n\t// read 4k at a time\n\tbuf := make([]byte, 4096)\n\tfor {\n\t\tn, err := r.Read(buf)\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\t// we're done\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t// write the 4k chunk\n\t\tif _, err := w.Write(buf[:n]); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\t// flush any pending compressed data\n\tif err = w.Flush(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// make sure we successfully close the compressed file\n\tif err := outFile.Close(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn outFile.Name(), nil\n}",
"func compressGZ(d []byte) ([]byte, error) {\n\tbuf := bytes.Buffer{}\n\tzw := gzip.NewWriter(&buf)\n\tif _, err := zw.Write(d); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := zw.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}",
"func (c *Compression) checkFileCompressibilityAndType(in io.Reader) (newReader io.Reader, compressible bool, mimeType string, err error) {\n\t// Unwrap accounting, get compressibility of file, rewind reader, then wrap accounting back on\n\tin, wrap := accounting.UnWrap(in)\n\tvar b bytes.Buffer\n\t_, err = io.CopyN(&b, in, c.HeuristicBytes)\n\tif err != nil && err != io.EOF {\n\t\treturn nil, false, \"\", err\n\t}\n\tcompressible, _, err = c.GetFileCompressionInfo(bytes.NewReader(b.Bytes()))\n\tif err != nil {\n\t\treturn nil, false, \"\", err\n\t}\n\tmimeType, _ = mimetype.Detect(b.Bytes())\n\tin = io.MultiReader(bytes.NewReader(b.Bytes()), in)\n\tin = wrap(in)\n\treturn in, compressible, mimeType, nil\n}",
"func (s *segment) Compress() error {\n\tif s.gReader != nil {\n\t\treturn ErrImmutableSegment // segment is already compressed and is immutable\n\t}\n\ts.appender.Close()\n\tif s.gReader != nil {\n\t\ts.gReader.Close()\n\t}\n\tf, err := os.OpenFile(s.path+CompressedExt, os.O_CREATE|os.O_WRONLY, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgWriter := gzip.NewWriter(f)\n\t_, err = s.rFile.Seek(0, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(gWriter, s.rFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = gWriter.Flush()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgWriter.Close()\n\ts.rFile.Close()\n\ts.appender.Close()\n\treturn os.Remove(s.filename)\n}",
"func canCompress(value value) bool { return value&0x7fffffff == value }",
"func isArchiveFormatRar(archivePath string, password string) error {\n\treadCloser, err := rardecode.OpenReader(archivePath, password)\n\tif err == nil {\n\t\t_ = readCloser.Close()\n\t}\n\treturn err\n}",
"func IsMeta(p string) bool {\n\tbase := path.Base(p)\n\n\t// https://wiki.debian.org/RepositoryFormat#Compression_of_indices\n\tswitch {\n\tcase strings.HasSuffix(base, \".gz\"):\n\t\tbase = base[0 : len(base)-3]\n\tcase strings.HasSuffix(base, \".bz2\"):\n\t\tbase = base[0 : len(base)-4]\n\tcase strings.HasSuffix(base, \".xz\"):\n\t\tbase = base[0 : len(base)-3]\n\tcase strings.HasSuffix(base, \".lzma\"):\n\t\tbase = base[0 : len(base)-5]\n\tcase strings.HasSuffix(base, \".lz\"):\n\t\tbase = base[0 : len(base)-3]\n\t}\n\n\tswitch base {\n\tcase \"Release\", \"Release.gpg\", \"InRelease\":\n\t\treturn true\n\tcase \"Packages\", \"Sources\", \"Index\":\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (b *Bucket) IsReadablePath(pth string, id did.DID) bool {\n\tmd, _, ok := b.GetMetadataForPath(pth, false)\n\tif !ok {\n\t\treturn false\n\t}\n\trole, ok := md.Roles[\"*\"]\n\tif ok && role > NoneRole {\n\t\treturn true\n\t}\n\trole, ok = md.Roles[id]\n\tif ok && role > NoneRole {\n\t\treturn true\n\t}\n\treturn false\n}",
"func Decompress(src io.Reader, dst string) error {\n\t// need to set umask to be 000 for current process.\n\t// there will be some files having higher permission like 777,\n\t// eventually permission will be set to 755 when umask is 022.\n\t_, err := system.Umask(0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.MkdirAll(dst, common.FileMode0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tzr, err := gzip.NewReader(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttr := tar.NewReader(zr)\n\ttype DirStruct struct {\n\t\theader *tar.Header\n\t\tdir string\n\t\tnext, prev *DirStruct\n\t}\n\n\tprefixes := make(map[string]*DirStruct)\n\tfor {\n\t\theader, err := tr.Next()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// validate name against path traversal\n\t\tif !validRelPath(header.Name) {\n\t\t\treturn fmt.Errorf(\"tar contained invalid name error %q\", header.Name)\n\t\t}\n\n\t\ttarget := filepath.Join(dst, header.Name)\n\n\t\tswitch header.Typeflag {\n\t\tcase tar.TypeDir:\n\t\t\tif _, err = os.Stat(target); err != nil {\n\t\t\t\tif err = os.MkdirAll(target, os.FileMode(header.Mode)); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\t// building a double linked list\n\t\t\t\tprefix := filepath.Dir(target)\n\t\t\t\tprev := prefixes[prefix]\n\t\t\t\t//an root dir\n\t\t\t\tif prev == nil {\n\t\t\t\t\tprefixes[target] = &DirStruct{header: header, dir: target, next: nil, prev: nil}\n\t\t\t\t} else {\n\t\t\t\t\tnewHead := &DirStruct{header: header, dir: target, next: nil, prev: prev}\n\t\t\t\t\tprev.next = newHead\n\t\t\t\t\tprefixes[target] = newHead\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase tar.TypeReg:\n\t\t\terr = func() error {\n\t\t\t\t// regularly won't mkdir, unless add newFolder on compressing\n\t\t\t\tinErr := utils.MkDirIfNotExists(filepath.Dir(target))\n\t\t\t\tif inErr != nil {\n\t\t\t\t\treturn inErr\n\t\t\t\t}\n\n\t\t\t\tfileToWrite, inErr := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_RDWR, os.FileMode(header.Mode))\n\t\t\t\tif inErr != nil {\n\t\t\t\t\treturn inErr\n\t\t\t\t}\n\n\t\t\t\tdefer fileToWrite.Close()\n\t\t\t\tif _, inErr = io.Copy(fileToWrite, tr); inErr != nil {\n\t\t\t\t\treturn inErr\n\t\t\t\t}\n\t\t\t\t// for not changing\n\t\t\t\treturn os.Chtimes(target, header.AccessTime, header.ModTime)\n\t\t\t}()\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, v := range prefixes {\n\t\t// for taking the last one\n\t\tif v.next != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// every change in dir, will change the metadata of that dir\n\t\t// change times from the last one\n\t\t// do this is for not changing metadata of parent dir\n\t\tfor dirStr := v; dirStr != nil; dirStr = dirStr.prev {\n\t\t\tif err = os.Chtimes(dirStr.dir, dirStr.header.AccessTime, dirStr.header.ModTime); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (l *levelHandler) isCompactable(delSize int64) bool {\n\treturn l.getTotalSize()-delSize >= l.maxTotalSize\n}",
"func (enterpriseManagement *EnterpriseManagementV1) GetEnableGzipCompression() bool {\n\treturn enterpriseManagement.Service.GetEnableGzipCompression()\n}",
"func (o *VersionedConnection) HasLoadBalanceCompression() bool {\n\tif o != nil && o.LoadBalanceCompression != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func isTarArchive(r io.Reader) bool {\n\ttarReader := tar.NewReader(r)\n\t_, err := tarReader.Next()\n\treturn err == nil\n}",
"func (bo *BytesObj) IsObject() bool {\n\tif bo == nil {\n\t\treturn false\n\t}\n\treturn bo.tp&isObj == isObj\n}",
"func (schematics *SchematicsV1) GetEnableGzipCompression() bool {\n\treturn schematics.Service.GetEnableGzipCompression()\n}",
"func isServerGzipCompLevelDirective(directive string) bool {\n\tif isEqualString(directive, ServerGzipCompLevelDirective) {\n\t\treturn true\n\t}\n\treturn false\n}",
"func compress(filename string) error {\n\tin, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer in.Close()\n\n\tout, err := os.Create(filename + \".gz\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\tgzout := gzip.NewWriter(out)\n\t_, err = io.Copy(gzout, in)\n\tgzout.Close()\n\n\treturn err\n}",
"func (s *server) compressedKey(prefix string, digest *pb.Digest, compressed bool) string {\n\tif compressed {\n\t\treturn s.key(\"zstd_\"+prefix, digest)\n\t}\n\treturn s.key(prefix, digest)\n}",
"func isGzipEncodingAccepted(req *http.Request) bool {\n\tfor _, v := range strings.Split(req.Header.Get(\"Accept-Encoding\"), \",\") {\n\t\tif strings.TrimSpace(v) == \"gzip\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}",
"func GzipAccepted(header http.Header) bool {\n\ta := header.Get(acceptEncodingHeader)\n\tparts := strings.Split(a, \",\")\n\tfor _, part := range parts {\n\t\tpart = strings.TrimSpace(part)\n\t\tif part == \"gzip\" || strings.HasPrefix(part, \"gzip;\") {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}",
"func (s IntegrationSuite) TestCheckSchemaCompression(t *testing.T) {\n\tdir := getDir(t, \"testdata/validcfg\")\n\n\t// Ignore all linters except for the compression one\n\tforceOnlyRulesWarning(dir.Config, \"compression\")\n\topts, err := OptionsForDir(dir)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error from OptionsForDir: %v\", err)\n\t}\n\tlogicalSchema := dir.LogicalSchemas[0]\n\twsOpts, err := workspace.OptionsForDir(dir, s.d.Instance)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error from workspace.OptionsForDir: %v\", err)\n\t}\n\twsSchema, err := workspace.ExecLogicalSchema(logicalSchema, wsOpts)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error from workspace.ExecLogicalSchema: %v\", err)\n\t}\n\n\t// Count the InnoDB tables in the dir, for use in computing the expected\n\t// warning annotation count below\n\tvar innoTableCount int\n\tfor _, tbl := range wsSchema.Tables {\n\t\tif tbl.Engine == \"InnoDB\" {\n\t\t\tinnoTableCount++\n\t\t}\n\t}\n\n\t// Perform tests with various permutations of allow-list and flavor, and\n\t// confirm the number of annotations matches expectations. Note that the only\n\t// compressed tables in the dir are the two in testdata/validcfg/compression.sql;\n\t// one uses KEY_BLOCK_SIZE=2, and the other effectively uses 8 by way of\n\t// defaulting to half the page size.\n\tcases := []struct {\n\t\tallowList []string\n\t\tflavor tengo.Flavor\n\t\texpectedWarningCount int\n\t}{\n\t\t{[]string{\"8kb\"}, s.d.Flavor(), innoTableCount - 1},\n\t\t{[]string{\"page\", \"8kb\"}, tengo.FlavorMySQL57, innoTableCount - 1},\n\t\t{[]string{\"page\"}, tengo.FlavorMariaDB103, innoTableCount},\n\t\t{[]string{\"none\"}, s.d.Flavor(), 2},\n\t\t{[]string{\"none\", \"4kb\"}, s.d.Flavor(), 2},\n\t\t{[]string{\"none\", \"4kb\", \"page\"}, s.d.Flavor(), 2},\n\t\t{[]string{\"none\", \"invalid-value\"}, s.d.Flavor(), 2},\n\t\t{[]string{\"invalid-value\"}, s.d.Flavor(), innoTableCount},\n\t}\n\tfor n, c := range cases {\n\t\topts.RuleConfig[\"compression\"] = c.allowList\n\t\topts.Flavor = c.flavor\n\t\tresult := CheckSchema(wsSchema, opts)\n\t\tif result.WarningCount != c.expectedWarningCount {\n\t\t\tt.Errorf(\"cases[%d] expected warning count %d, instead found %d\", n, c.expectedWarningCount, result.WarningCount)\n\t\t}\n\t}\n\n\t// If the Dockerized test instance's Flavor supports page compression, verify\n\t// that the regexp used by tableCompressionMode() works properly.\n\t// Store a mapping of table name -> expected 2nd return value of tableCompressionMode().\n\tvar tableExpectedClause map[string]string\n\tif s.d.Flavor().Min(tengo.FlavorMySQL57) {\n\t\tdir = getDir(t, \"testdata/pagecomprmysql\")\n\t\ttableExpectedClause = map[string]string{\n\t\t\t\"page_comp_zlib\": \"COMPRESSION='zlib'\",\n\t\t\t\"page_comp_lz4\": \"COMPRESSION='lz4'\",\n\t\t\t\"page_comp_none\": \"\",\n\t\t}\n\t} else if s.d.Flavor().Min(tengo.FlavorMariaDB102) {\n\t\tdir = getDir(t, \"testdata/pagecomprmaria\")\n\t\ttableExpectedClause = map[string]string{\n\t\t\t\"page_comp_1\": \"`PAGE_COMPRESSED`=1\",\n\t\t\t\"page_comp_on\": \"`PAGE_COMPRESSED`='on'\",\n\t\t\t\"page_comp_0\": \"\",\n\t\t\t\"page_comp_off\": \"\",\n\t\t}\n\t}\n\tif tableExpectedClause != nil {\n\t\tlogicalSchema := dir.LogicalSchemas[0]\n\t\twsOpts, err := workspace.OptionsForDir(dir, s.d.Instance)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Unexpected error from workspace.OptionsForDir: %v\", err)\n\t\t}\n\t\twsSchema, err := workspace.ExecLogicalSchema(logicalSchema, wsOpts)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Unexpected error from workspace.ExecLogicalSchema: %v\", err)\n\t\t}\n\t\tif len(wsSchema.Failures) > 0 {\n\t\t\tt.Fatalf(\"%d of the CREATEs in %s unexpectedly failed: %+v\", len(wsSchema.Failures), dir, wsSchema.Failures)\n\t\t}\n\t\tfor _, tbl := range wsSchema.Tables {\n\t\t\texpectedClause, ok := tableExpectedClause[tbl.Name]\n\t\t\tif !ok {\n\t\t\t\tt.Fatalf(\"Unexpectedly found table %s in dir %s, not present in tableExpectedClause mapping for flavor %s\", tbl.Name, dir, s.d.Flavor())\n\t\t\t}\n\t\t\tvar expectedMode string\n\t\t\tif expectedClause == \"\" {\n\t\t\t\texpectedMode = \"none\"\n\t\t\t} else {\n\t\t\t\texpectedMode = \"page\"\n\t\t\t}\n\t\t\tactualMode, actualClause := tableCompressionMode(tbl)\n\t\t\tif actualMode != expectedMode || actualClause != expectedClause {\n\t\t\t\tt.Errorf(\"Unexpected return value from tableCompressionMode(%s): got %q,%q; expected %q,%q\", tbl.Name, actualMode, actualClause, expectedMode, expectedClause)\n\t\t\t}\n\t\t}\n\t}\n}",
"func (o JobExtractPtrOutput) Compression() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *JobExtract) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Compression\n\t}).(pulumi.StringPtrOutput)\n}",
"func (g G1) BytesCompressed() []byte { return g.encodeBytes(true) }",
"func (o *StorageHyperFlexStorageContainer) HasUnCompressedUsedBytes() bool {\n\tif o != nil && o.UnCompressedUsedBytes != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (o JobExtractOutput) Compression() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobExtract) *string { return v.Compression }).(pulumi.StringPtrOutput)\n}",
"func (o OpenZfsVolumeOutput) DataCompressionType() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *OpenZfsVolume) pulumi.StringPtrOutput { return v.DataCompressionType }).(pulumi.StringPtrOutput)\n}",
"func isMaxObjectSize(size int64) bool {\n\treturn size > maxObjectSize\n}",
"func getFileSizeOK(path string, maxFileSize int64) bool {\n\tsize, err := GetFileSize(path)\n\treturn err == nil && size != 0 && (size < maxFileSize || hasCompressionExtension(path))\n}",
"func (cachingApi *CachingApiV1) GetEnableGzipCompression() bool {\n\treturn cachingApi.Service.GetEnableGzipCompression()\n}",
"func (q *CompoundQuery) GetCompressedQuery() []byte {\n\treturn flateCompressor.MustCompressString(\n\t\tojson.MarshalJSON(q),\n\t)\n}",
"func (me TxsdClipPathTypeClipPathUnits) IsObjectBoundingBox() bool {\n\treturn me.String() == \"objectBoundingBox\"\n}",
"func (*Object) Descriptor() ([]byte, []int) {\n\treturn file_s3_proto_s3_proto_rawDescGZIP(), []int{54}\n}",
"func (botManagement *BotManagementV1) GetEnableGzipCompression() bool {\n\treturn botManagement.Service.GetEnableGzipCompression()\n}",
"func isZoneInfoFile(buf []byte) bool {\n\treturn bytes.Index(buf, []byte(zoneInfoFileHeaderSignatureString)) != -1\n}",
"func IsBucketPath(path string) bool {\n\ttrimmedPath := strings.Trim(path, \"/\")\n\tif trimmedPath == \"\" {\n\t\treturn false\n\t}\n\treturn len(strings.Split(trimmedPath, \"/\")) == 1\n}",
"func (o *VersionedConnection) GetLoadBalanceCompressionOk() (*string, bool) {\n\tif o == nil || o.LoadBalanceCompression == nil {\n\t\treturn nil, false\n\t}\n\treturn o.LoadBalanceCompression, true\n}",
"func (x *Big) isCompact() bool { return x.compact != c.Inflated }",
"func TestHandlerCompressed(t *testing.T) {\n\tassert := assert.New(t)\n\n\tvar configMap = map[string]interface{}{\n\t\t\"http_timeout\": 2,\n\t\t\"username\": \"testuser\",\n\t\t\"password\": \"secret\",\n\t}\n\tjsonConfig, err := json.Marshal(configMap)\n\tviper.ReadConfig(bytes.NewBuffer(jsonConfig))\n\n\t// mock server of external location\n\tbody := []byte(`{\"data\": already gzipped}`)\n\tbodyLen := fmt.Sprintf(\"%d\", len(body))\n\tmockServer := httptest.NewServer(\n\t\thttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Header().Set(\"Content-Encoding\", \"gzip\")\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.Header().Set(\"Content-Length\", bodyLen)\n\t\t\tw.Write(body)\n\t\t}),\n\t)\n\tdefer mockServer.Close()\n\n\tproxy, err := NewProxyClient()\n\t// mock proxy client url\n\tproxy.baseURL = mockServer.URL\n\tassert.Nil(err)\n\n\t// request to proxy without gzip encoding\n\ttestURL := fmt.Sprintf(\"%s/foo/1\", mockServer.URL)\n\tclientRequest, _ := http.NewRequest(\"GET\", testURL, nil)\n\tw := httptest.NewRecorder()\n\tproxy.Handler(w, clientRequest)\n\n\tassert.Equal(\"gzip\", w.HeaderMap.Get(\"Content-Encoding\"))\n\tassert.Equal(bodyLen, w.HeaderMap.Get(\"Content-Length\"))\n\tassert.Equal(\"application/json\", w.HeaderMap.Get(\"Content-Type\"))\n\t// compare the gzipped proxied response\n\tassert.Equal(body, w.Body.Bytes())\n\tassert.Equal(200, w.Code)\n}",
"func (o TableExternalDataConfigurationPtrOutput) Compression() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TableExternalDataConfiguration) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Compression\n\t}).(pulumi.StringPtrOutput)\n}",
"func (globalLoadBalancerMonitor *GlobalLoadBalancerMonitorV1) GetEnableGzipCompression() bool {\n\treturn globalLoadBalancerMonitor.Service.GetEnableGzipCompression()\n}",
"func BundleUncompress(input io.Reader, path string) error {\n\tfileReader, err := gzip.NewReader(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer fileReader.Close()\n\n\ttarBallReader := tar.NewReader(fileReader)\n\n\tfor {\n\t\theader, err := tarBallReader.Next()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\t// get the individual filename and extract to the current directory\n\t\t// and join it with path\n\t\tfilename := filepath.Join(path, header.Name)\n\n\t\tswitch header.Typeflag {\n\t\tcase tar.TypeDir:\n\t\t\t// handle directory\n\t\t\terr = os.MkdirAll(filename, os.ModePerm)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase tar.TypeReg, tar.TypeRegA:\n\t\t\t// we need to make sure the folder exists\n\t\t\tdir := filepath.Dir(filename)\n\t\t\terr = os.MkdirAll(dir, os.ModePerm)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// handle normal file\n\t\t\twriter, err := os.Create(filename)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tio.Copy(writer, tarBallReader)\n\n\t\t\terr = os.Chmod(filename, os.ModePerm)\n\t\t\tif err != nil {\n\t\t\t\twriter.Close()\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\twriter.Close()\n\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"Unable to untar type : %c in file %s\", header.Typeflag, filename)\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (directLinkProvider *DirectLinkProviderV2) GetEnableGzipCompression() bool {\n\treturn directLinkProvider.Service.GetEnableGzipCompression()\n}",
"func (api objectAPIHandlers) headObjectInArchiveFileHandler(ctx context.Context, objectAPI ObjectLayer, bucket, object string, w http.ResponseWriter, r *http.Request) {\n\tif crypto.S3.IsRequested(r.Header) || crypto.S3KMS.IsRequested(r.Header) { // If SSE-S3 or SSE-KMS present -> AWS fails with undefined error\n\t\twriteErrorResponseHeadersOnly(w, errorCodes.ToAPIErr(ErrBadRequest))\n\t\treturn\n\t}\n\tif _, ok := crypto.IsRequested(r.Header); !objectAPI.IsEncryptionSupported() && ok {\n\t\twriteErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrBadRequest), r.URL)\n\t\treturn\n\t}\n\n\tzipPath, object, err := splitZipExtensionPath(object)\n\tif err != nil {\n\t\twriteErrorResponseHeadersOnly(w, toAPIError(ctx, err))\n\t\treturn\n\t}\n\n\tgetObjectInfo := objectAPI.GetObjectInfo\n\tif api.CacheAPI() != nil {\n\t\tgetObjectInfo = api.CacheAPI().GetObjectInfo\n\t}\n\n\topts, err := getOpts(ctx, r, bucket, zipPath)\n\tif err != nil {\n\t\twriteErrorResponseHeadersOnly(w, toAPIError(ctx, err))\n\t\treturn\n\t}\n\n\tif s3Error := checkRequestAuthType(ctx, r, policy.GetObjectAction, bucket, zipPath); s3Error != ErrNone {\n\t\tif getRequestAuthType(r) == authTypeAnonymous {\n\t\t\t// As per \"Permission\" section in\n\t\t\t// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectHEAD.html\n\t\t\t// If the object you request does not exist,\n\t\t\t// the error Amazon S3 returns depends on\n\t\t\t// whether you also have the s3:ListBucket\n\t\t\t// permission.\n\t\t\t// * If you have the s3:ListBucket permission\n\t\t\t// on the bucket, Amazon S3 will return an\n\t\t\t// HTTP status code 404 (\"no such key\")\n\t\t\t// error.\n\t\t\t// * if you don’t have the s3:ListBucket\n\t\t\t// permission, Amazon S3 will return an HTTP\n\t\t\t// status code 403 (\"access denied\") error.`\n\t\t\tif globalPolicySys.IsAllowed(policy.Args{\n\t\t\t\tAction: policy.ListBucketAction,\n\t\t\t\tBucketName: bucket,\n\t\t\t\tConditionValues: getConditionValues(r, \"\", \"\", nil),\n\t\t\t\tIsOwner: false,\n\t\t\t}) {\n\t\t\t\t_, err = getObjectInfo(ctx, bucket, zipPath, opts)\n\t\t\t\tif toAPIError(ctx, err).Code == \"NoSuchKey\" {\n\t\t\t\t\ts3Error = ErrNoSuchKey\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twriteErrorResponseHeadersOnly(w, errorCodes.ToAPIErr(s3Error))\n\t\treturn\n\t}\n\n\tvar rs *HTTPRangeSpec\n\n\t// Validate pre-conditions if any.\n\topts.CheckPrecondFn = func(oi ObjectInfo) bool {\n\t\treturn checkPreconditions(ctx, w, r, oi, opts)\n\t}\n\n\tzipObjInfo, err := getObjectInfo(ctx, bucket, zipPath, opts)\n\tif err != nil {\n\t\twriteErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)\n\t\treturn\n\t}\n\n\tvar zipInfo []byte\n\n\tif z, ok := zipObjInfo.UserDefined[archiveInfoMetadataKey]; ok {\n\t\tzipInfo = []byte(z)\n\t} else {\n\t\tzipInfo, err = updateObjectMetadataWithZipInfo(ctx, objectAPI, bucket, zipPath, opts)\n\t}\n\tif err != nil {\n\t\twriteErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)\n\t\treturn\n\t}\n\n\tfile, err := zipindex.FindSerialized(zipInfo, object)\n\tif err != nil {\n\t\tif err == io.EOF {\n\t\t\twriteErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrNoSuchKey), r.URL)\n\t\t} else {\n\t\t\twriteErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)\n\t\t}\n\t\treturn\n\t}\n\n\tobjInfo := ObjectInfo{\n\t\tBucket: bucket,\n\t\tName: file.Name,\n\t\tSize: int64(file.UncompressedSize64),\n\t\tModTime: zipObjInfo.ModTime,\n\t}\n\n\t// Set standard object headers.\n\tif err = setObjectHeaders(w, objInfo, nil, opts); err != nil {\n\t\twriteErrorResponseHeadersOnly(w, toAPIError(ctx, err))\n\t\treturn\n\t}\n\n\t// Set any additional requested response headers.\n\tsetHeadGetRespHeaders(w, r.URL.Query())\n\n\t// Successful response.\n\tif rs != nil {\n\t\tw.WriteHeader(http.StatusPartialContent)\n\t} else {\n\t\tw.WriteHeader(http.StatusOK)\n\t}\n}",
"func AreFilesReadable(s *session.Session, bucketName string) (bool, error) {\n\tsvc := s3.New(s)\n\tdownloader := s3manager.NewDownloader(s)\n\tparams := &s3.ListObjectsInput{Bucket: aws.String(bucketName)}\n\tresp, err := svc.ListObjects(params)\n\tif err != nil {\n\t\tif awsErr, ok := err.(awserr.Error); ok {\n\t\t\t// Get error details\n\t\t\tif awsErr.Code() == \"NoSuchBucket\" {\n\t\t\t\treturn false, err\n\t\t\t} else {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t}\n\tif resp.Contents == nil {\n\t\treturn false, fmt.Errorf(\"No files in bucket\")\n\t}\n\ttestKey := resp.Contents[0].Key\n\tfile, err := os.Create(*testKey)\n\n\tif err != nil {\n\t\tlog.Panicf(\"Unable to open file %q, %v\", \"testfile\", err)\n\t}\n\n\tdefer file.Close()\n\t_, err = downloader.Download(file,\n\t\t&s3.GetObjectInput{\n\t\t\tBucket: aws.String(bucketName),\n\t\t\tKey: aws.String(*testKey),\n\t\t})\n\n\tif err != nil {\n\t\tlog.Printf(\"Unable to download item %q, %v\", *testKey, err)\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}",
"func (project *ProjectV1) GetEnableGzipCompression() bool {\n\treturn project.Service.GetEnableGzipCompression()\n}",
"func GzipAssetInfo(name string) (os.FileInfo, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _gzipbindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"GzipAssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}"
] | [
"0.653064",
"0.6529697",
"0.64835864",
"0.64447665",
"0.64436954",
"0.58735466",
"0.5823497",
"0.57750416",
"0.574731",
"0.57112044",
"0.55475014",
"0.5543348",
"0.551083",
"0.55057955",
"0.5493801",
"0.54699224",
"0.5439296",
"0.53979534",
"0.53725475",
"0.5351564",
"0.53263605",
"0.53100675",
"0.5216219",
"0.51827943",
"0.5135391",
"0.5119133",
"0.5115053",
"0.5105897",
"0.51042897",
"0.5070833",
"0.50591904",
"0.5004352",
"0.4999333",
"0.495428",
"0.4953856",
"0.4917674",
"0.48886058",
"0.48530287",
"0.48321953",
"0.47937098",
"0.4779642",
"0.47508335",
"0.47474217",
"0.4740835",
"0.47266224",
"0.47157997",
"0.47081825",
"0.4706051",
"0.46941677",
"0.4693014",
"0.46919867",
"0.4666104",
"0.46623546",
"0.4636686",
"0.46337295",
"0.46211046",
"0.4597662",
"0.45973298",
"0.45952752",
"0.45923552",
"0.45805508",
"0.45353514",
"0.45343637",
"0.45274407",
"0.4521014",
"0.45146033",
"0.45143545",
"0.45123985",
"0.4511008",
"0.4503914",
"0.44868493",
"0.44862133",
"0.4483607",
"0.44792488",
"0.44718206",
"0.44690955",
"0.44627392",
"0.4462347",
"0.4461217",
"0.44578153",
"0.44548994",
"0.44546333",
"0.4452324",
"0.44386083",
"0.44358915",
"0.44290206",
"0.44287542",
"0.44255704",
"0.4419947",
"0.44131127",
"0.44112375",
"0.43984717",
"0.4392735",
"0.43864083",
"0.4382994",
"0.43791425",
"0.43665504",
"0.43647304",
"0.43594155",
"0.43592966"
] | 0.93761814 | 0 |
IsObjectDirectory returns true iff path is of a directory, i.e., contains a .dir extension | func IsObjectDirectory(path string) bool {
return path[len(path)-len(DirectoryExtension):] == DirectoryExtension
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (l *Location) IsDirectory() bool {\n\treturn strings.HasSuffix(l.Object, \"/\") || strings.HasSuffix(l.Object, \"/*\")\n}",
"func isDirectory(path string) bool {\n\n\tinfo, err := os.Stat(path)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn info.IsDir()\n}",
"func isDirectory(path string) bool {\n\tfi, err := os.Stat(path)\n\treturn err == nil && fi.IsDir()\n}",
"func (o ObjectType) IsDir() bool {\n\treturn o.mode.IsDir()\n}",
"func isDirectory(path string) bool {\n\tfileInfo, err := os.Stat(path)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn fileInfo.IsDir()\n}",
"func isDirectory(path string) (bool, error) {\n\tfileInfo, err := os.Stat(path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn fileInfo.IsDir(), nil\n}",
"func isDirectory(origin string) bool {\n\tfile, err := os.Stat(origin)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn file.Mode().IsDir()\n}",
"func isDirectory(name string) bool {\r\n\tinfo, err := os.Stat(name)\r\n\tif err != nil {\r\n\t\tlog.Fatal(err)\r\n\t}\r\n\treturn info.IsDir()\r\n}",
"func isDirectory(name string) bool {\n\tinfo, err := os.Stat(name)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn info.IsDir()\n}",
"func isDirectory(name string) bool {\n\tinfo, err := os.Stat(name)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn info.IsDir()\n}",
"func isDirectory(name string) bool {\n\tinfo, err := os.Stat(name)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn info.IsDir()\n}",
"func isDirectory(name string) bool {\n\tinfo, err := os.Stat(name)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn info.IsDir()\n}",
"func isDirectory(name string) bool {\n\tinfo, err := os.Stat(name)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn info.IsDir()\n}",
"func isDirectory(name string) bool {\n\tinfo, err := os.Stat(name)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn info.IsDir()\n}",
"func isDirectory(name string) bool {\n\tinfo, err := os.Stat(name)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn info.IsDir()\n}",
"func IsDirectory(path string) bool {\n\tfInfo, err := os.Stat(path)\n\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tif fInfo.IsDir() {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func IsDirectory(path string) bool {\n\tfi, err := os.Stat(path)\n\n\treturn err == nil && fi.IsDir()\n}",
"func (ros RealOS) IsDirectory(p string) bool {\n\tif stat, err := os.Stat(path.Clean(p)); err == nil {\n\t\tif stat.IsDir() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}",
"func IsDirectory(path string) (bool, error) {\n\tfi, err := os.Stat(path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif fi.Size() > maxFileSize {\n\t\treturn false, errors.New(\"Ignore large files: \" + fi.Name() + \"\\n\")\n\t}\n\tswitch mode := fi.Mode(); {\n\tcase mode.IsDir():\n\t\treturn true, nil\n\tdefault:\n\t\treturn false, nil\n\t}\n}",
"func isDir(path string) (bool, error) {\n\tfi, err := os.Lstat(path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn fi.IsDir(), nil\n}",
"func isDir(path string) bool {\n\tinfo, err := os.Stat(path)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn info.IsDir()\n}",
"func IsDirectory(path string) bool {\n\tinfo, err := os.Stat(path)\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn info.IsDir()\n}",
"func isDir(dirPath string) bool {\n\tstat, err := os.Stat(dirPath)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn stat.IsDir()\n}",
"func (i *FileInfo) IsDir() bool { return i.Mode().IsDir() }",
"func (rf *HTTPResFile) IsDirectory() bool {\n\treturn false\n}",
"func IsDirectory(path string) bool {\n\tfileInfo, err := os.Stat(path)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn fileInfo.IsDir()\n}",
"func (fa FileAttributes) IsDirectory() bool {\n\treturn fa&16 > 0\n}",
"func isDirectory(dir string) (b bool, err error) {\n\tfi, err := os.Stat(dir)\n\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\tif !fi.IsDir() {\n\t\treturn false, fmt.Errorf(`not a directory: %v`, dir)\n\t}\n\n\treturn true, nil\n}",
"func IsDirectory(path string) (bool, error) {\n\tfileInfo, err := os.Stat(path)\n\treturn fileInfo.IsDir(), err\n}",
"func PathIsDir(directory string) bool {\n\tif info, err := os.Stat(directory); err != nil || !info.IsDir() {\n\t\treturn false\n\t}\n\treturn true\n}",
"func (m Metadata) IsDir() bool {\n\treturn m.Mode&sIFDIR == sIFDIR\n}",
"func IsDirectory(path string) (bool, error) {\n\tfileInfo, err := os.Stat(path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn fileInfo.IsDir(), err\n}",
"func (i *Item) IsDir() bool { return i.directoryEntry.FileAttributes&0x10 != 0 }",
"func isDir(path string) (bool, error) {\n\tstat, err := os.Stat(path)\n\tif err == nil {\n\t\treturn stat.IsDir(), nil\n\t}\n\n\tif os.IsNotExist(err) {\n\t\treturn false, nil\n\t}\n\n\treturn (nil != stat && stat.IsDir()), err\n}",
"func (u *volumeUtil) IsDir(fullPath string) (bool, error) {\n\tdir, err := os.Open(fullPath)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer dir.Close()\n\n\tstat, err := dir.Stat()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn stat.IsDir(), nil\n}",
"func IsDir(pth string) bool {\n\t// Assuming it exists\n\tstat, _ := os.Stat(pth)\n\tif stat.IsDir() {\n\t\treturn true\n\t}\n\treturn false\n}",
"func IsDirectory(filePath string) bool {\n\tstat, err := os.Stat(filePath)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn stat.IsDir()\n}",
"func isDir(dir string) bool {\n\tfi, err := os.Stat(dir)\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\tif fi.Mode().IsDir() {\n\t\treturn true\n\t}\n\treturn false\n}",
"func IsDir(path string) bool {\n\tf, err := os.Stat(path)\n\treturn err == nil && f.IsDir()\n}",
"func (e DirectoryEntry) IsDir() bool { return ((e.OffsetToData & 0x80000000) >> 31) > 0 }",
"func (*GuluFile) IsDir(path string) bool {\n\tfio, err := os.Lstat(path)\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\n\tif nil != err {\n\t\tlogger.Warnf(\"determines whether [%s] is a directory failed: [%v]\", path, err)\n\t\treturn false\n\t}\n\treturn fio.IsDir()\n}",
"func isDir(path string) bool {\n\treturn path[len(path)-1] == os.PathSeparator\n}",
"func isDir(f string) bool {\n\tif info, err := os.Stat(f); err != nil {\n\t\treturn false\n\t} else {\n\t\treturn info.IsDir()\n\t}\n}",
"func isDir(dir string) bool {\n\tf, e := os.Stat(dir)\n\tif e != nil {\n\t\treturn false\n\t}\n\treturn f.IsDir()\n}",
"func (*Root) IsDir() bool { return true }",
"func isDir(path string) bool {\n\treturn os.IsPathSeparator(path[len(path)-1])\n}",
"func isDir(path string) (bool, error) {\n\tsrc, err := os.Stat(path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif src.Mode().IsRegular() {\n\t\tfmt.Println(path + \" already exist as a file!\")\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}",
"func (me TxsdNodeRoleSimpleContentExtensionCategory) IsDirectory() bool {\n\treturn me.String() == \"directory\"\n}",
"func IsDirectory(name string) (isDir bool, err error) {\n\tfInfo, err := os.Stat(name)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn fInfo.IsDir(), nil\n}",
"func IsDir(fsPath string) bool {\n if len(fsPath) == 0 {\n return false\n }\n stat, err := os.Stat(fsPath)\n return err == nil && stat.Mode().IsDir()\n}",
"func (fi *fileInfo) IsDir() bool { return fi.Mode().IsDir() }",
"func IsDir(path string) bool {\n\tinfo, err := os.Stat(path)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn info.IsDir()\n}",
"func IsDir(path string) bool {\n\n\ts, err := os.Stat(path)\n\n\tif err != nil {\n\n\t\treturn false\n\n\t}\n\n\treturn s.IsDir()\n}",
"func (s *State) isDir(cf manager.RepositoryEntry) bool {\n\tinfo, err := os.Stat(cf.Path)\n\treturn err == nil && info.IsDir()\n}",
"func IsDir(path string) bool {\n\tif path == \"\" {\n\t\treturn false\n\t}\n\n\tif fi, err := os.Stat(path); err == nil {\n\t\treturn fi.IsDir()\n\t}\n\treturn false\n}",
"func (s sys) IsDir(finfo os.FileInfo) bool {\n\treturn finfo.Mode().IsDir()\n}",
"func IsDir(path string) bool {\n\ts, err := os.Stat(path)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn s.IsDir()\n}",
"func (f File) IsDir() bool {\n\tfp := f.FullPath()\n\tfi, err := os.Stat(fp)\n\tif err != nil {\n\t\treturn false\n\t}\n\tmode := fi.Mode()\n\tif mode.IsDir() {\n\t\treturn true\n\t}\n\treturn false\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}",
"func (fi bindataFileInfo) IsDir() bool {\n\treturn fi.mode&os.ModeDir != 0\n}"
] | [
"0.77211547",
"0.72438985",
"0.7199888",
"0.7151319",
"0.7145256",
"0.71392155",
"0.7089175",
"0.70202345",
"0.69939303",
"0.69939303",
"0.69939303",
"0.69939303",
"0.69939303",
"0.69939303",
"0.69939303",
"0.69889545",
"0.69766504",
"0.6974625",
"0.6944162",
"0.6894724",
"0.68843347",
"0.68775505",
"0.68648064",
"0.6845463",
"0.6843605",
"0.6802382",
"0.6785538",
"0.67771196",
"0.676122",
"0.6753772",
"0.6722361",
"0.669185",
"0.66792685",
"0.6660464",
"0.6651729",
"0.66499126",
"0.6633636",
"0.66324073",
"0.66317534",
"0.6630054",
"0.66287994",
"0.6613912",
"0.66010827",
"0.6590101",
"0.6589945",
"0.65843207",
"0.6582926",
"0.6573211",
"0.6557952",
"0.6556791",
"0.6552157",
"0.653759",
"0.6523823",
"0.65185297",
"0.6507034",
"0.6502943",
"0.6502166",
"0.64967823",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504",
"0.64960504"
] | 0.88540584 | 0 |
Compress compresses the file inPath using tmpDir fo storing the compressed output file and any intermediate temporary files it might need to create. It returns the full path to the compressed file, or an error. | func Compress(inPath string, tmpDir string) (string, error) {
// create a temporary file with a unique name compress it -- multiple files
// are named 000: pg_notify/0000, pg_subtrans/0000
outFile, err := ioutil.TempFile(tmpDir, "pgCarpenter.")
if err != nil {
return "", err
}
// open input file
inFile, err := os.Open(inPath)
if err != nil {
return "", err
}
// we open this for read only, and this process exists after a finite (short)
// period of time; there's no need to throw an error if closing it fails
defer inFile.Close()
// buffer read from the input file and lz4 writer
r := bufio.NewReader(inFile)
w := lz4.NewWriter(outFile)
// read 4k at a time
buf := make([]byte, 4096)
for {
n, err := r.Read(buf)
if err != nil && err != io.EOF {
return "", err
}
// we're done
if n == 0 {
break
}
// write the 4k chunk
if _, err := w.Write(buf[:n]); err != nil {
return "", err
}
}
// flush any pending compressed data
if err = w.Flush(); err != nil {
return "", err
}
// make sure we successfully close the compressed file
if err := outFile.Close(); err != nil {
return "", err
}
return outFile.Name(), nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func Compress(dirName string) (string, error) {\n\tdir, err := os.Open(dirName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer dir.Close()\n\n\tdirInfo, err := dir.Stat()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif !dirInfo.IsDir() {\n\t\treturn \"\", errors.New(\"not a dir: \" + \"dirName\")\n\t}\n\n\tfiles, err := dir.Readdir(0)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(files) == 0 {\n\t\tlog.Warning.Println(\"dir=\", dirName, \"is empty\")\n\t\treturn \"\", errors.New(\"dir is empty\")\n\t}\n\n\tgzFileName := dirName + \".tgz\"\n\ttgzfile, err := os.Create(gzFileName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer tgzfile.Close()\n\n\tvar fileWriter io.WriteCloser = tgzfile\n\tarchiver := gzip.NewWriter(fileWriter)\n\tarchiver.Name = gzFileName\n\tdefer archiver.Close()\n\n\ttarfileWriter := tar.NewWriter(archiver)\n\tdefer tarfileWriter.Close()\n\n\tfor _, fileInfo := range files {\n\t\tif fileInfo.IsDir() {\n\t\t\treturn \"\", errors.New(\"unexpected dir in\" + dirName)\n\t\t}\n\t\tfile, err := os.Open(filepath.Join(dir.Name(), fileInfo.Name()))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tdefer file.Close()\n\n\t\theader, err := tar.FileInfoHeader(fileInfo, fileInfo.Name())\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\terr = tarfileWriter.WriteHeader(header)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\t_, err = io.Copy(tarfileWriter, file)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\treturn gzFileName, nil\n}",
"func (cmp Compressor) Compress(path string) error {\n compressedPath := path + \".lz4\"\n\n err := exec.Command(cmp.lz4Path, path, compressedPath).Run()\n if err != nil {\n return err\n }\n\n return os.Remove(path)\n}",
"func Compress(path, target string) error {\n\t//TODO this is...dense. cyclomatic complexity >10\n\t//TODOAY we refactor this to use go channels\n\n\t//Verify directory exists\n\ts, err := os.Stat(path)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"fs: compress failed to detect archive from path\")\n\t}\n\n\t//TODO i'm not convinced this will work on individual files sooooo...\n\tif !s.IsDir() {\n\t\treturn errors.New(\"fs: compress operation requires path to a directory\")\n\t}\n\n\t//Get the archives parent for a default storage location\n\tparentPath, err := filepath.Abs(target)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"fs: compress failed to extract absolute path of archive\")\n\t}\n\n\t//Open the zip archive for writing\n\tarchiveBuffer, err := os.OpenFile(parentPath+string(os.PathSeparator)+s.Name()+\".zip\", os.O_RDWR|os.O_CREATE, 0755)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"fs: compress failed to open \"+archiveBuffer.Name()+\".zip\")\n\t}\n\n\t//Initialize compression writer\n\tz := zip.NewWriter(archiveBuffer)\n\n\t//walk the provided directory\n\tw := walker.New(path)\n\tif err := w.Walk(); err != nil {\n\t\treturn errors.Wrap(err, \"fs: compress failed to walk archive\")\n\t}\n\n\tfor _, file := range w.Archive() {\n\t\t//Get the files relative path in the archive\n\t\trelPath, err := filepath.Rel(path, file)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"fs: compress failed to extract relative file path in archive\")\n\t\t}\n\t\t//Create zip file buffer for compression storage\n\t\tzipFile, err := z.Create(s.Name() + string(os.PathSeparator) + relPath)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"fs: compress failed to create zip file \"+relPath)\n\t\t}\n\t\t//Open file for copying\n\t\tf, err := os.Open(file)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"fs: compress failed to open \"+file)\n\t\t}\n\n\t\t//copy file into zip archive\n\t\tif _, err := io.Copy(zipFile, f); err != nil {\n\t\t\treturn errors.Wrap(err, \"fs: failed to write file to zip folder\")\n\t\t}\n\t\t//close file opened in iteration\n\t\tif err := f.Close(); err != nil {\n\t\t\treturn errors.Wrap(err, \"fs: compress failed to close \"+file)\n\t\t}\n\t}\n\n\t//close zip archive\n\tif err := z.Close(); err != nil {\n\t\treturn errors.Wrap(err, \"fs: compress failed to close zip writer\")\n\t}\n\t//close archive buffer\n\tif err := archiveBuffer.Close(); err != nil {\n\t\treturn errors.Wrap(err, \"fs: compress failed to close archive buffer\")\n\t}\n\n\treturn nil\n\n}",
"func compress(file_path string) error {\n\n\tfile, err := os.Open(file_path)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer file.Close()\n\n\tnewFile, err := os.Create(file_path + \".gz\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer newFile.Close()\n\n\tgzipOut := gzip.NewWriter(newFile)\n\n\t_, err = io.Copy(newFile, file)\n\n\tgzipOut.Close()\n\n\treturn err\n\n}",
"func Compress(targetFile *os.File, paths ...string) (file *os.File, err error) {\n\treturn compress(targetFile, true, paths)\n}",
"func FileCompress(fd *os.File) ([]byte, error) {\n\tvar zlibBuffer bytes.Buffer\n\tzlibWriter, err := zlib.NewWriterLevel(&zlibBuffer, zlib.BestCompression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer zlibWriter.Close()\n\t_, err = bufio.NewReader(fd).WriteTo(zlibWriter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tzlibWriter.Flush()\n\treturn zlibBuffer.Bytes(), nil\n}",
"func Decompress(inPath string, outPath string) error {\n\t// open the input, compressed file\n\tinFile, err := os.Open(inPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// we open this for read only, and this process exists after a finite (short)\n\t// period of time; there's no need to throw an error if closing it fails\n\tdefer inFile.Close()\n\n\t// open output file\n\toutFile, err := os.Create(outPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// lz4 read buffer\n\tr := lz4.NewReader(inFile)\n\t// write buffer\n\tw := bufio.NewWriter(outFile)\n\n\t// 4kb chunks\n\tbuf := make([]byte, 4096)\n\tfor {\n\t\t// read a chunk\n\t\tn, err := r.Read(buf)\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn err\n\t\t}\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t// write a chunk\n\t\tif _, err := w.Write(buf[:n]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// flush and pending data\n\tif err = w.Flush(); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// make sure we successfully close the compressed file\n\tif err := outFile.Close(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func (fc *FakeCompressor) CompressFilesInDir(dir string) (path string, err error) {\n\tfilesInDir, _ := fc.fs.Glob(filepath.Join(dir, \"*\"))\n\tarchive := map[string][]byte{}\n\n\tfor _, file := range filesInDir {\n\t\tfileContents, err := fc.fs.ReadFile(filepath.Join(dir, file))\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"reading file to compress: %s\", err.Error())\n\t\t}\n\t\tarchive[file] = fileContents\n\t}\n\tcompressedArchive, err := json.Marshal(archive)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"marshalling json: %s\", err.Error())\n\t}\n\tcompressedFile, _ := fc.fs.TempFile(\"stemcell-tgz\")\n\tpath = compressedFile.Name()\n\terr = fc.fs.WriteFile(compressedFile.Name(), compressedArchive)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"writing file: %s\", err.Error())\n\t}\n\treturn path, nil\n}",
"func (s *Gzip) CompressFile(source, target string) ([]byte, error) {\n\n\t//\tReading file and error handle\n\treader, err := os.Open(source)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn nil, err\n\t}\n\t//\tCreating target file in target destination\n\tfilename := filepath.Base(source)\n\tname := strings.TrimSuffix(filename, filepath.Ext(filename))\n\ttarget = filepath.Join(target, fmt.Sprintf(\"%s.gz\", name))\n\twriter, err := os.Create(target)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer writer.Close()\n\n\t//\tGzip of the given file\n\tarchiver := gzip.NewWriter(writer)\n\tarchiver.Name = filename\n\tdefer archiver.Close()\n\n\t_, err = io.Copy(archiver, reader)\n\treturn nil, err\n}",
"func (s *segment) Compress() error {\n\tif s.gReader != nil {\n\t\treturn ErrImmutableSegment // segment is already compressed and is immutable\n\t}\n\ts.appender.Close()\n\tif s.gReader != nil {\n\t\ts.gReader.Close()\n\t}\n\tf, err := os.OpenFile(s.path+CompressedExt, os.O_CREATE|os.O_WRONLY, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgWriter := gzip.NewWriter(f)\n\t_, err = s.rFile.Seek(0, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(gWriter, s.rFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = gWriter.Flush()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgWriter.Close()\n\ts.rFile.Close()\n\ts.appender.Close()\n\treturn os.Remove(s.filename)\n}",
"func PrecompressDir(dirPath string, options Options) error {\n\tvar eg errgroup.Group\n\terr := fs.WalkDir(os.DirFS(dirPath), \".\", func(p string, d fs.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\tif !compressibleExtensions[filepath.Ext(p)] {\n\t\t\treturn nil\n\t\t}\n\t\tp = path.Join(dirPath, p)\n\t\tif options.ProgressFn != nil {\n\t\t\toptions.ProgressFn(p)\n\t\t}\n\n\t\teg.Go(func() error {\n\t\t\treturn Precompress(p, options)\n\t\t})\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn eg.Wait()\n}",
"func (a *TarArchiver) tempFile() (f *os.File, clean func(), err error) {\n\tf, err = ioutil.TempFile(\"\", \"tar_archiver_\")\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to create temporary file\")\n\t}\n\n\treturn f, func() {\n\t\t_ = f.Close()\n\t\t_ = os.Remove(f.Name())\n\t}, nil\n}",
"func tempFileFromPath(path string) (string, error) {\n\tf, err := ioutil.TempFile(\"/tmp\", \"throttler\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Error creating temporary file %s\", err)\n\t}\n\tdefer f.Close()\n\n\treader, err := pathio.Reader(path)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Error reading from the path %s\", err)\n\t}\n\tdefer reader.Close()\n\n\tif _, err = io.Copy(f, reader); err != nil {\n\t\treturn \"\", fmt.Errorf(\"Error copying the data from s3 %s\", err)\n\t}\n\treturn f.Name(), nil\n}",
"func WriteTempFile(\n\tctx context.Context, reqReader io.Reader, absBasePath config.Path,\n) (hash types.Base64Hash, size types.FileSizeBytes, path types.Path, err error) {\n\tsize = -1\n\tlogger := util.GetLogger(ctx)\n\ttmpFileWriter, tmpFile, tmpDir, err := createTempFileWriter(absBasePath)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\terr2 := tmpFile.Close()\n\t\tif err == nil {\n\t\t\terr = err2\n\t\t}\n\t}()\n\n\t// Hash the file data. The hash will be returned. The hash is useful as a\n\t// method of deduplicating files to save storage, as well as a way to conduct\n\t// integrity checks on the file data in the repository.\n\thasher := sha256.New()\n\tteeReader := io.TeeReader(reqReader, hasher)\n\tbytesWritten, err := io.Copy(tmpFileWriter, teeReader)\n\tif err != nil && err != io.EOF {\n\t\tRemoveDir(tmpDir, logger)\n\t\treturn\n\t}\n\n\terr = tmpFileWriter.Flush()\n\tif err != nil {\n\t\tRemoveDir(tmpDir, logger)\n\t\treturn\n\t}\n\n\thash = types.Base64Hash(base64.RawURLEncoding.EncodeToString(hasher.Sum(nil)[:]))\n\tsize = types.FileSizeBytes(bytesWritten)\n\tpath = tmpDir\n\treturn\n}",
"func TempFile(dir, prefix string) *os.File {\n\tf, err := ioutil.TempFile(dir, prefix)\n\tAbortIf(err)\n\treturn f\n}",
"func CreateTempZip(filenameInZip, content string) (string, error) {\n\ttempFile, err := ioutil.TempFile(\"\", \"hashi-test-\")\n\tzipFile := NewErrorWriter(tempFile, err)\n\tdefer ioutils.Close(tempFile)\n\n\tzipWriter := zip.NewWriter(zipFile)\n\tdefer ioutils.Close(zipWriter)\n\n\tfileWriter := NewErrorWriter(zipWriter.Create(filenameInZip))\n\t_, _ = fileWriter.Write([]byte(content))\n\n\tif fileWriter.Err() != nil {\n\t\treturn \"\", fileWriter.Err()\n\t}\n\n\treturn tempFile.Name(), nil\n}",
"func compress(filename string) error {\n\tin, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer in.Close()\n\n\tout, err := os.Create(filename + \".gz\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\tgzout := gzip.NewWriter(out)\n\t_, err = io.Copy(gzout, in)\n\tgzout.Close()\n\n\treturn err\n}",
"func TempFile(dir, prefix string) (*File, error) {\n\tf, err := ioutil.TempFile(dir, prefix)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &File{f, Path(f.Name())}, nil\n}",
"func CompressFiles(paths ...string) ([]byte, error) {\n\tif env.Debug {\n\t\tlog.Printf(\"Compressing: %v\", paths)\n\t}\n\tif len(paths) == 0 {\n\t\treturn nil, fmt.Errorf(\"no path provided\")\n\t}\n\tvar b bytes.Buffer\n\terr := archiver.Zip.Write(&b, paths)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.Bytes(), nil\n}",
"func Compress(u string, config Config, d driver.Driver, p *composer.JSONData) error {\n\t// Prepare path and archive path\n\tgd := &download.Git{\n\t\tName: p.Name,\n\t\tVersion: p.Version,\n\t\tURL: u,\n\t\tSource: p.Source,\n\t\tDistDir: config.DistDir,\n\t}\n\tgd.Prepare()\n\t// Prepare compression\n\tcz := compress.Zip{\n\t\tSourcePath: gd.SourcePath,\n\t}\n\tcz.Prepare()\n\t// Run download\n\tif !gd.PathExist && !cz.IsExist {\n\t\terr := gd.Run()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// Run compression\n\tif gd.PathExist && !cz.IsExist {\n\t\terr := cz.Run()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif cz.IsExist {\n\t\thost := config.File.Homepage\n\t\tif config.File.Archive.PrefixURL != \"\" {\n\t\t\thost = config.File.Archive.PrefixURL\n\t\t}\n\n\t\tp.Dist = map[string]string{\n\t\t\t\"type\": cz.Format,\n\t\t\t\"url\": host + \"/\" + path.Join(config.File.Archive.Directory, strings.Replace(cz.TargetPath, gd.DistDir, \"\", -1)),\n\t\t\t\"reference\": d.GetReference(),\n\t\t\t\"shasum\": hashFile(cz.TargetPath),\n\t\t}\n\t}\n\n\treturn nil\n}",
"func BundleCompress(rootPath string, output io.Writer) error {\n\tfileWriter := gzip.NewWriter(output)\n\tdefer fileWriter.Close()\n\n\ttarfileWriter := tar.NewWriter(fileWriter)\n\tdefer tarfileWriter.Close()\n\n\tfiles, err := GetAllFiles(rootPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, file := range files {\n\t\t// in order to prevent defer stacking up,\n\t\t// a function wrapper is being used. so once the\n\t\t// file is close, defer will be executed to close the\n\t\t// file handler\n\t\terr := func(path string) error {\n\t\t\tfile, err := os.Open(filepath.Join(rootPath, path))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tdefer file.Close()\n\n\t\t\tfileInfo, err := file.Stat()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\theader := new(tar.Header)\n\t\t\theader.Name = path\n\t\t\theader.Size = fileInfo.Size()\n\t\t\theader.Mode = int64(fileInfo.Mode())\n\t\t\theader.ModTime = fileInfo.ModTime()\n\n\t\t\terr = tarfileWriter.WriteHeader(header)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t_, err = io.Copy(tarfileWriter, file)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}(file)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (c *Config) TempPath() string {\n\tif c.options.TempPath == \"\" {\n\t\treturn filepath.Join(os.TempDir(), \"esp\")\n\t}\n\n\treturn fs.Abs(c.options.TempPath)\n}",
"func TempFile(dir, content string) (string, func(), error) {\n\tf, err := ioutil.TempFile(dir, \"go-test-tmpfile\")\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\tif err := ioutil.WriteFile(f.Name(), []byte(content), 0644); err != nil {\n\t\treturn \"\", nil, err\n\t}\n\trmFunc := func() { os.Remove(f.Name()) }\n\treturn f.Name(), rmFunc, nil\n}",
"func Compress(data []byte, name string) ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\tw := zip.NewWriter(buf)\n\n\t//w.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {\n\t//\treturn flate.NewWriter(out, flate.BestCompression)\n\t//})\n\n\tz, err := w.Create(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = z.Write(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = w.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}",
"func (r *Repository) TempFile(prefix string) (*os.File, error) {\n\tdir := filepath.Join(r.Root, \"tmp\")\n\tos.MkdirAll(dir, 0777)\n\treturn ioutil.TempFile(dir, prefix)\n}",
"func TempFile(dir, pattern string) (*os.File, error) {\n\treturn os.CreateTemp(dir, pattern)\n}",
"func Archive(inFilePath string, writer io.Writer, progress ProgressFunc) (err error) {\n\tvar zipWriter *zip.Writer\n\tvar zipFileWriter io.Writer\n\tvar zipHeader *zip.FileHeader\n\tvar archivePath, relativeFilePath, basePath string\n\tvar file *os.File\n\n\tzipWriter = zip.NewWriter(writer)\n\n\tbasePath = filepath.Dir(inFilePath)\n\n\terr = filepath.Walk(inFilePath, func(filePath string, fileInfo os.FileInfo, walkErr error) (err error) {\n\t\tif walkErr == nil {\n\t\t\tif !fileInfo.IsDir() {\n\n\t\t\t\trelativeFilePath, err = filepath.Rel(basePath, filePath)\n\t\t\t\tif err == nil {\n\n\t\t\t\t\tarchivePath = filepath.ToSlash(relativeFilePath)\n\n\t\t\t\t\tif progress != nil {\n\t\t\t\t\t\tprogress(archivePath)\n\t\t\t\t\t}\n\n\t\t\t\t\tzipHeader, err = zip.FileInfoHeader(fileInfo)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tzipHeader.Name = archivePath\n\t\t\t\t\t\tzipHeader.Method = zip.Deflate\n\t\t\t\t\t\t// fmt.Printf(\"archive path [%s]\\n\", archivePath)\n\t\t\t\t\t\tzipFileWriter, err = zipWriter.CreateHeader(zipHeader)\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\tfile, err = os.Open(filePath)\n\t\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\t\t_, err = io.Copy(zipFileWriter, file)\n\t\t\t\t\t\t\t\tfile.Close()\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\terr = walkErr\n\t\t}\n\t\treturn\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn zipWriter.Close()\n}",
"func GetCompressedFiles(files []scan.File, rootPath string) (newfiles []scan.File, compresspaths []string, err error) {\n\t//check if file list contains compressed files, if so, scan their contents\n\tfor _, file := range files {\n\t\t//Unpack and append to file list\n\t\ttmppath, err := ioutil.TempDir(\"\", \"ebzip\")\n\t\tif err != nil {\n\t\t\treturn newfiles, compresspaths, err\n\t\t}\n\t\tcompresspaths = append(compresspaths, tmppath)\n\t\tfilenames, err := Uncompress(file.Path, tmppath)\n\t\tif err != nil {\n\t\t\treturn newfiles, compresspaths, err\n\t\t}\n\t\tfor _, subfile := range filenames {\n\t\t\tif !isIgnoredFile(subfile, rootPath) && !scan.CompressPattern.MatchString(subfile) {\n\t\t\t\tvar curFile scan.File\n\t\t\t\tcurFile.Path = file.Path + \"/\" + filepath.Base(subfile)\n\t\t\t\tcurFile.Name = subfile //Build view file name in format: file.zip/contents/file\n\t\t\t\tnewfiles = append(newfiles, curFile)\n\t\t\t}\n\t\t}\n\t}\n\treturn newfiles, compresspaths, nil\n}",
"func (w *RotateWriter) compress(source string) (err error) {\n\t// Read uncompressed file.\n\trawfile, err := os.Open(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer rawfile.Close()\n\n\t// Calculate the buffer size.\n\tinfo, _ := rawfile.Stat()\n\trawbytes := make([]byte, info.Size())\n\n\t// Read rawfile content into buffer.\n\tbuffer := bufio.NewReader(rawfile)\n\t_, err = buffer.Read(rawbytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar buf bytes.Buffer\n\twriter := gzip.NewWriter(&buf)\n\twriter.Write(rawbytes)\n\twriter.Close()\n\n\terr = ioutil.WriteFile(source+\".gz\", buf.Bytes(), info.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Remove uncompressed.\n\tgo os.Remove(source)\n\n\treturn nil\n}",
"func CreateTmpFile(dir, filePrefix, content string) string {\n\ttmpfile, err := ioutil.TempFile(dir, filePrefix)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif _, err := tmpfile.Write([]byte(content)); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif err := tmpfile.Close(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn tmpfile.Name()\n}",
"func (fs *Mysqlfs) TempFile(dir, prefix string) (billy.File, error) {\n\treturn util.TempFile(fs, dir, prefix)\n}",
"func Compress(out, in []byte) (outSize int, err error) {\n\toutSize = int(C.LZ4_compress_limitedOutput(p(in), p(out), clen(in), clen(out)))\n\tif outSize == 0 {\n\t\terr = errors.New(\"Insufficient space for compression\")\n\t}\n\treturn\n}",
"func (ctx *Context) TempDir(name string) (string, error) {\n\ttmpLayer, err := ctx.Layer(\"gcpbuildpack-tmp\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"creating layer: %w\", err)\n\t}\n\tdirectory := filepath.Join(tmpLayer.Path, name)\n\tif err := ctx.MkdirAll(directory, 0755); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn directory, nil\n}",
"func Compress(input, output []byte) (outSize int, err error) {\r\n\toutSize = int(C.lzf_compress(p(input), clen(input), p(output), clen(output)))\r\n\tif outSize == 0 {\r\n\t\terr = ErrInsufficientBuffer\r\n\t}\r\n\treturn\r\n}",
"func GetTmpPath() string {\n\treturn tmpPath\n}",
"func mustZipTree(srcPath string) string {\n\tvar out bytes.Buffer\n\tw := zip.NewWriter(&out)\n\tif err := filepath.Walk(srcPath, func(path string, fi os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Ignore directories and hidden files.\n\t\t// No entry is needed for directories in a zip file.\n\t\t// Each file is represented with a path, no directory\n\t\t// entities are required to build the hierarchy.\n\t\tif fi.IsDir() || strings.HasPrefix(fi.Name(), \".\") {\n\t\t\treturn nil\n\t\t}\n\t\trelPath, err := filepath.Rel(srcPath, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tb, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfHeader, err := zip.FileInfoHeader(fi)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfHeader.Name = filepath.ToSlash(relPath)\n\t\tfHeader.Method = zip.Deflate\n\t\tf, err := w.CreateHeader(fHeader)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = f.Write(b)\n\t\treturn err\n\t}); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := w.Close(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(out.Bytes())\n}",
"func Compress(file *os.File, outputName string) {\n\t// gerar a arvore a partir da frequencia dos caracteres do texto\n\troot := Harvest(GetMap(file))\n\n\t// gerar dicionario\n\tdict := make(map[string]string)\n\n\tif root.IsLeaf() {\n\t\tdict[root.Value] = \"0\"\n\t} else {\n\t\tcreateDict(root, dict, \"\")\n\t}\n\n\t//Resetar cursor\n\tfile.Seek(0, 0)\n\t//Escrever Árvore\n\toutputFile, _ := os.Create(outputName)\n\twriter := bit.NewWriter(outputFile)\n\twriteNode(root, writer)\n\n\t// Codificar\n\n\twriteCodified(file, dict, writer)\n}",
"func CreateTempFilesInDir(tb testing.TB, name string, content []byte, in ...string) (string, func()) {\n\ttb.Helper()\n\n\tparent := \"\"\n\tif len(in) > 0 {\n\t\tparent = in[0]\n\t}\n\n\ttmpDir, err := ioutil.TempDir(parent, name+\"-testdir-*\")\n\tif err != nil {\n\t\ttb.Fatalf(\"unexpectedly failed creating the temp dir: %v\", err)\n\t}\n\n\tfor i := 0; i < 3; i++ {\n\t\ttmpfile, err := ioutil.TempFile(tmpDir, name+\"_*.testfile\")\n\t\tif err != nil {\n\t\t\ttb.Fatalf(\"unexpectedly failed creating the temp file: %v\", err)\n\t\t}\n\n\t\tif _, err := tmpfile.Write(content); err != nil {\n\t\t\ttb.Fatalf(\"unexpectedly failed writing to the temp file: %v\", err)\n\t\t}\n\n\t\tif err := tmpfile.Close(); err != nil {\n\t\t\ttb.Fatalf(\"unexpectedly failed closing the temp file: %v\", err)\n\t\t}\n\t}\n\n\treturn tmpDir, func() { os.RemoveAll(tmpDir) }\n}",
"func Decompress(path, target string) error {\n\n\t//create zip reader\n\tr, err := zip.OpenReader(path)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"fs: decompress failed to open zip reader\")\n\t}\n\n\t//iterate and extract all files in the zip archive to target\n\tfor _, file := range r.File {\n\t\t//Get absolute location from archive relative path\n\t\tdestFile := filepath.Join(target, file.Name)\n\n\t\t//Get files directory name and create the folder hierarchy\n\t\tdestDir, _ := filepath.Split(destFile)\n\t\tif err := os.MkdirAll(destDir, file.Mode()); err != nil {\n\t\t\treturn errors.Wrap(err, \"fs: decompress failed to create destination\")\n\t\t}\n\n\t\t//open zipped file for decompression\n\t\tzippedFile, err := file.Open()\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"fs: decompress failed to open zipped file\")\n\t\t}\n\n\t\t//open destination file\n\t\tdest, err := os.OpenFile(destFile, os.O_RDWR|os.O_CREATE, file.Mode())\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"fs: decompress failed to open destination file\")\n\t\t}\n\n\t\t//Write unzipped file to destination\n\t\tif _, err := io.Copy(dest, zippedFile); err != nil {\n\t\t\treturn errors.Wrap(err, \"fs: decompress failed to write unzip file to destination\")\n\t\t}\n\n\t\t//close opened zip file\n\t\tif err := zippedFile.Close(); err != nil {\n\t\t\treturn errors.Wrap(err, \"fs: decompress failed to close zipped file\")\n\t\t}\n\n\t\t//close opened destination file\n\t\tif err := dest.Close(); err != nil {\n\t\t\treturn errors.Wrap(err, \"fs: decompress failed to close destination file\")\n\t\t}\n\n\t}\n\n\t//close zip reader\n\tif err := r.Close(); err != nil {\n\t\treturn errors.Wrap(err, \"fs: decompress failed to close zip reader\")\n\t}\n\n\treturn nil\n}",
"func compressFiles(files []string) error {\n\t// set output file\n\toutFile, err := os.Create(outputName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer outFile.Close()\n\n\t// set zip writer\n\tzipWriter := zip.NewWriter(outFile)\n\n\t// add files into zip\n\terr = addFiles(zipWriter, files)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer zipWriter.Close()\n\treturn nil\n}",
"func TempFile() (*os.File, error) {\n\treturn ioutil.TempFile(os.TempDir(), \"pavo\")\n}",
"func (d *Directory) Temporary() error {\n\ttmp, err := ioutil.TempDir(\"\", \"workdir\")\n\tif err != nil {\n\t\treturn err\n\t}\n\td.SetPath(tmp)\n\treturn nil\n}",
"func zipr(pathToZip, destinationPath string) error {\n\tdestinationFile, err := os.Create(destinationPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tzipWriter := zip.NewWriter(destinationFile)\n\n\terr = filepath.Walk(pathToZip, func(filePath string, info os.FileInfo, err error) error {\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trelPath := strings.TrimPrefix(filePath, pathToZip)\n\t\trelPath = strings.TrimPrefix(relPath, \"/\") // remove the slash if it exists\n\n\t\tfmt.Print(\" adding \" + relPath)\n\n\t\tfileToZip, err := os.Open(filePath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\theader, err := zip.FileInfoHeader(info)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\theader.Name = relPath // preserve the relative path\n\t\theader.Method = zip.Deflate // compress the file\n\n\t\twriter, err := zipWriter.CreateHeader(header)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\twritten, err := io.Copy(writer, fileToZip)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// TODO print the compression ratio (original size / compressed size)\n\t\tcompressedSize := 1.0 // TODO calculate\n\t\tcompressionRatio := compressedSize / float64(written) // TODO handle file size 0\n\t\tfmt.Printf(\" (compression %0.f%%)\\n\", compressionRatio)\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = zipWriter.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func ArchiveFile(inFilePath string, outFilePath string, progress ProgressFunc) (err error) {\n\tvar outFile *os.File\n\n\toutFile, err = os.Create(outFilePath)\n\tif err == nil {\n\t\terr = Archive(inFilePath, outFile, progress)\n\t\toutFile.Sync()\n\t\toutFile.Close()\n\t}\n\treturn\n}",
"func tempFile(hostsPath string) (*os.File, error) {\n\t// Create the temporary file in the same location as the hosts-file to inherit\n\t// the correct permissions from the parent directory.\n\treturn os.CreateTemp(filepath.Dir(hostsPath), \"hostsfile-temp\")\n}",
"func GetTmpPath() string {\n\treturn outputPath\n}",
"func Compress(data []byte) []byte {\n\t// apply zlib compression\n\tvar b bytes.Buffer\n\tw := zlib.NewWriter(&b)\n\t_, err := w.Write(data)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tw.Close()\n\n\treturn b.Bytes()\n}",
"func bzipCompress(d []byte) ([]byte, error) {\n\tvar out bytes.Buffer\n\tcmd := exec.Command(\"bzip2\", \"-c\", \"-9\")\n\tcmd.Stdin = bytes.NewBuffer(d)\n\tcmd.Stdout = &out\n\terr := cmd.Run()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out.Bytes(), nil\n}",
"func genZIP(debug, logger *log.Logger, noMtime, noCompress bool, src string) (string, error) {\n\tbuf := &bytes.Buffer{}\n\n\tw := zip.NewWriter(buf)\n\terr := filepath.Walk(src, func(path string, fi os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Ignore directories and hidden files.\n\t\t// No entry is needed for directories in a zip file.\n\t\t// Each file is represented with a path, no directory\n\t\t// entities are required to build the hierarchy.\n\t\tif fi.IsDir() || strings.HasPrefix(fi.Name(), \".\") {\n\t\t\treturn nil\n\t\t}\n\t\trelPath, err := filepath.Rel(src, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t/* #nosec */\n\t\tb, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfHeader, err := zip.FileInfoHeader(fi)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif noMtime {\n\t\t\t// Always use the same modification time so that\n\t\t\t// the output is deterministic with respect to the file contents.\n\t\t\tfHeader.SetModTime(mtimeDate)\n\t\t}\n\t\tfHeader.Name = filepath.ToSlash(relPath)\n\t\tif !noCompress {\n\t\t\tfHeader.Method = zip.Deflate\n\t\t}\n\t\tf, err := w.CreateHeader(fHeader)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = f.Write(b)\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\terr = w.Close()\n\ts := &strings.Builder{}\n\tfor _, b := range buf.Bytes() {\n\t\tif b == '\\n' {\n\t\t\t_, err = s.WriteString(`\\n`)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Println(\"Error writing to output string\")\n\t\t\t\tos.Exit(exSoftware)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif b == '\\\\' {\n\t\t\t_, err = s.WriteString(`\\\\`)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Println(\"Error writing to output string\")\n\t\t\t\tos.Exit(exSoftware)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif b == '\"' {\n\t\t\t_, err = s.WriteString(`\\\"`)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Println(\"Error writing to output string\")\n\t\t\t\tos.Exit(exSoftware)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif (b >= 32 && b <= 126) || b == '\\t' {\n\t\t\terr = s.WriteByte(b)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Println(\"Error writing byte to output string\")\n\t\t\t\tos.Exit(exSoftware)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Fprintf(s, \"\\\\x%02x\", b)\n\t}\n\treturn s.String(), err\n}",
"func (t *Tar) Compress(directory files.Directory, writer *bytes.Buffer) error {\n\tgzipWriter, err := gzip.NewWriterLevel(writer, flate.BestCompression)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttarWriter := tar.NewWriter(gzipWriter)\n\n\tfiles.WalkFileTree(directory, func(file files.File) {\n\t\tbuffer := &bytes.Buffer{}\n\t\tif err := file.CopyContent(buffer); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\ttarHeader := &tar.Header{\n\t\t\tName: filepath.ToSlash(file.AbsolutePath().String()),\n\t\t\tMode: int64(file.PermissionSet()),\n\t\t\tSize: int64(buffer.Len()),\n\t\t\tTypeflag: tar.TypeReg,\n\t\t}\n\n\t\tif err := tarWriter.WriteHeader(tarHeader); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif _, err := tarWriter.Write(buffer.Bytes()); err != nil {\n\t\t\treturn\n\t\t}\n\t})\n\n\tfiles.WalkDirectoryTree(directory, func(d files.Directory) {\n\t\ttarHeader := &tar.Header{\n\t\t\tName: filepath.ToSlash(d.AbsolutePath().String()),\n\t\t\tMode: int64(d.PermissionSet()),\n\t\t\tTypeflag: tar.TypeDir,\n\t\t}\n\n\t\tif err := tarWriter.WriteHeader(tarHeader); err != nil {\n\t\t\treturn\n\t\t}\n\t})\n\n\tif err := gzipWriter.Close(); err != nil {\n\t\treturn err\n\t}\n\n\treturn tarWriter.Close()\n}",
"func TempDir() string",
"func compressDirectory(source, target string) error {\n\t// Create file with target name and defer its closing\n\tzipfile, err := os.Create(target)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer zipfile.Close()\n\n\t// Create a new zip writer and pass our zipfile in\n\tarchive := zip.NewWriter(zipfile)\n\tdefer archive.Close()\n\n\t// Get os.FileInfo about our source\n\tinfo, err := os.Stat(source)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t// Check to see if the provided source file is a directory and set baseDir if so\n\tvar baseDir string\n\tif info.IsDir() {\n\t\tbaseDir = filepath.Base(source)\n\t}\n\n\t// Walk the whole filepath\n\tfilepath.Walk(source, func(path string, info os.FileInfo, err error) error {\n\t\text := filepath.Ext(path)\n\t\t_, ok := fileExtWhitelist[ext]\n\n\t\tif ok || (info.IsDir() && (ext != \".git\" && path != \"node_modules\")) {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Creates a partially-populated FileHeader from an os.FileInfo\n\t\t\theader, err := zip.FileInfoHeader(info)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Check if baseDir has been set (from the IsDir check) and if it has not been\n\t\t\t// set, update the header.Name to reflect the correct path\n\t\t\tif baseDir != \"\" {\n\t\t\t\theader.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))\n\t\t\t}\n\n\t\t\t// Check if the file we are iterating is a directory and update the header.Name\n\t\t\t// or the header.Method appropriately\n\t\t\tif info.IsDir() {\n\t\t\t\theader.Name += \"/\"\n\t\t\t} else {\n\t\t\t\theader.Method = zip.Deflate\n\t\t\t}\n\n\t\t\t// Add a file to the zip archive using the provided FileHeader for the file metadata\n\t\t\twriter, err := archive.CreateHeader(header)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Return nil if at this point if info is a directory\n\t\t\tif info.IsDir() {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\t// If it was not a directory, we open the file and copy it into the archive writer\n\t\t\t// ingore zip files\n\t\t\tfile, err := os.Open(path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer file.Close()\n\t\t\t_, err = io.Copy(writer, file)\n\t\t}\n\n\t\treturn err\n\t})\n\n\treturn err\n}",
"func Zip(srcFile string, destZip string) error {\n\tzipfile, err := os.Create(destZip)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer zipfile.Close()\n\n\tarchive := zip.NewWriter(zipfile)\n\tdefer archive.Close()\n\n\terr = filepath.Walk(srcFile, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\theader, err := zip.FileInfoHeader(info)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\theader.Name = path\n\t\tif info.IsDir() {\n\t\t\theader.Name += \"/\"\n\t\t} else {\n\t\t\theader.Method = zip.Deflate\n\t\t}\n\n\t\twriter, err := archive.CreateHeader(header)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !info.IsDir() {\n\t\t\tfile, err := os.Open(path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer file.Close()\n\t\t\t_, err = io.Copy(writer, file)\n\t\t}\n\t\treturn err\n\t})\n\n\treturn err\n}",
"func CreateTempFile() (file *os.File, err error) {\n\ttempDir := TempDir()\n\n\tfile, err = os.CreateTemp(tempDir, GetRuntimeInfo(1).Filename()+\"-\")\n\tif Error(err) {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tDebugError(file.Close())\n\t}()\n\n\tDebug(fmt.Sprintf(\"CreateTempFile : %s\", file.Name()))\n\n\treturn file, err\n}",
"func temporaryFile(name string) (*os.File, error) {\n\tworkingDir, err := os.Getwd()\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\t// Put everything in the ./sparta directory\n\tbuildDir := filepath.Join(workingDir, \".sparta\")\n\tmkdirErr := os.MkdirAll(buildDir, os.ModePerm)\n\tif nil != mkdirErr {\n\t\treturn nil, mkdirErr\n\t}\n\n\t// Use a stable temporary name\n\ttemporaryPath := filepath.Join(buildDir, name)\n\ttmpFile, err := os.Create(temporaryPath)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to create temporary file: \" + err.Error())\n\t}\n\treturn tmpFile, nil\n}",
"func (s *Gzip) Compress(reader io.Reader, writer io.Writer) error {\n\n\tarchiver := gzip.NewWriter(writer)\n\tdefer archiver.Close()\n\n\t_, err := io.Copy(archiver, reader)\n\treturn err\n}",
"func tempFile(dir, prefix string) string {\n\tf, err := ioutil.TempFile(dir, prefix)\n\tpanicIfError(err)\n\tf.Close()\n\treturn f.Name()\n}",
"func (e *Entry) tempPath() string {\n\tparts := make([]string, 1, len(e.path)+1)\n\tparts[0] = e.root.path\n\tparts = append(parts, e.path[:len(e.path)-1]...)\n\tparts = append(parts, e.tempName())\n\treturn filepath.Join(parts...)\n}",
"func compress(fileName string) string {\n\tzipper := new(archivex.ZipFile)\n\tzipper.Create(fileName)\n\n\t// Setting permissions on file to os.ModePerm or 0777 doesn't seem to keep the proper permissions.\n\t// So use the file's own?\n\t// aegisAppFileInfo, _ := os.Stat(aegisAppName)\n\n\t// Create a header for aegis_app to retain permissions?\n\theader := &zip.FileHeader{\n\t\tName: \"aegis_app\",\n\t\tMethod: zip.Store,\n\t\tModifiedTime: uint16(time.Now().UnixNano()),\n\t\tModifiedDate: uint16(time.Now().UnixNano()),\n\t}\n\t// os.ModePerm = -rwxrwxrwx\n\theader.SetMode(os.ModePerm)\n\t// log.Println(\"aegis_app file mode:\", aegisAppFileInfo.Mode())\n\t// header.SetMode(aegisAppFileInfo.Mode())\n\tzipWriter, _ := zipper.Writer.CreateHeader(header)\n\t// log.Println(\"zip header\", header)\n\n\tcontent, err := ioutil.ReadFile(aegisAppName)\n\tif err == nil {\n\t\tzipWriter.Write(content)\n\t}\n\n\t// Add the compiled Go app\n\t// zipper.AddFile(aegisAppName) <-- maybe this is writing w/o the header... have to use the writer returned by CreateHeader()??\n\tzipper.Close()\n\n\tpwd, _ := os.Getwd()\n\tbuiltZip := filepath.Join(pwd, fileName)\n\t// Set the config\n\tcfg.Lambda.SourceZip = builtZip\n\n\treturn builtZip\n}",
"func (a Aferox) TempFile(dir string, pattern string) (afero.File, error) {\n\tif dir != \"\" {\n\t\tdir = a.Abs(dir)\n\t}\n\treturn a.Afero.TempFile(dir, pattern)\n}",
"func (c *Compressor) Compress(w io.Writer) (io.WriteCloser, error) {\n\tif cw, got := c.compressors.Get().(*writer); got {\n\t\tcw.writer.Reset(w)\n\t\treturn cw, nil\n\t}\n\n\tcw, err := gzip.NewWriterLevel(w, c.level)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &writer{\n\t\twriter: cw,\n\t\tpool: &c.compressors,\n\t}, nil\n}",
"func (up *Uploader) TempFile() (*os.File, error) {\n\tif up.Meta.Range == nil {\n\t\treturn TempFile()\n\t}\n\treturn TempFileChunks(up.Meta.Range.Start, up.Root, up.Meta.UploadSid, up.Meta.Filename)\n}",
"func (c *ZstdCompressor) Compress(in io.Reader) error {\n\t_, err := io.Copy(c.encoder, in)\n\tif err != nil {\n\t\tc.encoder.Close()\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func (c *Client) CallCompressed(ctx context.Context, method string,\n\targ interface{}, res interface{}, ctype CompressionType, timeout time.Duration) error {\n\treturn c.call(ctx, method, arg, res, ctype, timeout)\n}",
"func CreateTempFile(tb testing.TB, name string, content []byte, in ...string) (string, func()) {\n\ttb.Helper()\n\n\tparent := \"\"\n\tif len(in) > 0 {\n\t\tparent = in[0]\n\t}\n\n\ttmpfile, err := ioutil.TempFile(parent, name+\"_*.testfile\")\n\tif err != nil {\n\t\ttb.Fatalf(\"unexpectedly failed creating the temp file: %v\", err)\n\t}\n\n\tif _, err := tmpfile.Write(content); err != nil {\n\t\ttb.Fatalf(\"unexpectedly failed writing to the temp file: %v\", err)\n\t}\n\n\tif err := tmpfile.Close(); err != nil {\n\t\ttb.Fatalf(\"unexpectedly failed closing the temp file: %v\", err)\n\t}\n\n\treturn tmpfile.Name(), func() { os.Remove(tmpfile.Name()) }\n}",
"func (self Codec) Compress(input []byte) ([]byte, error) {\n\treturn self.compression.Compress(input)\n}",
"func TempDirForOutDir(outDir string) (tempPath string) {\n\treturn filepath.Join(outDir, \".temp\")\n}",
"func Compress(d []byte) (*bytes.Buffer, error) {\n\tif len(d) == 0 {\n\t\treturn nil, errors.New(\"utils: empty data\")\n\t}\n\n\tvar buf bytes.Buffer\n\n\tw := gzip.NewWriter(&buf)\n\t_, err := w.Write(d)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_ = w.Close()\n\n\treturn &buf, nil\n}",
"func InTempDir(path ...string) string {\n\treturn filepath.Join(append([]string{os.TempDir()}, path...)...)\n}",
"func Compress(compType CompressionType, rawData []byte) ([]byte, error) {\n\tswitch compType {\n\tcase GZIP:\n\t\treturn gzipCompress(rawData)\n\tdefault:\n\t\terrMsg := fmt.Sprintf(\"Compression Type : %v is not yet supported.\", compType)\n\t\treturn nil, errors.New(errMsg)\n\t}\n}",
"func CompressGzip(filename string, file []byte) (result []byte, err error) {\n\tvar buf = new(bytes.Buffer)\n\tvar gw = gzip.NewWriter(buf)\n\n\tgw.Name = filename\n\n\tif _, err = gw.Write(file); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = gw.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), err\n}",
"func CreateTempfile(tmpDir, prefix, suffix string) (string, error) {\n\tf, err := ioutil.TempFile(tmpDir, prefix)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar tmpName string\n\tif tmpName, err = filepath.Abs(f.Name()); err != nil {\n\t\treturn \"\", err\n\t}\n\tif err = f.Close(); err != nil {\n\t\treturn \"\", err\n\t}\n\tif err = os.Remove(tmpName); err != nil {\n\t\tglog.Errorf(\"CreateTempfile unable to remove %s\", tmpName)\n\t\treturn \"\", err\n\t}\n\treturn tmpName + suffix, nil\n}",
"func tempFile(t *testing.T) (*os.File, func()) {\n\ttemp, err := ioutil.TempFile(os.TempDir(), \"darity\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treturn temp, func() {\n\t\t_ = temp.Close()\n\t\t_ = os.Remove(temp.Name())\n\t}\n}",
"func (c *cloner) zipPath() (string, error) {\n\tzipFiles, err := c.listZipFiles()\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\tcacheCandidates := zipFiles\n\tif c.noCache {\n\t\tcacheCandidates = nil\n\t}\n\tzipPath, cacheHit, err := c.downloadZip(cacheCandidates)\n\tif err != nil {\n\t\tif cacheHit {\n\t\t\tc.cli.printWarning(err)\n\t\t} else {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tif cacheHit {\n\t\tlog.Print(color.YellowString(\"Using cached sample apps ...\"))\n\t}\n\t// Remove obsolete files\n\tfor _, zf := range zipFiles {\n\t\tif zf.path != zipPath {\n\t\t\tos.Remove(zf.path)\n\t\t}\n\t}\n\treturn zipPath, nil\n}",
"func ProduceTGZfile(resource string) (io.Reader, error) {\n\tlog := context.GetDefaultLogger()\n\tvar buf bytes.Buffer\n\tvar filesFound []string\n\tvar link string\n\n\tgzipWriter := gzip.NewWriter(&buf)\n\tdefer gzipWriter.Close()\n\n\ttarWriter := tar.NewWriter(gzipWriter)\n\tdefer tarWriter.Close()\n\n\terr := filepath.Walk(resource, func(absoluteFilePath string, fileInfo os.FileInfo, err error) error {\n\t\tif IsSuffixSupported(fileInfo.Name()) {\n\n\t\t\tfileToCompress, err := os.Open(absoluteFilePath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer fileToCompress.Close()\n\n\t\t\tstat, err := fileToCompress.Stat()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif fileInfo.Mode()&os.ModeSymlink != 0 {\n\t\t\t\tlink, err = os.Readlink(absoluteFilePath)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\theader, err := tar.FileInfoHeader(fileInfo, link)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\theader.Name = filepath.ToSlash(fileInfo.Name())\n\t\t\theader.Linkname = filepath.ToSlash(header.Linkname)\n\t\t\theader.Format = tar.FormatPAX\n\t\t\theader.Size = stat.Size()\n\t\t\theader.Mode = int64(stat.Mode())\n\t\t\theader.ModTime = stat.ModTime()\n\t\t\t// write header\n\t\t\tif err := tarWriter.WriteHeader(header); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif _, err := io.Copy(tarWriter, fileToCompress); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfilesFound = append(filesFound, fileToCompress.Name())\n\t\t}\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Errorf(message.KogitoBuildFileWalkingError, resource, err)\n\t}\n\tlog.Infof(message.KogitoBuildFoundFile, filesFound)\n\treturn &buf, err\n}",
"func (pool *PackagePool) GenerateTempPath(filename string) (string, error) {\n\trandom := uuid.NewRandom().String()\n\n\treturn filepath.Join(pool.rootPath, random[0:2], random[2:4], random[4:]+filename), nil\n}",
"func (s *Store) TmpFile() (*os.File, error) {\n\tdir, err := s.TmpDir()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ioutil.TempFile(dir, \"\")\n}",
"func TemporaryDirectoryForBigFiles() string {\n\tvar temporaryDirectoryForBigFiles string\n\tif runtime.GOOS == \"windows\" {\n\t\ttemporaryDirectoryForBigFiles = os.TempDir()\n\t} else {\n\t\ttemporaryDirectoryForBigFiles = \"/var/tmp\"\n\t}\n\treturn temporaryDirectoryForBigFiles\n}",
"func (s *Gzip) DecompressFile(source, target string) error {\n\n\t//\tReading file and error handle\n\treader, err := os.Open(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer reader.Close()\n\n\t//\tReading zipped files\n\tarchive, err := gzip.NewReader(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer archive.Close()\n\n\t//\tCreating unzipped file\n\ttarget = filepath.Join(target, archive.Name)\n\twriter, err := os.Create(target)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer writer.Close()\n\n\t_, err = io.Copy(writer, archive)\n\treturn err\n}",
"func getOciTempCachePath(c *Handle) (string, error) {\n\t// This function may act on an cache object that is not fully initialized\n\t// so it is not a method on a Handle but rather an independent\n\t// function\n\n\treturn updateCacheSubdir(c, OciTempDir)\n}",
"func GetTempDir() (string, error) { return ioutil.TempDir(TempDir, \"\") }",
"func TempFile(dir, prefix string, suffix string) (f *os.File, err error) {\n\tif dir == \"\" {\n\t\tdir = os.TempDir()\n\t}\n\n\t// The maximum size of random file count\n\t// TODO: see if we can do this at package scope somehow\n\tvar maxRand *big.Int = big.NewInt(0)\n\tmaxRand.SetString(\"FFFFFFFFFFFFFFFF\", 16)\n\n\tvar randNum *big.Int\n\n\tfor i := 0; i < 10000; i++ {\n\t\t// Generate random part of the path name\n\t\trandNum, err = rand.Int(rand.Reader, maxRand)\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// Transform to an int\n\t\trandString := hex.EncodeToString(randNum.Bytes())\n\n\t\t// Attempt to open file and fail if it already exists\n\t\tname := filepath.Join(dir, prefix+randString+suffix)\n\t\tf, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)\n\t\tif os.IsExist(err) {\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\treturn\n}",
"func TempFilePath(prefix, suffix string) (string, error) {\n\tp, err := RandomFileName(prefix, suffix)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Join(os.TempDir(), p), nil\n}",
"func TempFile(t *testing.T, data string) (string, func()) {\n\tt.Helper()\n\n\tfp, err := ioutil.TempFile(os.TempDir(), \"gotest\")\n\tif err != nil {\n\t\tt.Fatalf(\"test.TempFile: could not create file in %v: %v\", os.TempDir(), err)\n\t}\n\n\tdefer func() {\n\t\terr := fp.Close()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"test.TempFile: close: %v\", err)\n\t\t}\n\t}()\n\n\t_, err = fp.WriteString(data)\n\tif err != nil {\n\t\tt.Fatalf(\"test.TempFile: write: %v\", err)\n\t}\n\n\treturn fp.Name(), func() {\n\t\terr := os.Remove(fp.Name())\n\t\tif err != nil {\n\t\t\tt.Errorf(\"test.TempFile: cannot remove %#v: %v\", fp.Name(), err)\n\t\t}\n\t}\n}",
"func (a Aferox) TempDir(dir string, prefix string) (string, error) {\n\tif dir != \"\" {\n\t\tdir = a.Abs(dir)\n\t}\n\treturn a.Afero.TempDir(dir, prefix)\n}",
"func Pack(gzPath, dirPath string, pathMap map[string]int) error {\n\tfw, err := os.Create(gzPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fw.Close()\n\n\tgw := gzip.NewWriter(fw)\n\tdefer gw.Close()\n\n\ttw := tar.NewWriter(gw)\n\tdefer tw.Close()\n\n\tfor path, val := range pathMap {\n\t\tif val < 0 {\n\t\t\tcontinue\n\t\t}\n\t\tf, err := os.Stat(filepath.Join(dirPath, path))\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif f.IsDir() {\n\t\t\tcontinue\n\t\t}\n\n\t\tfr, err := os.Open(filepath.Join(dirPath, path))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer fr.Close()\n\n\t\th := new(tar.Header)\n\t\th.Name = path\n\t\th.Size = f.Size()\n\t\th.Mode = int64(f.Mode())\n\t\th.ModTime = f.ModTime()\n\n\t\terr = tw.WriteHeader(h)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = io.Copy(tw, fr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}",
"func Untargzip(path string, r io.Reader) error {\n\tungzipped, err := gzip.NewReader(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttarball := tar.NewReader(ungzipped)\n\n\tdefer ungzipped.Close()\n\n\t// We have to treat things differently for git-archives\n\tisGitArchive := false\n\n\t// Alright, things seem in order, let's make the base directory\n\tos.MkdirAll(path, 0755)\n\tfor {\n\t\thdr, err := tarball.Next()\n\t\tif err == io.EOF {\n\t\t\t// finished the tar\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Skip the base dir\n\t\tif hdr.Name == \"./\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t// If this was made with git-archive it will be in kinda an ugly\n\t\t// format, but we can identify it by the pax_global_header \"file\"\n\t\tname := hdr.Name\n\t\tif name == \"pax_global_header\" {\n\t\t\tisGitArchive = true\n\t\t\tcontinue\n\t\t}\n\n\t\t// It will also contain an extra subdir that we will automatically strip\n\t\tif isGitArchive {\n\t\t\tparts := strings.Split(name, \"/\")\n\t\t\tname = strings.Join(parts[1:], \"/\")\n\t\t}\n\n\t\tfpath := filepath.Join(path, name)\n\t\tif hdr.FileInfo().IsDir() {\n\t\t\terr = os.MkdirAll(fpath, 0755)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tfile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE, hdr.FileInfo().Mode())\n\t\tdefer file.Close()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = io.Copy(file, tarball)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfile.Close()\n\t}\n\treturn nil\n}",
"func TestCompress(t *testing.T) {\n\tnewIntegrationTest(\"compress.example.com\", \"compress\").withoutSSHKey().\n\t\twithAddons(\n\t\t\tawsEBSCSIAddon,\n\t\t\tdnsControllerAddon,\n\t\t\tawsCCMAddon,\n\t\t).\n\t\trunTestTerraformAWS(t)\n}",
"func processDirectory(dirpath string) {\r\n\r\n\tvar wg sync.WaitGroup\r\n\r\n\terr := filepath.Walk(dirpath, func(path string, info os.FileInfo, err error) error {\r\n\t\tif info.IsDir() {\r\n\t\t\treturn nil\r\n\t\t}\r\n\t\twg.Add(1)\r\n\t\tprocessFile(path, dirpath, &wg)\r\n\t\treturn nil\r\n\t})\r\n\r\n\twg.Wait()\r\n\r\n\tif err != nil {\r\n\t\tlog.Fatal(err)\r\n\t\ttime.Sleep(10 * time.Second)\r\n\t\treturn\r\n\t}\r\n\r\n\t// compress\r\n\tcandiname := dirpath\r\n\text := \".zip\"\r\n\t// add _re until not exist file\r\n\tfor {\r\n\t\tif _, err := os.Stat(candiname + ext); os.IsNotExist(err) {\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tcandiname += \"_re\"\r\n\t}\r\n\r\n\tfmt.Println(dirpath + \"_re\")\r\n\t// bandizip.exe doesn't save top folder name, but bc.exe does, so use *.* with -r\r\n\tcmd := exec.Command(zipApp, \"c\", \"-r\", candiname+ext, dirpath+\"_re\\\\*.*\")\r\n\texecErr := cmd.Run()\r\n\tif execErr != nil {\r\n\t\tpanic(execErr)\r\n\t}\r\n\r\n\t// delete folder A_re\r\n\tos.RemoveAll(dirpath + \"_re\")\r\n}",
"func tempFileFrom(path string) (tf *os.File, err error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tpattern := \"*\"\n\tif ext := filepath.Ext(path); ext != \"\" {\n\t\tpattern = fmt.Sprintf(\"*.%s\", ext)\n\t}\n\n\ttf, err = ioutil.TempFile(\"\", pattern)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\ttf.Close()\n\t\t}\n\t}()\n\n\tif _, err := io.Copy(tf, f); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err := tf.Seek(0, io.SeekStart); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tf, nil\n}",
"func CompressTar(src []string, dest string) (err error) {\n\t// create the dest tar file...\n\tfile, err := os.Create(dest)\n\tif err != nil {\n\t\tlog.Println(\"Error create file:\", err)\n\t\treturn err\n\t}\n\tdefer file.Close()\n\t// apply one tar writer to write file\n\ttw := tar.NewWriter(file)\n\tdefer tw.Close()\n\t// loop compress src list files\n\tfor _, v := range src {\n\t\terr = filepath.Walk(v, func(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Error compress file:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// get file information header\n\t\t\theader, err := tar.FileInfoHeader(info, \"\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Error get file info header:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// assign compress method\n\t\t\terr = tw.WriteHeader(header)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Error write compress file header:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// open the src file...\n\t\t\tdata, err := os.Open(path)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Error open file:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer data.Close()\n\t\t\t// write compress data into file\n\t\t\t_, err = io.Copy(tw, data)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Error write compress data into file:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn err\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error compress file:\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}",
"func processArchive(path string) {\r\n\text := filepath.Ext(path)\r\n\r\n\t// -o:outputpath\r\n\textractpath := strings.TrimSpace(path[:len(path)-len(ext)])\r\n\r\n\tcmd := exec.Command(zipApp, \"x\", \"-o:\"+extractpath, path)\r\n\r\n\texecErr := cmd.Run()\r\n\tif execErr != nil {\r\n\t\tpanic(execErr)\r\n\t}\r\n\r\n\tprocessDirectory(extractpath)\r\n\r\n\tos.RemoveAll(extractpath)\r\n}",
"func TempDir() string {\n\treturn tempDir\n}",
"func createTempFile(dir, fileNamePattern string, fileSize uint64) (absFilePath string, merkleRoot crypto.Hash, err error) {\n\terr = os.MkdirAll(dir, 0700)\n\tif err != nil {\n\t\treturn \"\", crypto.Hash{}, fmt.Errorf(\"error creating an upload directory: %v\", err)\n\t}\n\tf, err := ioutil.TempFile(dir, fileNamePattern)\n\tif err != nil {\n\t\treturn \"\", crypto.Hash{}, fmt.Errorf(\"error creating temp file: %v\", err)\n\t}\n\tdefer func() {\n\t\terr = errors.Compose(err, f.Close())\n\t}()\n\n\tabsFilePath, err = filepath.Abs(f.Name())\n\tif err != nil {\n\t\treturn \"\", crypto.Hash{}, fmt.Errorf(\"error getting temp file absolute path: %v\", err)\n\t}\n\n\t// Fill the file with random data.\n\tmerkleRoot, err = randFillFile(f, fileSize)\n\tif err != nil {\n\t\treturn \"\", crypto.Hash{}, fmt.Errorf(\"error filling file with random data: %v\", err)\n\t}\n\n\treturn absFilePath, merkleRoot, nil\n}",
"func TempDir(tc Context) (string, error) {\n\treturn os.TempDir(), nil\n}",
"func CompressTarGz(src []string, dest string) (err error) {\n\t// create the dest tar.gz file...\n\tfile, err := os.Create(dest)\n\tif err != nil {\n\t\tlog.Println(\"Error create file:\", err)\n\t\treturn err\n\t}\n\tdefer file.Close()\n\t// apply one gzip writer to write file\n\tgw := gzip.NewWriter(file)\n\tdefer gw.Close()\n\t// apply one tar writer to write file\n\ttw := tar.NewWriter(gw)\n\tdefer tw.Close()\n\t// loop compress src list files\n\tfor _, v := range src {\n\t\terr = filepath.Walk(v, func(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Error compress file:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// get file information header\n\t\t\theader, err := tar.FileInfoHeader(info, \"\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Error get file info header:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// assign compress method\n\t\t\terr = tw.WriteHeader(header)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Error write compress file header:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// open the src file...\n\t\t\tdata, err := os.Open(path)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Error open file:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer data.Close()\n\t\t\t// write compress data into file\n\t\t\t_, err = io.Copy(tw, data)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Error write compress data into file:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn err\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error compress file:\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}",
"func (fs FilesystemStorage) TempDir() string {\n\treturn filepath.Join(fs.String(), \"tmp\")\n}",
"func TempDir() (WorkDir, error) {\n\ttmpPath, err := ioutil.TempDir(\"\", \"workdir\")\n\tif err != nil {\n\t\treturn WorkDir(\"\"), err\n\t}\n\treturn WorkDir(tmpPath), nil\n}",
"func TempNamedFile(dir, prefix, ext string) (string, error) {\n\tvar f, err = TempFile(dir, prefix, ext)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar n = f.Name()\n\tf.Close()\n\treturn n, nil\n}",
"func createTemporaryFile(content, extension, fileName, prefix, suffix, dir string) os.File {\n\tbinaryContent := []byte(content)\n\tvar tmpFile *os.File\n\tvar err error\n\n\tif fileName == \"\" {\n\t\ttmpFile, err = ioutil.TempFile(dir, prefix+\"*\"+suffix+\".\"+extension)\n\t} else {\n\t\tfileName = filepath.Join(dir, fileName+\".\"+extension)\n\t\ttmpFile, err = os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)\n\t}\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer closeFile(*tmpFile)\n\tif _, err := tmpFile.Write(binaryContent); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn *tmpFile\n}"
] | [
"0.6226838",
"0.5990775",
"0.59854096",
"0.5882066",
"0.58763057",
"0.58193755",
"0.5473196",
"0.54528064",
"0.542648",
"0.526625",
"0.5130097",
"0.5127105",
"0.5085201",
"0.5072822",
"0.5063636",
"0.50320655",
"0.50147414",
"0.49929637",
"0.4960555",
"0.4955685",
"0.4935977",
"0.48971236",
"0.4891632",
"0.48859012",
"0.4877304",
"0.48765913",
"0.4867281",
"0.48280394",
"0.47968665",
"0.4794061",
"0.4786516",
"0.4786236",
"0.47708547",
"0.47656316",
"0.47631952",
"0.47566846",
"0.4754074",
"0.47502717",
"0.474546",
"0.47340813",
"0.47249496",
"0.47214666",
"0.471966",
"0.4716555",
"0.47113615",
"0.47104713",
"0.4708859",
"0.46936038",
"0.46875897",
"0.4685779",
"0.46764407",
"0.4671609",
"0.4655191",
"0.46493754",
"0.464816",
"0.4625965",
"0.46199918",
"0.46195847",
"0.46109748",
"0.46100983",
"0.46037418",
"0.45924634",
"0.45876172",
"0.45740038",
"0.45600012",
"0.45491135",
"0.45377114",
"0.45342192",
"0.4518281",
"0.45011806",
"0.44919235",
"0.44869858",
"0.4486138",
"0.44848728",
"0.44771644",
"0.4476094",
"0.4460168",
"0.44559133",
"0.4455651",
"0.44526097",
"0.44460398",
"0.44274718",
"0.44077846",
"0.43887064",
"0.43882412",
"0.438324",
"0.4376773",
"0.43666098",
"0.43655622",
"0.43579715",
"0.43493855",
"0.43409717",
"0.43353334",
"0.43349728",
"0.4327505",
"0.43249622",
"0.42961487",
"0.42897496",
"0.42778954",
"0.4277478"
] | 0.7649324 | 0 |
Decompress decompresses the file inPath to outPath. | func Decompress(inPath string, outPath string) error {
// open the input, compressed file
inFile, err := os.Open(inPath)
if err != nil {
return err
}
// we open this for read only, and this process exists after a finite (short)
// period of time; there's no need to throw an error if closing it fails
defer inFile.Close()
// open output file
outFile, err := os.Create(outPath)
if err != nil {
return err
}
// lz4 read buffer
r := lz4.NewReader(inFile)
// write buffer
w := bufio.NewWriter(outFile)
// 4kb chunks
buf := make([]byte, 4096)
for {
// read a chunk
n, err := r.Read(buf)
if err != nil && err != io.EOF {
return err
}
if n == 0 {
break
}
// write a chunk
if _, err := w.Write(buf[:n]); err != nil {
return err
}
}
// flush and pending data
if err = w.Flush(); err != nil {
panic(err)
}
// make sure we successfully close the compressed file
if err := outFile.Close(); err != nil {
return err
}
return nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func Decompress(file *os.File, outputName string) {\n\t// Ler Árvore (Reconstruir)\n\treader := bit.NewReader(file)\n\troot := readTree(reader)\n\tif root == nil {\n\t\tpanic(\"Árvore nula!\")\n\t}\n\t// Decodificar percorrendo a arvore\n\tif root.IsLeaf() {\n\t\tnodeHelper := tree.New(\"\", nil, nil)\n\t\tnodeHelper.Left = root\n\t\troot = nodeHelper\n\t}\n\tdecodeFile(reader, outputName, root)\n}",
"func Decompress(path, target string) error {\n\n\t//create zip reader\n\tr, err := zip.OpenReader(path)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"fs: decompress failed to open zip reader\")\n\t}\n\n\t//iterate and extract all files in the zip archive to target\n\tfor _, file := range r.File {\n\t\t//Get absolute location from archive relative path\n\t\tdestFile := filepath.Join(target, file.Name)\n\n\t\t//Get files directory name and create the folder hierarchy\n\t\tdestDir, _ := filepath.Split(destFile)\n\t\tif err := os.MkdirAll(destDir, file.Mode()); err != nil {\n\t\t\treturn errors.Wrap(err, \"fs: decompress failed to create destination\")\n\t\t}\n\n\t\t//open zipped file for decompression\n\t\tzippedFile, err := file.Open()\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"fs: decompress failed to open zipped file\")\n\t\t}\n\n\t\t//open destination file\n\t\tdest, err := os.OpenFile(destFile, os.O_RDWR|os.O_CREATE, file.Mode())\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"fs: decompress failed to open destination file\")\n\t\t}\n\n\t\t//Write unzipped file to destination\n\t\tif _, err := io.Copy(dest, zippedFile); err != nil {\n\t\t\treturn errors.Wrap(err, \"fs: decompress failed to write unzip file to destination\")\n\t\t}\n\n\t\t//close opened zip file\n\t\tif err := zippedFile.Close(); err != nil {\n\t\t\treturn errors.Wrap(err, \"fs: decompress failed to close zipped file\")\n\t\t}\n\n\t\t//close opened destination file\n\t\tif err := dest.Close(); err != nil {\n\t\t\treturn errors.Wrap(err, \"fs: decompress failed to close destination file\")\n\t\t}\n\n\t}\n\n\t//close zip reader\n\tif err := r.Close(); err != nil {\n\t\treturn errors.Wrap(err, \"fs: decompress failed to close zip reader\")\n\t}\n\n\treturn nil\n}",
"func Uncompress() gonzo.Stage {\n\treturn func(ctx context.Context, in <-chan gonzo.File, out chan<- gonzo.File) error {\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase file, ok := <-in:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tcontent, err := gzip.NewReader(file)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tfs := gonzo.NewFile(\n\t\t\t\t\t&doublecloser{content, file.Close},\n\t\t\t\t\tgonzo.FileInfoFrom(file.FileInfo()),\n\t\t\t\t)\n\n\t\t\t\tout <- fs\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\t\t\t}\n\t\t}\n\t}\n}",
"func (x *Xz) Decompress(in io.Reader, out io.Writer) error {\n\tr, err := fastxz.NewReader(in, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(out, r)\n\treturn err\n}",
"func (cmp Compressor) Compress(path string) error {\n compressedPath := path + \".lz4\"\n\n err := exec.Command(cmp.lz4Path, path, compressedPath).Run()\n if err != nil {\n return err\n }\n\n return os.Remove(path)\n}",
"func Decompress(header *common.Header, filename string, output string) error {\r\n\r\n\tf, err := os.Open(filename)\r\n\tdefer f.Close()\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\tinitOpenedZipFiles()\r\n\tdefer closeOpenedZipFiles()\r\n\r\n\tfoldersNum := len(header.Folders)\r\n\treadedFolders := 0\r\n\r\n\tfor _, folder := range header.Folders {\r\n\t\tif (folder.Flags == common.FData || folder.Flags == common.FFolder) && folder.Data == uint32(0xFFFFFFFF) {\r\n\t\t\treadedFolders++\r\n\t\t\tui.Current().Unpack(readedFolders, foldersNum)\r\n\t\t\terr = writeFile(output, header, &folder, nil)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tneedToRead := int64(header.Size)\r\n\treaded := int64(0)\r\n\r\n\tvar b bytes.Buffer\r\n\r\n\tr := lzma.NewReader(f)\r\n\r\n\tfor _, dataRecord := range header.Data {\r\n\t\tb.Reset()\r\n\t\tn, err := io.CopyN(&b, r, int64(dataRecord.Size))\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t\treaded += n\r\n\r\n\t\tfor _, folder := range header.Folders {\r\n\t\t\tif folder.Flags == common.FData && folder.Data == uint32(dataRecord.Offset) {\r\n\t\t\t\treadedFolders++\r\n\t\t\t\terr = writeFile(output, header, &folder, b.Bytes())\r\n\t\t\t\tui.Current().Unpack(readedFolders, foldersNum)\r\n\t\t\t\tif err != nil {\r\n\t\t\t\t\treturn err\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\t_ = r.Close()\r\n\tb.Reset()\r\n\r\n\truntime.GC()\r\n\tif readed != needToRead {\r\n\t\treturn fmt.Errorf(\"Readed: %d, Expected: %d\", readed, needToRead)\r\n\t}\r\n\r\n\treturn nil\r\n}",
"func (s *Gzip) DecompressFile(source, target string) error {\n\n\t//\tReading file and error handle\n\treader, err := os.Open(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer reader.Close()\n\n\t//\tReading zipped files\n\tarchive, err := gzip.NewReader(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer archive.Close()\n\n\t//\tCreating unzipped file\n\ttarget = filepath.Join(target, archive.Name)\n\twriter, err := os.Create(target)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer writer.Close()\n\n\t_, err = io.Copy(writer, archive)\n\treturn err\n}",
"func (dec *ZstdDecompressor) Decompress(out io.Writer) error {\n\t_, err := io.Copy(out, dec.decoder)\n\tif err != nil {\n\t\tdec.decoder.Close()\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func decompress(src io.Reader, dest io.Writer) {\n\tdecompressor := flate.NewReader(src)\n\tio.Copy(dest, decompressor)\n\tdecompressor.Close()\n}",
"func Uncompress(out, in []byte) (outSize int, err error) {\n\toutSize = int(C.LZ4_decompress_safe(p(in), p(out), clen(in), clen(out)))\n\tif outSize < 0 {\n\t\terr = errors.New(\"Malformed compression stream\")\n\t}\n\treturn\n}",
"func Decompress(b []byte, s *Scratch) ([]byte, error) {\n\ts, err := s.prepare(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.Out = s.Out[:0]\n\terr = s.readNCount()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = s.buildDtable()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = s.decompress()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.Out, nil\n}",
"func Decompress(dst, src []byte) ([]byte, error) {\n\treturn decoder.DecodeAll(src, dst)\n}",
"func (s *Gzip) Decompress(reader io.Reader, writer io.Writer) error {\n\n\tarchive, err := gzip.NewReader(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer archive.Close()\n\n\t_, err = io.Copy(writer, archive)\n\treturn err\n\n}",
"func Decompress(input, output []byte) (outSize int, err error) {\r\n\tvar errCode C.int\r\n\toutSize = int(C.lzf_decompress(p(input), clen(input), p(output), clen(output), &errCode))\r\n\tif outSize > 0 {\r\n\t\treturn\r\n\t}\r\n\tswitch errCode {\r\n\tcase C.E2BIG:\r\n\t\terr = ErrInsufficientBuffer\r\n\tcase C.EINVAL:\r\n\t\terr = ErrDataCorruption\r\n\tdefault:\r\n\t\terr = ErrUnknown\r\n\t}\r\n\treturn\r\n}",
"func DecompressFiles(b []byte, dir string) error {\n\tif env.Debug {\n\t\tlog.Printf(\"Decompressing %d bytes to %s\", len(b), dir)\n\t}\n\treturn archiver.Zip.Read(bytes.NewBuffer(b), dir)\n}",
"func BundleUncompress(input io.Reader, path string) error {\n\tfileReader, err := gzip.NewReader(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer fileReader.Close()\n\n\ttarBallReader := tar.NewReader(fileReader)\n\n\tfor {\n\t\theader, err := tarBallReader.Next()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\t// get the individual filename and extract to the current directory\n\t\t// and join it with path\n\t\tfilename := filepath.Join(path, header.Name)\n\n\t\tswitch header.Typeflag {\n\t\tcase tar.TypeDir:\n\t\t\t// handle directory\n\t\t\terr = os.MkdirAll(filename, os.ModePerm)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase tar.TypeReg, tar.TypeRegA:\n\t\t\t// we need to make sure the folder exists\n\t\t\tdir := filepath.Dir(filename)\n\t\t\terr = os.MkdirAll(dir, os.ModePerm)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// handle normal file\n\t\t\twriter, err := os.Create(filename)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tio.Copy(writer, tarBallReader)\n\n\t\t\terr = os.Chmod(filename, os.ModePerm)\n\t\t\tif err != nil {\n\t\t\t\twriter.Close()\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\twriter.Close()\n\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"Unable to untar type : %c in file %s\", header.Typeflag, filename)\n\t\t}\n\t}\n\n\treturn nil\n}",
"func UnarchiveFile(inFilePath string, outFilePath string, progress ProgressFunc) (err error) {\n\tvar inFile *os.File\n\tvar inFileInfo os.FileInfo\n\n\tinFile, err = os.Open(inFilePath)\n\tif err == nil {\n\t\tinFileInfo, err = inFile.Stat()\n\t\tif err == nil {\n\t\t\terr = Unarchive(inFile, inFileInfo.Size(), outFilePath, progress)\n\t\t}\n\t\tinFile.Close()\n\t}\n\treturn\n}",
"func DecompressCommand(src io.Reader, url, cmd, os, arch string) (io.Reader, error) {\n\tfor _, fileType := range fileTypes {\n\t\tif strings.HasSuffix(url, fileType.ext) {\n\t\t\treturn fileType.decompress(src, cmd, os, arch)\n\t\t}\n\t}\n\tlog.Print(\"File is not compressed\")\n\treturn src, nil\n}",
"func decompress(in []byte) ([]byte, error) {\n\tr, err := zlib.NewReader(bytes.NewBuffer(in))\n\tif err != nil {\n\t\treturn nil, errors.New(\"decompression failed\")\n\t}\n\n\tbuf := new(bytes.Buffer)\n\t_, err = buf.ReadFrom(r)\n\t//log.Printf(\"Decompressed %d bytes from %d bytes\\n\", unzippedLen, len(in))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}",
"func Uncompress(data []byte) []byte {\n\tb := bytes.NewBuffer(data)\n\tr, err := zlib.NewReader(b)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tbuf, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tr.Close()\n\n\treturn buf\n}",
"func Decompress(dst, src []byte) (n int, err error) {\n\tif len(src) == 0 {\n\t\treturn 0, nil\n\t}\n\tvar result C.int\n\tif len(dst) > 0 {\n\t\tresult = C.LZ4_decompress_safe(\n\t\t\t(*C.char)(unsafe.Pointer(&src[0])),\n\t\t\t(*C.char)(unsafe.Pointer(&dst[0])),\n\t\t\tC.int(len(src)),\n\t\t\tC.int(len(dst)))\n\t}\n\tif result <= 0 {\n\t\treturn 0, ErrDecompress\n\t}\n\treturn int(result), nil\n}",
"func Compress(inPath string, tmpDir string) (string, error) {\n\t// create a temporary file with a unique name compress it -- multiple files\n\t// are named 000: pg_notify/0000, pg_subtrans/0000\n\toutFile, err := ioutil.TempFile(tmpDir, \"pgCarpenter.\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// open input file\n\tinFile, err := os.Open(inPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// we open this for read only, and this process exists after a finite (short)\n\t// period of time; there's no need to throw an error if closing it fails\n\tdefer inFile.Close()\n\n\t// buffer read from the input file and lz4 writer\n\tr := bufio.NewReader(inFile)\n\tw := lz4.NewWriter(outFile)\n\n\t// read 4k at a time\n\tbuf := make([]byte, 4096)\n\tfor {\n\t\tn, err := r.Read(buf)\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\t// we're done\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t// write the 4k chunk\n\t\tif _, err := w.Write(buf[:n]); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\t// flush any pending compressed data\n\tif err = w.Flush(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// make sure we successfully close the compressed file\n\tif err := outFile.Close(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn outFile.Name(), nil\n}",
"func Uncompress(_ *flag.FlagSet) cmdflag.Handler {\n\treturn func(args ...string) (int, error) {\n\t\tzr := lz4.NewReader(nil)\n\n\t\t// Use stdin/stdout if no file provided.\n\t\tif len(args) == 0 {\n\t\t\tzr.Reset(os.Stdin)\n\t\t\t_, err := io.Copy(os.Stdout, zr)\n\t\t\treturn 0, err\n\t\t}\n\n\t\tfor fidx, zfilename := range args {\n\t\t\t// Input file.\n\t\t\tzfile, err := os.Open(zfilename)\n\t\t\tif err != nil {\n\t\t\t\treturn fidx, err\n\t\t\t}\n\t\t\tzinfo, err := zfile.Stat()\n\t\t\tif err != nil {\n\t\t\t\treturn fidx, err\n\t\t\t}\n\t\t\tmode := zinfo.Mode() // use the same mode for the output file\n\n\t\t\t// Output file.\n\t\t\tfilename := strings.TrimSuffix(zfilename, lz4Extension)\n\t\t\tfile, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, mode)\n\t\t\tif err != nil {\n\t\t\t\treturn fidx, err\n\t\t\t}\n\t\t\tzr.Reset(zfile)\n\n\t\t\tzfinfo, err := zfile.Stat()\n\t\t\tif err != nil {\n\t\t\t\treturn fidx, err\n\t\t\t}\n\t\t\tvar (\n\t\t\t\tsize int\n\t\t\t\tout io.Writer = file\n\t\t\t\tzsize = zfinfo.Size()\n\t\t\t\tbar *progressbar.ProgressBar\n\t\t\t)\n\t\t\tif zsize > 0 {\n\t\t\t\tbar = progressbar.NewOptions64(zsize,\n\t\t\t\t\t// File transfers are usually slow, make sure we display the bar at 0%.\n\t\t\t\t\tprogressbar.OptionSetRenderBlankState(true),\n\t\t\t\t\t// Display the filename.\n\t\t\t\t\tprogressbar.OptionSetDescription(filename),\n\t\t\t\t\tprogressbar.OptionClearOnFinish(),\n\t\t\t\t)\n\t\t\t\tout = io.MultiWriter(out, bar)\n\t\t\t\t_ = zr.Apply(\n\t\t\t\t\tlz4.OnBlockDoneOption(func(n int) {\n\t\t\t\t\t\tsize += n\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// Uncompress.\n\t\t\t_, err = io.Copy(out, zr)\n\t\t\tif err != nil {\n\t\t\t\treturn fidx, err\n\t\t\t}\n\t\t\tfor _, c := range []io.Closer{zfile, file} {\n\t\t\t\terr := c.Close()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fidx, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif bar != nil {\n\t\t\t\t_ = bar.Clear()\n\t\t\t\tfmt.Printf(\"%s %d\\n\", zfilename, size)\n\t\t\t}\n\t\t}\n\n\t\treturn len(args), nil\n\t}\n}",
"func Decompress(b io.Reader) ([]byte, error) {\n\tr, err := gzip.NewReader(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Close()\n\n\td, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn d, nil\n}",
"func bz2Decompress1(src, des string) error {\n\tstart := time.Now()\n\tvar bzReader io.Reader\n\tvar f, w *os.File\n\tvar err error\n\tfilename := filepath.Join(des, getFilename(src))\n\terr = func() error { // file obj prepare\n\t\tif err = os.MkdirAll(des, 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tf, err = os.Open(src)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tw, err = os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0777)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tdefer w.Close()\n\n\tbzReader = bzip2.NewReader(f)\n\tra := readahead.NewReader(bzReader) // use readahead to optimize\n\tdefer ra.Close()\n\n\tio.Copy(w, ra)\n\tfmt.Println(time.Since(start))\n\treturn nil\n}",
"func Decompress(src io.Reader, dst string) error {\n\t// need to set umask to be 000 for current process.\n\t// there will be some files having higher permission like 777,\n\t// eventually permission will be set to 755 when umask is 022.\n\t_, err := system.Umask(0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.MkdirAll(dst, common.FileMode0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tzr, err := gzip.NewReader(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttr := tar.NewReader(zr)\n\ttype DirStruct struct {\n\t\theader *tar.Header\n\t\tdir string\n\t\tnext, prev *DirStruct\n\t}\n\n\tprefixes := make(map[string]*DirStruct)\n\tfor {\n\t\theader, err := tr.Next()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// validate name against path traversal\n\t\tif !validRelPath(header.Name) {\n\t\t\treturn fmt.Errorf(\"tar contained invalid name error %q\", header.Name)\n\t\t}\n\n\t\ttarget := filepath.Join(dst, header.Name)\n\n\t\tswitch header.Typeflag {\n\t\tcase tar.TypeDir:\n\t\t\tif _, err = os.Stat(target); err != nil {\n\t\t\t\tif err = os.MkdirAll(target, os.FileMode(header.Mode)); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\t// building a double linked list\n\t\t\t\tprefix := filepath.Dir(target)\n\t\t\t\tprev := prefixes[prefix]\n\t\t\t\t//an root dir\n\t\t\t\tif prev == nil {\n\t\t\t\t\tprefixes[target] = &DirStruct{header: header, dir: target, next: nil, prev: nil}\n\t\t\t\t} else {\n\t\t\t\t\tnewHead := &DirStruct{header: header, dir: target, next: nil, prev: prev}\n\t\t\t\t\tprev.next = newHead\n\t\t\t\t\tprefixes[target] = newHead\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase tar.TypeReg:\n\t\t\terr = func() error {\n\t\t\t\t// regularly won't mkdir, unless add newFolder on compressing\n\t\t\t\tinErr := utils.MkDirIfNotExists(filepath.Dir(target))\n\t\t\t\tif inErr != nil {\n\t\t\t\t\treturn inErr\n\t\t\t\t}\n\n\t\t\t\tfileToWrite, inErr := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_RDWR, os.FileMode(header.Mode))\n\t\t\t\tif inErr != nil {\n\t\t\t\t\treturn inErr\n\t\t\t\t}\n\n\t\t\t\tdefer fileToWrite.Close()\n\t\t\t\tif _, inErr = io.Copy(fileToWrite, tr); inErr != nil {\n\t\t\t\t\treturn inErr\n\t\t\t\t}\n\t\t\t\t// for not changing\n\t\t\t\treturn os.Chtimes(target, header.AccessTime, header.ModTime)\n\t\t\t}()\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, v := range prefixes {\n\t\t// for taking the last one\n\t\tif v.next != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// every change in dir, will change the metadata of that dir\n\t\t// change times from the last one\n\t\t// do this is for not changing metadata of parent dir\n\t\tfor dirStr := v; dirStr != nil; dirStr = dirStr.prev {\n\t\t\tif err = os.Chtimes(dirStr.dir, dirStr.header.AccessTime, dirStr.header.ModTime); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}",
"func Decompress(proof *CommitmentProof) *CommitmentProof {\n\tcomp := proof.GetCompressed()\n\tif comp != nil {\n\t\treturn &CommitmentProof{\n\t\t\tProof: &CommitmentProof_Batch{\n\t\t\t\tBatch: decompress(comp),\n\t\t\t},\n\t\t}\n\t}\n\treturn proof\n}",
"func decompress(targetDir string, tarFile string, excludeFiles []string) error {\n\treader, err := os.Open(tarFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer reader.Close()\n\n\tgzReader, err := gzip.NewReader(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer gzReader.Close()\n\n\ttarReader := tar.NewReader(gzReader)\n\tfor {\n\t\theader, err := tarReader.Next()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif isExcluded(header.Name, excludeFiles) {\n\t\t\tcontinue\n\t\t}\n\n\t\ttarget := path.Join(targetDir, header.Name)\n\t\tswitch header.Typeflag {\n\t\tcase tar.TypeDir:\n\t\t\terr = os.MkdirAll(target, os.FileMode(header.Mode))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase tar.TypeReg:\n\t\t\tw, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_, err = io.Copy(w, tarReader)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tw.Close()\n\t\tdefault:\n\t\t\tlog.Printf(\"Unsupported type: %v\", header.Typeflag)\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (s *Scratch) decompress() error {\n\tbr := &s.bits\n\tif err := br.init(s.br.unread()); err != nil {\n\t\treturn err\n\t}\n\n\tvar s1, s2 decoder\n\t// Initialize and decode first state and symbol.\n\ts1.init(br, s.decTable, s.actualTableLog)\n\ts2.init(br, s.decTable, s.actualTableLog)\n\n\t// Use temp table to avoid bound checks/append penalty.\n\tvar tmp = s.ct.tableSymbol[:256]\n\tvar off uint8\n\n\t// Main part\n\tif !s.zeroBits {\n\t\tfor br.off >= 8 {\n\t\t\tbr.fillFast()\n\t\t\ttmp[off+0] = s1.nextFast()\n\t\t\ttmp[off+1] = s2.nextFast()\n\t\t\tbr.fillFast()\n\t\t\ttmp[off+2] = s1.nextFast()\n\t\t\ttmp[off+3] = s2.nextFast()\n\t\t\toff += 4\n\t\t\t// When off is 0, we have overflowed and should write.\n\t\t\tif off == 0 {\n\t\t\t\ts.Out = append(s.Out, tmp...)\n\t\t\t\tif len(s.Out) >= s.DecompressLimit {\n\t\t\t\t\treturn fmt.Errorf(\"output size (%d) > DecompressLimit (%d)\", len(s.Out), s.DecompressLimit)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor br.off >= 8 {\n\t\t\tbr.fillFast()\n\t\t\ttmp[off+0] = s1.next()\n\t\t\ttmp[off+1] = s2.next()\n\t\t\tbr.fillFast()\n\t\t\ttmp[off+2] = s1.next()\n\t\t\ttmp[off+3] = s2.next()\n\t\t\toff += 4\n\t\t\tif off == 0 {\n\t\t\t\ts.Out = append(s.Out, tmp...)\n\t\t\t\t// When off is 0, we have overflowed and should write.\n\t\t\t\tif len(s.Out) >= s.DecompressLimit {\n\t\t\t\t\treturn fmt.Errorf(\"output size (%d) > DecompressLimit (%d)\", len(s.Out), s.DecompressLimit)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\ts.Out = append(s.Out, tmp[:off]...)\n\n\t// Final bits, a bit more expensive check\n\tfor {\n\t\tif s1.finished() {\n\t\t\ts.Out = append(s.Out, s1.final(), s2.final())\n\t\t\tbreak\n\t\t}\n\t\tbr.fill()\n\t\ts.Out = append(s.Out, s1.next())\n\t\tif s2.finished() {\n\t\t\ts.Out = append(s.Out, s2.final(), s1.final())\n\t\t\tbreak\n\t\t}\n\t\ts.Out = append(s.Out, s2.next())\n\t\tif len(s.Out) >= s.DecompressLimit {\n\t\t\treturn fmt.Errorf(\"output size (%d) > DecompressLimit (%d)\", len(s.Out), s.DecompressLimit)\n\t\t}\n\t}\n\treturn br.close()\n}",
"func unbzip2(path string, file io.Reader) {\n\tuntar(path, bzip2.NewReader(file))\n}",
"func DeCompressGzip(src []string, dest string) (err error) {\n\t// check the dest whether dir or not...\n\tis, err := utils.IsDir(dest)\n\tif err != nil {\n\t\tlog.Println(\"Error check dest dir:\", err)\n\t\treturn err\n\t}\n\tif !is {\n\t\terr = errors.New(\"dest path is not dir\")\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\t// loop decompress src list files\n\tfor _, v := range src {\n\t\terr = filepath.Walk(v, func(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Error compress file:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// open the src file...\n\t\t\tdata, err := os.Open(path)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Error open file:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer data.Close()\n\t\t\t// apply one gzip reader to read file\n\t\t\tgr, err := gzip.NewReader(data)\n\t\t\tdefer gr.Close()\n\t\t\t// read the extend of file name\n\t\t\ttarget := routes.TrimSuffixSlash(dest) + \"/\" + routes.TrimSuffixPoint(info.Name()) + \".\" + string(gr.Extra)\n\t\t\t//...\n\t\t\t// create the dest tar file...\n\t\t\tfile, err := os.Create(target)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Error create file:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer file.Close()\n\t\t\t// read compress data into file\n\t\t\t_, err = io.Copy(file, gr)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Error read decompress data into file:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn err\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error compress file:\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}",
"func (m *Matrix) Decompress(bs []byte) error {\n\tcontent, err := cmp.DecompressBytes(bs)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.FromBytes(content)\n\treturn nil\n}",
"func UnzipImpl(reader *zip.Reader, dest string, verbose bool) error {\n for _, f := range reader.File {\n zipped, err := f.Open()\n if err != nil {\n return errors.New(\"unzip: Unable to open [\" + f.Name + \"]\")\n }\n\n defer zipped.Close()\n\n path := filepath.Join(dest, f.Name)\n if f.FileInfo().IsDir() {\n os.MkdirAll(path, f.Mode())\n if verbose {\n fmt.Println(\"Creating directory\", path)\n }\n } else {\n // Ensure we create the parent folder\n err := os.MkdirAll(filepath.Dir(path), os.ModePerm)\n if err != nil {\n return errors.New(\"unzip: Unable to create parent folder [\" + path + \"]\")\n }\n\n writer, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, f.Mode())\n if err != nil {\n return errors.New(\"unzip: Unable to create [\" + path + \"]\")\n }\n\n defer writer.Close()\n\n if _, err = io.Copy(writer, zipped); err != nil {\n return errors.New(\"unzip: Unable to create content in [\" + path + \"]\")\n }\n\n if verbose {\n fmt.Println(\"Decompressing : \", path)\n }\n }\n }\n return nil\n}",
"func (p *Pipeline) Decompress() error {\n\t// decompress the database pipeline data\n\tdata, err := decompress(p.Data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// overwrite compressed pipeline data with decompressed pipeline data\n\tp.Data = data\n\n\treturn nil\n}",
"func Unarchive(reader io.ReaderAt, readerSize int64, outFilePath string, progress ProgressFunc) (err error) {\n\tvar zipReader *zip.Reader\n\tvar j int\n\n\tzipReader, err = zip.NewReader(reader, readerSize)\n\tif err == nil {\n\t\tfor j = 0; j < len(zipReader.File) && err == nil; j++ {\n\t\t\terr = unarchiveFile(zipReader.File[j], outFilePath, progress)\n\t\t}\n\n\t}\n\treturn\n}",
"func (c *Compressor) Decompress(r io.Reader) (io.ReadCloser, error) {\n\tif dr, got := c.decompressors.Get().(*reader); got {\n\t\tif err := dr.reader.Reset(r); err != nil {\n\t\t\tc.decompressors.Put(r)\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn dr, nil\n\t}\n\n\tdr, err := gzip.NewReader(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &reader{\n\t\treader: dr,\n\t\tpool: &c.decompressors,\n\t}, nil\n}",
"func ungzip(path string, file io.Reader) {\n\tstream, err := gzip.NewReader(file)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer stream.Close()\n\tuntar(path, stream)\n}",
"func Decompress(src []byte) []byte {\n\n\tvar i, j, r, c int\n\tvar flags uint\n\n\tsrcBuf := bytes.NewBuffer(src)\n\tdst := bytes.Buffer{}\n\n\t// ring buffer of size n, with extra f-1 bytes to aid string comparison\n\ttextBuf := make([]byte, n+f-1)\n\n\tr = n - f\n\tflags = 0\n\n\tfor {\n\t\tflags = flags >> 1\n\t\tif ((flags) & 0x100) == 0 {\n\t\t\tbite, err := srcBuf.ReadByte()\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tc = int(bite)\n\t\t\tflags = uint(c | 0xFF00) /* uses higher byte cleverly to count eight*/\n\t\t}\n\t\tif flags&1 == 1 {\n\t\t\tbite, err := srcBuf.ReadByte()\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tc = int(bite)\n\t\t\tdst.WriteByte(byte(c))\n\t\t\ttextBuf[r] = byte(c)\n\t\t\tr++\n\t\t\tr &= (n - 1)\n\t\t} else {\n\t\t\tbite, err := srcBuf.ReadByte()\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ti = int(bite)\n\n\t\t\tbite, err = srcBuf.ReadByte()\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tj = int(bite)\n\n\t\t\ti |= ((j & 0xF0) << 4)\n\t\t\tj = (j & 0x0F) + threshold\n\t\t\tfor k := 0; k <= j; k++ {\n\t\t\t\tc = int(textBuf[(i+k)&(n-1)])\n\t\t\t\tdst.WriteByte(byte(c))\n\t\t\t\ttextBuf[r] = byte(c)\n\t\t\t\tr++\n\t\t\t\tr &= (n - 1)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dst.Bytes()\n}",
"func (comp *Compressor) Decompress() (string, error) {\n\tdictSize := 256\n\tdictionary := make(map[byte][]byte, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\tdictionary[byte(i)] = []byte{byte(i)}\n\t}\n\n\tvar result strings.Builder\n\tvar word []byte\n\tfor _, k := range comp.Yield {\n\t\tvar entry []byte\n\t\tif x, ok := dictionary[k]; ok {\n\t\t\tentry = x[:len(x):len(x)]\n\t\t} else if int(k) == dictSize && len(word) > 0 {\n\t\t\tentry = append(word, word[0])\n\t\t} else {\n\t\t\treturn result.String(), UnknownSymbolError(k)\n\t\t}\n\t\tresult.Write(entry)\n\n\t\tif len(word) > 0 {\n\t\t\tword = append(word, entry[0])\n\t\t\tdictionary[byte(dictSize)] = word\n\t\t\tdictSize++\n\t\t}\n\t\tword = entry\n\t}\n\treturn result.String(), nil\n}",
"func Uncompress(src string, dest string) (filenames []string, err error) {\n\tr, err := zip.OpenReader(src)\n\tif err != nil {\n\t\treturn filenames, err\n\t}\n\tdefer r.Close()\n\n\tfor _, f := range r.File {\n\t\t//Create anonymous function to avoid leaving too many files open\n\t\tcopyZipFile := func(f *zip.File) ([]string, error) {\n\t\t\trc, err := f.Open()\n\t\t\tif err != nil {\n\t\t\t\treturn filenames, err\n\t\t\t}\n\n\t\t\tdefer rc.Close()\n\n\t\t\t// Store filename/path for returning and using later on\n\t\t\tfpath := filepath.Join(dest, f.Name)\n\n\t\t\t// Check for ZipSlip exploit\n\t\t\tif !strings.HasPrefix(fpath, filepath.Clean(dest+string(os.PathSeparator))) {\n\t\t\t\treturn filenames, fmt.Errorf(\"%s: illegal file path\", fpath)\n\t\t\t}\n\n\t\t\tfilenames = append(filenames, fpath)\n\n\t\t\tif f.FileInfo().IsDir() {\n\t\t\t\t// Make Folder\n\t\t\t\terr = os.MkdirAll(fpath, os.ModePerm)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn filenames, err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {\n\t\t\t\t\treturn filenames, err\n\t\t\t\t}\n\t\t\t\tbody, err := ioutil.ReadAll(rc)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn filenames, err\n\t\t\t\t}\n\t\t\t\terr = ioutil.WriteFile(fpath, body, 0644)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn filenames, err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn filenames, nil\n\t\t}\n\n\t\tfilenames, err = copyZipFile(f)\n\t\tif err != nil {\n\t\t\treturn filenames, err\n\t\t}\n\t}\n\treturn filenames, nil\n}",
"func (r *Registry) Decompress(alg string, data []byte) ([]byte, error) {\n\t// resolve compression algorithm\n\talgorithm, err := r.resolveAlgorithm(alg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// decompress data using specified algorithm\n\tresult, err := algorithm.Decompress(data)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"decompression failed for alg[%s]: %s\", alg, err.Error())\n\t}\n\n\treturn result, nil\n}",
"func decompressBytes(input []byte) (output []byte, err error) {\n\tb := bytes.NewReader(input)\n\tvar r io.ReadCloser\n\n\tr, err = zlib.NewReader(b)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer r.Close()\n\n\tbuffer := new(bytes.Buffer)\n\t_, err = buffer.ReadFrom(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\toutput = buffer.Bytes()\n\treturn\n}",
"func decompressBytes(input []byte) (output []byte, err error) {\n\tb := bytes.NewReader(input)\n\tvar r io.ReadCloser\n\n\tr, err = zlib.NewReader(b)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer r.Close()\n\n\tbuffer := new(bytes.Buffer)\n\t_, err = buffer.ReadFrom(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\toutput = buffer.Bytes()\n\treturn\n}",
"func Uncompressed(to *tarOpts) {\n\treturn\n}",
"func Unpack(src string, dest string) (err error) {\n\t// first, open the file\n\tfile, err := os.Open(src)\n\tif err != nil {\n\t\tlog.Println(\"Error open file:\", err)\n\t\treturn err\n\t}\n\t// second, read file data\n\tbuf := make([]byte, 60)\n\trd := bufio.NewReader(file)\n\t_, err = rd.Read(buf)\n\tif err != nil {\n\t\tlog.Println(\"Error read file:\", err)\n\t\treturn err\n\t}\n\t// third, close the file\n\terr = file.Close()\n\tif err != nil {\n\t\tlog.Println(\"Error close file:\", err)\n\t\treturn err\n\t}\n\t// fourth, find the algorithm\n\tbuf = buf[48:56]\n\tindex := bytes.IndexByte(buf, 0)\n\ttp := string(buf[0:index])\n\tswitch tp {\n\tcase \"AES\", \"aes\":\n\t\terr = UnpackAES(src, dest)\n\tcase \"DES\", \"des\":\n\t\terr = UnpackDES(src, dest)\n\tcase \"3DES\", \"3des\":\n\t\terr = Unpack3DES(src, dest)\n\tcase \"RSA\", \"rsa\":\n\t\terr = UnpackRSA(src, dest)\n\tcase \"BASE64\", \"base64\":\n\t\terr = UnpackBase64(src, dest)\n\tdefault:\n\t\ts := fmt.Sprint(\"Undefined unpack algorithm.\")\n\t\terr = errors.New(s)\n\t}\n\treturn err\n}",
"func DecompressStream(compression Compression, out io.Writer, in io.Reader) (n int64, err error) {\n\treader, err := compression.DecompressReader(in)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer func() {\n\t\tif err == nil {\n\t\t\terr = reader.Close()\n\t\t}\n\t}()\n\treturn io.Copy(out, reader)\n}",
"func (t *Tar) Decompress(reader io.Reader) (directory files.Directory, e error) {\n\troot := files.NewRootDirectory()\n\n\tgzipReader, e := gzip.NewReader(reader)\n\tif e != nil {\n\t\treturn root, e\n\t}\n\n\ttarReader := tar.NewReader(gzipReader)\n\n\tvar foundError error\n\tfor {\n\t\theader, bufferReaderError := tarReader.Next()\n\t\tif bufferReaderError == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif bufferReaderError != nil {\n\t\t\tfoundError = bufferReaderError\n\t\t\tbreak\n\t\t}\n\n\t\tif header.Typeflag == tar.TypeDir {\n\t\t\troot.Directory(paths.Of(header.Name)).WithPermission(header.FileInfo().Mode())\n\t\t} else {\n\t\t\tif err := root.NewFile(paths.Of(header.Name)).WithPermission(header.FileInfo().Mode()).Write(tarReader); err != nil {\n\t\t\t\tfoundError = err\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := gzipReader.Close(); err != nil { // Close the gzip reader\n\t\treturn nil, err\n\t}\n\n\treturn root, foundError\n}",
"func UnGzipFile(src, dst string) error {\n\tsrcFile, err := gfile.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer srcFile.Close()\n\tdstFile, err := gfile.Create(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer dstFile.Close()\n\n\treader, err := gzip.NewReader(srcFile)\n\tif err != nil {\n\t\terr = gerror.Wrap(err, `gzip.NewReader failed`)\n\t\treturn err\n\t}\n\tdefer reader.Close()\n\n\tif _, err = io.Copy(dstFile, reader); err != nil {\n\t\terr = gerror.Wrap(err, `io.Copy failed`)\n\t\treturn err\n\t}\n\treturn nil\n}",
"func unzip(src string) error {\n r, err := zip.OpenReader(src)\n if err != nil {\n return err\n }\n defer func() {\n if err := r.Close(); err != nil {\n panic(err)\n }\n }()\n dest := filepath.Dir(src)\n\n // Closure to address file descriptors issue with all the deferred .Close() methods\n extractAndWriteFile := func(f *zip.File) error {\n rc, err := f.Open()\n if err != nil {\n return err\n }\n defer func() {\n if err := rc.Close(); err != nil {\n panic(err)\n }\n }()\n path := filepath.Join(dest, f.Name)\n\n if f.FileInfo().IsDir() {\n os.MkdirAll(path, f.Mode())\n } else {\n f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())\n if err != nil {\n return err\n }\n defer func() {\n if err := f.Close(); err != nil {\n panic(err)\n }\n }()\n _, err = io.Copy(f, rc)\n if err != nil {\n return err\n }\n }\n return nil\n }\n\n for _, f := range r.File {\n err := extractAndWriteFile(f)\n if err != nil {\n return err\n }\n }\n\n return nil\n}",
"func (s *segment) Compress() error {\n\tif s.gReader != nil {\n\t\treturn ErrImmutableSegment // segment is already compressed and is immutable\n\t}\n\ts.appender.Close()\n\tif s.gReader != nil {\n\t\ts.gReader.Close()\n\t}\n\tf, err := os.OpenFile(s.path+CompressedExt, os.O_CREATE|os.O_WRONLY, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgWriter := gzip.NewWriter(f)\n\t_, err = s.rFile.Seek(0, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(gWriter, s.rFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = gWriter.Flush()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgWriter.Close()\n\ts.rFile.Close()\n\ts.appender.Close()\n\treturn os.Remove(s.filename)\n}",
"func HandleDecompression(r *retryablehttp.Request, bodyOrig []byte) (bodyDec []byte, err error) {\n\tencodingHeader := strings.ToLower(r.Header.Get(\"Accept-Encoding\"))\n\tif encodingHeader == \"gzip\" {\n\t\tgzipreader, err := gzip.NewReader(bytes.NewReader(bodyOrig))\n\t\tif err != nil {\n\t\t\treturn bodyDec, err\n\t\t}\n\t\tdefer gzipreader.Close()\n\n\t\tbodyDec, err = ioutil.ReadAll(gzipreader)\n\t\tif err != nil {\n\t\t\treturn bodyDec, err\n\t\t}\n\n\t\treturn bodyDec, nil\n\t}\n\n\treturn bodyOrig, nil\n}",
"func UnpackToFile(src string, target string, dest string) (err error) {\n\t// first, open the file\n\tfile, err := os.Open(src)\n\tif err != nil {\n\t\tlog.Println(\"Error open file:\", err)\n\t\treturn err\n\t}\n\t// second, read file data\n\tbuf := make([]byte, 60)\n\trd := bufio.NewReader(file)\n\t_, err = rd.Read(buf)\n\tif err != nil {\n\t\tlog.Println(\"Error read file:\", err)\n\t\treturn err\n\t}\n\t// third, close the file\n\terr = file.Close()\n\tif err != nil {\n\t\tlog.Println(\"Error close file:\", err)\n\t\treturn err\n\t}\n\t// fourth, find the algorithm\n\tbuf = buf[48:56]\n\tindex := bytes.IndexByte(buf, 0)\n\ttp := string(buf[0:index])\n\tswitch tp {\n\tcase \"AES\", \"aes\":\n\t\terr = UnpackAESToFile(src, target, dest)\n\tcase \"DES\", \"des\":\n\t\terr = UnpackDESToFile(src, target, dest)\n\tcase \"3DES\", \"3des\":\n\t\terr = Unpack3DESToFile(src, target, dest)\n\tcase \"RSA\", \"rsa\":\n\t\terr = UnpackRSAToFile(src, target, dest)\n\tcase \"BASE64\", \"base64\":\n\t\terr = UnpackBase64ToFile(src, target, dest)\n\tdefault:\n\t\ts := fmt.Sprint(\"Undefined unpack algorithm.\")\n\t\terr = errors.New(s)\n\t}\n\treturn err\n}",
"func Decompress(b []byte) ([]byte, error) {\n\tdec := make([]byte, 0, len(b)) // estimate initial size\n\n\tfor len(b) > 0 {\n\t\tswitch b[0] {\n\t\tcase 254: // verbatim byte\n\t\t\tif len(b) < 2 {\n\t\t\t\treturn nil, ErrDecompression\n\t\t\t}\n\t\t\tdec = append(dec, b[1])\n\t\t\tb = b[2:]\n\t\tcase 255: // verbatim string\n\t\t\tif len(b) < 2 {\n\t\t\t\treturn nil, ErrDecompression\n\t\t\t}\n\t\t\tn := int(b[1])\n\t\t\tif len(b) < n+2 {\n\t\t\t\treturn nil, ErrDecompression\n\t\t\t}\n\t\t\tdec = append(dec, b[2:n+2]...)\n\t\t\tb = b[n+2:]\n\t\tdefault: // look up encoded value\n\t\t\tdec = append(dec, codes[int(b[0])]...)\n\t\t\tb = b[1:]\n\t\t}\n\t}\n\n\treturn dec, nil\n}",
"func Decompress(b AbstractBlob) AbstractBlob {\n\tif b==nil || !b.IsDirect() { return b }\n\t\n\tlzb,ok := b.(*BlobLz4Compressed)\n\tif !ok { return b }\n\t\n\tl := lzb.UCLen\n\tif l>0x7E000000 { return nil }\n\tbuf := make([]byte,l)\n\ti,e := lz4.UncompressBlock(lzb.Lz4Content,buf,0)\n\tif e!=nil { return nil }\n\tif i<l { buf = buf[:i] }\n\treturn &BlobDirect{buf}\n}",
"func UnpackToFileConfine(src string, target string, dest string) (err error) {\n\t// first, open the file\n\tfile, err := os.Open(src)\n\tif err != nil {\n\t\tlog.Println(\"Error open file:\", err)\n\t\treturn err\n\t}\n\t// second, read file data\n\tbuf := make([]byte, 60)\n\trd := bufio.NewReader(file)\n\t_, err = rd.Read(buf)\n\tif err != nil {\n\t\tlog.Println(\"Error read file:\", err)\n\t\treturn err\n\t}\n\t// third, close the file\n\terr = file.Close()\n\tif err != nil {\n\t\tlog.Println(\"Error close file:\", err)\n\t\treturn err\n\t}\n\t// fourth, find the algorithm\n\tbuf = buf[48:56]\n\tindex := bytes.IndexByte(buf, 0)\n\ttp := string(buf[0:index])\n\tswitch tp {\n\tcase \"AES\", \"aes\":\n\t\terr = UnpackAESToFileConfine(src, target, dest)\n\tcase \"DES\", \"des\":\n\t\terr = UnpackDESToFileConfine(src, target, dest)\n\tcase \"3DES\", \"3des\":\n\t\terr = Unpack3DESToFileConfine(src, target, dest)\n\tcase \"RSA\", \"rsa\":\n\t\terr = UnpackRSAToFileConfine(src, target, dest)\n\tcase \"BASE64\", \"base64\":\n\t\terr = UnpackBase64ToFileConfine(src, target, dest)\n\tdefault:\n\t\ts := fmt.Sprint(\"Undefined unpack algorithm.\")\n\t\terr = errors.New(s)\n\t}\n\treturn err\n}",
"func Unzip(from, to string) error {\n\tf, err := os.OpenFile(from, os.O_RDONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tstat, err := f.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn MUnzip(f, stat.Size(), to)\n}",
"func Compress(out, in []byte) (outSize int, err error) {\n\toutSize = int(C.LZ4_compress_limitedOutput(p(in), p(out), clen(in), clen(out)))\n\tif outSize == 0 {\n\t\terr = errors.New(\"Insufficient space for compression\")\n\t}\n\treturn\n}",
"func decompressByte(src []byte) []byte {\n\tcompressedData := bytes.NewBuffer(src)\n\tdeCompressedData := new(bytes.Buffer)\n\tdecompress(compressedData, deCompressedData)\n\treturn deCompressedData.Bytes()\n}",
"func processArchive(path string) {\r\n\text := filepath.Ext(path)\r\n\r\n\t// -o:outputpath\r\n\textractpath := strings.TrimSpace(path[:len(path)-len(ext)])\r\n\r\n\tcmd := exec.Command(zipApp, \"x\", \"-o:\"+extractpath, path)\r\n\r\n\texecErr := cmd.Run()\r\n\tif execErr != nil {\r\n\t\tpanic(execErr)\r\n\t}\r\n\r\n\tprocessDirectory(extractpath)\r\n\r\n\tos.RemoveAll(extractpath)\r\n}",
"func Decompress(compData []byte) ([]byte, error) {\n\tr := bytes.NewReader(compData)\n\n\theader := make([]byte, 16)\n\tn, err := r.Read(header)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if n != len(header) {\n\t\treturn nil, err\n\t}\n\n\t// Just return the data if it doesn't contain the cmp header.\n\tif !bytes.Equal(header, []byte(\"cmp\\x2020110113\\x20\\x20\\x20\\x00\")) {\n\t\treturn compData, nil\n\t}\n\n\tvar output []byte\n\tfor {\n\t\tb, err := r.ReadByte()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif b == 0 {\n\t\t\t// If it's a null byte, then the next byte is how many nulls to add.\n\t\t\tnullCount, err := r.ReadByte()\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t} else if err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\toutput = append(output, make([]byte, int(nullCount))...)\n\t\t} else {\n\t\t\toutput = append(output, b)\n\t\t}\n\t}\n\n\treturn output, nil\n}",
"func (cd *ContinueDecompress) Release() {\n\tif cd.lz4Stream != nil {\n\t\tC.LZ4_freeStreamDecode(cd.lz4Stream)\n\t\tcd.lz4Stream = nil\n\t}\n}",
"func (d *decompressor) Close() error {\n\tvar err error\n\tfor d.buf.Len() > 0 {\n\t\t_, err = d.writeUncompressed()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\td.closed = true\n\treturn nil\n}",
"func DecompressSnappyBlock(src []byte, dst []byte) error {\n\tdstLen := len(dst)\n\tresult, err := snappy.Decode(dst, src)\n\tif len(result) != dstLen {\n\t\tpanic(\"corrupted decodedLen in header\")\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func decompressLZ4(src io.Reader) io.Reader {\n\tpr, pw := io.Pipe()\n\tzr := lz4.NewReader(src)\n\tgo func() {\n\t\t_, err := zr.WriteTo(pw)\n\t\tpw.CloseWithError(err) // make sure the other side can see EOF or other errors\n\t}()\n\treturn pr\n\n}",
"func Unzip(src, dest string) error {\n\tr, err := zip.OpenReader(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Close()\n\n\tfor _, f := range r.File {\n\t\trc, err := f.Open()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer rc.Close()\n\n\t\tpath := filepath.Join(dest, f.Name)\n\t\tif f.FileInfo().IsDir() {\n\t\t\tos.MkdirAll(path, f.Mode())\n\t\t} else {\n\t\t\tf, err := os.OpenFile(\n\t\t\t\tpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer f.Close()\n\t\t\t// kopiert aus reader in writer\n\t\t\t_, err = io.Copy(f, rc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}",
"func UnpackAssets(gzByte []byte, projectName, rootPath, relativeDirNameInHatch string) error {\n\tif gzByte == nil || len(gzByte) == 0 {\n\t\treturn fmt.Errorf(\"gzByte must be a gz file content with base64 encoding\")\n\t}\n\n\tgzContent, err := base64.StdEncoding.DecodeString(string(gzByte))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode base64 error: %s\", err)\n\t}\n\n\tbuf := bytes.NewReader(gzContent)\n\terr = decompress(buf, projectName, rootPath, relativeDirNameInHatch)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decompress error: %s\", err)\n\t}\n\treturn nil\n}",
"func NewDecompressor(ct CompressionType, r io.ReadCloser) io.ReadCloser {\n\tif ct == NoCompression {\n\t\treturn r\n\t} else if ct == Snappy {\n\t\td := &Decompressor{\n\t\t\tur: r,\n\t\t\trc: snappy.NewReader(r),\n\t\t\tct: ct,\n\t\t}\n\t\treturn d\n\t} else {\n\t\tpanic(\"unknown compression type\")\n\t}\n}",
"func UnzipFLate(buf []byte) (data []byte, err error) {\n\tr := flate.NewReader(bytes.NewBuffer(buf))\n\tdefer r.Close()\n\treturn ioutil.ReadAll(r)\n}",
"func UnzipFile(zipfile string, dest string, verbose bool) error {\n reader, err := zip.OpenReader(zipfile)\n if err != nil {\n return errors.New(\"unzip: Unable to open [\" + zipfile + \"]\")\n }\n defer reader.Close()\n return UnzipImpl(&reader.Reader, dest, verbose)\n}",
"func ZstdDecompress(in io.Reader, out io.Writer, opts ...zstd.DOption) error {\n\tdec, err := NewZstdDecompressor(in, opts...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer dec.Close()\n\n\tif err = dec.Decompress(out); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func (g *GRPC) decompressHandler(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\tif contentEncoding := r.Header.Get(\"Content-Encoding\"); contentEncoding != \"\" {\n\t\t\t\tdecompressorFn, ok := g.restDecompressors[contentEncoding]\n\t\t\t\tif !ok {\n\t\t\t\t\thttp.Error(w, fmt.Sprintf(\"request content-encoding=%s, server does not support this\", contentEncoding), http.StatusPreconditionFailed)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\treader, err := decompressorFn(r.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.Error(w, fmt.Sprintf(\"problem with decompressor(%s): %s\", contentEncoding, err), http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tr.Body = ioutil.NopCloser(reader)\n\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t}\n\t\t},\n\t)\n}",
"func untargz(src io.Reader, dst string) error {\n\t// ungzip\n\tzr, err := gzip.NewReader(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// untar\n\ttr := tar.NewReader(zr)\n\n\t// uncompress each element\n\tfor {\n\t\theader, err := tr.Next()\n\t\tif err == io.EOF {\n\t\t\tbreak // end of archiver\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// validate name against path traversal\n\t\tif !validRelPath(header.Name) {\n\t\t\treturn fmt.Errorf(\"tar contained invalid name error %q\", header.Name)\n\t\t}\n\n\t\t// add dst + re-format slashes according to system\n\t\ttarget := filepath.Join(dst, header.Name)\n\t\t// if no join is needed, replace with ToSlash:\n\t\t// target = filepath.ToSlash(header.Name)\n\n\t\t// check the type\n\t\tswitch header.Typeflag {\n\n\t\t// if its a dir and it doesn't exist create it (with 0755 permission)\n\t\tcase tar.TypeDir:\n\t\t\tif _, err := os.Stat(target); err != nil {\n\t\t\t\tif err := os.MkdirAll(target, 0755); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t// if it's a file create it (with same permission)\n\t\tcase tar.TypeReg:\n\t\t\tfileToWrite, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// copy over contents\n\t\t\tif _, err := io.Copy(fileToWrite, tr); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// manually close here after each file operation; deferring would cause each file close\n\t\t\t// to wait until all operations have completed.\n\n\t\t\tif err := fileToWrite.Close(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}",
"func Decompress(compressed *vector.Vector) (*vector.Vector, error) {\n\tif compressed.Size() == 0 {\n\t\treturn compressed, nil\n\t}\n\n\tlastByteInBits := int(compressed.MustGet(0).(byte))\n\n\tprefixTree, nextIndex := decompressPrefixTree(compressed, 1)\n\tdecompressed := vector.New()\n\n\tcodes := decompressHuffmanCodes(compressed, nextIndex, lastByteInBits)\n\n\tvar err error\n\tnextIndex = 0\n\n\tfor nextIndex < codes.Size() {\n\t\tnextIndex, err = decodeHuffmanCode(codes, nextIndex, prefixTree, decompressed)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn decompressed, nil\n}",
"func Compress(file *os.File, outputName string) {\n\t// gerar a arvore a partir da frequencia dos caracteres do texto\n\troot := Harvest(GetMap(file))\n\n\t// gerar dicionario\n\tdict := make(map[string]string)\n\n\tif root.IsLeaf() {\n\t\tdict[root.Value] = \"0\"\n\t} else {\n\t\tcreateDict(root, dict, \"\")\n\t}\n\n\t//Resetar cursor\n\tfile.Seek(0, 0)\n\t//Escrever Árvore\n\toutputFile, _ := os.Create(outputName)\n\twriter := bit.NewWriter(outputFile)\n\twriteNode(root, writer)\n\n\t// Codificar\n\n\twriteCodified(file, dict, writer)\n}",
"func unarch(afile, target string) error {\n\tlog.WithFields(log.Fields{\"func\": \"restore.unarch\"}).Debug(fmt.Sprintf(\"Unpacking %s into %s\", afile, target))\n\terr := zip.UnarchiveFile(afile, target, func(apath string) {\n\t\tlog.WithFields(log.Fields{\"func\": \"restore.unarch\"}).Debug(fmt.Sprintf(\"%s\", apath))\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Can't unpack archive: %s\", err)\n\t}\n\treturn nil\n}",
"func UnpackConfine(src string, dest string) (err error) {\n\t// first, open the file\n\tfile, err := os.Open(src)\n\tif err != nil {\n\t\tlog.Println(\"Error open file:\", err)\n\t\treturn err\n\t}\n\t// second, read file data\n\tbuf := make([]byte, 60)\n\trd := bufio.NewReader(file)\n\t_, err = rd.Read(buf)\n\tif err != nil {\n\t\tlog.Println(\"Error read file:\", err)\n\t\treturn err\n\t}\n\t// third, close the file\n\terr = file.Close()\n\tif err != nil {\n\t\tlog.Println(\"Error close file:\", err)\n\t\treturn err\n\t}\n\t// fourth, find the algorithm\n\tbuf = buf[48:56]\n\tindex := bytes.IndexByte(buf, 0)\n\ttp := string(buf[0:index])\n\tswitch tp {\n\tcase \"AES\", \"aes\":\n\t\terr = UnpackAESConfine(src, dest)\n\tcase \"DES\", \"des\":\n\t\terr = UnpackDESConfine(src, dest)\n\tcase \"3DES\", \"3des\":\n\t\terr = Unpack3DESConfine(src, dest)\n\tcase \"RSA\", \"rsa\":\n\t\terr = UnpackRSAConfine(src, dest)\n\tcase \"BASE64\", \"base64\":\n\t\terr = UnpackBase64Confine(src, dest)\n\tdefault:\n\t\ts := fmt.Sprint(\"Undefined unpack algorithm.\")\n\t\terr = errors.New(s)\n\t}\n\treturn err\n}",
"func (c *Compressor) Decompress(b []byte) (image.Image, error) {\n\tr := bytes.NewBuffer(b)\n\n\tvar width, height uint32\n\tif err := binary.Read(r, encodingEndian, &width); err != nil {\n\t\treturn nil, errors.New(\"failed to read width field: \" + err.Error())\n\t}\n\tif err := binary.Read(r, encodingEndian, &height); err != nil {\n\t\treturn nil, errors.New(\"failed to read height field: \" + err.Error())\n\t}\n\n\texpander, err := readPCAExpander(r)\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed to read PCA expander: \" + err.Error())\n\t} else if len(expander.basis[0]) != c.blockSize*c.blockSize {\n\t\treturn nil, errors.New(\"block size mismatch\")\n\t}\n\n\tvar minValue, maxValue float64\n\tif err := binary.Read(r, encodingEndian, &minValue); err != nil {\n\t\treturn nil, errors.New(\"failed to read min value: \" + err.Error())\n\t}\n\tif err := binary.Read(r, encodingEndian, &maxValue); err != nil {\n\t\treturn nil, errors.New(\"failed to read max value: \" + err.Error())\n\t}\n\n\trect := image.Rect(0, 0, int(width), int(height))\n\tblockCount := blocker.Count(rect, c.blockSize)\n\timageBlocks := make([]linalg.Vector, blockCount)\n\tfor i := range imageBlocks {\n\t\treducedBlock := make(linalg.Vector, len(expander.basis))\n\t\tfor j := range reducedBlock {\n\t\t\tif val, err := r.ReadByte(); err != nil {\n\t\t\t\treturn nil, errors.New(\"failed to read data: \" + err.Error())\n\t\t\t} else {\n\t\t\t\tnum := ((float64(val) / 255.0) * (maxValue - minValue)) + minValue\n\t\t\t\treducedBlock[j] = num\n\t\t\t}\n\t\t}\n\t\timageBlocks[i] = expander.Expand(reducedBlock)\n\t}\n\n\treturn blocker.Image(rect.Dx(), rect.Dy(), imageBlocks, c.blockSize), nil\n}",
"func DecryptFile(inFile, outFile string, conf *model.Configuration) (err error) {\n\tif conf == nil {\n\t\treturn errors.New(\"pdfcpu: missing configuration for decryption\")\n\t}\n\tconf.Cmd = model.DECRYPT\n\n\tvar f1, f2 *os.File\n\n\tif f1, err = os.Open(inFile); err != nil {\n\t\treturn err\n\t}\n\n\ttmpFile := inFile + \".tmp\"\n\tif outFile != \"\" && inFile != outFile {\n\t\ttmpFile = outFile\n\t\tlog.CLI.Printf(\"writing %s...\\n\", outFile)\n\t} else {\n\t\tlog.CLI.Printf(\"writing %s...\\n\", inFile)\n\t}\n\n\tif f2, err = os.Create(tmpFile); err != nil {\n\t\tf1.Close()\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tf2.Close()\n\t\t\tf1.Close()\n\t\t\tif outFile == \"\" || inFile == outFile {\n\t\t\t\tos.Remove(tmpFile)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif err = f2.Close(); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif err = f1.Close(); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif outFile == \"\" || inFile == outFile {\n\t\t\terr = os.Rename(tmpFile, inFile)\n\t\t}\n\t}()\n\n\treturn Decrypt(f1, f2, conf)\n}",
"func UnzipAndUntar(dst string, r io.Reader) error {\n\n // gzr, err := gzip.NewReader(r)\n // defer gzr.Close()\n // if err != nil {\n // return err\n // }\n\n tr := tar.NewReader(r)\n\n for {\n header, err := tr.Next()\n\n switch {\n\n // if no more files are found return\n case err == io.EOF:\n return nil\n\n // return any other error\n case err != nil:\n return err\n\n // if the header is nil, just skip it (not sure how this happens)\n case header == nil:\n continue\n }\n\n // the target location where the dir/file should be created\n\n target := filepath.Join(dst, header.Name)\n\n // the following switch could also be done using fi.Mode(), not sure if there\n // a benefit of using one vs. the other.\n // fi := header.FileInfo()\n\n // check the file type\n switch header.Typeflag {\n\n // if its a dir and it doesn't exist create it\n case tar.TypeDir:\n if _, err := os.Stat(target); err != nil {\n if err := os.MkdirAll(target, 0755); err != nil {\n return err\n }\n }\n\n // if it's a file create it\n case tar.TypeReg:\n // create dirs below if non existing\n if err := os.MkdirAll(filepath.Dir(target), 0755); err != nil {\n return err\n }\n\n f, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))\n if err != nil {\n return err\n }\n defer f.Close()\n\n // copy over contents\n if _, err := io.Copy(f, tr); err != nil {\n return err\n }\n }\n }\n}",
"func Unzip(src, dest string) (err error) {\n\tdest = filepath.Clean(dest) + string(os.PathSeparator)\n\n\tr, err := zip.OpenReader(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fs.CheckClose(r, &err)\n\n\tif err := file.MkdirAll(dest, 0755); err != nil {\n\t\treturn err\n\t}\n\n\t// Closure to address file descriptors issue with all the deferred .Close() methods\n\textractAndWriteFile := func(f *zip.File) error {\n\t\tpath := filepath.Join(dest, f.Name)\n\t\t// Check for Zip Slip: https://github.com/rclone/rclone/issues/3529\n\t\tif !strings.HasPrefix(path, dest) {\n\t\t\treturn fmt.Errorf(\"%s: illegal file path\", path)\n\t\t}\n\n\t\trc, err := f.Open()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer fs.CheckClose(rc, &err)\n\n\t\tif f.FileInfo().IsDir() {\n\t\t\tif err := file.MkdirAll(path, 0755); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tif err := file.MkdirAll(filepath.Dir(path), 0755); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tf, err := file.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer fs.CheckClose(f, &err)\n\n\t\t\t_, err = io.Copy(f, rc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\tfor _, f := range r.File {\n\t\terr := extractAndWriteFile(f)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (f *Fs) putUncompress(in io.Reader, src fs.ObjectInfo, options []fs.OpenOption, put putFn, mimeType string, verifyCompressedObject bool) (fs.Object, *ObjectMetadata, error) {\n\t// Unwrap the accounting, add our metadata hasher, then wrap it back on\n\tin, wrap := accounting.UnWrap(in)\n\tmetaHasher := md5.New()\n\tin = io.TeeReader(in, metaHasher)\n\twrappedIn := wrap(in)\n\t// If verifyCompressedObject is on, find a hash the destination supports to compute a hash of\n\t// the compressed data.\n\tht := f.Fs.Hashes().GetOne()\n\tvar hasher *hash.MultiHasher\n\tvar err error\n\tif ht != hash.None && verifyCompressedObject {\n\t\t// unwrap the accounting again\n\t\twrappedIn, wrap = accounting.UnWrap(wrappedIn)\n\t\thasher, err = hash.NewMultiHasherTypes(hash.NewHashSet(ht))\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\t// add the hasher and re-wrap the accounting\n\t\twrappedIn = io.TeeReader(wrappedIn, hasher)\n\t\twrappedIn = wrap(wrappedIn)\n\t}\n\t// Put the object\n\to, err := put(wrappedIn, f.renameObjectInfo(src, f.c.generateDataName(src.Remote(), src.Size(), false), src.Size()), options...)\n\t//o, err := operations.Rcat(f, f.c.generateDataName(src.Remote(), src.Size(), false), wrappedIn, src.ModTime())\n\tif err != nil {\n\t\tif o != nil {\n\t\t\tremoveErr := o.Remove()\n\t\t\tif removeErr != nil {\n\t\t\t\tfs.Errorf(o, \"Failed to remove partially transferred object: %v\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil, nil, err\n\t}\n\t// Check the hashes of the compressed data if we were comparing them\n\tif ht != hash.None && hasher != nil {\n\t\terr := f.verifyObjectHash(o, hasher, ht)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\t// Return our object and metadata\n\treturn o, newMetadata(o.Size(), Uncompressed, []uint32{}, metaHasher.Sum([]byte{}), mimeType), nil\n}",
"func (cpk *CompressedPublicKey) Uncompress() (*PublicKey, error) {\n\t// Should only execute the decompression branch of ParsePublicKey\n\tpk_s, err := btcec.ParsePubKey(cpk[:], S256)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newPublicKeyCoords(pk_s.X, pk_s.Y), nil\n}",
"func Untargzip(path string, r io.Reader) error {\n\tungzipped, err := gzip.NewReader(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttarball := tar.NewReader(ungzipped)\n\n\tdefer ungzipped.Close()\n\n\t// We have to treat things differently for git-archives\n\tisGitArchive := false\n\n\t// Alright, things seem in order, let's make the base directory\n\tos.MkdirAll(path, 0755)\n\tfor {\n\t\thdr, err := tarball.Next()\n\t\tif err == io.EOF {\n\t\t\t// finished the tar\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Skip the base dir\n\t\tif hdr.Name == \"./\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t// If this was made with git-archive it will be in kinda an ugly\n\t\t// format, but we can identify it by the pax_global_header \"file\"\n\t\tname := hdr.Name\n\t\tif name == \"pax_global_header\" {\n\t\t\tisGitArchive = true\n\t\t\tcontinue\n\t\t}\n\n\t\t// It will also contain an extra subdir that we will automatically strip\n\t\tif isGitArchive {\n\t\t\tparts := strings.Split(name, \"/\")\n\t\t\tname = strings.Join(parts[1:], \"/\")\n\t\t}\n\n\t\tfpath := filepath.Join(path, name)\n\t\tif hdr.FileInfo().IsDir() {\n\t\t\terr = os.MkdirAll(fpath, 0755)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tfile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE, hdr.FileInfo().Mode())\n\t\tdefer file.Close()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = io.Copy(file, tarball)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfile.Close()\n\t}\n\treturn nil\n}",
"func compress(file_path string) error {\n\n\tfile, err := os.Open(file_path)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer file.Close()\n\n\tnewFile, err := os.Create(file_path + \".gz\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer newFile.Close()\n\n\tgzipOut := gzip.NewWriter(newFile)\n\n\t_, err = io.Copy(newFile, file)\n\n\tgzipOut.Close()\n\n\treturn err\n\n}",
"func UnTarIt(src string, dst string) error {\n\tsrcFile, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = os.MkdirAll(dst, 0755); err != nil {\n\t\treturn err\n\t}\n\tgzr, err := gzip.NewReader(srcFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer gzr.Close()\n\ttr := tar.NewReader(gzr)\n\tfor {\n\t\theader, err := tr.Next()\n\t\tif err != nil {\n\t\t\tif err == io.EOF { // no more files\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tif err = unTarEntry(dst, tr, header); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}",
"func desz(src []byte, dst interface{}) error {\n\tdec := gob.NewDecoder(bytes.NewBuffer(src))\n\tif err := dec.Decode(dst); err != nil {\n\t\treturn errors.New(\"DESZ FAILED!\")\n\t}\n\treturn nil\n}",
"func Unzip(src []byte, dest string) error {\n\tr := openZip(src)\n\tos.MkdirAll(dest, 0755)\n\t// Closure to address file descriptors issue with all the deferred .Close() methods\n\textractAndWriteFile := func(f *zip.File) error {\n\n\t\tpath := filepath.Join(dest, f.Name)\n\t\tisLink := f.FileInfo().Mode()&os.ModeSymlink == os.ModeSymlink\n\n\t\t// dir\n\t\tif f.FileInfo().IsDir() && !isLink {\n\t\t\treturn os.MkdirAll(path, f.Mode())\n\t\t}\n\n\t\t// open file\n\t\trc, err := f.Open()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer rc.Close()\n\n\t\t// link\n\t\tif isLink {\n\t\t\tbuf, err := ioutil.ReadAll(rc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn os.Symlink(string(buf), path)\n\t\t}\n\n\t\t// file\n\t\t// eventually create a missing ddir\n\t\terr = os.MkdirAll(filepath.Dir(path), 0755)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\t_, err = io.Copy(file, rc)\n\t\treturn err\n\t}\n\tfor _, f := range r.File {\n\t\terr := extractAndWriteFile(f)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n\treturn nil\n}",
"func DecodeByPath(archivePath, csvFilename string, dst interface{}) error {\n\tgzFile, err := os.Open(archivePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\t_ = gzFile.Close()\n\t}()\n\n\tif err := DecodeFromFile(gzFile, csvFilename, dst); err != nil {\n\t\treturn err\n\t}\n\n\treturn gzFile.Close()\n}",
"func (cd *ContinueDecompress) Process(dst, src []byte) (int, error) {\n\tif len(src) == 0 {\n\t\treturn 0, ErrNoData\n\t}\n\tif cd.offset < 0 || cd.offset >= cd.dictionarySize {\n\t\treturn 0, ErrInternal\n\t}\n\n\t// Decompress to ringbuffer, then copy to dst\n\tvar result C.int\n\tif dstLen := len(dst); dstLen > 0 {\n\t\tif dstLen > cd.maxMessageSize {\n\t\t\tdstLen = cd.maxMessageSize\n\t\t}\n\t\tresult = C.LZ4_decompress_safe_continue_and_memcpy(\n\t\t\tcd.lz4Stream,\n\t\t\t(*C.char)(unsafe.Pointer(&src[0])),\n\t\t\tC.int(len(src)),\n\t\t\t(*C.char)(unsafe.Pointer(&cd.ringBuffer[cd.offset])),\n\t\t\tC.int(dstLen),\n\t\t\t(*C.char)(unsafe.Pointer(&dst[0])))\n\t}\n\tif result <= 0 {\n\t\treturn 0, ErrDecompress\n\t}\n\n\t// Update stats\n\tcd.processTimes++\n\tcd.totalSrcLen += int64(len(src))\n\tcd.totalDecompressedLen += int64(result)\n\n\t// Add and wraparound the ringbuffer offset\n\tcd.offset += int(result)\n\tif cd.offset >= cd.dictionarySize {\n\t\tcd.offset = 0\n\t}\n\n\treturn int(result), nil\n}",
"func Unzip(src, dest string) error {\n\tr, err := zip.OpenReader(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Close()\n\n\tfor _, f := range r.File {\n\t\trc, err := f.Open()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer rc.Close()\n\n\t\tfpath := filepath.Join(dest, f.Name)\n\t\tif f.FileInfo().IsDir() {\n\t\t\tos.MkdirAll(fpath, f.Mode())\n\t\t} else {\n\t\t\tvar fdir string\n\t\t\tif lastIndex := strings.LastIndex(fpath, string(os.PathSeparator)); lastIndex > -1 {\n\t\t\t\tfdir = fpath[:lastIndex]\n\t\t\t}\n\n\t\t\terr = os.MkdirAll(fdir, f.Mode())\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tf, err := os.OpenFile(\n\t\t\t\tfpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer f.Close()\n\n\t\t\t_, err = io.Copy(f, rc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}",
"func (dc *Decompressor) Close() error {\n\tif dc.ct == NoCompression {\n\t\tpanic(\"no suppose to reach here\")\n\t} else if dc.ct == Snappy {\n\t\treturn dc.ur.Close()\n\t} else {\n\t\tpanic(\"unknown compression type\")\n\t}\n}",
"func (m *Matrix) LoadUnCompressed(path string) error {\n\tdat, err2 := ioutil.ReadFile(path)\n\tif err2 != nil {\n\t\treturn err2\n\t}\n\tm.FromBytes(dat)\n\treturn nil\n}",
"func (Export) CompressGZIP(in []byte) (out []byte) {\n\t// RFC 1952, section 2.3.1.\n\tvar gzipHeader = [10]byte{0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff}\n\n\t// RFC 1951, section 3.2.4.\n\tvar blockHeader [5]byte\n\tconst maxBlockSize = math.MaxUint16\n\tnumBlocks := 1 + len(in)/maxBlockSize\n\n\t// RFC 1952, section 2.3.1.\n\tvar gzipFooter [8]byte\n\tbinary.LittleEndian.PutUint32(gzipFooter[0:4], crc32.ChecksumIEEE(in))\n\tbinary.LittleEndian.PutUint32(gzipFooter[4:8], uint32(len(in)))\n\n\t// Encode the input without compression using raw DEFLATE blocks.\n\tout = make([]byte, 0, len(gzipHeader)+len(blockHeader)*numBlocks+len(in)+len(gzipFooter))\n\tout = append(out, gzipHeader[:]...)\n\tfor blockHeader[0] == 0 {\n\t\tblockSize := maxBlockSize\n\t\tif blockSize > len(in) {\n\t\t\tblockHeader[0] = 0x01 // final bit per RFC 1951, section 3.2.3.\n\t\t\tblockSize = len(in)\n\t\t}\n\t\tbinary.LittleEndian.PutUint16(blockHeader[1:3], uint16(blockSize))\n\t\tbinary.LittleEndian.PutUint16(blockHeader[3:5], ^uint16(blockSize))\n\t\tout = append(out, blockHeader[:]...)\n\t\tout = append(out, in[:blockSize]...)\n\t\tin = in[blockSize:]\n\t}\n\tout = append(out, gzipFooter[:]...)\n\treturn out\n}",
"func Unzip(src, dest string) error {\n\tr, err := zip.OpenReader(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\tif err := r.Close(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\tos.MkdirAll(dest, 0755)\n\n\t// Closure to address file descriptors issue with all the deferred .Close() methods\n\textractAndWriteFile := func(f *zip.File) error {\n\t\trc, err := f.Open()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer func() {\n\t\t\tif err := rc.Close(); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}()\n\n\t\tthePath := filepath.Join(dest, f.Name)\n\n\t\tif f.FileInfo().IsDir() {\n\t\t\tos.MkdirAll(thePath, f.Mode())\n\t\t} else {\n\t\t\tos.MkdirAll(filepath.Dir(thePath), f.Mode())\n\t\t\tf, err := os.OpenFile(thePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tdefer func() {\n\t\t\t\tif err := f.Close(); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\t_, err = io.Copy(f, rc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tfor _, f := range r.File {\n\t\terr := extractAndWriteFile(f)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (m *Matrix) SaveUnCompressed(path string) error {\n\treturn ioutil.WriteFile(path, m.ToBytes(), 0644)\n}",
"func DecryptFile(in, out string, key []byte) (err error) {\n\tinFile, err := os.Open(in)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer inFile.Close()\n\n\toutFile, err := os.OpenFile(out, os.O_WRONLY|os.O_CREATE|os.O_TRUNC,\n\t\t0600)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer outFile.Close()\n\n\terr = DecryptReader(key, inFile, outFile)\n\treturn\n}",
"func UntarUncompressed(tarArchive io.Reader, dest string, options *archive.TarOptions) error {\n\treturn untarHandler(tarArchive, dest, options, false, dest)\n}",
"func UncompressBytes(data []byte) []byte {\n\treadCloser, err := zlib.NewReader(bytes.NewReader(data))\n\tif err != nil {\n\t\tmod.Error(\"UncompressBytes:\", err)\n\t\treturn []byte{}\n\t}\n\tret := bytes.NewBuffer(make([]byte, 0, 8192))\n\tio.Copy(ret, readCloser)\n\treadCloser.Close()\n\treturn ret.Bytes()\n}",
"func (c *Composition) Decompose(dir string) (output string, err error) {\n\tvar outputBytes []byte\n\n\t_, err = c.issueCommand([]string{\"stop\"}, dir)\n\tif err != nil {\n\t\tlogger.Fatalf(err.Error())\n\t}\n\n\toutputBytes, err = c.issueCommand([]string{\"rm\", \"-f\"}, dir)\n\t// Now remove associated chaincode containers if any\n\tcontainerErr := c.DockerHelper.RemoveContainersWithNamePrefix(c.ProjectName)\n\n\tif containerErr != nil {\n\t\tlogger.Fatalf(containerErr.Error())\n\t}\n\n\treturn string(outputBytes), err\n}",
"func Decompress(data []byte) ([]byte, error) {\n\t// Start off assuming that decompressing a buffer makes the result\n\t// larger. This is mostly but not always true.\n\tret := make([]byte, 0, len(data)*2)\n\tfor o := 0; o < len(data); o++ {\n\t\tb := data[o]\n\t\tswitch {\n\t\tcase b == 0:\n\t\t\tret = append(ret, b)\n\t\tcase (b >= 1 && b <= 8):\n\t\t\tif o+int(b)+1 > len(data) {\n\t\t\t\treturn nil, fmt.Errorf(\"copy from past end of block: %v/%v\", len(data), o+int(b)+1)\n\t\t\t}\n\t\t\td := data[o+1 : o+int(b)+1]\n\t\t\tret = append(ret, d...)\n\t\t\to += int(b)\n\t\tcase (b >= 0x09 && b <= 0x7f):\n\t\t\tret = append(ret, b)\n\t\tcase b >= 0x80 && b <= 0xbf:\n\t\t\to++\n\t\t\tm := int(b)<<8 + int(data[o])\n\t\t\tdist := (m & 0x3fff) >> 3\n\t\t\tl := m&0x07 + 3\n\t\t\tif dist > len(ret) {\n\t\t\t\tlog.Fatalf(\"dist %v, len %v but len(ret) only %v (%x)\", dist, l, len(ret), m)\n\t\t\t}\n\t\t\tif dist < 1 {\n\t\t\t\tlog.Printf(\"dist %v is less than 1\", dist)\n\t\t\t\tdist = 1\n\t\t\t}\n\t\t\tsl := len(ret)\n\t\t\tfor i := 0; i < l; i++ {\n\t\t\t\tidx := (len(ret) - dist)\n\t\t\t\tif idx < 0 || idx >= len(ret) {\n\t\t\t\t\tlog.Printf(\"Out of range; started %v, off %v, len %v, curidx %v, curlen %v\", sl, dist, l, idx, len(ret))\n\t\t\t\t}\n\t\t\t\tsb := ret[idx]\n\t\t\t\tret = append(ret, sb)\n\t\t\t}\n\t\tcase b >= 0xc0:\n\t\t\tret = append(ret, ' ')\n\t\t\tret = append(ret, b^0x80)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"unknown byte %v\", b)\n\t\t}\n\n\t}\n\n\treturn ret, nil\n}"
] | [
"0.7095708",
"0.67740107",
"0.65838283",
"0.64039356",
"0.6301482",
"0.6252142",
"0.60783213",
"0.6070446",
"0.59905404",
"0.59894836",
"0.59650695",
"0.5957409",
"0.59405726",
"0.5851418",
"0.57854205",
"0.5725998",
"0.57241064",
"0.5715861",
"0.5655431",
"0.56361043",
"0.5623391",
"0.56201",
"0.55701786",
"0.5560715",
"0.55221057",
"0.5520064",
"0.5482557",
"0.5454707",
"0.5424246",
"0.5409221",
"0.53904766",
"0.5359531",
"0.53490406",
"0.53229487",
"0.5267511",
"0.52545536",
"0.5248388",
"0.5244814",
"0.52394044",
"0.5189245",
"0.5138309",
"0.51231354",
"0.51231354",
"0.5118709",
"0.5115074",
"0.50958025",
"0.5089599",
"0.5083265",
"0.5075534",
"0.50631255",
"0.5056117",
"0.5048615",
"0.50270146",
"0.5020094",
"0.50160736",
"0.498013",
"0.49706623",
"0.49617085",
"0.4956263",
"0.49296135",
"0.49150968",
"0.49124625",
"0.49101892",
"0.48769492",
"0.48766845",
"0.48720783",
"0.4862217",
"0.48568618",
"0.48563513",
"0.48523593",
"0.48426348",
"0.48378253",
"0.48365992",
"0.4827093",
"0.48266694",
"0.482184",
"0.480452",
"0.4786639",
"0.47829872",
"0.47828686",
"0.47761974",
"0.47570363",
"0.4754495",
"0.47282752",
"0.47113648",
"0.47065145",
"0.46917927",
"0.4691547",
"0.4690315",
"0.467368",
"0.4669021",
"0.46654862",
"0.46633443",
"0.46422967",
"0.46338376",
"0.4631217",
"0.46252042",
"0.4612801",
"0.45972908",
"0.45844102"
] | 0.777666 | 0 |
NewEventHandler creates new event handler | func NewEventHandler(notifier notifier.Notifier) *EventHandler {
return &EventHandler{
notifier: notifier,
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func NewEventHandler(app *application, evt *v1.Event) EventHandler {\n\tkey := registryKey{APIVersion: evt.InvolvedObject.APIVersion, Kind: evt.InvolvedObject.Kind}\n\tfactory := handlerRegistry[key]\n\tif factory != nil {\n\t\tif handler := factory(app, evt); handler != nil {\n\t\t\treturn handler\n\t\t}\n\t}\n\treturn NewDefaultEventHandler(app, evt)\n}",
"func newEventHandler(fn interface{}, configurators []EventConfigurator) *eventHandler {\n\te := &eventHandler{\n\t\tcallBack: reflect.ValueOf(fn),\n\t\tMutex: sync.Mutex{},\n\t}\n\t// config\n\tfor i := range configurators {\n\t\tconfigurators[i](e)\n\t}\n\treturn e\n}",
"func NewEventHandler(kind string, queue workqueue.Interface) cache.ResourceEventHandler {\n\thandler := cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tlogAndQueue(\"Add\", kind, queue, obj, nil)\n\t\t},\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\tlogAndQueue(\"Update\", kind, queue, new, old)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tlogAndQueue(\"Delete\", kind, queue, obj, nil)\n\t\t},\n\t}\n\treturn handler\n}",
"func NewEventHandler(region, lbID string, lbClient cloud.LoadBalance, k8sCli client.Client) *EventHandler {\n\treturn &EventHandler{\n\t\tctx: context.Background(),\n\t\tlbID: lbID,\n\t\tregion: region,\n\t\tlbClient: lbClient,\n\t\tk8sCli: k8sCli,\n\t\teventRecvCache: NewEventCache(),\n\t\teventDoingCache: NewEventCache(),\n\t}\n}",
"func NewEventHandler(handlerType string) *EventHandler {\n\treturn &EventHandler{\n\t\tType: handlerType,\n\t\tEvents: []goevent.Event{},\n\t\tRecv: make(chan goevent.Event, 10),\n\t}\n}",
"func NewEventHandler(ctx context.Context, clientFactory keptn.ClientFactoryInterface, eventSenderClient keptn.EventSenderClientInterface, event cloudevents.Event) (DynatraceEventHandler, error) {\n\teventHandler, err := getEventHandler(ctx, eventSenderClient, event, clientFactory)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Cannot handle event\")\n\t\treturn NewErrorHandler(fmt.Errorf(\"cannot handle event: %w\", err), event, eventSenderClient, clientFactory.CreateUniformClient()), nil\n\t}\n\n\treturn eventHandler, nil\n}",
"func NewEventHandler(ctx context.Context, queue workqueue.RateLimitingInterface, handler handler.EventHandler, predicates []predicate.Predicate) *EventHandler {\n\treturn &EventHandler{\n\t\tctx: ctx,\n\t\thandler: handler,\n\t\tqueue: queue,\n\t\tpredicates: predicates,\n\t}\n}",
"func NewEventHandler(evtfn func(eventbus.Event) error) eventbus.EventHandler {\n\tif evtfn == nil {\n\t\treturn eventbus.NOOPHandler\n\t}\n\treturn eventbus.Handler(evtfn)\n}",
"func NewEventHandler(eventService domain.EventSvc) *EventHandler {\n\treturn &EventHandler{\n\t\teventService: eventService,\n\t}\n}",
"func NewEventHandler(_ context.Context, logger *zap.Logger) *EventHandler {\n\treturn &EventHandler{\n\t\tlogger: logger,\n\t\thandlers: make(map[string]fanout.EventHandler),\n\t}\n}",
"func NewEventHandler(url string) EventHandler {\n\treturn EventHandler{\n\t\tclient: &http.Client{\n\t\t\tTimeout: 30 * time.Second,\n\t\t},\n\t\turl: url,\n\t}\n}",
"func NewEventHandler(writeAheadLogService *wal.Service, multiplexingService *multiplexing.Service,\n\teventsCache *caching.EventsCache, parser events.Parser, processor events.Processor) (eventHandler *EventHandler) {\n\treturn &EventHandler{\n\t\twriteAheadLogService: writeAheadLogService,\n\t\tmultiplexingService: multiplexingService,\n\t\teventsCache: eventsCache,\n\t\tparser: parser,\n\t\tprocessor: processor,\n\t}\n}",
"func setEventHandler(fn func())",
"func (w *watcher) AddEventHandler(h ResourceEventHandler) {\n\tw.handler = h\n}",
"func (d *DevClient) CreateEventHandler(systemKey, name string, data map[string]interface{}) (map[string]interface{}, error) {\n\treturn createEventHandler(d, _EVENTS_HDLRS_PREAMBLE+systemKey+\"/\"+name, data)\n}",
"func NewCmdCreateEventHandler(f cmdutil.Factory, out io.Writer) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"handler\",\n\t\tShort: \"Create event handler\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tRunCreateEventHandler(f, out, cmd)\n\t\t},\n\t}\n\tcmd.Flags().StringP(\"source\", \"s\", \"\", \"File containing event handler source code\")\n\tcmd.Flags().StringP(\"frontend\", \"f\", \"\", \"Event handler frontend\")\n\tcmd.Flags().StringP(\"url\", \"u\", \"\", \"URL of event handler source code\")\n\tcmd.Flags().StringP(\"version\", \"v\", \"1.0\", \"Event handler version\")\n\tcmd.Flags().StringP(\"dependencies-file\", \"d\", \"\", \"File containing event handler dependencies\")\n\tcmd.Flags().StringP(\"dependencies-url\", \"l\", \"\", \"URL of event handler source dependencies\")\n\n\treturn cmd\n}",
"func (socket *MockSocket) AddEventHandler(\n\thandler socket.EventHandler,\n) {\n}",
"func (e *Event) AddHandler(name string, handler EventHandler) {\n e.mu.Lock()\n defer e.mu.Unlock()\n if e.events == nil {\n e.events = make(map[string][]EventHandler)\n }\n handlers, has := e.events[name]\n if !has {\n handlers = make([]EventHandler, 0, 1)\n }\n e.events[name] = append(handlers, handler)\n}",
"func (p *Probe) AddEventHandler(eventType model.EventType, handler EventHandler) error {\n\tif eventType >= model.MaxAllEventType {\n\t\treturn errors.New(\"unsupported event type\")\n\t}\n\n\tp.eventHandlers[eventType] = append(p.eventHandlers[eventType], handler)\n\n\treturn nil\n}",
"func NewEventHandler(podInformer coreinformers.PodInformer, nodeInformer coreinformers.NodeInformer, verifier verifier, authSyncNodeURL, hmsSyncNodeURL string) (*NodeHandler, error) {\n\tauth, err := auth.NewClient(authSyncNodeURL, hmsSyncNodeURL, &clientcmdapi.AuthProviderConfig{Name: \"gcp\"})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpodIndexer := podInformer.Informer().GetIndexer()\n\tpodIndexer.AddIndexers(map[string]cache.IndexFunc{\n\t\tindexByNode: func(obj interface{}) ([]string, error) {\n\t\t\tpod, ok := obj.(*core.Pod)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid pod object from key %v\", obj)\n\t\t\t}\n\t\t\tnode := pod.Spec.NodeName\n\t\t\treturn []string{node}, nil\n\t\t},\n\t})\n\tnh := &NodeHandler{\n\t\tpodIndexer: podIndexer,\n\t\tverifier: verifier,\n\t\tauth: auth,\n\t\tnodeIndexer: nodeInformer.Informer().GetIndexer(),\n\t\tnodeMap: &nodeMap{m: make(map[string]*nodeGSAs)},\n\t}\n\tnh.InitEventHandler(\"node-syncer\", nh.process)\n\tnodeInformer.Informer().AddEventHandlerWithResyncPeriod(nh.ResourceEventHandler(), eventHandlerResyncPeriod)\n\treturn nh, nil\n}",
"func (engine *TcpEngin) HandleNewClient(onNewClient func(client *TcpClient)) {\r\n\tengine.onNewClientHandler = onNewClient\r\n}",
"func (e *eventProcessor) AddEventHandler(handler EventHandler) {\n\te.handlersMutex.Lock()\n\tdefer e.handlersMutex.Unlock()\n\te.handlers = append(e.handlers, handler)\n}",
"func (eventRouter EventRouter) AddHandler(event string, eventHandler EventHandler) {\n\tlog.Printf(\"Registering handler for event %s\", event)\n\n\teventRouter.mappings[event] = eventHandler\n}",
"func NewHandler(newEventStream NewEventStreamHandler) *Handler {\n\treturn NewHandlerBuffered(newEventStream, 0)\n}",
"func (e *EventManager) AddHandler(eventType EventType, handler EventHandler) {\n\tif int(eventType) >= len(e.rCounts) { // Check if we have enough room\n\t\t// Resize the handler tables accordingly\n\t\tnewRCounts := make([]int, eventType+1) // Counts\n\t\tnewRChans := make([]chan Event, eventType+1) // Channels\n\t\tcopy(newRCounts, e.rCounts)\n\t\tcopy(newRChans, e.channels)\n\t\te.rCounts = newRCounts\n\t\te.channels = newRChans\n\n\t\t// Create new count and channel\n\t\te.rCounts[eventType] = 1\n\t\te.channels[eventType] = make(chan Event, 1)\n\t} else {\n\t\te.rCounts[eventType]++\n\t\te.channels[eventType] = make(chan Event, e.rCounts[eventType])\n\t}\n\n\tgo handler.EventLoop(e.channels[eventType])\n}",
"func (h GenerateThumbAndBigShotsOnMediaImportedHandler) NewEvent() interface{} {\n\treturn &events.MediaImported{}\n}",
"func RunCreateEventHandler(f cmdutil.Factory, out io.Writer, cmd *cobra.Command) error {\n\n\taddress, err := cmdutil.GetServerAddress(cmd)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to connect to server: %v\", err)\n\t\treturn nil\n\t}\n\n\teventHandlerName := cmdutil.GetFlagString(cmd, \"eventhandler\")\n\teventHandlerNamespace := cmdutil.GetFlagString(cmd, \"namespace\")\n\teventHandlerBuilder := cmdutil.GetFlagString(cmd, \"eventhandlerbuilder\")\n\teventHandlerSourceCodeFile := cmdutil.GetFlagString(cmd, \"source\")\n\teventHandlerSourceCodeURL := cmdutil.GetFlagString(cmd, \"url\")\n\teventHandlerVersion := cmdutil.GetFlagString(cmd, \"version\")\n\teventHandlerDependenciesFile := cmdutil.GetFlagString(cmd, \"dependencies-file\")\n\teventHandlerDependenciesURL := cmdutil.GetFlagString(cmd, \"dependencies-url\")\n\teventHandlerFrontend := cmdutil.GetFlagString(cmd, \"frontend\")\n\tcomment := cmdutil.GetFlagString(cmd, \"comment\")\n\n\tvar eventHandlerSourceCode []byte\n\n\tif \"\" != eventHandlerSourceCodeFile {\n\t\teventHandlerSourceCode, err = ioutil.ReadFile(eventHandlerSourceCodeFile)\n\t\tif nil != err {\n\t\t\tlog.Fatalf(\"could not read source code file %s: %v\", eventHandlerSourceCodeFile, err)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tvar eventHandlerDependencies []byte\n\n\tif \"\" != eventHandlerDependenciesFile {\n\t\teventHandlerDependencies, err = ioutil.ReadFile(eventHandlerDependenciesFile)\n\t\tif nil != err {\n\t\t\tlog.Fatalf(\"could not read dependecies file %s: %v\", eventHandlerDependenciesFile, err)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tfmt.Fprintf(out, \"Create event handler = %s version %s in namespace = %s using event handler builder = %s with frontend = %s\\n\", eventHandlerName, eventHandlerVersion, eventHandlerNamespace, eventHandlerBuilder, eventHandlerFrontend)\n\n\t// Set up a connection to the server.\n\tconn, err := grpc.Dial(address, grpc.WithInsecure())\n\tif err != nil {\n\t\tlog.Fatalf(\"did not connect: %v\", err)\n\t}\n\tdefer conn.Close()\n\tc := klessapi.NewKlessAPIClient(conn)\n\n\t// Contact the server and print out its response.\n\tr, err := c.CreateEventHandler(context.Background(), &klessapi.CreateEventHandlerRequest{EventHandlerName: eventHandlerName,\n\t\tEventHandlerNamespace: eventHandlerNamespace,\n\t\tEventHandlerBuilder: eventHandlerBuilder,\n\t\tEventHandlerSourceCode: eventHandlerSourceCode,\n\t\tEventHandlerSourceCodeURL: eventHandlerSourceCodeURL,\n\t\tEventHandlerVersion: eventHandlerVersion,\n\t\tEventHandlerFrontend: eventHandlerFrontend,\n\t\tEventHandlerDependencies: eventHandlerDependencies,\n\t\tEventHandlerDependenciesURL: eventHandlerDependenciesURL,\n\t\tComment: comment,\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"could not create event handler: %v\", err)\n\t}\n\n\tfmt.Fprintf(out, \"Server response: %s\\n\", r.Response)\n\n\treturn nil\n}",
"func (b *Bot) SetNewMessageHandler(fn newMessageHandlerFunc) {\n\tb.handlers.newMessageHandler = fn\n}",
"func newCallBackHandler() (raw.OnewayHandler, <-chan map[string]string) {\n\tserverCalledBack := make(chan map[string]string)\n\treturn func(ctx context.Context, body []byte) error {\n\t\tserverCalledBack <- extractBaggage(ctx)\n\t\treturn nil\n\t}, serverCalledBack\n}",
"func newHandler(chain *Chain, handler Handler) (ch *ChainHandler) {\n\tch = new(ChainHandler)\n\tch.chain = chain\n\tch.handler = handler\n\treturn\n}",
"func (h CreateMediaOnMediaImportedHandler) NewEvent() interface{} {\n\treturn &events.MediaImported{}\n}",
"func NewEventHandlers() *EventHandlers {\n\treturn &EventHandlers{}\n}",
"func new_(e interface{}) func() Event {\n\ttyp := reflect.TypeOf(e)\n\treturn func() Event {\n\t\treturn reflect.New(typ).Interface().(Event)\n\t}\n}",
"func newEvent(name string, args ...interface{}) (*Event, error) {\n\tid, err := uuid.NewV4()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theader := &EventHeader{Id: id.String(), Version: ProtocolVersion}\n\n\te := Event{\n\t\tHeader: header,\n\t\tName: name,\n\t\tArgs: args,\n\t}\n\n\treturn &e, nil\n}",
"func (i *Conn) AddHandler(event Event, handler Handler) {\n\ti.handlers[event] = handler\n}",
"func (w Wrapper) OnNewMessage(f NewMessageHandler) {\n\tw.longpoll.EventNew(4, func(i []interface{}) error {\n\t\tvar event NewMessage\n\t\tif err := event.parse(i); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tf(event)\n\n\t\treturn nil\n\t})\n}",
"func (p *Probe) AddCustomEventHandler(eventType model.EventType, handler CustomEventHandler) error {\n\tif eventType >= model.MaxAllEventType {\n\t\treturn errors.New(\"unsupported event type\")\n\t}\n\n\tp.customEventHandlers[eventType] = append(p.customEventHandlers[eventType], handler)\n\n\treturn nil\n}",
"func (this *Button)AddEventListener(event string, responceChannel chan string) {\n\t//array içinde arama yapılıyor eğer bulunursa append edilecek bulunamazsa eklenecek.\n\tif _, present := this.eventListener[event]; present {\n\t\tthis.eventListener[event] = append(this.eventListener[event], responceChannel)\n\t} else {\n\t\tthis.eventListener[event] = []chan string{responceChannel}\n\t}\n}",
"func AddHandler(handler func()) {\n\t// Create the channel and start the main interrupt handler which invokes all other callbacks and exits if not\n\t// already done.\n\tif Chan == nil {\n\t\tChan = make(chan os.Signal, 1)\n\t\tsignal.Notify(Chan, Signals...)\n\t\tgo Listener()\n\t}\n\tAddHandlerChan <- handler\n}",
"func AddHandler(handler HandlerFunc, evts ...string) *HandlerFunc {\n\tfor _, evt := range evts {\n\t\tif evt == \"*\" && len(evts) > 1 {\n\t\t\tlogrus.Warn(AddMultipleWildcardWarning)\n\t\t\treturn AddHandler(handler, \"*\")\n\t\t}\n\t}\n\n\thPtr := &handler\n\n\teventHandlersLock.Lock()\n\tdefer eventHandlersLock.Unlock()\n\n\tfor _, evt := range evts {\n\t\teventHandlers[evt] = append(eventHandlers[evt], hPtr)\n\t}\n\n\treturn hPtr\n}",
"func newCommandHandler() *commandHandler {\n\treturn &commandHandler{make(cmdMap)}\n}",
"func newCommandHandler() *commandHandler {\n\treturn &commandHandler{make(cmdMap)}\n}",
"func NewHandler() *Handler {\n\treturn &Handler{\n\t\tevents: []*event.Event{},\n\t}\n}",
"func (e *FakeElement) AddEventListener(event string, handler func(Object)) Element {\n\te.EventListeners[event] = append(e.EventListeners[event], handler)\n\treturn e\n}",
"func (s *snmpType) newHandler(hostConfig configReader.SnmpAgent) (*snmpgo.SNMP, error) {\n\treturn snmp.NewHandler(hostConfig)\n}",
"func (l Listener) AddHandler(cmd string, handleFunc func()) {\n\tl[cmd] = handleFunc\n}",
"func newEvent(path string) Event {\n\te := Event{Path: path}\n\treturn e\n}",
"func (t *Trigger) NewHandler(settings map[string]interface{}) *Handler {\n\n\tnewHandler := &Handler{settings: settings}\n\tt.handlers = append(t.handlers, newHandler)\n\n\treturn newHandler\n}",
"func New(h []IHandler) *Handler {\n\treturn &Handler{handler: h}\n}",
"func (w *Watcher) newEvent(name string, mask uint32) Event {\n\te := Event{Name: name}\n\tif mask&unix.IN_CREATE == unix.IN_CREATE || mask&unix.IN_MOVED_TO == unix.IN_MOVED_TO {\n\t\te.Op |= Create\n\t}\n\tif mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF || mask&unix.IN_DELETE == unix.IN_DELETE {\n\t\te.Op |= Remove\n\t}\n\tif mask&unix.IN_MODIFY == unix.IN_MODIFY {\n\t\te.Op |= Write\n\t}\n\tif mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF || mask&unix.IN_MOVED_FROM == unix.IN_MOVED_FROM {\n\t\te.Op |= Rename\n\t}\n\tif mask&unix.IN_ATTRIB == unix.IN_ATTRIB {\n\t\te.Op |= Chmod\n\t}\n\treturn e\n}",
"func NewEventsHandler(config *mesh.Configuration, maxRequestSize int64) http.Handler {\n\treturn traceHeaderHandler{next: &maxBytesHandler{next: http.HandlerFunc(getEventsHandler(config)), limit: maxRequestSize}}\n}",
"func NewEvent(meta EventHandler) *Event {\n\treturn &Event{\n\t\tMetadata: meta,\n\t\teventResults: make(chan interface{}, 1),\n\t\tcancelled: make(chan struct{}),\n\t\tstats: eventStatistics{},\n\t}\n}",
"func NewHandler() Handler {\n\treturn Handler{}\n}",
"func newExecHandler() *exec.Exec {\n\tvar exe = new(exec.Exec)\n\treturn exe\n}",
"func NewHandlerFunc() NodeHandlerFunc {\n\treturn func(n Node) {}\n}",
"func (c *Controller) RegisterEventHandler(typ string, f func(model.Config, model.Event)) {\n\tc.eventHandlers = append(c.eventHandlers, f)\n}",
"func (app AppModule) NewHandler() sdk.Handler {\n\treturn NewHandler(app.msKeeper, app.poaKeeper)\n}",
"func newSignalHandler() *signalHandler {\n\treturn &signalHandler{\n\t\tsignals: make(map[uint64]signalUser),\n\t\ttracer: nil,\n\t}\n}",
"func (h *Handler) EventHandle(etype string, name string, eventHandler EventHandler) {\n\tif eventHandler == nil {\n\t\tpanic(\"serfer: nil event handler\")\n\t}\n\tif !validEventType(etype) {\n\t\tpanic(fmt.Sprintf(\"serfer: unknown event type %q\", etype))\n\t}\n\t// The event type '*' is the same as an empty event type '' and the latest\n\t// should be used\n\tif etype == \"*\" {\n\t\tetype = \"\"\n\t}\n\t// TODO: Do we really want this? or overwrite the event or add another event with same name?\n\t// Only the default entry can be overwritten\n\t// if _, ok := h.entry[etype][name]; ok && len(etype) != 0 && len(name) != 0 {\n\t// \tpanic(fmt.Sprintf(\"serfer: multiple registrations for %s named %q\", etype, name))\n\t// }\n\tif h.entry == nil {\n\t\th.entry = newEntries()\n\t}\n\n\tvar ehs []EventHandler\n\tif _, ok := h.entry[etype][name]; ok {\n\t\tehs = append(h.entry[etype][name].h, eventHandler)\n\t} else {\n\t\tehs = []EventHandler{eventHandler}\n\t}\n\n\tif _, ok := h.entry[etype]; !ok {\n\t\th.entry[etype] = make(map[string]handlerEntry)\n\t}\n\th.entry[etype][name] = handlerEntry{\n\t\teventType: etype,\n\t\tname: name,\n\t\th: ehs,\n\t}\n}",
"func (c *Client) On(event string, handler Handler) {\n\tc.handlers[event] = handler\n}",
"func (b *unityBridge) AddEventHandler(eventType unity.EventType,\n\teventHandler EventHandler) (uint64, error) {\n\tif !unity.IsValidEventType(eventType) {\n\t\treturn 0, fmt.Errorf(\"invalid event type\")\n\t}\n\n\ttag, err := b.cbs.AddContinuous(callbacks.Key(eventType), eventHandler)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn uint64(tag), nil\n}",
"func New(notifier *gobrake.Notifier) *Handler {\n\th := Handler{notifier}\n\treturn &h\n}",
"func (am AppModule) NewHandler() sdk.Handler {\n\treturn NewHandler(am.keeper)\n}",
"func (am AppModule) NewHandler() sdk.Handler {\n\treturn NewHandler(am.keeper)\n}",
"func (am AppModule) NewHandler() sdk.Handler {\n\treturn NewHandler(am.keeper)\n}",
"func (consumer *Consumer) AddHandler(handler goevents.MessageHandler) {\n\tconsumer.consumer.AddHandler(gonsq.HandlerFunc(func(nsqMessage *gonsq.Message) error {\n\t\tdefer nsqMessage.Finish()\n\t\treturn handler.HandleMessage(&Message{message: nsqMessage})\n\t}))\n}",
"func newDescriptorHandler(descr *kvs.KVDescriptor) *descriptorHandler {\n\treturn &descriptorHandler{\n\t\tdescriptor: descr,\n\t}\n}",
"func (h *HTML) On(event string, handler EventHandler) *HTML {\n\th.events = append(h.events, eventHandler{event, handler})\n\treturn h\n}",
"func hNewEvent(c echo.Context) error {\n\tvar e httpError\n\n\tif (len(c.FormValue(\"code\")) == 0) || (len(c.FormValue(\"title\")) == 0) {\n\t\treturn c.JSON(http.StatusNotAcceptable, \"input information is not valid\")\n\t}\n\tuserCODE := c.FormValue(\"code\")\n\n\t// read from token user id\n\tvar tokenUserID int64\n\ttokenUserID = 1\n\n\tu, errGet := blog.GetUserByCode(tokenUserID, userCODE)\n\tif errGet != nil {\n\t\te.TheError = \"user code \" + userCODE + \" not found.\"\n\t\treturn c.JSON(http.StatusNotFound, e)\n\t}\n\tvar ev Event\n\tev.OpenedByUserID = u.ID\n\tev.Contents = c.FormValue(\"content\")\n\tev.Title = c.FormValue(\"title\")\n\n\terrAdd := blog.AddEvent(&ev)\n\tif errAdd != nil {\n\t\te.TheError = errAdd.Error()\n\t\treturn c.JSON(http.StatusInternalServerError, e)\n\t}\n\tfname, errUpload := lowlevelUploadFile(c, u.ID, ev.ID)\n\tif errUpload != nil {\n\t\te.TheError = \"could not upload file: \" + errUpload.Error()\n\t\treturn c.JSON(http.StatusInternalServerError, e)\n\t}\n\te.TheError = \"OK\" + \" - \" + fname\n\treturn c.JSON(http.StatusOK, e)\n}",
"func newSignalHandler() *signalHandler {\n\treturn &signalHandler{\n\t\tsignals: make([]signalUser, 0, 10),\n\t\ttracer: nil,\n\t}\n}",
"func AddNewEvent(event eventinfo.Info) {\n\teventList = append(eventList, event)\n}",
"func (r ResourceEventHandlerFuncs) OnAdd(obj interface{}) {\n\tif r.AddFunc != nil {\n\t\tr.AddFunc(obj)\n\t}\n}",
"func (c *Client) defaultEventHandler() cache.ResourceEventHandlerFuncs {\n\treturn cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tc.handleEvent(events.Added, nil, obj)\n\t\t},\n\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tc.handleEvent(events.Updated, oldObj, newObj)\n\t\t},\n\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tc.handleEvent(events.Deleted, obj, nil)\n\t\t},\n\t}\n}",
"func (h *Hub) On(event string, fn EventHandler) *Hub {\n\tif h.listeners[event] == nil {\n\t\th.listeners[event] = []EventHandler{}\n\t}\n\n\th.listeners[event] = append(h.listeners[event], fn)\n\n\treturn h\n}",
"func (e *EventHandlerFuncs) OnAdd(table string, model Model) {\n\tif e.AddFunc != nil {\n\t\te.AddFunc(table, model)\n\t}\n}",
"func (b *EventBus) AddHandler(m goevent.EventMatcher, h goevent.EventHandler) error {\n\treturn b.Err\n}",
"func (s *Server) newHandler() http.Handler {\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"/register\", s.wrapMiddleware(registerHandler)).Methods(\"POST\")\n\tr.HandleFunc(\"/session/{id}\", s.wrapMiddleware(getHandler)).Methods(\"GET\")\n\tr.HandleFunc(\"/session\", s.wrapMiddleware(createHandler)).Methods(\"POST\")\n\tr.HandleFunc(\"/readiness\", predis.NewReadinessCheck(s.pool))\n\n\treturn r\n}",
"func newMessageHandler(m chan<- string, f parserFunc) *messageHandler {\n\treturn &messageHandler{\n\t\tmessages: m,\n\t\tparserFunc: f,\n\t}\n}",
"func (n *Node) HandleNewEventLocked(ev *roothash.Event) {\n\t// Nothing to do here.\n}",
"func NewHandler(pubsubapiClient pubsubapi.Client, estafetteService estafette.Service) Handler {\n\treturn Handler{\n\t\tpubsubapiClient: pubsubapiClient,\n\t\testafetteService: estafetteService,\n\t}\n}",
"func NewHandler(clusterID string, dataType string, act Action) *Handler {\n\th := &Handler{\n\t\tdataType: dataType,\n\t\tqueue: make(chan *action.SyncData, defaultHandlerQueueSize),\n\t\tact: act,\n\t\tclusterID: clusterID,\n\t}\n\treturn h\n}",
"func NewHandler(k Keeper) sdk.Handler {\n\treturn func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) {\n\t\tctx = ctx.WithEventManager(sdk.NewEventManager())\n\t\tswitch msg := msg.(type) {\n\t\tcase MsgCreate:\n\t\t\treturn handleMsgCreate(ctx, k, &msg)\n\t\tcase MsgDelete:\n\t\t\treturn handleMsgDelete(ctx, k, &msg)\n\t\tdefault:\n\t\t\treturn nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, \"unrecognized %s message type: %T\", types.ModuleName, msg)\n\t\t}\n\t}\n}",
"func (handler *WebsocketHandler) AddHandler(commandName string, fn func(context.Context, interfaces.WebsocketClient, interfaces.WebsocketCommand)) {\n\thandler.Handlers[commandName] = fn\n}",
"func (s *Server) On(event string, f interface{}) {\n\tvalue := reflect.ValueOf(f)\n\n\tif !validHandler(value, reflect.TypeOf(f).Name()) {\n\t\tpanic(\"On: invalid callback for event \" + event)\n\t}\n\n\ts.handlersLock.Lock()\n\ts.handlers[event] = ®Method{value, value.Type().In(1)}\n\ts.handlersLock.Unlock()\n}",
"func (c *Client) RegisterHandler(n string, h EventHandler) {\n var handlers []EventHandler\n\n reg, ok := c.Subscribers.Load(n)\n\n if ok {\n handlers = reg.([]EventHandler)\n }\n\n handlers = append(handlers, h)\n c.Subscribers.Store(n, handlers)\n}",
"func NewHandler() *Handler {\n\treturn &Handler{\n\t\tentry: newEntries(),\n\t}\n}",
"func newDataHandler(prices []DataPoint) *DataHandler {\n\treturn &DataHandler{\n\t\tPrices: prices,\n\t}\n}",
"func New(secret string, h Func) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tb, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"reading body\")\n\t\t\tresponse.InternalServerError(w)\n\t\t\treturn\n\t\t}\n\n\t\tsignature := r.Header.Get(\"Stripe-Signature\")\n\t\te, err := webhook.ConstructEvent(b, signature, secret)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"constructing event\")\n\t\t\tresponse.InternalServerError(w)\n\t\t\treturn\n\t\t}\n\n\t\tctx := log.WithFields(log.Fields{\n\t\t\t\"event_id\": e.ID,\n\t\t\t\"event_type\": e.Type,\n\t\t})\n\n\t\tctx.Info(\"handling stripe event\")\n\t\tif err := h(&e); err != nil {\n\t\t\tctx.WithError(err).Error(\"handling stripe event\")\n\t\t\tresponse.InternalServerError(w)\n\t\t\treturn\n\t\t}\n\n\t\tctx.Info(\"handled stripe event\")\n\t\tresponse.OK(w)\n\t})\n}",
"func buildEventHandler(store *stateStore, fidStore store.Singleton) events.Handler {\n\treturn eventrules.New(\n\t\tlogAllEvents(),\n\t\teventMetrics(store.metricsAPI, time.Now, true),\n\t\tcontroller.LiftErrors().DropOnError(),\n\t).Handle(events.Handlers{\n\t\tscheduler.Event_FAILURE: executorFailure(),\n\t\tscheduler.Event_OFFERS: trackOffersReceived(store).HandleF(resourceOffers(store)),\n\t\tscheduler.Event_UPDATE: controller.AckStatusUpdates(store.cli).AndThen().HandleF(statusUpdate(store)),\n\t\tscheduler.Event_SUBSCRIBED: controller.TrackSubscription(fidStore, store.config.FailoverTimeout),\n\t})\n}",
"func newHTTPHandler(web3Handler Web3Handler) *hTTPHandler {\n\treturn &hTTPHandler{\n\t\tmsgHandler: web3Handler,\n\t}\n}",
"func (a *Asock) AddHandler(name string, argmode string, df DispatchFunc) error {\n\tif _, ok := a.d[name]; ok {\n\t\treturn fmt.Errorf(\"handler '%v' already exists\", name)\n\t}\n\tif argmode != \"split\" && argmode != \"nosplit\" {\n\t\treturn fmt.Errorf(\"invalid argmode '%v'\", argmode)\n\t}\n\ta.d[name] = &dispatchFunc{df, argmode}\n\ta.help = \"\"\n\tfor cmd := range a.d {\n\t\ta.help = a.help + cmd + \" \"\n\t}\n\treturn nil\n}",
"func (t *TableCache) AddEventHandler(handler EventHandler) {\n\tt.eventProcessor.AddEventHandler(handler)\n}",
"func NewHandler(intfs *Interfaces) infra.Handler {\n\tf := func(r *infra.Request) *infra.HandlerResult {\n\t\thandler := &handler{\n\t\t\tintfs: intfs,\n\t\t\trequest: r,\n\t\t}\n\t\treturn handler.Handle()\n\t}\n\treturn infra.HandlerFunc(f)\n}",
"func (w *OutputWriter) GetEventHandler() *runtime.EventHandler {\n\thandler := runtime.EventHandler{}\n\thandler.TestFinished = func(testResult runtime.TestResult) {\n\t\ttr := convertTestResult(testResult)\n\t\tw.printResult(tr)\n\t}\n\n\thandler.TestSkipped = func(testResult runtime.TestResult) {\n\t\ttr := convertTestResult(testResult)\n\t\tw.printSkip(tr)\n\t}\n\n\treturn &handler\n}",
"func NewHandler(hdlr interface{}) Handler {\n\treturn DefaultServer.NewHandler(hdlr)\n}",
"func Newhandler(service *comment.Service) *Handler {\n\treturn &Handler{\n\t\tService: service,\n\t}\n}",
"func (i *multiNamespaceInformer) AddEventHandler(handler cache.ResourceEventHandler) {\n\ti.AddEventHandlerWithResyncPeriod(handler, i.resyncPeriod)\n}",
"func (d *DevClient) UpdateEventHandler(systemKey, name string, data map[string]interface{}) (map[string]interface{}, error) {\n\treturn updateEventHandler(d, _EVENTS_HDLRS_PREAMBLE+systemKey+\"/\"+name, data)\n}",
"func NewEvent(\n\trkind,\n\trapiVersion,\n\trnamespace,\n\trname,\n\treason string,\n\tsource Source,\n\tmessage MsgKey,\n\targs ...interface{}) Info {\n\tmsgText, err := getEventMsg(message, args...)\n\tif err != nil {\n\t\tglog.Error(err)\n\t}\n\treturn Info{\n\t\tKind: rkind,\n\t\tName: rname,\n\t\tNamespace: rnamespace,\n\t\tReason: reason,\n\t\tSource: source,\n\t\tMessage: msgText,\n\t}\n}",
"func NewHandler(handler HandlerFunc) *Handler {\n\tph := &Handler{panicChan: make(chan Info), handle: handler, mu: &sync.Mutex{}, quit: make(chan struct{})}\n\tgo ph.listen()\n\treturn ph\n}"
] | [
"0.71682805",
"0.7156138",
"0.71377176",
"0.6746839",
"0.674366",
"0.66717136",
"0.6587883",
"0.65227765",
"0.6437374",
"0.64316064",
"0.6380567",
"0.6248131",
"0.61711705",
"0.6157125",
"0.598441",
"0.5973853",
"0.5949763",
"0.5934126",
"0.5804517",
"0.58044064",
"0.57587826",
"0.57575375",
"0.5741029",
"0.57181257",
"0.570987",
"0.5694107",
"0.5686159",
"0.5683752",
"0.5657991",
"0.5629163",
"0.55875325",
"0.5583833",
"0.5583534",
"0.5582565",
"0.556978",
"0.55447423",
"0.5543426",
"0.55410796",
"0.55380905",
"0.5537746",
"0.55137664",
"0.55137664",
"0.5501163",
"0.55005264",
"0.54992616",
"0.5474037",
"0.54607254",
"0.5447487",
"0.5428482",
"0.5422513",
"0.5414779",
"0.54100233",
"0.5407079",
"0.54000497",
"0.5392613",
"0.53920615",
"0.5380367",
"0.53788936",
"0.53766906",
"0.53724897",
"0.53679216",
"0.5364238",
"0.53623474",
"0.53623474",
"0.53623474",
"0.53583276",
"0.53578645",
"0.5351929",
"0.5349415",
"0.53431034",
"0.5342765",
"0.53378034",
"0.53254896",
"0.5322238",
"0.53168327",
"0.53128517",
"0.53103346",
"0.53082436",
"0.5306679",
"0.5290256",
"0.52874756",
"0.52837515",
"0.5276862",
"0.5273626",
"0.52717704",
"0.5270913",
"0.52635145",
"0.5260434",
"0.5256967",
"0.5252078",
"0.5250915",
"0.5240738",
"0.52253777",
"0.522357",
"0.5221627",
"0.52210116",
"0.519741",
"0.5195903",
"0.5193124",
"0.51897395"
] | 0.6724587 | 5 |
Handle checks event health and notifies if unhealthy | func (h *EventHandler) Handle(obj interface{}) error {
event, ok := obj.(*corev1.Event)
if !ok {
return fmt.Errorf("handler expects event object, got %t", obj)
}
if event.Type == corev1.EventTypeNormal {
return nil
}
payload := h.getPayload(event)
return h.notifier.Notify(payload)
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (r *GoMetricsRegistry) RunHealthchecks() {}",
"func (manager *Manager) HealthHandler(healthCheck *healthcheck.Manager) {\n\tlog := logging.For(\"core/healthcheck/handler\").WithField(\"func\", \"healthcheck\")\n\n\tsignalChan := make(chan os.Signal, 1)\n\tsignal.Notify(signalChan, syscall.SIGUSR1)\n\n\tfor {\n\t\tselect {\n\t\tcase _ = <-signalChan:\n\t\t\tlog.Debug(\"HealthHandler Debug triggered\")\n\t\t\thealthCheck.Debug()\n\t\tcase checkresult := <-healthCheck.Incoming:\n\t\t\t// Status change entity\n\t\t\t// pool + backend + node = node check Changed\n\t\t\t// pool + backend = backend check changed - applies to nodes\n\t\t\t// pool = pool check changed - applies to vip\n\t\t\tlog.WithField(\"pool\", checkresult.PoolName).WithField(\"backend\", checkresult.BackendName).WithField(\"node\", checkresult.NodeName).WithField(\"actualstatus\", checkresult.ActualStatus.String()).WithField(\"reportedstatus\", checkresult.ReportedStatus.String()).WithField(\"errormsg\", checkresult.ErrorMsg).WithField(\"check\", checkresult.Description).Info(\"Received health update from worker\")\n\n\t\t\t// Set status in healh pool\n\t\t\thealthCheck.SetCheckStatus(checkresult.WorkerUUID, checkresult.ReportedStatus, checkresult.ErrorMsg)\n\n\t\t\t// Get all nodes using the check\n\t\t\tnodeUUIDs := healthCheck.GetPools(checkresult.WorkerUUID)\n\t\t\tlog.WithField(\"nodeuuids\", nodeUUIDs).WithField(\"workeruuid\", checkresult.WorkerUUID).Debug(\"Pools to update\")\n\n\t\t\t// and check each individual node using the above check, to see if status changes\n\t\t\tfor _, nodeUUID := range nodeUUIDs {\n\t\t\t\tactualStatus, poolName, backendName, nodeName, errors := healthCheck.GetNodeStatus(nodeUUID)\n\t\t\t\tcheckresult.ReportedStatus = actualStatus\n\t\t\t\tcheckresult.ErrorMsg = errors\n\t\t\t\tcheckresult.NodeUUID = nodeUUID\n\t\t\t\tif poolName != \"\" {\n\t\t\t\t\tcheckresult.PoolName = poolName\n\t\t\t\t}\n\n\t\t\t\tif nodeName != \"\" {\n\t\t\t\t\tcheckresult.NodeName = nodeName\n\t\t\t\t}\n\n\t\t\t\tif backendName != \"\" {\n\t\t\t\t\tcheckresult.BackendName = backendName\n\t\t\t\t}\n\n\t\t\t\tlog.WithField(\"pool\", checkresult.PoolName).WithField(\"backend\", checkresult.BackendName).WithField(\"node\", checkresult.NodeName).WithField(\"reportedstatus\", checkresult.ReportedStatus.String()).WithField(\"error\", checkresult.ErrorMsg).Info(\"Sending status update to cluster\")\n\t\t\t\tmanager.healthchecks <- checkresult // do not send pointers, since pointer will change data\n\t\t\t}\n\n\t\t}\n\t}\n}",
"func handleRootHealth(name string, firstTimeHealthy func(), checks ...HealthChecker) http.HandlerFunc {\n\tvar notifyOnce sync.Once\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\texcluded := getExcludedChecks(r)\n\t\t// failedVerboseLogOutput is for output to the log. It indicates detailed failed output information for the log.\n\t\tvar failedVerboseLogOutput bytes.Buffer\n\t\tvar failedChecks []string\n\t\tvar individualCheckOutput bytes.Buffer\n\t\tfor _, check := range checks {\n\t\t\t// no-op the check if we've specified we want to exclude the check\n\t\t\tif _, has := excluded[check.Name()]; has {\n\t\t\t\tdelete(excluded, check.Name())\n\t\t\t\t_, _ = fmt.Fprintf(&individualCheckOutput, \"[+]%s excluded: ok\\n\", check.Name())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := check.Check(r); err != nil {\n\t\t\t\t// don't include the error since this endpoint is public. If someone wants more detail\n\t\t\t\t// they should have explicit permission to the detailed checks.\n\t\t\t\t_, _ = fmt.Fprintf(&individualCheckOutput, \"[-]%s failed: reason withheld\\n\", check.Name())\n\t\t\t\t// but we do want detailed information for our log\n\t\t\t\t_, _ = fmt.Fprintf(&failedVerboseLogOutput, \"[-]%s failed: %v\\n\", check.Name(), err)\n\t\t\t\tfailedChecks = append(failedChecks, check.Name())\n\t\t\t} else {\n\t\t\t\t_, _ = fmt.Fprintf(&individualCheckOutput, \"[+]%s ok\\n\", check.Name())\n\t\t\t}\n\t\t}\n\t\tif len(excluded) > 0 {\n\t\t\t_, _ = fmt.Fprintf(&individualCheckOutput, \"warn: some health checks cannot be excluded: no matches for %s\\n\", formatQuoted(maps.Keys(excluded)...))\n\t\t\tslog.Warn(fmt.Sprintf(\"cannot exclude some health checks, no health checks are installed matching %s\",\n\t\t\t\tformatQuoted(maps.Keys(excluded)...)))\n\t\t}\n\t\t// always be verbose on failure\n\t\tif len(failedChecks) > 0 {\n\t\t\tslog.Error(fmt.Sprintf(\"%s check failed: %s\\n%v\", strings.Join(failedChecks, \",\"), name, failedVerboseLogOutput.String()))\n\t\t\thttp.Error(w, fmt.Sprintf(\"%s%s check failed\", individualCheckOutput.String(), name), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t// signal first time this is healthy\n\t\tif firstTimeHealthy != nil {\n\t\t\tnotifyOnce.Do(firstTimeHealthy)\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"text/plain; charset=utf-8\")\n\t\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\t\tif _, found := r.URL.Query()[\"verbose\"]; !found {\n\t\t\t_, _ = fmt.Fprint(w, \"ok\")\n\t\t\treturn\n\t\t}\n\n\t\t_, _ = individualCheckOutput.WriteTo(w)\n\t\t_, _ = fmt.Fprintf(w, \"%s check passed\\n\", name)\n\t}\n}",
"func (c *QueueController) checkAndUpdateServiceHealth(exitCode errors.ExitCode) {\n\tvar svcStatusErr error\n\tmarkUnhealthy := false\n\tif c.isCriticalError(exitCode) {\n\t\tsvcStatusErr = fmt.Errorf(\"critical error (%d) occurred. Marking worker unhealthy\", exitCode)\n\t\tmarkUnhealthy = true\n\t}\n\tif c.isPersistentError(exitCode) {\n\t\tsvcStatusErr = fmt.Errorf(\"errors (%d) occurred multiple times in a row. Marking worker unhealthy\", exitCode)\n\t\tmarkUnhealthy = true\n\t}\n\tif markUnhealthy {\n\t\tsvcStatus := c.statusManager.svcStatus\n\t\tsvcStatus.IsHealthy = false\n\t\tsvcStatus.Error = svcStatusErr\n\t\tc.statusManager.UpdateService(svcStatus)\n\t\tc.inv.stat.Gauge(stats.WorkerUnhealthy).Update(1)\n\t}\n}",
"func healthcheck(rw http.ResponseWriter, req *http.Request) {\n for name, h := range toolbox.AdminCheckList {\n if err := h.Check(); err != nil {\n fmt.Fprintf(rw, \"%s : %s\\n\", name, err.Error())\n } else {\n fmt.Fprintf(rw, \"%s : ok\\n\", name)\n }\n }\n}",
"func RunHealthChecks(ctx context.Context, s *Status, k8sClientset *kubernetes.Clientset) {\n\ts.SetReady(\"KubeAPIServer\", false, \"initialized to false\")\n\n\t// Loop forever and perform healthchecks.\n\tfor {\n\t\t// Kube-apiserver HealthCheck\n\t\thealthStatus := 0\n\t\tk8sCheckDone := make(chan interface{}, 1)\n\t\tgo func(k8sCheckDone <-chan interface{}) {\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t\tselect {\n\t\t\tcase <-k8sCheckDone:\n\t\t\t\t// The check has completed.\n\t\t\tdefault:\n\t\t\t\t// Check is still running, so report not ready.\n\t\t\t\ts.SetReady(\n\t\t\t\t\t\"KubeAPIServer\",\n\t\t\t\t\tfalse,\n\t\t\t\t\tfmt.Sprintf(\"Error reaching apiserver: taking a long time to check apiserver\"),\n\t\t\t\t)\n\t\t\t}\n\t\t}(k8sCheckDone)\n\t\tk8sClientset.Discovery().RESTClient().Get().AbsPath(\"/healthz\").Do(ctx).StatusCode(&healthStatus)\n\t\tk8sCheckDone <- nil\n\t\tif healthStatus != http.StatusOK {\n\t\t\tklog.Errorf(\"Failed to reach apiserver\")\n\t\t\ts.SetReady(\n\t\t\t\t\"KubeAPIServer\",\n\t\t\t\tfalse,\n\t\t\t\tfmt.Sprintf(\"Error reaching apiserver: %v with http status code: %d\", nil, healthStatus),\n\t\t\t)\n\t\t} else {\n\t\t\ts.SetReady(\"KubeAPIServer\", true, \"\")\n\t\t}\n\n\t\ttime.Sleep(10 * time.Second)\n\t}\n}",
"func doHealth(sdk *sdk.SDK) {\n\ttick := time.Tick(2 * time.Second)\n\tfor {\n\t\terr := sdk.Health()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"[wrapper] Could not send health ping, %v\", err)\n\t\t}\n\t\t<-tick\n\t}\n}",
"func (r *DefaultTaggedRegistry) RunHealthchecks() {\n\tr.mutex.Lock()\n\tdefer r.mutex.Unlock()\n\tfor _, t := range r.metrics {\n\t\tfor _, i := range t {\n\t\t\tif h, ok := i.GetMetric().(metrics.Healthcheck); ok {\n\t\t\t\th.Check()\n\t\t\t}\n\t\t}\n\t}\n}",
"func handleHealthCheck(m *MicroService, d *net.Dialer) bool {\r\n\tchange := false\r\n\tfor i, inst := range m.Instances {\r\n\t\t_, err := d.Dial(\"tcp\", inst.Host)\r\n\t\tif err != nil {\r\n\t\t\tif !m.isBlacklisted(i) {\r\n\t\t\t\tm.blackList(i, true)\r\n\t\t\t\tlogInfo(\"Instance: \" + inst.Host + \" is now marked as DOWN\")\r\n\t\t\t\tchange = true\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tif m.isBlacklisted(i) {\r\n\t\t\t\tm.blackList(i, false)\r\n\t\t\t\tlogInfo(\"Instance: \" + inst.Host + \" is now marked as UP\")\r\n\t\t\t\tchange = true\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn change\r\n}",
"func (c *Canary) HealthChecking(config schemas.Config) error {\n\thealthy := false\n\n\tfor !healthy {\n\t\tc.Logger.Debugf(\"Start Timestamp: %d, timeout: %s\", config.StartTimestamp, config.Timeout)\n\t\tisTimeout, _ := tool.CheckTimeout(config.StartTimestamp, config.Timeout)\n\t\tif isTimeout {\n\t\t\treturn fmt.Errorf(\"timeout has been exceeded : %.0f minutes\", config.Timeout.Minutes())\n\t\t}\n\n\t\tisDone, err := c.Deployer.HealthChecking(config)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"error happened while health checking\")\n\t\t}\n\n\t\tif isDone {\n\t\t\thealthy = true\n\t\t} else {\n\t\t\ttime.Sleep(config.PollingInterval)\n\t\t}\n\t}\n\n\treturn nil\n}",
"func HealthListener(site site.API) {\n\t// nop\n}",
"func (check *HealthCheck) CheckHealth(brokerUpdates chan<- Update, clusterUpdates chan<- Update, stop <-chan struct{}) {\n\tmanageTopic := !check.config.NoTopicCreation\n\terr := check.connect(manageTopic, stop)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer check.close(manageTopic)\n\n\tcheck.randSrc = rand.NewSource(time.Now().UnixNano())\n\n\tlog.Info(\"starting health check loop\")\n\tticker := time.NewTicker(check.config.CheckInterval)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tbrokerStatus := check.checkBrokerHealth()\n\n\t\t\tdata, err := json.Marshal(brokerStatus)\n\t\t\tif err != nil {\n\t\t\t\tlog.Warn(\"Error while marshaling broker status: %s\", err.Error())\n\t\t\t\tdata = simpleStatus(brokerStatus.Status)\n\t\t\t}\n\n\t\t\tbrokerUpdates <- Update{brokerStatus.Status, data}\n\n\t\t\tif brokerStatus.Status == unhealthy {\n\t\t\t\tclusterUpdates <- Update{red, simpleStatus(red)}\n\t\t\t\tlog.Info(\"closing connection and reconnecting\")\n\t\t\t\terr := check.reconnect(stop)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Info(\"error while reconnecting:\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tlog.Info(\"reconnected\")\n\t\t\t} else {\n\t\t\t\tclusterStatus := check.checkClusterHealth()\n\t\t\t\tdata, err := json.Marshal(clusterStatus)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warn(\"Error while marshaling cluster status: %s\", err.Error())\n\t\t\t\t\tdata = simpleStatus(clusterStatus.Status)\n\t\t\t\t}\n\n\t\t\t\tclusterUpdates <- Update{clusterStatus.Status, data}\n\t\t\t}\n\t\tcase <-stop:\n\t\t\treturn\n\t\t}\n\t}\n}",
"func handleHealthCheck(w http.ResponseWriter, r *http.Request) (error, int) {\n\treturn httputil.SendJSON(w, map[string]string{\"status\": \"OK\"})\n}",
"func (h *healthCheckHandler) HealthCheck(c *gin.Context) {\n\n\terr := h.u.HealthCheck()\n\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"result\": statusUnhealty, \"metadata\": nil})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\"result\": statusHealthy, \"metadata\": nil})\n}",
"func HealthCheck(w http.ResponseWriter, r *http.Request) {\n\n\tvar err error\n\tvar bytes []byte\n\n\tapsc := gorillaContext.Get(r, \"apsc\").(push.Client)\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\thealthMsg := HealthStatus{\n\t\tStatus: \"ok\",\n\t}\n\n\tpwToken := gorillaContext.Get(r, \"push_worker_token\").(string)\n\tpushEnabled := gorillaContext.Get(r, \"push_enabled\").(bool)\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\n\tif pushEnabled {\n\t\t_, err := auth.GetPushWorker(pwToken, refStr)\n\t\tif err != nil {\n\t\t\thealthMsg.Status = \"warning\"\n\t\t}\n\n\t\thealthMsg.PushServers = []PushServerInfo{\n\t\t\t{\n\t\t\t\tEndpoint: apsc.Target(),\n\t\t\t\tStatus: apsc.HealthCheck(context.TODO()).Result(),\n\t\t\t},\n\t\t}\n\n\t} else {\n\t\thealthMsg.PushFunctionality = \"disabled\"\n\t}\n\n\tif bytes, err = json.MarshalIndent(healthMsg, \"\", \" \"); err != nil {\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\trespondOK(w, bytes)\n}",
"func appHealthChecks(db *sql.DB) ([]health.Checker, func()) {\n\tdbCheck := sqlhealth.New(db)\n\tlist := []health.Checker{dbCheck}\n\treturn list, func() {\n\t\tdbCheck.Stop()\n\t}\n}",
"func (w *WorkloadHealthChecker) PerformApplicationHealthCheck(callback func(*ProbeEvent), quit chan struct{}) {\n\tif w == nil {\n\t\treturn\n\t}\n\n\thealthCheckLog.Infof(\"starting health check for %T in %v\", w.prober, w.config.InitialDelay)\n\t// delay before starting probes.\n\ttime.Sleep(w.config.InitialDelay)\n\n\t// tracks number of success & failures after last success/failure\n\tnumSuccess, numFail := 0, 0\n\t// if the last send/event was a success, this is true, by default false because we want to\n\t// first send a healthy message.\n\tlastState := lastStateUndefined\n\n\tdoCheck := func() {\n\t\t// probe target\n\t\thealthy, err := w.prober.Probe(w.config.ProbeTimeout)\n\t\tif healthy.IsHealthy() {\n\t\t\thealthCheckLog.Debug(\"probe completed with healthy status\")\n\t\t\t// we were healthy, increment success counter\n\t\t\tnumSuccess++\n\t\t\t// wipe numFail (need consecutive success)\n\t\t\tnumFail = 0\n\t\t\t// if we reached the threshold, mark the target as healthy\n\t\t\tif numSuccess == w.config.SuccessThresh && lastState != lastStateHealthy {\n\t\t\t\thealthCheckLog.Info(\"success threshold hit, marking as healthy\")\n\t\t\t\tcallback(&ProbeEvent{Healthy: true})\n\t\t\t\tnumSuccess = 0\n\t\t\t\tlastState = lastStateHealthy\n\t\t\t}\n\t\t} else {\n\t\t\thealthCheckLog.Debugf(\"probe completed with unhealthy status: %v\", err)\n\t\t\t// we were not healthy, increment fail counter\n\t\t\tnumFail++\n\t\t\t// wipe numSuccess (need consecutive failure)\n\t\t\tnumSuccess = 0\n\t\t\t// if we reached the fail threshold, mark the target as unhealthy\n\t\t\tif numFail == w.config.FailThresh && lastState != lastStateUnhealthy {\n\t\t\t\thealthCheckLog.Infof(\"failure threshold hit, marking as unhealthy: %v\", err)\n\t\t\t\tnumFail = 0\n\t\t\t\tcallback(&ProbeEvent{\n\t\t\t\t\tHealthy: false,\n\t\t\t\t\tUnhealthyStatus: http.StatusInternalServerError,\n\t\t\t\t\tUnhealthyMessage: err.Error(),\n\t\t\t\t})\n\t\t\t\tlastState = lastStateUnhealthy\n\t\t\t}\n\t\t}\n\t}\n\n\t// Send the first request immediately\n\tdoCheck()\n\tperiodTicker := time.NewTicker(w.config.CheckFrequency)\n\tdefer periodTicker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-quit:\n\t\t\treturn\n\t\tcase <-periodTicker.C:\n\t\t\tdoCheck()\n\t\t}\n\t}\n}",
"func getContainersHealthCheck(cc v3.ComponentContainer) (livenesshandler corev1.Handler, readinesshandler corev1.Handler) {\n\t//log.Debugf(\"Container info is %v\", cc)\n\t//if !reflect.DeepEqual(cc.LivenessProbe, v3.HealthProbe{}) {\n\tif cc.LivenessProbe != nil {\n\t\tif cc.LivenessProbe.Exec != nil {\n\t\t\tif len(cc.LivenessProbe.Exec.Command) != 0 {\n\t\t\t\tvar commandlist []string\n\t\t\t\tfor _, i := range cc.LivenessProbe.Exec.Command {\n\t\t\t\t\tlist := strings.Split(i, \" \")\n\t\t\t\t\tcommandlist = append(commandlist, list...)\n\t\t\t\t}\n\t\t\t\tlivenesshandler = corev1.Handler{\n\t\t\t\t\tExec: &corev1.ExecAction{\n\t\t\t\t\t\tCommand: commandlist,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t} else if cc.LivenessProbe.HTTPGet != nil {\n\t\t\tif cc.LivenessProbe.HTTPGet.Path != \"\" && cc.LivenessProbe.HTTPGet.Port > 0 {\n\t\t\t\tlivenesshandler = corev1.Handler{\n\t\t\t\t\tHTTPGet: &corev1.HTTPGetAction{\n\t\t\t\t\t\tPath: cc.LivenessProbe.HTTPGet.Path,\n\t\t\t\t\t\tPort: intstr.IntOrString{\n\t\t\t\t\t\t\tType: intstr.Int,\n\t\t\t\t\t\t\tIntVal: int32(cc.LivenessProbe.HTTPGet.Port),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t} else if cc.LivenessProbe.TCPSocket != nil {\n\t\t\tif cc.LivenessProbe.TCPSocket.Port > 0 {\n\t\t\t\tlivenesshandler = corev1.Handler{\n\t\t\t\t\tTCPSocket: &corev1.TCPSocketAction{\n\t\t\t\t\t\tPort: intstr.IntOrString{\n\t\t\t\t\t\t\tIntVal: int32(cc.LivenessProbe.TCPSocket.Port),\n\t\t\t\t\t\t\tType: intstr.Int,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlivenesshandler = corev1.Handler{}\n\t\t}\n\t}\n\t//if !reflect.DeepEqual(cc.ReadinessProbe, v3.HealthProbe{}) {\n\tif cc.ReadinessProbe != nil {\n\t\tif cc.ReadinessProbe.Exec != nil {\n\t\t\tif len(cc.ReadinessProbe.Exec.Command) != 0 {\n\t\t\t\tvar commandlist []string\n\t\t\t\tfor _, i := range cc.ReadinessProbe.Exec.Command {\n\t\t\t\t\tlist := strings.Split(i, \" \")\n\t\t\t\t\tcommandlist = append(commandlist, list...)\n\t\t\t\t}\n\t\t\t\treadinesshandler = corev1.Handler{\n\t\t\t\t\tExec: &corev1.ExecAction{\n\t\t\t\t\t\tCommand: commandlist,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t} else if cc.ReadinessProbe.HTTPGet != nil {\n\t\t\tif cc.ReadinessProbe.HTTPGet.Path != \"\" && cc.ReadinessProbe.HTTPGet.Port > 0 {\n\t\t\t\treadinesshandler = corev1.Handler{\n\t\t\t\t\tHTTPGet: &corev1.HTTPGetAction{\n\t\t\t\t\t\tPath: cc.ReadinessProbe.HTTPGet.Path,\n\t\t\t\t\t\tPort: intstr.IntOrString{\n\t\t\t\t\t\t\tType: intstr.Int,\n\t\t\t\t\t\t\tIntVal: int32(cc.ReadinessProbe.HTTPGet.Port),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t} else if cc.ReadinessProbe.TCPSocket != nil {\n\t\t\tif cc.ReadinessProbe.TCPSocket.Port > 0 {\n\t\t\t\treadinesshandler = corev1.Handler{\n\t\t\t\t\tTCPSocket: &corev1.TCPSocketAction{\n\t\t\t\t\t\tPort: intstr.IntOrString{\n\t\t\t\t\t\t\tIntVal: int32(cc.ReadinessProbe.TCPSocket.Port),\n\t\t\t\t\t\t\tType: intstr.Int,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treadinesshandler = corev1.Handler{}\n\t\t}\n\t}\n\treturn\n}",
"func (a *infrastructureHandlers) healthCheck(c *gin.Context) {\n\tresponse := HealthCheckResponseSuccess{}\n\tresponse.BuildSha = os.Getenv(\"APP_BUILD_HASH\")\n\tresponse.Name = os.Getenv(\"APP_NAME\")\n\tresponse.Version = os.Getenv(\"APP_VERSION\")\n\tc.JSON(200, response)\n}",
"func healthCheck(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"Ready\"))\n}",
"func healthCheck(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}",
"func doHealth(sdk *sdk.SDK, stop <-chan struct{}) {\n\ttick := time.Tick(2 * time.Second)\n\tfor {\n\t\terr := sdk.Health()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Could not send health ping, %v\", err)\n\t\t}\n\t\tselect {\n\t\tcase <-stop:\n\t\t\tlog.Print(\"Stopped health pings\")\n\t\t\treturn\n\t\tcase <-tick:\n\t\t}\n\t}\n}",
"func (r *Runner) Run(signals <-chan os.Signal, ready chan<- struct{}) error {\n\tlogger := r.logger.Session(\"garden-health\")\n\thealthcheckTimeout := r.clock.NewTimer(r.timeoutInterval)\n\thealthcheckComplete := make(chan error, 1)\n\n\tlogger.Info(\"starting\")\n\n\tgo r.healthcheckCycle(logger, healthcheckComplete)\n\n\tselect {\n\tcase signal := <-signals:\n\t\tlogger.Info(\"signalled\", lager.Data{\"signal\": signal.String()})\n\t\treturn nil\n\n\tcase <-healthcheckTimeout.C():\n\t\tr.setUnhealthy(logger)\n\t\tr.checker.Cancel(logger)\n\t\tlogger.Info(\"timed-out\")\n\t\treturn HealthcheckTimeoutError{}\n\n\tcase err := <-healthcheckComplete:\n\t\tif err != nil {\n\t\t\tr.setUnhealthy(logger)\n\t\t\treturn err\n\t\t}\n\t\thealthcheckTimeout.Stop()\n\t}\n\n\tr.setHealthy(logger)\n\n\tclose(ready)\n\tlogger.Info(\"started\")\n\n\tstartHealthcheck := r.clock.NewTimer(r.checkInterval)\n\temitInterval := r.clock.NewTicker(r.emissionInterval)\n\tdefer emitInterval.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase signal := <-signals:\n\t\t\tlogger.Info(\"signalled-complete\", lager.Data{\"signal\": signal.String()})\n\t\t\treturn nil\n\n\t\tcase <-startHealthcheck.C():\n\t\t\thealthcheckTimeout.Reset(r.timeoutInterval)\n\t\t\tgo r.healthcheckCycle(logger, healthcheckComplete)\n\n\t\tcase <-healthcheckTimeout.C():\n\t\t\tr.setUnhealthy(logger)\n\t\t\tr.checker.Cancel(logger)\n\t\t\tr.metronClient.SendMetric(CellUnhealthyMetric, 1)\n\n\t\tcase <-emitInterval.C():\n\t\t\tr.emitUnhealthyCellMetric(logger)\n\n\t\tcase err := <-healthcheckComplete:\n\t\t\ttimeoutOk := healthcheckTimeout.Stop()\n\t\t\tswitch err.(type) {\n\t\t\tcase nil:\n\t\t\t\tif timeoutOk {\n\t\t\t\t\tr.setHealthy(logger)\n\t\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tr.setUnhealthy(logger)\n\t\t\t}\n\n\t\t\tstartHealthcheck.Reset(r.checkInterval)\n\t\t}\n\t}\n}",
"func createHealthChecks(gatewayUrl string) healthcheck.Handler {\n\thealth := healthcheck.NewHandler()\n\n\thealth.AddReadinessCheck(\"FRITZ!Box connection\",\n\t\thealthcheck.HTTPGetCheck(gatewayUrl+\"/any.xml\", time.Duration(3)*time.Second))\n\n\thealth.AddLivenessCheck(\"go-routines\", healthcheck.GoroutineCountCheck(100))\n\treturn health\n}",
"func (e *CityService) Healthcheck(ctx context.Context, req *cityservice.EmptyRequest, rsp *cityservice.Response) error {\n\tutil.WriteLogMain(\"Call Healthcheck Service\")\n\trsp.Msg = \"Success\"\n\treturn nil\n}",
"func TestHealthHandler(t *testing.T) {\n\t// clear out existing checks.\n\tDefaultRegistry = NewRegistry()\n\n\t// protect an http server\n\thandler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.WriteHeader(http.StatusNoContent)\n\t}))\n\n\t// wrap it in our health handler\n\thandler = Handler(handler)\n\n\t// use this swap check status\n\tupdater := NewStatusUpdater()\n\tRegister(\"test_check\", updater)\n\n\t// now, create a test server\n\tserver := httptest.NewServer(handler)\n\n\tcheckUp := func(t *testing.T, message string) {\n\t\tresp, err := http.Get(server.URL)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"error getting success status: %v\", err)\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tif resp.StatusCode != http.StatusNoContent {\n\t\t\tt.Fatalf(\"unexpected response code from server when %s: %d != %d\", message, resp.StatusCode, http.StatusNoContent)\n\t\t}\n\t\t// NOTE(stevvooe): we really don't care about the body -- the format is\n\t\t// not standardized or supported, yet.\n\t}\n\n\tcheckDown := func(t *testing.T, message string) {\n\t\tresp, err := http.Get(server.URL)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"error getting down status: %v\", err)\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tif resp.StatusCode != http.StatusServiceUnavailable {\n\t\t\tt.Fatalf(\"unexpected response code from server when %s: %d != %d\", message, resp.StatusCode, http.StatusServiceUnavailable)\n\t\t}\n\t}\n\n\t// server should be up\n\tcheckUp(t, \"initial health check\")\n\n\t// now, we fail the health check\n\tupdater.Update(fmt.Errorf(\"the server is now out of commission\"))\n\tcheckDown(t, \"server should be down\") // should be down\n\n\t// bring server back up\n\tupdater.Update(nil)\n\tcheckUp(t, \"when server is back up\") // now we should be back up.\n}",
"func doHealth(s *gosdk.SDK, stop <-chan struct{}) {\n\ttick := time.Tick(2 * time.Second)\n\tfor {\n\t\terr := s.Health()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Could not send health ping, %v\", err)\n\t\t}\n\t\tselect {\n\t\tcase <-stop:\n\t\t\tlog.Print(\"Stopped health pings\")\n\t\t\treturn\n\t\tcase <-tick:\n\t\t}\n\t}\n}",
"func (s Server) CheckHealthHandler(rw http.ResponseWriter, req *http.Request) {\n\trespMsg := struct {\n\t\tMessage string `json:\"message\"`\n\t}{\n\t\tMessage: \"Application is alive.\",\n\t}\n\ts.Log.Infof(\"Health check response: %v\", respMsg)\n\trespondSuccessJSON(rw, 200, respMsg)\n}",
"func healthcheck(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n}",
"func HealthCheckerMain(ctx context.Context, addr, component string, ctors ...injection.ControllerConstructor) {\n\tvar wrappers []injection.ControllerConstructor\n\thcs := sync.Map{}\n\n\t// We need to wait for each controller to be constructed and checked\n\t// before the health endpoint will be ready.\n\tctorsWg := sync.WaitGroup{}\n\tctorsWg.Add(len(ctors))\n\n\t// Find all the HealthCheckers\n\tfor i := range ctors {\n\t\tctor := ctors[i]\n\n\t\t// Wrap the given ControllerConstructor so that the resulting\n\t\t// controller can be check to see if it implements HealthChecker. If\n\t\t// it does, then keep track of it so that its health can be polled.\n\t\twrappers = append(wrappers, func(ctx context.Context, cmw configmap.Watcher) *controller.Impl {\n\t\t\tctorsWg.Done()\n\t\t\tctrl := ctor(ctx, cmw)\n\t\t\tif hc, ok := ctrl.Reconciler.(HealthChecker); ok {\n\t\t\t\thcs.Store(hc, ctx)\n\t\t\t}\n\t\t\treturn ctrl\n\t\t})\n\t}\n\n\t// Poll the HealthCheckers. If there is an empty list of HealthCheckers,\n\t// then default to healthy. Otherwise default to unhealthy so that the\n\t// status starts out as not ready.\n\thealthyInt := int32(0)\n\tgo func() {\n\t\tctorsWg.Wait()\n\n\t\t// Poll HealthCheckers\n\t\tfor range time.Tick(5 * time.Second) {\n\t\t\t// Check health\n\t\t\thealthy := int32(1)\n\t\t\thcs.Range(func(key, value interface{}) bool {\n\t\t\t\t// Don't type check because we want this to panic if this gets\n\t\t\t\t// messed up from earlier in the function.\n\t\t\t\thc := key.(HealthChecker)\n\t\t\t\tctx, cancel := context.WithTimeout(value.(context.Context), 30*time.Second)\n\t\t\t\tdefer cancel()\n\n\t\t\t\tif err := hc.Healthy(ctx); err != nil {\n\t\t\t\t\tlogging.FromContext(ctx).Warnf(\"health check failed: %v\", err)\n\t\t\t\t\thealthy = 0\n\t\t\t\t}\n\n\t\t\t\t// Only continue if we're still healthy\n\t\t\t\treturn healthy == 1\n\t\t\t})\n\n\t\t\t// Update status\n\t\t\tatomic.StoreInt32(&healthyInt, healthy)\n\t\t}\n\t}()\n\n\t// Start the health check endpoint on the given address.\n\tgo func() {\n\t\tctorsWg.Wait()\n\n\t\tlog.Fatal(http.ListenAndServe(addr, http.HandlerFunc(\n\t\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tif atomic.LoadInt32(&healthyInt) != 1 {\n\t\t\t\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tw.WriteHeader(http.StatusNoContent)\n\t\t\t},\n\t\t)))\n\t}()\n\n\tsharedmain.MainWithContext(ctx, component, wrappers...)\n}",
"func (h *StandHystrix) doCheck() {\n\tif h.checkAliveFunc == nil || h.checkHystrixFunc == nil {\n\t\treturn\n\t}\n\tif h.IsHystrix() {\n\t\tisAlive := h.checkAliveFunc()\n\t\tif isAlive {\n\t\t\th.TriggerAlive()\n\t\t\th.GetCounter().Clear()\n\t\t\ttime.AfterFunc(time.Duration(h.checkHystrixInterval)*time.Second, h.doCheck)\n\t\t} else {\n\t\t\ttime.AfterFunc(time.Duration(h.checkAliveInterval)*time.Second, h.doCheck)\n\t\t}\n\t} else {\n\t\tisHystrix := h.checkHystrixFunc()\n\t\tif isHystrix {\n\t\t\th.TriggerHystrix()\n\t\t\ttime.AfterFunc(time.Duration(h.checkAliveInterval)*time.Second, h.doCheck)\n\t\t} else {\n\t\t\ttime.AfterFunc(time.Duration(h.checkHystrixInterval)*time.Second, h.doCheck)\n\t\t}\n\t}\n}",
"func (notifier *HTTPNotifier) Healthcheck() health.Status {\n\tqueueSize, err := database.CountNotificationsToSend()\n\treturn health.Status{IsEssential: false, IsHealthy: err == nil, Details: struct{ QueueSize int }{QueueSize: queueSize}}\n}",
"func (m *Monitor) HealthCheck(healthChannel chan bool) {\n\tres, resErr := http.Get(fmt.Sprintf(\"http://%s\", *m.MasterIP))\n\tif resErr != nil {\n\t\tlog.Println(resErr)\n\t\thealthChannel <- false\n\t} else if res.Status != \"200 OK\" {\n\t\tlog.Println(fmt.Errorf(\"healthcheck responded with status other than 200 OK, %s\", res.Status))\n\t\thealthChannel <- false\n\t} else {\n\t\tlog.Println(*m.MasterIP, \"passes health check\")\n\t\thealthChannel <- true\n\t}\n\treturn\n}",
"func Check(\n\thealthCheckFunc func() bool,\n\tpollDelay time.Duration,\n\thealthTimeout time.Duration,\n\tupdates chan<- bool,\n\tquit <-chan struct{},\n) {\n\tgo check(healthCheckFunc, pollDelay,\n\t\thealthTimeout, updates, quit)\n}",
"func (check *HealthCheck) ServeHealth(brokerUpdates <-chan Update, clusterUpdates <-chan Update, stop <-chan struct{}) {\n\tport := check.config.statusServerPort\n\n\tstatusServer := func(name, path, errorStatus string, updates <-chan Update) {\n\t\trequests := make(chan chan Update)\n\n\t\t// goroutine that encapsulates the current status\n\t\tgo func() {\n\t\t\tstatus := Update{errorStatus, simpleStatus(errorStatus)}\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase update := <-updates:\n\n\t\t\t\t\tif !bytes.Equal(status.Data, update.Data) {\n\t\t\t\t\t\tlog.WithField(\"status\", string(update.Data)).Info(name, \" now reported as \", update.Status)\n\t\t\t\t\t\tstatus = update\n\t\t\t\t\t}\n\n\t\t\t\tcase request := <-requests:\n\t\t\t\t\trequest <- status\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\thttp.HandleFunc(path, func(writer http.ResponseWriter, request *http.Request) {\n\t\t\tresponseChannel := make(chan Update)\n\t\t\trequests <- responseChannel\n\t\t\tcurrentStatus := <-responseChannel\n\t\t\tif currentStatus.Status == errorStatus {\n\t\t\t\thttp.Error(writer, string(currentStatus.Data), 500)\n\t\t\t} else {\n\t\t\t\twriter.Write(currentStatus.Data)\n\t\t\t\tio.WriteString(writer, \"\\n\")\n\t\t\t}\n\t\t})\n\t}\n\n\thttp.DefaultServeMux = http.NewServeMux()\n\tstatusServer(\"cluster\", \"/cluster\", red, clusterUpdates)\n\tstatusServer(\"broker\", \"/\", unhealthy, brokerUpdates)\n\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", port))\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to listen to port \", port, \": \", err)\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-stop:\n\t\t\t\tlistener.Close()\n\t\t\t}\n\t\t}\n\t}()\n\thttp.Serve(listener, nil)\n\treturn\n}",
"func (fwdclient *Client) HealthCheck() error {\n\tlog.Debugf(\"%s: url=%s\", fwdclient.AppName, fwdclient.ActionUrls.Health)\n\treq, err := http.NewRequest(\"GET\", fwdclient.ActionUrls.Health, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Splunk %s\", fwdclient.Token))\n\tresp, err := fwdclient.httpclient.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\" Please check splunk authorization token. %s: Health check failed: %s\", fwdclient.AppName, err)\n\t}\n\tdefer resp.Body.Close()\n\tlog.Debugf(\"%s: status=%d %s\", fwdclient.AppName, resp.StatusCode, http.StatusText(resp.StatusCode))\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"%s: Failed during Health check : %d %s\", fwdclient.AppName, resp.StatusCode, http.StatusText(resp.StatusCode))\n\t}\n\trespBody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: Failed while reading health response body: %s\", fwdclient.AppName, err)\n\t}\n\thealthCheckResponse := new(HealthCheckResponse)\n\tif err := json.Unmarshal(respBody, healthCheckResponse); err != nil {\n\t\treturn fmt.Errorf(\"%s: health check failed: the response is not JSON but: %s\", fwdclient.AppName, respBody)\n\t}\n\tlog.Debugf(\"%s: code=%d, text=%s\", fwdclient.AppName, healthCheckResponse.Code, healthCheckResponse.Text)\n\treturn nil\n}",
"func (p *RoundRobinPool) HealthCheck() {\n\n\tt := time.NewTicker(time.Minute * 2)\n\tfor {\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\tlog.Println(\"starting health check...\")\n\t\t\tp.HealthCheckUp()\n\t\t\tlog.Println(\"Health check completed\")\n\t\t}\n\t}\n}",
"func (c *anypointClient) healthcheck(name string) (status *hc.Status) {\n\t// Create the default status\n\tstatus = &hc.Status{\n\t\tResult: hc.OK,\n\t}\n\n\tuser, err := c.GetCurrentUser()\n\tif err != nil {\n\t\tstatus = &hc.Status{\n\t\t\tResult: hc.FAIL,\n\t\t\tDetails: fmt.Sprintf(\"%s Failed. Unable to connect to Mulesoft, check Mulesoft configuration. %s\", name, err.Error()),\n\t\t}\n\t}\n\tif user == nil {\n\t\tstatus = &hc.Status{\n\t\t\tResult: hc.FAIL,\n\t\t\tDetails: fmt.Sprintf(\"%s Failed. Unable to connect to Mulesoft, check Mulesoft configuration.\", name),\n\t\t}\n\t}\n\n\treturn status\n}",
"func healthCheckHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"OK\")\n}",
"func (h *handler) health(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"OK\")\n}",
"func (c *Check) Health(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\tctx, span := trace.StartSpan(ctx, \"handlers.Check.Health\")\n\tdefer span.End()\n\n\tvar health struct {\n\t\tStatus string `json:\"status\"`\n\t}\n\n\t// Check if the database is ready.\n\tif err := database.StatusCheck(ctx, c.db); err != nil {\n\n\t\t// If the database is not ready we will tell the client and use a 500\n\t\t// status. Do not respond by just returning an error because further up in\n\t\t// the call stack will interpret that as an unhandled error.\n\t\thealth.Status = \"db not ready\"\n\t\treturn web.Respond(ctx, w, health, http.StatusInternalServerError)\n\t}\n\n\thealth.Status = \"ok\"\n\treturn web.Respond(ctx, w, health, http.StatusOK)\n}",
"func checkHealth(server *domain.Server) {\n\t// We will consider a server to be healthy if we can open a tcp connection\n\t// to the host:port of the server within a reasonable time frame.\n\t_, err := net.DialTimeout(\"tcp\", server.Url.Host, time.Second*5)\n\tif err != nil {\n\t\tlog.Errorf(\"Could not connect to the server at '%s'\", server.Url.Host)\n\t\told := server.SetLiveness(false)\n\t\tif old {\n\t\t\tlog.Warnf(\"Transitioning server '%s' from Live to Unavailable state\", server.Url.Host)\n\t\t}\n\t\treturn\n\t}\n\told := server.SetLiveness(true)\n\tif !old {\n\t\tlog.Infof(\"Transitioning server '%s' from Unavailable to Live state\", server.Url.Host)\n\t}\n}",
"func healthCheck(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Status OK.\\n\")\n}",
"func healthcheck(ha *lib.HTTPAdapter) {\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"/health\", ha.HealthHandler).Methods(\"GET\")\n\taddr := fmt.Sprintf(\"127.0.0.1:%v\", serverConfig.HealthcheckHTTPport)\n\tserver := &http.Server{Addr: addr, Handler: r}\n\tlogger.Printf(\"HTTP healthcheck listening on: %v\", addr)\n\tlogger.Println(server.ListenAndServe())\n}",
"func (server *Server) handleGetHealthz(c *gin.Context) {\n\terrs := make([]serviceError, 0)\n\tfor name, service := range server.services {\n\t\tif err := service.Healthy(); err != nil {\n\t\t\terrs = append(errs, serviceError{name, err.Error()})\n\t\t}\n\t}\n\tif len(errs) > 0 {\n\t\tc.JSON(500, errs)\n\t} else {\n\t\tc.JSON(200, errs)\n\t}\n}",
"func main() {\n\n\t// Create a new Checker\n\tchecker := health.NewChecker(\n\t\t// A simple successFunc to see if a fake file system up.\n\t\thealth.WithCheck(health.Check{\n\t\t\tName: \"filesystem\",\n\t\t\tTimeout: 2 * time.Second, // A successFunc specific timeout.\n\t\t\tInterceptors: []health.Interceptor{createCheckLogger, logCheck},\n\t\t\tCheck: func(ctx context.Context) error {\n\t\t\t\treturn fmt.Errorf(\"this is a check error\") // example error\n\t\t\t},\n\t\t}),\n\t)\n\n\thandler := health.NewHandler(checker, health.WithMiddleware(createRequestLogger, logRequest))\n\n\t// We Create a new http.Handler that provides health successFunc information\n\t// serialized as a JSON string via HTTP.\n\thttp.Handle(\"/health\", handler)\n\thttp.ListenAndServe(\":3000\", nil)\n}",
"func Healthcheck(context *gin.Context) {\n\tcontext.JSON(http.StatusOK, gin.H{\"message\": \"App up and running\"})\n}",
"func (manager *Manager) InitializeHealthChecks(h *healthcheck.Manager) {\n\tlog := logging.For(\"core/healthcheck/init\").WithField(\"func\", \"healthcheck\")\n\tvar expectedWorkers []*healthcheck.Worker\n\tvar expectedNodes []string\n\tvar newUUIDForExistingWorkers []*healthcheck.Worker\n\tfor poolName, pool := range config.Get().Loadbalancer.Pools {\n\t\t// Create workers for pool checks\n\t\tvar poolWorkers []*healthcheck.Worker\n\t\tfor _, check := range pool.HealthChecks {\n\t\t\tsourceip := pool.Listener.IP\n\t\t\tif pool.Listener.SourceIP != \"\" {\n\t\t\t\tsourceip = pool.Listener.SourceIP\n\t\t\t}\n\t\t\tworker := healthcheck.NewWorker(poolName, \"\", \"\", \"\", check.IP, check.Port, sourceip, check, h.Incoming)\n\t\t\tpoolWorkers = append(poolWorkers, worker)\n\t\t}\n\t\tfor backendName, backend := range config.Get().Loadbalancer.Pools[poolName].Backends {\n\t\t\tvar backendWorkers []*healthcheck.Worker\n\t\t\t// Create workers for backend checks\n\t\t\tfor _, check := range backend.HealthChecks {\n\t\t\t\tif check.IP != \"\" {\n\t\t\t\t\tsourceip := pool.Listener.IP\n\t\t\t\t\tif pool.Listener.SourceIP != \"\" {\n\t\t\t\t\t\tsourceip = pool.Listener.SourceIP\n\t\t\t\t\t}\n\t\t\t\t\tworker := healthcheck.NewWorker(poolName, backendName, \"\", \"\", check.IP, check.Port, sourceip, check, h.Incoming)\n\t\t\t\t\tbackendWorkers = append(backendWorkers, worker)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, node := range backend.Nodes {\n\t\t\t\tvar nodeWorkers []*healthcheck.Worker\n\t\t\t\t// For each node\n\t\t\t\tfor _, check := range backend.HealthChecks {\n\t\t\t\t\tif check.IP == \"\" {\n\t\t\t\t\t\tsourceip := pool.Listener.IP\n\t\t\t\t\t\tif pool.Listener.SourceIP != \"\" {\n\t\t\t\t\t\t\tsourceip = pool.Listener.SourceIP\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tport := node.Port\n\t\t\t\t\t\tif check.Port != 0 {\n\t\t\t\t\t\t\tport = check.Port\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Create workers for node specific checks\n\t\t\t\t\t\tworker := healthcheck.NewWorker(poolName, backendName, node.Name(), node.UUID, node.IP, port, sourceip, check, h.Incoming)\n\t\t\t\t\t\tnodeWorkers = append(nodeWorkers, worker)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Register all checks applicable to this node\n\t\t\t\tvar nodeChecks []string\n\t\t\t\tfor _, w := range nodeWorkers {\n\t\t\t\t\tnodeChecks = append(nodeChecks, w.UUID())\n\t\t\t\t}\n\n\t\t\t\tfor _, w := range backendWorkers {\n\t\t\t\t\tnodeChecks = append(nodeChecks, w.UUID())\n\t\t\t\t}\n\n\t\t\t\tfor _, w := range poolWorkers {\n\t\t\t\t\tnodeChecks = append(nodeChecks, w.UUID())\n\t\t\t\t}\n\n\t\t\t\t// Register all checks applicable to the node UUID\n\t\t\t\tnew := h.SetCheckPool(node.UUID, poolName, backendName, node.Name(), backend.HealthCheckMode, nodeChecks)\n\t\t\t\tif new {\n\t\t\t\t\tnewUUIDForExistingWorkers = append(newUUIDForExistingWorkers, nodeWorkers...)\n\t\t\t\t}\n\n\t\t\t\t// keep track of all existing nodes\n\t\t\t\texpectedNodes = append(expectedNodes, node.UUID)\n\n\t\t\t\t// Register worker for node checks\n\t\t\t\texpectedWorkers = append(expectedWorkers, nodeWorkers...)\n\t\t\t}\n\t\t\t// Register worker for backend checks\n\t\t\texpectedWorkers = append(expectedWorkers, backendWorkers...)\n\t\t}\n\t\t// Register worker for pool checks\n\t\texpectedWorkers = append(expectedWorkers, poolWorkers...)\n\t}\n\n\t// Clean up existing workers\n\tlog.WithField(\"current\", len(h.Workers)).WithField(\"expected\", len(expectedWorkers)).Debug(\"Workers count\")\n\t// current workers\n\tvar removeWorkers []int\n\tcurrent := h.Workers\n\tfor cid, cworker := range current {\n\t\t// go through all current workers\n\t\tfound := false\n\n\t\t// Get copy of existing worker, and trim them to keep removableProxy list\n\t\tvar expected []*healthcheck.Worker\n\t\tfor _, worker := range expectedWorkers {\n\t\t\texpected = append(expected, worker)\n\t\t}\n\n\t\t// Compare UUID of existing workers with collected workers\n\t\tfor eid, eworker := range expected {\n\t\t\t// if UUID matches, we don't need to recreate the check\n\t\t\tif cworker.UUID() == eworker.UUID() {\n\t\t\t\tlog.Debugf(\"Existing worker check: current:%s new:%s\", cworker.UUID(), eworker.UUID())\n\t\t\t\t// we have a matching current with expected check, no need to add it again\n\t\t\t\texpectedWorkers = append(expectedWorkers[:eid], expectedWorkers[eid+1:]...)\n\t\t\t\tfound = true\n\n\t\t\t\t// also check if this is part of the list with new NodeUUID's\n\t\t\t\tfor _, nworker := range newUUIDForExistingWorkers {\n\t\t\t\t\tif cworker.UUID() == nworker.UUID() {\n\t\t\t\t\t\tlog.Debugf(\"Refresh worker check: current:%s new:%s\", cworker.UUID(), eworker.UUID())\n\n\t\t\t\t\t\tcworker.Poll()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif found == false {\n\t\t\t// stop worker, its no longer expected\n\t\t\tlog.Debugf(\"Nonexisting worker check: current:%s \", cworker.UUID())\n\t\t\tremoveWorkers = append(removeWorkers, cid)\n\t\t}\n\t}\n\n\tlog.WithField(\"count\", len(removeWorkers)).Debug(\"Workers to be stopped\")\n\tfor _, id := range reverse(removeWorkers) {\n\t\tlog.WithField(\"id\", id).Debug(\"Stopping worker\")\n\t\th.StopWorker(id)\n\t}\n\n\t// expectedChecks no longer contains the active workers, so these need to be started regardless\n\tlog.WithField(\"count\", len(expectedWorkers)).Debug(\"Workers to be started\")\n\tfor _, worker := range expectedWorkers {\n\t\tlog.WithField(\"id\", worker.UUID()).Debug(\"Starting worker\")\n\t\th.RegisterWorker(worker)\n\t\tworker.Start()\n\t}\n\n\tlog.WithField(\"count\", len(expectedWorkers)).Debug(\"Workers running\")\n\n\t// clean up node data\n\th.CleanNodeTracker(expectedNodes)\n}",
"func checkEnvoyStats(host string, port uint16) error {\n\tstate, ws, err := util.GetReadinessStats(host, port)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get readiness stats: %v\", err)\n\t}\n\n\tif state != nil && admin.ServerInfo_State(*state) != admin.ServerInfo_LIVE {\n\t\treturn fmt.Errorf(\"server is not live, current state is: %v\", admin.ServerInfo_State(*state).String())\n\t}\n\n\tif !ws {\n\t\treturn fmt.Errorf(\"workers have not yet started\")\n\t}\n\n\treturn nil\n}",
"func (c *Connection) healthCheck() {\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(healthCheckTime):\n\t\t\tif !c.Retrying {\n\t\t\t\t// capture current rmq host\n\t\t\t\toldHost := c.Config.Host\n\n\t\t\t\tif err := c.validateHost(); err != nil {\n\t\t\t\t\tkillService(\"failed to validate rmq host: \", err)\n\t\t\t\t}\n\n\t\t\t\t// this means new host was assigned meanwhile (in c.validateHost())\n\t\t\t\tif oldHost != c.Config.Host {\n\t\t\t\t\tif err := c.recreateConn(); err != nil {\n\t\t\t\t\t\tkillService(\"failed to recreate rmq connection: \", err)\n\t\t\t\t\t}\n\n\t\t\t\t\tlog.Println(\"rmq connected to new host: \", c.Config.Host)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"func (s *Server) HealthCheckHandler(w http.ResponseWriter, r *http.Request) {\n\ttime.Sleep(time.Duration(s.Config.Delay) * time.Second)\n\tstatus := 200\n\tif !s.Config.Healthy {\n\t\tstatus = 500\n\t}\n\tw.WriteHeader(status)\n\tlog.Info(\"host: \", r.Host, \" uri: \", r.RequestURI, \" status: \", status)\n\n}",
"func doHealthcheck(ctx context.Context) {\n\t_, err := State(ctx)\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\tos.Exit(0)\n}",
"func healthcheckHandler(w http.ResponseWriter, req *http.Request) {\n\tport := req.Header.Get(\"Original-Tcp-Port\")\n\tif port == \"\" {\n\t\tmsg := \"Header Original-Tcp-Port not found in request\"\n\t\tlog.Error().Msg(msg)\n\t\tsetHealthcheckResponse(w, http.StatusBadRequest, msg)\n\t\treturn\n\t}\n\n\taddress := fmt.Sprintf(\"%s:%s\", constants.LocalhostIPAddress, port)\n\tconn, err := net.Dial(\"tcp\", address)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Failed to establish connection to %s\", address)\n\t\tlog.Error().Err(err).Msg(msg)\n\t\tsetHealthcheckResponse(w, http.StatusNotFound, msg)\n\t\treturn\n\t}\n\n\tif err = conn.Close(); err != nil {\n\t\tlog.Error().Err(err).Msgf(\"Failed to close connection to %s\", address)\n\t}\n\n\tmsg := fmt.Sprintf(\"Successfully established connection to %s\", address)\n\tlog.Debug().Msg(msg)\n\tsetHealthcheckResponse(w, http.StatusOK, msg)\n}",
"func (s *Status) Check() HealthResult {\n\thr := HealthResult{\n\t\tName: s.name,\n\t\tDescription: s.description,\n\t\tCheckResults: make([]healthResultEntry, len(s.checkers)),\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(s.checkers))\n\n\tfor i, ch := range s.checkers {\n\t\tgo func(i int, ch checker) {\n\t\t\tdefer wg.Done()\n\n\t\t\tvar cr CheckResponse\n\t\t\tch.checkFunc(&cr)\n\t\t\thr.CheckResults[i] = healthResultEntry{\n\t\t\t\tName: ch.name,\n\t\t\t\tHealth: cr.health,\n\t\t\t\tOutput: cr.output,\n\t\t\t\tAction: cr.action,\n\t\t\t\tImpact: cr.impact,\n\t\t\t}\n\t\t\ts.updateCheckMetrics(ch, cr)\n\t\t}(i, ch)\n\t}\n\n\twg.Wait()\n\n\tvar seenHealthy, seenDegraded, seenUnhealthy bool\n\tfor _, hcr := range hr.CheckResults {\n\t\tswitch hcr.Health {\n\t\tcase healthy:\n\t\t\tseenHealthy = true\n\t\tcase degraded:\n\t\t\tseenDegraded = true\n\t\tcase unhealthy:\n\t\t\tseenUnhealthy = true\n\t\t}\n\t}\n\n\tswitch {\n\tcase seenUnhealthy:\n\t\thr.Health = unhealthy\n\tcase seenDegraded:\n\t\thr.Health = degraded\n\tcase seenHealthy:\n\t\thr.Health = healthy\n\tdefault:\n\t\t// We have no health checks. Assume unhealthy.\n\t\thr.Health = unhealthy\n\t}\n\n\treturn hr\n}",
"func GlooctlCheckEventuallyHealthy(offset int, testHelper *helper.SoloTestHelper, timeoutInterval string) {\n\tEventuallyWithOffset(offset, func() error {\n\t\tcontextWithCancel, cancel := context.WithCancel(context.Background())\n\t\tdefer cancel()\n\t\topts := &options.Options{\n\t\t\tMetadata: core.Metadata{\n\t\t\t\tNamespace: testHelper.InstallNamespace,\n\t\t\t},\n\t\t\tTop: options.Top{\n\t\t\t\tCtx: contextWithCancel,\n\t\t\t},\n\t\t}\n\t\terr := check.CheckResources(opts)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"glooctl check detected a problem with the installation\")\n\t\t}\n\t\treturn nil\n\t}, timeoutInterval, \"5s\").Should(BeNil())\n}",
"func (service *DaemonHeartbeat) Check(ctx context.Context, req *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {\n\n\theartbeat, err := GetHeartbeat(config.GetString(config.HeartbeatServiceEndpoint), config.GetString(config.ServiceHeartbeatType),\n\t\tconfig.GetString(config.ServiceId))\n\n\tif strings.Compare(heartbeat.Status, Online.String()) == 0 {\n\t\treturn &grpc_health_v1.HealthCheckResponse{Status: grpc_health_v1.HealthCheckResponse_SERVING}, nil\n\t}\n\n\treturn &grpc_health_v1.HealthCheckResponse{Status: grpc_health_v1.HealthCheckResponse_SERVICE_UNKNOWN}, errors.New(\"Service heartbeat unknown \" + err.Error())\n}",
"func (a *Agent) CheckHealth() error {\n\tif hc.RunChecks() != hc.OK {\n\t\treturn utilErrors.ErrInitServicesNotReady\n\t}\n\treturn nil\n}",
"func HealthHandler(w http.ResponseWriter, _ *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(healthMsg) //nolint:errcheck\n}",
"func (h *HealthImpl) Check(ctx context.Context, req *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {\n\n\treturn &grpc_health_v1.HealthCheckResponse{\n\t\tStatus: grpc_health_v1.HealthCheckResponse_SERVING,\n\t}, nil\n}",
"func serveHealthCheck() {\n\tln, err := net.ListenTCP(\"tcp\", &net.TCPAddr{Port: 85})\n\tif err != nil {\n\t\tlog.Critical(nil, \"could not begin health check listener; %v\", err)\n\t}\n\tdefer ln.Close()\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tlog.Err(nil, \"could not accept health check request\", err)\n\t\t\tcontinue\n\t\t}\n\t\t// The load balancer sends a particular string and expects it echoed back.\n\t\tif _, err := io.Copy(conn, conn); err != nil {\n\t\t\tlog.Err(nil, \"could not write health check response\", err)\n\t\t}\n\t\tconn.Close()\n\t}\n}",
"func TestWebServerNotOK(t *testing.T) {\n\n\tctx, _ := context.WithCancel(context.Background())\n\n\t// create a new kuberhealthy\n\tkh := makeTestKuberhealthy(t)\n\n\t// add a fake check to it with a not ok return\n\tfc := NewFakeCheck()\n\tdesiredError := randomdata.SillyName()\n\tfc.Errors = []string{desiredError}\n\tfc.OK = false\n\tkh.AddCheck(fc)\n\n\t// run the checker for enough time to make and update CRD entries, then stop it\n\tgo kh.Start(ctx)\n\ttime.Sleep(time.Second * 5)\n\tkh.StopChecks()\n\n\t// now run our test against the web server handler\n\trecorder := httptest.NewRecorder()\n\treq, err := http.NewRequest(\"GET\", \"/\", bytes.NewBufferString(\"\"))\n\tif err != nil {\n\t\tt.Fatal(\"Error creating request\", err)\n\t}\n\terr = kh.healthCheckHandler(recorder, req)\n\tif err != nil {\n\t\tt.Fatal(\"Error from health check handler:\", err)\n\t}\n\n\t// check the http status from the server\n\tif recorder.Code != http.StatusOK {\n\t\tt.Fatal(\"Bad response from handler\", recorder.Code)\n\t}\n\n\t// output the response from the server\n\tb, err := ioutil.ReadAll(recorder.Body)\n\tif err != nil {\n\t\tt.Fatal(\"Error reading response body\", err)\n\t}\n\tt.Log(string(b))\n\n\t// decode the response body to validate the contents\n\tvar state health.State\n\tjson.Unmarshal(b, &state)\n\n\tif len(state.Errors) < 1 {\n\t\tt.Fatal(\"The expected error message was not set.\")\n\t}\n\tif state.Errors[0] != desiredError {\n\t\tt.Fatal(\"The expected error message was not set. Got\", state.Errors[0], \"wanted\", desiredError)\n\t}\n\n\t// check that OK is false\n\tif state.OK != false {\n\t\tt.Fatal(\"Did not observe status page failure when one was expected\")\n\t}\n\n}",
"func (h *HealthImpl) HandleHealthCheck(w http.ResponseWriter, r *http.Request) {\n\tif h.isHealthy {\n\t\tresponse.RespondWithMessage(w, http.StatusOK, \"OK\")\n\t} else {\n\t\tif h.isPreparingShutdown {\n\t\t\tresponse.RespondWithPreparingShutdown(w)\n\t\t} else {\n\t\t\tresponse.RespondWithUnhealthy(w)\n\t\t}\n\t}\n}",
"func healthHandler(response http.ResponseWriter, req *http.Request, rcvr *receiver.Receiver) {\n\tdefer req.Body.Close()\n\tresponse.Header().Set(\"Content-Type\", \"application/json\")\n\n\trcvr.StateLock.Lock()\n\tdefer rcvr.StateLock.Unlock()\n\n\tvar lastChanged time.Time\n\tif rcvr.CurrentState != nil {\n\t\tlastChanged = rcvr.CurrentState.LastChanged\n\t}\n\n\tmessage, _ := json.Marshal(ApiStatus{\n\t\tMessage: \"Healthy!\",\n\t\tLastChanged: lastChanged,\n\t\tServiceChanged: rcvr.LastSvcChanged,\n\t})\n\n\tresponse.Write(message)\n}",
"func (c Checks) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tvar errFound bool\n\tfor _, check := range c.Checks {\n\t\terr := check.Check(c.Context)\n\t\tif err != nil {\n\t\t\tif c.Logger != nil {\n\t\t\t\tc.Logger(\"Error performing health check for %T (%s): %+v\\n\", check, check.LogInfo(c.Context), err)\n\t\t\t}\n\t\t\terrFound = true\n\t\t}\n\t}\n\tif errFound {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"Everything is on fire and nothing is okay.\"))\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(\"OK\"))\n}",
"func (a *Agent) handleCheck(payload []byte) error {\n\trequest := &v2.CheckRequest{}\n\tif err := json.Unmarshal(payload, request); err != nil {\n\t\treturn err\n\t} else if request == nil {\n\t\treturn errors.New(\"given check configuration appears invalid\")\n\t}\n\n\t// only schedule check execution if its not already in progress\n\t// ** check hooks are part of a checks execution\n\ta.inProgressMu.Lock()\n\t_, in := a.inProgress[request.Config.Name]\n\ta.inProgressMu.Unlock()\n\tif !in {\n\t\tlogger.Info(\"scheduling check execution: \", request.Config.Name)\n\n\t\tif ok := a.prepareCheck(request.Config); !ok {\n\t\t\t// An error occured during the preparation of the check and the error has\n\t\t\t// been sent back to the server. At this point we should not execute the\n\t\t\t// check and wait for the next check request\n\t\t\treturn nil\n\t\t}\n\n\t\tgo a.executeCheck(request)\n\t} else {\n\t\treturn fmt.Errorf(\"check execution still in progress: %s\", request.Config.Name)\n\t}\n\n\treturn nil\n}",
"func (r *checker) DoChecks() {\n\tfor _, check := range r.checks {\n\t\tcheck.result.LastCheck = time.Now()\n\t\tcheck.result.Count++\n\t\tcheck.result.LastStatus, check.result.LastMessage = check.Exec()\n\n\t\tlog.Debugf(\"%s health check: status=%s, message=%s\", check.Name, check.result.LastStatus, check.result.LastMessage)\n\t}\n}",
"func handleHealthCheck(c *Context, w http.ResponseWriter, _ *http.Request) {\n\tbuildInfo := make(map[string]string)\n\tbuildInfo[\"buildHash\"] = buildHash\n\tbuildInfo[\"buildHashShort\"] = buildHashShort\n\n\tdetails := make(map[string]map[string]string)\n\tdetails[\"buildInfo\"] = buildInfo\n\n\tresponse := healthCheckResponse{\n\t\tStatus: \"pass\",\n\t\tVersion: \"1\",\n\t\tReleaseID: buildTag,\n\t\tDetails: details,\n\t\tDescription: \"The stateless HTTP service backing the Mattermost marketplace\",\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/health+json\")\n\toutputJSON(c, w, response)\n}",
"func (c *controller) health(w http.ResponseWriter, r *http.Request) {\n\tlogger.Trace(\"health check\")\n\tw.WriteHeader(http.StatusNoContent)\n}",
"func (s *HealthServer) Check(ctx context.Context, in *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {\n\tlog.Printf(\"Handling Check request [%v]\", in)\n\treturn &healthpb.HealthCheckResponse{Status: healthpb.HealthCheckResponse_SERVING}, nil\n}",
"func (hc *HealthService) Check(ctx context.Context, request *grpchealthv1.HealthCheckRequest) (*grpchealthv1.HealthCheckResponse, error) {\n\tif request == nil {\n\t\tst := status.New(codes.InvalidArgument, \"health check request is nil\")\n\t\treturn createHealthCheckResponse(grpchealthv1.HealthCheckResponse_UNKNOWN), st.Err()\n\t}\n\n\tif err := hc.checker.Check(ctx); err != nil {\n\t\treturn createHealthCheckResponse(grpchealthv1.HealthCheckResponse_NOT_SERVING), err\n\t}\n\treturn createHealthCheckResponse(grpchealthv1.HealthCheckResponse_SERVING), nil\n}",
"func testHealth(service *bridge.Service, client fargo.EurekaConnection, elbReg *fargo.Instance) {\n\tcontainerID := service.Origin.ContainerID\n\n\t// Get actual eureka status and lookup previous logical registration status\n\teurekaStatus := getELBStatus(client, elbReg)\n\tlog.Debugf(\"Eureka status check gave: %v\", eurekaStatus)\n\tlast := getPreviousStatus(containerID)\n\n\t// Work out an appropriate registration status given previous and current values\n\tstatusChange := determineNewEurekaStatus(containerID, eurekaStatus, last)\n\tsetPreviousStatus(containerID, statusChange.newStatus)\n\telbReg.Status = statusChange.registrationStatus\n\tlog.Debugf(\"Status health check returned prev: %v registration: %v\", last, elbReg.Status)\n}",
"func okHealthCheck(proxy *Proxy) error {\n\treturn nil\n}",
"func healthHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Passed\")\n}",
"func (h *Health) Measure(ctx context.Context) Check {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\ttracer := h.tp.Tracer(h.instrumentationName)\n\n\tctx, span := tracer.Start(\n\t\tctx,\n\t\t\"health.Measure\",\n\t\ttrace.WithAttributes(attribute.Int(\"checks\", len(h.checks))),\n\t)\n\tdefer span.End()\n\n\tstatus := StatusOK\n\tfailures := make(map[string]string)\n\n\tlimiterCh := make(chan bool, h.maxConcurrent)\n\tdefer close(limiterCh)\n\n\tvar (\n\t\twg sync.WaitGroup\n\t\tmu sync.Mutex\n\t)\n\tfor _, c := range h.checks {\n\t\tlimiterCh <- true\n\t\twg.Add(1)\n\n\t\tgo func(c Config) {\n\t\t\tctx, span := tracer.Start(ctx, c.Name)\n\t\t\tdefer func() {\n\t\t\t\tspan.End()\n\t\t\t\t<-limiterCh\n\t\t\t\twg.Done()\n\t\t\t}()\n\n\t\t\tresCh := make(chan error)\n\n\t\t\tgo func() {\n\t\t\t\tresCh <- c.Check(ctx)\n\t\t\t\tdefer close(resCh)\n\t\t\t}()\n\n\t\t\ttimeout := time.NewTimer(c.Timeout)\n\n\t\t\tselect {\n\t\t\tcase <-timeout.C:\n\t\t\t\tmu.Lock()\n\t\t\t\tdefer mu.Unlock()\n\n\t\t\t\tspan.SetStatus(codes.Error, string(StatusTimeout))\n\n\t\t\t\tfailures[c.Name] = string(StatusTimeout)\n\t\t\t\tstatus = getAvailability(status, c.SkipOnErr)\n\t\t\tcase res := <-resCh:\n\t\t\t\tif !timeout.Stop() {\n\t\t\t\t\t<-timeout.C\n\t\t\t\t}\n\n\t\t\t\tmu.Lock()\n\t\t\t\tdefer mu.Unlock()\n\n\t\t\t\tif res != nil {\n\t\t\t\t\tspan.RecordError(res)\n\n\t\t\t\t\tfailures[c.Name] = res.Error()\n\t\t\t\t\tstatus = getAvailability(status, c.SkipOnErr)\n\t\t\t\t}\n\t\t\t}\n\t\t}(c)\n\t}\n\n\twg.Wait()\n\tspan.SetAttributes(attribute.String(\"status\", string(status)))\n\n\tvar systemMetrics *System\n\tif h.systemInfoEnabled {\n\t\tsystemMetrics = newSystemMetrics()\n\t}\n\n\treturn newCheck(h.component, status, systemMetrics, failures)\n}",
"func healthcheck(w http.ResponseWriter, r *http.Request) {\n\tduration := time.Since(time.Now())\n\tif duration.Seconds() > 10 {\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(fmt.Sprintf(\"error: %v\", duration.Seconds())))\n\t} else {\n\t\tw.WriteHeader(200)\n\t\tw.Header().Set(\"HOW-ARE-YOU\", \"FINE_THANK_YOU\")\n\t}\n}",
"func (m *ActiveHealthCheckUnhealthy) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif m.GetInterval() < 1 {\n\t\treturn ActiveHealthCheckUnhealthyValidationError{\n\t\t\tfield: \"Interval\",\n\t\t\treason: \"value must be greater than or equal to 1\",\n\t\t}\n\t}\n\n\tif len(m.GetHttpStatuses()) < 1 {\n\t\treturn ActiveHealthCheckUnhealthyValidationError{\n\t\t\tfield: \"HttpStatuses\",\n\t\t\treason: \"value must contain at least 1 item(s)\",\n\t\t}\n\t}\n\n\t_ActiveHealthCheckUnhealthy_HttpStatuses_Unique := make(map[int32]struct{}, len(m.GetHttpStatuses()))\n\n\tfor idx, item := range m.GetHttpStatuses() {\n\t\t_, _ = idx, item\n\n\t\tif _, exists := _ActiveHealthCheckUnhealthy_HttpStatuses_Unique[item]; exists {\n\t\t\treturn ActiveHealthCheckUnhealthyValidationError{\n\t\t\t\tfield: fmt.Sprintf(\"HttpStatuses[%v]\", idx),\n\t\t\t\treason: \"repeated value must contain unique items\",\n\t\t\t}\n\t\t} else {\n\t\t\t_ActiveHealthCheckUnhealthy_HttpStatuses_Unique[item] = struct{}{}\n\t\t}\n\n\t\tif val := item; val < 200 || val > 599 {\n\t\t\treturn ActiveHealthCheckUnhealthyValidationError{\n\t\t\t\tfield: fmt.Sprintf(\"HttpStatuses[%v]\", idx),\n\t\t\t\treason: \"value must be inside range [200, 599]\",\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif val := m.GetHttpFailures(); val < 1 || val > 254 {\n\t\treturn ActiveHealthCheckUnhealthyValidationError{\n\t\t\tfield: \"HttpFailures\",\n\t\t\treason: \"value must be inside range [1, 254]\",\n\t\t}\n\t}\n\n\tif val := m.GetTcpFailures(); val < 1 || val > 254 {\n\t\treturn ActiveHealthCheckUnhealthyValidationError{\n\t\t\tfield: \"TcpFailures\",\n\t\t\treason: \"value must be inside range [1, 254]\",\n\t\t}\n\t}\n\n\tif val := m.GetTimeouts(); val < 1 || val > 254 {\n\t\treturn ActiveHealthCheckUnhealthyValidationError{\n\t\t\tfield: \"Timeouts\",\n\t\t\treason: \"value must be inside range [1, 254]\",\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (p *RoundRobinPool) HealthCheckUp() {\n\tfor _, b := range p.servers {\n\t\tstatus := \"up\"\n\t\talive := p.isServerAlive(b.URL)\n\t\tb.SetAlive(alive)\n\t\tif !alive {\n\t\t\tstatus = \"down\"\n\t\t}\n\t\tlog.Printf(\"%s [%s]\\n\", b.URL, status)\n\t}\n}",
"func (server *SBServer) HealthcheckHandler(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase http.MethodPost:\n\t\tauthHeader := r.Header.Get(\"Authorization\")\n\t\tif authHeader != \"\" {\n\n\t\t\t// Validate authentication\n\t\t\tuser, pass, err := util.ExtractCredentialsFromAuthorizationHeader(authHeader)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(500)\n\t\t\t\tw.Write([]byte(\"Error during decoding of authorization header.\"))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := server.Database.LoginUser(user, pass); err != nil {\n\t\t\t\tw.WriteHeader(401)\n\t\t\t\tw.Write([]byte(\"Authentication for user \\\"\" + user + \"\\\" failed.\"))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Validate room\n\t\t\turlSuffix := strings.TrimPrefix(r.URL.Path, \"/healthcheck/\")\n\t\t\tif urlSuffix != \"\" {\n\t\t\t\turlSuffixSplit := strings.Split(urlSuffix, \"/\")\n\t\t\t\tif len(urlSuffixSplit) > 2 || (len(urlSuffixSplit) == 2 && urlSuffixSplit[1] != \"\") {\n\t\t\t\t\tw.WriteHeader(400)\n\t\t\t\t\tw.Write([]byte(\"Room name is illegal.\"))\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\troomName := urlSuffixSplit[0]\n\t\t\t\troom, err := server.GetRoom(roomName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tw.WriteHeader(404)\n\t\t\t\t\tw.Write([]byte(\"Room \\\"\" + roomName + \"\\\" not found.\"))\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif !room.IsOnline(user) {\n\t\t\t\t\tw.WriteHeader(403)\n\t\t\t\t\tw.Write([]byte(\"Room \\\"\" + roomName + \"\\\" exists but player \\\"\" + user + \"\\\" is not int it.\"))\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Returns status code 200 to show server is online and healthy and all configurations are valid\n\t\tw.WriteHeader(200)\n\tdefault:\n\t\tw.WriteHeader(405)\n\t}\n}",
"func healthCheckHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n}",
"func HealthCheck(w http.ResponseWriter, req *http.Request) {\n\tlog.Println(\"🚑 healthcheck ok!\")\n\tw.WriteHeader(http.StatusOK)\n}",
"func (h *allocHealthWatcherHook) watchHealth(ctx context.Context, deadline time.Time, tracker *allochealth.Tracker, done chan<- struct{}) {\n\tdefer close(done)\n\n\t// Default to unhealthy for the deadline reached case\n\thealthy := false\n\n\tselect {\n\tcase <-ctx.Done():\n\t\t// Graceful shutdown\n\t\treturn\n\n\tcase <-tracker.AllocStoppedCh():\n\t\t// Allocation has stopped so no need to set health\n\t\treturn\n\n\tcase <-time.After(time.Until(deadline)):\n\t\t// Time is up! Fallthrough to set unhealthy.\n\t\th.logger.Trace(\"deadline reached; setting unhealthy\", \"deadline\", deadline)\n\n\tcase healthy = <-tracker.HealthyCh():\n\t\t// Health received. Fallthrough to set it.\n\t}\n\n\th.logger.Trace(\"health set\", \"healthy\", healthy)\n\n\t// If this is an unhealthy deployment emit events for tasks\n\tvar taskEvents map[string]*structs.TaskEvent\n\tif !healthy && h.isDeploy {\n\t\ttaskEvents = tracker.TaskEvents()\n\t}\n\n\th.healthSetter.SetHealth(healthy, h.isDeploy, taskEvents)\n}",
"func (h *Healthz) Handler(w http.ResponseWriter, r *http.Request) {\n\th.Lock()\n\tdefer h.Unlock()\n\th.healthzCount++\n\tfor name, handler := range h.checks {\n\t\tif err := handler.Check(r); err != nil {\n\t\t\tw.WriteHeader(500)\n\t\t\terrMsg := fmt.Sprintf(\"check %v failed, err: %v\", name, err)\n\t\t\t_, _ = w.Write([]byte(errMsg))\n\t\t\tklog.Infof(\"/healthz %v\", errMsg)\n\t\t\treturn\n\t\t}\n\t}\n\n\tw.WriteHeader(200)\n\t_, _ = w.Write([]byte(\"ok\"))\n\tif h.healthzCount%10 == 0 {\n\t\tklog.V(5).Infof(\"/healthz ok %v\", h.info)\n\t}\n}",
"func (tr *trooper) healthChanged(health, mid, max int) {\n\tif tr.hms != nil {\n\t\tfor _, monitor := range tr.hms {\n\t\t\tmonitor.healthUpdated(health, mid, max)\n\t\t}\n\t}\n}",
"func (sp *ServerPool) HealthCheck() {\n\tfor _, server := range sp.servers {\n\t\tstatus, load := heartbeat.PingServer(server.URL)\n\t\t//TODO: Ping each server 3 times? To determine if healthy\n\t\tserver.SetOnline(status)\n\t\tserver.SetResponseTime(load)\n\t}\n}",
"func (hc *HealthCheckerImpl) Probe(ctx context.Context, l logr.Logger, logSuffix string, nodeID int) error {\n\tl.V(int(zapcore.DebugLevel)).Info(\"Health check probe\", \"label\", logSuffix, \"nodeID\", nodeID)\n\tstsname := hc.cluster.StatefulSetName()\n\tstsnamespace := hc.cluster.Namespace()\n\n\tsts, err := hc.clientset.AppsV1().StatefulSets(stsnamespace).Get(ctx, stsname, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn kube.HandleStsError(err, l, stsname, stsnamespace)\n\t}\n\n\tif err := scale.WaitUntilStatefulSetIsReadyToServe(ctx, hc.clientset, stsnamespace, stsname, *sts.Spec.Replicas); err != nil {\n\t\treturn errors.Wrapf(err, \"error rolling update stategy on pod %d\", nodeID)\n\t}\n\n\t// we check _status/vars on all cockroachdb pods looking for pairs like\n\t// ranges_underreplicated{store=\"1\"} 0 and wait if any are non-zero until all are 0.\n\t// We can recheck every 10 seconds. We are waiting for this maximum 3 minutes\n\terr = hc.waitUntilUnderReplicatedMetricIsZero(ctx, l, logSuffix, stsname, stsnamespace, *sts.Spec.Replicas)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// we will wait 22 seconds and check again _status/vars on all cockroachdb pods looking for pairs like\n\t// ranges_underreplicated{store=\"1\"} 0. This time we do not wait anymore. This suplimentary check\n\t// is due to the fact that a node can be evicted in some cases\n\ttime.Sleep(22 * time.Second)\n\tl.V(int(zapcore.DebugLevel)).Info(\"second wait loop for range_underreplicated metric\", \"label\", logSuffix, \"nodeID\", nodeID)\n\terr = hc.waitUntilUnderReplicatedMetricIsZero(ctx, l, logSuffix, stsname, stsnamespace, *sts.Spec.Replicas)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func healthHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(\"Alive!\"))\n}",
"func (s *healthchecker) Healthcheck(r *http.Request) (interface{}, error) {\n\tl := s.log.WithField(\"handler\", \"Healthcheck\")\n\tl.Debug(\"New Healthcheck request received\")\n\tl.Debug(\"Returning newly generated Healthcheck\")\n\treturn &healthcheck{Status: \"OK\", Hostname: s.hostname}, nil\n}",
"func HandlerHealthCheck(writer http.ResponseWriter, request *http.Request) {\n\twriter.WriteHeader(http.StatusOK)\n\tlog.Println(\"............Healthcheck success.............\")\n\treturn\n}",
"func (c *ControllerImpl) HealthCheck(ctx context.Context) error {\n\treturn nil\n}",
"func (c *Chargeback) healthinessHandler(w http.ResponseWriter, r *http.Request) {\n\tlogger := newRequestLogger(c.logger, r, c.rand)\n\tif !c.testWriteToPrestoSingleFlight(logger) {\n\t\twriteResponseAsJSON(logger, w, http.StatusInternalServerError,\n\t\t\tstatusResponse{\n\t\t\t\tStatus: \"not healthy\",\n\t\t\t\tDetails: \"cannot write to PrestoDB\",\n\t\t\t})\n\t\treturn\n\t}\n\twriteResponseAsJSON(logger, w, http.StatusOK, statusResponse{Status: \"ok\"})\n}",
"func (l *SharedLoadBalancer) ensureHealthCheck(loadbalancerID string, pool *elbmodel.PoolResp,\n\tport v1.ServicePort, service *v1.Service, node *v1.Node) error {\n\thealthCheckOpts := getHealthCheckOptionFromAnnotation(service, l.loadbalancerOpts)\n\tmonitorID := pool.HealthmonitorId\n\tklog.Infof(\"add or update or remove health check: %s : %#v\", monitorID, healthCheckOpts)\n\n\tif healthCheckOpts.Enable {\n\t\terr := l.allowHealthCheckRule(node)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tprotocolStr := parseProtocol(service, port)\n\t// create health monitor\n\tif monitorID == \"\" && healthCheckOpts.Enable {\n\t\t_, err := l.createHealthMonitor(loadbalancerID, pool.Id, protocolStr, healthCheckOpts)\n\t\treturn err\n\t}\n\n\t// update health monitor\n\tif monitorID != \"\" && healthCheckOpts.Enable {\n\t\treturn l.updateHealthMonitor(monitorID, protocolStr, healthCheckOpts)\n\t}\n\n\t// delete health monitor\n\tif monitorID != \"\" && !healthCheckOpts.Enable {\n\t\tklog.Infof(\"Deleting health monitor %s for pool %s\", monitorID, pool.Id)\n\t\terr := l.sharedELBClient.DeleteHealthMonitor(monitorID)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to delete health monitor %s for pool %s, error: %v\", monitorID, pool.Id, err)\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (w *Watchdog) RunChecksAndNotify() error {\n\ttoNotify := w.RunChecks()\n\n\tif len(toNotify) > 0 {\n\t\tif w.NotificationHandler == nil {\n\t\t\tlog.Error(\"No notification handler\")\n\t\t\treturn nil\n\t\t}\n\n\t\tlog.Info(\"Sending Notification\")\n\t\treturn w.NotificationHandler.Notify(toNotify)\n\t}\n\n\tlog.Info(\"No newly offline agents\")\n\treturn nil\n}",
"func HealthCheck(w http.ResponseWriter, r *http.Request) {}",
"func TestAllocRunner_DeploymentHealth_Unhealthy_Checks(t *testing.T) {\n\tci.Parallel(t)\n\n\talloc := mock.Alloc()\n\ttask := alloc.Job.TaskGroups[0].Tasks[0]\n\ttask.Driver = \"mock_driver\"\n\ttask.Config = map[string]interface{}{\n\t\t\"run_for\": \"10s\",\n\t}\n\n\t// Set a service with check\n\ttask.Services = []*structs.Service{\n\t\t{\n\t\t\tName: \"fakservice\",\n\t\t\tPortLabel: \"http\",\n\t\t\tChecks: []*structs.ServiceCheck{\n\t\t\t\t{\n\t\t\t\t\tName: \"fakecheck\",\n\t\t\t\t\tType: structs.ServiceCheckScript,\n\t\t\t\t\tCommand: \"true\",\n\t\t\t\t\tInterval: 30 * time.Second,\n\t\t\t\t\tTimeout: 5 * time.Second,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Make the alloc be part of a deployment\n\talloc.DeploymentID = uuid.Generate()\n\talloc.Job.TaskGroups[0].Update = structs.DefaultUpdateStrategy.Copy()\n\talloc.Job.TaskGroups[0].Update.HealthCheck = structs.UpdateStrategyHealthCheck_Checks\n\talloc.Job.TaskGroups[0].Update.MaxParallel = 1\n\talloc.Job.TaskGroups[0].Update.MinHealthyTime = 100 * time.Millisecond\n\talloc.Job.TaskGroups[0].Update.HealthyDeadline = 1 * time.Second\n\n\tcheckUnhealthy := &api.AgentCheck{\n\t\tCheckID: uuid.Generate(),\n\t\tStatus: api.HealthWarning,\n\t}\n\n\tconf, cleanup := testAllocRunnerConfig(t, alloc)\n\tdefer cleanup()\n\n\t// Only return the check as healthy after a duration\n\tconsulClient := conf.Consul.(*regMock.ServiceRegistrationHandler)\n\tconsulClient.AllocRegistrationsFn = func(allocID string) (*serviceregistration.AllocRegistration, error) {\n\t\treturn &serviceregistration.AllocRegistration{\n\t\t\tTasks: map[string]*serviceregistration.ServiceRegistrations{\n\t\t\t\ttask.Name: {\n\t\t\t\t\tServices: map[string]*serviceregistration.ServiceRegistration{\n\t\t\t\t\t\t\"123\": {\n\t\t\t\t\t\t\tService: &api.AgentService{Service: \"fakeservice\"},\n\t\t\t\t\t\t\tChecks: []*api.AgentCheck{checkUnhealthy},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}, nil\n\t}\n\n\tar, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\tgo ar.Run()\n\tdefer destroy(ar)\n\n\tvar lastUpdate *structs.Allocation\n\tupd := conf.StateUpdater.(*MockStateUpdater)\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlastUpdate = upd.Last()\n\t\tif lastUpdate == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\t\tif !lastUpdate.DeploymentStatus.HasHealth() {\n\t\t\treturn false, fmt.Errorf(\"want deployment status unhealthy; got unset\")\n\t\t} else if *lastUpdate.DeploymentStatus.Healthy {\n\t\t\t// This is fatal\n\t\t\tt.Fatal(\"want deployment status unhealthy; got healthy\")\n\t\t}\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.NoError(t, err)\n\t})\n\n\t// Assert that we have an event explaining why we are unhealthy.\n\trequire.Len(t, lastUpdate.TaskStates, 1)\n\ttaskState := lastUpdate.TaskStates[task.Name]\n\trequire.NotNil(t, taskState)\n\trequire.NotEmpty(t, taskState.Events)\n\tlast := taskState.Events[len(taskState.Events)-1]\n\trequire.Equal(t, allochealth.AllocHealthEventSource, last.Type)\n\trequire.Contains(t, last.Message, \"by healthy_deadline\")\n}",
"func health(w http.ResponseWriter, _ *http.Request) {\n\tif !Storage.Healthy() {\n\t\tmsg := \"database is not healthy\"\n\t\thttp.Error(w, msg, http.StatusServiceUnavailable)\n\t}\n}",
"func HandleHealthCheck(syncMan *syncman.Manager) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\tctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)\n\t\tdefer cancel()\n\n\t\tif err := syncMan.HealthCheck(); err != nil {\n\t\t\t_ = helpers.Response.SendErrorResponse(ctx, w, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\n\t\t_ = helpers.Response.SendOkayResponse(ctx, http.StatusOK, w)\n\t}\n}",
"func (api *API) health(w http.ResponseWriter, req *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(\"OK\"))\n}",
"func HealthCheckHandler(ctx *gin.Context) {\n\tlog.Info(\"received request for health check route\")\n\tctx.JSON(http.StatusOK, gin.H{\"http_code\": http.StatusOK,\n\t\t\"message\": \"Service running\"})\n}",
"func Health() (err error) {\n\treturn // yeah, we're good :)\n}",
"func (hc *healthCheckExtension) handler() http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tif hc.check() && hc.state.Get() == healthcheck.Ready {\n\t\t\tw.WriteHeader(200)\n\t\t} else {\n\t\t\tw.WriteHeader(500)\n\t\t}\n\t})\n}",
"func healthHandler(w http.ResponseWriter, r *http.Request) {\n\tbeeline.AddField(r.Context(), \"alive\", true)\n\tw.Write([]byte(`{\"alive\": \"yes\"}`))\n}"
] | [
"0.709131",
"0.70775664",
"0.6727526",
"0.6463843",
"0.6458907",
"0.6456858",
"0.64515644",
"0.64320844",
"0.6408324",
"0.64071524",
"0.6399542",
"0.6396202",
"0.6389143",
"0.63829434",
"0.63559914",
"0.63552296",
"0.6330259",
"0.63142663",
"0.62631667",
"0.62396705",
"0.6237838",
"0.6226116",
"0.6223033",
"0.62229437",
"0.62222105",
"0.6219106",
"0.6206397",
"0.61618114",
"0.61533964",
"0.61460763",
"0.61429894",
"0.6110573",
"0.6100417",
"0.6091622",
"0.60912824",
"0.6077373",
"0.6076289",
"0.60736597",
"0.6063602",
"0.60544616",
"0.60531175",
"0.60524285",
"0.60506344",
"0.6044707",
"0.6042802",
"0.60370356",
"0.60325474",
"0.6027663",
"0.6025572",
"0.6023598",
"0.6018109",
"0.6015896",
"0.60157895",
"0.600204",
"0.59981227",
"0.5993346",
"0.59927195",
"0.59781694",
"0.59710157",
"0.59683484",
"0.59658915",
"0.59635067",
"0.5952871",
"0.5928697",
"0.5920402",
"0.59182405",
"0.5908873",
"0.59057355",
"0.5886196",
"0.58796763",
"0.5876782",
"0.58743715",
"0.5873271",
"0.58715165",
"0.586231",
"0.5859064",
"0.58565766",
"0.5853305",
"0.5850115",
"0.58490825",
"0.5846847",
"0.58410865",
"0.5840356",
"0.5831647",
"0.58290786",
"0.582471",
"0.5824201",
"0.58237314",
"0.5818064",
"0.57910347",
"0.5786896",
"0.5785337",
"0.5785271",
"0.57849437",
"0.5771086",
"0.57654005",
"0.5760199",
"0.5753434",
"0.5752858",
"0.5752707",
"0.5747576"
] | 0.0 | -1 |
NewMaxMindGeoLibResolver creates a new instance of MaxMindGeoLibResolver | func NewMaxMindGeoLibResolver(homeDirResolver *filesystem.HomeDirResolver) *MaxMindGeoLibResolver {
return &MaxMindGeoLibResolver{
homeDirResolver: homeDirResolver,
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func NewMaxMind(conf *config.Config) *MaxMind {\n\treturn &MaxMind{\n\t\tProvider: Provider{\n\t\t\tdirectory: conf.Directory,\n\t\t\tdbname: \"maxmind\",\n\t\t\tdownloadTimeout: time.Minute,\n\t\t\tprecision: conf.Precision,\n\t\t\tupdateLock: &sync.RWMutex{},\n\t\t},\n\t}\n}",
"func NewMaxMind(fileNameV4 string, fileNameV6 string) (*MaxMind, error) {\n\tm := new(MaxMind)\n\tvar err error\n\tm.asnInfo = make([]AsnInfo, 500000)\n\n\tif fileNameV4 != \"\" {\n\t\terr = m.loadCsvV4(fileNameV4) // Modifies m.asnInfo\n\t\tif err != nil {\n\t\t\treturn m, err\n\t\t}\n\t}\n\n\tif fileNameV6 != \"\" {\n\t\terr = m.loadCsvV6(fileNameV6) // Modifies m.asnInfo\n\t\tif err != nil {\n\t\t\treturn m, err\n\t\t}\n\t}\n\n\tsort.Sort(byStart(m.asnInfo))\n\treturn m, err\n}",
"func New() *Resolver {\n\treturn &Resolver{}\n}",
"func New() *Resolver {\n\treturn &Resolver{}\n}",
"func New(store database.DAL) *Resolver {\n\treturn &Resolver{store}\n}",
"func NewResolver(args map[string]interface{}) Resolver {\n\treturn &concreteResolver{args: args}\n}",
"func NewResolver(config *config.Config) Resolver {\n\tif config.RemoteTaggerEnabled {\n\t\toptions, err := remote.NodeAgentOptions()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"unable to configure the remote tagger: %s\", err)\n\t\t} else {\n\t\t\treturn &DefaultResolver{\n\t\t\t\ttagger: remote.NewTagger(options),\n\t\t\t}\n\t\t}\n\t}\n\treturn &DefaultResolver{\n\t\ttagger: &nullTagger{},\n\t}\n}",
"func NewResolver(cln *client.Client, mw *progress.MultiWriter) (Resolver, error) {\n\troot, exist, err := modulesPathExist()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !exist {\n\t\treturn &remoteResolver{cln, mw, root}, nil\n\t}\n\n\treturn &vendorResolver{root}, nil\n}",
"func NewResolver(opts ...Option) resolver.Interface {\n\tr := &Resolver{}\n\n\t// Apply all options.\n\tfor _, o := range opts {\n\t\to(r)\n\t}\n\n\treturn r\n}",
"func (c *Client) MaxmindGeoLite(resource, queryTime string) (map[string]interface{}, error) {\n\tm := make(map[string]string)\n\tm[\"resource\"] = resource\n\tm[\"query_time\"] = queryTime\n\treturn c.execute(maxmindGeoLitePath, m)\n}",
"func (s StaticInfoExtn) NewGeo() (StaticInfoExtn_GeoInfo, error) {\n\tss, err := NewStaticInfoExtn_GeoInfo(s.Struct.Segment())\n\tif err != nil {\n\t\treturn StaticInfoExtn_GeoInfo{}, err\n\t}\n\terr = s.Struct.SetPtr(1, ss.Struct.ToPtr())\n\treturn ss, err\n}",
"func NewResolver() *Resolver {\n\tclient := http.Client{\n\t\tTimeout: time.Second * 3,\n\t}\n\n\treturn &Resolver{\n\t\tClient: client,\n\t}\n}",
"func NewResolver() *Resolver {\n\treturn &Resolver{\n\t\tresolver: dnsr.New(defaultCacheSize),\n\t}\n}",
"func NewResolver(namespaceTag, defaultNamespace []byte) Resolver {\n\tif namespaceTag == nil {\n\t\tnamespaceTag = defaultNamespaceTag\n\t}\n\tif defaultNamespace == nil {\n\t\tdefaultNamespace = defaultNamespaceValue\n\t}\n\treturn &resolver{\n\t\tnamespaceTag: namespaceTag,\n\t\tdefaultNamespace: defaultNamespace,\n\t}\n}",
"func NewResolver() exec.Resolver {\n\treturn &resolver{}\n}",
"func NewResolver(interpreter *Interpreter) *Resolver {\n\treturn &Resolver{\n\t\tscopes: NewScopes(),\n\t\tinterpreter: interpreter,\n\t\tcurFunc: FuncNone,\n\t\tinLoop: false,\n\t\tinClass: false,\n\t\tinSubClass: false,\n\t\tinInit: false,\n\t\thadError: false,\n\t}\n}",
"func NewResolver(err error) *Resolver {\n\treturn &Resolver{err: err}\n}",
"func NewResolver(err error) *Resolver {\n\treturn &Resolver{err: err}\n}",
"func NewResolver(locale i18n.Locale, base string) *Resolver {\n\treturn &Resolver{base, locale, map[string]*MessageFormat{}}\n}",
"func NewResolver(urlMapLoader IURLMapLoader) *Resolver {\n\treturn &Resolver{\n\t\turlMapLoader: urlMapLoader,\n\t}\n}",
"func New(cfg Config, opts ...Option) *Resolver {\n\tr := &Resolver{logger: cfg.Logger}\n\tfor _, opt := range opts {\n\t\topt(r)\n\t}\n\treturn r\n}",
"func NewMResolver(\n\tlogger *log.Logger,\n\tconn dnsconn.Conn,\n\tservers []*Server,\n\tzones *Zones,\n\tallowQuery Access,\n\tallowUpdate Access,\n) *MResolver {\n\treturn &MResolver{\n\t\tlogger: logger,\n\t\tconn: conn,\n\t\tservers: servers,\n\t\tzones: zones,\n\t\tallowQuery: allowQuery,\n\t\tallowUpdate: allowUpdate,\n\t}\n}",
"func NewResolver(alternateHosts []string) *resolver {\n\thosts := map[string]bool{}\n\tif len(alternateHosts) > 0 {\n\t\tfor _, h := range alternateHosts {\n\t\t\thosts[h] = true\n\t\t}\n\t}\n\treturn &resolver{\n\t\tcache: hosts,\n\t}\n}",
"func NewGeoLite2() (Locator, error) {\n\tif _, err := os.Stat(dbPath + geoLite2DbName); os.IsNotExist(err) {\n\t\tif os.Getenv(\"MAXMIND_LICENSE\") != \"\" {\n\t\t\terr := downloadGeoLite2Db(os.Getenv(\"MAXMIND_LICENSE\"))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tdb, err := geoip2.Open(dbPath + geoLite2DbName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &geoLite2{\n\t\tdb: db,\n\t}, nil\n}",
"func NewResolver(timeout time.Duration) *Resolver {\n\treturn &Resolver{\n\t\tresolver: &net.Resolver{},\n\t\ttimeout: timeout,\n\t}\n}",
"func NewResolver(db driver.Database, stellarDriver *stellar.Driver, txSourceDriver txsource.Driver) Resolver {\n\tr := new(resolver)\n\tr.db = db\n\tr.txSourceDriver = txSourceDriver\n\tr.stellarDriver = stellarDriver\n\tr.approveReqRes = approveReqResolver{r}\n\tr.docRes = docResolver{r}\n\tr.mutationRes = mutationResolver{r}\n\tr.queryRes = queryResolver{r}\n\tr.tradeRes = tradeResolver{r}\n\tr.tradeStageAddReqRes = tradeStageAddReqResolver{r}\n\tr.tradeStageDocRes = tradeStageDocResolver{r}\n\tr.userRes = userResolver{r}\n\tr.accessApprovalRes = accessApprovalResolver{r}\n\tr.tradeOfferRes = tradeOfferRes{r}\n\tr.moderatorRes = stageModeratorResolver{r}\n\tr.notificationRes = notificationResolver{r}\n\treturn r\n}",
"func NewResolver(db *sql.DB) graphqlbackend.CampaignsResolver {\n\treturn &Resolver{store: ee.NewStore(db)}\n}",
"func newRepository() Repository {\n\tif cfg == nil {\n\t\tpanic(fmt.Errorf(\"missing configuration\"))\n\t}\n\tif log == nil {\n\t\tpanic(fmt.Errorf(\"missing logger\"))\n\t}\n\n\tp2p.SetConfig(cfg)\n\tp2p.SetLogger(log)\n\n\t// create connections\n\tcaBridge, dbBridge, rpcBridge, geoBridge, err := connect(cfg, log)\n\tif err != nil {\n\t\tlog.Fatal(\"repository init failed\")\n\t\treturn nil\n\t}\n\n\t// construct the proxy instance\n\tp := proxy{\n\t\tcache: caBridge,\n\t\tdb: dbBridge,\n\t\trpc: rpcBridge,\n\t\tgeoip: geoBridge,\n\t\tlog: log,\n\t\tcfg: cfg,\n\n\t\t// get the map of governance contracts\n\t\tgovContracts: governanceContractsMap(cfg.Governance),\n\n\t\t// keep reference to the SOL compiler\n\t\tsolCompiler: cfg.Compiler.DefaultSolCompilerPath,\n\t}\n\n\t// return the proxy\n\treturn &p\n}",
"func NewClient(ctx context.Context) *MaxMindClient {\n\turl := &url.URL{\n\t\tScheme: \"https\",\n\t\tHost: \"minfraud.maxmind.com\",\n\t\tPath: \"/minfraud/v2.0/\",\n\t}\n\ttransport := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout: 5 * time.Second,\n\t\t\tKeepAlive: 5 * time.Second,\n\t\t}).DialContext,\n\t\tForceAttemptHTTP2: true,\n\t\tMaxIdleConns: 100,\n\t\tIdleConnTimeout: 5 * time.Second,\n\t\tTLSHandshakeTimeout: 5 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t},\n\t}\n\n\treturn &MaxMindClient{\n\t\trt: transport,\n\t\tctx: ctx,\n\t\tbase: url,\n\t}\n}",
"func New(config netx.Config) *Resolver {\n\tprimary, err := netx.NewDNSClientWithOverrides(config,\n\t\t\"https://cloudflare.com/dns-query\", \"dns.cloudflare.com\", \"\", \"\")\n\truntimex.PanicOnError(err, \"cannot create dns over https resolver\")\n\tfallback, err := netx.NewDNSClient(config, \"system:///\")\n\truntimex.PanicOnError(err, \"cannot create system resolver\")\n\treturn &Resolver{\n\t\tPrimary: primary,\n\t\tPrimaryFailure: atomicx.NewInt64(),\n\t\tPrimaryQuery: atomicx.NewInt64(),\n\t\tFallback: fallback,\n\t\tFallbackFailure: atomicx.NewInt64(),\n\t\tFallbackQuery: atomicx.NewInt64(),\n\t}\n}",
"func NewResolver(p *agent.Peer, r rendezvous, cache DiskCache, d dialers.Defaults) Resolver {\n\treturn Resolver{\n\t\tlocal: p,\n\t\trendezvous: r,\n\t\tdialer: d,\n\t\tcache: cache,\n\t}\n}",
"func Newgeo(conf GeoConfig,\n\tlog log.Modular, stats metrics.Type,\n) (types.Processor, error) {\n\tdb, err := geoip2.Open(conf.File)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm := &geo{\n\t\tfile: conf.File,\n\t\tlog: log,\n\t\tfield: conf.Field,\n\t\tgeoip2DB: db,\n\t\tstats: stats,\n\t}\n\treturn m, nil\n}",
"func NewResolver(fileDescriptorProtos ...*descriptorpb.FileDescriptorProto) (Resolver, error) {\n\treturn newResolver(fileDescriptorProtos...)\n}",
"func NewResolver(baseConfig config.Config, client kubectl.Client, configOptions *loader.ConfigOptions, log log.Logger) ResolverInterface {\n\tvar id string\n\n\tvar kubeLoader kubeconfig.Loader\n\tif client == nil {\n\t\tkubeLoader = kubeconfig.NewLoader()\n\t} else {\n\t\tkubeLoader = client.KubeConfigLoader()\n\t}\n\n\tbasePath, err := filepath.Abs(\".\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tremote, err := git.GetRemote(basePath)\n\tif err == nil {\n\t\tid = remote\n\t} else {\n\t\tid = basePath\n\t}\n\n\treturn &resolver{\n\t\tRootID: id,\n\t\tDependencyGraph: newGraph(newNode(id, nil)),\n\n\t\tBaseConfig: baseConfig.Config(),\n\t\tBaseCache: baseConfig.Generated(),\n\t\tBaseVars: baseConfig.Variables(),\n\n\t\tConfigOptions: configOptions,\n\n\t\t// We only need that for saving\n\t\tkubeLoader: kubeLoader,\n\t\tclient: client,\n\t\tgeneratedSaver: generated.NewConfigLoaderFromDevSpacePath(\"\", baseConfig.Path()),\n\t\tlog: log,\n\t}\n}",
"func New(provider string) (Provider, error) {\n\tswitch provider {\n\tcase \"freeGeoIP\":\n\t\tpr := new(freeGeoIP)\n\t\treturn pr, nil\n\t}\n\treturn nil, ErrNoSuchProvider\n}",
"func New(\n\tnotifier discovery.Notifier,\n\tdiscoverer discovery.Discoverer,\n\tlogger *zap.Logger,\n\tdiscoveryMinPeers int,\n) *Resolver {\n\tseed := time.Now().UnixNano()\n\trandom := rand.New(rand.NewSource(seed))\n\tr := &Resolver{\n\t\tnotifier: notifier,\n\t\tdiscoverer: discoverer,\n\t\tdiscoCh: make(chan []string, 100),\n\t\tlogger: logger,\n\t\tdiscoveryMinPeers: discoveryMinPeers,\n\t\tsalt: []byte(strconv.FormatInt(random.Int63(), 10)), // random salt for rendezvousHash\n\t\tscheme: strconv.FormatInt(seed, 36), // make random scheme which will be used when registering\n\t}\n\n\t// Register the resolver with grpc so it's available for grpc.Dial\n\tresolver.Register(r)\n\n\t// Register the discoCh channel with notifier so it continues to fetch a list of host/port\n\tnotifier.Register(r.discoCh)\n\treturn r\n}",
"func NewResolver(serviceName string) *resolver {\n\treturn &resolver{serviceName: serviceName}\n}",
"func NewResolver(serviceName string) *resolver {\n\treturn &resolver{serviceName: serviceName}\n}",
"func New(server io.Server, registry packages.Registry) packages.ApplicationPackageHandler {\n\treturn &GeolocationPackage{\n\t\tserver: server,\n\t\tregistry: registry,\n\t}\n}",
"func NewGeoLite2() (Locator, error) {\n\tdb, err := geoip2.Open(dbFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &geoLite2{\n\t\tdb: db,\n\t}, nil\n}",
"func NewResolver(\n\tlogger fw.Logger,\n\ttracer fw.Tracer,\n\tchangeLog changelog.ChangeLog,\n\turlRetriever url.Retriever,\n\turlCreator url.Creator,\n\trequesterVerifier requester.Verifier,\n\tauthenticator authenticator.Authenticator,\n) Resolver {\n\treturn Resolver{\n\t\tQuery: newQuery(logger, tracer, authenticator, changeLog, urlRetriever),\n\t\tMutation: newMutation(\n\t\t\tlogger,\n\t\t\ttracer,\n\t\t\tchangeLog,\n\t\t\turlCreator,\n\t\t\trequesterVerifier,\n\t\t\tauthenticator,\n\t\t),\n\t}\n}",
"func NewResolver(fileDescriptors ...protodescriptor.FileDescriptor) (Resolver, error) {\n\treturn newResolver(fileDescriptors...)\n}",
"func NewResolver(root string, backgroundTaskManager *task.BackgroundTaskManager, cfg config.Config, resolveHandlers map[string]remote.Handler, metadataStore metadata.Store, overlayOpaqueType OverlayOpaqueType, additionalDecompressors func(context.Context, source.RegistryHosts, reference.Spec, ocispec.Descriptor) []metadata.Decompressor) (*Resolver, error) {\n\tresolveResultEntryTTL := time.Duration(cfg.ResolveResultEntryTTLSec) * time.Second\n\tif resolveResultEntryTTL == 0 {\n\t\tresolveResultEntryTTL = defaultResolveResultEntryTTLSec * time.Second\n\t}\n\tprefetchTimeout := time.Duration(cfg.PrefetchTimeoutSec) * time.Second\n\tif prefetchTimeout == 0 {\n\t\tprefetchTimeout = defaultPrefetchTimeoutSec * time.Second\n\t}\n\n\t// layerCache caches resolved layers for future use. This is useful in a use-case where\n\t// the filesystem resolves and caches all layers in an image (not only queried one) in parallel,\n\t// before they are actually queried.\n\tlayerCache := cacheutil.NewTTLCache(resolveResultEntryTTL)\n\tlayerCache.OnEvicted = func(key string, value interface{}) {\n\t\tif err := value.(*layer).close(); err != nil {\n\t\t\tlogrus.WithField(\"key\", key).WithError(err).Warnf(\"failed to clean up layer\")\n\t\t\treturn\n\t\t}\n\t\tlogrus.WithField(\"key\", key).Debugf(\"cleaned up layer\")\n\t}\n\n\t// blobCache caches resolved blobs for futural use. This is especially useful when a layer\n\t// isn't eStargz/stargz (the *layer object won't be created/cached in this case).\n\tblobCache := cacheutil.NewTTLCache(resolveResultEntryTTL)\n\tblobCache.OnEvicted = func(key string, value interface{}) {\n\t\tif err := value.(remote.Blob).Close(); err != nil {\n\t\t\tlogrus.WithField(\"key\", key).WithError(err).Warnf(\"failed to clean up blob\")\n\t\t\treturn\n\t\t}\n\t\tlogrus.WithField(\"key\", key).Debugf(\"cleaned up blob\")\n\t}\n\n\tif err := os.MkdirAll(root, 0700); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Resolver{\n\t\trootDir: root,\n\t\tresolver: remote.NewResolver(cfg.BlobConfig, resolveHandlers),\n\t\tlayerCache: layerCache,\n\t\tblobCache: blobCache,\n\t\tprefetchTimeout: prefetchTimeout,\n\t\tbackgroundTaskManager: backgroundTaskManager,\n\t\tconfig: cfg,\n\t\tresolveLock: new(namedmutex.NamedMutex),\n\t\tmetadataStore: metadataStore,\n\t\toverlayOpaqueType: overlayOpaqueType,\n\t\tadditionalDecompressors: additionalDecompressors,\n\t}, nil\n}",
"func NewResolver(userExists existsFn) *Resolver {\n\treturn &Resolver{\n\t\tfiles: map[string][]string{},\n\t\tdomains: map[string]bool{},\n\t\taliases: map[string][]Recipient{},\n\n\t\tuserExistsInDB: userExists,\n\t}\n}",
"func NewResolver(domainLoader ILoader) IResolver {\n\treturn &Resolver{\n\t\tdomainLoader: domainLoader,\n\t}\n}",
"func NewResolver(transact persistence.Transactioner, svc EventDefService, bndlSvc BundleService, bndlRefSvc BundleReferenceService, converter EventDefConverter, frConverter FetchRequestConverter, specService SpecService, specConverter SpecConverter) *Resolver {\n\treturn &Resolver{\n\t\ttransact: transact,\n\t\tsvc: svc,\n\t\tbndlSvc: bndlSvc,\n\t\tbndlRefSvc: bndlRefSvc,\n\t\tconverter: converter,\n\t\tfrConverter: frConverter,\n\t\tspecConverter: specConverter,\n\t\tspecService: specService,\n\t}\n}",
"func NewResolver(\n\tlogger logger.Logger,\n\tshortLinkRetriever shortlink.Retriever,\n\tshortLinkCreator shortlink.Creator,\n\tshortLinkUpdater shortlink.Updater,\n\tchangeLog changelog.ChangeLog,\n\trequesterVerifier requester.Verifier,\n\tauthenticator authenticator.Authenticator,\n\tuserRepo repository.User,\n\tuserShortLinkRepo repository.UserShortLink,\n\tkeyGen keygen.KeyGenerator,\n) Resolver {\n\treturn Resolver{\n\t\tQuery: newQuery(logger, authenticator, changeLog, shortLinkRetriever, userShortLinkRepo),\n\t\tMutation: newMutation(\n\t\t\tlogger,\n\t\t\tchangeLog,\n\t\t\tshortLinkCreator,\n\t\t\tshortLinkUpdater,\n\t\t\trequesterVerifier,\n\t\t\tauthenticator,\n\t\t\tuserRepo,\n\t\t\tkeyGen,\n\t\t),\n\t}\n}",
"func New(ctx context.Context) *Resolver {\n\treturn &Resolver{\n\t\tctx: ctx,\n\t\tresultSetPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn &resultSet{\n\t\t\t\t\tbuffers: make(map[int]*BufPair, 8),\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tbyteSlicesPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\tslice := make([][]byte, 0, 24)\n\t\t\t\treturn &slice\n\t\t\t},\n\t\t},\n\t\twaitGroupPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn &sync.WaitGroup{}\n\t\t\t},\n\t\t},\n\t\tbufPairPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\tpair := BufPair{\n\t\t\t\t\tData: fastbuffer.New(),\n\t\t\t\t\tErrors: fastbuffer.New(),\n\t\t\t\t}\n\t\t\t\treturn &pair\n\t\t\t},\n\t\t},\n\t\tbufPairSlicePool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\tslice := make([]*BufPair, 0, 24)\n\t\t\t\treturn &slice\n\t\t\t},\n\t\t},\n\t\terrChanPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn make(chan error, 1)\n\t\t\t},\n\t\t},\n\t\thash64Pool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn xxhash.New()\n\t\t\t},\n\t\t},\n\t\tinflightFetchPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn &inflightFetch{\n\t\t\t\t\tbufPair: BufPair{\n\t\t\t\t\t\tData: fastbuffer.New(),\n\t\t\t\t\t\tErrors: fastbuffer.New(),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tinflightFetches: map[uint64]*inflightFetch{},\n\t}\n}",
"func NewResolver(context *base.Context, address string) (Resolver, error) {\n\tif len(address) == 0 {\n\t\treturn nil, errors.Errorf(\"invalid address value: %q\", address)\n\t}\n\n\t// Ensure addr has port and host set.\n\taddress = ensureHostPort(address, base.DefaultPort)\n\treturn &socketResolver{typ: \"tcp\", addr: address}, nil\n}",
"func New(ctx context.Context, m map[string]interface{}) (auth.Manager, error) {\n\tvar mgr manager\n\tif err := mgr.Configure(m); err != nil {\n\t\treturn nil, err\n\t}\n\tgw, err := pool.GetGatewayServiceClient(pool.Endpoint(mgr.c.GatewayAddr))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmgr.gw = gw\n\n\treturn &mgr, nil\n}",
"func New(dispatcher service.Dispatcher, context context.Client, channelID string, opts ...options.Opt) *PeerResolver {\n\tparams := defaultParams(context, channelID)\n\toptions.Apply(params, opts)\n\n\tlogger.Debugf(\"Creating new balanced peer resolver\")\n\n\treturn &PeerResolver{\n\t\tparams: params,\n\t}\n}",
"func NewResolverPool(res []Resolver, maxQueries int, logger *log.Logger) *ResolverPool {\n\trp := &ResolverPool{\n\t\tResolvers: res,\n\t\tDone: make(chan struct{}, 2),\n\t\tLog: logger,\n\t\tdomainCacheChan: make(chan *domainReq, 10),\n\t\twildcardQueue: queue.NewQueue(),\n\t\tsemMaxWildcard: semaphore.NewWeighted(int64(maxQueries / len(res))),\n\t}\n\n\t// Assign a null logger when one is not provided\n\tif rp.Log == nil {\n\t\trp.Log = log.New(ioutil.Discard, \"\", 0)\n\t}\n\n\tgo rp.processWildcardRequests()\n\tgo rp.manageDomainCache(rp.domainCacheChan)\n\treturn rp\n}",
"func newDependencyResolver(\n\tbasePath string,\n\texclusions []*regexp.Regexp) (dr dag.DependencyResolver) {\n\tdr = &dependencyResolver{\n\t\tbasePath: basePath,\n\t\texclusions: exclusions,\n\t}\n\n\treturn\n}",
"func New() *Ipref {\n\tudp := unbound.New()\n\ttcp := unbound.New()\n\ttcp.SetOption(\"tcp-upstream:\", \"yes\")\n\n\tmclient := &MapperClient{}\n\tmclient.init()\n\n\tipr := &Ipref{u: udp, t: tcp, m: mclient}\n\n\tfor k, v := range options {\n\t\tif err := ipr.setOption(k, v); err != nil {\n\t\t\tlog.Warningf(\"Could not set option: %s\", err)\n\t\t}\n\t}\n\n\treturn ipr\n}",
"func NewResolver() peerresolver.Provider {\n\treturn func(ed service.Dispatcher, context context.Client, channelID string, opts ...options.Opt) peerresolver.Resolver {\n\t\treturn New(ed, context, channelID, opts...)\n\t}\n}",
"func New(domains []string, outputLocation string, prefix string) *provider.Provider {\n\tloc := &Local{\n\t\tdomains: domains,\n\t\tprefix: prefix,\n\t\toutputLocation: outputLocation,\n\t}\n\tprov := provider.Provider(loc)\n\treturn &prov\n}",
"func (mm *MaxMind) Resolve(ips []net.IP) ResolveResult {\n\treturn mm.resolveSafe(func() map[string]GeoResult {\n\t\tresults := make(map[string]GeoResult)\n\n\t\tfor _, ip := range ips {\n\t\t\tswitch mm.precision {\n\t\t\tcase config.PrecisionCountry:\n\t\t\t\tresults[ip.String()] = mm.resolveCountryResult(ip)\n\t\t\tcase config.PrecisionCity:\n\t\t\t\tresults[ip.String()] = mm.resolveCityResult(ip)\n\t\t\t}\n\t\t}\n\n\t\treturn results\n\t})\n}",
"func NewGeoDB(zipfile string) (GeoFinder, error) {\n\tf, err := os.Open(zipfile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tzf, err := zip.NewReader(f, fi.Size())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar blocks, countries *zip.File\n\tfor _, f := range zf.File {\n\t\tif strings.HasSuffix(f.Name, \"-Blocks-IPv4.csv\") {\n\t\t\tblocks = f\n\t\t} else if strings.HasSuffix(f.Name, \"-Country-Locations-en.csv\") {\n\t\t\tcountries = f\n\t\t}\n\t}\n\tif blocks == nil || countries == nil {\n\t\treturn nil, errors.New(\"ZIP does not contains blocks or countries\")\n\t}\n\n\tdb := geodb{}\n\tcn := map[string]string{}\n\n\tif err := readCSV(countries, []string{\"geoname_id\", \"country_iso_code\"}, func(row []string) error {\n\t\tcn[row[0]] = row[1]\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := readCSV(blocks, []string{\"network\", \"geoname_id\"}, func(row []string) error {\n\t\tnetwork, id := row[0], row[1]\n\t\tcountry, ok := cn[id]\n\t\tif !ok {\n\t\t\t// Some ranges may not contain country data\n\t\t\treturn nil\n\t\t}\n\t\t_, ipnet, err := net.ParseCIDR(network)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdb = append(db, ipRange{Net: ipnet, Country: country})\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn db, nil\n}",
"func NewResolver(backend bind.ContractBackend, domain string) (*Resolver, error) {\n\tregistry, err := NewRegistry(backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Ensure the name is registered\n\townerAddress, err := registry.Owner(domain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif bytes.Equal(ownerAddress.Bytes(), UnknownAddress.Bytes()) {\n\t\treturn nil, errors.New(\"unregistered name\")\n\t}\n\n\t// Obtain the resolver address for this domain\n\tresolver, err := registry.ResolverAddress(domain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewResolverAt(backend, domain, resolver)\n}",
"func newServer() *geoServer {\n\ts := new(geoServer)\n\ts.loadLocations(data.MustAsset(\"data/locations.json\"))\n\treturn s\n}",
"func NewGeoIP(filePath string) (*GeoIP, error) {\n\t// 判断文件是否存在\n\t_, err := os.Stat(filePath)\n\tif err != nil && os.IsNotExist(err) {\n\t\tlog.Println(\"文件不存在,请自行下载 Geoip2 City库,并保存在\", filePath)\n\t\treturn nil, err\n\t} else {\n\t\tdb, err := geoip2.Open(filePath)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\treturn &GeoIP{db: db}, nil\n\t}\n}",
"func NewGeospatial(baseURL string) Geospatial {\n\treturn &geospatialService{baseURL}\n}",
"func New(localAddress raft.ServerAddress, dialOptions []grpc.DialOption) *Manager {\n\treturn &Manager{\n\t\tlocalAddress: localAddress,\n\t\tdialOptions: dialOptions,\n\n\t\trpcChan: make(chan raft.RPC),\n\t\tconnections: map[raft.ServerID]*conn{},\n\t}\n}",
"func NewMTAResolver(m *mta.MTA, workspaceDir string) *MTAResolver {\n\tresolver := &MTAResolver{*m, workspaceDir, &ResolveContext{\n\t\tglobal: map[string]string{},\n\t\tmodules: map[string]map[string]string{},\n\t\tresources: map[string]map[string]string{},\n\t}, []string{}}\n\n\tfor _, module := range m.Modules {\n\t\tresolver.context.modules[module.Name] = map[string]string{}\n\t}\n\n\tfor _, resource := range m.Resources {\n\t\tresolver.context.resources[resource.Name] = map[string]string{}\n\t}\n\treturn resolver\n}",
"func newResolver(w *v8.Worker, s Store) (*moduleResolver, error) {\n\tr := &moduleResolver{w, s}\n\n\tfor _, assetName := range builtin.ListAssetNames() {\n\t\tif assetName == \"index.js\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tcode, err := s.ReadModule(assetName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Include required built in functions\n\t\tif err := w.Load(assetName, code); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// // Read core.js from VFS\n\t// b64, err := s.ReadModule(\"base64.js\")\n\t// if err != nil {\n\t// \treturn nil, err\n\t// }\n\n\t// // Include required built in functions\n\t// if err := w.Load(\"base64.js\", b64); err != nil {\n\t// \treturn nil, err\n\t// }\n\n\t// // Read core.js from VFS\n\t// core, err := s.ReadModule(\"core.js\")\n\t// if err != nil {\n\t// \treturn nil, err\n\t// }\n\n\t// // Include required built in functions\n\t// if err := w.Load(\"core.js\", core); err != nil {\n\t// \treturn nil, err\n\t// }\n\treturn r, nil\n}",
"func New(indexer cache.Store) *Manager {\n\tlogger := &bgplog.Logger{Entry: log}\n\tc := &metallbctl.Controller{\n\t\tClient: bgpk8s.New(logger.Logger),\n\t\tIPs: metallballoc.New(),\n\t}\n\n\tf, err := os.Open(option.Config.BGPConfigPath)\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Failed to open BGP config file\")\n\t}\n\tdefer f.Close()\n\n\tconfig, err := bgpconfig.Parse(f)\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Failed to parse BGP configuration\")\n\t}\n\tc.SetConfig(logger, config)\n\n\tmgr := &Manager{\n\t\tController: c,\n\t\tlogger: logger,\n\n\t\tqueue: workqueue.New(),\n\t\tindexer: indexer,\n\t}\n\tgo mgr.run()\n\n\treturn mgr\n}",
"func NewDefaultResolver(resolver Resolver) DefaultResolver {\n\treturn &DefaultResolverImpl{Resolver: resolver}\n}",
"func newAgentEndpointsManager() *agentEndpointsManager {\n\treturn &agentEndpointsManager{make(map[string]*agentEndpoint), &sync.RWMutex{}}\n}",
"func SetupResolverPool(addrs []string, maxQueries int, log *log.Logger) *ResolverPool {\n\tif len(addrs) <= 0 {\n\t\treturn nil\n\t}\n\n\t// Do not allow the number of resolvers to exceed the ulimit\n\ttemp := addrs\n\taddrs = []string{}\n\tmax := int(float64(limits.GetFileLimit())*0.7) / 2\n\tfor i, r := range temp {\n\t\tif i > max {\n\t\t\tbreak\n\t\t}\n\t\taddrs = append(addrs, r)\n\t}\n\n\tfinished := make(chan Resolver, 100)\n\tfor _, addr := range addrs {\n\t\tgo func(ip string, ch chan Resolver) {\n\t\t\tif n := NewBaseResolver(ip); n != nil {\n\t\t\t\tch <- n\n\t\t\t\treturn\n\t\t\t}\n\t\t\tch <- nil\n\t\t}(addr, finished)\n\t}\n\n\tl := len(addrs)\n\tvar resolvers []Resolver\n\tt := time.NewTimer(5 * time.Second)\n\tdefer t.Stop()\nloop:\n\tfor i := 0; i < l; i++ {\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\tbreak loop\n\t\tcase r := <-finished:\n\t\t\tif r != nil {\n\t\t\t\tresolvers = append(resolvers, r)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(resolvers) == 0 {\n\t\treturn nil\n\t}\n\treturn NewResolverPool(resolvers, maxQueries, log)\n}",
"func NewResolverPool(res []Resolver, logger *log.Logger) *ResolverPool {\n\trp := &ResolverPool{\n\t\tResolvers: res,\n\t\tDone: make(chan struct{}, 2),\n\t\tLog: logger,\n\t\twildcards: make(map[string]*wildcard),\n\t\tdomainCache: make(map[string]struct{}),\n\t}\n\n\t// Assign a null logger when one is not provided\n\tif rp.Log == nil {\n\t\trp.Log = log.New(ioutil.Discard, \"\", 0)\n\t}\n\n\trp.SanityChecks()\n\treturn rp\n}",
"func NewConflictResolver(\n\tconfig Config, fbo *folderBranchOps) *ConflictResolver {\n\t// make a logger with an appropriate module name\n\tbranchSuffix := \"\"\n\tif fbo.branch() != data.MasterBranch {\n\t\tbranchSuffix = \" \" + string(fbo.branch())\n\t}\n\ttlfStringFull := fbo.id().String()\n\tlog := config.MakeLogger(\n\t\tfmt.Sprintf(\"CR %s%s\", tlfStringFull[:8], branchSuffix))\n\n\tcr := &ConflictResolver{\n\t\tconfig: config,\n\t\tfbo: fbo,\n\t\tprepper: folderUpdatePrepper{\n\t\t\tconfig: config,\n\t\t\tfolderBranch: fbo.folderBranch,\n\t\t\tblocks: &fbo.blocks,\n\t\t\tlog: log,\n\t\t\tvlog: config.MakeVLogger(log),\n\t\t},\n\t\tlog: traceLogger{log},\n\t\tdeferLog: traceLogger{log.CloneWithAddedDepth(1)},\n\t\tmaxRevsThreshold: crMaxRevsThresholdDefault,\n\t\tcurrInput: conflictInput{\n\t\t\tunmerged: kbfsmd.RevisionUninitialized,\n\t\t\tmerged: kbfsmd.RevisionUninitialized,\n\t\t},\n\t}\n\n\tif fbo.bType == standard && config.Mode().ConflictResolutionEnabled() {\n\t\tcr.startProcessing(libcontext.BackgroundContextWithCancellationDelayer())\n\t}\n\treturn cr\n}",
"func New(cfg config.Config, log *logrus.Logger) error {\n\tvar tpl bytes.Buffer\n\tvars := map[string]interface{}{\n\t\t\"typename\": getTypeName(cfg.Repository.URL),\n\t}\n\n\tindexMappingTemplate, _ := template.New(\"geo_mapping\").Parse(`{\n\t\t\"mappings\": {\n\t\t\t\"{{ .typename }}\": {\n\t\t\t\t\"properties\": {\n\t\t\t\t\t\"geometry\": {\n\t\t\t\t\t\t\"type\": \"geo_shape\"\n\t\t\t\t\t},\n \"collection\": {\n \"type\": \"text\",\n \"fielddata\": true\n }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}`)\n\n\tindexMappingTemplate.Execute(&tpl, vars)\n\n\tctx := context.Background()\n\n\tclient, err := createClient(&cfg.Repository)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tindexName := getIndexName(cfg.Repository.URL)\n\n\tcreateIndex, err := client.CreateIndex(indexName).Body(tpl.String()).Do(ctx)\n\tif err != nil {\n\t\terrorText := fmt.Sprintf(\"Cannot create repository: %v\\n\", err)\n\t\tlog.Errorf(errorText)\n\t\treturn errors.New(errorText)\n\t}\n\tif !createIndex.Acknowledged {\n\t\treturn errors.New(\"CreateIndex was not acknowledged. Check that timeout value is correct.\")\n\t}\n\n\tlog.Debug(\"Creating Repository\" + cfg.Repository.URL)\n\tlog.Debug(\"Type: \" + cfg.Repository.Type)\n\tlog.Debug(\"URL: \" + cfg.Repository.URL)\n\n\treturn nil\n}",
"func NewGeoIPDB(name string, loader BlocklistLoader, geoDBFile string) (*GeoIPDB, error) {\n\tif geoDBFile == \"\" {\n\t\tgeoDBFile = \"/usr/share/GeoIP/GeoLite2-City.mmdb\"\n\t}\n\tgeoDB, err := maxminddb.Open(geoDBFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open geo location database file: %w\", err)\n\t}\n\n\trules, err := loader.Load()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdb := make(map[uint64]struct{})\n\tfor _, r := range rules {\n\t\tr = strings.TrimSpace(r)\n\t\tif strings.HasPrefix(r, \"#\") || r == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tr = strings.Split(r, \"#\")[0] // possible comment at the end of the line\n\t\tr = strings.TrimSpace(r)\n\t\tvalue, err := strconv.ParseUint(r, 10, 64) // GeoNames ID\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to parse geoname id in rule '%s': %w\", r, err)\n\t\t}\n\t\tdb[value] = struct{}{}\n\t}\n\treturn &GeoIPDB{\n\t\tname: name,\n\t\tgeoDB: geoDB,\n\t\tgeoDBFile: geoDBFile,\n\t\tdb: db,\n\t\tloader: loader,\n\t}, nil\n}",
"func New(refHostname string, optFuncs ...Opt) (remotes.Resolver, error) {\n\tvar o opts\n\tfor _, of := range optFuncs {\n\t\tof(&o)\n\t}\n\tvar authzOpts []docker.AuthorizerOpt\n\tif authCreds, err := NewAuthCreds(refHostname); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tauthzOpts = append(authzOpts, docker.WithAuthCreds(authCreds))\n\t}\n\tauthz := docker.NewDockerAuthorizer(authzOpts...)\n\tplainHTTPFunc := docker.MatchLocalhost\n\tif o.plainHTTP {\n\t\tplainHTTPFunc = docker.MatchAllHosts\n\t}\n\tregOpts := []docker.RegistryOpt{\n\t\tdocker.WithAuthorizer(authz),\n\t\tdocker.WithPlainHTTP(plainHTTPFunc),\n\t}\n\tif o.skipVerifyCerts {\n\t\ttr := &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: true,\n\t\t\t},\n\t\t}\n\t\tclient := &http.Client{\n\t\t\tTransport: tr,\n\t\t}\n\t\tregOpts = append(regOpts, docker.WithClient(client))\n\t}\n\tresovlerOpts := docker.ResolverOptions{\n\t\tHosts: docker.ConfigureDefaultRegistries(regOpts...),\n\t}\n\tresolver := docker.NewResolver(resovlerOpts)\n\treturn resolver, nil\n}",
"func NewPool(fn ResolverFactory) *Pool {\n\treturn &Pool{\n\t\tfactory: fn,\n\t}\n}",
"func NewMockResolver() *MockResolver {\n\treturn &MockResolver{\n\t\tCommitGraphFunc: &ResolverCommitGraphFunc{\n\t\t\tdefaultHook: func(context.Context, int) (graphqlbackend.CodeIntelligenceCommitGraphResolver, error) {\n\t\t\t\treturn nil, nil\n\t\t\t},\n\t\t},\n\t\tDeleteIndexByIDFunc: &ResolverDeleteIndexByIDFunc{\n\t\t\tdefaultHook: func(context.Context, int) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\tDeleteUploadByIDFunc: &ResolverDeleteUploadByIDFunc{\n\t\t\tdefaultHook: func(context.Context, int) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\tGetIndexByIDFunc: &ResolverGetIndexByIDFunc{\n\t\t\tdefaultHook: func(context.Context, int) (dbstore.Index, bool, error) {\n\t\t\t\treturn dbstore.Index{}, false, nil\n\t\t\t},\n\t\t},\n\t\tGetIndexesByIDsFunc: &ResolverGetIndexesByIDsFunc{\n\t\t\tdefaultHook: func(context.Context, ...int) ([]dbstore.Index, error) {\n\t\t\t\treturn nil, nil\n\t\t\t},\n\t\t},\n\t\tGetUploadByIDFunc: &ResolverGetUploadByIDFunc{\n\t\t\tdefaultHook: func(context.Context, int) (dbstore.Upload, bool, error) {\n\t\t\t\treturn dbstore.Upload{}, false, nil\n\t\t\t},\n\t\t},\n\t\tGetUploadsByIDsFunc: &ResolverGetUploadsByIDsFunc{\n\t\t\tdefaultHook: func(context.Context, ...int) ([]dbstore.Upload, error) {\n\t\t\t\treturn nil, nil\n\t\t\t},\n\t\t},\n\t\tIndexConfigurationFunc: &ResolverIndexConfigurationFunc{\n\t\t\tdefaultHook: func(context.Context, int) ([]byte, error) {\n\t\t\t\treturn nil, nil\n\t\t\t},\n\t\t},\n\t\tIndexConnectionResolverFunc: &ResolverIndexConnectionResolverFunc{\n\t\t\tdefaultHook: func(dbstore.GetIndexesOptions) *resolvers.IndexesResolver {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\tQueryResolverFunc: &ResolverQueryResolverFunc{\n\t\t\tdefaultHook: func(context.Context, *graphqlbackend.GitBlobLSIFDataArgs) (resolvers.QueryResolver, error) {\n\t\t\t\treturn nil, nil\n\t\t\t},\n\t\t},\n\t\tQueueAutoIndexJobForRepoFunc: &ResolverQueueAutoIndexJobForRepoFunc{\n\t\t\tdefaultHook: func(context.Context, int) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\tUpdateIndexConfigurationByRepositoryIDFunc: &ResolverUpdateIndexConfigurationByRepositoryIDFunc{\n\t\t\tdefaultHook: func(context.Context, int, string) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\tUploadConnectionResolverFunc: &ResolverUploadConnectionResolverFunc{\n\t\t\tdefaultHook: func(dbstore.GetUploadsOptions) *resolvers.UploadsResolver {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t}\n}",
"func newManager() *roolManager {\n\treturn &roolManager{pathes: make(map[string]*rool)}\n}",
"func (*lbManualResolver) Close() {}",
"func newNSManager() (*nsManager, error) {\n\tnsm := &nsManager{}\n\terr := nsm.init()\n\treturn nsm, err\n}",
"func NewDefault(m map[string]interface{}) (share.Manager, error) {\n\tc := &config{}\n\tif err := mapstructure.Decode(m, c); err != nil {\n\t\terr = errors.Wrap(err, \"error creating a new manager\")\n\t\treturn nil, err\n\t}\n\n\ts, err := metadata.NewCS3Storage(c.GatewayAddr, c.ProviderAddr, c.ServiceUserID, c.ServiceUserIdp, c.MachineAuthAPIKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tindexer := indexer.CreateIndexer(s)\n\n\tclient, err := pool.GetGatewayServiceClient(c.GatewayAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn New(client, s, indexer)\n}",
"func newLocation(lat, long coordinate) *location {\n\treturn &location{lat.decimal(), long.decimal()}\n}",
"func newRouter() *Router {\n\treturn &Router{routes: make([]*Route, 0)}\n}",
"func (_BaseContentSpace *BaseContentSpaceCaller) LibraryFactory(opts *bind.CallOpts) (common.Address, error) {\n\tvar out []interface{}\n\terr := _BaseContentSpace.contract.Call(opts, &out, \"libraryFactory\")\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}",
"func NewCustomResolver(hosts map[string][]string) Resolver {\n\treturn &resolver{\n\t\thosts: hosts,\n\t}\n}",
"func newAzureNetworkMapper() *AzureNetworkMapper {\n\treturn &AzureNetworkMapper{}\n}",
"func New(precision Accuracy) *GeoBass {\n\treturn &GeoBass{\n\t\titems: make(map[uint64]interface{}),\n\t\tprecision: precision,\n\t}\n}",
"func newRouter() *router {\n\treturn &router{\n\t\troots: make(map[string]*node),\n\t}\n}",
"func New(ipAddress, ipStackAPIToken string, sensitivity int) (*Geofence, error) {\n\t// Create new client for ipstack.com\n\tipStackClient, err := ipstack.New(ipStackAPIToken)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Ensure sensitivity is between 1 - 5\n\terr = validateSensitivity(sensitivity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// New Geofence object\n\tgeofence := &Geofence{\n\t\tIPStackClient: ipStackClient,\n\t\tSensitivity: sensitivity,\n\t}\n\n\t// If no ip address passed, get current device location details\n\tif ipAddress == \"\" {\n\t\tcurrentHostLocation, err := geofence.IPStackClient.Me()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgeofence.Latitude = currentHostLocation.Latitide\n\t\tgeofence.Longitude = currentHostLocation.Longitude\n\t\t// If address is passed, fetch details for it\n\t} else {\n\t\terr = validateIPAddress(ipAddress)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tremoteHostLocation, err := geofence.IPStackClient.IP(ipAddress)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgeofence.Latitude = remoteHostLocation.Latitide\n\t\tgeofence.Longitude = remoteHostLocation.Longitude\n\t}\n\treturn geofence, nil\n}",
"func (gc *LinearConverter) MaxLongitude() float64 {\n\treturn gc.maxLon\n}",
"func stdlibResolver() Resolver { return stdlib{} }",
"func NewResolver(resolverName string) (Resolver, error) {\n\tswitch strings.ToLower(resolverName) {\n\tcase OpenDNSName:\n\t\treturn newOpenDNSResolver(), nil\n\tcase IFConfigName, IFConfigCoName:\n\t\treturn &ifConfigResolver{url: ifConfigCoURL}, nil\n\tcase IFConfigMeName:\n\t\treturn &ifConfigResolver{url: ifConfigMeURL}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"%w: %s\", errUnknownResolver, resolverName)\n\t}\n}",
"func NewManager(mgmURL string, simianURL string, pers persist.MGMDB, osdb persist.Database, log logger.Log) Manager {\n\trMgr := regionMgr{}\n\trMgr.simianURL = simianURL\n\trMgr.mgmURL = mgmURL\n\trMgr.mgm = pers\n\trMgr.osdb = osdb\n\trMgr.log = logger.Wrap(\"REGION\", log)\n\treturn rMgr\n}",
"func NewRouter(opts ...RouterOptionFunc) *Router {\n\trouter := &Router{map[uint8]IModule{}, FullRouteEnabler, nil, nil}\n\tfor _, opt := range opts {\n\t\topt(router)\n\t}\n\treturn router\n}",
"func NewManager() *Manager {\n\treturn &Manager{requestEndpoint: &RequestEndpoint{}, distReq: &GoogleDistanceRequester{}}\n}",
"func (s StaticInfoExtn_GeoInfo_Location) NewInterfaces(n int32) (capnp.UInt64List, error) {\n\tl, err := capnp.NewUInt64List(s.Struct.Segment(), n)\n\tif err != nil {\n\t\treturn capnp.UInt64List{}, err\n\t}\n\terr = s.Struct.SetPtr(1, l.List.ToPtr())\n\treturn l, err\n}",
"func NewPlanner()(*Planner) {\n m := &Planner{\n Entity: *NewEntity(),\n }\n return m\n}",
"func New() confmap.Provider {\n\treturn &provider{}\n}",
"func newGameServerAllocations(c *AllocationV1Client, namespace string) *gameServerAllocations {\n\treturn &gameServerAllocations{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}",
"func NewAddresser() Addresser { return &addresser{execute: rtnlExecute} }",
"func NewMaplAdapter(port string, rulesFilename string) (Server, error) {\n\n\t//log.Println(Params)\n\n\n\tif Params.Logging{\n\t\t/* in remarks. just output to stdout and use kubectl logs...\n\t\t// setup a log outfile file\n\t\tf, err := os.OpenFile(\"log.txt\", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0777)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\tdefer f.Close()\n\t\tlog.SetOutput(f) //set output of logs to f\n\t\t*/\n\t}else{\n\t\tlog.SetOutput(ioutil.Discard) // output discarded if no log is needed\n\t}\n\t// -------------------------\n\n\tif port == \"\" {\n\t\tport = \"0\"\n\t}\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\":%s\", port))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to listen on socket: %v\", err)\n\t}\n\ts := &MaplAdapter{\n\t\tlistener: listener,\n\t\trules: MAPL_engine.YamlReadRulesFromFile(rulesFilename),\n\t}\n\tlog.Printf(\"read %v rules from file \\\"%v\\\"\\n\",len(s.rules.Rules),rulesFilename)\n\tlog.Printf(\"listening on \\\"%v\\\"\\n\", s.Addr())\n\ts.server = grpc.NewServer()\n\tauthorization.RegisterHandleAuthorizationServiceServer(s.server, s)\n\n\treturn s, nil\n}"
] | [
"0.62867504",
"0.57990015",
"0.5724626",
"0.5724626",
"0.56279874",
"0.5578216",
"0.5465597",
"0.5409691",
"0.53667367",
"0.5352722",
"0.53365004",
"0.5303146",
"0.5284972",
"0.5262867",
"0.5259484",
"0.5229253",
"0.5205475",
"0.5205475",
"0.5202448",
"0.520197",
"0.52008885",
"0.5174903",
"0.51720625",
"0.51652545",
"0.51582336",
"0.5132762",
"0.5085141",
"0.505626",
"0.5050347",
"0.5036794",
"0.5034839",
"0.5032302",
"0.49973097",
"0.4963503",
"0.4959855",
"0.4952453",
"0.49462694",
"0.49462694",
"0.48982415",
"0.48812917",
"0.48664385",
"0.48631978",
"0.48604405",
"0.4860259",
"0.4856961",
"0.4848125",
"0.48292252",
"0.48162055",
"0.4810549",
"0.48077917",
"0.4804945",
"0.47875983",
"0.47666255",
"0.47637868",
"0.4750949",
"0.47252765",
"0.4720353",
"0.47160292",
"0.47117215",
"0.4687262",
"0.4678808",
"0.46724522",
"0.4661208",
"0.45432597",
"0.45364076",
"0.4529696",
"0.45017624",
"0.44950196",
"0.44785786",
"0.447328",
"0.44711465",
"0.44706538",
"0.44549206",
"0.44521913",
"0.44422352",
"0.44318694",
"0.4412051",
"0.4407188",
"0.43945026",
"0.43938592",
"0.43890956",
"0.4388897",
"0.43542624",
"0.43374917",
"0.43362528",
"0.43345973",
"0.432743",
"0.43243447",
"0.43223423",
"0.43203333",
"0.43177897",
"0.43175307",
"0.42998618",
"0.42953703",
"0.429216",
"0.4285064",
"0.42833444",
"0.42696393",
"0.42538697",
"0.4253604"
] | 0.79387987 | 0 |
GetPath provides path to MaxMind Geo Library there is only one possible path where the lib file can be found: $HOME/.tango/GeoLite2City.mmdb $HOME path should be different on diff OS | func (r *MaxMindGeoLibResolver) GetPath() (string, error) {
homeDirectory := r.homeDirResolver.GetPath()
maxmindGeoLibPath := filepath.Join(homeDirectory, "GeoLite2-City.mmdb")
_, maxmindGeoLibExistError := os.Stat(maxmindGeoLibPath)
return maxmindGeoLibPath, maxmindGeoLibExistError
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func SpatialiteModulePath() string {\n\tvar libExtension string\n\t// FIXME: Does Plan9 use .so? Where does Windows put the library?\n\tswitch runtime.GOOS {\n\tcase \"darwin\":\n\t\tlibExtension = \".dylib\"\n\tcase \"windows\":\n\t\tlibExtension = \".dll\"\n\tdefault:\n\t\tlibExtension = \".so\"\n\t}\n\n\tvar directory string\n\tif fileExists(libFile(\"/usr/local/lib\", libExtension)) {\n\t\tdirectory = \"/usr/local/lib\"\n\t} else if fileExists(libFile(\"/usr/lib64\", libExtension)) {\n\t\tdirectory = \"/usr/lib64\"\n\t} else if fileExists(libFile(\"/usr/lib\", libExtension)) {\n\t\tdirectory = \"/usr/lib\"\n\t} else {\n\t\tlog.Fatalf(\"Unable to find valid path for mod_spatialite.\")\n\t}\n\n\treturn libFile(directory, libExtension)\n}",
"func GetDbPath() string {\n\tdirectory := GetDbDir()\n\tfile := getEnv(\"ENM_DB_FILE\", \"enm.db\")\n\n\treturn path.Join(directory, file)\n}",
"func (p *CProject) LibPath(f *File) string {\n base := p.LibName(f) + \".so\"\n\n return filepath.Join(p.dstDir, base)\n}",
"func GetDatabasePath() (string, error) {\n usr, err := user.Current()\n if err != nil {\n return \"\", err\n }\n return path.Join(usr.HomeDir, \".jmpdata\"), nil\n}",
"func (s *Server) data_path() (path string) {\n\tpaths := STRINGS.Split(OS.Getenv(\"GOPATH\"), \";\")\n\tfor k := range paths {\n\t\tpath = paths[k] + \"/src/FKGoServer/FKGRpc_GeoOP/Res/GeoIP2-City.mmdb\"\n\t\t_, err := OS.Lstat(path)\n\t\tif err == nil {\n\t\t\treturn path\n\t\t}\n\t}\n\treturn\n}",
"func (p *MemPkg) Path() string { return p.path }",
"func (_BaseAccessWallet *BaseAccessWalletCaller) GetLibrary(opts *bind.CallOpts, position *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"getLibrary\", position)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}",
"func goPath() string {\n\tgpDefault := build.Default.GOPATH\n\tgps := filepath.SplitList(gpDefault)\n\n\treturn gps[0]\n}",
"func NewMaxMindGeoLibResolver(homeDirResolver *filesystem.HomeDirResolver) *MaxMindGeoLibResolver {\n\treturn &MaxMindGeoLibResolver{\n\t\thomeDirResolver: homeDirResolver,\n\t}\n}",
"func (c *client) GetTKGBoMDirectory() (string, error) {\n\ttkgDir, err := c.GetTKGDirectory()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(tkgDir, constants.LocalBOMsFolderName), nil\n}",
"func (db *LDB) Location() string {\n return db.path\n}",
"func resolveBitcodePath(bcPath string) string {\n\tif _, err := os.Stat(bcPath); os.IsNotExist(err) {\n\t\t// If the bitcode file does not exist, try to find it in the store\n\t\tif LLVMBitcodeStorePath != \"\" {\n\t\t\t// Compute absolute path hash\n\t\t\tabsBcPath, _ := filepath.Abs(bcPath)\n\t\t\tstoreBcPath := path.Join(LLVMBitcodeStorePath, getHashedPath(absBcPath))\n\t\t\tif _, err := os.Stat(storeBcPath); os.IsNotExist(err) {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\treturn storeBcPath\n\t\t}\n\t\tLogWarning(\"Failed to find the file %v\\n\", bcPath)\n\t\treturn \"\"\n\t}\n\treturn bcPath\n}",
"func GetModemFirmwarePath() string {\n\treturn \"/opt/google/modemfwd-firmware/\"\n}",
"func getLibraryName(path string) string {\n\ti := strings.LastIndex(path, vendirDirMatch)\n\tif i == -1 {\n\t\treturn path\n\t}\n\n\ti += len(vendirDirMatch)\n\tif len(path) < i {\n\t\treturn path\n\t}\n\n\tpkg := path[i:]\n\tpkg = filepath.Dir(pkg)\n\tstrings.Replace(pkg, `\\`, `/`, -1)\n\treturn pkg\n}",
"func (m *Win32LobAppFileSystemDetection) GetPath()(*string) {\n val, err := m.GetBackingStore().Get(\"path\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func GetModemHelperPath() string {\n\treturn \"/opt/google/modemfwd-helpers/\"\n}",
"func (c *Client) MaxmindGeoLite(resource, queryTime string) (map[string]interface{}, error) {\n\tm := make(map[string]string)\n\tm[\"resource\"] = resource\n\tm[\"query_time\"] = queryTime\n\treturn c.execute(maxmindGeoLitePath, m)\n}",
"func GetBadgerDbPath(dataDir string) string {\n\treturn filepath.Join(dataDir, badgerDbFolder)\n}",
"func (_AccessIndexor *AccessIndexorCaller) GetLibrary(opts *bind.CallOpts, position *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _AccessIndexor.contract.Call(opts, &out, \"getLibrary\", position)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}",
"func GetGobin() (string, error) {\n\t// Get GOPATH.\n\tgopath := os.Getenv(\"GOPATH\")\n\tif gopath == \"\" {\n\t\tgopath = build.Default.GOPATH\n\t}\n\n\t// Prepare destination path.\n\tbinPath := path.Join(gopath, \"bin\")\n\tif err := os.MkdirAll(binPath, 0755); err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"cannot mkdir %v\", binPath)\n\t}\n\n\treturn binPath, nil\n}",
"func (module *sdkLibraryXml) implPath(ctx android.ModuleContext) string {\n\timplName := proptools.String(module.properties.Lib_name)\n\tif apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo); !apexInfo.IsForPlatform() {\n\t\t// TODO(b/146468504): ApexVariationName() is only a soong module name, not apex name.\n\t\t// In most cases, this works fine. But when apex_name is set or override_apex is used\n\t\t// this can be wrong.\n\t\treturn fmt.Sprintf(\"/apex/%s/javalib/%s.jar\", apexInfo.ApexVariationName, implName)\n\t}\n\tpartition := \"system\"\n\tif module.SocSpecific() {\n\t\tpartition = \"vendor\"\n\t} else if module.DeviceSpecific() {\n\t\tpartition = \"odm\"\n\t} else if module.ProductSpecific() {\n\t\tpartition = \"product\"\n\t} else if module.SystemExtSpecific() {\n\t\tpartition = \"system_ext\"\n\t}\n\treturn \"/\" + partition + \"/framework/\" + implName + \".jar\"\n}",
"func gopath() string {\n\trootDir, _ := rootDir()\n\treturn filepath.Join(rootDir, \".gong.deps\")\n}",
"func downloadGeoLite2Db(maxmindDBLicense string) error {\n\t// Download the GeoLite2Db .tar.gz file with the database inside it.\n\tr, err := http.Get(fmt.Sprintf(\"https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-City&license_key=%s&suffix=tar.gz\", maxmindDBLicense))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create a temporary directory to untar downloaded .tar.gz with database.\n\ttempDir, err := ioutil.TempDir(\"\", \"geoip\")\n\t// Delete temporary directory.\n\tdefer func(tempDir string) {\n\t\terr := os.RemoveAll(tempDir)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}(tempDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create a temporary file to store downloaded .tar.gz with database.\n\ttempFile, err := ioutil.TempFile(\"\", \"geoip*.tar.gz\")\n\t// Delete temporary file.\n\tdefer func(tempFile *os.File) {\n\t\terr := os.Remove(tempFile.Name())\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}(tempFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Copy bytes from downloaded file to temporary file.\n\t_, err = io.Copy(tempFile, r.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Untar the downloaded file to the temporary directory.\n\terr = archiver.Unarchive(tempFile.Name(), tempDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create the path to move decompressed database file.\n\terr = os.MkdirAll(dbPath, 0o755)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Find geoip.geoLite2DbName inside the tempDir.\n\terr = filepath.Walk(tempDir, func(p string, i fs.FileInfo, err error) error {\n\t\tif i.Name() == geoLite2DbName {\n\t\t\t// Move from temporary directory to geoip.geoLite2DbName to geoip.dbPath.\n\t\t\terr := os.Rename(p, dbPath+geoLite2DbName)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func getRepoPath() (string, error) {\n\t// Set default base path and directory name\n\tdirectoryName := \".saturn\"\n\n\t// Join the path and directory name, then expand the home path\n\tfullPath, err := homedir.Expand(filepath.Join(\"~\", directoryName))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Return the shortest lexical representation of the path\n\treturn filepath.Clean(fullPath), nil\n}",
"func KMToDBPath(dir string, km *km.KeyManager) (string, error) {\n\n\tidPubKey, err := km.IdentityPublicKey()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Abs(filepath.Join(dir, idPubKey+\".db\"))\n\n}",
"func Location() (path string, err error) {\n\tif ocmconfig := os.Getenv(\"OCM_CONFIG\"); ocmconfig != \"\" {\n\t\treturn ocmconfig, nil\n\t}\n\n\t// Determine home directory to use for the legacy file path\n\thome, err := homedir.Dir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpath = filepath.Join(home, \".ocm.json\")\n\n\t_, err = os.Stat(path)\n\tif os.IsNotExist(err) {\n\t\t// Determine standard config directory\n\t\tconfigDir, err := os.UserConfigDir()\n\t\tif err != nil {\n\t\t\treturn path, err\n\t\t}\n\n\t\t// Use standard config directory\n\t\tpath = filepath.Join(configDir, \"/ocm/ocm.json\")\n\t}\n\n\treturn path, nil\n}",
"func getDroneDBPath() string {\n\treturn path.Join(getDronePath(), \"db\")\n}",
"func GetBasePath() string {\n\tvendorDir := filepath.Join(GetHomeDir(), \".autoai\")\n\tCreateFolderIfNotExist(vendorDir)\n\ttargetDir := filepath.Join(vendorDir, \"aid\")\n\treturn targetDir\n}",
"func (lr *libraryCache) GetLibrary() (*library.LibraryResolver, error) {\n\tlr.mtx.Lock()\n\tdefer lr.mtx.Unlock()\n\n\tif lr.refCount == 0 {\n\t\tp, err := ioutil.TempDir(\"\", \"skiff-core-scratch-\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlr.path = p\n\t} else {\n\t\tlr.refCount++\n\t\treturn lr.lib, nil\n\t}\n\n\tlib, err := library.BuildLibraryResolver(lr.path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlr.lib = lib\n\tlr.refCount++\n\treturn lib, nil\n}",
"func GetLatitudeAndLongitude(ip string) (lat, lon float64, radius uint16) {\n\tgeoIpdb, err := geoip2.Open(\"databases/GeoLite2-City.mmdb\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer geoIpdb.Close()\n\n\tipAddress := net.ParseIP(ip)\n\trecord, err := geoIpdb.City(ipAddress)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn -10000, -10000, 65535\n\t}\n\tlat = record.Location.Latitude\n\tlon = record.Location.Longitude\n\tradius = record.Location.AccuracyRadius\n\treturn\n}",
"func (c *Config) SecurityProviderLibPath() string {\n\tconfiguredLibs := c.backend.GetString(\"client.BCCSP.security.library\")\n\tlibPaths := strings.Split(configuredLibs, \",\")\n\tlogger.Debugf(\"Configured BCCSP Lib Paths %s\", libPaths)\n\tvar lib string\n\tfor _, path := range libPaths {\n\t\tif _, err := os.Stat(strings.TrimSpace(path)); !os.IsNotExist(err) {\n\t\t\tlib = strings.TrimSpace(path)\n\t\t\tbreak\n\t\t}\n\t}\n\tif lib != \"\" {\n\t\tlogger.Debugf(\"Found softhsm library: %s\", lib)\n\t} else {\n\t\tlogger.Debug(\"Softhsm library was not found\")\n\t}\n\treturn lib\n}",
"func Gopath() (gp string) {\n\tgopaths := strings.Split(os.Getenv(\"GOPATH\"), string(filepath.ListSeparator))\n\n\tif len(gopaths) == 1 && gopaths[0] != \"\" {\n\t\treturn gopaths[0]\n\t}\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn\n\t}\n\tabspwd, err := filepath.Abs(pwd)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, gopath := range gopaths {\n\t\tif gopath == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tabsgp, err := filepath.Abs(gopath)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif strings.HasPrefix(abspwd, absgp) {\n\t\t\treturn absgp\n\t\t}\n\t}\n\treturn build.Default.GOPATH\n}",
"func getConfigPath(path string) (file string) {\r\n\treturn fmt.Sprintf(\"%s/%s\", path, \"app.ini\")\r\n}",
"func lookupProjPath(protoAbs string) (result string) {\n\tlastIndex := len(protoAbs)\n\tcurPath := protoAbs\n\n\tfor lastIndex > 0 {\n\t\tif fileExist(curPath+\"/cmd\") && fileExist(curPath+\"/api\") {\n\t\t\tresult = curPath\n\t\t\treturn\n\t\t}\n\t\tlastIndex = strings.LastIndex(curPath, string(os.PathSeparator))\n\t\tcurPath = protoAbs[:lastIndex]\n\t}\n\tresult = \"\"\n\treturn\n}",
"func (config *SQLConfiguration) GetPath() string {\n\tvar path, defaultFile, customFile string\n\tpath = \"database/\"\n\tdefaultFile = path + \"default.json\"\n\tcustomFile = path + \"custom.json\"\n\tif _, err := os.Open(\"conf/\" + customFile); err == nil {\n\t\treturn customFile\n\t}\n\treturn defaultFile\n}",
"func getRenvLibrary(rpath string) (string, error) {\n\tlog.Trace(\"invoking renv to get library path\")\n\n\trs := rcmd.NewRSettings(rpath)\n\tres, err := rcmd.RunRscriptWithArgs(\n\t\tafero.NewOsFs(), \"\", rs,\n\t\t[]string{\"-e\", \"cat('\\n_pkgr_', renv::paths$library(), '_pkgr_\\n', sep = '')\"},\n\t\t\"\")\n\n\tif err != nil {\n\t\tif exerr, ok := err.(*exec.ExitError); ok {\n\t\t\tlog.Warnf(\"error getting library path from renv: %s\\n\",\n\t\t\t\texerr.Stderr)\n\t\t} else {\n\t\t\tlog.Warnf(\"error getting library path from renv: %s\\n\",\n\t\t\t\terr)\n\t\t}\n\n\t\treturn \"\", err\n\t}\n\n\tmarker := \"_pkgr_\"\n\tvar lib string\n\tlines := rp.ScanLines(res)\n\tfor _, l := range lines {\n\t\tif strings.HasPrefix(l, marker) && strings.HasSuffix(l, marker) {\n\t\t\tlib = strings.TrimSuffix(strings.TrimPrefix(l, marker), marker)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif lib == \"\" {\n\t\tlog.Warnf(\"did not find renv library in output:\\n %q\\n\", lines)\n\n\t\treturn \"\", errors.New(\"Malformed renv library path\")\n\t}\n\n\treturn lib, nil\n}",
"func getProjectPath(defaultProjectPath, defaultDownloadPath string) (currentConfigPath string, backupConfigPath string,\n\tlatestConfigPath string, btfsBinaryPath string, btfsBackupPath string, latestBtfsBinaryPath string, err error) {\n\tif (runtime.GOOS == \"darwin\" || runtime.GOOS == \"linux\" || runtime.GOOS == \"windows\") && (runtime.GOARCH == \"amd64\" || runtime.GOARCH == \"386\") {\n\t\text := \"\"\n\t\tif runtime.GOOS == \"windows\" {\n\t\t\text = \".exe\"\n\t\t}\n\n\t\tcurrentConfigPath = fmt.Sprint(defaultProjectPath, \"config.yaml\")\n\t\tbackupConfigPath = fmt.Sprint(defaultDownloadPath, \"config.yaml.bk\")\n\t\tlatestConfigPath = fmt.Sprint(defaultDownloadPath, fmt.Sprintf(\"config_%s_%s.yaml\", runtime.GOOS, runtime.GOARCH))\n\t\tbtfsBinaryPath = fmt.Sprint(defaultProjectPath, fmt.Sprintf(\"btfs%s\", ext))\n\t\tbtfsBackupPath = fmt.Sprint(defaultDownloadPath, fmt.Sprintf(\"btfs%s.bk\", ext))\n\t\tlatestBtfsBinaryPath = fmt.Sprint(defaultDownloadPath, fmt.Sprintf(\"btfs-%s-%s%s\", runtime.GOOS, runtime.GOARCH, ext))\n\t} else {\n\t\tfmt.Printf(\"Operating system [%s], arch [%s] does not support automatic updates\\n\", runtime.GOOS, runtime.GOARCH)\n\t\treturn currentConfigPath, backupConfigPath, latestConfigPath, btfsBinaryPath, btfsBackupPath, latestBtfsBinaryPath, errors.New(\"os does not support automatic updates\")\n\t}\n\treturn\n}",
"func getMcConfigPath() (string, error) {\n\tdir, err := getMcConfigDir()\n\tif err != nil {\n\t\treturn \"\", NewIodine(iodine.New(err, nil))\n\t}\n\treturn filepath.Join(dir, mcConfigFile), nil\n}",
"func DMPath() string {\n\treturn os.Getenv(\"GOPATH\") + \"/src/github.com/digimakergo/digimaker\"\n}",
"func getConfigPath() (string, error) {\n\thome, homeErr := os.UserHomeDir()\n\tif homeErr == nil {\n\t\tif _, err := os.Stat(filepath.Join(home, \".bin\", \"config.json\")); !os.IsNotExist(err) {\n\t\t\treturn filepath.Join(path.Join(home, \".bin\")), nil\n\t\t}\n\t}\n\n\tc := os.Getenv(\"XDG_CONFIG_HOME\")\n\tif _, err := os.Stat(c); !os.IsNotExist(err) {\n\t\treturn filepath.Join(c, \"bin\"), nil\n\t}\n\n\tif homeErr != nil {\n\t\treturn \"\", homeErr\n\t}\n\tc = filepath.Join(home, \".config\")\n\tif _, err := os.Stat(c); !os.IsNotExist(err) {\n\t\treturn filepath.Join(c, \"bin\"), nil\n\t}\n\n\treturn filepath.Join(home, \".bin\"), nil\n}",
"func getPacoPath() string {\n\tpath := os.Getenv(\"PACOPATH\")\n\tif path == \"\" {\n\t\tpath = \".\"\n\t}\n\n\treturn path\n}",
"func (pp *protoPackage) pkgPath() string {\n\treturn strings.Replace(pp.Pkg, \".\", \"/\", -1)\n}",
"func Gopath() string {\n\treturn os.Getenv(gopathEnv)\n}",
"func getCacheDir() string {\n\tcacheRoot := os.ExpandEnv(\"$HOME/.cache\")\n\tif xdgCache, ok := os.LookupEnv(\"XDG_CACHE_HOME\"); ok {\n\t\tcacheRoot = xdgCache\n\t}\n\treturn filepath.Join(cacheRoot, \"barista\", \"http\")\n}",
"func retrieveImportPath(dirPath string) (string, error) {\n\tgoPath, err := exec.LookPath(\"go\")\n\n\tif err != nil {\n\t\treturn \"\", errors.New(\"Unable to retrieve go executable path , error:\" + err.Error())\n\t}\n\n\tcmd := exec.Command(goPath, \"list\")\n\tcmd.Dir = dirPath\n\tbytes, err := cmd.Output()\n\n\tif err != nil {\n\t\treturn \"\", errors.New(\n\t\t\t\"Unable to retrieve import path for directory, are you using go modules? Error: \" + err.Error(),\n\t\t)\n\t}\n\n\treturn strings.TrimSuffix(string(bytes), \"\\n\"), nil\n}",
"func (_BaseAccessControlGroup *BaseAccessControlGroupCaller) GetLibrary(opts *bind.CallOpts, position *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _BaseAccessControlGroup.contract.Call(opts, &out, \"getLibrary\", position)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}",
"func GetGobinPath(name string) (string, error) {\n\tgobinPath, err := GetGobin()\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"cannot get $GOPATH/bin path\")\n\t}\n\n\treturn path.Join(gobinPath, name), nil\n}",
"func (ref OpenDB) ParseLEFLibrary(filepath string) (err error) {\n\trc := C.ReadLib(ref.db, C.CString(filepath), C.CString(generateLibraryName(filepath)))\n\tif rc != 0 {\n\t\tcErr := C.GoString(C.LastError)\n\t\tif len(cErr) > 0 {\n\t\t\terr = fmt.Errorf(\"%v\", C.GoString(C.LastError))\n\t\t} else {\n\t\t\terr = fmt.Errorf(\"Unknown error has occured\")\n\t\t}\n\t}\n\treturn\n}",
"func (h Hashicorp) GetPath() string {\n\treturn h.FilePath\n}",
"func NewGeoIP(filePath string) (*GeoIP, error) {\n\t// 判断文件是否存在\n\t_, err := os.Stat(filePath)\n\tif err != nil && os.IsNotExist(err) {\n\t\tlog.Println(\"文件不存在,请自行下载 Geoip2 City库,并保存在\", filePath)\n\t\treturn nil, err\n\t} else {\n\t\tdb, err := geoip2.Open(filePath)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\treturn &GeoIP{db: db}, nil\n\t}\n}",
"func (c *Config) GetDatabasePath() string {\n\treturn c.strings[dbPathVar]\n}",
"func (m *PrinterLocation) GetLongitude()(*float64) {\n val, err := m.GetBackingStore().Get(\"longitude\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*float64)\n }\n return nil\n}",
"func (pr *PkgDecoder) PkgPath() string { return pr.pkgPath }",
"func GetPath(p string) (result string) {\n\tif !strings.HasSuffix(p, DepsFile) {\n\t\tresult = p + \"/\" + DepsFile\n\t}\n\tresult = filepath.Clean(result)\n\treturn\n}",
"func (module *SdkLibraryImport) DexJarBuildPath() android.Path {\n\t// The dex implementation jar extracted from the .apex file should be used in preference to the\n\t// source.\n\tif module.dexJarFile != nil {\n\t\treturn module.dexJarFile\n\t}\n\tif module.implLibraryModule == nil {\n\t\treturn nil\n\t} else {\n\t\treturn module.implLibraryModule.DexJarBuildPath()\n\t}\n}",
"func cliLocation() string {\n\tprofilePath, err := azcli.ProfilePath()\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tcfg, err := ini.Load(filepath.Join(filepath.Dir(profilePath), \"config\"))\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn cfg.Section(\"defaults\").Key(\"location\").Value()\n}",
"func getAptlyConfigPath() (string, error) {\n\tuserHomeDir, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn \"\", trace.Wrap(err, \"failed to get user home directory path\")\n\t}\n\n\tuserAptlyConfigPath := path.Join(userHomeDir, \".aptly.conf\")\n\t_, err = os.Stat(userAptlyConfigPath)\n\tif err == nil {\n\t\treturn userAptlyConfigPath, nil\n\t}\n\n\tif !errors.Is(err, os.ErrNotExist) {\n\t\treturn \"\", trace.Wrap(err, \"failed to check if %q exists\", userAptlyConfigPath)\n\t}\n\n\tsystemAptlyConfigPath := \"/etc/aptly.conf\"\n\t_, err = os.Stat(systemAptlyConfigPath)\n\tif err == nil {\n\t\treturn systemAptlyConfigPath, nil\n\t}\n\n\tif !errors.Is(err, os.ErrNotExist) {\n\t\treturn \"\", trace.Wrap(err, \"failed to check if %q exists\", systemAptlyConfigPath)\n\t}\n\n\treturn \"\", trace.Errorf(\"Aptly config not found at %q or %q\", userAptlyConfigPath, systemAptlyConfigPath)\n}",
"func getModulePath(repo string) (string, error) {\n\tb, err := utils.DownloadFile(repo, \"\", \"go.mod\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmodulePath := parser.ModulePath(b)\n\tif len(modulePath) == 0 {\n\t\treturn \"\", fmt.Errorf(\"module path: %s: unable to parse remote go.mod\", repo)\n\t}\n\n\treturn string(modulePath), nil\n}",
"func (r *HomeDirResolver) GetPath() string {\n\thomeDirectory, err := os.UserHomeDir()\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttangoHomeDirectory := filepath.Join(homeDirectory, \".tango\")\n\n\t// ensure that tango home dir is in place\n\tif _, err := os.Stat(tangoHomeDirectory); os.IsNotExist(err) {\n\t\tos.Mkdir(tangoHomeDirectory, os.ModePerm)\n\t}\n\n\treturn tangoHomeDirectory\n}",
"func (a BuildBlock) openCLib() *string {\n\t// open the c-shared library\n\tvar err error\n\tvar f []byte\n\tif runtime.GOOS == \"windows\" {\n\t\tf, err = ioutil.ReadFile(a.libpath + \"c_hieroglyph.dll\")\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Cannot open program c-shared library: %s\\n\", err)\n\t\t\treturn nil\n\t\t}\n\t} else if runtime.GOOS == \"linux\" {\n\t\tf, err = ioutil.ReadFile(a.libpath + \"c_hieroglyph.so\")\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Cannot open program c-shared library: %s\\n\", err)\n\t\t\treturn nil\n\t\t}\n\t}\n\tfile := string(f)\n\treturn &file\n}",
"func GetDbDir() string {\n\treturn getEnv(\"ENM_DB_DIRECTORY\", \"/data/database\")\n}",
"func (c *client) GetTKGConfigPath() (string, error) {\n\ttkgDir, err := c.GetTKGDirectory()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(tkgDir, constants.TKGConfigFileName), nil\n}",
"func (g *GetLanguagePackStringRequest) GetLanguagePackDatabasePath() (value string) {\n\tif g == nil {\n\t\treturn\n\t}\n\treturn g.LanguagePackDatabasePath\n}",
"func get_target_path(arch string, version string) string {\n\tvar target_path string\n\tif version == \"nightly\" {\n\t\ttarget_path = arch\n\t} else {\n\t\tdirectories := get_directories(cache_instance, db, arch)\n\t\tmTime := time.Time(dropbox.DBTime{})\n\t\tvar latest_directory dropbox.Entry\n\t\tfor _, dir := range directories {\n\t\t\tif strings.Contains(dir.Path, version) {\n\t\t\t\tif time.Time(dir.Modified).After(mTime) {\n\t\t\t\t\tmTime = time.Time(dir.Modified)\n\t\t\t\t\tlatest_directory = dir\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttarget_path = latest_directory.Path\n\t}\n\treturn target_path\n}",
"func getConfigFilePath() (string, error) {\n var err error\n configPath := configdir.LocalConfig(\"road-trip\")\n err = configdir.MakePath(configPath) // Ensure it exists.\n if err != nil {\n return \"\", errors.New(\"Cannot access folder: '\" + configPath + \"' to store config file.\")\n }\n\n return configPath + string(os.PathSeparator) + \"player.yaml\", nil\n}",
"func GetSurgeDir() string {\n\treturn os.Getenv(\"APPDATA\") + string(os.PathSeparator) + \"Surge\"\n}",
"func (c *client) Path() string {\n\tblockRange := os.Getenv(\"BLOCK_RANGE\")\n\tif blockRange == \"\" {\n\t\tblockRange = defaultBlockRange\n\t}\n\tstr, err := filepath.Abs(\"testutil/dbconfig/test.data/pgsql_\" + blockRange + \".sql\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn str\n}",
"func GetTokenLocation() string {\n\tmyself, err := user.Current()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\thomedir := myself.HomeDir\n\treturn homedir + \"/.photoprism/\"\n}",
"func getWalletAddress() string {\n\tfn := \"wallet\"\n\tif _, err := os.Stat(fn); os.IsNotExist(err) {\n\t\t// File does not exist\n\t\tlog.Println(\"Wallet file does not exist.\")\n\t\treturn \"\"\n\t}\n\tdata, err := ioutil.ReadFile(fn)\n\tif err != nil {\n\t\tlog.Println(\"Error reading Wallet file.\", err)\n\t\treturn \"\"\n\t}\n\treturn string(data)\n}",
"func NewGeoDB(zipfile string) (GeoFinder, error) {\n\tf, err := os.Open(zipfile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tzf, err := zip.NewReader(f, fi.Size())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar blocks, countries *zip.File\n\tfor _, f := range zf.File {\n\t\tif strings.HasSuffix(f.Name, \"-Blocks-IPv4.csv\") {\n\t\t\tblocks = f\n\t\t} else if strings.HasSuffix(f.Name, \"-Country-Locations-en.csv\") {\n\t\t\tcountries = f\n\t\t}\n\t}\n\tif blocks == nil || countries == nil {\n\t\treturn nil, errors.New(\"ZIP does not contains blocks or countries\")\n\t}\n\n\tdb := geodb{}\n\tcn := map[string]string{}\n\n\tif err := readCSV(countries, []string{\"geoname_id\", \"country_iso_code\"}, func(row []string) error {\n\t\tcn[row[0]] = row[1]\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := readCSV(blocks, []string{\"network\", \"geoname_id\"}, func(row []string) error {\n\t\tnetwork, id := row[0], row[1]\n\t\tcountry, ok := cn[id]\n\t\tif !ok {\n\t\t\t// Some ranges may not contain country data\n\t\t\treturn nil\n\t\t}\n\t\t_, ipnet, err := net.ParseCIDR(network)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdb = append(db, ipRange{Net: ipnet, Country: country})\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn db, nil\n}",
"func (r *Client) GuessLibrary() {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tr.Library = strings.Replace(RhythmboxXmlLibrary, \"$HOME\", usr.HomeDir, 1)\n\tfmt.Println(r.Library)\n}",
"func (*HttpPacFiles) GetPath() string { return \"/api/objects/http/pac_file/\" }",
"func (mdb *memdbSlice) Path() string {\n\treturn mdb.path\n}",
"func (b *BgpSystem) GetPath() string { return fmt.Sprintf(\"/api/objects/bgp/system/%s\", b.Reference) }",
"func Get_longitude(ipaddress string) IP2Locationrecord {\n\treturn handleError(defaultDB.query(ipaddress, longitude))\n}",
"func getPath() string {\n\treturn os.Getenv(pathEnvVar)\n}",
"func (app *App) dotPath() string { return os.Getenv(\"HOME\") + \"/.\" + app.codeName }",
"func GetLongitude(fulladdress string) float64{\n\tvar s GoogleMaps\n\tvar long64 float64\n\tBaseurl:= \"http://maps.google.com/maps/api/geocode/json?address=\"\n\tAddurl:= fulladdress\n\tUrl:= Baseurl + Addurl\n\tUrl = strings.Replace(Url,\" \",\"%20\",-1)\n\tapiResponse, err:= http.Get(Url)\n\tif err!=nil {\n\t\tfmt.Printf(\"error occurred\")\n\t\tfmt.Printf(\"%s\", err)\n\t\tos.Exit(1)\n\t}else{\n\t\tdefer apiResponse.Body.Close()\n\t\tcontents, err:= ioutil.ReadAll(apiResponse.Body)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\terr= json.Unmarshal(contents, &s)\n\t\tif err!=nil {\n\t\t\tfmt.Println(\"Here is the error from longitude\")\n\t\t\tfmt.Printf(\"%s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tlong64=s.Results[0].Geometry.Location.Lng\t\t\n}\nreturn long64\n}",
"func (ls *LocationStore) Path() string {\n\treturn fmt.Sprintf(\"env/locations/%s.yml\", ls.name)\n}",
"func (d *DockerPath) GetBlockDBPath(network string) string {\n\treturn filepath.Join(d.GetDataPath(network), d.BlockDBDirName)\n}",
"func getBasePath() string {\r\n\tdir, err := os.Getwd()\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\tfor _, err := ioutil.ReadFile(filepath.Join(dir, \"go.mod\")); err != nil && len(dir) > 1; {\r\n\t\tdir = filepath.Dir(dir)\r\n\t\t_, err = ioutil.ReadFile(filepath.Join(dir, \"go.mod\"))\r\n\t}\r\n\tif len(dir) < 2 {\r\n\t\tpanic(\"No go.mod found\")\r\n\t}\r\n\treturn dir\r\n}",
"func (b *BrBuilder) GetSymbolPath(hash, name string) string {\n\treturn filepath.Join(b.StorePath, name, hash, name)\n}",
"func getConfig(path string) (*configparser.ConfigParser, error){\r\n p, err := configparser.NewConfigParserFromFile(path)\r\n if err != nil {\r\n return nil,err\r\n }\r\n\r\n return p,nil\r\n}",
"func (a BuildBlock) openPLib() *string {\n\tvar err error\n\tvar f []byte\n\tif a.Extension == \".py\" {\n\t\t// open the python library\n\t\tf, err = ioutil.ReadFile(a.libpath + \"hieroglyph.py\")\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Cannot open python library: %s\\n\", err)\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\treturn nil\n\t}\n\tfile := string(f)\n\treturn &file\n}",
"func getFullPath(binaryPath string) (string, error) {\n\t// NOTE(thomastaylor312): I am leaving this code commented out here. During\n\t// the implementation of post-render, it was brought up that if we are\n\t// relying on plugins, we should actually use the plugin system so it can\n\t// properly handle multiple OSs. This will be a feature add in the future,\n\t// so I left this code for reference. It can be deleted or reused once the\n\t// feature is implemented\n\n\t// Manually check the plugin dir first\n\t// if !strings.Contains(binaryPath, string(filepath.Separator)) {\n\t// \t// First check the plugin dir\n\t// \tpluginDir := helmpath.DataPath(\"plugins\") // Default location\n\t// \t// If location for plugins is explicitly set, check there\n\t// \tif v, ok := os.LookupEnv(\"HELM_PLUGINS\"); ok {\n\t// \t\tpluginDir = v\n\t// \t}\n\t// \t// The plugins variable can actually contain multiple paths, so loop through those\n\t// \tfor _, p := range filepath.SplitList(pluginDir) {\n\t// \t\t_, err := os.Stat(filepath.Join(p, binaryPath))\n\t// \t\tif err != nil && !os.IsNotExist(err) {\n\t// \t\t\treturn \"\", err\n\t// \t\t} else if err == nil {\n\t// \t\t\tbinaryPath = filepath.Join(p, binaryPath)\n\t// \t\t\tbreak\n\t// \t\t}\n\t// \t}\n\t// }\n\n\t// Now check for the binary using the given path or check if it exists in\n\t// the path and is executable\n\tcheckedPath, err := exec.LookPath(binaryPath)\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"unable to find binary at %s\", binaryPath)\n\t}\n\n\treturn filepath.Abs(checkedPath)\n}",
"func SetLocalLibpath() {\n\tif libSqlite3Pcre != \"\" {\n\t\treturn\n\t}\n\n\trepositoryRoot, err := exec.Command(\"git\", \"rev-parse\", \"--show-toplevel\").Output()\n\tif err != nil {\n\t\tpanic(\"can't find the libsqlite3-pcre library because LIBSQLITE3_PCRE was not set and you're not in the git repository, which is where the library is expected to be.\")\n\t}\n\tif runtime.GOOS == \"darwin\" {\n\t\tlibSqlite3Pcre = path.Join(strings.TrimSpace(string(repositoryRoot)), \"libsqlite3-pcre.dylib\")\n\t} else {\n\t\tlibSqlite3Pcre = path.Join(strings.TrimSpace(string(repositoryRoot)), \"libsqlite3-pcre.so\")\n\t}\n\tif _, err := os.Stat(libSqlite3Pcre); os.IsNotExist(err) {\n\t\tpanic(errors.Errorf(\"can't find the libsqlite3-pcre library because LIBSQLITE3_PCRE was not set and %s doesn't exist at the root of the repository - try building it with `./dev/libsqlite3-pcre/build.sh`\", libSqlite3Pcre))\n\t}\n}",
"func getPlistFile() (*os.File, error) {\n\treturn getFirstAvailableFile([]string{\n\t\t\"/System/Library/CoreServices/SystemVersion.plist\",\n\t\t\"/System/Library/CoreServices/ServerVersion.plist\",\n\t})\n}",
"func MySQLClientPath() (string, error) {\n\t// 'brew install mysql-client' installs the client into an unusual path\n\t// https://docs.brew.sh/FAQ#why-should-i-install-homebrew-in-the-default-location\n\tvar homebrewPrefix string\n\tswitch runtime.GOOS {\n\tcase \"darwin\":\n\t\thomebrewPrefix = \"/usr/local\"\n\t\tif runtime.GOARCH == \"arm64\" {\n\t\t\thomebrewPrefix = \"/opt/homebrew\"\n\t\t}\n\tcase \"linux\":\n\t\thomebrewPrefix = \"/home/linuxbrew/.linuxbrew\"\n\t}\n\n\toldpath := os.Getenv(\"PATH\")\n\tnewpath := homebrewPrefix + \"/opt/mysql-client/bin/\" + string(os.PathListSeparator) + oldpath\n\tdefer func() {\n\t\tif err := os.Setenv(\"PATH\", oldpath); err != nil {\n\t\t\tfmt.Println(\"failed to restore PATH\", err)\n\t\t}\n\t}()\n\n\tif err := os.Setenv(\"PATH\", newpath); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpath, err := exec.LookPath(\"mysql\")\n\tif err == nil {\n\t\treturn path, nil\n\t}\n\n\tmsg := \"couldn't find the 'mysql' command-line tool required to run this command.\"\n\tinstallURL := \"https://docs.planetscale.com/reference/planetscale-environment-setup\"\n\n\tswitch runtime.GOOS {\n\tcase \"darwin\":\n\t\tif HasHomebrew() {\n\t\t\treturn \"\", fmt.Errorf(\"%s\\nTo install, run: brew install mysql-client\", msg)\n\t\t}\n\n\t\tinstallURL = \"https://docs.planetscale.com/reference/planetscale-environment-setup#macos-instructions\"\n\tcase \"linux\":\n\t\tinstallURL = \"https://docs.planetscale.com/reference/planetscale-environment-setup#linux-instructions\"\n\tcase \"windows\":\n\t\tinstallURL = \"https://docs.planetscale.com/reference/planetscale-environment-setup#windows-instructions\"\n\t}\n\n\treturn \"\", fmt.Errorf(\"%s\\nTo install, follow the instructions: %s\", msg, installURL)\n}",
"func (repo Repository) GetByFullPath(fullpath string) (data []byte, err error) {\n\tfullPath := path.Join(repo.StorageDir, fullpath)\n\tdata, err = ioutil.ReadFile(fullPath)\n\n\treturn\n}",
"func getDotFilePath() string{\n\tusr, err := user.Current()\n\tif err != nil{\n\t\tlog.Fatal(err)\n\t}\n\tdotFile := usr.HomeDir + \"/.gitlocalstats\"\n\treturn dotFile\n}",
"func (o *StorageSpaceAllOf) GetLbaLocation() string {\n\tif o == nil || o.LbaLocation == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.LbaLocation\n}",
"func (dn *DNode) getDbPath(clusterType string, replicaID uint64) string {\n\treturn fmt.Sprintf(\"%s/%s/%d\", dn.dbPath, clusterType, replicaID)\n}",
"func (c *client) GetTKGProvidersDirectory() (string, error) {\n\ttkgDir, err := c.GetTKGDirectory()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(tkgDir, constants.LocalProvidersFolderName), nil\n}",
"func PathCfgDir() string {\n\tdir := os.Getenv(ENV_CFG_DIR)\n\tif dir != \"\" {\n\t\treturn dir\n\t}\n\thomeDir, err := Home()\n\tif err != nil {\n\t\tlog.Fatal(\"can not fetch home directory\")\n\t}\n\treturn filepath.Join(homeDir, DEFAULT_CFG_DIR)\n}",
"func GetAutoCompleteHome() (string, error) {\n\tgoctlH, err := GetGoctlHome()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Join(goctlH, autoCompleteDir), nil\n}",
"func (l *RemoteProvider) PackageLocation() string {\n\treturn path.Join(homedir.HomeDir(), \".meshery\", \"provider\", l.ProviderName, l.PackageVersion)\n}",
"func (c CrostiniGuestOS) GetBinPath() string {\n\treturn \"/tmp/trace_replay/bin\"\n}",
"func (*BgpRouteMaps) GetPath() string { return \"/api/objects/bgp/route_map/\" }",
"func (*LegoPort) Path() string { return filepath.Join(prefix, LegoPortPath) }",
"func getConfigPath() (string, error) {\n\treturn \"./veille.yaml\", nil\n}"
] | [
"0.5630482",
"0.559057",
"0.5488511",
"0.5349648",
"0.53356326",
"0.52581185",
"0.5196373",
"0.51702076",
"0.4993472",
"0.49209893",
"0.48700115",
"0.48602825",
"0.4858257",
"0.48558006",
"0.48479274",
"0.48353517",
"0.47806114",
"0.4773219",
"0.47629172",
"0.47492555",
"0.4740336",
"0.47368863",
"0.4717443",
"0.46737307",
"0.46679327",
"0.46413958",
"0.46347082",
"0.4634423",
"0.46334013",
"0.4618225",
"0.45800772",
"0.45586297",
"0.45574486",
"0.455282",
"0.4551807",
"0.45320427",
"0.4528535",
"0.45264953",
"0.45197558",
"0.45185256",
"0.45131612",
"0.45109192",
"0.45081592",
"0.4502702",
"0.4491388",
"0.4488311",
"0.44732764",
"0.4472845",
"0.44646442",
"0.44370282",
"0.44340563",
"0.443173",
"0.44213045",
"0.44180816",
"0.44137323",
"0.441279",
"0.4409916",
"0.44081184",
"0.43974966",
"0.43902048",
"0.4387332",
"0.43672433",
"0.43666452",
"0.4365852",
"0.43656012",
"0.43655434",
"0.43635106",
"0.43594998",
"0.43510517",
"0.43419412",
"0.4341502",
"0.4331998",
"0.4328563",
"0.4324668",
"0.43192765",
"0.43070635",
"0.43047202",
"0.42992476",
"0.42987624",
"0.42919683",
"0.42792335",
"0.42730594",
"0.4270859",
"0.42701253",
"0.42689964",
"0.42683434",
"0.4268269",
"0.42656106",
"0.42651424",
"0.42543498",
"0.424972",
"0.42474487",
"0.42474028",
"0.4235196",
"0.4233999",
"0.4233723",
"0.42331567",
"0.42315024",
"0.42297503",
"0.4224943"
] | 0.77446544 | 0 |
ListTracks is an old API and is not implemeted for this provider. Instead, FetchLibrary should be used. | func (c *Client) ListTracks() ([]*jamsonic.Track, error) {
panic("should not be called.")
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func GetListTracks(w http.ResponseWriter, r *http.Request) {\n\tresponse := make(map[string]interface{})\n\tqueuedTracks := context.tq.list()\n\n\tresponse[\"queue\"] = queuedTracks\n\tresponse[\"now_playing\"] = map[string]interface{}{\n\t\t\"track\": context.np.current,\n\t\t\"time_remaining\": context.np.timeRemaining,\n\t}\n\n\tjresponse, _ := json.Marshal(response)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write(jresponse)\n}",
"func (c *gitTracks) List(opts v1.ListOptions) (result *v1alpha1.GitTrackList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = &v1alpha1.GitTrackList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"gittracks\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}",
"func (c *Client) TrackList() ([]Track, error) {\n\tres, err := c.Exec(\"get_property\", \"track-list\")\n\tif res == nil {\n\t\treturn nil, err\n\t}\n\t//log.Errorf(\"Data %s\", string(res.Data))\n\tvar ta []Track\n\tif err = json.Unmarshal([]byte(res.Data), &ta); err != nil {\n\t\treturn nil, fmt.Errorf(\"data %s, err %v\", res.Data, err)\n\t}\n\treturn ta, nil\n}",
"func (sc *SoundCloud) GetTracks(url string, submitter *gumble.User) ([]interfaces.Track, error) {\n\tvar (\n\t\tapiURL string\n\t\terr error\n\t\tresp *http.Response\n\t\tv *jason.Object\n\t\ttrack bot.Track\n\t\ttracks []interfaces.Track\n\t)\n\n\turlSplit := strings.Split(url, \"#t=\")\n\n\tapiURL = \"http://api.soundcloud.com/resolve?url=%s&client_id=%s\"\n\n\tif sc.isPlaylist(url) {\n\t\t// Submitter has added a playlist!\n\t\tresp, err = http.Get(fmt.Sprintf(apiURL, urlSplit[0], viper.GetString(\"api_keys.soundcloud\")))\n\t\tdefer resp.Body.Close()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tv, err = jason.NewObjectFromReader(resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttitle, _ := v.GetString(\"title\")\n\t\tpermalink, _ := v.GetString(\"permalink_url\")\n\t\tplaylist := &bot.Playlist{\n\t\t\tID: permalink,\n\t\t\tTitle: title,\n\t\t\tSubmitter: submitter.Name,\n\t\t\tService: sc.ReadableName,\n\t\t}\n\n\t\tvar scTracks []*jason.Object\n\t\tscTracks, err = v.GetObjectArray(\"tracks\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdummyOffset, _ := time.ParseDuration(\"0s\")\n\t\tfor _, t := range scTracks {\n\t\t\ttrack, err = sc.getTrack(t, dummyOffset, submitter)\n\t\t\tif err != nil {\n\t\t\t\t// Skip this track.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttrack.Playlist = playlist\n\t\t\ttracks = append(tracks, track)\n\t\t}\n\n\t\tif len(tracks) == 0 {\n\t\t\treturn nil, errors.New(\"Invalid playlist. No tracks were added\")\n\t\t}\n\t\treturn tracks, nil\n\t}\n\n\t// Submitter has added a track!\n\n\toffset := 0\n\t// Calculate track offset if needed\n\tif len(urlSplit) == 2 {\n\t\ttimeSplit := strings.Split(urlSplit[1], \":\")\n\t\tmultiplier := 1\n\t\tfor i := len(timeSplit) - 1; i >= 0; i-- {\n\t\t\ttime, _ := strconv.Atoi(timeSplit[i])\n\t\t\toffset += time * multiplier\n\t\t\tmultiplier *= 60\n\t\t}\n\t}\n\tplaybackOffset, _ := time.ParseDuration(fmt.Sprintf(\"%ds\", offset))\n\n\tresp, err = http.Get(fmt.Sprintf(apiURL, urlSplit[0], viper.GetString(\"api_keys.soundcloud\")))\n\tdefer resp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tv, err = jason.NewObjectFromReader(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttrack, err = sc.getTrack(v, playbackOffset, submitter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttracks = append(tracks, track)\n\treturn tracks, nil\n}",
"func GetTracks() *[]models.Track {\n\tvar tracks []models.Track\n\tvar track models.Track\n\tvar skip string // Skip the keyp value\n\n\tdb, err := open()\n\tdefer db.Close()\n\tutil.CheckErr(\"GetTracks\", err, true)\n\n\trows, err := db.Query(\"SELECT * FROM tracks\")\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(&track.Id,\n\t\t\t&track.TrackNumber,\n\t\t\t&track.Name,\n\t\t\t&track.AlbumId,\n\t\t\t&track.ArtistId,\n\t\t\t&track.DiscNumber,\n\t\t\t&track.Genre,\n\t\t\t&skip,\n\t\t\t&track.Path)\n\t\tutil.CheckErr(\"GetTracks\", err, true)\n\t\ttracks = append(tracks, track)\n\t}\n\n\treturn &tracks\n}",
"func getTracks(c *gin.Context) {\n\tartists := database.GetArtists()\n\talbums := database.GetAlbums()\n\ttracks := database.GetTracks()\n\tfull := fullJson{artists, albums, tracks}\n\n c.JSON(200, full)\n}",
"func GetTracks(s statefulsort.StatefulSort) []*Track {\n\telements := s.Elements()\n\ttracks := make([]*Track, len(elements))\n\tfor i, e := range elements {\n\t\tt, ok := e.(*Track)\n\t\tif !ok {\n\t\t\tlog.Fatal(\"could not convert interface to *Track\")\n\t\t}\n\t\ttracks[i] = t\n\t}\n\treturn tracks\n}",
"func getMultipleTracks(store Datastore, w http.ResponseWriter, r *http.Request) {\n\ttracks, totalPages, err := queryMultipleTracks(store , r)\n\tvar result SearchResult\n\tresult.Tracks = tracks\n\tresult.TotalPages = totalPages\n\twriteJSONResponse(w, result, err)\n}",
"func TestGetTracks(t *testing.T) {\n\tfmt.Println(\"Running test TestGetTracks\")\n\n\tvar response []int\n\n\tif err := sendGetRequest(\"/api/igc\", &response, true); err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\n\tif len(response) != 2 {\n\t\tt.Fatalf(\"Expected length of track IDs array to be 2\")\n\t}\n}",
"func (m *AndroidManagedStoreApp) GetAppTracks()([]AndroidManagedStoreAppTrackable) {\n val, err := m.GetBackingStore().Get(\"appTracks\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]AndroidManagedStoreAppTrackable)\n }\n return nil\n}",
"func (m *mediaStream) queryTracks(t webrtc.RTPCodecType) []Track {\n\tm.l.RLock()\n\tdefer m.l.RUnlock()\n\n\tresult := make([]Track, 0)\n\tfor track := range m.tracks {\n\t\tif track.Kind() == t || t == trackTypeDefault {\n\t\t\tresult = append(result, track)\n\t\t}\n\t}\n\n\treturn result\n}",
"func PrintTracks(s statefulsort.StatefulSort) {\n\ttracks := GetTracks(s)\n\tconst format = \"%v\\t%v\\t%v\\t%v\\t%v\\t\\n\"\n\ttw := new(tabwriter.Writer).Init(os.Stdout, 0, 8, 2, ' ', 0)\n\tfmt.Fprintf(tw, format, \"Title\", \"Artist\", \"Album\", \"Year\", \"Length\")\n\tfmt.Fprintf(tw, format, \"-----\", \"------\", \"-----\", \"----\", \"------\")\n\tfor _, t := range tracks {\n\t\tfmt.Fprintf(tw, format, t.Title, t.Artist, t.Album, t.Year, t.Length)\n\t}\n\ttw.Flush() // calculate column widths and print table\n}",
"func queryMultipleTracks(store Datastore, r *http.Request) (tracks []Track, totalPages int, err error) {\n\tvar query string\n\tpredicates := make(map[string]string)\n\tfor key, value := range r.URL.Query() {\n\t\tif key == \"q\" {\n\t\t\tquery = value[0]\n\t\t}\n\t\tif strings.HasPrefix(key, \"p.\") {\n\t\t\tpredicates[key[2:len(key)]] = value[0]\n\t\t}\n\t}\n\tstandardLimit := 20\n\toffset, limit := parsePageParam(r.URL.Query().Get(\"page\"), standardLimit)\n\tvar totalTracks int\n\tif (query != \"\") {\n\t\ttracks, totalTracks, err = store.trackSearch(query, offset, limit)\n\t} else {\n\t\ttracks, totalTracks, err = store.searchByPredicates(predicates, offset, limit)\n\t}\n\ttotalPages = int(math.Ceil(float64(totalTracks) / float64(standardLimit)))\n\treturn tracks, totalPages, err\n}",
"func HostSpotifyFetchPlaylistTracks(playlistID string, pool *redis.Pool) (types.Playlist, error) {\n\t// log.Printf(\"PLAYLIST IS %s\\n\", playlistID)\n\tpool = &redis.Pool{\n\t\tDial: func() (redis.Conn, error) {\n\t\t\t// log.Println(os.Getenv(\"REDIS_URL\"))\n\t\t\treturn redisurl.Connect()\n\t\t},\n\t}\n\n\ttok, err := GetSpotifyAuthToken()\n\tif err != nil {\n\t\treturn types.Playlist{}, err\n\t}\n\t// log.Printf(\"\\nReturned token: %#v\", tok.AccessToken)\n\n\tconn := pool.Get()\n\tdefer conn.Close()\n\n\tauth := spotify.NewAuthenticator(os.Getenv(\"SPOTIFY_REDIRECT_URI\"), scopes)\n\tclient := auth.NewClient(tok)\n\tspotifyPlaylist, err := client.GetPlaylist(spotify.ID(playlistID))\n\tif err != nil {\n\t\treturn types.Playlist{}, err\n\t}\n\tdurationMs := 0\n\tavatar := \"\"\n\tif len(spotifyPlaylist.Owner.Images) > 0 {\n\t\tavatar = spotifyPlaylist.Owner.Images[0].URL\n\t}\n\tplaylist := types.Playlist{Description: spotifyPlaylist.Description,\n\t\tCollaborative: spotifyPlaylist.Collaborative,\n\t\tTitle: spotifyPlaylist.Name,\n\t\tOwner: types.PlaylistOwner{Avatar: avatar, ID: spotifyPlaylist.Owner.ID,\n\t\t\tName: spotifyPlaylist.Name},\n\t\tURL: spotifyPlaylist.ExternalURLs[\"spotify\"],\n\t\tCover: spotifyPlaylist.Images[0].URL,\n\t}\n\tfor _, single := range spotifyPlaylist.Tracks.Tracks {\n\t\tdurationMs += single.Track.Duration\n\t\timg := \"\"\n\t\tif len(single.Track.Album.Images) > 0 {\n\t\t\timg = single.Track.Album.Images[0].URL\n\t\t}\n\t\tsingleT := &types.SingleTrack{\n\t\t\tAddedAt: single.AddedAt,\n\t\t\tCover: img,\n\t\t\tDuration: single.Track.Duration,\n\t\t\tExplicit: single.Track.Explicit,\n\t\t\tID: single.Track.ID.String(),\n\t\t\tPlatform: util.HostSpotify,\n\t\t\tTitle: single.Track.Name,\n\t\t\tURL: single.Track.Endpoint,\n\t\t\tReleaseDate: single.Track.Album.ReleaseDate,\n\t\t\tPreview: single.Track.PreviewURL,\n\t\t\tAlbum: single.Track.Album.Name,\n\t\t}\n\t\tfor _, r := range single.Track.Artists {\n\t\t\tsingleT.Artistes = append(singleT.Artistes, r.Name)\n\t\t}\n\t\tplaylist.Tracks = append(playlist.Tracks, *singleT)\n\t}\n\tplaylist.Duration = durationMs\n\n\tif err != nil {\n\t\treturn types.Playlist{}, nil\n\t}\n\tif err != nil {\n\t\treturn types.Playlist{}, nil\n\t}\n\n\t// log.Println(\"Tracks found for the playlist is: \", playlist)\n\treturn playlist, nil\n}",
"func (s *Service) List(ctx context.Context) ([]Album, error) {\n\tvar result []Album\n\talbumsListCall := s.photos.List().PageSize(maxAlbumsPerPage).ExcludeNonAppCreatedData()\n\terr := albumsListCall.Pages(ctx, func(response *photoslibrary.ListAlbumsResponse) error {\n\t\tfor _, res := range response.Albums {\n\t\t\tresult = append(result, toAlbum(res))\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tvar emptyResult []Album\n\t\treturn emptyResult, fmt.Errorf(\"listing albums: %w\", err)\n\t}\n\treturn result, nil\n}",
"func (c *Client) GetRecentTracks(user string, limit int) []RecentTrack {\n\turl := fmt.Sprintf(\"method=user.getrecenttracks&user=%v&api_key=%v&format=json&limit=%d\", user, c.Apikey, limit)\n\treqURL := c.BaseURL + url\n\tresponse, err := c.httpClient.Get(reqURL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tresponseSlice, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvar ret GetRecentTracks\n\tvar tracks []RecentTrack\n\terr = json.Unmarshal(responseSlice, &ret)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor _, track := range ret.RecentTracks.RecentTracks {\n\t\ttrack.PlayDate = track.TempDate.Uts.Time\n\t\ttracks = append(tracks, track)\n\t}\n\n\treturn tracks\n}",
"func (c *gitTracks) Get(name string, options v1.GetOptions) (result *v1alpha1.GitTrack, err error) {\n\tresult = &v1alpha1.GitTrack{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"gittracks\").\n\t\tName(name).\n\t\tVersionedParams(&options, scheme.ParameterCodec).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}",
"func (r repo) GetAll() []*Tracklist {\n\treturn r.Tracklists\n}",
"func (t *Tuner) WatchTracks(handler func(Tracks)) watch.Watch {\n\treturn t.tracks.Watch(handler)\n}",
"func (c *TrackerController) List(ctx *app.ListTrackerContext) error {\n\texp, err := query.Parse(ctx.Filter)\n\tif err != nil {\n\t\treturn goa.ErrBadRequest(fmt.Sprintf(\"could not parse filter: %s\", err.Error()))\n\t}\n\tstart, limit, err := parseLimit(ctx.Page)\n\tif err != nil {\n\t\treturn goa.ErrBadRequest(fmt.Sprintf(\"could not parse paging: %s\", err.Error()))\n\t}\n\treturn application.Transactional(c.db, func(appl application.Application) error {\n\t\tresult, err := appl.Trackers().List(ctx.Context, exp, start, &limit)\n\t\tif err != nil {\n\t\t\treturn goa.ErrInternal(fmt.Sprintf(\"Error listing trackers: %s\", err.Error()))\n\t\t}\n\t\treturn ctx.OK(result)\n\t})\n\n}",
"func (ar AlbumDbRepository) populateTracks(album *domain.Album) {\n\ttracksRepo := TrackDbRepository{AppContext: ar.AppContext}\n\tif tracks, err := tracksRepo.GetTracksForAlbum(album.Id); err == nil {\n\t\talbum.Tracks = tracks\n\t}\n}",
"func (s *Client) GetUserSavedTracks(ctx context.Context, token *oauth2.Token, q *QParams) (*models.UserSavedTracks, error) {\n\tvar endpoint *url.URL = s.API.UserSavedTracksURL\n\t//in go structs containing primitive types are copied by value\n\t//https://stackoverflow.com/questions/51635766/how-do-i-copy-a-struct-in-golang\n\tlog.Println(\"SAME ADDRESS ?????\")\n\tlog.Println(&endpoint == &s.API.UserSavedTracksURL)\n\tif q != nil {\n\t\tparams := url.Values{}\n\t\tif q.Limit != nil {\n\t\t\tvar l int = *(q).Limit\n\t\t\tvalid := (l >= 1) && (l <= 50)\n\t\t\tif valid {\n\t\t\t\tparams.Set(\"limit\", strconv.Itoa(l))\n\t\t\t}\n\t\t}\n\t\tif q.Offset != nil {\n\t\t\tvar offset int = *(q).Offset\n\t\t\tif offset > 0 {\n\t\t\t\tparams.Set(\"offset\", strconv.Itoa(offset))\n\t\t\t}\n\t\t}\n\t\tif q.Market != nil {\n\t\t\tvar m string = *(q).Market\n\t\t\tif validMarketOpt(m) {\n\t\t\t\tparams.Set(\"market\", *(q).Market)\n\t\t\t}\n\t\t}\n\n\t\tendpoint.RawQuery = params.Encode()\n\t}\n\turl := endpoint.String()\n\tlog.Println(url)\n\tlog.Printf(\"User saved tracks url: %v\\n\", url)\n\n\ttracks := &models.UserSavedTracks{}\n\n\thttpClient := s.Config.Client(ctx, token)\n\tresp, err := httpClient.Get(url)\n\tif resp.StatusCode >= http.StatusBadRequest {\n\t\tlog.Println(\"status code todo:return err\")\n\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif err := json.NewDecoder(resp.Body).Decode(tracks); err != nil {\n\t\tlog.Printf(\"Could not decode body: %v\\n\", err)\n\t\treturn nil, err\n\t}\n\n\treturn tracks, nil\n\n}",
"func GetTracksPath() []string {\n\tdb, err := open()\n\tdefer db.Close()\n\tutil.CheckErr(\"GetTracksPath\", err, true)\n\n\t// Counts the number of rows for the slice initialisation (paths)\n\tvar count int\n\terr = db.QueryRow(\"SELECT count(*) FROM tracks\").Scan(&count)\n\tutil.CheckErr(\"GetTracksPath\", err, true)\n\n\tvar path string\n\tpaths := make([]string, count)\n\n\t// Selects path for each track and put them in the paths slice\n\trows, err := db.Query(\"SELECT path FROM tracks\")\n\tutil.CheckErr(\"GetTracksPath\", err, true)\n\tdefer rows.Close()\n\n\ti := 0\n\tfor rows.Next() {\n\t\terr := rows.Scan(&path)\n\t\tutil.CheckErr(\"GetTracksPath\", err, false)\n\t\tpaths[i] = path\n\t\ti++\n\t}\n\terr = rows.Err()\n\tutil.CheckErr(\"GetTracksPath\", err, true)\n\n\treturn paths\n}",
"func (r *SharedAlbumsService) List() *SharedAlbumsListCall {\n\tc := &SharedAlbumsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\treturn c\n}",
"func (s *MeService) GetLibraryPlaylistTracks(ctx context.Context, id string, opt *Options) ([]Song, error) {\n\tu := fmt.Sprintf(\"v1/me/library/playlists/%s/tracks\", id)\n\n\tvar tracks []Song\n\tfor len(u) > 0 {\n\t\tlpt, _, err := s.getLibraryPlaylistsTracks(ctx, u, opt)\n\t\tif err != nil {\n\t\t\treturn tracks, err\n\t\t}\n\n\t\ttracks = append(tracks, lpt.Data...)\n\t\tu = lpt.Next\n\t}\n\n\treturn tracks, nil\n}",
"func updateMultipleTracks(store Datastore, r *http.Request, updatesForTracks Track) (result SearchResult, action string, err error) {\n\ttracks, totalPages, err := queryMultipleTracks(store, r)\n\tresult.TotalPages = totalPages\n\tif err != nil {\n\t\treturn\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\tonlyMissing := (r.Header.Get(\"If-None-Match\") == \"*\")\n\n\tresult.Tracks = make([]Track, 0)\n\taction = \"noChange\"\n\tfor i := range tracks {\n\t\ttrackupdates := updatesForTracks\n\t\ttrackupdates.ID = tracks[i].ID\n\t\tstoredTrack, trackAction, trackError := store.updateCreateTrackDataByField(\"id\", tracks[i].ID, trackupdates, tracks[i], onlyMissing)\n\t\tif trackError != nil {\n\t\t\terr = trackError\n\t\t\treturn\n\t\t}\n\t\tif trackAction == \"noChange\" {\n\t\t\tcontinue\n\t\t}\n\t\tif trackAction != \"trackUpdated\" {\n\t\t\terr = errors.New(\"Unexpected action \"+trackAction)\n\t\t\treturn\n\t\t}\n\t\tresult.Tracks = append(result.Tracks, storedTrack)\n\t\taction = \"tracksUpdated\"\n\t}\n\tif action != \"noChange\" {\n\t\tstore.Loganne.post(action, strconv.Itoa(len(result.Tracks)) + \" tracks updated\", Track{}, Track{})\n\t}\n\treturn\n}",
"func (sp *StreamProc) TrackInfos() []TrackInfo {\n\tret := make([]TrackInfo, len(sp.tracks))\n\tfor trackID, track := range sp.tracks {\n\t\tret[trackID] = TrackInfo{\n\t\t\tLastSequenceNumber: uint16(atomic.LoadUint32(&track.lastSequenceNumber)),\n\t\t\tLastTimeRTP: atomic.LoadUint32(&track.lastTimeRTP),\n\t\t\tLastTimeNTP: atomic.LoadInt64(&track.lastTimeNTP),\n\t\t\tLastSSRC: atomic.LoadUint32(&track.lastSSRC),\n\t\t}\n\t}\n\treturn ret\n}",
"func (m *AndroidManagedStoreApp) SetAppTracks(value []AndroidManagedStoreAppTrackable)() {\n err := m.GetBackingStore().Set(\"appTracks\", value)\n if err != nil {\n panic(err)\n }\n}",
"func TrackGET(w http.ResponseWriter, _ *http.Request) {\n\t// Get all tracks from the database\n\tvar all = trackDB.GetAll()\n\t// Create a bson.ObjectID slice\n\tvar ids []bson.ObjectId\n\n\t// Loop through all tracks\n\tfor _, track := range all {\n\t\t// Append the track ID to the ID-slice\n\t\tids = append(ids, track.Id)\n\t}\n\n\t// Set header content-type to JSON\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t// Encode and displays all the track-ID's\n\tjson.NewEncoder(w).Encode(ids)\n}",
"func (i *API) List(kind string) ([][]byte, error) {\n\treturn i.primaryStore.RawList(kind)\n}",
"func NewMockTracks(ctrl *gomock.Controller) *MockTracks {\n\tmock := &MockTracks{ctrl: ctrl}\n\tmock.recorder = &MockTracksMockRecorder{mock}\n\treturn mock\n}",
"func (sc *ScreenlyClient) List() *PlayList {\n\tplaylist := &PlayList{}\n\t// The assets endpoint returns a JSON list not a JSON object, so the\n\t// response body can't be decoded directly to a PlayList. So we have\n\t// to unmarshal to the PlayList.Assets field.\n\tresponse, err := sc.doHttp(\"GET\", \"assets\", nil)\n\n\tif err == nil {\n\t\t//io.Copy(os.Stdout, response.Body)\n\t\t// Create a buffer and read response body, eg. [{...}, {...}]\n\t\tb := new(bytes.Buffer)\n\t\t// (the first ignored parameter is the number of bytes read)\n\t\t_, err := b.ReadFrom(response.Body)\n\n\t\tif err == nil {\n\t\t\t// ...now unmarshal to the PlayList.Assets slice.\n\t\t\terr := json.Unmarshal(b.Bytes(), &playlist.Assets)\n\t\t\tif err == nil {\n\t\t\t\treturn playlist\n\t\t\t}\n\t\t}\n\t}\n\tpanic(err)\n}",
"func (c *LastFM) GetSimilarTracks(artist, track string) (*sources.CacheableSimilarTracks, error) {\n\tsongs, err := c.api.Track.GetSimilar(lfm.P{\"artist\": artist, \"track\": track, \"limit\": c.c.MaxTopSimTracks})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to GetSimilarTracks for %s - %s, error: %v\", artist, track, err)\n\t}\n\n\tvar st []string\n\tfor _, tracks := range songs.Tracks {\n\t\tst = append(st, fmt.Sprintf(\"%s by %s\", tracks.Name, tracks.Artist.Name))\n\t}\n\treturn &sources.CacheableSimilarTracks{SimilarTracks: st}, nil\n}",
"func (p *serviceProvidersImpl) List(ctx context.Context) (*servicesv1.ServiceProviderList, error) {\n\tproviders := &servicesv1.ServiceProviderList{}\n\n\treturn providers, p.Store().Client().List(ctx,\n\t\tstore.ListOptions.InNamespace(HubNamespace),\n\t\tstore.ListOptions.InTo(providers),\n\t)\n}",
"func (client FavoritesClient) List(ctx context.Context, resourceGroupName string, resourceName string, favoriteType FavoriteType, sourceType FavoriteSourceType, canFetchContent *bool, tags []string) (result ListApplicationInsightsComponentFavorite, err error) {\n\treq, err := client.ListPreparer(ctx, resourceGroupName, resourceName, favoriteType, sourceType, canFetchContent, tags)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"insights.FavoritesClient\", \"List\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"insights.FavoritesClient\", \"List\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.ListResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"insights.FavoritesClient\", \"List\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}",
"func (v SongsResource) List(c buffalo.Context) error {\n\t// Get the DB connection from the context\n\ttx, ok := c.Value(\"tx\").(*pop.Connection)\n\tif !ok {\n\t\treturn errors.WithStack(errors.New(\"no transaction found\"))\n\t}\n\n\tsongs := &models.Songs{}\n\n\t// Paginate results. Params \"page\" and \"per_page\" control pagination.\n\t// Default values are \"page=1\" and \"per_page=20\".\n\tq := tx.PaginateFromParams(c.Params())\n\n\t// Retrieve all Songs from the DB\n\tif err := q.All(songs); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\t// Add the paginator to the context so it can be used in the template.\n\tc.Set(\"pagination\", q.Paginator)\n\n\treturn c.Render(200, r.Auto(c, songs))\n}",
"func (r *AlbumsService) List() *AlbumsListCall {\n\tc := &AlbumsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\treturn c\n}",
"func (c *ClientConn) Tracks() Tracks {\n\treturn c.tracks\n}",
"func (s *GenericStorage) List(gvk schema.GroupVersionKind) (result []runtime.Object, walkerr error) {\n\twalkerr = s.walkKind(gvk, func(content []byte) error {\n\t\tobj, err := s.decode(content, gvk)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tresult = append(result, obj)\n\t\treturn nil\n\t})\n\treturn\n}",
"func EndpointSaveTracks(ids []string) string {\n\treturn EndpointMe() + \"/tracks?ids=\" + strings.Join(ids, \",\")\n}",
"func (p *Pipeline) GetOutputTracks() []*webrtc.Track {\n\treturn p.outputTracks\n}",
"func (c *Client) List(p ListParameters) ([]Release, error) {\n\tresponse, err := c.client.ListReleases(p.Options()...) // TODO Paging.\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tvar releases []Release\n\tif response != nil && response.Releases != nil {\n\t\tfor _, item := range response.Releases {\n\t\t\treleases = append(releases, *(fromHelm(item)))\n\t\t}\n\t}\n\treturn releases, nil\n}",
"func (h *Handler) listSongs(w http.ResponseWriter, r *http.Request) {\n\tr.ParseForm()\n\tartist, ok1 := r.Form[\"artist\"]\n\talbum, ok2 := r.Form[\"album\"]\n\n\tvar songs []map[string]string\n\tvar err error\n\n\tif ok1 && ok2 {\n\t\tsongs, err = h.MpdClient.GetSongs(artist[0], album[0])\n\t} else if ok1 && !ok2 {\n\t\tsongs, err = h.MpdClient.GetSongs(artist[0], \"\")\n\t} else {\n\t\tsongs, err = h.MpdClient.GetFiles()\n\t}\n\n\tif err != nil {\n\t\tprintError(w, \"An error occured while processing your request\", err)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, jsoniffy(songs))\n}",
"func (c *SeriesController) List(ctx *app.ListSeriesContext) error {\n\t// SeriesController_List: start_implement\n\tm, err := c.fm()\n\tif err != nil {\n\t\tgoa.ContextLogger(ctx).Error(`unable to get model`, `error`, err.Error())\n\t\treturn ctx.ServiceUnavailable()\n\t}\n\tdefer func() { m.Close() }()\n\n\tlist, err := m.ListSeriesByIDs(nil, nil, nil, nil)\n\tif err != nil {\n\t\tgoa.ContextLogger(ctx).Error(`failed to get series list`, `error`, err.Error())\n\t\treturn ctx.InternalServerError()\n\t}\n\n\tbs := make(app.SeriesCollection, len(list))\n\tfor i, bk := range list {\n\t\tbs[i] = convert.ToSeriesMedia(bk)\n\t}\n\treturn ctx.OK(bs)\n\t// SeriesController_List: end_implement\n}",
"func (s *playlistService) List(ctx context.Context, search *Search) ([]models.Playlist, uint, error) {\n\tlists, numRows, err := s.repo.Find(search.Search, search.Offset, search.Limit)\n\tif err != nil {\n\t\treturn nil, 0, MakeErrorWithData(\n\t\t\thttp.StatusInternalServerError,\n\t\t\tErrCodeRepoError,\n\t\t\tfmt.Sprintf(\"Error while searching playlists\"),\n\t\t\terr,\n\t\t)\n\t}\n\t// Set a marker to the main playlist\n\tmainID := s.events.DefaultPlaylistID(ctx)\n\tfor i, list := range lists {\n\t\tif list.ID == mainID {\n\t\t\tlists[i].IsMain = true // There are no pointers here - so we'll do it this way\n\t\t}\n\t}\n\treturn lists, numRows, nil\n}",
"func NewStatefulTracks(tracks []*Track) statefulsort.StatefulSort {\n\treturn statefulsort.NewStatefulSort(toIface(tracks), names, cmpFuncs)\n}",
"func (c *Client) UserHasTracks(ids ...ID) ([]bool, error) {\n\tif l := len(ids); l == 0 || l > 50 {\n\t\treturn nil, errors.New(\"spotify: UserHasTracks supports 1 to 50 IDs per call\")\n\t}\n\tspotifyURL := fmt.Sprintf(\"%sme/tracks/contains?ids=%s\", c.baseURL, strings.Join(toStringSlice(ids), \",\"))\n\n\tvar result []bool\n\n\terr := c.get(spotifyURL, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, err\n}",
"func (g genericPlugin) List(gvk schema.GroupVersionKind, namespace string,\n\tclient plugin.KubernetesConnector) ([]helm.KubernetesResource, error) {\n\n\tvar returnData []helm.KubernetesResource\n\treturn returnData, nil\n}",
"func getTracksDay(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tif _, err := conf.DS.GetRadiostationID(vars[\"station\"]); err != nil {\n\t\tlog.Printf(\"getTracksDay Handler: GetRadiostationID(%s): %s\\n\", vars[\"station\"], err.Error())\n\t\thandleError(w, http.StatusBadRequest, \"Bad request\")\n\t\treturn\n\t}\n\n\tt, err := time.Parse(\"2006-01-02\", vars[\"date\"])\n\tif err != nil {\n\t\tlog.Printf(\"getTracksDay Handler: time.Parse(%s): %s\\n\", vars[\"date\"], err.Error())\n\t\thandleError(w, http.StatusBadRequest, \"Bad request\")\n\t\treturn\n\t}\n\n\tloc, _ := time.LoadLocation(\"Europe/Vienna\")\n\tsince := time.Date(\n\t\tt.Year(),\n\t\tt.Month(),\n\t\tt.Day(),\n\t\t0, 0, 0, 0,\n\t\tloc,\n\t)\n\tuntil := time.Date(\n\t\tt.Year(),\n\t\tt.Month(),\n\t\tt.Day(),\n\t\t23, 59, 59, 0,\n\t\tloc,\n\t)\n\n\tvar tracks []model.Track\n\tif vars[\"filter\"] == \"top\" {\n\t\ttracks, err = conf.DS.GetTopTracks(vars[\"station\"], since, until)\n\t} else {\n\t\ttracks, err = conf.DS.GetAllTracks(vars[\"station\"], since, until)\n\t}\n\tif err != nil {\n\t\tlog.Printf(\"getTracksDay Handler: GetTopTracks/GetAllTracks(%s, %q, %q): %s\\n\", vars[\"station\"],\n\t\t\tsince, until, err.Error())\n\t\thandleError(w, http.StatusInternalServerError, \"Internal server error\")\n\t\treturn\n\t}\n\n\ttype response struct {\n\t\tStation string `json:\"station\"`\n\t\tDate string `json:\"date\"`\n\t\tPlays []model.Track `json:\"plays\"`\n\t}\n\n\tresp := response{vars[\"station\"], vars[\"date\"], tracks}\n\tj, err := jsonMarshal(resp)\n\tif err != nil {\n\t\tlog.Printf(\"getTracksDay Handler: %s\\n\", err.Error())\n\t\thandleError(w, http.StatusInternalServerError, \"Internal server error\")\n\t\treturn\n\t}\n\twriteJSONResponse(w, j)\n}",
"func ListArtists(album string, sort sortOrder, asc bool) []ArtistData {\n\tglobalListCache.RLock()\n\tdefer globalListCache.RUnlock()\n\n\tald, ok := globalListCache.albums[album]\n\tif !ok {\n\t\tswitch sort {\n\t\tcase SortTracks:\n\t\t\tif asc {\n\t\t\t\treturn copyArtistList(globalListCache.artistsByTracksRev)\n\t\t\t} else {\n\t\t\t\treturn copyArtistList(globalListCache.artistsByTracks)\n\t\t\t}\n\t\tcase SortAlbums:\n\t\t\tif asc {\n\t\t\t\treturn copyArtistList(globalListCache.artistsByAlbumsRev)\n\t\t\t} else {\n\t\t\t\treturn copyArtistList(globalListCache.artistsByAlbums)\n\t\t\t}\n\t\tcase SortName:\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\tif asc {\n\t\t\t\treturn copyArtistList(globalListCache.artistsByNameRev)\n\t\t\t} else {\n\t\t\t\treturn copyArtistList(globalListCache.artistsByName)\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch sort {\n\tcase SortTracks:\n\t\tif asc {\n\t\t\treturn copyArtistList(ald.artistsByTracksRev)\n\t\t} else {\n\t\t\treturn copyArtistList(ald.artistsByTracks)\n\t\t}\n\tcase SortAlbums:\n\t\tif asc {\n\t\t\treturn copyArtistList(ald.artistsByAlbumsRev)\n\t\t} else {\n\t\t\treturn copyArtistList(ald.artistsByAlbums)\n\t\t}\n\tcase SortName:\n\t\tfallthrough\n\tdefault:\n\t\tif asc {\n\t\t\treturn copyArtistList(ald.artistsByNameRev)\n\t\t} else {\n\t\t\treturn copyArtistList(ald.artistsByName)\n\t\t}\n\t}\n}",
"func (t *FakeObjectTracker) List(gvr schema.GroupVersionResource, gvk schema.GroupVersionKind, ns string) (runtime.Object, error) {\n\tif t.fakingOptions.failAll != nil {\n\t\terr := t.fakingOptions.failAll.RunFakeInvocations()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn t.delegatee.List(gvr, gvk, ns)\n}",
"func newGitTracks(c *FarosV1alpha1Client, namespace string) *gitTracks {\n\treturn &gitTracks{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}",
"func (s *virtualHubLister) List(selector labels.Selector) (ret []*v1alpha1.VirtualHub, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.VirtualHub))\n\t})\n\treturn ret, err\n}",
"func (that *Stream) List(pageModel *PageModel) (*StreamResponseModelList, error) {\n\tpath := fmt.Sprintf(\"%s/%s/%s\", lib.DefaultAPIURL, lib.DefaultAPIVersion, \"streams\")\n\tpath = paramsUtil(path, pageModel)\n\n\tdata, err := that.client.Get(path)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponseList := new(StreamResponseModelList)\n\n\terr = json.Unmarshal(data[:len(data)], &responseList)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn responseList, nil\n}",
"func (_Bfs *BfsCallerSession) List(absolutePath string, offset *big.Int, limit *big.Int) (*big.Int, []BfsInfo, error) {\n\treturn _Bfs.Contract.List(&_Bfs.CallOpts, absolutePath, offset, limit)\n}",
"func (c *Client) List(page int, limit int) (List, error) {\n\tURL := c.url\n\tif page != 0 || limit != 0 {\n\t\tif page != 0 {\n\t\t\tURL.RawQuery = url.QueryEscape(strconv.Itoa(page))\n\t\t}\n\t\tif limit != 0 {\n\t\t\tURL.RawQuery = url.QueryEscape(strconv.Itoa(limit))\n\t\t}\n\t}\n\tres, err := c.get(c.url.String())\n\tif err != nil {\n\t\treturn List{}, err\n\t}\n\tlist := List{}\n\terr = json.Unmarshal(res, &list)\n\treturn list, err\n}",
"func (_Bfs *BfsSession) List(absolutePath string, offset *big.Int, limit *big.Int) (*big.Int, []BfsInfo, error) {\n\treturn _Bfs.Contract.List(&_Bfs.CallOpts, absolutePath, offset, limit)\n}",
"func (a *DefaultClient) List(l vfs.Location) ([]string, error) {\n\tURL, err := url.Parse(l.(*Location).ContainerURL())\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tcontainerURL := azblob.NewContainerURL(*URL, a.pipeline)\n\tctx := context.Background()\n\tvar list []string\n\tfor marker := (azblob.Marker{}); marker.NotDone(); {\n\t\tlistBlob, err := containerURL.ListBlobsHierarchySegment(ctx, marker, \"/\",\n\t\t\tazblob.ListBlobsSegmentOptions{Prefix: utils.RemoveLeadingSlash(l.Path())})\n\t\tif err != nil {\n\t\t\treturn []string{}, err\n\t\t}\n\n\t\tmarker = listBlob.NextMarker\n\n\t\tfor i := range listBlob.Segment.BlobItems {\n\t\t\tlist = append(list, listBlob.Segment.BlobItems[i].Name)\n\t\t}\n\t}\n\treturn list, nil\n}",
"func (d decks) ListDecks() []string {\n\treturn nil\n}",
"func (o *Drive) GetOpticalNumAudioTracks(ctx context.Context) (opticalNumAudioTracks uint32, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"OpticalNumAudioTracks\").Store(&opticalNumAudioTracks)\n\treturn\n}",
"func (s *ProviderGRPC) ListBuckets(ctx context.Context, req *pb.ListBucketsRequest) (*pb.ListBucketsResponse, error) {\n\tif req.Project.Id == \"\" {\n\t\treturn nil, errors.New(\"Project ID is required\")\n\t}\n\tvar buckets []*pb.Bucket\n\tit := s.client.Buckets(ctx, req.Project.Id)\n\tfor {\n\t\tbattrs, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Bucket iterator failed: %v\", err)\n\t\t}\n\t\tbuckets = append(buckets, &pb.Bucket{\n\t\t\tName: battrs.Name,\n\t\t})\n\t}\n\treturn &pb.ListBucketsResponse{Buckets: buckets}, nil\n}",
"func (c *Client) Search(ctx context.Context, search, filter string, page int) ([]string, error) {\n\tif page <= 0 {\n\t\tpage = 1\n\t}\n\n\tresolved, ok := filters[filter]\n\tif !ok {\n\t\tresolved = defaultTrackFilter\n\t}\n\n\tu, err := url.Parse(fmt.Sprintf(\"%s/music#\", c.baseURL))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to build search URL: %w\", err)\n\t}\n\n\tparams := url.Values(map[string][]string{\n\t\t\"s\": {search},\n\t\t\"p\": {strconv.Itoa(page)},\n\t\t\"f\": {resolved},\n\t})\n\n\tu.RawQuery = params.Encode()\n\n\tdocument, err := c.getSearchPageDocument(ctx, u.String())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get search page document: %w\", err)\n\t}\n\n\treturn c.parseTracksFromSearch(document), nil\n}",
"func (symbols) List(ctx context.Context, repo api.RepoName, commitID api.CommitID, mode string, params lspext.WorkspaceSymbolParams) ([]lsp.SymbolInformation, error) {\n\tif Mocks.Symbols.List != nil {\n\t\treturn Mocks.Symbols.List(ctx, repo, commitID, mode, params)\n\t}\n\n\tvar symbols []lsp.SymbolInformation\n\trootURI := lsp.DocumentURI(\"git://\" + string(repo) + \"?\" + string(commitID))\n\terr := xlang.UnsafeOneShotClientRequest(ctx, mode, rootURI, \"workspace/symbol\", params, &symbols)\n\treturn symbols, err\n}",
"func (c *Client) ListPlaylists() ([]*jamsonic.Playlist, error) {\n\tpanic(\"not implemented\")\n}",
"func SpotifySearchTrack(query string, limit int32) *spotify.SearchResult {\n\tresults, err := client.SearchOpt(query, spotify.SearchTypeTrack|spotify.SearchTypeArtist, &spotify.Options{Limit: createInt(limit)})\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn results\n}",
"func (s *KSession) GetTrack(id int64) (results Track, err error) {\n\tresults = Track{}\n\tres, err := s.request(\"GET\", EndpointLyricsTrack(id), nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(res, &results)\n\treturn\n}",
"func (c *Client) UserSavedTracks(limit int) (SavedTrackPage, error) {\n return c.UserSavedTracksOpt(limit, 0, \"\")\n}",
"func RefreshLists() error {\n\trows, err := listCacheQuery.Query()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\n\ttracks := make([]*listCacheTrack, 0, 0x3fff)\n\tfor rows.Next() {\n\t\tt := &listCacheTrack{}\n\t\terr := rows.Scan(&t.Artist, &t.Album, &t.Year)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttracks = append(tracks, t)\n\t}\n\n\tglobalListCache.Lock()\n\tdefer globalListCache.Unlock()\n\n\t// Make sure there is no stale data.\n\tglobalListCache.artists = map[string]*listCacheArtist{}\n\n\tglobalListCache.artistsByName = nil\n\tglobalListCache.artistsByTracks = nil\n\tglobalListCache.artistsByAlbums = nil\n\n\tglobalListCache.artistsByNameRev = nil\n\tglobalListCache.artistsByTracksRev = nil\n\tglobalListCache.artistsByAlbumsRev = nil\n\n\tglobalListCache.albums = map[string]*listCacheAlbum{}\n\n\tglobalListCache.albumsByName = nil\n\tglobalListCache.albumsByTracks = nil\n\tglobalListCache.albumsByYear = nil\n\n\tglobalListCache.albumsByNameRev = nil\n\tglobalListCache.albumsByTracksRev = nil\n\tglobalListCache.albumsByYearRev = nil\n\n\t// Populate the master artist list\n\n\tfor _, t := range tracks {\n\t\tif t.Artist != \"\" {\n\t\t\tard, ok := globalListCache.artists[t.Artist]\n\t\t\tif !ok {\n\t\t\t\tard = &listCacheArtist{\n\t\t\t\t\tdata: &ArtistData{t.Artist, 0, 0},\n\t\t\t\t\talbums: map[string]*AlbumData{},\n\t\t\t\t}\n\t\t\t\tglobalListCache.artists[t.Artist] = ard\n\n\t\t\t\tglobalListCache.artistsByName = append(globalListCache.artistsByName, ard.data)\n\t\t\t\tglobalListCache.artistsByTracks = append(globalListCache.artistsByTracks, ard.data)\n\t\t\t\tglobalListCache.artistsByAlbums = append(globalListCache.artistsByAlbums, ard.data)\n\n\t\t\t\tglobalListCache.artistsByNameRev = append(globalListCache.artistsByNameRev, ard.data)\n\t\t\t\tglobalListCache.artistsByTracksRev = append(globalListCache.artistsByTracksRev, ard.data)\n\t\t\t\tglobalListCache.artistsByAlbumsRev = append(globalListCache.artistsByAlbumsRev, ard.data)\n\t\t\t}\n\n\t\t\tard.data.Tracks++\n\t\t}\n\n\t\t// OK, the artist data is done, now for the album:\n\n\t\tif t.Album != \"\" {\n\t\t\tald, ok := globalListCache.albums[t.Album]\n\t\t\tif !ok {\n\t\t\t\tald = &listCacheAlbum{\n\t\t\t\t\tdata: &AlbumData{t.Album, 0, 0},\n\t\t\t\t\tartists: map[string]*ArtistData{},\n\t\t\t\t}\n\n\t\t\t\tglobalListCache.albums[t.Album] = ald\n\n\t\t\t\tglobalListCache.albumsByName = append(globalListCache.albumsByName, ald.data)\n\t\t\t\tglobalListCache.albumsByTracks = append(globalListCache.albumsByTracks, ald.data)\n\t\t\t\tglobalListCache.albumsByYear = append(globalListCache.albumsByYear, ald.data)\n\n\t\t\t\tglobalListCache.albumsByNameRev = append(globalListCache.albumsByNameRev, ald.data)\n\t\t\t\tglobalListCache.albumsByTracksRev = append(globalListCache.albumsByTracksRev, ald.data)\n\t\t\t\tglobalListCache.albumsByYearRev = append(globalListCache.albumsByYearRev, ald.data)\n\t\t\t}\n\t\t\tald.data.Tracks++\n\t\t\tif t.Year > ald.data.Year {\n\t\t\t\tald.data.Year = t.Year\n\t\t\t}\n\t\t}\n\n\t\t// Now for the individual lists\n\n\t\tif t.Album != \"\" && t.Artist != \"\" {\n\t\t\t// Artist album list\n\t\t\tard, ok := globalListCache.artists[t.Artist]\n\t\t\tif !ok {\n\t\t\t\tpanic(\"Combobulater discombobulated.\")\n\t\t\t}\n\n\t\t\tarald, ok := ard.albums[t.Album]\n\t\t\tif !ok {\n\t\t\t\tarald = &AlbumData{t.Album, 0, 0}\n\n\t\t\t\tard.data.Albums++\n\n\t\t\t\tard.albums[t.Album] = arald\n\n\t\t\t\tard.albumsByName = append(ard.albumsByName, arald)\n\t\t\t\tard.albumsByTracks = append(ard.albumsByTracks, arald)\n\t\t\t\tard.albumsByYear = append(ard.albumsByYear, arald)\n\n\t\t\t\tard.albumsByNameRev = append(ard.albumsByNameRev, arald)\n\t\t\t\tard.albumsByTracksRev = append(ard.albumsByTracksRev, arald)\n\t\t\t\tard.albumsByYearRev = append(ard.albumsByYearRev, arald)\n\t\t\t}\n\t\t\tarald.Tracks++\n\t\t\tif t.Year > arald.Year {\n\t\t\t\tarald.Year = t.Year\n\t\t\t}\n\n\t\t\t// Album artist list\n\t\t\tald, ok := globalListCache.albums[t.Album]\n\t\t\tif !ok {\n\t\t\t\tpanic(\"Combobulater discombobulated.\")\n\t\t\t}\n\n\t\t\talard, ok := ald.artists[t.Artist]\n\t\t\tif !ok {\n\t\t\t\talard = &ArtistData{t.Artist, 0, 0}\n\t\t\t\talard.Albums = 1\n\n\t\t\t\tald.artists[t.Artist] = alard\n\n\t\t\t\tald.artistsByName = append(ald.artistsByName, alard)\n\t\t\t\tald.artistsByTracks = append(ald.artistsByTracks, alard)\n\t\t\t\tald.artistsByAlbums = append(ald.artistsByAlbums, alard)\n\n\t\t\t\tald.artistsByNameRev = append(ald.artistsByNameRev, alard)\n\t\t\t\tald.artistsByTracksRev = append(ald.artistsByTracksRev, alard)\n\t\t\t\tald.artistsByAlbumsRev = append(ald.artistsByAlbumsRev, alard)\n\t\t\t}\n\t\t\talard.Tracks++\n\t\t}\n\t}\n\n\t// Now we need to sort all the lists:\n\n\t// Artists\n\tsort.Sort(artistSorter{globalListCache.artistsByName, func(a, b *ArtistData) bool {\n\t\treturn NaturalLess(strings.ToLower(a.Name), strings.ToLower(b.Name))\n\t}})\n\tsort.Sort(artistSorter{globalListCache.artistsByTracks, func(a, b *ArtistData) bool {\n\t\treturn a.Tracks < b.Tracks\n\t}})\n\tsort.Sort(artistSorter{globalListCache.artistsByAlbums, func(a, b *ArtistData) bool {\n\t\treturn a.Albums < b.Albums\n\t}})\n\n\tsort.Sort(sort.Reverse(artistSorter{globalListCache.artistsByNameRev, func(a, b *ArtistData) bool {\n\t\treturn NaturalLess(strings.ToLower(a.Name), strings.ToLower(b.Name))\n\t}}))\n\tsort.Sort(sort.Reverse(artistSorter{globalListCache.artistsByTracksRev, func(a, b *ArtistData) bool {\n\t\treturn a.Tracks < b.Tracks\n\t}}))\n\tsort.Sort(sort.Reverse(artistSorter{globalListCache.artistsByAlbumsRev, func(a, b *ArtistData) bool {\n\t\treturn a.Albums < b.Albums\n\t}}))\n\n\t// Album artist list\n\tfor _, ald := range globalListCache.albums {\n\t\tsort.Sort(artistSorter{ald.artistsByName, func(a, b *ArtistData) bool {\n\t\t\treturn NaturalLess(strings.ToLower(a.Name), strings.ToLower(b.Name))\n\t\t}})\n\t\tsort.Sort(artistSorter{ald.artistsByTracks, func(a, b *ArtistData) bool {\n\t\t\treturn a.Tracks < b.Tracks\n\t\t}})\n\t\tsort.Sort(artistSorter{ald.artistsByAlbums, func(a, b *ArtistData) bool {\n\t\t\treturn a.Albums < b.Albums\n\t\t}})\n\n\t\tsort.Sort(sort.Reverse(artistSorter{ald.artistsByNameRev, func(a, b *ArtistData) bool {\n\t\t\treturn NaturalLess(strings.ToLower(a.Name), strings.ToLower(b.Name))\n\t\t}}))\n\t\tsort.Sort(sort.Reverse(artistSorter{ald.artistsByTracksRev, func(a, b *ArtistData) bool {\n\t\t\treturn a.Tracks < b.Tracks\n\t\t}}))\n\t\tsort.Sort(sort.Reverse(artistSorter{ald.artistsByAlbumsRev, func(a, b *ArtistData) bool {\n\t\t\treturn a.Albums < b.Albums\n\t\t}}))\n\t}\n\n\t// Albums\n\tsort.Sort(albumSorter{globalListCache.albumsByName, func(a, b *AlbumData) bool {\n\t\treturn NaturalLess(strings.ToLower(a.Name), strings.ToLower(b.Name))\n\t}})\n\tsort.Sort(albumSorter{globalListCache.albumsByTracks, func(a, b *AlbumData) bool {\n\t\treturn a.Tracks < b.Tracks\n\t}})\n\tsort.Sort(albumSorter{globalListCache.albumsByYear, func(a, b *AlbumData) bool {\n\t\treturn a.Year < b.Year\n\t}})\n\n\tsort.Sort(sort.Reverse(albumSorter{globalListCache.albumsByNameRev, func(a, b *AlbumData) bool {\n\t\treturn NaturalLess(strings.ToLower(a.Name), strings.ToLower(b.Name))\n\t}}))\n\tsort.Sort(sort.Reverse(albumSorter{globalListCache.albumsByTracksRev, func(a, b *AlbumData) bool {\n\t\treturn a.Tracks < b.Tracks\n\t}}))\n\tsort.Sort(sort.Reverse(albumSorter{globalListCache.albumsByYearRev, func(a, b *AlbumData) bool {\n\t\treturn a.Year < b.Year\n\t}}))\n\n\t// Artist album list\n\tfor _, ard := range globalListCache.artists {\n\t\tsort.Sort(albumSorter{ard.albumsByName, func(a, b *AlbumData) bool {\n\t\t\treturn NaturalLess(strings.ToLower(a.Name), strings.ToLower(b.Name))\n\t\t}})\n\t\tsort.Sort(albumSorter{ard.albumsByTracks, func(a, b *AlbumData) bool {\n\t\t\treturn a.Tracks < b.Tracks\n\t\t}})\n\t\tsort.Sort(albumSorter{ard.albumsByYear, func(a, b *AlbumData) bool {\n\t\t\treturn a.Year < b.Year\n\t\t}})\n\n\t\tsort.Sort(sort.Reverse(albumSorter{ard.albumsByNameRev, func(a, b *AlbumData) bool {\n\t\t\treturn NaturalLess(strings.ToLower(a.Name), strings.ToLower(b.Name))\n\t\t}}))\n\t\tsort.Sort(sort.Reverse(albumSorter{ard.albumsByTracksRev, func(a, b *AlbumData) bool {\n\t\t\treturn a.Tracks < b.Tracks\n\t\t}}))\n\t\tsort.Sort(sort.Reverse(albumSorter{ard.albumsByYearRev, func(a, b *AlbumData) bool {\n\t\t\treturn a.Year < b.Year\n\t\t}}))\n\t}\n\n\t// That was a lot of sorting.\n\treturn nil\n}",
"func (c *Client) GetArtistTopTracks(id string, options *Options) ([]FullTrack, error) {\n\tvar t struct {\n\t\tTopTracks []FullTrack `json:\"tracks\"`\n\t}\n\n\turl := constructURL(options, c.baseURL, \"artists\", \"id\", \"top-tracks\")\n\terr := c.get(url, &t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn t.TopTracks, nil\n}",
"func (cs *controller) ListVolumes(\n\tctx context.Context,\n\treq *csi.ListVolumesRequest,\n) (*csi.ListVolumesResponse, error) {\n\n\treturn nil, status.Error(codes.Unimplemented, \"\")\n}",
"func (api *bucketAPI) ApisrvList(ctx context.Context, opts *api.ListWatchOptions) ([]*objstore.Bucket, error) {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn apicl.ObjstoreV1().Bucket().List(context.Background(), opts)\n\t}\n\n\t// List from local cache\n\tctkitObjs, err := api.List(ctx, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar ret []*objstore.Bucket\n\tfor _, obj := range ctkitObjs {\n\t\tret = append(ret, &obj.Bucket)\n\t}\n\treturn ret, nil\n}",
"func (store Datastore) TracksV2Controller(w http.ResponseWriter, r *http.Request) {\n\ttrackurl := r.URL.Query().Get(\"url\")\n\tfingerprint := r.URL.Query().Get(\"fingerprint\")\n\tnormalisedpath := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, \"/v2/tracks\"), \"/\")\n\tpathparts := strings.Split(normalisedpath, \"/\")\n\n\tvar trackid int\n\tvar filtervalue interface{}\n\tvar filterfield string\n\tif len(pathparts) > 1 {\n\t\tid, err := strconv.Atoi(pathparts[1])\n\t\tif err == nil {\n\t\t\tfilterfield = \"id\"\n\t\t\tfiltervalue = pathparts[1]\n\t\t\ttrackid = id\n\t\t}\n\t} else if len(trackurl) > 0 {\n\t\tfilterfield = \"url\"\n\t\tfiltervalue = trackurl\n\t} else if len(fingerprint) > 0 {\n\t\tfilterfield = \"fingerprint\"\n\t\tfiltervalue = fingerprint\n\t}\n\tif filterfield == \"\" {\n\t\tif len(pathparts) <= 1 {\n\t\t\tswitch r.Method {\n\t\t\tcase \"PATCH\":\n\t\t\t\ttrack, err := DecodeTrack(r.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif track.ID != 0 {\n\t\t\t\t\thttp.Error(w, \"Can't bulk update id\", http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif track.URL != \"\" {\n\t\t\t\t\thttp.Error(w, \"Can't bulk update url\", http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif track.Fingerprint != \"\" {\n\t\t\t\t\thttp.Error(w, \"Can't bulk update fingerprint\", http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tupdateMultipleTracksAndRespond(store, w, r, track)\n\t\t\tcase \"GET\":\n\t\t\t\tgetMultipleTracks(store, w, r)\n\t\t\tdefault:\n\t\t\t\tMethodNotAllowed(w, []string{\"GET\", \"PATCH\"})\n\t\t\t}\n\t\t} else {\n\t\t\tswitch pathparts[1] {\n\t\t\tcase \"random\":\n\t\t\t\twriteRandomTracksV2(store, w)\n\t\t\tdefault:\n\t\t\t\thttp.Error(w, \"Track Endpoint Not Found\", http.StatusNotFound)\n\t\t\t}\n\t\t}\n\t} else if len(pathparts) > 2 {\n\t\tswitch pathparts[2] {\n\t\tcase \"weighting\":\n\t\t\tswitch r.Method {\n\t\t\tcase \"PUT\":\n\t\t\t\tbody, err := ioutil.ReadAll(r.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\twriteErrorResponse(w, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tweighting, err := strconv.ParseFloat(string(body), 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.Error(w, \"Weighting must be a number\", http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\terr = store.setTrackWeighting(trackid, weighting)\n\t\t\t\tif err != nil {\n\t\t\t\t\twriteErrorResponse(w, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tfallthrough\n\t\t\tcase \"GET\":\n\t\t\t\twriteWeighting(store, w, trackid)\n\t\t\tdefault:\n\t\t\t\tMethodNotAllowed(w, []string{\"GET\", \"PUT\"})\n\t\t\t}\n\t\tdefault:\n\t\t\thttp.Error(w, \"Track Endpoint Not Found\", http.StatusNotFound)\n\t\t}\n\t} else {\n\t\tswitch r.Method {\n\t\tcase \"PATCH\":\n\t\t\tfallthrough\n\t\tcase \"PUT\":\n\t\t\tvar savedTrack Track\n\t\t\tvar action string\n\t\t\ttrack, err := DecodeTrack(r.Body)\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tswitch filterfield {\n\t\t\tcase \"id\":\n\t\t\t\ttrack.ID = trackid\n\t\t\tcase \"url\":\n\t\t\t\ttrack.URL = trackurl\n\t\t\tcase \"fingerprint\":\n\t\t\t\ttrack.Fingerprint = fingerprint\n\t\t\t}\n\t\t\tonlyMissing := (r.Header.Get(\"If-None-Match\") == \"*\")\n\t\t\texistingTrack, err := store.getTrackDataByField(filterfield, filtervalue)\n\t\t\tif r.Method == \"PATCH\" {\n\t\t\t\tif err != nil && err.Error() == \"Track Not Found\" {\n\t\t\t\t\thttp.Error(w, \"Track Not Found\", http.StatusNotFound)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tsavedTrack, action, err = store.updateCreateTrackDataByField(filterfield, filtervalue, track, existingTrack, onlyMissing)\n\t\t\t} else {\n\t\t\t\tmissingFields := []string{}\n\t\t\t\tif track.Fingerprint == \"\" {\n\t\t\t\t\tmissingFields = append(missingFields, \"fingerprint\")\n\t\t\t\t}\n\t\t\t\tif track.URL == \"\" {\n\t\t\t\t\tmissingFields = append(missingFields, \"url\")\n\t\t\t\t}\n\t\t\t\tif track.Duration == 0 {\n\t\t\t\t\tmissingFields = append(missingFields, \"duration\")\n\t\t\t\t}\n\t\t\t\tif len(missingFields) > 0 {\n\t\t\t\t\thttp.Error(w, \"Missing fields \\\"\"+strings.Join(missingFields, \"\\\" and \\\"\")+\"\\\"\", http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tsavedTrack, action, err = store.updateCreateTrackDataByField(filterfield, filtervalue, track, existingTrack, onlyMissing)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\twriteErrorResponse(w, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Header().Set(\"Track-Action\", action)\n\t\t\twriteJSONResponse(w, savedTrack, err)\n\t\tcase \"GET\":\n\t\t\twriteTrackDataByField(store, w, filterfield, filtervalue)\n\t\tcase \"DELETE\":\n\t\t\tdeleteTrackHandler(store, w, trackid)\n\t\tdefault:\n\t\t\tMethodNotAllowed(w, []string{\"GET\", \"PUT\", \"PATCH\", \"DELETE\"})\n\t\t}\n\t}\n}",
"func List(collection Getter) func(ctx context.Context) ([]interface{}, error) {\n\treturn func(ctx context.Context) ([]interface{}, error) {\n\t\tprojects := []Project{}\n\t\terr := collection.GetAll(ctx, &projects)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems := make([]interface{}, len(projects))\n\t\tfor i, v := range projects {\n\t\t\titems[i] = v\n\t\t}\n\t\treturn items, nil\n\t}\n}",
"func (driver *Driver) ListVolumes(ctx context.Context, req *csi.ListVolumesRequest) (*csi.ListVolumesResponse, error) {\n\tklog.V(4).Infof(\"ListVolumes: called with args %#v\", req)\n\treturn nil, status.Error(codes.Unimplemented, \"\")\n}",
"func (c *Client) channelsList(ctx context.Context) ([]*channel, error) {\n\tvar resp struct {\n\t\tResponseHeader\n\t\tChannels []channel `json:\"channels\"`\n\t}\n\tif err := rpc(ctx, c, &resp, \"channels.list\"); err != nil {\n\t\treturn nil, err\n\t}\n\tchannels := make([]*channel, 0)\n\tfor _, ch := range resp.Channels {\n\t\tch := ch\n\t\tinitChannel(c, &ch)\n\t\tchannels = append(channels, &ch)\n\t}\n\treturn channels, nil\n}",
"func (f *FakeProjectProvider) List(options *provider.ProjectListOptions) ([]*kubermaticapiv1.Project, error) {\n\treturn nil, errors.New(\"not implemented\")\n}",
"func (api *dscprofileAPI) ApisrvList(ctx context.Context, opts *api.ListWatchOptions) ([]*cluster.DSCProfile, error) {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn apicl.ClusterV1().DSCProfile().List(context.Background(), opts)\n\t}\n\n\t// List from local cache\n\tctkitObjs, err := api.List(ctx, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar ret []*cluster.DSCProfile\n\tfor _, obj := range ctkitObjs {\n\t\tret = append(ret, &obj.DSCProfile)\n\t}\n\treturn ret, nil\n}",
"func (p *Provider) List() ([]string, error) {\n\treturn p.provider.ListClusters()\n}",
"func (d *Driver) ListVolumes(ctx context.Context, req *csi.ListVolumesRequest) (*csi.ListVolumesResponse, error) {\n\treturn nil, status.Error(codes.Unimplemented, \"\")\n}",
"func (d *Driver) ListVolumes(ctx context.Context, req *csi.ListVolumesRequest) (*csi.ListVolumesResponse, error) {\n\treturn nil, status.Error(codes.Unimplemented, \"\")\n}",
"func (s virtualHubNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.VirtualHub, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.VirtualHub))\n\t})\n\treturn ret, err\n}",
"func (c *Manager) ListLibraries(ctx context.Context) ([]string, error) {\n\turl := c.Resource(internal.LibraryPath)\n\tvar res []string\n\treturn res, c.Do(ctx, url.Request(http.MethodGet), &res)\n}",
"func (c *client) List() ([]Buildpack, error) {\n\tcfg, err := c.fetchConfig()\n\tif err != nil || cfg == nil {\n\t\treturn nil, err\n\t}\n\n\tvar order struct {\n\t\tBuildpacks []Buildpack `json:\"buildpacks\"`\n\t}\n\tif err := json.NewDecoder(strings.NewReader(cfg.Config.Labels[metadataLabel])).Decode(&order); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn order.Buildpacks, nil\n}",
"func (c *Client) ListVoices() (r *ListVoicesResponse) {\n\tresp := c.queryAPI(&Request{\n\t\tXMLName: xml.Name{Local: \"listVoices\"},\n\t\tAccountID: c.AccountID,\n\t\tPassword: c.Password,\n\t})\n\tif resp.Error != nil {\n\t\tr.Error = resp.Error\n\t\treturn\n\t}\n\n\tif err := xml.Unmarshal(resp.Raw, &r); err != nil {\n\t\tr.Error = err\n\t}\n\n\treturn\n}",
"func List(ctx context.Context, client *selvpcclient.ServiceClient) ([]*Project, *selvpcclient.ResponseResult, error) {\n\turl := strings.Join([]string{client.Endpoint, resourceURL}, \"/\")\n\tresponseResult, err := client.DoRequest(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif responseResult.Err != nil {\n\t\treturn nil, responseResult, responseResult.Err\n\t}\n\n\t// Extract projects from the response body.\n\tvar result struct {\n\t\tProjects []*Project `json:\"projects\"`\n\t}\n\terr = responseResult.ExtractResult(&result)\n\tif err != nil {\n\t\treturn nil, responseResult, err\n\t}\n\n\treturn result.Projects, responseResult, nil\n}",
"func List() []string {\n\tvar output []string\n\tfor pushURL := range config.All().Tarts {\n\t\toutput = append(output, pushURL)\n\t}\n\treturn output\n}",
"func List(c messagebird.Client, options *messagebird.PaginationRequest) (*Groups, error) {\n\tgroupList := &Groups{}\n\tif err := c.Request(groupList, http.MethodGet, path+\"?\"+options.QueryParams(), nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn groupList, nil\n}",
"func (o *Drive) GetOpticalNumDataTracks(ctx context.Context) (opticalNumDataTracks uint32, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"OpticalNumDataTracks\").Store(&opticalNumDataTracks)\n\treturn\n}",
"func (p *VolumePlugin) ListVolumes() ([]*volume.Volume, error) {\n\tif err := p.verifyReachable(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogrus.Infof(\"Listing volumes using plugin %s\", p.Name)\n\n\tresp, err := p.sendRequest(nil, listPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif err := p.handleErrorResponse(resp, listPath, \"\"); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvolumeRespBytes, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"reading response body from volume plugin %s: %w\", p.Name, err)\n\t}\n\n\tvolumeResp := new(volume.ListResponse)\n\tif err := json.Unmarshal(volumeRespBytes, volumeResp); err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshalling volume plugin %s list response: %w\", p.Name, err)\n\t}\n\n\treturn volumeResp.Volumes, nil\n}",
"func (ah *AdminHandler) DeleteAllTracks(req *router.Request) {\n\t_, err := ah.db.Delete(mdb.TRACKS, nil)\n\tif err != nil {\n\t\treq.SendError(&router.Error{StatusCode: http.StatusInternalServerError, Message: \"Internal database error\"})\n\t\treturn\n\t}\n\treq.SendText(\"Everything deleted\", http.StatusOK)\n}",
"func (o *Drive) GetOpticalNumTracks(ctx context.Context) (opticalNumTracks uint32, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"OpticalNumTracks\").Store(&opticalNumTracks)\n\treturn\n}",
"func (c *kongs) List(opts v1.ListOptions) (result *v1alpha1.KongList, err error) {\n\tresult = &v1alpha1.KongList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"kongs\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}",
"func (c *PeerService) List(gid string, providerName string) ([]Peer, *http.Response, error) {\n\tresponse := new(peerListResponse)\n\tapiError := new(APIError)\n\tpath := fmt.Sprintf(\"%s/peers?providerName=%s\", gid, providerName)\n\tresp, err := c.sling.New().Get(path).Receive(response, apiError)\n\treturn response.Results, resp, relevantError(err, *apiError)\n}",
"func (svc *OTXPulseDetailService) List(opt *ListOptions) (*PulseList, error) {\n\tif opt == nil {\n\t\topt = &ListOptions{\n\t\t\tPage: 1,\n\t\t\tPerPage: 20,\n\t\t}\n\t}\n\n\treq, err := svc.client.newRequest(http.MethodGet, SubscriptionsURLPath, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := addURLOptions(req.URL, opt); err != nil {\n\t\treturn nil, fmt.Errorf(\"applying url options: %v\", err)\n\t}\n\n\tvar list PulseList\n\tif err := svc.client.do(req, &list); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &list, nil\n}",
"func (p Plugin) List(ctx context.Context, module string) ([]string, error) {\n\tresp, err := p.c.List(ctx, &stpb.ListRequest{Module: module})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp.GetVersions(), nil\n}",
"func (m *manager) List(query ...*models.ProjectQueryParam) ([]*models.Project, error) {\n\tvar q *models.ProjectQueryParam\n\tif len(query) > 0 {\n\t\tq = query[0]\n\t}\n\treturn dao.GetProjects(q)\n}",
"func (c *Client) List(opts *ListOptions) ([]*team.Team, error) {\n\tc.init()\n\n\treq := &stack.TeamListRequest{}\n\tif opts != nil {\n\t\treq.Slug = opts.Slug\n\t}\n\n\tresp := stack.TeamListResponse{}\n\tif err := c.kloud().Call(\"team.list\", req, &resp); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.Teams, nil\n}",
"func (c *Client) ListPlayShare() ([]*PlayShare, error) {\n\tresp, err := c.Get(aqbOrigin + \"/aqb/blog/post/webdav/index.php?format=json\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar psl playShareResponse\n\tif err := json.Unmarshal(b, &psl); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !psl.IsSuccess {\n\t\treturn nil, fmt.Errorf(\"server returns error: %s\", psl.Message)\n\t}\n\n\treturn psl.List, nil\n}",
"func (s *implLoadTestServiceServer) List(context.Context, *grpcProxyV2.ListRequest) (*grpcProxyV2.ListResponse, error) {\n\treturn nil, status.Error(codes.Unimplemented, \"\")\n}",
"func playlistItemsList(service *youtube.Service, part string, playlistId string, pageToken string) *youtube.PlaylistItemListResponse {\n\tcall := service.PlaylistItems.List([]string{part})\n\tcall = call.PlaylistId(playlistId)\n\tif pageToken != \"\" {\n\t\tcall = call.PageToken(pageToken)\n\t}\n\tresponse, err := call.Do()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn response\n}"
] | [
"0.7480291",
"0.7333298",
"0.72715867",
"0.6864569",
"0.6478907",
"0.63281804",
"0.6155347",
"0.6142881",
"0.61423993",
"0.6109937",
"0.5969686",
"0.5884183",
"0.5630576",
"0.56127685",
"0.5604307",
"0.55701953",
"0.54581124",
"0.5336995",
"0.5301999",
"0.5273045",
"0.5247849",
"0.52422583",
"0.5234002",
"0.52227974",
"0.52094454",
"0.5203245",
"0.5192401",
"0.5158772",
"0.51585335",
"0.5138227",
"0.51352787",
"0.5133608",
"0.5070094",
"0.50437963",
"0.5033468",
"0.49913588",
"0.49741253",
"0.4958794",
"0.49566633",
"0.49262935",
"0.49223766",
"0.49183804",
"0.49096057",
"0.490179",
"0.4883687",
"0.48786712",
"0.48418888",
"0.48397982",
"0.48138654",
"0.48034772",
"0.477698",
"0.4768542",
"0.47583914",
"0.47528815",
"0.47525653",
"0.4742529",
"0.47391298",
"0.47338596",
"0.47311455",
"0.4729535",
"0.4727483",
"0.47252274",
"0.47178423",
"0.4712615",
"0.4686675",
"0.46813607",
"0.46792418",
"0.4670623",
"0.46698698",
"0.46561405",
"0.4652619",
"0.46394172",
"0.46380115",
"0.46376228",
"0.4632531",
"0.46249604",
"0.46170172",
"0.46071428",
"0.46053138",
"0.46053138",
"0.46049824",
"0.45976853",
"0.4595866",
"0.45869124",
"0.4583032",
"0.45773274",
"0.4576558",
"0.4574333",
"0.45733112",
"0.4557144",
"0.45557618",
"0.45481175",
"0.4539911",
"0.45359093",
"0.45340964",
"0.4533777",
"0.4528854",
"0.45234337",
"0.4522937",
"0.45170504"
] | 0.79745233 | 0 |
ListPlaylists should return the playlists. Currently this feature is not implemented for this provider. | func (c *Client) ListPlaylists() ([]*jamsonic.Playlist, error) {
panic("not implemented")
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (player *musicPlayer) listPlaylists() ([]string, error) {\n\tplayer.Lock()\n\tdefer player.Unlock()\n\t//only the playlists in playlist directory is exposed\n\tfileInfo, err := os.Stat(player.playlistsDir)\n\tif os.IsNotExist(err) || !fileInfo.IsDir() {\n\t\treturn nil, errors.New(playlist_not_found_msg)\n\t}\n\tplaylists := make([]string, 0)\n\td, err := os.Open(player.playlistsDir)\n\tif err != nil {\n\t\treturn nil, errors.New(playlist_not_found_msg)\n\t}\n\tdefer d.Close()\n\tfiles, err := d.Readdir(-1)\n\tif err != nil {\n\t\treturn nil, errors.New(playlist_not_found_msg)\n\t}\n\n\tfor _, file := range files {\n\t\tif file.Mode().IsRegular() && strings.HasSuffix(file.Name(), playlistsExtension) {\n\t\t\tplaylists = append(playlists, file.Name())\n\t\t}\n\t}\n\tif len(playlists) == 0 {\n\t\treturn nil, errors.New(playlist_not_found_msg)\n\t}\n\treturn playlists, nil\n}",
"func RetrievePlaylists(c *gin.Context) {\n\tcode := c.Param(\"code\")\n\tsession, err := FindSessionForCode(&Session{Code: code})\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, common.NewError(\"session\", errors.New(\"Invalid session code\")))\n\t\treturn\n\t}\n\tplaylists, _ := GetPlaylistsForSession(session)\n\tc.JSON(http.StatusOK, playlists)\n}",
"func (s *playlistService) List(ctx context.Context, search *Search) ([]models.Playlist, uint, error) {\n\tlists, numRows, err := s.repo.Find(search.Search, search.Offset, search.Limit)\n\tif err != nil {\n\t\treturn nil, 0, MakeErrorWithData(\n\t\t\thttp.StatusInternalServerError,\n\t\t\tErrCodeRepoError,\n\t\t\tfmt.Sprintf(\"Error while searching playlists\"),\n\t\t\terr,\n\t\t)\n\t}\n\t// Set a marker to the main playlist\n\tmainID := s.events.DefaultPlaylistID(ctx)\n\tfor i, list := range lists {\n\t\tif list.ID == mainID {\n\t\t\tlists[i].IsMain = true // There are no pointers here - so we'll do it this way\n\t\t}\n\t}\n\treturn lists, numRows, nil\n}",
"func playlistItemsList(service *youtube.Service, part string, playlistId string, pageToken string) *youtube.PlaylistItemListResponse {\n\tcall := service.PlaylistItems.List([]string{part})\n\tcall = call.PlaylistId(playlistId)\n\tif pageToken != \"\" {\n\t\tcall = call.PageToken(pageToken)\n\t}\n\tresponse, err := call.Do()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn response\n}",
"func (s *ApiInterface) GetMoodPlaylists(c echo.Context) error {\n\t//mood := c.Param(\"mood\")\n\tparams := new(MoodParams)\n\terr := c.Bind(params)\n\tif err != nil {\n\t\treturn BadRequestResponse(c, err.Error())\n\t}\n\n\tif params.Mood == \"\"{\n\t\tparams.Mood = \"happy\"\n\t}\n\tif params.Playlist != \"\" {\n\t\tplaylist := s.spotify.SearchPlaylist(params.Playlist)\n\t\tplaylist.Event = params.Fitevent\n\t\ts.AddPlaylist(params.Mood,playlist)\n\t\tlog.Println(playlist)\n\t\tplays := make([]api.PlaylistModel,0)\n\t\tplays = append(plays, playlist)\n\t\treturn DataResponse(c, http.StatusOK, plays)\n\t}\n\n\n\tplaylists := s.GetPlaylistbyMood(params.Mood)\n\n\tif len(playlists) < 1 {\n\t\treturn MessageResponseForward(c,http.StatusOK, \"playlist not available, mind some suggestions?\")\n\t}\n\n\t//return c.JSONPretty(200, playlists, \"\" )\n\treturn DataResponse(c, http.StatusOK, playlists)\n}",
"func (c *Client) ListPlayShare() ([]*PlayShare, error) {\n\tresp, err := c.Get(aqbOrigin + \"/aqb/blog/post/webdav/index.php?format=json\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar psl playShareResponse\n\tif err := json.Unmarshal(b, &psl); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !psl.IsSuccess {\n\t\treturn nil, fmt.Errorf(\"server returns error: %s\", psl.Message)\n\t}\n\n\treturn psl.List, nil\n}",
"func (sc *ScreenlyClient) List() *PlayList {\n\tplaylist := &PlayList{}\n\t// The assets endpoint returns a JSON list not a JSON object, so the\n\t// response body can't be decoded directly to a PlayList. So we have\n\t// to unmarshal to the PlayList.Assets field.\n\tresponse, err := sc.doHttp(\"GET\", \"assets\", nil)\n\n\tif err == nil {\n\t\t//io.Copy(os.Stdout, response.Body)\n\t\t// Create a buffer and read response body, eg. [{...}, {...}]\n\t\tb := new(bytes.Buffer)\n\t\t// (the first ignored parameter is the number of bytes read)\n\t\t_, err := b.ReadFrom(response.Body)\n\n\t\tif err == nil {\n\t\t\t// ...now unmarshal to the PlayList.Assets slice.\n\t\t\terr := json.Unmarshal(b.Bytes(), &playlist.Assets)\n\t\t\tif err == nil {\n\t\t\t\treturn playlist\n\t\t\t}\n\t\t}\n\t}\n\tpanic(err)\n}",
"func (m *MockUsecase) GetPlaylists() ([]*models.Playlist, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPlaylists\")\n\tret0, _ := ret[0].([]*models.Playlist)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}",
"func (c *Client) ListPlaylistEntries() ([]*jamsonic.PlaylistEntry, error) {\n\tpanic(\"should not be called.\")\n}",
"func (s *MeService) GetLibraryPlaylistsByIds(ctx context.Context, opt *LibraryPlaylistsByIdsOptions) (*LibraryPlaylists, *Response, error) {\n\tu := \"v1/me/library/playlists\"\n\n\treturn s.getLibraryPlaylists(ctx, u, opt)\n}",
"func (t *teamsImpl) List(ctx context.Context) (*orgv1.TeamList, error) {\n\tmodel, err := t.persistenceMgr.Teams().List(ctx)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"trying to retrieve list of team in kore\")\n\n\t\treturn nil, err\n\t}\n\n\treturn DefaultConvertor.FromTeamsModelList(model), nil\n}",
"func (s *Job) SetPlaylists(v []*Playlist) *Job {\n\ts.Playlists = v\n\treturn s\n}",
"func (s *MeService) GetAllLibraryPlaylists(ctx context.Context, opt *PageOptions) (*LibraryPlaylists, *Response, error) {\n\tu := \"v1/me/library/playlists\"\n\n\treturn s.getLibraryPlaylists(ctx, u, opt)\n}",
"func (s *Client) GetUserPlaylists(id string) (*SimplePlaylistPage, error) {\n\tconst URL = \"https://api.spotify.com/v1/users/%s/playlists\"\n\n\tplaylistURL := fmt.Sprintf(URL, id)\n\tlog.Printf(\"getting: %v\", playlistURL)\n\n\tpl := &SimplePlaylistPage{}\n\tif err := s.get(playlistURL, pl); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn pl, nil\n}",
"func (s *workspaces) List(ctx context.Context, organization string, options *WorkspaceListOptions) (*WorkspaceList, error) {\n\tif !validStringID(&organization) {\n\t\treturn nil, ErrInvalidOrg\n\t}\n\tif err := options.valid(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := fmt.Sprintf(\"organizations/%s/workspaces\", url.QueryEscape(organization))\n\treq, err := s.client.NewRequest(\"GET\", u, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twl := &WorkspaceList{}\n\terr = req.Do(ctx, wl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn wl, nil\n}",
"func (mr *MockUsecaseMockRecorder) GetPlaylists() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPlaylists\", reflect.TypeOf((*MockUsecase)(nil).GetPlaylists))\n}",
"func (s *CreateJobInput) SetPlaylists(v []*CreateJobPlaylist) *CreateJobInput {\n\ts.Playlists = v\n\treturn s\n}",
"func (c *Client) GetList(dir string) ([]string, error) {\n\tvar list []string\n\n\t// Prepare the URL\n\tURL := fmt.Sprintf(wpListURL, dir)\n\n\t// Make the Request\n\tresp, err := c.getRequest(URL)\n\tif err != nil {\n\t\treturn list, err\n\t}\n\n\t// Drain body and check Close error\n\tdefer drainAndClose(resp.Body, &err)\n\tbytes, err := ioutil.ReadAll(resp.Body)\n\tmatches := regexList.FindAllStringSubmatch(string(bytes), -1)\n\n\t// Add all matches to extension list\n\tfor _, match := range matches {\n\t\tlist = append(list, match[1])\n\t}\n\n\treturn list, err\n}",
"func (db *Mysql) GetLists(args *models.GetListsArgs, user *models.User) (*[]models.ListInfo, error) {\n\tvar lists []models.ListInfo\n\n\tteam, err := db.getTeamFromID(args.TeamID)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"func\": \"GetLists\",\n\t\t\t\"subFunc\": \"getTeamFromID\",\n\t\t\t\"userID\": user.ID,\n\t\t\t\"args\": *args,\n\t\t}).Error(err)\n\t\treturn nil, err\n\t}\n\n\tif team.AdminID != user.ID {\n\t\treturn nil, errors.New(\"User not admin of team\")\n\t}\n\n\terr = db.Client.Table(\"lists\").Joins(\"LEFT JOIN tasks on lists.id = tasks.list_id\").\n\t\tSelect(\"lists.*,\"+\n\t\t\t\"sum(case when complete = true AND tasks.archived = false then 1 else 0 end) as completed_tasks,\"+\n\t\t\t\"sum(case when complete = false AND tasks.archived = false then 1 else 0 end) as pending_tasks\").\n\t\tWhere(\"lists.archived = false AND lists.user_id = ? AND lists.team_id = ?\", user.ID, team.ID).\n\t\tGroup(\"lists.id\").\n\t\tFind(&lists).Error\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"func\": \"GetLists\",\n\t\t\t\"info\": \"retrieving list info\",\n\t\t\t\"userID\": user.ID,\n\t\t}).Error(err)\n\t\treturn nil, err\n\t}\n\n\treturn &lists, nil\n}",
"func ListFor(cl *Client, b string, l string) (*trello.List, error) {\n\tm := cl.Member\n\tif list, ok := listmap[b][l]; ok {\n\t\treturn list, nil\n\t}\n\n\tboard, err := BoardFor(m, b)\n\tif err != nil {\n\t\t// handle error\n\t\treturn nil, err\n\t}\n\tif board == nil {\n\t\treturn nil, fmt.Errorf(\"Board %s not found\", b)\n\t}\n\n\tlists, err := board.GetLists(trello.Defaults())\n\tif err != nil {\n\t\t// handle error\n\t\treturn nil, err\n\t}\n\tif listmap[board.Name] == nil {\n\t\tlistmap[board.Name] = map[string]*trello.List{}\n\t}\n\tfor _, li := range lists {\n\t\t// fmt.Println(\"examining board \", b)\n\t\t// fmt.Println(b.Name, \"->\", b)\n\t\t// if listmap[board.Name] == nil {\n\t\t// listmap[board.Name] = map[string]*trello.List{}\n\t\t// }\n\t\t// fmt.Println(\"list \", li.Name)\n\t\tlistmap[board.Name][li.Name] = li\n\t}\n\tlist := listmap[b][l]\n\treturn list, nil\n}",
"func listPlayers(w http.ResponseWriter, r *http.Request) {\n\tplayer := models.NewPlayer(\"\")\n\tskue.List(view, player, w, r)\n}",
"func ListPlayers(state *state.State, cmd DiscordCommand) error {\n\t// Create RCON connection\n\tconn, err := rcon.Dial(conf.Minecraft.RconIP, conf.Minecraft.RconPort, conf.Minecraft.RconPassword)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\t// Authenticate to RCON\n\tif err = conn.Authenticate(); err != nil {\n\t\treturn err\n\t}\n\n\t// Send the command to Minecraft\n\tresp, err := conn.SendCommand(\"minecraft:list\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Vanilla servers dont support the 'minecraft:' command prefix\n\tif strings.HasPrefix(resp, \"Unknown or incomplete command\") {\n\t\tresp, err = conn.SendCommand(\"list\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tembed := createListEmbed(strings.Split(resp, \":\"))\n\treturn SendCommandEmbed(state, cmd, embed)\n}",
"func (c *Client) ListScramSecrets(ctx context.Context, params *ListScramSecretsInput, optFns ...func(*Options)) (*ListScramSecretsOutput, error) {\n\tif params == nil {\n\t\tparams = &ListScramSecretsInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"ListScramSecrets\", params, optFns, addOperationListScramSecretsMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*ListScramSecretsOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}",
"func (s *TeamsServiceOp) List(ctx context.Context, orgID string, listOptions *ListOptions) ([]atlas.Team, *Response, error) {\n\tif orgID == \"\" {\n\t\treturn nil, nil, atlas.NewArgError(\"orgID\", \"must be set\")\n\t}\n\tpath := fmt.Sprintf(teamsBasePath, orgID)\n\n\t// Add query params from listOptions\n\tpath, err := setQueryParams(path, listOptions)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := s.Client.NewRequest(ctx, http.MethodGet, path, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\troot := new(atlas.TeamsResponse)\n\tresp, err := s.Client.Do(ctx, req, root)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\tif l := root.Links; l != nil {\n\t\tresp.Links = l\n\t}\n\n\treturn root.Results, resp, nil\n}",
"func (c *Client) GetList(board *trello.Board, name string) (*trello.List, error) {\n\tlists, err := board.GetLists(trello.Defaults())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, list := range lists {\n\t\tif list.Name == name {\n\t\t\treturn list, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"could not find list %s on board %s\", name, board.Name)\n}",
"func (c *vaultLists) List(opts v1.ListOptions) (result *v1alpha1.VaultList, err error) {\n\tresult = &v1alpha1.VaultList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"vaultlists\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}",
"func PollsList(c buffalo.Context) error {\n\t// Get the DB connection from the context\n\ttx, ok := c.Value(\"tx\").(*pop.Connection)\n\tif !ok {\n\t\treturn errors.WithStack(errors.New(\"no transaction found\"))\n\t}\n\n\tpolls := models.Polls{}\n\n\t// Retrieve all Polls from the DB\n\tif err := tx.All(&polls); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tresult := PollsWithMembers{}\n\n\t// retrieve members of each pole\n\tfor _, p := range polls {\n\t\ts, err := obtainPollStatistics(tx, &p)\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\n\t\ttmp := PollWithMembers{p, s}\n\t\tresult = append(result, tmp)\n\t}\n\n\treturn c.Render(200, r.JSON(result))\n}",
"func (s *playlistService) ListEntries(ctx context.Context, id uint, offset uint, limit uint) ([]models.PlaylistVideoEntry, uint, error) {\n\t// Check if the playlist exists\n\t_, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\t// All right - get the entries\n\tlist, numRows, err := s.repo.GetEntries(id, offset, limit)\n\tif err != nil {\n\t\treturn nil, 0, MakeErrorWithData(\n\t\t\thttp.StatusInternalServerError,\n\t\t\tErrCodeRepoError,\n\t\t\tfmt.Sprintf(\"Error while retrieving playlist entries for #%d\", id),\n\t\t\terr,\n\t\t)\n\t}\n\treturn list, numRows, nil\n}",
"func (s *ApiInterface) SelectMoodPlaylists(c echo.Context) error {\n\t//mood := c.Param(\"mood\")\n\tparams := new(MoodParams)\n\n\tif frontend {\n\t\t// bind params\n\t\terr := c.Bind(params)\n\t\tif err != nil {\n\t\t\treturn BadRequestResponse(c, err.Error())\n\t\t}\n\t}else {\n\t\tparams.Mood = \"happy\"\n\t}\n\tplaylists := s.GetPlaylistbyMood(params.Mood)\n\n\tvar p string\n\tif len(playlists) < 1 {\n\t\tp = \"3cEYpjA9oz9GiPac4AsH4n\"\n\t}\n\n\tp = playlists[0].Id\n\n\tplaylist := s.spotify.SearchPlaylist(p)\n\n\t//log.Println(playlist)\n\n\treturn c.JSONPretty(200, playlist, \"\" )\n}",
"func GetList(w http.ResponseWriter, r *http.Request) {\n\tlist, err := watchlist.GetWatchList(r)\n\n\tif err != nil {\n\t\thttpext.AbortAPI(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thttpext.JSON(w, list)\n}",
"func (c *Client) ListWorkspaces(ctx context.Context, params *ListWorkspacesInput, optFns ...func(*Options)) (*ListWorkspacesOutput, error) {\n\tif params == nil {\n\t\tparams = &ListWorkspacesInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"ListWorkspaces\", params, optFns, addOperationListWorkspacesMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*ListWorkspacesOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}",
"func (s *teams) List(ctx context.Context, organization string, options *TeamListOptions) (*TeamList, error) {\n\tif !validStringID(&organization) {\n\t\treturn nil, ErrInvalidOrg\n\t}\n\tif err := options.valid(); err != nil {\n\t\treturn nil, err\n\t}\n\tu := fmt.Sprintf(\"organizations/%s/teams\", url.QueryEscape(organization))\n\treq, err := s.client.NewRequest(\"GET\", u, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttl := &TeamList{}\n\terr = req.Do(ctx, tl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tl, nil\n}",
"func listTeams(w http.ResponseWriter, r *http.Request) {\n\tteam := models.NewTeam(\"\")\n\tskue.List(view, team, w, r)\n}",
"func (app *application) listPlayers(w http.ResponseWriter, r *http.Request) {\n\tplayerID := app.session.GetInt(r, \"authenticatedPlayerID\")\n\tp, err := app.players.List(playerID, \"loggedIn\")\n\tif err != nil {\n\t\tif xerrors.Is(err, models.ErrNoRecord) {\n\t\t\tapp.notFound(w)\n\t\t} else {\n\t\t\tapp.serverError(w, err)\n\t\t}\n\t\treturn\n\t}\n\tapp.renderPlayers(w, r, \"list.players.page.tmpl\", &templateDataPlayers{\n\t\tPlayers: \t\t\tp,\n\t})\n}",
"func (r *RemarketingListsService) List(profileId int64, advertiserId int64) *RemarketingListsListCall {\n\tc := &RemarketingListsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.profileId = profileId\n\tc.urlParams_.Set(\"advertiserId\", fmt.Sprint(advertiserId))\n\treturn c\n}",
"func (c *Client) List(opts *ListOptions) ([]*team.Team, error) {\n\tc.init()\n\n\treq := &stack.TeamListRequest{}\n\tif opts != nil {\n\t\treq.Slug = opts.Slug\n\t}\n\n\tresp := stack.TeamListResponse{}\n\tif err := c.kloud().Call(\"team.list\", req, &resp); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.Teams, nil\n}",
"func (g Gitlab) List(ctx context.Context) ([]string, error) {\n\tclient, err := gitlab.NewClient(\n\t\tg.Token,\n\t\tgitlab.WithBaseURL(g.URL),\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"List: %w\", err)\n\t}\n\n\t// TODO: pagination\n\trepos, resp, err := client.Projects.ListProjects(\n\t\t&gitlab.ListProjectsOptions{\n\t\t\tVisibility: gitlab.Visibility(gitlab.PrivateVisibility),\n\t\t},\n\t\tgitlab.WithContext(ctx),\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"List: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tvar res []string\n\tfor _, r := range repos {\n\t\tres = append(res, r.SSHURLToRepo)\n\t}\n\n\treturn res, nil\n}",
"func (a MWSWorkspacesAPI) List(mwsAcctId string) ([]model.MWSWorkspace, error) {\n\tvar mwsWorkspacesList []model.MWSWorkspace\n\n\tworkspacesAPIPath := fmt.Sprintf(\"/accounts/%s/workspaces\", mwsAcctId)\n\n\tresp, err := a.Client.performQuery(http.MethodGet, workspacesAPIPath, \"2.0\", nil, nil, nil)\n\tif err != nil {\n\t\treturn mwsWorkspacesList, err\n\t}\n\n\terr = json.Unmarshal(resp, &mwsWorkspacesList)\n\treturn mwsWorkspacesList, err\n}",
"func List(collection Getter) func(ctx context.Context) ([]interface{}, error) {\n\treturn func(ctx context.Context) ([]interface{}, error) {\n\t\tprojects := []Project{}\n\t\terr := collection.GetAll(ctx, &projects)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems := make([]interface{}, len(projects))\n\t\tfor i, v := range projects {\n\t\t\titems[i] = v\n\t\t}\n\t\treturn items, nil\n\t}\n}",
"func GetLists(ctx Context) {\n\titems, err := db.SelectAllItems()\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, nil)\n\t\treturn\n\t}\n\tctx.JSON(http.StatusOK, items)\n}",
"func ListGames(_ context.Context) ([]*Game, error) {\n\tc := &http.Client{Timeout: time.Second * 10}\n\tresp, err := c.Get(gameListURL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error requesting game list: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"recevied non 200 status code\")\n\t}\n\n\tif resp.Body == http.NoBody {\n\t\treturn nil, fmt.Errorf(\"empty body received\")\n\t}\n\n\tvar games []*Game\n\tif err := json.NewDecoder(resp.Body).Decode(&games); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to read body: %w\", err)\n\t}\n\n\treturn games, nil\n}",
"func GetListTracks(w http.ResponseWriter, r *http.Request) {\n\tresponse := make(map[string]interface{})\n\tqueuedTracks := context.tq.list()\n\n\tresponse[\"queue\"] = queuedTracks\n\tresponse[\"now_playing\"] = map[string]interface{}{\n\t\t\"track\": context.np.current,\n\t\t\"time_remaining\": context.np.timeRemaining,\n\t}\n\n\tjresponse, _ := json.Marshal(response)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write(jresponse)\n}",
"func (a *alphaMock) GetList(ctx context.Context, in *alpha.GetListRequest, opts ...grpc.CallOption) (*alpha.List, error) {\n\t// TODO(#2716): Implement me!\n\treturn nil, errors.Errorf(\"Unimplemented -- GetList coming soon\")\n}",
"func (p *Proxy) List() (data [][]string) {\n\tlumber.Trace(\"Proxy listing subscriptions...\")\n\tp.RLock()\n\tdata = p.subscriptions.ToSlice()\n\tp.RUnlock()\n\n\treturn\n}",
"func (b *ListBuilder) List() (*List, error) {\n\tif len(b.errs) > 0 {\n\t\treturn nil, errors.Errorf(\"failed to build pvc list: %+v\", b.errs)\n\t}\n\n\tb.buildFromTemplateIfNilList()\n\n\tif b.filters == nil || len(b.filters) == 0 {\n\t\treturn b.list, nil\n\t}\n\n\tfilteredList := &List{}\n\tfor _, pvc := range b.list.items {\n\t\tif b.filters.all(pvc) {\n\t\t\tfilteredList.items = append(filteredList.items, pvc)\n\t\t}\n\t}\n\n\treturn filteredList, nil\n}",
"func (s *Server) List(ctx context.Context, q *project.ProjectQuery) (*v1alpha1.AppProjectList, error) {\n\tlist, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).List(ctx, metav1.ListOptions{})\n\tif list != nil {\n\t\tnewItems := make([]v1alpha1.AppProject, 0)\n\t\tfor i := range list.Items {\n\t\t\tproject := list.Items[i]\n\t\t\tif s.enf.Enforce(ctx.Value(\"claims\"), rbacpolicy.ResourceProjects, rbacpolicy.ActionGet, project.Name) {\n\t\t\t\tnewItems = append(newItems, project)\n\t\t\t}\n\t\t}\n\t\tlist.Items = newItems\n\t}\n\treturn list, err\n}",
"func (c *CappedList) List() []string {\n\t// get size of list\n\tsize, err := c.client.LLen(c.name).Result()\n\tif err != nil {\n\t\tsetup.LogCommon(err).Error(\"Failed LLen\")\n\t} else if size > c.size {\n\t\t// sanity check that the list is not bigger than possible\n\t\tsetup.LogCommon(nil).WithField(\"size\", size).Error(\"Size is larger than expected\")\n\t}\n\n\t// get the elements\n\tout, err := c.client.LRange(c.name, 0, size-1).Result()\n\tif err != nil {\n\t\tsetup.LogCommon(err).Error(\"Failed LRange\")\n\t}\n\n\treturn out\n\n}",
"func List(ctx context.Context, client *containerd.Client, options types.ContainerListOptions) ([]ListItem, error) {\n\tcontainers, err := filterContainers(ctx, client, options.Filters, options.LastN, options.All)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn prepareContainers(ctx, client, containers, options)\n}",
"func (m *HookManager) List(opts ...ListOption) (r *HookList, err error) {\n\topts = m.defaults(opts)\n\terr = m.get(m.uri(\"roles\")+m.q(opts), &r)\n\treturn\n}",
"func (c *Firewall) GetList() ([]string, error) {\n\tans := c.container()\n\treturn c.ns.Listing(util.Get, c.pather(), ans)\n}",
"func (tm *topicManager) SubscribedList() []string {\n\ttm.locker.RLock()\n\tlist := make([]string, 0, len(tm.allTopics))\n\tfor name := range tm.allTopics {\n\t\tlist = append(list, name)\n\t}\n\ttm.locker.RUnlock()\n\treturn list\n}",
"func AppsListPlans(ctx context.Context, req *AppsListPlansReq, opt ...RequestOption) (*AppsListPlansResponse, error) {\n\tif req == nil {\n\t\treq = new(AppsListPlansReq)\n\t}\n\tresp := &AppsListPlansResponse{request: req}\n\tr, err := doRequest(ctx, req, opt...)\n\tif r != nil {\n\t\tresp.response = *r\n\t}\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\tresp.Data = []components.MarketplaceListingPlan{}\n\terr = r.decodeBody(&resp.Data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}",
"func (t *TeamsService) List() (*TeamListResponse, *simpleresty.Response, error) {\n\tvar result *TeamListResponse\n\turlStr := t.client.http.RequestURL(\"/teams\")\n\n\t// Set the correct authentication header\n\tt.client.setAuthTokenHeader(t.client.accountAccessToken)\n\n\t// Execute the request\n\tresponse, getErr := t.client.http.Get(urlStr, &result, nil)\n\n\treturn result, response, getErr\n}",
"func (a *Client) ListPipelines(params *ListPipelinesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListPipelinesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListPipelinesParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"listPipelines\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/applications/{appName}/pipelines\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &ListPipelinesReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ListPipelinesOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for listPipelines: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}",
"func testList(t *testing.T) *List {\n\tc := testClient()\n\tc.BaseURL = mockResponse(\"lists\", \"list-api-example.json\").URL\n\tlist, err := c.GetList(\"4eea4ff\", Defaults())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn list\n}",
"func (s *Server) List(ctx context.Context, q *ProjectQuery) (*v1alpha1.AppProjectList, error) {\n\tlist, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).List(metav1.ListOptions{})\n\tlist.Items = append(list.Items, v1alpha1.GetDefaultProject(s.ns))\n\tif list != nil {\n\t\tnewItems := make([]v1alpha1.AppProject, 0)\n\t\tfor i := range list.Items {\n\t\t\tproject := list.Items[i]\n\t\t\tif s.enf.EnforceClaims(ctx.Value(\"claims\"), \"projects\", \"get\", project.Name) {\n\t\t\t\tnewItems = append(newItems, project)\n\t\t\t}\n\t\t}\n\t\tlist.Items = newItems\n\t}\n\treturn list, err\n}",
"func (p *Profile) ListGet() *queue.List {\n\treturn &p.List\n}",
"func (tmdb *TMDb) GetAccountLists(id int, sessionID string, options map[string]string) (*MovieLists, error) {\n\tvar availableOptions = map[string]struct{}{\n\t\t\"page\": {},\n\t\t\"language\": {}}\n\tvar lists MovieLists\n\toptionsString := getOptionsString(options, availableOptions)\n\turi := fmt.Sprintf(\"%s/account/%v/lists?api_key=%s&session_id=%s%s\", baseURL, id, tmdb.apiKey, sessionID, optionsString)\n\tresult, err := getTmdb(uri, &lists)\n\treturn result.(*MovieLists), err\n}",
"func (s *appsyncDatasourceLister) List(selector labels.Selector) (ret []*v1alpha1.AppsyncDatasource, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.AppsyncDatasource))\n\t})\n\treturn ret, err\n}",
"func listMembers() (members []User, err error) {\n\tmembersMu.Lock()\n\tdefer membersMu.Unlock()\n\n\tif membersCache == nil {\n\t\turl := fmt.Sprintf(\"%s/teams/%s/members\", *ghAPIFl, *ghTeamFl)\n\t\treq, err := http.NewRequest(\"GET\", url, nil)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot create GET request: %s\", err)\n\t\t}\n\t\taddAuthentication(req)\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot fetch response: %s\", err)\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tvar members []User\n\t\tif err := json.NewDecoder(resp.Body).Decode(&members); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot decode response: %s\", err)\n\t\t}\n\t\tisBlacklisted := blacklistedMembers()\n\t\tfor i := len(members) - 1; i >= 0; i-- {\n\t\t\tif isBlacklisted[members[i].Login] {\n\t\t\t\tmembers = append(members[:i], members[(i+1):]...)\n\t\t\t}\n\t\t}\n\t\tmembersCache = members\n\t}\n\n\treturn membersCache, nil\n}",
"func (c *Client) ListTracks() ([]*jamsonic.Track, error) {\n\tpanic(\"should not be called.\")\n}",
"func (c *Client) ListConfigs(ctx context.Context, params *ListConfigsInput, optFns ...func(*Options)) (*ListConfigsOutput, error) {\n\tif params == nil {\n\t\tparams = &ListConfigsInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"ListConfigs\", params, optFns, addOperationListConfigsMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*ListConfigsOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}",
"func (r *r) List() ([]*internal.Item, error) {\n\treturn nil, fmt.Errorf(\"not implemented yet\")\n}",
"func (client FirewallPolicyRuleGroupsClient) List(ctx context.Context, resourceGroupName string, firewallPolicyName string) (result FirewallPolicyRuleGroupListResultPage, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/FirewallPolicyRuleGroupsClient.List\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.fprglr.Response.Response != nil {\n\t\t\t\tsc = result.fprglr.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tresult.fn = client.listNextResults\n\treq, err := client.ListPreparer(ctx, resourceGroupName, firewallPolicyName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"network.FirewallPolicyRuleGroupsClient\", \"List\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListSender(req)\n\tif err != nil {\n\t\tresult.fprglr.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"network.FirewallPolicyRuleGroupsClient\", \"List\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult.fprglr, err = client.ListResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"network.FirewallPolicyRuleGroupsClient\", \"List\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\tif result.fprglr.hasNextLink() && result.fprglr.IsEmpty() {\n\t\terr = result.NextWithContext(ctx)\n\t\treturn\n\t}\n\n\treturn\n}",
"func (m *manager) List(query ...*models.ProjectQueryParam) ([]*models.Project, error) {\n\tvar q *models.ProjectQueryParam\n\tif len(query) > 0 {\n\t\tq = query[0]\n\t}\n\treturn dao.GetProjects(q)\n}",
"func (s *ProjectsService) List(ctx context.Context, opts *PagingOptions) (*ProjectsList, error) {\n\tquery := addPaging(url.Values{}, opts)\n\treq, err := s.Client.NewRequest(ctx, http.MethodGet, newURI(projectsURI), WithQuery(query))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get projects request creation failed: %w\", err)\n\t}\n\tres, resp, err := s.Client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"list projects failed: %w\", err)\n\t}\n\n\tif resp != nil && resp.StatusCode == http.StatusNotFound {\n\t\treturn nil, ErrNotFound\n\t}\n\n\tif resp != nil && resp.StatusCode == http.StatusBadRequest {\n\t\treturn nil, fmt.Errorf(\"list projects failed: %s\", resp.Status)\n\t}\n\n\tp := &ProjectsList{\n\t\tProjects: []*Project{},\n\t}\n\tif err := json.Unmarshal(res, p); err != nil {\n\t\treturn nil, fmt.Errorf(\"list projects failed, unable to unmarshal repository list json: %w\", err)\n\t}\n\n\tfor _, r := range p.GetProjects() {\n\t\tr.Session.set(resp)\n\t}\n\n\treturn p, nil\n}",
"func (c *ProjectService) List() ([]Project, *http.Response, error) {\n\tresponse := new(projectListResponse)\n\tapiError := new(APIError)\n\tresp, err := c.sling.New().Get(\"\").Receive(response, apiError)\n\treturn response.Results, resp, relevantError(err, *apiError)\n}",
"func (m *Mux) List(ds *discordgo.Session, dm *discordgo.Message, ctx *Context) {\n\tresp := \"```\\n\"\n\n\tfor p, v := range Config.Feeds {\n\t\tresp += strconv.Itoa(p) + \": \" + v.Feed.Title + \", \" + v.Feed.Link + \"\\n\"\n\t}\n\n\tresp += \"```\\n\"\n\n\tds.ChannelMessageSend(dm.ChannelID, resp)\n\n\treturn\n}",
"func (w Webhook) List(ctx context.Context, listOptions postmand.RepositoryListOptions) ([]*postmand.Webhook, error) {\n\twebhooks := []*postmand.Webhook{}\n\tquery, args := listQuery(\"webhooks\", listOptions)\n\terr := w.db.SelectContext(ctx, &webhooks, query, args...)\n\treturn webhooks, err\n}",
"func (s *Service) LiveList(c context.Context, mid, build int64, pn, ps int, platform string, plat int8) (data []*history.ListRes, err error) {\n\tres, err := s.historyDao.HistoryByTP(c, mid, pn, ps, _tpLive)\n\tif err != nil {\n\t\tlog.Error(\"%+v \", err)\n\t\treturn\n\t}\n\tif len(res) == 0 {\n\t\tdata = []*history.ListRes{}\n\t\treturn\n\t}\n\tdata = s.TogetherHistory(c, res, mid, build, platform, plat)\n\treturn\n}",
"func (d TinkDB) ListWorkflows(fn func(wf Workflow) error) error {\n\trows, err := d.instance.Query(`\n\tSELECT id, template, devices, created_at, updated_at\n\tFROM workflow\n\tWHERE\n\t\tdeleted_at IS NULL;\n\t`)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer rows.Close()\n\tvar (\n\t\tid, tmp, tar string\n\t\tcrAt, upAt time.Time\n\t)\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(&id, &tmp, &tar, &crAt, &upAt)\n\t\tif err != nil {\n\t\t\terr = errors.Wrap(err, \"SELECT\")\n\t\t\td.logger.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\twf := Workflow{\n\t\t\tID: id,\n\t\t\tTemplate: tmp,\n\t\t\tHardware: tar,\n\t\t}\n\t\twf.CreatedAt, _ = ptypes.TimestampProto(crAt)\n\t\twf.UpdatedAt, _ = ptypes.TimestampProto(upAt)\n\t\terr = fn(wf)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr = rows.Err()\n\tif err == sql.ErrNoRows {\n\t\terr = nil\n\t}\n\treturn err\n}",
"func getSwarmingRpcsBotList(ctx context.Context, c *Client, call *swarming_api.BotsListCall) (*swarming_api.SwarmingRpcsBotList, error) {\n\tvar tl *swarming_api.SwarmingRpcsBotList\n\tf := func() error {\n\t\tvar err error\n\t\ttl, err = call.Context(ctx).Do()\n\t\treturn err\n\t}\n\terr := callWithRetries(ctx, f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn tl, nil\n}",
"func (pl *PolledList) List() *pb.ListResponse { return pl.resp.Load().(*pb.ListResponse) }",
"func (pl *PolledList) List() *pb.ListResponse { return pl.resp.Load().(*pb.ListResponse) }",
"func (nls *NetworkListService) ListNetworkLists(opts ListNetworkListsOptions) (*[]AkamaiNetworkList, *ClientResponse, error) {\n\n\tapiURI := fmt.Sprintf(\"%s?listType=%s&extended=%t&includeDeprecated=%t&includeElements=%t\",\n\t\tapiPaths[\"network_list\"],\n\t\topts.TypeOflist,\n\t\topts.Extended,\n\t\topts.IncludeDeprecated,\n\t\topts.IncludeElements)\n\n\tvar k *AkamaiNetworkLists\n\tresp, err := nls.client.NewRequest(\"GET\", apiURI, nil, &k)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn &k.NetworkLists, resp, err\n\n}",
"func List() []string {\n\tvar output []string\n\tfor pushURL := range config.All().Tarts {\n\t\toutput = append(output, pushURL)\n\t}\n\treturn output\n}",
"func (m *Manager) GetReplayList(ctx context.Context, projectUUID uuid.UUID) ([]models.ReplaySpec, error) {\n\treplays, err := m.replaySpecRepoFac.New().GetByProjectID(ctx, projectUUID)\n\tif err != nil {\n\t\tif err == store.ErrResourceNotFound {\n\t\t\treturn []models.ReplaySpec{}, nil\n\t\t}\n\t\treturn []models.ReplaySpec{}, err\n\t}\n\n\tvar recentReplays []models.ReplaySpec\n\tfor _, replay := range replays {\n\t\tif replay.CreatedAt.After(time.Now().UTC().Add(replayListWindow)) {\n\t\t\trecentReplays = append(recentReplays, replay)\n\t\t}\n\t}\n\treturn recentReplays, nil\n}",
"func TeamList(ctx context.Context, w http.ResponseWriter, req *http.Request) error {\n\tvar user = ctx.Value(UserKey).(*dash.User)\n\n\tjson.NewEncoder(w).Encode(teamListResponse{\n\t\tStatus: \"success\",\n\t\tTeams: user.TeamMemberships,\n\t})\n\treturn nil\n}",
"func (s *API) ListQueues(w http.ResponseWriter, req *http.Request) {\n\tlog.Debug(\"ListQueues\")\n\n\tqueueNamePrefix := req.FormValue(\"QueueNamePrefix\")\n\tvar queues []string\n\tfor k, v := range s.sqs.queues {\n\t\tif strings.HasPrefix(k, queueNamePrefix) {\n\t\t\tqueues = append(queues, v.url)\n\t\t}\n\t}\n\n\tresponse := ListQueuesResponse{\n\t\tResult: ListQueuesResult{queues},\n\t\tMetaData: ResponseMetaData{\"00000000-0000-0000-0000-000000000000\"},\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/xml\")\n\tenc := xml.NewEncoder(w)\n\tenc.Indent(\" \", \" \")\n\tif err := enc.Encode(response); err != nil {\n\t\tlog.Errorf(\"error: %s\", err)\n\t}\n}",
"func listHandler(w http.ResponseWriter, r *http.Request) *appError {\n\tvideos, err := bittube.DB.ListVideos()\n\tif err != nil {\n\t\treturn appErrorf(err, \"could not list videos: %v\", err)\n\t}\n\n\treturn listTmpl.Execute(w, r, videos)\n}",
"func ListPushed(client *occlient.Client, componentName string, applicationName string) (URLList, error) {\n\n\tlabelSelector := fmt.Sprintf(\"%v=%v\", applabels.ApplicationLabel, applicationName)\n\n\tif componentName != \"\" {\n\t\tlabelSelector = labelSelector + fmt.Sprintf(\",%v=%v\", componentlabels.ComponentLabel, componentName)\n\t}\n\n\tklog.V(4).Infof(\"Listing routes with label selector: %v\", labelSelector)\n\troutes, err := client.ListRoutes(labelSelector)\n\n\tif err != nil {\n\t\treturn URLList{}, errors.Wrap(err, \"unable to list route names\")\n\t}\n\n\tvar urls []URL\n\tfor _, r := range routes {\n\t\tif r.OwnerReferences != nil && r.OwnerReferences[0].Kind == \"Ingress\" {\n\t\t\tcontinue\n\t\t}\n\t\ta := getMachineReadableFormat(r)\n\t\turls = append(urls, a)\n\t}\n\n\turlList := getMachineReadableFormatForList(urls)\n\treturn urlList, nil\n\n}",
"func (s *applicationProtocolLister) List(selector labels.Selector) (ret []*v1alpha1.ApplicationProtocol, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ApplicationProtocol))\n\t})\n\treturn ret, err\n}",
"func (g *Goi18n) ListLangs() []string {\n\tg.mu.RLock()\n\tdefer g.mu.RUnlock()\n\tlangs := make([]string, len(g.langs))\n\tcopy(langs, g.langs)\n\treturn langs\n}",
"func GetListMembersWithLists(w http.ResponseWriter, r *http.Request) {\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\r\n\tvar lists []List\r\n\r\n\tjson.NewDecoder(r.Body).Decode(&lists)\r\n\r\n\tvar listMembers = make([]ListMember, 0)\r\n\tfmt.Println(\"lists \", lists)\r\n\tfor _, list := range lists {\r\n\t\tvar listMemberArray []ListMember\r\n\t\tdb.Where(\"listID = ?\", list.UUID).Find(&listMemberArray)\r\n\t\tlistMembers = append(listMembers, listMemberArray...)\r\n\t}\r\n\tfmt.Println(\"listmembers \", listMembers)\r\n\tjson.NewEncoder(w).Encode(listMembers)\r\n}",
"func getAllLists(w io.Writer, r *http.Request) error {\n\tc := appengine.NewContext(r)\n\n\t// If the user is logged in fetch only their lists.\n\t// - user.Current : http://golang.org/s/users#Current\n\t// - Query.Ancestor : http://golang.org/s/datastore#Query.Ancestor\n\n\tlists := []List{}\n\tkeys, err := datastore.NewQuery(listKind).GetAll(c, &lists)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"fetch all lists: %v\", err)\n\t}\n\n\t// Update the encoded keys and encode the lists.\n\tfor i, k := range keys {\n\t\tlists[i].ID = k.Encode()\n\t}\n\treturn json.NewEncoder(w).Encode(lists)\n}",
"func (km *KataMonitor) ListSandboxes(w http.ResponseWriter, r *http.Request) {\n\tsandboxes := km.sandboxCache.getSandboxList()\n\thtmlResponse := IfReturnHTMLResponse(w, r)\n\tif htmlResponse {\n\t\tlistSandboxesHtml(sandboxes, w)\n\t} else {\n\t\tlistSandboxesText(sandboxes, w)\n\t}\n}",
"func (s *inmemStore) List(ctx context.Context, preference *pref.Preference) ([]*pref.Preference, error) {\n\tres := []*pref.Preference{}\n\n\t// Org\n\tp, ok := s.preference[preferenceKey{\n\t\tOrgID: preference.OrgID,\n\t}]\n\tif ok {\n\t\tres = append(res, &p)\n\t}\n\n\t// Org + Teams (teams are numerically ordered)\n\tsort.Slice(preference.Teams, func(i, j int) bool {\n\t\treturn preference.Teams[i] < preference.Teams[j]\n\t})\n\n\tfor _, t := range preference.Teams {\n\t\tp, ok := s.preference[preferenceKey{\n\t\t\tOrgID: preference.OrgID,\n\t\t\tTeamID: t,\n\t\t}]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tres = append(res, &p)\n\t}\n\n\t// Org + UserID\n\tif preference.UserID != 0 { // avoid adding the org preferences twice\n\t\tp, ok := s.preference[preferenceKey{\n\t\t\tOrgID: preference.OrgID,\n\t\t\tUserID: preference.UserID,\n\t\t}]\n\t\tif ok {\n\t\t\tres = append(res, &p)\n\t\t}\n\t}\n\n\treturn res, nil\n}",
"func (s *Server) ListClocks(ctx context.Context, req *pb.ListClocksRequest) (*pb.ListClocksResponse, error) {\n\tnames := []string{}\n\tfor name := range s.clockset {\n\t\tnames = append(names, name)\n\t}\n\treturn &pb.ListClocksResponse{Names: names}, nil\n}",
"func (c *FakeGoogleCloudPubSubSources) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.GoogleCloudPubSubSourceList, err error) {\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewListAction(googlecloudpubsubsourcesResource, googlecloudpubsubsourcesKind, c.ns, opts), &v1alpha1.GoogleCloudPubSubSourceList{})\n\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\tlabel, _, _ := testing.ExtractFromListOptions(opts)\n\tif label == nil {\n\t\tlabel = labels.Everything()\n\t}\n\tlist := &v1alpha1.GoogleCloudPubSubSourceList{ListMeta: obj.(*v1alpha1.GoogleCloudPubSubSourceList).ListMeta}\n\tfor _, item := range obj.(*v1alpha1.GoogleCloudPubSubSourceList).Items {\n\t\tif label.Matches(labels.Set(item.Labels)) {\n\t\t\tlist.Items = append(list.Items, item)\n\t\t}\n\t}\n\treturn list, err\n}",
"func (s *ProviderGRPC) ListBuckets(ctx context.Context, req *pb.ListBucketsRequest) (*pb.ListBucketsResponse, error) {\n\tif req.Project.Id == \"\" {\n\t\treturn nil, errors.New(\"Project ID is required\")\n\t}\n\tvar buckets []*pb.Bucket\n\tit := s.client.Buckets(ctx, req.Project.Id)\n\tfor {\n\t\tbattrs, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Bucket iterator failed: %v\", err)\n\t\t}\n\t\tbuckets = append(buckets, &pb.Bucket{\n\t\t\tName: battrs.Name,\n\t\t})\n\t}\n\treturn &pb.ListBucketsResponse{Buckets: buckets}, nil\n}",
"func ListSubports(port, workDir string) ([]string, error) {\n\tlistCmd := exec.Command(\"mpbb\", \"--work-dir\", workDir, \"list-subports\", \"--archive-site=\", \"--archive-site-private=\", port)\n\tstdout, err := listCmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err = listCmd.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\tsubports := make([]string, 0, 1)\n\tstdoutScanner := bufio.NewScanner(stdout)\n\tfor stdoutScanner.Scan() {\n\t\tline := stdoutScanner.Text()\n\t\tsubports = append(subports, line)\n\t}\n\tif err = listCmd.Wait(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn subports, nil\n}",
"func (repository *MockVideoRepository) GetVideoList(search string, start *uint, count *uint) ([]Video, error) {\n\tvideos := repository.videos\n\tif len(search) != 0 {\n\t\tfiltered := make([]Video, 0)\n\t\tfor _, v := range videos {\n\t\t\tif strings.Contains(v.Name, search) {\n\t\t\t\tfiltered = append(filtered, v)\n\t\t\t}\n\t\t}\n\t\tvideos = filtered\n\t}\n\tif start != nil {\n\t\tvideos = videos[*start:]\n\t}\n\tif count != nil {\n\t\tvideos = videos[:*count]\n\t}\n\treturn videos, repository.errorToReturn\n}",
"func (p *Projector) ListTopics() ([]string, error) {\n\trespch := make(chan []interface{}, 1)\n\tcmd := []interface{}{pCmdListTopics, respch}\n\tresp, err := c.FailsafeOp(p.reqch, respch, cmd, p.finch)\n\terr = c.OpError(err, resp, 1)\n\treturn resp[0].([]string), err\n}",
"func (o *OpenPolls) List() []interface{} {\n\to.RLock()\n\tdefer o.RUnlock()\n\n\tdst := make([]interface{}, 0, len(o.ids))\n\tfor _, stub := range o.ids {\n\t\tdst = append(dst, stub)\n\t}\n\n\treturn dst\n}",
"func (c Client) List(listParams *stripe.SubscriptionScheduleListParams) *Iter {\n\treturn &Iter{stripe.GetIter(listParams, func(p *stripe.Params, b *form.Values) ([]interface{}, stripe.ListContainer, error) {\n\t\tlist := &stripe.SubscriptionScheduleList{}\n\t\terr := c.B.CallRaw(http.MethodGet, \"/v1/subscription_schedules\", c.Key, b, p, list)\n\n\t\tret := make([]interface{}, len(list.Data))\n\t\tfor i, v := range list.Data {\n\t\t\tret[i] = v\n\t\t}\n\n\t\treturn ret, list, err\n\t})}\n}",
"func (c *Client) GetListedBots(ctx context.Context, dims []*swarming_api.SwarmingRpcsStringPair) ([]*ListedHost, error) {\n\tvar out []*ListedHost\n\n\tbots, err := c.GetBots(ctx, dims)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, bot := range bots {\n\t\tvar err error\n\t\tnewEntry := &ListedHost{}\n\t\tnewEntry.Hostname, err = LookupDimension(bot.Dimensions, \"dut_name\")\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tout = append(out, newEntry)\n\t}\n\n\treturn out, nil\n}",
"func (m *MockExtensionStore) ListPublishers(v0 context.Context, v1 stores.PublishersListOptions) ([]*stores.Publisher, error) {\n\tr0, r1 := m.ListPublishersFunc.nextHook()(v0, v1)\n\tm.ListPublishersFunc.appendCall(ExtensionStoreListPublishersFuncCall{v0, v1, r0, r1})\n\treturn r0, r1\n}",
"func (p *listDiscoveryPlugin) ListProjects(provider *gophercloud.ProviderClient, eo gophercloud.EndpointOpts, domainUUID string) ([]core.KeystoneProject, error) {\n\tclient, err := openstack.NewIdentityV3(provider, eo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//gophercloud does not support project listing yet - do it manually\n\turl := client.ServiceURL(\"projects\")\n\tvar opts struct {\n\t\tDomainUUID string `q:\"domain_id\"`\n\t}\n\topts.DomainUUID = domainUUID\n\tquery, err := gophercloud.BuildQueryString(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turl += query.String()\n\n\tvar result gophercloud.Result\n\t_, err = client.Get(url, &result.Body, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar data struct {\n\t\tProjects []core.KeystoneProject `json:\"projects\"`\n\t}\n\terr = result.ExtractInto(&data)\n\treturn data.Projects, err\n}",
"func (c *DefaultIdentityProvider) ListGroups(ctx context.Context, options *metainternal.ListOptions) (*auth.GroupList, error) {\n\tkeyword := \"\"\n\tlimit := 50\n\tif options.FieldSelector != nil {\n\t\tkeyword, _ = options.FieldSelector.RequiresExactMatch(auth.KeywordQueryTag)\n\t\tlimitStr, _ := options.FieldSelector.RequiresExactMatch(auth.QueryLimitTag)\n\t\tif li, err := strconv.Atoi(limitStr); err == nil && li > 0 {\n\t\t\tlimit = li\n\t\t}\n\t}\n\n\t_, tenantID := authentication.GetUsernameAndTenantID(ctx)\n\tif tenantID != \"\" && tenantID != c.tenantID {\n\t\treturn nil, apierrors.NewBadRequest(\"must in the same tenant\")\n\t}\n\n\tallList, err := c.localGroupLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar localGroupList []*authv1.LocalGroup\n\tfor i, item := range allList {\n\t\tif item.Spec.TenantID == c.tenantID {\n\t\t\tlocalGroupList = append(localGroupList, allList[i])\n\t\t}\n\t}\n\n\tif keyword != \"\" {\n\t\tvar newList []*authv1.LocalGroup\n\t\tfor i, val := range localGroupList {\n\t\t\tif strings.Contains(val.Name, keyword) || strings.Contains(val.Spec.DisplayName, keyword) {\n\t\t\t\tnewList = append(newList, localGroupList[i])\n\t\t\t}\n\t\t}\n\t\tlocalGroupList = newList\n\t}\n\n\titems := localGroupList[0:min(len(localGroupList), limit)]\n\n\tgroupList := auth.GroupList{}\n\tfor _, item := range items {\n\t\tgroup := convertToGroup(item)\n\t\tgroupList.Items = append(groupList.Items, group)\n\t}\n\n\treturn &groupList, nil\n}",
"func (s *Starter) List() error {\n\treturn nil\n}"
] | [
"0.7020494",
"0.6430154",
"0.62139994",
"0.62087834",
"0.6195182",
"0.5899103",
"0.5810742",
"0.57816875",
"0.5761272",
"0.56757796",
"0.5598892",
"0.5521912",
"0.5471712",
"0.5426882",
"0.5422508",
"0.5412061",
"0.53927726",
"0.5299401",
"0.5255639",
"0.524921",
"0.5206764",
"0.52017015",
"0.5183225",
"0.5154696",
"0.5151799",
"0.5141043",
"0.51334995",
"0.51262796",
"0.51234174",
"0.510936",
"0.5105557",
"0.50935847",
"0.509049",
"0.50833815",
"0.5079947",
"0.5054208",
"0.5051827",
"0.5040293",
"0.5038451",
"0.50284684",
"0.5025174",
"0.5019996",
"0.4992999",
"0.49926993",
"0.4987935",
"0.4985053",
"0.49805522",
"0.49795565",
"0.49757177",
"0.49683127",
"0.4968042",
"0.49674463",
"0.49644133",
"0.49606538",
"0.49592817",
"0.49493176",
"0.49460456",
"0.49332687",
"0.4930932",
"0.49283254",
"0.4921303",
"0.49171543",
"0.49171075",
"0.49121362",
"0.49083918",
"0.490535",
"0.4894492",
"0.4887398",
"0.48865184",
"0.4872111",
"0.48711392",
"0.4865435",
"0.48621017",
"0.48621017",
"0.48605555",
"0.4859645",
"0.4845288",
"0.48353565",
"0.48348907",
"0.48259678",
"0.4825109",
"0.4822378",
"0.48150563",
"0.4813861",
"0.48115087",
"0.48104775",
"0.48098576",
"0.48080742",
"0.4798473",
"0.47984037",
"0.47981519",
"0.4797855",
"0.4795887",
"0.47938642",
"0.4785439",
"0.47833303",
"0.47831088",
"0.4782527",
"0.47816315",
"0.4781126"
] | 0.79752415 | 0 |
ListPlaylistEntries is an old API and is not implemented for this provider. | func (c *Client) ListPlaylistEntries() ([]*jamsonic.PlaylistEntry, error) {
panic("should not be called.")
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (s *playlistService) ListEntries(ctx context.Context, id uint, offset uint, limit uint) ([]models.PlaylistVideoEntry, uint, error) {\n\t// Check if the playlist exists\n\t_, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\t// All right - get the entries\n\tlist, numRows, err := s.repo.GetEntries(id, offset, limit)\n\tif err != nil {\n\t\treturn nil, 0, MakeErrorWithData(\n\t\t\thttp.StatusInternalServerError,\n\t\t\tErrCodeRepoError,\n\t\t\tfmt.Sprintf(\"Error while retrieving playlist entries for #%d\", id),\n\t\t\terr,\n\t\t)\n\t}\n\treturn list, numRows, nil\n}",
"func playlistItemsList(service *youtube.Service, part string, playlistId string, pageToken string) *youtube.PlaylistItemListResponse {\n\tcall := service.PlaylistItems.List([]string{part})\n\tcall = call.PlaylistId(playlistId)\n\tif pageToken != \"\" {\n\t\tcall = call.PageToken(pageToken)\n\t}\n\tresponse, err := call.Do()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn response\n}",
"func (s *playlistService) ListMainEntries(ctx context.Context, offset uint, limit uint) ([]models.PlaylistVideoEntry, uint, error) {\n\tmainID := s.events.DefaultPlaylistID(ctx)\n\tif mainID == 0 {\n\t\treturn nil, 0, ErrNoCurrentEvent\n\t}\n\treturn s.ListEntries(ctx, mainID, offset, limit)\n}",
"func (s *playlistService) List(ctx context.Context, search *Search) ([]models.Playlist, uint, error) {\n\tlists, numRows, err := s.repo.Find(search.Search, search.Offset, search.Limit)\n\tif err != nil {\n\t\treturn nil, 0, MakeErrorWithData(\n\t\t\thttp.StatusInternalServerError,\n\t\t\tErrCodeRepoError,\n\t\t\tfmt.Sprintf(\"Error while searching playlists\"),\n\t\t\terr,\n\t\t)\n\t}\n\t// Set a marker to the main playlist\n\tmainID := s.events.DefaultPlaylistID(ctx)\n\tfor i, list := range lists {\n\t\tif list.ID == mainID {\n\t\t\tlists[i].IsMain = true // There are no pointers here - so we'll do it this way\n\t\t}\n\t}\n\treturn lists, numRows, nil\n}",
"func (c Client) ListEntries(ids []string) ([]Entry, error) {\n\tif len(ids) > 1000 {\n\t\treturn nil, errors.New(\"The number of entry ids you can pass as an input is limited to 1,000.\")\n\t}\n\turl := c.Config.BaseURL + \"/\" + c.Config.Version + \"/\" + entriesEndpoint + \"/.mget\"\n\tpayload, err := json.Marshal(ids)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewReader(payload))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"Authorization\", \"Bearer \"+c.Config.Token)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\tresp, err := c.Client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar entries []Entry\n\terr = json.Unmarshal(body, &entries)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn entries, nil\n}",
"func (s *SwiftLocation) ListEntries(directoryPath string) ([]FileSpec, *ListEntriesError) {\n\treturn nil, ErrListEntriesNotSupported\n}",
"func (t *TimeEntriesService) List(ctx context.Context, opts *TimeEntriesListOptions) ([]*TimeEntry, *Response, error) {\n\tu := \"time_entries\"\n\tu, err := addOptions(u, opts)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := t.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\ttype Page struct {\n\t\tPagination\n\t\tTimeEntries []*TimeEntry `json:\"time_entries\"`\n\t}\n\tvar page Page\n\n\tresp, err := t.client.Do(ctx, req, &page)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\tresp.populatePageValues(page.Pagination)\n\n\treturn page.TimeEntries, resp, nil\n}",
"func (r *Reference) listEntries() ([]Entry, apis.Version, error) {\n\tif err := r.unlocker.Ensure(); err != nil {\n\t\treturn nil, 0, err\n\t}\n\tdata, ver, err := r.t.client.Read(r.chunk, 0, apis.MaxChunkSize)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tvar result []Entry\n\tfor i := 0; i < EntryCount; i++ {\n\t\tentry := decode(data[i *EntrySize:i *EntrySize+EntrySize], i)\n\t\tif !entry.IsOk() {\n\t\t\treturn nil, 0, errors.New(\"found invalid entry in folder!\")\n\t\t}\n\t\tif entry.Type != NONEXISTENT {\n\t\t\tresult = append(result, entry)\n\t\t}\n\t}\n\treturn result, ver, nil\n}",
"func (s *TimeEntriesService) List(start, end *time.Time) ([]TimeEntry, error) {\n\tu := \"time_entries\"\n\tparams := url.Values{}\n\tif start != nil {\n\t\tparams.Add(\"start_date\", start.Format(time.RFC3339))\n\t}\n\tif end != nil {\n\t\tparams.Add(\"end_date\", end.Format(time.RFC3339))\n\t}\n\tu += \"?\" + params.Encode()\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata := new([]TimeEntry)\n\t_, err = s.client.Do(req, data)\n\n\treturn *data, err\n}",
"func (c *Client) ListPlaylists() ([]*jamsonic.Playlist, error) {\n\tpanic(\"not implemented\")\n}",
"func (s *RaftServer) ListEntries(_ context.Context, _ *raftapi.Empty) (*raftapi.EntryListResponse, error) {\n\tlist, err := s.logRepo.List()\n\tif err != nil {\n\t\treturn nil, model.NewRaftError(&s.member, err)\n\t}\n\tvar logEntries = make([]*raftapi.LogEntry, 0)\n\tfor _, entry := range list {\n\t\tlogEntries = append(logEntries, &raftapi.LogEntry{\n\t\t\tTerm: entry.Term,\n\t\t\tValue: entry.Value,\n\t\t})\n\t}\n\tresponse := &raftapi.EntryListResponse{Entries: logEntries}\n\treturn response, nil\n}",
"func (p *pool) listEntries() ([]entry, error) {\n\tconn := p.Get()\n\tdefer conn.Close()\n\n\tids, err := redis.Ints(conn.Do(\"SMEMBERS\", key(\"entries\")))\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(\"can not receive ids: %w\", err)\n\t}\n\n\tvar entries []entry\n\tfor _, id := range ids {\n\t\tvalues, err := redis.Strings(conn.Do(\n\t\t\t\"HMGET\",\n\t\t\tkey(\"entry\", strconv.Itoa(id)),\n\t\t\t\"from\",\n\t\t\t\"subject\",\n\t\t\t\"text\",\n\t\t\t\"fileext\",\n\t\t\t\"created\",\n\t\t))\n\t\tif err != nil {\n\t\t\treturn nil, xerrors.Errorf(\"can not receice entry %d: %w\", id, err)\n\t\t}\n\n\t\tcreated, err := time.Parse(\"2006-01-02 15:04:05\", values[4])\n\t\tif err != nil {\n\t\t\treturn nil, xerrors.Errorf(\"can not parse created time: %w\", err)\n\t\t}\n\n\t\tentries = append(entries, entry{\n\t\t\tID: id,\n\t\t\tFrom: values[0],\n\t\t\tSubject: values[1],\n\t\t\tText: values[2],\n\t\t\tExtension: values[3],\n\t\t\tCreated: created.Format(\"2006-01-02 15:04\"),\n\t\t})\n\t}\n\treturn entries, nil\n}",
"func (c *CardClient) QueryPlaylist(ca *Card) *PlaylistQuery {\n\tquery := &PlaylistQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := ca.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(card.Table, card.FieldID, id),\n\t\t\tsqlgraph.To(playlist.Table, playlist.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2O, true, card.PlaylistTable, card.PlaylistColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(ca.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}",
"func (t *Tree) ListEntries() (Entries, error) {\n\tif t.entriesParsed {\n\t\treturn t.entries, nil\n\t}\n\n\tstdout, err := NewCommand(\"ls-tree\", t.ID.String()).RunInDirBytes(t.repo.Path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tt.entries, err = parseTreeEntries(stdout, t)\n\tif err == nil {\n\t\tt.entriesParsed = true\n\t}\n\n\treturn t.entries, err\n}",
"func (c *PlaylistClient) Query() *PlaylistQuery {\n\treturn &PlaylistQuery{config: c.config}\n}",
"func (sc *ScreenlyClient) List() *PlayList {\n\tplaylist := &PlayList{}\n\t// The assets endpoint returns a JSON list not a JSON object, so the\n\t// response body can't be decoded directly to a PlayList. So we have\n\t// to unmarshal to the PlayList.Assets field.\n\tresponse, err := sc.doHttp(\"GET\", \"assets\", nil)\n\n\tif err == nil {\n\t\t//io.Copy(os.Stdout, response.Body)\n\t\t// Create a buffer and read response body, eg. [{...}, {...}]\n\t\tb := new(bytes.Buffer)\n\t\t// (the first ignored parameter is the number of bytes read)\n\t\t_, err := b.ReadFrom(response.Body)\n\n\t\tif err == nil {\n\t\t\t// ...now unmarshal to the PlayList.Assets slice.\n\t\t\terr := json.Unmarshal(b.Bytes(), &playlist.Assets)\n\t\t\tif err == nil {\n\t\t\t\treturn playlist\n\t\t\t}\n\t\t}\n\t}\n\tpanic(err)\n}",
"func (c *CardScanClient) QueryPlaylist(cs *CardScan) *PlaylistQuery {\n\tquery := &PlaylistQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := cs.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(cardscan.Table, cardscan.FieldID, id),\n\t\t\tsqlgraph.To(playlist.Table, playlist.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.M2O, false, cardscan.PlaylistTable, cardscan.PlaylistColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(cs.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}",
"func getPlaylistIds() []string {\n\tclient := &http.Client{}\n\n\tvar ids []string\n\turl := \"https://api.spotify.com/v1/users/\" + userId + \"/playlists?limit=50\"\n\tplaylistRequest, err := http.NewRequest(\"GET\", url, nil)\n\n\tplaylistRequest.Header.Add(\"Authorization\", key)\n\tresponse, err := client.Do(playlistRequest)\n\tif err != nil {\n\t\tfmt.Println(\"Request failed with error:\", err)\n\t} else {\n\t\tdata, _ := ioutil.ReadAll(response.Body)\n\t\titems := gjson.Get(string(data), \"items\")\n\t\tfor i := 0; i < len(items.Array()); i++ {\n\t\t\tid := gjson.Get(items.Array()[i].String(), \"id\")\n\t\t\tids = append(ids, id.String())\n\t\t}\n\t}\n\treturn getPlaylistSongIds(ids)\n}",
"func (suite *ExternalPluginEntryTestSuite) TestList() {\n\tmockScript := &mockExternalPluginScript{path: \"plugin_script\"}\n\tentry := externalPluginEntry{\n\t\tEntryBase: NewEntry(\"foo\"),\n\t\tscript: mockScript,\n\t}\n\tentry.SetTestID(\"/foo\")\n\n\tctx := context.Background()\n\tmockInvokeAndWait := func(stdout []byte, err error) {\n\t\tmockScript.OnInvokeAndWait(ctx, \"list\", entry.id(), entry.state).Return(stdout, err).Once()\n\t}\n\n\t// Test that if InvokeAndWait errors, then List returns its error\n\tmockErr := fmt.Errorf(\"execution error\")\n\tmockInvokeAndWait([]byte{}, mockErr)\n\t_, err := entry.List(ctx)\n\tsuite.EqualError(mockErr, err.Error())\n\n\t// Test that List returns an error if stdout does not have the right\n\t// output format\n\tmockInvokeAndWait([]byte(\"bad format\"), nil)\n\t_, err = entry.List(ctx)\n\tsuite.Regexp(regexp.MustCompile(\"stdout\"), err)\n\n\t// Test that List properly decodes the entries from stdout\n\tstdout := \"[\" +\n\t\t\"{\\\"name\\\":\\\"foo\\\",\\\"supported_actions\\\":[\\\"list\\\"]}\" +\n\t\t\"]\"\n\tmockInvokeAndWait([]byte(stdout), nil)\n\tentries, err := entry.List(ctx)\n\tif suite.NoError(err) {\n\t\texpectedEntries := []Entry{\n\t\t\t&externalPluginEntry{\n\t\t\t\tEntryBase: NewEntry(\"foo\"),\n\t\t\t\tsupportedActions: []string{\"list\"},\n\t\t\t\tscript: entry.script,\n\t\t\t},\n\t\t}\n\n\t\tsuite.Equal(expectedEntries, entries)\n\t}\n}",
"func (suite *ExternalPluginEntryTestSuite) TestList() {\n\tmockScript := &mockExternalPluginScript{path: \"plugin_script\"}\n\tentry := &externalPluginEntry{\n\t\tEntryBase: NewEntry(\"foo\"),\n\t\tscript: mockScript,\n\t}\n\tentry.SetTestID(\"/foo\")\n\n\tctx := context.Background()\n\tmockInvokeAndWait := func(stdout []byte, err error) {\n\t\tmockScript.OnInvokeAndWait(ctx, \"list\", entry).Return(stdout, err).Once()\n\t}\n\n\t// Test that if InvokeAndWait errors, then List returns its error\n\tmockErr := fmt.Errorf(\"execution error\")\n\tmockInvokeAndWait([]byte{}, mockErr)\n\t_, err := entry.List(ctx)\n\tsuite.EqualError(mockErr, err.Error())\n\n\t// Test that List returns an error if stdout does not have the right\n\t// output format\n\tmockInvokeAndWait([]byte(\"bad format\"), nil)\n\t_, err = entry.List(ctx)\n\tsuite.Regexp(regexp.MustCompile(\"stdout\"), err)\n\n\t// Test that List properly decodes the entries from stdout\n\tstdout := \"[\" +\n\t\t\"{\\\"name\\\":\\\"foo\\\",\\\"methods\\\":[\\\"list\\\"]}\" +\n\t\t\"]\"\n\tmockInvokeAndWait([]byte(stdout), nil)\n\tentries, err := entry.List(ctx)\n\tif suite.NoError(err) {\n\t\texpectedEntries := []Entry{\n\t\t\t&externalPluginEntry{\n\t\t\t\tEntryBase: NewEntry(\"foo\"),\n\t\t\t\tmethods: []string{\"list\"},\n\t\t\t\tscript: entry.script,\n\t\t\t},\n\t\t}\n\n\t\tsuite.Equal(expectedEntries, entries)\n\t}\n}",
"func (service *EntriesService) List(spaceID string) *Collection {\n\tpath := fmt.Sprintf(\"/spaces/%s%s/entries\", spaceID, getEnvPath(service.c))\n\tmethod := \"GET\"\n\n\treq, err := service.c.newRequest(method, path, nil, nil)\n\tif err != nil {\n\t\treturn &Collection{}\n\t}\n\n\tcol := NewCollection(&CollectionOptions{})\n\tcol.c = service.c\n\tcol.req = req\n\n\treturn col\n}",
"func createPlaylist() {\n\tvar URL *url.URL\n\tURL, err := url.Parse(\"https://api.spotify.com\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tURL.Path += \"v1/users/\" + sCurrentUser.UserID + \"/playlists\"\n\n\treqBody := map[string]interface{}{\n\t\t\"name\": partyName,\n\t\t\"description\": \"My party created by SoundSync\",\n\t}\n\n\tbytesRepresentation, err := json.Marshal(reqBody)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"POST\", URL.String(), bytes.NewBuffer(bytesRepresentation))\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+sAcsTok.AccessToken)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = json.Unmarshal(body, &sCurrentPlaylist)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println()\n\tfmt.Println(\"Playlist Information:\")\n\tfmt.Printf(\"\\t:Playlist Name: %s\\n\", sCurrentPlaylist.PlaylistName)\n\tfmt.Printf(\"\\t:Playlist URI: %s\\n\", sCurrentPlaylist.PlaylistURI)\n\n\tdefer resp.Body.Close()\n}",
"func (ep *eventsProvider) List(pageParams ...interface{}) ([]*events.Item, error) {\n\titems := make([]*events.Item, len(ep.Data))\n\n\tep.mutex.RLock()\n\tdefer ep.mutex.RUnlock()\n\tcopy(items, ep.Data)\n\n\treturn items, nil\n}",
"func (s *EtcdV3) List(directory string) ([]*store.KVPair, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), s.timeout)\n\tdefer cancel()\n\n\tresp, err := s.client.Get(ctx, directory, clientv3.WithPrefix())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkvpairs := make([]*store.KVPair, 0, len(resp.Kvs))\n\n\tif len(resp.Kvs) == 0 {\n\t\treturn kvpairs, nil\n\t}\n\n\tfor _, kv := range resp.Kvs {\n\t\tpair := &store.KVPair{\n\t\t\tKey: string(kv.Key),\n\t\t\tValue: kv.Value,\n\t\t\tLastIndex: uint64(kv.Version),\n\t\t}\n\t\tkvpairs = append(kvpairs, pair)\n\t}\n\n\treturn kvpairs, nil\n}",
"func RetrievePlaylists(c *gin.Context) {\n\tcode := c.Param(\"code\")\n\tsession, err := FindSessionForCode(&Session{Code: code})\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, common.NewError(\"session\", errors.New(\"Invalid session code\")))\n\t\treturn\n\t}\n\tplaylists, _ := GetPlaylistsForSession(session)\n\tc.JSON(http.StatusOK, playlists)\n}",
"func NewPlaylistView(playSong func(song *models.Song), playSongs func(songs []*models.Song)) *PlaylistView {\n\tp := &PlaylistView{\n\t\tBanner: twidgets.NewBanner(),\n\t\tprevious: &previous{},\n\t\tlist: twidgets.NewScrollList(nil),\n\t\tplaySongFunc: playSong,\n\t\tplaySongsFunc: playSongs,\n\n\t\tdescription: tview.NewTextView(),\n\t\tprevBtn: newButton(\"Back\"),\n\t\tplayBtn: newButton(\"Play all\"),\n\t}\n\n\tp.list.ItemHeight = 2\n\tp.list.Padding = 1\n\tp.list.SetInputCapture(p.listHandler)\n\tp.list.SetBorder(true)\n\tp.list.SetBorderColor(config.Color.Border)\n\tp.list.Grid.SetColumns(1, -1)\n\n\tp.SetBorder(true)\n\tp.SetBorderColor(config.Color.Border)\n\tp.list.SetBackgroundColor(config.Color.Background)\n\tp.Grid.SetBackgroundColor(config.Color.Background)\n\tp.listFocused = false\n\tp.playBtn.SetSelectedFunc(p.playAll)\n\n\tp.Banner.Grid.SetRows(1, 1, 1, 1, -1)\n\tp.Banner.Grid.SetColumns(6, 2, 10, -1, 10, -1, 10, -3)\n\tp.Banner.Grid.SetMinSize(1, 6)\n\n\tp.Banner.Grid.AddItem(p.prevBtn, 0, 0, 1, 1, 1, 5, false)\n\tp.Banner.Grid.AddItem(p.description, 0, 2, 2, 6, 1, 10, false)\n\tp.Banner.Grid.AddItem(p.playBtn, 3, 2, 1, 1, 1, 10, true)\n\tp.Banner.Grid.AddItem(p.list, 4, 0, 1, 8, 4, 10, false)\n\n\tbtns := []*button{p.prevBtn, p.playBtn}\n\tselectables := []twidgets.Selectable{p.prevBtn, p.playBtn, p.list}\n\tfor _, btn := range btns {\n\t\tbtn.SetLabelColor(config.Color.ButtonLabel)\n\t\tbtn.SetLabelColorActivated(config.Color.ButtonLabelSelected)\n\t\tbtn.SetBackgroundColor(config.Color.ButtonBackground)\n\t\tbtn.SetBackgroundColorActivated(config.Color.ButtonBackgroundSelected)\n\t}\n\n\tp.prevBtn.SetSelectedFunc(p.goBack)\n\n\tp.Banner.Selectable = selectables\n\tp.description.SetBackgroundColor(config.Color.Background)\n\tp.description.SetTextColor(config.Color.Text)\n\treturn p\n}",
"func (this *FtpsClient) List() (rDirEntryArray_X []DirEntry, rRts error) {\n\tvar DirEntryPtr_X *DirEntry\n\tvar Line_S string\n\trDirEntryArray_X = nil\n\trRts = this.sendRequestToFtpServerDataConn(\"LIST -a\", 150)\n\tif rRts == nil {\n\t\tpReader_O := bufio.NewReader(this.dataConnection_I)\n\t\tif pReader_O != nil {\n\t\t\tfor {\n\t\t\t\tLine_S, rRts = pReader_O.ReadString('\\n')\n\t\t\t\tif rRts == nil {\n\t\t\t\t\t//if rRts == io.EOF {\t\t\t\tbreak\t\t\t}\n\t\t\t\t\t//\t\t\t\t\tthis.debugInfo(\"[LIST] \" + Line_S)\n\t\t\t\t\tDirEntryPtr_X, rRts = this.parseEntryLine(Line_S)\n\t\t\t\t\trDirEntryArray_X = append(rDirEntryArray_X, *DirEntryPtr_X)\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t_, _, rRts = this.CloseFtpDataChannel()\n\t}\n\n\treturn\n}",
"func EndpointGetUserPlaylist(uid, pid string) string {\n\treturn EndpointGetUser(uid) + \"/playlists/\" + pid\n}",
"func (r *ProjectsLogEntriesService) List(projectsId string, filter string, orderBy string, pageSize int64, pageToken string) *ProjectsLogEntriesListCall {\n\treturn &ProjectsLogEntriesListCall{\n\t\ts: r.s,\n\t\tprojectsId: projectsId,\n\t\tfilter: filter,\n\t\torderBy: orderBy,\n\t\tpageSize: pageSize,\n\t\tpageToken: pageToken,\n\t\tcaller_: googleapi.JSONCall{},\n\t\tparams_: make(map[string][]string),\n\t\tpathTemplate_: \"v1beta3/projects/{projectsId}/logEntries\",\n\t}\n}",
"func (service *EntriesService) List(spaceID string) *Collection {\n\tpath := fmt.Sprintf(\"/spaces/%s/environments/%s/entries\", spaceID, service.c.Environment)\n\n\treq, err := service.c.newRequest(http.MethodGet, path, nil, nil)\n\tif err != nil {\n\t\treturn &Collection{}\n\t}\n\n\tcol := NewCollection(&CollectionOptions{})\n\tcol.c = service.c\n\tcol.req = req\n\n\treturn col\n}",
"func (c *Client) StreamingList(ctx context.Context, id ID) (chan Event, error) {\n\tparams := url.Values{}\n\tparams.Set(\"list\", string(id))\n\n\treturn c.streaming(ctx, \"list\", params)\n}",
"func StartListEntriesCall(m telemetry.Metrics) *telemetry.CallCounter {\n\treturn telemetry.StartCall(m, telemetry.RegistrationAPI, telemetry.Entry, telemetry.List)\n}",
"func parseDashPlaylist(r io.Reader) (AvailableMedia, error) {\n\t// Parse XML\n\tvar parsedXML DashPlaylistXML\n\terr := xml.NewDecoder(r).Decode(&parsedXML)\n\tif err != nil {\n\t\treturn AvailableMedia{}, errors.Wrap(err, \"cannot parse XML\")\n\t}\n\t// Convert to result\n\tvar result AvailableMedia\n\tfor _, media := range parsedXML.Period.MediaTypes {\n\t\tswitch media.ContentType {\n\t\tcase \"video\":\n\t\t\tresult.AvailableVideos = make([]AvailableVideo, len(media.Qualities))\n\t\t\tfor i, video := range media.Qualities {\n\t\t\t\tresult.AvailableVideos[i] = AvailableVideo(video.BaseURL)\n\t\t\t}\n\t\tcase \"audio\":\n\t\t\tresult.AvailableAudios = make([]AvailableAudio, len(media.Qualities))\n\t\t\tfor i, audio := range media.Qualities {\n\t\t\t\tresult.AvailableAudios[i] = AvailableAudio(audio.BaseURL)\n\t\t\t}\n\t\tcase \"\": // Used in very old videos. See tests\n\t\t\tfor _, m := range media.Qualities {\n\t\t\t\tif strings.HasPrefix(m.ID, \"VIDEO\") {\n\t\t\t\t\tresult.AvailableVideos = append(result.AvailableVideos, AvailableVideo(m.BaseURL))\n\t\t\t\t} else if strings.HasPrefix(m.ID, \"AUDIO\") {\n\t\t\t\t\tresult.AvailableAudios = append(result.AvailableAudios, AvailableAudio(m.BaseURL))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn result, nil\n}",
"func (c *ServerConn) List(path string) (entries []*ftps_qftp_client.Entry, err error) {\n\tconn, err := c.cmdDataConnFrom(0, \"LIST %s\", path)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tr := &response{conn, c}\n\tdefer r.Close()\n\n\tscanner := bufio.NewScanner(r)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tentry, err := parseListLine(line)\n\t\tif err == nil {\n\t\t\tentries = append(entries, entry)\n\t\t}\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn\n}",
"func UpdatePlaylist(auth *[]string) error {\n\t// Get env variables.\n\tplaylistId := os.Getenv(\"PLAYLIST_ID\")\n\tnumTopSongs, convErr := strconv.Atoi(os.Getenv(\"N_TOP_SONGS\"))\n\tif convErr != nil {\n\t\terrF := fmt.Errorf(\"Could not convert N_TOP_SONGS env variable: %v\", convErr)\n\t\treturn errF\n\t}\n\n\ttopSongs, topErr := getTopSongs(numTopSongs, auth)\n\tif topErr != nil {\n\t\treturn topErr\n\t}\n\n\treplaceErr := replacePlaylistSongs(playlistId, topSongs, auth)\n\tif replaceErr != nil {\n\t\treturn replaceErr\n\t}\n\n\tnow := time.Now()\n\tdescription := fmt.Sprintf(\"--- last updated: %s --- beep boop im a bot.\", now.Format(\"02/01 03:04pm\"))\n\n\tdescriptionErr := updateDescription(playlistId, description, auth)\n\tif descriptionErr != nil {\n\t\tlogger.Error(descriptionErr)\n\t}\n\n\treturn nil\n}",
"func (c *PlaylistClient) Get(ctx context.Context, id int) (*Playlist, error) {\n\treturn c.Query().Where(playlist.ID(id)).Only(ctx)\n}",
"func (s *Client) GetPlaylist(url string) (*FullPlaylist, error) {\n\tconst URL = \"https://api.spotify.com/v1/playlists/%s\"\n\n\t// WOW! Good URL cleaning! Nice!\n\turl = strings.TrimPrefix(url, \"http://\")\n\turl = strings.TrimPrefix(url, \"https://\")\n\tid := strings.TrimPrefix(url, \"open.spotify.com/playlist/\")\n\n\tplaylistURL := fmt.Sprintf(URL, id)\n\t// log.Printf(\"getting: %v\", playlistURL) XXX: Debug\n\n\tpl := &FullPlaylist{}\n\tif err := s.get(playlistURL, pl); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn pl, nil\n}",
"func ExtractPlaylistInfo(URL string, opts *ExtractOpts, videos chan Video, errc chan error) {\n\tif opts == nil {\n\t\topts = NewExtractOpts()\n\t}\n\n\tparallel(opts.Count, opts.Procs, func(start, end int) {\n\t\t// Construct youtube-dl arguments\n\t\targs := createExtractArgs(URL, opts, start, end)\n\t\terr := doYoutubedl(args, func(stdin, stderr io.ReadCloser) {\n\t\t\tfor {\n\t\t\t\t// Decode video JSON\n\t\t\t\tv := Video{}\n\t\t\t\terr := json.NewDecoder(stdin).Decode(&v)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err != io.EOF && errc != nil {\n\t\t\t\t\t\terrc <- err\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif videos != nil {\n\t\t\t\t\tvideos <- v\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\tif err != nil && errc != nil {\n\t\t\terrc <- err\n\t\t}\n\t})\n\n\t// Close channels\n\tif videos != nil {\n\t\tclose(videos)\n\t}\n\tif errc != nil {\n\t\tclose(errc)\n\t}\n}",
"func GxPlaylist(children ...Element) *CompoundElement { return newCE(\"gx:Playlist\", children) }",
"func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {\n\tif f.opt.SharedFiles {\n\t\treturn f.listReceivedFiles(ctx)\n\t}\n\tif f.opt.SharedFolders {\n\t\treturn f.listSharedFolders(ctx)\n\t}\n\n\troot := f.slashRoot\n\tif dir != \"\" {\n\t\troot += \"/\" + dir\n\t}\n\n\tstarted := false\n\tvar res *files.ListFolderResult\n\tfor {\n\t\tif !started {\n\t\t\targ := files.ListFolderArg{\n\t\t\t\tPath: f.opt.Enc.FromStandardPath(root),\n\t\t\t\tRecursive: false,\n\t\t\t\tLimit: 1000,\n\t\t\t}\n\t\t\tif root == \"/\" {\n\t\t\t\targ.Path = \"\" // Specify root folder as empty string\n\t\t\t}\n\t\t\terr = f.pacer.Call(func() (bool, error) {\n\t\t\t\tres, err = f.srv.ListFolder(&arg)\n\t\t\t\treturn shouldRetry(ctx, err)\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tswitch e := err.(type) {\n\t\t\t\tcase files.ListFolderAPIError:\n\t\t\t\t\tif e.EndpointError != nil && e.EndpointError.Path != nil && e.EndpointError.Path.Tag == files.LookupErrorNotFound {\n\t\t\t\t\t\terr = fs.ErrorDirNotFound\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tstarted = true\n\t\t} else {\n\t\t\targ := files.ListFolderContinueArg{\n\t\t\t\tCursor: res.Cursor,\n\t\t\t}\n\t\t\terr = f.pacer.Call(func() (bool, error) {\n\t\t\t\tres, err = f.srv.ListFolderContinue(&arg)\n\t\t\t\treturn shouldRetry(ctx, err)\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"list continue: %w\", err)\n\t\t\t}\n\t\t}\n\t\tfor _, entry := range res.Entries {\n\t\t\tvar fileInfo *files.FileMetadata\n\t\t\tvar folderInfo *files.FolderMetadata\n\t\t\tvar metadata *files.Metadata\n\t\t\tswitch info := entry.(type) {\n\t\t\tcase *files.FolderMetadata:\n\t\t\t\tfolderInfo = info\n\t\t\t\tmetadata = &info.Metadata\n\t\t\tcase *files.FileMetadata:\n\t\t\t\tfileInfo = info\n\t\t\t\tmetadata = &info.Metadata\n\t\t\tdefault:\n\t\t\t\tfs.Errorf(f, \"Unknown type %T\", entry)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Only the last element is reliably cased in PathDisplay\n\t\t\tentryPath := metadata.PathDisplay\n\t\t\tleaf := f.opt.Enc.ToStandardName(path.Base(entryPath))\n\t\t\tremote := path.Join(dir, leaf)\n\t\t\tif folderInfo != nil {\n\t\t\t\td := fs.NewDir(remote, time.Time{}).SetID(folderInfo.Id)\n\t\t\t\tentries = append(entries, d)\n\t\t\t} else if fileInfo != nil {\n\t\t\t\to, err := f.newObjectWithInfo(ctx, remote, fileInfo)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tentries = append(entries, o)\n\t\t\t}\n\t\t}\n\t\tif !res.HasMore {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn entries, nil\n}",
"func (k *KV) List(prefix string, q *QueryOptions) (KVPairs, *QueryMeta, error) {\n\tresp, qm, err := k.getInternal(prefix, map[string]string{\"recurse\": \"\"}, q)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif resp == nil {\n\t\treturn nil, qm, nil\n\t}\n\tdefer closeResponseBody(resp)\n\n\tvar entries []*KVPair\n\tif err := decodeBody(resp, &entries); err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn entries, qm, nil\n}",
"func (act Account) List(f ListFilter) (List, error) {\n\tvar cl List\n\terr := common.SendGetRequest(fmt.Sprintf(conference.List, act.AccountSid)+f.getQueryString(), act, &cl)\n\treturn cl, err\n}",
"func (srv *Server) PlaylistChange(form url.Values, ps httprouter.Params) (interface{}, error) {\n\tsrv.PlaylistID++\n\tsrv.playlistIndex = 0\n\tt := PlaylistChange{\n\t\tPlaylistId: srv.PlaylistID,\n\t}\n\tif len(form[\"clear\"]) > 0 {\n\t\tsrv.Playlist = nil\n\t\tsrv.ch <- cmdStop\n\t}\n\tm := make(map[SongID]int)\n\tfor i, id := range srv.Playlist {\n\t\tm[id] = i\n\t}\n\tfor _, rem := range form[\"remove\"] {\n\t\tid, err := ParseSongID(rem)\n\t\tif err != nil {\n\t\t\tt.Error(err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tif s, ok := srv.songs[id]; !ok {\n\t\t\tt.Error(\"unknown id: %v\", rem)\n\t\t} else if s == srv.song {\n\t\t\tsrv.ch <- cmdStop\n\t\t}\n\t\tdelete(m, id)\n\t}\n\tfor _, add := range form[\"add\"] {\n\t\tid, err := ParseSongID(add)\n\t\tif err != nil {\n\t\t\tt.Error(err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := srv.songs[id]; !ok {\n\t\t\tt.Error(\"unknown id: %v\", add)\n\t\t}\n\t\tm[id] = len(m)\n\t}\n\tsrv.Playlist = make(Playlist, len(m))\n\tfor songid, index := range m {\n\t\tsrv.Playlist[index] = songid\n\t}\n\tsrv.Save()\n\treturn &t, nil\n}",
"func (c *Client) PlaylistNext() error {\n\t_, err := c.Exec(\"playlist-next\", \"weak\")\n\treturn err\n}",
"func (s *ApiInterface) GetMoodPlaylists(c echo.Context) error {\n\t//mood := c.Param(\"mood\")\n\tparams := new(MoodParams)\n\terr := c.Bind(params)\n\tif err != nil {\n\t\treturn BadRequestResponse(c, err.Error())\n\t}\n\n\tif params.Mood == \"\"{\n\t\tparams.Mood = \"happy\"\n\t}\n\tif params.Playlist != \"\" {\n\t\tplaylist := s.spotify.SearchPlaylist(params.Playlist)\n\t\tplaylist.Event = params.Fitevent\n\t\ts.AddPlaylist(params.Mood,playlist)\n\t\tlog.Println(playlist)\n\t\tplays := make([]api.PlaylistModel,0)\n\t\tplays = append(plays, playlist)\n\t\treturn DataResponse(c, http.StatusOK, plays)\n\t}\n\n\n\tplaylists := s.GetPlaylistbyMood(params.Mood)\n\n\tif len(playlists) < 1 {\n\t\treturn MessageResponseForward(c,http.StatusOK, \"playlist not available, mind some suggestions?\")\n\t}\n\n\t//return c.JSONPretty(200, playlists, \"\" )\n\treturn DataResponse(c, http.StatusOK, playlists)\n}",
"func (app *application) listPlayers(w http.ResponseWriter, r *http.Request) {\n\tplayerID := app.session.GetInt(r, \"authenticatedPlayerID\")\n\tp, err := app.players.List(playerID, \"loggedIn\")\n\tif err != nil {\n\t\tif xerrors.Is(err, models.ErrNoRecord) {\n\t\t\tapp.notFound(w)\n\t\t} else {\n\t\t\tapp.serverError(w, err)\n\t\t}\n\t\treturn\n\t}\n\tapp.renderPlayers(w, r, \"list.players.page.tmpl\", &templateDataPlayers{\n\t\tPlayers: \t\t\tp,\n\t})\n}",
"func handlePlaylist(session fnet.Session) {\n\tlog.Println(\"Handling playlist\")\n\n\twm, err := buildPlaylistMessage()\n\tif checkError(session, err, EvtPlaylist) {\n\t\treturn\n\t}\n\tsession.Conn.Send(wm)\n}",
"func (s priceEntriesService) List(ctx context.Context, paginationOpt common.PaginationOption, sortOpts common.SortOptions) (model.PriceEntries, error) {\n\treturn s.storage.PriceImport().GetPriceEntries(ctx, sortOpts, paginationOpt)\n}",
"func listPlayers(w http.ResponseWriter, r *http.Request) {\n\tplayer := models.NewPlayer(\"\")\n\tskue.List(view, player, w, r)\n}",
"func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {\n\t// defer log.Trace(f, \"dir=%q\", dir)(\"entries = %v, err=%v\", &entries, &err)\n\tif f.root == \"\" && dir == \"\" {\n\t\tentries = make(fs.DirEntries, 0, len(f.upstreams))\n\t\tfor combineDir := range f.upstreams {\n\t\t\td := fs.NewDir(combineDir, f.when)\n\t\t\tentries = append(entries, d)\n\t\t}\n\t\treturn entries, nil\n\t}\n\tu, uRemote, err := f.findUpstream(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tentries, err = u.f.List(ctx, uRemote)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn u.wrapEntries(ctx, entries)\n}",
"func (sc *SoundCloud) GetTracks(url string, submitter *gumble.User) ([]interfaces.Track, error) {\n\tvar (\n\t\tapiURL string\n\t\terr error\n\t\tresp *http.Response\n\t\tv *jason.Object\n\t\ttrack bot.Track\n\t\ttracks []interfaces.Track\n\t)\n\n\turlSplit := strings.Split(url, \"#t=\")\n\n\tapiURL = \"http://api.soundcloud.com/resolve?url=%s&client_id=%s\"\n\n\tif sc.isPlaylist(url) {\n\t\t// Submitter has added a playlist!\n\t\tresp, err = http.Get(fmt.Sprintf(apiURL, urlSplit[0], viper.GetString(\"api_keys.soundcloud\")))\n\t\tdefer resp.Body.Close()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tv, err = jason.NewObjectFromReader(resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttitle, _ := v.GetString(\"title\")\n\t\tpermalink, _ := v.GetString(\"permalink_url\")\n\t\tplaylist := &bot.Playlist{\n\t\t\tID: permalink,\n\t\t\tTitle: title,\n\t\t\tSubmitter: submitter.Name,\n\t\t\tService: sc.ReadableName,\n\t\t}\n\n\t\tvar scTracks []*jason.Object\n\t\tscTracks, err = v.GetObjectArray(\"tracks\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdummyOffset, _ := time.ParseDuration(\"0s\")\n\t\tfor _, t := range scTracks {\n\t\t\ttrack, err = sc.getTrack(t, dummyOffset, submitter)\n\t\t\tif err != nil {\n\t\t\t\t// Skip this track.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttrack.Playlist = playlist\n\t\t\ttracks = append(tracks, track)\n\t\t}\n\n\t\tif len(tracks) == 0 {\n\t\t\treturn nil, errors.New(\"Invalid playlist. No tracks were added\")\n\t\t}\n\t\treturn tracks, nil\n\t}\n\n\t// Submitter has added a track!\n\n\toffset := 0\n\t// Calculate track offset if needed\n\tif len(urlSplit) == 2 {\n\t\ttimeSplit := strings.Split(urlSplit[1], \":\")\n\t\tmultiplier := 1\n\t\tfor i := len(timeSplit) - 1; i >= 0; i-- {\n\t\t\ttime, _ := strconv.Atoi(timeSplit[i])\n\t\t\toffset += time * multiplier\n\t\t\tmultiplier *= 60\n\t\t}\n\t}\n\tplaybackOffset, _ := time.ParseDuration(fmt.Sprintf(\"%ds\", offset))\n\n\tresp, err = http.Get(fmt.Sprintf(apiURL, urlSplit[0], viper.GetString(\"api_keys.soundcloud\")))\n\tdefer resp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tv, err = jason.NewObjectFromReader(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttrack, err = sc.getTrack(v, playbackOffset, submitter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttracks = append(tracks, track)\n\treturn tracks, nil\n}",
"func (s *Service) LiveList(c context.Context, mid, build int64, pn, ps int, platform string, plat int8) (data []*history.ListRes, err error) {\n\tres, err := s.historyDao.HistoryByTP(c, mid, pn, ps, _tpLive)\n\tif err != nil {\n\t\tlog.Error(\"%+v \", err)\n\t\treturn\n\t}\n\tif len(res) == 0 {\n\t\tdata = []*history.ListRes{}\n\t\treturn\n\t}\n\tdata = s.TogetherHistory(c, res, mid, build, platform, plat)\n\treturn\n}",
"func (f *Fs) List(dir string) (entries fs.DirEntries, err error) {\n\tentries, err = f.Fs.List(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.processEntries(entries)\n}",
"func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {\n\tvar iErr error\n\t_, err = f.listAll(ctx, dir, false, false, defaultDepth, func(remote string, isDir bool, info *api.Prop) bool {\n\t\tif isDir {\n\t\t\td := fs.NewDir(remote, time.Time(info.Modified))\n\t\t\t// .SetID(info.ID)\n\t\t\t// FIXME more info from dir? can set size, items?\n\t\t\tentries = append(entries, d)\n\t\t} else {\n\t\t\to, err := f.newObjectWithInfo(ctx, remote, info)\n\t\t\tif err != nil {\n\t\t\t\tiErr = err\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tentries = append(entries, o)\n\t\t}\n\t\treturn false\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif iErr != nil {\n\t\treturn nil, iErr\n\t}\n\treturn entries, nil\n}",
"func (a *API) createNewPlaylist(decade int, country string, moods []string) (radiooooo.Playlist, error) {\n\tbody := new(bytes.Buffer)\n\tpl := QueryPayload{\n\t\tDecade: strconv.Itoa(decade),\n\t\tCountry: country,\n\t\tMoods: moods,\n\t}\n\tif err := json.NewEncoder(body).Encode(pl); err != nil {\n\t\treturn radiooooo.Playlist{}, err\n\t}\n\treq, err := http.NewRequest(\"POST\", fmt.Sprintf(\"%s/api/playlist/next\", a.Endpoint), body)\n\tif err != nil {\n\t\treturn radiooooo.Playlist{}, err\n\t}\n\t// This request doesn't work without this content type\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := a.Client.Do(req)\n\tif err != nil {\n\t\treturn radiooooo.Playlist{}, err\n\t}\n\tdefer resp.Body.Close()\n\tvar playlist radiooooo.PlaylistResponse\n\tif err := json.NewDecoder(resp.Body).Decode(&playlist); err != nil {\n\t\treturn radiooooo.Playlist{}, err\n\t}\n\treturn radiooooo.Playlist{ID: playlist.Playlist}, nil\n}",
"func (s RPCService) List(ctx context.Context, filter *Filter) (*QuestionList, error) {\n\tlist, err := s.storage.Filter(filter)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Coudln't get questions from the storage: %v\", err)\n\t}\n\n\treturn &QuestionList{\n\t\tQuestions: list,\n\t}, nil\n}",
"func (as *ArtworkService) List(ids []int, opts ...Option) ([]*Artwork, error) {\n\tfor len(ids) < 1 {\n\t\treturn nil, ErrEmptyIDs\n\t}\n\n\tfor _, id := range ids {\n\t\tif id < 0 {\n\t\t\treturn nil, ErrNegativeID\n\t\t}\n\t}\n\n\tvar art []*Artwork\n\n\topts = append(opts, SetFilter(\"id\", OpContainsAtLeast, sliceconv.Itoa(ids)...))\n\terr := as.client.post(as.end, &art, opts...)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"cannot get Artworks with IDs %v\", ids)\n\t}\n\n\treturn art, nil\n}",
"func (gs *GreetingService) List(c endpoints.Context, r *GreetingsListReq) (*GreetingsList, error) {\n\tif r.Limit <= 0 {\n\t\tr.Limit = 10\n\t}\n\n\tq := datastore.NewQuery(\"Greeting\").Order(\"-Date\").Limit(r.Limit)\n\tgreets := make([]*Greeting, 0, r.Limit)\n\tkeys, err := q.GetAll(c, &greets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor i, k := range keys {\n\t\tgreets[i].Key = k\n\t}\n\treturn &GreetingsList{greets}, nil\n}",
"func (m *MockIStore) ListEntries(arg0 context.Context, arg1 impl.ListEntriesParams) ([]model.Entry, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListEntries\", arg0, arg1)\n\tret0, _ := ret[0].([]model.Entry)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}",
"func (gs *GreetingService) List(c endpoints.Context, r *GreetingsListReq) (*GreetingsList, error) {\n\tif r.Limit <= 0 {\n\t\tr.Limit = 10\n\t}\n\n\tq := datastore.NewQuery(\"Greeting\").Limit(r.Limit)\n\tgreets := make([]*Greeting, 0, r.Limit)\n\tkeys, err := q.GetAll(c, &greets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor i, k := range keys {\n\t\tgreets[i].Key = k\n\t}\n\treturn &GreetingsList{greets}, nil\n}",
"func ListProjectEvents(id string) error {\n\tclient, err := NewExtPacketClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tevents, _, err := client.Events.ListProjectEvents(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te := MarshallAndPrint(events)\n\treturn e\n}",
"func (h *FlinkApplicationQueryHandler) List(ctx context.Context, project, service, applicationId string) (*ListFlinkApplicationQueryResponse, error) {\n\tpath := buildPath(\"project\", project, \"service\", service, \"flink\", \"application\", applicationId, \"query\")\n\tbts, err := h.client.doGetRequest(ctx, path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r ListFlinkApplicationQueryResponse\n\treturn &r, checkAPIResponse(bts, &r)\n}",
"func ListPlayers(state *state.State, cmd DiscordCommand) error {\n\t// Create RCON connection\n\tconn, err := rcon.Dial(conf.Minecraft.RconIP, conf.Minecraft.RconPort, conf.Minecraft.RconPassword)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\t// Authenticate to RCON\n\tif err = conn.Authenticate(); err != nil {\n\t\treturn err\n\t}\n\n\t// Send the command to Minecraft\n\tresp, err := conn.SendCommand(\"minecraft:list\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Vanilla servers dont support the 'minecraft:' command prefix\n\tif strings.HasPrefix(resp, \"Unknown or incomplete command\") {\n\t\tresp, err = conn.SendCommand(\"list\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tembed := createListEmbed(strings.Split(resp, \":\"))\n\treturn SendCommandEmbed(state, cmd, embed)\n}",
"func ListPreviewResults(cmd *cobra.Command, args []string) error {\n\n\tclient, err := auth.GetClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Parse all flags\n\n\tvar countDefault int32\n\tcount := &countDefault\n\terr = flags.ParseFlag(cmd.Flags(), \"count\", &count)\n\tif err != nil {\n\t\treturn fmt.Errorf(`error parsing \"count\": ` + err.Error())\n\t}\n\tvar offsetDefault int32\n\toffset := &offsetDefault\n\terr = flags.ParseFlag(cmd.Flags(), \"offset\", &offset)\n\tif err != nil {\n\t\treturn fmt.Errorf(`error parsing \"offset\": ` + err.Error())\n\t}\n\tvar sid string\n\terr = flags.ParseFlag(cmd.Flags(), \"sid\", &sid)\n\tif err != nil {\n\t\treturn fmt.Errorf(`error parsing \"sid\": ` + err.Error())\n\t}\n\t// Form query params\n\tgenerated_query := model.ListPreviewResultsQueryParams{}\n\tgenerated_query.Count = count\n\tgenerated_query.Offset = offset\n\n\t// Silence Usage\n\tcmd.SilenceUsage = true\n\n\tresp, err := client.SearchService.ListPreviewResults(sid, &generated_query)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjsonx.Pprint(cmd, resp)\n\treturn nil\n}",
"func (r *r) List() ([]*internal.Item, error) {\n\treturn nil, fmt.Errorf(\"not implemented yet\")\n}",
"func (p Plugin) List(ctx context.Context, module string) ([]string, error) {\n\tresp, err := p.c.List(ctx, &stpb.ListRequest{Module: module})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp.GetVersions(), nil\n}",
"func ListArtists(album string, sort sortOrder, asc bool) []ArtistData {\n\tglobalListCache.RLock()\n\tdefer globalListCache.RUnlock()\n\n\tald, ok := globalListCache.albums[album]\n\tif !ok {\n\t\tswitch sort {\n\t\tcase SortTracks:\n\t\t\tif asc {\n\t\t\t\treturn copyArtistList(globalListCache.artistsByTracksRev)\n\t\t\t} else {\n\t\t\t\treturn copyArtistList(globalListCache.artistsByTracks)\n\t\t\t}\n\t\tcase SortAlbums:\n\t\t\tif asc {\n\t\t\t\treturn copyArtistList(globalListCache.artistsByAlbumsRev)\n\t\t\t} else {\n\t\t\t\treturn copyArtistList(globalListCache.artistsByAlbums)\n\t\t\t}\n\t\tcase SortName:\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\tif asc {\n\t\t\t\treturn copyArtistList(globalListCache.artistsByNameRev)\n\t\t\t} else {\n\t\t\t\treturn copyArtistList(globalListCache.artistsByName)\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch sort {\n\tcase SortTracks:\n\t\tif asc {\n\t\t\treturn copyArtistList(ald.artistsByTracksRev)\n\t\t} else {\n\t\t\treturn copyArtistList(ald.artistsByTracks)\n\t\t}\n\tcase SortAlbums:\n\t\tif asc {\n\t\t\treturn copyArtistList(ald.artistsByAlbumsRev)\n\t\t} else {\n\t\t\treturn copyArtistList(ald.artistsByAlbums)\n\t\t}\n\tcase SortName:\n\t\tfallthrough\n\tdefault:\n\t\tif asc {\n\t\t\treturn copyArtistList(ald.artistsByNameRev)\n\t\t} else {\n\t\t\treturn copyArtistList(ald.artistsByName)\n\t\t}\n\t}\n}",
"func (s *ProjectKeyService) List(organizationSlug string, projectSlug string) ([]ProjectKey, *http.Response, error) {\n\tprojectKeys := new([]ProjectKey)\n\tapiError := new(APIError)\n\tresp, err := s.sling.New().Get(\"projects/\"+organizationSlug+\"/\"+projectSlug+\"/keys/\").Receive(projectKeys, apiError)\n\treturn *projectKeys, resp, relevantError(err, *apiError)\n}",
"func (a *Client) ListChannelListings(params *ListChannelListingsParams, authInfo runtime.ClientAuthInfoWriter) (*ListChannelListingsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListChannelListingsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"listChannelListings\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/channels/{channel_id}/listings\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListChannelListingsReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ListChannelListingsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for listChannelListings: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}",
"func (c *cronFederatedHPAs) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.CronFederatedHPAList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = &v1alpha1.CronFederatedHPAList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"cronfederatedhpas\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}",
"func (v *dir) List(ctx context.Context) ([]plugin.Entry, error) {\n\tif v.dirmap != nil {\n\t\t// Children have been pre-populated by a source parent.\n\t\treturn v.generateChildren(v.dirmap), nil\n\t}\n\n\t// Generate child hierarchy. Don't store it on this entry, but populate new dirs from it.\n\tdirmap, err := v.impl.VolumeList(ctx, v.path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn v.generateChildren(&dirMap{mp: dirmap}), nil\n}",
"func (c *gitTracks) List(opts v1.ListOptions) (result *v1alpha1.GitTrackList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = &v1alpha1.GitTrackList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"gittracks\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}",
"func (client *Client) ListErRouteEntriesWithChan(request *ListErRouteEntriesRequest) (<-chan *ListErRouteEntriesResponse, <-chan error) {\n\tresponseChan := make(chan *ListErRouteEntriesResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.ListErRouteEntries(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}",
"func (c *Client) PlaylistPrevious() error {\n\t_, err := c.Exec(\"playlist-prev\", \"weak\")\n\treturn err\n}",
"func (api *Cmtt) GetFlashEntries() (*[]Entry, error) {\n\tres, err := api.execute(\"getflashholdedentry\", nil, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := &[]Entry{}\n\terr = castStruct(res, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, err\n}",
"func (protocol *CacheStorageProtocol) RequestEntries(\n\tparams *storage.RequestEntriesParams,\n) <-chan *storage.RequestEntriesResult {\n\tresultChan := make(chan *storage.RequestEntriesResult)\n\tcommand := NewCommand(protocol.Socket, \"CacheStorage.requestEntries\", params)\n\tresult := &storage.RequestEntriesResult{}\n\n\tgo func() {\n\t\tresponse := <-protocol.Socket.SendCommand(command)\n\t\tif nil != response.Error && 0 != response.Error.Code {\n\t\t\tresult.Err = response.Error\n\t\t} else {\n\t\t\tresult.Err = json.Unmarshal(response.Result, &result)\n\t\t}\n\t\tresultChan <- result\n\t\tclose(resultChan)\n\t}()\n\n\treturn resultChan\n}",
"func HostSpotifyFetchPlaylistTracks(playlistID string, pool *redis.Pool) (types.Playlist, error) {\n\t// log.Printf(\"PLAYLIST IS %s\\n\", playlistID)\n\tpool = &redis.Pool{\n\t\tDial: func() (redis.Conn, error) {\n\t\t\t// log.Println(os.Getenv(\"REDIS_URL\"))\n\t\t\treturn redisurl.Connect()\n\t\t},\n\t}\n\n\ttok, err := GetSpotifyAuthToken()\n\tif err != nil {\n\t\treturn types.Playlist{}, err\n\t}\n\t// log.Printf(\"\\nReturned token: %#v\", tok.AccessToken)\n\n\tconn := pool.Get()\n\tdefer conn.Close()\n\n\tauth := spotify.NewAuthenticator(os.Getenv(\"SPOTIFY_REDIRECT_URI\"), scopes)\n\tclient := auth.NewClient(tok)\n\tspotifyPlaylist, err := client.GetPlaylist(spotify.ID(playlistID))\n\tif err != nil {\n\t\treturn types.Playlist{}, err\n\t}\n\tdurationMs := 0\n\tavatar := \"\"\n\tif len(spotifyPlaylist.Owner.Images) > 0 {\n\t\tavatar = spotifyPlaylist.Owner.Images[0].URL\n\t}\n\tplaylist := types.Playlist{Description: spotifyPlaylist.Description,\n\t\tCollaborative: spotifyPlaylist.Collaborative,\n\t\tTitle: spotifyPlaylist.Name,\n\t\tOwner: types.PlaylistOwner{Avatar: avatar, ID: spotifyPlaylist.Owner.ID,\n\t\t\tName: spotifyPlaylist.Name},\n\t\tURL: spotifyPlaylist.ExternalURLs[\"spotify\"],\n\t\tCover: spotifyPlaylist.Images[0].URL,\n\t}\n\tfor _, single := range spotifyPlaylist.Tracks.Tracks {\n\t\tdurationMs += single.Track.Duration\n\t\timg := \"\"\n\t\tif len(single.Track.Album.Images) > 0 {\n\t\t\timg = single.Track.Album.Images[0].URL\n\t\t}\n\t\tsingleT := &types.SingleTrack{\n\t\t\tAddedAt: single.AddedAt,\n\t\t\tCover: img,\n\t\t\tDuration: single.Track.Duration,\n\t\t\tExplicit: single.Track.Explicit,\n\t\t\tID: single.Track.ID.String(),\n\t\t\tPlatform: util.HostSpotify,\n\t\t\tTitle: single.Track.Name,\n\t\t\tURL: single.Track.Endpoint,\n\t\t\tReleaseDate: single.Track.Album.ReleaseDate,\n\t\t\tPreview: single.Track.PreviewURL,\n\t\t\tAlbum: single.Track.Album.Name,\n\t\t}\n\t\tfor _, r := range single.Track.Artists {\n\t\t\tsingleT.Artistes = append(singleT.Artistes, r.Name)\n\t\t}\n\t\tplaylist.Tracks = append(playlist.Tracks, *singleT)\n\t}\n\tplaylist.Duration = durationMs\n\n\tif err != nil {\n\t\treturn types.Playlist{}, nil\n\t}\n\tif err != nil {\n\t\treturn types.Playlist{}, nil\n\t}\n\n\t// log.Println(\"Tracks found for the playlist is: \", playlist)\n\treturn playlist, nil\n}",
"func getPlaylistSongIds(playlistIds []string) []string {\n\tclient := &http.Client{}\n\n\tvar ids []string\n\n\tfor _, plId := range playlistIds {\n\t\turl := \"https://api.spotify.com/v1/playlists/\" + plId + \"/tracks?market=US&fields=items(track(id))&limit=50&offset=0\"\n\t\tplaylistRequest, err := http.NewRequest(\"GET\", url, nil)\n\t\tplaylistRequest.Header.Add(\"Authorization\", key)\n\t\tresponse, err := client.Do(playlistRequest)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Request failed with error:\", err)\n\t\t} else {\n\t\t\tdata, _ := ioutil.ReadAll(response.Body)\n\t\t\titems := gjson.Get(string(data), \"items\")\n\t\t\tfor i := 0; i < len(items.Array()); i++ {\n\t\t\t\tid := gjson.Get(items.Array()[i].String(), \"track.id\")\n\t\t\t\tids = append(ids, id.String())\n\t\t\t}\n\t\t}\n\t}\n\treturn ids\n}",
"func (c *Cache) List(ctx context.Context, rawQuery string, dest *[]byte) error {\n\treturn c.group.Get(ctx, prefixList+rawQuery, groupcache.AllocatingByteSliceSink(dest))\n}",
"func (f *Fs) listReceivedFiles(ctx context.Context) (entries fs.DirEntries, err error) {\n\tstarted := false\n\tvar res *sharing.ListFilesResult\n\tfor {\n\t\tif !started {\n\t\t\targ := sharing.ListFilesArg{\n\t\t\t\tLimit: 100,\n\t\t\t}\n\t\t\terr := f.pacer.Call(func() (bool, error) {\n\t\t\t\tres, err = f.sharing.ListReceivedFiles(&arg)\n\t\t\t\treturn shouldRetry(ctx, err)\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tstarted = true\n\t\t} else {\n\t\t\targ := sharing.ListFilesContinueArg{\n\t\t\t\tCursor: res.Cursor,\n\t\t\t}\n\t\t\terr := f.pacer.Call(func() (bool, error) {\n\t\t\t\tres, err = f.sharing.ListReceivedFilesContinue(&arg)\n\t\t\t\treturn shouldRetry(ctx, err)\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"list continue: %w\", err)\n\t\t\t}\n\t\t}\n\t\tfor _, entry := range res.Entries {\n\t\t\tfmt.Printf(\"%+v\\n\", entry)\n\t\t\tentryPath := entry.Name\n\t\t\to := &Object{\n\t\t\t\tfs: f,\n\t\t\t\turl: entry.PreviewUrl,\n\t\t\t\tremote: entryPath,\n\t\t\t\tmodTime: *entry.TimeInvited,\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tentries = append(entries, o)\n\t\t}\n\t\tif res.Cursor == \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn entries, nil\n}",
"func (c *PlaylistClient) Hooks() []Hook {\n\treturn c.hooks.Playlist\n}",
"func GetPlaylist() *Playlist {\n\tif playlist == nil {\n\t\tplaylist = NewPlaylist()\n\t}\n\treturn playlist\n}",
"func (f *Asciidoc) ListEntry(depth int, text string) (string, error) {\n\tif text == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\tprefix := strings.Repeat(\"*\", (depth + 1))\n\treturn fmt.Sprintf(\"%s %s\\n\", prefix, text), nil\n}",
"func (player *musicPlayer) listPlaylists() ([]string, error) {\n\tplayer.Lock()\n\tdefer player.Unlock()\n\t//only the playlists in playlist directory is exposed\n\tfileInfo, err := os.Stat(player.playlistsDir)\n\tif os.IsNotExist(err) || !fileInfo.IsDir() {\n\t\treturn nil, errors.New(playlist_not_found_msg)\n\t}\n\tplaylists := make([]string, 0)\n\td, err := os.Open(player.playlistsDir)\n\tif err != nil {\n\t\treturn nil, errors.New(playlist_not_found_msg)\n\t}\n\tdefer d.Close()\n\tfiles, err := d.Readdir(-1)\n\tif err != nil {\n\t\treturn nil, errors.New(playlist_not_found_msg)\n\t}\n\n\tfor _, file := range files {\n\t\tif file.Mode().IsRegular() && strings.HasSuffix(file.Name(), playlistsExtension) {\n\t\t\tplaylists = append(playlists, file.Name())\n\t\t}\n\t}\n\tif len(playlists) == 0 {\n\t\treturn nil, errors.New(playlist_not_found_msg)\n\t}\n\treturn playlists, nil\n}",
"func (m *manager) List(query ...*models.ProjectQueryParam) ([]*models.Project, error) {\n\tvar q *models.ProjectQueryParam\n\tif len(query) > 0 {\n\t\tq = query[0]\n\t}\n\treturn dao.GetProjects(q)\n}",
"func (s *V3Backend) List(ctx context.Context, key string) ([]args.Pair, error) {\n\tresp, err := s.Client.Get(ctx, key, etcd.WithPrefix())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(resp.Kvs) == 0 {\n\t\treturn nil, errors.New(fmt.Sprintf(\"'%s' not found\", key))\n\t}\n\tresult := make([]args.Pair, 0)\n\tfor _, node := range resp.Kvs {\n\t\tresult = append(result, args.Pair{Key: string(node.Key), Value: node.Value})\n\t}\n\treturn result, nil\n}",
"func (r *ProjectsTimeSeriesService) List(name string) *ProjectsTimeSeriesListCall {\n\tc := &ProjectsTimeSeriesListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}",
"func (c *PeerService) List(gid string, providerName string) ([]Peer, *http.Response, error) {\n\tresponse := new(peerListResponse)\n\tapiError := new(APIError)\n\tpath := fmt.Sprintf(\"%s/peers?providerName=%s\", gid, providerName)\n\tresp, err := c.sling.New().Get(path).Receive(response, apiError)\n\treturn response.Results, resp, relevantError(err, *apiError)\n}",
"func pagedList(\n\tctx context.Context,\n\tlog *logrus.Entry,\n\trevision string,\n\tlist model.ListInterface,\n\ttoKVPs func(Resource) ([]*model.KVPair, error),\n\tlistFunc func(ctx context.Context, opts metav1.ListOptions) (runtime.Object, error),\n) (\n\t*model.KVPairList,\n\terror,\n) {\n\tlp := pager.New(listFunc)\n\topts := metav1.ListOptions{ResourceVersion: revision}\n\tif revision != \"\" {\n\t\topts.ResourceVersionMatch = metav1.ResourceVersionMatchNotOlderThan\n\t}\n\tresult, isPaged, err := lp.List(ctx, opts)\n\tif err != nil {\n\t\treturn nil, K8sErrorToCalico(err, list)\n\t}\n\tlogCtx := log.WithField(\"pagedList\", isPaged)\n\tlogCtx.Debug(\"List() call completed, convert results\")\n\n\t// For each item in the response, convert it to a KVPair and add it to the list.\n\tkvps := []*model.KVPair{}\n\terr = meta.EachListItem(result, func(obj runtime.Object) error {\n\t\tres := obj.(Resource)\n\t\tresult, err := toKVPs(res)\n\t\tif err != nil {\n\t\t\tlogCtx.WithError(err).WithField(\"Item\", res).Warning(\"unable to process resource, skipping\")\n\t\t\treturn nil\n\t\t}\n\t\tif result != nil {\n\t\t\tkvps = append(kvps, result...)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, K8sErrorToCalico(err, list)\n\t}\n\n\t// Extract list revision information.\n\tm, err := meta.ListAccessor(result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &model.KVPairList{\n\t\tKVPairs: kvps,\n\t\tRevision: m.GetResourceVersion(),\n\t}, nil\n}",
"func (s *previewLister) List(selector labels.Selector) (ret []*v1alpha1.Preview, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Preview))\n\t})\n\treturn ret, err\n}",
"func (d *DogNZB) List(t Type) ([]Item, error) {\n\tb, err := d.get(d.buildURL(\"list\", t, \"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar q ListQuery\n\tif err := xml.Unmarshal(b, &q); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// if dognzb sent an error back, we should also error\n\tif q.ErrorCode != 0 {\n\t\treturn nil, fmt.Errorf(\"%v\", q.ErrorDesc)\n\t}\n\n\treturn q.Channel.Items, nil\n}",
"func (c *klusterlets) List(ctx context.Context, opts metav1.ListOptions) (result *v1.KlusterletList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = &v1.KlusterletList{}\n\terr = c.client.Get().\n\t\tResource(\"klusterlets\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}",
"func parseLsListLine(line string) (*ftps_qftp_client.Entry, error) {\n\tfields := strings.Fields(line)\n\tif len(fields) >= 7 && fields[1] == \"folder\" && fields[2] == \"0\" {\n\t\te := &ftps_qftp_client.Entry{\n\t\t\tType: ftps_qftp_client.EntryTypeFolder,\n\t\t\tName: strings.Join(fields[6:], \" \"),\n\t\t}\n\t\tif err := e.SetTime(fields[3:6]); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn e, nil\n\t}\n\n\tif fields[1] == \"0\" {\n\t\te := &ftps_qftp_client.Entry{\n\t\t\tType: ftps_qftp_client.EntryTypeFile,\n\t\t\tName: strings.Join(fields[7:], \" \"),\n\t\t}\n\n\t\tif err := e.SetSize(fields[2]); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := e.SetTime(fields[4:7]); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn e, nil\n\t}\n\n\tif len(fields) < 9 {\n\t\treturn nil, errUnsupportedListLine\n\t}\n\n\te := &ftps_qftp_client.Entry{}\n\tswitch fields[0][0] {\n\tcase '-':\n\t\te.Type = ftps_qftp_client.EntryTypeFile\n\t\tif err := e.SetSize(fields[4]); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase 'd':\n\t\te.Type = ftps_qftp_client.EntryTypeFolder\n\tcase 'l':\n\t\te.Type = ftps_qftp_client.EntryTypeLink\n\tdefault:\n\t\treturn nil, errors.New(\"Unknown entry type\")\n\t}\n\n\tif err := e.SetTime(fields[5:8]); err != nil {\n\t\treturn nil, err\n\t}\n\n\te.Name = strings.Join(fields[8:], \" \")\n\treturn e, nil\n}",
"func (c *Client) List(path string) (entries []client.DirEnt, err error) {\n\tvar ret internal.ListReturn\n\terr = c.server.Call(\"list\", &ret, path, c.session)\n\tif err != nil {\n\t\treturn nil, client.MakeFatalError(err)\n\t}\n\tif ret.Err != \"\" {\n\t\treturn nil, fmt.Errorf(ret.Err)\n\t}\n\tvar ents []client.DirEnt\n\tfor _, e := range ret.Entries {\n\t\tents = append(ents, e)\n\t}\n\treturn ents, nil\n}",
"func (c *kongs) List(opts v1.ListOptions) (result *v1alpha1.KongList, err error) {\n\tresult = &v1alpha1.KongList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"kongs\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}",
"func (s *playlistService) AddEntry(ctx context.Context, id uint, entry *models.PlaylistEntry) error {\n\t// Check if the playlist exists\n\t_, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\tentry.RequestedBy = strings.TrimSpace(entry.RequestedBy)\n\tif entry.RequestedBy == \"\" {\n\t\treturn MakeErrorWithData(\n\t\t\thttp.StatusBadRequest,\n\t\t\tErrCodeRequiredFieldMissing,\n\t\t\t\"RequestedBy must not be empty\",\n\t\t\tmap[string]string{\n\t\t\t\t\"field\": \"requestedBy\",\n\t\t\t},\n\t\t)\n\t}\n\t// Check if the video exists\n\t_, err = s.videoRepo.GetByID(entry.VideoHash)\n\tif err != nil {\n\t\tif err == repos.ErrEntityNotExisting {\n\t\t\treturn MakeError(\n\t\t\t\thttp.StatusBadRequest,\n\t\t\t\tErrCodeVideoNotFound,\n\t\t\t\t\"The requested video does not exist\",\n\t\t\t)\n\t\t}\n\t\treturn MakeErrorWithData(\n\t\t\thttp.StatusInternalServerError,\n\t\t\tErrCodeRepoError,\n\t\t\t\"Failed to retrieve video information\",\n\t\t\terr,\n\t\t)\n\t}\n\tif err := s.repo.AddEntry(id, entry); err != nil {\n\t\treturn MakeErrorWithData(\n\t\t\thttp.StatusInternalServerError,\n\t\t\tErrCodeRepoError,\n\t\t\tfmt.Sprintf(\"Error while adding entry to playlist #%d\", id),\n\t\t\terr,\n\t\t)\n\t}\n\t// NumRequested++\n\tif err := s.videoRepo.BumpNumRequested(entry.VideoHash); err != nil {\n\t\t// Do not report the error back, but log it!\n\t\ts.logger.WithError(err).WithField(log.FldVideo, entry.VideoHash).Error(\"Failed to update request counter for video\")\n\t}\n\treturn nil\n}",
"func (t *Tree) ListEntriesRecursive() (Entries, error) {\n\tif t.entriesRecursiveParsed {\n\t\treturn t.entriesRecursive, nil\n\t}\n\tstdout, err := NewCommand(\"ls-tree\", \"-t\", \"-r\", t.ID.String()).RunInDirBytes(t.repo.Path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tt.entriesRecursive, err = parseTreeEntries(stdout, t)\n\tif err == nil {\n\t\tt.entriesRecursiveParsed = true\n\t}\n\n\treturn t.entriesRecursive, err\n}",
"func ListHistoryByPlayer(db *gorm.DB, id int) []History {\n\tvar history []History\n\tdb.Where(\"player_id = ?\", id).Find(&history)\n\n\treturn history\n}",
"func (mr *MockIStoreMockRecorder) ListEntries(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListEntries\", reflect.TypeOf((*MockIStore)(nil).ListEntries), arg0, arg1)\n}",
"func (s *MeService) GetLibraryPlaylistTracks(ctx context.Context, id string, opt *Options) ([]Song, error) {\n\tu := fmt.Sprintf(\"v1/me/library/playlists/%s/tracks\", id)\n\n\tvar tracks []Song\n\tfor len(u) > 0 {\n\t\tlpt, _, err := s.getLibraryPlaylistsTracks(ctx, u, opt)\n\t\tif err != nil {\n\t\t\treturn tracks, err\n\t\t}\n\n\t\ttracks = append(tracks, lpt.Data...)\n\t\tu = lpt.Next\n\t}\n\n\treturn tracks, nil\n}"
] | [
"0.7966291",
"0.6598785",
"0.6561364",
"0.63831013",
"0.5997888",
"0.5931071",
"0.5802549",
"0.57821965",
"0.56691915",
"0.5645718",
"0.5630918",
"0.5503956",
"0.54796",
"0.53174067",
"0.5308516",
"0.52733445",
"0.5272165",
"0.52561796",
"0.5234577",
"0.51927793",
"0.5180792",
"0.51597047",
"0.5156673",
"0.51524436",
"0.5151795",
"0.51418805",
"0.5131282",
"0.51263744",
"0.5122957",
"0.511122",
"0.51073",
"0.50991523",
"0.50893235",
"0.5082801",
"0.5069547",
"0.5068798",
"0.5061888",
"0.5060328",
"0.50441635",
"0.5033243",
"0.5032715",
"0.50314707",
"0.50276387",
"0.50189614",
"0.5011619",
"0.5006865",
"0.49786893",
"0.4977039",
"0.4975105",
"0.49712053",
"0.49710286",
"0.496554",
"0.49633208",
"0.4957258",
"0.4949011",
"0.49401745",
"0.49371383",
"0.49359748",
"0.49051097",
"0.49041623",
"0.48902154",
"0.48852926",
"0.4884131",
"0.48683164",
"0.48680997",
"0.48505837",
"0.48493156",
"0.48465106",
"0.48407727",
"0.4828075",
"0.4826659",
"0.482463",
"0.48219776",
"0.48209256",
"0.4818576",
"0.48135173",
"0.4810555",
"0.48070782",
"0.47973394",
"0.47871143",
"0.47851604",
"0.4782748",
"0.47817713",
"0.47810292",
"0.47783443",
"0.47769257",
"0.4775722",
"0.47744808",
"0.4772853",
"0.47715154",
"0.47668868",
"0.4759984",
"0.47563213",
"0.47490495",
"0.4745524",
"0.47370365",
"0.47363952",
"0.4734276",
"0.47342527",
"0.47337282"
] | 0.84085166 | 0 |
GetTrackInfo is an old API and is not implemented for this provider. | func (c *Client) GetTrackInfo(trackID string) (*jamsonic.Track, error) {
panic("should not be called.")
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (s *Server) GetCurrentTrack(ctx context.Context, in *GetTrackRequest) (*Track, error) {\n\tif in.ZoneId == \"\" && in.SpeakerId == \"\" {\n\t\treturn &Track{}, nil\n\t}\n\tif in.ZoneId != \"\" {\n\t\tt, err := s.service.GetTrackForZone(in.ZoneId)\n\t\tif err != nil {\n\t\t\treturn &Track{}, nil\n\t\t}\n\t\treturn &Track{Artist: t.Artist, Album: t.Album, Title: t.Title, Artwork: t.Artwork}, nil\n\t} else {\n\t\tt, err := s.service.GetTrackForSpeaker(in.SpeakerId)\n\t\tif err != nil {\n\t\t\treturn &Track{}, nil\n\t\t}\n\t\treturn &Track{Artist: t.Artist, Album: t.Album, Title: t.Title, Artwork: t.Artwork}, nil\n\t}\n}",
"func SpotifyGetTrack(trackID spotify.ID) *spotify.FullTrack {\n\tresults, err := client.GetTrack(trackID)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn results\n}",
"func (c *gitTracks) Get(name string, options v1.GetOptions) (result *v1alpha1.GitTrack, err error) {\n\tresult = &v1alpha1.GitTrack{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"gittracks\").\n\t\tName(name).\n\t\tVersionedParams(&options, scheme.ParameterCodec).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}",
"func (s *KSession) GetTrack(id int64) (results Track, err error) {\n\tresults = Track{}\n\tres, err := s.request(\"GET\", EndpointLyricsTrack(id), nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(res, &results)\n\treturn\n}",
"func TrackInfo(embed *discordgo.MessageEmbed) *discordgo.MessageEmbed {\n\tembed.Author.Name = \"Command: ti / tinfo / tracking / trackinfo\"\n\tembed.Description = \"`(ti|tinfo|tracking|trackinfo)` gives you the information regarding what types of scores are being tracked for the channel.\"\n\tembed.Fields = []*discordgo.MessageEmbedField{\n\t\t{\n\t\t\tName: \"Related Commands:\",\n\t\t\tValue: \"`track`, `tracktoggle`\",\n\t\t},\n\t}\n\treturn embed\n}",
"func (s Mocha) ParseTrackInfo(raw []byte) (*models.TrackInfo, error) {\n\treturn parseTrackInfo(raw)\n}",
"func (t Tunes) ParseTrackInfo(raw []byte) (*models.TrackInfo, error) {\n\tresp := &wdwnTunesResponse{}\n\terr := json.Unmarshal(raw, &resp)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to unmarshal WDWNTunes info: %w\", err)\n\t\treturn nil, err\n\t}\n\tinfo := &models.TrackInfo{}\n\n\tstartedAt, err := time.Parse(\"2006-01-02 15:04:05-07:00\", resp.CurrentTrack.Start)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to parse WDWNTunes started at info: %w\", err)\n\t\tstartedAt = time.Time{}\n\t}\n\n\tinfo.Title = resp.CurrentTrack.Title\n\tinfo.Artist = resp.CurrentTrack.Artist\n\tinfo.Album = \"\"\n\tinfo.Duration = resp.CurrentTrack.Duration\n\tinfo.StartedAt = startedAt\n\n\treturn info, nil\n}",
"func (o *SmsTracking) GetTrack() string {\n\tif o == nil || o.Track == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Track\n}",
"func (o *SmsTracking) GetTrackOk() (*string, bool) {\n\tif o == nil || o.Track == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Track, true\n}",
"func (c *Client) GetTrack(id string, options *Options) (FullTrack, error) {\n\tvar track FullTrack\n\n\turl := constructURL(options, c.baseURL, \"tracks\", id)\n\terr := c.get(url, &track)\n\tif err != nil {\n\t\treturn FullTrack{}, err\n\t}\n\treturn track, nil\n}",
"func (sp *StreamProc) TrackInfos() []TrackInfo {\n\tret := make([]TrackInfo, len(sp.tracks))\n\tfor trackID, track := range sp.tracks {\n\t\tret[trackID] = TrackInfo{\n\t\t\tLastSequenceNumber: uint16(atomic.LoadUint32(&track.lastSequenceNumber)),\n\t\t\tLastTimeRTP: atomic.LoadUint32(&track.lastTimeRTP),\n\t\t\tLastTimeNTP: atomic.LoadInt64(&track.lastTimeNTP),\n\t\t\tLastSSRC: atomic.LoadUint32(&track.lastSSRC),\n\t\t}\n\t}\n\treturn ret\n}",
"func GetTrack(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tid := vars[\"short_id\"]\n\n\ttrack, err := database.GetTrackByShortID(id)\n\tif err != nil {\n\t\tutils.RespondWithJSON(w, http.StatusInternalServerError, \"error\", nil)\n\t\treturn\n\t}\n\n\tutils.RespondWithJSON(w, http.StatusOK, \"success\", track)\n\treturn\n}",
"func (api *AfterShipApiV4Impl) GetTrackings(params apiV4.GetTrackingsParams) (apiV4.TrackingsData, apiV4.AfterShipApiError) {\n\tvar trackingsEnvelope apiV4.TrackingsEnvelope\n\turl := apiV4.TRACKINGS_ENDPOINT\n\tqueryStringObj, err := query.Values(params)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tqueryString := queryStringObj.Encode()\n\tif queryString != \"\" {\n\t\turl += \"?\" + queryString\n\t}\n\terror := api.request(\"GET\", url, &trackingsEnvelope, nil)\n\treturn trackingsEnvelope.Data, error\n}",
"func (c *Client) GetTrack(ctx context.Context, trackPageURL string) (*Track, error) {\n\tif !strings.HasPrefix(trackPageURL, c.baseURL) {\n\t\treturn nil, fmt.Errorf(\"%s is an invalid URL: must start with %s\", trackPageURL, c.baseURL)\n\t}\n\n\tdocument, err := c.getTrackPageDocument(ctx, trackPageURL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get track page document: %w\", err)\n\t}\n\n\ttrack, err := c.parseTrack(document)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to download track: %w\", err)\n\t}\n\n\treturn track, nil\n}",
"func (a *AlbumMethods) GetInfo(artist, album string, autocorrect bool, username string, lang string) (*AlbumInfo, error) {\n\tquery := a.standardQuery(artist, album, autocorrect)\n\tquery[\"username\"] = username\n\tquery[\"lang\"] = lang\n\treturn a.getInfo(query)\n}",
"func (s Seasons) ParseTrackInfo(raw []byte) (*models.TrackInfo, error) {\n\treturn parseTrackInfo(raw)\n}",
"func (s *TrackerService) Info(trackerName string, query RequestQuery) (*TrackerInfo, *Response, error) {\n\treq, err := s.client.NewRequest(\"GET\", fmt.Sprintf(\"%s?limit=%d&page=%d\", path.Join(s.client.Project, trackerName), query.Limit, query.Page), nil)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\ttickets := new(TrackerInfo)\n\tresp, err := s.client.Do(req, tickets)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn tickets, resp, err\n}",
"func (v *VolumePublishManager) ReadTrackingInfo(\n\tctx context.Context, volumeID string,\n) (*utils.VolumeTrackingInfo, error) {\n\tfields := LogFields{\"volumeID\": volumeID}\n\tLogc(ctx).WithFields(fields).Trace(\">>>> ReadTrackingInfo\")\n\tdefer Logc(ctx).WithFields(fields).Trace(\"<<<< ReadTrackingInfo\")\n\n\treturn v.readTrackingInfo(ctx, volumeID)\n}",
"func (t *Track) Get() error {\n\n\tif err := db.Where(&t).First(&t).Error; err != nil {\n\t\tlogrus.Warn(err)\n\t\treturn err\n\t}\n\n\tlogrus.Infof(\"icii retrieved information for track #%x\", t.ID)\n\n\treturn nil\n\n}",
"func GetTracks() *[]models.Track {\n\tvar tracks []models.Track\n\tvar track models.Track\n\tvar skip string // Skip the keyp value\n\n\tdb, err := open()\n\tdefer db.Close()\n\tutil.CheckErr(\"GetTracks\", err, true)\n\n\trows, err := db.Query(\"SELECT * FROM tracks\")\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(&track.Id,\n\t\t\t&track.TrackNumber,\n\t\t\t&track.Name,\n\t\t\t&track.AlbumId,\n\t\t\t&track.ArtistId,\n\t\t\t&track.DiscNumber,\n\t\t\t&track.Genre,\n\t\t\t&skip,\n\t\t\t&track.Path)\n\t\tutil.CheckErr(\"GetTracks\", err, true)\n\t\ttracks = append(tracks, track)\n\t}\n\n\treturn &tracks\n}",
"func (api *AfterShipApiV4Impl) GetTracking(id apiV4.TrackingId, fields string, lang string) (apiV4.Tracking, apiV4.AfterShipApiError) {\n\tvar trackingEnvelope apiV4.TrackingEnvelope\n\tvar url string\n\tif id.Id != \"\" {\n\t\turl = apiV4.TRACKINGS_ENDPOINT + \"/\" + id.Id\n\t} else if id.Slug != \"\" && id.TrackingNumber != \"\" {\n\t\turl = apiV4.TRACKINGS_ENDPOINT + \"/\" + id.Slug + \"/\" + id.TrackingNumber\n\t}\n\tfieldsAdded := false\n\tif fields != \"\" {\n\t\turl += \"?fields=\" + fields\n\t\tfieldsAdded = true\n\t}\n\tif lang != \"\" {\n\t\tif fieldsAdded {\n\t\t\turl += \"&\"\n\t\t} else {\n\t\t\turl += \"?\"\n\t\t}\n\t\turl += \"lang=\" + lang\n\t}\n\terr := api.request(\"GET\", url, &trackingEnvelope, nil)\n\treturn trackingEnvelope.Data.Tracking, err\n}",
"func GetCurrentTrack() (string, error) {\n\ttrack, err := Mpc(\"current\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(track), nil\n}",
"func (obj *GenericMeasure) GetInfo(ctx context.Context) (*NxInfo, error) {\n\tresult := &struct {\n\t\tInfo *NxInfo `json:\"qInfo\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetInfo\", result)\n\treturn result.Info, err\n}",
"func GetInfo() (*Info, error) {\n\tvar result Info\n\terr := result.discover()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}",
"func (s *Client) GetUserSavedTracks(ctx context.Context, token *oauth2.Token, q *QParams) (*models.UserSavedTracks, error) {\n\tvar endpoint *url.URL = s.API.UserSavedTracksURL\n\t//in go structs containing primitive types are copied by value\n\t//https://stackoverflow.com/questions/51635766/how-do-i-copy-a-struct-in-golang\n\tlog.Println(\"SAME ADDRESS ?????\")\n\tlog.Println(&endpoint == &s.API.UserSavedTracksURL)\n\tif q != nil {\n\t\tparams := url.Values{}\n\t\tif q.Limit != nil {\n\t\t\tvar l int = *(q).Limit\n\t\t\tvalid := (l >= 1) && (l <= 50)\n\t\t\tif valid {\n\t\t\t\tparams.Set(\"limit\", strconv.Itoa(l))\n\t\t\t}\n\t\t}\n\t\tif q.Offset != nil {\n\t\t\tvar offset int = *(q).Offset\n\t\t\tif offset > 0 {\n\t\t\t\tparams.Set(\"offset\", strconv.Itoa(offset))\n\t\t\t}\n\t\t}\n\t\tif q.Market != nil {\n\t\t\tvar m string = *(q).Market\n\t\t\tif validMarketOpt(m) {\n\t\t\t\tparams.Set(\"market\", *(q).Market)\n\t\t\t}\n\t\t}\n\n\t\tendpoint.RawQuery = params.Encode()\n\t}\n\turl := endpoint.String()\n\tlog.Println(url)\n\tlog.Printf(\"User saved tracks url: %v\\n\", url)\n\n\ttracks := &models.UserSavedTracks{}\n\n\thttpClient := s.Config.Client(ctx, token)\n\tresp, err := httpClient.Get(url)\n\tif resp.StatusCode >= http.StatusBadRequest {\n\t\tlog.Println(\"status code todo:return err\")\n\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif err := json.NewDecoder(resp.Body).Decode(tracks); err != nil {\n\t\tlog.Printf(\"Could not decode body: %v\\n\", err)\n\t\treturn nil, err\n\t}\n\n\treturn tracks, nil\n\n}",
"func (obj *GenericMeasure) GetInfoRaw(ctx context.Context) (json.RawMessage, error) {\n\tresult := &struct {\n\t\tInfo json.RawMessage `json:\"qInfo\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetInfo\", result)\n\treturn result.Info, err\n}",
"func (c *Coinbene) GetPairInfo(symbol string) (PairData, error) {\n\tresp := struct {\n\t\tData PairData `json:\"data\"`\n\t}{}\n\tparams := url.Values{}\n\tparams.Set(\"symbol\", symbol)\n\tpath := common.EncodeURLValues(coinbeneAPIVersion+coinbenePairInfo, params)\n\treturn resp.Data, c.SendHTTPRequest(exchange.RestSpot, path, spotPairInfo, &resp)\n}",
"func (s *LocalStore) Info(_ context.Context, _ *storepb.InfoRequest) (*storepb.InfoResponse, error) {\n\treturn s.info, nil\n}",
"func SpotifySearchTrack(query string, limit int32) *spotify.SearchResult {\n\tresults, err := client.SearchOpt(query, spotify.SearchTypeTrack|spotify.SearchTypeArtist, &spotify.Options{Limit: createInt(limit)})\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn results\n}",
"func (a *UtilsApiService) GetFeatureTrackUsingGet(ctx context.Context, featureTrackId string) (FeatureTrack, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue FeatureTrack\n\t)\n\n\t// create path and map variables\n\ta.client = NewAPIClient(&Configuration{\n\t\tBasePath: ctx.Value(\"BasePath\").(string),\n\t\tDefaultHeader: make(map[string]string),\n\t\tUserAgent: \"Swagger-Codegen/1.0.0/go\",\n\t})\n\tlocalVarPath := a.client.cfg.BasePath + \"/nucleus/v1/feature_track/{feature_track_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"feature_track_id\"+\"}\", fmt.Sprintf(\"%v\", featureTrackId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"*/*\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode < 300 {\n\t\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v FeatureTrack\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}",
"func (m *AndroidManagedStoreApp) GetAppTracks()([]AndroidManagedStoreAppTrackable) {\n val, err := m.GetBackingStore().Get(\"appTracks\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]AndroidManagedStoreAppTrackable)\n }\n return nil\n}",
"func (e *examplePlugin) GetInfo(ctx context.Context, req *registerapi.InfoRequest) (*registerapi.PluginInfo, error) {\n\treturn ®isterapi.PluginInfo{\n\t\tType: e.pluginType,\n\t\tName: e.pluginName,\n\t\tEndpoint: e.endpoint,\n\t\tSupportedVersions: e.versions,\n\t}, nil\n}",
"func (c *LastFM) GetSimilarTracks(artist, track string) (*sources.CacheableSimilarTracks, error) {\n\tsongs, err := c.api.Track.GetSimilar(lfm.P{\"artist\": artist, \"track\": track, \"limit\": c.c.MaxTopSimTracks})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to GetSimilarTracks for %s - %s, error: %v\", artist, track, err)\n\t}\n\n\tvar st []string\n\tfor _, tracks := range songs.Tracks {\n\t\tst = append(st, fmt.Sprintf(\"%s by %s\", tracks.Name, tracks.Artist.Name))\n\t}\n\treturn &sources.CacheableSimilarTracks{SimilarTracks: st}, nil\n}",
"func (s *Server) GetLyrics(ctx context.Context, track *api.TracksInfo) (*api.LyricsInfo, error) {\n\turi, err := s.GeniusClient.GetSongURL(ctx, track.GetArtist(), track.GetName())\n\tif err != nil {\n\t\tlog.Printf(\"Error geting uri from genius.com: %s\", err)\n\t\turi = \"\"\n\t}\n\n\tlyrics, err := s.GeniusClient.GetSongLyrics(ctx, uri)\n\tif err != nil {\n\t\tlog.Printf(\"Error geting lyrics from genius.com: %s\", err)\n\t\tlyrics = \"\"\n\t}\n\n\tresult := &api.LyricsInfo{\n\t\tGeniusURI: uri,\n\t\tLyrics: lyrics,\n\t}\n\treturn result, nil\n}",
"func (b *Base) GetInfo() (*GetInfoResp, error) {\n\treturn nil, ErrFunctionNotSupported\n}",
"func (client DDMetricsClient) GetInfo() (*DDInfo, error) {\n\tinfoURL := client.endpoint\n\tinfoURL.Path = \"/info\"\n\tresp, err := client.httpClient.Get(infoURL.String())\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinfo := DDInfo{}\n\terr = json.NewDecoder(resp.Body).Decode(&info)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlogrus.Debugln(\"Received /info from Deepdetect :\", info)\n\treturn &info, nil\n}",
"func getTracks(c *gin.Context) {\n\tartists := database.GetArtists()\n\talbums := database.GetAlbums()\n\ttracks := database.GetTracks()\n\tfull := fullJson{artists, albums, tracks}\n\n c.JSON(200, full)\n}",
"func (*Spotify) GetMetadata(url string) (*Metadata, error) {\n\tif strings.HasPrefix(url, \"spotify:track:\") {\n\t\turl = \"https://open.spotify.com/track/\" + strings.TrimPrefix(url, \"spotify:track:\")\n\t}\n\n\ttrackInfo, err := botData.BotClients.Spotify.GetTrackInfo(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmetadata := &Metadata{\n\t\tTitle: trackInfo.Title,\n\t\tDisplayURL: url,\n\t\tStreamURL: trackInfo.StreamURL,\n\t\tDuration: float64(trackInfo.Duration / 1000),\n\t\tArtworkURL: trackInfo.ArtURL,\n\t\tThumbnailURL: trackInfo.ArtURL,\n\t}\n\n\tfor _, artist := range trackInfo.Artists {\n\t\ttrackArtist := &MetadataArtist{\n\t\t\tName: artist.Title,\n\t\t\tURL: \"https://open.spotify.com/artist/\" + artist.ArtistID,\n\t\t}\n\t\tmetadata.Artists = append(metadata.Artists, *trackArtist)\n\t}\n\n\treturn metadata, nil\n}",
"func (c Clients) ClientTrackingInfo(ctx context.Context) ([]string, error) {\n\treq := newRequest(\"*2\\r\\n$6\\r\\nCLIENT\\r\\n$12\\r\\nTRACKINGINFO\\r\\n$\")\n\treturn c.c.cmdStrings(ctx, req)\n}",
"func (a API) GetInfo(cmd *None) (e error) {\n\tRPCHandlers[\"getinfo\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}",
"func (search *TrackToSearch) HostSpotifySearchTrack() (*types.SingleTrack, error) {\n\tpayload := url.QueryEscape(fmt.Sprintf(\"track:%s artist:%s\", search.Title, search.Artiste))\n\tsearchURL := fmt.Sprintf(\"%s/v1/search?q=%s&type=track\", os.Getenv(\"SPOTIFY_API_BASE\"), payload)\n\toutput := &types.HostSpotifySearchTrack{}\n\ttoken, err := GetSpotifyAuthToken()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = MakeSpotifyRequest(searchURL, token.AccessToken, output)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// log.Printf(\"\\nOUTPUT HERE: %#v\\n\\n\", output.Tracks)\n\tif len(output.Tracks.Items) > 0 {\n\n\t\tif len(output.Tracks.Items[0].Artists) > 0 {\n\t\t\tbase := output.Tracks.Items[0]\n\t\t\tartistes := []string{}\n\t\t\tfor i := range output.Tracks.Items[0].Artists {\n\t\t\t\tartistes = append(artistes, output.Tracks.Items[0].Artists[i].Name)\n\t\t\t}\n\t\t\ttrack := &types.SingleTrack{\n\t\t\t\tCover: base.Album.Images[0].URL,\n\t\t\t\tDuration: base.DurationMs,\n\t\t\t\tExplicit: base.Explicit,\n\t\t\t\tID: base.ID,\n\t\t\t\tPlatform: util.HostSpotify,\n\t\t\t\tPreview: base.PreviewURL,\n\t\t\t\tReleaseDate: base.Album.ReleaseDate,\n\t\t\t\tTitle: base.Name,\n\t\t\t\tURL: base.ExternalUrls.Spotify,\n\t\t\t\tArtistes: artistes,\n\t\t\t}\n\t\t\treturn track, nil\n\t\t}\n\t}\n\treturn nil, errors.NotFound\n}",
"func TestGetTracks(t *testing.T) {\n\tfmt.Println(\"Running test TestGetTracks\")\n\n\tvar response []int\n\n\tif err := sendGetRequest(\"/api/igc\", &response, true); err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\n\tif len(response) != 2 {\n\t\tt.Fatalf(\"Expected length of track IDs array to be 2\")\n\t}\n}",
"func (sc *SoundCloud) GetTracks(url string, submitter *gumble.User) ([]interfaces.Track, error) {\n\tvar (\n\t\tapiURL string\n\t\terr error\n\t\tresp *http.Response\n\t\tv *jason.Object\n\t\ttrack bot.Track\n\t\ttracks []interfaces.Track\n\t)\n\n\turlSplit := strings.Split(url, \"#t=\")\n\n\tapiURL = \"http://api.soundcloud.com/resolve?url=%s&client_id=%s\"\n\n\tif sc.isPlaylist(url) {\n\t\t// Submitter has added a playlist!\n\t\tresp, err = http.Get(fmt.Sprintf(apiURL, urlSplit[0], viper.GetString(\"api_keys.soundcloud\")))\n\t\tdefer resp.Body.Close()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tv, err = jason.NewObjectFromReader(resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttitle, _ := v.GetString(\"title\")\n\t\tpermalink, _ := v.GetString(\"permalink_url\")\n\t\tplaylist := &bot.Playlist{\n\t\t\tID: permalink,\n\t\t\tTitle: title,\n\t\t\tSubmitter: submitter.Name,\n\t\t\tService: sc.ReadableName,\n\t\t}\n\n\t\tvar scTracks []*jason.Object\n\t\tscTracks, err = v.GetObjectArray(\"tracks\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdummyOffset, _ := time.ParseDuration(\"0s\")\n\t\tfor _, t := range scTracks {\n\t\t\ttrack, err = sc.getTrack(t, dummyOffset, submitter)\n\t\t\tif err != nil {\n\t\t\t\t// Skip this track.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttrack.Playlist = playlist\n\t\t\ttracks = append(tracks, track)\n\t\t}\n\n\t\tif len(tracks) == 0 {\n\t\t\treturn nil, errors.New(\"Invalid playlist. No tracks were added\")\n\t\t}\n\t\treturn tracks, nil\n\t}\n\n\t// Submitter has added a track!\n\n\toffset := 0\n\t// Calculate track offset if needed\n\tif len(urlSplit) == 2 {\n\t\ttimeSplit := strings.Split(urlSplit[1], \":\")\n\t\tmultiplier := 1\n\t\tfor i := len(timeSplit) - 1; i >= 0; i-- {\n\t\t\ttime, _ := strconv.Atoi(timeSplit[i])\n\t\t\toffset += time * multiplier\n\t\t\tmultiplier *= 60\n\t\t}\n\t}\n\tplaybackOffset, _ := time.ParseDuration(fmt.Sprintf(\"%ds\", offset))\n\n\tresp, err = http.Get(fmt.Sprintf(apiURL, urlSplit[0], viper.GetString(\"api_keys.soundcloud\")))\n\tdefer resp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tv, err = jason.NewObjectFromReader(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttrack, err = sc.getTrack(v, playbackOffset, submitter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttracks = append(tracks, track)\n\treturn tracks, nil\n}",
"func GetTracks(s statefulsort.StatefulSort) []*Track {\n\telements := s.Elements()\n\ttracks := make([]*Track, len(elements))\n\tfor i, e := range elements {\n\t\tt, ok := e.(*Track)\n\t\tif !ok {\n\t\t\tlog.Fatal(\"could not convert interface to *Track\")\n\t\t}\n\t\ttracks[i] = t\n\t}\n\treturn tracks\n}",
"func GetListTracks(w http.ResponseWriter, r *http.Request) {\n\tresponse := make(map[string]interface{})\n\tqueuedTracks := context.tq.list()\n\n\tresponse[\"queue\"] = queuedTracks\n\tresponse[\"now_playing\"] = map[string]interface{}{\n\t\t\"track\": context.np.current,\n\t\t\"time_remaining\": context.np.timeRemaining,\n\t}\n\n\tjresponse, _ := json.Marshal(response)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write(jresponse)\n}",
"func (obj *GenericObject) GetInfo(ctx context.Context) (*NxInfo, error) {\n\tresult := &struct {\n\t\tInfo *NxInfo `json:\"qInfo\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetInfo\", result)\n\treturn result.Info, err\n}",
"func GetTrackSettings(cmd *cobra.Command) (int, time.Duration) {\n\tmaxPollRetries, _ := cmd.Flags().GetInt(maxPollRetriesFlag)\n\tpollFrequency, _ := cmd.Flags().GetDuration(pollFrequencyFlag)\n\treturn maxPollRetries, pollFrequency\n}",
"func (c ClientFake) GetTrackers(query string) ([]Tracker, error) {\n\treturn []Tracker{{}, {}, {}, {}, {}}, nil\n}",
"func (p *Param) GetInfo() error {\n\treturn errors.New(\"Param.GetInfo() has not been implemented yet.\")\n}",
"func (obj *GenericObject) GetInfoRaw(ctx context.Context) (json.RawMessage, error) {\n\tresult := &struct {\n\t\tInfo json.RawMessage `json:\"qInfo\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetInfo\", result)\n\treturn result.Info, err\n}",
"func (ydl *youtubeDl) GetInfo() (Info, error) {\n\t// Setup command with '-J' argument\n\tcmd := exec.Command(ydl.YoutubeDlPath, \"-J\", ydl.VideoURL)\n\tstdOut, err := cmd.StdoutPipe()\n\n\tif err != nil {\n\t\treturn Info{}, err\n\t}\n\n\tif err := cmd.Start(); err != nil {\n\t\treturn Info{}, err\n\t}\n\n\tif err := json.NewDecoder(stdOut).Decode(&ydl.Info); err != nil {\n\t\treturn Info{}, err\n\t}\n\n\treturn ydl.Info, cmd.Wait()\n}",
"func (t *SpotifyDevice) PrevTrack() {\n\tif t.client == nil {\n\t\treturn\n\t}\n\tlog.Println(\"Previous track on Spotify device\")\n\tif err := t.client.PreviousOpt(t.playOpts); err != nil {\n\t\tlog.Println(err)\n\t}\n}",
"func TrackGET(w http.ResponseWriter, _ *http.Request) {\n\t// Get all tracks from the database\n\tvar all = trackDB.GetAll()\n\t// Create a bson.ObjectID slice\n\tvar ids []bson.ObjectId\n\n\t// Loop through all tracks\n\tfor _, track := range all {\n\t\t// Append the track ID to the ID-slice\n\t\tids = append(ids, track.Id)\n\t}\n\n\t// Set header content-type to JSON\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t// Encode and displays all the track-ID's\n\tjson.NewEncoder(w).Encode(ids)\n}",
"func (c *Cache) TrackingGet(key string) TrackedItem {\n\titem := c.Get(key)\n\tif item == nil {\n\t\treturn NilTracked\n\t}\n\titem.track()\n\treturn item\n}",
"func (p *ComputationPlugin) GetInfo(definition string, response *dagger.ComputationPluginInfo) error {\n\tp.mx.RLock()\n\tdefer p.mx.RUnlock()\n\tinfo, err := p.impl.GetInfo(definition)\n\t*response = info\n\treturn err\n}",
"func GetInfo(ctx context.Context, c *chrome.Conn) ([]Info, error) {\n\tinfos := make([]Info, 0)\n\terr := c.EvalPromise(ctx,\n\t\t`new Promise(function(resolve, reject) {\n\t\t\tchrome.system.display.getInfo(function(info) { resolve(info); });\n\t\t})`, &infos)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get display info\")\n\t}\n\treturn infos, nil\n}",
"func (c *Client) TrackList() ([]Track, error) {\n\tres, err := c.Exec(\"get_property\", \"track-list\")\n\tif res == nil {\n\t\treturn nil, err\n\t}\n\t//log.Errorf(\"Data %s\", string(res.Data))\n\tvar ta []Track\n\tif err = json.Unmarshal([]byte(res.Data), &ta); err != nil {\n\t\treturn nil, fmt.Errorf(\"data %s, err %v\", res.Data, err)\n\t}\n\treturn ta, nil\n}",
"func GetTrackingMethod(settingsMgr *settings.SettingsManager) v1alpha1.TrackingMethod {\n\ttm, err := settingsMgr.GetTrackingMethod()\n\tif err != nil || tm == \"\" {\n\t\treturn TrackingMethodLabel\n\t}\n\treturn v1alpha1.TrackingMethod(tm)\n}",
"func (c *Client) ListTracks() ([]*jamsonic.Track, error) {\n\tpanic(\"should not be called.\")\n}",
"func (mr *MockRepoSyncInfoKeeperMockRecorder) GetTracked(name interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetTracked\", reflect.TypeOf((*MockRepoSyncInfoKeeper)(nil).GetTracked), name)\n}",
"func GetInfo() *Info {\n\tif info == nil {\n\t\tinfo = &Info{\n\t\t\tsvcName: make(map[string]string),\n\t\t\tobjInfo: make(map[string]objInfo),\n\t\t}\n\t}\n\treturn info\n}",
"func (a API) GetPeerInfo(cmd *None) (e error) {\n\tRPCHandlers[\"getpeerinfo\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}",
"func NewTrack(distance int) Track {\n\tpanic(\"Please implement the NewTrack function\")\n}",
"func GetInfo(r io.Reader, totalSize int64) (*Metadata, error) {\n\tvar metadata Metadata\n\tvar err error\n\n\tskipReader := id3.NewSkipReader(r)\n\tmetadata.tagSize, err = skipReader.ReadThrough()\n\n\tif err != nil {\n\t\treturn &metadata, err\n\t}\n\n\t// Read MP3 frame header\n\tvar headerBits uint32\n\n\tif err = binary.Read(r, binary.BigEndian, &headerBits); err != nil {\n\t\treturn &metadata, err\n\t}\n\n\tif metadata.mp3Header, err = mp3header.Parse(headerBits); err != nil {\n\t\treturn &metadata, err\n\t}\n\n\tmetadata.calculateDuration(totalSize)\n\n\treturn &metadata, nil\n}",
"func (ah *AdminHandler) GetTrackCount(req *router.Request) {\n\ttCnt, err := ah.db.Count(mdb.TRACKS)\n\tif err != nil {\n\t\treq.SendError(&router.Error{StatusCode: http.StatusInternalServerError, Message: \"Internal database error\"})\n\t\treturn\n\t}\n\treq.SendText(strconv.FormatInt(tCnt, 10), http.StatusOK)\n}",
"func (c *Client) GetRecentTracks(user string, limit int) []RecentTrack {\n\turl := fmt.Sprintf(\"method=user.getrecenttracks&user=%v&api_key=%v&format=json&limit=%d\", user, c.Apikey, limit)\n\treqURL := c.BaseURL + url\n\tresponse, err := c.httpClient.Get(reqURL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tresponseSlice, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvar ret GetRecentTracks\n\tvar tracks []RecentTrack\n\terr = json.Unmarshal(responseSlice, &ret)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor _, track := range ret.RecentTracks.RecentTracks {\n\t\ttrack.PlayDate = track.TempDate.Uts.Time\n\t\ttracks = append(tracks, track)\n\t}\n\n\treturn tracks\n}",
"func GetInfo() string {\n\treturn fmt.Sprintf(\"version: %s, commit: %s\", Version, GitCommit)\n}",
"func GetInfo() adapter.Info {\n\treturn adapter.Info{\n\t\tName: \"svcctrl\",\n\t\tImpl: \"istio.io/istio/mixer/adapter/svcctrl\",\n\t\tDescription: \"Interface to Google Service Control\",\n\t\tSupportedTemplates: []string{\n\t\t\tmetric.TemplateName,\n\t\t},\n\t\tDefaultConfig: &config.Params{\n\t\t\tServiceName: \"library-example.sandbox.googleapis.com\",\n\t\t},\n\n\t\tNewBuilder: func() adapter.HandlerBuilder { return &builder{} },\n\t}\n}",
"func Get() Detail {\n\tif infoProvider == nil {\n\t\treturn Detail{}\n\t}\n\treturn infoProvider.Get()\n}",
"func (o *Drive) GetOpticalNumDataTracks(ctx context.Context) (opticalNumDataTracks uint32, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"OpticalNumDataTracks\").Store(&opticalNumDataTracks)\n\treturn\n}",
"func (v *VolumePublishManager) ListVolumeTrackingInfo(ctx context.Context) (map[string]*utils.VolumeTrackingInfo, error) {\n\tLogc(ctx).Debug(\">>>> ListVolumeTrackingInfo\")\n\tdefer Logc(ctx).Debug(\"<<<< ListVolumeTrackingInfo\")\n\n\t// Volumes have a 1-1 relationship with a tracking file. A tracking file may contain 1-many published paths.\n\tfiles, err := v.GetVolumeTrackingFiles()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not find volume tracking info files; %s\", err)\n\t}\n\n\tif len(files) == 0 {\n\t\tLogc(ctx).Debug(\"No tracking files found.\")\n\t\treturn nil, errors.NotFoundError(\"no tracking files found\")\n\t}\n\n\t// Discover the tracking files and their volume tracking info.\n\ttrackingFiles := make(map[string]*utils.VolumeTrackingInfo, len(files))\n\tfor _, file := range files {\n\t\tvolumeID := strings.ReplaceAll(file.Name(), \".json\", \"\")\n\t\ttrackingInfo, err := v.readTrackingInfo(ctx, volumeID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttrackingFiles[volumeID] = trackingInfo\n\t}\n\n\treturn trackingFiles, nil\n}",
"func (t *SpotifyDevice) NextTrack() {\n\tif t.client == nil {\n\t\treturn\n\t}\n\tlog.Println(\"Next track on Spotify device\")\n\tif err := t.client.NextOpt(t.playOpts); err != nil {\n\t\tlog.Println(err)\n\t}\n}",
"func (o *SmsTracking) HasTrack() bool {\n\tif o != nil && o.Track != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (c Client) Track(e *Event) (success bool, err error) {\n\te.SetToken(c.token)\n\tvalues := url.Values{}\n\tvalues.Set(\"data\", base64.StdEncoding.EncodeToString([]byte(e.JSON())))\n\treq := url.URL{\n\t\tScheme: Protocol,\n\t\tHost: Host,\n\t\tPath: TrackingPath,\n\t\tRawQuery: values.Encode(),\n\t}\n\tresp, err := http.Get(req.String())\n\tif success = err == nil; !success {\n\t\treturn\n\t}\n\tdefer func() {\n\t\terr = resp.Body.Close()\n\t}()\n\trespBody, err := ioutil.ReadAll(resp.Body)\n\tif success = err == nil; !success {\n\t\treturn\n\t}\n\tsuccess = string(respBody) == \"1\"\n\treturn\n}",
"func GetPluginInfo(plugin *examplePlugin) cache.PluginInfo {\n\treturn cache.PluginInfo{\n\t\tSocketPath: plugin.endpoint,\n\t}\n}",
"func (p MigProfileInfo) GetInfo() MigProfileInfo {\n\treturn p\n}",
"func (store *Store) getInfo(evidence types.Evidence) Info {\n\treturn store.GetInfo(evidence.Height(), evidence.Hash())\n}",
"func (obj *GenericVariable) GetInfo(ctx context.Context) (*NxInfo, error) {\n\tresult := &struct {\n\t\tInfo *NxInfo `json:\"qInfo\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetInfo\", result)\n\treturn result.Info, err\n}",
"func (obj *GenericDimension) GetInfoRaw(ctx context.Context) (json.RawMessage, error) {\n\tresult := &struct {\n\t\tInfo json.RawMessage `json:\"qInfo\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetInfo\", result)\n\treturn result.Info, err\n}",
"func (k *xyzProvider) GetPluginInfo(context.Context, *pbempty.Empty) (*pulumirpc.PluginInfo, error) {\n\treturn &pulumirpc.PluginInfo{\n\t\tVersion: k.version,\n\t}, nil\n}",
"func (b *Binance) GetInfoService() {\n\tinfo, err := b.client.NewExchangeInfoService().Do(context.Background())\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tfor k, v := range info.Symbols {\n\t\tfmt.Printf(\"%v %s %s\\n\", k, v.Symbol, v.Status)\n\t}\n}",
"func TimeTrack(start time.Time, name string) {\n\telapsed := time.Since(start)\n\tfmt.Println(name, \"took\", elapsed, \", result: \")\n\tfmt.Println()\n}",
"func (player *musicPlayer) getCurrentSongInfo() (string, error) {\n\tplayer.Lock()\n\tdefer player.Unlock()\n\tif player.state.current < len(player.state.queue) {\n\t\treturn player.state.queue[player.state.current], nil\n\t}\n\treturn \"\", errors.New(cannot_get_info_msg)\n}",
"func (obj *GenericVariable) GetInfoRaw(ctx context.Context) (json.RawMessage, error) {\n\tresult := &struct {\n\t\tInfo json.RawMessage `json:\"qInfo\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetInfo\", result)\n\treturn result.Info, err\n}",
"func (d Download) GetInfo() (*Info, error) {\n\n\treq, err := NewRequest(d.ctx, \"HEAD\", d.URL, d.Header)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif res, err := d.Client.Do(req); err == nil && res.StatusCode == http.StatusOK {\n\n\t\treturn &Info{\n\t\t\tSize: uint64(res.ContentLength),\n\t\t\tName: getNameFromHeader(res.Header.Get(\"content-disposition\")),\n\t\t\tRangeable: res.Header.Get(\"accept-ranges\") == \"bytes\",\n\t\t}, nil\n\t}\n\n\treturn &Info{}, nil\n}",
"func GetInfo(BaseURL, QueryParam, authKey string) ([]byte, error) {\n\tif authKey == \"\" {\n\t\treturn nil, errors.New(\"No Auth Header\")\n\t}\n\tNewURL := fmt.Sprintf(\"%v/%v\", BaseURL, QueryParam)\n\tmaxTime := time.Second * 10\n\tclient := &http.Client{Timeout: maxTime}\n\treq, err := http.NewRequest(\"GET\", NewURL, nil)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Unable to set request 400\")\n\t}\n\treq.Header.Set(\"X-Riot-Token\", authKey)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode >= 300 || resp.StatusCode < 200 {\n\t\treturn nil, fmt.Errorf(\"server didn’t respond 200 OK: %v\", resp.StatusCode)\n\t}\n\tBodyText, err := ioutil.ReadAll(resp.Body)\n\tdefer resp.Body.Close()\n\tif err != nil {\n\t\treturn nil, errors.New(\"Server error: 500\")\n\t}\n\treturn BodyText, nil\n\n}",
"func (o *Drive) GetOpticalNumTracks(ctx context.Context) (opticalNumTracks uint32, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"OpticalNumTracks\").Store(&opticalNumTracks)\n\treturn\n}",
"func (p Plugin) Info(ctx context.Context, module string, vsn string) ([]byte, error) {\n\tresp, err := p.c.GetInfo(ctx, &stpb.GetModuleRequest{Module: module, Version: vsn})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp.GetData(), nil\n}",
"func (o *SmsTracking) SetTrack(v string) {\n\to.Track = &v\n}",
"func TimeTrack(start time.Time, name string) {\n\tif !ShowTimeTrack {\n\t\treturn\n\t}\n\telapsed := time.Since(start)\n\tlog.Printf(\"%s took %s\", name, elapsed)\n}",
"func (s *identityServer) GetPluginInfo(ctx context.Context, r *csi.GetPluginInfoRequest) (*csi.GetPluginInfoResponse, error) {\n\tklog.V(4).Infof(\"IdentityServer.GetPluginInfo called with %+v\", r)\n\tm := map[string]string{\"url\": driverRepo}\n\treturn &csi.GetPluginInfoResponse{\n\t\tName: driverName,\n\t\tVendorVersion: s.driverVersion,\n\t\tManifest: m,\n\t}, nil\n}",
"func GetInfo() *Info {\n\treturn &Info{\n\t\tBuildID: BuildID,\n\t\tChange: Change,\n\t\tCommitMsg: CommitMsg,\n\t\tNewBuildURL: NewBuildURL,\n\t\tTag: Tag,\n\t\tOldBuildURL: OldBuildURL,\n\t\tRevision: CurrentCommit,\n\t\tVersion: Version,\n\t}\n}",
"func (c *Spotify) Get() {\n\tif sdbus == nil {\n\t\tsdbus = connDbus()\n\t}\n\n\tsong := Metadata()\n\tpstatus := Status()\n\n\t// TODO buggy spotify only sends a single artist\n\tsongData := song.Value().(map[string]dbus.Variant)\n\tc.Artist = songData[\"xesam:artist\"].Value().([]string)[0]\n\tc.Title = songData[\"xesam:title\"].Value().(string)\n\tc.Rating = int(songData[\"xesam:autoRating\"].Value().(float64) * 100)\n\tc.Status = pstatus.Value().(string)\n\tc.Url = songData[\"xesam:url\"].Value().(string)\n\tc.ArtUrl = songData[\"mpris:artUrl\"].Value().(string)\n\n\tidx := strings.LastIndex(c.ArtUrl, \"/\")\n\tc.ArtFile = c.ArtUrl[idx+1:]\n}",
"func (c *Client) GetInfo(dir, name string) ([]byte, error) {\n\tvar info *InfoResponse\n\tvar bytes []byte\n\n\t// Main URL Components\n\tu := &url.URL{\n\t\tScheme: \"https\",\n\t\tHost: \"api.wordpress.org\",\n\t\tPath: fmt.Sprintf(\"%s/info/1.1/\", dir),\n\t}\n\n\t// Prepare Query Values\n\t// TODO: Add ability to overwrite default fields?\n\tvalues := []string{\n\t\tfmt.Sprintf(\"action=%s_information\", dir[:len(dir)-1]),\n\t\t\"request[slug]=\" + name,\n\t}\n\tvalues = append(values, defaultFields...)\n\n\t// Add Query Params to URL and return it as a string\n\tu.RawQuery = strings.Join(values, \"&\")\n\tURL := u.String()\n\n\t// Make the Request\n\tresp, err := c.getRequest(URL)\n\tif err != nil {\n\t\treturn bytes, err\n\t}\n\n\tdefer drainAndClose(resp.Body, &err)\n\n\tbytes, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn bytes, err\n\t}\n\n\tif string(bytes) == \"false\" {\n\t\treturn nil, errors.New(\"No data returned\")\n\t}\n\n\terr = json.Unmarshal(bytes, &info)\n\tif err != nil {\n\t\treturn bytes, err\n\t}\n\n\tbytes, err = json.Marshal(info)\n\tif err != nil {\n\t\treturn bytes, err\n\t}\n\n\treturn bytes, err\n}",
"func (c *MqClient) QueryTracker() (*proto.TrackerInfo, error) {\n\treq := NewMessage()\n\treq.SetCmd(proto.Tracker)\n\n\tinfo := &proto.TrackerInfo{}\n\terr := c.invokeCmd(req, info)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn info, err\n}",
"func (_TokensNetwork *TokensNetworkCaller) GetChannelParticipantInfo(opts *bind.CallOpts, token common.Address, participant common.Address, partner common.Address) (*big.Int, [24]byte, uint64, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t\tret1 = new([24]byte)\n\t\tret2 = new(uint64)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t}\n\terr := _TokensNetwork.contract.Call(opts, out, \"getChannelParticipantInfo\", token, participant, partner)\n\treturn *ret0, *ret1, *ret2, err\n}",
"func (m *Master) GetInfo(procSign string, out *InfoRsp) error {\n\tif err := m.updatePidInfo(procSign); err != nil {\n\t\treturn err\n\t}\n\tinfo := m.pidInfo[procSign]\n\n\t*out = InfoRsp{\n\t\tProcSign: procSign,\n\t\tPid: info.Pid,\n\t\tElapsed: info.Elapsed,\n\t\tStatus: info.Status,\n\t\tCPU: info.CPU,\n\t\tMemory: info.Memory,\n\t}\n\treturn nil\n}",
"func (n *Node) GetPeerInfo(ctx context.Context, req *api.PeerRequest) (*api.PeerInfo, error) {\n\tif err := checkSource(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// food for discovery\n\thost := api.GrpcPeerHost(ctx)\n\tn.CheckPeerIsKnown(host, nil)\n\n\tvar id hash.Peer\n\n\tif req.PeerID == \"\" {\n\t\tid = n.ID\n\t} else {\n\t\tid = hash.HexToPeer(req.PeerID)\n\t}\n\n\tif id == n.ID { // self\n\t\tinfo := n.AsPeer()\n\t\treturn info.ToWire(), nil\n\t}\n\n\tinfo := n.store.GetWirePeer(id)\n\tif info == nil {\n\t\treturn nil, status.Error(codes.NotFound, fmt.Sprintf(\"peer not found: %s\", req.PeerID))\n\t}\n\n\treturn info, nil\n}",
"func (frame *AvFrame) GetInfo() (width int, height int, linesize [8]int32, data [8]*uint8) {\n\twidth = int(frame.linesize[0])\n\theight = int(frame.height)\n\tfor i := range linesize {\n\t\tlinesize[i] = int32(frame.linesize[i])\n\t}\n\tfor i := range data {\n\t\tdata[i] = (*uint8)(frame.data[i])\n\t}\n\t// log.Println(\"Linesize is \", frame.linesize, \"Data is\", data)\n\treturn\n}",
"func (e *Event) Track() string {\n\treturn e.track\n}"
] | [
"0.63399136",
"0.6201334",
"0.6110165",
"0.60943365",
"0.6016428",
"0.59254855",
"0.5920174",
"0.5907783",
"0.581144",
"0.57925",
"0.57899785",
"0.57562315",
"0.5729202",
"0.56931305",
"0.5597965",
"0.5583422",
"0.5577962",
"0.5558856",
"0.5544902",
"0.5423817",
"0.5410241",
"0.5400862",
"0.5395594",
"0.53585106",
"0.5355852",
"0.5325607",
"0.5316097",
"0.5293084",
"0.52808934",
"0.52661616",
"0.52520514",
"0.52330625",
"0.5208954",
"0.5194605",
"0.5179673",
"0.51698226",
"0.5137632",
"0.5137402",
"0.5128125",
"0.5119719",
"0.51052326",
"0.51000714",
"0.50797987",
"0.5065678",
"0.5060219",
"0.50523806",
"0.50478107",
"0.5045251",
"0.5031901",
"0.5025854",
"0.5024628",
"0.50227326",
"0.5004523",
"0.49627638",
"0.49403873",
"0.49210617",
"0.49185428",
"0.48990783",
"0.4870811",
"0.48696023",
"0.48695317",
"0.48695314",
"0.4841275",
"0.48354143",
"0.48303726",
"0.48199716",
"0.48191357",
"0.47942063",
"0.4787248",
"0.47854242",
"0.4780789",
"0.47777835",
"0.47765595",
"0.47714436",
"0.4760031",
"0.47335464",
"0.4731236",
"0.47251916",
"0.4720452",
"0.4717823",
"0.47159207",
"0.4708021",
"0.47000468",
"0.4695607",
"0.46822292",
"0.46728337",
"0.46667886",
"0.46636912",
"0.4656166",
"0.46340093",
"0.46304482",
"0.46254048",
"0.46157196",
"0.46156508",
"0.4608157",
"0.46021497",
"0.46002576",
"0.45984825",
"0.4597019",
"0.45881742"
] | 0.8091644 | 0 |
GetStream returns a ReadCloser stream of the track. The audio is encoded as a MP3. | func (c *Client) GetStream(songID string) (io.ReadCloser, error) {
url := c.makeRequestURL("stream") + "&format=mp3&id=" + songID
resp, err := http.Get(url)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, errors.New(resp.Status)
}
return resp.Body, nil
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (sc *SoundCloud) Stream(track string) (io.ReadCloser, error) {\n\t// Get the HTTP Stream\n\trsp, err := http.Get(sc.streamUrl(track).String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Createa http stream buffer\n\tbuff := buffer.HTTPBuffer(rsp)\n\tgo buff.Buffer() // Start buffering\n\tscs := &SoundCloudStream{\n\t\tbuffer: buff,\n\t\tdecoder: &mpa.Reader{Decoder: &mpa.Decoder{Input: buff}},\n\t}\n\treturn scs, nil\n}",
"func GetStream(w http.ResponseWriter, r *http.Request) {\n\t// Retrieve render\n\tren := context.Get(r, CtxRender).(*render.Render)\n\n\t// Advertise that clients may send Range requests\n\tw.Header().Set(\"Accept-Ranges\", \"bytes\")\n\n\t// Check API version\n\tif version, ok := mux.Vars(r)[\"version\"]; ok {\n\t\t// Check if this API call is supported in the advertised version\n\t\tif !apiVersionSet.Has(version) {\n\t\t\tren.JSON(w, 400, errRes(400, \"unsupported API version: \"+version))\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Check for an ID parameter\n\tpID, ok := mux.Vars(r)[\"id\"]\n\tif !ok {\n\t\tren.JSON(w, 400, errRes(400, \"no integer stream ID provided\"))\n\t\treturn\n\t}\n\n\t// Verify valid integer ID\n\tid, err := strconv.Atoi(pID)\n\tif err != nil {\n\t\tren.JSON(w, 400, errRes(400, \"invalid integer stream ID\"))\n\t\treturn\n\t}\n\n\t// Attempt to load the song with matching ID\n\tsong := &data.Song{ID: id}\n\tif err := song.Load(); err != nil {\n\t\t// Check for invalid ID\n\t\tif err == sql.ErrNoRows {\n\t\t\tren.JSON(w, 404, errRes(404, \"song ID not found\"))\n\t\t\treturn\n\t\t}\n\n\t\t// All other errors\n\t\tlog.Println(err)\n\t\tren.JSON(w, 500, serverErr)\n\t\treturn\n\t}\n\n\t// Attempt to access data stream\n\tstream, err := song.Stream()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tren.JSON(w, 500, serverErr)\n\t\treturn\n\t}\n\n\t// Generate a string used for logging this operation\n\topStr := fmt.Sprintf(\"[#%05d] %s - %s [%s %dkbps]\", song.ID, song.Artist, song.Title,\n\t\tdata.CodecMap[song.FileTypeID], song.Bitrate)\n\n\t// Attempt to send file stream over HTTP\n\tlog.Println(\"stream: starting:\", opStr)\n\n\t// Pass stream using song's file size, auto-detect MIME type\n\tif err := HTTPStream(song, \"\", song.FileSize, stream, r, w); err != nil {\n\t\t// Check for client reset\n\t\tif strings.Contains(err.Error(), \"connection reset by peer\") || strings.Contains(err.Error(), \"broken pipe\") {\n\t\t\treturn\n\t\t}\n\n\t\t// Check for invalid range, return HTTP 416\n\t\tif err == ErrInvalidRange {\n\t\t\tren.JSON(w, 416, errRes(416, \"invalid HTTP Range header boundaries\"))\n\t\t\treturn\n\t\t}\n\n\t\tlog.Println(\"stream: error:\", err)\n\t\treturn\n\t}\n\n\tlog.Println(\"stream: completed:\", opStr)\n\treturn\n}",
"func (s Song) Stream() (io.ReadSeeker, error) {\n\t// Attempt to open the file associated with this song\n\treturn os.Open(s.FileName)\n}",
"func (c *Client) Stream(t *soundcloud.Track) (*StreamOutput, error) {\n\tvar (\n\t\terr error\n\t\tresp *http.Response\n\t\treq *http.Request\n\t\tout StreamOutput\n\t)\n\n\tif req, err = sling.New().\n\t\tGet(fmt.Sprintf(\"https://api.soundcloud.com/tracks/%d/streams\", t.Id)).\n\t\tQueryStruct(StreamParam{ClientID: c.clientID}).\n\t\tRequest(); err != nil {\n\t\treturn nil, fmt.Errorf(\"create query: %w\", err)\n\t}\n\n\tif resp, err = c.hc.Do(req); err != nil {\n\t\treturn nil, fmt.Errorf(\"execute query: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\to, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"read body: %w\", err)\n\t}\n\n\tif err = json.Unmarshal(o, &out); err != nil {\n\t\treturn nil, fmt.Errorf(\"decode body: %w\", err)\n\t}\n\n\treturn &out, nil\n}",
"func (c *webTransportClosedClient) GetStream() rpcc.Stream { return c.Stream }",
"func (o *AudioStreamPlayer) GetStream() AudioStreamImplementer {\n\t//log.Println(\"Calling AudioStreamPlayer.GetStream()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"AudioStreamPlayer\", \"get_stream\")\n\n\t// Call the parent method.\n\t// AudioStream\n\tretPtr := gdnative.NewEmptyObject()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := newAudioStreamFromPointer(retPtr)\n\n\t// Check to see if we already have an instance of this object in our Go instance registry.\n\tif instance, ok := InstanceRegistry.Get(ret.GetBaseObject().ID()); ok {\n\t\treturn instance.(AudioStreamImplementer)\n\t}\n\n\t// Check to see what kind of class this is and create it. This is generally used with\n\t// GetNode().\n\tclassName := ret.GetClass()\n\tif className != \"AudioStream\" {\n\t\tactualRet := getActualClass(className, ret.GetBaseObject())\n\t\treturn actualRet.(AudioStreamImplementer)\n\t}\n\n\treturn &ret\n}",
"func (c *DiskCache) GetStream(ctx context.Context, repo *gitalypb.Repository, req proto.Message) (_ io.ReadCloser, err error) {\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tc.missTotals.Inc()\n\t\t}\n\t}()\n\n\tc.requestTotals.Inc()\n\n\trespPath, err := c.KeyPath(ctx, repo, req)\n\tswitch {\n\tcase os.IsNotExist(err):\n\t\treturn nil, ErrReqNotFound\n\tcase err == nil:\n\t\tbreak\n\tdefault:\n\t\treturn nil, err\n\t}\n\n\tctxlogrus.Extract(ctx).\n\t\tWithField(\"stream_path\", respPath).\n\t\tInfo(\"getting stream\")\n\n\trespF, err := os.Open(respPath)\n\tswitch {\n\tcase os.IsNotExist(err):\n\t\treturn nil, ErrReqNotFound\n\tcase err == nil:\n\t\tbreak\n\tdefault:\n\t\treturn nil, err\n\t}\n\n\treturn instrumentedReadCloser{\n\t\tReadCloser: respF,\n\t\tcounter: c.bytesFetchedtotals,\n\t}, nil\n}",
"func GetStreamURL(songID string) (stream string, err error) {\n\turl := fmt.Sprintf(\"https://api.soundcloud.com/tracks/%s/stream?client_id=%s\", songID, scClientID)\n\tfmt.Println(url)\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tresponse, err := http.DefaultTransport.RoundTrip(req)\n\tdefer response.Body.Close()\n\n\tvar r streamURLResponse\n\n\tresp, err := ioutil.ReadAll(response.Body)\n\tfmt.Println(string(resp))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tif err = json.Unmarshal(resp, &r); err != nil {\n\t\tfmt.Println(\"cannot unmarshal json: \" + err.Error())\n\t\treturn\n\t}\n\tstream = r.location\n\treturn\n}",
"func (c *webSocketClosedClient) GetStream() rpcc.Stream { return c.Stream }",
"func (f FFmpeg) Stream() (io.ReadCloser, error) {\n\t// Verify ffmpeg is running\n\tif !f.started {\n\t\treturn nil, ErrFFmpegNotStarted\n\t}\n\n\t// Return stream\n\treturn f.stream, nil\n}",
"func (c *webTransportConnectionEstablishedClient) GetStream() rpcc.Stream { return c.Stream }",
"func (c *webTransportCreatedClient) GetStream() rpcc.Stream { return c.Stream }",
"func (c *dataReceivedClient) GetStream() rpcc.Stream { return c.Stream }",
"func (c *loadingFinishedClient) GetStream() rpcc.Stream { return c.Stream }",
"func Open(url string) (*Stream, error) {\n\tlog.Print(\"[INFO] Opening \", url)\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Add(\"accept\", \"*/*\")\n\treq.Header.Add(\"user-agent\", \"iTunes/12.9.2 (Macintosh; OS X 10.14.3) AppleWebKit/606.4.5\")\n\treq.Header.Add(\"icy-metadata\", \"1\")\n\n\t// Timeout for establishing the connection.\n\t// We don't want for the stream to timeout while we're reading it, but\n\t// we do want a timeout for establishing the connection to the server.\n\tdialer := &net.Dialer{Timeout: 5 * time.Second}\n\ttransport := &http.Transport{Dial: dialer.Dial}\n\tclient := &http.Client{Transport: transport}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor k, v := range resp.Header {\n\t\tlog.Print(\"[DEBUG] HTTP header \", k, \": \", v[0])\n\t}\n\n\tbitrate, err := strconv.Atoi(resp.Header.Get(\"icy-br\"))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot parse bitrate: %v\", err)\n\t}\n\n\tmetaint, err := strconv.Atoi(resp.Header.Get(\"icy-metaint\"))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot parse metaint: %v\", err)\n\t}\n\n\ts := &Stream{\n\t\tName: resp.Header.Get(\"icy-name\"),\n\t\tGenre: resp.Header.Get(\"icy-genre\"),\n\t\tDescription: resp.Header.Get(\"icy-description\"),\n\t\tURL: resp.Header.Get(\"icy-url\"),\n\t\tBitrate: bitrate,\n\t\tmetaint: metaint,\n\t\tmetadata: nil,\n\t\tpos: 0,\n\t\trc: resp.Body,\n\t}\n\n\treturn s, nil\n}",
"func NewStream(filename string) (io.ReadCloser, error) {\n\tparts, err := url.Parse(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif parts.Scheme == \"s3\" {\n\t\treturn client.GetS3Obj(parts.Host, parts.Path)\n\t}\n\treturn os.Open(filename)\n}",
"func (msh *MockStreamHandler) GetStream(string, bool) (network.Stream, error) {\n\treturn nil, nil\n}",
"func (fs *Ipfs) GetStream(path string) (io.ReadCloser, error) {\n\tp := ipath.New(path)\n\tunixfs := fs.coreAPI.Unixfs()\n\tnode, err := unixfs.Get(context.Background(), p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// node should be files.File\n\tfile, ok := node.(files.File)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"path is not a file: '%s'\", path)\n\t}\n\n\treturn file, nil\n}",
"func (c *requestInterceptedClient) GetStream() rpcc.Stream { return c.Stream }",
"func (c *responseReceivedClient) GetStream() rpcc.Stream { return c.Stream }",
"func GetStream(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *StreamState, opts ...pulumi.ResourceOption) (*Stream, error) {\n\tvar resource Stream\n\terr := ctx.ReadResource(\"aws-native:kinesis:Stream\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func (c *subresourceWebBundleMetadataReceivedClient) GetStream() rpcc.Stream { return c.Stream }",
"func (c *trustTokenOperationDoneClient) GetStream() rpcc.Stream { return c.Stream }",
"func (ssec *SSEClient) GetStream(uri string) error {\n\tssec.Lock()\n\tdefer ssec.Unlock()\n\tvar err error\n\tif ssec.url, err = url.Parse(uri); err != nil {\n\t\treturn errors.Wrap(err, \"error parsing URL\")\n\t}\n\tssec.wg.Add(1)\n\tgo ssec.process()\n\treturn err\n}",
"func (c *requestServedFromCacheClient) GetStream() rpcc.Stream { return c.Stream }",
"func (c *webSocketCreatedClient) GetStream() rpcc.Stream { return c.Stream }",
"func (c *INDIClient) GetBlobStream(deviceName, propName, blobName string) (rdr io.ReadCloser, id string, err error) {\n\tdevice, err := c.findDevice(deviceName)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tprop, ok := device.BlobProperties[propName]\n\tif !ok {\n\t\terr = ErrPropertyNotFound\n\t\treturn\n\t}\n\n\t_, ok = prop.Values[blobName]\n\tif !ok {\n\t\terr = ErrPropertyValueNotFound\n\t\treturn\n\t}\n\n\tguid := uuid.New()\n\tid = guid.String()\n\n\tkey := fmt.Sprintf(\"%s_%s_%s\", deviceName, propName, blobName)\n\n\tr, w := io.Pipe()\n\n\trdr = r\n\n\twriters := map[string]io.Writer{}\n\n\tif ws, ok := c.blobStreams.Load(key); ok {\n\t\twriters = ws.(map[string]io.Writer)\n\t}\n\n\twriters[id] = w\n\n\tc.blobStreams.Store(key, writers)\n\n\treturn\n}",
"func (p *StreamPublisher) GetStream(name string) (chan Streamable, error) {\n\tstream, ok := p.Streams[name]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"stream '%s' not available\", name)\n\t}\n\n\treturn stream, nil\n}",
"func (c *signedExchangeReceivedClient) GetStream() rpcc.Stream { return c.Stream }",
"func (s StreamService) GetStream(channelID int64, streamType model.StreamType, r *core.Request) model.Stream {\n\tstream := struct {\n\t\tstream model.Stream\n\t}{}\n\tr.SendRequest(fmt.Sprintf(\"%s/%d\", core.StreamsURI, channelID), stream)\n\n\treturn stream.stream\n}",
"func (twitchAPI *TwitchAPI) GetStream(channelName string, onSuccess func(Stream),\n\tonHTTPError jsonapi.HTTPErrorCallback, onInternalError jsonapi.InternalErrorCallback) {\n\tvar streamsChannel streamsChannel\n\tonSuccessfulRequest := func() {\n\t\tonSuccess(streamsChannel.Stream)\n\t}\n\ttwitchAPI.Get(\"/streams/\"+channelName, nil, &streamsChannel, onSuccessfulRequest,\n\t\tonHTTPError, onInternalError)\n}",
"func (c *loadingFailedClient) GetStream() rpcc.Stream { return c.Stream }",
"func (c *requestWillBeSentClient) GetStream() rpcc.Stream { return c.Stream }",
"func GetStream(aggregateType, aggregateID string) string {\n\treturn fmt.Sprintf(\"%s!%s\", aggregateType, aggregateID)\n}",
"func (handle *Handle) GetStream() (Stream, error) {\n\tvar s Stream\n\tvar some *C.cudaStream_t\n\t//x := C.cudnnHandle_t(handle.Pointer())\n\n\ty := C.cudnnGetStream(handle.x, some)\n\ts.stream = *some\n\treturn s, Status(y).error(\"(*Handle).GetStream\")\n}",
"func (o *AudioStreamPlayer) GetStreamPlayback() AudioStreamPlaybackImplementer {\n\t//log.Println(\"Calling AudioStreamPlayer.GetStreamPlayback()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"AudioStreamPlayer\", \"get_stream_playback\")\n\n\t// Call the parent method.\n\t// AudioStreamPlayback\n\tretPtr := gdnative.NewEmptyObject()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := newAudioStreamPlaybackFromPointer(retPtr)\n\n\t// Check to see if we already have an instance of this object in our Go instance registry.\n\tif instance, ok := InstanceRegistry.Get(ret.GetBaseObject().ID()); ok {\n\t\treturn instance.(AudioStreamPlaybackImplementer)\n\t}\n\n\t// Check to see what kind of class this is and create it. This is generally used with\n\t// GetNode().\n\tclassName := ret.GetClass()\n\tif className != \"AudioStreamPlayback\" {\n\t\tactualRet := getActualClass(className, ret.GetBaseObject())\n\t\treturn actualRet.(AudioStreamPlaybackImplementer)\n\t}\n\n\treturn &ret\n}",
"func (s *S3) GetReadCloser(chunk storage.Chunk) (io.ReadCloser, error) {\n\tresult, err := s.Client.GetObject(&s3.GetObjectInput{\n\t\tRange: aws.String(\"bytes=\" + strconv.FormatUint(chunk.ObjectOffset, 10) + \"-\" + strconv.FormatUint(chunk.ObjectOffset+chunk.Size-1, 10)),\n\t\tBucket: aws.String(s.Bucket),\n\t\tKey: aws.String(chunk.Key),\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result.Body, nil\n}",
"func (c *subresourceWebBundleMetadataErrorClient) GetStream() rpcc.Stream { return c.Stream }",
"func (c *responseReceivedExtraInfoClient) GetStream() rpcc.Stream { return c.Stream }",
"func (c *webSocketHandshakeResponseReceivedClient) GetStream() rpcc.Stream { return c.Stream }",
"func (c *webSocketFrameErrorClient) GetStream() rpcc.Stream { return c.Stream }",
"func GetSTTFromStream(c *config.Config, audio io.Reader) (*STTResponse, error) {\n\tparams := &backend.CallParams{\n\t\tCredentials: c.GetCredentials(),\n\t\tMethod: \"POST\",\n\t\tPath: sttEndpoint,\n\t\tBody: audio,\n\t}\n\n\tres, err := c.Backend.Call(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer res.Body.Close()\n\tvar stt STTResponse\n\tjson.NewDecoder(res.Body).Decode(&stt)\n\treturn &stt, nil\n}",
"func (c *reportingAPIReportAddedClient) GetStream() rpcc.Stream { return c.Stream }",
"func (c *webSocketFrameSentClient) GetStream() rpcc.Stream { return c.Stream }",
"func (s *Session) OpenReadStream(sType SessionType, fo FilterOptions) (ReadStream, error) {\n\tswitch sType {\n\tcase SessionReadCapture:\n\t\ts.wp.Add()\n\t\tparStream := newSessionStream(s, s.dbo, s.schema, s.wp)\n\t\trs, err := newReadCapStream(parStream, s.cancel, fo)\n\t\tif err != nil {\n\t\t\ts.wp.Done()\n\t\t}\n\t\treturn rs, nil\n\tcase SessionReadPrefix:\n\t\ts.wp.Add()\n\t\tparStream := newSessionStream(s, s.dbo, s.schema, s.wp)\n\t\trs, err := newReadPrefixStream(parStream, s.cancel, fo)\n\t\tif err != nil {\n\t\t\ts.wp.Done()\n\t\t}\n\t\treturn rs, nil\n\tcase SessionReadEntity:\n\t\ts.wp.Add()\n\t\tparStream := newSessionStream(s, s.dbo, s.schema, s.wp)\n\t\tes, err := newReadEntityStream(parStream, s.cancel, fo)\n\t\tif err != nil {\n\t\t\ts.wp.Done()\n\t\t}\n\t\treturn es, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported read stream type\")\n\t}\n}",
"func (d *driver) ReadStream(ctx context.Context, path string, offset int64) (io.ReadCloser, error) {\n\tdefer debugTime()()\n\treader, err := d.shell.Cat(d.fullPath(path))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = io.CopyN(ioutil.Discard, reader, offset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ioutil.NopCloser(reader), nil\n}",
"func (c *resourceChangedPriorityClient) GetStream() rpcc.Stream { return c.Stream }",
"func (s Storage) Get(path string) (io.ReadCloser, error) {\n\tloc, err := s.fullPath(path)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn os.Open(loc)\n}",
"func (c *eventSourceMessageReceivedClient) GetStream() rpcc.Stream { return c.Stream }",
"func (c *webSocketWillSendHandshakeRequestClient) GetStream() rpcc.Stream { return c.Stream }",
"func (m *Metadata) GetStream(name string) *StreamInfo {\n\treturn m.streams[name]\n}",
"func (c *subresourceWebBundleInnerResponseParsedClient) GetStream() rpcc.Stream { return c.Stream }",
"func (s *S3Storage) Get(path string) (io.ReadCloser, error) {\n\tpath = s.addPrefix(path)\n\tresp, err := s.bucket.GetResponse(path)\n\tif resp == nil || err != nil {\n\t\tif err.Error() == \"The specified key does not exist.\" {\n\t\t\terr = strata.ErrNotFound(path)\n\t\t}\n\t\treturn nil, err\n\t}\n\tetag, found := resp.Header[\"Etag\"]\n\tif !found {\n\t\treturn nil, errors.New(\"No Etag header\")\n\t}\n\tif len(etag) == 0 {\n\t\treturn nil, errors.New(\"Etag header is empty\")\n\t}\n\t// Note: s3test does not require the trimming, but real S3 does\n\tchecksum, err := hex.DecodeString(strings.TrimSuffix(strings.TrimPrefix(etag[0], \"\\\"\"), \"\\\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn strata.NewChecksummingReader(resp.Body, checksum), nil\n}",
"func (me *Server) GetStream(appName string, instName string, name string) *Stream {\n\tme.mtx.RLock()\n\tdefer me.mtx.RUnlock()\n\n\tapp, ok := me.applications[appName]\n\tif !ok {\n\t\tapp = new(Application).Init(appName, me.logger, me.factory)\n\t\tme.applications[appName] = app\n\t}\n\n\treturn app.GetStream(instName, name)\n}",
"func (s *KSession) GetTrack(id int64) (results Track, err error) {\n\tresults = Track{}\n\tres, err := s.request(\"GET\", EndpointLyricsTrack(id), nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(res, &results)\n\treturn\n}",
"func (f *FFS) Get(ctx context.Context, c cid.Cid) (io.Reader, error) {\n\tstream, err := f.client.Get(ctx, &rpc.GetRequest{\n\t\tCid: util.CidToString(c),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treader, writer := io.Pipe()\n\tgo func() {\n\t\tfor {\n\t\t\treply, err := stream.Recv()\n\t\t\tif err == io.EOF {\n\t\t\t\t_ = writer.Close()\n\t\t\t\tbreak\n\t\t\t} else if err != nil {\n\t\t\t\t_ = writer.CloseWithError(err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t_, err = writer.Write(reply.GetChunk())\n\t\t\tif err != nil {\n\t\t\t\t_ = writer.CloseWithError(err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn reader, nil\n}",
"func (c *reportingAPIReportUpdatedClient) GetStream() rpcc.Stream { return c.Stream }",
"func (r *OperationReader) ReadStream(\n\ton templater.OnDataStream,\n\tstopCh <-chan struct{},\n) error {\n\treturn nil\n}",
"func (c *webSocketFrameReceivedClient) GetStream() rpcc.Stream { return c.Stream }",
"func (c *Client) RenterStreamGet(siaPath string) (resp []byte, err error) {\n\tsiaPath = strings.TrimPrefix(siaPath, \"/\")\n\tresp, err = c.getRawResponse(\"/renter/stream/\" + siaPath)\n\treturn\n}",
"func (c *Client) GetServiceStream(ctx context.Context, id int, decode bool) (io.ReadCloser, *http.Response, error) {\n\tu := fmt.Sprintf(\"services/%d/stream\", id)\n\n\treturn c.getTS(ctx, u, decode)\n}",
"func (s Store) Get(prefix, bucketname, filename string) (io.ReadCloser, error) {\n\tobjOut, err := s.api.HeadObject(&s3.HeadObjectInput{\n\t\tBucket: aws.String(bucketname),\n\t\tKey: aws.String(prefix + filename),\n\t})\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Could not get metadata for object %s\", filename)\n\t}\n\n\tlength := *objOut.ContentLength\n\tpr, pw := io.Pipe()\n\tgo func() {\n\t\tdefer pw.Close() // nolint: errcheck, gosec\n\n\t\tvar (\n\t\t\ti, start, remainder int64\n\t\t\trangeSpecifier string\n\t\t)\n\n\t\tfor i = 0; i < length/readBlockSize; i++ {\n\t\t\tstart = i * readBlockSize\n\t\t\trangeSpecifier = fmt.Sprintf(\"bytes=%d-%d\", start, start+readBlockSize-1)\n\t\t\tdata, err := s.getDataInRange(prefix, bucketname, filename, rangeSpecifier)\n\t\t\tif err != nil {\n\t\t\t\tpw.CloseWithError(errors.Wrap(err, \"Could not get data\")) // nolint: errcheck, gosec\n\t\t\t}\n\t\t\t_, err = pw.Write(data)\n\t\t\tif err != nil {\n\t\t\t\tpw.CloseWithError(errors.Wrap(err, \"Could not write data\")) // nolint: errcheck, gosec\n\t\t\t}\n\n\t\t}\n\t\tremainder = length % readBlockSize\n\t\tif remainder > 0 {\n\t\t\tstart = (length / readBlockSize) * readBlockSize\n\t\t\trangeSpecifier = fmt.Sprintf(\"bytes=%d-%d\", start, start+remainder-1)\n\t\t\tdata, err := s.getDataInRange(prefix, bucketname, filename, rangeSpecifier)\n\t\t\tif err != nil {\n\t\t\t\tpw.CloseWithError(errors.Wrap(err, \"Could not get data\")) // nolint: errcheck, gosec\n\t\t\t}\n\t\t\t_, err = pw.Write(data)\n\t\t\tif err != nil {\n\t\t\t\tpw.CloseWithError(errors.Wrap(err, \"Could not get data\")) // nolint: errcheck, gosec\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn pr, nil\n}",
"func Decode(r io.ReadSeeker) (audio.Decoded, error) {\n\tb := bufiox.NewReader(r)\n\tdec, err := mp3.NewDecoder(b)\n\treturn &decoded{Decoder: *dec}, err\n}",
"func NewStream(\n\tURI string,\n\tstoringDirectory string,\n\tkeepFiles bool,\n\taudio bool,\n\tloggingOpts ProcessLoggingOpts,\n\twaitTimeOut time.Duration,\n) (*Stream, string) {\n\tid := uuid.New().String()\n\tpath := fmt.Sprintf(\"%s/%s\", storingDirectory, id)\n\terr := os.MkdirAll(path, os.ModePerm)\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t\treturn nil, \"\"\n\t}\n\tprocess := NewProcess(keepFiles, audio)\n\tcmd := process.Spawn(path, URI)\n\n\t// Create nil pointer in case logging is not enabled\n\tcmdLogger := (*lumberjack.Logger)(nil)\n\t// Create logger otherwise\n\tif loggingOpts.Enabled {\n\t\tcmdLogger = &lumberjack.Logger{\n\t\t\tFilename: fmt.Sprintf(\"%s/%s.log\", loggingOpts.Directory, id),\n\t\t\tMaxSize: loggingOpts.MaxSize,\n\t\t\tMaxBackups: loggingOpts.MaxBackups,\n\t\t\tMaxAge: loggingOpts.MaxAge,\n\t\t\tCompress: loggingOpts.Compress,\n\t\t}\n\t\tcmd.Stderr = cmdLogger\n\t\tcmd.Stdout = cmdLogger\n\t}\n\tstream := Stream{\n\t\tID: id,\n\t\tCMD: cmd,\n\t\tProcess: process,\n\t\tMux: &sync.Mutex{},\n\t\tPath: fmt.Sprintf(\"/%s/index.m3u8\", filepath.Join(\"stream\", id)),\n\t\tStorePath: path,\n\t\tStreak: hotstreak.New(hotstreak.Config{\n\t\t\tLimit: 10,\n\t\t\tHotWait: time.Minute * 2,\n\t\t\tActiveWait: time.Minute * 4,\n\t\t}).Activate(),\n\t\tOriginalURI: URI,\n\t\tKeepFiles: keepFiles,\n\t\tLoggingOpts: &loggingOpts,\n\t\tLogger: cmdLogger,\n\t\tRunning: false,\n\t\tWaitTimeOut: waitTimeOut,\n\t}\n\tlogrus.Debugf(\"%s store path created | Stream\", stream.StorePath)\n\treturn &stream, id\n}",
"func (v Vehicle) Stream() (chan *StreamEvent, chan error, error) {\n\turl := StreamURL + \"/stream/\" + strconv.Itoa(v.VehicleID) + \"/?values=\" + StreamParams\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\treq.SetBasicAuth(ActiveClient.Auth.Email, v.Tokens[0])\n\tresp, err := ActiveClient.HTTP.Do(req)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\teventChan := make(chan *StreamEvent)\n\terrChan := make(chan error)\n\tgo readStream(resp, eventChan, errChan)\n\n\treturn eventChan, errChan, nil\n}",
"func (c *Connection) GetStream(id uint32) *Stream {\n\tiid := int(id)\n\n\tif iid >= len(c.streams) {\n\t\treturn nil\n\t}\n\n\treturn &c.streams[iid]\n}",
"func getStreamFromURL(fileURI string) (io.ReadCloser, error) {\n\turl, err := url.Parse(fileURI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tswitch url.Scheme {\n\tcase \"http\", \"https\":\n\t\tresp, err := http.Get(fileURI)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn resp.Body, nil\n\tcase \"file\", \"\":\n\t\tf, err := os.Open(fileURI)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn f, nil\n\tdefault:\n\t\treturn nil, errors.New(\"URL Not supported\")\n\t}\n}",
"func (c *requestWillBeSentExtraInfoClient) GetStream() rpcc.Stream { return c.Stream }",
"func (sp *StreamPool) Get(ctx xctx.XContext, peerId peer.ID) (*Stream, error) {\n\tif v, ok := sp.streams.Get(peerId.Pretty()); ok {\n\t\tif stream, ok := v.(*Stream); ok {\n\t\t\tif stream.Valid() {\n\t\t\t\treturn stream, nil\n\t\t\t} else {\n\t\t\t\tsp.DelStream(stream)\n\t\t\t\tctx.GetLog().Warn(\"stream not valid, create new stream\", \"peerId\", peerId)\n\t\t\t}\n\t\t}\n\t}\n\n\tsp.mutex.Lock()\n\tdefer sp.mutex.Unlock()\n\tif v, ok := sp.streams.Get(peerId.Pretty()); ok {\n\t\tif stream, ok := v.(*Stream); ok {\n\t\t\tif stream.Valid() {\n\t\t\t\treturn stream, nil\n\t\t\t} else {\n\t\t\t\tsp.DelStream(stream)\n\t\t\t\tctx.GetLog().Warn(\"stream not valid, create new stream\", \"peerId\", peerId)\n\t\t\t}\n\t\t}\n\t}\n\n\tnetStream, err := sp.srv.host.NewStream(sp.ctx, peerId, protocol.ID(protocolID))\n\tif err != nil {\n\t\tctx.GetLog().Warn(\"new net stream error\", \"peerId\", peerId, \"error\", err)\n\t\treturn nil, ErrNewStream\n\t}\n\n\treturn sp.NewStream(ctx, netStream)\n}",
"func Decode(rc io.ReadCloser) (s beep.StreamSeekCloser, format beep.Format, err error) {\n\tdefer func() {\n\t\tif err != nil {\n\t\t\terr = errors.Wrap(err, \"ogg/vorbis\")\n\t\t}\n\t}()\n\td, err := oggvorbis.NewReader(rc)\n\tif err != nil {\n\t\treturn nil, beep.Format{}, err\n\t}\n\tformat = beep.Format{\n\t\tSampleRate: beep.SampleRate(d.SampleRate()),\n\t\tNumChannels: govorbisNumChannels,\n\t\tPrecision: govorbisPrecision,\n\t}\n\treturn &decoder{rc, d, format, nil}, format, nil\n}",
"func (s *Stream) Read() error {\n\tif s.callback.IsValid() {\n\t\treturn CanNotReadFromACallbackStream\n\t}\n\tif s.in == nil {\n\t\treturn CanNotReadFromAnOutputOnlyStream\n\t}\n\tbuf, frames, err := getBuffer(s.in, s.inParams)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn newError(C.Pa_ReadStream(s.paStream, buf, C.ulong(frames)))\n}",
"func GetAudioFile(downloadURL, id, FName string, client *http.Client) *OnError {\n\t// fmt.Println(\"Gopher's getting the audio File\")\n\treq, err := newRequest(downloadURL, \"GET\", nil)\n\tif err != nil {\n\t\treturn &OnError{err, \"Error during GetAudioFile Get request\"}\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn &OnError{err, \"Error during GetAudioFile response\"}\n\t}\n\tdebug(\"GetAudioFile Response:%v\", resp)\n\terr = DecryptMedia(resp.Body, id, FName, resp.ContentLength)\n\tif err != nil {\n\t\treturn &OnError{err, \"Error during DecryptMedia\"}\n\t}\n\tdefer resp.Body.Close()\n\treturn nil\n}",
"func (ws *WrappedStream) Stream() net.Stream {\n\treturn ws.stream\n}",
"func (a *AnimatedEmoji) GetSound() (value File) {\n\tif a == nil {\n\t\treturn\n\t}\n\treturn a.Sound\n}",
"func (s *SessionSRTP) OpenReadStream(SSRC uint32) (*ReadStream, error) {\n\tr, _ := s.session.getOrCreateReadStream(SSRC, s)\n\treturn r, nil\n}",
"func (event ActivityReceivedEventArgs) GetAudio() (*audio.PullAudioOutputStream, error) {\n\tvar handle C.SPXHANDLE\n\tret := uintptr(C.dialog_service_connector_activity_received_event_get_audio(event.handle, &handle))\n\tif ret != C.SPX_NOERROR {\n\t\treturn nil, common.NewCarbonError(ret)\n\t}\n\treturn audio.NewPullAudioOutputStreamFromHandle(handle2uintptr(handle)), nil\n}",
"func (c *subresourceWebBundleInnerResponseErrorClient) GetStream() rpcc.Stream { return c.Stream }",
"func New(r io.Reader) (stream *Stream, err error) {\n\t// Verify FLAC signature and parse the StreamInfo metadata block.\n\tbr := bufio.NewReader(r)\n\tstream = &Stream{r: br}\n\tisLast, err := stream.parseStreamInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Skip the remaining metadata blocks.\n\tfor !isLast {\n\t\tblock, err := meta.New(br)\n\t\tif err != nil && err != meta.ErrReservedType {\n\t\t\treturn stream, err\n\t\t}\n\t\tif err = block.Skip(); err != nil {\n\t\t\treturn stream, err\n\t\t}\n\t\tisLast = block.IsLast\n\t}\n\n\treturn stream, nil\n}",
"func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {\n\treturn f.Put(ctx, in, src, options...)\n}",
"func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {\n\treturn f.Put(ctx, in, src, options...)\n}",
"func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {\n\treturn f.Put(ctx, in, src, options...)\n}",
"func (r *Radio) Play(b *dream.Session, vc *discordgo.VoiceConnection) (*dream.AudioDispatcher, error) {\n\tsong, err := r.Queue.Song()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar stream io.ReadCloser\n\n\tif r.UseYoutubeDL {\n\t\tyt := exec.Command(\"youtube-dl\", \"-f\", \"bestaudio\", \"--youtube-skip-dash-manifest\", \"-o\", \"-\", song.URL)\n\t\tstream, err = yt.StdoutPipe()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = yt.Start()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tstream, err = util.YoutubeDL(song.URL)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tdisp := b.PlayStream(vc, stream)\n\treturn disp, nil\n}",
"func (t *TwitterController) GetStream() {\n\tdefer wg.Done()\n\n\t// Kafka producer setup\n\tconn, err := kafka.DialLeader(context.Background(), \"tcp\", \"localhost:9092\", topic, partition)\n\tif err != nil {\n\t\tlog.Fatal(\"failed to dial leader:\", err)\n\t}\n\n\t// HTTP request setup\n\tauthorizationBearer := \"Bearer \" + os.Getenv(\"TWITTER_AUTH_BEARER\")\n\tclient := &http.Client{}\n\n\treq, _ := http.NewRequest(\"GET\", streamURL, nil)\n\treq.Header.Add(\"Authorization\", authorizationBearer)\n\n\tresp, _ := client.Do(req)\n\treader := bufio.NewReader(resp.Body)\n\n\tfor {\n\t\tselect {\n\t\t// When receive quit channel, stop streaming\n\t\tcase <-quit:\n\t\t\t// Close HTTP connection\n\t\t\tdefer resp.Body.Close()\n\n\t\t\t// Close Kafka connection\n\t\t\tif err := conn.Close(); err != nil {\n\t\t\t\tlog.Fatal(\"failed to close writer:\", err)\n\t\t\t}\n\n\t\t\tfmt.Print(\"Stop streaming...\")\n\t\t\treturn\n\n\t\tdefault:\n\t\t\t// Read the response\n\t\t\ttweet, _ := reader.ReadBytes('\\n')\n\t\t\tline := string(tweet)\n\n\t\t\tfmt.Print(line)\n\n\t\t\t// Send raw tweet to Kafka topic\n\t\t\t_, err = conn.WriteMessages(\n\t\t\t\tkafka.Message{Value: []byte(line)},\n\t\t\t)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(\"Failed to write messages:\", err)\n\t\t\t}\n\t\t}\n\t}\n}",
"func (m *Music) Play(reader *bufio.Reader, volume100 int) {\n\tm.playing = true\n\tdefer func() {\n\t\tm.played <- true\n\t\tif m.stopping {\n\t\t\tm.stopped <- true\n\t\t}\n\t\tm.playing = false\n\t}()\n\n\tvolume := int(SampleAmp16bit * (float64(volume100) / 100.0))\n\toutputFileName := m.output\n\n\tif m.piano == nil {\n\t\tm.piano = NewPiano()\n\t}\n\n\tvar outputFile *os.File\n\tvar err error\n\n\t// output file\n\tif len(outputFileName) > 0 {\n\t\tif outputFileName == \"-\" {\n\t\t\toutputFile = os.Stdout\n\t\t\tm.quietMode = true\n\t\t} else {\n\t\t\topt := os.O_WRONLY | os.O_TRUNC | os.O_CREATE\n\t\t\toutputFile, err = os.OpenFile(outputFileName, opt, 0644)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"Error opening output file:\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t\tdefer outputFile.Close()\n\t}\n\n\tif m.quietMode {\n\t\tPrintSheet = false\n\t\tPrintNotes = false\n\t}\n\n\t// sustain state\n\tsustain := &Sustain{\n\t\tattack: 8,\n\t\tdecay: 4,\n\t\tsustain: 4,\n\t\trelease: 9,\n\t\tbuf: make([]int16, quarterNote),\n\t}\n\n\t// read lines\n\tchord := &Chord{}\n\tbufWaveLimit := 1024 * 1024 * 100\n\tcontrolKeys := \"RDHTSAVC\"\n\tmeasures := \"WHQESTI\"\n\thands := \"0LR7\"\n\tzeroToNine := \"0123456789\"\n\ttempos := zeroToNine\n\tamplitudes := zeroToNine\n\tchordNumbers := zeroToNine\n\tignoredKeys := \"\\t |\"\n\tsustainTypes := \"ADSR\"\n\tsustainLevels := zeroToNine\n\tvoiceControls := \"DPVN\"\n\n\tvar (\n\t\tbufOutput []int16\n\t\tduration = 'Q' // default note duration\n\t\tdotted bool\n\t\trest rune\n\t\tctrl rune\n\t\tvoice Voice = m.piano // default voice is piano\n\t\tsustainType rune\n\t\thand = 'R' // default is middle C octave\n\t\thandLevel rune\n\t\tcount int // line counter\n\t\ttempo = 4 // normal speed\n\t\tamplitude = 9 // max volume\n\t\tmixNextLine bool\n\t\tbufMix []int16\n\t\tlineMix string\n\t\twaitNext bool\n\t\tblockComment bool\n\t)\n\n\tfor {\n\t\tline, done := nextMusicLine(reader)\n\t\tif done {\n\t\t\tbreak\n\t\t}\n\t\tif strings.HasPrefix(line, \"#\") {\n\t\t\tif strings.HasPrefix(line, \"##\") {\n\t\t\t\t// ignore block comment\n\t\t\t\tif blockComment {\n\t\t\t\t\tblockComment = false\n\t\t\t\t} else {\n\t\t\t\t\tblockComment = true\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// ignore comments\n\t\t\t\tif PrintSheet {\n\t\t\t\t\tfmt.Println(line)\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif blockComment {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasSuffix(line, \"VN\") {\n\t\t\t// include next line to mixer\n\t\t\tmixNextLine = true\n\t\t} else {\n\t\t\tmixNextLine = false\n\t\t}\n\t\tvar bufWave []int16\n\t\tfor _, key := range line {\n\t\t\tkeystr := string(key)\n\t\t\tif strings.ContainsAny(keystr, ignoredKeys) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ctrl == 0 && strings.ContainsAny(keystr, controlKeys) {\n\t\t\t\tctrl = key\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ctrl > 0 {\n\t\t\t\tswitch ctrl {\n\t\t\t\tcase 'D': // duration\n\t\t\t\t\tif strings.ContainsAny(keystr, measures) {\n\t\t\t\t\t\tduration = key\n\t\t\t\t\t}\n\t\t\t\t\tif key == 'D' {\n\t\t\t\t\t\tdotted = true\n\t\t\t\t\t}\n\t\t\t\tcase 'R': // reset\n\t\t\t\t\tif strings.ContainsAny(keystr, measures) {\n\t\t\t\t\t\trest = key\n\t\t\t\t\t}\n\t\t\t\tcase 'H': // hand\n\t\t\t\t\tif strings.ContainsAny(keystr, hands) {\n\t\t\t\t\t\thand = key\n\t\t\t\t\t}\n\t\t\t\tcase 'T': // tempo\n\t\t\t\t\tif strings.ContainsAny(keystr, tempos) {\n\t\t\t\t\t\ttempo = strings.Index(tempos, keystr)\n\t\t\t\t\t}\n\t\t\t\tcase 'S': // sustain\n\t\t\t\t\tif strings.ContainsAny(keystr, sustainTypes) {\n\t\t\t\t\t\tsustainType = key\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif strings.ContainsAny(keystr, sustainLevels) {\n\t\t\t\t\t\tlevel := strings.Index(sustainLevels, keystr)\n\t\t\t\t\t\tswitch sustainType {\n\t\t\t\t\t\tcase 'A':\n\t\t\t\t\t\t\tsustain.attack = level\n\t\t\t\t\t\tcase 'D':\n\t\t\t\t\t\t\tsustain.decay = level\n\t\t\t\t\t\tcase 'S':\n\t\t\t\t\t\t\tsustain.sustain = level\n\t\t\t\t\t\tcase 'R':\n\t\t\t\t\t\t\tsustain.release = level\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase 'A': // amplitude\n\t\t\t\t\tif strings.ContainsAny(keystr, amplitudes) {\n\t\t\t\t\t\tamplitude = strings.Index(amplitudes, keystr)\n\t\t\t\t\t}\n\t\t\t\tcase 'V': // voice\n\t\t\t\t\tif strings.ContainsAny(keystr, voiceControls) {\n\t\t\t\t\t\tswitch key {\n\t\t\t\t\t\tcase 'D': // default voice\n\t\t\t\t\t\t\tvoice.ComputerVoice(true)\n\t\t\t\t\t\tcase 'P':\n\t\t\t\t\t\t\tvoice = m.piano\n\t\t\t\t\t\t\tif voice.NaturalVoiceFound() {\n\t\t\t\t\t\t\t\tvoice.ComputerVoice(false)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'V':\n\t\t\t\t\t\t\tif m.violin == nil {\n\t\t\t\t\t\t\t\tm.violin = NewViolin()\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tvoice = m.violin\n\t\t\t\t\t\t\tvoice.ComputerVoice(false)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase 'C': // chord\n\t\t\t\t\tif strings.ContainsAny(keystr, chordNumbers) {\n\t\t\t\t\t\tchord.count = 0\n\t\t\t\t\t\tchord.number = strings.Index(chordNumbers, keystr)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif rest > 0 {\n\t\t\t\t\tbufRest := restNote(rest, dotted, tempo)\n\t\t\t\t\tif bufRest != nil {\n\t\t\t\t\t\tif voice.NaturalVoice() {\n\t\t\t\t\t\t\treleaseNote(sustain.buf, 0, sustain.Ratio())\n\t\t\t\t\t\t\tmixSoundWave(bufRest, sustain.buf)\n\t\t\t\t\t\t\tclearBuffer(sustain.buf)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbufWave = append(bufWave, bufRest...)\n\t\t\t\t\t}\n\t\t\t\t\trest = 0\n\t\t\t\t}\n\t\t\t\tctrl = 0\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch hand {\n\t\t\tcase '0': // octave 0\n\t\t\t\thandLevel = 1000\n\t\t\tcase 'L': // octave 1, 2, 3\n\t\t\t\thandLevel = 2000\n\t\t\tcase 'R': // octave 4, 5, 6\n\t\t\t\thandLevel = 3000\n\t\t\tcase '7', '8': // octave 7, 8\n\t\t\t\thandLevel = 4000\n\t\t\t}\n\t\t\tnote := &Note{\n\t\t\t\tkey: handLevel + key,\n\t\t\t\tvolume: volume,\n\t\t\t\tamplitude: amplitude,\n\t\t\t\tduration: duration,\n\t\t\t\tdotted: dotted,\n\t\t\t\ttempo: tempo,\n\t\t\t\tsamples: 0,\n\t\t\t}\n\t\t\tnote.measure()\n\t\t\tif voice.GetNote(note, sustain) {\n\t\t\t\tdotted = false\n\t\t\t\tif chord.number > 0 {\n\t\t\t\t\t// playing a chord\n\t\t\t\t\tchord.count++\n\t\t\t\t\tif chord.buf == nil {\n\t\t\t\t\t\tchord.buf = make([]int16, len(note.buf))\n\t\t\t\t\t\tcopy(chord.buf, note.buf)\n\t\t\t\t\t\tif voice.NaturalVoice() {\n\t\t\t\t\t\t\t//copyBuffer(sustain.buf, chord.buf)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmixSoundWave(chord.buf, note.buf)\n\t\t\t\t\t\tif voice.NaturalVoice() {\n\t\t\t\t\t\t\t//mixSoundWave(sustain.buf, note.buf)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif chord.count == chord.number {\n\t\t\t\t\t\tif voice.NaturalVoice() {\n\t\t\t\t\t\t\trelease := len(note.buf) / 10 * sustain.sustain\n\t\t\t\t\t\t\tratio := sustain.Ratio()\n\t\t\t\t\t\t\treleaseNote(sustain.buf, release, ratio)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnote.buf = chord.buf\n\t\t\t\t\t\tchord.Reset()\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif PrintNotes {\n\t\t\t\t\t\t\tfmt.Printf(\"%v-\", m.piano.keyNoteMap[note.key])\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvoice.SustainNote(note, sustain)\n\t\t\t\tbufWave = append(bufWave, note.buf...)\n\t\t\t\tif len(bufWave) > bufWaveLimit {\n\t\t\t\t\tfmt.Fprintln(os.Stderr, \"Line wave buffer exceeds 100MB limit.\")\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t\tif PrintNotes {\n\t\t\t\t\tfmt.Printf(\"%v \", m.piano.keyNoteMap[note.key])\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvoiceName := strings.Split(fmt.Sprintf(\"%T\", voice), \".\")[1]\n\t\t\t\tnoteName := m.piano.keyNoteMap[note.key]\n\t\t\t\tfmt.Printf(\"%s: Invalid note: %s (%s)\\n\", voiceName, keystr, noteName)\n\t\t\t}\n\t\t}\n\t\tif mixNextLine {\n\t\t\tif bufMix == nil {\n\t\t\t\tbufMix = make([]int16, len(bufWave))\n\t\t\t\tcopy(bufMix, bufWave)\n\t\t\t\tlineMix = line\n\t\t\t} else {\n\t\t\t\tlineMix += \"\\n\" + line\n\t\t\t\tmixSoundWave(bufMix, bufWave)\n\t\t\t}\n\t\t\tcount++\n\t\t\tclearBuffer(sustain.buf)\n\t\t\tcontinue\n\t\t}\n\t\tif bufMix != nil {\n\t\t\tmixSoundWave(bufMix, bufWave)\n\t\t\tbufWave = bufMix\n\t\t\tbufMix = nil\n\t\t\tline = lineMix + \"\\n\" + line\n\t\t}\n\t\tif PrintNotes {\n\t\t\tfmt.Println()\n\t\t}\n\t\tif outputFile == nil {\n\t\t\tif len(bufWave) > 0 {\n\t\t\t\tif waitNext {\n\t\t\t\t\tm.WaitLine() // wait until previous line is done playing\n\t\t\t\t}\n\t\t\t\t// prepare next line while playing\n\t\t\t\tgo m.Playback(bufWave, bufWave)\n\t\t\t\tif PrintSheet {\n\t\t\t\t\tfmt.Println(line)\n\t\t\t\t}\n\t\t\t\twaitNext = true\n\t\t\t} else if PrintSheet {\n\t\t\t\tfmt.Println(line)\n\t\t\t}\n\t\t} else {\n\t\t\t// saving to file\n\t\t\tbuf := make([]int16, 2*len(bufWave))\n\t\t\tfor i, bar := range bufWave {\n\t\t\t\tbuf[i*2] = bar\n\t\t\t\tbuf[i*2+1] = bar\n\t\t\t}\n\t\t\tbufOutput = append(bufOutput, buf...)\n\t\t\tif PrintSheet {\n\t\t\t\tfmt.Println(line)\n\t\t\t}\n\t\t}\n\t\tclearBuffer(sustain.buf)\n\t\tcount++\n\t\tif m.stopping {\n\t\t\tbreak\n\t\t}\n\t}\n\tif waitNext {\n\t\tm.WaitLine()\n\t}\n\n\tif outputFile != nil {\n\t\t// save wave to file\n\t\tbuflen := len(bufOutput)\n\t\theader := NewWaveHeader(2, SampleRate, 16, buflen*2)\n\t\t_, err = header.WriteHeader(outputFile)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, \"Error writing to output file:\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tbuf := int16ToByteBuf(bufOutput)\n\t\t_, err := outputFile.Write(buf)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, \"Error writing to output file:\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif outputFileName != \"-\" {\n\t\t\tfmt.Printf(\"wrote %s bytes to '%s'\\n\", numberComma(int64(len(buf))), outputFileName)\n\t\t}\n\t}\n}",
"func (s StreamService) GetStreams() {\n\n}",
"func GetUserStream(id string) (StreamData, error) {\n\tvar stream StreamData\n\n\ttwitClient := http.Client{\n\t\tTimeout: time.Second * 200, // Maximum of 2 secs\n\t}\n\n\treq, err := http.NewRequest(http.MethodGet, \"https://api.twitch.tv/kraken/streams/\"+id, nil)\n\tif err != nil {\n\t\treturn stream, err\n\t}\n\n\treq.Header.Set(\"Accept\", accept)\n\treq.Header.Add(\"Client-ID\", tID)\n\n\tres, getErr := twitClient.Do(req)\n\tif getErr != nil {\n\t\treturn stream, getErr\n\t}\n\n\tbody, readErr := ioutil.ReadAll(res.Body)\n\tif readErr != nil {\n\t\treturn stream, readErr\n\t}\n\n\tres.Body.Close()\n\tif string(body) == `{\"stream\":null}` {\n\t\treturn stream, errors.New(\"Stream is currently offline\")\n\t}\n\n\terr = json.Unmarshal([]byte(body), &stream)\n\tif err != nil {\n\t\treturn stream, err\n\t}\n\n\treturn stream, nil\n}",
"func (c *baseChannels) GetS3Channel() chan *S3Object {\n\treturn c.s3Channel\n}",
"func GetLogFile(client kubernetes.Interface, namespace, podID string, container string, usePreviousLogs bool) (\n\tio.ReadCloser, error) {\n\tlogOptions := &v1.PodLogOptions{\n\t\tContainer: container,\n\t\tFollow: false,\n\t\tPrevious: usePreviousLogs,\n\t\tTimestamps: false,\n\t}\n\tlogStream, err := openStream(client, namespace, podID, logOptions)\n\treturn logStream, err\n}",
"func (c *cache) RetrieveStream(key string) io.ReadCloser {\n\tf, err := os.Open(c.path(key))\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\tlog.Warning(\"Failed to retrieve %s from cache: %s\", key, err)\n\t\t}\n\t\treturn nil\n\t}\n\treturn f\n}",
"func (h ExternalMusicHandler) GetClient(session *sessions.Session) (music.Client, error) {\n\tauthenticator, err := h.AuthenticationProvider.GetAuth(session)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := h.MusicService.Authenticate(authenticator)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}",
"func (c *File) GetStreamInfo() (*StreamInfoBlock, error) {\n\tif c.Meta[0].Type != StreamInfo {\n\t\treturn nil, ErrorNoStreamInfo\n\t}\n\tstreamInfo := bytes.NewReader(c.Meta[0].Data)\n\tres := StreamInfoBlock{}\n\n\tif buf, err := readUint16(streamInfo); err != nil {\n\t\treturn nil, ErrorStreamInfoEarlyEOF\n\t} else {\n\t\tres.BlockSizeMin = int(buf)\n\t}\n\n\tif buf, err := readUint16(streamInfo); err != nil {\n\t\treturn nil, ErrorStreamInfoEarlyEOF\n\t} else {\n\t\tres.BlockSizeMax = int(buf)\n\t}\n\n\tbuf := bytes.NewBuffer([]byte{0})\n\tbuf24 := make([]byte, 3)\n\tif _, err := io.ReadFull(streamInfo, buf24); err != nil {\n\t\treturn nil, ErrorStreamInfoEarlyEOF\n\t}\n\tbuf.Write(buf24)\n\tif buf, err := readUint32(buf); err != nil {\n\t\treturn nil, ErrorStreamInfoEarlyEOF\n\t} else {\n\t\tres.FrameSizeMin = int(buf)\n\t}\n\tbuf.Reset()\n\tbuf.WriteByte(0)\n\tif _, err := io.ReadFull(streamInfo, buf24); err != nil {\n\t\treturn nil, ErrorStreamInfoEarlyEOF\n\t}\n\tbuf.Write(buf24)\n\tif buf, err := readUint32(buf); err != nil {\n\t\treturn nil, ErrorStreamInfoEarlyEOF\n\t} else {\n\t\tres.FrameSizeMax = int(buf)\n\t}\n\n\tbuf.Reset()\n\tbuf.WriteByte(0)\n\tsmpl := make([]byte, 3)\n\tif _, err := io.ReadFull(streamInfo, smpl); err != nil {\n\t\treturn nil, ErrorStreamInfoEarlyEOF\n\t}\n\tbuf.Write(smpl)\n\tif smplrate, err := readUint32(buf); err != nil {\n\t\treturn nil, ErrorStreamInfoEarlyEOF\n\t} else {\n\t\tres.SampleRate = int(smplrate >> 4)\n\t}\n\tif _, err := streamInfo.Seek(-1, io.SeekCurrent); err != nil {\n\t\treturn nil, ErrorStreamInfoEarlyEOF\n\t}\n\n\tif channel, err := readUint8(streamInfo); err != nil {\n\t\treturn nil, ErrorStreamInfoEarlyEOF\n\t} else {\n\t\tres.ChannelCount = int(channel<<4>>5) + 1\n\t}\n\tbuf.Reset()\n\tif _, err := streamInfo.Seek(-1, io.SeekCurrent); err != nil {\n\t\treturn nil, ErrorStreamInfoEarlyEOF\n\t}\n\n\tif bitdepth, err := readUint16(streamInfo); err != nil {\n\t\treturn nil, ErrorStreamInfoEarlyEOF\n\t} else {\n\t\tres.BitDepth = int(bitdepth<<7>>11) + 1\n\t}\n\tif _, err := streamInfo.Seek(-1, io.SeekCurrent); err != nil {\n\t\treturn nil, ErrorStreamInfoEarlyEOF\n\t}\n\n\tvar smplcount int64\n\tif count, err := readUint32(streamInfo); err != nil {\n\t\treturn nil, ErrorStreamInfoEarlyEOF\n\t} else {\n\t\tsmplcount += int64(count<<4>>4) << 8\n\t}\n\tif count, err := readUint8(streamInfo); err != nil {\n\t\treturn nil, ErrorStreamInfoEarlyEOF\n\t} else {\n\t\tsmplcount += int64(count)\n\t}\n\tres.SampleCount = smplcount\n\n\tres.AudioMD5 = make([]byte, 16)\n\tif _, err := io.ReadFull(streamInfo, res.AudioMD5); err != nil {\n\t\treturn nil, ErrorStreamInfoEarlyEOF\n\t}\n\n\treturn &res, nil\n\n}",
"func (m *Media) GetStreams()([]MediaStreamable) {\n return m.streams\n}",
"func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {\n\treturn nil, errorReadOnly\n}",
"func (s *SessionSRTCP) OpenReadStream(SSRC uint32) (*ReadStream, error) {\n\tr, _ := s.session.getOrCreateReadStream(SSRC, s)\n\treturn r, nil\n}",
"func (s *Stream) Reader() io.Reader {\n\t// TODO: This might modify file, return a new reader instead\n\ts.file.Seek(0, 0)\n\treturn s.file\n}",
"func (f *Fs) PutStream(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {\n\treturn f.put(in, src, options, f.Fs.Features().PutStream)\n}",
"func (c *Client) GetTrack(id string, options *Options) (FullTrack, error) {\n\tvar track FullTrack\n\n\turl := constructURL(options, c.baseURL, \"tracks\", id)\n\terr := c.get(url, &track)\n\tif err != nil {\n\t\treturn FullTrack{}, err\n\t}\n\treturn track, nil\n}",
"func (o *AudioStreamPlayer) GetMixTarget() AudioStreamPlayerMixTarget {\n\t//log.Println(\"Calling AudioStreamPlayer.GetMixTarget()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"AudioStreamPlayer\", \"get_mix_target\")\n\n\t// Call the parent method.\n\t// enum.AudioStreamPlayer::MixTarget\n\tretPtr := gdnative.NewEmptyInt()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewIntFromPointer(retPtr)\n\treturn AudioStreamPlayerMixTarget(ret)\n}",
"func rawDecoder(f *os.File) (AudioStream, error) {\n\treturn &file{File: f}, nil\n}",
"func (r *resource) Open() io.ReadSeeker {\n\treturn bytes.NewReader(r.data)\n}"
] | [
"0.6775385",
"0.62344253",
"0.59986454",
"0.5945688",
"0.56664544",
"0.55468243",
"0.5513596",
"0.54077435",
"0.5403101",
"0.53692526",
"0.53535575",
"0.5328915",
"0.53116333",
"0.52892804",
"0.523862",
"0.52336264",
"0.52291775",
"0.5214617",
"0.521006",
"0.52036756",
"0.51532936",
"0.51445943",
"0.5121852",
"0.5040711",
"0.50101113",
"0.5006323",
"0.49608174",
"0.49346834",
"0.49109235",
"0.49078318",
"0.49026996",
"0.4889142",
"0.48832595",
"0.48718622",
"0.4869507",
"0.48612073",
"0.4856989",
"0.4834633",
"0.48289388",
"0.48238304",
"0.4803262",
"0.48031792",
"0.47853115",
"0.47769278",
"0.47489342",
"0.47481906",
"0.47480577",
"0.47479528",
"0.47352177",
"0.47272846",
"0.47030306",
"0.46770945",
"0.46549022",
"0.4651524",
"0.46429893",
"0.46406913",
"0.46296793",
"0.4592053",
"0.45895818",
"0.45871958",
"0.45865735",
"0.45784652",
"0.45624572",
"0.4547396",
"0.45401272",
"0.45241567",
"0.45072925",
"0.44966653",
"0.44955668",
"0.44913015",
"0.44886076",
"0.44859856",
"0.44759274",
"0.44727576",
"0.44720125",
"0.4465137",
"0.44521716",
"0.4448531",
"0.444277",
"0.444277",
"0.444277",
"0.44372293",
"0.44244927",
"0.4411308",
"0.44092783",
"0.4398939",
"0.43826237",
"0.43622005",
"0.4356308",
"0.43493202",
"0.4349106",
"0.43479493",
"0.4342904",
"0.43339625",
"0.43184754",
"0.43161193",
"0.4307744",
"0.42958626",
"0.42932865",
"0.42890635"
] | 0.7068442 | 0 |
GetProvider returns the provider identifier. | func (c *Client) GetProvider() jamsonic.MusicProvider {
return jamsonic.SubSonic
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (reg *Registry) GetProvider() string {\n\treturn reg.apiRegistry.Spec.Provider\n}",
"func (c Base) GetProvider() string {\n\treturn c.Provider\n}",
"func GetProvider(provider string) (Provider, error) {\n\tproviderString := strings.ToLower(provider)\n\n\tif providerString == \"local\" {\n\t\treturn Local{}, nil\n\t}\n\n\tif providerString == \"circleciv2\" {\n\t\treturn CircleCIv2{}, nil\n\t}\n\n\tif providerString == \"githubactions\" {\n\t\treturn GithubActions{}, nil\n\t}\n\n\tif providerString == \"awscodebuild\" {\n\t\treturn AWSCodeBuild{}, nil\n\t}\n\n\treturn nil, errors.New(\"build provider not supported: \" + provider)\n}",
"func (retriever *CredRetrieverConsul) GetProvider() string {\n\treturn retriever.Provider\n}",
"func GetProvider(name string) (Provider, error) {\n\tprovidersMutex.Lock()\n\tdefer providersMutex.Unlock()\n\tf, found := providers[name]\n\tif !found {\n\t\treturn nil, fmt.Errorf(\"provider %s is not registered\", name)\n\t}\n\treturn f()\n}",
"func (s *Service) GetProvider(name string) Provider {\n\treturn s.providers[name]\n}",
"func GetProvider(name string) (Provider, error) {\n\tprovider, ok := customProviders[name]\n\tif ok != true {\n\t\tprovider, ok = defaultProviders[name]\n\t}\n\n\tif ok != true {\n\t\treturn Provider{}, errors.New(fmt.Sprintf(\"unknown provider: %s\", name))\n\t}\n\n\tif provider.ScopeDelimiter == \"\" {\n\t\tprovider.ScopeDelimiter = \",\"\n\t}\n\treturn provider, nil\n}",
"func GetProvider() Provider {\n\treturn basicProvider{}\n}",
"func (o *IdentityCredentialIdentifierOidcProperties) GetProvider() string {\n\tif o == nil || o.Provider == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Provider\n}",
"func GetProvider(providerName string) Provider {\n\tswitch providerName {\n\tcase \"google\":\n\t\treturn NewGoogleProvider()\n\tcase \"github\":\n\t\treturn NewGitHubProvider()\n\tdefault:\n\t\treturn NewGoogleProvider()\n\t}\n}",
"func (retriever *CredRetrieverEtcd) GetProvider() string {\n\treturn retriever.Provider\n}",
"func (u UserHandler) GetProvider(name string) (prov AuthenticationProvider, err error) {\n\tif err = u.db.Where(AuthenticationProvider{Name: name}).First(&prov).Error; err != nil {\n\t\terr = fmt.Errorf(\"failed finding provider: %w\", err)\n\t}\n\treturn\n}",
"func (t ProviderType) GetProvider() (GenericProvider, error) {\n\tswitch t {\n\tcase ProviderDocker:\n\t\tprovider, err := NewDockerProvider()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to create Docker provider\")\n\t\t}\n\t\treturn provider, nil\n\t}\n\treturn nil, errors.New(\"unknown provider\")\n}",
"func (retriever *CredRetrieverRemoteFs) GetProvider() string {\n\treturn retriever.Provider\n}",
"func (retriever *CredRetrieverLocalFs) GetProvider() string {\n\treturn retriever.Provider\n}",
"func GetProvider() string {\n\tprovider, ok := os.LookupEnv(\"OBJECT_STORE_PROVIDER\")\n\texpect(ok).To(beTrue(), fmt.Sprintf(\"No environment variable 'PROVIDER' supplied. Valid values are: %s, %s, %s\",\n\t\tdrivers.ProviderAws, drivers.ProviderAzure, drivers.ProviderGke))\n\tswitch provider {\n\tcase drivers.ProviderAws, drivers.ProviderAzure, drivers.ProviderGke:\n\tdefault:\n\t\tfail(fmt.Sprintf(\"Valid values for 'PROVIDER' environment variables are: %s, %s, %s\",\n\t\t\tdrivers.ProviderAws, drivers.ProviderAzure, drivers.ProviderGke))\n\t}\n\treturn provider\n}",
"func (o *SuperKeyRequest) GetProvider() string {\n\tif o == nil || o.Provider == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Provider\n}",
"func (r MemRepository) GetProvider(id string) (*model.Provider, error) {\n\tvar err error\n\n\titem, ok := r.providers[id]\n\n\tif ok {\n\t\terr = nil\n\t} else {\n\t\terr = model.ErrNotFound\n\t}\n\treturn &item, err\n}",
"func (c *CIDOffer) GetProviderID() *nodeid.NodeID {\n\treturn c.providerID\n}",
"func (pv *Providers) GetProvider(name provider.Name) (Provider, error) {\n\tpv.mu.RLock()\n\tdefer pv.mu.RUnlock()\n\t// properly (in case internalProvider is Unknown)\n\tif name == provider.Unknown {\n\t\treturn nil, errors.New(\"invalid provider\")\n\t}\n\tif !name.IsExternal() {\n\t\terr := fmt.Errorf(\"invalid provider: %s\", name)\n\t\treturn nil, err\n\t}\n\tpvd := pv.providers[string(name)]\n\tif pvd == nil {\n\t\treturn nil, fmt.Errorf(\"no provider for %s exists\", name)\n\t}\n\treturn pvd, nil\n}",
"func getProvider(id string) *provider {\n\tif mockGetProviderValue != nil {\n\t\treturn mockGetProviderValue\n\t}\n\tp, _ := auth.GetProviderByConfigID(auth.ProviderConfigID{Type: providerType, ID: id}).(*provider)\n\treturn p\n}",
"func GetProvider(cookie string) (string, error) {\n\tvar nilstr string\n\n\te, err := state.ParseEnvelope(cookie)\n\tif err != nil {\n\t\treturn nilstr, err\n\t}\n\n\treturn e.GetProvider(), nil\n}",
"func GetInstanceProviderID(ctx context.Context, cloud Interface, nodeName types.NodeName) (string, error) {\n\tinstances, ok := cloud.Instances()\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"failed to get instances from cloud provider\")\n\t}\n\tinstanceID, err := instances.InstanceID(ctx, nodeName)\n\tif err != nil {\n\t\tif err == NotImplemented {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\treturn \"\", fmt.Errorf(\"failed to get instance ID from cloud provider: %v\", err)\n\t}\n\treturn cloud.ProviderName() + \"://\" + instanceID, nil\n}",
"func (m *MachineScope) ProviderID() string {\n\treturn ptr.Deref(m.AzureMachine.Spec.ProviderID, \"\")\n}",
"func (r *Registry) GetProvider(code string) (RatesProvider, error) {\n\tfor providerCode, provider := range r.providers {\n\t\tif providerCode == code {\n\t\t\treturn provider, nil\n\t\t}\n\t}\n\treturn nil, errors.New(\"provider with code \" + code + \"does not registered\")\n}",
"func (p *PaymentsPaymentForm) GetProviderID() (value int64) {\n\tif p == nil {\n\t\treturn\n\t}\n\treturn p.ProviderID\n}",
"func (mg *Group) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *SQLFunction) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func Provider() *provider.Provider {\n\treturn p\n}",
"func (mg *SQLDatabase) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *Router) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *GremlinDatabase) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *Instance) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *Instance) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (u *UnknownProvider) GetProviderString() string {\n\treturn \"unknown\"\n}",
"func (mg *User) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (r *EBSVolumeResizer) GetProviderVolumeID(pv *v1.PersistentVolume) (string, error) {\n\tvolumeID := pv.Spec.AWSElasticBlockStore.VolumeID\n\tif volumeID == \"\" {\n\t\treturn \"\", fmt.Errorf(\"got empty volume id for volume %v\", pv)\n\t}\n\n\treturn r.ExtractVolumeID(volumeID)\n}",
"func (mg *Table) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *SQLStoredProcedure) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *UserGroupMembership) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *InstanceProfile) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *Firewall) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *SecurityGroup) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *GremlinGraph) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *Network) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *Role) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *ElasticIP) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *OpenIDConnectProvider) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *CassandraKeySpace) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *Policy) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (s *Server) Provider() Provider {\n\treturn s.provider\n}",
"func (mg *Account) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *NotebookWorkspace) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (c *Client) ProviderID() gitprovider.ProviderID {\n\treturn ProviderID\n}",
"func (mg *SQLContainer) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *MongoDatabase) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *MongoCollection) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *SQLTrigger) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (o *StorageNetAppCloudTargetAllOf) GetProviderType() string {\n\tif o == nil || o.ProviderType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ProviderType\n}",
"func (mg *CassandraTable) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *EC2NetworkInterface) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (c *EBSVolumeResizer) GetProviderVolumeID(pv *v1.PersistentVolume) (string, error) {\n\tvolumeID := pv.Spec.AWSElasticBlockStore.VolumeID\n\tif volumeID == \"\" {\n\t\treturn \"\", fmt.Errorf(\"volume id is empty for volume %q\", pv.Name)\n\t}\n\tidx := strings.LastIndex(volumeID, constants.EBSVolumeIDStart) + 1\n\tif idx == 0 {\n\t\treturn \"\", fmt.Errorf(\"malfored EBS volume id %q\", volumeID)\n\t}\n\treturn volumeID[idx:], nil\n}",
"func (cloud *Cloud) ProviderName() string {\n\treturn providerName\n}",
"func (o AuthRequirementOutput) ProviderId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AuthRequirement) *string { return v.ProviderId }).(pulumi.StringPtrOutput)\n}",
"func (mg *Address) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *EC2LaunchTemplate) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (p *packet) getProvider(tag string) (*provider, error) {\n\tprv, ok := p.providers.Load(tag)\n\tif !ok {\n\t\treturn nil, ProviderNotFound\n\t}\n\treturn prv.(*provider), nil\n}",
"func (mg *AccessKey) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *RouterNAT) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *Subnetwork) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *RouteTable) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func NewProvider() *Provider {\n\treturn &Provider{}\n}",
"func (mg *TransitGateway) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *RouteTableAssociation) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *SecurityGroupRule) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (c *cloud) ProviderName() string {\n\treturn ProviderName\n}",
"func (driver Driver) ProviderName() string {\n\treturn driver.data.ProviderName.String()\n}",
"func (mg *GroupPolicyAttachment) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (p Provider) GetCode() string {\n\treturn p.code\n}",
"func (mg *ManagedSSLCertificate) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (s *Store) GetProviderByProviderID(ctx context.Context, id *int) (*[]Provider, error) {\n\tp := []Provider{}\n\n\tif err := s.db.Select(&p, getProviderByProviderID, id); err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\treturn &p, nil\n}",
"func (ts *Tester) Provider() string {\n\treturn \"eks\"\n}",
"func GetProvider() providers.StreamProvider {\n\tdb, err := datastore.NewSqlDb(datastore.SQL_DRIVER, datastore.DATABASE_SOURCE)\n\tif err != nil {\n\t\tglog.Fatalf(\"Could not initialize DB connection: %s\", err)\n\t}\n\tstore := storage.NewDatastoreMconfigStorage(db)\n\treturn NewMconfigStreamProvider(store)\n}",
"func (o AuthRequirementResponseOutput) ProviderId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AuthRequirementResponse) string { return v.ProviderId }).(pulumi.StringOutput)\n}",
"func (s *Store) GetProviderByID(ctx context.Context, id int) (*[]Provider, error) {\n\tp := []Provider{}\n\n\tif err := s.db.Select(&p, getProviderByID, id); err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\treturn &p, nil\n}",
"func (mg *VPC) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (iter *PlanIterator) Provider(t tokens.Type) (plugin.Provider, error) {\n\tpkg := t.Package()\n\tprov, err := iter.p.Provider(pkg)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if prov == nil {\n\t\treturn nil, errors.Errorf(\"could not load resource provider for package '%v' from $PATH\", pkg)\n\t}\n\treturn prov, nil\n}",
"func (mg *UserPolicyAttachment) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (c *Client) ProviderType() string {\n\treturn c.client.Driver.String()\n}",
"func (p *Provider) Type() string {\n\treturn ProviderType\n}",
"func (mg *VpcEndpoint) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (vpcIks *IksVpcSession) GetProviderDisplayName() provider.VolumeProvider {\n\treturn Provider\n}",
"func (p *Provider) GetKey() interface{} {\n\treturn p.key\n}",
"func (mg *RolePolicyAttachment) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *Subnet) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (mg *TransitGatewayRoute) GetProviderReference() *xpv1.Reference {\n\treturn mg.Spec.ProviderReference\n}",
"func (s *scwServer) ProviderID() string {\n\treturn \"\"\n}",
"func GetTunnelProvider() string {\n\tveryFlagInput()\n\treturn provider\n}",
"func (p Provider) String() string {\n\treturn providerNames[p]\n}",
"func (c *MockAzureCloud) ProviderID() kops.CloudProviderID {\n\treturn kops.CloudProviderAzure\n}"
] | [
"0.7975703",
"0.7776886",
"0.7494708",
"0.74714816",
"0.7453306",
"0.74428016",
"0.74188364",
"0.7384566",
"0.7337826",
"0.72578424",
"0.7256498",
"0.7218999",
"0.72146267",
"0.71836275",
"0.7176117",
"0.70643485",
"0.7005775",
"0.6987899",
"0.6949124",
"0.6899411",
"0.68723464",
"0.6804978",
"0.6757534",
"0.67301184",
"0.6630979",
"0.66253835",
"0.65925425",
"0.6536557",
"0.6528494",
"0.6517744",
"0.6469839",
"0.6460826",
"0.6443385",
"0.6443385",
"0.64343625",
"0.6427047",
"0.6413254",
"0.64020085",
"0.6381388",
"0.6367848",
"0.6359808",
"0.63402873",
"0.6328962",
"0.63198835",
"0.63126993",
"0.6287139",
"0.6285102",
"0.62813294",
"0.628026",
"0.6275634",
"0.62711656",
"0.6245988",
"0.6236179",
"0.6220122",
"0.62136215",
"0.62109244",
"0.61996126",
"0.6197421",
"0.61907136",
"0.6188802",
"0.61762965",
"0.61705923",
"0.6162307",
"0.6159101",
"0.6157654",
"0.6143239",
"0.6130103",
"0.6129108",
"0.61131495",
"0.61064434",
"0.60832965",
"0.6074287",
"0.6062204",
"0.6052444",
"0.60506564",
"0.60485387",
"0.60470986",
"0.6028416",
"0.59979033",
"0.5991583",
"0.5979114",
"0.5975031",
"0.59721684",
"0.59630257",
"0.59618735",
"0.59600973",
"0.5959119",
"0.59553903",
"0.594952",
"0.594556",
"0.5942903",
"0.59372795",
"0.593241",
"0.5929532",
"0.5909126",
"0.5901667",
"0.5896497",
"0.5892772",
"0.5880598",
"0.5876415"
] | 0.67967564 | 22 |
MarshalJSON creates JSON game representation | func (g *Game) MarshalJSON() ([]byte, error) {
return json.Marshal(&GameJson{
CreatedAt: g.CreatedAt,
UpdatedAt: g.UpdatedAt,
Table: g.TournamentTable.Table,
RightPlayers: g.RightPlayerNames(),
LeftPlayers: g.LeftPlayerNames(),
RightScore: g.GetOrCalculateRightScore(),
LeftScore: g.GetOrCalculateLeftScore(),
Winner: g.Winner,
})
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (v Game) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson6601e8cdEncodeJsongen1(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v GameFull) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson6601e8cdEncodeJsongen(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v Game) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson6601e8cdEncodeJsongen1(w, v)\n}",
"func (v GameOver) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson6601e8cdEncodeGithubComGoParkMailRu2018242GameServerTypes1(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (g *Game) MarshalJSON() ([]byte, error) {\n\tg.RLock()\n\tdefer g.RUnlock()\n\treturn json.Marshal(g.gameState)\n}",
"func (g *Game) Marshal() []byte {\n\treturn []byte(`{\"id\":\"` + g.id + `\",\"board\":\"` + string(g.board) + `\",\"status\":\"` + g.status + `\"}`)\n}",
"func (v GameFull) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson6601e8cdEncodeJsongen(w, v)\n}",
"func (g *Game) getGameJson() []byte {\n\tb, err := json.Marshal(g)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn b\n}",
"func (v GameOver) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson6601e8cdEncodeGithubComGoParkMailRu2018242GameServerTypes1(w, v)\n}",
"func (game *T) JSON(seat *Seat) cast.JSON {\n\tif game == nil {\n\t\treturn nil\n\t}\n\tseats := cast.JSON{}\n\tfor _, s := range game.Seats {\n\t\tseats[s.Username] = s.JSON()\n\t}\n\treturn cast.JSON{\n\t\t\"id\": game.ID(),\n\t\t// \"life\": seat.Life,\n\t\t\"hand\": seat.Hand.JSON(),\n\t\t\"state\": game.State.JSON(),\n\t\t// \"elements\": seat.Elements.JSON(),\n\t\t\"username\": seat.Username,\n\t\t// \"opponent\": game.GetOpponentSeat(seat.Username).Username,\n\t\t\"seats\": seats,\n\t}\n}",
"func (game *T) WriteJSON(json cast.JSON) {\n\tfor _, seat := range game.Seats {\n\t\tseat.WriteJSON(json)\n\t}\n}",
"func (player *Player) WriteJSON(v interface{}) error {\n\tplayer.packetStack <- v\n\treturn nil\n}",
"func write(out *bufio.Writer, game map[string]interface{}) error {\n\tb, err := json.MarshalIndent(game, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = out.Write(b)\n\treturn err\n}",
"func (v RoomPlayer) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncode20191OPGPlus2InternalPkgModels11(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (h Horse) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"isAShowHorse\", h.IsAShowHorse)\n\tpopulate(objectMap, \"name\", h.Name)\n\treturn json.Marshal(objectMap)\n}",
"func (p Season) Serialize() common.JSON {\n\treturn common.JSON{\n\t\t\"ID\": p.ID,\n\t\t\"Name\": p.Name,\n\t\t\"Year\": p.Year,\n\t\t\"EventsID\": p.EventsID,\n\t}\n}",
"func (v AddWeapon) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson6601e8cdEncodeGithubComGoParkMailRu2018242GameServerTypes3(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v EventPlayersCreated) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoMedia2(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v ScoreboardData) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncode20191OPGPlus2InternalPkgModels8(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (o Overlay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"audioGainLevel\", o.AudioGainLevel)\n\tpopulate(objectMap, \"end\", o.End)\n\tpopulate(objectMap, \"fadeInDuration\", o.FadeInDuration)\n\tpopulate(objectMap, \"fadeOutDuration\", o.FadeOutDuration)\n\tpopulate(objectMap, \"inputLabel\", o.InputLabel)\n\tobjectMap[\"@odata.type\"] = o.ODataType\n\tpopulate(objectMap, \"start\", o.Start)\n\treturn json.Marshal(objectMap)\n}",
"func (j JpgLayer) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"height\", j.Height)\n\tpopulate(objectMap, \"label\", j.Label)\n\tpopulate(objectMap, \"quality\", j.Quality)\n\tpopulate(objectMap, \"width\", j.Width)\n\treturn json.Marshal(objectMap)\n}",
"func (v Attack) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson6601e8cdEncodeGithubComGoParkMailRu2018242GameServerTypes4(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v MoveCharacter) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson6601e8cdEncodeGithubComGoParkMailRu2018242GameServerTypes6(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (self *PhysicsP2) ToJSON() interface{}{\n return self.Object.Call(\"toJSON\")\n}",
"func (v AddWeapon) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson6601e8cdEncodeGithubComGoParkMailRu2018242GameServerTypes3(w, v)\n}",
"func (v PlayerEvent) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoMedia1(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v ReassignWeapons) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson6601e8cdEncodeGithubComGoParkMailRu2018242GameServerTypes9(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (w *WordScore) MarshalJSON() ([]byte, error) {\n\tstr := fmt.Sprintf(\"{\\\"%s\\\":%.1f}\", w.Word, w.Score)\n\treturn []byte(str), nil\n}",
"func (v Away) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer33(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v AttackingСharacter) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson6601e8cdEncodeGithubComGoParkMailRu2018242GameServerTypes5(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v Clock) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson3e8ab7adEncodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca16(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (g *Game) getPlayersJson() []byte {\n\tb, err := json.Marshal(g.Players)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn b\n}",
"func (v Mode) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer16(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v PlayerProperty) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoMedia(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v Attack) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson6601e8cdEncodeGithubComGoParkMailRu2018242GameServerTypes4(w, v)\n}",
"func (c *T) JSON() cast.JSON {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn cast.JSON{\n\t\t\"id\": c.ID,\n\t\t\"cardid\": c.Proto.ID,\n\t\t\"name\": c.Proto.Name,\n\t\t\"costs\": c.Proto.Costs.JSON(),\n\t\t\"text\": c.Proto.Text,\n\t\t\"username\": c.Username,\n\t\t\"image\": c.Proto.Image,\n\t\t\"type\": c.Proto.Type.String(),\n\t\t\"powers\": c.Proto.Powers.JSON(),\n\t}\n}",
"func (v ExportItem) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonB83d7b77EncodeGoplaygroundMyjson1(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (p PacketCapture) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"properties\", p.Properties)\n\treturn json.Marshal(objectMap)\n}",
"func (npc NPC) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(NewJSONNPC(npc))\n}",
"func (a AudioOverlay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"audioGainLevel\", a.AudioGainLevel)\n\tpopulate(objectMap, \"end\", a.End)\n\tpopulate(objectMap, \"fadeInDuration\", a.FadeInDuration)\n\tpopulate(objectMap, \"fadeOutDuration\", a.FadeOutDuration)\n\tpopulate(objectMap, \"inputLabel\", a.InputLabel)\n\tobjectMap[\"@odata.type\"] = \"#Microsoft.Media.AudioOverlay\"\n\tpopulate(objectMap, \"start\", a.Start)\n\treturn json.Marshal(objectMap)\n}",
"func (v RoomsOnlineMessage) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncode20191OPGPlus2InternalPkgModels10(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v EventPlayersCreated) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoMedia2(w, v)\n}",
"func (v EventInterstitialShown) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage74(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v captchaRule) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson795c59c6EncodeGrapeGuardRules6(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v RoomPlayer) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonD2b7633eEncode20191OPGPlus2InternalPkgModels11(w, v)\n}",
"func (v captchaRule) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson795c59c6EncodeGrapeGuardRules6(w, v)\n}",
"func (v Event) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson6601e8cdEncodeGithubComGoParkMailRu2018242GameServerTypes12(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (l LookingGlassOutput) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"command\", l.Command)\n\tpopulate(objectMap, \"output\", l.Output)\n\treturn json.Marshal(objectMap)\n}",
"func (l LiveOutput) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", l.ID)\n\tpopulate(objectMap, \"name\", l.Name)\n\tpopulate(objectMap, \"properties\", l.Properties)\n\tpopulate(objectMap, \"systemData\", l.SystemData)\n\tpopulate(objectMap, \"type\", l.Type)\n\treturn json.Marshal(objectMap)\n}",
"func (schedule Schedule) JSON() []byte {\n\tb, err := json.Marshal(&schedule)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\treturn b\n}",
"func JSON(data interface{}, args ...interface{}) string {\n\tw := Writer{\n\t\tOptions: ojg.DefaultOptions,\n\t\tWidth: 80,\n\t\tMaxDepth: 3,\n\t\tSEN: false,\n\t}\n\tw.config(args)\n\tb, _ := w.encode(data)\n\n\treturn string(b)\n}",
"func (v Element) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonB83d7b77EncodeGoplaygroundMyjson2(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v AttackingСharacter) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson6601e8cdEncodeGithubComGoParkMailRu2018242GameServerTypes5(w, v)\n}",
"func (v VideoOverlay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"audioGainLevel\", v.AudioGainLevel)\n\tpopulate(objectMap, \"cropRectangle\", v.CropRectangle)\n\tpopulate(objectMap, \"end\", v.End)\n\tpopulate(objectMap, \"fadeInDuration\", v.FadeInDuration)\n\tpopulate(objectMap, \"fadeOutDuration\", v.FadeOutDuration)\n\tpopulate(objectMap, \"inputLabel\", v.InputLabel)\n\tobjectMap[\"@odata.type\"] = \"#Microsoft.Media.VideoOverlay\"\n\tpopulate(objectMap, \"opacity\", v.Opacity)\n\tpopulate(objectMap, \"position\", v.Position)\n\tpopulate(objectMap, \"start\", v.Start)\n\treturn json.Marshal(objectMap)\n}",
"func (v Vertices) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker50(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (board *Board) MarshalJSON() ([]byte, error) {\n\tstate := make([]int, 0)\n\n\tfor i := 0; i < board.Len(); i++ {\n\t\tstate = append(state, board.GetTileAt(i))\n\t}\n\n\treturn json.Marshal(struct {\n\t\tBoard\n\t\tState []int `json:\"state\"`\n\t}{\n\t\tBoard: Board(*board),\n\t\tState: state,\n\t})\n}",
"func (v GuardRule) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson795c59c6EncodeGrapeGuardRules10(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (s Slots) JSON() string {\n\ttype t struct {\n\t\tAddress string `json:\"slot-owner\"`\n\t\tKey string `json:\"bls-public-key\"`\n\t\tStake string `json:\"actual-stake\"`\n\t}\n\ttype v struct {\n\t\tSlots []t `json:\"slots\"`\n\t}\n\tdata := v{}\n\tfor i := range s {\n\t\tnewData := t{\n\t\t\tcommon2.MustAddressToBech32(s[i].Address),\n\t\t\ts[i].BlsPublicKey.Hex(),\n\t\t\ts[i].Dec.String(),\n\t\t}\n\t\tdata.Slots = append(data.Slots, newData)\n\t}\n\tb, _ := json.Marshal(data)\n\treturn string(b)\n}",
"func (v Kick) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer20(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v Join) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer21(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v ReassignWeapons) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson6601e8cdEncodeGithubComGoParkMailRu2018242GameServerTypes9(w, v)\n}",
"func (d *Dump) MarshalJSON() ([]byte, error) {\n\td.mutex.RLock()\n\tdefer d.mutex.RUnlock()\n\n\tvar buffer bytes.Buffer\n\n\tbuffer.WriteString(`[`)\n\tfor i, item := range d.items {\n\t\tda, err := item.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbuffer.Write(da)\n\t\tif i != len(d.items)-1 {\n\t\t\tbuffer.WriteString(`,`)\n\t\t}\n\t}\n\tbuffer.WriteString(`]`)\n\n\treturn buffer.Bytes(), nil\n}",
"func (w *RandomWorld) BeingsToJSON(fileName string) {\n\tfi, _ := os.Create(fileName)\n\tdefer fi.Close()\n\tfz := NewWriter(fi)\n\te := NewEncoder(fz)\n\n\tif err := e.Encode(w.BeingList); err != nil {\n\t\tpanic(err)\n\t}\n}",
"func (v WSHotDepths) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson25363b2dEncodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi4(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (pm *PongMessage) Marshal() ([]byte, error) {\n\treturn json.Marshal(pm)\n}",
"func (v Post) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson5a72dc82EncodeGithubComTimRazumovTechnoparkDBAppModels6(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v PackoutRule) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson795c59c6EncodeGrapeGuardRules8(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (b Bot) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", b.Etag)\n\tpopulate(objectMap, \"id\", b.ID)\n\tpopulate(objectMap, \"kind\", b.Kind)\n\tpopulate(objectMap, \"location\", b.Location)\n\tpopulate(objectMap, \"name\", b.Name)\n\tpopulate(objectMap, \"properties\", b.Properties)\n\tpopulate(objectMap, \"sku\", b.SKU)\n\tpopulate(objectMap, \"tags\", b.Tags)\n\tpopulate(objectMap, \"type\", b.Type)\n\tpopulate(objectMap, \"zones\", b.Zones)\n\treturn json.Marshal(objectMap)\n}",
"func (lump *Game) Marshall() ([]byte, error) {\n\tvar buf bytes.Buffer\n\terr := binary.Write(&buf, binary.LittleEndian, lump.Header.LumpCount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, lumpHeader := range lump.Header.GameLumps {\n\t\tif err = binary.Write(&buf, binary.LittleEndian, lumpHeader); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tfor _, l := range lump.GameLumps {\n\t\tif err = binary.Write(&buf, binary.LittleEndian, l.Length); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err = binary.Write(&buf, binary.LittleEndian, l.Data); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn buf.Bytes(), err\n}",
"func (s *Siegfried) JSON() string {\n\tversion := config.Version()\n\tstr := fmt.Sprintf(\n\t\t\"{\\\"siegfried\\\":\\\"%d.%d.%d\\\",\\\"scandate\\\":\\\"%v\\\",\\\"signature\\\":\\\"%s\\\",\\\"created\\\":\\\"%v\\\",\\\"identifiers\\\":[\",\n\t\tversion[0], version[1], version[2],\n\t\ttime.Now().Format(time.RFC3339),\n\t\tconfig.SignatureBase(),\n\t\ts.C.Format(time.RFC3339))\n\tfor i, id := range s.ids {\n\t\tif i > 0 {\n\t\t\tstr += \",\"\n\t\t}\n\t\td := id.Describe()\n\t\tstr += fmt.Sprintf(\"{\\\"name\\\":\\\"%s\\\",\\\"details\\\":\\\"%s\\\"}\", d[0], d[1])\n\t}\n\tstr += \"],\"\n\treturn str\n}",
"func (v PostFull) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeGithubComMailcoursesTechnoparkDbmsForumGeneratedModels7(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v matchRule) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker19(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v ScoreboardAnswer) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncode20191OPGPlus2InternalPkgModels9(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v PlantainerShadowStatePieceSt) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson5bd79fa1EncodeMevericcoreMcplantainer4(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func JSONEncoder() Encoder { return jsonEncoder }",
"func (o *Echo) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(o.ToMap())\n}",
"func (v GetFwLeaderboardsCharactersOk) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson8cdad7c3EncodeGithubComCurzonjGoesiEsi1(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (k Kitten) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"eatsMiceYet\", k.EatsMiceYet)\n\tpopulate(objectMap, \"hisses\", k.Hisses)\n\tpopulate(objectMap, \"likesMilk\", k.LikesMilk)\n\tpopulate(objectMap, \"meows\", k.Meows)\n\tpopulate(objectMap, \"name\", k.Name)\n\treturn json.Marshal(objectMap)\n}",
"func (g *Group) MarshalJSON() ([]byte, error) {\n\tvals := g.toMap()\n\tvals[\"id\"] = g.ID\n\tvals[\"name\"] = g.Name\n\treturn json.Marshal(vals)\n}",
"func (self *PhysicsP2) ToJSONI(args ...interface{}) interface{}{\n return self.Object.Call(\"toJSON\", args)\n}",
"func (v GuardRule) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson795c59c6EncodeGrapeGuardRules10(w, v)\n}",
"func (v Pet) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson14a1085EncodeGithubComIamStubborNPetstoreDbModels1(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v Clock) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson3e8ab7adEncodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca16(w, v)\n}",
"func (v Part) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer12(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (b BastionSessionState) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"message\", b.Message)\n\tpopulate(objectMap, \"sessionId\", b.SessionID)\n\tpopulate(objectMap, \"state\", b.State)\n\treturn json.Marshal(objectMap)\n}",
"func (p Pet) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"name\", p.Name)\n\treturn json.Marshal(objectMap)\n}",
"func (v CaptureScreenshotReturns) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage98(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v Tab) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer6(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (h H264Layer) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"adaptiveBFrame\", h.AdaptiveBFrame)\n\tpopulate(objectMap, \"bFrames\", h.BFrames)\n\tpopulate(objectMap, \"bitrate\", h.Bitrate)\n\tpopulate(objectMap, \"bufferWindow\", h.BufferWindow)\n\tpopulate(objectMap, \"crf\", h.Crf)\n\tpopulate(objectMap, \"entropyMode\", h.EntropyMode)\n\tpopulate(objectMap, \"frameRate\", h.FrameRate)\n\tpopulate(objectMap, \"height\", h.Height)\n\tpopulate(objectMap, \"label\", h.Label)\n\tpopulate(objectMap, \"level\", h.Level)\n\tpopulate(objectMap, \"maxBitrate\", h.MaxBitrate)\n\tpopulate(objectMap, \"profile\", h.Profile)\n\tpopulate(objectMap, \"referenceFrames\", h.ReferenceFrames)\n\tpopulate(objectMap, \"slices\", h.Slices)\n\tpopulate(objectMap, \"width\", h.Width)\n\treturn json.Marshal(objectMap)\n}",
"func (v MoveCharacter) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson6601e8cdEncodeGithubComGoParkMailRu2018242GameServerTypes6(w, v)\n}",
"func (v VideoLayer) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"adaptiveBFrame\", v.AdaptiveBFrame)\n\tpopulate(objectMap, \"bFrames\", v.BFrames)\n\tpopulate(objectMap, \"bitrate\", v.Bitrate)\n\tpopulate(objectMap, \"frameRate\", v.FrameRate)\n\tpopulate(objectMap, \"height\", v.Height)\n\tpopulate(objectMap, \"label\", v.Label)\n\tpopulate(objectMap, \"maxBitrate\", v.MaxBitrate)\n\tpopulate(objectMap, \"slices\", v.Slices)\n\tpopulate(objectMap, \"width\", v.Width)\n\treturn json.Marshal(objectMap)\n}",
"func (v EventPipelineStageMove) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk3(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (v Quit) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer11(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}",
"func (f FirewallPacketCaptureParameters) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", f.ID)\n\tpopulate(objectMap, \"properties\", f.Properties)\n\treturn json.Marshal(objectMap)\n}",
"func (ts *TimeStats) JSON() string {\n\tout, _ := json.Marshal(ts)\n\tts.Total = 0\n\tts.Earliest = time.Time{}\n\tts.Latest = time.Time{}\n\treturn string(out)\n\n}",
"func (s *Strobe) MarshalJSON() ([]byte, error) {\n\tss := strobeJSON{\n\t\tCurFlags: s.curFlags,\n\t\tInitialized: s.initialized,\n\t\tI0: s.i0,\n\t\tPos: s.pos,\n\t\tPosBegin: s.posBegin,\n\t\tR: s.r,\n\t\tState: s.st,\n\t\tKeccakState: s.keccakState[:],\n\t}\n\n\treturn json.Marshal(ss)\n}",
"func (p PresetConfigurations) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"complexity\", p.Complexity)\n\tpopulate(objectMap, \"interleaveOutput\", p.InterleaveOutput)\n\tpopulate(objectMap, \"keyFrameIntervalInSeconds\", p.KeyFrameIntervalInSeconds)\n\tpopulate(objectMap, \"maxBitrateBps\", p.MaxBitrateBps)\n\tpopulate(objectMap, \"maxHeight\", p.MaxHeight)\n\tpopulate(objectMap, \"maxLayers\", p.MaxLayers)\n\tpopulate(objectMap, \"minBitrateBps\", p.MinBitrateBps)\n\tpopulate(objectMap, \"minHeight\", p.MinHeight)\n\treturn json.Marshal(objectMap)\n}",
"func (h H265VideoLayer) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"adaptiveBFrame\", h.AdaptiveBFrame)\n\tpopulate(objectMap, \"bFrames\", h.BFrames)\n\tpopulate(objectMap, \"bitrate\", h.Bitrate)\n\tpopulate(objectMap, \"frameRate\", h.FrameRate)\n\tpopulate(objectMap, \"height\", h.Height)\n\tpopulate(objectMap, \"label\", h.Label)\n\tpopulate(objectMap, \"maxBitrate\", h.MaxBitrate)\n\tpopulate(objectMap, \"slices\", h.Slices)\n\tpopulate(objectMap, \"width\", h.Width)\n\treturn json.Marshal(objectMap)\n}",
"func (uc *UseCase) JSON(indents ...int) []byte {\n\tindent := 0\n\tif 0 < len(indents) {\n\t\tindent = indents[0]\n\t}\n\treturn []byte(oj.JSON(uc, indent))\n}",
"func (g GroupByUserSession) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"groupByVariables\", g.GroupByVariables)\n\treturn json.Marshal(objectMap)\n}"
] | [
"0.7667663",
"0.7302632",
"0.7081352",
"0.7062559",
"0.7052415",
"0.66752076",
"0.66466886",
"0.65558296",
"0.6462651",
"0.62101954",
"0.6006036",
"0.5992634",
"0.5988495",
"0.5932444",
"0.5911325",
"0.57917476",
"0.5789904",
"0.57041484",
"0.5684057",
"0.5654009",
"0.56101006",
"0.5573966",
"0.5572276",
"0.55674344",
"0.55662125",
"0.5561787",
"0.5540052",
"0.55296487",
"0.55053085",
"0.55052906",
"0.5496268",
"0.54893845",
"0.54706454",
"0.5459874",
"0.5434539",
"0.5433846",
"0.5428858",
"0.5415543",
"0.5414677",
"0.5409849",
"0.53984565",
"0.53901875",
"0.53895694",
"0.53842723",
"0.5381989",
"0.53780806",
"0.5368205",
"0.5348857",
"0.5344145",
"0.5343152",
"0.5342633",
"0.5326904",
"0.53220576",
"0.5318843",
"0.53135026",
"0.5311345",
"0.530165",
"0.5298907",
"0.5298351",
"0.52945846",
"0.52932626",
"0.5289152",
"0.52872586",
"0.5282641",
"0.5276653",
"0.5269604",
"0.5267912",
"0.52669287",
"0.5254921",
"0.5249731",
"0.5246815",
"0.5245157",
"0.52392656",
"0.5237533",
"0.5236252",
"0.5233493",
"0.52314055",
"0.52276117",
"0.5226555",
"0.5225285",
"0.52240443",
"0.52232945",
"0.5220258",
"0.52200603",
"0.5218975",
"0.52121425",
"0.5208309",
"0.5203073",
"0.52015847",
"0.52010196",
"0.52007407",
"0.5200602",
"0.5199482",
"0.51990753",
"0.5189869",
"0.51878697",
"0.5183088",
"0.51796514",
"0.51742053",
"0.5172185"
] | 0.72168684 | 2 |
GetOrCalculateRightScore returns game score for saven games or calcukates new score | func (g *Game) GetOrCalculateRightScore() int {
if g.RightScore == 0 {
right, _ := g.GameScore()
return int(right)
}
return g.RightScore
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (g *Game) GetOrCalculateLeftScore() int {\n\tif g.LeftScore == 0 {\n\t\t_, left := g.GameScore()\n\t\treturn int(left)\n\t}\n\treturn g.LeftScore\n}",
"func (g *Game) UpdateScore() error {\n\tswitch g.Winner {\n\tcase RIGHT:\n\t\tright, _ := g.GameScore()\n\t\tg.RightScore = int(right)\n\t\tg.LeftScore = -int(right)\n\t\treturn nil\n\tcase LEFT:\n\t\t_, left := g.GameScore()\n\t\tg.RightScore = -int(left)\n\t\tg.LeftScore = int(left)\n\t\treturn nil\n\tcase DRAW:\n\t\tscore := g.TournamentTable.Tournament.GameScore / 2\n\t\tg.RightScore = int(score)\n\t\tg.LeftScore = int(score)\n\t\treturn nil\n\tdefault:\n\t\treturn errors.New(\"no winner in this game\")\n\t}\n}",
"func calcScore2(opp string, me string) int {\n\tif me == \"X\" {\n\t\t/*\n\t\t* LOSE\n\t\t* A -> Rock 3\n\t\t* B -> Paper 1\n\t\t* C -> Scissor 2\n\t\t */\n\t\tswitch opp {\n\t\tcase \"A\":\n\t\t\treturn LOSE + 3\n\t\tcase \"B\":\n\t\t\treturn LOSE + 1\n\t\tcase \"C\":\n\t\t\treturn LOSE + 2\n\t\tdefault:\n\t\t\treturn 0\n\t\t}\n\t} else if me == \"Y\" {\n\t\tswitch opp {\n\t\tcase \"A\":\n\t\t\treturn TIE + 1\n\t\tcase \"B\":\n\t\t\treturn TIE + 2\n\t\tcase \"C\":\n\t\t\treturn TIE + 3\n\t\tdefault:\n\t\t\treturn 0\n\t\t}\n\t} else {\n\t\t/*\n\t\t* WIN\n\t\t* A -> Rock 2\n\t\t* B -> Paper 3\n\t\t* C -> Scissor 1\n\t\t */\n\t\tswitch opp {\n\t\tcase \"A\":\n\t\t\treturn WIN + 2\n\t\tcase \"B\":\n\t\t\treturn WIN + 3\n\t\tcase \"C\":\n\t\t\treturn WIN + 1\n\t\tdefault:\n\t\t\treturn 0\n\t\t}\n\t}\n}",
"func (g *Game) GameScore() (uint, uint) {\n\tleft := round(float64(g.TournamentTable.Tournament.GameScore) * g.gameLeftScoreFactor())\n\treturn g.TournamentTable.Tournament.GameScore - left, left\n}",
"func (g *Game) Score() int {\n\trollIndex := 0\n\tfor frame := 0; frame < frameNumberPerGame; frame++ {\n\t\tif g.isStrike(rollIndex) {\n\t\t\tg.score += cleanPinNumber + g.getStrikeBonus(rollIndex)\n\t\t\trollIndex++\n\t\t} else if g.isSpare(rollIndex) {\n\t\t\tg.score += cleanPinNumber + g.getSpareBonus(rollIndex)\n\t\t\trollIndex += 2\n\t\t} else {\n\t\t\tg.score += g.getFrameScore(rollIndex)\n\t\t\trollIndex += 2\n\t\t}\n\n\t}\n\treturn g.score\n}",
"func (sqlite *SQLiteDB) OveralScore(from time.Time, to time.Time) (int32, error) {\n\tvar score int32\n\terr := sqlite.db.Get(&score,\n\t\t`SELECT round(AVG(rating * weight)/AVG($1 * weight)*100) as score\n\t\tFROM ratings\n\t\tINNER JOIN tickets ON ratings.ticket_id=tickets.id\n\t\tINNER JOIN rating_categories ON ratings.rating_category_id=rating_categories.id\n\t\tWHERE tickets.created_at BETWEEN $2 AND $3;`,\n\t\tdb.MaxRating, from.Format(db.SimpleDateFormat), to.Format(db.SimpleDateFormat))\n\n\tif err != nil {\n\t\treturn score, err\n\t}\n\treturn score, err\n}",
"func (game *Game) calculateGameWinner() {\n\twinningPlayer := 0\n\twinningTotal := MaxPossibleScore\n\n\tfor i := range game.players {\n\t\tplayerTotal := game.players[i].calcuateTotalGameScore()\n\n\t\tif playerTotal < winningTotal {\n\t\t\twinningTotal = playerTotal\n\t\t\twinningPlayer = i\n\t\t}\n\t}\n\n\tgame.gameWinner = winningPlayer\n}",
"func (b *Board) Score() int {\n\tif !b.Finish {\n\t\treturn 0\n\t}\n\n\t// yaku ? or finish move\n\t// b.HasYaku() //TODO: yaku score\n\ts := b.LastAttackMove.Attack.GetScore()\n\tif b.LastAttackMove.FaceDown && b.LastAttackMove.Block == b.LastAttackMove.Attack {\n\t\ts = s * 2\n\t}\n\treturn s\n}",
"func GetScorer(home bool, game responses.FantasyGame) *Scorer {\n\tif home {\n\t\treturn &Scorer{\n\t\t\tTeam: game.Home,\n\t\t\tScore: game.HomeScore.Score.Value,\n\t\t}\n\t}\n\n\treturn &Scorer{\n\t\tTeam: game.Away,\n\t\tScore: game.AwayScore.Score.Value,\n\t}\n}",
"func (d *diff) CalcScore(key interface{}) float64 {\n\treturn 0\n}",
"func (g *G) Score() int {\n\t/* Fill in this Function */\n\treturn 0\n}",
"func (b *Board) score() Player {\n\tstatic_eval := b.evaluate_static()\n\tif static_eval != NoPlayer {\n\t\treturn static_eval\n\t}\n\n\tif len(b.vacantSquares()) == 0 {\n\t\treturn NoPlayer\n\t}\n\n\tbranch_evals := func() []Player {\n\t\tout := []Player{}\n\t\tfor _, branch := range b.possibleMoves() {\n\t\t\tout = append(out, branch.score())\n\t\t}\n\t\treturn out\n\t}()\n\n\tswitch b.NextPlayer() {\n\tcase Player1:\n\t\tif playerInList(Player1, branch_evals) {\n\t\t\treturn Player1\n\t\t} else if playerInList(NoPlayer, branch_evals) {\n\t\t\treturn NoPlayer\n\t\t} else {\n\t\t\treturn Player2\n\t\t}\n\tcase Player2:\n\t\tif playerInList(Player2, branch_evals) {\n\t\t\treturn Player2\n\t\t} else if playerInList(NoPlayer, branch_evals) {\n\t\t\treturn NoPlayer\n\t\t} else {\n\t\t\treturn Player1\n\t\t}\n\t}\n\n\treturn NoPlayer\n}",
"func (g *Game) GetScore() int {\n\treturn g.score\n}",
"func (s *State) ApplyScore(north, south, west, east string, nsScore, weScore int) error {\n\tseating := s.CurrentRound().FindSeating(north, south, west, east)\n\tif seating == nil {\n\t\treturn fmt.Errorf(\"Couldn't find a seating with these players: N %s, S %s, W %s, E %s\", north, south, west, east)\n\t}\n\n\tseating.Finished = true\n\tseating.NSScore = nsScore\n\tseating.WEScore = weScore\n\tif nsScore >= weScore {\n\t\tseating.NSWins = true\n\t}\n\n\treturn nil\n}",
"func (p *Player) GetScore() (score int) {\n\thasAce := false\n\tfor _, c := range p.DealtCards {\n\t\tif c.Rank == deck.Ace {\n\t\t\thasAce = true\n\t\t}\n\t\tscore += Scoring[c.Rank]\n\t}\n\tif hasAce {\n\t\tif score+10 <= blackjack {\n\t\t\tscore += 10\n\t\t}\n\t}\n\treturn score\n}",
"func (game *Game) Score() int {\n\treturn game.score\n}",
"func (va VAScore) Score() float64 {\n\tif va.Err != nil {\n\t\treturn 0.0\n\t}\n\treturn va.Achieved - va.Expected\n}",
"func (b Engine) GetScore() float64 {\n\treturn b.Score\n}",
"func (eng *Engine) Score() int32 {\n\treturn Evaluate(eng.Position).GetCentipawnsScore() * eng.Position.Us().Multiplier()\n}",
"func (t *Table) ScoreRound() []int {\n\tallPoints := 26\n\troundScores := make([]int, len(t.players))\n\tshotMoon := false\n\tshooter := -1\n\tfor i := 0; i < len(t.players); i++ {\n\t\troundScores[i] = t.players[i].CalculateScore()\n\t\tif roundScores[i] == allPoints {\n\t\t\tshotMoon = true\n\t\t\tshooter = i\n\t\t}\n\t}\n\tif shotMoon {\n\t\tfor i := 0; i < len(t.players); i++ {\n\t\t\tif i == shooter {\n\t\t\t\troundScores[i] = 0\n\t\t\t} else {\n\t\t\t\troundScores[i] = allPoints\n\t\t\t}\n\t\t}\n\t}\n\treturn roundScores\n}",
"func (c *CommitResult) GetScore() *float64 {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.Score\n}",
"func (g *Game) getFrameScore(rollIndex int) int {\n\treturn g.rolls[rollIndex] + g.rolls[rollIndex+1]\n}",
"func (eng *Engine) cachedScore(e *hashEntry) int32 {\n\tif e.kind&hasStatic == 0 {\n\t\te.kind |= hasStatic\n\t\te.static = int16(eng.Score())\n\t}\n\treturn int32(e.static)\n}",
"func (r *Rule) GetScore(colname string, row dur.Row) int64 {\n\tcell := row.Col(colname)\n\tvar res int64\n\tres = r.featureRaw.Get(colname + \".default\").Int()\n\tbin := r.featureRaw.Get(colname + \".bin\") //gjson.GetBytes(r.featureRaw, colname+\".bin\")\n\tbintype := r.featureRaw.Get(colname + \".bintype\").String()\n\t// pre logic\n\tpre := r.featureRaw.Get(colname + \".pre\").String()\n\tpreScore, need, error := ParsePre(pre, row)\n\tif error != nil {\n\t\tlog.Println(error)\n\t}\n\tif need {\n\t\treturn preScore\n\t}\n\n\t// if number\n\tif bintype == \"math\" {\n\t\tbin.ForEach(func(k, v gjson.Result) bool {\n\t\t\tn, err := strconv.ParseFloat(cell, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn false // if cannot conv to flat64 for example null then break and use default value\n\t\t\t}\n\t\t\tif mathinterval.Get(k.String()).Hit(n) {\n\t\t\t\tres = v.Int()\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t}\n\n\tif bintype == \"text\" {\n\t\tbin.ForEach(func(k, v gjson.Result) bool {\n\t\t\tif k.String() == cell {\n\t\t\t\tres = v.Int()\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t}\n\n\treturn res\n}",
"func (v *Vote) Score(r []int) int {\n\tif DumbScore {\n\t\treturn v.DumbScore(r)\n\t}\n\th := make(map[int]int) //map candidates to index\n\tfor k, v := range v.C {\n\t\tki, err := strconv.Atoi(k)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\th[v] = ki\n\t}\n\n\tres := 0\n\tfor i := 0; i < len(r); i++ {\n\t\tif r[i] == -1 {\n\t\t\tcontinue\n\t\t}\n\t\tw := (r[i] - len(r)/2)\n\t\tif w < 0 {\n\t\t\tw = -w\n\t\t\tw += len(r) - r[i]\n\t\t} else {\n\t\t\tw++\n\t\t}\n\t\trx := (i - h[r[i]]) * w\n\t\tif rx < 0 {\n\t\t\tres += -rx\n\t\t} else {\n\t\t\tres += rx\n\t\t}\n\t}\n\treturn res\n}",
"func (el *gameStruct) Score() int {\n\treturn el.points\n}",
"func Score(x, y float64) int {\n\tswitch dist := math.Sqrt(x*x + y*y); {\n\tcase dist <= inner:\n\t\treturn 10\n\tcase dist <= middle:\n\t\treturn 5\n\tcase dist <= outer:\n\t\treturn 1\n\tdefault:\n\t\treturn 0\n\t}\n}",
"func (m *SecureScoreControlProfile) GetMaxScore()(*float64) {\n return m.maxScore\n}",
"func (m *SecureScoreControlProfile) GetMaxScore()(*float64) {\n val, err := m.GetBackingStore().Get(\"maxScore\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*float64)\n }\n return nil\n}",
"func (move Move) Score() uint16 {\n\treturn uint16(move & 0xffff)\n}",
"func CalculateMatchScore(region string, summoners []rgapi.Summoner) (*MatchScore, error) {\n\tif len(summoners) != PlayersPerMatch {\n\t\treturn nil, errors.New(fmt.Sprint(\n\t\t\t\"Calculating match score requires \", PlayersPerMatch, \" players, was given \", len(summoners)))\n\t}\n\n\t//For each summoner, get the best game they have in their recent history\n\t//TODO: Save timestamp of most recently checked games in DB or Redis\n\tplayerScores := make([]*PlayerScore, len(summoners))\n\tfor i := 0; i < len(summoners); i++ {\n\t\tplayerScore, err := PlayerScoreBestRecent(region, summoners[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tplayerScores[i] = playerScore\n\t}\n\n\t//Create teams and match score objects\n\tblueTeamScore := TeamScore{\n\t\tTop: playerScores[0],\n\t\tJungle: playerScores[1],\n\t\tMid: playerScores[2],\n\t\tBottom: playerScores[3],\n\t\tSupport: playerScores[4],\n\t\tScore: playerScores[0].Score + playerScores[1].Score + playerScores[2].Score + playerScores[3].Score + playerScores[4].Score,\n\t}\n\tblueTeamScore.ScoreString = fmt.Sprintf(\"%.2f\", blueTeamScore.Score)\n\tredTeamScore := TeamScore{\n\t\tTop: playerScores[5],\n\t\tJungle: playerScores[6],\n\t\tMid: playerScores[7],\n\t\tBottom: playerScores[8],\n\t\tSupport: playerScores[9],\n\t\tScore: playerScores[5].Score + playerScores[6].Score + playerScores[7].Score + playerScores[8].Score + playerScores[9].Score,\n\t}\n\tredTeamScore.ScoreString = fmt.Sprintf(\"%.2f\", redTeamScore.Score)\n\tmatchScore := MatchScore{\n\t\tBlueTeam: blueTeamScore,\n\t\tRedTeam: redTeamScore,\n\t}\n\n\t//Pick the winner\n\t//TODO: Do this by user-selected team name instead of Blue/Red\n\tif blueTeamScore.Score > redTeamScore.Score {\n\t\tmatchScore.WinningSide = BlueTeam\n\t\tmatchScore.WinningTeam = \"Blue\"\n\t} else if redTeamScore.Score > blueTeamScore.Score {\n\t\tmatchScore.WinningSide = RedTeam\n\t\tmatchScore.WinningTeam = \"Red\"\n\t}\n\n\treturn &matchScore, nil\n}",
"func (ap *AnimeParser) getScore(eachTop *goquery.Selection) float64 {\n\tscore := eachTop.Find(\"td:nth-of-type(3)\").Text()\n\tscore = strings.TrimSpace(strings.Replace(score, \"N/A\", \"\", -1))\n\treturn utils.StrToFloat(score)\n}",
"func (g *Game) GetOpponentScore() int {\n\treturn g.opponentScore\n}",
"func Score(x, y float64) int {\n\tdistance := math.Sqrt(math.Pow(x, 2) + math.Pow(y, 2))\n\n\tswitch {\n\tcase distance <= 1:\n\t\treturn 10\n\tcase distance <= 5:\n\t\treturn 5\n\tcase distance <= 10:\n\t\treturn 1\n\tdefault:\n\t\treturn 0\n\t}\n}",
"func (h handler) GetScore(c echo.Context) error {\n\tvar scoreRequest ScoreRequest\n\n\tif err := c.Bind(&scoreRequest); err != nil {\n\t\treturn c.JSON(http.StatusBadRequest, err)\n\t}\n\n\tsnapshotScoreResponse, err := getScore(scoreRequest)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, err)\n\t}\n\n\treturn c.JSON(http.StatusOK, snapshotScoreResponse)\n}",
"func UpdateScore(c *fiber.Ctx) {\n\tShopID := c.Params(\"shop_id\")\n\tUserID := userIDF(c.Get(\"token\"))\n\n\tvar Data ScoreStruct\n\n\tif errorParse := c.BodyParser(&Data); errorParse != nil {\n\t\tfmt.Println(\"Error parsing data\", errorParse)\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Error al parsear información\"})\n\t\tc.Status(400)\n\t\treturn\n\t}\n\n\tif Data.Score <= 0 {\n\t\tfmt.Println(\"score can't be empty\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Score can't be empty\"})\n\t\tc.Status(400)\n\t\treturn\n\t}\n\n\tvar Score ScoreSQL\n\n\t_, ErrorUpdateScoreUser := sq.Update(\"shop_score_users\").\n\t\tSet(\"score\", Data.Score).\n\t\tWhere(\"user_id = ? AND shop_id = ?\", UserID, ShopID).\n\t\tRunWith(database).\n\t\tExec()\n\n\tif ErrorUpdateScoreUser != nil {\n\t\tfmt.Println(\"Error to update score\", ErrorUpdateScoreUser)\n\t}\n\n\tErrorScore := sq.Select(\n\t\t\"AVG(score) as score\",\n\t).\n\t\tFrom(\"shop_score_users\").\n\t\tWhere(\"shop_id = ?\", ShopID).\n\t\tRunWith(database).\n\t\tQueryRow().\n\t\tScan(\n\t\t\t&Score.Score,\n\t\t)\n\n\tif ErrorScore != nil {\n\t\tfmt.Println(ErrorScore, \"Error get score\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with get score\"})\n\t\tc.SendStatus(400)\n\t\treturn\n\t}\n\n\tqueryUpdateValue := sq.Update(\"shop\")\n\n\tScoreFloat, _ := strconv.ParseFloat(Score.Score.String, 64)\n\n\tNewScore := fmt.Sprintf(\"%.0f\", ScoreFloat)\n\n\t_, ErrorUpdateScoreShop := queryUpdateValue.\n\t\tSet(\"score_shop\", NewScore).\n\t\tWhere(\"shop_id = ? \", ShopID).\n\t\tRunWith(database).\n\t\tExec()\n\n\tif ErrorUpdateScoreShop != nil {\n\t\tfmt.Println(ErrorUpdateScoreShop, \"Problem with update score\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with update score\"})\n\t\tc.SendStatus(500)\n\t\treturn\n\t}\n\n\tc.JSON(SuccessResponse{MESSAGE: \"Calificación actualizada\"})\n}",
"func (s PositionEvaluator) Evaluate(p *position.Position) float64 {\n\t// calculate initial material\n\tmaterial := p.GetMaterial()\n\tpceCount := p.GetPieceCount()\n\tpceList := p.GetPieceList()\n\n\tscore := material[position.WHITE] - material[position.BLACK]\n\n\t//calculate\n\t//piece\n\t//squares\n\tpce := position.PwP\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore += pawnTable[position.SQ64(sq120)]\n\t}\n\n\tpce = position.PbP\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore -= pawnTable[mirror64[position.SQ64(sq120)]]\n\t}\n\n\tpce = position.PwN\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore += knightTable[position.SQ64(sq120)]\n\t}\n\n\tpce = position.PbN\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore -= knightTable[mirror64[position.SQ64(sq120)]]\n\t}\n\n\tpce = position.PwB\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore += bishopTable[position.SQ64(sq120)]\n\t}\n\n\tpce = position.PbB\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore -= bishopTable[mirror64[position.SQ64(sq120)]]\n\t}\n\n\tpce = position.PwR\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore += rookTable[position.SQ64(sq120)]\n\t}\n\n\tpce = position.PbR\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore -= rookTable[mirror64[position.SQ64(sq120)]]\n\t}\n\n\treturn float64(score)\n}",
"func (o *SecureScore) GetCurrentScore() AnyOfnumberstringstring {\n\tif o == nil || o.CurrentScore == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret\n\t}\n\treturn *o.CurrentScore\n}",
"func (b FirstEvaluator) Evaluate(pos *game.Position) float32 {\n\tigo, winner := pos.GameOver()\n\tif igo {\n\t\treturn winner.EvaluationWin()\n\t}\n\t// Theory:\n\t// * Winning subboards is good\n\t// * Number of legal moves is good(ish)\n\t// * Winning subboards relative to win condition - e.g. xor bigboard with wc and check\n\n\tbbSM := pos.BigBoard(pos.SideToMove)\n\n\t// calculate lowest mse with a win condition on a board\n\tbestMSESM := 1000\n\tmseSM := 0\n\tfor _, wc := range game.WinConditions {\n\t\tmseSM = bits.OnesCount32(wc ^ bbSM)\n\t\tif mseSM < bestMSESM {\n\t\t\tbestMSESM = mseSM\n\t\t}\n\t}\n\tfMseSM := float32(mseSM) / 9\n\n\t// calculate number of legal moves\n\tnlm := float32(pos.CountLegalMoves())\n\n\t// number of won subboards\n\tnwbbSM := float32(bits.OnesCount32(bbSM)) / 9\n\n\t// ---------------------------------------------\n\n\tbbSMO := pos.BigBoard(pos.SideToMove.Other())\n\n\t// calculate lowest mse with a win condition on a board\n\tbestMSESMO := 1000\n\tmseSMO := 0\n\tfor _, wc := range game.WinConditions {\n\t\tmseSMO = bits.OnesCount32(wc ^ bbSMO)\n\t\tif mseSMO < bestMSESMO {\n\t\t\tbestMSESMO = mseSM\n\t\t}\n\t}\n\tfMseSMO := float32(mseSMO) / 9\n\n\t// number of won subboards\n\tnwbbSMO := float32(bits.OnesCount32(bbSMO)) / 9\n\n\tvalue := .00002*nlm + (-0.08)*(fMseSM-fMseSMO) + 0.04*(nwbbSM-nwbbSMO)\n\treturn pos.SideToMove.EvaluationCoefficient() * value\n}",
"func (s *Scorer) subtractScore(appID marathon.AppID) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tvar ok bool\n\tvar score *Score\n\tif score, ok = s.scores[appID]; !ok {\n\t\treturn\n\t}\n\n\tscore.score -= s.ScaleDownScore\n}",
"func ComputeScore(dir int, order elevio.ButtonEvent, atFloor int, idle bool) int {\n\tN := numFloors - 1\n\td := int(math.Abs(float64(atFloor - order.Floor)))\n\tif idle {\n\t\treturn (N + 3) - d\n\t}\n\t//towards call\n\tif ((dir == 1) == (order.Floor > atFloor)) && ((dir == 1) == (order.Floor >= atFloor)) {\n\t\tif order.Button == 0 { //same dir button\n\t\t\treturn (N + 2) - d\n\t\t} else if order.Button == 1 { //opposite dir button\n\t\t\treturn (N + 1) - d\n\t\t}\n\t}\n\t//away from call\n\treturn 1\n}",
"func (room Room) GetScore() []int {\n\tvar scoreList []int\n\tfor _, player := range room.Players {\n\t\tscoreList = append(scoreList, player.Credit)\n\t}\n\treturn scoreList\n}",
"func (m *LogLoss) Score() float64 {\n\tm.mu.RLock()\n\tlogsum := m.logsum\n\tweight := m.weight\n\tm.mu.RUnlock()\n\n\tif weight > 0 {\n\t\treturn -logsum / weight\n\t}\n\treturn -math.Log(m.epsilon)\n}",
"func GetScore(res http.ResponseWriter, req *http.Request) {\n\tswitch req.Method {\n\n\t}\n}",
"func (d *Dispatcher) calScore(numReqs, restSpace int, avgResponseTime float) score int {\n\t//\n\treturn\n}",
"func (o *MicrosoftGraphControlScore) GetScoreOk() (AnyOfnumberstringstring, bool) {\n\tif o == nil || o.Score == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret, false\n\t}\n\treturn *o.Score, true\n}",
"func (o *MicrosoftGraphControlScore) GetScore() AnyOfnumberstringstring {\n\tif o == nil || o.Score == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret\n\t}\n\treturn *o.Score\n}",
"func (game *Game) calculateRoundWinner() {\n\tlowestScoreIndex := 0 //default to first player.. incase they all have the same score\n\tlowestScore := MaxRoundScore\n\n\tfor i := range game.players {\n\t\tif game.players[i].roundScores[game.roundIndex] < lowestScore {\n\t\t\tlowestScoreIndex = i\n\t\t\tlowestScore = game.players[i].roundScores[game.roundIndex]\n\t\t}\n\t}\n\n\tgame.roundWinner[game.roundIndex] = lowestScoreIndex\n}",
"func (ms MatchScore) CalculateFinalScore(match Match) float32 {\n\taverage := match.AverageScore()\n\n\tgame := match.Game()\n\n\tif average == float32(math.Inf(1)) {\n\t\tms.FinalScore = 100\n\t} else if ms.IsWinner {\n\t\tms.FinalScore = (ms.BaseScore / average) * 110\n\t} else {\n\t\tms.FinalScore = ms.BaseScore / average * 100\n\t}\n\n\tms.FinalScore = (game.ComplexityRating / 5) * ms.FinalScore\n\n\tdbmap.Update(&ms)\n\treturn ms.FinalScore\n}",
"func CreatePlayerScore(gameName string, kills int, deaths int, assists int, cs int, tripleKills int, quadraKills int, pentaKills int) *PlayerScore {\n\tscore := PlayerScore{\n\t\tSummonerName: gameName,\n\t\tKills: float32(kills) * PointValues[KillsString],\n\t\tDeaths: float32(deaths) * PointValues[DeathsString],\n\t\tAssists: float32(assists) * PointValues[AssistsString],\n\t\tCS: float32(cs) * PointValues[CSString],\n\t\tTripleKills: float32(tripleKills) * PointValues[TripleKillsString],\n\t\tQuadraKills: float32(quadraKills) * PointValues[QuadraKillsString],\n\t\tPentakills: float32(pentaKills) * PointValues[PentakillsString],\n\t}\n\tscore.CSString = fmt.Sprintf(\"%.2f\", score.CS)\n\n\t//Bonus points for getting at least 10 kills/assists in the same game\n\tif kills+assists >= 10 {\n\t\tscore.TenKA = PointValues[TenKAString]\n\t}\n\n\tscore.Score = score.Kills + score.Deaths + score.Assists + score.CS + score.TenKA + score.TripleKills +\n\t\tscore.QuadraKills + score.Pentakills\n\tscore.ScoreString = fmt.Sprintf(\"%.2f\", score.Score)\n\n\treturn &score\n}",
"func (f *FileSystemPlayerStore) GetPlayerScore(name string) int {\n\n\tplayer := f.GetLeague().Find(name)\n\n\tif player != nil {\n\t\treturn player.Wins\n\t}\n\n\treturn 0\n}",
"func SetScore(c *fiber.Ctx) {\n\tShopID := c.Params(\"shop_id\")\n\tUserID := userIDF(c.Get(\"token\"))\n\n\tvar Data ScoreStruct\n\n\tif errorParse := c.BodyParser(&Data); errorParse != nil {\n\t\tfmt.Println(\"Error parsing data\", errorParse)\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Error al parsear información\"})\n\t\tc.Status(400)\n\t\treturn\n\t}\n\n\tif Data.Score <= 0 {\n\t\tfmt.Println(\"score can't be empty\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Score can't be empty\"})\n\t\tc.Status(400)\n\t\treturn\n\t}\n\n\tvar Score ScoreSQL\n\tvar Response ResponseScore\n\n\t_, errorInsert := sq.Insert(\"shop_score_users\").\n\t\tColumns(\n\t\t\t\"user_id\",\n\t\t\t\"shop_id\",\n\t\t\t\"score\",\n\t\t).\n\t\tValues(\n\t\t\tUserID,\n\t\t\tShopID,\n\t\t\tData.Score,\n\t\t).\n\t\tRunWith(database).\n\t\tExec()\n\n\tif errorInsert != nil {\n\t\tfmt.Println(\"Error to save score\", errorInsert)\n\t}\n\n\tErrorScore := sq.Select(\n\t\t\"AVG(score) as score\",\n\t).\n\t\tFrom(\"shop_score_users\").\n\t\tWhere(\"shop_id = ?\", ShopID).\n\t\tRunWith(database).\n\t\tQueryRow().\n\t\tScan(\n\t\t\t&Score.Score,\n\t\t)\n\n\tif ErrorScore != nil {\n\t\tfmt.Println(ErrorScore, \"Error get score\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with get score\"})\n\t\tc.SendStatus(400)\n\t\treturn\n\t}\n\n\tqueryUpdateValue := sq.Update(\"shop\")\n\n\tScoreFloat, _ := strconv.ParseFloat(Score.Score.String, 64)\n\n\tNewScore := fmt.Sprintf(\"%.0f\", ScoreFloat)\n\n\t_, ErrorUpdateOffer := queryUpdateValue.\n\t\tSet(\"score_shop\", NewScore).\n\t\tWhere(\"shop_id = ? \", ShopID).\n\t\tRunWith(database).\n\t\tExec()\n\n\tif ErrorUpdateOffer != nil {\n\t\tfmt.Println(ErrorUpdateOffer, \"Problem with update score\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with update score\"})\n\t\tc.SendStatus(500)\n\t\treturn\n\t}\n\n\tResponse.Score = &NewScore\n\n\tc.JSON(Response)\n}",
"func (m *PlayerMutation) Score() (r int, exists bool) {\n\tv := m.score\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}",
"func (r Round)countScore(players map[string]*Player, master *Player,countInTotal,countBadAnswer bool)(map[string]int,map[string]*DetailScore){\n\troundScore := make(map[string]int,len(players))\n\tdetailScore := make(map[string]*DetailScore,len(players))\n\tfor _,p := range players {\n\t\troundScore[p.Name] = 0\n\t\tdetailScore[p.Name] = &DetailScore{false,0,0}\n\t}\n\tfor playerID,vote := range r.votes {\n\t\tname := players[playerID].Name\n\t\tif r.playersDefinition[vote].isCorrect {\n\t\t\tif countInTotal {\n\t\t\t\tplayers[playerID].Score+=2\n\t\t\t}\n\t\t\troundScore[name] += 2\n\t\t\tg := detailScore[name]\n\t\t\tg.GoodDef = true\n\t\t}else{\n\t\t\tidDefinitionPlayer := r.playersDefinition[vote].playerId\n\t\t\tif countInTotal {\n\t\t\t\tplayers[idDefinitionPlayer].Score++\n\t\t\t}\n\t\t\troundScore[players[idDefinitionPlayer].Name] ++\n\t\t\tdetailScore[players[idDefinitionPlayer].Name].VotePoint++\n\t\t\t// Point bad response for master\n\t\t\tif countBadAnswer {\n\t\t\t\tif countInTotal {\n\t\t\t\t\tmaster.Score++\n\t\t\t\t}\n\t\t\t\troundScore[master.Name] ++\n\t\t\t\tdetailScore[master.Name].ErrorPoint++\n\t\t\t}\n\t\t}\n\t}\n\treturn roundScore,detailScore\n}",
"func (solution Solution) Score() int {\n\tscore := 0\n\tfor _, order := range solution {\n\t\tscore += order.score\n\t}\n\n\treturn score\n}",
"func (p *Password) GetScore() int {\n\treturn p.Score\n}",
"func Score(c *fiber.Ctx) {\n\tShopID := c.Params(\"shop_id\")\n\tUserID := c.Params(\"user_id\")\n\tvar Score ScoreSQL\n\tvar Response ResponseScore\n\n\tErrorScore := sq.Select(\n\t\t\"AVG(score) as score\",\n\t).\n\t\tFrom(\"shop_score_users\").\n\t\tWhere(\"shop_id = ? AND user_id = ?\", ShopID, UserID).\n\t\tRunWith(database).\n\t\tQueryRow().\n\t\tScan(\n\t\t\t&Score.Score,\n\t\t)\n\n\tif ErrorScore != nil {\n\t\tfmt.Println(ErrorScore, \"Error get score\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with get score\"})\n\t\tc.SendStatus(400)\n\t\treturn\n\t}\n\n\tResponse.Score = &Score.Score.String\n\n\tc.JSON(Response)\n}",
"func (pl *AvailabilityNodePriority) Score(ctx context.Context, args interface{}, states *state.State, feasiblePods []int32, key types.NamespacedName, podID int32) (uint64, *state.Status) {\n\tlogger := logging.FromContext(ctx).With(\"Score\", pl.Name())\n\tvar score uint64 = 0\n\n\tspreadArgs, ok := args.(string)\n\tif !ok {\n\t\tlogger.Errorf(\"Scoring args %v for priority %q are not valid\", args, pl.Name())\n\t\treturn 0, state.NewStatus(state.Unschedulable, ErrReasonInvalidArg)\n\t}\n\n\tskewVal := state.AvailabilityNodePriorityArgs{}\n\tdecoder := json.NewDecoder(strings.NewReader(spreadArgs))\n\tdecoder.DisallowUnknownFields()\n\tif err := decoder.Decode(&skewVal); err != nil {\n\t\treturn 0, state.NewStatus(state.Unschedulable, ErrReasonInvalidArg)\n\t}\n\n\tif states.Replicas > 0 { //need at least a pod to compute spread\n\t\tvar skew int32\n\n\t\t_, nodeName, err := states.GetPodInfo(state.PodNameFromOrdinal(states.StatefulSetName, podID))\n\t\tif err != nil {\n\t\t\treturn score, state.NewStatus(state.Error, ErrReasonNoResource)\n\t\t}\n\n\t\tcurrentReps := states.NodeSpread[key][nodeName] //get #vreps on this node\n\t\tfor otherNodeName := range states.NodeToZoneMap { //compare with #vreps on other nodes\n\t\t\tif otherNodeName != nodeName {\n\t\t\t\totherReps := states.NodeSpread[key][otherNodeName]\n\t\t\t\tif skew = (currentReps + 1) - otherReps; skew < 0 {\n\t\t\t\t\tskew = skew * int32(-1)\n\t\t\t\t}\n\n\t\t\t\t//logger.Infof(\"Current Node %v with %d and Other Node %v with %d causing skew %d\", nodeName, currentReps, otherNodeName, otherReps, skew)\n\t\t\t\tif skew > skewVal.MaxSkew {\n\t\t\t\t\tlogger.Infof(\"Pod %d in node %v will cause an uneven node spread %v with other node %v\", podID, nodeName, states.NodeSpread[key], otherNodeName)\n\t\t\t\t}\n\t\t\t\tscore = score + uint64(skew)\n\t\t\t}\n\t\t}\n\n\t\tscore = math.MaxUint64 - score //lesser skews get higher score\n\t}\n\n\treturn score, state.NewStatus(state.Success)\n}",
"func addScore(s int){\n\tscoreData.Scores = append(scoreData.Scores, s)\n\t\t\t\n\t\t\t// TODO: check if there is a score to check with\n\t\t\tsort.Slice(scoreData.Scores, func(i, j int) bool { return scoreData.Scores[i] > scoreData.Scores[j] })\n\t\t\tif scoreData.Scores[0] > scoreData.Highscore {\n\t\t\t\ttmp := scoreData.Highscore\n\t\t\t\tscoreData.Highscore = scoreData.Scores[0]\n\t\t\t\tscoreData.Scores[0] = tmp\n\t\t\t}\n\t\t\t\n}",
"func (g *Game) renderScore(f *Frame) {\n\tcol, row := scoreCoords()\n\tf.Draw(fmt.Sprintf(\"Score: %d\", g.score), col, row, ColorDefault, ColorDefault)\n}",
"func (s *PublicSfcAPI) GetValidationScore(ctx context.Context, stakerID hexutil.Uint) (*hexutil.Big, error) {\n\tv, err := s.b.GetValidationScore(ctx, idx.StakerID(stakerID))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn (*hexutil.Big)(v), err\n}",
"func (m *Vulnerability) GetPriorityScore()(*int32) {\n val, err := m.GetBackingStore().Get(\"priorityScore\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}",
"func getRtScore(mediaTitle, omdbTitle string, mediaSeason int, tomatoUrl string, isTv bool) (string, error) {\n\t// Generate RT media URL if OMDb doesn't provide it\n\tif tomatoUrl == \"\" || tomatoUrl == \"N/A\" {\n\t\tif isTv {\n\t\t\ttomatoUrl = rtBaseUrl + \"/tv/\" + getRtName(mediaTitle) + fmt.Sprintf(\"/s%0d\", mediaSeason)\n\t\t} else {\n\t\t\ttomatoUrl = rtBaseUrl + \"/m/\" + getRtName(omdbTitle)\n\t\t}\n\t}\n\n\tres, doc, err := getMediaDoc(tomatoUrl, rtBaseUrl)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer res.Body.Close()\n\n\t// Extract RT rating\n\tvar rating string\n\tif isTv {\n\t\trating = doc.Find(rtTvScoreSelector).\n\t\t\tFirst().Text()\n\t} else {\n\t\trating = doc.Find(rtMovieScoreSelector).\n\t\t\tFirst().Text()\n\t}\n\t// Cleanup newlines, get first number, cleanup percentage signs\n\trating = strings.Trim(strings.Trim(strings.Split(strings.TrimSpace(rating), \" \")[0], \"\\n\"), \"%\")\n\n\tif rating == \"\" || !isInt(rating) {\n\t\treturn \"N/A\", nil\n\t}\n\n\treturn rating, nil\n}",
"func (it *VRR) get(winner, loser int) int {\n\tvar out int\n\tif winner > loser {\n\t\tout = it.counts[winner][loser]\n\t} else {\n\t\tout = it.counts[loser][loser+winner]\n\t}\n\treturn out\n}",
"func (d Dispatcher) Score() float64 {\n\treturn d.GetBench().GetScore()\n}",
"func (stats *AccuracyStatistics) GetAccuracyStats(remainingScore int, dart *Dart) {\n\tif remainingScore-dart.GetScore() < 171 {\n\t\t// We only want to calculate accuracy stats when player has a remaining score over 170\n\t\treturn\n\t}\n\n\tscore := dart.Value.Int64\n\tswitch score {\n\tcase 20:\n\t\tstats.hits20++\n\t\tstats.attempts20++\n\t\tstats.Accuracy20.Float64 += 100\n\tcase 5, 1:\n\t\tstats.attempts20++\n\t\tstats.Accuracy20.Float64 += 70\n\tcase 12, 18:\n\t\tstats.attempts20++\n\t\tstats.Accuracy20.Float64 += 30\n\tcase 9, 4:\n\t\tstats.attempts20++\n\t\tstats.Accuracy20.Float64 += 5\n\tcase 19:\n\t\tstats.hits19++\n\t\tstats.attempts19++\n\t\tstats.Accuracy19.Float64 += 100\n\tcase 7, 3:\n\t\tstats.attempts19++\n\t\tstats.Accuracy19.Float64 += 70\n\tcase 16, 17:\n\t\tstats.attempts19++\n\t\tstats.Accuracy19.Float64 += 30\n\tcase 8, 2:\n\t\tstats.attempts19++\n\t\tstats.Accuracy19.Float64 += 5\n\tdefault:\n\t\tstats.misses++\n\t}\n}",
"func evaluate(board [8][8]int, player int) float32 {\n\tvar score float32\n\n\t//Created a grid of relative score values for each cell\n\t//Based on Reversi strategy\n\t//Corners are stable and valuable, but adjacent cells can lead to losing a corner\n\t//Edge pieces are somewhat stable and valuable otherwise\n\t//Cells 2 away from corner facilitate corner capturing\n\t//All other tiles are weighted at 1\n\n\tcellValue := [][]int{\n\t\t{50, -20, 10, 5, 5, 10, -20, 50},\n\t\t{-20, -20, 1, 1, 1, 1, -20, -20},\n\t\t{10, 1, 5, 1, 1, 5, 1, 10},\n\t\t{5, 1, 1, 1, 1, 1, 1, 5},\n\t\t{5, 1, 1, 1, 1, 1, 1, 5},\n\t\t{10, 1, 5, 1, 1, 5, 1, 10},\n\t\t{-20, -20, 1, 1, 1, 1, -20, -20},\n\t\t{50, -20, 10, 5, 5, 10, -20, 50},\n\t}\n\n\t//Coin Parity\n\tvar pScore float32\n\tvar pCoin float32\n\tvar oCoin float32\n\n\t//Score player and opponent cell\n\tfor i := 0; i < 8; i++ {\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tif board[i][j] == player {\n\t\t\t\tpCoin += float32(cellValue[i][j])\n\t\t\t} else if board[i][j] == enemy(player) {\n\t\t\t\toCoin += float32(cellValue[i][j])\n\t\t\t}\n\t\t}\n\t}\n\n\t//Parity score is difference in scores over total score\n\tpScore = (pCoin - oCoin) / (pCoin + oCoin)\n\n\t//Difference in Mobility\n\t//Create games assuming board state and turn to calculate size of valid moves\n\tvar mScore float32\n\n\tpMob := createGame(board, player)\n\toMob := createGame(board, enemy(player))\n\n\tplayerMobility := len(pMob.validMoves)\n\tenemyMobility := len(oMob.validMoves)\n\n\tswitch{\n\tcase playerMobility > enemyMobility:\n\t\tmScore = float32(playerMobility)/float32(playerMobility + enemyMobility)\n\tcase enemyMobility > playerMobility:\n\t\tmScore = -float32(enemyMobility)/float32(playerMobility + enemyMobility)\n\tdefault:\n\t\tmScore = 0\n\t}\n\n\t//fmt.Printf(\"Parity:%v Mobility:%v\\n\", pScore, mScore)\n\t//Total evaluated score\n\tscore = (pScore * 500) + (mScore * 600)\n\n\treturn score\n}",
"func Score(hand ...deck.Card) int {\n\tminScore := minScore(hand...)\n\tif minScore > 11 {\n\t\treturn minScore\n\t}\n\tfor _, c := range hand {\n\t\tif int(c.Rank) == 1 {\n\t\t\t// ace is currently worth 1, and we are changing it to be worth 11\n\t\t\t// 11 - 1 = 10\n\t\t\treturn minScore + 10\n\t\t}\n\t}\n\treturn minScore\n}",
"func (o *SecureScore) GetMaxScore() AnyOfnumberstringstring {\n\tif o == nil || o.MaxScore == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret\n\t}\n\treturn *o.MaxScore\n}",
"func (v vvalue) Score(n int) float64 {\n\treturn v.f(n)\n}",
"func (pi *PolicyItem) computeEvalScore(service ServiceDefinition) {\n\tscore := ITEM_DEFAULT_SCORE\n\n\tif contains(pi.Groups, GroupPublic) {\n\t\tscore -= DISCOUNT_USERSGROUPS\n\t} else {\n\t\tcount := len(pi.Users) + len(pi.Groups)\n\t\tscore -= int(math.Min(float64(DISCOUNT_USERSGROUPS), float64(count)))\n\t}\n\n\tscore -= int(math.Round(float64((DISCOUNT_ACCESS_TYPES * len(pi.Accesses)) / len(service.AccessTypes))))\n\n\tcustomConditionsPenalty := CUSTOM_CONDITION_PENALTY * len(pi.Conditions)\n\tcustomConditionsDiscount := DISCOUNT_CUSTOM_CONDITIONS - customConditionsPenalty\n\n\tif customConditionsDiscount > 0 {\n\t\tscore -= customConditionsDiscount\n\t}\n\n\tpi.score = score\n}",
"func (c *Claim) Score(ctx *ServerContext) (float32, Error) {\n\tif c.QueryAt == nil {\n\t\treturn c.Truth, nil\n\t}\n\treturn c.scoreAt(ctx)\n}",
"func (s *Survey) Score() (score uint) {\n\tfor _, a := range s.Answers {\n\t\tswitch t := a[\"answer\"].(map[string]interface{})[\"score\"].(type) {\n\t\tcase int: // FIXME score came from models_test.newSurvey test case is int type\n\t\t\tscore = score + uint(t)\n\t\tcase float64:\n\t\t\tscore = score + uint(t)\n\t\t}\n\t}\n\treturn\n}",
"func (s Square) Right() int {\n\treturn s.left + s.width\n}",
"func (b *Block) Score() int64 {\n\treturn b.work\n}",
"func Score(fileOptions map[string]interface{}) {\n\toptions, err := parseFlags(fileOptions)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tinputFiles := readSharedInputFiles(options)\n\n\tscores := preyScore{\n\t\tBait: calculateBaitComponent(options, inputFiles),\n\t\tDomain: calculateDomainComponent(options, inputFiles),\n\t\tStudy: calculateStudyComponent(options, inputFiles),\n\t\tText: calculateTextComponent(options, inputFiles),\n\t}\n\n\twriteScores(scores, inputFiles, options.outFile)\n}",
"func (e *Square10) DetermineWinner() int {\n\tscore := []int{0, 0}\n\tfor _, owner := range e.ownership {\n\t\tif owner == contested {\n\t\t\tcontinue\n\t\t}\n\t\tscore[owner]++\n\t}\n\tfor player, points := range score {\n\t\tif points+player > 50 {\n\t\t\treturn player\n\t\t}\n\t}\n\treturn -1\n}",
"func UpdateGot(p1Needs, p2Needs, p1Got, p2Got float64) (float64, float64) {\n\t// We have too many wins for both players based on the new race, roll back wins proportionally.\n\tfor p1Got > p1Needs && p2Got > p2Needs {\n\t\tpwin := p1Needs / (p1Needs + p2Needs)\n\t\tr := rand.Float64()\n\t\t//\t\tglog.V(2).Infof(\"both players have too many games needs:%f|%f got:%f|%f \", p1Needs, p2Needs, p1Got, p2Got)\n\t\tif r < pwin {\n\t\t\t//\t\t\tglog.V(2).Infof(\"p1 docked a game\\n\")\n\t\t\tp1Got -= 1\n\t\t} else {\n\t\t\t//\t\t\tglog.V(2).Infof(\"p2 docked a game\\n\")\n\t\t\tp2Got -= 1\n\t\t}\n\n\t}\n\t// We didn't have enough matches for the new race, use math/rand\n\t// to make something up proportional\n\tfor p1Got < p1Needs && p2Got < p2Needs {\n\t\tpwin := p1Needs / (p1Needs + p2Needs)\n\t\tr := rand.Float64()\n\t\t//\t\tglog.V(2).Infof(\"neither player can achieve a win: needs:%f|%f got:%f|%f \", p1Needs, p2Needs, p1Got, p2Got)\n\t\tif r < pwin {\n\t\t\t//\t\t\tglog.V(2).Infof(\"p1 given a game\\n\")\n\t\t\tp1Got += 1\n\t\t} else {\n\t\t\t//\t\t\tglog.V(2).Infof(\"p1 given a game\\n\")\n\t\t\tp2Got += 1\n\t\t}\n\t}\n\t// Only one player had too many games - they win.\n\tif p1Got > p1Needs {\n\t\t//\t\tglog.V(2).Infof(\"p1 had enough games to win: needs:%f|%f got:%f|%f \\n\", p1Needs, p2Needs, p1Got, p2Got)\n\t\tp1Got = p1Needs\n\t}\n\tif p2Got > p2Needs {\n\t\t//\t\tglog.V(2).Infof(\"p2 had enough games to win: needs:%f|%f got:%f|%f \\n\", p1Needs, p2Needs, p1Got, p2Got)\n\t\tp2Got = p2Needs\n\t}\n\n\treturn p1Got, p2Got\n}",
"func Score(hand ...deck.Card) int {\n\tminScore := minScore(hand...)\n\tif minScore > 11 {\n\t\t// we can't increase 12 to 22, because that will be a bust\n\t\treturn minScore\n\t}\n\n\tfor _, c := range hand {\n\t\tif c.Rank == deck.Ace {\n\t\t\t// ace is currently worth 1, and we are changing it to be worth 11\n\t\t\t// 11 - 1 = 10\n\t\t\treturn minScore + 10\n\t\t}\n\t}\n\treturn minScore\n}",
"func FormatScore(game responses.FantasyGame) string {\n\thomeTeam := game.Home.Name\n\tawayTeam := game.Away.Name\n\n\thomeScore := game.HomeScore.Score.Value\n\tawayScore := game.AwayScore.Score.Value\n\n\tif homeScore > awayScore {\n\t\treturn fmt.Sprintf(\"%v beat %v with a score of %.2f-%.2f.\\n\", homeTeam, awayTeam, homeScore, awayScore)\n\t} else if awayScore > homeScore {\n\t\treturn fmt.Sprintf(\"%v beat %v with a score of %.2f-%.2f.\\n\", awayTeam, homeTeam, awayScore, homeScore)\n\t} else {\n\t\treturn fmt.Sprintf(\"Whaaaat....%v and %v tied with a score of %.2f-%.2f.\\n\", homeTeam, awayTeam, homeScore, awayScore)\n\t}\n}",
"func Score(x, y float64) (score int) {\n\t// in order to lie within the circle area the distance of the point (x,y) from (0,0) coordinates\n\t// must be less or equal to the radius of the circle\n\tr := radius(x, y)\n\tswitch {\n\tcase r <= 1.0:\n\t\tscore = 10\n\tcase r <= 5.0:\n\t\tscore = 5\n\tcase r <= 10.0:\n\t\tscore = 1\n\tdefault:\n\t\tscore = 0\n\t}\n\treturn\n}",
"func FinalScore(scorers []*card.Item) (sum uint8) {\n\tfor _, s := range scorers {\n\t\tsum += Points(s)\n\t}\n\treturn\n}",
"func (sr *ServiceRegistry) GetScores() (map[string]int, error) {\n\tsr.Lock()\n\n\tif sr.Services == nil || len(sr.Services) == 0 {\n\t\treturn nil, fmt.Errorf(\"no services found in the service registry\")\n\t}\n\n\tscores := map[string]int{}\n\n\tfor teamName, services := range sr.Services {\n\t\tscores[teamName] = 0\n\t\tfor _, service := range services {\n\t\t\tscores[teamName] = scores[teamName] + service.Points\n\t\t}\n\t}\n\n\tsr.Unlock()\n\n\treturn scores, nil\n}",
"func (o *DocumentRiskSummary) GetRiskScore() float32 {\n\tif o == nil || o.RiskScore.Get() == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\n\treturn *o.RiskScore.Get()\n}",
"func Score(x, y float64) int {\n\tswitch {\n\tcase inCircle(x, y, 1):\n\t\treturn 10\n\tcase inCircle(x, y, 5):\n\t\treturn 5\n\tcase inCircle(x, y, 10):\n\t\treturn 1\n\tdefault:\n\t\treturn 0\n\t}\n}",
"func (DBConnection *MariaDBPlugin) GetUserVoteScore(UserID uint64, ImageID uint64) (int64, error) {\n\t//Check if user voted before\n\tsqlQuery := \"SELECT Score FROM ImageUserScores WHERE UserID=? AND ImageID=?;\"\n\tvar score int64\n\terr := DBConnection.DBHandle.QueryRow(sqlQuery, UserID, ImageID).Scan(&score)\n\tif err != nil {\n\t\tif err != sql.ErrNoRows {\n\t\t\tlogging.WriteLog(logging.LogLevelError, \"MariaDBPlugin/UpdateUserVoteScore\", strconv.FormatUint(UserID, 10), logging.ResultFailure, []string{\"Failed to verify score existance\", err.Error()})\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn score, nil\n}",
"func Score(dice []int, category string) int {\n\tswitch category {\n\tcase \"ones\":\n\t\tif count, ok := groupDice(dice)[1]; ok {\n\t\t\treturn count * 1\n\t\t}\n\tcase \"twos\":\n\t\tif count, ok := groupDice(dice)[2]; ok {\n\t\t\treturn count * 2\n\t\t}\n\tcase \"threes\":\n\t\tif count, ok := groupDice(dice)[3]; ok {\n\t\t\treturn count * 3\n\t\t}\n\tcase \"fours\":\n\t\tif count, ok := groupDice(dice)[4]; ok {\n\t\t\treturn count * 4\n\t\t}\n\tcase \"fives\":\n\t\tif count, ok := groupDice(dice)[5]; ok {\n\t\t\treturn count * 5\n\t\t}\n\tcase \"sixes\":\n\t\tif count, ok := groupDice(dice)[6]; ok {\n\t\t\treturn count * 6\n\t\t}\n\tcase \"full house\":\n\t\treturn scoreFullHouse(groupDice(dice))\n\tcase \"four of a kind\":\n\t\tfor num, count := range groupDice(dice) {\n\t\t\tif count >= 4 {\n\t\t\t\treturn num * 4\n\t\t\t}\n\t\t}\n\tcase \"little straight\":\n\t\tif sortAndCompare(dice, []int{1, 2, 3, 4, 5}) {\n\t\t\treturn 30\n\t\t}\n\tcase \"big straight\":\n\t\tif sortAndCompare(dice, []int{2, 3, 4, 5, 6}) {\n\t\t\treturn 30\n\t\t}\n\tcase \"choice\":\n\t\tsum := 0\n\t\tfor _, die := range dice {\n\t\t\tsum += die\n\t\t}\n\t\treturn sum\n\tcase \"yacht\":\n\t\tif len(groupDice(dice)) == 1 {\n\t\t\treturn 50\n\t\t}\n\t}\n\n\treturn 0\n}",
"func (am *Antman) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\tklog.Infof(\"in Score for podName : %v\", pod.Name)\n\tnodeInfo, err := am.frameworkHandle.SnapshotSharedLister().NodeInfos().Get(nodeName)\n\tif err != nil {\n\t\treturn 0, framework.NewStatus(framework.Error, fmt.Sprintf(\"getting node %q from Snapshot: %v\", nodeName, err))\n\t}\n\n\tpodInfo := am.getOrCreatePodInfo(pod, time.Now())\n\tpodKey := podInfo.key\n\tif len(podKey) == 0 {\n\t\t// normal pod, not opportunistic pod in antman\n\t\t// return 100 for every node to bypass the scoring\n\t\treturn int64(100), nil\n\t}\n\n\t// note that, because there are multiple score plugins in k8s\n\t// it is not the final score for this node\n\treturn am.GpuScore(state, pod, nodeInfo)\n}",
"func Score(state State) float32 {\n\tswitch state {\n\tcase Unknown:\n\t\treturn 0\n\tcase Outage:\n\t\treturn 0.25\n\tcase Major:\n\t\treturn 0.50\n\tcase Minor:\n\t\treturn 0.75\n\tcase OK:\n\t\treturn 1.00\n\tdefault:\n\t\treturn 0\n\t}\n}",
"func (s *Server) GetScore(id string) (models.Score, error) {\n\tscore := models.Score{\n\t\tPlayer: id,\n\t}\n\n\tscoreQuery, err := s.database.PrepareNamed(\n\t\t`SELECT * FROM scores\n\t\tWHERE player = :player`)\n\tif err != nil {\n\t\ts.logger.Error(\"Prepare score query\", \"error\", err)\n\t}\n\n\terr = scoreQuery.Get(&score, score)\n\tif err == sql.ErrNoRows {\n\t\treturn score, err\n\t}\n\n\tif err != nil {\n\t\ts.logger.Error(\"Query score\", \"error\", err)\n\t\treturn score, err\n\t}\n\n\treturn score, nil\n}",
"func Score(hand ...deck.Card) int { // using variadic so user can pass in just one card if desired\n\tminScore := minScore(hand...)\n\tif minScore > 11 {\n\t\treturn minScore\n\t}\n\tfor _, c := range hand {\n\t\tif c.Rank == deck.Ace {\n\t\t\treturn minScore + 10 // ace is currently worth 1, so adding 10 to make it worth 11\n\t\t}\n\t\t// only 1 ace can be used as 11 and still be under 21\n\t}\n\treturn minScore\n}",
"func (l *LabelResult) GetScore() *float64 {\n\tif l == nil {\n\t\treturn nil\n\t}\n\treturn l.Score\n}",
"func (m *MockScoring) GetScore(arg0 string) (float64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetScore\", arg0)\n\tret0, _ := ret[0].(float64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}",
"func ComputeRating(name string, gameID int, gameType string, result float64) {\n\n\tvar bullet, blitz, standard, correspondence, bulletRD, blitzRD, standardRD, correspondenceRD float64\n\tvar oBullet, oBlitz, oStandard, oCorrespondence, oBulletRD, oBlitzRD, oStandardRD, oCorrespondenceRD float64\n\n\t//update player's rating and notify them of rating change, also determine player color to assign correct rating\n\tif All.Games[gameID].WhitePlayer == name {\n\t\t_, bullet, blitz, standard, correspondence, bulletRD, blitzRD, standardRD,\n\t\t\tcorrespondenceRD = GetRatingAndRD(name)\n\t\t_, oBullet, oBlitz, oStandard, oCorrespondence, oBulletRD, oBlitzRD,\n\t\t\toStandardRD, oCorrespondenceRD = GetRatingAndRD(PrivateChat[name])\n\t} else {\n\t\t_, bullet, blitz, standard, correspondence, bulletRD, blitzRD, standardRD,\n\t\t\tcorrespondenceRD = GetRatingAndRD(PrivateChat[name])\n\t\t_, oBullet, oBlitz, oStandard, oCorrespondence, oBulletRD, oBlitzRD,\n\t\t\toStandardRD, oCorrespondenceRD = GetRatingAndRD(name)\n\t}\n\n\tvar whiteRating float64\n\tvar blackRating float64\n\tvar whiteRD float64\n\tvar blackRD float64\n\tconst (\n\t\tbulletString = \"bullet\"\n\t\tblitzString = \"blitz\"\n\t\tstandardString = \"standard\"\n\t\tcorrespondenceString = \"correspondence\"\n\t)\n\n\tif gameType == bulletString {\n\n\t\twhiteRating, whiteRD = grabRating(bullet, bulletRD, oBullet, oBulletRD, result)\n\t\tblackRating, blackRD = grabRating(oBullet, oBulletRD, bullet, bulletRD, 1.0-result)\n\n\t\t//updates database with players new rating and RD\n\t\tif All.Games[gameID].WhitePlayer == name {\n\t\t\tupdateRating(bulletString, name, whiteRating, whiteRD, PrivateChat[name], blackRating, blackRD)\n\t\t} else {\n\t\t\tupdateRating(bulletString, PrivateChat[name], whiteRating, whiteRD, name, blackRating, blackRD)\n\t\t}\n\n\t} else if gameType == blitzString {\n\n\t\twhiteRating, whiteRD = grabRating(blitz, blitzRD, oBlitz, oBlitzRD, result)\n\t\tblackRating, blackRD = grabRating(oBlitz, oBlitzRD, blitz, blitzRD, 1.0-result)\n\n\t\t//updates both players rating\n\t\tif All.Games[gameID].WhitePlayer == name {\n\t\t\tupdateRating(blitzString, name, whiteRating, whiteRD, PrivateChat[name], blackRating, blackRD)\n\t\t} else {\n\t\t\tupdateRating(blitzString, PrivateChat[name], whiteRating, whiteRD, name, blackRating, blackRD)\n\t\t}\n\n\t} else if gameType == standardString {\n\n\t\twhiteRating, whiteRD = grabRating(standard, standardRD, oStandard, oStandardRD, result)\n\t\tblackRating, blackRD = grabRating(oStandard, oStandardRD, standard, standardRD, 1.0-result)\n\t\t//updates database with players new rating and RD\n\t\tif All.Games[gameID].WhitePlayer == name {\n\t\t\tupdateRating(standardString, name, whiteRating, whiteRD, PrivateChat[name], blackRating, blackRD)\n\t\t} else {\n\t\t\tupdateRating(standardString, PrivateChat[name], whiteRating, whiteRD, name, blackRating, blackRD)\n\t\t}\n\t} else if gameType == correspondenceString {\n\t\twhiteRating, whiteRD = grabRating(correspondence, correspondenceRD, oCorrespondence, oCorrespondenceRD, result)\n\t\tblackRating, blackRD = grabRating(oCorrespondence, oCorrespondenceRD, correspondence, correspondenceRD, 1.0-result)\n\t\t//updates database with players new rating and RD\n\t\tif All.Games[gameID].WhitePlayer == name {\n\t\t\tupdateRating(correspondenceString, name, whiteRating, whiteRD, PrivateChat[name], blackRating, blackRD)\n\t\t} else {\n\t\t\tupdateRating(correspondenceString, PrivateChat[name], whiteRating, whiteRD, name, blackRating, blackRD)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Not a valid game type rate.go 1\")\n\t}\n\n\tvar r Nrating\n\tr.Type = \"rating\"\n\tr.WhiteRating = whiteRating\n\tr.BlackRating = blackRating\n\n\tif _, ok := Active.Clients[name]; ok { // send data if other guy is still connected\n\t\twebsocket.JSON.Send(Active.Clients[name], &r)\n\t}\n\n\tif _, ok := Active.Clients[PrivateChat[name]]; ok { // send data if other guy is still connected\n\t\twebsocket.JSON.Send(Active.Clients[PrivateChat[name]], &r)\n\t}\n}",
"func (h *Hand) Scores() []int {\n\tscores := []int{0}\n\tfor _, card := range h.Cards {\n\t\tif !card.faceUp {\n\t\t\tcontinue\n\t\t}\n\t\tfor i, score := range scores {\n\t\t\t// Add the first value to each score branch.\n\t\t\tscores[i] += card.Values()[0]\n\t\t\tfor _, cardValue := range card.Values()[1:] {\n\t\t\t\t// Make more score branches for further card values.\n\t\t\t\t// In other words, branch on aces.\n\t\t\t\tscores = append(scores, score+cardValue)\n\t\t\t}\n\t\t}\n\t}\n\t// If we have blackjack then return that alone\n\tfor _, score := range scores {\n\t\tif score == 21 {\n\t\t\treturn []int{21}\n\t\t}\n\t}\n\tscores = util.UniqueInts(scores)\n\tscores = sanitiseScores(scores)\n\tsort.Ints(scores)\n\treturn scores\n}",
"func final(player int, game Game) float32 {\n\tgame.calcScore()\n\tvar MAX float32\n\tMAX = 10000\n\n\tif player == 1 {\n\t\tif game.WhiteCount > game.BlackCount {\n\t\t\treturn MAX\n\t\t} else if game.BlackCount > game.WhiteCount {\n\t\t\treturn -MAX\n\t\t} else {\n\t\t\treturn 0\n\t\t}\n\t} else {\n\t\tif game.WhiteCount > game.BlackCount {\n\t\t\treturn -MAX\n\t\t} else if game.BlackCount > game.WhiteCount {\n\t\t\treturn MAX\n\t\t} else {\n\t\t\treturn 0\n\t\t}\n\t}\n}",
"func CreateMatchScore(match *Match, gameID int, playerUserName string, baseScore float32, isWinner bool) (bool, *MatchScore) {\n\tok, player := FindUser(playerUserName)\n\n\tif !ok {\n\t\treturn false, nil\n\t}\n\n\tmatchScore := &MatchScore{\n\t\tMatchID: match.ID,\n\t\tGameID: gameID,\n\t\tPlayerUserName: player.Username,\n\t\tPlayerDisplayName: player.FirstName,\n\t\tBaseScore: baseScore,\n\t\tIsWinner: isWinner,\n\t}\n\n\terr := dbmap.Insert(matchScore)\n\n\tif err != nil {\n\t\tlog.Print(\"ERROR: \")\n\t\tlog.Println(err)\n\t}\n\n\tmatch.CalculateAll()\n\n\treturn (err == nil), matchScore\n}",
"func updatePawnChainScore(pawnchain int) float64 {\n\tvar score float64\n\tif pawnchain > 2 {\n\t\tscore += float64(pawnchain) * LONGPAWNCHAIN\n\t} else if pawnchain != 0 {\n\t\tscore += ISOLATEDPAWN / float64(pawnchain)\n\t}\n\treturn score\n}",
"func GetScore(s, substr string) Score {\n\ts = strings.ToLower(s)\n\tsubstr = strings.ToLower(substr)\n\t// TODO: try using same terms everywhere. Current zoo of \"a\", \"s\", \"str\"\n\t// looks silly\n\tif em := exactMatches(s, substr); em.Distance != -1 {\n\t\treturn em\n\t}\n\tvar score Score\n\tif len(substr) > 3 {\n\t\tscore = calcLevenshteinScore(s, substr)\n\t} else { // TODO why this \"if\" exists?\n\t\tscore.Distance = calcLeventshteinDistance(s, substr, levenThreshold)\n\t\tscore.I2 = min(len(substr), len(s))\n\t}\n\treturn score\n}",
"func Score(word string) int {\n\tscore := 0\n\tfor _, c := range strings.ToUpper(word) {\n\t\tscore = score + letterValues.getScore(c)\n\t}\n\treturn score\n}"
] | [
"0.6962864",
"0.6771088",
"0.6445897",
"0.6340977",
"0.6023018",
"0.60210246",
"0.60036117",
"0.5951539",
"0.59173906",
"0.59006196",
"0.58824503",
"0.58778745",
"0.5850142",
"0.58323866",
"0.5830416",
"0.58280706",
"0.5807789",
"0.57857466",
"0.5785142",
"0.5758699",
"0.57463026",
"0.57366174",
"0.57013434",
"0.5698608",
"0.5675941",
"0.5663103",
"0.56304336",
"0.56146",
"0.56095016",
"0.5598425",
"0.55962956",
"0.55848575",
"0.5576638",
"0.55726916",
"0.5571501",
"0.5569181",
"0.5553476",
"0.55469924",
"0.554438",
"0.55362207",
"0.5528356",
"0.5502812",
"0.5502254",
"0.55011976",
"0.54881114",
"0.54858655",
"0.5484692",
"0.54820055",
"0.54789716",
"0.5464416",
"0.5464393",
"0.5412588",
"0.54110533",
"0.5399511",
"0.53876173",
"0.53601253",
"0.5349731",
"0.53380084",
"0.533033",
"0.5304929",
"0.53028786",
"0.53015083",
"0.53013986",
"0.53002214",
"0.52970785",
"0.5288672",
"0.5277099",
"0.5253033",
"0.52411",
"0.5240939",
"0.52404135",
"0.52387244",
"0.52245855",
"0.52222925",
"0.5217454",
"0.5211634",
"0.5211291",
"0.5204453",
"0.52029204",
"0.5196483",
"0.51893353",
"0.5186694",
"0.51836646",
"0.5180774",
"0.51718175",
"0.5161831",
"0.5153533",
"0.5150063",
"0.51450837",
"0.5141875",
"0.5139017",
"0.51350933",
"0.5134573",
"0.51332474",
"0.513294",
"0.5108535",
"0.5108517",
"0.5101807",
"0.5087143",
"0.5086943"
] | 0.79509056 | 0 |
GetOrCalculateLeftScore returns game score for saven games or calculates new score | func (g *Game) GetOrCalculateLeftScore() int {
if g.LeftScore == 0 {
_, left := g.GameScore()
return int(left)
}
return g.LeftScore
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (g *Game) GetOrCalculateRightScore() int {\n\tif g.RightScore == 0 {\n\t\tright, _ := g.GameScore()\n\t\treturn int(right)\n\t}\n\treturn g.RightScore\n}",
"func (g *Game) GameScore() (uint, uint) {\n\tleft := round(float64(g.TournamentTable.Tournament.GameScore) * g.gameLeftScoreFactor())\n\treturn g.TournamentTable.Tournament.GameScore - left, left\n}",
"func (g *Game) UpdateScore() error {\n\tswitch g.Winner {\n\tcase RIGHT:\n\t\tright, _ := g.GameScore()\n\t\tg.RightScore = int(right)\n\t\tg.LeftScore = -int(right)\n\t\treturn nil\n\tcase LEFT:\n\t\t_, left := g.GameScore()\n\t\tg.RightScore = -int(left)\n\t\tg.LeftScore = int(left)\n\t\treturn nil\n\tcase DRAW:\n\t\tscore := g.TournamentTable.Tournament.GameScore / 2\n\t\tg.RightScore = int(score)\n\t\tg.LeftScore = int(score)\n\t\treturn nil\n\tdefault:\n\t\treturn errors.New(\"no winner in this game\")\n\t}\n}",
"func (eng *Engine) Score() int32 {\n\treturn Evaluate(eng.Position).GetCentipawnsScore() * eng.Position.Us().Multiplier()\n}",
"func (g *G) Score() int {\n\t/* Fill in this Function */\n\treturn 0\n}",
"func (game *Game) Score() int {\n\treturn game.score\n}",
"func (b *Board) score() Player {\n\tstatic_eval := b.evaluate_static()\n\tif static_eval != NoPlayer {\n\t\treturn static_eval\n\t}\n\n\tif len(b.vacantSquares()) == 0 {\n\t\treturn NoPlayer\n\t}\n\n\tbranch_evals := func() []Player {\n\t\tout := []Player{}\n\t\tfor _, branch := range b.possibleMoves() {\n\t\t\tout = append(out, branch.score())\n\t\t}\n\t\treturn out\n\t}()\n\n\tswitch b.NextPlayer() {\n\tcase Player1:\n\t\tif playerInList(Player1, branch_evals) {\n\t\t\treturn Player1\n\t\t} else if playerInList(NoPlayer, branch_evals) {\n\t\t\treturn NoPlayer\n\t\t} else {\n\t\t\treturn Player2\n\t\t}\n\tcase Player2:\n\t\tif playerInList(Player2, branch_evals) {\n\t\t\treturn Player2\n\t\t} else if playerInList(NoPlayer, branch_evals) {\n\t\t\treturn NoPlayer\n\t\t} else {\n\t\t\treturn Player1\n\t\t}\n\t}\n\n\treturn NoPlayer\n}",
"func (g *Game) Score() int {\n\trollIndex := 0\n\tfor frame := 0; frame < frameNumberPerGame; frame++ {\n\t\tif g.isStrike(rollIndex) {\n\t\t\tg.score += cleanPinNumber + g.getStrikeBonus(rollIndex)\n\t\t\trollIndex++\n\t\t} else if g.isSpare(rollIndex) {\n\t\t\tg.score += cleanPinNumber + g.getSpareBonus(rollIndex)\n\t\t\trollIndex += 2\n\t\t} else {\n\t\t\tg.score += g.getFrameScore(rollIndex)\n\t\t\trollIndex += 2\n\t\t}\n\n\t}\n\treturn g.score\n}",
"func (el *gameStruct) Score() int {\n\treturn el.points\n}",
"func (g *Game) GetScore() int {\n\treturn g.score\n}",
"func (b Engine) GetScore() float64 {\n\treturn b.Score\n}",
"func (d *diff) CalcScore(key interface{}) float64 {\n\treturn 0\n}",
"func calcScore2(opp string, me string) int {\n\tif me == \"X\" {\n\t\t/*\n\t\t* LOSE\n\t\t* A -> Rock 3\n\t\t* B -> Paper 1\n\t\t* C -> Scissor 2\n\t\t */\n\t\tswitch opp {\n\t\tcase \"A\":\n\t\t\treturn LOSE + 3\n\t\tcase \"B\":\n\t\t\treturn LOSE + 1\n\t\tcase \"C\":\n\t\t\treturn LOSE + 2\n\t\tdefault:\n\t\t\treturn 0\n\t\t}\n\t} else if me == \"Y\" {\n\t\tswitch opp {\n\t\tcase \"A\":\n\t\t\treturn TIE + 1\n\t\tcase \"B\":\n\t\t\treturn TIE + 2\n\t\tcase \"C\":\n\t\t\treturn TIE + 3\n\t\tdefault:\n\t\t\treturn 0\n\t\t}\n\t} else {\n\t\t/*\n\t\t* WIN\n\t\t* A -> Rock 2\n\t\t* B -> Paper 3\n\t\t* C -> Scissor 1\n\t\t */\n\t\tswitch opp {\n\t\tcase \"A\":\n\t\t\treturn WIN + 2\n\t\tcase \"B\":\n\t\t\treturn WIN + 3\n\t\tcase \"C\":\n\t\t\treturn WIN + 1\n\t\tdefault:\n\t\t\treturn 0\n\t\t}\n\t}\n}",
"func (sqlite *SQLiteDB) OveralScore(from time.Time, to time.Time) (int32, error) {\n\tvar score int32\n\terr := sqlite.db.Get(&score,\n\t\t`SELECT round(AVG(rating * weight)/AVG($1 * weight)*100) as score\n\t\tFROM ratings\n\t\tINNER JOIN tickets ON ratings.ticket_id=tickets.id\n\t\tINNER JOIN rating_categories ON ratings.rating_category_id=rating_categories.id\n\t\tWHERE tickets.created_at BETWEEN $2 AND $3;`,\n\t\tdb.MaxRating, from.Format(db.SimpleDateFormat), to.Format(db.SimpleDateFormat))\n\n\tif err != nil {\n\t\treturn score, err\n\t}\n\treturn score, err\n}",
"func (c *CommitResult) GetScore() *float64 {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.Score\n}",
"func (va VAScore) Score() float64 {\n\tif va.Err != nil {\n\t\treturn 0.0\n\t}\n\treturn va.Achieved - va.Expected\n}",
"func (eng *Engine) cachedScore(e *hashEntry) int32 {\n\tif e.kind&hasStatic == 0 {\n\t\te.kind |= hasStatic\n\t\te.static = int16(eng.Score())\n\t}\n\treturn int32(e.static)\n}",
"func (h handler) GetScore(c echo.Context) error {\n\tvar scoreRequest ScoreRequest\n\n\tif err := c.Bind(&scoreRequest); err != nil {\n\t\treturn c.JSON(http.StatusBadRequest, err)\n\t}\n\n\tsnapshotScoreResponse, err := getScore(scoreRequest)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, err)\n\t}\n\n\treturn c.JSON(http.StatusOK, snapshotScoreResponse)\n}",
"func (game *Game) calculateGameWinner() {\n\twinningPlayer := 0\n\twinningTotal := MaxPossibleScore\n\n\tfor i := range game.players {\n\t\tplayerTotal := game.players[i].calcuateTotalGameScore()\n\n\t\tif playerTotal < winningTotal {\n\t\t\twinningTotal = playerTotal\n\t\t\twinningPlayer = i\n\t\t}\n\t}\n\n\tgame.gameWinner = winningPlayer\n}",
"func CreatePlayerScore(gameName string, kills int, deaths int, assists int, cs int, tripleKills int, quadraKills int, pentaKills int) *PlayerScore {\n\tscore := PlayerScore{\n\t\tSummonerName: gameName,\n\t\tKills: float32(kills) * PointValues[KillsString],\n\t\tDeaths: float32(deaths) * PointValues[DeathsString],\n\t\tAssists: float32(assists) * PointValues[AssistsString],\n\t\tCS: float32(cs) * PointValues[CSString],\n\t\tTripleKills: float32(tripleKills) * PointValues[TripleKillsString],\n\t\tQuadraKills: float32(quadraKills) * PointValues[QuadraKillsString],\n\t\tPentakills: float32(pentaKills) * PointValues[PentakillsString],\n\t}\n\tscore.CSString = fmt.Sprintf(\"%.2f\", score.CS)\n\n\t//Bonus points for getting at least 10 kills/assists in the same game\n\tif kills+assists >= 10 {\n\t\tscore.TenKA = PointValues[TenKAString]\n\t}\n\n\tscore.Score = score.Kills + score.Deaths + score.Assists + score.CS + score.TenKA + score.TripleKills +\n\t\tscore.QuadraKills + score.Pentakills\n\tscore.ScoreString = fmt.Sprintf(\"%.2f\", score.Score)\n\n\treturn &score\n}",
"func (o *SecureScore) GetCurrentScore() AnyOfnumberstringstring {\n\tif o == nil || o.CurrentScore == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret\n\t}\n\treturn *o.CurrentScore\n}",
"func (b *Board) Score() int {\n\tif !b.Finish {\n\t\treturn 0\n\t}\n\n\t// yaku ? or finish move\n\t// b.HasYaku() //TODO: yaku score\n\ts := b.LastAttackMove.Attack.GetScore()\n\tif b.LastAttackMove.FaceDown && b.LastAttackMove.Block == b.LastAttackMove.Attack {\n\t\ts = s * 2\n\t}\n\treturn s\n}",
"func (g *Game) getFrameScore(rollIndex int) int {\n\treturn g.rolls[rollIndex] + g.rolls[rollIndex+1]\n}",
"func (m *PlayerMutation) OldScore(ctx context.Context) (v int, err error) {\n\tif !m.op.Is(OpUpdateOne) {\n\t\treturn v, fmt.Errorf(\"OldScore is only allowed on UpdateOne operations\")\n\t}\n\tif m.id == nil || m.oldValue == nil {\n\t\treturn v, fmt.Errorf(\"OldScore requires an ID field in the mutation\")\n\t}\n\toldValue, err := m.oldValue(ctx)\n\tif err != nil {\n\t\treturn v, fmt.Errorf(\"querying old value for OldScore: %w\", err)\n\t}\n\treturn oldValue.Score, nil\n}",
"func (s *State) ApplyScore(north, south, west, east string, nsScore, weScore int) error {\n\tseating := s.CurrentRound().FindSeating(north, south, west, east)\n\tif seating == nil {\n\t\treturn fmt.Errorf(\"Couldn't find a seating with these players: N %s, S %s, W %s, E %s\", north, south, west, east)\n\t}\n\n\tseating.Finished = true\n\tseating.NSScore = nsScore\n\tseating.WEScore = weScore\n\tif nsScore >= weScore {\n\t\tseating.NSWins = true\n\t}\n\n\treturn nil\n}",
"func (m *LogLoss) Score() float64 {\n\tm.mu.RLock()\n\tlogsum := m.logsum\n\tweight := m.weight\n\tm.mu.RUnlock()\n\n\tif weight > 0 {\n\t\treturn -logsum / weight\n\t}\n\treturn -math.Log(m.epsilon)\n}",
"func (pl *AvailabilityNodePriority) Score(ctx context.Context, args interface{}, states *state.State, feasiblePods []int32, key types.NamespacedName, podID int32) (uint64, *state.Status) {\n\tlogger := logging.FromContext(ctx).With(\"Score\", pl.Name())\n\tvar score uint64 = 0\n\n\tspreadArgs, ok := args.(string)\n\tif !ok {\n\t\tlogger.Errorf(\"Scoring args %v for priority %q are not valid\", args, pl.Name())\n\t\treturn 0, state.NewStatus(state.Unschedulable, ErrReasonInvalidArg)\n\t}\n\n\tskewVal := state.AvailabilityNodePriorityArgs{}\n\tdecoder := json.NewDecoder(strings.NewReader(spreadArgs))\n\tdecoder.DisallowUnknownFields()\n\tif err := decoder.Decode(&skewVal); err != nil {\n\t\treturn 0, state.NewStatus(state.Unschedulable, ErrReasonInvalidArg)\n\t}\n\n\tif states.Replicas > 0 { //need at least a pod to compute spread\n\t\tvar skew int32\n\n\t\t_, nodeName, err := states.GetPodInfo(state.PodNameFromOrdinal(states.StatefulSetName, podID))\n\t\tif err != nil {\n\t\t\treturn score, state.NewStatus(state.Error, ErrReasonNoResource)\n\t\t}\n\n\t\tcurrentReps := states.NodeSpread[key][nodeName] //get #vreps on this node\n\t\tfor otherNodeName := range states.NodeToZoneMap { //compare with #vreps on other nodes\n\t\t\tif otherNodeName != nodeName {\n\t\t\t\totherReps := states.NodeSpread[key][otherNodeName]\n\t\t\t\tif skew = (currentReps + 1) - otherReps; skew < 0 {\n\t\t\t\t\tskew = skew * int32(-1)\n\t\t\t\t}\n\n\t\t\t\t//logger.Infof(\"Current Node %v with %d and Other Node %v with %d causing skew %d\", nodeName, currentReps, otherNodeName, otherReps, skew)\n\t\t\t\tif skew > skewVal.MaxSkew {\n\t\t\t\t\tlogger.Infof(\"Pod %d in node %v will cause an uneven node spread %v with other node %v\", podID, nodeName, states.NodeSpread[key], otherNodeName)\n\t\t\t\t}\n\t\t\t\tscore = score + uint64(skew)\n\t\t\t}\n\t\t}\n\n\t\tscore = math.MaxUint64 - score //lesser skews get higher score\n\t}\n\n\treturn score, state.NewStatus(state.Success)\n}",
"func (room Room) GetScore() []int {\n\tvar scoreList []int\n\tfor _, player := range room.Players {\n\t\tscoreList = append(scoreList, player.Credit)\n\t}\n\treturn scoreList\n}",
"func (f *FileSystemPlayerStore) GetPlayerScore(name string) int {\n\n\tplayer := f.GetLeague().Find(name)\n\n\tif player != nil {\n\t\treturn player.Wins\n\t}\n\n\treturn 0\n}",
"func (k Keeper) GetGames(ctx sdk.Context) int64 {\n\treturn k.GetRunningAverageTotal(ctx, Games24ValueKey)\n}",
"func (b FirstEvaluator) Evaluate(pos *game.Position) float32 {\n\tigo, winner := pos.GameOver()\n\tif igo {\n\t\treturn winner.EvaluationWin()\n\t}\n\t// Theory:\n\t// * Winning subboards is good\n\t// * Number of legal moves is good(ish)\n\t// * Winning subboards relative to win condition - e.g. xor bigboard with wc and check\n\n\tbbSM := pos.BigBoard(pos.SideToMove)\n\n\t// calculate lowest mse with a win condition on a board\n\tbestMSESM := 1000\n\tmseSM := 0\n\tfor _, wc := range game.WinConditions {\n\t\tmseSM = bits.OnesCount32(wc ^ bbSM)\n\t\tif mseSM < bestMSESM {\n\t\t\tbestMSESM = mseSM\n\t\t}\n\t}\n\tfMseSM := float32(mseSM) / 9\n\n\t// calculate number of legal moves\n\tnlm := float32(pos.CountLegalMoves())\n\n\t// number of won subboards\n\tnwbbSM := float32(bits.OnesCount32(bbSM)) / 9\n\n\t// ---------------------------------------------\n\n\tbbSMO := pos.BigBoard(pos.SideToMove.Other())\n\n\t// calculate lowest mse with a win condition on a board\n\tbestMSESMO := 1000\n\tmseSMO := 0\n\tfor _, wc := range game.WinConditions {\n\t\tmseSMO = bits.OnesCount32(wc ^ bbSMO)\n\t\tif mseSMO < bestMSESMO {\n\t\t\tbestMSESMO = mseSM\n\t\t}\n\t}\n\tfMseSMO := float32(mseSMO) / 9\n\n\t// number of won subboards\n\tnwbbSMO := float32(bits.OnesCount32(bbSMO)) / 9\n\n\tvalue := .00002*nlm + (-0.08)*(fMseSM-fMseSMO) + 0.04*(nwbbSM-nwbbSMO)\n\treturn pos.SideToMove.EvaluationCoefficient() * value\n}",
"func (p *Player) GetScore() (score int) {\n\thasAce := false\n\tfor _, c := range p.DealtCards {\n\t\tif c.Rank == deck.Ace {\n\t\t\thasAce = true\n\t\t}\n\t\tscore += Scoring[c.Rank]\n\t}\n\tif hasAce {\n\t\tif score+10 <= blackjack {\n\t\t\tscore += 10\n\t\t}\n\t}\n\treturn score\n}",
"func GetScorer(home bool, game responses.FantasyGame) *Scorer {\n\tif home {\n\t\treturn &Scorer{\n\t\t\tTeam: game.Home,\n\t\t\tScore: game.HomeScore.Score.Value,\n\t\t}\n\t}\n\n\treturn &Scorer{\n\t\tTeam: game.Away,\n\t\tScore: game.AwayScore.Score.Value,\n\t}\n}",
"func (o *MicrosoftGraphControlScore) GetScore() AnyOfnumberstringstring {\n\tif o == nil || o.Score == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret\n\t}\n\treturn *o.Score\n}",
"func (m *SecureScoreControlProfile) GetMaxScore()(*float64) {\n val, err := m.GetBackingStore().Get(\"maxScore\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*float64)\n }\n return nil\n}",
"func (r *Rule) GetScore(colname string, row dur.Row) int64 {\n\tcell := row.Col(colname)\n\tvar res int64\n\tres = r.featureRaw.Get(colname + \".default\").Int()\n\tbin := r.featureRaw.Get(colname + \".bin\") //gjson.GetBytes(r.featureRaw, colname+\".bin\")\n\tbintype := r.featureRaw.Get(colname + \".bintype\").String()\n\t// pre logic\n\tpre := r.featureRaw.Get(colname + \".pre\").String()\n\tpreScore, need, error := ParsePre(pre, row)\n\tif error != nil {\n\t\tlog.Println(error)\n\t}\n\tif need {\n\t\treturn preScore\n\t}\n\n\t// if number\n\tif bintype == \"math\" {\n\t\tbin.ForEach(func(k, v gjson.Result) bool {\n\t\t\tn, err := strconv.ParseFloat(cell, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn false // if cannot conv to flat64 for example null then break and use default value\n\t\t\t}\n\t\t\tif mathinterval.Get(k.String()).Hit(n) {\n\t\t\t\tres = v.Int()\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t}\n\n\tif bintype == \"text\" {\n\t\tbin.ForEach(func(k, v gjson.Result) bool {\n\t\t\tif k.String() == cell {\n\t\t\t\tres = v.Int()\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t}\n\n\treturn res\n}",
"func ComputeScore(dir int, order elevio.ButtonEvent, atFloor int, idle bool) int {\n\tN := numFloors - 1\n\td := int(math.Abs(float64(atFloor - order.Floor)))\n\tif idle {\n\t\treturn (N + 3) - d\n\t}\n\t//towards call\n\tif ((dir == 1) == (order.Floor > atFloor)) && ((dir == 1) == (order.Floor >= atFloor)) {\n\t\tif order.Button == 0 { //same dir button\n\t\t\treturn (N + 2) - d\n\t\t} else if order.Button == 1 { //opposite dir button\n\t\t\treturn (N + 1) - d\n\t\t}\n\t}\n\t//away from call\n\treturn 1\n}",
"func (ap *AnimeParser) getScore(eachTop *goquery.Selection) float64 {\n\tscore := eachTop.Find(\"td:nth-of-type(3)\").Text()\n\tscore = strings.TrimSpace(strings.Replace(score, \"N/A\", \"\", -1))\n\treturn utils.StrToFloat(score)\n}",
"func (s PositionEvaluator) Evaluate(p *position.Position) float64 {\n\t// calculate initial material\n\tmaterial := p.GetMaterial()\n\tpceCount := p.GetPieceCount()\n\tpceList := p.GetPieceList()\n\n\tscore := material[position.WHITE] - material[position.BLACK]\n\n\t//calculate\n\t//piece\n\t//squares\n\tpce := position.PwP\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore += pawnTable[position.SQ64(sq120)]\n\t}\n\n\tpce = position.PbP\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore -= pawnTable[mirror64[position.SQ64(sq120)]]\n\t}\n\n\tpce = position.PwN\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore += knightTable[position.SQ64(sq120)]\n\t}\n\n\tpce = position.PbN\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore -= knightTable[mirror64[position.SQ64(sq120)]]\n\t}\n\n\tpce = position.PwB\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore += bishopTable[position.SQ64(sq120)]\n\t}\n\n\tpce = position.PbB\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore -= bishopTable[mirror64[position.SQ64(sq120)]]\n\t}\n\n\tpce = position.PwR\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore += rookTable[position.SQ64(sq120)]\n\t}\n\n\tpce = position.PbR\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore -= rookTable[mirror64[position.SQ64(sq120)]]\n\t}\n\n\treturn float64(score)\n}",
"func (r Round)countScore(players map[string]*Player, master *Player,countInTotal,countBadAnswer bool)(map[string]int,map[string]*DetailScore){\n\troundScore := make(map[string]int,len(players))\n\tdetailScore := make(map[string]*DetailScore,len(players))\n\tfor _,p := range players {\n\t\troundScore[p.Name] = 0\n\t\tdetailScore[p.Name] = &DetailScore{false,0,0}\n\t}\n\tfor playerID,vote := range r.votes {\n\t\tname := players[playerID].Name\n\t\tif r.playersDefinition[vote].isCorrect {\n\t\t\tif countInTotal {\n\t\t\t\tplayers[playerID].Score+=2\n\t\t\t}\n\t\t\troundScore[name] += 2\n\t\t\tg := detailScore[name]\n\t\t\tg.GoodDef = true\n\t\t}else{\n\t\t\tidDefinitionPlayer := r.playersDefinition[vote].playerId\n\t\t\tif countInTotal {\n\t\t\t\tplayers[idDefinitionPlayer].Score++\n\t\t\t}\n\t\t\troundScore[players[idDefinitionPlayer].Name] ++\n\t\t\tdetailScore[players[idDefinitionPlayer].Name].VotePoint++\n\t\t\t// Point bad response for master\n\t\t\tif countBadAnswer {\n\t\t\t\tif countInTotal {\n\t\t\t\t\tmaster.Score++\n\t\t\t\t}\n\t\t\t\troundScore[master.Name] ++\n\t\t\t\tdetailScore[master.Name].ErrorPoint++\n\t\t\t}\n\t\t}\n\t}\n\treturn roundScore,detailScore\n}",
"func (o *MicrosoftGraphControlScore) GetScoreOk() (AnyOfnumberstringstring, bool) {\n\tif o == nil || o.Score == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret, false\n\t}\n\treturn *o.Score, true\n}",
"func EmptyScore() Score {\n\treturn Score{\n\t\tScoreProposal: EmptyScoreProposal(header.Header{BlockHash: make([]byte, 32)}),\n\t\tCandidate: *block.NewBlock(),\n\t}\n}",
"func (no *NetworkOverhead) Score(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\tscore := framework.MinNodeScore\n\n\t// Get PreFilterState\n\tpreFilterState, err := getPreFilterState(cycleState)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to read preFilterState from cycleState\", \"preFilterStateKey\", preFilterStateKey)\n\t\treturn score, framework.NewStatus(framework.Error, \"not eligible due to failed to read from cycleState, return min score\")\n\t}\n\n\t// If scoreEqually, return minScore\n\tif preFilterState.scoreEqually {\n\t\treturn score, framework.NewStatus(framework.Success, \"scoreEqually enabled: minimum score\")\n\t}\n\n\t// Return Accumulated Cost as score\n\tscore = preFilterState.finalCostMap[nodeName]\n\tklog.V(4).InfoS(\"Score:\", \"pod\", pod.GetName(), \"node\", nodeName, \"finalScore\", score)\n\treturn score, framework.NewStatus(framework.Success, \"Accumulated cost added as score, normalization ensures lower costs are favored\")\n}",
"func (m *SecureScoreControlProfile) GetMaxScore()(*float64) {\n return m.maxScore\n}",
"func (s *Scorer) subtractScore(appID marathon.AppID) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tvar ok bool\n\tvar score *Score\n\tif score, ok = s.scores[appID]; !ok {\n\t\treturn\n\t}\n\n\tscore.score -= s.ScaleDownScore\n}",
"func (m *Vulnerability) GetPriorityScore()(*int32) {\n val, err := m.GetBackingStore().Get(\"priorityScore\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}",
"func (b *Block) Score() int64 {\n\treturn b.work\n}",
"func UpdateScore(c *fiber.Ctx) {\n\tShopID := c.Params(\"shop_id\")\n\tUserID := userIDF(c.Get(\"token\"))\n\n\tvar Data ScoreStruct\n\n\tif errorParse := c.BodyParser(&Data); errorParse != nil {\n\t\tfmt.Println(\"Error parsing data\", errorParse)\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Error al parsear información\"})\n\t\tc.Status(400)\n\t\treturn\n\t}\n\n\tif Data.Score <= 0 {\n\t\tfmt.Println(\"score can't be empty\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Score can't be empty\"})\n\t\tc.Status(400)\n\t\treturn\n\t}\n\n\tvar Score ScoreSQL\n\n\t_, ErrorUpdateScoreUser := sq.Update(\"shop_score_users\").\n\t\tSet(\"score\", Data.Score).\n\t\tWhere(\"user_id = ? AND shop_id = ?\", UserID, ShopID).\n\t\tRunWith(database).\n\t\tExec()\n\n\tif ErrorUpdateScoreUser != nil {\n\t\tfmt.Println(\"Error to update score\", ErrorUpdateScoreUser)\n\t}\n\n\tErrorScore := sq.Select(\n\t\t\"AVG(score) as score\",\n\t).\n\t\tFrom(\"shop_score_users\").\n\t\tWhere(\"shop_id = ?\", ShopID).\n\t\tRunWith(database).\n\t\tQueryRow().\n\t\tScan(\n\t\t\t&Score.Score,\n\t\t)\n\n\tif ErrorScore != nil {\n\t\tfmt.Println(ErrorScore, \"Error get score\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with get score\"})\n\t\tc.SendStatus(400)\n\t\treturn\n\t}\n\n\tqueryUpdateValue := sq.Update(\"shop\")\n\n\tScoreFloat, _ := strconv.ParseFloat(Score.Score.String, 64)\n\n\tNewScore := fmt.Sprintf(\"%.0f\", ScoreFloat)\n\n\t_, ErrorUpdateScoreShop := queryUpdateValue.\n\t\tSet(\"score_shop\", NewScore).\n\t\tWhere(\"shop_id = ? \", ShopID).\n\t\tRunWith(database).\n\t\tExec()\n\n\tif ErrorUpdateScoreShop != nil {\n\t\tfmt.Println(ErrorUpdateScoreShop, \"Problem with update score\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with update score\"})\n\t\tc.SendStatus(500)\n\t\treturn\n\t}\n\n\tc.JSON(SuccessResponse{MESSAGE: \"Calificación actualizada\"})\n}",
"func addScore(s int){\n\tscoreData.Scores = append(scoreData.Scores, s)\n\t\t\t\n\t\t\t// TODO: check if there is a score to check with\n\t\t\tsort.Slice(scoreData.Scores, func(i, j int) bool { return scoreData.Scores[i] > scoreData.Scores[j] })\n\t\t\tif scoreData.Scores[0] > scoreData.Highscore {\n\t\t\t\ttmp := scoreData.Highscore\n\t\t\t\tscoreData.Highscore = scoreData.Scores[0]\n\t\t\t\tscoreData.Scores[0] = tmp\n\t\t\t}\n\t\t\t\n}",
"func Score(hand ...deck.Card) int {\n\tminScore := minScore(hand...)\n\tif minScore > 11 {\n\t\treturn minScore\n\t}\n\tfor _, c := range hand {\n\t\tif int(c.Rank) == 1 {\n\t\t\t// ace is currently worth 1, and we are changing it to be worth 11\n\t\t\t// 11 - 1 = 10\n\t\t\treturn minScore + 10\n\t\t}\n\t}\n\treturn minScore\n}",
"func (game *Game) calculateRoundWinner() {\n\tlowestScoreIndex := 0 //default to first player.. incase they all have the same score\n\tlowestScore := MaxRoundScore\n\n\tfor i := range game.players {\n\t\tif game.players[i].roundScores[game.roundIndex] < lowestScore {\n\t\t\tlowestScoreIndex = i\n\t\t\tlowestScore = game.players[i].roundScores[game.roundIndex]\n\t\t}\n\t}\n\n\tgame.roundWinner[game.roundIndex] = lowestScoreIndex\n}",
"func (m *MockScoring) GetScore(arg0 string) (float64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetScore\", arg0)\n\tret0, _ := ret[0].(float64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}",
"func (t *Table) ScoreRound() []int {\n\tallPoints := 26\n\troundScores := make([]int, len(t.players))\n\tshotMoon := false\n\tshooter := -1\n\tfor i := 0; i < len(t.players); i++ {\n\t\troundScores[i] = t.players[i].CalculateScore()\n\t\tif roundScores[i] == allPoints {\n\t\t\tshotMoon = true\n\t\t\tshooter = i\n\t\t}\n\t}\n\tif shotMoon {\n\t\tfor i := 0; i < len(t.players); i++ {\n\t\t\tif i == shooter {\n\t\t\t\troundScores[i] = 0\n\t\t\t} else {\n\t\t\t\troundScores[i] = allPoints\n\t\t\t}\n\t\t}\n\t}\n\treturn roundScores\n}",
"func SetScore(c *fiber.Ctx) {\n\tShopID := c.Params(\"shop_id\")\n\tUserID := userIDF(c.Get(\"token\"))\n\n\tvar Data ScoreStruct\n\n\tif errorParse := c.BodyParser(&Data); errorParse != nil {\n\t\tfmt.Println(\"Error parsing data\", errorParse)\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Error al parsear información\"})\n\t\tc.Status(400)\n\t\treturn\n\t}\n\n\tif Data.Score <= 0 {\n\t\tfmt.Println(\"score can't be empty\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Score can't be empty\"})\n\t\tc.Status(400)\n\t\treturn\n\t}\n\n\tvar Score ScoreSQL\n\tvar Response ResponseScore\n\n\t_, errorInsert := sq.Insert(\"shop_score_users\").\n\t\tColumns(\n\t\t\t\"user_id\",\n\t\t\t\"shop_id\",\n\t\t\t\"score\",\n\t\t).\n\t\tValues(\n\t\t\tUserID,\n\t\t\tShopID,\n\t\t\tData.Score,\n\t\t).\n\t\tRunWith(database).\n\t\tExec()\n\n\tif errorInsert != nil {\n\t\tfmt.Println(\"Error to save score\", errorInsert)\n\t}\n\n\tErrorScore := sq.Select(\n\t\t\"AVG(score) as score\",\n\t).\n\t\tFrom(\"shop_score_users\").\n\t\tWhere(\"shop_id = ?\", ShopID).\n\t\tRunWith(database).\n\t\tQueryRow().\n\t\tScan(\n\t\t\t&Score.Score,\n\t\t)\n\n\tif ErrorScore != nil {\n\t\tfmt.Println(ErrorScore, \"Error get score\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with get score\"})\n\t\tc.SendStatus(400)\n\t\treturn\n\t}\n\n\tqueryUpdateValue := sq.Update(\"shop\")\n\n\tScoreFloat, _ := strconv.ParseFloat(Score.Score.String, 64)\n\n\tNewScore := fmt.Sprintf(\"%.0f\", ScoreFloat)\n\n\t_, ErrorUpdateOffer := queryUpdateValue.\n\t\tSet(\"score_shop\", NewScore).\n\t\tWhere(\"shop_id = ? \", ShopID).\n\t\tRunWith(database).\n\t\tExec()\n\n\tif ErrorUpdateOffer != nil {\n\t\tfmt.Println(ErrorUpdateOffer, \"Problem with update score\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with update score\"})\n\t\tc.SendStatus(500)\n\t\treturn\n\t}\n\n\tResponse.Score = &NewScore\n\n\tc.JSON(Response)\n}",
"func (l *LabelResult) GetScore() *float64 {\n\tif l == nil {\n\t\treturn nil\n\t}\n\treturn l.Score\n}",
"func Score(c *fiber.Ctx) {\n\tShopID := c.Params(\"shop_id\")\n\tUserID := c.Params(\"user_id\")\n\tvar Score ScoreSQL\n\tvar Response ResponseScore\n\n\tErrorScore := sq.Select(\n\t\t\"AVG(score) as score\",\n\t).\n\t\tFrom(\"shop_score_users\").\n\t\tWhere(\"shop_id = ? AND user_id = ?\", ShopID, UserID).\n\t\tRunWith(database).\n\t\tQueryRow().\n\t\tScan(\n\t\t\t&Score.Score,\n\t\t)\n\n\tif ErrorScore != nil {\n\t\tfmt.Println(ErrorScore, \"Error get score\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with get score\"})\n\t\tc.SendStatus(400)\n\t\treturn\n\t}\n\n\tResponse.Score = &Score.Score.String\n\n\tc.JSON(Response)\n}",
"func (i *InMemoryPlayerStore) GetPlayerScore(name string) int {\n\treturn i.store[name]\n}",
"func (b *Bound) Left() float64 {\n\treturn b.sw[0]\n}",
"func (stats *AccuracyStatistics) GetAccuracyStats(remainingScore int, dart *Dart) {\n\tif remainingScore-dart.GetScore() < 171 {\n\t\t// We only want to calculate accuracy stats when player has a remaining score over 170\n\t\treturn\n\t}\n\n\tscore := dart.Value.Int64\n\tswitch score {\n\tcase 20:\n\t\tstats.hits20++\n\t\tstats.attempts20++\n\t\tstats.Accuracy20.Float64 += 100\n\tcase 5, 1:\n\t\tstats.attempts20++\n\t\tstats.Accuracy20.Float64 += 70\n\tcase 12, 18:\n\t\tstats.attempts20++\n\t\tstats.Accuracy20.Float64 += 30\n\tcase 9, 4:\n\t\tstats.attempts20++\n\t\tstats.Accuracy20.Float64 += 5\n\tcase 19:\n\t\tstats.hits19++\n\t\tstats.attempts19++\n\t\tstats.Accuracy19.Float64 += 100\n\tcase 7, 3:\n\t\tstats.attempts19++\n\t\tstats.Accuracy19.Float64 += 70\n\tcase 16, 17:\n\t\tstats.attempts19++\n\t\tstats.Accuracy19.Float64 += 30\n\tcase 8, 2:\n\t\tstats.attempts19++\n\t\tstats.Accuracy19.Float64 += 5\n\tdefault:\n\t\tstats.misses++\n\t}\n}",
"func Score(x, y float64) int {\n\tswitch dist := math.Sqrt(x*x + y*y); {\n\tcase dist <= inner:\n\t\treturn 10\n\tcase dist <= middle:\n\t\treturn 5\n\tcase dist <= outer:\n\t\treturn 1\n\tdefault:\n\t\treturn 0\n\t}\n}",
"func Score(hand ...deck.Card) int {\n\tminScore := minScore(hand...)\n\tif minScore > 11 {\n\t\t// we can't increase 12 to 22, because that will be a bust\n\t\treturn minScore\n\t}\n\n\tfor _, c := range hand {\n\t\tif c.Rank == deck.Ace {\n\t\t\t// ace is currently worth 1, and we are changing it to be worth 11\n\t\t\t// 11 - 1 = 10\n\t\t\treturn minScore + 10\n\t\t}\n\t}\n\treturn minScore\n}",
"func updatePawnChainScore(pawnchain int) float64 {\n\tvar score float64\n\tif pawnchain > 2 {\n\t\tscore += float64(pawnchain) * LONGPAWNCHAIN\n\t} else if pawnchain != 0 {\n\t\tscore += ISOLATEDPAWN / float64(pawnchain)\n\t}\n\treturn score\n}",
"func (vk *VK) AppsGetScore(params map[string]string) (response AppsGetScoreResponse, vkErr Error) {\n\tvk.RequestUnmarshal(\"apps.getScore\", params, &response, &vkErr)\n\treturn\n}",
"func Score(state State) float32 {\n\tswitch state {\n\tcase Unknown:\n\t\treturn 0\n\tcase Outage:\n\t\treturn 0.25\n\tcase Major:\n\t\treturn 0.50\n\tcase Minor:\n\t\treturn 0.75\n\tcase OK:\n\t\treturn 1.00\n\tdefault:\n\t\treturn 0\n\t}\n}",
"func (o *SecureScore) HasCurrentScore() bool {\n\tif o != nil && o.CurrentScore != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (l *LexerEngine) Score() int {\n\treturn l.score\n}",
"func (move Move) Score() uint16 {\n\treturn uint16(move & 0xffff)\n}",
"func (solution Solution) Score() int {\n\tscore := 0\n\tfor _, order := range solution {\n\t\tscore += order.score\n\t}\n\n\treturn score\n}",
"func GetScores(ctx context.Context, id int) g.Map {\n\tctx, span := gtrace.NewSpan(ctx, \"GetScores\")\n\tdefer span.End()\n\tif id == 100 {\n\t\treturn g.Map{\n\t\t\t\"math\": 100,\n\t\t\t\"english\": 60,\n\t\t\t\"chinese\": 50,\n\t\t}\n\t}\n\treturn nil\n}",
"func (m *PlayerMutation) Score() (r int, exists bool) {\n\tv := m.score\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}",
"func (am *Antman) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\tklog.Infof(\"in Score for podName : %v\", pod.Name)\n\tnodeInfo, err := am.frameworkHandle.SnapshotSharedLister().NodeInfos().Get(nodeName)\n\tif err != nil {\n\t\treturn 0, framework.NewStatus(framework.Error, fmt.Sprintf(\"getting node %q from Snapshot: %v\", nodeName, err))\n\t}\n\n\tpodInfo := am.getOrCreatePodInfo(pod, time.Now())\n\tpodKey := podInfo.key\n\tif len(podKey) == 0 {\n\t\t// normal pod, not opportunistic pod in antman\n\t\t// return 100 for every node to bypass the scoring\n\t\treturn int64(100), nil\n\t}\n\n\t// note that, because there are multiple score plugins in k8s\n\t// it is not the final score for this node\n\treturn am.GpuScore(state, pod, nodeInfo)\n}",
"func (sr *ServiceRegistry) GetScores() (map[string]int, error) {\n\tsr.Lock()\n\n\tif sr.Services == nil || len(sr.Services) == 0 {\n\t\treturn nil, fmt.Errorf(\"no services found in the service registry\")\n\t}\n\n\tscores := map[string]int{}\n\n\tfor teamName, services := range sr.Services {\n\t\tscores[teamName] = 0\n\t\tfor _, service := range services {\n\t\t\tscores[teamName] = scores[teamName] + service.Points\n\t\t}\n\t}\n\n\tsr.Unlock()\n\n\treturn scores, nil\n}",
"func (ps *PodState) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\tnodeInfo, err := ps.handle.SnapshotSharedLister().NodeInfos().Get(nodeName)\n\tif err != nil {\n\t\treturn 0, framework.NewStatus(framework.Error, fmt.Sprintf(\"getting node %q from Snapshot: %v\", nodeName, err))\n\t}\n\n\t// pe.score favors nodes with terminating pods instead of nominated pods\n\t// It calculates the sum of the node's terminating pods and nominated pods\n\treturn ps.score(nodeInfo)\n}",
"func Score(hand ...deck.Card) int { // using variadic so user can pass in just one card if desired\n\tminScore := minScore(hand...)\n\tif minScore > 11 {\n\t\treturn minScore\n\t}\n\tfor _, c := range hand {\n\t\tif c.Rank == deck.Ace {\n\t\t\treturn minScore + 10 // ace is currently worth 1, so adding 10 to make it worth 11\n\t\t}\n\t\t// only 1 ace can be used as 11 and still be under 21\n\t}\n\treturn minScore\n}",
"func GetGameStatsFromRolls(rolls []string) (game Game, gameError error) {\n\t// set up the game state\n\tgame = getEmptyGame()\n\n\trollData, err := getCleanedRollsData(rolls)\n\n\tif err != nil {\n\t\t// roll data is invalid. Cannot continue\n\t\tgameErrorMessage := fmt.Sprintf(\"Error: Game stats could not be calculated because the roll data is invalid. %v\", err)\n\t\tgameError = errors.New(gameErrorMessage)\n\t\treturn\n\t}\n\n\tfor _, currentRoll := range rollData {\n\t\tgame.GameState = gameInProgress\n\t\t// add roll to the current frame\n\t\tgame.addRoll(currentRoll)\n\n\t\t// move to the next frame\n\t\tgame.advanceGameState()\n\t}\n\n\treturn\n}",
"func (g *Game) GetOpponentScore() int {\n\treturn g.opponentScore\n}",
"func (o *MicrosoftGraphControlScore) HasScore() bool {\n\tif o != nil && o.Score != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func DefuseScore(g *Game, p *Player) (c *ScoreCard) {\n\n\tc = new(ScoreCard)\n\tc.Player = p\n\n\tif p.Dead {\n\t\tc.Score = 0\n\t\treturn\n\t}\n\n\tc.Score = uint64(p.Duration / time.Second)\n\n\t// The player that defused the bomb gets 5 minutes bonus!\n\tif p.Defused {\n\t\tc.Score = c.Score + 60*5\n\t}\n\n\treturn\n}",
"func (o *TileBounds) GetLeft() int32 {\n\tif o == nil || o.Left == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Left\n}",
"func (s *PublicSfcAPI) GetValidationScore(ctx context.Context, stakerID hexutil.Uint) (*hexutil.Big, error) {\n\tv, err := s.b.GetValidationScore(ctx, idx.StakerID(stakerID))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn (*hexutil.Big)(v), err\n}",
"func MockScore(hdr header.Header, c block.Block) Score {\n\tprevHash, _ := crypto.RandEntropy(32)\n\n\treturn Score{\n\t\tScoreProposal: MockScoreProposal(hdr),\n\t\tPrevHash: prevHash,\n\t\tCandidate: c,\n\t}\n}",
"func GetSmsLeft(lastname, login, pass string) (SmsLeft, error) {\n\tclient, err := newHTTPClient()\n\tif err != nil {\n\t\treturn NoSmsLeft, errors.Wrap(err, \"unable to create httpClient\")\n\t}\n\n\tloginner := httpLoginner{client}\n\tif err = loginner.Login(lastname, login, pass); err != nil {\n\t\treturn NoSmsLeft, errors.Wrap(err, \"unable to login\")\n\t}\n\n\tsmsLeftGetter := &httpSmsLeftGetter{client}\n\treturn smsLeftGetter.Get()\n}",
"func (o *SecureScore) GetCurrentScoreOk() (AnyOfnumberstringstring, bool) {\n\tif o == nil || o.CurrentScore == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret, false\n\t}\n\treturn *o.CurrentScore, true\n}",
"func getScoreTest(scoreType string) func(float64, float64) float64 {\n\tif scoreType == \"gte\" {\n\t\treturn func(score, currentThreshold float64) float64 {\n\t\t\tif score < currentThreshold {\n\t\t\t\treturn score\n\t\t\t}\n\t\t\treturn currentThreshold\n\t\t}\n\t}\n\treturn func(score, currentThreshold float64) float64 {\n\t\tif score > currentThreshold {\n\t\t\treturn score\n\t\t}\n\t\treturn currentThreshold\n\t}\n}",
"func (g *Game) renderScore(f *Frame) {\n\tcol, row := scoreCoords()\n\tf.Draw(fmt.Sprintf(\"Score: %d\", g.score), col, row, ColorDefault, ColorDefault)\n}",
"func (b *Board) ScoreFloor() {\n\tfor _, tile := range b.Floor {\n\t\tb.Score -= tile.ScoreModifier\n\t}\n\tb.ResetFloor()\n}",
"func incrementScore(b *bot.SlackBot, team, user string) (int, error) {\n\n\tscore := 0\n\n\tsess, err := session.NewSession(&aws.Config{Region: aws.String(b.Region)})\n\tif err != nil {\n\t\treturn score, errors.Wrap(err, \"unable to create session\")\n\t}\n\n\tddb := dynamodb.New(sess)\n\n\tinput := &dynamodb.UpdateItemInput{\n\t\tExpressionAttributeValues: map[string]*dynamodb.AttributeValue{\":s\": {N: aws.String(\"1\")}},\n\t\tTableName: aws.String(b.ScoreTable),\n\t\tKey: map[string]*dynamodb.AttributeValue{\"uid\": {S: aws.String(team + \":\" + user)}},\n\t\tReturnValues: aws.String(\"UPDATED_NEW\"),\n\t\tUpdateExpression: aws.String(\"add score :s\"),\n\t}\n\n\tv, err := ddb.UpdateItem(input)\n\tif err != nil {\n\t\treturn score, errors.Wrap(err, \"unable to update database\")\n\t}\n\n\terr = dynamodbattribute.Unmarshal(v.Attributes[\"score\"], &score)\n\n\tif err != nil {\n\t\treturn score, errors.Wrap(err, \"unable to unmarshal return value\")\n\t}\n\n\treturn score, nil\n}",
"func (pl *RepeatPriority) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\n rnode := pl.handle.GetNodeUsageFactor(nodeName)\n rhigh := pl.handle.GetHighestUsageFactor()\n\n nodeRF := float64(rnode)/float64(rhigh)\n score := math.Exp(-5*float64(nodeRF))\n return int64(score*100), nil\n}",
"func (c *Claim) Score(ctx *ServerContext) (float32, Error) {\n\tif c.QueryAt == nil {\n\t\treturn c.Truth, nil\n\t}\n\treturn c.scoreAt(ctx)\n}",
"func (d *Dispatcher) calScore(numReqs, restSpace int, avgResponseTime float) score int {\n\t//\n\treturn\n}",
"func (s *Server) GetScore(id string) (models.Score, error) {\n\tscore := models.Score{\n\t\tPlayer: id,\n\t}\n\n\tscoreQuery, err := s.database.PrepareNamed(\n\t\t`SELECT * FROM scores\n\t\tWHERE player = :player`)\n\tif err != nil {\n\t\ts.logger.Error(\"Prepare score query\", \"error\", err)\n\t}\n\n\terr = scoreQuery.Get(&score, score)\n\tif err == sql.ErrNoRows {\n\t\treturn score, err\n\t}\n\n\tif err != nil {\n\t\ts.logger.Error(\"Query score\", \"error\", err)\n\t\treturn score, err\n\t}\n\n\treturn score, nil\n}",
"func (p *Password) GetScore() int {\n\treturn p.Score\n}",
"func (m *PlayerMutation) AddedScore() (r int, exists bool) {\n\tv := m.addscore\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}",
"func Score(x, y float64) int {\n\tdistance := math.Sqrt(math.Pow(x, 2) + math.Pow(y, 2))\n\n\tswitch {\n\tcase distance <= 1:\n\t\treturn 10\n\tcase distance <= 5:\n\t\treturn 5\n\tcase distance <= 10:\n\t\treturn 1\n\tdefault:\n\t\treturn 0\n\t}\n}",
"func FormatScore(game responses.FantasyGame) string {\n\thomeTeam := game.Home.Name\n\tawayTeam := game.Away.Name\n\n\thomeScore := game.HomeScore.Score.Value\n\tawayScore := game.AwayScore.Score.Value\n\n\tif homeScore > awayScore {\n\t\treturn fmt.Sprintf(\"%v beat %v with a score of %.2f-%.2f.\\n\", homeTeam, awayTeam, homeScore, awayScore)\n\t} else if awayScore > homeScore {\n\t\treturn fmt.Sprintf(\"%v beat %v with a score of %.2f-%.2f.\\n\", awayTeam, homeTeam, awayScore, homeScore)\n\t} else {\n\t\treturn fmt.Sprintf(\"Whaaaat....%v and %v tied with a score of %.2f-%.2f.\\n\", homeTeam, awayTeam, homeScore, awayScore)\n\t}\n}",
"func CalculateMatchScore(region string, summoners []rgapi.Summoner) (*MatchScore, error) {\n\tif len(summoners) != PlayersPerMatch {\n\t\treturn nil, errors.New(fmt.Sprint(\n\t\t\t\"Calculating match score requires \", PlayersPerMatch, \" players, was given \", len(summoners)))\n\t}\n\n\t//For each summoner, get the best game they have in their recent history\n\t//TODO: Save timestamp of most recently checked games in DB or Redis\n\tplayerScores := make([]*PlayerScore, len(summoners))\n\tfor i := 0; i < len(summoners); i++ {\n\t\tplayerScore, err := PlayerScoreBestRecent(region, summoners[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tplayerScores[i] = playerScore\n\t}\n\n\t//Create teams and match score objects\n\tblueTeamScore := TeamScore{\n\t\tTop: playerScores[0],\n\t\tJungle: playerScores[1],\n\t\tMid: playerScores[2],\n\t\tBottom: playerScores[3],\n\t\tSupport: playerScores[4],\n\t\tScore: playerScores[0].Score + playerScores[1].Score + playerScores[2].Score + playerScores[3].Score + playerScores[4].Score,\n\t}\n\tblueTeamScore.ScoreString = fmt.Sprintf(\"%.2f\", blueTeamScore.Score)\n\tredTeamScore := TeamScore{\n\t\tTop: playerScores[5],\n\t\tJungle: playerScores[6],\n\t\tMid: playerScores[7],\n\t\tBottom: playerScores[8],\n\t\tSupport: playerScores[9],\n\t\tScore: playerScores[5].Score + playerScores[6].Score + playerScores[7].Score + playerScores[8].Score + playerScores[9].Score,\n\t}\n\tredTeamScore.ScoreString = fmt.Sprintf(\"%.2f\", redTeamScore.Score)\n\tmatchScore := MatchScore{\n\t\tBlueTeam: blueTeamScore,\n\t\tRedTeam: redTeamScore,\n\t}\n\n\t//Pick the winner\n\t//TODO: Do this by user-selected team name instead of Blue/Red\n\tif blueTeamScore.Score > redTeamScore.Score {\n\t\tmatchScore.WinningSide = BlueTeam\n\t\tmatchScore.WinningTeam = \"Blue\"\n\t} else if redTeamScore.Score > blueTeamScore.Score {\n\t\tmatchScore.WinningSide = RedTeam\n\t\tmatchScore.WinningTeam = \"Red\"\n\t}\n\n\treturn &matchScore, nil\n}",
"func Score(fileOptions map[string]interface{}) {\n\toptions, err := parseFlags(fileOptions)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tinputFiles := readSharedInputFiles(options)\n\n\tscores := preyScore{\n\t\tBait: calculateBaitComponent(options, inputFiles),\n\t\tDomain: calculateDomainComponent(options, inputFiles),\n\t\tStudy: calculateStudyComponent(options, inputFiles),\n\t\tText: calculateTextComponent(options, inputFiles),\n\t}\n\n\twriteScores(scores, inputFiles, options.outFile)\n}",
"func (s *PublicSfcAPI) GetOriginationScore(ctx context.Context, stakerID hexutil.Uint) (*hexutil.Big, error) {\n\tv, err := s.b.GetOriginationScore(ctx, idx.StakerID(stakerID))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn (*hexutil.Big)(v), err\n}",
"func GetScore(res http.ResponseWriter, req *http.Request) {\n\tswitch req.Method {\n\n\t}\n}",
"func (o *SecureScore) GetMaxScore() AnyOfnumberstringstring {\n\tif o == nil || o.MaxScore == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret\n\t}\n\treturn *o.MaxScore\n}"
] | [
"0.6696034",
"0.63771224",
"0.61025196",
"0.6052825",
"0.58927405",
"0.5823099",
"0.58230156",
"0.58192295",
"0.58158493",
"0.5772777",
"0.57697165",
"0.57476145",
"0.5745706",
"0.57228965",
"0.5706288",
"0.570082",
"0.5670466",
"0.5651189",
"0.5647113",
"0.5632848",
"0.5629679",
"0.5608018",
"0.5573327",
"0.55683315",
"0.5566474",
"0.5545459",
"0.5504814",
"0.5497783",
"0.5472838",
"0.54686344",
"0.5448416",
"0.5440548",
"0.5413772",
"0.54019064",
"0.5394001",
"0.53848517",
"0.5351391",
"0.53291005",
"0.5316563",
"0.53111374",
"0.52958983",
"0.5290529",
"0.52869374",
"0.5286461",
"0.528544",
"0.52832514",
"0.5253016",
"0.52510303",
"0.5240297",
"0.52295166",
"0.52243084",
"0.522035",
"0.5218126",
"0.5214968",
"0.52069646",
"0.5170066",
"0.51539963",
"0.5149497",
"0.5146764",
"0.5145011",
"0.51412195",
"0.51388305",
"0.5123739",
"0.51201594",
"0.51145333",
"0.5108013",
"0.51073045",
"0.51052344",
"0.5088923",
"0.507741",
"0.5071208",
"0.5066448",
"0.50599724",
"0.50330293",
"0.5029668",
"0.5025996",
"0.5022794",
"0.5021085",
"0.50166184",
"0.50154704",
"0.50004756",
"0.4997387",
"0.49944416",
"0.49915242",
"0.49903226",
"0.49815622",
"0.49755847",
"0.49703568",
"0.4969253",
"0.49622843",
"0.49547562",
"0.49534965",
"0.4947173",
"0.49435657",
"0.49307323",
"0.49289092",
"0.49090922",
"0.4904131",
"0.4900561",
"0.48969272"
] | 0.81663126 | 0 |
GameScore calculates score for right and left side | func (g *Game) GameScore() (uint, uint) {
left := round(float64(g.TournamentTable.Tournament.GameScore) * g.gameLeftScoreFactor())
return g.TournamentTable.Tournament.GameScore - left, left
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"func (g *Game) UpdateScore() error {\n\tswitch g.Winner {\n\tcase RIGHT:\n\t\tright, _ := g.GameScore()\n\t\tg.RightScore = int(right)\n\t\tg.LeftScore = -int(right)\n\t\treturn nil\n\tcase LEFT:\n\t\t_, left := g.GameScore()\n\t\tg.RightScore = -int(left)\n\t\tg.LeftScore = int(left)\n\t\treturn nil\n\tcase DRAW:\n\t\tscore := g.TournamentTable.Tournament.GameScore / 2\n\t\tg.RightScore = int(score)\n\t\tg.LeftScore = int(score)\n\t\treturn nil\n\tdefault:\n\t\treturn errors.New(\"no winner in this game\")\n\t}\n}",
"func calcScore2(opp string, me string) int {\n\tif me == \"X\" {\n\t\t/*\n\t\t* LOSE\n\t\t* A -> Rock 3\n\t\t* B -> Paper 1\n\t\t* C -> Scissor 2\n\t\t */\n\t\tswitch opp {\n\t\tcase \"A\":\n\t\t\treturn LOSE + 3\n\t\tcase \"B\":\n\t\t\treturn LOSE + 1\n\t\tcase \"C\":\n\t\t\treturn LOSE + 2\n\t\tdefault:\n\t\t\treturn 0\n\t\t}\n\t} else if me == \"Y\" {\n\t\tswitch opp {\n\t\tcase \"A\":\n\t\t\treturn TIE + 1\n\t\tcase \"B\":\n\t\t\treturn TIE + 2\n\t\tcase \"C\":\n\t\t\treturn TIE + 3\n\t\tdefault:\n\t\t\treturn 0\n\t\t}\n\t} else {\n\t\t/*\n\t\t* WIN\n\t\t* A -> Rock 2\n\t\t* B -> Paper 3\n\t\t* C -> Scissor 1\n\t\t */\n\t\tswitch opp {\n\t\tcase \"A\":\n\t\t\treturn WIN + 2\n\t\tcase \"B\":\n\t\t\treturn WIN + 3\n\t\tcase \"C\":\n\t\t\treturn WIN + 1\n\t\tdefault:\n\t\t\treturn 0\n\t\t}\n\t}\n}",
"func (r Round)countScore(players map[string]*Player, master *Player,countInTotal,countBadAnswer bool)(map[string]int,map[string]*DetailScore){\n\troundScore := make(map[string]int,len(players))\n\tdetailScore := make(map[string]*DetailScore,len(players))\n\tfor _,p := range players {\n\t\troundScore[p.Name] = 0\n\t\tdetailScore[p.Name] = &DetailScore{false,0,0}\n\t}\n\tfor playerID,vote := range r.votes {\n\t\tname := players[playerID].Name\n\t\tif r.playersDefinition[vote].isCorrect {\n\t\t\tif countInTotal {\n\t\t\t\tplayers[playerID].Score+=2\n\t\t\t}\n\t\t\troundScore[name] += 2\n\t\t\tg := detailScore[name]\n\t\t\tg.GoodDef = true\n\t\t}else{\n\t\t\tidDefinitionPlayer := r.playersDefinition[vote].playerId\n\t\t\tif countInTotal {\n\t\t\t\tplayers[idDefinitionPlayer].Score++\n\t\t\t}\n\t\t\troundScore[players[idDefinitionPlayer].Name] ++\n\t\t\tdetailScore[players[idDefinitionPlayer].Name].VotePoint++\n\t\t\t// Point bad response for master\n\t\t\tif countBadAnswer {\n\t\t\t\tif countInTotal {\n\t\t\t\t\tmaster.Score++\n\t\t\t\t}\n\t\t\t\troundScore[master.Name] ++\n\t\t\t\tdetailScore[master.Name].ErrorPoint++\n\t\t\t}\n\t\t}\n\t}\n\treturn roundScore,detailScore\n}",
"func (g *Game) Score() int {\n\trollIndex := 0\n\tfor frame := 0; frame < frameNumberPerGame; frame++ {\n\t\tif g.isStrike(rollIndex) {\n\t\t\tg.score += cleanPinNumber + g.getStrikeBonus(rollIndex)\n\t\t\trollIndex++\n\t\t} else if g.isSpare(rollIndex) {\n\t\t\tg.score += cleanPinNumber + g.getSpareBonus(rollIndex)\n\t\t\trollIndex += 2\n\t\t} else {\n\t\t\tg.score += g.getFrameScore(rollIndex)\n\t\t\trollIndex += 2\n\t\t}\n\n\t}\n\treturn g.score\n}",
"func (p Problem) Score(correct []int, actual []int) float64 {\n\tgap := 0.0\n\tfor i:=0 ; i < len(correct) && i < len(actual); i++ {\n\t\tgap += math.Abs(float64(correct[i]) - float64(actual[i]))\n\t}\n\n\treturn -gap\n}",
"func Score(x, y float64) int {\n\tswitch dist := math.Sqrt(x*x + y*y); {\n\tcase dist <= inner:\n\t\treturn 10\n\tcase dist <= middle:\n\t\treturn 5\n\tcase dist <= outer:\n\t\treturn 1\n\tdefault:\n\t\treturn 0\n\t}\n}",
"func ComputeScore(dir int, order elevio.ButtonEvent, atFloor int, idle bool) int {\n\tN := numFloors - 1\n\td := int(math.Abs(float64(atFloor - order.Floor)))\n\tif idle {\n\t\treturn (N + 3) - d\n\t}\n\t//towards call\n\tif ((dir == 1) == (order.Floor > atFloor)) && ((dir == 1) == (order.Floor >= atFloor)) {\n\t\tif order.Button == 0 { //same dir button\n\t\t\treturn (N + 2) - d\n\t\t} else if order.Button == 1 { //opposite dir button\n\t\t\treturn (N + 1) - d\n\t\t}\n\t}\n\t//away from call\n\treturn 1\n}",
"func (g *Game) renderScore(f *Frame) {\n\tcol, row := scoreCoords()\n\tf.Draw(fmt.Sprintf(\"Score: %d\", g.score), col, row, ColorDefault, ColorDefault)\n}",
"func (v *Vote) Score(r []int) int {\n\tif DumbScore {\n\t\treturn v.DumbScore(r)\n\t}\n\th := make(map[int]int) //map candidates to index\n\tfor k, v := range v.C {\n\t\tki, err := strconv.Atoi(k)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\th[v] = ki\n\t}\n\n\tres := 0\n\tfor i := 0; i < len(r); i++ {\n\t\tif r[i] == -1 {\n\t\t\tcontinue\n\t\t}\n\t\tw := (r[i] - len(r)/2)\n\t\tif w < 0 {\n\t\t\tw = -w\n\t\t\tw += len(r) - r[i]\n\t\t} else {\n\t\t\tw++\n\t\t}\n\t\trx := (i - h[r[i]]) * w\n\t\tif rx < 0 {\n\t\t\tres += -rx\n\t\t} else {\n\t\t\tres += rx\n\t\t}\n\t}\n\treturn res\n}",
"func (s PositionEvaluator) Evaluate(p *position.Position) float64 {\n\t// calculate initial material\n\tmaterial := p.GetMaterial()\n\tpceCount := p.GetPieceCount()\n\tpceList := p.GetPieceList()\n\n\tscore := material[position.WHITE] - material[position.BLACK]\n\n\t//calculate\n\t//piece\n\t//squares\n\tpce := position.PwP\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore += pawnTable[position.SQ64(sq120)]\n\t}\n\n\tpce = position.PbP\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore -= pawnTable[mirror64[position.SQ64(sq120)]]\n\t}\n\n\tpce = position.PwN\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore += knightTable[position.SQ64(sq120)]\n\t}\n\n\tpce = position.PbN\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore -= knightTable[mirror64[position.SQ64(sq120)]]\n\t}\n\n\tpce = position.PwB\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore += bishopTable[position.SQ64(sq120)]\n\t}\n\n\tpce = position.PbB\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore -= bishopTable[mirror64[position.SQ64(sq120)]]\n\t}\n\n\tpce = position.PwR\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore += rookTable[position.SQ64(sq120)]\n\t}\n\n\tpce = position.PbR\n\tfor i := 0; i < pceCount[pce]; i++ {\n\t\tsq120 := pceList[pce][i]\n\t\tscore -= rookTable[mirror64[position.SQ64(sq120)]]\n\t}\n\n\treturn float64(score)\n}",
"func evaluate(board [8][8]int, player int) float32 {\n\tvar score float32\n\n\t//Created a grid of relative score values for each cell\n\t//Based on Reversi strategy\n\t//Corners are stable and valuable, but adjacent cells can lead to losing a corner\n\t//Edge pieces are somewhat stable and valuable otherwise\n\t//Cells 2 away from corner facilitate corner capturing\n\t//All other tiles are weighted at 1\n\n\tcellValue := [][]int{\n\t\t{50, -20, 10, 5, 5, 10, -20, 50},\n\t\t{-20, -20, 1, 1, 1, 1, -20, -20},\n\t\t{10, 1, 5, 1, 1, 5, 1, 10},\n\t\t{5, 1, 1, 1, 1, 1, 1, 5},\n\t\t{5, 1, 1, 1, 1, 1, 1, 5},\n\t\t{10, 1, 5, 1, 1, 5, 1, 10},\n\t\t{-20, -20, 1, 1, 1, 1, -20, -20},\n\t\t{50, -20, 10, 5, 5, 10, -20, 50},\n\t}\n\n\t//Coin Parity\n\tvar pScore float32\n\tvar pCoin float32\n\tvar oCoin float32\n\n\t//Score player and opponent cell\n\tfor i := 0; i < 8; i++ {\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tif board[i][j] == player {\n\t\t\t\tpCoin += float32(cellValue[i][j])\n\t\t\t} else if board[i][j] == enemy(player) {\n\t\t\t\toCoin += float32(cellValue[i][j])\n\t\t\t}\n\t\t}\n\t}\n\n\t//Parity score is difference in scores over total score\n\tpScore = (pCoin - oCoin) / (pCoin + oCoin)\n\n\t//Difference in Mobility\n\t//Create games assuming board state and turn to calculate size of valid moves\n\tvar mScore float32\n\n\tpMob := createGame(board, player)\n\toMob := createGame(board, enemy(player))\n\n\tplayerMobility := len(pMob.validMoves)\n\tenemyMobility := len(oMob.validMoves)\n\n\tswitch{\n\tcase playerMobility > enemyMobility:\n\t\tmScore = float32(playerMobility)/float32(playerMobility + enemyMobility)\n\tcase enemyMobility > playerMobility:\n\t\tmScore = -float32(enemyMobility)/float32(playerMobility + enemyMobility)\n\tdefault:\n\t\tmScore = 0\n\t}\n\n\t//fmt.Printf(\"Parity:%v Mobility:%v\\n\", pScore, mScore)\n\t//Total evaluated score\n\tscore = (pScore * 500) + (mScore * 600)\n\n\treturn score\n}",
"func (b *Board) Score() int {\n\tif !b.Finish {\n\t\treturn 0\n\t}\n\n\t// yaku ? or finish move\n\t// b.HasYaku() //TODO: yaku score\n\ts := b.LastAttackMove.Attack.GetScore()\n\tif b.LastAttackMove.FaceDown && b.LastAttackMove.Block == b.LastAttackMove.Attack {\n\t\ts = s * 2\n\t}\n\treturn s\n}",
"func Score(x, y float64) int {\n\tdistance := math.Sqrt(math.Pow(x, 2) + math.Pow(y, 2))\n\n\tswitch {\n\tcase distance <= 1:\n\t\treturn 10\n\tcase distance <= 5:\n\t\treturn 5\n\tcase distance <= 10:\n\t\treturn 1\n\tdefault:\n\t\treturn 0\n\t}\n}",
"func (g *Game) getFrameScore(rollIndex int) int {\n\treturn g.rolls[rollIndex] + g.rolls[rollIndex+1]\n}",
"func (g *Game) GetOrCalculateLeftScore() int {\n\tif g.LeftScore == 0 {\n\t\t_, left := g.GameScore()\n\t\treturn int(left)\n\t}\n\treturn g.LeftScore\n}",
"func (d *diff) CalcScore(key interface{}) float64 {\n\treturn 0\n}",
"func (g *Game) GetOrCalculateRightScore() int {\n\tif g.RightScore == 0 {\n\t\tright, _ := g.GameScore()\n\t\treturn int(right)\n\t}\n\treturn g.RightScore\n}",
"func (t *Table) ScoreRound() []int {\n\tallPoints := 26\n\troundScores := make([]int, len(t.players))\n\tshotMoon := false\n\tshooter := -1\n\tfor i := 0; i < len(t.players); i++ {\n\t\troundScores[i] = t.players[i].CalculateScore()\n\t\tif roundScores[i] == allPoints {\n\t\t\tshotMoon = true\n\t\t\tshooter = i\n\t\t}\n\t}\n\tif shotMoon {\n\t\tfor i := 0; i < len(t.players); i++ {\n\t\t\tif i == shooter {\n\t\t\t\troundScores[i] = 0\n\t\t\t} else {\n\t\t\t\troundScores[i] = allPoints\n\t\t\t}\n\t\t}\n\t}\n\treturn roundScores\n}",
"func (eng *Engine) Score() int32 {\n\treturn Evaluate(eng.Position).GetCentipawnsScore() * eng.Position.Us().Multiplier()\n}",
"func (va VAScore) Score() float64 {\n\tif va.Err != nil {\n\t\treturn 0.0\n\t}\n\treturn va.Achieved - va.Expected\n}",
"func scoreCoords() (col coord, row coord) {\n\tcol = 1\n\trow = (CardHeight * 3) + 1\n\treturn\n}",
"func (game *Game) Score() int {\n\treturn game.score\n}",
"func (g *G) Score() int {\n\t/* Fill in this Function */\n\treturn 0\n}",
"func (el *gameStruct) Score() int {\n\treturn el.points\n}",
"func (solution Solution) Score() int {\n\tscore := 0\n\tfor _, order := range solution {\n\t\tscore += order.score\n\t}\n\n\treturn score\n}",
"func Score(x, y float64) int {\n\tswitch {\n\tcase inCircle(x, y, 1):\n\t\treturn 10\n\tcase inCircle(x, y, 5):\n\t\treturn 5\n\tcase inCircle(x, y, 10):\n\t\treturn 1\n\tdefault:\n\t\treturn 0\n\t}\n}",
"func (move Move) Score() uint16 {\n\treturn uint16(move & 0xffff)\n}",
"func (sqlite *SQLiteDB) OveralScore(from time.Time, to time.Time) (int32, error) {\n\tvar score int32\n\terr := sqlite.db.Get(&score,\n\t\t`SELECT round(AVG(rating * weight)/AVG($1 * weight)*100) as score\n\t\tFROM ratings\n\t\tINNER JOIN tickets ON ratings.ticket_id=tickets.id\n\t\tINNER JOIN rating_categories ON ratings.rating_category_id=rating_categories.id\n\t\tWHERE tickets.created_at BETWEEN $2 AND $3;`,\n\t\tdb.MaxRating, from.Format(db.SimpleDateFormat), to.Format(db.SimpleDateFormat))\n\n\tif err != nil {\n\t\treturn score, err\n\t}\n\treturn score, err\n}",
"func Score(word string) int {\n\tscore := 0\n\tfor _, c := range strings.ToUpper(word) {\n\t\tscore = score + letterValues.getScore(c)\n\t}\n\treturn score\n}",
"func (g *Game) scoreOf() [3]int {\n\tcb := 0\n\tcw := 0\n\tfor x := 0; x < 8; x++ {\n\t\tfor y := 0; y < 8; y++ {\n\t\t\tb := g.Board[x][y]\n\t\t\tif b == Black {\n\t\t\t\tcb++\n\t\t\t} else if b == White {\n\t\t\t\tcw++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn [3]int{cb, cw, cb + cw}\n}",
"func (b *Board) score() Player {\n\tstatic_eval := b.evaluate_static()\n\tif static_eval != NoPlayer {\n\t\treturn static_eval\n\t}\n\n\tif len(b.vacantSquares()) == 0 {\n\t\treturn NoPlayer\n\t}\n\n\tbranch_evals := func() []Player {\n\t\tout := []Player{}\n\t\tfor _, branch := range b.possibleMoves() {\n\t\t\tout = append(out, branch.score())\n\t\t}\n\t\treturn out\n\t}()\n\n\tswitch b.NextPlayer() {\n\tcase Player1:\n\t\tif playerInList(Player1, branch_evals) {\n\t\t\treturn Player1\n\t\t} else if playerInList(NoPlayer, branch_evals) {\n\t\t\treturn NoPlayer\n\t\t} else {\n\t\t\treturn Player2\n\t\t}\n\tcase Player2:\n\t\tif playerInList(Player2, branch_evals) {\n\t\t\treturn Player2\n\t\t} else if playerInList(NoPlayer, branch_evals) {\n\t\t\treturn NoPlayer\n\t\t} else {\n\t\t\treturn Player1\n\t\t}\n\t}\n\n\treturn NoPlayer\n}",
"func Score(x, y float64) (score int) {\n\t// in order to lie within the circle area the distance of the point (x,y) from (0,0) coordinates\n\t// must be less or equal to the radius of the circle\n\tr := radius(x, y)\n\tswitch {\n\tcase r <= 1.0:\n\t\tscore = 10\n\tcase r <= 5.0:\n\t\tscore = 5\n\tcase r <= 10.0:\n\t\tscore = 1\n\tdefault:\n\t\tscore = 0\n\t}\n\treturn\n}",
"func Score(state State) float32 {\n\tswitch state {\n\tcase Unknown:\n\t\treturn 0\n\tcase Outage:\n\t\treturn 0.25\n\tcase Major:\n\t\treturn 0.50\n\tcase Minor:\n\t\treturn 0.75\n\tcase OK:\n\t\treturn 1.00\n\tdefault:\n\t\treturn 0\n\t}\n}",
"func (game *Game) calculateGameWinner() {\n\twinningPlayer := 0\n\twinningTotal := MaxPossibleScore\n\n\tfor i := range game.players {\n\t\tplayerTotal := game.players[i].calcuateTotalGameScore()\n\n\t\tif playerTotal < winningTotal {\n\t\t\twinningTotal = playerTotal\n\t\t\twinningPlayer = i\n\t\t}\n\t}\n\n\tgame.gameWinner = winningPlayer\n}",
"func Score(word string) int {\n\tvar score int\n\tif word == \"\" {\n\t\treturn score\n\t}\n\n\tfor _, letter := range word {\n\t\tscore += grading[unicode.ToUpper(letter)]\n\t}\n\treturn score\n}",
"func (p *Puzzle) ComputeScore(words []string) int {\n\tisPangram := func(word string) bool {\n\t\tletters := map[string]struct{}{\n\t\t\tp.CenterLetter: {},\n\t\t}\n\t\tfor _, letter := range p.Letters {\n\t\t\tletters[letter] = struct{}{}\n\t\t}\n\n\t\tfor _, letter := range word {\n\t\t\tdelete(letters, string(letter))\n\t\t}\n\n\t\treturn len(letters) == 0\n\t}\n\n\tvar score int\n\tfor _, word := range words {\n\t\tif len(word) == 4 {\n\t\t\tscore += 1\n\t\t\tcontinue\n\t\t}\n\n\t\tscore += len(word)\n\n\t\t// pangrams get a 7 point bonus\n\t\tif isPangram(word) {\n\t\t\tscore += 7\n\t\t}\n\t}\n\n\treturn score\n}",
"func Score(word string) int {\n\tword = strings.ToUpper(word)\n\n\tscore := 0\n\tfor i := 0; i < len(word); i++ {\n\t\tscore += letterValues[word[i]]\n\t}\n\n\treturn score\n}",
"func (eng *Engine) cachedScore(e *hashEntry) int32 {\n\tif e.kind&hasStatic == 0 {\n\t\te.kind |= hasStatic\n\t\te.static = int16(eng.Score())\n\t}\n\treturn int32(e.static)\n}",
"func Score(needle, haystack string) float64 {\n\tneedleLength := len(needle)\n\thaystackLength := len(haystack)\n\tif needleLength > haystackLength {\n\t\treturn -1\n\t}\n\n\tif needleLength == 0 {\n\t\treturn 0\n\t}\n\n\tlowerNeedle := strings.ToLower(needle)\n\tlowerHaystack := strings.ToLower(haystack)\n\tscore := 0.0\n\tfor i, j := 0, 0; i < needleLength && j < haystackLength; i, j = i+1, j+1 {\n\n\t\tletter := lowerNeedle[i]\n\t\tletterIndex := strings.IndexByte(lowerHaystack[j:], letter) + j\n\t\tif (letterIndex - j) < 0 {\n\t\t\treturn -1\n\t\t}\n\n\t\tif areLettersSameCase(needle[i], haystack[j]) {\n\t\t\tscore += 0.5\n\t\t}\n\n\t\tif letterIndex == j {\n\t\t\t// Letter was consecutive\n\t\t\tscore += 8\n\t\t} else {\n\t\t\tscore += 1 - (0.1 * float64(letterIndex))\n\t\t\t// Move j up to the next found letter.\n\t\t\tj = letterIndex\n\t\t}\n\n\t\tif j == haystackLength-1 && i < needleLength-1 {\n\t\t\treturn -1\n\t\t}\n\t}\n\treturn score\n}",
"func Score(fileOptions map[string]interface{}) {\n\toptions, err := parseFlags(fileOptions)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tinputFiles := readSharedInputFiles(options)\n\n\tscores := preyScore{\n\t\tBait: calculateBaitComponent(options, inputFiles),\n\t\tDomain: calculateDomainComponent(options, inputFiles),\n\t\tStudy: calculateStudyComponent(options, inputFiles),\n\t\tText: calculateTextComponent(options, inputFiles),\n\t}\n\n\twriteScores(scores, inputFiles, options.outFile)\n}",
"func score (nilai int) string{\r\n\r\n\t//untuk posisi kondisi c dan b bisa ditukar, namun untuk posisi kondisi a tidak bisa.\r\n\t//dikarenakan kondisi a itu selain dari kondisi c dan b.\r\n\tif nilai <= 40 {\r\n\t\treturn \"C\"\r\n\t} else if nilai >40 && nilai <=70 {\r\n\t\treturn \"B\"\r\n\t} else {\r\n\t\treturn \"A\"\r\n\t}\r\n\r\n}",
"func FormatScore(game responses.FantasyGame) string {\n\thomeTeam := game.Home.Name\n\tawayTeam := game.Away.Name\n\n\thomeScore := game.HomeScore.Score.Value\n\tawayScore := game.AwayScore.Score.Value\n\n\tif homeScore > awayScore {\n\t\treturn fmt.Sprintf(\"%v beat %v with a score of %.2f-%.2f.\\n\", homeTeam, awayTeam, homeScore, awayScore)\n\t} else if awayScore > homeScore {\n\t\treturn fmt.Sprintf(\"%v beat %v with a score of %.2f-%.2f.\\n\", awayTeam, homeTeam, awayScore, homeScore)\n\t} else {\n\t\treturn fmt.Sprintf(\"Whaaaat....%v and %v tied with a score of %.2f-%.2f.\\n\", homeTeam, awayTeam, homeScore, awayScore)\n\t}\n}",
"func Score(word string) (score int) {\n\tfor _, l := range word {\n\t\tl = unicode.ToUpper(l)\n\t\tif s, ok := letterScores[l]; ok {\n\t\t\tscore += s\n\t\t}\n\t}\n\treturn\n}",
"func final(player int, game Game) float32 {\n\tgame.calcScore()\n\tvar MAX float32\n\tMAX = 10000\n\n\tif player == 1 {\n\t\tif game.WhiteCount > game.BlackCount {\n\t\t\treturn MAX\n\t\t} else if game.BlackCount > game.WhiteCount {\n\t\t\treturn -MAX\n\t\t} else {\n\t\t\treturn 0\n\t\t}\n\t} else {\n\t\tif game.WhiteCount > game.BlackCount {\n\t\t\treturn -MAX\n\t\t} else if game.BlackCount > game.WhiteCount {\n\t\t\treturn MAX\n\t\t} else {\n\t\t\treturn 0\n\t\t}\n\t}\n}",
"func (s *State) ApplyScore(north, south, west, east string, nsScore, weScore int) error {\n\tseating := s.CurrentRound().FindSeating(north, south, west, east)\n\tif seating == nil {\n\t\treturn fmt.Errorf(\"Couldn't find a seating with these players: N %s, S %s, W %s, E %s\", north, south, west, east)\n\t}\n\n\tseating.Finished = true\n\tseating.NSScore = nsScore\n\tseating.WEScore = weScore\n\tif nsScore >= weScore {\n\t\tseating.NSWins = true\n\t}\n\n\treturn nil\n}",
"func (d *Dispatcher) calScore(numReqs, restSpace int, avgResponseTime float) score int {\n\t//\n\treturn\n}",
"func Score(cards set.Cards) *Pnts {\n\tsum := Pnts(0)\n\tfor _, c := range cards {\n\t\tsum += Pnts(Points(c))\n\t}\n\treturn &sum\n}",
"func Score(dice []int, category string) int {\n\tswitch category {\n\tcase \"ones\":\n\t\tif count, ok := groupDice(dice)[1]; ok {\n\t\t\treturn count * 1\n\t\t}\n\tcase \"twos\":\n\t\tif count, ok := groupDice(dice)[2]; ok {\n\t\t\treturn count * 2\n\t\t}\n\tcase \"threes\":\n\t\tif count, ok := groupDice(dice)[3]; ok {\n\t\t\treturn count * 3\n\t\t}\n\tcase \"fours\":\n\t\tif count, ok := groupDice(dice)[4]; ok {\n\t\t\treturn count * 4\n\t\t}\n\tcase \"fives\":\n\t\tif count, ok := groupDice(dice)[5]; ok {\n\t\t\treturn count * 5\n\t\t}\n\tcase \"sixes\":\n\t\tif count, ok := groupDice(dice)[6]; ok {\n\t\t\treturn count * 6\n\t\t}\n\tcase \"full house\":\n\t\treturn scoreFullHouse(groupDice(dice))\n\tcase \"four of a kind\":\n\t\tfor num, count := range groupDice(dice) {\n\t\t\tif count >= 4 {\n\t\t\t\treturn num * 4\n\t\t\t}\n\t\t}\n\tcase \"little straight\":\n\t\tif sortAndCompare(dice, []int{1, 2, 3, 4, 5}) {\n\t\t\treturn 30\n\t\t}\n\tcase \"big straight\":\n\t\tif sortAndCompare(dice, []int{2, 3, 4, 5, 6}) {\n\t\t\treturn 30\n\t\t}\n\tcase \"choice\":\n\t\tsum := 0\n\t\tfor _, die := range dice {\n\t\t\tsum += die\n\t\t}\n\t\treturn sum\n\tcase \"yacht\":\n\t\tif len(groupDice(dice)) == 1 {\n\t\t\treturn 50\n\t\t}\n\t}\n\n\treturn 0\n}",
"func Score(tiles string) int {\n\ttotal := 0\n\n\t//convert all tile to lower case ascii\n\ts := strings.ToLower(tiles)\n\n\t//look up the tiles value in array and add it to the running total\n\tfor _, v := range s {\n\t\ttotal += tileValues[v-0x61] //0x61 is the hex value of char 'a'\n\t}\n\n\treturn total\n}",
"func Score(word string) int {\n\tvar outScore = 0\n\tif word == \"\" {\n\t\treturn outScore\n\t}\n\tfor i := 0; i < len(word); i++ {\n\t\tc := string(word[i])\n\t\tfor _, scores := range scrabbleScores {\n\t\t\tif strings.ToLower(c) == strings.ToLower(scores.letter) {\n\t\t\t\toutScore += scores.score\n\t\t\t}\n\t\t}\n\t}\n\n\treturn outScore\n\n}",
"func CreatePlayerScore(gameName string, kills int, deaths int, assists int, cs int, tripleKills int, quadraKills int, pentaKills int) *PlayerScore {\n\tscore := PlayerScore{\n\t\tSummonerName: gameName,\n\t\tKills: float32(kills) * PointValues[KillsString],\n\t\tDeaths: float32(deaths) * PointValues[DeathsString],\n\t\tAssists: float32(assists) * PointValues[AssistsString],\n\t\tCS: float32(cs) * PointValues[CSString],\n\t\tTripleKills: float32(tripleKills) * PointValues[TripleKillsString],\n\t\tQuadraKills: float32(quadraKills) * PointValues[QuadraKillsString],\n\t\tPentakills: float32(pentaKills) * PointValues[PentakillsString],\n\t}\n\tscore.CSString = fmt.Sprintf(\"%.2f\", score.CS)\n\n\t//Bonus points for getting at least 10 kills/assists in the same game\n\tif kills+assists >= 10 {\n\t\tscore.TenKA = PointValues[TenKAString]\n\t}\n\n\tscore.Score = score.Kills + score.Deaths + score.Assists + score.CS + score.TenKA + score.TripleKills +\n\t\tscore.QuadraKills + score.Pentakills\n\tscore.ScoreString = fmt.Sprintf(\"%.2f\", score.Score)\n\n\treturn &score\n}",
"func (am *Antman) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\tklog.Infof(\"in Score for podName : %v\", pod.Name)\n\tnodeInfo, err := am.frameworkHandle.SnapshotSharedLister().NodeInfos().Get(nodeName)\n\tif err != nil {\n\t\treturn 0, framework.NewStatus(framework.Error, fmt.Sprintf(\"getting node %q from Snapshot: %v\", nodeName, err))\n\t}\n\n\tpodInfo := am.getOrCreatePodInfo(pod, time.Now())\n\tpodKey := podInfo.key\n\tif len(podKey) == 0 {\n\t\t// normal pod, not opportunistic pod in antman\n\t\t// return 100 for every node to bypass the scoring\n\t\treturn int64(100), nil\n\t}\n\n\t// note that, because there are multiple score plugins in k8s\n\t// it is not the final score for this node\n\treturn am.GpuScore(state, pod, nodeInfo)\n}",
"func Score(letters string) (score int) {\n\tfor _, char := range letters {\n\t\tscore += scoreForLetter(char)\n\t}\n\n\treturn score\n}",
"func Score(hand ...deck.Card) int {\n\tminScore := minScore(hand...)\n\tif minScore > 11 {\n\t\treturn minScore\n\t}\n\tfor _, c := range hand {\n\t\tif int(c.Rank) == 1 {\n\t\t\t// ace is currently worth 1, and we are changing it to be worth 11\n\t\t\t// 11 - 1 = 10\n\t\t\treturn minScore + 10\n\t\t}\n\t}\n\treturn minScore\n}",
"func (b FirstEvaluator) Evaluate(pos *game.Position) float32 {\n\tigo, winner := pos.GameOver()\n\tif igo {\n\t\treturn winner.EvaluationWin()\n\t}\n\t// Theory:\n\t// * Winning subboards is good\n\t// * Number of legal moves is good(ish)\n\t// * Winning subboards relative to win condition - e.g. xor bigboard with wc and check\n\n\tbbSM := pos.BigBoard(pos.SideToMove)\n\n\t// calculate lowest mse with a win condition on a board\n\tbestMSESM := 1000\n\tmseSM := 0\n\tfor _, wc := range game.WinConditions {\n\t\tmseSM = bits.OnesCount32(wc ^ bbSM)\n\t\tif mseSM < bestMSESM {\n\t\t\tbestMSESM = mseSM\n\t\t}\n\t}\n\tfMseSM := float32(mseSM) / 9\n\n\t// calculate number of legal moves\n\tnlm := float32(pos.CountLegalMoves())\n\n\t// number of won subboards\n\tnwbbSM := float32(bits.OnesCount32(bbSM)) / 9\n\n\t// ---------------------------------------------\n\n\tbbSMO := pos.BigBoard(pos.SideToMove.Other())\n\n\t// calculate lowest mse with a win condition on a board\n\tbestMSESMO := 1000\n\tmseSMO := 0\n\tfor _, wc := range game.WinConditions {\n\t\tmseSMO = bits.OnesCount32(wc ^ bbSMO)\n\t\tif mseSMO < bestMSESMO {\n\t\t\tbestMSESMO = mseSM\n\t\t}\n\t}\n\tfMseSMO := float32(mseSMO) / 9\n\n\t// number of won subboards\n\tnwbbSMO := float32(bits.OnesCount32(bbSMO)) / 9\n\n\tvalue := .00002*nlm + (-0.08)*(fMseSM-fMseSMO) + 0.04*(nwbbSM-nwbbSMO)\n\treturn pos.SideToMove.EvaluationCoefficient() * value\n}",
"func (pl *RepeatPriority) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\n rnode := pl.handle.GetNodeUsageFactor(nodeName)\n rhigh := pl.handle.GetHighestUsageFactor()\n\n nodeRF := float64(rnode)/float64(rhigh)\n score := math.Exp(-5*float64(nodeRF))\n return int64(score*100), nil\n}",
"func UpdateScore(c *fiber.Ctx) {\n\tShopID := c.Params(\"shop_id\")\n\tUserID := userIDF(c.Get(\"token\"))\n\n\tvar Data ScoreStruct\n\n\tif errorParse := c.BodyParser(&Data); errorParse != nil {\n\t\tfmt.Println(\"Error parsing data\", errorParse)\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Error al parsear información\"})\n\t\tc.Status(400)\n\t\treturn\n\t}\n\n\tif Data.Score <= 0 {\n\t\tfmt.Println(\"score can't be empty\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Score can't be empty\"})\n\t\tc.Status(400)\n\t\treturn\n\t}\n\n\tvar Score ScoreSQL\n\n\t_, ErrorUpdateScoreUser := sq.Update(\"shop_score_users\").\n\t\tSet(\"score\", Data.Score).\n\t\tWhere(\"user_id = ? AND shop_id = ?\", UserID, ShopID).\n\t\tRunWith(database).\n\t\tExec()\n\n\tif ErrorUpdateScoreUser != nil {\n\t\tfmt.Println(\"Error to update score\", ErrorUpdateScoreUser)\n\t}\n\n\tErrorScore := sq.Select(\n\t\t\"AVG(score) as score\",\n\t).\n\t\tFrom(\"shop_score_users\").\n\t\tWhere(\"shop_id = ?\", ShopID).\n\t\tRunWith(database).\n\t\tQueryRow().\n\t\tScan(\n\t\t\t&Score.Score,\n\t\t)\n\n\tif ErrorScore != nil {\n\t\tfmt.Println(ErrorScore, \"Error get score\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with get score\"})\n\t\tc.SendStatus(400)\n\t\treturn\n\t}\n\n\tqueryUpdateValue := sq.Update(\"shop\")\n\n\tScoreFloat, _ := strconv.ParseFloat(Score.Score.String, 64)\n\n\tNewScore := fmt.Sprintf(\"%.0f\", ScoreFloat)\n\n\t_, ErrorUpdateScoreShop := queryUpdateValue.\n\t\tSet(\"score_shop\", NewScore).\n\t\tWhere(\"shop_id = ? \", ShopID).\n\t\tRunWith(database).\n\t\tExec()\n\n\tif ErrorUpdateScoreShop != nil {\n\t\tfmt.Println(ErrorUpdateScoreShop, \"Problem with update score\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with update score\"})\n\t\tc.SendStatus(500)\n\t\treturn\n\t}\n\n\tc.JSON(SuccessResponse{MESSAGE: \"Calificación actualizada\"})\n}",
"func (m *LogLoss) Score() float64 {\n\tm.mu.RLock()\n\tlogsum := m.logsum\n\tweight := m.weight\n\tm.mu.RUnlock()\n\n\tif weight > 0 {\n\t\treturn -logsum / weight\n\t}\n\treturn -math.Log(m.epsilon)\n}",
"func Score(hand ...deck.Card) int {\n\tminScore := minScore(hand...)\n\tif minScore > 11 {\n\t\t// we can't increase 12 to 22, because that will be a bust\n\t\treturn minScore\n\t}\n\n\tfor _, c := range hand {\n\t\tif c.Rank == deck.Ace {\n\t\t\t// ace is currently worth 1, and we are changing it to be worth 11\n\t\t\t// 11 - 1 = 10\n\t\t\treturn minScore + 10\n\t\t}\n\t}\n\treturn minScore\n}",
"func (b *Board) ScoreTile(coord WallCoordinate) WallScore {\n\tresult := WallScore{\n\t\tTiles: make([]WallCoordinate, 0),\n\t}\n\n\trows := len(wallLayout)\n\tcols := len(wallLayout[0])\n\n\t// Add the scoring tile to the result\n\tresult.Tiles = append(result.Tiles, coord)\n\n\t// Calculate the score for horizontal adjacent tiles\n\thorizontalTiles := make([]WallCoordinate, 0)\n\n\t// Count the adjacent tiles to the right\n\tif coord.Col < cols-1 {\n\t\tfor i := coord.Col + 1; i < cols; i++ {\n\t\t\tif b.Wall[coord.Row][i].HasTile {\n\t\t\t\thorizontalTiles = append(horizontalTiles, WallCoordinate{Row: coord.Row, Col: i})\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Count the adjacent tiles to the left\n\tif coord.Col > 0 {\n\t\tfor i := coord.Col - 1; i >= 0; i-- {\n\t\t\tif b.Wall[coord.Row][i].HasTile {\n\t\t\t\thorizontalTiles = append(horizontalTiles, WallCoordinate{Row: coord.Row, Col: i})\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If there were adjacent tiles, add the tiles and score to the result\n\tif len(horizontalTiles) > 0 {\n\t\tresult.Tiles = append(result.Tiles, horizontalTiles...)\n\t\tresult.Score += len(horizontalTiles) + 1\n\t}\n\n\t// Calculate the score for vertical adjacent tiles\n\tverticalTiles := make([]WallCoordinate, 0)\n\n\t// Count the adjacent tiles below\n\tif coord.Row < rows-1 {\n\t\tfor i := coord.Row + 1; i < rows; i++ {\n\t\t\tif b.Wall[i][coord.Col].HasTile {\n\t\t\t\tverticalTiles = append(verticalTiles, WallCoordinate{Row: i, Col: coord.Col})\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Count the adjacent tiles above\n\tif coord.Row > 0 {\n\t\tfor i := coord.Row - 1; i >= 0; i-- {\n\t\t\tif b.Wall[i][coord.Col].HasTile {\n\t\t\t\tverticalTiles = append(verticalTiles, WallCoordinate{Row: i, Col: coord.Col})\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If there were adjacent tiles, add the specified tile\n\tif len(verticalTiles) > 0 {\n\t\tresult.Tiles = append(result.Tiles, verticalTiles...)\n\t\tresult.Score += len(verticalTiles) + 1\n\t}\n\n\t// If the tile doesn't have any adjacent tiles, it's worth 1 point\n\tif len(result.Tiles) == 1 {\n\t\tresult.Score = 1\n\t}\n\n\treturn result\n}",
"func (ps *PodState) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\tnodeInfo, err := ps.handle.SnapshotSharedLister().NodeInfos().Get(nodeName)\n\tif err != nil {\n\t\treturn 0, framework.NewStatus(framework.Error, fmt.Sprintf(\"getting node %q from Snapshot: %v\", nodeName, err))\n\t}\n\n\t// pe.score favors nodes with terminating pods instead of nominated pods\n\t// It calculates the sum of the node's terminating pods and nominated pods\n\treturn ps.score(nodeInfo)\n}",
"func Score(word string) int {\n\tvar score int\n\n\tfor _, c := range word {\n\t\tscore += pointValue(c)\n\t}\n\n\treturn score\n}",
"func CalculateMatchScore(region string, summoners []rgapi.Summoner) (*MatchScore, error) {\n\tif len(summoners) != PlayersPerMatch {\n\t\treturn nil, errors.New(fmt.Sprint(\n\t\t\t\"Calculating match score requires \", PlayersPerMatch, \" players, was given \", len(summoners)))\n\t}\n\n\t//For each summoner, get the best game they have in their recent history\n\t//TODO: Save timestamp of most recently checked games in DB or Redis\n\tplayerScores := make([]*PlayerScore, len(summoners))\n\tfor i := 0; i < len(summoners); i++ {\n\t\tplayerScore, err := PlayerScoreBestRecent(region, summoners[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tplayerScores[i] = playerScore\n\t}\n\n\t//Create teams and match score objects\n\tblueTeamScore := TeamScore{\n\t\tTop: playerScores[0],\n\t\tJungle: playerScores[1],\n\t\tMid: playerScores[2],\n\t\tBottom: playerScores[3],\n\t\tSupport: playerScores[4],\n\t\tScore: playerScores[0].Score + playerScores[1].Score + playerScores[2].Score + playerScores[3].Score + playerScores[4].Score,\n\t}\n\tblueTeamScore.ScoreString = fmt.Sprintf(\"%.2f\", blueTeamScore.Score)\n\tredTeamScore := TeamScore{\n\t\tTop: playerScores[5],\n\t\tJungle: playerScores[6],\n\t\tMid: playerScores[7],\n\t\tBottom: playerScores[8],\n\t\tSupport: playerScores[9],\n\t\tScore: playerScores[5].Score + playerScores[6].Score + playerScores[7].Score + playerScores[8].Score + playerScores[9].Score,\n\t}\n\tredTeamScore.ScoreString = fmt.Sprintf(\"%.2f\", redTeamScore.Score)\n\tmatchScore := MatchScore{\n\t\tBlueTeam: blueTeamScore,\n\t\tRedTeam: redTeamScore,\n\t}\n\n\t//Pick the winner\n\t//TODO: Do this by user-selected team name instead of Blue/Red\n\tif blueTeamScore.Score > redTeamScore.Score {\n\t\tmatchScore.WinningSide = BlueTeam\n\t\tmatchScore.WinningTeam = \"Blue\"\n\t} else if redTeamScore.Score > blueTeamScore.Score {\n\t\tmatchScore.WinningSide = RedTeam\n\t\tmatchScore.WinningTeam = \"Red\"\n\t}\n\n\treturn &matchScore, nil\n}",
"func errorScore(text string, errors int) float64 {\n\treturn 1. / (1. + float64(errors))\n}",
"func (s *Scorer) subtractScore(appID marathon.AppID) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tvar ok bool\n\tvar score *Score\n\tif score, ok = s.scores[appID]; !ok {\n\t\treturn\n\t}\n\n\tscore.score -= s.ScaleDownScore\n}",
"func (b *board) multiplier(x, y int) Multiplier {\n\tmax_x, max_y := b.width-1, b.height-1\n\n\toutside := func(a, b int) bool {\n\t\txInside := x >= a && x <= b\n\t\tyInside := y >= a && y <= b\n\t\treturn !(xInside && yInside)\n\t}\n\n\t// double word score\n\t// the center spot\n\tif (x == y) && (x == max_x/2) {\n\t\treturn double_word_score\n\t}\n\n\n\t// triple word score\n\t// outer grid of halfs\n\tif (x % (max_x/2) == 0) && (y % (max_y/2) == 0) {\n\t\treturn triple_word_score\n\t}\n\n\n\t// double word score\n\t// the diagnols that aren't already something and are not in the center\n\tif (x == y || max_x-x == y || max_y-y == x) && outside(max_x-2, max_x+2) {\n\t\treturn double_word_score\n\t}\n\n\n\t// triple letter score\n\t// inner grid of fourths that aren't already something\n\tif (x-1 == (max_x-2)/4) && (y-1 == (max_y-2)/4) {\n\t\treturn triple_letter_score\n\t}\n\n\n\t// double letter score\n\t// the following is very 15x15 board specific...\n\tboxAroundCenter := func(a, max int) bool {\n\t\treturn (a == (max/2)-1 || a == (max/2)+1)\n\t}\n\t// a box around the center\n\tif boxAroundCenter(x, max_x) && boxAroundCenter(y, max_y) {\n\t\treturn double_letter_score\n\t}\n\t// on the outside border\n\tif outside(1, 13) {\n\t\tif (x == 3 || x == 11) || (y == 3 || y == 11) {\n\t\t\treturn double_letter_score\n\t\t}\n\t}\n\t// those triangle things\n\tif !outside(3, 12) {\n\t\tif (x == 3 || x == 11) && (y == max_y/2) {\n\t\t\treturn double_letter_score\n\t\t}\n\t\tif (y == 3 || y == 11) && (x == max_x/2) {\n\t\t\treturn double_letter_score\n\t\t}\n\t\tif (x == 2 || x == 12) && (y == max_y-1 || y == max_y+1) {\n\t\t\treturn double_letter_score\n\t\t}\n\t\tif (y == 2 || y == 12) && (x == max_x-1 || x == max_x+1) {\n\t\t\treturn double_letter_score\n\t\t}\n\t}\n\n\treturn normal\n}",
"func (room Room) GetScore() []int {\n\tvar scoreList []int\n\tfor _, player := range room.Players {\n\t\tscoreList = append(scoreList, player.Credit)\n\t}\n\treturn scoreList\n}",
"func scoreMatch(c *gin.Context) {\n\n\tparam := c.Param(\"id\")\n\tmatchID, err := strconv.Atoi(param)\n\tif handleError(err, c) {\n\t\treturn\n\t}\n\n\tvar request struct {\n\t\tPointNum int `form:\"pointNum\" binding:\"required\"`\n\t\tFaults int `form:\"faults\"`\n\t\tLets int `form:\"lets\"`\n\t\tAce *bool `form:\"ace\"`\n\t\tUnforcedError *bool `form:\"unforcedError\"`\n\t\tWinnerID int `form:\"winnerID\" binding:\"required\"`\n\t}\n\n\tvar response ScoreResponse\n\n\tif !tryGetRequest(c, &request) {\n\t\treturn\n\t}\n\n\tprintln(\"Updating current point\")\n\n\t// Update the current point\n\tsqlStatement := `UPDATE point SET \n\tfaults=$3, \n\tlets=$4,\n\tace=$5,\n\tunforced_error=$6,\n\twinner_id=$7\n\tWHERE number=$1 AND match_id=$2`\n\t_, err = db.Exec(sqlStatement, request.PointNum, matchID, request.Faults, request.Lets, request.Ace, request.UnforcedError, request.WinnerID)\n\tif handleError(err, c) {\n\t\treturn\n\t}\n\n\tprintln(\"Checking if match is over\")\n\n\t// Get players wins\n\tsqlStatement = `\n\tSELECT player.id, (SELECT COUNT(winner_id) FROM point\n\t\t\tWHERE winner_id = player.id and match_id = $1) as wins\n\tFROM player\n\tJOIN match_participant mp ON player_id = player.id\n\tWHERE mp.match_id = $1;`\n\trows, err := db.Query(sqlStatement, matchID)\n\tif handleError(err, c) {\n\t\treturn\n\t}\n\n\tvar winnerWins, otherWins int\n\tfor rows.Next() {\n\t\tvar wins, id int\n\t\terr = rows.Scan(&id, &wins)\n\t\tif err != nil {\n\t\t\tprintln(err.Error())\n\t\t}\n\n\t\tif id == request.WinnerID {\n\t\t\twinnerWins = wins\n\t\t} else {\n\t\t\totherWins = wins\n\t\t}\n\t}\n\n\t// Get match info, points to win by, min points, server and receiver\n\tsqlStatement = `SELECT min_points, win_by, server_id, receiver_id FROM point\n\t\t\t\t\tJOIN match on point.match_id = match.id\n\t\t\t\t\tWHERE point.match_id = $1 and number = $2`\n\n\tvar curServer, curReceiver, minpoints, winBy int\n\terr = db.QueryRow(sqlStatement, matchID, request.PointNum).Scan(&minpoints, &winBy, &curServer, &curReceiver)\n\tif handleError(err, c) {\n\t\treturn\n\t}\n\n\t// Check if match over\n\tif winnerWins >= minpoints {\n\t\tdif := winnerWins - otherWins\n\t\tif dif >= winBy {\n\t\t\t// game over\n\t\t\t// create new match result with winner\n\t\t\tsqlStatement = `INSERT INTO match_result (match_id, winner_id)\n\t\t\t\t\t\t\tVALUES\n\t\t\t\t\t\t\t($1, $2)`\n\t\t\t_, err = db.Exec(sqlStatement, matchID, request.WinnerID)\n\t\t\tif handleError(err, c) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Update match for end date\n\t\t\tsqlStatement = `UPDATE match SET end_date=current_timestamp WHERE id = $1`\n\t\t\t_, err = db.Exec(sqlStatement, matchID)\n\t\t\tif handleError(err, c) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tc.JSON(http.StatusOK, response)\n\t\t\treturn\n\n\t\t}\n\t}\n\n\t// new point\n\n\tvar newServer, newReceiver int\n\t// Swap server every 2 points\n\tif request.PointNum%2 == 0 {\n\t\tnewServer = curReceiver\n\t\tnewReceiver = curServer\n\t} else {\n\t\tnewServer = curServer\n\t\tnewReceiver = curReceiver\n\t}\n\n\tvar newPointNum = request.PointNum + 1\n\tsqlStatement = `INSERT INTO point (number, match_id, server_id, receiver_id)\n\tVALUES ($1, $2, $3, $4)`\n\t_, err = db.Exec(sqlStatement, newPointNum, matchID, newServer, newReceiver)\n\tif handleError(err, c) {\n\t\treturn\n\t}\n\n\tresponse = ScoreResponse{Point: &newPointNum, NewServer: &newServer, LastPointWinnerPts: winnerWins, OtherPlayerPoints: otherWins}\n\n\tc.JSON(http.StatusOK, response)\n\n}",
"func (ap *AnimeParser) getScore(eachTop *goquery.Selection) float64 {\n\tscore := eachTop.Find(\"td:nth-of-type(3)\").Text()\n\tscore = strings.TrimSpace(strings.Replace(score, \"N/A\", \"\", -1))\n\treturn utils.StrToFloat(score)\n}",
"func Evaluate(board [][]string, player string, opponent string) int {\n\tfor row := 0; row < 3; row++ {\n\t\tif board[row][0] == board[row][1] &&\n\t\t\tboard[row][1] == board[row][2] {\n\t\t\tif board[row][0] == player {\n\t\t\t\treturn 10\n\n\t\t\t} else if board[row][0] == opponent {\n\t\t\t\treturn -10\n\t\t\t}\n\t\t}\n\t}\n\n\tfor col := 0; col < 3; col++ {\n\t\tif board[0][col] == board[1][col] &&\n\t\t\tboard[1][col] == board[2][col] {\n\t\t\tif board[0][col] == player {\n\t\t\t\treturn 10\n\t\t\t} else if board[0][col] == opponent {\n\t\t\t\treturn -10\n\t\t\t}\n\t\t}\n\t}\n\n\tif board[0][0] == board[1][1] && board[1][1] == board[2][2] {\n\t\tif board[0][0] == player {\n\t\t\treturn 10\n\t\t} else if board[0][0] == opponent {\n\t\t\treturn -10\n\t\t}\n\t}\n\n\tif board[0][2] == board[1][1] && board[1][1] == board[2][0] {\n\t\tif board[0][2] == player {\n\t\t\treturn +10\n\t\t} else if board[0][2] == opponent {\n\t\t\treturn -10\n\t\t}\n\t}\n\n\treturn 0\n}",
"func (pl *AvailabilityNodePriority) Score(ctx context.Context, args interface{}, states *state.State, feasiblePods []int32, key types.NamespacedName, podID int32) (uint64, *state.Status) {\n\tlogger := logging.FromContext(ctx).With(\"Score\", pl.Name())\n\tvar score uint64 = 0\n\n\tspreadArgs, ok := args.(string)\n\tif !ok {\n\t\tlogger.Errorf(\"Scoring args %v for priority %q are not valid\", args, pl.Name())\n\t\treturn 0, state.NewStatus(state.Unschedulable, ErrReasonInvalidArg)\n\t}\n\n\tskewVal := state.AvailabilityNodePriorityArgs{}\n\tdecoder := json.NewDecoder(strings.NewReader(spreadArgs))\n\tdecoder.DisallowUnknownFields()\n\tif err := decoder.Decode(&skewVal); err != nil {\n\t\treturn 0, state.NewStatus(state.Unschedulable, ErrReasonInvalidArg)\n\t}\n\n\tif states.Replicas > 0 { //need at least a pod to compute spread\n\t\tvar skew int32\n\n\t\t_, nodeName, err := states.GetPodInfo(state.PodNameFromOrdinal(states.StatefulSetName, podID))\n\t\tif err != nil {\n\t\t\treturn score, state.NewStatus(state.Error, ErrReasonNoResource)\n\t\t}\n\n\t\tcurrentReps := states.NodeSpread[key][nodeName] //get #vreps on this node\n\t\tfor otherNodeName := range states.NodeToZoneMap { //compare with #vreps on other nodes\n\t\t\tif otherNodeName != nodeName {\n\t\t\t\totherReps := states.NodeSpread[key][otherNodeName]\n\t\t\t\tif skew = (currentReps + 1) - otherReps; skew < 0 {\n\t\t\t\t\tskew = skew * int32(-1)\n\t\t\t\t}\n\n\t\t\t\t//logger.Infof(\"Current Node %v with %d and Other Node %v with %d causing skew %d\", nodeName, currentReps, otherNodeName, otherReps, skew)\n\t\t\t\tif skew > skewVal.MaxSkew {\n\t\t\t\t\tlogger.Infof(\"Pod %d in node %v will cause an uneven node spread %v with other node %v\", podID, nodeName, states.NodeSpread[key], otherNodeName)\n\t\t\t\t}\n\t\t\t\tscore = score + uint64(skew)\n\t\t\t}\n\t\t}\n\n\t\tscore = math.MaxUint64 - score //lesser skews get higher score\n\t}\n\n\treturn score, state.NewStatus(state.Success)\n}",
"func Score(word string) int {\n\tscore := 0\n\n\tfor _, r := range word {\n\t\tscore += processLetter(unicode.ToUpper(r))\n\t}\n\treturn score\n}",
"func ageScore(donorAge int, recipientAge int) float64 {\n\t// âge des priorités : 2 mineurs ou 2 seniors\n\tif (donorAge <= 18 && recipientAge <= 18) || (donorAge >= 65 && recipientAge >= 65) {\n\t\treturn 1.0\n\t}\n\n\tageDiff := int(math.Abs(float64(donorAge - recipientAge)))\n\tif (ageDiff >= 0) && (ageDiff <= 5) {\n\t\treturn 1.0\n\t} else if (ageDiff >= 6) && (ageDiff <= 10) {\n\t\treturn 0.8\n\t} else if (ageDiff >= 11) && (ageDiff <= 20) {\n\t\treturn 0.6\n\t} else if (ageDiff >= 21) && (ageDiff <= 30) {\n\t\treturn 0.3\n\t} else if (ageDiff >= 31) && (ageDiff <= 40) {\n\t\treturn 0.1\n\t}\n\treturn 0.0\n}",
"func FinalScore(scorers []*card.Item) (sum uint8) {\n\tfor _, s := range scorers {\n\t\tsum += Points(s)\n\t}\n\treturn\n}",
"func (s *Survey) Score() (score uint) {\n\tfor _, a := range s.Answers {\n\t\tswitch t := a[\"answer\"].(map[string]interface{})[\"score\"].(type) {\n\t\tcase int: // FIXME score came from models_test.newSurvey test case is int type\n\t\t\tscore = score + uint(t)\n\t\tcase float64:\n\t\t\tscore = score + uint(t)\n\t\t}\n\t}\n\treturn\n}",
"func Score(word string) {\n\tpoints := 0\n\tsum, count := 0, 0\n\tfor _, item := range strings.Split(word, \"\") {\n\n\t\t// fmt.Println(\"Index e item \", in, item)\n\n\t\tfor index, point := range letters {\n\n\t\t\tif index == strings.ToUpper(item) {\n\t\t\t\t// fmt.Println(\"Index y point \", index, point)\n\t\t\t\tfmt.Println(\"Points: \", point)\n\n\t\t\t\tcount = strings.Count(strings.ToUpper(item), index)\n\t\t\t\tif count > 1 {\n\t\t\t\t\tpoints += count * point\n\t\t\t\t}\n\t\t\t\tsum = point\n\t\t\t\tpoints += sum\n\t\t\t\t// fmt.Println(\"Puntos actuales: \", points)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println(\"Puntos totales: \", points)\n}",
"func MapRankToScore(rank, size int) float64 { return float64(size - rank) }",
"func (player *Player) AddScore(scores []Score) (total int) {\n\tfor _, score := range scores {\n\t\ttotal += score.Value\n\t}\n\tif total == 0 {\n\t\treturn\n\t}\n\n\tplayer.LastScore = player.Score\n\tplayer.Score += total\n\treturn\n}",
"func (r *Rule) GetScore(colname string, row dur.Row) int64 {\n\tcell := row.Col(colname)\n\tvar res int64\n\tres = r.featureRaw.Get(colname + \".default\").Int()\n\tbin := r.featureRaw.Get(colname + \".bin\") //gjson.GetBytes(r.featureRaw, colname+\".bin\")\n\tbintype := r.featureRaw.Get(colname + \".bintype\").String()\n\t// pre logic\n\tpre := r.featureRaw.Get(colname + \".pre\").String()\n\tpreScore, need, error := ParsePre(pre, row)\n\tif error != nil {\n\t\tlog.Println(error)\n\t}\n\tif need {\n\t\treturn preScore\n\t}\n\n\t// if number\n\tif bintype == \"math\" {\n\t\tbin.ForEach(func(k, v gjson.Result) bool {\n\t\t\tn, err := strconv.ParseFloat(cell, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn false // if cannot conv to flat64 for example null then break and use default value\n\t\t\t}\n\t\t\tif mathinterval.Get(k.String()).Hit(n) {\n\t\t\t\tres = v.Int()\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t}\n\n\tif bintype == \"text\" {\n\t\tbin.ForEach(func(k, v gjson.Result) bool {\n\t\t\tif k.String() == cell {\n\t\t\t\tres = v.Int()\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t}\n\n\treturn res\n}",
"func (game *Game) calculateRoundWinner() {\n\tlowestScoreIndex := 0 //default to first player.. incase they all have the same score\n\tlowestScore := MaxRoundScore\n\n\tfor i := range game.players {\n\t\tif game.players[i].roundScores[game.roundIndex] < lowestScore {\n\t\t\tlowestScoreIndex = i\n\t\t\tlowestScore = game.players[i].roundScores[game.roundIndex]\n\t\t}\n\t}\n\n\tgame.roundWinner[game.roundIndex] = lowestScoreIndex\n}",
"func Score(c *fiber.Ctx) {\n\tShopID := c.Params(\"shop_id\")\n\tUserID := c.Params(\"user_id\")\n\tvar Score ScoreSQL\n\tvar Response ResponseScore\n\n\tErrorScore := sq.Select(\n\t\t\"AVG(score) as score\",\n\t).\n\t\tFrom(\"shop_score_users\").\n\t\tWhere(\"shop_id = ? AND user_id = ?\", ShopID, UserID).\n\t\tRunWith(database).\n\t\tQueryRow().\n\t\tScan(\n\t\t\t&Score.Score,\n\t\t)\n\n\tif ErrorScore != nil {\n\t\tfmt.Println(ErrorScore, \"Error get score\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with get score\"})\n\t\tc.SendStatus(400)\n\t\treturn\n\t}\n\n\tResponse.Score = &Score.Score.String\n\n\tc.JSON(Response)\n}",
"func (g *Game) GetScore() int {\n\treturn g.score\n}",
"func (d Dispatcher) Score() float64 {\n\treturn d.GetBench().GetScore()\n}",
"func Score(hand ...deck.Card) int { // using variadic so user can pass in just one card if desired\n\tminScore := minScore(hand...)\n\tif minScore > 11 {\n\t\treturn minScore\n\t}\n\tfor _, c := range hand {\n\t\tif c.Rank == deck.Ace {\n\t\t\treturn minScore + 10 // ace is currently worth 1, so adding 10 to make it worth 11\n\t\t}\n\t\t// only 1 ace can be used as 11 and still be under 21\n\t}\n\treturn minScore\n}",
"func (g *Game)ComputeCount()(map[string]int,map[string]*DetailScore,map[string]int){\n\troundScore,detailScore := g.CurrentRound.countScore(g.playersById,g.Players[g.CurrentDicoPlayer],false,g.TypeGameNormal)\n\treturn roundScore,detailScore,g.GetTotalScore()\n}",
"func decodeScore(score float64) (int64, uint16) {\n\tval := int64(score)\n\ttimestamp := (val >> 16) & 0xffffffff\n\ttries := uint16(val & 0xffff)\n\treturn timestamp, tries\n}",
"func CalcScore(values []int) (float64, error) {\n\tsize, err := MatrixSize(values)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\tsums := make([]int, size*2+1)\n\n\t// calculate sum\n\tfor i := 0; i < size; i++ {\n\t\tsums[i*2], err = RowSum(values, i)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tsums[i*2+1], err = ColSum(values, i)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\tsums[size*2], err = DiagonalSum(values)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tscore, err := CalcVariance(sums)\n\tif err != nil {\n\t\treturn 0.0, nil\n\t}\n\n\treturn score, nil\n}",
"func UpdateScore(amount int) {\n\tgs.Score += amount\n\tsp.ScoreText.SetText(fmt.Sprintf(\"Score: %d\", gs.Score))\n}",
"func (no *NetworkOverhead) Score(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\tscore := framework.MinNodeScore\n\n\t// Get PreFilterState\n\tpreFilterState, err := getPreFilterState(cycleState)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to read preFilterState from cycleState\", \"preFilterStateKey\", preFilterStateKey)\n\t\treturn score, framework.NewStatus(framework.Error, \"not eligible due to failed to read from cycleState, return min score\")\n\t}\n\n\t// If scoreEqually, return minScore\n\tif preFilterState.scoreEqually {\n\t\treturn score, framework.NewStatus(framework.Success, \"scoreEqually enabled: minimum score\")\n\t}\n\n\t// Return Accumulated Cost as score\n\tscore = preFilterState.finalCostMap[nodeName]\n\tklog.V(4).InfoS(\"Score:\", \"pod\", pod.GetName(), \"node\", nodeName, \"finalScore\", score)\n\treturn score, framework.NewStatus(framework.Success, \"Accumulated cost added as score, normalization ensures lower costs are favored\")\n}",
"func (b Engine) GetScore() float64 {\n\treturn b.Score\n}",
"func (p *Player) GetScore() (score int) {\n\thasAce := false\n\tfor _, c := range p.DealtCards {\n\t\tif c.Rank == deck.Ace {\n\t\t\thasAce = true\n\t\t}\n\t\tscore += Scoring[c.Rank]\n\t}\n\tif hasAce {\n\t\tif score+10 <= blackjack {\n\t\t\tscore += 10\n\t\t}\n\t}\n\treturn score\n}",
"func Score(s string) int {\n\tcount := 0\n\tfor _, r := range strings.ToUpper(s) {\n\t\tcount += letterValue[r]\n\t}\n\n\treturn count\n}",
"func Score(value string) int {\n\tresult := 0\n\tvalueAllUpper := strings.ToUpper(value)\n\tfor i := 0; i < len(valueAllUpper); i++ {\n\t\tfor key, val := range scores {\n\t\t\tif strings.IndexByte(key, valueAllUpper[i]) >= 0 {\n\t\t\t\tresult += val\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}",
"func SetScore(c *fiber.Ctx) {\n\tShopID := c.Params(\"shop_id\")\n\tUserID := userIDF(c.Get(\"token\"))\n\n\tvar Data ScoreStruct\n\n\tif errorParse := c.BodyParser(&Data); errorParse != nil {\n\t\tfmt.Println(\"Error parsing data\", errorParse)\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Error al parsear información\"})\n\t\tc.Status(400)\n\t\treturn\n\t}\n\n\tif Data.Score <= 0 {\n\t\tfmt.Println(\"score can't be empty\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Score can't be empty\"})\n\t\tc.Status(400)\n\t\treturn\n\t}\n\n\tvar Score ScoreSQL\n\tvar Response ResponseScore\n\n\t_, errorInsert := sq.Insert(\"shop_score_users\").\n\t\tColumns(\n\t\t\t\"user_id\",\n\t\t\t\"shop_id\",\n\t\t\t\"score\",\n\t\t).\n\t\tValues(\n\t\t\tUserID,\n\t\t\tShopID,\n\t\t\tData.Score,\n\t\t).\n\t\tRunWith(database).\n\t\tExec()\n\n\tif errorInsert != nil {\n\t\tfmt.Println(\"Error to save score\", errorInsert)\n\t}\n\n\tErrorScore := sq.Select(\n\t\t\"AVG(score) as score\",\n\t).\n\t\tFrom(\"shop_score_users\").\n\t\tWhere(\"shop_id = ?\", ShopID).\n\t\tRunWith(database).\n\t\tQueryRow().\n\t\tScan(\n\t\t\t&Score.Score,\n\t\t)\n\n\tif ErrorScore != nil {\n\t\tfmt.Println(ErrorScore, \"Error get score\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with get score\"})\n\t\tc.SendStatus(400)\n\t\treturn\n\t}\n\n\tqueryUpdateValue := sq.Update(\"shop\")\n\n\tScoreFloat, _ := strconv.ParseFloat(Score.Score.String, 64)\n\n\tNewScore := fmt.Sprintf(\"%.0f\", ScoreFloat)\n\n\t_, ErrorUpdateOffer := queryUpdateValue.\n\t\tSet(\"score_shop\", NewScore).\n\t\tWhere(\"shop_id = ? \", ShopID).\n\t\tRunWith(database).\n\t\tExec()\n\n\tif ErrorUpdateOffer != nil {\n\t\tfmt.Println(ErrorUpdateOffer, \"Problem with update score\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with update score\"})\n\t\tc.SendStatus(500)\n\t\treturn\n\t}\n\n\tResponse.Score = &NewScore\n\n\tc.JSON(Response)\n}",
"func (b *Board) ScoreFloor() {\n\tfor _, tile := range b.Floor {\n\t\tb.Score -= tile.ScoreModifier\n\t}\n\tb.ResetFloor()\n}",
"func (h *Hand) Scores() []int {\n\tscores := []int{0}\n\tfor _, card := range h.Cards {\n\t\tif !card.faceUp {\n\t\t\tcontinue\n\t\t}\n\t\tfor i, score := range scores {\n\t\t\t// Add the first value to each score branch.\n\t\t\tscores[i] += card.Values()[0]\n\t\t\tfor _, cardValue := range card.Values()[1:] {\n\t\t\t\t// Make more score branches for further card values.\n\t\t\t\t// In other words, branch on aces.\n\t\t\t\tscores = append(scores, score+cardValue)\n\t\t\t}\n\t\t}\n\t}\n\t// If we have blackjack then return that alone\n\tfor _, score := range scores {\n\t\tif score == 21 {\n\t\t\treturn []int{21}\n\t\t}\n\t}\n\tscores = util.UniqueInts(scores)\n\tscores = sanitiseScores(scores)\n\tsort.Ints(scores)\n\treturn scores\n}",
"func calculateScore(bestClass base.Feature, classes map[base.Feature][]float64) float64 {\n var sum float64 = 0;\n for class, distances := range(classes) {\n for _, distance := range(distances) {\n if (class == bestClass) {\n sum += distance;\n } else {\n sum -= distance;\n }\n }\n }\n\n return (1.0 / (sum + float64(util.Sign(sum)))) + (2.0 * float64(len(classes[bestClass])));\n}",
"func (c *Claim) Score(ctx *ServerContext) (float32, Error) {\n\tif c.QueryAt == nil {\n\t\treturn c.Truth, nil\n\t}\n\treturn c.scoreAt(ctx)\n}",
"func (g *Game)Count()(map[string]int,map[string]*DetailScore,map[string]int){\n\troundScore,detailScore := g.CurrentRound.countScore(g.playersById,g.Players[g.CurrentDicoPlayer],true,g.TypeGameNormal)\n\treturn roundScore,detailScore,g.GetTotalScore()\n}",
"func updatePawnChainScore(pawnchain int) float64 {\n\tvar score float64\n\tif pawnchain > 2 {\n\t\tscore += float64(pawnchain) * LONGPAWNCHAIN\n\t} else if pawnchain != 0 {\n\t\tscore += ISOLATEDPAWN / float64(pawnchain)\n\t}\n\treturn score\n}"
] | [
"0.67207325",
"0.6519543",
"0.63390255",
"0.63319117",
"0.6323507",
"0.6314036",
"0.62595856",
"0.61863875",
"0.61842114",
"0.60595137",
"0.6030532",
"0.59850454",
"0.5970548",
"0.59298086",
"0.5918475",
"0.5910249",
"0.5907338",
"0.58553475",
"0.5848734",
"0.584787",
"0.58034754",
"0.57975173",
"0.5788707",
"0.5776463",
"0.57742405",
"0.57587427",
"0.5743945",
"0.5716897",
"0.5693104",
"0.5680982",
"0.56688267",
"0.561711",
"0.5614243",
"0.5594199",
"0.5537196",
"0.5533831",
"0.5532492",
"0.552683",
"0.551595",
"0.55119574",
"0.5495182",
"0.54928696",
"0.5491508",
"0.5489063",
"0.54853195",
"0.5482188",
"0.5468013",
"0.54607624",
"0.5446887",
"0.5433662",
"0.5428975",
"0.540241",
"0.5394724",
"0.53933334",
"0.5389623",
"0.53845274",
"0.53736156",
"0.5338651",
"0.533413",
"0.53292114",
"0.5325163",
"0.52964133",
"0.5296225",
"0.52950346",
"0.5287052",
"0.52834666",
"0.5270709",
"0.5266398",
"0.5257739",
"0.5245138",
"0.5221803",
"0.52171206",
"0.52115124",
"0.52085775",
"0.52048236",
"0.51940554",
"0.51921445",
"0.51915586",
"0.5190046",
"0.5189683",
"0.5183283",
"0.51784843",
"0.517624",
"0.5171909",
"0.51695746",
"0.5160464",
"0.51592606",
"0.5157041",
"0.5131502",
"0.5127669",
"0.51253474",
"0.5104233",
"0.5102",
"0.5096002",
"0.50959736",
"0.5093219",
"0.50916785",
"0.50856423",
"0.50856",
"0.5084401"
] | 0.66270703 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.