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
DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceAccountRef.
func (in *ServiceAccountRef) DeepCopy() *ServiceAccountRef { if in == nil { return nil } out := new(ServiceAccountRef) in.DeepCopyInto(out) return out }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (in *ServiceAccount) DeepCopy() *ServiceAccount {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceAccount)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceRef) DeepCopy() *ServiceRef {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceRef)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceReference) DeepCopy() *ServiceReference {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceReference)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceReference) DeepCopy() *ServiceReference {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceReference)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceAccountV1) DeepCopy() *ServiceAccountV1 {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceAccountV1)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *LokiServiceAccount) DeepCopy() *LokiServiceAccount {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(LokiServiceAccount)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o BuildRunSpecOutput) ServiceAccount() BuildRunSpecServiceAccountPtrOutput {\n\treturn o.ApplyT(func(v BuildRunSpec) *BuildRunSpecServiceAccount { return v.ServiceAccount }).(BuildRunSpecServiceAccountPtrOutput)\n}", "func (o AiEndpointDeployedModelOutput) ServiceAccount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AiEndpointDeployedModel) *string { return v.ServiceAccount }).(pulumi.StringPtrOutput)\n}", "func (o InstanceFromTemplateOutput) ServiceAccount() InstanceFromTemplateServiceAccountOutput {\n\treturn o.ApplyT(func(v *InstanceFromTemplate) InstanceFromTemplateServiceAccountOutput { return v.ServiceAccount }).(InstanceFromTemplateServiceAccountOutput)\n}", "func (o BuildRunSpecPtrOutput) ServiceAccount() BuildRunSpecServiceAccountPtrOutput {\n\treturn o.ApplyT(func(v *BuildRunSpec) *BuildRunSpecServiceAccount {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ServiceAccount\n\t}).(BuildRunSpecServiceAccountPtrOutput)\n}", "func (o FolderNotificationConfigOutput) ServiceAccount() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FolderNotificationConfig) pulumi.StringOutput { return v.ServiceAccount }).(pulumi.StringOutput)\n}", "func (o LookupOrganizationNotificationConfigResultOutput) ServiceAccount() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupOrganizationNotificationConfigResult) string { return v.ServiceAccount }).(pulumi.StringOutput)\n}", "func (o InstanceOutput) ServiceAccount() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.ServiceAccount }).(pulumi.StringOutput)\n}", "func (c *component) serviceAccount() *corev1.ServiceAccount {\n\treturn &corev1.ServiceAccount{\n\t\tTypeMeta: metav1.TypeMeta{Kind: \"ServiceAccount\", APIVersion: \"v1\"},\n\t\tObjectMeta: metav1.ObjectMeta{Name: APLName, Namespace: common.CalicoNamespace},\n\t}\n}", "func (o ApplicationOutput) ServiceAccount() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Application) pulumi.StringOutput { return v.ServiceAccount }).(pulumi.StringOutput)\n}", "func (o ConnectionCloudResourceOutput) ServiceAccountId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ConnectionCloudResource) *string { return v.ServiceAccountId }).(pulumi.StringPtrOutput)\n}", "func (o ArgoCDSpecRepoOutput) Serviceaccount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDSpecRepo) *string { return v.Serviceaccount }).(pulumi.StringPtrOutput)\n}", "func (o ArgoCDSpecRepoPtrOutput) Serviceaccount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDSpecRepo) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Serviceaccount\n\t}).(pulumi.StringPtrOutput)\n}", "func ServiceAccount(iamClient *iam.Service, accountId *ServiceAccountId) (*iam.ServiceAccount, error) {\n\taccount, err := iamClient.Projects.ServiceAccounts.Get(accountId.ResourceName()).Do()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not find service account '%s': %v\", accountId.ResourceName(), err)\n\t}\n\n\treturn account, nil\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 (in *DruidService) DeepCopy() *DruidService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DruidService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o NodeOutput) ServiceAccount() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Node) pulumi.StringOutput { return v.ServiceAccount }).(pulumi.StringOutput)\n}", "func (o NodeOutput) ServiceAccount() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Node) pulumi.StringOutput { return v.ServiceAccount }).(pulumi.StringOutput)\n}", "func (o LakeOutput) ServiceAccount() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Lake) pulumi.StringOutput { return v.ServiceAccount }).(pulumi.StringOutput)\n}", "func (in *ServiceBindingSchema) DeepCopy() *ServiceBindingSchema {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceBindingSchema)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceConnection) DeepCopy() *ServiceConnection {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceConnection)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (kubeutil *Kube) ApplyServiceAccount(serviceAccount *corev1.ServiceAccount) (*corev1.ServiceAccount, error) {\n\toldServiceAccount, err := kubeutil.GetServiceAccount(serviceAccount.Namespace, serviceAccount.GetName())\n\tif err != nil && errors.IsNotFound(err) {\n\t\tcreatedServiceAccount, err := kubeutil.kubeClient.CoreV1().ServiceAccounts(serviceAccount.GetNamespace()).Create(context.TODO(), serviceAccount, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create ServiceAccount object: %w\", err)\n\t\t}\n\t\tlog.Debugf(\"Created ServiceAccount %s in namespace %s\", createdServiceAccount.GetName(), createdServiceAccount.GetNamespace())\n\t\treturn createdServiceAccount, nil\n\t} else if err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get ServiceAccount object: %w\", err)\n\t}\n\n\tlog.Debugf(\"ServiceAccount object %s already exists in namespace %s, updating the object now\", serviceAccount.GetName(), serviceAccount.GetNamespace())\n\toldServiceAccountJson, err := json.Marshal(oldServiceAccount)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal old ServiceAccount object: %w\", err)\n\t}\n\n\tnewServiceAccount := oldServiceAccount.DeepCopy()\n\tnewServiceAccount.OwnerReferences = serviceAccount.OwnerReferences\n\tnewServiceAccount.Labels = serviceAccount.Labels\n\tnewServiceAccount.Annotations = serviceAccount.Annotations\n\tnewServiceAccount.AutomountServiceAccountToken = serviceAccount.AutomountServiceAccountToken\n\n\tnewServiceAccountJson, err := json.Marshal(newServiceAccount)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal new ServiceAccount object: %w\", err)\n\t}\n\n\tpatchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldServiceAccountJson, newServiceAccountJson, corev1.ServiceAccount{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create two way merge patch ServiceAccount objects: %w\", err)\n\t}\n\n\tif !IsEmptyPatch(patchBytes) {\n\t\tpatchedServiceAccount, err := kubeutil.kubeClient.CoreV1().ServiceAccounts(serviceAccount.GetNamespace()).Patch(context.TODO(), serviceAccount.GetName(), types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to patch ServiceAccount object: %w\", err)\n\t\t}\n\t\tlog.Debugf(\"Patched ServiceAccount %s in namespace %s\", patchedServiceAccount.GetName(), patchedServiceAccount.GetNamespace())\n\t\treturn patchedServiceAccount, nil\n\t} else {\n\t\tlog.Debugf(\"No need to patch ServiceAccount %s \", serviceAccount.GetName())\n\t}\n\n\treturn oldServiceAccount, nil\n}", "func (in *ServiceFields) DeepCopy() *ServiceFields {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceFields)\n\tin.DeepCopyInto(out)\n\treturn out\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 (in *MongoService) DeepCopy() *MongoService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MongoService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o ConnectionCloudSqlOutput) ServiceAccountId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ConnectionCloudSql) *string { return v.ServiceAccountId }).(pulumi.StringPtrOutput)\n}", "func NewAccountService(client *binarylane.Client) AccountService {\n\treturn &accountService{\n\t\tclient: client,\n\t}\n}", "func (in *BcsService) DeepCopy() *BcsService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(BcsService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func NewAccountService(pr repository.Profile, logger *logrus.Logger) Profile {\n\treturn &profileService{\n\t\tprofileRepo: pr,\n\t\tlog: logger,\n\t}\n}", "func (in *AuthenticationService) DeepCopy() *AuthenticationService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AuthenticationService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceInstance) DeepCopy() *ServiceInstance {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceInstance)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o OceanLaunchSpecOutput) ServiceAccount() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *OceanLaunchSpec) pulumi.StringOutput { return v.ServiceAccount }).(pulumi.StringOutput)\n}", "func (b *taskBuilder) serviceAccount(sa string) {\n\tb.Spec.ServiceAccount = sa\n}", "func (in *ConsoleService) DeepCopy() *ConsoleService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ConsoleService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceV1) DeepCopy() *ServiceV1 {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceV1)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *Client) Set(ctx context.Context, name, namespace string, o Options) (err error) {\n\tspec := &v1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tAnnotations: o.Annotations,\n\t\t\tLabels: o.Labels,\n\t\t},\n\t\tAutomountServiceAccountToken: &o.AutomountServiceAccountToken,\n\t\tImagePullSecrets: func() (l []v1.LocalObjectReference) {\n\t\t\tfor _, s := range o.ImagePullSecrets {\n\t\t\t\tl = append(l, v1.LocalObjectReference{Name: s})\n\t\t\t}\n\t\t\treturn\n\t\t}(),\n\t\tSecrets: func() (l []v1.ObjectReference) {\n\t\t\tfor _, s := range o.Secrets {\n\t\t\t\tl = append(l, v1.ObjectReference{Name: s})\n\t\t\t}\n\t\t\treturn\n\t\t}(),\n\t}\n\n\t_, err = c.clientset.CoreV1().ServiceAccounts(namespace).Update(ctx, spec, metav1.UpdateOptions{})\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t_, err = c.clientset.CoreV1().ServiceAccounts(namespace).Create(ctx, spec, metav1.CreateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"creating service account %s in namespace %s: %w\", name, namespace, err)\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"updating service account %s in namespace %s: %w\", name, namespace, err)\n\t\t}\n\t}\n\n\treturn\n}", "func (c *ProjectsTransferConfigsPatchCall) ServiceAccountName(serviceAccountName string) *ProjectsTransferConfigsPatchCall {\n\tc.urlParams_.Set(\"serviceAccountName\", serviceAccountName)\n\treturn c\n}", "func (c *ProjectsLocationsTransferConfigsPatchCall) ServiceAccountName(serviceAccountName string) *ProjectsLocationsTransferConfigsPatchCall {\n\tc.urlParams_.Set(\"serviceAccountName\", serviceAccountName)\n\treturn c\n}", "func (in *MongoServiceList) DeepCopy() *MongoServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MongoServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceProfile) DeepCopy() *ServiceProfile {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceProfile)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func NewAccountService(repository repository.AcccountRepository) AccountService {\n\treturn &accountService{\n\t\trepository: repository,\n\t}\n}", "func (in *ServiceAccountPolicy) ResolveReferences(ctx context.Context, c client.Reader) error {\n\tr := reference.NewAPIResolver(c, in)\n\n\t// Resolve spec.forProvider.serviceAccount\n\trsp, err := r.Resolve(ctx, reference.ResolutionRequest{\n\t\tCurrentValue: reference.FromPtrValue(in.Spec.ForProvider.ServiceAccount),\n\t\tReference: in.Spec.ForProvider.ServiceAccountRef,\n\t\tSelector: in.Spec.ForProvider.ServiceAccountSelector,\n\t\tTo: reference.To{Managed: &ServiceAccount{}, List: &ServiceAccountList{}},\n\t\tExtract: ServiceAccountRRN(),\n\t})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"spec.forProvider.cryptoKey\")\n\t}\n\tin.Spec.ForProvider.ServiceAccount = reference.ToPtrValue(rsp.ResolvedValue)\n\tin.Spec.ForProvider.ServiceAccountRef = rsp.ResolvedReference\n\n\t// Resolve spec.ForProvider.Policy.Bindings[*].Members\n\tfor i := range in.Spec.ForProvider.Policy.Bindings {\n\t\tmrsp, err := r.ResolveMultiple(ctx, reference.MultiResolutionRequest{\n\t\t\tCurrentValues: in.Spec.ForProvider.Policy.Bindings[i].Members,\n\t\t\tReferences: in.Spec.ForProvider.Policy.Bindings[i].ServiceAccountMemberRefs,\n\t\t\tSelector: in.Spec.ForProvider.Policy.Bindings[i].ServiceAccountMemberSelector,\n\t\t\tTo: reference.To{Managed: &ServiceAccount{}, List: &ServiceAccountList{}},\n\t\t\tExtract: ServiceAccountMemberName(),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"spec.forProvider.Policy.Bindings[%d].Members\", i)\n\t\t}\n\t\tin.Spec.ForProvider.Policy.Bindings[i].Members = mrsp.ResolvedValues\n\t\tin.Spec.ForProvider.Policy.Bindings[i].ServiceAccountMemberRefs = mrsp.ResolvedReferences\n\t}\n\n\treturn nil\n}", "func (in *Service) DeepCopy() *Service {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Service)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Service) DeepCopy() *Service {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Service)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Service) DeepCopy() *Service {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Service)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Service) DeepCopy() *Service {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Service)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Service) DeepCopy() *Service {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Service)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Service) DeepCopy() *Service {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Service)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Service) DeepCopy() *Service {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Service)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *Client) WatchServiceAccounts(namespace string, opts *k8s.WatchOptions, events chan k8s.ServiceAccountWatchEvent) error {\n\tif events == nil {\n\t\treturn errors.New(\"events must not be nil\")\n\t}\n\trawEvents := make(chan k8s.WatchEvent)\n\tgo func() {\n\t\tfor rawEvent := range rawEvents {\n\t\t\tevents <- &watchEventServiceAccount{raw: rawEvent}\n\t\t}\n\t\tclose(events)\n\t}()\n\t_, err := c.doWatch(\"GET\", serviceaccountGeneratePath(namespace, \"\")+\"?\"+watchOptionsQuery(opts), nil, rawEvents)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to watch ServiceAccounts\")\n\t}\n\treturn nil\n}", "func (in *WorkloadServiceClaimReference) DeepCopy() *WorkloadServiceClaimReference {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(WorkloadServiceClaimReference)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Account) DeepCopy() *Account {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Account)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Account) DeepCopy() *Account {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Account)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *CassandraService) DeepCopy() *CassandraService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(CassandraService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceInstanceBinding) DeepCopy() *ServiceInstanceBinding {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceInstanceBinding)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *BcsServiceList) DeepCopy() *BcsServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(BcsServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceConfig) DeepCopy() *ServiceConfig {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceConfig)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *TemplateService) DeepCopy() *TemplateService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TemplateService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *ProjectsTransferConfigsCreateCall) ServiceAccountName(serviceAccountName string) *ProjectsTransferConfigsCreateCall {\n\tc.urlParams_.Set(\"serviceAccountName\", serviceAccountName)\n\treturn c\n}", "func (o DirectoryConfigOutput) ServiceAccountCredentials() DirectoryConfigServiceAccountCredentialsOutput {\n\treturn o.ApplyT(func(v *DirectoryConfig) DirectoryConfigServiceAccountCredentialsOutput {\n\t\treturn v.ServiceAccountCredentials\n\t}).(DirectoryConfigServiceAccountCredentialsOutput)\n}", "func (in *MobileClientService) DeepCopy() *MobileClientService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MobileClientService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RouteServiceBinding) DeepCopy() *RouteServiceBinding {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RouteServiceBinding)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceTemplate) DeepCopy() *ServiceTemplate {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceTemplate)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ConsoleServiceList) DeepCopy() *ConsoleServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ConsoleServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *ProjectsLocationsTransferConfigsCreateCall) ServiceAccountName(serviceAccountName string) *ProjectsLocationsTransferConfigsCreateCall {\n\tc.urlParams_.Set(\"serviceAccountName\", serviceAccountName)\n\treturn c\n}", "func (in *DiscoveryService) DeepCopy() *DiscoveryService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DiscoveryService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *InnerService) DeepCopy() *InnerService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(InnerService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func NewService(r repo.AccountRepository) AccountService {\n\treturn &accountService{r}\n}", "func (in *ServiceBroker) DeepCopy() *ServiceBroker {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceBroker)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ProxyService) DeepCopy() *ProxyService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ProxyService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *InnerServiceList) DeepCopy() *InnerServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(InnerServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (s *serviceAccountLister) ServiceAccounts(namespace string) v1.ServiceAccountNamespaceLister {\n\treturn serviceAccountNamespaceLister{client: s.client, tweakListOptions: s.tweakListOptions, namespace: namespace}\n}", "func (in *ServiceEntry) DeepCopy() *ServiceEntry {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceEntry)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceList) DeepCopy() *ServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceList) DeepCopy() *ServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SpinnakerService) DeepCopy() *SpinnakerService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SpinnakerService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AuthenticationServiceList) DeepCopy() *AuthenticationServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AuthenticationServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o *CloudSnapshotAccount) DeepCopy() *CloudSnapshotAccount {\n\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tout := &CloudSnapshotAccount{}\n\to.DeepCopyInto(out)\n\n\treturn out\n}", "func (in *ServiceAccountRef) DeepCopyInto(out *ServiceAccountRef) {\n\t*out = *in\n}", "func (in *ServiceRef) DeepCopyInto(out *ServiceRef) {\n\t*out = *in\n}", "func (in *ImportedAccount) DeepCopy() *ImportedAccount {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ImportedAccount)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (s *serviceAccountLister) List(selector labels.Selector) (ret []*corev1.ServiceAccount, err error) {\n\tlistopt := metav1.ListOptions{\n\t\tLabelSelector: selector.String(),\n\t}\n\tif s.tweakListOptions != nil {\n\t\ts.tweakListOptions(&listopt)\n\t}\n\tlist, err := s.client.CoreV1().ServiceAccounts(metav1.NamespaceAll).List(listopt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i := range list.Items {\n\t\tret = append(ret, &list.Items[i])\n\t}\n\treturn ret, nil\n}", "func (o InstanceOutput) ServiceAccountScopes() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringArrayOutput { return v.ServiceAccountScopes }).(pulumi.StringArrayOutput)\n}", "func (in *ServiceExport) DeepCopy() *ServiceExport {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceExport)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o *SparseCloudSnapshotAccount) DeepCopy() *SparseCloudSnapshotAccount {\n\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tout := &SparseCloudSnapshotAccount{}\n\to.DeepCopyInto(out)\n\n\treturn out\n}", "func (in *ServiceParameter) DeepCopy() *ServiceParameter {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceParameter)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AppService) DeepCopy() *AppService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AppService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *GitAccount) DeepCopy() *GitAccount {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(GitAccount)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceType) DeepCopy() *ServiceType {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceType)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func resourceServiceAccount() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreateContext: ServiceAccountCreate,\n\t\tReadContext: ServiceAccountRead,\n\t\t// UpdateContext: ServiceAccountUpdate,\n\t\tDeleteContext: ServiceAccountDelete,\n\t\tImporter: &schema.ResourceImporter{\n\t\t\tStateContext: schema.ImportStatePassthroughContext,\n\t\t},\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tDescription: \"\",\n\t\t\t},\n\t\t\t\"description\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tDescription: \"Service Account Description\",\n\t\t\t},\n\t\t},\n\t}\n}", "func (in *CatalogServiceClaim) DeepCopy() *CatalogServiceClaim {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(CatalogServiceClaim)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PrivateLinkService) DeepCopy() *PrivateLinkService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PrivateLinkService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o LookupInstanceResultOutput) ServiceAccounts() ServiceAccountResponseArrayOutput {\n\treturn o.ApplyT(func(v LookupInstanceResult) []ServiceAccountResponse { return v.ServiceAccounts }).(ServiceAccountResponseArrayOutput)\n}", "func (in *ServiceInstanceSchema) DeepCopy() *ServiceInstanceSchema {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceInstanceSchema)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *UnprotectedService) DeepCopy() *UnprotectedService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(UnprotectedService)\n\tin.DeepCopyInto(out)\n\treturn out\n}" ]
[ "0.6922871", "0.68160284", "0.65097475", "0.65097475", "0.6234114", "0.6091671", "0.6017589", "0.594521", "0.5911724", "0.58977866", "0.5787274", "0.57625866", "0.57212543", "0.5715463", "0.5705707", "0.56993514", "0.5689972", "0.56890875", "0.5659267", "0.55872035", "0.5576813", "0.5550432", "0.5550432", "0.5522159", "0.54668564", "0.5446381", "0.5438074", "0.5311535", "0.5309023", "0.5296117", "0.52885896", "0.5273716", "0.52605504", "0.5236743", "0.5227876", "0.5218584", "0.5201275", "0.51961684", "0.5183802", "0.51828736", "0.5181567", "0.5162099", "0.51615894", "0.51586986", "0.51395845", "0.51310617", "0.51102084", "0.5110183", "0.5110183", "0.5110183", "0.5110183", "0.5110183", "0.5110183", "0.5110183", "0.5107584", "0.5102078", "0.5095276", "0.5095276", "0.50920194", "0.50882566", "0.5079709", "0.507543", "0.5064726", "0.50635517", "0.50462824", "0.5036532", "0.50224113", "0.50164384", "0.50139594", "0.50089103", "0.50036293", "0.49821928", "0.49794623", "0.4978499", "0.49614343", "0.4943315", "0.49253392", "0.49202424", "0.49163476", "0.49163476", "0.49141493", "0.4899855", "0.48882622", "0.4883082", "0.48628944", "0.48626047", "0.48560044", "0.48495477", "0.48315814", "0.48240364", "0.4823593", "0.4813846", "0.48013592", "0.48004746", "0.47979558", "0.4792384", "0.47869313", "0.47787455", "0.4755598", "0.475526" ]
0.7754007
0
DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be nonnil.
func (in *ServiceRef) DeepCopyInto(out *ServiceRef) { *out = *in }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *RunInfo) DeepCopyInto(out *RunInfo) {\n\t*out = *r\n}", "func (in *Base) DeepCopyInto(out *Base) {\n\t*out = *in\n\treturn\n}", "func (in *ForkObject) DeepCopyInto(out *ForkObject) {\n\t*out = *in\n}", "func (in *TargetObjectInfo) DeepCopyInto(out *TargetObjectInfo) {\n\t*out = *in\n}", "func (in *DebugObjectInfo) DeepCopyInto(out *DebugObjectInfo) {\n\t*out = *in\n}", "func (in *Input) DeepCopyInto(out *Input) {\n\t*out = *in\n}", "func (u *SSN) DeepCopyInto(out *SSN) {\n\t*out = *u\n}", "func (in *ExistPvc) DeepCopyInto(out *ExistPvc) {\n\t*out = *in\n}", "func (in *DockerStep) DeepCopyInto(out *DockerStep) {\n\t*out = *in\n\tif in.Inline != nil {\n\t\tin, out := &in.Inline, &out.Inline\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tout.Auth = in.Auth\n\treturn\n}", "func (in *Container) DeepCopyInto(out *Container) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.Command != nil {\n\t\tin, out := &in.Command, &out.Command\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.LifeCycleScript != nil {\n\t\tin, out := &in.LifeCycleScript, &out.LifeCycleScript\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *RuntimeRef) DeepCopyInto(out *RuntimeRef) {\n\t*out = *in\n}", "func (in *Ibft2) DeepCopyInto(out *Ibft2) {\n\t*out = *in\n\treturn\n}", "func (in *TestResult) DeepCopyInto(out *TestResult) {\n\t*out = *in\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *Haproxy) DeepCopyInto(out *Haproxy) {\n\t*out = *in\n\treturn\n}", "func (in *SSH) DeepCopyInto(out *SSH) {\n\t*out = *in\n\treturn\n}", "func (in *Runtime) DeepCopyInto(out *Runtime) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (b *Base64) DeepCopyInto(out *Base64) {\n\t*out = *b\n}", "func (in *EventDependencyTransformer) DeepCopyInto(out *EventDependencyTransformer) {\n\t*out = *in\n\treturn\n}", "func (in *StageOutput) DeepCopyInto(out *StageOutput) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Dependent) DeepCopyInto(out *Dependent) {\n\t*out = *in\n\treturn\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *GitFileGeneratorItem) DeepCopyInto(out *GitFileGeneratorItem) {\n\t*out = *in\n}", "func (in *AnsibleStep) DeepCopyInto(out *AnsibleStep) {\n\t*out = *in\n\treturn\n}", "func (in *Forks) DeepCopyInto(out *Forks) {\n\t*out = *in\n\tif in.DAO != nil {\n\t\tin, out := &in.DAO, &out.DAO\n\t\t*out = new(uint)\n\t\t**out = **in\n\t}\n}", "func (in *ContainerPort) DeepCopyInto(out *ContainerPort) {\n\t*out = *in\n}", "func (in *General) DeepCopyInto(out *General) {\n\t*out = *in\n\treturn\n}", "func (in *IsoContainer) DeepCopyInto(out *IsoContainer) {\n\t*out = *in\n}", "func (in *Git) DeepCopyInto(out *Git) {\n\t*out = *in\n\treturn\n}", "func (in *BackupProgress) DeepCopyInto(out *BackupProgress) {\n\t*out = *in\n}", "func (in *ConfigFile) DeepCopyInto(out *ConfigFile) {\n\t*out = *in\n}", "func (in *DataDisk) DeepCopyInto(out *DataDisk) {\n\t*out = *in\n}", "func (in *PhaseStep) DeepCopyInto(out *PhaseStep) {\n\t*out = *in\n}", "func (u *MAC) DeepCopyInto(out *MAC) {\n\t*out = *u\n}", "func (in *Variable) DeepCopyInto(out *Variable) {\n\t*out = *in\n}", "func (in *RestoreProgress) DeepCopyInto(out *RestoreProgress) {\n\t*out = *in\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Path) DeepCopyInto(out *Path) {\n\t*out = *in\n\treturn\n}", "func (in *NamespacedObjectReference) DeepCopyInto(out *NamespacedObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *GitDirectoryGeneratorItem) DeepCopyInto(out *GitDirectoryGeneratorItem) {\n\t*out = *in\n}", "func (in *NamePath) DeepCopyInto(out *NamePath) {\n\t*out = *in\n\treturn\n}", "func (in *ConsoleCreateObj) DeepCopyInto(out *ConsoleCreateObj) {\n\t*out = *in\n}", "func (in *UsedPipelineRun) DeepCopyInto(out *UsedPipelineRun) {\n\t*out = *in\n}", "func (in *BuildTemplate) DeepCopyInto(out *BuildTemplate) {\n\t*out = *in\n\tif in.Cmd != nil {\n\t\tin, out := &in.Cmd, &out.Cmd\n\t\t*out = make([]BuildTemplateStep, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n}", "func (in *ObjectInfo) DeepCopyInto(out *ObjectInfo) {\n\t*out = *in\n\tout.GroupVersionKind = in.GroupVersionKind\n\treturn\n}", "func (in *Files) DeepCopyInto(out *Files) {\n\t*out = *in\n}", "func (in *Source) DeepCopyInto(out *Source) {\n\t*out = *in\n\tif in.Dependencies != nil {\n\t\tin, out := &in.Dependencies, &out.Dependencies\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MavenRepositories != nil {\n\t\tin, out := &in.MavenRepositories, &out.MavenRepositories\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\treturn\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *StackBuild) DeepCopyInto(out *StackBuild) {\n\t*out = *in\n\treturn\n}", "func (in *BuildTaskRef) DeepCopyInto(out *BuildTaskRef) {\n\t*out = *in\n\treturn\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *PathInfo) DeepCopyInto(out *PathInfo) {\n\t*out = *in\n}", "func (in *PoA) DeepCopyInto(out *PoA) {\n\t*out = *in\n}", "func (in *Section) DeepCopyInto(out *Section) {\n\t*out = *in\n\tif in.SecretRefs != nil {\n\t\tin, out := &in.SecretRefs, &out.SecretRefs\n\t\t*out = make([]SecretReference, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Files != nil {\n\t\tin, out := &in.Files, &out.Files\n\t\t*out = make([]FileMount, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *DNSSelection) DeepCopyInto(out *DNSSelection) {\n\t*out = *in\n\tif in.Include != nil {\n\t\tin, out := &in.Include, &out.Include\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Exclude != nil {\n\t\tin, out := &in.Exclude, &out.Exclude\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n}", "func (in *ReleaseVersion) DeepCopyInto(out *ReleaseVersion) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *PathRule) DeepCopyInto(out *PathRule) {\n\t*out = *in\n\treturn\n}", "func (in *Command) DeepCopyInto(out *Command) {\n\t*out = *in\n\tif in.Flags != nil {\n\t\tin, out := &in.Flags, &out.Flags\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Value != nil {\n\t\tin, out := &in.Value, &out.Value\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *DockerLifecycleData) DeepCopyInto(out *DockerLifecycleData) {\n\t*out = *in\n}", "func (in *RunScriptStepConfig) DeepCopyInto(out *RunScriptStepConfig) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *Checksum) DeepCopyInto(out *Checksum) {\n\t*out = *in\n}", "func (in *DomainNameOutput) DeepCopyInto(out *DomainNameOutput) {\n\t*out = *in\n}", "func (in *InterfaceStruct) DeepCopyInto(out *InterfaceStruct) {\n\t*out = *in\n\tif in.val != nil {\n\t\tin, out := &in.val, &out.val\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *Ref) DeepCopyInto(out *Ref) {\n\t*out = *in\n}", "func (in *MemorySpec) DeepCopyInto(out *MemorySpec) {\n\t*out = *in\n}", "func (in *BuildJenkinsInfo) DeepCopyInto(out *BuildJenkinsInfo) {\n\t*out = *in\n\treturn\n}", "func (in *KopsNode) DeepCopyInto(out *KopsNode) {\n\t*out = *in\n\treturn\n}", "func (in *VirtualDatabaseBuildObject) DeepCopyInto(out *VirtualDatabaseBuildObject) {\n\t*out = *in\n\tif in.Incremental != nil {\n\t\tin, out := &in.Incremental, &out.Incremental\n\t\t*out = new(bool)\n\t\t**out = **in\n\t}\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]v1.EnvVar, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\tout.Git = in.Git\n\tin.Source.DeepCopyInto(&out.Source)\n\tif in.Webhooks != nil {\n\t\tin, out := &in.Webhooks, &out.Webhooks\n\t\t*out = make([]WebhookSecret, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *MaintenanceInfo) DeepCopyInto(out *MaintenanceInfo) {\n\t*out = *in\n\treturn\n}", "func (in *FalconAPI) DeepCopyInto(out *FalconAPI) {\n\t*out = *in\n}", "func (in *EBS) DeepCopyInto(out *EBS) {\n\t*out = *in\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n\treturn\n}", "func (in *Empty) DeepCopyInto(out *Empty) {\n\t*out = *in\n\tout.XXX_NoUnkeyedLiteral = in.XXX_NoUnkeyedLiteral\n\tif in.XXX_unrecognized != nil {\n\t\tin, out := &in.XXX_unrecognized, &out.XXX_unrecognized\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *ComponentDistGit) DeepCopyInto(out *ComponentDistGit) {\n\t*out = *in\n\treturn\n}", "func (in *Persistence) DeepCopyInto(out *Persistence) {\n\t*out = *in\n\tout.Size = in.Size.DeepCopy()\n\treturn\n}", "func (in *Memory) DeepCopyInto(out *Memory) {\n\t*out = *in\n\tout.Required = in.Required.DeepCopy()\n}", "func (in *ManagedDisk) DeepCopyInto(out *ManagedDisk) {\n\t*out = *in\n}", "func (e *Email) DeepCopyInto(out *Email) {\n\t*out = *e\n}", "func (in *ImageInfo) DeepCopyInto(out *ImageInfo) {\n\t*out = *in\n}", "func (in *ShootRef) DeepCopyInto(out *ShootRef) {\n\t*out = *in\n}", "func (in *NetflowType) DeepCopyInto(out *NetflowType) {\n\t*out = *in\n\treturn\n}", "func (in *N3000Fpga) DeepCopyInto(out *N3000Fpga) {\n\t*out = *in\n}", "func (in *Node) DeepCopyInto(out *Node) {\n\t*out = *in\n\tif in.FailStatus != nil {\n\t\tin, out := &in.FailStatus, &out.FailStatus\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MigratingSlots != nil {\n\t\tin, out := &in.MigratingSlots, &out.MigratingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.ImportingSlots != nil {\n\t\tin, out := &in.ImportingSlots, &out.ImportingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n}", "func (in *BuiltInAdapter) DeepCopyInto(out *BuiltInAdapter) {\n\t*out = *in\n}", "func (in *CPUSpec) DeepCopyInto(out *CPUSpec) {\n\t*out = *in\n}", "func (in *LoopState) DeepCopyInto(out *LoopState) {\n\t*out = *in\n}" ]
[ "0.8216088", "0.8128937", "0.81051093", "0.8086112", "0.80840266", "0.806814", "0.80643326", "0.80272067", "0.8013088", "0.79972315", "0.799318", "0.7988673", "0.79883105", "0.79879236", "0.79879236", "0.7986761", "0.79770774", "0.7973031", "0.7970074", "0.7970074", "0.7970074", "0.7968491", "0.7963908", "0.7962594", "0.79461676", "0.79461676", "0.79453707", "0.794318", "0.794318", "0.79430556", "0.7941854", "0.7939476", "0.7937904", "0.79294026", "0.7925471", "0.7917021", "0.79131836", "0.79123056", "0.7910745", "0.79105514", "0.79092926", "0.7906994", "0.79068947", "0.7905208", "0.7905208", "0.7904789", "0.7904576", "0.7902542", "0.789971", "0.7898187", "0.789275", "0.78916943", "0.78905755", "0.7889031", "0.7887323", "0.7887001", "0.78859967", "0.78859967", "0.788571", "0.7881972", "0.7875957", "0.7875957", "0.78754383", "0.78744066", "0.78725743", "0.7872079", "0.78715914", "0.7865343", "0.7863912", "0.7863912", "0.7863912", "0.78638506", "0.7863712", "0.7862366", "0.7859421", "0.7858547", "0.7857873", "0.78512096", "0.7847138", "0.78456485", "0.7841974", "0.78375477", "0.7837439", "0.78371376", "0.7835643", "0.7833311", "0.78312105", "0.7830207", "0.7828144", "0.7826242", "0.7825785", "0.782401", "0.7820985", "0.7819203", "0.78140086", "0.7812223", "0.7811996", "0.7811559", "0.78109616", "0.7809847", "0.7809696" ]
0.0
-1
DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceRef.
func (in *ServiceRef) DeepCopy() *ServiceRef { if in == nil { return nil } out := new(ServiceRef) in.DeepCopyInto(out) return out }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (in *ServiceReference) DeepCopy() *ServiceReference {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceReference)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceReference) DeepCopy() *ServiceReference {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceReference)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Service) DeepCopy() *Service {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Service)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Service) DeepCopy() *Service {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Service)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Service) DeepCopy() *Service {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Service)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Service) DeepCopy() *Service {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Service)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Service) DeepCopy() *Service {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Service)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Service) DeepCopy() *Service {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Service)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Service) DeepCopy() *Service {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Service)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DiscoveryService) DeepCopy() *DiscoveryService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DiscoveryService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceV1) DeepCopy() *ServiceV1 {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceV1)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *MongoService) DeepCopy() *MongoService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MongoService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *InnerService) DeepCopy() *InnerService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(InnerService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ProxyService) DeepCopy() *ProxyService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ProxyService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceAccountRef) DeepCopy() *ServiceAccountRef {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceAccountRef)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceInstance) DeepCopy() *ServiceInstance {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceInstance)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceFields) DeepCopy() *ServiceFields {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceFields)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ConsoleService) DeepCopy() *ConsoleService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ConsoleService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DruidService) DeepCopy() *DruidService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DruidService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AppService) DeepCopy() *AppService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AppService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *BcsService) DeepCopy() *BcsService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(BcsService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *MobileClientService) DeepCopy() *MobileClientService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MobileClientService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RegistryService) DeepCopy() *RegistryService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RegistryService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *VirtualService) DeepCopy() *VirtualService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(VirtualService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *VirtualService) DeepCopy() *VirtualService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(VirtualService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceBindingSchema) DeepCopy() *ServiceBindingSchema {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceBindingSchema)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *TemplateService) DeepCopy() *TemplateService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TemplateService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *InlineService) DeepCopy() *InlineService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(InlineService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *MongoServiceList) DeepCopy() *MongoServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MongoServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SpinnakerService) DeepCopy() *SpinnakerService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SpinnakerService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PrivateLinkService) DeepCopy() *PrivateLinkService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PrivateLinkService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceExport) DeepCopy() *ServiceExport {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceExport)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RouteServiceBinding) DeepCopy() *RouteServiceBinding {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RouteServiceBinding)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *UnprotectedService) DeepCopy() *UnprotectedService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(UnprotectedService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *GatewayService) DeepCopy() *GatewayService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(GatewayService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PagerdutyService) DeepCopy() *PagerdutyService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PagerdutyService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceConnection) DeepCopy() *ServiceConnection {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceConnection)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *HelloHttpService) DeepCopy() *HelloHttpService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(HelloHttpService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceSelector) DeepCopy() *ServiceSelector {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceSelector)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceList) DeepCopy() *ServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceList) DeepCopy() *ServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceSpec) DeepCopy() *ServiceSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceSpec) DeepCopy() *ServiceSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceInstanceBinding) DeepCopy() *ServiceInstanceBinding {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceInstanceBinding)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ExternalService) DeepCopy() *ExternalService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ExternalService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *LokiService) DeepCopy() *LokiService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(LokiService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceTemplate) DeepCopy() *ServiceTemplate {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceTemplate)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *InnerServiceList) DeepCopy() *InnerServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(InnerServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceConfig) DeepCopy() *ServiceConfig {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceConfig)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *CassandraService) DeepCopy() *CassandraService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(CassandraService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *WeatherService) DeepCopy() *WeatherService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(WeatherService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AppMeshVirtualService) DeepCopy() *AppMeshVirtualService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AppMeshVirtualService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceType) DeepCopy() *ServiceType {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceType)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceProfile) DeepCopy() *ServiceProfile {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceProfile)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceEntry) DeepCopy() *ServiceEntry {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceEntry)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceParameter) DeepCopy() *ServiceParameter {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceParameter)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ECService) DeepCopy() *ECService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ECService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func AddRefService(self *interface{}) int32 {\n\treturn zero\n}", "func (in *ServicePort) DeepCopy() *ServicePort {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServicePort)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *MongoServiceSpec) DeepCopy() *MongoServiceSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MongoServiceSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DiscoveryServiceCertificate) DeepCopy() *DiscoveryServiceCertificate {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DiscoveryServiceCertificate)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DiscoveryServiceList) DeepCopy() *DiscoveryServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DiscoveryServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ProxyServiceSpec) DeepCopy() *ProxyServiceSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ProxyServiceSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *InnerServicePort) DeepCopy() *InnerServicePort {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(InnerServicePort)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (s Obj_value) NewService() (ServiceInfo, error) {\n\ts.Struct.SetUint16(4, 7)\n\tss, err := NewServiceInfo(s.Struct.Segment())\n\tif err != nil {\n\t\treturn ServiceInfo{}, err\n\t}\n\terr = s.Struct.SetPtr(0, ss.Struct.ToPtr())\n\treturn ss, err\n}", "func (in *AuthenticationService) DeepCopy() *AuthenticationService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AuthenticationService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func AsRef(name string) *duckv1.KReference {\n\treturn &duckv1.KReference{\n\t\tKind: \"Service\",\n\t\tName: name,\n\t\tAPIVersion: \"v1\",\n\t}\n}", "func (in *ConsoleServiceList) DeepCopy() *ConsoleServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ConsoleServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RemoteShuffleService) DeepCopy() *RemoteShuffleService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RemoteShuffleService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DiscoveryServiceSpec) DeepCopy() *DiscoveryServiceSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DiscoveryServiceSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *InnerServiceSpec) DeepCopy() *InnerServiceSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(InnerServiceSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *IstioVirtualService) DeepCopy() *IstioVirtualService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(IstioVirtualService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceStatus) DeepCopy() *ServiceStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceStatus) DeepCopy() *ServiceStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *BcsServiceList) DeepCopy() *BcsServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(BcsServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *MobileSecurityService) DeepCopy() *MobileSecurityService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MobileSecurityService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceBroker) DeepCopy() *ServiceBroker {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceBroker)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *InnerServiceStatus) DeepCopy() *InnerServiceStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(InnerServiceStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ProxyServiceList) DeepCopy() *ProxyServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ProxyServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServiceAccount) DeepCopy() *ServiceAccount {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServiceAccount)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *MongoServiceStatus) DeepCopy() *MongoServiceStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MongoServiceStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DiscoveryServiceCertificateSigner) DeepCopy() *DiscoveryServiceCertificateSigner {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DiscoveryServiceCertificateSigner)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func Service(name, namespace string, so ...ServiceOption) *v1.Service {\n\ts := &v1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tUID: \"cccccccc-cccc-cccc-cccc-cccccccccccc\",\n\t\t},\n\t}\n\tfor _, opt := range so {\n\t\topt(s)\n\t}\n\treturn s\n}", "func (service *BaseService) Clone() *BaseService {\n\tif IsNil(service) {\n\t\treturn nil\n\t}\n\n\t// First, copy the service options struct.\n\tserviceOptions := *service.Options\n\n\t// Next, make a copy the service struct, then use the copy of the service options.\n\t// Note, we'll re-use the \"Client\" instance from the original BaseService instance.\n\tclone := *service\n\tclone.Options = &serviceOptions\n\n\treturn &clone\n}", "func (in *JarService) DeepCopy() *JarService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(JarService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *HelloHttpServiceList) DeepCopy() *HelloHttpServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(HelloHttpServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (context *BaseServiceContext) Service() Service {\n\treturn context.service\n}", "func NewService(client commandapi.Client, config *config.Config, ffSetter feature_flags.Setter) Service {\n\treturn &srv{\n\t\tclient: client,\n\t\tconfig: config,\n\t\tpollDelaySecs: config.CommandChannelIntervalSec,\n\t\tffHandler: handler.NewFFHandler(config, ffSetter),\n\t}\n}", "func (in *ConsolePluginService) DeepCopy() *ConsolePluginService {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ConsolePluginService)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func NewService(connService connection.Servicer, log commonLog.Logger) *Service {\n\treturn &Service{\n\t\tconnService: connService,\n\t\tlog: log,\n\t}\n}", "func (in *BcsServiceSpec) DeepCopy() *BcsServiceSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(BcsServiceSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func Service(name, namespace string, so ...ServiceOption) *v1beta1.Service {\n\ts := &v1beta1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t},\n\t}\n\tfor _, opt := range so {\n\t\topt(s)\n\t}\n\ts.SetDefaults(context.Background())\n\treturn s\n}", "func NewService(c *restapi.RestClient) *Service {\n\ts := Service{}\n\ts.client = c\n\ts.ValidPermissions = ValidPermissionMap.Service\n\ts.SetType = settype.Service.String()\n\ts.apiRead = \"/Subscriptions/GetSubscription\"\n\ts.apiCreate = \"/Subscriptions/AddSubscription\"\n\ts.apiDelete = \"/Subscriptions/DeleteSubscription\"\n\ts.apiUpdate = \"/Subscriptions/UpdateSubscription\"\n\ts.apiPermissions = \"/Subscriptions/SetSubscriptionPermissions\"\n\n\treturn &s\n}", "func (r *ReconcileVirtualMachineService) CreateOrUpdateService(ctx *context.VirtualMachineServiceContext) (*corev1.Service, error) {\n\tvmService := ctx.VMService\n\t// We can use vmService's namespace and name since Service and VirtualMachineService live in the same namespace.\n\tserviceKey := client.ObjectKey{Name: vmService.Name, Namespace: vmService.Namespace}\n\n\tctx.Logger.V(5).Info(\"Reconciling k8s service\")\n\tdefer ctx.Logger.V(5).Info(\"Finished reconciling k8s Service\")\n\n\t// Find the current Service.\n\tcurrentService := &corev1.Service{}\n\tif err := r.Get(ctx, serviceKey, currentService); err != nil {\n\t\tif !errors.IsNotFound(err) {\n\t\t\tctx.Logger.Error(err, \"Failed to get Service\")\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Service does not exist, we will create it.\n\t\tctx.Logger.V(5).Info(\"Service not found. Will attempt to create it\")\n\t\tcurrentService = r.vmServiceToService(ctx)\n\t}\n\n\t// Determine if VirtualMachineService needs any update by comparing current k8s to newService synthesized from\n\t// VirtualMachineService\n\tnewService := currentService.DeepCopy()\n\tsvcFromVmService := r.vmServiceToService(ctx)\n\n\t// Merge labels of the Service with the VirtualMachineService. VirtualMachineService wins in case of conflicts.\n\t// We can't just clobber the labels since other operators (Net Operator) might rely on them.\n\tif newService.Labels == nil {\n\t\tnewService.Labels = vmService.Labels\n\t} else {\n\t\tfor k, v := range vmService.Labels {\n\t\t\tif oldValue, ok := newService.Labels[k]; ok {\n\t\t\t\tctx.Logger.V(5).Info(\"Replacing previous label value on service\",\n\t\t\t\t\t\"key\", k, \"oldValue\", oldValue, \"newValue\", v)\n\t\t\t}\n\t\t\tnewService.Labels[k] = v\n\t\t}\n\t}\n\n\t// Merge annotations of the Service with the VirtualMachineService. VirtualMachineService wins in case of conflicts.\n\tif newService.Annotations == nil {\n\t\tnewService.Annotations = vmService.Annotations\n\t} else {\n\t\tfor k, v := range vmService.Annotations {\n\t\t\tif oldValue, ok := newService.Annotations[k]; ok {\n\t\t\t\tctx.Logger.V(5).Info(\"Replacing previous annotation value on service\",\n\t\t\t\t\t\"key\", k, \"oldValue\", oldValue, \"newValue\", v)\n\t\t\t}\n\t\t\tnewService.Annotations[k] = v\n\t\t}\n\t}\n\n\t// Explicitly remove provider specific annotations\n\tannotationsToBeRemoved, err := r.loadbalancerProvider.GetToBeRemovedServiceAnnotations(ctx, ctx.VMService)\n\tif err != nil {\n\t\tctx.Logger.Error(err, \"Failed to get to be removed loadbalancer annotations for service\")\n\t\treturn nil, err\n\t}\n\tfor k := range annotationsToBeRemoved {\n\t\tctx.Logger.V(5).Info(\"Removing annotation from service\", \"key\", k)\n\t\tdelete(newService.Annotations, k)\n\t}\n\n\t// Explicitly remove provider specific labels\n\tlabelsToBeRemoved, err := r.loadbalancerProvider.GetToBeRemovedServiceLabels(ctx, ctx.VMService)\n\tif err != nil {\n\t\tctx.Logger.Error(err, \"Failed to get to be removed loadbalancer labels for service\")\n\t\treturn nil, err\n\t}\n\tfor k := range labelsToBeRemoved {\n\t\tctx.Logger.V(5).Info(\"Removing label from service\", \"key\", k)\n\t\tdelete(newService.Labels, k)\n\t}\n\n\t// Explicitly remove vm service managed annotations if needed\n\tfor _, k := range []string{utils.AnnotationServiceExternalTrafficPolicyKey, utils.AnnotationServiceHealthCheckNodePortKey} {\n\t\tif _, exist := svcFromVmService.Annotations[k]; !exist {\n\t\t\tif v, exist := newService.Annotations[k]; exist {\n\t\t\t\tctx.Logger.V(5).Info(\"Removing annotation from service\", \"key\", k, \"value\", v)\n\t\t\t}\n\t\t\tdelete(newService.Annotations, k)\n\t\t}\n\t}\n\n\tnewService.Spec.Type = svcFromVmService.Spec.Type\n\tnewService.Spec.ExternalName = svcFromVmService.Spec.ExternalName\n\tnewService.Spec.Ports = svcFromVmService.Spec.Ports\n\tnewService.Spec.LoadBalancerIP = svcFromVmService.Spec.LoadBalancerIP\n\tnewService.Spec.ExternalTrafficPolicy = svcFromVmService.Spec.ExternalTrafficPolicy\n\tif !apiequality.Semantic.DeepEqual(newService.Spec.LoadBalancerSourceRanges, svcFromVmService.Spec.LoadBalancerSourceRanges) {\n\t\tnewService.Spec.LoadBalancerSourceRanges = svcFromVmService.Spec.LoadBalancerSourceRanges\n\t}\n\n\t// Maintain the existing mapping of ServicePort -> NodePort\n\t// as un-setting it will cause the apiserver to allocate a\n\t// new NodePort on an Update.\n\tpopulateNodePorts(currentService, newService)\n\n\t// Add VM operator annotations.\n\tpkg.AddAnnotations(&newService.ObjectMeta)\n\n\t// Create or update or don't update Service.\n\tcreateService := len(currentService.ResourceVersion) == 0\n\tif createService {\n\t\tctx.Logger.Info(\"Creating k8s Service\", \"service\", newService)\n\t\terr = r.Create(ctx, newService)\n\t\tr.recorder.EmitEvent(ctx.VMService, OpCreate, err, false)\n\t} else if !apiequality.Semantic.DeepEqual(currentService, newService) {\n\t\tctx.Logger.Info(\"Updating k8s Service\", \"service\", newService)\n\t\terr = r.Update(ctx, newService)\n\t\tr.recorder.EmitEvent(ctx.VMService, OpUpdate, err, false)\n\t} else {\n\t\tctx.Logger.V(5).Info(\"No need to update current K8s Service. Skipping Update\",\n\t\t\t\"currentService\", currentService, \"vmService\", ctx.VMService)\n\t}\n\n\treturn newService, err\n}", "func (in *AppServiceList) DeepCopy() *AppServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AppServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *GatewayServiceList) DeepCopy() *GatewayServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(GatewayServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PagerdutyServiceList) DeepCopy() *PagerdutyServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PagerdutyServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (ss *serviceSubscriptions) updateService(service *corev1.Service) {\n\tss.Lock()\n\tdefer ss.Unlock()\n\n\tid := ServiceID{\n\t\tNamespace: service.Namespace,\n\t\tName: service.Name,\n\t}\n\n\tif id != ss.service {\n\t\tfor listener, port := range ss.listeners {\n\t\t\tss.endpoints.Unsubscribe(ss.service, port, \"\", listener)\n\t\t\tlistener.NoEndpoints(true) // Clear out previous endpoints.\n\t\t\terr := ss.endpoints.Subscribe(id, port, \"\", listener)\n\t\t\tif err != nil {\n\t\t\t\tss.log.Warnf(\"failed to subscribe to %s: %s\", id, err)\n\t\t\t\tlistener.NoEndpoints(true) // Clear out previous endpoints.\n\t\t\t\tlistener.Add(singletonAddress(ss.clusterIP, port))\n\t\t\t}\n\t\t}\n\t\tss.service = id\n\t\tss.pod = AddressSet{}\n\t}\n}", "func (in *ServiceRef) DeepCopyInto(out *ServiceRef) {\n\t*out = *in\n}", "func (in *Service) DeepCopyInterface() interface{} {\n\treturn in.DeepCopy()\n}" ]
[ "0.79889023", "0.79889023", "0.71423465", "0.71423465", "0.71423465", "0.71423465", "0.71423465", "0.71423465", "0.71423465", "0.68184793", "0.6766675", "0.67632616", "0.6729097", "0.6706522", "0.6657321", "0.66313547", "0.6480278", "0.6434709", "0.64028084", "0.63402987", "0.6339863", "0.6338389", "0.6324956", "0.6323474", "0.6323474", "0.6321833", "0.63139194", "0.62218386", "0.62195", "0.62154865", "0.6186897", "0.61745685", "0.6165597", "0.6157374", "0.6093171", "0.6067023", "0.60598594", "0.60157925", "0.6012679", "0.6012215", "0.6012215", "0.60030425", "0.60030425", "0.59757954", "0.5961714", "0.5934801", "0.59271765", "0.5924777", "0.5907679", "0.589197", "0.58885497", "0.587056", "0.5869601", "0.5869319", "0.58465683", "0.5782751", "0.57646453", "0.57565653", "0.57400525", "0.57389855", "0.5729175", "0.57264245", "0.5715677", "0.5677262", "0.5673239", "0.5654425", "0.56489843", "0.56416243", "0.5624859", "0.562476", "0.5624707", "0.5616524", "0.5586234", "0.5586234", "0.5578704", "0.5574712", "0.55620396", "0.5556517", "0.55270714", "0.55257463", "0.5506853", "0.5480353", "0.5477384", "0.54772156", "0.54696035", "0.5448278", "0.544766", "0.53854334", "0.53730905", "0.5349944", "0.53459597", "0.5342329", "0.53374803", "0.5330958", "0.5327653", "0.5297237", "0.5296562", "0.5292961", "0.5291404", "0.5283641" ]
0.8665822
0
Projects lists all the projects that belong to the token holder.
func (c Client) Projects() ([]Project, error) { u := mustParseURL(c.baseURL) u.Path += "projects" projects := make([]Project, 0) // if there's more projects than returned by default by the API, links array will // be provided. The object that has the 'rel' field with the value of 'next' will // also contain the 'href' with the complete link to the next page. for u != nil { resp, err := c.request(http.MethodGet, u, nil) if err != nil { return nil, fmt.Errorf("fetching files failed: %s", err.Error()) } defer resp.Close() var r struct { apiOKResponseTemplate Projects []Project `json:"items"` } if err := json.NewDecoder(resp).Decode(&r); err != nil { return nil, fmt.Errorf("unmarshalling response failed: %s", err.Error()) } projects = append(projects, r.Projects...) u = nil for _, link := range r.Links { if link.Rel == "next" { u = mustParseURL(link.Href) } } } return projects, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pg *MongoDb) ListProjects(ctx context.Context, filter string, pageSize int, pageToken string) ([]*prpb.Project, string, error) {\n\t//id := decryptInt64(pageToken, pg.PaginationKey, 0)\n\t//TODO\n\treturn nil, \"\", nil\n}", "func (k *Keystone) ListProjectsAPI(c echo.Context) error {\n\tclusterID := c.Request().Header.Get(xClusterIDKey)\n\tif ke := getKeystoneEndpoints(clusterID, k.endpointStore); len(ke) > 0 {\n\t\treturn k.proxyRequest(c)\n\t}\n\t_, err := k.validateToken(c.Request())\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = k.setAssignment(clusterID)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.JSON(http.StatusOK, &asfkeystone.ProjectListResponse{\n\t\tProjects: k.Assignment.ListProjects(),\n\t})\n}", "func (k *Keystone) ListAuthProjectsAPI(c echo.Context) error {\n\tclusterID := c.Request().Header.Get(xClusterIDKey)\n\tif ke := getKeystoneEndpoints(clusterID, k.endpointStore); len(ke) > 0 {\n\t\treturn k.proxyRequest(c)\n\t}\n\n\ttoken, err := k.validateToken(c.Request())\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfigEndpoint, err := k.setAssignment(clusterID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tuserProjects := []*keystone.Project{}\n\tuser := token.User\n\tprojects := k.Assignment.ListProjects()\n\tif configEndpoint == \"\" {\n\t\tfor _, project := range projects {\n\t\t\tfor _, role := range user.Roles {\n\t\t\t\tif role.Project.Name == project.Name {\n\t\t\t\t\tuserProjects = append(userProjects, role.Project)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tuserProjects = append(userProjects, projects...)\n\t}\n\tprojectsResponse := &asfkeystone.ProjectListResponse{\n\t\tProjects: userProjects,\n\t}\n\treturn c.JSON(http.StatusOK, projectsResponse)\n}", "func ProjectList(c *gin.Context) error {\n\tuserID, err := GetIDParam(c, userIDParam)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toption := &model.ProjectQueryOption{\n\t\tUserID: userID,\n\t}\n\n\tif limit := c.Query(\"limit\"); limit != \"\" {\n\t\tif i, err := strconv.Atoi(limit); err == nil {\n\t\t\toption.Limit = i\n\t\t}\n\t}\n\n\tif offset := c.Query(\"offset\"); offset != \"\" {\n\t\tif i, err := strconv.Atoi(offset); err == nil {\n\t\t\toption.Offset = i\n\t\t}\n\t}\n\n\tif order := c.Query(\"order\"); order != \"\" {\n\t\toption.Order = order\n\t} else {\n\t\toption.Order = \"-created_at\"\n\t}\n\n\tif err := CheckUserPermission(c, *userID); err == nil {\n\t\toption.Private = true\n\t}\n\n\tlist, err := model.GetProjectList(option)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn common.APIResponse(c, http.StatusOK, list)\n}", "func (k *Keystone) ListProjectsAPI(c echo.Context) error {\n\tclusterID := c.Request().Header.Get(xClusterIDKey)\n\tif ke := getKeystoneEndpoints(clusterID, k.endpointStore); len(ke) > 0 {\n\t\treturn k.proxyRequest(c, ke)\n\t}\n\n\ttoken, err := k.validateToken(c.Request())\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfigEndpoint, err := k.setAssignment(clusterID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tuserProjects := []*keystone.Project{}\n\tuser := token.User\n\tprojects := k.Assignment.ListProjects()\n\tif configEndpoint == \"\" {\n\t\tfor _, project := range projects {\n\t\t\tfor _, role := range user.Roles {\n\t\t\t\tif role.Project.Name == project.Name {\n\t\t\t\t\tuserProjects = append(userProjects, role.Project)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tuserProjects = append(userProjects, projects...)\n\t}\n\tprojectsResponse := &ProjectListResponse{\n\t\tProjects: userProjects,\n\t}\n\treturn c.JSON(http.StatusOK, projectsResponse)\n}", "func (p *ProjectProvider) List(options *provider.ProjectListOptions) ([]*kubermaticapiv1.Project, error) {\n\tif options == nil {\n\t\toptions = &provider.ProjectListOptions{}\n\t}\n\tprojects := &kubermaticapiv1.ProjectList{}\n\tif err := p.clientPrivileged.List(context.Background(), projects); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar ret []*kubermaticapiv1.Project\n\tfor _, project := range projects.Items {\n\t\tif len(options.ProjectName) > 0 && project.Spec.Name != options.ProjectName {\n\t\t\tcontinue\n\t\t}\n\t\tif len(options.OwnerUID) > 0 {\n\t\t\towners := project.GetOwnerReferences()\n\t\t\tfor _, owner := range owners {\n\t\t\t\tif owner.UID == options.OwnerUID {\n\t\t\t\t\tret = append(ret, project.DeepCopy())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tret = append(ret, project.DeepCopy())\n\t}\n\n\t// Filter out restricted labels\n\tfor i, project := range ret {\n\t\tproject.Labels = label.FilterLabels(label.ClusterResourceType, project.Labels)\n\t\tret[i] = project\n\t}\n\n\treturn ret, nil\n}", "func ProjectListAll(w http.ResponseWriter, r *http.Request) {\n\n\t// Init output\n\toutput := []byte(\"\")\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\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\n\t// Get Results Object\n\n\tres, err := projects.Find(\"\", \"\", refStr)\n\n\tif err != nil && err.Error() != \"not found\" {\n\t\terr := APIErrQueryDatastore()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := res.ExportJSON()\n\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\toutput = []byte(resJSON)\n\trespondOK(w, output)\n\n}", "func GetProjects() []m.Project {\n body, err := authenticatedGet(\"projects\")\n if err != nil {\n panic(err.Error())\n } else {\n var responseData projectResponse\n err = json.Unmarshal(body, &responseData)\n if err != nil {\n panic(err.Error())\n }\n\n return responseData.Data\n }\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 (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 (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 ListProjects() error {\n\tclient, err := NewPacketClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprojects, _, err := client.Projects.List()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te := MarshallAndPrint(projects)\n\treturn e\n}", "func ListProjects(config *Config) error {\n\tgitlab := gogitlab.NewGitlab(config.Host, config.ApiPath, config.Token)\n\tprojects, err := gitlab.AllProjects()\n\tif err != nil {\n\t\treturn Mask(err)\n\t}\n\tfor _, p := range projects {\n\t\tif p.Archived {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", p.Name)\n\t}\n\treturn nil\n}", "func (c *Client) Projects(page int, per_page int) ([]*Project, error) {\n\n\turl, opaque := c.ResourceUrl(projectsUrl, nil, QMap{\n\t\t\"page\": strconv.Itoa(page),\n\t\t\"per_page\": strconv.Itoa(per_page),\n\t})\n\n\tvar projects []*Project\n\n\tcontents, err := c.Do(\"GET\", url, opaque, nil)\n\tif err == nil {\n\t\terr = json.Unmarshal(contents, &projects)\n\t}\n\n\treturn projects, err\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 (self *CassandraMetaStore) findAllProjects() ([]*meta.Project, error) {\n\titr := self.cassandraService.Client.Query(\"select name, oids from projects;\").Iter()\n\tvar oids []string\n\tvar name string\n\tproject_list := []*meta.Project{}\n\tfor itr.Scan(&name, &oids) {\n\t\tproject_list = append(project_list, &meta.Project{Name: name, Oids: oids})\n\t}\n\n\tif err := itr.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(project_list) == 0 {\n\t\treturn nil, meta.ErrProjectNotFound\n\t}\n\treturn project_list, 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 (cli *bkCli) projectList(quietList bool) error {\n\n\tt := time.Now()\n\n\tprojects, err := cli.listProjects()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif quietList {\n\t\tfor _, proj := range projects {\n\t\t\tfmt.Printf(\"%-36s\\n\", *proj.ID)\n\t\t}\n\t\treturn nil // we are done\n\t}\n\n\ttb := table.New(projectColumns)\n\tvals := make(map[string]interface{})\n\n\tfor _, proj := range projects {\n\t\tif proj.FeaturedBuild != nil {\n\t\t\tfb := proj.FeaturedBuild\n\t\t\tvals = utils.ToMap(projectColumns, []interface{}{*proj.ID, *proj.Name, *fb.Number, toString(fb.Branch), toString(fb.Message), toString(fb.State), valString(fb.FinishedAt)})\n\t\t} else {\n\t\t\tvals = utils.ToMap(projectColumns, []interface{}{*proj.ID, *proj.Name, 0, \"\", \"\", \"\", \"\"})\n\t\t}\n\t\ttb.AddRow(vals)\n\t}\n\ttb.Markdown = true\n\ttb.Print()\n\n\tfmt.Printf(\"\\nTime taken: %s\\n\", time.Now().Sub(t))\n\n\treturn err\n}", "func Projects() map[string]Project {\n\t// todo don't expose map here\n\treturn projects\n}", "func ProjectList(quietList bool) error {\n\tcli, err := newBkCli()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn cli.projectList(quietList)\n}", "func (c *ClientImpl) ListProject(ctx context.Context, hcpHostURL string) ([]hcpModels.Tenant, error) {\n\tspan, _ := opentracing.StartSpanFromContext(ctx, \"List HCP Projects\")\n\tdefer span.Finish()\n\n\tsession, err := c.getSession(ctx, hcpHostURL, hcpUserName, hcpPassword)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstatus = Failure\n\tmonitor := metrics.StartExternalCall(externalSvcName, \"List Projects from HCP\")\n\tdefer func() { monitor.RecordWithStatus(status) }()\n\n\tresp, err := mlopsHttp.ExecuteHTTPRequest(\n\t\tctx,\n\t\tc.client,\n\t\thcpHostURL+projectPathV1,\n\t\thttp.MethodGet,\n\t\tmap[string]string{sessionHeader: session},\n\t\tbytes.NewReader(nil),\n\t)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"while fetching projects from MLOps controller platform.\")\n\t}\n\n\tstatus = Success\n\n\terr = c.deleteSession(ctx, hcpHostURL, session)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar tenants hcpModels.ListTenants\n\t_, parseRespErr := common.ParseResponse(resp, &tenants)\n\tif parseRespErr != nil {\n\t\tlog.Errorf(\"Failed to fetch projects from HCP: %v\", parseRespErr)\n\t\treturn nil, errors.Wrapf(parseRespErr, \"Failed to fetch projects from HCP\")\n\t}\n\n\t// filter only ML projects\n\tvar mlProjects []hcpModels.Tenant\n\tfor _, tenant := range tenants.Embedded.Tenants {\n\t\tif tenant.Features.MlProject {\n\t\t\tmlProjects = append(mlProjects, tenant)\n\t\t}\n\t}\n\treturn mlProjects, nil\n}", "func (p *ProjectHandler) ListProjects(ctx context.Context,\n\treq *proto.ListProjectsRequest, resp *proto.ListProjectsResponse) error {\n\tla := project.NewListAction(p.model)\n\tprojects, e := la.Do(ctx, req)\n\tif e != nil {\n\t\treturn e\n\t}\n\tauthUser, err := middleware.GetUserFromContext(ctx)\n\tif err == nil && authUser.Username != \"\" {\n\t\t// with username\n\t\t// 获取 project id, 用以获取对应的权限\n\t\tids := getProjectIDs(projects)\n\t\tperms, err := auth.ProjectIamClient.GetMultiProjectMultiActionPermission(\n\t\t\tauthUser.Username, ids,\n\t\t\t[]string{auth.ProjectCreate, auth.ProjectView, auth.ProjectEdit, auth.ProjectDelete},\n\t\t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// 处理返回\n\t\tsetListPermsResp(resp, projects, perms)\n\t} else {\n\t\t// without username\n\t\tsetListPermsResp(resp, projects, nil)\n\t}\n\tif err := projutil.PatchBusinessName(resp.Data.Results); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func getSnykProjects(token string, org string) []string {\n\tclient, err := snyk.NewClient(snyk.WithToken(token))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// List all projects for the authenticated user.\n\tprojects, err := client.OrganizationProjects(context.TODO(), org)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Generate a slice containing all the full project names for an org.\n\tvar s []string\n\tfor _, project := range projects {\n\t\t// Project names contain manifest files after a colon; only grab the project name.\n\t\ts = append(s, strings.Split(project.Name, \":\")[0])\n\t}\n\t// In case there were multiple manifests for a project, there are now multiple items duplicated in\n\t// our list. The deduplicate() function removes these.\n\treturn deduplicate(s)\n}", "func ProjectList(opts gitlab.ListProjectsOptions, n int) ([]*gitlab.Project, error) {\n\tlist, resp, err := lab.Projects.ListProjects(&opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.CurrentPage == resp.TotalPages {\n\t\treturn list, nil\n\t}\n\topts.Page = resp.NextPage\n\tfor len(list) < n || n == -1 {\n\t\tif n != -1 {\n\t\t\topts.PerPage = n - len(list)\n\t\t}\n\t\tprojects, resp, err := lab.Projects.ListProjects(&opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topts.Page = resp.NextPage\n\t\tlist = append(list, projects...)\n\t\tif resp.CurrentPage == resp.TotalPages {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn list, nil\n}", "func GetAllProjects(w http.ResponseWriter, r *http.Request) {\n\tu := mw.GetUser(r.Context())\n\tif u == nil {\n\t\tw.WriteHeader(403)\n\t\tw.Write(apiError(\"you must be logged in to view all projects\"))\n\t\treturn\n\t}\n\n\tprojects, err := Store.Projects().GetAll()\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\tw.Write(apiError(err.Error()))\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tsendJSON(w, projects)\n}", "func (d *Driver) ProjectList() (*ProjectListResponse, error) {\n\tresponse := &ProjectListResponse{}\n\tlistProjects := project.NewListProjectsParams()\n\tresp, err := d.project.ListProjects(listProjects, d.auth)\n\tif err != nil {\n\t\treturn response, err\n\t}\n\tresponse.Project = resp.Payload\n\treturn response, 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 (repos *TestRepositories) ListProjects(ctx context.Context, owner string, repo string, opts *github.ProjectListOptions) ([]*github.Project, *github.Response, error) {\n\n\tvar resultProjects = make([]*github.Project, 3)\n\n\tnames := []string{\"Project 1\", \"Project 2\", \"Project 3\"}\n\tbodies := []string{\"This is a project\", \"This is a project\", \"This is a project\"}\n\n\tfor i, v := range []int{1, 2, 3} {\n\t\tresultProjects[i] = &github.Project{\n\t\t\tNumber: &v,\n\t\t\tName: &names[i],\n\t\t\tBody: &bodies[i],\n\t\t}\n\t}\n\n\treturn resultProjects, prepareGitHubAPIResponse(), nil\n\n}", "func (c *Client) ListProject() (projectNames []string, err error) {\n\th := map[string]string{\n\t\t\"x-log-bodyrawsize\": \"0\",\n\t}\n\n\turi := \"/\"\n\tproj := convert(c, \"\")\n\n\ttype Project struct {\n\t\tProjectName string `json:\"projectName\"`\n\t}\n\n\ttype Body struct {\n\t\tProjects []Project `json:\"projects\"`\n\t}\n\n\tr, err := request(proj, \"GET\", uri, h, nil)\n\tif err != nil {\n\t\treturn nil, NewClientError(err)\n\t}\n\n\tdefer r.Body.Close()\n\tbuf, _ := ioutil.ReadAll(r.Body)\n\tif r.StatusCode != http.StatusOK {\n\t\terr := new(Error)\n\t\tjson.Unmarshal(buf, err)\n\t\treturn nil, err\n\t}\n\n\tbody := &Body{}\n\terr = json.Unmarshal(buf, body)\n\tfor _, project := range body.Projects {\n\t\tprojectNames = append(projectNames, project.ProjectName)\n\t}\n\treturn projectNames, err\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 (s *ProjectsService) ListProjects(opt *ProjectOptions) (*map[string]ProjectInfo, *Response, error) {\n\tu := \"projects/\"\n\n\tu, err := addOptions(u, opt)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tv := new(map[string]ProjectInfo)\n\tresp, err := s.client.Call(\"GET\", u, nil, v)\n\treturn v, resp, err\n}", "func Projects(ctx context.Context) (map[string]*configpb.ProjectConfig, error) {\n\tval, err := projectCacheSlot.Fetch(ctx, func(any) (val any, exp time.Duration, err error) {\n\t\tvar pc map[string]*configpb.ProjectConfig\n\t\tif pc, err = fetchProjects(ctx); err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\t\treturn pc, time.Minute, nil\n\t})\n\tswitch {\n\tcase err == caching.ErrNoProcessCache:\n\t\t// A fallback useful in unit tests that may not have the process cache\n\t\t// available. Production environments usually have the cache installed\n\t\t// by the framework code that initializes the root context.\n\t\treturn fetchProjects(ctx)\n\tcase err != nil:\n\t\treturn nil, err\n\tdefault:\n\t\tpc := val.(map[string]*configpb.ProjectConfig)\n\t\treturn pc, nil\n\t}\n}", "func All() ([]Project, error) {\n\tnames, err := workdir.ProjectNames()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprojects := []Project{}\n\tnow := time.Now()\n\tfor _, name := range names {\n\t\tp, err := FromName(name)\n\t\tif err != nil {\n\t\t\tcontinue // should not happen\n\t\t}\n\t\tp.Lock = locks.Check(name, now)\n\t\tprojects = append(projects, *p)\n\t}\n\treturn projects, nil\n}", "func GetProjects(w http.ResponseWriter, r *http.Request, auth string) []Project {\n\tvar projects []Project\n\tprojectFileName := auth + globals.PROJIDFILE\n\t//First see if project already exist\n\tstatus, filepro := caching.ShouldFileCache(projectFileName, globals.PROJIDDIR)\n\tdefer filepro.Close()\n\tif status == globals.Error || status == globals.DirFail {\n\t\thttp.Error(w, \"Failed to create a file\", http.StatusInternalServerError)\n\t\treturn nil\n\t}\n\tif status == globals.Exist {\n\t\t//The file exist\n\t\t//We read from file\n\t\terr := caching.ReadFile(filepro, &projects)\n\t\tif err != nil {\n\t\t\terrmsg := \"The Failed Reading from file with error\" + err.Error()\n\t\t\thttp.Error(w, errmsg, http.StatusInternalServerError)\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\t//Else we need to query to get it\n\t\tfor i := 0; i < globals.MAXPAGE; i++ {\n\t\t\tvar subProj []Project\n\t\t\tquery := globals.GITAPI + globals.PROJQ + globals.PAGEQ + strconv.Itoa(i+1)\n\t\t\terr := apiGetCall(w, query, auth, &subProj)\n\t\t\tif err != nil {\n\t\t\t\t//The API call has failed\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t//When it's empty we no longer need to do calls\n\t\t\tif len(subProj) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tprojects = append(projects, subProj...)\n\t\t}\n\t\tcaching.CacheStruct(filepro, projects)\n\n\t}\n\treturn projects\n}", "func TestProjectsList(t *testing.T) {\n\n\tviper.Set(\"token\", token)\n\n\tprojects, err := projects.GetProjects()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif len(projects) < 1 {\n\t\tt.Error(\"no projects\")\n\t} else {\n\t\tvar ok bool\n\t\tfor _, p := range projects {\n\t\t\tif p.Name == projectTest {\n\t\t\t\tok = true\n\t\t\t}\n\t\t}\n\t\tif !ok {\n\t\t\tt.Error(\"there is no \", projectTest)\n\t\t}\n\t}\n}", "func (o ShareSettingsResponseOutput) Projects() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ShareSettingsResponse) []string { return v.Projects }).(pulumi.StringArrayOutput)\n}", "func (a *DefaultApiService) Projects(ctx context.Context) ([]Project, *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 \tsuccessPayload []Project\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/projects\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json; charset=utf-8\", }\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\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarQueryParams.Add(\"circle-token\", key)\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn successPayload, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\tdefer localVarHttpResponse.Body.Close()\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tbodyBytes, _ := ioutil.ReadAll(localVarHttpResponse.Body)\n\t\treturn successPayload, localVarHttpResponse, reportError(\"Status: %v, Body: %s\", localVarHttpResponse.Status, bodyBytes)\n\t}\n\n\tif err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\n\n\treturn successPayload, localVarHttpResponse, err\n}", "func (a *Client) ListProjects(params *ListProjectsParams) (*ListProjectsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListProjectsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"listProjects\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/projects\",\n\t\tProducesMediaTypes: []string{\"application/release-manager.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/release-manager.v1+json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &ListProjectsReader{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\treturn result.(*ListProjectsOK), nil\n\n}", "func ListProject(projectID string) error {\n\tclient, err := NewPacketClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp, _, err := client.Projects.Get(projectID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te := MarshallAndPrint(p)\n\treturn e\n}", "func GetProjects(_ *router.WebRequest) *model.Container {\n\tlist, err := factory.GetGitClient().ListProjects()\n\tif err != nil {\n\t\treturn model.ErrorResponse(model.MessageItem{\n\t\t\tCode: \"list-error\",\n\t\t\tMessage: err.Error(),\n\t\t}, 500)\n\t}\n\tdata := make([]interface{}, 0)\n\tfor _, item := range list {\n\t\tdata = append(data, item)\n\t}\n\treturn model.ListResponse(data)\n}", "func (s *service) filterClaProjects(ctx context.Context, projects []*v2ProjectServiceModels.ProjectOutput) []*v2ProjectServiceModels.ProjectOutput { //nolint\n\tresults := make([]*v2ProjectServiceModels.ProjectOutput, 0)\n\tprChan := make(chan *v2ProjectServiceModels.ProjectOutput)\n\tfor _, v := range projects {\n\t\tgo func(projectOutput *v2ProjectServiceModels.ProjectOutput) {\n\t\t\tproject, err := s.projectRepo.GetCLAGroupsByExternalID(ctx, &v1ProjectParams.GetProjectsByExternalIDParams{\n\t\t\t\tProjectSFID: projectOutput.ID,\n\t\t\t\tPageSize: aws.Int64(1),\n\t\t\t}, DontLoadRepoDetails)\n\t\t\tif err != nil {\n\t\t\t\tlog.Warnf(\"Unable to fetch project details for project with external id %s. error = %s\", projectOutput.ID, err)\n\t\t\t\tprChan <- nil\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif project.ResultCount == 0 {\n\t\t\t\tprChan <- nil\n\t\t\t\treturn\n\t\t\t}\n\t\t\tprChan <- projectOutput\n\t\t}(v)\n\t}\n\tfor range projects {\n\t\tproject := <-prChan\n\t\tif project != nil {\n\t\t\tresults = append(results, project)\n\t\t}\n\t}\n\treturn results\n}", "func (m *ModelProject) ListProjects(ctx context.Context, cond *operator.Condition, pagination *page.Pagination) (\n\t[]Project, int64, error) {\n\tprojectList := make([]Project, 0)\n\tfinder := m.db.Table(m.tableName).Find(cond)\n\t// total 表示根据条件得到的总量\n\ttotal, err := finder.Count(ctx)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tif len(pagination.Sort) != 0 {\n\t\tfinder = finder.WithSort(dbtable.MapInt2MapIf(pagination.Sort))\n\t}\n\tif pagination.Offset != 0 {\n\t\tfinder = finder.WithStart(pagination.Offset * pagination.Limit)\n\t}\n\tif pagination.Limit == 0 {\n\t\tfinder = finder.WithLimit(page.DefaultProjectLimit)\n\t} else {\n\t\tfinder = finder.WithLimit(pagination.Limit)\n\t}\n\n\t// 设置拉取全量数据\n\tif pagination.All {\n\t\tfinder = finder.WithLimit(0).WithStart(0)\n\t}\n\n\t// 获取数据\n\tif err := finder.All(ctx, &projectList); err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\treturn projectList, total, nil\n}", "func (t *TeamsService) ListProjects(teamID int) (*TeamProjectAssocListResponse, *simpleresty.Response, error) {\n\tvar result *TeamProjectAssocListResponse\n\turlStr := t.client.http.RequestURL(\"/team/%d/projects\", teamID)\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 (o ShareSettingsOutput) Projects() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ShareSettings) []string { return v.Projects }).(pulumi.StringArrayOutput)\n}", "func (s *ProjectsService) All(ctx context.Context) ([]*Project, error) {\n\tp := []*Project{}\n\topts := &PagingOptions{Limit: perPageLimit}\n\terr := allPages(opts, func() (*Paging, error) {\n\t\tlist, err := s.List(ctx, opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tp = append(p, list.GetProjects()...)\n\t\treturn &list.Paging, nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn p, nil\n}", "func (self *CassandraMetaStore) Projects() ([]*meta.Project, error) {\n\treturn self.findAllProjects()\n}", "func (c *Session) VisibleProjects() []types.ID {\n\tvar projectIds []types.ID\n\tfor _, v := range c.Perms {\n\t\tpairs := strings.Split(v, \"_\")\n\t\tif len(pairs) == 2 {\n\t\t\tid, err := types.ParseID(pairs[1])\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tprojectIds = append(projectIds, id)\n\t\t}\n\t}\n\tif projectIds == nil {\n\t\treturn []types.ID{}\n\t}\n\treturn projectIds\n}", "func (w Workspace) Projects(\n\tctx context.Context,\n\tafter *string,\n\tbefore *string,\n\tfirst *int,\n\tlast *int,\n) (ProjectConnection, error) {\n\treturn PaginateProjectIDSliceContext(ctx, w.ProjectIDs, after, before, first, last)\n}", "func (s *service) filterClaProjects(projects []*v2ProjectServiceModels.ProjectOutput) []*v2ProjectServiceModels.ProjectOutput { //nolint\n\tresults := make([]*v2ProjectServiceModels.ProjectOutput, 0)\n\tprChan := make(chan *v2ProjectServiceModels.ProjectOutput)\n\tfor _, v := range projects {\n\t\tgo func(projectOutput *v2ProjectServiceModels.ProjectOutput) {\n\t\t\tproject, err := s.projectRepo.GetCLAGroupsByExternalID(&v1ProjectParams.GetProjectsByExternalIDParams{\n\t\t\t\tProjectSFID: projectOutput.ID,\n\t\t\t\tPageSize: aws.Int64(1),\n\t\t\t}, DontLoadRepoDetails)\n\t\t\tif err != nil {\n\t\t\t\tlog.Warnf(\"Unable to fetch project details for project with external id %s. error = %s\", projectOutput.ID, err)\n\t\t\t\tprChan <- nil\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif project.ResultCount == 0 {\n\t\t\t\tprChan <- nil\n\t\t\t\treturn\n\t\t\t}\n\t\t\tprChan <- projectOutput\n\t\t}(v)\n\t}\n\tfor range projects {\n\t\tproject := <-prChan\n\t\tif project != nil {\n\t\t\tresults = append(results, project)\n\t\t}\n\t}\n\treturn results\n}", "func (o ShareSettingsResponsePtrOutput) Projects() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *ShareSettingsResponse) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Projects\n\t}).(pulumi.StringArrayOutput)\n}", "func (w *ServerInterfaceWrapper) Projects(ctx echo.Context) error {\n\tvar err error\n\n\t// HasSecurity is set\n\n\tctx.Set(\"OpenId.Scopes\", []string{\"exitus/project.read\"})\n\n\t// Parameter object where we will unmarshal all parameters from the context\n\tvar params ProjectsParams\n\t// ------------- Optional query parameter \"q\" -------------\n\tif paramValue := ctx.QueryParam(\"q\"); paramValue != \"\" {\n\t}\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"q\", ctx.QueryParams(), &params.Q)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter q: %s\", err))\n\t}\n\n\t// ------------- Optional query parameter \"offset\" -------------\n\tif paramValue := ctx.QueryParam(\"offset\"); paramValue != \"\" {\n\t}\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"offset\", ctx.QueryParams(), &params.Offset)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter offset: %s\", err))\n\t}\n\n\t// ------------- Optional query parameter \"limit\" -------------\n\tif paramValue := ctx.QueryParam(\"limit\"); paramValue != \"\" {\n\t}\n\n\terr = runtime.BindQueryParameter(\"form\", true, false, \"limit\", ctx.QueryParams(), &params.Limit)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter limit: %s\", err))\n\t}\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.Projects(ctx, params)\n\treturn err\n}", "func Projects() []*gitlab.Project {\n\tpath := gitlab.WithBaseURL(strings.Join([]string{Config.BaseURL, \"api\", Config.Version}, \"/\"))\n\tclient, err := gitlab.NewClient(Config.Token, path)\n\tif err != nil {\n\t\tErr(err)\n\t}\n\tprePage := 100\n\ttotalPages := 2\n\tvar allProjects []*gitlab.Project\n\n\tfor curPage := 1; curPage <= totalPages; curPage++ {\n\t\tlistOpt := gitlab.ListOptions{PerPage: prePage, Page: curPage}\n\t\tprojectsOpt := gitlab.ListProjectsOptions{Simple: t, ListOptions: listOpt}\n\t\tprojects, res, err := client.Projects.ListProjects(&projectsOpt)\n\t\tif err != nil {\n\t\t\tErr(err)\n\t\t}\n\t\tallProjects = append(allProjects, projects...)\n\t\ttotalPages = res.TotalPages\n\t}\n\treturn allProjects\n}", "func (p *Provider) GetProjects() []string {\n\treturn p.opts.projects\n}", "func ProjectNames(c context.Context, a cfgclient.Authority) ([]types.ProjectName, error) {\n\tconfigPath := ProjectConfigPath(c)\n\n\tvar metas []*config.Meta\n\tif err := cfgclient.Projects(c, a, configPath, nil, &metas); err != nil {\n\t\tlog.WithError(err).Errorf(c, \"Failed to load project configs.\")\n\t\treturn nil, err\n\t}\n\n\t// Iterate through our Metas and extract the project names.\n\tprojects := make([]types.ProjectName, 0, len(metas))\n\tfor _, meta := range metas {\n\t\tif projectName := meta.ConfigSet.Project(); projectName != \"\" {\n\t\t\tprojects = append(projects, types.ProjectName(projectName))\n\t\t}\n\t}\n\tsort.Sort(projectNameSlice(projects))\n\treturn projects, nil\n}", "func (o ShareSettingsPtrOutput) Projects() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *ShareSettings) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Projects\n\t}).(pulumi.StringArrayOutput)\n}", "func (g *Client) AllProjects() ([]*Project, error) {\n\tvar per_page = 100\n\tvar projects []*Project\n\n\tfor i := 1; true; i++ {\n\t\tcontents, err := g.Projects(i, per_page)\n\t\tif err != nil {\n\t\t\treturn projects, err\n\t\t}\n\n\t\tfor _, value := range contents {\n\t\t\tprojects = append(projects, value)\n\t\t}\n\n\t\tif len(projects) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tif len(projects)/i < per_page {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn projects, nil\n}", "func GetListProj(c *gin.Context) {\r\n\t//var gp []model.GrupProject\r\n\t//var gp1 model.GrupProject\r\n\tvar gp3 []model.Project\r\n\r\n\t/*if err := c.Bind(&u); err != nil {\r\n\t\tutils.WrapAPIError(c, err.Error(), http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\t//log.Println(\"LOGIN\") */\r\n\r\n\t//di save >> save\r\n\r\n\taID := c.Param(\"username\")\r\n\r\n\t//model.DB.Where(\"username = ?\", aID).Preload(\"GrupProject\", \"username\", aID).Find(&gp3)\r\n\r\n\tmodel.DB.Preload(\"GrupProject\", \"username\", aID).Find(&gp3)\r\n\t//model.DB.Raw(\"Select * from projct group by username order by trending desc limit 3\").Scan(&trending_membership)\r\n\r\n\t//model.DB.Where(\"grup_projects.username = ?\", aID).Preload(\"GrupProject\", \"username\", aID).Find(&gp3)\r\n\r\n\t//model.DB.Model(&gp1).Where(\"username=?\", aID).Scan(&gp)\r\n\t//model.DB.Model(&gp).Where(\"id_project=?\", gp.id_project).Scan(&gp3)\r\n\r\n\tutils.WrapAPIData(c, map[string]interface{}{\r\n\t\t\"Anggota\": gp3,\r\n\t}, http.StatusOK, \"success\")\r\n}", "func (s *StubTodoStore) GetAllProjects() []model.Project {\n\tvar projects []model.Project\n\n\tfor key := range s.Projects {\n\t\tprojects = append(projects, model.Project{Name: key})\n\t}\n\n\treturn projects\n}", "func GetProjects() ([]*github.Repository) {\n\n\tctx := context.Background()\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: os.Getenv(\"GITHUB_PAT\")},\n\t)\n\ttc := oauth2.NewClient(ctx, ts)\n\n\tclient := github.NewClient(tc)\n\n\t// list all repositories for the authenticated user\n\trepos, _, _ := client.Repositories.List(ctx, \"\", nil)\n\n\t// for _, repo := range repos {\n \n // fmt.Println(*repo.HTMLURL)\n // }\n\n\treturn repos\n}", "func (g *Gitlab) ListProjects(page int) (projects []*gitlab.Project, err error) {\n\n\topt := &gitlab.ListProjectsOptions{}\n\topt.ListOptions.Page = page\n\topt.ListOptions.PerPage = _defaultPerPage\n\n\tif projects, _, err = g.client.Projects.ListProjects(opt); err != nil {\n\t\terr = errors.Wrapf(err, \"ListProjects err(%+v)\", err)\n\t\treturn\n\t}\n\treturn\n}", "func (d *Dao) HubProjects(c context.Context, projectName string) (projects []*model.HubProject, err error) {\n\tvar req *http.Request\n\n\turl := d.c.BiliHub.Host + _projectURI + \"?page=1&page_size=15&name=\" + projectName\n\tif req, err = d.newRequest(http.MethodGet, url, nil); err != nil {\n\t\treturn\n\t}\n\n\treq.SetBasicAuth(d.c.BiliHub.Username, d.c.BiliHub.Password)\n\n\tif err = d.httpClient.Do(c, req, &projects); err != nil {\n\t\tlog.Error(\"d.HubProjects url(%s) err(%v)\", url, err)\n\t\terr = ecode.MerlinHubRequestErr\n\t\treturn\n\t}\n\n\treturn\n}", "func UpdateProjects(values interface{}, token string) ([]*Project, error) {\n\t// declarations\n\tprojects := make([]*Project, len(makeSlice(values)))\n\tvar uid int64\n\tif user, err := GetUser(token); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tuid = user.Id\n\t}\n\tidentifier := make(map[int64]bool)\n\n\t// update or insert projects\n\tfor i, value := range makeSlice(values) {\n\t\tentry := makeStringMap(value)\n\t\tgh_id := makeInt64(entry[\"id\"])\n\t\tidentifier[gh_id] = true\n\t\tproject := Project{\n\t\t\tGH_Id: gh_id,\n\t\t\tName: makeString(entry[\"full_name\"]),\n\t\t\tClone_url: makeString(entry[\"html_url\"]),\n\t\t}\n\n\t\tif existsProject(project.GH_Id) {\n\t\t\tif err := updateProject(&project, uid); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\tif err := createProject(&project, uid); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tprojects[i] = &project\n\t}\n\n\t// delete projects that no longer exist\n\trows, err := db.Query(\"SELECT gh_id, pid, uid FROM projects\"+\n\t\t\" INNER JOIN members ON projects.id=members.pid WHERE uid=$1\", uid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer rows.Close()\n\tvar gh_id, pid int64\n\tfor rows.Next() {\n\t\tif err := rows.Scan(&gh_id, &pid, &uid); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif _, ok := identifier[gh_id]; !ok {\n\t\t\tvar dummy string\n\t\t\tdb.QueryRow(\"DELETE FROM members WHERE uid=$1 AND pid=$2\", uid,\n\t\t\t\tpid).Scan(&dummy)\n\t\t\tvar count int64 = -1\n\t\t\tif err := db.QueryRow(\"SELECT count(*) FROM members WHERE pid=$1\",\n\t\t\t\tpid).Scan(&count); err == nil && count == 0 {\n\t\t\t\tdb.QueryRow(\"DELETE FROM projects WHERE id=$1\", pid).\n\t\t\t\t\tScan(&dummy)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn projects, nil\n}", "func (g *projectGateway) ListProjectsAction(params project.ListProjectsParams) middleware.Responder {\n\tlistRsp, err := g.projectClient.List(context.TODO(), &proto.ListRequest{})\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn project.NewCreateProjectInternalServerError()\n\t}\n\n\tvar projects = []*models.Project{}\n\tfor _, listResp := range listRsp.Projects {\n\t\tp := &models.Project{\n\t\t\tUUID: strfmt.UUID(listResp.Uuid),\n\t\t\tName: listResp.Name,\n\t\t\tDescription: listResp.Description,\n\t\t}\n\t\tprojects = append(projects, p)\n\t}\n\n\treturn project.NewListProjectsOK().WithPayload(projects)\n}", "func (s *ProjectsService) ListProjects() ([]*Project, *Response, error) {\n\treq, err := s.client.NewRequest(\"GET\", \"projects\", nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tvar p []*Project\n\tresp, err := s.client.Do(req, &p)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn p, resp, err\n}", "func (ps *ProjectStore) GetAll() ([]models.Project, error) {\n\tvar projects []models.Project\n\n\trows, err := ps.db.Query(`SELECT p.id, p.created_date, p.name, \n\t\t\t\t\t\t\t\t p.key, p.repo, p.homepage,\n\t\t\t\t\t\t\t\t p.icon_url, \n\t\t\t\t\t\t\t \t json_build_object('id', lead.id, 'username', lead.username, 'email', lead.email, 'full_name', lead.full_name, 'profile_picture', lead.profile_picture) AS lead\n\t\t\t\t\t\t\t FROM projects AS p\n\t\t\t\t\t\t\t JOIN users AS lead ON p.lead_id = lead.id;`)\n\tif err != nil {\n\t\treturn projects, handlePqErr(err)\n\t}\n\n\tfor rows.Next() {\n\t\tvar p models.Project\n\n\t\terr = intoProject(rows, &p)\n\t\tif err != nil {\n\t\t\treturn projects, handlePqErr(err)\n\t\t}\n\n\t\tprojects = append(projects, p)\n\t}\n\n\treturn projects, nil\n}", "func (g *GH) ListProjects() []*github.Project {\n\tctx := context.Background()\n\tprojectOptions := &github.ProjectListOptions{State: \"open\"}\n\tprojects, rsp, err := g.c.Organizations.ListProjects(ctx, g.org, projectOptions)\n\tif err != nil {\n\t\tlog.Println(\"Unable to List Projects in Org\", rsp, g.org, err)\n\t}\n\treturn projects\n}", "func GetProjects(w http.ResponseWriter, r *http.Request) {\n\t// Get IDs for projects\n\t// Grab those projects.\n\t// Return those cool projects and response\n}", "func (c *Client) ListProjects(listall bool) ([]models.Project, error) {\n\treq, err := c.newRequest(\"GET\", projectPath, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif listall {\n\t\tparams := req.URL.Query()\n\t\tparams.Add(\"displayAll\", \"true\")\n\t\treq.URL.RawQuery = params.Encode()\n\t}\n\n\tresult := make([]models.Project, 0)\n\n\tresp, err := c.do(req, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// StatusCodes 401 and 409 mean empty response and should be treated as such\n\tif resp.StatusCode == 401 || resp.StatusCode == 409 {\n\t\treturn nil, nil\n\t}\n\n\tif resp.StatusCode >= 299 {\n\t\treturn nil, errors.New(\"Got non-2xx return code: \" + strconv.Itoa(resp.StatusCode))\n\t}\n\n\treturn result, nil\n}", "func (u *Projects) Index(c echo.Context) error {\n\tuc, ok := c.(*middlewares.LoginContext)\n\tif !ok {\n\t\terr := errors.New(\"Can not cast context\")\n\t\tlogging.SharedInstance().ControllerWithStacktrace(err, c).Error(err)\n\t\treturn err\n\t}\n\n\tcurrentUser := uc.CurrentUser\n\tprojects, err := account.UserProjects(currentUser)\n\tif err != nil {\n\t\tlogging.SharedInstance().ControllerWithStacktrace(err, c).Error(err)\n\t\treturn err\n\t}\n\n\tvar projectEntities []*project.Project\n\tfor _, p := range projects {\n\t\tprojectEntities = append(projectEntities, p)\n\t}\n\tjsonProjects, err := views.ParseProjectsJSON(projectEntities)\n\tif err != nil {\n\t\tlogging.SharedInstance().ControllerWithStacktrace(err, c).Error(err)\n\t\treturn err\n\t}\n\n\treturn c.JSON(http.StatusOK, jsonProjects)\n}", "func GetProjects(e Executor, userID string) (*ProjectSimpleList, error) {\n\treq, _ := http.NewRequest(\"GET\", RexBaseURL+apiProjectByOwner+userID, nil)\n\n\tresp, err := e.Execute(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tio.Copy(ioutil.Discard, resp.Body)\n\t}()\n\n\tvar projects ProjectSimpleList\n\terr = json.NewDecoder(resp.Body).Decode(&projects)\n\n\t// set ID for convenience\n\tfor i, p := range projects.Embedded.Projects {\n\t\tre, _ := regexp.Compile(\"/projects/(.*)\")\n\t\tvalues := re.FindStringSubmatch(p.Links.Self.Href)\n\t\tif len(values) > 0 {\n\t\t\tprojects.Embedded.Projects[i].ID = values[1]\n\t\t}\n\t}\n\treturn &projects, err\n}", "func (s Step) Projects(\n\tctx context.Context,\n\tafter *string,\n\tbefore *string,\n\tfirst *int,\n\tlast *int,\n) (ProjectConnection, error) {\n\treturn PaginateProjectIDSliceContext(ctx, s.ProjectIDs, after, before, first, last)\n}", "func AllProjects() []Project {\n\tvar p []Project\n\to := Setting.SortBy + \" \" + Setting.SortOrder\n\tDB.Order(o).Find(&p)\n\treturn p\n}", "func GetProjectList(tasks []api.Task) []api.Task {\n\tvar result []api.Task\n\tfor _, task := range tasks {\n\t\tif task.IsProject() {\n\t\t\tresult = append(result, task)\n\t\t}\n\t}\n\treturn result\n}", "func (c *CodeShipProvider) GetProjectsList() ([]string, error) {\n\tres, _, err := c.API.ListProjects(c.Context)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.Projects = res.Projects\n\n\tvar strs []string\n\tfor index, project := range res.Projects {\n\t\tstrs = append(strs, fmt.Sprintf(\"[%d] %s\", index, project.Name))\n\t}\n\n\treturn strs, 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 (f *FakeProjectProvider) List(options *provider.ProjectListOptions) ([]*kubermaticapiv1.Project, error) {\n\treturn nil, errors.New(\"not implemented\")\n}", "func ListProjectHandler(c *gin.Context) {\r\n\tres, err := ListProjectsCore()\r\n\tif err != nil {\r\n\t\tc.JSON(500, err)\r\n\t} else {\r\n\t\tc.JSON(200, res)\r\n\t}\r\n}", "func CommandShowProjects(conf Config, ctx, query Query) error {\n\tif len(query.IDs) > 0 || query.HasOperators() {\n\t\treturn errors.New(\"query/context not supported for show-projects\")\n\t}\n\n\tts, err := LoadTaskSet(conf.Repo, conf.IDsFile, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\tts.DisplayProjects()\n\treturn nil\n}", "func (pc *MockProjectConnector) FindProjects(key string, limit int, sortDir int, isAuthenticated bool) ([]model.ProjectRef, error) {\n\tprojects := []model.ProjectRef{}\n\tif sortDir > 0 {\n\t\tfor i := 0; i < len(pc.CachedProjects); i++ {\n\t\t\tp := pc.CachedProjects[i]\n\t\t\tvisible := isAuthenticated || (!isAuthenticated && !p.Private)\n\t\t\tif p.Identifier >= key && visible {\n\t\t\t\tprojects = append(projects, p)\n\t\t\t\tif len(projects) == limit {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor i := len(pc.CachedProjects) - 1; i >= 0; i-- {\n\t\t\tp := pc.CachedProjects[i]\n\t\t\tvisible := isAuthenticated || (!isAuthenticated && !p.Private)\n\t\t\tif p.Identifier < key && visible {\n\t\t\t\tprojects = append(projects, p)\n\t\t\t\tif len(projects) == limit {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn projects, nil\n}", "func GetTrendingProjects(db *sql.DB) []Project {\n\tprojects := []Project{}\n\n\tsqlQuery := `SELECT * FROM projects ORDER BY followers desc LIMIT 20;`\n\trows, err := db.Query(sqlQuery)\n\n\tdefer rows.Close()\n\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\n\tfor rows.Next() {\n\t\tproject := Project{}\n\t\trows.Scan(&project.Name, pq.Array(&project.ProjectImgs),\n\t\t\t&project.DefaultImageIndex, pq.Array(&project.Tags),\n\t\t\t&project.Description, &project.Followers)\n\n\t\tprojects = append(projects, project)\n\t}\n\n\treturn projects\n}", "func (h *Handler) GetProjects(w http.ResponseWriter, r *http.Request) {\n\tvar err error\n\tvar projects []data.Project\n\n\tif projects, err = h.TodoGo.GetProjects(r.Context()); err != nil {\n\t\tresponse.Error(w, err)\n\t\treturn\n\t}\n\tresponse.Success(200, w, projects)\n}", "func ProjectListOne(w http.ResponseWriter, r *http.Request) {\n\n\t// Init output\n\toutput := []byte(\"\")\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\t// Grab url path variables\n\turlVars := mux.Vars(r)\n\turlProject := urlVars[\"project\"]\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\n\t// Get Results Object\n\tresults, err := projects.Find(\"\", urlProject, refStr)\n\n\tif err != nil {\n\n\t\tif err.Error() == \"not found\" {\n\t\t\terr := APIErrorNotFound(\"ProjectUUID\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t\terr := APIErrQueryDatastore()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tres := results.One()\n\tresJSON, err := res.ExportJSON()\n\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\toutput = []byte(resJSON)\n\trespondOK(w, output)\n\n}", "func ProjectsGET(c *gin.Context) {\n\tuser := c.MustGet(\"user\").(*User)\n\tif err := user.FetchProjects(); err != nil {\n\t\tc.JSON(http.StatusInternalServerError, nil)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, user.Projects)\n}", "func (g *GlobalConfig) GetProjectNameList() []string {\n\tpl := []string{}\n\n\tfor _, p := range g.Projects {\n\t\tif p.Path != \"\" {\n\t\t\tpl = append(pl, p.Name)\n\t\t}\n\t}\n\n\treturn pl\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 (dp *DummyProject) GetAll(owner ...string) []*project.Project {\n\tpr := []*project.Project{}\n\n\tfor _, p := range projects {\n\t\tfor _, ow := range owner {\n\t\t\tif p.Owner == ow {\n\t\t\t\tpr = append(pr, p)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif a, ok := acl[p.Name]; ok {\n\t\t\t\tfor _, u := range a {\n\t\t\t\t\tif ow == u {\n\t\t\t\t\t\tpr = append(pr, p)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn pr\n}", "func All() []model.Project {\n projects := []model.Project{}\n\n // Find Projects and eager-load ProjectConfig.\n app.DB.\n Preload(\"ProjectConfig\").\n Order(\"nsp desc\").\n Find(&projects)\n\n return projects\n}", "func getProjects(r *http.Request) ([]byte, error) {\n\tm := bson.M{}\n\tif pid, e := convert.Id(r.FormValue(\"id\")); e == nil {\n\t\tm[db.ID] = pid\n\t}\n\tp, e := db.Projects(m, nil)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\treturn util.JSON(map[string]interface{}{\"projects\": p})\n}", "func GetRenewProjects(ctx iris.Context) {\n\tvar resp renewProjectsResp\n\tdb := ctx.Values().Get(\"db\").(*sql.DB)\n\tif err := resp.RenewProjects.GetAll(db); err != nil {\n\t\tctx.StatusCode(http.StatusInternalServerError)\n\t\tctx.JSON(jsonError{\"Liste des projets de renouvellement, requête RU : \" + err.Error()})\n\t\treturn\n\t}\n\tif err := resp.Cities.GetAll(db); err != nil {\n\t\tctx.StatusCode(http.StatusInternalServerError)\n\t\tctx.JSON(jsonError{\"Liste des projets de renouvellement, requête villes : \" + err.Error()})\n\t\treturn\n\t}\n\tif err := resp.RPEventTypes.GetAll(db); err != nil {\n\t\tctx.StatusCode(http.StatusInternalServerError)\n\t\tctx.JSON(jsonError{\"Liste des projets de renouvellement, requête événements types : \" + err.Error()})\n\t\treturn\n\t}\n\tif err := resp.Commissions.GetAll(db); err != nil {\n\t\tctx.StatusCode(http.StatusInternalServerError)\n\t\tctx.JSON(jsonError{\"Liste des projets de renouvellement, requête commissions : \" + err.Error()})\n\t\treturn\n\t}\n\tif err := resp.BudgetActions.GetAll(db); err != nil {\n\t\tctx.StatusCode(http.StatusInternalServerError)\n\t\tctx.JSON(jsonError{\"Liste des projets de renouvellement, requête actions budgétaires : \" + err.Error()})\n\t\treturn\n\t}\n\tyear := (int64)(time.Now().Year())\n\tif err := resp.FcPreProgs.GetAllOfKind(year, models.KindRenewProject, db); err != nil {\n\t\tctx.StatusCode(http.StatusInternalServerError)\n\t\tctx.JSON(jsonError{\"Liste des projets de renouvellement, requête préprogrammation : \" + err.Error()})\n\t\treturn\n\t}\n\tif err := resp.RPMultiAnnualReports.GetAll(db); err != nil {\n\t\tctx.StatusCode(http.StatusInternalServerError)\n\t\tctx.JSON(jsonError{\"Liste des projets de renouvellement, requête rapport pluriannuel : \" + err.Error()})\n\t\treturn\n\t}\n\tctx.StatusCode(http.StatusOK)\n\tctx.JSON(resp)\n}", "func (impl *ProjectAPIClient) List(ctx context.Context, token *api.Token) (reply []application.Definition, err error) {\n\terr = client.CallHTTP(ctx, impl.BaseURL, \"ProjectAPI.List\", atomic.AddUint64(&impl.sequence, 1), &reply, token)\n\treturn\n}", "func (s projectService) GetAll() ([]*Project, error) {\n\titems := []*Project{}\n\tpath, err := getAllPath(s)\n\tif err != nil {\n\t\treturn items, err\n\t}\n\n\t_, err = apiGet(s.getClient(), &items, path)\n\treturn items, err\n}", "func (v *ProjectClient) GetAllProjects() ([]Project, error) {\n\tkey := ProjectKey{\n\t\tProjectName: \"\",\n\t}\n\n\tvar res []Project\n\tvalues, err := db.DBconn.Find(v.storeName, key, v.tagMeta)\n\tif err != nil {\n\n\t}\n\n\tfor _, value := range values {\n\t\tp := Project{}\n\t\terr = db.DBconn.Unmarshal(value, &p)\n\t\tif err != nil {\n\t\t\treturn []Project{}, pkgerrors.Wrap(err, \"Unmarshaling Project\")\n\t\t}\n\t\tres = append(res, p)\n\t}\n\treturn res, nil\n}", "func GetProjects() (projects []m.Project, err error) {\n\tfmt.Println(\"GetProjects()\")\n\tbody, err := authenticatedGet(\"projects\")\n\tif err != nil {\n\t\tfmt.Printf(\"Got an error loading projects: %s\", err.Error())\n\t\treturn\n\t}\n\n\tvar responseData projectResponse\n\terr = json.Unmarshal(body, &responseData)\n\tif err != nil {\n\t\tfmt.Printf(\"Got an error parsing unmarshalling projects response: %s\\n\", err.Error())\n\t\treturn\n\t}\n\n\tprojects = responseData.Data\n\n\treturn\n}", "func (gp *GetProjects) Execute(fed FederatorInterface) error {\n\tvar wg sync.WaitGroup\n\tvar projects hubapi.ProjectList\n\n\thubs := fed.GetHubs()\n\tlog.Debugf(\"GetProjects federator hubs: %+v\", hubs)\n\thubCount := len(hubs)\n\tprojectsListCh := make(chan *hubapi.ProjectList, hubCount)\n\n\twg.Add(hubCount)\n\tfor hubURL, client := range hubs {\n\t\tgo func(client *hub.Client, url string, id string, rt GetProjectsRequestType) {\n\t\t\tdefer wg.Done()\n\t\t\tif rt == ProjectsGetAll {\n\t\t\t\tlog.Debugf(\"querying all projects\")\n\t\t\t\tlist, err := client.ListAllProjects()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warningf(\"failed to get projects from %s: %v\", url, err)\n\t\t\t\t\tprojectsListCh <- nil\n\t\t\t\t} else {\n\t\t\t\t\tprojectsListCh <- list\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlink := hubapi.ResourceLink{Href: fmt.Sprintf(\"https://%s/api/projects/%s\", url, id)}\n\t\t\t\tlog.Debugf(\"querying project %s\", link.Href)\n\t\t\t\tcl, err := client.GetProject(link)\n\t\t\t\tlog.Debugf(\"response to project query from %s: %+v\", link.Href, cl)\n\t\t\t\tif err != nil {\n\t\t\t\t\tprojectsListCh <- nil\n\t\t\t\t} else {\n\t\t\t\t\tlist := &hubapi.ProjectList{\n\t\t\t\t\t\tTotalCount: 1,\n\t\t\t\t\t\tItems: []hubapi.Project{*cl},\n\t\t\t\t\t}\n\t\t\t\t\tprojectsListCh <- list\n\t\t\t\t}\n\t\t\t}\n\t\t}(client, hubURL, gp.projectID, gp.requestType)\n\t}\n\n\twg.Wait()\n\tfor i := 0; i < hubCount; i++ {\n\t\tresponse := <-projectsListCh\n\t\tif response != nil {\n\t\t\tlog.Debugf(\"a hub responded with project list: %+v\", response)\n\t\t\tgp.mergeProjectList(&projects, response)\n\t\t}\n\t}\n\n\tgetResponse := GetProjectsResponse{\n\t\trequestType: gp.requestType,\n\t\tprojectID: gp.projectID,\n\t\tallProjects: &projects,\n\t}\n\n\tgp.responseCh <- &getResponse\n\treturn nil\n}", "func ExampleDeviceFarm_ListProjects_shared00() {\n\tsvc := devicefarm.New(session.New())\n\tinput := &devicefarm.ListProjectsInput{\n\t\tArn: aws.String(\"arn:aws:devicefarm:us-west-2:123456789101:project:7ad300ed-8183-41a7-bf94-12345EXAMPLE\"),\n\t\tNextToken: aws.String(\"RW5DdDJkMWYwZjM2MzM2VHVpOHJIUXlDUXlhc2QzRGViYnc9SEXAMPLE\"),\n\t}\n\n\tresult, err := svc.ListProjects(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase devicefarm.ErrCodeArgumentException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeArgumentException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeNotFoundException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeNotFoundException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeLimitExceededException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeLimitExceededException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeServiceAccountException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeServiceAccountException, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tfmt.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\t// Print the error, cast err to awserr.Error to get the Code and\n\t\t\t// Message from an error.\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Println(result)\n}", "func (project *ProjectV1) ListProjectsWithContext(ctx context.Context, listProjectsOptions *ListProjectsOptions) (result *ProjectCollection, response *core.DetailedResponse, err error) {\n\terr = core.ValidateStruct(listProjectsOptions, \"listProjectsOptions\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbuilder := core.NewRequestBuilder(core.GET)\n\tbuilder = builder.WithContext(ctx)\n\tbuilder.EnableGzipCompression = project.GetEnableGzipCompression()\n\t_, err = builder.ResolveRequestURL(project.Service.Options.URL, `/v1/projects`, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor headerName, headerValue := range listProjectsOptions.Headers {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\n\tsdkHeaders := common.GetSdkHeaders(\"project\", \"V1\", \"ListProjects\")\n\tfor headerName, headerValue := range sdkHeaders {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\tbuilder.AddHeader(\"Accept\", \"application/json\")\n\n\tif listProjectsOptions.Start != nil {\n\t\tbuilder.AddQuery(\"start\", fmt.Sprint(*listProjectsOptions.Start))\n\t}\n\tif listProjectsOptions.Limit != nil {\n\t\tbuilder.AddQuery(\"limit\", fmt.Sprint(*listProjectsOptions.Limit))\n\t}\n\n\trequest, err := builder.Build()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar rawResponse map[string]json.RawMessage\n\tresponse, err = project.Service.Request(request, &rawResponse)\n\tif err != nil {\n\t\treturn\n\t}\n\tif rawResponse != nil {\n\t\terr = core.UnmarshalModel(rawResponse, \"\", &result, UnmarshalProjectCollection)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tresponse.Result = result\n\t}\n\n\treturn\n}", "func ListProjects() ([]model.Project, error) {\n\tprojects, err := model.ListProjects()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(projects) == 0 {\n\t\treturn nil, errors.New(\"no project found\")\n\t}\n\treturn projects, nil\n}", "func (c *Client) ListProject(ctx context.Context, p *ListProjectPayload) (res *StationsFull, err error) {\n\tvar ires interface{}\n\tires, err = c.ListProjectEndpoint(ctx, p)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ires.(*StationsFull), nil\n}", "func LoadAllProjects() ([]ProjectPrint, error) {\n\trow, err := DB.Query(\"SELECT id,name,created_by FROM projects\")\n\tvar projects []ProjectPrint\n\tcheckErr(err)\n\tfor row.Next() {\n\t\tvar u ProjectPrint\n\t\trow.Scan(&u.ID, &u.Name, &u.CreatedBy)\n\t\tu.Issues = GetAllIssuesByID(u.ID)\n\t\tu.Owner = GetUserByID(u.CreatedBy)\n\t\tprojects = append(projects, u)\n\t}\n\treturn projects, nil\n}", "func (a *App) IndexProject(w http.ResponseWriter, req *http.Request) {\n\tdb := context.Get(req, \"db\").(*mgo.Database)\n\tif db == nil {\n\t\ta.R.JSON(w, http.StatusInternalServerError, &Response{Status: \"Error\", Message: \"Unable to access database\"})\n\t\treturn\n\t}\n\n\tuser := context.Get(req, \"user\").(*User)\n\tif user == nil {\n\t\ta.R.JSON(w, http.StatusInternalServerError, &Response{Status: \"Error\", Message: \"Unable to retrieve user\"})\n\t\treturn\n\t}\n\n\t// Ensure query is restricted to only projects to which the user is authorized\n\tor := &bson.M{\n\t\t\"$or\": []bson.M{\n\t\t\tbson.M{\"owner\": user.ID},\n\t\t\tbson.M{\"contributors\": user.ID},\n\t\t},\n\t}\n\tvar projects []lair.Project\n\tif err := db.C(a.C.Projects).Find(or).All(&projects); err != nil {\n\t\ta.R.JSON(w, http.StatusInternalServerError, &Response{Status: \"Error\", Message: \"Unable to retrieve project index\"})\n\t\treturn\n\t}\n\ta.R.JSON(w, http.StatusOK, projects)\n}" ]
[ "0.71771556", "0.68300486", "0.68204504", "0.68188494", "0.6786697", "0.6783694", "0.6747027", "0.67415625", "0.6694138", "0.66898185", "0.66296756", "0.6558482", "0.65004283", "0.6477567", "0.6470259", "0.6456625", "0.6454959", "0.64408636", "0.64160526", "0.6415494", "0.63931304", "0.63926154", "0.63831455", "0.6374607", "0.6369818", "0.6360176", "0.6328334", "0.6328054", "0.6307073", "0.6277999", "0.6260688", "0.625987", "0.62595004", "0.6235455", "0.62031424", "0.61992323", "0.61946696", "0.6183935", "0.61659527", "0.61599207", "0.6156383", "0.615486", "0.6150225", "0.61493516", "0.6144187", "0.61426955", "0.61410254", "0.6136098", "0.609651", "0.60939", "0.60661435", "0.60553324", "0.60523814", "0.6048075", "0.604388", "0.6042951", "0.6038988", "0.6037452", "0.6037152", "0.602341", "0.6022257", "0.60174716", "0.6014485", "0.60117024", "0.6003091", "0.6000035", "0.59786844", "0.5964393", "0.5951454", "0.5948885", "0.59440154", "0.5931567", "0.5918291", "0.59057856", "0.59013", "0.58990407", "0.58890593", "0.588718", "0.5884254", "0.58697253", "0.584732", "0.5841389", "0.58403605", "0.5824523", "0.5824405", "0.5816391", "0.5811181", "0.58025277", "0.57900035", "0.5777647", "0.577597", "0.5774102", "0.5769484", "0.57651985", "0.57609576", "0.5749204", "0.573068", "0.57274103", "0.57173413", "0.57134104" ]
0.5867073
80
Upload allows users to upload photos, they may be marked as public or private
func Upload(w http.ResponseWriter, r *http.Request) { // Get uploaded file r.ParseMultipartForm(32 << 20) file, _, err := r.FormFile("uploadFile") if err != nil { w.WriteHeader(http.StatusBadRequest) fmt.Println(err) return } defer file.Close() // Get isPublic attribute IsPublicFromValue := r.FormValue("IsPublic") if IsPublicFromValue == "" { w.WriteHeader(http.StatusBadRequest) return } IsPublic, err := strconv.ParseBool(IsPublicFromValue) if err != nil { w.WriteHeader(http.StatusBadRequest) return } // Identify who the user is username := r.Context().Value("username") if username == nil { w.WriteHeader(http.StatusInternalServerError) return } // Get user bucket id bucketID, err := GetUserGUID(username.(string)) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } // Generate a unique ID to identify the photo object photoID := uuid.New().String() // Register photo in photos table photo := Photo{ ID: photoID, IsPublic: IsPublic, UserID: *bucketID, } DB.Create(&photo) // Retrieve user's bucket bkt := Client.Bucket(getBucketForPhoto(photo)) // Verify existence of bucket // Only run in production as Google Cloud Storage emulator for local development does not support metadata retrieval // TODO: Need more robust diaster recovery if !IsDebug { _, err = Client.Bucket(getBucketForPhoto(photo)).Attrs(r.Context()) if err == storage.ErrBucketNotExist { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte("Bucket does not exist: " + err.Error())) return } } // Upload photo to bucket obj := bkt.Object(photoID) objWriter := obj.NewWriter(r.Context()) if _, err := io.Copy(objWriter, file); err != nil { w.WriteHeader(http.StatusInternalServerError) return } if err := objWriter.Close(); err != nil { w.WriteHeader(http.StatusInternalServerError) return } w.Write([]byte(photoID)) w.WriteHeader(http.StatusOK) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func IMAGE_PostUploadForm(res http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\tif validPerm, permErr := HasPermission(res, req, image_Make_Permission); !validPerm {\n\t\t// User Must be at least Writer.\n\t\tfmt.Fprint(res, `{\"result\":\"failure\",\"reason\":\"Invalid Authorization: `+permErr.Error()+`\",\"code\":418}`)\n\t\treturn\n\t}\n\t// ACTION: Give the user an internal permissions key?\n\n\tServeTemplateWithParams(res, \"simpleImageUploader.html\", req.FormValue(\"oid\"))\n}", "func UploadFile(res http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\treq.ParseMultipartForm(1024 * 1024 * 5) // Max size 5242880 bytes. (i.e) 5 MB\n\n\tf, h, e := req.FormFile(\"photo\")\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\tdefer f.Close()\n\n\tmediaPath := photos.GetMediaPath()\n\ttoken := Session.Get(req)\n\tj := &jwt.Jwt{}\n\tj = j.GetUserInfo(token)\n\n\tfilenameArr := strings.Split(h.Filename, \".\")\n\tfilename := filenameArr[0] + \"-\" + fmt.Sprintf(\"%v\", time.Now().Unix()) + \".\" + filenameArr[1]\n\n\tuserPath := fp.Join(mediaPath, j.Username)\n\tfilePath := fp.Join(mediaPath, j.Username, filename)\n\trelativePath := photos.GetRelativeMediaPath(j.Username, filename)\n\tphoto := Photo{\n\t\tPath: filePath,\n\t\tRelativePath: relativePath,\n\t\tUserID: j.UID,\n\t\tCaption: req.FormValue(\"caption\"),\n\t}\n\tdb.Get().Create(&photo)\n\n\tphotos.MakeSureThePath(userPath)\n\tfile, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, os.ModePerm)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\n\tio.Copy(file, f)\n\thttp.Redirect(res, req, \"/\", http.StatusSeeOther)\n}", "func handlePhotoUpload(photoUrl, title, thumbnailUrl string, chatID int64, asPhoto bool) {\n\t// Inform the user we are doing some shit\n\tvar stopReportChannel chan struct{}\n\tif asPhoto {\n\t\tstopReportChannel = statusReporter(chatID, \"upload_photo\")\n\t} else {\n\t\tstopReportChannel = statusReporter(chatID, \"upload_document\")\n\t}\n\tdefer close(stopReportChannel)\n\t// Download the gif\n\ttmpFile, err := reddit.DownloadPhoto(photoUrl)\n\tif err != nil {\n\t\tlog.Println(\"Cannot download file\", photoUrl, \":\", err)\n\t\tbot.Send(tgbotapi.NewMessage(chatID, \"Cannot download file.\\nHere is the link to file: \"+photoUrl))\n\t\treturn\n\t}\n\tdefer func() { // Cleanup\n\t\ttmpFile.Close()\n\t\tos.Remove(tmpFile.Name())\n\t}()\n\t// Check filesize\n\tif asPhoto {\n\t\tasPhoto = util.CheckFileSize(tmpFile.Name(), PhotoMaxUploadSize) // send photo as file if it is larger than 10MB\n\t}\n\tif !util.CheckFileSize(tmpFile.Name(), RegularMaxUploadSize) {\n\t\tbot.Send(tgbotapi.NewMessage(chatID, \"This file is too big to upload it on telegram!\\nHere is the link to image: \"+photoUrl))\n\t\treturn\n\t}\n\t// Download thumbnail\n\tvar tmpThumbnailFile *os.File = nil\n\tif !util.CheckFileSize(tmpFile.Name(), NoThumbnailNeededSize) && thumbnailUrl != \"\" {\n\t\ttmpThumbnailFile, err = reddit.DownloadThumbnail(thumbnailUrl)\n\t\tif err == nil {\n\t\t\tdefer func() {\n\t\t\t\ttmpThumbnailFile.Close()\n\t\t\t\tos.Remove(tmpThumbnailFile.Name())\n\t\t\t}()\n\t\t}\n\t}\n\t// Upload\n\tvar msg tgbotapi.Chattable\n\tif asPhoto {\n\t\tphoto := tgbotapi.NewPhoto(chatID, telegramUploadOsFile{tmpFile})\n\t\tphoto.Caption = title\n\t\tif tmpThumbnailFile != nil {\n\t\t\tphoto.Thumb = telegramUploadOsFile{tmpThumbnailFile}\n\t\t}\n\t\tmsg = photo\n\t} else {\n\t\tphoto := tgbotapi.NewDocument(chatID, telegramUploadOsFile{tmpFile})\n\t\tphoto.Caption = title\n\t\tif tmpThumbnailFile != nil {\n\t\t\tphoto.Thumb = telegramUploadOsFile{tmpThumbnailFile}\n\t\t}\n\t\tmsg = photo\n\t}\n\t_, err = bot.Send(msg)\n\tif err != nil {\n\t\tbot.Send(tgbotapi.NewMessage(chatID, \"Cannot upload file.\\nHere is the link to image: \"+photoUrl))\n\t\tlog.Println(\"Cannot upload file:\", err)\n\t\treturn\n\t}\n}", "func UploadingImages(w http.ResponseWriter, r *http.Request) {\n\t// Set CORS\n\tw.Header().Set(utils.ContentType, utils.ApplicationJSON)\n\tw.Header().Set(utils.Cors, utils.CorsWildCard)\n\tw.Header().Set(utils.ArrowHeader, utils.ContentType)\n\tw.Header().Set(utils.ArrowMethods, utils.Methods)\n\tw.Header().Set(utils.Credential, utils.True)\n\t// Get jwt from header.\n\treqToken := r.Header.Get(utils.Authorization)\n\t// Check if jwt is verified.\n\tuserID := utils.VerifyToken(reqToken)\n\tif userID == 0 {\n\t\tresultjson := dto.SimpleResutlJSON{\n\t\t\tStatus: false,\n\t\t\tErrorCode: utils.InvalidToken,\n\t\t}\n\t\t// convert structs to json\n\t\tres, err := json.Marshal(resultjson)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write(res)\n\t\treturn\n\t}\n\t// Get article id from URL query parameter with string type and convert it to int.\n\tatlID := \"article_id\"\n\tatlIDStr := r.URL.Query().Get(atlID)\n\tarticleID, _ := strconv.Atoi(atlIDStr)\n\tvar maxSize int64 = 200000\n\terr := r.ParseMultipartForm(maxSize)\n\tif err != nil {\n\t\tfmt.Fprintln(w, err)\n\t\treturn\n\t}\n\tformdata := r.MultipartForm\n\n\tvar fieldName = \"multiplefiles\"\n\tfiles := formdata.File[fieldName]\n\n\tsession, err := session.NewSession(&aws.Config{\n\t\tRegion: aws.String(os.Getenv(\"REGION\")),\n\t\tCredentials: credentials.NewStaticCredentials(\n\t\t\tos.Getenv(\"ID\"),\n\t\t\tos.Getenv(\"KEY\"),\n\t\t\t\"\"),\n\t})\n\tif err != nil {\n\t\tresultjson := dto.SimpleResutlJSON{\n\t\t\tStatus: false,\n\t\t\tErrorCode: utils.FailedGenerateAWSSession,\n\t\t}\n\t\t// convert structs to json\n\t\tres, err := json.Marshal(resultjson)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write(res)\n\t\treturn\n\t}\n\n\t// Array for image path\n\turlArray := []dto.ImageStruct{}\n\n\tfor i := range files {\n\t\tfile, err := files[i].Open()\n\t\tdefer file.Close()\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(w, err)\n\t\t\treturn\n\t\t}\n\n\t\tfileHead := files[i]\n\t\t// Get file name\n\t\tfileName := fileHead.Filename\n\t\t// Get file extension.\n\t\tfileExtension := filepath.Ext(fileName)\n\t\t// Acceptable extensions\n\t\tvar (\n\t\t\tjpg = \".jpg\"\n\t\t\tjpeg = \".jpeg\"\n\t\t\tpng = \".png\"\n\t\t)\n\t\t// Check extensions\n\t\tif fileExtension != jpeg && fileExtension != jpg && fileExtension != png {\n\t\t\tbreak\n\t\t}\n\t\t// Uploading icon to AWS S3.\n\t\timagePath, uploadError := utils.UploadingToS3(session, file, fileHead)\n\t\tif uploadError != nil {\n\t\t\tresultjson := dto.SimpleResutlJSON{\n\t\t\t\tStatus: false,\n\t\t\t\tErrorCode: utils.FailedUploadImages,\n\t\t\t}\n\t\t\t// convert structs to json\n\t\t\tres, err := json.Marshal(resultjson)\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\tw.Write(res)\n\t\t\treturn\n\t\t}\n\n\t\timageData := dto.ImageStruct{\n\t\t\tImageURL: imagePath,\n\t\t\tUserID: userID,\n\t\t\tArticleID: articleID,\n\t\t}\n\n\t\t// Push generated path to slice\n\t\turlArray = append(urlArray, imageData)\n\t}\n\t// Insert DB\n\tRegisterImages := model.UploadImage(urlArray)\n\n\tif !RegisterImages {\n\t\tresultjson := dto.SimpleResutlJSON{\n\t\t\tStatus: false,\n\t\t\tErrorCode: utils.FailedUploadImages,\n\t\t}\n\t\t// convert structs to json\n\t\tres, err := json.Marshal(resultjson)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write(res)\n\t\treturn\n\t}\n\n\tresultjson := dto.SimpleResutlJSON{\n\t\tStatus: true,\n\t\tErrorCode: utils.SuccessCode,\n\t}\n\t// convert structs to json\n\tres, err := json.Marshal(resultjson)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(res)\n\treturn\n}", "func UploadPhotoUserPath() string {\n\treturn \"/user/media\"\n}", "func UploadHandler(c *gin.Context) {\n\n\terr := c.Request.ParseMultipartForm(1000)\n\tform, err := c.MultipartForm()\n\tif err != nil {\n\t\tc.String(http.StatusBadRequest, fmt.Sprintf(\"get form err: %s\", err.Error()))\n\t\tfmt.Println(\"error getting multipartform\", err)\n\t\tpanic(err)\n\t}\n\n\tif !service.VerifyAPIRequest(c, form.Value[\"token\"]) {\n\t\treturn\n\t}\n\n\tfiles := form.File[\"files\"]\n\tinfoArray := form.Value[\"infoArray\"]\n\n\tfor i, file := range files {\n\t\tfilename := filepath.Base(file.Filename)\n\t\tunixTime, err := strconv.ParseInt(infoArray[i], 10, 64)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\terr = MyStore.CreatePhoto(filename, file, unixTime)\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusUnsupportedMediaType, nil)\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tc.JSON(http.StatusOK, nil)\n}", "func (h *Handler) Upload(source string, destination string) {\n\tlog.Warn(\"generic doesn't support file upload\")\n}", "func UploadFiles(c *gin.Context) {\n\tlocationFull := \"\"\n\tpreviewImage := \"\"\n\tpathName := \"files_\" + c.Request.Header[\"Application-Id\"][0]\n\n\tformFile, _ := c.FormFile(\"file\")\n\n\tfile, _ := formFile.Open()\n\tdefer file.Close()\n\n\tvar copiedFile io.Reader\n\tvar buf bytes.Buffer\n\n\tif isImage(formFile.Header[\"Content-Type\"][0]) {\n\t\tcopiedFile = io.TeeReader(file, &buf)\n\t\tpreview, err := makePreview(copiedFile)\n\n\t\tif err == nil {\n\t\t\tnewFileName, _ := newFileName(pathName, formFile.Header[\"Content-Type\"][0])\n\t\t\tpreviewImage, _ = s3.Upload(preview, newFileName)\n\t\t}\n\t}\n\n\tnewFileName, err := newFileName(pathName, formFile.Header[\"Content-Type\"][0])\n\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\tvar errUpload error\n\tif buf.Len() == 0 {\n\t\tlocationFull, errUpload = s3.Upload(file, newFileName)\n\t} else {\n\t\tr := bytes.NewReader(buf.Bytes())\n\t\tlocationFull, errUpload = s3.Upload(r, newFileName)\n\t}\n\n\tif errUpload != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": errUpload.Error()})\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"result\": map[string]string{\n\t\t\t\"url\": locationFull,\n\t\t\t\"previewUrl\": previewImage,\n\t\t\t\"type\": formFile.Header[\"Content-Type\"][0],\n\t\t}})\n}", "func (ref *Files) Upload(file *File, reader io.ReadSeeker, authOptions ...AuthOption) error {\n\tsize, err := getSeekerSize(reader)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unexpected error when get length of file: %v\", err)\n\t}\n\n\towner, err := file.fetchOwner(ref.c, authOptions...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unexpected error when fetch owner: %v\", err)\n\t}\n\n\tif file.Size == 0 {\n\t\tfile.Size = size\n\t}\n\n\tif reflect.ValueOf(file.Meatadata).IsNil() {\n\t\tfile.Meatadata = make(map[string]interface{})\n\t}\n\tfile.Meatadata[\"size\"] = file.Size\n\tif owner != nil {\n\t\tfile.Meatadata[\"owner\"] = owner.ID\n\t} else {\n\t\tfile.Meatadata[\"owner\"] = \"unknown\"\n\t}\n\n\ttoken, uploadURL, err := file.fetchToken(ref.c, authOptions...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch file.Provider {\n\tcase \"qiniu\":\n\t\tif err := file.uploadQiniu(token, \"https://up.qbox.me/\", reader); err != nil {\n\t\t\tif err := file.fileCallback(false, token, ref.c, authOptions...); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\tcase \"s3\":\n\t\tif err := file.uploadS3(token, uploadURL, reader); err != nil {\n\t\t\tif err := file.fileCallback(false, token, ref.c, authOptions...); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\tcase \"qcloud\":\n\t\tif err := file.uploadCOS(token, uploadURL, reader); err != nil {\n\t\t\tif err := file.fileCallback(false, token, ref.c, authOptions...); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := file.fileCallback(true, token, ref.c, authOptions...); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func ImageUpload(w http.ResponseWriter, r *http.Request) {\n\n\t// add cors support\n\thelpers.SetupResponse(&w, r)\n\tif r.Method == \"OPTIONS\" {\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"content-type\", \"application/json\")\n\n\tif (*r).Method == \"POST\" {\n\n\t\tid_available := false\n\t\tid, _, err := auth.ExtractUserIDEmail(r)\n\n\t\tif err != nil {\n\n\t\t} else {\n\t\t\tid_available = true\n\t\t}\n\n\t\tnew_id, _ := primitive.ObjectIDFromHex(id)\n\t\ttext := r.FormValue(\"text\")\n\t\timage_type := r.FormValue(\"type\")\n\t\tcharacteristics := r.Form[\"characteristics\"]\n\t\tfiles := r.MultipartForm.File[\"image\"]\n\n\t\tif len(text) < 1 {\n\t\t\thttp.Error(w, fmt.Sprintf(`{\"status\":\"error\",\"error\":true,\"msg\":\"%s\"}`, \"Image text must be provided\"), 400)\n\t\t\treturn\n\t\t}\n\n\t\tif len(image_type) < 1 || image_type != \"private\" && image_type != \"public\" {\n\t\t\thttp.Error(w, fmt.Sprintf(`{\"status\":\"error\",\"error\":true,\"msg\":\"%s\"}`, \"Image type must be provided, either private or public\"), 400)\n\t\t\treturn\n\t\t}\n\n\t\tif len(characteristics) < 1 {\n\t\t\thttp.Error(w, fmt.Sprintf(`{\"status\":\"error\",\"error\":true,\"msg\":\"%s\"}`, \"Image characteristics must be provided\"), 400)\n\t\t\treturn\n\t\t}\n\n\t\tif !id_available {\n\t\t\tif image_type != \"public\" {\n\t\t\t\thttp.Error(w, fmt.Sprintf(`{\"status\":\"error\",\"error\":true,\"msg\":\"%s\"}`, \"Image type must be made public or create an account to make it private\"), 400)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tfor _, fileHeader := range files {\n\n\t\t\tif fileHeader.Size > MAX_UPLOAD_SIZE {\n\t\t\t\thttp.Error(w, fmt.Sprintf(\"The uploaded image is too big: %s. Please use an image less than 20MB in size\", fileHeader.Filename), 400)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Open the file\n\t\t\tfile, err := fileHeader.Open()\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tdefer file.Close()\n\n\t\t\tbuff := make([]byte, 512)\n\t\t\t_, err = file.Read(buff)\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfiletype := http.DetectContentType(buff)\n\t\t\tif filetype != \"image/jpeg\" && filetype != \"image/png\" {\n\t\t\t\thttp.Error(w, \"The provided file format is not allowed. Please upload a JPEG or PNG image\", 400)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// create an AWS session which can be\n\t\t\t// reused if we're uploading many files\n\t\t\ts, err := session.NewSession(&aws.Config{\n\t\t\t\tRegion: aws.String(\"eu-west-2\"),\n\t\t\t\tCredentials: credentials.NewStaticCredentials(\n\t\t\t\t\tos.Getenv(\"S3_ACCESS_ID\"), // id\n\t\t\t\t\tos.Getenv(\"S3_SECRET_ID\"), // secret\n\t\t\t\t\t\"\"), // token can be left blank for now\n\t\t\t})\n\n\t\t\tif err != nil {\n\t\t\t\tlogger.Log(err)\n\t\t\t\thttp.Error(w, fmt.Sprintf(`{\"status\":\"error\",\"error\":true,\"msg\":\"%s\"}`, \"error occured while trying to upload\"), 400)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfileName, err := helpers.UploadFileToS3(s, file, fileHeader, \"images/\")\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, fmt.Sprintf(`{\"status\":\"error\",\"error\":true,\"msg\":\"%s\"}`, \"error occured while trying to upload file\"), 400)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar image models.Image\n\n\t\t\tcollection, err := helpers.GetDBCollection(\"images\")\n\n\t\t\tif err != nil {\n\t\t\t\tlogger.Log(err)\n\t\t\t\thttp.Error(w, fmt.Sprintf(`{\"status\":\"error\",\"error\":true,\"msg\":\"%s\"}`, \"couldn't connect to the mongo collection\"), 500)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif id_available {\n\t\t\t\timage.UserID = new_id\n\t\t\t}\n\n\t\t\timage.Image = fileName\n\t\t\timage.Characteristics = characteristics\n\t\t\timage.Text = text\n\t\t\timage.Type = image_type\n\t\t\timage.CreatedAt = time.Now().Format(time.RFC3339)\n\t\t\timage.UpdatedAt = time.Now().Format(time.RFC3339)\n\n\t\t\t_, err = collection.InsertOne(context.TODO(), image)\n\n\t\t\tif err != nil {\n\t\t\t\tlogger.Log(err)\n\t\t\t\thttp.Error(w, fmt.Sprintf(`{\"status\":\"error\",\"msg\":\"error occured while trying to saving image\"}`), 400)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\n\t\tjson.NewEncoder(w).Encode(models.Response{\n\t\t\tStatus: \"success\",\n\t\t\tError: false,\n\t\t\tMsg: \"User image(s) uploaded successfully\",\n\t\t})\n\t\treturn\n\n\t}\n\thttp.Error(w, fmt.Sprintf(`{\"status\":\"error\",\"error\":true,\"msg\":\"%s\"}`, \"method not allowed\"), 400)\n\treturn\n}", "func doUpload(newImages []string) bool {\n\tfmt.Printf(\"Would you like to upload all %d images to your Flickr account? Y or N?\\n\", len(newImages))\n\tanswer := \"\"\n\tfmt.Scanf(\"%s\", &answer)\n\treturn strings.ToLower(strings.TrimSpace(answer)) == \"y\"\n}", "func upload(w http.ResponseWriter, r *http.Request) {\n\tresponse := struct {\n\t\tSuccess bool `json:\"success\"`\n\t\tErrorMsg string `json:\"error,omitempty\"`\n\t\tImage *db.Image `json:\"image,omitempty\"`\n\t}{}\n\n\terr := r.ParseMultipartForm(10 * MB) // Limit file sizes to 10Mb\n\n\tif err != nil {\n\t\tresponse.Success = false\n\t\tresponse.ErrorMsg = ErrorFailedToParseForm\n\t} else {\n\t\tf, mf, err := r.FormFile(\"image\")\n\n\t\tif err != nil {\n\t\t\tresponse.Success = false\n\t\t\tresponse.ErrorMsg = ErrorImageFileNotFound\n\t\t} else {\n\t\t\ttoken := r.Header.Get(\"X-ImgyToken\")\n\n\t\t\tif token == \"\" {\n\t\t\t\tresponse.Success = false\n\t\t\t\tresponse.ErrorMsg = ErrorNoUploadTokenPresent\n\t\t\t} else {\n\t\t\t\tif u := db.GetUserByUpload(token); u != nil {\n\t\t\t\t\tkey := util.GetRandom(8)\n\t\t\t\t\tcontentType := mf.Header.Get(\"Content-Type\")\n\t\t\t\t\text := util.GetExtension(strings.ToLower(contentType))\n\t\t\t\t\tif ext == \"\" {\n\t\t\t\t\t\t// verify extension\n\t\t\t\t\t\tresponse.Success = false\n\t\t\t\t\t\tresponse.ErrorMsg = ErrorUnsupportedFileType\n\t\t\t\t\t} else {\n\t\t\t\t\t\tb, _ := ioutil.ReadAll(f)\n\n\t\t\t\t\t\tres, err := amazonWebServices.Upload(key+\".\"+ext, contentType, b)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tresponse.Success = false\n\t\t\t\t\t\t\tresponse.ErrorMsg = ErrorUploadFailed\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tresponse.Image = &db.Image{\n\t\t\t\t\t\t\t\tImageID: key,\n\t\t\t\t\t\t\t\tUserID: u.UserID,\n\t\t\t\t\t\t\t\tS3Link: res.Location,\n\t\t\t\t\t\t\t\tExtension: ext,\n\t\t\t\t\t\t\t\tImgyLink: conf.OauthURL + \"/\" + key,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tresponse.Success = true\n\n\t\t\t\t\t\t\tresponse.Image.Save()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tresponse.Success = false\n\t\t\t\t\tresponse.ErrorMsg = ErrorInvalidToken\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tjson.NewEncoder(w).Encode(&response)\n\n}", "func (gcs *gcsPhotos) uploadPhotos() []string {\n ext := \".jpg\"\n subDir := \"photos/\"\n testPhotos := []string{ \"0\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\",\"20\",\"21\",\"22\",\"23\",\"24\"}\n\t \n for _, name := range testPhotos {\n ffile := subDir + name + ext\n srcFile, fName, err := gcs.read(ffile)\n if err != nil {\n log.Errorf(gcs.ctx, \"Open / read file error %v\", err)\n return nil\n }\n fName = fName + ext\n gcs.write(fName, srcFile)\n log.Infof(gcs.ctx, \"In File: %s, Out File: %s\\n\", ffile, fName)\n }\n\t return gcs.retrievePhotos()\n}", "func upload(w http.ResponseWriter, r *http.Request) {\n\ttoken, ok := identity.FromContext(r.Context())\n\tif !ok {\n\t\thttp.Error(w, \"Unauthorized\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t_, oka := token.Scopes[\"admin\"]\n\t_, okw := token.Scopes[\"write\"]\n\n\tif !oka || !okw {\n\t\thttp.Error(w, \"Unauthorized\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\treader, err := r.MultipartReader()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tctx := r.Context()\n\tif err := provider.Upload(ctx, reader); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\trender.JSON(w)\n}", "func ImageUploadHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"uploading image\")\n\tauthHeader := r.Header.Get(\"Authorization\")\n\tif authHeader == \"\" {\n\t\tlog.Println(\"token not received\")\n\t}\n\n\t// Parse our multipart form, 10 << 20 specifies a maximum\n\t// upload of 10 MB files.\n\tr.ParseMultipartForm(10 << 20)\n\t// FormFile returns the first file for the given key\n\t// it also returns the FileHeader so we can get the Filename,\n\t// the Header and the size of the file\n\tfile, _, err := r.FormFile(FileID)\n\tif err != nil {\n\t\tfmt.Println(\"error Retrieving the File\")\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tdefer file.Close()\n\n\t// Create a temporary file within our server directory that follows\n\t// a particular naming pattern\n\n\tusername := r.Header.Get(auth.UsernameKey)\n\ttempFile, err := ioutil.TempFile(\"image-server\", fmt.Sprintf(\"%s_*.png\", username))\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"%s\\n\", err.Error())\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tdefer tempFile.Close()\n\n\t// read all of the contents of our uploaded file into a\n\t// byte array\n\tfileBytes, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tfmt.Fprintf(w, \"%s\\n\", err.Error())\n\t\treturn\n\t}\n\t// write this byte array to our temporary file\n\t_, err = tempFile.Write(fileBytes)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tfmt.Fprintf(w, \"%s\\n\", err.Error())\n\t\treturn\n\t}\n\t// save the link to users profile\n\tuserKey := UserPrefix + username\n\tuser, err := getUserByKey(userKey)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"%s\\n\", err.Error())\n\t\treturn\n\t}\n\n\tuser.UserData.ProfilePicURL = tempFile.Name()\n\tuserBytes, err := json.Marshal(user)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t_, _ = fmt.Fprintf(w, \"%s\\n\", err.Error())\n\t\treturn\n\t}\n\t_ = db.SetJsonValues(userKey, userBytes)\n\n\tfmt.Fprintf(w, \"successfully Uploaded image\\n\")\n}", "func (s *shares) UpdatePublicUpload(shareID int, public bool) error {\n\treturn s.baseShareUpdate(strconv.Itoa(shareID), \"publicUpload\", strconv.FormatBool(public))\n}", "func UploadProfilePic(w http.ResponseWriter,r*http.Request) {\n\tfile,hanler,err:=r.FormFile(\"avatar\")\n\tvar filetype=strings.Split(hanler.Filename,\".\")[1]\n\tvar uploads string=\"uploads/avatar/\"+UserID+\".\"+filetype\n\n\t//Error handleling for copying images from local storage\n\tf,err:=os.OpenFile(uploads,os.O_WRONLY|os.O_CREATE,0666)\n\tif err != nil {\n\t\thttp.Error(w,\"Avatar upload error\",400)\n\t\treturn\n\t}\n\t_,err=io.Copy(f,file)\n\tif err != nil {\n\t\thttp.Error(w,\"Copy avatar upload error\"+err.Error(),400)\n\t\treturn\n\t}\n\n\tvar user models.User\n\tuser.Avatar=UserID+\".\"+filetype\n\t\n\tstatus,err:=db.ModifyUser(user,UserID)\n\tif err != nil || status==false {\n\t\thttp.Error(w,\"Avatar upload error, not the user you're looking\",http.StatusBadRequest)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-type\",\"application/json\")\n\tw.WriteHeader(http.StatusCreated)\n}", "func (s *PublicStorageServer) Upload(ctx context.Context, input *pbs.File) (*pbs.FileURL, error) {\n\tvar obj file.MinioObj\n\tobj.FromPublicFile(input)\n\n\tinfo, err := services.MinioClient.PutObject(context.Background(), \"public\", obj.ObjectName, bytes.NewReader(obj.File), -1, minio.PutObjectOptions{ContentType: obj.Option.ContentType})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"Upload public file %s has been success\", obj.ObjectName)\n\n\treturn &pbs.FileURL{\n\t\tUrl: info.Location,\n\t}, nil\n}", "func ChangePermissions(w http.ResponseWriter, r *http.Request) {\n\t// Identify who the user is\n\tusername := r.Context().Value(\"username\")\n\tif username == nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Get userid for user\n\tuserID, err := GetUserGUID(username.(string))\n\tif err != nil {\n\t\tw.Write([]byte(err.Error()))\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Retrieve PhotoID and IsPublic from JSON request body\n\tvar requestedPhoto Photo\n\terr = json.NewDecoder(r.Body).Decode(&requestedPhoto)\n\tif err != nil {\n\t\tw.Write([]byte(\"Missing PhotoID or IsPublic attribute\"))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif requestedPhoto.ID == \"\" {\n\t\tw.Write([]byte(\"PhotoID not provided in request body\"))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// make sure photo exists\n\tvar photos []Photo\n\tDB.Where(&Photo{ID: requestedPhoto.ID}).Find(&photos)\n\n\tif len(photos) > 1 {\n\t\tw.Write([]byte(\"Multiple photos returned\"))\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\n\t}\n\n\tif len(photos) == 0 {\n\t\tw.Write([]byte(\"No photos returned\"))\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tphoto := photos[0]\n\n\t// Make sure photo belongs to user\n\tif photo.UserID != *userID {\n\t\tw.Write([]byte(\"photo does not belong to user\"))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// If permission has changed photo needs to be updated in photos tabe and object needs to be moved between buckets\n\tif photo.IsPublic != requestedPhoto.IsPublic {\n\t\t// If permission has gone from public to private\n\t\tif photo.IsPublic == true && requestedPhoto.IsPublic == false {\n\t\t\terr = moveBuckets(r.Context(), PUBLIC_BUCKET_NAME, *userID, photo.ID)\n\t\t\tif err != nil {\n\t\t\t\tw.Write([]byte(err.Error()))\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// If permission has gone from private to public\n\t\tif photo.IsPublic == false && requestedPhoto.IsPublic == true {\n\t\t\terr = moveBuckets(r.Context(), *userID, PUBLIC_BUCKET_NAME, photo.ID)\n\t\t\tif err != nil {\n\t\t\t\tw.Write([]byte(err.Error()))\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// change permission for photo in photos table\n\t\tphoto.IsPublic = requestedPhoto.IsPublic\n\t\tDB.Save(&photo)\n\t}\n\n\tw.Write([]byte(\"photo visibility has been changed\"))\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func UploadPhoto(req UploadPhotoRequest) error {\n\tvar err error\n\trow := configure.SQL.QueryRow(`\n\t\tSELECT year, title FROM Album WHERE id = ?\n\t`, req.AlbumID)\n\tvar (\n\t\tyear int\n\t\ttitle string\n\t)\n\tif err = row.Scan(&year, &title); err != nil {\n\t\tlog.Println(\"Error while scanning row\")\n\t\treturn err\n\t}\n\talbumPath := fmt.Sprintf(\"%s/album/%d/%s\", configure.AppProperties.StaticFilePath, year, title)\n\tinsertPhoto := `INSERT INTO Photo (album_id, path) VALUES (?, ?)`\n\tfor _, photoBase64 := range req.PhotoList {\n\t\tphotoName := strconv.FormatInt(time.Now().Unix(), 10)\n\t\tphotoPath := albumPath + string(os.PathSeparator) + photoName\n\t\t// TODO: Transaction management\n\t\tif photoPath, err = utils.DecodeAndSaveBase64(photoPath, photoBase64, utils.ImageBase64); err != nil {\n\t\t\tlog.Println(\"Failed on DecodeAndSaveBase64\")\n\t\t\treturn err\n\t\t}\n\t\tif _, err = configure.SQL.Query(insertPhoto, req.AlbumID, photoPath); err != nil {\n\t\t\tlog.Println(\"Failed on inserting photo\")\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func apiFileUpload(rw http.ResponseWriter, req *http.Request) {\n\tuser, err := users.GetBySession(req)\n\tif err != nil {\n\t\thttp.Error(rw, \"Login required\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\t// Get file from form\n\tfile, header, err := req.FormFile(\"file\")\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdefer file.Close()\n\n\t// Check file size\n\tlenstr := header.Header.Get(\"Content-length\")\n\tif len(lenstr) < 1 {\n\t\thttp.Error(rw, \"Length required\", http.StatusLengthRequired)\n\t\treturn\n\t}\n\tsize, err := strconv.ParseInt(lenstr, 10, 64)\n\tif err != nil || size > mabelConf.MaxUploadSize {\n\t\thttp.Error(rw, \"File size is too big.\", http.StatusRequestEntityTooLarge)\n\t\treturn\n\t}\n\n\t// Check user quota\n\tif user.Data.UsedQuota+size > user.Data.MaxQuota {\n\t\thttp.Error(rw, \"You reached your file upload quota. Please delete some files before submitting new ones.\",\n\t\t\thttp.StatusConflict)\n\t\treturn\n\t}\n\n\t// Do the actual upload\n\terr = upload(user, file, header.Filename)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Update user quota\n\tdb.IncQuota(user.Data.Id, size)\n\n\t// TODO: show success message\n\thttp.Redirect(rw, req, \"/\", http.StatusMovedPermanently)\n}", "func (pubManager PublicationManager) Upload(file multipart.File, extension string, pub *Publication) error {\n\n\t// create a temp file in the default directory\n\ttmpfile, err := ioutil.TempFile(\"\", \"uploaded-*\"+extension)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.Remove(tmpfile.Name())\n\n\t// copy the request payload to the temp file\n\tif _, err = io.Copy(tmpfile, file); err != nil {\n\t\treturn err\n\t}\n\n\t// close the temp file\n\tif err = tmpfile.Close(); err != nil {\n\t\treturn err\n\t}\n\n\t// encrypt the publication and send a notification to the License server\n\treturn encryptPublication(tmpfile.Name(), pub, pubManager)\n}", "func upload(c *gin.Context) {\n\n\t// single file\n\tfile, _ := c.FormFile(\"file\")\n\tfmt.Println(file.Filename)\n}", "func handleGuestImageUpload(w http.ResponseWriter, r *http.Request) {\n\tpostURL := getImageUploadURL(getContext(r))\n\ttmplData := map[string]string{\n\t\t\"uploadURL\": postURL,\n\t\t\"loginURL\": getLoginURL(r, \"/\"),\n\t\t\"logoutURL\": getLogoutURL(r, \"\"),\n\t}\n\trenderTemplate(w, \"image_upload.html\", tmplData)\n}", "func UploadPhoto(chatID, replyToMessageID int64, localFilePath, caption string, entities []*client.TextEntity) (*client.Message, error) {\n\n\trequest := client.SendMessageRequest{\n\t\tChatId: chatID,\n\t\tReplyToMessageId: replyToMessageID,\n\t\tInputMessageContent: &client.InputMessagePhoto{\n\t\t\tPhoto: &client.InputFileLocal{\n\t\t\t\tPath: localFilePath,\n\t\t\t},\n\t\t\tCaption: &client.FormattedText{\n\t\t\t\tText: caption,\n\t\t\t\tEntities: entities,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn tdlibClient.SendMessage(&request)\n\n}", "func handleAlbumUpload(album reddit.FetchResultAlbum, chatID int64, asFile bool) {\n\t// Report status\n\tstopReportChannel := statusReporter(chatID, \"upload_photo\")\n\tdefer close(stopReportChannel)\n\t// Download each file of album\n\tvar err error\n\tfilePaths := make([]*os.File, 0, len(album.Album))\n\tdefer func() { // cleanup\n\t\tfor _, f := range filePaths {\n\t\t\tf.Close()\n\t\t\tos.Remove(f.Name())\n\t\t}\n\t}()\n\tfileConfigs := make([]interface{}, 0, len(album.Album))\n\tfileLinks := make([]string, 0, len(album.Album))\n\tfor _, media := range album.Album {\n\t\tvar tmpFile *os.File\n\t\tvar link string\n\t\tvar f interface{}\n\t\tswitch media.Type {\n\t\tcase reddit.FetchResultMediaTypePhoto:\n\t\t\ttmpFile, err = reddit.DownloadPhoto(media.Link)\n\t\t\tif err == nil {\n\t\t\t\tif asFile {\n\t\t\t\t\tuploadFile := tgbotapi.NewInputMediaDocument(telegramUploadOsFile{tmpFile})\n\t\t\t\t\tuploadFile.Caption = media.Caption\n\t\t\t\t\tf = uploadFile\n\t\t\t\t} else {\n\t\t\t\t\tuploadFile := tgbotapi.NewInputMediaPhoto(telegramUploadOsFile{tmpFile})\n\t\t\t\t\tuploadFile.Caption = media.Caption\n\t\t\t\t\tf = uploadFile\n\t\t\t\t}\n\t\t\t}\n\t\tcase reddit.FetchResultMediaTypeGif:\n\t\t\ttmpFile, err = reddit.DownloadGif(media.Link)\n\t\t\tif err == nil {\n\t\t\t\tif asFile {\n\t\t\t\t\tuploadFile := tgbotapi.NewInputMediaDocument(telegramUploadOsFile{tmpFile})\n\t\t\t\t\tuploadFile.Caption = media.Caption\n\t\t\t\t\tf = uploadFile\n\t\t\t\t} else {\n\t\t\t\t\tuploadFile := tgbotapi.NewInputMediaVideo(telegramUploadOsFile{tmpFile})\n\t\t\t\t\tuploadFile.Caption = media.Caption\n\t\t\t\t\tf = uploadFile\n\t\t\t\t}\n\t\t\t}\n\t\tcase reddit.FetchResultMediaTypeVideo:\n\t\t\ttmpFile, err = reddit.DownloadVideo(media.Link, \"\") // TODO: can i do something about audio URL?\n\t\t\tif err == nil {\n\t\t\t\tif asFile {\n\t\t\t\t\tuploadFile := tgbotapi.NewInputMediaDocument(telegramUploadOsFile{tmpFile})\n\t\t\t\t\tuploadFile.Caption = media.Caption\n\t\t\t\t\tf = uploadFile\n\t\t\t\t} else {\n\t\t\t\t\tuploadFile := tgbotapi.NewInputMediaVideo(telegramUploadOsFile{tmpFile})\n\t\t\t\t\tuploadFile.Caption = media.Caption\n\t\t\t\t\tuploadFile.SupportsStreaming = true\n\t\t\t\t\tf = uploadFile\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Println(\"cannot download media of gallery:\", err)\n\t\t\tbot.Send(tgbotapi.NewMessage(chatID, \"Cannot download gallery media; The link was: \"+link))\n\t\t\tcontinue\n\t\t}\n\t\tfileConfigs = append(fileConfigs, f)\n\t\tlink = media.Link\n\t\tfileLinks = append(fileLinks, media.Link)\n\t\tfilePaths = append(filePaths, tmpFile)\n\t}\n\t// Now upload 10 of them at once\n\ti := 0\n\tfor ; i < len(fileConfigs)/10; i++ {\n\t\t_, err = bot.SendMediaGroup(tgbotapi.NewMediaGroup(chatID, fileConfigs[i*10:(i+1)*10]))\n\t\tif err != nil {\n\t\t\tlog.Println(\"Cannot upload gallery:\", err)\n\t\t\tbot.Send(tgbotapi.NewMessage(chatID, generateGalleryFailedMessage(fileLinks[i*10:(i+1)*10])))\n\t\t}\n\t}\n\terr = nil // needed for last error check\n\tfileConfigs = fileConfigs[i*10:]\n\tif len(fileConfigs) == 1 {\n\t\tswitch f := fileConfigs[0].(type) {\n\t\tcase tgbotapi.InputMediaPhoto:\n\t\t\t_, err = bot.Send(tgbotapi.NewPhoto(chatID, f.Media))\n\t\tcase tgbotapi.InputMediaVideo:\n\t\t\t_, err = bot.Send(tgbotapi.NewVideo(chatID, f.Media))\n\t\tcase tgbotapi.InputMediaDocument:\n\t\t\t_, err = bot.Send(tgbotapi.NewDocument(chatID, f.Media))\n\t\t}\n\t} else if len(fileConfigs) > 1 {\n\t\t_, err = bot.SendMediaGroup(tgbotapi.NewMediaGroup(chatID, fileConfigs))\n\t}\n\tif err != nil {\n\t\tlog.Println(\"cannot upload gallery:\", err)\n\t\tbot.Send(tgbotapi.NewMessage(chatID, generateGalleryFailedMessage(fileLinks[i*10:])))\n\t}\n}", "func HandleUpload(w http.ResponseWriter, r *http.Request){\n\tfile, header, _ := r.FormFile(\"image\")\n\timage, _, _ := image.Decode(file)\n\timages[header.Filename] = image\n\thttp.Redirect(w, r, \"/image?name=\"+header.Filename, 303)\n}", "func APIUpload(opts *ServerOpts) func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS, PUT, DELETE\")\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization\")\n\t\tif r.Method == \"OPTIONS\" {\n\t\t\treturn\n\t\t}\n\t\tif r.Method != \"POST\" {\n\t\t\twriteErr(w, \"Method not allowed\", http.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\n\t\tr.ParseMultipartForm(32 << 20)\n\t\tfile, fileHeader, err := r.FormFile(\"file\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"can not retrieve file: %v\", err)\n\t\t\twriteErr(w, \"Internal Server Error\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tdefer file.Close()\n\n\t\tname, err := diverseName(fileHeader.Filename)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"can not retrieve file: %v\", err)\n\t\t\twriteErr(w, \"Internal Server Error\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tht := sha256.New()\n\t\tht.Write([]byte(name))\n\t\thash := hex.EncodeToString(ht.Sum(nil))\n\n\t\topts.StorageDriver.Init()\n\t\treader, err := opts.StorageDriver.NewReader(hash, \"upload/\")\n\t\tif err == nil {\n\t\t\treader.Close()\n\t\t\twriteErr(w, \"Image already exists\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tbody, err := ioutil.ReadAll(file)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"can not retrieve file: %v\", err)\n\t\t\twriteErr(w, \"Internal Server Error\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\topts.StorageDriver.Write(body, hash, \"upload/\")\n\t\tfinalURL := fmt.Sprintf(\"https://%s/image/upload/f_auto/%s\", opts.Domain, name)\n\t\tfmt.Println(\"Uploaded filename\", finalURL)\n\t\tb, err := json.Marshal(&UploadAPIResponse{URL: finalURL, Error: \"\"})\n\t\tw.Write(b)\n\t}\n}", "func UploadMultipleFile(c *gin.Context) {\r\n\tform, _ := c.MultipartForm() // declare multiple file\r\n\tfiles := form.File[\"upload-files\"]\r\n\tpath := \"images/\"\r\n\r\n\t// bikin for untuk upload filesnya\r\n\tfor _, file := range files {\r\n\t\tfmt.Println(file.Filename)\r\n\t\t// checking saat upload apakah ada error atau tidak\r\n\t\tif err := c.SaveUploadedFile(file, path+file.Filename); err != nil { // ketika ada error\r\n\t\t\tfmt.Println(path)\r\n\t\t\tfmt.Println(\"Ada error \", err.Error())\r\n\t\t} else { // tidak ada error\r\n\r\n\t\t\tc.String(http.StatusOK, fmt.Sprintf(\"'%s' uploaded!\", file.Filename))\r\n\t\t}\r\n\t}\r\n}", "func handleImageUpload(w http.ResponseWriter, r *http.Request) {\n\tpostURL := getImageUploadURL(getContext(r))\n\ttmplData := map[string]string{\n\t\t\"username\": getUserEmail(r),\n\t\t\"uploadURL\": postURL,\n\t\t\"loginURL\": getLoginURL(r, \"/\"),\n\t\t\"logoutURL\": getLogoutURL(r, \"\"),\n\t}\n\trenderTemplate(w, \"image_upload.html\", tmplData)\n}", "func UploadImage(w http.ResponseWriter, r *http.Request) {\n\n\t//Get current Session\n\tsession, _ := store.Get(r, \"session\")\n\tname := session.Values[\"username\"].(string)\n\n\t//Get User uploading Image\n\tuser, err := model.GetUserByUsername(name)\n\tif err != nil {\n\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\n\t}\n\n\t//Get FormFile\n\tr.ParseMultipartForm(10 << 20)\n\tfile, handler, err := r.FormFile(\"uploadfile\")\n\tdefer file.Close()\n\tif err != nil {\n\n\t\tw.WriteHeader(http.StatusConflict)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\n\t}\n\n\t//Get All Other Data from Form\n\tfilename := handler.Filename //Imagename\n\tdescription := r.FormValue(\"description\") //ImageDescription\n\tuploadtime, err := strconv.ParseInt(r.FormValue(\"uploadtime\"), 10, 64) //Upload Time in Millisesconds\n\tif err != nil {\n\n\t\tw.WriteHeader(http.StatusConflict)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\n\t}\n\n\t//Create Temp File\n\tworkingDir, _ := os.Getwd()\n\ttempDir := workingDir + \"/temp\"\n\tif runtime.GOOS == \"windows\" {\n\t\ttempDir = workingDir + \"\\\\temp\"\n\t}\n\n\ttempFile, err := ioutil.TempFile(tempDir, \"upload-*.png\")\n\tif err != nil {\n\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\n\t}\n\tdefer tempFile.Close()\n\n\t//Write to File to Upload\n\timagebytes, err := ioutil.ReadAll(file)\n\tif err != nil {\n\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\n\t}\n\ttempFile.Write(imagebytes)\n\n\t//Try Uploading Image with all Metadata\n\terr = user.CreateImage(imagebytes, filename, description, uploadtime)\n\tif err != nil {\n\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\n\t}\n\n\t//Delete Tempfile\n\tutils.FlushTempFiles()\n\n\tw.WriteHeader(http.StatusCreated)\n}", "func (h *HandlerRepo) ImageUploadingHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"POST\" {\n\t\thttp.Error(w, \"Method Not Allowed\", http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\t// Parsing and Setting the max request size\n\tr.Body = http.MaxBytesReader(w, r.Body, MAX_UPLOAD_SIZE)\n\tif err := r.ParseMultipartForm(MAX_UPLOAD_SIZE); err != nil {\n\t\tlog.Println(\"Error in size of request !\")\n\t\treturn\n\t}\n\n\t// File uploading operation will be here\n\tfile, fileHeader, err := r.FormFile(\"image_file\")\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn\n\t}\n\tdefer func(file multipart.File) {\n\t\terr = file.Close()\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\tlog.Println(err.Error())\n\t\t\treturn\n\t\t}\n\t}(file)\n\n\tdst, err := os.Create(fmt.Sprintf(\"./src/static/images/%s%d%s\",\n\t\tr.Form.Get(\"first_name\"), time.Now().UnixNano(), filepath.Ext(fileHeader.Filename)))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdefer func(dst *os.File) {\n\t\terr = dst.Close()\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\treturn\n\t\t}\n\t}(dst)\n\n\t_, err = io.Copy(dst, file)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn\n\t}\n\n\tlog.Println(\"File Uploaded\")\n\thttp.Redirect(w, r, \"/status\", http.StatusSeeOther)\n\treturn\n}", "func uploadFile(w http.ResponseWriter, r *http.Request, table interface{}, AdminFile bool) {\n\tmem, _ := strconv.Atoi(r.Header[\"Content-Length\"][0])\n\tr.ParseMultipartForm(int64(mem))\n\tif r.Method != http.MethodPost {\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tresponse := Models.UploadFileResponse{\n\t\tError: \"\",\n\t\tResult: false,\n\t\tFileName: \"\",\n\t}\n\tlogged, _, id, _ := Controler.Authenticated(r)\n\tif !logged && !(id > 0) {\n\t\tresponse.Error = \"Access denied\"\n\t\tjsonResponse(w, http.StatusOK, &response)\n\t\treturn\n\t}\n\tfile, handle, err := r.FormFile(\"file\")\n\tdescription := r.FormValue(\"description\")\n\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"%v\", err)\n\t\treturn\n\t}\n\tdefer file.Close()\n\n\tmimeType := handle.Header.Get(\"Content-Type\")\n\t//switch mimeType {\n\t//case \"image/jpeg\":\n\tfileKey = Controler.TokenGenerator() //and filename\n\tif saveFile(w, file, handle, &response, fileKey) {\n\t\tinsertFileInfo(id, fileKey, description, mimeType, table, AdminFile)\n\t\tresponse.Result = true\n\t\tresponse.FileName = fileKey\n\t}\n\t//case \"image/png\":\n\t//\tif saveFile(w, file, handle, &response) {\n\t//\t\tFileName := insertFileInfo(id, handle.Filename, description, mimeType, table)\n\t//\t\tresponse.Result = true\n\t//\t\tresponse.FileName = FileName\n\t//\t}\n\t//default:\n\t//\tresponse.Error = \"The format file is not valid.\"\n\t//\tjsonResponse(w, http.StatusBadRequest, &response)\n\t//\treturn\n\t//}\n\tjsonResponse(w, http.StatusNoContent, &response)\n\n}", "func (cs *CloudStorage) Upload(ctx context.Context, user *domain.User,\n\tbucket string, attrs *domain.ImgAttrs, r io.Reader, prefix string) error {\n\twc := cs.Bucket(bucket).Object(prefix).NewWriter(ctx)\n\tif _, err := io.Copy(wc, r); err != nil {\n\t\treturn err\n\t}\n\tif err := wc.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func UploadFiles(c *fiber.Ctx) error {\n\ttoken := c.Locals(\"user\").(*jwt.Token)\n\tuser, err := services.GetUserFromJWT(*token)\n\tif err != nil {\n\t\treturn c.Status(fiber.StatusNotFound).JSON(fiber.Map{\n\t\t\t\"message\": err.Error(),\n\t\t})\n\t}\n\n\t// Parse the multipart form:\n\tform, err := c.MultipartForm()\n\tif err != nil {\n\t\treturn c.Status(fiber.StatusBadRequest).JSON(fiber.Map{\"message\": err.Error()})\n\t}\n\n\tfiles := form.File[\"files\"]\n\n\tstoredFiles, errors := services.UploadFiles(c, files, &user)\n\tif errors != nil {\n\t\treturn c.Status(fiber.StatusBadRequest).JSON(fiber.Map{\"message\": errors})\n\t}\n\treturn c.Status(fiber.StatusOK).JSON(storedFiles)\n}", "func helperAnonFiles(cfg cliargs.CLIArgs, anonfiles bool) {\n\tuploadFunction := particeps.AnonFilesUpload\n\tvar website string\n\tif anonfiles {\n\t\twebsite = \"https://anonfiles.com\"\n\t} else {\n\t\twebsite = \"https://bayfiles.com\"\n\t\tuploadFunction = particeps.BayFilesUpload\n\t}\n\tfmt.Println(website)\n\tres, err := uploadFunction(cfg.Filename)\n\tassertNonNil(err)\n\tfmt.Printf(\"particeps: successfully uploaded \\\"%s\\\" to %s/\\n\", cfg.Filename, website)\n\tfmt.Printf(\"particeps: full-length link: %s\\n\", res.FullURL)\n\tfmt.Printf(\"particeps: short link: %s\\n\", res.ShortURL)\n}", "func (n *UserNode) Upload(src *os.File, dst, name, hash string, size int64, seas []string) {\n\tdone := make(chan bool)\n\ttag := tpCrypto.SHA512HexFromBytes([]byte(dst + name + hash))\n\tuploadInfo := &userUploadInfo{\n\t\tsrc: src,\n\t\tpackages: int64(math.Ceil(float64(size) / float64(lib.PackageSize))),\n\t\toperations: make(map[p2pPeer.ID]*tpUser.Operation),\n\t\tdone: done,\n\t}\n\tseaIDs := make([]p2pPeer.ID, 0)\n\tfor _, s := range seas {\n\t\tseaPub, err := p2pCrypto.UnmarshalSecp256k1PublicKey(tpCrypto.HexToBytes(s))\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tseaID, err := p2pPeer.IDFromPublicKey(seaPub)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tseaIDs = append(seaIDs, seaID)\n\t\tuploadInfo.operations[seaID] = n.GenerateOperation(s, dst, name, hash, size)\n\t}\n\tn.uploadInfos.Lock()\n\tn.uploadInfos.m[tag] = uploadInfo\n\tn.uploadInfos.Unlock()\n\tfor _, seaID := range seaIDs {\n\t\terr := n.SendUploadQuery(seaID, tag, size)\n\t\tif err != nil {\n\t\t\tdelete(uploadInfo.operations, seaID)\n\t\t\tcontinue\n\t\t}\n\t}\n\tgo func(info *userUploadInfo) {\n\t\tuploadInfo.Lock()\n\t\tif len(uploadInfo.operations) == 0 {\n\t\t\tdone <- true\n\t\t}\n\t\tuploadInfo.Unlock()\n\t}(uploadInfo)\n\t<-done\n\tlib.Logger.WithFields(logrus.Fields{\n\t\t\"tag\": tag,\n\t}).Info(\"fragment upload finish\")\n\tn.uploadInfos.Lock()\n\tdelete(n.uploadInfos.m, tag)\n\tn.uploadInfos.Unlock()\n}", "func (client *activeClient) Upload(c *ishell.Context) {\n\tpath := strings.Join(c.Args, \" \")\n\tinfo, _ := os.Stat(path)\n\n\tc.ProgressBar().Indeterminate(true)\n\tc.ProgressBar().Start()\n\n\tcontent, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tc.ProgressBar().Final(green(\"[Server] \") + red(\"[!] Upload failed could not read local file!\"))\n\t\tc.ProgressBar().Stop()\n\t\tc.Println(green(\"[Server] \") + red(\"[!] \", err))\n\t\treturn\n\t}\n\n\tf := shared.File{\n\t\tContent: content,\n\t\tPath: path,\n\t\tPerm: info.Mode(),\n\t}\n\n\tif err := client.RPC.Call(\"API.RecvFile\", f, &void); err != nil {\n\t\tc.ProgressBar().Final(green(\"[Server] \") + red(\"[!] Upload failed!\"))\n\t\tc.ProgressBar().Stop()\n\t\tc.Println(green(\"[Server] \") + red(\"[!] \", err))\n\t\treturn\n\t}\n\n\tc.ProgressBar().Final(green(\"[Server] \") + green(\"[+] Upload Successful\"))\n\tc.ProgressBar().Final(yellow(\"[\"+client.Client.Name+\"] \") + green(\"[+] Upload successfully received\"))\n\tc.ProgressBar().Stop()\n}", "func AllowedImages(file multipart.File, fileheader *multipart.FileHeader) error {\n\tsize := fileheader.Size\n\tif size > 20<<20 {\n\t\treturn errors.New(\"Image is too big\")\n\t}\n\tbuff := make([]byte, 512)\n\tif _, err := file.Read(buff); err != nil {\n\t\treturn errors.New(\"Can't read Image\")\n\t}\n\tfile.Seek(0, 0)\n\tcontentType := http.DetectContentType(buff)\n\tif len(contentType) < 6 || contentType[:6] != \"image/\" {\n\t\treturn errors.New(\"It's not image\")\n\t}\n\treturn nil\n}", "func uploadHandler(ctx *router.Context) {\n\t// Only bots should upload test results. Check IP address against a whitelist.\n\tc, w, r := ctx.Context, ctx.Writer, ctx.Request\n\twhitelisted, err := auth.GetState(c).DB().IsInWhitelist(\n\t\tc, auth.GetState(c).PeerIP(), \"bots\")\n\tif err != nil {\n\t\tlogging.WithError(err).Errorf(c, \"uploadHandler: check IP whitelist\")\n\t\thttp.Error(w, \"Failed IP whitelist check\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif !whitelisted {\n\t\tlogging.WithError(err).Errorf(\n\t\t\tc, \"Uploading IP %s is not whitelisted\", auth.GetState(c).PeerIP())\n\t\thttp.Error(w, \"IP is not whitelisted\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tif r.TLS == nil {\n\t\tlogging.Errorf(c, \"uploadHandler: only allow HTTPS\")\n\t\thttp.Error(w, \"Only HTTPS requests are allowed\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tfileheaders := r.MultipartForm.File[\"file\"]\n\tif !info.IsDevAppServer(c) {\n\t\tc = appengine.WithContext(c, r)\n\t}\n\tlogging.Infof(c, \"%d files in this upload\", len(fileheaders))\n\tfor _, fh := range fileheaders {\n\t\tif err := doFileUpload(c, fh); err != nil {\n\t\t\tmsg := logging.WithError(err)\n\t\t\tcode := http.StatusInternalServerError\n\t\t\tif se, ok := err.(statusError); ok {\n\t\t\t\tcode = se.code\n\t\t\t}\n\t\t\tif code >= http.StatusInternalServerError {\n\t\t\t\tmsg.Errorf(c, \"uploadHandler\")\n\t\t\t} else {\n\t\t\t\tmsg.Warningf(c, \"uploadHandler\")\n\t\t\t}\n\t\t\thttp.Error(w, err.Error(), code)\n\t\t\treturn\n\t\t}\n\t}\n\n\tio.WriteString(w, \"OK\")\n}", "func (ac *activeClient) Upload(c *ishell.Context) {\n\tpath := strings.Join(c.Args, \" \")\n\tinfo, _ := os.Stat(path)\n\n\tc.ProgressBar().Indeterminate(true)\n\tc.ProgressBar().Start()\n\n\tcontent, err := os.ReadFile(path)\n\tif err != nil {\n\t\tc.ProgressBar().Final(green(\"[Server] \") + red(\"[!] Upload failed could not read local file:\", err))\n\t\tc.ProgressBar().Stop()\n\t\treturn\n\t}\n\n\tf := shared.File{\n\t\tContent: content,\n\t\tPath: path,\n\t\tPerm: info.Mode(),\n\t}\n\n\tif err := ac.RPC.Call(\"API.RecvFile\", f, &void); err != nil {\n\t\tc.ProgressBar().Final(green(\"[Server] \") + red(\"[!] Upload failed:\", err))\n\t\tc.ProgressBar().Stop()\n\t\treturn\n\t}\n\n\tc.ProgressBar().Final(green(\"[Server] \") + green(\"[+] Upload Successful\"))\n\tc.ProgressBar().Final(yellow(\"[\"+ac.Data().Name+\"] \") + green(\"[+] Upload successfully received\"))\n\tc.ProgressBar().Stop()\n}", "func (ref *Files) UploadFromURL(file *File, authOptions ...AuthOption) error {\n\tif reflect.ValueOf(file.Meatadata).IsNil() {\n\t\tfile.Meatadata = make(map[string]interface{})\n\t}\n\towner, err := file.fetchOwner(ref.c, authOptions...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unexpected error when fetch owner: %v\", err)\n\t}\n\tfile.Meatadata[\"__source\"] = \"external\"\n\tif owner != nil {\n\t\tfile.Meatadata[\"owner\"] = owner.ID\n\t} else {\n\t\tfile.Meatadata[\"owner\"] = \"unknown\"\n\t}\n\n\tpath := \"/1.1/files\"\n\toptions := ref.c.getRequestOptions()\n\toptions.JSON = encodeFile(file, false)\n\n\tresp, err := ref.c.request(methodPost, path, options, authOptions...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trespJSON := make(map[string]interface{})\n\tif err := json.Unmarshal(resp.Bytes(), &respJSON); err != nil {\n\t\treturn err\n\t}\n\n\tobjectID, ok := respJSON[\"objectId\"].(string)\n\tif !ok {\n\t\treturn fmt.Errorf(\"unexpected error when fetch objectId: want type string but %v\", reflect.TypeOf(respJSON[\"objectId\"]))\n\t}\n\tfile.ID = objectID\n\n\tcreatedAt, ok := respJSON[\"createdAt\"].(string)\n\tif !ok {\n\t\treturn fmt.Errorf(\"unexpected error when fetch createdAt: want type string but %v\", reflect.TypeOf(respJSON[\"createdAt\"]))\n\t}\n\tdecodedCreatedAt, err := time.Parse(time.RFC3339, createdAt)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unexpected error when parse createdAt: %v\", err)\n\t}\n\tfile.CreatedAt = decodedCreatedAt\n\n\treturn nil\n}", "func (s *Session) UploadMultiPhotos(ps, ns []string, owner int) ([]string, error) {\n\tif ps == nil {\n\t\treturn nil, nil\n\t}\n\treturn multiUploads(s, ps, ns, getWallPhotoUploader(owner))\n}", "func (u *Uploader) Upload(reader io.Reader, input s3.PutObjectInput) error {\n\treturn errors.New(\"unimplemented\")\n}", "func UploadSingleFile(c *gin.Context) {\r\n\tfile, _ := c.FormFile(\"upload-file\")\r\n\tfmt.Println(file.Filename)\r\n\tpath := \"images/\"\r\n\r\n\t// checking saat upload ada error atau tidak\r\n\tif err := c.SaveUploadedFile(file, path+file.Filename); err != nil { // ketika ada error\r\n\t\tfmt.Println(path)\r\n\t\tfmt.Println(\"Ada error \", err.Error())\r\n\t} else { // tidak ada error\r\n\t\tc.String(http.StatusOK, fmt.Sprintf(\"'%s' uploaded!\", file.Filename))\r\n\t}\r\n}", "func (c *ProfileController) uploadImage(ctx iris.Context, id string) (string, error) {\n\tfile, info, err := ctx.FormFile(\"image_profile\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer file.Close()\n\t// replacer.Replace digunakan untuk mereplace karakter uncommon di file name\n\tfilename := fmt.Sprintf(\"%s%s%s\", id, \"_\", replacer.Replace(info.Filename, \"_\"))\n\tout, err := os.OpenFile(\"./web/public/images/profile/\"+filename, os.O_WRONLY|os.O_CREATE, 0666)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer out.Close()\n\n\tio.Copy(out, file)\n\n\treturn filename, nil\n}", "func (s *UserSettingsSummary) SetUploadAllowed(v string) *UserSettingsSummary {\n\ts.UploadAllowed = &v\n\treturn s\n}", "func (a *attachUp) Upload() (string, error) {\n\terr := multiUploadNonPhoto(a, a.sess, 0)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tss, err := a.sess.UploadMultiPhotos(a.p, a.pn, 0)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\ta.s = append(a.s, ss...)\n\treturn strings.Join(a.s, \",\"), nil\n}", "func FileCreate(ctx *gin.Context) {\n\tvar user *model.User\n\tif userInterface, exists := ctx.Get(\"User\"); !exists {\n\t\t// User has not been created, we only allow existing user to visit images stored\n\t\tmisc.ReturnStandardError(ctx, 403, \"you will have to be a registered user to do this\")\n\t\treturn\n\t} else {\n\t\tuser = userInterface.(*model.User)\n\t}\n\tfile := &model.File{}\n\tif err := jsonapi.UnmarshalPayload(ctx.Request.Body, file); err != nil {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"cannot unmarshal JSON of request\")\n\t\treturn\n\t} else if file.Filename == nil || file.Type == nil {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"filename and type must be provided\")\n\t\treturn\n\t} else if _, ok := FileTypes[*file.Type]; !ok {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"type '\"+*file.Type+\"' is not accepted\")\n\t\treturn\n\t}\n\t// get file extension\n\tfileNameSlice := strings.Split(*file.Filename, \".\")\n\textension := fileNameSlice[len(fileNameSlice)-1]\n\tif _, ok := AllowedExtensions[extension]; !ok {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"file extension '\"+extension+\"'is not accepted\")\n\t\treturn\n\t}\n\t// standardize filename to uuid + extension\n\tnewFilename := uuid.New().String() + \".\" + extension\n\tfile.Filename = &newFilename\n\tfile.UploaderID = &user.ID\n\tfile.Uploader = user\n\n\tdb := ctx.MustGet(\"DB\").(*gorm.DB)\n\tif err := db.Save(file).Error; err != nil {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"cannot save file record to database\")\n\t\treturn\n\t}\n\texpiresAt := time.Now().UTC().Add(SASValidTime)\n\t// we assign only create permission to this SAS (create permission does not allow updating resources)\n\tqp, err := getSASQueryParam(expiresAt, FileTypes[*file.Type], *file.Filename, azblob.BlobSASPermissions{Create: true}.String())\n\tif err != nil {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"cannot save file record to database\")\n\t\treturn\n\t}\n\tfile.QueryParam = qp\n\tfile.QueryParamExpiresAt = expiresAt.Add(-SASValidAllowance)\n\tfile.Endpoint = \"https://\" + viper.GetString(\"azure.accountName\") + \".blob.core.windows.net/\" + FileTypes[*file.Type] + \"/\" + newFilename\n\tctx.Status(http.StatusCreated)\n\tif err := jsonapi.MarshalPayloadWithoutIncluded(ctx.Writer, file); err != nil {\n\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\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 getImage(w http.ResponseWriter, req *http.Request) {\n\n\t// Manage Cors\n\tsetCors(&w)\n\tif req.Method == \"OPTIONS\" {\n\t\treturn\n\t}\n\n\t// Authorize request\n\tclaims, err := authRequest(req)\n\tif err != nil {\n\t\tlogger.Error(\"Unauthorized request to upload sending 401: %v\", err)\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(\"401 - Unauthorized request, ensure you sign in and obtain the jwt auth token\"))\n\t\treturn\n\t}\n\n\tvars := mux.Vars(req)\n\n\t// validate url parameters and retrieve imageMeta\n\t// returns a 404 if data cannot be found in the db otherwise assumes bad request\n\timageMeta, err := validateVars(vars)\n\tif err != nil {\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Failed to validate vars sending 400: %v\", err)\n\t\t\tif strings.Contains(err.Error(), \"404 - Not found\") {\n\t\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\t\tw.Write([]byte(\"404 - Not found, no image with that information available\"))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\tw.Write([]byte(\"400 - Bad request unable to parse url parameters\"))\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Ensure user has access permissions\n\tif claims.Uid != int(imageMeta.Uid) {\n\t\tlogger.Error(\"unauthorized user attempting to delete image\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(\"401 - Unauthorized, this file is private and you do not have access\"))\n\t\treturn\n\t}\n\n\t// prepare file for sending\n\tfileBytes, err := ioutil.ReadFile(fmt.Sprintf(\"./%s/%s/%s\", IMAGE_DIR, vars[\"uid\"], vars[\"fileId\"]))\n\tif err != nil {\n\t\tlogger.Error(\"Failed to retrieve file: %v\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"500 - Failed to retrieve file, try again later\"))\n\t}\n\n\tw.Header().Set(\"Content-Type\", imageMeta.Encoding)\n\tw.Write(fileBytes)\n\treturn\n}", "func Upload(g *gin.Context) {\n\tdst := \"./upload/\"\n\tfile, err := g.FormFile(\"file\")\n\tif err != nil {\n\t\tlog.Println(\"[ERROR] FormFile err: \", err)\n\t\tg.JSON(http.StatusInternalServerError, gin.H{\"message\": err})\n\t\treturn\n\t}\n\n\t// file.Filename abc.mp4\n\text := filepath.Ext(file.Filename) // .mp4\n\tkey := strings.TrimSuffix(file.Filename, ext) // abc\n\ttargetName := key + \"-visualnavigation\" + ext\n\terr = g.SaveUploadedFile(file, dst+targetName)\n\tif err != nil {\n\t\tlog.Println(\"[ERROR] SaveUploadedFile err: \", err)\n\t\tg.JSON(http.StatusInternalServerError, gin.H{\"message\": err})\n\t\treturn\n\t}\n\tg.JSON(http.StatusOK, gin.H{\n\t\t\"message\": \"Save file to \" + dst + targetName,\n\t})\n}", "func UploadPicture(w http.ResponseWriter, r *http.Request) *appError {\n session, err := store.Get(r, \"session-name\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n s3 := S3{\n EndPointString: session.Values[\"Endpoint\"].(string),\n AccessKey: session.Values[\"AccessKey\"].(string),\n SecretKey: session.Values[\"SecretKey\"].(string),\n Namespace: session.Values[\"Namespace\"].(string),\n }\n\n decoder := json.NewDecoder(r.Body)\n var s map[string]string\n err = decoder.Decode(&s)\n if err != nil {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Can't decode JSON data\"}\n }\n bucketName := s[\"bucket\"]\n retention := s[\"retention\"]\n fileName := s[\"file_name\"]\n imageWidth := s[\"image_width\"]\n imageHeight := s[\"image_height\"]\n gpsLatitude := s[\"gps_latitude\"]\n gpsLongitude := s[\"gps_longitude\"]\n datetime := s[\"datetime\"]\n\n contentType := \"binary/octet-stream\"\n pictureHeaders := make(map[string][]string)\n thumbnailHeaders := make(map[string][]string)\n pictureHeaders[\"Content-Type\"] = []string{contentType}\n thumbnailHeaders[\"Content-Type\"] = []string{contentType}\n if retention != \"\" {\n i, err := strconv.Atoi(retention)\n if err != nil {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Can't use this retention value\"}\n }\n pictureHeaders[\"x-emc-retention-period\"] = []string{strconv.Itoa(i * 24 * 3600)}\n thumbnailHeaders[\"x-emc-retention-period\"] = []string{strconv.Itoa(i * 24 * 3600)}\n }\n pictureHeaders[\"x-amz-meta-image-width\"] = []string{imageWidth}\n pictureHeaders[\"x-amz-meta-image-height\"] = []string{imageHeight}\n if gpsLatitude != \"\" {\n pictureHeaders[\"x-amz-meta-gps-latitude\"] = []string{gpsLatitude}\n }\n if gpsLongitude != \"\" {\n pictureHeaders[\"x-amz-meta-gps-longitude\"] = []string{gpsLongitude}\n }\n if datetime != \"\" {\n pictureHeaders[\"x-amz-meta-datetime\"] = []string{datetime}\n }\n preparedPictureS3Request, _ := prepareS3Request(s3, bucketName, \"PUT\", \"/pictures/\" + fileName, pictureHeaders, true)\n preparedThumbnailS3Request, _ := prepareS3Request(s3, bucketName, \"PUT\", \"/thumbnails/\" + fileName, thumbnailHeaders, true)\n delete(pictureHeaders, \"host\")\n delete(thumbnailHeaders, \"host\")\n\n rendering.JSON(w, http.StatusOK, struct {\n PictureHeaders map[string][]string `json:\"picture_headers\"`\n PictureUrl string `json:\"picture_url\"`\n ThumbnailHeaders map[string][]string `json:\"thumbnail_headers\"`\n ThumbnailUrl string `json:\"thumbnail_url\"`\n } {\n PictureHeaders: pictureHeaders,\n PictureUrl: preparedPictureS3Request.Url,\n ThumbnailHeaders: thumbnailHeaders,\n ThumbnailUrl: preparedThumbnailS3Request.Url,\n })\n return nil\n}", "func (s *Service) Upload(ctx context.Context, uploadKey, uploadToken, contentType string, data []byte) (result *model.Result, err error) {\n\tif !s.verify(uploadKey, uploadToken) {\n\t\terr = ecode.AccessDenied\n\t\treturn\n\t}\n\tkey, secret, bucket := s.authorizeInfo(uploadKey)\n\tif contentType == \"\" {\n\t\tcontentType = http.DetectContentType(data)\n\t}\n\tlocation, etag, err := s.bfs.Upload(ctx, key, secret, contentType, bucket, \"\", \"\", data)\n\tif err != nil {\n\t\treturn\n\t}\n\tresult = &model.Result{\n\t\tLocation: location,\n\t\tEtag: etag,\n\t}\n\treturn\n}", "func (h *HandlerRepo) MultipleImageUploadingHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"POST\" {\n\t\thttp.Error(w, \"Method Not Allowed\", http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\tr.Body = http.MaxBytesReader(w, r.Body, MAX_MULTIPLE_SIZE) // Use for limiting the r.Body\n\tif err := r.ParseMultipartForm(MAX_MULTIPLE_SIZE); err != nil { // Parse form have multipart/form-data into it\n\t\tlog.Println(err.Error())\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tfiles := r.MultipartForm.File[\"images_file\"] // Use for getting the all files in the request\n\n\tfor _, fileHeader := range files {\n\t\tif fileHeader.Size == MAX_UPLOAD_SIZE {\n\t\t\tlog.Println(\"Uploaded file is too big\")\n\t\t\thttp.Error(w, \"Uploaded file is too big\", http.StatusBadRequest)\n\t\t\tcontinue\n\t\t}\n\n\t\tuFile, err := fileHeader.Open()\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tdefer func(uFile multipart.File) {\n\t\t\terr = uFile.Close()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t}(uFile)\n\n\t\tuF, err := os.Create(fmt.Sprintf(\"./src/static/images/%s%d%s\",\n\t\t\tr.Form.Get(\"first_name\"), time.Now().UnixNano(), filepath.Ext(fileHeader.Filename)))\n\t\tdefer func(uF *os.File) {\n\t\t\terr = uF.Close()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t}(uF)\n\n\t\t_, err = io.Copy(uF, uFile)\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Println(\"Files Uploaded !\")\n\thttp.Redirect(w, r, \"/status\", http.StatusSeeOther)\n\treturn\n}", "func (s *UserSettings) SetUploadAllowed(v string) *UserSettings {\n\ts.UploadAllowed = &v\n\treturn s\n}", "func handleImageUploadComplete(w http.ResponseWriter, r *http.Request) {\n\tctx := getContext(r)\n\t// XXX: blobstore parse must be called before r.FormValue\n\tblobKey, otherValues := getImageParseUploadKey(ctx, r)\n\tname := otherValues.Get(\"name\")\n\tlog.Println(\"Storing\", name, \" blob key:\", blobKey)\n\tif blobKey != \"\" {\n\t\tupdateImageRecord(ctx, name, blobKey, getUserEmail(r))\n\t\thttp.Redirect(w, r, \"/imageview?blobkey=\"+blobKey, http.StatusFound)\n\t}\t\n\thttp.Redirect(w, r, \"/\", http.StatusFound)\n}", "func (s *Server) handleUpload(w http.ResponseWriter, req *http.Request) error {\n\tglog.Infof(\"%s %s\", req.Method, req.URL.Path)\n\tif s.opts.AllowCORS {\n\t\torigin := \"*\"\n\t\tif len(req.Header[\"Origin\"]) > 0 {\n\t\t\torigin = req.Header[\"Origin\"][0]\n\t\t}\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\tw.Header().Set(\"Access-Control-Max-Age\", \"1800\")\n\t\t// X-Report-Url header is used to report back the link to the report.\n\t\tw.Header().Set(\"Access-Control-Expose-Headers\", \"X-Report-Url\")\n\t\tif req.Method == \"OPTIONS\" {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST\")\n\t\t}\n\t}\n\tif req.Method == \"OPTIONS\" {\n\t\treturn nil\n\t}\n\tuserHash := \"unknown\"\n\tif s.opts.UseOpenID {\n\t\tvar err error\n\t\tuserHash, err = s.authenticate(w, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif req.Method != \"POST\" {\n\t\treturn fmt.Errorf(\"Unsupported method %s on %s\", req.Method, req.URL.Path)\n\t}\n\treq.Body = http.MaxBytesReader(w, req.Body, maxUploadSize)\n\terr := req.ParseMultipartForm(maxUploadSize)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error parsing upload form: %s\", err)\n\t}\n\tf, _, err := req.FormFile(\"notebook\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"no notebook file in the form: %s\\nRequest %s\", err, req.URL)\n\t}\n\tdefer f.Close()\n\tb, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading upload: %s\", err)\n\t}\n\t// If exercise_id is specified in the request, then we need to grade only that exercise.\n\trequestedExerciseID := req.FormValue(\"exercise_id\")\n\t// TODO(salikh): Add user identifier to the file name.\n\tsubmissionID := uuid.New().String()\n\tsubmissionFilename := filepath.Join(s.opts.UploadDir, submissionID+\".ipynb\")\n\terr = ioutil.WriteFile(submissionFilename, b, 0700)\n\tglog.V(3).Infof(\"Uploaded %d bytes\", len(b))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error writing uploaded file: %s\", err)\n\t}\n\t// Store user hash and submission ID inside the metadata.\n\tdata := make(map[string]interface{})\n\terr = json.Unmarshal(b, &data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not parse submission as JSON: %s\", err)\n\t}\n\tvar metadata map[string]interface{}\n\tv, ok := data[\"metadata\"]\n\tif ok {\n\t\tmetadata, ok = v.(map[string]interface{})\n\t}\n\tif !ok {\n\t\tmetadata = make(map[string]interface{})\n\t\tdata[\"metadata\"] = metadata\n\t}\n\tmetadata[\"submission_id\"] = submissionID\n\tmetadata[\"user_hash\"] = userHash\n\tmetadata[\"timestamp\"] = time.Now().Unix()\n\tif requestedExerciseID != \"\" {\n\t\tmetadata[\"requested_exercise_id\"] = requestedExerciseID\n\t}\n\tb, err = json.Marshal(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// submissionID is an UUID, so it does not require escaping.\n\treportURL := \"/report/\" + submissionID\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\t// X-Report-Url header is used to report back the link to the report.\n\tw.Header().Set(\"X-Report-Url\", reportURL)\n\tglog.V(5).Infof(\"Uploaded: %s\", string(b))\n\tif s.opts.LogToBucket && s.opts.LogBucketName != \"\" {\n\t\tctx := req.Context()\n\t\tclient, err := storage.NewClient(ctx)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create Cloud Storage client: %w\", err)\n\t\t}\n\t\tbucket := client.Bucket(s.opts.LogBucketName)\n\t\tlogW := bucket.Object(submissionID + \".ipynb\").NewWriter(ctx)\n\t\tn, err := logW.Write(b)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error writing log to bucket %q: %w\",\n\t\t\t\ts.opts.LogBucketName, err)\n\t\t}\n\t\terr = logW.Close()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error closing log writer: %w\", err)\n\t\t}\n\t\tglog.V(5).Infof(\"Written %d bytes to %s to log bucket %s\", n, submissionID+\".ipynb\", s.opts.LogBucketName)\n\t}\n\tif !s.opts.GradeLocally {\n\t\tglog.V(3).Infof(\"Checking %d bytes\", len(b))\n\t\terr = s.scheduleCheck(b)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = uploadResultTmpl.Execute(w, reportURL)\n\t\tif err != nil {\n\t\t\tglog.Error(err)\n\t\t}\n\t\treturn nil\n\t}\n\t// Grade locally\n\treport, err := s.opts.Autograder.Grade(b)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error grading: %s\", err)\n\t}\n\treportFilename := filepath.Join(s.opts.UploadDir, submissionID+\".txt\")\n\terr = ioutil.WriteFile(reportFilename, report, 0775)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error writing to %q: %s\", reportFilename, err)\n\t}\n\tif s.opts.LogToBucket && s.opts.LogBucketName != \"\" {\n\t\tctx := req.Context()\n\t\tclient, err := storage.NewClient(ctx)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create Cloud Storage client: %w\", err)\n\t\t}\n\t\tbucket := client.Bucket(s.opts.LogBucketName)\n\t\tlogW := bucket.Object(submissionID + \".txt\").NewWriter(ctx)\n\t\tn, err := logW.Write(report)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error writing log to bucket %q: %w\",\n\t\t\t\ts.opts.LogBucketName, err)\n\t\t}\n\t\terr = logW.Close()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error closing log writer: %w\", err)\n\t\t}\n\t\tglog.V(5).Infof(\"Written %d bytes to %s to log bucket %s\", n, submissionID+\".txt\", s.opts.LogBucketName)\n\t}\n\tif path.Ext(req.URL.Path) == \".txt\" {\n\t\t// Return the plain text of report JSON.\n\t\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\t\t_, err := w.Write(report)\n\t\treturn err\n\t}\n\treturn s.renderReport(w, submissionID, report)\n}", "func apiUploadHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {\n\tuserName := sessionHandler.GetUserName(r)\n\tif userName != \"\" {\n\t\t// Create multipart reader\n\t\treader, err := r.MultipartReader()\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\t// Slice to hold all paths to the files\n\t\tallFilePaths := make([]string, 0)\n\t\t// Copy each part to destination.\n\t\tfor {\n\t\t\tpart, err := reader.NextPart()\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// If part.FileName() is empty, skip this iteration.\n\t\t\tif part.FileName() == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Folder structure: year/month/randomname\n\t\t\tcurrentDate := date.GetCurrentTime()\n\t\t\tfilePath := filepath.Join(filenames.ImagesFilepath, currentDate.Format(\"2006\"), currentDate.Format(\"01\"))\n\t\t\tif os.MkdirAll(filePath, 0777) != nil {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdst, err := os.Create(filepath.Join(filePath, strconv.FormatInt(currentDate.Unix(), 10)+\"_\"+uuid.Must(uuid.NewV4()).String()+filepath.Ext(part.FileName())))\n\t\t\tdefer dst.Close()\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif _, err := io.Copy(dst, part); err != nil {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Rewrite to file path on server\n\t\t\tfilePath = strings.Replace(dst.Name(), filenames.ImagesFilepath, \"/images\", 1)\n\t\t\t// Make sure to always use \"/\" as path separator (to make a valid url that we can use on the blog)\n\t\t\tfilePath = filepath.ToSlash(filePath)\n\t\t\tallFilePaths = append(allFilePaths, filePath)\n\t\t}\n\t\tjson, err := json.Marshal(allFilePaths)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(json)\n\t\treturn\n\t}\n\thttp.Error(w, \"Not logged in!\", http.StatusInternalServerError)\n}", "func (s *UpdateUserSettingsInput) SetUploadAllowed(v string) *UpdateUserSettingsInput {\n\ts.UploadAllowed = &v\n\treturn s\n}", "func (c *Client) Upload(endpoint string, filename string) *grequests.Response {\n\tfmt.Printf(\"Uploading %s >>> %s\", filename, endpoint)\n\tfd, err := grequests.FileUploadFromDisk(filename)\n\tif err != nil {\n\t\tutilities.CheckError(err, \"Cannot open file: \"+filename)\n\t}\n\tresp, err := grequests.Post(endpoint, &grequests.RequestOptions{\n\t\tFiles: fd,\n\t})\n\tif err != nil {\n\t\tutilities.CheckError(err, \"Cannot make requests to \"+endpoint)\n\t}\n\tif resp.Ok != true {\n\t\tlog.Println(resp.String())\n\t\tlog.Println(\"Request did not return OK\")\n\t}\n\treturn resp\n}", "func UploadToGCloudStorage(bucket, filePath, fileName string, isPublic bool) (string, error) {\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\tlogrus.Error(\"[UploadToGCloudStorage] Open file error: \", err)\n\t\treturn \"\", err\n\t}\n\n\tdefer func() {\n\t\terr = file.Close()\n\t}()\n\n\tobj := client.Bucket(bucket).Object(fileName)\n\twriter := obj.NewWriter(ctx)\n\tif _, err = io.Copy(writer, file); err != nil {\n\t\tlogrus.Error(\"[UploadToGCloudStorage] Copy file error: \", err)\n\t\treturn \"\", err\n\t}\n\n\tif err = writer.Close(); err != nil {\n\t\tlogrus.Error(\"[UploadToGCloudStorage] close writer error: \", err)\n\t\treturn \"\", err\n\t}\n\n\tif isPublic {\n\t\tacl := client.Bucket(bucket).Object(fileName).ACL()\n\t\tif err := acl.Set(ctx, storage.AllUsers, storage.RoleReader); err != nil {\n\t\t\tlogrus.Error(\"[UploadToGCloudStorage] ACL set error: \", err)\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn fileName, nil\n}", "func uploadBookHandler(res http.ResponseWriter, req *http.Request) {\n _, claims, err := jwtauth.FromContext(req.Context())\n if err != nil {\n log.Println(err)\n res.WriteHeader(500)\n return\n }\n\n // Parse the uploaded forms\n if err := req.ParseMultipartForm(maxFormMemory); err != nil {\n res.WriteHeader(500)\n return\n }\n\n // Upload each uploaded book to the server\n for _, header := range req.MultipartForm.File[\"books\"] {\n filename := header.Filename\n file, err := header.Open()\n if err != nil {\n res.WriteHeader(500)\n log.Println(err)\n return\n }\n\n stream, err := booksBucket.OpenUploadStream(filename, options.GridFSUpload())\n if err != nil {\n res.WriteHeader(400)\n log.Println(err)\n return\n }\n defer stream.Close()\n\n if _, err := io.Copy(stream, file); err != nil {\n res.WriteHeader(500)\n log.Println(err)\n return\n }\n\n _, err = usersCollection.UpdateOne(\n context.Background(),\n bson.M{\"username\": claims[\"username\"].(string)},\n bson.M{\"$push\": bson.M{\"books\": Book{Id: stream.FileID.(primitive.ObjectID), Title: filename}}},\n options.Update().SetUpsert(true),\n )\n if err != nil {\n res.WriteHeader(500)\n log.Println(err)\n return\n }\n }\n\n // Go back to the library page \n http.Redirect(res, req, \"/library\", 302)\n}", "func SharedFolderDoUpload(username, path, filename string, file io.ReadCloser)error{\n\tspl := strings.Split(path, \"/\")\n\tfullPath := filepath.Join(getSharedFolderHome(spl[0]), sanitizeInputPath(strings.Join(spl[1:], \"/\")), sanitizeInputPath(filename))\n\t\n\tdefer file.Close()\n\tdst, err := os.OpenFile(fullPath, os.O_CREATE | os.O_WRONLY, 0777)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer dst.Close()\n\t\n\t_, err = io.Copy(dst, file)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *StorageService) Upload(\n\tuserID *mytype.OID,\n\tfile io.Reader,\n\tcontentType string,\n\tsize int64,\n) (*UploadResponse, error) {\n\t// Hash of the file contents to be used as the s3 object 'key'.\n\thash := sha1.New()\n\tio.Copy(hash, file)\n\tkey := fmt.Sprintf(\"%x\", hash.Sum(nil))\n\n\tobjectName := fmt.Sprintf(\n\t\t\"%s/%s/%s/%s\",\n\t\tkey[:2],\n\t\tkey[3:5],\n\t\tkey[6:8],\n\t\tkey[9:],\n\t)\n\tobjectPath := strings.Join([]string{\n\t\tuserID.Short,\n\t\tobjectName,\n\t}, \"/\")\n\n\t_, err := s.svc.StatObject(\n\t\ts.bucket,\n\t\tobjectPath,\n\t\tminio.StatObjectOptions{},\n\t)\n\tif err != nil {\n\t\tminioError := minio.ToErrorResponse(err)\n\t\tif minioError.Code != \"NoSuchKey\" {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn nil, err\n\t\t}\n\t\tn, err := s.svc.PutObject(\n\t\t\ts.bucket,\n\t\t\tobjectPath,\n\t\t\tfile,\n\t\t\tsize,\n\t\t\tminio.PutObjectOptions{ContentType: contentType},\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\n\t\tmylog.Log.WithField(\"size\", n).Info(util.Trace(\"uploaded new file\"))\n\t\treturn &UploadResponse{\n\t\t\tKey: key,\n\t\t\tIsNewObject: true,\n\t\t}, nil\n\t}\n\n\tmylog.Log.WithField(\"key\", key).Info(util.Trace(\"\"))\n\treturn &UploadResponse{\n\t\tKey: key,\n\t\tIsNewObject: false,\n\t}, nil\n}", "func SetPictureHandler(w http.ResponseWriter, r *http.Request) {\n\tdb := Connect()\n\tdefer db.Close()\n\n\tcanAccess, actorAccount := ValidateAuth(db, r, w)\n\tif !canAccess {\n\t\treturn\n\t}\n\n\t// This was a previous attempt when we uploaded via a form (the Moya code in the iOS client still does this).\n\t// However, on iOS, to use an upload task in the background, we need to accept the files like this.\n\t//err := r.ParseMultipartForm(1024 * 1024 * 5)\n\t//if err != nil {\n\t//\tlog.Println(\"failed to parse request\")\n\t//\thttp.Error(w, \"failed to parse request\", http.StatusBadRequest)\n\t//\treturn\n\t//}\n\t//\n\t//file, _, err := r.FormFile(\"file\")\n\t//if err != nil {\n\t//\tlog.Println(\"failed to find file in request\")\n\t//\thttp.Error(w, \"failed to find file\", http.StatusBadRequest)\n\t//\treturn\n\t//}\n\t//defer file.Close()\n\n\tbuf := bytes.NewBuffer(nil)\n\tif _, err := io.Copy(buf, r.Body); err != nil {\n\t\thttp.Error(w, \"failed to copy file\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tpeerId, err := RecordNewPayload(db, actorAccount.Id, buf.Bytes())\n\tif err != nil {\n\t\thttp.Error(w, \"failed to record payload\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr = SendNotificationToAccountId(db, peerId)\n\tif err != nil {\n\t\thttp.Error(w, \"failed to find peer account record\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tWriteBackConnectedResponse(w, db, actorAccount)\n}", "func (g *Ghost) Upload(file string) (upl *corepb.Upload) {\n\treturn\n}", "func PostUpload() error {\n\treturn nil\n}", "func (s *CreateUserSettingsInput) SetUploadAllowed(v string) *CreateUserSettingsInput {\n\ts.UploadAllowed = &v\n\treturn s\n}", "func (c *command) confirmUpload(url string, files files) (bool, error) {\n\tprompt := fmt.Sprintf(\"Uploading the following files to [%s]\\n%s\\n%s\", url, files, msgContinueOrAbort)\n\n\terr := c.Fprintln(prompt)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn strings.ToLower(c.Prompt()) == \"y\", nil\n}", "func Upload(ctx context.Context, p string, userID int, data io.Reader) error {\n\tvar err error\n\tif p, err = validatePath(p); err != nil {\n\t\treturn err\n\t}\n\n\t// identify the source and query that\n\tsources, err := getSourcesForUser(ctx, userID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsplitPath := strings.Split(p, \"/\")\n\tfor _, source := range sources {\n\t\tif splitPath[1] == source.Prefix {\n\t\t\treturn uploadFromSource(ctx, source, strings.Join(splitPath[2:], \"/\"), userID, data)\n\t\t}\n\t}\n\treturn errors.New(\"No such root source\")\n}", "func (a *App) UploadFiles(writer http.ResponseWriter, req *http.Request) {\n\tlog.Info(\"received upload request\")\n\n\tuploadRecord := NewUploadRecord()\n\ta.uploadRecords.Append(uploadRecord)\n\n\tuploadRunningMutex.Lock()\n\tshouldRun := !uploadRunning\n\tuploadRunning = true\n\tuploadRunningMutex.Unlock()\n\n\tif shouldRun {\n\t\tlog.Info(\"starting upload goroutine\")\n\n\t\ta.uploadWait.Add(1)\n\n\t\tgo func() {\n\t\t\tlog.Info(\"running upload goroutine\")\n\n\t\t\tuploadRecord.SetStatus(UploadingStatus)\n\n\t\t\tdefer func() {\n\t\t\t\tuploadRecord.SetCompletionTime()\n\n\t\t\t\tuploadRunningMutex.Lock()\n\t\t\t\tuploadRunning = false\n\t\t\t\tuploadRunningMutex.Unlock()\n\n\t\t\t\ta.uploadWait.Done()\n\t\t\t}()\n\n\t\t\tuploadLogStdoutPath := path.Join(a.LogDirectory, \"uploads.stdout.log\")\n\t\t\tuploadLogStdoutFile, err := os.Create(uploadLogStdoutPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(errors.Wrapf(err, \"failed to open file %s\", uploadLogStdoutPath))\n\t\t\t\tuploadRecord.SetStatus(FailedStatus)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tuploadLogStderrPath := path.Join(a.LogDirectory, \"uploads.stderr.log\")\n\t\t\tuploadLogStderrFile, err := os.Create(uploadLogStderrPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(errors.Wrapf(err, \"failed to open file %s\", uploadLogStderrPath))\n\t\t\t\tuploadRecord.SetStatus(FailedStatus)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tparts := a.uploadCommand()\n\t\t\tcmd := exec.Command(parts[0], parts[1:]...)\n\t\t\tcmd.Stdout = uploadLogStdoutFile\n\t\t\tcmd.Stderr = uploadLogStderrFile\n\n\t\t\tif err = cmd.Run(); err != nil {\n\t\t\t\tlog.Error(errors.Wrap(err, \"error running porklock for uploads\"))\n\t\t\t\tuploadRecord.SetStatus(FailedStatus)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tuploadRecord.SetStatus(CompletedStatus)\n\n\t\t\tlog.Info(\"exiting upload goroutine without errors\")\n\t\t}()\n\t}\n\n\tif err := uploadRecord.MarshalAndWrite(writer); err != nil {\n\t\tlog.Error(err)\n\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t}\n}", "func (fs fsObjects) isMultipartUpload(bucket, prefix string) bool {\n\tuploadsIDPath := pathJoin(fs.fsPath, bucket, prefix, uploadsJSONFile)\n\t_, err := fsStatFile(uploadsIDPath)\n\tif err != nil {\n\t\tif err == errFileNotFound {\n\t\t\treturn false\n\t\t}\n\t\terrorIf(err, \"Unable to access uploads.json \"+uploadsIDPath)\n\t\treturn false\n\t}\n\treturn true\n}", "func UploadAction(w http.ResponseWriter, r *http.Request) {\n\n\tpageVars := PageVars{}\n\taddPageVars(r, &pageVars)\n\n\tif len(pageVars.BName) <= 0 {\n\t\thttp.Redirect(w, r, \"/objectlist?bucketName=\"+pageVars.BName+\"&prefix=\"+pageVars.Prefix+\"&errorM=Invalid bucket name\", http.StatusSeeOther)\n\t} else {\n\t\tbucket := aws.String(pageVars.BName)\n\t\t// Maximum upload of 1024 MB files\n\t\tr.ParseMultipartForm(1024 << 20)\n\n\t\t// Get handler for filename, size and headers\n\t\tfile, handler, err := r.FormFile(\"uploadfile\")\n\n\t\t// close file after func\n\t\tdefer file.Close()\n\n\t\tif err != nil {\n\t\t\thttp.Redirect(w, r, \"/objectlist?bucketName=\"+pageVars.BName+\"&prefix=\"+pageVars.Prefix+\"&errorM=Error uploading the file\", http.StatusSeeOther)\n\t\t} else {\n\t\t\tfn := handler.Filename\n\t\t\tif len(pageVars.Prefix) > 0 {\n\t\t\t\tfn = pageVars.Prefix + \"/\" + fn\n\t\t\t}\n\t\t\tfilename := aws.String(fn)\n\n\t\t\tuploader := s3manager.NewUploader(sess)\n\n\t\t\t_, err = uploader.Upload(&s3manager.UploadInput{\n\t\t\t\tBucket: bucket,\n\t\t\t\tKey: filename,\n\t\t\t\tBody: file,\n\t\t\t})\n\n\t\t\tif err != nil {\n\t\t\t\tif awsErr, ok := err.(awserr.Error); ok {\n\t\t\t\t\thttp.Redirect(w, r, \"/objectlist?bucketName=\"+pageVars.BName+\"&prefix=\"+pageVars.Prefix+\"&errorM=\"+awsErr.Message(), http.StatusSeeOther)\n\t\t\t\t} else {\n\t\t\t\t\thttp.Redirect(w, r, \"/objectlist?bucketName=\"+pageVars.BName+\"&prefix=\"+pageVars.Prefix+\"&errorM=Error in uploading to S3\", http.StatusSeeOther)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thttp.Redirect(w, r, \"/objectlist?bucketName=\"+pageVars.BName+\"&prefix=\"+pageVars.Prefix+\"&successM=Successfully uploaded\", http.StatusSeeOther)\n\t\t\t}\n\t\t}\n\t}\n\n}", "func (s *replayService) Upload(destination string, mode os.FileMode, content []byte) error {\n\ts.storage[destination] = content\n\treturn nil\n}", "func (g GCPClient) UploadFile(src, dst, bucketName string, public bool) error {\n\tlog.Infof(\"Uploading file %s to Google Storage as %s\", src, dst)\n\tf, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tobjectCall := g.storage.Objects.Insert(bucketName, &storage.Object{Name: dst}).Media(f)\n\n\tif public {\n\t\tobjectCall.PredefinedAcl(\"publicRead\")\n\t}\n\n\t_, err = objectCall.Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Infof(\"Upload Complete!\")\n\tfmt.Println(\"gs://\" + bucketName + \"/\" + dst)\n\treturn nil\n}", "func UploadAvatar(c *fiber.Ctx) {\n\tfile, err := c.FormFile(\"file\")\n\n\tif err != err {\n\t\tfmt.Println(err)\n\t}\n\n\timage := helper.UploadImg(file, \"avatar\")\n\n\tc.JSON(ResponseResultSimple{Result: image.URL})\n}", "func UploadRichContent() {}", "func (l *Libvirt) StorageVolUpload(Vol StorageVol, outStream io.Reader, Offset uint64, Length uint64, Flags StorageVolUploadFlags) (err error) {\n\tvar buf []byte\n\n\targs := StorageVolUploadArgs {\n\t\tVol: Vol,\n\t\tOffset: Offset,\n\t\tLength: Length,\n\t\tFlags: Flags,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\n\t_, err = l.requestStream(208, constants.Program, buf, outStream, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (f *Files) UploadREST(rw http.ResponseWriter,r *http.Request){\n\n\tvars := mux.Vars(r)\n\tid := vars[\"id\"]\n\tfn := vars[\"filename\"]\n\n\tf.log.Info(\"handle POST\",\"ID\",id,\"Filename\",fn)\n\n\t// no need to check for invalid id or filename as the mux router will not send requests\n\t// here unless they have the correct parameters\n\tf.SaveFiles(id,fn,r.Body,rw)\n\n\n}", "func (g *gcs) Upload(ctx context.Context, localPath string, remotePath string) (err error) {\n\tgcsObject := g.bucket.Object(remotePath)\n\tgcsWriter := gcsObject.NewWriter(g.context)\n\n\tsourceFile, err := os.Open(localPath)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer sourceFile.Close()\n\n\tif _, err = io.Copy(gcsWriter, sourceFile); err != nil {\n\t\treturn\n\t}\n\n\tif err = gcsWriter.Close(); err != nil {\n\t\tgcsObject.Delete(g.context)\n\t\treturn\n\t}\n\n\tif err = gcsObject.ACL().Set(g.context, storage.AllUsers, storage.RoleReader); err != nil {\n\t\tgcsObject.Delete(g.context)\n\t\treturn\n\t}\n\n\treturn\n}", "func (o *ObjectNode) createMultipleUploadHandler(w http.ResponseWriter, r *http.Request) {\n\n\tvar err error\n\tvar errorCode *ErrorCode\n\n\tdefer func() {\n\t\tif errorCode != nil {\n\t\t\t_ = errorCode.ServeResponse(w, r)\n\t\t\treturn\n\t\t}\n\t}()\n\n\tvar param = ParseRequestParam(r)\n\tif param.Bucket() == \"\" {\n\t\terrorCode = InvalidBucketName\n\t\treturn\n\t}\n\tif param.Object() == \"\" {\n\t\terrorCode = InvalidKey\n\t\treturn\n\t}\n\n\tvar vol *Volume\n\tif vol, err = o.vm.Volume(param.Bucket()); err != nil {\n\t\tlog.LogErrorf(\"createMultipleUploadHandler: load volume fail: requestID(%v) err(%v)\",\n\t\t\tGetRequestID(r), err)\n\t\terrorCode = NoSuchBucket\n\t\treturn\n\t}\n\n\t// system metadata\n\t// Get the requested content-type.\n\t// In addition to being used to manage data types, it is used to distinguish\n\t// whether the request is to create a directory.\n\tcontentType := r.Header.Get(HeaderNameContentType)\n\t// Get request header : content-disposition\n\tcontentDisposition := r.Header.Get(HeaderNameContentDisposition)\n\t// Get request header : Cache-Control\n\tcacheControl := r.Header.Get(HeaderNameCacheControl)\n\tif len(cacheControl) > 0 && !ValidateCacheControl(cacheControl) {\n\t\terrorCode = InvalidCacheArgument\n\t\treturn\n\t}\n\t// Get request header : Expires\n\texpires := r.Header.Get(HeaderNameExpires)\n\tif len(expires) > 0 && !ValidateCacheExpires(expires) {\n\t\terrorCode = InvalidCacheArgument\n\t\treturn\n\t}\n\n\t// Checking user-defined metadata\n\tvar metadata = ParseUserDefinedMetadata(r.Header)\n\n\t// Check 'x-amz-tagging' header\n\tvar tagging *Tagging\n\tif xAmxTagging := r.Header.Get(HeaderNameXAmzTagging); xAmxTagging != \"\" {\n\t\tif tagging, err = ParseTagging(xAmxTagging); err != nil {\n\t\t\terrorCode = InvalidArgument\n\t\t\treturn\n\t\t}\n\t}\n\tvar opt = &PutFileOption{\n\t\tMIMEType: contentType,\n\t\tDisposition: contentDisposition,\n\t\tTagging: tagging,\n\t\tMetadata: metadata,\n\t\tCacheControl: cacheControl,\n\t\tExpires: expires,\n\t}\n\n\tvar uploadID string\n\tif uploadID, err = vol.InitMultipart(param.Object(), opt); err != nil {\n\t\tlog.LogErrorf(\"createMultipleUploadHandler: init multipart fail, requestID(%v) err(%v)\",\n\t\t\tGetRequestID(r), err)\n\t\terrorCode = InternalErrorCode(err)\n\t\treturn\n\t}\n\n\tinitResult := InitMultipartResult{\n\t\tBucket: param.Bucket(),\n\t\tKey: param.Object(),\n\t\tUploadId: uploadID,\n\t}\n\n\tvar bytes []byte\n\tvar marshalError error\n\tif bytes, marshalError = MarshalXMLEntity(initResult); marshalError != nil {\n\t\tlog.LogErrorf(\"createMultipleUploadHandler: marshal result fail, requestID(%v) err(%v)\",\n\t\t\tGetRequestID(r), err)\n\t\terrorCode = InternalErrorCode(marshalError)\n\t\treturn\n\t}\n\n\t// set response header\n\tw.Header()[HeaderNameContentType] = []string{HeaderValueContentTypeXML}\n\tw.Header()[HeaderNameContentLength] = []string{strconv.Itoa(len(bytes))}\n\tif _, err = w.Write(bytes); err != nil {\n\t\tlog.LogErrorf(\"createMultipleUploadHandler: write response body fail, requestID(%v) err(%v)\",\n\t\t\tGetRequestID(r), err)\n\t}\n\treturn\n}", "func (c *s3Client) ShareUpload(isRecursive bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) {\n\tbucket, object := c.url2BucketAndObject()\n\tp := minio.NewPostPolicy()\n\tif e := p.SetExpires(time.Now().UTC().Add(expires)); e != nil {\n\t\treturn nil, probe.NewError(e)\n\t}\n\tif strings.TrimSpace(contentType) != \"\" || contentType != \"\" {\n\t\t// No need to verify for error here, since we have stripped out spaces.\n\t\tp.SetContentType(contentType)\n\t}\n\tif e := p.SetBucket(bucket); e != nil {\n\t\treturn nil, probe.NewError(e)\n\t}\n\tif isRecursive {\n\t\tif e := p.SetKeyStartsWith(object); e != nil {\n\t\t\treturn nil, probe.NewError(e)\n\t\t}\n\t} else {\n\t\tif e := p.SetKey(object); e != nil {\n\t\t\treturn nil, probe.NewError(e)\n\t\t}\n\t}\n\tm, e := c.api.PresignedPostPolicy(p)\n\treturn m, probe.NewError(e)\n}", "func upload(w http.ResponseWriter, r *http.Request) {\n\t// Gets upload path and validates it\n\tpath, _ := url.PathUnescape(r.Header.Get(\"rei-path\"))\n\treader, _ := r.MultipartReader()\n\tpart, _ := reader.NextPart()\n\tfp, err := validPath(path)\n\tif err != nil {\n\t\tsendHTTPResp(w, 500, err)\n\t\treturn\n\t}\n\n\t// Copies the src file to the dst\n\tdst, _ := os.Create(fp)\n\t_, err = io.Copy(dst, part)\n\tif err != nil {\n\t\tsendHTTPResp(w, 500, err)\n\t\treturn\n\t}\n\tw.Write([]byte(\"ok\"))\n}", "func UploadAvatarBook(c echo.Context) error {\n\t// Read form fields\n\tidBook := c.FormValue(\"id\")\n\tbook := models.Book{}\n\n\t// get connection\n\tdb := provider.GetConnection()\n\tdefer db.Close()\n\n\t// Validation user exist\n\tif db.First(&book, \"id = ?\", idBook).RecordNotFound() {\n\t\treturn c.JSON(http.StatusOK, utilities.Response{\n\t\t\tMessage: fmt.Sprintf(\"No se encontró el registro con id %d\", idBook),\n\t\t})\n\t}\n\n\t// Source\n\tfile, err := c.FormFile(\"avatar\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tsrc, err := file.Open()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer src.Close()\n\n\t// Destination\n\tccc := sha256.Sum256([]byte(string(book.ID)))\n\tname := fmt.Sprintf(\"%x%s\", ccc, filepath.Ext(file.Filename))\n\tavatarSRC := \"static/books/\" + name\n\tdst, err := os.Create(avatarSRC)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer dst.Close()\n\tbook.Avatar = avatarSRC\n\n\t// Copy\n\tif _, err = io.Copy(dst, src); err != nil {\n\t\treturn err\n\t}\n\n\t// Update database user\n\tif err := db.Model(&book).Update(book).Error; err != nil {\n\t\treturn err\n\t}\n\n\t// Return response\n\treturn c.JSON(http.StatusOK, utilities.Response{\n\t\tSuccess: true,\n\t\tData: book.ID,\n\t\tMessage: fmt.Sprintf(\"El avatar del libro %s, se subió correctamente\", book.Name),\n\t})\n}", "func isBlob(req *http.Request) bool {\n\telem := strings.Split(req.URL.Path, \"/\")\n\telem = elem[1:]\n\tif elem[len(elem)-1] == \"\" {\n\t\telem = elem[:len(elem)-1]\n\t}\n\tif len(elem) < 3 {\n\t\treturn false\n\t}\n\treturn elem[len(elem)-2] == \"blobs\" || (elem[len(elem)-3] == \"blobs\" &&\n\t\telem[len(elem)-2] == \"uploads\")\n}", "func (u *uploader) Upload(ctx context.Context, r *http.Request, field string) error {\n\timg, err := imageupload.Process(r, field)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger.Infof(\"IMAGE: %+v\", img)\n\n\tthumb, err := imageupload.ThumbnailPNG(img, 250, 250)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := ioutil.WriteFile(\"./store/tmp.png\", thumb.Data, 0644); err != nil {\n\t\treturn err\n\t}\n\n\tlogger.Infow(\"file saved\", \"file\", \"./store/tmp.png\", \"request-id\", middleware.GetReqID(ctx))\n\treturn nil\n}", "func checkUploadHandler(w http.ResponseWriter, r *http.Request) {\n\tuser := oauth.GetUserOrFail(w, r)\n\tif user == nil {\n\t\thttp.Error(w, \"\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tchunkPath := filepath.Join(conf.UploadDir, user.(*nano.User).Id, \"incomplete\", r.FormValue(\"flowFilename\"), r.FormValue(\"flowChunkNumber\"))\n\tif _, err := os.Stat(chunkPath); err != nil {\n\t\thttp.Error(w, \"chunk not found\", http.StatusSeeOther)\n\t\treturn\n\t}\n}", "func (c *Client) Upload(src []byte, dest string) error {\n\n\tdestUrl, err := url.Parse(fmt.Sprintf(\"files/%s/%s\", c.Username, dest))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, _, err = c.sendRequest(\"PUT\", c.Url.ResolveReference(destUrl).String(), src, nil, nil)\n\n\treturn err\n}", "func addImage(w http.ResponseWriter, req *http.Request) {\n\n\t// Manage Cors\n\tsetCors(&w)\n\tif req.Method == \"OPTIONS\" {\n\t\treturn\n\t}\n\n\tclaims, err := authRequest(req)\n\tif err != nil {\n\t\tlogger.Error(\"Unauthorized request to upload sending 401: %v\", err)\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(\"401 - Unauthorized request, ensure you sign in and obtain the jwt auth token\"))\n\t\treturn\n\t}\n\n\t// attempt to retrieve file from form\n\timg, imgHeader, err := req.FormFile(\"image\")\n\tif err != nil {\n\t\tlogger.Error(\"failed to read file sending 500: %v\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"500 - Failed to read file, try again later\"))\n\t\treturn\n\t}\n\tdefer img.Close()\n\n\t// Read small part of file to ID content type\n\tbuffer := make([]byte, 512)\n\t_, err = img.Read(buffer)\n\tif err != nil {\n\t\tlogger.Error(\"failed to validate file type sending 400: %v\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"400 - Failed to validate file type, ensure the file is correctly formatted as a jpeg (jpg) or png\"))\n\t\treturn\n\t}\n\n\t// Read enough of file to determine type\n\tfileType := http.DetectContentType(buffer)\n\n\t// Reset the pointer location for writing later\n\timg.Seek(0, 0)\n\n\t// Validate Content-Type and image type\n\tcontentType := req.Header.Get(\"Content-Type\")\n\tif !strings.Contains(contentType, \"multipart/form-data\") || (fileType != \"image/jpeg\" && fileType != \"image/png\") {\n\t\tlogger.Error(\"file type failure not accepted sending 400: %v\", err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"400 - Failed to upload, please use multipart form data with an image of type jpeg (jpg) or png\"))\n\t\treturn\n\t}\n\n\t// Generate file extension based on data type\n\tfileExt := strings.Split(fileType, \"/\")[1]\n\n\tuid := claims.Uid\n\n\t// default to not shareable unless explicitly false\n\tshareable := false\n\tif req.FormValue(\"shareable\") == \"true\" {\n\t\tshareable = true\n\t}\n\n\t// ensure storage directory for the user exists\n\terr = os.MkdirAll(fmt.Sprintf(\"./%s/%v\", IMAGE_DIR, uid), os.ModePerm)\n\tif err != nil {\n\t\tlogger.Error(\"failed to establish image directory: %v\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"500 - Failed to read file, try again later\"))\n\t\treturn\n\t}\n\n\t// Determine if filename exists\n\ttitle := req.FormValue(\"title\")\n\tif len(title) == 0 {\n\t\ttitle = imgHeader.Filename\n\t}\n\n\t// Manually assign extension even if one is already there\n\ttitle = fmt.Sprintf(\"%s.%s\", strings.Split(title, \".\")[0], fileExt)\n\n\t// Prepare image meta for SQL storage\n\timageData := Image{\n\t\tUid: int32(uid),\n\t\tTitle: title,\n\t\tSize: int32(imgHeader.Size),\n\t\tRef: \"\", // placeholder reference for update after id is assigned to ensure unique filename\n\t\tShareable: shareable,\n\t\tEncoding: fileType,\n\t}\n\n\t// Insert image data and retrieve unique id\n\timageData.Id, err = AddImageData(imageData)\n\tif err != nil {\n\t\tlogger.Error(\"failed to add image meta: %v\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"500 - Failed to add image meta, try again later\"))\n\t\treturn\n\t}\n\n\t// Get REF_URL\n\trefUrl := os.Getenv(\"REF_URL\")\n\tif len(refUrl) == 0 {\n\t\trefUrl = REF_URL\n\t}\n\n\t// Generate file reference string with unique file name in the format of IMAGE_DIR/UID/ID.ext\n\timageData.Ref = fmt.Sprintf(\"%s/%s/%v/%v.%v\", refUrl, IMAGE_DIR, imageData.Uid, imageData.Id, fileExt)\n\n\t// Update table with dynamic image reference\n\t// This is can be extended to support third party storage solutions\n\terr = UpdateImageData(imageData)\n\tif err != nil {\n\t\tlogger.Error(\"failed to update metadata with image reference: %v\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"500 - Failed to update file referece in database, try again later\"))\n\n\t\tDeleteImageData(imageData) // Clean DB for unsuccessful update\n\n\t\treturn\n\t}\n\n\t// Generate local file reference string\n\tfileRefStr := fmt.Sprintf(\"./%s/%v/%v.%v\", IMAGE_DIR, imageData.Uid, imageData.Id, fileExt)\n\n\t// create file with reference string for writing\n\tfileRef, err := os.Create(fileRefStr)\n\tif err != nil {\n\t\tlogger.Error(\"failed to create file reference: %v\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"500 - Failed to create file reference, try again later\"))\n\n\t\tDeleteImageData(imageData) // Clean DB for unsuccessful update\n\t\treturn\n\t}\n\n\t// save the file at the reference\n\t_, err = io.Copy(fileRef, img)\n\tif err != nil {\n\t\tlogger.Error(\"failed to save image: %v\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"500 - Failed to save file reference, try again later\"))\n\n\t\tDeleteImageData(imageData) // Clean DB for unsuccessful update\n\t\treturn\n\t}\n\n\t// marshal response in json\n\tjs, err := json.Marshal(imageData)\n\tif err != nil {\n\t\tlogger.Error(\"failed to marshal json sending 500: %v\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"500 - Something went wrong on our end\"))\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write(js)\n\tlogger.Info(\"Successfully uploaded (Title: %v - Size: %v - Type: %v)\", title, imgHeader.Size, fileType)\n\treturn\n}", "func (msg *Message) UploadPhoto(r io.Reader, caption string) Uploadable {\n\treturn &uploadPhotoReply{\n\t\tMessage: msg.ReplyWith(\"\"),\n\n\t\tr: r,\n\t\tcaption: caption,\n\n\t\tbot: msg.bot,\n\t}\n}", "func (d *Dao) UploadByFile(c context.Context, imgpath string) (location string, err error) {\n\tdata, err := ioutil.ReadFile(imgpath)\n\tif err != nil {\n\t\tlog.Error(\"UploadByFile ioutil.ReadFile error (%v) | imgpath(%s)\", err, imgpath)\n\t\treturn\n\t}\n\tfileType := http.DetectContentType(data)\n\tif fileType != \"image/jpeg\" && fileType != \"image/png\" {\n\t\tlog.Error(\"file type not allow file type(%s)\", fileType)\n\t\terr = ecode.CreativeArticleImageTypeErr\n\t}\n\tbody := new(bytes.Buffer)\n\t_, err = body.Write(data)\n\tif err != nil {\n\t\tlog.Error(\"body.Write error (%v)\", err)\n\t\treturn\n\t}\n\treq, err := http.NewRequest(_method, _url, body)\n\tif err != nil {\n\t\tlog.Error(\"http.NewRequest error (%v) | fileType(%s)\", err, fileType)\n\t\treturn\n\t}\n\texpire := time.Now().Unix()\n\tauthorization := authorize(_key, _secret, _method, _bucket, expire)\n\treq.Header.Set(\"Host\", _url)\n\treq.Header.Add(\"Date\", fmt.Sprint(expire))\n\treq.Header.Add(\"Authorization\", authorization)\n\treq.Header.Add(\"Content-Type\", fileType)\n\t// timeout\n\tc, cancel := context.WithTimeout(c, time.Duration(d.c.BFS.Timeout))\n\treq = req.WithContext(c)\n\tdefer cancel()\n\tresp, err := d.client.Do(req)\n\tif err != nil {\n\t\tlog.Error(\"d.Client.Do error(%v) | url(%s)\", err, _url)\n\t\terr = ecode.BfsUploadServiceUnavailable\n\t\treturn\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\tlog.Error(\"Upload http.StatusCode nq http.StatusOK (%d) | url(%s)\", resp.StatusCode, _url)\n\t\terr = errUpload\n\t\treturn\n\t}\n\theader := resp.Header\n\tcode := header.Get(\"Code\")\n\tif code != strconv.Itoa(http.StatusOK) {\n\t\tlog.Error(\"strconv.Itoa err, code(%s) | url(%s)\", code, _url)\n\t\terr = errUpload\n\t\treturn\n\t}\n\tlocation = header.Get(\"Location\")\n\treturn\n}", "func getPMPhotoUploader(gid int) uploader {\n\tv := url.Values{}\n\tif gid != 0 {\n\t\tv.Set(\"group_id\", strconv.Itoa(gid))\n\t}\n\treturn &pmPhotoUpload{\n\t\tbaseUpload: &baseUpload{\n\t\t\tmUp: pmPhotoUploadServer,\n\t\t\tf: fileFieldName,\n\t\t\tv: v,\n\t\t\tlimit: VK_MAX_PHOTOS,\n\t\t},\n\t\tUploadWallPhotos: &UploadWallPhotos{},\n\t}\n}", "func UploadMobileHandler(c *gin.Context) {\n\n\terr := c.Request.ParseMultipartForm(1000)\n\n\tform, err := c.MultipartForm()\n\tif err != nil {\n\t\tc.String(http.StatusBadRequest, fmt.Sprintf(\"get form err: %s\", err.Error()))\n\t\tfmt.Println(\"error getting multipartform\", err)\n\t\tpanic(err)\n\t}\n\n\tfiles := form.File[\"files\"]\n\tinfoArray := form.Value[\"infoArray\"]\n\n\tfor i, file := range files {\n\t\tfilename := filepath.Base(file.Filename)\n\t\tinfo := infoArray[i]\n\n\t\tvar raw map[string]interface{}\n\t\tif err := json.Unmarshal([]byte(info), &raw); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\terr := MyStore.CreatePhotoFromMobile(filename, file, raw)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\t// c.String(http.StatusOK, fmt.Sprintf(\"uploaded %d files!\", len(files)))\n\tc.Data(http.StatusOK, \"text/html; charset=utf-8\", []byte(fmt.Sprintf(\"uploaded %d files! <a href='http://localhost:3000'>back</a>\", len(files))))\n}", "func uploadBlob(ctx context.Context, img imageSpec, auth string, body []byte) error {\n\tuploadURL, err := getUploadLocation(ctx, img, auth)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif strings.ContainsRune(uploadURL, '?') {\n\t\treturn fmt.Errorf(\"upload url contains '?': %q\", uploadURL)\n\t}\n\tuploadURL += fmt.Sprintf(\"?digest=sha256:%x\", sha256.Sum256(body))\n\treq, err := http.NewRequestWithContext(ctx, http.MethodPut, uploadURL, bytes.NewReader(body))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Authorization\", \"Basic \"+auth)\n\treq.Header.Set(\"Content-Type\", \"application/octet-stream\")\n\treq.ContentLength = int64(len(body))\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusCreated {\n\t\tb := new(bytes.Buffer)\n\t\tio.Copy(b, io.LimitReader(resp.Body, 1024))\n\t\treturn fmt.Errorf(\"unexpected status on blob upload %q: %v\\n%s\", req.URL, resp.Status, b.Bytes())\n\t}\n\treturn nil\n}", "func SubirAvatar(w http.ResponseWriter, r *http.Request) {\n\n\tfile, handler, err := r.FormFile(\"avatar\")\n\tswitch err {\n\tcase nil:\n\t\t// do nothing\n\tcase http.ErrMissingFile:\n\t\thttp.Error(w, \"No se encontro la KEY asociada al archivo! http.ErrMissingFile \"+err.Error(), http.StatusBadRequest)\n\t\tlog.Println(\"http.ErrMissingFile\")\n\t\treturn\n\tdefault:\n\t\thttp.Error(w, \"Ocurrió un error al obtener el archivo \"+err.Error(), http.StatusBadRequest)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tvar array = strings.Split(handler.Filename, \".\")\n\tvar extension = strings.ToLower(array[len(array)-1])\n\n\tif extension == \"jpg\" {\n\t\textension = \"jpeg\"\n\t}\n\n\tmached, err := regexp.MatchString(\"jpeg|png|gif\", extension)\n\n\tif !mached {\n\t\textension = \"\"\n\t} else {\n\t\textension = \".\" + extension\n\t}\n\n\tvar archivo string = \"uploads/avatars/\" + IDUsuario + extension\n\n\tf, err := os.OpenFile(archivo, os.O_WRONLY|os.O_CREATE, 0666)\n\tif err != nil {\n\t\thttp.Error(w, \"Error al subir la imagen ! \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t_, err = io.Copy(f, file)\n\tif err != nil {\n\t\thttp.Error(w, \"Error al copiar la imagen ! \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar usuario models.Usuario\n\tvar status bool\n\n\tusuario.Avatar = IDUsuario + extension\n\tstatus, err = bd.ModificoRegistro(usuario, IDUsuario)\n\tif err != nil || status == false {\n\t\thttp.Error(w, \"Error al grabar el avatar en la BD ! \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusCreated)\n\t// w.Write([]byte(`Test`))\n}", "func TestUpload(t *testing.T) {\n\toss := NewService(\"<<api key>>\", \"<<secret key>>\")\n\toss.SetEndPoint(\"oss-cn-shanghai.aliyuncs.com\")\n\toss.SetBucket(\"dong-feng\")\n\n\topts1 := &UploadOptions{\n\t\tObjectName: \"test\",\n\t\tPublic: true,\n\t\tIsFolder: true,\n\t}\n\n\tresp := oss.Upload(opts1)\n\tif resp.Error != nil {\n\t\tt.Error(resp.Error)\n\t}\n\n\topts2 := &UploadOptions{\n\t\tObjectName: \"../test/index.html\",\n\t\tPublic: true,\n\t\tParentFolder: \"test\",\n\t}\n\n\tresp = oss.Upload(opts2)\n\tif resp.Error != nil {\n\t\tt.Error(resp.Error)\n\t}\n}", "func TestUpload(t *testing.T) {\n\tdb := sql.NewDb()\n\tif err := db.Initialize(); err != nil {\n\t\tt.Error(err)\n\t}\n\tprofile, err := db.ProfileTable.GetProfileImage(\"freelancer\", \"ashkan\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif string(profile.Data) != \"aaa\" {\n\t\tt.Errorf(\"Error : %s\", string(profile.Data))\n\t}\n}", "func (cl Client) AnonymousUpload(path string) (Response, error) {\n\tvar err error\n\tir := Response{}\n\treq, err := cl.NewFileUploadRequest(\n\t\tImageBase,\n\t\tnil,\n\t\t\"image\",\n\t\t\"./test.png\",\n\t)\n\tauthHeader := []string{\"Client-ID \" + cl.ClientID}\n\treq.Header.Add(\"Authorization\", strings.Join(authHeader, \" \"))\n\tresponse, err := cl.Do(req)\n\tif err != nil {\n\t\treturn ir, err\n\t}\n\tdefer response.Body.Close()\n\tbody, err := ioutil.ReadAll(response.Body)\n\n\terr = json.Unmarshal(body, &ir)\n\tif err != nil {\n\t\treturn ir, err\n\t}\n\treturn ir, err\n}", "func (p *FileInf) initResumableUpload(metadata map[string]interface{}) string {\r\n\ttokenparams := url.Values{}\r\n\ttokenparams.Set(\"fields\", \"id,mimeType,name,parents\")\r\n\tmeta, _ := json.Marshal(metadata)\r\n\tr := &RequestParams{\r\n\t\tMethod: \"POST\",\r\n\t\tAPIURL: resumableUrl + \"&\" + tokenparams.Encode(),\r\n\t\tData: bytes.NewBuffer(meta),\r\n\t\tContenttype: \"application/json; charset=UTF-8\",\r\n\t\tAccesstoken: p.Accesstoken,\r\n\t\tDtime: 10,\r\n\t}\r\n\tres, err := r.FetchAPIres()\r\n\tif res.StatusCode != 200 || err != nil {\r\n\t\tfmt.Fprintf(os.Stderr, \"Error: %v\\n%v\\n\", err, res)\r\n\t\tos.Exit(1)\r\n\t}\r\n\treturn res.Header[\"Location\"][0]\r\n}" ]
[ "0.6137154", "0.608181", "0.60776865", "0.5972178", "0.5893536", "0.5838742", "0.5828034", "0.5776307", "0.568447", "0.5679493", "0.5652551", "0.563114", "0.5607", "0.5593149", "0.5588747", "0.5576847", "0.55685544", "0.55474", "0.55472434", "0.5525405", "0.5523969", "0.55160797", "0.548961", "0.5475459", "0.54304725", "0.54091746", "0.5402064", "0.5383284", "0.5378734", "0.53712076", "0.5339728", "0.53283185", "0.53128624", "0.52920985", "0.5280003", "0.5278593", "0.52760637", "0.5273246", "0.52516294", "0.52348644", "0.522266", "0.52213466", "0.52131444", "0.5210635", "0.5209919", "0.51981515", "0.51953655", "0.51799977", "0.5163709", "0.5155544", "0.51539505", "0.51523", "0.51499194", "0.514646", "0.5144687", "0.5128697", "0.512606", "0.5122432", "0.5122256", "0.51199096", "0.5117638", "0.51126647", "0.511085", "0.5105264", "0.51021147", "0.50984395", "0.5094743", "0.5094591", "0.50924426", "0.5090923", "0.5086034", "0.5085428", "0.50847024", "0.5079525", "0.50791", "0.5072276", "0.50667757", "0.50517005", "0.505079", "0.50504076", "0.504994", "0.504909", "0.50447375", "0.5042027", "0.5028915", "0.5025691", "0.5020254", "0.50181127", "0.4993673", "0.49890697", "0.49872553", "0.4986855", "0.49784368", "0.4970672", "0.49660307", "0.4957706", "0.49556968", "0.49477074", "0.4947705", "0.4941881" ]
0.6866995
0
ChangePermissions allows users to change the visibility of photo between public (everyone can see) and private (only you can see)
func ChangePermissions(w http.ResponseWriter, r *http.Request) { // Identify who the user is username := r.Context().Value("username") if username == nil { w.WriteHeader(http.StatusInternalServerError) return } // Get userid for user userID, err := GetUserGUID(username.(string)) if err != nil { w.Write([]byte(err.Error())) w.WriteHeader(http.StatusInternalServerError) return } // Retrieve PhotoID and IsPublic from JSON request body var requestedPhoto Photo err = json.NewDecoder(r.Body).Decode(&requestedPhoto) if err != nil { w.Write([]byte("Missing PhotoID or IsPublic attribute")) w.WriteHeader(http.StatusBadRequest) return } if requestedPhoto.ID == "" { w.Write([]byte("PhotoID not provided in request body")) w.WriteHeader(http.StatusBadRequest) return } // make sure photo exists var photos []Photo DB.Where(&Photo{ID: requestedPhoto.ID}).Find(&photos) if len(photos) > 1 { w.Write([]byte("Multiple photos returned")) w.WriteHeader(http.StatusInternalServerError) } if len(photos) == 0 { w.Write([]byte("No photos returned")) w.WriteHeader(http.StatusInternalServerError) return } photo := photos[0] // Make sure photo belongs to user if photo.UserID != *userID { w.Write([]byte("photo does not belong to user")) w.WriteHeader(http.StatusBadRequest) return } // If permission has changed photo needs to be updated in photos tabe and object needs to be moved between buckets if photo.IsPublic != requestedPhoto.IsPublic { // If permission has gone from public to private if photo.IsPublic == true && requestedPhoto.IsPublic == false { err = moveBuckets(r.Context(), PUBLIC_BUCKET_NAME, *userID, photo.ID) if err != nil { w.Write([]byte(err.Error())) w.WriteHeader(http.StatusInternalServerError) return } } // If permission has gone from private to public if photo.IsPublic == false && requestedPhoto.IsPublic == true { err = moveBuckets(r.Context(), *userID, PUBLIC_BUCKET_NAME, photo.ID) if err != nil { w.Write([]byte(err.Error())) w.WriteHeader(http.StatusInternalServerError) return } } // change permission for photo in photos table photo.IsPublic = requestedPhoto.IsPublic DB.Save(&photo) } w.Write([]byte("photo visibility has been changed")) w.WriteHeader(http.StatusOK) return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (uc *Userclient) iEditPermissions(args *userproto.EditPermissionsArgs, reply *userproto.EditPermissionsReply) error {\r\n\t//if args.permission = nil then we are removing people from the permission list\r\n\t//also gotta check if we are adding a user to the permission list if the user actually exists\r\n\t//otherwise if the user already exists on the list we just change the permission to the new value\r\n\t//may want to change permissions to better reflect the scaling of them or something gah\r\n\r\n\t//get the current directory because we can only edit permissions of a file when we are in it's directory\r\n\tcurrDir, wdErr := os.Getwd()\r\n\tif wdErr != nil {\r\n\t\treturn wdErr\r\n\t}\r\n\t//strip the path down to only the path after the WhiteBoard file, since the rest is not consistant computer to computer\r\n\tpaths := strings.SplitAfterN(currDir, \"WhiteBoard\", -1)\r\n\t//create the filepath to the actula file \r\n\tfilepath := paths[1] + \"/\" + args.Filepath\r\n\t//find out the key from the FileKeyMap\r\n\tkeyperm, exists := uc.fileKeyMap[filepath]\r\n\tif exists != true {\r\n\t\treply.Status = userproto.ENOSUCHFILE\r\n\t\treturn nil\r\n\t}\r\n\tkey := keyperm.Key\r\n\t//actually get the current permissions info from the server\r\n\t//LATER: can also cache this info if we are acessing it frequently to reduce RPC calls\r\n\t//chances are in real life however that this won't be acessed very frequently from any particular user\r\n\t//so may be safe to ignore that case\r\n\tjfile, getErr := uc.midclient.Get(key, uc.user.Username)\r\n\tif getErr != nil {\r\n\t\treturn getErr\r\n\t}\r\n\t//unmarshal that shit\r\n\tvar file storageproto.SyncFile\r\n\tfileBytes := []byte(jfile)\r\n\tunmarshalErr := json.Unmarshal(fileBytes, &file)\r\n\tif unmarshalErr != nil {\r\n\t\treturn unmarshalErr\r\n\t}\r\n\r\n\t//get the current permissions\r\n\t//we don't need to lock anything while changing the permissions because only the owner of a particular file can change the permissions, \r\n\t//which means that there won't be any instance where two people are changing the same permissions at once\r\n\tpermissions := file.Permissions\r\n\r\n\t//go through all the users\r\n\tfor i := 0; i < len(args.Users); i++ {\r\n\t\t_, exists := permissions[args.Users[i]]\r\n\t\t//if the dude already exists then just change the permissions\r\n\t\tif exists == true {\r\n\t\t\t//if the permissions is NONE then we just remove the dude from the list\r\n\t\t\tif args.Permission == storageproto.NONE {\r\n\t\t\t\tdelete(permissions, args.Users[i])\r\n\t\t\t} else {\r\n\t\t\t\tpermissions[args.Users[i]] = args.Permission\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\t//otherwise we have to check if the dude is a valid dude\r\n\t\t\t_, exists := uc.midclient.Get(args.Users[i], \"\")\r\n\t\t\t//if he is then we can add him to the list\r\n\t\t\tif exists != nil {\r\n\t\t\t\t//if the permission is NONE then just don't add him\r\n\t\t\t\tif args.Permission != storageproto.NONE {\r\n\t\t\t\t\tpermissions[args.Users[i]] = args.Permission\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t//we are done so the permissions are changed and we need to update the server\r\n\tfile.Permissions = permissions\r\n\tfilejson, marshalErr := json.Marshal(file)\r\n\tif marshalErr != nil {\r\n\t\treturn marshalErr\r\n\t}\r\n\r\n\terr := uc.midclient.Put(key, string(filejson), uc.user.Username)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\treply.Status = userproto.OK\r\n\r\n\treturn nil\r\n}", "func (uc *Userclient) EditPermissions(args *userproto.EditPermissionsArgs, reply *userproto.EditPermissionsReply) error {\r\n\treturn uc.iEditPermissions(args, reply)\r\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 (c *Client) ModifyImageSharePermission(request *ModifyImageSharePermissionRequest) (response *ModifyImageSharePermissionResponse, err error) {\n return c.ModifyImageSharePermissionWithContext(context.Background(), request)\n}", "func changePermission(db *sqlite.Driver, acct *Account, newPerm PermLevel) (*Account, error) {\n\tvar err error\n\tvar stmt = fmt.Sprintf(\"update %s set permission_level = ? where id = ?\", tableName)\n\tif _, err = db.Exec(stmt, newPerm, acct.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\tacct.PermLevel = newPerm\n\treturn acct, nil\n}", "func ChangePermission(directory string) error {\n\treturn filepath.Walk(directory, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif info.Mode().Perm() != file.DefaultPermissionOctal {\n\t\t\treturn os.Chmod(path, file.DefaultPermissionOctal)\n\t\t}\n\t\treturn nil\n\t})\n}", "func (k Key) SetPermissions(value uint32) {\n\tk[12] = byte(value >> 24)\n\tk[13] = byte(value >> 16)\n\tk[14] = byte(value >> 8)\n\tk[15] = byte(value)\n}", "func setTestPermissions() {\n\tgitPerms := []string{\"asherhawk\"}\n\tallPerms := []string{\"duncanblack\"}\n\tconfig.Permissions = map[string][]string{\"all\": allPerms, \"git\": gitPerms}\n}", "func TaggeePermissions(taggee string, switchTo bool) error {\n\tstmt, err := mysqlBus.DB.Prepare(\"UPDATE Tag SET status = ? WHERE username_taggee = ? \")\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = stmt.Exec(switchTo, taggee)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n\n}", "func (a PermissionsAPI) replacePermissions(securable, name string, list PermissionsList) error {\n\texisting, err := a.getPermissions(securable, name)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn a.updatePermissions(securable, name, list.diff(existing))\n}", "func (res *GitRes) SetAccess(dstIsPublic bool) error {\n\tmeta, err := res.GetMetaX()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif meta.IsPublic == dstIsPublic {\n\t\treturn nil\n\t}\n\n\tsrcIdxGF, srcAppGF := res.GetPublicGitFile()\n\tdstIdx, dstApp := res.GetPrivateKeyPath()\n\n\tif meta.IsPublic == false {\n\t\tsrcIdxGF, srcAppGF = res.GetPrivateGitFile()\n\t\tdstIdx, dstApp = res.GetPublicKeyPath()\n\t}\n\n\tif err := srcAppGF.CopyTo(dstApp); err != nil {\n\t\treturn err\n\t}\n\n\tif err := srcIdxGF.CopyTo(dstIdx); err != nil {\n\t\treturn err\n\t}\n\n\tif derr2 := srcAppGF.Delete(); derr2 != nil {\n\t\tlog.Error(derr2)\n\t}\n\n\tif derr1 := srcIdxGF.Delete(); derr1 != nil {\n\t\tlog.Error(derr1)\n\t}\n\n\tidxLP, _ := res.GetFilePathInCache()\n\tos.Remove(idxLP)\n\t// os.Remove(appLP)\n\n\treturn nil\n}", "func setFilePermissions(path string, p FilePermissions) error {\n\tvar err error\n\tuid, gid := os.Getuid(), os.Getgid()\n\n\tif p.User() != \"\" {\n\t\tif uid, err = strconv.Atoi(p.User()); err == nil {\n\t\t\tgoto GROUP\n\t\t}\n\n\t\t// Try looking up the user by name\n\t\tif u, err := user.Lookup(p.User()); err == nil {\n\t\t\tuid, _ = strconv.Atoi(u.Uid)\n\t\t\tgoto GROUP\n\t\t}\n\n\t\treturn fmt.Errorf(\"invalid user specified: %v\", p.User())\n\t}\n\nGROUP:\n\tif p.Group() != \"\" {\n\t\tif gid, err = strconv.Atoi(p.Group()); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid group specified: %v\", p.Group())\n\t\t}\n\t}\n\tif err := os.Chown(path, uid, gid); err != nil {\n\t\treturn fmt.Errorf(\"failed setting ownership to %d:%d on %q: %s\",\n\t\t\tuid, gid, path, err)\n\t}\n\n\tif p.Mode() != \"\" {\n\t\tmode, err := strconv.ParseUint(p.Mode(), 8, 32)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid mode specified: %v\", p.Mode())\n\t\t}\n\t\tif err := os.Chmod(path, os.FileMode(mode)); err != nil {\n\t\t\treturn fmt.Errorf(\"failed setting permissions to %d on %q: %s\",\n\t\t\t\tmode, path, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func SetPermission(fileID, email, perm string) (err error) {\n\tcnt := auth.GetClient()\n\n\tsrv, err := drive.New(cnt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprf, err := GetUserDoc(fileID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif prf.Owner1 == email || prf.Owner2 == email {\n\t\ttemp, err := srv.Permissions.GetIdForEmail(email).Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = srv.Permissions.Update(fileID, temp.Id, &drive.Permission{\n\t\t\tValue: email,\n\t\t\tRole: perm,\n\t\t\tType: \"user\",\n\t\t}).Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t_, err := srv.Permissions.Insert(fileID, &drive.Permission{\n\t\t\tValue: email,\n\t\t\tRole: perm,\n\t\t\tType: \"user\",\n\t\t}).SendNotificationEmails(false).Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func modifyImageIamPolicy(c *cli.Context, w io.Writer, action string) error {\n\terr := checkArgCount(c, 1)\n\tif err != nil {\n\t\treturn err\n\t}\n\timageID := c.Args()[0]\n\tprincipal := c.String(\"principal\")\n\trole := c.String(\"role\")\n\n\tif !c.GlobalIsSet(\"non-interactive\") {\n\t\tvar err error\n\t\tprincipal, err = askForInput(\"Principal: \", principal)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(principal) == 0 {\n\t\treturn fmt.Errorf(\"Please provide principal\")\n\t}\n\n\tif !c.GlobalIsSet(\"non-interactive\") {\n\t\tvar err error\n\t\trole, err = askForInput(\"Role: \", role)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(role) == 0 {\n\t\treturn fmt.Errorf(\"Please provide role\")\n\t}\n\n\tclient.Photonclient, err = client.GetClient(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar delta photon.PolicyDelta\n\tdelta = photon.PolicyDelta{Principal: principal, Action: action, Role: role}\n\ttask, err := client.Photonclient.Images.ModifyIam(imageID, &delta)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = waitOnTaskOperation(task.ID, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif utils.NeedsFormatting(c) {\n\t\tpolicy, err := client.Photonclient.Images.GetIam(imageID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tutils.FormatObject(policy, w, c)\n\t}\n\n\treturn 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 (r *ProjectsService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *ProjectsTestIamPermissionsCall {\n\tc := &ProjectsTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\tc.testiampermissionsrequest = testiampermissionsrequest\n\treturn c\n}", "func (r *ProjectsService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *ProjectsTestIamPermissionsCall {\n\tc := &ProjectsTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\tc.testiampermissionsrequest = testiampermissionsrequest\n\treturn c\n}", "func (a *AgentServer) updatePermissions(user *user.User) error {\n\t// Tests may provide a testPermissions function to test potentially\n\t// vulnerable moments during permission updating.\n\ttestPermissions := func() {\n\t\tif a.testPermissions != nil {\n\t\t\ta.testPermissions()\n\t\t}\n\t}\n\n\ttestPermissions()\n\n\tuid, err := strconv.Atoi(user.Uid)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tgid, err := strconv.Atoi(user.Gid)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\ttestPermissions()\n\n\tif err := os.Chmod(a.Path, teleport.FileMaskOwnerOnly); err != nil {\n\t\treturn trace.ConvertSystemError(err)\n\t}\n\n\ttestPermissions()\n\n\tif err := os.Chown(a.Path, uid, gid); err != nil {\n\t\treturn trace.ConvertSystemError(err)\n\t}\n\n\ttestPermissions()\n\n\t// To prevent a privilege escalation attack, this must occur\n\t// after the socket permissions are updated.\n\tif err := os.Chown(a.Dir, uid, gid); err != nil {\n\t\treturn trace.ConvertSystemError(err)\n\t}\n\n\treturn nil\n}", "func setFilePermissions(path string, user, group, mode string) error {\n\tvar err error\n\tuid, gid := os.Getuid(), os.Getgid()\n\n\tif user != \"\" {\n\t\tif uid, err = strconv.Atoi(user); err == nil {\n\t\t\tgoto GROUP\n\t\t}\n\n\t\t// Try looking up the user by name\n\t\tu, err := osuser.Lookup(user)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to look up user %s: %v\", user, err)\n\t\t}\n\t\tuid, _ = strconv.Atoi(u.Uid)\n\t}\n\nGROUP:\n\tif group != \"\" {\n\t\tif gid, err = strconv.Atoi(group); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid group specified: %v\", group)\n\t\t}\n\t}\n\tif err := os.Chown(path, uid, gid); err != nil {\n\t\treturn fmt.Errorf(\"failed setting ownership to %d:%d on %q: %s\",\n\t\t\tuid, gid, path, err)\n\t}\n\n\tif mode != \"\" {\n\t\tmode, err := strconv.ParseUint(mode, 8, 32)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid mode specified: %v\", mode)\n\t\t}\n\t\tif err := os.Chmod(path, os.FileMode(mode)); err != nil {\n\t\t\treturn fmt.Errorf(\"failed setting permissions to %d on %q: %s\",\n\t\t\t\tmode, path, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func UpdatePermission(c *gin.Context) {\n\tupdatePermission := model.Permission{}\n\tc.BindJSON(&updatePermission)\n\n\terr := service.UpdatePermission(updatePermission)\n\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\terror := service.GetGormErrorCode(err.Error())\n\n\t\tc.JSON(500, error)\n\t} else {\n\t\tc.String(200, \"ok\")\n\t}\n}", "func (db *SQLiteDB) SetPermissions(prm Permission) error {\n\n\tquery, err := db.Exec(\"INSERT INTO Permissions (`UserID`, `GroupID` , `Permission`) VALUES (?,?,?) \"+\n\t\t\"ON CONFLICT(`UserID`,`GroupID`,`Permission`) DO UPDATE \"+\n\t\t\"SET `Permission` = Excluded.Permission\", prm.UserID, prm.GroupID, prm.Permission)\n\tif err != nil {\n\t\tdb.AddLogEvent(Log{Event: \"SetPermissions_QueryFailed\", Message: \"Impossible to create the execute the query\", Error: err.Error()})\n\t\treturn err\n\t}\n\trows, err := query.RowsAffected()\n\tif err != nil {\n\t\tdb.AddLogEvent(Log{Event: \"SetPermissions_RowsInfoNotGot\", Message: \"Impossible to get afftected rows\", Error: err.Error()})\n\t\treturn err\n\t}\n\tif rows < 1 {\n\t\tdb.AddLogEvent(Log{Event: \"SetPermissions_NoRowsAffected\", Message: \"No rows affected\"})\n\t\treturn NoRowsAffected{error: errors.New(\"No rows affected from the query\")}\n\t}\n\treturn err\n\n\t/*stmt, err := db.Prepare(\"INSERT INTO Permissions (`User`, `Group` , `Permission`) VALUES (?,?,?) ON CONFLICT(`User`,`Group`,`Permission`) DO UPDATE SET `Permission` = Excluded.Permission\")\n\tif err != nil {\n\t\tdb.AddLogEvent(Log{Event: \"SetPermissions_QueryFailed\", Message: \"The query for the SetPermissions function failed\", Error: err.Error()})\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\t//And we execute it passing the parameters\n\trows, err := stmt.Exec(userID, groupID, permissions)\n\n\tif err != nil {\n\t\tdb.AddLogEvent(Log{Event: \"SetPermissions_NotFoundUnknown\", Message: \"The execution of the query for the SetPermissions function failed\", Error: err.Error()})\n\t\treturn err\n\t}\n\n\tres, err := rows.RowsAffected()\n\n\tif err != nil {\n\t\tdb.AddLogEvent(Log{Event: \"SetPermissions_ExecutionQueryError\", Message: \"The fetching of the query results for the SetPermissions function failed\", Error: err.Error()})\n\t\treturn err\n\t}\n\tif res > 0 {\n\t\treturn nil\n\t}\n\tdb.AddLogEvent(Log{Event: \"SetPermissions_NotChangesMade\", Message: \"No changes was made to the database!\", Error: err.Error()})\n\treturn errors.New(\"No changes to the database was made\")*/\n}", "func SetPermissions(dir string, perm os.FileMode) error {\n\treturn filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn os.Chmod(path, perm)\n\t})\n}", "func (r *V1alpha1Service) TestIamPermissions(resource string, googleiamv1__testiampermissionsrequest *GoogleIamV1__TestIamPermissionsRequest) *V1alpha1TestIamPermissionsCall {\n\tc := &V1alpha1TestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\tc.googleiamv1__testiampermissionsrequest = googleiamv1__testiampermissionsrequest\n\treturn c\n}", "func (r *ProjectsOccurrencesService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *ProjectsOccurrencesTestIamPermissionsCall {\n\tc := &ProjectsOccurrencesTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\tc.testiampermissionsrequest = testiampermissionsrequest\n\treturn c\n}", "func (r *FoldersService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *FoldersTestIamPermissionsCall {\n\tc := &FoldersTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\tc.testiampermissionsrequest = testiampermissionsrequest\n\treturn c\n}", "func (r *DatasetsService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *DatasetsTestIamPermissionsCall {\n\tc := &DatasetsTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\tc.testiampermissionsrequest = testiampermissionsrequest\n\treturn c\n}", "func changeFileOwnership(config *Configuration) error {\n\tif config.UserName == \"\" {\n\t\treturn errors.New(\"no username supplied in config\")\n\t}\n\n\tusr, err := config.ext.lookupUser(config.UserName)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"user lookup\")\n\t}\n\n\tgrp, err := getGroup(config.ext, usr, config.GroupName)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"group lookup\")\n\t}\n\n\tif err := chownAll(config, usr, grp); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *ProjectsServiceAccountsService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *ProjectsServiceAccountsTestIamPermissionsCall {\n\tc := &ProjectsServiceAccountsTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\tc.testiampermissionsrequest = testiampermissionsrequest\n\treturn c\n}", "func (r *ProjectsServiceAccountsService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *ProjectsServiceAccountsTestIamPermissionsCall {\n\tc := &ProjectsServiceAccountsTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\tc.testiampermissionsrequest = testiampermissionsrequest\n\treturn c\n}", "func (c *Client) EditChannelPermission(\n\tchannelID discord.ChannelID,\n\toverwriteID discord.Snowflake, data EditChannelPermissionData) error {\n\n\treturn c.FastRequest(\n\t\t\"PUT\", EndpointChannels+channelID.String()+\"/permissions/\"+overwriteID.String(),\n\t\thttputil.WithJSONBody(data), httputil.WithHeaders(data.Header()),\n\t)\n}", "func (r *OrganizationsService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *OrganizationsTestIamPermissionsCall {\n\tc := &OrganizationsTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\tc.testiampermissionsrequest = testiampermissionsrequest\n\treturn c\n}", "func (r *OrganizationsService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *OrganizationsTestIamPermissionsCall {\n\tc := &OrganizationsTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\tc.testiampermissionsrequest = testiampermissionsrequest\n\treturn c\n}", "func (c *JobsClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) {\n\treturn c.internalClient.TestIamPermissions(ctx, req, opts...)\n}", "func (App) Permissions() []evo.Permission { return []evo.Permission{} }", "func (self File) Permissions(permissions os.FileMode) File {\n\terr := os.Chmod(self.String(), permissions)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn self\n}", "func (a *AgentServer) SetTestPermissions(testPermissions func()) {\n\ta.testPermissions = testPermissions\n}", "func IsPermission(err error) bool", "func (void *VoidResponse) SetCanChangeInfo(can bool) *VoidResponse {\n\tbody := JSON{\n\t\t\"can_change_info\": can,\n\t}\n\tvoid.Request = void.Request.Send(body)\n\n\treturn void\n}", "func NormalizePermissions(filename string, force bool) {\n\ts := \"\"\n\tif force {\n\t\ts = \"sudo \"\n\t}\n\t//if on mac and force\n\tif runtime.GOOS == \"darwin\" && force {\n\t\tfmt.Println(\"\\t\" + s + \"xattr -c \\\"\" + filename + \"\\\"\")\n\t\tfmt.Println(\"\\t\" + s + \"chmod -N \\\"\" + filename + \"\\\"\")\n\t}\n\t//can happen on either linux or mac\n\n\tif force && os.Getenv(\"USER\") != \"\" {\n\t\tg := \"\"\n\t\tif os.Getenv(\"GROUP\") != \"\" {\n\t\t\tg = \":\" + os.Getenv(\"GROUP\")\n\t\t}\n\t\tfmt.Println(\"\\t\" + s + \"chown \" + os.Getenv(\"USER\") + g + \" \\\"\" + filename + \"\\\"\")\n\t}\n}", "func (p *FileInf) createPermissions(u *url.URL) error {\n\tq := u.Query()\n\tif p.PermissionInfo.Role == \"\" || p.PermissionInfo.Type == \"\" {\n\t\treturn fmt.Errorf(\"role and type are required for creating permissions\")\n\t}\n\tif p.PermissionInfo.Transferownership {\n\t\tq.Set(\"transferOwnership\", \"true\")\n\t}\n\tq.Set(\"fields\", \"allowFileDiscovery,deleted,displayName,domain,emailAddress,expirationTime,id,kind,photoLink,role,teamDrivePermissionDetails,type\")\n\tu.RawQuery = q.Encode()\n\tmeta := struct {\n\t\tRole string `json:\"role,omitempty\"`\n\t\tType string `json:\"type,omitempty\"`\n\t\tEmailAddress string `json:\"emailAddress,omitempty\"`\n\t}{\n\t\tp.PermissionInfo.Role, p.PermissionInfo.Type, p.PermissionInfo.Emailaddress,\n\t}\n\tmetadata, err := json.Marshal(meta)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr := &RequestParams{\n\t\tMethod: \"POST\",\n\t\tAPIURL: u.String(),\n\t\tData: bytes.NewBuffer(metadata),\n\t\tAccesstoken: p.Accesstoken,\n\t\tContenttype: \"application/json\",\n\t\tDtime: 30,\n\t}\n\tp.reqAndGetRawResponse(r)\n\tp.Msgar = append(p.Msgar, \"Permission was created.\")\n\treturn nil\n}", "func SetFilePermissions(srcPath string, userString string, groupString string, perms os.FileMode) (err error) {\n\tvar accessList []api.ExplicitAccess\n\n\tif userString == \"\" {\n\t\taccessList = append(accessList, acl.GrantName((uint32(perms)&0700)<<23, \"CREATOR OWNER\"))\n\t} else {\n\t\taccessList = append(accessList, acl.GrantName((uint32(perms)&0700)<<23, userString))\n\t}\n\n\tif groupString == \"\" {\n\t\taccessList = append(accessList, acl.GrantName((uint32(perms)&0070)<<26, \"CREATOR OWNER\"))\n\t} else {\n\t\taccessList = append(accessList, acl.GrantName((uint32(perms)&0070)<<26, groupString))\n\t}\n\n\treturn acl.Apply(\n\t\tsrcPath,\n\t\ttrue,\n\t\tfalse,\n\t\taccessList...,\n\t)\n\n\treturn\n}", "func ModifyPerfil(w http.ResponseWriter, r *http.Request) {\n\n\tvar t models.Usuario\n\n\terr := json.NewDecoder(r.Body).Decode(&t)\n\tif err != nil {\n\t\thttp.Error(w, \"Datos Incorrectos. \"+err.Error(), 400)\n\t\treturn\n\t}\n\n\tvar status bool\n\tstatus, err = bd.ModifyRegistro(t, IDUsuario)\n\tif err != nil {\n\t\thttp.Error(w, \"Ocurrio un error al intentar Modificar el registro. \"+err.Error(), 400)\n\t\treturn\n\t}\n\n\tif status == false {\n\t\thttp.Error(w, \"No se ha logrado modificar el registro del usuario \", 400)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n}", "func SetFilePermissions(srcPath string, userString string, groupString string, perms os.FileMode) (err error) {\n\terr = os.Chmod(srcPath, perms)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// User\n\tuid := -1\n\tif userString != \"\" {\n\t\tu, err := user.Lookup(userString)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tuid, err = strconv.Atoi(u.Uid)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Group\n\tgid := -1\n\tif groupString != \"\" {\n\t\tg, err := user.LookupGroup(groupString)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tgid, err = strconv.Atoi(g.Gid)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif uid != -1 || gid != -1 {\n\t\terr = os.Chown(srcPath, uid, gid)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn\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 (m *ProtectGroup) SetPrivacy(value *GroupPrivacy)() {\n err := m.GetBackingStore().Set(\"privacy\", value)\n if err != nil {\n panic(err)\n }\n}", "func (r *ProjectsNotesService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *ProjectsNotesTestIamPermissionsCall {\n\tc := &ProjectsNotesTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\tc.testiampermissionsrequest = testiampermissionsrequest\n\treturn c\n}", "func Permisos(perm int64) structs_lwh.Permisos {\n\tuserPerm := perm / 100\n\n\tgroupPerm := (perm - userPerm*100) / 10\n\n\totherPerm := perm - userPerm*100\n\n\tvar permisos structs_lwh.Permisos\n\t//Permisos Usuarios\n\t//------------------------------------------------------------------------------------------\n\tif userPerm%2 == 1 {\n\t\tpermisos.Permiso[0].Exec = true\n\t} else if userPerm%2 == 0 {\n\t\tpermisos.Permiso[0].Exec = false\n\t}\n\n\tif (userPerm/2)%2 == 1 {\n\t\tpermisos.Permiso[0].Write = true\n\t} else if (userPerm/2)%2 == 0 {\n\t\tpermisos.Permiso[0].Write = false\n\t}\n\n\tif ((userPerm/2)/2)%2 == 1 {\n\t\tpermisos.Permiso[0].Read = true\n\t} else if ((userPerm/2)/2)%2 == 0 {\n\t\tpermisos.Permiso[0].Read = false\n\t}\n\t//-----------------------------------------------------------------------------------------------\n\n\tif groupPerm%2 == 1 {\n\t\tpermisos.Permiso[1].Exec = true\n\t} else if groupPerm%2 == 0 {\n\t\tpermisos.Permiso[1].Exec = false\n\t}\n\n\tif (groupPerm/2)%2 == 1 {\n\t\tpermisos.Permiso[1].Write = true\n\t} else if (groupPerm/2)%2 == 0 {\n\t\tpermisos.Permiso[1].Write = false\n\t}\n\n\tif ((groupPerm/2)/2)%2 == 1 {\n\t\tpermisos.Permiso[1].Read = true\n\t} else if ((groupPerm/2)/2)%2 == 0 {\n\t\tpermisos.Permiso[1].Read = false\n\t}\n\t//------------------------------------------------------------------------------------------------\n\n\tif otherPerm%2 == 1 {\n\t\tpermisos.Permiso[2].Exec = true\n\t} else if otherPerm%2 == 0 {\n\t\tpermisos.Permiso[2].Exec = true\n\t}\n\n\tif (otherPerm/2)%2 == 1 {\n\t\tpermisos.Permiso[2].Write = true\n\t} else if (otherPerm/2)%2 == 0 {\n\t\tpermisos.Permiso[2].Write = false\n\t}\n\n\tif ((otherPerm/2)/2)%2 == 1 {\n\t\tpermisos.Permiso[2].Read = true\n\t} else if ((otherPerm/2)/2)%2 == 0 {\n\t\tpermisos.Permiso[2].Read = false\n\t}\n\treturn permisos\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 *IdentityTestIAMPermissionsResponse) SetPermissions(v []string) {\n\to.Permissions = &v\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 (uh permissionHandler) Persmisions(c *gin.Context) {\n\tpermissions := uh.casbinAuth.Policies()\n\tc.JSON(http.StatusOK, gin.H{\"permissions\": permissions})\n}", "func (r *ProjectsLocationsConnectionProfilesService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *ProjectsLocationsConnectionProfilesTestIamPermissionsCall {\n\tc := &ProjectsLocationsConnectionProfilesTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\tc.testiampermissionsrequest = testiampermissionsrequest\n\treturn c\n}", "func (permission *Permission) Allow(mode PermissionMode, roles ...string) *Permission{\n\tif mode == CRUD {\n\t\treturn permission.Allow(Create, roles...).Allow(Update, roles...).Allow(Read, roles...).Allow(Delete, roles...)\n\t}\n\n\tif permission.AllowedRoles[mode] == nil {\n\t\tpermission.AllowedRoles[mode] = []string{}\n\t}\n\tpermission.AllowedRoles[mode] = append(permission.AllowedRoles[mode], roles...)\n\treturn permission\n}", "func G_1_CheckPublicPermissions(a_p M) M {\n\tvar v_d M = None\n\t_ = v_d\n\t// @ 871 @ 25 @ CheckPublicPermissions\n\t// Vcall: fn: <parse.Tfield object at 0x2b1270cf15d0>\n\t// Vcall: args: [<parse.Tvar object at 0x2b1270cf1610>]\n\t// Vcall: names: ['']\n\t// Vcall: star: None\n\t// Vcall: starstar: None\n\t// Vvar: local var p -> 'a_p'\n\ta_p = MkGo(i_filepath.Clean).Call( /*Yvar.str*/ a_p) // Assign <class 'parse.Tvar'> lhs <type 'str'> = rhs <type 'str'>\n\t// $ 871 $ 25 $\n\t// @ 895 @ 26 @ CheckPublicPermissions\n\t// Vcall: fn: <parse.Tfield object at 0x2b1270cf17d0>\n\t// Vcall: args: []\n\t// Vcall: names: []\n\t// Vcall: star: None\n\t// Vcall: starstar: None\n\t// Vcall: fn: <parse.Tfield object at 0x2b1270cf1710>\n\t// Vcall: args: [<parse.Tvar object at 0x2b1270cf1750>]\n\t// Vcall: names: ['']\n\t// Vcall: star: None\n\t// Vcall: starstar: None\n\t// Vvar: local var p -> 'a_p'\n\tif /*DoNE*/ /*General*/ /*invoker*/ f_INVOKE_0_Mode(MkGo(i_os.Stat).Call( /*Yvar.str*/ a_p)).BitAnd( /*Yint.str*/ litI_95b09698fda1f64af16708ffb859eab9).NE( /*Yint.str*/ litI_95b09698fda1f64af16708ffb859eab9) {\n\t\t// @ 938 @ 27 @ CheckPublicPermissions\n\t\t// Vcall: fn: <parse.Tfield object at 0x2b1270cf1a90>\n\t\t// Vcall: args: []\n\t\t// Vcall: names: []\n\t\t// Vcall: star: None\n\t\t// Vcall: starstar: None\n\t\t// Vcall: fn: <parse.Tfield object at 0x2b1270cf19d0>\n\t\t// Vcall: args: [<parse.Tvar object at 0x2b1270cf1a10>]\n\t\t// Vcall: names: ['']\n\t\t// Vcall: star: None\n\t\t// Vcall: starstar: None\n\t\t// Vvar: local var p -> 'a_p'\n\t\t// Vvar: local var p -> 'a_p'\n\t\tpanic(M(( /*DoMod*/ /*Ystr.str*/ litS_1e41c88a380b6897e691627e99ec07fc.Mod(MkTupleV( /*General*/ /*invoker*/ f_INVOKE_0_Mode(MkGo(i_os.Stat).Call( /*Yvar.str*/ a_p)) /*Yvar.str*/, a_p)))))\n\t\t// $ 938 $ 27 $\n\t}\n\t// $ 895 $ 26 $\n\t// @ 1006 @ 28 @ CheckPublicPermissions\n\t// Vcall: fn: <parse.Tfield object at 0x2b1270cf1d10>\n\t// Vcall: args: [<parse.Tvar object at 0x2b1270cf1d50>]\n\t// Vcall: names: ['']\n\t// Vcall: star: None\n\t// Vcall: starstar: None\n\t// Vvar: local var p -> 'a_p'\n\t// @@@@@@ Creating var \"d\" in scope @@@@@@\n\tv_d = MkGo(i_filepath.Dir).Call( /*Yvar.str*/ a_p) // Assign <class 'parse.Tvar'> lhs <type 'str'> = rhs <type 'str'>\n\t// $ 1006 $ 28 $\n\t// @ 1028 @ 29 @ CheckPublicPermissions\n\tfor {\n\t\t// Vvar: local var d -> 'v_d'\n\t\t// Ybool::__str__ '(/*DoNE*//*Yvar.str*/v_d.NE(/*Ystr.str*/litS_5058f1af8388633f609cadb75a75dc9d))' None\n\t\tvar andand_102 M = /*Ybool.str*/ MkBool(( /*DoNE*/ /*Yvar.str*/ v_d.NE( /*Ystr.str*/ litS_5058f1af8388633f609cadb75a75dc9d)))\n\t\tif andand_102.Bool() {\n\t\t\t// Vvar: local var d -> 'v_d'\n\t\t\t// Ybool::__str__ '(/*DoNE*//*Yvar.str*/v_d.NE(/*Ystr.str*/litS_6666cd76f96956469e7be39d750cc7d9))' None\n\t\t\tandand_102 = /*Ybool.str*/ MkBool(( /*DoNE*/ /*Yvar.str*/ v_d.NE( /*Ystr.str*/ litS_6666cd76f96956469e7be39d750cc7d9)))\n\t\t}\n\t\tvar andand_101 M = andand_102\n\t\tif andand_101.Bool() {\n\t\t\t// Vvar: local var d -> 'v_d'\n\t\t\t// Ybool::__str__ '(/*DoNE*//*Yvar.str*/v_d.NE(/*Ystr.str*/litS_d41d8cd98f00b204e9800998ecf8427e))' None\n\t\t\tandand_101 = /*Ybool.str*/ MkBool(( /*DoNE*/ /*Yvar.str*/ v_d.NE( /*Ystr.str*/ litS_d41d8cd98f00b204e9800998ecf8427e)))\n\t\t}\n\t\tif !( /*AsBool*/ andand_101.Bool()) {\n\t\t\tbreak\n\t\t}\n\t\t// @ 1073 @ 30 @ CheckPublicPermissions\n\t\t// Vcall: fn: <parse.Tfield object at 0x2b1270d0d210>\n\t\t// Vcall: args: []\n\t\t// Vcall: names: []\n\t\t// Vcall: star: None\n\t\t// Vcall: starstar: None\n\t\t// Vcall: fn: <parse.Tfield object at 0x2b1270d0d150>\n\t\t// Vcall: args: [<parse.Tvar object at 0x2b1270d0d190>]\n\t\t// Vcall: names: ['']\n\t\t// Vcall: star: None\n\t\t// Vcall: starstar: None\n\t\t// Vvar: local var d -> 'v_d'\n\t\tif /*DoNE*/ /*General*/ /*invoker*/ f_INVOKE_0_Mode(MkGo(i_os.Stat).Call( /*Yvar.str*/ v_d)).BitAnd( /*Yint.str*/ litI_d39934ce111a864abf40391f3da9cdf5).NE( /*Yint.str*/ litI_d39934ce111a864abf40391f3da9cdf5) {\n\t\t\t// @ 1118 @ 31 @ CheckPublicPermissions\n\t\t\t// Vcall: fn: <parse.Tfield object at 0x2b1270d0d4d0>\n\t\t\t// Vcall: args: []\n\t\t\t// Vcall: names: []\n\t\t\t// Vcall: star: None\n\t\t\t// Vcall: starstar: None\n\t\t\t// Vcall: fn: <parse.Tfield object at 0x2b1270d0d410>\n\t\t\t// Vcall: args: [<parse.Tvar object at 0x2b1270d0d450>]\n\t\t\t// Vcall: names: ['']\n\t\t\t// Vcall: star: None\n\t\t\t// Vcall: starstar: None\n\t\t\t// Vvar: local var d -> 'v_d'\n\t\t\t// Vvar: local var d -> 'v_d'\n\t\t\tpanic(M(( /*DoMod*/ /*Ystr.str*/ litS_01a99182d678d59178e9adbb72ff87ae.Mod(MkTupleV( /*General*/ /*invoker*/ f_INVOKE_0_Mode(MkGo(i_os.Stat).Call( /*Yvar.str*/ v_d)) /*Yvar.str*/, v_d)))))\n\t\t\t// $ 1118 $ 31 $\n\t\t}\n\t\t// $ 1073 $ 30 $\n\t\t// @ 1200 @ 32 @ CheckPublicPermissions\n\t\t// Vcall: fn: <parse.Tfield object at 0x2b1270d0d750>\n\t\t// Vcall: args: [<parse.Tvar object at 0x2b1270d0d790>]\n\t\t// Vcall: names: ['']\n\t\t// Vcall: star: None\n\t\t// Vcall: starstar: None\n\t\t// Vvar: local var d -> 'v_d'\n\t\tv_d = MkGo(i_filepath.Dir).Call( /*Yvar.str*/ v_d) // Assign <class 'parse.Tvar'> lhs <type 'str'> = rhs <type 'str'>\n\t\t// $ 1200 $ 32 $\n\t}\n\t// $ 1028 $ 29 $\n\n\treturn None\n}", "func (s *Service) Permissions(c context.Context, username string) (res *model.Permissions, err error) {\n\tuser := &model.User{}\n\tres = new(model.Permissions)\n\t//根据username 招到userid\n\tres.UID = user.ID\n\tres.Perms = make([]string, 10)\n\tres.Admin = true\n\treturn\n}", "func CheckAccess(permissionGroup string, hasRole string, makerChecker bool, requestedMethod string, requestedEndpoint string) (bool, error) {\n\n\tp := authPermissions.Permissions()\n\t// permissionsByte, err := ioutil.ReadFile(\"../permissions.json\")\n\tvar permissions Permissions\n\t// if err != nil {\n\t// \tpanic(err)\n\t// }\n\terr := json.Unmarshal([]byte(p), &permissions)\n\t// fmt.Print(string(permissionsByte))\n\n\tif err != nil {\n\t\tLOGGER.Error(\"Error while parsing JSON\")\n\t\treturn false, errors.New(\"not authorized, no matching permissions\")\n\t}\n\n\tif permissionGroup == \"Jwt\" {\n\n\t\t// endpoints requiring JWT\n\t\t// fmt.Print(\"\\n\\n\" + requestedMethod + \" | jwt endpoints:\\n\")\n\t\tjwtEndp := permissions.Permissions.Jwt.Default.Method[requestedMethod].Endpoint\n\t\tfor key, value := range jwtEndp {\n\t\t\t// fmt.Println(key+\" - Allow: \", value.Role.Allow)\n\t\t\tif hasRole == \"allow\" && value.Role.Allow == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"Permissions Succeeded! \"+key+\" - Allow: \", value.Role.Allow)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif permissionGroup == \"Super_permissions\" && makerChecker == false {\n\n\t\t// super user endpoints\n\t\t// fmt.Print(\"\\n\\n\" + requestedMethod + \" | super user endpoints:\\n\")\n\t\tsuperEndpDef := permissions.Permissions.Super_permissions.Default.Method[requestedMethod].Endpoint\n\t\tfor key, value := range superEndpDef {\n\t\t\t// fmt.Println(key+\" - Admin: \", value.Role.Admin)\n\t\t\t// fmt.Println(key+\" - Manager: \", value.Role.Manager)\n\t\t\tif hasRole == \"admin\" && value.Role.Admin == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Admin: \", value.Role.Admin)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tif hasRole == \"manager\" && value.Role.Manager == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Manager: \", value.Role.Manager)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif permissionGroup == \"Super_permissions\" && makerChecker == true {\n\n\t\t// super user endpoints requiring maker/checker\n\t\t// fmt.Print(\"\\n\\n\" + requestedMethod + \" | super user + maker/checker endpoints:\\n\")\n\t\tsuperEndpMC := permissions.Permissions.Super_permissions.Maker_checker.Method[requestedMethod].Endpoint\n\t\tfor key, value := range superEndpMC {\n\t\t\t// fmt.Println(key+\" - Admin: \", value.Role.Admin)\n\t\t\t// fmt.Println(key+\" - Manager: \", value.Role.Manager)\n\t\t\tif hasRole == \"admin\" && value.Role.Admin == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Admin: \", value.Role.Admin)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tif hasRole == \"manager\" && value.Role.Manager == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Manager: \", value.Role.Manager)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif permissionGroup == \"Participant_permissions\" && makerChecker == false {\n\n\t\t// participant user endpoints\n\t\t// fmt.Print(\"\\n\\n\" + requestedMethod + \" | participant endpoints:\\n\")\n\t\tparticipantEndpDef := permissions.Permissions.Participant_permissions.Default.Method[requestedMethod].Endpoint\n\t\tfor key, value := range participantEndpDef {\n\t\t\t// fmt.Println(key+\" - Admin: \", value.Role.Admin)\n\t\t\t// fmt.Println(key+\" - Manager: \", value.Role.Manager)\n\t\t\tif hasRole == \"admin\" && value.Role.Admin == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Admin: \", value.Role.Admin)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tif hasRole == \"manager\" && value.Role.Manager == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Manager: \", value.Role.Manager)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif permissionGroup == \"Participant_permissions\" && makerChecker == true {\n\n\t\t// participant user endpoints requiring maker/checker\n\t\t// fmt.Print(\"\\n\\n\" + requestedMethod + \" | participant + maker/checker endpoints:\\n\")\n\t\tparticipantEndpMC := permissions.Permissions.Participant_permissions.Maker_checker.Method[requestedMethod].Endpoint\n\t\tfor key, value := range participantEndpMC {\n\t\t\t// fmt.Println(key+\" - Admin: \", value.Role.Admin)\n\t\t\t// fmt.Println(key+\" - Manager: \", value.Role.Manager)\n\t\t\tif hasRole == \"admin\" && value.Role.Admin == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Admin: \", value.Role.Admin)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tif hasRole == \"manager\" && value.Role.Manager == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Manager: \", value.Role.Manager)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn false, errors.New(\"not authorized, no matching permissions\")\n\n}", "func (_Storage *StorageCallerSession) Permissions(arg0 uint8) (*big.Int, error) {\n\treturn _Storage.Contract.Permissions(&_Storage.CallOpts, arg0)\n}", "func (permission *Permission) Allow(mode PermissionMode, roles ...string) *Permission {\n\tif mode == CRUD {\n\t\treturn permission.Allow(Create, roles...).Allow(Update, roles...).Allow(Read, roles...).Allow(Delete, roles...)\n\t}\n\n\tif permission.AllowedRoles[mode] == nil {\n\t\tpermission.AllowedRoles[mode] = []string{}\n\t}\n\tpermission.AllowedRoles[mode] = append(permission.AllowedRoles[mode], roles...)\n\treturn permission\n}", "func (_Bucket *BucketTransactor) SetWritePermission(opts *bind.TransactOpts, _fileId *big.Int, _entity common.Address, _permission bool) (*types.Transaction, error) {\n\treturn _Bucket.contract.Transact(opts, \"setWritePermission\", _fileId, _entity, _permission)\n}", "func checkPermissions(s *model.SessionContext, methodPermission, userPermission string) bool {\n\t// Blocked permission no access.\n\tif userPermission == utils.BlockPermission {\n\t\tlogutil.Errorf(s, \"RBAC check failed... Permission is set to blocked...\")\n\t\treturn false\n\t}\n\n\t// Lower permission Deny access. \"Read vs Modify\" case\n\tif userPermission == utils.ReadPermission &&\n\t\tmethodPermission == utils.ModifyPermission {\n\t\tlogutil.Errorf(s, \"RBAC check failed...\"+\n\t\t\t\"Method permission - %s & User Permission - %s \", methodPermission, userPermission)\n\t\treturn false\n\t}\n\n\t// Matching permission allow access.\n\t// Higher permission allow access. \"Modify vs Read\" case\n\treturn true\n}", "func (r *ProjectsLocationsDataExchangesService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *ProjectsLocationsDataExchangesTestIamPermissionsCall {\n\tc := &ProjectsLocationsDataExchangesTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\tc.testiampermissionsrequest = testiampermissionsrequest\n\treturn c\n}", "func (m *RetentionLabelSettings) SetIsMetadataUpdateAllowed(value *bool)() {\n err := m.GetBackingStore().Set(\"isMetadataUpdateAllowed\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s BridgeObjectId_HttpApi) NewPermissions(n int32) (capnp.BitList, error) {\n\tl, err := capnp.NewBitList(s.Struct.Segment(), n)\n\tif err != nil {\n\t\treturn capnp.BitList{}, err\n\t}\n\terr = s.Struct.SetPtr(2, l.List.ToPtr())\n\treturn l, err\n}", "func (u *UserModel) UpdatePermissions(userID int, permissions []*models.UserPermission) error {\n\tvar IDs []int\n\tfor _, p := range permissions {\n\t\tIDs = append(IDs, p.Permission.ID)\n\t}\n\n\ttx, _ := u.DB.Begin()\n\tdefer tx.Rollback()\n\n\tstmt := `DELETE FROM permission_user WHERE user_id = ? AND permission_id NOT IN (?` + strings.Repeat(\", ?\", len(IDs)-1) + `)`\n\t_, err := u.DB.Exec(stmt, userID, IDs)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\tfor _, id := range IDs {\n\t\tstmt := `INSERT INTO permission_user (user_id, permission_id)\n\t\t\t SELECT ?, ? \n\t\t\t FROM DUAL\n\t\t\t WHERE NOT EXISTS (\n\t\t\t\tSELECT 1\n\t\t\t\tFROM permission_user\n\t\t\t\tWHERE user_id = ? AND permission_id = ?\n\t\t\t )\n\t\t\tLIMIT 1`\n\n\t\t_, err = u.DB.Exec(stmt, userID, id, userID, id)\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttx.Commit()\n\treturn nil\n}", "func (_Storage *StorageSession) Permissions(arg0 uint8) (*big.Int, error) {\n\treturn _Storage.Contract.Permissions(&_Storage.CallOpts, arg0)\n}", "func (r *ProjectsLocationsMigrationJobsService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *ProjectsLocationsMigrationJobsTestIamPermissionsCall {\n\tc := &ProjectsLocationsMigrationJobsTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\tc.testiampermissionsrequest = testiampermissionsrequest\n\treturn c\n}", "func (r *OrganizationsEnvironmentsService) TestIamPermissions(resource string, googleiamv1testiampermissionsrequest *GoogleIamV1TestIamPermissionsRequest) *OrganizationsEnvironmentsTestIamPermissionsCall {\n\tc := &OrganizationsEnvironmentsTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\tc.googleiamv1testiampermissionsrequest = googleiamv1testiampermissionsrequest\n\treturn c\n}", "func FileModePerm(m os.FileMode,) os.FileMode", "func (r *Permitter) ViewerCanAdmin(\n\tctx context.Context,\n\tnode interface{},\n) (bool, error) {\n\tviewer, ok := myctx.UserFromContext(ctx)\n\tif !ok {\n\t\terr := &myctx.ErrNotFound{\"viewer\"}\n\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\treturn false, err\n\t}\n\tif viewer.Login.String == Guest {\n\t\treturn false, nil\n\t}\n\tvid := viewer.ID.String\n\tswitch node := node.(type) {\n\tcase data.Activity:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tactivity, err := r.repos.Activity().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &activity.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Activity:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tactivity, err := r.repos.Activity().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &activity.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.ActivityAsset:\n\t\tactivityID := &node.ActivityID\n\t\tif activityID.Status == pgtype.Undefined {\n\t\t\tactivityAsset, err := r.repos.ActivityAsset().load.Get(ctx, node.AssetID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tactivityID = &activityAsset.ActivityID\n\t\t}\n\t\tactivity, err := r.repos.Activity().load.Get(ctx, activityID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\treturn vid == activity.UserID.String, nil\n\tcase *data.ActivityAsset:\n\t\tactivityID := &node.ActivityID\n\t\tif activityID.Status == pgtype.Undefined {\n\t\t\tactivityAsset, err := r.repos.ActivityAsset().load.Get(ctx, node.AssetID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tactivityID = &activityAsset.ActivityID\n\t\t}\n\t\tactivity, err := r.repos.Activity().load.Get(ctx, activityID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\treturn vid == activity.UserID.String, nil\n\tcase data.Appled:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tappled, err := r.repos.Appled().load.Get(ctx, node.ID.Int)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &appled.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Appled:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tappled, err := r.repos.Appled().load.Get(ctx, node.ID.Int)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &appled.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.Comment:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tcomment, err := r.repos.Comment().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &comment.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Comment:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tcomment, err := r.repos.Comment().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &comment.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.CommentDraftBackup:\n\t\tcomment, err := r.repos.Comment().load.Get(ctx, node.CommentID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\tuserID := &comment.UserID\n\t\treturn vid == userID.String, nil\n\tcase *data.CommentDraftBackup:\n\t\tcomment, err := r.repos.Comment().load.Get(ctx, node.CommentID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\tuserID := &comment.UserID\n\t\treturn vid == userID.String, nil\n\tcase data.Course:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tcourse, err := r.repos.Course().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &course.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Course:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tcourse, err := r.repos.Course().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &course.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.CourseLesson:\n\t\tcourseID := &node.CourseID\n\t\tif courseID.Status == pgtype.Undefined {\n\t\t\tcourseLesson, err := r.repos.CourseLesson().load.Get(ctx, node.LessonID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tcourseID = &courseLesson.CourseID\n\t\t}\n\t\tcourse, err := r.repos.Course().load.Get(ctx, courseID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\treturn vid == course.UserID.String, nil\n\tcase *data.CourseLesson:\n\t\tcourseID := &node.CourseID\n\t\tif courseID.Status == pgtype.Undefined {\n\t\t\tcourseLesson, err := r.repos.CourseLesson().load.Get(ctx, node.LessonID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tcourseID = &courseLesson.CourseID\n\t\t}\n\t\tcourse, err := r.repos.Course().load.Get(ctx, courseID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\treturn vid == course.UserID.String, nil\n\tcase data.Email:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\temail, err := r.repos.Email().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &email.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Email:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\temail, err := r.repos.Email().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &email.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.Enrolled:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tenrolled, err := r.repos.Enrolled().load.Get(ctx, node.ID.Int)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &enrolled.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Enrolled:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tenrolled, err := r.repos.Enrolled().load.Get(ctx, node.ID.Int)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &enrolled.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.EVT:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tevt, err := r.repos.EVT().load.Get(ctx, node.EmailID.String, node.Token.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &evt.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.EVT:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tevt, err := r.repos.EVT().load.Get(ctx, node.EmailID.String, node.Token.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &evt.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.Label:\n\t\tlabel, err := r.repos.Label().load.Get(ctx, node.ID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\tstudy, err := r.repos.Study().load.Get(ctx, label.StudyID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\treturn vid == study.UserID.String, nil\n\tcase *data.Label:\n\t\tlabel, err := r.repos.Label().load.Get(ctx, node.ID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\tstudy, err := r.repos.Study().load.Get(ctx, label.StudyID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\treturn vid == study.UserID.String, nil\n\tcase data.Labeled:\n\t\tuserID := mytype.OID{}\n\t\tswitch node.LabelableID.Type {\n\t\tcase \"Comment\":\n\t\t\tcomment, err := r.repos.Comment().load.Get(ctx, node.LabelableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = comment.UserID\n\t\tcase \"Lesson\":\n\t\t\tlesson, err := r.repos.Lesson().load.Get(ctx, node.LabelableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = lesson.UserID\n\t\tcase \"UserAsset\":\n\t\t\tlesson, err := r.repos.UserAsset().load.Get(ctx, node.LabelableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = lesson.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Labeled:\n\t\tuserID := mytype.OID{}\n\t\tswitch node.LabelableID.Type {\n\t\tcase \"Comment\":\n\t\t\tcomment, err := r.repos.Comment().load.Get(ctx, node.LabelableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = comment.UserID\n\t\tcase \"Lesson\":\n\t\t\tlesson, err := r.repos.Lesson().load.Get(ctx, node.LabelableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = lesson.UserID\n\t\tcase \"UserAsset\":\n\t\t\tlesson, err := r.repos.UserAsset().load.Get(ctx, node.LabelableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = lesson.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.Lesson:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tlesson, err := r.repos.Lesson().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &lesson.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Lesson:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tlesson, err := r.repos.Lesson().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &lesson.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.LessonDraftBackup:\n\t\tlesson, err := r.repos.Lesson().load.Get(ctx, node.LessonID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\tuserID := &lesson.UserID\n\t\treturn vid == userID.String, nil\n\tcase *data.LessonDraftBackup:\n\t\tlesson, err := r.repos.Lesson().load.Get(ctx, node.LessonID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\tuserID := &lesson.UserID\n\t\treturn vid == userID.String, nil\n\tcase data.Notification:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tnotification, err := r.repos.Notification().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &notification.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Notification:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tnotification, err := r.repos.Notification().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &notification.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.PRT:\n\t\treturn vid == node.UserID.String, nil\n\tcase *data.PRT:\n\t\treturn vid == node.UserID.String, nil\n\tcase data.Study:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tstudy, err := r.repos.Study().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &study.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Study:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tstudy, err := r.repos.Study().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &study.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.Topiced:\n\t\tuserID := mytype.OID{}\n\t\tswitch node.TopicableID.Type {\n\t\tcase \"Course\":\n\t\t\tcourse, err := r.repos.Course().load.Get(ctx, node.TopicableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = course.UserID\n\t\tcase \"Study\":\n\t\t\tstudy, err := r.repos.Study().load.Get(ctx, node.TopicableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = study.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Topiced:\n\t\tuserID := mytype.OID{}\n\t\tswitch node.TopicableID.Type {\n\t\tcase \"Course\":\n\t\t\tcourse, err := r.repos.Course().load.Get(ctx, node.TopicableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = course.UserID\n\t\tcase \"Study\":\n\t\t\tstudy, err := r.repos.Study().load.Get(ctx, node.TopicableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = study.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.User:\n\t\treturn vid == node.ID.String, nil\n\tcase *data.User:\n\t\treturn vid == node.ID.String, nil\n\tcase data.UserAsset:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tuserAsset, err := r.repos.UserAsset().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &userAsset.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.UserAsset:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tuserAsset, err := r.repos.UserAsset().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &userAsset.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tdefault:\n\t\treturn false, nil\n\t}\n\treturn false, nil\n}", "func (r *ProjectsLocationsDataExchangesListingsService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *ProjectsLocationsDataExchangesListingsTestIamPermissionsCall {\n\tc := &ProjectsLocationsDataExchangesListingsTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.resource = resource\n\tc.testiampermissionsrequest = testiampermissionsrequest\n\treturn c\n}", "func UpdateCgroupPermission(CgroupBase string, device *types.Device, isAddDevice bool) error {\n\tvar path string\n\n\tif isAddDevice {\n\t\tpath = filepath.Join(CgroupBase, \"devices.allow\")\n\t} else {\n\t\tpath = filepath.Join(CgroupBase, \"devices.deny\")\n\t}\n\tvalue := device.CgroupString()\n\tif err := ioutil.WriteFile(path, []byte(value), 0600); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\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 (s *UpdateSecurityProfileInput) SetPermissions(v []*string) *UpdateSecurityProfileInput {\n\ts.Permissions = v\n\treturn s\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 (m *TeamMemberSettings) SetAllowCreatePrivateChannels(value *bool)() {\n m.allowCreatePrivateChannels = value\n}", "func (*ExistingRoleRelationships_Permissions) Descriptor() ([]byte, []int) {\n\treturn file_protodef_user_user_proto_rawDescGZIP(), []int{14, 0}\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 (c *jobsRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) {\n\tm := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true}\n\tjsonReq, err := m.Marshal(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbaseUrl, err := url.Parse(c.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbaseUrl.Path += fmt.Sprintf(\"/v2/%v:testIamPermissions\", req.GetResource())\n\n\tparams := url.Values{}\n\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\n\tbaseUrl.RawQuery = params.Encode()\n\n\t// Build HTTP headers from client and context metadata.\n\thds := []string{\"x-goog-request-params\", fmt.Sprintf(\"%s=%v\", \"resource\", url.QueryEscape(req.GetResource()))}\n\n\thds = append(c.xGoogHeaders, hds...)\n\thds = append(hds, \"Content-Type\", \"application/json\")\n\theaders := gax.BuildHeaders(ctx, hds...)\n\topts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tresp := &iampb.TestIamPermissionsResponse{}\n\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\tif settings.Path != \"\" {\n\t\t\tbaseUrl.Path = settings.Path\n\t\t}\n\t\thttpReq, err := http.NewRequest(\"POST\", baseUrl.String(), bytes.NewReader(jsonReq))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttpReq = httpReq.WithContext(ctx)\n\t\thttpReq.Header = headers\n\n\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer httpRsp.Body.Close()\n\n\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}, opts...)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\treturn resp, nil\n}", "func (user *User) SetAllowLike(setting ViewAccess) bool {\n\tvalue := setting.Data()\n\tset := Setting{\n\t\tKey: data.AllowLike,\n\t\tValue: value,\n\t}\n\n\tok := user.doPrivacySettings(set)\n\tif ok {\n\t\tuser.SettingsPrivacy.AllowLike = setting\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *PatchedUpdateWorkspaceInvitation) SetPermissions(v string) {\n\to.Permissions = &v\n}", "func (s *API) ChangeMessageVisibility(w http.ResponseWriter, req *http.Request) {\n\tlog.Debug(\"ChangeMessageVisibility\")\n\tw.WriteHeader(http.StatusNotImplemented)\n}", "func (r *Resolver) Permissions() PermissionsResolver { return &permissionsResolver{r} }", "func (c *Client) ModifyDocumentPermission(ctx context.Context, params *ModifyDocumentPermissionInput, optFns ...func(*Options)) (*ModifyDocumentPermissionOutput, error) {\n\tif params == nil {\n\t\tparams = &ModifyDocumentPermissionInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"ModifyDocumentPermission\", params, optFns, c.addOperationModifyDocumentPermissionMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*ModifyDocumentPermissionOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (m *Group) SetVisibility(value *string)() {\n m.visibility = value\n}", "func TestPermissions(t *testing.T) {\n\tt.Parallel()\n\twinners := []parameters{\n\t\t[]string{\"/dev/null\", \"-rw-rw-rw-\"},\n\t\t[]string{\"/proc/\", \"-r-xr-xr-x\"},\n\t\t[]string{\"/bin/\", \"-rwxr-xr-x\"},\n\t}\n\tlosers := []parameters{\n\t\t[]string{\"/dev/null\", \"----------\"},\n\t\t[]string{\"/proc/\", \"----------\"},\n\t\t[]string{\"/bin/\", \"----------\"},\n\t}\n\ttestInputs(t, permissions, winners, losers)\n}", "func (c *Config) SetSSHKeyPermissions() error {\n\tprivateKey := c.GetSSHKeyPath()\n\tcmd := exec.Command(\"chmod\", \"0600\", privateKey)\n\tutil.PrintCommand(cmd)\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tlog.Printf(\"Error while trying to change private ssh key permissions at %s: %s\\n\", privateKey, out)\n\t\treturn err\n\t}\n\tpublicKey := c.GetSSHKeyPath() + \".pub\"\n\tcmd = exec.Command(\"chmod\", \"0600\", publicKey)\n\tutil.PrintCommand(cmd)\n\tout, err = cmd.CombinedOutput()\n\tif err != nil {\n\t\tlog.Printf(\"Error while trying to change public ssh key permissions at %s: %s\\n\", publicKey, out)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *DeviceManagementConfigurationSettingDefinition) SetApplicability(value DeviceManagementConfigurationSettingApplicabilityable)() {\n err := m.GetBackingStore().Set(\"applicability\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *DeviceManagementConfigurationSettingDefinition) SetVisibility(value *DeviceManagementConfigurationSettingVisibility)() {\n err := m.GetBackingStore().Set(\"visibility\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s Service) ChangePatronymic(ctx context.Context, patronymic *string, permission *account.Permission) error {\n\tspan := s.tracer.MakeSpan(ctx, \"ChangePatronymic\")\n\tdefer span.Finish()\n\n\ttoken := s.retriveToken(ctx)\n\tif token == \"\" {\n\t\treturn errors.New(\"token_is_empty\")\n\t}\n\n\ts.passContext(&ctx)\n\n\tuserID, err := s.authRPC.GetUserID(ctx, token)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t\treturn err\n\t}\n\n\t//check for patronymic. only contain alphabets and not be over 120 characters\n\terr = middlenicknameValidator(patronymic)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = s.repository.Users.ChangePatronymic(ctx, userID, patronymic, permission)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\n\treturn nil\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 (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 (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 SetPath(permissions string) error {\n\tif permissions != \"default\" {\n\t\tpl, err := NewPermissionsLoader(permissions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = pl\n\t\tif !pl.Get().Watch {\n\t\t\tglobalPermissions.Close() // This will still keep the permissions themselves in memory\n\t\t}\n\n\t} else {\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = nil\n\t}\n\treturn nil\n}", "func (p *BlobPermissions) String() string {\n\tvar b bytes.Buffer\n\tif p.Read {\n\t\tb.WriteRune('r')\n\t}\n\tif p.Add {\n\t\tb.WriteRune('a')\n\t}\n\tif p.Create {\n\t\tb.WriteRune('c')\n\t}\n\tif p.Write {\n\t\tb.WriteRune('w')\n\t}\n\tif p.Delete {\n\t\tb.WriteRune('d')\n\t}\n\tif p.DeletePreviousVersion {\n\t\tb.WriteRune('x')\n\t}\n\tif p.PermanentDelete {\n\t\tb.WriteRune('y')\n\t}\n\tif p.List {\n\t\tb.WriteRune('l')\n\t}\n\tif p.Tag {\n\t\tb.WriteRune('t')\n\t}\n\tif p.Move {\n\t\tb.WriteRune('m')\n\t}\n\tif p.Execute {\n\t\tb.WriteRune('e')\n\t}\n\tif p.Ownership {\n\t\tb.WriteRune('o')\n\t}\n\tif p.Permissions {\n\t\tb.WriteRune('p')\n\t}\n\tif p.SetImmutabilityPolicy {\n\t\tb.WriteRune('i')\n\t}\n\treturn b.String()\n}", "func (*NewRoleRelationships_Permissions) Descriptor() ([]byte, []int) {\n\treturn file_protodef_user_user_proto_rawDescGZIP(), []int{15, 0}\n}", "func (_Bucket *BucketTransactor) SetReadPermission(opts *bind.TransactOpts, _fileId *big.Int, _entity common.Address, _permission bool) (*types.Transaction, error) {\n\treturn _Bucket.contract.Transact(opts, \"setReadPermission\", _fileId, _entity, _permission)\n}", "func (s *Service) convertPermissions(perms []client.Permission) (map[string][]Privilege, error) {\n\tprivileges := make(map[string][]Privilege, len(perms))\n\tfor _, perm := range perms {\n\t\tswitch perm {\n\t\tcase client.NoPermissions:\n\t\tcase client.APIPermission:\n\t\t\tprivileges[rootResource] = []Privilege{AllPrivileges}\n\t\t\t// Subtractive permission, only add it if something else doesn't already exist.\n\t\t\tif _, ok := privileges[writeResource]; !ok {\n\t\t\t\tprivileges[writeResource] = []Privilege{NoPrivileges}\n\t\t\t}\n\t\t\t// Do not give config API access unless specificaly granted\n\t\t\tif _, ok := privileges[configResource]; !ok {\n\t\t\t\tprivileges[configResource] = []Privilege{NoPrivileges}\n\t\t\t}\n\t\tcase client.ConfigAPIPermission:\n\t\t\tprivileges[pingResource] = []Privilege{AllPrivileges}\n\t\t\tprivileges[configResource] = []Privilege{AllPrivileges}\n\t\tcase client.WritePointsPermission:\n\t\t\tprivileges[pingResource] = []Privilege{AllPrivileges}\n\t\t\tprivileges[writeResource] = []Privilege{AllPrivileges}\n\t\tcase client.AllPermissions:\n\t\t\tprivileges[rootResource] = []Privilege{AllPrivileges}\n\t\t\tprivileges[configResource] = []Privilege{AllPrivileges}\n\t\t\tprivileges[writeResource] = []Privilege{AllPrivileges}\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown permission %v\", perm)\n\t\t}\n\t}\n\treturn privileges, nil\n}", "func makeAccessible(path string, uid, gid int, doChown bool) error {\n\tif doChown {\n\t\tif err := os.Chown(path, uid, gid); err != nil {\n\t\t\treturn fmt.Errorf(\"cannot chown %s to %d:%d: %w\", path, uid, gid, err)\n\t\t}\n\t}\n\tfor ; path != \"/\"; path = filepath.Dir(path) {\n\t\tvar st unix.Stat_t\n\t\terr := unix.Stat(path, &st)\n\t\tif err != nil {\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tif int(st.Uid) == uid && int(st.Gid) == gid {\n\t\t\tcontinue\n\t\t}\n\t\tperm := os.FileMode(st.Mode) & os.ModePerm\n\t\tif perm&0o111 != 0o111 {\n\t\t\tif err := os.Chmod(path, perm|0o111); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func PermissionProxy(in interface{}, out interface{}) {\n\tra := reflect.ValueOf(in)\n\touts := proxy.GetInternalStructs(out)\n\tfor _, out := range outs {\n\t\trint := reflect.ValueOf(out).Elem()\n\t\tfor i := 0; i < ra.NumMethod(); i++ {\n\t\t\tmethodName := ra.Type().Method(i).Name\n\t\t\tfield, exists := rint.Type().FieldByName(methodName)\n\t\t\tif !exists {\n\t\t\t\t// log.Printf(\"exclude method %s from fullNode\", methodName)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\trequiredPerm := field.Tag.Get(\"perm\")\n\t\t\tif requiredPerm == \"\" {\n\t\t\t\tpanic(\"missing 'perm' tag on \" + field.Name) // ok\n\t\t\t}\n\t\t\tcurule := defaultRule()\n\t\t\tcurule.Perm = requiredPerm\n\n\t\t\tfn := ra.Method(i)\n\t\t\trint.FieldByName(methodName).Set(reflect.MakeFunc(field.Type, func(args []reflect.Value) (results []reflect.Value) {\n\t\t\t\tctx := args[0].Interface().(context.Context)\n\t\t\t\terrNum := 0\n\t\t\t\tif !auth.HasPerm(ctx, defaultPerms, curule.Perm) {\n\t\t\t\t\terrNum++\n\t\t\t\t\tgoto ABORT\n\t\t\t\t}\n\t\t\t\treturn fn.Call(args)\n\t\t\tABORT:\n\t\t\t\terr := xerrors.Errorf(\"missing permission to invoke '%s'\", methodName)\n\t\t\t\tif errNum&1 == 1 {\n\t\t\t\t\terr = xerrors.Errorf(\"%s (need '%s')\", err, curule.Perm)\n\t\t\t\t}\n\t\t\t\trerr := reflect.ValueOf(&err).Elem()\n\t\t\t\tif fn.Type().NumOut() == 2 {\n\t\t\t\t\treturn []reflect.Value{\n\t\t\t\t\t\treflect.Zero(fn.Type().Out(0)),\n\t\t\t\t\t\trerr,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn []reflect.Value{rerr}\n\t\t\t}))\n\t\t}\n\t}\n\n}", "func (m *RoleDefinition) SetRolePermissions(value []RolePermissionable)() {\n m.rolePermissions = value\n}" ]
[ "0.6386941", "0.61053145", "0.58309543", "0.5733254", "0.57278687", "0.5681798", "0.56737554", "0.56447285", "0.55250835", "0.5524847", "0.55135715", "0.5482064", "0.54747975", "0.5453116", "0.53916466", "0.5386464", "0.5386464", "0.53733885", "0.53500324", "0.5275077", "0.52682614", "0.52035433", "0.51888233", "0.51875407", "0.5183558", "0.5180221", "0.51681495", "0.51679176", "0.51679176", "0.5147641", "0.51332927", "0.51332927", "0.51304626", "0.5114377", "0.5106087", "0.5094054", "0.5086588", "0.50777817", "0.5053442", "0.50488913", "0.5039057", "0.50332797", "0.50315315", "0.50267464", "0.50188416", "0.50143486", "0.50061935", "0.498567", "0.49845362", "0.49798602", "0.49739444", "0.4961502", "0.49451685", "0.49401277", "0.49178836", "0.4881278", "0.48774981", "0.4872282", "0.4863574", "0.48566717", "0.4828461", "0.48222342", "0.48219186", "0.4817417", "0.48085475", "0.48005906", "0.47847185", "0.47844023", "0.4749348", "0.47389638", "0.47381", "0.47318178", "0.47294712", "0.47234717", "0.47217503", "0.47190633", "0.471613", "0.47095615", "0.47086418", "0.47063392", "0.46966863", "0.46935567", "0.4693003", "0.46839508", "0.4683243", "0.46768498", "0.4663309", "0.4659082", "0.4653643", "0.46498036", "0.46473104", "0.46462974", "0.4645488", "0.46445087", "0.4641512", "0.46336004", "0.4628905", "0.46269166", "0.46211505", "0.4619838" ]
0.77092814
0
Delete allows users to delete photos
func Delete(w http.ResponseWriter, r *http.Request) { // get user info username := r.Context().Value("username") if username == nil { w.WriteHeader(http.StatusInternalServerError) return } // retrieve photo id from api call var requestedPhoto Photo err := json.NewDecoder(r.Body).Decode(&requestedPhoto) if err != nil { w.Write([]byte("Missing PhotoID or IsPublic attribute")) w.WriteHeader(http.StatusBadRequest) return } if requestedPhoto.ID == "" { w.Write([]byte("PhotoID not provided in request body")) w.WriteHeader(http.StatusBadRequest) return } // make sure photo exists var photos []Photo DB.Where(&Photo{ID: requestedPhoto.ID}).Find(&photos) if len(photos) > 1 { w.Write([]byte("Multiple photos returned")) w.WriteHeader(http.StatusInternalServerError) } if len(photos) == 0 { w.Write([]byte("No photos returned")) w.WriteHeader(http.StatusInternalServerError) return } photo := photos[0] // Make sure photo belongs to user userID, err := GetUserGUID(username.(string)) if photo.UserID != *userID { w.Write([]byte("photo does not belong to user")) w.WriteHeader(http.StatusBadRequest) return } // delete photo from photos table DB.Delete(&photo) // delete file from bucket imageFile := Client.Bucket(getBucketForPhoto(photo)).Object(photo.ID) if err = imageFile.Delete(r.Context()); err != nil { err = fmt.Errorf("Object(%q).Delete: %v", photo.ID, err) w.Write([]byte(err.Error())) w.WriteHeader(http.StatusInternalServerError) return } w.Write([]byte("photo deleted")) w.WriteHeader(http.StatusOK) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func DeletePhotos(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tids := vars[\"ids\"]\n\tstringIDsArray := strings.Split(ids, \",\")\n\tvar array []bson.ObjectId\n\tlog.Println(stringIDsArray)\n\tfor _, id := range stringIDsArray {\n\t\tif bson.IsObjectIdHex(id) {\n\t\t\tarray = append(array, bson.ObjectIdHex(id))\n\t\t}\n\t}\n\n\tlog.Println(array)\n\n\tuser, _ := database.GetUserByID(utils.GetUserObjectID(r))\n\n\tphotos, err := database.GetPhotos(user.ID, array)\n\tif err != nil {\n\t\tutils.RespondWithJSON(w, http.StatusInternalServerError, \"error\", nil)\n\t\treturn\n\t}\n\n\tvar site models.Site\n\tfor _, photo := range photos {\n\t\tif photo.SiteID != site.ID {\n\t\t\tsite, _ = database.GetSiteByID(photo.SiteID)\n\t\t}\n\t\tif !utils.IsAuthorized(site, user) {\n\t\t\tutils.RespondWithJSON(w, http.StatusUnauthorized, \"unauthorized\", nil)\n\t\t\treturn\n\t\t}\n\t}\n\n\terr = database.DeletePhotos(user.ID, array)\n\tif err != nil {\n\t\tutils.RespondWithJSON(w, http.StatusInternalServerError, \"error\", nil)\n\t\treturn\n\t}\n\terr = utils.RemoveGoogleCloudPhotos(photos)\n\t// if err != nil {\n\t// \tutils.RespondWithJSON(w, http.StatusInternalServerError, \"error\", nil)\n\t// \treturn\n\t// }\n\n\tutils.RespondWithJSON(w, http.StatusOK, \"success\", nil)\n\treturn\n}", "func DeletePhotos(userID bson.ObjectId, ids []bson.ObjectId) error {\n\tlog.Println(ids)\n\t_, err := DB.C(photosCollection).RemoveAll(bson.M{\n\t\t\"owner_id\": userID,\n\t\t\"_id\": bson.M{\n\t\t\t\"$in\": ids,\n\t\t},\n\t})\n\treturn err\n}", "func adminImagesDelete(w http.ResponseWriter, r *http.Request) {\n\ttype response struct {\n\t\tOk bool\n\t}\n\tid := r.URL.Path\n\tresp := response{}\n\n\t_, err := db.Exec(`DELETE FROM images WHERE appointment_id = $1`, id)\n\tif err != nil {\n\t\tjson.NewEncoder(w).Encode(resp)\n\t\treturn\n\t}\n\n\t// set ok and send\n\tresp.Ok = true\n\terr = json.NewEncoder(w).Encode(resp)\n\tif err != nil {\n\t\tlog.Println(\"appointment img delete:\", err)\n\t}\n}", "func delImage(w http.ResponseWriter, req *http.Request) {\n\n\t// Manage Cors\n\tsetCors(&w)\n\tif req.Method == \"OPTIONS\" {\n\t\treturn\n\t}\n\n\t// Authenticate user\n\tclaims, err := authRequest(req)\n\tif err != nil {\n\t\tlogger.Error(\"Unauthorized request to upload sending 401: %v\", err)\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(\"401 - Unauthorized request, ensure you sign in and obtain the jwt auth token\"))\n\t\treturn\n\t}\n\n\tvars := mux.Vars(req)\n\t// validate url parameters and retrieve imageMeta\n\timageMeta, err := validateVars(vars)\n\tif err != nil {\n\t\tlogger.Error(\"Failed to validate vars sending 400: %v\", err)\n\t\tif strings.Contains(err.Error(), \"404 - Not found\") {\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\tw.Write([]byte(\"404 - Not found, no image with that information available\"))\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"400 - Bad request unable to parse url parameters\"))\n\t\treturn\n\t}\n\n\t// Ensure there is no uid miss match\n\tuidVal, err := strconv.Atoi(vars[\"uid\"])\n\tif uidVal != int(imageMeta.Uid) {\n\t\tlogger.Error(\"uid miss match when attempting to delete image sending 400\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"400 - Uid mismatch ensure you are using the correct image reference\"))\n\t\treturn\n\t}\n\n\t// Ensure user has access permissions\n\tif claims.Uid != int(imageMeta.Uid) {\n\t\tlogger.Error(\"unauthorized user attempting to delete image\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(\"401 - Unauthorized, you do not have permissions to modify this image\"))\n\t\treturn\n\t}\n\n\t// Delete meta from database\n\terr = DeleteImageData(imageMeta)\n\tif err != nil {\n\t\tlogger.Error(\"failed to delete image from database sending 500: %v\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"500 - Unable to delete image from database, try again later\"))\n\t\treturn\n\t}\n\n\t// Delete file from storage\n\tfileRef := fmt.Sprintf(\"./%s/%s/%s\", IMAGE_DIR, vars[\"uid\"], vars[\"fileId\"])\n\terr = os.Remove(fileRef)\n\t// Orphaned file is ok to leave as database entry is already deleted\n\t// Automated data integrity checks or manual removal is recommended\n\t// This will look like a successfull deletion from the users perspective\n\tif err != nil {\n\t\tlogger.Error(\"failed to delete image data, clean orphaned files via automated data integrity check: %v\", err)\n\t} else {\n\t\tlogger.Info(\"Successfully deleted image: %v\", imageMeta.Id)\n\t}\n\n\treturn\n}", "func DeletePhoto(id string) error {\n\tclient, ctx, cancel := getDBConnection()\n\tdefer cancel()\n\tdefer client.Disconnect(ctx)\n\n\tcol := client.Database(\"cat-scribers\").Collection(\"photos\")\n\n\toid, _ := primitive.ObjectIDFromHex(id)\n\n\t_, err := col.DeleteOne(ctx, bson.M{\"_id\": oid})\n\n\treturn err\n}", "func DeletePhoto(photoID int) error {\n\tdeletePhoto := `DELETE FROM Photo WHERE id = ?`\n\tif _, err := configure.SQL.Query(deletePhoto, photoID); err != nil {\n\t\tlog.Println(\"Failed to delete photo\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func DeleteImage(c * gin.Context){\n\tdb := database.DBConn()\n\tid:= c.Param(\"id\")\n\t_, err := db.Query(\"Delete FROM images WHERE id = \" + id)\n\tif err != nil{\n\t\tc.JSON(500, gin.H{\n\t\t\t\"messages\" : \"Story not found\",\n\t\t});\n\t\tpanic(\"error delte clothes\")\n\t}\n\tc.JSON(200, gin.H{\n\t\t\"messages\": \"deleted\",\n\t})\n\tdefer db.Close()\n}", "func DeletePhotoHandler(c *gin.Context) {\n\tif !service.VerifyAPIRequest(c, c.Request.Header[\"Token\"]) {\n\t\treturn\n\t}\n\tif photoid, err := strconv.Atoi(c.Param(\"photoID\")); err == nil {\n\t\terr := MyStore.DeletePhoto(photoid)\n\t\tif err == nil {\n\t\t\tc.JSON(http.StatusOK, []*entity.Joke{})\n\t\t} else {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func deleteAPIImageHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {\n\tuserName := sessionHandler.GetUserName(r)\n\tif userName != \"\" { // TODO: Check if the user has permissions to delete the image\n\t\t// Get the file name from the json data\n\t\tdecoder := json.NewDecoder(r.Body)\n\t\tvar json JSONImage\n\t\terr := decoder.Decode(&json)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\terr = filepath.Walk(filenames.ImagesFilepath, func(filePath string, info os.FileInfo, err error) error {\n\t\t\tif !info.IsDir() && filepath.Base(filePath) == filepath.Base(json.Filename) {\n\t\t\t\terr := os.Remove(filePath)\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\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"Image deleted!\"))\n\t\treturn\n\t}\n\thttp.Error(w, \"Not logged in!\", http.StatusInternalServerError)\n}", "func (o *BraceletPhoto) Delete(exec boil.Executor) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no BraceletPhoto provided for delete\")\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), braceletPhotoPrimaryKeyMapping)\n\tsql := \"DELETE FROM `bracelet_photo` WHERE `id`=?\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\t_, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to delete from bracelet_photo\")\n\t}\n\n\treturn nil\n}", "func UserDelete(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n}", "func DeleteImage(w http.ResponseWriter, r *http.Request) {\n\n\t//Get current Session\n\tsession, _ := store.Get(r, \"session\")\n\tname := session.Values[\"username\"].(string)\n\n\t//Pathparameter\n\tvars := mux.Vars(r)\n\timageID := vars[\"imageID\"]\n\n\t//Get User Commenting Image\n\tuser, err := model.GetUserByUsername(name)\n\tif err != nil {\n\n\t\tw.WriteHeader(http.StatusConflict)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\n\t}\n\n\t//Delete Image from Database\n\tuser.DeleteImage(imageID)\n\n\t//Make Response JSON\n\tresponseModel := struct {\n\t\tMessage string\n\t}{Message: \"Image was deleted Sussesfully!\"}\n\tresponseJSON, err := json.Marshal(responseModel)\n\tif err != nil {\n\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\n\t}\n\n\t//Write response\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusAccepted)\n\tw.Write(responseJSON)\n}", "func (c *UploadController) Delete() {\n\timg := struct {\n\t\tFileName string `json:\"fileName\"`\n\t}{}\n\terr := json.Unmarshal(c.Ctx.Input.RequestBody, &img)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\t// remove thumbnail\n\terr = os.Remove(thumbnailsFolder + img.FileName)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\t// remove main image\n\terr = os.Remove(imagesFolder + img.FileName)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tc.Data[\"json\"] = img\n\tc.ServeJSON()\n}", "func (client *GalleryImageVersionsClient) delete(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, options *GalleryImageVersionsBeginDeleteOptions) (*azcore.Response, error) {\n\treq, err := client.deleteCreateRequest(ctx, resourceGroupName, galleryName, galleryImageName, galleryImageVersionName, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := client.con.Pipeline().Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !resp.HasStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent) {\n\t\treturn nil, client.deleteHandleError(resp)\n\t}\n\treturn resp, nil\n}", "func (o *Picture) Delete(exec boil.Executor) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no Picture provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), picturePrimaryKeyMapping)\n\tsql := \"DELETE FROM `pictures` WHERE `id`=?\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\t_, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to delete from pictures\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DeleteFile(res http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\tphotoID := params.ByName(\"id\")\n\n\tphoto := Photo{}\n\tdb.Get().First(&photo, \"id = ?\", photoID)\n\n\terr := os.Remove(photo.Path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdb.Get().Delete(&photo)\n\n\thttp.Redirect(res, req, \"/home\", http.StatusSeeOther)\n}", "func deleteImage(c *cli.Context) error {\n\terr := checkArgCount(c, 1)\n\tif err != nil {\n\t\treturn err\n\t}\n\tid := c.Args().First()\n\n\tif confirmed(c) {\n\t\tclient.Photonclient, err = client.GetClient(c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdeleteTask, err := client.Photonclient.Images.Delete(id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = waitOnTaskOperation(deleteTask.ID, c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tfmt.Println(\"OK, canceled\")\n\t}\n\n\treturn nil\n}", "func deleteImage(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\",\"application/json\")\n\tparam := mux.Vars(r)\n\t//CQL Operation\n\tif err:= Session.Query(`UPDATE albumtable SET imagelist=imagelist-['?'] WHERE albname=?;`,param[\"image\"],param[\"album\"]).Exec();err!=nil {\n\t\tfmt.Println(err)\n\t} else {\n\t\tfmt.Fprintf(w, \"New image added\")\n\t}\n}", "func (picHdlr *PictureHandler) DeletePicture(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tid, err := strconv.Atoi(ps.ByName(\"id\"))\n\n\tif err != nil {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\thttp.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)\n\t\treturn\n\t}\n\tfmt.Println(\"id \", id)\n\n\terrs := picHdlr.picSrv.DeletePicture(id)\n\n\tif errs != nil {\n\t\tfmt.Println(errs)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\thttp.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusNoContent)\n\treturn\n}", "func (c *ImageController) Delete(ctx *app.DeleteImageContext) error {\n\t// ImageController_Delete: start_implement\n\n\t// Put your logic here\n\n\t// ImageController_Delete: end_implement\n\treturn nil\n}", "func (h *viewerHandler) softdelete(w http.ResponseWriter, r *http.Request) {\n\tif r.PostFormValue(h.pt.pr.DeletePicReally()) == \"\" {\n\t\thttpError(w, &HTTPErr{\n\t\t\tMessage: \"\\\"Really\\\" box not checked\",\n\t\t\tCode: http.StatusBadRequest,\n\t\t})\n\t\treturn\n\t}\n\n\trawDeletionReason := r.PostFormValue(h.pt.pr.DeletePicReason())\n\tdeletionReasonNum, err := strconv.ParseInt(rawDeletionReason, 10, 32)\n\tif err != nil {\n\t\thttpError(w, err)\n\t\treturn\n\t}\n\n\treq := &api.SoftDeletePicRequest{\n\t\tPicId: r.PostFormValue(h.pt.pr.PicId()),\n\t\tDetails: r.PostFormValue(h.pt.pr.DeletePicDetails()),\n\t\tReason: api.DeletionReason(deletionReasonNum),\n\t\tDeletionTime: nil,\n\t}\n\n\tctx := r.Context()\n\t_, err = h.c.SoftDeletePic(ctx, req)\n\tif err != nil {\n\t\thttpError(w, err)\n\t\treturn\n\t}\n\n\thttp.Redirect(w, r, h.pt.Viewer(req.PicId).RequestURI(), http.StatusSeeOther)\n}", "func (c *GalleryImageClient) Delete(ctx context.Context, location, name string) error {\n\treturn c.internal.Delete(ctx, location, name)\n}", "func (s *AvatarsService) Delete (ctx context.Context, entityType string, owningObjectID string, avatarID int64) (*http.Response, error) {\n\tendpoint := fmt.Sprintf(\"universal_avatar/type/%v/owner/%v/avatar/%v\", entityType, owningObjectID, avatarID)\n\treq, err := s.client.NewRequest(\"DELETE\", endpoint, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := s.client.Do(ctx, req, nil)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\treturn resp, err\n}", "func DeleteImageService(imageid string) bool {\n\tsuccess := domain.UserDeleteItem(imageid)\n\treturn success\n}", "func (s *Server) DeleteImage(w http.ResponseWriter, r *http.Request, params httprouter.Params) {\n\tUUID := params.ByName(\"UUID\")\n\tdeleteKey := params.ByName(\"key\")\n\timage, err := s.imageDao.Load(UUID)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\tif image.Delete != deleteKey {\n\t\tw.WriteHeader(http.StatusForbidden)\n\t\treturn\n\t}\n\terr = s.imageDao.Delete(image)\n\tif err != nil {\n\t\ts.logger.Println(err)\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\terr = s.fs.Delete(image)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n}", "func DeleteImage(c *fiber.Ctx) {\n\tShopID := c.Params(\"shop_id\")\n\n\tvar DeleteImage DataDeleteImage\n\n\tif errorParse := c.BodyParser(&DeleteImage); 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\t_, ErrorDelete := sq.Delete(\"images_shop\").\n\t\tWhere(\"url_image = ? AND shop_id = ?\", DeleteImage.URLImage, ShopID).\n\t\tRunWith(database).\n\t\tExec()\n\n\tif ErrorDelete != nil {\n\t\tfmt.Println(\"Error to delete image\", ErrorDelete)\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Error to delete image\"})\n\t\tc.Status(400)\n\t}\n\n\tc.JSON(SuccessResponse{MESSAGE: \"Imagen eliminada\"})\n}", "func (ser *UserMediaListService) Delete(id int, tx db.Tx) error {\n\treturn tx.Database().Delete(id, ser, tx)\n}", "func (r *repository) Delete(id uint) error {\n\tif err := r.db.Where(\"id = ?\", id).Delete(&models.Upload{}).Error; err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *UsersService) DeletePhoto() *UsersDeletePhotoCall {\n\tvar call UsersDeletePhotoCall\n\tcall.service = s\n\treturn &call\n}", "func DeleteUserProfileHandler(w http.ResponseWriter, r *http.Request) {\n\n}", "func (v *ImageClient) Delete(imageName string) error {\n\n\t//Construct the composite key to select the entry\n\tkey := ImageKey{\n\t\t// Owner:\townerName,\n\t\t// ClusterName:\tclusterName,\n\t\tImageName: imageName,\n\t}\n\terr := v.util.DBDelete(v.storeName, key, v.tagMeta)\n\n\t//Delete image from FS\n\tfilePath, _, err := v.GetDirPath(imageName)\n\tif err != nil {\n\t\treturn pkgerrors.Wrap(err, \"Get file path\")\n\t}\n\terr = os.Remove(filePath)\n if err != nil {\n return pkgerrors.Wrap(err, \"Delete image file\")\n }\n\n\treturn nil\n}", "func (c *Client) ImageDelete(imgID int) error {\n\targs := make(map[string]interface{})\n\targs[\"ImageID\"] = imgID\n\n\t_, err := c.apiCall(\"image.delete\", args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (me imageStore) Delete(imageID uint) (bool, error) {\n\tif err := me.Db.Unscoped().Exec(\"DELETE FROM images WHERE id = ? \", imageID).Error; err != nil {\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}", "func (pc UserController) Delete(c *gin.Context) {\n\tid := c.Params.ByName(\"id\")\n\tvar u repository.UserRepository\n\tidInt, _ := strconv.Atoi(id)\n\tif err := u.DeleteByID(idInt); err != nil {\n\t\tc.AbortWithStatus(403)\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\tc.JSON(200, gin.H{\"success\": \"ID\" + id + \"のユーザーを削除しました\"})\n\treturn\n}", "func deleteImageResource(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {\n\t// Warning or errors can be collected in a slice type\n\tvar diags diag.Diagnostics\n\tclient := (meta.(Client)).Client\n\tname := rdEntryStr(d, \"name\")\n\tid := rdEntryStr(d, \"id\")\n\terrMsgPrefix := getErrMsgPrefix(\"Image\", name, id, \"Delete\")\n\tcfg, err := getImage(client, name, id)\n\tif err != nil {\n\t\treturn diag.Errorf(\"%s Failed to get Image. err: %s\", errMsgPrefix, err.Error())\n\t}\n\tif cfg == nil {\n\t\tlog.Printf(\"%s Unexpected Error. nil config\", errMsgPrefix)\n\t\treturn diags\n\t}\n\tclient.XRequestIdPrefix = \"TF-image-delete\"\n\turlExtension := getImageUrl(name, id, \"delete\")\n\trspData := &swagger_models.ZsrvResponse{}\n\t_, err = client.SendReq(\"DELETE\", urlExtension, nil, rspData)\n\tif err != nil {\n\t\treturn diag.Errorf(\"%s. Request Failed. err: %s\", errMsgPrefix, err.Error())\n\t}\n\tlog.Printf(\"[INFO] Image %s(id:%s) Delete Successful.\", name, cfg.ID)\n\treturn diags\n}", "func DeleteUser(c *gin.Context) {}", "func (m *ItemPhotoRequestBuilder) Delete(ctx context.Context, requestConfiguration *ItemPhotoRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.ToDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.BaseRequestBuilder.RequestAdapter.SendNoContent(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func (f *FakeImagesClient) Delete(ctx context.Context, deleteOpts *images.DeleteRequest, opts ...grpc.CallOption) (*googleprotobuf.Empty, error) {\n\tf.Lock()\n\tdefer f.Unlock()\n\tf.appendCalled(\"delete\", deleteOpts)\n\tif err := f.getError(\"delete\"); err != nil {\n\t\treturn nil, err\n\t}\n\t_, ok := f.ImageList[deleteOpts.Name]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"image does not exist\")\n\t}\n\tdelete(f.ImageList, deleteOpts.Name)\n\treturn &googleprotobuf.Empty{}, nil\n}", "func (cmd *SLCommand) Delete(args []string) error {\n\tl := newModifyFlags()\n\tif err := l.flagSet.Parse(args); err != nil {\n\t\treturn nil // we don't return error, the usage will be printed instead\n\t}\n\n\tif len(l.imageIds) == 0 {\n\t\treturn errors.New(\"no value for -ids flag\")\n\t}\n\n\treturn cmd.DeleteImages(l.imageIds...)\n}", "func (ctrl *RedirCtrl) Delete(c *gin.Context) {\n\tif c.Param(\"redirect\") != \"api\" || c.Param(\"url\") == \"\" {\n\t\tc.JSON(ctrl.Config.STATUS_CODES[\"BAD_REQUEST\"], gin.H{\n\t\t\t\"error\": \"Bad Request\",\n\t\t})\n\t\treturn\n\t}\n\tredir := c.Param(\"url\")\n\t// check if exists\n\tredirect, err := ctrl.RedirService.FindByRedirect(context.TODO(), redir, models.REDIRECTSCOLLECTION)\n\tif err != nil {\n\t\tc.JSON(ctrl.Config.STATUS_CODES[\"INTERNAL_SERVER_ERROR\"], gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\tredirect.Deleted = true\n\tredirDeleteForm := models.DeleteRedirectForm{\n\t\tDeleted: redirect.Deleted,\n\t\tUpdatedAt: time.Now(),\n\t}\n\t// updates deleted field to true\n\t_, err = ctrl.RedirService.Update(context.TODO(), redirect.ID, redirDeleteForm, models.REDIRECTSCOLLECTION)\n\tif err != nil {\n\t\tc.JSON(ctrl.Config.STATUS_CODES[\"INTERNAL_SERVER_ERROR\"], gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\tc.JSON(ctrl.Config.STATUS_CODES[\"OK\"], redirect)\n}", "func (c *UnsavedPostImageClient) Delete() *UnsavedPostImageDelete {\n\tmutation := newUnsavedPostImageMutation(c.config, OpDelete)\n\treturn &UnsavedPostImageDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (a *ImageApiService) DeleteUserImage(ctx _context.Context, userId string, imageType ImageType, index int32, itemType string) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/Users/{userId}/Images/{itemType}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"userId\"+\"}\", _neturl.QueryEscape(parameterToString(userId, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"imageType\"+\"}\", _neturl.QueryEscape(parameterToString(imageType, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"index\"+\"}\", _neturl.QueryEscape(parameterToString(index, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"itemType\"+\"}\", _neturl.QueryEscape(parameterToString(itemType, \"\")) , -1)\n\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{}\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\", \"application/json; profile=CamelCase\", \"application/json; profile=PascalCase\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"X-Emby-Authorization\"] = key\n\t\t}\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 nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn 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 == 403 {\n\t\t\tvar v ProblemDetails\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 localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func DeleteImages(c echo.Context) error {\n\terr := model.DeleteImages()\n\tif err != nil {\n\t\treturn c.String(http.StatusExpectationFailed, \"failed\")\n\t}\n\treturn c.String(http.StatusOK, \"deleted\")\n}", "func Delete(c *gin.Context) {\n\ttokenStr := c.Request.Header.Get(\"Authorization\")\n\tif tokenStr == \"\" || len(tokenStr) < 7 {\n\t\tfailUpdate(c, http.StatusUnauthorized, \"Unauthorized\")\n\t\treturn\n\t}\n\t_, admin, valid, err := ParseToken(tokenStr[7:])\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tif !valid || !admin {\n\t\tfailUpdate(c, http.StatusUnauthorized, \"Unauthorized\")\n\t\treturn\n\t}\n\n\tuserid := c.Param(\"userid\")\n\n\terr = model.Delete(userid)\n\tif err != nil {\n\t\tfailUpdate(c, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tc.JSON(http.StatusNoContent, gin.H{\n\t\t\"message\": \"Deleted successfully\",\n\t\t\"status\": http.StatusNoContent,\n\t})\n}", "func DeletePagenote(w http.ResponseWriter, req *http.Request) {\n\tdefer log.WithTrace().Info(\"DeletePagenote...\")\n\tsecurity.EnableCORS(w)\n\tif (isHTTPOption(req)) {\n\t\treturn\n\t}\n\tif !requirePost(w, req) {\n\t\tlog.Warn(\"DeletePagenote: invalid http method...\")\n\t\treturn\n\t}\n\tif !requireAuth(w, req) {\n\t\tlog.Warn(\"SavePagenote: not authorized...\")\n\t\treturn\n\t}\n\tidList := parseRemoveNotesRequest(req)\n\tdeleted := rmNotes(idList)\n\twriteRespMessage(w, nil, deleted)\n}", "func doDelete(w http.ResponseWriter, r *http.Request) {\n\n\t// get the user ID from the path\n\tfields := strings.Split(r.URL.String(), \"/\")\n\tid, err := strconv.ParseUint(fields[len(fields)-1], 10, 64)\n\tif nil != err {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog.Printf(\"Request to delete user %v\", id)\n\n\t// start of protected code changes\n\tlock.Lock()\n\tvar tmp = []*User{}\n\tfor _, u := range db {\n\t\tif id == u.ID {\n\t\t\tcontinue\n\t\t}\n\t\ttmp = append(tmp, u)\n\t}\n\tdb = tmp\n\t// end protected code changes\n\tlock.Unlock()\n}", "func TestAlbumAddDeletePhoto(t *testing.T) {\n\talbum := api.Album{\n\t\tAlbumTitle: WellKnownAlbumTitle,\n\t}\n\n\tnewAlbum, err := Client.V1().CreateAlbum(album)\n\tif err != nil {\n\t\tt.Errorf(\"expected success creating album: %v\", err)\n\t\tt.FailNow()\n\t}\n\n\t// Add Photos\n\tphotos := []string{\n\t\tWellKnownPhotoID,\n\t}\n\terr = Client.V1().AddPhotosToAlbum(newAlbum.AlbumUID, photos)\n\tif err != nil {\n\t\tt.Errorf(\"expected to add photos to album: %v\", err)\n\t\t// Note: We do NOT FailNow() here because we want to clean up\n\t}\n\n\t// Get the photos by album\n\tupdatedPhotos, err := Client.V1().GetPhotos(&api.PhotoOptions{\n\t\tCount: 100,\n\t\tAlbumUID: newAlbum.AlbumUID,\n\t})\n\tif err != nil {\n\t\tt.Errorf(\"expecting to list photos by album: %v\", err)\n\t\t// Note: We do NOT FailNow() here because we want to clean up\n\t}\n\n\tvar updatedPhotoIDs []string\n\tfor _, photo := range updatedPhotos {\n\t\tupdatedPhotoIDs = append(updatedPhotoIDs, photo.PhotoUID)\n\t}\n\tif len(updatedPhotos) != 2 {\n\t\tt.Errorf(\"expecting 2 well known photo in album, found: %d\", len(updatedPhotos))\n\t}\n\n\terr = Client.V1().DeletePhotosFromAlbum(newAlbum.AlbumUID, updatedPhotoIDs)\n\tif err != nil {\n\t\tt.Errorf(\"expected to delete newly created photos from album: %v\", err)\n\t\t// Note: We do NOT FailNow() here because we want to clean up\n\t}\n\n\t// Get the photos by album\n\tupdatedPhotos, err = Client.V1().GetPhotos(&api.PhotoOptions{\n\t\tCount: 100,\n\t\tAlbumUID: newAlbum.AlbumUID,\n\t})\n\tif err != nil {\n\t\tt.Errorf(\"expecting to list photos by album: %v\", err)\n\t\t// Note: We do NOT FailNow() here because we want to clean up\n\t}\n\n\tif len(updatedPhotos) != 0 {\n\t\tt.Errorf(\"expected empty album, found %d photos\", len(updatedPhotos))\n\t\t// Note: We do NOT FailNow() here because we want to clean up\n\t}\n\n\terr = Client.V1().DeleteAlbums([]string{newAlbum.AlbumUID})\n\tif err != nil {\n\t\tt.Errorf(\"expected delete album %s, album not deleted: %v\", newAlbum.AlbumUID, err)\n\t\tt.FailNow()\n\t}\n\n\t// put the album back\n\tCreateWellKnownAlbum()\n}", "func deleteVolunteer(c *gin.Context) {\n\temail := c.Params.ByName(\"email\")\n\tvar vol Volunteer\n\tif err := db.Where(\"email = ?\", email).Find(&vol).Error; err != nil {\n\t\tcreateNotFoundResponse(c)\n\t\treturn\n\t}\n\n\t//Checks if data belongs to the user\n\tif !volunteerAuth(c, &vol) {\n\t\treturn\n\t}\n\t//Deletes from database\n\tdb.Delete(&vol)\n\n\t//Deletes from authentification map\n\tdelete(authMap, vol.Email)\n\tc.JSON(200, gin.H{\"Message\": email + \" deleted\"})\n}", "func deleteProfile(w http.ResponseWriter, r *http.Request) {\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparams := mux.Vars(r)[\"id\"] //get Parameter value as string\n\n\t_id, err := primitive.ObjectIDFromHex(params) // convert params to mongodb Hex ID\n\tif err != nil {\n\t\tfmt.Printf(err.Error())\n\t}\n\topts := options.Delete().SetCollation(&options.Collation{}) // to specify language-specific rules for string comparison, such as rules for lettercase\n\tres, err := userCollection.DeleteOne(context.TODO(), bson.D{{\"_id\", _id}}, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"deleted %v documents\\n\", res.DeletedCount)\n\tjson.NewEncoder(w).Encode(res.DeletedCount) // return number of documents deleted\n\n}", "func (s *Service) SignaturesDeleteImage(imageType string, signatureID string, userID string) *SignaturesDeleteImageOp {\n\treturn &SignaturesDeleteImageOp{\n\t\tCredential: s.credential,\n\t\tMethod: \"DELETE\",\n\t\tPath: strings.Join([]string{\"users\", userID, \"signatures\", signatureID, imageType}, \"/\"),\n\t\tAccept: \"application/json\",\n\t\tQueryOpts: make(url.Values),\n\t\tVersion: esign.APIv21,\n\t}\n}", "func (a *ImageApiService) DeleteUserImage2(ctx _context.Context, userId string, imageType ImageType, index int32, itemType string) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/Users/{userId}/Images/{itemType}/{index}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"userId\"+\"}\", _neturl.QueryEscape(parameterToString(userId, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"imageType\"+\"}\", _neturl.QueryEscape(parameterToString(imageType, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"index\"+\"}\", _neturl.QueryEscape(parameterToString(index, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"itemType\"+\"}\", _neturl.QueryEscape(parameterToString(itemType, \"\")) , -1)\n\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{}\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\", \"application/json; profile=CamelCase\", \"application/json; profile=PascalCase\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"X-Emby-Authorization\"] = key\n\t\t}\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 nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn 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 == 403 {\n\t\t\tvar v ProblemDetails\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 localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (c *PostImageClient) Delete() *PostImageDelete {\n\tmutation := newPostImageMutation(c.config, OpDelete)\n\treturn &PostImageDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *Client) Delete(path string) error {\n\t_, _, err := c.sendRequest(\"DELETE\", fmt.Sprintf(\"files/%s/%s\", c.Username, path), nil, nil, nil)\n\treturn err\n}", "func Delete(c *gin.Context) {\n\tuserID, err := getUserID(c.Param(\"user_id\"))\n\tif err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\n\tif err := services.UserServ.DeleteUser(userID); err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, map[string]string{\"status\": \"deleted\"})\n}", "func (m *DeleteImageTagModel) Delete() (err error) {\n\n\t// check model validity\n\tif !m.IsValid() {\n\t\treturn errors.New(\"DeleteImageTagModel is not valid\")\n\t}\n\n\t// Get Database handle\n\tdbase, err := db.GetDb()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tps1, err := dbase.Prepare(`DELETE tm FROM tagmap AS tm\n INNER JOIN tags ON tm.tag_id = tags.tag_id\n WHERE image_id = ? AND tm.tag_id = ? AND ib_id = ?`)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer ps1.Close()\n\n\t_, err = ps1.Exec(m.Image, m.Tag, m.Ib)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n\n}", "func RunImagesDelete(ns string, config doit.Config, out io.Writer, args []string) error {\n\tclient := config.GetGodoClient()\n\n\tif len(args) != 1 {\n\t\treturn doit.NewMissingArgsErr(ns)\n\t}\n\n\tid, err := strconv.Atoi(args[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = client.Images.Delete(id)\n\treturn err\n}", "func (g Goba) DeleteImage(typ DatabaseType, name string) error {\n\tfor _, handler := range g.handlers {\n\t\tif handler.Type() == typ {\n\t\t\treturn handler.DeleteImage(name)\n\t\t}\n\t}\n\treturn ErrNoSuchHandler\n}", "func _delete(context echo.Context, user *User) error {\n\tdeleteErr := Remove(user.Key)\n\tif deleteErr != nil {\n\t\tlog.Printf(\"Cannot delete user %v\", deleteErr)\n\t\treturn context.JSON(http.StatusInternalServerError, errors.New(\"Cannot delete user with ID: \"+user.ID))\n\t}\n\treturn context.NoContent(http.StatusNoContent)\n}", "func Delete(client *gophercloud.ServiceClient, id string, bearer map[string]string) (r volumes.DeleteResult) {\n\t_, r.Err = client.Delete(deleteURL(client, id), &gophercloud.RequestOpts{\n\t\tMoreHeaders: bearer,\n\t})\n\treturn\n}", "func Delete(c *gin.Context) {\n\tuserID, idErr := getUserID(c.Param(\"user_id\"))\n\tif idErr != nil {\n\t\tc.JSON(idErr.Status, idErr)\n\t\treturn\n\t}\n\tif err := services.UserService.DeleteUser(userID); err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\t/*VERY IMPORTANT TO RETURN THE SAME CONTENT TYPE IN\n\tSUCCESS AS IN ERRORS\n\tIE. if we return c.JSON... for failure we can not later use\n\t c.String for success becouse we realize we not have a payload\n\t They must be the same.\n\n\t*/\n\n\tc.JSON(http.StatusOK, map[string]string{\"status\": \"deleted\"})\n\n}", "func (client *GalleryImagesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, options *GalleryImagesClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif galleryName == \"\" {\n\t\treturn nil, errors.New(\"parameter galleryName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{galleryName}\", url.PathEscape(galleryName))\n\tif galleryImageName == \"\" {\n\t\treturn nil, errors.New(\"parameter galleryImageName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{galleryImageName}\", url.PathEscape(galleryImageName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-07-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func FileDeleteHandler(w http.ResponseWriter, r *http.Request) {\n\tr.ParseForm()\n\n\tfileSha1 := r.Form.Get(\"filehash\")\n\tfileMeta := meta.GetFileMeta(fileSha1)\n\n\t//delete file from disk\n\terr := os.Remove(fileMeta.FileAddr)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// delete file index\n\tmeta.RemoveFileMeta(fileSha1)\n\n\tw.WriteHeader(http.StatusOK)\n}", "func DeleteAlbum(albumDeleteHash string, clientID string) {\n\turl := \"https://api.imgur.com/3/album/\" + albumDeleteHash\n\tmethod := \"DELETE\"\n\n\tpayload := &bytes.Buffer{}\n\twriter := multipart.NewWriter(payload)\n\terr := writer.Close()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(method, url, payload)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\treq.Header.Add(\"Authorization\", \"Client-ID \"+clientID)\n\n\treq.Header.Set(\"Content-Type\", writer.FormDataContentType())\n\tres, err := client.Do(req)\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tif strings.Contains(string(body), \"200\") {\n\t\tfmt.Println(color.GreenString(\"[+]\"), \"Delete was a success\")\n\t}\n\n}", "func handleDelete(ctx *verifierContext, status *types.VerifyImageStatus) {\n\n\tlog.Functionf(\"handleDelete(%s) refcount %d\",\n\t\tstatus.ImageSha256, status.RefCount)\n\n\tif _, err := os.Stat(status.FileLocation); err == nil {\n\t\tlog.Functionf(\"handleDelete removing %s\",\n\t\t\tstatus.FileLocation)\n\t\tif err := os.RemoveAll(status.FileLocation); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t} else {\n\t\tlog.Warnf(\"handleDelete: Unable to delete %s: %s\",\n\t\t\tstatus.FileLocation, err)\n\t}\n\n\tunpublishVerifyImageStatus(ctx, status)\n\tlog.Functionf(\"handleDelete done for %s\", status.ImageSha256)\n}", "func RemoveUploadedImage(ctx *gin.Context) {\n\n\timageID, _ := strconv.Atoi(ctx.Param(\"id\"))\n\n\tdatabase.DB.Delete(&models.Image{Model: gorm.Model{ID: uint(imageID)}})\n\n\tctx.JSON(http.StatusNoContent, nil)\n}", "func Delete(c *gin.Context) {\n\tuserId, idErr := getUserID(c.Param(\"user_id\"))\n\tif idErr != nil {\n\t\tc.JSON(idErr.Status, idErr)\n\t\treturn\n\t}\n\n\tif err := services.UsersService.DeleteUser(userId); err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, map[string]string{\"status\": \"deleted\"})\n}", "func (a UsersAPI) Delete(userID string) error {\n\tuserPath := fmt.Sprintf(\"/preview/scim/v2/Users/%v\", userID)\n\treturn a.client.Scim(a.context, http.MethodDelete, userPath, nil, nil)\n}", "func (s *Store) Delete(c *gin.Context) {\n\n}", "func (g *GistFile) Delete(id string) (*http.Response, error) {\n\turll := fmt.Sprintf(\"/gists/%s\", id)\n\treq, err := http.NewRequest(http.MethodDelete, urll, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := auth.Session.Client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func TagDelete(c *gin.Context) {\n\tdb := models.GetDB()\n\ttag := models.Tag{}\n\tdb.First(&tag, c.Param(\"title\"))\n\tif len(tag.Title) == 0 {\n\t\tc.HTML(http.StatusNotFound, \"errors/404\", nil)\n\t\treturn\n\t}\n\tif err := db.Delete(&tag).Error; err != nil {\n\t\tlogrus.Error(err)\n\t\tc.HTML(http.StatusInternalServerError, \"errors/500\", gin.H{\"Error\": err.Error()})\n\t\treturn\n\t}\n\tc.Redirect(http.StatusFound, \"/admin/tags\")\n}", "func (h *Handler) DeleteImage(w http.ResponseWriter, r *http.Request) {\n\timageName := r.URL.Query().Get(\"name\")\n\timagePool := r.URL.Query().Get(\"pool\")\n\n\tdeleteImageReq := model.BlockImage{\n\t\tName: imageName,\n\t\tPoolName: imagePool,\n\t}\n\n\tif deleteImageReq.Name == \"\" || deleteImageReq.PoolName == \"\" {\n\t\tlogger.Errorf(\"image missing required fields: %+v\", deleteImageReq)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr := ceph.DeleteImage(h.context, h.config.clusterInfo.Name, deleteImageReq.Name, deleteImageReq.PoolName)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to delete image %+v: %+v\", deleteImageReq, err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write([]byte(fmt.Sprintf(\"succeeded deleting image %s\", deleteImageReq.Name)))\n}", "func Delete(c *gin.Context) {\r\n\tpost := getById(c)\r\n\tif post.ID == 0 {\r\n\t\treturn\r\n\t}\r\n\tdb.Unscoped().Delete(&post)\r\n\tc.JSON(http.StatusOK, gin.H{\r\n\t\t\"messege\": \"deleted successfuly\",\r\n\t\t\"data\": \"\",\r\n\t})\r\n}", "func (s UserAuthServiceImpl) DeleteManyUserAuth(filter interface{}) error {\n\n\tresult := <-s.UserAuthRepo.Delete(userAuthCollectionName, filter, false)\n\tif result.Error != nil {\n\t\treturn result.Error\n\t}\n\treturn nil\n}", "func (u *App) Delete(c echo.Context, id string) error {\n\tfile, err := u.udb.View(u.db, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := u.rbac.EnforceUser(c, file.UserID); err != nil {\n\t\treturn err\n\t}\n\n\tif file.Type == model.ResourceApplication {\n\t\tif err = u.rbac.EnforceRole(c, model.OperatorRole); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tgo model.DeleteFiles(&[]model.File{*file})\n\treturn u.udb.Delete(u.db, id)\n}", "func deleteImage(t *testing.T, projectID string, imageName string) {\n\t// Load the Image ID saved by the earlier build_image stage\n\timage := gcp.FetchImage(t, projectID, imageName)\n\timage.DeleteImage(t)\n}", "func (cl Client) DeleteAnonymousUploadedImg(deleteHash string) (DeleteResponse, error) {\n\tvar err error\n\tir := DeleteResponse{}\n\trequest, _ := cl.PrepareAuthRequest(\"DELETE\", ImageBase+\"/\"+deleteHash)\n\tresponse, err := cl.Do(request)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer response.Body.Close()\n\tbody, err := ioutil.ReadAll(response.Body)\n\n\terr = json.Unmarshal(body, &ir)\n\tif err != nil {\n\t\treturn ir, err\n\t}\n\treturn ir, err\n}", "func DeleteGalleryHandler(db *sql.DB) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tgalleryID := mux.Vars(r)[\"id\"]\n\n\t\terr := DeleteGallery(db, galleryID)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error: %v\", err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"Success\"))\n\t}\n}", "func Delete() error {\n\n}", "func del(w http.ResponseWriter, r *http.Request) {\n\tname := r.URL.Query().Get(\":name\")\n\tdelete(pets, name)\n}", "func (f FileDAO) Delete(name, password string) error {\n\t//Perform security verification\n\tif _, err := f.Read(name, password); err != nil {\n\t\treturn err\n\t}\n\n\tfilename, err := f.filename(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn os.Remove(filename)\n}", "func (m *MockUsecase) DeletePhotos(comment commModel.Comment) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeletePhotos\", comment)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func db_delete_user(username string) {\n file_path := path.Join(\"db/users\", strings.ToLower(username) + \".json\")\n\n err := os.Remove(file_path)\n \n if err != nil {\n fmt.Println(err.Error())\n return\n }\n fmt.Println(\"User Removed: \", username)\n}", "func (h *UserHandler) Delete(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tidStr := vars[\"id\"]\n\tid, err := strconv.ParseUint(idStr, 10, 64)\n\tif err != nil {\n\t\tlog.Println(errors.Wrapf(err, \"error parse uint:%v\", idStr))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog.Printf(\"/users/%d DELETE handled\", id)\n\n\tif err := h.model.Delete(id); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusNoContent)\n}", "func (c *UsersDeletePhotoCall) Do(ctx context.Context) error {\n\tconst endpoint = \"users.deletePhoto\"\n\tv, err := c.Values()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar res struct {\n\t\tobjects.GenericResponse\n\t}\n\tif err := c.service.client.postForm(ctx, endpoint, v, &res); err != nil {\n\t\treturn errors.Wrap(err, `failed to post to users.deletePhoto`)\n\t}\n\tif !res.OK {\n\t\treturn errors.New(res.Error.String())\n\t}\n\n\treturn nil\n}", "func DeletePerson(c *gin.Context) {\n // Get model if exist\n var person models.Person\n if err := models.DB.First(&person, \"id = ?\", c.Param(\"id\")).Error; err != nil {\n c.JSON(http.StatusBadRequest, gin.H{\"error\": \"Record not found!\"})\n return\n }\n\n models.DB.Delete(&person)\n\n c.JSON(http.StatusOK, gin.H{\"data\": true})\n}", "func DeleteController(ctx iris.Context) {\n\tu, ok := ctx.Values().Get(middlewares.ContextKey).(*user.User)\n\tif !ok {\n\t\tutils.ResponseErr(ctx, ErrBadUser)\n\t\treturn\n\t}\n\tid := ctx.Params().Get(\"id\")\n\tvar g gost.Gost\n\terr := g.GetGostById(id)\n\tif err != nil {\n\t\tutils.ResponseErr(ctx, ErrGostNotFound)\n\t\treturn\n\t}\n\tif u.Username != g.User.Username {\n\t\tutils.ResponseErr(ctx, ErrNotYourOwn)\n\t\treturn\n\t}\n\terr = g.Remove(true)\n\tif err != nil {\n\t\tutils.ResponseErr(ctx, err)\n\t\treturn\n\t}\n\tutils.ResponseData(ctx, fmt.Sprintf(\"Gost remove success %s!\", g.ID))\n}", "func Delete(w http.ResponseWriter, r *http.Request){\n\n\t//pegando a url atraves da requisiçãp (.Get = pegar )\n\tidDoProduto := r.URL.Query().Get(\"id\") // pegando o id da url\n\n\tmodels.DeletaProduto(idDoProduto)\n\thttp.Redirect(w, r, \"/\", 301)\n}", "func (u *App) Delete(c echo.Context, id string) error {\n\tif err := u.rbac.EnforceRole(c, model.AdminRole); err != nil {\n\t\treturn err\n\t}\n\n\tpost, err := u.udb.View(u.db, id)\n\tif err = zaplog.ZLog(err); err != nil {\n\t\treturn err\n\t}\n\n\tif post.Status != model.StatusDraft {\n\t\treturn zaplog.ZLog(errors.New(\"Apenas é possível eliminar artigos em rascunho\"))\n\t}\n\n\treturn u.udb.Delete(u.db, id)\n}", "func (client *GalleryImageVersionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, options *GalleryImageVersionsBeginDeleteOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{galleryName}\", url.PathEscape(galleryName))\n\turlPath = strings.ReplaceAll(urlPath, \"{galleryImageName}\", url.PathEscape(galleryImageName))\n\turlPath = strings.ReplaceAll(urlPath, \"{galleryImageVersionName}\", url.PathEscape(galleryImageVersionName))\n\treq, err := azcore.NewRequest(ctx, http.MethodDelete, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\tquery := req.URL.Query()\n\tquery.Set(\"api-version\", \"2020-09-30\")\n\treq.URL.RawQuery = query.Encode()\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func uploadDeleteHandler(w http.ResponseWriter, r *http.Request) {\n\tupDownDelete(\"upload\", theCfg.uploadDir, false, w, r)\n\n}", "func (uc UserController) deleteUsers(response http.ResponseWriter, request *http.Request, p httprouter.Params) {\n\tresponse.Header().Add(\"content-type\", \"application/json\")\n\n\tctx, _ := context.WithTimeout(context.Background(), 10*time.Second)\n\tuc.collection.Drop(ctx)\n}", "func (app *App) Delete(ctx context.Context) error {\n\terr := app.Authenticate(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn app.User().Extensions().ID(app.ExtensionName).Request().Delete(ctx)\n}", "func (remoteAccessVpnUserApi *RemoteAccessVpnUserApi) Delete(remoteAccessVpnUser RemoteAccessVpnUser) (bool, error) {\n\tsend, merr := json.Marshal(remoteAccessVpnUser)\n\tif merr != nil {\n\t\treturn false, merr\n\t}\n\t_, err := remoteAccessVpnUserApi.entityService.Delete(remoteAccessVpnUser.Id, send, map[string]string{})\n\treturn err == nil, err\n}", "func (h *Handler) delete() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tvars := mux.Vars(r)\n\t\tid := vars[userID]\n\t\terr := h.UserDAO.Delete(r.Context(), id)\n\t\tswitch {\n\t\tcase errors.Is(err, errorx.ErrNoUser):\n\t\t\tmsg := &errorMessage{\n\t\t\t\tMessage: fmt.Sprintf(\"user %s does not exist\", id),\n\t\t\t}\n\t\t\tresponse.JSON(w, http.StatusNotFound, msg)\n\t\t\treturn\n\t\tcase errors.Is(err, errorx.ErrDeleteUser):\n\t\t\tmsg := &errorMessage{\n\t\t\t\tMessage: fmt.Sprintf(\"user %s has been deleted\", id),\n\t\t\t}\n\t\t\tresponse.JSON(w, http.StatusGone, msg)\n\t\t\treturn\n\t\tcase err != nil:\n\t\t\tmsg := &errorMessage{\n\t\t\t\tError: err.Error(),\n\t\t\t\tMessage: \"user datastore error\",\n\t\t\t}\n\t\t\tresponse.JSON(w, http.StatusInternalServerError, msg)\n\t\t\treturn\n\t\tdefault:\n\t\t\tresponse.JSON(w, http.StatusNoContent, nil)\n\t\t}\n\t}\n\n}", "func Delete(c *gin.Context) {\n\tid, err := strconv.Atoi(c.Param(\"id\"))\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\terr = utils.DeleteItem(id)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\tc.JSON(200, gin.H{\"status\": \"Item deleted\"})\n}", "func RawDelete(restClient *rest.RESTClient, streams genericiooptions.IOStreams, url, filename string) error {\n\treturn raw(restClient, streams, url, filename, \"DELETE\")\n}", "func qemuImgDelete(sysOS *sys.OS, imgPath string) error {\n\treturn deleteProfile(sysOS, qemuImgProfileName(imgPath), qemuImgProfileFilename(imgPath))\n}", "func (o *BraceletPhoto) DeleteG() error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no BraceletPhoto provided for deletion\")\n\t}\n\n\treturn o.Delete(boil.GetDB())\n}", "func (file *File) Delete() (err error) {\n\treturn file.upload.client.removeFile(file.upload.getParams(), file.getParams())\n}", "func (c *client) Delete(_ context.Context, request *blobstore.DeleteRequest) (*blobstore.DeleteResponse, error) {\n\tif err := os.Remove(c.bodyPath(request.Key)); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := os.Remove(c.tagsPath(request.Key)); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &blobstore.DeleteResponse{}, nil\n}" ]
[ "0.7011417", "0.69017696", "0.6777559", "0.67353654", "0.6700946", "0.6612022", "0.6590683", "0.6524534", "0.64540064", "0.6401866", "0.6380001", "0.63725716", "0.63711727", "0.6361337", "0.62740403", "0.6255791", "0.6253453", "0.6214657", "0.6205462", "0.6102082", "0.6092225", "0.606276", "0.60535353", "0.6013737", "0.601086", "0.59943", "0.5992324", "0.5987911", "0.59518427", "0.5905958", "0.589955", "0.5892575", "0.5892199", "0.5889856", "0.5880082", "0.5876062", "0.5852813", "0.58149385", "0.5808859", "0.5801041", "0.57993287", "0.57970273", "0.57818574", "0.57768536", "0.57729596", "0.5750679", "0.5730916", "0.5730758", "0.5719538", "0.5716017", "0.5715064", "0.57113147", "0.5686568", "0.56728965", "0.567011", "0.5663608", "0.5652507", "0.5640254", "0.5617464", "0.56103575", "0.56048447", "0.55976784", "0.55928093", "0.5578187", "0.5573011", "0.55712324", "0.5562511", "0.5559287", "0.5556317", "0.5535152", "0.5533238", "0.55133885", "0.55036587", "0.55021286", "0.5496939", "0.5477866", "0.5476947", "0.5464066", "0.54624665", "0.54610807", "0.54547924", "0.5452429", "0.54497415", "0.544794", "0.54400885", "0.5439376", "0.5435449", "0.54305935", "0.54274464", "0.5424607", "0.5418078", "0.54158527", "0.5409013", "0.540898", "0.54035115", "0.5397862", "0.53973097", "0.5394815", "0.5394576", "0.5385406" ]
0.7924666
0
Forward declaration of isBadVersion API.
func firstBadVersion(n int) int { return sort.Search(n, func(version int) bool { return isBadVersion(version) }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func isBadVersion(version int) bool{\n return false\n}", "func isBadVersion(version int) bool{\n\treturn true\n}", "func IsVersionMismatch(err error) (match bool) {\n\t_, match = err.(*VersionMismatchError)\n\treturn\n}", "func _isValidFileVersion(v FileVersion) bool {\n\tif v.Format == nil {\n\t\treturn false\n\t}\n\tif v.Link == \"\" {\n\t\treturn false\n\t}\n\treturn true\n}", "func validateVersion(version string) bool {\n\treturn versionFilter.MatchString(version)\n}", "func (e BadRequest) IsBadRequest() {}", "func (s *SwaggerSchema) isDifferentApiVersion(obj *unstructured.Unstructured) bool {\n\tgroupVersion := obj.GetAPIVersion()\n\treturn len(groupVersion) > 0 && s.api.ApiVersion != groupVersion\n}", "func ValidateFormatVersion(formatVersion uint32) (bool) {\n if formatVersion == 1 || formatVersion == 2 || formatVersion == 3 || formatVersion == 4 { //format version should still be 1 for now\n return true\n }\n return false\n}", "func isValidVersion(version string) bool {\n\n\tisOk, _ := regexp.MatchString(\"^v\\\\d+\\\\.\\\\d+\\\\.\\\\d+\", version)\n\treturn isOk\n}", "func isValidVersion(s string) bool {\n\n\tif s == \"\" {\n\t\t//assume latest version\n\t\treturn true\n\t}\n\n\tif s[0] == 'v' && len(s) > 1 && isNumeric(string(s[1])) {\n\t\treturn true\n\t}\n\n\tif isNumeric(string(s[0])) {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func isValidVersion(v string) bool {\n\trule := regexp.MustCompile(`^\\d+\\.\\d+\\.\\d+$`)\n\treturn rule.MatchString(v)\n}", "func IsVersion(s string) bool {\n\tvs := ReturnVersions()\n\tfor _, v := range vs {\n\t\tif v == s {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func validateVersion(p *field.Path, value string) field.ErrorList {\n\terrs := field.ErrorList{}\n\t_, err := api.ParseVersion(value)\n\tif err != nil {\n\t\terrs = append(errs, field.Invalid(p, value, err.Error()))\n\t}\n\treturn errs\n}", "func IsValidXAPIVersion(version string) bool {\n\treturn ToXAPIVersion(version) != XAPIVersionVoid\n}", "func isValidVersionFormat(version string) bool {\n\tmatch, _ := regexp.MatchString(\"[0-9]+\\\\.[0-9]+\\\\.[0-9]+\", version)\n\treturn match\n}", "func (pr LocalPackageReference) HasApiVersion(ver string) bool {\n\treturn strings.EqualFold(pr.apiVersion, ver)\n}", "func isV2OrHigherIncompat(version string) bool {\r\n\tif !semver.IsValid(version) {\r\n\t\treturn false\r\n\t}\r\n\tmajor := semver.Major(version)\r\n\t// minor nuance: here we are purposefully attempting to treat v2.0.0-alpha as a \"v2\" release\r\n\treturn major != \"v0\" && major != \"v1\" && semver.Build(version) == \"+incompatible\"\r\n}", "func isValidVersion(version string) bool {\n\tif len(version) == 0 {\n\t\treturn true\n\t}\n\n\tisOk, _ := regexp.MatchString(\"^[1-9]\\\\.([8-9]\\\\d*|[1-9]\\\\d+)|^[1-9]\\\\d+\\\\.|^[2-9]\\\\.\", version)\n\treturn isOk\n}", "func checkVersion(ver string) error {\n\tif ver[0] == 'v' {\n\t\tver = ver[1:]\n\t}\n\tv, err := semver.NewVersion(ver)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc, err := semver.NewConstraint(\">= 1.2\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !c.Check(v) {\n\t\treturn ErrIncompatibleVersion\n\t}\n\treturn nil\n}", "func (a API) VersionChk() (isNew bool) {\n\tselect {\n\tcase o := <-a.Ch.(chan VersionRes):\n\t\tif o.Err != nil {\n\t\t\ta.Result = o.Err\n\t\t} else {\n\t\t\ta.Result = o.Res\n\t\t}\n\t\tisNew = true\n\tdefault:\n\t}\n\treturn\n}", "func _IsSupportedPluginAPIVersion(version string) bool {\n\treturn version == \"0.0.8\"\n}", "func Valid(format, version string) error {\n\tversionParser, exists := GetParser(format)\n\tif !exists {\n\t\treturn ErrUnknownVersionFormat\n\t}\n\n\tif !versionParser.Valid(version) {\n\t\treturn ErrInvalidVersion\n\t}\n\n\treturn nil\n}", "func checkVersion(api *api) error {\n\tversion := api.runtimeVersion()\n\tcompVersion := api.compiledVersion()\n\tif (version >> 16) != (compVersion >> 16) {\n\t\treturn errors.Errorf(\"hwloc API incompatible with runtime: compiled for version 0x%x but using 0x%x\\n\",\n\t\t\tcompVersion, version)\n\t}\n\treturn nil\n}", "func IsValid(x string) bool {\n\treturn parse(x) != version{}\n}", "func IsValidVersion(value string) bool {\n\t_, err := semver.NewVersion(value)\n\treturn err == nil\n}", "func ValidateTransactionVersion(transactionVersion uint32) (bool) {\n if transactionVersion == 1 { //current transaction version\n return true\n }\n return false\n}", "func validateHardcodedVersion(wd string, version string) error {\n\tpkgs, err := packages.Load(&packages.Config{\n\t\tDir: filepath.Dir(wd),\n\t\tMode: packages.NeedName | packages.NeedFiles |\n\t\t\tpackages.NeedCompiledGoFiles | packages.NeedImports |\n\t\t\tpackages.NeedTypes | packages.NeedTypesSizes,\n\t}, \"golang.org/x/tools/gopls/internal/lsp/debug\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(pkgs) != 1 {\n\t\treturn fmt.Errorf(\"expected 1 package, got %v\", len(pkgs))\n\t}\n\tpkg := pkgs[0]\n\tobj := pkg.Types.Scope().Lookup(\"Version\")\n\tc, ok := obj.(*types.Const)\n\tif !ok {\n\t\treturn fmt.Errorf(\"no constant named Version\")\n\t}\n\thardcodedVersion, err := strconv.Unquote(c.Val().ExactString())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif semver.Prerelease(hardcodedVersion) != \"\" {\n\t\treturn fmt.Errorf(\"unexpected pre-release for hardcoded version: %s\", hardcodedVersion)\n\t}\n\t// Don't worry about pre-release tags and expect that there is no build\n\t// suffix.\n\tversion = strings.TrimSuffix(version, semver.Prerelease(version))\n\tif hardcodedVersion != version {\n\t\treturn fmt.Errorf(\"expected version to be %s, got %s\", *versionFlag, hardcodedVersion)\n\t}\n\treturn nil\n}", "func CheckAPIVersion(serverVersion string) chain.Middleware {\n\treturn func(next chain.Handler) chain.Handler {\n\t\treturn func(w http.ResponseWriter, r *http.Request) error {\n\t\t\tversions := r.Header[\"Draupnir-Version\"]\n\t\t\tif len(versions) == 0 {\n\t\t\t\tapi.MissingApiVersion.Render(w, http.StatusBadRequest)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tmajor, minor, _, err := version.ParseSemver(serverVersion)\n\n\t\t\t// If we can't parse our server version then we shouldn't react by rejecting all\n\t\t\t// requests.\n\t\t\tif err == nil {\n\t\t\t\trequestVersion := versions[0]\n\t\t\t\trequestMajor, requestMinor, _, err := version.ParseSemver(requestVersion)\n\n\t\t\t\tif err != nil || major != requestMajor || minor < requestMinor {\n\t\t\t\t\tapi.InvalidApiVersion(requestVersion).Render(w, http.StatusBadRequest)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn next(w, r)\n\t\t}\n\t}\n}", "func supportsVersionUpgrade(uc *upgradev1alpha1.UpgradeConfig) bool {\n\treturn empty(uc.Spec.Desired.Image) && !empty(uc.Spec.Desired.Version) && !empty(uc.Spec.Desired.Channel)\n}", "func ValidateVersion(version, service string, client *fastly.Client) {\n\tv, err := strconv.Atoi(version)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tcommon.Failure()\n\t}\n\n\tvalid, msg, err := client.ValidateVersion(&fastly.ValidateVersionInput{\n\t\tService: service,\n\t\tVersion: v,\n\t})\n\tif err != nil {\n\t\tfmt.Printf(\"\\nThere was a problem validating version %s\\n\\n%s\", common.Yellow(version), common.Red(err))\n\t\tcommon.Failure()\n\t}\n\n\tvar validColour, details string\n\n\tvalidColour = common.Green(valid)\n\n\tif valid == false {\n\t\tvalidColour = common.Red(valid)\n\t\tdetails = common.Red(msg)\n\t}\n\n\tfmt.Printf(\"\\nService '%s' valid? %s\\n\\n%s\", common.Yellow(service), validColour, details)\n}", "func checkSchemaVersion(version string) error {\n\t// First get the major version number from the schema. The schema version string should be in the format\n\t// \"major.minor.patch\", \"major.minor\", or \"major\".\n\n\tparts := strings.Split(version, \".\")\n\tif len(parts) == 0 {\n\t\treturn fmt.Errorf(\"error splitting schema version %q into parts\", version)\n\t}\n\n\tmajorVersion, err := strconv.Atoi(parts[0])\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error converting major version component %q to an integer: %v\", parts[0], err)\n\t}\n\n\t// Find the latest supported version for the major version and use that to determine if the provided version is\n\t// supported.\n\tsupportedVersion, ok := supportedSchemaVersions[majorVersion]\n\tif !ok {\n\t\treturn fmt.Errorf(\"major version %d not supported\", majorVersion)\n\t}\n\tif mtest.CompareServerVersions(supportedVersion, version) < 0 {\n\t\treturn fmt.Errorf(\n\t\t\t\"latest version supported for major version %d is %q, which is incompatible with specified version %q\",\n\t\t\tmajorVersion, supportedVersion, version,\n\t\t)\n\t}\n\treturn nil\n}", "func (u utilityEndpoints) versionCheck(c echo.Context) error {\n\tvf, err := u.version.VersionFormatter(version.FullVersion)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"format version\")\n\t\treturn c.JSON(http.StatusInternalServerError, NewErrorResponse(err))\n\t}\n\n\tmsg, update, err := u.version.UpdateWarningVersion(vf)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"update warning version\")\n\t\treturn c.JSON(http.StatusInternalServerError, NewErrorResponse(err))\n\t}\n\n\tresponse := VersionResponse{\n\t\tVersion: u.version.GetHumanVersion(),\n\t\tMsg: msg,\n\t\tUpdate: update,\n\t}\n\n\treturn c.JSON(http.StatusOK, response)\n}", "func isReleaseVersion(version string) bool {\n\tparts := strings.Split(version, \"-\")\n\n\tif len(parts) > 2 || strings.Contains(version, \"dirty\") || strings.Contains(version, \"-g\") {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (o *VirtualizationIweHost) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func isValidDowngrade(verFrom *semver.Version, verTo *semver.Version) bool {\n\treturn verTo.Equal(*AllowedDowngradeVersion(verFrom))\n}", "func ValidateVersion(h http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\turlPart := strings.Split(r.URL.Path, \"/\")\n\n\t\t// look for version in available version, or other endpoints\n\t\tfor _, ver := range jsonObject.Versions {\n\t\t\tif ver == urlPart[1] || r.URL.Path == \"/\" {\n\t\t\t\t// pass along\n\t\t\t\th.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// parse errror\n\t\tErrorHandler(w, r, http.StatusNotFound)\n\t\treturn\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func isNotIncompatible(content string) bool {\n\tver, err := version.NewVersion(content)\n\tif err != nil {\n\t\tpanic(errors.Wrapf(err, \"must've provided a valid semver\"))\n\t}\n\n\treturn ver.Metadata() != \"incompatible\"\n}", "func packageHasVersionSuffix(pkg string) bool {\n\tif pkg == \"\" {\n\t\treturn false\n\t}\n\tparts := strings.Split(pkg, \".\")\n\tif len(parts) < 2 {\n\t\treturn false\n\t}\n\tlastPart := parts[len(parts)-1]\n\tif len(lastPart) < 2 {\n\t\treturn false\n\t}\n\tif lastPart[0] != 'v' {\n\t\treturn false\n\t}\n\tversion := lastPart[1:]\n\tif strings.Contains(version, \"test\") {\n\t\tsplit := strings.SplitN(version, \"test\", 2)\n\t\tif len(split) != 2 {\n\t\t\treturn false\n\t\t}\n\t\treturn stringIsPositiveNumber(split[0])\n\t}\n\tif strings.Contains(version, \"alpha\") {\n\t\treturn packageVersionIsValidAlphaOrBeta(version, \"alpha\")\n\t}\n\tif strings.Contains(version, \"beta\") {\n\t\treturn packageVersionIsValidAlphaOrBeta(version, \"beta\")\n\t}\n\treturn stringIsPositiveNumber(version)\n}", "func validate(clientVersion, constraint string) (bool, error) {\n\tc, err := semver.NewConstraint(constraint)\n\tif err != nil {\n\t\treturn false, errors.Wrapf(err, \"unable to parse version constraint %q\", constraint)\n\t}\n\n\tv, err := semver.NewVersion(clientVersion)\n\tif err != nil {\n\t\treturn false, errors.Wrapf(err, \"supplied client version %q cannot be parsed as semver\", clientVersion)\n\t}\n\n\treturn c.Check(v), nil\n}", "func VersionAPI(path string, version Version) (API, error) {\n\treturn nil, fmt.Errorf(\"not implemented\")\n}", "func (v Version) Valid() bool {\n\treturn Version1 <= v && v <= Version4\n}", "func isBeforeV1(version string) bool {\r\n\treturn semver.IsValid(version) && semver.Compare(version, \"v1.0.0\") < 0\r\n}", "func checkVersion() bool {\n\tif len(os.Args) < 2 {\n\t\treturn false\n\t}\n\targ := os.Args[1]\n\tfor _, name := range cli.VersionFlag.Names() {\n\t\tif arg == \"-\"+name || arg == \"--\"+name {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func checkVersion(cReg registry.ClusterRegistry) (string, bool) {\n\tfv := version.SemVersion\n\tlv, err := cReg.LatestDaemonVersion()\n\tif err != nil {\n\t\tlog.Errorf(\"error attempting to check latest fleet version in Registry: %v\", err)\n\t} else if lv != nil && fv.LessThan(*lv) {\n\t\treturn fmt.Sprintf(oldVersionWarning, fv.String(), lv.String()), false\n\t}\n\treturn \"\", true\n}", "func isValidModelVersion(model string, version string, dmsaUrl string) (isValid bool, err error) {\n\tif cachedIsValidVersion != nil {\n\t\tisValid = *cachedIsValidVersion\n\t\treturn\n\t}\n\n\tparts := strings.Split(version, \".\")\n\tif len(parts) != 3 {\n\t\terr = fmt.Errorf(\"Model version must look like X.Y.Z, not '%s'\", version)\n\t\treturn\n\t}\n\n\t// First, test the DMSA service URL itself\n\tvar response *http.Response\n\tresponse, err = http.Get(dmsaUrl)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Cannot access data-models-sqlalchemy web service at %s: %v\", dmsaUrl, err)\n\t\treturn\n\t}\n\tif response.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Data-models-sqlalchemy web service (%s) returned error response: %v\", dmsaUrl, http.StatusText(response.StatusCode))\n\t\treturn\n\t}\n\n\t// Now check the requested version\n\turl := joinUrlPath(dmsaUrl, fmt.Sprintf(\"/%s/%s/ddl/postgresql/tables/\", model, version))\n\tresponse, err = http.Get(url)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Cannot access data-models-sqlalchemy web service at %v: %v\", url, err)\n\t\treturn\n\t}\n\tif response.StatusCode != 200 {\n\t\treturn // Normal \"not valid\" return: isValid will be false and err will be nil\n\t}\n\t// Normal \"valid\" return\n\tcachedIsValidVersion = new(bool)\n\t*cachedIsValidVersion = true\n\tisValid = *cachedIsValidVersion\n\treturn\n}", "func getValidVersion(version string) string {\n\tif version != \"\" {\n\t\treturn version\n\t}\n\n\treturn \"Not Installed\"\n}", "func isPseudoVersion(v string) bool {\n\treturn strings.Count(v, \"-\") >= 2 && semver.IsValid(v) && pseudoVersionRE.MatchString(v)\n}", "func IsValidUpgrade(previous, latest *semver.Version) bool {\n\tswitch {\n\tcase previous == nil || latest == nil:\n\t\treturn true\n\tcase previous.Major() > latest.Major():\n\t\treturn true\n\tcase previous.Major() == latest.Major():\n\t\treturn previous.Minor() >= latest.Minor() ||\n\t\t\tprevious.Minor() == latest.Minor()-1\n\tcase previous.Major() == latest.Major()-1:\n\t\treturn latest.Minor() == 0\n\tdefault:\n\t\treturn false\n\t}\n}", "func (a *DefaultApiService) VersionCheck(ctx _context.Context) (ServiceVersion, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ServiceVersion\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/version\"\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{}\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\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 *ApplianceImageBundleAllOf) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func isV1(version string) bool {\r\n\tif !semver.IsValid(version) || isBeforeV1(version) {\r\n\t\treturn false\r\n\t}\r\n\treturn semver.Major(version) == \"v1\"\r\n}", "func ExcludedVersion(verbose bool) (bool, error) {\r\n\treport := func(err error) error { return fmt.Errorf(\"excludedversion: %v\", err) }\r\n\r\n\t// track our versions in { path: version } map.\r\n\tversions := make(map[string]string)\r\n\tmods, err := buildlist.Resolve()\r\n\tif err != nil {\r\n\t\treturn false, report(err)\r\n\t}\r\n\t// build up our reference map\r\n\tfor _, mod := range mods {\r\n\t\tif verbose {\r\n\t\t\tfmt.Printf(\"gomodvet: excludedversion: module %s: %+v\\n\", mod.Path, mod)\r\n\t\t}\r\n\t\tversions[mod.Path] = mod.Version\r\n\t}\r\n\r\n\t// do our check by parsing each 'go.mod' file being used,\r\n\t// and check if we are using a path/version combination excluded\r\n\t// by one of a go.mod file in our dependecies\r\n\tflagged := false\r\n\tfor _, mod := range mods {\r\n\t\tif mod.Main {\r\n\t\t\t// here we assume the main module's 'go.mod' is in a consistent state,\r\n\t\t\t// and not using something excluded in its own 'go.mod' file. The 'go' tool\r\n\t\t\t// enforces this on a 'go build', 'go mod tidy', etc.\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\tfile, err := modfile.Parse(mod.GoMod)\r\n\t\tif err != nil {\r\n\t\t\treturn false, report(err)\r\n\t\t}\r\n\t\tfor _, exclude := range file.Exclude {\r\n\t\t\tusingVersion, ok := versions[exclude.Path]\r\n\t\t\tif !ok {\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\t\t\tif usingVersion == exclude.Version {\r\n\t\t\t\tfmt.Printf(\"gomodvet-005: a module is using a version excluded by another module. excluded version: %s %s\\n\",\r\n\t\t\t\t\texclude.Path, exclude.Version)\r\n\t\t\t\tflagged = true\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn flagged, nil\r\n}", "func (o *Ga4ghExternalIdentifier) GetVersionOk() (string, bool) {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.Version, true\n}", "func TestUnitAcceptableVersion(t *testing.T) {\n\tinvalidVersions := []string{\n\t\t// ascii gibberish\n\t\t\"foobar\",\n\t\t\"foobar.0\",\n\t\t\"foobar.9\",\n\t\t\"0.foobar\",\n\t\t\"9.foobar\",\n\t\t\"foobar.0.0\",\n\t\t\"foobar.9.9\",\n\t\t\"0.foobar.0\",\n\t\t\"9.foobar.9\",\n\t\t\"0.0.foobar\",\n\t\t\"9.9.foobar\",\n\t\t// utf-8 gibberish\n\t\t\"世界\",\n\t\t\"世界.0\",\n\t\t\"世界.9\",\n\t\t\"0.世界\",\n\t\t\"9.世界\",\n\t\t\"世界.0.0\",\n\t\t\"世界.9.9\",\n\t\t\"0.世界.0\",\n\t\t\"9.世界.9\",\n\t\t\"0.0.世界\",\n\t\t\"9.9.世界\",\n\t\t// missing numbers\n\t\t\".\",\n\t\t\"..\",\n\t\t\"...\",\n\t\t\"0.\",\n\t\t\".1\",\n\t\t\"2..\",\n\t\t\".3.\",\n\t\t\"..4\",\n\t\t\"5.6.\",\n\t\t\".7.8\",\n\t\t\".9.0.\",\n\t}\n\tfor _, v := range invalidVersions {\n\t\terr := acceptableVersion(v)\n\t\tif _, ok := err.(invalidVersionError); err == nil || !ok {\n\t\t\tt.Errorf(\"acceptableVersion returned %q for version %q, but expected invalidVersionError\", err, v)\n\t\t}\n\t}\n\tinsufficientVersions := []string{\n\t\t// random small versions\n\t\t\"0\",\n\t\t\"00\",\n\t\t\"0000000000\",\n\t\t\"0.0\",\n\t\t\"0000000000.0\",\n\t\t\"0.0000000000\",\n\t\t\"0.0.0.0.0.0.0.0\",\n\t\t/*\n\t\t\t\"0.0.9\",\n\t\t\t\"0.0.999\",\n\t\t\t\"0.0.99999999999\",\n\t\t\t\"0.1.2\",\n\t\t\t\"0.1.2.3.4.5.6.7.8.9\",\n\t\t\t// pre-hardfork versions\n\t\t\t\"0.3.3\",\n\t\t\t\"0.3.9.9.9.9.9.9.9.9.9.9\",\n\t\t\t\"0.3.9999999999\",\n\t\t\t\"1.3.0\",\n\t\t*/\n\t}\n\tfor _, v := range insufficientVersions {\n\t\terr := acceptableVersion(v)\n\t\tif _, ok := err.(insufficientVersionError); err == nil || !ok {\n\t\t\tt.Errorf(\"acceptableVersion returned %q for version %q, but expected insufficientVersionError\", err, v)\n\t\t}\n\t}\n\tvalidVersions := []string{\n\t\tminimumAcceptablePeerVersion,\n\t\t\"1.3.7\",\n\t\t\"1.4.0\",\n\t\t\"1.6.0\",\n\t\t\"1.6.1\",\n\t\t\"1.9\",\n\t\t\"1.999\",\n\t\t\"1.9999999999\",\n\t\t\"2\",\n\t\t\"2.0\",\n\t\t\"2.0.0\",\n\t\t\"9\",\n\t\t\"9.0\",\n\t\t\"9.0.0\",\n\t\t\"9.9.9\",\n\t}\n\tfor _, v := range validVersions {\n\t\terr := acceptableVersion(v)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"acceptableVersion returned %q for version %q, but expected nil\", err, v)\n\t\t}\n\t}\n}", "func (o *Version) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *ApplianceImageBundleAllOf) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func validateSignatureVersion(signature nbv1.S3SignatureVersion, nsStoreName string) error {\n\tif signature != \"\" &&\n\t\tsignature != nbv1.S3SignatureVersionV2 &&\n\t\tsignature != nbv1.S3SignatureVersionV4 {\n\t\treturn util.NewPersistentError(\"InvalidSignatureVersion\",\n\t\t\tfmt.Sprintf(\"Invalid s3 signature version %q for namespace store %q\",\n\t\t\t\tsignature, nsStoreName))\n\t}\n\treturn nil\n}", "func (o *EquipmentIoCardBase) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *EquipmentIoCardBase) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func TestVersion(t *testing.T) {\n\tvers := Version()\n\tif len(vers) == 0 {\n\t\tt.Error(\"version string is not present\")\n\t}\n}", "func (version *Version) CheckExists() (bool, error)", "func (o *SoftwareTechs) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (p ProtocolVersion) Valid() bool {\n\treturn p <= ProtocolVersion(experimentalRPCProtocolVersion)\n}", "func InRange(format, version, versionRange string) (bool, error) {\n\tversionParser, exists := GetParser(format)\n\tif !exists {\n\t\treturn false, ErrUnknownVersionFormat\n\t}\n\n\tin, err := versionParser.InRange(version, versionRange)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"Format\": format, \"Version\": version, \"Range\": versionRange}).Error(err)\n\t}\n\treturn in, err\n}", "func (o *VirtualizationIweHost) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (in *InitIn) SupportsVersion(maj, min uint32) bool {\n\treturn in.Major > maj || (in.Major == maj && in.Minor >= min)\n}", "func (o *WebhooksJsonWebhook) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (s *SwaggerSchema) delegateIfDifferentApiVersion(obj *unstructured.Unstructured) (bool, []error) {\n\t// Never delegate objects in the same ApiVersion or we will get infinite recursion\n\tif !s.isDifferentApiVersion(obj) {\n\t\treturn false, nil\n\t}\n\n\t// Delegate validation of this object to the correct SwaggerSchema for its ApiGroup\n\tnewSchema, err := NewSwaggerSchemaFor(s.delegate, obj.GroupVersionKind().GroupVersion())\n\tif err != nil {\n\t\treturn true, []error{err}\n\t}\n\treturn true, newSchema.Validate(obj)\n}", "func (hrsi *SubscriberItem) checkVersion(chartVersion *repo.ChartVersion) bool {\n\tif hrsi.Subscription != nil {\n\t\tif hrsi.Subscription.Spec.PackageFilter != nil {\n\t\t\tif hrsi.Subscription.Spec.PackageFilter.Version != \"\" {\n\t\t\t\tversion := chartVersion.GetVersion()\n\t\t\t\tversionVersion, err := semver.Parse(version)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.V(3).Info(\"Skipping error in parsing version, taking it as not match. The error is:\", err)\n\t\t\t\t\treturn false\n\t\t\t\t}\n\n\t\t\t\tfilterVersion, err := semver.ParseRange(hrsi.Subscription.Spec.PackageFilter.Version)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Error(err)\n\t\t\t\t\treturn false\n\t\t\t\t}\n\n\t\t\t\treturn filterVersion(versionVersion)\n\t\t\t}\n\t\t}\n\t}\n\n\tklog.V(5).Info(\"Version check passed for:\", chartVersion)\n\n\treturn true\n}", "func CheckBpfVersion(fd int) error {\n\tvar v BpfVersion\n\terr := ioctlPtr(fd, BIOCVERSION, unsafe.Pointer(&v))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif v.Major != BPF_MAJOR_VERSION || v.Minor != BPF_MINOR_VERSION {\n\t\treturn EINVAL\n\t}\n\treturn nil\n}", "func (v Versioning) Validate() error {\n\t// Not supported yet\n\t// switch v.MFADelete {\n\t// case Enabled, Disabled:\n\t// default:\n\t// \treturn Errorf(\"unsupported MFADelete state %s\", v.MFADelete)\n\t// }\n\tswitch v.Status {\n\tcase Enabled, Suspended:\n\tdefault:\n\t\treturn Errorf(\"unsupported Versioning status %s\", v.Status)\n\t}\n\treturn nil\n}", "func newVersionAvailable(currentVersion string) (bool, *string, error) {\n\tgardenctlLatestURL := \"https://api.github.com/repos/gardener/gardenctl/releases/latest\"\n\tresp, err := http.Get(gardenctlLatestURL)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\n\tdata := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(body), &data); err != nil {\n\t\treturn false, nil, err\n\t}\n\tvar latestVersion string\n\tif data[\"tag_name\"] != nil {\n\t\tlatestVersion = data[\"tag_name\"].(string)\n\t}\n\n\tc, err := semver.NewConstraint(\"> \" + currentVersion)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\n\tlatest, err := semver.NewVersion(latestVersion)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\n\treturn c.Check(latest), &latestVersion, nil\n}", "func (o *APICheck) Version() int {\n\n\treturn 1\n}", "func (o *ConnectorTypeAllOf) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *ConnectorTypeAllOf) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (e Err) Version(v Version) Err {\n\tif v > Latest {\n\t\tv = Latest\n\t}\n\ti := int((int(v) * MaxErr) | int(e))\n\treturn ErrVer[i]\n}", "func (o *DeviceResourceVersionValueWeb) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (c *Cases) Version(v string) bool {\n\tfor _, r := range build.Default.ReleaseTags {\n\t\tif v == r {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v HugoVersion) IsValid() bool {\n\tcurrent := hugo.CurrentVersion.Version()\n\tif v.Extended && !hugo.IsExtended {\n\t\treturn false\n\t}\n\n\tisValid := true\n\n\tif v.Min != \"\" && current.Compare(v.Min) > 0 {\n\t\tisValid = false\n\t}\n\n\tif v.Max != \"\" && current.Compare(v.Max) < 0 {\n\t\tisValid = false\n\t}\n\n\treturn isValid\n}", "func (o *NiaapiNewReleaseDetailAllOf) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (c *client) checkVersion() error {\n\tbinaryVersionOutput, err := c.runCmd(\"version\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\texp, _ := regexp.Compile(fmt.Sprintf(`%s version v([^\\s-]+)`, binaryName))\n\tbinaryVersion := exp.FindStringSubmatch(binaryVersionOutput)\n\tif c.verbose {\n\t\tfmt.Printf(\"Extracted %s version: '%s'\", binaryName, binaryVersion[1])\n\t}\n\tif len(binaryVersion) < 2 {\n\t\treturn fmt.Errorf(\"Could not extract %s version from command output:\\n%s\", binaryName, binaryVersionOutput)\n\t}\n\tbinarySemVersion, err := semver.Parse(binaryVersion[1])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tminRequiredSemVersion, _ := semver.Parse(minRequiredVersion)\n\tif binarySemVersion.Major > minRequiredSemVersion.Major {\n\t\tincompatibleMajorVersionMsg := \"You are using an unsupported k3d major version '%d'. The supported k3d major version for this command is '%d'.\"\n\t\treturn fmt.Errorf(incompatibleMajorVersionMsg, binarySemVersion.Major, minRequiredSemVersion.Major)\n\t} else if binarySemVersion.LT(minRequiredSemVersion) {\n\t\tincompatibleVersionMsg := \"You are using an unsupported k3d version '%s'. The supported k3d version for this command is >= '%s'.\"\n\t\treturn fmt.Errorf(incompatibleVersionMsg, binaryVersion, minRequiredSemVersion)\n\t}\n\n\treturn nil\n}", "func (v *ProtocolVersion) BelowVersion(other *ProtocolVersion) bool {\n\treturn v.Below(other.Major, other.Minor)\n}", "func CheckCompatible(versionSpec string) error {\n\tr, err := semver.ParseRange(versionSpec)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif r(parsedVersion) {\n\t\treturn nil\n\t}\n\treturn incompatibleVersion{\n\t\texpected: versionSpec,\n\t\tcurrent: Version,\n\t}\n}", "func (e NotFound) IsNotFound() {}", "func checkIsNewVersion(hConstraints version.Constraints, serverVersion *version.Version) (bool, bool) {\n\tisNewerVersion := false\n\tallConstraintsValid := true\n\tfor _, constraint := range hConstraints {\n\t\tvalidConstraint := constraint.Check(serverVersion)\n\t\tif !validConstraint {\n\t\t\tallConstraintsValid = false\n\t\t\tconstraintVersionString := getConstraintVersion(constraint.String())\n\n\t\t\tconstraintVersion, err := version.NewVersion(constraintVersionString)\n\t\t\tif err != nil {\n\t\t\t\treturn false, false\n\t\t\t}\n\t\t\tif serverVersion.GreaterThan(constraintVersion) {\n\t\t\t\tisNewerVersion = true\n\t\t\t} else {\n\t\t\t\treturn false, false\n\t\t\t}\n\t\t}\n\t}\n\treturn isNewerVersion, allConstraintsValid\n}", "func checkCompatibleVersion(\n\tcfg config.SQL,\n\texpectedVersion string,\n) error {\n\n\tconnection, err := newConn(&sqlConnectParams{\n\t\thost: cfg.ConnectAddr,\n\t\tuser: cfg.User,\n\t\tpassword: cfg.Password,\n\t\tdriverName: cfg.DriverName,\n\t\tdatabase: cfg.DatabaseName,\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to create SQL connection: %v\", err.Error())\n\t}\n\tdefer connection.Close()\n\n\treturn schema.VerifyCompatibleVersion(connection, cfg.DatabaseName, expectedVersion)\n}", "func (o *InterfaceCapability) GetVersionOk() (*int32, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (f *FlowState) HasValidVersion() bool {\n\treturn f != nil && f.Kind == FlowStateKind && f.APIVersion == SchemeGroupVersion.String()\n}", "func IsRegularVersion(s string) bool {\n\treturn regexpRegularVersion.MatchString(s)\n}", "func (o *Ga4ghExternalIdentifier) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *DeviceResourceVersionValueWeb) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func IsUnstableBuild() bool {\n\treturn isUnstableBuild.Get(func() bool {\n\t\t_, rest, ok := strings.Cut(Short(), \".\")\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\tminorStr, _, ok := strings.Cut(rest, \".\")\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\tminor, err := strconv.Atoi(minorStr)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn minor%2 == 1\n\t})\n}", "func (p *UserStoreClient) CheckVersion(ctx context.Context, clientName string, edamVersionMajor int16, edamVersionMinor int16) (r bool, err error) {\n var _args1 UserStoreCheckVersionArgs\n _args1.ClientName = clientName\n _args1.EdamVersionMajor = edamVersionMajor\n _args1.EdamVersionMinor = edamVersionMinor\n var _result2 UserStoreCheckVersionResult\n if err = p.Client_().Call(ctx, \"checkVersion\", &_args1, &_result2); err != nil {\n return\n }\n return _result2.GetSuccess(), nil\n}", "func (ver *Version) IsCompatible(otherVer *Version) bool {\n if ver.Major != otherVer.Major {\n return false\n }\n\n /* same major version. Check minor */\n if ver.Minor < 0 && otherVer.Minor >= 0 {\n return true\n }\n\n if ver.Minor >= 0 && otherVer.Minor < 0 {\n return true\n }\n\n /* both < 0, or both > 0 */\n if ver.Minor != otherVer.Minor {\n return false\n }\n\n /* same minor version. Check patch */\n if ver.Patch < 0 && otherVer.Patch >= 0 {\n return true\n }\n if ver.Patch >= 0 && otherVer.Patch < 0 {\n return true\n }\n return ver.Patch == otherVer.Patch\n}", "func (o *WebhooksJsonWebhook) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (v *ProtocolVersion) AboveVersion(other *ProtocolVersion) bool {\n\treturn v.Above(other.Major, other.Minor)\n}", "func (c Initializer) verifyServedVersion(client crdclient.CustomResourceDefinitionsGetter, crdName, version string, result *verifier.Result) error {\n\texistingCrd, err := c.getCrdForVerify(client, crdName, result)\n\tif err != nil || existingCrd == nil {\n\t\treturn err\n\t}\n\tif healthy, msg, err := status.IsHealthy(existingCrd); !healthy || err != nil {\n\t\tif !healthy {\n\t\t\tresult.AddErrors(msg)\n\t\t} else {\n\t\t\tresult.AddErrors(err.Error())\n\t\t}\n\t\treturn nil\n\t}\n\n\tvar expectedVersion *apiextv1.CustomResourceDefinitionVersion\n\tvar allNames = []string{}\n\tfor _, v := range existingCrd.Spec.Versions {\n\t\tv := v\n\t\tallNames = append(allNames, v.Name)\n\t\tif v.Name == version {\n\t\t\texpectedVersion = &v\n\t\t\tbreak\n\t\t}\n\t}\n\tif expectedVersion == nil {\n\t\tresult.AddErrors(fmt.Sprintf(\"Expected API version %s was not found for %s, api-server only supports %v. Please update your KUDO CLI.\", version, crdName, allNames))\n\t\treturn nil\n\t}\n\tif !expectedVersion.Served {\n\t\tresult.AddErrors(fmt.Sprintf(\"Expected API version %s for %s is known to api-server, but is not served. Please update your KUDO CLI.\", version, crdName))\n\t}\n\treturn nil\n}", "func runtimeLiblxcVersionAtLeast(major int, minor int, micro int) bool {\n\tversion := Version()\n\tversion = strings.Replace(version, \" (devel)\", \"-devel\", 1)\n\tparts := strings.Split(version, \".\")\n\tpartsLen := len(parts)\n\tif partsLen == 0 {\n\t\treturn false\n\t}\n\n\tdevelParts := strings.Split(parts[partsLen-1], \"-\")\n\tif len(develParts) == 2 && develParts[1] == \"devel\" {\n\t\treturn true\n\t}\n\n\tmaj := -1\n\tmin := -1\n\tmic := -1\n\n\tfor i, v := range parts {\n\t\tif i > 2 {\n\t\t\tbreak\n\t\t}\n\n\t\tnum, err := strconv.Atoi(v)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\n\t\tswitch i {\n\t\tcase 0:\n\t\t\tmaj = num\n\t\tcase 1:\n\t\t\tmin = num\n\t\tcase 2:\n\t\t\tmic = num\n\t\t}\n\t}\n\n\t/* Major version is greater. */\n\tif maj > major {\n\t\treturn true\n\t}\n\n\tif maj < major {\n\t\treturn false\n\t}\n\n\t/* Minor number is greater.*/\n\tif min > minor {\n\t\treturn true\n\t}\n\n\tif min < minor {\n\t\treturn false\n\t}\n\n\t/* Patch number is greater. */\n\tif mic > micro {\n\t\treturn true\n\t}\n\n\tif mic < micro {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (e *ErrInvalidPipelineManifestVersion) Is(target error) bool {\n\tt, ok := target.(*ErrInvalidPipelineManifestVersion)\n\treturn ok && t.invalidVersion == e.invalidVersion\n}", "func (o *WorkflowServiceItemDefinitionAllOf) GetVersionOk() (*int64, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (r *Responder) HTTPVersionNotSupported() { r.write(http.StatusHTTPVersionNotSupported) }" ]
[ "0.7800074", "0.7698673", "0.61183864", "0.5984667", "0.59743524", "0.5790841", "0.57839173", "0.57596445", "0.5734349", "0.5708786", "0.5705013", "0.5690198", "0.5686768", "0.5666567", "0.56633246", "0.5652546", "0.5641665", "0.55701846", "0.55573326", "0.55366045", "0.55338675", "0.55010974", "0.5472257", "0.5444862", "0.54431033", "0.54205847", "0.5411629", "0.5407247", "0.54048073", "0.5361432", "0.53080755", "0.53056324", "0.5294428", "0.5273072", "0.52648705", "0.5250967", "0.5250884", "0.52497315", "0.5237944", "0.5215414", "0.5199277", "0.51897514", "0.5185471", "0.5170912", "0.516327", "0.5155037", "0.51489204", "0.5140873", "0.51027185", "0.51019555", "0.5097726", "0.50963026", "0.5091819", "0.50904155", "0.50812453", "0.5073672", "0.5058754", "0.50384146", "0.50100636", "0.500756", "0.50046736", "0.4997293", "0.499529", "0.49938214", "0.49558565", "0.49548918", "0.49529895", "0.49408796", "0.49408174", "0.49406204", "0.49389124", "0.49344355", "0.49329475", "0.492757", "0.492757", "0.4923424", "0.49084437", "0.49035946", "0.49005857", "0.4898885", "0.48961556", "0.48896593", "0.48870122", "0.48830557", "0.4875069", "0.4872744", "0.48608407", "0.4855761", "0.4855293", "0.4852238", "0.4852108", "0.48515922", "0.48509756", "0.4842518", "0.4842289", "0.484146", "0.4836752", "0.48357368", "0.48336223", "0.48314857", "0.48306993" ]
0.0
-1
NewUsecase is constructor for create default implementation of usecase ShowPostBySlug
func NewUsecase(outputPort Outport) Inport { return &showPostBySlugInteractor{ outport: outputPort, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New(ctx *sweetygo.Context) error {\n\ttitle := ctx.Param(\"title\")\n\tcat := ctx.Param(\"cat\")\n\thtml := ctx.Param(\"html\")\n\tmd := ctx.Param(\"md\")\n\tif title != \"\" && cat != \"\" && html != \"\" && md != \"\" {\n\t\terr := model.NewPost(title, cat, html, md)\n\t\tif err != nil {\n\t\t\treturn ctx.JSON(500, 0, \"create post error\", nil)\n\t\t}\n\t\treturn ctx.JSON(201, 1, \"success\", nil)\n\t}\n\treturn ctx.JSON(406, 0, \"I can't understand what u want\", nil)\n}", "func (u *App) Create(c echo.Context, req *Create) (*model.Post, error) {\n\tid, err := util.GenerateUUID()\n\tif err = zaplog.ZLog(err); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar operator model.User\n\tif err = u.db.Model(&model.User{}).Where(\"uuid = ?\", req.Author).First(&operator).Error; err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar dupe model.Post\n\tif err = u.db.Model(&model.Post{}).Where(\"slug = ?\", req.Slug).Order(\"id DESC\").First(&dupe).Error; err == nil {\n\t\tfragment := strings.TrimPrefix(dupe.Slug, req.Slug)\n\t\tif fragment == \"\" {\n\t\t\treq.Slug += \"-2\"\n\t\t}\n\n\t\tcounter, err := strconv.Atoi(strings.TrimPrefix(fragment, \"-\"))\n\t\tif err != nil {\n\t\t\treq.Slug += \"-2\"\n\t\t} else {\n\t\t\treq.Slug += fmt.Sprintf(\"-%d\", counter+1)\n\t\t}\n\t}\n\n\tif len(req.Excerpt) > 255 {\n\t\treq.Excerpt = req.Excerpt[:250] + \"...\"\n\t}\n\n\tpost := model.Post{\n\t\tBase: model.Base{ID: id},\n\t\tAuthor: req.Author,\n\t\tAuthorName: operator.Name,\n\t\tCategory: req.Category,\n\t\tTags: req.Tags,\n\t\tTitle: req.Title,\n\t\tSlug: req.Slug,\n\t\tContent: req.Content,\n\t\tExcerpt: req.Excerpt,\n\t\tStatus: req.Status,\n\t}\n\treturn u.udb.Create(u.db, post)\n}", "func newPost(body string, timestamp int64, next *post) *post {\n\treturn &post{body, timestamp, next}\n}", "func New(s shorter.Store, c interface{}) (shorter.Shorter, error) {\n\t// load extends configuration\n\t// TODO: implement\n\treturn nil, errors.New(\"unimplemented\")\n}", "func New(fn string) (*Post, error) {\n\tb, err := ioutil.ReadFile(fn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//Check if document start with valid token\n\tif !bytes.HasPrefix(b, []byte(\"---\\n\")) {\n\t\treturn nil, errMissingFrontMatter\n\t}\n\tb = bytes.TrimPrefix(b, []byte(\"---\\n\"))\n\n\t//Split b to array, array[0] is front matter\n\t//array[1] is the rest of text (post's body)\n\tarr := bytes.SplitN(b, []byte(\"\\n---\\n\"), 2)\n\n\t//Generate meta from text\n\tm, err := newMeta(string(arr[0]))\n\n\t//Convert the rest of text to Markdown\n\tbody := blackfriday.MarkdownCommon(arr[1])\n\tp := &Post{\n\t\tm,\n\t\tslug.Make(m.Title),\n\t\ttemplate.HTML(body),\n\t}\n\treturn p, nil\n}", "func (a App) NewPost(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\n\ttmpl := buildView(\"new_post\")\n\n\tpd := PageData{\n\t\tPageTitle: \"New Post\",\n\t\tPost: Post{},\n\t}\n\n\terr := tmpl.ExecuteTemplate(res, \"layout\", pd)\n\n\tif err != nil {\n\t\thttp.Error(res, err.Error(), http.StatusInternalServerError)\n\t}\n}", "func NewPost(author, vehicle, title, excerpt, body string) *Post {\n\treturn &Post{\n\t\tID: PostID(utils.NewPostID()),\n\t\tAuthor: author,\n\t\tVehicle: vehicle,\n\t\tTitle: title,\n\t\tExcerpt: excerpt,\n\t\tBody: body,\n\t}\n}", "func NewMockPostUsecase(ctrl *gomock.Controller) *MockPostUsecase {\n\tmock := &MockPostUsecase{ctrl: ctrl}\n\tmock.recorder = &MockPostUsecaseMockRecorder{mock}\n\treturn mock\n}", "func (s *SpotifyExtender) New() {\r\n\r\n}", "func NewShow(t *testing.T, s *shows.Show) *shows.Show {\n\tif err := s.Save(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tlifecycle.SaveModels(t, s)\n\treturn s\n}", "func NewPost() *Post {\n\treturn &Post{\n\t\tId: bson.NewObjectId(),\n\t\tCreatedAt: utils.Now(),\n\t}\n}", "func NewPost(username string, imageURL string, thumbnailURL string, caption string, url string, messageBody string, mood MoodState, keywords []string, likers []string) *Post {\n\n\tauditableContent := AuditableContent{createdBy: username, createdTime: time.Now()}\n\n\treturn &Post{\n\t\tauditableContent: auditableContent,\n\t\tcaption: caption,\n\t\turl: url,\n\t\timageURL: imageURL,\n\t\tthumbnailURL: thumbnailURL,\n\t\tmessageBody: messageBody,\n\t\tauthorMood: mood,\n\t\tkeywords: keywords,\n\t\tlikers: likers,\n\t}\n}", "func newPost(fullPath string) (*Post, error) {\n\tf, err := os.Open(fullPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer f.Close()\n\n\t// Load the HTML document\n\tdom, err := goquery.NewDocumentFromReader(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp := &Post{\n\t\tDOM: dom,\n\t\tHTMLFileName: filepath.Base(f.Name()),\n\t\tImages: make([]*Image, 0),\n\t\tTags: make([]string, 0),\n\t\tLastmod: time.Now().Format(time.RFC3339),\n\t}\n\n\t// draft is prefixed in filename\n\tp.Draft = strings.HasPrefix(p.HTMLFileName, DraftPrefix)\n\n\treturn p, nil\n}", "func NewPost(w http.ResponseWriter, r *http.Request, u *models.User) {\n\tswitch r.Method {\n\tcase \"POST\":\n\t\terr := savePost(0, r.FormValue, u)\n\t\tif err != nil {\n\t\t\ttpl.ExecuteTemplate(w, \"404\", nil)\n\t\t\treturn\n\t\t}\n\n\t\thttp.Redirect(w, r, \"/manage\", http.StatusFound)\n\n\tcase \"GET\":\n\t\ttpl.ExecuteTemplate(w, \"editPost\", nil)\n\t}\n}", "func NewUseCase(filepath string) (uc *UseCase, err error) {\n\tvar data []byte\n\n\tif data, err = ioutil.ReadFile(filepath); err != nil {\n\t\treturn\n\t}\n\tvar m map[string]interface{}\n\tvar p sen.Parser\n\tvar v interface{}\n\tif v, err = p.Parse(data); err != nil {\n\t\treturn\n\t}\n\tif m, _ = v.(map[string]interface{}); m == nil {\n\t\treturn nil, fmt.Errorf(\"expected a map, not a %T\", v)\n\t}\n\tuc = &UseCase{Filepath: filepath}\n\tif uc.Comment, err = asString(m[\"comment\"]); err != nil {\n\t\treturn\n\t}\n\tif err = uc.addSteps(m[\"steps\"]); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func NewPostFunc(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != http.MethodPost {\n\t\ttools.ExecuteError(w, http.StatusMethodNotAllowed, \"Method not allowed\")\n\t\treturn\n\t}\n\tauthorID := r.FormValue(\"authorID\")\n\tauthor := r.FormValue(\"postAuthor\")\n\tthreadsID := r.Form[\"category\"] // returns slice of threadsID\n\tif count := tools.ThreadsCount(threadsID); count < 1 {\n\t\t// TODO Send message to user\n\t\thttp.Redirect(w, r, \"/addpost\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tpostTitle := r.FormValue(\"postTitle\")\n\tpostContent := r.FormValue(\"postContent\")\n\tif tools.IsEmpty(postTitle) || tools.IsEmpty(postContent) {\n\t\t// TODO Send message to user\n\t\thttp.Redirect(w, r, \"/addpost\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tpostsmanager.AddPost(threadsID, postTitle, postContent, author, authorID)\n\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\tlog.Printf(\"NewPostFunc (postshandler.go) author is %s, it's id is %s, threads are %v, postTitle is %s, content is %s\", author, authorID, threadsID, postTitle, postContent)\n}", "func NewUsecase(logger *logrus.Logger) *Usecase {\n\treturn &Usecase{Logger: logger}\n}", "func NewPost(username string, mood MoodState, caption string, MessageBody string, url string, imageURL string, thumbnailURI string, keywords []string) *Post {\n\n\tauditableContent := AuditableContent{CreatedBy: username, TimeCreated: time.Now()}\n\treturn &Post{Caption: caption, MessageBody: MessageBody, URL: url, ImageURI: imageURL, ThumbnailURI: thumbnailURI, AuthorMood: mood, Keywords: keywords, AuditableContent: auditableContent}\n}", "func NewPost(username string, mood MoodState, caption string, messageBody string, url string, imageURI string, thumbnailURI string, keywords []string) *Post {\n\tauditableContent := AuditableContent{CreatedBy: username, TimeCreated: time.Now()}\n\treturn &Post{Caption: caption, MessageBody: messageBody, URL: url, ImageURI: imageURI, ThumbnailURI: thumbnailURI, AuthorMood: mood, Keywords: keywords, AuditableContent: auditableContent}\n}", "func New(config Configuration) *Slugifier {\n\tif config.IsValidCharacterChecker == nil {\n\t\tconfig.IsValidCharacterChecker = validCharacter\n\t}\n\n\tif config.ReplaceCharacter == 0 {\n\t\tconfig.ReplaceCharacter = '-'\n\t}\n\n\treturn &Slugifier{isValidCharacter: config.IsValidCharacterChecker, replaceCharacter: config.ReplaceCharacter}\n}", "func (s WashingtonPostScraper) CreateNewWashingtonPostScraper() *WashingtonPostScraper {\n\tc := colly.NewCollector()\n\t// c := colly.NewCollector(colly.Debugger(&debug.LogDebugger{}))\n\tc.UserAgent = s.UserAgent()\n\tc.IgnoreRobotsTxt = false\n\n\t// Adding this wait so AJAX can load, might need to look at https://github.com/chromedp/chromedp in the future\n\tc.Limit(&colly.LimitRule{\n\t\tDelay: 5 * time.Second,\n\t})\n\n\tscraper := WashingtonPostScraper{\n\t\tcollector: c,\n\t}\n\treturn &scraper\n}", "func NewUseCase(repo Repository) UseCase {\n\treturn &useCase{\n\t\tRepo: repo,\n\t}\n}", "func (s *ShortURLService) CreateShortURL(meta *ShortURLMeta) (*models.ShortURL, error) {\n\n\t// TODO Fix issue:\n\t// The model creation is updating the Tag Model even for tags that exist... eventually should be fixed\n\t// FindIfExists not implemented\n\n\tvar shortURL models.ShortURL\n\n\tif meta.ValidSince != \"\" {\n\t\tvalidSince, err := utils.ParseDateString(meta.ValidSince)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tshortURL.ValidSince = validSince\n\t} else {\n\t\tnow := time.Now()\n\t\tshortURL.ValidSince = &now\n\t}\n\n\tif meta.ValidUntil != \"\" {\n\t\tvalidUntil, err := utils.ParseDateString(meta.ValidUntil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tshortURL.ValidUntil = validUntil\n\t}\n\n\t// if domain is not set, use default\n\tif meta.Domain == \"\" {\n\t\tmeta.Domain = s.Config.ShortDomainHost\n\t\ts.SetDomain(&shortURL, s.Config.ShortDomainHost)\n\t} else {\n\t\ts.SetDomain(&shortURL, meta.Domain)\n\t}\n\n\t// check original url?\n\tshortURL.OriginalURL = meta.LongURL\n\n\t// generate short code with length or use slug\n\tif meta.CustomSlug != \"\" {\n\t\tshortURL.ShortCode = meta.CustomSlug\n\t} else {\n\t\tshortCode, err := utils.MakeSlug(int(meta.ShortCodeLength))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tshortURL.ShortCode = shortCode\n\t}\n\n\t// max visits\n\tshortURL.MaxVisits = meta.MaxVisits\n\n\t// tags\n\terr := s.AssignTags(&shortURL, meta.Tags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.DB.Create(&shortURL)\n\treturn &shortURL, nil //edit\n}", "func (v HashtagsResource) New(c buffalo.Context) error {\n\t// Make hashtag available inside the html template\n\tc.Set(\"hashtag\", &models.Hashtag{})\n\treturn c.Render(200, r.HTML(\"hashtags/new.html\"))\n}", "func NewUseCase(repo domain.Repository) *UseCase {\n\tuc := new(UseCase)\n\trepository = repo\n\treturn uc\n}", "func NewUsecase(repo Repository) Usecase {\n\treturn &usecase{\n\t\trepository: repo,\n\t}\n}", "func (a StoriesAllStories) construct() StoriesAllStoriesClass { return &a }", "func (t *BlogDB) NewPost(authorID bson.ObjectId, title, name, md, ptype string) (post *Post, err error) {\n\tif isExists, err := t.IsNameExists(name); err != nil {\n\t\treturn nil, err\n\t} else if isExists {\n\t\treturn nil, fmt.Errorf(\"post name `%v` already exists\", name)\n\t}\n\n\tts := time.Now()\n\tp := &Post{\n\t\tType: strings.ToLower(ptype),\n\t\tMarkdown: md,\n\t\tContent: string(ParseMarkdown2HTML([]byte(md))),\n\t\tModifiedAt: ts,\n\t\tCreatedAt: ts,\n\t\tTitle: title,\n\t\tName: strings.ToLower(url.QueryEscape(name)),\n\t\tStatus: \"publish\",\n\t\tAuthor: authorID,\n\t}\n\tp.Menu = ExtractMenu(p.Content)\n\n\tif utils.Settings.GetBool(\"dry\") {\n\t\tlibs.Logger.Info(\"insert post\",\n\t\t\tzap.String(\"title\", p.Title),\n\t\t\tzap.String(\"name\", p.Name),\n\t\t\t// zap.String(\"markdown\", p.Markdown),\n\t\t\t// zap.String(\"content\", p.Content),\n\t\t)\n\t} else {\n\t\tif err = t.dbcli.GetCol(POST_COL_NAME).Insert(p); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"try to insert post got error\")\n\t\t}\n\t}\n\n\treturn p, nil\n}", "func New(r IRepository) *Usecase {\n\treturn &Usecase{\n\t\tr,\n\t}\n}", "func newPage(pattern string, tmpls []string, getData getDataFn) *page {\n\treturn &page{\n\t\tpattern,\n\t\tgetTemplate(tmpls),\n\t\tgetData,\n\t}\n}", "func NewPost(url string) *Request { return NewRequest(\"POST\", url) }", "func New(process *stage.Process, action, suffix string, step int) *Meta {\n\treturn &Meta{\n\t\tProcess: *process,\n\t\tAction: action,\n\t\tMode: suffix,\n\t\tStep: step,\n\t}\n}", "func NewPage(ctx *sweetygo.Context) error {\n\tctx.Set(\"title\", \"New\")\n\tctx.Set(\"editor\", true)\n\treturn ctx.Render(200, \"posts/new\")\n}", "func New(domain string) (*Shortener, error) {\n\tdb, err := store.New(\"memory\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdomain = strings.TrimSpace(domain)\n\tif domain == \"\" {\n\t\treturn nil, fmt.Errorf(\"Empty domain is not allowed\")\n\t}\n\tif !strings.HasPrefix(domain, \"http\") {\n\t\tdomain = \"http://\" + domain\n\t}\n\tshortener := &Shortener{db, domain}\n\treturn shortener, nil\n}", "func (v ToursResource) New(c buffalo.Context) error {\n\treturn c.Render(200, r.Auto(c, &models.Tour{}))\n}", "func newSuggestSwapsSetup(cfg *Config, lnd *test.LndMockServices,\n\tparams Parameters) *testSuggestSwapsSetup {\n\n\treturn &testSuggestSwapsSetup{\n\t\tcfg: cfg,\n\t\tlnd: lnd,\n\t\tparams: params,\n\t}\n}", "func New(repo WriteExchanger, user User) *Usecase {\n\treturn &Usecase{repo, user}\n}", "func (a StoriesAllStoriesNotModified) construct() StoriesAllStoriesClass { return &a }", "func newMeta(db *leveldb.DB) (*meta, error) {\n\ttasks, err := loadTaskMetas(db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &meta{\n\t\ttasks: tasks,\n\t}, nil\n}", "func New(ctx activity.InitContext) (activity.Activity, error) {\n\n//\ts := &Settings{}\n//\terr := metadata.MapToStruct(ctx.Settings(), s, true)\n//\tif err != nil {\n//\t\treturn nil, err\n//\t}\n\n//\tctx.Logger().Debugf(\"Setting: %s\", s.ASetting)\n\n\tact := &Activity{} //add aSetting to instance//nothing to add now\n\n\treturn act, nil\n}", "func (env *Env) CreatePost(w http.ResponseWriter, r *http.Request) {\n\t// Grab the context to get the user\n\tctx := r.Context()\n\t// Clean everything\n\ts := bluemonday.UGCPolicy()\n\tuser := ctx.Value(contextUser).(*models.User)\n\ttitle := s.Sanitize(r.FormValue(\"title\"))\n\tslug := s.Sanitize(r.FormValue(\"slug\"))\n\tsubtitle := s.Sanitize(r.FormValue(\"subtitle\"))\n\tshort := s.Sanitize(r.FormValue(\"short\"))\n\tcontent := s.Sanitize(r.FormValue(\"content\"))\n\tdigest := s.Sanitize(r.FormValue(\"digest\"))\n\t// published must be parsed into a bool\n\tpublished, err := strconv.ParseBool(s.Sanitize(r.FormValue(\"published\")))\n\tif err != nil {\n\t\tenv.log(r, err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tp, err := env.DB.InsertPost(user.ID, title, slug, subtitle, short, content, digest, published)\n\tif err != nil {\n\t\tenv.log(r, err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\t// Send out created post\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(p)\n}", "func NewPost(w http.ResponseWriter, r *http.Request) {\n\n\tdb, err := sqlx.Connect(\"postgres\", connStr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tvar post m.PostIn\n\t_ = json.NewDecoder(r.Body).Decode(&post)\n\n\tquery := `insert into posts(title, content)\n\t\t\t\t\t\t\t\t\t\t\t values(:title, :content)`\n\n\t_, err = db.NamedExec(query, post)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func NewProfileStringUsecase(nr repo.StringRepo) *profileStringUsecase {\n // should be an assert\n if nr==nil {\n log.Fatal(fmt.Errorf(\"invalid repo.StringRepo\")) \n }\n u := &profileStringUsecase {profileRepo: nr }\n return u\n}", "func (v SuggestionsResource) New(c buffalo.Context) error {\n\t// Make suggestion available inside the html template\n\tc.Set(\"suggestion\", &models.Suggestion{})\n\n\treturn c.Render(200, r.HTML(\"suggestions/new.html\"))\n}", "func (a *api) newScenario(i interface{}) {\n\ta.c = nil\n\ta.resp = nil\n\ta.err = nil\n\ta.c = client.New(goaclient.HTTPClientDoer(http.DefaultClient))\n\ta.c.Host = \"localhost:8080\"\n}", "func TestNew_noMetaOnInit(t *testing.T) {\n\tt.Parallel()\n\n\ttmpDir := t.TempDir()\n\tbucket, err := fileblob.OpenBucket(tmpDir, nil)\n\trequire.NoError(t, err)\n\trequire.NoError(t,\n\t\tbucket.WriteAll(context.Background(), \".pulumi/stacks/dev.json\", []byte(\"bar\"), nil))\n\n\tctx := context.Background()\n\t_, err = New(ctx, diagtest.LogSink(t), \"file://\"+filepath.ToSlash(tmpDir), nil)\n\trequire.NoError(t, err)\n\n\tassert.NoFileExists(t, filepath.Join(tmpDir, \".pulumi\", \"meta.yaml\"))\n}", "func (c BlogPostItem) NewPost() revel.Result {\n\treturn c.Render(c)\n}", "func (e *Extractor) Slug(s string) error { return e.Meta(\"SLUG\", s) }", "func newFeature(name, description string, def, dynamic, install bool) *Feature {\n\tfeature := &Feature{\n\t\tname: name,\n\t\tdescription: description,\n\t\tdef: def,\n\t\tval: def,\n\t\tdynamic: dynamic,\n\t\tinstall: install,\n\t}\n\n\t// feature will be stored in feature map, features contained in feature\n\t// map will then be initialized\n\tfeatures[name] = feature\n\n\treturn feature\n}", "func New() Karteikaesten {\n\tvar db Karteikaesten\n\n\td := api.New(client.HostURL).DB(\"karteikaesten\")\n\tdb.db = d\n\n\tdb.views.OeffentlichKastenidKartenindex = OeffentlichKastenidKartenindex{\n\t\tView: d.View(\"karten\", \"oeffentlich-kastenid-kartenindex\"),\n\t}\n\n\tdb.views.NachAutor = NachAutor{\n\t\tView: d.View(\"kasten\", \"nach-autor\"),\n\t}\n\n\tdb.views.OeffentlichNachKategorie = OeffentlichNachKategorie{\n\t\tView: d.View(\"kasten\", \"oeffentlich-nach-kategorie\"),\n\t}\n\n\tdb.views.KartenNachAutor = KartenNachAutor{\n\t\tView: d.View(\"karten\", \"nach-autor\"),\n\t}\n\n\treturn db\n}", "func (h *Handlers) NewURL(w http.ResponseWriter, r *http.Request, params map[string]string) {\n\tu := params[\"\"]\n\n\tif !h.ValidateURL(u) {\n\t\th.RespondError(w, ErrInvalidURL, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\treqDB := h.masterDB.Copy()\n\tdefer reqDB.Close()\n\n\tcollection := reqDB.DB(\"\").C(urlCollection)\n\n\tslug := h.slugifier.GenerateUniqueSlug(8, collection, \"slug\")\n\n\tnewUrl := URL{\n\t\tSlug: slug,\n\t\tOriginalURL: u,\n\t\tShortURL: h.Host + \"/\" + slug,\n\t}\n\n\tif err := collection.Insert(&newUrl); err != nil {\n\t\th.RespondError(w, ErrUnableToShortenUrl, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\th.RespondJSON(w, newUrl, 201)\n}", "func (f Feeds) New(url string) error {\n\tfeed, err := gofeed.NewParser().ParseURL(url)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"gofeed parse %v\", err)\n\t}\n\tf[url] = NewFeed(feed.Title)\n\treturn nil\n}", "func New(ctx resource.Context, cfg echo.Config) (i echo.Instance, err error) {\n\terr = resource.UnsupportedEnvironment(ctx.Environment())\n\n\tctx.Environment().Case(environment.Native, func() {\n\t\ti, err = native.New(ctx, cfg)\n\t})\n\n\tctx.Environment().Case(environment.Kube, func() {\n\t\ti, err = kube.New(ctx, cfg)\n\t})\n\treturn\n}", "func New(_ context.Context, next http.Handler, config *TestConfiguration, name string) (http.Handler, error) {\n\ts := &SouinTraefikPlugin{\n\t\tname: name,\n\t\tnext: next,\n\t}\n\tc := parseConfiguration(*config)\n\n\ts.Retriever = DefaultSouinPluginInitializerFromConfiguration(&c)\n\treturn s, nil\n}", "func (fs *FS) NewPost(id int64, parent int64, msg Message) error {\n\terr := fs.writePost(id, parent, msg)\n\tif err != nil { return err }\n\n\t// when id==parent, it's a thread\n\tif id == parent {\n\t\terr := fs.setThread(id, msg)\n\t\tfmt.Println(err)\n\t\tif err != nil { return err }\n\t}\n\treturn nil\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 NewPostRouter(br fiber.Router, conn *config.DBConn) {\n\trouter := br.Group(\"/posts\")\n\tpostRepo := repository.NewPostRepository(conn)\n\tsharedPostRepo := repository.NewSharedPostRepository(conn)\n\tuserRepo := repository.NewUserRepository(conn)\n\ttopicRepo := repository.NewTopicRepository(conn)\n\tcommentRepo := repository.NewCommentRepository(conn)\n\tspaceRepo := repository.NewSpaceRepository(conn)\n\tpostService := services.NewPostService(postRepo, userRepo, sharedPostRepo, commentRepo, spaceRepo, topicRepo)\n\tuserService := services.NewUserService(userRepo, postRepo, topicRepo, spaceRepo, sharedPostRepo)\n\tcommentService := services.NewCommentService(commentRepo, userRepo, postRepo)\n\tcontroller := controllers.NewPostController(postService, userService, commentService)\n\n\trouter.Get(\"/feed\", middleware.AuthorizeRoute(), controller.GetFeedForUser)\n\trouter.Get(\"/questions\", middleware.AuthorizeRoute(), controller.GetQuestionsForUser)\n\trouter.Get(\"/suggestions\", middleware.AuthorizeRoute(), controller.GetSuggestedQuestions)\n\trouter.Get(\"/slug\", middleware.AuthorizeRoute(), controller.GetBySlug)\n\trouter.Patch(\"/:id/upvote\", middleware.AuthorizeRoute(), controller.UpvotePostByUser)\n\trouter.Patch(\"/:id/downvote\", middleware.AuthorizeRoute(), controller.DownvotePostByUser)\n\trouter.Patch(\"/:id/follow\", middleware.AuthorizeRoute(), controller.FollowPost)\n\trouter.Patch(\"/:id/unfollow\", middleware.AuthorizeRoute(), controller.UnfollowPost)\n\trouter.Post(\"/:id/share\", middleware.AuthorizeRoute(), controller.SharePost)\n\trouter.Post(\"/:id/topics\", middleware.AuthorizeRoute(), controller.AddTopicsToPost)\n\trouter.Get(\"/:id/topics\", middleware.AuthorizeRoute(), controller.GetTopicsForPost)\n\trouter.Get(\"/:id/answers\", middleware.AuthorizeRoute(), controller.GetAnswersForQuestion)\n\trouter.Get(\"/:id\", controller.GetOne)\n\trouter.Get(\"/\", controller.GetAll)\n\trouter.Post(\"/\", middleware.AuthorizeRoute(), controller.Create)\n\trouter.Delete(\"/:id\", controller.DeleteOne)\n}", "func Show(ctx *sweetygo.Context) error {\n\tif title := ctx.Param(\"title\"); title != \"\" {\n\t\ttitle := strings.Replace(title, \"-\", \" \", -1)\n\t\tpost, err := model.GetPostByTitle(title)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif post.ID == 0 {\n\t\t\treturn ctx.Text(404, \"404 not found\")\n\t\t}\n\t\tctx.Set(\"post\", post)\n\t\tctx.Set(\"title\", title)\n\t\tctx.Set(\"show\", true)\n\t\treturn ctx.Render(200, \"posts/show\")\n\t}\n\treturn nil\n}", "func New(title string, path string, body string) *BlogPost {\n\treturn &BlogPost{Title: title,\n\t\tPath: path,\n\t\tBody: template.HTML(body),\n\t\tApproved: false,\n\t\tDeleted: false,\n\t\tPublished: false,\n\t\tCreatedDate: time.Now(),\n\t}\n}", "func New(cl domain.ColumnRepository, t domain.TaskRepository, c domain.CommentRepository) domain.TaskUsecase {\n\treturn &taskUsecase{columnRepo: cl, taskRepo: t, commentRepo: c}\n}", "func newAnalysis(ep *whodunit.Episode, d *Detective) *Analysis {\n\treturn &Analysis{\n\t\tEpisode: ep,\n\t\tdetective: d,\n\t\tassetType: assetTypeForCloudService(d.cloudService),\n\t}\n}", "func Create(w http.ResponseWriter, r *http.Request) {\n\tc := flight.Context(w, r)\n\n\tv := c.View.New(\"article/create\")\n\tc.Repopulate(v.Vars, \"tittle\")\n\tv.Render(w, r)\n}", "func (c *Client) newPost(endpoint string, reqBody []byte) (*http.Request, error) {\n\tcurl, err := c.getURL(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err := http.NewRequest(http.MethodPost, curl, bytes.NewReader(reqBody))\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Failed posting to %s\", curl)\n\t}\n\treturn req, nil\n}", "func NewPost(creator *ID, text string, attachment *string) (*Post, error) {\n\tp := &Post{\n\t\tID: NewID(),\n\t\tCreator: creator,\n\t\tText: text,\n\t\tAttachment: attachment,\n\t\tCreatedAt: time.Now(),\n\t}\n\terr := p.Validate()\n\tif err != nil {\n\t\treturn nil, ErrInvalidEntity\n\t}\n\treturn p, nil\n}", "func newAlias() *Alias {\n\treturn &Alias{url: \"\", dict: make(Dict)}\n}", "func New(svc service.Service, logger log.Logger) Set {\n\treturn Set{\n\t\tNewSiteEndpoint: Middlewares(MakeNewSiteEndpoint(svc), logger),\n\t\tDeleteSiteEndpoint: Middlewares(MakeDeleteSiteEndpoint(svc), logger),\n\t\tCheckSitenameExistsEndpoint: Middlewares(MakeCheckSitenameExistsEndpoint(svc), logger),\n\t\tGetSiteIDByUserIDEndpoint: Middlewares(MakeGetSiteIDByUserIDEndpoint(svc), logger),\n\t\tGetConfigEndpoint: Middlewares(MakeGetConfigEndpoint(svc), logger),\n\t\tUpdateConfigEndpoint: Middlewares(MakeUpdateConfigEndpoint(svc), logger),\n\t\tGetThemesEndpoint: Middlewares(MakeGetThemesEndpoint(svc), logger),\n\t\tUpdateSiteThemeEndpoint: Middlewares(MakeUpdateSiteThemeEndpoint(svc), logger),\n\t\tPostAboutEndpoint: Middlewares(MakePostAboutEndpoint(svc), logger),\n\t\tGetAboutEndpoint: Middlewares(MakeGetAboutEndpoint(svc), logger),\n\t}\n}", "func (s *slugsService) Create(ctx context.Context, db *gorm.DB, img image.Image, w *DeploymentStream) (*Slug, error) {\n\treturn slugsCreateByImage(ctx, db, s.ImageRegistry, img, w)\n}", "func NewBase() Base {\r\n\treturn Base{\r\n\t\tActive: \"\",\r\n\t\tTitle: \"Lemonade Stand Supply\",\r\n\t}\r\n}", "func createPost(w http.ResponseWriter, r *http.Request) {\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\tvar post Post\r\n\t_ = json.NewDecoder(r.Body).Decode(&post)\r\n\tpost.ID = strconv.Itoa(rand.Intn(10000))\r\n\tposts = append(posts, post)\r\n\tjson.NewEncoder(w).Encode(&post)\r\n}", "func slugsCreate(db *gorm.DB, slug *Slug) (*Slug, error) {\n\treturn slug, db.Create(slug).Error\n}", "func NewMockIPostUsecase(ctrl *gomock.Controller) *MockIPostUsecase {\n\tmock := &MockIPostUsecase{ctrl: ctrl}\n\tmock.recorder = &MockIPostUsecaseMockRecorder{mock}\n\treturn mock\n}", "func CreatePost(travelcapsule, title, message, imgloc string, hashtags []string, username string, session *r.Session) string {\n\tcapsule := travelcapsule\n\n\tif travelcapsule != \"\" {\n\t\tvar body ct.Body\n\t\tbody = ct.Body{\n\t\t\tMessage: message,\n\t\t}\n\t\t\n\t\tpost := ct.Post{\n\t\t\tTitle: title,\n\t\t\tCreatedOn: time.Now(),\n\t\t\tCreatedBy: username,\n\t\t\tPostBody: body,\n\t\t\tHashtags: hashtags,\n\t\t\tLikes: 0,\n\t\t}\n\t\tcreator := CheckTravelCapsuleExists(travelcapsule, session)\n\t\tfmt.Println(\"Creator: \" + creator + \" User: \" + username)\n\t\tif creator == username {\n\t\t\tgo addImageToPost(imgloc, travelcapsule, post, session)\n\t\t\tfmt.Println(\"Added image\")\n\t\t\treturn capsule\n\t\t}\n\t}\n\treturn \"\"\n}", "func CreateUsecase(userRepo user.UserRepo) user.UserUsecase {\n\treturn &UserUsecaseImpl{userRepo}\n}", "func CreateEndpoint(w http.ResponseWriter, req *http.Request) {\n\tvar url ShortURL\n\t_ = json.NewDecoder(req.Body).Decode($url)\n\tvar n1q1Params []interface{}\n\tn1q1Params = append(n1q1Params, url.LongURL)\n\tquery := gocb.NewN1qlQuery(\"SELECT `\" + bucketName + \"`.* FROM `\" + bucketName + \"` WHERE longUrl = $1\")\n\trows, err := bucket.ExecuteN1qlQuery(query, n1qlParams)\n\tif err != nil {\n w.WriteHeader(401)\n w.Write([]byte(err.Error()))\n return\n\t}\n\tvar row ShortURL\n rows.One(&row)\n if row == (ShortURL{}) {\n hd := hashids.NewData()\n h := hashids.NewWithData(hd)\n now := time.Now()\n url.ID, _ = h.Encode([]int{int(now.Unix())})\n url.ShortUrl = \"http://localhost:12345/\" + url.ID\n bucket.Insert(url.ID, url, 0)\n } else {\n url = row\n }\n json.NewEncoder(w).Encode(url)\n}", "func NewUseCase(repository user.Repository) *UserUseCase {\n\treturn &UserUseCase{\n\t\trepository,\n\t}\n}", "func (h *MovieHandler) new(w http.ResponseWriter, r *http.Request) {\n\t// Render a HTML response and set status code.\n\trender.HTML(w, http.StatusOK, \"movie/new.html\", nil)\n}", "func CreatePost(w http.ResponseWriter, r *http.Request) {\n\tvar createPost CreatePostDto\n\tif err := json.NewDecoder(r.Body).Decode(&createPost); err != nil {\n\t\tresponse.Error(w, http.StatusBadGateway, err.Error())\n\t\treturn\n\t}\n\n\tvar post Posts\n\tpost.Title = createPost.Title\n\tpost.Description = createPost.Description\n\tpost.ImageURL = createPost.ImageURL\n\n\tuserID := gCtx.Get(r, \"uid\")\n\tpostID, err := post.Save(userID.(string))\n\tif err != nil {\n\t\tresponse.Error(w, http.StatusBadGateway, err.Error())\n\t\treturn\n\t}\n\tresponse.Success(w, r,\n\t\thttp.StatusCreated,\n\t\tmap[string]interface{}{\n\t\t\t\"id\": postID,\n\t\t},\n\t)\n\treturn\n}", "func (wds *WeaponAISystem) New(w *ecs.World) {\n\n}", "func (o *FakeObject) New(args ...interface{}) Object { return o.Invoke(args) }", "func newDemos(c *DemocontrollerV1alpha1Client, namespace string) *demos {\n\treturn &demos{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}", "func (t *BlogDB) NewPost(authorID bson.ObjectId, title, name, md string) (post *Post, err error) {\n\tif isExists, err := t.IsNameExists(name); err != nil {\n\t\treturn nil, err\n\t} else if isExists {\n\t\treturn nil, fmt.Errorf(\"post name `%v` already exists\", name)\n\t}\n\n\tts := time.Now()\n\tp := &Post{\n\t\tMarkdown: md,\n\t\tContent: string(markdown.ToHTML([]byte(md), nil, nil)),\n\t\tModifiedAt: ts,\n\t\tCreatedAt: ts,\n\t\tTitle: title,\n\t\tName: name,\n\t\tStatus: \"publish\",\n\t\tAuthor: authorID,\n\t}\n\n\tif utils.Settings.GetBool(\"dry\") {\n\t\tutils.Logger.Info(\"insert post\",\n\t\t\tzap.String(\"title\", p.Title),\n\t\t\tzap.String(\"name\", p.Name),\n\t\t\t// zap.String(\"markdown\", p.Markdown),\n\t\t\t// zap.String(\"content\", p.Content),\n\t\t)\n\t} else {\n\t\tif err = t.posts.Insert(p); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"try to insert post got error\")\n\t\t}\n\t}\n\n\treturn p, nil\n}", "func (bbo *TabularBBO) NewEpisode() {}", "func NewInstance(endpoint string, meta InstanceMeta) Instance {\n\t// FIXME: How about if meta have \"endpoint\" ?\n\tif meta == nil {\n\t\tmeta = make(InstanceMeta)\n\t}\n\tmeta[\"endpoint\"] = endpoint\n\treturn Instance{\n\t\tID: uuid.New(),\n\t\tEndpoint: endpoint,\n\t\tMeta: meta,\n\t}\n}", "func New(w http.ResponseWriter, r *http.Request) {\n\tgetTemplates().ExecuteTemplate(w, \"New\", nil)\n}", "func (s StorePaymentPurposeGiftedPremium) construct() StorePaymentPurposeClass { return &s }", "func NewBusinessScenarioPlanner()(*BusinessScenarioPlanner) {\n m := &BusinessScenarioPlanner{\n Entity: *NewEntity(),\n }\n return m\n}", "func (vm *ViewModel) NewBlogFromDb(data *models.Article) *Blog {\n\tb := &Blog{}\n\tb.Title = data.Title.String\n\tif b.Title == \"\" {\n\t\tb.Title = \"无题\"\n\t}\n\tb.Content = data.Content.String\n\tb.Adddate = data.AddDate.Time.Format(dateFormat)\n\n\tcateData, _ := vm.Cates(qm.Where(\"`index` = ?\", data.Cate.Int)).OneG()\n\tif cateData != nil {\n\t\tb.CateID = cateData.Index\n\t\tb.CateName = cateData.Cate\n\t}\n\n\treturn b\n}", "func (turnbull *turnbull) buildScaffoldUsecasePresenter(entity model.Entity) (error){\n\n\tif len(entity.Presenters) > 0 {\n\n\t\t// Build\n\t\tbuf := &bytes.Buffer{}\n\t\terr := turnbull.generator.ScaffoldUsecasePresenter(entity, buf)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// File Name\n\t\tfileName, err := turnbull.formatter.OutputScaffoldUsecasePresenterFile(entity)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// File\n\t\tfile, err := os.Create(fileName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\n\t\t// Write\n\t\t_, err = file.WriteString(buf.String())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\t\n\n\treturn nil\n}", "func NewProductController(router gin.IRouter, client *ent.Client) *ProductController {\n pc := &ProductController{\n client: client,\n router: router,\n }\n pc.register()\n return pc\n }", "func (s *BlugService) CreatePost(ctx context.Context, post *models.Post) (err error) {\n\tdefer func(begin time.Time) {\n\t\ts.Logger.Info(\n\t\t\t\"blug\",\n\t\t\tzap.String(\"method\", \"createpost\"),\n\t\t\tzap.Int(\"id\", post.ID),\n\t\t\tzap.NamedError(\"err\", err),\n\t\t\tzap.Duration(\"took\", time.Since(begin)),\n\t\t)\n\t}(time.Now())\n\n\tunsafe := blackfriday.Run(\n\t\t[]byte(post.Markdown),\n\t\tblackfriday.WithNoExtensions(),\n\t)\n\tpost.HTML = string(bluemonday.UGCPolicy().SanitizeBytes(unsafe))\n\n\terr = s.DB.CreatePost(post)\n\n\treturn err\n}", "func newDefaultAdvisor(soarBin, configFile string) *DefaultAdvisor {\n\treturn &DefaultAdvisor{\n\t\tparser: parser.NewParserWithDefault(),\n\t\tsoarBin: soarBin,\n\t\tconfigFile: configFile,\n\t}\n}", "func (t *UseCase_UseCase_UseCase) NewSite(Site string) (*UseCase_UseCase_UseCase_Site, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Site == nil {\n\t\tt.Site = make(map[string]*UseCase_UseCase_UseCase_Site)\n\t}\n\n\tkey := Site\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Site[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Site\", key)\n\t}\n\n\tt.Site[key] = &UseCase_UseCase_UseCase_Site{\n\t\tSite: &Site,\n\t}\n\n\treturn t.Site[key], nil\n}", "func NewTask(vres *artworksviews.Task) *Task {\n\tvar res *Task\n\tswitch vres.View {\n\tcase \"tiny\":\n\t\tres = newTaskTiny(vres.Projected)\n\tcase \"default\", \"\":\n\t\tres = newTask(vres.Projected)\n\t}\n\treturn res\n}", "func New(engine *gin.Engine) resource.Routable {\n\tanimals := &animals{group: engine.Group(\"/animals\")}\n\t{\n\t\tanimals.group.GET(\"\", animals.findAnimals)\n\t\tanimals.group.GET(\"/:id\", animals.getAnimals)\n\t\tanimals.group.DELETE(\"/:id\", animals.deleteAnimals)\n\t}\n\treturn animals\n}", "func New() *Meta {\n\treturn &Meta{}\n}", "func New() *Meta {\n\treturn &Meta{}\n}", "func NewFaq(ctx *pulumi.Context,\n\tname string, args *FaqArgs, opts ...pulumi.ResourceOption) (*Faq, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.IndexId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'IndexId'\")\n\t}\n\tif args.RoleArn == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'RoleArn'\")\n\t}\n\tif args.S3Path == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'S3Path'\")\n\t}\n\tvar resource Faq\n\terr := ctx.RegisterResource(\"aws:kendra/faq:Faq\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func CreatePost(images []types.FileMetadata, author types.User, p types.RawPost, headerImage types.FileMetadata) (interface{}, error) {\n\tif p.ShortURL == \"new\" {\n\t\treturn nil, errors.New(\"the title `new` is reserved\")\n\t}\n\n\tvar post types.Post\n\tdb := database.GetMySQLInstance()\n\tdefer db.Close()\n\n\terr := db.Where(\"shorturl LIKE ?\", p.ShortURL).First(&post).Error\n\tif err != gorm.ErrRecordNotFound {\n\t\treturn nil, errors.New(\"post with similar title already exists..be unique\")\n\t}\n\n\tif p.HeaderImageIndex == nil {\n\t\tp.HeaderImageIndex = &EmptyHeaderIndex\n\t}\n\n\tpost = types.Post{\n\t\tAuthor: &author,\n\t\tTitle: p.Title,\n\t\tShortURL: p.ShortURL,\n\t\tType: p.Type,\n\t\tAbstract: p.Abstract,\n\t\tContent: p.Content,\n\t\tPubDate: p.PubDate,\n\t\tTags: CleanTags(p.Tags),\n\t\tHeaderImageIndex: p.HeaderImageIndex,\n\t\tReadNext: []string{p.ReadNext},\n\t\tIPOwner: p.IPOwner,\n\t}\n\n\t// headerImage was seperated from other images in handler earlier so we can\n\t// process headerImage differently later\n\t// @todo: func resolveHeaderImage\n\n\tpost, err = resolveAttachments(images, post, *post.HeaderImageIndex, headerImage, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = createPost(&post, db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn post, nil\n}", "func newSearch(inst *Instagram) *Search {\n\tsearch := &Search{\n\t\tinst: inst,\n\t}\n\treturn search\n}" ]
[ "0.58909637", "0.5425699", "0.53912926", "0.53115577", "0.52724636", "0.5240457", "0.519414", "0.51667655", "0.5088023", "0.5032141", "0.5024942", "0.50157803", "0.5003912", "0.49888113", "0.49785644", "0.4961714", "0.49477577", "0.49056473", "0.4904455", "0.48526642", "0.4848975", "0.4847145", "0.4842453", "0.48414657", "0.48188496", "0.4809164", "0.4800606", "0.47940463", "0.47838694", "0.47554585", "0.4689967", "0.46722084", "0.46633923", "0.46597278", "0.4658361", "0.4647829", "0.46442273", "0.46328956", "0.4628932", "0.46195272", "0.46141577", "0.4603306", "0.46016008", "0.45956966", "0.4580797", "0.45662513", "0.45456743", "0.45296505", "0.45229596", "0.45121565", "0.45065302", "0.45042685", "0.4502495", "0.4499972", "0.44967252", "0.44939023", "0.44939023", "0.4490495", "0.44808763", "0.44790328", "0.4476074", "0.44689617", "0.44490612", "0.4448812", "0.44481224", "0.44444683", "0.444057", "0.44361585", "0.4426393", "0.44190958", "0.44136295", "0.44106606", "0.44053242", "0.44012392", "0.43962872", "0.4389896", "0.43880185", "0.4383155", "0.4382153", "0.4376846", "0.4371368", "0.43695152", "0.4360169", "0.43471783", "0.43443382", "0.4338078", "0.43343863", "0.43314633", "0.43302858", "0.43238047", "0.4320425", "0.43178582", "0.4317281", "0.4317169", "0.43138346", "0.43073204", "0.43073204", "0.4306402", "0.43050823", "0.4304728" ]
0.67127544
0
Execute the usecase ShowPostBySlug
func (r *showPostBySlugInteractor) Execute(ctx context.Context, req InportRequest) (*InportResponse, error) { res := &InportResponse{} err := repository.WithTransaction(ctx, r.outport, func(ctx context.Context) error { postObj, err := r.outport.FindPostBySlug(ctx, req.Slug) if err != nil { return apperror.ObjectNotFound.Var(postObj) } postObj.UpdateViewCount() err = r.outport.SavePost(ctx, postObj) if err != nil { return err } var vCategories []CategoryResponse for _, v := range postObj.Categories { vCategories = append(vCategories, CategoryResponse{ ID: v.ID, Category: v.Category, }) } var vTags []TagResponse for _, v := range postObj.Tags { vTags = append(vTags, TagResponse{ ID: v.ID, Tag: v.Tag, }) } res = &InportResponse{ ID: postObj.ID, Title: postObj.Title, Description: postObj.Description, Content: json.RawMessage(postObj.Content), Cover: postObj.Cover, Slug: postObj.Slug, ViewCount: postObj.ViewCount, Categories: vCategories, Tags: vTags, UserID: postObj.UserID, AuthorName: postObj.User.Name, CreatedAt: postObj.CreatedAt, UpdatedAt: postObj.UpdatedAt, } return nil }) if err != nil { return nil, err } return res, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Show(ctx *sweetygo.Context) error {\n\tif title := ctx.Param(\"title\"); title != \"\" {\n\t\ttitle := strings.Replace(title, \"-\", \" \", -1)\n\t\tpost, err := model.GetPostByTitle(title)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif post.ID == 0 {\n\t\t\treturn ctx.Text(404, \"404 not found\")\n\t\t}\n\t\tctx.Set(\"post\", post)\n\t\tctx.Set(\"title\", title)\n\t\tctx.Set(\"show\", true)\n\t\treturn ctx.Render(200, \"posts/show\")\n\t}\n\treturn nil\n}", "func ShowPost(c buffalo.Context) error {\n\tdatabase := c.Value(\"tx\").(*pop.Connection)\n\n\tpost := &models.Post{}\n\n\tif txErr := database.Eager().Find(post, c.Param(\"post_id\")); txErr != nil {\n\n\t\tnotFoundResponse := utils.NewErrorResponse(\n\t\t\thttp.StatusNotFound,\n\t\t\t\"post_id\",\n\t\t\tfmt.Sprintf(\"The requested post %s is removed or move to somewhere else.\", c.Param(\"post_id\")),\n\t\t)\n\t\treturn c.Render(http.StatusNotFound, r.JSON(notFoundResponse))\n\t}\n\n\tpostResponse := PostResponse{\n\t\tCode: fmt.Sprintf(\"%d\", http.StatusOK),\n\t\tData: post,\n\t}\n\treturn c.Render(http.StatusOK, r.JSON(postResponse))\n}", "func (cmd *ShowPostCommand) Run(c *client.Client, args []string) error {\n\tvar path string\n\tif len(args) > 0 {\n\t\tpath = args[0]\n\t} else {\n\t\tpath = fmt.Sprintf(\"/posts/%v\", cmd.PostID)\n\t}\n\tlogger := goa.NewLogger(log.New(os.Stderr, \"\", log.LstdFlags))\n\tctx := goa.WithLogger(context.Background(), logger)\n\tresp, err := c.ShowPost(ctx, path)\n\tif err != nil {\n\t\tgoa.LogError(ctx, \"failed\", \"err\", err)\n\t\treturn err\n\t}\n\n\tgoaclient.HandleResponse(c.Client, resp, PrettyPrint)\n\treturn nil\n}", "func (dash *Dashboard) UpdateSlug() {\n\tdash.Slug = utils.Slugify(dash.Title)\n}", "func (a App) ShowPost(res http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\n\ttmpl := buildView(\"show_post\")\n\n\t// Standard server error, but don't crash\n\tp := findPostById(params.ByName(\"id\"))\n\tif p.Id == \"\" {\n\t\tmsg := fmt.Sprintf(\"No post with id %v\", params.ByName(\"id\"))\n\t\thttp.Error(res, msg, http.StatusInternalServerError)\n\t}\n\n\tpd := PageData{\n\t\tPageTitle: p.Title,\n\t\tPost: p,\n\t}\n\n\terr := tmpl.ExecuteTemplate(res, \"layout\", pd)\n\n\tif err != nil {\n\t\thttp.Error(res, err.Error(), http.StatusInternalServerError)\n\t}\n}", "func (c CategoryPostController) Show(ctx *fasthttp.RequestCtx) {\n\tvar post model.PostDEP\n\tvar postSlug model.PostSlug\n\tvar postDetail model.PostDetail\n\tvar postCategoryAssignment model.PostCategoryAssignment\n\tvar category model.Category\n\tvar user model.User\n\tc.GetDB().QueryRowWithModel(fmt.Sprintf(`\n\t\tSELECT \n\t\t\tp.id as id, p.author_id as author_id, u.username as author_username, \n\t\t\tp.inserted_at as inserted_at, ps.slug as slug, pd.title as title, \n\t\t\tpd.description as description, pd.content as content\n\t\tFROM %s AS p\n\t\tLEFT OUTER JOIN %s AS ps ON p.id = ps.post_id\n\t\tLEFT OUTER JOIN %s AS ps2 ON ps.post_id = ps2.post_id AND ps.id < ps2.id\n\t\tINNER JOIN %s AS pd ON p.id = pd.post_id\n\t\tLEFT OUTER JOIN %s AS pd2 ON pd.post_id = pd2.post_id AND pd.id < pd2.id\n\t\tINNER JOIN %s AS u ON p.author_id = u.id\n\t\tINNER JOIN %s AS pca ON p.id = pca.post_id\n\t\tINNER JOIN %s AS c ON pca.category_id = c.id\n\t\tWHERE ps2.id IS NULL AND pd2.id IS NULL AND (c.id::text = $1::text OR c.slug = $1) AND \n\t\t\t(p.id::text = $2::text OR ps.slug = $2)\n\t`, c.Model.TableName(), postSlug.TableName(), postSlug.TableName(), postDetail.TableName(),\n\t\tpostDetail.TableName(), user.TableName(), postCategoryAssignment.TableName(), category.TableName()),\n\t\t&post,\n\t\tphi.URLParam(ctx, \"categoryID\"),\n\t\tphi.URLParam(ctx, \"postID\")).Force()\n\n\tc.JSONResponse(ctx, model2.ResponseSuccessOne{\n\t\tData: post,\n\t}, fasthttp.StatusOK)\n}", "func (p *Post) Slug() string {\n return Slugified(p.Title)\n}", "func showPost(w http.ResponseWriter, r *http.Request) {\n\n\tw.Header().Set(\"cache-control\", \"no-store, no-cache, must-revalidate\")\n\tsession := sessions.Start(w, r)\n\n\tif len(session.GetString(\"username\")) == 0 {\n\t\thttp.Redirect(w, r, \"/login\", 301)\n\t}\n\n\tcurrentUser := QueryUser(session.GetString(\"username\"))\n\tvars := mux.Vars(r)\n\tpost_id := vars[\"id\"]\n\n\tvar posts = post{}\n\tvar timestamp time.Time\n\tvar yeahed string\n\n\tdb.QueryRow(\"SELECT posts.id, created_by, community_id, created_at, body, image, username, nickname, avatar, online FROM posts LEFT JOIN users ON users.id = created_by WHERE posts.id = ?\", post_id).\n\t\tScan(&posts.ID, &posts.CreatedBy, &posts.CommunityID, &timestamp, &posts.Body, &posts.Image, &posts.PosterUsername, &posts.PosterNickname, &posts.PosterIcon, &posts.PosterOnline)\n\tposts.CreatedAt = humanTiming(timestamp)\n\n\tdb.QueryRow(\"SELECT id FROM yeahs WHERE yeah_post = ? AND yeah_by = ? AND on_comment=0\", posts.ID, currentUser.ID).Scan(&yeahed)\n\tif yeahed != \"\" {\n\t\tposts.Yeahed = true\n\t}\n\n\tdb.QueryRow(\"SELECT COUNT(id) FROM yeahs WHERE yeah_post = ? AND on_comment=0\", post_id).Scan(&posts.YeahCount)\n\tdb.QueryRow(\"SELECT COUNT(id) FROM comments WHERE post = ?\", post_id).Scan(&posts.CommentCount)\n\n\tyeah_rows, _ := db.Query(\"SELECT yeahs.id, username, avatar FROM yeahs LEFT JOIN users ON users.id = yeah_by WHERE yeah_post = ? AND yeah_by != ? AND on_comment=0 ORDER BY yeahs.id DESC\", post_id, currentUser.ID)\n\tvar yeahs []yeah\n\n\tfor yeah_rows.Next() {\n\n\t\tvar row = yeah{}\n\n\t\terr = yeah_rows.Scan(&row.ID, &row.Username, &row.Avatar)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tyeahs = append(yeahs, row)\n\n\t}\n\tyeah_rows.Close()\n\n\tcomment_rows, _ := db.Query(\"SELECT comments.id, created_by, created_at, body, image, username, nickname, avatar, online FROM comments LEFT JOIN users ON users.id = created_by WHERE post = ? ORDER BY created_at ASC\", post_id)\n\tvar comments []comment\n\n\tfor comment_rows.Next() {\n\n\t\tvar row = comment{}\n\t\tvar timestamp time.Time\n\n\t\terr = comment_rows.Scan(&row.ID, &row.CreatedBy, &timestamp, &row.Body, &row.Image, &row.CommenterUsername, &row.CommenterNickname, &row.CommenterIcon, &row.CommenterOnline)\n\t\trow.CreatedAt = humanTiming(timestamp)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\n\t\tdb.QueryRow(\"SELECT 1 FROM yeahs WHERE yeah_post = ? AND yeah_by = ? AND on_comment=1\", row.ID, currentUser.ID).Scan(&row.Yeahed)\n\n\t\tdb.QueryRow(\"SELECT COUNT(id) FROM yeahs WHERE yeah_post = ? AND on_comment=1\", row.ID).Scan(&row.YeahCount)\n\n\t\tcomments = append(comments, row)\n\n\t}\n\tcomment_rows.Close()\n\n\tcommunity := QueryCommunity(strconv.Itoa(posts.CommunityID))\n\tpjax := r.Header.Get(\"X-PJAX\") == \"\"\n\n\tvar data = map[string]interface{}{\n\t\t\"Title\": posts.PosterNickname + \"'s post\",\n\t\t\"Pjax\": pjax,\n\t\t\"CurrentUser\": currentUser,\n\t\t\"Community\": community,\n\t\t\"Post\": posts,\n\t\t\"Yeahs\": yeahs,\n\t\t\"Comments\": comments,\n\t}\n\n\terr := templates.ExecuteTemplate(w, \"post.html\", data)\n\tif err != nil {\n\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\n\t}\n\n\treturn\n\n}", "func PostChangeSlug(slug string) bool {\n\tpost := new(Post)\n\terr := post.GetPostBySlug(slug)\n\tif err != nil {\n\t\treturn true\n\t}\n\treturn false\n}", "func (e *Extractor) Slug(s string) error { return e.Meta(\"SLUG\", s) }", "func ShowPostsHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"showing posts\")\n}", "func PublishPost(shorturl string) (types.Post, error) {\n\tdb := database.GetMySQLInstance()\n\tdefer db.Close()\n\tvar post types.Post\n\terr := db.Where(\"shorturl LIKE ?\", shorturl).First(&post).Error\n\tif err != nil && err == gorm.ErrRecordNotFound {\n\t\treturn post, errors.New(\"post not found\")\n\t}\n\n\terr = db.Model(&post).Updates(map[string]interface{}{\"published\": true}).Error\n\tif err != nil {\n\t\treturn post, err\n\t}\n\n\tpost.Published = true\n\treturn post, nil\n}", "func NewUsecase(outputPort Outport) Inport {\n\treturn &showPostBySlugInteractor{\n\t\toutport: outputPort,\n\t}\n}", "func (o *KanbanViewView) GetSlug() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Slug\n}", "func HandleShow(context router.Context) error {\n\n\t// No auth - this is public\n\n\t// Find the user\n\tuser, err := users.Find(context.ParamInt(\"id\"))\n\tif err != nil {\n\t\tcontext.Logf(\"#error parsing user id: %s\", err)\n\t\treturn router.NotFoundError(err)\n\t}\n\n\t// Get the user comments\n\tq := comments.Where(\"user_id=?\", user.Id).Limit(10).Order(\"created_at desc\")\n\tuserComments, err := comments.FindAll(q)\n\tif err != nil {\n\t\treturn router.InternalError(err)\n\t}\n\n\t// Get the user stories\n\tq = stories.Where(\"user_id=?\", user.Id).Limit(50).Order(\"created_at desc\")\n\tuserStories, err := stories.FindAll(q)\n\tif err != nil {\n\t\treturn router.InternalError(err)\n\t}\n\n\t// Render the Template\n\tview := view.New(context)\n\tview.AddKey(\"user\", user)\n\tview.AddKey(\"comments\", userComments)\n\tview.AddKey(\"stories\", userStories)\n\tview.AddKey(\"meta_title\", user.Name)\n\tview.AddKey(\"meta_desc\", user.Name)\n\n\treturn view.Render()\n\n}", "func EditPost(req *http.Request, params martini.Params, res render.Render) {\n\tvar post Post\n\tpost.Slug = params[\"slug\"]\n\tpost, err := post.Get()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tres.JSON(500, map[string]interface{}{\"error\": \"Internal server error\"})\n\t\treturn\n\t}\n\tres.HTML(200, \"post/edit\", post)\n}", "func (p *Post) Url() string {\n\treturn \"/\" + p.Slug\n}", "func HandleUpdateShow(w http.ResponseWriter, r *http.Request) error {\n\n\t// Fetch the params\n\tparams, err := mux.Params(r)\n\tif err != nil {\n\t\treturn server.InternalError(err)\n\t}\n\n\t// Find the post\n\tpost, err := posts.Find(params.GetInt(posts.KeyName))\n\tif err != nil {\n\t\treturn server.NotFoundError(err)\n\t}\n\n\t// Authorise update post\n\tuser := session.CurrentUser(w, r)\n\terr = can.Update(post, user)\n\tif err != nil {\n\t\treturn server.NotAuthorizedError(err)\n\t}\n\n\t// Fetch the users\n\tauthors, err := users.FindAll(users.Where(\"role=?\", users.Admin))\n\tif err != nil {\n\t\treturn server.InternalError(err)\n\t}\n\n\t// Render the template\n\tview := view.NewRenderer(w, r)\n\tview.AddKey(\"currentUser\", user)\n\tview.AddKey(\"post\", post)\n\tview.AddKey(\"authors\", authors)\n\treturn view.Render()\n}", "func (n *OpenBazaarNode) GeneratePostSlug(status string) (string, error) {\n\tstatus = strings.Replace(status, \"/\", \"\", -1)\n\tcounter := 1\n\tslugBase := createSlugFor(status)\n\tslugToTry := slugBase\n\tfor {\n\t\t_, err := n.GetPostFromSlug(slugToTry)\n\t\tif os.IsNotExist(err) {\n\t\t\treturn slugToTry, nil\n\t\t} else if err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tslugToTry = slugBase + strconv.Itoa(counter)\n\t\tcounter++\n\t}\n}", "func ShowPosting(ctx *gin.Context) {\n\tvar posting []models.PostItem\n\terr := models.DB.Find(&posting).Error\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, map[string] interface{}{\n\t\t\t\"status\": http.StatusInternalServerError,\n\t\t\t\"message\": \"Gagal\",\n\t\t})\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, map[string] interface{}{\n\t\t\"status\": http.StatusOK,\n\t\t\"data\": posting,\n\t})\n}", "func (prc *PipelineRunsController) Show(c *gin.Context) {\n\tpipelineRun := pipeline.Run{}\n\terr := pipelineRun.SetID(c.Param(\"runID\"))\n\tif err != nil {\n\t\tjsonAPIError(c, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\tpipelineRun, err = prc.App.PipelineORM().FindRun(pipelineRun.ID)\n\tif err != nil {\n\t\tjsonAPIError(c, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tres := presenters.NewPipelineRunResource(pipelineRun, prc.App.GetLogger())\n\tjsonAPIResponse(c, res, \"pipelineRun\")\n}", "func (n *OpenBazaarNode) GetPostFromSlug(slug string) (*pb.SignedPost, error) {\n\t// Read post file\n\tpostPath := path.Join(n.RepoPath, \"root\", \"posts\", slug+\".json\")\n\tfile, err := ioutil.ReadFile(postPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Unmarshal post\n\tsl := new(pb.SignedPost)\n\terr = jsonpb.UnmarshalString(string(file), sl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn sl, nil\n}", "func (c *Client) StackBySlug(slug string) (Stack, error) {\n\tstack := Stack{}\n\terr := c.request(\"GET\", fmt.Sprintf(\"/api/instances/%s\", slug), nil, nil, &stack)\n\n\tif err != nil {\n\t\treturn stack, err\n\t}\n\n\treturn stack, err\n}", "func (r *PostingBot) Post(p *reddit.Post) error {\n\tswitch {\n\tcase p.NSFW:\n\t\t// We hide NSFW content\n\t\tmsg := tgbotapi.NewMessage(r.Config.ChatID, fmt.Sprintf(\"Uh oh, nsfw content! 🔞\\n%s\", p.URL))\n\t\tmsg.DisableWebPagePreview = true\n\t\tmsg.ReplyMarkup = utility.SetupInlineKeyboard(p.Subreddit, p.Permalink)\n\t\tr.TBot.Send(msg)\n\tcase p.Media.RedditVideo.IsGIF:\n\t\tmsg := tgbotapi.NewDocumentUpload(r.Config.ChatID, p.URL)\n\t\tmsg.ReplyMarkup = utility.SetupInlineKeyboard(p.Subreddit, p.Permalink)\n\t\tr.TBot.Send(msg)\n\tcase strings.Contains(p.URL, \".jpg\") || strings.Contains(p.URL, \".png\"):\n\t\tmsg := tgbotapi.NewPhotoUpload(r.Config.ChatID, \"\")\n\t\tmsg.FileID = p.URL\n\t\tmsg.UseExisting = true\n\t\tmsg.ReplyMarkup = utility.SetupInlineKeyboard(p.Subreddit, p.Permalink)\n\t\tr.TBot.Send(msg)\n\tdefault:\n\t\tif r.Config.VideoDownload {\n\t\t\tfileName, err := video.GetVideo(p.URL)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t\tvideoPath := r.Config.DownloadPath + fileName\n\n\t\t\tmsg := tgbotapi.NewVideoUpload(r.Config.ChatID, videoPath)\n\t\t\tmsg.ReplyMarkup = utility.SetupInlineKeyboard(p.Subreddit, p.Permalink)\n\n\t\t\tr.TBot.Send(msg)\n\t\t\tos.Remove(videoPath)\n\t\t} else {\n\t\t\tmsg := tgbotapi.NewMessage(r.Config.ChatID, p.URL)\n\t\t\tr.TBot.Send(msg)\n\t\t}\n\t}\n\treturn nil\n}", "func (p *Post) GetPostBySlug(slug string) error {\n\terr := postSession.Clone().DB(DBName).C(\"posts\").Find(bson.M{\"slug\": slug}).One(p)\n\treturn err\n}", "func (upu *UnsavedPostUpdate) ClearSlug() *UnsavedPostUpdate {\n\tupu.mutation.ClearSlug()\n\treturn upu\n}", "func (ec EntryController) GetEntryBySlug(w http.ResponseWriter, r *http.Request) {\n\tslug := r.FormValue(\"slug\")\n\n\tvar entry models.Entry\n\n\tvar filter = bson.M{\"$and\": bson.A{\n\t\tbson.M{\"deleted\": bson.M{\"$ne\": true}},\n\t\tbson.M{\"slug\": slug},\n\t},\n\t}\n\n\terr := ec.coll.FindOne(context.Background(), filter).Decode(&entry)\n\n\tif err != nil {\n\t\tshared.FError(w, http.StatusBadRequest, \"Invalid slug\")\n\t\treturn\n\t}\n\n\tshared.FResponse(w, http.StatusOK, entry)\n}", "func (h *ShortenerHandler) Find(w http.ResponseWriter, r *http.Request) {\n\tshortURLParam := chi.URLParam(r, \"shortURL\")\n\turl, err := h.url.Find(shortURLParam)\n\tif err != nil {\n\t\trender.Render(w, r, sendNotFoundResponse(err.Error()))\n\t\treturn\n\t}\n\n\terr = render.Render(w, r, object.CreateURLResponse(url))\n\tif err != nil {\n\t\trender.Render(w, r, sendInternalServerErrorResponse(err.Error()))\n\t\treturn\n\t}\n}", "func (s StoryRepository) FindBySlug(slug string) (story chronicle.Story, err error) {\n\tdefer func() {\n\t\tif err != nil && err != sql.ErrNoRows {\n\t\t\terr = errors.Wrap(err, function.GetFunctionName(s.FindBySlug))\n\t\t}\n\t}()\n\n\tstory = chronicle.Story{}\n\tquery := `SELECT\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\ttitle, \n\t\t\t\t\t\t\tslug, \n\t\t\t\t\t\t\texcerpt, \n\t\t\t\t\t\t\tcontent,\n\t\t\t\t\t\t\treporter,\n\t\t\t\t\t\t\teditor,\n\t\t\t\t\t\t\tauthor,\n\t\t\t\t\t\t\tstatus,\n\t\t\t\t\t\t\tmedia, \n\t\t\t\t\t\t\tlikes,\n\t\t\t\t\t\t\tshares,\n\t\t\t\t\t\t\tviews,\n\t\t\t\t\t\t\tcreatedAt, \n\t\t\t\t\t\t\tupdatedAt\n\t\t\t\t\t\tFROM stories \n\t\t\t\t\t\tWHERE slug=$1`\n\n\terr = s.db.Get(&story, query, slug)\n\tif err != nil {\n\t\treturn chronicle.Story{}, err\n\t}\n\n\t// fill s.getTopicsForStory(story.ID)\n\tstory.Topics, err = s.getTopicsForStory(story.ID)\n\tif err != nil {\n\t\treturn chronicle.Story{}, err\n\t}\n\n\treturn story, err\n}", "func DashboardPostPut(r render.Render, db *gorm.DB, s sessions.Session, req *http.Request, args martini.Params) {\n\tuser, ok := checkSession(s, db)\n\tif ok == false {\n\t\tr.JSON(403, map[string]string{\"error\": \"not logged in\"})\n\t\treturn\n\t}\n\n\tid, err := strconv.Atoi(req.FormValue(\"id\"))\n\tif err != nil {\n\t\tr.JSON(400, map[string]string{\"error\": \"invalid id\"})\n\t\treturn\n\t}\n\ttitle := req.FormValue(\"title\")\n\tcontent := req.FormValue(\"content\")\n\n\tif id > 0 {\n\t\tvar post wpdb.Post\n\t\tdb.Where(\"ID=?\", id).Find(&post)\n\t\tif post.Id == 0 {\n\t\t\tr.JSON(400, map[string]string{\"error\": \"post not found\"})\n\t\t\treturn\n\t\t}\n\n\t\t// TO DO: Revisioning stuff for last edited by\n\t\tpost.Title = title\n\t\tpost.Content = content\n\t\tdb.Save(&post)\n\t\treturn\n\t}\n\n\tpost := wpdb.Post{\n\t\tUserId: user.Id,\n\t\tPostDate: time.Now().Format(\"2006-01-02 15:04:05\"),\n\t\tContent: content,\n\t\tTitle: title,\n\t\tName: strings.ToLower(strings.Replace(title, \" \", \"-\", -1)),\n\t}\n\n\tdb.Save(&post)\n\tr.JSON(200, map[string]int64{\"postid\": post.Id})\n}", "func (app *application) showSnippet(w http.ResponseWriter, r *http.Request) {\n\t// Extract the value of the id parameter from the query string and try to convert it to an integer using the strconv.Atoi() function. If it can't be converted to an integer, or the value is less than 1, we return a 404 page not found response.\n\tid, err := strconv.Atoi(r.URL.Query().Get(\"id\"))\n\tif err != nil || id < 1 {\n\t\tapp.notFound(w) // use the notFound() helper\n\t\treturn\n\t}\n\t// Use the fmt.Fprintf() function to interpolate the id value with our response and write it to the http.ResponseWriter.\n\tfmt.Fprintf(w, \"Display a specific snippet with ID %d...\", id)\n}", "func (h *FriendlyHost) Display() string {\n\treturn svchost.ForDisplay(h.Raw)\n}", "func (p *Post) GetURL() string {\n\trgx, _ := regexp.Compile(\"[^A-Za-z\\\\-]\")\n\tslugged := rgx.ReplaceAllString(p.Slug, \"\")\n\treturn p.Resolver.Post(strings.ToLower(slugged))\n}", "func Show(c *gin.Context) {\r\n\tpost := getById(c)\r\n\tc.JSON(http.StatusOK, gin.H{\r\n\t\t\"messege\": \"\",\r\n\t\t\"data\": post,\r\n\t})\r\n}", "func (cmd *ShowHeroCommand) Run(c *client.Client, args []string) error {\n\tvar path string\n\tif len(args) > 0 {\n\t\tpath = args[0]\n\t} else {\n\t\tpath = fmt.Sprintf(\"/heroes/%v\", cmd.HeroID)\n\t}\n\tlogger := goa.NewLogger(log.New(os.Stderr, \"\", log.LstdFlags))\n\tctx := goa.WithLogger(context.Background(), logger)\n\tresp, err := c.ShowHero(ctx, path)\n\tif err != nil {\n\t\tgoa.LogError(ctx, \"failed\", \"err\", err)\n\t\treturn err\n\t}\n\n\tgoaclient.HandleResponse(c.Client, resp, cmd.PrettyPrint)\n\treturn nil\n}", "func (o *KanbanViewView) GetSlugOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Slug, true\n}", "func GetShowFeed(c echo.Context) error {\n\tshowUUID := c.Param(\"uuid\")\n\n\ttype tpl struct {\n\t\tBaseURL string\n\t\tShow *core.Show\n\t}\n\tvar err error\n\tvar data = tpl{\n\t\tBaseURL: viper.GetString(\"baseurl\"),\n\t}\n\n\t// get feed\n\tshow, found, err := core.GetShowByUUID(showUUID)\n\tif err != nil {\n\t\tlogger.Log.Error(fmt.Sprintf(\"%s - GetShowFeed -> core.GetShowByUUID(%s) - %s \", c.Request().RemoteAddr, showUUID, err))\n\t\treturn c.NoContent(http.StatusInternalServerError)\n\t}\n\tif !found {\n\t\treturn c.String(http.StatusNotFound, \"show not found\")\n\t}\n\n\t// if locked or not sync\n\tif show.Locked || show.Task == \"firstsync\" {\n\t\treturn c.String(http.StatusNotFound, \"show locked or not synched yet\")\n\t}\n\n\t// get episodes\n\tshow.Episodes, err = show.GetEpisodes()\n\tif err != nil {\n\t\tlogger.Log.Error(fmt.Sprintf(\"%s - GetShowFeed -> show.GetEpisodes - %s \", c.Request().RemoteAddr, err))\n\t\treturn c.NoContent(http.StatusInternalServerError)\n\t}\n\n\t// Enclosures\n\tfor i, ep := range show.Episodes {\n\t\tshow.Episodes[i].Enclosure, _, err = ep.GetEnclosure()\n\t\tif err != nil {\n\t\t\tlogger.Log.Error(fmt.Sprintf(\"%s - GetShowFeed -> ep.GetEnclosure() - %s \", c.Request().RemoteAddr, err))\n\t\t\treturn c.NoContent(http.StatusInternalServerError)\n\t\t}\n\n\t\t// Enclosure URL must be http and not https (WTF !!!)\n\t\tif strings.HasPrefix(show.Episodes[i].Enclosure.URL, \"https://\") {\n\t\t\tshow.Episodes[i].Enclosure.URL = \"http://\" + show.Episodes[i].Enclosure.URL[8:]\n\t\t}\n\t}\n\n\t// Episode Image\n\tfor i, ep := range show.Episodes {\n\t\tshow.Episodes[i].Image, _, err = ep.GetImage()\n\t\tif err != nil {\n\t\t\tlogger.Log.Error(fmt.Sprintf(\"%s - GetShowFeed -> ep.GetImage() - %s \", c.Request().RemoteAddr, err))\n\t\t\treturn c.NoContent(http.StatusInternalServerError)\n\t\t}\n\t}\n\n\t// Show Image\n\tshow.Image, _, err = show.GetImage()\n\tif err != nil {\n\t\tlogger.Log.Error(fmt.Sprintf(\"%s - GetShowFeed -> show.GetImage - %s \", c.Request().RemoteAddr, err))\n\t\treturn c.NoContent(http.StatusInternalServerError)\n\t}\n\n\tdata.Show = &show\n\n\t// load template\n\ttplF, err := template.ParseFiles(path.Join(viper.GetString(\"rootPath\"), \"etc/tpl/showfeed.rss\"))\n\tif err != nil {\n\t\tlogger.Log.Error(fmt.Sprintf(\"%s - GetShowFeed -> template.ParseFiles - %s \", c.Request().RemoteAddr, err))\n\t\treturn c.NoContent(http.StatusInternalServerError)\n\t}\n\n\tbuf := bytes.Buffer{}\n\tif err = tplF.Execute(&buf, data); err != nil {\n\t\tlogger.Log.Error(fmt.Sprintf(\"%s - GetShowFeed -> mailTpl.Execute - %s \", c.Request().RemoteAddr, err))\n\t\treturn c.NoContent(http.StatusInternalServerError)\n\t}\n\treturn c.XMLBlob(http.StatusOK, buf.Bytes())\n}", "func (upuo *UnsavedPostUpdateOne) ClearSlug() *UnsavedPostUpdateOne {\n\tupuo.mutation.ClearSlug()\n\treturn upuo\n}", "func (c *GetUserPostClosestController) Post() {\n\tc.EnableXSRF = false\n\n\tcookiekey := beego.AppConfig.String(\"passid\")\n\n\t//get from cache\n\tpassId, _ := c.GetSecureCookie(cookiekey, \"passid\")\n\tif len(passId) <= 0 {\n\t\tpassId = c.GetString(\"passid\", \"\")\n\t\tif len(passId) < 1{\n\t\t\toutput, _ := library.ReturnJsonWithError(library.GetUserFail, \"ref\", nil)\n\t\t\tc.Ctx.WriteString(output)\n\t\t\treturn\n\t\t}\n\t}\n\tcahchedUser, err := models.GetUserFromCache(passId, true)\n\tif err != nil {\n\t\toutput, _ := library.ReturnJsonWithError(library.GetUserFail, \"ref\", err.Error())\n\t\tc.Ctx.WriteString(output)\n\t\treturn\n\t}\n\tuid := cahchedUser.UserProfile.Id\n\n\toption := c.GetString(\"option\")\n\tvar isNext bool = false\n\tif option == \"next\"{\n\t\tisNext = true\n\t}\n\tdate := c.GetString(\"date\")\n\tdateCorrect := strings.Replace(date, \"/\", \"\", -1)\n\tintDate ,_ := strconv.Atoi(dateCorrect)\n\tvar newPostDb = models.NewPost()\n\t//var getUser = newUser.GetUserProfile()\n\t//logs.Warning(getUser)\n\tpostList, err := newPostDb.GetUserClosestPost(uid, intDate, isNext)\n\n\tvar output string\n\n\tif err != nil{\n\t\toutput, _ = library.ReturnJsonWithError(library.CodeErrCommen, err.Error(), nil)\n\n\t}else {\n\t\toutput, _ = library.ReturnJsonWithError(library.CodeSucc, \"ref\", postList)\n\t}\n\n\tc.Ctx.WriteString(output)\n}", "func (i Internet) Slug() string {\n\tslug := strings.Repeat(\"?\", i.Faker.IntBetween(1, 5)) +\n\t\t\"-\" +\n\t\tstrings.Repeat(\"?\", i.Faker.IntBetween(1, 6))\n\n\treturn strings.ToLower(i.Faker.Lexify(slug))\n}", "func (app *application) showSnippet(w http.ResponseWriter, r *http.Request) {\n\tid, err := strconv.Atoi(r.URL.Query().Get(\"id\"))\n\tif err != nil || id < 1 {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\t// Use the fmt.Fprintf() function to interpolate the id value with our response\n\t// and write it to the http.ResponseWriter.\n\tfmt.Fprintf(w, \"Display a specific snippet with ID %d...\", id)\n}", "func (o *KanbanViewView) SetSlug(v string) {\n\to.Slug = v\n}", "func (f *FactTypeFilter) WhereSlug(p entql.StringP) {\n\tf.Where(p.Field(facttype.FieldSlug))\n}", "func GetPost(idString string, w http.ResponseWriter) {\r\n\tfmt.Println(\"inside GetPost\")\r\n\t//Connect Mongodb\r\n\tclient, err := mongo.NewClient(options.Client().ApplyURI(\"mongodb://127.0.0.1:27017\"))\r\n\tif err != nil {\r\n\t\tlog.Fatal(err)\r\n\t}\r\n\tctx, _ := context.WithTimeout(context.Background(), 10*time.Second)\r\n\terr = client.Connect(ctx)\r\n\tif err != nil {\r\n\t\tlog.Fatal(err)\r\n\t}\r\n\tdefer client.Disconnect(ctx)\r\n\r\n\t//Post Inside Database\r\n\tcollection := client.Database(\"inShotsDB\").Collection(\"posts\")\r\n\tid, err := primitive.ObjectIDFromHex(idString)\r\n\tfilter := bson.M{\"_id\": id}\r\n\tvar post Article\r\n\terr2 := collection.FindOne(context.TODO(), filter).Decode(&post)\r\n\tif err2 != nil {\r\n\t\tlog.Fatal(err2)\r\n\t}\r\n\tfmt.Println(\"Found Post\", post.Title)\r\n\tfmt.Fprintf(w, post.Title, post.Subtitle, post.Content)\r\n}", "func (n *OpenBazaarNode) DeletePost(slug string) error {\n\ttoDelete := path.Join(n.RepoPath, \"root\", \"posts\", slug+\".json\")\n\terr := os.Remove(toDelete)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar index []postData\n\tindexPath := path.Join(n.RepoPath, \"root\", \"posts.json\")\n\t_, ferr := os.Stat(indexPath)\n\tif !os.IsNotExist(ferr) {\n\t\t// Read existing file\n\t\tfile, err := ioutil.ReadFile(indexPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = json.Unmarshal(file, &index)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Check to see if the slug exists in the list. If so delete it.\n\tfor i, d := range index {\n\t\tif d.Slug != slug {\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(index) == 1 {\n\t\t\tindex = []postData{}\n\t\t\tbreak\n\t\t}\n\t\tindex = append(index[:i], index[i+1:]...)\n\t}\n\n\t// Write the index back to file\n\tf, err := os.Create(indexPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tj, jerr := json.MarshalIndent(index, \"\", \" \")\n\tif jerr != nil {\n\t\treturn jerr\n\t}\n\t_, werr := f.Write(j)\n\tif werr != nil {\n\t\treturn werr\n\t}\n\n\treturn n.updateProfileCounts()\n}", "func (q *BaseQuestion) Do(key string) error {\n\ttitleSlug := key\n\n\t// try to parse id\n\tif q.Problems.Do() == nil {\n\t\tif s := q.Problems.StatStatus(key); s != nil {\n\t\t\ttitleSlug = s.Stat.QuestionTitleSlug\n\t\t}\n\t}\n\n\t// parse title slug\n\tbody := strings.NewReader(fmt.Sprintf(`{\"operationName\":\"getQuestionDetail\",\"variables\":{\"titleSlug\":\"%s\"},\"query\":\"query getQuestionDetail($titleSlug: String!) {\\n isCurrentUserAuthenticated\\n question(titleSlug: $titleSlug) {\\n questionId\\n questionFrontendId\\n questionTitle\\n translatedTitle\\n questionTitleSlug\\n content\\n translatedContent\\n difficulty\\n stats\\n allowDiscuss\\n contributors {\\n username\\n profileUrl\\n __typename\\n }\\n similarQuestions\\n mysqlSchemas\\n randomQuestionUrl\\n sessionId\\n categoryTitle\\n submitUrl\\n interpretUrl\\n codeDefinition\\n sampleTestCase\\n enableTestMode\\n metaData\\n langToValidPlayground\\n enableRunCode\\n enableSubmit\\n judgerAvailable\\n infoVerified\\n envInfo\\n urlManager\\n article\\n questionDetailUrl\\n libraryUrl\\n companyTags {\\n name\\n slug\\n translatedName\\n __typename\\n }\\n companyTagStats\\n topicTags {\\n name\\n slug\\n translatedName\\n __typename\\n }\\n __typename\\n }\\n interviewed {\\n interviewedUrl\\n companies {\\n id\\n name\\n slug\\n __typename\\n }\\n timeOptions {\\n id\\n name\\n __typename\\n }\\n stageOptions {\\n id\\n name\\n __typename\\n }\\n __typename\\n }\\n subscribeUrl\\n isPremium\\n loginUrl\\n}\\n\"}`, titleSlug))\n\treq, err := http.NewRequest(\"POST\", \"https://leetcode.com/graphql\", body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tq.Referer = fmt.Sprintf(\n\t\t\"https://leetcode.com/problems/%s/description/\",\n\t\ttitleSlug,\n\t)\n\treq.Header.Set(\"x-csrftoken\", guestToken)\n\treq.Header.Set(\"content-type\", \"application/json\")\n\treq.Header.Set(\"cache-control\", \"no-cache\")\n\treq.Header.Set(\"referer\", q.Referer)\n\tclient := &http.Client{\n\t\tTimeout: time.Second * 15,\n\t}\n\treq.AddCookie(&http.Cookie{\n\t\tName: \"csrftoken\",\n\t\tValue: guestToken,\n\t\tPath: \"/\",\n\t\tDomain: \".leetcode.com\",\n\t\tSecure: true,\n\t\tExpires: time.Now(),\n\t})\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tif err = json.Unmarshal(data, &Response{\n\t\tData: ResponseData{\n\t\t\tQuestion: q,\n\t\t},\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\ts, err := strconv.Unquote(strconv.Quote(q.CodeDefinition))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = json.Unmarshal([]byte(s), &q.Codes); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o IntegrationEmailsOnPushOutput) Slug() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *IntegrationEmailsOnPush) pulumi.StringOutput { return v.Slug }).(pulumi.StringOutput)\n}", "func (fn GetAPIV1PostsPublicPostIDHandlerFunc) Handle(params GetAPIV1PostsPublicPostIDParams) middleware.Responder {\n\treturn fn(params)\n}", "func Show(tag string, conn Connection) []show.Show {\n\tvar shows []show.Show\n\tt, err := newTag(tag, conn)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to get tag %s: %s\", tag, err)\n\t}\n\tmovies := t.Movies(conn)\n\tfor _, movie := range movies {\n\t\tvar show show.Show\n\t\tshow.Directory = movie.Path\n\t\tshow.Title = movie.Title\n\t\tshows = append(shows, show)\n\t}\n\treturn shows\n}", "func (repo *Posts) Post(id graphql.ID) *models.Post {\n\treturn repo.posts[id]\n}", "func (b ExcuseBot) Run(c *Command) string {\n\tdoc, err := goquery.NewDocument(\"http://developerexcuses.com/\")\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\treturn doc.Find(\".wrapper center a\").First().Text()\n}", "func (c *PostThumbnailClient) QueryPost(pt *PostThumbnail) *PostQuery {\n\tquery := &PostQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := pt.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(postthumbnail.Table, postthumbnail.FieldID, id),\n\t\t\tsqlgraph.To(post.Table, post.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2O, true, postthumbnail.PostTable, postthumbnail.PostColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(pt.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func (sh *Handler) doPost(ctx *fasthttp.RequestCtx) {\n\tfullURL := ctx.PostBody()\n\tif len(fullURL) == 0 {\n\t\tctx.Error(\"Body is empty\", fasthttp.StatusBadRequest)\n\t}\n\tshort, err := sh.storage.Save(fullURL)\n\tif err != nil {\n\t\tctx.Error(err.Error(), fasthttp.StatusInternalServerError)\n\t}\n\tfmt.Fprintf(ctx, \"Short url: %s/%s\", ctx.Host(), short)\n\treturn\n}", "func (s *Service) HandleShow(w http.ResponseWriter, r *http.Request) {\n\tsubs, err := s.subscriptionRepository.FindOne(\n\t\tr.Context(), s.getResourceID(r), s.getSubscriptionID(r),\n\t)\n\tif err != nil {\n\t\tstatus := http.StatusInternalServerError\n\t\tif errRepo, ok := err.(flare.SubscriptionRepositoryError); ok && errRepo.NotFound() {\n\t\t\tstatus = http.StatusNotFound\n\t\t}\n\n\t\ts.writer.Error(w, \"error during subscription search\", err, status)\n\t\treturn\n\t}\n\n\ts.writer.Response(w, transformSubscription(subs), http.StatusOK, nil)\n}", "func (bot *Bot) doPost() error {\n\tvar comic *Comic\n\n\tcomic, err := bot.getComic()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"Image URL: %s\\nPermalink: %s\\nTime: %s\\n\", comic.ComicURL, comic.Permalink, time.Now().Format(time.RFC3339))\n\n\terr = bot.postComic(comic)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Success\")\n\treturn nil\n}", "func (d *Deogracias) Post(p *reddit.Post) error {\n\terr := d.bot.Reply(p.Name, d.getPostQuote())\n\tif err != nil {\n\t\tlog.Println(errors.WithStack(errors.Errorf(\"failed to make post reply: %v\", err)))\n\t}\n\treturn nil\n}", "func (handler *Handler) handlePostGet(w http.ResponseWriter, r *http.Request) {\n\t// We get the id in url and parse it as uint type\n\tvars := mux.Vars(r)\n\tid := vars[\"id\"]\n\ti, err := strconv.ParseUint(id, 10, 64)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tdb := repository.NewPostRepository(handler.DB)\n\n\t// We try to find the post with given id\n\tpost, err := db.FindById(uint(i))\n\tif err != nil {\n\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\tresponses.ERROR(w, http.StatusNotFound, errors.New(\"the post with id \" + id + \" could not found\"))\n\t\t} else {\n\t\t\t// If method is failed for another reason than \"record not found\"\n\t\t\t// We don't want to share that reason with user\n\t\t\t// Instead we send a generic error to the user\n\t\t\t// and print the actual error to the console\n\t\t\tresponses.ERROR(w, http.StatusInternalServerError, errors.New(\"something went wrong\"))\n\t\t\tlog.Println(err)\n\t\t}\n\t\treturn\n\t}\n\n\t// If post is not published only the author can access it.\n\tif post.IsPublished == false {\n\t\tuid, err := auth.ExtractTokenID(r)\n\t\tif err != nil {\n\t\t\t// If the requester not authenticated we pretend like post is not exist\n\t\t\t// for protection against data leak.\n\t\t\tresponses.ERROR(w, http.StatusNotFound, errors.New(\"the post with id \" + id + \" could not found\"))\n\t\t\treturn\n\t\t}\n\n\t\tif uid != post.Author.ID {\n\t\t\tresponses.ERROR(w, http.StatusNotFound, errors.New(\"the post with id \" + id + \" could not found\"))\n\t\t\treturn\n\t\t}\n\t}\n\n\tresponses.JSON(w, http.StatusOK, post)\n}", "func Show(w http.ResponseWriter, r *http.Request) {\n\tc := flight.Context(w, r)\n\n\tarticle, _, err := article.ByID(c.DB, c.Param(\"id\"), c.UserID)\n\tif err != nil {\n\t\tc.FlashErrorGeneric(err)\n\t\tc.Redirect(uri)\n\t\treturn\n\t}\n\n\tv := c.View.New(\"article/show\")\n\tv.Vars[\"article\"] = article\n\tv.Render(w, r)\n}", "func Show(w http.ResponseWriter, request *http.Request, p httprouter.Params) {\n\n\t// //get the user and assign to User UP struct\n\t// err := m.GetUserbyUUID(\"kRtrima\", w, request)\n\t// if err != nil {\n\t// \tLogger.Println(\"Not able to find the user by UUID!!\")\n\t// \thttp.Redirect(w, request, \"/login\", 401)\n\t// \treturn\n\t// }\n\n\tvar thread m.Thread\n\n\tdocit, err := m.ToDocID(p.ByName(\"id\"))\n\tif err != nil {\n\t\tLogger.Println(\"Not able to get the docid\")\n\t\thttp.Redirect(w, request, \"/Dashboard\", 302)\n\t\treturn\n\t}\n\n\t//get the thread and assign to Thread TP struct\n\terr = m.Threads.Find(\"_id\", docit, &thread)\n\tif err != nil {\n\t\tLogger.Println(\"Not able to Find the thread by ID!!\")\n\t\thttp.Redirect(w, request, \"/Dashboard\", 302)\n\t\treturn\n\t}\n\n\tvar up m.User\n\n\t//get the User and assign to User UP struct\n\terr = m.Users.Find(\"_id\", thread.User, &up)\n\tif err != nil {\n\t\tLogger.Println(\"Not able to Find the user by ID!!\")\n\t}\n\n\tvar cmt []m.Comment\n\n\t//get the comment and assign to Comment CP struct\n\terr = m.Comments.FindbyKeyValue(\"thread\", thread.ID, &cmt)\n\tif err != nil {\n\t\tLogger.Println(\"Not able to Find The Comments by ID!!\")\n\t}\n\n\t// get the list of mongo collections\n\tcoll, err := m.ShowCollectionNames(m.DB)\n\tif err != nil {\n\t\tLogger.Println(\"Not able to Get the list of Collection!!\")\n\t}\n\n\tdashlist := m.FindDetails{\n\t\tCollectionNames: coll,\n\t\tContentDetails: &thread,\n\t\tComments: cmt,\n\t\tUser: &up,\n\t}\n\n\tvar LIP m.LogInUser\n\n\terr = m.GetLogInUser(\"User\", &LIP, request)\n\tif err != nil {\n\t\tdashlist.LogInUser = nil\n\t\tLogger.Printf(\"Failed to get the login details %v\\n\", err)\n\t} else {\n\t\tdashlist.LogInUser = &LIP\n\t}\n\n\tgenerateHTML(w, &dashlist, \"Layout\", \"ThreadLeftSideBar\", \"ThreadTopSideBar\", \"ThreadModal\", \"ThreadShowContent\")\n}", "func (c *TaskContext) TaskSlug() string {\n\treturn c.Task.Slug\n}", "func (o ServiceEmailsOnPushOutput) Slug() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ServiceEmailsOnPush) pulumi.StringOutput { return v.Slug }).(pulumi.StringOutput)\n}", "func ValidateSlug(fl v.FieldLevel) bool {\n\tm, _ := regexp.MatchString(\"^[a-z0-9]+[a-z0-9-]+[a-z0-9]+$\", fl.Field().String())\n\treturn m\n}", "func (prc *PipelineRunsController) Show(c *gin.Context) {\n\tpipelineRun := pipeline.Run{}\n\terr := pipelineRun.SetID(c.Param(\"runID\"))\n\tif err != nil {\n\t\tjsonAPIError(c, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\terr = preloadPipelineRunDependencies(prc.App.GetStore().DB).\n\t\tWhere(\"pipeline_runs.id = ?\", pipelineRun.ID).\n\t\tFirst(&pipelineRun).Error\n\n\tif err != nil {\n\t\tjsonAPIError(c, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tjsonAPIResponse(c, pipelineRun, \"offChainReportingPipelineRun\")\n}", "func (c *Command) commandViewPostID(postID string, bmarks *bookmarks.Bookmarks) (string, error) {\n\tpostID = utils.GetPostIDFromLink(postID)\n\n\tvar bmark *bookmarks.Bookmark\n\tbmark, err := bmarks.GetBookmark(postID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar labelNames []string\n\tlabelNames, err = bmarks.GetBmarkLabelNames(bmark)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar text string\n\ttext, err = bmarks.GetBmarkTextDetailed(bmark, labelNames, c.Args)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"Unable to get bookmark text\")\n\t}\n\treturn text, nil\n}", "func (o *GridViewUpdate) SetSlug(v string) {\n\to.Slug = v\n}", "func (o *GridViewUpdate) GetSlug() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Slug\n}", "func (u *App) Create(c echo.Context, req *Create) (*model.Post, error) {\n\tid, err := util.GenerateUUID()\n\tif err = zaplog.ZLog(err); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar operator model.User\n\tif err = u.db.Model(&model.User{}).Where(\"uuid = ?\", req.Author).First(&operator).Error; err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar dupe model.Post\n\tif err = u.db.Model(&model.Post{}).Where(\"slug = ?\", req.Slug).Order(\"id DESC\").First(&dupe).Error; err == nil {\n\t\tfragment := strings.TrimPrefix(dupe.Slug, req.Slug)\n\t\tif fragment == \"\" {\n\t\t\treq.Slug += \"-2\"\n\t\t}\n\n\t\tcounter, err := strconv.Atoi(strings.TrimPrefix(fragment, \"-\"))\n\t\tif err != nil {\n\t\t\treq.Slug += \"-2\"\n\t\t} else {\n\t\t\treq.Slug += fmt.Sprintf(\"-%d\", counter+1)\n\t\t}\n\t}\n\n\tif len(req.Excerpt) > 255 {\n\t\treq.Excerpt = req.Excerpt[:250] + \"...\"\n\t}\n\n\tpost := model.Post{\n\t\tBase: model.Base{ID: id},\n\t\tAuthor: req.Author,\n\t\tAuthorName: operator.Name,\n\t\tCategory: req.Category,\n\t\tTags: req.Tags,\n\t\tTitle: req.Title,\n\t\tSlug: req.Slug,\n\t\tContent: req.Content,\n\t\tExcerpt: req.Excerpt,\n\t\tStatus: req.Status,\n\t}\n\treturn u.udb.Create(u.db, post)\n}", "func Publish() error {\n\treturn sh.RunV(\"sh\", \"publish.sh\");\n}", "func (t *Team) GetSlug() string {\n\tif t == nil || t.Slug == nil {\n\t\treturn \"\"\n\t}\n\treturn *t.Slug\n}", "func (r *searchBot) Post(p *reddit.Post) error {\n\tif strings.Contains(p.SelfText, r.searchText) {\n\t\t<-time.After(2 * time.Second) // Buffer\n\t\tpost := datamanager.PostMessage{URL: p.URL, Text: p.SelfText}\n\t\tmsg, err := json.Marshal(post)\n\t\tif err != nil {\n\t\t\tlogger.Error(fmt.Sprintf(\"Error converting to JSON for Reddit post %s\", p.URL))\n\t\t}\n\t\tpubErr := r.distClient.Channel.Publish(\n\t\t\tconfig.DefaultExchange(),\n\t\t\tr.distClient.Queue.Name,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t\tdistributed.PublishBody(msg),\n\t\t)\n\t\tif pubErr != nil {\n\t\t\tlogger.Error(fmt.Sprintf(\"Error publishing message to queue %s\", r.distClient.Queue.Name))\n\t\t}\n\t}\n\treturn nil\n}", "func (app *application) showSnippet(res http.ResponseWriter, req *http.Request) {\n\tid, err := strconv.Atoi(req.URL.Query().Get(\":id\"))\n\tif err != nil || id < 1 {\n\t\tapp.notFound(res)\n\t\treturn\n\t}\n\n\tsnippet, err := app.snippets.Get(id)\n\tif err != nil {\n\t\tapp.notFound(res)\n\t\treturn\n\t}\n\n\t//flash := app.session.PopString(req, \"flash\")\n\ttmplData := &Templates{Snippet: snippet}\n\n\tapp.render(res, req, \"show.page.html\", tmplData)\n}", "func HandleCreateShow(w http.ResponseWriter, r *http.Request) error {\n\n\tpage := pages.New()\n\n\t// Authorise\n\tuser := session.CurrentUser(w, r)\n\terr := can.Create(page, user)\n\tif err != nil {\n\t\treturn server.NotAuthorizedError(err)\n\t}\n\n\t// Fetch the users\n\tauthors, err := users.FindAll(users.Where(\"role=?\", users.Admin))\n\tif err != nil {\n\t\treturn server.InternalError(err)\n\t}\n\n\t// Render the template\n\tview := view.NewRenderer(w, r)\n\tview.AddKey(\"page\", page)\n\tview.AddKey(\"authors\", authors)\n\tview.AddKey(\"currentUser\", user)\n\treturn view.Render()\n}", "func (po *Post) String() string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(\"Post(\")\n\tbuilder.WriteString(fmt.Sprintf(\"id=%v, \", po.ID))\n\tbuilder.WriteString(\"create_time=\")\n\tbuilder.WriteString(po.CreateTime.Format(time.ANSIC))\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"update_time=\")\n\tbuilder.WriteString(po.UpdateTime.Format(time.ANSIC))\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"slug=\")\n\tbuilder.WriteString(po.Slug)\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"title=\")\n\tbuilder.WriteString(po.Title)\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"content=\")\n\tbuilder.WriteString(po.Content)\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"content_html=\")\n\tbuilder.WriteString(po.ContentHTML)\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"summary=\")\n\tbuilder.WriteString(po.Summary)\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"published_at=\")\n\tbuilder.WriteString(po.PublishedAt.Format(time.ANSIC))\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"view_count=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", po.ViewCount))\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"public=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", po.Public))\n\tbuilder.WriteByte(')')\n\treturn builder.String()\n}", "func getSlug(project string) (string, error) {\n\tif !ledger.IsGitProject(project) {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"Cannot add %s: not a git project\", project))\n\t}\n\tsession := sh.NewSession()\n\tsession.SetDir(project)\n\tout, err := session.Command(\"git\", \"remote\", \"show\", \"-n\", getRemote(project)).Command(\"grep\", \"Fetch\").Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\toutput := strings.TrimSpace(string(out))\n\treg := regexp.MustCompile(`[^/:]*/[^/:]*$`)\n\tres := reg.FindStringSubmatch(output)\n\treturn res[0], nil\n}", "func (c *EntryController) Show(ctx *app.ShowEntryContext) error {\n\tdto := storage.EntryDTO{\n\t\tContestID: ctx.Contest,\n\t\tContestSlug: ctx.ContestSlug,\n\t\tTaskID: ctx.Task,\n\t\tTaskSlug: ctx.TaskSlug,\n\t\tDTO: storage.DTO{\n\t\t\tPage: ctx.Page,\n\t\t\tPageSize: ctx.PageSize,\n\t\t\tOrder: strings.ToUpper(ctx.Sort),\n\t\t},\n\t}\n\n\tentries, err := c.entryRepo.FindBy(dto)\n\n\tres := app.ComJossemargtSaoEntryCollection{}\n\tif err != nil {\n\t\tif errors.Cause(sql.ErrNoRows) != nil {\n\t\t\treturn ctx.OK(res)\n\t\t}\n\n\t\treturn errors.Wrap(err, \"Un-expected error\")\n\t}\n\n\tfor _, entry := range entries {\n\t\tres = append(res, entryModelToMedia(&entry))\n\t}\n\n\treturn ctx.OK(res)\n}", "func (p *Post) Insert() error {\n\tif !PostChangeSlug(p.Slug) {\n\t\tp.Slug = generateNewSlug(p.Slug, 1)\n\t}\n\n\terr := postSession.Clone().DB(DBName).C(\"posts\").Insert(p)\n\n\treturn err\n}", "func (puo *PostUpdateOne) SetSlug(s string) *PostUpdateOne {\n\tpuo.mutation.SetSlug(s)\n\treturn puo\n}", "func (handler TopicHandler) Show(c *gin.Context) {\n\ttopic_id := c.Param(\"topic_id\")\n\ttopic := m.Topic{}\n\tquery := handler.db.Where(\"id = ?\",topic_id).First(&topic)\n\tif query.RowsAffected > 0 {\n\t\tc.JSON(http.StatusOK,topic)\n\t} else {\n\t\trespond(http.StatusBadRequest,\"Unable to find room\",c,true)\n\t}\n}", "func showIndex(c *gin.Context) {\n\trender(\n\t\tc,\n\t\tgin.H{\n\t\t\t\"title\": \"Home Page\",\n\t\t\t\"payload\": films,\n\t\t},\n\t\ttemplates.Index,\n\t)\n}", "func (cc *CleanupCommand) Execute(_ []string) error {\n\tlog.Printf(\"[INFO] cleanup for site %s\", cc.Site)\n\n\tposts, err := cc.postsInRange(cc.From, cc.To)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't get posts: %w\", err)\n\t}\n\tlog.Printf(\"[DEBUG] got %d posts\", len(posts))\n\n\ttotalComments, spamComments := 0, 0\n\tfor _, post := range posts {\n\t\tcomments, e := cc.listComments(post.URL)\n\t\tif e != nil {\n\t\t\tcontinue\n\t\t}\n\t\ttotalComments += len(comments)\n\n\t\tif cc.SetTitle {\n\t\t\tcc.procTitles(comments)\n\t\t} else {\n\t\t\tspamComments += cc.procSpam(comments)\n\t\t}\n\t}\n\n\tmsg := fmt.Sprintf(\"comments=%d, spam=%d\", totalComments, spamComments)\n\tif cc.SetTitle {\n\t\tmsg = fmt.Sprintf(\"comments=%d\", totalComments)\n\t}\n\n\tlog.Printf(\"[INFO] completed, %s\", msg)\n\treturn err\n}", "func Show(w http.ResponseWriter, r *http.Request) {\n\tc := flight.Context(w, r)\n\n\titem, _, err := summary.ByID(c.DB, c.Param(\"id\"))\n\tif err != nil {\n\t\tc.FlashErrorGeneric(err)\n\t\tc.Redirect(uri)\n\t\treturn\n\t}\n\n\tv := c.View.New(\"summary/show\")\n\tv.Vars[\"item\"] = item\n\tv.Render(w, r)\n}", "func (pu *PostUpdate) SetSlug(s string) *PostUpdate {\n\tpu.mutation.SetSlug(s)\n\treturn pu\n}", "func (d *Dao) Publish(c context.Context, arg *blocked.ArgPublishSearch) (ids []int64, pager *blocked.Pager, err error) {\n\treq := d.elastic.NewRequest(blocked.BusinessBlockedPublish).Index(blocked.TableBlockedPublish).Fields(\"id\")\n\tif arg.Keyword != blocked.SearchDefaultString {\n\t\treq.WhereLike([]string{\"title\", \"sub_title\"}, []string{arg.Keyword}, true, elastic.LikeLevelHigh)\n\t}\n\tif arg.Type != blocked.SearchDefaultNum {\n\t\treq.WhereEq(\"ptype\", arg.Type)\n\t}\n\treq.WhereRange(\"show_time\", arg.ShowFrom, arg.ShowTo, elastic.RangeScopeLcRc)\n\treq.WhereEq(\"status\", blocked.SearchDefaultStatus)\n\treq.Pn(arg.PN).Ps(arg.PS).Order(arg.Order, arg.Sort)\n\tvar res *search.ReSearchData\n\tif err = req.Scan(c, &res); err != nil {\n\t\terr = errors.Errorf(\"elastic search(%s) error(%v)\", req.Params(), err)\n\t\treturn\n\t}\n\tids, pager = pagerExtra(res)\n\treturn\n}", "func (c *BugProfileController) Show(ctx *app.ShowBugProfileContext) error {\n\t// BugProfileController_Show: start_implement\n\n\t// Put your logic here\n\n\t// BugProfileController_Show: end_implement\n\treturn nil\n}", "func (h *Handler) Handle() (string, error) {\n\tcmd, parameters, err := h.isValid()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\th.MattermostUserId = h.Args.UserId\n\tauth, err := h.IsAuthorizedAdmin(h.MattermostUserId)\n\tif err != nil {\n\t\treturn \"\", errors.WithMessage(err, \"Failed to get authorization. Please contact your system administrator.\\nFailure\")\n\t}\n\tif !auth {\n\t\treturn \"\", errors.New(\"You must be authorized to use the plugin. Please contact your system administrator.\")\n\t}\n\n\thandler := h.help\n\tswitch cmd {\n\tcase \"info\":\n\t\thandler = h.info\n\tcase \"connect\":\n\t\thandler = h.connect\n\tcase \"viewcal\":\n\t\thandler = h.viewCalendar\n\t}\n\tout, err := handler(parameters...)\n\tif err != nil {\n\t\treturn \"\", errors.WithMessagef(err, \"Command /%s %s failed\", config.CommandTrigger, cmd)\n\t}\n\n\treturn out, nil\n}", "func (h *Howdoi) Execute() {\n\tflag.Parse()\n\n\tif h.ShowHelp {\n\t\tfmt.Println(help)\n\t\tos.Exit(0)\n\t}\n\n\tif h.ShowVersion {\n\t\tfmt.Println(version)\n\t\tos.Exit(0)\n\t}\n\n\t// position must be > 0\n\tif h.Position == 0 {\n\t\th.Position = 1\n\t}\n\n\terr := h.sanitizeQuestion(flag.Args())\n\tif err != nil {\n\t\tfmt.Println(help)\n\t\tos.Exit(1)\n\t}\n\n\tlinks, err := h.getLinks()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tanswer, err := h.getAnswer(links)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(answer)\n}", "func (PeekCommandHandler) Handle(_ string, message, _ *client.Message) error {\n\n\t//\n\tnextPost, err := dbwrapper.GetNextPost()\n\tif err != nil {\n\t\t_, _ = api.SendPlainReplyText(message.ChatId, message.Id, l.GetString(l.COMMANDS_PEEK_NO_POST_FOUND))\n\t\treturn err\n\t}\n\n\t//\n\tcaption := nextPost.Caption\n\tif posting.GetChannelHandle() != \"\" && !strings.Contains(nextPost.Caption, \"@\"+posting.GetChannelHandle()) {\n\t\tcaption = fmt.Sprintf(\"%s\\n\\n@%s\", caption, posting.GetChannelHandle())\n\t}\n\n\tft, err := api.GetFormattedText(caption)\n\tif err != nil {\n\t\tft = &client.FormattedText{\n\t\t\tText: caption,\n\t\t\tEntities: nil,\n\t\t}\n\t}\n\n\t//\n\t_, err = api.ShareMedia(nextPost.Media.Type, message.ChatId, message.Id, nextPost.Media.FileID, ft.Text, ft.Entities)\n\treturn err\n\n}", "func (u *Usage) Show() error {\n\th := u.handler\n\tdefer h.cleanup()\n\n\tif err := h.setup([]api.Script{api.Usage}, []api.Script{}); err != nil {\n\t\treturn err\n\t}\n\n\treturn h.execute(api.Usage)\n}", "func (s *Service) ChangePost(ctx context.Context, draftID, companyID string, post *job.Posting) (string, error) {\n\tspan := s.tracer.MakeSpan(ctx, \"ChangePost\")\n\tdefer span.Finish()\n\n\t// // get userID\n\t// userID, err := s.authRPC.GetUserID(ctx)\n\t// if err != nil {\n\t// \ts.tracer.LogError(span, err)\n\t// \treturn \"\", err\n\t// }\n\n\terr := post.SetID(draftID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// check admin level\n\tallowed := s.checkAdminLevel(\n\t\tctx,\n\t\tcompanyID,\n\t\tcompanyadmin.AdminLevelAdmin,\n\t\tcompanyadmin.AdminLevelJob,\n\t)\n\tif !allowed {\n\t\treturn \"\", errors.New(\"not_allowed\")\n\t}\n\n\t// post.SetCompanyID(companyID)\n\t// post.SetUserID(userID)\n\t// // id := post.GenerateID()\n\t//\n\t// if !post.JobMetadata.Anonymous {\n\t// \tpost.CompanyDetails = &company.Details{\n\t// \t\t// TODO: company avatar, URL, Industry, subindustry\n\t// \t}\n\t// \tpost.CompanyDetails.SetCompanyID(companyID)\n\t// }\n\t//\n\t// now := time.Now()\n\t// post.CreatedAt = now\n\t// // post.ActivationDate = time.Date(\n\t// // \tint(post.JobDetails.PublishYear),\n\t// // \ttime.Month(int(post.JobDetails.PublishMonth)),\n\t// // \tint(post.JobDetails.PublishDay),\n\t// // \t0, 0, 0, 0, time.Now().Location(),\n\t// // )\n\t// post.ActivationDate = now //time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())\n\t//\n\t// // if post.ActivationDate.Before(post.CreatedAt) {\n\t// // \treturn \"\", errors.New(\"activation_date_can_not_be_in_past\")\n\t// // }\n\t//\n\t// post.Status = job.StatusActive //TODO: why it was Draft?\n\t// post.JobPriority = post.JobMetadata.JobPlan.GetPriority()\n\t//\n\t// if post.JobDetails.SalaryMin > 0 && post.JobDetails.SalaryInterval != \"\" {\n\t// \tpost.NormalizedSalaryMin = float32(post.JobDetails.SalaryMin) / float32(post.JobDetails.SalaryInterval.GetHours()) // TODO also convert currency\n\t// }\n\t//\n\t// if post.JobDetails.SalaryMax > 0 && post.JobDetails.SalaryInterval != \"\" {\n\t// \tpost.NormalizedSalaryMax = float32(post.JobDetails.SalaryMax) / float32(post.JobDetails.SalaryInterval.GetHours()) // TODO also convert currency\n\t// }\n\t//\n\t// // calc expire date\n\t// post.ExpirationDate = now.AddDate(0, 0, post.JobMetadata.JobPlan.GetDays())\n\n\terr = s.jobs.UpdateJobDetails(ctx, post)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn post.GetID(), nil\n}", "func (tb *TaskBuilder) Show() string {\n\treturn fmt.Sprintf(`SHOW TASKS LIKE '%v' IN DATABASE \"%v\"`, EscapeString(tb.name), EscapeString(tb.db))\n}", "func GetBlogPostBySlug(ctx context.Context, slug string) (*BlogPostVersion, error) {\n\tquery := datastore.NewQuery(blogPostVersionKind).\n\t\tFilter(\"Slug=\", slug).\n\t\tFilter(\"Published=\", true)\n\n\tvar post = new(BlogPostVersion)\n\tpostlist := query.Run(ctx)\n\t_, err := postlist.Next(post)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn post, nil\n}", "func (a *Add) Handle(app *base.Shorty, surl *base.ShortURL, params ...string) error {\n\tapp.Store.AddShortURL(surl)\n\treturn nil\n}", "func (c *DlaasPlugin) Run(context plugin.PluginContext, args []string) {\n\tui := terminal.NewStdUI()\n\n\tdefer func() {\n\t\tif l, ok := trace.Logger.(trace.Closer); ok {\n\t\t\tl.Close()\n\t\t}\n\t}()\n\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\texitCode, er := strconv.Atoi(fmt.Sprint(err))\n\t\t\tif er == nil {\n\t\t\t\tos.Exit(exitCode)\n\t\t\t}\n\n\t\t\t// FIXME QuietPanic does not exist\n\t\t\t//if err != terminal.QuietPanic {\n\t\t\t//\tfmt.Printf(\"%v\\n\", err)\n\t\t\t//}\n\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n\tactions := map[string]cli.ActionFunc{\n\t\tmetadata.ProjectInit: func(c *cli.Context) error {\n\t\t\treturn cmd.NewInitCmd(ui, context).Run(c)\n\t\t},\n\t\tmetadata.Train: func(c *cli.Context) error {\n\t\t\treturn cmd.NewTrainCmd(ui, context).Run(c)\n\t\t},\n\t\tmetadata.Show: func(c *cli.Context) error {\n\t\t\treturn cmd.NewShowCmd(ui, context).Run(c)\n\t\t},\n\t\tmetadata.Delete: func(c *cli.Context) error {\n\t\t\treturn cmd.NewDeleteCmd(ui, context).Run(c)\n\t\t},\n\t\tmetadata.List: func(c *cli.Context) error {\n\t\t\treturn cmd.NewListCmd(ui, context).Run(c)\n\t\t},\n\t\tmetadata.Download: func(c *cli.Context) error {\n\t\t\treturn cmd.NewDownloadCmd(ui, context).Run(c)\n\t\t},\n\t\tmetadata.Logs: func(c *cli.Context) error {\n\t\t\treturn cmd.NewLogsCmd(ui, context).Run(c)\n\t\t},\n\t\tmetadata.Loglines: func(c *cli.Context) error {\n\t\t\treturn cmd.NewLoglinesCmd(ui, context).Run(c)\n\t\t},\n\t\tmetadata.Emetrics: func(c *cli.Context) error {\n\t\t\treturn cmd.NewEmetricsCmd(ui, context).Run(c)\n\t\t},\n\t\tmetadata.Halt: func(c *cli.Context) error {\n\t\t\treturn cmd.NewHaltCmd(ui, context).Run(c)\n\t\t},\n\t\tmetadata.Version: func(c *cli.Context) error {\n\t\t\treturn cmd.NewVersion(ui, context).Run(c)\n\t\t},\n\t}\n\n\tbashCompletes := map[string]cli.BashCompleteFunc{\n\t\tmetadata.Delete: \tcmd.ModelIDCompletion,\n\t\tmetadata.Train: \tcmd.TrainCmdCompletion,\n\t\tmetadata.Show: \tcmd.ModelIDCompletion,\n\t\tmetadata.ProjectInit: cmd.InitCmdCompletion,\n\t\tmetadata.Download: \t\tcmd.DownloadCmdCompletion,\n\t\tmetadata.Logs: \t\tcmd.TrainingLogsCompletion,\n\t\tmetadata.Loglines: \tcmd.LoglinesCompletion,\n\t\tmetadata.Emetrics: \tcmd.EMetricsCompletion,\n\t\tmetadata.Halt: \t\tcmd.ModelIDCompletion,\n\t}\n\n cli.CommandHelpTemplate = commandHelp\n\tcli.BashCompletionFlag = cli.BoolFlag{\n\t\tName: \"generate-dl-completion\",\n\t\tHidden: true,\n\t}\n\n\tapp := cli.NewApp()\n\tapp.Name = \"bluemix dl\"\n\tapp.EnableBashCompletion = true\n\tapp.Commands = make([]cli.Command, len(metadata.Commands))\n\tfor index, command := range metadata.Commands {\n\t\tapp.Commands[index] = cli.Command{\n\t\t\tName: command.Name,\n\t\t\tDescription: command.Description,\n\t\t\tUsage: command.Usage,\n\t\t\tFlags: command.CliFlags,\n\t\t\tAction: actions[command.Name],\n\t\t\tBashComplete: bashCompletes[command.Name],\n\t\t}\n\t}\n\n\tapp.Run(os.Args)\n}", "func (h *MovieHandler) show(w http.ResponseWriter, r *http.Request) {\n\t// Parse the id param from the URL and convert it into an int64.\n\tid, err := strconv.ParseInt(chi.URLParam(r, \"id\"), 10, 64)\n\tif err != nil {\n\t\t// Render an error response and set status code.\n\t\thttp.Error(w, \"Not Found\", http.StatusNotFound)\n\t\tlog.Println(\"Error:\", err)\n\t\treturn\n\t}\n\n\t// Call GetMovie to get the movie from the database.\n\tif movie, err := h.MovieService.GetMovie(id); err != nil {\n\t\t// Render an error response and set status code.\n\t\thttp.Error(w, \"Not Found\", http.StatusNotFound)\n\t\tlog.Println(\"Error:\", err)\n\t} else {\n\t\t// Render a HTML response and set status code.\n\t\trender.HTML(w, http.StatusOK, \"movie/show.html\", movie)\n\t}\n}", "func (t *TeamLDAPMapping) GetSlug() string {\n\tif t == nil || t.Slug == nil {\n\t\treturn \"\"\n\t}\n\treturn *t.Slug\n}", "func (fn CreateShortLinkHandlerFunc) Handle(params CreateShortLinkParams, principal interface{}) middleware.Responder {\n\treturn fn(params, principal)\n}", "func (p *Publisher) Run() error {\n\tspecResponse, err := p.sdAPI.PostCommand(p.commandSpec)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Post failed: %v\", err)\n\t}\n\n\terr = p.tagCommand(specResponse)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Tag failed: %v\", err)\n\t}\n\n\t// Published successfully\n\t// Show version number of command published by sd-cmd\n\tfmt.Println(specResponse.Version)\n\n\treturn nil\n}", "func GenerateSlug(modelName string, name string) (generatedSlug string) {\n\n\to := orm.NewOrm()\n\tgeneratedSlug = slug.Make(name)\n\tvar slugInt int\n\n\tmodelName = strings.ToLower(modelName)\n\n\tqueryO := o.QueryTable(modelName).Filter(\"slug__startswith\", generatedSlug)\n\n\tswitch modelName {\n\tcase \"countries\":\n\n\t\tvar countries []*Countries\n\t\tqueryO.All(&countries)\n\n\t\tfor _, val := range countries {\n\t\t\tformatSlug(val.Slug, generatedSlug, &slugInt)\n\t\t}\n\n\tcase \"activities\":\n\n\t\tvar activities []*Activities\n\t\tqueryO.All(&activities)\n\n\t\tfor _, val := range activities {\n\t\t\tformatSlug(val.Slug, generatedSlug, &slugInt)\n\t\t}\n\n\tcase \"locations\":\n\n\t\tvar locations []*Locations\n\t\tqueryO.All(&locations)\n\n\t\tfor _, val := range locations {\n\t\t\tformatSlug(val.Slug, generatedSlug, &slugInt)\n\t\t}\n\n\tcase \"images\":\n\n\t\tvar images []*Images\n\t\tqueryO.All(&images)\n\n\t\tfor _, val := range images {\n\t\t\tformatSlug(val.Slug, generatedSlug, &slugInt)\n\t\t}\n\n\tcase \"portfolios\":\n\n\t\tvar portfolio []*Portfolios\n\t\tqueryO.All(&portfolio)\n\n\t\tfor _, val := range portfolio {\n\t\t\tformatSlug(val.Slug, generatedSlug, &slugInt)\n\t\t}\n\n\tcase \"sectors\":\n\n\t\tvar sector []*Sectors\n\t\tqueryO.All(&sector)\n\n\t\tfor _, val := range sector {\n\t\t\tformatSlug(val.Slug, generatedSlug, &slugInt)\n\t\t}\n\n\tcase \"services\":\n\n\t\tvar service []*Services\n\t\tqueryO.All(&service)\n\n\t\tfor _, val := range service {\n\t\t\tformatSlug(val.Slug, generatedSlug, &slugInt)\n\t\t}\n\n\t}\n\n\tif slugInt > 0 {\n\t\tgeneratedSlug = generatedSlug + \"-\" + strconv.Itoa(slugInt+1)\n\t}\n\n\treturn\n}", "func (srv *Server) handlePost(res http.ResponseWriter, req *http.Request) {\n\tfor _, rute := range srv.routePosts {\n\t\tvals, ok := rute.parse(req.URL.Path)\n\t\tif ok {\n\t\t\trute.endpoint.call(res, req, srv.evals, vals)\n\t\t\treturn\n\t\t}\n\t}\n\tres.WriteHeader(http.StatusNotFound)\n}", "func (app *App) ShowSnippet(w http.ResponseWriter, r *http.Request) {\n\t// Pat doesn't strip the colon from the named capture key, so we need to\n\t// get the value of \":id\" from the query string instead of \"id\".\n\tid, err := strconv.Atoi(r.URL.Query().Get(\":id\"))\n\tif err != nil || id < 1 {\n\t\tapp.NotFound(w) // Use the app.NotFound() helper.\n\t\treturn\n\t}\n\n\tsnippet, err := app.Database.GetSnippet(id)\n\tif err != nil {\n\t\tapp.ServerError(w, err)\n\t\treturn\n\t}\n\tif snippet == nil {\n\t\tapp.NotFound(w)\n\t\treturn\n\t}\n\n\t// Load the session data then use the PopString() method to retrieve the value\n\t// for the \"flash\" key. PopString() also deletes the key and value from the\n\t// session data, so it acts like a one-time fetch. If there is no matching\n\t// key in the session data it will return the empty string. If you want to\n\t// retrieve a string from the session and not delete it you should use the\n\t// GetString() method instead.\n\tsession, _ := app.Sessions.Load(r.Context(), \"flash\")\n\tflash := app.Sessions.PopString(session, \"flash\")\n\t//io.WriteString(w, flash)\n\n\t// Render the show.page.html template, passing in the snippet data wrapped in our HTMLData struct.\n\tapp.RenderHTML(w, r, \"show.page.html\", &HTMLData{\n\t\tSnippet: snippet,\n\t\tFlash: flash,\n\t})\n}" ]
[ "0.63513255", "0.5738546", "0.57292014", "0.55722785", "0.5411228", "0.5343942", "0.53318965", "0.5194136", "0.5159168", "0.49706224", "0.49073952", "0.4837351", "0.478994", "0.47826794", "0.4760586", "0.47508007", "0.4747875", "0.46760988", "0.4666304", "0.46457812", "0.4644765", "0.46403947", "0.46403143", "0.46239236", "0.4602074", "0.45970786", "0.45953822", "0.45645416", "0.45557383", "0.4555244", "0.4534439", "0.45249385", "0.4517976", "0.45041734", "0.44876418", "0.44751805", "0.44677415", "0.44658753", "0.4426687", "0.4417104", "0.44081748", "0.4406457", "0.43987665", "0.43938243", "0.4391345", "0.4387078", "0.43839437", "0.43640995", "0.43602443", "0.4351067", "0.43443078", "0.43411723", "0.433633", "0.43334267", "0.4329675", "0.43280554", "0.43262005", "0.43236867", "0.43160188", "0.43101364", "0.4310034", "0.43087885", "0.42967534", "0.4295086", "0.42825922", "0.42807782", "0.42803302", "0.427562", "0.4274805", "0.42730013", "0.4257782", "0.4257557", "0.4256618", "0.42402738", "0.42383778", "0.42374295", "0.4237194", "0.4234033", "0.42246607", "0.42197862", "0.42135265", "0.4212966", "0.42111638", "0.4210816", "0.4209606", "0.4205933", "0.4205439", "0.42050916", "0.42034075", "0.41991103", "0.4197792", "0.41891456", "0.41868937", "0.41853496", "0.41756022", "0.41728973", "0.41699106", "0.41653106", "0.41637895", "0.41631946" ]
0.6104211
1
sprintByteHex returns a formatted string of the byte array in hexadecimal with a nicely formatted humanreadable output
func sprintByteHex(b []byte) string { output := "\t" for i, b := range b { output += fmt.Sprintf("%x", b) if (i+1)%16 == 0 { output += "\n\n\t" } else if (i+1)%4 == 0 { output += " " } else { output += " " } } output += "\n" return output }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func hex(bytes []byte) string {\n\t// return number of spaces to print based on i's position in slice s\n\tspaces := func(s []byte, i int) int {\n\t\tif i == len(s)-1 {\n\t\t\treturn 0\n\t\t}\n\t\tif (i+1)%4 == 0 {\n\t\t\treturn 2\n\t\t}\n\t\treturn 1\n\t}\n\n\tsb := strings.Builder{}\n\tfor i := range bytes {\n\t\tfmt.Fprintf(&sb, \"%02x%*s\", bytes[i], spaces(bytes, i), \"\")\n\t}\n\treturn sb.String()\n}", "func HexStringOfBytes(ar []byte) string {\n\treturn fmt.Sprintf(\"%0X\", ar)\n}", "func BytesToHexSting(bytes []byte) string {\n\n\treturn hex.EncodeToString(bytes)\n\n}", "func (b Bytes) HexStr(noPrefix ...bool) string { return ToHex(b.Bytes(), noPrefix...) }", "func printBytes(s string) {\n for i := 0; i < len(s); i++ {\n fmt.Printf(\"%x \", s[i]) //output Unicode, %x is the format specifier for hexadecimal.\n }\n}", "func byteString(b []byte) string {\n\tif len(b) < 1 {\n\t\treturn \"\"\n\t}\n\n\ts := make([]byte, len(b)*3-1)\n\ti, j := 0, 0\n\tfor n := len(b) - 1; i < n; i, j = i+1, j+3 {\n\t\ts[j+0] = hex[(b[i] >> 4)]\n\t\ts[j+1] = hex[(b[i] & 0x0f)]\n\t\ts[j+2] = ' '\n\t}\n\ts[j+0] = hex[(b[i] >> 4)]\n\ts[j+1] = hex[(b[i] & 0x0f)]\n\treturn string(s)\n}", "func BytesToHex(b []byte) string {\n\treturn hex.EncodeToString(b)\n}", "func BytesToHex(b []byte) string {\n\treturn hex.EncodeToString(b)\n}", "func printBytes(s string) {\n\tfmt.Printf(\"Bytes: \")\n\t// len(s) returns number of bytes in the string\n\tfor i := 0; i < len(s); i++ {\n\t\t// %x is the format specifier for hexadecimal\n\t\tfmt.Printf(\"%x \", s[i])\n\t}\n}", "func Hex(data []byte) string {\n\treturn fmt.Sprintf(\"%x\", data)\n}", "func FmtHexString(b []byte) string {\n\th := []byte(hex.EncodeToString(b))\n\tvar buf bytes.Buffer\n\tvar c int = 1\n\tfor i := 0; i < len(h); i = i + 2 {\n\t\tbuf.WriteString(\" \")\n\t\tbuf.Write(h[i:i+2])\n\t\tc++\n\t\tif c == 5 {\n\t\t\tbuf.WriteString(\" \")\n\t\t\tc = 1\n\t\t}\n\t}\n\treturn buf.String()\n}", "func HexToString(hex_array []byte) string {\n\t\n\treturn hex.EncodeToString(hex_array)\n\n\t/*var buf bytes.Buffer\n\n\tfor i := 0; i < len(hex_array); i++ {\n\t\tfmt.Fprintf(&buf, \"%02x\", uint8(hex_array[i]))\n\t\t//buf.WriteString(strconv.FormatUint(uint64(hex_array[i]), 16))\n\n\t}\n\treturn buf.String()\n\t*/\n}", "func PrintHex(title string, data []byte, col int) {\n\tvar (\n\t\tstart, x int\n\t\tc byte\n\t)\n\tfmt.Print(title)\n\tfor x, c = range data {\n\t\tif x%col == 0 {\n\t\t\tif x > 0 {\n\t\t\t\tfmt.Print(\" ||\")\n\t\t\t}\n\t\t\tfor y := start; y < x; y++ {\n\t\t\t\tif data[y] >= 33 && data[y] <= 126 {\n\t\t\t\t\tfmt.Printf(\" %c\", data[y])\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Print(\" .\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tfmt.Printf(\"\\n%4d -\", x)\n\t\t\tstart = x\n\t\t}\n\n\t\tfmt.Printf(\" %02X\", c)\n\t}\n\trest := col - (x % col)\n\tif rest > 0 {\n\t\tfor y := 1; y < rest; y++ {\n\t\t\tfmt.Print(\" \")\n\t\t}\n\t\tfmt.Print(\" ||\")\n\t}\n\tfor y := start; y <= x; y++ {\n\t\tif data[y] >= 33 && data[y] <= 126 {\n\t\t\tfmt.Printf(\" %c\", data[y])\n\t\t} else {\n\t\t\tfmt.Print(\" .\")\n\t\t}\n\t}\n\n\tfmt.Println()\n}", "func BytesToHexString(bytes []byte) string {\n\treturn hex.EncodeToString(bytes)\n}", "func ByteToString(b byte) string {\n\treturn fmt.Sprintf(\"%08b\", b)\n}", "func PrintBytes(data []uint8) {\r\n\tfmt.Print(GetStr(data))\r\n}", "func HexEncodeToString(b []byte) string {\n\treturn \"0x\" + hex.EncodeToString(b)\n}", "func printhex(data []byte) {\n\tfmt.Printf(\">00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f\\n -----------------------------------------------\\n \")\n\ti := 0\n\tfor _, b := range data {\n\t\tfmt.Printf(\"%02x\", b)\n\t\ti++\n\t\tswitch i {\n\t\tcase 8:\n\t\t\tfmt.Printf(\",\")\n\t\tcase 16:\n\t\t\tfmt.Printf(\"\\n \")\n\t\t\ti = 0\n\t\tdefault:\n\t\t\tfmt.Printf(\" \")\n\t\t}\n\t}\n\tif i != 0 {\n\t\tfmt.Println()\n\t}\n\tfmt.Println()\n}", "func ByteToStr(inputBytes []byte) string {\r\n\treturn string(inputBytes[:])\r\n}", "func MakeHex(barray []byte) string {\n return hex.EncodeToString(barray)\n}", "func (rgba *rgba) printHex() string {\n\treturn fmt.Sprintf(\"#%02X%02X%02X%02X\", rgba.RGBA.R, rgba.RGBA.G, rgba.RGBA.B, rgba.RGBA.A)\n}", "func (h HexBytes) String() string {\n\treturn ToHex(h)\n}", "func hexString(b []byte) string {\n\thexlen := len(b) * 2\n\thexbuf := make([]byte, hexlen)\n\tj := hexlen - 1\n\tfor _, n := range b {\n\t\thexbuf[j] = hex[n&0xf]\n\t\thexbuf[j-1] = hex[n>>4]\n\t\tj -= 2\n\t}\n\treturn string(hexbuf)\n}", "func hexString(b []byte) string {\n\thexlen := len(b) * 2\n\thexbuf := make([]byte, hexlen)\n\tj := hexlen - 1\n\tfor _, n := range b {\n\t\thexbuf[j] = hex[n&0xf]\n\t\thexbuf[j-1] = hex[n>>4]\n\t\tj -= 2\n\t}\n\treturn string(hexbuf)\n}", "func ByteToString(bs [65]int8) string {\n\tb := make([]byte, len(bs))\n\tfor i, v := range bs {\n\t\tb[i] = byte(v)\n\t}\n\treturn string(b)\n}", "func BytesString(hash []byte) string {\n\treturn fmt.Sprintf(\"%X\", hash)\n}", "func F(bytes []byte) string {\n\treturn fmt.Sprintf(\"%x\", bytes)\n}", "func (b *Buffer) ToStringHex() string {\n\treturn hex.EncodeToString(b.b)\n}", "func hex(buf []byte) string {\n\tconst hexa = \"0123456789abcdef\"\n\tres := make([]byte, len(buf)*2)\n\tfor i, b := range buf {\n\t\tres[i*2] = hexa[b>>4]\n\t\tres[i*2+1] = hexa[b&0x0f]\n\t}\n\treturn string(res)\n}", "func Hex(value interface{}) (string, error) {\n\tswitch v := value.(type) {\n\tcase Hexer:\n\t\treturn v.Hex(), nil\n\tcase []byte:\n\t\treturn fmt.Sprintf(\"%#x\", v), nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"does not support %T\", v)\n\t}\n}", "func HexToBytes(s string) ([]byte, error) {\n\tif strings.HasPrefix(s, \"0x\") {\n\t\ts = strings.Replace(s, \"0x\", \"\", 1)\n\t} else if strings.HasPrefix(s, \"0X\") {\n\t\ts = strings.Replace(s, \"0X\", \"\", 1)\n\t}\n\treturn hex.DecodeString(s)\n}", "func toHex(bz []byte) string {\n\ttext := strings.ToUpper(hex.EncodeToString(bz))\n\n\tvar buffer bytes.Buffer\n\tfor i, r := range text {\n\t\tbuffer.WriteRune(r)\n\t\tif i < len(text)-1 && i%4 == 3 {\n\t\t\tbuffer.WriteRune(' ')\n\t\t}\n\t}\n\treturn buffer.String()\n}", "func BytesToString(bs []byte) string {\n\tvar sb strings.Builder\n\tfor i, b := range bs {\n\t\tif i > 0 {\n\t\t\tsb.WriteString(\" \")\n\t\t}\n\t\tsb.WriteString(strconv.FormatUint(uint64(b), 16))\n\t}\n\treturn sb.String()\n}", "func (s Snowflake) HexPrettyString() string {\n\treturn \"0x\" + strconv.FormatUint(uint64(s), 16)\n}", "func (s Snowflake) HexString() string {\n\treturn strconv.FormatUint(uint64(s), 16)\n}", "func hex(data []byte) string {\n\tbuf := make([]byte, 4*len(data))\n\tconst digits = \"0123456789abcdef\"\n\tfor i, b := range data {\n\t\tbuf[i*4] = '\\\\'\n\t\tbuf[(i*4)+1] = 'x'\n\t\tbuf[(i*4)+2] = digits[b>>4]\n\t\tbuf[(i*4)+3] = digits[b&0x0F]\n\t}\n\treturn string(buf)\n}", "func Hex(n int) string { return String(n, HexChars) }", "func HexToBytes(h string) []byte {\n\ts, err := hex.DecodeString(h)\n\tif err != nil {\n\t\tfmt.Errorf(\"faild to convert BytesToFloat(%s) with error : %s\", h, err.Error())\n\t\treturn []byte(\"\")\n\t}\n\treturn s\n}", "func BytetoStrHex(str []byte) string {\n\treturn hex.EncodeToString(str)\n}", "func (c *ByteBuffer) HexDump() string {\n\treturn fmt.Sprintf(\"%x\", c.Buffer.Bytes())\n}", "func HexStringToByte(str string) []byte {\n\th, err := hex.DecodeString(str)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn h\n}", "func HexToBytes(hex Hex) []byte {\n\tout := make([]byte, len(hex)/2)\n\tfor i := 0; i < len(hex); i += 2 {\n\t\tnum := hex[i]<<4 + hex[i+1]\n\t\tout[i/2] = num\n\t}\n\n\treturn out\n}", "func StrToHexBytes(s string) HexBytes {\n\treturn []byte(s)\n}", "func FormatByte(s uint64) string {\n\treturn humanFormat(s, 1000, siSizes)\n}", "func ByteToString(b *[]byte) string {\n\tresult := *b\n\treturn string(result[:])\n}", "func (a Address) Hex() string {\n\treturn fmt.Sprintf(\"%x\", a[:])\n}", "func StringBytes(b []byte) string { return *(*string)(Pointer(&b)) }", "func BigIntToHexStr(i *big.Int) string {\n\th := i.Text(16)\n\tif len(h)%2 == 1 {\n\t\th = \"0\" + h // make sure that the length is even\n\t}\n\treturn \"0x\" + h\n}", "func HexEncode(bs []byte) string {\n\treturn fmt.Sprintf(\"0x%s\", hex.EncodeToString(bs))\n}", "func (b Beacon) Hex() string { return util.Encode(b[:]) }", "func (f Fingerprint) Hex() string {\n\tf.assertIsSet()\n\tb := f.fingerprintBytes\n\n\treturn fmt.Sprintf(\"%0X\", b)\n}", "func twoDigitHexa(i uint32) string {\n\tif i > 0xf {\n\t\treturn fmt.Sprintf(\"%x\", uint8(i))\n\t}\n\n\treturn fmt.Sprintf(\"0%x\", uint8(i))\n}", "func ByteToString(b []byte) string {\n\tn := bytes.IndexByte(b, 0)\n\tif n == -1 {\n\t\treturn string(b[:])\n\t}\n\treturn string(b[:n])\n\n}", "func Hex(n int) (ss string, err error) {\n\tbs, err := Bytes(n)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tss = hex.EncodeToString(bs)\n\n\treturn\n}", "func Hex(n int) string {\n\treturn fmt.Sprintf(\"0x%x\", n)\n}", "func (b Bytes) Hex() []byte {\n\tdst := make([]byte, hex.EncodedLen(len(b)))\n\thex.Encode(dst, b.Bytes())\n\treturn dst\n}", "func hex(num uint) string {\r\n\ttemp := []byte{'0', '0', '0', '0', '0', '0'}\r\n\r\n\tfor counter := 0; num > 0; counter++ {\r\n\t\tn := uint8(num & 0xF)\r\n\t\tif n < 10 {\r\n\t\t\ttemp[5-counter] = '0' + n\r\n\t\t} else {\r\n\t\t\ttemp[5-counter] = ('A' - 10) + n\r\n\t\t}\r\n\r\n\t\tnum >>= 4\r\n\t}\r\n\r\n\treturn string(temp)\r\n}", "func EncodeToHex(value interface{}) (string, error) {\n\tbz, err := Encode(value)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%#x\", bz), nil\n}", "func (fr *Frame) hexToString(first int, last ...int) string {\n\tdecodedString, _ := hex.DecodeString(fr.getHexValue(first))\n\treturn fmt.Sprint(decodedString[0])\n}", "func (addr *Address) Hex() string {\n\tvar format = \"0x%s\"\n\thexStr := strings.ToUpper(big.NewInt(0).SetBytes(addr.Payload).Text(16))\n\n\t// Prepend a zero\n\tif len(hexStr)%2 == 1 {\n\t\tformat = \"0x0%s\"\n\t}\n\n\treturn fmt.Sprintf(format, hexStr)\n}", "func (bs ByteSlice) String() string {\n\treturn hex.EncodeToString([]byte(bs))\n}", "func BytesToString(b []byte) string { return *(*string)(unsafe.Pointer(&b)) }", "func Hexlify(inputBytes []byte) string {\r\n\treturn hex.EncodeToString(inputBytes)\r\n}", "func toHex(input []int) string {\n\tout := \"\"\n\tfor _, v := range input {\n\t\th := fmt.Sprintf(\"%x\", v)\n\t\tif len(h) == 1 {\n\t\t\tout += \"0\"\n\t\t}\n\t\tout += h\n\t}\n\treturn out\n}", "func HashToString(nbytes [crypto.HashLen]byte) string {\n\tbytes := nbytes[:]\n\treturn hex.EncodeToString(bytes)\n}", "func (s StorageDataRaw) Hex() string {\n\treturn fmt.Sprintf(\"%#x\", s)\n}", "func toHex(x []byte) []byte {\n\tz := make([]byte, 2*len(x))\n\thex.Encode(z, x)\n\treturn z\n}", "func Uint64ToHexBytes(i uint64) []byte {\n\treturn []byte(strconv.FormatUint(i, 16))\n}", "func (h Hash20) Hex() string { return util.Encode(h[:]) }", "func (s *ss) hexString() string {\n\ts.notEOF()\n\tfor {\n\t\tb, ok := s.hexByte()\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\ts.buf.WriteByte(b)\n\t}\n\tif len(s.buf) == 0 {\n\t\ts.errorString(\"no hex data for %x string\")\n\t\treturn \"\"\n\t}\n\treturn string(s.buf)\n}", "func StringToBytes(hexstring string) ([]byte, error) {\n\thexStrings := strings.Fields(hexstring)\n\thexBytes := make([]byte, 0, len(hexStrings))\n\tfor _, s := range hexStrings {\n\t\tif len(s) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tu, err := strconv.ParseUint(strings.TrimSpace(s), 16, 8)\n\t\tif err != nil {\n\t\t\treturn hexBytes, err\n\t\t}\n\t\thexBytes = append(hexBytes, uint8(u))\n\t}\n\treturn hexBytes, nil\n}", "func HexAxpy(c, b []float64, s float64, ci, bi int)", "func (z *Int) Hex() string {\n\treturn fmt.Sprintf(\"%016x.%016x.%016x.%016x\", z[3], z[2], z[1], z[0])\n}", "func hexToBytes(hexadecimal string) []byte {\n\n\tn := len(hexadecimal)\n\tvar intBytes = make([]byte, int(n/2))\n\n\tfor i := 0; i < len(intBytes); i++ {\n\t\tx, _ := strconv.ParseUint(hexadecimal[0+i*2:2+i*2], 16, 64)\n\t\tintBytes[i] = byte(x)\n\t}\n\n\treturn intBytes\n}", "func IntToHex(n int64) []byte {\n\treturn []byte(strconv.FormatInt(n, 16))\n}", "func (buf Hex) String() string {\n\treturn hex.EncodeToString(buf)\n}", "func toHex(c byte) int {\n\tif c >= '0' && c <= '9' {\n\t\treturn int(c) - '0'\n\t} else if c >= 'A' && c <= 'F' {\n\t\treturn 10 + int(c) - 'A'\n\t} else if c >= 'a' && c <= 'f' {\n\t\treturn 10 + int(c) - 'a'\n\t} else {\n\t\treturn -1\n\t}\n}", "func (this UUID) Hex() string {\n\tx := [16]byte(this)\n\treturn fmt.Sprintf(\"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\",\n\t\tx[0], x[1], x[2], x[3], x[4],\n\t\tx[5], x[6],\n\t\tx[7], x[8],\n\t\tx[9], x[10], x[11], x[12], x[13], x[14], x[15])\n\n}", "func HexToBytes(hexstring string) (b []byte) {\n\tb, _ = hex.DecodeString(hexstring)\n\treturn b\n}", "func HexString(input []byte, startBitPos int, numOfBits int) (result string, resultPtr *string, err error) {\n\tif Len(input)-startBitPos < numOfBits {\n\t\treturn \"\", nil, errors.New(\"Input is less than \" + string(numOfBits) + \" bits\")\n\t}\n\n\ttmpArr, _, err := SubBits(input, startBitPos, numOfBits)\n\tresult = hex.EncodeToString(tmpArr)\n\treturn result, &result, err\n}", "func HashBytes(bytes []byte) string {\n\thash := blake2b.Sum256(bytes)\n\treturn hex.EncodeToString(hash[:])\n}", "func Bin2hex(src []byte) string {\n\treturn hex.EncodeToString(src)\n}", "func (x *BigUInt) String() string {\n\tif len(x.data) == 0 {\n\t\treturn \"0x0\"\n\t}\n\tstr := \"0x\"\n\tfor i := len(x.data) - 1; i >= 0; i-- {\n\t\tif x.data[i] > 0xF || i == len(x.data)-1 {\n\t\t\tstr += fmt.Sprintf(\"%x\", x.data[i])\n\t\t} else {\n\t\t\tstr += fmt.Sprintf(\"0%x\", x.data[i])\n\t\t}\n\t\tif i != 0 && i%4 == 0 {\n\t\t\tstr += \"_\"\n\t\t}\n\t}\n\treturn str\n}", "func (b Bytes32) HexStr() string {\n\treturn ToHex(b.Bytes())\n}", "func BuildBytes(bytes []byte) string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(\"[\\n\")\n\tfor i, b := range bytes {\n\t\tbuilder.WriteString(fmt.Sprintf(\"0x%02x,\", b))\n\t\tif i%8 == 7 {\n\t\t\tbuilder.WriteString(\"\\n\")\n\t\t}\n\t}\n\tbuilder.WriteString(\"]\")\n\treturn builder.String()\n}", "func RandBytesHex(n int) string {\n\treturn fmt.Sprintf(\"%x\", RandBytes(n))\n}", "func uint32StrHex(u uint32) string {\n\tstr := fmt.Sprintf(\"%x\", u)\n\t// Add a 0 to the start of odd-length string. This converts \"0x1AB\" to \"0x01AB\"\n\tif (len(str) % 2) != 0 {\n\t\tstr = \"0\" + str\n\t}\n\treturn \"0x\" + str\n}", "func intr2hex (i int) string {\n d:= fmt.Sprintf(\"0x%02x\", i)\n return d\n}", "func (b Bytes64) Hex() []byte {\n\tdst := make([]byte, hex.EncodedLen(len(b)))\n\thex.Encode(dst, b.Bytes())\n\treturn dst\n}", "func ByteArrayToString(buf []byte) string {\n\treturn *(*string)(unsafe.Pointer(&buf))\n}", "func hexToBytes(origHex string) []byte {\n\tbuf, err := hex.DecodeString(origHex)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn buf\n}", "func Int64ToHexBytes(i int64) []byte {\n\treturn []byte(strconv.FormatInt(i, 16))\n}", "func HexFmt(fileName string, numElementsPerLine int) string {\n\tbinFile, err := os.Open(fileName)\n\tcheckError(err)\n\tdefer binFile.Close()\n\n\tbin, err := ioutil.ReadAll(binFile)\n\tcheckError(err)\n\n\tvar sb strings.Builder\n\tfor i, b := range bin {\n\t\tif i > 0 && i%numElementsPerLine == 0 {\n\t\t\tsb.WriteString(\"\\n\")\n\t\t}\n\t\ts := fmt.Sprintf(\"0x%02X, \", b)\n\t\tsb.WriteString(s)\n\t}\n\treturn sb.String()\n}", "func binToHex(binaryText string) string {\n\n\tvar hexText string\n\n\tfor i := 0; i < len(binaryText); i += 4 {\n\n\t\tbinaryTextPart := binaryText[0+i : 4+i]\n\t\thexText += binHexMap[binaryTextPart]\n\t}\n\treturn hexText\n}", "func (t TraceID) HexString() string {\n\treturn data.TraceID(t).HexString()\n}", "func HexStringToBytes(str string) ([]byte, error) {\n\tn := hex.DecodedLen(len([]byte(str)))\n\tbs := make([]byte, n)\n\t_, err := hex.Decode(bs, []byte(str))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bs, nil\n}", "func convertBytesToString(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func (me TcolorType) ToXsdtHexBinary() xsdt.HexBinary { return xsdt.HexBinary(me) }", "func digestToBytes(t *testing.T, digest types.Digest) []byte {\n\tbytes, err := sql.DigestToBytes(digest)\n\trequire.NoError(t, err)\n\treturn bytes\n}", "func HexStringToBytes(hexstr string) []byte {\n\n\tbytes, err := hex.DecodeString(hexstr)\n\tif err != nil {\n\n\t\treturn nil\n\n\t}\n\treturn bytes\n\n}" ]
[ "0.7051886", "0.69957966", "0.6890688", "0.66078013", "0.66071355", "0.6593887", "0.6553541", "0.6553541", "0.6450825", "0.63917994", "0.63325244", "0.6282256", "0.6254831", "0.62540656", "0.62537855", "0.6201541", "0.6201484", "0.6167006", "0.61478466", "0.61307985", "0.6110655", "0.60809785", "0.60486674", "0.60486674", "0.6028782", "0.60279244", "0.6018471", "0.59342533", "0.59183556", "0.5896795", "0.5890913", "0.58403134", "0.5839663", "0.58277464", "0.5826385", "0.58241045", "0.5817451", "0.5801727", "0.57998276", "0.57902664", "0.57792926", "0.5758849", "0.575204", "0.57426924", "0.5701488", "0.56805587", "0.567965", "0.56768894", "0.5665284", "0.56469387", "0.5642119", "0.56349003", "0.5625755", "0.5616241", "0.5612492", "0.56099415", "0.5608565", "0.5594542", "0.557901", "0.5553598", "0.55263495", "0.55205697", "0.5516124", "0.54875", "0.5483287", "0.54763055", "0.54688805", "0.5453163", "0.54392236", "0.5428612", "0.5419365", "0.5418267", "0.5399767", "0.5399228", "0.5375573", "0.53589994", "0.53545994", "0.5352175", "0.5341317", "0.53263944", "0.5313184", "0.5312263", "0.5305311", "0.5287103", "0.5273088", "0.5271887", "0.526956", "0.52476686", "0.5244041", "0.52385443", "0.523466", "0.5233862", "0.5232199", "0.5231512", "0.52194005", "0.52158743", "0.52120745", "0.5209216", "0.51970935", "0.518932" ]
0.8088775
0
driverArgsToMap turns driver.Value list into a parameter map for neo4j parameters
func driverArgsToMap(args []driver.Value) (map[string]interface{}, error) { output := map[string]interface{}{} for _, arg := range args { argBytes, ok := arg.([]byte) if !ok { return nil, errors.New("You must pass only a gob encoded map to the Exec/Query args") } m, err := encoding.Unmarshal(argBytes) if err != nil { return nil, err } for k, v := range m.(map[string]interface{}) { output[k] = v } } return output, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func mapArgs(rawArgs string) (map[string]string, error) {\n\targMap := make(map[string]string)\n\n\t// split params: param0:<param-val0> paramN:<param-valN> badparam\n\tparams, err := commandSplit(rawArgs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// for each, split pram:<pram-value> into {param, <param-val>}\n\tfor _, param := range params {\n\t\tcmdName, cmdStr, err := namedParamSplit(param)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"map args: %s\", err)\n\t\t}\n\t\targMap[cmdName] = cmdStr\n\t}\n\n\treturn argMap, nil\n}", "func argsToParams(args []string) map[string]string {\n\tif len(args) == 0 {\n\t\treturn nil\n\t}\n\tparams := make(map[string]string)\n\tfor _, a := range args {\n\t\tif !strings.Contains(a, \"=\") {\n\t\t\tcontinue\n\t\t}\n\t\tparts := strings.Split(a, \"=\")\n\t\t// Ignore any arguments that do not look like parameters\n\t\tif len(parts) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tparams[parts[0]] = parts[1]\n\t}\n\treturn params\n}", "func toParams(u *core.Connection) map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"connection_id\": u.ID,\n\t\t\"connection_name\": u.Name,\n\t\t\"connection_pid\": u.PID,\n\t\t\"connection_data_base\": u.DataBase,\n\t\t\"connection_host\": u.Host,\n\t\t\"connection_port\": u.Port,\n\t\t\"connection_user\": u.User,\n\t\t\"connection_password\": u.Password,\n\t\t\"connection_description\": u.Description,\n\t\t\"connection_created\": u.Created,\n\t\t\"connection_updated\": u.Updated,\n\t}\n}", "func NodesToParameterMap(node *StructNode,\n\tpaths map[string]*StructNode, filter *support.FieldFilters, tags []string) {\n\n\tif filter.IsIncluded(node.FqName) {\n\t\tfor _, tagname := range tags {\n\t\t\tif tag, ok := node.Tag[tagname]; ok {\n\t\t\t\tif fullName := tag.GetFullName(); fullName != \"\" {\n\t\t\t\t\tpaths[tag.GetFullName()] = node\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif node.HasChildren() {\n\t\tchildren := node.Childs\n\t\tfor i := range node.Childs {\n\t\t\tNodesToParameterMap(&children[i], paths, filter, tags)\n\t\t}\n\t}\n}", "func toMap(params []interface{}) map[string]interface{} {\n\tpar := make(map[string]interface{})\n\tif len(params) == 0 {\n\t\treturn par\n\t}\n\tif len(params)%2 != 0 {\n\t\tpanic(\"WithParams: len(params) % 2 != 0\")\n\t}\n\tfor i := 0; i < len(params)/2; i++ {\n\t\tkey, ok := params[2*i].(string)\n\t\tif !ok {\n\t\t\tpanic(\"WithParams: string expected\")\n\t\t}\n\t\tpar[key] = params[2*i+1]\n\t}\n\treturn par\n}", "func queryParamValuesToMap(values []string) []interface{} {\n\tv := make([]interface{}, len(values))\n\tfor i, value := range values {\n\t\tv[i] = value\n\t}\n\treturn v\n}", "func (ctx *TestContext) getParameterMap(parameters string) map[string]string {\n\tparameterMap := make(map[string]string)\n\tarrayParameters := strings.Split(parameters, \",\")\n\tfor _, paramKeyValue := range arrayParameters {\n\t\tkeyVal := strings.Split(paramKeyValue, \"=\")\n\n\t\tparameterMap[keyVal[0]] = keyVal[1]\n\t}\n\n\treturn parameterMap\n}", "func parseParams(params map[string]interface{}) (map[string]*nebula.Value, error) {\n\tparamsMap := make(map[string]*nebula.Value)\n\tfor k, v := range params {\n\t\tnv, err := value2Nvalue(v)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse params: %s\", err.Error())\n\t\t}\n\t\tparamsMap[k] = nv\n\t}\n\treturn paramsMap, nil\n}", "func paramsAsMap(params *moleculer.ActionSchema) map[string]interface{} {\n\t//TODO\n\tschema := make(map[string]interface{})\n\treturn schema\n}", "func (ec *executionContext) field_Mutation_addPlayer_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\tvar err error\n\targs := map[string]interface{}{}\n\tvar arg0 *string\n\tif tmp, ok := rawArgs[\"boardId\"]; ok {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"boardId\"))\n\t\targ0, err = ec.unmarshalOString2ᚖstring(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"boardId\"] = arg0\n\tvar arg1 *model.Role\n\tif tmp, ok := rawArgs[\"role\"]; ok {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"role\"))\n\t\targ1, err = ec.unmarshalORole2ᚖgithubᚗcomᚋLeonFelipeCorderoᚋgolangᚑbeerᚑgameᚋgraphᚋmodelᚐRole(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"role\"] = arg1\n\treturn args, nil\n}", "func paramsToEnv(from map[string]interface{}, to map[string]string) error {\n\tfor k, v := range from {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tt := reflect.TypeOf(v)\n\t\tvv := reflect.ValueOf(v)\n\n\t\tk = \"PLUGIN_\" + strings.ToUpper(k)\n\n\t\tswitch t.Kind() {\n\t\tcase reflect.Bool:\n\t\t\tto[k] = strconv.FormatBool(vv.Bool())\n\n\t\tcase reflect.String:\n\t\t\tto[k] = vv.String()\n\n\t\tcase reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int8:\n\t\t\tto[k] = fmt.Sprintf(\"%v\", vv.Int())\n\n\t\tcase reflect.Float32, reflect.Float64:\n\t\t\tto[k] = fmt.Sprintf(\"%v\", vv.Float())\n\n\t\tcase reflect.Map:\n\t\t\tto[k] = encodeMap(vv.Interface())\n\n\t\tcase reflect.Slice:\n\t\t\tto[k] = encodeSlice(vv.Interface())\n\t\t}\n\t}\n\treturn nil\n}", "func (d *DriversOptions) GetDriversMaintainParameters(plugin_args map[string]string, action string) {\n\tfor n, v := range d.Drivers {\n\t\tfor k, o := range v.Options {\n\t\t\tif o.Value == \"\" {\n\t\t\t\tgotrace.Trace(\"Instance '%s' parameter '%s' has no value.\", n, k)\n\t\t\t}\n\t\t\tplugin_args[k] = o.Value\n\t\t}\n\t}\n}", "func createParams(observations []*models.Observation, dimensionIDs map[string]string) (map[string]interface{}, error) {\n\n\trows := make([]interface{}, 0)\n\n\tfor _, observation := range observations {\n\n\t\trow := map[string]interface{}{\n\t\t\t\"v\": observation.Row,\n\t\t\t\"i\": observation.RowIndex,\n\t\t}\n\n\t\tfor _, option := range observation.DimensionOptions {\n\n\t\t\tdimensionName := strings.ToLower(option.DimensionName)\n\n\t\t\tdimensionLookUp := observation.InstanceID + \"_\" + dimensionName + \"_\" + option.Name\n\n\t\t\tnodeID, ok := dimensionIDs[dimensionLookUp]\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"No nodeId found for %s\", dimensionLookUp)\n\t\t\t}\n\n\t\t\trow[dimensionName] = nodeID\n\t\t}\n\n\t\trows = append(rows, row)\n\t}\n\n\treturn map[string]interface{}{\"rows\": rows}, nil\n}", "func createParamsMap(params []TrafficOpsParameter) map[string]map[string]string {\n\tm := make(map[string]map[string]string)\n\tfor _, param := range params {\n\t\tif m[param.ConfigFile] == nil {\n\t\t\tm[param.ConfigFile] = make(map[string]string)\n\t\t}\n\t\tm[param.ConfigFile][param.Name] = param.Value\n\t}\n\treturn m\n}", "func (f *ForkParams) ToMap() (map[string]interface{}, error) {\n\tvar inMap map[string]interface{}\n\tinrec, err := json.Marshal(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(inrec, &inMap)\n\treturn inMap, err\n}", "func (dc *Client) MapParams(req *client.Request) (interface{}, error) {\n\tr := req.API.Method.IntegrationRequest\n\tif len(r.ParamTypes) != len(r.MappingParams) {\n\t\treturn nil, errors.New(\"Numbers of param types and paramMappings are not the same\")\n\t}\n\tvar values []interface{}\n\tfor _, mappingParam := range r.MappingParams {\n\t\tsource, _, err := client.ParseMapSource(mappingParam.Name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif mapper, ok := mappers[source]; ok {\n\t\t\tif err := mapper.Map(mappingParam, req, &values, buildOption(mappingParam)); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\treturn values, nil\n}", "func (o *Aliyun) makeMapArgs(args []map[string]string) string {\n\tstr := \"\"\n\tif len(args) > 0 {\n\t\tfor _, v := range args {\n\t\t\tfor kk, vv := range v {\n\t\t\t\tstr += \"&\" + kk + \"=\" + vv + \"&\"\n\t\t\t}\n\t\t}\n\t}\n\treturn str[:len(str)-1]\n}", "func (tr *GremlinDatabase) GetParameters() (map[string]interface{}, error) {\n\tp, err := json.TFParser.Marshal(tr.Spec.ForProvider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbase := map[string]interface{}{}\n\treturn base, json.TFParser.Unmarshal(p, &base)\n}", "func nativeToCypher(v interface{}) map[string]interface{} {\n\tif v == nil {\n\t\treturn map[string]interface{}{\"name\": \"CypherNull\", \"data\": nil}\n\t}\n\tswitch x := v.(type) {\n\tcase int64:\n\t\treturn valueResponse(\"CypherInt\", x)\n\tcase string:\n\t\treturn valueResponse(\"CypherString\", x)\n\tcase bool:\n\t\treturn valueResponse(\"CypherBool\", x)\n\tcase float64:\n\t\treturn valueResponse(\"CypherFloat\", x)\n\tcase []interface{}:\n\t\tvalues := make([]interface{}, len(x))\n\t\tfor i, y := range x {\n\t\t\tvalues[i] = nativeToCypher(y)\n\t\t}\n\t\treturn valueResponse(\"CypherList\", values)\n\tcase []string:\n\t\tvalues := make([]interface{}, len(x))\n\t\tfor i, y := range x {\n\t\t\tvalues[i] = nativeToCypher(y)\n\t\t}\n\t\treturn valueResponse(\"CypherList\", values)\n\tcase map[string]interface{}:\n\t\tvalues := make(map[string]interface{})\n\t\tfor k, v := range x {\n\t\t\tvalues[k] = nativeToCypher(v)\n\t\t}\n\t\treturn valueResponse(\"CypherMap\", values)\n\tcase neo4j.Node:\n\t\treturn map[string]interface{}{\n\t\t\t\"name\": \"Node\", \"data\": map[string]interface{}{\n\t\t\t\t\"id\": nativeToCypher(x.Id),\n\t\t\t\t\"labels\": nativeToCypher(x.Labels),\n\t\t\t\t\"props\": nativeToCypher(x.Props),\n\t\t\t}}\n\t}\n\tpanic(fmt.Sprintf(\"Don't know how to patch %T\", v))\n}", "func mapParams(params interface{}, fn func(param string, index int, field reflect.StructField)) {\n\trParams := reflect.TypeOf(params)\n\tfor i := 0; i < rParams.NumField(); i++ {\n\t\tfield := rParams.Field(i)\n\t\tparam := field.Tag.Get(\"json\")\n\t\tif !strings.HasSuffix(param, \"_admins\") {\n\t\t\tfn(param, i, field)\n\t\t}\n\t}\n}", "func accNeo4jMap(node1 *nodeInfo, node2 *nodeInfo, relationship string, timeStamp string, acc telegraf.Accumulator) {\n\tcypherCmd := mergeNeo4jLinks(node1, node2, relationship, timeStamp)\n\tacc.AddFields(\"db_relay\", map[string]interface{}{\"cmd\": cypherCmd}, map[string]string{\"dc_tag\": \"na\"}, time.Now())\n}", "func addParamsList(params map[string]string, label string, ids []string) {\n\tfor i, id := range ids {\n\t\tparams[label+\".\"+strconv.Itoa(i+1)] = id\n\t}\n}", "func Map(args ...interface{}) (map[string]interface{}, error) {\n\tif len(args)%2 != 0 {\n\t\treturn nil, fmt.Errorf(\"expecting even number of arguments, got %d\", len(args))\n\t}\n\n\tm := make(map[string]interface{})\n\tfn := \"\"\n\tfor _, v := range args {\n\t\tif len(fn) == 0 {\n\t\t\tif s, ok := v.(string); ok {\n\t\t\t\tfn = s\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn m, fmt.Errorf(\"expecting string for odd numbered arguments, got %+v\", v)\n\t\t}\n\t\tm[fn] = v\n\t\tfn = \"\"\n\t}\n\n\treturn m, nil\n}", "func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) {\n\tdargs := make([]driver.Value, len(named))\n\tfor n, param := range named {\n\t\tif len(param.Name) > 0 {\n\t\t\treturn nil, errors.New(\"sql: driver does not support the use of Named Parameters\")\n\t\t}\n\t\tdargs[n] = param.Value\n\t}\n\treturn dargs, nil\n}", "func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) {\n\tdargs := make([]driver.Value, len(named))\n\tfor n, param := range named {\n\t\tif len(param.Name) > 0 {\n\t\t\treturn nil, errors.New(\"sql: driver does not support the use of Named Parameters\")\n\t\t}\n\t\tdargs[n] = param.Value\n\t}\n\treturn dargs, nil\n}", "func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) {\n\tdargs := make([]driver.Value, len(named))\n\tfor n, param := range named {\n\t\tif len(param.Name) > 0 {\n\t\t\treturn nil, errors.New(\"sql: driver does not support the use of Named Parameters\")\n\t\t}\n\t\tdargs[n] = param.Value\n\t}\n\treturn dargs, nil\n}", "func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) {\n\tdargs := make([]driver.Value, len(named))\n\tfor n, param := range named {\n\t\tif len(param.Name) > 0 {\n\t\t\treturn nil, errors.New(\"sql: driver does not support the use of Named Parameters\")\n\t\t}\n\t\tdargs[n] = param.Value\n\t}\n\treturn dargs, nil\n}", "func AddIndependentPropertyGeneratorsForPostArgsMatchConditionParameters(gens map[string]gopter.Gen) {\n\tgens[\"MatchValues\"] = gen.SliceOf(gen.AlphaString())\n\tgens[\"NegateCondition\"] = gen.PtrOf(gen.Bool())\n\tgens[\"Operator\"] = gen.PtrOf(gen.AlphaString())\n\tgens[\"Selector\"] = gen.PtrOf(gen.AlphaString())\n\tgens[\"Transforms\"] = gen.SliceOf(gen.AlphaString())\n\tgens[\"TypeName\"] = gen.PtrOf(gen.AlphaString())\n}", "func ToMap(componentName, src, root string) (map[string]interface{}, error) {\n\tobj, err := jsonnetParseFn(\"params.libsonnet\", src)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"parse jsonnet\")\n\t}\n\n\tcomponentObject, err := componentParams(obj, componentName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm, err := convertObjectToMapFn(componentObject)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif componentName == \"\" {\n\t\treturn m[root].(map[string]interface{}), nil\n\t}\n\n\tparamsMap, ok := m[componentName].(map[string]interface{})\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"component %q params is not an object\", componentName)\n\t}\n\n\treturn paramsMap, nil\n}", "func remapNodeArgs(n *spec.Node, args map[string]interface{}) (map[string]interface{}, error) {\n\tjobArgs2 := map[string]interface{}{}\n\tfor _, arg := range n.Args {\n\t\tvar ok bool\n\t\tjobArgs2[*arg.Expected], ok = args[*arg.Given]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"cannot create job %s: missing %s from job args\", *n.NodeType, *arg.Given)\n\t\t}\n\t}\n\treturn jobArgs2, nil\n}", "func (component *Component) ArgsFromMap(args map[string]string) []string {\n\tres := []string{}\n\tfor argumentName, argumentValue := range args {\n\t\tres = append(res, fmt.Sprintf(\"--%s=%s\", argumentName, argumentValue))\n\t}\n\treturn res\n}", "func mapfn(kvs ...interface{}) (map[string]interface{}, error) {\n\tif len(kvs)%2 != 0 {\n\t\treturn nil, errors.New(\"map requires even number of arguments.\")\n\t}\n\tm := make(map[string]interface{})\n\tfor i := 0; i < len(kvs); i += 2 {\n\t\ts, ok := kvs[i].(string)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"even args to map must be strings.\")\n\t\t}\n\t\tm[s] = kvs[i+1]\n\t}\n\treturn m, nil\n}", "func parameteriseValues(args []string, valueMap map[string]string) []string {\n\tfor k, v := range valueMap {\n\t\tkey := strings.Replace(k, \"_\", \"-\", -1)\n\t\targs = append(args, \"--\"+key)\n\n\t\tif fmt.Sprintf(\"%v\", v) != \"\" {\n\t\t\targs = append(args, fmt.Sprintf(\"%v\", v))\n\t\t}\n\t}\n\n\treturn args\n}", "func (tr *GremlinGraph) GetParameters() (map[string]interface{}, error) {\n\tp, err := json.TFParser.Marshal(tr.Spec.ForProvider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbase := map[string]interface{}{}\n\treturn base, json.TFParser.Unmarshal(p, &base)\n}", "func mapExecutorNames(ge *agent.Response_GetExecutors) map[string]string {\n\tresults := map[string]string{}\n\tif ge != nil {\n\t\tfor _, e := range ge.GetExecutors() {\n\t\t\tei := e.GetExecutorInfo()\n\t\t\tid := ei.GetExecutorID().Value\n\t\t\tresults[id] = ei.GetName()\n\t\t}\n\t}\n\treturn results\n}", "func (h *httpRouterExtended) paramsToMap(params jsRouter.Params, w http.ResponseWriter) map[string][]string {\n\trv := make(map[string][]string)\n\n\t// check if its a catch-all route\n\troute := params.MatchedRoutePath()\n\tcatchAllRoute := false\n\tif strings.Contains(route, \"*\") {\n\t\tcatchAllRoute = true\n\t}\n\n\tfor _, p := range params {\n\t\tif p.Key == jsRouter.MatchedRoutePathParam {\n\t\t\tcontinue\n\t\t}\n\n\t\tif p.Key == \"filepath\" {\n\t\t\trv[p.Key] = []string{p.Value}\n\t\t\tcontinue\n\t\t}\n\n\t\tif catchAllRoute {\n\t\t\turlParam := strings.Split(strings.Trim(p.Value, \"/\"), \"/\")\n\t\t\tfor i := 0; i < len(urlParam); i++ {\n\t\t\t\tif h.router.options.CatchAllKeyValuePair {\n\n\t\t\t\t\tif i+1 >= len(urlParam) {\n\t\t\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\t\t\t_, _ = w.Write([]byte(ErrKeyValuePair.Error()))\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\n\t\t\t\t\trv[urlParam[i]] = []string{urlParam[i+1]}\n\t\t\t\t\ti++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trv[strconv.Itoa(i)] = []string{urlParam[i]}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\trv[p.Key] = []string{p.Value}\n\t}\n\treturn rv\n}", "func (e *Encoder) Args(v []driver.Value) error {\n\t_, err := e.Int16(int16(len(v)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor i := 0; i < len(v); i++ {\n\t\t_, err = e.Marshal(v[i])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Map(vars ...Variable) map[string]interface{} {\n\tresult := map[string]interface{}{}\n\tfor _, v := range vars {\n\t\tresult[(string)(v)] = v.Value()\n\t}\n\treturn result\n}", "func createParamsMap(params []string) *map[string]string {\n\n\tparamsMap := map[string]string{}\n\n\tfor _, param := range params {\n\t\tkeyval := strings.Split(param, \"=\")\n\t\tif len(keyval) == 0 || len(keyval) > 2 {\n\t\t\tcontinue // weird but skip\n\t\t}\n\t\tif len(keyval) == 1 {\n\t\t\tparamsMap[strings.TrimSpace(keyval[0])] = \"\" // no value\n\t\t\tcontinue\n\t\t}\n\t\tparamsMap[strings.TrimSpace(keyval[0])] = strings.TrimSpace(keyval[1])\n\t}\n\tif len(paramsMap) < 1 {\n\t\treturn nil\n\t}\n\treturn &paramsMap\n\n}", "func (tr *MongoDatabase) GetParameters() (map[string]interface{}, error) {\n\tp, err := json.TFParser.Marshal(tr.Spec.ForProvider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbase := map[string]interface{}{}\n\treturn base, json.TFParser.Unmarshal(p, &base)\n}", "func (ec *executionContext) field_Mutation_activateGame_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\tvar err error\n\targs := map[string]interface{}{}\n\tvar arg0 string\n\tif tmp, ok := rawArgs[\"testUUID\"]; ok {\n\t\targ0, err = ec.unmarshalNString2string(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"testUUID\"] = arg0\n\treturn args, nil\n}", "func (tr *SQLDatabase) GetParameters() (map[string]interface{}, error) {\n\tp, err := json.TFParser.Marshal(tr.Spec.ForProvider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbase := map[string]interface{}{}\n\treturn base, json.TFParser.Unmarshal(p, &base)\n}", "func mapValues(params map[string]string) url.Values {\n\tvalues := url.Values{}\n\tfor key, val := range params {\n\t\tvalues.Add(key, val)\n\t}\n\treturn values\n}", "func CommandArgs(allArgs map[string]reflect.Value) {\n\tallArgs[\"config\"] = reflect.ValueOf(&ConfigFile)\n\tallArgs[\"cfg\"] = reflect.ValueOf(&ConfigFile)\n\tallArgs[\"help\"] = reflect.ValueOf(&Help)\n\tallArgs[\"h\"] = reflect.ValueOf(&Help)\n}", "func newParsedArgs(original map[string]interface{}, newFilename string) map[string]interface{} {\n\tout := make(map[string]interface{})\n\tfor k, v := range original {\n\t\tout[k] = v\n\t}\n\tout[\"--filename\"] = newFilename\n\treturn out\n}", "func ProcessHelperArguments(arguments []structure.Helper) map[string]string {\n\targumentsMap := make(map[string]string)\n\tfor index := range arguments {\n\t\t// Separate = arguments and put them in map\n\t\targumentParts := strings.SplitN(arguments[index].Name, \"=\", 2)\n\t\tif len(argumentParts) > 1 {\n\t\t\targumentsMap[argumentParts[0]] = argumentParts[1]\n\t\t} else {\n\t\t\targumentsMap[arguments[index].Name] = \"\"\n\t\t}\n\t}\n\treturn argumentsMap\n}", "func parseParams(params []string) (map[string]interface{}, error) {\n\tparamsMap := make(map[string]interface{})\n\tregex := regexp.MustCompile(`^([A-z_]+[A-z0-9_]*[\\.{1}[A-z0-9_]+]*)=([\\s\\S]*)$`)\n\tfor _, param := range params {\n\t\tif regex.MatchString(param) {\n\t\t\tcaptures := regex.FindStringSubmatch(param)\n\t\t\tparamsMap[captures[1]] = captures[2]\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"'%s' does not match the pattern 'key=var', ex: MODE=test\", param)\n\t\t}\n\t}\n\n\treturn paramsMap, nil\n}", "func ConnectArgs(cfg *config.DB) string {\n\t// TODO: ssl mode is disabled.\n\treturn fmt.Sprintf(\"host=%s user=%s password=%s dbname=%s\"+\n\t\t\" port=%d sslmode=disable\", cfg.Host, cfg.User, cfg.Password,\n\t\tcfg.DBName, cfg.Port)\n}", "func queryToMap(query url.Values, m map[string]interface{}) map[string]interface{} {\n\t// no-op if query is empty, do not create the key m[\"query\"]\n\tif len(query) == 0 {\n\t\treturn m\n\t}\n\n\t/* 'parameter' will represent url.Values\n\tmap[string]interface{}{\n\t\t\"parameter-a\": []interface{}{\n\t\t\t\"a\",\n\t\t\t\"b\",\n\t\t},\n\t\t\"parameter-b\": []interface{}{\n\t\t\t\"x\",\n\t\t\t\"y\",\n\t\t},\n\t}\n\t*/\n\tparameters := map[string]interface{}{}\n\tfor param, values := range query {\n\t\tparameters[param] = queryParamValuesToMap(values)\n\t}\n\tm[\"query\"] = parameters\n\treturn m\n}", "func mapParameters(parameters []types.Parameter) []*cloudformation.Parameter {\n\treturnParams := make([]*cloudformation.Parameter, 0)\n\tfor _, p := range parameters {\n\t\treturnParams = append(returnParams, &cloudformation.Parameter{\n\t\t\tParameterKey: aws.String(p.ParameterKey),\n\t\t\tParameterValue: aws.String(p.ParameterValue),\n\t\t})\n\t}\n\n\treturn returnParams\n}", "func genArgs(optionMap map[string]string) []string {\n\toptions := []string{}\n\tfor k, v := range optionMap {\n\t\tif v != \"\" {\n\t\t\tk = fmt.Sprintf(\"%s=%s\", k, v)\n\t\t}\n\t\toptions = append(options, k)\n\t}\n\treturn options\n}", "func mapToStruct(params map[string]interface{}, elem *reflect.Value) {\n\tfor k, v := range params {\n\t\tif _, ok := v.([]interface{}); ok {\n\t\t\t// skip if the value v is array\n\t\t\tcontinue\n\t\t}\n\t\tsetFieldOfElem(elem, k, v)\n\t}\n}", "func (opts BatchCreateOpts) ToDBCreateMap() (map[string]interface{}, error) {\n\tdbs := make([]map[string]interface{}, len(opts))\n\tfor i, db := range opts {\n\t\tdbMap, err := db.ToMap()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdbs[i] = dbMap\n\t}\n\treturn map[string]interface{}{\"databases\": dbs}, nil\n}", "func AddIndependentPropertyGeneratorsForServerPortMatchConditionParameters(gens map[string]gopter.Gen) {\n\tgens[\"MatchValues\"] = gen.SliceOf(gen.AlphaString())\n\tgens[\"NegateCondition\"] = gen.PtrOf(gen.Bool())\n\tgens[\"Operator\"] = gen.PtrOf(gen.AlphaString())\n\tgens[\"Transforms\"] = gen.SliceOf(gen.AlphaString())\n\tgens[\"TypeName\"] = gen.PtrOf(gen.AlphaString())\n}", "func (c *context) Args() InterfaceMap {\n\treturn c.Params()\n}", "func (o StorageClusterSpecStorkPtrOutput) Args() pulumi.MapOutput {\n\treturn o.ApplyT(func(v *StorageClusterSpecStork) map[string]interface{} {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Args\n\t}).(pulumi.MapOutput)\n}", "func (q *Query) ParamsAsMap() map[string]interface{} {\n\tif paramsMap, ok := q.Params().(map[string]interface{}); ok {\n\t\treturn paramsMap\n\t}\n\treturn nil\n}", "func (tr *SQLContainer) GetParameters() (map[string]interface{}, error) {\n\tp, err := json.TFParser.Marshal(tr.Spec.ForProvider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbase := map[string]interface{}{}\n\treturn base, json.TFParser.Unmarshal(p, &base)\n}", "func prepareruntaskparamsdict(runtaskjsonmap map[string]interface{}, runtask Runtask) {\n\tif runtask.Cluster != \"\" {\n\t\truntaskjsonmap[\"cluster\"] = runtask.Cluster\n\t}\n\tif runtask.TaskDefinition != \"\" {\n\t\truntaskjsonmap[\"taskDefinition\"] = runtask.TaskDefinition\n\t}\n\tif runtask.Count != 0 {\n\t\truntaskjsonmap[\"count\"] = runtask.Count\n\t}\n\n\tif runtask.Group != \"\" {\n\t\truntaskjsonmap[\"group\"] = runtask.Group\n\t}\n\tif runtask.StartedBy != \"\" {\n\t\truntaskjsonmap[\"startedBy\"] = runtask.StartedBy\n\t}\n\n\tprepareruntaskoverridesparams(runtaskjsonmap, runtask)\n\tprepareruntaskplacementConstraintsparams(runtaskjsonmap, runtask)\n\tprepareruntaskplacementStrategyparams(runtaskjsonmap, runtask)\n}", "func (tr *SQLFunction) GetParameters() (map[string]interface{}, error) {\n\tp, err := json.TFParser.Marshal(tr.Spec.ForProvider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbase := map[string]interface{}{}\n\treturn base, json.TFParser.Unmarshal(p, &base)\n}", "func (s SecretForDockerRegistryGeneratorV1) ParamNames() []GeneratorParam {\n\treturn []GeneratorParam{\n\t\t{\"name\", true},\n\t\t{\"docker-username\", true},\n\t\t{\"docker-email\", false},\n\t\t{\"docker-password\", true},\n\t\t{\"docker-server\", true},\n\t}\n}", "func dimsToMap(dims producers.Dimensions) map[string]string {\n\tresults := map[string]string{\n\t\t\"mesos_id\": dims.MesosID,\n\t\t\"cluster_id\": dims.ClusterID,\n\t\t\"container_id\": dims.ContainerID,\n\t\t\"executor_id\": dims.ExecutorID,\n\t\t\"framework_name\": dims.FrameworkName,\n\t\t\"framework_id\": dims.FrameworkID,\n\t\t\"framework_role\": dims.FrameworkRole,\n\t\t\"framework_principal\": dims.FrameworkPrincipal,\n\t\t\"task_name\": dims.TaskName,\n\t\t\"task_id\": dims.TaskID,\n\t\t\"hostname\": dims.Hostname,\n\t}\n\tfor k, v := range dims.Labels {\n\t\tresults[k] = v\n\t}\n\treturn results\n}", "func MakeParams(cmd *cobra.Command, params []GeneratorParam) map[string]interface{} {\n\tresult := map[string]interface{}{}\n\tfor ix := range params {\n\t\tf := cmd.Flags().Lookup(params[ix].Name)\n\t\tif f != nil {\n\t\t\tresult[params[ix].Name] = f.Value.String()\n\t\t}\n\t}\n\treturn result\n}", "func DriverConfigs() map[string]interface{} {\n\treturn ds.config.Driver\n}", "func stmtMapManipulation(c *Condition, stmt string, args []interface{}, conditionType int) string {\n\n\t// initialize arguments\n\tif len(c.args) == 0 {\n\t\tc.args = make(map[int][]interface{})\n\t}\n\n\t// manipulate statement\n\tif len(args) >= 1 {\n\t\tfor i := 0; i < len(args); i++ {\n\t\t\t// handel array arguments\n\t\t\tif reflect.ValueOf(args[i]).Kind() == reflect.Array || reflect.ValueOf(args[i]).Kind() == reflect.Slice {\n\t\t\t\t//split after placeholder and only replace the map placeholder\n\t\t\t\tspStmt := strings.SplitAfter(stmt, PLACEHOLDER)\n\t\t\t\t// because of this logic, the append placeholders need a different name without ?. TODO create a more prof. solution.\n\t\t\t\tspStmt[i] = strings.Replace(spStmt[i], PLACEHOLDER, PLACEHOLDER+strings.Repeat(\", \"+PLACEHOLDER_APPEND, reflect.ValueOf(args[i]).Len()-1), -1)\n\t\t\t\tstmt = strings.Join(spStmt, \"\")\n\t\t\t}\n\t\t\t// add single or (map,slice) arguments\n\t\t\tc.addArgument(conditionType, args[i])\n\t\t}\n\t}\n\tstmt = strings.Replace(stmt, PLACEHOLDER_APPEND, PLACEHOLDER, -1)\n\n\treturn stmt\n}", "func (opts CreateOpts) ToServerCreateMap() (map[string]interface{}, error) {\n\tb, err := gophercloud.BuildRequestBody(opts, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif opts.UserData != nil {\n\t\tvar userData string\n\t\tif _, err := base64.StdEncoding.DecodeString(string(opts.UserData)); err != nil {\n\t\t\tuserData = base64.StdEncoding.EncodeToString(opts.UserData)\n\t\t} else {\n\t\t\tuserData = string(opts.UserData)\n\t\t}\n\t\tb[\"user_data\"] = &userData\n\t}\n\n\tif len(opts.SecurityGroups) > 0 {\n\t\tsecurityGroups := make([]map[string]interface{}, len(opts.SecurityGroups))\n\t\tfor i, groupName := range opts.SecurityGroups {\n\t\t\tsecurityGroups[i] = map[string]interface{}{\"name\": groupName}\n\t\t}\n\t\tb[\"security_groups\"] = securityGroups\n\t}\n\n\tswitch v := opts.Networks.(type) {\n\tcase []Network:\n\t\tif len(v) > 0 {\n\t\t\tnetworks := make([]map[string]interface{}, len(v))\n\t\t\tfor i, net := range v {\n\t\t\t\tnetworks[i] = make(map[string]interface{})\n\t\t\t\tif net.UUID != \"\" {\n\t\t\t\t\tnetworks[i][\"uuid\"] = net.UUID\n\t\t\t\t}\n\t\t\t\tif net.Port != \"\" {\n\t\t\t\t\tnetworks[i][\"port\"] = net.Port\n\t\t\t\t}\n\t\t\t\tif net.FixedIP != \"\" {\n\t\t\t\t\tnetworks[i][\"fixed_ip\"] = net.FixedIP\n\t\t\t\t}\n\t\t\t\tif net.Tag != \"\" {\n\t\t\t\t\tnetworks[i][\"tag\"] = net.Tag\n\t\t\t\t}\n\t\t\t}\n\t\t\tb[\"networks\"] = networks\n\t\t}\n\tcase string:\n\t\tif v == \"auto\" || v == \"none\" {\n\t\t\tb[\"networks\"] = v\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(`networks must be a slice of Network struct or a string with \"auto\" or \"none\" values, current value is %q`, v)\n\t\t}\n\t}\n\n\tif opts.Min != 0 {\n\t\tb[\"min_count\"] = opts.Min\n\t}\n\n\tif opts.Max != 0 {\n\t\tb[\"max_count\"] = opts.Max\n\t}\n\n\treturn map[string]interface{}{\"server\": b}, nil\n}", "func GetCapabilitiesAsMap(capabilities []configv1.ClusterVersionCapability) map[configv1.ClusterVersionCapability]struct{} {\n\tcaps := make(map[configv1.ClusterVersionCapability]struct{}, len(capabilities))\n\tfor _, c := range capabilities {\n\t\tcaps[c] = struct{}{}\n\t}\n\treturn caps\n}", "func (q *Query) CopyParamsAsMap() map[string]interface{} {\n\tif paramsMap, ok := q.Params().(map[string]interface{}); ok {\n\t\tparamsCopy := map[string]interface{}{}\n\t\tfor k, v := range paramsMap {\n\t\t\tparamsCopy[k] = v\n\t\t}\n\t\treturn paramsCopy\n\t}\n\treturn nil\n}", "func setNodeArgs(n *spec.Node, argsTo, argsFrom map[string]interface{}) error {\n\tif len(n.Sets) == 0 {\n\t\treturn nil\n\t}\n\tfor _, key := range n.Sets {\n\t\tvar ok bool\n\t\tvar val interface{}\n\t\tval, ok = argsFrom[*key.Arg]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"expected %s to set %s in jobargs\", *n.NodeType, *key.Arg)\n\t\t}\n\t\targsTo[*key.As] = val\n\t}\n\n\treturn nil\n}", "func AddIndependentPropertyGeneratorsForSocketAddrMatchConditionParameters(gens map[string]gopter.Gen) {\n\tgens[\"MatchValues\"] = gen.SliceOf(gen.AlphaString())\n\tgens[\"NegateCondition\"] = gen.PtrOf(gen.Bool())\n\tgens[\"Operator\"] = gen.PtrOf(gen.AlphaString())\n\tgens[\"Transforms\"] = gen.SliceOf(gen.AlphaString())\n\tgens[\"TypeName\"] = gen.PtrOf(gen.AlphaString())\n}", "func AddIndependentPropertyGeneratorsForClientPortMatchConditionParameters(gens map[string]gopter.Gen) {\n\tgens[\"MatchValues\"] = gen.SliceOf(gen.AlphaString())\n\tgens[\"NegateCondition\"] = gen.PtrOf(gen.Bool())\n\tgens[\"Operator\"] = gen.PtrOf(gen.AlphaString())\n\tgens[\"Transforms\"] = gen.SliceOf(gen.AlphaString())\n\tgens[\"TypeName\"] = gen.PtrOf(gen.AlphaString())\n}", "func (opts CreateOpts) ToMap() (map[string]interface{}, error) {\n\tif len(opts.Name) > 64 {\n\t\terr := gophercloud.ErrInvalidInput{}\n\t\terr.Argument = \"databases.CreateOpts.Name\"\n\t\terr.Value = opts.Name\n\t\terr.Info = \"Must be less than 64 chars long\"\n\t\treturn nil, err\n\t}\n\treturn gophercloud.BuildRequestBody(opts, \"\")\n}", "func paramToClassMap(classesMap map[string]phpClass, p Parameter) {\n\tif p.BaseType == phpObject && p.BaseType != p.Type {\n\t\tclassesMap[p.Type] = phpClass{\n\t\t\tName: p.Type,\n\t\t\tFields: p.Properties,\n\t\t}\n\t}\n}", "func paramsToLog(entry wlog.MapLogEntry) []string {\n\tvar params []string\n\tfor k, v := range entry.StringValues() {\n\t\tparams = append(params, fmt.Sprintf(\"%s: %s\", k, v))\n\t}\n\tfor k, v := range entry.SafeLongValues() {\n\t\tparams = append(params, fmt.Sprintf(\"%s: %v\", k, v))\n\t}\n\tfor k, v := range entry.IntValues() {\n\t\tparams = append(params, fmt.Sprintf(\"%s: %v\", k, v))\n\t}\n\tfor k, v := range entry.StringListValues() {\n\t\tparams = append(params, fmt.Sprintf(\"%s: %v\", k, v))\n\t}\n\tfor k, v := range entry.StringMapValues() {\n\t\tparams = append(params, fmt.Sprintf(\"%s: %v\", k, v))\n\t}\n\tfor k, v := range entry.AnyMapValues() {\n\t\tparams = append(params, fmt.Sprintf(\"%s: %v\", k, v))\n\t}\n\tfor k, v := range entry.ObjectValues() {\n\t\tval, ok := marshalers.StringForType(v.MarshalerType, k, v.Value)\n\t\tif !ok {\n\t\t\tval = fmt.Sprintf(\"%+v\", v.Value)\n\t\t}\n\t\tparams = append(params, fmt.Sprintf(\"%s: %v\", k, val))\n\t}\n\treturn params\n}", "func driverArgsConnLocked(ci driver.Conn, ds *driverStmt, args []any) ([]driver.NamedValue, error) {\n\tnvargs := make([]driver.NamedValue, len(args))\n\n\t// -1 means the driver doesn't know how to count the number of\n\t// placeholders, so we won't sanity check input here and instead let the\n\t// driver deal with errors.\n\twant := -1\n\n\tvar si driver.Stmt\n\tvar cc ccChecker\n\tif ds != nil {\n\t\tsi = ds.si\n\t\twant = ds.si.NumInput()\n\t\tcc.want = want\n\t}\n\n\t// Check all types of interfaces from the start.\n\t// Drivers may opt to use the NamedValueChecker for special\n\t// argument types, then return driver.ErrSkip to pass it along\n\t// to the column converter.\n\tnvc, ok := si.(driver.NamedValueChecker)\n\tif !ok {\n\t\tnvc, ok = ci.(driver.NamedValueChecker)\n\t}\n\tcci, ok := si.(driver.ColumnConverter)\n\tif ok {\n\t\tcc.cci = cci\n\t}\n\n\t// Loop through all the arguments, checking each one.\n\t// If no error is returned simply increment the index\n\t// and continue. However if driver.ErrRemoveArgument\n\t// is returned the argument is not included in the query\n\t// argument list.\n\tvar err error\n\tvar n int\n\tfor _, arg := range args {\n\t\tnv := &nvargs[n]\n\t\tif np, ok := arg.(NamedArg); ok {\n\t\t\tif err = validateNamedValueName(np.Name); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\targ = np.Value\n\t\t\tnv.Name = np.Name\n\t\t}\n\t\tnv.Ordinal = n + 1\n\t\tnv.Value = arg\n\n\t\t// Checking sequence has four routes:\n\t\t// A: 1. Default\n\t\t// B: 1. NamedValueChecker 2. Column Converter 3. Default\n\t\t// C: 1. NamedValueChecker 3. Default\n\t\t// D: 1. Column Converter 2. Default\n\t\t//\n\t\t// The only time a Column Converter is called is first\n\t\t// or after NamedValueConverter. If first it is handled before\n\t\t// the nextCheck label. Thus for repeats tries only when the\n\t\t// NamedValueConverter is selected should the Column Converter\n\t\t// be used in the retry.\n\t\tchecker := defaultCheckNamedValue\n\t\tnextCC := false\n\t\tswitch {\n\t\tcase nvc != nil:\n\t\t\tnextCC = cci != nil\n\t\t\tchecker = nvc.CheckNamedValue\n\t\tcase cci != nil:\n\t\t\tchecker = cc.CheckNamedValue\n\t\t}\n\n\tnextCheck:\n\t\terr = checker(nv)\n\t\tswitch err {\n\t\tcase nil:\n\t\t\tn++\n\t\t\tcontinue\n\t\tcase driver.ErrRemoveArgument:\n\t\t\tnvargs = nvargs[:len(nvargs)-1]\n\t\t\tcontinue\n\t\tcase driver.ErrSkip:\n\t\t\tif nextCC {\n\t\t\t\tnextCC = false\n\t\t\t\tchecker = cc.CheckNamedValue\n\t\t\t} else {\n\t\t\t\tchecker = defaultCheckNamedValue\n\t\t\t}\n\t\t\tgoto nextCheck\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"sql: converting argument %s type: %v\", describeNamedValue(nv), err)\n\t\t}\n\t}\n\n\t// Check the length of arguments after conversion to allow for omitted\n\t// arguments.\n\tif want != -1 && len(nvargs) != want {\n\t\treturn nil, fmt.Errorf(\"sql: expected %d arguments, got %d\", want, len(nvargs))\n\t}\n\n\treturn nvargs, nil\n\n}", "func _SplitStatementMapKeyValues(db *sql.DB, udn_schema map[string]interface{}, source_array []string) []string {\n\t//UdnLog(udn_schema, \"\\nSplit: Map Key Values: %v\\n\\n\", source_array)\n\n\treturn source_array\n}", "func (s *BaseMySqlParserListener) EnterFunctionArgs(ctx *FunctionArgsContext) {}", "func (ec *executionContext) field_Mutation_addPet_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\tvar err error\n\targs := map[string]interface{}{}\n\tvar arg0 model.PetInput\n\tif tmp, ok := rawArgs[\"pet\"]; ok {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"pet\"))\n\t\targ0, err = ec.unmarshalNPetInput2githubᚗcomᚋharshpreet93ᚋnextᚑgqlgenᚑentᚋbackendᚋgraphᚋmodelᚐPetInput(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"pet\"] = arg0\n\treturn args, nil\n}", "func (opts BindOpts) ToBindOptsMap() (map[string]interface{}, error) {\n\treturn gophercloud.BuildRequestBody(opts, \"nic\")\n}", "func (cmd *Cmd) SelectArguments(reqParams, optParams []string) (selected NodeMap, unknown, missing []string) {\n\tif cmd.Anonymous {\n\t\tselected, unknown, missing = cmd.selectAnonymousArguments(reqParams, optParams)\n\t} else {\n\t\tselected, unknown, missing = cmd.selectNamedArguments(reqParams, optParams)\n\t}\n\treturn\n}", "func AddIndependentPropertyGeneratorsForRemoteAddressMatchConditionParameters(gens map[string]gopter.Gen) {\n\tgens[\"MatchValues\"] = gen.SliceOf(gen.AlphaString())\n\tgens[\"NegateCondition\"] = gen.PtrOf(gen.Bool())\n\tgens[\"Operator\"] = gen.PtrOf(gen.AlphaString())\n\tgens[\"Transforms\"] = gen.SliceOf(gen.AlphaString())\n\tgens[\"TypeName\"] = gen.PtrOf(gen.AlphaString())\n}", "func copyParamValuesIntoMap(dst map[string]interface{}, src interface{}) {\n\t// nil is empty map, just bail with log\n\tif src == nil {\n\t\tlogrus.Debugf(\"src is nil; no work to do\")\n\t\treturn\n\t}\n\t// convert the interface to a map type to walk its keys/values\n\tif srcMap := convertInterfaceToMap(src); srcMap != nil {\n\t\tfor k, v := range srcMap {\n\t\t\t_, value := fetchMetaValue(\"value\", v)\n\t\t\tif _, ok := value.(string); ok {\n\t\t\t\tdst[k] = v\n\t\t\t} else {\n\t\t\t\tlogrus.Tracef(\"value for key %s is of type %T; skipping\", k, value)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// If not map, warn and bail\n\t\tlogrus.Warnf(\"src is not a map type; skipping\")\n\t}\n}", "func paramsToLog(entry wlog.MapLogEntry) []string {\n\tvar params []string\n\tfor k, v := range entry.StringValues() {\n\t\tparams = append(params, fmt.Sprintf(\"%s: %s\", k, v))\n\t}\n\tfor k, v := range entry.SafeLongValues() {\n\t\tparams = append(params, fmt.Sprintf(\"%s: %v\", k, v))\n\t}\n\tfor k, v := range entry.IntValues() {\n\t\tparams = append(params, fmt.Sprintf(\"%s: %v\", k, v))\n\t}\n\tfor k, v := range entry.StringListValues() {\n\t\tparams = append(params, fmt.Sprintf(\"%s: %v\", k, v))\n\t}\n\tfor k, v := range entry.StringMapValues() {\n\t\tparams = append(params, fmt.Sprintf(\"%s: %v\", k, v))\n\t}\n\tfor k, v := range entry.AnyMapValues() {\n\t\tparams = append(params, fmt.Sprintf(\"%s: %v\", k, v))\n\t}\n\tfor k, v := range entry.ObjectValues() {\n\t\tparams = append(params, fmt.Sprintf(\"%s: %v\", k, v))\n\t}\n\treturn params\n}", "func (s *BaseLittleDuckListener) EnterEscritura_params_next(ctx *Escritura_params_nextContext) {}", "func convertVariablesToMap(params map[string]interface{}) map[string]string {\n\tvalues := make(map[string]string)\n\tfor k, v := range params {\n\t\tk = firstLowercase(k)\n\t\tif v != 0 && v != \"\" {\n\t\t\tif _, ok := v.(int); ok {\n\t\t\t\tvalues[k] = strconv.Itoa(v.(int))\n\t\t\t} else {\n\t\t\t\tvalues[k] = v.(string)\n\t\t\t}\n\t\t}\n\t}\n\treturn values\n}", "func (tr *GremlinGraph) GetConnectionDetailsMapping() map[string]string {\n\treturn nil\n}", "func linkedConstructInputsMap(ctx *pulumi.Context, inputs map[string]interface{}) (pulumi.Map, error)", "func parseParams(params map[string][]string) url.Values {\n\tv := url.Values{}\n\tfor key, values := range params {\n\t\tfor _, value := range values {\n\t\t\tv.Add(key, value)\n\t\t}\n\t}\n\treturn v\n}", "func RunParamList(m map[string]interface{}) error {\n\tpl, err := NewParamList(m)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn pl.Run()\n}", "func MarshalNeoFields(obj interface{}) map[string]interface{} {\n\tprops := map[string]interface{}{}\n\tforEachSettableNeoStructField(reflect.ValueOf(obj).Elem(), func(field reflect.Value, tag string) {\n\t\tfieldInterface := field.Interface()\n\t\tswitch fieldInterface.(type) {\n\t\tcase uuid.UUID:\n\t\t\tuid := fieldInterface.(uuid.UUID)\n\t\t\tprops[tag] = uid.String()\n\t\tcase time.Time:\n\t\t\ttimeValue := fieldInterface.(time.Time)\n\t\t\tprops[tag] = neo4j.LocalDateTimeOf(timeValue)\n\t\tdefault:\n\t\t\tprops[tag] = fieldInterface\n\t\t}\n\t})\n\treturn props\n}", "func subTargetParams(cmdToExec string, targetParams map[string]string) string {\n\tfor k, v := range targetParams {\n\t\tparamholder := \"{\" + k + \"}\"\n\t\tcmdToExec = strings.ReplaceAll(cmdToExec, paramholder, v)\n\t}\n\treturn cmdToExec\n}", "func extractParams(parameter string) map[string]string {\n\tm := make(map[string]string)\n\tfor _, p := range strings.Split(parameter, \",\") {\n\t\tif p == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif i := strings.Index(p, \"=\"); i < 0 {\n\t\t\tm[p] = \"\"\n\t\t} else {\n\t\t\tm[p[0:i]] = p[i+1:]\n\t\t}\n\t}\n\n\treturn m\n}", "func ToParamsAndPrepare(in any) (Params, error) {\n\tif types.IsNil(in) {\n\t\treturn Params{}, nil\n\t}\n\tm, err := ToStringMapE(in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tPrepareParams(m)\n\treturn m, nil\n}", "func AddIndependentPropertyGeneratorsForQueryStringMatchConditionParameters(gens map[string]gopter.Gen) {\n\tgens[\"MatchValues\"] = gen.SliceOf(gen.AlphaString())\n\tgens[\"NegateCondition\"] = gen.PtrOf(gen.Bool())\n\tgens[\"Operator\"] = gen.PtrOf(gen.AlphaString())\n\tgens[\"Transforms\"] = gen.SliceOf(gen.AlphaString())\n\tgens[\"TypeName\"] = gen.PtrOf(gen.AlphaString())\n}", "func Args(p Pack) map[string]interface{} {\n\treturn p.Args\n}", "func GetBaseURIParameters(config CONFIGURATION) map[string]interface{} {\r\n kvpMap := map[string]interface{}{\r\n }\r\n return kvpMap;\r\n}", "func preparestoptaskparamsdict(stoptaskjsonmap map[string]interface{}, stoptask Stoptask) {\n\tif stoptask.Cluster != \"\" {\n\t\tstoptaskjsonmap[\"cluster\"] = stoptask.Cluster\n\t}\n\n\tif stoptask.Reason != \"\" {\n\t\tstoptaskjsonmap[\"reason\"] = stoptask.Reason\n\t}\n\n\tif stoptask.Task != \"\" {\n\t\tstoptaskjsonmap[\"task\"] = stoptask.Task\n\t}\n}", "func (d Dispatcher) ExecArgs(id string, hash string) ([]interface{}, error) {\n\te, err := d.GetBC().FindExec(id, hash)\n\tif err != nil {\n\t\treturn make([]interface{}, 1), err\n\t}\n\treturn e.GetArgs(), nil\n}", "func (tr *MongoCollection) GetParameters() (map[string]interface{}, error) {\n\tp, err := json.TFParser.Marshal(tr.Spec.ForProvider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbase := map[string]interface{}{}\n\treturn base, json.TFParser.Unmarshal(p, &base)\n}", "func (opts CreateOpts) ToServerCreateMap() (map[string]interface{}, error) {\n\tb, err := golangsdk.BuildRequestBody(opts, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif opts.UserData != nil {\n\t\tvar userData string\n\t\tif _, err := base64.StdEncoding.DecodeString(string(opts.UserData)); err != nil {\n\t\t\tuserData = base64.StdEncoding.EncodeToString(opts.UserData)\n\t\t} else {\n\t\t\tuserData = string(opts.UserData)\n\t\t}\n\t\tb[\"user_data\"] = &userData\n\t}\n\n\treturn map[string]interface{}{\"server\": b}, nil\n}" ]
[ "0.53027666", "0.5219961", "0.5159778", "0.5078906", "0.49744081", "0.49501595", "0.49113458", "0.48044524", "0.4773885", "0.47444138", "0.46754888", "0.46352243", "0.45708403", "0.45623273", "0.45322862", "0.45287666", "0.44981897", "0.4490554", "0.44724736", "0.44593903", "0.44571868", "0.44546276", "0.44529888", "0.44467306", "0.44467306", "0.44467306", "0.44467306", "0.44099405", "0.4375185", "0.43746403", "0.43659568", "0.43480116", "0.43443364", "0.4342022", "0.43260148", "0.43228692", "0.43217248", "0.43130955", "0.4312463", "0.43119287", "0.43083572", "0.42926922", "0.42853993", "0.4279567", "0.42547902", "0.4237947", "0.4234464", "0.4228814", "0.42280975", "0.42097527", "0.42072102", "0.42044657", "0.42040122", "0.41896012", "0.4183959", "0.4165091", "0.41646606", "0.41563696", "0.4145879", "0.41439858", "0.41364402", "0.41339332", "0.4130172", "0.41224062", "0.41169992", "0.41158697", "0.41126958", "0.41004303", "0.40924016", "0.40832883", "0.40736312", "0.40712422", "0.40664288", "0.40596476", "0.4059233", "0.40572143", "0.40571204", "0.40518114", "0.40495136", "0.40478724", "0.40467295", "0.4044933", "0.40409678", "0.40335768", "0.40283644", "0.4006375", "0.40037262", "0.3995605", "0.39941362", "0.39920408", "0.3986155", "0.3981809", "0.396978", "0.3964599", "0.39642844", "0.3959971", "0.3958268", "0.39567438", "0.39555022", "0.3953469" ]
0.7387417
0
Fetches scheduled games from the MASTER master base station
func fetchScheduledGames() []gm.Game { uri := viper.GetString("master_URL") + "/api/games" resp, _ := http.Get(uri) defer closeResponse(resp) body, _ := ioutil.ReadAll(resp.Body) var gms []gm.Game jsonErr := json.Unmarshal(body, &gms) if jsonErr != nil { logger.Error().Msg("could not get schedule game from MASTER master base station") } return gms }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func AllGames(w http.ResponseWriter, r *http.Request) {\r\n\tdb, err = gorm.Open(\"sqlite3\", \"collegiateCS.db\")\r\n\t//cStats := make(chan []dbStats)\r\n\t//cPlayers := make(chan []dbPlayer)\r\n\t//cRosters := make(chan []dbRoster)\r\n\r\n\tif err != nil {\r\n\t\tfmt.Println(err.Error())\r\n\t\tpanic(\"Failed to connect to db\")\r\n\t}\r\n\tdefer db.Close()\r\n\t//Trigger happy to create go routines, alwasy wanted to use them\r\n\t//go allStats(cStats)\r\n\t//go allPlayers(cPlayers)\r\n\t//go allRosters(cRosters)\r\n\r\n\tvar dbGames []dbGame\r\n\tdb.Find(&dbGames)\r\n\t//dbStatsOp := <-cStats\r\n\t//dbPlayers := <-cPlayers\r\n\t//dbRosters := <-cRosters\r\n\t//close(cStats)\r\n\t//close(cPlayers)\r\n\t//close(cRosters)\r\n\taGames := buildGame(&dbGames)\r\n\tjson.NewEncoder(w).Encode(*aGames)\r\n}", "func GetMasterSchedule(w http.ResponseWriter, r *http.Request) {\n\tgid := chi.URLParam(r, \"groupID\")\n\tgroupID, err := primitive.ObjectIDFromHex(gid)\n\tif err != nil {\n\t\trender.Render(w, r, ErrInvalidRequest(err))\n\t\treturn\n\t}\n\tms := &MasterSchedule{}\n\terr = mh.GetMasterSchedule(ms, bson.M{\"groupId\": groupID})\n\tif err != nil {\n\t\trender.Render(w, r, ErrNotFound(err))\n\t\treturn\n\t}\n\trender.Status(r, http.StatusOK)\n\trender.Render(w, r, NewMasterScheduleResponse(*ms))\n}", "func fetchGames(request request) (*GameCollection, *Error) {\n\tresult := &GameCollection{}\n\terr := httpClient.do(request, result)\n\n\treturn result, err\n}", "func ScheduleScrapes(mtID int, attempt int, app *Application) func(time.Time) {\n\n\treturn func(now time.Time) {\n\n\t\tfail := func(err error) {\n\t\t\tlog.Print(log.Error, err)\n\t\t\tat := now.Add(time.Duration(app.Config.Scheduling.WaitTime) * time.Minute)\n\n\t\t\t// schedule another attempt unless max attempts have been done.\n\t\t\t// if max attempts exceeded, schedule the next day's task\n\t\t\tif attempt < app.Config.Scheduling.MaxAttempts {\n\t\t\t\tlog.Printf(log.Warning, \"attempt %d to schedule scrapes for mtID=%d will retry at %s\",\n\t\t\t\t\tattempt+2, mtID, at.Format(time.UnixDate))\n\t\t\t\tapp.Scheduler.Add(scheduler.NewTask(\n\t\t\t\t\tat,\n\t\t\t\t\tScheduleScrapes(mtID, attempt+1, app)))\n\t\t\t} else {\n\t\t\t\tlog.Printf(log.Warning, \"exceeded max attempts (%d) to schedule scrapes for mtID=%d).\", attempt, mtID)\n\t\t\t\tapp.Scheduler.Add(scheduler.NewTask(\n\t\t\t\t\tstartOfNextDay(at),\n\t\t\t\t\tScheduleScrapes(mtID, 0, app)))\n\t\t\t}\n\t\t}\n\n\t\t// read mt and cams\n\t\tmt, err := db.Mountain(mtID)\n\t\tcams, err := db.CamerasOnMountain(mtID)\n\t\tif err != nil {\n\t\t\tfail(err)\n\t\t\treturn // can't continue if can't read DB\n\t\t}\n\n\t\t// get tz info for mt\n\t\ttz, err := time.LoadLocation(mt.TzLocation)\n\t\tif err != nil {\n\t\t\tfail(err)\n\t\t\treturn // can't continue if can't get tz\n\t\t}\n\t\tnow = now.In(tz) // convert time to correct tz\n\t\tlog.Printf(log.Debug, \"processing mountain %s(id=%d)\", mt.Name, mt.ID)\n\n\t\t// get astro data for mt\n\t\t// const maxTries = 3\n\t\t// var tries int\n\t\tvar sun astro.Data\n\t\t// for ; tries < maxTries; tries++ {\n\t\t// \tsun, err = astro.Get(mt.Latitude, mt.Longitude, now)\n\t\t// \tif err == nil {\n\t\t// \t\tbreak\n\t\t// \t}\n\t\t// \ttime.Sleep(3 * time.Second)\n\t\t// }\n\t\t// if tries >= maxTries {\n\t\t// \tlog.Printf(log.Error, \"too many tries to get astro data for %s(id=%d). falling back to local calculation\", mt.Name, mt.ID)\n\t\tsun, err = astro.GetLocal(mt.Latitude, mt.Longitude, now)\n\t\tif err != nil {\n\t\t\terr = errors.Wrap(err, \"using local calculation\")\n\t\t\tfail(err)\n\t\t\treturn\n\t\t}\n\t\t// } else {\n\t\t// \tlog.Printf(log.Debug, \"took %d/%d tries to get astro data for %s(id=%d)\", tries+1, maxTries, mt.Name, mt.ID)\n\t\t// }\n\n\t\t// for each cam\n\t\tfor _, cam := range cams {\n\t\t\t// skip inactive cams\n\t\t\tif !cam.IsActive {\n\t\t\t\tlog.Printf(log.Debug, \"skipping inactive cam %s(id=%d)\", cam.Name, cam.ID)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// round current time to nearest cam interval\n\t\t\tinterval := time.Duration(cam.Interval) * time.Minute\n\t\t\tstart := roundup(now, interval)\n\t\t\tstop := startOfNextDay(now)\n\t\t\tcount := 0\n\t\t\tbegin, end := start, stop\n\t\t\t// for each time+interval until end-of-day...\n\t\t\tfor t := start; t.Before(stop); t = t.Add(interval) {\n\t\t\t\t// determine if the cam should be scraped at time t\n\t\t\t\tdata := RulesData{\n\t\t\t\t\tAstro: sun,\n\t\t\t\t\tMountain: mt,\n\t\t\t\t\tCamera: cam,\n\t\t\t\t\tNow: t}\n\t\t\t\tdo, err := cam.ExecuteRules(data)\n\t\t\t\tif do {\n\t\t\t\t\t// schedule a scrape\n\t\t\t\t\tapp.Scheduler.Add(scheduler.NewTask(\n\t\t\t\t\t\tt,\n\t\t\t\t\t\tScrape(mt.ID, cam.ID, app.Config)))\n\t\t\t\t\t// record actual number of scrapes scheduled\n\t\t\t\t\t// and the true first and last times\n\t\t\t\t\tcount++\n\t\t\t\t\tif begin.IsZero() {\n\t\t\t\t\t\tbegin = t\n\t\t\t\t\t}\n\t\t\t\t\tend = t\n\t\t\t\t} else if err != nil {\n\t\t\t\t\tfail(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tlog.Printf(log.Debug, \"%d scrapes scheduled for %s(id=%d) from %s to %s every %s\",\n\t\t\t\tcount, cam.Name, cam.ID,\n\t\t\t\tbegin.Format(time.UnixDate), end.Format(time.UnixDate),\n\t\t\t\tinterval)\n\t\t}\n\n\t\t// schedule ScheduleScrapes() for next day\n\t\tnext := startOfNextDay(now)\n\t\tapp.Scheduler.Add(scheduler.NewTask(\n\t\t\tnext,\n\t\t\tScheduleScrapes(mtID, 0, app)))\n\t\tlog.Printf(log.Debug, \"next ScheduleScrapes(%s) at %s\", mt.Name, next.Format(time.UnixDate))\n\t}\n}", "func fetchClassSchedules(roomname, term string) ([]ClassSchedule, *nerr.E) {\n\n\t//we figure out the building\n\tbr := strings.Split(roomname, \"-\")\n\tvar toReturn []ClassSchedule\n\n\tvar resp ClassResponse\n\n\terr := wso2requests.MakeWSO2Request(\"GET\", fmt.Sprintf(\"https://api.byu.edu/byuapi/classes/v1?year_term=%v&building=%v&context=class_schedule\", term, br[0]), []byte{}, &resp)\n\n\tif err != nil {\n\t\treturn toReturn, err.Addf(\"Couldn't fetch class scheudle\")\n\t}\n\n\tfor i := range resp.Values {\n\t\ttoReturn = append(toReturn, resp.Values[i])\n\t}\n\n\tfor resp.Metadata.PageEnd < resp.Metadata.CollectionSize {\n\n\t\terr := wso2requests.MakeWSO2Request(\"GET\", fmt.Sprintf(\"https://api.byu.edu/byuapi/classes/v1?year_term=%v&building=%v&context=class_schedule&page_start=%v\", term, br[0], resp.Metadata.PageEnd+1), []byte{}, &resp)\n\n\t\tif err != nil {\n\t\t\treturn toReturn, err.Addf(\"Couldn't fetch class scheudle\")\n\t\t}\n\n\t\tfor i := range resp.Values {\n\t\t\ttoReturn = append(toReturn, resp.Values[i])\n\t\t}\n\t\tlog.L.Debugf(\"Have %v classes\", len(toReturn))\n\t}\n\n\treturn toReturn, nil\n}", "func FetchGameTimelines(gameURID string) (responses.GameTimelines, error) {\n var timelines responses.GameTimelines\n\n ID := urid.GetID(gameURID)\n region := urid.GetRegion(gameURID)\n\n url := createURL(region, \"match/v3/timelines/by-match/\" + ID)\n err := fetch(&timelines, url, nil)\n\n if err != nil {\n return timelines, err\n }\n\n return timelines, nil\n}", "func (q *InfluxQuery) GetAll(dateStart string) []Session {\n\n\t// Getting all activities\n\tdriveSessions := q.GetDrives(dateStart)\n\tchargeSessions := q.GetCharges(dateStart)\n\tsleepSessions := q.GetSleeps(dateStart)\n\n\ttotalSession := driveSessions\n\ttotalSession = append(totalSession, chargeSessions...)\n\ttotalSession = append(totalSession, sleepSessions...)\n\tsort.Slice(totalSession, func(i, j int) bool { return totalSession[i].Start < totalSession[j].Start })\n\n\t// Getting idle sessions\n\tvar lastEnd time.Time\n\tvar returnSession []Session\n\tfor i, v := range totalSession {\n\n\t\tstart, _ := time.Parse(time.RFC3339, v.Start)\n\t\tend, _ := time.Parse(time.RFC3339, v.End)\n\n\t\tv.Start = start.Format(\"15:04:05\")\n\t\tv.End = end.Format(\"15:04:05\")\n\n\t\tif len(totalSession) > i+1 {\n\n\t\t\tnextStart, _ := time.Parse(time.RFC3339, totalSession[i+1].Start)\n\n\t\t\tif nextStart.After(end.Add(time.Minute * 2)) {\n\n\t\t\t\treturnSession = append(returnSession, Session{\n\n\t\t\t\t\tType: \"idle\",\n\t\t\t\t\tStart: end.Format(\"15:04:05\"),\n\t\t\t\t\tEnd: nextStart.Format(\"15:04:05\"),\n\t\t\t\t\tData: q.getIdleData(end.Format(time.RFC3339), nextStart.Format(time.RFC3339)),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\treturnSession = append(returnSession, v)\n\t\tlastEnd = end\n\t}\n\n\tloc, err := time.LoadLocation(q.TimeZone)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tnow := time.Now().In(loc)\n\n\tif dateStart == now.Format(\"2006-01-02\") {\n\n\t\tif lastEnd.Add(time.Minute).Before(now) {\n\n\t\t\treturnSession = append(returnSession, Session{\n\t\t\t\tType: \"idle\",\n\t\t\t\tStart: lastEnd.Format(\"15:04:05\"),\n\t\t\t\tEnd: now.Format(\"15:04:05\"),\n\t\t\t\tData: q.getIdleData(lastEnd.Format(time.RFC3339), time.Now().Format(time.RFC3339)),\n\t\t\t})\n\t\t}\n\t}\n\n\t// Ordering and returning data\n\tsort.Slice(returnSession, func(i, j int) bool { return returnSession[i].Start < returnSession[j].Start })\n\treturn returnSession\n}", "func FetchGamesList(accountURID string, query interface{}) (responses.GamesList, error) {\n var gamesList responses.GamesList\n\n ID := urid.GetID(accountURID)\n region := urid.GetRegion(accountURID)\n\n url := createURL(region, \"match/v3/matchlists/by-account/\" + ID)\n err := fetch(&gamesList, url, query)\n\n if err != nil {\n return gamesList, err\n }\n\n return gamesList, nil\n}", "func StartSyncLoop() {\n\tinterval := time.NewTicker(30 * time.Second)\n\tquit := make(chan struct{})\n\tgo fetchGames(interval, quit)\n}", "func SearchMyMLBGames(date string, games map[int][]string, myTeamsMap map[int]string) map[int][]string {\n\tdomain := \"http://gd2.mlb.com/components/game/mlb/\"\n\tsuffix := \"/grid_ce.xml\"\n\turl := domain + date + suffix\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n\tdefer resp.Body.Close()\n\txml, err := ioutil.ReadAll(resp.Body)\n\tm, err := mxj.NewMapXml(xml)\n\n\tgameInfos, err := m.ValuesForKey(\"game\")\n\tif err != nil {\n\t\tlog.Fatal(\"err:\", err.Error())\n\t\tlog.Printf(\"MLB site '%s' response empty\", domain)\n\t\tgames[0] = []string{\"Error connecting to \" + domain}\n\t\treturn games\n\t}\n\n\t// now just manipulate Map entries returned as []interface{} array.\n\tfor k, v := range gameInfos {\n\t\tgameID := \"\"\n\t\taGameVal, _ := v.(map[string]interface{})\n\t\tif aGameVal[\"-media_state\"].(string) == \"media_dead\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t// rescan looking for keys with data: Values or Value\n\t\tgm := aGameVal[\"game_media\"].(map[string]interface{})\n\t\thb := gm[\"homebase\"].(map[string]interface{})\n\t\tmedia := hb[\"media\"].([]interface{})\n\t\tfor _, val := range media {\n\t\t\taMediaVal, _ := val.(map[string]interface{})\n\t\t\tif aMediaVal[\"-type\"].(string) != \"condensed_game\" {\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tgameID = aMediaVal[\"-id\"].(string)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif gameID != \"\" {\n\t\t\tfetchGame := false\n\n\t\t\tawayTeamIDs := aGameVal[\"-away_team_id\"].(string)\n\t\t\tawayTeamID, _ := strconv.Atoi(awayTeamIDs)\n\t\t\thomeTeamIDs := aGameVal[\"-home_team_id\"].(string)\n\t\t\thomeTeamID, _ := strconv.Atoi(homeTeamIDs)\n\t\t\tif myTeamsMap[awayTeamID] != \"\" {\n\t\t\t\tfetchGame = true\n\t\t\t} else if myTeamsMap[homeTeamID] != \"\" {\n\t\t\t\tfetchGame = true\n\t\t\t}\n\n\t\t\tif fetchGame {\n\t\t\t\t// grab mp4 URLs per game\n\t\t\t\tdetailURL := \"http://m.mlb.com/gen/multimedia/detail\" + generateDetailURL(gameID)\n\t\t\t\tgameURL := fetchGameURL(detailURL, desiredQuality)\n\n\t\t\t\tgames[k] = []string{awayTeamIDs, homeTeamIDs, gameURL}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn games\n}", "func (c *Client) GetGames(token string, options *GetGamesOptions) ([]*models.Game, error) {\n\turl := fmt.Sprintf(\"%s/games\", c.addr)\n\tif options == nil {\n\t\toptions = NoOptions\n\t}\n\tif options.ExcludeAssigned {\n\t\turl += \"?excludeAssigned=true\"\n\t}\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while building HTTP request\")\n\t}\n\treq.Header.Add(models.XAuthToken, token)\n\tres, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, ErrFetchingGames\n\t}\n\tif res.StatusCode != http.StatusOK {\n\t\tif res.StatusCode == http.StatusUnauthorized {\n\t\t\treturn nil, ErrNoAuthorization\n\t\t}\n\t\treturn nil, ErrFetchingGames\n\t}\n\n\tvar games models.GamesResponse\n\tif err := json.NewDecoder(res.Body).Decode(&games); err != nil {\n\t\treturn nil, fmt.Errorf(\"error while decoding body: %w\", err)\n\t}\n\n\treturn games.Games, nil\n}", "func statsAPIScheduleURL(time time.Time) string {\n\thost := \"https://statsapi.mlb.com\"\n\tpath := \"/api/v1/schedule\"\n\tquery := \"?language=en&sportId=1&hydrate=game(content(summary,media(epg))),linescore(runners),flags,team,review&date=\"\n\tmonth := time.Format(\"01\")\n\tday := time.Format(\"02\")\n\tyear := time.Format(\"2006\")\n\treturn host + path + query + month + \"/\" + day + \"/\" + year\n}", "func FetchGame(c *gin.Context) {\n\tcategoryID := c.Param(\"id\")\n\tif categoryID == \"\" {\n\t\tlog.Fatal(\"Category ID not found\")\n\t\tc.JSON(http.StatusNotFound, gin.H{\"result\": \"Invalid category ID\",})\n\t\treturn\n\t}\n\tdb := database.Connect()\n\tvar game []model.Game\n\tquery := db.Find(&game, categoryID)\n\tdefer query.Close()\n\n\tif len(game) == 0 {\n\t\tc.JSON(http.StatusNotFound, gin.H{\"result\": \"Games not found\"})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\"result\": query,})\n}", "func (st *SqliteStoreMatchup) GetMatchups(league *data.League, season *data.Season) ([]data.Matchup, error) {\n\tvar matchups []data.Matchup\n\trows, err := st.database.Query(`SELECT league_id, season_year, id,\n\thome, away, round, start FROM matchup WHERE league_id=? AND season_year=?`, league.ID, season.Year)\n\tif err != nil {\n\t\tfmt.Printf(\"GetMatchups query Err: %v\\n\", err)\n\t\treturn []data.Matchup{}, err\n\t}\n\tvar leagueID string\n\tvar seasonYear int\n\tvar ID string\n\tvar homeID string\n\tvar awayID string\n\tvar round int\n\tvar start string\n\tfor rows.Next() {\n\t\tmatchup := &data.Matchup{}\n\t\terr := rows.Scan(&leagueID, &seasonYear, &ID, &homeID, &awayID, &round, &start)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"GetMatchup Scan Err: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tleague, _ := st.store.League().GetLeague(leagueID)\n\t\tseason, _ := st.store.Season().GetSeason(seasonYear, league)\n\t\thome, _ := st.store.Team().GetTeam(homeID, league)\n\t\taway, _ := st.store.Team().GetTeam(awayID, league)\n\t\tmatchup.League = *league\n\t\tmatchup.Season = *season\n\t\tmatchup.ID = ID\n\t\tif home != nil {\n\t\t\tmatchup.Home = *home\n\t\t}\n\t\tif away != nil {\n\t\t\tmatchup.Away = *away\n\t\t}\n\t\tmatchup.Round = round\n\t\tmatchup.Start, err = time.Parse(time.RFC3339, start)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"GetMatchup Invalid time Err: %v\\n\", err)\n\n\t\t}\n\t\tif home != nil && away != nil {\n\t\t\tmatchup.SeasonGames, _ = st.store.Game().GetSeasonGames(league, season, home, away)\n\t\t\tmatchup.PlayoffGames, _ = st.store.Game().GetPlayoffGames(league, season, home, away)\n\t\t}\n\t\tmatchup.CalculateResult()\n\t\tmatchups = append(matchups, *matchup)\n\t}\n\trows.Close()\n\treturn matchups, nil\n}", "func pushToLocalDB(games []gm.Game) {\n\tt := time.Now()\n\n\tfor _, game := range games {\n\t\tif int64(t.Unix()) < game.AbsStart+int64(game.Duration) {\n\t\t\tif !isInLocalDB(game) {\n\t\t\t\tdb.ScheduleGame(game)\n\t\t\t}\n\t\t}\n\t}\n}", "func AllGamePending() []Game_Detail {\n\torm := get_DBFront()\n\tvar allGame, allPendingGame []Game_Detail\n\terr := orm.SetTable(\"game\").FindAll(&allGame)\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_334\", err})\n\t\treturn allGame\n\t}\n\n\tfor _, v := range allGame {\n\t\tstartTime, _ := time.Parse(layout, v.Timestarted)\n\t\ttimeNow, _ := time.Parse(layout, time.Now().String())\n\t\tif startTime.Sub(timeNow) > 15*time.Minute {\n\t\t\tallPendingGame = append(allPendingGame, v)\n\t\t}\n\t}\n\n\tSliceReverse(allPendingGame)\n\treturn allPendingGame\n}", "func (c Client) GetSchedules(stationIds []string, dates []string) ([]Schedule, error) {\n\turl := fmt.Sprint(DefaultBaseURL, APIVersion, \"/schedules\")\n\tfmt.Println(\"URL:>\", url)\n\n\t//buffer to store the json request\n\tvar buffer bytes.Buffer\n\n\t//creating the request\n\tbuffer.WriteString(\"[\")\n\tfor index, station := range stationIds {\n\t\t//fmt.Println(station)\n\t\tbuffer.WriteString(`{\"stationID\":\"`+ station + `\",\"date\":[`)\n \tfor index2, date := range dates {\n\t\t buffer.WriteString(`\"`+date+`\"`)\n\t\t if index2 != len(dates)-1 {\n\t\t\t buffer.WriteString(\",\")\n\t\t } else {\n buffer.WriteString(\"]\")\n }\n }\n\t\tif index != len(stationIds)-1 {\n\t\t\tbuffer.WriteString(\"},\")\n\t\t} else {\n buffer.WriteString(\"}\")\n }\n\t}\n\tbuffer.WriteString(\"]\")\n\n\t//setup the request\n\treq, err := http.NewRequest(\"POST\", url, &buffer)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept-Encoding\", \"deflate,gzip\")\n\treq.Header.Set(\"token\", c.Token)\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\tlog.Fatal(resp.Status)\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close() //resp.Body.Close() will run when we're finished.\n \n // decode the response\n\tvar h []Schedule\n \n // debug code\t\n //body, _ := ioutil.ReadAll(resp.Body)\n\t//fmt.Println(string(body))\n \n\t// decode the body\n\terr = json.NewDecoder(resp.Body).Decode(&h)\n\tif err != nil {\n\t\tfmt.Println(\"Error parsing schedules response\")\n\t\tlog.Fatal(err)\n\t\treturn nil, err\n\t}\n\n\treturn h, nil\n}", "func fetchAllPlayingBroadcasts() ([]*Broadcast, error) {\n\tbroadcastFinder := models.NewBroadcastFinder().IsPlaying()\n\tif err := broadcastFinder.Do(); err != nil {\n\t\treturn nil, err\n\t}\n\tmBroadcasts := broadcastFinder.Result()\n\tsrvBroadcasts := []*Broadcast{}\n\tfor i := range mBroadcasts {\n\t\tsrvBroadcast := modelBroadcastToSrvBroadcast(mBroadcasts[i])\n\t\tsrvBroadcasts = append(srvBroadcasts, srvBroadcast)\n\t}\n\treturn srvBroadcasts, nil\n}", "func (h *Handler) GetGamesList() (result string) {\n\tresult = \"<h2>Games List</h2>\\n\"\n\tresult += \" timestamp: \" + time.Now().String() + \"\\n<p>\\n\"\n\tgames := h.gPool.GetGamesList()\n\tfor _, v := range games {\n\t\tline := fmt.Sprintf(\"<li>%s: %s, %d players</li>\", v.GetID(), v.GetStatus(), v.StartPlayers)\n\t\tresult += line\n\t}\n\treturn\n}", "func soundersScheduleCollector() {\n\n\tfetchSoundersSchedule()\n\n\tc := time.Tick(24 * time.Hour)\n\tfor _ = range c {\n\t\tfetchSoundersSchedule()\n\t}\n}", "func TestGetBorrowedGamesWorking(t *testing.T) {\n\tclearTable()\n\tinsertBorrowedGame()\n\n\tapitest.New().\n\t\tDebug().\n\t\tHandler(newApp().Router).\n\t\tGet(\"/api/borrowedgames\").\n\t\tExpect(t).\n\t\tStatus(http.StatusOK).\n\t\tEnd()\n}", "func (client ScheduleClient) RequestSchedule(date string) ([]byte, error) {\n\trequestURL := client.Config.BaseURL + date + \".xml\"\n\trequest, _ := http.NewRequest(\"GET\", requestURL, nil)\n\trequest.Header.Add(\"authorization\", encodeAsBasicAuth(client.Config.User, client.Config.Password))\n\tlog.Println(\"executing request to \" + requestURL)\n\tresp, respErr := client.Client.Do(request)\n\tif respErr != nil {\n\t\tlog.Println(respErr.Error())\n\t\treturn nil, errors.New(\"HTTP Error: \" + respErr.Error())\n\t}\n\tdata, parseBodyErr := ioutil.ReadAll(resp.Body)\n\tif parseBodyErr == nil {\n\t\treturn data, nil\n\t} \n\treturn nil, errors.New(\"Parse Response Body Error: \" + parseBodyErr.Error())\n}", "func FetchGame(gameURID string) (responses.Game, error) {\n var game responses.Game\n\n ID := urid.GetID(gameURID)\n region := urid.GetRegion(gameURID)\n\n url := createURL(region, \"match/v3/matches/\" + ID)\n err := fetch(&game, url, nil)\n\n if err != nil {\n return game, err\n }\n\n return game, nil\n}", "func (db *DataBase) GetGames(userID int) (\n\tgames []models.GameInformation, err error) {\n\tvar (\n\t\ttx *sql.Tx\n\t\tURLs []string\n\t)\n\n\tif tx, err = db.Db.Begin(); err != nil {\n\t\treturn\n\t}\n\tdefer tx.Rollback()\n\n\tif URLs, err = db.getGamesURL(tx, userID); err != nil {\n\t\treturn\n\t}\n\n\tgames = make([]models.GameInformation, 0)\n\tfor _, URL := range URLs {\n\t\tvar info models.GameInformation\n\t\tif info, err = db.GetGame(URL); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tgames = append(games, info)\n\t}\n\n\terr = tx.Commit()\n\treturn\n}", "func fetchGame(request request) (*Game, *Error) {\n\tresult := &gameResponse{}\n\n\terr := httpClient.do(request, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &result.Data, nil\n}", "func DBFetchXSeasonalAnime(value int) ([]projectModels.StructureAnime, error) {\n\n\tresp, err := r.Table(\"cache_seasonal_animes\").OrderBy(r.Asc(\"id\")).Limit(value).Run(dbSession)\n\tif err != nil {\n\t\treturn []projectModels.StructureAnime{}, err\n\t}\n\n\tif resp.IsNil() {\n\t\treturn []projectModels.StructureAnime{}, errors.New(\"Empty Result\")\n\t}\n\n\tvar seasonalAnimeIDs []map[string]interface{}\n\tif err = resp.All(&seasonalAnimeIDs); err != nil {\n\t\treturn []projectModels.StructureAnime{}, err\n\t}\n\n\terr = resp.Close()\n\tcommon.CheckErrorAndPanic(err)\n\n\tvar animelist []projectModels.StructureAnime\n\tfor _, v := range seasonalAnimeIDs {\n\t\tres, err := r.Table(\"animes\").Filter(map[string]interface{}{\n\t\t\t\"id\": v[\"malID\"].(string),\n\t\t}).Run(dbSession)\n\t\tif err != nil {\n\t\t\treturn []projectModels.StructureAnime{}, err\n\t\t}\n\t\tif res.IsNil() {\n\t\t\treturn []projectModels.StructureAnime{}, errors.New(\"Empty Result\")\n\t\t}\n\t\tvar anime projectModels.StructureAnime\n\t\tif err = res.One(&anime); err != nil {\n\t\t\treturn []projectModels.StructureAnime{}, err\n\t\t}\n\t\terr = res.Close()\n\t\tcommon.CheckErrorAndPanic(err)\n\n\t\tanimelist = append(animelist, anime)\n\t}\n\n\tif len(animelist) == 0 {\n\t\treturn []projectModels.StructureAnime{}, errors.New(\"Empty Result\")\n\t}\n\treturn animelist, nil\n}", "func (g *Gamefeed) Sync() ([]Event, error) {\n\turl := fmt.Sprintf(\"%s/gamefeed.json\", APIURL)\n\tg.LastID = settings.Settings.IRE.LastID\n\tif g.LastID > 0 {\n\t\turl = fmt.Sprintf(\"%s?id=%d\", url, g.LastID)\n\t}\n\n\tvar deathsights []Event\n\n\tif !settings.Settings.IRE.DeathsightEnabled { // Oops, we're disabled, bail out\n\t\treturn deathsights, nil\n\t}\n\n\tif err := httpclient.GetJSON(url, &g.Events); err == nil {\n\t\tfor _, event := range *g.Events {\n\t\t\tgo logEvent(event)\n\t\t\tif event.ID > g.LastID {\n\t\t\t\tg.LastID = event.ID\n\t\t\t}\n\n\t\t\tif event.Type == \"DEA\" {\n\t\t\t\tdeathsights = append(deathsights, event)\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn nil, err // Error at httpclient.GetJSON() call\n\t}\n\n\tsettings.Settings.Lock()\n\tdefer settings.Settings.Unlock()\n\tsettings.Settings.IRE.LastID = g.LastID\n\tsort.Sort(eventsByDate(deathsights))\n\treturn deathsights, nil\n}", "func (a *SchedulesAPI) RequestAvailableSchedules() (res AvailableSchedulesResponse, err error) {\n\tparams := initSchedulesRequest(\"scheds\")\n\terr = params.requestAPI(a, &res)\n\treturn\n}", "func (l *RemoteProvider) GetSchedules(req *http.Request, page, pageSize, order string) ([]byte, error) {\n\tif !l.Capabilities.IsSupported(PersistSchedules) {\n\t\tlogrus.Error(\"operation not available\")\n\t\treturn []byte{}, ErrInvalidCapability(\"PersistSchedules\", l.ProviderName)\n\t}\n\n\tep, _ := l.Capabilities.GetEndpointForFeature(PersistSchedules)\n\n\tlogrus.Infof(\"attempting to fetch schedules from cloud\")\n\n\tremoteProviderURL, _ := url.Parse(l.RemoteProviderURL + ep)\n\tq := remoteProviderURL.Query()\n\tif page != \"\" {\n\t\tq.Set(\"page\", page)\n\t}\n\tif pageSize != \"\" {\n\t\tq.Set(\"page_size\", pageSize)\n\t}\n\tif order != \"\" {\n\t\tq.Set(\"order\", order)\n\t}\n\tremoteProviderURL.RawQuery = q.Encode()\n\tlogrus.Debugf(\"constructed schedules url: %s\", remoteProviderURL.String())\n\tcReq, _ := http.NewRequest(http.MethodGet, remoteProviderURL.String(), nil)\n\n\ttokenString, err := l.GetToken(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := l.DoRequest(cReq, tokenString)\n\tif err != nil {\n\t\treturn nil, ErrFetch(err, \"Perf Schedule Page\", resp.StatusCode)\n\t}\n\tdefer func() {\n\t\t_ = resp.Body.Close()\n\t}()\n\tbdr, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, ErrDataRead(err, \"Perf Schedule Page\")\n\t}\n\n\tif resp.StatusCode == http.StatusOK {\n\t\tlogrus.Infof(\"schedules successfully retrieved from remote provider\")\n\t\treturn bdr, nil\n\t}\n\tlogrus.Errorf(\"error while fetching schedules: %s\", bdr)\n\treturn nil, ErrFetch(err, fmt.Sprint(bdr), resp.StatusCode)\n}", "func (t *TaskRPC) SchedList(data shared.TaskRPCData, tasks *[]shared.Task) error {\n\tstart := time.Now()\n\n\tconn := Connections.Get(data.Channel)\n\n\t// Read the sites that this user has access to\n\terr := DB.SQL(`select \n\t\tt.*,\n\t\tm.name as machine_name,\n\t\ts.name as site_name,s.id as site_id,\n\t\tu.username as username\n\t\tfrom task t \n\t\t\tleft join machine m on m.id=t.machine_id\n\t\t\tleft join site s on s.id=m.site_id\n\t\t\tleft join users u on u.id=t.assigned_to\n\t\twhere t.sched_id=$1\n\t\torder by t.startdate`, data.ID).\n\t\tQueryStructs(tasks)\n\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t}\n\n\tfor k, v := range *tasks {\n\n\t\t// trim the descr field\n\t\tif len(v.Descr) > 80 {\n\t\t\t(*tasks)[k].Descr = v.Descr[:80] + \"...\"\n\t\t}\n\n\t\t// Get the latest thumbnails for this task, if present\n\t\tphotos := []shared.Photo{}\n\t\tDB.SQL(`select id,thumb \n\t\t\tfrom photo \n\t\t\twhere (entity='task' and entity_id=$1) \n\t\t\tor (entity='event' and entity_id=$2) \n\t\t\tor (entity='sched' and entity_id=$3) \n\t\t\torder by type,id desc`, v.ID, v.EventID, v.SchedID).\n\t\t\tQueryStructs(&photos)\n\t\t(*tasks)[k].Photos = photos\n\t}\n\n\tlogger(start, \"Task.SchedList\",\n\t\tfmt.Sprintf(\"Sched %d\", data.ID),\n\t\tfmt.Sprintf(\"%d Tasks\", len(*tasks)),\n\t\tdata.Channel, conn.UserID, \"task\", 0, false)\n\n\treturn nil\n}", "func search(schedules chan<- schedule.Schedule, cronConfig *config.Config) {\n\t// @I Support different sources of candidate Schedules configurable via JSON\n\t// or YAML\n\n\t// Create Redis Storage.\n\tstorage, err := storage.Create(cronConfig.Storage)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// The duration of the search interval.\n\tinterval, err := time.ParseDuration(cronConfig.SearchInterval)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tcandidateSchedules, err := storage.Search(interval)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor _, schedule := range candidateSchedules {\n\t\tschedules <- *schedule\n\t}\n\n\t// Repeat the search after the defined search interval.\n\ttime.Sleep(interval)\n\tsearch(schedules, cronConfig)\n}", "func (db *BotDB) GetSchedule(guild uint64) []ScheduleEvent {\n\tq, err := db.sqlGetSchedule.Query(guild)\n\tif db.CheckError(\"GetSchedule\", err) != nil {\n\t\treturn []ScheduleEvent{}\n\t}\n\tdefer q.Close()\n\tr := make([]ScheduleEvent, 0, 2)\n\tfor q.Next() {\n\t\tp := ScheduleEvent{}\n\t\tif err := q.Scan(&p.ID, &p.Date, &p.Type, &p.Data); err == nil {\n\t\t\tr = append(r, p)\n\t\t}\n\t}\n\treturn r\n}", "func getCompMatches(c *gin.Context) {\n\tcompID := c.Param(\"id\")\n\n\tvar request struct {\n\t\tLimit *int `form:\"limit\"`\n\t\tFrom *time.Time `form:\"from\"`\n\t\tTo *time.Time `form:\"to\"`\n\t}\n\n\tif !tryGetRequest(c, &request) {\n\t\treturn\n\t}\n\n\tsqlStatement := `SELECT id, start_date, end_date, winner_id FROM match\n\tLEFT JOIN match_result ON match.id = match_result.match_id\n\tWHERE match.comp_id = $1 and (start_date >= $2 or $2 is NULL) and (end_date >= $3 or $3 is NULL)\n\tORDER BY end_date DESC\n\tLIMIT $4`\n\n\trows, err := db.Query(sqlStatement, compID, request.From, request.To, request.Limit)\n\n\tif handleError(err, c) {\n\t\treturn\n\t}\n\n\tvar matchResponse struct {\n\t\tMatches []Match `json:\"matches\"`\n\t}\n\tmatchResponse.Matches = []Match{}\n\tfor rows.Next() {\n\t\tvar match Match\n\t\terr = rows.Scan(&match.MatchID, &match.StartDate, &match.EndDate, &match.WinnerID)\n\t\tif err != nil {\n\t\t\tprintln(err.Error())\n\t\t}\n\n\t\tmatch.Player1, match.Player2 = getPlayersFromMatch(match.MatchID)\n\n\t\tscore := MatchScore{}\n\t\tscore.Player1, score.Player2 = getMatchScore(match.MatchID, match.Player1.Id, match.Player2.Id)\n\t\tmatch.Score = &score\n\n\t\tmatchResponse.Matches = append(matchResponse.Matches, match)\n\t}\n\n\tc.JSON(http.StatusOK, matchResponse)\n}", "func availableGames(gameInstallation GameInstallation) []Game {\n\tvar games []Game\n\n\tfiles, err := ioutil.ReadDir(gameInstallation.SavedGamesPath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, f := range files {\n\t\tif _, valid := ValidGameName(f.Name()); valid {\n\t\t\tgame, err := NewGame(f.Name(), path.Join(gameInstallation.SavedGamesPath, f.Name()))\n\t\t\tif err == nil {\n\t\t\t\tgames = append(games, *game)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn games\n}", "func (h *HLTB) SearchGame(ctx context.Context, query string) (*Game, error) {\n\tresp, err := ctxhttp.PostForm(ctx, h.cli, \"https://howlongtobeat.com/search_results?page=1\", queryForm(query))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif !apiclient.IsOK(resp.StatusCode) {\n\t\treturn nil, &apiclient.Error{API: \"hltb\", StatusCode: resp.StatusCode}\n\t}\n\n\tpage, err := html.Parse(resp.Body)\n\tif err != nil {\n\t\treturn nil, &apiclient.Error{API: \"hltb\", Err: err}\n\t}\n\n\tnoResults, err := htmlquery.Query(page, \"//li[contains(text(), 'No results for')]\")\n\tif err != nil {\n\t\treturn nil, &apiclient.Error{API: \"hltb\", Err: err}\n\t}\n\tif noResults != nil {\n\t\treturn nil, errNotFound\n\t}\n\n\ttitle, err := htmlquery.Query(page, \"//div[@class='search_list_details']/*/a\")\n\tif err != nil {\n\t\treturn nil, &apiclient.Error{API: \"hltb\", Err: err}\n\t}\n\tif title == nil {\n\t\treturn nil, errNotFound\n\t}\n\n\tvar game Game\n\n\tpath, err := htmlquery.Query(page, \"//div[@class='search_list_details']/*/a/@href\")\n\tif err != nil {\n\t\treturn nil, &apiclient.Error{API: \"hltb\", Err: err}\n\t}\n\tif p := trimmedInner(path); p != \"\" {\n\t\tgame.URL = \"https://howlongtobeat.com/\" + p\n\t}\n\n\ttimes, err := htmlquery.QueryAll(page, \"//div[contains(@class, 'search_list_tidbit')]\")\n\tif err != nil {\n\t\treturn nil, &apiclient.Error{API: \"hltb\", Err: err}\n\t}\n\nFind:\n\tfor i, node := range times {\n\t\tswitch i {\n\t\tcase 1:\n\t\t\tgame.MainStory = cleanTime(node)\n\t\tcase 3:\n\t\t\tgame.MainPlusExtra = cleanTime(node)\n\t\tcase 5:\n\t\t\tgame.Completionist = cleanTime(node)\n\t\t\tbreak Find\n\t\t}\n\t}\n\n\ttitleText := trimmedInner(title)\n\n\tif titleText == \"\" || game == (Game{}) {\n\t\treturn nil, errNotFound\n\t}\n\n\tgame.Title = titleText\n\n\treturn &game, nil\n}", "func listGames(client api.HangmanClient) error {\n\tvar output string\n\n\tctx, cancel := AppContext()\n\tdefer cancel()\n\n\tr, err := client.ListGames(ctx, &api.GameRequest{Id: -1})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(r.Game) > 0 {\n\t\toutput += \"ID | \tPlyerID | Ongoing | Attempts Left | Hint \\n\"\n\t\tfor _, v := range r.Game {\n\t\t\t//TODO: this should be improved visually\n\t\t\toutput += fmt.Sprint(v.Id, \" \t\", v.PlayerId, \" \", v.Status, \"\t \", v.RetryLeft, \"\t\", v.WordMasked, \"\\n\")\n\t\t}\n\t} else {\n\t\treturn errors.New(\"No saved games on the server\")\n\t}\n\n\tfmt.Println(\"███████╗ █████╗ ██╗ ██╗███████╗██████╗ ██████╗ █████╗ ███╗ ███╗███████╗███████╗\")\n\tfmt.Println(\"██╔════╝██╔══██╗██║ ██║██╔════╝██╔══██╗ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝██╔════╝\")\n\tfmt.Println(\"███████╗███████║██║ ██║█████╗ ██║ ██║ ██║ ███╗███████║██╔████╔██║█████╗ ███████╗\")\n\tfmt.Println(\"╚════██║██╔══██║╚██╗ ██╔╝██╔══╝ ██║ ██║ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ ╚════██║\")\n\tfmt.Println(\"███████║██║ ██║ ╚████╔╝ ███████╗██████╔╝ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗███████║\")\n\tfmt.Println(\"╚══════╝╚═╝ ╚═╝ ╚═══╝ ╚══════╝╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚══════╝\")\n\tfmt.Println(\" \")\n\n\tfmt.Println(output)\n\treturn nil\n}", "func GetLeagueStandings(leagueID string) error {\n\turl := apiRoot + \"FetchLeagueStandings\" + getFiltering(leagueID)\n\tresult, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"standings: %v\\n\", result)\n\treturn nil\n}", "func ScheduleRefresh(scheduleConfig ScheduleConfig) {\n\tschedule := gocron.NewScheduler(time.UTC)\n\tclient = newClient()\n\n\tschedule.Every(scheduleConfig.HCSSTokenRefreshInterval).Minutes().Do(func() {\n\t\tlog.Println(\"Refreshing access token...\")\n\t\tclient = newClient()\n\t})\n\tschedule.Every(scheduleConfig.JobRefreshInterval).Minutes().Do(refreshJobs)\n\tschedule.Every(scheduleConfig.EmployeeRefreshInterval).Minutes().Do(refreshEmployees)\n\tschedule.Every(scheduleConfig.EquipmentRefreshInterval).Minutes().Do(refreshEquipment)\n\tschedule.Every(scheduleConfig.TimecardRefreshInterval).Minutes().Do(refreshTimecards)\n\n\tschedule.StartAsync()\n}", "func list_featured_game(ctx *iris.Context) {\n gameshort := ctx.GetString(\"gameshort\")\n\n // Check if the game exists\n game := &objects.Game{}\n app.Database.Where(\"short = ?\", gameshort).Or(\"id = ?\", cast.ToUint(gameshort)).First(game)\n if game.Short != gameshort && game.ID != cast.ToUint(gameshort) {\n utils.WriteJSON(ctx, iris.StatusNotFound, utils.Error(\"The gameshort is invalid.\").Code(2125))\n return\n }\n\n var featured []objects.Featured\n app.Database.Find(&featured)\n output := []map[string]interface{}{}\n for _,element := range featured {\n if element.Mod.GameID == game.ID {\n output = append(output, utils.ToMap(element))\n }\n }\n utils.WriteJSON(ctx, iris.StatusOK, iris.Map{\"error\": false, \"count\": len(output), \"data\": output})\n}", "func (c Client) listGamesRequest() {\n\terr := c.encodeRequest(messages.PlayerReq{Action: game.ListGames})\n\tif err != nil {\n\t\tfmt.Fprintf(c.Output, \"unexpected error: %v \\n\", err)\n\t}\n\n\tvar resp messages.ListGamesResp\n\terr = c.decodeResponse(&resp)\n\tif err != nil {\n\t\tfmt.Fprintf(c.Output, \"unexpected error: %v\", err)\n\t}\n\n\tif resp.Error != nil {\n\t\tfmt.Fprintln(c.Output, resp.Error.Message)\n\t\treturn\n\t}\n\n\tif len(resp.Games) == 0 {\n\t\tfmt.Fprintf(c.Output, \"no games have been found. Type '%v' to start \\n\", game.NewGame)\n\t} else {\n\t\tfor _, g := range resp.Games {\n\t\t\tfmt.Fprintf(c.Output, \"Game ID: %d * Hero: %s * Characters tried: %v * Status: %v \\n\", g.GameID, g.WordToGuess, g.CharsTried, g.Status)\n\t\t}\n\t}\n}", "func (a *SchedulesAPI) RequestSpecialSchedules() (res SpecialSchedulesResponse, err error) {\n\tparams := initSchedulesRequest(\"special\")\n\terr = params.requestAPI(a, &res)\n\treturn\n}", "func (gj *Gamejam) LoadAllTeams() []Team {\n\tvar err error\n\tvar ret []Team\n\tif err = gj.m.openDB(); err != nil {\n\t\treturn ret\n\t}\n\tdefer gj.m.closeDB()\n\n\tvar tmUUIDs []string\n\ttmsPath := append(gj.mPath, \"teams\")\n\tif tmUUIDs, err = gj.m.bolt.GetBucketList(tmsPath); err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn ret\n\t}\n\tfor _, v := range tmUUIDs {\n\t\ttm, _ := gj.LoadTeam(v)\n\t\tif tm != nil {\n\t\t\tret = append(ret, *tm)\n\t\t}\n\t}\n\treturn ret\n}", "func (c *Client) Arena() (team []*CharacterStats, lastUpdate time.Time, err error) {\n\tdoc, err := c.Get(fmt.Sprintf(\"https://swgoh.gg/u/%s/\", c.profile))\n\tif err != nil {\n\t\treturn\n\t}\n\torder := make([]string, 0, 5)\n\tbasicStats := make(map[string]CharacterStats)\n\tdoc.Find(\".current-rank-team\").First().Find(\".static-char-portrait\").Each(func(i int, s *goquery.Selection) {\n\t\tcharName := s.AttrOr(\"title\", \"UNKOWN\")\n\t\tcharBasicStats := CharacterStats{\n\t\t\tName: charName,\n\t\t\tLevel: atoi(s.Find(\".char-portrait-full-level\").Text()),\n\t\t\tStars: stars(s),\n\t\t}\n\t\tbasicStats[charName] = charBasicStats\n\t\torder = append(order, charName)\n\t})\n\tfor _, name := range order {\n\t\tbasic := basicStats[name]\n\t\tif c.authorized {\n\t\t\tvar stat *CharacterStats\n\t\t\tstat, err = c.CharacterStats(name)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif stat.GearLevel < 0 {\n\t\t\t\tstat.Name = basic.Name\n\t\t\t\tstat.Level = basic.GearLevel\n\t\t\t\tstat.Stars = basic.Stars\n\t\t\t}\n\t\t\tteam = append(team, stat)\n\t\t} else {\n\t\t\tteam = append(team, &basic)\n\t\t}\n\t}\n\ttimestamp := doc.Find(\".user-last-updated .datetime\").First().AttrOr(\"data-datetime\", \"0000-00-00T00:00:00Z\")\n\tlastUpdate, err = time.Parse(time.RFC3339, timestamp)\n\treturn\n}", "func (r *SeasonsService) All(showTraktID string,extraInfo string) (seasons *Season, result *Result) {\n\tvar url *url.URL\n\tif extraInfo == \"\"{\n\t\turl, _ = showSeasonsURL.Expand(M{\"showTraktID\": showTraktID})\n\t}else {\n\t\turl, _ = showSeasonsExtendedURL.Expand(M{\"showTraktID\": showTraktID,\"extraInfo\":extraInfo})\n\t}\n\tresult = r.client.get(url, &seasons)\n\treturn\n}", "func TheBigScheduler(b config.Booking) error {\n\n\tscheduleQuery := `INSERT INTO bookings.bookings \n\t(member_id, request_level, resource, preference, given_resource, timeslot_id, start_time, end_time, public_id, application_datetime)\n\tVALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10);`\n\n\t_, err := config.Database.Query(scheduleQuery,\n\t\tb.MemberID,\n\t\tb.RequestLevel,\n\t\tb.Resource,\n\t\tb.Preference,\n\t\tb.GivenResource,\n\t\tb.TimeslotID,\n\t\tb.StartTime,\n\t\tb.EndTime,\n\t\tb.PublicID,\n\t\tb.ApplicationDateTime)\n\n\treturn err\n\n\t// TODO: Allocations\n\n}", "func (i *IDOTA2League) GetLiveGames() (*geyser.Request, error) {\n\tsm, err := i.Interface.Methods.Get(schema.MethodKey{\n\t\tName: \"GetLiveGames\",\n\t\tVersion: 1,\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq := geyser.NewRequest(i.Interface, sm)\n\n\treturn req, nil\n}", "func (c *Client) FetchSchedule(fetchMoreInfo bool) ([]Course, error) {\n\t// TODO: GET page, then check if a <form> exists, then extract the name of the radio buttons?\n\tpostData := url.Values{}\n\tpostData.Add(\"SSR_DUMMY_RECV1$sels$0\", \"0\")\n\n\tif resp, err := c.RequestPagePost(scheduleListViewPath, postData); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tdefer resp.Body.Close()\n\n\t\tcontents, err := ioutil.ReadAll(resp.Body)\n\t\tfmt.Println(string(contents))\n\n\t\tnodes, err := html.ParseFragment(resp.Body, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(nodes) != 1 {\n\t\t\treturn nil, errors.New(\"invalid number of root elements\")\n\t\t}\n\n\t\tcourses, err := parseSchedule(nodes[0])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif fetchMoreInfo {\n\t\t\tc.authLock.RLock()\n\t\t\tdefer c.authLock.RUnlock()\n\t\t\tif err := fetchExtraScheduleInfo(&c.client, courses, nodes[0]); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\treturn courses, nil\n\t}\n}", "func (s *API) GetAllSchedules(\n\tparams map[string]zoho.Parameter,\n) (data GetSchedulesResponse, err error) {\n\tendpoint := zoho.Endpoint{\n\t\tName: \"GetAllSchedules\",\n\t\tURL: fmt.Sprintf(\n\t\t\t\"https://shifts.zoho.%s/api/v1/%s/%s/%s\",\n\t\t\ts.ZohoTLD,\n\t\t\ts.OrganizationID,\n\t\t\tSettingsModule,\n\t\t\tschedulesModule,\n\t\t),\n\t\tMethod: zoho.HTTPGet,\n\t\tResponseData: &GetSchedulesResponse{},\n\t}\n\n\terr = s.Zoho.HTTPRequest(&endpoint)\n\tif err != nil {\n\t\treturn GetSchedulesResponse{}, fmt.Errorf(\"failed to retrieve schedules: %s\", err)\n\t}\n\tif v, ok := endpoint.ResponseData.(*GetSchedulesResponse); ok {\n\t\treturn *v, nil\n\t}\n\treturn GetSchedulesResponse{}, fmt.Errorf(\"data retrieved was not 'GetSchedulesResponse'\")\n}", "func RunSchedule() {\n\tgo func() {\n\t\tcount := 0\n\t\tfor {\n\t\t\ttime.Sleep(time.Hour * 4)\n\t\t\tcount++\n\t\t\tBuzzy = true\n\t\t\tif count == 12 {\n\t\t\t\tcount = 0\n\t\t\t\terr := SearchForClanIds(other.Flags, false)\n\t\t\t\tif err != nil {\n\t\t\t\t\tapiErr(\"RunSchedule\", err, \"error check SearchForClanIds\")\n\t\t\t\t\tother.DevPrint(\"ERROR: [SearchForClanIds]:\", err.Error())\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr := GetClanData()\n\t\t\t\tif err != nil {\n\t\t\t\t\tapiErr(\"RunSchedule\", err, \"error check GetClanData\")\n\t\t\t\t\tother.DevPrint(\"ERROR: [GetClanData]:\", err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t\tGetIcons()\n\t\t\tBuzzy = false\n\t\t}\n\t}()\n}", "func (s *Schedule) GetAll(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\tconn, err := db.Connect()\n\tif err != nil {\n\t\treturn common.APIError(http.StatusInternalServerError, err)\n\t}\n\n\tsession := conn.NewSession(nil)\n\tdefer session.Close()\n\tdefer conn.Close()\n\n\tif request.QueryStringParameters == nil {\n\t\trequest.QueryStringParameters = map[string]string{\n\t\t\t\"event_id\": request.PathParameters[\"id\"],\n\t\t}\n\t} else {\n\t\trequest.QueryStringParameters[\"event_id\"] = request.PathParameters[\"id\"]\n\t}\n\n\tresult, err := db.Select(session, db.TableEventSchedule, request.QueryStringParameters, Schedule{})\n\tif err != nil {\n\t\treturn common.APIError(http.StatusInternalServerError, err)\n\t}\n\n\treturn common.APIResponse(result, http.StatusOK)\n}", "func (r *Resolvers) GetGames(p graphql.ResolveParams) (interface{}, error) {\n\treturn r.db.GetGames(p.Args[\"userId\"].(string))\n}", "func ScheduledJob(city string) {\n\tgo func() {\n\t\tc := time.Tick(10 * time.Hour)\n\t\tfor range c {\n\t\t\tGetAndSaveWeatherData(city)\n\t\t}\n\t}()\n\tselect {}\n}", "func (db *Database) GetSchedule(startLocationName, destinationName, date string) ([]Trip, map[int][]TripOffering, error) {\n trips := []Trip{}\n offerings := make(map[int][]TripOffering)\n row, err := db.Query(fmt.Sprintf(\"SELECT * FROM Trip WHERE StartLocationName=%s\", startLocationName))\n if err != nil {\n return trips, offerings, err\n }\n // Get the trips with the given start location name\n trips = RowToTrips(row)\n row.Close()\n // Get the trip offerings for each trip\n for _, t := range trips {\n row, err := db.Query(fmt.Sprintf(\"SELECT * FROM TripOffering WHERE TripNumber=%d\", t.TripNumber))\n if err != nil {\n return trips, offerings, err\n }\n for row.Next() {\n var tripNumber int\n var date string\n var scheduledStartTime string\n var scheduledArrivalTime string\n var driverName string\n var busID int\n row.Scan(&tripNumber, &date, &scheduledStartTime, &scheduledArrivalTime, &driverName, &busID)\n if _, ok := offerings[tripNumber]; !ok {\n offerings[tripNumber] = []TripOffering{}\n }\n offerings[tripNumber] = append(offerings[tripNumber], TripOffering{\n TripNumber: tripNumber,\n Date: date,\n ScheduledStartTime: scheduledStartTime,\n ScheduledArrivalTime: scheduledArrivalTime,\n DriverName: driverName,\n BusID: busID,\n })\n }\n row.Close()\n }\n return trips, offerings, nil\n}", "func getFullBuilds(c context.Context, masterName, builderName string, finished bool) ([]*buildbotBuild, error) {\n\t// TODO(hinoka): Builder specific structs.\n\tq := ds.NewQuery(\"buildbotBuild\")\n\tq = q.Eq(\"finished\", finished)\n\tq = q.Eq(\"master\", masterName)\n\tq = q.Eq(\"builder\", builderName)\n\tq = q.Order(\"-number\")\n\tq.Finalize()\n\t// Ignore the cursor, we don't need it.\n\tbuildbots, _, err := runBuildsQuery(c, q, 25)\n\treturn buildbots, err\n}", "func FetchLeaderboards(gapi interface {\n\tLeaderboards() ([]gga.Leaderboard, error)\n\tScores(gga.Leaderboard) (*gga.LeaderboardScores, error)\n}) ([]*gga.LeaderboardScores, error) {\n\n\tleaderboards, err := gapi.Leaderboards()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar boardsScores []*gga.LeaderboardScores\n\n\tvar wg sync.WaitGroup\n\tres := make(chan *gga.LeaderboardScores, len(leaderboards))\n\terrs := make(chan error, len(leaderboards))\n\n\tdefer close(errs)\n\tdefer close(res)\n\n\twg.Add(len(leaderboards))\n\n\tfor _, board := range leaderboards {\n\t\tgo func(b gga.Leaderboard) {\n\t\t\tdefer wg.Done()\n\n\t\t\tscores, err := gapi.Scores(b)\n\t\t\tif err != nil {\n\t\t\t\terrs <- err\n\t\t\t}\n\t\t\tres <- scores\n\t\t}(board)\n\t}\n\twg.Wait()\n\nFORZ:\n\tfor {\n\t\tselect {\n\t\tcase err := <-errs:\n\t\t\treturn nil, err\n\t\tcase scores := <-res:\n\t\t\tboardsScores = append(boardsScores, scores)\n\t\tdefault:\n\t\t\tbreak FORZ\n\t\t}\n\t}\n\n\treturn boardsScores, nil\n}", "func NewMasterSchedule(sch jdscheduler.Schedule, groupID primitive.ObjectID) (*MasterSchedule, error) {\n\n\townerMap := make(map[string]ScheduleMapUnit)\n\tfor i, s := range sch.Seasons {\n\t\tfor j, b := range s.Blocks {\n\t\t\tfor k, unit := range b.Units {\n\t\t\t\tscm := ScheduleMapUnit{unit.Participant, unit.Start, []int{i, j, k}}\n\t\t\t\townerMap[unit.ID.String()] = scm\n\t\t\t}\n\t\t}\n\t}\n\t// TODO: get scheudle's scheudler pick order state, create trade log\n\tms := &MasterSchedule{primitive.NilObjectID, sch, ownerMap, []Trade{}, time.Now(), groupID}\n\treturn ms, nil\n}", "func getPlayerList() (err error) {\n\tserver := strings.Builder{}\n\tfmt.Fprintf(&server, \"http://%s/players.json\", ServerAddress)\n\n\treq, err := jsonGet.Get(server.String())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer req.Body.Close()\n\n\terr = json.NewDecoder(req.Body).Decode(&ServerDetails.Players)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn\n}", "func (m *Manager) cron() {\n\tm.mutex.RLock()\n\tpeers := m.peers.Excludes(nil, 5)\n\tm.mutex.RUnlock()\n\tfor _, p := range peers {\n\t\trr, err := p.ReadRecent()\n\t\tif !log.If(err) {\n\t\t\tm.mutex.Lock()\n\t\t\tupdated, errr := m.recent.Merge(rr)\n\t\t\tm.mutex.Unlock()\n\t\t\tif !log.If(errr) && updated {\n\t\t\t\tlog.If(m.Broadcast())\n\t\t\t}\n\t\t}\n\t\trp, err := p.ReadPeers()\n\t\tif !log.If(err) {\n\t\t\tlog.If(m.AddPeers(rp))\n\t\t}\n\t\trt, err := p.ReadTags()\n\t\tif !log.If(err) {\n\t\t\tlog.If(m.AddTag(rt))\n\t\t}\n\t}\n}", "func (a *SchedulesAPI) RequestStationSchedules(orig, date string) (res StationSchedulesResponse, err error) {\n\tparams := initSchedulesRequest(\"stnsched\")\n\tparams.options[\"orig\"] = []string{orig}\n\n\tif date != \"\" {\n\t\tparams.options[\"date\"] = []string{date}\n\t}\n\n\terr = params.requestAPI(a, &res)\n\treturn\n}", "func (s *Scheduler) schedule() {\n\t// Do we have space left in our buffer?\n\tif s.CountScheduledRuns() >= schedulerBufferLimit {\n\t\t// No space left. Exit.\n\t\treturn\n\t}\n\n\t// Get scheduled pipelines but limit the returning number of elements.\n\tscheduled, err := s.storeService.PipelineGetScheduled(schedulerBufferLimit)\n\tif err != nil {\n\t\tgaia.Cfg.Logger.Debug(\"cannot get scheduled pipelines\", \"error\", err.Error())\n\t\treturn\n\t}\n\n\t// Iterate scheduled runs\n\tfor id := range scheduled {\n\t\t// If we are a server instance, we will by default give the worker the advantage.\n\t\t// Only in case all workers are busy we will schedule work on the server.\n\t\tworkers := s.memDBService.GetAllWorker()\n\t\tif gaia.Cfg.Mode == gaia.ModeServer && len(workers) > 0 {\n\t\t\t// Check if all workers are busy / inactive\n\t\t\tinvalidWorkers := 0\n\t\t\tfor _, w := range workers {\n\t\t\t\tif w.Slots == 0 || w.Status != gaia.WorkerActive {\n\t\t\t\t\tinvalidWorkers++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Insert pipeline run into memdb where all workers get their work from\n\t\t\tif len(workers) > invalidWorkers {\n\t\t\t\t// Mark them as scheduled\n\t\t\t\tscheduled[id].Status = gaia.RunScheduled\n\n\t\t\t\t// Update entry in store\n\t\t\t\terr = s.storeService.PipelinePutRun(scheduled[id])\n\t\t\t\tif err != nil {\n\t\t\t\t\tgaia.Cfg.Logger.Debug(\"could not put pipeline run into store\", \"error\", err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif err := s.memDBService.InsertPipelineRun(scheduled[id]); err != nil {\n\t\t\t\t\tgaia.Cfg.Logger.Error(\"failed to insert pipeline run into memdb via schedule\", \"error\", err.Error())\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// Check if this primary is not allowed to run work\n\t\tif gaia.Cfg.PreventPrimaryWork {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Mark them as scheduled\n\t\tscheduled[id].Status = gaia.RunScheduled\n\n\t\t// Update entry in store\n\t\terr = s.storeService.PipelinePutRun(scheduled[id])\n\t\tif err != nil {\n\t\t\tgaia.Cfg.Logger.Debug(\"could not put pipeline run into store\", \"error\", err.Error())\n\t\t\tcontinue\n\t\t}\n\n\t\t// push scheduled run into our channel\n\t\ts.scheduledRuns <- *scheduled[id]\n\t}\n}", "func refreshTimecards() error {\n\tlog.Println(\"Refreshing timecards...\")\n\tsummaries, err := client.GetTimecardSummaries(TimecardFilters{\n\t\tStartDate: common.TwoSundaysAgo(time.Now().Local()).Format(\"2006-01-02\"),\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thjTimecards := []Timecard{}\n\tfor _, summary := range summaries {\n\t\ttc, _ := client.GetTimecard(summary.ID)\n\t\thjTimecards = append(hjTimecards, tc)\n\t}\n\n\ttimecards.UpdateOrSaveManyTimecards(transformTimecards(hjTimecards))\n\treturn nil\n}", "func (s *Service) OnlineList(c context.Context) (ret *monitor.MoniRet, err error) {\n\tvar (\n\t\tmts = make([]*monitor.Monitor, 0)\n\t\tmt = &monitor.Monitor{}\n\t)\n\tif err = s.DB.Select(\"interface,count,mtime\").Where(\"app_id=?\", \"online\").Find(&mts).Error; err != nil {\n\t\tlog.Error(\"s.OnlineList query error(%v)\", err)\n\t}\n\tif len(mts) < 1 {\n\t\treturn\n\t}\n\tif err = s.DB.Where(\"app_id=?\", \"online\").First(mt).Error; err != nil {\n\t\tlog.Error(\"s.OnlineList query error(%v)\", err)\n\t}\n\treturn merge(s.packing(mts), s.times(mt.MTime), \"count\"), err\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 fetchGamesLink(link requestable, filter filter, sort *Sorting, embeds string) (*GameCollection, *Error) {\n\tif !link.exists() {\n\t\treturn &GameCollection{}, nil\n\t}\n\n\treturn fetchGames(link.request(filter, sort, embeds))\n}", "func (worker *DistinctNameWorker) MonthlyCronJob() {\n\tcurrentDay := time.Now().UTC().Unix() / SecondsForDay\n\tclient := worker.ConnPool.Get()\n\tdefer client.Close()\n\n\treply, err := client.Do(\"SMEMBERS\", \"current_month\")\n\tresults, err := redis.Values(reply, err)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, result := range results {\n\t\tresultDay, err := strconv.ParseInt(string(result.([]uint8)), 10, 32)\n\t\tif err != nil {\n\t\t\tLogError(err, \"can't parse results from redis\")\n\t\t}\n\t\tif currentDay-resultDay > 30 {\n\t\t\t//moving this day's results to monthly bucket\n\t\t\tmonthForResultDay := time.Unix(resultDay*SecondsForDay, 0).Month().String()\n\t\t\tyearForResultDay := time.Unix(resultDay*SecondsForDay, 0).Year()\n\n\t\t\t//adding this day's results to MONTH+YEAR named hash\n\t\t\tclient.Send(\"SADD\", monthForResultDay+\"-\"+string(yearForResultDay), resultDay)\n\t\t\t//removing from current_month set\n\t\t\tclient.Send(\"SREM\", \"current_month\", resultDay)\n\t\t\tclient.Flush()\n\t\t\tclient.Receive()\n\t\t\t_, err := client.Receive()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Println(\"Monthly job watcher finished job\")\n}", "func (s *Scheduler) FetchAgentSchedInfo(hostname string) (*types.AgentSchedInfo, error) {\n\ts.agentSchedInofLock.RLock()\n\tdefer s.agentSchedInofLock.RUnlock()\n\n\treturn s.store.FetchAgentSchedInfo(hostname)\n}", "func (n *NodeManager) Gets(target string, hours int64) ([]OsqueryNode, error) {\n\tvar nodes []OsqueryNode\n\tswitch target {\n\tcase \"all\":\n\t\tif err := n.DB.Find(&nodes).Error; err != nil {\n\t\t\treturn nodes, err\n\t\t}\n\tcase \"active\":\n\t\t//if err := n.DB.Where(\"updated_at > ?\", time.Now().AddDate(0, 0, -3)).Find(&nodes).Error; err != nil {\n\t\tif err := n.DB.Where(\"updated_at > ?\", time.Now().Add(time.Duration(hours)*time.Hour)).Find(&nodes).Error; err != nil {\n\t\t\treturn nodes, err\n\t\t}\n\tcase \"inactive\":\n\t\t//if err := n.DB.Where(\"updated_at < ?\", time.Now().AddDate(0, 0, -3)).Find(&nodes).Error; err != nil {\n\t\tif err := n.DB.Where(\"updated_at < ?\", time.Now().Add(time.Duration(hours)*time.Hour)).Find(&nodes).Error; err != nil {\n\t\t\treturn nodes, err\n\t\t}\n\t}\n\treturn nodes, nil\n}", "func gameManager() {\n\t//up to 100 game instances ;; should be made expanding, not fixed\n\tmax := 100\n\twidth := boardWidth //width of board\n\tboards := make([]Board, max)\n\n\tfor i := 0; i < max; i++ {\n\t\t(boards)[i].B = make([][]Spot, width)\n\t\tboards[i].Bp = 81\n\t\tboards[i].Wp = 81\n\t\tfor j := 0; j < width; j++ {\n\t\t\t((boards)[i]).B[j] = make([]Spot, width)\n\t\t}\n\t}\n\n\ta := true\n\tfor a {\n\t\tselect {\n\t\tcase inst := <- reqChan:\n\t\t\tselect {\n\t\t\tcase move := <- moveChan:\n\t\t\t\t/* rules checking occurs here ;; must add */\n\t\t\t\tif move.S == B {\n\t\t\t\t\tboards[inst].Bp--\n\t\t\t\t} else if move.S == W {\n\t\t\t\t\tboards[inst].Wp--\n\t\t\t\t}\n\t\t\t\t(boards[inst]).B[move.Y][move.X] = move.S\n\t\t\tcase act := <- activeChan:\n\t\t\t\tif boards[inst].A == Active && act == Inactive {\n\t\t\t\t\tfor i := 0; i < boardWidth; i++ {\n\t\t\t\t\t\tfor j := 0; j < boardWidth; j++ {\n\t\t\t\t\t\t\t(boards[inst]).B[i][j] = E\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\t\tboards[inst].A = act\n\t\t\t\tfmt.Printf(\"ID %d is now %v\\n\", inst, act)\n\t\t\t\t\n\t\t\tdefault: boardChan <- boards[inst]\n\t\t\t}\n\t\tcase a = <- killChan:\n\t\tcase <- getActiveChan:\t\n\t\t\tstr := \"\"\n\n\t\t\tfor i := 0; i < max; i++ {\n\t\t\t\tif(boards[i].A == Active) {\n\t\t\t\t\tstr += (sc.Itoa(i) + \",\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tstr += \"nil\"\n\n\t\t\tstrChan <- str\n\t\tdefault:\n\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t}\n\t}\n}", "func GetADVSchedules(id string, addr string, localIP string) error {\r\n\tlocalAddr, err := net.ResolveIPAddr(\"ip\", localIP)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\tLocalBindAddr := &net.TCPAddr{IP: localAddr.IP}\r\n\ttransport := &http.Transport{\r\n\t\tDial: (&net.Dialer{\r\n\t\t\tLocalAddr: LocalBindAddr,\r\n\t\t\tTimeout: 5 * time.Second,\r\n\t\t\tKeepAlive: 30 * time.Second,\r\n\t\t}).Dial,\r\n\t}\r\n\tclient := &http.Client{\r\n\t\tTransport: transport,\r\n\t}\r\n\r\n\turl := \"http://\" + addr + \"/adm/adv-schedules/\" + id + \"?format=cic\"\r\n\r\n\treq, err := http.NewRequest(\"GET\", url, nil)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\tresp, err := client.Do(req)\r\n\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\tif resp.StatusCode != 200 {\r\n\t\treturn fmt.Errorf(\"ADM Receved %v\", resp.Status)\r\n\t}\r\n\r\n\tfor {\r\n\t\tbuf := make([]byte, 32*1024)\r\n\t\t_, err := resp.Body.Read(buf)\r\n\r\n\t\tif err != nil && err != io.EOF {\r\n\t\t\treturn err\r\n\t\t}\r\n\r\n\t\tif err == io.EOF {\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n\tresp.Body.Close()\r\n\ttransport.CloseIdleConnections()\r\n\r\n\treturn nil\r\n}", "func (db *BotDB) GetEvents(guild uint64, maxnum int) []ScheduleEvent {\n\tq, err := db.sqlGetEvents.Query(guild, maxnum)\n\tif db.CheckError(\"GetEvents\", err) != nil {\n\t\treturn []ScheduleEvent{}\n\t}\n\tdefer q.Close()\n\tr := make([]ScheduleEvent, 0, 2)\n\tfor q.Next() {\n\t\tp := ScheduleEvent{}\n\t\tif err := q.Scan(&p.ID, &p.Date, &p.Type, &p.Data); err == nil {\n\t\t\tr = append(r, p)\n\t\t}\n\t}\n\treturn r\n}", "func getFetchers(orm *model.Orm) map[string]lib.FetchManager {\n\tfetch := make(map[string]lib.FetchManager)\n\tnbaFetcher := nba.Fetcher{*year, &fetchers.HttpFetcher{\"NBA\", make(map[string]string)}}\n\tnbaFetcher.FetchMethod.AddUrlParam(\"api_key\", \"8uttxzxefmz45ds8ckz764vr\")\n\tfetch[\"NBA\"] = &nba.FetchManager{Orm: *orm, Fetcher: nbaFetcher, Sport: lib.Sports[\"NBA\"]}\n\t/*\n\t\tnflFetcher := nfl.Fetcher{*year, &fetchers.HttpFetcher{\"NFL\", make(map[string]string)}}\n\t\tnflFetcher.FetchMethod.AddUrlParam(\"api_key\", \"dmefnmpwjn7nk6uhbhgsnxd6\")\n\t\tfetch[\"NFL\"] = &nfl.FetchManager{Orm: *orm, Fetcher: nflFetcher, Sport: lib.Sports[\"NFL\"]}\n\t*/\n\treturn fetch\n}", "func GetCurrentRuns(req *http.Request, params martini.Params, r render.Render) {\n\ttype AllPendingRuns struct {\n\t\tCurrentRuns []structs.PendingRun `json:\"current_runs\"`\n\t\tCurrentCronRuns []structs.PendingCronRun `json:\"current_cron_runs\"`\n\t}\n\n\truns, err := dbstore.GetCurrentRuns()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tr.JSON(500, map[string]interface{}{\"response\": err})\n\t\treturn\n\t}\n\n\tcronRuns, err := dbstore.GetCurrentCronRuns()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tr.JSON(500, map[string]interface{}{\"response\": err})\n\t\treturn\n\t}\n\n\tvar resp AllPendingRuns\n\tresp.CurrentCronRuns = cronRuns\n\tresp.CurrentRuns = runs\n\n\tr.JSON(200, resp)\n}", "func getCompPlayers(c *gin.Context) {\n\tid := c.Param(\"id\")\n\tsqlStatement := `SELECT id, first_name, last_name, is_admin FROM player \n\tLEFT JOIN comp_reg ON id=comp_reg.player_id\n\tWHERE comp_reg.comp_id=$1 and (comp_reg.pending != true or comp_reg.pending is null);`\n\tqueryPlayers(c, sqlStatement, id)\n}", "func (s *GameServer) startRound(now time.Time) {\n\tvar ids []PlayerId\n\tfor id := range s.players {\n\t\tids = append(ids, id)\n\t}\n\trand.Shuffle(len(ids), func(i, j int) {\n\t\tids[i], ids[j] = ids[j], ids[i]\n\t})\n\n\ts.matchups = nil\n\tfor i := 0; i < len(ids)-1; i += 2 {\n\t\ts.matchups = append(s.matchups, &Matchup{\n\t\t\tPlayers: [2]PlayerId{ids[i], ids[i+1]},\n\t\t})\n\t}\n\n\ts.phase = PhasePicking\n\ts.phaseDeadline = now.Add(time.Second * 10)\n}", "func CronJob() {\n\tfor i := 0; i < 10; i++ {\n\t\tGetTime()\n\t\ttime.Sleep(5 * 60 * 1000 * time.Millisecond)\n \t}\n\n}", "func (r *Repository) GetGames() ([]Game, error) {\n\tgames := []Game{}\n\t//paging ignored for the timebeing\n\tquery := \"SELECT id, board, status, computer_mark FROM games\"\n\trows, err := r.db.Query(query)\n\n\tif err != nil {\n\t\tlogger.Error(\"failed to get games from db\", zap.Error(err))\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tgame := Game{}\n\t\terr = rows.Scan(&game.ID, &game.Board, &game.Status, &game.ComputerMark)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"failed to scan game row\", zap.Error(err))\n\t\t\tcontinue\n\t\t}\n\t\tgames = append(games, game)\n\t}\n\treturn games, nil\n}", "func (db *Database) GetDriverWeeklySchedule(driverName string, date string) ([]TripOffering, error) {\n result := []TripOffering{}\n sameWeek := func(t1, t2 *time.Time) bool {\n year1, week1 := t1.ISOWeek()\n year2, week2 := t2.ISOWeek()\n return year1 == year2 && week1 == week2\n }\n row, err := db.Query(\"SELECT * FROM TripOffering WHERE DriverName=%q\", driverName)\n if err != nil {\n return result, err\n }\n defer row.Close()\n date1, err := time.Parse(DATE_FORMAT, date)\n if err != nil {\n return result, err\n }\n if err != nil {\n return result, err\n }\n for row.Next() {\n var tripNumber int\n var date string\n var scheduledStartTime string\n var scheduledArrivalTime string\n var driverName string\n var busID int\n row.Scan(&tripNumber, &date, &scheduledStartTime, &scheduledArrivalTime, &driverName, &busID)\n date2, err := time.Parse(DATE_FORMAT, date)\n if err != nil {\n log.Fatal(err)\n }\n if sameWeek(&date1, &date2) {\n result = append(result, TripOffering{\n TripNumber: tripNumber,\n Date: date,\n ScheduledStartTime: scheduledStartTime,\n ScheduledArrivalTime: scheduledArrivalTime,\n DriverName: driverName,\n BusID: busID,\n })\n }\n }\n return result, nil\n}", "func Update() {\n\ttick1 := time.Tick(1e9) // 1 second\n\tfor {\n\t\tselect {\n\t\tcase <-tick1:\n\t\t\t// go slotgame.Update()\n\t\t\tfor _, event := range eventList {\n\t\t\t\tif event.IsLaunch {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdb.SQLSelect()\n\t}\n}", "func (l *RemoteProvider) GetSchedule(req *http.Request, scheduleID string) ([]byte, error) {\n\tif !l.Capabilities.IsSupported(PersistSchedules) {\n\t\tlogrus.Error(\"operation not available\")\n\t\treturn nil, ErrInvalidCapability(\"PersistSchedules\", l.ProviderName)\n\t}\n\n\tep, _ := l.Capabilities.GetEndpointForFeature(PersistSchedules)\n\n\tlogrus.Infof(\"attempting to fetch schedule from cloud for id: %s\", scheduleID)\n\n\tremoteProviderURL, _ := url.Parse(fmt.Sprintf(\"%s%s/%s\", l.RemoteProviderURL, ep, scheduleID))\n\tlogrus.Debugf(\"constructed schedule url: %s\", remoteProviderURL.String())\n\tcReq, _ := http.NewRequest(http.MethodGet, remoteProviderURL.String(), nil)\n\n\ttokenString, err := l.GetToken(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := l.DoRequest(cReq, tokenString)\n\tif err != nil {\n\t\treturn nil, ErrFetch(err, \"Perf Schedule :\"+scheduleID, resp.StatusCode)\n\t}\n\tdefer func() {\n\t\t_ = resp.Body.Close()\n\t}()\n\tbdr, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, ErrDataRead(err, \"Perf Schedule :\"+scheduleID)\n\t}\n\n\tif resp.StatusCode == http.StatusOK {\n\t\tlogrus.Infof(\"schedule successfully retrieved from remote provider\")\n\t\treturn bdr, nil\n\t}\n\treturn nil, ErrFetch(err, fmt.Sprint(bdr), resp.StatusCode)\n}", "func (a *SchedulesAPI) RequestHolidaySchedules() (res HolidaySchedulesResponse, err error) {\n\tparams := initSchedulesRequest(\"holiday\")\n\terr = params.requestAPI(a, &res)\n\treturn\n}", "func (r *Room) StartGame() {\n\tif r.Status != Waiting || r.board == nil {\n\t\treturn\n\t}\n\tr.Status = Started\n\tch := make(chan Update)\n\tend := time.NewTicker(r.board.Life()).C\n\tgo r.board.Start(r.in, ch)\n\tfor {\n\t\tselect {\n\t\tcase update := <-ch:\n\t\t\tif update.Status == Winner {\n\t\t\t\tr.Status = Ended\n\t\t\t\tgo SendUpdate(r.out, update)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tgo SendUpdate(r.out, update)\n\t\tcase <-end:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (sched *Scheduler) scanFromDB() ([]*mail.EmailContent, error) {\n\tvar resp []*mail.EmailContent\n\t// fromTime := time.Now().Add(-time.Minute * 2) // subtract by 2 minutes - why not one?\n\n\ttype UUU struct {\n\t\tID uint `json:\"id\"`\n\t\tCustomerName string `json:\"customer_name\"`\n\t\tEmail string `json:\"email\"`\n\t}\n\tvar uuu UUU\n\trows, err := sched.db.Raw(\"SELECT id, customer_name, email FROM ecommerce.orders WHERE thank_you_email_sent = ?;\", false).Rows()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil, err\n\t}\n\t// MUST to call this function at the end to free connection to mysql\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(&uuu.ID, &uuu.CustomerName, &uuu.Email)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Cannot scan row due to error: \", err)\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Println(\"vao: \", uuu.Email)\n\t\tresp = append(resp, &mail.EmailContent{\n\t\t\tID: int64(uuu.ID),\n\t\t\tSubject: DefaultThankyouSubject,\n\t\t\tPlainTextContent: DefaultThankyouBodyPlain,\n\t\t\tHtmlContent: DefaultThankyouBodyHtml,\n\t\t\tToUser: &mail.EmailUser{\n\t\t\t\tName: uuu.CustomerName,\n\t\t\t\tEmail: uuu.Email,\n\t\t\t},\n\t\t})\n\t}\n\treturn resp, nil\n}", "func getMonsters(env Environment, cr int) []Monster {\n\tcandidates := make([]Monster,10)\n\tfor name, mon := range monsterCache {\n\t\tcrInt, _ := strconv.Atoi(mon.Challenge_Rating)\n\t\tif crInt == cr {\n\t\t\tcandidates = append(candidates, mon)\n\t\t\tfmt.Println(name)\n\t\t}\n\t}\n\n\treturn candidates\n}", "func (j *DSRocketchat) FetchItems(ctx *Ctx) (err error) {\n\tvar (\n\t\tdateFrom time.Time\n\t\tsDateFrom string\n\t)\n\tif ctx.DateFrom != nil {\n\t\tdateFrom = *ctx.DateFrom\n\t} else {\n\t\tdateFrom = DefaultDateFrom\n\t}\n\tsDateFrom = ToESDate(dateFrom)\n\trateLimit, rateLimitReset := -1, -1\n\tcacheDur := time.Duration(48) * time.Hour\n\turl := j.URL + \"/api/v1/channels.info?roomName=\" + neturl.QueryEscape(j.Channel)\n\tmethod := Get\n\theaders := map[string]string{\"X-User-ID\": j.User, \"X-Auth-Token\": j.Token}\n\tvar (\n\t\tres interface{}\n\t\tstatus int\n\t\toutHeaders map[string][]string\n\t)\n\tthrN := GetThreadsNum(ctx)\n\tsleeps, rates := 0, 0\n\tfor {\n\t\terr = SleepForRateLimit(ctx, j, rateLimit, rateLimitReset, j.MinRate, j.WaitRate)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t// curl -s -H 'X-Auth-Token: token' -H 'X-User-ID: user' URL/api/v1/channels.info?roomName=channel | jq '.'\n\t\t// 48 hours for caching channel info\n\t\tres, status, _, outHeaders, err = Request(\n\t\t\tctx,\n\t\t\turl,\n\t\t\tmethod,\n\t\t\theaders,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\tmap[[2]int]struct{}{{200, 200}: {}, {429, 429}: {}}, // JSON statuses: 200, 429\n\t\t\tnil, // Error statuses\n\t\t\tmap[[2]int]struct{}{{200, 200}: {}, {429, 429}: {}}, // OK statuses: 200, 429\n\t\t\tmap[[2]int]struct{}{{200, 200}: {}}, // Cache statuses: 200\n\t\t\ttrue, // retry\n\t\t\t&cacheDur, // cache duration\n\t\t\tfalse, // skip in dry-run mode\n\t\t)\n\t\trateLimit, rateLimitReset, _ = UpdateRateLimit(ctx, j, outHeaders, \"\", \"\")\n\t\t// Rate limit\n\t\tif status == 413 {\n\t\t\trates++\n\t\t\tcontinue\n\t\t}\n\t\t// Too many requests\n\t\tif status == 429 {\n\t\t\tsleeps++\n\t\t\tj.SleepAsRequested(res, thrN)\n\t\t\tcontinue\n\t\t}\n\t\tif sleeps > 0 || rates > 0 {\n\t\t\tPrintf(\"recovered after %d sleeps and %d rate limits\\n\", sleeps, rates)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tbreak\n\t}\n\tchannelInfo, ok := res.(map[string]interface{})[\"channel\"]\n\tif !ok {\n\t\tdata, _ := res.(map[string]interface{})\n\t\terr = fmt.Errorf(\"cannot read channel info from:\\n%s\", data)\n\t\treturn\n\t}\n\t// Process messages (possibly in threads)\n\tvar (\n\t\tch chan error\n\t\tallMsgs []interface{}\n\t\tallMsgsMtx *sync.Mutex\n\t\tescha []chan error\n\t\teschaMtx *sync.Mutex\n\t)\n\tif thrN > 1 {\n\t\tch = make(chan error)\n\t\tallMsgsMtx = &sync.Mutex{}\n\t\teschaMtx = &sync.Mutex{}\n\t}\n\tnThreads := 0\n\tprocessMsg := func(c chan error, item map[string]interface{}) (wch chan error, e error) {\n\t\tdefer func() {\n\t\t\tif c != nil {\n\t\t\t\tc <- e\n\t\t\t}\n\t\t}()\n\t\tesItem := j.AddMetadata(ctx, item)\n\t\tif ctx.Project != \"\" {\n\t\t\titem[\"project\"] = ctx.Project\n\t\t}\n\t\tesItem[\"data\"] = item\n\t\tif allMsgsMtx != nil {\n\t\t\tallMsgsMtx.Lock()\n\t\t}\n\t\tallMsgs = append(allMsgs, esItem)\n\t\tnMsgs := len(allMsgs)\n\t\tif nMsgs >= ctx.ESBulkSize {\n\t\t\tsendToElastic := func(c chan error) (ee error) {\n\t\t\t\tdefer func() {\n\t\t\t\t\tif c != nil {\n\t\t\t\t\t\tc <- ee\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t\tee = SendToElastic(ctx, j, true, UUID, allMsgs)\n\t\t\t\tif ee != nil {\n\t\t\t\t\tPrintf(\"error %v sending %d messages to ElasticSearch\\n\", ee, len(allMsgs))\n\t\t\t\t}\n\t\t\t\tallMsgs = []interface{}{}\n\t\t\t\tif allMsgsMtx != nil {\n\t\t\t\t\tallMsgsMtx.Unlock()\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif thrN > 1 {\n\t\t\t\twch = make(chan error)\n\t\t\t\tgo func() {\n\t\t\t\t\t_ = sendToElastic(wch)\n\t\t\t\t}()\n\t\t\t} else {\n\t\t\t\te = sendToElastic(nil)\n\t\t\t\tif e != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif allMsgsMtx != nil {\n\t\t\t\tallMsgsMtx.Unlock()\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\toffset, total := 0, 0\n\tif thrN > 1 {\n\t\tfor {\n\t\t\tvar messages []map[string]interface{}\n\t\t\tmessages, offset, total, rateLimit, rateLimitReset, err = j.GetRocketchatMessages(ctx, sDateFrom, offset, rateLimit, rateLimitReset, thrN)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor _, message := range messages {\n\t\t\t\tmessage[\"channel_info\"] = channelInfo\n\t\t\t\tgo func(message map[string]interface{}) {\n\t\t\t\t\tvar (\n\t\t\t\t\t\te error\n\t\t\t\t\t\tesch chan error\n\t\t\t\t\t)\n\t\t\t\t\tesch, e = processMsg(ch, message)\n\t\t\t\t\tif e != nil {\n\t\t\t\t\t\tPrintf(\"process error: %v\\n\", e)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif esch != nil {\n\t\t\t\t\t\tif eschaMtx != nil {\n\t\t\t\t\t\t\teschaMtx.Lock()\n\t\t\t\t\t\t}\n\t\t\t\t\t\tescha = append(escha, esch)\n\t\t\t\t\t\tif eschaMtx != nil {\n\t\t\t\t\t\t\teschaMtx.Unlock()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}(message)\n\t\t\t\tnThreads++\n\t\t\t\tif nThreads == thrN {\n\t\t\t\t\terr = <-ch\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tnThreads--\n\t\t\t\t}\n\t\t\t}\n\t\t\tif offset >= total {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tfor nThreads > 0 {\n\t\t\terr = <-ch\n\t\t\tnThreads--\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor {\n\t\t\tvar messages []map[string]interface{}\n\t\t\tmessages, offset, total, rateLimit, rateLimitReset, err = j.GetRocketchatMessages(ctx, sDateFrom, offset, rateLimit, rateLimitReset, thrN)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor _, message := range messages {\n\t\t\t\tmessage[\"channel_info\"] = channelInfo\n\t\t\t\t_, err = processMsg(nil, message)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tif offset >= total {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif eschaMtx != nil {\n\t\teschaMtx.Lock()\n\t}\n\tfor _, esch := range escha {\n\t\terr = <-esch\n\t\tif err != nil {\n\t\t\tif eschaMtx != nil {\n\t\t\t\teschaMtx.Unlock()\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\tif eschaMtx != nil {\n\t\teschaMtx.Unlock()\n\t}\n\tnMsgs := len(allMsgs)\n\tif ctx.Debug > 0 {\n\t\tPrintf(\"%d remaining messages to send to ES\\n\", nMsgs)\n\t}\n\tif nMsgs > 0 {\n\t\terr = SendToElastic(ctx, j, true, UUID, allMsgs)\n\t\tif err != nil {\n\t\t\tPrintf(\"Error %v sending %d messages to ES\\n\", err, len(allMsgs))\n\t\t}\n\t}\n\treturn\n}", "func GetMasterSite(response http.ResponseWriter, request *http.Request) {\n\t//var results MstSite\n\tvar errorResponse = ErrorResponse{\n\t\tCode: http.StatusInternalServerError, Message: \"Internal Server Error.\",\n\t}\n\n\tcollection := Client.Database(\"msdb\").Collection(\"t_mst_site\")\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tcursor, err := collection.Find(ctx, bson.M{})\n\tvar results []bson.M\n\terr = cursor.All(ctx, &results)\n\n\tdefer cancel()\n\n\tif err != nil {\n\t\terrorResponse.Message = \"Document not found\"\n\t\treturnErrorResponse(response, request, errorResponse)\n\t} else {\n\t\tvar successResponse = SuccessResponse{\n\t\t\tCode: http.StatusOK,\n\t\t\tMessage: \"Success\",\n\t\t\tResponse: results,\n\t\t}\n\n\t\tsuccessJSONResponse, jsonError := json.Marshal(successResponse)\n\n\t\tif jsonError != nil {\n\t\t\treturnErrorResponse(response, request, errorResponse)\n\t\t}\n\t\tresponse.Header().Set(\"Content-Type\", \"application/json\")\n\t\tresponse.Write(successJSONResponse)\n\t}\n\n}", "func getPlayerComps(c *gin.Context) {\n\n\tparam := c.Param(\"id\")\n\tplayerid, err := strconv.Atoi(param)\n\tif handleError(err, c) {\n\t\treturn\n\t}\n\n\tsqlStatement := `SELECT id, comp_name, is_private, creator_id, \n\t(SELECT COUNT(player_id) FROM comp_reg WHERE comp_id = id and pending = false) as totalplayers, null as pos \n\t\tFROM comp\n\t\tLEFT JOIN comp_reg ON comp.id = comp_reg.comp_id \n\t\tWHERE comp_reg.player_id = $1 and pending = false\n\t\tGROUP BY comp.id`\n\n\tres, err := getCompetitions(c, sqlStatement, playerid)\n\tif handleError(err, c) {\n\t\treturn\n\t}\n\n\t// Getting player position\n\n\tsqlStatement = `SELECT \n\tp.id,\n\t(SELECT count(winner_id)\n\tFROM match_result\n\tJOIN match ON match_id = match.id\n\tJOIN comp on match.comp_id = comp.id\n\twhere comp.id = $1 and winner_id = p.id) AS wins \n\tFROM player p\n\tJOIN match_participant mp on mp.player_id = p.id\n\tJOIN match m ON mp.match_id = m.id\n\tJOIN comp c ON c.id = m.comp_id\n\tJOIN match_result mr on mr.match_id = m.id \n\tWHERE c.id = $1\n\tGROUP BY p.id\n\tORDER BY wins DESC\n\t;`\n\n\t// For each comp\n\n\tfor index := 0; index < len(res.Competitions); index++ {\n\t\trows, err := db.Query(sqlStatement, res.Competitions[index].Id)\n\t\tif handleError(err, c) {\n\t\t\treturn\n\t\t}\n\n\t\t// For each player in comp\n\t\ti := 1\n\t\tfor rows.Next() {\n\t\t\tvar scannedID, wins int\n\t\t\terr = rows.Scan(&scannedID, &wins)\n\t\t\tif err != nil {\n\t\t\t\tprintln(err.Error())\n\t\t\t}\n\n\t\t\tif scannedID == playerid {\n\t\t\t\tres.Competitions[index].PlayerPos = &i\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\ti++\n\n\t\t}\n\t}\n\n\tc.JSON(http.StatusOK, res)\n\n}", "func getPlayers(c *gin.Context) {\n\n\tsqlStatement := `SELECT id, first_name, last_name, is_admin FROM player;`\n\tqueryPlayers(c, sqlStatement)\n}", "func (scw *SplitCloneWorker) findDestinationMasters(ctx context.Context) error {\n\tscw.setState(WorkerStateFindTargets)\n\n\t// Make sure we find a master for each destination shard and log it.\n\tscw.wr.Logger().Infof(\"Finding a MASTER tablet for each destination shard...\")\n\tfor _, si := range scw.destinationShards {\n\t\twaitCtx, waitCancel := context.WithTimeout(ctx, *waitForHealthyTabletsTimeout)\n\t\tdefer waitCancel()\n\t\tif err := scw.tsc.WaitForTablets(waitCtx, scw.cell, si.Keyspace(), si.ShardName(), []topodatapb.TabletType{topodatapb.TabletType_MASTER}); err != nil {\n\t\t\treturn fmt.Errorf(\"cannot find MASTER tablet for destination shard for %v/%v (in cell: %v): %v\", si.Keyspace(), si.ShardName(), scw.cell, err)\n\t\t}\n\t\tmasters := scw.tsc.GetHealthyTabletStats(si.Keyspace(), si.ShardName(), topodatapb.TabletType_MASTER)\n\t\tif len(masters) == 0 {\n\t\t\treturn fmt.Errorf(\"cannot find MASTER tablet for destination shard for %v/%v (in cell: %v) in HealthCheck: empty TabletStats list\", si.Keyspace(), si.ShardName(), scw.cell)\n\t\t}\n\t\tmaster := masters[0]\n\n\t\t// Get the MySQL database name of the tablet.\n\t\tkeyspaceAndShard := topoproto.KeyspaceShardString(si.Keyspace(), si.ShardName())\n\t\tscw.destinationDbNames[keyspaceAndShard] = topoproto.TabletDbName(master.Tablet)\n\n\t\t// TODO(mberlin): Verify on the destination master that the\n\t\t// _vt.blp_checkpoint table has the latest schema.\n\n\t\tscw.wr.Logger().Infof(\"Using tablet %v as destination master for %v/%v\", topoproto.TabletAliasString(master.Tablet.Alias), si.Keyspace(), si.ShardName())\n\t}\n\tscw.wr.Logger().Infof(\"NOTE: The used master of a destination shard might change over the course of the copy e.g. due to a reparent. The HealthCheck module will track and log master changes and any error message will always refer the actually used master address.\")\n\n\treturn nil\n}", "func Sync() {\n\tticker := time.NewTicker(time.Second * 30)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tallBroadcasts, err := fetchAllPlayingBroadcasts()\n\t\t\tif err != nil {\n\t\t\t\tutils.GetLog().Error(\"broadcasts.Sync.fetchAllPlayingBroadcasts error: %+v\", err)\n\t\t\t}\n\t\t\tfor _, bro := range allBroadcasts {\n\t\t\t\tbroSync := NewBroadcastSync(bro)\n\t\t\t\tif err := broSync.Do(); err != nil {\n\t\t\t\t\tutils.GetLog().Error(\"broadcasts.BroadcastSync.Do error: %+v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *GameModel) All() ([]*models.Game, error) {\n\treturn m.gamesFromQuery(`SELECT g.id, g.name, g.franchise_id, f.name AS frachise_name FROM GAMES g LEFT JOIN FRANCHISES f ON f.id = g.franchise_id`)\n}", "func Schedule(names ...string) ([]window.Schedule, error) {\n\tvar r window.Reader\n\tm, err := window.Windows(auklib.ConfDir, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(names) == 0 {\n\t\tnames = m.Keys()\n\t}\n\tdeck.Infof(\"Aggregating schedule for label(s): %s\", strings.Join(names, \", \"))\n\tvar out []window.Schedule\n\tfor i := range names {\n\t\tschedules := m.AggregateSchedules(names[i])\n\t\tvar success int64 = 1\n\t\tif len(schedules) == 0 {\n\t\t\tdeck.Errorf(\"no schedule found for label %q\", names[i])\n\t\t\tsuccess = 0\n\t\t\tcontinue\n\t\t}\n\n\t\tmetricName := fmt.Sprintf(\"%s/%s\", auklib.MetricRoot, \"schedule_retrieved\")\n\t\tmetric, err := metrics.NewInt(metricName, auklib.MetricSvc)\n\t\tif err != nil {\n\t\t\tdeck.Warningf(\"could not create metric: %v\", err)\n\t\t}\n\t\tmetric.Data.AddStringField(\"request\", names[i])\n\t\tmetric.Set(success)\n\n\t\tout = append(out, findNearest(schedules))\n\t}\n\treturn out, nil\n}", "func (gameController GameController) ReadAll(context *gin.Context) {\r\n\tvar games []models.Game\r\n\tgameController.Database.Preload(\"Players\").Preload(\"Turns\").Find(&games)\r\n\tcontext.JSON(http.StatusOK, games)\r\n}", "func Games(f *GameFilter, s *Sorting, c *Cursor, embeds string) (*GameCollection, *Error) {\n\treturn fetchGames(request{\"GET\", \"/games\", f, s, c, embeds})\n}", "func QueryGames(games *Games) error {\n\trows, err := db.DB.Query(selectAllSQL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tgame := Game{}\n\t\terr = rows.Scan(\n\t\t\t&game.ID,\n\t\t\t&game.Title,\n\t\t\t&game.CreatedAt,\n\t\t\t&game.UpdatedAt,\n\t\t\t&game.BegunAt,\n\t\t\t&game.FinishedAt,\n\t\t\t&game.Archived,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgames.Games = append(games.Games, game)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func GetPlayers(w http.ResponseWriter, req *http.Request) {\n\n\tid \t \t:= req.URL.Query().Get(\"id\")\n\tteamID \t:= req.URL.Query().Get(\"teamID\")\n\tname \t \t:= req.URL.Query().Get(\"name\")\n\tage \t \t:= strings.Split(req.URL.Query().Get(\"age\"),\"-\")\n\tposition \t:= req.URL.Query().Get(\"position\")\n\tvalue \t \t:= strings.Split(req.URL.Query().Get(\"value\"),\"-\")\n\texprValue \t:= strings.Split(req.URL.Query().Get(\"exprValue\"),\"-\")\n\texprDate \t:= strings.Split(req.URL.Query().Get(\"exprDate\"),\"-\")\n\trating \t\t:= strings.Split(req.URL.Query().Get(\"rating\"),\"-\")\n\tpotential \t:= strings.Split(req.URL.Query().Get(\"potential\"),\"-\")\n\n\tfmt.Print(\"1\")\n err := queryPlayers(id,teamID,name,age,position,value,exprValue,exprDate,rating,potential)\n\n\tif err != nil {\n\t\tfmt.Print(\"err boş değil.\")\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\n out, err := json.Marshal(playerList)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(out))\n}", "func (s *Series) Games(filter *GameFilter, sort *Sorting, embeds string) (*GameCollection, *Error) {\n\treturn fetchGamesLink(firstLink(s, \"games\"), filter, sort, embeds)\n}", "func (bt *Hackerbeat) fetchStories() ([]story, error) {\n\tresp, err := bt.httpClient.Get(getTopStoriesURL)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not get top stories from HackerNews API\")\n\t}\n\n\tbytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not read top stories response from HackerNews API\")\n\t}\n\n\tvar storyIDs []uint\n\terr = json.Unmarshal(bytes, &storyIDs)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not parse top stories response from HackerNews API\")\n\t}\n\n\tstories := make(chan story)\n\tfor _, storyID := range storyIDs[0:bt.config.NumberOfStories] {\n\t\tgo bt.fetchStory(stories, storyID)\n\t}\n\n\ttimeout := time.NewTicker(bt.config.Timeout)\n\tvar list []story\n\t// Until we reach timeout value, collect all stories from child goroutines\n\tfor {\n\t\tselect {\n\t\tcase story := <-stories:\n\t\t\tlist = append(list, story)\n\t\t\t// If all stories have been retreived, return list of stories\n\t\t\tif len(list) == bt.config.NumberOfStories {\n\t\t\t\treturn list, nil\n\t\t\t}\n\t\tcase <-timeout.C:\n\t\t\t// If timeout is reached, return all retrieved stories and warn the user\n\t\t\t// that timeout was reached\n\t\t\tbt.logger.Warnw(\n\t\t\t\t\"timeout reached when fetching stories\",\n\t\t\t\t\"timeout_value\", bt.config.Timeout.String(),\n\t\t\t)\n\t\t\treturn list, nil\n\t\t}\n\t}\n}", "func GameLoop(gs *GameService, c config.Configuration, seed int64) {\n\tsleep, err := time.ParseDuration(c.SleepBetween)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor {\n\t\ttime.Sleep(sleep)\n\t\tif c.MinimumPlayer <= len(gs.players) {\n\t\t\tlog.Print(\"New game started with \", len(gs.players), \" players\")\n\t\t\tboard, winner, err := gs.startGame(c, seed)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(\"StartGame\", err)\n\t\t\t}\n\t\t\tlog.Print(\"Game ended without errors, winner: \", board.Winner().Name)\n\t\t\tgs.total = scoreboard.Join(gs.total, *board)\n\t\t\tif winner == nil {\n\t\t\t\twinner = board.Winner()\n\t\t\t}\n\t\t\tgs.announceResult(board, winner)\n\t\t\tgs.Clean()\n\t\t}\n\t\tgs.PingPlayers()\n\t}\n}", "func main() {\n\tdate := time.Now().AddDate(0, 0, -1)\n\tdates := \"year_\" + date.Format(\"2006/month_01/day_02\")\n\n\tmyTeamsMap := InitMyTeamsMap()\n\tgames := make(map[int][]string)\n\tgames = SearchMyMLBGames(dates, games, myTeamsMap)\n\n\tdownloadedGames := downloadMyMLBGames(games, myTeamsMap)\n\tlog.Printf(\"%v\", downloadedGames)\n\n\tpushBulletAPI := os.Getenv(\"pushBulletAPI\")\n\tlog.Printf(pushBulletAPI)\n\n\t// TODO3: prepare upload_urls per game\n\n\t// TODO4: upload games to pushbullet\n\n\t// TODO5: send file via pushbullet\n}", "func (sq *allSavedQueriesCached) fetchInitialListFromFrontend() {\n\tsq.mu.Lock()\n\tdefer sq.mu.Unlock()\n\n\tattempts := 0\n\tfor {\n\t\tallSavedQueries, err := api.InternalClient.SavedQueriesListAll(context.Background())\n\t\tif err != nil {\n\t\t\tif attempts > 3 {\n\t\t\t\t// Only print the error if we've retried a few times, otherwise\n\t\t\t\t// we would be needlessly verbose when the frontend just hasn't\n\t\t\t\t// started yet but will soon.\n\t\t\t\tlog15.Error(\"executor: error fetching saved queries list (trying again in 5s)\", \"error\", err)\n\t\t\t}\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t\tattempts++\n\t\t\tcontinue\n\t\t}\n\t\tsq.allSavedQueries = make(map[string]api.SavedQuerySpecAndConfig, len(allSavedQueries))\n\t\tfor spec, config := range allSavedQueries {\n\t\t\tsq.allSavedQueries[savedQueryIDSpecKey(spec)] = api.SavedQuerySpecAndConfig{\n\t\t\t\tSpec: spec,\n\t\t\t\tConfig: config,\n\t\t\t}\n\t\t}\n\t\tlog15.Debug(\"existing saved queries detected\", \"total_saved_queries\", len(sq.allSavedQueries))\n\t\treturn\n\t}\n}" ]
[ "0.5648042", "0.55517983", "0.5492142", "0.52553743", "0.5250552", "0.52463615", "0.5244019", "0.52150124", "0.5173499", "0.51730657", "0.51409185", "0.5131815", "0.5131049", "0.5098903", "0.5086736", "0.5056043", "0.5048437", "0.50338256", "0.49914128", "0.49527743", "0.49510616", "0.4949677", "0.4943454", "0.49427053", "0.4932915", "0.49262327", "0.49034286", "0.48976964", "0.4871371", "0.4854408", "0.48317048", "0.48291683", "0.4825746", "0.48186237", "0.48160222", "0.4805532", "0.48023832", "0.47968993", "0.479327", "0.4779628", "0.4776777", "0.47574654", "0.47472665", "0.47429827", "0.47374853", "0.47368756", "0.4736104", "0.471748", "0.47125432", "0.4701223", "0.4699123", "0.4698907", "0.46887347", "0.46881598", "0.46823928", "0.46751788", "0.4662982", "0.46418622", "0.4630919", "0.46297082", "0.46290627", "0.46265283", "0.46180353", "0.46168554", "0.46049213", "0.46003824", "0.4595436", "0.4593129", "0.45886278", "0.45884553", "0.4586318", "0.45840916", "0.4578777", "0.45682004", "0.45671654", "0.45667595", "0.45652434", "0.45638093", "0.4557892", "0.45410493", "0.45344004", "0.4533543", "0.45311356", "0.4531132", "0.45298395", "0.4528861", "0.45285434", "0.45270362", "0.45232227", "0.45196852", "0.4512382", "0.45099613", "0.4497426", "0.4495367", "0.44864386", "0.44824922", "0.44818455", "0.4477294", "0.44721088", "0.44603676" ]
0.80941576
0
isInLocalDB returns true if this game already exists in the localDB
func isInLocalDB(game gm.Game) bool { dbGames := db.GetGames() for _, g := range dbGames { if game.GameID == g.GameID { return true } } return false }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func pushToLocalDB(games []gm.Game) {\n\tt := time.Now()\n\n\tfor _, game := range games {\n\t\tif int64(t.Unix()) < game.AbsStart+int64(game.Duration) {\n\t\t\tif !isInLocalDB(game) {\n\t\t\t\tdb.ScheduleGame(game)\n\t\t\t}\n\t\t}\n\t}\n}", "func (db *AppDB) Exists(t time.Time) bool {\n\tif _, err := db.Result(t); err != nil {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (b *Binary) LocalExist() bool {\n\treturn b.file.LocalExist()\n}", "func (m *MongoDB) DatabaseIsExisting() bool {\n\tif m.client == nil {\n\t\treturn false\n\t}\n\tif m.db == nil {\n\t\treturn false\n\t}\n\n\tname := m.db.Name()\n\tdatabases, _ := m.client.ListDatabaseNames(m.ctx, bson.M{})\n\treturn inStringSlice(name, databases)\n}", "func DbExists(s *mg.Session, db string) (bool) {\n names, err := s.DatabaseNames()\n if err != nil {\n return false\n }\n for _, value := range names {\n if (value == db){\n return true\n }\n }\n return false;\n}", "func IsLocalStore(s kv.Storage) bool {\n\t_, ok := s.(*dbStore)\n\treturn ok\n}", "func isDbExist(fileName string) bool {\n\t_, err := os.Stat(fileName)\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}", "func checkDbExist(db *sql.DB) bool {\n\trows, err := db.Query(\"SELECT * FROM kitemmuorts\")\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer rows.Close()\n\tif rows != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (p Database) Exists() bool {\n\tdi := &databaseInfo{}\n\treturn unmarshalURL(p.DBURL(), &di) == nil && di.DBName == p.Name\n}", "func NewGame(game Game_Detail) bool {\n\torm := get_DBFront()\n\terr := orm.SetTable(\"game\").Save(&game)\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_423\", err})\n\t\treturn false\n\t}\n\treturn true\n}", "func ExistDb(name string) bool {\n\n\tif _, err := os.Stat(name); err != nil {\n\n\t\tif os.IsNotExist(err) {\n\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (m VolumeStoreMode) IsLocal() bool {\n\treturn (m & LocalStore) != 0\n}", "func (db StdNetDB) Exists() bool {\n\tp := db.Path()\n\t// check root directory\n\t_, err := os.Stat(p)\n\tif err == nil {\n\t\t// check subdirectories for skiplist\n\t\tfor _, c := range base64.Alphabet {\n\t\t\tif _, err = os.Stat(filepath.Join(p, fmt.Sprintf(\"r%c\", c))); err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn err == nil\n}", "func DBExist() bool {\n\tif _, err := os.Stat(dbFile); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (s *SQLiteStore) stackExists(stackname string) (bool, error) {\n\treturn false, nil\n}", "func (s *StateDB) Exist(addr types.AddressHash) bool {\n\treturn s.getStateObject(addr) != nil\n}", "func CheckDBExists(loggedInUser, dbOwner, dbFolder, dbName string) (bool, error) {\n\tdbQuery := `\n\t\tSELECT count(db_id)\n\t\tFROM sqlite_databases\n\t\tWHERE user_id = (\n\t\t\t\tSELECT user_id\n\t\t\t\tFROM users\n\t\t\t\tWHERE lower(user_name) = lower($1)\n\t\t\t)\n\t\t\tAND folder = $2\n\t\t\tAND db_name = $3\n\t\t\tAND is_deleted = false`\n\t// If the request is from someone who's not logged in, or is for another users database, ensure we only consider\n\t// public databases\n\tif strings.ToLower(loggedInUser) != strings.ToLower(dbOwner) || loggedInUser == \"\" {\n\t\tdbQuery += `\n\t\t\tAND public = true`\n\t}\n\tvar DBCount int\n\terr := pdb.QueryRow(dbQuery, dbOwner, dbFolder, dbName).Scan(&DBCount)\n\tif err != nil {\n\t\tlog.Printf(\"Checking if a database exists failed: %v\\n\", err)\n\t\treturn true, err\n\t}\n\tif DBCount == 0 {\n\t\t// Database isn't in our system\n\t\treturn false, nil\n\t}\n\n\t// Database exists\n\treturn true, nil\n}", "func (u *User) IsLocal() bool {\n\treturn u.LoginSource <= 0\n}", "func (o *LocalDatabaseProvider) HasOnBoarding2FA() bool {\n\tif o != nil && o.OnBoarding2FA != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (db *firestoreDB) HasGameByPassword(password string) bool {\n\tgame, err := db.LookupGameByPassword(password)\n\treturn err == nil && game != nil\n}", "func (s *Database) Exists() bool {\n\t_, err := os.Stat(s.dbFile)\n\treturn err == nil\n}", "func (db *firestoreDB) HasGameByID(id string) bool {\n\tgame, err := db.LookupGameByID(id)\n\treturn err == nil && game != nil\n}", "func (q storestateQuery) ExistsG() (bool, error) {\n\treturn q.Exists(boil.GetDB())\n}", "func (m *Manager) Exists(globalID string) bool {\n\tcount, _ := m.collection.Find(bson.M{\"globalid\": globalID}).Count()\n\n\treturn count == 1\n}", "func TestExists(t *testing.T) {\n\tdb, err := Open(db_filename, \"c\")\n\tdefer db.Close()\n\tdefer os.Remove(db_filename)\n\n\tif err != nil {\n\t\tt.Error(\"Couldn't create database\")\n\t}\n\n\terr = db.Insert(\"foo\", \"bar\")\n\texists := db.Exists(\"foo\")\n\tif !exists {\n\t\tt.Error(\"Inserted key reported as not existing\")\n\t}\n}", "func isDbConnected() bool {\n\treturn Session != nil && DB != nil\n}", "func (o *LocalDatabaseProvider) HasCreated() bool {\n\tif o != nil && o.Created != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func JetExistsG(id int) (bool, error) {\n\treturn JetExists(boil.GetDB(), id)\n}", "func Exist() bool {\n\tdb := GetConnect()\n\tdefer db.Close()\n\n\trpg := new(Rpg)\n\terr := db.Model(rpg).Order(\"id DESC\").Limit(1).Select()\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn false\n\t}\n\treturn true\n}", "func (s *Drive) Local() bool { return s.config.OAuth.ClientID == \"\" }", "func (r *Release) localExist() error {\n\tvar (\n\t\tversion string = fmt.Sprintf(\"terraform-%s.zip\", r.Version)\n\t\terr error\n\t)\n\n\tif _, err = os.Stat(filepath.Join(r.Home, PathTmp.toString(), version)); !os.IsNotExist(err) {\n\t\tfmt.Println(\"Already in cache ...\")\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o *Ga4ghExternalIdentifier) HasDatabase() bool {\n\tif o != nil && o.Database != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (user *User) IsLocal() bool {\n\treturn user.Role == UserRoleLocal\n}", "func (db *DB) IsInitialized() bool {\n\treturn db.IsDBInitialized\n}", "func (db *DB) IsInitialized() bool {\n\treturn db.IsDBInitialized\n}", "func DatabaseExists(ctx context.Context, name string, opts ...db.Option) (exists bool, err error) {\n\tvar conn *db.Connection\n\tdefer func() {\n\t\terr = db.PoolCloseFinalizer(conn, err)\n\t}()\n\n\tconn, err = OpenManagementConnection(opts...)\n\tif err != nil {\n\t\treturn\n\t}\n\n\texists, err = conn.QueryContext(ctx, \"SELECT 1 FROM pg_database WHERE datname = $1\", name).Any()\n\treturn\n}", "func (me TxsdRegistryHandleSimpleContentExtensionRegistry) IsLocal() bool {\n\treturn me.String() == \"local\"\n}", "func (l *levelDBRepo) Exists(tenantID, id []byte) bool {\n\tkey := getKey(tenantID, id)\n\tres, err := l.db.Has(key, nil)\n\t// TODO check this\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn res\n}", "func (yt *YhTeam) Exists() bool {\n\treturn yt._exists\n}", "func isConnected(db *sql.DB) bool {\n\treturn db.Ping() == nil\n}", "func (bdm *MySQLDBManager) CheckDBExists() (bool, error) {\n\tbc, err := bdm.GetBlockchainObject()\n\n\tif err != nil {\n\t\treturn false, nil\n\t}\n\n\ttophash, err := bc.GetTopHash()\n\n\tif err != nil {\n\t\treturn false, nil\n\t}\n\n\tif len(tophash) > 0 {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}", "func (drv SQLiteDriver) DatabaseExists(u *url.URL) (bool, error) {\n\t_, err := os.Stat(sqlitePath(u))\n\tif os.IsNotExist(err) {\n\t\treturn false, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}", "func databaseExists(ctx context.Context, pgConn *pgx.Conn, dbName string) (exists bool, err error) {\n\tconst query = \"SELECT EXISTS (SELECT 1 FROM pg_database WHERE datname=$1)\"\n\terr = pgConn.QueryRow(ctx, query, dbName).Scan(&exists)\n\tif err != nil {\n\t\treturn false, trace.Wrap(err)\n\t}\n\treturn exists, nil\n}", "func instanceExists(name string) bool {\n\tvar exists bool\n\terr := pool.QueryRow(\"SELECT EXISTS (SELECT FROM PROVISION WHERE name = $1)\", name).Scan(&exists)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn false\n\t}\n\treturn exists\n}", "func (h *Handle) LocalDB() (IDB, error) {\n\tdb := C.alpm_get_localdb(h.ptr)\n\tif db == nil {\n\t\treturn nil, h.LastError()\n\t}\n\n\treturn &DB{db, *h}, nil\n}", "func (q premiumSlotQuery) ExistsG(ctx context.Context) (bool, error) {\n\treturn q.Exists(ctx, boil.GetContextDB())\n}", "func (tq *TeamQuery) Exist(ctx context.Context) (bool, error) {\n\tctx = setContextOp(ctx, tq.ctx, \"Exist\")\n\tswitch _, err := tq.FirstID(ctx); {\n\tcase IsNotFound(err):\n\t\treturn false, nil\n\tcase err != nil:\n\t\treturn false, fmt.Errorf(\"ent: check existence: %w\", err)\n\tdefault:\n\t\treturn true, nil\n\t}\n}", "func CheckUsernameExistsDB(username string) (bool, error) {\n\tdb, err := OpenConnectionDB()\n\tdefer db.Close()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tresult, err := db.Query(\"SELECT true FROM `user` WHERE `username` = '\" + username + \"'\")\n\tdefer result.Close()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tvar exist bool\n\n\tresult.Next()\n\t_ = result.Scan(&exist)\n\n\treturn exist, err\n}", "func (dbclient *CouchDatabase) Exists() (bool, error) {\n\t_, dbReturn, err := dbclient.GetDatabaseInfo()\n\tif dbReturn != nil && dbReturn.StatusCode == http.StatusNotFound {\n\t\treturn false, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}", "func (o *ImageImportManifest) HasLocalImageId() bool {\n\tif o != nil && o.LocalImageId != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (osq *OfflineSessionQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := osq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn osq.sqlExist(ctx)\n}", "func (osq *OfflineSessionQuery) Exist(ctx context.Context) (bool, error) {\n\tctx = setContextOp(ctx, osq.ctx, \"Exist\")\n\tswitch _, err := osq.FirstID(ctx); {\n\tcase IsNotFound(err):\n\t\treturn false, nil\n\tcase err != nil:\n\t\treturn false, fmt.Errorf(\"db: check existence: %w\", err)\n\tdefault:\n\t\treturn true, nil\n\t}\n}", "func existsProject(gh_id int64) bool {\n\terr := db.QueryRow(\"SELECT gh_id FROM projects WHERE gh_id = $1\", gh_id).\n\t\tScan(&gh_id)\n\treturn err != sql.ErrNoRows\n}", "func IsMovieInDB(mov movie.Movie, table string, db *sql.DB) (bool, error) {\n\tsqlStmt := \"SELECT EXISTS (SELECT 1 FROM \\\"\" + table + \"\\\" WHERE Name = ? AND Size = ? AND FileName = ?);\"\n\tstmt, err := db.Prepare(sqlStmt)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer stmt.Close()\n\tresult := stmt.QueryRow(mov.Name, mov.Size, mov.FileName)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tvar res bool\n\terr = result.Scan(&res)\n\treturn res, nil\n}", "func isNewServer(ctx context.Context, prevUUID string, db *sql.DB, flavor string) (bool, error) {\n\tif len(prevUUID) == 0 {\n\t\t// no sub dir exists before\n\t\treturn true, nil\n\t}\n\tuuid, err := utils.GetServerUUID(ctx, db, flavor)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif strings.HasPrefix(prevUUID, uuid) {\n\t\t// same server as before\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}", "func (gs *GameSet) Exists(item int64) bool {\n\tgs.mutex.Lock()\n\t_, exists := gs.data[item]\n\tgs.mutex.Unlock()\n\treturn exists\n}", "func (q rentalRowerQuery) ExistsG() (bool, error) {\n\treturn q.Exists(boil.GetDB())\n}", "func checkIfDatabaseExists(connDetail ConnectionDetails, dbName string) (found bool, err error) {\n\n\tvar db *sql.DB\n\n\tif db, err = connect(connDetail); err != nil {\n\t\treturn\n\t}\n\tdefer db.Close()\n\n\ttotalRows := 0\n\tif err = db.QueryRow(\"SELECT count(1) FROM pg_database WHERE datname = $1\", dbName).Scan(&totalRows); err != nil {\n\t\treturn\n\t}\n\n\tfound = (totalRows > 0)\n\n\treturn\n}", "func (imd *InMemoryDb) Connected() bool {\n\treturn imd.connected\n}", "func (m *LogoManager) Exists(globalID string) bool {\n\tcount, _ := m.collection.Find(bson.M{\"globalid\": globalID}).Count()\n\n\treturn count == 1\n}", "func (q offerQuery) ExistsG() (bool, error) {\n\treturn q.Exists(boil.GetDB())\n}", "func (s *Store) Exists(name string) bool {\n\ts.mu.Lock()\n\t_, ok := s.ls[name]\n\ts.mu.Unlock()\n\treturn ok\n}", "func (s *Store) Exists(name string) bool {\n\ts.mu.Lock()\n\t_, ok := s.ls[name]\n\ts.mu.Unlock()\n\treturn ok\n}", "func (w *Wallet) Exists(label string) bool {\n\treturn w.store.Exists(label)\n}", "func hasTable(db *sql.DB, tableName string) bool {\n\tsqlStmt := `SELECT name FROM sqlite_master WHERE type='table' AND name=?;`\n\tvar n string\n\terr := db.QueryRow(sqlStmt, tableName).Scan(&n)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn n == tableName\n}", "func doesQueryExistAlreadyInDatabase(query string, db models.Datastore) bool {\n\treturn db.GetSetQuery(query) != nil\n}", "func (r *ModuleStore) Exists(ctx context.Context, module, vsn string) bool {\n\tresult := models.Module{}\n\tquery := r.conn.Where(\"module = ?\", module).Where(\"version = ?\", vsn)\n\tcount, err := query.Count(&result)\n\n\treturn err == nil && count > 0\n}", "func (wcr *WordChainsResolver) IsWordInDB(w string) bool {\n\tfor _, word := range wcr.wordList {\n\t\tif w == word {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (p Database) Running() bool {\n\tdbs := []string{}\n\tu := fmt.Sprintf(\"%s/%s\", p.BaseURL(), \"_all_dbs\")\n\treturn unmarshalURL(u, &dbs) == nil && len(dbs) > 0\n}", "func (q storeQuery) ExistsG(ctx context.Context) (bool, error) {\n\treturn q.Exists(ctx, boil.GetContextDB())\n}", "func (r *RepoRef) IsLocal() bool {\n\treturn r.Path != \"\"\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 InventoryExistsG(id int64) (bool, error) {\n\treturn InventoryExists(boil.GetDB(), id)\n}", "func CreateGame(c *gin.Context) {\n\tdbStatement := \"\"\n\n\tdbStatement = \"CREATE TABLE IF NOT EXISTS game (\"\n\tdbStatement += \"id SERIAL PRIMARY KEY\"\n\tdbStatement += \", name text\"\n\tdbStatement += \", players integer\"\n\tdbStatement += \", roles bytea\"\n\tdbStatement += \", universes integer\"\n\tdbStatement += \", round integer\"\n\tdbStatement += \", nightPhase boolean\"\n\tdbStatement += \", randomSeed integer\"\n\tdbStatement += \")\"\n\tquantumutilities.DbExec(c, db, dbStatement)\n\n\tdbStatement = \"CREATE TABLE IF NOT EXISTS players (\"\n\tdbStatement += \"id BIGSERIAL PRIMARY KEY\"\n\tdbStatement += \", name text\"\n\tdbStatement += \", num integer\"\n\tdbStatement += \", gameid integer\"\n\tdbStatement += \", actions text\"\n\tdbStatement += \")\"\n\tquantumutilities.DbExec(c, db, dbStatement)\n\n\troleBlob, err := quantumutilities.GetBytes(GameSetup.Roles)\n\tquantumutilities.HandleErr(c, err, \"Error getting Roles as bytes\")\n\troleBytesString := fmt.Sprintf(\"'\\\\x%x'\", roleBlob)\n\tdbStatement = \"INSERT INTO game (\"\n\tdbStatement += \"name, players, roles, universes, round, nightPhase, randomSeed\"\n\tdbStatement += \") VALUES (\"\n\tdbStatement += \"'\" + GameSetup.Name + \"'\"\n\tdbStatement += \", \" + strconv.Itoa(GameSetup.Total)\n\tdbStatement += \", \" + roleBytesString\n\tdbStatement += \", \" + strconv.FormatUint(GameSetup.Universes, 10)\n\tdbStatement += \", \" + strconv.Itoa(Game.RoundNum)\n\tdbStatement += \", TRUE\"\n\tdbStatement += \", \" + strconv.Itoa(int(rand.Int31()))\n\tdbStatement += \") RETURNING id\"\n\tvar gameID = quantumutilities.DbExecReturn(c, db, dbStatement)\n\n\t// Assign random player numbers\n\tperm := rand.Perm(len(Players))\n\tlog.Printf(\"len(players) %d\", len(Players))\n\tfor i, p := range Players {\n\t\tdbStatement = \"INSERT INTO players (\"\n\t\tdbStatement += \"name, num, gameid, actions\"\n\t\tdbStatement += \") VALUES (\"\n\t\tdbStatement += \"'\" + p.Name + \"'\"\n\t\tdbStatement += \", \" + strconv.Itoa(perm[i])\n\t\tdbStatement += \", \" + strconv.Itoa(gameID)\n\t\tdbStatement += \", ''\"\n\t\tdbStatement += \")\"\n\t\tlog.Printf(\"Going to execute %q\", dbStatement)\n\t\tquantumutilities.DbExec(c, db, dbStatement)\n\t}\n}", "func JetExistsGP(id int) bool {\n\te, err := JetExists(boil.GetDB(), id)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func (self *LevelDBStore) Has(key []byte) (bool, error) {\n\treturn self.db.Has(key, nil)\n}", "func IsSetup() (bool, error) {\n\tvar setup bool\n\terr := db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket(users)\n\t\tif b == nil {\n\t\t\t// bucket doesn't exist\n\t\t\treturn nil\n\t\t}\n\t\tk, v := b.Cursor().First()\n\t\tsetup = k != nil && v != nil\n\t\treturn nil\n\t})\n\treturn setup, err\n}", "func (self PostgresDatabase) HasArticleLocal(message_id string) bool {\n var count int64\n err := self.conn.QueryRow(\"SELECT COUNT(message_id) FROM ArticlePosts WHERE message_id = $1\", message_id).Scan(&count)\n if err != nil {\n log.Println(\"failed to check for local article\", message_id, err)\n }\n return count > 0\n}", "func (db *Ops) IsLeader() bool {\n\treturn db.metaDB.IsLeader()\n}", "func (drv ClickHouseDriver) DatabaseExists(u *url.URL) (bool, error) {\n\tname := drv.databaseName(u)\n\n\tdb, err := drv.openClickHouseDB(u)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer mustClose(db)\n\n\texists := false\n\terr = db.QueryRow(\"SELECT 1 FROM system.databases where name = ?\", name).\n\t\tScan(&exists)\n\tif err == sql.ErrNoRows {\n\t\treturn false, nil\n\t}\n\n\treturn exists, err\n}", "func CheckDB(db *sql.DB, strDBName string) (bool, error) {\n\n\t// Does the database exist?\n\tresult, err := db.Query(\"SELECT db_id('\" + strDBName + \"')\")\n\tdefer result.Close()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfor result.Next() {\n\t\tvar s sql.NullString\n\t\terr := result.Scan(&s)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\t// Check result\n\t\tif s.Valid {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t}\n\n\t// This return() should never be hit...\n\treturn false, err\n}", "func IsGameEnded() bool {\n\tif !player1.GetAvailability() || !player2.GetAvailability() {\n\t\treturn true\n\t}\n\treturn false\n}", "func isKeyInDB(tx *sql.Tx, key string) bool {\n\trow := getStmt(tx, \"isKeyInDB\").QueryRow(key)\n\tvar n int\n\t_ = row.Scan(&n)\n\treturn n == 1\n}", "func TicketExistsG(ctx context.Context, guildID int64, localID int64) (bool, error) {\n\treturn TicketExists(ctx, boil.GetContextDB(), guildID, localID)\n}", "func (o *LocalDatabaseProvider) HasId() bool {\n\tif o != nil && o.Id != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (drv *Driver) DatabaseExists() (bool, error) {\n\t_, err := os.Stat(ConnectionString(drv.databaseURL))\n\tif os.IsNotExist(err) {\n\t\treturn false, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}", "func (sq *ServerQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := sq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn sq.sqlExist(ctx)\n}", "func StorestateExistsG(statename string) (bool, error) {\n\treturn StorestateExists(boil.GetDB(), statename)\n}", "func IsLocal(path string) bool {\n\tif _, err := os.Stat(path); err != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func (nimq *NetInterfaceModeQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := nimq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn nimq.sqlExist(ctx)\n}", "func db_check_user_exists(username string) bool {\n file_path := path.Join(\"db/users\", strings.ToLower(username) + \".json\")\n \n if _, err := os.Stat(file_path); !os.IsNotExist(err) {\n return true\n }\n return false\n}", "func IsURLExistsInDB(url string) bool {\n\tfor i := 0; i < len(domains); i += 1 {\n\t\tif url == domains[i] {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (client *ClientRPC) CreateGame(name string, hostPassword string) bool {\n\t// Tell relay to host game\n\tsuccess := false\n\tdata := GameData{\n\t\tName: name,\n\t\tPassword: hostPassword,\n\t}\n\tfor i := 0; i < 2; i++ {\n\t\terr := client.relay.Call(\"ServerRPCMethods.NewGame\", data, &success)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\tif err == rpc.ErrShutdown {\n\t\t\tif !client.connect() {\n\t\t\t\tlog.Printf(\"ClientRPC: Lost connection to relay and are unable to reconnect\")\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tlog.Printf(\"ClientRPC: Lost connection to relay but was able to reconnect\")\n\t\t} else {\n\t\t\tlog.Printf(\"ClientRPC error: %v\", err)\n\t\t\treturn false\n\t\t}\n\t}\n\treturn success\n}", "func (g *Godis) EXISTS(keys ...string) (int, error) {\n\tcount := 0\n\tfor _, key := range keys {\n\t\tif _, ok := g.db[key]; ok {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count, nil\n}", "func(db *Persistence) AppExists(appName string) (bool, error) {\n log.Debug(fmt.Sprintf(\"checking if application %s exists...\", appName))\n query := `SELECT application_id FROM applications WHERE application_name = $1`\n row := db.Session.QueryRow(context.Background(), query, appName)\n\n var appId uuid.UUID\n if err := row.Scan(&appId); err != nil {\n switch err {\n case pgx.ErrNoRows:\n return false, nil\n default:\n return false, err\n }\n }\n return true, nil\n}", "func updateGame(game string, username string) bool {\n\tsuccess := false\n\tif success = checkID(game); success && gameStarted {\n\t\treturn true\n\t}\n\treturn false\n}", "func (s *Storage) IsAvailable() error {\n\tif err := s.db.Ping(); err != nil {\n\t\treturn err\n\t}\n\n\t// This is necessary because once a database connection is initiallly\n\t// established subsequent calls to the Ping method return success even if the\n\t// database goes down.\n\t//\n\t// https://github.com/lib/pq/issues/533\n\tif _, err := s.db.Exec(\"SELECT 1\"); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *LDBStore) Has(_ context.Context, addr Address) bool {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\n\tikey := getIndexKey(addr)\n\t_, err := s.db.Get(ikey)\n\n\treturn err == nil\n}", "func (s *Store) Exists(ctx context.Context, name string) bool {\n\treturn s.storage.Exists(ctx, s.Passfile(name))\n}", "func (s *Store) Exists(ctx context.Context, name string) bool {\n\treturn s.store.Exists(ctx, s.passfile(name))\n}" ]
[ "0.6165867", "0.5681191", "0.56591237", "0.56353617", "0.5559647", "0.5554416", "0.5552465", "0.5522966", "0.54746", "0.5412814", "0.54034585", "0.5390477", "0.53722733", "0.5341808", "0.53362715", "0.5335849", "0.53276443", "0.53212655", "0.5317387", "0.52765626", "0.52355975", "0.52310914", "0.522531", "0.5211627", "0.52078044", "0.52035314", "0.5171419", "0.5144421", "0.5140739", "0.5139203", "0.51354575", "0.5095293", "0.5089872", "0.50839585", "0.50839585", "0.50808036", "0.507384", "0.5068195", "0.50525093", "0.5046716", "0.503355", "0.50060254", "0.4998285", "0.49927157", "0.49785498", "0.49774703", "0.4970845", "0.4967988", "0.49598476", "0.49594572", "0.49561206", "0.49356723", "0.4932249", "0.49249643", "0.49242613", "0.4919696", "0.4913887", "0.4913025", "0.49109226", "0.4908014", "0.49031183", "0.48930955", "0.48930955", "0.48861653", "0.48859295", "0.48849076", "0.48812506", "0.48801157", "0.48733357", "0.48669338", "0.48591182", "0.48575762", "0.4855793", "0.4854477", "0.48406044", "0.48389512", "0.4831075", "0.48226032", "0.4821144", "0.4819417", "0.48179382", "0.48169187", "0.4815465", "0.48146617", "0.48123732", "0.48068765", "0.48022547", "0.47893804", "0.47890455", "0.47882405", "0.47842714", "0.47708622", "0.47652745", "0.4761484", "0.4753784", "0.47466153", "0.47460973", "0.47428983", "0.47428313", "0.4741631" ]
0.8528136
0
pushToLocalDB grabs future games and schedules them in local database
func pushToLocalDB(games []gm.Game) { t := time.Now() for _, game := range games { if int64(t.Unix()) < game.AbsStart+int64(game.Duration) { if !isInLocalDB(game) { db.ScheduleGame(game) } } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func DBPushSeasonalAnimes(index int, malID string) {\n\t_, err := r.Table(\"seasonal_animes\").Insert(map[string]interface{}{\n\t\t\"id\": index,\n\t\t\"malID\": malID,\n\t}).RunWrite(dbSession)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n}", "func fetchScheduledGames() []gm.Game {\n\turi := viper.GetString(\"master_URL\") + \"/api/games\"\n\n\tresp, _ := http.Get(uri)\n\n\tdefer closeResponse(resp)\n\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tvar gms []gm.Game\n\n\tjsonErr := json.Unmarshal(body, &gms)\n\tif jsonErr != nil {\n\t\tlogger.Error().Msg(\"could not get schedule game from MASTER master base station\")\n\t}\n\n\treturn gms\n}", "func GenerateInitialData(db *sql.DB) {\n var teams []string\n\n db.Exec(\"TRUNCATE TABLE game\")\n db.Exec(\"DELETE FROM team\")\n for i := 0; i < 30; i++ {\n id := pgtype.UUID{}\n err := db.QueryRow(fmt.Sprintf(`INSERT INTO team(name) VALUES ('Team %d') RETURNING id;`, i + 1)).Scan(&id)\n if err != nil {\n println(err.Error())\n }\n idStr, _ := id.EncodeText(nil, nil)\n teams = append(teams, string(idStr))\n }\n for i := 0; i < len(teams); i += 2 {\n _, err := db.Exec(fmt.Sprintf(`INSERT INTO game(location, team_a, team_b) VALUES ('Location %d', '%s', '%s') RETURNING id;`, i + 1, teams[i], teams[i + 1]))\n if err != nil {\n println(err.Error())\n }\n }\n\n}", "func (st *SqliteStoreMatchup) GetMatchups(league *data.League, season *data.Season) ([]data.Matchup, error) {\n\tvar matchups []data.Matchup\n\trows, err := st.database.Query(`SELECT league_id, season_year, id,\n\thome, away, round, start FROM matchup WHERE league_id=? AND season_year=?`, league.ID, season.Year)\n\tif err != nil {\n\t\tfmt.Printf(\"GetMatchups query Err: %v\\n\", err)\n\t\treturn []data.Matchup{}, err\n\t}\n\tvar leagueID string\n\tvar seasonYear int\n\tvar ID string\n\tvar homeID string\n\tvar awayID string\n\tvar round int\n\tvar start string\n\tfor rows.Next() {\n\t\tmatchup := &data.Matchup{}\n\t\terr := rows.Scan(&leagueID, &seasonYear, &ID, &homeID, &awayID, &round, &start)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"GetMatchup Scan Err: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tleague, _ := st.store.League().GetLeague(leagueID)\n\t\tseason, _ := st.store.Season().GetSeason(seasonYear, league)\n\t\thome, _ := st.store.Team().GetTeam(homeID, league)\n\t\taway, _ := st.store.Team().GetTeam(awayID, league)\n\t\tmatchup.League = *league\n\t\tmatchup.Season = *season\n\t\tmatchup.ID = ID\n\t\tif home != nil {\n\t\t\tmatchup.Home = *home\n\t\t}\n\t\tif away != nil {\n\t\t\tmatchup.Away = *away\n\t\t}\n\t\tmatchup.Round = round\n\t\tmatchup.Start, err = time.Parse(time.RFC3339, start)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"GetMatchup Invalid time Err: %v\\n\", err)\n\n\t\t}\n\t\tif home != nil && away != nil {\n\t\t\tmatchup.SeasonGames, _ = st.store.Game().GetSeasonGames(league, season, home, away)\n\t\t\tmatchup.PlayoffGames, _ = st.store.Game().GetPlayoffGames(league, season, home, away)\n\t\t}\n\t\tmatchup.CalculateResult()\n\t\tmatchups = append(matchups, *matchup)\n\t}\n\trows.Close()\n\treturn matchups, nil\n}", "func SaveToDB(g *Game) error {\n\n db, err := GetDBConnection(g.databaseURL)\n if err != nil {\n return err\n }\n defer db.Close()\n\n for _, hero := range g.heroes {\n stmt, err := db.Prepare(\"INSERT INTO hero \" +\n \"(player_name, player_lastname, hero_name, email, twitter, hclass, hero_online, token, hero_level, race, title, ttl, xpos, ypos, \" +\n \" ring, amulet, charm, weapon, helm, tunic, gloves, shield, leggings, boots \" +\n \") \" +\n \"VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) \" +\n \"ON DUPLICATE KEY UPDATE \" +\n \"hero_online=VALUES(hero_online), hero_level=VALUES(hero_level), ttl=VALUES(ttl), xpos=VALUES(xpos), ypos=VALUES(ypos), \" +\n \"ring=VALUES(ring), amulet=VALUES(amulet), charm=VALUES(charm), weapon=VALUES(weapon), \" +\n \"helm=VALUES(helm), tunic=VALUES(tunic), gloves=VALUES(gloves), shield=VALUES(shield), \" +\n \"leggings=VALUES(leggings), boots=VALUES(boots);\")\n if err != nil {\n log.Error(err)\n }\n\n ttl := int(hero.nextLevelAt.Sub(time.Now()).Seconds())\n res, err := stmt.Exec(hero.FirstName, hero.LastName, hero.HeroName, hero.Email, hero.Twitter, hero.HeroClass, hero.Enabled, hero.token,\n hero.Level, hero.HeroRace, hero.HeroTitle, ttl, hero.Xpos, hero.Ypos,\n hero.Equipment.Ring, hero.Equipment.Amulet, hero.Equipment.Charm, hero.Equipment.Weapon, hero.Equipment.Helm, hero.Equipment.Tunic, hero.Equipment.Gloves, hero.Equipment.Shield, hero.Equipment.Leggings, hero.Equipment.Boots)\n if err != nil {\n log.Error(err)\n }\n\n lastID, err := res.LastInsertId()\n if err != nil {\n log.Error(err)\n } else {\n hero.id = lastID\n }\n }\n\n return nil\n}", "func DBPushPopularAnimes(index int, malID string) {\n\t_, err := r.Table(\"popular_animes\").Insert(map[string]interface{}{\n\t\t\"id\": index,\n\t\t\"malID\": malID,\n\t}).RunWrite(dbSession)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n}", "func DBPushRecentAnimes(index int, malID string, episodeIndex int) {\n\t_, err := r.Table(\"recent_animes\").Insert(map[string]interface{}{\n\t\t\"id\": index,\n\t\t\"malID\": malID,\n\t\t\"episodeIndex\": episodeIndex,\n\t}).RunWrite(dbSession)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n}", "func (conn *Connection) PushToLobby() {\n\tif conn.done() {\n\t\treturn\n\t}\n\tconn.wGroup.Add(1)\n\tdefer func() {\n\t\tconn.wGroup.Done()\n\t}()\n\n\tconn.setRoom(nil)\n\tconn.setBoth(false)\n}", "func (s *Store) push() {\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(time.Second * 15):\n\t\t\tlogs.INFO.Println(\"Initiating push....\")\n\t\t\tgo s.sync()\n\t\t}\n\t}\n}", "func CreateGame(c *gin.Context) {\n\tdbStatement := \"\"\n\n\tdbStatement = \"CREATE TABLE IF NOT EXISTS game (\"\n\tdbStatement += \"id SERIAL PRIMARY KEY\"\n\tdbStatement += \", name text\"\n\tdbStatement += \", players integer\"\n\tdbStatement += \", roles bytea\"\n\tdbStatement += \", universes integer\"\n\tdbStatement += \", round integer\"\n\tdbStatement += \", nightPhase boolean\"\n\tdbStatement += \", randomSeed integer\"\n\tdbStatement += \")\"\n\tquantumutilities.DbExec(c, db, dbStatement)\n\n\tdbStatement = \"CREATE TABLE IF NOT EXISTS players (\"\n\tdbStatement += \"id BIGSERIAL PRIMARY KEY\"\n\tdbStatement += \", name text\"\n\tdbStatement += \", num integer\"\n\tdbStatement += \", gameid integer\"\n\tdbStatement += \", actions text\"\n\tdbStatement += \")\"\n\tquantumutilities.DbExec(c, db, dbStatement)\n\n\troleBlob, err := quantumutilities.GetBytes(GameSetup.Roles)\n\tquantumutilities.HandleErr(c, err, \"Error getting Roles as bytes\")\n\troleBytesString := fmt.Sprintf(\"'\\\\x%x'\", roleBlob)\n\tdbStatement = \"INSERT INTO game (\"\n\tdbStatement += \"name, players, roles, universes, round, nightPhase, randomSeed\"\n\tdbStatement += \") VALUES (\"\n\tdbStatement += \"'\" + GameSetup.Name + \"'\"\n\tdbStatement += \", \" + strconv.Itoa(GameSetup.Total)\n\tdbStatement += \", \" + roleBytesString\n\tdbStatement += \", \" + strconv.FormatUint(GameSetup.Universes, 10)\n\tdbStatement += \", \" + strconv.Itoa(Game.RoundNum)\n\tdbStatement += \", TRUE\"\n\tdbStatement += \", \" + strconv.Itoa(int(rand.Int31()))\n\tdbStatement += \") RETURNING id\"\n\tvar gameID = quantumutilities.DbExecReturn(c, db, dbStatement)\n\n\t// Assign random player numbers\n\tperm := rand.Perm(len(Players))\n\tlog.Printf(\"len(players) %d\", len(Players))\n\tfor i, p := range Players {\n\t\tdbStatement = \"INSERT INTO players (\"\n\t\tdbStatement += \"name, num, gameid, actions\"\n\t\tdbStatement += \") VALUES (\"\n\t\tdbStatement += \"'\" + p.Name + \"'\"\n\t\tdbStatement += \", \" + strconv.Itoa(perm[i])\n\t\tdbStatement += \", \" + strconv.Itoa(gameID)\n\t\tdbStatement += \", ''\"\n\t\tdbStatement += \")\"\n\t\tlog.Printf(\"Going to execute %q\", dbStatement)\n\t\tquantumutilities.DbExec(c, db, dbStatement)\n\t}\n}", "func isInLocalDB(game gm.Game) bool {\n\tdbGames := db.GetGames()\n\n\tfor _, g := range dbGames {\n\t\tif game.GameID == g.GameID {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (lob *Lobby) createGame(startingTeam int, round int) {\n\n\tnewGame := Game{\n\t\tGameUid: shortuuid.New(),\n\t\tStartingTeam: startingTeam,\n\t\tCurrentRound: round,\n\t\tTeam1Ready: false,\n\t\tTeam2Ready: false,\n\t\tGameState: created,\n\t\tTeam1UID: lob.Team1UID,\n\t\tTeam2UID: lob.Team2UID,\n\t}\n\n\tlob.Games = append(lob.Games, newGame)\n\n}", "func WorkloadPush(ctx context.Context, db *mongo.Database, w ...Workload) error {\n\tcol := db.Collection(queueCollection)\n\tdocs := make([]interface{}, 0, len(w))\n\tfor _, wl := range w {\n\t\tdocs = append(docs, wl)\n\t}\n\t_, err := col.InsertMany(ctx, docs)\n\n\treturn err\n}", "func main() {\n\tdate := time.Now().AddDate(0, 0, -1)\n\tdates := \"year_\" + date.Format(\"2006/month_01/day_02\")\n\n\tmyTeamsMap := InitMyTeamsMap()\n\tgames := make(map[int][]string)\n\tgames = SearchMyMLBGames(dates, games, myTeamsMap)\n\n\tdownloadedGames := downloadMyMLBGames(games, myTeamsMap)\n\tlog.Printf(\"%v\", downloadedGames)\n\n\tpushBulletAPI := os.Getenv(\"pushBulletAPI\")\n\tlog.Printf(pushBulletAPI)\n\n\t// TODO3: prepare upload_urls per game\n\n\t// TODO4: upload games to pushbullet\n\n\t// TODO5: send file via pushbullet\n}", "func AllGames(w http.ResponseWriter, r *http.Request) {\r\n\tdb, err = gorm.Open(\"sqlite3\", \"collegiateCS.db\")\r\n\t//cStats := make(chan []dbStats)\r\n\t//cPlayers := make(chan []dbPlayer)\r\n\t//cRosters := make(chan []dbRoster)\r\n\r\n\tif err != nil {\r\n\t\tfmt.Println(err.Error())\r\n\t\tpanic(\"Failed to connect to db\")\r\n\t}\r\n\tdefer db.Close()\r\n\t//Trigger happy to create go routines, alwasy wanted to use them\r\n\t//go allStats(cStats)\r\n\t//go allPlayers(cPlayers)\r\n\t//go allRosters(cRosters)\r\n\r\n\tvar dbGames []dbGame\r\n\tdb.Find(&dbGames)\r\n\t//dbStatsOp := <-cStats\r\n\t//dbPlayers := <-cPlayers\r\n\t//dbRosters := <-cRosters\r\n\t//close(cStats)\r\n\t//close(cPlayers)\r\n\t//close(cRosters)\r\n\taGames := buildGame(&dbGames)\r\n\tjson.NewEncoder(w).Encode(*aGames)\r\n}", "func AddMoveToDB(move *Move) string {\n\tdb := ConnectDatabase()\n\tdefer db.Close()\n\n\tstatus := \"success\"\n\n\t_, err := db.Query(\"INSERT INTO moves VALUES (0, \\\"\" + move.OldAddress + \"\\\", \\\"\" + move.DestinationAddress + \"\\\", \\\"\" + move.FamilyName + \"\\\", \\\"\" + move.PreviewImageURL + \"\\\")\")\n\tif err != nil {\n\t\tstatus = \"failure\"\n\t\tfmt.Println(err.Error())\n\t}\n\n\treturn status\n}", "func SyncToSMdb() {\n\n\tdbName := c.DBConfig.DBName.StockMarketRawD1\n\tnames, _ := h.GetCollectionNames(dbName)\n\tcCount := len(names)\n\n\tfor i, name := range names {\n\t\tMergeDMtoMM(name)\n\t\tfmt.Printf(\"Synchronizing daily-bar to monthly-bar. Stock code:%s (%d/%d) \\r\", name, i+1, cCount)\n\t}\n\tfmt.Println()\n}", "func SendDB(conn net.Conn) error {\n\tvar err error\n\ttarget, err := ioutil.ReadFile(\"dump.rdb\")\n\tif err != nil {\n\t\tconn.Close()\n\t\treturn err\n\t}\n\tcompressor := lz4.NewWriter(conn)\n\t_, err = compressor.Write(target)\n\tcompressor.Flush()\n\tgob.NewEncoder(conn).Encode(cluster.Clock)\n\tconn.Close()\n\treturn err\n}", "func main() {\n\tvar zones types.Zones\n\tvar sites types.Sites\n\tvar subnets types.Subnets\n\tvar transitions types.Transitions\n\t\n\tdb, err := db.New(config.DbPath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// Init Zones\n\tzones = append(zones, &types.Zone{1, \"Zone 1\"})\n\tzones = append(zones, &types.Zone{2, \"Zone 2\"})\n\tzones = append(zones, &types.Zone{3, \"Zone 3\"})\n\tzones = append(zones, &types.Zone{4, \"Zone 4\"})\n\t// Init Sites\n\tsites = append(sites, &types.Site{\"1.2.3.4\", \"Site 1\"})\n\tsites = append(sites, &types.Site{\"2.3.4.5\", \"Site 2\"})\n\tsites = append(sites, &types.Site{\"3.4.5.6\", \"Site 3\"})\n\tsites = append(sites, &types.Site{\"4.5.6.7\", \"Site 4\"})\n\t// Init Subnets\n\tsubnets = append(subnets, &types.Subnet{net.IPNet{IP: net.ParseIP(\"192.168.0.1\"), Mask: net.IPv4Mask(255, 255, 255, 255)}, 1, \"1.2.3.4\"})\n\tsubnets = append(subnets, &types.Subnet{net.IPNet{IP: net.ParseIP(\"192.168.2.0\"), Mask: net.IPv4Mask(255, 255, 255, 0)}, 2, \"2.3.4.5\"})\n\tsubnets = append(subnets, &types.Subnet{net.IPNet{IP: net.ParseIP(\"192.3.0.0\"), Mask: net.IPv4Mask(255, 255, 0, 0)}, 3, \"3.4.5.6\"})\n\tsubnets = append(subnets, &types.Subnet{net.IPNet{IP: net.ParseIP(\"4.0.0.0\"), Mask: net.IPv4Mask(255, 0, 0, 0)}, 4, \"4.5.6.7\"})\n\tsubnets = append(subnets, &types.Subnet{net.IPNet{IP: net.ParseIP(\"10.0.0.0\"), Mask: net.IPv4Mask(255, 0, 0, 0)}, 4, \"4.5.6.7\"})\n\t// Init Transitions\n\ttransitions = append(transitions, &types.Transition{1, 1, 2, 80, 100, \"TCP\", \"allow\"})\n\ttransitions = append(transitions, &types.Transition{2, 2, 1, 80, 100, \"UDP\", \"drop\"})\n\ttransitions = append(transitions, &types.Transition{3, 1, 2, 0, 0, \"TCP\", \"allow\"})\n\ttransitions = append(transitions, &types.Transition{4, 3, 4, 100, 0, \"\", \"allow\"})\n\ttransitions = append(transitions, &types.Transition{5, 1, 0, 80, 100, \"TCP\", \"allow\"})\n\ttransitions = append(transitions, &types.Transition{6, 0, 2, 80, 100, \"UDP\", \"allow\"})\n\n\t// Insert stuff\n\terr = db.InsertZones(zones)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = db.InsertSites(sites)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = db.InsertSubnets(subnets)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = db.InsertTransitions(transitions)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (d *GameDailyDao) syncAndSave(host string, platId uint32, channelId uint32, timestamp, now int64, start, end string, curPage int) (pages int, winLoseMoneyInteger, winLoseMoneyDecimals int32, err error) {\n\n\tvar resp GameDailyApiResp\n\tresp, err = d.subSync(host, platId, start, end, curPage)\n\tif err != nil {\n\t\tcommon.LogFuncError(\"%v\", err)\n\t\treturn\n\t}\n\n\tif resp.Status != 200 {\n\t\terr = fmt.Errorf(\"get game daily failed : %+v\", resp)\n\t\treturn\n\t}\n\n\tpages = resp.Maxpage\n\n\twinLoseMoneyInteger, winLoseMoneyDecimals, err = d.save(channelId, timestamp, now, resp.Data)\n\tif err != nil {\n\t\tcommon.LogFuncError(\"%v\", err)\n\t\treturn\n\t}\n\n\treturn\n}", "func (scheduleAPI *scheduleAPIServer) saveScheduleWorker() {\n\tfor {\n\t\tselect {\n\t\tcase <-scheduleAPI.ctx.Done():\n\t\t\treturn\n\t\tcase <-time.After(time.Duration(5 * time.Minute)):\n\t\t\tfunc() {\n\t\t\t\tf, err := os.OpenFile(\"snapshot\", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 066)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Log.Warn(\"error while saving file\", zap.Error(err))\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Lock the mutex\n\t\t\t\tscheduleAPI.muSchedule.Lock()\n\n\t\t\t\tbs, err := proto.Marshal(&scheduleAPI.weeklySchedule)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Log.Error(\"error while marshaling file\", zap.Error(err))\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Unlock the mutex\n\t\t\t\tscheduleAPI.muSchedule.Unlock()\n\n\t\t\t\t_, err = f.Write(bs)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogger.Log.Error(\"error while writing to file\", zap.Error(err))\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}()\n\t\t}\n\t}\n}", "func runTable(game models.Game) {\n\tfmt.Println(\"running table with id\", game.GameID)\n\tgameTable := GameTableMap[game.GameID]\n\tfor {\n\t\tselect {\n\t\tcase gamePlayer := <-gameTable.Join:\n\t\t\tgameTable.ActivePlayers[gamePlayer] = true\n\t\tcase gamePlayer := <-gameTable.Leave:\n\t\t\t_, ok := gameTable.ActivePlayers[gamePlayer]\n\t\t\tif ok {\n\t\t\t\tgamePlayer.Conn.Close()\n\t\t\t\tdelete(gameTable.ActivePlayers, gamePlayer)\n\t\t\t}\n\t\tcase socketData := <-gameTable.Broadcast:\n\t\t\tif socketData.MessageType == \"GAME\" {\n\t\t\t\tfirebaseclients.UpdateGame(socketData.Game)\n\t\t\t} else if socketData.MessageType == \"TABLE_MESSAGE\" {\n\t\t\t\tfirebaseclients.UpdateTableMessage(socketData.TableMessage)\n\t\t\t} else if socketData.MessageType == \"CHAT\" {\n\t\t\t\tfirebaseclients.UpdateChatMessage(socketData.Chat)\n\t\t\t}\n\n\t\t\tfor player, isActive := range gameTable.ActivePlayers {\n\t\t\t\tif isActive {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase player.Send <- socketData:\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tclose(player.Send)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase gameTable.Leave <- player:\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\tcase game := <-gameTable.End:\n\t\t\tfmt.Println(\"Ending game table for game id\", game.GameID)\n\t\t\tfirebaseclients.UpdateGame(game)\n\t\t\tsocketData := models.SocketData{MessageType: \"GAME\", Game: game}\n\t\t\tfor player, isActive := range gameTable.ActivePlayers {\n\t\t\t\tif isActive {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase player.Send <- socketData:\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tclose(player.Send)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor player := range gameTable.ActivePlayers {\n\t\t\t\tgameTable.Leave <- player\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (b *Backend) Save(root internal.Root) ([]internal.Game, error) {\n\tvar gameJSON []byte\n\tvar games []internal.Game\n\terr := b.DB.Update(func(txn *badger.Txn) error {\n\t\tvar err error\n\t\tfor _, date := range root.Dates {\n\t\t\tdateString := date.DateString\n\t\t\tfor _, game := range date.Games {\n\t\t\t\tkey := fmt.Sprintf(\"%s:%d:%d\", dateString, game.Teams[\"away\"].Team.ID, game.Teams[\"home\"].Team.ID)\n\t\t\t\tgameJSON, err = json.Marshal(game)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ttxn.Set([]byte(key), gameJSON)\n\t\t\t\tgames = append(games, game)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn games, err\n}", "func cronSpotify() {\n\tpauses, errDb := db.GetFromUts(time.Now().Unix())\n\tif errDb != nil {\n\t\tlog.Println(\"DB FAILURE : \", errDb)\n\t}\n\n\tfor _, pause := range pauses {\n\t\ttok, errTok := pause.GetToken()\n\t\tif errTok != nil {\n\t\t\tlog.Println(\"MARSHAL FAILURE : \", errTok)\n\t\t\tcontinue\n\t\t}\n\n\t\tclient := sleepspotify.GetClient(tok)\n\t\tgo pauseSpotifyRoutine(client, pause)\n\t}\n}", "func (g *Game) saveEventToDB(message string, heroes []*Hero) error {\n db, err := GetDBConnection(g.databaseURL)\n if err != nil {\n return err\n }\n defer db.Close()\n\n tx, err := db.Begin()\n if err != nil {\n return err\n }\n\n r, err := tx.Exec(\"INSERT INTO worldevent (event_text) VALUES (?)\", message)\n if err != nil {\n return err\n }\n\n eventID, err := r.LastInsertId()\n if err != nil {\n return err\n }\n\n for _, hero := range heroes {\n if _, err = tx.Exec(\"INSERT INTO heroworldevent (hero_id, worldevent_id ) VALUES (?, ?)\", hero.id, eventID); err != nil {\n return err\n }\n }\n\n err = tx.Commit()\n if err != nil {\n tx.Rollback()\n return err\n }\n\n return nil\n}", "func (room *Room) Save(wg *sync.WaitGroup) (err error) {\n\tdefer func() {\n\t\tif wg != nil {\n\t\t\twg.Done()\n\t\t}\n\t}()\n\tif room.done() {\n\t\treturn re.ErrorRoomDone()\n\t}\n\troom.wGroup.Add(1)\n\tdefer func() {\n\t\troom.wGroup.Done()\n\t}()\n\n\tplayers := room.Players.RPlayers()\n\n\t// made in NewRoom\n\t//room.Settings.ID = room.ID()\n\n\tgame := models.Game{\n\t\tID: room.dbRoomID,\n\t\tSettings: room.Settings,\n\t\tRecruitmentTime: room.recruitmentTime(),\n\t\tPlayingTime: room.playingTime(),\n\t\tChatID: room.dbChatID,\n\t\tStatus: int32(room.Status()),\n\t\tDate: room.Date(),\n\t}\n\n\twinners := room.Winners()\n\tgamers := make([]models.Gamer, 0)\n\tfor id, player := range players {\n\t\tgamer := models.Gamer{\n\t\t\tID: player.ID,\n\t\t\tScore: player.Points,\n\t\t\tExplosion: player.Died,\n\t\t\tWon: room.Winner(winners, id),\n\t\t}\n\t\tgamers = append(gamers, gamer)\n\t}\n\n\tfield := models.Field{\n\t\tWidth: room.Field.Width,\n\t\tHeight: room.Field.Height,\n\t\tCellsLeft: room.Field._cellsLeft,\n\t\tDifficult: 0,\n\t\tMines: room.Field.Mines,\n\t}\n\n\tcells := make([]models.Cell, 0)\n\tfor _, cellHistory := range room.Field.History() {\n\t\tcell := models.Cell{\n\t\t\tPlayerID: cellHistory.PlayerID,\n\t\t\tX: cellHistory.X,\n\t\t\tY: cellHistory.Y,\n\t\t\tValue: cellHistory.Value,\n\t\t\tDate: cellHistory.Time,\n\t\t}\n\t\tcells = append(cells, cell)\n\t}\n\n\thistory := room.history()\n\tactions := make([]models.Action, 0)\n\tfor _, actionHistory := range history {\n\t\taction := models.Action{\n\t\t\tPlayerID: actionHistory.Player,\n\t\t\tActionID: actionHistory.Action,\n\t\t\tDate: actionHistory.Time,\n\t\t}\n\t\tactions = append(actions, action)\n\t}\n\n\tgameInformation := models.GameInformation{\n\t\tGame: game,\n\t\tGamers: gamers,\n\t\tField: field,\n\t\tActions: actions,\n\t\tCells: cells,\n\t}\n\n\tif err = room.lobby.db().SaveGame(gameInformation); err != nil {\n\t\tutils.Debug(false, \"err. Cant save.\", err.Error())\n\t\troom.lobby.AddNotSavedGame(&gameInformation)\n\t}\n\n\treturn\n}", "func upload() {\n\tnow := time.Now().In(loc)\n\tbefore := now.Add(-6e10)\n\n\tuplimit := now.Format(\"ipx.200601021504\")\n\tdownlimit := before.Format(\"ipx.200601021504\")\n\n\tif rs := ssdb.Cmd(\"scan\", downlimit, uplimit, 9999999); rs.State == hissdb.ReplyOK {\n\t\tfor _, v := range rs.Hash() {\n\t\t\tid, ip := getIdIp(v.Key)\n\t\t\tif dberr := db.Table(\"flows\").Where(\"user_id = ?\", id).Updates(map[string]interface{}{\n\t\t\t\t\"used\": gorm.Expr(\"used + ? * ?\", v.Value, config.Multiple),\n\t\t\t\t\"updated_at\": time.Now(),\n\t\t\t}).Error; dberr != nil {\n\t\t\t\tlogger.Printf(\"warn\", \"[upload]update mysql error: %v\", dberr.Error())\n\t\t\t}\n\n\t\t\t// Logs\n\t\t\tused, _ := strconv.ParseFloat(v.Value, 0)\n\t\t\tdb.Exec(\"INSERT INTO `logs_\"+logshash(id)+\"` (`user_id`, `flows`, `node`, `client_ip`, `used_at`) VALUES (?, ?, ?, ?, ?)\", id, float32(used)*config.Multiple, config.NodeName, ip, now.Format(\"2006/01/02 15:04:05\"))\n\n\t\t}\n\t} else {\n\t\tlogger.Printf(\"warn\", \"[ssdb]cmd error: scan %s %s 9999999\", downlimit, uplimit)\n\t}\n\n}", "func (r Resolver) addToDB() {\n\tquery := fmt.Sprintf(\n\t\t`INSERT INTO noobles (title, category, description, audio, creator)\nVALUES ($1, $2, $3, $4, $5)\nRETURNING id`,\n\t)\n\n\terr := database.PGclient.QueryRow(context.TODO(), query,\n\t\tr.nooble.Title, r.nooble.Category, r.nooble.Description, r.nooble.Audio, r.nooble.Creator.Email).Scan(&r.nooble.ID)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n}", "func copyData(dbCfg *config.DbManager, srvCfg *config.Server) error {\n\tappName := dbCfg.ApplicationName\n\tsrcSt := dbCfg.SrcStartTime.Truncate(resolution)\n\tdstSt := dbCfg.DstStartTime.Truncate(resolution)\n\tdstEt := dbCfg.DstEndTime.Truncate(resolution)\n\tsrcEt := srcSt.Add(dstEt.Sub(dstSt))\n\n\tfmt.Printf(\"copying %s from %s-%s to %s-%s\\n\",\n\t\tappName,\n\t\tsrcSt.String(),\n\t\tsrcEt.String(),\n\t\tdstSt.String(),\n\t\tdstEt.String(),\n\t)\n\n\t// TODO: add more correctness checks\n\tif !srcSt.Before(srcEt) || !dstSt.Before(dstEt) {\n\t\treturn fmt.Errorf(\"Incorrect time parameters. Start time has to be before end time. \"+\n\t\t\t\"src start: %q end: %q, dst start: %q end: %q\", srcSt, srcEt, dstSt, dstEt)\n\t}\n\n\ts, err := storage.New(srvCfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif dbCfg.EnableProfiling {\n\t\tupstream := direct.New(s)\n\t\tselfProfilingConfig := &agent.SessionConfig{\n\t\t\tUpstream: upstream,\n\t\t\tAppName: \"pyroscope.dbmanager.cpu{}\",\n\t\t\tProfilingTypes: types.DefaultProfileTypes,\n\t\t\tSpyName: types.GoSpy,\n\t\t\tSampleRate: 100,\n\t\t\tUploadRate: 10 * time.Second,\n\t\t}\n\t\tsession := agent.NewSession(selfProfilingConfig, logrus.StandardLogger())\n\t\tupstream.Start()\n\t\t_ = session.Start()\n\t}\n\n\tsk, err := storage.ParseKey(appName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcount := int(srcEt.Sub(srcSt) / (resolution))\n\tbar := pb.StartNew(count)\n\n\tdurDiff := dstSt.Sub(srcSt)\n\n\tsigc := make(chan os.Signal, 1)\n\tsignal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM)\n\n\tfor srct := srcSt; srct.Before(srcEt); srct = srct.Add(resolution) {\n\t\tbar.Increment()\n\t\tselect {\n\t\tcase <-sigc:\n\t\t\tbreak\n\t\tdefault:\n\t\t}\n\n\t\tsrct2 := srct.Add(resolution)\n\t\tgOut, err := s.Get(&storage.GetInput{\n\t\t\tStartTime: srct,\n\t\t\tEndTime: srct2,\n\t\t\tKey: sk,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif gOut.Tree != nil {\n\t\t\tdstt := srct.Add(durDiff)\n\t\t\tdstt2 := dstt.Add(resolution)\n\n\t\t\terr = s.Put(&storage.PutInput{\n\t\t\t\tStartTime: dstt,\n\t\t\t\tEndTime: dstt2,\n\t\t\t\tKey: sk,\n\t\t\t\tVal: gOut.Tree,\n\t\t\t\tSpyName: gOut.SpyName,\n\t\t\t\tSampleRate: gOut.SampleRate,\n\t\t\t\tUnits: gOut.Units,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tbar.Finish()\n\treturn s.Close()\n}", "func SavetoMySQL(redisclient *redis.Client, db *sql.DB) {\n\n\t// Created on 19/7/2018\n\t// This program will save data to MySQL\n\t// Call function to return all Orders from MongoDB\n\t// for each order\n\t// ... insert Order into MySQL\n\t// ....for each order item\n\t// ....... insert OrderItem into MySQL\n\t// that's it\n\n\tstatuscompleted := \"Completed\"\n\n\tlistoforders := Getallcompleted(redisclient, statuscompleted)\n\n\tfor i := 0; i < len(listoforders); i++ {\n\n\t\torder := listoforders[i]\n\n\t\tnumber, _ := strconv.Atoi(order.ID)\n\t\tfullname := order.ClientName\n\t\tdate := order.Date\n\t\tttime := order.Time\n\t\tstatus := order.Status\n\t\ttotal, _ := strconv.ParseFloat(order.TotalGeral, 64)\n\n\t\t_, err := db.Exec(\"INSERT INTO festajunina.order(number, status, fullname, total, date, time) VALUES(?,?,?,?,?,?)\", number, status, fullname, total, date, ttime)\n\n\t\tif err != nil {\n\t\t\t// http.Error(res, \"Server error, unable to create your account.\", 500)\n\t\t\treturn\n\t\t}\n\n\t\tnumitem := 0\n\t\tfor p := 0; p < len(order.Items); p++ {\n\n\t\t\tnumitem++\n\t\t\torderitem := order.Items[p]\n\n\t\t\tfkordernumber, _ := strconv.Atoi(order.ID)\n\t\t\tsequencenumber := numitem // made up value\n\t\t\tdishname := orderitem.PratoName\n\t\t\ttotal, _ := strconv.ParseFloat(orderitem.Total, 64)\n\t\t\tprice, _ := strconv.ParseFloat(orderitem.Price, 64)\n\t\t\tquantidade, _ := strconv.Atoi(orderitem.Quantidade)\n\n\t\t\t_, err := db.Exec(\"INSERT INTO festajunina.orderitem(fkordernumber, sequencenumber, dishname, quantity, price, total) VALUES(?,?,?,?,?,?)\", fkordernumber, sequencenumber, dishname, quantidade, price, total)\n\n\t\t\tif err != nil {\n\t\t\t\t// http.Error(res, \"Server error, unable to create your account.\", 500)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\n\t}\n\treturn\n}", "func sendJobsToDB(jobs [] *types.GithubJob) {\n\tclient, err := aws.CreateDynamoClient()\n\n\tif err != nil {\n\t\tloggly.Error(err)\n\t\treturn\n\t}\n\n\tfor _, j := range jobs {\n\t\terr := aws.PutItem(client, TableName, *j)\n\t\tif err != nil {\n\t\t\tloggly.Error(err)\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (r *routine) push(versions int64, url, username, password string) {\n\tentropy := random.New(r.id + 1)\n\n\tfor r.nCharts > 0 {\n\t\tname, err := r.generateName(entropy)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t_versions := r.versionsToCreate(versions)\n\t\tr.nCharts -= _versions\n\n\t\tfor i := _versions; i > 0; i-- {\n\t\t\tversion, err := r.generateVersion(entropy, _versions)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treader, err := r.generateChart(name, version)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err = r.pushChart(reader, username, password, url, false); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}", "func StartSyncLoop() {\n\tinterval := time.NewTicker(30 * time.Second)\n\tquit := make(chan struct{})\n\tgo fetchGames(interval, quit)\n}", "func insertMasterQueue(conn *connection) {\n masterQueue.PushBack(conn)\n}", "func (st *SqliteStoreMatchup) AddMatchup(matchup *data.Matchup) error {\n\tstatement, err := st.database.Prepare(`INSERT INTO matchup (league_id, season_year, id,\n\t\thome, away, round, start) VALUES (?, ?, ?, ?, ?, ?, ?)`)\n\tif err != nil {\n\t\tfmt.Printf(\"AddMatchup Prepare Err: %v\\n\", err)\n\t\treturn err\n\t}\n\t_, err = statement.Exec(matchup.League.ID, matchup.Season.Year, matchup.ID, matchup.Home.ID, matchup.Away.ID, matchup.Round, matchup.Start.Format(time.RFC3339))\n\tif err != nil {\n\t\tfmt.Printf(\"AddMatchup Exec Err: %v\\n\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func fillDatabase() {\n\n\tfor _, album := range albums {\n\n\t\tfmt.Println(album)\n\n\t\t_, err := dbClient.Exec(\"INSERT INTO album (id, title, artist, price) VALUES ($1, $2, $3, $4)\", album.ID, album.Title, album.Artist, album.Price)\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tfmt.Println(\"Database filled: \", albums)\n}", "func (anomalies Anomalies) SendToDB(db *sqlx.DB, mutex *sync.Mutex) error {\n\tif len(anomalies.Readings) == 0 {\n\t\treturn nil\n\t}\n\tfor _, reading := range anomalies.Readings {\n\t\tmutex.Lock()\n\t\t_, err := db.Exec(`\n\t\t\tINSERT INTO anomalies (\n\t\t\t\tname,\n\t\t\t\ttimestamp,\n\t\t\t\tunix,\n\t\t\t\tbattery_voltage,\n\t\t\t\tsolar_voltage,\n\t\t\t\tbattery_amperage,\n\t\t\t\tload_amperage,\n\t\t\t\tsolar_amperage,\n\t\t\t\tavg_load_power,\n\t\t\t\tavg_solar_power,\n\t\t\t\tavg_hydro_power,\n\t\t\t\toutside_temp,\n\t\t\t\tcabin_temp,\n\t\t\t\tbattery_temp\n\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);\n\t\t`,\n\t\t\tanomalies.Name,\n\t\t\treading.Timestamp,\n\t\t\treading.Unix,\n\t\t\treading.BatteryVoltage,\n\t\t\treading.SolarVoltage,\n\t\t\treading.BatteryAmperage,\n\t\t\treading.LoadAmperage,\n\t\t\treading.SolarAmperage,\n\t\t\treading.AvgLoadPower,\n\t\t\treading.AvgSolarPower,\n\t\t\treading.AvgHydroPower,\n\t\t\treading.OutsideTemp,\n\t\t\treading.CabinTemp,\n\t\t\treading.BatteryTemp,\n\t\t)\n\t\tmutex.Unlock()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (g *game) broadcastGameInfo() {\n\tfor i := 0; i < len(g.Players); i++ {\n\t\tgi := getGameInfo(g, g.Players[i])\n\t\tmsg, err := json.Marshal(gi)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Can't marshal gameinfo message to json:\", err)\n\t\t\treturn\n\t\t}\n\t\tif g.Players[i].Connection != nil {\n\t\t\tg.Players[i].Connection.Outbound <- msg\n\t\t}\n\t}\n}", "func populateTestDatabaseTasks(t *testing.T, db *store.Database) {\n\ttaskBiology := model.Task{Name: \"biology\", ProjectID: uint(2)}\n\terr := db.PostTask(taskBiology)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error populating test database with tasks: %v\", err)\n\t\treturn\n\t}\n\n\ttaskPhysics := model.Task{Name: \"physics\", ProjectID: uint(2)}\n\terr = db.PostTask(taskPhysics)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error populating test database with tasks: %v\", err)\n\t}\n}", "func (w *MongoWorker) InsertGame(ctx context.Context, gameID string, clan *Clan) error {\n\tclanWithNamePrefixes := clan.NewClanWithNamePrefixes()\n\tclanJSON, err := json.Marshal(clanWithNamePrefixes)\n\tif err != nil {\n\t\treturn errors.New(\"Could not serialize clan\")\n\t}\n\n\tvar clanMap map[string]interface{}\n\tjson.Unmarshal(clanJSON, &clanMap)\n\n\tw.updateClanIntoMongoDB(ctx, gameID, \"update\", clanMap, clan.PublicID)\n\n\treturn nil\n}", "func insertSavedQueryIntoDB(ctx context.Context, s *api.Settings, sq *savedQueryField) error {\n\tfor _, query := range sq.SavedQueries {\n\t\t// Add case for global settings. It should make a site admin user the owner of that saved search.\n\t\tif s.Subject.User != nil {\n\t\t\t_, err := db.SavedSearches.Create(ctx, &types.SavedSearch{Description: query.Description, Query: query.Query, Notify: query.Notify, NotifySlack: query.NotifySlack, UserID: s.Subject.User})\n\t\t\tif err != nil {\n\t\t\t\treturn errors.WithMessagef(err, `migrate.saved-queries: unable to insert user saved query into database.`)\n\t\t\t}\n\t\t} else if s.Subject.Org != nil {\n\t\t\t_, err := db.SavedSearches.Create(ctx, &types.SavedSearch{Description: query.Description, Query: query.Query, Notify: query.Notify, NotifySlack: query.NotifySlack, OrgID: s.Subject.Org})\n\t\t\tif err != nil {\n\t\t\t\treturn errors.WithMessagef(err, `migrate.saved-queries: unable to migrate org saved query into database.`)\n\t\t\t}\n\t\t} else if s.Subject.Site || s.Subject.Default {\n\t\t\tsiteAdminID := getFirstSiteAdminID(ctx)\n\t\t\t_, err := db.SavedSearches.Create(ctx, &types.SavedSearch{Description: query.Description, Query: query.Query, Notify: query.Notify, NotifySlack: query.NotifySlack, UserID: siteAdminID})\n\t\t\tif err != nil {\n\t\t\t\treturn errors.WithMessagef(err, `migrate.saved-queries: unable to migrate global saved query into database.`)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func pushSync(t *testing.T, r *RingStore, e *model.ProcessEvent) {\n\tdone := make(chan bool)\n\terr := r.Push(e, done)\n\trequire.NoError(t, err)\n\tok := <-done\n\trequire.True(t, ok)\n}", "func prepTrackpoints(trackpointPrepper *TrackpointPrepper, streamer *Streamer, db *sql.DB, conf base.Configuration) {\n\tfmt.Println(\"TrackpointPrepper:\", trackpointPrepper.WindowStart, \"-\", trackpointPrepper.WindowEnd)\n\twindowSize := conf.TrackpointPrepWindowSize\n\ttimeWarp := conf.TimeWarp\n\ttargetSpeed := conf.TargetSpeedPerSecond\n\n\t// Get all currently active routes.\n\tids := make([]int64, 0)\n\tfor _, r := range trackpointPrepper.Routes {\n\t\tids = append(ids, r.Id)\n\t}\n\troutes := getRoutes(trackpointPrepper.WindowStart, trackpointPrepper.WindowEnd, ids, db)\n\n\t// Get new set of active routes.\n\ttrackpointPrepper.Routes = append(trackpointPrepper.Routes, routes...)\n\tnewRoutes := make([]Route, 0)\n\tfor _, r := range trackpointPrepper.Routes {\n\t\tif !r.DoTime.Before(trackpointPrepper.WindowStart) {\n\t\t\tnewRoutes = append(newRoutes, r)\n\t\t}\n\t}\n\n\t// Update everything to contain the final set of routes and make ready for next iteration.\n\ttrackpointPrepper.Routes = newRoutes\n\tfmt.Println(\"TrackpointPrepper.Routes.len:\", len(trackpointPrepper.Routes))\n\n\tif len(trackpointPrepper.Routes) > int(conf.NumTaxis / 10) {\n\t\t// Create updates for all taxis. First, compute how many updates we need to reach the target speed.\n\t\tnumUpdates := windowSize * targetSpeed\n\t\tnumTimeSlices := numUpdates / float64(len(trackpointPrepper.Routes))\n\t\ttimeInc := time.Duration(1000000000.0*windowSize*timeWarp/numTimeSlices) * time.Nanosecond\n\n\t\ttimeSlice := trackpointPrepper.WindowStart\n\t\tupdates := make([][]byte, 0)\n\t\tfor timeSlice.Before(trackpointPrepper.WindowEnd) {\n\t\t\tsliceEnd := timeSlice.Add(timeInc)\n\n\t\t\tfor _, r := range trackpointPrepper.Routes {\n\t\t\t\t// Check if this route just started now. If so, we have to create an occupancy message.\n\t\t\t\t// If it's a route with passengers, a destination message has to be added too.\n\t\t\t\tif r.PuTime.After(timeSlice) && r.PuTime.Before(sliceEnd) {\n\t\t\t\t\t// This is a new route, we have to generate an occupancy message.\n\t\t\t\t\t// Since we include all messages in both streams, here we kinda redundantly send both messages.\n\t\t\t\t\to, _ := json.Marshal(TaxiOccupancyUpdate{r.TaxiId, r.PassengerCount,\n\t\t\t\t\t\tr.EndLon, r.EndLat})\n\t\t\t\t\tupdates = append(updates, o)\n\n\t\t\t\t\tb, _ := json.Marshal(TaxiDestinationUpdate{r.TaxiId, r.PassengerCount,\n\t\t\t\t\t\tr.EndLon, r.EndLat})\n\t\t\t\t\tupdates = append(updates, b)\n\t\t\t\t}\n\n\t\t\t\t// Check if this route is just stopping now. If so, we have to send the journey (esp. price) information.\n\t\t\t\tif r.DoTime.After(timeSlice) && r.DoTime.Before(sliceEnd) {\n\t\t\t\t\tb, _ := json.Marshal(TaxiRouteCompletedUpdate{r.TaxiId, r.PassengerCount,\n\t\t\t\t\t\tr.Distance, r.Duration, r.FareAmount, r.Extra,\n\t\t\t\t\t\tr.MTATax, r.TipAmount, r.TollsAmount, r.EHailFee,\n\t\t\t\t\t\tr.ImprovementSurcharge, r.TotalAmount, r.PaymentType,\n\t\t\t\t\t\tr.TripType})\n\t\t\t\t\tupdates = append(updates, b)\n\t\t\t\t\tdelete(trackpointPrepper.ReservedTaxis, r.TaxiId)\n\t\t\t\t}\n\n\t\t\t\t// In some rare cases, the taxi gets ordered to the pickup location (let's say by a reservation call).\n\t\t\t\t// Optimally, the simulator would already generate these events...\n\t\t\t\t// For now, we do this approx. for one taxi every 10 seconds.\n\t\t\t\tif r.PassengerCount == 0 && rand.Float64() < 1.0 /\n\t\t\t\t\t(10000000000.0/float64(timeInc.Nanoseconds())*float64(len(trackpointPrepper.Routes))) {\n\t\t\t\t\ttrackpointPrepper.ReservedTaxis[r.TaxiId] = true\n\t\t\t\t\tb, _ := json.Marshal(TaxiReservationUpdate{r.TaxiId, r.EndLon, r.EndLat})\n\t\t\t\t\tupdates = append(updates, b)\n\t\t\t\t}\n\n\t\t\t\t// In any case, we want to generate some location updates.\n\t\t\t\t// TODO Auf UNIX / Mac scheint es anders kodiert zu sein, d.h. das strings Replace ist nicht nötig.\n\t\t\t\t// TODO Auf Ubuntu geht es so (gleich wie Windows).\n\t\t\t\tcoords, _, err := polyline.DecodeCoords([]byte(r.Geometry))\n\t\t\t\t// coords, _, err := polyline.DecodeCoords([]byte(strings.Replace(r.Geometry, \"\\\\\\\\\", \"\\\\\", -1)))\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tperc := timeSlice.Sub(r.PuTime).Seconds() / r.DoTime.Sub(r.PuTime).Seconds()\n\t\t\t\tif perc > 0 && perc < 1 {\n\t\t\t\t\tlon, lat := taxisim.AlongPolyline(taxisim.PolylineLength(coords)*perc, coords)\n\t\t\t\t\tif streamer.TaxiupdateChannel != nil {\n\t\t\t\t\t\tvar resLon *float64\n\t\t\t\t\t\tvar resLat *float64\n\t\t\t\t\t\tif trackpointPrepper.ReservedTaxis[r.TaxiId] {\n\t\t\t\t\t\t\tresLon = &r.EndLon\n\t\t\t\t\t\t\tresLat = &r.EndLat\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif r.PassengerCount > 0 {\n\t\t\t\t\t\t\tb, _ := json.Marshal(TaxiUpdate{r.TaxiId, lon, lat,\n\t\t\t\t\t\t\t\tr.PassengerCount, &r.EndLon, &r.EndLat, resLon, resLat})\n\t\t\t\t\t\t\tupdates = append(updates, b)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tb, _ := json.Marshal(TaxiUpdate{r.TaxiId, lon, lat,\n\t\t\t\t\t\t\t\tr.PassengerCount, nil, nil, resLon, resLat})\n\t\t\t\t\t\t\tupdates = append(updates, b)\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\ttimeSlice = timeSlice.Add(timeInc)\n\t\t}\n\t\t// Because some routes are not within the time slices, there are not enough updates. We fill in the missing ones\n\t\t// by repeating some.\n\t\tmissingUpdates := int(numUpdates) - len(updates)\n\t\tupdateCount := float64(len(updates)) / float64(missingUpdates)\n\t\tcnt := 0.0\n\t\ttotCnt := 0\n\t\tfor _, r := range updates {\n\t\t\t*streamer.TaxiupdateChannel <- r\n\t\t\ttotCnt += 1\n\t\t\tif updateCount > 0 && cnt > updateCount {\n\t\t\t\t*streamer.TaxiupdateChannel <- r\n\t\t\t\ttotCnt += 1\n\t\t\t\tcnt -= updateCount\n\t\t\t}\n\n\t\t\tcnt += 1\n\t\t}\n\t\tfmt.Println(\"Added messages\", totCnt)\n\n\t\ttrackpointPrepper.WindowStart = trackpointPrepper.WindowStart.Add(time.Second * time.Duration(windowSize*timeWarp))\n\t\ttrackpointPrepper.WindowEnd = trackpointPrepper.WindowEnd.Add(time.Second * time.Duration(windowSize*timeWarp))\n\t} else {\n\t\ttrackpointPrepper.WindowStart = time.Date(2016, time.January, 1, 0, 29, 20, 0, time.UTC)\n\t\ttrackpointPrepper.WindowEnd = time.Date(2016, time.January, 1, 0, 29, int(20+windowSize*conf.TimeWarp), 0, time.UTC)\n\t}\n}", "func (s *Store) sync() {\n\tresult, err := logger.GetAll(local)\n\tif err != nil {\n\t\tlogs.CRITICAL.Println(\"Panic for get all objects\")\n\t}\n\ttotal := len(result)\n\tif total != 0 {\n\t\tlogs.INFO.Println(\"Total of records: \", total)\n\t}\n\tif total == 0 {\n\t\tlog.Println(\"Nothing to sync\")\n\t\tif store.getFile() != \"\" {\n\t\t\tlogs.INFO.Println(\"Initiating clearing....\")\n\t\t\tremoveLines(store.getFile(), 1, -1)\n\t\t}\n\t\tstore.Transaction = nil\n\t\treturn\n\t}\n\tfor i := 0; i < total; i++ {\n\t\tlogs.INFO.Println(\"PUSH -> UserName: \" +\n\t\t\tresult[i].UserName + \" :: DataBase: \" +\n\t\t\tresult[i].DatabaseName + \" :: VirtualTransactionID: \" +\n\t\t\tresult[i].VirtualTransactionID)\n\n\t\tstore.Transaction = append(store.Transaction, result[i].VirtualTransactionID)\n\t\tlogger.Persist(prod, result[i])\n\t\t// Depending on the amount of data and traffic, goroutines that were\n\t\t// first run have already removed the registry, not identifying the\n\t\t// registry in the database at the current execution.\n\t\terr := logger.DeletePerObjectId(local, result[i].ID)\n\t\tif err != nil {\n\t\t\tlogs.INFO.Println(\"ObjectId -> \" + result[i].ID.Hex() + \" removed on the last goroutine\")\n\t\t}\n\t}\n}", "func (d *GameDailyDao) save(channelId uint32, timestamp, now int64, list []GameDailyItem) (winLoseMoneyInteger, winLoseMoneyDecimals int32, err error) {\n\tdbDailies := make([]gamemodels.ChannelDaily, 0, len(list))\n\tfor _, item := range list {\n\t\tvar tmpTimestamp uint32\n\t\ttmpTimestamp, err = common.TimeStrToUint32Plus(item.Date)\n\t\tif int64(tmpTimestamp) != timestamp { //skip time no fit one\n\t\t\tcontinue\n\t\t}\n\n\t\tdbDaily := gamemodels.ChannelDaily{\n\t\t\tChannelId: channelId,\n\t\t\tCtime: timestamp,\n\t\t\tMtime: now,\n\t\t}\n\n\t\tdbDaily.WinLoseMoneyInteger, dbDaily.WinLoseMoneyDecimals, err = common.DecodeCurrencyNoCarePrecision(fmt.Sprint(item.WinLoseMoney))\n\t\tif err != nil {\n\t\t\tcommon.LogFuncError(\"%v\", err)\n\t\t\treturn\n\t\t}\n\t\tdbDaily.ChipsInteger, dbDaily.ChipsDecimals, err = common.DecodeCurrencyNoCarePrecision(fmt.Sprint(item.Chips))\n\t\tif err != nil {\n\t\t\tcommon.LogFuncError(\"%v\", err)\n\t\t\treturn\n\t\t}\n\n\t\twinLoseMoneyInteger, winLoseMoneyDecimals = common.AddCurrency2(winLoseMoneyInteger, winLoseMoneyDecimals,\n\t\t\tdbDaily.WinLoseMoneyInteger, dbDaily.WinLoseMoneyDecimals)\n\n\t\tif winLoseMoneyInteger < 0 {\n\t\t\twinLoseMoneyInteger *= -1\n\t\t}\n\n\t\tif winLoseMoneyDecimals < 0 {\n\t\t\twinLoseMoneyDecimals *= -1\n\t\t}\n\n\t\tdbDailies = append(dbDailies, dbDaily)\n\t}\n\n\t_, err = d.Orm.InsertMulti(common.BulkCount, &dbDailies)\n\tif err != nil {\n\t\tcommon.LogFuncError(\"%v\", err)\n\t\treturn\n\t}\n\n\treturn\n}", "func (s *Scheduler) schedule() {\n\t// Do we have space left in our buffer?\n\tif s.CountScheduledRuns() >= schedulerBufferLimit {\n\t\t// No space left. Exit.\n\t\treturn\n\t}\n\n\t// Get scheduled pipelines but limit the returning number of elements.\n\tscheduled, err := s.storeService.PipelineGetScheduled(schedulerBufferLimit)\n\tif err != nil {\n\t\tgaia.Cfg.Logger.Debug(\"cannot get scheduled pipelines\", \"error\", err.Error())\n\t\treturn\n\t}\n\n\t// Iterate scheduled runs\n\tfor id := range scheduled {\n\t\t// If we are a server instance, we will by default give the worker the advantage.\n\t\t// Only in case all workers are busy we will schedule work on the server.\n\t\tworkers := s.memDBService.GetAllWorker()\n\t\tif gaia.Cfg.Mode == gaia.ModeServer && len(workers) > 0 {\n\t\t\t// Check if all workers are busy / inactive\n\t\t\tinvalidWorkers := 0\n\t\t\tfor _, w := range workers {\n\t\t\t\tif w.Slots == 0 || w.Status != gaia.WorkerActive {\n\t\t\t\t\tinvalidWorkers++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Insert pipeline run into memdb where all workers get their work from\n\t\t\tif len(workers) > invalidWorkers {\n\t\t\t\t// Mark them as scheduled\n\t\t\t\tscheduled[id].Status = gaia.RunScheduled\n\n\t\t\t\t// Update entry in store\n\t\t\t\terr = s.storeService.PipelinePutRun(scheduled[id])\n\t\t\t\tif err != nil {\n\t\t\t\t\tgaia.Cfg.Logger.Debug(\"could not put pipeline run into store\", \"error\", err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif err := s.memDBService.InsertPipelineRun(scheduled[id]); err != nil {\n\t\t\t\t\tgaia.Cfg.Logger.Error(\"failed to insert pipeline run into memdb via schedule\", \"error\", err.Error())\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// Check if this primary is not allowed to run work\n\t\tif gaia.Cfg.PreventPrimaryWork {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Mark them as scheduled\n\t\tscheduled[id].Status = gaia.RunScheduled\n\n\t\t// Update entry in store\n\t\terr = s.storeService.PipelinePutRun(scheduled[id])\n\t\tif err != nil {\n\t\t\tgaia.Cfg.Logger.Debug(\"could not put pipeline run into store\", \"error\", err.Error())\n\t\t\tcontinue\n\t\t}\n\n\t\t// push scheduled run into our channel\n\t\ts.scheduledRuns <- *scheduled[id]\n\t}\n}", "func (s *GameServer) startRound(now time.Time) {\n\tvar ids []PlayerId\n\tfor id := range s.players {\n\t\tids = append(ids, id)\n\t}\n\trand.Shuffle(len(ids), func(i, j int) {\n\t\tids[i], ids[j] = ids[j], ids[i]\n\t})\n\n\ts.matchups = nil\n\tfor i := 0; i < len(ids)-1; i += 2 {\n\t\ts.matchups = append(s.matchups, &Matchup{\n\t\t\tPlayers: [2]PlayerId{ids[i], ids[i+1]},\n\t\t})\n\t}\n\n\ts.phase = PhasePicking\n\ts.phaseDeadline = now.Add(time.Second * 10)\n}", "func (uq *UploadQueue) Schedule(safeRing, unsafeRing *ring.Ring) (map[*spool.ActiveNode][]*model.ShardToSave, error) {\n\t// define constant for indicating current schedule phase\n\tconst (\n\t\tPhase1 = 1\n\t\tPhase2 = 2\n\t)\n\n\t// sort the files to upload before scheduling\n\tuq.sort()\n\n\t// begin a transaction\n\ttx := database.Conn().Begin()\n\tdefer func() {\n\t\t// when panic is occurred, rollback all transactions\n\t\tif r := recover(); r != nil {\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\n\t// if cannot begin the transaction\n\tif err := tx.Error; err != nil {\n\t\treturn nil, err\n\t}\n\n\tphase := Phase1\n\tprevSafeRing := safeRing\n\tprevUnsafeRing := unsafeRing\n\tcurrRing := safeRing\n\tquotas := make(map[*spool.ActiveNode][]*model.ShardToSave)\n\n\t// for every files to save\n\tfor _, file := range uq.Files {\n\t\t// create the file record\n\t\tif err := tx.Create(file.Model).Error; err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// if curr phase is phase2, change current phase to phase1\n\t\t// and move curr ring to previous safe ring\n\t\tif phase == Phase2 {\n\t\t\tphase = Phase1\n\t\t\tprevUnsafeRing = currRing\n\t\t\tcurrRing = prevSafeRing\n\t\t}\n\n\t\t// for every shards\n\t\tfor pos, shard := range file.Data {\n\t\t\ttolerance := 0\n\t\t\t// find the node which can store this shard\n\t\t\tfor currRing.Value.(*spool.ActiveNode).Status.Capacity < uint64(len(shard)) {\n\t\t\t\tcurrRing = currRing.Next()\n\n\t\t\t\ttolerance++\n\t\t\t\tif tolerance >= currRing.Len() {\n\t\t\t\t\tif phase == Phase1 {\n\t\t\t\t\t\t// change to phase2 when\n\t\t\t\t\t\t// no longer there are none possible things among the safe nodes\n\t\t\t\t\t\tphase = Phase2\n\t\t\t\t\t\tprevSafeRing = currRing // save current safe ring\n\t\t\t\t\t\tcurrRing = prevUnsafeRing // move curr ring to previous unsafe ring\n\t\t\t\t\t\ttolerance = 0\n\t\t\t\t\t} else if phase == Phase2 {\n\t\t\t\t\t\t// reach at this point when\n\t\t\t\t\t\t// no longer there are none possible things among the all nodes\n\t\t\t\t\t\ttx.Rollback() // rollback the transaction\n\t\t\t\t\t\treturn nil, ErrLackOfStorage\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// set current node\n\t\t\tcurrNode := currRing.Value.(*spool.ActiveNode)\n\n\t\t\t// create the shard record\n\t\t\tshardModel := &model.Shard{\n\t\t\t\tPosition: uint8(pos),\n\t\t\t\tFileID: file.Model.ID,\n\t\t\t\tMachineID: currNode.Model.MachineID,\n\t\t\t\tChecksum: errcorr.Checksum(shard),\n\t\t\t}\n\t\t\tshardModel.DecideName()\n\t\t\tif err := tx.Create(shardModel).Error; err != nil {\n\t\t\t\ttx.Rollback()\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t// assignment shard to this node\n\t\t\tquotas[currNode] = append(\n\t\t\t\tquotas[currNode],\n\t\t\t\t&model.ShardToSave{\n\t\t\t\t\tName: shardModel.Name,\n\t\t\t\t\tData: shard,\n\t\t\t\t},\n\t\t\t)\n\n\t\t\t// node status prediction\n\t\t\tcurrNode.Status.Capacity -= uint64(len(shard))\n\n\t\t\tcurrRing = currRing.Next()\n\t\t}\n\t}\n\n\t// commit the transaction\n\ttx.Commit()\n\n\treturn quotas, nil\n}", "func (st *SqliteStoreMatchup) GetMatchup(league *data.League, season *data.Season, id string) (*data.Matchup, error) {\n\trow := st.database.QueryRow(`SELECT league_id, season_year, id,\n\thome, away, round, start\n\tFROM matchup WHERE league_id=? AND season_year=? AND id=?`, league.ID, season.Year, id)\n\tvar leagueID string\n\tvar seasonYear int\n\tvar ID string\n\tvar homeID string\n\tvar awayID string\n\tvar round int\n\tvar start string\n\n\tif row != nil {\n\t\tmatchup := &data.Matchup{}\n\t\terr := row.Scan(&leagueID, &seasonYear, &ID, &homeID, &awayID, &round, &start)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"GetMatchup Scan Err: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tleague, _ := st.store.League().GetLeague(leagueID)\n\t\tseason, _ := st.store.Season().GetSeason(seasonYear, league)\n\t\thome, _ := st.store.Team().GetTeam(homeID, league)\n\t\taway, _ := st.store.Team().GetTeam(awayID, league)\n\t\tmatchup.League = *league\n\t\tmatchup.Season = *season\n\t\tmatchup.ID = ID\n\t\tif home != nil {\n\t\t\tmatchup.Home = *home\n\t\t}\n\t\tif away != nil {\n\t\t\tmatchup.Away = *away\n\t\t}\n\t\tmatchup.Round = round\n\t\tmatchup.Start, err = time.Parse(time.RFC3339, start)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"GetMatchup Invalid time Err: %v\\n\", err)\n\n\t\t}\n\t\tif home != nil && away != nil {\n\t\t\tmatchup.SeasonGames, _ = st.store.Game().GetSeasonGames(league, season, home, away)\n\t\t\tmatchup.PlayoffGames, _ = st.store.Game().GetPlayoffGames(league, season, home, away)\n\t\t}\n\t\tmatchup.CalculateResult()\n\t\treturn matchup, nil\n\t}\n\treturn nil, errors.New(\"Matchup not found\")\n}", "func storeInDB(data string) error {\n\t//dial new db session\n\tvar err error\n\t//var session *session\n\tsession, err := mgo.Dial(\"127.0.0.1\") //TODO use connection pool\n\tif err != nil {\n\t\t//Raise error\n\t\treturn err\n\t}\n\t//close afterwards\n\tdefer session.Close()\n\n\t//unmarshal json\n\tvar js map[string]interface{}\n\tjson.Unmarshal([]byte(data), &js)\n\n\t//add to collection sync in DB wellnomics\n\tc := session.DB(\"wellnomics\").C(\"sync\")\n\terr = c.Insert(&js)\n\tif err != nil {\n\t\t//Raise error\n\t\treturn err\n\t}\n\treturn nil\n}", "func main() {\n fmt.Println(\"----------\")\n defer fmt.Println(\"----------\")\n\n // Open up our database connection.\n // I've set up a database on my local machine using phpmyadmin.\n // The database is called testDb\n //db, err := sql.Open(\"mysql\", \"root:1234@tcp(127.0.0.1:3307)/rugby\")\n db, err := sqlx.Open(\"mysql\", \"root:1234@tcp(127.0.0.1:3307)/rugby\")\n\n\n // if there is an error opening the connection, handle it\n check(err)\n\n // defer the close till after the main function has finished\n // executing\n defer db.Close()\n rows, err := db.Queryx(\"SELECT * FROM team\")\n check(err)\n type Team struct{\n TeamID int `db:\"TeamID\"`\n TeamName string `db:\"TeamName\"`\n TeamType string `db:\"TeamType\"`\n ClubID int `db:\"ClubID\"`\n }\n var team Team\n for rows.Next() {\n err := rows.StructScan(&team)\n if err != nil {\n log.Fatalln(err)\n }\n fmt.Printf(\"%#v\\n\", team)\n }\n\n\n\n}", "func seedDatabase(db *sql.DB) {\n\t_, err := db.Exec(`INSERT INTO app\n\t\t\t(id, app_id, app_name, deleted_at)\n\t\tVALUES \n\t\t\t('1b9e7a5f-af7c-4055-b488-72f2b5f72266', 'com.aerogear.foobar', 'Foobar', NULL),\n\t\t\t('ae2da1f5-a9c4-4305-84bc-80da683fbc36', 'com.test.app1', 'App One', '2019-02-18 14:36:35'),\n\t\t\t('0890506c-3dd1-43ad-8a09-21a4111a65a6', 'com.aerogear.testapp', 'Test App', NULL);\n\n\t\tINSERT INTO version\n\t\t\t(id, version, app_id, disabled, disabled_message, num_of_app_launches)\n\t\tVALUES \n\t\t\t('f6fe70a3-8c99-429c-8c77-a2efa7d0b458', '1', 'com.aerogear.testapp', FALSE, '', 5000),\n \t('9bc87235-6bcb-40ab-993c-8722d86e2201', '1.1', 'com.aerogear.testapp', TRUE, 'Please contact an administrator', 1000),\n\t\t\t('def3c38b-5765-4041-a8e1-b2b60d58bece', '1', 'com.test.app1', FALSE, '', 10000);\n\t\t\t\t\n\t\tINSERT INTO device\n\t\t\t(id, version_id, app_id, device_id, device_type, device_version)\n\t\tVALUES \n\t\t\t('d19feeb4-fb21-44e8-9990-473bf97a0a3f', 'f6fe70a3-8c99-429c-8c77-a2efa7d0b458', 'com.aerogear.testapp', 'a742f8b7-5e2f-43f3-a3c8-073da858420f', 'iOS', '10.2'),\n\t\t\t('00cb8957-db04-4ab6-8fd8-14b9fc516dbd', '9bc87235-6bcb-40ab-993c-8722d86e2201', 'com.aerogear.testapp', 'd1895cc1-28d7-4283-932d-8bcab9e4a461', 'Android', '3.2'),\n\t\t\t('e3b43b01-167b-48ef-8ff4-caf2e6613dee', '9bc87235-6bcb-40ab-993c-8722d86e2201', 'com.aerogear.testapp', 'feee7f81-0e33-4548-abbb-17a681c12f3b', 'Android', '4.1'),\n\t\t\t('ab411c3e-29f8-4e70-9ddc-8bafbba3fc4c', 'def3c38b-5765-4041-a8e1-b2b60d58bece', 'com.test.app1', '94da9833-093e-4f4c-9a93-b11600ce46b7', 'iOS', '2.0'),\n\t\t\t('a42a128a-dfb6-435c-8653-8f66ab3a5a1c', 'def3c38b-5765-4041-a8e1-b2b60d58bece', 'com.test.app1', '94132b0c-d7b1-4419-bcce-fc6760c59e3a', 'Android', '4.1');\n\t`)\n\n\tif err != nil {\n\t\tlogrus.Println(err)\n\t}\n}", "func populateTestDatabaseProjects(t *testing.T, db *store.Database) {\n\terr := db.PostProject(\"homework\")\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error populating test database with projects: %v\", err)\n\t\treturn\n\t}\n\n\terr = db.PostProject(\"cleaning\")\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error populating test database with projects: %v\", err)\n\t}\n}", "func main() {\n\taddr := os.Getenv(\"ADDR\")\n\tif len(addr) == 0 {\n\t\taddr = \":8000\"\n\t}\n\n\t// access to user store\n\tdsn := os.Getenv(\"DSN\")\n\tdb, err := sql.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\tfmt.Printf(\"error opening database: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// store game/results\n\tmg := os.Getenv(\"MONGO_ADDR\")\n\tsess, err := mgo.Dial(mg)\n\tif err != nil {\n\t\tlog.Fatalf(\"error dialing mongo: %v\", err)\n\t}\n\n\tch, err := handlers.ConnectQueue(os.Getenv(\"RABBITMQ\"))\n\tif err != nil {\n\t\tlog.Fatalf(\"error connecting to queue, %v\", err)\n\t}\n\t// TODO: initialize lobbies\n\t// TODO: need context\n\tctx := handlers.TriviaContext{\n\t\tMongo: m.NewMongoStore(sess),\n\t\tUsers: u.NewMySqlStore(db),\n\t\tLobbies: map[bson.ObjectId]*handlers.Lobby{},\n\t\tChannel: ch,\n\t}\n\t// connect/add queue to context\n\t//ctx.ConnectQueue(os.Getenv(\"RABBITADDR\"))\n\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"/v1/trivia\", ctx.LobbyHandler)\n\tmux.HandleFunc(\"/v1/trivia/\", ctx.SpecificLobbyHandler)\n\tmux.HandleFunc(\"/v1/trivia/user/\", ctx.StatisticsHandler)\n\n\tlog.Printf(\"Server is listening at http:/trivia/%s\", addr)\n\tlog.Fatal(http.ListenAndServe(addr, mux))\n}", "func (g *Gamefeed) Sync() ([]Event, error) {\n\turl := fmt.Sprintf(\"%s/gamefeed.json\", APIURL)\n\tg.LastID = settings.Settings.IRE.LastID\n\tif g.LastID > 0 {\n\t\turl = fmt.Sprintf(\"%s?id=%d\", url, g.LastID)\n\t}\n\n\tvar deathsights []Event\n\n\tif !settings.Settings.IRE.DeathsightEnabled { // Oops, we're disabled, bail out\n\t\treturn deathsights, nil\n\t}\n\n\tif err := httpclient.GetJSON(url, &g.Events); err == nil {\n\t\tfor _, event := range *g.Events {\n\t\t\tgo logEvent(event)\n\t\t\tif event.ID > g.LastID {\n\t\t\t\tg.LastID = event.ID\n\t\t\t}\n\n\t\t\tif event.Type == \"DEA\" {\n\t\t\t\tdeathsights = append(deathsights, event)\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn nil, err // Error at httpclient.GetJSON() call\n\t}\n\n\tsettings.Settings.Lock()\n\tdefer settings.Settings.Unlock()\n\tsettings.Settings.IRE.LastID = g.LastID\n\tsort.Sort(eventsByDate(deathsights))\n\treturn deathsights, nil\n}", "func (l *RemoteProvider) SaveSchedule(tokenString string, s *Schedule) ([]byte, error) {\n\tif !l.Capabilities.IsSupported(PersistSchedules) {\n\t\tlogrus.Error(\"operation not available\")\n\t\treturn nil, ErrInvalidCapability(\"PersistSchedules\", l.ProviderName)\n\t}\n\n\tep, _ := l.Capabilities.GetEndpointForFeature(PersistSchedules)\n\n\tdata, err := json.Marshal(s)\n\tif err != nil {\n\t\treturn nil, ErrMarshal(err, \"schedule for shipping\")\n\t}\n\n\tlogrus.Debugf(\"schedule: %s, size: %d\", data, len(data))\n\tlogrus.Infof(\"attempting to save schedule to remote provider\")\n\tbf := bytes.NewBuffer(data)\n\n\tremoteProviderURL, _ := url.Parse(l.RemoteProviderURL + ep)\n\tcReq, _ := http.NewRequest(http.MethodPost, remoteProviderURL.String(), bf)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := l.DoRequest(cReq, tokenString)\n\tif err != nil {\n\t\tlogrus.Errorf(\"unable to send schedule: %v\", err)\n\t\treturn nil, ErrPost(err, \"Perf Schedule\", resp.StatusCode)\n\t}\n\n\tdefer func() {\n\t\t_ = resp.Body.Close()\n\t}()\n\tbdr, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, ErrDataRead(err, \"Perf Schedule\")\n\t}\n\n\tif resp.StatusCode == http.StatusCreated {\n\t\tlogrus.Infof(\"schedule successfully sent to remote provider: %s\", string(bdr))\n\t\treturn bdr, nil\n\t}\n\n\treturn bdr, ErrPost(err, fmt.Sprint(bdr), resp.StatusCode)\n}", "func (s *server) dump() {\n\t// start connection to redis\n\tclient, err := redis.Dial(\"tcp\", s.redis_host)\n\tif err != nil {\n\t\tlog.Critical(err)\n\t\treturn\n\t}\n\tdefer client.Close()\n\n\t// start connection to mongodb\n\tsess, err := mgo.Dial(s.mongodb_url)\n\tif err != nil {\n\t\tlog.Critical(err)\n\t\treturn\n\t}\n\tdefer sess.Close()\n\t// database is provided in url\n\tdb := sess.DB(\"\")\n\n\t// copy & clean dirty map\n\ts.Lock()\n\tdirty_list := make([]interface{}, 0, len(s.dirty))\n\tfor k := range s.dirty {\n\t\tdirty_list = append(dirty_list, k)\n\t}\n\ts.dirty = make(map[string]bool)\n\ts.Unlock()\n\n\tif len(dirty_list) == 0 { // ignore emtpy dirty list\n\t\tlog.Trace(\"emtpy dirty list\")\n\t\treturn\n\t}\n\n\t// write data in batch\n\tvar sublist []interface{}\n\tfor i := 0; i < len(dirty_list); i += BATCH_SIZE {\n\t\tif (i+1)*BATCH_SIZE > len(dirty_list) { // reach end\n\t\t\tsublist = dirty_list[i*BATCH_SIZE:]\n\t\t} else {\n\t\t\tsublist = dirty_list[i*BATCH_SIZE : (i+1)*BATCH_SIZE]\n\t\t}\n\n\t\t// mget data from redis\n\t\trecords, err := client.Cmd(\"mget\", sublist...).ListBytes()\n\t\tif err != nil {\n\t\t\tlog.Critical(err)\n\t\t\treturn\n\t\t}\n\n\t\t// save to mongodb\n\t\tvar tmp map[string]interface{}\n\t\tfor k, v := range sublist {\n\t\t\terr := bson.Unmarshal(records[k], &tmp)\n\t\t\tif err != nil {\n\t\t\t\tlog.Critical(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// split key into TABLE NAME and RECORD ID\n\t\t\tstrs := strings.Split(v.(string), \":\")\n\t\t\tif len(strs) != 2 { // log the wrong key\n\t\t\t\tlog.Critical(\"cannot split key\", v)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttblname, id_str := strs[0], strs[1]\n\t\t\t// save data to mongodb\n\t\t\tid, err := strconv.Atoi(id_str)\n\t\t\tif err != nil {\n\t\t\t\tlog.Critical(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, err = db.C(tblname).Upsert(bson.M{\"Id\": id}, tmp)\n\t\t\tif err != nil {\n\t\t\t\tlog.Critical(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\tlog.Info(\"num records saved:\", len(dirty_list))\n\truntime.GC()\n}", "func push() {\n\tlog.Debug(\"state init\")\n\tstorage, err := sqlite.New(cfg.Secret.State)\n\tif err != nil {\n\t\tlog.Fatalf(\"push | sqlite.New [%s]\", err)\n\t}\n\n\tstoredFiles, err := storage.Files()\n\tif err != nil {\n\t\tlog.Fatalf(\"push | storage.Files [%s]\", err)\n\t}\n\n\tscannedFiles := scanLocalFiles(cfg.Root.Plain)\n\tlog.Infof(\"files tracked [%d]\", len(storedFiles))\n\tlog.Infof(\"files scanned [%d]\", len(scannedFiles))\n\n\tvar syncRequired bool\n\tfor _, scannedFile := range scannedFiles {\n\t\ttracked, updated := checkFile(scannedFile, storedFiles)\n\t\tif !tracked {\n\t\t\tlog.Infof(\"new file [%s]\", scannedFile)\n\n\t\t\tUUIDs, err := storage.UUIDs()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"push | storage.UUIDs [%s]\", err)\n\t\t\t}\n\n\t\t\tobfuscated := newUnique(UUIDs)\n\t\t\terr = crypto.Encrypt([]byte(cfg.Secret.Key), scannedFile, fmt.Sprintf(\"%s/%s\", cfg.Root.Encrypted, obfuscated))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"push | crypto.Encrypt [%s]\", err)\n\t\t\t}\n\n\t\t\tmd5sum, err := crypto.MD5(scannedFile)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"push | crypto.MD5 [%s]\", err)\n\t\t\t}\n\n\t\t\terr = storage.Add(scannedFile, md5sum, obfuscated)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"push | storage.Add [%s]\", err)\n\t\t\t}\n\n\t\t\tsyncRequired = true\n\t\t} else {\n\t\t\tif updated {\n\t\t\t\tlog.Infof(\"updated [%s]\", scannedFile)\n\t\t\t\tobfuscated, err := storage.Obfuscated(scannedFile)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"push | storage.Obfuscated [%s]\", err)\n\t\t\t\t}\n\n\t\t\t\terr = crypto.Encrypt([]byte(cfg.Secret.Key), scannedFile, fmt.Sprintf(\"%s/%s\", cfg.Root.Encrypted, obfuscated))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"push | crypto.Encrypt [%s]\", err)\n\t\t\t\t}\n\n\t\t\t\tmd5sum, err := crypto.MD5(scannedFile)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"push | crypto.MD5 [%s]\", err)\n\t\t\t\t}\n\n\t\t\t\terr = storage.Update(scannedFile, md5sum)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"push | storage.Update [%s]\", err)\n\t\t\t\t}\n\t\t\t\tsyncRequired = true\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Infof(\"sync required [%v]\", syncRequired)\n\tif syncRequired {\n\t\terr := crypto.Encrypt([]byte(cfg.Secret.Key), cfg.Secret.State, fmt.Sprintf(\"%s/%s\", cfg.Root.Encrypted, cfg.Secret.Obfuscated))\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"push | crypto.Encrypt [%s]\", err)\n\t\t}\n\n\t\terr = repo.Push(cfg.Root.Encrypted, *debug)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"push | repo.Push [%s]\", err)\n\t\t}\n\t}\n\n\tlog.Debug(\"state close\")\n\terr = storage.Close()\n\tif err != nil {\n\t\tlog.Fatalf(\"push | storage.Close [%s]\", err)\n\t}\n}", "func StartAddDataForProjects() {\n\tvar projects []Project\n\tdata, err := ioutil.ReadFile(\"../dump_data/projects.json\")\n\tcheckErr(err)\n\terr = json.Unmarshal(data, &projects)\n\tcheckErr(err)\n\tfmt.Println(\"data extracted from file\")\n\tfmt.Println(\"# Inserting values\")\n\tvar lastInsertID int\n\tfor _, value := range projects {\n\t\terr := DB.QueryRow(\"INSERT INTO projects(name,created_by) VALUES($1,$2) returning id;\", value.Name, value.CreatedBy).Scan(&lastInsertID)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfmt.Println(\"last inserted id =\", lastInsertID)\n\t}\n\n}", "func autoMigrate() {\n\t// Add auto migrate bellow this line\n\tConn.Exec(`CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";`)\n\tlog.Println(\"STARTING AUTO MIGRATE \")\n\tConn.AutoMigrate(\n\t\tmodels.SsUser{},\n\t\tmodels.Paket{},\n\t\tmodels.CapsterCollection{},\n\t\tmodels.Barber{},\n\t\tmodels.BarberPaket{},\n\t\tmodels.BarberCapster{},\n\t\tmodels.SaFileUpload{},\n\t\tmodels.OrderH{},\n\t\tmodels.OrderD{},\n\t\tmodels.SsSequenceNo{},\n\t)\n\n\tConn.Exec(`\n\tCREATE OR REPLACE FUNCTION update_status_new_job() \n\tRETURNS void AS $$\n\t\t#variable_conflict use_variable\n\t\tDECLARE\n\t\t\tcurtime timestamp := now();\n\t\tBEGIN\n\t\t\tupdate order_h\n\t\t\t\tset status = 'C'\n\t\t\twhere status ='N' \n\t\t\tand order_date < current_timestamp\n\t\t\tand (EXTRACT(EPOCH FROM current_timestamp-order_date)/3600)::int >=2;\n\t\tEND;\n\t$$ LANGUAGE plpgsql;\n\n\tCREATE OR REPLACE FUNCTION public.last_day(date)\n\tRETURNS date AS\n\t$$\n \t\tSELECT (date_trunc('MONTH', $1) + INTERVAL '1 MONTH - 1 day')::date;\n\t$$ LANGUAGE 'sql' IMMUTABLE STRICT;\n\t\t\t\n\tCREATE OR REPLACE FUNCTION public.week_of_month(\n\t\tp_date DATE,\n\t\tp_direction INT -- DEFAULT 1 -- for 8.4 and above\n\t ) RETURNS INT AS\n\t $$\n\t\tSELECT CASE WHEN $2 >= 0 THEN\n\t\t\tcase when CEIL(EXTRACT(DAY FROM $1) / 7)::int > 4 then\n\t\t\t\t4 \n\t\t\telse\n\t\t\t\tCEIL(EXTRACT(DAY FROM $1) / 7)::int\n\t\t\tEND\n\t\tELSE \n\t\t 0 - CEIL(\n\t\t\t(EXTRACT(DAY FROM last_day($1)) - EXTRACT(DAY FROM $1) + 1) / 7\n\t\t )::int\n\t\tEND\n\t $$ LANGUAGE 'sql' IMMUTABLE;\n\t \n\t CREATE OR REPLACE FUNCTION public.fbarber_beranda_s(p_status varchar, p_date varchar)\n\t RETURNS \n\t TABLE(\n\t\t owner_id integer,\n\t\t barber_id integer,\n\t\t barber_name varchar,\n\t\t file_id integer,\n\t\t file_name varchar,\n\t\t file_path varchar,\n\t\t file_type varchar,\n\t\t price numeric\n\t )\n\t LANGUAGE plpgsql\n\t AS $function$\n\t DECLARE v_id INTEGER; \n\t BEGIN \t\n\t\t RETURN QUERY \n\t\t\t select \tbarber.owner_id ,\n\t\t\t\t\t\t barber.barber_id ,\n\t\t\t\t\t\t barber.barber_name ,\n\t\t\t\t\t\t barber.file_id ,\n\t\t\t\t\t\t sa_file_upload.file_name ,\n\t\t\t\t\t\t sa_file_upload.file_path ,\n\t\t\t\t\t\t sa_file_upload.file_type ,\n\t\t\t\t\t\t (\n\t\t\t\t\t\t\t select coalesce(sum(od.price),0) from order_d od join order_h oh\n\t\t\t\t\t\t\t\t on oh.order_id = od.order_id \n\t\t\t\t\t\t\t where oh.barber_id = barber.barber_id \n\t\t\t\t\t\t\t and oh.order_date::date = p_date::date \n\t\t\t\t\t\t\t and oh.status =p_status\n\t\t\t\t\t\t ) as price\n\t\t\t\t\t\t from barber\n\t\t\t\t\t\t left join sa_file_upload on sa_file_upload.file_id = barber.file_id\n\t ;\n\t\t\t\t\n\t END;\n\t $function$\n\t ;\n\n\t \n\t\tCREATE OR replace FUNCTION public.fbarber_beranda_status(p_status varchar, p_date varchar)\n\t\tRETURNS \n\t\tTABLE(\n\t\t\towner_id integer,\n\t\t\tprogress_status integer,\n\t\t\tfinish_status integer,\n\t\t\tcancel_status integer\n\t\t\t,income_price numeric\n\t\t)\n\t\tLANGUAGE plpgsql\n\t\tAS $function$\n\t\tDECLARE v_id INTEGER; \n\t\tBEGIN \t\n\t\t\tRETURN QUERY \n\t\t\tselect \n\t\t\t\tss.owner_id ,\n\t\t\t\tss.progress_status,\n\t\t\t\tss.finish_status,\n\t\t\t\tss.cancel_status\n\t\t\t\t,\n\t\t\t\t(\n\t\t\t\t\t\tselect coalesce(sum(od.price ),0)::numeric \n\t\t\t\t\tfrom order_h oh join order_d od\n\t\t\t\t\ton oh.order_id = od.order_id \n\t\t\t\t\twhere oh.order_date::date= p_date::date \n\t\t\t\t\tand oh.status = p_status\n\t\t\t\t\tand oh.barber_id in(\n\t\t\t\t\t\tselect b2.barber_id from barber b2 \n\t\t\t\t\t\twhere b2.owner_id = ss.owner_id\n\t\t\t\t\t)\n\t\t\t\t)::numeric as income_price\n\t\t\tfrom (\n\t\t\t\tselect b.owner_id,\n\t\t\t\tcount(case a.status when 'P' then 1 else null end)::integer as progress_status,\n\t\t\t\t\t\t\tcount(case a.status when 'F' then 1 else null end)::integer as finish_status,\n\t\t\t\t\t\t\tcount(case a.status when 'C' then 1 else null end)::integer as cancel_status\n\t\t\t\tfrom order_h a join barber b\n\t\t\t\ton a.barber_id = b.barber_id \n\t\t\t\twhere a.order_date::date=p_date::date\n\t\t\t\tgroup by b.owner_id\n\t\t\t) ss\t\t\n\n\t\t;\n\t\t\t\t\n\t\tEND;\n\t\t$function$\n\t\t;\n\n\t \n\n\t\tCREATE OR REPLACE VIEW public.v_order_h\n\t\tAS SELECT barber.owner_id,\n\t\t\tbarber.barber_id,\n\t\t\tbarber.barber_name,\n\t\t\torder_h.order_id,\n\t\t\torder_h.status,\n\t\t\torder_h.from_apps,\n\t\t\torder_h.capster_id,\n\t\t\torder_h.order_date,\n\t\t\tss_user.name AS capster_name,\n\t\t\tss_user.file_id,\n\t\t\tsa_file_upload.file_name,\n\t\t\tsa_file_upload.file_path,\n\t\t\t( SELECT sum(order_d.price) AS sum\n\t\t\t\tFROM order_d\n\t\t\t\tWHERE order_d.order_id = order_h.order_id) AS price,\n\t\t\tweek_of_month(order_h.order_date::date, 1) AS weeks,\n\t\t\tdate_part('year'::text, order_h.order_date) AS years,\n\t\t\tdate_part('month'::text, order_h.order_date) AS months,\n\t\t\torder_h.customer_name,\n\t\t\torder_h.order_no\n\t\tFROM barber\n\t\t\tJOIN order_h ON order_h.barber_id = barber.barber_id\n\t\t\tJOIN ss_user ON ss_user.user_id = order_h.capster_id\n\t\t\tLEFT JOIN sa_file_upload ON sa_file_upload.file_id = ss_user.file_id;\n\n\n\t\tCREATE OR REPLACE VIEW public.v_capster\n\t\tAS\n\t\tSELECT \n\t\t\tss_user.user_id as capster_id,ss_user.user_name,ss_user.name,\n\t\t\tss_user.is_active,sa_file_upload.file_id,sa_file_upload.file_name,\n\t\t\tsa_file_upload.file_path,sa_file_upload.file_type, 0 as rating,\n\t\t\t(case when b.barber_id is not null then true else false end) as in_use,\n\t\t\tss_user.user_type,ss_user.user_input,ss_user.time_edit ,b.barber_id,\n\t\t\tb.barber_name\n\t\t\t\n\t\t FROM \"ss_user\" \n\t\t\tleft join sa_file_upload ON sa_file_upload.file_id = ss_user.file_id\n\t\t\tleft join barber_capster bc on bc.capster_id = ss_user.user_id \n\t\t\tleft join barber b on bc.barber_id =b.barber_id \n\t\t\tand b.owner_id::varchar = ss_user.user_input;\n\t \n\t `)\n\n\tlog.Println(\"FINISHING AUTO MIGRATE \")\n}", "func UploadToClubhouse(jiraFile string, userMaps []userMap, token string, testMode bool) error {\n\texport, err := GetDataFromXMLFile(jiraFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata := export.GetDataForClubhouse(userMaps)\n\tfmt.Printf(\"Found %d epics and %d stories.\\n\\n\", len(data.Epics), len(data.Stories))\n\t\n\tif !testMode{\n\t\tfmt.Println(\"Sending data to Clubhouse...\")\n\t\terr = SendData(token, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (g *Gateway) Sync() {\n\tg.lock.RLock()\n\tdefer g.lock.RUnlock()\n\n\tif g.server == nil || g.info.Role != db.RaftVoter {\n\t\treturn\n\t}\n\n\tclient, err := g.getClient()\n\tif err != nil {\n\t\tlogger.Warnf(\"Failed to get client: %v\", err)\n\t\treturn\n\t}\n\n\tdefer func() { _ = client.Close() }()\n\n\tfiles, err := client.Dump(context.Background(), \"db.bin\")\n\tif err != nil {\n\t\t// Just log a warning, since this is not fatal.\n\t\tlogger.Warnf(\"Failed get database dump: %v\", err)\n\t\treturn\n\t}\n\n\tdir := filepath.Join(g.db.Dir(), \"global\")\n\tfor _, file := range files {\n\t\tpath := filepath.Join(dir, file.Name)\n\t\terr := os.WriteFile(path, file.Data, 0600)\n\t\tif err != nil {\n\t\t\tlogger.Warnf(\"Failed to dump database file %s: %v\", file.Name, err)\n\t\t}\n\t}\n}", "func main() {\r\n\tlog.SetFlags(log.LstdFlags | log.Lshortfile)\r\n\tlog.SetOutput(os.Stdout)\r\n\r\n\tl, err := net.Listen(\"tcp\", \":5550\")\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\tdefer l.Close()\r\n\r\n\tlog.Println(l.Addr())\r\n\r\n\t// db, err := bolt.Open(\"packet.db\", 0600, &bolt.Options{Timeout: 1 * time.Second})\r\n\t// if err != nil {\r\n\t// \tpanic(err)\r\n\t// }\r\n\t// defer db.Close()\r\n\r\n\t// startWorker(8, func(c chan []byte) {\r\n\t// \tfor b := range c {\r\n\t// \t\t// 保存包\r\n\t// \t\tif err := db.Update(func(tx *bolt.Tx) error {\r\n\t// \t\t\tbucket, err := tx.CreateBucketIfNotExists([]byte(\"Bucket\"))\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\tid, err := bucket.NextSequence()\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\treturn bucket.Put([]byte(\"key\"+strconv.Itoa(int(id))), b)\r\n\t// \t\t}); err != nil {\r\n\t// \t\t\tlog.Println(err)\r\n\t// \t\t\tcontinue\r\n\t// \t\t}\r\n\t// \t}\r\n\t// }, c)\r\n\r\n\tfor {\r\n\t\tconn, err := l.Accept()\r\n\t\tif err != nil {\r\n\t\t\tlog.Println(err)\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t\tgo handleConn(conn)\r\n\t}\r\n}", "func ServersPush(src, dst string, cu *CommonUser, ipFile string, wt *sync.WaitGroup, ccons chan struct{}, crs chan machine.Result, timeout int) {\n\thosts, err := parseIpfile(ipFile, cu)\n\tif err != nil {\n\t\tlog.Error(\"Parse %s error, error=%s\", ipFile, err)\n\t\treturn\n\t}\n\n\tips := config.GetIps(hosts)\n\tlog.Info(\"[servers]=%v\", ips)\n\tfmt.Printf(\"[servers]=%v\\n\", ips)\n\n\tls := len(hosts)\n\tgo output.PrintResults2(crs, ls, wt, ccons, timeout)\n\n\tfor _, h := range hosts {\n\t\tccons <- struct{}{}\n\t\tserver := machine.NewScpServer(h.Ip, h.Port, h.User, h.Psw, \"scp\", src, dst, cu.force, timeout)\n\t\twt.Add(1)\n\t\tgo server.PRunScp(crs)\n\t}\n}", "func ScheduleScrapes(mtID int, attempt int, app *Application) func(time.Time) {\n\n\treturn func(now time.Time) {\n\n\t\tfail := func(err error) {\n\t\t\tlog.Print(log.Error, err)\n\t\t\tat := now.Add(time.Duration(app.Config.Scheduling.WaitTime) * time.Minute)\n\n\t\t\t// schedule another attempt unless max attempts have been done.\n\t\t\t// if max attempts exceeded, schedule the next day's task\n\t\t\tif attempt < app.Config.Scheduling.MaxAttempts {\n\t\t\t\tlog.Printf(log.Warning, \"attempt %d to schedule scrapes for mtID=%d will retry at %s\",\n\t\t\t\t\tattempt+2, mtID, at.Format(time.UnixDate))\n\t\t\t\tapp.Scheduler.Add(scheduler.NewTask(\n\t\t\t\t\tat,\n\t\t\t\t\tScheduleScrapes(mtID, attempt+1, app)))\n\t\t\t} else {\n\t\t\t\tlog.Printf(log.Warning, \"exceeded max attempts (%d) to schedule scrapes for mtID=%d).\", attempt, mtID)\n\t\t\t\tapp.Scheduler.Add(scheduler.NewTask(\n\t\t\t\t\tstartOfNextDay(at),\n\t\t\t\t\tScheduleScrapes(mtID, 0, app)))\n\t\t\t}\n\t\t}\n\n\t\t// read mt and cams\n\t\tmt, err := db.Mountain(mtID)\n\t\tcams, err := db.CamerasOnMountain(mtID)\n\t\tif err != nil {\n\t\t\tfail(err)\n\t\t\treturn // can't continue if can't read DB\n\t\t}\n\n\t\t// get tz info for mt\n\t\ttz, err := time.LoadLocation(mt.TzLocation)\n\t\tif err != nil {\n\t\t\tfail(err)\n\t\t\treturn // can't continue if can't get tz\n\t\t}\n\t\tnow = now.In(tz) // convert time to correct tz\n\t\tlog.Printf(log.Debug, \"processing mountain %s(id=%d)\", mt.Name, mt.ID)\n\n\t\t// get astro data for mt\n\t\t// const maxTries = 3\n\t\t// var tries int\n\t\tvar sun astro.Data\n\t\t// for ; tries < maxTries; tries++ {\n\t\t// \tsun, err = astro.Get(mt.Latitude, mt.Longitude, now)\n\t\t// \tif err == nil {\n\t\t// \t\tbreak\n\t\t// \t}\n\t\t// \ttime.Sleep(3 * time.Second)\n\t\t// }\n\t\t// if tries >= maxTries {\n\t\t// \tlog.Printf(log.Error, \"too many tries to get astro data for %s(id=%d). falling back to local calculation\", mt.Name, mt.ID)\n\t\tsun, err = astro.GetLocal(mt.Latitude, mt.Longitude, now)\n\t\tif err != nil {\n\t\t\terr = errors.Wrap(err, \"using local calculation\")\n\t\t\tfail(err)\n\t\t\treturn\n\t\t}\n\t\t// } else {\n\t\t// \tlog.Printf(log.Debug, \"took %d/%d tries to get astro data for %s(id=%d)\", tries+1, maxTries, mt.Name, mt.ID)\n\t\t// }\n\n\t\t// for each cam\n\t\tfor _, cam := range cams {\n\t\t\t// skip inactive cams\n\t\t\tif !cam.IsActive {\n\t\t\t\tlog.Printf(log.Debug, \"skipping inactive cam %s(id=%d)\", cam.Name, cam.ID)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// round current time to nearest cam interval\n\t\t\tinterval := time.Duration(cam.Interval) * time.Minute\n\t\t\tstart := roundup(now, interval)\n\t\t\tstop := startOfNextDay(now)\n\t\t\tcount := 0\n\t\t\tbegin, end := start, stop\n\t\t\t// for each time+interval until end-of-day...\n\t\t\tfor t := start; t.Before(stop); t = t.Add(interval) {\n\t\t\t\t// determine if the cam should be scraped at time t\n\t\t\t\tdata := RulesData{\n\t\t\t\t\tAstro: sun,\n\t\t\t\t\tMountain: mt,\n\t\t\t\t\tCamera: cam,\n\t\t\t\t\tNow: t}\n\t\t\t\tdo, err := cam.ExecuteRules(data)\n\t\t\t\tif do {\n\t\t\t\t\t// schedule a scrape\n\t\t\t\t\tapp.Scheduler.Add(scheduler.NewTask(\n\t\t\t\t\t\tt,\n\t\t\t\t\t\tScrape(mt.ID, cam.ID, app.Config)))\n\t\t\t\t\t// record actual number of scrapes scheduled\n\t\t\t\t\t// and the true first and last times\n\t\t\t\t\tcount++\n\t\t\t\t\tif begin.IsZero() {\n\t\t\t\t\t\tbegin = t\n\t\t\t\t\t}\n\t\t\t\t\tend = t\n\t\t\t\t} else if err != nil {\n\t\t\t\t\tfail(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tlog.Printf(log.Debug, \"%d scrapes scheduled for %s(id=%d) from %s to %s every %s\",\n\t\t\t\tcount, cam.Name, cam.ID,\n\t\t\t\tbegin.Format(time.UnixDate), end.Format(time.UnixDate),\n\t\t\t\tinterval)\n\t\t}\n\n\t\t// schedule ScheduleScrapes() for next day\n\t\tnext := startOfNextDay(now)\n\t\tapp.Scheduler.Add(scheduler.NewTask(\n\t\t\tnext,\n\t\t\tScheduleScrapes(mtID, 0, app)))\n\t\tlog.Printf(log.Debug, \"next ScheduleScrapes(%s) at %s\", mt.Name, next.Format(time.UnixDate))\n\t}\n}", "func (lob *Lobby) createDefaultGame(startingTeam int) {\n\n\tnewGame := Game{\n\t\tGameUid: shortuuid.New(),\n\t\tStartingTeam: startingTeam,\n\t\tCurrentRound: 1,\n\t\tTeam1Ready: false,\n\t\tTeam2Ready: false,\n\t\tGameState: selectedMap,\n\t\tTeam1UID: lob.Team1UID,\n\t\tTeam2UID: lob.Team2UID,\n\t\tGameMap: nagrand,\n\t}\n\n\tlob.Games = append(lob.Games, newGame)\n\n}", "func queueTrackRemote(track string) {\n\n\tm := remoteCommand{\n\t\tCommand: \"play_track\",\n\t\tParam: track,\n\t}\n\n\terr := pushMessage(context.sqs, m)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tlog.Println(\"Track Queued: \", track)\n}", "func FlushCacheProjects(pinfos []*PkgInfo, procks []*PkgRock) {\n\tq := connDb()\n\tdefer q.Close()\n\n\t// Update project data.\n\tfor _, p := range pinfos {\n\t\tinfo := new(PkgInfo)\n\t\terr := q.WhereEqual(\"path\", p.Path).Find(info)\n\t\tif err == nil {\n\t\t\t// Shoule always be nil, just in case not exist.\n\t\t\tp.Id = info.Id\n\t\t\t// Limit 10 views each period.\n\t\t\tif p.Views-info.Views > 10 {\n\t\t\t\tp.Views = info.Views + 10\n\t\t\t}\n\t\t}\n\t\t_, err = q.Save(p)\n\t\tif err != nil {\n\t\t\tbeego.Error(\"models.FlushCacheProjects(\", p.Path, \") ->\", err)\n\t\t}\n\t}\n\n\t// Update rock this week.\n\tif time.Now().UTC().Weekday() == time.Monday && utils.Cfg.MustBool(\"task\", \"rock_reset\") {\n\t\tutils.Cfg.SetValue(\"task\", \"rock_reset\", \"0\")\n\t\tutils.SaveConfig()\n\t\t// Reset rock table.\n\t\t_, err := q.Where(\"id > ?\", int64(0)).Delete(new(PkgRock))\n\t\tif err != nil {\n\t\t\tbeego.Error(\"models.FlushCacheProjects -> Reset rock table:\", err)\n\t\t}\n\t} else if time.Now().UTC().Weekday() != time.Monday && !utils.Cfg.MustBool(\"task\", \"rock_reset\") {\n\t\tutils.Cfg.SetValue(\"task\", \"rock_reset\", \"1\")\n\t\tutils.SaveConfig()\n\t}\n\n\tfor _, pr := range procks {\n\t\tr := new(PkgRock)\n\t\terr := q.WhereEqual(\"pid\", pr.Pid).Find(r)\n\t\tif err == nil {\n\t\t\tpr.Id = r.Id\n\t\t\tr.Delta += pr.Rank - r.Rank\n\t\t\tpr.Delta = r.Delta\n\t\t}\n\t\tq.Save(pr)\n\t}\n}", "func main() {\n\ttopshot.Initialize()\n\n\tisDatabaseModePtr := flag.Bool(\"useDb\", false, \"attempt to use a database, furthur env variables are required\")\n\tdumpSetPlaysPtr := flag.Bool(\"dumpSchema\", false, \"console print database schema and latest moment data in TopShot contract\")\n\tinterationsPtr := flag.Int(\"i\", 1, \"the number of iterations to execute before exiting (0 forever)\")\n\tquietPtr := flag.Bool(\"quiet\", false, \"do not display events to the console\")\n\tflag.Parse()\n\n\tvar eventEmitters []topshot.EventEmitter\n\tvar endPoint *topshot.Configuration\n\tvar initErr error\n\tif *isDatabaseModePtr {\n\t\tendPoint, initErr = topshot.Configuration_MainNet_withMySql()\n\t\tpanicOnError(initErr)\n\t} else {\n\t\tendPoint, initErr = topshot.Configuration_MainNet()\n\t\tpanicOnError(initErr)\n\t}\n\n\tif !*quietPtr {\n\t\teventEmitters = append(eventEmitters, topshot.EventEmitter_DebugConsoleListener())\n\t}\n\n\tvar db *sql.DB\n\tif len(endPoint.MySqlConnection) > 0 {\n\t\tvar dbErr error\n\t\tdb, dbErr = topshot.MySQL_Database_Create(context.Background(), endPoint)\n\t\tpanicOnError(dbErr)\n\t\teventEmitters = append(eventEmitters, topshot.MySQL_EventEmitter_Updater_Listener(db, true))\n\t} else {\n\t\tdb = nil\n\t}\n\n\tif *dumpSetPlaysPtr {\n\t\ttopshot.TopShotUtil_dumpSetPlaysData(endPoint)\n\t} else {\n\t\tprevJobstate := topshot.LoadJobState()\n\t\tinterations := *interationsPtr\n\t\tprocess := topshot.Process{\n\t\t\tConfig: endPoint,\n\t\t\tErrorControl: topshot.Backoff_Create(topshot.Backoff_AlgorithmNoBlast(topshot.Backoff_ConsoleLogger())),\n\t\t\tQueryApi: nil,\n\t\t\tLastBlockProcessed: prevJobstate.LastBlockProcessed,\n\t\t\tEmitter: topshot.EventEmitter_Create(eventEmitters),\n\t\t\tCurrentInterval: topshot.IntervalStats{},\n\t\t}\n\t\tif interations == 0 {\n\t\t\tfor i := 0; true; i++ {\n\t\t\t\terr := loop(prevJobstate, &process)\n\t\t\t\tloopCompleted(&process, err)\n\t\t\t}\n\t\t} else {\n\t\t\tfor i := 0; i < interations; i++ {\n\t\t\t\terr := loop(prevJobstate, &process)\n\t\t\t\tloopCompleted(&process, err)\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *Sync) updateRemoteDB(claims []jsonrpc.Claim, ownClaims []jsonrpc.Claim) (total, fixed, removed int, err error) {\n\tallClaimsInfo := s.mapFromClaims(claims)\n\townClaimsInfo := s.mapFromClaims(ownClaims)\n\tcount := len(allClaimsInfo)\n\tidsToRemove := make([]string, 0, count)\n\n\tfor videoID, chainInfo := range allClaimsInfo {\n\t\ts.syncedVideosMux.RLock()\n\t\tsv, claimInDatabase := s.syncedVideos[videoID]\n\t\ts.syncedVideosMux.RUnlock()\n\n\t\tmetadataDiffers := claimInDatabase && sv.MetadataVersion != int8(chainInfo.MetadataVersion)\n\t\tclaimIDDiffers := claimInDatabase && sv.ClaimID != chainInfo.ClaimID\n\t\tclaimNameDiffers := claimInDatabase && sv.ClaimName != chainInfo.ClaimName\n\t\tclaimMarkedUnpublished := claimInDatabase && !sv.Published\n\t\t_, isOwnClaim := ownClaimsInfo[videoID]\n\t\ttransferred := !isOwnClaim || s.DbChannelData.TransferState == 3\n\t\ttransferStatusMismatch := claimInDatabase && sv.Transferred != transferred\n\n\t\tif metadataDiffers {\n\t\t\tlog.Debugf(\"%s: Mismatch in database for metadata. DB: %d - Blockchain: %d\", videoID, sv.MetadataVersion, chainInfo.MetadataVersion)\n\t\t}\n\t\tif claimIDDiffers {\n\t\t\tlog.Debugf(\"%s: Mismatch in database for claimID. DB: %s - Blockchain: %s\", videoID, sv.ClaimID, chainInfo.ClaimID)\n\t\t}\n\t\tif claimNameDiffers {\n\t\t\tlog.Debugf(\"%s: Mismatch in database for claimName. DB: %s - Blockchain: %s\", videoID, sv.ClaimName, chainInfo.ClaimName)\n\t\t}\n\t\tif claimMarkedUnpublished {\n\t\t\tlog.Debugf(\"%s: Mismatch in database: published but marked as unpublished\", videoID)\n\t\t}\n\t\tif !claimInDatabase {\n\t\t\tlog.Debugf(\"%s: Published but is not in database (%s - %s)\", videoID, chainInfo.ClaimName, chainInfo.ClaimID)\n\t\t}\n\t\tif transferStatusMismatch {\n\t\t\tlog.Debugf(\"%s: is marked as transferred %t but it's actually %t\", videoID, sv.Transferred, transferred)\n\t\t}\n\n\t\tif !claimInDatabase || metadataDiffers || claimIDDiffers || claimNameDiffers || claimMarkedUnpublished || transferStatusMismatch {\n\t\t\tclaimSize := uint64(0)\n\t\t\tif chainInfo.Claim.Value.GetStream().Source != nil {\n\t\t\t\tclaimSize, err = chainInfo.Claim.GetStreamSizeByMagic()\n\t\t\t\tif err != nil {\n\t\t\t\t\tclaimSize = 0\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tutil.SendToSlack(\"[%s] video with claimID %s has no source?! panic prevented...\", s.DbChannelData.ChannelId, chainInfo.ClaimID)\n\t\t\t}\n\t\t\tfixed++\n\t\t\tlog.Debugf(\"updating %s in the database\", videoID)\n\t\t\terr = s.Manager.ApiConfig.MarkVideoStatus(shared.VideoStatus{\n\t\t\t\tChannelID: s.DbChannelData.ChannelId,\n\t\t\t\tVideoID: videoID,\n\t\t\t\tStatus: shared.VideoStatusPublished,\n\t\t\t\tClaimID: chainInfo.ClaimID,\n\t\t\t\tClaimName: chainInfo.ClaimName,\n\t\t\t\tSize: util.PtrToInt64(int64(claimSize)),\n\t\t\t\tMetaDataVersion: chainInfo.MetadataVersion,\n\t\t\t\tIsTransferred: &transferred,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn count, fixed, 0, err\n\t\t\t}\n\t\t}\n\t}\n\n\t//reload the synced videos map before we use it for further processing\n\tif fixed > 0 {\n\t\terr := s.setStatusSyncing()\n\t\tif err != nil {\n\t\t\treturn count, fixed, 0, err\n\t\t}\n\t}\n\n\tfor vID, sv := range s.syncedVideos {\n\t\tif sv.Transferred || sv.IsLbryFirst {\n\t\t\t_, ok := allClaimsInfo[vID]\n\t\t\tif !ok && sv.Published {\n\t\t\t\tsearchResponse, err := s.daemon.ClaimSearch(jsonrpc.ClaimSearchArgs{\n\t\t\t\t\tClaimID: &sv.ClaimID,\n\t\t\t\t\tPage: 1,\n\t\t\t\t\tPageSize: 20,\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif len(searchResponse.Claims) == 0 {\n\t\t\t\t\tlog.Debugf(\"%s: was transferred but appears abandoned! we should ignore this - claimID: %s\", vID, sv.ClaimID)\n\t\t\t\t\tcontinue //TODO: we should flag these on the db\n\t\t\t\t} else {\n\t\t\t\t\tif sv.IsLbryFirst {\n\t\t\t\t\t\tlog.Debugf(\"%s: was published using lbry-first so we don't want to do anything here! - claimID: %s\", vID, sv.ClaimID)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Debugf(\"%s: was transferred and was then edited! we should ignore this - claimID: %s\", vID, sv.ClaimID)\n\t\t\t\t\t}\n\t\t\t\t\t//return count, fixed, 0, errors.Err(\"%s: isn't our control but is on the database and on the blockchain. wtf is up? ClaimID: %s\", vID, sv.ClaimID)\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t_, ok := ownClaimsInfo[vID]\n\t\tif !ok && sv.Published {\n\t\t\tlog.Debugf(\"%s: claims to be published but wasn't found in the list of claims and will be removed if --remove-db-unpublished was specified (%t)\", vID, s.Manager.CliFlags.RemoveDBUnpublished)\n\t\t\tidsToRemove = append(idsToRemove, vID)\n\t\t}\n\t}\n\tif s.Manager.CliFlags.RemoveDBUnpublished && len(idsToRemove) > 0 {\n\t\tlog.Infof(\"removing: %s\", strings.Join(idsToRemove, \",\"))\n\t\terr := s.Manager.ApiConfig.DeleteVideos(idsToRemove)\n\t\tif err != nil {\n\t\t\treturn count, fixed, len(idsToRemove), err\n\t\t}\n\t\tremoved++\n\t}\n\t//reload the synced videos map before we use it for further processing\n\tif removed > 0 {\n\t\terr := s.setStatusSyncing()\n\t\tif err != nil {\n\t\t\treturn count, fixed, removed, err\n\t\t}\n\t}\n\treturn count, fixed, removed, nil\n}", "func (db *DB) Push(url, ref string) error {\n\tif ref == \"\" {\n\t\tref = db.ref\n\t}\n\t// The '+' prefix sets force=true,\n\t// so the remote ref is created if it doesn't exist.\n\trefspec := fmt.Sprintf(\"+%s:%s\", db.ref, ref)\n\tremote, err := db.repo.CreateAnonymousRemote(url, refspec)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer remote.Free()\n\tpush, err := remote.NewPush()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"git_push_new: %v\", err)\n\t}\n\tdefer push.Free()\n\tif err := push.AddRefspec(refspec); err != nil {\n\t\treturn fmt.Errorf(\"git_push_refspec_add: %v\", err)\n\t}\n\tif err := push.Finish(); err != nil {\n\t\treturn fmt.Errorf(\"git_push_finish: %v\", err)\n\t}\n\treturn nil\n}", "func (c *PumpsClient) syncLocalPumpStatus(_ context.Context) {\n\tnodeStatus := &node.Status{\n\t\tNodeID: localPump,\n\t\tAddr: c.binlogSocket,\n\t\tIsAlive: true,\n\t\tState: node.Online,\n\t}\n\tc.addPump(NewPumpStatus(nodeStatus, c.Security), true)\n}", "func PlaceBet(gid, uid int, t, txhash string, amount float64) bool {\n\tdb, err := sql.Open(\"sqlite3\", db_front)\n\tif !check_err(err) {\n\t\treturn false\n\t}\n\tdefer db.Close()\n\n\tvar query string\n\ttx, err := db.Begin()\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_472\", err})\n\t\treturn false\n\t}\n\n\t// Insert\n\tquery = \"INSERT INTO currentbet(txhash, gid, uid, type, bet) values(?,?,?,?,?)\"\n\tstmt, err := tx.Prepare(query)\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_480\", err})\n\t\treturn false\n\t}\n\tdefer stmt.Close()\n\t_, err = stmt.Exec(txhash, gid, uid, t, amount-tx_fee)\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_486\", err})\n\t\treturn false\n\t}\n\n\t// Update Game, pool poolsum, amount = amount - transaction fee 0.0001\n\tswitch t {\n\tcase \"A_Win\":\n\t\tquery = \"UPDATE game SET poolwin = poolwin + %f, poolsum = poolsum + %f WHERE id = %d\"\n\tcase \"B_Win\":\n\t\tquery = \"UPDATE game SET poollose = poollose + %f, poolsum = poolsum + %f WHERE id = %d\"\n\tcase \"Odd\":\n\t\tquery = \"UPDATE game SET poolodd = poolodd + %f, poolsum = poolsum + %f WHERE id = %d\"\n\tcase \"Even\":\n\t\tquery = \"UPDATE game SET pooleven = pooleven + %f, poolsum = poolsum + %f WHERE id = %d\"\n\tcase \"Large\":\n\t\tquery = \"UPDATE game SET poollarge = poollarge + %f, poolsum = poolsum + %f WHERE id = %d\"\n\tcase \"Small\":\n\t\tquery = \"UPDATE game SET poolsmall = poolsmall + %f, poolsum = poolsum + %f WHERE id = %d\"\n\t}\n\tquery = fmt.Sprintf(query, amount-tx_fee, amount-tx_fee, gid)\n\tstmt, err = tx.Prepare(query)\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_508\", err})\n\t\treturn false\n\t}\n\t_, err = stmt.Exec()\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_513\", err})\n\t\treturn false\n\t}\n\n\t// Update User, set balance = balance - amount\n\tquery = fmt.Sprintf(\"UPDATE user SET balance = balance - %f, alltimebet = alltimebet + %f WHERE id = %d\", amount, amount-tx_fee, uid)\n\tstmt, err = tx.Prepare(query)\n\t_, err = stmt.Exec()\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_522\", err})\n\t\treturn false\n\t}\n\n\t// Insert alluserbet, set betamount = betamount + amount - tx_fee\n\tquery = fmt.Sprintf(\"INSERT INTO alluserbet(uid, gid, type, betamount,txhash, bettime) values(?,?,?,?,?,?)\")\n\tstmt, err = tx.Prepare(query)\n\t_, err = stmt.Exec(uid, gid, t, amount-tx_fee, txhash, time.Now().Format(layout))\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_531\", err})\n\t\treturn false\n\t}\n\n\terr = tx.Commit()\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_537\", err})\n\t\ttx.Rollback()\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (i *Interactor) RebuildDB() utils.Error {\n\t// data is a map of player's results indexed by year\n\tdata, err := parse.All()\n\tif err != nil {\n\t\treturn utils.NewError(err, \"E_PARSE_RBLD\", 500)\n\t}\n\n\tdb := memdb.New()\n\n\tfor year, lines := range data {\n\t\tgame := db.AddGame(year, lines[0].Category, lines[0].Start, lines[0].End)\n\t\tfor _, line := range lines {\n\t\t\tif db.ContainsPlayer(line.Name, line.Surname) {\n\t\t\t\t// prova a risolvere ominimia\n\t\t\t\t// if !omonimiaRisolta\n\t\t\t\t// \twrite to JSON raw data\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// filter\n\t\t\t// solve if needed\n\t\t\t// save in memory\n\t\t\tplayer := db.AddPlayer(line.Name, line.Surname)\n\t\t\tresult := db.AddResult(line.Exercises, line.Time, line.Points, line.Position)\n\t\t\tdb.AddParticipation(player, game, result, line.City)\n\t\t}\n\t}\n\n\tdb.Show()\n\t// save in DB\n\treturn utils.NewNilError()\n}", "func refreshDatabases() {\n\t//Nullify all maps to not cause issues\n\tloadedMessagesMapHDog = make(map[int]Message)\n\tloadedMessagesMapHam = make(map[int]Message)\n\t/* Ping our CRUD API to get our most recent databases */\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\treq, err := http.NewRequest(\"GET\", isMessageBoardMade, nil)\n\tif err != nil {\n\t\ttheErr := \"There was an error getting a random id in getRandomID: \" + err.Error()\n\t\tlogWriter(theErr)\n\t\tfmt.Println(theErr)\n\t}\n\treq.Header.Add(\"Content-Type\", \"text/plain\")\n\n\tresp, err := http.DefaultClient.Do(req.WithContext(ctx))\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\ttheErr := \"There was an error getting a response for refreshDatabases: \" + err.Error()\n\t\tlogWriter(theErr)\n\t\tfmt.Println(theErr)\n\t}\n\n\ttype ReturnMessage struct {\n\t\tTheErr []string `json:\"TheErr\"`\n\t\tResultMsg []string `json:\"ResultMsg\"`\n\t\tSuccOrFail int `json:\"SuccOrFail\"`\n\t\tGivenHDogMB MessageBoard `json:\"GivenHDogMB\"`\n\t\tGivenHamMB MessageBoard `json:\"GivenHamMB\"`\n\t}\n\tvar otherReturnedMessage ReturnMessage\n\tjson.Unmarshal(body, &otherReturnedMessage)\n\n\t//Validate our responses; if successful response, update our db\n\tif otherReturnedMessage.SuccOrFail != 0 {\n\t\t//Failure, log error\n\t\tmessage := \"\"\n\t\tfor j := 0; j < len(otherReturnedMessage.TheErr); j++ {\n\t\t\tmessage = message + otherReturnedMessage.TheErr[j] + \"\\n\"\n\t\t}\n\t\tlogWriter(message)\n\t\tfmt.Println(message)\n\t} else {\n\t\t//Fill our databases with response\n\t\ttheMessageBoardHDog = otherReturnedMessage.GivenHDogMB\n\t\ttheMessageBoardHam = otherReturnedMessage.GivenHamMB\n\t\t//Fill our messages with go routine DEBUG\n\t\tfillMessageMaps(\"hotdog\")\n\t\tfillMessageMaps(\"hamburger\")\n\t}\n}", "func WriteDB(taskList []tasks.Task, task tasks.Task) {\n\tfmt.Println(taskList, task)\n\tnewList := []tasks.Task{task}\n\n\ttaskList = append(newList, taskList...)\n\n\tCloseDB(taskList)\n}", "func (conn *Connection) PushToRoom(room *Room) {\n\tif conn.done() {\n\t\treturn\n\t}\n\tconn.wGroup.Add(1)\n\tdefer func() {\n\t\tconn.wGroup.Done()\n\t}()\n\n\tconn.setRoom(room)\n}", "func (m *Master) StoreRun(session *gocql.Session, id gocql.UUID, ts time.Time) error {\n\tlog.Printf(\"Saving new run '%s' to DB\", id.String())\n\tq := `INSERT INTO runs (id, create_time) values (?, ?)`\n\tif err := session.Query(q, id, ts).Exec(); err != nil {\n\t\treturn fmt.Errorf(\"error storing run in DB: %v\", err)\n\t}\n\treturn nil\n}", "func (db *db) backfillVersions() error {\n\tdb.refreshLock.Lock()\n\tdefer db.refreshLock.Unlock()\n\n\tversions, err := db.sequins.backend.ListVersions(db.name, \"\", db.sequins.config.RequireSuccessFile)\n\tif err != nil {\n\t\treturn err\n\t} else if len(versions) == 0 {\n\t\treturn nil\n\t}\n\n\t// Only look at the last 3 versions, to keep this next part quick.\n\tif len(versions) > 3 {\n\t\tversions = versions[len(versions)-3:]\n\t}\n\n\t// Iterate through all the versions we know about, and track the remote and\n\t// local partitions for it. We don't download anything we don't have, but if\n\t// one is ready - because we have all the partitions locally, or because our\n\t// peers already do - we can switch to it immediately. Even if none are\n\t// available immediately, we can still start watching out for peers on old\n\t// versions for which we have data locally, in case they start to appear (as\n\t// would happen if a bunch of nodes with stale data started up together).\n\tfor i := len(versions) - 1; i >= 0; i-- {\n\t\tv := versions[i]\n\t\tfiles, err := db.sequins.backend.ListFiles(db.name, v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tversion := newVersion(db.sequins, db.localPath(v), db.name, v, len(files))\n\t\tif version.ready() {\n\t\t\t// The version is complete, most likely because our peers have it. We\n\t\t\t// can switch to it right away, and build any (possibly underreplicated)\n\t\t\t// partitions in the background.\n\t\t\t// TODO: In the case that we *do* have some data locally, this will cause\n\t\t\t// us to advertise that before we're actually listening over HTTP.\n\t\t\tlog.Println(\"Starting with pre-loaded version\", v, \"of\", db.name)\n\n\t\t\tdb.mux.prepare(version)\n\t\t\tdb.upgrade(version)\n\t\t\tdb.trackVersion(version, versionBuilding)\n\t\t\tgo func() {\n\t\t\t\terr := version.build(files)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"Error building version %s of %s: %s\", v, db.name, err)\n\t\t\t\t\tdb.trackVersion(version, versionError)\n\t\t\t\t}\n\n\t\t\t\tlog.Println(\"Finished building version\", v, \"of\", db.name)\n\t\t\t\tdb.trackVersion(version, versionAvailable)\n\t\t\t\tversion.advertiseAndWait()\n\t\t\t}()\n\n\t\t\tbreak\n\t\t} else if version.getBlockStore() != nil {\n\t\t\t// The version isn't complete, but we have partitions locally and can\n\t\t\t// start waiting on peers. This happens if, for example, a complete\n\t\t\t// cluster with stored data comes up all at once.\n\t\t\tdb.switchVersion(version)\n\t\t} else {\n\t\t\tversion.close()\n\t\t}\n\t}\n\n\tgo db.cleanupStore()\n\treturn nil\n}", "func main() {\n\trand.Seed(time.Now().UTC().UnixNano())\n\n\tp := argparse.NewParser(\"ch_fill\", \"Fill Clickhouse database with data\")\n\n\tdsnArg := p.String(\"d\", \"dsn\", &argparse.Options{\n\t\tRequired: false,\n\t\tHelp: \"Clickhouse DSN for native protocol communication\",\n\t\tDefault: \"tcp://localhost:9000/?database=default&username=default\",\n\t})\n\n\ttableArg := p.String(\"t\", \"table\", &argparse.Options{\n\t\tRequired: false,\n\t\tHelp: \"Table name\",\n\t\tDefault: \"test\",\n\t})\n\n\tbatchSizeArg := p.Int(\"b\", \"batch-size\", &argparse.Options{\n\t\tRequired: false,\n\t\tHelp: \"Batch size for bulk inserts\",\n\t\tDefault: 10000,\n\t})\n\n\tmaxRecordsArg := p.Int(\"r\", \"records\", &argparse.Options{\n\t\tRequired: false,\n\t\tHelp: \"Number of records to insert in total\",\n\t\tDefault: 28800000,\n\t})\n\n\terr := p.Parse(os.Args)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdsn := *dsnArg\n\ttableName := *tableArg\n\tbatchSize := *batchSizeArg\n\tmaxRecords := *maxRecordsArg\n\ts := fmt.Sprintf(\"INSERT INTO %s (tsUnix, tsDateTime, tsString, rndNumber) VALUES (?, ?, ?, ?)\", tableName)\n\n\tc, err := sql.Open(\"clickhouse\", dsn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor batch := 0; batch < maxRecords/batchSize; batch++ {\n\t\ttx, err := c.Begin()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tstmt, err := tx.Prepare(s)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfor recordInBatch := 0; recordInBatch < batchSize; recordInBatch++ {\n\t\t\tmillisSinceEpoch := recordInBatch + (batch * batchSize)\n\t\t\tts := time.Unix(0, 0).Add(time.Duration(millisSinceEpoch) * time.Millisecond)\n\t\t\trnd := rand.Int31n(1000)\n\t\t\t_, err = stmt.Exec(ts.UnixNano(), ts, fmt.Sprint(rnd), uint32(rnd))\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t\terr = tx.Commit()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\terr = stmt.Close()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfmt.Println(\"Inserted batch\", batch+1)\n\t}\n}", "func (p *Peer) pushPeers() {\n\tp.QueueMessage(p.peersMessage())\n}", "func (gs *GameState) endGame(uStore users.Store, gameError error) {\n\tmsgInterface := map[string]interface{}{\n\t\t\"action\": \"game-over\",\n\t}\n\tif gameError != nil {\n\t\tmsgInterface[\"error\"] = gameError.Error()\n\t}\n\n\tmsg, err := json.Marshal(msgInterface)\n\tif err != nil {\n\t\tfmt.Printf(\"error marshalling JSON: %v\", err)\n\t\tselect {\n\t\tcase gs.quit <- 1:\n\t\tdefault:\n\t\t}\n\t}\n\tgs.notify(&gameEvent{\n\t\ttarget: nil,\n\t\tdata: msg,\n\t})\n\n\townerMap := make(map[bson.ObjectId]*users.User)\n\tresults := make([][]*gameResult, len(gs.gameSubmissions))\n\n\t// for each of the gameSubmission trees\n\tfor i, gameSub := range gs.gameSubmissions {\n\t\tcurr := gameSub\n\t\t// navigate through each tree, pulling out data\n\t\tfor curr != nil {\n\t\t\tif curr.roundSubmission == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// cache user pointers to reduce db lookups\n\t\t\towner, found := ownerMap[curr.roundSubmission.Owner]\n\t\t\tif !found {\n\t\t\t\tu, err := uStore.GetByID(curr.roundSubmission.Owner)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Printf(\"error marshalling JSON: %v\", err)\n\t\t\t\t\tselect {\n\t\t\t\t\tcase gs.quit <- 1:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\townerMap[u.ID] = u\n\t\t\t\towner = u\n\t\t\t}\n\t\t\tresults[i] = append(results[i], &gameResult{\n\t\t\t\tOwner: owner,\n\t\t\t\tImageHash: curr.roundSubmission.ImageHash,\n\t\t\t\tDescription: curr.roundSubmission.Description,\n\t\t\t})\n\t\t\tcurr = curr.next\n\t\t}\n\t}\n\n\t// broadcast game results to all clients\n\tmsg, err = json.Marshal(map[string]interface{}{\n\t\t\"action\": \"game-results\",\n\t\t\"results\": results,\n\t})\n\tif err != nil {\n\t\tfmt.Printf(\"error marshalling JSON: %v\", err)\n\t\tselect {\n\t\tcase gs.quit <- 1:\n\t\tdefault:\n\t\t}\n\t}\n\tgs.notify(&gameEvent{\n\t\ttarget: nil,\n\t\tdata: msg,\n\t})\n}", "func Work(log *log.Logger, dgraph data.Dgraph, search Search, keys Keys, url URL) error {\n\tlog.Println(\"feed: Work: Wait for the database is ready ...\")\n\tctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n\tdefer cancel()\n\terr := data.Readiness(ctx, dgraph.URL, 5*time.Second)\n\tif err != nil {\n\t\tlog.Printf(\"feed: Work: Readiness: ERROR: %v\", err)\n\t\treturn ErrFailed\n\t}\n\n\tdb, err := data.NewDB(dgraph)\n\tif err != nil {\n\t\tlog.Printf(\"feed: Work: New Data: ERROR: %v\", err)\n\t\treturn ErrFailed\n\t}\n\n\tctx = context.Background()\n\tif err := db.Schema.Create(ctx); err != nil {\n\t\tlog.Printf(\"feed: Work: Create Schema: ERROR: %v\", err)\n\t\treturn ErrFailed\n\t}\n\n\tcity, err := addCity(ctx, log, db, search.CityName, search.Lat, search.Lng)\n\tif err != nil {\n\t\tlog.Printf(\"feed: Work: Add City: ERROR: %v\", err)\n\t\treturn ErrFailed\n\t}\n\n\tif err := replaceWeather(ctx, log, db, keys.WeatherKey, url.Weather, city.ID, city.Lat, city.Lng); err != nil {\n\t\tlog.Printf(\"feed: Work: Replace Weather: ERROR: %v\", err)\n\t\treturn ErrFailed\n\t}\n\n\tif err := replaceAdvisory(ctx, log, db, url.Advisory, city.ID, search.CountryCode); err != nil {\n\t\tlog.Printf(\"feed: Work: Replace Advisory: ERROR: %v\", err)\n\t\treturn ErrFailed\n\t}\n\n\tif err := addPlaces(ctx, log, db, keys.MapKey, city, search.Categories, search.Radius); err != nil {\n\t\tlog.Printf(\"feed: Work: Add Place: ERROR: %v\", err)\n\t\treturn ErrFailed\n\t}\n\n\treturn nil\n}", "func main() {\n\tdb, err := sqlx.Connect(\"mysql\", user+\":\"+password+\"@/\"+dbname+\"?charset=\"+charset)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Printf(\"connected\")\n\tdefer db.Close()\n\n\turlCity := \"https://myfave.com/api/mobile/cities\"\n\n\tspaceClient := http.Client{\n\t\tTimeout: time.Second * 2, // Maximum of 2 secs\n\t}\n\n\treq, err := http.NewRequest(http.MethodGet, urlCity, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treq.Header.Set(\"User-Agent\", \"fave-testcoding\")\n\n\tres, getErr := spaceClient.Do(req)\n\tif getErr != nil {\n\t\tlog.Fatal(getErr)\n\t}\n\n\tbody, readErr := ioutil.ReadAll(res.Body)\n\tif readErr != nil {\n\t\tlog.Fatal(readErr)\n\t}\n\n\tvar cities []extract.Cities\n\n\tjson.Unmarshal([]byte(body), &cities)\n\tfor _, city := range cities {\n\t\tsqlStatement := `\n\t\tINSERT INTO city (country, currency, city_id, lat, lon, city_name, slug)\n\t\t\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?)`\n\n\t\tdb.MustExec(sqlStatement, city.Country, city.Currency, city.ID, city.Lat, city.Lng, city.Name, city.Slug)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n}", "func (self *journeyPlanner) submitFlights(tb *TravellerBots,fe *flap.Engine, startOfDay flap.EpochTime, fp *flightPaths, debit bool) error {\n\n\t// Iterate through all journeys for today\n\tit,err := self.NewIterator(startOfDay)\n\tif err != nil {\n\t\treturn logError(err)\n\t}\n\tfor it.Next() {\n\n\t\t// Retrieve planned flights and traveller\n\t\tplannedFlights := it.Value()\n\t\tp,err := it.Passport()\n\t\tif err != nil {\n\t\t\treturn logError(err)\n\t\t}\n\t\t\n\t\t// Submit all the flights\n\t\tfor _, j := range(plannedFlights.journies) {\n\t\t\n\t\t\t// Submit flight\n\t\t\tvar flights [1]flap.Flight\n\t\t\tflights[0]=j.flight\n\t\t\terr = fe.SubmitFlights(p,flights[:],j.flight.Start,debit)\n\t\t\tvar bi botId\n\t\t\tbi.fromPassport(p)\n\n\t\t\t// If successful ...\n\t\t\tlogFlight := fmt.Sprintf(\"%s from %s to %s leaving %s returning %s\", p.ToString(),j.flight.FromAirport.ToString(), j.flight.ToAirport.ToString(), j.flight.Start.ToTime(), j.flight.End.ToTime())\n\n\t\t\tif err == nil {\n\t\t\t\t// ... plan journey ...\n\t\t\t\ttb.GetBot(bi).stats.Submitted(j.flight.Distance)\n\t\t\t\tif j.jt==jtOutbound {\n\t\t\t\t\terr = self.planInbound(&j,p,startOfDay,fe)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn logError(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// ... and report\n\t\t\t\tif fp != nil { \n\t\t\t\t\tfp.addFlight(j.flight.FromAirport,j.flight.ToAirport,j.flight.Start,j.flight.End,fe.Airports,bi.band)\n\t\t\t\t}\n\t\t\t\tlogDebug(\"Flight submitted:\", logFlight)\n\t\t\t} else {\n\t\t\t\tlogDebug(\"Flight rejected:\", logFlight)\n\t\t\t\ttb.GetBot(bi).stats.Refused()\n\t\t\t}\n\t\t}\n\n\t\t// Delete the record\n\t\t// TBD\n\t}\n\n\treturn nil\n}", "func (pb *PBServer) tick() {\n pb.mu.Lock()\n // Your code here\n v := pb.view\n pb.view, _ = pb.vs.Ping(pb.view.Viewnum)\n if pb.view.Viewnum > v.Viewnum && pb.view.Backup != \"\" && pb.me == pb.view.Primary {\n// if v.Backup != pb.view.Backup && pb.view.Backup != \"\" && pb.me == pb.view.Primary {\n args := &CopyArgs{}\n reply := CopyReply{}\n args.KV = pb.kv\n args.Serials = pb.serials\n fmt.Printf(\"######%s copy database\\n\", pb.me)\n for true {\n ok := call(pb.view.Backup, \"PBServer.ForwardComplete\", args, &reply)\n if ok {\n break\n }\n }\n }\n pb.mu.Unlock()\n// DPrintf(\"tick! %s %d\\n\", pb.me, pb.view.Viewnum);\n}", "func (assignment *Assignment) Push(db *sql.DB) error {\n\t// Convert struct to map\n\tmarshalled, err := json.Marshal(assignment)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar assignmentMap map[string]interface{}\n\terr = json.Unmarshal(marshalled, &assignmentMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// fix a few fields\n\tassignmentMap[\"description\"] = string(blackfriday.MarkdownCommon([]byte(assignment.Description)))\n\tinvalidFields := []string{\"updated_at\", \"created_at\", \"id\", \"html_url\",\n\t\t\"submissions_download_url\", \"course_id\", \"anonymous_submissions\",\n\t\t\"discussion_topic\", \"intra_group_peer_reviews\", \"needs_grading_count\",\n\t\t\"peer_review_count\", \"peer_reviews_assign_at\", \"quiz_id\", \"rubric\",\n\t\t\"rubric_settings\", \"use_rubric_for_grading\"}\n\tfor _, field := range invalidFields {\n\t\tdelete(assignmentMap, field)\n\t}\n\n\ta := map[string]interface{}{\n\t\t\"assignment\": assignmentMap,\n\t}\n\n\tcourses, _ := findCourses(db)\n\tfor _, course := range courses {\n\t\tcourseId := course.CanvasId\n\t\tcreateAssignmentPath := fmt.Sprintf(assignmentsPath, courseId)\n\t\tfmt.Printf(\"Pushing %s to %s\\n\", assignment.Name, course.Name)\n\t\tmustPostObject(createAssignmentPath, url.Values{}, a, nil)\n\t}\n\treturn nil\n}", "func InsertPlayers(players []apiobjects.Player) ([]uint64, error) {\n\tvar result [MaxItems]uint64\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\tlog.Printf(\"error starting tx: %v\\n\", err)\n\t\terr2 := rescueDb()\n\t\tif err2 != nil {\n\t\t\tlogErr(err2)\n\t\t\treturn nil, err\n\t\t}\n\t\t// time.Sleep(3 * time.Second)\n\t\ttx, err2 = db.Begin()\n\t\tif err2 != nil {\n\t\t\tlogErr(err2)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// stmt, err := tx.Prepare(query)\n\tlenPlayers := 0\n\tvar newID uint64\n\tfor i, player := range players {\n\t\tlenPlayers++\n\t\trow := tx.QueryRow(\"INSERT INTO players (name, description, logo_link, rating) VALUES ($1, $2, $3, $4) RETURNING id;\",\n\t\t\tplayer.Name, player.Description, player.LogoLink, player.Rating)\n\t\tswitch err := row.Scan(&newID); err {\n\t\tcase sql.ErrNoRows:\n\t\t\tlog.Printf(\"error scanning db result: %v\\n\", err)\n\t\tcase nil:\n\t\t\tresult[i] = newID\n\t\tdefault:\n\t\t\tlog.Printf(\"error while inserting row: %v\\n\", err)\n\t\t\ttx.Rollback()\n\n\t\t\treturn nil, err\n\t\t}\n\n\t}\n\ttx.Commit()\n\treturn result[0:lenPlayers], nil\n}", "func (m *MoneyDB) transferStageToPartition(stageName string) (name string) {\n\tt, err := time.Parse(\"mem_2006_01_02_stage\", stageName)\n\tif err != nil {\n\t\tfmt.Println(\"error parsing last stage\\n\", err)\n\t\treturn\n\t}\n\nget_part:\n\tname = m.GetPartition(t)\n\n\t// partition hasn't been created\n\tif name == \"\" {\n\t\tfmt.Println(\"partition does not exist, creating...\")\n\t\t_, err = m.NewPartitionTable(t)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"coulndn't make partition table\\n\", err)\n\t\t\treturn\n\t\t}\n\t\tgoto get_part\n\t}\n\n\tq := fmt.Sprintf(`INSERT INTO runs(symbol, start, end, partition_name) (SELECT symbol, min(updated_at), max(updated_at), '%s' as partition_name from %s GROUP BY symbol)`, name, stageName)\n\n\t// register staged runs in the runs table\n\t_, err = m.Exec(q)\n\tif err != nil {\n\t\tfmt.Println(\"couldn't trasnfer from stage\\n\", err)\n\t\treturn\n\t}\n\n\t// transfer to the partition\n\tq = fmt.Sprintf(`INSERT INTO %s (SELECT * FROM %s);`, name, stageName)\n\t_, err = m.Exec(q)\n\tif err != nil {\n\t\tfmt.Println(\"couldn't trasnfer from stage\\n\", err)\n\t\treturn\n\t}\n\n\t// drop the stage\n\tq = fmt.Sprintf(`DROP TABLE %s;`, stageName)\n\t_, err = m.Exec(q)\n\tif err != nil {\n\t\tfmt.Println(\"couldn't trasnfer from stage\\n\", err)\n\t\treturn\n\t}\n\n\treturn\n}", "func SearchAndStore(src []*imap.Client, dsts map[string][]*imap.Client, dbFile string, quickSyncCount int) (err error) {\n\tvar cmd *imap.Command\n\tcmd, err = GetAllMessages(src[0])\n\tif err != nil {\n\t\tlog.Printf(\"Unable to get all messages!\")\n\t\treturn\n\t}\n\n\t// connect to cache\n\tcache, err := NewCache(dbFile)\n\tif err != nil {\n\t\tlog.Printf(\"problems initiating cache - %s\", err.Error())\n\t\treturn\n\t}\n\tdefer cache.Close()\n\n\t// setup message fetchers to pull from the source/memcache\n\tfetchRequests := make(chan fetchRequest)\n\tfor _, srcConn := range src {\n\t\tgo fetchEmails(srcConn, fetchRequests, cache)\n\t}\n\n\tvar appendRequests []chan WorkRequest\n\tvar storers sync.WaitGroup\n\t// setup storers for each destination\n\tfor _, dst := range dsts {\n\t\tstoreRequests := make(chan WorkRequest)\n\t\tfor _, dstConn := range dst {\n\t\t\tstorers.Add(1)\n\t\t\tgo CheckAndAppendMessages(dstConn, storeRequests, fetchRequests, &storers)\n\t\t}\n\t\tappendRequests = append(appendRequests, storeRequests)\n\t}\n\n\t// build the requests and send them\n\tlog.Printf(\"store processing for %d messages from the source inbox\", len(cmd.Data))\n\tvar rsp *imap.Response\n\tvar indx int\n\tstartTime := time.Now()\n\tsyncStart := 0\n\t// consider quick sync\n\tif quickSyncCount != 0 {\n\t\tsyncStart = len(cmd.Data) - quickSyncCount\n\t\tlog.Printf(\"found quick sync count. will only sync messages %d through %d\", syncStart, len(cmd.Data))\n\t}\n\tfor indx, rsp = range cmd.Data[syncStart:] {\n\t\theader := imap.AsBytes(rsp.MessageInfo().Attrs[\"RFC822.HEADER\"])\n\t\tif msg, _ := mail.ReadMessage(bytes.NewReader(header)); msg != nil {\n\t\t\theader := \"Message-Id\"\n\t\t\tvalue := msg.Header.Get(header)\n\n\t\t\t// create the store request and pass it to each dst's storers\n\t\t\tstoreRequest := WorkRequest{Value: value, Header: header, UID: rsp.MessageInfo().UID}\n\t\t\tfor _, storeRequests := range appendRequests {\n\t\t\t\tstoreRequests <- storeRequest\n\t\t\t}\n\n\t\t\tif ((indx % 100) == 0) && (indx > 0) {\n\t\t\t\tsince := time.Since(startTime)\n\t\t\t\trate := 100 / since.Seconds()\n\t\t\t\tstartTime = time.Now()\n\t\t\t\tlog.Printf(\"Completed store processing for %d messages from the source inbox. Rate: %f msg/s\", indx, rate)\n\t\t\t}\n\t\t}\n\t}\n\n\t// after everything is on the channel, close them...\n\tfor _, storeRequests := range appendRequests {\n\t\tclose(storeRequests)\n\t}\n\t// ... and wait for our workers to finish up.\n\tstorers.Wait()\n\n\t// once the storers are complete we can close the fetch channel\n\tclose(fetchRequests)\n\n\tlog.Printf(\"search and store processes complete\")\n\treturn nil\n}", "func main() {\n\tconfig, err := config.Environ()\n\tif err != nil {\n\t\tlogger := logrus.WithError(err)\n\t\tlogger.Fatalln(\"main: invalid configuration\")\n\t}\n\n\tsession := db.NewSessionStore(config.Database.Datasource, config.Database.Database)\n\tstageStore := stage.New(session)\n\tctx := context.Background()\n\n\titem1 := &core.Stage{\n\t\tID: \"1\",\n\t}\n\titem2 := &core.Stage{\n\t\tID: \"2\",\n\t}\n\tq := queue.NewQueue(stageStore)\n\tq.Schedule(ctx, item1)\n\tq.Schedule(ctx, item2)\n\tstage, err := q.Request(ctx)\n\tif err != nil {\n\t\tlogrus.Errorf(\"request next stage err : %v\", err.Error())\n\t}\n\tlogrus.Infof(\"next: %v\", stage.ID)\n}", "func (pq *persistQueue) push(task *persistTask) {\n\tpq.queue <- task\n}", "func (s *Session) sendEventsFromDatabase(parentContext context.Context, topic string, offset uint64) error {\n\tsessionLog.Debug(\"after subscribe send events\", zap.String(\"session.id\", s.ID), zap.Uint64(\"offset\", offset))\n\n\teventType, err := getEventTypeFromTopic(topic)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"get event type error: %s\", err)\n\t}\n\n\tvar conn *pgxpool.Conn\n\tconn, err = pool.Acquire(parentContext)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"pool acquire connection error: %s\", err)\n\t}\n\n\tdefer func() {\n\t\tconn.Release()\n\t}()\n\n\tevents, err := fetchAllEvents(parentContext, conn.Conn(), offset, 0) // TODO: may be need count\n\tif err != nil {\n\t\treturn fmt.Errorf(\"fetch all events error: %s\", err)\n\t}\n\n\tsessionLog.Debug(\"fetchAllEvents\",\n\t\tzap.Uint64(\"offset\", offset),\n\t\tzap.Int(\"events.len\", len(events)),\n\t\tzap.String(\"session.id\", s.ID))\n\n\tif len(events) == 0 {\n\t\treturn nil\n\t}\n\tfilteredEvents := filterEventsByEventType(events, eventType)\n\n\tsessionLog.Debug(\"filterEventsByEventType\",\n\t\tzap.Int(\"eventType\", eventType),\n\t\tzap.Int(\"filteredEvents.len\", len(filteredEvents)),\n\t\tzap.String(\"session.id\", s.ID))\n\n\tif len(filteredEvents) == 0 {\n\t\treturn nil\n\t}\n\n\terr = s.sendChunked(parentContext, filteredEvents) // blocked !\n\tif err != nil {\n\t\treturn fmt.Errorf(\"sendChunked error: %s\", err)\n\t}\n\n\treturn nil\n}", "func AllGamePending() []Game_Detail {\n\torm := get_DBFront()\n\tvar allGame, allPendingGame []Game_Detail\n\terr := orm.SetTable(\"game\").FindAll(&allGame)\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_334\", err})\n\t\treturn allGame\n\t}\n\n\tfor _, v := range allGame {\n\t\tstartTime, _ := time.Parse(layout, v.Timestarted)\n\t\ttimeNow, _ := time.Parse(layout, time.Now().String())\n\t\tif startTime.Sub(timeNow) > 15*time.Minute {\n\t\t\tallPendingGame = append(allPendingGame, v)\n\t\t}\n\t}\n\n\tSliceReverse(allPendingGame)\n\treturn allPendingGame\n}", "func FromCacheToDB() {\n\n\tvar labels []event\n\tvar data = getRedisData()\n\tfor key, value := range data {\n\t\tstringKey := key\n\t\tstringKeySplit := strings.Split(stringKey, RedisKeySeparator)\n\t\tif len(stringKeySplit) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tid := stringKeySplit[0]\n\t\tlabel := stringKeySplit[1]\n\t\tif len(id) == 0 || len(label) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\teventParam := event{\n\t\t\tid: id,\n\t\t\tlabel: label[:100],\n\t\t\tcount: value,\n\t\t}\n\t\tlabels = append(labels, eventParam)\n\t}\n\tgo bulkSaveToDB(labels)\n\tlabels = []event{}\n\tRedisClient.Do(\"FLUSHALL\").Result()\n}", "func UpdatePlayerLatestGameweekData() {\n\tlog.SetPrefix(\"UPDATE_PLAYER_LATEST_STATS - \")\n\t// TODO Cache the latestGameweekID value and if the gameweek is present\n\tlatestGameweekID := getLatestGameweekID()\n\tisGameweekPresent := isGameweekPresentInGameweekStats(latestGameweekID)\n\tdb := database.GetDB()\n\tcurrentWeekStats := FetchGameweekData(latestGameweekID)\n\tfor i := range currentWeekStats.GameweekArray {\n\t\tgameweekStat := currentWeekStats.GameweekArray[i].Stats\n\t\tgameweekStat.ElementID = currentWeekStats.GameweekArray[i].ID\n\t\tgameweekStat.GameweekNumber = latestGameweekID\n\t\tprimaryKey := strconv.Itoa(gameweekStat.ElementID) +\n\t\t\t\"_\" + strconv.Itoa(gameweekStat.GameweekNumber)\n\t\tgameweekStat.ID = primaryKey\n\t\tif isGameweekPresent {\n\t\t\tdb.Table(\"gameweek_stats\").Where(\"ID = ?\", primaryKey).\n\t\t\t\tDelete(GameweekStats{})\n\t\t}\n\t\tdb.Create(&gameweekStat)\n\t\tlog.Printf(\"Added data for player %d for game week %d\",\n\t\t\tgameweekStat.ElementID, gameweekStat.GameweekNumber)\n\t}\n}", "func (d *Release) Push(only ...string) error {\n\tif _ = d.merge(); len(d.src) == 0 {\n\t\treturn ErrMissing\n\t}\n\tif d.rebase(only); len(d.src) == 0 {\n\t\treturn ErrMissing\n\t}\n\tvar g errgroup.Group\n\tfor _, server := range d.to {\n\t\tc := server\n\t\tg.Go(func() error {\n\t\t\treturn c.Bulk(d.src)\n\t\t})\n\t}\n\td.err = g.Wait()\n\treturn d.err\n}", "func (m *Manager) cron() {\n\tm.mutex.RLock()\n\tpeers := m.peers.Excludes(nil, 5)\n\tm.mutex.RUnlock()\n\tfor _, p := range peers {\n\t\trr, err := p.ReadRecent()\n\t\tif !log.If(err) {\n\t\t\tm.mutex.Lock()\n\t\t\tupdated, errr := m.recent.Merge(rr)\n\t\t\tm.mutex.Unlock()\n\t\t\tif !log.If(errr) && updated {\n\t\t\t\tlog.If(m.Broadcast())\n\t\t\t}\n\t\t}\n\t\trp, err := p.ReadPeers()\n\t\tif !log.If(err) {\n\t\t\tlog.If(m.AddPeers(rp))\n\t\t}\n\t\trt, err := p.ReadTags()\n\t\tif !log.If(err) {\n\t\t\tlog.If(m.AddTag(rt))\n\t\t}\n\t}\n}", "func SaveStockDataToDB(stocksData []StockData, db *gorm.DB) error {\n\tfor _, sd := range stocksData {\n\t\tstockModel := &models.Stock{}\n\t\tquery := db.Where(\"code = ?\", sd.Code)\n\t\tquery.First(stockModel)\n\t\t// If stock exists, update\n\t\tif stockModel.ID != uuid.Nil {\n\t\t\tstockModel.Shares = sd.Shares\n\t\t\tstockModel.ListingBoard = sd.ListingBoard\n\t\t} else { // Else Create\n\t\t\tlayout := \"2006-01-02T15:04:05\"\n\t\t\tparsedDate, err := time.Parse(layout, sd.ListingDate)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t\tstockModel = &models.Stock{\n\t\t\t\tCode: sd.Code,\n\t\t\t\tName: sd.Name,\n\t\t\t\tListingDate: parsedDate,\n\t\t\t\tShares: sd.Shares,\n\t\t\t\tListingBoard: sd.ListingBoard,\n\t\t\t}\n\t\t}\n\t\tdb.Save(stockModel)\n\t}\n\treturn nil\n}", "func pushTxn(db *client.DB, now hlc.Timestamp, txn *roachpb.Transaction,\n\ttyp roachpb.PushTxnType) {\n\n\t// Attempt to push the transaction which created the intent.\n\tpushArgs := &roachpb.PushTxnRequest{\n\t\tSpan: roachpb.Span{\n\t\t\tKey: txn.Key,\n\t\t},\n\t\tNow: now,\n\t\tPusherTxn: roachpb.Transaction{TxnMeta: enginepb.TxnMeta{Priority: math.MaxInt32}},\n\t\tPusheeTxn: txn.TxnMeta,\n\t\tPushType: typ,\n\t}\n\tb := &client.Batch{}\n\tb.AddRawRequest(pushArgs)\n\tif err := db.Run(b); err != nil {\n\t\tlog.Warningf(context.TODO(), \"push of txn %s failed: %s\", txn, err)\n\t\treturn\n\t}\n\tbr := b.RawResponse()\n\t// Update the supplied txn on successful push.\n\t*txn = br.Responses[0].GetInner().(*roachpb.PushTxnResponse).PusheeTxn\n}" ]
[ "0.56290245", "0.54186916", "0.5408968", "0.5404486", "0.53052187", "0.51920897", "0.5188981", "0.5183002", "0.5134982", "0.49880126", "0.49807742", "0.4967738", "0.495166", "0.49266243", "0.49192014", "0.48657754", "0.48431918", "0.4842832", "0.48361173", "0.48208678", "0.48192996", "0.47969696", "0.47746587", "0.47393075", "0.47376248", "0.47225147", "0.4706784", "0.47034916", "0.46895593", "0.4686007", "0.4682446", "0.46604347", "0.46442547", "0.46262002", "0.46207896", "0.46050707", "0.45836195", "0.4582195", "0.45417038", "0.4539397", "0.45236266", "0.45195863", "0.45193616", "0.45015177", "0.4485674", "0.4477839", "0.4472423", "0.446545", "0.44627306", "0.44546354", "0.44513682", "0.44509143", "0.44411168", "0.44268814", "0.44265684", "0.44252482", "0.4424133", "0.44209462", "0.44200012", "0.441815", "0.43946454", "0.43903166", "0.43837062", "0.43826896", "0.4381298", "0.43701446", "0.4369779", "0.43680575", "0.43678397", "0.43612534", "0.43468988", "0.43395793", "0.43388933", "0.43331724", "0.4330408", "0.4329707", "0.43294784", "0.43266362", "0.4325728", "0.4320609", "0.43199193", "0.4315704", "0.43092412", "0.4308098", "0.43043038", "0.42950466", "0.42895022", "0.42856157", "0.42769456", "0.42746222", "0.42746106", "0.42721707", "0.42709583", "0.4266318", "0.42660055", "0.424771", "0.4245842", "0.42452386", "0.42445466", "0.4240127" ]
0.8595324
0
StartSyncLoop starts a go routine to fetch games from MASTER master base station this runs on an interval
func StartSyncLoop() { interval := time.NewTicker(30 * time.Second) quit := make(chan struct{}) go fetchGames(interval, quit) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (k *KubeBoot) RunSyncLoop() {\n\tctx := context.Background()\n\n\tif k.Master {\n\t\tclient, err := k.Kubernetes.KubernetesClient()\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"could not create kubernetes client: %v\", err))\n\t\t}\n\n\t\tklog.Info(\"polling for apiserver readiness\")\n\t\tfor {\n\t\t\t_, err = client.CoreV1().Namespaces().Get(ctx, \"kube-system\", metav1.GetOptions{})\n\t\t\tif err == nil {\n\t\t\t\tklog.Info(\"successfully connected to the apiserver\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tklog.Infof(\"failed to connect to the apiserver (will sleep and retry): %v\", err)\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t}\n\n\tfor {\n\t\tif err := k.syncOnce(ctx); err != nil {\n\t\t\tklog.Warningf(\"error during attempt to bootstrap (will sleep and retry): %v\", err)\n\t\t}\n\n\t\ttime.Sleep(1 * time.Minute)\n\t}\n}", "func (s *Server) Sync() {\n\tdefer base.CheckPanic()\n\tbase.Logger().Info(\"start meta sync\", zap.Int(\"meta_timeout\", s.cfg.Master.MetaTimeout))\n\tfor {\n\t\tvar meta *protocol.Meta\n\t\tvar err error\n\t\tif meta, err = s.masterClient.GetMeta(context.Background(), &protocol.RequestInfo{NodeType: protocol.NodeType_ServerNode}); err != nil {\n\t\t\tbase.Logger().Error(\"failed to get meta\", zap.Error(err))\n\t\t\tgoto sleep\n\t\t}\n\n\t\t// load master config\n\t\terr = json.Unmarshal([]byte(meta.Config), &s.cfg)\n\t\tif err != nil {\n\t\t\tbase.Logger().Error(\"failed to parse master config\", zap.Error(err))\n\t\t\tgoto sleep\n\t\t}\n\n\t\t// connect to data store\n\t\tif s.dataAddress != s.cfg.Database.DataStore {\n\t\t\tbase.Logger().Info(\"connect data store\", zap.String(\"database\", s.cfg.Database.DataStore))\n\t\t\tif s.dataStore, err = data.Open(s.cfg.Database.DataStore); err != nil {\n\t\t\t\tbase.Logger().Error(\"failed to connect data store\", zap.Error(err))\n\t\t\t\tgoto sleep\n\t\t\t}\n\t\t\ts.dataAddress = s.cfg.Database.DataStore\n\t\t}\n\n\t\t// connect to cache store\n\t\tif s.cacheAddress != s.cfg.Database.CacheStore {\n\t\t\tbase.Logger().Info(\"connect cache store\", zap.String(\"database\", s.cfg.Database.CacheStore))\n\t\t\tif s.cacheStore, err = cache.Open(s.cfg.Database.CacheStore); err != nil {\n\t\t\t\tbase.Logger().Error(\"failed to connect cache store\", zap.Error(err))\n\t\t\t\tgoto sleep\n\t\t\t}\n\t\t\ts.cacheAddress = s.cfg.Database.CacheStore\n\t\t}\n\n\t\t// check FM version\n\t\ts.latestFMVersion = meta.FmVersion\n\t\tif s.latestFMVersion != s.fmVersion {\n\t\t\tbase.Logger().Info(\"new factorization machine model found\",\n\t\t\t\tzap.Int64(\"old_version\", s.fmVersion),\n\t\t\t\tzap.Int64(\"new_version\", s.latestFMVersion))\n\t\t\ts.syncedChan <- true\n\t\t}\n\tsleep:\n\t\ttime.Sleep(time.Duration(s.cfg.Master.MetaTimeout) * time.Second)\n\t}\n}", "func StartSync() error {\n\tfor {\n\t\terr := manager().processOnce()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}", "func BeginSync(st o.SyncType) {\n\n\tdbName := c.DBConfig.DBName.StockD1\n\tnames, _ := h.GetCollectionNames(dbName)\n\tcCount := len(names)\n\tvar start, end time.Time\n\tstart = time.Now()\n\tfmt.Println(\"Sync stock base information from database StockD1. SyncType is \", st.ToString())\n\tfmt.Println(\"Begin time: \", start.Format(\"2006-01-02 15:04:05\"))\n\tfor i, name := range names {\n\t\tIncrementSync(name, st)\n\t\tfmt.Printf(\"Stock code: %s (%d/%d) \\r\", name, i+1, cCount)\n\t}\n\tend = time.Now()\n\tfmt.Println(\"Synchronization Completed at \", end.Format(\"2006-01-02 15:04:05\"))\n\tfmt.Println(\"Duration: \", end.Sub(start).String())\n\tfmt.Println()\n}", "func Sync() {\n\tticker := time.NewTicker(time.Second * 30)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tallBroadcasts, err := fetchAllPlayingBroadcasts()\n\t\t\tif err != nil {\n\t\t\t\tutils.GetLog().Error(\"broadcasts.Sync.fetchAllPlayingBroadcasts error: %+v\", err)\n\t\t\t}\n\t\t\tfor _, bro := range allBroadcasts {\n\t\t\t\tbroSync := NewBroadcastSync(bro)\n\t\t\t\tif err := broSync.Do(); err != nil {\n\t\t\t\t\tutils.GetLog().Error(\"broadcasts.BroadcastSync.Do error: %+v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (a *Agent) StartSync() {\n\tgo a.sync.Run()\n\ta.logger.Printf(\"[INFO] agent: started state syncer\")\n}", "func BeginSyncRTD() {\n\tdbNameRaw := c.DBConfig.DBName.StockMarketRawD1\n\tnamesRaw, _ := h.GetCollectionNames(dbNameRaw)\n\n\tcCount := len(namesRaw)\n\tvar start, end time.Time\n\tstart = time.Now()\n\tfmt.Println(\"Sync database StockMarketRawD1 to StockD1.\")\n\tfmt.Println(\"Begin time: \", start.Format(\"2006-01-02 15:04:05\"))\n\tfor i, name := range namesRaw {\n\t\tIncrementSyncRTD(name)\n\t\tfmt.Printf(\"Stock code: %s (%d/%d) \\r\", name, i+1, cCount)\n\t}\n\tend = time.Now()\n\tfmt.Println(\"Synchronization Completed at \", end.Format(\"2006-01-02 15:04:05\"))\n\tfmt.Println(\"Duration: \", end.Sub(start).String())\n\tfmt.Println()\n}", "func startSyncDispatcher() {\n\tif syncRequired() && !syncDispatcherRunning {\n\t\tsync := newSyncDispatcher(varnamdConfig.syncIntervalInSecs * time.Second)\n\t\tsync.start()\n\t\tsync.runNow() // run one round of sync immediatly rather than waiting for the next interval to occur\n\t\tsyncDispatcherRunning = true\n\t}\n}", "func (server *Server) Start() {\n\t// Here we create the local player\n\tserver.syncsDelay = append(server.syncsDelay, []int{})\n\tserver.player = fake.FullName()\n\tserver.players = append(server.players, server.player)\n\tserver.id = 0\n\tserver.syncs = append(server.syncs, fmt.Sprintf(\"new %s %d\", server.player, server.id))\n\n\t// For ever loop on another thread\n\tgo func() {\n\t\tfor {\n\t\t\t// Handle incoming request\n\t\t\tconn, err := server.ln.Accept()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdata := make([]byte, 256)\n\t\t\t_, err = conn.Read(data)\n\t\t\tif err != nil {\n\t\t\t\tprint(err.Error())\n\t\t\t}\n\t\t\tbody := string(data)\n\n\t\t\tif strings.Contains(body, \"new\") {\n\t\t\t\t// New player can only join if the game isn't started\n\t\t\t\tif !server.started {\n\t\t\t\t\t// Clean given command\n\t\t\t\t\t// Something from \"new Sarah Montgomery\\x00\" to \"Sarah Montgomery\"\n\t\t\t\t\tname := strings.Replace(body, \"new \", \"\", 1)\n\t\t\t\t\tname = strings.Replace(name, \"\\x00\", \"\", 1)\n\n\t\t\t\t\t// Send id for new player\n\t\t\t\t\t_, _ = fmt.Fprintf(conn, strconv.Itoa(len(server.players)))\n\n\t\t\t\t\tsync := fmt.Sprintf(\"new %s %d\", name, len(server.players))\n\t\t\t\t\tprintln(sync)\n\n\t\t\t\t\t// Register this new player\n\t\t\t\t\tserver.players = append(server.players, name) // new name\n\t\t\t\t\tfirstSyncs := make([]int, len(server.syncs)) // all modification before creation has to be sync\n\t\t\t\t\tfor i, _ := range server.syncs {\n\t\t\t\t\t\tfirstSyncs[i] = i\n\t\t\t\t\t}\n\t\t\t\t\tserver.syncsDelay = append(server.syncsDelay, firstSyncs) // new array of not sent sync\n\t\t\t\t\tserver.NewSync(sync, len(server.players)-1) // other should be warned about this creation\n\t\t\t\t} else {\n\t\t\t\t\t_, _ = fmt.Fprintf(conn, \"kick them all\")\n\t\t\t\t}\n\t\t\t} else if strings.Contains(body, \"fetch\") {\n\t\t\t\t// Get player id first\n\t\t\t\tid := getPlayerID(body, 6)\n\n\t\t\t\t// Return syncs that hasn't be sent yet\n\t\t\t\tdata := \"\"\n\t\t\t\tfor _, syncID := range server.syncsDelay[id] {\n\t\t\t\t\tdata += server.syncs[syncID] + \"\\n\"\n\t\t\t\t}\n\t\t\t\tif data == \"\" {\n\t\t\t\t\t_, _ = fmt.Fprintf(conn, \"<empty>\")\n\t\t\t\t} else {\n\t\t\t\t\t_, _ = fmt.Fprintf(conn, data)\n\n\t\t\t\t\t// Player was warned\n\t\t\t\t\t// So he won't be warned again\n\t\t\t\t\tserver.syncsDelay[id] = []int{}\n\t\t\t\t}\n\t\t\t} else if strings.Contains(body, \"sync\") {\n\t\t\t\t// Don't bother me with modification if you can't do modification\n\t\t\t\t// No useless job\n\t\t\t\tif !strings.Contains(body, \"<empty>\") {\n\t\t\t\t\t// Get player id first\n\t\t\t\t\tid := getPlayerID(body, 5)\n\n\t\t\t\t\t// Remove \"sync %d\" from received sync\n\t\t\t\t\tbody = body[7 : len(body)-1]\n\n\t\t\t\t\t// Register sync\n\t\t\t\t\tserver.NewSync(body, id)\n\t\t\t\t\t// println(id)\n\t\t\t\t}\n\t\t\t\t_, _ = fmt.Fprintf(conn, \"good\")\n\t\t\t} else {\n\t\t\t\t_, _ = fmt.Fprintf(conn, \"what?\")\n\t\t\t}\n\t\t\t_ = conn.Close()\n\t\t}\n\t}()\n}", "func SyncRemoteFragmentationSessionsLoop(nsCli *nscli.Client) {\n\tfor {\n\t\tctxID, err := uuid.NewV4()\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"new uuid error\")\n\t\t}\n\n\t\tctx := context.Background()\n\t\tctx = context.WithValue(ctx, logging.ContextIDKey, ctxID)\n\n\t\terr = storage.Transaction(func(ctx context.Context, handler *store.Handler) error {\n\t\t\treturn syncRemoteFragmentationSessions(ctx, handler, nsCli)\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"sync remote fragmentation setup error\")\n\t\t}\n\t\ttime.Sleep(ctrl.s.SyncInterval)\n\t}\n}", "func (s *ServerGroup) Sync() {\n\tsyncCh := s.targetManager.SyncCh()\n\n\tfor {\n\t\tselect {\n\t\tcase <-s.ctx.Done():\n\t\t\treturn\n\t\tcase targetGroupMap := <-syncCh:\n\t\t\tlogrus.Debug(\"Updating targets from discovery manager\")\n\t\t\t// TODO: retry and error handling\n\t\t\terr := s.loadTargetGroupMap(targetGroupMap)\n\t\t\tfor err != nil {\n\t\t\t\tlogrus.Errorf(\"Error loading servergroup, retrying: %v\", err)\n\t\t\t\t// TODO: configurable backoff\n\t\t\t\tselect {\n\t\t\t\tcase <-time.After(time.Second):\n\t\t\t\t\terr = s.loadTargetGroupMap(targetGroupMap)\n\t\t\t\tcase <-s.ctx.Done():\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *DataStore) StartSync(stop <-chan struct{}) {\n\tgo func() {\n\t\tticker := time.NewTicker(1 * time.Minute)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\ts.Lock()\n\t\t\t\tif s.dirty {\n\t\t\t\t\tfile, err := os.Create(s.path)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Errorf(\"data not saved. %v\", err)\n\t\t\t\t\t\ts.Unlock()\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\terr = s.Write(file)\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Errorf(\"data not saved. %v\", err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Infoln(\"saved data\")\n\t\t\t\t\t\ts.dirty = false\n\t\t\t\t\t}\n\t\t\t\t\tfile.Close()\n\t\t\t\t}\n\t\t\t\ts.Unlock()\n\t\t\tcase <-stop:\n\t\t\t\tlog.Infoln(\"stopping data sync\")\n\t\t\t\tticker.Stop()\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n}", "func (m *Monitor) Sync() {\n\tfor name := range m.clients {\n\t\tgo func(n string, client *client.HTTP) {\n\t\t\terr := m.CaptureNetData(client, n)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"error parsing netData for %s: %v\\n\", name, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Printf(\"parsed netData for %s\\n\", name)\n\n\t\t}(name, m.clients[name])\n\t}\n}", "func (sm *SyncManager) startSync() {\n\t// Return now if we're already syncing.\n\tif sm.syncPeer != nil {\n\t\treturn\n\t}\n\n\tbestHeight := sm.cfg.Chain.BestHeight()\n\tvar bestPeer *peer.Peer\n\tfor peer, state := range sm.peerStates {\n\t\tif !state.syncCandidate {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Remove sync candidate peers that are no longer candidates due\n\t\t// to passing their latest known block. NOTE: The < is\n\t\t// intentional as opposed to <=. While technically the peer\n\t\t// doesn't have a later block when it's equal, it will likely\n\t\t// have one soon so it is a reasonable choice. It also allows\n\t\t// the case where both are at 0 such as during regression test.\n\t\tif peer.Height() < bestHeight {\n\t\t\tstate.syncCandidate = false\n\t\t\tcontinue\n\t\t}\n\n\t\t// Just pick the first available candidate.\n\t\tbestPeer = peer\n\t\tbreak\n\t}\n\n\t// Start syncing from the best peer if one was selected.\n\tif bestPeer != nil {\n\t\t// Do not start syncing if we have the same height with best peer.\n\t\tif bestPeer.Height() == bestHeight {\n\t\t\treturn\n\t\t}\n\n\t\tsm.syncWith(bestPeer)\n\t} else {\n\t\tlog.Warnf(\"No sync peer candidates available\")\n\t}\n}", "func (this *RpcObject) Loop() {\n\tfor this.IsRun {\n\t\tstart := time.Now()\n\t\tthis.ExecuteEvent()\n\t\tdelta := MAX_SLEEP_TIME - time.Now().Sub(start)\n\t\tif delta > 0 {\n\t\t\ttime.Sleep(delta)\n\t\t} else {\n\t\t\truntime.Gosched()\n\t\t}\n\t}\n}", "func (module *ScreensaverModule) Loop(srv *Server) {\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(5 * time.Second):\n\t\t\tmodule.Tick(srv)\n\t\t}\n\t}\n}", "func (synckerManager *SynckerManager) manageSyncProcess() {\n\tdefer time.AfterFunc(time.Second*5, synckerManager.manageSyncProcess)\n\n\t//check if enable\n\tif !synckerManager.isEnabled || synckerManager.config == nil {\n\t\treturn\n\t}\n\trole, chainID := synckerManager.config.Node.GetUserMiningState()\n\tsynckerManager.BeaconSyncProcess.isCommittee = (role == common.CommitteeRole) && (chainID == -1)\n\n\tpreloadAddr := synckerManager.config.Blockchain.GetConfig().ChainParams.PreloadAddress\n\tsynckerManager.BeaconSyncProcess.start()\n\n\twg := sync.WaitGroup{}\n\twantedShard := synckerManager.config.Blockchain.GetWantedShard()\n\tfor sid, syncProc := range synckerManager.ShardSyncProcess {\n\t\twg.Add(1)\n\t\tgo func(sid int, syncProc *ShardSyncProcess) {\n\t\t\tdefer wg.Done()\n\t\t\tif _, ok := wantedShard[byte(sid)]; ok || (int(sid) == chainID) {\n\t\t\t\t//check preload shard\n\t\t\t\tif preloadAddr != \"\" {\n\t\t\t\t\tif syncProc.status != RUNNING_SYNC { //run only when start\n\t\t\t\t\t\tif err := preloadDatabase(sid, int(syncProc.Chain.GetEpoch()), preloadAddr, synckerManager.config.Blockchain.GetShardChainDatabase(byte(sid)), nil); err != nil {\n\t\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t\t\tLogger.Infof(\"Preload shard %v fail!\", sid)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsynckerManager.config.Blockchain.RestoreShardViews(byte(sid))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsyncProc.start()\n\t\t\t} else {\n\t\t\t\tsyncProc.stop()\n\t\t\t}\n\t\t\tsyncProc.isCommittee = role == common.CommitteeRole || role == common.PendingRole\n\t\t}(sid, syncProc)\n\t}\n\twg.Wait()\n\n}", "func GameLoop(gs *GameService, c config.Configuration, seed int64) {\n\tsleep, err := time.ParseDuration(c.SleepBetween)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor {\n\t\ttime.Sleep(sleep)\n\t\tif c.MinimumPlayer <= len(gs.players) {\n\t\t\tlog.Print(\"New game started with \", len(gs.players), \" players\")\n\t\t\tboard, winner, err := gs.startGame(c, seed)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(\"StartGame\", err)\n\t\t\t}\n\t\t\tlog.Print(\"Game ended without errors, winner: \", board.Winner().Name)\n\t\t\tgs.total = scoreboard.Join(gs.total, *board)\n\t\t\tif winner == nil {\n\t\t\t\twinner = board.Winner()\n\t\t\t}\n\t\t\tgs.announceResult(board, winner)\n\t\t\tgs.Clean()\n\t\t}\n\t\tgs.PingPlayers()\n\t}\n}", "func (s *Server) loop() {\n\theartbeatTicker := s.clock.NewTicker(heartbeatInterval)\n\tdefer heartbeatTicker.Stop()\n\n\tresyncTicker := s.clock.NewTicker(resyncInterval)\n\tdefer resyncTicker.Stop()\n\n\tfor {\n\t\tselect {\n\t\t//\n\t\t// Re-sync cluster peers\n\t\t//\n\t\tcase <-resyncTicker.Chan():\n\t\t\terr := s.resyncPeerList()\n\t\t\tif err != nil {\n\t\t\t\ts.WithError(err).Error(\"Unexpected error re-syncing the list of peer nodes.\")\n\t\t\t}\n\n\t\t\terr = s.resyncNethealthPods()\n\t\t\tif err != nil {\n\t\t\t\ts.WithError(err).Error(\"Unexpected error re-syncing the list of peer pods.\")\n\t\t\t}\n\t\tcase <-s.triggerResync:\n\t\t\terr := s.resyncPeerList()\n\t\t\tif err != nil {\n\t\t\t\ts.WithError(err).Error(\"Unexpected error re-syncing the list of peer nodes.\")\n\t\t\t}\n\n\t\t\terr = s.resyncNethealthPods()\n\t\t\tif err != nil {\n\t\t\t\ts.WithError(err).Error(\"Unexpected error re-syncing the list of peer pods.\")\n\t\t\t}\n\n\t\t//\n\t\t// Send a heartbeat to each peer we know about\n\t\t// Check for peers that are timing out / down\n\t\t//\n\t\tcase <-heartbeatTicker.Chan():\n\t\t\ts.checkTimeouts()\n\t\t\tfor _, peer := range s.peers {\n\t\t\t\ts.sendHeartbeat(peer)\n\t\t\t}\n\n\t\t//\n\t\t// Rx heartbeats responses from peers\n\t\t//\n\t\tcase rx := <-s.rxMessage:\n\t\t\terr := s.processAck(rx)\n\t\t\tif err != nil {\n\t\t\t\ts.WithFields(logrus.Fields{\n\t\t\t\t\tlogrus.ErrorKey: err,\n\t\t\t\t\t\"peer_addr\": rx.peerAddr,\n\t\t\t\t\t\"rx_time\": rx.rxTime,\n\t\t\t\t\t\"message\": rx.message,\n\t\t\t\t}).Error(\"Error processing icmp message.\")\n\t\t\t}\n\t\t}\n\t}\n}", "func StartUpdateFollowersLoop(\n\tctx context.Context,\n\tfollowTarget string,\n\tredisCl *redis.Client,\n\thelixCl *helix.Client,\n) {\n\tgo func() {\n\t\tUpdateFollowers(ctx, followTarget, redisCl, helixCl)\n\t\tt := time.NewTicker(5 * time.Minute)\n\t\tfor range t.C {\n\t\t\tUpdateFollowers(ctx, followTarget, redisCl, helixCl)\n\t\t}\n\t}()\n}", "func (sm *SyncManager) startSync() {\n\t// Return now if we're already syncing.\n\tif sm.syncPeer != nil {\n\t\treturn\n\t}\n\n\tbestHeight := sm.chain.GetHeight()\n\tvar bestPeer *peer.Peer\n\tfor peer, state := range sm.peerStates {\n\t\tif !state.syncCandidate {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Remove sync candidate peers that are no longer candidates due\n\t\t// to passing their latest known block. NOTE: The < is\n\t\t// intentional as opposed to <=. While technically the peer\n\t\t// doesn't have a later block when it's equal, it will likely\n\t\t// have one soon so it is a reasonable choice. It also allows\n\t\t// the case where both are at 0 such as during regression test.\n\t\tif peer.Height() < bestHeight {\n\t\t\tstate.syncCandidate = false\n\t\t\tcontinue\n\t\t}\n\n\t\t// Just pick the first available candidate.\n\t\tbestPeer = peer\n\t\tbreak\n\t}\n\n\t// Start syncing from the best peer if one was selected.\n\tif bestPeer != nil {\n\t\t// Do not start syncing if we have the same height with best peer.\n\t\tif bestPeer.Height() == bestHeight {\n\t\t\treturn\n\t\t}\n\n\t\t// Clear the requestedBlocks if the sync peer changes, otherwise\n\t\t// we may ignore blocks we need that the last sync peer failed\n\t\t// to send.\n\t\tsm.requestedBlocks = make(map[common.Uint256]struct{})\n\t\tsm.requestedConfirmedBlocks = make(map[common.Uint256]struct{})\n\n\t\tlocator, err := sm.chain.LatestBlockLocator()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to get block locator for the \"+\n\t\t\t\t\"latest block: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Infof(\"Syncing to block height %d from peer %v\",\n\t\t\tbestPeer.Height(), bestPeer.Addr())\n\n\t\tsm.syncPeer = bestPeer\n\t\tsm.syncHeight = bestPeer.Height()\n\t\tsm.syncStartTime = time.Now()\n\t\tbestPeer.PushGetBlocksMsg(locator, &zeroHash)\n\t} else {\n\t\tlog.Warnf(\"No sync peer candidates available\")\n\t}\n}", "func (oc *Operachain) Sync() {\n\tfor {\n\t\t//requestVersion\n\t\ttime.Sleep(time.Second)\n\n\t\tfor _, node := range oc.KnownAddress {\n\t\t\tif node != oc.MyAddress {\n\t\t\t\tpayload := gobEncode(HeightMsg{oc.KnownHeight, oc.MyAddress})\n\t\t\t\treqeust := append(commandToBytes(\"rstBlocks\"), payload...)\n\t\t\t\toc.sendData(node, reqeust)\n\t\t\t}\n\t\t}\n\t}\n}", "func startSync(conn *client.Conn, serverID uint32, name string, pos uint32) error {\n\tconn.ResetSequence()\n\tpacket := dumpCommand(serverID, name, pos)\n\terr := conn.WritePacket(packet)\n\treturn errors.Annotatef(err, \"write COM_BINLOG_DUMP %v\", packet)\n}", "func (client *Client) Sync() {\n\t/*go func() {*/\n\tstart := time.Now()\n\t// Fetch\n\tconn, err := net.Dial(\"tcp\", client.address)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t_, _ = fmt.Fprintf(conn, \"fetch \"+strconv.Itoa(client.id))\n\tresponse := make([]byte, 1024)\n\t_, err = conn.Read(response)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tbody := string(response)\n\tif !strings.Contains(body, \"<empty>\") {\n\t\tclient.syncs = body\n\t}\n\t_ = conn.Close()\n\n\t// Then sync\n\tconn, err = net.Dial(\"tcp\", client.address)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Build sync object\n\tdata := \"\"\n\tif len(client.actions) != 0 {\n\t\tfor _, action := range client.actions {\n\t\t\tswitch action.(type) {\n\t\t\tcase *CameraMovementAction:\n\t\t\t\tsync := action.(*CameraMovementAction)\n\t\t\t\tdata += fmt.Sprintf(\"skin %d %f %f %f %f %f %f\",\n\t\t\t\t\tclient.id,\n\t\t\t\t\tsync.position.X(),\n\t\t\t\t\tsync.position.Y(),\n\t\t\t\t\tsync.position.Z(),\n\t\t\t\t\tsync.rotation.X(),\n\t\t\t\t\tsync.rotation.Y(),\n\t\t\t\t\tsync.rotation.Z())\n\t\t\tdefault:\n\t\t\t\tpanic(\"unknown INetworkAction type\")\n\t\t\t}\n\t\t}\n\t} else {\n\t\tdata = \"<empty>\"\n\t}\n\n\t_, _ = fmt.Fprintf(conn, fmt.Sprintf(\"sync %d\\n\", client.id)+data)\n\tresponse = make([]byte, 256)\n\t_, err = conn.Read(response)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif !strings.Contains(string(response), \"good\") {\n\t\tpanic(\"The server is a fucking liar!\")\n\t}\n\t_ = conn.Close()\n\n\t// All modification send\n\t// Clean modifications\n\tclient.actions = []INetworkAction{}\n\t/*}()*/\n\tfmt.Printf(\"ping :%d\\r\", time.Now().Sub(start).Milliseconds())\n}", "func (f *lightFetcher) syncLoop() {\n\tdefer f.wg.Done()\n\tfor {\n\t\tselect {\n\t\tcase <-f.closeCh:\n\t\t\treturn\n\t\t// request loop keeps running until no further requests are necessary or possible\n\t\tcase <-f.requestTrigger:\n\t\t\tf.lock.Lock()\n\t\t\tvar (\n\t\t\t\trq *distReq\n\t\t\t\treqID uint64\n\t\t\t\tsyncing bool\n\t\t\t)\n\t\t\tif !f.syncing {\n\t\t\t\trq, reqID, syncing = f.nextRequest()\n\t\t\t}\n\t\t\tf.requestTriggered = rq != nil\n\t\t\tf.lock.Unlock()\n\n\t\t\tif rq != nil {\n\t\t\t\tif _, ok := <-f.handler.backend.reqDist.queue(rq); ok {\n\t\t\t\t\tif syncing {\n\t\t\t\t\t\tf.lock.Lock()\n\t\t\t\t\t\tf.syncing = true\n\t\t\t\t\t\tf.lock.Unlock()\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgo func() {\n\t\t\t\t\t\t\ttime.Sleep(softRequestTimeout)\n\t\t\t\t\t\t\tf.reqMu.Lock()\n\t\t\t\t\t\t\treq, ok := f.requested[reqID]\n\t\t\t\t\t\t\tif ok {\n\t\t\t\t\t\t\t\treq.timeout = true\n\t\t\t\t\t\t\t\tf.requested[reqID] = req\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tf.reqMu.Unlock()\n\t\t\t\t\t\t\t// keep starting new requests while possible\n\t\t\t\t\t\t\tf.requestTrigger <- struct{}{}\n\t\t\t\t\t\t}()\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tf.requestTrigger <- struct{}{}\n\t\t\t\t}\n\t\t\t}\n\t\tcase reqID := <-f.timeoutChn:\n\t\t\tf.reqMu.Lock()\n\t\t\treq, ok := f.requested[reqID]\n\t\t\tif ok {\n\t\t\t\tdelete(f.requested, reqID)\n\t\t\t}\n\t\t\tf.reqMu.Unlock()\n\t\t\tif ok {\n\t\t\t\tf.handler.backend.serverPool.adjustResponseTime(req.peer.poolEntry, time.Duration(mclock.Now()-req.sent), true)\n\t\t\t\treq.peer.Log().Debug(\"Fetching data timed out hard\")\n\t\t\t\tgo f.handler.removePeer(req.peer.id)\n\t\t\t}\n\t\tcase resp := <-f.deliverChn:\n\t\t\tf.reqMu.Lock()\n\t\t\treq, ok := f.requested[resp.reqID]\n\t\t\tif ok && req.peer != resp.peer {\n\t\t\t\tok = false\n\t\t\t}\n\t\t\tif ok {\n\t\t\t\tdelete(f.requested, resp.reqID)\n\t\t\t}\n\t\t\tf.reqMu.Unlock()\n\t\t\tif ok {\n\t\t\t\tf.handler.backend.serverPool.adjustResponseTime(req.peer.poolEntry, time.Duration(mclock.Now()-req.sent), req.timeout)\n\t\t\t}\n\t\t\tf.lock.Lock()\n\t\t\tif !ok || !(f.syncing || f.processResponse(req, resp)) {\n\t\t\t\tresp.peer.Log().Debug(\"Failed processing response\")\n\t\t\t\tgo f.handler.removePeer(resp.peer.id)\n\t\t\t}\n\t\t\tf.lock.Unlock()\n\t\tcase p := <-f.syncDone:\n\t\t\tf.lock.Lock()\n\t\t\tp.Log().Debug(\"Done synchronising with peer\")\n\t\t\tf.checkSyncedHeaders(p)\n\t\t\tf.syncing = false\n\t\t\tf.lock.Unlock()\n\t\t\tf.requestTrigger <- struct{}{} // f.requestTriggered is always true here\n\t\t}\n\t}\n}", "func (scholten *Scholten) loop() {\n\n\terr := scholten.serv.startListening()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif scholten.root {\n\t\tgo scholten.doWork()\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase basic := <-scholten.basicChan:\n\t\t\t// ALUNO\n\n\t\tcase control := <-scholten.controlChan:\n\t\t\t// ALUNO\n\n\t\tcase termination := <- scholten.terminationChan:\n\t\t\t// ALUNO\n\t\t}\n\t}\n}", "func (s *Server) Sync(stream pb.KVStore_SyncServer) error {\n\tfor {\n\t\t// receive a stream of sync requests from another node\n\t\tmsg, err := stream.Recv()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\ts.logger.Error(\"sync connection closed due to EOF\", zap.Error(err))\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tconst msg = \"sync connection closed due to unexpected error\"\n\t\t\ts.logger.Error(msg, zap.Error(err))\n\t\t\treturn fmt.Errorf(msg+\": %w\", err)\n\t\t}\n\n\t\ts.logger.Debug(\"sync_in\", zap.Stringer(\"op\", msg.Operation),\n\t\t\tzap.String(\"key\", msg.Key), zap.Int64(\"ts\", msg.GetTimestamp()))\n\n\t\t// TODO: create a SyncMessage with From & ToProto\n\t\t// insert sync operation into this node's store\n\t\tif err := s.store.SyncIn(msg); err != nil {\n\t\t\tconst msg = \"failed to store sync message\"\n\t\t\ts.logger.Error(msg, zap.Error(err))\n\t\t\treturn fmt.Errorf(msg+\": %w\", err)\n\t\t}\n\t}\n}", "func StartGameLoop() (chan *MoveMessage, chan *AddMessage, chan *AddMessage) {\n\t// about 16 milliseconds for 60 fps a second\n\tgameTick := time.NewTicker(time.Millisecond * 10)\n\n\t// Physics runs at 50 fps\n\tphysicsTick := time.NewTicker(time.Millisecond * 20)\n\ttimeStep := (time.Millisecond * 2).Seconds()\n\n\t// TODO: Figure out buffering properly\n\tmoveChannel := make(chan *MoveMessage, 10)\n\taddChannel := make(chan *AddMessage, 10)\n\tbroadcastAddChannel := make(chan *AddMessage, 10)\n\n\t// actual Game Loop. TODO: Should this be a function call?\n\tgo func() {\n\t\t// Run the game loop forever.\n\t\tfor range gameTick.C {\n\n\t\t\t// NOTE TO FUTURE SELF: if multiple channels are ready, select will\n\t\t\t// pick one randomly and move on!! There are a few solutions I can see\n\t\t\t// to help this. First, have a select for each channel or read the\n\t\t\t// channels outside of the game loop.\n\t\t\t// TODO: this could be a function probably\n\t\t\tfor i := 0; i < 10; i++ {\n\t\t\t\t// Arbitraily read up to ten add requests in a single frame\n\t\t\t\tselect {\n\t\t\t\tcase msg := <-addChannel:\n\t\t\t\t\tTrace.Printf(\"Adding with %+v\\n\", msg)\n\t\t\t\t\tplayer := NewPlayer(msg.X, msg.Y, msg.Id)\n\t\t\t\t\tAddPlayerObjectToWorld(player)\n\t\t\t\t\tAddObjectToConnectionData(&player, player.Id, msg.sourceId)\n\t\t\t\t\t// TODO: Have proper error checking and only add to broadcast channel if\n\t\t\t\t\t// successful\n\t\t\t\t\tbroadcastAddChannel <- msg\n\t\t\t\tdefault:\n\t\t\t\t\t// Move on to other things\n\t\t\t\t}\n\t\t\t}\n\t\t\t// TODO: Have this done with a channel I think...\n\t\t\tbroadCastGameObjects()\n\t\t}\n\t}()\n\n\t// Start phyics loop, give it the movement channel and it's ticker\n\tgo PhysicsLoop(physicsTick, moveChannel, timeStep)\n\n\tInfo.Println(\"Started Game Loop\")\n\n\treturn moveChannel, addChannel, broadcastAddChannel\n}", "func (c *Client) Loop(n, m int) {\n\tinterval := initialInterval\n\tfor {\n\t\trandSleep(n, m)\n\t\tresp, err := c.MakeRequest(\"3\", \"2\", true, false)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tuc := resp.Apps[0].UpdateCheck\n\t\tif uc.Status != \"ok\" {\n\t\t\tc.Log(\"update check status: %s\\n\", uc.Status)\n\t\t} else {\n\t\t\tc.SetVersion(resp)\n\t\t}\n\t}\n}", "func (m *Monitor) runMonitorLoop() error {\n\t// Get all nodes in cluster\n\tcfg, err := kubeutils.BuildConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient, err := clientset.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tklog.Info(\"started master\")\n\tvar deadNodes []*v1.Node\n\tfor {\n\t\t// Don't thrash here..\n\t\tklog.V(4).Info(\"little pause before work\")\n\t\ttime.Sleep(pausePollingSecs)\n\n\t\t// Get all the nodes - that have been reported as UnReachable...\n\t\t// reporting happens using configmaps in specified namespace\n\t\tdeadNodes, err = kubeutils.GetUnreachableNodes(client, m.namespace)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"error getting nodes reported as unreachable: %s\", err)\n\t\t\t// Try again\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(3).Infof(\"got an unreachable node list (%d nodes)\", len(deadNodes))\n\n\t\t// reap any nodes as required...\n\t\tif m.reap && len(deadNodes) > 0 {\n\t\t\tklog.V(4).Info(\"We are set to reap\")\n\t\t\tfor _, node := range deadNodes {\n\t\t\t\tif err := reaper.Reap(node, client, m.dryRun); err != nil {\n\t\t\t\t\tklog.Errorf(\"error reaping %s, %s\", node.Name, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func Work() {\n\n\t//to play with n people, the client should send packets to n ports in order to mock n different players.\n\tfor offset:=0;offset<constant.MaxNum;offset++{\n\t\tfmt.Println(\"\\ntrying to ping \",constant.ServerIp,\":\",constant.ServerUdpPort+offset)\n\t\tping(constant.ServerIp,constant.ServerUdpPort+offset)\n\t}\n\tfmt.Println(\"\\n\\n\\n=====================================\")\n\tfmt.Println(\"ok then you can start the game now!\")\n\tfmt.Println(\"=====================================\")\n\n\t//then sniff map info packets. You can still play games if this step failed.\n\tnewsniff()\n\n}", "func (c *Curator) updateTsmonLoop() {\n\tscanTicker := time.NewTicker(10 * time.Second)\n\n\tfor {\n\t\tc.blockIfNotLeader()\n\t\tids := c.stateHandler.GetKnownTSIDs()\n\t\tc.tsMon.updateExpected(ids)\n\t\tlog.Infof(\"@@@ tsmon: %s\", c.tsMon)\n\t\t<-scanTicker.C\n\t}\n}", "func (gameCommunication *GameCommunication) Sync() {\n\tgameCommunication.Client.SendSyncRequest()\n}", "func (r *BinlogReader) StartSyncByGTID(gset mysql.GTIDSet) (Streamer, error) {\n\tr.tctx.L().Info(\"begin to sync binlog\", zap.Stringer(\"GTID Set\", gset))\n\tr.usingGTID = true\n\n\tif r.running {\n\t\treturn nil, terror.ErrReaderAlreadyRunning.Generate()\n\t}\n\n\tif err := r.updateUUIDs(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tpos, err := r.getPosByGTID(gset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr.tctx.L().Info(\"get pos by gtid\", zap.Stringer(\"GTID Set\", gset), zap.Stringer(\"Position\", pos))\n\n\tr.prevGset = gset\n\tr.currGset = nil\n\n\tr.latestServerID = 0\n\tr.running = true\n\ts := newLocalStreamer()\n\n\tr.wg.Add(1)\n\tgo func() {\n\t\tdefer r.wg.Done()\n\t\tr.tctx.L().Info(\"start reading\", zap.Stringer(\"position\", pos))\n\t\terr = r.parseRelay(r.tctx.Context(), s, *pos)\n\t\tif errors.Cause(err) == r.tctx.Context().Err() {\n\t\t\tr.tctx.L().Warn(\"parse relay finished\", log.ShortError(err))\n\t\t} else if err != nil {\n\t\t\ts.closeWithError(err)\n\t\t\tr.tctx.L().Error(\"parse relay stopped\", zap.Error(err))\n\t\t}\n\t}()\n\n\treturn s, nil\n}", "func (cluster *mongoCluster) syncServers() {\n\tcluster.Lock()\n\tif cluster.syncing || cluster.references == 0 {\n\t\tcluster.Unlock()\n\t\treturn\n\t}\n\tcluster.syncing = true\n\tcluster.Unlock()\n\nrestart:\n\n\tlog(\"[sync] Starting full topology synchronization...\")\n\n\tcluster.Lock()\n\t// Check again, so that ref=0 stops restarting.\n\tif cluster.references == 0 {\n\t\tcluster.syncing = false\n\t\tcluster.Unlock()\n\t\treturn\n\t}\n\tcluster.references++ // Keep alive while syncing.\n\tdirect := cluster.direct\n\tcluster.Unlock()\n\n\tknown := cluster.getKnownAddrs()\n\n\t// Note that the logic below is lock free. The locks below are\n\t// just to avoid race conditions internally and to wait for the\n\t// procedure to finish.\n\n\tvar started, finished int\n\tvar done sync.Mutex\n\tvar m sync.Mutex\n\n\tdone.Lock()\n\tseen := make(map[string]bool)\n\n\tvar spawnSync func(addr string)\n\tspawnSync = func(addr string) {\n\t\tm.Lock()\n\t\tstarted++\n\t\tm.Unlock()\n\n\t\tgo func() {\n\t\t\tdefer func() {\n\t\t\t\tm.Lock()\n\t\t\t\tfinished++\n\t\t\t\tif started == finished && finished >= len(known) {\n\t\t\t\t\tdone.Unlock()\n\t\t\t\t}\n\t\t\t\tm.Unlock()\n\t\t\t}()\n\n\t\t\tserver, err := newServer(addr)\n\t\t\tif err != nil {\n\t\t\t\tlog(\"[sync] Failed to start sync of \", addr, \": \", err.String())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif _, found := seen[server.ResolvedAddr]; found {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tseen[server.ResolvedAddr] = true\n\n\t\t\thosts, err := cluster.syncServer(server)\n\t\t\tif !direct && err == nil {\n\t\t\t\tfor _, addr := range hosts {\n\t\t\t\t\tspawnSync(addr)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor _, addr := range known {\n\t\tspawnSync(addr)\n\t}\n\n\tdone.Lock()\n\n\tcluster.Lock()\n\tlog(\"[sync] Synchronization completed: \", cluster.masters.Len(),\n\t\t\" master(s) and, \", cluster.slaves.Len(), \" slave(s) alive.\")\n\n\t// Update dynamic seeds, but only if we have any good servers. Otherwise,\n\t// leave them alone for better chances of a successful sync in the future.\n\tif !cluster.servers.Empty() {\n\t\tdynaSeeds := make([]string, cluster.servers.Len())\n\t\tfor i, server := range cluster.servers.Slice() {\n\t\t\tdynaSeeds[i] = server.Addr\n\t\t}\n\t\tcluster.dynaSeeds = dynaSeeds\n\t\tdebugf(\"[sync] New dynamic seeds: %#v\\n\", dynaSeeds)\n\t}\n\n\t// Poke all waiters so they have a chance to timeout.\n\tcluster.serverSynced.Broadcast()\n\n\tif !direct && cluster.masters.Empty() || cluster.servers.Empty() {\n\t\tlog(\"[sync] No masters found. Synchronize again.\")\n\n\t\tcluster.Unlock()\n\t\tcluster.Release() // May stop resyncing with refs=0.\n\t\ttime.Sleep(5e8)\n\t\tgoto restart\n\t}\n\n\t// Reference is decreased after unlocking, so that\n\t// if refs=0, Release handles it.\n\tcluster.Unlock()\n\tcluster.Release()\n\n\t// Hold off before allowing another sync. No point in\n\t// burning CPU looking for down servers.\n\ttime.Sleep(5e8)\n\tcluster.Lock()\n\tcluster.syncing = false\n\t// Poke all waiters so they have a chance to timeout or\n\t// restart syncing if they wish to.\n\tcluster.serverSynced.Broadcast()\n\tcluster.Unlock()\n}", "func (s *Refresh) StartBackgroundRefresh() {\n\tgo s.FindServerStateAdded()\n}", "func (g *Guard) start(ctx context.Context) {\n\tticker := time.NewTicker(g.duration)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tlogger.Debugf(\"starting firewall guard round\")\n\n\t\t\tconnectedPeers := g.connectionManager.ConnectedPeers()\n\n\t\t\tfor _, connectedPeer := range connectedPeers {\n\t\t\t\tif g.currentlyChecking(connectedPeer) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Ensure we mark the peer as being checked before\n\t\t\t\t// executing the async stake check.\n\t\t\t\tg.markAsChecking(connectedPeer)\n\t\t\t\tgo g.checkFirewallRules(connectedPeer)\n\t\t\t}\n\t\t}\n\t}\n}", "func (d *DriveDB) sync() {\n\tvar c *gdrive.ChangeList\n\tfor {\n\t\tc = <-d.changes\n\t\terr := d.processChange(c)\n\t\tif err != nil {\n\t\t\t// TODO: trigger reinit(), unless rate > N, then log.Fatal\n\t\t\tlog.Printf(\"error evaluating change from drive: %v\", err)\n\t\t}\n\t}\n}", "func (wh *sessionholder) loop() {\n\tlog.Println(\"sessionholder.loop start\")\n\t// save to map, for keep-alive\n\tholderMap[wh.uuid] = wh\n\tsess := wh.sess\n\n\tgo wh.serveCmdStream()\n\n\tfor {\n\t\t// TODO: accept streams\n\t\tstream, err := sess.AcceptStream(context.Background())\n\t\tif err != nil {\n\t\t\tlog.Println(\"sess.AcceptStream failed:\", err)\n\t\t\tbreak\n\t\t}\n\n\t\t// TODO: service link stream\n\t\tgo onPairRequest(stream)\n\t}\n\n\t// remove from map\n\tdelete(holderMap, wh.uuid)\n}", "func (hm *HM) Startup(gvec string) {\n\n\tvar i uint8\n\tfor i = 0; i < uint8(len(hm.locks)); i++ {\n\t\thm.locks[i] = &Lock{\n\t\t\tmutex: new(sync.Mutex),\n\t\t\tlocal: hm.pid == hm.getLockManager(i),\n\t\t\theld: false,\n\t\t\tlastReq: hm.getLockManager(i),\n\t\t\tnextID: 0,\n\t\t\tnextVC: nil,\n\t\t}\n\t}\n\n\tif gvec != \"\" {\n\t\tprocess := gvec + strconv.Itoa(int(hm.pid))\n\t\thm.vecLog = govec.InitGoVector(process, process)\n\t}\n\t// init barriers\n\thm.barrierCnt = 0\n\thm.halt = make(chan bool)\n\n\tlocConf, err := configs.ReadConfig()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\tfmt.Println(\"NRPROC: \", hm.nrProc, locConf, locConf.DroneList)\n\n\tdronesConnected := locConf.DroneList\n\n\tif locConf.IsCBM {\n\t\t//we're the first drone, start up the others\n\t\tfmt.Println(\"CBM, Starting Node Setup\")\n\t\t_, dronesConnected, err := ipc.StartNodes(locConf.Drones[:hm.nrProc-1])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t\t//unable to start nodes sucessfully\n\t\t}\n\t\t//initialise IPC module\n\t\thm.ipc, hm.txChan, hm.rxChan = ipc.Init(dronesConnected, \"\")\n\t} else {\n\t\t//not the first drone\n\t\t//initialise IPC module\n\t\thm.ipc, hm.txChan, hm.rxChan = ipc.Init(dronesConnected, locConf.CBM)\n\t}\n\t// Start the background Receive handler\n\tgo hm.rxMsgHandler()\n}", "func (c *connection) sendLoop() {\n\tc.group.Add(1)\n\tvar id int\n\tfor msg := range c.out {\n\t\ttime.Sleep(0)\n\t\tid = int(msg[0])\n\t\tif id == c.myId {\n\t\t\tc.in <- msg\n\t\t} else {\n\t\t\tif id >= len(c.peers) {\n\t\t\t\tgo func() {\n\t\t\t\t\ttime.Sleep(time.Millisecond * 500)\n\t\t\t\t\tc.out <- msg\n\t\t\t\t}()\n\t\t\t} else {\n\t\t\t\tmsg[0] = 1\n\n\t\t\t\twrite(c.peers[id].conn, msg)\n\t\t\t}\n\t\t}\n\t}\n\tc.running = false\n\tc.group.Done()\n\tc.group.Wait()\n\tclose(c.in)\n}", "func (d *LoopVars) askForSync() {\n\td.ensureInit()\n\tselect {\n\tcase d.syncSoon <- struct{}{}:\n\tdefault:\n\t}\n}", "func Start() {\n\t//set each server status as online to start\n\tfor i := range config.Config.Servers {\n\t\tconfig.Config.Servers[i].Online = true\n\t}\n\n\terr := bot.Session.UpdateStatus(0, config.Config.GameStatus)\n\n\tsendMessageToRooms(blue, \"Server Status\", \"Bot started! Type !ServerStatus to see the status of your servers :smiley:\", false)\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\t//start a new go routine\n\tgo scanServers()\n}", "func Start() {\n\tres, err := storage.P2PToConnect()\n\tif err == nil {\n\t\tfor _, p := range res {\n\t\t\tn := node{addr: p, lastSeen: time.Now().Unix()}\n\t\t\tpeerAll.Store(fmt.Sprintf(\"%s:%d\", n.addr.IP, n.addr.Port), n)\n\t\t}\n\t}\n\n\tfor {\n\t\tpeerAll.Range(func(key, value interface{}) bool {\n\t\t\ttime.Sleep(time.Second)\n\t\t\tn, ok := value.(node)\n\t\t\tif ok {\n\t\t\t\tif n.lastSeen < time.Now().Unix()-86400 {\n\t\t\t\t\tpeerAll.Delete(fmt.Sprintf(\"%s:%d\", n.addr.IP, n.addr.Port))\n\t\t\t\t} else {\n\t\t\t\t\tgo work(n.addr)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t}\n}", "func startBackgroundPermsSync(ctx context.Context, syncer *authz.PermsSyncer, db dbutil.DB) {\n\tglobals.WatchPermissionsUserMapping()\n\tgo func() {\n\t\tt := time.NewTicker(5 * time.Second)\n\t\tfor range t.C {\n\t\t\tallowAccessByDefault, authzProviders, _, _ :=\n\t\t\t\tfrontendAuthz.ProvidersFromConfig(\n\t\t\t\t\tctx,\n\t\t\t\t\tconf.Get(),\n\t\t\t\t\tossDB.ExternalServices(db),\n\t\t\t\t)\n\t\t\tossAuthz.SetProviders(allowAccessByDefault, authzProviders)\n\t\t}\n\t}()\n\n\tgo syncer.Run(ctx)\n}", "func Sync(syncName string) {\n\ts := SyncServiceStatus(syncName)\n\tif s == \"running\" {\n\t\tfmt.Println(syncRunningErr)\n\t\treturn\n\t}\n\n\tfmt.Println()\n\tconsole.Println(\"⚡ Syncing files between your system and the Tokaido environment\", \"\")\n\tutils.StdoutStreamCmdDebug(\"unison\", syncName, \"-watch=false\")\n}", "func (s *Server) loopServiceDiscovery() {\n\ts.Info(\"Starting DNS service discovery for nethealth pod.\")\n\tticker := s.clock.NewTicker(dnsDiscoveryInterval)\n\tdefer ticker.Stop()\n\tquery := s.config.ServiceDiscoveryQuery\n\n\tpreviousNames := []string{}\n\n\tfor {\n\t\t<-ticker.Chan()\n\n\t\ts.Debugf(\"Querying %v for service discovery\", query)\n\t\tnames, err := net.LookupHost(query)\n\t\tif err != nil {\n\t\t\ts.WithError(err).WithField(\"query\", query).Error(\"Error querying service discovery.\")\n\t\t\tcontinue\n\t\t}\n\n\t\tsort.Strings(names)\n\t\tif reflect.DeepEqual(names, previousNames) {\n\t\t\tcontinue\n\t\t}\n\t\tpreviousNames = names\n\t\ts.Info(\"Triggering peer resync due to service discovery change\")\n\n\t\tselect {\n\t\tcase s.triggerResync <- true:\n\t\tdefault:\n\t\t\t// Don't block\n\t\t}\n\t}\n}", "func (s *Server) OnStart() error {\n\tgo s.loop(state{\n\t\tqueries: make(map[Query]map[string]chan<- interface{}),\n\t\tclients: make(map[string]map[Query]struct{}),\n\t})\n\treturn nil\n}", "func (bili *BiliClient) heartbeatLoop() {\n\tfor bili.checkConnect() {\n\t\terr := bili.sendSocketData(0, 16, bili.protocolVersion, 2, 1, \"\")\n\t\tif err != nil {\n\t\t\tbili.setConnect(false)\n\t\t\tlog.Printf(\"heartbeatError:%s\\r\\n\", err.Error())\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(time.Second * 5)\n\t}\n}", "func (s *GameService) RunGame() {\n\tisGameLooping := true\n\tfor isGameLooping {\n\t\tif len(s.Players) > 0 {\n\t\t\ts.MoveShot()\n\t\t\ts.ClearDeadPlayers()\n\t\t\ts.CreateResponse()\n\t\t}\n\t\ttime.Sleep(5 * time.Millisecond)\n\t}\n}", "func (am *AppManager) Start() {\n\tlogger.Printf(\"Starting Goroutine to refresh applications data every %d minute(s)\\n\", am.appUpdateInterval)\n\t//get the data as soon as possible\n\tgo am.refreshAppData()\n\tticker := time.NewTicker(time.Duration(int64(am.appUpdateInterval)) * time.Minute)\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tgo am.refreshAppData()\n\n\t\t\tcase tempAppInfo := <-am.updateChannel:\n\t\t\t\tlogger.Printf(\"App Update....received %d app details\", len(tempAppInfo))\n\t\t\t\tam.appData = tempAppInfo\n\n\t\t\tcase rr := <-am.readChannel:\n\t\t\t\tad := am.getAppData(rr.appGUID)\n\t\t\t\trr.responseChan <- ad\n\n\t\t\tcase <-am.closeChannel:\n\t\t\t\tlogger.Print(\"quit \\r\\n\")\n\t\t\t\tticker.Stop()\n\t\t\t}\n\t\t}\n\t}()\n}", "func (c *Coordinator) run(ctx context.Context) error {\n\tminRemoteClientsPerGame := 1\n\tmaxRemoteClientsPerGame := 10\n\tfor {\n\t\tclients, err := c.awaitRemoteClients(ctx, minRemoteClientsPerGame, maxRemoteClientsPerGame)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error awaiting remote clients\")\n\t\t}\n\n\t\t// Add a couple of AI clients.\n\t\tnumAIClients := 4 - len(clients)\n\t\tif numAIClients <= 0 {\n\t\t\tnumAIClients = 1\n\t\t}\n\t\tfor i := 0; i < numAIClients; i++ {\n\t\t\tvar aiClient *ai.Client\n\t\t\tvar err error\n\t\t\tif i%3 == 2 {\n\t\t\t\taiClient, err = ai.NewClient(c.logEntry.Logger, ai.RandomStrategy(rand.Int63n(30)+2))\n\t\t\t} else {\n\t\t\t\taiClient, err = ai.NewClient(c.logEntry.Logger, ai.OpportunisticStrategy())\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"error creating ai client\")\n\t\t\t}\n\t\t\tclients = append(clients, aiClient)\n\t\t}\n\n\t\tc.logEntry.Debug(\"Starting a new game\")\n\t\terr = c.startGame(ctx, clients)\n\t\tif err != nil {\n\t\t\t// As we still own the clients here, make sure we stop them\n\t\t\t// before quiting ourselves.\n\t\t\tdisconnectAll(clients)\n\t\t\treturn errors.Wrap(err, \"Error starting game\")\n\t\t}\n\t}\n}", "func rpcClientConnectLoop(legacyRPCServer *legacyrpc.Server, loader *wallet.Loader) {\n\tvar certs []byte\n\t// if !cfg.UseSPV {\n\tcerts = readCAFile()\n\t// }\n\tfor {\n\t\tvar (\n\t\t\tchainClient chain.Interface\n\t\t\terr error\n\t\t)\n\t\t// if cfg.UseSPV {\n\t\t// \tvar (\n\t\t// \t\tchainService *neutrino.ChainService\n\t\t// \t\tspvdb walletdb.DB\n\t\t// \t)\n\t\t// \tnetDir := networkDir(cfg.AppDataDir.Value, ActiveNet.Params)\n\t\t// \tspvdb, err = walletdb.Create(\"bdb\",\n\t\t// \t\tfilepath.Join(netDir, \"neutrino.db\"))\n\t\t// \tdefer spvdb.Close()\n\t\t// \tif err != nil {\n\t\t// \t\tlog<-cl.Errorf{\"unable to create Neutrino DB: %s\", err)\n\t\t// \t\tcontinue\n\t\t// \t}\n\t\t// \tchainService, err = neutrino.NewChainService(\n\t\t// \t\tneutrino.Config{\n\t\t// \t\t\tDataDir: netDir,\n\t\t// \t\t\tDatabase: spvdb,\n\t\t// \t\t\tChainParams: *ActiveNet.Params,\n\t\t// \t\t\tConnectPeers: cfg.ConnectPeers,\n\t\t// \t\t\tAddPeers: cfg.AddPeers,\n\t\t// \t\t})\n\t\t// \tif err != nil {\n\t\t// \t\tlog<-cl.Errorf{\"couldn't create Neutrino ChainService: %s\", err)\n\t\t// \t\tcontinue\n\t\t// \t}\n\t\t// \tchainClient = chain.NewNeutrinoClient(ActiveNet.Params, chainService)\n\t\t// \terr = chainClient.Start()\n\t\t// \tif err != nil {\n\t\t// \t\tlog<-cl.Errorf{\"couldn't start Neutrino client: %s\", err)\n\t\t// \t}\n\t\t// } else {\n\t\tchainClient, err = startChainRPC(certs)\n\t\tif err != nil {\n\t\t\tlog <- cl.Error{\n\t\t\t\t\"unable to open connection to consensus RPC server:\", err}\n\t\t\tcontinue\n\t\t}\n\t\t// }\n\t\t// Rather than inlining this logic directly into the loader\n\t\t// callback, a function variable is used to avoid running any of\n\t\t// this after the client disconnects by setting it to nil. This\n\t\t// prevents the callback from associating a wallet loaded at a\n\t\t// later time with a client that has already disconnected. A\n\t\t// mutex is used to make this concurrent safe.\n\t\tassociateRPCClient := func(w *wallet.Wallet) {\n\t\t\tw.SynchronizeRPC(chainClient)\n\t\t\tif legacyRPCServer != nil {\n\t\t\t\tlegacyRPCServer.SetChainServer(chainClient)\n\t\t\t}\n\t\t}\n\t\tmu := new(sync.Mutex)\n\t\tloader.RunAfterLoad(func(w *wallet.Wallet) {\n\t\t\tmu.Lock()\n\t\t\tassociate := associateRPCClient\n\t\t\tmu.Unlock()\n\t\t\tif associate != nil {\n\t\t\t\tassociate(w)\n\t\t\t}\n\t\t})\n\t\tchainClient.WaitForShutdown()\n\t\tmu.Lock()\n\t\tassociateRPCClient = nil\n\t\tmu.Unlock()\n\t\tloadedWallet, ok := loader.LoadedWallet()\n\t\tif ok {\n\t\t\t// Do not attempt a reconnect when the wallet was explicitly stopped.\n\t\t\tif loadedWallet.ShuttingDown() {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tloadedWallet.SetChainSynced(false)\n\t\t\t// TODO: Rework the wallet so changing the RPC client does not require stopping and restarting everything.\n\t\t\tloadedWallet.Stop()\n\t\t\tloadedWallet.WaitForShutdown()\n\t\t\tloadedWallet.Start()\n\t\t}\n\t}\n}", "func SyncToSMdb() {\n\n\tdbName := c.DBConfig.DBName.StockMarketRawD1\n\tnames, _ := h.GetCollectionNames(dbName)\n\tcCount := len(names)\n\n\tfor i, name := range names {\n\t\tMergeDMtoMM(name)\n\t\tfmt.Printf(\"Synchronizing daily-bar to monthly-bar. Stock code:%s (%d/%d) \\r\", name, i+1, cCount)\n\t}\n\tfmt.Println()\n}", "func (manager *ClientManager) Start() {\n\tfor {\n\t\tselect {\n\t\tcase conn := <-manager.register:\n\n\t\t\tlog.Printf(\"Registering connection\")\n\t\t\tmanager.clients[conn] = true\n\n\t\tcase conn := <-manager.unregister:\n\t\t\tlog.Printf(\"Unregistering connection.\")\n\t\t\tif _, ok := manager.clients[conn]; ok {\n\t\t\t\tclose(conn.send)\n\t\t\t\tdelete(manager.clients, conn)\n\t\t\t}\n\t\tcase event := <-manager.Broadcast:\n\t\t\tlog.Printf(\"Sending event %s\", event)\n\t\t\t//Marshal once\n\t\t\ttoSend, err := json.Marshal(&event)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor conn := range manager.clients {\n\t\t\t\tselect {\n\t\t\t\tcase conn.send <- toSend: //this might need to be more robust - to handle a connection that is just taking a minute\n\t\t\t\tdefault:\n\t\t\t\t\tclose(conn.send)\n\t\t\t\t\tdelete(manager.clients, conn)\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n}", "func (c *ConfigManager) Start() {\n\tc.saveLoop()\n}", "func main() {\n\t//defer profile.Start(profile.CPUProfile).Stop()\n\n\t//flag.Parse()\n\n\tfmt.Println(\"Launching server...\")\n\n\tClientList = make(map[uint32]*Client)\n\tC_List_lock = new(sync.Mutex)\n\n\tport := strconv.Itoa(Protocol.SERVER_PORT)\n\n\tln, err := net.Listen(\"tcp\", \":\"+port)\n\tif nil != err {\n\t\tlog.Fatalf(\"fail to bind Port err: %v\", err)\n\t}\n\n\tvar idcounter uint32 = 0\n\tfor RunningFlag {\n\t\tconn, err := ln.Accept()\n\n\t\tif nil != err {\n\t\t\tlog.Fatalln(\"Connection error\")\n\t\t\tcontinue\n\t\t}\n\n\t\tc := Client{\n\t\t\tConn: conn,\n\t\t\tId: idcounter,\n\t\t}\n\t\tc.X = int32(rand.Intn(50))\n\t\tc.Y = int32(rand.Intn(50))\n\t\tc.Init()\n\n\t\tpacket := Protocol.Packet_SC_Login_OK{\n\t\t\tPacket_type: Protocol.SC_LOGIN_OK,\n\t\t\tId: c.Id,\n\t\t}\n\n\t\tUtility.SendPacket(c.Conn, packet)\n\t\tidcounter++\n\n\t\t// to all\n\t\tputpacket := Protocol.Packet_SC_Put_Player{\n\t\t\tPacket_type: Protocol.SC_PUT_PLAYER,\n\t\t\tX: uint16(c.X),\n\t\t\tY: uint16(c.Y),\n\t\t\tId: c.Id,\n\t\t}\n\n\t\tC_List_lock.Lock()\n\t\tClientList[c.Id] = &c\n\t\tC_List_lock.Unlock()\n\n\t\tvar idx uint32 = 0\n\t\tfor idx < idcounter {\n\t\t\tcl := ClientList[idx]\n\t\t\tif cl != nil {\n\t\t\t\tUtility.SendPacket(cl.Conn, putpacket)\n\t\t\t}\n\t\t\tidx++\n\t\t}\n\t\tidx = 0\n\t\t// to me\n\t\tfor idx < idcounter {\n\t\t\tcl := ClientList[idx]\n\n\t\t\tif cl != nil && cl.Id != c.Id {\n\t\t\t\tpacket := Protocol.Packet_SC_Put_Player{\n\t\t\t\t\tPacket_type: Protocol.SC_PUT_PLAYER,\n\t\t\t\t\tX: uint16(cl.X),\n\t\t\t\t\tY: uint16(cl.Y),\n\t\t\t\t\tId: cl.Id,\n\t\t\t\t}\n\n\t\t\t\tUtility.SendPacket(c.Conn, packet)\n\t\t\t}\n\t\t\tidx++\n\t\t}\n\n\t\tgo ConnectionProcess(&c)\n\n\t}\n\n\tprintln(\"Server End\")\n}", "func (m *cidsMap) Sync(vmis []*virtv1.VirtualMachineInstance) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tfor _, vmi := range vmis {\n\t\tif vmi.Status.VSOCKCID == nil {\n\t\t\tcontinue\n\t\t}\n\t\tkey := controller.VirtualMachineInstanceKey(vmi)\n\t\tm.cids[key] = *vmi.Status.VSOCKCID\n\t\tm.reverse[*vmi.Status.VSOCKCID] = key\n\t}\n}", "func startDaemon() error {\n\t// Establish multithreading.\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\t// Create all of the modules.\n\tgateway, err := gateway.New(config.Siad.RPCaddr, filepath.Join(config.Siad.SiaDir, modules.GatewayDir))\n\tif err != nil {\n\t\treturn err\n\t}\n\tcs, err := consensus.New(gateway, filepath.Join(config.Siad.SiaDir, modules.ConsensusDir))\n\tif err != nil {\n\t\treturn err\n\t}\n\texplorer, err := explorer.New(cs, filepath.Join(config.Siad.SiaDir, modules.ExplorerDir))\n\tif err != nil {\n\t\treturn err\n\t}\n\tsrv, err := api.NewServer(config.Siad.APIaddr, cs, gateway, nil, nil, nil, nil, nil, explorer)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Bootstrap to the network.\n\tif !config.Siad.NoBootstrap {\n\t\tfor i := range modules.BootstrapPeers {\n\t\t\tgo gateway.Connect(modules.BootstrapPeers[i])\n\t\t}\n\t}\n\n\t// Send a struct down the started channel, so the testing package knows\n\t// that daemon startup has completed. A gofunc is used with the hope that\n\t// srv.Serve() will start running before the value is sent down the\n\t// channel.\n\tgo func() {\n\t\tstarted <- struct{}{}\n\t}()\n\n\t// Start serving api requests.\n\terr = srv.Serve()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Controller) Sync() {\n\t// Identify projects without worker threads\n\tid := func(instance, project string) string { return fmt.Sprintf(\"%s/%s\", instance, project) }\n\tneedsWorker := map[string][]string{}\n\tneedsWorkerCount := map[string]int{}\n\tfor instance, projects := range c.config().Gerrit.OrgReposConfig.AllRepos() {\n\t\tfor project := range projects {\n\t\t\tif _, ok := c.projectsWithWorker[id(instance, project)]; ok {\n\t\t\t\t// The worker thread is already up for this project, nothing needs\n\t\t\t\t// to be done.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tneedsWorker[instance] = append(needsWorker[instance], project)\n\t\t\tneedsWorkerCount[instance]++\n\t\t}\n\t}\n\t// First time seeing these projects, spin up worker threads for them.\n\tstaggerPosition := 0\n\tfor instance, projects := range needsWorker {\n\t\tstaggerIncement := c.config().Gerrit.TickInterval.Duration / time.Duration(needsWorkerCount[instance])\n\t\tfor _, project := range projects {\n\t\t\tc.projectsWithWorker[id(instance, project)] = true\n\t\t\tlogrus.WithFields(logrus.Fields{\"instance\": instance, \"repo\": project}).Info(\"Starting worker for project.\")\n\t\t\tgo func(instance, project string, staggerPosition int) {\n\t\t\t\t// Stagger new worker threads across the loop period to reduce load on the Gerrit API and Git server.\n\t\t\t\tnapTime := staggerIncement * time.Duration(staggerPosition)\n\t\t\t\ttime.Sleep(napTime)\n\n\t\t\t\t// Now start the repo worker thread.\n\t\t\t\tpreviousRun := time.Now()\n\t\t\t\tfor {\n\t\t\t\t\ttimeDiff := time.Until(previousRun.Add(c.config().Gerrit.TickInterval.Duration))\n\t\t\t\t\tif timeDiff > 0 {\n\t\t\t\t\t\ttime.Sleep(timeDiff)\n\t\t\t\t\t}\n\t\t\t\t\tpreviousRun = time.Now()\n\t\t\t\t\tc.processSingleProject(instance, project)\n\t\t\t\t}\n\t\t\t}(instance, project, staggerPosition)\n\t\t\tstaggerPosition++\n\t\t}\n\t}\n}", "func (m *Master) Sync(a *SyncArgs, r *SyncRes) error {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\ts := m.slaves[a.ID]\n\tif s == nil {\n\t\treturn errors.New(\"unknown slave\")\n\t}\n\tm.statExecs += a.Execs\n\tm.statRestarts += a.Restarts\n\tif m.coverFullness < a.CoverFullness {\n\t\tm.coverFullness = a.CoverFullness\n\t}\n\ts.lastSync = time.Now()\n\tr.Inputs = s.pending\n\ts.pending = nil\n\treturn nil\n}", "func (ad *AWSData) loop() {\n\tad.getAWSInfo()\n\n\tfor ad.running {\n\t\tstart := time.Now()\n\t\tdelayTimer := time.NewTimer(ad.delay)\n\t\tlog.Trace(\"Loop Start\")\n\t\tselect {\n\t\tcase ac := <-ad.hostChange:\n\t\t\tlog.Trace(\"Loop:Changing Host\")\n\t\t\terr := ad.doSetAddress(ac)\n\t\t\tif err != nil {\n\t\t\t\tlog.Warn(\"got error setting DNS:{}, {}\", ac, err)\n\t\t\t}\n\t\tcase <-ad.forceUpdate:\n\t\t\tlog.Trace(\"Loop:AWS force Update\")\n\t\t\tad.getAWSInfo()\n\t\tcase <-delayTimer.C:\n\t\t\tlog.Trace(\"Loop:Hit AWS update timeout\")\n\t\t\terr := ad.getAWSInfo()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(\"Problems talking to AWS:{}\", err)\n\t\t\t}\n\t\t}\n\t\tdelayTimer.Stop()\n\t\tloopTime := time.Since(start).Seconds()\n\t\tdnsLoopLatency.Observe(loopTime)\n\t\tlog.Trace(\"Loop End: {}s\", fmt.Sprintf(\"%.4f\", loopTime))\n\t}\n\tif ad.running {\n\t\tlog.Warn(\"Exited main loop w/o shuttdown!\")\n\t}\n}", "func ServerLoop(app *gopi.AppInstance, done <-chan struct{}) error {\n\n\tserver, ok := app.ModuleInstance(\"rpc/server\").(gopi.RPCServer)\n\tif server == nil || ok == false {\n\t\treturn errors.New(\"rpc/server missing\")\n\t}\n\n\t// Create the sensors module\n\tif service := new(SensorService); service == nil {\n\t\treturn errors.New(\"SensorService missing\")\n\t} else if err := server.Start(service); err != nil {\n\t\treturn err\n\t}\n\n\t// wait for done\n\t<-done\n\n\t// Bomb out\n\treturn nil\n}", "func fetchScheduledGames() []gm.Game {\n\turi := viper.GetString(\"master_URL\") + \"/api/games\"\n\n\tresp, _ := http.Get(uri)\n\n\tdefer closeResponse(resp)\n\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tvar gms []gm.Game\n\n\tjsonErr := json.Unmarshal(body, &gms)\n\tif jsonErr != nil {\n\t\tlogger.Error().Msg(\"could not get schedule game from MASTER master base station\")\n\t}\n\n\treturn gms\n}", "func (manager *syncerManager) Sync(namespace, name string) {\n\tmanager.mu.Lock()\n\tdefer manager.mu.Unlock()\n\tkey := getServiceKey(namespace, name)\n\tif portInfoMap, ok := manager.svcPortMap[key]; ok {\n\t\tfor svcPort, portInfo := range portInfoMap {\n\t\t\tif syncer, ok := manager.syncerMap[getSyncerKey(namespace, name, svcPort, portInfo)]; ok {\n\t\t\t\tif !syncer.IsStopped() {\n\t\t\t\t\tsyncer.Sync()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *Server) startGrpcLoop(grpcPort int) {\n\tdefer s.wg.Done()\n\tParams := &paramtable.Get().QueryNodeGrpcServerCfg\n\tvar kaep = keepalive.EnforcementPolicy{\n\t\tMinTime: 5 * time.Second, // If a client pings more than once every 5 seconds, terminate the connection\n\t\tPermitWithoutStream: true, // Allow pings even when there are no active streams\n\t}\n\n\tvar kasp = keepalive.ServerParameters{\n\t\tTime: 60 * time.Second, // Ping the client if it is idle for 60 seconds to ensure the connection is still active\n\t\tTimeout: 10 * time.Second, // Wait 10 second for the ping ack before assuming the connection is dead\n\t}\n\tvar lis net.Listener\n\tvar err error\n\terr = retry.Do(s.ctx, func() error {\n\t\taddr := \":\" + strconv.Itoa(grpcPort)\n\t\tlis, err = net.Listen(\"tcp\", addr)\n\t\tif err == nil {\n\t\t\ts.querynode.SetAddress(fmt.Sprintf(\"%s:%d\", Params.IP, lis.Addr().(*net.TCPAddr).Port))\n\t\t} else {\n\t\t\t// set port=0 to get next available port\n\t\t\tgrpcPort = 0\n\t\t}\n\t\treturn err\n\t}, retry.Attempts(10))\n\tif err != nil {\n\t\tlog.Error(\"QueryNode GrpcServer:failed to listen\", zap.Error(err))\n\t\ts.grpcErrChan <- err\n\t\treturn\n\t}\n\n\topts := tracer.GetInterceptorOpts()\n\ts.grpcServer = grpc.NewServer(\n\t\tgrpc.KeepaliveEnforcementPolicy(kaep),\n\t\tgrpc.KeepaliveParams(kasp),\n\t\tgrpc.MaxRecvMsgSize(Params.ServerMaxRecvSize.GetAsInt()),\n\t\tgrpc.MaxSendMsgSize(Params.ServerMaxSendSize.GetAsInt()),\n\t\tgrpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(\n\t\t\totelgrpc.UnaryServerInterceptor(opts...),\n\t\t\tlogutil.UnaryTraceLoggerInterceptor,\n\t\t\tinterceptor.ClusterValidationUnaryServerInterceptor(),\n\t\t\tinterceptor.ServerIDValidationUnaryServerInterceptor(func() int64 {\n\t\t\t\tif s.serverID.Load() == 0 {\n\t\t\t\t\ts.serverID.Store(paramtable.GetNodeID())\n\t\t\t\t}\n\t\t\t\treturn s.serverID.Load()\n\t\t\t}),\n\t\t)),\n\t\tgrpc.StreamInterceptor(grpc_middleware.ChainStreamServer(\n\t\t\totelgrpc.StreamServerInterceptor(opts...),\n\t\t\tlogutil.StreamTraceLoggerInterceptor,\n\t\t\tinterceptor.ClusterValidationStreamServerInterceptor(),\n\t\t\tinterceptor.ServerIDValidationStreamServerInterceptor(func() int64 {\n\t\t\t\tif s.serverID.Load() == 0 {\n\t\t\t\t\ts.serverID.Store(paramtable.GetNodeID())\n\t\t\t\t}\n\t\t\t\treturn s.serverID.Load()\n\t\t\t}),\n\t\t)))\n\tquerypb.RegisterQueryNodeServer(s.grpcServer, s)\n\n\tctx, cancel := context.WithCancel(s.ctx)\n\tdefer cancel()\n\n\tgo funcutil.CheckGrpcReady(ctx, s.grpcErrChan)\n\tif err := s.grpcServer.Serve(lis); err != nil {\n\t\tlog.Debug(\"QueryNode Start Grpc Failed!!!!\")\n\t\ts.grpcErrChan <- err\n\t}\n\n}", "func RunSync(yml load.Config, samplesToMerge *load.SamplesToMerge, originalAPINo int) {\n\tload.Logrus.WithFields(logrus.Fields{\n\t\t\"name\": yml.Name,\n\t\t\"apis\": len(yml.APIs),\n\t}).Debug(\"config: processing apis: Sync Mode\")\n\n\t// load secrets\n\t_ = loadSecrets(&yml)\n\n\tfor i := range yml.APIs {\n\t\tdataSets := FetchData(i, &yml, samplesToMerge)\n\t\tprocessor.RunDataHandler(dataSets, samplesToMerge, i, &yml, originalAPINo)\n\t}\n\n\tload.Logrus.WithFields(logrus.Fields{\n\t\t\"name\": yml.Name,\n\t\t\"apis\": len(yml.APIs),\n\t}).Debug(\"config: finished processing apis: Sync Mode\")\n\n\t// processor.ProcessSamplesToMerge(&samplesToMerge, &yml)\n\t// hren joinAndMerge processing - replacing processor.ProcessSamplesToMerge\n\t// ProcessSamplesMergeJoin will be processed in the run() function for the whole config\n\t// processor.ProcessSamplesMergeJoin(&samplesToMerge, &yml)\n}", "func (g *Game) StartGame() {\n\tg.createBoard()\n\tb := g.board\n\tb.MakeGrid(15, 15)\n\tbCount := 40\n\n\tb.PopulateBoard()\n\tb.SeedBees(bCount)\n\tb.EstablishNeighbors()\n\n\tgameOver := false\n\tb.PrintBoard()\n\n\tfor !gameOver {\n\t\tinput := getCoords()\n\t\tcell := b.FindCell(input)\n\t\tif cell.Bee {\n\t\t\tgameOver = true\n\t\t}\n\t\tcell.Show(b.Grid)\n\t\tb.PrintBoard()\n\t}\n\tb.RevealAll()\n\tfmt.Println(\"GAME OVER\")\n\tb.PrintBoard()\n}", "func startNewGame(conn net.Conn, r *bufio.Reader) {\n var username string\n board := makeBoard()\n started := false\n\n for (!started) {\n message, _ := r.ReadString('\\n')\n data := strings.Split(strings.TrimSuffix(message, \"\\r\\n\"), \" \")\n if (\"START\" == data[0]) {\n username = data[1]\n started = true\n fmt.Println(\"Starting New Game\\n\")\n } else {\n conn.Write([]byte(\"Invalid Command\\n\"))\n }\n }\n ticker := time.NewTicker(1 * time.Second)\n input := make(chan string)\n go checkShot(input, &board, r, conn, username)\n\n for range ticker.C {\n if !board.won {\n gameLoop(&board, r, conn, username, input)\n } else {\n ticker.Stop()\n conn.Write([]byte(\"Good Game! Let's Play Again!\\n\"))\n startNewGame(conn, r)\n }\n }\n}", "func Start() {\n\tonce.Do(func() {\n\t\tvar err error\n\t\tclient, err = ssdpbase.NewClient()\n\t\tlog.Panice(err)\n\n\t\tgo loop()\n\t})\n}", "func Loop(){\n\tfor {\n\t\t\t <-ElectionTimer.C\n\t\t\tif r.Id == r.LeaderId { \n\t\t\t\t\t//r.ResetTimer()\n\t\t\t\t}else{\n\t\t\t\t\tr.CallElection()\t\t\t\t\t\t\t\n\t\t\t\t}\n\t\t}//end of for\t\n}", "func LoadSyncData(hsURL, token, tempFile string) (json.RawMessage, error) {\n\tsyncData := loadDataFromDisk(tempFile)\n\tif syncData != nil {\n\t\tlog.Printf(\"Loaded sync data from %s\\n\", tempFile)\n\t\treturn syncData, nil\n\t}\n\t// We need to do a remote hit to the homeserver\n\thttpCli := &http.Client{}\n\n\tfilterStr := url.QueryEscape(`{\"event_format\":\"federation\", \"room\":{\"timeline\":{\"limit\":50}}}`)\n\n\tattempts := 0\n\n\tvar body []byte\n\tfor attempts < 20 {\n\t\tattempts++\n\t\t// Perform the sync\n\t\tlog.Println(\"Performing /sync...\")\n\t\tfilterReq, err := http.NewRequest(\"GET\", hsURL+\"/_matrix/client/r0/sync?filter=\"+filterStr, nil)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"failed to create sync request: %s\\n\", err)\n\t\t\tcontinue\n\t\t}\n\t\tbody, err = doRequest(httpCli, filterReq, token)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"failed to perform sync request: %s\\n\", err)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\tif body == nil {\n\t\treturn nil, fmt.Errorf(\"failed to perform /sync\")\n\t}\n\n\t// dump it straight to disk first\n\terr := ioutil.WriteFile(tempFile, body, 0644)\n\tif err != nil {\n\t\tlog.Printf(\"WARNING: failed to write sync data to disk: %s\", err)\n\t}\n\n\treturn body, nil\n}", "func (g *Game) startGame() {\n\tg.isStarted = true\n\tg.spawnRandomItems(len(g.Players) * 3)\n\tfor _, player := range g.Players {\n\t\tplayer.start()\n\t\tplayer.itemPos(*g)\n\t}\n}", "func (s *Syncer) Run() error {\n\tfor {\n\t\terrors := s.RunOnce()\n\t\tvar err error\n\t\tif len(errors) != 0 {\n\t\t\tif len(errors) == 1 {\n\t\t\t\terr = errors[0]\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"Errors: %v\", errors)\n\t\t\t}\n\t\t\ts.logger.WithError(err).Error(\"Failed running sync\")\n\t\t} else {\n\t\t\ts.logger.Debug(\"Updating success timestamp\")\n\t\t\ts.updateSuccessTimestamp()\n\t\t}\n\n\t\t// No poll interval configured, so return now\n\t\tif s.pollInterval == 0 {\n\t\t\ts.logger.Info(\"No poll configured\")\n\t\t\treturn err\n\t\t}\n\t\tsleep := randomize(s.pollInterval)\n\t\ts.logger.WithField(\"duration\", sleep).Info(\"Sleeping\")\n\t\ttime.Sleep(sleep)\n\t}\n}", "func (s *GameServer) startRound(now time.Time) {\n\tvar ids []PlayerId\n\tfor id := range s.players {\n\t\tids = append(ids, id)\n\t}\n\trand.Shuffle(len(ids), func(i, j int) {\n\t\tids[i], ids[j] = ids[j], ids[i]\n\t})\n\n\ts.matchups = nil\n\tfor i := 0; i < len(ids)-1; i += 2 {\n\t\ts.matchups = append(s.matchups, &Matchup{\n\t\t\tPlayers: [2]PlayerId{ids[i], ids[i+1]},\n\t\t})\n\t}\n\n\ts.phase = PhasePicking\n\ts.phaseDeadline = now.Add(time.Second * 10)\n}", "func (c *switchBotCollector) updateLoop() {\n\tticker := time.NewTicker(scrapeInterval)\n\n\tlog.Println(\"start collecting...\")\n\tc.update()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tc.update()\n\t\t}\n\t}\n}", "func (g *Grabber) Sync(notify chan int) {\n\tgrowing := 1\n\tfor {\n\t\tselect {\n\t\tcase <-g.done:\n\t\t\treturn\n\t\tcase <-time.After(time.Duration(growing) * time.Hour):\n\t\t}\n\n\t\tsame, err := g.loadMetaMetrics()\n\t\tif !same {\n\t\t\tnotify <- g.index // send index to scheduler\n\t\t}\n\t\tif err != nil {\n\t\t\tgl.Log.Errorf(\"loadMetaMetrics error. err=%s grabber=%s\", err, g.Name)\n\t\t\tcontinue\n\t\t}\n\t\tif growing < 16 {\n\t\t\tgrowing = growing * 2\n\t\t}\n\t}\n}", "func (server *Server) Sync() {\n\n}", "func StartGettingWeather() {\n\t// get some initial data from start\n\t// mainWeatherGetter()\n\n\tfor i := range time.Tick(time.Second * time.Duration(delay)) {\n\t\t_ = i\n\t\tloopCounter++\n\t\tfmt.Println(time.Now().Format(time.RFC850), \" counter: \", loopCounter)\n\t\tmainWeatherGetter()\n\t}\n}", "func (s *SshConnection) Start() {\n\tfor {\n\t\ts.connectionStatusMU.Lock()\n\t\ts.connectionStatus = STATUS_CONNECTING\n\t\ts.connectionStatusMU.Unlock()\n\t\tif err := s.connect(); err != nil {\n\t\t\tlog.Printf(\"error while connecting %s\", err)\n\t\t\ttime.Sleep(s.reconnectionInterval)\n\t\t\tcontinue\n\t\t}\n\t\t// client connected. Free the wait group\n\t\ts.Connected.Done()\n\t\ts.connectionStatusMU.Lock()\n\t\ts.connectionStatus = STATUS_CONNECTED\n\t\ts.connectionStatusMU.Unlock()\n\t\ts.keepAlive()\n\t\ts.Close()\n\t\ts.Connected.Add(1)\n\t}\n}", "func (gdb *Gdb) syncRtData() error {\n\tt := time.NewTicker(gdb.rtTimeDuration)\n\tfor {\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\tif err := gdb.rtDb.Sync(); err != nil {\n\t\t\t\tfmt.Println(\"fatal error occurred while synchronizing realTime data:\" + err.Error())\n\t\t\t\ttime.Sleep(time.Minute)\n\t\t\t\tos.Exit(-1)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n}", "func (svrs Servers) StartTest() {\n\tfor i, s := range svrs {\n\t\ts.Show()\n\t\tlatency := pingTest(s.URL)\n\t\tdlSpeed := downloadTest(s.URL, latency)\n\t\tulSpeed := uploadTest(s.URL, latency)\n\t\tsvrs[i].DLSpeed = dlSpeed\n\t\tsvrs[i].ULSpeed = ulSpeed\n\t\tsvrs[i].Ping = latency\n\t}\n}", "func (gc *GelfCore) Sync() error {\n\treturn nil\n}", "func (rcs *Service) pingLoop(done <-chan struct{}) {\n\tpingChan := make(chan *model.RemoteCluster, MaxConcurrentSends*2)\n\n\t// create a thread pool to send pings concurrently to remotes.\n\tfor i := 0; i < MaxConcurrentSends; i++ {\n\t\tgo rcs.pingEmitter(pingChan, done)\n\t}\n\n\tgo rcs.pingGenerator(pingChan, done)\n}", "func startBackgroundPermsSync(ctx context.Context, syncer *authz.PermsSyncer, db ossDB.DB) {\n\tglobals.WatchPermissionsUserMapping()\n\tgo func() {\n\t\tt := time.NewTicker(frontendAuthz.RefreshInterval())\n\t\tfor range t.C {\n\t\t\tallowAccessByDefault, authzProviders, _, _, _ := frontendAuthz.ProvidersFromConfig(\n\t\t\t\tctx,\n\t\t\t\tconf.Get(),\n\t\t\t\tdb.ExternalServices(),\n\t\t\t\tdb,\n\t\t\t)\n\t\t\tossAuthz.SetProviders(allowAccessByDefault, authzProviders)\n\t\t}\n\t}()\n\n\tgo syncer.Run(ctx)\n}", "func (j *CronJob) startSyncJob() {\n\tconfig := xcron.DefaultConfig()\n\tconfig.WithSeconds = true\n\tconfig.ImmediatelyRun = true\n\tcron := config.Build()\n\n\t// run every minute\n\t_, _ = cron.AddFunc(\"@every 15s\", func() error {\n\t\txlog.Debug(\"start sync job\")\n\n\t\t//load all jobs and write jobs to etcd\n\t\tj.writeJobsToEtcd()\n\n\t\t//remove job not exists\n\t\tj.removeInvalidJob()\n\n\t\t//clear timeout task\n\t\tj.clearTasks()\n\n\t\treturn nil\n\t})\n\n\tcron.Start()\n}", "func (r *Room) StartGame() {\n\tif r.Status != Waiting || r.board == nil {\n\t\treturn\n\t}\n\tr.Status = Started\n\tch := make(chan Update)\n\tend := time.NewTicker(r.board.Life()).C\n\tgo r.board.Start(r.in, ch)\n\tfor {\n\t\tselect {\n\t\tcase update := <-ch:\n\t\t\tif update.Status == Winner {\n\t\t\t\tr.Status = Ended\n\t\t\t\tgo SendUpdate(r.out, update)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tgo SendUpdate(r.out, update)\n\t\tcase <-end:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *RegionSyncer) StartSyncWithLeader(addr string) {\n\ts.wg.Add(1)\n\ts.RLock()\n\tclosed := s.closed\n\ts.RUnlock()\n\tgo func() {\n\t\tdefer s.wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-closed:\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t}\n\t\t\t// establish client\n\t\t\tclient, err := s.establish(addr)\n\t\t\tif err != nil {\n\t\t\t\tif ev, ok := status.FromError(err); ok {\n\t\t\t\t\tif ev.Code() == codes.Canceled {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlog.Error(\"server failed to establish sync stream with leader\", zap.String(\"server\", s.server.Name()), zap.String(\"leader\", s.server.GetLeader().GetName()), zap.Error(err))\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.Info(\"server starts to synchronize with leader\", zap.String(\"server\", s.server.Name()), zap.String(\"leader\", s.server.GetLeader().GetName()), zap.Uint64(\"request-index\", s.history.GetNextIndex()))\n\t\t\tfor {\n\t\t\t\tresp, err := client.Recv()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(\"region sync with leader meet error\", zap.Error(err))\n\t\t\t\t\tif err = client.CloseSend(); err != nil {\n\t\t\t\t\t\tlog.Error(\"failed to terminate client stream\", zap.Error(err))\n\t\t\t\t\t}\n\t\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif s.history.GetNextIndex() != resp.GetStartIndex() {\n\t\t\t\t\tlog.Warn(\"server sync index not match the leader\",\n\t\t\t\t\t\tzap.String(\"server\", s.server.Name()),\n\t\t\t\t\t\tzap.Uint64(\"own\", s.history.GetNextIndex()),\n\t\t\t\t\t\tzap.Uint64(\"leader\", resp.GetStartIndex()),\n\t\t\t\t\t\tzap.Int(\"records-length\", len(resp.GetRegions())))\n\t\t\t\t\t// reset index\n\t\t\t\t\ts.history.ResetWithIndex(resp.GetStartIndex())\n\t\t\t\t}\n\t\t\t\tfor _, r := range resp.GetRegions() {\n\t\t\t\t\terr = s.server.GetStorage().SaveRegion(r)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\ts.history.Record(core.NewRegionInfo(r, nil))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}", "func (d *WindowsDataplane) loopUpdatingDataplane() {\n\tlog.Debug(\"Started windows dataplane driver loop\")\n\n\thealthTicks := time.NewTicker(healthInterval).C\n\td.reportHealth()\n\n\t// Fill the apply throttle leaky bucket.\n\tthrottleC := jitter.NewTicker(100*time.Millisecond, 10*time.Millisecond).Channel()\n\tbeingThrottled := false\n\n\tdatastoreInSync := false\n\n\t// function to pass messages to the managers for processing\n\tprocessMsgFromCalcGraph := func(msg interface{}) {\n\t\tlog.WithField(\"msg\", proto.MsgStringer{Msg: msg}).Infof(\n\t\t\t\"Received %T update from calculation graph\", msg)\n\t\tfor _, mgr := range d.allManagers {\n\t\t\tmgr.OnUpdate(msg)\n\t\t}\n\t\tswitch msg.(type) {\n\t\tcase *proto.InSync:\n\t\t\tlog.WithField(\"timeSinceStart\", time.Since(processStartTime)).Info(\n\t\t\t\t\"Datastore in sync, flushing the dataplane for the first time...\")\n\t\t\tdatastoreInSync = true\n\t\t}\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase msg := <-d.toDataplane:\n\t\t\t// Process the message we received, then opportunistically process any other\n\t\t\t// pending messages.\n\t\t\tbatchSize := 1\n\t\t\tprocessMsgFromCalcGraph(msg)\n\t\tmsgLoop1:\n\t\t\tfor i := 0; i < msgPeekLimit; i++ {\n\t\t\t\tselect {\n\t\t\t\tcase msg := <-d.toDataplane:\n\t\t\t\t\tprocessMsgFromCalcGraph(msg)\n\t\t\t\t\tbatchSize++\n\t\t\t\tdefault:\n\t\t\t\t\t// Channel blocked so we must be caught up.\n\t\t\t\t\tbreak msgLoop1\n\t\t\t\t}\n\t\t\t}\n\t\t\td.dataplaneNeedsSync = true\n\t\tcase upd := <-d.ifaceAddrUpdates:\n\t\t\td.endpointMgr.OnHostAddrsUpdate(upd)\n\t\tcase <-throttleC:\n\t\t\td.applyThrottle.Refill()\n\t\tcase <-healthTicks:\n\t\t\td.reportHealth()\n\t\tcase <-d.reschedC:\n\t\t\tlog.Debug(\"Reschedule kick received\")\n\t\t\td.dataplaneNeedsSync = true\n\t\t\td.reschedC = nil\n\t\t}\n\n\t\tif datastoreInSync && d.dataplaneNeedsSync {\n\t\t\t// Dataplane is out-of-sync, check if we're throttled.\n\t\t\tif d.applyThrottle.Admit() {\n\t\t\t\tif beingThrottled && d.applyThrottle.WouldAdmit() {\n\t\t\t\t\tlog.Info(\"Dataplane updates no longer throttled\")\n\t\t\t\t\tbeingThrottled = false\n\t\t\t\t}\n\t\t\t\tlog.Info(\"Applying dataplane updates\")\n\t\t\t\tapplyStart := time.Now()\n\n\t\t\t\t// Actually apply the changes to the dataplane.\n\t\t\t\td.apply()\n\n\t\t\t\tapplyTime := time.Since(applyStart)\n\t\t\t\tlog.WithField(\"msecToApply\", applyTime.Seconds()*1000.0).Info(\n\t\t\t\t\t\"Finished applying updates to dataplane.\")\n\n\t\t\t\tif !d.doneFirstApply {\n\t\t\t\t\tlog.WithField(\n\t\t\t\t\t\t\"secsSinceStart\", time.Since(processStartTime).Seconds(),\n\t\t\t\t\t).Info(\"Completed first update to dataplane.\")\n\t\t\t\t\td.doneFirstApply = true\n\t\t\t\t}\n\n\t\t\t\td.reportHealth()\n\t\t\t} else {\n\t\t\t\tif !beingThrottled {\n\t\t\t\t\tlog.Info(\"Dataplane updates throttled\")\n\t\t\t\t\tbeingThrottled = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (ag *TSMClient) StartWorking() {\n\tlog.Info(\"Worker is starting work.\")\n\tdefer ag.waitGrp.Done()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ag.ctx.Done():\n\t\t\treturn\n\t\tcase work := <-ag.tsCh:\n\t\t\tag.DoWork(work)\n\t\t}\n\t}\n}", "func (s *Scheduler) Start(ctx context.Context) {\n\tfor {\n\t\tat, ok := s.clock.Receive(ctx)\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\ts.do(at)\n\t}\n}", "func mainLoop(ch chan int) {\n\tfmt.Println(\"Looping\")\n\n\tfor {\n\t\tfmt.Println(\"Updating world...\")\n\t\tupdate()\n\t\ttime.Sleep(updateInterval)\n\t}\n\tch <- 0\n}", "func (s *server) Start() {\n\t// Already started?\n\tif atomic.AddInt32(&s.started, 1) != 1 {\n\t\tlogging.CPrint(logging.INFO, \"started exit\", logging.LogFormat{\"started\": s.started})\n\t\treturn\n\t}\n\n\tlogging.CPrint(logging.TRACE, \"starting server\", logging.LogFormat{})\n\n\t// srvrLog.Trace(\"Starting server\")\n\tlogging.CPrint(logging.INFO, \"begin to start any com\", logging.LogFormat{})\n\n\t// Start SyncManager\n\ts.syncManager.Start()\n\n\ts.wg.Add(1)\n\n}", "func (m *Master) Start() int {\n\tgo m.input.run()\n\tfor _, workers := range m.workers {\n\t\tfor _, worker := range workers {\n\t\t\tgo worker.run()\n\t\t}\n\t}\n\tgo m.output.run()\n\treturn <-m.output.endChannel\n}", "func (cwl *CollectWeatherLoop) Start() {\n\tfor {\n\t\tselect {\n\t\tcase <-cwl.ticker.C:\n\t\t\t// collect the weather\n\t\t\tdata, err := cwl.sensorCollector.Collect()\n\t\t\tif err != nil {\n\t\t\t\tcwl.log.Error(err)\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvalues := map[string]string{\n\t\t\t\t\"humidity\": fmt.Sprintf(\"%.2f\", data.Humidity),\n\t\t\t\t\"temperature\": fmt.Sprintf(\"%.2f\", data.Temperature),\n\t\t\t}\n\n\t\t\ttags := map[string]string{\n\t\t\t\t\"room\": \"baby\",\n\t\t\t}\n\n\t\t\t// push to InfluxDB\n\t\t\terr = cwl.influxDBSender.Send(\"weather\", values, tags)\n\t\t\tif err != nil {\n\t\t\t\tcwl.log.Error(err)\n\t\t\t}\n\t\tcase <-cwl.done:\n\t\t\treturn\n\t\t}\n\t}\n}", "func startIncomingJobs() {\n\tfor relayName, _ := range config.Relays {\n\t\tgo incomingSchedular(relayName, config.Relays[relayName].GetSMSInterval)\n\t}\n}", "func (m *manager) backgroundSync(ctx context.Context) error {\n\tsyncTimer, syncTimerDone := inctimer.New()\n\tdefer syncTimerDone()\n\tfor {\n\t\tsyncInterval := m.backgroundSyncInterval()\n\t\tlog.WithField(\"syncInterval\", syncInterval.String()).Debug(\"Performing regular background work\")\n\n\t\tvar errs error\n\t\t// get a copy of the node identities to avoid locking the entire manager\n\t\t// throughout the process of running the datapath validation.\n\t\tnodes := m.GetNodeIdentities()\n\t\tfor _, nodeIdentity := range nodes {\n\t\t\t// Retrieve latest node information in case any event\n\t\t\t// changed the node since the call to GetNodes()\n\t\t\tm.mutex.RLock()\n\t\t\tentry, ok := m.nodes[nodeIdentity]\n\t\t\tif !ok {\n\t\t\t\tm.mutex.RUnlock()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tentry.mutex.Lock()\n\t\t\tm.mutex.RUnlock()\n\t\t\tm.Iter(func(nh datapath.NodeHandler) {\n\t\t\t\tif err := nh.NodeValidateImplementation(entry.node); err != nil {\n\t\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\t\"handler\": nh.Name(),\n\t\t\t\t\t\t\"node\": entry.node.Name,\n\t\t\t\t\t}).WithError(err).\n\t\t\t\t\t\tError(\"Failed to apply node handler during background sync. Cilium may have degraded functionality. See error message for details.\")\n\t\t\t\t\terrs = errors.Join(errs, fmt.Errorf(\"failed while handling %s on node %s: %w\", nh.Name(), entry.node.Name, err))\n\t\t\t\t}\n\t\t\t})\n\t\t\tentry.mutex.Unlock()\n\n\t\t\tm.metrics.DatapathValidations.Inc()\n\t\t}\n\n\t\tif errs != nil {\n\t\t\tm.healthReporter.Degraded(\"Failed to apply node validation\", errs)\n\t\t} else {\n\t\t\tm.healthReporter.OK(\"Node validation successful\")\n\t\t}\n\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tcase <-syncTimer.After(syncInterval):\n\t\t}\n\t}\n}", "func (sm *SyncManager) Start() {\n\t// Already started?\n\tif atomic.AddInt32(&sm.started, 1) != 1 {\n\t\treturn\n\t}\n\n\tsm.wg.Add(1)\n\tgo sm.blockHandler()\n}", "func RunSyncdb(name string, force bool, verbose bool) error {\n\tBootStrap()\n\n\tal := getDbAlias(name)\n\tcmd := new(commandSyncDb)\n\tcmd.al = al\n\tcmd.force = force\n\tcmd.noInfo = !verbose\n\tcmd.verbose = verbose\n\tcmd.rtOnError = true\n\treturn cmd.Run()\n}", "func (self *ShadowRedisSlave) trySync() {\n\tmasterId, masterOffset := self.fetchMasterIdAndReplOffset()\n\n\tif masterOffset > 0 {\n\t\tlog.Infof(\"Master [%s] has Repl Offset: [%d]. Try partial sync.\", masterId, masterOffset)\n\t\tcmd := \"PSYNC \" + masterId + \" \" + strconv.FormatInt(masterOffset, 10) + \"\\r\\n\"\n\t\t_, err := self.conn.Write([]byte(cmd))\n\t\tcheckError(err)\n\n\t\tlog.Debugf(\"Sent request : [%s]\", cmd)\n\n\t\texpectedLengh := len(RESP_CONTINUE)\n\t\tbuf := make([]byte, expectedLengh)\n\t\tn, err := self.conn.Read(buf)\n\t\tcheckError(err)\n\n\t\tfor i := 0; i < expectedLengh; i++ {\n\t\t\tif RESP_CONTINUE[i] != buf[i] {\n\t\t\t\tlog.Fatalf(\"Invalid psync response: %s\", string(buf[:n]))\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\n\t\t// set current offset\n\t\tself.offset = masterOffset - 1\n\t\tlog.Infof(\"Start offset : %d\", self.offset)\n\n\t} else {\n\t\t// log.Infof(\"No Master Repl Offset. Try full sync.\")\n\t\t// _, err := self.conn.Write([]byte(\"SYNC\\r\\n\"))\n\t\t// checkError(err)\n\n\t\t// Master will send `+FULLRESYNC {offset}\\r\\n` response first.\n\t\t// Parse it and keep offset to self.offset\n\t\tlog.Fatal(\"Can not send PSYNC. Terminated.\")\n\t\tos.Exit(1)\n\t}\n}" ]
[ "0.6990082", "0.6505114", "0.64570576", "0.63625956", "0.6352401", "0.622634", "0.5981771", "0.59244317", "0.5794886", "0.5771718", "0.57458603", "0.56999516", "0.56738234", "0.566845", "0.5636276", "0.55920625", "0.558578", "0.55855894", "0.55784124", "0.55763596", "0.5526159", "0.5523068", "0.5512906", "0.5490543", "0.5489009", "0.5444266", "0.53961486", "0.53860545", "0.5378948", "0.53580236", "0.5339664", "0.53304154", "0.5314114", "0.5298889", "0.52980584", "0.5265241", "0.5255824", "0.52409256", "0.5235792", "0.5230737", "0.5226354", "0.51903814", "0.518781", "0.5186411", "0.51823443", "0.51664716", "0.51643", "0.5161984", "0.5149473", "0.5144862", "0.51283956", "0.51273733", "0.5117377", "0.5115689", "0.5113574", "0.50834", "0.5082375", "0.5081831", "0.5073377", "0.5068976", "0.5051932", "0.5037311", "0.50359553", "0.5020826", "0.50207424", "0.5019909", "0.5017474", "0.5015808", "0.5014701", "0.50134355", "0.50115275", "0.50081", "0.5003945", "0.5002734", "0.5000243", "0.49983993", "0.499419", "0.49875727", "0.49827594", "0.49814117", "0.49762252", "0.49722466", "0.49721476", "0.49684986", "0.4961041", "0.49587685", "0.495784", "0.49555466", "0.49523902", "0.49273697", "0.49235848", "0.49217337", "0.49047247", "0.49026933", "0.4901972", "0.48953798", "0.48937052", "0.4887237", "0.48776874", "0.48683405" ]
0.8255443
0
init ... creates a new GitHub request object with all the gh api urls
func init() { urls = &pluginWebURL{ base: "https://api.github.com", authURL: "/authorizations", assigneeURL: "/repos/%s/%s/issues/%d/assignees", issueURL: "/repos/%s/%s/issues", labelURL: "/repos/%s/%s/issues/%d/labels", repo: "/repos/%s/%s", userRepo: "/user/repos", } info, _ := githandler.Remote() org := info.Organisation repo := info.Repository token := githandler.ConfigGet("token", "phlow") GitHub = &GitHubImpl{ urls, repo, org, token, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (g *GitHubStruct) github_set_url(server string) (err error) {\n\tgh_url := \"\"\n\tif g.github_source.Urls == nil {\n\t\tg.github_source.Urls = make(map[string]string)\n\t}\n\tif !g.maintain_ctxt {\n\t\tif server == \"\" || server == \"api.github.com\" || server == \"github.com\" {\n\t\t\tg.github_source.Urls[\"github-base-url\"] = \"https://api.github.com/\" // Default public API link\n\t\t\tg.github_source.Urls[\"github-url\"] = \"https://github.com\" // Default public link\n\t\t\tg.github_source.Urls[\"github-ssh\"] = \"[email protected]:\" // Default SSH connect string\n\t\t} else {\n\t\t\t// To accept GitHub entreprise without ssl, permit server to have url format.\n\t\t\tvar entr_github_re *regexp.Regexp\n\t\t\tif re, err := regexp.Compile(\"^(https?://)(.*)(/api/v3)/?$\"); err != nil {\n\t\t\t\treturn err\n\t\t\t} else {\n\t\t\t\tentr_github_re = re\n\t\t\t}\n\t\t\tres := entr_github_re.FindAllString(server, -1)\n\t\t\tif res == nil {\n\t\t\t\tgh_url = \"https://\" + server + \"/api/v3/\"\n\t\t\t\tg.github_source.Urls[\"github-url\"] = \"https://\" + server\n\t\t\t\tg.github_source.Urls[\"github-ssh\"] = \"git@\" + server + \":\" // SSH connect string\n\t\t\t} else {\n\t\t\t\tif res[2] == \"\" {\n\t\t\t\t\treturn fmt.Errorf(\"Unable to determine github URL from '%s'. It must be [https?://]Server[:Port][/api/v3]\", server)\n\t\t\t\t}\n\t\t\t\tif res[1] == \"\" {\n\t\t\t\t\tgh_url += \"https://\"\n\t\t\t\t}\n\t\t\t\tgh_url += res[2]\n\t\t\t\tg.github_source.Urls[\"github-url\"] = gh_url\n\t\t\t\tgh_url += \"/api/v3/\"\n\t\t\t\tg.github_source.Urls[\"github-ssh\"] = \"git@\" + res[2] + \":\" // SSH connect string\n\t\t\t}\n\t\t\tg.github_source.Urls[\"github-base-url\"] = gh_url\n\t\t\tg.githubDeploy.Urls = g.github_source.Urls\n\t\t}\n\t} else {\n\t\t// In case of maintain context, we read only Deploy repository.\n\t\tg.github_source.Urls = g.githubDeploy.Urls\n\t\tgh_url = g.github_source.Urls[\"github-base-url\"]\n\t}\n\n\tif gh_url == \"\" {\n\t\treturn\n\t}\n\n\tg.Client.BaseURL, err = url.Parse(gh_url)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t/*\t// Adding api/V3 for server given or url without path, ie http?://<server> instead or http?://<server>/<path>?\n\t\tif g.Client.BaseURL.Path == \"\" {\n\t\t\tlog.Printf(\"Adding /api/v3 to github url given %s\", gh_url)\n\t\t\tg.Client.BaseURL.Path = \"/api/v3/\"\n\t\t\tg.github_source.Urls[\"github-base-url\"] = g.Client.BaseURL.String()\n\t\t}*/\n\treturn\n}", "func initConfig() {\n\ttoken := rootCmd.Flag(\"token\").Value.String()\n\tgiturl := rootCmd.Flag(\"giturl\").Value.String()\n\tGitClient = gitlab.NewClient(nil, token)\n\tGitClient.SetBaseURL(giturl + \"/api/v4/\")\n}", "func New(organization string, c *config.Config) *API {\n\tctx := context.Background()\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: c.GithubToken},\n\t)\n\ttc := oauth2.NewClient(ctx, ts)\n\n\tclient := gh.NewClient(tc)\n\n\treturn &API{\n\t\torganization,\n\t\ttc,\n\t\tclient,\n\t\tcache{validDuration: time.Duration(6 * time.Hour)},\n\t}\n}", "func Init() *GithubBridge {\n\ts := &GithubBridge{\n\t\tGoServer: &goserver.GoServer{},\n\t\tserving: true,\n\t\tgetter: prodHTTPGetter{},\n\t\tattempts: 0,\n\t\tfails: 0,\n\t\tadded: make(map[string]time.Time),\n\t\taddedMutex: &sync.Mutex{},\n\t\taddedCount: make(map[string]int64),\n\t\tissueLock: &sync.Mutex{},\n\t}\n\treturn s\n}", "func (g *baseGithub) newRequest(method, url string, body interface{}) (*http.Request, error) {\n\tvar err error\n\n\tvar buf io.ReadWriter\n\tif body != nil {\n\t\tbuf = new(bytes.Buffer)\n\t\tenc := json.NewEncoder(buf)\n\t\tenc.SetEscapeHTML(false)\n\t\terr = enc.Encode(body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(method, url, buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif body != nil {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\treq.Header.Set(\"Accept\", \"application/json\")\n\n\treturn req, nil\n}", "func Init(_host, _user, _token string) {\n\tinitLogger()\n\tInitCache()\n\tcmdLogger.Debugf(\"initializing\")\n\tdefaultPrinter.DisableColor()\n\tif len(_host) > 0 && _host[len(_host)-1:][0] == '/' {\n\t\t_host = _host[0 : len(_host)-1]\n\t}\n\thost = _host\n\tuser = _user\n\ttoken = _token\n\tlab = gitlab.NewClient(gitlabHttpClient(), token)\n\tif lab.BaseURL().String() != (_host + \"/api/v4/\") {\n\t\tcmdLogger.Debugf(\"Changing BaseURL from %s to %s\", lab.BaseURL().String(), _host)\n\t\tlab.SetBaseURL(host + \"/api/v4\")\n\t}\n\tgraphqlClient = graphql.NewClient(host+\"/api/graphql\", withToken())\n\tgraphqlClient.Log = func(s string) {\n\t\tcmdLogger.Debugf(s)\n\t}\n\tviper.SetDefault(\"edit.filetype\", \"markdown\")\n}", "func (h *HTTPClient) newReq(method, token, projID, path string, body io.Reader) (*http.Request, error) {\n\turlStr := fmt.Sprintf(\"%s://%s:%d/3/projects/%s/%s\", h.scheme, h.host, h.port, projID, path)\n\treq, err := http.NewRequest(method, urlStr, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Authorization\", \"OAuth \"+token)\n\treturn req, nil\n}", "func New(logger *logrus.Entry, accessToken string) (Github, error) {\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: accessToken},\n\t)\n\n\t// Base http client with authentication\n\thttpClient := oauth2.NewClient(context.Background(), ts)\n\thttpClient.Timeout = Timeout\n\n\tc := github.NewClient(httpClient)\n\n\treturn &baseGithub{\n\t\tlogger: logger,\n\t\thttp: httpClient,\n\t\tc: c,\n\t\tdownloadClient: &http.Client{\n\t\t\tTimeout: Timeout,\n\t\t},\n\t}, nil\n}", "func NewFetch(repos, exclude, optional []string) *Fetch {\n\tfor i, url := range repos {\n\t\tif !strings.HasSuffix(url, \"/\") {\n\t\t\trepos[i] = url + \"/\"\n\t\t}\n\t\tif strings.HasPrefix(url, \"http:\") {\n\t\t\tlog.Warning(\"Repo URL %s is not secure, you should really be using https\", url)\n\t\t}\n\t}\n\tf := &Fetch{\n\t\trepos: repos,\n\t\tclient: &http.Client{Timeout: 30 * time.Second},\n\t\tcache: map[string][]byte{},\n\t\texclude: toMap(exclude),\n\t\toptional: toMap(optional),\n\t}\n\tf.Resolver = NewResolver(f)\n\treturn f\n}", "func (c *Client) newRequest(ctx context.Context, method, url string, body io.Reader) (*http.Request, error) {\n\t// Build new request with base URL.\n\treq, err := http.NewRequest(method, c.URL+url, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Set API key in header.\n\tif user := wtf.UserFromContext(ctx); user != nil && user.APIKey != \"\" {\n\t\treq.Header.Set(\"Authorization\", \"Bearer \"+user.APIKey)\n\t}\n\n\t// Default to JSON format.\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treq.Header.Set(\"Content-type\", \"application/json\")\n\n\treturn req, nil\n}", "func New(url string, token string) (g *Gitlab) {\n\tg = &Gitlab{\n\t\turl: url,\n\t\ttoken: token,\n\t\tclient: gitlab.NewClient(nil, token),\n\t}\n\tg.client.SetBaseURL(url)\n\treturn\n}", "func init() {\n\t// HackerNews allows API use without authentication, so we don't need an account.\n\t// We can just create our client object and use it.\n\thackerNewsClient = gophernews.NewClient()\n\t// Reddit, on the other hand, does require authentication. I set up an account, but you'll\n\t// need to set up your own. It's free.\n\t// Here, I pass in the username, password, and user agent string the API client will use.\n\tvar err error\n\tredditSession, err = geddit.NewLoginSession(\"g_d_bot\", \"K417k4FTua52\", \"gdAgent v0\")\n\t// In case of an error, we'll just exit the program.\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func (h *handler) initFromActionsEnv(ctx context.Context) {\n\ttoken := h.GetInput(\"repo_token\")\n\tif token == \"\" {\n\t\th.Fatalf(\"Empty repo_token\")\n\t}\n\th.Client = github.NewClient(oauth2.NewClient(ctx, oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: token},\n\t)))\n}", "func init() {\n\tflag.StringVar(&RedirectURL, \"redirect_url\", \"http://127.0.0.1:3000/auth\", \"Redirect URL used during oauth\")\n\tflag.Parse()\n\t// Gets Apps secrets & id for github\n\tghubCreds.Init()\n\tfmt.Println(ghubCreds)\n\tconf = &oauth2.Config{\n\t\tClientID: ghubCreds.Cid,\n\t\tClientSecret: ghubCreds.Csecret,\n\t\tRedirectURL: RedirectURL,\n\t\tScopes: []string{\"user:email\"},\n\t\tEndpoint: github.Endpoint,\n\t}\n}", "func (k *KeKahu) newRequest(method, endpoint string, body io.Reader) (*http.Request, error) {\n\n\t// Parse the endpoint\n\tep, err := url.Parse(endpoint)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not parse endpoint: %s\", err)\n\t}\n\n\t// Resolve the URL reference\n\tbaseURL, err := k.config.GetURL()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turl := baseURL.ResolveReference(ep)\n\n\t// Construct the request\n\treq, err := http.NewRequest(method, url.String(), body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not create request: %s\", err)\n\t}\n\n\t// Add the headers\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", k.config.APIKey))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept\", \"application/json\")\n\n\ttrace(\"created %s request to %s\", method, url)\n\treturn req, nil\n}", "func New(inConf *config.Config) Client {\n\turl := OrgRepoUrl\n\n\tspecifiedUrl := os.Getenv(\"GHCLI_GITHUB_URL\")\n\tif specifiedUrl != \"\" {\n\t\turl = specifiedUrl\n\t}\n\n\treturn Client{\n\t\tconf: inConf,\n\t\tgithubUrl: url,\n\t\tclient: &http.Client{},\n\t}\n}", "func (c *Client) NewRequest(method, urlStr string, body io.Reader) (*http.Request, error) {\n\trel, err := url.Parse(path.Join(apiVersion, urlStr))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := c.baseURL.ResolveReference(rel)\n\treq, err := http.NewRequest(method, u.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"Authorization\", \"Bearer \"+c.config.accessToken)\n\tif c.userAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", c.userAgent)\n\t}\n\treturn req, nil\n}", "func Request(\n\tnamespace, manifestDir, sha string, labels []string,\n\tgithubURL, apiURL, org, repo, token string,\n) {\n\tbranchName := fmt.Sprintf(\"deploy-%s\", sha)\n\ttmpDir, err := ioutil.TempDir(\"/tmp\", branchName)\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"creating tmp dir\")\n\t}\n\n\tdefer os.RemoveAll(tmpDir)\n\n\tcloneURL := buildCloneURL(githubURL, org, repo)\n\tauthURL := url.URL{\n\t\tScheme: cloneURL.Scheme,\n\t\tUser: url.UserPassword(\"dummy\", token),\n\t\tHost: cloneURL.Host,\n\t}\n\n\tcredFile := path.Join(tmpDir, \"git-credentials\")\n\terr = ioutil.WriteFile(credFile, []byte(authURL.String()), 0600)\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"writing credentials file\")\n\t}\n\n\tconfig := fmt.Sprintf(\"credential.helper=store --file=%s\", credFile)\n\tsrcDir := path.Join(tmpDir, \"src\")\n\tgit.MustRun(tmpDir, \"clone\",\n\t\t\"--config\", config,\n\t\t\"--config\", \"user.email=robot\",\n\t\t\"--config\", \"user.name=Robot\",\n\t\tcloneURL.String(),\n\t\tsrcDir,\n\t)\n\tgit.MustRun(srcDir, \"checkout\", \"-b\", branchName)\n\tgit.MustRun(srcDir, \"rm\", \"-r\", \"--ignore-unmatch\", namespace)\n\n\terr = copyDir(manifestDir, path.Join(srcDir, namespace))\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"copying manifests to repo\")\n\t}\n\n\tgit.MustRun(srcDir, \"add\", \"--all\")\n\n\tmsg := fmt.Sprintf(\"%s at %s\", namespace, sha)\n\tif len(labels) > 0 {\n\t\tmsg = fmt.Sprintf(\"%s\\n\", msg)\n\t\tfor _, l := range labels {\n\t\t\tmsg = fmt.Sprintf(\"%s\\n%s\", msg, l)\n\t\t}\n\t}\n\tgit.MustRun(srcDir, \"commit\",\n\t\t\"--message\", msg,\n\t\t\"--allow-empty\",\n\t)\n\tgit.MustRun(srcDir, \"push\", \"origin\", branchName)\n\n\t// Raise PR [\"deployments\" repo] with requested changes\n\n\tctx := context.Background()\n\tclient, err := gh.NewClient(ctx, apiURL, token)\n\n\ttitle := namespace + \" deployment request\"\n\thead := branchName\n\tbase := \"master\"\n\tbody := \"Deployment request for \" + namespace + \" at \" + sha\n\n\tpr, _, err := client.PullRequests.Create(ctx, org, repo, &github.NewPullRequest{\n\t\tTitle: &title,\n\t\tHead: &head,\n\t\tBase: &base,\n\t\tBody: &body,\n\t})\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"creating PR\")\n\t} else {\n\t\tlog.WithField(\"pullRequest\", *pr.Number).Info(\"pull request raised\")\n\t}\n}", "func (fetcher *Fetcher) Init() {\n\tfetcher.cpuUsageUrl = TSDB_URL + \"start=\" + TIME_AGO + \"&m=\" + AGREGATOR + \":\" + CPU_METRIC + \"{host=\" + HOST + \",colo=\" + COLO + \"}&format=json\"\n\tfetcher.memUsageUrl = TSDB_URL + \"start=\" + TIME_AGO + \"&m=\" + AGREGATOR + \":\" + MEM_USAGE_METRIC + \"{host=\" + HOST + \",colo=\" + COLO + \"}&format=json\"\n\tfetcher.diskFreeUrl = TSDB_URL + \"start=\" + TIME_AGO + \"&m=\" + AGREGATOR + \":\" + DISK_FREE_METRIC + \"{host=\" + HOST + \",colo=\" + COLO + \"}&format=json\"\n}", "func InitGithub(config *GithubConfig) {\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: config.Token},\n\t)\n\ttc := oauth2.NewClient(oauth2.NoContext, ts)\n\tservice = &githubService{\n\t\tconfig: config,\n\t\tclient: github.NewClient(tc),\n\t}\n}", "func NewGithub(config *models.Config) services.Service {\n\treturn &Github{NewFetcher(config, utils.NewHTTPJsonFetcher(config.HTTPRequestTimeout))}\n}", "func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {\n\t// this method is based off\n\t// https://github.com/google/go-github/blob/master/github/github.go:\n\t// NewRequest as it's a very nice way of doing this\n\t_, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// This is useful as this functionality works the same for the actual\n\t// BASE_URL and the download url (TODO(ttacon): insert download url)\n\t// this seems to be failing to work not RFC3986 (url resolution)\n\t//\tresolvedUrl := c.BaseUrl.ResolveReference(parsedUrl)\n\tresolvedUrl, err := url.Parse(c.BaseUrl.String() + urlStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf := new(bytes.Buffer)\n\tif body != nil {\n\t\tif err = json.NewEncoder(buf).Encode(body); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(method, resolvedUrl.String(), buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO(ttacon): identify which headers we should add\n\t// e.g. \"Accept\", \"Content-Type\", \"User-Agent\", etc.\n\treq.Header.Add(\"User-Agent\", USER_AGENT)\n\treturn req, nil\n}", "func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {\n\t// this method is based off\n\t// https://github.com/google/go-github/blob/master/github/github.go:\n\t// NewRequest as it's a very nice way of doing this\n\t_, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// This is useful as this functionality works the same for the actual\n\t// BASE_URL and the download url (TODO(ttacon): insert download url)\n\t// this seems to be failing to work not RFC3986 (url resolution)\n\t//\tresolvedUrl := c.BaseUrl.ResolveReference(parsedUrl)\n\tresolvedUrl, err := url.Parse(c.BaseUrl.String() + urlStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf := new(bytes.Buffer)\n\tif body != nil {\n\t\tif err = json.NewEncoder(buf).Encode(body); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(method, resolvedUrl.String(), buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO(ttacon): identify which headers we should add\n\t// e.g. \"Accept\", \"Content-Type\", \"User-Agent\", etc.\n\treq.Header.Add(\"User-Agent\", USER_AGENT)\n\treturn req, nil\n}", "func NewRequest(url string, branch string, author string, email string, date string, deps *[]Request) *Request {\n\treturn &Request{\n\t\turl,\n\t\tbranch,\n\t\tauthor,\n\t\temail,\n\t\tdate,\n\t\tdeps,\n\t}\n}", "func Init(ctx context.Context, local bool, gerritUrl string) (gerrit.GerritInterface, error) {\n\tts, err := git_steps.Init(ctx, local)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar rv gerrit.GerritInterface\n\terr = td.Do(ctx, td.Props(\"Gerrit Init\").Infra(), func(ctx context.Context) error {\n\t\tclient := httputils.DefaultClientConfig().WithTokenSource(ts).Client()\n\t\tg, err := gerrit.NewGerrit(gerritUrl, td.HttpClient(ctx, client))\n\t\trv = g\n\t\treturn err\n\t})\n\treturn rv, err\n}", "func newAPIRequest(host, path, apiKey string, body []byte) (*http.Request, error) {\n\treturn newAPIRequestWithHost(host, path, apiKey, body)\n}", "func (r *Repo) Init() error {\n\t// We get all needed information about the repo based on the remote url\n\tremote, err := getRemoteFromLocalRepoPath(r.LocalPath, r.RemoteName)\n\n\t// Parse the remote url into needed information, different paths for ssh vs http remotes\n\tswitch {\n\tcase strings.Contains(remote, \"://\"):\n\t\tremote = strings.TrimSpace(remote)\n\t\tremote = strings.TrimPrefix(remote, \"http://\")\n\t\tremote = strings.TrimPrefix(remote, \"https://\")\n\t\tremote = strings.TrimPrefix(remote, \"ssh://git@\")\n\t\tremote = strings.TrimSuffix(remote, \".git\")\n\t\tremoteS := strings.SplitN(remote, \"/\", 2) //nolint:gomnd\n\n\t\tr.HTTPURL = remote\n\t\tr.BaseURL = remoteS[0]\n\t\tr.Path = remoteS[1]\n\tcase strings.Contains(remote, \"@\"):\n\t\tremote = strings.TrimSpace(remote)\n\t\tremote = strings.TrimPrefix(remote, \"git@\")\n\t\tremote = strings.TrimSuffix(remote, \".git\")\n\t\tremoteS := strings.Split(remote, \":\")\n\n\t\tr.HTTPURL = remoteS[0] + \"/\" + remoteS[1]\n\t\tr.BaseURL = remoteS[0]\n\t\tr.Path = remoteS[1]\n\tdefault:\n\t\treturn fmt.Errorf(\"your remote (%s), %s, is not an SSH or HTTP remote\", r.RemoteName, remote)\n\t}\n\n\t// We create a list of gitlab groups that we can collect variables from. These are\n\t// just the paths before the repo name.\n\tgroups := path.Dir(r.Path)\n\tgroupsN := strings.Count(groups, \"/\") + 1\n\tfor i := groupsN; i > 0; i-- {\n\t\tr.Groups = append(r.Groups, groups)\n\t\tgroups = path.Dir(groups)\n\t}\n\n\treturn err\n}", "func newLogsAPIRequest(host, path, apiKey string, body []byte) (*http.Request, error) {\n\treturn newAPIRequestWithHost(host, path, apiKey, body)\n}", "func Initialize(lines []string) {\n\t// Put all URLs in the queue\n\tfor _, line := range lines {\n\t\tif line != \"\" { // Filter empty lines, in case there are any\n\t\t\tstate.queueChan <- scraping.Request{line, true} // This is a top level request\n\t\t\tstate.totalURLsToRequest += 1\n\t\t}\n\t}\n}", "func (c *Client) newRequest(method, urlStr string, body io.Reader) (*http.Request, error) {\n\treq, err := http.NewRequest(method, urlStr, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treq.Header.Set(\"api-name\", c.apiName)\n\treq.Header.Set(\"api-key\", c.apiKey)\n\treq.Header.Set(c.userHeader, c.user)\n\treturn req, nil\n}", "func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {\n\trel, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := c.baseURL.ResolveReference(rel)\n\n\tbuf := new(bytes.Buffer)\n\tif body != nil {\n\t\terr := json.NewEncoder(buf).Encode(body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(method, u.String(), buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"Authorization\", \"Bearer \"+c.authToken)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treturn req, nil\n}", "func NewGitHubFetcher(token string) *GitHubFetcher {\n\tts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})\n\ttc := oauth2.NewClient(oauth2.NoContext, ts)\n\tgf := &GitHubFetcher{\n\t\tc: github.NewClient(tc),\n\t}\n\treturn gf\n}", "func newRepoCache(apiURL *url.URL, a auth.Authenticator) *rcache.Cache {\n\tvar cacheTTL time.Duration\n\tif urlIsGitHubDotCom(apiURL) {\n\t\tcacheTTL = 10 * time.Minute\n\t} else {\n\t\t// GitHub Enterprise\n\t\tcacheTTL = 30 * time.Second\n\t}\n\n\tkey := \"\"\n\tif a != nil {\n\t\tkey = a.Hash()\n\t}\n\treturn rcache.NewWithTTL(\"gh_repo:\"+key, int(cacheTTL/time.Second))\n}", "func (c *Client) newRequest(method, path string) (*request, error) {\n\tbase, _ := url.Parse(c.config.Address)\n\tu, err := url.Parse(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := &request{\n\t\tconfig: &c.config,\n\t\tmethod: method,\n\t\turl: &url.URL{\n\t\t\tScheme: base.Scheme,\n\t\t\tUser: base.User,\n\t\t\tHost: base.Host,\n\t\t\tPath: u.Path,\n\t\t\tRawPath: u.RawPath,\n\t\t},\n\t\theader: make(http.Header),\n\t\tparams: make(map[string][]string),\n\t}\n\tif c.config.Region != \"\" {\n\t\tr.params.Set(\"region\", c.config.Region)\n\t}\n\tif c.config.Namespace != \"\" {\n\t\tr.params.Set(\"namespace\", c.config.Namespace)\n\t}\n\tif c.config.WaitTime != 0 {\n\t\tr.params.Set(\"wait\", durToMsec(r.config.WaitTime))\n\t}\n\tif c.config.SecretID != \"\" {\n\t\tr.token = r.config.SecretID\n\t}\n\n\t// Add in the query parameters, if any\n\tfor key, values := range u.Query() {\n\t\tfor _, value := range values {\n\t\t\tr.params.Add(key, value)\n\t\t}\n\t}\n\n\tfor key, values := range c.config.Headers {\n\t\tr.header[key] = values\n\t}\n\n\treturn r, nil\n}", "func createGist(url string, args []string) *grequests.Response {\n\t// get first teo arguments\n\tdescription := args[0]\n\t// remaining arguments are file names with path\n\tvar fileContents = make(map[string]File)\n\tfor i := 1; i < len(args); i++ {\n\t\tdat, err := ioutil.ReadFile(args[i])\n\t\tif err != nil {\n\t\t\tlog.Println(\"Please check the filenames. Absolute path (or) same directory are allowed\")\n\t\t\treturn nil\n\t\t}\n\t\tvar file File\n\t\tfile.Content = string(dat)\n\t\tfileContents[args[i]] = file\n\t}\n\tvar gist = Gist{Description: description, Public: true, Files: fileContents}\n\tvar postBody, _ = json.Marshal(gist)\n\tvar requestOptions_copy = requestOptions\n\t// Add data to JSON field\n\trequestOptions_copy.JSON = string(postBody)\n\t// make a Post request to Github\n\tresp, err := grequests.Post(url, requestOptions_copy)\n\tif err != nil {\n\t\tlog.Println(\"Create request failed for Github API\")\n\t}\n\treturn resp\n}", "func (c *Client) NewRequest(path string, urlVal url.Values) (*http.Request, error) {\n\tvar url strings.Builder\n\turl.WriteString(c.BaseURL.String())\n\turl.WriteString(path)\n\tif urlVal != nil || urlVal.Encode() != \"\" {\n\t\turl.WriteString(\"?\")\n\t\turl.WriteString(urlVal.Encode())\n\t}\n\n\tc.logger.Println(url.String())\n\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not create new request: %s\", err.Error())\n\t}\n\n\treq.Header.Add(\"Accept\", \"application/json\")\n\n\tvar bearer strings.Builder\n\tbearer.WriteString(\"Bearer \")\n\tbearer.WriteString(c.Token)\n\treq.Header.Add(\"authorization\", bearer.String())\n\n\treturn req, nil\n}", "func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {\n\trel, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := c.BaseURL.ResolveReference(rel)\n\n\tvar buf io.ReadWriter\n\tif body != nil {\n\t\tbuf = new(bytes.Buffer)\n\t\terr := json.NewEncoder(buf).Encode(body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(method, u.String(), buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tauthHeader := \"Bearer \" + c.Option.APIKey\n\n\treq.Header.Set(\"Authorization\", authHeader)\n\tif c.UserAgent != \"\" {\n\t\treq.Header.Add(\"User-Agent\", c.UserAgent)\n\t}\n\n\treturn req, nil\n}", "func HTTPInitDocumentation(r *gin.Engine) {\n\tbaseURL, ok := os.LookupEnv(\"HTTP_DOMAIN\")\n\tif !ok {\n\t\tpanic(\"http-docs-error\")\n\t}\n\turl := ginSwagger.URL(fmt.Sprintf(\"%s/swagger/doc.json\", baseURL))\n\tr.GET(\"/swagger/*any\", ginSwagger.WrapHandler(swaggerFiles.Handler, url))\n}", "func newGithubClient(token string) *github.Client {\n\tsrc := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: token},\n\t)\n\thttpClient := oauth2.NewClient(context.Background(), src)\n\treturn github.NewClient(httpClient)\n}", "func (r *Requester) newRequest(endpoint string) (*http.Request, error) {\n req, err := http.NewRequest(\"GET\", endpoint, nil)\n if err != nil {\n return nil, err\n }\n\tbearer := fmt.Sprintf(\"Bearer %s\", r.bearer)\n req.Header.Add(\"Authorization\", bearer)\n\treq.Header.Add(\"Ocp-Apim-Subscription-Key\", apimKey)\n req.Header.Set(\"User-Agent\", \"hackacraic\")\n\treturn req, nil\n}", "func New(repoURLPath string) (repo.Importer, error) {\n\t// Parse URL\n\t// Examples:\n\t// - https://github.com/[nikoksr]/[proji] -> extracts user and repo name; no branch name\n\t// - https://github.com/[nikoksr]/[proji]/tree/[master] -> extracts user, repo and branch name\n\tr := regexp.MustCompile(`github.com/(?P<User>[^/]+)/(?P<Repo>[^/]+)(/tree/(?P<Branch>[^/]+))?`)\n\tspecs := r.FindStringSubmatch(repoURLPath)\n\n\tif specs == nil || len(specs) < 5 {\n\t\treturn nil, fmt.Errorf(\"could not parse url path\")\n\t}\n\n\tuserName := specs[1]\n\trepoName := specs[2]\n\tbranchName := specs[4]\n\n\tif userName == \"\" || repoName == \"\" {\n\t\treturn nil, fmt.Errorf(\"could not extract user and/or repository name. Please check the URL\")\n\t}\n\n\t// Default to master if no branch was defined\n\tif branchName == \"\" {\n\t\tbranchName = \"master\"\n\t}\n\n\tg := &github{apiBaseURI: \"https://api.github.com/repos/\", userName: userName, repoName: repoName, branchName: branchName, repoSHA: \"\"}\n\treturn g, g.setRepoSHA()\n}", "func (j *DSGitHub) Validate(ctx *Ctx) (err error) {\n\tj.Org = strings.TrimSpace(j.Org)\n\tif j.Org == \"\" {\n\t\terr = fmt.Errorf(\"github org must be set\")\n\t\treturn\n\t}\n\tj.Repo = strings.TrimSpace(j.Repo)\n\tif strings.HasSuffix(j.Repo, \".git\") {\n\t\tlRepo := len(j.Repo)\n\t\tj.Repo = j.Repo[:lRepo-4]\n\t}\n\tif j.Repo == \"\" {\n\t\terr = fmt.Errorf(\"github repo must be set\")\n\t\treturn\n\t}\n\tj.Category = strings.TrimSpace(j.Category)\n\tif j.Category == \"\" {\n\t\terr = fmt.Errorf(\"github category must be set\")\n\t\treturn\n\t}\n\tj.URL = \"https://github.com/\" + j.Org + \"/\" + j.Repo\n\tdefer func() {\n\t\tPrintf(\"configured %d GitHub OAuth clients\\n\", len(j.Clients))\n\t}()\n\tj.Tokens = strings.TrimSpace(j.Tokens)\n\t// Get GitHub OAuth from env or from file\n\toAuth := j.Tokens\n\tif strings.Contains(oAuth, \"/\") {\n\t\tbytes, err := ioutil.ReadFile(oAuth)\n\t\tFatalOnError(err)\n\t\toAuth = strings.TrimSpace(string(bytes))\n\t}\n\t// GitHub authentication or use public access\n\tj.Context = context.Background()\n\tif oAuth == \"\" {\n\t\tclient := github.NewClient(nil)\n\t\tj.Clients = append(j.Clients, client)\n\t} else {\n\t\toAuths := strings.Split(oAuth, \",\")\n\t\tfor _, auth := range oAuths {\n\t\t\tj.OAuthKeys = append(j.OAuthKeys, auth)\n\t\t\tts := oauth2.StaticTokenSource(\n\t\t\t\t&oauth2.Token{AccessToken: auth},\n\t\t\t)\n\t\t\ttc := oauth2.NewClient(j.Context, ts)\n\t\t\tclient := github.NewClient(tc)\n\t\t\tj.Clients = append(j.Clients, client)\n\t\t}\n\t}\n\tif CacheGitHubRepo {\n\t\tj.GitHubRepo = make(map[string]map[string]interface{})\n\t}\n\tif CacheGitHubIssues {\n\t\tj.GitHubIssues = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubUser {\n\t\tj.GitHubUser = make(map[string]map[string]interface{})\n\t}\n\tif CacheGitHubIssueComments {\n\t\tj.GitHubIssueComments = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubCommentReactions {\n\t\tj.GitHubCommentReactions = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubIssueReactions {\n\t\tj.GitHubIssueReactions = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubPull {\n\t\tj.GitHubPull = make(map[string]map[string]interface{})\n\t}\n\tif CacheGitHubPulls {\n\t\tj.GitHubPulls = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubPullReviews {\n\t\tj.GitHubPullReviews = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubPullReviewComments {\n\t\tj.GitHubPullReviewComments = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubReviewCommentReactions {\n\t\tj.GitHubReviewCommentReactions = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubPullRequestedReviewers {\n\t\tj.GitHubPullRequestedReviewers = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubPullCommits {\n\t\tj.GitHubPullCommits = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubUserOrgs {\n\t\tj.GitHubUserOrgs = make(map[string][]map[string]interface{})\n\t}\n\t// Multithreading\n\tj.ThrN = GetThreadsNum(ctx)\n\tif j.ThrN > 1 {\n\t\tj.GitHubMtx = &sync.RWMutex{}\n\t\tj.GitHubRateMtx = &sync.RWMutex{}\n\t\tif CacheGitHubRepo {\n\t\t\tj.GitHubRepoMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubIssues {\n\t\t\tj.GitHubIssuesMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubUser {\n\t\t\tj.GitHubUserMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubIssueComments {\n\t\t\tj.GitHubIssueCommentsMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubCommentReactions {\n\t\t\tj.GitHubCommentReactionsMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubIssueReactions {\n\t\t\tj.GitHubIssueReactionsMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubPull {\n\t\t\tj.GitHubPullMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubPulls {\n\t\t\tj.GitHubPullsMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubPullReviews {\n\t\t\tj.GitHubPullReviewsMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubPullReviewComments {\n\t\t\tj.GitHubPullReviewCommentsMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubReviewCommentReactions {\n\t\t\tj.GitHubReviewCommentReactionsMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubPullRequestedReviewers {\n\t\t\tj.GitHubPullRequestedReviewersMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubPullCommits {\n\t\t\tj.GitHubPullCommitsMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubUserOrgs {\n\t\t\tj.GitHubUserOrgsMtx = &sync.RWMutex{}\n\t\t}\n\t}\n\tj.Hint, _ = j.handleRate(ctx)\n\tj.CacheDir = os.Getenv(\"HOME\") + \"/.perceval/github-users-cache/\"\n\t_ = os.MkdirAll(j.CacheDir, 0777)\n\treturn\n}", "func (r *RequestBuilder) Build(httpVerb string, uri string, body io.Reader) (*http.Request, error) {\n\turl, err := r.getAbsoluteURL(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequest, err := http.NewRequest(httpVerb, url, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequest.Header.Add(\"Content-Type\", \"application/json\")\n\trequest.Header.Add(\"User-Agent\", r.userAgent)\n\n\tif len(r.token) > 0 {\n\t\trequest.Header.Add(\"Authorization\", fmt.Sprintf(\"Bearer %s\", r.token))\n\t}\n\n\treturn request, nil\n}", "func (c *Client) newGetRequest(URLStr string) (*http.Request, error) {\n\trel, err := url.Parse(URLStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := c.baseURL.ResolveReference(rel)\n\n\t// Create a new get request with the url provided\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Set the api key on the request\n\treq.Header.Set(apiKeyHeader, c.apiKey)\n\n\t// If we specify a user agent we override the current one\n\tif c.userAgent != \"\" {\n\t\treq.Header.Set(userAgentHeader, c.userAgent)\n\t}\n\treturn req, nil\n}", "func SearchGitHub(query string, options SearchOptions, client *http.Client, results *[]RepoSearchResult, resultSet map[string]bool) (err error) {\n\tbase := \"\"\n\tif GetFlags().GithubRepo {\n\t\tbase = \"https://github.com/\" + query + \"/search\"\n\t} else {\n\t\tbase = \"https://github.com/search\"\n\t}\n\tpage, pages := 0, 1\n\tvar delay = 5\n\torders := []string{\"asc\"}\n\trankings := []string{\"indexed\"}\n\tfor i := 0; i < len(orders); i++ {\n\t\tfor j := 0; j < len(rankings); j++ {\n\t\t\tif i == 1 && j == 1 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor page < pages {\n\t\t\t\tstr := ConstructSearchURL(base, query, options)\n\t\t\t\t// fmt.Println(str)\n\t\t\t\tresponse, err := client.Get(str)\n\t\t\t\t// fmt.Println(response.StatusCode)\n\t\t\t\t// fmt.Println(err)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif response != nil {\n\t\t\t\t\t\t// fmt.Println(response.StatusCode)\n\t\t\t\t\t\tif response.StatusCode == 403 {\n\t\t\t\t\t\t\tresponse.Body.Close()\n\t\t\t\t\t\t\tdelay += 5\n\t\t\t\t\t\t\tcolor.Yellow(\"[!] Rate limited by GitHub. Waiting \" + strconv.Itoa(delay) + \"s...\")\n\t\t\t\t\t\t\ttime.Sleep(time.Duration(delay) * time.Second)\n\t\t\t\t\t\t} else if response.StatusCode == 503 {\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif delay > 10 {\n\t\t\t\t\tdelay--\n\t\t\t\t}\n\t\t\t\tresponseData, err := ioutil.ReadAll(response.Body)\n\t\t\t\tresponseStr := string(responseData)\n\t\t\t\t// fmt.Println(responseStr)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\tresponse.Body.Close()\n\t\t\t\tresultRegex := regexp.MustCompile(\"href=\\\"\\\\/((.*)\\\\/blob\\\\/([0-9a-f]{40}\\\\/([^#\\\"]+)))\\\">\")\n\t\t\t\tmatches := resultRegex.FindAllStringSubmatch(responseStr, -1)\n\t\t\t\tif page == 0 {\n\t\t\t\t\tif len(matches) == 0 {\n\t\t\t\t\t\tresultRegex = regexp.MustCompile(\"(?s)react-app\\\\.embeddedData\\\">(.*?)<\\\\/script>\")\n\t\t\t\t\t\tmatch := resultRegex.FindStringSubmatch(responseStr)\n\t\t\t\t\t\tvar resultPayload NewSearchPayload\n\t\t\t\t\t\t\n\t\t\t\t\t\tif len(match) == 0 {\n\t\t\t\t\t\t\tpage++\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tjson.Unmarshal([]byte(match[1]), &resultPayload)\n\t\t\t\t\t\tif !GetFlags().ResultsOnly && !GetFlags().JsonOutput {\n\t\t\t\t\t\t\tif pages != resultPayload.Payload.PageCount {\n\t\t\t\t\t\t\t\tcolor.Cyan(\"[*] Searching \" + strconv.Itoa(resultPayload.Payload.PageCount) + \" pages of results for '\" + query + \"'...\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpages = resultPayload.Payload.PageCount\n\t\t\t\t\t} else {\n\t\t\t\t\t\tregex := regexp.MustCompile(\"\\\\bdata\\\\-total\\\\-pages\\\\=\\\"(\\\\d+)\\\"\")\n\t\t\t\t\t\tmatch := regex.FindStringSubmatch(responseStr)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif len(match) == 2 {\n\t\t\t\t\t\t\tnewPages, err := strconv.Atoi(match[1])\n\t\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\t\tif newPages > GetFlags().Pages {\n\t\t\t\t\t\t\t\t\tnewPages = GetFlags().Pages\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tpages = newPages\n\t\t\t\t\t\t\t\tif pages > 99 && GetFlags().ManyResults {\n\t\t\t\t\t\t\t\t\tif !GetFlags().ResultsOnly && !GetFlags().JsonOutput {\n\t\t\t\t\t\t\t\t\t\tcolor.Cyan(\"[*] Searching 100+ pages of results for '\" + query + \"'...\")\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\torders = append(orders, \"desc\")\n\t\t\t\t\t\t\t\t\trankings = append(orders, \"\")\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tif !GetFlags().ResultsOnly && !GetFlags().JsonOutput {\n\t\t\t\t\t\t\t\t\t\tcolor.Cyan(\"[*] Searching \" + strconv.Itoa(pages) + \" pages of results for '\" + query + \"'...\")\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} else {\n\t\t\t\t\t\t\t\tcolor.Red(\"[!] An error occurred while parsing the page count.\")\n\t\t\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif strings.Index(responseStr, \"Sign in to GitHub\") > -1 {\n\t\t\t\t\t\t\t\tcolor.Red(\"[!] Unable to log into GitHub.\")\n\t\t\t\t\t\t\t\tlog.Fatal()\n\t\t\t\t\t\t\t} else if len(matches) > 0 {\n\t\t\t\t\t\t\t\tif !GetFlags().ResultsOnly {\n\t\t\t\t\t\t\t\t\tcolor.Cyan(\"[*] Searching 1 page of results for '\" + query + \"'...\")\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\t\t\t\t}\n\t\t\t\tpage++\n\t\t\t\tif len(matches) == 0 {\n\t\t\t\t\tresultRegex = regexp.MustCompile(\"(?s)react-app\\\\.embeddedData\\\">(.*?)<\\\\/script>\")\n\t\t\t\t\tmatch := resultRegex.FindStringSubmatch(responseStr)\n\t\t\t\t\tvar resultPayload NewSearchPayload\n\t\t\t\t\tif len(match) > 0 {\n\t\t\t\t\t\t// fmt.Println(match[1]/)\n\t\t\t\t\t\t// fmt.Println(match[1])\n\t\t\t\t\t\tjson.Unmarshal([]byte(match[1]), &resultPayload)\n\t\t\t\t\t\tfor _, result := range resultPayload.Payload.Results {\n\t\t\t\t\t\t\tif resultSet[(result.RepoName+result.Path)] == true {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif result.RepoName == \"\" {\n\t\t\t\t\t\t\t\tresult.RepoName = result.RepoNwo\n\t\t\t\t\t\t\t}\t\n\t\t\t\t\t\t\tresultSet[(result.RepoName + result.Path)] = true\n\t\t\t\t\t\t\tSearchWaitGroup.Add(1)\n\t\t\t\t\t\t\tgo ScanAndPrintResult(client, RepoSearchResult{\n\t\t\t\t\t\t\t\tRepo: result.RepoName,\n\t\t\t\t\t\t\t\tFile: result.Path,\n\t\t\t\t\t\t\t\tRaw: result.RepoName + \"/\" + result.CommitSha + \"/\" + result.Path,\n\t\t\t\t\t\t\t\tSource: \"repo\",\n\t\t\t\t\t\t\t\tQuery: query,\n\t\t\t\t\t\t\t\tURL: \"https://github.com/\" + result.RepoName + \"/blob/\" + result.CommitSha + \"/\" + result.Path,\n\t\t\t\t\t\t\t})\t\n\t\t\t\t\t\t\t// fmt.Println(result.RepoName + \"/\" + result.DefaultBranch + \"/\" + result.Path)\n\t\t\t\t\t\t}\t\n\t\t\t\t\t}\n\t\t\t\t} \n\t\t\t\toptions.Page = (page + 1)\n\t\t\t}\n\n\t\t}\n\t}\n\treturn nil\n}", "func New() *github.Client {\n\tctx := context.Background()\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: GithubAccessToken},\n\t)\n\n\ttc := oauth2.NewClient(ctx, ts)\n\tclient := github.NewClient(tc)\n\n\treturn client\n}", "func NewGifRequest(url ...string) *GifRequest {\n\trecorder := NewRecorder()\n\trq := &GifRequest{\n\t\tRecord: recorder,\n\t\tBaseURL: fmt.Sprintf(\"http://api.giphy.com/v1/gifs/search?rating=pg\"),\n\t}\n\n\tif len(url) != 0 {\n\t\trq.BaseURL = url[0]\n\t}\n\n\treturn rq\n}", "func (c *Client) newRequest(url string) (*http.Request, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"user-key\", c.key)\n\treq.Header.Add(\"Accept\", \"application/json\")\n\n\treturn req, nil\n}", "func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {\n\trel, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := c.BaseURL.ResolveReference(rel)\n\n\tvar buf io.ReadWriter\n\tif body != nil {\n\t\tbuf = new(bytes.Buffer)\n\t\terr := json.NewEncoder(buf).Encode(body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(method, u.String(), buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif c.accessToken != \"\" {\n\t\treq.Header.Add(\"Authorization\", \"Bearer \"+c.accessToken)\n\t}\n\n\treq.Header.Add(\"Accept\", mediaTypeV1)\n\tif c.UserAgent != \"\" {\n\t\treq.Header.Add(\"User-Agent\", c.UserAgent)\n\t}\n\treturn req, nil\n}", "func (c *apiClient) newRequest(ctx context.Context, method, resourcePath string,\n\tquery url.Values, body io.Reader) (*http.Request, error) {\n\tURL, err := url.Parse(c.BaseURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// BaseURL and resource URL is joined if they have a path\n\tURL.Path = c.joinURLPath(URL.Path, resourcePath)\n\tif query != nil {\n\t\tURL.RawQuery = query.Encode()\n\t}\n\trequest, err := http.NewRequestWithContext(ctx, method, URL.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trequest.Host = c.Host // allow cloudfronting\n\tif c.Authorization != \"\" {\n\t\trequest.Header.Set(\"Authorization\", c.Authorization)\n\t}\n\tif c.Accept != \"\" {\n\t\trequest.Header.Set(\"Accept\", c.Accept)\n\t}\n\trequest.Header.Set(\"User-Agent\", c.UserAgent)\n\treturn request, nil\n}", "func buildRequest(t Target) (http.Request, error) {\n\tif t.URL == \"\" {\n\t\treturn http.Request{}, errors.New(\"empty URL\")\n\t}\n\tif len(t.URL) < 8 {\n\t\treturn http.Request{}, errors.New(\"URL too short\")\n\t}\n\t//prepend \"http://\" if scheme not provided\n\t//maybe a cleaner way to do this via net.url?\n\tif t.URL[:7] != \"http://\" && t.URL[:8] != \"https://\" {\n\t\tt.URL = \"http://\" + t.URL\n\t}\n\tvar urlStr string\n\tvar err error\n\t//when regex set, generate urls\n\tif t.RegexURL {\n\t\turlStr, err = reggen.Generate(t.URL, 10)\n\t\tif err != nil {\n\t\t\treturn http.Request{}, fmt.Errorf(\"failed to parse regex: %w\", err)\n\t\t}\n\t} else {\n\t\turlStr = t.URL\n\t}\n\tURL, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn http.Request{}, fmt.Errorf(\"failed to parse URL %s: %w\", urlStr, err)\n\t}\n\tif URL.Host == \"\" {\n\t\treturn http.Request{}, errors.New(\"empty hostname\")\n\t}\n\n\tif t.Options.DNSPrefetch {\n\t\taddrs, err := net.LookupHost(URL.Hostname())\n\t\tif err != nil {\n\t\t\treturn http.Request{}, fmt.Errorf(\"failed to prefetch host %s\", URL.Host)\n\t\t}\n\t\tif len(addrs) == 0 {\n\t\t\treturn http.Request{}, fmt.Errorf(\"no addresses found for %s\", URL.Host)\n\t\t}\n\t\tURL.Host = addrs[0]\n\t}\n\n\t//setup the request\n\tvar req *http.Request\n\tif t.Options.BodyFilename != \"\" {\n\t\tfileContents, fileErr := ioutil.ReadFile(t.Options.BodyFilename)\n\t\tif fileErr != nil {\n\t\t\treturn http.Request{}, fmt.Errorf(\"failed to read contents of file %s: %w\", t.Options.BodyFilename, fileErr)\n\t\t}\n\t\treq, err = http.NewRequest(t.Options.Method, URL.String(), bytes.NewBuffer(fileContents))\n\t} else if t.Options.Body != \"\" {\n\t\tbodyStr := t.Options.Body\n\t\tif t.Options.RegexBody {\n\t\t\tbodyStr, err = reggen.Generate(t.Options.Body, 10)\n\t\t\tif err != nil {\n\t\t\t\treturn http.Request{}, fmt.Errorf(\"failed to parse regex: %w\", err)\n\t\t\t}\n\t\t}\n\t\treq, err = http.NewRequest(t.Options.Method, URL.String(), bytes.NewBuffer([]byte(bodyStr)))\n\t} else {\n\t\treq, err = http.NewRequest(t.Options.Method, URL.String(), nil)\n\t}\n\tif err != nil {\n\t\treturn http.Request{}, fmt.Errorf(\"failed to create request: %w\", err)\n\t}\n\t//add headers\n\tif t.Options.Headers != \"\" {\n\t\theaderMap, err := parseKeyValString(t.Options.Headers, \",\", \":\")\n\t\tif err != nil {\n\t\t\treturn http.Request{}, fmt.Errorf(\"could not parse headers: %w\", err)\n\t\t}\n\t\tfor key, val := range headerMap {\n\t\t\treq.Header.Add(key, val)\n\t\t}\n\t}\n\n\treq.Header.Set(\"User-Agent\", t.Options.UserAgent)\n\n\t//add cookies\n\tif t.Options.Cookies != \"\" {\n\t\tcookieMap, err := parseKeyValString(t.Options.Cookies, \";\", \"=\")\n\t\tif err != nil {\n\t\t\treturn http.Request{}, fmt.Errorf(\"could not parse cookies: %w\", err)\n\t\t}\n\t\tfor key, val := range cookieMap {\n\t\t\treq.AddCookie(&http.Cookie{Name: key, Value: val})\n\t\t}\n\t}\n\n\tif t.Options.BasicAuth != \"\" {\n\t\tauthMap, err := parseKeyValString(t.Options.BasicAuth, \",\", \":\")\n\t\tif err != nil {\n\t\t\treturn http.Request{}, fmt.Errorf(\"could not parse basic auth: %w\", err)\n\t\t}\n\t\tfor key, val := range authMap {\n\t\t\treq.SetBasicAuth(key, val)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn *req, nil\n}", "func New(\n\tconfig Config,\n) (*Github, error) {\n\tctx := context.Background()\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: config.Token},\n\t)\n\ttc := oauth2.NewClient(ctx, ts)\n\ttc.Transport = config.TransportMiddleware(tc.Transport)\n\n\tvar client *github.Client\n\tif config.BaseURL != \"\" {\n\t\tvar err error\n\t\tclient, err = github.NewEnterpriseClient(config.BaseURL, \"\", tc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tclient = github.NewClient(tc)\n\t}\n\n\treturn &Github{\n\t\tRepositoryListing: config.RepoListing,\n\t\tMergeTypes: config.MergeTypes,\n\t\ttoken: config.Token,\n\t\tbaseURL: config.BaseURL,\n\t\tFork: config.ForkMode,\n\t\tForkOwner: config.ForkOwner,\n\t\tSSHAuth: config.SSHAuth,\n\t\tghClient: client,\n\t\tReadOnly: config.ReadOnly,\n\t\tcheckPermissions: config.CheckPermissions,\n\t\thttpClient: &http.Client{\n\t\t\tTransport: config.TransportMiddleware(http.DefaultTransport),\n\t\t},\n\t}, nil\n}", "func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {\n\tvar s string\n\tif strings.HasPrefix(urlStr, \"/\") {\n\t\ts = fmt.Sprintf(\"/%s%s\", apiVersion, urlStr)\n\t} else {\n\t\ts = fmt.Sprintf(\"/%s/%s\", apiVersion, urlStr)\n\t}\n\trel, err := url.Parse(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := c.BaseURL.ResolveReference(rel)\n\n\tvar buf io.ReadWriter\n\tif body != nil {\n\t\tbuf = new(bytes.Buffer)\n\t\terr = json.NewEncoder(buf).Encode(body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(method, u.String(), buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif body != nil {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\treturn req, nil\n}", "func Github(ctx *sapphire.CommandContext) {\n\trepo := strings.Split(ctx.Arg(0).AsString(), \"/\")\n\n\tif len(repo) < 2 {\n\t\tctx.Reply(\"Invalid repository. it must be in the format `username/repository`\")\n\t\treturn\n\t}\n\n\tres, err := http.Get(\"https://api.github.com/repos/\" + repo[0] + \"/\" + repo[1])\n\n\tif err != nil {\n\t\tctx.Error(err)\n\t\treturn\n\t}\n\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != 200 {\n\t\tctx.Reply(\"Could not fetch that repository, are you sure it exists?\")\n\t\treturn\n\t}\n\n\tbuf, err := ioutil.ReadAll(res.Body)\n\n\tif err != nil {\n\t\tctx.Error(err)\n\t\treturn\n\t}\n\n\tvar data struct {\n\t\tName string `json:\"full_name\"`\n\t\tLanguage string `json:\"language\"`\n\t\tURL string `json:\"html_url\"`\n\t\tDescription string `json:\"description\"`\n\t\tSize int `json:\"size\"`\n\t\tWatchers int `json:\"subscribers_count\"`\n\t\tForks int `json:\"forks_count\"`\n\t\tStargazers int `json:\"stargazers_count\"`\n\t\tOpenIssues int `json:\"open_issues\"`\n\t\tOwner struct {\n\t\t\tAvatarURL string `json:\"avatar_url\"`\n\t\t} `json:\"owner\"`\n\t\tLicense struct {\n\t\t\tName string `json:\"name\"`\n\t\t\tURL string `json:\"url\"`\n\t\t} `json:\"license\"`\n\t\tFork bool `json:\"fork\"`\n\t\tArchived bool `json:\"archived\"`\n\t\tParent struct {\n\t\t\tName string `json:\"full_nane\"`\n\t\t\tURL string `json:\"html_url\"`\n\t\t} `json:\"parent\"`\n\t}\n\n\terr = json.Unmarshal(buf, &data)\n\n\tif err != nil {\n\t\tctx.Error(err)\n\t\treturn\n\t}\n\n\tlicense := \"None\"\n\tif data.License.Name != \"\" {\n\t\tif data.License.URL != \"\" {\n\t\t\tlicense = fmt.Sprintf(\"[%s](%s)\", data.License.Name, data.License.URL)\n\t\t} else {\n\t\t\tlicense = data.License.Name\n\t\t}\n\t}\n\n\tdescription := \"No Description\"\n\n\tif data.Description != \"\" {\n\t\tdescription = data.Description\n\t}\n\n\tfooter := make([]string, 0)\n\n\tif data.Fork {\n\t\tfooter = append(footer, fmt.Sprintf(\"❯ **Forked** from [%s](%s)\", data.Parent.Name, data.Parent.URL))\n\t}\n\n\tif data.Archived {\n\t\tfooter = append(footer, \"❯ This repository is **Archived**\")\n\t}\n\n\tfooterText := \"\"\n\n\tif len(footer) > 0 {\n\t\tfooterText = strings.Join(footer, \"\\n\")\n\t}\n\n\tctx.BuildEmbed(sapphire.NewEmbed().\n\t\tSetColor(0xDFAC7C).\n\t\tSetTitle(data.Name).\n\t\tSetAuthor(\"GitHub\", \"https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png\").\n\t\tSetURL(data.URL).\n\t\tSetThumbnail(data.Owner.AvatarURL).\n\t\tSetDescription(fmt.Sprintf(\"%s\\n\\n❯ **Language:** %s\\n❯ **Forks:** %s\\n❯ **License:** %s\\n❯ **Open Issues:** %s\\n❯ **Watchers:** %s\\n❯ **Stars:** %s\\n❯ **Clone Size:** %s\\n%s\",\n\t\t\tdescription,\n\t\t\tdata.Language,\n\t\t\thumanize.Comma(int64(data.Forks)),\n\t\t\tlicense,\n\t\t\thumanize.Comma(int64(data.OpenIssues)),\n\t\t\thumanize.Comma(int64(data.Watchers)),\n\t\t\thumanize.Comma(int64(data.Stargazers)),\n\t\t\thumanize.Bytes(uint64(data.Size*1024)),\n\t\t\tfooterText,\n\t\t)))\n}", "func (c *Client) newRequest(method string, refURL string, params url.Values) (*http.Request, error) {\n\trel, err := url.Parse(refURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif params != nil {\n\t\trel.RawQuery = params.Encode()\n\t}\n\tu := c.BaseURL.ResolveReference(rel)\n\n\tvar req *http.Request\n\n\treq, err = http.NewRequest(method, u.String(), nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func (qiwi *PersonalAPI) newRequest(apiKey, method, spath string, data map[string]interface{}) (req *http.Request, err error) {\n\n\tvar path = APIURL + spath\n\n\tvar body io.Reader\n\n\tif len(data) > 0 {\n\n\t\ts, err := json.Marshal(data)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tbody = bytes.NewBuffer(s)\n\n\t}\n\n\treq, err = http.NewRequest(method, path, body)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"Accept\", \"application/json\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+apiKey)\n\n\treturn req, err\n}", "func Init(clientid string, scope string) (string, string, error) {\n\tif clientid == \"\" {\n\t\treturn \"\", \"\", errors.New(\"No Client ID Provided\")\n\t}\n\tscopelist := []string{\"\", \"repo\", \"repo:status\",\n\t\t\"repo_deployment\", \"public_repo\", \"repo:invite\",\n\t\t\"security_events\", \"admin:repo_hook\", \"write:repo_hook\",\n\t\t\"read:repo_hook\", \"admin:org\", \"write:org\",\n\t\t\"read:org\", \"admin:public_key\", \"write:public_key\",\n\t\t\"read:public_key\", \"admin:org_hook\", \"gist\",\n\t\t\"notifications\", \"user\", \"read:user\",\n\t\t\"user:email\", \"user:follow\", \"delete_repo\",\n\t\t\"write:discussion\", \"read:discussion\", \"write:packages\",\n\t\t\"read:packages\", \"delete:packages\", \"admin:gpg_key\",\n\t\t\"write:gpg_key\", \"read:gpg_key\", \"workflow\"}\n\tif strings.Contains(scope, \",\") {\n\t\tscopeslice := strings.Split(scope, \",\")\n\t\tfor _, element := range scopeslice {\n\t\t\tif !contains(scopelist, element) {\n\t\t\t\treturn \"\", \"\", errors.New(\"Invalid scope\")\n\t\t\t}\n\t\t}\n\t} else if !contains(scopelist, scope) {\n\t\treturn \"\", \"\", errors.New(\"Invalid scope\")\n\t}\n\tclient := resty.New()\n\tresponse, err := client.R().\n\t\tSetQueryString(\"client_id=\"+clientid+\"&scope=\"+scope).\n\t\tSetHeader(\"User-Agent\", \"libgithubauth <https://github.com/BlyatManGopnik/libgithubauth>\").\n\t\tSetHeader(\"Accept\", \"application/json\").\n\t\tPost(\"https://github.com/login/device/code\")\n\tjsondat := fmt.Sprint(response)\n\tif getJSONValue(jsondat, \"error\") == \"Not Found\" {\n\t\treturn \"\", \"\", errors.New(\"Invalid Client ID\")\n\t}\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tdevicecode := getJSONValue(jsondat, \"device_code\")\n\tusercode := getJSONValue(jsondat, \"user_code\")\n\treturn devicecode, usercode, nil\n}", "func init() {\n\tRepoCreateTodo(Todo{Name: \"Write presentation\"})\n\tRepoCreateTodo(Todo{Name: \"Host meetup\"})\n}", "func init() {\n\tRepoCreateTodo(Todo{Name: \"Write presentation\"})\n\tRepoCreateTodo(Todo{Name: \"Host meetup\"})\n}", "func NewRequest(r *http.Request, storagea string) (*Request, error) {\n\tvar err error\n\treq := new(Request)\n\n\tpath := r.URL.Path[1:] // strip leading slash\n\n\n\treq.URL, err = url.Parse(path)\n\n\n\tif err != nil || !req.URL.IsAbs() {\n\t\t// first segment is likely options\n\t\tparts := strings.SplitN(path, \"/\", 2)\n\t\tif len(parts) != 2 {\n\t\t\treturn nil, URLError{\"too few path segments\", r.URL}\n\t\t}\n\n\t\tu := storagea + parts[1]\n\n\t\treq.URL, err = url.Parse(u)\n\t\tif err != nil {\n\t\t\treturn nil, URLError{fmt.Sprintf(\"unable to parse remote URL: %v\", err), r.URL}\n\t\t}\n\n\t\treq.Options = ParseOptions(parts[0])\n\t}\n\n\n\tif !req.URL.IsAbs() {\n\t\treturn nil, URLError{\"must provide absolute remote URL\", r.URL}\n\t}\n\n\n\tif req.URL.Scheme != \"http\" && req.URL.Scheme != \"https\" {\n\t\treturn nil, URLError{\"remote URL must have http or https URL\", r.URL}\n\t}\n\n\n\n\t// query string is always part of the remote URL\n\treq.URL.RawQuery = r.URL.RawQuery\n\treturn req, nil\n}", "func (s *imageBuilderServer) Init(ctx context.Context, gitRepo *api.GitRepo) (*api.Response, error) {\n\ts.initialized = true\n\n\t// TODO: save git repo params and clone\n\n\treturn &okResponse, nil\n}", "func NewFromURL(base *url.URL) *Client {\n\n\tif baseStr := base.String(); len(baseStr) > 0 {\n\n\t\tLogger.Debug(\"Creating Marathon Client from url.URL = %s\", base.String())\n\t\tbaseURL, err := url.Parse(baseStr)\n\t\tif err != nil {\n\t\t\tLogger.Debug(\"Invalid baseURL\")\n\t\t\treturn nil\n\t\t}\n\n\t\t_client := &Client{}\n\t\treturn _client.New(baseURL)\n\t}\n\treturn nil\n}", "func New(apiKey string, logger *logging.StandardLogger) *Client {\n\tc := &http.Client{Timeout: 15 * time.Second}\n\n\tq := baseURL.Query() // Get a copy of the query values.\n\tq.Add(\"token\", apiKey) // Add a new value to the set.\n\tbaseURL.RawQuery = q.Encode() // Encode and assign back to the original query.\n\n\treturn &Client{\n\t\tc: c,\n\t\tapiKey: apiKey,\n\t\tsyncToken: \"*\",\n\t\tlogger: logger,\n\t}\n}", "func New(url string) *Client {\n\treturn &Client{&http.Client{}, url, func(r *http.Request) *http.Request { return r }}\n}", "func (client *Client) newGetRequest(urlString string) (*http.Request, error) {\n\trelevantUrl, err := url.Parse(urlString)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfinalUrl := client.baseURL.ResolveReference(relevantUrl)\n\n\treq, err := http.NewRequest(\"GET\", finalUrl.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(apiKeyHeader, client.apiKey)\n\n\tif client.userAgent != \"\" {\n\t\treq.Header.Set(userAgentHeader, client.userAgent)\n\t}\n\n\treturn req, nil\n}", "func (a *APIv2) NewAPIRequest(method, urlStr string, body io.Reader) (*http.Request, error) {\n\treq, err := http.NewRequest(method, urlStr, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.SetBasicAuth(\"x\", a.key)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"X-Gms-Client-Version\", config.VERSION)\n\treq.Header.Add(\"X-Gms-Revision\", utils.GetCurrentRevision())\n\treq.Header.Add(\"X-Gms-Branch\", utils.GetCurrentBranch())\n\treturn req, nil\n}", "func init() {\r\n\tappConfig = config.GetAppConfiguration();\r\n\trequestTimeout := time.Duration(appConfig[\"httpRequestTimeout\"].(float64));\r\n\thttpClient = http.Client{Timeout: time.Millisecond * requestTimeout}\r\n}", "func New(opts ...Option) (RequestClient, error) {\n\tr := RequestClient{\n\t\tmethod: defaultMethod,\n\t\tbase: defaultBaseURL,\n\t\tbody: bytes.NewBuffer(nil),\n\t\tqueries: make(url.Values),\n\t\theaders: make(http.Header),\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(&r)\n\t}\n\n\tapiURL, err := url.Parse(buildRaw(r.base, r.path, r.queries))\n\n\tif err != nil {\n\t\treturn RequestClient{}, err\n\t}\n\n\tr.resourceURL = apiURL\n\n\treturn r, nil\n}", "func NewHTTP(idxAddr, dst string) (RepositoryGetter, error) {\n\trepoAddr := baseOfURL(idxAddr)\n\n\trepoURL, err := url.Parse(repoAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tidxURL, err := url.Parse(idxAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &HTTPGetter{\n\t\tidxURL: idxURL,\n\t\trepoURL: repoURL,\n\t\tdst: path.Join(dst, rand.String(10)),\n\t\tunderlying: &getter.HttpGetter{\n\t\t\tClient: defaultClient,\n\t\t},\n\t}, nil\n}", "func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {\n\trel, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := c.baseURL.ResolveReference(rel)\n\n\tvar data io.Reader\n\tif body != nil {\n\t\tb, err := json.Marshal(body)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdata = bytes.NewReader(b)\n\t}\n\n\treq, err := http.NewRequest(method, u.String(), data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept\", \"application/json\")\n\n\t// Set session cookie if there is one\n\tif c.session != nil {\n\t\treq.Header.Set(\"Authorization\", c.session.Authorization)\n\t\t// TODO: remove this\n\t\t//fmt.Printf(c.session.Authorization)\n\t}\n\n\treturn req, nil\n}", "func (conn Connection) newRequest(method, cmd string, body io.Reader) *http.Request {\n\t// req, err := conn.jhReq(method, cmd, body)\n\treq, err := http.NewRequest(method, conn.HubURL+cmd, body)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Coulnd't generate HTTP request - %s\\n\", err.Error()))\n\t}\n\n\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"token %s\", conn.Token))\n\n\treturn req\n}", "func Init(testing bool, token string) {\n\tif testing {\n\t\tapiURL = \"https://api.staging.tauros.io\"\n\t}\n\tapiToken = token\n}", "func (c *GithubConfig) Init(gerritClient gerrit.GerritInterface, githubClient *github.GitHub) (CodeReview, error) {\n\treturn newGithubCodeReview(c, githubClient)\n}", "func (c *Client) NewRequest(method, urlStr string, body io.Reader) (*http.Request, error) {\n\tif !strings.HasSuffix(c.BaseURL.Path, \"/\") {\n\t\treturn nil, fmt.Errorf(\"BaseURL must have a trailing slash, but %q does not\", c.BaseURL)\n\t}\n\trel, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := c.BaseURL.ResolveReference(rel)\n\n\treq, err := http.NewRequest(method, u.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif c.UserAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", c.UserAgent)\n\t}\n\treturn req, nil\n}", "func (c *Client) NewRequest(method, urlStr string, body io.Reader) (*http.Request, error) {\n\trel, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := c.BaseURL.ResolveReference(rel)\n\n\treq, err := http.NewRequest(method, u.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func initConfig() {\n\n\t_, hasToken := os.LookupEnv(\"PRIVATE_ACCESS_TOKEN\")\n\t_, hasURL := os.LookupEnv(\"CI_PROJECT_URL\")\n\tif !hasToken || !hasURL {\n\t\tlog.Fatal(\"You need to set 'CI_PROJECT_URL' and 'PRIVATE_ACCESS_TOKEN'\")\n\t}\n\n\tviper.Set(\"Token\", os.Getenv(\"PRIVATE_ACCESS_TOKEN\"))\n\tviper.Set(\"ProjectUrl\", os.Getenv(\"CI_PROJECT_URL\"))\n\n\tu, err := url.Parse(viper.GetString(\"ProjectUrl\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tviper.Set(\"BaseUrl\", fmt.Sprintf(\"%s://%s\", u.Scheme, u.Host))\n\tviper.Set(\"RegistryUrl\", fmt.Sprintf(\"%s/container_registry.json\", viper.GetString(\"ProjectUrl\")))\n\n}", "func (c *Client) NewRequest(method, urlStr string, opt interface{}, body interface{}) (*http.Request, error) {\n\trel, err := addOptions(urlStr, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif AuthTest {\n\t\t// Add the auth_test param\n\t\tvalues := rel.Query()\n\t\tvalues.Add(\"auth_test\", strconv.FormatBool(AuthTest))\n\t\trel.RawQuery = values.Encode()\n\t}\n\n\tu := c.BaseURL.ResolveReference(rel)\n\n\tbuf := new(bytes.Buffer)\n\tif body != nil {\n\t\terr := json.NewEncoder(buf).Encode(body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(method, u.String(), buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"Authorization\", \"Bearer \"+c.authToken)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treturn req, nil\n}", "func newFetch(g *Goproxy, name, tempDir string) (*fetch, error) {\n\tf := &fetch{\n\t\tg: g,\n\t\tname: name,\n\t\ttempDir: tempDir,\n\t}\n\n\tvar escapedModulePath string\n\tif strings.HasSuffix(name, \"/@latest\") {\n\t\tescapedModulePath = strings.TrimSuffix(name, \"/@latest\")\n\t\tf.ops = fetchOpsResolve\n\t\tf.moduleVersion = \"latest\"\n\t\tf.contentType = \"application/json; charset=utf-8\"\n\t} else if strings.HasSuffix(name, \"/@v/list\") {\n\t\tescapedModulePath = strings.TrimSuffix(name, \"/@v/list\")\n\t\tf.ops = fetchOpsList\n\t\tf.moduleVersion = \"latest\"\n\t\tf.contentType = \"text/plain; charset=utf-8\"\n\t} else {\n\t\tnameParts := strings.SplitN(name, \"/@v/\", 2)\n\t\tif len(nameParts) != 2 {\n\t\t\treturn nil, errors.New(\"missing /@v/\")\n\t\t}\n\n\t\tescapedModulePath = nameParts[0]\n\n\t\tnameExt := path.Ext(nameParts[1])\n\t\tescapedModuleVersion := strings.TrimSuffix(\n\t\t\tnameParts[1],\n\t\t\tnameExt,\n\t\t)\n\t\tswitch nameExt {\n\t\tcase \".info\":\n\t\t\tf.ops = fetchOpsDownloadInfo\n\t\t\tf.contentType = \"application/json; charset=utf-8\"\n\t\tcase \".mod\":\n\t\t\tf.ops = fetchOpsDownloadMod\n\t\t\tf.contentType = \"text/plain; charset=utf-8\"\n\t\tcase \".zip\":\n\t\t\tf.ops = fetchOpsDownloadZip\n\t\t\tf.contentType = \"application/zip\"\n\t\tcase \"\":\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"no file extension in filename %q\",\n\t\t\t\tescapedModuleVersion,\n\t\t\t)\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"unexpected extension %q\",\n\t\t\t\tnameExt,\n\t\t\t)\n\t\t}\n\n\t\tvar err error\n\t\tf.moduleVersion, err = module.UnescapeVersion(\n\t\t\tescapedModuleVersion,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif f.moduleVersion == \"latest\" {\n\t\t\treturn nil, errors.New(\"invalid version\")\n\t\t} else if !semver.IsValid(f.moduleVersion) {\n\t\t\tif f.ops == fetchOpsDownloadInfo {\n\t\t\t\tf.ops = fetchOpsResolve\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"unrecognized version\")\n\t\t\t}\n\t\t}\n\t}\n\n\tvar err error\n\tf.modulePath, err = module.UnescapePath(escapedModulePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tf.modAtVer = fmt.Sprint(f.modulePath, \"@\", f.moduleVersion)\n\tf.requiredToVerify = g.goBinEnvGOSUMDB != \"off\" &&\n\t\t!globsMatchPath(g.goBinEnvGONOSUMDB, f.modulePath)\n\n\treturn f, nil\n}", "func (sp *spider) init(ctx context.Context) {\n\tif sp.downloader == nil {\n\t\tsp.downloader = downloader.NewSimpleDownloader(10*time.Second, nil)\n\t}\n\tif sp.downloaderCoroutineNum < 1 {\n\t\tsp.downloaderCoroutineNum = 1\n\t}\n\tif sp.processorCoroutineNum < 1 {\n\t\tsp.processorCoroutineNum = 1\n\t}\n\tif sp.pipelines == nil {\n\t\tsp.pipelines = append(sp.pipelines, pipeline.NewConsolePipeline())\n\t}\n\tif sp.scheduler == nil {\n\t\tsp.scheduler = scheduler.NewMemScheduler(ctx, sp.wg)\n\t}\n\tif sp.maxDownloadRetryTime < 1 {\n\t\tsp.maxDownloadRetryTime = 3\n\t}\n\tfor _, request := range sp.startRequests {\n\t\tsp.scheduler.PushChan() <- request\n\t}\n\tsp.startRequests = nil //clear object\n}", "func (g *GoFlickr) newRequest(apiMethod string) ApiRequest {\n\n\treq := ApiRequest{\n\t\tMethodName: apiMethod,\n\t}\n\treq.addParam(\"api_key\", g.ApiKey)\n\treq.addParam(\"format\", \"json\")\n\treq.addParam(\"nojsoncallback\", \"1\")\n\treturn req\n\n}", "func (c *Config) client(httpClient *http.Client) *github.Client {\n\t{\n\t\t// Avoid modifying httpClient.\n\t\ttmp := *httpClient\n\t\ttmp.Transport = c.applyAppdash(tmp.Transport)\n\t\thttpClient = &tmp\n\t}\n\n\tg := github.NewClient(httpClient)\n\tif c.BaseURL != nil {\n\t\tg.BaseURL = c.BaseURL\n\t}\n\treturn g\n}", "func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {\n\tif !strings.HasSuffix(c.baseURL.Path, \"/\") {\n\t\treturn nil, fmt.Errorf(\"BaseURL must have a trailing slash, but %q does not\", c.baseURL)\n\t}\n\tu, err := c.baseURL.Parse(urlStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar buf io.ReadWriter\n\tif body != nil {\n\t\tbuf = new(bytes.Buffer)\n\t\terr := json.NewEncoder(buf).Encode(body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(method, u.String(), buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\treq.Header.Set(\"Accept\", \"application/json; charset=utf-8\")\n\treq.Header.Set( \"x-api-key\", c.opts.apiKey)\n\treq.Header.Set(\"Host\", \"openapi.etsy.com\")\n\treq.Header.Set(\"User-Agent\", c.UserAgent)\n\n\treturn req, nil\n}", "func (r *Reddit) Init() {\n\t// Get Reddit Client Credentials from the environment variables\n\tclientID := os.Getenv(\"REDDIT_CLIENT_ID\")\n\tclientSecret := os.Getenv(\"REDDIT_CLIENT_SECRET\")\n\n\tif clientID == \"\" || clientSecret == \"\" {\n\t\tlog.Fatalln(\"Reddit Client ID and Secret have not been set\")\n\t\treturn\n\t}\n\n\tr.ClientID = clientID\n\tr.ClientSecret = clientSecret\n\n\tr.UserAgent = \"MEME_API\"\n\n\taccessToken := r.GetAccessToken()\n\n\tif accessToken == \"\" {\n\t\tlog.Fatalln(\"Error while getting Access Token\")\n\t\treturn\n\t}\n\n\tr.AccessToken = accessToken\n}", "func (c *ChangeRequest) InitChangeRequest() error {\n\tif c.URL != \"\" {\n\t\tu, err := url.Parse(c.URL)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.Host = u.Hostname()\n\t\tc.Port = u.Port()\n\t}\n\treturn nil\n}", "func NewRequest(method, urlStr string, body io.Reader) (*Request, error) {\n\treq, err := http.NewRequest(method, urlStr, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Request{\n\t\t\treq, Retries, Timeout, backoff.NewExponentialBackOff()},\n\t\tnil\n}", "func NewGist(tok string) Gist {\n\tg := new(Gist)\n\n\t//g.ua = &http.Client{}\n\tg.Client = &http.Client{}\n\tg.token = tok\n\n\treturn *g\n}", "func (c *Client) NewRequest(method, apiPath string, body interface{}) (*http.Request, error) {\n loc, err := joinPaths(c.BaseURL, apiPath)\n if err != nil {\n return nil, err\n }\n\n buf := new(bytes.Buffer)\n if body != nil {\n err = json.NewEncoder(buf).Encode(body)\n if err != nil {\n return nil, err\n }\n }\n\n req, err := http.NewRequest(method, loc.String(), buf)\n if err != nil {\n return nil, err\n }\n\n req.Header.Add(\"Content-Type\", \"application/json\")\n req.Header.Add(\"Accept\", \"application/json, text/plain, */*\")\n req.Header.Add(\"User-Agent\", c.UserAgent)\n return req, nil\n}", "func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {\n\n\trel, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := c.BaseURL.ResolveReference(rel)\n\n\tvar buf io.ReadWriter\n\tif body != nil {\n\t\tbuf = new(bytes.Buffer)\n\t\terr := json.NewEncoder(buf).Encode(body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(method, u.String(), buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif body != nil {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\tif c.UserAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", c.UserAgent)\n\t}\n\treturn req, nil\n}", "func (c *Client) NewRequest(method, urlStr string, body io.Reader) (*http.Request, error) {\n\trel, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := c.BaseURL.ResolveReference(rel)\n\n\treq, err := http.NewRequest(method, u.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif c.UserAgent != \"\" {\n\t\treq.Header.Add(\"User-Agent\", c.UserAgent)\n\t}\n\treturn req, nil\n}", "func New(key string) *Api {\n\treturn &Api{&http.Client{}, key, \"https://newsapi.org/v2/\"}\n}", "func (c client) newRequest(ctx context.Context, method string, url string, body io.Reader) (*http.Request, error) {\n\treq, err := http.NewRequestWithContext(ctx, method, url, body)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to build request %w\", err)\n\t}\n\n\treturn req, nil\n}", "func New(perfGit *perfgit.Git, tracker progress.Tracker, shortcutStore shortcut.Store, dfBuilder dataframe.DataFrameBuilder, paramsProvider regression.ParamsetProvider) *Requests {\n\tret := &Requests{\n\t\tperfGit: perfGit,\n\t\tshortcutStore: shortcutStore,\n\t\tdfBuilder: dfBuilder,\n\t\ttracker: tracker,\n\t\tparamsProvier: paramsProvider,\n\t}\n\treturn ret\n}", "func newRequest(method, url string, body string) *http.Request {\n\treq, err := http.NewRequest(method, url, strings.NewReader(body))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-API-Token\", \"token1\")\n\treturn req\n}", "func (c *Client) NewRequest(ctx context.Context, method string, urlStr string, body interface{}) (*http.Request, error) {\n\trelURL, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tu := c.BaseURL.ResolveReference(relURL)\n\n\tvar buf io.ReadWriter\n\tif body != nil {\n\t\tbuf = new(bytes.Buffer)\n\t\terr = json.NewEncoder(buf).Encode(body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(method, u.String(), buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq = req.WithContext(ctx)\n\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"Bearer %s\", c.token))\n\n\tif c.UserAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", c.UserAgent)\n\t}\n\n\tif body != nil {\n\t\treq.Header.Set(\"Content-Type\", mediaTypeJSON)\n\t}\n\n\treturn req, err\n}", "func getGitHubLoginUrl(w http.ResponseWriter, r *http.Request) {\n\tloginUrl, err := github.LoginUrl()\n\thelpers.HandleError(err)\n\tresp := map[string]interface{}{\n\t\t\"data\": loginUrl,\n\t}\n\tapiResponse(resp, w)\n}", "func NewRequest(host string) *Request {\n\trequest := &Request{host, url.Values{}, http.Header{}, BasicAuth{}}\n\treturn request\n}", "func newJIRAHTTPClient(config cfg.Config) (*http.Client, error) {\n\tctx := context.Background()\n\n\toauthConfig, err := oauthConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttok, ok := jiraTokenFromConfig(config)\n\tif !ok {\n\t\ttok, err = jiraTokenFromWeb(oauthConfig)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfig.SetJIRAToken(tok)\n\t}\n\n\treturn oauthConfig.Client(ctx, tok), nil\n}", "func newTestGitHubClient() *Client {\n\tgclient := github.NewClient(nil)\n\tclient := Client{\n\t\tclient: gclient,\n\t}\n\treturn &client\n}", "func newClient(token string) *github.Client {\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: token},\n\t)\n\ttc := oauth2.NewClient(context.Background(), ts)\n\n\treturn github.NewClient(tc)\n}", "func newClientWithURL(url string, apiKey string, apiSecret string) (Client, error) {\n\treturn newClientWithURLs(apiKey, apiSecret, url, url, url, url)\n}" ]
[ "0.62665045", "0.6114478", "0.60820365", "0.60081553", "0.5948533", "0.57346517", "0.5724615", "0.56408477", "0.5497713", "0.54658604", "0.544195", "0.54246414", "0.54128045", "0.5398113", "0.53730345", "0.5361448", "0.5348309", "0.5343398", "0.5334841", "0.5331546", "0.5330763", "0.5319349", "0.5319349", "0.5311132", "0.52917576", "0.5288256", "0.5277177", "0.5256214", "0.5220784", "0.51947206", "0.5189931", "0.51783526", "0.5162721", "0.51584524", "0.51509213", "0.5142856", "0.51346874", "0.5130091", "0.51253235", "0.5125022", "0.5110533", "0.51087946", "0.51082385", "0.51039326", "0.5086509", "0.50861746", "0.5083395", "0.50800705", "0.50793207", "0.5076943", "0.50677073", "0.50674677", "0.5065097", "0.5060145", "0.5057306", "0.5054934", "0.50477034", "0.50450194", "0.50450194", "0.5042572", "0.5019912", "0.50194174", "0.5012324", "0.5011059", "0.5009012", "0.5004296", "0.49998796", "0.49980557", "0.49980158", "0.49961793", "0.49922425", "0.4987815", "0.49847397", "0.49815762", "0.49808258", "0.4979515", "0.49754986", "0.49740124", "0.49730444", "0.49708143", "0.49570945", "0.49523106", "0.49502045", "0.49441025", "0.49429837", "0.49420393", "0.49415776", "0.49403048", "0.49400577", "0.49364674", "0.49356955", "0.4935016", "0.49328333", "0.4925726", "0.49231794", "0.49159542", "0.49152055", "0.4914697", "0.4914148", "0.49113744" ]
0.654776
0
Default ... Get default branch of a GitHub issue
func (g *GitHubImpl) Default() (defUrl string, err error) { URL := fmt.Sprintf(g.URLNoEsc(g.pluginWebURL.repo), g.org, g.repo) req, _ := http.NewRequest("GET", URL, nil) q := req.URL.Query() q.Add("access_token", g.token) req.URL.RawQuery = q.Encode() body, err := NewPWRequest().Do(req) if err != nil { return "", err } re := Repo{} if err = json.Unmarshal(body, &re); err != nil { return "", err } return re.DefaultBranch, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getDefaultBranch(client *gitlab.Client, projectID int) (*gitlab.Branch, error) {\n\tproject, _, err := client.Projects.GetProject(projectID, &gitlab.GetProjectOptions{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fetching project failed : %v\", err)\n\t}\n\n\tdefaultBranch := project.DefaultBranch\n\n\t//\tfirst try with the possible option\n\tbranch, _, err := client.Branches.GetBranch(projectID, defaultBranch)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fetching default branch failed : %v\", err)\n\t}\n\n\treturn branch, nil\n}", "func GetDefaultBranch(ctx context.Context, repo api.RepoName) (refName string, commit api.CommitID, err error) {\n\tif Mocks.GetDefaultBranch != nil {\n\t\treturn Mocks.GetDefaultBranch(repo)\n\t}\n\n\trefBytes, _, exitCode, err := ExecSafe(ctx, repo, []string{\"symbolic-ref\", \"HEAD\"})\n\trefName = string(bytes.TrimSpace(refBytes))\n\n\tif err == nil && exitCode == 0 {\n\t\t// Check that our repo is not empty\n\t\tcommit, err = ResolveRevision(ctx, repo, \"HEAD\", ResolveRevisionOptions{NoEnsureRevision: true})\n\t}\n\n\t// If we fail to get the default branch due to cloning or being empty, we return nothing.\n\tif err != nil {\n\t\tif gitdomain.IsCloneInProgress(err) || errors.HasType(err, &gitdomain.RevisionNotFoundError{}) {\n\t\t\treturn \"\", \"\", nil\n\t\t}\n\t\treturn \"\", \"\", err\n\t}\n\n\treturn refName, commit, nil\n}", "func (p *Project) GetDefaultBranch() (string, error) {\n\tcmd := exec.Command(\"git\", \"remote\", \"show\", \"origin\")\n\tcmd.Dir = workdir.ProjectDir(p.Name)\n\treader, err := stdoutStderrReader(cmd, nil)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(reader)\n\tstdout := buf.String()\n\tre := regexp.MustCompile(\"HEAD branch: (\\\\S+)\")\n\tgroup := re.FindStringSubmatch(stdout)\n\n\treturn group[1], nil\n}", "func newDefaultBranchResult(ctx context.Context, ghc ghGraphQLClient, repoURL string) (repository.Branch, error) {\n\tformattedURI, err := createNewGitHubV4URI(repoURL)\n\tif err != nil {\n\t\treturn repository.Branch{}, err\n\t}\n\tqueryResult := new(defaultBranchQuery)\n\tallDefaultBranchCommits := make([]commit, 0)\n\tdefaultBranchInfoVariables := map[string]interface{}{\n\t\t\"url\": githubv4.URI(*formattedURI),\n\t\t\"defaultBranchCommitCursor\": (*githubv4.String)(nil),\n\t}\n\n\terr = paginationQuery(ctx, ghc, queryResult, defaultBranchInfoVariables, queryPageLimit, func(v interface{}) (bool, error) {\n\t\tdbq, ok := v.(*defaultBranchQuery)\n\t\tif !ok {\n\t\t\treturn false, newTypeMismatchError(\"defaultBranchQuery\", dbq)\n\t\t}\n\t\tresourceType := v.(*defaultBranchQuery).Resource.Typename\n\t\tif resourceType != repositoryType {\n\t\t\treturn false, repository.NewTypeMismatchError(repositoryType, resourceType)\n\t\t}\n\t\trepo := dbq.Resource.Repository\n\n\t\tallDefaultBranchCommits = append(allDefaultBranchCommits, repo.DefaultBranchRef.Target.Commit.History.Nodes...)\n\t\thasMoreResults := repo.DefaultBranchRef.Target.Commit.History.PageInfo.HasNextPage\n\t\tdefaultBranchInfoVariables[\"defaultBranchCommitCursor\"] = githubv4.NewString(repo.DefaultBranchRef.Target.Commit.History.PageInfo.EndCursor)\n\t\treturn hasMoreResults, nil\n\t})\n\tif err != nil {\n\t\treturn repository.Branch{}, err\n\t}\n\n\tdefaultBranchName := queryResult.Resource.Repository.DefaultBranchRef.Name\n\tcommits := make([]repository.CommitRef, 0)\n\tfor _, commit := range allDefaultBranchCommits {\n\t\trepoCommit := repository.NewCommitRef(commit.URL)\n\t\tcommits = append(commits, repoCommit)\n\t}\n\treturn repository.NewBranch(defaultBranchName, commits), nil\n}", "func (ghc *client) GetDefaultBranch(ctx context.Context, commitURI string) (repository.DefaultBranch, error) {\n\tdefaultBranchResult, err := newDefaultBranchResult(ctx, ghc.ghClient, commitURI)\n\tif err != nil {\n\t\treturn repository.DefaultBranch{}, fmt.Errorf(\"GetDefaultBranch query could not be completed. Error: %s\", err)\n\t}\n\treturn defaultBranchResult, nil\n}", "func (gr GitRepo) GetDefaultBranch() string {\n\treturn gr.DefaultBranch\n}", "func (r *Repository) GetDefaultBranch() string {\n\tif r == nil || r.DefaultBranch == nil {\n\t\treturn \"\"\n\t}\n\treturn *r.DefaultBranch\n}", "func (v Repository) DefaultTrackingBranch() string {\n\tif v.Revision != \"\" && !common.IsImmutable(v.Revision) {\n\t\treturn v.Revision\n\t}\n\tif v.DestBranch != \"\" && !common.IsImmutable(v.DestBranch) {\n\t\treturn v.DestBranch\n\t}\n\tif v.Upstream != \"\" && !common.IsImmutable(v.Upstream) {\n\t\treturn v.Upstream\n\t}\n\tif v.ManifestDefaultRevision != \"\" && !common.IsImmutable(v.ManifestDefaultRevision) {\n\t\treturn v.ManifestDefaultRevision\n\t}\n\treturn \"\"\n}", "func (p *PushEventRepository) GetDefaultBranch() string {\n\tif p == nil || p.DefaultBranch == nil {\n\t\treturn \"\"\n\t}\n\treturn *p.DefaultBranch\n}", "func GetGitRepositoryDefaultBranch(url string) (string, error) {\n\terr := C.git_libgit2_init()\n\tif err < 0 {\n\t\treturn \"\", errors.New(\"failed to initialize libgit2\")\n\t}\n\tvar odb *C.git_odb\n\terr = C.git_odb_new(&odb)\n\tif err != 0 {\n\t\treturn \"\", errors.New(\"failed to create git_odb\")\n\t}\n\tvar repo *C.git_repository\n\terr = C.git_repository_wrap_odb(&repo, odb)\n\tif err != 0 {\n\t\treturn \"\", errors.New(\"failed to wrap odb into repository\")\n\t}\n\tvar remote *C.git_remote\n\terr = C.git_remote_create_anonymous(&remote, repo, C.CString(url))\n\tif err != 0 {\n\t\treturn \"\", errors.New(\"failed to create anonymous remote\")\n\t}\n\terr = C.git_remote_connect(remote, C.GIT_DIRECTION_FETCH, nil, nil, nil)\n\tif err != 0 {\n\t\treturn \"\", errors.New(\"failed to connect to remote (fetch)\")\n\t}\n\tvar remote_heads **C.git_remote_head\n\tvar remote_heads_size C.ulong\n\terr = C.git_remote_ls(&remote_heads, &remote_heads_size, remote)\n\tif err != 0 {\n\t\treturn \"\", errors.New(\"failed to list remote heads\")\n\t}\n\tvar remote_heads2 []*C.git_remote_head\n\tsh := (*reflect.SliceHeader)(unsafe.Pointer(&remote_heads2))\n\tsh.Data = uintptr(unsafe.Pointer(remote_heads))\n\tsh.Len = int(remote_heads_size)\n\tsh.Cap = int(remote_heads_size)\n\tfound := \"\"\n\tfor _, remote_head := range remote_heads2 {\n\t\tif remote_head.symref_target != nil {\n\t\t\t// s := C.GoString(C.git_oid_tostr_s(&remote_head.oid))\n\t\t\th := C.GoString(remote_head.name)\n\t\t\tif h != \"HEAD\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsr := C.GoString(remote_head.symref_target)\n\t\t\tsr = strings.TrimPrefix(sr, \"refs/heads/\")\n\t\t\tlog.Printf(\"[%s] Found default branch name = %s\\n\", h, sr)\n\t\t\tfound = sr\n\t\t}\n\t}\n\tC.git_remote_free(remote)\n\tC.git_repository_free(repo)\n\tC.git_odb_free(odb)\n\tC.git_libgit2_shutdown()\n\n\treturn found, nil\n}", "func GetDefaultBranch(branches []VCSBranch) VCSBranch {\n\tfor _, branch := range branches {\n\t\tif branch.Default {\n\t\t\treturn branch\n\t\t}\n\t}\n\treturn VCSBranch{}\n}", "func GetDefaultBranchName(dbOwner, dbFolder, dbName string) (branchName string, err error) {\n\tdbQuery := `\n\t\tSELECT db.default_branch\n\t\tFROM sqlite_databases AS db\n\t\tWHERE db.user_id = (\n\t\t\t\tSELECT user_id\n\t\t\t\tFROM users\n\t\t\t\tWHERE lower(user_name) = lower($1)\n\t\t\t)\n\t\t\tAND db.folder = $2\n\t\t\tAND db.db_name = $3\n\t\t\tAND db.is_deleted = false`\n\tvar b pgx.NullString\n\terr = pdb.QueryRow(dbQuery, dbOwner, dbFolder, dbName).Scan(&b)\n\tif err != nil {\n\t\tif err != pgx.ErrNoRows {\n\t\t\tlog.Printf(\"Error when retrieving default branch name for database '%s%s%s': %v\\n\", dbOwner,\n\t\t\t\tdbFolder, dbName, err)\n\t\t} else {\n\t\t\tlog.Printf(\"No default branch name exists for database '%s%s%s'. This shouldn't happen\\n\", dbOwner,\n\t\t\t\tdbFolder, dbName)\n\t\t}\n\t\treturn\n\t}\n\tif b.Valid {\n\t\tbranchName = b.String\n\t}\n\treturn\n}", "func refFromCtx(ctx context.Context) string {\n\treturn DefaultBranchName\n}", "func refFromCtx(ctx context.Context) string {\n\treturn depot.DefaultBranchName\n}", "func (v GithubVCS) GetFileFromDefaultBranch(ctx context.Context, path string, runinfo *RunInfo) (string, error) {\n\trunInfoOnMain := &RunInfo{}\n\truninfo.DeepCopyInto(runInfoOnMain)\n\trunInfoOnMain.BaseBranch = runInfoOnMain.DefaultBranch\n\n\ttektonyaml, err := v.GetFileInsideRepo(ctx, path, true, runInfoOnMain)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"cannot find %s inside the %s branch: %w\", path, runInfoOnMain.BaseBranch, err)\n\t}\n\treturn tektonyaml, err\n}", "func (g *github) GetBranchName() string { return g.branchName }", "func (novis *Novis) GetBranch(name string) *Branch {\n\treturn novis.Get(name)\n}", "func (g *GitUtil) GetBranch() (string, error) {\n\tref, err := g.Repository.Head()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif !ref.Name().IsBranch() {\n\t\tbranches, err := g.Repository.Branches()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tvar currentBranch string\n\t\tfound := branches.ForEach(func(p *plumbing.Reference) error {\n\n\t\t\tif p.Name().IsBranch() && p.Name().Short() != \"origin\" {\n\t\t\t\tcurrentBranch = p.Name().Short()\n\t\t\t\treturn fmt.Errorf(\"break\")\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\n\t\tif found != nil {\n\t\t\tlog.Debugf(\"Found branch from HEAD %s\", currentBranch)\n\t\t\treturn currentBranch, nil\n\t\t}\n\n\t\treturn \"\", fmt.Errorf(\"no branch found, found %s, please checkout a branch (git checkout -b <BRANCH>)\", ref.Name().String())\n\t}\n\tlog.Debugf(\"Found branch %s\", ref.Name().Short())\n\treturn ref.Name().Short(), nil\n}", "func GetBranch(name string) *Branch {\n\treturn novis.Get(name)\n}", "func GetDefaultSource(ps v1.GitLikeProjectSource) (remoteName string, remoteURL string, revision string, err error) {\n\t// get git checkout information\n\t// if there are multiple remotes we are ignoring them, as we don't need to setup git repository as it is defined here,\n\t// the only thing that we need is to download the content\n\n\tif ps.CheckoutFrom != nil && ps.CheckoutFrom.Revision != \"\" {\n\t\trevision = ps.CheckoutFrom.Revision\n\t}\n\tif len(ps.Remotes) > 1 {\n\t\tif ps.CheckoutFrom == nil {\n\t\t\terr = fmt.Errorf(\"there are multiple git remotes but no checkoutFrom information\")\n\t\t\treturn \"\", \"\", \"\", err\n\t\t}\n\t\tremoteName = ps.CheckoutFrom.Remote\n\t\tif val, ok := ps.Remotes[remoteName]; ok {\n\t\t\tremoteURL = val\n\t\t} else {\n\t\t\terr = fmt.Errorf(\"checkoutFrom.Remote is not defined in Remotes\")\n\t\t\treturn \"\", \"\", \"\", err\n\n\t\t}\n\t} else {\n\t\t// there is only one remote, using range to get it as there are not indexes\n\t\tfor name, url := range ps.Remotes {\n\t\t\tremoteName = name\n\t\t\tremoteURL = url\n\t\t}\n\n\t}\n\n\treturn remoteName, remoteURL, revision, err\n\n}", "func getRef() (ref *github.Reference, err error) {\n\tif ref, _, err = client.Git.GetRef(ctx, *data.sourceOwner, *data.sourceRepo, \"refs/heads/\"+*data.commitBranch); err == nil {\n\t\treturn ref, nil\n\t}\n\n\t// We consider that an error means the branch has not been found and needs to\n\t// be created.\n\tif *data.commitBranch == *data.baseBranch {\n\t\treturn nil, errors.New(\"The commit branch does not exist but `-base-branch` is the same as `-commit-branch`\")\n\t}\n\n\tif *data.baseBranch == \"\" {\n\t\treturn nil, errors.New(\"The `-base-branch` should not be set to an empty string when the branch specified by `-commit-branch` does not exists\")\n\t}\n\n\tvar baseRef *github.Reference\n\tif baseRef, _, err = client.Git.GetRef(ctx, *data.sourceOwner, *data.sourceRepo, \"refs/heads/\"+*data.baseBranch); err != nil {\n\t\treturn nil, err\n\t}\n\tnewRef := &github.Reference{Ref: github.String(\"refs/heads/\" + *data.commitBranch), Object: &github.GitObject{SHA: baseRef.Object.SHA}}\n\tref, _, err = client.Git.CreateRef(ctx, *data.sourceOwner, *data.sourceRepo, newRef)\n\treturn ref, err\n}", "func DefaultCommit(dbOwner, dbFolder, dbName string) (string, error) {\n\t// If no commit ID was supplied, we retrieve the latest commit ID from the default branch\n\tdbQuery := `\n\t\tSELECT branch_heads->default_branch->'commit' AS commit_id\n\t\tFROM sqlite_databases\n\t\tWHERE user_id = (\n\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)\n\t\t\tAND folder = $2\n\t\t\tAND db_name = $3\n\t\t\tAND is_deleted = false`\n\tvar commitID string\n\terr := pdb.QueryRow(dbQuery, dbOwner, dbFolder, dbName).Scan(&commitID)\n\tif err != nil {\n\t\tlog.Printf(\"Error when retrieving head commit ID of default branch: %v\\n\", err.Error())\n\t\treturn \"\", errors.New(\"Internal error when looking up database details\")\n\t}\n\treturn commitID, nil\n}", "func (st *buildStatus) branch() string {\n\tif st.SubRev != \"\" {\n\t\treturn st.SubRevBranch\n\t}\n\treturn st.RevBranch\n}", "func main() {\n\tvar gitPath = \"/home/pi/project/test\"\n\trepo, err := gogit.PlainOpen(gitPath)\n\tb, e := repo.Branch(\"home\")\n\tfmt.Println(b, e)\n\tpanicError(err)\n\tbranches, err := repo.Branches()\n\tpanicError(err)\n\t//fmt.Println(branches)\n\tbranches.ForEach(func(ref *plumbing.Reference) error {\n\t\tfmt.Println(ref)\n\t\treturn nil\n\t})\n}", "func SetDefaultBranch(ctx context.Context, ownerName, repoName, branch string) ResponseExtra {\n\treqURL := setting.LocalURL + fmt.Sprintf(\"api/internal/hook/set-default-branch/%s/%s/%s\",\n\t\turl.PathEscape(ownerName),\n\t\turl.PathEscape(repoName),\n\t\turl.PathEscape(branch),\n\t)\n\treq := newInternalRequest(ctx, reqURL, \"POST\")\n\t_, extra := requestJSONResp(req, &responseText{})\n\treturn extra\n}", "func (r *Repo) BranchRef() string {\n\treturn fmt.Sprintf(\"refs/heads/%s\", r.Branch)\n}", "func GetCurrentBranch() string {\n\tcmd := exec.Command(\"git\", \"branch\")\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out\n\tcmd.Run()\n\tlines := strings.Split(out.String(), \"\\n\")\n\tfor _, line := range lines {\n\t\tif strings.Contains(line, \"*\") {\n\t\t\tbranch := strings.Replace(line, \"*\", \"\", -1)\n\t\t\tbranch = strings.TrimSpace(branch)\n\t\t\treturn branch\n\t\t}\n\t}\n\treturn \"\"\n}", "func (o TriggerGithubPullRequestPtrOutput) Branch() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TriggerGithubPullRequest) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Branch\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *MockRepoClient) GetDefaultBranch() (*clients.BranchRef, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetDefaultBranch\")\n\tret0, _ := ret[0].(*clients.BranchRef)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func Branch() string {\n\treturn run.Capture(\"git rev-parse --abbrev-ref HEAD\")\n}", "func CurrentBranch(ctx context.Context, dEnv *env.DoltEnv, replay ReplayCommitFn, nerf NeedsRebaseFn) error {\n\theadRef, err := dEnv.RepoStateReader().CWBHeadRef()\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn rebaseRefs(ctx, dEnv.DbData(), replay, nerf, headRef)\n}", "func (o TriggerGithubPullRequestOutput) Branch() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TriggerGithubPullRequest) string { return v.Branch }).(pulumi.StringOutput)\n}", "func GetMatchingBranch(input string) (string, error) {\n\tvar foundBranches []string\n\n\tloweredInput := strings.ToLower(input)\n\tfor _, branch := range GetBranches() {\n\t\tloweredBranch := strings.ToLower(branch)\n\t\tif loweredBranch == loweredInput {\n\t\t\treturn input, nil\n\t\t} else if strings.Contains(loweredBranch, loweredInput) {\n\t\t\tfoundBranches = append(foundBranches, branch)\n\t\t}\n\t}\n\n\tif len(foundBranches) > 1 {\n\t\treturn \"\", fmt.Errorf(\"multiple branches found: %s\", strings.Join(foundBranches, \", \"))\n\t} else if len(foundBranches) == 1 {\n\t\treturn foundBranches[0], nil\n\t}\n\n\tlog.Errorf(\"Branch not found: %s. We have %d known branches\", input, len(branches))\n\n\t// branch not found in local list, but maybe it was created recently -> let's try it if jenkins accept it\n\treturn input, nil\n}", "func gitBranchName() string {\n\t// branch name variable set by Github Actions\n\tif branch, isset := os.LookupEnv(\"GITHUB_HEAD_REF\"); isset && branch != \"\" {\n\t\treturn \"origin/\" + branch\n\t}\n\tif branch, isset := os.LookupEnv(\"GITHUB_REF\"); isset && branch != \"\" {\n\t\treturn \"origin/\" + strings.TrimPrefix(branch, \"refs/heads/\")\n\t}\n\tbranch := getCmdOutput(\"git rev-parse --abbrev-ref HEAD\")\n\treturn branch\n}", "func (s *splicer) branch(name string) error {\n\treturn s.gitCall(\"checkout\", \"-B\", name, \"master\")\n}", "func GetBranchFromRef(ref string) string {\n\tparts := strings.Split(ref, \"/\")\n\treturn strings.Join(parts[2:], \"/\")\n}", "func (c *config) branch(name string) (output string, err error) {\n\tlog.Printf(\"creating branch: %v\", name)\n\n\tdefaultCommand := []string{\"branch\", name}\n\n\treturn c.command(defaultCommand...)\n\n}", "func (p *Project) GetCachedDefaultBranch() (string, error) {\n\tcachedDefaultBranch := cache.DefaultBranch.Load(p.Name)\n\n\tif cachedDefaultBranch != \"\" {\n\t\t// returns cached default branch\n\t\treturn cachedDefaultBranch, nil\n\t}\n\n\tdefaultBranch, err := p.GetDefaultBranch()\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcache.DefaultBranch.Store(p.Name, defaultBranch)\n\n\treturn defaultBranch, nil\n}", "func switchBranch(repo *gogit.Repository, pushBranch string) error {\n\tlocalBranch := plumbing.NewBranchReferenceName(pushBranch)\n\n\t// is the branch already present?\n\t_, err := repo.Reference(localBranch, false)\n\tswitch {\n\tcase err == plumbing.ErrReferenceNotFound:\n\t\t// make a new branch, starting at HEAD\n\t\thead, err := repo.Head()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbranchRef := plumbing.NewHashReference(localBranch, head.Hash())\n\t\tif err = repo.Storer.SetReference(branchRef); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase err != nil:\n\t\treturn err\n\tdefault:\n\t\t// local branch found, great\n\t\tbreak\n\t}\n\n\ttree, err := repo.Worktree()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn tree.Checkout(&gogit.CheckoutOptions{\n\t\tBranch: localBranch,\n\t})\n}", "func GetBranch(ctx *context.APIContext) {\n\t// swagger:operation GET /repos/{owner}/{repo}/branches/{branch} repository repoGetBranch\n\t// ---\n\t// summary: Retrieve a specific branch from a repository, including its effective branch protection\n\t// produces:\n\t// - application/json\n\t// parameters:\n\t// - name: owner\n\t// in: path\n\t// description: owner of the repo\n\t// type: string\n\t// required: true\n\t// - name: repo\n\t// in: path\n\t// description: name of the repo\n\t// type: string\n\t// required: true\n\t// - name: branch\n\t// in: path\n\t// description: branch to get\n\t// type: string\n\t// required: true\n\t// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/Branch\"\n\t// \"404\":\n\t// \"$ref\": \"#/responses/notFound\"\n\n\tbranchName := ctx.Params(\"*\")\n\n\tbranch, err := ctx.Repo.GitRepo.GetBranch(branchName)\n\tif err != nil {\n\t\tif git.IsErrBranchNotExist(err) {\n\t\t\tctx.NotFound(err)\n\t\t} else {\n\t\t\tctx.Error(http.StatusInternalServerError, \"GetBranch\", err)\n\t\t}\n\t\treturn\n\t}\n\n\tc, err := branch.GetCommit()\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetCommit\", err)\n\t\treturn\n\t}\n\n\tbranchProtection, err := git_model.GetFirstMatchProtectedBranchRule(ctx, ctx.Repo.Repository.ID, branchName)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetBranchProtection\", err)\n\t\treturn\n\t}\n\n\tbr, err := convert.ToBranch(ctx, ctx.Repo.Repository, branch.Name, c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin())\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"convert.ToBranch\", err)\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, br)\n}", "func DetermineGitHubRefType(owner string, repo string, unknownRef string) (*PossiblyStableTag, *Branch, bool, error) {\n\tgithubClient := githubapi.NewGitHubClient()\n\ttagResponse, githubResponse, err := githubClient.Git.GetRef(context.Background(), owner, repo, fmt.Sprintf(\"tags/%s\", unknownRef))\n\tif err != nil {\n\t\tif githubResponse.Response.StatusCode != 404 && err.Error() != \"multiple matches found for this ref\" {\n\t\t\treturn nil, nil, false, errors.Wrapf(err, \"failed to get tag ref for owner %s, repo %s, tag %s\", owner, repo, unknownRef)\n\t\t}\n\t}\n\n\tif tagResponse != nil {\n\t\treturn &PossiblyStableTag{\n\t\t\tTagName: unknownRef,\n\t\t\tCommitSHA: tagResponse.Object.GetSHA()[0:7],\n\t\t}, nil, false, nil\n\t}\n\n\tbranchResponse, githubResponse, err := githubClient.Git.GetRef(context.Background(), owner, repo, fmt.Sprintf(\"heads/%s\", unknownRef))\n\tif err != nil {\n\t\tif githubResponse.Response.StatusCode != 404 {\n\t\t\treturn nil, nil, false, errors.Wrap(err, \"failed to get head ref\")\n\t\t}\n\t}\n\n\tif branchResponse != nil {\n\t\treturn nil, &Branch{\n\t\t\tBranchName: unknownRef,\n\t\t\tCommitSHA: branchResponse.Object.GetSHA()[0:7],\n\t\t}, false, nil\n\t}\n\n\tcommitResponse, githubResponse, err := githubClient.Repositories.GetCommit(context.Background(), owner, repo, unknownRef)\n\tif err != nil {\n\t\tif githubResponse.Response.StatusCode != 404 {\n\t\t\treturn nil, nil, false, errors.Wrap(err, \"failed to get commit ref\")\n\t\t}\n\t}\n\n\tif commitResponse != nil {\n\t\treturn nil, nil, true, nil\n\t}\n\n\treturn nil, nil, false, nil\n}", "func getModuleBranch(moduleName string, proj *model.Project) (string, error) {\n\t// find the module of the patch\n\tfor _, module := range proj.Modules {\n\t\tif module.Name == moduleName {\n\t\t\treturn module.Branch, nil\n\t\t}\n\t}\n\treturn \"\", errors.Errorf(\"module '%s' unknown or not found\", moduleName)\n}", "func (h *branchesService) determineCommitBranch(\n\trepo *Repo, c *Commit, branchesChildren map[string][]string,\n) *Branch {\n\t// At this point, if a commit c has possible branches in c.Branches[], they will all be\n\t// live git branches. However, on return the c.Branches[] may contain deleted or ambiguous\n\t// branches as well\n\n\tif branch := h.hasOnlyOneBranch(c); branch != nil {\n\t\t// Commit only has one branch, it must have been an actual branch tip originally, use that\n\t\treturn branch\n\t} else if branch := h.isLocalRemoteBranch(c); branch != nil {\n\t\t// Commit has only local and its remote branch, prefer remote remote branch\n\t\treturn branch\n\t} else if branch := h.hasParentChildSetBranch(c, branchesChildren); branch != nil {\n\t\t// The commit has several possible branches, and one is set as parent of the others by the user\n\t\treturn branch\n\t} else if branch := h.hasChildrenPriorityBranch(c, branchesChildren); branch != nil {\n\t\t// The commit has several possible branches, and one of the children's branches is set as the\n\t\t// the parent branch of the other children's branches\n\t\treturn branch\n\t} else if branch := h.isSameChildrenBranches(c); branch != nil {\n\t\t// Commit has no branch but has 2 children with same branch\n\t\treturn branch\n\t} else if branch := h.isMergedDeletedRemoteBranchTip(repo, c); branch != nil {\n\t\t// Commit has no branch and no children, but has a merge child, the commit is a tip\n\t\t// of a deleted branch. It might be a deleted remote branch. Lets try determine branch name\n\t\t// based on merge child's subject or use a generic branch name based on commit id\n\t\treturn branch\n\t} else if branch := h.isMergedDeletedBranchTip(repo, c); branch != nil {\n\t\t// Commit has no branch and no children, but has a merge child, the commit is a tip\n\t\t// of a deleted remote branch, lets try determine branch name based on merge child's\n\t\t// subject or use a generic branch name based on commit id\n\t\treturn branch\n\t} else if branch := h.hasOneChildInDeletedBranch(c); branch != nil {\n\t\t// Commit is middle commit in a deleted branch with only one child above, use same branch\n\t\treturn branch\n\t} else if branch := h.hasOneChildWithLikelyBranch(c); branch != nil {\n\t\t// Commit multiple possible git branches but has one child, which has a likely known branch, use same branch\n\t\treturn branch\n\t} else if branch := h.hasMainBranch(c); branch != nil {\n\t\t// Commit, has several possible branches, and one is in the priority list, e.g. main, master, ...\n\t\treturn branch\n\t} else if branch := h.hasBranchNameInSubject(repo, c); branch != nil {\n\t\t// A branch name could be parsed form the commit subject or a child subject.\n\t\t// The commit will be set to that branch and also if above (first child) commits have\n\t\t// ambiguous branches, the will be reset to same branch as well. This will 'repair' branch\n\t\t// when a parsable commit subjects are encountered.\n\t\treturn branch\n\t} else if branch := h.hasOnlyOneChild(c); branch != nil {\n\t\t// Commit has one child commit and not merge commits, reuse that child commit branch\n\t\treturn branch\n\t} else if branch := h.isChildAmbiguousBranch(c); branch != nil {\n\t\t// one of the commit children is a ambiguous branch, reuse same ambiguous branch\n\t\treturn branch\n\t}\n\n\t// Commit, has several possible branches, and we could not determine which branch is best,\n\t// create a new ambiguous branch. Later commits may fix this by parsing subjects of later\n\t// commits, or the user has to manually set the branch.\n\treturn repo.addAmbiguousBranch(c)\n}", "func Get(name string) *Branch {\n\treturn novis.Get(name)\n}", "func (c *GitHubClient) SetDefaultBranch(ctx context.Context, owner, repo, defaultBranchName string) error {\n\tr := &github.Repository{\n\t\tDefaultBranch: github.String(defaultBranchName),\n\t}\n\trepositoryResp, _, err := c.Repositories.Edit(ctx, owner, repo, r)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"setting repo to default branch %v: %w\", defaultBranchName, err)\n\t}\n\tlog.Info().Interface(\"repositoryResponse\", repositoryResp).Msg(\"success updating default push branch\")\n\treturn nil\n}", "func getBranch(urlstr string, branch string, dst string) {\n\tlog.Debugf(\"Getting branch %s\", branch)\n\tif sh.DirExists(dst) {\n\t\tlog.Infof(\"Folder exists, skipping cloning %s\", dst)\n\t\tlog.Infof(\"Checking out %s\", branch)\n\t\tif oldPwd := sh.Pwd(); !(oldPwd == dst) {\n\t\t\tsh.Cd(dst)\n\t\t\tsh.SetE(exec.Command(\"git\", \"checkout\", branch))\n\t\t\tsh.Cd(oldPwd)\n\t\t} else {\n\t\t\tsh.SetE(exec.Command(\"git\", \"checkout\", branch))\n\t\t}\n\t} else {\n\t\tlog.Infof(\"Cloning into %s\", dst)\n\t\tcloneCmd := []string{\n\t\t\t// don't verify the ssl certificate (I've run into trouble with it)\n\t\t\t\"-c\", \"http.sslVerify=false\",\n\t\t\t\"clone\", urlstr, dst,\n\t\t\t// only clone this branch, with two commits of history\n\t\t\t\"--branch=\" + branch, \"--single-branch\",\n\t\t\t\"--depth\", \"2\",\n\t\t}\n\t\tsh.SetE(exec.Command(\"git\", cloneCmd...))\n\t}\n\tlog.Debugf(\"Done getting branch %s\", branch)\n}", "func (b *BitBucketClient) GetBranch(workspace string, repositorySlug string, branchName string) (dto.BitBucketResponseBranchCreate, error) {\n\tlog.Logger().StartMessage(\"Get branch\")\n\tif err := b.beforeRequest(); err != nil {\n\t\tlog.Logger().FinishMessage(\"Get branch\")\n\t\treturn dto.BitBucketResponseBranchCreate{}, err\n\t}\n\n\tb.client.SetBaseURL(DefaultBitBucketBaseAPIUrl)\n\n\tendpoint := fmt.Sprintf(\"/repositories/%s/%s/refs/branches/%s\", workspace, repositorySlug, branchName)\n\tresponse, statusCode, err := b.client.Get(endpoint, map[string]string{})\n\tif err != nil {\n\t\tlog.Logger().FinishMessage(\"Get branch\")\n\t\treturn dto.BitBucketResponseBranchCreate{}, err\n\t}\n\n\tif statusCode == http.StatusNotFound {\n\t\tlog.Logger().FinishMessage(\"Get branch\")\n\t\treturn dto.BitBucketResponseBranchCreate{}, errors.New(\"this branch doesn't exist. \")\n\t}\n\n\tif statusCode == http.StatusForbidden {\n\t\tlog.Logger().FinishMessage(\"Get branch\")\n\t\treturn dto.BitBucketResponseBranchCreate{}, errors.New(\"action is not permitted. \")\n\t}\n\n\tresponseObject := dto.BitBucketResponseBranchCreate{}\n\terr = json.Unmarshal(response, &responseObject)\n\tif err != nil {\n\t\tlog.Logger().AddError(err).Msg(\"Error during response unmarshal\")\n\t\tlog.Logger().FinishMessage(\"Get branch\")\n\t\treturn dto.BitBucketResponseBranchCreate{}, err\n\t}\n\n\tlog.Logger().FinishMessage(\"Get branch\")\n\treturn responseObject, nil\n}", "func (g GithubClient) GetBranch(ctx context.Context, owner, repo, branch string) (*github.Branch, *github.Response, error) {\n\treturn g.client.Repositories.GetBranch(ctx, owner, repo, branch)\n}", "func (self *Repository) Branch(path string) error { return nil }", "func (r *Repo) GetBranchIfTracked(refName string) *Branch {\n\tbranchName := strings.TrimPrefix(refName, \"origin/\")\n\tfor name, branch := range r.Branches {\n\t\tif name == branchName {\n\t\t\treturn branch\n\t\t}\n\t}\n\treturn nil\n}", "func GetBranch(repo *models.Repository, branch string) (*git.Branch, error) {\n\tif len(branch) == 0 {\n\t\treturn nil, fmt.Errorf(\"GetBranch: empty string for branch\")\n\t}\n\tgitRepo, err := git.OpenRepository(repo.RepoPath())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer gitRepo.Close()\n\n\treturn gitRepo.GetBranch(branch)\n}", "func (m *MockRepoClient) GetDefaultBranchName() (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetDefaultBranchName\")\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetGitBranch(dir string) (string, error) {\n\treturn runGit(dir, \"rev-parse\", \"--abbrev-ref\", \"HEAD\")\n}", "func branchGit() {\n\n}", "func (o LookupBranchResultOutput) Default() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v LookupBranchResult) bool { return v.Default }).(pulumi.BoolOutput)\n}", "func defaultGithubClient() *github.Client {\n\ttoken, ok := os.LookupEnv(\"GITHUB_TOKEN\")\n\tif ok {\n\t\tctx := context.Background()\n\t\tts := oauth2.StaticTokenSource(\n\t\t\t&oauth2.Token{AccessToken: token},\n\t\t)\n\t\ttc := oauth2.NewClient(ctx, ts)\n\t\treturn github.NewClient(tc)\n\t}\n\treturn github.NewClient(nil)\n}", "func GetBranch() string {\n\tv := Map[\"branch\"]\n\treturn v\n}", "func (o TriggerGithubPushPtrOutput) Branch() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TriggerGithubPush) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Branch\n\t}).(pulumi.StringPtrOutput)\n}", "func (u *BookUseCases) GetDefault(user domain.AppUser) (domain.Book, error) {\n\treturn u.BookRepository.GetDefault(user)\n}", "func CurrentBranch() (string, error) {\n\tresult, err := exec.Command(\"git\", \"symbolic-ref\", \"--short\", \"HEAD\").Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.TrimSpace(string(result)), nil\n}", "func GetDefaultLevel(bdg *v1.Badge) (*v1.BadgeLevel, error) {\n\tlevels, err := UnmarshalLevels(*bdg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar found v1.BadgeLevel\n\tfor _, lvl := range levels {\n\t\tif lvl.IsDefault {\n\t\t\tif found.ID != \"\" {\n\t\t\t\treturn nil, errors.New(\"there are more than one levels with `isdefault=true`\")\n\t\t\t}\n\t\t\tfound = lvl\n\t\t}\n\t}\n\tif found.ID == \"\" {\n\t\treturn nil, errors.New(\"there is no level with `isdefault=true`\")\n\t}\n\treturn &found, nil\n}", "func GetAppBranch() (string, error) {\n\tcmdArgs := []string{\"rev-parse\", \"--abbrev-ref\", \"HEAD\"}\n\tbranchName, err := exec.Command(\"/usr/bin/git\", cmdArgs...).Output()\n\treturn string(branchName), err\n}", "func (g *GitLocal) Branch(dir string) (string, error) {\n\treturn g.GitCLI.Branch(dir)\n}", "func switchToBranch(opts RepoOpts) {\n\tr, err := git.PlainOpen(opts.path)\n\tCheckIfError(err)\n\n\tw, err := r.Worktree()\n\tCheckIfError(err)\n\n\terr1 := w.Checkout(&git.CheckoutOptions{})\n\tCheckIfError(err1)\n\tfmt.Println(\"Switching to master for \" + opts.path)\n}", "func (o TriggerGithubPushOutput) Branch() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v TriggerGithubPush) *string { return v.Branch }).(pulumi.StringPtrOutput)\n}", "func GitBranch(e *editarea.EditArea) string {\n\tcmdOut, err := exec.Command(\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\").Output()\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn string(cmdOut)\n}", "func lookupTip(r *git.Repository, refname string) *git.Commit {\n\tref, err := r.LookupReference(refname)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tcommit, err := lookupCommit(r, ref.Target())\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn commit\n}", "func lookupTip(r *git.Repository, refname string) *git.Commit {\n\tref, err := r.References.Lookup(refname)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tcommit, err := lookupCommit(r, ref.Target())\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn commit\n}", "func (g *GitRepo) lookupBranch(branch string) (*git.Branch, error) {\n\tremoteBranch := fmt.Sprintf(\"%s%s\", originPrefix, branch)\n\tb, err := g.r.LookupBranch(remoteBranch, git.BranchRemote)\n\tif err == nil && b != nil {\n\t\tlog.Infof(\"Found remote branch '%s'\", remoteBranch)\n\t\treturn b, nil\n\t}\n\n\tlog.Infof(\"Searching for local branch '%s'...\", branch)\n\treturn g.r.LookupBranch(branch, git.BranchLocal)\n}", "func CurrentBranchByRoot(ctx context.Context, dEnv *env.DoltEnv, replay ReplayRootFn, nerf NeedsRebaseFn) error {\n\treplayCommit := wrapReplayRootFn(replay)\n\theadRef, err := dEnv.RepoStateReader().CWBHeadRef()\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn rebaseRefs(ctx, dEnv.DbData(), replayCommit, nerf, headRef)\n}", "func (p *PullRequest) GetHead() *PullRequestBranch {\n\tif p == nil {\n\t\treturn nil\n\t}\n\treturn p.Head\n}", "func (d *DefaultGitClient) SwitchBack() error {\n\tw, err := d.repo.Worktree()\n\tif err != nil {\n\t\treturn errors.Errorf(`Failed to git branch switch back because \"%s\"`, err)\n\t}\n\n\terr = w.Checkout(&git.CheckoutOptions{\n\t\tBranch: plumbing.ReferenceName(\"refs/heads/\" + d.BaseBranch()),\n\t\tForce: true,\n\t})\n\n\tif err != nil {\n\t\treturn errors.Errorf(`failed to switch branch because \"%s\"`, err)\n\t}\n\n\treturn nil\n}", "func GetDefaultPath() (string, error) {\n\treturn GetGobinPath(\"golangci-lint\")\n}", "func (a *Client) GetBranch(params *GetBranchParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetBranchOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetBranchParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"getBranch\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/vcs/branch/{branchID}\",\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: &GetBranchReader{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.(*GetBranchOK)\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 getBranch: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (p *PullRequest) GetBase() *PullRequestBranch {\n\tif p == nil {\n\t\treturn nil\n\t}\n\treturn p.Base\n}", "func checkoutLocalBranch(config *GitXargsConfig, ref *plumbing.Reference, worktree *git.Worktree, remoteRepository *github.Repository, localRepository *git.Repository) (plumbing.ReferenceName, error) {\n\tlogger := logging.GetLogger(\"git-xargs\")\n\n\t// BranchName is a global variable that is set in cmd/root.go. It is override-able by the operator via the --branch-name or -b flag. It defaults to \"git-xargs\"\n\n\tbranchName := plumbing.NewBranchReferenceName(config.BranchName)\n\tlogger.WithFields(logrus.Fields{\n\t\t\"Branch Name\": branchName,\n\t\t\"Repo\": remoteRepository.GetName(),\n\t}).Debug(\"Created branch\")\n\n\t// Create a branch specific to the multi repo script runner\n\tco := &git.CheckoutOptions{\n\t\tHash: ref.Hash(),\n\t\tBranch: branchName,\n\t\tCreate: true,\n\t}\n\n\t// Attempt to checkout the new tool-specific branch on which the supplied command will be executed\n\tcheckoutErr := worktree.Checkout(co)\n\n\tif checkoutErr != nil {\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"Error\": checkoutErr,\n\t\t\t\"Repo\": remoteRepository.GetName(),\n\t\t}).Debug(\"Error creating new branch\")\n\n\t\t// Track the error checking out the branch\n\t\tconfig.Stats.TrackSingle(BranchCheckoutFailed, remoteRepository)\n\n\t\treturn branchName, errors.WithStackTrace(checkoutErr)\n\t}\n\n\t// Pull latest code from remote branch if it exists to avoid fast-forwarding errors\n\tpo := &git.PullOptions{\n\t\tRemoteName: \"origin\",\n\t\tReferenceName: branchName,\n\t\tAuth: &http.BasicAuth{\n\t\t\tUsername: remoteRepository.GetOwner().GetLogin(),\n\t\t\tPassword: os.Getenv(\"GITHUB_OAUTH_TOKEN\"),\n\t\t},\n\t\tProgress: os.Stdout,\n\t}\n\n\tpullErr := worktree.Pull(po)\n\n\tif pullErr != nil {\n\n\t\tif pullErr == plumbing.ErrReferenceNotFound {\n\t\t\t// The suppled branch just doesn't exist yet on the remote - this is not a fatal error and will\n\t\t\t// allow the new branch to be pushed in pushLocalBranch\n\t\t\tconfig.Stats.TrackSingle(BranchRemoteDidntExistYet, remoteRepository)\n\t\t\treturn branchName, nil\n\t\t}\n\n\t\t// Track the error pulling the latest from the remote branch\n\t\tconfig.Stats.TrackSingle(BranchRemotePullFailed, remoteRepository)\n\n\t\treturn branchName, errors.WithStackTrace(pullErr)\n\t}\n\n\treturn branchName, nil\n}", "func handleBranchSelect(g *gocui.Gui, v *gocui.View) error {\n\tif err := renderBranchesOptions(g); err != nil {\n\t\treturn err\n\t}\n\t// This really shouldn't happen: there should always be a master branch\n\tif len(state.Branches) == 0 {\n\t\treturn renderString(g, \"main\", \"No branches for this repo\")\n\t}\n\tgo func() {\n\t\tbranch := getSelectedBranch(v)\n\t\tdiff, err := getBranchGraph(branch.Name, branch.BaseBranch)\n\t\tif err != nil && strings.HasPrefix(diff, \"fatal: ambiguous argument\") {\n\t\t\tdiff = \"There is no tracking for this branch\"\n\t\t}\n\t\trenderString(g, \"main\", diff)\n\t}()\n\treturn nil\n}", "func (a *Action) GetBranch() string {\n\treturn strings.TrimPrefix(a.RefName, git.BranchPrefix)\n}", "func (t TestRepo) Fetch(name string, refs ...string) {\n\tif len(refs) == 0 {\n\t\trefs = []string{\"refs/heads/master\"}\n\t}\n\terr := t.remote(name).Fetch(refs, nil, \"\")\n\tCheckFatal(t.test, err)\n}", "func firstMatchingBuild(states, sortBy string) Build {\n\tvs := url.Values{}\n\tvs.Add(\"build.event_type\", \"push\")\n\tvs.Add(\"branch.name\", travisBranch)\n\tvs.Add(\"sort_by\", sortBy)\n\tif states != \"\" {\n\t\tvs.Add(\"build.state\", states)\n\t}\n\tvs.Add(\"limit\", \"1\")\n\n\tvar builds Builds\n\n\tpath := fmt.Sprintf(\"/repo/%v/builds?%v\", url.PathEscape(travisRepoSlug), vs.Encode())\n\tcallTravisAPI(\"GET\", path, http.StatusOK, &builds)\n\n\tif len(builds.Builds) == 0 {\n\t\tlog.Fatal(\"found no builds\")\n\t}\n\n\treturn builds.Builds[0]\n}", "func (novis *Novis) Get(name string) *Branch {\n\tvar branch *Branch\n\troute := strings.Split(name, \".\")\n\tlast := route[len(route)-1]\n\tfor branch = range novis.traverse(name) {\n\t\tif branch.name == last {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn branch\n}", "func (p *NoteStoreClient) GetDefaultNotebook(ctx context.Context, authenticationToken string) (r *Notebook, err error) {\n var _args63 NoteStoreGetDefaultNotebookArgs\n _args63.AuthenticationToken = authenticationToken\n var _result64 NoteStoreGetDefaultNotebookResult\n if err = p.Client_().Call(ctx, \"getDefaultNotebook\", &_args63, &_result64); err != nil {\n return\n }\n switch {\n case _result64.UserException!= nil:\n return r, _result64.UserException\n case _result64.SystemException!= nil:\n return r, _result64.SystemException\n }\n\n return _result64.GetSuccess(), nil\n}", "func StoreDefaultBranchName(dbOwner, folder, dbName, branchName string) error {\n\tdbQuery := `\n\t\tUPDATE sqlite_databases\n\t\tSET default_branch = $4\n\t\tWHERE user_id = (\n\t\t\t\tSELECT user_id\n\t\t\t\tFROM users\n\t\t\t\tWHERE lower(user_name) = lower($1)\n\t\t\t\t)\n\t\t\tAND folder = $2\n\t\t\tAND db_name = $3`\n\tcommandTag, err := pdb.Exec(dbQuery, dbOwner, folder, dbName, branchName)\n\tif err != nil {\n\t\tlog.Printf(\"Changing default branch for database '%v' to '%v' failed: %v\\n\", dbName, branchName, err)\n\t\treturn err\n\t}\n\tif numRows := commandTag.RowsAffected(); numRows != 1 {\n\t\tlog.Printf(\"Wrong number of rows (%v) affected during update: database: %v, new branch name: '%v'\\n\",\n\t\t\tnumRows, dbName, branchName)\n\t}\n\treturn nil\n}", "func executeJiraDefault(p *Plugin, c *plugin.Context, header *model.CommandArgs, args ...string) *model.CommandResponse {\n\treturn p.help(header)\n}", "func getLatestCommitFromRepo(ctx context.Context, client GitilesLogger, branch string) (string, error) {\n\tif hash := ctx.Value(overrideLatestCommitKey); hash != nil {\n\t\treturn hash.(string), nil\n\t}\n\tctx, span := trace.StartSpan(ctx, \"gitilesfollower_getLatestCommitFromRepo\")\n\tdefer span.End()\n\tlatestCommit, err := client.Log(ctx, branch, gitiles.LogLimit(1))\n\tif err != nil {\n\t\treturn \"\", skerr.Wrapf(err, \"getting last commit\")\n\t}\n\tif len(latestCommit) < 1 {\n\t\treturn \"\", skerr.Fmt(\"No commits returned\")\n\t}\n\treturn latestCommit[0].Hash, nil\n}", "func (machine *Dishwasher) Branch(branch string) {\r\n machine.Append(func() (string, error) {\r\n // IDEA take care of special cases, such as the master branch\r\n // checking if branch exists\r\n branchExists := false\r\n output, oops := RunCommand(\"git branch\")\r\n if oops != nil {\r\n return string(output), oops\r\n }\r\n branches := strings.Split(output, \"\\n\")\r\n for _, rawMaybe := range branches {\r\n maybe := strings.Replace(rawMaybe, \"*\", \" \", -1)\r\n maybe = strings.TrimSpace(maybe)\r\n if maybe == branch {\r\n branchExists = true\r\n }\r\n }\r\n\r\n // creating branch if necessary\r\n if !branchExists {\r\n branchCmd := fmt.Sprintf(\"git branch %s\", branch)\r\n output, oops = RunCommand(branchCmd)\r\n if oops != nil {\r\n return string(output), oops\r\n }\r\n }\r\n\r\n // switching to target branch\r\n checkoutCmd := fmt.Sprintf(\"git checkout %s\", branch)\r\n output, oops = RunCommand(checkoutCmd)\r\n return string(output), oops\r\n })\r\n}", "func (c *client) GetIssue(org, repo string, number int) (*Issue, error) {\n\tdurationLogger := c.log(\"GetIssue\", org, repo, number)\n\tdefer durationLogger()\n\n\tvar i Issue\n\t_, err := c.request(&request{\n\t\t// allow emoji\n\t\t// https://developer.github.com/changes/2018-02-22-label-description-search-preview/\n\t\taccept: \"application/vnd.github.symmetra-preview+json\",\n\t\tmethod: http.MethodGet,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/issues/%d\", org, repo, number),\n\t\torg: org,\n\t\texitCodes: []int{200},\n\t}, &i)\n\treturn &i, err\n}", "func (b Branch) GetAction(ctx context.Context, c *github.Client, owner, repo string) string {\n\toc, rc := getConfig(ctx, c, owner, repo)\n\tmc := mergeConfig(oc, rc, repo)\n\treturn mc.Action\n}", "func NewGetLeaderboardDefault(code int) *GetLeaderboardDefault {\n\treturn &GetLeaderboardDefault{\n\t\t_statusCode: code,\n\t}\n}", "func GetBranch(db *sqlx.DB, id int) (Branch, error) {\n\tvar branch Branch\n\n\terr := db.Get(&branch, \"SELECT * FROM branches WHERE id=$1\", id)\n\n\tif err != nil {\n\t\treturn Branch{}, err\n\t}\n\n\treturn branch, nil\n}", "func FindOneProjectRefWithCommitQueueByOwnerRepoAndBranch(owner, repo, branch string) (*ProjectRef, error) {\n\tprojectRefs, err := FindMergedEnabledProjectRefsByRepoAndBranch(owner, repo, branch)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Could not fetch project ref for repo '%s/%s' with branch '%s'\",\n\t\t\towner, repo, branch)\n\t}\n\tfor _, p := range projectRefs {\n\t\tif p.CommitQueue.IsEnabled() {\n\t\t\tp.checkDefaultLogger()\n\t\t\treturn &p, nil\n\t\t}\n\t}\n\n\tgrip.Debug(message.Fields{\n\t\t\"message\": \"no matching project ref with commit queue enabled\",\n\t\t\"owner\": owner,\n\t\t\"repo\": repo,\n\t\t\"branch\": branch,\n\t})\n\treturn nil, nil\n}", "func switchBranch(config *gctsDeployOptions, httpClient piperhttp.Sender, currentBranch string, targetBranch string) (*switchBranchResponseBody, error) {\n\tvar response switchBranchResponseBody\n\tlog.Entry().Infof(\"gCTS Deploy : Switching branch for repository : %v, from branch: %v to %v\", config.Repository, currentBranch, targetBranch)\n\trequestURL := config.Host +\n\t\t\"/sap/bc/cts_abapvcs/repository/\" + config.Repository + \"/branches/\" + currentBranch +\n\t\t\"/switch?branch=\" + targetBranch + \"&sap-client=\" + config.Client\n\n\trequestURL, urlErr := addQueryToURL(requestURL, config.QueryParameters)\n\n\tif urlErr != nil {\n\n\t\treturn nil, urlErr\n\t}\n\n\tresp, httpErr := httpClient.SendRequest(\"GET\", requestURL, nil, nil, nil)\n\tdefer func() {\n\t\tif resp != nil && resp.Body != nil {\n\t\t\tresp.Body.Close()\n\t\t}\n\t}()\n\tif httpErr != nil {\n\t\t_, errorDumpParseErr := parseErrorDumpFromResponseBody(resp)\n\t\tif errorDumpParseErr != nil {\n\t\t\treturn nil, errorDumpParseErr\n\t\t}\n\t\treturn &response, httpErr\n\t} else if resp == nil {\n\t\treturn &response, errors.New(\"did not retrieve a HTTP response\")\n\t}\n\tparsingErr := piperhttp.ParseHTTPResponseBodyJSON(resp, &response)\n\tif parsingErr != nil {\n\t\treturn &response, parsingErr\n\t}\n\tlog.Entry().Infof(\"Switched branches from %v to %v. The commits where switched from %v to %v\", currentBranch, config.Branch, response.Result.FromCommit, response.Result.ToCommit)\n\treturn &response, nil\n}", "func GuessDefault(path string, l output.Logger) Default {\n\tutil := newDefaultsUtil(l)\n\n\tguesser := DefaultGuesser{\n\t\tNewGolangDefault(util),\n\t\tNewNodeYarnDefault(util),\n\t\tNewNodeNpmDefault(util),\n\t\tNewJavaMavenDefault(util),\n\t}\n\n\tworkdir, err := filepath.Abs(path)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdef := guesser.Find(workdir)\n\treturn def\n}", "func MakeIssueReference(id interface{}) string {\n\treturn fmt.Sprintf(\"refs/heads/%s/%v\", IssueBranchPrefix, id)\n}", "func branchChangeID(br string) string {\n\tout, err := exec.Command(\"git\", \"show\", br, \"--\").CombinedOutput()\n\tif err != nil {\n\t\tlog.Printf(\"Error running git show %v: %v: %s\", br, err, out)\n\t}\n\tif m := changeRx.FindSubmatch(out); m != nil {\n\t\treturn string(m[1])\n\t}\n\treturn \"\"\n}", "func getJiraIssue(issueKey string, jiraClient *jira.Client) (JiraIssue, error) {\n\n\tvar jiraIssue JiraIssue\n\n\tissue, _, err := jiraClient.Issue.Get(issueKey, nil)\n\tif err != nil {\n\t\tlog.Printf(\"Cannot find %v\", issueKey)\n\t\treturn jiraIssue, err\n\t}\n\n\t//Fields from ticket itself\n\tjiraIssue.Key = issue.Key //Task key\n\tjiraIssue.Summary = issue.Fields.Summary //Task name\n\tjiraIssue.Estimation = issue.Fields.TimeTracking.OriginalEstimate //Estimation\n\n\tif issue.Fields.Parent != nil {\n\t\tjiraIssue.ParentKey = issue.Fields.Parent.Key //Parent task key\n\t}\n\n\t//Fields from parent ticket\n\tif jiraIssue.ParentKey == \"\" {\n\t\treturn jiraIssue, fmt.Errorf(\"issue %v does not have parent ticket, do nothing\", issueKey)\n\t}\n\tissue, _, err = jiraClient.Issue.Get(jiraIssue.ParentKey, nil)\n\tif err != nil {\n\t\tlog.Printf(\"Cannot find parent ticket %v\", issueKey)\n\t\treturn jiraIssue, err\n\t}\n\n\tjiraIssue.ParentSummary = issue.Fields.Summary //Parent task summary\n\tjiraIssue.ParentDescription = issue.Fields.Description\n\n\t//Example of issue.Fields.Unknowns[\"customfield_10416\"]:\n\t//customfield_10416:map[id:12016 self:https://inchcapeglobal.atlassian.net/rest/api/2/customFieldOption/12016 value:IMP_22]\n\tbudgetMap := issue.Fields.Unknowns[\"customfield_10416\"] //Budget\n\tbudgetMap2, ok := budgetMap.(map[string]interface{})\n\tif ok {\n\t\tjiraIssue.ParentBudget = budgetMap2[\"value\"].(string)\n\t}\n\n\treturn jiraIssue, nil\n\n}", "func (s *server) packIssue(name upspin.PathName, issue *maintner.GitHubIssue) (*upspin.DirEntry, error) {\n\tkey := issueKey{\n\t\tname: name,\n\t\tupdated: issue.Updated,\n\t}\n\ts.mu.Lock()\n\tpacked, ok := s.issue[key]\n\ts.mu.Unlock()\n\tif ok {\n\t\treturn packed.de, nil\n\t}\n\tde, data, err := s.pack(name, key.Ref(), formatIssue(issue))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.mu.Lock()\n\ts.issue[key] = packedIssue{\n\t\tde: de,\n\t\tdata: data,\n\t}\n\ts.mu.Unlock()\n\treturn de, nil\n}", "func defaultGetProjectID(rd *RowData) (string, error) {\n\treturn \"\", RowDataNotApplicableError\n}", "func branchName() (string, string) {\n\tbranch := gitBranchName()\n\treleaseName := strings.TrimPrefix(branch, \"origin/\")\n\n\treturn releaseName, branch\n}", "func (fp *AcceptProjectInvitationRequest_FieldTerminalPath) GetDefault() interface{} {\n\tswitch fp.selector {\n\tcase AcceptProjectInvitationRequest_FieldPathSelectorName:\n\t\treturn (*project_invitation.Reference)(nil)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Invalid selector for AcceptProjectInvitationRequest: %d\", fp.selector))\n\t}\n}" ]
[ "0.76395214", "0.72123367", "0.7082229", "0.70578945", "0.6987225", "0.692187", "0.679232", "0.66691875", "0.6630789", "0.64667594", "0.6397041", "0.63649535", "0.6181196", "0.61626583", "0.6102478", "0.59017694", "0.5774812", "0.5746847", "0.56741744", "0.56536037", "0.56517714", "0.5646828", "0.5595356", "0.55688226", "0.5527252", "0.55227613", "0.5518438", "0.5479159", "0.54773057", "0.54737484", "0.5463938", "0.5450031", "0.544465", "0.54379404", "0.54222625", "0.5416291", "0.5404958", "0.53931147", "0.53793585", "0.5371461", "0.5368525", "0.5342916", "0.5336115", "0.53269166", "0.5313888", "0.53001595", "0.52981853", "0.52871794", "0.5286577", "0.5264407", "0.5243097", "0.5227689", "0.5196478", "0.5188232", "0.5114839", "0.511046", "0.5093868", "0.50892466", "0.50736797", "0.5071253", "0.507065", "0.50685865", "0.50522244", "0.50352466", "0.501882", "0.5012939", "0.5010187", "0.50027084", "0.50006485", "0.49977076", "0.49892393", "0.49869004", "0.498647", "0.4982432", "0.49669006", "0.49666306", "0.49619815", "0.49540985", "0.4954051", "0.4946382", "0.4939849", "0.49148008", "0.4912108", "0.49103108", "0.4895559", "0.48933694", "0.48903236", "0.48742208", "0.48739672", "0.48689437", "0.48570007", "0.48467144", "0.48443455", "0.48418006", "0.48224208", "0.4817495", "0.48027182", "0.47964585", "0.47909397", "0.47816744" ]
0.73888147
1
SetAssignee ... Set assignee on a GitHub Issue
func (g *GitHubImpl) SetAssignee(assignee string, issue int) (err error) { URL := fmt.Sprintf(g.URLNoEsc(urls.assigneeURL), g.org, g.repo, issue) jsonBytes, _ := json.Marshal(Assignee{Assignees: []string{assignee}}) req, _ := http.NewRequest("POST", URL, bytes.NewBuffer(jsonBytes)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "token "+g.token) _, err = NewPWRequest().Do(req) if err != nil { return err } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (issue *Issue) Assignee(name string) error {\n\tencodedParams, err := json.Marshal(map[string]string{\"name\": name})\n\tif err != nil {\n\t\treturn err\n\t}\n\turl := fmt.Sprintf(\"%s/issue/%s/assignee\", BaseURL, issue.Key)\n\tcode, body := execRequest(\"PUT\", url, bytes.NewBuffer(encodedParams))\n\tif code == http.StatusNoContent {\n\t\treturn nil\n\t}\n\treturn handleJiraError(body)\n}", "func (issue *Issue) Assignee(name string) error {\n\tparams := make(map[string]string)\n\tparams[\"name\"] = name\n\tb, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuff := bytes.NewBuffer(b)\n\turl := fmt.Sprintf(\"%s/issue/%s/assignee\", BaseUrl, issue.Key)\n\tcode, body := execRequest(\"PUT\", url, buff)\n\tif code == http.StatusNoContent {\n\t\treturn nil\n\t} else {\n\t\treturn handleJiraError(body)\n\t}\n}", "func (o *Task) SetAssignee(ctx context.Context, exec boil.ContextExecutor, insert bool, related *User) error {\n\tvar err error\n\tif insert {\n\t\tif err = related.Insert(ctx, exec, boil.Infer()); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to insert into foreign table\")\n\t\t}\n\t}\n\n\tupdateQuery := fmt.Sprintf(\n\t\t\"UPDATE \\\"tasks\\\" SET %s WHERE %s\",\n\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 1, []string{\"assignee_id\"}),\n\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", 2, taskPrimaryKeyColumns),\n\t)\n\tvalues := []interface{}{related.ID, o.ID}\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, updateQuery)\n\t\tfmt.Fprintln(writer, values)\n\t}\n\tif _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil {\n\t\treturn errors.Wrap(err, \"failed to update local table\")\n\t}\n\n\tqueries.Assign(&o.AssigneeID, related.ID)\n\tif o.R == nil {\n\t\to.R = &taskR{\n\t\t\tAssignee: related,\n\t\t}\n\t} else {\n\t\to.R.Assignee = related\n\t}\n\n\tif related.R == nil {\n\t\trelated.R = &userR{\n\t\t\tAssigneeTasks: TaskSlice{o},\n\t\t}\n\t} else {\n\t\trelated.R.AssigneeTasks = append(related.R.AssigneeTasks, o)\n\t}\n\n\treturn nil\n}", "func (c *client) AssignIssue(org, repo string, number int, logins []string) error {\n\tdurationLogger := c.log(\"AssignIssue\", org, repo, number, logins)\n\tdefer durationLogger()\n\n\tassigned := make(map[string]bool)\n\tvar i Issue\n\t_, err := c.request(&request{\n\t\tmethod: http.MethodPost,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/issues/%d/assignees\", org, repo, number),\n\t\torg: org,\n\t\trequestBody: map[string][]string{\"assignees\": logins},\n\t\texitCodes: []int{201},\n\t}, &i)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, assignee := range i.Assignees {\n\t\tassigned[NormLogin(assignee.Login)] = true\n\t}\n\tmissing := MissingUsers{action: \"assign\"}\n\tfor _, login := range logins {\n\t\tif !assigned[NormLogin(login)] {\n\t\t\tmissing.Users = append(missing.Users, login)\n\t\t}\n\t}\n\tif len(missing.Users) > 0 {\n\t\treturn missing\n\t}\n\treturn nil\n}", "func assignUser(issue *Issue, user *User) error {\n\trepo, repoErr := issue.GetRepository()\n\tif repoErr != nil {\n\t\treturn fmt.Errorf(\"Cannot extract repo name from URL: %s\", repoErr)\n\t}\n\tvar body bytes.Buffer\n\terr := json.NewEncoder(&body).Encode(map[string]interface{}{\n\t\t\"assignee\": user.Login,\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot encode body: %s\", err)\n\t}\n\turl := fmt.Sprintf(\"%s/repos/%s/%s/issues/%d\",\n\t\t*ghAPIFl, *ghOrgFl, repo, issue.Number)\n\treq, err := http.NewRequest(\"PATCH\", url, &body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot create PATCH request: %s\", err)\n\t}\n\taddAuthentication(req)\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot do request: %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"unexpected response: %d\", resp.StatusCode)\n\t}\n\tlog.Printf(\"%s assigned to #%d issue of %q\", user.Login, issue.Number, repo)\n\tcomment := fmt.Sprintf(\"Pull request seem to be stale, assigning @%s as the responsible developer.\", user.Login)\n\tif err := writeGithubComment(issue, comment); err != nil {\n\t\tlog.Printf(\"cannot comment on %s's #%d pull request: %s\", repo, issue.Number, err)\n\t}\n\treturn nil\n}", "func (wouo *WorkOrderUpdateOne) SetAssignee(s string) *WorkOrderUpdateOne {\n\twouo.assignee = &s\n\treturn wouo\n}", "func (o *WatchlistScreeningIndividualUpdateResponse) SetAssignee(v string) {\n\to.Assignee.Set(&v)\n}", "func (m *EducationAssignment) SetAssignTo(value EducationAssignmentRecipientable)() {\n m.assignTo = value\n}", "func (wou *WorkOrderUpdate) SetAssignee(s string) *WorkOrderUpdate {\n\twou.assignee = &s\n\treturn wou\n}", "func MRAssign(mr *gitlab.MergeRequest, userID int) error {\n\tfor _, user := range mr.Assignees {\n\t\tif user.ID == userID {\n\t\t\treturn nil\n\t\t}\n\t}\n\t_mr, _, err := lab.MergeRequests.UpdateMergeRequest(mr.ProjectID, mr.ID, &gitlab.UpdateMergeRequestOptions{\n\t\tAssigneeIDs: []int{userID},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tmr = _mr\n\treturn nil\n}", "func (m *ScheduleChangeRequest) SetAssignedTo(value *ScheduleChangeRequestActor)() {\n err := m.GetBackingStore().Set(\"assignedTo\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *SequentialActivationRenewalsAlertIncident) SetAssigneeId(value *string)() {\n err := m.GetBackingStore().Set(\"assigneeId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *SequentialActivationRenewalsAlertIncident) SetAssigneeUserPrincipalName(value *string)() {\n err := m.GetBackingStore().Set(\"assigneeUserPrincipalName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *SequentialActivationRenewalsAlertIncident) SetAssigneeDisplayName(value *string)() {\n err := m.GetBackingStore().Set(\"assigneeDisplayName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *EducationAssignment) SetCreatedBy(value IdentitySetable)() {\n m.createdBy = value\n}", "func (i *IssueRequest) GetAssignee() string {\n\tif i == nil || i.Assignee == nil {\n\t\treturn \"\"\n\t}\n\treturn *i.Assignee\n}", "func (t *Task) SetAssigneeUserID(assigneeUserID string) {\n\tif assigneeUserID != \"\" {\n\t\t// Update only if not empty\n\t\tt.AssigneeUserID = sql.NullString{String: assigneeUserID, Valid: true}\n\t}\n}", "func (i *IssueEvent) GetAssignee() *User {\n\tif i == nil {\n\t\treturn nil\n\t}\n\treturn i.Assignee\n}", "func (p *PullRequest) GetAssignee() *User {\n\tif p == nil {\n\t\treturn nil\n\t}\n\treturn p.Assignee\n}", "func (i *Issue) GetAssignee() *User {\n\tif i == nil {\n\t\treturn nil\n\t}\n\treturn i.Assignee\n}", "func (wouo *WorkOrderUpdateOne) SetNillableAssignee(s *string) *WorkOrderUpdateOne {\n\tif s != nil {\n\t\twouo.SetAssignee(*s)\n\t}\n\treturn wouo\n}", "func (i *IssuesEvent) GetAssignee() *User {\n\tif i == nil {\n\t\treturn nil\n\t}\n\treturn i.Assignee\n}", "func (j *DSGitHub) EnrichIssueAssignees(ctx *Ctx, issue map[string]interface{}, assignees []map[string]interface{}, affs bool) (richItems []interface{}, err error) {\n\t// type: category, type(_), item_type( ), issue_assignee=true\n\t// copy issue: github_repo, repo_name, repository\n\t// identify: id, id_in_repo, issue_assignee_login, url_id\n\t// standard: metadata..., origin, project, project_slug, uuid\n\t// parent: issue_id, issue_number\n\t// identity: author_... -> assignee_...,\n\t// common: is_github_issue=1, is_github_issue_assignee=1\n\tiID, _ := issue[\"id\"]\n\tid, _ := iID.(string)\n\tiIssueID, _ := issue[\"issue_id\"]\n\tissueID := int(iIssueID.(float64))\n\tissueNumber, _ := issue[\"id_in_repo\"]\n\tiNumber, _ := issueNumber.(int)\n\tiGithubRepo, _ := issue[\"github_repo\"]\n\tgithubRepo, _ := iGithubRepo.(string)\n\tcopyIssueFields := []string{\"category\", \"github_repo\", \"repo_name\", \"repository\", \"repo_short_name\", \"pull_request\"}\n\tfor _, assignee := range assignees {\n\t\trich := make(map[string]interface{})\n\t\tfor _, field := range RawFields {\n\t\t\tv, _ := issue[field]\n\t\t\trich[field] = v\n\t\t}\n\t\tfor _, field := range copyIssueFields {\n\t\t\trich[field], _ = issue[field]\n\t\t}\n\t\tif ctx.Project != \"\" {\n\t\t\trich[\"project\"] = ctx.Project\n\t\t}\n\t\trich[\"type\"] = \"issue_assignee\"\n\t\trich[\"item_type\"] = \"issue assignee\"\n\t\trich[\"issue_assignee\"] = true\n\t\trich[\"issue_id\"] = issueID\n\t\trich[\"issue_number\"] = issueNumber\n\t\tiLogin, _ := assignee[\"login\"]\n\t\tlogin, _ := iLogin.(string)\n\t\trich[\"id_in_repo\"], _ = assignee[\"id\"]\n\t\trich[\"issue_assignee_login\"] = login\n\t\trich[\"id\"] = id + \"/assignee/\" + login\n\t\trich[\"url_id\"] = fmt.Sprintf(\"%s/issues/%d/assignees/%s\", githubRepo, iNumber, login)\n\t\trich[\"author_login\"] = login\n\t\trich[\"author_name\"], _ = assignee[\"name\"]\n\t\trich[\"author_avatar_url\"], _ = assignee[\"avatar_url\"]\n\t\trich[\"assignee_avatar_url\"] = rich[\"author_avatar_url\"]\n\t\trich[\"assignee_login\"] = login\n\t\trich[\"assignee_name\"], _ = assignee[\"name\"]\n\t\trich[\"assignee_domain\"] = nil\n\t\tiEmail, ok := assignee[\"email\"]\n\t\tif ok {\n\t\t\temail, _ := iEmail.(string)\n\t\t\tary := strings.Split(email, \"@\")\n\t\t\tif len(ary) > 1 {\n\t\t\t\trich[\"assignee_domain\"] = strings.TrimSpace(ary[1])\n\t\t\t}\n\t\t}\n\t\trich[\"assignee_org\"], _ = assignee[\"company\"]\n\t\trich[\"assignee_location\"], _ = assignee[\"location\"]\n\t\trich[\"assignee_geolocation\"] = nil\n\t\t// We consider assignee assignment at issue creation date\n\t\tiCreatedAt, _ := issue[\"created_at\"]\n\t\tcreatedAt, _ := iCreatedAt.(time.Time)\n\t\trich[j.DateField(ctx)] = createdAt\n\t\tif affs {\n\t\t\tauthorKey := \"assignee\"\n\t\t\tvar affsItems map[string]interface{}\n\t\t\taffsItems, err = j.AffsItems(ctx, map[string]interface{}{\"assignee\": assignee}, GitHubIssueAssigneeRoles, createdAt)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor prop, value := range affsItems {\n\t\t\t\trich[prop] = value\n\t\t\t}\n\t\t\tfor _, suff := range AffsFields {\n\t\t\t\trich[Author+suff] = rich[authorKey+suff]\n\t\t\t}\n\t\t\torgsKey := authorKey + MultiOrgNames\n\t\t\t_, ok := Dig(rich, []string{orgsKey}, false, true)\n\t\t\tif !ok {\n\t\t\t\trich[orgsKey] = []interface{}{}\n\t\t\t}\n\t\t}\n\t\tfor prop, value := range CommonFields(j, createdAt, j.Category) {\n\t\t\trich[prop] = value\n\t\t}\n\t\tfor prop, value := range CommonFields(j, createdAt, j.Category+\"_assignee\") {\n\t\t\trich[prop] = value\n\t\t}\n\t\trichItems = append(richItems, rich)\n\t}\n\treturn\n}", "func (t *Timeline) GetAssignee() *User {\n\tif t == nil {\n\t\treturn nil\n\t}\n\treturn t.Assignee\n}", "func (wou *WorkOrderUpdate) SetNillableAssignee(s *string) *WorkOrderUpdate {\n\tif s != nil {\n\t\twou.SetAssignee(*s)\n\t}\n\treturn wou\n}", "func (m *MockClient) AssignIssue(org, repo string, number int, logins []string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AssignIssue\", org, repo, number, logins)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (c *client) UnassignIssue(org, repo string, number int, logins []string) error {\n\tdurationLogger := c.log(\"UnassignIssue\", org, repo, number, logins)\n\tdefer durationLogger()\n\n\tassigned := make(map[string]bool)\n\tvar i Issue\n\t_, err := c.request(&request{\n\t\tmethod: http.MethodDelete,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/issues/%d/assignees\", org, repo, number),\n\t\torg: org,\n\t\trequestBody: map[string][]string{\"assignees\": logins},\n\t\texitCodes: []int{200},\n\t}, &i)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, assignee := range i.Assignees {\n\t\tassigned[NormLogin(assignee.Login)] = true\n\t}\n\textra := ExtraUsers{action: \"unassign\"}\n\tfor _, login := range logins {\n\t\tif assigned[NormLogin(login)] {\n\t\t\textra.Users = append(extra.Users, login)\n\t\t}\n\t}\n\tif len(extra.Users) > 0 {\n\t\treturn extra\n\t}\n\treturn nil\n}", "func (o *WatchlistScreeningIndividualUpdateResponse) GetAssignee() string {\n\tif o == nil || o.Assignee.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn *o.Assignee.Get()\n}", "func (j *DSGitHub) EnrichPullRequestAssignees(ctx *Ctx, pull map[string]interface{}, assignees []map[string]interface{}, affs bool) (richItems []interface{}, err error) {\n\t// type: category, type(_), item_type( ), pull_request_assignee=true\n\t// copy pull request: github_repo, repo_name, repository\n\t// identify: id, id_in_repo, pull_request_assignee_login, url_id\n\t// standard: metadata..., origin, project, project_slug, uuid\n\t// parent: pull_request_id, pull_request_number\n\t// identity: author_... -> assignee_...,\n\t// common: is_github_pull_request=1, is_github_pull_request_assignee=1\n\tiID, _ := pull[\"id\"]\n\tid, _ := iID.(string)\n\tiPullID, _ := pull[\"pull_request_id\"]\n\tpullID := int(iPullID.(float64))\n\tpullNumber, _ := pull[\"id_in_repo\"]\n\tiNumber, _ := pullNumber.(int)\n\tiGithubRepo, _ := pull[\"github_repo\"]\n\tgithubRepo, _ := iGithubRepo.(string)\n\tcopyPullFields := []string{\"category\", \"github_repo\", \"repo_name\", \"repository\", \"repo_short_name\"}\n\tfor _, assignee := range assignees {\n\t\trich := make(map[string]interface{})\n\t\tfor _, field := range RawFields {\n\t\t\tv, _ := pull[field]\n\t\t\trich[field] = v\n\t\t}\n\t\tfor _, field := range copyPullFields {\n\t\t\trich[field], _ = pull[field]\n\t\t}\n\t\tif ctx.Project != \"\" {\n\t\t\trich[\"project\"] = ctx.Project\n\t\t}\n\t\trich[\"type\"] = \"pull_request_assignee\"\n\t\trich[\"item_type\"] = \"pull request assignee\"\n\t\trich[\"pull_request_assignee\"] = true\n\t\trich[\"pull_request_id\"] = pullID\n\t\trich[\"pull_request_number\"] = pullNumber\n\t\tiLogin, _ := assignee[\"login\"]\n\t\tlogin, _ := iLogin.(string)\n\t\trich[\"id_in_repo\"], _ = assignee[\"id\"]\n\t\trich[\"pull_request_assignee_login\"] = login\n\t\trich[\"id\"] = id + \"/assignee/\" + login\n\t\trich[\"url_id\"] = fmt.Sprintf(\"%s/pulls/%d/assignees/%s\", githubRepo, iNumber, login)\n\t\trich[\"author_login\"] = login\n\t\trich[\"author_name\"], _ = assignee[\"name\"]\n\t\trich[\"author_avatar_url\"], _ = assignee[\"avatar_url\"]\n\t\trich[\"assignee_avatar_url\"] = rich[\"author_avatar_url\"]\n\t\trich[\"assignee_login\"] = login\n\t\trich[\"assignee_name\"], _ = assignee[\"name\"]\n\t\trich[\"assignee_domain\"] = nil\n\t\tiEmail, ok := assignee[\"email\"]\n\t\tif ok {\n\t\t\temail, _ := iEmail.(string)\n\t\t\tary := strings.Split(email, \"@\")\n\t\t\tif len(ary) > 1 {\n\t\t\t\trich[\"assignee_domain\"] = strings.TrimSpace(ary[1])\n\t\t\t}\n\t\t}\n\t\trich[\"assignee_org\"], _ = assignee[\"company\"]\n\t\trich[\"assignee_location\"], _ = assignee[\"location\"]\n\t\trich[\"assignee_geolocation\"] = nil\n\t\t// We consider assignee enrollment at pull request creation date\n\t\tiCreatedAt, _ := pull[\"created_at\"]\n\t\tcreatedAt, _ := iCreatedAt.(time.Time)\n\t\trich[j.DateField(ctx)] = createdAt\n\t\tif affs {\n\t\t\tauthorKey := \"assignee\"\n\t\t\tvar affsItems map[string]interface{}\n\t\t\taffsItems, err = j.AffsItems(ctx, map[string]interface{}{\"assignee\": assignee}, GitHubPullRequestAssigneeRoles, createdAt)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor prop, value := range affsItems {\n\t\t\t\trich[prop] = value\n\t\t\t}\n\t\t\tfor _, suff := range AffsFields {\n\t\t\t\trich[Author+suff] = rich[authorKey+suff]\n\t\t\t}\n\t\t\torgsKey := authorKey + MultiOrgNames\n\t\t\t_, ok := Dig(rich, []string{orgsKey}, false, true)\n\t\t\tif !ok {\n\t\t\t\trich[orgsKey] = []interface{}{}\n\t\t\t}\n\t\t}\n\t\tfor prop, value := range CommonFields(j, createdAt, j.Category) {\n\t\t\trich[prop] = value\n\t\t}\n\t\tfor prop, value := range CommonFields(j, createdAt, j.Category+\"_assignee\") {\n\t\t\trich[prop] = value\n\t\t}\n\t\trichItems = append(richItems, rich)\n\t}\n\treturn\n}", "func (m memberUsecase) AssignToProject(ctx context.Context, memberID models.UUID, projectID models.UUID) error {\n\treturn m.memberRepos.AssignToProject(ctx, memberID, projectID)\n}", "func (m *MockIssueClient) AssignIssue(org, repo string, number int, logins []string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AssignIssue\", org, repo, number, logins)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (j *Jira) IssuesAssignedTo(user string, maxResults int, startAt int) (i IssueList, err error) {\n\turi := j.ApiPath + \"/search?jql=assignee=\\\"\" +\n\t\turl.QueryEscape(user) + \"\\\"&startAt=\" + strconv.Itoa(startAt) +\n\t\t\"&maxResults=\" + strconv.Itoa(maxResults)\n\n\tcontents, err := j.getRequest(uri)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar issues IssueList\n\terr = json.Unmarshal(contents, &issues)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, issue := range issues.Issues {\n\t\tt, _ := time.Parse(dateLayout, issue.Fields.Created)\n\t\tissue.CreatedAt = t\n\t}\n\n\tpagination := Pagination{\n\t\tTotal: issues.Total,\n\t\tStartAt: issues.StartAt,\n\t\tMaxResults: issues.MaxResults,\n\t}\n\tpagination.Compute()\n\tissues.Pagination = &pagination\n\n\treturn issues, nil\n}", "func Handle(client *github.Client, event github.IssueCommentEvent) error {\n\tcomment := *event.Comment.Body\n\t//regular expression to Assign or unassign the Assignees\n\treg := regexp.MustCompile(\"(?mi)^/(un)?assign(( @?[-\\\\w]+?)*)\\\\s*$\")\n\n\tif reg.MatchString(comment) {\n\t\tctx := context.Background()\n\t\t//split the assignees and operation to be performed.\n\t\tsubstrings := strings.Split(comment, \"@\")\n\t\t//list of assignees to be assigned for issues/PR\n\t\tlistOfAssignees := make([]string, 0)\n\t\t//range over the substring to get the list of assignees\n\t\tfor i, assignees := range substrings {\n\t\t\tif i == 0 {\n\t\t\t\t//first index is the operation to be performed, rest will be the assignees\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlistOfAssignees = append(listOfAssignees, assignees)\n\t\t}\n\t\t//operation is the assign or unassign check\n\t\toperation := strings.Trim(substrings[0], \" \")\n\t\tif operation == Assign {\n\t\t\t_, _, err := client.Issues.AddAssignees(ctx, *event.Repo.Owner.Login, *event.Repo.Name, *event.Issue.Number, listOfAssignees)\n\t\t\tif err != nil {\n\t\t\t\tglog.Fatalf(\"Unable to Add Assignees: %v err: %v\", listOfAssignees, err)\n\t\t\t\treturn err\n\t\t\t} else {\n\t\t\t\tglog.Infof(\"Assignee added successfully: %v\", listOfAssignees)\n\t\t\t}\n\t\t} else if operation == Unassign {\n\t\t\t_, _, err := client.Issues.RemoveAssignees(ctx, *event.Repo.Owner.Login, *event.Repo.Name, *event.Issue.Number, listOfAssignees)\n\t\t\tif err != nil {\n\t\t\t\tglog.Fatalf(\"Cannot remove Assignees: %v err: %v\", listOfAssignees, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tglog.Infof(\"Removed assignee: %v\", listOfAssignees)\n\t\t}\n\t}\n\treturn nil\n}", "func (m *ThreatAssessmentRequest) SetCreatedBy(value IdentitySetable)() {\n m.createdBy = value\n}", "func (o *Task) RemoveAssignee(ctx context.Context, exec boil.ContextExecutor, related *User) error {\n\tvar err error\n\n\tqueries.SetScanner(&o.AssigneeID, nil)\n\tif _, err = o.Update(ctx, exec, boil.Whitelist(\"assignee_id\")); err != nil {\n\t\treturn errors.Wrap(err, \"failed to update local table\")\n\t}\n\n\tif o.R != nil {\n\t\to.R.Assignee = nil\n\t}\n\tif related == nil || related.R == nil {\n\t\treturn nil\n\t}\n\n\tfor i, ri := range related.R.AssigneeTasks {\n\t\tif queries.Equal(o.AssigneeID, ri.AssigneeID) {\n\t\t\tcontinue\n\t\t}\n\n\t\tln := len(related.R.AssigneeTasks)\n\t\tif ln > 1 && i < ln-1 {\n\t\t\trelated.R.AssigneeTasks[i] = related.R.AssigneeTasks[ln-1]\n\t\t}\n\t\trelated.R.AssigneeTasks = related.R.AssigneeTasks[:ln-1]\n\t\tbreak\n\t}\n\treturn nil\n}", "func (o *Task) Assignee(mods ...qm.QueryMod) userQuery {\n\tqueryMods := []qm.QueryMod{\n\t\tqm.Where(\"\\\"id\\\" = ?\", o.AssigneeID),\n\t}\n\n\tqueryMods = append(queryMods, mods...)\n\n\tquery := Users(queryMods...)\n\tqueries.SetFrom(query.Query, \"\\\"users\\\"\")\n\n\treturn query\n}", "func (pu *ProjectUtil) AssignRole(projectName, username string) error {\n\tif len(strings.TrimSpace(projectName)) == 0 ||\n\t\tlen(strings.TrimSpace(username)) == 0 {\n\t\treturn errors.New(\"Project name and username are required for assigning role\")\n\t}\n\n\tpid := pu.GetProjectID(projectName)\n\tif pid == -1 {\n\t\treturn fmt.Errorf(\"Failed to get project ID with name %s\", projectName)\n\t}\n\n\tm := models.Member{\n\t\tRoleID: 2,\n\t\tMemberUser: &models.MemUser{\n\t\t\tUserName: username,\n\t\t},\n\t}\n\n\tbody, err := json.Marshal(&m)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\turl := fmt.Sprintf(\"%s%s%d%s\", pu.rootURI, \"/api/v2.0/projects/\", pid, \"/members\")\n\tif err := pu.testingClient.Post(url, body); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func assignVolunteerToTeam(c *gin.Context) {\n\tidentifier := c.Params.ByName(\"identifier\")\n\n\tvar ve VolunteerEmail\n\t//Validates json\n\tif err := c.BindJSON(&ve); err != nil {\n\t\tcreateBadRequestResponse(c, err)\n\t\treturn\n\t}\n\temail := ve.VolunteerEmail\n\n\t//Gets VolunteerEmail from database\n\terr := db.Raw(getCfgString(cSelectVolunteerEmail), ve.VolunteerEmail, identifier).Find(&ve).Error\n\tif err == nil {\n\t\tcreateStatusConflictResponse(c)\n\t\treturn\n\t}\n\n\t//Gets Team from database\n\tvar tm Team\n\tif err := db.Where(\"identifier = ?\", identifier).First(&tm).Error; err != nil {\n\t\tcreateInternalErrorResponse(c)\n\t\treturn\n\t}\n\n\t//Writes VolunterEmail to the database\n\tve = VolunteerEmail{tm.ID, email}\n\tif err := db.Create(&ve).Error; err != nil {\n\t\tcreateInternalErrorResponse(c)\n\t\treturn\n\t}\n\tc.JSON(200, ve)\n\n}", "func (m *EducationAssignment) SetLastModifiedBy(value IdentitySetable)() {\n m.lastModifiedBy = value\n}", "func (i *IssueEvent) GetAssigner() *User {\n\tif i == nil {\n\t\treturn nil\n\t}\n\treturn i.Assigner\n}", "func FindAssigneeByID(_id string) (Assignee, error) {\r\n\tvar assignee Assignee\r\n\tvar err error\r\n\r\n\tif assignee, err = repository.ReadAssigneeByID(_id); err != nil {\r\n\t\treturn assignee, &HttpError{http.StatusNotFound, \"Invalid assignee ID, assignee couldn't be found\"}\r\n\t}\r\n\r\n\treturn assignee, err\r\n}", "func AssignGoalToUser(db *sql.DB, email string, goal string) error {\n\tq := \"update users set goals=? where email=?\"\n\tif _, err := db.Exec(q, goal, email); err != nil {\n\t\treturn errors.Wrap(err, \"unable to set user goal in AssignGoalToUser\")\n\t}\n\treturn nil\n}", "func (wouo *WorkOrderUpdateOne) ClearAssignee() *WorkOrderUpdateOne {\n\twouo.assignee = nil\n\twouo.clearassignee = true\n\treturn wouo\n}", "func (wou *WorkOrderUpdate) ClearAssignee() *WorkOrderUpdate {\n\twou.assignee = nil\n\twou.clearassignee = true\n\treturn wou\n}", "func (m *ThreatAssessmentRequest) SetCreatedBy(value IdentitySetable)() {\n err := m.GetBackingStore().Set(\"createdBy\", value)\n if err != nil {\n panic(err)\n }\n}", "func (r a) Assign(company string, team string, engagement string, params map[string]string) (*http.Response, []byte) {\n return r.client.Put(\"/otask/v1/tasks/companies/\" + company + \"/teams/\" + team + \"/engagements/\" + engagement + \"/tasks\", params)\n}", "func NewAssigneeResponse() *AssigneeResponse {\n\tthis := AssigneeResponse{}\n\treturn &this\n}", "func (a *Aspect) NoteAssignedTo(r Entity) {\n\t// if a.Entity != nil && a.Entity != r {\n\t// \tpanic(errForeign)\n\t// }\n\ta.Entity = r\n}", "func (m *EducationAssignment) SetAssignDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() {\n m.assignDateTime = value\n}", "func (c *client) SetMilestone(org, repo string, issueNum, milestoneNum int) error {\n\tdurationLogger := c.log(\"SetMilestone\", org, repo, issueNum, milestoneNum)\n\tdefer durationLogger()\n\n\tissue := &struct {\n\t\tMilestone int `json:\"milestone\"`\n\t}{Milestone: milestoneNum}\n\n\t_, err := c.request(&request{\n\t\tmethod: http.MethodPatch,\n\t\tpath: fmt.Sprintf(\"/repos/%v/%v/issues/%d\", org, repo, issueNum),\n\t\torg: org,\n\t\trequestBody: &issue,\n\t\texitCodes: []int{200},\n\t}, nil)\n\treturn err\n}", "func SetUserReviewer(db *sql.DB, userEmail string, eligibleReviewer string, cycle string) error {\n\tq := `\n INSERT INTO review_requests\n (recipient_id,\n reviewer_id,\n cycle_id)\n VALUES ((SELECT id\n FROM users\n WHERE email =?\n LIMIT 1),\n (SELECT id\n FROM users\n WHERE email =?\n LIMIT 1),\n (SELECT id\n FROM review_cycles\n WHERE name =?\n LIMIT 1))\n `\n\tif _, err := db.Exec(q, userEmail, eligibleReviewer, cycle); err != nil {\n\t\treturn errors.Wrap(err, \"unable to set review request in SetUserReviewer\")\n\t}\n\treturn nil\n}", "func (_Authority *AuthorityTransactor) SetOwner(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) {\n\treturn _Authority.contract.Transact(opts, \"setOwner\", newOwner)\n}", "func (o *AssigneeResponse) SetAssignees(v []ViewFormAssignee) {\n\to.Assignees = &v\n}", "func (o *WatchlistScreeningIndividualUpdateResponse) GetAssigneeOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Assignee.Get(), o.Assignee.IsSet()\n}", "func responsiblePerson(mr *gitlab.MergeRequest, reviewers map[string]string) string {\n\tif mr.Assignee != nil && mr.Assignee.Username != \"\" {\n\t\tif assignee, ok := reviewers[mr.Assignee.Username]; ok {\n\t\t\treturn assignee\n\t\t}\n\t}\n\n\tif mr.Author == nil {\n\t\treturn \"\"\n\t}\n\n\tif author, ok := reviewers[mr.Author.Username]; ok {\n\t\treturn author\n\t}\n\n\treturn mr.Author.Name\n}", "func (m *EducationAssignment) GetCreatedBy()(IdentitySetable) {\n return m.createdBy\n}", "func (m *EducationAssignment) GetAssignTo()(EducationAssignmentRecipientable) {\n return m.assignTo\n}", "func (m *PlannerAssignedToTaskBoardTaskFormat) SetOrderHintsByAssignee(value PlannerOrderHintsByAssigneeable)() {\n m.orderHintsByAssignee = value\n}", "func (s *Selection) AssignElevator(req common.MasterAssignRequest, reply *common.MasterAssignReply) error {\n\tlog.Println(\"Selection.AssignElevator():\")\n\tlog.Println(\"Selection.AssignElevator(): Request: NumPeople: \", req.NumPeople, \", Floor: \", req.Floor)\n\n\te := &common.Elevator {\n\t\tIsActive : true,\n\t\tCurrentFloor : 5,\n\t\tLastChecked : time.Now(),\n\t\tDirection : common.DOWN,\n\t}\n\n\treply.Elevator = e\n\n//\tlog.Println(\"Selection.AssignElevator(): Reply: \", e)\n\n\treturn nil\n}", "func (c *client) CreateIssue(org, repo, title, body string, milestone int, labels, assignees []string) (int, error) {\n\tdurationLogger := c.log(\"CreateIssue\", org, repo, title)\n\tdefer durationLogger()\n\n\tdata := struct {\n\t\tTitle string `json:\"title,omitempty\"`\n\t\tBody string `json:\"body,omitempty\"`\n\t\tMilestone int `json:\"milestone,omitempty\"`\n\t\tLabels []string `json:\"labels,omitempty\"`\n\t\tAssignees []string `json:\"assignees,omitempty\"`\n\t}{\n\t\tTitle: title,\n\t\tBody: body,\n\t\tMilestone: milestone,\n\t\tLabels: labels,\n\t\tAssignees: assignees,\n\t}\n\tvar resp struct {\n\t\tNum int `json:\"number\"`\n\t}\n\t_, err := c.request(&request{\n\t\t// allow the description and draft fields\n\t\t// https://developer.github.com/changes/2019-02-14-draft-pull-requests/\n\t\taccept: \"application/vnd.github+json, application/vnd.github.shadow-cat-preview\",\n\t\tmethod: http.MethodPost,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/issues\", org, repo),\n\t\torg: org,\n\t\trequestBody: &data,\n\t\texitCodes: []int{201},\n\t}, &resp)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn resp.Num, nil\n}", "func (m *SequentialActivationRenewalsAlertIncident) GetAssigneeId()(*string) {\n val, err := m.GetBackingStore().Get(\"assigneeId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (c *Client) Assign(ctx context.Context, id uint64, role NodeRole) error {\n\trequest := protocol.Message{}\n\tresponse := protocol.Message{}\n\n\trequest.Init(4096)\n\tresponse.Init(4096)\n\n\tprotocol.EncodeAssign(&request, id, uint64(role))\n\n\tif err := c.protocol.Call(ctx, &request, &response); err != nil {\n\t\treturn err\n\t}\n\n\tif err := protocol.DecodeEmpty(&response); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (mr *MockClientMockRecorder) AssignIssue(org, repo, number, logins interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AssignIssue\", reflect.TypeOf((*MockClient)(nil).AssignIssue), org, repo, number, logins)\n}", "func (c *RollbarAPIClient) AssignUserToTeam(teamID, userID int) error {\n\tl := log.With().Int(\"userID\", userID).Int(\"teamID\", teamID).Logger()\n\tl.Debug().Msg(\"Assigning user to team\")\n\tresp, err := c.Resty.R().\n\t\tSetPathParams(map[string]string{\n\t\t\t\"teamID\": strconv.Itoa(teamID),\n\t\t\t\"userID\": strconv.Itoa(userID),\n\t\t}).\n\t\tSetError(ErrorResult{}).\n\t\tPut(c.BaseURL + pathTeamUser)\n\tif err != nil {\n\t\tl.Err(err).Msg(\"Error assigning user to team\")\n\t\treturn err\n\t}\n\terr = errorFromResponse(resp)\n\tif err != nil {\n\t\t// API returns status `403 Forbidden` on invalid user to team assignment\n\t\t// https://github.com/rollbar/terraform-provider-rollbar/issues/66\n\t\tif resp.StatusCode() == http.StatusForbidden {\n\t\t\tl.Err(err).Msg(\"Team or user not found\")\n\t\t\treturn ErrNotFound\n\t\t}\n\t\tl.Err(err).Msg(\"Error assigning user to team\")\n\t\treturn err\n\t}\n\tl.Debug().Msg(\"Successfully assigned user to team\")\n\treturn nil\n}", "func (m *EducationSubmissionResource) SetAssignmentResourceUrl(value *string)() {\n err := m.GetBackingStore().Set(\"assignmentResourceUrl\", value)\n if err != nil {\n panic(err)\n }\n}", "func (group *Group) SetOwner(ownerID int) error {\n\tsite := NewSite(\n\t\tgroup.client,\n\t\tfmt.Sprintf(\"%s/_api/Site\", group.client.AuthCnfg.GetSiteURL()),\n\t\tgroup.config,\n\t)\n\n\tcg, err := group.Select(\"Id\").Get()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar principal struct {\n\t\tContentType struct {\n\t\t\tName string\n\t\t}\n\t}\n\n\tpType := \"group\"\n\tpData, err := site.RootWeb().UserInfoList().Items().Expand(\"ContentType\").Filter(fmt.Sprintf(\"Id eq %d\", ownerID)).Get()\n\tif err != nil {\n\t\treturn nil\n\t}\n\tif len(pData.Data()) > 0 {\n\t\tif err := json.Unmarshal(pData.Data()[0].Normalized(), &principal); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif principal.ContentType.Name == \"Person\" {\n\t\t\tpType = \"user\"\n\t\t}\n\t}\n\n\tb := csom.NewBuilder()\n\two, _ := b.AddObject(csom.NewObjectProperty(\"Web\"), nil)\n\tsg, _ := b.AddObject(csom.NewObjectProperty(\"SiteGroups\"), wo)\n\tgr, _ := b.AddObject(csom.NewObjectMethod(\"GetById\", []string{fmt.Sprintf(`<Parameter Type=\"Number\">%d</Parameter>`, cg.Data().ID)}), sg)\n\towner := csom.NewObjectMethod(\"GetById\", []string{fmt.Sprintf(`<Parameter Type=\"Number\">%d</Parameter>`, ownerID)})\n\n\tif pType == \"group\" {\n\t\towner, _ = b.AddObject(owner, sg)\n\t} else {\n\t\tsu, _ := b.AddObject(csom.NewObjectProperty(\"SiteUsers\"), wo)\n\t\towner, _ = b.AddObject(owner, su)\n\t}\n\t_, _ = b.Compile() // force object nodes IDs calc\n\n\tb.AddAction(csom.NewAction(fmt.Sprintf(`\n\t\t<SetProperty Id=\"{{.ID}}\" ObjectPathId=\"{{.ObjectID}}\" Name=\"Owner\">\n\t\t\t<Parameter ObjectPathId=\"%d\" />\n\t\t</SetProperty>\n\t`, owner.GetID())), gr)\n\tb.AddAction(csom.NewAction(`<Method Name=\"Update\" Id=\"{{.ID}}\" ObjectPathId=\"{{.ObjectID}}\" />`), gr)\n\n\tcsomPkg, err := b.Compile()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient := NewHTTPClient(group.client)\n\t_, err = client.ProcessQuery(group.client.AuthCnfg.GetSiteURL(), bytes.NewBuffer([]byte(csomPkg)), group.config)\n\n\treturn err\n}", "func (m *MockServiceBoard) AssignUser(arg0 models.TaskAssignerInput) (models.UserOutsideShort, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AssignUser\", arg0)\n\tret0, _ := ret[0].(models.UserOutsideShort)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *ExternalActivity) SetPerformedBy(value Identityable)() {\n err := m.GetBackingStore().Set(\"performedBy\", value)\n if err != nil {\n panic(err)\n }\n}", "func (u Users) Assign(role RoleInterface, userID Owner, _ interface{}) (int64, error) {\n\tvar err error\n\tvar roleID int64\n\n\tif _, ok := userID.(string); ok {\n\t\tif userID.(string) == \"\" {\n\t\t\treturn 0, ErrUserRequired\n\t\t}\n\t} else if _, ok := userID.(int64); ok {\n\t\tif userID.(int64) == 0 {\n\t\t\treturn 0, ErrUserRequired\n\t\t}\n\t}\n\n\tif _, ok := role.(int64); ok {\n\t\troleID = role.(int64)\n\t} else if _, ok := role.(string); ok {\n\t\tif role.(string)[:1] == \"/\" {\n\t\t\troleID, err = u.rbac.Roles().GetRoleID(role.(string))\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t} else {\n\t\t\troleID, err = u.rbac.Roles().TitleID(role.(string))\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t}\n\t}\n\n\tif roleID > 0 {\n\t\tvar query = fmt.Sprintf(\"INSERT INTO %s (user_id, role_id, assignment_date) VALUES(?,?,?)\", u.getTable())\n\t\tres, err := u.rbac.db.Exec(query, userID, roleID, time.Now().Nanosecond())\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tinsertID, _ := res.LastInsertId()\n\n\t\treturn insertID, nil\n\t}\n\n\treturn 0, fmt.Errorf(\"role could not be found\")\n}", "func SetPermission(fileID, email, perm string) (err error) {\n\tcnt := auth.GetClient()\n\n\tsrv, err := drive.New(cnt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprf, err := GetUserDoc(fileID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif prf.Owner1 == email || prf.Owner2 == email {\n\t\ttemp, err := srv.Permissions.GetIdForEmail(email).Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = srv.Permissions.Update(fileID, temp.Id, &drive.Permission{\n\t\t\tValue: email,\n\t\t\tRole: perm,\n\t\t\tType: \"user\",\n\t\t}).Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t_, err := srv.Permissions.Insert(fileID, &drive.Permission{\n\t\t\tValue: email,\n\t\t\tRole: perm,\n\t\t\tType: \"user\",\n\t\t}).SendNotificationEmails(false).Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *EducationAssignment) SetAssignedDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() {\n m.assignedDateTime = value\n}", "func (mr *MockIssueClientMockRecorder) AssignIssue(org, repo, number, logins interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AssignIssue\", reflect.TypeOf((*MockIssueClient)(nil).AssignIssue), org, repo, number, logins)\n}", "func (p *PullrequestAssignee) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t//&validators.StringIsPresent{Field: p.PullrequestID, Name: \"PullrequestID\"},\n\t//&validators.StringIsPresent{Field: p.AssigneeID, Name: \"AssigneeID\"},\n\t), nil\n}", "func (o *AssigneeFormAssigneesResponse) SetAssignees(v []ViewFormAssignee) {\n\to.Assignees = &v\n}", "func AssignTeamToUser(db *sql.DB, email string, team string) error {\n\tteams, err := GetUsersTeams(db, email)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to fetch teams for comparison in AssignTeamToUser\")\n\t}\n\tif inList(team, teams) {\n\t\t// user already associated with this team\n\t\treturn nil\n\t}\n\n\tq := `\n INSERT INTO user_teams\n (user_id,\n team_id)\n VALUES ((SELECT id\n FROM users\n WHERE email =?\n LIMIT 1),\n (SELECT id\n FROM teams\n WHERE name =?\n LIMIT 1))\n `\n\tif _, err := db.Exec(q, email, team); err != nil {\n\t\treturn errors.Wrap(err, \"unable to assign team in AssignTeamToUser\")\n\t}\n\treturn nil\n}", "func (_SweetToken *SweetTokenTransactor) SetOwner(opts *bind.TransactOpts, owner_ common.Address) (*types.Transaction, error) {\n\treturn _SweetToken.contract.Transact(opts, \"setOwner\", owner_)\n}", "func setOwner(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tvar err error\n\tfmt.Println(\"starting set_owner\")\n\n\tif len(args) != 2 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 2\")\n\t}\n\n\treceiptId := args[0]\n\townerId := args[1]\n\tfmt.Println(receiptId + \"->\" + ownerId)\n\n\t// check if user already exists\n\towner, err := getOwner(stub, ownerId)\n\tif err != nil {\n\t\treturn shim.Error(\"This owner does not exist - \" + ownerId)\n\t}\n\n\t// get receipt's current state\n\treceiptAsBytes, err := stub.GetState(receiptId)\n\tif err != nil {\n\t\treturn shim.Error(\"Failed to get Receipt\")\n\t}\n\tres := Receipt{}\n\tjson.Unmarshal(receiptAsBytes, &res)\n\n\tres.OwnerRelation.Id = owner.Id\n\tres.OwnerRelation.Username = owner.Username\n\n\tjsonAsBytes, _ := json.Marshal(res)\n\terr = stub.PutState(args[0], jsonAsBytes)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tfmt.Println(\"- end set owner\")\n\treturn shim.Success(nil)\n}", "func (m *ManagementTemplateStep) SetCreatedByUserId(value *string)() {\n err := m.GetBackingStore().Set(\"createdByUserId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *SequentialActivationRenewalsAlertIncident) GetAssigneeUserPrincipalName()(*string) {\n val, err := m.GetBackingStore().Get(\"assigneeUserPrincipalName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func setCreatedBy(ctx context.Context, resource corev2.Resource) {\n\tmeta := resource.GetObjectMeta()\n\tif claims := jwt.GetClaimsFromContext(ctx); claims != nil {\n\t\tmeta.CreatedBy = claims.StandardClaims.Subject\n\t\tresource.SetObjectMeta(meta)\n\t}\n}", "func (u *user) changeEmail(email string) {\n u.email = email\n}", "func (r a) AssignToEngagement(engagementRef string, params map[string]string) (*http.Response, []byte) {\n return r.client.Put(\"/tasks/v2/tasks/contracts/\" + engagementRef, params)\n}", "func (_ProjectWalletAuthoriser *ProjectWalletAuthoriserTransactor) SetAuthoriser(opts *bind.TransactOpts, _authoriser common.Address) (*types.Transaction, error) {\n\treturn _ProjectWalletAuthoriser.contract.Transact(opts, \"setAuthoriser\", _authoriser)\n}", "func (m *AgreementAcceptance) SetUserEmail(value *string)() {\n m.userEmail = value\n}", "func (cli *OpsGenieAlertV2Client) Assign(req alertsv2.AssignAlertRequest) (*AsyncRequestResponse, error) {\n\treturn cli.sendAsyncPostRequest(&req)\n}", "func (m *UnifiedRoleAssignmentScheduleRequest) SetPrincipal(value DirectoryObjectable)() {\n m.principal = value\n}", "func (j *DSGitHub) ProcessIssue(ctx *Ctx, inIssue map[string]interface{}) (issue map[string]interface{}, err error) {\n\tissue = inIssue\n\tissue[\"user_data\"] = map[string]interface{}{}\n\tissue[\"assignee_data\"] = map[string]interface{}{}\n\tissue[\"assignees_data\"] = []interface{}{}\n\tissue[\"comments_data\"] = []interface{}{}\n\tissue[\"reactions_data\"] = []interface{}{}\n\t// [\"user\", \"assignee\", \"assignees\", \"comments\", \"reactions\"]\n\tuserLogin, ok := Dig(issue, []string{\"user\", \"login\"}, false, true)\n\tif ok {\n\t\tissue[\"user_data\"], _, err = j.githubUser(ctx, userLogin.(string))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tassigneeLogin, ok := Dig(issue, []string{\"assignee\", \"login\"}, false, true)\n\tif ok {\n\t\tissue[\"assignee_data\"], _, err = j.githubUser(ctx, assigneeLogin.(string))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tiAssignees, ok := Dig(issue, []string{\"assignees\"}, false, true)\n\tif ok {\n\t\tassignees, _ := iAssignees.([]interface{})\n\t\tassigneesAry := []map[string]interface{}{}\n\t\tfor _, assignee := range assignees {\n\t\t\taLogin, ok := Dig(assignee, []string{\"login\"}, false, true)\n\t\t\tif ok {\n\t\t\t\tassigneeData, _, e := j.githubUser(ctx, aLogin.(string))\n\t\t\t\tif e != nil {\n\t\t\t\t\terr = e\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tassigneesAry = append(assigneesAry, assigneeData)\n\t\t\t}\n\t\t}\n\t\tissue[\"assignees_data\"] = assigneesAry\n\t}\n\tnumber, ok := Dig(issue, []string{\"number\"}, false, true)\n\tif ok {\n\t\tissue[\"comments_data\"], err = j.githubIssueComments(ctx, j.Org, j.Repo, int(number.(float64)))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tiCnt, ok := Dig(issue, []string{\"reactions\", \"total_count\"}, false, true)\n\t\tif ok {\n\t\t\tissue[\"reactions_data\"] = []interface{}{}\n\t\t\tcnt := int(iCnt.(float64))\n\t\t\tif cnt > 0 {\n\t\t\t\tissue[\"reactions_data\"], err = j.githubIssueReactions(ctx, j.Org, j.Repo, int(number.(float64)))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (m *ScheduleChangeRequest) SetSenderUserId(value *string)() {\n err := m.GetBackingStore().Set(\"senderUserId\", value)\n if err != nil {\n panic(err)\n }\n}", "func FindAssigneeIDByName(name string) string {\r\n\tvar assignee Assignee\r\n\tvar err error\r\n\r\n\tif assignee, err = repository.ReadAssigneeByName(name); err != nil {\r\n\t\treturn \"\"\r\n\t}\r\n\r\n\treturn assignee.ID\r\n}", "func doAssign(be pb.BackendClient) {\n\n\tfor {\n\t\tmatch := <-matches\n\t\tids := []string{}\n\t\tfor _, t := range match.Tickets {\n\t\t\tids = append(ids, t.Id)\n\t\t}\n\n\t\treq := &pb.AssignTicketsRequest{\n\t\t\tTicketIds: ids,\n\t\t\tAssignment: &pb.Assignment{\n\t\t\t\tConnection: fmt.Sprintf(\"%d.%d.%d.%d:2222\", rand.Intn(256), rand.Intn(256), rand.Intn(256), rand.Intn(256)),\n\t\t\t},\n\t\t}\n\n\t\tif _, err := be.AssignTickets(context.Background(), req); err != nil {\n\t\t\terrMsg := fmt.Sprintf(\"failed to assign tickets: %w\", err)\n\t\t\terrRead, ok := errMap.Load(errMsg)\n\t\t\tif !ok {\n\t\t\t\terrRead = 0\n\t\t\t}\n\t\t\terrMap.Store(errMsg, errRead.(int)+1)\n\t\t}\n\n\t\tatomic.AddUint64(&assigned, uint64(len(ids)))\n\t\tfor _, id := range ids {\n\t\t\tdeleteIds <- id\n\t\t}\n\t}\n}", "func (m *Drive) SetOwner(value IdentitySetable)() {\n m.owner = value\n}", "func (u *user) changeEmail(email string) {\n u.email = email\n}", "func (k Keeper) SetOwner(ctx sdk.Context, name string, owner sdk.AccAddress) {\n\twhois := k.GetWhois(ctx, name)\n\twhois.Owner = owner\n\tk.SetWhois(ctx, name, whois)\n}", "func (k Keeper) SetOwner(ctx sdk.Context, name string, owner sdk.AccAddress) {\n\twhois := k.GetWhois(ctx, name)\n\twhois.Owner = owner\n\tk.SetWhois(ctx, name, whois)\n}", "func (m *ScheduleChangeRequest) SetManagerUserId(value *string)() {\n err := m.GetBackingStore().Set(\"managerUserId\", value)\n if err != nil {\n panic(err)\n }\n}", "func setOwnerRef(r *unstructured.Unstructured, set *apps.ResourceSet) {\n\tvar newRefs []metav1.OwnerReference\n\tfor _, or := range r.GetOwnerReferences() {\n\t\tif or.APIVersion != \"apps.cloudrobotics.com/v1alpha1\" || or.Kind != \"ResourceSet\" {\n\t\t\tnewRefs = append(newRefs, or)\n\t\t}\n\t}\n\t_true := true\n\tnewRefs = append(newRefs, metav1.OwnerReference{\n\t\tAPIVersion: \"apps.cloudrobotics.com/v1alpha1\",\n\t\tKind: \"ResourceSet\",\n\t\tName: set.Name,\n\t\tUID: set.UID,\n\t\tBlockOwnerDeletion: &_true,\n\t})\n\tr.SetOwnerReferences(newRefs)\n}", "func (f AssignedFilter) ApplyIssue(context operations.Context, issue *github.Issue) bool {\n\treturn f.isAssigned == (issue.Assignee != nil)\n}", "func TestGitHubIssueMapping(t *testing.T) {\n\t// given\n\tresource.Require(t, resource.UnitTest)\n\tvar gitData = []remoteData{\n\t\t// JSON data file of Github issue with assignee to test that the data is getting correctly Mapped through the Map function\n\t\t// Github Issue API URL for the respective JSON data file to update the cache\n\t\t{\"github_issue_with_assignee.json\", true, \"http://api.github.com/repos/fabric8-wit-test/fabric8-wit-test-unit/issues/2\"},\n\t\t// JSON data file of Github issue with assignee and label\n\t\t// Issue API URL for the respective JSON file to update the cache\n\t\t{\"github_issue_with_assignee_labels.json\", true, \"https://api.github.com/repos/fabric8-wit-unit-test/fabric8-wit-test/issues/1\"},\n\t}\n\t// when/then\n\tfor _, j := range gitData {\n\t\tdoTestIssueMapping(t, j, remoteworkitem.ProviderGithub)\n\t}\n}", "func (r *Repository) GetAssigneesURL() string {\n\tif r == nil || r.AssigneesURL == nil {\n\t\treturn \"\"\n\t}\n\treturn *r.AssigneesURL\n}", "func (c *Seaweed) Assign(args url.Values) (result *AssignResult, err error) {\n\tjsonBlob, _, err := c.client.get(encodeURI(*c.master, \"/dir/assign\", args), nil)\n\tif err == nil {\n\t\tresult = &AssignResult{}\n\t\tif err = json.Unmarshal(jsonBlob, result); err != nil {\n\t\t\terr = fmt.Errorf(\"/dir/assign result JSON unmarshal error:%v, json:%s\", err, string(jsonBlob))\n\t\t} else if result.Count == 0 {\n\t\t\terr = errors.New(result.Error)\n\t\t}\n\t}\n\n\treturn\n}" ]
[ "0.7824912", "0.7743104", "0.73689044", "0.73582506", "0.7141999", "0.68957514", "0.68766004", "0.67772126", "0.6706829", "0.66746527", "0.66430116", "0.6564776", "0.64136", "0.633491", "0.6322022", "0.6214112", "0.61791426", "0.6134709", "0.61321056", "0.610459", "0.60129243", "0.5996689", "0.59730995", "0.5928421", "0.5922199", "0.58906835", "0.5888426", "0.58274853", "0.5793441", "0.57652205", "0.57533324", "0.5690994", "0.56859714", "0.5672067", "0.5642607", "0.5599856", "0.55441207", "0.551617", "0.5492026", "0.54914844", "0.5449781", "0.5414184", "0.53964293", "0.53697044", "0.53684455", "0.53637195", "0.5358635", "0.53340226", "0.53295857", "0.532186", "0.530363", "0.530212", "0.5239058", "0.5238825", "0.51948535", "0.51945007", "0.51826966", "0.51793337", "0.51732016", "0.51555157", "0.5151186", "0.5141608", "0.51361704", "0.511457", "0.510275", "0.5068845", "0.50417405", "0.50404596", "0.50289", "0.50245774", "0.5018047", "0.5013402", "0.50105476", "0.50002897", "0.4975375", "0.49650237", "0.4958223", "0.49507168", "0.49412134", "0.49338117", "0.49153823", "0.49113125", "0.4871713", "0.48698038", "0.4860762", "0.48584694", "0.48520938", "0.48516846", "0.4848806", "0.48453173", "0.48439005", "0.48352903", "0.48234522", "0.48234522", "0.48173657", "0.48133847", "0.48092934", "0.48023576", "0.4800138", "0.47997108" ]
0.87511265
0
Auth ... Auth request to gh
func (g *GitHubImpl) Auth(user, pass string) (token string, err error) { perm, err := createGHPermissions() if err != nil { return "", err } req, _ := http.NewRequest("POST", g.URLNoEsc(urls.authURL), bytes.NewBuffer([]byte(perm))) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.SetBasicAuth(user, pass) body, err := NewPWRequest().Do(req) if err != nil { return "", err } re := Auth{} if err = json.Unmarshal(body, &re); err != nil { return "", err } return re.Token, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Client) Auth() (string, error) {\n\t// First do an empty get to get the auth challenge\n\treq, err := http.NewRequest(http.MethodGet, c.BaseURL+\"/v2/\", nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\trsp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed sending auth request: %w\", err)\n\t}\n\tdefer rsp.Body.Close()\n\tio.Copy(io.Discard, rsp.Body)\n\n\tif rsp.StatusCode == http.StatusOK {\n\t\t// no auth needed\n\t\treturn \"\", nil\n\t}\n\n\tif rsp.StatusCode != http.StatusUnauthorized {\n\t\treturn \"\", fmt.Errorf(\"unexpected status %s\", rsp.Status)\n\t}\n\n\t// The Www-Authenticate header tells us where to go to get a token\n\tvals, err := parseWWWAuthenticate(rsp.Header.Get(\"Www-Authenticate\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tu, err := url.Parse(vals[\"realm\"])\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not parse authentication realm: %w\", err)\n\t}\n\tq := u.Query()\n\tq.Set(\"service\", vals[\"service\"])\n\tq.Set(\"scope\", \"repository:\"+c.Name+\":pull,push\")\n\tu.RawQuery = q.Encode()\n\n\tfmt.Printf(\"get %s\\n\", u)\n\n\treq, err = http.NewRequest(http.MethodGet, u.String(), nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq.SetBasicAuth(c.User, c.Password)\n\n\trsp, err = http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed sending auth request: %w\", err)\n\t}\n\tdefer rsp.Body.Close()\n\tif rsp.StatusCode != http.StatusOK {\n\t\treturn \"\", fmt.Errorf(\"unexpected status %s\", rsp.Status)\n\t}\n\tbody, err := io.ReadAll(rsp.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not read auth response body: %w\", err)\n\t}\n\n\ttype token struct {\n\t\tToken string `json:\"token\"`\n\t}\n\tvar tok token\n\tif err := json.Unmarshal(body, &tok); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to unmarshal token: %w\", err)\n\t}\n\n\treturn tok.Token, nil\n}", "func (c *Client) auth(req *fasthttp.Request) error {\n\tif c.key == \"\" || len(c.secret) == 0 {\n\t\treturn errors.New(\"API key and secret not configured\")\n\t}\n\n\tvar payload bytes.Buffer\n\n\tts := strconv.FormatInt(unixTime(), 10)\n\n\tpayload.WriteString(ts)\n\tpayload.Write(req.Header.Method())\n\tpayload.Write(req.URI().RequestURI())\n\tif req.Body() != nil {\n\t\tpayload.Write(req.Body())\n\t}\n\n\thash := hmac.New(sha256.New, c.secret)\n\thash.Write(payload.Bytes())\n\n\treq.Header.Set(HeaderKey, c.key)\n\treq.Header.Set(HeaderSign, hex.EncodeToString(hash.Sum(nil)))\n\treq.Header.Set(HeaderTS, ts)\n\tif c.subaccount != \"\" {\n\t\treq.Header.Set(HeaderSubaccount, c.subaccount)\n\t}\n\treturn nil\n}", "func (o *SlackOAuthHandlers) Auth(w http.ResponseWriter, r *http.Request) {\n\tparams, err := url.ParseQuery(r.URL.RawQuery)\n\tif err != nil {\n\t\thlog.FromRequest(r).Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"parsing query params\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// An error is received when a user declines to install\n\t// or an unexpected issue occurs. The app treats a\n\t// declined install gracefully.\n\tif params[\"error\"] != nil {\n\t\tswitch params[\"error\"][0] {\n\t\tcase errAccessDenied:\n\t\t\thlog.FromRequest(r).Info().\n\t\t\t\tErr(errors.New(params[\"error\"][0])).\n\t\t\t\tMsg(\"user declined install\")\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\treturn\n\t\tdefault:\n\t\t\thlog.FromRequest(r).Error().\n\t\t\t\tErr(errors.New(params[\"error\"][0])).\n\t\t\t\tMsg(\"failed install\")\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\n\tcode := params[\"code\"]\n\tif len(code) != 1 {\n\t\thlog.FromRequest(r).Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"code not provided\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// TODO: inject an http client with http logging.\n\tresp, err := http.Get(fmt.Sprintf(\n\t\to.AccessURLTemplate,\n\t\to.ClientID,\n\t\to.ClientSecret,\n\t\tcode[0],\n\t))\n\tif err != nil {\n\t\thlog.FromRequest(r).Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"oauth req error\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvar access accessResponse\n\tif err := json.NewDecoder(resp.Body).Decode(&access); err != nil {\n\t\thlog.FromRequest(r).Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"unable to decode slack access response\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif !access.OK {\n\t\thlog.FromRequest(r).Warn().\n\t\t\tMsg(\"access not ok\")\n\t\tw.WriteHeader(http.StatusForbidden)\n\t\treturn\n\t}\n\n\terr = o.TokenWriter.Store(&TokenData{\n\t\tTeamID: access.TeamID,\n\t\tUserID: access.UserID,\n\t\tBotToken: access.Bot.BotAccessToken,\n\t\tBotUserID: access.Bot.BotUserID,\n\t\tAccessToken: access.AccessToken,\n\t})\n\tif err != nil {\n\t\thlog.FromRequest(r).Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"unable to store token\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tredirect := fmt.Sprintf(\"https://slack.com/app_redirect?app=%s\", o.AppID)\n\thttp.Redirect(w, r, redirect, http.StatusFound)\n}", "func (w Web) Auth(c *gin.Context) {\n\tif expectedHash, ok := c.GetQuery(\"hash\"); ok {\n\t\tvar errorMessage string\n\t\tvar datas []string\n\t\tfor k, v := range c.Request.URL.Query() {\n\t\t\tif k == \"hash\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdatas = append(datas, fmt.Sprintf(\"%s=%s\", k, v[0]))\n\t\t}\n\t\tsort.Strings(datas)\n\t\tmac := hmac.New(sha256.New, w.SecretKey[:])\n\t\tauthDataStr := strings.Join(datas, \"\\n\")\n\t\tio.WriteString(mac, authDataStr)\n\t\thash := fmt.Sprintf(\"%x\", mac.Sum(nil))\n\t\tif expectedHash != hash {\n\t\t\terrorMessage = \"data is not from Telegram\"\n\t\t} else if authDate, err := strconv.Atoi(c.Query(\"auth_date\")); err == nil {\n\t\t\tif int64(time.Now().Sub(time.Unix(int64(authDate), 0)).Seconds()) > 86400 {\n\t\t\t\terrorMessage = \"Data is outdated\"\n\t\t\t} else {\n\t\t\t\tw.setCookie(c, \"auth_data_str\", authDataStr)\n\t\t\t\tw.setCookie(c, \"auth_data_hash\", hash)\n\t\t\t\tuserid, err := strconv.ParseInt(c.Query(\"id\"), 10, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\t_logger.Printf(\"can not convert %s to int. err* %v\", c.Query(\"id\"), err)\n\t\t\t\t}\n\t\t\t\tmsg := tgbotapi.NewMessage(userid, fmt.Sprintf(\"hello https://t.me/%d, welcome to NS_FC_bot.\", userid))\n\t\t\t\t_, err = w.TgBotClient.Send(msg)\n\t\t\t\tif err != nil {\n\t\t\t\t\t_logger.Printf(\"send message to user telegram failed. err: %v\", err)\n\t\t\t\t}\n\t\t\t\tw.setCookie(c, \"authed\", \"true\")\n\t\t\t\tc.Redirect(http.StatusTemporaryRedirect, \"/user/\"+c.Query(\"id\"))\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\terrorMessage = err.Error()\n\t\t}\n\t\tc.Redirect(http.StatusTemporaryRedirect, \"/login?error=\"+errorMessage)\n\t\treturn\n\t}\n}", "func makeAuthRequest(apiKey string) string {\n\n\tclient := &http.Client{}\n\treq, _ := http.NewRequest(\"GET\", \"https://rep.checkpoint.com/rep-auth/service/v1.0/request\", nil)\n\treq.Header.Set(\"Client-Key\", apiKey)\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\t// log.Println(string(body))\n\treturn string(body)\n}", "func (c *config) Auth(token, secret string) (string, error) {\n\tclient := c.newClientToken(token, secret)\n\tuser, err := client.FindCurrent()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn user.Login, nil\n\t// creates a new http request to bitbucket.\n\t\n\t// var buf io.ReadWriter\n\t// req, err := http.NewRequest(\"GET\",\"https://api.bitbucket.org/2.0/user/\",buf)\n\t// if err != nil {\n\t// \treturn \"\",err\n\t// }\n\t// req.Header.Set(\"Authorization\", \"Basic ampxX3Rlc3Q6bkFEUFZtTThyRFEzRDUyUmNhSFE=\")\n\n\t// client := &http.Client{}\n\t// resp, err := client.Do(req)\n\t// if err != nil {\n\t// \treturn \"\",err\n\t// }\n\t// defer resp.Body.Close()\n\n\t// // if an error is encountered, parse and return the\n\t// // error response.\n\t// if resp.StatusCode > http.StatusPartialContent {\n\t// \terr := internal.Error{}\n\t// \tjson.NewDecoder(resp.Body).Decode(&err)\n\t// \terr.Status = resp.StatusCode\n\t// \treturn \"\",err\n\t// }\n\t// body, err := ioutil.ReadAll(resp.Body)\n // if err != nil {\n // // handle error\n // }\n\n\n\t// out := new(internal.Account)\n\t// // return json.NewDecoder(resp.Body).Decode(out),nil\n\t// json.Unmarshal(body,out)\n\n\t// log.Debug(out.Login)\n\t// return out.Login,err\n\n\t// log.Debug(\"resp is \",resp)\n\n\t// if a json response is expected, parse and return\n\t// the json response.\n\t// if out != nil {\n\t// \treturn json.NewDecoder(resp.Body).Decode(out)\n\t// }\n\t\n\t// return \"\", nil\n\n}", "func Auth(next handlers.HandlerFunc) handlers.HandlerFunc {\n\treturn func(env *handlers.Env, w http.ResponseWriter, r *http.Request) error {\n\t\tsignature, err := r.Cookie(\"signature\")\n\t\tif err != nil {\n\t\t\treturn handlers.StatusData{\n\t\t\t\tCode: http.StatusUnauthorized,\n\t\t\t\tData: map[string]string{\n\t\t\t\t\t\"error\": \"No signature cookie found\",\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\n\t\theaderPayload, err := r.Cookie(\"header.payload\")\n\t\tif err != nil {\n\t\t\treturn handlers.StatusData{\n\t\t\t\tCode: http.StatusUnauthorized,\n\t\t\t\tData: map[string]string{\n\t\t\t\t\t\"error\": \"No headerPayload cookie found\",\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\n\t\ttokenString := headerPayload.Value + \".\" + signature.Value\n\n\t\tctx := cnt.Background()\n\t\tauthManager := auth_proto.NewAuthCheckerClient(env.GRCPAuth)\n\t\ttoken, err := authManager.Check(ctx,\n\t\t\t&auth_proto.Token{\n\t\t\t\tToken: tokenString,\n\t\t\t})\n\n\t\tif err != nil {\n\t\t\tenv.Logger.Errorw(\"Error during grpc request\",\n\t\t\t\t\"err\", err.Error(),\n\t\t\t\t\"grpc\", \"user\",\n\t\t\t)\n\t\t\treturn handlers.StatusData{\n\t\t\t\tCode: http.StatusInternalServerError,\n\t\t\t\tData: map[string]string{\n\t\t\t\t\t\"error\": \"Internal server error\",\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\n\t\tif !token.Valid {\n\t\t\treturn handlers.StatusData{\n\t\t\t\tCode: http.StatusUnauthorized,\n\t\t\t\tData: map[string]string{\n\t\t\t\t\t\"error\": \"Token is not valid\",\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\n\t\tclaims := make(map[string]interface{})\n\t\terr = json.Unmarshal(token.Claims, &claims)\n\t\tif err != nil {\n\t\t\tenv.Logger.Warnw(\"Can't unmarshall data\",\n\t\t\t\t\"err\", err.Error(),\n\t\t\t\t\"data\", claims,\n\t\t\t\t\"json\", string(token.Claims),\n\t\t\t)\n\t\t\treturn handlers.StatusData{\n\t\t\t\tCode: http.StatusUnauthorized,\n\t\t\t\tData: map[string]string{\n\t\t\t\t\t\"error\": \"Token is not valid\",\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\n\t\tcontext.Set(r, \"claims\", claims)\n\n\t\treturn next(env, w, r)\n\t}\n}", "func GitHub(c *gin.Context) {\n\tc.Set(keyRedirect, auther.GetGitHubAuthURL())\n}", "func gitAuth() *http.BasicAuth {\n\n\tvar auth *http.BasicAuth\n\n\t// The username can be anything for HTTPS Git operations\n\tgitUsername := \"fanal-aquasecurity-scan\"\n\n\t// We first check if a GitHub token was provided\n\tgithubToken := os.Getenv(\"GITHUB_TOKEN\")\n\tif githubToken != \"\" {\n\t\tauth = &http.BasicAuth{\n\t\t\tUsername: gitUsername,\n\t\t\tPassword: githubToken,\n\t\t}\n\t\treturn auth\n\t}\n\n\t// Otherwise we check if a GitLab token was provided\n\tgitlabToken := os.Getenv(\"GITLAB_TOKEN\")\n\tif gitlabToken != \"\" {\n\t\tauth = &http.BasicAuth{\n\t\t\tUsername: gitUsername,\n\t\t\tPassword: gitlabToken,\n\t\t}\n\t\treturn auth\n\t}\n\n\t// If no token was provided, we simply return a nil,\n\t// which will make the request to be unauthenticated\n\treturn nil\n\n}", "func getGitHubAccessToken(w http.ResponseWriter, r *http.Request) {\n\t// Use the built in ioutil from io/ioutil to\n\t// read the request body into a []byte\n\tbody, err := ioutil.ReadAll(r.Body)\n\thelpers.HandleError(err)\n\n\t// Decode the JSON request body to our GHTokenReqBody\n\t// so we can use the session code\n\tvar tokenReqBody GHTokenReqBody\n\terr = json.Unmarshal(body, &tokenReqBody)\n\thelpers.HandleError(err)\n\n\t// 1. Grab the access token from GitHub using the session code\n\taccessToken, err := github.GetAccessToken(tokenReqBody.SessionCode)\n\thelpers.HandleError(err)\n\n\t// 2. Call the check token method with our new access token\n\t// to get the logged in users details\n\tcheckTokenResult, err := github.CheckToken(accessToken)\n\thelpers.HandleError(err)\n\n\t// 3: Check if the user exists using their GitHub user id, and either:\n\t// - Create a new user record if this is their first time logging in\n\t// - Get the existing users details\n\n\tvar user models.User\n\tif !db.GitHubUserExists(*checkTokenResult.User.Login) {\n\t\tuser = db.CreateUser(*checkTokenResult.User)\n\t} else {\n\t\tuser = db.GetUserByGitHubLogin(*checkTokenResult.User.Login)\n\t}\n\n\t// 4: Set a cookie containing the user's token\n\t// that we can use for future request, only\n\t// set the Secure attribute to true if not in\n\t// development mode\n\tisDev := os.Getenv(\"HOSTING_ENV\") == \"Development\"\n\ttokenCookieExpires := 30 * 24 * time.Hour\n\ttokenCookie := &http.Cookie{\n\t\tName: tokenCookieName,\n\t\tValue: accessToken,\n\t\tPath: \"/\",\n\t\tExpires: time.Now().Add(tokenCookieExpires),\n\t\tMaxAge: 0,\n\t\tSecure: !isDev,\n\t\tHttpOnly: true,\n\t\tSameSite: http.SameSiteStrictMode,\n\t\tUnparsed: []string{},\n\t}\n\thttp.SetCookie(w, tokenCookie)\n\tw.WriteHeader(http.StatusOK)\n\n\t// 5: Return the users details to the caller\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(user)\n}", "func (c *Client) auth() error {\n\tconst authEndpoint = apiEndpointBase + \"/v1/shim/login\"\n\tfprint, _ := json.Marshal(authVersion)\n\n\tauthRequest, _ := json.Marshal(authRequest{\n\t\tusername: c.Username,\n\t\tpassword: c.Password,\n\t\tfingerprint: string(fprint),\n\t})\n\n\tresp, err := http.DoPost(authEndpoint, basicAuth(c.Username, c.Password), authRequest)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tauthp := &authPayload{}\n\tif err := json.Unmarshal(resp, authp); err != nil {\n\t\treturn err\n\t}\n\n\tc.accessToken = authp.Oauth2.AccessToken\n\tc.expiry = time.Now().Add(time.Second * time.Duration(authp.Oauth2.ExpiresIn))\n\treturn nil\n}", "func AuthToken(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tfmt.Println(\"Remote Host: \", r.RemoteAddr)\n\n\t// Now, we create the JWT from the info in the query parameters\n\n\t// Extract parameters from encoded query parameter set\n\tvalues := r.URL.Query()\n\tif len(values) == 0 {\n\t\tpanic(\"Query string was empty (length 0) -- unable to parse query parameters and create Response\")\n\t}\n\n\tvar grantType, service, clientId, accessType, rawScope, refreshToken /*, username, password*/ string\n\n\tgrantType = values.Get(GRANT_TYPE)\n\tservice = values.Get(SERVICE)\n\tclientId = values.Get(CLIENT_ID)\n\taccessType = values.Get(ACCESS_TYPE)\n\trawScope = values.Get(SCOPE)\n\trefreshToken = values.Get(REFRESH_TOKEN)\n\t// ToDo -- Docker Registry Auth only (for now) uses the Password Authorization Grant Type\n\t// TODO need to refactor\n\t// see https://docs.docker.com/registry/spec/auth/oauth/\n\t//username = values.Get(USERNAME)\n\t//password = values.Get(PASSWORD)\n\n\n\t// debugging\n\tfmt.Println(grantType)\n\tfmt.Println(service)\n\tfmt.Println(clientId)\n\tfmt.Println(accessType)\n\tfmt.Println(rawScope)\n\tfmt.Println(refreshToken)\n\n\t// TODO this is where we would be handling AuthZ (make sure this user with this action in our ACL)\n\n\tfmt.Println(\"-----------------------------------\")\n\n\t// Handle creating the claim set\n\tvar scope []ScopeAccess\n\tclaimSet := &ClaimSet{\n\t\tIssuer: \"auth-server\", // the auth server -- this string has to directly match what is in the config file\n\t\tSubject: \"\",\n\t\tAudience: r.RemoteAddr, // the docker registry address\n\t\tExpirationTime: uint64(time.Now().Add(time.Minute * time.Duration(10)).Unix()), // always now + 10 minutes time\n\t\tNotBefore: uint64(time.Now().Unix()),\n\t\tIssuedAt: uint64(time.Now().Unix()),\n\t\tJwtId: RandomString(15),\n\t}\n\t// parse the access scope, and insert it into the claim set as needed\n\tscope, err := ParseScope(rawScope)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif len(scope) == 0 {\n\t\t// make sure it is a \"\" that gets encoded here, in the \"access\" part, since no scope was defined\n\t\t//claimSet.EmptyAccess = \"\"\n\t} else {\n\t\tclaimSet.Access = scope\n\t}\n\n\t// Make sure our weird use of Json is working\n\tjsonClaimSet, jsonErr := json.Marshal(claimSet)\n\tif jsonErr != nil {\n\t\tpanic(jsonErr)\n\t}\n\tfmt.Println(string(jsonClaimSet))\n\n\t// Create the \"kid\", from the DER encoded key\n\tderKeyAsBytes, err0 := ioutil.ReadFile(\"/root/go/src/dockerRegistryAuthServer/pkcs8_1024.der\")\n\tif err0 != nil {\n\t\tpanic(err0)\n\t}\n\t//fmt.Println(string(derKeyAsBytes)) //debugging\n\tkid := CreateKidFromDer(derKeyAsBytes)\n\n\t// Create the header, using the kid\n\theader := &JoseHeader{\n\t\tType: \"JWT\",\n\t\tAlgo: \"RS256\",\n\t\tKeyId: kid,\n\t}\n\n\t// Create the actual JWT, using the PEM encoded key, as well as claimset and header\n\ttoken := CreateRS256Token(claimSet, header, \"/root/go/src/dockerRegistryAuthServer/pkcs8_1024.pem\")\n\n\t// pack the token into the right header\n\tresponse := Response{\n\t\tAccessToken: token,\n\t\tExpiresIn: 600, // 600 seconds = 10 minutes\n\t\tScope: ScopeToResponse(scope),\n\t}\n\n\tif err := json.NewEncoder(w).Encode(response); err != nil {\n\t\tpanic(err)\n\t}\n}", "func DoAuth(request Request) (res Response, err error) {\n\tparams, _ := json.Marshal(request)\n\tparamstr := string(params)\n\treq, _ := http.NewRequest(\"POST\", tokenAPI, strings.NewReader(paramstr))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept\", \"application/json\")\n\n\tclient := &http.Client{Timeout: time.Duration(15 * time.Second)}\n\thttpres, httperr := client.Do(req)\n\tif httperr != nil {\n\t\terr = httperr\n\t} else if httpres.StatusCode == 200 {\n\t\tbodyBytes, _ := ioutil.ReadAll(httpres.Body)\n\t\tjson.Unmarshal(bodyBytes, &res)\n\t}\n\n\treturn\n}", "func bungieAuth(c *gin.Context) {\n discordID := c.Query(\"id\")\n\n bungieAuthURL := \"https://www.bungie.net/en/OAuth/Authorize?client_id=\" +\n os.Getenv(\"CLIENT_ID\") +\n \"&response_type=code\" +\n \"&state=\" + discordID\n\n c.Redirect(http.StatusMovedPermanently, bungieAuthURL)\n}", "func OAUTHRedirect(ctx *fiber.Ctx) error {\n\n\tmodels.SYSLOG.Tracef(\"entering OAUTHRedirect; original URL: %v\", ctx.OriginalURL())\n\tdefer models.SYSLOG.Trace(\"exiting OAUTHRedirect\")\n\n\t// First, we need to get the value of the `code` query param\n\tcode := ctx.Query(\"code\", \"\")\n\tif len(code) < 1 {\n\t\treturn ctx.SendStatus(fiber.StatusBadRequest)\n\t}\n\n\t// Next, lets for the HTTP request to call the github oauth enpoint\tto get our access token\n\n\ta := fiber.AcquireAgent()\n\treq := a.Request()\n\treq.Header.SetMethod(fiber.MethodPost)\n\treq.Header.Set(\"accept\", \"application/json\")\n\treq.SetRequestURI(fmt.Sprintf(\"https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s\", models.ClientID, models.ClientSecret, code))\n\tif err := a.Parse(); err != nil {\n\t\tmodels.SYSLOG.Errorf(\"could not create HTTP request: %v\", err)\n\t}\n\n\tvar retCode int\n\tvar retBody []byte\n\tvar errs []error\n\t// Send out the HTTP request\n\tvar t *models.OAuthAccessResponse\n\n\tif retCode, retBody, errs = a.Struct(&t); len(errs) > 0 {\n\t\tmodels.SYSLOG.Tracef(\"received: %v\", string(retBody))\n\t\tmodels.SYSLOG.Errorf(\"could not send HTTP request: %v\", errs)\n\t\treturn ctx.SendStatus(fiber.StatusInternalServerError)\n\t}\n\tmodels.SYSLOG.Tracef(\"received : %v %v %v\", retCode, string(retBody), errs)\n\n\tvar sess *session.Session\n\tvar err error\n\t// Finally, send a response to redirect the user to the \"welcome\" page with the access token\n\tif sess, err = models.MySessionStore.Get(ctx); err == nil {\n\t\tsess.Set(\"token\", t.AccessToken)\n\t\tmodels.SYSLOG.Tracef(\"setting session token %v\", t.AccessToken)\n\t\tsessData, _ := models.MySessionStore.Get(ctx)\n\t\tdefer sessData.Save()\n\t\t//models.MySessionStore.RegisterType(models.OAuthAccessResponse)\n\t\tsessData.Set(\"oauth-scope\", t.Scope)\n\t\tsessData.Set(\"oauth-token-type\", t.TokenType)\n\t\tsessData.Set(\"oauth-token\", t.AccessToken)\n\n\t\tif err != nil {\n\t\t\tmodels.SYSLOG.Errorf(\"session saving exception %v\", err)\n\t\t}\n\t\tmodels.SYSLOG.Tracef(\"redirecting to /welcome.html?access_token=%v\", t.AccessToken)\n\t\t//\t\treturn ctx.Redirect(\"/welcome.html?access_token=\"+t.AccessToken, fiber.StatusFound)\n\t\treturn ctx.Redirect(\"/welcome.html\", fiber.StatusFound)\n\t}\n\n\tmodels.SYSLOG.Tracef(\"redirecting to /\")\n\treturn ctx.Redirect(\"/\", fiber.StatusTemporaryRedirect)\n}", "func Auth(ctx context.Context, clientSecretKeyFile []byte) error {\n\tconfig, err := google.ConfigFromJSON(clientSecretKeyFile, []string{builderAPIScope}...)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Get OAuth2 token from the user. It will be written into cacheFilename.\n\ttokenCacheFilename, err := tokenCacheFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Check the shell is appropriate for use of launched browsers, otherwise present the copy/paste\n\t// flow.\n\tnonSSH := checkShell()\n\tnotWindows := runtime.GOOS != \"windows\"\n\ttok, err := token(ctx, config, tokenCacheFilename, nonSSH && notWindows)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := saveToken(tokenCacheFilename, tok); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *KeycloakClient) do(req *http.Request) (*http.Response, error) {\n\tlog.Println(req.Method + \" \" + req.URL.String())\n\treq.Header.Set(\"Authorization\", \"Bearer \"+c.token)\n\treturn http.DefaultClient.Do(req)\n}", "func (app *App) SetAuth(r *http.Request) {\n\n}", "func (req *Request) GenerateAuth(creds *Credentials) error {\r\n\thawkcreds := &hawk.Credentials{\r\n\t\tID: creds.UserID,\r\n\t\tKey: creds.APIKey,\r\n\t\tHash: sha256.New,\r\n\t}\r\n\r\n\tclientAuth := hawk.NewRequestAuth(req.request, hawkcreds, 0)\r\n\tclientAuth.Ext = creds.OrganizationID\r\n\r\n\tif req.request.Body != nil {\r\n\t\treqBody, err := ioutil.ReadAll(req.request.Body)\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t\treq.request.Body = ioutil.NopCloser(bytes.NewBuffer(reqBody))\r\n\t\tif len(reqBody) > 0 {\r\n\t\t\tlog.Debugf(\"[DEBUG] Payload: %s\", string(reqBody))\r\n\t\t\tpayloadHash := clientAuth.PayloadHash(\"application/json\")\r\n\t\t\tpayloadHash.Write(reqBody)\r\n\t\t\tclientAuth.SetHash(payloadHash)\r\n\t\t\treq.request.Header.Set(\"Content-Type\", \"application/json\")\r\n\t\t}\r\n\t}\r\n\r\n\treq.request.Header.Set(\"Authorization\", clientAuth.RequestHeader())\r\n\treq.request.Header.Set(\"Accept\", \"application/json\")\r\n\r\n\treturn nil\r\n}", "func (g *GitHubImpl) CheckAuth() (bool, error) {\n\n\tURL := fmt.Sprintf(g.URLNoEsc(urls.userRepo))\n\n\treq, _ := http.NewRequest(\"GET\", URL, nil)\n\tq := req.URL.Query()\n\tq.Add(\"access_token\", g.token)\n\treq.URL.RawQuery = q.Encode()\n\n\tclient := http.DefaultClient\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif res.StatusCode != http.StatusOK {\n\t\treturn false, errors.New(strconv.Itoa(res.StatusCode))\n\t}\n\treturn true, nil\n}", "func (c *APIController) AuthGoogle() {\n\tcode := c.Input().Get(\"code\")\n\tstate := c.Input().Get(\"state\")\n\taddition := c.Input().Get(\"addition\")\n\tRedirectURL := c.Input().Get(\"redirect_url\")\n\n\tvar resp Response\n\tvar res authResponse\n\tres.IsAuthenticated = true\n\n\tif state != beego.AppConfig.String(\"GoogleAuthState\") {\n\t\tres.IsAuthenticated = false\n\t\tresp = Response{Status: \"fail\", Msg: \"unauthorized\", Data: res}\n\t\tc.Data[\"json\"] = resp\n\t\tc.ServeJSON()\n\t\treturn\n\t}\n\n\tgoogleOauthConfig.RedirectURL = RedirectURL\n\n\t// https://github.com/golang/oauth2/issues/123#issuecomment-103715338\n\tctx := context.WithValue(oauth2.NoContext, oauth2.HTTPClient, httpClient)\n\ttoken, err := googleOauthConfig.Exchange(ctx, code)\n\tif err != nil {\n\t\tres.IsAuthenticated = false\n\t\tpanic(err)\n\t}\n\n\tresponse, err := httpClient.Get(\"https://www.googleapis.com/oauth2/v2/userinfo?alt=json&access_token=\" + token.AccessToken)\n\tdefer response.Body.Close()\n\tcontents, err := ioutil.ReadAll(response.Body)\n\n\tvar tempUser userInfoFromGoogle\n\terr = json.Unmarshal(contents, &tempUser)\n\tif err != nil {\n\t\tres.IsAuthenticated = false\n\t\tpanic(err)\n\t}\n\tres.Email = tempUser.Email\n\tres.Avatar = tempUser.Picture\n\n\tif addition == \"signup\" {\n\t\tuserId := object.HasGoogleAccount(res.Email)\n\t\tif userId != \"\" {\n\t\t\tif len(object.GetMemberAvatar(userId)) == 0 {\n\t\t\t\tavatar := UploadAvatarToOSS(res.Avatar, userId)\n\t\t\t\tobject.LinkMemberAccount(userId, \"avatar\", avatar)\n\t\t\t}\n\t\t\tc.SetSessionUser(userId)\n\t\t\tutil.LogInfo(c.Ctx, \"API: [%s] signed in\", userId)\n\t\t\tres.IsSignedUp = true\n\t\t} else {\n\t\t\tif userId := object.HasMail(res.Email); userId != \"\" {\n\t\t\t\tc.SetSessionUser(userId)\n\t\t\t\tutil.LogInfo(c.Ctx, \"API: [%s] signed in\", userId)\n\t\t\t\tres.IsSignedUp = true\n\t\t\t\t_ = object.LinkMemberAccount(userId, \"google_account\", tempUser.Email)\n\t\t\t} else {\n\t\t\t\tres.IsSignedUp = false\n\t\t\t}\n\t\t}\n\t\tres.Addition = res.Email\n\t\tresp = Response{Status: \"ok\", Msg: \"success\", Data: res}\n\t} else {\n\t\tmemberId := c.GetSessionUser()\n\t\tif memberId == \"\" {\n\t\t\tresp = Response{Status: \"fail\", Msg: \"no account exist\", Data: res}\n\t\t\tc.Data[\"json\"] = resp\n\t\t\tc.ServeJSON()\n\t\t\treturn\n\t\t}\n\t\tlinkRes := object.LinkMemberAccount(memberId, \"google_account\", res.Email)\n\t\tif linkRes {\n\t\t\tresp = Response{Status: \"ok\", Msg: \"success\", Data: linkRes}\n\t\t} else {\n\t\t\tresp = Response{Status: \"fail\", Msg: \"link account failed\", Data: linkRes}\n\t\t}\n\t\tif len(object.GetMemberAvatar(memberId)) == 0 {\n\t\t\tavatar := UploadAvatarToOSS(res.Avatar, memberId)\n\t\t\tobject.LinkMemberAccount(memberId, \"avatar\", avatar)\n\t\t}\n\t}\n\n\tc.Data[\"json\"] = resp\n\n\tc.ServeJSON()\n}", "func addAuthentication(req *http.Request) {\n\tif *ghAuthKey != \"\" {\n\t\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"token %s\", *ghAuthKey))\n\t} else {\n\t\treq.SetBasicAuth(*ghUserFl, *ghPassFl)\n\t}\n}", "func (a API) Auth(w http.ResponseWriter, r *http.Request, state string, redirect_url string) {\r\n\thttp.Redirect(w, r, a.AuthUrl(state, redirect_url), http.StatusFound)\r\n}", "func Auth() gin.HandlerFunc {\r\n\tif gin.Mode() == \"debug\" {\r\n\t\treturn func(c *gin.Context) { c.Next() }\r\n\t}\r\n\treturn func(c *gin.Context) {\r\n\t\tAccessKey := c.GetHeader(\"AccessKey\")\r\n\t\tif c.GetHeader(\"AccessKey\") == \"\" {\r\n\t\t\tAccessKey = c.GetHeader(\"Token\")\r\n\t\t}\r\n\r\n\t\tsession := sessions.Default(c)\r\n\t\tLoginUserID := session.Get(\"UserID\")\r\n\t\tIsLeader := session.Get(\"IsLeader\")\r\n\r\n\t\tfmt.Println(\"AccessKey: \", AccessKey)\r\n\t\tswitch AccessKey {\r\n\t\tcase \"\":\r\n\t\t\tif LoginUserID != nil {\r\n\t\t\t\tc.Set(\"UserID\", LoginUserID)\r\n\t\t\t\tc.Set(\"IsLeader\", IsLeader)\r\n\t\t\t\tc.Next()\r\n\t\t\t} else {\r\n\t\t\t\tsession := sessions.Default(c)\r\n\t\t\t\tUserID := session.Get(\"UserID\")\r\n\t\t\t\tIsLeader := session.Get(\"IsLeader\")\r\n\r\n\t\t\t\tfmt.Println(\"UserID, IsLeader\", UserID, IsLeader)\r\n\t\t\t\tif UserID == nil {\r\n\t\t\t\t\tc.JSON(http.StatusUnauthorized, gin.H{\"message\": \"Empty AccessKey Please authorize before requesting\"})\r\n\t\t\t\t\tc.Abort()\r\n\t\t\t\t}\r\n\t\t\t\tc.Set(\"UserID\", UserID)\r\n\t\t\t\tc.Set(\"IsLeader\", IsLeader)\r\n\t\t\t\tc.Next()\r\n\r\n\t\t\t}\r\n\r\n\t\tdefault:\r\n\t\t\tUserID, IsLeader, err := utils.LoadAccessKey(AccessKey)\r\n\r\n\t\t\tif LoginUserID != nil {\r\n\t\t\t\tc.Set(\"UserID\", UserID)\r\n\t\t\t\tc.Set(\"IsLeader\", IsLeader)\r\n\t\t\t\tc.Next()\r\n\t\t\t} else {\r\n\t\t\t\tif err != nil {\r\n\t\t\t\t\tc.JSON(http.StatusUnauthorized, gin.H{\"message\": \"Please authorize before requesting\"})\r\n\t\t\t\t\tc.Abort()\r\n\t\t\t\t}\r\n\r\n\t\t\t\tc.Set(\"UserID\", UserID)\r\n\t\t\t\tc.Set(\"IsLeader\", IsLeader)\r\n\r\n\t\t\t\tc.Next()\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "func (s *Server) auth(req *http.Request) (clientKey string, authed, peer bool, err error) {\n\tid := req.Header.Get(ID)\n\ttoken := req.Header.Get(Token)\n\tif id != \"\" && token != \"\" {\n\t\t// peer authentication\n\t\ts.peerLock.Lock()\n\t\tp, ok := s.peers[id]\n\t\ts.peerLock.Unlock()\n\n\t\tif ok && p.token == token {\n\t\t\treturn id, true, true, nil\n\t\t}\n\t}\n\n\tid, authed, err = s.authorizer(req)\n\treturn id, authed, false, err\n}", "func gh(user string) string {\n\treturn auth.GitHubPrefix + user\n}", "func authHandler(c *fb.Context, w http.ResponseWriter, r *http.Request) (int, error) {\n\tif c.Auth.Method == \"none\" {\n\t\t// NoAuth instances shouldn't call this method.\n\t\treturn 0, nil\n\t}\n\n\tif c.Auth.Method == \"proxy\" {\n\t\t// Receive the Username from the Header and check if it exists.\n\t\tu, err := c.Store.Users.GetByUsername(r.Header.Get(c.Auth.Header), c.NewFS)\n\t\tif err != nil {\n\t\t\treturn http.StatusForbidden, nil\n\t\t}\n\n\t\tc.User = u\n\t\treturn printToken(c, w)\n\t}\n\n\t// Receive the credentials from the request and unmarshal them.\n\tvar cred cred\n\n\tif r.Body == nil {\n\t\treturn http.StatusForbidden, nil\n\t}\n\n\terr := json.NewDecoder(r.Body).Decode(&cred)\n\tif err != nil {\n\t\treturn http.StatusForbidden, err\n\t}\n\n\t// Wenkun, Validate the token of user from cloud server and return JWT token.\n\tif c.Auth.Method != \"none\" {\n\t\tok, u := validateAuthByUserId(c, cred.Username)\n\t\tif !ok {\n\t\t\treturn http.StatusForbidden, nil\n\t\t}\n\n\t\tc.User = u\n\t\treturn printToken(c, w)\n\t}\n\n\t// If ReCaptcha is enabled, check the code.\n\tif len(c.ReCaptcha.Secret) > 0 {\n\t\tok, err := reCaptcha(c.ReCaptcha.Host, c.ReCaptcha.Secret, cred.ReCaptcha)\n\t\tif err != nil {\n\t\t\treturn http.StatusForbidden, err\n\t\t}\n\n\t\tif !ok {\n\t\t\treturn http.StatusForbidden, nil\n\t\t}\n\t}\n\n\t// Checks if the user exists.\n\tu, err := c.Store.Users.GetByUsername(cred.Username, c.NewFS)\n\tif err != nil {\n\t\treturn http.StatusForbidden, nil\n\t}\n\n\t// Checks if the password is correct.\n\tif !fb.CheckPasswordHash(cred.Password, u.Password) {\n\t\treturn http.StatusForbidden, nil\n\t}\n\n\tc.User = u\n\treturn printToken(c, w)\n}", "func (a *authClient) Do(req *http.Request) (*http.Response, error) {\n\t// TODO if we still have a valid token, try using it first\n\ttoken := jwt.New(jwt.SigningMethodRS256)\n\ttoken.Claims[\"uid\"] = a.config.ID\n\ttoken.Claims[\"exp\"] = time.Now().Add(time.Hour).Unix()\n\t// SignedString will treat secret as PEM-encoded key\n\ttokenStr, err := token.SignedString([]byte(a.config.Secret))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tauthReq := struct {\n\t\tUID string `json:\"uid\"`\n\t\tToken string `json:\"token,omitempty\"`\n\t}{\n\t\tUID: a.config.ID,\n\t\tToken: tokenStr,\n\t}\n\n\tb, err := json.Marshal(authReq)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tauthBody := bytes.NewBuffer(b)\n\tresp, err := a.client.Post(a.config.LoginEndpoint, \"application/json\", authBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer errorutil.Ignore(resp.Body.Close)\n\tif resp.StatusCode != 200 {\n\t\treturn nil, ErrAuthFailed\n\t}\n\n\tvar authResp struct {\n\t\tToken string `json:\"token\"`\n\t}\n\terr = json.NewDecoder(resp.Body).Decode(&authResp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif req.Header == nil {\n\t\treq.Header = make(http.Header)\n\t}\n\treq.Header.Set(\"Authorization\", \"token=\"+authResp.Token)\n\n\treturn a.client.Do(req)\n}", "func gwAuthChecker(urls []conf.AllowUrl) gin.HandlerFunc {\n\tvar allowUrls = make(map[string]bool)\n\tfor _, url := range urls {\n\t\tfor _, p := range url.Urls {\n\t\t\ts := p\n\t\t\tallowUrls[s] = true\n\t\t}\n\t}\n\treturn func(c *gin.Context) {\n\t\ts := getHostServer(c)\n\t\tuser := getUser(c)\n\t\tpath := fmt.Sprintf(\"%s:%s\", c.Request.Method, c.Request.URL.Path)\n\t\trequestId := getRequestId(s, c)\n\t\t//\n\t\t// No auth and request URI not in allowed urls.\n\t\t// UnAuthorized\n\t\t//\n\t\tif (user.IsEmpty() || !user.IsAuth()) && !allowUrls[path] {\n\t\t\tauth := s.conf.Security.AuthServer\n\t\t\t// Check url are allow dict.\n\t\t\tpayload := gin.H{\n\t\t\t\t\"Auth\": gin.H{\n\t\t\t\t\t\"LogIn\": gin.H{\n\t\t\t\t\t\t\"Url\": fmt.Sprintf(\"%s/%s\",\n\t\t\t\t\t\t\tstrings.TrimRight(auth.Addr, \"/\"), strings.TrimLeft(auth.LogIn.Url, \"/\")),\n\t\t\t\t\t\t\"Methods\": auth.LogIn.Methods,\n\t\t\t\t\t\t\"AuthTypes\": auth.LogIn.AuthTypes,\n\t\t\t\t\t},\n\t\t\t\t\t\"LogOut\": gin.H{\n\t\t\t\t\t\t\"Url\": fmt.Sprintf(\"%s/%s\",\n\t\t\t\t\t\t\tstrings.TrimRight(auth.Addr, \"/\"), strings.TrimLeft(auth.LogOut.Url, \"/\")),\n\t\t\t\t\t\t\"Methods\": auth.LogOut.Methods,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t\tbody := s.RespBodyBuildFunc(http.StatusUnauthorized, requestId, errDefault401Msg, payload)\n\t\t\tc.JSON(http.StatusUnauthorized, body)\n\t\t\tc.Abort()\n\t\t\treturn\n\t\t}\n\t\tc.Next()\n\t}\n}", "func gwLogin(c *gin.Context) {\n\ts := getHostServer(c)\n\treqId := getRequestId(s, c)\n\tvar err error\n\tvar hasCheckPass = false\n\tvar checker = s.AuthParamChecker\n\tvar authParam AuthParameter\n\tfor _, resolver := range s.AuthParamResolvers {\n\t\tauthParam = resolver.Resolve(c)\n\t\tif err = checker.Check(authParam); err == nil {\n\t\t\thasCheckPass = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !hasCheckPass {\n\t\tc.JSON(http.StatusBadRequest, s.RespBodyBuildFunc(http.StatusBadRequest, reqId, err, nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\t// Login\n\tuser, err := s.AuthManager.Login(authParam)\n\tif err != nil || user.IsEmpty() {\n\t\tc.JSON(http.StatusNotFound, s.RespBodyBuildFunc(http.StatusNotFound, reqId, err.Error(), nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tsid, credential, ok := encryptSid(s, authParam)\n\tif !ok {\n\t\tc.JSON(http.StatusInternalServerError, s.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"Create session ID fail.\", nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tif err := s.SessionStateManager.Save(sid, user); err != nil {\n\t\tc.JSON(http.StatusInternalServerError, s.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"Save session fail.\", err.Error()))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tvar userPerms []gin.H\n\tfor _, p := range user.Permissions {\n\t\tuserPerms = append(userPerms, gin.H{\n\t\t\t\"Key\": p.Key,\n\t\t\t\"Name\": p.Name,\n\t\t\t\"Desc\": p.Descriptor,\n\t\t})\n\t}\n\tcks := s.conf.Security.Auth.Cookie\n\texpiredAt := time.Duration(cks.MaxAge) * time.Second\n\tvar userRoles = gin.H{\n\t\t\"Id\": 0,\n\t\t\"name\": \"\",\n\t\t\"desc\": \"\",\n\t}\n\tpayload := gin.H{\n\t\t\"Credentials\": gin.H{\n\t\t\t\"Token\": credential,\n\t\t\t\"ExpiredAt\": time.Now().Add(expiredAt).Unix(),\n\t\t},\n\t\t\"Roles\": userRoles,\n\t\t\"Permissions\": userPerms,\n\t}\n\tbody := s.RespBodyBuildFunc(0, reqId, nil, payload)\n\tc.SetCookie(cks.Key, credential, cks.MaxAge, cks.Path, cks.Domain, cks.Secure, cks.HttpOnly)\n\tc.JSON(http.StatusOK, body)\n}", "func (g *Git) Auth() error {\n\tep, err := transport.NewEndpoint(g.Repository.URL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif strings.HasPrefix(ep.Protocol, \"ssh\") {\n\t\tkey, err := os.ReadFile(g.SSHKeyPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsigner, err := ssh.ParsePrivateKey(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tg.AuthMethod = &gitssh.PublicKeys{\n\t\t\tUser: gitssh.DefaultUsername,\n\t\t\tSigner: signer,\n\t\t}\n\t} else {\n\t\tg.AuthMethod = &githttp.BasicAuth{\n\t\t\tUsername: g.Login,\n\t\t\tPassword: g.Password,\n\t\t}\n\t}\n\treturn nil\n}", "func DoAuth(ctx *gin.Context) {\n\t// Handle the exchange code to initiate a transport.\n\tsession := sessions.Default(ctx)\n\tretrievedState := session.Get(\"state\")\n\n\tif session.Get(\"userid\") != nil {\n\t\treturn\n\t}\n\n\tif retrievedState != ctx.Query(\"state\") {\n\t\tctx.AbortWithError(http.StatusUnauthorized, fmt.Errorf(\"Invalid session state: %s\", retrievedState))\n\t\treturn\n\t}\n\n\ttok, err := conf.Exchange(oauth2.NoContext, ctx.Query(\"code\"))\n\tif err != nil {\n\t\tctx.AbortWithError(http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tclient := conf.Client(oauth2.NoContext, tok)\n\temail, err := client.Get(\"https://www.googleapis.com/oauth2/v3/userinfo\")\n\tif err != nil {\n\t\tctx.AbortWithError(http.StatusBadRequest, err)\n\t\treturn\n\t}\n\tdefer email.Body.Close()\n\tdata, err := ioutil.ReadAll(email.Body)\n\tif err != nil {\n\t\tglog.Errorf(\"[Gin-OAuth] Could not read Body: %s\", err)\n\t\tctx.AbortWithError(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tvar user User\n\terr = json.Unmarshal(data, &user)\n\tif err != nil {\n\t\tglog.Errorf(\"[Gin-OAuth] Unmarshal userinfo failed: %s\", err)\n\t\tctx.AbortWithError(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\t// save userinfo, which could be used in Handlers\n\tctx.Set(\"user\", user)\n\n\tvals := map[string]string{\n\t\t\"Name\": user.Name,\n\t\t\"Email\": user.Email,\n\t\t\"Picture\": user.Picture,\n\t\t\"GivenName\": user.GivenName,\n\t\t\"FamilyName\": user.FamilyName,\n\t\t\"EmailVerified\": fmt.Sprintf(\"%v\", user.EmailVerified),\n\t\t\"Gender\": user.Gender,\n\t\t\"Sub\": user.Sub,\n\t\t\"Profile\": user.Profile,\n\t}\n\tseccookie.StoreSecureCookie(ctx, vals, scookie)\n\n\t// Redirect to root after auth\n\tctx.Redirect(http.StatusTemporaryRedirect, \"/\")\n}", "func (a *API) Auth(req *http.Request) {\n\t//Supports unauthenticated access to confluence:\n\t//if username and token are not set, do not add authorization header\n\tif a.Username != \"\" && a.Token != \"\" {\n\t\treq.SetBasicAuth(a.Username, a.Token)\n\t}\n}", "func (a *Auth) Do() (*http.Client, error) {\n\t// If a cache file is given, read from the cache file\n\tif a.CacheFile != \"\" {\n\t\ttmpCache := &AuthConfig{}\n\t\terr := tmpCache.Load(a.CacheFile)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Could not load cache file with path: \" + a.CacheFile)\n\t\t\treturn nil, err\n\t\t}\n\t\t// replace empty entries with cached values\n\t\tif a.Config.ConsumerKey == \"\" {\n\t\t\ta.Config.ConsumerKey = tmpCache.ConsumerKey\n\t\t}\n\t\tif a.Config.ConsumerSecret == \"\" {\n\t\t\ta.Config.ConsumerSecret = tmpCache.ConsumerSecret\n\t\t}\n\t\tif a.Config.VerCode == \"\" {\n\t\t\ta.Config.VerCode = tmpCache.VerCode\n\t\t}\n\t\t// Cache the new settings\n\t\terr = a.Config.Cache(a.CacheFile)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n\tc := oauth.NewConsumer(\n\t\ta.Config.ConsumerKey,\n\t\ta.Config.ConsumerSecret,\n\t\toauth.ServiceProvider{\n\t\t\tRequestTokenUrl: \"https://api.copy.com/oauth/request\",\n\t\t\tAuthorizeTokenUrl: \"https://www.copy.com/applications/authorize\",\n\t\t\tAccessTokenUrl: \"https://api.copy.com/oauth/access\",\n\t\t},\n\t)\n\t// If a verification code has not been supplied, request it from the browser and return.\n\tif a.Config.VerCode == \"\" {\n\t\t_, url, err := c.GetRequestTokenAndUrl(\"oob\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println(\"(1) Go to: \" + url)\n\t\tfmt.Println(\"(2) Grant access, you should get back a verification code.\")\n\t\tfmt.Println(\"(3) Run the program again with command line argument -code $AUTHCODE\")\n\t\treturn nil, nil\n\t}\n\t// If a code is supplied, atempt to obtain an authorization\n\taccessToken, _, err := c.GetRequestTokenAndUrl(\"oob\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil, nil\n\t}\n\tc.AuthorizeToken(accessToken, a.Config.VerCode)\n\treturn nil, nil\n}", "func (s *server) checkAuth(r *http.Request) error {\n\tauthhdr := r.Header[\"Authorization\"]\n\tif len(authhdr) == 0 {\n\t\treturn ErrNoAuth\n\t}\n\n\tauthsha := sha256.Sum256([]byte(authhdr[0]))\n\tcmp := subtle.ConstantTimeCompare(authsha[:], s.authsha[:])\n\tif cmp != 1 {\n\t\treturn ErrBadAuth\n\t}\n\treturn nil\n}", "func (b *basicAuth) set(r *http.Request) { r.SetBasicAuth(b.username, b.password) }", "func (h *Handler) AuthHandler(w http.ResponseWriter, r *http.Request) {\n\t// Preveri ali se stanje iz *LoginHandler in v odgovoru ujemata\n\tsc, err := r.Cookie(\"originalState\")\n\tif err != nil || sc.Value != r.FormValue(\"state\") {\n\t\t// Stanje se ne ujema ali pa je prislo do napake, odgovori z 401\n\t\tlog.Error(err.Error())\n\t\thttp.Error(w, \"Neveljavno stanje v odgovoru\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t// Zamenjaj avtorizacijsko kodo pridobljeno iz prvotne preusmeritve za Token, s katerim lahko pridobimo podrobnosti o uporabniku\n\ttok, err := h.OAuthConf.Exchange(oauth2.NoContext, r.FormValue(\"code\"))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t// Preveri ali je token veljaven\n\tif tok.Valid() == false {\n\t\thttp.Error(w, \"Tokec je neveljaven\", http.StatusUnauthorized)\n\t}\n\n\t// Preko klienta poslji zahtevek s tokenom na naslov za pridobivanje osnovnih podatkov o uporabniku\n\tclient := h.OAuthConf.Client(oauth2.NoContext, tok)\n\tuserResponse, err := client.Get(\"https://www.googleapis.com/oauth2/v3/userinfo\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t// Shrani prejete podatke v GoogleUser\n\tvar gu GoogleUser\n\terr = json.NewDecoder(userResponse.Body).Decode(&gu)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\tlog.Info(gu.Email)\n\n\t// Preveri ali uporabnik ze obstaja (preko unique emaila), ce ne ga shrani\n\tvar u *biolog.User\n\tu, err = h.UserHandler.UserService.UserByEmail(gu.Email)\n\n\tif err != nil {\n\t\tif err.Error() == \"Not found\" {\n\t\t\t// Uporabnik ni bil najden, torej se prijavlja na novo\n\t\t\t// Iz GoogleUser izgradi biolog.User in ga shrani v PB\n\t\t\tu = &biolog.User{\n\t\t\t\tExternalID: &gu.ID,\n\t\t\t\tDisplayName: &gu.Name,\n\t\t\t\tGivenName: &gu.GivenName,\n\t\t\t\tFamilyName: &gu.FamilyName,\n\t\t\t\tEmail: &gu.Email,\n\t\t\t\tPicture: &gu.Picture,\n\t\t\t\tExternalAuthProvider: &googleAuth,\n\t\t\t}\n\t\t\tu, err = h.UserHandler.UserService.CreateUser(*u)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"Uporabnika ni bilo mogoce kreirati: \", err)\n\t\t\t\trespondWithError(w, http.StatusInternalServerError, \"Napaka pri kreiranju uporabnika\")\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Error(err.Error())\n\t\t\trespondWithError(w, http.StatusInternalServerError, \"Neznana napaka pri kreiranju uporabnika\")\n\t\t}\n\t}\n\n\t// Dodeli nov JWT uporabniku\n\t// TODO:\n\t// - preveri cas za potek JWT tokena (10-15min ?)\n\tclaims := &EmailClaims{\n\t\tgu.Email,\n\t\tjwt.StandardClaims{\n\t\t\tExpiresAt: time.Now().Unix() + 3600,\n\t\t\tIssuer: \"biolog-app\",\n\t\t},\n\t}\n\tjwttok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\n\tss, _ := jwttok.SignedString(jwtSignKey)\n\tssJSON, _ := json.Marshal(map[string]string{\"token\": ss})\n\n\t// Odgovori z JWT v telesu zahtevka\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(ssJSON)\n\t// TODO:\n\t// - logika za preusmeritev, ali naj bo to na frontend (vrni JWT v Cookie in preusmeri?)\n\t// - refresh token\n\t// glej https://stackoverflow.com/questions/43090518/how-to-properly-handle-a-jwt-refresh\n\n\t// Po uspesni prijavi uporabnika preusmeri na domaco stran\n\t//http.Redirect(w, r, \"/home\", http.StatusMovedPermanently)\n}", "func (gh *GitHub) Authenticate(ctx context.Context, token string) {\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: token},\n\t)\n\ttc := oauth2.NewClient(ctx, ts)\n\tgh.Client = github.NewClient(tc)\n}", "func (f *Fs) getAuth(req *http.Request) (err error) {\n\tf.authMu.Lock()\n\tdefer f.authMu.Unlock()\n\tctx := req.Context()\n\n\t// if have auth, check it is in date\n\tif f.opt.Authorization == \"\" || f.opt.User == \"\" || f.authExpiry.IsZero() || time.Until(f.authExpiry) < expiryLeeway {\n\t\t// Get the auth token\n\t\tf.srv.SetSigner(nil) // temporarily remove the signer so we don't infinitely recurse\n\t\terr = f.getAuthToken(ctx)\n\t\tf.srv.SetSigner(f.getAuth) // replace signer\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Set Authorization header\n\treq.Header.Set(\"Authorization\", f.opt.Authorization)\n\n\treturn nil\n}", "func getGitHubLoginUrl(w http.ResponseWriter, r *http.Request) {\n\tloginUrl, err := github.LoginUrl()\n\thelpers.HandleError(err)\n\tresp := map[string]interface{}{\n\t\t\"data\": loginUrl,\n\t}\n\tapiResponse(resp, w)\n}", "func Auth(c *gin.Context) {\n\ttokenString := c.Request.Header.Get(\"Authorization\")\n\t// Parse token that got from Header to our SigningMethodH\n\ttoken, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {\n\t\tif jwt.GetSigningMethod(\"HS256\") != token.Method {\n\t\t\tLog.Fatalf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t\treturn nil, fmt.Errorf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t}\n\n\t\treturn []byte(time.Now().Format(\"2019-03-29\")), nil\n\t})\n\n\t// Verify the token\n\tif token != nil && err == nil {\n\t\tLog.Println(\"token verified\")\n\t} else {\n\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, model.JSONResults{\n\t\t\tStatus: http.StatusUnauthorized,\n\t\t\tMessage: model.Message{\n\t\t\t\tError: err.Error(),\n\t\t\t},\n\t\t})\n\t}\n}", "func (s CoSigner) Auth(req *httpclient.Request, method, uri string, body []byte) {\n\th := sha256.New()\n\th.Write(append([]byte(method+uri), body...))\n\tdigest := h.Sum(nil)\n\n\tbts, err := rsa.SignPKCS1v15(rand.Reader, s.sigKey, cCrypto.SHA256, digest)\n\tif err == nil {\n\t\treq.H(\"Authorization\", base64.StdEncoding.EncodeToString(bts))\n\t}\n}", "func authCheck(c *gin.Context) {\n\t// Parse the token from the header. Take into account that the token prepended by Bearer\n\t// keyword.\n\tvar (\n\t\ttoken string\n\t\terr error\n\t)\n\t{\n\t\th := c.GetHeader(\"Authorization\")\n\t\tif len(h) < 8 {\n\t\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, msg(\"authorization header missed or not valid\"))\n\t\t\treturn\n\t\t}\n\t\ts := strings.SplitN(h, \"Bearer \", 2)\n\t\tif len(s) < 2 {\n\t\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, msg(\"badly formatted authorization header (Bearer missed)\"))\n\t\t\treturn\n\t\t}\n\t\ttoken = s[1]\n\t}\n\n\t// Pass auth data into gin context.\n\tvar u *user.User\n\t{\n\t\tif u, err = user.AuthCheck(context.Background(), token); err != nil {\n\t\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, msg(err.Error()))\n\t\t\treturn\n\t\t}\n\t\tc.Set(session, *u)\n\t}\n\n\tc.Next()\n}", "func authEndpoint(rw http.ResponseWriter, req *http.Request) {\n\n\t// request has to be POST\n\tif req.Method != \"POST\" {\n\t\thttp.Error(rw, \"bad method, only post allowed\", http.StatusBadRequest)\n\t}\n\n\t// has to be authenticated, in a real we would use soemthing more\n\t// secure like certificates etc.\n\tuser, _, ok := req.BasicAuth()\n\n\tif !ok {\n\t\thttp.Error(rw, \"authentication required\", http.StatusForbidden)\n\t}\n\n\tlog.Println(\"basic authentication successful for \", user)\n\n\t// now we issue token and return it\n\n\t// This context will be passed to all methods.\n\tctx := req.Context()\n\n\t// Create an empty session object which will be passed to the request handlers\n\tmySessionData := newSession(\"\")\n\n\t// This will create an access request object and iterate through the registered TokenEndpointHandlers to validate the request.\n\taccessRequest, err := fositeInstance.NewAccessRequest(ctx, req, mySessionData)\n\n\t// Catch any errors, e.g.:\n\t// * unknown client\n\t// * invalid redirect\n\t// * ...\n\tif err != nil {\n\t\tlog.Printf(\"Error occurred in NewAccessRequest: %+v\", err)\n\t\tfositeInstance.WriteAccessError(rw, accessRequest, err)\n\t\treturn\n\t}\n\n\t// If this is a client_credentials grant, grant all requested scopes\n\t// NewAccessRequest validated that all requested scopes the client is allowed to perform\n\t// based on configured scope matching strategy.\n\tif accessRequest.GetGrantTypes().ExactOne(\"client_credentials\") {\n\t\tfor _, scope := range accessRequest.GetRequestedScopes() {\n\t\t\taccessRequest.GrantScope(scope)\n\t\t}\n\t}\n\n\t// Next we create a response for the access request. Again, we iterate through the TokenEndpointHandlers\n\t// and aggregate the result in response.\n\tresponse, err := fositeInstance.NewAccessResponse(ctx, accessRequest)\n\tif err != nil {\n\t\tlog.Printf(\"Error occurred in NewAccessResponse: %+v\", err)\n\t\tfositeInstance.WriteAccessError(rw, accessRequest, err)\n\t\treturn\n\t}\n\n\t// All done, send the response.\n\tfositeInstance.WriteAccessResponse(rw, accessRequest, response)\n\n}", "func (t *CookieAuthTransport) buildAuthRequest() (*http.Request, error) {\n\tbody := struct {\n\t\tUsername string `json:\"username\"`\n\t\tPassword string `json:\"password\"`\n\t}{\n\t\tt.Username,\n\t\tt.Password,\n\t}\n\n\tb := new(bytes.Buffer)\n\tjson.NewEncoder(b).Encode(body)\n\n\t// TODO Use a context here\n\treq, err := http.NewRequest(http.MethodPost, t.AuthURL, b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treturn req, nil\n}", "func makeAuthedRequest(method string, url string) []byte {\n\tbody := []byte(\"\")\n\n\treq, _ := http.NewRequest(method, apiBase+url, bytes.NewBuffer(body))\n\treq.Header.Add(\"Authorization\", \"Bearer \"+accessToken)\n\n\tclient := http.Client{}\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\tpanic(\"Could not make call to \" + url)\n\t}\n\n\tdefer res.Body.Close()\n\tbodyBytes, err := ioutil.ReadAll(res.Body)\n\treturn bodyBytes\n}", "func doAuthRequest() (*Auth, error) {\n\n\t// create request\n\tauth_payload := strings.NewReader(\"grant_type=client_credentials&scope=\" + AUTH_SCOPE)\n\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(API_METHOD, API_BASE_URL+\"/oauth2/v2.0/token\", auth_payload)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil, err\n\t}\n\n\t// set headers\n\treq.SetBasicAuth(REST_KEY, REST_SECRET)\n\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n\t// make request\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\n\t// extract Auth object from response body\n\tvar a Auth\n\n\terr = json.NewDecoder(res.Body).Decode(&a)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\treturn &a, nil\n}", "func Auth(g *gin.Context) {\n\tlog.Println(\"Auth\")\n\tclientIdStr, ok := g.GetQuery(\"client_id\")\n\tif !ok {\n\t\tg.JSON(400, \"error\")\n\t\treturn\n\t}\n\n\tclientId, err := strconv.Atoi(clientIdStr)\n\tif err != nil {\n\t\tg.JSON(400, \"error\")\n\t\treturn\n\t}\n\n\tauthCode := \"22222323asdf\"\n\tm := store[clientId]\n\tm.AuthCode = authCode\n\tstore[clientId] = m\n\n\tg.JSON(200, authCode)\n}", "func oauth2FactoryToken(w http.ResponseWriter, r *http.Request) {\n\tparas, incName := r.URL.Query(), mux.Vars(r)[\"incName\"]\n\t// if error parameter exists.\n\tif _, ok := paras[\"error\"]; ok {\n\t\thttp.Redirect(w, r, \"/index\", http.StatusFound)\n\t\treturn\n\t}\n\tform := url.Values{}\n\tform.Add(\"client_id\", oauth2Infos[incName].clientId)\n\tform.Add(\"client_secret\", oauth2Infos[incName].clientSecret)\n\tform.Add(\"code\", paras[\"code\"][0])\n\tform.Add(\"redirect_uri\", oauth2Infos[incName].redirectUrl)\t// the redirectUrl should be my host index\n\tform.Add(\"state\", incName)\n\n\tres, _ := http.Post(oauth2Infos[incName].tokenUrl, \"application/x-www-form-urlencoded\", strings.NewReader(form.Encode()))\n\tbody, _ := ioutil.ReadAll(res.Body)\n\tres, _ = http.Get(oauth2Infos[incName].infoUrl + \"?access_token=\" + jsonProcessString(string(body))[\"access_token\"])\n\tbody, _ = ioutil.ReadAll(res.Body)\n\t// Get the access_token and put user information to mydatabase\n\tinfos := &githubUser{}\n\tjson.Unmarshal(body, &infos)\n\tif users := SelectUser(map[string]interface{}{\"username\": infos.Login, \"source\": incName}); len(users) == 0 {\n\t\tgo AddUser(User{Source: incName, UserId: uuid.Must(uuid.NewV4()).String(), Username: infos.Login, Password: infos.Login, Avatar: infos.AvatarURL, InfoURL: infos.URL, Bio: infos.Bio})\n\t}\n\n\t// Later, we will marsh a better user info cookie.\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: \"user\",\n\t\tValue: infos.Login,\t// user struct json\n\t\tPath: \"/\",\n\t\tExpires: time.Now().AddDate(0, 1, 0),\n\t\tMaxAge: 86400,\t// 100 hours' validate time\n\t})\n\thttp.Redirect(w, r, \"/index\", http.StatusFound)\t\t// redirect to the index page\n}", "func AuthAndCallAPI(w http.ResponseWriter, r *http.Request, service string, method string, version string) {\n\te := Execution{name: \"AuthAndCallAPI \" + service}\n\te.Start()\n\n\tauthorization := r.Header.Get(\"authorization\")\n\n\ttoken := \"\"\n\ts := strings.Split(authorization, \" \")\n\tif len(s) >= 2 {\n\t\ttoken = s[1]\n\t}\n\n\tconfig := config.GetConfig()\n\tresp, _ := resty.R().\n\t\tSetFormData(map[string]string{\n\t\t\t\"token\": token,\n\t\t\t\"service\": service,\n\t\t}).\n\t\tSetResult(&Respon{}).\n\t\tPost(config.API.Auth + \"v100/auth/check_token\")\n\n\tvar respon Respon\n\t_ = json.Unmarshal(resp.Body(), &respon)\n\n\tif respon.Code != 200 {\n\t\trespond := Respon{\n\t\t\tStatus: respon.Status,\n\t\t\tCode: respon.Code,\n\t\t\tMessage: respon.Message,\n\t\t\tExeTime: respon.ExeTime,\n\t\t\tData: respon.Data,\n\t\t\tError: respon.Error,\n\t\t}\n\t\tRespondJson(w, resp.StatusCode(), respond)\n\t\treturn\n\t}\n\n\tCallAPI(w, r, service, method, version)\n}", "func AuthCallback(w http.ResponseWriter, r *http.Request) {\n\tcode := r.FormValue(\"code\")\n\tcallbackState := r.FormValue(\"state\")\n\n\tclientID, err := state.DecryptState(callbackState, os.Getenv(\"SECRET\"))\n\tif err != nil {\n\t\thttp.Error(w, \"State could not be verified\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tconfigValue, err := config.ReadConfigFromEnv(clientID)\n\tif err != nil {\n\t\tlog.Printf(\"Error while verifying state: %v\", err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\ttoken, err := github.Exchange(configValue.ClientID, configValue.ClientSecretID, code)\n\tif err != nil {\n\t\tlog.Printf(\"Error while exchange code %s for client %s with Github: %v\", code, configValue.ClientID, err)\n\t\thttp.Error(w, fmt.Sprintf(\"Code %s for client %s was not accepted by the Oauth provider\", code, configValue.ClientID), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tredirectURLWithToken := fmt.Sprintf(\"%s?token=%s\", configValue.RedirectURL, token)\n\n\tw.Header().Set(\"Location\", redirectURLWithToken)\n\tw.WriteHeader(http.StatusTemporaryRedirect)\n}", "func CheckAuth(c *gin.Context) {\n\n}", "func (client *OAuthClient) DoAuth(rToken *oauth.RequestToken) error {\n\taccessToken, err := client.OAuthConsumer.AuthorizeToken(rToken, \"\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient.http, err = client.OAuthConsumer.MakeHttpClient(accessToken)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s Server) Auth(c context.Context, r *gabby.AuthRequest) (*gabby.AuthResponse, error) {\n\treturn nil, nil\n}", "func auth(ctx *importer.SetupContext) (*oauth.Config, error) {\n\tclientId, secret, err := ctx.Credentials()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &oauth.Config{\n\t\tClientId: clientId,\n\t\tClientSecret: secret,\n\t\tAuthURL: authURL,\n\t\tTokenURL: tokenURL,\n\t\tRedirectURL: ctx.CallbackURL(),\n\t}, nil\n}", "func GenerateAuth(c *gin.Context) {\n\tappEngine := appengine.NewContext(c.Request)\n\trandomString := uniuri.NewLen(32)\n\n\trequestObj := AuthenticatedModel{Token: randomString, Cards: []Card{}}\n\tkey := datastore.NewIncompleteKey(appEngine, TokenKey, SandboxPromotionsKey(appEngine, TokenKey))\n\n\tif _, err := datastore.Put(appEngine, key, &requestObj); err != nil {\n\t\tc.JSON(http.StatusBadGateway, gin.H{\"status_code\": http.StatusBadGateway, \"status_message\": err.Error()})\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{\"X-Auth\": randomString})\n\t}\n}", "func (g *GitHub) Authcallback(code, state string) (string, error) {\n\tif code == \"\" || state == \"\" {\n\t\treturn \"\", fmt.Errorf(\"code or state is nil\")\n\t}\n\n\t// Caicloud web address,eg caicloud.io\n\tuiPath := osutil.GetStringEnv(cloud.ConsoleWebEndpoint, \"http://localhost:8000\")\n\tredirectURL := fmt.Sprintf(\"%s/cyclone/add?type=github&code=%s&state=%s\", uiPath, code, state)\n\n\t// Sync to get token.\n\tgo g.getToken(code, state)\n\treturn redirectURL, nil\n}", "func (s SPusher) Auth(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) {\n\tvar appKey = req.Header.Get(\"X-App-Key\")\n\tif s.key != appKey {\n\t\tsendJSONResponse(rw, http.StatusBadRequest, \"err\", \"Invalid X-App-Key\")\n\t\treturn\n\t}\n\tvar timestamp = req.Header.Get(\"X-Request-Time\")\n\tvar unixTimestamp, _ = strconv.ParseInt(timestamp, 10, 0)\n\tvar reqTime = time.Unix(unixTimestamp, 0)\n\tvar took = time.Since(reqTime)\n\tif took < 0 {\n\t\ttook = -took\n\t}\n\tif took > 10*time.Minute {\n\t\tsendJSONResponse(rw, http.StatusBadRequest, \"err\", \"Invalid X-Request-Time\")\n\t\treturn\n\t}\n\n\tvar signParams = make(map[string]string)\n\tsignParams[\"app_key\"] = appKey\n\tsignParams[\"timestamp\"] = timestamp\n\tsignParams[\"path\"] = req.URL.Path\n\tvar query = req.URL.Query()\n\tif query != nil {\n\t\tfor key := range query {\n\t\t\tsignParams[key] = query.Get(key)\n\t\t}\n\t}\n\tif req.Method == \"POST\" {\n\t\treq.ParseForm()\n\t\tif req.Form != nil {\n\t\t\tfor key := range req.Form {\n\t\t\t\tsignParams[key] = req.Form.Get(key)\n\t\t\t}\n\n\t\t}\n\t}\n\tvar exceptSign = utils.HmacMD5(s.secret, signParams)\n\tvar sign = req.Header.Get(\"X-Request-Signature\")\n\tif sign != exceptSign {\n\t\tsendJSONResponse(rw, http.StatusBadRequest, \"err\", \"Invalid X-Request-Signature\")\n\t\treturn\n\t}\n\tnext(rw, req)\n}", "func (c *B2) authRequest(method, apiPath string, body io.Reader) (*http.Request, *authorizationState, error) {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\tif !c.auth.isValid() {\n\t\tif c.Debug {\n\t\t\tlog.Println(\"No valid authorization token, re-authorizing client\")\n\t\t}\n\t\tif err := c.internalAuthorizeAccount(); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tpath := c.auth.APIEndpoint + v1 + apiPath\n\n\treq, err := http.NewRequest(method, path, body)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq.Header.Add(\"Authorization\", c.auth.AuthorizationToken)\n\n\tif c.Debug {\n\t\tlog.Printf(\"authRequest: %s %s\\n\", method, req.URL)\n\t}\n\n\treturn req, c.auth, nil\n}", "func main() {\n\t// Prompt for auth input\n\tfmt.Println(\"Enter username: \")\n\tvar user string\n\tfmt.Scanln(&user)\n\tfmt.Println(\"Enter password: \")\n\tvar password string\n\tfmt.Scanln(&password)\n\n\tvar api string\n\tif api = os.Getenv(\"UP_ENDPOINT\"); api == \"\" {\n\t\tapi = \"https://api.upbound.io\"\n\t}\n\n\tbase, _ := url.Parse(api)\n\tcj, err := cookiejar.New(nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tupClient := up.NewClient(func(c *up.HTTPClient) {\n\t\tc.BaseURL = base\n\t\tc.HTTP = &http.Client{\n\t\t\tJar: cj,\n\t\t}\n\t})\n\tcfg := up.NewConfig(func(cfg *up.Config) {\n\t\tcfg.Client = upClient\n\t})\n\tauth := &struct {\n\t\tID string `json:\"id\"`\n\t\tPassword string `json:\"password\"`\n\t}{\n\t\tID: user,\n\t\tPassword: password,\n\t}\n\tjsonStr, err := json.Marshal(auth)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tu, err := base.Parse(\"/v1/login\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq, err := http.NewRequest(http.MethodPost, u.String(), bytes.NewReader(jsonStr))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\terr = cfg.Client.Do(req, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tclient := accounts.NewClient(cfg)\n\taccounts, err := client.List(context.Background())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor _, a := range accounts {\n\t\tfmt.Println(a.Account.Name)\n\t}\n}", "func sign(req *http.Request, accessKey, secretKey, signName string) {\n\tif accessKey == \"\" {\n\t\treturn\n\t}\n\ttoSign := req.Method + \"\\n\"\n\tfor _, n := range HEADER_NAMES {\n\t\ttoSign += req.Header.Get(n) + \"\\n\"\n\t}\n\tbucket := strings.Split(req.URL.Host, \".\")[0]\n\ttoSign += \"/\" + bucket + req.URL.Path\n\th := hmac.New(sha1.New, []byte(secretKey))\n\t_, _ = h.Write([]byte(toSign))\n\tsig := base64.StdEncoding.EncodeToString(h.Sum(nil))\n\ttoken := signName + \" \" + accessKey + \":\" + sig\n\treq.Header.Add(\"Authorization\", token)\n}", "func authLoginHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\tgithub.RedirectToLogin(w, r)\n}", "func (dc *DClient) Do(req *http.Request) (*http.Response, error) {\n\treturn dc.doDigestAuth(req)\n}", "func googleAuth(ctx *neptulon.ReqCtx, db data.DB, pass string) error {\n\tvar r tokenContainer\n\tif err := ctx.Params(&r); err != nil || r.Token == \"\" {\n\t\tctx.Err = &neptulon.ResError{Code: 666, Message: \"Malformed or null Google oauth access token was provided.\"}\n\t\treturn fmt.Errorf(\"auth: google: malformed or null Google oauth token '%v' was provided: %v\", r.Token, err)\n\t}\n\n\tp, err := getTokenInfo(r.Token)\n\tif err != nil {\n\t\tctx.Err = &neptulon.ResError{Code: 666, Message: \"Failed to authenticated with the given Google oauth access token.\"}\n\t\treturn fmt.Errorf(\"auth: google: error during Google API call using provided token: %v with error: %v\", r.Token, err)\n\t}\n\n\t// retrieve user information\n\tuser, ok := db.GetByEmail(p.Email)\n\tif !ok {\n\t\t// this is a first-time registration so create user profile via Google+ profile info\n\t\tuser = &models.User{Email: p.Email, Name: p.Name, Picture: p.Picture, Registered: time.Now()}\n\n\t\t// save the user information for user ID to be generated by the database\n\t\tif ierr := db.SaveUser(user); ierr != nil {\n\t\t\treturn fmt.Errorf(\"auth: google: failed to persist user information: %v\", ierr)\n\t\t}\n\n\t\t// create the JWT token\n\t\ttoken := jwt.New(jwt.SigningMethodHS256)\n\t\ttoken.Claims[\"userid\"] = user.ID\n\t\ttoken.Claims[\"created\"] = user.Registered.Unix()\n\t\tuser.JWTToken, err = token.SignedString([]byte(pass))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"auth: google: jwt signing error: %v\", err)\n\t\t}\n\n\t\t// now save the full user info\n\t\tif err := db.SaveUser(user); err != nil {\n\t\t\treturn fmt.Errorf(\"auth: google: failed to persist user information: %v\", err)\n\t\t}\n\n\t\t// store user ID in session so user can make authenticated call after this\n\t\tctx.Conn.Session.Set(\"userid\", user.ID)\n\t}\n\n\tctx.Res = gAuthRes{ID: user.ID, Token: user.JWTToken, Name: user.Name, Email: user.Email, Picture: user.Picture}\n\tctx.Session.Set(middleware.CustResLogDataKey, gAuthRes{ID: user.ID, Token: user.JWTToken, Name: user.Name, Email: user.Email})\n\tlog.Printf(\"auth: google: logged in: %v, %v\", p.Name, p.Email)\n\treturn nil\n}", "func serverAuth(logger *zap.Logger, url string, user string, password string) (string, error) {\n\tlogger.Debug(\"serverAuth called\", zap.String(\"url\", url), zap.String(\"user\", user))\n\tbody := fmt.Sprintf(`{\"auth\":{\"identity\":{\"methods\":[\"password\"],\"password\":{\"user\":{\"domain\":{\"id\":\"default\"},\"name\":\"%s\",\"password\":\"%s\"}}}}}`, user, password)\n\trbody := strings.NewReader(body)\n\treq, err := http.NewRequest(\"POST\", url+\"v3/auth/tokens\", rbody)\n\tif err != nil {\n\t\tlogger.Debug(\"serverAuth error from NewRequest POST\", zap.String(\"url\", url), zap.String(\"user\", user), zap.Error(err))\n\t\treturn \"\", err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tlogger.Debug(\"serverAuth error from DefaultClient.Do POST\", zap.String(\"url\", url), zap.String(\"user\", user), zap.Error(err))\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != 201 {\n\t\tlogger.Debug(\"serverAuth error from POST return status\", zap.String(\"url\", url), zap.String(\"user\", user), zap.Int(\"status\", resp.StatusCode))\n\t\treturn \"\", fmt.Errorf(\"server auth token request gave status %d\", resp.StatusCode)\n\t}\n\trv := resp.Header.Get(\"X-Subject-Token\")\n\tif len(rv) == 0 {\n\t\tlogger.Debug(\"serverAuth succeeded, but ended up with zero-length token\")\n\t} else {\n\t\tlogger.Debug(\"serverAuth succeeded\")\n\t}\n\treturn rv, nil\n}", "func authClient(cacheFile, code string) (*http.Client, error) {\n\tconfig := &oauth.Config{\n\t\tClientId: clientId,\n\t\tClientSecret: clientSecret,\n\t\tScope: storage.DevstorageFull_controlScope,\n\t\tAuthURL: \"https://accounts.google.com/o/oauth2/auth\",\n\t\tTokenURL: \"https://accounts.google.com/o/oauth2/token\",\n\t\tTokenCache: oauth.CacheFile(cacheFile),\n\t\tRedirectURL: \"urn:ietf:wg:oauth:2.0:oob\",\n\t}\n\n\ttransport := &oauth.Transport{\n\t\tConfig: config,\n\t\tTransport: http.DefaultTransport,\n\t}\n\n\ttoken, err := config.TokenCache.Token()\n\tif err != nil {\n\t\tif code == \"\" {\n\t\t\turl := config.AuthCodeURL(\"\")\n\t\t\treturn nil, fmt.Errorf(\"Visit URL to get a code then run again with -code=YOUR_CODE\\n%s\", url)\n\t\t}\n\n\t\t// Exchange auth code for access token\n\t\ttoken, err = transport.Exchange(code)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlog.Printf(\"Token is cached in %v\\n\", config.TokenCache)\n\t}\n\ttransport.Token = token\n\n\treturn transport.Client(), nil\n}", "func IGLogin(w http.ResponseWriter, r *http.Request, user *IGAuthCred) bool {\n\tif r.FormValue(\"code\") == \"\" {\n\t\tlog.Print(\"Code was not recieved\")\n\t\treturn false\n\t}\n\tapiURL := IG_API_URL\n\tresource := \"/oauth/access_token\"\n\tdata := url.Values{}\n\tdata.Add(\"code\", r.FormValue(\"code\"))\n\tdata.Add(\"redirect_uri\", REDIRECT_URL)\n\tdata.Add(\"grant_type\", \"authorization_code\")\n\tdata.Add(\"client_secret\", CLIENT_SECRET)\n\tdata.Add(\"client_id\", CLIENT_ID)\n\n\tu, _ := url.ParseRequestURI(apiURL)\n\tu.Path = resource\n\turlStr := u.String()\n\n\tclient := &http.Client{}\n\tr, err := http.NewRequest(\"POST\", urlStr, strings.NewReader(data.Encode()))\n\n\tif err != nil {\n\t\tlog.Print(\"Eorror creating the POST request : \", err)\n\t\treturn false\n\t}\n\n\tr.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n\tresp, err := client.Do(r)\n\n\tb, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\tlog.Print(\"Error reading the body\", err)\n\t\treturn false\n\t}\n\n\terr = json.Unmarshal(b, &user)\n\n\tif err != nil {\n\t\tlog.Print(\"Error unmarshalling the reponse\", err)\n\t\treturn false\n\t}\n\n\terr = resp.Body.Close()\n\n\tif err != nil {\n\t\tlog.Print(\"Cannot close the body\", err)\n\t\treturn false\n\t}\n\n\treturn true\n}", "func Auth (c *gin.Context) {\n auth := c.Request.Header.Get(\"Authorization\")\n\n if strings.HasPrefix(auth, defaultAuthSchema) {\n token, err := jwt.Parse(auth[len(defaultAuthSchema)+1:], func(token *jwt.Token) (interface{}, error) {\n if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\n return nil, fmt.Errorf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n }\n return []byte(SECRET), nil\n })\n \n if err == nil && token.Valid {\n \n userID := int(token.Claims[\"UserID\"].(float64))\n \n c.Set(\"UserID\", userID)\n c.Next()\n return\n }\n \n }\n\n c.Status(http.StatusUnauthorized)\n c.Abort()\n\n}", "func (h *Handler) GoogleLoginHandler(w http.ResponseWriter, r *http.Request) {\n\t// Uporabnik, v katerega bomo prebrali podatke\n\tvar u *biolog.User\n\t// Prebere telo zahtevka (trenutno le JSON z poljem token)\n\tdecoder := json.NewDecoder(r.Body)\n\ttokStr := struct {\n\t\tToken string `json:\"token\"`\n\t}{}\n\tif err := decoder.Decode(&tokStr); err != nil {\n\t\trespondWithError(w, 400, \"Please include a token in the request body\")\n\t}\n\n\t// Parsaj token, hkrati se preveri tudi Google podpis\n\ttok, err := jwt.Parse(tokStr.Token, func(token *jwt.Token) (interface{}, error) {\n\t\t// Get the Google certificates\n\t\t// TODO: -cache the certificate for the specified time\n\t\tresp, err := http.Get(\"https://www.googleapis.com/oauth2/v3/certs\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Prebere telo odgovora v keys objekt\n\t\tdefer resp.Body.Close()\n\t\tvar keys map[string][]GoogleKey\n\t\tdecoder = json.NewDecoder(resp.Body)\n\t\tif err := decoder.Decode(&keys); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Preglej kateri 'kid' se ujema z nasim tokecom in na podlagi\n\t\t// N (modulus) in E (eksponent) zgradi javni kljuc\n\t\tfor _, v := range keys[\"keys\"] {\n\t\t\tif v.Kid == token.Header[\"kid\"] {\n\t\t\t\tpubKey := &rsa.PublicKey{N: new(big.Int), E: 0}\n\t\t\t\t// FIXME: ne preverja za napake pri dekodiranju\n\t\t\t\tnByte, _ := base64.RawURLEncoding.DecodeString(v.N)\n\t\t\t\teData, _ := base64.RawURLEncoding.DecodeString(v.E)\n\t\t\t\teBig := new(big.Int)\n\t\t\t\teBig.SetBytes(eData)\n\t\t\t\tpubKey.E = int(eBig.Int64())\n\t\t\t\tpubKey.N.SetBytes(nByte)\n\n\t\t\t\treturn pubKey, nil\n\t\t\t}\n\t\t}\n\n\t\t// 'kid' v tokenu se ni ujemal z nobenim\n\t\treturn nil, errors.New(\"Google kid and token kid do not match\")\n\t})\n\t// Preveri ce je prislo do napake med parsanjem\n\tif err != nil {\n\t\tlog.Error(\"Problem Google tokeca: \", err)\n\t\trespondWithError(w, 400, \"Problem pri parsanju Google tokeca\")\n\t\treturn\n\t}\n\n\t// TODO: preveri ali je AUD prisel iz biolog\n\n\t// Preberi 'claims' iz tokena\n\tif claims, _ := tok.Claims.(jwt.MapClaims); tok.Valid {\n\t\tgu := new(GoogleUser)\n\t\tgu.Email = claims[\"email\"].(string)\n\t\tgu.EmailVerified = claims[\"email_verified\"].(bool)\n\t\tgu.FamilyName = claims[\"family_name\"].(string)\n\t\tgu.GivenName = claims[\"given_name\"].(string)\n\t\tgu.ID = claims[\"sub\"].(string)\n\t\tgu.Name = claims[\"name\"].(string)\n\t\tgu.Picture = claims[\"picture\"].(string)\n\n\t\t// Preveri ali uporabnik obstaja (unique email)\n\t\tu, err = h.UserHandler.UserService.UserByEmail(gu.Email)\n\t\tif err != nil {\n\t\t\t// Prislo je do napake, ali pa uporabnik ne obstaja\n\t\t\tif err.Error() == \"Not found\" {\n\t\t\t\t// Uporabnik ni bil najden, torej se prijavlja na novo\n\t\t\t\t// Iz GoogleUser izgradi biolog.User in ga shrani v PB\n\t\t\t\tu = &biolog.User{\n\t\t\t\t\tExternalID: &gu.ID,\n\t\t\t\t\tDisplayName: &gu.Name,\n\t\t\t\t\tGivenName: &gu.GivenName,\n\t\t\t\t\tFamilyName: &gu.FamilyName,\n\t\t\t\t\tEmail: &gu.Email,\n\t\t\t\t\tPicture: &gu.Picture,\n\t\t\t\t\tExternalAuthProvider: &googleAuth,\n\t\t\t\t}\n\t\t\t\tu, err = h.UserHandler.UserService.CreateUser(*u)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(\"Uporabnika ni bilo mogoce kreirati: \", err)\n\t\t\t\t\trespondWithError(w, http.StatusInternalServerError, \"Napaka pri kreiranju uporabnika\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Prislo je do druge napake pri iskanju uporabnika\n\t\t\t\tlog.Error(\"Iskanje uporabnika po emailu:\", err)\n\t\t\t\trespondWithError(w, http.StatusInternalServerError, \"Napaka pri iskanju uporabnika\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else {\n\t\trespondWithError(w, 400, \"Google tokec ni veljaven\")\n\t\treturn\n\t}\n\n\t// Preveri ali imamo podatke o uporabniki za kreiranje JWT\n\tif u == nil {\n\t\trespondWithError(w, 500, \"Uporabnik pri prijavljanju je nil\")\n\t\treturn\n\t}\n\n\t// Dodeli nov JWT uporabniku\n\t// TODO:\n\t// - preveri cas za potek JWT tokena (10-15min ?)\n\tclaims := &EmailClaims{\n\t\t*u.Email,\n\t\tjwt.StandardClaims{\n\t\t\tExpiresAt: time.Now().Unix() + 3600,\n\t\t\tIssuer: \"biolog-app\",\n\t\t},\n\t}\n\tjwttok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\n\tss, _ := jwttok.SignedString(jwtSignKey)\n\tssJSON, _ := json.Marshal(map[string]string{\"token\": ss})\n\n\t// Odgovori z JWT v telesu zahtevka\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(ssJSON)\n}", "func (srv *targetServiceHandler) auth(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := httpbakery.ContextWithRequest(context.TODO(), req)\n\t\tops, err := opsForRequest(req)\n\t\tif err != nil {\n\t\t\tfail(w, http.StatusInternalServerError, \"%v\", err)\n\t\t\treturn\n\t\t}\n\t\tauthChecker := srv.checker.Auth(httpbakery.RequestMacaroons(req)...)\n\t\tif _, err = authChecker.Allow(ctx, ops...); err != nil {\n\t\t\thttpbakery.WriteError(ctx, w, srv.oven.Error(ctx, req, err))\n\t\t\treturn\n\t\t}\n\t\th.ServeHTTP(w, req)\n\t})\n}", "func verifyAuth(w http.ResponseWriter, r *http.Request) {\n\thttpJSON(w, httpMessageReturn{Message: \"OK\"}, http.StatusOK, nil)\n}", "func (s *Server) Authenticate(wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\ts.Session = grequests.NewSession(nil)\n\tresp, err := s.Session.Get(s.URL+loginURL, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tlog.Fatalln(\"Failed to get csrf: \" + s.Name)\n\t}\n\n\tdoc, err := goquery.NewDocumentFromReader(strings.NewReader((resp.String())))\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tlog.Fatalln(\"Failed to parse html: \" + s.Name)\n\t}\n\n\tcsrfToken := \"\"\n\tdoc.Find(\"meta\").Each(func(i int, s *goquery.Selection) {\n\t\tif name, _ := s.Attr(\"name\"); name == \"csrf-token\" {\n\t\t\tcsrfToken, _ = s.Attr(\"content\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tresp, err = s.Session.Get(s.URL+verifyURL, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tlog.Fatalln(\"Failed to verify: \" + s.Name)\n\t}\n\n\ts.Headers = &map[string]string{\n\t\t\"csrf-token\": csrfToken,\n\t\t\"Connection\": \"keep-alive\",\n\t\t\"Content-Type\": \"application/json\",\n\t\t\"Accept\": \"application/x-www-form-urlencoded; charset=utf-8\",\n\t}\n\n\tresp, err = s.Session.Post(s.URL+passwordURL, &grequests.RequestOptions{\n\t\tJSON: map[string]string{\n\t\t\t\"username\": s.Username,\n\t\t\t\"password\": s.Password,\n\t\t},\n\t\t// Cookies: cookies.Cookies,\n\t\tHeaders: *s.Headers,\n\t})\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tlog.Fatalln(\"Failed to login: \" + s.Name)\n\t}\n\n\t// pretty.Println(resp.String())\n\tif !s.IsThirdParty {\n\t\t// log.Println(\"TOTP logic here...\")\n\t\ttotp := gotp.NewDefaultTOTP(s.Seed)\n\t\t// log.Println(totp.Now())\n\t\tresp, err = s.Session.Post(s.URL+challengeURL, &grequests.RequestOptions{\n\t\t\tJSON: map[string]string{\n\t\t\t\t\"username\": s.Username,\n\t\t\t\t\"password\": s.Password,\n\t\t\t\t\"challenge\": totp.Now(),\n\t\t\t},\n\t\t\t// Cookies: cookies.Cookies,\n\t\t\tHeaders: *s.Headers,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tlog.Fatalln(\"Failed to login: \" + s.Name)\n\t\t}\n\t\t// pretty.Println(resp.String())\n\t}\n}", "func GitHubOAuthHandler(w http.ResponseWriter, r *http.Request) {\n\turl := r.URL.Query()\n\ttoken, err := ghOAuth.Exchange(oauth2.NoContext, url.Get(\"code\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tid, _ := strconv.Atoi(url.Get(\"state\"))\n\t_, _, err = dbClient.Collection(\"users\").Add(ctx, map[string]interface{}{\n\t\t\"ID\": id,\n\t\t\"Token\": token.AccessToken,\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed adding user: %v\", err)\n\t}\n\thttp.Redirect(w, r, \"https://t.me/kfr_cibot\", 302)\n}", "func buildAuth() autoupdateHttp.Authenticator {\n\treturn fakeAuth(1)\n}", "func buildAuth() autoupdateHttp.Authenticator {\n\treturn fakeAuth(1)\n}", "func (c *client) Auth(token, secret string) (string, error) {\n\treturn \"\", fmt.Errorf(\"Not Implemented\")\n}", "func VerifyAuthToken(r *http.Request) (Status, bool) {\n\n\t//initialise the default return status\n\ts := Status{\n\t\tgithub.User{},\n\t\tfalse,\n\t\tfalse,\n\t}\n\tctx := appengine.NewContext(r)\n\tauth, err := firebase.GetAuth()\n\tif err != nil {\n\t\tlog.Errorf(ctx, \"Credentials Error: %v\", err)\n\t\treturn s, false\n\t}\n\ttoken := r.Header.Get(\"Authorization\")\n\n\t// We have to use urlfetch when using App Engine\n\tdecodedToken, err := auth.VerifyIDTokenWithTransport(token, urlfetch.Client(ctx).Transport)\n\tif err != nil {\n\t\tlog.Infof(ctx, \"Credentials Error: %v\", err)\n\t\treturn s, false\n\t}\n\tclaims := decodedToken.Claims()\n\tfirebaseClaims, ok := claims[\"firebase\"].(map[string]interface{})\n\tif !ok {\n\t\tlog.Errorf(ctx, \"Firebase Claims Error: %v\", err)\n\t\treturn s, false\n\t}\n\tidentities, ok := firebaseClaims[\"identities\"].(map[string]interface{})\n\tif !ok {\n\t\tlog.Errorf(ctx, \"Firebase Identities Error: %v\", ok)\n\t\treturn s, false\n\t}\n\tvar u github.User\n\tidString := \"\"\n\tID, ok := identities[\"github.com\"].([]interface{})\n\tif !ok {\n\t\tlog.Errorf(ctx, \"Failed to get provider data: %v\", ok)\n\t\treturn s, false\n\t}\n\tidString = ID[0].(string)\n\tu.ID, _ = strconv.ParseUint(idString, 10, 64)\n\n\temail, ok := identities[\"email\"].([]interface{})\n\tif !ok {\n\t\tlog.Errorf(ctx, \"Invalid email error: %v\", ok)\n\t\treturn s, false\n\t}\n\tu.Email, _ = email[0].(string)\n\tu.FireKey, ok = claims[\"user_id\"].(string)\n\tif !ok {\n\t\tlog.Errorf(ctx, \"Firebase Key Error: %v\", err)\n\t\treturn s, false\n\t}\n\tuserFromDB, newUser := u.IsNew()\n\tif newUser || userFromDB.ID == 0 {\n\t\t// Get login name from Github\n\t\tresp, err := github.API(ctx, userAPI+idString)\n\t\tif err != nil {\n\t\t\treturn s, false\n\t\t}\n\t\tresBody, _ := ioutil.ReadAll(resp.Body)\n\t\tvar jsonResponse map[string]interface{}\n\t\tjson.Unmarshal(resBody, &jsonResponse)\n\t\tu.Login = jsonResponse[\"login\"].(string)\n\t\tu.Add()\n\t\ts = Status{u, true, true}\n\t} else {\n\t\ts = Status{userFromDB, true, false}\n\t}\n\n\t// returns user, validity and whether or not the user is a new user\n\treturn s, true\n}", "func Auth(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Infof(\"Authenticating request: \")\n\t\tif r.Header.Get(\"user\") != \"foo\" {\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tlog.Infof(\"Auth: Pass\")\n\t\tnext.ServeHTTP(w, r)\n\n\t})\n}", "func MakeAuthAPI(\n\tmetricsName string, userAPI userapi.QueryAcccessTokenAPI,\n\tf func(*http.Request, *userapi.Device) util.JSONResponse,\n\tchecks ...AuthAPIOption,\n) http.Handler {\n\th := func(req *http.Request) util.JSONResponse {\n\t\tlogger := util.GetLogger(req.Context())\n\t\tdevice, err := auth.VerifyUserFromRequest(req, userAPI)\n\t\tif err != nil {\n\t\t\tlogger.Debugf(\"VerifyUserFromRequest %s -> HTTP %d\", req.RemoteAddr, err.Code)\n\t\t\treturn *err\n\t\t}\n\t\t// add the user ID to the logger\n\t\tlogger = logger.WithField(\"user_id\", device.UserID)\n\t\treq = req.WithContext(util.ContextWithLogger(req.Context(), logger))\n\t\t// add the user to Sentry, if enabled\n\t\thub := sentry.GetHubFromContext(req.Context())\n\t\tif hub != nil {\n\t\t\thub.Scope().SetUser(sentry.User{\n\t\t\t\tUsername: device.UserID,\n\t\t\t})\n\t\t\thub.Scope().SetTag(\"user_id\", device.UserID)\n\t\t\thub.Scope().SetTag(\"device_id\", device.ID)\n\t\t}\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tif hub != nil {\n\t\t\t\t\thub.CaptureException(fmt.Errorf(\"%s panicked\", req.URL.Path))\n\t\t\t\t}\n\t\t\t\t// re-panic to return the 500\n\t\t\t\tpanic(r)\n\t\t\t}\n\t\t}()\n\n\t\t// apply additional checks, if any\n\t\topts := AuthAPIOpts{}\n\t\tfor _, opt := range checks {\n\t\t\topt(&opts)\n\t\t}\n\n\t\tif !opts.GuestAccessAllowed && device.AccountType == userapi.AccountTypeGuest {\n\t\t\treturn util.JSONResponse{\n\t\t\t\tCode: http.StatusForbidden,\n\t\t\t\tJSON: spec.GuestAccessForbidden(\"Guest access not allowed\"),\n\t\t\t}\n\t\t}\n\n\t\tjsonRes := f(req, device)\n\t\t// do not log 4xx as errors as they are client fails, not server fails\n\t\tif hub != nil && jsonRes.Code >= 500 {\n\t\t\thub.Scope().SetExtra(\"response\", jsonRes)\n\t\t\thub.CaptureException(fmt.Errorf(\"%s returned HTTP %d\", req.URL.Path, jsonRes.Code))\n\t\t}\n\t\treturn jsonRes\n\t}\n\treturn MakeExternalAPI(metricsName, h)\n}", "func (a *App) Auth() negroni.HandlerFunc {\n\treturn negroni.HandlerFunc(func(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {\n\t\tdb, ok := context.Get(req, \"db\").(*mgo.Database)\n\t\tif !ok {\n\t\t\ta.R.JSON(w, http.StatusInternalServerError, &Response{Status: \"Error\", Message: \"Internal server error\"})\n\t\t\treturn\n\t\t}\n\t\tauthHeader := req.Header.Get(\"Authorization\")\n\t\tif authHeader == \"\" {\n\t\t\ta.R.JSON(w, http.StatusUnauthorized, &Response{Status: \"Error\", Message: \"Not Authorized\"})\n\t\t\treturn\n\t\t}\n\t\tdata, err := base64.StdEncoding.DecodeString(strings.Replace(authHeader, \"Basic \", \"\", 1))\n\t\tif err != nil {\n\t\t\ta.R.JSON(w, http.StatusUnauthorized, &Response{Status: \"Error\", Message: \"Not Authorized\"})\n\t\t\treturn\n\t\t}\n\t\tuser := &User{}\n\t\tparts := strings.Split(string(data), \":\")\n\t\tif len(parts) < 2 {\n\t\t\ta.R.JSON(w, http.StatusUnauthorized, &Response{Status: \"Error\", Message: \"Not Authorized\"})\n\t\t\treturn\n\t\t}\n\t\tif parts[0] == parts[1] {\n\t\t\tshaHash := sha256.New()\n\t\t\tif _, err := shaHash.Write([]byte(parts[0])); err != nil {\n\t\t\t\ta.R.JSON(w, http.StatusUnauthorized, &Response{Status: \"Error\", Message: \"Not Authorized\"})\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttoken := base64.StdEncoding.EncodeToString(shaHash.Sum(nil))\n\t\t\tif err := db.C(\"users\").Find(bson.M{\n\t\t\t\t\"services.resume.loginTokens\": bson.M{\"$elemMatch\": bson.M{\"hashedToken\": token}},\n\t\t\t}).One(&user); err != nil {\n\t\t\t\ta.R.JSON(w, http.StatusUnauthorized, &Response{Status: \"Error\", Message: \"Not Authorized\"})\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tin := []bson.M{bson.M{\"address\": parts[0], \"verified\": false}}\n\t\t\tif err := db.C(\"users\").Find(bson.M{\"emails\": bson.M{\"$in\": in}}).One(&user); err != nil {\n\t\t\t\ta.R.JSON(w, http.StatusUnauthorized, &Response{Status: \"Error\", Message: \"Not Authorized\"})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tshaHash := sha256.New()\n\t\t\tif _, err := shaHash.Write([]byte(parts[1])); err != nil {\n\t\t\t\thttp.Error(w, \"Not Authorized\", http.StatusUnauthorized)\n\t\t\t\treturn\n\t\t\t}\n\t\t\th := hex.EncodeToString(shaHash.Sum(nil))\n\t\t\tif err := bcrypt.CompareHashAndPassword([]byte(user.Services.Password.Bcrypt), []byte(h)); err != nil {\n\t\t\t\ta.R.JSON(w, http.StatusUnauthorized, &Response{Status: \"Error\", Message: \"Not Authorized\"})\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tcontext.Set(req, \"user\", user)\n\t\tnext(w, req)\n\t})\n}", "func (r *Request) BasicAuth() (username, password string, ok bool)", "func (c *B2) authGet(apiPath string) (*http.Response, *authorizationState, error) {\n\treq, auth, err := c.authRequest(\"GET\", apiPath, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err := c.httpClient.Do(req)\n\treturn resp, auth, err\n}", "func Github(t string) func(c *Conn) (*api.Secret, error) {\n\treturn func(c *Conn) (*api.Secret, error) {\n\t\treturn c.Client.Write(\"/auth/github/login\", map[string]interface{}{\n\t\t\t\"token\": t,\n\t\t})\n\t}\n}", "func Github(opts *oauth2.Options) martini.Handler {\n\tauthUrl := \"https://github.com/login/oauth/authorize\"\n\ttokenUrl := \"https://github.com/login/oauth/access_token\"\n\treturn NewOAuth2Provider(opts, authUrl, tokenUrl)\n}", "func (g *GitHub) getToken(code, state string) error {\n\tif code == \"\" || state == \"\" {\n\t\tlog.ErrorWithFields(\"code or state is nil\", log.Fields{\"code\": code, \"state\": state})\n\t\treturn fmt.Errorf(\"code or state is nil\")\n\t}\n\tlog.InfoWithFields(\"cyclone receives auth code\", log.Fields{\"request code\": code})\n\n\t// Get a object to request token.\n\tconf, err := g.getConf()\n\tif err != nil {\n\t\tlog.Warnf(\"Unable to get the conf according coderepository\")\n\t\treturn err\n\t}\n\n\t// To communication with githubo or other vcs to get token.\n\tvar tok *oauth2.Token\n\ttok, err = conf.Exchange(oauth2.NoContext, code) // Post a token request and receive toeken.\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\n\tif !tok.Valid() {\n\t\tlog.Fatalf(\"Token invalid. Got: %#v\", tok)\n\t\treturn err\n\t}\n\tlog.Info(\"get the token successfully!\")\n\n\t// Create service in database (but not ready to be used yet).\n\tvcstoken := api.VscToken{\n\t\tUserID: state,\n\t\tVsc: \"github\",\n\t\tVsctoken: *tok,\n\t}\n\n\tds := store.NewStore()\n\tdefer ds.Close()\n\n\t_, err = ds.FindtokenByUserID(state, \"github\")\n\tif err != nil {\n\t\terr = ds.NewTokenDocument(&vcstoken)\n\t\tif err != nil {\n\t\t\tlog.ErrorWithFields(\"NewTokenDocument\", log.Fields{\"user_id\": state,\n\t\t\t\t\"token\": tok, \"error\": err})\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\terr = ds.UpdateToken(&vcstoken)\n\t\tif err != nil {\n\t\t\tlog.ErrorWithFields(\"UpdateToken\", log.Fields{\"user_id\": state,\n\t\t\t\t\"token\": tok, \"error\": err})\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func GithubLoginHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"GithubLoginHandler\")\n\tparams := r.URL.Query()[\"jwt\"]\n\tif len(params) == 0 {\n\t\thttp.Redirect(w, r, \"/\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tcurState := params[0]\n\turl := githubOauthConfig.AuthCodeURL(curState)\n\thttp.Redirect(w, r, url, http.StatusTemporaryRedirect)\n}", "func GetAuth(user, password, request_type, endpoint, body string) (map[string]interface{}, *http.Response) {\n\t\thttp.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\t\tclient := &http.Client{}\n\t\tdata := []byte(body)\n redfish_ep := strings.Replace(endpoint, \"redfish\", \"https\", 1)\n req, err := http.NewRequest(request_type, redfish_ep, bytes.NewBuffer(data))\n\t\treq.SetBasicAuth(user, password)\n\t\treq.Header.Add(\"Content-Type\", \"application/json\")\n\t\treq.Header.Set(\"Accept\", \"application/json\")\n\t\tresp, err := client.Do(req)\n\t\tresp_json := make(map[string]interface{})\n\t\tif err != nil{\n\t fmt.Printf(\"The HTTP request failed with error %s\\n\", err)\n\t } else {\n\t \t\tbodyText, err := ioutil.ReadAll(resp.Body)\n\t\t// defer resp.Body.Close()\n\t\tif err != nil{\n\t \t\tfmt.Printf(\"The HTTP request failed with error %s\\n\", err)\n\t }\n\t\ts := []byte(bodyText)\n\t\tjson.Unmarshal(s, &resp_json)\n}\n\t\tdefer resp.Body.Close()\n\t\treturn resp_json, resp\n}", "func beginAuth(w http.ResponseWriter, r *http.Request) {\n\tgothic.BeginAuthHandler(w, r)\n}", "func authHandler(w http.ResponseWriter, r *http.Request) {\n\turl := config(r.Host).AuthCodeURL(r.URL.RawQuery)\n\thttp.Redirect(w, r, url, http.StatusFound)\n}", "func simpleAuth(w http.ResponseWriter, r *http.Request) (err string) {\n\theader := strings.Fields(r.Header.Get(\"Authorization\"))\n\tif len(header) < 2 {\n\t\tInfo.Println(\"No token given, not able to process request\")\n\t\treturn \"ko\"\n\t}\n\ts := strings.SplitN(r.Header.Get(\"Authorization\"), \" \", 2)\n\tif s[1] == token {\n\t\tDebug.Println(\"Token is eligible\")\n\t} else {\n\t\thttp.Error(w, \"Not authorized\", 401)\n\n\t}\n\treturn \"\"\n}", "func (h *TestAuth) Forgot(w http.ResponseWriter, req *http.Request) {\n\tresponse := make(map[string]string, 5)\n\n\tresponse[\"state\"] = authz.AuthSuccess\n\tresponse[\"access_token\"] = \"access\"\n\t//response[\"id_token\"] = *authResult.IdToken\n\tresponse[\"refresh_token\"] = \"refersh\"\n\tresponse[\"expires\"] = \"3600\"\n\tresponse[\"token_type\"] = \"Bearer\"\n\trespData, _ := json.Marshal(response)\n\tw.WriteHeader(200)\n\tfmt.Fprint(w, string(respData))\n}", "func Login(hc *http.Client, gateEndpoint string, token *oauth2.Token) error {\n\treq, err := http.NewRequest(http.MethodGet, gateEndpoint+\"/login\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", token.AccessToken))\n\n\tif _, err := hc.Do(req); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Github(config *Config) negroni.Handler {\n\tauthUrl := \"https://github.com/login/oauth/authorize\"\n\ttokenUrl := \"https://github.com/login/oauth/access_token\"\n\treturn NewOAuth2Provider(config, authUrl, tokenUrl)\n}", "func auth(c *bm.Context) {\n\tvar (\n\t\tparams = c.Request.Form\n\t\terr error\n\t\tipaddr, cdnip string\n\t\tmid, aid int64\n\t)\n\taidStr := params.Get(\"aid\")\n\tif aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil {\n\t\tc.JSON(nil, ecode.RequestErr)\n\t\treturn\n\t}\n\tif vmid, ok := c.Get(\"mid\"); !ok {\n\t\tmid = 0\n\t} else {\n\t\tmid = vmid.(int64)\n\t}\n\tipaddr = params.Get(\"ip\")\n\tcdnip = params.Get(\"cdnip\")\n\tif ipaddr == \"\" && cdnip == \"\" {\n\t\tc.JSON(nil, ecode.RequestErr)\n\t\treturn\n\t}\n\tc.JSON(svr.Auth(c, aid, mid, ipaddr, cdnip))\n}", "func AuthHandler(w http.ResponseWriter, r *http.Request) {\n\tdecoder := json.NewDecoder(r.Body)\n\tvar b authBody\n\terr := decoder.Decode(&b)\n\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid Body.\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tgoogleID, err := firebase.VerifyIDToken(b.GoogleToken, os.Getenv(\"FIREBASE_PROJECT_ID\"))\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusForbidden)\n\t\treturn\n\t}\n\n\tuser, err := models.FindUserByGoogleIDOrInit(googleID)\n\n\tif err != nil {\n\t\tInternalServerError(err, w)\n\t\treturn\n\t}\n\n\tif user.Name == \"\" {\n\t\tid := hash(googleID)\n\n\t\tname := \"\"\n\t\ti := 0\n\t\tfor name == \"\" {\n\t\t\tgenName, err2 := nameGen.GenerateNameWithSeed(1, 1, 3, int64(id+uint32(i)))\n\t\t\tif err2 != nil {\n\t\t\t\thttp.Error(w, err2.Error(), http.StatusForbidden)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tcount, err3 := models.CountUsersByName(genName)\n\t\t\tif err3 != nil {\n\t\t\t\tInternalServerError(err, w)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif count == 0 {\n\t\t\t\tname = genName\n\t\t\t}\n\t\t\ti = i + 1\n\t\t}\n\n\t\tuser.Name = name\n\t\tuser.Balance = scores.InitialBalance\n\t}\n\n\terr = user.Save()\n\tif err != nil {\n\t\tInternalServerError(err, w)\n\t\treturn\n\t}\n\n\ttoken, err := auth.GenerateJWTToken(user)\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusForbidden)\n\t\treturn\n\t}\n\n\tuser.AvatarURL = os.Getenv(\"BASE_URL\") + \"/users/\" + user.Name + \"/avatar\"\n\n\tbytes, err := json.Marshal(authResponseBody{Token: token, User: user})\n\n\tif err != nil {\n\t\tInternalServerError(err, w)\n\t\treturn\n\t}\n\n\tw.Write(bytes)\n}", "func authWrapper(handler http.HandlerFunc, secrets auth.SecretProvider, host string) http.HandlerFunc {\n\tauthenticator := &auth.BasicAuth{Realm: host, Secrets: secrets}\n\treturn auth.JustCheck(authenticator, handler)\n}", "func (p *PoolHeightFetcher) Auth() {\n\tvar msg models.StratumMsg\n\tmethod := \"mining.authorize\"\n\tmsg.ID = p.ID\n\tmsg.Method = method\n\tmsg.Params = []string{p.Param.Username, p.Param.Password}\n\tp.AuthID = msg.ID.(uint64)\n\tp.ID++\n\t// beam\n\tif p.Param.CoinType == \"beam\" {\n\t\tmsg.Method = \"login\"\n\t\tmsg.ID = \"login\"\n\t\tmsg.APIKey = p.Param.Username\n\t\tmsg.JsonRPC = \"2.0\"\n\t}\n\tif p.Param.CoinType == \"grin\" {\n\t\tmsg.Method = \"login\"\n\t\tmsg.ID = \"login\"\n\t\tmsg.Params = map[string]string{\n\t\t\t\"login\": p.Param.Username,\n\t\t\t\"pass\": p.Param.Password,\n\t\t\t\"agent\": \"grin-miner\",\n\t\t}\n\t}\n\tp.WriteConn(msg)\n}", "func RedirectHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"I AM HERE REDIRECTED\")\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stdout, \"could not parse query: %s\", err.Error())\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t}\n\tcode := r.FormValue(\"code\")\n\n\treqURL := fmt.Sprintf(\"https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s\", ClientID, ClientSecret, code)\n\treq, err := http.NewRequest(http.MethodPost, reqURL, nil)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stdout, \"could not retrieve http request: %s\", err.Error())\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t}\n\n\treq.Header.Set(http.CanonicalHeaderKey(\"accept\"), \"application/json\")\n\treq.Header.Set(\"X-OAuth-Scopes\", \"gists\")\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stdout, \"could not send HTTP request: %s\", err.Error())\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t}\n\n\tdefer res.Body.Close()\n\t// Parse the request body into the `OAuthAccessResponse` struct\n\tvar t OAuthAccessResponse\n\tif err := json.NewDecoder(res.Body).Decode(&t); err != nil {\n\t\tfmt.Fprintf(os.Stdout, \"could not parse JSON response: %s\", err.Error())\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t}\n\tSession.AccessToken = t.AccessToken\n\n\tw.WriteHeader(http.StatusFound)\n\tw.Write([]byte(\"OK\"))\n}", "func (g *GitLab) Auth(ctx context.Context, token, _ string) (string, error) {\n\tclient, err := newClient(g.url, token, g.SkipVerify)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tlogin, _, err := client.Users.CurrentUser(gitlab.WithContext(ctx))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn login.Username, nil\n}", "func Auth(g *gin.Context) {\n\tvar data POSTdata\n\tg.BindJSON(&data)\n\n\tcache := models.InitCache()\n\n\t//check password\n\tgetpass, check := user[data.Username]\n\tif !check || getpass != data.Password {\n\t\treturn\n\t}\n\n\t//Create token of cookie, and it in sessionToken\n\tu, err := uuid.NewV4()\n\tsessionToken := u.String()\n\n\t//Set SessionToken to Redis \n\t_, err = cache.Do(\"SETEX\", sessionToken, \"1800\", data.Username)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t//Set Cookie to User\n\thttp.SetCookie(g.Writer, &http.Cookie{\n\t\tName:\t\t\"session_token\",\n\t\tValue:\t\tsessionToken,\n\t\tExpires:\ttime.Now().Add(120 * time.Second),\n\t})\n\n}" ]
[ "0.6465212", "0.6398342", "0.63612264", "0.6326609", "0.6284491", "0.623715", "0.6218349", "0.62039566", "0.6200897", "0.61832404", "0.6146673", "0.6112144", "0.6095562", "0.6078164", "0.60686564", "0.60548", "0.6046615", "0.6037247", "0.6036029", "0.6015311", "0.59805304", "0.59483975", "0.5921521", "0.59149015", "0.58718854", "0.5866347", "0.58506215", "0.5847065", "0.5832375", "0.58041817", "0.58010095", "0.579778", "0.57725155", "0.57372457", "0.5722094", "0.5704712", "0.568159", "0.5681049", "0.566758", "0.5663564", "0.5653375", "0.56528574", "0.5641246", "0.5640423", "0.5640087", "0.5628404", "0.56217474", "0.5611092", "0.56061995", "0.560541", "0.5601475", "0.56005836", "0.5587685", "0.5576382", "0.55749094", "0.55747485", "0.5563508", "0.55617005", "0.5558426", "0.55578476", "0.55474156", "0.55439067", "0.5539885", "0.5531038", "0.55262125", "0.5520451", "0.5515269", "0.55137986", "0.55111384", "0.5510395", "0.55062115", "0.55033904", "0.5501796", "0.54904974", "0.54904974", "0.5484287", "0.5481979", "0.5468725", "0.5462572", "0.54575914", "0.5456761", "0.5453161", "0.5449576", "0.5435277", "0.5413009", "0.54043776", "0.54005444", "0.5398684", "0.53972524", "0.5387719", "0.5377528", "0.5365735", "0.5365665", "0.5364161", "0.5358167", "0.534822", "0.53451514", "0.5343953", "0.5338569", "0.53350765" ]
0.62837017
5
CheckAuth ... Checks personal access token validity by requesting private repositories and checking status code
func (g *GitHubImpl) CheckAuth() (bool, error) { URL := fmt.Sprintf(g.URLNoEsc(urls.userRepo)) req, _ := http.NewRequest("GET", URL, nil) q := req.URL.Query() q.Add("access_token", g.token) req.URL.RawQuery = q.Encode() client := http.DefaultClient res, err := client.Do(req) if err != nil { return false, err } if res.StatusCode != http.StatusOK { return false, errors.New(strconv.Itoa(res.StatusCode)) } return true, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CheckAuth(ctx context.Context, sys *types.SystemContext, username, password, registry string) error {\n\tnewLoginClient, err := newDockerClientWithDetails(sys, registry, username, password, \"\", nil, \"\")\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"error creating new docker client\")\n\t}\n\n\tresp, err := newLoginClient.makeRequest(ctx, \"GET\", \"/v2/\", nil, nil, v2Auth)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tswitch resp.StatusCode {\n\tcase http.StatusOK:\n\t\treturn nil\n\tcase http.StatusUnauthorized:\n\t\treturn ErrUnauthorizedForCredentials\n\tdefault:\n\t\treturn errors.Errorf(\"error occured with status code %q\", resp.StatusCode)\n\t}\n}", "func authCheck(c *gin.Context) {\n\t// Parse the token from the header. Take into account that the token prepended by Bearer\n\t// keyword.\n\tvar (\n\t\ttoken string\n\t\terr error\n\t)\n\t{\n\t\th := c.GetHeader(\"Authorization\")\n\t\tif len(h) < 8 {\n\t\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, msg(\"authorization header missed or not valid\"))\n\t\t\treturn\n\t\t}\n\t\ts := strings.SplitN(h, \"Bearer \", 2)\n\t\tif len(s) < 2 {\n\t\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, msg(\"badly formatted authorization header (Bearer missed)\"))\n\t\t\treturn\n\t\t}\n\t\ttoken = s[1]\n\t}\n\n\t// Pass auth data into gin context.\n\tvar u *user.User\n\t{\n\t\tif u, err = user.AuthCheck(context.Background(), token); err != nil {\n\t\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, msg(err.Error()))\n\t\t\treturn\n\t\t}\n\t\tc.Set(session, *u)\n\t}\n\n\tc.Next()\n}", "func VerifyAuthToken(r *http.Request) (Status, bool) {\n\n\t//initialise the default return status\n\ts := Status{\n\t\tgithub.User{},\n\t\tfalse,\n\t\tfalse,\n\t}\n\tctx := appengine.NewContext(r)\n\tauth, err := firebase.GetAuth()\n\tif err != nil {\n\t\tlog.Errorf(ctx, \"Credentials Error: %v\", err)\n\t\treturn s, false\n\t}\n\ttoken := r.Header.Get(\"Authorization\")\n\n\t// We have to use urlfetch when using App Engine\n\tdecodedToken, err := auth.VerifyIDTokenWithTransport(token, urlfetch.Client(ctx).Transport)\n\tif err != nil {\n\t\tlog.Infof(ctx, \"Credentials Error: %v\", err)\n\t\treturn s, false\n\t}\n\tclaims := decodedToken.Claims()\n\tfirebaseClaims, ok := claims[\"firebase\"].(map[string]interface{})\n\tif !ok {\n\t\tlog.Errorf(ctx, \"Firebase Claims Error: %v\", err)\n\t\treturn s, false\n\t}\n\tidentities, ok := firebaseClaims[\"identities\"].(map[string]interface{})\n\tif !ok {\n\t\tlog.Errorf(ctx, \"Firebase Identities Error: %v\", ok)\n\t\treturn s, false\n\t}\n\tvar u github.User\n\tidString := \"\"\n\tID, ok := identities[\"github.com\"].([]interface{})\n\tif !ok {\n\t\tlog.Errorf(ctx, \"Failed to get provider data: %v\", ok)\n\t\treturn s, false\n\t}\n\tidString = ID[0].(string)\n\tu.ID, _ = strconv.ParseUint(idString, 10, 64)\n\n\temail, ok := identities[\"email\"].([]interface{})\n\tif !ok {\n\t\tlog.Errorf(ctx, \"Invalid email error: %v\", ok)\n\t\treturn s, false\n\t}\n\tu.Email, _ = email[0].(string)\n\tu.FireKey, ok = claims[\"user_id\"].(string)\n\tif !ok {\n\t\tlog.Errorf(ctx, \"Firebase Key Error: %v\", err)\n\t\treturn s, false\n\t}\n\tuserFromDB, newUser := u.IsNew()\n\tif newUser || userFromDB.ID == 0 {\n\t\t// Get login name from Github\n\t\tresp, err := github.API(ctx, userAPI+idString)\n\t\tif err != nil {\n\t\t\treturn s, false\n\t\t}\n\t\tresBody, _ := ioutil.ReadAll(resp.Body)\n\t\tvar jsonResponse map[string]interface{}\n\t\tjson.Unmarshal(resBody, &jsonResponse)\n\t\tu.Login = jsonResponse[\"login\"].(string)\n\t\tu.Add()\n\t\ts = Status{u, true, true}\n\t} else {\n\t\ts = Status{userFromDB, true, false}\n\t}\n\n\t// returns user, validity and whether or not the user is a new user\n\treturn s, true\n}", "func CheckAuth(s Session) *PzCustomError {\n\ttargURL := s.PzAddr + \"/service\"\n\tLogAudit(s, s.UserID, \"verify Piazza auth key request\", targURL, \"\", INFO)\n\t_, err := SubmitSinglePart(\"GET\", \"\", targURL, s.PzAuth)\n\tif err != nil {\n\t\treturn &PzCustomError{LogMsg: \"Could not confirm user authorization.\"}\n\t}\n\tLogAudit(s, targURL, \"verify Piazza auth key response\", s.UserID, \"\", INFO)\n\treturn nil\n}", "func checkAuth(w http.ResponseWriter, r *http.Request, s *MemorySessionStore) bool {\n\tauth := r.Header.Get(\"Authorization\")\n\tif auth == \"\" {\n\t\treturnHTTP(w, http.StatusUnauthorized, nil)\n\t\treturn false\n\t}\n\n\tmatch := authRegexp.FindStringSubmatch(auth)\n\tif len(match) != 2 {\n\t\treturnHTTP(w, http.StatusBadRequest, nil)\n\t\treturn false\n\t}\n\n\tid := match[1]\n\tif !s.Check(id) {\n\t\treturnHTTP(w, http.StatusUnauthorized, nil)\n\t\treturn false\n\t}\n\n\treturn true\n}", "func gwAuthChecker(urls []conf.AllowUrl) gin.HandlerFunc {\n\tvar allowUrls = make(map[string]bool)\n\tfor _, url := range urls {\n\t\tfor _, p := range url.Urls {\n\t\t\ts := p\n\t\t\tallowUrls[s] = true\n\t\t}\n\t}\n\treturn func(c *gin.Context) {\n\t\ts := getHostServer(c)\n\t\tuser := getUser(c)\n\t\tpath := fmt.Sprintf(\"%s:%s\", c.Request.Method, c.Request.URL.Path)\n\t\trequestId := getRequestId(s, c)\n\t\t//\n\t\t// No auth and request URI not in allowed urls.\n\t\t// UnAuthorized\n\t\t//\n\t\tif (user.IsEmpty() || !user.IsAuth()) && !allowUrls[path] {\n\t\t\tauth := s.conf.Security.AuthServer\n\t\t\t// Check url are allow dict.\n\t\t\tpayload := gin.H{\n\t\t\t\t\"Auth\": gin.H{\n\t\t\t\t\t\"LogIn\": gin.H{\n\t\t\t\t\t\t\"Url\": fmt.Sprintf(\"%s/%s\",\n\t\t\t\t\t\t\tstrings.TrimRight(auth.Addr, \"/\"), strings.TrimLeft(auth.LogIn.Url, \"/\")),\n\t\t\t\t\t\t\"Methods\": auth.LogIn.Methods,\n\t\t\t\t\t\t\"AuthTypes\": auth.LogIn.AuthTypes,\n\t\t\t\t\t},\n\t\t\t\t\t\"LogOut\": gin.H{\n\t\t\t\t\t\t\"Url\": fmt.Sprintf(\"%s/%s\",\n\t\t\t\t\t\t\tstrings.TrimRight(auth.Addr, \"/\"), strings.TrimLeft(auth.LogOut.Url, \"/\")),\n\t\t\t\t\t\t\"Methods\": auth.LogOut.Methods,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t\tbody := s.RespBodyBuildFunc(http.StatusUnauthorized, requestId, errDefault401Msg, payload)\n\t\t\tc.JSON(http.StatusUnauthorized, body)\n\t\t\tc.Abort()\n\t\t\treturn\n\t\t}\n\t\tc.Next()\n\t}\n}", "func (s *server) checkAuth(r *http.Request) error {\n\tauthhdr := r.Header[\"Authorization\"]\n\tif len(authhdr) == 0 {\n\t\treturn ErrNoAuth\n\t}\n\n\tauthsha := sha256.Sum256([]byte(authhdr[0]))\n\tcmp := subtle.ConstantTimeCompare(authsha[:], s.authsha[:])\n\tif cmp != 1 {\n\t\treturn ErrBadAuth\n\t}\n\treturn nil\n}", "func CheckToken(token string) (*github.Authorization, error) {\n\t// Get our GitHub OAuth application ID\n\tclientID := getClientID()\n\n\t// Create a new basic authentication client to use in the request\n\tclient, ctx := getBasicAuthClient()\n\n\t// Check the token using the go-github library and grab the response\n\tauth, _, err := client.Authorizations.Check(ctx, clientID, token)\n\n\t// Check that the response has a value and no errors are present\n\tif auth == nil || err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Return the response and no errors\n\treturn auth, nil\n}", "func (o *SlackOAuthHandlers) Auth(w http.ResponseWriter, r *http.Request) {\n\tparams, err := url.ParseQuery(r.URL.RawQuery)\n\tif err != nil {\n\t\thlog.FromRequest(r).Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"parsing query params\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// An error is received when a user declines to install\n\t// or an unexpected issue occurs. The app treats a\n\t// declined install gracefully.\n\tif params[\"error\"] != nil {\n\t\tswitch params[\"error\"][0] {\n\t\tcase errAccessDenied:\n\t\t\thlog.FromRequest(r).Info().\n\t\t\t\tErr(errors.New(params[\"error\"][0])).\n\t\t\t\tMsg(\"user declined install\")\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\treturn\n\t\tdefault:\n\t\t\thlog.FromRequest(r).Error().\n\t\t\t\tErr(errors.New(params[\"error\"][0])).\n\t\t\t\tMsg(\"failed install\")\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\n\tcode := params[\"code\"]\n\tif len(code) != 1 {\n\t\thlog.FromRequest(r).Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"code not provided\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// TODO: inject an http client with http logging.\n\tresp, err := http.Get(fmt.Sprintf(\n\t\to.AccessURLTemplate,\n\t\to.ClientID,\n\t\to.ClientSecret,\n\t\tcode[0],\n\t))\n\tif err != nil {\n\t\thlog.FromRequest(r).Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"oauth req error\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvar access accessResponse\n\tif err := json.NewDecoder(resp.Body).Decode(&access); err != nil {\n\t\thlog.FromRequest(r).Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"unable to decode slack access response\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif !access.OK {\n\t\thlog.FromRequest(r).Warn().\n\t\t\tMsg(\"access not ok\")\n\t\tw.WriteHeader(http.StatusForbidden)\n\t\treturn\n\t}\n\n\terr = o.TokenWriter.Store(&TokenData{\n\t\tTeamID: access.TeamID,\n\t\tUserID: access.UserID,\n\t\tBotToken: access.Bot.BotAccessToken,\n\t\tBotUserID: access.Bot.BotUserID,\n\t\tAccessToken: access.AccessToken,\n\t})\n\tif err != nil {\n\t\thlog.FromRequest(r).Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"unable to store token\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tredirect := fmt.Sprintf(\"https://slack.com/app_redirect?app=%s\", o.AppID)\n\thttp.Redirect(w, r, redirect, http.StatusFound)\n}", "func CheckAuth(c *gin.Context) {\n\n}", "func (g *Gitlab) CheckToken(scm *api.SCMConfig) bool {\n\tif _, err := g.ListRepos(scm); err != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func Check() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar code int\n\t\tvar token string\n\n\t\tcode = e.SUCCESS\n\t\trToken := c.Request.Header[\"Authorization\"]\n\n\t\tif len(rToken) < 1 {\n\t\t\tcode = e.ERROR_MISSING_TOKEN\n\t\t} else {\n\t\t\ttoken = rToken[0]\n\t\t\tsplitToken := strings.Split(token, \"Bearer\")\n\t\t\ttoken = strings.TrimSpace(splitToken[1])\n\n\t\t\tclaims, err := util.ParseToken(token)\n\t\t\tif err != nil {\n\t\t\t\tcode = e.ERROR_AUTH_CHECK_TOKEN_FAIL\n\t\t\t} else {\n\t\t\t\tif time.Now().Unix() > claims.ExpiresAt {\n\t\t\t\t\tcode = e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT\n\t\t\t\t} else {\n\t\t\t\t\tc.Set(\"id_user\", claims.ID)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif code != e.SUCCESS {\n\t\t\tc.JSON(http.StatusUnauthorized, gin.H{\n\t\t\t\t\"code\": code,\n\t\t\t\t\"msg\": e.GetMsg(code),\n\t\t\t})\n\t\t\tc.Abort()\n\t\t\treturn\n\t\t}\n\n\t\tc.Next()\n\n\t}\n}", "func (a *BasicAuth) CheckAuth(r *http.Request) string {\n\ts := strings.SplitN(r.Header.Get(\"Authorization\"), \" \", 2)\n\tif len(s) != 2 || s[0] != \"Basic\" {\n\t\treturn \"\"\n\t}\n\n\tb, err := base64.StdEncoding.DecodeString(s[1])\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tpair := strings.SplitN(string(b), \":\", 2)\n\tif len(pair) != 2 {\n\t\treturn \"\"\n\t}\n\tuser, password := pair[0], pair[1]\n\tsecret := a.Secrets(user, a.Realm)\n\tif secret == \"\" {\n\t\treturn \"\"\n\t}\n\tcompare := compareFuncs[0].compare\n\tfor _, cmp := range compareFuncs[1:] {\n\t\tif strings.HasPrefix(secret, cmp.prefix) {\n\t\t\tcompare = cmp.compare\n\t\t\tbreak\n\t\t}\n\t}\n\tif compare([]byte(secret), []byte(password)) != nil {\n\t\treturn \"\"\n\t}\n\treturn pair[0]\n}", "func gitAuth() *http.BasicAuth {\n\n\tvar auth *http.BasicAuth\n\n\t// The username can be anything for HTTPS Git operations\n\tgitUsername := \"fanal-aquasecurity-scan\"\n\n\t// We first check if a GitHub token was provided\n\tgithubToken := os.Getenv(\"GITHUB_TOKEN\")\n\tif githubToken != \"\" {\n\t\tauth = &http.BasicAuth{\n\t\t\tUsername: gitUsername,\n\t\t\tPassword: githubToken,\n\t\t}\n\t\treturn auth\n\t}\n\n\t// Otherwise we check if a GitLab token was provided\n\tgitlabToken := os.Getenv(\"GITLAB_TOKEN\")\n\tif gitlabToken != \"\" {\n\t\tauth = &http.BasicAuth{\n\t\t\tUsername: gitUsername,\n\t\t\tPassword: gitlabToken,\n\t\t}\n\t\treturn auth\n\t}\n\n\t// If no token was provided, we simply return a nil,\n\t// which will make the request to be unauthenticated\n\treturn nil\n\n}", "func validateAccessToken(token string, providedUsername string) bool {\n\tidpHost, idpPort := resolveIdpHostAndPort()\n\turl := \"https://\" + idpHost + \":\" + idpPort + \"/oauth2/introspect\"\n\tpayload := strings.NewReader(\"token=\" + token)\n\treq, err := http.NewRequest(\"POST\", url, payload)\n\tif err != nil {\n\t\tglog.Error(\"Error creating new request to the introspection endpoint: \", err)\n\t\textension.Exit(extension.ErrorExitCode)\n\t}\n\n\tusername, password := resolveCredentials()\n\treq.SetBasicAuth(username, password)\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tglog.Error(\"Error sending the request to the introspection endpoint: \", err)\n\t\textension.Exit(extension.ErrorExitCode)\n\t}\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tglog.Error(\"Error reading the response from introspection endpoint: \", err)\n\t\textension.Exit(extension.ErrorExitCode)\n\t}\n\tvar result map[string]interface{}\n\terr = json.Unmarshal([]byte(string(body)), &result)\n\tif err != nil {\n\t\tglog.Error(\"Error un marshalling the json: \", err)\n\t\textension.Exit(extension.ErrorExitCode)\n\t}\n\tisActive, ok := (result[\"active\"]).(bool)\n\tif !ok {\n\t\tglog.Error(\"Error casting active to boolean. This may be due to a invalid token\")\n\t\textension.Exit(extension.ErrorExitCode)\n\t}\n\tisExpired := isExpired(result[\"exp\"])\n\tisValidUser := isValidUser(result[\"username\"], providedUsername)\n\treturn isExpired && isActive && isValidUser\n}", "func checkAuth(pswd string) Adapter {\n\treturn func(fn http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {\n\t\t\t// if no password was given to the server, leave the doors wide open\n\t\t\tif pswd == \"\" {\n\t\t\t\tfn.ServeHTTP(rw, req)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ts := http.StatusForbidden\n\n\t\t\t// make sure the header exists\n\t\t\ta, ok := req.Header[\"Authorization\"]\n\t\t\tif !ok {\n\t\t\t\thttp.Error(rw, (newResponse(s, 0)).JSON(), s)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// go returns a map, so loop over it\n\t\t\tfor _, v := range a {\n\t\t\t\t// Bearer\n\t\t\t\tif len(v) < 7 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif v[7:] == pswd {\n\t\t\t\t\tfn.ServeHTTP(rw, req)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\thttp.Error(rw, (newResponse(s, 0)).JSON(), s)\n\t\t\treturn\n\t\t})\n\t}\n}", "func verifyAuth(w http.ResponseWriter, r *http.Request) {\n\thttpJSON(w, httpMessageReturn{Message: \"OK\"}, http.StatusOK, nil)\n}", "func ServeAuthCheck(ctx *fasthttp.RequestCtx) {\n\tif !security.IsAuthorized(ctx) {\n\t\treturn\n\t}\n\tresponse.SendNothing(ctx)\n}", "func (p *Proxy) CheckAuth() (bool, error) {\n\tu, err := url.Parse(\"http://\" + p.config.Addr.String())\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"invalid proxy url: %w\", err)\n\t}\n\n\t// We need http client with custom transport\n\thttpClient := http.DefaultClient\n\n\ttr := http.DefaultTransport\n\t// Pass our newly deployed local proxy\n\ttr.(*http.Transport).Proxy = http.ProxyURL(u)\n\t// We check it against corporate proxy, so it usually use MITM\n\ttr.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\n\thttpClient.Transport = tr\n\n\treq, err := http.NewRequest(\"GET\", p.config.PingURL.String(), nil)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"cannot create request: %w\", err)\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Minute)\n\tdefer cancel()\n\treq = req.WithContext(ctx)\n\n\tif err := p.setProxyAuthorizationHeader(req); err != nil {\n\t\treturn false, fmt.Errorf(\"cannot set authorization header: %w\", err)\n\t}\n\n\trepeat := true\n\nAgain:\n\tresp, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"cannot do request: %w\", err)\n\t}\n\t//noinspection ALL\n\tdefer resp.Body.Close()\n\n\tif _, err := ioutil.ReadAll(resp.Body); err != nil {\n\t\treturn false, fmt.Errorf(\"cannot read body: %w\", err)\n\t}\n\n\tif resp.StatusCode == http.StatusProxyAuthRequired && repeat {\n\t\trepeat = false\n\t\tgoto Again\n\t}\n\n\tif resp.StatusCode == http.StatusOK {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}", "func CheckAuth(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif auth.IsLoggedIn(r) {\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tif strings.HasPrefix(r.URL.Path, \"/api\") {\n\t\t\tcommon.NewAPIResponse(\"Login required\", nil).WriteResponse(w, http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(w, r, \"/login\", http.StatusTemporaryRedirect)\n\t\treturn\n\t})\n}", "func authOk(sucProb byte) error {\n\t/* Get a random number */\n\tb := make([]byte, 1)\n\tif _, err := rand.Read(b); nil != err {\n\t\treturn fmt.Errorf(\"random read: %v\", err)\n\t}\n\t/* See if it's a winner */\n\tif b[0] <= sucProb {\n\t\treturn nil\n\t}\n\treturn errors.New(\"permission denied\")\n}", "func (ac *AuthChecker) Check(resource, namespace string, client mobile.ExternalHTTPRequester) (bool, error) {\n\tuser, err := ac.UserRepo.GetUser()\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"openshift.ac.Check -> failed to retrieve user details\")\n\t}\n\tu, err := url.Parse(ac.Host)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"openshift.ac.Check -> failed to parse openshift host when attempting to check authorization\")\n\t}\n\tu.Path = path.Join(\"/oapi/v1/namespaces/\" + namespace + \"/localresourceaccessreviews\")\n\tpayload := authCheckJsonPayload{\n\t\tVerb: \"update\",\n\t\tResource: \"deploymentconfigs\",\n\t}\n\tbytePayload, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"openshift.ac.Check -> failed to build payload for check authorization\")\n\t}\n\treq, err := http.NewRequest(\"POST\", u.String(), bytes.NewReader(bytePayload))\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"openshift.ac.Check -> failed to build request to check authorization\")\n\t}\n\treq.Header.Set(\"authorization\", \"bearer \"+ac.Token)\n\treq.Header.Set(\"Content-Type\", \"Application/JSON\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"openshift.ac.Check -> failed to make request to check authorization\")\n\t}\n\tdefer func() {\n\t\tif err := resp.Body.Close(); err != nil {\n\t\t\tlogrus.Error(\"failed to close response body. can cause file handle leaks \", err)\n\t\t}\n\t}()\n\tif resp.StatusCode == http.StatusForbidden {\n\t\t// user does not have permission to create the permission check in the namespace\n\t\treturn false, nil\n\t} else if resp.StatusCode != http.StatusCreated {\n\t\tif resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {\n\t\t\treturn false, &AuthenticationError{Message: \"openshift.ac.Check -> (\" + strconv.Itoa(resp.StatusCode) + \") access was denied\", StatusCode: resp.StatusCode}\n\t\t}\n\n\t\treturn false, errors.New(\"openshift.ac.Check -> unexpected response code from openshift \" + strconv.Itoa(resp.StatusCode))\n\t}\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"openshift.ac.Check -> failed to read the response body after reading user\")\n\t}\n\tres := &authCheckResponse{}\n\terr = json.Unmarshal(data, res)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"openshift.ac.Check -> error decoding response to auth check\")\n\t}\n\tfor _, u := range res.Users {\n\t\tif u == user.User {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn user.InAnyGroup(res.Groups), nil\n}", "func AuthAdminAccess(context *gin.Context, db int, tokenSecret string, needs []string, release bool) {\n\tif !release {\n\t\tcontext.Next()\n\t\treturn\n\t}\n\n\troles, err := GetRequestTokenRole(context, db, tokenSecret)\n\tif err != nil {\n\t\tcommon.ResponseError(context, code.SpawnErrNeedPerm())\n\t\tlog.Debug(\"authorization role access error:%+v\", err)\n\t\treturn\n\t}\n\n\tfor _, need := range needs {\n\t\tfor _, role := range roles {\n\t\t\tif strings.ToLower(need) == strings.ToLower(role) {\n\t\t\t\tgoto next\n\t\t\t}\n\t\t}\n\t}\n\n\tcommon.ResponseError(context, code.SpawnErrNeedPerm())\n\tlog.Debug(\"authorization profile access %s need access\",\n\t\tcontext.Request.RequestURI)\n\treturn\nnext:\n\tcontext.Next()\n}", "func getGitHubAccessToken(w http.ResponseWriter, r *http.Request) {\n\t// Use the built in ioutil from io/ioutil to\n\t// read the request body into a []byte\n\tbody, err := ioutil.ReadAll(r.Body)\n\thelpers.HandleError(err)\n\n\t// Decode the JSON request body to our GHTokenReqBody\n\t// so we can use the session code\n\tvar tokenReqBody GHTokenReqBody\n\terr = json.Unmarshal(body, &tokenReqBody)\n\thelpers.HandleError(err)\n\n\t// 1. Grab the access token from GitHub using the session code\n\taccessToken, err := github.GetAccessToken(tokenReqBody.SessionCode)\n\thelpers.HandleError(err)\n\n\t// 2. Call the check token method with our new access token\n\t// to get the logged in users details\n\tcheckTokenResult, err := github.CheckToken(accessToken)\n\thelpers.HandleError(err)\n\n\t// 3: Check if the user exists using their GitHub user id, and either:\n\t// - Create a new user record if this is their first time logging in\n\t// - Get the existing users details\n\n\tvar user models.User\n\tif !db.GitHubUserExists(*checkTokenResult.User.Login) {\n\t\tuser = db.CreateUser(*checkTokenResult.User)\n\t} else {\n\t\tuser = db.GetUserByGitHubLogin(*checkTokenResult.User.Login)\n\t}\n\n\t// 4: Set a cookie containing the user's token\n\t// that we can use for future request, only\n\t// set the Secure attribute to true if not in\n\t// development mode\n\tisDev := os.Getenv(\"HOSTING_ENV\") == \"Development\"\n\ttokenCookieExpires := 30 * 24 * time.Hour\n\ttokenCookie := &http.Cookie{\n\t\tName: tokenCookieName,\n\t\tValue: accessToken,\n\t\tPath: \"/\",\n\t\tExpires: time.Now().Add(tokenCookieExpires),\n\t\tMaxAge: 0,\n\t\tSecure: !isDev,\n\t\tHttpOnly: true,\n\t\tSameSite: http.SameSiteStrictMode,\n\t\tUnparsed: []string{},\n\t}\n\thttp.SetCookie(w, tokenCookie)\n\tw.WriteHeader(http.StatusOK)\n\n\t// 5: Return the users details to the caller\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(user)\n}", "func (sa SASLDAuth) Check(req *AuthReq, ok *bool) (err error) {\n\t*ok, err = saslauthd.Auth(req.User, req.Password, service, realm)\n\treturn\n}", "func CheckAccess(ctx *context.T) (time.Duration, error) {\n\tif principal := v23.GetPrincipal(ctx); principal != nil {\n\t\t// We have access to some credentials so we'll try to load them.\n\t\t_, err := v23.WithPrincipal(ctx, principal)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tblessings, _ := principal.BlessingStore().Default()\n\t\tnow := time.Now()\n\t\tleft := blessings.Expiry().Sub(now)\n\t\tif blessings.Expiry().After(now.Add(30 * time.Minute)) {\n\t\t\treturn left, nil\n\t\t}\n\t\tif blessings.Expiry().IsZero() {\n\t\t\treturn left, fmt.Errorf(\"credentials are not set, try setting the V23_CREDENTIALS using 'export V23_CREDENTIALS=%s'\", os.ExpandEnv(\"${HOME}/.v23\"))\n\t\t}\n\t\treturn left, fmt.Errorf(\"credentials are set to expire in %v, use grail-access to refresh them\", left)\n\t}\n\treturn 0, fmt.Errorf(\"credentials directory doesn't exist, use the grail-access and/or grail-role commands to create one and to login\")\n}", "func (a *App) CheckAuth() {\n\tsynchronizer := NewSynchronizer()\n\tsynchronizer.CheckAuth()\n}", "func CheckToken(client *flickr.FlickrClient, oauthToken string) (*CheckTokenResponse, error) {\n\tclient.EndpointUrl = flickr.API_ENDPOINT\n\tclient.ClearArgs()\n\tclient.Args.Set(\"method\", \"flickr.auth.oauth.checkToken\")\n\tclient.Args.Set(\"oauth_token\", oauthToken)\n\tclient.ApiSign()\n\n\tresponse := &CheckTokenResponse{}\n\terr := flickr.DoGet(client, response)\n\treturn response, err\n}", "func requireAuthWeb(c *router.Context, next router.Handler) {\n\tif auth.CurrentIdentity(c.Context) == identity.AnonymousIdentity {\n\t\tloginURL, err := auth.LoginURL(c.Context, \"/\")\n\t\tif err != nil {\n\t\t\tlogging.Errorf(c.Context, \"Failed to get login URL\")\n\t\t\thttp.Error(c.Writer, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tlogging.Infof(c.Context, \"Redirecting to %s\", loginURL)\n\t\thttp.Redirect(c.Writer, c.Request, loginURL, 302)\n\t\treturn\n\t}\n\n\tisGoogler, err := auth.IsMember(c.Context, rwGroup)\n\tif err != nil {\n\t\tc.Writer.WriteHeader(http.StatusInternalServerError)\n\t\tlogging.Errorf(c.Context, \"Failed to get group membership.\")\n\t\treturn\n\t}\n\tif isGoogler {\n\t\tnext(c)\n\t\treturn\n\t}\n\n\ttemplates.MustRender(c.Context, c.Writer, \"pages/access_denied.html\", nil)\n}", "func authHandler(c *fb.Context, w http.ResponseWriter, r *http.Request) (int, error) {\n\tif c.Auth.Method == \"none\" {\n\t\t// NoAuth instances shouldn't call this method.\n\t\treturn 0, nil\n\t}\n\n\tif c.Auth.Method == \"proxy\" {\n\t\t// Receive the Username from the Header and check if it exists.\n\t\tu, err := c.Store.Users.GetByUsername(r.Header.Get(c.Auth.Header), c.NewFS)\n\t\tif err != nil {\n\t\t\treturn http.StatusForbidden, nil\n\t\t}\n\n\t\tc.User = u\n\t\treturn printToken(c, w)\n\t}\n\n\t// Receive the credentials from the request and unmarshal them.\n\tvar cred cred\n\n\tif r.Body == nil {\n\t\treturn http.StatusForbidden, nil\n\t}\n\n\terr := json.NewDecoder(r.Body).Decode(&cred)\n\tif err != nil {\n\t\treturn http.StatusForbidden, err\n\t}\n\n\t// Wenkun, Validate the token of user from cloud server and return JWT token.\n\tif c.Auth.Method != \"none\" {\n\t\tok, u := validateAuthByUserId(c, cred.Username)\n\t\tif !ok {\n\t\t\treturn http.StatusForbidden, nil\n\t\t}\n\n\t\tc.User = u\n\t\treturn printToken(c, w)\n\t}\n\n\t// If ReCaptcha is enabled, check the code.\n\tif len(c.ReCaptcha.Secret) > 0 {\n\t\tok, err := reCaptcha(c.ReCaptcha.Host, c.ReCaptcha.Secret, cred.ReCaptcha)\n\t\tif err != nil {\n\t\t\treturn http.StatusForbidden, err\n\t\t}\n\n\t\tif !ok {\n\t\t\treturn http.StatusForbidden, nil\n\t\t}\n\t}\n\n\t// Checks if the user exists.\n\tu, err := c.Store.Users.GetByUsername(cred.Username, c.NewFS)\n\tif err != nil {\n\t\treturn http.StatusForbidden, nil\n\t}\n\n\t// Checks if the password is correct.\n\tif !fb.CheckPasswordHash(cred.Password, u.Password) {\n\t\treturn http.StatusForbidden, nil\n\t}\n\n\tc.User = u\n\treturn printToken(c, w)\n}", "func (a Authz) CheckAuthz(w http.ResponseWriter, r * http.Request){\n\tw.Header().Set(\"Content-type\",\"applicaiton/json\")\n\t\n\trequest := SubjectAccessReview{}\n\tresponse :=SubjectAccessReview{}\n\t_ = json.NewDecoder(r.Body).Decode(&request)//Retrieve body\n\tusername := request.Spec.User \n\tgroups := request.Spec.Groups\n\taction := request.Spec.ResourceAttributes.Verb\n\tlog.Println(\"REQUEST : \",request)\n\t\n if(request.Spec.ResourceAttributes.Namespace == \"webhook\"){\n\t\tif (contains(groups,\"admin\")){// admin can do anything\n\t\t\tresponse.Status.Allowed = true\n\t\t}else if (contains(groups,\"dev\")){\n\t\t\tif (action != \"get\" && action != \"list\"){ //dev can read data only\n\t\t\t\tresponse.Status.Allowed = false\n\t\t\t}else{\n\t\t\t\tresponse.Status.Allowed = true\n\t\t\t}\n\t\t}else{\n\t\t\tresponse.Status.Allowed = false\n\t\t}\n\t\tlog.Printf(\"%s in group %s perform %s on resource %s is allowed == \",username,groups,action,request.Spec.ResourceAttributes.Resource,response.Status.Allowed)\n\t}else{\n\t\tresponse.Status.Allowed = false\n\t}\n\tw.Header().Set(\"Content-type\",\"application/json\")\n\tjson.NewEncoder(w).Encode(response)\n\n}", "func login() (*oauth2.Token, error) {\n\tvar (\n\t\tauthServerUrl = \"https://accounts.vdatlab.com/auth/realms/vdatlab.com\"\n\t\tclientID = \"chat.apps.vdatlab.com\"\n\t\tredirectURL = \"http://127.0.0.1:12345/auth/callback\"\n\t\ttoken *oauth2.Token\n\t)\n\n\tauthServerWellKnownCfg, err := getWellKnownConfig(authServerUrl)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// initialize the code verifier\n\tvar CodeVerifier, _ = cv.CreateCodeVerifier()\n\n\t// Create code_challenge with S256 method\n\tcodeChallenge := CodeVerifier.CodeChallengeS256()\n\n\t// construct the authorization URL (with Auth0 as the authorization provider)\n\tauthorizationURL := fmt.Sprintf(\n\t\t\"%s?audience=\"+\n\t\t\t\"&scope=openid\"+\n\t\t\t\"&response_type=code\"+\n\t\t\t\"&client_id=%s\"+\n\t\t\t\"&code_challenge=%s\"+\n\t\t\t\"&code_challenge_method=S256\"+\n\t\t\t\"&redirect_uri=%s\",\n\t\tauthServerWellKnownCfg.AuthorizationEndpoint, clientID, codeChallenge, redirectURL)\n\n\t// start a web server to listen on a callback URL\n\tserver := &http.Server{Addr: redirectURL}\n\n\t// define a handler that will get the authorization code, call the token endpoint, and close the HTTP server\n\thttp.HandleFunc(\"/auth/callback\", func(w http.ResponseWriter, r *http.Request) {\n\t\t// get the authorization code\n\t\tcode := r.URL.Query().Get(\"code\")\n\t\tif code == \"\" {\n\t\t\tfmt.Println(\"snap: Url Param 'code' is missing\")\n\t\t\tio.WriteString(w, \"Error: could not find 'code' URL parameter\\n\")\n\n\t\t\t// close the HTTP server and return\n\t\t\tcleanup(server)\n\t\t\treturn\n\t\t}\n\n\t\t// trade the authorization code and the code verifier for an access token\n\t\tcodeVerifier := CodeVerifier.String()\n\t\ttoken, err = getAccessToken(authServerWellKnownCfg.TokenEndpoint, clientID, codeVerifier, code, redirectURL)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"snap: could not get access token\")\n\t\t\tio.WriteString(w, \"Error: could not retrieve access token\\n\")\n\n\t\t\t// close the HTTP server and return\n\t\t\tcleanup(server)\n\t\t\treturn\n\t\t}\n\n\t\t// return an indication of success to the caller\n\t\tio.WriteString(w, `\n\t\t<html>\n\t\t\t<body>\n\t\t\t\t<h1>Login successful!</h1>\n\t\t\t</body>\n\t\t\t<script type='text/javascript'>\n\t\t\t\t self.close();\n\t\t\t</script>\n\t\t</html>`)\n\n\t\tfmt.Println(\"Login Successfully\")\n\n\t\t// close the HTTP server\n\t\tcleanup(server)\n\t})\n\n\t// parse the redirect URL for the port number\n\tu, err := url.Parse(redirectURL)\n\tif err != nil {\n\t\tfmt.Printf(\"snap: bad redirect URL: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// set up a listener on the redirect port\n\tport := fmt.Sprintf(\":%s\", u.Port())\n\tl, err := net.Listen(\"tcp\", port)\n\tif err != nil {\n\t\tfmt.Printf(\"snap: can't listen to port %s: %s\\n\", port, err)\n\t\tos.Exit(1)\n\t}\n\n\t// open a browser window to the authorizationURL\n\terr = open.Start(authorizationURL)\n\tif err != nil {\n\t\tfmt.Printf(\"snap: can't open browser to URL %s: %s\\n\", authorizationURL, err)\n\t\tos.Exit(1)\n\t}\n\n\t// start the blocking web server loop\n\t// this will exit when the handler gets fired and calls server.Close()\n\tserver.Serve(l)\n\n\treturn token, nil\n}", "func (a *api) checkAccessToken() bool {\n\treturn a.accessToken != \"\"\n}", "func (recv *HttpUserService) Validate(accessToken string) bool {\n\n\t// execute HTTP request here\n\t// todo\n\n\treturn accessToken == \"1234\"\n}", "func (s *Auth) Status() (bool, string) {\n\tpath := s.authManager.OAuth2Config(context.Background(), nil).AuthCodeURL(\"\")\n\t_, err := http.Get(path)\n\tif err == nil {\n\t\treturn true, \"success\"\n\t}\n\n\treturn false, err.Error()\n}", "func checkCredentials() (bool, *http.Client) {\n\tauthInput, err := ioutil.ReadFile(\"credentials.json\")\n\tif err != nil {\n\t\tlog.Println(\"Error Reading Credentials File: \", err)\n\t\treturn true, &http.Client{}\n\t}\n\taccessDetails := accessDetails{}\n\n\tjson.Unmarshal([]byte(authInput), &accessDetails)\n\tif accessDetails.ConsumerKey == \"\" || accessDetails.ConsumerSecret == \"\" || accessDetails.AccessToken == \"\" || accessDetails.AccessSecret == \"\" {\n\t\tlog.Println(\"Missing access information.\")\n\t\treturn true, &http.Client{}\n\t}\n\tconfig := oauth1.NewConfig(accessDetails.ConsumerKey, accessDetails.ConsumerSecret)\n\ttoken := oauth1.NewToken(accessDetails.AccessToken, accessDetails.AccessSecret)\n\t// httpClient will automatically authorize http.Request's\n\thttpClient := config.Client(oauth1.NoContext, token)\n\treturn false, httpClient\n}", "func TestResticPrivateRepositories(t *testing.T) {\n\tctx := context.Background()\n\tbuf := make([]byte, 32)\n\t_, err := io.ReadFull(rand.Reader, buf)\n\trequire.NoError(t, err)\n\n\t// setup rclone with a local backend in a temporary directory\n\ttempdir := t.TempDir()\n\n\topt := newOpt()\n\n\t// set private-repos mode & test user\n\topt.PrivateRepos = true\n\topt.Auth.BasicUser = \"test\"\n\topt.Auth.BasicPass = \"password\"\n\n\t// make a new file system in the temp dir\n\tf := cmd.NewFsSrc([]string{tempdir})\n\ts, err := newServer(ctx, f, &opt)\n\trequire.NoError(t, err)\n\trouter := s.Server.Router()\n\n\t// Requesting /test/ should allow access\n\treqs := []*http.Request{\n\t\tnewAuthenticatedRequest(t, \"POST\", \"/test/?create=true\", nil, opt.Auth.BasicUser, opt.Auth.BasicPass),\n\t\tnewAuthenticatedRequest(t, \"POST\", \"/test/config\", strings.NewReader(\"foobar test config\"), opt.Auth.BasicUser, opt.Auth.BasicPass),\n\t\tnewAuthenticatedRequest(t, \"GET\", \"/test/config\", nil, opt.Auth.BasicUser, opt.Auth.BasicPass),\n\t}\n\tfor _, req := range reqs {\n\t\tcheckRequest(t, router.ServeHTTP, req, []wantFunc{wantCode(http.StatusOK)})\n\t}\n\n\t// Requesting with bad credentials should raise unauthorised errors\n\treqs = []*http.Request{\n\t\tnewRequest(t, \"GET\", \"/test/config\", nil),\n\t\tnewAuthenticatedRequest(t, \"GET\", \"/test/config\", nil, opt.Auth.BasicUser, \"\"),\n\t\tnewAuthenticatedRequest(t, \"GET\", \"/test/config\", nil, \"\", opt.Auth.BasicPass),\n\t\tnewAuthenticatedRequest(t, \"GET\", \"/test/config\", nil, opt.Auth.BasicUser+\"x\", opt.Auth.BasicPass),\n\t\tnewAuthenticatedRequest(t, \"GET\", \"/test/config\", nil, opt.Auth.BasicUser, opt.Auth.BasicPass+\"x\"),\n\t}\n\tfor _, req := range reqs {\n\t\tcheckRequest(t, router.ServeHTTP, req, []wantFunc{wantCode(http.StatusUnauthorized)})\n\t}\n\n\t// Requesting everything else should raise forbidden errors\n\treqs = []*http.Request{\n\t\tnewAuthenticatedRequest(t, \"GET\", \"/\", nil, opt.Auth.BasicUser, opt.Auth.BasicPass),\n\t\tnewAuthenticatedRequest(t, \"POST\", \"/other_user\", nil, opt.Auth.BasicUser, opt.Auth.BasicPass),\n\t\tnewAuthenticatedRequest(t, \"GET\", \"/other_user/config\", nil, opt.Auth.BasicUser, opt.Auth.BasicPass),\n\t}\n\tfor _, req := range reqs {\n\t\tcheckRequest(t, router.ServeHTTP, req, []wantFunc{wantCode(http.StatusForbidden)})\n\t}\n\n}", "func (rest *TestTokenStorageREST) TestStatusExternalTokenUnauthorized() {\n\trest.checkStatusExternalTokenUnauthorized(\"https://github.com/sbose78\", \"github\")\n\trest.checkStatusExternalTokenUnauthorized(\"github\", \"github\")\n\trest.checkStatusExternalTokenUnauthorized(\"https://api.starter-us-east-2.openshift.com\", \"openshift-v3\")\n\trest.checkStatusExternalTokenUnauthorized(\"openshift\", \"openshift-v3\")\n}", "func authCheck(j server.JSONEndpoint) server.JSONEndpoint {\n\treturn func(r *http.Request) (code int, res interface{}, err error) {\n\t\t// check for User ID header injected by API Gateway\n\t\tidStr := r.Header.Get(\"USER_ID\")\n\t\t// verify it's an int\n\t\tid, err := strconv.ParseUint(idStr, 10, 64)\n\t\t// reject request if bad/no user ID\n\t\tif err != nil || id == 0 {\n\t\t\treturn http.StatusUnauthorized, nil, UnauthErr\n\t\t}\n\t\t// set the ID in context if we're good\n\t\tcontext.Set(r, userIDKey, id)\n\n\t\treturn j(r)\n\t}\n}", "func DoAuth(request Request) (res Response, err error) {\n\tparams, _ := json.Marshal(request)\n\tparamstr := string(params)\n\treq, _ := http.NewRequest(\"POST\", tokenAPI, strings.NewReader(paramstr))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept\", \"application/json\")\n\n\tclient := &http.Client{Timeout: time.Duration(15 * time.Second)}\n\thttpres, httperr := client.Do(req)\n\tif httperr != nil {\n\t\terr = httperr\n\t} else if httpres.StatusCode == 200 {\n\t\tbodyBytes, _ := ioutil.ReadAll(httpres.Body)\n\t\tjson.Unmarshal(bodyBytes, &res)\n\t}\n\n\treturn\n}", "func CheckProjectAccess(project string, ts oauth2.TokenSource) (bool, error) {\n\tctx := context.Background()\n\n\ts, err := crm.NewService(ctx, option.WithTokenSource(ts))\n\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to create service with error; %+v\", err)\n\t\treturn false, err\n\t}\n\n\tp := crm.NewProjectsService(s)\n\n\t// TODO(jlewi): We use setIamPolicy as a check that we have sufficient access to the project\n\t// might be better to use cluster Admin or similar permission.\n\treq := &crm.TestIamPermissionsRequest{\n\t\tPermissions: []string{\"resourcemanager.projects.setIamPolicy\"},\n\t}\n\n\texp := backoff.NewExponentialBackOff()\n\texp.InitialInterval = 2 * time.Second\n\texp.MaxInterval = 5 * time.Second\n\texp.MaxElapsedTime = time.Minute\n\texp.Reset()\n\n\tisValid := false\n\n\tlog.Infof(\"Testing new token grants sufficient privileges\")\n\terr = backoff.Retry(func() error {\n\t\t// Get current policy\n\n\t\tres, err := p.TestIamPermissions(project, req).Do()\n\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"There was a problem testing IAM permissions: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\tif len(res.Permissions) > 0 {\n\t\t\tisValid = true\n\t\t}\n\t\treturn nil\n\t}, exp)\n\n\treturn isValid, err\n}", "func checkSecretsAccess(proj *project.Project) error {\n\tallowed, err := access.Secrets(proj.Owner())\n\tif err != nil {\n\t\treturn locale.WrapError(err, \"secrets_err_access\")\n\t}\n\tif !allowed {\n\t\treturn locale.NewError(\"secrets_warning_no_access\")\n\t}\n\treturn nil\n}", "func (e AuthService) Check() (bool, error) {\n\turl := \"/authentication\"\n\n\tresp, err := e.client.MakeRequest(\n\t\t\"GET\",\n\t\turl,\n\t\t0,\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer resp.Body.Close()\n\n\tswitch resp.StatusCode {\n\tcase http.StatusOK:\n\t\treturn true, nil\n\tcase http.StatusUnauthorized:\n\t\tfallthrough\n\tcase http.StatusForbidden:\n\t\treturn false, nil\n\tdefault:\n\t\treturn false, e.client.handleUnexpectedResponse(resp)\n\t}\n}", "func CheckAuthorizedUser(store JSonStore, req *http.Request) (string, bool) {\n\tvar credentials = req.Header[\"Authorization\"][0];\n\tvar decoded, decodedErr = base64.StdEncoding.DecodeString(credentials)\n\tif decodedErr != nil {\n\t\tlog.Println(\"error could not decode credentials\");\n\t\treturn \"\", false;\n\t}\n\tvar s = string(decoded);\n\tvar parts = strings.Split(s, \":\");\n\tvar username = parts[0];\n\tvar password = parts[1];\n\n\tvar res []map[string]string = store.GetJSonBlobs(map[string]string{\"type\":\"user\", \"username\": username, \"password\": password});\n\n\tif (len(res) == 0) {\n\t\tlog.Println(\"User authenticated.\");\n\t\treturn username, true;\n\t} else {\n\t\tlog.Println(\"User access Denied: \" + username);\n\t\treturn username, false;\n\t}\n}", "func (c *Client) Auth() (string, error) {\n\t// First do an empty get to get the auth challenge\n\treq, err := http.NewRequest(http.MethodGet, c.BaseURL+\"/v2/\", nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\trsp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed sending auth request: %w\", err)\n\t}\n\tdefer rsp.Body.Close()\n\tio.Copy(io.Discard, rsp.Body)\n\n\tif rsp.StatusCode == http.StatusOK {\n\t\t// no auth needed\n\t\treturn \"\", nil\n\t}\n\n\tif rsp.StatusCode != http.StatusUnauthorized {\n\t\treturn \"\", fmt.Errorf(\"unexpected status %s\", rsp.Status)\n\t}\n\n\t// The Www-Authenticate header tells us where to go to get a token\n\tvals, err := parseWWWAuthenticate(rsp.Header.Get(\"Www-Authenticate\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tu, err := url.Parse(vals[\"realm\"])\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not parse authentication realm: %w\", err)\n\t}\n\tq := u.Query()\n\tq.Set(\"service\", vals[\"service\"])\n\tq.Set(\"scope\", \"repository:\"+c.Name+\":pull,push\")\n\tu.RawQuery = q.Encode()\n\n\tfmt.Printf(\"get %s\\n\", u)\n\n\treq, err = http.NewRequest(http.MethodGet, u.String(), nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq.SetBasicAuth(c.User, c.Password)\n\n\trsp, err = http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed sending auth request: %w\", err)\n\t}\n\tdefer rsp.Body.Close()\n\tif rsp.StatusCode != http.StatusOK {\n\t\treturn \"\", fmt.Errorf(\"unexpected status %s\", rsp.Status)\n\t}\n\tbody, err := io.ReadAll(rsp.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not read auth response body: %w\", err)\n\t}\n\n\ttype token struct {\n\t\tToken string `json:\"token\"`\n\t}\n\tvar tok token\n\tif err := json.Unmarshal(body, &tok); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to unmarshal token: %w\", err)\n\t}\n\n\treturn tok.Token, nil\n}", "func CheckAuthenticationData(r *http.Request) *mdl.User {\n\treturn mdl.FindUser(appengine.NewContext(r), \"Auth\", r.Header.Get(\"Authorization\"))\n}", "func TestOAuthVerifyState(t *testing.T) {\n\tservice := NewOAuth2Service(testClientID, testClientSecret, testScopes, testTokenURL, testAuthURL)\n\tservice.ExchangeAuthCodeForToken(testCode)\n}", "func AuthToken(r *http.Request) (bool, error) {\n\ttoken := getToken(r)\n\texist, err := redisClient.SIsMember(dbToken, string(token)).Result()\n\tif err != nil {\n\t\tlog.Printf(\"error with redis occurred, error : %v\", err)\n\t\treturn false, err\n\t}\n\n\treturn exist, nil\n\n}", "func validateAuth(c *fb.Context, r *http.Request) (bool, *fb.User) {\n\tif c.Auth.Method == \"none\" {\n\t\tc.User = c.DefaultUser\n\t\treturn true, c.User\n\t}\n\n\t// If proxy auth is used do not verify the JWT token if the header is provided.\n\tif c.Auth.Method == \"proxy\" {\n\t\tu, err := c.Store.Users.GetByUsername(r.Header.Get(c.Auth.Header), c.NewFS)\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tc.User = u\n\t\treturn true, c.User\n\t}\n\n\tkeyFunc := func(token *jwt.Token) (interface{}, error) {\n\t\treturn c.Key, nil\n\t}\n\n\tvar claims claims\n\ttoken, err := request.ParseFromRequestWithClaims(r,\n\t\textractor{},\n\t\t&claims,\n\t\tkeyFunc,\n\t)\n\n\tif err != nil || !token.Valid {\n\t\treturn false, nil\n\t}\n\n\tu, err := c.Store.Users.Get(claims.User.ID, c.NewFS)\n\tif err != nil {\n\t\treturn false, nil\n\t}\n\n\tc.User = u\n\treturn true, u\n}", "func (api *API) authorize(ctx *gin.Context) {\n\t// Decode the request\n\tvar request authorizeRequest\n\terr := ctx.ShouldBindJSON(&request)\n\tif api.check(err, ctx, http.StatusBadRequest) {\n\t\treturn\n\t}\n\n\t// Get the state from the client-side cookie\n\tqueryState, err := ctx.Request.Cookie(\"state\")\n\tif api.check(err, ctx, http.StatusUnauthorized) {\n\t\treturn\n\t}\n\n\t// Create session to check back-end state\n\tsession := sessions.Default(ctx)\n\tsessionState := session.Get(\"state\")\n\n\t// Compare the two states\n\tif queryState.Value != sessionState { // Compare session and query states\n\t\tapi.check(fmt.Errorf(\"invalid query state: %v\", queryState.Value),\n\t\t\tctx, http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t// If they have a token already, don't issue a new one\n\t_, err = ctx.Request.Cookie(\"token\")\n\tif err == nil {\n\t\t// Maybe search PG database to see if its valid\n\t\tctx.JSON(http.StatusOK, ok())\n\t\treturn\n\t}\n\n\t// Handle the exchange code to initiate a transport and get a token\n\ttoken, err := api.oauthConfig.Exchange(\n\t\toauth2.NoContext,\n\t\trequest.Code,\n\t)\n\tif api.check(err, ctx, http.StatusUnauthorized) {\n\t\treturn\n\t}\n\n\t// Construct the client to get the sub.\n\tu, err := api.getUserInfo(token)\n\tif api.check(err, ctx) {\n\t\treturn\n\t}\n\n\t// Insert the token into the database\n\terr = api.database.InsertToken(u.Sub, token, u.Email)\n\tif api.check(err, ctx) {\n\t\treturn\n\t}\n\n\t// Try and get user from database to determine whether to update,\n\t// add, or do nothing\n\tstringUsername, err := models.UsernameFromEmail(u.Email)\n\tif api.check(err, ctx) {\n\t\treturn\n\t}\n\tdbUser, err := api.database.GetUser(string(stringUsername))\n\tcookieUsername := dbUser.Username\n\tif string(dbUser.Username) == \"\" { // If the user does not exist\n\t\tnewUser, err := models.NewUser(u.Email, models.Freshman, true)\n\t\tif api.check(err, ctx) {\n\t\t\treturn\n\t\t}\n\t\tnewUser.ProfilePic = u.Picture // Get and set the profile picture\n\t\tapi.database.AddUser(newUser)\n\t\tcookieUsername = newUser.Username\n\t\tapi.log.Infof(\"added user %s to database (in authorization)\", u.Email)\n\t} else { // If the user EXISTS\n\t\tif dbUser.Registered == false { // If this is their first login\n\t\t\t// Update the account's profile picture and registration\n\t\t\t// status\n\t\t\terr = api.database.InitAccount(string(stringUsername), u.Picture)\n\t\t\tif api.check(err, ctx) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\t// Set the token in a cookie\n\thttp.SetCookie(ctx.Writer, &http.Cookie{\n\t\tName: \"token\",\n\t\tValue: token.AccessToken,\n\t\tPath: \"/\",\n\t\tMaxAge: 30 * 60,\n\t\tSecure: false,\n\t})\n\t// Set the username in a cookie\n\thttp.SetCookie(ctx.Writer, &http.Cookie{\n\t\tName: \"username\",\n\t\tValue: string(cookieUsername),\n\t\tPath: \"/\",\n\t\tMaxAge: 30 * 60,\n\t\tSecure: false,\n\t})\n\n\tapi.log.Infof(\"authorized %s\", u.Email)\n\n\tctx.JSON(http.StatusOK, ok())\n}", "func AuthToken(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tfmt.Println(\"Remote Host: \", r.RemoteAddr)\n\n\t// Now, we create the JWT from the info in the query parameters\n\n\t// Extract parameters from encoded query parameter set\n\tvalues := r.URL.Query()\n\tif len(values) == 0 {\n\t\tpanic(\"Query string was empty (length 0) -- unable to parse query parameters and create Response\")\n\t}\n\n\tvar grantType, service, clientId, accessType, rawScope, refreshToken /*, username, password*/ string\n\n\tgrantType = values.Get(GRANT_TYPE)\n\tservice = values.Get(SERVICE)\n\tclientId = values.Get(CLIENT_ID)\n\taccessType = values.Get(ACCESS_TYPE)\n\trawScope = values.Get(SCOPE)\n\trefreshToken = values.Get(REFRESH_TOKEN)\n\t// ToDo -- Docker Registry Auth only (for now) uses the Password Authorization Grant Type\n\t// TODO need to refactor\n\t// see https://docs.docker.com/registry/spec/auth/oauth/\n\t//username = values.Get(USERNAME)\n\t//password = values.Get(PASSWORD)\n\n\n\t// debugging\n\tfmt.Println(grantType)\n\tfmt.Println(service)\n\tfmt.Println(clientId)\n\tfmt.Println(accessType)\n\tfmt.Println(rawScope)\n\tfmt.Println(refreshToken)\n\n\t// TODO this is where we would be handling AuthZ (make sure this user with this action in our ACL)\n\n\tfmt.Println(\"-----------------------------------\")\n\n\t// Handle creating the claim set\n\tvar scope []ScopeAccess\n\tclaimSet := &ClaimSet{\n\t\tIssuer: \"auth-server\", // the auth server -- this string has to directly match what is in the config file\n\t\tSubject: \"\",\n\t\tAudience: r.RemoteAddr, // the docker registry address\n\t\tExpirationTime: uint64(time.Now().Add(time.Minute * time.Duration(10)).Unix()), // always now + 10 minutes time\n\t\tNotBefore: uint64(time.Now().Unix()),\n\t\tIssuedAt: uint64(time.Now().Unix()),\n\t\tJwtId: RandomString(15),\n\t}\n\t// parse the access scope, and insert it into the claim set as needed\n\tscope, err := ParseScope(rawScope)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif len(scope) == 0 {\n\t\t// make sure it is a \"\" that gets encoded here, in the \"access\" part, since no scope was defined\n\t\t//claimSet.EmptyAccess = \"\"\n\t} else {\n\t\tclaimSet.Access = scope\n\t}\n\n\t// Make sure our weird use of Json is working\n\tjsonClaimSet, jsonErr := json.Marshal(claimSet)\n\tif jsonErr != nil {\n\t\tpanic(jsonErr)\n\t}\n\tfmt.Println(string(jsonClaimSet))\n\n\t// Create the \"kid\", from the DER encoded key\n\tderKeyAsBytes, err0 := ioutil.ReadFile(\"/root/go/src/dockerRegistryAuthServer/pkcs8_1024.der\")\n\tif err0 != nil {\n\t\tpanic(err0)\n\t}\n\t//fmt.Println(string(derKeyAsBytes)) //debugging\n\tkid := CreateKidFromDer(derKeyAsBytes)\n\n\t// Create the header, using the kid\n\theader := &JoseHeader{\n\t\tType: \"JWT\",\n\t\tAlgo: \"RS256\",\n\t\tKeyId: kid,\n\t}\n\n\t// Create the actual JWT, using the PEM encoded key, as well as claimset and header\n\ttoken := CreateRS256Token(claimSet, header, \"/root/go/src/dockerRegistryAuthServer/pkcs8_1024.pem\")\n\n\t// pack the token into the right header\n\tresponse := Response{\n\t\tAccessToken: token,\n\t\tExpiresIn: 600, // 600 seconds = 10 minutes\n\t\tScope: ScopeToResponse(scope),\n\t}\n\n\tif err := json.NewEncoder(w).Encode(response); err != nil {\n\t\tpanic(err)\n\t}\n}", "func Auth(ctx context.Context, clientSecretKeyFile []byte) error {\n\tconfig, err := google.ConfigFromJSON(clientSecretKeyFile, []string{builderAPIScope}...)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Get OAuth2 token from the user. It will be written into cacheFilename.\n\ttokenCacheFilename, err := tokenCacheFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Check the shell is appropriate for use of launched browsers, otherwise present the copy/paste\n\t// flow.\n\tnonSSH := checkShell()\n\tnotWindows := runtime.GOOS != \"windows\"\n\ttok, err := token(ctx, config, tokenCacheFilename, nonSSH && notWindows)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := saveToken(tokenCacheFilename, tok); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (ac *accessController) Authorized(ctx context.Context, accessRecords ...auth.Access) (context.Context, error) {\n\tvar resData ResponseData\n\tvar err1 error\n\treq, err := context.GetRequest(ctx)\n\t//res, err2 := context.GetResponseWriter(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif req.Header.Get(\"SSL_CLIENT_CERT\") == \"\" {\n\t\tlog.Debugln(\"repo name: %s\", getName(ctx))\n\n\t\treturn nil, &challenge{\n\t\t\trealm: ac.realm,\n\t\t\terr: fmt.Errorf(\"Authentication Failure\"),\n\t\t}\n\t}\n\n\tpemStr := req.Header.Get(\"SSL_CLIENT_CERT\")\n\tlog.Debugln(\"SSL CERT: %s\", pemStr)\n\trepoName := getName(ctx)\n\t//if it is a push request\n\t//or the the URI requested is /v2/ (ping)\n\t//then don't call authentication service\n\tlog.Debugln(\"requestURI: \", req.RequestURI)\n\tlog.Debugln(\"requested repo name: \", getName(ctx))\n\tif skipAuth(req) {\n\t\tlog.Debugln(\"Returning without calling authentication servie\")\n\t\treturn auth.WithUser(ctx, auth.UserInfo{Name: \"entitled-ping\"}), nil\n\t}\n\n\t// check for repo name being empty. If repo name is empty\n\t// and the URI is not for ping, return authentication error\n\tif \"/v2/\" != req.RequestURI && repoName == \"\" {\n\t\tlog.Errorln(\"No repo name retrieved. This should not happen\")\n\t\treturn nil, &challenge{\n\t\t\trealm: ac.realm,\n\t\t\terr: fmt.Errorf(\"Authentication Failure as no repo name has been supplied\"),\n\t\t}\n\t}\n\n\tlibraryName := repoName[:strings.LastIndex(repoName, \"/\")+1]\n\tlog.Debugln(\"Computed library name: \", libraryName)\n\tpath := fmt.Sprintf(\"/content/dist/rhel/server/7/7Server/x86_64/containers/registry/%s\", libraryName)\n\n\tif resData, err1 = ac.service.CheckEntitlementV2(req, path); err1 != nil {\n\t\tlog.Errorln(\"Service returned error: \", err1)\n\t\treturn nil, &challenge{\n\t\t\trealm: ac.realm,\n\t\t\terr: fmt.Errorf(\"Authentication Failure\"),\n\t\t}\n\t}\n\n\tif resData.Verified != \"true\" {\n\t\tlog.Errorln(\"Service returned unauthenticated/unauthorized\")\n\t\treturn nil, &challenge{\n\t\t\trealm: ac.realm,\n\t\t\terr: fmt.Errorf(\"Authentication Failure\"),\n\t\t}\n\t}\n\n\treturn auth.WithUser(ctx, auth.UserInfo{Name: \"entitled\"}), nil\n}", "func AuthAndCallAPI(w http.ResponseWriter, r *http.Request, service string, method string, version string) {\n\te := Execution{name: \"AuthAndCallAPI \" + service}\n\te.Start()\n\n\tauthorization := r.Header.Get(\"authorization\")\n\n\ttoken := \"\"\n\ts := strings.Split(authorization, \" \")\n\tif len(s) >= 2 {\n\t\ttoken = s[1]\n\t}\n\n\tconfig := config.GetConfig()\n\tresp, _ := resty.R().\n\t\tSetFormData(map[string]string{\n\t\t\t\"token\": token,\n\t\t\t\"service\": service,\n\t\t}).\n\t\tSetResult(&Respon{}).\n\t\tPost(config.API.Auth + \"v100/auth/check_token\")\n\n\tvar respon Respon\n\t_ = json.Unmarshal(resp.Body(), &respon)\n\n\tif respon.Code != 200 {\n\t\trespond := Respon{\n\t\t\tStatus: respon.Status,\n\t\t\tCode: respon.Code,\n\t\t\tMessage: respon.Message,\n\t\t\tExeTime: respon.ExeTime,\n\t\t\tData: respon.Data,\n\t\t\tError: respon.Error,\n\t\t}\n\t\tRespondJson(w, resp.StatusCode(), respond)\n\t\treturn\n\t}\n\n\tCallAPI(w, r, service, method, version)\n}", "func TestValidAuth(t *testing.T) {\n\tt.Parallel()\n\ta, err := getAuth()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !ValidAuth(a) {\n\t\tt.Error(ErrInvalidAuth)\n\t}\n}", "func (a Authn)CheckAuthentication(w http.ResponseWriter, r *http.Request){\r\n\t\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\ta.Token.Status.Error=\"\"\r\n\t_=json.NewDecoder(r.Body).Decode(&a.Token)\r\n\tfmt.Println(\"payload : \",a.Token)\r\n\ttoken:=strings.Split(a.Token.Spec.Token,\":\")\r\n\tif len(token[0]) <1 || len(token[1])<1{\r\n\t\ta.Token.Status.Authenticated=false\r\n\t\ta.Token.Status.Error=\"token is not correct!\"\r\n\t\tw.WriteHeader(http.StatusForbidden)\r\n\t\tjson.NewEncoder(w).Encode(&a.Token)\r\n\t}else{\r\n\t\tfmt.Println(\"retrieve user |\",strings.TrimSpace(token[0]),\"|\")\r\n\t\turl:=os.Getenv(\"USR_API\")+strings.TrimSpace(token[0])\r\n\t\tmethod:=\"GET\"\r\n\t\theaders:=make(map[string]string)\r\n\t\tpayload := new(strings.Reader)\r\n\t\tclient:=lib.CallAPI{url,method,headers,payload,false}\r\n\t\tresponse,err:=client.CallRest()\r\n\t\t\r\n\t\tuserDTO:=dto.UserDTO{}\r\n\t\terr=json.NewDecoder(response.Body).Decode(&userDTO)\r\n\t\tfmt.Println(\"USER DTO \",userDTO)\r\n\t\tif err != nil{\r\n\t\t\ta.Token.Status.Authenticated=false\r\n\t\t\ta.Token.Status.Error=\"user-management response is not correct!\"\r\n\t\t\tw.WriteHeader(http.StatusForbidden)\r\n\t\t\tjson.NewEncoder(w).Encode(&a)\r\n\t\t\t\r\n\t\t}else{\r\n\t\t\tif userDTO.Password == token[1]{\r\n\t\t\t\tfmt.Println(\"userDTO password and token is the same\")\r\n\t\t\t\ta.Token.Status.Authenticated=true\r\n\t\t\t\ta.Token.Status.User.Username=userDTO.User\r\n\t\t\t\ta.Token.Status.User.UID=strconv.Itoa(userDTO.UID)\r\n\t\t\t\ta.Token.Status.User.Groups=nil\r\n\t\t\t\tfor _,group :=range userDTO.Groups{\r\n\t\t\t\t\ta.Token.Status.User.Groups=append(a.Token.Status.User.Groups,group.Group)\r\n\t\t\t\t}\r\n\t\t\t\tjson.NewEncoder(w).Encode(&a.Token)\r\n\t\t\t}else{\r\n\t\t\t\tfmt.Println(\"DTO password |\",userDTO.Password,\"| token password: |\",token[1],\"|\")\r\n\t\t\t\ta.Token.Status.Authenticated=false\r\n\t\t\t\ta.Token.Status.Error=\"User or Password is not correct!\"\r\n\t\t\t\tw.WriteHeader(http.StatusForbidden)\r\n\t\t\t\tjson.NewEncoder(w).Encode(&a.Token)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "func (i *Image) getAuthToken() error {\n\t//first we need to check response to GET /v2/ if we will get unauthorized then we will need to obtain token\n\tresp, err := http.Get(protocol + \"://\" + i.Registry + \"/v2/\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar realm, service string\n\tif resp.StatusCode == http.StatusUnauthorized {\n\t\t// we need token for this repo. WWW-Authenticate header will tell us where to get it\n\t\tre := regexp.MustCompile(`Bearer realm=\"(?P<realm>.*)\",service=\"(?P<service>.*)\"`)\n\t\tparsed := re.FindStringSubmatch(resp.Header.Get(\"WWW-Authenticate\"))\n\t\trealm, service = parsed[1], parsed[2]\n\t} else {\n\t\t//no token needed\n\t\treturn nil\n\t}\n\tresp, err = http.Get(realm + \"?service=\" + service + \"&scope=repository:\" + i.ImageName + \":pull\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar authResponse interface{}\n\tdecoder := json.NewDecoder(resp.Body)\n\terr = decoder.Decode(&authResponse)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn errors.New(\"Auth status code: \" + resp.Status)\n\t}\n\t/*\n\t Line below might look bit cryptic to newcomers but it's quite simple\n\t we decoded JSON response into interface{} datatype, but encoding/json package\n\t put map[string]interface{} there. We know that we want \"token\" field from json\n\t and it is a string. So we type asserted first interface{} to map[string]interface{}\n\t and then interface{} from map to string. We could avoid all this by creating\n\t proper struct for response json and parse json directly to this struct, but I'm too lazy ;)\n\t drawback: it will crash when asserted types doesn't match,\n\t but as all this is just for blog it's fine. Remember all type assertions presented in this\n\t code were made by professionals don't try this at home.\n\t*/\n\ti.Token = authResponse.(map[string]interface{})[\"token\"].(string)\n\n\treturn nil\n}", "func simpleAuth(w http.ResponseWriter, r *http.Request) (err string) {\n\theader := strings.Fields(r.Header.Get(\"Authorization\"))\n\tif len(header) < 2 {\n\t\tInfo.Println(\"No token given, not able to process request\")\n\t\treturn \"ko\"\n\t}\n\ts := strings.SplitN(r.Header.Get(\"Authorization\"), \" \", 2)\n\tif s[1] == token {\n\t\tDebug.Println(\"Token is eligible\")\n\t} else {\n\t\thttp.Error(w, \"Not authorized\", 401)\n\n\t}\n\treturn \"\"\n}", "func AuthCheck(c *gin.Context) {\n\tif firebase.AuthClient == nil {\n\t\treturn\n\t}\n\tidToken := c.GetHeader(\"Authorization\")\n\tif idToken == \"\" {\n\t\treturn\n\t}\n\tctx := context.Background()\n\ttoken, err := firebase.AuthClient.VerifyIDTokenAndCheckRevoked(ctx, idToken[len(\"Bearer \"):])\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\temail, found := token.Claims[\"email\"]\n\tif !found {\n\t\treturn\n\t}\n\temailStr, isString := email.(string)\n\tif !isString || emailStr == \"\" {\n\t\treturn\n\t}\n\temailVerified := token.Claims[\"email_verified\"]\n\temailVerifiedBool := emailVerified.(bool)\n\n\tuser := model.UserAccount{\n\t\tEmail: emailStr,\n\t\tEmailVerified: emailVerifiedBool,\n\t}\n\tc.Set(\"loginUser\", user)\n}", "func CheckAccess(permissionGroup string, hasRole string, makerChecker bool, requestedMethod string, requestedEndpoint string) (bool, error) {\n\n\tp := authPermissions.Permissions()\n\t// permissionsByte, err := ioutil.ReadFile(\"../permissions.json\")\n\tvar permissions Permissions\n\t// if err != nil {\n\t// \tpanic(err)\n\t// }\n\terr := json.Unmarshal([]byte(p), &permissions)\n\t// fmt.Print(string(permissionsByte))\n\n\tif err != nil {\n\t\tLOGGER.Error(\"Error while parsing JSON\")\n\t\treturn false, errors.New(\"not authorized, no matching permissions\")\n\t}\n\n\tif permissionGroup == \"Jwt\" {\n\n\t\t// endpoints requiring JWT\n\t\t// fmt.Print(\"\\n\\n\" + requestedMethod + \" | jwt endpoints:\\n\")\n\t\tjwtEndp := permissions.Permissions.Jwt.Default.Method[requestedMethod].Endpoint\n\t\tfor key, value := range jwtEndp {\n\t\t\t// fmt.Println(key+\" - Allow: \", value.Role.Allow)\n\t\t\tif hasRole == \"allow\" && value.Role.Allow == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"Permissions Succeeded! \"+key+\" - Allow: \", value.Role.Allow)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif permissionGroup == \"Super_permissions\" && makerChecker == false {\n\n\t\t// super user endpoints\n\t\t// fmt.Print(\"\\n\\n\" + requestedMethod + \" | super user endpoints:\\n\")\n\t\tsuperEndpDef := permissions.Permissions.Super_permissions.Default.Method[requestedMethod].Endpoint\n\t\tfor key, value := range superEndpDef {\n\t\t\t// fmt.Println(key+\" - Admin: \", value.Role.Admin)\n\t\t\t// fmt.Println(key+\" - Manager: \", value.Role.Manager)\n\t\t\tif hasRole == \"admin\" && value.Role.Admin == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Admin: \", value.Role.Admin)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tif hasRole == \"manager\" && value.Role.Manager == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Manager: \", value.Role.Manager)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif permissionGroup == \"Super_permissions\" && makerChecker == true {\n\n\t\t// super user endpoints requiring maker/checker\n\t\t// fmt.Print(\"\\n\\n\" + requestedMethod + \" | super user + maker/checker endpoints:\\n\")\n\t\tsuperEndpMC := permissions.Permissions.Super_permissions.Maker_checker.Method[requestedMethod].Endpoint\n\t\tfor key, value := range superEndpMC {\n\t\t\t// fmt.Println(key+\" - Admin: \", value.Role.Admin)\n\t\t\t// fmt.Println(key+\" - Manager: \", value.Role.Manager)\n\t\t\tif hasRole == \"admin\" && value.Role.Admin == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Admin: \", value.Role.Admin)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tif hasRole == \"manager\" && value.Role.Manager == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Manager: \", value.Role.Manager)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif permissionGroup == \"Participant_permissions\" && makerChecker == false {\n\n\t\t// participant user endpoints\n\t\t// fmt.Print(\"\\n\\n\" + requestedMethod + \" | participant endpoints:\\n\")\n\t\tparticipantEndpDef := permissions.Permissions.Participant_permissions.Default.Method[requestedMethod].Endpoint\n\t\tfor key, value := range participantEndpDef {\n\t\t\t// fmt.Println(key+\" - Admin: \", value.Role.Admin)\n\t\t\t// fmt.Println(key+\" - Manager: \", value.Role.Manager)\n\t\t\tif hasRole == \"admin\" && value.Role.Admin == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Admin: \", value.Role.Admin)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tif hasRole == \"manager\" && value.Role.Manager == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Manager: \", value.Role.Manager)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif permissionGroup == \"Participant_permissions\" && makerChecker == true {\n\n\t\t// participant user endpoints requiring maker/checker\n\t\t// fmt.Print(\"\\n\\n\" + requestedMethod + \" | participant + maker/checker endpoints:\\n\")\n\t\tparticipantEndpMC := permissions.Permissions.Participant_permissions.Maker_checker.Method[requestedMethod].Endpoint\n\t\tfor key, value := range participantEndpMC {\n\t\t\t// fmt.Println(key+\" - Admin: \", value.Role.Admin)\n\t\t\t// fmt.Println(key+\" - Manager: \", value.Role.Manager)\n\t\t\tif hasRole == \"admin\" && value.Role.Admin == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Admin: \", value.Role.Admin)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tif hasRole == \"manager\" && value.Role.Manager == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Manager: \", value.Role.Manager)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn false, errors.New(\"not authorized, no matching permissions\")\n\n}", "func (c ContainerImage) NeedAuth() bool {\n\tif c.Private {\n\t\treturn true\n\t}\n\treturn strings.HasPrefix(c.Repository, \"quay.io/\")\n}", "func OAUTHRedirect(ctx *fiber.Ctx) error {\n\n\tmodels.SYSLOG.Tracef(\"entering OAUTHRedirect; original URL: %v\", ctx.OriginalURL())\n\tdefer models.SYSLOG.Trace(\"exiting OAUTHRedirect\")\n\n\t// First, we need to get the value of the `code` query param\n\tcode := ctx.Query(\"code\", \"\")\n\tif len(code) < 1 {\n\t\treturn ctx.SendStatus(fiber.StatusBadRequest)\n\t}\n\n\t// Next, lets for the HTTP request to call the github oauth enpoint\tto get our access token\n\n\ta := fiber.AcquireAgent()\n\treq := a.Request()\n\treq.Header.SetMethod(fiber.MethodPost)\n\treq.Header.Set(\"accept\", \"application/json\")\n\treq.SetRequestURI(fmt.Sprintf(\"https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s\", models.ClientID, models.ClientSecret, code))\n\tif err := a.Parse(); err != nil {\n\t\tmodels.SYSLOG.Errorf(\"could not create HTTP request: %v\", err)\n\t}\n\n\tvar retCode int\n\tvar retBody []byte\n\tvar errs []error\n\t// Send out the HTTP request\n\tvar t *models.OAuthAccessResponse\n\n\tif retCode, retBody, errs = a.Struct(&t); len(errs) > 0 {\n\t\tmodels.SYSLOG.Tracef(\"received: %v\", string(retBody))\n\t\tmodels.SYSLOG.Errorf(\"could not send HTTP request: %v\", errs)\n\t\treturn ctx.SendStatus(fiber.StatusInternalServerError)\n\t}\n\tmodels.SYSLOG.Tracef(\"received : %v %v %v\", retCode, string(retBody), errs)\n\n\tvar sess *session.Session\n\tvar err error\n\t// Finally, send a response to redirect the user to the \"welcome\" page with the access token\n\tif sess, err = models.MySessionStore.Get(ctx); err == nil {\n\t\tsess.Set(\"token\", t.AccessToken)\n\t\tmodels.SYSLOG.Tracef(\"setting session token %v\", t.AccessToken)\n\t\tsessData, _ := models.MySessionStore.Get(ctx)\n\t\tdefer sessData.Save()\n\t\t//models.MySessionStore.RegisterType(models.OAuthAccessResponse)\n\t\tsessData.Set(\"oauth-scope\", t.Scope)\n\t\tsessData.Set(\"oauth-token-type\", t.TokenType)\n\t\tsessData.Set(\"oauth-token\", t.AccessToken)\n\n\t\tif err != nil {\n\t\t\tmodels.SYSLOG.Errorf(\"session saving exception %v\", err)\n\t\t}\n\t\tmodels.SYSLOG.Tracef(\"redirecting to /welcome.html?access_token=%v\", t.AccessToken)\n\t\t//\t\treturn ctx.Redirect(\"/welcome.html?access_token=\"+t.AccessToken, fiber.StatusFound)\n\t\treturn ctx.Redirect(\"/welcome.html\", fiber.StatusFound)\n\t}\n\n\tmodels.SYSLOG.Tracef(\"redirecting to /\")\n\treturn ctx.Redirect(\"/\", fiber.StatusTemporaryRedirect)\n}", "func (c *RestController) CheckToken(w http.ResponseWriter, r *http.Request) {\n\tvar req CheckTokenRequest\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.Check(r.Context(), &req)\n\tif err != nil {\n\t\tc.Error(w, err)\n\t\treturn\n\t}\n\tc.JSON(w, res.Data, http.StatusOK)\n}", "func (a *Auth) Do() (*http.Client, error) {\n\t// If a cache file is given, read from the cache file\n\tif a.CacheFile != \"\" {\n\t\ttmpCache := &AuthConfig{}\n\t\terr := tmpCache.Load(a.CacheFile)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Could not load cache file with path: \" + a.CacheFile)\n\t\t\treturn nil, err\n\t\t}\n\t\t// replace empty entries with cached values\n\t\tif a.Config.ConsumerKey == \"\" {\n\t\t\ta.Config.ConsumerKey = tmpCache.ConsumerKey\n\t\t}\n\t\tif a.Config.ConsumerSecret == \"\" {\n\t\t\ta.Config.ConsumerSecret = tmpCache.ConsumerSecret\n\t\t}\n\t\tif a.Config.VerCode == \"\" {\n\t\t\ta.Config.VerCode = tmpCache.VerCode\n\t\t}\n\t\t// Cache the new settings\n\t\terr = a.Config.Cache(a.CacheFile)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n\tc := oauth.NewConsumer(\n\t\ta.Config.ConsumerKey,\n\t\ta.Config.ConsumerSecret,\n\t\toauth.ServiceProvider{\n\t\t\tRequestTokenUrl: \"https://api.copy.com/oauth/request\",\n\t\t\tAuthorizeTokenUrl: \"https://www.copy.com/applications/authorize\",\n\t\t\tAccessTokenUrl: \"https://api.copy.com/oauth/access\",\n\t\t},\n\t)\n\t// If a verification code has not been supplied, request it from the browser and return.\n\tif a.Config.VerCode == \"\" {\n\t\t_, url, err := c.GetRequestTokenAndUrl(\"oob\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println(\"(1) Go to: \" + url)\n\t\tfmt.Println(\"(2) Grant access, you should get back a verification code.\")\n\t\tfmt.Println(\"(3) Run the program again with command line argument -code $AUTHCODE\")\n\t\treturn nil, nil\n\t}\n\t// If a code is supplied, atempt to obtain an authorization\n\taccessToken, _, err := c.GetRequestTokenAndUrl(\"oob\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil, nil\n\t}\n\tc.AuthorizeToken(accessToken, a.Config.VerCode)\n\treturn nil, nil\n}", "func (j *DSGitHub) Validate(ctx *Ctx) (err error) {\n\tj.Org = strings.TrimSpace(j.Org)\n\tif j.Org == \"\" {\n\t\terr = fmt.Errorf(\"github org must be set\")\n\t\treturn\n\t}\n\tj.Repo = strings.TrimSpace(j.Repo)\n\tif strings.HasSuffix(j.Repo, \".git\") {\n\t\tlRepo := len(j.Repo)\n\t\tj.Repo = j.Repo[:lRepo-4]\n\t}\n\tif j.Repo == \"\" {\n\t\terr = fmt.Errorf(\"github repo must be set\")\n\t\treturn\n\t}\n\tj.Category = strings.TrimSpace(j.Category)\n\tif j.Category == \"\" {\n\t\terr = fmt.Errorf(\"github category must be set\")\n\t\treturn\n\t}\n\tj.URL = \"https://github.com/\" + j.Org + \"/\" + j.Repo\n\tdefer func() {\n\t\tPrintf(\"configured %d GitHub OAuth clients\\n\", len(j.Clients))\n\t}()\n\tj.Tokens = strings.TrimSpace(j.Tokens)\n\t// Get GitHub OAuth from env or from file\n\toAuth := j.Tokens\n\tif strings.Contains(oAuth, \"/\") {\n\t\tbytes, err := ioutil.ReadFile(oAuth)\n\t\tFatalOnError(err)\n\t\toAuth = strings.TrimSpace(string(bytes))\n\t}\n\t// GitHub authentication or use public access\n\tj.Context = context.Background()\n\tif oAuth == \"\" {\n\t\tclient := github.NewClient(nil)\n\t\tj.Clients = append(j.Clients, client)\n\t} else {\n\t\toAuths := strings.Split(oAuth, \",\")\n\t\tfor _, auth := range oAuths {\n\t\t\tj.OAuthKeys = append(j.OAuthKeys, auth)\n\t\t\tts := oauth2.StaticTokenSource(\n\t\t\t\t&oauth2.Token{AccessToken: auth},\n\t\t\t)\n\t\t\ttc := oauth2.NewClient(j.Context, ts)\n\t\t\tclient := github.NewClient(tc)\n\t\t\tj.Clients = append(j.Clients, client)\n\t\t}\n\t}\n\tif CacheGitHubRepo {\n\t\tj.GitHubRepo = make(map[string]map[string]interface{})\n\t}\n\tif CacheGitHubIssues {\n\t\tj.GitHubIssues = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubUser {\n\t\tj.GitHubUser = make(map[string]map[string]interface{})\n\t}\n\tif CacheGitHubIssueComments {\n\t\tj.GitHubIssueComments = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubCommentReactions {\n\t\tj.GitHubCommentReactions = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubIssueReactions {\n\t\tj.GitHubIssueReactions = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubPull {\n\t\tj.GitHubPull = make(map[string]map[string]interface{})\n\t}\n\tif CacheGitHubPulls {\n\t\tj.GitHubPulls = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubPullReviews {\n\t\tj.GitHubPullReviews = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubPullReviewComments {\n\t\tj.GitHubPullReviewComments = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubReviewCommentReactions {\n\t\tj.GitHubReviewCommentReactions = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubPullRequestedReviewers {\n\t\tj.GitHubPullRequestedReviewers = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubPullCommits {\n\t\tj.GitHubPullCommits = make(map[string][]map[string]interface{})\n\t}\n\tif CacheGitHubUserOrgs {\n\t\tj.GitHubUserOrgs = make(map[string][]map[string]interface{})\n\t}\n\t// Multithreading\n\tj.ThrN = GetThreadsNum(ctx)\n\tif j.ThrN > 1 {\n\t\tj.GitHubMtx = &sync.RWMutex{}\n\t\tj.GitHubRateMtx = &sync.RWMutex{}\n\t\tif CacheGitHubRepo {\n\t\t\tj.GitHubRepoMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubIssues {\n\t\t\tj.GitHubIssuesMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubUser {\n\t\t\tj.GitHubUserMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubIssueComments {\n\t\t\tj.GitHubIssueCommentsMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubCommentReactions {\n\t\t\tj.GitHubCommentReactionsMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubIssueReactions {\n\t\t\tj.GitHubIssueReactionsMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubPull {\n\t\t\tj.GitHubPullMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubPulls {\n\t\t\tj.GitHubPullsMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubPullReviews {\n\t\t\tj.GitHubPullReviewsMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubPullReviewComments {\n\t\t\tj.GitHubPullReviewCommentsMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubReviewCommentReactions {\n\t\t\tj.GitHubReviewCommentReactionsMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubPullRequestedReviewers {\n\t\t\tj.GitHubPullRequestedReviewersMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubPullCommits {\n\t\t\tj.GitHubPullCommitsMtx = &sync.RWMutex{}\n\t\t}\n\t\tif CacheGitHubUserOrgs {\n\t\t\tj.GitHubUserOrgsMtx = &sync.RWMutex{}\n\t\t}\n\t}\n\tj.Hint, _ = j.handleRate(ctx)\n\tj.CacheDir = os.Getenv(\"HOME\") + \"/.perceval/github-users-cache/\"\n\t_ = os.MkdirAll(j.CacheDir, 0777)\n\treturn\n}", "func checkToken(request *Request) (bool, error) {\n\tif request.MethodName == \"auth\" {\n\t\treturn true, nil\n\t} else {\n\t\tif valid, err := model.CheckToken(request.Token); valid && err == nil {\n\t\t\treturn true, nil\n\t\t} else {\n\t\t\treturn false, err\n\t\t}\n\t}\n}", "func TestOAUTH2Token(t *testing.T) {\n\tconnection, err := NewConnectionBuilder().\n\t\tURL(\"http://localhost:9100/api\").\n\t\tUsername(\"admin\").\n\t\tPassword(\"password\").\n\t\tBuild()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tdefer connection.Close()\n\tvcr := govcr.NewVCR(\"connection_oauth2\",\n\t\t&govcr.VCRConfig{\n\t\t\tClient: connection.client,\n\t\t\tDisableRecording: true,\n\t\t})\n\t// Replace our HTTPClient with a vcr client wrapping it\n\tconnection.client = vcr.Client\n\tprojectsResource := connection.Projects()\n\n\t// Trigger the auth flow.\n\tgetProjectsRequest := projectsResource.Get()\n\tif len(connection.token) != 0 || len(connection.bearer) != 0 {\n\t\tt.Errorf(\"Connection should have no tokens. token: '%s', bearer: '%s'\",\n\t\t\tconnection.token,\n\t\t\tconnection.bearer)\n\t}\n\t_, err = getProjectsRequest.Send()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif len(connection.token) != 0 || len(connection.bearer) == 0 {\n\t\tt.Errorf(\"Connection should have only a bearer token. token: '%s', bearer: '%s'\",\n\t\t\tconnection.token,\n\t\t\tconnection.bearer)\n\t}\n}", "func (g *V3) CheckToken() error {\n\tif _, err := g.listReposInner(false); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (rest *TestTokenStorageREST) TestStatusExternalTokenValidOnForcePullInternalError() {\n\tidentity, err := testsupport.CreateTestIdentity(rest.DB, uuid.NewV4().String(), \"KC\")\n\trequire.Nil(rest.T(), err)\n\trest.checkStatusExternalTokenValidOnForcePullInternalError(identity, \"https://github.com/a/b\", \"https://github.com\")\n\trest.checkStatusExternalTokenValidOnForcePullInternalError(identity, \"github\", \"https://github.com\")\n\trest.checkStatusExternalTokenValidOnForcePullInternalError(identity, \"openshift\", \"https://api.starter-us-east-2.openshift.com/\")\n\trest.checkStatusExternalTokenValidOnForcePullInternalError(identity, \"https://api.starter-us-east-2.openshift.com\", \"https://api.starter-us-east-2.openshift.com/\")\n}", "func Auth(next handlers.HandlerFunc) handlers.HandlerFunc {\n\treturn func(env *handlers.Env, w http.ResponseWriter, r *http.Request) error {\n\t\tsignature, err := r.Cookie(\"signature\")\n\t\tif err != nil {\n\t\t\treturn handlers.StatusData{\n\t\t\t\tCode: http.StatusUnauthorized,\n\t\t\t\tData: map[string]string{\n\t\t\t\t\t\"error\": \"No signature cookie found\",\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\n\t\theaderPayload, err := r.Cookie(\"header.payload\")\n\t\tif err != nil {\n\t\t\treturn handlers.StatusData{\n\t\t\t\tCode: http.StatusUnauthorized,\n\t\t\t\tData: map[string]string{\n\t\t\t\t\t\"error\": \"No headerPayload cookie found\",\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\n\t\ttokenString := headerPayload.Value + \".\" + signature.Value\n\n\t\tctx := cnt.Background()\n\t\tauthManager := auth_proto.NewAuthCheckerClient(env.GRCPAuth)\n\t\ttoken, err := authManager.Check(ctx,\n\t\t\t&auth_proto.Token{\n\t\t\t\tToken: tokenString,\n\t\t\t})\n\n\t\tif err != nil {\n\t\t\tenv.Logger.Errorw(\"Error during grpc request\",\n\t\t\t\t\"err\", err.Error(),\n\t\t\t\t\"grpc\", \"user\",\n\t\t\t)\n\t\t\treturn handlers.StatusData{\n\t\t\t\tCode: http.StatusInternalServerError,\n\t\t\t\tData: map[string]string{\n\t\t\t\t\t\"error\": \"Internal server error\",\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\n\t\tif !token.Valid {\n\t\t\treturn handlers.StatusData{\n\t\t\t\tCode: http.StatusUnauthorized,\n\t\t\t\tData: map[string]string{\n\t\t\t\t\t\"error\": \"Token is not valid\",\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\n\t\tclaims := make(map[string]interface{})\n\t\terr = json.Unmarshal(token.Claims, &claims)\n\t\tif err != nil {\n\t\t\tenv.Logger.Warnw(\"Can't unmarshall data\",\n\t\t\t\t\"err\", err.Error(),\n\t\t\t\t\"data\", claims,\n\t\t\t\t\"json\", string(token.Claims),\n\t\t\t)\n\t\t\treturn handlers.StatusData{\n\t\t\t\tCode: http.StatusUnauthorized,\n\t\t\t\tData: map[string]string{\n\t\t\t\t\t\"error\": \"Token is not valid\",\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\n\t\tcontext.Set(r, \"claims\", claims)\n\n\t\treturn next(env, w, r)\n\t}\n}", "func oauth2FactoryToken(w http.ResponseWriter, r *http.Request) {\n\tparas, incName := r.URL.Query(), mux.Vars(r)[\"incName\"]\n\t// if error parameter exists.\n\tif _, ok := paras[\"error\"]; ok {\n\t\thttp.Redirect(w, r, \"/index\", http.StatusFound)\n\t\treturn\n\t}\n\tform := url.Values{}\n\tform.Add(\"client_id\", oauth2Infos[incName].clientId)\n\tform.Add(\"client_secret\", oauth2Infos[incName].clientSecret)\n\tform.Add(\"code\", paras[\"code\"][0])\n\tform.Add(\"redirect_uri\", oauth2Infos[incName].redirectUrl)\t// the redirectUrl should be my host index\n\tform.Add(\"state\", incName)\n\n\tres, _ := http.Post(oauth2Infos[incName].tokenUrl, \"application/x-www-form-urlencoded\", strings.NewReader(form.Encode()))\n\tbody, _ := ioutil.ReadAll(res.Body)\n\tres, _ = http.Get(oauth2Infos[incName].infoUrl + \"?access_token=\" + jsonProcessString(string(body))[\"access_token\"])\n\tbody, _ = ioutil.ReadAll(res.Body)\n\t// Get the access_token and put user information to mydatabase\n\tinfos := &githubUser{}\n\tjson.Unmarshal(body, &infos)\n\tif users := SelectUser(map[string]interface{}{\"username\": infos.Login, \"source\": incName}); len(users) == 0 {\n\t\tgo AddUser(User{Source: incName, UserId: uuid.Must(uuid.NewV4()).String(), Username: infos.Login, Password: infos.Login, Avatar: infos.AvatarURL, InfoURL: infos.URL, Bio: infos.Bio})\n\t}\n\n\t// Later, we will marsh a better user info cookie.\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: \"user\",\n\t\tValue: infos.Login,\t// user struct json\n\t\tPath: \"/\",\n\t\tExpires: time.Now().AddDate(0, 1, 0),\n\t\tMaxAge: 86400,\t// 100 hours' validate time\n\t})\n\thttp.Redirect(w, r, \"/index\", http.StatusFound)\t\t// redirect to the index page\n}", "func (c *config) Auth(token, secret string) (string, error) {\n\tclient := c.newClientToken(token, secret)\n\tuser, err := client.FindCurrent()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn user.Login, nil\n\t// creates a new http request to bitbucket.\n\t\n\t// var buf io.ReadWriter\n\t// req, err := http.NewRequest(\"GET\",\"https://api.bitbucket.org/2.0/user/\",buf)\n\t// if err != nil {\n\t// \treturn \"\",err\n\t// }\n\t// req.Header.Set(\"Authorization\", \"Basic ampxX3Rlc3Q6bkFEUFZtTThyRFEzRDUyUmNhSFE=\")\n\n\t// client := &http.Client{}\n\t// resp, err := client.Do(req)\n\t// if err != nil {\n\t// \treturn \"\",err\n\t// }\n\t// defer resp.Body.Close()\n\n\t// // if an error is encountered, parse and return the\n\t// // error response.\n\t// if resp.StatusCode > http.StatusPartialContent {\n\t// \terr := internal.Error{}\n\t// \tjson.NewDecoder(resp.Body).Decode(&err)\n\t// \terr.Status = resp.StatusCode\n\t// \treturn \"\",err\n\t// }\n\t// body, err := ioutil.ReadAll(resp.Body)\n // if err != nil {\n // // handle error\n // }\n\n\n\t// out := new(internal.Account)\n\t// // return json.NewDecoder(resp.Body).Decode(out),nil\n\t// json.Unmarshal(body,out)\n\n\t// log.Debug(out.Login)\n\t// return out.Login,err\n\n\t// log.Debug(\"resp is \",resp)\n\n\t// if a json response is expected, parse and return\n\t// the json response.\n\t// if out != nil {\n\t// \treturn json.NewDecoder(resp.Body).Decode(out)\n\t// }\n\t\n\t// return \"\", nil\n\n}", "func IsLegalUserByRefreshToken(Auth string) (bool, User) {\n\n\tvar Answer bool\n\tvar currentToken Token\n\tvar currentUser User\n\n\ttoken := strings.Replace(Auth, \"Bearer \", \"\", -1)\n\n\t// var blankid uuid.UUID\n\tDb.Where(\"token = ?\", token).Last(&currentToken)\n\tif currentToken.Token != \"\" {\n\n\t\tif currentToken.Expired.After(time.Now()) {\n\n\t\t\tDb.Where(\"id = ?\", currentToken.UserID).Last(&currentUser)\n\n\t\t\tif currentUser.Name != \"\" {\n\t\t\t\tAnswer = true\n\t\t\t} else {\n\t\t\t\tAnswer = false\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn Answer, currentUser\n\n}", "func TestPreOAUTH2(t *testing.T) {\n\t//\n\t// Password manuall edited in cassete:\n\t// Basic = printf \"admin:PASSWORD\"| base64\n\t// Body = printf '{\"username\":\"admin\",\"password\":\"PASSWORD\"}'|base64\n\tconnection, err := NewConnectionBuilder().\n\t\tURL(\"https://tower.private/api\").\n\t\tUsername(\"admin\").\n\t\tPassword(\"PASSWORD\").\n\t\tInsecure(true).\n\t\tBuild()\n\tif err != nil {\n\t\tt.Errorf(\"Error creating connection: %s\", err)\n\t}\n\tdefer connection.Close()\n\tvcr := govcr.NewVCR(\"connection_pre_oauth2\",\n\t\t&govcr.VCRConfig{\n\t\t\tClient: connection.client,\n\t\t\tDisableRecording: true,\n\t\t})\n\t// Replace our HTTPClient with a vcr client wrapping it\n\tconnection.client = vcr.Client\n\tprojectsResource := connection.Projects()\n\n\t// Trigger the auth flow.\n\tgetProjectsRequest := projectsResource.Get()\n\tif len(connection.token) != 0 || len(connection.bearer) != 0 {\n\t\tt.Errorf(\"Connection should have no tokens. token: '%s', bearer: '%s'\",\n\t\t\tconnection.token,\n\t\t\tconnection.bearer)\n\t}\n\t_, err = getProjectsRequest.Send()\n\tif err != nil {\n\t\tt.Errorf(\"Error sending project request: %s\", err)\n\t}\n\tif len(connection.token) == 0 || len(connection.bearer) != 0 {\n\t\tt.Errorf(\"Connection should have only an auth token. token: '%s', bearer: '%s'\",\n\t\t\tconnection.token,\n\t\t\tconnection.bearer)\n\t}\n}", "func checkPermissions(request *Request) (bool, error) {\n\tif request.MethodName == \"auth\" {\n\t\treturn true, nil\n\t} else {\n\t\tif token, err := model.TokenByValue(request.Token); err == nil{\n\t\t\tif user, err := model.UserById(token.UserId); err == nil{\n\t\t\t\treturn isOperationAllowed(user, request.MethodName), nil\n\t\t\t}\n\t\t} else {\n\t\t\treturn false, err\n\t\t}\n\t\treturn false, nil\n\t}\n}", "func (oc *Client) primaryAuth(loginDetails *creds.LoginDetails) (string, string, string, error) {\n\n\toktaURL, err := url.Parse(loginDetails.URL)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", errors.Wrap(err, \"error building oktaURL\")\n\t}\n\n\toktaOrgHost := oktaURL.Host\n\t//authenticate via okta api\n\tauthReq := AuthRequest{Username: loginDetails.Username, Password: loginDetails.Password}\n\tif loginDetails.StateToken != \"\" {\n\t\tauthReq = AuthRequest{StateToken: loginDetails.StateToken}\n\t}\n\tauthBody := new(bytes.Buffer)\n\terr = json.NewEncoder(authBody).Encode(authReq)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", errors.Wrap(err, \"error encoding authreq\")\n\t}\n\n\tauthSubmitURL := fmt.Sprintf(\"https://%s/api/v1/authn\", oktaOrgHost)\n\n\treq, err := http.NewRequest(\"POST\", authSubmitURL, authBody)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", errors.Wrap(err, \"error building authentication request\")\n\t}\n\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"Accept\", \"application/json\")\n\n\tres, err := oc.client.Do(req)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", errors.Wrap(err, \"error retrieving auth response\")\n\t}\n\n\tbody, err := io.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", errors.Wrap(err, \"error retrieving body from response\")\n\t}\n\n\tresp := string(body)\n\n\tauthStatus := gjson.Get(resp, \"status\").String()\n\toktaSessionToken := gjson.Get(resp, \"sessionToken\").String()\n\n\treturn authStatus, oktaSessionToken, resp, nil\n}", "func isAuthorized(endpoint func(http.ResponseWriter, *http.Request)) http.Handler {\r\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\r\n\t\r\n\t\r\n\tvar N = len(idlist) //Size of the users list\r\n\t\r\n\tif r.Header[\"Clientid\"] != nil { //Let's first check the user filled the 'Clientid' header key\r\n\t\t//We verify whether or not the ID submitted is valid\r\n\t\tvar verif string = \"not ok\"\r\n\t\tfor i:=0;i<N;i++{\r\n\t\t\tif r.Header[\"Clientid\"][0]==idlist[i]{\r\n\t\t\t\tverif=\"ok\" \r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t//Verification of the encrypted password submitted by the user\r\n\t\tif verif==\"ok\"{ //The Client ID is valid, let's verify the password is correct and matches the client ID\r\n\t\t\tif r.Header[\"Clientid\"][0]==\"1\" { //First case: the user signed in as user 1\r\n\t\t\t\tif r.Header[\"Token\"] != nil { //Once again, a token is required to continue the authentication process\r\n\t\t\t\t\r\n\t\t\t\t\t\ttoken, err := jwt.Parse(r.Header[\"Token\"][0], func(token *jwt.Token) (interface{}, error) {\r\n\t\t\t\t\t\t\tif _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\r\n\t\t\t\t\t\t\t\treturn nil, fmt.Errorf(\"There was an error\")\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\treturn mySigningKeyone, nil\t\r\n\t\t\t\t\t\t})\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif err != nil {\r\n\t\t\t\t\t\t\tfmt.Fprintf(w, err.Error())\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t//if the 'token' is valid, user 1 has now signed in\r\n\t\t\t\t\t\tif token.Valid {\r\n\t\t\t\t\t\t\tclientnum=r.Header[\"Clientid\"][0] \r\n\t\t\t\t\t\t\tendpoint(w, r)\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\telse {\r\n\t\t\t\t\t\t\tfmt.Fprintf(w, \"Not Authorized\")\r\n\t\t\t\t\t}\r\n\t\t\t}\telse { //Second case: the user signed in as user 2\r\n\t\t\t\tif r.Header[\"Token\"] != nil { //Once again, a token is required to continue the authentication process\r\n\t\t\t\t\r\n\t\t\t\t\t\ttoken, err := jwt.Parse(r.Header[\"Token\"][0], func(token *jwt.Token) (interface{}, error) {\r\n\t\t\t\t\t\t\tif _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\r\n\t\t\t\t\t\t\t\treturn nil, fmt.Errorf(\"There was an error\")\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\treturn mySigningKeytwo, nil\t\r\n\t\t\t\t\t\t})\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif err != nil {\r\n\t\t\t\t\t\t\tfmt.Fprintf(w, err.Error())\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t//if the 'token' is valid, user 2 has now signed in\r\n\t\t\t\t\t\tif token.Valid {\r\n\t\t\t\t\t\t\tclientnum=r.Header[\"Clientid\"][0] \r\n\t\t\t\t\t\t\tendpoint(w, r)\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\telse {\r\n\t\t\t\t\r\n\t\t\t\t\t\t\tfmt.Fprintf(w, \"Not Authorized\")\r\n\t\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\telse { \r\n\t\t\t\tfmt.Fprintf(w, \"This ID does not exist\")\r\n\t\t}\r\n\t\t\t\t\t\r\n\t\t} else {\r\n\t\t\tfmt.Fprintf(w, \"Insert ID\")\r\n\t\t}\r\n\t})\r\n}", "func CheckAuth(prefix string, repo *model.Repo) func(jqeventrouter.Handler) jqeventrouter.Handler {\n\treturn func(h jqeventrouter.Handler) jqeventrouter.Handler {\n\t\treturn jqeventrouter.HandlerFunc(func(event *jquery.Event, ui *js.Object, params url.Values) bool {\n\t\t\treqURL, _ := url.Parse(ui.Get(\"toPage\").String())\n\t\t\tif reqURL.Path == prefix+\"/callback.html\" {\n\t\t\t\t// Allow unauthenticated callback, needed by dev logins\n\t\t\t\treturn true\n\t\t\t}\n\t\t\t_, err := repo.CurrentUser()\n\t\t\tif err != nil && err != model.ErrNotLoggedIn {\n\t\t\t\tlog.Printf(\"Unknown error: %s\", err)\n\t\t\t}\n\t\t\tif err == model.ErrNotLoggedIn {\n\t\t\t\tredir := \"login.html\"\n\t\t\t\tlog.Debug(\"TODO: use params instead of re-parsing URL?\")\n\t\t\t\tparsed, _ := url.Parse(js.Global.Get(\"location\").String())\n\t\t\t\tfmt.Printf(\"params = %v\\nparsed = %v\\n\", params, parsed.Query())\n\t\t\t\tif p := parsed.Query().Get(\"provider\"); p != \"\" {\n\t\t\t\t\tredir = \"callback.html\"\n\t\t\t\t}\n\t\t\t\tlog.Printf(\"Redirecting unauthenticated user to %s\\n\", redir)\n\t\t\t\tlog.Debug(\"TODO: Do I need ui.Set *and* trigger before change here?\")\n\t\t\t\tui.Set(\"toPage\", redir)\n\t\t\t\tevent.StopImmediatePropagation()\n\t\t\t\tjquery.NewJQuery(\":mobile-pagecontainer\").Trigger(\"pagecontainerbeforechange\", ui)\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn h.HandleEvent(event, ui, url.Values{})\n\t\t})\n\t}\n}", "func checkReturnCode(resp http.Response) (err error) {\n\terr = nil\n\tif resp.StatusCode >= 300 {\n\t\tswitch resp.StatusCode {\n\t\tcase http.StatusNotFound:\n\t\t\terr = httpErrorMesg(resp, \"Check for valid argument (user, group etc).\")\n\t\tcase http.StatusUnauthorized:\n\t\t\terr = httpErrorMesg(resp, \"Check for valid token.\")\n\t\tcase http.StatusForbidden:\n\t\t\terr = httpErrorMesg(resp, \"Check for valid token and token user must be an admin\")\n\t\tdefault:\n\t\t\terr = httpError(resp)\n\t\t}\n\t}\n\treturn err\n}", "func checkReturnCode(resp http.Response) (err error) {\n\terr = nil\n\tif resp.StatusCode >= 300 {\n\t\tswitch resp.StatusCode {\n\t\tcase http.StatusNotFound:\n\t\t\terr = httpErrorMesg(resp, \"Check for valid argument (user, group etc).\")\n\t\tcase http.StatusUnauthorized:\n\t\t\terr = httpErrorMesg(resp, \"Check for valid token.\")\n\t\tcase http.StatusForbidden:\n\t\t\terr = httpErrorMesg(resp, \"Check for valid token and token user must be an admin\")\n\t\tdefault:\n\t\t\terr = httpError(resp)\n\t\t}\n\t}\n\treturn err\n}", "func (om *Sdk) ReadyForAuth() bool {\n\tresp, err := om.api.EnsureAvailability(api.EnsureAvailabilityInput{})\n\treturn err == nil && resp.Status == api.EnsureAvailabilityStatusComplete\n}", "func validate(url, token string) (bool, error) {\n\turl = strings.TrimSuffix(url, \"/\")\n\tpath := fmt.Sprintf(\"%s/api/authentication/validate\", url)\n\n\tlog.Infof(\"test path:%s\", path)\n\treq, err := http.NewRequest(http.MethodGet, path, nil)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t// -u your-token: , colon(:) is needed.\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Basic %s\", base64.StdEncoding.EncodeToString([]byte(token+\":\"))))\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tlog.Errorf(\"Fail to validate sonarqube token as %s\", err.Error())\n\t\treturn false, convertSonarQubeError(err, resp)\n\t}\n\tdefer func() {\n\t\tif err := resp.Body.Close(); err != nil {\n\t\t\tlog.Errorf(\"Fail to close response body as: %v\", err)\n\t\t}\n\t}()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Errorf(\"Fail to validate sonarqube token as %s\", err.Error())\n\t\treturn false, err\n\t}\n\n\tvalid := &validResp{}\n\tif resp.StatusCode/100 == 2 {\n\t\terr := json.Unmarshal(body, valid)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tif valid.Valid {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, cerr.ErrorExternalAuthenticationFailed.Error(valid)\n\t}\n\n\terr = fmt.Errorf(\"Fail to validate sonarqube token as %s, resp code: %v \", body, resp.StatusCode)\n\treturn false, err\n}", "func ValidateAuth(verifyKey *rsa.PublicKey, h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\tauthorizationHeader := r.Header.Get(\"Authorization\")\n\t\tif authorizationHeader != \"\" {\n\t\t\tbearerToken := strings.TrimPrefix(authorizationHeader, \"Bearer\")\n\t\t\tbearerToken = strings.TrimSpace(bearerToken)\n\t\t\t// tokenPart := bearerToken[1] //Grab the token part, what we are truly interested in\n\t\t\tcustomClaims := &claims.Claims{}\n\n\t\t\ttoken, err := jwt.ParseWithClaims(bearerToken, customClaims, func(token *jwt.Token) (interface{}, error) {\n\t\t\t\treturn verifyKey, nil\n\t\t\t})\n\n\t\t\tif err != nil { // Malformed token, returns with http code 403 as usual\n\t\t\t\tw.WriteHeader(http.StatusForbidden)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !token.Valid {\n\t\t\t\tw.WriteHeader(http.StatusForbidden)\n\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx := r.Context()\n\t\t\t// Everything went well, proceed with the request and set the caller to the user retrieved from the parsed token\n\t\t\tr = r.WithContext(AddClaims(ctx, customClaims))\n\t\t\th.ServeHTTP(w, r) // proceed in the middleware chain!\n\t\t} else {\n\t\t\tjson.NewEncoder(w).Encode(\"Invalid Authorization Token\")\n\t\t}\n\t})\n}", "func (am authManager) healthCheck(authInfo api.AuthInfo) error {\n\treturn am.clientManager.HasAccess(authInfo)\n}", "func checkLoggedIn(w http.ResponseWriter, r *http.Request) (*ReqBody, error) {\n\t// get token from request header\n\tReqBody, err := getTknFromReq(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// check if the token is valid or not\n\t// if valid return the user currently logged in\n\tuser := verifyToken(ReqBody.Token)\n\tReqBody.UserDB = user\n\tlog.Println(\"checklogged in\", ReqBody)\n\treturn ReqBody, nil\n}", "func RequestTokenUsingAuthorizationCode(env *Environment) gin.HandlerFunc {\n fn := func(c *gin.Context) {\n log := c.MustGet(env.Constants.LogKey).(*logrus.Entry)\n log = log.WithFields(logrus.Fields{\n \"func\": \"RequestTokenUsingAuthorizationCode\",\n })\n\n error := c.Query(\"error\"); // Hydra specific error handling\n if error != \"\" {\n c.AbortWithStatus(http.StatusBadRequest)\n return\n }\n\n oauth2Config := FetchOAuth2Config(env, c)\n if oauth2Config == nil {\n log.Debug(\"Missing oauth2 config. Hint: Oauth2 config is missing from context. Did you call ConfigureOauth2 before calling RequestTokenUsingAuthorizationCode?\")\n c.AbortWithStatus(http.StatusInternalServerError)\n return\n }\n\n code := c.Query(\"code\")\n if code == \"\" {\n // Unauthorized, request an access token for required scopes only using authorization code flow.\n // TODO: Add pkce\n\n idTokenHint := IdTokenHint(env, c)\n\n // Use precalculated state iff present\n state := FetchPrecalculatedState(env, c)\n\n initUrl, err := StartAuthenticationSession(env, c, oauth2Config, idTokenHint, state)\n if err != nil {\n log.Debug(err.Error())\n c.AbortWithStatus(http.StatusInternalServerError)\n return\n }\n\n // This is not allowed by ORY Hydra even though the url (without params) is registered to the client\n /*emailChallenge := c.Query(\"email_challenge\")\n if emailChallenge != \"\" {\n q := initUrl.Query()\n\n redirectUri := q.Get(\"redirect_uri\")\n if redirectUri != \"\" {\n _redirect, err := url.Parse(redirectUri)\n if err != nil {\n log.Debug(err.Error())\n c.AbortWithStatus(http.StatusInternalServerError)\n return\n }\n\n rq := _redirect.Query()\n rq.Add(\"email_challenge\", emailChallenge)\n _redirect.RawQuery = rq.Encode()\n q.Set(\"redirect_uri\", _redirect.String())\n initUrl.RawQuery = q.Encode()\n }\n\n }*/\n\n c.Redirect(http.StatusFound, initUrl.String())\n c.Abort()\n return\n }\n\n // We recived a code request, try and exchange it for a token.\n\n requestState := c.Query(\"state\")\n if requestState == \"\" {\n log.Debug(\"Missing state in query\")\n c.AbortWithStatus(http.StatusBadRequest)\n return\n }\n log = log.WithFields(logrus.Fields{ \"state\":requestState })\n\n valid := ValidateSessionState(env, c, requestState)\n if valid == false {\n log.Debug(\"Request state invalid\")\n c.AbortWithStatus(http.StatusBadRequest)\n return\n }\n\n // Require redirect_to registered to session exchange state\n redirectTo, exists := FetchSessionRedirect(env, c, requestState)\n if exists == false {\n log.Debug(\"Session redirect not found\")\n c.AbortWithStatus(http.StatusBadRequest)\n return\n }\n log = log.WithFields(logrus.Fields{ \"session.redirect_to\":redirectTo })\n\n token, err := oauth2Config.Exchange(context.Background(), code)\n if err != nil {\n log.Debug(err.Error())\n c.AbortWithStatus(http.StatusBadRequest) // FIXME: Maybe we should redirect back reboot the process. Since the access token was not aquired.\n return\n }\n\n if token.Valid() == false {\n c.AbortWithStatus(http.StatusForbidden)\n return\n }\n\n // Optional extract IdToken iff present.\n idToken, idTokenHint, err := fetchIdTokenFromAccessToken(env, oauth2Config, token)\n if err != nil {\n log.Debug(err.Error())\n c.AbortWithStatus(http.StatusBadRequest)\n return\n }\n\n if idToken != nil {\n c.Set(env.Constants.ContextIdTokenKey, idToken)\n }\n\n if idTokenHint != \"\" {\n c.Set(env.Constants.ContextIdTokenHintKey, idTokenHint)\n }\n\n c.Set(env.Constants.ContextAccessTokenKey, token)\n c.Next()\n return\n }\n return gin.HandlerFunc(fn)\n}", "func (p *GitInstallationScopedMiddleware) doesUserHaveGitInstallationAccess(ctx context.Context, githubIntegrationID, gitInstallationID uint) error {\n\tctx, span := telemetry.NewSpan(ctx, \"check-user-has-git-installation-access\")\n\tdefer span.End()\n\n\toauthInt, err := p.config.Repo.GithubAppOAuthIntegration().ReadGithubAppOauthIntegration(githubIntegrationID)\n\tif err != nil {\n\t\treturn telemetry.Error(ctx, span, err, \"unable to read github app oauth integration\")\n\t}\n\n\tif p.config.GithubAppConf == nil {\n\t\treturn telemetry.Error(ctx, span, nil, \"config has invalid GithubAppConf\")\n\t}\n\n\tif _, _, err = oauth.GetAccessToken(oauthInt.SharedOAuthModel,\n\t\t&p.config.GithubAppConf.Config,\n\t\toauth.MakeUpdateGithubAppOauthIntegrationFunction(oauthInt, p.config.Repo)); err != nil {\n\t\treturn telemetry.Error(ctx, span, err, \"unable to get access token\")\n\t}\n\n\tclient := github.NewClient(p.config.GithubConf.Client(ctx, &oauth2.Token{\n\t\tAccessToken: string(oauthInt.AccessToken),\n\t\tRefreshToken: string(oauthInt.RefreshToken),\n\t\tTokenType: \"Bearer\",\n\t}))\n\n\taccountIDs := make([]int64, 0)\n\n\tAuthUser, _, err := client.Users.Get(ctx, \"\")\n\tif err != nil {\n\t\treturn telemetry.Error(ctx, span, err, \"unable to get authenticated user\")\n\t}\n\n\taccountIDs = append(accountIDs, *AuthUser.ID)\n\n\topts := &github.ListOptions{\n\t\tPerPage: 100,\n\t\tPage: 1,\n\t}\n\n\tfor {\n\t\torgs, pages, err := client.Organizations.List(ctx, \"\", opts)\n\t\tif err != nil {\n\t\t\treturn telemetry.Error(ctx, span, err, \"unable to list organizations\")\n\t\t}\n\n\t\tfor _, org := range orgs {\n\t\t\taccountIDs = append(accountIDs, *org.ID)\n\t\t}\n\n\t\tif pages.NextPage == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\ttelemetry.WithAttributes(span, telemetry.AttributeKV{Key: \"account-ids\", Value: fmt.Sprintf(\"%v\", accountIDs)})\n\n\tinstallations, err := p.config.Repo.GithubAppInstallation().ReadGithubAppInstallationByAccountIDs(accountIDs)\n\tif err != nil {\n\t\treturn telemetry.Error(ctx, span, err, \"unable to read github app installations\")\n\t}\n\n\tinstallationIds := make([]int64, 0)\n\tfor _, installation := range installations {\n\t\tinstallationIds = append(installationIds, installation.InstallationID)\n\t}\n\n\ttelemetry.WithAttributes(span, telemetry.AttributeKV{Key: \"installation-ids-for-account-ids\", Value: fmt.Sprintf(\"%v\", installationIds)})\n\n\tfor _, installation := range installations {\n\t\tif uint(installation.InstallationID) == gitInstallationID {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn telemetry.Error(ctx, span, nil, \"user does not have access to github app installation\")\n}", "func Example_authFailureTest() {\n\tconfigEnv := os.Getenv(\"CONFIG\")\n\n\tif configEnv == \"\" {\n\t\tfmt.Println(\"Please provide CONFIG environmenet variable (see Example_authFailureTest doc)\")\n\t\treturn\n\t}\n\n\t// Start Server\n\tif config, err := gauth.FromCredentialsFile(configEnv, \"http://localhost:6060/gauth\", nil); err != nil {\n\t\tfmt.Println(\"Could not open config file\", configEnv)\n\t} else {\n\t\tserver := &http.Server{}\n\t\tdefer server.Close()\n\t\tserver.Handler = gauth.Middleware(config, &gauth.MemorySessions{}, nil)\n\t\tserver.Addr = \":6060\"\n\t\tgo server.ListenAndServe()\n\t}\n\n\t// make validate_token call\n\tclient := &http.Client{CheckRedirect: func(r *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }}\n\tresp, err := client.Get(\"http://localhost:6060/some_path\")\n\tif err != nil {\n\t\tfmt.Println(\"Failed with error\", err)\n\t} else if resp.StatusCode != http.StatusTemporaryRedirect {\n\t\tfmt.Println(\"Failed with status\", resp.Status)\n\t} else if loc, err := resp.Location(); err != nil {\n\t\tfmt.Println(\"Failed to get redirect location\", err)\n\t} else if loc.Host != \"accounts.google.com\" {\n\t\tfmt.Println(\"Strange redirect location\", loc)\n\t} else {\n\t\tfmt.Println(\"Succeeded!\")\n\t}\n\n\t// Output: Succeeded!\n}", "func (auth *Manager) RegularAuth(minLevel int32, minSignees uint8, maxSignees uint8, service core.APIService) core.APIService {\n\n\t// this code is evaluated on startup, not during authentication\n\tif minLevel < 0 {\n\t\tpanic(\"auth.Wrapper: RegularAuth: minLevel must be gte 0\")\n\t}\n\n\treturn &wrapped{\n\t\tinfoService: service.InfoService,\n\t\tconfigService: func(ctx context.Context, config *v0.Config) (*v0.Response, error) {\n\n\t\t\tif uint8(len(config.Witness.Signatures)) < minSignees {\n\t\t\t\treturn response.MSG(\n\t\t\t\t\tv0.Code_BadRequest,\n\t\t\t\t\tfmt.Sprintf(\"at least %v signees are needed for this operation\", minSignees)), nil\n\t\t\t}\n\n\t\t\tif uint8(len(config.Witness.Signatures)) > maxSignees {\n\t\t\t\treturn response.MSG(\n\t\t\t\t\tv0.Code_BadRequest,\n\t\t\t\t\tfmt.Sprintf(\"no more than %v signees may be used for this operation\", minSignees)), nil\n\t\t\t}\n\n\t\t\tok, wrongSig, err := auth.Check(config)\n\t\t\tif err != nil {\n\t\t\t\treturn response.MSG(v0.Code_BadRequest, err.Error()), nil\n\t\t\t}\n\n\t\t\tif !ok {\n\t\t\t\treturn response.MSG(v0.Code_BadRequest, fmt.Sprintf(\"incorrect signature for: %s\", wrongSig)), nil\n\t\t\t}\n\n\t\t\thave, err := auth.HaveOwners(ctx, core.TXFromContext(ctx))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif !have {\n\t\t\t\treturn response.MSG(v0.Code_NotImplemented, \"An OwnerSet must first be provided\"), nil\n\t\t\t}\n\n\t\t\ttx := core.TXFromContext(ctx)\n\n\t\t\t// compute the total auth level\n\t\t\tvar totalAuthLevel int32\n\t\t\tfor _, user := range config.Witness.Signatures {\n\t\t\t\tuser, err := auth.Store.Users.Get(ctx, tx, user.GetPrimaryPublicKey())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn response.Err(err), nil\n\t\t\t\t}\n\t\t\t\ttotalAuthLevel += user.AuthLevel\n\t\t\t}\n\t\t\tif totalAuthLevel < minLevel {\n\t\t\t\treturn response.MSG(\n\t\t\t\t\tv0.Code_BadRequest,\n\t\t\t\t\tfmt.Sprintf(\"the minimum combined AuthLevel required for this operation is %v\", minLevel)), nil\n\t\t\t}\n\t\t\treturn service.ConfigService(ctx, config)\n\t\t},\n\t}\n\n}", "func isOIDCTokenAuth(req *http.Request) bool {\n\treturn req.URL.Path == \"/konnect/v1/token\"\n}", "func (a *API) Auth(ctx context.Context, request *AuthRequest) (*OkResponse, error) {\n\tvar err error\n\n\tif request.Ip == \"\" {\n\t\treturn nil, errors.New(\"ip is required for Auth method\")\n\t}\n\n\tip, err := entities.NewWithoutMaskPart(request.Ip)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar conform bool\n\n\t// if ip conform black list - no auth (even if ip conform white list)\n\tconform, err = a.isConformByBlackList(ctx, ip)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif conform {\n\t\treturn &OkResponse{Ok: false}, nil\n\t}\n\n\t// if ip conform white list - auth is ok\n\tconform, err = a.isConformByWhiteList(ctx, ip)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif conform {\n\t\treturn &OkResponse{Ok: true}, nil\n\t}\n\n\tconform, err = a.isConformByIPBucket(ctx, ip)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !conform {\n\t\treturn &OkResponse{Ok: false}, nil\n\t}\n\n\tconform, err = a.isConformByPasswordBucket(ctx, request.Password)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !conform {\n\t\treturn &OkResponse{Ok: false}, nil\n\t}\n\n\tconform, err = a.isConformByLoginBucket(ctx, request.Login)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &OkResponse{Ok: conform}, nil\n}", "func (s *Service) Auth(ctx context.Context, authConfig *registry.AuthConfig, userAgent string) (status, token string, err error) {\n\t// TODO Use ctx when searching for repositories\n\tregistryHostName := IndexHostname\n\n\tif authConfig.ServerAddress != \"\" {\n\t\tserverAddress := authConfig.ServerAddress\n\t\tif !strings.HasPrefix(serverAddress, \"https://\") && !strings.HasPrefix(serverAddress, \"http://\") {\n\t\t\tserverAddress = \"https://\" + serverAddress\n\t\t}\n\t\tu, err := url.Parse(serverAddress)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", invalidParamWrapf(err, \"unable to parse server address\")\n\t\t}\n\t\tregistryHostName = u.Host\n\t}\n\n\t// Lookup endpoints for authentication using \"LookupPushEndpoints\", which\n\t// excludes mirrors to prevent sending credentials of the upstream registry\n\t// to a mirror.\n\tendpoints, err := s.LookupPushEndpoints(registryHostName)\n\tif err != nil {\n\t\treturn \"\", \"\", invalidParam(err)\n\t}\n\n\tfor _, endpoint := range endpoints {\n\t\tstatus, token, err = loginV2(authConfig, endpoint, userAgent)\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t\tif errdefs.IsUnauthorized(err) {\n\t\t\t// Failed to authenticate; don't continue with (non-TLS) endpoints.\n\t\t\treturn status, token, err\n\t\t}\n\t\tlog.G(ctx).WithError(err).Infof(\"Error logging in to endpoint, trying next endpoint\")\n\t}\n\n\treturn \"\", \"\", err\n}", "func (c *APIController) AuthGoogle() {\n\tcode := c.Input().Get(\"code\")\n\tstate := c.Input().Get(\"state\")\n\taddition := c.Input().Get(\"addition\")\n\tRedirectURL := c.Input().Get(\"redirect_url\")\n\n\tvar resp Response\n\tvar res authResponse\n\tres.IsAuthenticated = true\n\n\tif state != beego.AppConfig.String(\"GoogleAuthState\") {\n\t\tres.IsAuthenticated = false\n\t\tresp = Response{Status: \"fail\", Msg: \"unauthorized\", Data: res}\n\t\tc.Data[\"json\"] = resp\n\t\tc.ServeJSON()\n\t\treturn\n\t}\n\n\tgoogleOauthConfig.RedirectURL = RedirectURL\n\n\t// https://github.com/golang/oauth2/issues/123#issuecomment-103715338\n\tctx := context.WithValue(oauth2.NoContext, oauth2.HTTPClient, httpClient)\n\ttoken, err := googleOauthConfig.Exchange(ctx, code)\n\tif err != nil {\n\t\tres.IsAuthenticated = false\n\t\tpanic(err)\n\t}\n\n\tresponse, err := httpClient.Get(\"https://www.googleapis.com/oauth2/v2/userinfo?alt=json&access_token=\" + token.AccessToken)\n\tdefer response.Body.Close()\n\tcontents, err := ioutil.ReadAll(response.Body)\n\n\tvar tempUser userInfoFromGoogle\n\terr = json.Unmarshal(contents, &tempUser)\n\tif err != nil {\n\t\tres.IsAuthenticated = false\n\t\tpanic(err)\n\t}\n\tres.Email = tempUser.Email\n\tres.Avatar = tempUser.Picture\n\n\tif addition == \"signup\" {\n\t\tuserId := object.HasGoogleAccount(res.Email)\n\t\tif userId != \"\" {\n\t\t\tif len(object.GetMemberAvatar(userId)) == 0 {\n\t\t\t\tavatar := UploadAvatarToOSS(res.Avatar, userId)\n\t\t\t\tobject.LinkMemberAccount(userId, \"avatar\", avatar)\n\t\t\t}\n\t\t\tc.SetSessionUser(userId)\n\t\t\tutil.LogInfo(c.Ctx, \"API: [%s] signed in\", userId)\n\t\t\tres.IsSignedUp = true\n\t\t} else {\n\t\t\tif userId := object.HasMail(res.Email); userId != \"\" {\n\t\t\t\tc.SetSessionUser(userId)\n\t\t\t\tutil.LogInfo(c.Ctx, \"API: [%s] signed in\", userId)\n\t\t\t\tres.IsSignedUp = true\n\t\t\t\t_ = object.LinkMemberAccount(userId, \"google_account\", tempUser.Email)\n\t\t\t} else {\n\t\t\t\tres.IsSignedUp = false\n\t\t\t}\n\t\t}\n\t\tres.Addition = res.Email\n\t\tresp = Response{Status: \"ok\", Msg: \"success\", Data: res}\n\t} else {\n\t\tmemberId := c.GetSessionUser()\n\t\tif memberId == \"\" {\n\t\t\tresp = Response{Status: \"fail\", Msg: \"no account exist\", Data: res}\n\t\t\tc.Data[\"json\"] = resp\n\t\t\tc.ServeJSON()\n\t\t\treturn\n\t\t}\n\t\tlinkRes := object.LinkMemberAccount(memberId, \"google_account\", res.Email)\n\t\tif linkRes {\n\t\t\tresp = Response{Status: \"ok\", Msg: \"success\", Data: linkRes}\n\t\t} else {\n\t\t\tresp = Response{Status: \"fail\", Msg: \"link account failed\", Data: linkRes}\n\t\t}\n\t\tif len(object.GetMemberAvatar(memberId)) == 0 {\n\t\t\tavatar := UploadAvatarToOSS(res.Avatar, memberId)\n\t\t\tobject.LinkMemberAccount(memberId, \"avatar\", avatar)\n\t\t}\n\t}\n\n\tc.Data[\"json\"] = resp\n\n\tc.ServeJSON()\n}", "func (s *Server) isAuthorized(ctx context.Context) (hash.Hash, error) {\n\tmd, ok := metadata.FromIncomingContext(ctx)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"credential not found in metadata, make sure to set it using the name %q\", CredentialToken)\n\t}\n\tif len(md[CredentialToken]) == 0 {\n\t\treturn nil, fmt.Errorf(\"credential not found in metadata, make sure to set it using the name %q\", CredentialToken)\n\t}\n\ttoken := md[CredentialToken][0]\n\trunnerHash, ok := s.tokenToRunnerHash.Load(token)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"credential token doesn't exist\")\n\t}\n\treturn runnerHash.(hash.Hash), nil\n}", "func RequiresAuth(token string) (bool, error) {\n\texists, err := TokenExists(token)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif exists {\n\t\tres, err := r.Table(\"tokens\").Filter(map[string]interface{}{\"Token\": token}).Run(session)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tvar transformToken modelToken.JWT\n\t\tres.One(&transformToken)\n\t\tres.Close()\n\n\t\tresu, err := r.Table(\"users\").Filter(map[string]interface{}{\"Name\": transformToken.Audience}).Run(session)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tvar user modelUser.User\n\t\tresu.One(&user)\n\t\tresu.Close()\n\n\t\tif transformToken.Expires <= time.Now().Unix() {\n\t\t\treturn true, nil\n\t\t}\n\t\tif transformToken.Expires > time.Now().Unix() {\n\t\t\tRevokeToken(&user)\n\t\t\treturn false, errors.New(\"Token has expired and been revoked.\")\n\t\t}\n\t}\n\treturn false, errors.New(\"The Token Does Not Exist\")\n}", "func isAuthorizationDataCorrect(authInf AuthInf, responseWriter http.ResponseWriter) bool {\n\tauthInf.Login = html.EscapeString(authInf.Login)\n\tauthInf.Password = GeneratePasswordHash(authInf.Password)\n\tvar count int\n\terr := src.Connection.QueryRow(\"SELECT COUNT(id) as count FROM users WHERE \" +\n\t\t\"login=? AND password=?\", authInf.Login, authInf.Password).Scan(&count)\n\tif err != nil {\n\t\treturn conf.ErrDatabaseQueryFailed.Print(responseWriter)\n\t}\n\tif count > 0 {\n\t\treturn true\n\t} else {\n\t\treturn conf.ErrAuthDataIncorrect.Print(responseWriter)\n\t}\n}", "func CheckAuth() gin.HandlerFunc {\n\treturn func(ctx *gin.Context) {\n\t\t_, err := seccookie.ReadSecureCookie(ctx, scookie)\n\t\tif err != nil {\n\t\t\tglog.Errorln(\"CHECK AUTH: not logged in\")\n\t\t}\n\t\tctx.Next()\n\t}\n}", "func Auth() gin.HandlerFunc {\r\n\tif gin.Mode() == \"debug\" {\r\n\t\treturn func(c *gin.Context) { c.Next() }\r\n\t}\r\n\treturn func(c *gin.Context) {\r\n\t\tAccessKey := c.GetHeader(\"AccessKey\")\r\n\t\tif c.GetHeader(\"AccessKey\") == \"\" {\r\n\t\t\tAccessKey = c.GetHeader(\"Token\")\r\n\t\t}\r\n\r\n\t\tsession := sessions.Default(c)\r\n\t\tLoginUserID := session.Get(\"UserID\")\r\n\t\tIsLeader := session.Get(\"IsLeader\")\r\n\r\n\t\tfmt.Println(\"AccessKey: \", AccessKey)\r\n\t\tswitch AccessKey {\r\n\t\tcase \"\":\r\n\t\t\tif LoginUserID != nil {\r\n\t\t\t\tc.Set(\"UserID\", LoginUserID)\r\n\t\t\t\tc.Set(\"IsLeader\", IsLeader)\r\n\t\t\t\tc.Next()\r\n\t\t\t} else {\r\n\t\t\t\tsession := sessions.Default(c)\r\n\t\t\t\tUserID := session.Get(\"UserID\")\r\n\t\t\t\tIsLeader := session.Get(\"IsLeader\")\r\n\r\n\t\t\t\tfmt.Println(\"UserID, IsLeader\", UserID, IsLeader)\r\n\t\t\t\tif UserID == nil {\r\n\t\t\t\t\tc.JSON(http.StatusUnauthorized, gin.H{\"message\": \"Empty AccessKey Please authorize before requesting\"})\r\n\t\t\t\t\tc.Abort()\r\n\t\t\t\t}\r\n\t\t\t\tc.Set(\"UserID\", UserID)\r\n\t\t\t\tc.Set(\"IsLeader\", IsLeader)\r\n\t\t\t\tc.Next()\r\n\r\n\t\t\t}\r\n\r\n\t\tdefault:\r\n\t\t\tUserID, IsLeader, err := utils.LoadAccessKey(AccessKey)\r\n\r\n\t\t\tif LoginUserID != nil {\r\n\t\t\t\tc.Set(\"UserID\", UserID)\r\n\t\t\t\tc.Set(\"IsLeader\", IsLeader)\r\n\t\t\t\tc.Next()\r\n\t\t\t} else {\r\n\t\t\t\tif err != nil {\r\n\t\t\t\t\tc.JSON(http.StatusUnauthorized, gin.H{\"message\": \"Please authorize before requesting\"})\r\n\t\t\t\t\tc.Abort()\r\n\t\t\t\t}\r\n\r\n\t\t\t\tc.Set(\"UserID\", UserID)\r\n\t\t\t\tc.Set(\"IsLeader\", IsLeader)\r\n\r\n\t\t\t\tc.Next()\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "func (rest *TestTokenStorageREST) TestRetrieveExternalTokenUnauthorized() {\n\trest.checkRetrieveExternalTokenUnauthorized(\"https://github.com/sbose78\", \"github\")\n\trest.checkRetrieveExternalTokenUnauthorized(\"github\", \"github\")\n\trest.checkRetrieveExternalTokenUnauthorized(\"https://api.starter-us-east-2.openshift.com\", \"openshift-v3\")\n\trest.checkRetrieveExternalTokenUnauthorized(\"openshift\", \"openshift-v3\")\n}", "func (g *GitHubImpl) Auth(user, pass string) (token string, err error) {\n\n\tperm, err := createGHPermissions()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq, _ := http.NewRequest(\"POST\", g.URLNoEsc(urls.authURL), bytes.NewBuffer([]byte(perm)))\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\treq.SetBasicAuth(user, pass)\n\n\tbody, err := NewPWRequest().Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tre := Auth{}\n\tif err = json.Unmarshal(body, &re); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn re.Token, nil\n}" ]
[ "0.64528763", "0.6141813", "0.60356563", "0.5977623", "0.5966018", "0.59558386", "0.5920924", "0.58737713", "0.585327", "0.58436126", "0.5831124", "0.5826388", "0.58148474", "0.579439", "0.57890946", "0.578735", "0.57012784", "0.5695301", "0.5692118", "0.5629942", "0.56271535", "0.5607494", "0.55882955", "0.5583518", "0.55435413", "0.55264115", "0.55093974", "0.55085516", "0.5506293", "0.5506063", "0.54651314", "0.54459435", "0.54277086", "0.54238236", "0.5409562", "0.54089934", "0.538176", "0.53601843", "0.5356227", "0.5350056", "0.53416246", "0.53406966", "0.5339781", "0.5335883", "0.5332351", "0.5325979", "0.5319842", "0.5316657", "0.5307756", "0.5306226", "0.53041697", "0.52996933", "0.5295218", "0.5291385", "0.5283986", "0.52819866", "0.52806944", "0.5277598", "0.52732044", "0.5270561", "0.5263275", "0.5258707", "0.5247628", "0.52413857", "0.5236602", "0.5232788", "0.5225826", "0.52232015", "0.5207717", "0.52069813", "0.52009773", "0.5195331", "0.5191238", "0.5189629", "0.5189171", "0.518268", "0.5182379", "0.51698154", "0.5169802", "0.5169802", "0.51672935", "0.5156156", "0.5152982", "0.5148291", "0.51443493", "0.5143532", "0.5142667", "0.51303786", "0.5128201", "0.5126391", "0.5123279", "0.5120157", "0.51159006", "0.5115158", "0.51041394", "0.51033574", "0.50943804", "0.5090536", "0.5087091", "0.50794154" ]
0.71946776
0
get user by id
func (u *UserDAO) Get(id int) User { stmt, err := db.Instance().Prepare("select uid, username, password from userinfo where uid=$1") db.CheckErr(err) rows, err := stmt.Query(id) var usr User for rows.Next() { var uid int var username string var password string err = rows.Scan(&uid, &username, &password) db.CheckErr(err) usr.Id = uid usr.Name = username usr.Pwd = password } return usr }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getUserById(id int) (User, error) {\n\tkeyString := fmt.Sprintf(\"user:%d\", id)\n\tfirstName, _ := redisConn.Hget(keyString, \"firstName\")\n\tlastName, _ := redisConn.Hget(keyString, \"lastName\")\n\temail, _ := redisConn.Hget(keyString, \"email\")\n\tuser := User{id, string(firstName), string(lastName), string(email)}\n\n\tmongoUser := User{}\n\tc := mongoClient.DB(\"cg\").C(\"users\")\n\terr := c.Find(bson.M{\"id\": id}).One(&mongoUser)\n\tif err != nil {\n\t\tlog.Printf(\"couldn't find user: \", err)\n\t} else {\n\t\tlog.Printf(\"mongo user: %v\", mongoUser)\n\t}\n\n\treturn user, nil\n}", "func (us *Users) Get(id int64) (*User, error) {\n\texp := fmt.Sprintf(\"user_id=%v\", id)\n\n\treturn getUserWhere(exp)\n}", "func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id int64) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (u *UserCtr) GetUserByid(c *gin.Context) {\n\tid,err := strconv.Atoi(c.Param(\"id\"))\n\tif err != nil {\n\t\tresp := errors.New(err.Error())\n\t\tc.JSON(http.StatusInternalServerError, resp)\n\t\treturn\n\t}\n\n\tuser, err := model.UserByID(u.DB,id)\n\tif err != nil {\n\t\tresp := errors.New(err.Error())\n\t\tc.JSON(http.StatusInternalServerError, resp)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"result\": user,\n\t})\n\treturn\n\n}", "func (u *User) Get(id string) error {\n\tsession := mongoSession.Clone()\n\tdefer session.Close()\n\tcollection := session.DB(mongoDialInfo.Database).C(usersCollectionName)\n\t// TODO: handle error\n\tif !bson.IsObjectIdHex(id) {\n\t\treturn errors.New(\"Invalid Object ID\")\n\t}\n\tobjectID := bson.ObjectIdHex(id)\n\terr := collection.FindId(objectID).One(u)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (_ *User) GetById(id uint) (interface{}, error) {\n\tuser := User{}\n\tif disableGetUserById || getTestDb().Where(\"id = ?\", id).Find(&user).RecordNotFound() {\n\t\treturn &user, errors.New(\"User not found\")\n\t}\n\treturn &user, nil\n}", "func (c *UserClient) Get(ctx context.Context, id uuid.UUID) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id uuid.UUID) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func GetUser(id int) (components.User, error) {\n\treturn getUser(id)\n}", "func (c *Client) GetUser(id string) (*dto.User, error) {\n\tvar user *dto.User\n\n\tr, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"users/%s\", id),\n\t\tnil,\n\t)\n\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\t_, err = c.Do(r, &user)\n\treturn user, err\n}", "func (uc UserController) getSingleUserbyID(response http.ResponseWriter, request *http.Request, parameters httprouter.Params) {\n\tresponse.Header().Add(\"content-type\", \"application/json\")\n\tid_string := parameters.ByName(\"id\")\n\n\tid, _ := primitive.ObjectIDFromHex(id_string)\n\tvar user Users\n\tctx, _ := context.WithTimeout(context.Background(), 10*time.Second)\n\terr := uc.collection.FindOne(ctx, bson.M{\"_id\": id}).Decode(&user)\n\tif err != nil {\n\t\tresponse.WriteHeader(http.StatusInternalServerError)\n\t\tresponse.Write([]byte(`{\"message: \"` + err.Error() + `\"}\"`))\n\t\treturn\n\t}\n\t// Decrypting the password\n\t// password := []byte(user.Password)\n\t// key := []byte(\"This is a key for the very secret password\")\n\t// password, _ = decrypt(key, password)\n\t// user.Password = string(password)\n\t//\n\tjson.NewEncoder(response).Encode(user)\n}", "func (u *User) GetById(id interface{}) error {\n\tif err := DB().Where(\"id = ?\", id).First(&u).Error; err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (u *UserModel) GetUserById(id uint64) (*UserModel, error) {\n\td := DB.Self.Where(\"id = ?\", id).First(&u)\n\tfmt.Println(\"GetUser-d\", d)\n\treturn u, d.Error\n}", "func GetUserById(id int) (v *User, err error) {\n\to := orm.NewOrm()\n\tv = &User{Id: id}\n\tif err = o.Read(v); err == nil {\n\t\treturn v, nil\n\t}\n\treturn nil, err\n}", "func (s UserStorage) GetOne(id string) (model.User, error) {\n\tintID, err := strconv.ParseInt(id, 10, 64)\n\tif err != nil {\n\t\terrMessage := fmt.Sprintf(\"User id must be an integer: %s\", id)\n\t\treturn model.User{}, api2go.NewHTTPError(errors.New(errMessage), errMessage, http.StatusBadRequest)\n\t}\n\tvar user model.User\n\tstr := []string{GET_ALL, \"where users.user_id = $1 limit 1\"}\n\tGET_ONE := strings.Join(str, \" \")\n\terror := s.db.SelectOne(&user, GET_ONE, intID)\n\tif error == nil {\n\t\treturn user, nil\n\t} else {\n\t\treturn model.User{}, fmt.Errorf(\"User for id %s not found\", id)\n\t}\t\n\t// return s.getOneWithAssociations(intID)\n}", "func (u *MyUserModel) GetById(id interface{}) error {\n\terr := dbmap.SelectOne(u, \"SELECT * FROM users WHERE id = $1\", id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func GetUser(id int) (User, error) {\n\tvar user User\n\trow := DB.QueryRow(\"select id, realname, username, email from users where id = $1\", id)\n\terr := row.Scan(&user.ID, &user.Realname, &user.Username, &user.Email)\n\treturn user, err\n}", "func GetUserByID(c *gin.Context) {\n\tid := c.Params.ByName(\"id\")\n\tvar user models.User\n\terr := models.GetUserByID(&user, id)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, user)\n\t}\n}", "func GetUserByID(id int64) *User {\n\tuser := new(User)\n\trow := DB.QueryRow(\"SELECT * from user WHERE id=?\", id)\n\terr := row.Scan(&user.ID, &user.Email, &user.Password, &user.Fullname, &user.TSLastLogin, &user.TSCreate, &user.TSUpdate, &user.Permission)\n\tif err != nil {\n\t\tlog.Errorln(\"User SELECT by ID Err: \", err)\n\t\treturn nil\n\t}\n\treturn user\n}", "func (u *UserService) GetUser(id string) (*User, error) {\n\tuser := &User{}\n\terr := u.QueryRow(\"SELECT id, name, phone, email, password FROM users WHERE id=$1 LIMIT 1\", id).Scan(&user.ID, &user.Name, &user.Phone, &user.Email, &user.HashedPassword)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn user, nil\n}", "func (m *manager) Get(ctx context.Context, id int) (*models.User, error) {\n\tusers, err := m.dao.List(ctx, q.New(q.KeyWords{\"user_id\": id}))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(users) == 0 {\n\t\treturn nil, errors.NotFoundError(nil).WithMessage(\"user %d not found\", id)\n\t}\n\n\treturn users[0], nil\n}", "func (rep *UserRepo) Get(ctx context.Context, id string) (*User, error) {\n\tu := &User{}\n\terr := rep.db.Query(\n\t\tctx,\n\t\trep.db.Select(\"*\").From(rep.table()).Where(\"id = ?\", id),\n\t).Decode(u)\n\treturn u, err\n}", "func (c Client) GetUser(ctx context.Context, id string) (api.User, error) {\n\t// TODO (erik): Make this function handle emails properly.\n\tvar user api.User\n\tif err := c.db.GetContext(ctx, &user, \"select * from users where id = ?\", id); err != nil {\n\t\treturn user, err\n\t}\n\n\treturn user, nil\n}", "func (c *Client) GetUser(ctx context.Context, id string) (*UserResponse, error) {\n\tvar resp struct {\n\t\tUser UserResponse `json:\"user\"`\n\t}\n\n\tvariables := make(map[string]interface{})\n\tvariables[\"id\"] = id\n\n\terr := c.transport.Raw(ctx, `\n\t\tquery User($id: String!) {\n\t\t\tuser(id: $id) {\n\t\t\t\tid\n\t\t\t\tname\n\t\t\t\temail\n\t\t\t\trole {\n\t\t\t\t\tid\n\t\t\t\t\tlabel\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t`, variables, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &resp.User, nil\n}", "func Get(id int64) (User, error) {\n\tvar u User\n\tstmt, err := db.Prepare(\"select id, name, age, created from user where id = ? \")\n\tdefer stmt.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn u, err\n\t}\n\terr = stmt.QueryRow(id).Scan(&u.ID, &u.Name, &u.Age, &u.Created)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn u, err\n\t}\n\treturn u, nil\n}", "func GetUserById(context *fiber.Ctx) error {\n\tid, err := ParseId(context)\n\n\tif err != nil {\n\t\treturn context.Status(400).JSON(&fiber.Map{\"error\": err.Error()})\n\t}\n\n\tvar user = repository.GetUserById(id)\n\n\tif user.ID == 0 {\n\t\tlog.Printf(\"user not found: %d\", id)\n\t\treturn context.Status(404).JSON(&fiber.Map{\"response\": \"not found\"})\n\t} else {\n\t\treturn context.Status(200).JSON(user)\n\t}\n}", "func (m *postgresDBRepo) GetUserById(id int) (models.User, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\tquery := `select id, first_name, last_name, email, password,\n\t\t access_level, created_at, updated_at\n\t\tfrom users where id = $1`\n\n\trow := m.DB.QueryRowContext(ctx, query, id)\n\tvar u models.User\n\terr := row.Scan(&u.ID, &u.FirstName, &u.LastName, &u.Email, &u.Password, &u.AccessLevel, &u.CreatedAt, &u.UpdatedAt)\n\tif err != nil {\n\t\treturn u, err\n\t}\n\n\treturn u, nil\n}", "func (repo *UserRepository) GetById(id string) (*dto.User, error) {\n\tselectStatement := \"SELECT * FROM `users` WHERE id = ?\"\n\tuser := &dto.User{}\n\tif err := repo.db.Get(user, selectStatement, id); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn user, nil\n}", "func (s *usersService) GetByID(id int) (User, error) {\n\tusr, err := s.repo.GetById(id)\n\tif err != nil {\n\t\tlog.Printf(\"error getting user: %s\\n\", err)\n\t\treturn User{}, err\n\t}\n\treturn usr, nil\n}", "func GetByID(id uint64) (*User, error) {\n\treturn getBy(\"id\", strconv.FormatUint(id, 10))\n}", "func GetUserById(id int, db *gorm.DB) (user User, err error) {\n\tuser.ID = id\n\tif err = db.First(&user).Error; err != nil {\n\t\terr = ErrUserNotFound\n\t}\n\treturn\n}", "func GetByID(w http.ResponseWriter, r *http.Request, DB *gorm.DB) {\n\tvar dbUser User\n\tparams := mux.Vars(r)\n\tuserID := params[\"id\"]\n\t//Need to make sure that the user that is requesting user info is either the user or an admin user\n\ttoken := r.Header.Get(\"Authorization\")\n\tresult, ID := utils.VerifyJWT(token)\n\tmyID := strconv.FormatUint(uint64(ID), 10)\n\t//results := utils.IsAdmin(token, DB)\n\t//fmt.Printf(\"%v\", results)\n\tif (result && userID == myID) || isAdmin(token, DB) {\n\t\tDB.Where(\"ID = ?\", userID).First(&dbUser)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tjson.NewEncoder(w).Encode(dbUser)\n\t} else {\n\t\tnotauthorizedResponse := response.JsonResponse(\"Not authorized\", 409)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tjson.NewEncoder(w).Encode(notauthorizedResponse)\n\t}\n\n}", "func (c *UsersClient) Get(ctx context.Context, id string) (*models.User, int, error) {\n\tresp, status, _, err := c.BaseClient.Get(ctx, base.GetHttpRequestInput{\n\t\tValidStatusCodes: []int{http.StatusOK},\n\t\tUri: base.Uri{\n\t\t\tEntity: fmt.Sprintf(\"/users/%s\", id),\n\t\t\tHasTenantId: true,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, status, err\n\t}\n\tdefer resp.Body.Close()\n\trespBody, _ := ioutil.ReadAll(resp.Body)\n\tvar user models.User\n\tif err := json.Unmarshal(respBody, &user); err != nil {\n\t\treturn nil, status, err\n\t}\n\treturn &user, status, nil\n}", "func (dao *UserDAO) Get(id uint) (*models.User, error) {\n\tvar user models.User\n\n\terr := config.Config.DB.Where(\"id = ?\", id).First(&user).Error\n\n\treturn &user, err\n}", "func (u *usecase) Get(ctx context.Context, id string) (*User, error) {\n\tuser, err := u.repository.Get(ctx, id)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error fetching a single user\")\n\t}\n\treturn user, nil\n}", "func GetUserByID(c *gin.Context) {\n\tid := c.Params.ByName(\"id\")\n\tvar user Models.User\n\terr := Models.GetUserByID(&user, id)\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\" : gin.H { \n\t\t\t\"status\": http.StatusNotFound,\n\t\t\t\"message\": err.Error(),\n\t\t}})\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK,gin.H{\n\t\t\t\"data\" : user,\n\t\t\t\"status\": http.StatusOK,\n\t\t})\n\t}\n}", "func (c *Client) GetUserByID(id string) (User, error) {\n\tvar (\n\t\turi = \"/rest/users/\" + id\n\t\tqueryParams = createQuery(&map[string]string{\n\t\t\t\"id\": id,\n\t\t})\n\t\tuser User\n\t)\n\n\tif id == \"\" {\n\t\treturn user, fmt.Errorf(\"id must not be empty\")\n\t}\n\n\tresponse, err := c.RestAPICall(rest.GET, uri, queryParams, nil)\n\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\tif err := json.Unmarshal([]byte(response), &user); err != nil {\n\t\treturn user, apiResponseError(response, err)\n\t}\n\n\treturn user, err\n}", "func (u *USER_DB) GetById(id interface{}) error {\n\terr := dbmap.SelectOne(u, \"SELECT * FROM USER WHERE Idx = ?\", id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func GetUser(id int64) (*User, error) {\n\tuser := User{}\n\terr := meddler.QueryRow(db, &user, userFindIdStmt, id)\n\treturn &user, err\n}", "func (p *Postgres) GetByID(id int) (*e.User, error) {\n\tdb := p.DB\n\tuser := e.User{}\n\n\terr := db.Model(&user).Where(\"id = ?\", id).Select()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &user, nil\n}", "func (u *User) GetUser(id int) error {\n\tconn, err := db.Connect()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tsql := `SELECT id,username,password,name,is_admin FROM users WHERE id = $1 LIMIT 1`\n\trow := conn.QueryRow(sql, id)\n\n\terr = row.Scan(&u.ID, &u.Username, &u.Password, &u.Name, &u.IsAdmin)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func GetUser(id int) (*User, error) {\n\tuser := new(User)\n\terr := db.Model(user).Where(\"id = ?\", id).Select()\n\treturn user, err\n}", "func UserByIDGet(c *gin.Context) {\n\tid, _ := strconv.ParseInt(c.Param(\"id\"), 10, 64)\n\tlog.Info(\"UserByIDGet \", id)\n\tm := model.UserByID(uint(id))\n\tginutils.WriteGinJSON(c, http.StatusOK, m)\n}", "func (u *userService) Get(id string) (*domain.User, error) {\n\treturn u.storage.Get(id)\n}", "func (db *Database) GetUser(id int) (*User, error) {\n\trow := db.db.QueryRow(`\n\t\tSELECT id, username, owner FROM melodious.accounts WHERE id=$1;\n\t`, id)\n\tuser := &User{}\n\terr := row.Scan(&(user.ID), &(user.Username), &(user.Owner))\n\tif err != nil {\n\t\treturn &User{}, err\n\t}\n\treturn user, nil\n}", "func (u *User) GetUserByID(id string) *User {\n\tvar result User\n\n\terr := database.DB.Where(\"id = ?\", id).First(&result).Error\n\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn &result\n}", "func GetUserByID(c *gin.Context, client *statsd.Client) {\n\tlog.Info(\"getting user by id\")\n\tid := c.Params.ByName(\"id\")\n\tvar user entity.User\n\terr := model.GetUserByID(&user, id, client)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"id\": user.ID,\n\t\t\t\"first_name\": user.FirstName,\n\t\t\t\"last_name\": user.LastName,\n\t\t\t\"username\": user.Username,\n\t\t\t\"account_created\": user.AccountCreated,\n\t\t\t\"account_updated\": user.AccountUpdated,\n\t\t})\n\t}\n}", "func (u *UserModel) Get(id int) (*models.User, error) {\n\tstmt := `SELECT u.id, u.uuid, u.first_name, u.last_name, u.email, u.phone, s.slug, u.created\n\t\t\t FROM user AS u\n\t\t LEFT JOIN ref_user_status AS s ON u.status_id = s.id\n\t\t\t WHERE u.id = ?`\n\n\tuser := &models.User{}\n\terr := u.DB.QueryRow(stmt, id).Scan(&user.ID, &user.UUID, &user.FirstName, &user.LastName, &user.Email, &user.Phone, &user.Status, &user.Created)\n\n\tif err == sql.ErrNoRows {\n\t\treturn nil, models.ErrNoRecord\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn user, nil\n}", "func GetUserById(id string) (Contact, error) {\n\tvar usr Contact\n\tfor r := 0; r < len(Users); r++ {\n\t\tif id == Users[r].ID {\n\t\t\tusr = Users[r]\n\t\t} else {\n\t\t\treturn Contact{}, errors.New(\"user not found\")\n\t\t}\n\t}\n\treturn usr, nil\n}", "func (s *UsersService) GetByID(id string) (*User, *Response, error) {\n\tu := fmt.Sprintf(\"users/%v\", id)\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tuser := new(User)\n\tresp, err := s.client.Do(req, user)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn user, resp, err\n}", "func GetUserByID(id int, engine *xorm.Engine) (*User, error) {\n\n\tuser := new(User)\n\tok, err := engine.Where(\"id=?\", id).Get(user)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif ok {\n\t\treturn user, nil\n\t}\n\treturn nil, fmt.Errorf(\"user (%d) not exist\", id)\n}", "func (d *DB) GetUser(id int) (User, error) {\n\tvar user User\n\terr := d.db.Find(&user, id).Error\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\treturn user, nil\n}", "func (dbh *DBHandler) GetUserByID(id int) *api.User {\n\tvar user *api.User\n\tresult, err := dbh.Connection.Query(`SELECT * FROM users WHERE telegram_id = ?;`, id)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer result.Close()\n\tif result.Next() {\n\t\terr := result.Scan(&user.ID, &user.Username)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tuser = &api.User{}\n\t\t}\n\t}\n\treturn user\n}", "func (prof *Profiles) ByID(id_ interface{}) (*User, error) {\n\tvar id string\n\tswitch x := id_.(type) {\n\tcase int64:\n\t\tid = fmt.Sprintf(\"%d\", x)\n\tcase int:\n\t\tid = fmt.Sprintf(\"%d\", x)\n\tcase string:\n\t\tid = x\n\tdefault:\n\t\treturn nil, errors.New(\"Invalid id, please provide a string or int(64)\")\n\t}\n\n\tbody, _, err := prof.insta.sendRequest(\n\t\t&reqOptions{\n\t\t\tEndpoint: fmt.Sprintf(urlUserByID, id),\n\t\t},\n\t)\n\tif err == nil {\n\t\tresp := userResp{}\n\t\terr = json.Unmarshal(body, &resp)\n\t\tif err == nil {\n\t\t\tuser := &resp.User\n\t\t\tuser.insta = prof.insta\n\t\t\treturn user, err\n\t\t}\n\t}\n\treturn nil, err\n}", "func GetUserByID(user *models.User, id uint) (err error) {\n\tif err = config.DB.Where(\"id = ?\", id).First(user).Error; err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (model *UserModel) Get(id int) (*models.User, error) {\n\tuser := &models.User{}\n\tstmt := `SELECT id, name, email, created, active FROM users WHERE id = ?`\n\terr := model.DB.QueryRow(stmt, id).Scan(&user.ID, &user.Name, &user.Email, &user.Created, &user.Active)\n\tif err != nil {\n\t\tif errors.Is(err, sql.ErrNoRows) {\n\t\t\treturn nil, models.ErrNoRecord\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn user, nil\n}", "func (s *Store) GetUser(id bson.ObjectId) (*models.User, error) {\n\tvar user models.User\n\terr := s.Users.Find(bson.M{\"_id\": id}).One(&user)\n\treturn &user, err\n}", "func (u *UserModel) Get(id int) (*models.User, error) {\n\tusr := &models.User{}\n\n\tstmt := `SELECT id, name, email, created, active FROM users WHERE id = ?`\n\terr := u.DB.QueryRow(stmt, id).Scan(&usr.ID, &usr.Name, &usr.Email, &usr.Created, &usr.Active)\n\tif err != nil {\n\t\tif errors.Is(err, sql.ErrNoRows) {\n\t\t\treturn nil, models.ErrNoRecord\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn usr, nil\n}", "func (ss *SQLStore) GetByID(id int64) (*User, error) {\n\trows, err := ss.db.Query(\"select id, Email, PassHash, UserName, FirstName, LastName, PhotoURL from USERS\")\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to query.\")\n\t}\n\n\tdefer rows.Close()\n\n\tusers := User{}\n\n\tfor rows.Next() {\n\t\t// Scans row into users struct.\n\t\tif err := rows.Scan(&users.ID, &users.Email,\n\t\t\t&users.PassHash, &users.UserName, &users.FirstName,\n\t\t\t&users.LastName, &users.PhotoURL); err != nil {\n\t\t\treturn nil, errors.New(\"Error scanning row.\")\n\t\t}\n\n\t\t// checks the ID, and if it matches, return that user.\n\t\tif users.ID == id {\n\t\t\treturn &users, nil\n\t\t}\n\t}\n\n\treturn nil, errors.New(\"User with ID not found.\")\n}", "func (mss *MySQLStore) GetByID(id int64) (*User, error) {\n\tuser := &User{}\n\trow := mss.Client.QueryRow(\"select * from users where user_id=?\", id)\n\tif err := row.Scan(&user.ID, &user.Email, &user.PassHash, &user.UserName,\n\t\t&user.FirstName, &user.LastName); err != nil {\n\t\treturn nil, err\n\t}\n\treturn user, nil\n}", "func (s *Service) GetByID(id int) (*User, error) {\n\t// Try to pull this User from the database.\n\tdbm, err := s.db.Users.GetByID(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a new User.\n\tuser := &User{\n\t\tID: dbm.ID,\n\t\tEmail: dbm.Email,\n\t\tPassword: dbm.Password,\n\t}\n\n\treturn user, nil\n}", "func (s User) GetByID(id string) (User, error) {\n\tvar (\n\t\tuser User\n\t\terr error\n\t)\n\n\ttx := gorm.MysqlConn().Begin()\n\tif err = tx.Find(&user, \"id = ?\", id).Error; err != nil {\n\t\ttx.Rollback()\n\t\treturn user, err\n\t}\n\ttx.Commit()\n\n\treturn user, err\n}", "func GetUserByID(c *gin.Context) {\n\tvar user, condition Users\n\n\tuserID, _ := strconv.ParseUint(c.Param(\"id\"), 10, 64)\n\tcondition.ID = uint(userID)\n\tuser.FindOne(condition)\n\n\tif user.ID == 0 {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"status\": http.StatusOK,\n\t\t\t\"message\": \"user is not found\",\n\t\t})\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"status\": http.StatusOK,\n\t\t\t\"data\": user,\n\t\t})\n\t}\n}", "func (rep *UserRepository) GetByID(userID int64) (user *models.User, err error) {\n\tuser = &models.User{}\n\terr = databaseConnection.First(user, \"id = ?\", userID).Error\n\treturn\n}", "func GetUserByID(c *gin.Context) {\n\tuser, err := getUserFromParams(c)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, user)\n\t}\n}", "func GetUser(id bson.ObjectId) User {\n\tsession, _ := mgo.Dial(\"127.0.0.1\")\n\tdefer session.Close()\n\tsession.SetMode(mgo.Monotonic, true)\n\tdb := session.DB(\"reimburse-me\").C(\"user\")\n\tvar result User\n\tdb.FindId(id).One(&result)\n\tresult.Token = \"\"\n\treturn result\n}", "func (u UserRepository) GetByID(id int) (interface{}, error) {\n\n\tvar sqlStm = `\n\t\tSELECT\ta.id, \n\t\t\t\ta.firstname, \n\t\t\t\ta.lastname, \n\t\t\t\ta.username, \n\t\t\t\ta.email, \n\t\t\t\ta.password, \n\t\t\t\ta.timestamp, \n\t\t\t\ta.updated \n\t\tFROM reservations_user a\n\t\tWHERE a.id = $1`\n\n\tvar user models.UserModel\n\n\tif err := u.DB.QueryRow(\n\t\tsqlStm,\n\t\tid,\n\t).Scan(\n\t\t&user.ID,\n\t\t&user.FirstName,\n\t\t&user.LastName,\n\t\t&user.UserName,\n\t\t&user.Email,\n\t\t&user.Password,\n\t\t&user.Timestamp,\n\t\t&user.Updated,\n\t); err != nil {\n\t\treturn nil, fmt.Errorf(\"%s\", err)\n\t}\n\n\treturn user, nil\n}", "func UserGet(db *sql.DB, id string) (User, error) {\n\tuser := User{}\n\terr := db.QueryRow(`\n\tSELECT id, email, password FROM \"user\" WHERE id=$1\n\t`, id).Scan(&user.ID, &user.Email, &user.Password)\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\treturn user, nil\n}", "func (db *DB) GetUser(id string) (*model.User, error) {\n\tvar user model.User\n\n\tcursor := db.collections.users.FindOne(\n\t\tcontext.Background(),\n\t\tbson.D{primitive.E{\n\t\t\tKey: \"_id\",\n\t\t\tValue: id,\n\t\t}},\n\t)\n\n\tif cursor.Err() != nil {\n\t\treturn nil, cursor.Err()\n\t}\n\n\terr := cursor.Decode(&user)\n\tif err != nil {\n\t\tif err == mongo.ErrNoDocuments {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn &user, nil\n}", "func (s *UsersService) Get(id string) (*User, *http.Response, error) {\n\turi := fmt.Sprintf(\"users/%v\", id)\n\n\tuser := new(User)\n\tres, err := s.client.Get(uri, user)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\n\treturn user, res, err\n}", "func (m *UserModel) GetByID(id string) (User, error) {\n\tvar user User\n\terr := m.db.Where(\"id = ?\", id).First(&user).Error\n\n\treturn user, err\n}", "func GetUserByID(id uint) (models.User, error) {\n\tvar u models.User\n\tresult := database.GetPostgresDB().First(&u, id)\n\tif result.Error != nil {\n\t\treturn models.User{}, result.Error\n\t}\n\treturn u, nil\n}", "func UserById(id int, fillAttributes bool) (u *UserModel, err error) {\n\tu, err = getUser(\"where id = $1\", id, true, fillAttributes)\n\treturn\n}", "func (self *UserManager) FindById(id interface{}) *models.User {\n\tdb := self.db\n\tuser := new(models.User)\n\tstmt, err := db.Prepare(\"SELECT * FROM users WHERE id = ?\")\n\tutils.CheckErr(err, nil)\n\terr = stmt.QueryRow(id).Scan(&user.Id, &user.FullName, &user.Address, &user.Phone, &user.Email, &user.Password, &user.Hash, &user.IsActive, &user.Token)\n\n\tif err != nil && err != sql.ErrNoRows {\n\t\tutils.CheckErr(err, nil)\n\t}\n\n\tif err == sql.ErrNoRows {\n\t\treturn nil\n\t} else {\n\t\treturn user\n\t}\n}", "func (s *Service) GetUser(id bson.ObjectId) (User, error) {\n\tsession := s.db.Copy()\n\tdefer session.Close()\n\n\tc := session.DB(\"\").C(userCollection)\n\tvar user User\n\terr := c.FindId(id).One(&user)\n\tif err != nil {\n\t\treturn user, fmt.Errorf(\"user not found: %v\", err)\n\t}\n\n\treturn user, nil\n}", "func (dao *UserDAO) Get(id uint) (*models.User, error) {\n\tvar user models.User\n\n\t// Query Database here...\n\n\t//user = models.User{\n\t//\tModel: models.Model{ID: 1},\n\t//\tFirstName: \"Martin\",\n\t//\tLastName: \"Heinz\",\n\t//\tAddress: \"Not gonna tell you\",\n\t//\tEmail: \"[email protected]\"}\n\n\t// if using Gorm:\n\terr := config.Config.DB.Where(\"id = ?\", id).\n\t\tFirst(&user).\n\t\tError\n\n\treturn &user, err\n}", "func (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {\n\tid, err := strconv.Atoi(r.URL.Query().Get(\"id\"))\n\tif err != nil {\n\t\trender.BadRequest(w, r, \"id must be an integer greater zero\")\n\t\treturn\n\t}\n\n\t// Query user details from userID\n\tuser, err := h.Client.User.\n\t\tQuery().\n\t\tWhere(usr.ID(id)).\n\t\tOnly(r.Context())\n\tif err != nil {\n\t\tswitch {\n\t\tcase ent.IsNotFound(err):\n\t\t\trender.NotFound(w, r, \"Email Doesn't exists\")\n\t\tdefault:\n\t\t\trender.InternalServerError(w, r, \"Server Error\")\n\t\t}\n\t\treturn\n\t}\n\trender.OK(w, r, user)\n}", "func GetOne(id int) (user model.User, err error) {\n\n\tuser, err = dao.GetOne(id) // 直接调dao了\n\tif err != nil {\n\t\treturn user, fmt.Errorf(\"GetOne in service Fail: %w\", err) // wrap\n\t}\n\treturn user, err\n}", "func GetUser(db sqlx.Queryer, id int64) (User, error) {\n\tvar user User\n\terr := sqlx.Get(db, &user, \"select \"+externalUserFields+\" from \\\"user\\\" where id = $1\", id)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn user, ErrDoesNotExist\n\t\t}\n\t\treturn user, errors.Wrap(err, \"select error\")\n\t}\n\n\treturn user, nil\n}", "func GetUserByID(id int) (*UserByID, error) {\n\tres := &UserByID{}\n\terr := urlToStruct(fmt.Sprintf(\"/users/userbyid/%d\", id), res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}", "func (m *mysqlUserRepository) GetByID(id int64) (res domain.User, err error) {\n\tquery := `SELECT id, name, email, updated_at, created_at, deleted_at\n\t\t\t\tFROM user WHERE ID = ?`\n\n\tlist, err := m.fetch(query, id)\n\tif err != nil {\n\t\treturn domain.User{}, nil\n\t}\n\n\tif len(list) > 0 {\n\t\tres = list[0]\n\t} else {\n\t\treturn res, domain.ErrNotFound\n\t}\n\n\treturn\n}", "func (app *App) getUser(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tid, err := strconv.Atoi(vars[\"id\"])\n\tif err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tuser := &users.User{ID: int64(id)}\n\tuser, err = user.GetUser(app.Db)\n\tif err != nil {\n\t\trespondWithError(w, http.StatusNotFound, err.Error())\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\trespondWithJSON(w, http.StatusOK, user)\n}", "func GetUser(id string) (User, error) {\n\tresult := User{}\n\terr := db.QueryRow(\"SELECT * FROM web_users WHERE ID = ?\", id).Scan(&result.ID, &result.Username,\n\t\t&result.RegisteredOn, &result.LastLogin, &result.AvatarURL, &result.AccessToken, &result.RefreshToken,\n\t\t&result.AccessExpiration)\n\tif err != nil {\n\t\treturn User{}, err\n\t}\n\n\treturn result, nil\n}", "func (store *MySQLStore) GetByID(id int64) (*User, error) {\n\tquery := \"SELECT * FROM users WHERE id = ?\"\n\tuser := &User{}\n\terr := store.db.QueryRow(query, id).Scan(&user.ID, &user.Email, &user.FirstName, &user.LastName, &user.PassHash,\n\t\t&user.UserName, &user.PhotoURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn user, nil\n}", "func (s *UserService) Get(id string) (*User, *Response, error) {\n\n\turl := fmt.Sprintf(\"Users/%s)\", id)\n\n\treq, err := s.client.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresource := new(User)\n\tresp, err := s.client.Do(req, &resource)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn resource, resp, err\n}", "func GetUser(tx *sql.Tx, id int64) (*User, error) {\n\tu := User{}\n\treturn &u, tx.QueryRow(\n\t\t\"select id, name, password_hash from users where id = $1\",\n\t\tid,\n\t).Scan(\n\t\t&u.ID,\n\t\t&u.Name,\n\t\t&u.PasswordHash,\n\t)\n}", "func (retUser) One(ctx context.Context, claims auth.Claims, db *sqlx.DB, id string) (*User, error) {\n\tctx, span := global.Tracer(\"service\").Start(ctx, \"internal.data.retrieve.user.one\")\n\tdefer span.End()\n\n\tif _, err := uuid.Parse(id); err != nil {\n\t\treturn nil, ErrInvalidID\n\t}\n\n\t// If you are not an admin and looking to retrieve someone else then you are rejected.\n\tif !claims.HasRole(auth.RoleAdmin) && claims.Subject != id {\n\t\treturn nil, ErrForbidden\n\t}\n\n\tvar u User\n\tconst q = `SELECT * FROM users WHERE user_id = $1`\n\tif err := db.GetContext(ctx, &u, q, id); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, ErrNotFound\n\t\t}\n\n\t\treturn nil, errors.Wrapf(err, \"selecting user %q\", id)\n\t}\n\n\treturn &u, nil\n}", "func (r *Repo) GetUser(_ context.Context, id int64) (entities.User, error) {\n\tvar u entities.User\n\terr := r.Get(&u, \"SELECT * FROM users WHERE id = $1\", id)\n\tif err != nil {\n\t\treturn entities.User{}, fmt.Errorf(\"error getting user: %w\", err)\n\t}\n\treturn u, nil\n}", "func (us *UserService) GetByID(ctx context.Context, id string) (user.User, error) {\n\tctx, cancel := context.WithTimeout(ctx, waitTime*time.Second)\n\tdefer cancel()\n\n\tobjectID, err := primitive.ObjectIDFromHex(id)\n\tif err != nil {\n\t\tus.log.Error(err)\n\t\treturn user.User{}, response.ErrInvalidID\n\t}\n\n\tu, err := us.repository.GetByID(ctx, objectID)\n\tif err != nil {\n\t\tus.log.Error(err)\n\t\treturn user.User{}, err\n\t}\n\n\treturn u, nil\n}", "func (us *userService) Get(id int64) (*model.User, error) {\n\treturn us.userRepo.GetByID(id)\n}", "func (srv *Service) GetUserByID(id string) (*models.User, error) {\n\t//call driven adapter responsible for getting a deployment from mongo database\n\tresponse, err := srv.mongoRepository.GetUserByID(id)\n\n\tif err != nil {\n\t\t//return the error sent by the repository\n\t\treturn nil, err\n\t}\n\n\tif response == nil { //user doesn't exist\n\t\treturn nil, &pkg.Error{Err: err, Code: http.StatusNotFound, Message: \"User with these credentials not found\"}\n\t}\n\n\treturn response, nil\n}", "func GetUser(id string) *User {\n\tif user, ok := Users[id]; ok {\n\t\treturn user\n\t}\n\treturn nil\n}" ]
[ "0.7972601", "0.7964725", "0.7894217", "0.7894217", "0.7894217", "0.7894217", "0.7894217", "0.7894217", "0.7894217", "0.7894217", "0.78521353", "0.7851767", "0.7846159", "0.7841692", "0.773739", "0.773739", "0.771031", "0.7708724", "0.768155", "0.7671836", "0.7657818", "0.7597864", "0.7597787", "0.7591685", "0.75902313", "0.75849503", "0.75785923", "0.7578463", "0.75628316", "0.7550751", "0.7541738", "0.75277555", "0.7526629", "0.75172246", "0.7495167", "0.74948233", "0.74883896", "0.74807274", "0.7476001", "0.74705565", "0.7460089", "0.7454964", "0.7439039", "0.7426366", "0.74254256", "0.7424923", "0.7410555", "0.7403901", "0.7386852", "0.73771447", "0.737535", "0.7374899", "0.7372393", "0.73618627", "0.7357194", "0.735681", "0.7346938", "0.7337013", "0.7335832", "0.7327853", "0.7325138", "0.73247135", "0.73093235", "0.7308355", "0.73040545", "0.7297786", "0.72977054", "0.7295824", "0.72928643", "0.72915876", "0.7290536", "0.72835004", "0.7275611", "0.72739875", "0.72720563", "0.7268749", "0.7267922", "0.72645813", "0.72616434", "0.7260456", "0.7258005", "0.7255078", "0.7250724", "0.7244921", "0.72437537", "0.723842", "0.7234259", "0.72239405", "0.72230965", "0.7222036", "0.72209024", "0.7220151", "0.7220143", "0.7216097", "0.7213016", "0.72119385", "0.7210883", "0.72078925", "0.7206913", "0.7196162" ]
0.7363407
53
get user by id
func (u *UserDAO) GetUserByName(uname string) User { stmt, err := db.Instance().Prepare("select uid, username, password from userinfo where username=$1") db.CheckErr(err) rows, err := stmt.Query(uname) var usr User for rows.Next() { var uid int var username string var password string err = rows.Scan(&uid, &username, &password) db.CheckErr(err) usr.Id = uid usr.Name = username usr.Pwd = password } return usr }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getUserById(id int) (User, error) {\n\tkeyString := fmt.Sprintf(\"user:%d\", id)\n\tfirstName, _ := redisConn.Hget(keyString, \"firstName\")\n\tlastName, _ := redisConn.Hget(keyString, \"lastName\")\n\temail, _ := redisConn.Hget(keyString, \"email\")\n\tuser := User{id, string(firstName), string(lastName), string(email)}\n\n\tmongoUser := User{}\n\tc := mongoClient.DB(\"cg\").C(\"users\")\n\terr := c.Find(bson.M{\"id\": id}).One(&mongoUser)\n\tif err != nil {\n\t\tlog.Printf(\"couldn't find user: \", err)\n\t} else {\n\t\tlog.Printf(\"mongo user: %v\", mongoUser)\n\t}\n\n\treturn user, nil\n}", "func (us *Users) Get(id int64) (*User, error) {\n\texp := fmt.Sprintf(\"user_id=%v\", id)\n\n\treturn getUserWhere(exp)\n}", "func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id int64) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (u *UserCtr) GetUserByid(c *gin.Context) {\n\tid,err := strconv.Atoi(c.Param(\"id\"))\n\tif err != nil {\n\t\tresp := errors.New(err.Error())\n\t\tc.JSON(http.StatusInternalServerError, resp)\n\t\treturn\n\t}\n\n\tuser, err := model.UserByID(u.DB,id)\n\tif err != nil {\n\t\tresp := errors.New(err.Error())\n\t\tc.JSON(http.StatusInternalServerError, resp)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"result\": user,\n\t})\n\treturn\n\n}", "func (u *User) Get(id string) error {\n\tsession := mongoSession.Clone()\n\tdefer session.Close()\n\tcollection := session.DB(mongoDialInfo.Database).C(usersCollectionName)\n\t// TODO: handle error\n\tif !bson.IsObjectIdHex(id) {\n\t\treturn errors.New(\"Invalid Object ID\")\n\t}\n\tobjectID := bson.ObjectIdHex(id)\n\terr := collection.FindId(objectID).One(u)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (_ *User) GetById(id uint) (interface{}, error) {\n\tuser := User{}\n\tif disableGetUserById || getTestDb().Where(\"id = ?\", id).Find(&user).RecordNotFound() {\n\t\treturn &user, errors.New(\"User not found\")\n\t}\n\treturn &user, nil\n}", "func (c *UserClient) Get(ctx context.Context, id uuid.UUID) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func (c *UserClient) Get(ctx context.Context, id uuid.UUID) (*User, error) {\n\treturn c.Query().Where(user.ID(id)).Only(ctx)\n}", "func GetUser(id int) (components.User, error) {\n\treturn getUser(id)\n}", "func (c *Client) GetUser(id string) (*dto.User, error) {\n\tvar user *dto.User\n\n\tr, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"users/%s\", id),\n\t\tnil,\n\t)\n\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\t_, err = c.Do(r, &user)\n\treturn user, err\n}", "func (uc UserController) getSingleUserbyID(response http.ResponseWriter, request *http.Request, parameters httprouter.Params) {\n\tresponse.Header().Add(\"content-type\", \"application/json\")\n\tid_string := parameters.ByName(\"id\")\n\n\tid, _ := primitive.ObjectIDFromHex(id_string)\n\tvar user Users\n\tctx, _ := context.WithTimeout(context.Background(), 10*time.Second)\n\terr := uc.collection.FindOne(ctx, bson.M{\"_id\": id}).Decode(&user)\n\tif err != nil {\n\t\tresponse.WriteHeader(http.StatusInternalServerError)\n\t\tresponse.Write([]byte(`{\"message: \"` + err.Error() + `\"}\"`))\n\t\treturn\n\t}\n\t// Decrypting the password\n\t// password := []byte(user.Password)\n\t// key := []byte(\"This is a key for the very secret password\")\n\t// password, _ = decrypt(key, password)\n\t// user.Password = string(password)\n\t//\n\tjson.NewEncoder(response).Encode(user)\n}", "func (u *User) GetById(id interface{}) error {\n\tif err := DB().Where(\"id = ?\", id).First(&u).Error; err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (u *UserModel) GetUserById(id uint64) (*UserModel, error) {\n\td := DB.Self.Where(\"id = ?\", id).First(&u)\n\tfmt.Println(\"GetUser-d\", d)\n\treturn u, d.Error\n}", "func GetUserById(id int) (v *User, err error) {\n\to := orm.NewOrm()\n\tv = &User{Id: id}\n\tif err = o.Read(v); err == nil {\n\t\treturn v, nil\n\t}\n\treturn nil, err\n}", "func (s UserStorage) GetOne(id string) (model.User, error) {\n\tintID, err := strconv.ParseInt(id, 10, 64)\n\tif err != nil {\n\t\terrMessage := fmt.Sprintf(\"User id must be an integer: %s\", id)\n\t\treturn model.User{}, api2go.NewHTTPError(errors.New(errMessage), errMessage, http.StatusBadRequest)\n\t}\n\tvar user model.User\n\tstr := []string{GET_ALL, \"where users.user_id = $1 limit 1\"}\n\tGET_ONE := strings.Join(str, \" \")\n\terror := s.db.SelectOne(&user, GET_ONE, intID)\n\tif error == nil {\n\t\treturn user, nil\n\t} else {\n\t\treturn model.User{}, fmt.Errorf(\"User for id %s not found\", id)\n\t}\t\n\t// return s.getOneWithAssociations(intID)\n}", "func (u *MyUserModel) GetById(id interface{}) error {\n\terr := dbmap.SelectOne(u, \"SELECT * FROM users WHERE id = $1\", id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func GetUser(id int) (User, error) {\n\tvar user User\n\trow := DB.QueryRow(\"select id, realname, username, email from users where id = $1\", id)\n\terr := row.Scan(&user.ID, &user.Realname, &user.Username, &user.Email)\n\treturn user, err\n}", "func GetUserByID(c *gin.Context) {\n\tid := c.Params.ByName(\"id\")\n\tvar user models.User\n\terr := models.GetUserByID(&user, id)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, user)\n\t}\n}", "func GetUserByID(id int64) *User {\n\tuser := new(User)\n\trow := DB.QueryRow(\"SELECT * from user WHERE id=?\", id)\n\terr := row.Scan(&user.ID, &user.Email, &user.Password, &user.Fullname, &user.TSLastLogin, &user.TSCreate, &user.TSUpdate, &user.Permission)\n\tif err != nil {\n\t\tlog.Errorln(\"User SELECT by ID Err: \", err)\n\t\treturn nil\n\t}\n\treturn user\n}", "func (u *UserService) GetUser(id string) (*User, error) {\n\tuser := &User{}\n\terr := u.QueryRow(\"SELECT id, name, phone, email, password FROM users WHERE id=$1 LIMIT 1\", id).Scan(&user.ID, &user.Name, &user.Phone, &user.Email, &user.HashedPassword)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn user, nil\n}", "func (m *manager) Get(ctx context.Context, id int) (*models.User, error) {\n\tusers, err := m.dao.List(ctx, q.New(q.KeyWords{\"user_id\": id}))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(users) == 0 {\n\t\treturn nil, errors.NotFoundError(nil).WithMessage(\"user %d not found\", id)\n\t}\n\n\treturn users[0], nil\n}", "func (rep *UserRepo) Get(ctx context.Context, id string) (*User, error) {\n\tu := &User{}\n\terr := rep.db.Query(\n\t\tctx,\n\t\trep.db.Select(\"*\").From(rep.table()).Where(\"id = ?\", id),\n\t).Decode(u)\n\treturn u, err\n}", "func (c Client) GetUser(ctx context.Context, id string) (api.User, error) {\n\t// TODO (erik): Make this function handle emails properly.\n\tvar user api.User\n\tif err := c.db.GetContext(ctx, &user, \"select * from users where id = ?\", id); err != nil {\n\t\treturn user, err\n\t}\n\n\treturn user, nil\n}", "func (c *Client) GetUser(ctx context.Context, id string) (*UserResponse, error) {\n\tvar resp struct {\n\t\tUser UserResponse `json:\"user\"`\n\t}\n\n\tvariables := make(map[string]interface{})\n\tvariables[\"id\"] = id\n\n\terr := c.transport.Raw(ctx, `\n\t\tquery User($id: String!) {\n\t\t\tuser(id: $id) {\n\t\t\t\tid\n\t\t\t\tname\n\t\t\t\temail\n\t\t\t\trole {\n\t\t\t\t\tid\n\t\t\t\t\tlabel\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t`, variables, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &resp.User, nil\n}", "func Get(id int64) (User, error) {\n\tvar u User\n\tstmt, err := db.Prepare(\"select id, name, age, created from user where id = ? \")\n\tdefer stmt.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn u, err\n\t}\n\terr = stmt.QueryRow(id).Scan(&u.ID, &u.Name, &u.Age, &u.Created)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn u, err\n\t}\n\treturn u, nil\n}", "func GetUserById(context *fiber.Ctx) error {\n\tid, err := ParseId(context)\n\n\tif err != nil {\n\t\treturn context.Status(400).JSON(&fiber.Map{\"error\": err.Error()})\n\t}\n\n\tvar user = repository.GetUserById(id)\n\n\tif user.ID == 0 {\n\t\tlog.Printf(\"user not found: %d\", id)\n\t\treturn context.Status(404).JSON(&fiber.Map{\"response\": \"not found\"})\n\t} else {\n\t\treturn context.Status(200).JSON(user)\n\t}\n}", "func (m *postgresDBRepo) GetUserById(id int) (models.User, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\tquery := `select id, first_name, last_name, email, password,\n\t\t access_level, created_at, updated_at\n\t\tfrom users where id = $1`\n\n\trow := m.DB.QueryRowContext(ctx, query, id)\n\tvar u models.User\n\terr := row.Scan(&u.ID, &u.FirstName, &u.LastName, &u.Email, &u.Password, &u.AccessLevel, &u.CreatedAt, &u.UpdatedAt)\n\tif err != nil {\n\t\treturn u, err\n\t}\n\n\treturn u, nil\n}", "func (repo *UserRepository) GetById(id string) (*dto.User, error) {\n\tselectStatement := \"SELECT * FROM `users` WHERE id = ?\"\n\tuser := &dto.User{}\n\tif err := repo.db.Get(user, selectStatement, id); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn user, nil\n}", "func (s *usersService) GetByID(id int) (User, error) {\n\tusr, err := s.repo.GetById(id)\n\tif err != nil {\n\t\tlog.Printf(\"error getting user: %s\\n\", err)\n\t\treturn User{}, err\n\t}\n\treturn usr, nil\n}", "func GetByID(id uint64) (*User, error) {\n\treturn getBy(\"id\", strconv.FormatUint(id, 10))\n}", "func GetUserById(id int, db *gorm.DB) (user User, err error) {\n\tuser.ID = id\n\tif err = db.First(&user).Error; err != nil {\n\t\terr = ErrUserNotFound\n\t}\n\treturn\n}", "func GetByID(w http.ResponseWriter, r *http.Request, DB *gorm.DB) {\n\tvar dbUser User\n\tparams := mux.Vars(r)\n\tuserID := params[\"id\"]\n\t//Need to make sure that the user that is requesting user info is either the user or an admin user\n\ttoken := r.Header.Get(\"Authorization\")\n\tresult, ID := utils.VerifyJWT(token)\n\tmyID := strconv.FormatUint(uint64(ID), 10)\n\t//results := utils.IsAdmin(token, DB)\n\t//fmt.Printf(\"%v\", results)\n\tif (result && userID == myID) || isAdmin(token, DB) {\n\t\tDB.Where(\"ID = ?\", userID).First(&dbUser)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tjson.NewEncoder(w).Encode(dbUser)\n\t} else {\n\t\tnotauthorizedResponse := response.JsonResponse(\"Not authorized\", 409)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tjson.NewEncoder(w).Encode(notauthorizedResponse)\n\t}\n\n}", "func (c *UsersClient) Get(ctx context.Context, id string) (*models.User, int, error) {\n\tresp, status, _, err := c.BaseClient.Get(ctx, base.GetHttpRequestInput{\n\t\tValidStatusCodes: []int{http.StatusOK},\n\t\tUri: base.Uri{\n\t\t\tEntity: fmt.Sprintf(\"/users/%s\", id),\n\t\t\tHasTenantId: true,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, status, err\n\t}\n\tdefer resp.Body.Close()\n\trespBody, _ := ioutil.ReadAll(resp.Body)\n\tvar user models.User\n\tif err := json.Unmarshal(respBody, &user); err != nil {\n\t\treturn nil, status, err\n\t}\n\treturn &user, status, nil\n}", "func (dao *UserDAO) Get(id uint) (*models.User, error) {\n\tvar user models.User\n\n\terr := config.Config.DB.Where(\"id = ?\", id).First(&user).Error\n\n\treturn &user, err\n}", "func (u *usecase) Get(ctx context.Context, id string) (*User, error) {\n\tuser, err := u.repository.Get(ctx, id)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error fetching a single user\")\n\t}\n\treturn user, nil\n}", "func GetUserByID(c *gin.Context) {\n\tid := c.Params.ByName(\"id\")\n\tvar user Models.User\n\terr := Models.GetUserByID(&user, id)\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\" : gin.H { \n\t\t\t\"status\": http.StatusNotFound,\n\t\t\t\"message\": err.Error(),\n\t\t}})\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK,gin.H{\n\t\t\t\"data\" : user,\n\t\t\t\"status\": http.StatusOK,\n\t\t})\n\t}\n}", "func (c *Client) GetUserByID(id string) (User, error) {\n\tvar (\n\t\turi = \"/rest/users/\" + id\n\t\tqueryParams = createQuery(&map[string]string{\n\t\t\t\"id\": id,\n\t\t})\n\t\tuser User\n\t)\n\n\tif id == \"\" {\n\t\treturn user, fmt.Errorf(\"id must not be empty\")\n\t}\n\n\tresponse, err := c.RestAPICall(rest.GET, uri, queryParams, nil)\n\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\tif err := json.Unmarshal([]byte(response), &user); err != nil {\n\t\treturn user, apiResponseError(response, err)\n\t}\n\n\treturn user, err\n}", "func (u *USER_DB) GetById(id interface{}) error {\n\terr := dbmap.SelectOne(u, \"SELECT * FROM USER WHERE Idx = ?\", id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func GetUser(id int64) (*User, error) {\n\tuser := User{}\n\terr := meddler.QueryRow(db, &user, userFindIdStmt, id)\n\treturn &user, err\n}", "func (p *Postgres) GetByID(id int) (*e.User, error) {\n\tdb := p.DB\n\tuser := e.User{}\n\n\terr := db.Model(&user).Where(\"id = ?\", id).Select()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &user, nil\n}", "func (u *User) GetUser(id int) error {\n\tconn, err := db.Connect()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tsql := `SELECT id,username,password,name,is_admin FROM users WHERE id = $1 LIMIT 1`\n\trow := conn.QueryRow(sql, id)\n\n\terr = row.Scan(&u.ID, &u.Username, &u.Password, &u.Name, &u.IsAdmin)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func GetUser(id int) (*User, error) {\n\tuser := new(User)\n\terr := db.Model(user).Where(\"id = ?\", id).Select()\n\treturn user, err\n}", "func UserByIDGet(c *gin.Context) {\n\tid, _ := strconv.ParseInt(c.Param(\"id\"), 10, 64)\n\tlog.Info(\"UserByIDGet \", id)\n\tm := model.UserByID(uint(id))\n\tginutils.WriteGinJSON(c, http.StatusOK, m)\n}", "func (u *userService) Get(id string) (*domain.User, error) {\n\treturn u.storage.Get(id)\n}", "func (db *Database) GetUser(id int) (*User, error) {\n\trow := db.db.QueryRow(`\n\t\tSELECT id, username, owner FROM melodious.accounts WHERE id=$1;\n\t`, id)\n\tuser := &User{}\n\terr := row.Scan(&(user.ID), &(user.Username), &(user.Owner))\n\tif err != nil {\n\t\treturn &User{}, err\n\t}\n\treturn user, nil\n}", "func (u *UserDAO) Get(id int) User {\n\tstmt, err := db.Instance().Prepare(\"select uid, username, password from userinfo where uid=$1\")\n\tdb.CheckErr(err)\n\n\trows, err := stmt.Query(id)\n\n\tvar usr User\n\tfor rows.Next() {\n\t\tvar uid int\n\t\tvar username string\n\t\tvar password string\n\t\terr = rows.Scan(&uid, &username, &password)\n\t\tdb.CheckErr(err)\n\t\tusr.Id = uid\n\t\tusr.Name = username\n\t\tusr.Pwd = password\n\t}\n\n\treturn usr\n}", "func (u *User) GetUserByID(id string) *User {\n\tvar result User\n\n\terr := database.DB.Where(\"id = ?\", id).First(&result).Error\n\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn &result\n}", "func GetUserByID(c *gin.Context, client *statsd.Client) {\n\tlog.Info(\"getting user by id\")\n\tid := c.Params.ByName(\"id\")\n\tvar user entity.User\n\terr := model.GetUserByID(&user, id, client)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"id\": user.ID,\n\t\t\t\"first_name\": user.FirstName,\n\t\t\t\"last_name\": user.LastName,\n\t\t\t\"username\": user.Username,\n\t\t\t\"account_created\": user.AccountCreated,\n\t\t\t\"account_updated\": user.AccountUpdated,\n\t\t})\n\t}\n}", "func (u *UserModel) Get(id int) (*models.User, error) {\n\tstmt := `SELECT u.id, u.uuid, u.first_name, u.last_name, u.email, u.phone, s.slug, u.created\n\t\t\t FROM user AS u\n\t\t LEFT JOIN ref_user_status AS s ON u.status_id = s.id\n\t\t\t WHERE u.id = ?`\n\n\tuser := &models.User{}\n\terr := u.DB.QueryRow(stmt, id).Scan(&user.ID, &user.UUID, &user.FirstName, &user.LastName, &user.Email, &user.Phone, &user.Status, &user.Created)\n\n\tif err == sql.ErrNoRows {\n\t\treturn nil, models.ErrNoRecord\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn user, nil\n}", "func GetUserById(id string) (Contact, error) {\n\tvar usr Contact\n\tfor r := 0; r < len(Users); r++ {\n\t\tif id == Users[r].ID {\n\t\t\tusr = Users[r]\n\t\t} else {\n\t\t\treturn Contact{}, errors.New(\"user not found\")\n\t\t}\n\t}\n\treturn usr, nil\n}", "func (s *UsersService) GetByID(id string) (*User, *Response, error) {\n\tu := fmt.Sprintf(\"users/%v\", id)\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tuser := new(User)\n\tresp, err := s.client.Do(req, user)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn user, resp, err\n}", "func GetUserByID(id int, engine *xorm.Engine) (*User, error) {\n\n\tuser := new(User)\n\tok, err := engine.Where(\"id=?\", id).Get(user)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif ok {\n\t\treturn user, nil\n\t}\n\treturn nil, fmt.Errorf(\"user (%d) not exist\", id)\n}", "func (d *DB) GetUser(id int) (User, error) {\n\tvar user User\n\terr := d.db.Find(&user, id).Error\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\treturn user, nil\n}", "func (dbh *DBHandler) GetUserByID(id int) *api.User {\n\tvar user *api.User\n\tresult, err := dbh.Connection.Query(`SELECT * FROM users WHERE telegram_id = ?;`, id)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer result.Close()\n\tif result.Next() {\n\t\terr := result.Scan(&user.ID, &user.Username)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tuser = &api.User{}\n\t\t}\n\t}\n\treturn user\n}", "func (prof *Profiles) ByID(id_ interface{}) (*User, error) {\n\tvar id string\n\tswitch x := id_.(type) {\n\tcase int64:\n\t\tid = fmt.Sprintf(\"%d\", x)\n\tcase int:\n\t\tid = fmt.Sprintf(\"%d\", x)\n\tcase string:\n\t\tid = x\n\tdefault:\n\t\treturn nil, errors.New(\"Invalid id, please provide a string or int(64)\")\n\t}\n\n\tbody, _, err := prof.insta.sendRequest(\n\t\t&reqOptions{\n\t\t\tEndpoint: fmt.Sprintf(urlUserByID, id),\n\t\t},\n\t)\n\tif err == nil {\n\t\tresp := userResp{}\n\t\terr = json.Unmarshal(body, &resp)\n\t\tif err == nil {\n\t\t\tuser := &resp.User\n\t\t\tuser.insta = prof.insta\n\t\t\treturn user, err\n\t\t}\n\t}\n\treturn nil, err\n}", "func GetUserByID(user *models.User, id uint) (err error) {\n\tif err = config.DB.Where(\"id = ?\", id).First(user).Error; err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (model *UserModel) Get(id int) (*models.User, error) {\n\tuser := &models.User{}\n\tstmt := `SELECT id, name, email, created, active FROM users WHERE id = ?`\n\terr := model.DB.QueryRow(stmt, id).Scan(&user.ID, &user.Name, &user.Email, &user.Created, &user.Active)\n\tif err != nil {\n\t\tif errors.Is(err, sql.ErrNoRows) {\n\t\t\treturn nil, models.ErrNoRecord\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn user, nil\n}", "func (s *Store) GetUser(id bson.ObjectId) (*models.User, error) {\n\tvar user models.User\n\terr := s.Users.Find(bson.M{\"_id\": id}).One(&user)\n\treturn &user, err\n}", "func (u *UserModel) Get(id int) (*models.User, error) {\n\tusr := &models.User{}\n\n\tstmt := `SELECT id, name, email, created, active FROM users WHERE id = ?`\n\terr := u.DB.QueryRow(stmt, id).Scan(&usr.ID, &usr.Name, &usr.Email, &usr.Created, &usr.Active)\n\tif err != nil {\n\t\tif errors.Is(err, sql.ErrNoRows) {\n\t\t\treturn nil, models.ErrNoRecord\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn usr, nil\n}", "func (ss *SQLStore) GetByID(id int64) (*User, error) {\n\trows, err := ss.db.Query(\"select id, Email, PassHash, UserName, FirstName, LastName, PhotoURL from USERS\")\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to query.\")\n\t}\n\n\tdefer rows.Close()\n\n\tusers := User{}\n\n\tfor rows.Next() {\n\t\t// Scans row into users struct.\n\t\tif err := rows.Scan(&users.ID, &users.Email,\n\t\t\t&users.PassHash, &users.UserName, &users.FirstName,\n\t\t\t&users.LastName, &users.PhotoURL); err != nil {\n\t\t\treturn nil, errors.New(\"Error scanning row.\")\n\t\t}\n\n\t\t// checks the ID, and if it matches, return that user.\n\t\tif users.ID == id {\n\t\t\treturn &users, nil\n\t\t}\n\t}\n\n\treturn nil, errors.New(\"User with ID not found.\")\n}", "func (mss *MySQLStore) GetByID(id int64) (*User, error) {\n\tuser := &User{}\n\trow := mss.Client.QueryRow(\"select * from users where user_id=?\", id)\n\tif err := row.Scan(&user.ID, &user.Email, &user.PassHash, &user.UserName,\n\t\t&user.FirstName, &user.LastName); err != nil {\n\t\treturn nil, err\n\t}\n\treturn user, nil\n}", "func (s *Service) GetByID(id int) (*User, error) {\n\t// Try to pull this User from the database.\n\tdbm, err := s.db.Users.GetByID(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a new User.\n\tuser := &User{\n\t\tID: dbm.ID,\n\t\tEmail: dbm.Email,\n\t\tPassword: dbm.Password,\n\t}\n\n\treturn user, nil\n}", "func (s User) GetByID(id string) (User, error) {\n\tvar (\n\t\tuser User\n\t\terr error\n\t)\n\n\ttx := gorm.MysqlConn().Begin()\n\tif err = tx.Find(&user, \"id = ?\", id).Error; err != nil {\n\t\ttx.Rollback()\n\t\treturn user, err\n\t}\n\ttx.Commit()\n\n\treturn user, err\n}", "func GetUserByID(c *gin.Context) {\n\tvar user, condition Users\n\n\tuserID, _ := strconv.ParseUint(c.Param(\"id\"), 10, 64)\n\tcondition.ID = uint(userID)\n\tuser.FindOne(condition)\n\n\tif user.ID == 0 {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"status\": http.StatusOK,\n\t\t\t\"message\": \"user is not found\",\n\t\t})\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"status\": http.StatusOK,\n\t\t\t\"data\": user,\n\t\t})\n\t}\n}", "func (rep *UserRepository) GetByID(userID int64) (user *models.User, err error) {\n\tuser = &models.User{}\n\terr = databaseConnection.First(user, \"id = ?\", userID).Error\n\treturn\n}", "func GetUserByID(c *gin.Context) {\n\tuser, err := getUserFromParams(c)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, user)\n\t}\n}", "func GetUser(id bson.ObjectId) User {\n\tsession, _ := mgo.Dial(\"127.0.0.1\")\n\tdefer session.Close()\n\tsession.SetMode(mgo.Monotonic, true)\n\tdb := session.DB(\"reimburse-me\").C(\"user\")\n\tvar result User\n\tdb.FindId(id).One(&result)\n\tresult.Token = \"\"\n\treturn result\n}", "func (u UserRepository) GetByID(id int) (interface{}, error) {\n\n\tvar sqlStm = `\n\t\tSELECT\ta.id, \n\t\t\t\ta.firstname, \n\t\t\t\ta.lastname, \n\t\t\t\ta.username, \n\t\t\t\ta.email, \n\t\t\t\ta.password, \n\t\t\t\ta.timestamp, \n\t\t\t\ta.updated \n\t\tFROM reservations_user a\n\t\tWHERE a.id = $1`\n\n\tvar user models.UserModel\n\n\tif err := u.DB.QueryRow(\n\t\tsqlStm,\n\t\tid,\n\t).Scan(\n\t\t&user.ID,\n\t\t&user.FirstName,\n\t\t&user.LastName,\n\t\t&user.UserName,\n\t\t&user.Email,\n\t\t&user.Password,\n\t\t&user.Timestamp,\n\t\t&user.Updated,\n\t); err != nil {\n\t\treturn nil, fmt.Errorf(\"%s\", err)\n\t}\n\n\treturn user, nil\n}", "func UserGet(db *sql.DB, id string) (User, error) {\n\tuser := User{}\n\terr := db.QueryRow(`\n\tSELECT id, email, password FROM \"user\" WHERE id=$1\n\t`, id).Scan(&user.ID, &user.Email, &user.Password)\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\treturn user, nil\n}", "func (db *DB) GetUser(id string) (*model.User, error) {\n\tvar user model.User\n\n\tcursor := db.collections.users.FindOne(\n\t\tcontext.Background(),\n\t\tbson.D{primitive.E{\n\t\t\tKey: \"_id\",\n\t\t\tValue: id,\n\t\t}},\n\t)\n\n\tif cursor.Err() != nil {\n\t\treturn nil, cursor.Err()\n\t}\n\n\terr := cursor.Decode(&user)\n\tif err != nil {\n\t\tif err == mongo.ErrNoDocuments {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn &user, nil\n}", "func (s *UsersService) Get(id string) (*User, *http.Response, error) {\n\turi := fmt.Sprintf(\"users/%v\", id)\n\n\tuser := new(User)\n\tres, err := s.client.Get(uri, user)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\n\treturn user, res, err\n}", "func (m *UserModel) GetByID(id string) (User, error) {\n\tvar user User\n\terr := m.db.Where(\"id = ?\", id).First(&user).Error\n\n\treturn user, err\n}", "func GetUserByID(id uint) (models.User, error) {\n\tvar u models.User\n\tresult := database.GetPostgresDB().First(&u, id)\n\tif result.Error != nil {\n\t\treturn models.User{}, result.Error\n\t}\n\treturn u, nil\n}", "func UserById(id int, fillAttributes bool) (u *UserModel, err error) {\n\tu, err = getUser(\"where id = $1\", id, true, fillAttributes)\n\treturn\n}", "func (self *UserManager) FindById(id interface{}) *models.User {\n\tdb := self.db\n\tuser := new(models.User)\n\tstmt, err := db.Prepare(\"SELECT * FROM users WHERE id = ?\")\n\tutils.CheckErr(err, nil)\n\terr = stmt.QueryRow(id).Scan(&user.Id, &user.FullName, &user.Address, &user.Phone, &user.Email, &user.Password, &user.Hash, &user.IsActive, &user.Token)\n\n\tif err != nil && err != sql.ErrNoRows {\n\t\tutils.CheckErr(err, nil)\n\t}\n\n\tif err == sql.ErrNoRows {\n\t\treturn nil\n\t} else {\n\t\treturn user\n\t}\n}", "func (s *Service) GetUser(id bson.ObjectId) (User, error) {\n\tsession := s.db.Copy()\n\tdefer session.Close()\n\n\tc := session.DB(\"\").C(userCollection)\n\tvar user User\n\terr := c.FindId(id).One(&user)\n\tif err != nil {\n\t\treturn user, fmt.Errorf(\"user not found: %v\", err)\n\t}\n\n\treturn user, nil\n}", "func (dao *UserDAO) Get(id uint) (*models.User, error) {\n\tvar user models.User\n\n\t// Query Database here...\n\n\t//user = models.User{\n\t//\tModel: models.Model{ID: 1},\n\t//\tFirstName: \"Martin\",\n\t//\tLastName: \"Heinz\",\n\t//\tAddress: \"Not gonna tell you\",\n\t//\tEmail: \"[email protected]\"}\n\n\t// if using Gorm:\n\terr := config.Config.DB.Where(\"id = ?\", id).\n\t\tFirst(&user).\n\t\tError\n\n\treturn &user, err\n}", "func (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {\n\tid, err := strconv.Atoi(r.URL.Query().Get(\"id\"))\n\tif err != nil {\n\t\trender.BadRequest(w, r, \"id must be an integer greater zero\")\n\t\treturn\n\t}\n\n\t// Query user details from userID\n\tuser, err := h.Client.User.\n\t\tQuery().\n\t\tWhere(usr.ID(id)).\n\t\tOnly(r.Context())\n\tif err != nil {\n\t\tswitch {\n\t\tcase ent.IsNotFound(err):\n\t\t\trender.NotFound(w, r, \"Email Doesn't exists\")\n\t\tdefault:\n\t\t\trender.InternalServerError(w, r, \"Server Error\")\n\t\t}\n\t\treturn\n\t}\n\trender.OK(w, r, user)\n}", "func GetOne(id int) (user model.User, err error) {\n\n\tuser, err = dao.GetOne(id) // 直接调dao了\n\tif err != nil {\n\t\treturn user, fmt.Errorf(\"GetOne in service Fail: %w\", err) // wrap\n\t}\n\treturn user, err\n}", "func GetUser(db sqlx.Queryer, id int64) (User, error) {\n\tvar user User\n\terr := sqlx.Get(db, &user, \"select \"+externalUserFields+\" from \\\"user\\\" where id = $1\", id)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn user, ErrDoesNotExist\n\t\t}\n\t\treturn user, errors.Wrap(err, \"select error\")\n\t}\n\n\treturn user, nil\n}", "func GetUserByID(id int) (*UserByID, error) {\n\tres := &UserByID{}\n\terr := urlToStruct(fmt.Sprintf(\"/users/userbyid/%d\", id), res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}", "func (m *mysqlUserRepository) GetByID(id int64) (res domain.User, err error) {\n\tquery := `SELECT id, name, email, updated_at, created_at, deleted_at\n\t\t\t\tFROM user WHERE ID = ?`\n\n\tlist, err := m.fetch(query, id)\n\tif err != nil {\n\t\treturn domain.User{}, nil\n\t}\n\n\tif len(list) > 0 {\n\t\tres = list[0]\n\t} else {\n\t\treturn res, domain.ErrNotFound\n\t}\n\n\treturn\n}", "func (app *App) getUser(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tid, err := strconv.Atoi(vars[\"id\"])\n\tif err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tuser := &users.User{ID: int64(id)}\n\tuser, err = user.GetUser(app.Db)\n\tif err != nil {\n\t\trespondWithError(w, http.StatusNotFound, err.Error())\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\trespondWithJSON(w, http.StatusOK, user)\n}", "func GetUser(id string) (User, error) {\n\tresult := User{}\n\terr := db.QueryRow(\"SELECT * FROM web_users WHERE ID = ?\", id).Scan(&result.ID, &result.Username,\n\t\t&result.RegisteredOn, &result.LastLogin, &result.AvatarURL, &result.AccessToken, &result.RefreshToken,\n\t\t&result.AccessExpiration)\n\tif err != nil {\n\t\treturn User{}, err\n\t}\n\n\treturn result, nil\n}", "func (store *MySQLStore) GetByID(id int64) (*User, error) {\n\tquery := \"SELECT * FROM users WHERE id = ?\"\n\tuser := &User{}\n\terr := store.db.QueryRow(query, id).Scan(&user.ID, &user.Email, &user.FirstName, &user.LastName, &user.PassHash,\n\t\t&user.UserName, &user.PhotoURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn user, nil\n}", "func (s *UserService) Get(id string) (*User, *Response, error) {\n\n\turl := fmt.Sprintf(\"Users/%s)\", id)\n\n\treq, err := s.client.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresource := new(User)\n\tresp, err := s.client.Do(req, &resource)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn resource, resp, err\n}", "func GetUser(tx *sql.Tx, id int64) (*User, error) {\n\tu := User{}\n\treturn &u, tx.QueryRow(\n\t\t\"select id, name, password_hash from users where id = $1\",\n\t\tid,\n\t).Scan(\n\t\t&u.ID,\n\t\t&u.Name,\n\t\t&u.PasswordHash,\n\t)\n}", "func (retUser) One(ctx context.Context, claims auth.Claims, db *sqlx.DB, id string) (*User, error) {\n\tctx, span := global.Tracer(\"service\").Start(ctx, \"internal.data.retrieve.user.one\")\n\tdefer span.End()\n\n\tif _, err := uuid.Parse(id); err != nil {\n\t\treturn nil, ErrInvalidID\n\t}\n\n\t// If you are not an admin and looking to retrieve someone else then you are rejected.\n\tif !claims.HasRole(auth.RoleAdmin) && claims.Subject != id {\n\t\treturn nil, ErrForbidden\n\t}\n\n\tvar u User\n\tconst q = `SELECT * FROM users WHERE user_id = $1`\n\tif err := db.GetContext(ctx, &u, q, id); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, ErrNotFound\n\t\t}\n\n\t\treturn nil, errors.Wrapf(err, \"selecting user %q\", id)\n\t}\n\n\treturn &u, nil\n}", "func (r *Repo) GetUser(_ context.Context, id int64) (entities.User, error) {\n\tvar u entities.User\n\terr := r.Get(&u, \"SELECT * FROM users WHERE id = $1\", id)\n\tif err != nil {\n\t\treturn entities.User{}, fmt.Errorf(\"error getting user: %w\", err)\n\t}\n\treturn u, nil\n}", "func (us *UserService) GetByID(ctx context.Context, id string) (user.User, error) {\n\tctx, cancel := context.WithTimeout(ctx, waitTime*time.Second)\n\tdefer cancel()\n\n\tobjectID, err := primitive.ObjectIDFromHex(id)\n\tif err != nil {\n\t\tus.log.Error(err)\n\t\treturn user.User{}, response.ErrInvalidID\n\t}\n\n\tu, err := us.repository.GetByID(ctx, objectID)\n\tif err != nil {\n\t\tus.log.Error(err)\n\t\treturn user.User{}, err\n\t}\n\n\treturn u, nil\n}", "func (us *userService) Get(id int64) (*model.User, error) {\n\treturn us.userRepo.GetByID(id)\n}", "func (srv *Service) GetUserByID(id string) (*models.User, error) {\n\t//call driven adapter responsible for getting a deployment from mongo database\n\tresponse, err := srv.mongoRepository.GetUserByID(id)\n\n\tif err != nil {\n\t\t//return the error sent by the repository\n\t\treturn nil, err\n\t}\n\n\tif response == nil { //user doesn't exist\n\t\treturn nil, &pkg.Error{Err: err, Code: http.StatusNotFound, Message: \"User with these credentials not found\"}\n\t}\n\n\treturn response, nil\n}", "func GetUser(id string) *User {\n\tif user, ok := Users[id]; ok {\n\t\treturn user\n\t}\n\treturn nil\n}" ]
[ "0.7972601", "0.7964725", "0.7894217", "0.7894217", "0.7894217", "0.7894217", "0.7894217", "0.7894217", "0.7894217", "0.7894217", "0.78521353", "0.7851767", "0.7846159", "0.7841692", "0.773739", "0.773739", "0.771031", "0.7708724", "0.768155", "0.7671836", "0.7657818", "0.7597864", "0.7597787", "0.7591685", "0.75902313", "0.75849503", "0.75785923", "0.7578463", "0.75628316", "0.7550751", "0.7541738", "0.75277555", "0.7526629", "0.75172246", "0.7495167", "0.74948233", "0.74883896", "0.74807274", "0.7476001", "0.74705565", "0.7460089", "0.7454964", "0.7439039", "0.7426366", "0.74254256", "0.7424923", "0.7410555", "0.7403901", "0.7386852", "0.73771447", "0.737535", "0.7374899", "0.7372393", "0.7363407", "0.73618627", "0.7357194", "0.735681", "0.7346938", "0.7337013", "0.7335832", "0.7327853", "0.7325138", "0.73247135", "0.73093235", "0.7308355", "0.73040545", "0.7297786", "0.72977054", "0.7295824", "0.72928643", "0.72915876", "0.7290536", "0.72835004", "0.7275611", "0.72739875", "0.72720563", "0.7268749", "0.7267922", "0.72645813", "0.72616434", "0.7260456", "0.7258005", "0.7255078", "0.7250724", "0.7244921", "0.72437537", "0.723842", "0.7234259", "0.72239405", "0.72230965", "0.7222036", "0.72209024", "0.7220151", "0.7220143", "0.7216097", "0.7213016", "0.72119385", "0.7210883", "0.72078925", "0.7206913", "0.7196162" ]
0.0
-1
OpenPCAP read file as gopacket.PacketSource
func OpenPCAP(file string) (*Pcap, error) { handle, err := pcap.OpenOffline(file) if err != nil { return nil, err } return &Pcap{source: gopacket.NewPacketSource(handle, handle.LinkType())}, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ReadPacketsFromPcap(pcapfile string, filter layers.IPProtocol, raw bool) ([]events.Event, []gopacket.Packet, error) {\n\tvar Events []events.Event\n\tvar rawPackets []gopacket.Packet\n\tvar ret []events.Event\n\tvar rawRet []gopacket.Packet\n\tpcapfilePath := MakeAssetFullPath(pcapfile)\n\n\tf, err := os.Open(pcapfilePath)\n\tif err != nil {\n\t\treturn []events.Event{}, []gopacket.Packet{}, err\n\t}\n\thandle, err := pcap.OpenOfflineFile(f)\n\tif err != nil {\n\t\treturn []events.Event{}, []gopacket.Packet{}, err\n\t}\n\n\tsrc := gopacket.NewPacketSource(handle, handle.LinkType())\n\tin := src.Packets()\n\nloop:\n\tfor {\n\t\tpacket := <-in\n\t\tif packet == nil {\n\t\t\tbreak loop\n\t\t}\n\n\t\tif _, ok := packet.NetworkLayer().(*layers.IPv4); ok {\n\t\t\tif packet.NetworkLayer().(*layers.IPv4).Protocol == filter {\n\t\t\t\tif raw {\n\t\t\t\t\trawPackets = append(rawPackets, packet)\n\t\t\t\t} else {\n\t\t\t\t\tswitch filter {\n\t\t\t\t\tcase layers.IPProtocolICMPv4:\n\t\t\t\t\t\tev, err := events.NewICMPv4Event(packet)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn []events.Event{}, []gopacket.Packet{}, err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tEvents = append(Events, ev)\n\n\t\t\t\t\tcase layers.IPProtocolUDP:\n\t\t\t\t\t\tev, err := events.NewUDPEvent(packet, 4)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn []events.Event{}, []gopacket.Packet{}, err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tEvents = append(Events, ev)\n\n\t\t\t\t\tcase layers.IPProtocolTCP:\n\t\t\t\t\t\tev, err := events.NewTCPEvent(packet, 4)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn []events.Event{}, []gopacket.Packet{}, err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tEvents = append(Events, ev)\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tcontinue loop\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if _, ok := packet.NetworkLayer().(*layers.IPv6); ok {\n\t\t\tif packet.NetworkLayer().(*layers.IPv6).NextHeader == filter {\n\t\t\t\tswitch filter {\n\t\t\t\tcase layers.IPProtocolICMPv6:\n\t\t\t\t\tev, err := events.NewICMPv6Event(packet)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn []events.Event{}, []gopacket.Packet{}, err\n\t\t\t\t\t}\n\n\t\t\t\t\tEvents = append(Events, ev)\n\n\t\t\t\tdefault:\n\t\t\t\t\tcontinue loop\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// I'm so lazy\n\tif raw {\n\t\trawRet = make([]gopacket.Packet, len(rawPackets))\n\t\tcopy(rawRet, rawPackets)\n\t}\n\n\tret = make([]events.Event, len(Events))\n\tcopy(ret, Events)\n\n\treturn ret, rawRet, nil\n}", "func p24101_file() {\n\tnr := 5342\n\tb, _ := ioutil.ReadFile(fmt.Sprintf(\"cr-proxy/replay/%d-24101.bin\", nr))\n\tp := Packet{\n\t\tBuf: b,\n\t\tPos: 7,\n\t}\n\t/*\n\t\tb, _ := ioutil.ReadFile(\"24101.dat\")\n\t\tp := Packet{\n\t\t\tBuf: b,\n\t\t\tPos: 0,\n\t\t}\n\t*/\n\tp24101(&p, nr)\n}", "func (f FilePP) GetSource() []byte {\n\treturn f.pp\n}", "func (c *Conn) createInfileDataPacket(filename string) ([]byte, error) {\n\tvar (\n\t\tf *os.File\n\t\tfi os.FileInfo\n\t\tb []byte\n\t\toff, n int\n\t\terr error\n\t)\n\n\tif f, err = os.Open(filename); err != nil {\n\t\treturn nil, myError(ErrFile, err)\n\t}\n\tdefer f.Close()\n\n\tif fi, err = f.Stat(); err != nil {\n\t\treturn nil, myError(ErrFile, err)\n\t}\n\n\tif b, err = c.buff.Reset(4 + int(fi.Size())); err != nil {\n\t\treturn nil, err\n\t}\n\n\toff += 4 // placeholder for protocol packet header\n\n\tif n, err = f.Read(b[off:]); err != nil {\n\t\treturn nil, myError(ErrFile, err)\n\t}\n\n\toff += n\n\n\treturn b[0:off], nil\n}", "func readPacket(reader *bufio.Reader, start *int, end int) (Packet, error) {\n\tbuf, err := reader.Peek(1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// An OSC Message starts with a '/'\n\tif buf[0] == '/' {\n\t\tpkt, err := readMessage(reader, start)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn pkt, err\n\t}\n\tif buf[0] == '#' { // An OSC bundle starts with a '#'\n\t\tpkt, err := readBundle(reader, start, end)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn pkt, nil\n\t}\n\n\tvar pkt Packet\n\treturn pkt, nil\n}", "func readSource(filename string, src []byte) ([]byte, error) {\n\tif src != nil {\n\t\treturn src, nil\n\t}\n\treturn os.ReadFile(filename)\n}", "func GetPacketReader(v string, snaplen int, rtimeout int64) (*pcap.Handle, error) {\n\tif FileIsExist(v) {\n\t\tpcap, e := pcap.OpenOffline(v)\n\t\tif e != nil {\n\t\t\treturn nil, fmt.Errorf(\"Open offline pcap file %s failed: %v\", v, e)\n\t\t}\n\n\t\treturn pcap, nil\n\t}\n\n\trt := time.Duration(rtimeout) * time.Second\n\tpcap, e := pcap.OpenLive(v, int32(snaplen), false, rt)\n\tif e != nil {\n\t\treturn nil, fmt.Errorf(\"Open network interface %s failed: %v\", v, e)\n\t}\n\n\treturn pcap, nil\n}", "func readGMPacket(c Client, cb func(Message) error) error {\n\theader := make([]byte, 12)\n\tif _, err := io.ReadFull(c.conn, header); err != nil {\n\t\treturn err\n\t}\n\theader1 := uint32(binary.LittleEndian.Uint32(header[0:4]))\n\theader2 := uint32(binary.LittleEndian.Uint32(header[4:8]))\n\theader3 := uint32(binary.LittleEndian.Uint32(header[8:12]))\n\tif header1 != gmMagicNumber1 {\n\t\treturn fmt.Errorf(\"packet contains invalid identifier/magic number\")\n\t}\n\tif header2 != uint32(12) {\n\t\treturn fmt.Errorf(\"packet header size is not 12\")\n\t}\n\tpayload := make([]byte, header3)\n\tif _, err := io.ReadFull(c.conn, payload); err != nil {\n\t\treturn err\n\t}\n\tif len(payload) != 0 {\n\t\tbuffer := Packet{payload: payload[1:]}\n\t\treturn cb(Message{Client: c, EventType: ClientData, DataType: int(payload[0]), Buffer: &buffer})\n\t}\n\treturn nil\n}", "func loadKeyFromFile(file string, pubkey bool) packet.Packet {\n\tpubkeyFD, err := os.Open(file)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"file\": file,\n\t\t}).WithError(err).Fatal(\"Couldn't open key file\")\n\t}\n\tres, err := armor.Decode(pubkeyFD)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"file\": file,\n\t\t}).WithError(err).Fatal(\"Couldn't read key file\")\n\t}\n\n\tif pubkey {\n\t\tif res.Type != openpgp.PublicKeyType {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"file\": file,\n\t\t\t\t\"type\": res.Type,\n\t\t\t}).Fatal(\"Public key file didn't contain public key\")\n\t\t}\n\t\tpkReader := packet.NewReader(res.Body)\n\t\tpkPacket, err := pkReader.Next()\n\t\tif res.Type != openpgp.PublicKeyType {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"file\": file,\n\t\t\t\t\"type\": res.Type,\n\t\t\t}).WithError(err).Fatal(\"Couldn't read public key packet\")\n\t\t}\n\t\t_, ok := pkPacket.(*packet.PublicKey)\n\t\tif !ok {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"file\": file,\n\t\t\t}).Fatal(\"Public key is not a public key\")\n\t\t}\n\t\treturn pkPacket\n\t}\n\tif res.Type != openpgp.PrivateKeyType {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"file\": file,\n\t\t\t\"type\": res.Type,\n\t\t}).Fatal(\"Private key file didn't contain private key\")\n\t}\n\tpkReader := packet.NewReader(res.Body)\n\tpkPacket, err := pkReader.Next()\n\tif res.Type != openpgp.PrivateKeyType {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"file\": file,\n\t\t\t\"type\": res.Type,\n\t\t}).WithError(err).Fatal(\"Couldn't read private key packet\")\n\t}\n\t_, ok := pkPacket.(*packet.PrivateKey)\n\tif !ok {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"file\": file,\n\t\t}).Fatal(\"Private key is not a private key\")\n\t}\n\treturn pkPacket\n}", "func loadFile(name string) *msg.Request {\n\tfile, err := os.Open(name)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tsource, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn &msg.Request{\n\t\tAction: msg.ParseAst,\n\t\tContent: string(source),\n\t}\n}", "func TestPacketReaderReadPacketHeader(t *testing.T) {\n\n//\tstream, err1 := os.Open(packetReaderPath)\n//\tif err1 != nil {\n//\t\tt.Errorf(\"i/o error on open: err = %+v\", err1)\n//\t\treturn\n//\t}\n//\tdefer stream.Close()\n\n//\tcacheReader := bufio.NewReader(stream)\n\n//\tpacket, _ := ioutil.ReadAll(cacheReader)\n\n//\tmemReader := bytes.NewReader(packet)\n\n//\tpktReader := NewPacketReader(memReader)\n//\tpktHeader , _ := pktReader.ReadPacketHeader()\n\n//\tt.Logf(\"pktHeader = %+v\", pktHeader)\n\n//\tmsgHeader, _ := pktReader.ReadPackedMessage()\n\n//\tt.Logf(\"msgHeader = %+v\", msgHeader)\n\n}", "func (c *PacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {\n\tif !c.ok() {\n\t\treturn 0, nil, syscall.EINVAL\n\t}\n\n\tc.mux.Lock()\n\tdeadline := c.deadline\n\treadDeadline := c.readDeadline\n\tc.mux.Unlock()\n\n\tselect {\n\tcase pp := <-c.packets:\n\t\treturn copy(p, pp.buf), pp.addr, nil\n\tcase <-readDeadline:\n\t\treturn 0, nil, ErrDeadline\n\tcase <-deadline:\n\t\treturn 0, nil, ErrDeadline\n\t}\n}", "func TestReadFromPcap(t *testing.T) {\n\ticmpPackets := make(chan gopacket.Packet, 100)\n\tipsecPackets := make(chan gopacket.Packet, 100)\n\tinitChannels(icmpPackets, ipsecPackets)\n\n\tquit := make(chan bool)\n\tcaptureReady := make(chan bool)\n\n\terr := capture(500, quit, captureReady, \"/test.pcap\")\n\tif err.Error() != \"/test.pcap: No such file or directory\" {\n\t\tt.Error(\"Tried reading a pcap file that doesn't exist. Didn't get the correct error. Got\", err, \"instead.\")\n\t}\n\tlog.Println(err)\n}", "func PacketSeqFromGoPacket(packet gopacket.Packet, outerLength int64, bpf *BPF, defragger *IPDefragger) *PacketSequence {\n\tps := &PacketSequence{}\n\n\tvar ipMetric *IPMetric\n\tpacket, ipMetric = ProcessGoPacket(packet, bpf, defragger)\n\tif packet == nil {\n\t\treturn ps\n\t}\n\n\tif packet.ErrorLayer() != nil {\n\t\tlogging.GetLogger().Debugf(\"Decoding or partial decoding error : %s\\n\", packet.Dump())\n\t}\n\n\tif packet.LinkLayer() == nil && packet.NetworkLayer() == nil {\n\t\tlogging.GetLogger().Debugf(\"Unknown packet : %s\\n\", packet.Dump())\n\t\treturn ps\n\t}\n\n\tpacketLayers := packet.Layers()\n\tmetadata := packet.Metadata()\n\n\tvar topLayer = packetLayers[0]\n\n\tif outerLength == 0 {\n\t\tif ethernetPacket, ok := topLayer.(*layers.Ethernet); ok {\n\t\t\tif metadata != nil && metadata.Length > 0 {\n\t\t\t\touterLength = int64(metadata.Length)\n\t\t\t} else {\n\t\t\t\touterLength = getLinkLayerLength(ethernetPacket)\n\t\t\t}\n\t\t} else if ipv4Packet, ok := topLayer.(*layers.IPv4); ok {\n\t\t\touterLength = int64(ipv4Packet.Length)\n\t\t} else if ipv6Packet, ok := topLayer.(*layers.IPv6); ok {\n\t\t\touterLength = int64(ipv6Packet.Length)\n\t\t}\n\t}\n\n\tpacketData := packet.Data()\n\n\t// length of the encapsulation header + the inner packet\n\ttopLayerIndex, topLayerOffset, topLayerLength := 0, 0, int(outerLength)\n\n\toffset, length := topLayerOffset, topLayerLength\n\tfor i, layer := range packetLayers {\n\t\tlength -= len(layer.LayerContents())\n\t\toffset += len(layer.LayerContents())\n\n\t\tswitch layer.LayerType() {\n\t\tcase layers.LayerTypeGRE:\n\t\t\t// If the next layer type is MPLS, we don't\n\t\t\t// creates the tunneling packet at this level, but at the next one.\n\t\t\tif i < len(packetLayers)-2 && packetLayers[i+1].LayerType() == layers.LayerTypeMPLS {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfallthrough\n\t\t\t// We don't split on vlan layers.LayerTypeDot1Q\n\t\tcase layers.LayerTypeVXLAN, layers.LayerTypeMPLS, layers.LayerTypeGeneve:\n\t\t\tp := &Packet{\n\t\t\t\tGoPacket: packet,\n\t\t\t\tLayers: packetLayers[topLayerIndex : i+1],\n\t\t\t\tData: packetData[topLayerOffset:],\n\t\t\t\tLength: int64(topLayerLength),\n\t\t\t}\n\t\t\t// As this is the top flow, we can use the layer pointer from GoPacket\n\t\t\t// This avoid to parse them later.\n\t\t\tif len(ps.Packets) == 0 {\n\t\t\t\tp.networkLayer = packet.NetworkLayer()\n\t\t\t\tp.transportLayer = packet.TransportLayer()\n\t\t\t}\n\n\t\t\tps.Packets = append(ps.Packets, p)\n\n\t\t\ttopLayerIndex = i + 1\n\t\t\ttopLayerLength = length\n\t\t\ttopLayerOffset = offset\n\t\t}\n\t}\n\n\tp := &Packet{\n\t\tGoPacket: packet,\n\t\tLayers: packetLayers[topLayerIndex:],\n\t\tData: packetData[topLayerOffset:],\n\t\tLength: int64(topLayerLength),\n\t\tIPMetric: ipMetric,\n\t}\n\tif len(ps.Packets) == 0 {\n\t\t// As this is the top flow, we can use the layer pointer from GoPacket\n\t\t// This avoid to parse them later.\n\t\tp.networkLayer = packet.NetworkLayer()\n\t\tp.transportLayer = packet.TransportLayer()\n\t}\n\n\tps.Packets = append(ps.Packets, p)\n\n\treturn ps\n}", "func readSource(filename string, src interface{}) ([]byte, error) {\n\tif src != nil {\n\t\tswitch s := src.(type) {\n\t\tcase string:\n\t\t\treturn []byte(s), nil\n\t\tcase []byte:\n\t\t\treturn s, nil\n\t\tcase *bytes.Buffer:\n\t\t\tif s != nil {\n\t\t\t\treturn s.Bytes(), nil\n\t\t\t}\n\t\tcase io.Reader:\n\t\t\tvar buf bytes.Buffer\n\t\t\tif _, err := io.Copy(&buf, s); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn buf.Bytes(), nil\n\t\t}\n\t\treturn nil, errors.New(\"invalid source\")\n\t}\n\treturn ioutil.ReadFile(filename)\n}", "func srcFile(path string) string {\n\treturn \"file://\" + file(path)\n}", "func readSource(filename string, src interface{}) ([]byte, error) {\n\tif src != nil {\n\t\tswitch s := src.(type) {\n\t\t\tcase string:\n\t\t\treturn []byte(s), nil\n\t\t\tcase []byte:\n\t\t\treturn s, nil\n\t\t\tcase *bytes.Buffer:\n\t\t\t// is io.Reader, but src is already available in []byte form\n\t\t\tif s != nil {\n\t\t\t\treturn s.Bytes(), nil\n\t\t\t}\n\t\t\tcase io.Reader:\n\t\t\tvar buf bytes.Buffer\n\t\t\tif _, err := io.Copy(&buf, s); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn buf.Bytes(), nil\n\t\t}\n\t\treturn nil, errors.New(\"invalid source\")\n\t}\n\treturn ioutil.ReadFile(filename)\n}", "func (c *PacketConn) ReadFrom(p []byte) (int, net.Addr, error) {\n\treturn c.buffer.ReadFrom(p)\n}", "func readSource(filename string, src interface{}) ([]byte, error) {\n\tif src != nil {\n\t\tswitch s := src.(type) {\n\t\tcase string:\n\t\t\treturn []byte(s), nil\n\t\tcase []byte:\n\t\t\treturn s, nil\n\t\tcase *bytes.Buffer:\n\t\t\t// is io.Reader, but src is already available in []byte form\n\t\t\tif s != nil {\n\t\t\t\treturn s.Bytes(), nil\n\t\t\t}\n\t\tcase io.Reader:\n\t\t\tvar buf bytes.Buffer\n\t\t\t_, err := io.Copy(&buf, s)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn buf.Bytes(), nil\n\t\tdefault:\n\t\t\treturn nil, errors.New(\"invalid source\")\n\t\t}\n\t}\n\n\treturn ioutil.ReadFile(filename)\n}", "func (s *baseNode) GetSource() []byte {\n\tif s.nodeType == NodeTypePackage {\n\t\tvar sources [][]byte\n\t\tfor _, rawFile := range s.realMe.(*Package).rawFiles {\n\t\t\tsources = append(sources, rawFile.source)\n\t\t}\n\t\treturn bytes.Join(sources, []byte{'\\n'})\n\t} else if s.nodeType == NodeTypeFile {\n\t\treturn s.rawFile.source\n\t}\n\n\tbase := token.Pos(s.rawFile.Base())\n\treturn s.rawFile.source[s.node.Pos()-base : s.node.End()-base]\n}", "func openCif(fp string) *Entry {\n\te, err := Read(gzReader(fp))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn e\n}", "func (p *Packet) GetSourceUIP() (SourceUIP [16]byte) {\n}", "func NewFileSource(path string) (*MapSource, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// changed how we handled a deferred file closure due to go lint security check https://github.com/securego/gosec/issues/512#issuecomment-675286833\n\tdefer func() {\n\t\tif cerr := f.Close(); cerr != nil {\n\t\t\tfmt.Printf(\"Error closing file: %s\\n\", cerr)\n\t\t}\n\t}()\n\tb, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm, err := NewJSONSource(b)\n\tif err == nil {\n\t\treturn m, nil\n\t}\n\tm, err = NewYAMLSource(b)\n\tif err == nil {\n\t\treturn m, nil\n\t}\n\treturn nil, fmt.Errorf(\"could not determine file format for %s\", path)\n}", "func readPK12(file string) ([]byte, error) {\n\tosFile, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treader := bufio.NewReaderSize(osFile, 4)\n\n\treturn ioutil.ReadAll(reader)\n}", "func (d PacketData) ReadFrom(src *buffer.Buffer, count int) int {\n\ttoRead := int64(count)\n\tif toRead > src.Size() {\n\t\ttoRead = src.Size()\n\t}\n\tclone := src.Clone()\n\tclone.Truncate(toRead)\n\td.pk.buf.Merge(&clone)\n\tsrc.TrimFront(toRead)\n\treturn int(toRead)\n}", "func (p *IPPacket) Src() [4]byte {\n\treturn [4]byte{(*p)[12], (*p)[13], (*p)[14], (*p)[15]}\n}", "func (ev *Evaler) Source(fname string) error {\n\tsrc, err := readFileUTF8(fname)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ev.SourceText(src)\n}", "func (ev *Evaler) Source(fname string) error {\n\tsrc, err := readFileUTF8(fname)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ev.SourceText(src)\n}", "func InjectPacket(pp *PacketParams, g *graph.Graph) (string, error) {\n\tsrcIP := getIP(pp.SrcIP)\n\tif srcIP == nil {\n\t\treturn \"\", errors.New(\"Source Node doesn't have proper IP\")\n\t}\n\n\tdstIP := getIP(pp.DstIP)\n\tif dstIP == nil {\n\t\treturn \"\", errors.New(\"Destination Node doesn't have proper IP\")\n\t}\n\n\tsrcMAC, err := net.ParseMAC(pp.SrcMAC)\n\tif err != nil || srcMAC == nil {\n\t\treturn \"\", errors.New(\"Source Node doesn't have proper MAC\")\n\t}\n\n\tdstMAC, err := net.ParseMAC(pp.DstMAC)\n\tif err != nil || dstMAC == nil {\n\t\treturn \"\", errors.New(\"Destination Node doesn't have proper MAC\")\n\t}\n\n\tg.RLock()\n\n\tsrcNode := g.GetNode(pp.SrcNodeID)\n\tif srcNode == nil {\n\t\tg.RUnlock()\n\t\treturn \"\", errors.New(\"Unable to find source node\")\n\t}\n\n\ttid, err := srcNode.GetFieldString(\"TID\")\n\tif err != nil {\n\t\tg.RUnlock()\n\t\treturn \"\", errors.New(\"Source node has no TID\")\n\t}\n\n\tifName, err := srcNode.GetFieldString(\"Name\")\n\tif err != nil {\n\t\tg.RUnlock()\n\t\treturn \"\", errors.New(\"Source node has no name\")\n\t}\n\n\t_, nsPath, err := topology.NamespaceFromNode(g, srcNode)\n\n\tg.RUnlock()\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trawSocket, err := common.NewRawSocketInNs(nsPath, ifName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar l []gopacket.SerializableLayer\n\tethLayer := &layers.Ethernet{SrcMAC: srcMAC, DstMAC: dstMAC}\n\tpayload := gopacket.Payload([]byte(pp.Payload))\n\n\tswitch pp.Type {\n\tcase \"icmp4\":\n\t\tethLayer.EthernetType = layers.EthernetTypeIPv4\n\t\tipLayer := &layers.IPv4{Version: 4, SrcIP: srcIP, DstIP: dstIP, Protocol: layers.IPProtocolICMPv4}\n\t\ticmpLayer := &layers.ICMPv4{\n\t\t\tTypeCode: layers.CreateICMPv4TypeCode(layers.ICMPv4TypeEchoRequest, 0),\n\t\t\tId: uint16(pp.ID),\n\t\t}\n\t\tl = append(l, ethLayer, ipLayer, icmpLayer, payload)\n\tcase \"icmp6\":\n\t\tethLayer.EthernetType = layers.EthernetTypeIPv6\n\t\tipLayer := &layers.IPv6{Version: 6, SrcIP: srcIP, DstIP: dstIP, NextHeader: layers.IPProtocolICMPv6}\n\t\ticmpLayer := &layers.ICMPv6{\n\t\t\tTypeCode: layers.CreateICMPv6TypeCode(layers.ICMPv6TypeEchoRequest, 0),\n\t\t\tTypeBytes: []byte{byte(pp.ID & int64(0xFF00) >> 8), byte(pp.ID & int64(0xFF)), 0, 0},\n\t\t}\n\t\ticmpLayer.SetNetworkLayerForChecksum(ipLayer)\n\t\tl = append(l, ethLayer, ipLayer, icmpLayer, payload)\n\tdefault:\n\t\trawSocket.Close()\n\t\treturn \"\", fmt.Errorf(\"Unsupported traffic type '%s'\", pp.Type)\n\t}\n\n\tbuffer := gopacket.NewSerializeBuffer()\n\tif err := gopacket.SerializeLayers(buffer, options, l...); err != nil {\n\t\trawSocket.Close()\n\t\treturn \"\", fmt.Errorf(\"Error while generating %s packet: %s\", pp.Type, err.Error())\n\t}\n\n\tpacketData := buffer.Bytes()\n\tpacket := gopacket.NewPacket(packetData, layers.LayerTypeEthernet, gopacket.Default)\n\tflowKey := flow.KeyFromGoPacket(&packet, \"\").String()\n\tflow := flow.NewFlow()\n\tflow.Init(flowKey, common.UnixMillis(time.Now()), &packet, int64(len(packetData)), tid, \"\", 0, 0)\n\n\tgo func() {\n\t\tdefer rawSocket.Close()\n\n\t\tfor i := int64(0); i < pp.Count; i++ {\n\t\t\tlogging.GetLogger().Debugf(\"Injecting packet on interface %s\", ifName)\n\n\t\t\tif _, err := syscall.Write(rawSocket.GetFd(), packetData); err != nil {\n\t\t\t\tlogging.GetLogger().Errorf(\"Write error: %s\", err.Error())\n\t\t\t}\n\n\t\t\tif i != pp.Count-1 {\n\t\t\t\ttime.Sleep(time.Millisecond * time.Duration(pp.Interval))\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn flow.TrackingID, nil\n}", "func SlurpData(t *testing.T, source string) []byte {\n\tdata, err := ioutil.ReadFile(source)\n\trequire.NoError(t, err)\n\treturn data\n}", "func (m *Mapper) ReadPacket(pkt gopacket.Packet) {\n\t// ether layer\n\tetherLayer := pkt.Layer(layers.LayerTypeEthernet)\n\tif etherLayer == nil {\n\t\treturn\n\t}\n\t// ip layer\n\tipLayer := pkt.Layer(layers.LayerTypeIPv4)\n\tif ipLayer == nil {\n\t\treturn\n\t}\n\tipHead := ipLayer.(*layers.IPv4)\n\t// tcp/udp layer\n\ttcpLayer := pkt.Layer(layers.LayerTypeTCP)\n\tvar srcPort, dstPort string\n\tprotocol := \"\"\n\tif tcpLayer != nil {\n\t\ttcp := tcpLayer.(*layers.TCP)\n\t\tprotocol = \"tcp\"\n\t\tsrcPort = strconv.Itoa(int(tcp.SrcPort))\n\t\tdstPort = strconv.Itoa(int(tcp.DstPort))\n\t}\n\tudpLayer := pkt.Layer(layers.LayerTypeUDP)\n\tif udpLayer != nil {\n\t\tudp := udpLayer.(*layers.UDP)\n\t\tprotocol = \"udp\"\n\t\tsrcPort = strconv.Itoa(int(udp.SrcPort))\n\t\tdstPort = strconv.Itoa(int(udp.DstPort))\n\t}\n\t//if both are nil,then protocol unknown, skip handling.\n\tif tcpLayer == nil && udpLayer == nil {\n\t\treturn\n\t}\n\n\t// now handling this packet\n\tkey := genKey(protocol, ipHead.SrcIP.String(), ipHead.DstIP.String(), srcPort, dstPort, m.isBiFlow)\n\n\t//first check flow packet size limit\n\tif _, ok := m.mmap[key]; ok && len(*m.mmap[key]) >= config.Global.LimitPacketsPerFlow {\n\t\treturn\n\t}\n\n\t//save it to its flow.\n\tif _, ok := m.mmap[key]; !ok { // if not new\n\t\t(m.mmap[key]) = &[]*gopacket.Packet{}\n\t}\n\t*(m.mmap[key]) = append(*(m.mmap[key]), &pkt)\n\t//statics\n\tm.countStatics++\n}", "func ParsePacket(data []byte) (OspfPacket, error) {\n\tvar p OspfPacket\n\n\tp.Header = parseHeader(data[:ospfv2HeaderLen])\n\n\t// ospfLayer := p.Layer(layers.LayerTypeOSPF)\n\t// if ospfLayer != nil {\n\t// \tfmt.Println(\"OSPF Layer detected\")\n\t// \tospf, ok := ospfLayer.(*layers.OSPFv2)\n\n\t// \tif !ok {\n\t// \t\treturn fmt.Errorf(\"Failed to parse OSPF at packet TIMESTAMP: %v\", pck.timestamp)\n\t// \t}\n\n\t// \tpck.routerID = util.Int2Ip(ospf.RouterID)\n\t// \tpck.area = util.Int2Ip(ospf.AreaID)\n\t// \tpck.length = int(ospf.PacketLength)\n\n\t// \tcontent := ospf.Content.(layers.LSUpdate)\n\n\t// \tfmt.Printf(\"%v\\n\", content.NumOfLSAs)\n\t// \tstart := pck.fullLen - pck.length + ospfv2HeaderLen\n\t// \tfmt.Printf(\"%v\\n\", p.Data()[start:])\n\t// }\n\n\treturn p, nil\n}", "func ReadPacket(r io.Reader) (*ControlPacket, error) {\n\tt := [1]byte{}\n\t_, err := io.ReadFull(r, t[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// cp := NewControlPacket(PacketType(t[0] >> 4))\n\t// if cp == nil {\n\t// \treturn nil, fmt.Errorf(\"invalid packet type requested, %d\", t[0]>>4)\n\t// }\n\n\tpt := t[0] >> 4\n\tcp := &ControlPacket{FixedHeader: FixedHeader{Type: pt}}\n\tswitch pt {\n\tcase CONNECT:\n\t\tcp.Content = &Connect{\n\t\t\tProtocolName: \"MQTT\",\n\t\t\tProtocolVersion: 5,\n\t\t\tProperties: &Properties{},\n\t\t}\n\tcase CONNACK:\n\t\tcp.Content = &Connack{Properties: &Properties{}}\n\tcase PUBLISH:\n\t\tcp.Content = &Publish{Properties: &Properties{}}\n\tcase PUBACK:\n\t\tcp.Content = &Puback{Properties: &Properties{}}\n\tcase PUBREC:\n\t\tcp.Content = &Pubrec{Properties: &Properties{}}\n\tcase PUBREL:\n\t\tcp.Flags = 2\n\t\tcp.Content = &Pubrel{Properties: &Properties{}}\n\tcase PUBCOMP:\n\t\tcp.Content = &Pubcomp{Properties: &Properties{}}\n\tcase SUBSCRIBE:\n\t\tcp.Flags = 2\n\t\tcp.Content = &Subscribe{\n\t\t\tSubscriptions: make(map[string]SubOptions),\n\t\t\tProperties: &Properties{},\n\t\t}\n\tcase SUBACK:\n\t\tcp.Content = &Suback{Properties: &Properties{}}\n\tcase UNSUBSCRIBE:\n\t\tcp.Flags = 2\n\t\tcp.Content = &Unsubscribe{Properties: &Properties{}}\n\tcase UNSUBACK:\n\t\tcp.Content = &Unsuback{Properties: &Properties{}}\n\tcase PINGREQ:\n\t\tcp.Content = &Pingreq{}\n\tcase PINGRESP:\n\t\tcp.Content = &Pingresp{}\n\tcase DISCONNECT:\n\t\tcp.Content = &Disconnect{Properties: &Properties{}}\n\tcase AUTH:\n\t\tcp.Flags = 1\n\t\tcp.Content = &Auth{Properties: &Properties{}}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown packet type %d requested\", pt)\n\t}\n\n\tcp.Flags = t[0] & 0xF\n\tif cp.Type == PUBLISH {\n\t\tcp.Content.(*Publish).QoS = (cp.Flags & 0x6) >> 1\n\t}\n\tvbi, err := getVBI(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcp.remainingLength, err = decodeVBI(vbi)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar content bytes.Buffer\n\tcontent.Grow(cp.remainingLength)\n\n\tn, err := io.CopyN(&content, r, int64(cp.remainingLength))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif n != int64(cp.remainingLength) {\n\t\treturn nil, fmt.Errorf(\"failed to read packet, expected %d bytes, read %d\", cp.remainingLength, n)\n\t}\n\terr = cp.Content.Unpack(&content)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cp, nil\n}", "func (c *packetConn) ReadFrom(b []byte) (int, net.Addr, error) {\n\tn, addr, err := c.PacketConn.ReadFrom(b)\n\tif err != nil {\n\t\treturn n, addr, err\n\t}\n\tb, err = Unpack(b, b[:n], c.AEAD)\n\treturn len(b), addr, err\n}", "func (c *packetConn) ReadFrom(b []byte) (int, net.Addr, error) {\n\tcipherBuf := newUDPBuffer()\n\tdefer freeUDPBuffer(cipherBuf)\n\tn, err := c.UDPConn.Read(cipherBuf)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\t// Avoid partially overlapping the plaintext and cipher slices since `Unpack` skips the salt\n\t// when calling `AEAD.Open` (see https://golang.org/pkg/crypto/cipher/#AEAD).\n\tbuf, err := shadowaead.Unpack(cipherBuf[c.cipher.SaltSize():], cipherBuf[:n], c.cipher)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\tsocksSrcAddr := socks.SplitAddr(buf)\n\tif socksSrcAddr == nil {\n\t\treturn 0, nil, errors.New(\"Failed to read source address\")\n\t}\n\tsrcAddr := NewAddr(socksSrcAddr.String(), \"udp\")\n\tn = copy(b, buf[len(socksSrcAddr):]) // Strip the SOCKS source address\n\tif len(b) < len(buf)-len(socksSrcAddr) {\n\t\treturn n, srcAddr, io.ErrShortBuffer\n\t}\n\treturn n, srcAddr, nil\n}", "func printPacket(packet rpc.LogMessage, prefix string, isCompressed bool, compressor compressor.Compressor) {\n\tif isCompressed {\n\t\tbuffer, err := compressor.Decompress(packet.Buffer)\n\t\tif err != nil {\n\t\t\tlog.Panic(\"Packet decompress failed\")\n\t\t}\n\t\tpacket.Buffer = buffer\n\t}\n\twp := uint64(0)\n\tfor i, info := range packet.Info {\n\t\tfilename := packet.Files.MapTable[packet.Files.Indexes[i]]\n\t\tlog.Printf(\"[%s:%s] %s (size: %d)\\n\", prefix, filename, string(packet.Buffer[wp:wp+info.Length]), len(packet.Buffer))\n\t\twp += info.Length\n\t}\n}", "func (ti *TypeInfo) NodeSrc(n ast.Node) []byte {\n\tstart := n.Pos()\n\tend := n.End()\n\tstartPosition := ti.FileSet.Position(start)\n\tendPosition := ti.FileSet.Position(end)\n\treturn ti.FileBytes[startPosition.Offset:endPosition.Offset]\n}", "func FileSyscallConn(f *os.File,) (syscall.RawConn, error)", "func Open(file string) (Data, error) {\n\n\tcfile := C.CString(file)\n\n\tiptcData := C.iptc_data_new_from_jpeg(cfile)\n\n\tC.free(unsafe.Pointer(cfile))\n\n\tif iptcData == nil {\n\t\treturn nil, fmt.Errorf(ErrNoIptcData.Error(), file)\n\t}\n\n\tdefer func() {\n\t\tC.iptc_data_unref(iptcData)\n\t}()\n\n\treturn parseIptcData(iptcData)\n}", "func (s *scpSession) getFile(localFile string) error {\n\t//var err error\n\tvar msg string\n\tvar fields []string\n\n\treader := bufio.NewReader(s.out)\n\n\tbuffer, n, err := s.readMessage(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmsgType := string(buffer[0])\n\n\tif msgType == msgCopyFile {\n\t\tmsg = string(buffer[1 : n-1])\n\t\tfields = strings.Split(msg, \" \")\n\n\t\treturn s.readFileData(reader, localFile, os.FileMode(cast.ToUint32(fields[0])), cast.ToInt(fields[1]))\n\t} else if buffer[0] == msgErr || buffer[0] == msgFatalErr {\n\t\treturn fmt.Errorf(\"%s\", string(buffer[1:n]))\n\t}\n\n\treturn fmt.Errorf(\"expected message type '%s', received '%s'\", msgCopyFile, msgType)\n}", "func readPacket(reader io.Reader) (*Packet, int, error) {\n\tidentifier, length, read, err := readHeader(reader)\n\tif err != nil {\n\t\treturn nil, read, err\n\t}\n\n\tp := &Packet{\n\t\tIdentifier: identifier,\n\t}\n\n\tp.Data = new(bytes.Buffer)\n\tp.Children = make([]*Packet, 0, 2)\n\tp.Value = nil\n\n\tif p.TagType == TypeConstructed {\n\t\t// TODO: if universal, ensure tag type is allowed to be constructed\n\n\t\t// Track how much content we've read\n\t\tcontentRead := 0\n\t\tfor {\n\t\t\tif length != LengthIndefinite {\n\t\t\t\t// End if we've read what we've been told to\n\t\t\t\tif contentRead == length {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\t// Detect if a packet boundary didn't fall on the expected length\n\t\t\t\tif contentRead > length {\n\t\t\t\t\treturn nil, read, fmt.Errorf(\"expected to read %d bytes, read %d\", length, contentRead)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Read the next packet\n\t\t\tchild, r, err := readPacket(reader)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, read, err\n\t\t\t}\n\t\t\tcontentRead += r\n\t\t\tread += r\n\n\t\t\t// Test is this is the EOC marker for our packet\n\t\t\tif isEOCPacket(child) {\n\t\t\t\tif length == LengthIndefinite {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\treturn nil, read, errors.New(\"eoc child not allowed with definite length\")\n\t\t\t}\n\n\t\t\t// Append and continue\n\t\t\tp.AppendChild(child)\n\t\t}\n\t\treturn p, read, nil\n\t}\n\n\tif length == LengthIndefinite {\n\t\treturn nil, read, errors.New(\"indefinite length used with primitive type\")\n\t}\n\n\t// Read definite-length content\n\tif MaxPacketLengthBytes > 0 && int64(length) > MaxPacketLengthBytes {\n\t\treturn nil, read, fmt.Errorf(\"length %d greater than maximum %d\", length, MaxPacketLengthBytes)\n\t}\n\tcontent := make([]byte, length)\n\tif length > 0 {\n\t\t_, err := io.ReadFull(reader, content)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn nil, read, io.ErrUnexpectedEOF\n\t\t\t}\n\t\t\treturn nil, read, err\n\t\t}\n\t\tread += length\n\t}\n\n\tif p.ClassType == ClassUniversal {\n\t\tp.Data.Write(content)\n\t\tp.ByteValue = content\n\n\t\tswitch p.Tag {\n\t\tcase TagEOC:\n\t\tcase TagBoolean:\n\t\t\tval, _ := ParseInt64(content)\n\n\t\t\tp.Value = val != 0\n\t\tcase TagInteger:\n\t\t\tp.Value, _ = ParseInt64(content)\n\t\tcase TagBitString:\n\t\tcase TagOctetString:\n\t\t\t// the actual string encoding is not known here\n\t\t\t// (e.g. for LDAP content is already an UTF8-encoded\n\t\t\t// string). Return the data without further processing\n\t\t\tp.Value = DecodeString(content)\n\t\tcase TagNULL:\n\t\tcase TagObjectIdentifier:\n\t\tcase TagObjectDescriptor:\n\t\tcase TagExternal:\n\t\tcase TagRealFloat:\n\t\t\tp.Value, err = ParseReal(content)\n\t\tcase TagEnumerated:\n\t\t\tp.Value, _ = ParseInt64(content)\n\t\tcase TagEmbeddedPDV:\n\t\tcase TagUTF8String:\n\t\t\tval := DecodeString(content)\n\t\t\tif !utf8.Valid([]byte(val)) {\n\t\t\t\terr = errors.New(\"invalid UTF-8 string\")\n\t\t\t} else {\n\t\t\t\tp.Value = val\n\t\t\t}\n\t\tcase TagRelativeOID:\n\t\tcase TagSequence:\n\t\tcase TagSet:\n\t\tcase TagNumericString:\n\t\tcase TagPrintableString:\n\t\t\tval := DecodeString(content)\n\t\t\tif err = isPrintableString(val); err == nil {\n\t\t\t\tp.Value = val\n\t\t\t}\n\t\tcase TagT61String:\n\t\tcase TagVideotexString:\n\t\tcase TagIA5String:\n\t\t\tval := DecodeString(content)\n\t\t\tfor i, c := range val {\n\t\t\t\tif c >= 0x7F {\n\t\t\t\t\terr = fmt.Errorf(\"invalid character for IA5String at pos %d: %c\", i, c)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\tp.Value = val\n\t\t\t}\n\t\tcase TagUTCTime:\n\t\tcase TagGeneralizedTime:\n\t\t\tp.Value, err = ParseGeneralizedTime(content)\n\t\tcase TagGraphicString:\n\t\tcase TagVisibleString:\n\t\tcase TagGeneralString:\n\t\tcase TagUniversalString:\n\t\tcase TagCharacterString:\n\t\tcase TagBMPString:\n\t\t}\n\t} else {\n\t\tp.Data.Write(content)\n\t}\n\n\treturn p, read, err\n}", "func ReadRawTCPPacketsFromPcap(pcapfile string) ([]gopacket.Packet, error) {\n\tvar packets []gopacket.Packet\n\t_, rawPackets, err := ReadPacketsFromPcap(pcapfile, layers.IPProtocolTCP, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, val := range rawPackets {\n\t\tpackets = append(packets, val.(gopacket.Packet))\n\t}\n\treturn packets, nil\n}", "func (conn *PacketPipe) ReadFrom(p []byte) (n int, addr net.Addr, err error) {\n\tn, err = conn.Read(p)\n\taddr = conn.RemoteAddr()\n\treturn\n}", "func (p *packetConn) ReadFrom(b []byte) (int, net.Addr, error) {\n\treturn 0, nil, ErrNotImplemented\n}", "func network(filePath string) (Network, error) {\n\tvar network Network\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn network, err\n\t}\n\tdefer func() {\n\t\tif err := file.Close(); err != nil {\n\t\t\tlog.Error(\"Failed to close file: %s, error: %v\", filePath, err)\n\t\t}\n\t}()\n\n\tsc := bufio.NewScanner(file)\n\tsc.Split(bufio.ScanLines)\n\tsc.Scan() // scan first header line\n\tsc.Scan() // scan second header line\n\tfor sc.Scan() {\n\t\tws := bufio.NewScanner(strings.NewReader(sc.Text()))\n\t\tws.Split(bufio.ScanWords)\n\t\twords := make([]string, 0, 18)\n\t\tfor ws.Scan() {\n\t\t\twords = append(words, ws.Text())\n\t\t}\n\t\tif len(words) < 13 {\n\t\t\tlog.Debug(\"apparently malformed line: %s\", sc.Text())\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(words[0], \"lo\") { // ignoring loopback\n\t\t\tcontinue\n\t\t}\n\n\t\trxBytes, err := strconv.Atoi(words[1])\n\t\tif err != nil {\n\t\t\tlog.Debug(\"apparently malformed line %q. Cause: %s\", sc.Text(), err.Error())\n\t\t\tcontinue\n\t\t}\n\t\trxPackets, err := strconv.Atoi(words[2])\n\t\tif err != nil {\n\t\t\tlog.Debug(\"apparently malformed line %q. Cause: %s\", sc.Text(), err.Error())\n\t\t\tcontinue\n\t\t}\n\t\trxErrors, err := strconv.Atoi(words[3])\n\t\tif err != nil {\n\t\t\tlog.Debug(\"apparently malformed line %q. Cause: %s\", sc.Text(), err.Error())\n\t\t\tcontinue\n\t\t}\n\t\trxDropped, err := strconv.Atoi(words[4])\n\t\tif err != nil {\n\t\t\tlog.Debug(\"apparently malformed line %q. Cause: %s\", sc.Text(), err.Error())\n\t\t\tcontinue\n\t\t}\n\t\ttxBytes, err := strconv.Atoi(words[9])\n\t\tif err != nil {\n\t\t\tlog.Debug(\"apparently malformed line %q. Cause: %s\", sc.Text(), err.Error())\n\t\t\tcontinue\n\t\t}\n\t\ttxPackets, err := strconv.Atoi(words[10])\n\t\tif err != nil {\n\t\t\tlog.Debug(\"apparently malformed line %q. Cause: %s\", sc.Text(), err.Error())\n\t\t\tcontinue\n\t\t}\n\t\ttxErrors, err := strconv.Atoi(words[11])\n\t\tif err != nil {\n\t\t\tlog.Debug(\"apparently malformed line %q. Cause: %s\", sc.Text(), err.Error())\n\t\t\tcontinue\n\t\t}\n\t\ttxDropped, err := strconv.Atoi(words[12])\n\t\tif err != nil {\n\t\t\tlog.Debug(\"apparently malformed line %q. Cause: %s\", sc.Text(), err.Error())\n\t\t\tcontinue\n\t\t}\n\n\t\tnetwork.RxBytes += int64(rxBytes)\n\t\tnetwork.RxDropped += int64(rxDropped)\n\t\tnetwork.RxErrors += int64(rxErrors)\n\t\tnetwork.RxPackets += int64(rxPackets)\n\t\tnetwork.TxBytes += int64(txBytes)\n\t\tnetwork.TxDropped += int64(txDropped)\n\t\tnetwork.TxErrors += int64(txErrors)\n\t\tnetwork.TxPackets += int64(txPackets)\n\t}\n\n\treturn network, nil\n}", "func (frpc *FakeRandomPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {\n\tif frpc.isClosed() {\n\t\treturn 0, nil, ErrClosedConnection\n\t}\n\n\tnum := rand.Int31n(10000) // Randomize metric name\n\tbuf := new(bytes.Buffer)\n\tswitch rand.Int31n(4) {\n\tcase 0: // Counter\n\t\tfmt.Fprintf(buf, \"statsd.tester.counter_%d:%f|c\\n\", num, rand.Float64()*100) // #nosec\n\tcase 1: // Gauge\n\t\tfmt.Fprintf(buf, \"statsd.tester.gauge_%d:%f|g\\n\", num, rand.Float64()*100) // #nosec\n\tcase 2: // Timer\n\t\tn := 10\n\t\tfor i := 0; i < n; i++ {\n\t\t\tfmt.Fprintf(buf, \"statsd.tester.timer_%d:%f|ms\\n\", num, rand.Float64()*100) // #nosec\n\t\t}\n\tcase 3: // Set\n\t\tfor i := 0; i < 10; i++ {\n\t\t\tfmt.Fprintf(buf, \"statsd.tester.set_%d:%d|s\\n\", num, rand.Int31n(9)+1) // #nosec\n\t\t}\n\tdefault:\n\t\tpanic(errors.New(\"unreachable\"))\n\t}\n\tn := copy(b, buf.Bytes())\n\treturn n, FakeAddr, nil\n}", "func (h *MemHome) Src(p string) map[string]*File {\n\tpkg := h.pkgs[p]\n\tif pkg == nil {\n\t\treturn nil\n\t}\n\n\tif len(pkg.files) == 0 {\n\t\treturn nil\n\t}\n\n\tret := make(map[string]*File)\n\tfor name, f := range pkg.files {\n\t\tpath := f.path\n\t\tif path == \"\" {\n\t\t\tpath = \"$\" + p + \"/\" + name\n\t\t}\n\n\t\tret[name] = &File{\n\t\t\tPath: path,\n\t\t\tName: name,\n\t\t\tReadCloser: f.Reader(),\n\t\t}\n\t}\n\n\treturn ret\n}", "func (b *DemoInstance) PacketIn(dpid net.HardwareAddr, pkt *ofp10.PacketIn) {\n\tlog.Println(\"PacketIn message received from:\", dpid, \"len:\", pkt.Len(), \"datalen:\", pkt.Data.Len(), \"hwsrc:\", pkt.Data.HWSrc, \"hwdst:\", pkt.Data.HWDst, pkt.Data.Ethertype)\n}", "func ReadPacket(r io.Reader) (*BasicPacket, error) {\n\tvar buff bytes.Buffer\n\ttr := io.TeeReader(r, &buff)\n\t// Read 8-byte packet header.\n\tvar headerBytes [packetHeaderSize]byte\n\tif _, err := io.ReadFull(tr, headerBytes[:]); err != nil {\n\t\treturn nil, trace.ConvertSystemError(err)\n\t}\n\n\t// Unmarshal packet header from the binary form.\n\tvar header PacketHeader\n\tif err := binary.Read(bytes.NewReader(headerBytes[:]), binary.BigEndian, &header); err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// Read packet data. Packet length includes header.\n\tdataBytes := make([]byte, header.Length-packetHeaderSize)\n\tif _, err := io.ReadFull(tr, dataBytes); err != nil {\n\t\treturn nil, trace.ConvertSystemError(err)\n\t}\n\n\tp := &BasicPacket{\n\t\theader: header,\n\t\tdata: dataBytes,\n\t\traw: buff,\n\t}\n\treturn p, nil\n}", "func Source(r io.Reader) YAMLOption {\n\tall, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn failed(err)\n\t}\n\treturn optionFunc(func(c *config) {\n\t\tc.sources = append(c.sources, source{bytes: all})\n\t})\n}", "func RawSource(r io.Reader) YAMLOption {\n\tall, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn failed(err)\n\t}\n\treturn optionFunc(func(c *config) {\n\t\tc.sources = append(c.sources, source{bytes: all, raw: true})\n\t})\n}", "func Open(peFile []byte) ([]byte, error) {\n\tportableExecutable, err := windows.GetPortableExecutable(peFile)\n\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tvar targetExecutable = windows.TargetExecutable{*portableExecutable}\n\t_, rawPayload, err := targetExecutable.GetPayload()\n\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\treturn rawPayload, nil\n}", "func FromBytes(rawBytes []byte, p Packet) error {\n\t// interface smuggling\n\tif pp, ok := p.(encoding.BinaryUnmarshaler); ok {\n\t\treturn pp.UnmarshalBinary(rawBytes)\n\t}\n\treader := bytes.NewReader(rawBytes)\n\treturn binary.Read(reader, binary.BigEndian, p)\n}", "func (c *conn) ReadFrom(b []byte) (n int, src net.Addr, err error) {\n\tvar cm *ipv4.ControlMessage\n\tfor {\n\t\tn, cm, src, err = c.PacketConn.ReadFrom(b)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif !cm.Dst.Equal(c.ip) {\n\t\t\tcontinue\n\t\t} else if cm.IfIndex != c.iface.Index {\n\t\t\tcontinue\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t}\n}", "func TransportFile(uuid string, owlh map[string]string, file string) {\n logs.Info(\"Get file \" + owlh[\"local_pcap_path\"] + \" from \" + owlh[\"name\"] + \" - \" + owlh[\"ip\"])\n TransportFileSSH(uuid, owlh, file)\n}", "func fileSource(filename string, i int) string {\n\treturn fmt.Sprintf(\"%s:%d\", filename, i)\n}", "func SourceFromPath(path string) (*Source, error) {\n in, err := os.Open(path)\n if err != nil {\n return nil, err\n }\n text, err := ioutil.ReadAll(in)\n if err != nil {\n return nil, err\n }\n return &Source{ Path : path, Text : text }, nil\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 (s *Scaffolder) AddPacket(\n\ttracer *placeholder.Tracer,\n\tmoduleName,\n\tpacketName string,\n\tpacketFields,\n\tackFields []string,\n\tnoMessage bool,\n) (sm xgenny.SourceModification, err error) {\n\tpath, err := gomodulepath.ParseAt(s.path)\n\tif err != nil {\n\t\treturn sm, err\n\t}\n\n\tmfName, err := multiformatname.NewName(moduleName, multiformatname.NoNumber)\n\tif err != nil {\n\t\treturn sm, err\n\t}\n\tmoduleName = mfName.Lowercase\n\n\tname, err := multiformatname.NewName(packetName)\n\tif err != nil {\n\t\treturn sm, err\n\t}\n\n\tif err := checkComponentValidity(s.path, moduleName, name, noMessage); err != nil {\n\t\treturn sm, err\n\t}\n\n\t// Module must implement IBC\n\tok, err := isIBCModule(s.path, moduleName)\n\tif err != nil {\n\t\treturn sm, err\n\t}\n\tif !ok {\n\t\treturn sm, fmt.Errorf(\"the module %s doesn't implement IBC module interface\", moduleName)\n\t}\n\n\t// Parse packet fields\n\tparsedPacketFields, err := field.ParseFields(packetFields, checkForbiddenPacketField)\n\tif err != nil {\n\t\treturn sm, err\n\t}\n\n\t// Parse acknowledgment fields\n\tparsedAcksFields, err := field.ParseFields(ackFields, checkGoReservedWord)\n\tif err != nil {\n\t\treturn sm, err\n\t}\n\n\t// Generate the packet\n\tvar (\n\t\tg *genny.Generator\n\t\topts = &ibc.PacketOptions{\n\t\t\tAppName: path.Package,\n\t\t\tModulePath: path.RawPath,\n\t\t\tModuleName: moduleName,\n\t\t\tOwnerName: owner(path.RawPath),\n\t\t\tPacketName: name,\n\t\t\tFields: parsedPacketFields,\n\t\t\tAckFields: parsedAcksFields,\n\t\t\tNoMessage: noMessage,\n\t\t}\n\t)\n\tg, err = ibc.NewPacket(tracer, opts)\n\tif err != nil {\n\t\treturn sm, err\n\t}\n\tsm, err = xgenny.RunWithValidation(tracer, g)\n\tif err != nil {\n\t\treturn sm, err\n\t}\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn sm, err\n\t}\n\treturn sm, s.finish(pwd, path.RawPath)\n}", "func (p *Plan) SourceFile() string {\n\treturn join(filepath.Base(p.Expand().Url))\n}", "func (f *Flow) initFromPacket(key, l2Key, l3Key uint64, packet *Packet, parentUUID string, uuids *UUIDs, opts *Opts) {\n\tnow := UnixMilli(packet.GoPacket.Metadata().CaptureInfo.Timestamp)\n\tf.Init(now, parentUUID, uuids)\n\n\tf.newLinkLayer(packet)\n\n\tf.LayersPath, f.Application = LayersPath(packet.Layers)\n\n\t// no network layer then no transport layer\n\tif err := f.newNetworkLayer(packet); err == nil {\n\t\tf.newTransportLayer(packet, opts)\n\t}\n\n\t// add optional application layer\n\tf.newApplicationLayer(packet, opts)\n\n\t// need to have as most variable filled as possible to get correct UUID\n\tf.setUUIDs(key, l2Key, l3Key)\n\n\t// update metrics\n\tf.Update(packet, opts)\n}", "func readPacket(r io.Reader) ([]byte, error) {\n\tvar buf [257]byte\n\tif _, err := r.Read(buf[:2]); err != nil {\n\t\tif err == io.EOF {\n\t\t\terr = io.ErrUnexpectedEOF\n\t\t}\n\t\treturn nil, err\n\t}\n\tpacket := buf[:2+buf[1]]\n\tif _, err := r.Read(packet[2:]); err != nil {\n\t\tif err == io.EOF {\n\t\t\terr = io.ErrUnexpectedEOF\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn packet, nil\n}", "func GospRequestFromFile(p *Parameters) error {\n\tf, err := os.Open(p.FileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tdec := json.NewDecoder(f)\n\tvar sr ServiceRequest\n\terr = dec.Decode(&sr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tchdirOrAbort(sr.UserData.Filename)\n\tLaunchPageGenerator(p, os.Stdout, &sr.UserData)\n\treturn nil\n}", "func Open(capsule string) {\n\tFile, _ := ioutil.ReadFile(capsule)\n\tsource = string(File)\n\tload()\n}", "func (session *NetSession) ReadPackage() (interface{}, error) {\n\tfmt.Println(\"reading package from rtsp session\")\n\tnewPackage := new(Package)\n\tnewPackage.RtspHeaderMap = make(map[string]string)\n\tnewPackage.Error = Ok\n\treqData := bytes.NewBuffer(nil)\n\tfor ifFirstLine := true; ; {\n\t\tline, isPrefix, err :=\n\t\t\tsession.Bufio.ReadLine()\n\t\tif err != nil {\n\t\t\treturn nil,\n\t\t\t\tfmt.Errorf(\"session.Bufio.ReadLine() : %v\", err)\n\t\t}\n\t\treqData.Write(line)\n\t\treqData.WriteString(\"\\r\\n\")\n\t\tif !isPrefix {\n\t\t\tif ifFirstLine {\n\t\t\t\titems := regexp.MustCompile(\"\\\\s+\").\n\t\t\t\t\tSplit(strings.\n\t\t\t\t\t\tTrimSpace(string(line)), -1)\n\t\t\t\tif len(items) < 3 ||\n\t\t\t\t\t!strings.HasPrefix(items[2], \"RTSP\") {\n\t\t\t\t\treturn nil,\n\t\t\t\t\t\tfmt.Errorf(\"first request line error\")\n\t\t\t\t}\n\t\t\t\tnewPackage.Method = items[0]\n\t\t\t\tnewPackage.URL = items[1]\n\t\t\t\tnewPackage.Version = items[2]\n\t\t\t\tifFirstLine = false\n\t\t\t} else {\n\t\t\t\tif items := regexp.MustCompile(\":\\\\s+\").Split(strings.\n\t\t\t\t\tTrimSpace(string(line)), 2); len(items) == 2 {\n\t\t\t\t\tnewPackage.RtspHeaderMap[items[0]] = items[1]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif len(line) == 0 {\n\t\t\tfmt.Printf(\"%v\", reqData.String())\n\t\t\tif length, exist :=\n\t\t\t\tnewPackage.RtspHeaderMap[\"Content-Length\"]; exist {\n\t\t\t\tif lengthInt, err := strconv.Atoi(length); err == nil && lengthInt > 0 {\n\t\t\t\t\tcontent := make([]byte, lengthInt)\n\t\t\t\t\tif _, err := io.ReadFull(session.Bufio, content); err == nil {\n\t\t\t\t\t\tnewPackage.Content = content\n\t\t\t\t\t\tfmt.Print(string(content))\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\treqData.Reset()\n\t\t\tbreak\n\t\t}\n\n\t}\n\treturn newPackage, nil\n}", "func (c *Client) ParseSourcesFromFile(path string) error {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer f.Close()\n\n\terr = c.ParseSourcesList(f)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *spiff) FileSource(path string) Source {\n\treturn NewSourceFile(path, s.fs)\n}", "func ListenToPacket(policies []config.Policy) {\n\tif len(policies) == 0 {\n\t\treturn\n\t}\n\n\tvar handle *pcap.Handle\n\thandle, err := pcap.OpenLive(\"any\", 65535, false, -1*time.Second)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer handle.Close()\n\n\tvar filters []string\n\tfor _, policy := range policies {\n\t\tfilters = append(filters, strings.ToLower(policy.Protocol)+\" dst port \"+policy.DstPort)\n\t}\n\n\terr = handle.SetBPFFilter(strings.Join(filters, \" \"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tpacketSource := gopacket.NewPacketSource(handle, handle.LinkType())\n\tfor packet := range packetSource.Packets() {\n\t\tipLayer := packet.Layer(layers.LayerTypeIPv4) // parse IP header\n\t\tipPacket := ipLayer.(*layers.IPv4)\n\n\t\tif ipPacket.NextLayerType() == layers.LayerTypeTCP {\n\t\t\tdataLayer := packet.Layer(layers.LayerTypeTCP) // parse TCP header\n\t\t\tdataPacket := dataLayer.(*layers.TCP)\n\n\t\t\tfmt.Println(\n\t\t\t\t\"--- Received TCP Packet: \",\n\t\t\t\tipPacket.SrcIP, ipPacket.DstIP,\n\t\t\t\tdataPacket.SrcPort, dataPacket.DstPort,\n\t\t\t\tdataPacket.Payload,\n\t\t\t)\n\t\t\tresult.UploadResult(ipPacket.DstIP.String(), dataPacket.DstPort.String(), true)\n\t\t} else if ipPacket.NextLayerType() == layers.LayerTypeUDP {\n\t\t\tdataLayer := packet.Layer(layers.LayerTypeUDP) // parse TCP header\n\t\t\tdataPacket := dataLayer.(*layers.UDP)\n\n\t\t\tfmt.Println(\n\t\t\t\t\"--- Received UDP Packet: \",\n\t\t\t\tipPacket.SrcIP, ipPacket.DstIP,\n\t\t\t\tdataPacket.SrcPort, dataPacket.DstPort,\n\t\t\t\tdataPacket.Payload,\n\t\t\t)\n\t\t\tresult.UploadResult(ipPacket.DstIP.String(), dataPacket.DstPort.String(), true)\n\t\t}\n\t}\n}", "func (d *Datagram) SourceIP() string {\n\treturn BytesToIPAddress(d.Data[12:16])\n}", "func New(handle *pcap.Handle, processor httpStreamProcessor) {\n\t// Set up assembly.\n\tfactory := &httpStreamFactory{\n\t\tprocessor: processor,\n\t}\n\tpool := tcpassembly.NewStreamPool(factory)\n\tassembler := tcpassembly.NewAssembler(pool)\n\n\t// Read in packets, pass to assembler.\n\tsrc := gopacket.NewPacketSource(handle, handle.LinkType())\n\tpackets := src.Packets()\n\trefresh := time.Tick(time.Minute)\n\tfor {\n\t\tselect {\n\t\tcase packet := <-packets:\n\t\t\t// A nil packet indicates the end of a pcap file.\n\t\t\tif packet == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Unusable packet.\n\t\t\tif packet.NetworkLayer() == nil || packet.TransportLayer() == nil || packet.TransportLayer().LayerType() != layers.LayerTypeTCP {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttcp := packet.TransportLayer().(*layers.TCP)\n\t\t\tassembler.AssembleWithTimestamp(packet.NetworkLayer().NetworkFlow(), tcp, packet.Metadata().Timestamp)\n\t\tcase <-refresh:\n\t\t\t// Every minute, flush connections that haven't seen activity recently.\n\t\t\tassembler.FlushOlderThan(time.Now().Add(time.Minute * -5))\n\t\t}\n\t}\n}", "func (d *Debugger) LoadSourceFile(filename string) error {\n\tcontents, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.vm.Run(contents)\n\treturn nil\n}", "func capture() {\n\n\t//opening a new index(take index opened in main)\n\tindexMutex.Lock()\n\tindex := openNewIndex()\n\tindexMutex.Unlock()\n\n\t//Openning pcap live (using variable's of router)\n\thandle, err = pcap.OpenLive(device, snaplen, promisc, timeout)\n\n\tif err != nil {\n\t\tlog.Fatal(\"Error/opening device \", err)\n\t}\n\n\tdefer handle.Close()\n\n\t//Ip of the host\n\tvar filter string = \"src host 192.168.1.106 and icmp\"\n\n\terr = handle.SetBPFFilter(filter)\n\n\tif err != nil {\n\t\tlog.Fatal(\"Error/filtering \", err)\n\t}\n\n\tpacketSource := gopacket.NewPacketSource(handle, handle.LinkType())\n\n\t//Go through all packeges we collect\n\tfor packet := range packetSource.Packets() {\n\t\tfmt.Println(\"capture\")\n\n\t\t//Needed the time when packet is recived\n\t\ttheTimeNow := time.Now()\n\n\t\tiplayer := packet.Layer(layers.LayerTypeIPv4)\n\t\tippacket, _ := iplayer.(*layers.IPv4)\n\t\ticmplayer := packet.Layer(layers.LayerTypeICMPv4)\n\t\ticmppacket := icmplayer.(*layers.ICMPv4)\n\n\t\t//this is only for testing if the packet is recived or not\n\t\tif icmppacket.TypeCode.String() == \"EchoRequest\" {\n\t\t\tif len(icmppacket.Payload) > 0 {\n\t\t\t\tlog.Println(\"Info: EchoRequest Recived\")\n\t\t\t} else {\n\t\t\t\tlog.Println(\"Warn: Empty EchoRequest Recived\")\n\n\t\t\t}\n\t\t}\n\n\t\t//Generating uuid of PcapData(packet)\n\t\tid := uuid.NewUUID()\n\n\t\t//Converting to string all arguments\n\t\t//Creating an object of a struct\n\t\tpcapData := PcapData{\n\t\t\tUUID: id.String(),\n\t\t\tTime: theTimeNow.String(),\n\t\t\tDestinationAddress: ippacket.DstIP.String(),\n\t\t\tProtocol: ippacket.Protocol.String(),\n\t\t\tICMPCode: icmppacket.TypeCode.String(),\n\t\t\tICMPSequenceNumber: strconv.Itoa(int(icmppacket.Seq)),\n\t\t\tPayloadDataLength: strconv.Itoa(int(len(icmppacket.Payload))),\n\t\t\tPayloadData: convert(icmppacket.Payload),\n\t\t}\n\t\t//Here we're indexing data we capture from pcap\n\t\terr := index.Index(pcapData.UUID, pcapData)\n\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Error/indexing\", err)\n\t\t}\n\n\t\tfmt.Println(\"Indexed Document\")\n\t\t// time.Sleep(1 * time.Millisecond)\n\t\truntime.Gosched()\n\t}\n\n}", "func (this *pet) ReadFrom(r io.Reader) (int64, error) {\n\t// var addrs = map[uint64]uintptr{}\n\tvar header [2]uint64\n\tn, err := io.ReadAtLeast(r, ((*[16]byte)(unsafe.Pointer(&header[0])))[:], 16)\n\tif err == nil {\n\t\tif header[0] != 13186359848934745181 {\n\t\t\terr = errors.New(\"pet: incompatible signature header\")\n\t\t} else {\n\t\t\tdata := make([]byte, header[1])\n\t\t\tif n, err = io.ReadAtLeast(r, data, len(data)); err == nil {\n\t\t\t\tvar pos0 int\n\t\t\t\terr = this.unmarshalFrom(&pos0, data /*, addrs*/)\n\t\t\t}\n\t\t\tn += 16\n\t\t}\n\t}\n\treturn int64(n), err\n}", "func (n *Network) Source(cfg SourceConfig) idk.Source {\n\tsrc := &NetworkSource{\n\t\tcur: cfg.startFrom,\n\t\tendAt: cfg.endAt,\n\n\t\trand: rand.New(rand.NewSource(22)),\n\n\t\tschema: n.schema,\n\t}\n\n\tsrc.typeZipf = rand.NewZipf(src.rand, 1.03, 4, uint64(len(dataTypeStrings))-1)\n\n\tsrc.record = make([]interface{}, len(src.schema))\n\tsrc.record[7] = int(1420070400 + cfg.startFrom)\n\n\treturn src\n}", "func FromFile(path ...string) Source {\n\treturn FromReadCloserError(os.Open(filepath.Join(path...)))\n}", "func NewSource(reader io.Reader, buf []byte) (*Source, error) {\n\tn, err := reader.Read(buf)\n\tif n == 0 {\n\t\treturn nil, err\n\t}\n\treturn &Source{\n\t\treader: reader,\n\t\tcurrent: buf[:n],\n\t\tbuf: buf,\n\t}, nil\n}", "func IP2File(file string, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\t/* var wgr sync.WaitGroup */\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer f.Close()\n\t// gr, err := gzip.NewReader(f)\n\tgr, err := pgzip.NewReaderN(f, 1024, 2048) //sfrutta il gzip con steroide che legge nel futuro per andare più veloce assai\n\n\tif err != nil { //se però si impippa qualcosa allora blocca tutto\n\t\tlog.Fatal(err)\n\t\tos.Exit(1)\n\t}\n\n\tbasefile := filepath.Base(file)\n\n\tfileelements := strings.Split(file, \"_\") //prende il nome del file di log e recupera i campi utili\n\tType := fileelements[1] //qui prede il tipo di log\n\t//SEIp := fileelements[3] //qui prende l'ip della cache\n\tdata := fileelements[4] //qui prende la data(\n\tpipe := RedisClient.Pipeline()\n\tn := 0\n\tif Type == \"accesslog\" { //se il tipo di log è \"accesslog\"\n\t\tscan := bufio.NewScanner(gr)\n\t\tvar saltariga int //per saltare le prime righe inutili\n\t\tfor scan.Scan() {\n\t\t\tif saltariga < 2 { //salta le prime due righe\n\t\t\t\tscan.Text()\n\t\t\t\tsaltariga = saltariga + 1\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tline := scan.Text()\n\n\t\t\ts := strings.Split(line, \"\\t\")\n\t\t\tif len(s) < 5 { // se i parametri sono meno di 20 allora ricomincia il loop, serve a evitare le linee che non ci interessano\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tClientip := s[2]\n\n\t\t\tkey := data + \"_\" + Clientip\n\n\t\t\terr := pipe.SAdd(key, basefile).Err()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tos.Exit(200)\n\t\t\t}\n\t\t\tt10g := (10 * 24 * time.Hour)\n\t\t\tpipe.Expire(key, t10g) //la chiave spira dopo 10 gg\n\t\t\tn++\n\t\t\tif n >= 100 {\n\t\t\t\t_, err := pipe.Exec()\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\tos.Exit(200)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//RedisClient.Pipeline().Close()\n\n\t\t_, err := pipe.Exec()\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(200)\n\t\t}\n\t}\n\n\tif Type == \"ingestlog\" {\n\t\treturn\n\t}\n\n\treturn //terminata la Go routine!!! :)\n}", "func (*TelemetryPacket) Descriptor() ([]byte, []int) {\n\treturn file_protocol_proto_rawDescGZIP(), []int{1}\n}", "func (g *GLTF) loadFileBytes(uri string) ([]byte, error) {\n\n\tlog.Debug(\"Loading File: %v\", uri)\n\n\tfpath := filepath.Join(g.path, uri)\n\tf, err := os.Open(fpath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tdata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func GetFirstPacketTimestamp(sFilename string) time.Time {\n\thandle, err := pcap.OpenOffline(sFilename)\n\tdefer handle.Close()\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(0)\n\t}\n\t_, packetHeaderInfo, _ := handle.ReadPacketData()\n\tts := packetHeaderInfo.Timestamp\n\tif iDebug == 1 {\n\t\tfmt.Println(\"DEBUG: Timestamp of first packet\", ts)\n\t}\n\treturn ts\n}", "func loadFile() (goPack, error) {\n\tf, readErr := ioutil.ReadFile(\"./gopack.yml\")\n\tvar goFile goPack\n\tmarshErr := yaml.Unmarshal(f, &goFile)\n\tif marshErr != nil || readErr != nil {\n\t\treturn goPack{}, errors.New(\"Failed to load file\")\n\t}\n\n\treturn goFile, nil\n}", "func parseSourceFile(path string) (sourceFile, error) {\n\tfileBytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn sourceFile{}, err\n\t}\n\tfileContent := string(fileBytes)\n\n\tout := sourceFile{\n\t\ttests: map[string]int{},\n\t}\n\n\tpos := 0\n\tfor _, span := range reTests.FindAllStringIndex(fileContent, -1) {\n\t\tout.parts = append(out.parts, fileContent[pos:span[0]])\n\t\tpos = span[0]\n\n\t\tmatch := reTests.FindStringSubmatch(fileContent[span[0]:span[1]])\n\t\tgroup := match[1]\n\t\tsuite := match[2]\n\t\tout.tests[group+\".\"+suite] = len(out.parts)\n\t}\n\tout.parts = append(out.parts, fileContent[pos:])\n\n\treturn out, nil\n}", "func TraceOpen(pcapFname string, pcapLinkType layers.LinkType) *Trace {\n\t// create a new trace\n\tvar trace Trace\n\n\t// open pcap file\n\thandlePCAP, err := pcap.OpenOffline(pcapFname)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// create pcap packet source\n\ttrace.pktSource = gopacket.NewPacketSource(handlePCAP, pcapLinkType)\n\n\t// return trace instance\n\treturn &trace\n}", "func DescriptorSourceFromProtoFiles(importPaths []string, fileNames ...string) (DescriptorSource, error) {\n\tp := protoparse.Parser{\n\t\tImportPaths: importPaths,\n\t\tInferImportPaths: len(importPaths) == 0,\n\t}\n\tfds, err := p.ParseFiles(fileNames...)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not parse given files: %v\", err)\n\t}\n\treturn DescriptorSourceFromFileDescriptors(fds...)\n}", "func getBufferFromInputResource(inputPath string) ([]byte, error) {\n\n\turl, err := url.Parse(inputPath)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Error parsing input file\")\n\t}\n\tif url.Scheme == \"http\" || url.Scheme == \"https\" {\n\t\tres, err := http.Get(inputPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer res.Body.Close()\n\t\treturn ioutil.ReadAll(res.Body)\n\t} else if url.Scheme == \"ftp\" {\n\t\treturn nil, errors.New(\"ftp not supported yet\")\n\n\t} else {\n\t\treturn ioutil.ReadFile(inputPath)\n\t}\n}", "func Open(path string) (*Pattern, error) {\n\tfi, err := os.Stat(path)\n\n\t// TODO better error handling\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif fi.Size() < headerSize {\n\t\treturn nil, fmt.Errorf(\"Splice file must be at least 14 bytes (input file is %d bytes)\", fi.Size())\n\t}\n\n\t// Read first 14 bytes to check magic header and required minimum filesize\n\tspliceFile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer spliceFile.Close()\n\n\tvalid, err := checkSpliceMagic(spliceFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !valid {\n\t\treturn nil, errors.New(\"File in not a valid splce file, magic header incorrect\")\n\t}\n\n\t// if packed on 1-byte alignment, dataSize could be a int64 in big-endian\n\t// hard to tell from example data and not sure why you'd mix big/little endian in the same file\n\t// but a single byte value seems too limiting regarding number of tracks\n\tvar dataSize int64\n\tbinary.Read(spliceFile, binary.BigEndian, &dataSize)\n\tminimumFileSize := headerSize + dataSize\n\n\t// By obeying the data size and not the file size we support fixture 5 with extra unused data\n\tif minimumFileSize > fi.Size() {\n\t\treturn nil, fmt.Errorf(\"File is truncated, required file size is %d - actual file size is %d\", minimumFileSize, fi.Size())\n\t}\n\n\t// More header data\n\n\t// 32 byte character ASCII string\n\tversion, err := readFixedNullTermString(spliceFile, 32)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// 4 byte little endian floating point\n\tvar tempo float32\n\terr = binary.Read(spliceFile, binary.LittleEndian, &tempo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar tracks []*Track\n\n\tfor {\n\t\ttrack := readTrack(spliceFile)\n\t\ttracks = append(tracks, track)\n\n\t\tpos, _ := spliceFile.Seek(0, os.SEEK_CUR)\n\t\tif pos-headerSize >= dataSize {\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\treturn &Pattern{\n\t\tVersion: version,\n\t\tTempo: tempo,\n\t\tTracks: tracks,\n\t}, nil\n\n}", "func newFrameFromPackets(pkts []ipPacket, tid int64) (f linkFrame) {\n f.method = RELAY_TUN_DATA\n f.param = map[string]interface{} { K_PKTS : bytesFromPkts(pkts), K_TID: tid}\n f.response = -1\n return\n}", "func (p Pinger) GetSrc() net.IP {\r\n\treturn p.src\r\n}", "func (upc *BroadcastRawUDPConn) ReadFrom(b []byte) (int, net.Addr, error) {\n\tipHdrMaxLen := ipv4MaximumHeaderSize\n\tudpHdrLen := udpMinimumSize\n\n\tfor {\n\t\tpkt := make([]byte, ipHdrMaxLen+udpHdrLen+len(b))\n\t\tn, _, err := upc.PacketConn.ReadFrom(pkt)\n\t\tif err != nil {\n\t\t\treturn 0, nil, err\n\t\t}\n\t\tif n == 0 {\n\t\t\treturn 0, nil, io.EOF\n\t\t}\n\t\tpkt = pkt[:n]\n\t\tbuf := uio.NewBigEndianBuffer(pkt)\n\n\t\t// To read the header length, access data directly.\n\t\tif !buf.Has(ipv4MinimumSize) {\n\t\t\tcontinue\n\t\t}\n\n\t\tipHdr := ipv4(buf.Data())\n\n\t\tif !buf.Has(int(ipHdr.headerLength())) {\n\t\t\tcontinue\n\t\t}\n\n\t\tipHdr = ipv4(buf.Consume(int(ipHdr.headerLength())))\n\n\t\tif ipHdr.transportProtocol() != udpProtocolNumber {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !buf.Has(udpHdrLen) {\n\t\t\tcontinue\n\t\t}\n\n\t\tudpHdr := udp(buf.Consume(udpHdrLen))\n\n\t\taddr := &net.UDPAddr{\n\t\t\tIP: ipHdr.destinationAddress(),\n\t\t\tPort: int(udpHdr.destinationPort()),\n\t\t}\n\t\tif !udpMatch(addr, upc.boundAddr) {\n\t\t\tcontinue\n\t\t}\n\t\tsrcAddr := &net.UDPAddr{\n\t\t\tIP: ipHdr.sourceAddress(),\n\t\t\tPort: int(udpHdr.sourcePort()),\n\t\t}\n\t\t// Extra padding after end of IP packet should be ignored,\n\t\t// if not dhcp option parsing will fail.\n\t\tdhcpLen := int(ipHdr.payloadLength()) - udpHdrLen\n\t\treturn copy(b, buf.Consume(dhcpLen)), srcAddr, nil\n\t}\n}", "func discoFromFile(absolutePath string) (contents []byte, err error) {\n\t_, err = os.Stat(absolutePath)\n\tif os.IsNotExist(err) {\n\t\terr = nil\n\t\treturn\n\t}\n\tcontents, err = ioutil.ReadFile(absolutePath)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error reading Discovery doc from %v: %v\", absolutePath, err)\n\t\treturn\n\t}\n\treturn\n}", "func (r *Reader) readPacket() ([]byte, error) {\n\tfor {\n\t\ts, err := r.Reader.ReadLine()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t} else if len(s) == 0 || s[len(s)-1] != lineDelim {\n\t\t\treturn nil, errors.New(\"invalid packet delimiter\")\n\t\t}\n\t\tif len(s) > 1 {\n\t\t\treturn s, nil\n\t\t}\n\t\t// clients may send message containing only 0x0a byte to keep connection alive\n\t\tif r.OnKeepAlive != nil {\n\t\t\tif err := r.OnKeepAlive(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n}", "func (trace *Trace) Packets() chan gopacket.Packet {\n\treturn trace.pktSource.Packets()\n}", "func (t *Target) parse(fn string) error {\n\tdata, err := ioutil.ReadFile(fn)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconnections := connectionset{}\n\txml.Unmarshal(data, &connections)\n\tfor _, conn := range connections.Conns {\n\t\tif conn.Id == t.Name {\n\t\t\tt.dest = strings.Replace(conn.URI, \"ipbusudp-2.0://\", \"\", 1)\n\t\t\t//ns := nodes{}\n\t\t\taddr := strings.Replace(conn.Address, \"file://\", \"\", 1)\n\t\t\tif err := t.parseregfile(addr, \"\", uint32(0)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn error(nil)\n}", "func (c *Client) Read() (*Packet, *ethernet.Frame, error) {\n\tbuf := make([]byte, 128)\n\tfor {\n\t\tn, _, err := c.p.ReadFrom(buf)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tp, eth, err := parsePacket(buf[:n])\n\t\tif err != nil {\n\t\t\tif err == errInvalidARPPacket {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, nil, err\n\t\t}\n\t\treturn p, eth, nil\n\t}\n}", "func (*mockFile) SourceLine(addr uint64) ([]plugin.Frame, error) {\n\t// Return enough data to support the SourceLine() calls needed for\n\t// weblist on cpuProfile() contents.\n\tframe := func(fn, file string, line int) plugin.Frame {\n\t\treturn plugin.Frame{Func: fn, File: file, Line: line}\n\t}\n\tswitch addr {\n\tcase 0x1000:\n\t\treturn []plugin.Frame{\n\t\t\tframe(\"mangled1000\", \"testdata/file1000.src\", 1),\n\t\t}, nil\n\tcase 0x1001:\n\t\treturn []plugin.Frame{\n\t\t\tframe(\"mangled1000\", \"testdata/file1000.src\", 1),\n\t\t}, nil\n\tcase 0x1002:\n\t\treturn []plugin.Frame{\n\t\t\tframe(\"mangled1000\", \"testdata/file1000.src\", 2),\n\t\t}, nil\n\tcase 0x1003:\n\t\treturn []plugin.Frame{\n\t\t\tframe(\"mangled1000\", \"testdata/file1000.src\", 1),\n\t\t}, nil\n\tcase 0x2000:\n\t\treturn []plugin.Frame{\n\t\t\tframe(\"mangled2001\", \"testdata/file2000.src\", 9),\n\t\t\tframe(\"mangled2000\", \"testdata/file2000.src\", 4),\n\t\t}, nil\n\tcase 0x3000:\n\t\treturn []plugin.Frame{\n\t\t\tframe(\"mangled3002\", \"testdata/file3000.src\", 2),\n\t\t\tframe(\"mangled3001\", \"testdata/file3000.src\", 5),\n\t\t\tframe(\"mangled3000\", \"testdata/file3000.src\", 6),\n\t\t}, nil\n\tcase 0x3001:\n\t\treturn []plugin.Frame{\n\t\t\tframe(\"mangled3001\", \"testdata/file3000.src\", 8),\n\t\t\tframe(\"mangled3000\", \"testdata/file3000.src\", 9),\n\t\t}, nil\n\tcase 0x3002:\n\t\treturn []plugin.Frame{\n\t\t\tframe(\"mangled3002\", \"testdata/file3000.src\", 5),\n\t\t\tframe(\"mangled3000\", \"testdata/file3000.src\", 9),\n\t\t}, nil\n\t}\n\n\treturn nil, nil\n}", "func FromFile(path string, x interface{}) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\tlog.Fatalf(\"[common] error opening file %s: %v\", path, err)\n\t}\n\tdefer file.Close()\n\n\t// read file as byte array\n\tbytes, _ := ioutil.ReadAll(file)\n\tif err := json.Unmarshal(bytes, x); err != nil {\n\t\tlog.Fatalf(\n\t\t\t\"[common] error unmarshaling json to output struct %T: %v (%s)\",\n\t\t\tx,\n\t\t\terr,\n\t\t\tpath,\n\t\t)\n\t}\n}", "func (*SerializedRyuPacket) Descriptor() ([]byte, []int) {\n\treturn file_pipelined_proto_rawDescGZIP(), []int{18}\n}", "func (fpc *FakePacketConn) ReadFrom(b []byte) (int, net.Addr, error) {\n\tif fpc.isClosed() {\n\t\treturn 0, nil, ErrClosedConnection\n\t}\n\n\tif atomic.AddUint64(&fpc.count, 1) >= fpc.limit {\n\t\t_ = fpc.Close() // nolint:gas\n\t\treturn 0, nil, ErrClosedConnection\n\t}\n\n\tn := copy(b, FakeMetric)\n\treturn n, FakeAddr, nil\n}", "func loadFile(path string) ([]byte, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb := make([]byte, fi.Size())\n\tf.Read(b)\n\treturn b, nil\n}", "func (u *userApp) loadRaw(filename string, x []uint8) (string, error) {\n\n\t// copy the code to the load address\n\tvar loadAdr uint16\n\tfor i, v := range x {\n\t\tu.mem.Write8(loadAdr+uint16(i), v)\n\t}\n\tendAdr := loadAdr + uint16(len(x)) - 1\n\n\treturn fmt.Sprintf(\"%s code %04x-%04x\", filename, loadAdr, endAdr), nil\n}" ]
[ "0.6322504", "0.62335175", "0.5824764", "0.56764734", "0.5661583", "0.54498464", "0.5445083", "0.54125637", "0.53544843", "0.5283854", "0.5241161", "0.5231053", "0.52022845", "0.51986253", "0.51750165", "0.51036865", "0.50913", "0.5089517", "0.50672114", "0.5062419", "0.5034824", "0.5028395", "0.50145537", "0.50071734", "0.50040543", "0.4996805", "0.49914944", "0.49914944", "0.49792808", "0.49635324", "0.49517468", "0.49498883", "0.49209625", "0.4906778", "0.49064896", "0.49039185", "0.49033844", "0.4892941", "0.4875025", "0.48657322", "0.48601943", "0.48569578", "0.48515877", "0.48477837", "0.4837513", "0.48331216", "0.48284134", "0.48248622", "0.48075244", "0.48043033", "0.4798122", "0.47901767", "0.47782916", "0.47739008", "0.4767512", "0.47641742", "0.47625753", "0.47615415", "0.475459", "0.475156", "0.47445747", "0.47406444", "0.47366387", "0.47275522", "0.47166598", "0.47160518", "0.46934637", "0.46926078", "0.46897563", "0.4686843", "0.4685161", "0.46847466", "0.46561062", "0.4655678", "0.4653772", "0.46435398", "0.46427885", "0.46352422", "0.4633761", "0.4626281", "0.46222436", "0.46214843", "0.460801", "0.4605646", "0.4605214", "0.46051437", "0.460316", "0.45962247", "0.4586854", "0.45867354", "0.45848036", "0.45789188", "0.45777917", "0.4575121", "0.45652923", "0.45639402", "0.45574835", "0.45507345", "0.45496523", "0.45491567" ]
0.5706543
3
PacketData use channel so it's possible to do range
func (p *Pcap) PacketData() chan PacketData { if p.channel == nil { p.channel = make(chan PacketData, 5) go func() { for gp := range p.source.Packets() { p.channel <- PacketData(gp.Data()) } }() } return p.channel }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (transfer *RawSocketIO) readPacketToChannel() {\n\n\tvar onePkt RawPacket\n\n\tvar err error\n\tfor {\n\n\t}\n}", "func SourceData(data ...int) <-chan int {\n\tfmt.Println(\"num:\", len(data))\n\tch := make(chan int, 80000000)\n\tgo func() {\n\t\tfor _, v := range data {\n\t\t\tch <- v\n\t\t}\n\t\tclose(ch)\n\t}()\n\treturn ch\n}", "func parseData(data []byte) (*dmr.Packet, error) {\n\tif len(data) != 55 {\n\t\treturn nil, fmt.Errorf(\"homebrew: expected 55 data bytes, got %d\", len(data))\n\t}\n\n\tvar dataType uint8\n\n\tswitch (data[15] >> 4) & 0x03 {\n\tcase 0x00, 0x01: // voice (B-F), voice sync (A)\n\t\tdataType = dmr.VoiceBurstA + (data[15] & 0x0f)\n\t\tbreak\n\tcase 0x02: // data sync\n\t\tdataType = (data[15] & 0x0f)\n\t\tbreak\n\tdefault: // unknown/unused\n\t\treturn nil, errors.New(\"homebrew: unexpected frame type 0b11\")\n\t}\n\n\tvar p = &dmr.Packet{\n\t\tSequence: data[4],\n\t\tSrcID: uint32(data[5])<<16 | uint32(data[6])<<8 | uint32(data[7]),\n\t\tDstID: uint32(data[8])<<16 | uint32(data[9])<<8 | uint32(data[10]),\n\t\tRepeaterID: uint32(data[11])<<24 | uint32(data[12])<<16 | uint32(data[13])<<8 | uint32(data[14]),\n\t\tTimeslot: (data[15] >> 7) & 0x01,\n\t\tCallType: (data[15] >> 6) & 0x01,\n\t\tStreamID: uint32(data[16])<<24 | uint32(data[17])<<16 | uint32(data[18])<<8 | uint32(data[19]),\n\t\tDataType: dataType,\n\t\tBER: data[53],\n\t\tRSSI: data[54]}\n\n\tvar pData = make([]byte, 33) // copy DMR data for correct parrot works\n\tcopy(pData, data[20:53])\n\n\tp.SetData(pData)\n\n\treturn p, nil\n}", "func (pb *PacketBuffer) Packet(n int) PacketData {\n\tstart := 0\n\tif n > 0 {\n\t\tstart = pb.offsets[n-1]\n\t}\n\tend := pb.offsets[n]\n\n\treturn PacketData{\n\t\tInfo: pb.cis[n],\n\t\tData: pb.data[start:end],\n\t}\n}", "func HandleChannelPacket(conn *connection.Channel, reader maplepacket.Reader) {\n\tswitch reader.ReadByte() {\n\tcase constants.RecvPing:\n\n\tcase constants.RecvChannelPlayerLoad:\n\t\thandlePlayerConnect(conn, reader)\n\n\tcase constants.RecvChannelUserPortal:\n\t\thandleUsePortal(conn, reader)\n\tcase constants.RecvChannelEnterCashShop:\n\n\tcase constants.RecvChannelPlayerMovement:\n\t\thandlePlayerMovement(conn, reader)\n\n\tcase constants.RecvChannelStandardSkill:\n\t\thandleStandardSkill(conn, reader)\n\n\tcase constants.RecvChannelRangedSkill:\n\t\thandleRangedSkill(conn, reader)\n\n\tcase constants.RecvChannelMagicSkill:\n\t\thandleMagicSkill(conn, reader)\n\n\tcase constants.RecvChannelDmgRecv:\n\t\thandleTakeDamage(conn, reader)\n\n\tcase constants.RecvChannelPlayerSendAllChat:\n\t\thandleAllChat(conn, reader)\n\n\tcase constants.RecvChannelSlashCommands:\n\t\thandleSlashCommand(conn, reader)\n\n\tcase constants.RecvChannelCharacterUIWindow:\n\t\thandleUIWindow(conn, reader)\n\n\tcase constants.RecvChannelEmoticon:\n\t\thandlePlayerEmoticon(conn, reader)\n\n\tcase constants.RecvChannelNpcDialogue:\n\t\thandleNPCChat(conn, reader)\n\n\tcase constants.RecvChannelNpcDialogueContinue:\n\t\thandleNPCChatContinue(conn, reader)\n\n\tcase constants.RecvChannelNpcShop:\n\t\thandleNPCShop(conn, reader)\n\n\tcase constants.RecvChannelInvMoveItem:\n\t\thandleMoveInventoryItem(conn, reader)\n\n\tcase constants.RecvChannelChangeStat:\n\t\thandleChangeStat(conn, reader)\n\n\tcase constants.RecvChannelPassiveRegen:\n\t\thandlePassiveRegen(conn, reader)\n\n\tcase constants.RecvChannelSkillUpdate:\n\t\thandleUpdateSkillRecord(conn, reader)\n\n\tcase constants.RecvChannelSpecialSkill:\n\t\thandleSpecialSkill(conn, reader)\n\n\tcase constants.RecvChannelCharacterInfo:\n\t\thandleRequestAvatarInfoWindow(conn, reader)\n\n\tcase constants.RecvChannelLieDetectorResult:\n\n\tcase constants.RecvChannelPartyInfo:\n\n\tcase constants.RecvChannelGuildManagement:\n\n\tcase constants.RecvChannelGuildReject:\n\n\tcase constants.RecvChannelAddBuddy:\n\n\tcase constants.RecvChannelMobControl:\n\t\thandleMobControl(conn, reader)\n\n\tcase constants.RecvChannelNpcMovement:\n\t\thandleNPCMovement(conn, reader)\n\n\tdefault:\n\t\tlog.Println(\"Unkown packet:\", reader)\n\t}\n}", "func read(chnl <-chan int){\n\ti := 0\n\tfor ;i < 10; {\n\t\tval, isDataAvailable := <- chnl\n\t\tif isDataAvailable {\n\t\t\tfmt.Println(\"Reader :\", val)\n\t\t\ti++\n\t\t}\n\t}\n}", "func buildData(p *dmr.Packet, repeaterID uint32) []byte {\n\tvar data = make([]byte, 55)\n\tcopy(data[:4], DMRData)\n\tdata[4] = p.Sequence\n\tdata[5] = uint8(p.SrcID >> 16)\n\tdata[6] = uint8(p.SrcID >> 8)\n\tdata[7] = uint8(p.SrcID)\n\tdata[8] = uint8(p.DstID >> 16)\n\tdata[9] = uint8(p.DstID >> 8)\n\tdata[10] = uint8(p.DstID)\n\tdata[11] = uint8(repeaterID >> 24)\n\tdata[12] = uint8(repeaterID >> 16)\n\tdata[13] = uint8(repeaterID >> 8)\n\tdata[14] = uint8(repeaterID)\n\tdata[15] = ((p.Timeslot & 0x01) << 7) | ((p.CallType & 0x01) << 6)\n\tdata[16] = uint8(p.StreamID >> 24)\n\tdata[17] = uint8(p.StreamID >> 16)\n\tdata[18] = uint8(p.StreamID >> 8)\n\tdata[19] = uint8(p.StreamID)\n\tcopy(data[20:53], p.Data)\n\n\tdata[53] = uint8(p.BER)\n\tdata[54] = uint8(p.RSSI)\n\n\tswitch p.DataType {\n\tcase dmr.VoiceBurstB, dmr.VoiceBurstC, dmr.VoiceBurstD, dmr.VoiceBurstE, dmr.VoiceBurstF:\n\t\tdata[15] |= (0x00 << 4)\n\t\tdata[15] |= (p.DataType - dmr.VoiceBurstA)\n\t\tbreak\n\tcase dmr.VoiceBurstA:\n\t\tdata[15] |= (0x01 << 4)\n\t\tbreak\n\tdefault:\n\t\tdata[15] |= (0x02 << 4)\n\t\tdata[15] |= (p.DataType)\n\t}\n\n\treturn data\n}", "func parsePacket(fromAddr *net.UDPAddr, data []byte) (*Packet, error) {\n\tif len(data) < minLen {\n\t\treturn nil, fmt.Errorf(\"packet is too short: %d bytes\", len(data))\n\t}\n\tif len(data) > maxLen {\n\t\treturn nil, fmt.Errorf(\"packet is exceeded max length: %d bytes\", len(data))\n\t}\n\tcurr := 0\n\tnext := func(n int) []byte {\n\t\tbs := data[curr : curr+n]\n\t\tcurr += n\n\t\treturn bs\n\t}\n\tu16, u32 := binary.BigEndian.Uint16, binary.BigEndian.Uint32\n\tp := Packet{}\n\tp.Type = next(1)[0]\n\tp.SeqNum = u32(next(4))\n\tp.FromAddr = fromAddr\n\ttoAddr, err := net.ResolveUDPAddr(\"udp\", fmt.Sprintf(\"%s:%d\", net.IP(next(4)), u16(next(2))))\n\t// If toAddr is loopback, it should be as same as the host of fromAddr.\n\tif toAddr.IP.IsLoopback() {\n\t\ttoAddr.IP = fromAddr.IP\n\t}\n\tp.ToAddr = toAddr\n\tp.Payload = data[curr:]\n\treturn &p, err\n}", "func (f *inFlow) onData(n uint32) error {\n\tif n == 0 {\n\t\treturn nil\n\t}\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tif f.pendingData+f.pendingUpdate+n > f.limit {\n\t\treturn fmt.Errorf(\"recieved %d-bytes data exceeding the limit %d bytes\", f.pendingData+f.pendingUpdate+n, f.limit)\n\t}\n\tif f.connInFlow != nil {\n\t\terr := f.connInFlow.onData(n)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tf.pendingData += n\n\treturn nil\n}", "func (s *Stream) readData(hdr header, flags uint16, conn io.Reader) error {\n\tif err := s.processFlags(flags); err != nil {\n\t\treturn err\n\t}\n\n\t// Check that our recv window is not exceeded\n\tlength := hdr.Length()\n\tif length == 0 {\n\t\treturn nil\n\t}\n\n\t// Wrap in a limited reader\n\tconn = &io.LimitedReader{R: conn, N: int64(length)}\n\n\t// Copy into buffer\n\ts.recvLock.Lock()\n\n\tif length > s.recvWindow {\n\t\ts.session.logger.Printf(\"[ERR] yamux: receive window exceeded (stream: %d, remain: %d, recv: %d)\", s.id, s.recvWindow, length)\n\t\treturn ErrRecvWindowExceeded\n\t}\n\n\tif s.recvBuf == nil {\n\t\t// Allocate the receive buffer just-in-time to fit the full data frame.\n\t\t// This way we can read in the whole packet without further allocations.\n\t\ts.recvBuf = bytes.NewBuffer(make([]byte, 0, length))\n\t}\n\tif _, err := io.Copy(s.recvBuf, conn); err != nil {\n\t\ts.session.logger.Printf(\"[ERR] yamux: Failed to read stream data: %v\", err)\n\t\ts.recvLock.Unlock()\n\t\treturn err\n\t}\n\n\t// Decrement the receive window\n\ts.recvWindow -= length\n\ts.recvLock.Unlock()\n\n\t// Unblock any readers\n\tasyncNotify(s.recvNotifyCh)\n\treturn nil\n}", "func sendPacketToChanel(senarioNum int) {\n\tsrcIps, _ := hosts(config.Scenarios.Scenario[senarioNum].Params.SrcIP)\n\t// dstIps, _ := hosts(config.Scenarios.Scenario[senarioNum].Params.DestIp)\n\tdstIPCount, _ := hostsCount(config.Scenarios.Scenario[senarioNum].Params.DestIp)\n\n\tnpingPossibility := dstIPCount *\n\t\t(config.Scenarios.Scenario[senarioNum].Params.DestPortEnd -\n\t\t\tconfig.Scenarios.Scenario[senarioNum].Params.DestPortStart)\n\n\tpacketCounter := 0\n\nsendPacketToChanelStart:\n\tfor _, SrcIP := range srcIps {\n\t\tfor SrcPort := config.Scenarios.Scenario[senarioNum].Params.SrcPortStart; SrcPort <= config.Scenarios.Scenario[senarioNum].Params.SrcPortEnd; SrcPort++ {\n\t\t\tif npingPossibility <= config.Scenarios.Scenario[senarioNum].Params.Size-packetCounter {\n\t\t\t\tscenariosNpingCmdMap[senarioNum] = append(scenariosNpingCmdMap[senarioNum],\n\t\t\t\t\tfmt.Sprintf(\"nping -c %v -rate %v --%v -p %v-%v --dest-ip %v -g %v -S %v --data-string justForTest &\",\n\t\t\t\t\t\tconfig.Scenarios.Scenario[senarioNum].Params.Size,\n\t\t\t\t\t\tconfig.Scenarios.Scenario[senarioNum].Params.Rate,\n\t\t\t\t\t\tstrings.ToLower(config.Scenarios.Scenario[senarioNum].Params.ProtocolVersion),\n\t\t\t\t\t\tconfig.Scenarios.Scenario[senarioNum].Params.DestPortStart,\n\t\t\t\t\t\tconfig.Scenarios.Scenario[senarioNum].Params.DestPortEnd,\n\t\t\t\t\t\tconfig.Scenarios.Scenario[senarioNum].Params.DestIp, SrcPort, SrcIP))\n\t\t\t\tpacketCounter += config.Scenarios.Scenario[senarioNum].Params.Size\n\t\t\t\tif packetCounter == config.Scenarios.Scenario[senarioNum].Params.Size {\n\t\t\t\t\tgoto sendPacketToChanelEnd\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tscenariosNpingCmdMap[senarioNum] = append(scenariosNpingCmdMap[senarioNum],\n\t\t\t\t\tfmt.Sprintf(\"nping -c %v -rate %v --%v -p %v-%v --dest-ip %v -g %v -S %v --data-string justForTest &\",\n\t\t\t\t\t\tconfig.Scenarios.Scenario[senarioNum].Params.Size,\n\t\t\t\t\t\tconfig.Scenarios.Scenario[senarioNum].Params.Rate,\n\t\t\t\t\t\tstrings.ToLower(config.Scenarios.Scenario[senarioNum].Params.ProtocolVersion),\n\t\t\t\t\t\tconfig.Scenarios.Scenario[senarioNum].Params.DestPortStart,\n\t\t\t\t\t\tconfig.Scenarios.Scenario[senarioNum].Params.DestPortEnd,\n\t\t\t\t\t\tconfig.Scenarios.Scenario[senarioNum].Params.DestIp, SrcPort, SrcIP))\n\t\t\t\tpacketCounter += npingPossibility\n\t\t\t\tif packetCounter == config.Scenarios.Scenario[senarioNum].Params.Size {\n\t\t\t\t\tgoto sendPacketToChanelEnd\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\nsendPacketToChanelEnd:\n\tif packetCounter < config.Scenarios.Scenario[senarioNum].Params.Size {\n\t\tgoto sendPacketToChanelStart\n\t}\n\t// packetCounter := 0\n\n\t// sendPacketToChanelStart:\n\t// \tfor _, SrcIP := range srcIps {\n\t// \t\tfor SrcPort := config.Scenarios.Scenario[senarioNum].Params.SrcPortStart; SrcPort <= config.Scenarios.Scenario[senarioNum].Params.SrcPortEnd; SrcPort++ {\n\t// \t\t\tpacketChanel <- fmt.Sprintf(\"nping -rate %v --%v -p %v-%v --dest-ip %v -g %v -S %v --data-string justForTest &\",\n\t// \t\t\t\tconfig.Scenarios.Scenario[senarioNum].Params.Rate,\n\t// \t\t\t\tstrings.ToLower(config.Scenarios.Scenario[senarioNum].Params.ProtocolVersion),\n\t// \t\t\t\tconfig.Scenarios.Scenario[senarioNum].Params.DestPortStart,\n\t// \t\t\t\tconfig.Scenarios.Scenario[senarioNum].Params.DestPortEnd,\n\t// \t\t\t\tconfig.Scenarios.Scenario[senarioNum].Params.DestIp, SrcPort, SrcIP)\n\t// \t\t\tpacketCounter++\n\t// \t\t\tif packetCounter == config.Scenarios.Scenario[senarioNum].Params.Size {\n\t// \t\t\t\tgoto sendPacketToChanelEnd\n\t// \t\t\t}\n\n\t// \t\t\t// for _, DstIP := range dstIps {\n\t// \t\t\t// \tfor DestPort := config.Scenarios.Scenario[senarioNum].Params.DestPortStart; DestPort <= config.Scenarios.Scenario[senarioNum].Params.DestPortEnd; DestPort++ {\n\n\t// \t\t\t// \t}\n\t// \t\t\t// }\n\t// \t\t}\n\t// \t}\n\n\t// sendPacketToChanelEnd:\n\t// \tif packetCounter < config.Scenarios.Scenario[senarioNum].Params.Size {\n\t// \t\tgoto sendPacketToChanelStart\n\t// \t}\n}", "func (g BasicPacket) Data() []byte {\n\treturn g.data\n}", "func (d *Dao) ChannelData(c context.Context, seasonType int, appInfo *conf.TVApp) (result []*model.Card, err error) {\n\tvar res struct {\n\t\tCode int `json:\"code\"`\n\t\tResult []*model.Card `json:\"result\"`\n\t}\n\tbangumiURL := d.conf.Host.APIZone\n\tparams := url.Values{}\n\tparams.Set(\"build\", appInfo.Build)\n\tparams.Set(\"mobi_app\", appInfo.MobiApp)\n\tparams.Set(\"platform\", appInfo.Platform)\n\tparams.Set(\"season_type\", strconv.Itoa(int(seasonType)))\n\tif err = d.client.Get(c, bangumiURL, \"\", params, &res); err != nil {\n\t\treturn\n\t}\n\tif res.Code != ecode.OK.Code() {\n\t\terr = errors.Wrap(ecode.Int(res.Code), bangumiURL+\"?\"+params.Encode())\n\t\treturn\n\t}\n\tif len(res.Result) == 0 {\n\t\terr = ecode.TvPGCRankEmpty\n\t\tlog.Error(\"[LoadPGCList] Zone %d, Err %v\", seasonType, err)\n\t\treturn\n\t}\n\tfor _, v := range res.Result {\n\t\tif v.NewEP != nil {\n\t\t\tv.BePGC()\n\t\t\tresult = append(result, v)\n\t\t}\n\t}\n\tif len(result) == 0 {\n\t\terr = ecode.TvPGCRankNewEPNil\n\t\tlog.Error(\"[LoadPGCList] Zone %d, Err %v\", seasonType, err)\n\t}\n\treturn\n}", "func (d *DataPacket) Data() []byte {\n\treturn d.data[126:d.length]\n}", "func carvePacket(buf *[]byte) (int, []byte) {\n\tdatalen := uint32(len(*buf))\n\tif datalen < 5 {\n\t\treturn -1, nil\n\t}\n\n\tsize := uint32((*buf)[0])<<24 + uint32((*buf)[1])<<16 + uint32((*buf)[2])<<8 +\n\t\tuint32((*buf)[3])\n\tif datalen < size+4 {\n\t\treturn -1, nil\n\t}\n\n\tend := size + 4\n\tptype := int((*buf)[4])\n\tdata := (*buf)[5 : size+4]\n\tif end >= datalen {\n\t\t*buf = nil\n\t} else {\n\t\t*buf = (*buf)[end:]\n\t}\n\n\t//\tlog.Printf(\"datalen=%d size=%d end=%d ptype=%d data=%d buf=%d\",\n\t//\t\tdatalen, size, end, ptype, len(data), len(*buf))\n\n\treturn ptype, data\n}", "func (d *Display) sendData(bits uint8) {\n\td.write8bits(bits, 1)\n}", "func (s *Shard) sendPacket(op types.GatewayOp, data interface{}) error {\n\ts.connMu.Lock()\n\tdefer s.connMu.Unlock()\n\n\ts.limiter.lock()\n\n\treturn s.conn.WriteJSON(&types.SendPacket{\n\t\tOp: op,\n\t\tData: data,\n\t})\n}", "func sendUDPPacket(ip string, data []byte) {\n\t// a random port is picked since we can't listen and read at the same time\n\tudpConn, err := net.Dial(\"udp\", ip)\n\tcheckErr(err, 559)\n\tdefer udpConn.Close()\n\n\t_, err = udpConn.Write(data)\n\tcheckErr(err, 563)\n}", "func (me *T) Data() <-chan float64 {\n\n\t// Create channel.\n\t//\n\t// We will return this to the caller.\n\t//\n\t// We will also spawn a goroutine and output the data from this datasack has onto it.\n\t//\n\t\tout := make(chan float64)\n\n\t// Spawn a goroutine that will output the data from this datasack onto the channel\n\t// we previously created.\n\t//\n\t// Note that this goroutine will probably block. But that's OK, since it is in\n\t// its own goroutine (and shouldn't take anything else down with it).\n\t//\n\t\tgo func() {\n\t\t\tfor _,value := range me.slice {\n\t\t\t\tout <- value\n\t\t\t}\n\n\t\t\tclose(out)\n\t\t}()\n\n\t// Return.\n\t\treturn out\n}", "func (transfer *RawSocketIO) readNextPacket() RawPacket {\n\treturn <-transfer.outPacketChan\n}", "func TestPacket(packet []byte) ([]byte, bool) {\n\tpacket, startSignal := ReadUShort(packet)\n\tfor startSignal != StartSignal && len(packet) > SizeOfShort {\n\t\tpacket, startSignal = ReadUShort(packet)\n\t}\n\tif len(packet) > SizeOfShort {\n\t\treturn packet, true\n\t} else {\n\t\treturn packet, false\n\t}\n}", "func (r *Reader) ReadPacketData(query []byte) (data []byte, ci gopacket.CaptureInfo, err error) {\n\tfor {\n\t\t//log.Printf(\"Start!\\n\")\n\t\tif bytes.Contains(r.blockSlice, query) {\n\t\t\t// Decode and return this block\n\t\t\t//log.Printf(\"Pattern WAS found in block %d\\n\", r.bnum)\n\t\t\tdata, ci, more, err := r.FindPacket(query)\n\t\t\tif more {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn data, ci, err\n\t\t} else {\n\t\t\t//log.Printf(\"Pattern NOT found in block %d\\n\", r.bnum)\n\t\t\t//skip this entire block\n\t\t\tif !r.SkipPackets() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\terr = io.EOF\n\treturn\n}", "func oscListen(responseChannel chan OscResponse, sock *net.UDPConn) {\n doLog( \"entering OSC packet listen loop\" )\n var buf []byte\n for {\n sock.ReadFromUDP(buf)\n doLog(\"TODO: decode packet\")\n }\n}", "func getData(command string) []byte {\n\n\tn := port.Write([]byte(command))\n\n\tbuf := make([]byte, bufferSize)\n\tn, err := port.Read(buf)\n\tif err != nil {\n\t\tlog.Println(\"Error reading from serial \", err, \". Is this the right port?\")\n\t}\n\n\tsplit := strings.Split(string(buf[:n]), \",\")\n\n\tif len(split) == numSerialAttrs { // Was a complete read\n\n\t\tdata = append(data, split)\n\n\t\tif len(data) == numberOfDataToFilter {\n\n\t\t\tsplit = dataFilter(data)\n\n\t\t\tout := strings.Join(split, \", \")\n\n\t\t\tlog.Println(out)\n\n\t\t\tfrequency, _ := strconv.ParseFloat(split[frequencyIdx], 64)\n\t\t\tselect {\n\t\t\tcase dutyCycleAndDistanceCh <- frequency:\n\t\t\tdefault:\n\t\t\t}\n\n\t\t\tfor i, attr := range split {\n\t\t\t\tattrValue, _ := strconv.ParseFloat(attr, 64)\n\n\t\t\t\tselect {\n\t\t\t\tcase serialAttrs[i].handleCh <- attrValue:\n\t\t\t\tdefault:\n\t\t\t\t}\n\n\t\t\t\tselect {\n\t\t\t\tcase serialAttrs[i].publishCh <- attr:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\t\tdata = data[:0]\n\t\t}\n\t}\n\n\treturn buf\n}", "func handlePacket(pkt *pcap.Packet) {\n\t// Ethernet frame has 14 bytes of stuff to ignore, so we start our root position here\n\tvar pos byte = 14\n\n\t// Grab the src IP address of this packet from the IP header.\n\tsrcIP := pkt.Data[pos+12 : pos+16]\n\tdstIP := pkt.Data[pos+16 : pos+20]\n\n\t// The IP frame has the header length in bits 4-7 of byte 0 (relative).\n\tpos += pkt.Data[pos] & 0x0F * 4\n\n\t// Grab the source port from the TCP header.\n\tsrcPort := uint16(pkt.Data[pos])<<8 + uint16(pkt.Data[pos+1])\n\tdstPort := uint16(pkt.Data[pos+2])<<8 + uint16(pkt.Data[pos+3])\n\n\t// The TCP frame has the data offset in bits 4-7 of byte 12 (relative).\n\tpos += byte(pkt.Data[pos+12]) >> 4 * 4\n\n\t// If this is a 0-length payload, do nothing. (Any way to change our filter\n\t// to only dump packets with data?)\n\tif len(pkt.Data[pos:]) <= 0 {\n\t\treturn\n\t}\n\n\t// This is either an inbound or outbound packet. Determine by seeing which\n\t// end contains our port. Either way, we want to put this on the channel of\n\t// the remote end.\n\tvar src string\n\tvar request bool = false\n\tif srcPort == port {\n\t\tsrc = fmt.Sprintf(\"%d.%d.%d.%d:%d\", dstIP[0], dstIP[1], dstIP[2],\n\t\t\tdstIP[3], dstPort)\n\t\t//\t\tlog.Printf(\"response to %s\", src)\n\t} else if dstPort == port {\n\t\tsrc = fmt.Sprintf(\"%d.%d.%d.%d:%d\", srcIP[0], srcIP[1], srcIP[2],\n\t\t\tsrcIP[3], srcPort)\n\t\trequest = true\n\t\t//\t\tlog.Printf(\"request from %s\", src)\n\t} else {\n\t\tlog.Fatalf(\"got packet src = %d, dst = %d\", srcPort, dstPort)\n\t}\n\n\t// Now we have the source and payload information, we can pass this off to\n\t// somebody who is better equipped to process it.\n\tgetChannel(src) <- &packet{request: request, data: pkt.Data[pos:]}\n}", "func (s *udtSocket) readPacket(m *multiplexer, p packet.Packet, from *net.UDPAddr) {\n\tnow := time.Now()\n\tif s.sockState == sockStateClosed {\n\t\treturn\n\t}\n\tif !from.IP.Equal(s.raddr.IP) || from.Port != s.raddr.Port {\n\t\tlog.Printf(\"Socket connected to %s received a packet from %s? Discarded\", s.raddr.String(), from.String())\n\t\treturn\n\t}\n\n\ts.recvEvent <- recvPktEvent{pkt: p, now: now}\n\n\tswitch sp := p.(type) {\n\tcase *packet.HandshakePacket: // sent by both peers\n\t\ts.readHandshake(m, sp, from)\n\tcase *packet.ShutdownPacket: // sent by either peer\n\t\ts.shutdownEvent <- shutdownMessage{sockState: sockStateClosed, permitLinger: true}\n\tcase *packet.AckPacket, *packet.LightAckPacket, *packet.NakPacket: // receiver -> sender\n\t\ts.sendEvent <- recvPktEvent{pkt: p, now: now}\n\tcase *packet.UserDefControlPacket:\n\t\ts.cong.onCustomMsg(*sp)\n\t}\n}", "func readData(conn net.Conn,\n\tdatalen uint16,\n\ttimeout time.Duration) ([]byte, error) {\n\trb := 0\n\ttb := int(datalen)\n\tdata := make([]byte, datalen)\n\n\tif timeout.Nanoseconds() != 0 {\n\t\t// The read operation will eventually timeout.\n\t\tconn.SetReadDeadline(time.Now().Add(timeout))\n\t} else {\n\t\t// The read operation will block forever whilst waiting for data.\n\t\tconn.SetReadDeadline(time.Time{})\n\t}\n\n\tfor rb < tb {\n\t\tnbytes, err := conn.Read(data[rb:])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\trb += nbytes\n\t}\n\n\treturn data, nil\n}", "func handlePacketDataTransfer(\n\tctx sdk.Context, k Keeper, packet channeltypes.Packet, data FungibleTokenPacketData,\n) (*sdk.Result, error) {\n\tif err := k.ReceiveTransfer(ctx, packet, data); err != nil {\n\t\t// NOTE (cwgoes): How do we want to handle this case? Maybe we should be more lenient,\n\t\t// it's safe to leave the channel open I think.\n\n\t\t// TODO: handle packet receipt that due to an error (specify)\n\t\t// the receiving chain couldn't process the transfer\n\n\t\t// source chain sent invalid packet, shutdown our channel end\n\t\tif err := k.ChanCloseInit(ctx, packet.DestinationPort, packet.DestinationChannel); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tacknowledgement := AckDataTransfer{}\n\tif err := k.PacketExecuted(ctx, packet, acknowledgement.GetBytes()); err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\tsdk.EventTypeMessage,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyModule, AttributeValueCategory),\n\t\t),\n\t)\n\n\treturn &sdk.Result{\n\t\tEvents: ctx.EventManager().Events().ToABCIEvents(),\n\t}, nil\n}", "func (s *session) handlePacket(p *receivedPacket) {\n\t// Discard packets once the amount of queued packets is larger than\n\t// the channel size, protocol.MaxSessionUnprocessedPackets\n\tselect {\n\tcase s.receivedPackets <- p:\n\tdefault:\n\t}\n}", "func data(number uint16) []byte {\n\tvar b bytes.Buffer\n\n\tstart := int(number) * 512\n\tif start > len(filedata) {\n\t\t// ignore the request, i.e. respond with zero bytes\n\t\tfmt.Print(\"end\\n\")\n\t\t//return terr(\"requested block beyond file\")\n\t\treturn b.Bytes()\n\t}\n\tend := start + 512\n\tif end > len(filedata) {\n\t\tend = len(filedata)\n\t}\n\tchunk := filedata[start:end]\n\tnumber += 1\n\tb.Grow(len(chunk) + 4)\n\tb.Write([]byte{0, 3})\n\tb.Write([]byte{\n\t\tbyte((number >> 8) & 0xff),\n\t\tbyte((number) & 0xff),\n\t})\n\tb.Write(chunk)\n\t// fmt.Printf(\"Sending block # %d\\n\", number)\n\tfmt.Printf(\".\")\n\treturn b.Bytes()\n}", "func (rhost *rhostData) cmdConnectData(rec *receiveData) (peer, addr string, port int, err error) {\n\n\t// Check data\n\tif rec == nil || rec.rd == nil || rec.rd.Data() == nil {\n\t\terr = errors.New(\"data not present\")\n\t\treturn\n\t}\n\n\t// Parse data\n\tdata := rec.rd.Data()\n\tvar portu uint32\n\n\t// \\TODO: fix it!!! From time to time teonet-go application send this data\n\t// with 255, 255 at the end. This code replace it to 0, 0. Neet to understand\n\t// what going on and fix it!\n\tl := len(data)\n\tif data[l-1] == 255 {\n\t\tdata[l-1] = 0\n\t}\n\tif data[l-2] == 255 {\n\t\tdata[l-2] = 0\n\t}\n\n\tbuf := bytes.NewBuffer(data)\n\tpeer, _ = buf.ReadString(0)\n\taddr, _ = buf.ReadString(0)\n\tbinary.Read(buf, binary.LittleEndian, &portu)\n\tpeer = strings.TrimSuffix(peer, \"\\x00\") // remove leading 0\n\taddr = strings.TrimSuffix(addr, \"\\x00\") // remove leading 0\n\tport = int(portu)\n\t//fmt.Printf(\"%v\\npeer: %s, addr: %s, port: %d\\n\", data, peer, addr, port)\n\treturn\n}", "func (c *curve) data(x, y *mod.Int) ([]byte, error) {\n\tb := c.encodePoint(x, y)\n\tdl := int(b[0])\n\tif dl > c.embedLen() {\n\t\treturn nil, errors.New(\"invalid embedded data length\")\n\t}\n\treturn b[1 : 1+dl], nil\n}", "func (pk PacketBufferPtr) Data() PacketData {\n\treturn PacketData{pk: pk}\n}", "func recvHeartBeat(sock *net.UDPConn, myMembers map[string]Entry, selfName string, c chan KVData) {\n\tfor {\n\t\t//we should change the byte length in the future\n\t\t//First initialize connection\n\t\tbuf := make([]byte, RECV_BUF_LEN)\n\t\t//fmt.Println(\"before\")\n\t\trlen, _, err := sock.ReadFromUDP(buf)\n\t\t//fmt.Println(\"after\")\n\t\tif QUIT == true {\n\t\t\treturn\n\t\t}\n\t\tlogError(err)\n\n\t\t//Second, setting up member information from retrieved value\n\t\tvar receivedMessage Message\n\t\terr = json.Unmarshal(buf[:rlen], &receivedMessage)\n\n\t\tif receivedMessage.Datatype == \"gossip\" {\n\t\t\treceivedMessageData := convertToEntryMap(receivedMessage.Data)\n\t\t\tgossipProtocolHandler(receivedMessageData, myMembers)\n\t\t} else if receivedMessage.Datatype == \"keyvalue\" {\n\t\t\treceivedMessageData := convertToKVData(receivedMessage.Data)\n\t\t\tkeyValueProtocolHandler(receivedMessageData, myMembers, selfName)\n\t\t} else if receivedMessage.Datatype == \"kvresp\" {\n\t\t\t//This handler is mainly just for testing client-stuff\n\t\t\treceivedMessageData := convertToKVData(receivedMessage.Data)\n\n\t\t\t//c <- receivedMessageData\n\n\t\t\tselect {\n\t\t\tcase c <- receivedMessageData:\n\t\t\tdefault:\n\t\t\t\t//fmt.Print(\"WARNING: Message received but not parsed | \")\n\t\t\t\t//fmt.Println(receivedMessageData)\n\t\t\t}\n\t\t} else if receivedMessage.Datatype == \"string\" {\n\t\t\tfmt.Println(receivedMessage.Data.(string))\n\t\t} else if receivedMessage.Datatype == \"batchkeys\" {\n\t\t\tbatchkeysProtocolHandler(receivedMessage.Data)\n\t\t} else if receivedMessage.Datatype == \"updateRM\" {\n\t\t\treceivedMessageData := convertToRM(receivedMessage.Data)\n\t\t\tupdateRMProtocolHandler(receivedMessageData, myMembers)\n\t\t} else if receivedMessage.Datatype == \"elected\" {\n\t\t\treceivedMessageData := convertToKVData(receivedMessage.Data)\n\t\t\tleaderProtocolHandler(receivedMessageData, myMembers)\n\t\t} else if receivedMessage.Datatype == \"first\" {\n\t\t\treceivedMessageData := convertToKVData(receivedMessage.Data)\n\t\t\tfirstKeyValueCommandHandler(receivedMessageData, myMembers)\n\t\t} else if receivedMessage.Datatype == \"leader-ask\" {\n\t\t\trequesting_ip := receivedMessage.Data.(string)\n\t\t\tleaderTellHandler(requesting_ip)\n\t\t} else if receivedMessage.Datatype == \"leader-tell\" {\n\t\t\tRM_LEADER = receivedMessage.Data.(string)\n\t\t} else if receivedMessage.Datatype == \"rmRequest\" {\n\t\t\trequesting_ip := receivedMessage.Data.(string)\n\t\t\trmRequestHandler(requesting_ip)\n\t\t} else if receivedMessage.Datatype == \"askforvalue\" {\n\t\t\trequestValueHandler(receivedMessage.Data.(string))\n\t\t} else if receivedMessage.Datatype == \"fillSparseEntry\" {\n\t\t\tfillSparseEntryHandler(receivedMessage.Data.(string), myMembers)\n\t\t}\n\t\tif err != nil {\n\t\t\tfmt.Print(\"MARSHALFAIL:\")\n\t\t\tfmt.Print(err)\n\t\t\tfmt.Println(time.Now())\n\t\t}\n\t}\n}", "func (rn *RicochetNetwork) SendRicochetPacket(conn net.Conn, channel int32, data []byte) {\n\theader := make([]byte, 4+len(data))\n\theader[0] = byte(len(header) >> 8)\n\theader[1] = byte(len(header) & 0x00FF)\n\theader[2] = 0x00\n\theader[3] = byte(channel)\n\tcopy(header[4:], data[:])\n\tconn.Write(header)\n}", "func packData(srcc <-chan string, destc chan<- []string) {\n\tt := time.NewTicker(500 * time.Millisecond)\n\tdefer t.Stop()\n\tdefer close(destc)\n\n\tvar ss []string\n\tfor {\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\tdestc <- ss\n\t\t\tfmt.Println(\"send data:\", ss)\n\n\t\t\tss = []string{}\n\t\tcase s, ok := <-srcc:\n\t\t\tif !ok {\n\n\t\t\t\t// send buffered data\n\t\t\t\tif len(ss) > 0 {\n\t\t\t\t\tdestc <- ss\n\t\t\t\t\tfmt.Println(\"send buffered data:\", ss)\n\t\t\t\t}\n\n\t\t\t\tfmt.Println(\"no src data anymore\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tss = append(ss, s)\n\t\t}\n\t}\n}", "func (c *ChannelData) Encode() {\n\tc.Raw = c.Raw[:0]\n\tc.WriteHeader()\n\tc.Raw = append(c.Raw, c.Data...)\n\tpadded := nearestPaddedValueLength(len(c.Raw))\n\tif bytesToAdd := padded - len(c.Raw); bytesToAdd > 0 {\n\t\tfor i := 0; i < bytesToAdd; i++ {\n\t\t\tc.Raw = append(c.Raw, 0)\n\t\t}\n\t}\n}", "func (transfer *RawSocketIO) receivePacket() RawPacket {\n\tif transfer.outPacketChan == nil {\n\t\tif _, err := transfer.startReceiveChannel(); err != nil {\n\t\t\treturn RawPacket{\n\t\t\t\tIoErr: err,\n\t\t\t}\n\t\t}\n\t}\n\treturn <-transfer.outPacketChan\n}", "func (f *framer) SendData(data []byte) []byte {\n\tbuf := make([]byte, len(data)+2)\n\tbinary.LittleEndian.PutUint16(buf[0:2], uint16(len(data)))\n\tcopy(buf[2:], data)\n\n\treturn buf\n}", "func (d PacketData) AsRange() Range {\n\treturn Range{\n\t\tpk: d.pk,\n\t\toffset: d.pk.dataOffset(),\n\t\tlength: d.Size(),\n\t}\n}", "func (kcp *KCP) Input(data []byte, regular, ackNoDelay bool) int {\n\tsnd_una := kcp.snd_una\n\t//if len(data) < IKCP_OVERHEAD {\n\t//\treturn -1\n\t//}\n\n\tvar latest uint32 // the latest ack packet\n\tvar flag int\n\tfor {\n\t\tvar ts, sn, una, conv uint32\n\t\tvar length, wnd uint16\n\t\tvar cmd, frg uint8\n\t\tleft_size := len(data)\n\n\t\tif left_size < int(IKCP_MINHEAD) {\n\t\t\tbreak\n\t\t}\n\n\t\tdata = ikcp_decode32u(data, &conv)\n\t\tif conv != kcp.conv {\n\t\t\treturn -1\n\t\t}\n\t\tdata = ikcp_decode8u(data, &cmd)\n\t\tif !(cmd > IKCP_CMD_BEG && cmd < IKCP_CMD_END) {\n\t\t\treturn -3\n\t\t}\n\n\t\tif cmd == IKCP_CMD_SYN || cmd == IKCP_CMD_PUSH {\n\t\t\tif left_size < int(IKCP_OVERHEAD) {\n\t\t\t\tfmt.Println(\"error recv err data cmd\", cmd, \"len\", len(data), \"too short\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdata = ikcp_decode8u(data, &frg)\n\t\t\tdata = ikcp_decode16u(data, &wnd)\n\t\t\tdata = ikcp_decode32u(data, &ts)\n\t\t\tdata = ikcp_decode32u(data, &sn)\n\t\t\tdata = ikcp_decode32u(data, &una)\n\t\t\tdata = ikcp_decode16u(data, &length)\n\t\t\tif len(data) < int(length) {\n\t\t\t\treturn -2\n\t\t\t}\n\t\t} else {\n\t\t\tdata = ikcp_decode16u(data, &wnd)\n\t\t\tdata = ikcp_decode32u(data, &ts)\n\t\t\tdata = ikcp_decode32u(data, &sn)\n\t\t\tdata = ikcp_decode32u(data, &una)\n\t\t}\n\n\t\t// only trust window updates from regular packets. i.e: latest update\n\t\tif regular {\n\t\t\tkcp.rmt_wnd = uint32(wnd)\n\t\t}\n\t\tkcp.parse_una(una)\n\t\tkcp.shrink_buf()\n\n\t\tif cmd == IKCP_CMD_ACK {\n\t\t\tkcp.parse_ack(sn)\n\t\t\tkcp.parse_fastack(sn, ts)\n\t\t\tflag |= 1\n\t\t\tlatest = ts\n\t\t} else if cmd == IKCP_CMD_PUSH {\n\t\t\tif _itimediff(sn, kcp.rcv_nxt+kcp.rcv_wnd) < 0 {\n\t\t\t\tkcp.ack_push(sn, ts)\n\t\t\t\tif _itimediff(sn, kcp.rcv_nxt) >= 0 {\n\t\t\t\t\tseg := kcp.newSegment(int(length))\n\t\t\t\t\tseg.conv = conv\n\t\t\t\t\tseg.cmd = cmd\n\t\t\t\t\tseg.frg = frg\n\t\t\t\t\tseg.wnd = wnd\n\t\t\t\t\tseg.ts = ts\n\t\t\t\t\tseg.sn = sn\n\t\t\t\t\tseg.una = una\n\t\t\t\t\tseg.data.Write(data[:length]) // delayed data copying\n\t\t\t\t\tkcp.parse_data(seg)\n\t\t\t\t\t//repeat = kcp.parse_data(seg)\n\t\t\t\t}\n\t\t\t}\n\t\t\t//if regular && repeat {\n\t\t\t//\tatomic.AddUint64(&DefaultSnmp.RepeatSegs, 1)\n\t\t\t//}\n\t\t} else if cmd == IKCP_CMD_WASK {\n\t\t\t// ready to send back IKCP_CMD_WINS in Ikcp_flush\n\t\t\t// tell remote my window size\n\t\t\tkcp.probe |= IKCP_ASK_TELL\n\t\t} else if cmd == IKCP_CMD_WINS {\n\t\t\t// do nothing\n\t\t} else if cmd == IKCP_CMD_SYN {\n\t\t\tfmt.Println(\"recv SYN\")\n\t\t\t//kcp.ack_push(sn, ts)\n\t\t\tif !kcp.syn {\n\t\t\t\tkcp.syn = true\n\t\t\t\tkcp.rcv_nxt++\n\t\t\t}\n\t\t} else if cmd == IKCP_CMD_CLOSE {\n\t\t\tkcp.close_second = true\n\t\t\tif kcp.close_first {\n\t\t\t\tkcp.close_confirm = true\n\t\t\t}\n\t\t} else if cmd == IKCP_CMD_CLOSE_CONFIRM {\n\t\t\tif kcp.close_confirm {\n\t\t\t\tkcp.close_final = true\n\t\t\t\tkcp.state = IKCP_STATE_EOF\n\t\t\t} else {\n\t\t\t\tkcp.close_confirm = true\n\t\t\t}\n\t\t\treturn 0\n\t\t} else if cmd == IKCP_CMD_RESET {\n\t\t\tkcp.close_final = true\n\t\t\tkcp.state = -IKCP_STATE_RESET\n\t\t} else {\n\t\t\treturn -3\n\t\t}\n\n\t\tdata = data[length:]\n\t}\n\t//atomic.AddUint64(&DefaultSnmp.InSegs, inSegs)\n\n\t// update rtt with the latest ts\n\t// ignore the FEC packet\n\tif flag != 0 && regular {\n\t\tcurrent := currentMs()\n\t\tif _itimediff(current, latest) >= 0 {\n\t\t\tkcp.update_ack(_itimediff(current, latest))\n\t\t}\n\t}\n\n\t// cwnd update when packet arrived\n\tif kcp.nocwnd == 0 {\n\t\tif _itimediff(kcp.snd_una, snd_una) > 0 {\n\t\t\tif kcp.cwnd < kcp.rmt_wnd {\n\t\t\t\tmss := kcp.mss\n\t\t\t\tif kcp.cwnd < kcp.ssthresh {\n\t\t\t\t\tkcp.cwnd++\n\t\t\t\t\tkcp.incr += mss\n\t\t\t\t} else {\n\t\t\t\t\tif kcp.incr < mss {\n\t\t\t\t\t\tkcp.incr = mss\n\t\t\t\t\t}\n\t\t\t\t\tkcp.incr += (mss*mss)/kcp.incr + (mss / 16)\n\t\t\t\t\tif (kcp.cwnd+1)*mss <= kcp.incr {\n\t\t\t\t\t\tkcp.cwnd++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif kcp.cwnd > kcp.rmt_wnd {\n\t\t\t\t\tkcp.cwnd = kcp.rmt_wnd\n\t\t\t\t\tkcp.incr = kcp.rmt_wnd * mss\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif !kcp.syn {\n\t\treturn 0\n\t}\n\n\treturn 0\n}", "func dataBlock(value ...uint16) []byte {\n\tdata := make([]byte, 2*len(value))\n\tfor i, v := range value {\n\t\tbinary.BigEndian.PutUint16(data[i*2:], v)\n\t}\n\treturn data\n}", "func (c *ForwardClient) DataStart(sc chan bool, dc chan string) error {\n\tlog.Printf(\"forwardData() Seting up channel and waiting for data\")\n\n\tvar err error\n\tc.writer, err = c.sess.Data()\n\tif err != nil {\n\t\t// If we can't get the data session going log an error and\n\t\t// let those waiting for us that things went bad\n\t\terr = c.handleClientError(\"Could not start DATA transmission\", err)\n\t\tsc <- false\n\t\treturn err\n\t}\n\n\t// Tell others we are ready to go\n\tsc <- true\n\n\tfor v := range dc {\n\t\t// TODO: Figure out how to flush this immediately\n\t\t// TODO: Error Checking ??\n\t\t// Otherwise it buffers until we close it\n\t\tlog.Printf(\"On Channel: %s\", v)\n\t\t_, err = io.WriteString(c.writer, v)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error writing to client: %v\", err)\n\t\t}\n\n\t\t// Update the timeouts\n\t\tc.resetDeadlines()\n\t}\n\n\t// Update timeouts for client\n\tc.resetDeadlines()\n\n\t// Complete the Data transfer\n\tlog.Println(\"Closing connection to 127.0.0.1:4444\")\n\terr = c.writer.Close()\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: Failed to Close data session: %s\", err)\n\t\tsc <- false\n\t\treturn nil\n\t}\n\tlog.Println(\"Data transfer to client complete!\")\n\n\t// Close the connection to the remote server\n\terr = c.sess.Quit()\n\tif err != nil {\n\t\tlog.Printf(\"WARNING: Failed to QUIT SMTP session: %s\", err)\n\t}\n\n\t// Tell others that we have finished\n\tsc <- true\n\n\treturn nil\n}", "func main() {\n\tgo func() {\n\t\tlog.Println(http.ListenAndServe(\"localhost:6060\", nil))\n\t}()\n\n\tvar workerNum = 1\n\tvar channelBufferSize = 100\n\tvar dataChannel = make(chan []byte, channelBufferSize)\n\n\thandle, err := pcap.OpenLive(\"en5\", 65536, false, 10 * time.Millisecond)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer handle.Close()\n\n\n\tmenu := 1\n\n\tfor i := 0; i < workerNum; i += 1 {\n\t\tw := engine.NewWorker()\n\n\t\tif menu == 1 {\n\n\t\t\tgo w.Decode(dataChannel)\n\t\t} else {\n\n\t\t}\n\n\t}\n\n\t//go func() {\n\t//\tfor {\n\t//\t\tdata, _, _ := handle.ZeroCopyReadPacketData()\n\t//\t\tdataChannel <- data\n\t//\t\t//fmt.Println(data)\n\t//\t}\n\t//}()\n\n\tpacketSource := gopacket.NewPacketSource(handle, handle.LinkType())\n\two := engine.NewWorker()\n\tgo wo.Decode2(packetSource)\n\n\ttime.Sleep(1 * time.Second)\n}", "func handlePacket(c *Conn, data []byte, addr Addr,\n\trh Handler) {\n\n\tmsg, err := ParseDgramMessage(data)\n\tif err != nil {\n\t\tlog.Printf(\"Error parsing %v\", err)\n\t\treturn\n\t}\n\n\trv := rh.ServeCOAP(c, msg)\n\tif rv != nil {\n\t\tTransmit(c, addr, rv)\n\t}\n}", "func (o *IPFixGen) sendDataPkt() {\n\tvar restartTimer = true\n\n\tif o.enabled {\n\t\t// Only Data Packets can have bursts.\n\t\tfor i := 0; i < int(o.dataPktsPerInterval); i++ {\n\t\t\tif o.paused {\n\t\t\t\to.ipfixPlug.stats.genPausedSkipWrite++\n\t\t\t\trestartTimer = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif o.isReachedMaxDataRecordsToSend() {\n\t\t\t\t// Max tx data records reached - no need to restart data timer.\n\t\t\t\trestartTimer = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\to.sendDataPktInt()\n\t\t}\n\t}\n\n\tif restartTimer {\n\t\to.timerw.StartTicks(&o.dataTimer, o.dataTicks)\n\t}\n}", "func ReadPacket(r io.Reader) (*ControlPacket, error) {\n\tt := [1]byte{}\n\t_, err := io.ReadFull(r, t[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// cp := NewControlPacket(PacketType(t[0] >> 4))\n\t// if cp == nil {\n\t// \treturn nil, fmt.Errorf(\"invalid packet type requested, %d\", t[0]>>4)\n\t// }\n\n\tpt := t[0] >> 4\n\tcp := &ControlPacket{FixedHeader: FixedHeader{Type: pt}}\n\tswitch pt {\n\tcase CONNECT:\n\t\tcp.Content = &Connect{\n\t\t\tProtocolName: \"MQTT\",\n\t\t\tProtocolVersion: 5,\n\t\t\tProperties: &Properties{},\n\t\t}\n\tcase CONNACK:\n\t\tcp.Content = &Connack{Properties: &Properties{}}\n\tcase PUBLISH:\n\t\tcp.Content = &Publish{Properties: &Properties{}}\n\tcase PUBACK:\n\t\tcp.Content = &Puback{Properties: &Properties{}}\n\tcase PUBREC:\n\t\tcp.Content = &Pubrec{Properties: &Properties{}}\n\tcase PUBREL:\n\t\tcp.Flags = 2\n\t\tcp.Content = &Pubrel{Properties: &Properties{}}\n\tcase PUBCOMP:\n\t\tcp.Content = &Pubcomp{Properties: &Properties{}}\n\tcase SUBSCRIBE:\n\t\tcp.Flags = 2\n\t\tcp.Content = &Subscribe{\n\t\t\tSubscriptions: make(map[string]SubOptions),\n\t\t\tProperties: &Properties{},\n\t\t}\n\tcase SUBACK:\n\t\tcp.Content = &Suback{Properties: &Properties{}}\n\tcase UNSUBSCRIBE:\n\t\tcp.Flags = 2\n\t\tcp.Content = &Unsubscribe{Properties: &Properties{}}\n\tcase UNSUBACK:\n\t\tcp.Content = &Unsuback{Properties: &Properties{}}\n\tcase PINGREQ:\n\t\tcp.Content = &Pingreq{}\n\tcase PINGRESP:\n\t\tcp.Content = &Pingresp{}\n\tcase DISCONNECT:\n\t\tcp.Content = &Disconnect{Properties: &Properties{}}\n\tcase AUTH:\n\t\tcp.Flags = 1\n\t\tcp.Content = &Auth{Properties: &Properties{}}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown packet type %d requested\", pt)\n\t}\n\n\tcp.Flags = t[0] & 0xF\n\tif cp.Type == PUBLISH {\n\t\tcp.Content.(*Publish).QoS = (cp.Flags & 0x6) >> 1\n\t}\n\tvbi, err := getVBI(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcp.remainingLength, err = decodeVBI(vbi)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar content bytes.Buffer\n\tcontent.Grow(cp.remainingLength)\n\n\tn, err := io.CopyN(&content, r, int64(cp.remainingLength))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif n != int64(cp.remainingLength) {\n\t\treturn nil, fmt.Errorf(\"failed to read packet, expected %d bytes, read %d\", cp.remainingLength, n)\n\t}\n\terr = cp.Content.Unpack(&content)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cp, nil\n}", "func (lg *logger) packet(s string) *raven.Packet {\n\n\tp := raven.NewPacket(s)\n\tfor k, v := range lg.buffer.Data {\n\t\tp.Extra[k] = v\n\t}\n\tp.Level = raven.INFO\n\tp.Logger = lg.scope\n\n\treturn p\n\n}", "func set_channel(c spi.Conn, channel uint8) {\n\tif (channel > 125) {\n\t\tchannel = 125\n\t}\n\twrite_register(c, RfCh, channel)\n}", "func NewPacket(data []byte, len uint32) *Packet {\n\treturn &Packet{\n\t\tTime: time.Now(),\n\t\tCaplen: len,\n\t\tLen: len,\n\t\tData: data,\n\t}\n}", "func (hf *HeaderFrame) Channel() uint16 { return hf.ChannelID }", "func (w *chanWriter) Write(data []byte) (written int, err error) {\n\tfor len(data) > 0 {\n\t\tfor w.rwin < 1 {\n\t\t\twin, ok := <-w.win\n\t\t\tif !ok {\n\t\t\t\treturn 0, io.EOF\n\t\t\t}\n\t\t\tw.rwin += win\n\t\t}\n\t\tn := min(len(data), w.rwin)\n\t\tpeersId := w.clientChan.peersId\n\t\tpacket := []byte{\n\t\t\tmsgChannelData,\n\t\t\tbyte(peersId >> 24), byte(peersId >> 16), byte(peersId >> 8), byte(peersId),\n\t\t\tbyte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n),\n\t\t}\n\t\tif err = w.clientChan.writePacket(append(packet, data[:n]...)); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tdata = data[n:]\n\t\tw.rwin -= n\n\t\twritten += n\n\t}\n\treturn\n}", "func incomingData() {\n\tfor {\n\t\tblock := <-p2p.BlockIn\n\t\tprocessBlock(block)\n\t}\n}", "func handleReadRequest(controlChannel *net.UDPConn, inputFileName string, outputFileName string) { \n\n\tfmt.Println(\"Sending Read request.\")\n initialPacket := constructInitialPacket(1, inputFileName)\n\tclientAddr:= controlChannel.LocalAddr()\n\tclientAddrStr := clientAddr.String()\n\tclientPort := strings.Split(clientAddrStr, \":\")\n\tfmt.Println(\"Client Port is : \", clientPort[1])\n _, errInitialPk := controlChannel.Write(initialPacket)\n check(errInitialPk)\n controlChannel.Close() \n\t\n\t/* Data Channel */\n\t\n\tvar ingressBuf [516]byte\n var ingressBufSize int\n var serverAddr *net.UDPAddr\n var clientDataBuf bytes.Buffer\n\tvar prevBlockNum uint16 = 0\n var blockNum uint16 = 0\n\tvar lastPacket bool = false\n\t\n\tnewService := \"127.0.0.1:\"+clientPort[1]\n\tnewudpAddr, err := net.ResolveUDPAddr(\"udp\", newService)\n\tcheck(err)\n\tdataChannel, err := net.ListenUDP(\"udp\", newudpAddr)\n\tcheck(err) \n \n /* Setting the read timeout limit for all data packets from the server to 8 seconds */\t\n\tdataChannel.SetReadDeadline(time.Now().Add(time.Second * 8))\n\t\n\tfor {\n\t /* For the last data packet, wait for additional 8 seconds after it has been sent to the server. */\n /* This handles the case when the last packet has been sent by client but not received by server. */\n /* If the server resends the Ack for previous data packet, client sends the last data packet again */\n /* File is created only after the entire content is read from the server */\n\t\t\t\n\t\t if lastPacket == true {\n\t\t\t _, _, err := dataChannel.ReadFromUDP(ingressBuf[0:])\n\t\t\t if neterr, ok := err.(net.Error); ok && neterr.Timeout() {\n\t\t\t\t fileWrite, err := os.Create(outputFileName)\n\t check(err)\n\t\t _, errOutput := fileWrite.WriteString(clientDataBuf.String())\n\t check(errOutput)\n\t\t fileWrite.Close()\n\t\t\t\t fmt.Println(\"File has been fully read from the server into the current directory.\")\n\t\t\t\t break\n\t\t\t }\n\t\t\t} else {\n\t ingressBufferSize, remoteAddr, err := dataChannel.ReadFromUDP(ingressBuf[0:])\n\t\t\t\t if neterr, ok := err.(net.Error); ok && neterr.Timeout() {\n\t\t\t fmt.Println(\"Server timed out. Closing connection. Try again.\")\n\t\t\t\t break\n\t\t\t }\n\t\t\t\t ingressBufSize = ingressBufferSize\n\t\t\t\t serverAddr = remoteAddr\n\t\t\t}\n\t\t\tingressByte := convertDataIngressBufType(ingressBuf)\n\t\t\topcode := getOpcode(ingressByte)\n\t\t\t/* Received Error Packet from the server */\n\t\t\tif opcode == 5 {\n\t\t\t fmt.Println(\"Data transfer did not succeed. Closing connection. Try again.\")\n\t\t\t break\n\t\t\t}\n\t\t\tblockNum = getBlockNum(ingressByte)\n\t\t\tfmt.Println(\"Received Data Block \", blockNum)\n\t\t\t\n\t\t\t/* Storing only unique data blocks in the buffer */ \n\t\t\t/* If Data is received and stored but if Ack did not reach the server, */\n\t\t\t/* data will be resent from server. In this case, no need to store it in the buffer again. */\n\t\t\t\n\t\t\tif prevBlockNum < blockNum { \n ingressDataBuf := getIngressData(ingressByte, ingressBufSize)\n clientDataBuf.Grow(len(ingressDataBuf)) \t\t\t\n\t _, err := clientDataBuf.Write(ingressDataBuf)\n\t check(err)\n\t\t\t}\n\t\t\t\n\t\t\t/* If Ack from client did not reach the server, server will timeout and send prev data packet again. */\n /* So send the Ack for the prev data block again to ensure that server will move onto the next data packet */\n\t\t\t\n\t\t\tprevBlockNum = blockNum\n\t\t\tackBuf := constructAckPacket(4, prevBlockNum)\n\t\t\t_, errWr1 := dataChannel.WriteToUDP(ackBuf, serverAddr)\n check(errWr1)\n\t\t\tfmt.Println(\"Sent Ack for block: \", prevBlockNum)\n\t\t\tif ingressBufSize < 516 {\n\t\t\t lastPacket = true\n\t\t\t}\t\n\t\t}\n\t\tdataChannel.Close()\n os.Exit(0)\n}", "func (kcp *KCP) parseData(newseg *segment) bool {\n\trepeat := false\n\tsn := newseg.sn\n\tif timediff(sn, kcp.recvNext+kcp.recvWnd) >= 0 || timediff(sn, kcp.recvNext) < 0 {\n\t\treturn true\n\t}\n\n\tistIdx := 0\n\tfor idx := len(kcp.recvBuffer) - 1; idx >= 0; idx-- {\n\t\tseg := kcp.recvBuffer[idx]\n\t\tif seg.sn == sn {\n\t\t\t// repeat message package\n\t\t\trepeat = true\n\t\t\tbreak\n\t\t}\n\n\t\tif timediff(sn, seg.sn) > 0 {\n\t\t\tistIdx = idx + 1\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !repeat {\n\t\tif istIdx == len(kcp.recvBuffer) {\n\t\t\tkcp.recvBuffer = append(kcp.recvBuffer, newseg)\n\t\t} else {\n\t\t\tkcp.recvBuffer = append(kcp.recvBuffer, &segment{})\n\t\t\tcopy(kcp.recvBuffer[istIdx+1:], kcp.recvBuffer[istIdx:])\n\t\t\tkcp.recvBuffer[istIdx] = newseg\n\t\t}\n\t}\n\n\t// move available data from recvBuffer -> recvQueue\n\tcount := 0\n\tfor idx := range kcp.recvBuffer {\n\t\tseg := kcp.recvBuffer[idx]\n\t\tif seg.sn == kcp.recvNext && len(kcp.recvBuffer) < int(kcp.recvWnd) {\n\t\t\tcount++\n\t\t\tkcp.recvNext++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif count > 0 {\n\t\tkcp.recvQueue = append(kcp.recvQueue, kcp.recvBuffer[:count]...)\n\t\tkcp.recvBuffer = removeFront(kcp.recvBuffer, count)\n\t}\n\n\treturn repeat\n}", "func (p *Packet) AvPacketFromData(d *uint8, s int) int {\n\treturn int(C.av_packet_from_data((*C.struct_AVPacket)(p), (*C.uint8_t)(d), C.int(s)))\n\n}", "func (d PacketData) ReadFromPacketData(oth PacketData, count int) {\n\tbuf := oth.ToBuffer()\n\tbuf.Truncate(int64(count))\n\td.MergeBuffer(&buf)\n\toth.TrimFront(count)\n\tbuf.Release()\n}", "func (p *Packet) GetData() []byte {\n\treturn p.Data\n}", "func (c *Client) loopRaw(ch chan<- int16, bytes []byte) {\n\tdefer close(ch)\n\n\taudioFrameSize := c.Mumble.Config.AudioFrameSize()\n\tvolume := MaxVolume - c.Volume()\n\tfor i := 0; true; i = (i + 1) % (len(bytes) / 2) {\n\t\tch <- int16(binary.LittleEndian.Uint16(bytes[i*2:i*2+2])) >> volume\n\n\t\t// Do the slow updates every frame\n\t\tif i%audioFrameSize == 0 {\n\t\t\tvolume = MaxVolume - c.Volume()\n\t\t\tif c.Mumble.AudioStopped() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}", "func (cc *clientConn) readPacket() (byte, []byte, error) {\n\treturn 0x00, nil, nil\n}", "func NewPacket(data []byte, code byte, length int) (p *Packet) {\n\tp = &Packet{\n\t\tData: data,\n\t\tCode: code,\n\t\tLength: length,\n\t}\n\treturn p\n}", "func (packet *Packet) Data() []byte {\n\treturn packet.data\n}", "func readPacket(r io.Reader) ([]byte, error) {\n\tvar buf [257]byte\n\tif _, err := r.Read(buf[:2]); err != nil {\n\t\tif err == io.EOF {\n\t\t\terr = io.ErrUnexpectedEOF\n\t\t}\n\t\treturn nil, err\n\t}\n\tpacket := buf[:2+buf[1]]\n\tif _, err := r.Read(packet[2:]); err != nil {\n\t\tif err == io.EOF {\n\t\t\terr = io.ErrUnexpectedEOF\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn packet, nil\n}", "func (bf *BodyFrame) Channel() uint16 { return bf.ChannelID }", "func routineBuffer(){\n\tchannel := make(chan int,4)//make channel and add buffer\n\twg.Add(2)\n\t//receive from channel\n\tgo func(channel <- chan int){\n\t\t//loop throug the channel\n\t\tfor i := range channel{\n\t\t\tfmt.Println(i)\n\t\t}\n\t\twg.Done()\n\t}(channel)\n\t//sending to channel\n\tgo func(channel chan <- int){\n\t\tchannel <- 100\n\t\tchannel <- 200\n\t\tclose(channel) //after sending close the channel \n\t\twg.Done()\n\t}(channel)\n\twg.Wait()\n}", "func handleWriteRequest(controlChannel *net.UDPConn, inputFileName string, outputFileName string) { \n\n fmt.Println(\"Sending write request.\")\n initialPacket := constructInitialPacket(2, outputFileName)\n\tclientAddr:= controlChannel.LocalAddr()\n\tclientAddrStr := clientAddr.String()\n\tclientPort := strings.Split(clientAddrStr, \":\")\n\tfmt.Println(\"Client Port is : \", clientPort[1])\n _, errWrite := controlChannel.Write(initialPacket)\n check(errWrite)\n controlChannel.Close()\n\t\n\t/* Data Channel */\n\t\n\tvar ingressBuf [4]byte\n\tprevDataPacket := make([]byte, 512)\n\tvar serverAddr *net.UDPAddr\n\tvar expectedBlockNum uint16 = 0\n\tvar lastPacket bool = false\n\tvar firstAck bool = true\n\tvar retryCount int = 1\n\tvar closeConn bool = false\n\t\n\tnewService := \"127.0.0.1:\"+clientPort[1]\n\tnewudpAddr, err := net.ResolveUDPAddr(\"udp\", newService)\n\tcheck(err)\n\tdataChannel, err := net.ListenUDP(\"udp\", newudpAddr)\n\tcheck(err) \n\tfileRead, err := os.Open(inputFileName) \n check(err)\n\t\n\t/* Read timeout for Ack from the server is set to 4 seconds */\n\tdataChannel.SetReadDeadline(time.Now().Add(time.Second * 4))\n \n\t/* The first Ack from the server is for block 0. It is to start the data transfer from the client. */\n\t/* If first Ack did not reach the client within the timeout period, datachannel client connection is closed */\n\t/* For other Acks, the previous data packet is retransmitted upto 4 times after the timeouts before closing the connection. */\n\t\n\tfor {\n\t for { \n\t _, remoteAddr, err := dataChannel.ReadFromUDP(ingressBuf[0:])\n\t\t if neterr, ok := err.(net.Error); ok && neterr.Timeout() {\n\t\t\t if firstAck == false {\n\t\t\t\t if retryCount == 4 {\n\t\t\t\t\t closeConn = true\n\t\t\t\t\t break\n\t\t\t\t\t}\n\t\t\t\t\t_, errWr := dataChannel.WriteToUDP(prevDataPacket, remoteAddr)\n check(errWr)\n\t\t\t\t\tretryCount += 1\n\t\t\t\t} else {\n\t\t\t\t fmt.Println(\"Server timed out. Closing connection. Try again.\") \n\t\t\t\t\tcloseConn = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} else {\n serverAddr = remoteAddr\t\t\t \n\t\t\t break\n\t\t\t}\n\t\t}\n\t\tif closeConn == true {\n\t\t break\n\t\t}\n\t\tingressByte := convertAckIngressBufType(ingressBuf)\n\t\topcode := getOpcode(ingressByte)\n\t\tif opcode != 4 {\n\t\t fmt.Println(\"Data transfer did not succeed. Closing connection. Try again.\")\n\t\t break\n\t\t}\n\t\tblockNum := getBlockNum(ingressByte)\n\t\tfmt.Println(\"Received Ack for block: \", blockNum)\n\t\tfirstAck = false\n\t\t\n\t\t/* When the Ack for last packet is received, client successfully closes the connection */\n\t\tif blockNum == expectedBlockNum {\n\t\t if lastPacket == true {\n\t\t fmt.Println(\"File has been successfully written to the server.\")\n\t\t break\n\t\t }\n\t\t inputBuf := make([]byte, 512)\n inputBufSize, err := fileRead.Read(inputBuf)\n\t\t /* If there is a file read failure send error packet to server */\n\t\t if err != nil {\n\t\t errorPacket := constructErrorPacket(5)\n\t\t\t _, errToServer := dataChannel.WriteToUDP(errorPacket, serverAddr)\n check(errToServer)\n\t\t\t break\n\t\t }\n\t\t expectedBlockNum = expectedBlockNum+1\n\t\t dataPacket := constructDataPacket(expectedBlockNum, inputBuf, inputBufSize)\n\t\t _, errWrite := dataChannel.WriteToUDP(dataPacket, serverAddr)\n check(errWrite)\n\t\t if len(dataPacket) < 516 {\n\t\t lastPacket = true\n\t\t }\n\t\t fmt.Println(\"Sent data block \", expectedBlockNum)\n\t\t prevDataPacket = make([]byte, len(dataPacket))\n\t\t prevDataPacket = dataPacket\n\t\t} else {\n\t\t fmt.Println(\"Data transfer did not succeed. Closing connection. Try again.\")\n\t\t break\n\t\t}\n\t}\n\tfileRead.Close()\n\tdataChannel.Close()\n os.Exit(0)\n}", "func parsePacketV2(data []byte) ([]byte, packetV2, error) {\n\tdata, ft, err := parseVarint(data)\n\tif err != nil {\n\t\treturn nil, packetV2{}, err\n\t}\n\tp := packetV2{\n\t\tfieldType: fieldType(ft),\n\t}\n\tif p.fieldType == fieldEOS {\n\t\treturn data, p, nil\n\t}\n\tdata, payloadLen, err := parseVarint(data)\n\tif err != nil {\n\t\treturn nil, packetV2{}, err\n\t}\n\tif payloadLen > len(data) {\n\t\treturn nil, packetV2{}, fmt.Errorf(\"field data extends past end of buffer\")\n\t}\n\tp.data = data[0:payloadLen]\n\treturn data[payloadLen:], p, nil\n}", "func (d *DataPacket) copy() DataPacket {\n\tcopySlice := make([]byte, len(d.data))\n\tcopy(copySlice, d.data)\n\treturn DataPacket{\n\t\tdata: copySlice,\n\t\tlength: d.length,\n\t}\n}", "func (r *Reader) readPacket() ([]byte, error) {\n\tfor {\n\t\ts, err := r.Reader.ReadLine()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t} else if len(s) == 0 || s[len(s)-1] != lineDelim {\n\t\t\treturn nil, errors.New(\"invalid packet delimiter\")\n\t\t}\n\t\tif len(s) > 1 {\n\t\t\treturn s, nil\n\t\t}\n\t\t// clients may send message containing only 0x0a byte to keep connection alive\n\t\tif r.OnKeepAlive != nil {\n\t\t\tif err := r.OnKeepAlive(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n}", "func newNetBufPayload(data []byte) (*netBuf, []byte) {\n\tnb := &netBuf{\n\t\tbuf: data,\n\t\tpool: -1,\n\t}\n\treturn nb, nb.buf\n}", "func setupNonblockingChannelTest(logf logger.Logf, traf *TrafficGen) {\n\tch := make(chan []byte, 1000)\n\n\tgo func() {\n\t\t// transmitter\n\t\tfor {\n\t\t\tb := make([]byte, 1600)\n\t\t\tn := traf.Generate(b, 16)\n\t\t\tif n == 0 {\n\t\t\t\tclose(ch)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase ch <- b[0 : n+16]:\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\t}()\n\n\tgo func() {\n\t\t// receiver\n\t\tfor b := range ch {\n\t\t\ttraf.GotPacket(b, 16)\n\t\t}\n\t}()\n}", "func readGMPacket(c Client, cb func(Message) error) error {\n\theader := make([]byte, 12)\n\tif _, err := io.ReadFull(c.conn, header); err != nil {\n\t\treturn err\n\t}\n\theader1 := uint32(binary.LittleEndian.Uint32(header[0:4]))\n\theader2 := uint32(binary.LittleEndian.Uint32(header[4:8]))\n\theader3 := uint32(binary.LittleEndian.Uint32(header[8:12]))\n\tif header1 != gmMagicNumber1 {\n\t\treturn fmt.Errorf(\"packet contains invalid identifier/magic number\")\n\t}\n\tif header2 != uint32(12) {\n\t\treturn fmt.Errorf(\"packet header size is not 12\")\n\t}\n\tpayload := make([]byte, header3)\n\tif _, err := io.ReadFull(c.conn, payload); err != nil {\n\t\treturn err\n\t}\n\tif len(payload) != 0 {\n\t\tbuffer := Packet{payload: payload[1:]}\n\t\treturn cb(Message{Client: c, EventType: ClientData, DataType: int(payload[0]), Buffer: &buffer})\n\t}\n\treturn nil\n}", "func (c *SquareChannel) SetValue(address uint16, data uint8) {\n\tswitch address {\n\t// Sweep period, negate, shift\n\tcase 0xFF10:\n\t\tc.SweepPeriodData = (data >> 4) & 0x7\n\t\tc.SweepNegate = (data & 0x8) == 0x8\n\t\tc.SweepShift = data & 0x7\n\t\tbreak\n\t// Duty, Length load (64-L)\n\tcase 0xFF11:\n\t\tfallthrough\n\tcase 0xFF16:\n\t\tc.DutyCounter = (data >> 6) & 0x3\n\t\tc.LengthData = data & 0x3F\n\t\tbreak\n\t// Starting volume, Envelope add mode, period\n\tcase 0xFF12:\n\t\tfallthrough\n\tcase 0xFF17:\n\t\t// DAC\n\t\tc.DACEnabled = (data & 0xF8) != 0\n\t\tc.VolumeData = (data >> 4) & 0xF\n\t\tc.envelopeAddMode = (data & 0x8) == 0x8\n\t\tc.envelopePeriodData = (data & 0x7)\n\t\tc.Volume = c.VolumeData\n\t\tbreak\n\t// Frequency LSB\n\tcase 0xFF13:\n\t\tfallthrough\n\tcase 0xFF18:\n\t\tc.FrequencyData = (c.FrequencyData & 0x700) | uint16(data)\n\t\tbreak\n\t// Trigger, Length enable, Frequency MSB\n\tcase 0xFF14:\n\t\tfallthrough\n\tcase 0xFF19:\n\t\tc.FrequencyData = (c.FrequencyData & 0xFF) | (uint16(data)&0x7)<<8\n\t\tc.LengthEnabled = (data & 0x40) == 0x40\n\t\tc.Trigger = (data & 0x80) == 0x80\n\t\tif c.Trigger {\n\t\t\tc.executeTrigger()\n\t\t}\n\t\tbreak\n\t}\n}", "func setupBlockingChannelTest(logf logger.Logf, traf *TrafficGen) {\n\tch := make(chan []byte, 1000)\n\n\tgo func() {\n\t\t// transmitter\n\t\tfor {\n\t\t\tb := make([]byte, 1600)\n\t\t\tn := traf.Generate(b, 16)\n\t\t\tif n == 0 {\n\t\t\t\tclose(ch)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tch <- b[0 : n+16]\n\t\t}\n\t}()\n\n\tgo func() {\n\t\t// receiver\n\t\tfor b := range ch {\n\t\t\ttraf.GotPacket(b, 16)\n\t\t}\n\t}()\n}", "func sendToPacketInfoChan(b *bytes.Buffer, conn net.Conn, c chan *packetInfo, t *Tracker) error {\n\tdefer b.Reset()\n\n\tpdata := new(message.Packets)\n\n\terr := proto.Unmarshal(b.Bytes(), pdata)\n\tif err != nil {\n\t\tif debugMode {\n\t\t\tfmt.Println(\"[Error] Unmarshal failed:\", b.Bytes())\n\t\t}\n\t\treturn err\n\t}\n\n\tif debugMode {\n\t\tfmt.Println(\"[Received]\", pdata)\n\t\tjsonData, err := json.MarshalIndent(pdata, \"\", \" \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", jsonData)\n\t}\n\n\tdata := &packetInfo{\n\t\tmessage: pdata,\n\t\tconn: conn,\n\t\ttracker: t,\n\t}\n\n\tc <- data\n\n\treturn nil\n}", "func (stmt *Statement) SendLongData(pnum int, data interface{}, pkt_size int) (\n err os.Error) {\n\n defer stmt.db.unlock()\n defer catchOsError(&err)\n stmt.db.lock()\n\n if stmt.db.conn == nil {\n return NOT_CONN_ERROR\n }\n if stmt.db.unreaded_rows {\n return UNREADED_ROWS_ERROR\n }\n if pnum < 0 || pnum >= stmt.ParamCount {\n return WRONG_PARAM_NUM_ERROR\n }\n if pkt_size -= 6; pkt_size < 0 {\n return SMALL_PKT_SIZE_ERROR\n }\n\n switch dd := data.(type) {\n case io.Reader:\n buf := make([]byte, pkt_size)\n for {\n nn, ee := io.ReadFull(dd, buf)\n if ee == os.EOF {\n return\n }\n if nn != 0 {\n stmt.db.sendCmd(\n _COM_STMT_SEND_LONG_DATA,\n stmt.id, uint16(pnum), buf[0:nn],\n )\n }\n if ee == io.ErrUnexpectedEOF {\n return\n } else if ee != nil {\n return ee\n }\n }\n\n case []byte:\n for len(dd) > pkt_size {\n stmt.db.sendCmd(\n _COM_STMT_SEND_LONG_DATA,\n stmt.id, uint16(pnum), dd[0:pkt_size],\n )\n dd = dd[pkt_size:]\n }\n stmt.db.sendCmd(_COM_STMT_SEND_LONG_DATA, stmt.id, uint16(pnum), dd)\n return\n\n case string:\n for len(dd) > pkt_size {\n stmt.db.sendCmd(\n _COM_STMT_SEND_LONG_DATA,\n stmt.id, uint16(pnum), dd[0:pkt_size],\n )\n dd = dd[pkt_size:]\n }\n stmt.db.sendCmd(_COM_STMT_SEND_LONG_DATA, stmt.id, uint16(pnum), dd)\n return\n }\n return UNK_DATA_TYPE_ERROR\n}", "func listenPacket(ifi *net.Interface, proto Protocol) (*packetConn, error) {\n\treturn nil, ErrNotImplemented\n}", "func (cc *CryptConn) SendPacket(data []byte) error {\n\tkeyRotDelta := byte(3)\n\n\tif keyRotDelta != 0 {\n\t\tcc.sendKeyRot = (uint32(keyRotDelta) * (cc.sendKeyRot + 1))\n\t}\n\n\t// Encrypt the data\n\tencData, combinedCheck, check0, check1, check2 := crypto.Encrypt(data, cc.sendKeyRot, nil)\n\n\theader := &CryptPacketHeader{}\n\theader.Pf0 = byte(((uint(len(encData)) >> 12) & 0xF3) | 3)\n\theader.KeyRotDelta = keyRotDelta\n\theader.PacketNum = uint16(cc.sentPackets)\n\theader.DataSize = uint16(len(encData))\n\theader.PrevPacketCombinedCheck = cc.prevSendPacketCombinedCheck\n\theader.Check0 = check0\n\theader.Check1 = check1\n\theader.Check2 = check2\n\n\theaderBytes, err := header.Encode()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcc.conn.Write(headerBytes)\n\tcc.conn.Write(encData)\n\n\tcc.sentPackets++\n\tcc.prevSendPacketCombinedCheck = combinedCheck\n\n\treturn nil\n}", "func (this *FtpsClient) ReadFtpDataChannel(_ExitAfterFirstRead_B bool, _DataArray_U8 []uint8) (rWaitDuration_S64 time.Duration, rIoDuration_S64 time.Duration, rNbRead_i int, rRts error) {\n\tvar NbRead_i int\n\tvar StartWaitTime_X, StartIoTime_X time.Time\n\tvar FirstIo_B bool\n\n\tStartWaitTime_X = time.Now()\n\tNbMaxToRead_i := len(_DataArray_U8)\n\trNbRead_i = 0\n\trRts = this.dataConnection_I.SetDeadline(time.Now().Add(time.Duration(this.FtpsParam_X.DataTimeout_S64) * time.Millisecond))\n\t//\tfmt.Printf(\"now %v to %v\\n\", time.Now(), time.Now().Add(this.FtpsParam_X.DataTimeout_S64))\n\n\tif rRts == nil {\n\t\tFirstIo_B = true\n\t\tfor {\n\t\t\tNbRead_i, rRts = this.dataConnection_I.Read(_DataArray_U8[rNbRead_i:])\n\t\t\tif rRts == nil {\n\t\t\t\tif FirstIo_B {\n\t\t\t\t\tStartIoTime_X = time.Now()\n\t\t\t\t\trWaitDuration_S64 = StartIoTime_X.Sub(StartWaitTime_X)\n\t\t\t\t\tFirstIo_B = false\n\t\t\t\t\tif _ExitAfterFirstRead_B {\n\t\t\t\t\t\tNbMaxToRead_i = 0\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\trNbRead_i = rNbRead_i + NbRead_i\n\t\t\t\tif rNbRead_i >= NbMaxToRead_i {\n\t\t\t\t\t//\t\t\tfmt.Printf(\"FINAL GOT %d/%d -> cont\\n\", rNbRead_i, NbMaxToRead_i)\n\t\t\t\t\trIoDuration_S64 = time.Now().Sub(StartIoTime_X)\n\t\t\t\t\tbreak\n\t\t\t\t} else {\n\t\t\t\t\t//\t\t\t\t\tfmt.Printf(\">>Partial got %d/%d -> cont\\n\", rNbRead_i, NbMaxToRead_i)\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tif rRts == io.EOF {\n\t\t\t\t\t//\t\t\t\t\ttime.Sleep(time.Millisecond * 100)\n\t\t\t\t\t//\t\t\t\t\tfmt.Printf(\"EOF->cont\\n\")\n\t\t\t\t} else {\n\t\t\t\t\t//\t\t\t\tfmt.Printf(\"%v %d/%d err1 %s\\n\", time.Now(), rNbRead_i, NbMaxToRead_i, rRts.Error())\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\t//\t\tfmt.Printf(\"err2 %s\\n\", rRts.Error())\n\t}\n\treturn\n}", "func (connectionHandler *ConnectionHandler) sendPacket(packet *GossipPacket, address *net.UDPAddr) {\n\t// encode message\n\tpacketToSend, err := protobuf.Encode(packet)\n\thelpers.ErrorCheck(err, false)\n\n\t// send message\n\t_, err = connectionHandler.gossiperData.Connection.WriteToUDP(packetToSend, address)\n\thelpers.ErrorCheck(err, false)\n}", "func (c *Client) sendPacket(t packetType, p []byte) (header, []byte, error) {\n\t// Generate the binary packet.\n\tpacket, err := packetise(t, p)\n\tif err != nil {\n\t\treturn header{}, nil, err\n\t}\n\n\t// Send the packet over the wire.\n\t_, err = c.connection.Write(packet)\n\tif err != nil {\n\t\treturn header{}, nil, err\n\t}\n\t// Receive and decode the response.\n\thead, payload, err := depacketise(c.connection)\n\tif err != nil {\n\t\treturn header{}, nil, err\n\t}\n\n\treturn head, payload, nil\n}", "func readPacket(reader io.Reader) (*Packet, int, error) {\n\tidentifier, length, read, err := readHeader(reader)\n\tif err != nil {\n\t\treturn nil, read, err\n\t}\n\n\tp := &Packet{\n\t\tIdentifier: identifier,\n\t}\n\n\tp.Data = new(bytes.Buffer)\n\tp.Children = make([]*Packet, 0, 2)\n\tp.Value = nil\n\n\tif p.TagType == TypeConstructed {\n\t\t// TODO: if universal, ensure tag type is allowed to be constructed\n\n\t\t// Track how much content we've read\n\t\tcontentRead := 0\n\t\tfor {\n\t\t\tif length != LengthIndefinite {\n\t\t\t\t// End if we've read what we've been told to\n\t\t\t\tif contentRead == length {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\t// Detect if a packet boundary didn't fall on the expected length\n\t\t\t\tif contentRead > length {\n\t\t\t\t\treturn nil, read, fmt.Errorf(\"expected to read %d bytes, read %d\", length, contentRead)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Read the next packet\n\t\t\tchild, r, err := readPacket(reader)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, read, err\n\t\t\t}\n\t\t\tcontentRead += r\n\t\t\tread += r\n\n\t\t\t// Test is this is the EOC marker for our packet\n\t\t\tif isEOCPacket(child) {\n\t\t\t\tif length == LengthIndefinite {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\treturn nil, read, errors.New(\"eoc child not allowed with definite length\")\n\t\t\t}\n\n\t\t\t// Append and continue\n\t\t\tp.AppendChild(child)\n\t\t}\n\t\treturn p, read, nil\n\t}\n\n\tif length == LengthIndefinite {\n\t\treturn nil, read, errors.New(\"indefinite length used with primitive type\")\n\t}\n\n\t// Read definite-length content\n\tif MaxPacketLengthBytes > 0 && int64(length) > MaxPacketLengthBytes {\n\t\treturn nil, read, fmt.Errorf(\"length %d greater than maximum %d\", length, MaxPacketLengthBytes)\n\t}\n\tcontent := make([]byte, length)\n\tif length > 0 {\n\t\t_, err := io.ReadFull(reader, content)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn nil, read, io.ErrUnexpectedEOF\n\t\t\t}\n\t\t\treturn nil, read, err\n\t\t}\n\t\tread += length\n\t}\n\n\tif p.ClassType == ClassUniversal {\n\t\tp.Data.Write(content)\n\t\tp.ByteValue = content\n\n\t\tswitch p.Tag {\n\t\tcase TagEOC:\n\t\tcase TagBoolean:\n\t\t\tval, _ := ParseInt64(content)\n\n\t\t\tp.Value = val != 0\n\t\tcase TagInteger:\n\t\t\tp.Value, _ = ParseInt64(content)\n\t\tcase TagBitString:\n\t\tcase TagOctetString:\n\t\t\t// the actual string encoding is not known here\n\t\t\t// (e.g. for LDAP content is already an UTF8-encoded\n\t\t\t// string). Return the data without further processing\n\t\t\tp.Value = DecodeString(content)\n\t\tcase TagNULL:\n\t\tcase TagObjectIdentifier:\n\t\tcase TagObjectDescriptor:\n\t\tcase TagExternal:\n\t\tcase TagRealFloat:\n\t\t\tp.Value, err = ParseReal(content)\n\t\tcase TagEnumerated:\n\t\t\tp.Value, _ = ParseInt64(content)\n\t\tcase TagEmbeddedPDV:\n\t\tcase TagUTF8String:\n\t\t\tval := DecodeString(content)\n\t\t\tif !utf8.Valid([]byte(val)) {\n\t\t\t\terr = errors.New(\"invalid UTF-8 string\")\n\t\t\t} else {\n\t\t\t\tp.Value = val\n\t\t\t}\n\t\tcase TagRelativeOID:\n\t\tcase TagSequence:\n\t\tcase TagSet:\n\t\tcase TagNumericString:\n\t\tcase TagPrintableString:\n\t\t\tval := DecodeString(content)\n\t\t\tif err = isPrintableString(val); err == nil {\n\t\t\t\tp.Value = val\n\t\t\t}\n\t\tcase TagT61String:\n\t\tcase TagVideotexString:\n\t\tcase TagIA5String:\n\t\t\tval := DecodeString(content)\n\t\t\tfor i, c := range val {\n\t\t\t\tif c >= 0x7F {\n\t\t\t\t\terr = fmt.Errorf(\"invalid character for IA5String at pos %d: %c\", i, c)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\tp.Value = val\n\t\t\t}\n\t\tcase TagUTCTime:\n\t\tcase TagGeneralizedTime:\n\t\t\tp.Value, err = ParseGeneralizedTime(content)\n\t\tcase TagGraphicString:\n\t\tcase TagVisibleString:\n\t\tcase TagGeneralString:\n\t\tcase TagUniversalString:\n\t\tcase TagCharacterString:\n\t\tcase TagBMPString:\n\t\t}\n\t} else {\n\t\tp.Data.Write(content)\n\t}\n\n\treturn p, read, err\n}", "func readPacket(c *mqttConn) {\n\tfor pr := range c.readch {\n\t\tif pr.Err != nil {\n\t\t\tc.closeConn(pr.Err.Error(), true)\n\t\t\tbreak\n\t\t}\n\t\tif pr.P == nil {\n\t\t\tc.closeConn(\"connect fail\", true)\n\t\t\tbreak\n\t\t}\n\t\tgo handlePacket(pr.P, c)\n\t}\n\tlog.Printf(\"handler no leak\")\n}", "func (s *Slave) nextFinalData() (p *Packet, err error) {\n\tpp, err := s.receive()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer pp.Release()\n\n\tp = &Packet{}\n\tif err := p.UnmarshalBinary(pp.body); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !s.VClock.Follow(p.InstanceID, p.LSN) {\n\t\treturn nil, ErrVectorClock\n\t}\n\n\tswitch p.Cmd {\n\tcase InsertCommand:\n\t\tq := p.Request.(*Insert)\n\t\tswitch q.Space {\n\t\tcase SpaceSchema:\n\t\t\t// assert space _schema always has str index on field one\n\t\t\t// and in \"cluster\" tuple uuid is string too\n\t\t\t// {\"cluster\", \"ea74fc91-54fe-4f64-adae-ad2bc3eb4194\"}\n\t\t\tkey := q.Tuple[0].(string)\n\t\t\tif key == SchemaKeyClusterUUID {\n\t\t\t\ts.ReplicaSet.UUID = q.Tuple[1].(string)\n\t\t\t}\n\t\tcase SpaceCluster:\n\t\t\t// fill in Replica Set from _cluster space; format:\n\t\t\t// {0x1, \"89b1203b-acda-4ff1-ae76-8069145344b8\"}\n\t\t\t// {0x2, \"7c025e42-2394-11e7-aacf-0242ac110002\"}\n\n\t\t\t// in reality _cluster key field is decoded to uint64\n\t\t\t// but we know exactly that it can be cast to uint32 without losing data\n\t\t\tinstanceIDu64, _ := typeconv.IntfToUint64(q.Tuple[0])\n\t\t\tinstanceID, _ := typeconv.IntfToUint32(instanceIDu64)\n\t\t\t// uuid\n\t\t\ts.ReplicaSet.SetInstance(instanceID, q.Tuple[1].(string))\n\t\t}\n\tcase OKCommand:\n\t\t// Current vclock. This is not used now, ignore.\n\t\treturn nil, io.EOF\n\t}\n\n\treturn p, nil\n}", "func handlePacket(miniServer *MiniServer, packetLength int, player *player.Player, in *buffer.MiniBuffer, out *buffer.MiniBuffer) {\n\n\tif packetLength == 1 { return }\n\n\tid := in.ReadVarInt()\n\n\tprintln(\"Length:\", packetLength, \"ID:\", \"0x\" + strconv.FormatInt(int64(id), 16))\n\n\tpacket := PacketHandlers[316][byte(id)]\n\n\tif packet == nil { println(\"Packet not found\", id); return }\n\n\tpacket.Handle(miniServer, &InboundPacket { Buffer: in, Player: player, PacketLength: packetLength }, out)\n}", "func (this *GB28181Receiver) receiveFrames(data []byte, n int) error {\n\tif n <= 4 {\n\t\tprintln(\"receiveFrames datalen <= 4\")\n\t\treturn errors.New(\"receiveFrames datalen <= 4\")\n\t}\n\n\tif data[0] == 0x00 && data[1] == 0x00 && data[2] == 0x00 && data[3] == 0x01 {\n\t\tif this.init == false {\n\t\t\tprintln(\"receiveFrames nalu got\")\n\t\t\tthis.init = true\n\t\t\tthis.buffer.Write(data[:n])\n\t\t} else {\n\t\t\tthis.index++\n\t\t\tiFrame := false\n\t\t\tif len(this.buffer.Bytes()) >= 4 && (this.buffer.Bytes()[4]&0x1F == 7 || this.buffer.Bytes()[4]&0x1F == 8 || this.buffer.Bytes()[4]&0x1F == 5) {\n\t\t\t\tiFrame = true\n\t\t\t}\n\t\t\tif this.index%100 == 0 {\n\t\t\t\tf, _ := strconv.ParseFloat(fmt.Sprintf(\"%0.2f\", 1.0/(float64(time.Now().Sub(this.t0).Nanoseconds())/1000000000.00)), 64)\n\t\t\t\tif f*100 > 0 {\n\t\t\t\t\tthis.fps = uint32(f * 100)\n\t\t\t\t}\n\t\t\t\tthis.t0 = time.Now()\n\t\t\t}\n\n\t\t\tbuf := make([]byte, this.buffer.Len())\n\t\t\tcopy(buf, this.buffer.Bytes())\n\t\t\tthis.ts += uint64(90000 / this.fps)\n\n\t\t\tframe := &core.H264ESFrame{\n\t\t\t\tData: buf,\n\t\t\t\tTimestamp: uint32(this.ts),\n\t\t\t\tIFrame: iFrame,\n\t\t\t\tIndex: this.index,\n\t\t\t}\n\t\t\tthis.AbsFPS = this.fps\n\t\t\tif iFrame == true {\n\t\t\t\tsp := h264.GetLiveSPS(this.buffer.Bytes())\n\t\t\t\tif sp.Width != 0 {\n\t\t\t\t\tthis.AbsWidth = sp.Width\n\t\t\t\t}\n\t\t\t\tif sp.Height != 0 {\n\t\t\t\t\tthis.AbsHeight = sp.Height\n\t\t\t\t}\n\t\t\t\tif len(sp.SPS) != 0 {\n\t\t\t\t\tthis.AbsSPS = sp.SPS\n\t\t\t\t}\n\t\t\t\tif len(sp.PPS) != 0 {\n\t\t\t\t\tthis.AbsPPS = sp.PPS\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tselect {\n\t\t\tcase _, ok := <-this.AbsStoped:\n\t\t\t\tif ok == false {\n\t\t\t\t\treturn errors.New(\"Receiver has been stopped\")\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tthis.AbsIndex++\n\t\t\t\tthis.AbsFrames <- frame\n\t\t\t\tthis.buffer.Reset()\n\t\t\t\tthis.init = true\n\t\t\t\tthis.buffer.Write(data[:n])\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif !this.init {\n\t\t\treturn errors.New(\"rawdata hasn't been inited\")\n\t\t}\n\t\tthis.buffer.Write(data[:n])\n\t}\n\n\treturn nil\n}", "func (p *dataPacket) Write(w io.Writer) (int, error) {\n\tif _, err := w.Write(p.nonce[:]); err != nil {\n\t\treturn 0, err\n\t}\n\tif err := binary.Write(w, binary.LittleEndian, int64(len(p.data))); err != nil {\n\t\treturn 0, err\n\t}\n\treturn w.Write(p.data)\n}", "func (buf buffer) read() {\n\tfor {\n\t\t// try to read the data\n\t\twbuf := make([]byte, 8192)\n\t\tn, err := buf.conn.Read(wbuf)\n\n\t\tif err != nil {\n\t\t\t// send an error if it's encountered\n\t\t\tbuf.errCh <- err\n\t\t\treturn\n\t\t}\n\n\t\tbuf.len += uint32(n)\n\t\tbuf.data = append(buf.data, wbuf[:n]...)\n\n\t\tfor buf.len >= pkgHeaderSize {\n\t\t\tif buf.pkg == nil {\n\t\t\t\tbuf.pkg, err = newPkg(buf.data)\n\t\t\t\tif err != nil {\n\t\t\t\t\tbuf.errCh <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttotal := buf.pkg.size + pkgHeaderSize\n\n\t\t\tif buf.len < total {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tbuf.pkg.setData(&buf.data, total)\n\n\t\t\t// The reserved ThingsDB events range is between 0..15\n\t\t\tif buf.pkg.tp <= 15 {\n\t\t\t\tbuf.evCh <- buf.pkg\n\t\t\t} else {\n\t\t\t\tbuf.pkgCh <- buf.pkg\n\t\t\t}\n\n\t\t\tbuf.data = buf.data[total:]\n\t\t\tbuf.len -= total\n\t\t\tbuf.pkg = nil\n\t\t}\n\t}\n}", "func packetise(t packetType, p []byte) ([]byte, error) {\n\t// Generate a random request ID.\n\tpad := [2]byte{}\n\tlength := int32(len(p) + 10)\n\tvar buf bytes.Buffer\n\tbinary.Write(&buf, binary.LittleEndian, length)\n\tbinary.Write(&buf, binary.LittleEndian, int32(0))\n\tbinary.Write(&buf, binary.LittleEndian, t)\n\tbinary.Write(&buf, binary.LittleEndian, p)\n\tbinary.Write(&buf, binary.LittleEndian, pad)\n\t// Notchian server doesn't like big packets :(\n\tif buf.Len() >= 1460 {\n\t\treturn nil, errors.New(\"Packet too big when packetising.\")\n\t}\n\t// Return the bytes.\n\treturn buf.Bytes(), nil\n}", "func (c *NetClient) processPacket(packet []byte) ([]byte, error) {\n\n\t// c.log.Debugf(\" Processing packet\")\n\t// c.log.Tracef(\"Removing first 37 bytes of the message\")\n\tif len(packet) > 38 {\n\t\treturn packet[38:], nil\n\t}\n\treturn packet, nil\n}", "func (r *Radio) Send(data []byte) {\n}", "func (k Keeper) SendPacket(ctx sdk.Context, packet ibcexported.PacketI) error {\n\tportID := packet.GetSourcePort()\n\tchannelID := packet.GetSourceChannel()\n\tcapName := host.ChannelCapabilityPath(portID, channelID)\n\tchanCap, ok := k.GetCapability(ctx, capName)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(channeltypes.ErrChannelCapabilityNotFound, \"could not retrieve channel capability at: %s\", capName)\n\t}\n\treturn k.channelKeeper.SendPacket(ctx, chanCap, packet)\n}", "func PermitChanDataOp(chantype, flag, name string) {\n\tHookCheckChanData(chantype, name, func(_ string, u *core.User, ch *core.Channel, _, _ string) (int, os.Error) {\n\t\tif HasOpFlag(u, ch, flag) {\n\t\t\treturn 10000, nil\n\t\t}\n\t\treturn 0, nil\n\t})\n}", "func rconPacket(password, cmd string) []byte {\n\treturn []byte(header + \"rcon \\\"\" + password + \"\\\" \" + cmd)\n}", "func (c *Conn) begin(packet []byte) (data []byte) {\n\tdata = packet\n\tif len(c.in) > 0 {\n\t\tc.in = append(c.in, data...)\n\t\tdata = c.in\n\t}\n\treturn data\n}", "func (me *FgServer) HandlePacket(xdr_bytes []byte, length int, sender_address *net.UDPAddr){\n\t\n\t// Check if sender is blacklisted\n\tif Blacklist.IsBlackListed(sender_address){\n\t\tBlacklist.Rejected++\n\t\t// TODO maybe add to a log\n\t\t//fmt.Println(\"Blacklisted\")\n\t\treturn\n\t}\n\n\t// Decode header message, ignore if error\n\theader, remainingBytes, err := message.DecodeHeader(xdr_bytes)\n\tif err != nil{\n\t\tfmt.Println(\"XDR header error\", err)\n\t\tme.PacketsInvalid++\n\t\treturn\n\t}\n\t//fmt.Println(\"remain=\", len(remainingBytes), sender_address.String(), header.Callsign())\n\tme.PacketsReceived++\n\n\n\t// Send packet out to crossfeeds via channel\n\tCrossfeed.Chan <- xdr_bytes\n\n\n\t//me.SendToCrossfeed(xdr_bytes, sender_address)\n\t//Crossfeeds.Chan <- xdr_bytes\n\t//------------------------------------------------------\n\t// First of all, send packet to all crossfeed servers.\n\t//SendToCrossfeed (Msg, Bytes, SenderAddress); ?? SHould then be send pre vaildation ?\n\t//me.SendToCrossfeed(Msg, Bytes, SenderAddress)\n\n\n\n\tif header.Magic == message.RELAY_MAGIC { // not a local client\n\t\tif !Relays.IsKnown(sender_address) {\n\t\t\tme.UnknownRelay++ \n\t\t\treturn\n\t\t}else{\n\t\t\tme.RelayMagic++ // bump relay magic packet\n\t\t}\n\t}\n\n\tcallsign := header.Callsign()\n\n\tvar player *Player\n\tvar position message.PositionMsg\n\tvar exists bool\n\tvar remBytes []byte\n\tvar err_pos error\n\n\t// Check if entry exists\n\tplayer, exists = me.Players[callsign]\n\n\tif exists == false && header.Type != message.TYPE_POS {\n\t\t// ignore until a position message\n\t\treturn\n\t}\n\tif exists == true && player.Address.String() != sender_address.String() {\n\t\t// sender has same callsign but different address, so ignore\n\t\treturn\n\t}\n\n\n\t// Decode position packer\n\tif header.Type == message.TYPE_POS\t{\n\n\t\tposition, remBytes, err_pos = message.DecodePosition(remainingBytes)\n\t\tif err != nil{\n\t\t\tfmt.Println(\"XDR Decode Position Error\", err_pos)\n\t\t\treturn\n\t\t}else if 1 == 2 {\n\t\t\tfmt.Println(\"remain2=\", len(remBytes))\n\t\t}\n\n\t\tif position.Position[X] == 0.0 || position.Position[Y] == 0.0 || position.Position[Z] == 0.0 {\n\t\t\treturn // ignore while position is not settled\n\t\t}\n\t\tme.PositionData++\n\t} else {\n\t\tme.NotPosData++\n\t}\n\n\t// Create new player\n\tif exists == false {\n\t\tplayer = me.AddPlayer(&header, &position, sender_address)\n\t}\n\n\tfmt.Println( callsign, position.Position[X], position.Position[Y])\n\tplayer.UpdatePosition(&position)\n\tplayer.Timestamp = Now()\n\tplayer.PktsReceivedFrom++\n\n\t//////////////////////////////////////////\n\t//\n\t// send the packet to all clients.\n\t// since we are walking through the list,\n\t// we look for the sending client, too. if it\n\t// is not already there, add it to the list\n\t//\n\t//////////////////////////////////////////////////\n\n\tisObserver := strings.ToLower(callsign)[0:3] == \"obs\"\n\tfor _, lp := range me.Players {\n\t\t\n\t\t//= ignore clients with errors\n\t\tif lp.HasErrors {\n\t\t\tcontinue // Umm is this locked out forever ?\n\t\t}\n\t\t\n\t\t\n\t\t// Sender == CurrentPlayer?\n\t\t/* FIXME: if Sender is a Relay,\n\t\t\t\t\tCurrentPlayer->Address will be\n\t\t\t\taddress of Relay and not the client's!\n\t\t\t\tso use a clientID instead\n\t\t*/\n\t\t//if loopCallsign == callsign { // alterative == CurrentPlayer.Callsign == xCallsign\n\t\t\t//if header.Type == message.TYPE_POS\t{\n\t\t\t\t// Update this players position\n\t\t\t\t//player.LastPos.Set( position.Position[X], position.Position[Y], position.Position[Z])\n\t\t\t\t//player.LastOrientation.Set( float64(position.Orientation[X]), float64(position.Orientation[Y]), float64(position.Orientation[Z]))\n\t\t\t//\tloopPlayer.LastPos.Set( position.Position[X], position.Position[Y], position.Position[Z])\n\t\t\t//\tloopPlayer.LastOrientation.Set( float64(position.Orientation[X]), float64(position.Orientation[Y]), float64(position.Orientation[Z]))\n\t\t\t//}//else{\n\t\t\t\t//SenderPosition = loopPlayer.LastPos\n\t\t\t\t//SenderOrientation = loopPlayer.LastOrientation\n\t\t\t//}\n\t\t\t//SendingPlayer = CurrentPlayer\n\t\t\t//loopPlayer.Timestamp = timestamp\n\t\t\t//loopPlayer.PktsReceivedFrom++\n\t\t\t//CurrentPlayer++;\n\t\t\t//continue; // don't send packet back to sender\n\t\t//}\n\t\t/// do not send packets to clients if the\n\t\t// origin is an observer, but do send\n\t\t// chat messages anyway\n\t\t// FIXME: MAGIC = SFGF!\n\t\tif isObserver && header.Type != message.TYPE_CHAT {\n\t\t\tcontinue\n\t\t}\n\t\t\n\t\t// Do not send packet to clients which are out of reach.\n\t\tif isObserver == false && int(Distance(player.LastPos, lp.LastPos)) > me.PlayerIsOutOfReach {\n\t\t\t//if ((Distance (SenderPosition, CurrentPlayer->LastPos) > m_PlayerIsOutOfReach)\n\t\t\t//&& (CurrentPlayer->Callsign.compare (0, 3, \"obs\", 3) != 0))\n\t\t\t//{\n\t\t\t//CurrentPlayer++ \n\t\t\tcontinue\n\t\t}\n\t\t\n\t\t// only send packet to local clients\n\t\tif lp.IsLocal && lp != player {\n\t\t\t//SendChatMessages (CurrentPlayer);\n\t\t\t//m_DataSocket->sendto (Msg, Bytes, 0, &CurrentPlayer->Address);\n\t\t\t_, err := me.DataSocket.WriteToUDP(xdr_bytes, player.Address)\n\t\t\tif err != nil {\n\t\t\t\t// TODO ?\n\t\t\t}\n\t\t\tlp.PktsSentTo++\n\t\t\tme.PktsForwarded++\n\t\t}\n\t\t//CurrentPlayer++; \n\t\t//\n\t} \n\t/* \n\tif (SendingPlayer == m_PlayerList.end())\n\t{ // player not yet in our list\n\t\t// should not happen, but test just in case\n\t\tSG_LOG (SG_SYSTEMS, SG_ALERT, \"## BAD => \"\n\t\t<< MsgHdr->Callsign << \":\" << SenderAddress.getHost()\n\t\t<< \" : \" << SenderIsKnown (MsgHdr->Callsign, SenderAddress)\n\t\t);\n\t\treturn;\n\t}\n\tDeleteMessageQueue ();\n\t*/\n\t//SendingPlayer := NewFG_Player() // placleholder\n\t//me.SendToRelays (xdr_bytes, length, player)\n\tRelays.Chan <- RelayData{Bytes: xdr_bytes, Player: player}\n\t\n}", "func SwitchData(x, y gb.UINT8, src, dst []gb.UINT8) {}", "func ParseData(in []byte) (*UDPCom, error) {\n\tv := &UDPCom{}\n\n\top := bytes.NewBuffer(in)\n\ttmp := op.Next(1)\n\tv.Cmd = tmp[0]\n\ttmp = op.Next(2)\n\tll := utils.Bytes2Uint16(tmp)\n\ttmp = op.Next(int(ll))\n\tt := tmp[0]\n\tip1 := tmp[1 : len(tmp)-2]\n\tport := utils.Bytes2Uint16(tmp[len(tmp)-2:])\n\tvv := &socketcore.Socks5Addr{\n\t\tAddressType: t,\n\t\tPort: port,\n\t}\n\tif t == 1 || t == 4 {\n\t\tvv.IPvX = ip1\n\t} else if t == 3 {\n\t\tvv.Domain = string(ip1)\n\t}\n\tv.Dst = vv\n\ttmp = op.Next(2)\n\tll = utils.Bytes2Uint16(tmp)\n\ttmp = op.Next(int(ll))\n\tt = tmp[0]\n\tip1 = tmp[1 : len(tmp)-2]\n\tport = utils.Bytes2Uint16(tmp[len(tmp)-2:])\n\n\tvv = &socketcore.Socks5Addr{\n\t\tAddressType: t,\n\t\tPort: port,\n\t}\n\tif t == 1 || t == 4 {\n\t\tvv.IPvX = ip1\n\t} else if t == 3 {\n\t\tvv.Domain = string(ip1)\n\t}\n\tv.Src = vv\n\n\tv.Data = op.Next(op.Len())\n\n\treturn v, nil\n}", "func handleData(pc net.PacketConn, addr net.Addr, pd *PacketData, connectionSvc *ConnectionService) {\n\tconnectionSvc.writeData(addr.String(), pd.BlockNum, pd.Data)\n\tackPacket := &PacketAck{pd.BlockNum}\n\tsendResponse(pc, addr, ackPacket)\n}", "func ListenOnPort(conn *net.UDPConn, isIntroducer bool, node nd.Node, ATApointer *bool) ms.MsList {\n\tfmt.Println(\"ListenOnPort\")\n\tvar buf [5120]byte\n\tfmt.Println(\"start reading\")\n\tn, _, err := conn.ReadFromUDP(buf[0:])\n\tfmt.Println(\"done reading\")\n\tif err != nil {\n\t\tfmt.Println(\"err != nil\")\n\t\treturn ms.MsList{}\n\t}\n\tgossip := []byte(\"gossip\")\n\tata := []byte(\"ata\")\n\tif n == len(gossip) {\n\t\tfmt.Println(\"changing to gossip\")\n\t\t*ATApointer = false\n\t\treturn ms.MsList{}\n\t} else if n == len(ata) {\n\t\tfmt.Println(\"changing to ATA\")\n\t\t*ATApointer = true\n\t\treturn ms.MsList{}\n\t}\n\n\tfmt.Println(\"UDPmessage received\")\n\n\tfmt.Println(\"---------------testing msgPING---------------\")\n\tfmt.Println(buf[:n])\n\n\tvar message Packet\n\tmessage.makePacket()\n\tvar metadata MessagePacket\n\tmetadata.makeMessagePacket()\n\n\t/*switch dtype:=buf[0];dtype{\n\tcase 1:\n\t\tfmt.Println(\"memberList received, start decoding\")\n\t\tmessage = decodeJSON(buf[1:n])\n\t\tmessage.Print()\n\tcase 2:\n\t\tfmt.Println(\"metadata received\")\n\t\tmetadata = decodeJson(buf[1:n])\n\t\t//metadata.Print()\n\t}*/\n\n\t/*fmt.Println(\"decoding....\")\n\tmessage = decodeJSON(buf[1:n])\n\tfmt.Println(\"received message: \")\n\tmessage.Input.Print()\n\n\tif isIntroducer && message.IsInitialization { // server is introducer and message is an initialization message\n\t\tcurrMsList := node.MsList\n\t\tcurrMsList = currMsList.Add(message.Input.List[0], node.LocalTime)\n\t\tfmt.Println(\"CurrMsList: \")\n\t\tcurrMsList.Print()\n\t\tencodedMsg := encodeJSON(Packet{1, currMsList, false})\n\t\tconn.WriteToUDP([]byte(encodedMsg), addr)\n\t\treturn currMsList\n\t} else { // server is introducer but message is not an initialization message\n\t\t// message.Input.Print()\n\t\t// fmt.Println(\"not \")\n\t\treturn message.Input\n\t}*/\n\n\treturn ms.MsList{}\n}" ]
[ "0.5991822", "0.5745444", "0.54106605", "0.5401272", "0.5397141", "0.5369524", "0.5252285", "0.52128696", "0.5182066", "0.51805663", "0.5179238", "0.5121911", "0.5121377", "0.5107385", "0.5102355", "0.50901985", "0.5049237", "0.5045345", "0.5041959", "0.5040263", "0.50279516", "0.50239533", "0.50146633", "0.49812475", "0.49740672", "0.4972682", "0.49714637", "0.49545896", "0.49449027", "0.49213856", "0.49186105", "0.49117637", "0.49094552", "0.49030358", "0.489348", "0.4882321", "0.48646158", "0.4861784", "0.48596406", "0.48569387", "0.48485416", "0.48150626", "0.4812165", "0.48111832", "0.48085484", "0.48062113", "0.48039344", "0.4787069", "0.47796243", "0.4773257", "0.47694325", "0.47597718", "0.47594953", "0.47575718", "0.47556296", "0.47531256", "0.474338", "0.47424808", "0.47360042", "0.4731775", "0.47266123", "0.47243026", "0.4711015", "0.4703409", "0.46991736", "0.4698958", "0.46938804", "0.46837723", "0.46822244", "0.4671555", "0.46709752", "0.46660346", "0.46576348", "0.46521476", "0.46469238", "0.46392038", "0.46359816", "0.4631566", "0.4629127", "0.4625905", "0.4624913", "0.46211225", "0.4608167", "0.4606485", "0.46049732", "0.46011013", "0.45927095", "0.45889613", "0.45814225", "0.45813605", "0.45765644", "0.4562125", "0.45536926", "0.45534587", "0.45505923", "0.45492795", "0.45491", "0.45454842", "0.45412183", "0.45402232" ]
0.6243957
0
Add Adds a ticker to TickerSet
func (tickerSet TickerSet) Add(ticker string) { tickerSet[ticker] = true }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *Probe) AddTicker(ts ...Ticker) {\n\tp.tickers = append(p.tickers, ts...)\n}", "func (m *Manager) AddTicker(w http.ResponseWriter, r *http.Request) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tlogger.Debugf(\"Got an API request to add a ticker\")\n\n\t// read body\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlogger.Errorf(\"%s\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// unmarshal into struct\n\tvar stockReq TickerRequest\n\tif err := json.Unmarshal(body, &stockReq); err != nil {\n\t\tlogger.Errorf(\"Unmarshalling: %s\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// ensure token is set\n\tif stockReq.Token == \"\" {\n\t\tlogger.Error(\"Discord token required\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// ensure currency is set\n\tif stockReq.Currency == \"\" {\n\t\tstockReq.Currency = \"usd\"\n\t}\n\n\t// add stock or crypto ticker\n\tif stockReq.Crypto {\n\n\t\t// ensure name is set\n\t\tif stockReq.Name == \"\" {\n\t\t\tlogger.Error(\"Name required for crypto\")\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\t// ensure currency is set\n\t\tif stockReq.CurrencySymbol == \"\" {\n\t\t\tstockReq.CurrencySymbol = \"$\"\n\t\t}\n\n\t\t// check if already existing\n\t\tif _, ok := m.WatchingTicker[strings.ToUpper(stockReq.Name)]; ok {\n\t\t\tlogger.Error(\"Ticker already exists\")\n\t\t\tw.WriteHeader(http.StatusConflict)\n\t\t\treturn\n\t\t}\n\n\t\tcrypto := NewCrypto(stockReq.Ticker, stockReq.Token, stockReq.Name, stockReq.Nickname, stockReq.Color, stockReq.Decorator, stockReq.Frequency, stockReq.Currency, stockReq.Pair, stockReq.PairFlip, stockReq.Activity, stockReq.Decimals, stockReq.CurrencySymbol, m.Cache, m.Context)\n\t\tm.addTicker(stockReq.Name, crypto)\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\terr = json.NewEncoder(w).Encode(crypto)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"Unable to encode ticker: %s\", err)\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t}\n\t\treturn\n\t}\n\n\t// ensure ticker is set\n\tif stockReq.Ticker == \"\" {\n\t\tlogger.Error(\"Ticker required\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// ensure name is set\n\tif stockReq.Name == \"\" {\n\t\tstockReq.Name = stockReq.Ticker\n\t}\n\n\t// check if already existing\n\tif _, ok := m.WatchingTicker[strings.ToUpper(stockReq.Ticker)]; ok {\n\t\tlogger.Error(\"Ticker already exists\")\n\t\tw.WriteHeader(http.StatusConflict)\n\t\treturn\n\t}\n\n\tstock := NewStock(stockReq.Ticker, stockReq.Token, stockReq.Name, stockReq.Nickname, stockReq.Color, stockReq.Decorator, stockReq.Frequency, stockReq.Currency, stockReq.Activity, stockReq.Decimals, stockReq.TwelveDataKey)\n\tm.addTicker(stockReq.Ticker, stock)\n\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\terr = json.NewEncoder(w).Encode(stock)\n\tif err != nil {\n\t\tlogger.Errorf(\"Unable to encode ticker: %s\", err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t}\n}", "func (quotes *Quotes) AddTickers(tickers []string) (added int, err error) {\n\tif added, err = quotes.profile.AddTickers(tickers); err == nil && added > 0 {\n\t\tquotes.stocks = nil // Force fetch.\n\t}\n\treturn\n}", "func NewTickerSet() TickerSet {\n\treturn make(TickerSet)\n}", "func (s *set) Add(t *Term) {\n\ts.insert(t)\n}", "func (s *SeriesIDSet) Add(id uint64) {\n\ts.Lock()\n\tdefer s.Unlock()\n\ts.AddNoLock(id)\n}", "func (p *Bittrex) StartTicker(pair string) {\n}", "func (s *DataAPI) AddMarketSource(mkt MarketSource) error {\n\tmktName, err := dex.MarketName(mkt.Base(), mkt.Quote())\n\tif err != nil {\n\t\treturn err\n\t}\n\tepochDur := mkt.EpochDuration()\n\ts.epochDurations[mktName] = epochDur\n\tbinCaches := make(map[uint64]*candles.Cache, len(binSizes)+1)\n\ts.marketCaches[mktName] = binCaches\n\tcacheList := make([]*candles.Cache, 0, len(binSizes)+1)\n\tfor _, binSize := range append([]uint64{epochDur}, binSizes...) {\n\t\tcache := candles.NewCache(candles.CacheSize, binSize)\n\t\tcacheList = append(cacheList, cache)\n\t\tbinCaches[binSize] = cache\n\t\tif binSize == bin5min {\n\t\t\ts.cache5min = cache\n\t\t}\n\t}\n\tif s.cache5min == nil {\n\t\tpanic(\"no 5-minute cache\")\n\t}\n\terr = s.db.LoadEpochStats(mkt.Base(), mkt.Quote(), cacheList)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (db *DataBase) AddSticker(user *tg.User, sticker *tg.Sticker) (bool, error) {\n\tlog.Ln(\"Trying to add\", sticker.FileID, \"sticker from\", user.ID, \"user\")\n\tif sticker.SetName == \"\" {\n\t\tsticker.SetName = models.SetUploaded\n\t}\n\n\tvar exists bool\n\terr := db.Update(func(tx *buntdb.Tx) error {\n\t\tvar err error\n\t\t_, exists, err = tx.Set(\n\t\t\tfmt.Sprint(\"user:\", user.ID, \":set:\", sticker.SetName, \":sticker:\", sticker.FileID), // key\n\t\t\tsticker.Emoji, // value\n\t\t\tnil, // options\n\t\t)\n\t\tif err == buntdb.ErrIndexExists {\n\t\t\texists = true\n\t\t\treturn nil\n\t\t}\n\n\t\treturn err\n\t})\n\n\treturn exists, err\n}", "func (tp *TickerPool) Add(name string, task func(context.Context)) (exists bool) {\n\t_, exists = tp.workers.LoadOrStore(name, task)\n\tif !exists {\n\t\tatomic.AddInt64(&tp.workerTotal, 1)\n\n\t\tif atomic.LoadInt64(&tp.workerTotal) == 1 {\n\t\t\t// if this is the first worker in the pool, the queue isn't running to start it\n\t\t\tgo tp.queue()\n\t\t}\n\t}\n\treturn\n}", "func (ts *TagSet) Add(tag string) (ok bool) {\n\tif ts.Has(tag) {\n\t\treturn false\n\t}\n\t*ts = append(*ts, tag)\n\treturn true\n}", "func (q *Quotes) Add(by, text string) Quote {\n\tq.Lock()\n\tdefer q.Unlock()\n\te := Quote{ID: q.next, Added: time.Now().Format(\"2006-01-02\"), By: by, Text: text}\n\tq.quotes[strconv.Itoa(q.next)] = e\n\tq.next++\n\tq.dirty = true\n\treturn e\n}", "func (set *tMatchSet) add(matchInfo *tMatch) *tMatchSet {\n\tmatch := matchInfo.match\n\tif set.matchSet == nil {\n\t\tset.matchSet = &order.MatchSet{Taker: match.Taker}\n\t}\n\tif set.matchSet.Taker.User() != match.Taker.User() {\n\t\tfmt.Println(\"!!!tMatchSet taker mismatch!!!\")\n\t}\n\tms := set.matchSet\n\tms.Makers = append(ms.Makers, match.Maker)\n\tms.Amounts = append(ms.Amounts, matchInfo.qty)\n\tms.Rates = append(ms.Rates, matchInfo.rate)\n\tms.Total += matchInfo.qty\n\tset.matchInfos = append(set.matchInfos, matchInfo)\n\treturn set\n}", "func (h *RedisHelper) AddToSet(set string, item string) (err error) {\n\t_, err = h.Conn.Do(\"SADD\", set, item);\n\treturn\n}", "func (s *Set) Add(c cid.Cid) {\n\ts.lk.Lock()\n\tdefer s.lk.Unlock()\n\ts.set[c] = struct{}{}\n}", "func (m KeyedSamples) Add(index int64, t time.Duration) {\n\tkey := fmt.Sprintf(\"%010d\", index) // Easiest way to have samples show up in sorted order in the json.\n\tms, found := m[key]\n\tif !found {\n\t\tms = new(Multisample)\n\t\tm[key] = ms\n\t}\n\tms.Add(t)\n}", "func (m *EntityMutation) SetTicker(s string) {\n\tm.ticker = &s\n}", "func (tg *TradesGroup) add(e event) {\n\ttg.Lock()\n\tdefer tg.Unlock()\n\ttg.subs[e.ChanID] = e\n}", "func (cg *CandlesGroup) add(e event) {\n\tcg.Lock()\n\tdefer cg.Unlock()\n\tcg.subs[e.ChanID] = e\n}", "func NewTicker(d Duration) *Ticker {}", "func (t *TimeSeries) Add(timestamp time.Time, datum float64) {\n\tt.records = append(t.records, &Record{\n\t\ttimestamp: timestamp,\n\t\tDatum: datum,\n\t})\n}", "func (s *dispatcherSets) add(ctx context.Context, args *SetDefinition) error {\n\tds, err := sets.NewKubernetesSet(ctx, s.kc, args.id, args.namespace, args.name, args.port)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to create kubernetes-based dispatcher set\")\n\t}\n\n\tif s.sets == nil {\n\t\ts.sets = make(map[int]sets.DispatcherSet)\n\t}\n\n\t// Add this set to the list of sets\n\ts.sets[args.id] = ds\n\n\treturn nil\n}", "func (client *Client) AddStickerToSet(userId int64, name, pngSticker, emojis string) *VoidResponse {\n\tbody := JSON{\n\t\t\"user_id\": userId,\n\t\t\"name\": name,\n\t\t\"png_sticker\": pngSticker,\n\t\t\"emojis\": emojis,\n\t}\n\tendpoint := client.baseURL + fmt.Sprintf(EndpointAddStickerToSet, client.accessToken)\n\trequest := gorequest.New().Post(endpoint).Set(UserAgentHeader, UserAgent+\"/\"+Version).Send(body)\n\n\tif _, err := url.ParseRequestURI(pngSticker); err != nil {\n\t\trequest.Type(gorequest.TypeMultipart).SendFile(pngSticker, \"\", \"png_sticker\")\n\t}\n\n\treturn &VoidResponse{\n\t\tClient: client,\n\t\tRequest: request,\n\t}\n}", "func (c *Concentrator) Add(t Input) {\n\tc.mu.Lock()\n\tfor _, trace := range t.Traces {\n\t\tc.addNow(&trace, t.ContainerID)\n\t}\n\tc.mu.Unlock()\n}", "func (c *Client) Add(ts prompb.TimeSeries) error {\n\tmetric, err := storageutils.TimeSeriesToCloudWatch(ts, c.whitelist.Labels)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !storageutils.Contains(c.whitelist.Metrics, *metric.MetricName) {\n\t\tc.logger.Infof(\"Skipping because metric has not been whitelisted: %s\", *metric.MetricName)\n\t\treturn nil\n\t}\n\n\tif len(metric.Dimensions) == 0 {\n\t\tc.logger.Infof(\"Skipping because no dimensions were found: %s\", *metric.MetricName)\n\t\treturn nil\n\t}\n\n\tif len(metric.Values) == 0 {\n\t\tc.logger.Infof(\"Skipping because no values were found: %s\", *metric.MetricName)\n\t\treturn nil\n\t}\n\n\tc.data = append(c.data, metric)\n\n\tif len(c.data) >= c.batch {\n\t\treturn c.Flush()\n\t}\n\n\treturn nil\n}", "func (set *SetString) Add(string string) {\n\tset.lock.Lock()\n\tset.cache[string] = true\n\tset.lock.Unlock()\n}", "func (s *Set[T]) Add(elts ...T) {\n\ts.resize(2 * len(elts))\n\tfor _, elt := range elts {\n\t\t(*s)[elt] = struct{}{}\n\t}\n}", "func (mds *marketDepthStream) AddTrade(price, qty uint64, createdAt string) {\n\tvar l = mds.logger.WithFields(logrus.Fields{\n\t\t\"method\": \"MarketDepth.Trade\",\n\t\t\"param_price\": price,\n\t\t\"param_qty\": qty,\n\t})\n\n\tt := &trade{\n\t\tqty,\n\t\tprice,\n\t\tcreatedAt,\n\t}\n\n\tmds.latestTradesLock.Lock()\n\tif len(mds.latestTrades) >= 20 {\n\t\t// FIXME: Check if this is correct and won't throw any error\n\t\tmds.latestTrades = mds.latestTrades[len(mds.latestTrades)-20:]\n\t}\n\n\tmds.latestTrades = append(mds.latestTrades, t)\n\tmds.latestTradesDiff = append(mds.latestTradesDiff, t)\n\tmds.latestTradesLock.Unlock()\n\n\tl.Debugf(\"Added\")\n}", "func (e *Engine) AddSeries(name string, tags map[string]string) error {\n\tpoint, err := models.NewPoint(name, models.NewTags(tags), models.Fields{\"v\": 1.0}, time.Now())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn e.writePoints(point)\n}", "func (o *RelatedAssetSerializerWithPermission) SetTicker(v string) {\n\to.Ticker = v\n}", "func (s *Set) add(c cid.Cid) {\n\ts.set[c] = struct{}{}\n}", "func ticker(s string) func() error {\n\n\treturn func() error {\n\n\t\tTIME += 1\n\n\t\treturn nil\n\t}\n}", "func (h *fakeRatesHistory) add(to time.Time, rate int64) {\n\tfor h.nextIntervalStart.Before(to) {\n\t\tr := record{h.nextIntervalStart, rate}\n\t\th.addPerThread(0 /* threadID */, r)\n\t\th.nextIntervalStart = h.nextIntervalStart.Add(h.interval)\n\t}\n}", "func (r *CompanySalesQuotesCollectionRequest) Add(ctx context.Context, reqObj *SalesQuote) (resObj *SalesQuote, err error) {\n\terr = r.JSONRequest(ctx, \"POST\", \"\", reqObj, &resObj)\n\treturn\n}", "func (fs *FileSet) Add(s string) {\n\t//找一个空channel,传入string\n\tif len(fs.fileChannels[fs.top]) == bufferSize {\n\t\tfs.fileChannels = append(fs.fileChannels, make(chan string, bufferSize))\n\t\tfs.top++\n\t}\n\tfs.fileChannels[fs.top] <- s\n}", "func SubscribeTicker(exchange string, p currency.Pair, a asset.Item) (dispatch.Pipe, error) {\n\texchange = strings.ToLower(exchange)\n\tservice.RLock()\n\tdefer service.RUnlock()\n\n\ttick, ok := service.Tickers[exchange][p.Base.Item][p.Quote.Item][a]\n\tif !ok {\n\t\treturn dispatch.Pipe{}, fmt.Errorf(\"ticker item not found for %s %s %s\",\n\t\t\texchange,\n\t\t\tp,\n\t\t\ta)\n\t}\n\treturn service.mux.Subscribe(tick.Main)\n}", "func (s *TickerService) Get(pair string) (*Tick, error) {\n\tpair = strings.ToUpper(pair)\n\treq, err := s.client.newRequest(\"GET\", \"pubticker/\"+pair, nil)\n\n\tif err != nil {\n\t\treturn nil, &ErrorHandler{FuncWhere: \"Ticker Get\", FuncWhat:\"newRequest\", FuncError: err.Error()}\n\t}\n\n\tv := &Tick{}\n\t_, err = s.client.do(req, v)\n\n\tif err != nil {\n\t\treturn nil, &ErrorHandler{FuncWhere: \"Ticker Get\", FuncWhat:\"do\", FuncError: err.Error()}\n\t}\n\n\treturn v, nil\n}", "func (s *HashSet) Add(data interface{}) error {\n\terr := s.checkT(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, ok := s.set[data]\n\tif ok {\n\t\treturn errors.New(\"ele exist\")\n\t}\n\ts.set[data] = nil\n\ts.size++\n\treturn nil\n}", "func (r *Redis) AddSet(ctx context.Context, key string, members ...string) error {\n\tif len(members) == 0 {\n\t\treturn nil\n\t}\n\t// convert strings to interfaces\n\tvalues := make([]interface{}, 0, len(members))\n\tfor _, member := range members {\n\t\tvalues = append(values, member)\n\t}\n\t// push set\n\treturn r.client.SAdd(ctx, r.Key(key), values...).Err()\n}", "func (s *UpdaterSet) Add(u Updater) error {\n\tif _, ok := s.set[u.Name()]; ok {\n\t\treturn ErrExists{[]string{u.Name()}}\n\t}\n\n\ts.set[u.Name()] = u\n\treturn nil\n}", "func AddSeries(w http.ResponseWriter, r *http.Request) {\n\tdecoder := json.NewDecoder(r.Body)\n\tvar data models.Series\n\terr := decoder.Decode(&data)\n\n\tif err != nil {\n\t\thttpext.AbortAPI(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tseries, err := watchlist.AddSeries(data, r)\n\n\tif err != nil {\n\t\thttpext.AbortAPI(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\thttpext.SuccessDataAPI(w, \"'\"+series.Title+\"' added succesfully\", series)\n}", "func (s *Set) Add(value string) error {\n\toriginalValue := value\n\tif !s.host.rawUTF8 {\n\t\tEncode(&value)\n\t}\n\t// Check that the value is not already there before adding\n\thas, err := s.Has(originalValue)\n\tif !has || noResult(err) {\n\t\t_, err = s.host.db.Exec(fmt.Sprintf(\"INSERT INTO %s (%s) VALUES ($1)\", s.table, setCol), value)\n\t}\n\treturn err\n}", "func (s Set) Add(k string) {\n\tif s.Contains(k) {\n\t\treturn\n\t}\n\ts.add(k)\n}", "func (t *TopK) Add(data []byte) *TopK {\n\tt.cms.Add(data)\n\tt.n++\n\n\tfreq := t.cms.Count(data)\n\tif t.isTop(freq) {\n\t\tt.insert(data, freq)\n\t}\n\n\treturn t\n}", "func (self *bestFit) add(x epochDays, y Kilometres) {\n\tself.AddY(float64(y))\n\tself.calculateLine(x)\n}", "func (s FeatureSet) Add(tag FeatureTag, values ...FeatureTagValue) {\n\tif !s.Contains(tag) {\n\t\ts[tag] = values\n\t\treturn\n\t}\n\tfor t, values := range s {\n\t\tif t.Equals(tag) {\n\t\t\ts[t] = append(s[t], values...)\n\t\t}\n\t}\n}", "func (sem SEManager) Add(se SearchEngine) error {\n sem.Engines = append(sem.Engines, se)\n return nil\n}", "func (se *StrataEstimator) Add(element uint64) {\n\tj := estimatorHash(element)\n\tse.Stratum[j].Add(element)\n}", "func Add(exchange string, p currency.Pair, a asset.Item, price, volume float64) error {\n\tif exchange == \"\" ||\n\t\ta == asset.Empty ||\n\t\tprice == 0 ||\n\t\tvolume == 0 ||\n\t\tp.Base.IsEmpty() ||\n\t\tp.Quote.IsEmpty() {\n\t\treturn errors.New(\"cannot add or update, invalid params\")\n\t}\n\n\tif p.Base.Equal(currency.XBT) {\n\t\tnewPair, err := currency.NewPairFromStrings(currency.BTC.String(),\n\t\t\tp.Quote.String())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tAppend(exchange, newPair, a, price, volume)\n\t}\n\n\tif p.Quote.Equal(currency.USDT) {\n\t\tnewPair, err := currency.NewPairFromStrings(p.Base.String(), currency.USD.String())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tAppend(exchange, newPair, a, price, volume)\n\t}\n\n\tAppend(exchange, p, a, price, volume)\n\treturn nil\n}", "func (s *StrSet) Add(element string) {\n\ts.els[element] = true\n}", "func (_m *ExtendedTimeStock) FindTimeSeriesByTicker(w http.ResponseWriter, r *http.Request) {\n\t_m.Called(w, r)\n}", "func (s *Set) Add(key string) {\n\tif s.Get(key) == nil {\n\t\ts.Insert(&Element{\n\t\t\tKey: key,\n\t\t})\n\t}\n}", "func (tt *MultiTokenSale) Add() (err error) {\n\t// 1 2 3 4 5 6 7 8 9 10 11 12\n\tstatement := `insert into multi_sales (tokenid,lookup_id,operation,blocknumber,index,txhash,buyer,seller,price,hash,position,quantity,timestamp) \n\t\t\t\t\tvalues ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) returning id`\n\tctx, cancel := context.WithTimeout(context.Background(), timeout())\n\tdefer cancel()\n\t// 1 2 3 4 5 6 7 8 9 10 11 12 13\n\terr = db.QueryRowContext(ctx, statement, tt.TokenID, tt.LookupID, tt.Operation, tt.BlockNumber, tt.TxIndex, tt.TxHash, tt.Buyer, tt.Seller, tt.Price, tt.Hash, tt.Position, tt.Quantity, tt.Timestamp).Scan(&tt.ID)\n\treturn\n}", "func (s *Set) Add(val string) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.set[val] = struct{}{}\n}", "func (c *Consistent) Add(elt string) {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.add(elt)\n}", "func (s Set) Add(key string) {\n\ts[key] = true\n}", "func (th *FutureSlice) Add(f RaftFuture) {\n\tif th.f == nil {\n\t\tth.f = make([]RaftFuture, 0)\n\t}\n\tif len(th.f) > 1 {\n\t\tpanic(\"only support one future\")\n\t}\n\tth.f = append(th.f, f)\n\tth.t = time.Now().UnixNano() / 1e3\n}", "func (model *Trade) Add(epoch int64, nanos int, price enum.Price, size enum.Size,\n\texchange enum.Exchange, tapeid enum.Tape, conditions ...enum.TradeCondition,\n) {\n\tmodel.Epoch = append(model.Epoch, epoch)\n\tmodel.Nanos = append(model.Nanos, int32(nanos))\n\tmodel.Price = append(model.Price, price)\n\tmodel.Size = append(model.Size, size)\n\tmodel.Exchange = append(model.Exchange, exchange)\n\tmodel.TapeID = append(model.TapeID, tapeid)\n\n\tcond1 := enum.NoTradeCondition\n\tcond2 := enum.NoTradeCondition\n\tcond3 := enum.NoTradeCondition\n\tcond4 := enum.NoTradeCondition\n\n\tswitch len(conditions) {\n\t// nolint:gomnd // index of options.\n\tcase 4:\n\t\tcond4 = conditions[3]\n\t\tfallthrough\n\t// nolint:gomnd // index of options.\n\tcase 3:\n\t\tcond3 = conditions[2]\n\t\tfallthrough\n\n\tcase 2:\n\t\tcond2 = conditions[1]\n\t\tfallthrough\n\n\tcase 1:\n\t\tcond1 = conditions[0]\n\tcase 0:\n\t\tbreak\n\tdefault:\n\t\tlog.Error(\"invalid length of conditions: %v\", len(conditions))\n\t}\n\n\tmodel.Cond4 = append(model.Cond4, cond4)\n\tmodel.Cond3 = append(model.Cond3, cond3)\n\tmodel.Cond2 = append(model.Cond2, cond2)\n\tmodel.Cond1 = append(model.Cond1, cond1)\n}", "func Add(s Spot) {\n\tpersist(s, add)\n}", "func (s *Set) Add(val interface{}) {\n\ts.set[val] = true\n}", "func (sr *ScraperRegistry) Add(s *types.Scraper) {\n\t// Initialize the Prometheus metric pointer\n\ts.InitializeMetrics()\n\t// Append initialized scraper to the slice of all scrapers\n\tsr.Scrapers = append(sr.Scrapers, s)\n}", "func (tw *MultiTimingsWrapper) Add(names []string, elapsed time.Duration) {\n\tif tw.name == \"\" {\n\t\ttw.timings.Add(names, elapsed)\n\t\treturn\n\t}\n\tnewlabels := combineLabels(tw.name, names)\n\ttw.timings.Add(newlabels, elapsed)\n}", "func (c *Consistent) Add(elt string) {\n\tc.Mu.Lock()\n\tdefer c.Mu.Unlock()\n\tc.add(elt)\n}", "func (r *CompanyCurrenciesCollectionRequest) Add(ctx context.Context, reqObj *Currency) (resObj *Currency, err error) {\n\terr = r.JSONRequest(ctx, \"POST\", \"\", reqObj, &resObj)\n\treturn\n}", "func (s *BoltCache) Add(key []byte, value models.Company) error {\n\ts.Lock.Lock()\n\tdefer s.Lock.Unlock()\n\treturn nil\n}", "func (m *Manager) AddToken(w http.ResponseWriter, r *http.Request) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tlogger.Debugf(\"Got an API request to add a ticker\")\n\n\t// read body\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlogger.Errorf(\"Error: %v\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"Error reading body: %v\", err)\n\t\treturn\n\t}\n\n\t// unmarshal into struct\n\tvar tokenReq TokenRequest\n\tif err := json.Unmarshal(body, &tokenReq); err != nil {\n\t\tlogger.Errorf(\"Error unmarshalling: %v\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"Error unmarshalling: %v\", err)\n\t\treturn\n\t}\n\n\t// ensure token is set\n\tif tokenReq.Token == \"\" {\n\t\tlogger.Error(\"Discord token required\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprint(w, \"Error: token required\")\n\t\treturn\n\t}\n\n\t// ensure currency is set\n\tif tokenReq.Currency == \"\" {\n\t\ttokenReq.Currency = \"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174\"\n\t}\n\n\t// ensure freq is set\n\tif tokenReq.Frequency == 0 {\n\t\ttokenReq.Frequency = 60\n\t}\n\n\t// ensure name is set\n\tif tokenReq.Name == \"\" {\n\t\tlogger.Error(\"Name required for token\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprint(w, \"Error: Name required\")\n\t\treturn\n\t}\n\n\t// check if already existing\n\tif _, ok := m.Watching[strings.ToUpper(tokenReq.Contract)]; ok {\n\t\tlogger.Error(\"Error: ticker already exists\")\n\t\tw.WriteHeader(http.StatusConflict)\n\t\treturn\n\t}\n\n\ttoken := NewToken(tokenReq.Contract, tokenReq.Token, tokenReq.Name, tokenReq.Nickname, tokenReq.Frequency, tokenReq.Currency)\n\tm.addToken(token)\n\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\terr = json.NewEncoder(w).Encode(token)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t}\n\treturn\n}", "func (c *Comics) Add(xkcd *XKCD) {\n\tdefer logger.Trace(\"method Add()\")()\n\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tsize := c.Len()\n\tif c.sorted && size > 0 && c.comics[size-1].Number > xkcd.Number {\n\t\tc.sorted = false\n\t}\n\n\tc.comics = append(c.comics, *xkcd)\n}", "func (set StringSet) Add(s string) {\n\tset[s] = struct{}{}\n}", "func (s StringSet) Add(element string) {\n\ts.Set[element] = true\n}", "func (set StringSet) Add(e string) {\n\tset[e] = true\n}", "func (c *cache) Add(k string, x []byte, d time.Duration) error {\n\t_, found := c.Get(k)\n\tif found {\n\t\treturn fmt.Errorf(\"Item %s already exists\", k)\n\t}\n\tatomic.AddInt32(&c.Statistic.AddCount, 1)\n\tatomic.AddInt32(&c.Statistic.ItemsCount, 1)\n\tatomic.AddInt32(&c.Statistic.Size, int32(len(x)))\n\tc.set(k, x, d)\n\treturn nil\n}", "func (cs *Set) Add(c Code) {\n\tif cs.Matches(c) {\n\t\treturn\n\t}\n\t*cs = append(*cs, c)\n}", "func (s *Set) Add(val string) {\n\ts.set[val] = true\n}", "func (s Set) add(k string, a...Symbol) {\n\n\tfor _, v := range a {\n\t\tif b, _ := s.contains(k, v); !b {\n\t\t\ts[k] = append(s[k], v)\n\t\t}\n\t}\n}", "func (s Set) Add(st string) {\n\tif _, ok := s[st]; !ok {\n\t\ts[st] = true\n\t}\n}", "func (l List) Add(s string) {\n\tl.Indexes = append(l.Indexes, s)\n\tv, ok := l.Set[s]\n\tif !ok {\n\t\tl.Set[s] = 1\n\t} else {\n\t\tl.Set[s] = v + 1\n\t}\n}", "func (r *reflectorStore) Add(obj interface{}) error {\n\tmetaObj := obj.(metav1.Object)\n\tentity := r.parser.Parse(obj)\n\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tr.hasSynced = true\n\tr.seen[string(metaObj.GetUID())] = entity.GetID()\n\tr.wlmetaStore.Notify([]workloadmeta.CollectorEvent{\n\t\t{\n\t\t\tType: workloadmeta.EventTypeSet,\n\t\t\tSource: collectorID,\n\t\t\tEntity: entity,\n\t\t},\n\t})\n\n\treturn nil\n}", "func (c *idempotentTimeCache) Add(s string) {\n\tc.mut.Lock()\n\tdefer c.mut.Unlock()\n\tif !c.cache.Has(s) {\n\t\tc.cache.Add(s)\n\t}\n}", "func (m *Measurement) AddSeries(s *Series) bool {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\tif _, ok := m.seriesByID[s.id]; ok {\n\t\treturn false\n\t}\n\tm.seriesByID[s.id] = s\n\ttagset := string(marshalTags(s.Tags))\n\tm.series[tagset] = s\n\tm.seriesIDs = append(m.seriesIDs, s.id)\n\n\t// the series ID should always be higher than all others because it's a new\n\t// series. So don't do the sort if we don't have to.\n\tif len(m.seriesIDs) > 1 && m.seriesIDs[len(m.seriesIDs)-1] < m.seriesIDs[len(m.seriesIDs)-2] {\n\t\tsort.Sort(m.seriesIDs)\n\t}\n\n\t// add this series id to the tag index on the measurement\n\tfor k, v := range s.Tags {\n\t\tvalueMap := m.seriesByTagKeyValue[k]\n\t\tif valueMap == nil {\n\t\t\tvalueMap = make(map[string]seriesIDs)\n\t\t\tm.seriesByTagKeyValue[k] = valueMap\n\t\t}\n\t\tids := valueMap[v]\n\t\tids = append(ids, s.id)\n\n\t\t// most of the time the series ID will be higher than all others because it's a new\n\t\t// series. So don't do the sort if we don't have to.\n\t\tif len(ids) > 1 && ids[len(ids)-1] < ids[len(ids)-2] {\n\t\t\tsort.Sort(ids)\n\t\t}\n\t\tvalueMap[v] = ids\n\t}\n\n\treturn true\n}", "func (r *repo) Add(tl *Tracklist) {\n\tr.Tracklists = append(r.Tracklists, tl)\n}", "func (lwwset LWWSet) Addition(value string) (LWWSet, error) {\n\t// Return an error if the value passed is nil\n\tif value == \"\" {\n\t\treturn lwwset, errors.New(\"empty value provided\")\n\t}\n\n\t// Order the LWWSet according\n\t// to the timestamps\n\tlwwset = lwwset.orderList()\n\n\t// Set = Set U value\n\tif !isPresent(value, lwwset.Add) {\n\t\tlwwset.Add = append(lwwset.Add, LWWNode{Value: value, Timestamp: time.Now()})\n\t}\n\n\t// Return the new LWWSet\n\t// followed by nil error\n\treturn lwwset, nil\n}", "func Add(w http.ResponseWriter, r *http.Request) {\n\tvar err error\n\n\t// Obtain the value from URL params\n\tvalue := mux.Vars(r)[\"value\"]\n\n\t// Add the given value to our stored LWWSet\n\tLWWSet, err = LWWSet.Addition(value)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"error\": err}).Error(\"failed to add value\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// DEBUG log in the case of success indicating\n\t// the new LWWSet and the value added\n\tlog.WithFields(log.Fields{\n\t\t\"set\": LWWSet,\n\t\t\"value\": value,\n\t}).Debug(\"successful lwwset addition\")\n\n\t// Return HTTP 200 OK in the case of success\n\tw.WriteHeader(http.StatusOK)\n}", "func (m *Mock) Ticker(d time.Duration) *Ticker {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tch := make(chan time.Time, 1)\n\tt := &Ticker{\n\t\tC: ch,\n\t\tc: ch,\n\t\tmock: m,\n\t\td: d,\n\t\tnext: m.now.Add(d),\n\t}\n\tm.timers = append(m.timers, (*internalTicker)(t))\n\treturn t\n}", "func (self *QueuedSet) Add(item interface{}) (isNew bool) {\n\tself.lock.Lock()\n\tdefer self.lock.Unlock()\n\tcount := self.set[item]\n\tself.q.Enqueue(item)\n\tself.set[item] = count + 1\n\treturn count == 0\n}", "func (l *LinkedList) AddStock(s1 *stock) {\n\tif l.count == 0 {\n\t\tl.head = s1 //No elements in the list\n\t} else {\n\t\tcurrentPost := l.head\n\t\tfor currentPost.next != nil {\n\t\t\tcurrentPost = currentPost.next\n\t\t}\n\t\tcurrentPost.next = s1\n\t}\n\tl.count++\n\tfmt.Println(\"Added successfully\")\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 (l *ChannelList) Add(key string, c *Channel) error {\n\t// add a new conn\n\tb := l.Bucket(key)\n\tb.Lock()\n\tif _, ok := b.data[key]; ok {\n\t\tb.Unlock()\n\t\tlog.Info(\"User: %s refresh conn bucket expire time\", key)\n\t\treturn nil\n\t} else {\n\t\tb.data[key] = c\n\t\tb.Unlock()\n\t\tlog.Info(\"User: %s add a new conn\", key)\n\t\tChStat.IncrCreate()\n\t\treturn nil\n\t}\n}", "func (m *systrayMap) Add(tray *_Systray) refId {\n\tm.lock.Lock()\n\tid := uuid()\n\tm.m[id] = &systrayRef{tray, 1}\n\tm.lock.Unlock()\n\t// fmt.Printf(\"storage: Added ref to %v with id %d\\n\", tray, id)\n\treturn id\n}", "func (s StringSet) Add(str string) {\n\ts[str] = struct{}{}\n}", "func (s *Store) AddUndoSet(cs undo.ChangeSetter) {\n\ts.notifyChange()\n\tswitch {\n\tcase s.grpUndo:\n\t\ts.active = append(s.active, cs)\n\tcase s.isUndoing:\n\t\ts.redo = append(s.redo, cs)\n\tdefault:\n\t\ts.undo = append(s.undo, cs)\n\t}\n}", "func (ti *TemplateInfo) Add(ts ...dm.Quest_TemplateSpec) {\n\t*ti = append(*ti, ts...)\n\tsort.Sort(*ti)\n\t*ti = (*ti)[:set.Uniq(*ti)]\n}", "func (s Set) Add(value interface{}) {\n\thash, err := hashstructure.Hash(value, nil)\n\tif err != nil {\n\t\tlog.Errorf(\"type could not be hashed: %+v\", value)\n\t}\n\ts[hash] = value\n}", "func Add(t1 TermT, t2 TermT) TermT {\n\treturn TermT(C.yices_add(C.term_t(t1), C.term_t(t2)))\n}", "func (s *Series) Insert(t time.Time, value float64) {\n\tb := &Bucket{s.floor(t), value}\n\tidx := s.index(b.T)\n\ts.buckets[idx] = b\n}", "func (m *Market) Ticker(symbol string) (MarketResponse, error) {\n\ttickerURL := URL(\"/v1/ticker\")\n\tvar result MarketResponse\n\tvalues := url.Values{}\n\n\tif symbol != \"\" {\n\t\tvalues.Add(\"symbol\", symbol)\n\t}\n\n\tresp, err := method.Get(tickerURL, nil, values)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn bodyToMarketResponse(resp.Body, &result)\n}", "func (c *ClosablePool) Add(tier int, closable types.Closable) {\n\ttierArray := []types.Closable{}\n\tif t, ok := c.closables[tier]; ok {\n\t\ttierArray = t\n\t}\n\tc.closables[tier] = append(tierArray, closable)\n}", "func (s *Set) Add(els ...string) Set {\n\tif *s == nil {\n\t\t*s = make(Set)\n\t}\n\tfor _, el := range els {\n\t\t(*s)[el] = struct{}{}\n\t}\n\n\treturn *s\n}", "func (d *DeltaStrSet) Add(l []string) {\n\tfor _, s := range l {\n\t\td.items[s] = true\n\t}\n}", "func (c Redis) Add(key string, value interface{}, expire time.Duration) error {\n\tif !c.conn.SetNX(key, value, expire).Val() {\n\t\treturn cache.ErrNotStored\n\t}\n\treturn nil\n}", "func (ss *StringSet) Add(elements ...string) *StringSet {\n\tfor _, e := range elements {\n\t\tss.set[e] = true\n\t}\n\treturn ss\n}" ]
[ "0.6783332", "0.62357235", "0.5940099", "0.57633084", "0.5707226", "0.5516756", "0.5442915", "0.5305915", "0.52769697", "0.5260699", "0.5242574", "0.51552254", "0.51529825", "0.514143", "0.50967014", "0.50883275", "0.50859696", "0.5076476", "0.5075704", "0.5075591", "0.50702107", "0.5039655", "0.5030827", "0.50110346", "0.50041604", "0.49844056", "0.49549726", "0.49451518", "0.49388736", "0.49348998", "0.4929684", "0.4912016", "0.49035415", "0.49029595", "0.48853895", "0.48716137", "0.4864787", "0.48627678", "0.48417747", "0.48318025", "0.48292598", "0.48283204", "0.48191315", "0.4797841", "0.47874644", "0.47706667", "0.4765919", "0.4758443", "0.47492376", "0.47463158", "0.4743439", "0.47416615", "0.47396377", "0.4737777", "0.4736962", "0.4734263", "0.47281644", "0.47126803", "0.4709114", "0.47082174", "0.4704764", "0.46986496", "0.469022", "0.46812803", "0.46777523", "0.46770033", "0.46620864", "0.46503082", "0.46437863", "0.46435052", "0.464312", "0.46343836", "0.46327725", "0.46230555", "0.46205837", "0.46203837", "0.46141088", "0.46134135", "0.46085095", "0.45919552", "0.45889434", "0.45849833", "0.4584288", "0.4580993", "0.45710126", "0.45706522", "0.4568147", "0.45616233", "0.45548984", "0.45520425", "0.45493236", "0.4548381", "0.4547315", "0.45470455", "0.45464033", "0.4528539", "0.45284435", "0.4528091", "0.45256162", "0.45251107" ]
0.7894736
0
NewTickerSet Creates a new empty TickerSet
func NewTickerSet() TickerSet { return make(TickerSet) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newSet(txn *Transaction, key []byte) *Set {\n\tnow := Now()\n\treturn &Set{\n\t\ttxn: txn,\n\t\tkey: key,\n\t\tmeta: &SetMeta{\n\t\t\tObject: Object{\n\t\t\t\tID: UUID(),\n\t\t\t\tCreatedAt: now,\n\t\t\t\tUpdatedAt: now,\n\t\t\t\tExpireAt: 0,\n\t\t\t\tType: ObjectSet,\n\t\t\t\tEncoding: ObjectEncodingHT,\n\t\t\t},\n\t\t\tLen: 0,\n\t\t},\n\t}\n}", "func NewSet() Set {\n\treturn make(Set)\n}", "func NewSet() Set {\n\tm := make(map[string]struct{})\n\treturn Set{m}\n}", "func NewSet()(*Set) {\n m := &Set{\n Entity: *iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.NewEntity(),\n }\n return m\n}", "func NewSet() *Set {\n\treturn &Set{\n\t\tcache: make(map[I]bool),\n\t}\n}", "func NewSet(t ...*Term) Set {\n\ts := newset(len(t))\n\tfor i := range t {\n\t\ts.Add(t[i])\n\t}\n\treturn s\n}", "func NewSet(elements ...interface{}) Set {\n\toptions := &SetOptions{Cache: true}\n\tset := options.newThreadSafeSet()\n\tset.Add(elements...)\n\treturn &set\n}", "func (s *Set) New() Set {\n\treturn Set{make(map[interface{}]bool), 0}\n}", "func NewSet() *Set {\n\treturn &Set{\n\t\tset: make(map[string]bool),\n\t}\n}", "func NewSet() *Set {\n\treturn newSet()\n}", "func NewSet(compare func(interface{}, interface{}) int) Set {\n\treturn Set{NewTree(compare)}\n}", "func NewSet() *Set {\n\treturn &Set{elements: make(map[interface{}]bool), mu: sync.Mutex{}}\n}", "func NewSet() *Set {\n\treturn &Set{}\n}", "func NewSet(labels ...Instance) Set {\n\ts := make(map[Instance]struct{})\n\tfor _, l := range labels {\n\t\ts[l] = struct{}{}\n\t}\n\n\treturn s\n}", "func NewSet() *Set {\n\treturn &Set{set: make(map[cid.Cid]struct{}), lk: sync.Mutex{}}\n}", "func NewSet() *Set {\n\treturn &Set{maxID: -1, used: make(set.Int64s), free: make(set.Int64s)}\n}", "func NewSet(timestamp Nanotime, values map[string]struct{}, source Source, tags Tags) Set {\n\treturn Set{Values: values, Timestamp: timestamp, Source: source, Tags: tags.Copy()}\n}", "func NewSet() *Set {\n\treturn NewSizedSet(0)\n}", "func NewSet() *Set {\n\treturn &Set{\n\t\tm: make(map[string]*namedMetric),\n\t}\n}", "func NewSet(els ...string) (s Set) {\n\treturn s.Add(els...)\n}", "func New(dataType string) *HashSet {\n\treturn &HashSet{\n\t\tset: make(map[interface{}]interface{}),\n\t\tt: dataType,\n\t\tsize: 0,\n\t}\n}", "func NewSet() *Set {\n\tcomparator := func(left, right interface{}) bool {\n\t\treturn left.(Ordered).LessThan(right.(Ordered))\n\t}\n\treturn NewCustomSet(comparator)\n}", "func New() *Set {\n\treturn &Set{make(Record)}\n}", "func NewSet() *Set {\n\ts := &Set{}\n\treturn s\n}", "func New(keys ...string) Set {\n\tset := Empty()\n\tfor _, k := range keys {\n\t\tset.Add(k)\n\t}\n\treturn set\n}", "func New() Set {\n\treturn make(map[string]bool)\n}", "func Newset(flag, ex, tr int) *set_st {\n\ts := new(set_st)\n\ts.m = make(mapProto)\n\ts.set = make(setProto, 0)\n\ts.pset = unsafe.Pointer(&s.set)\n\n\ts.expireTime = ex\n\ts.triggerInterval = tr\n\ts.flag = flag\n\n\tgo s.refresh()\n\n\treturn s\n}", "func (st *buildStatus) newTestSet(testStats *buildstats.TestStats, names []distTestName) (*testSet, error) {\n\tset := &testSet{\n\t\tst: st,\n\t\ttestStats: testStats,\n\t}\n\tfor _, name := range names {\n\t\tset.items = append(set.items, &testItem{\n\t\t\tset: set,\n\t\t\tname: name,\n\t\t\tduration: testStats.Duration(st.BuilderRev.Name, name.Old),\n\t\t\ttake: make(chan token, 1),\n\t\t\tdone: make(chan token),\n\t\t})\n\t}\n\treturn set, nil\n}", "func NewSet(name string, client *Client) Set {\n\treturn Set{name: name, c: client}\n}", "func NewSet(host *Host, name string) (*Set, error) {\n\ts := &Set{host, pq.QuoteIdentifier(name)} // name is the name of the table\n\t// list is the name of the column\n\tif _, err := s.host.db.Exec(fmt.Sprintf(\"CREATE TABLE IF NOT EXISTS %s (%s %s)\", s.table, setCol, defaultStringType)); err != nil {\n\t\tif !strings.HasSuffix(err.Error(), \"already exists\") {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif Verbose {\n\t\tlog.Println(\"Created table \" + s.table + \" in database \" + host.dbname)\n\t}\n\treturn s, nil\n}", "func NewHamtSet() HamtSet {\n\treturn HamtSet{\n\t\tset: hamt.NewSet(),\n\t}\n}", "func NewSet() *Set {\n\treturn &Set{\n\t\tproxies: make(map[Proxy]bool),\n\t}\n}", "func New(items ...string) *Set {\n\tset := &Set{make(map[string]bool, len(items))}\n\tset.AppendSlice(items)\n\treturn set\n}", "func New(values ...interface{}) *Set {\n\tset := &Set{items: make(map[interface{}]struct{})}\n\tif len(values) > 0 {\n\t\tset.Add(values...)\n\t}\n\treturn set\n}", "func New(base mb.BaseMetricSet) (mb.MetricSet, error) {\n\treturn &MetricSet{base}, nil\n}", "func New(vals ...interface{}) Set {\n\ts := &setImpl{\n\t\tset: make(map[interface{}]struct{}, 0),\n\t}\n\tfor _, i := range vals {\n\t\ts.Insert(i)\n\t}\n\treturn s\n}", "func NewSet(name string) *Set {\n\ts := &Set{name: name}\n\ts.set = make(map[string]struct{})\n\treturn s\n}", "func New(initial ...string) Set {\n\ts := make(Set)\n\n\tfor _, v := range initial {\n\t\ts.Insert(v)\n\t}\n\n\treturn s\n}", "func NewSet(values ...string) (set Set) {\n\tfor _, value := range values {\n\t\tif value != \"\" {\n\t\t\tset = append(set, New(value))\n\t\t}\n\t}\n\treturn\n}", "func FileSetNew() *FileSet {\n\tfs := &FileSet{\n\t\ttop: 0,\n\t}\n\tc := make(chan string, bufferSize)\n\tfs.fileChannels = append(fs.fileChannels, c)\n\treturn fs\n}", "func NewSet(opts ...SetOption) Set {\n\tresult := Set{}\n\tfor _, opt := range opts {\n\t\topt(&result)\n\t}\n\tcenter := result.calculateCenter()\n\tradius := result.calculateRadius(center)\n\tresult.bs = NewSphere(center, radius)\n\treturn result\n}", "func TestSet_New(t *testing.T) {\n\tt.Run(\"Set is empty on construction\", func(t *testing.T) {\n\t\ts := New()\n\t\tassert.True(t, s.isEmpty())\n\t})\n\tt.Run(\"Set has 0 'size'' on construction\", func(t *testing.T) {\n\t\ts := New()\n\t\tassert.Equal(t, 0, s.Size())\n\t})\n}", "func NewTicker(d Duration) *Ticker {}", "func NewSetString() *SetString {\n\treturn &SetString{\n\t\tcache: make(map[string]bool),\n\t}\n}", "func NewSet(items ...Value) *Set {\n\tmapItems := make([]privateSetMapItem, 0, len(items))\n\tvar mapValue struct{}\n\tfor _, x := range items {\n\t\tmapItems = append(mapItems, privateSetMapItem{Key: x, Value: mapValue})\n\t}\n\n\treturn &Set{backingMap: newprivateSetMap(mapItems)}\n}", "func (o SetOptions) New(elements ...interface{}) (set Set) {\n\tif o.Unsafe {\n\t\tnewSet := o.newThreadUnsafeSet()\n\t\tset = &newSet\n\t} else {\n\t\tnewSet := o.newThreadSafeSet()\n\t\tset = &newSet\n\t}\n\tset.Add(elements...)\n\treturn\n}", "func newPeerSet() *peerSet {\n\treturn &peerSet{\n\t\tpeers: make(map[string]*peer),\n\t}\n}", "func newWrappedSet(encapsulated Set, immutable bool) DependentSet {\n res := new(setWrapper)\n res.SetDerived = EmbeddedDependentSet(res)\n res.encapsulated = encapsulated\n res.immutable = immutable\n return res\n}", "func NewSetQuery() filters.Spec { return &modQuery{behavior: set} }", "func NewSet() Set {\n\tn := new(SetImp)\n\tn.setmap = make(map[string] Target)\n\treturn n\n}", "func New(base mb.BaseMetricSet) (mb.MetricSet, error) {\n\treturn &MetricSet{\n\t\tBaseMetricSet: base,\n\t}, nil\n}", "func NewSet(strings ...string) *Set {\n\tset := &Set{\n\t\tm: map[string]struct{}{},\n\t}\n\tfor _, s := range strings {\n\t\t_ = set.Add(s)\n\t}\n\treturn set\n}", "func newStringSet() stringSet {\n\treturn make(map[string]struct{})\n}", "func New() Set {\n\treturn make([]*big.Int, 0)\n}", "func NewTicker(b BackOff) *Ticker {\n\tc := make(chan time.Time)\n\tt := &Ticker{\n\t\tC: c,\n\t\tc: c,\n\t\tb: b,\n\t\tstop: make(chan struct{}, 1),\n\t}\n\tgo t.run()\n\truntime.SetFinalizer(t, func(x *Ticker) { x.Stop() })\n\treturn t\n}", "func NewHashSet(initCapacity int) *HashSet {\n\t//not illegal\n\tif initCapacity < defaultCapacity {\n\t\tinitCapacity = defaultCapacity\n\t}\n\treturn &HashSet{\n\t\tsize: 0,\n\t\tinnerMap: make(map[interface{}]interface{}, initCapacity),\n\t}\n}", "func NewSet(size int) Set {\n\treturn make(Set, (size+63)>>6)\n}", "func (c *Conn) NewSet(table, name string) (*Set, error) {\n\ttabs, err := c.ListTables()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, tab := range tabs {\n\t\tif tab.Name == table || table == \"\" {\n\t\t\ts, err := c.GetSetByName(tab, name)\n\t\t\tif s == nil {\n\t\t\t\t// TODO: how to inspect netlink errors? Seems we're getting back only fmt.wrapErr\n\t\t\t\tif table == \"\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn &Set{\n\t\t\t\tConn: c,\n\t\t\t\tSet: s,\n\t\t\t\tMap: make(map[string][]byte),\n\t\t\t}, nil\n\t\t}\n\t}\n\treturn nil, errors.New(\"table or set not found\")\n}", "func NewSet(ss ...string) Set {\n\tsset := map[string]bool{}\n\tfor _, s := range ss {\n\t\tsset[s] = true\n\t}\n\n\treturn sset\n}", "func NewSet(name string, loader pongo2.TemplateLoader) *TemplateSet {\n\treturn pongo2.NewSet(name, loader)\n}", "func NewSet(elements ...Element) (elem CollectionElement, err error) {\n\n\t// check for errors\n\tfor _, child := range elements {\n\t\tif child == nil {\n\t\t\terr = ErrInvalidElement\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif err == nil {\n\t\tcoll := &collectionElemImpl{\n\t\t\tstartSymbol: SetStartLiteral,\n\t\t\tendSymbol: SetEndLiteral,\n\t\t\tseparatorSymbol: SetSeparatorLiteral,\n\t\t\tcollection: []Element{},\n\t\t}\n\n\t\tvar base *baseElemImpl\n\t\tif base, err = makeBaseElement(coll, SetType, collectionSerialization(false)); err == nil {\n\t\t\tcoll.baseElemImpl = base\n\t\t\telem = coll\n\t\t\terr = elem.Append(elements...)\n\t\t}\n\t}\n\n\treturn elem, err\n}", "func NewSet(root *cobra.Command) {\n\troot.AddCommand(setCmd)\n\n\t// Here you will define your flags and configuration settings.\n\n\t// Cobra supports Persistent Flags which will work for this command\n\t// and all subcommands, e.g.:\n\t// listCmd.PersistentFlags().String(\"foo\", \"\", \"A help for foo\")\n\n\t// Cobra supports local flags which will only run when this command\n\t// is called directly, e.g.:\n\t// listCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n}", "func NewContractSet(event string, conditions []string, ratios []float64, numContracts float64, v bool) ContractSet {\n\tmarkets := make([]Market, 0)\n\toracle = MarketCreator{0, make(map[string]Contract), make(map[string]PoolToken)}\n\tMints := numContracts\n\tfor i := 0; i < len(conditions); i++ {\n\t\tcontract := Contract{conditions[i], numContracts}\n\t\tusd := numContracts * ratios[i]\n\t\tpoolToken := PoolToken{conditions[i], math.Sqrt(numContracts * usd)}\n\t\tp := Pool{contract, usd, poolToken}\n\t\tmarkets = append(markets, Market{p, conditions[i]})\n\t}\n\n\tcontractSet := ContractSet{markets, event, 0, \"none\", Mints}\n\t//verbose statement\n\tif v {\n\t\tfmt.Println(\"Newly created ContractSet\")\n\t\tfmt.Println(\"Event:\", event)\n\t\tfmt.Println(\"Conditions:\", conditions)\n\t\tfmt.Println(\"Ratios:\", ratios)\n\t\tfmt.Println(\"NumContracts\", numContracts)\n\t\tfmt.Println()\n\t}\n\n\treturn contractSet\n}", "func NewTicker(pairs ...string) (*Ticker, error) {\n\tif len(pairs) == 0 {\n\t\treturn nil, errors.New(\"no pairs provided\")\n\t}\n\n\tclients := make(map[string]*apiClient.Instance)\n\n\tfor k := range pairs {\n\t\tclients[pairs[k]] = apiClient.New(apiClient.Config{\n\t\t\tAddresses: []string{\n\t\t\t\tfmt.Sprintf(\"https://api.cryptonator.com/api/full/%s\", pairs[k]),\n\t\t\t},\n\t\t})\n\t}\n\n\treturn &Ticker{\n\t\tapiClients: clients,\n\t}, nil\n}", "func NewSet() *Set {\n\treturn &Set{\n\t\trules: make(map[string]*Rule),\n\t\trouter: route.New(),\n\t}\n}", "func New(elements ...string) *StringSet {\n\tset := &StringSet{make(map[string]bool)}\n\tset.Add(elements...)\n\treturn set\n}", "func (tickerSet TickerSet) Add(ticker string) {\n\ttickerSet[ticker] = true\n}", "func New(elems ...string) StringSet {\n\tset := NewWithCap(len(elems))\n\tset.Add(elems...)\n\treturn set\n}", "func NewSet(members ...uint) Set {\n\ts := Set{}\n\tfor _, member := range members {\n\t\ts[member] = true\n\t}\n\treturn s\n}", "func NewHashSet() *HashSet {\n\treturn &HashSet{\n\t\tm: map[hash.Hash]interface{}{},\n\t}\n}", "func New(name string) *Set {\n\treturn &Set{\n\t\terrors: make(chan error),\n\t\thosts: make(map[string]struct{}),\n\t\tname: name,\n\n\t\tadd: func(ip string) error {\n\t\t\tok, err := hostInSet(name, ip)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !ok {\n\t\t\t\tcmd := exec.Command(\"ipset\", \"add\", name, ip)\n\t\t\t\tvar stderr bytes.Buffer\n\t\t\t\tcmd.Stderr = &stderr\n\t\t\t\tif err := cmd.Run(); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to add host %s to set %s: %s\", ip, name, stderr.String())\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\tdel: func(ip string) error {\n\t\t\tok, err := hostInSet(name, ip)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif ok {\n\t\t\t\tcmd := exec.Command(\"ipset\", \"del\", name, ip)\n\t\t\t\tvar stderr bytes.Buffer\n\t\t\t\tcmd.Stderr = &stderr\n\t\t\t\tif err := cmd.Run(); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to remove host %s from set %s: %s\", ip, name, stderr.String())\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n}", "func New(opts *Options) *Set {\n\ts := &Set{\n\t\tsymid: make(map[string]id),\n\t\tnodes: make(map[node]nid),\n\t\tfacts: make(map[nid]map[fact]struct{}),\n\t\tedges: make(map[nid]map[edge]struct{}),\n\t\topts: opts,\n\t}\n\ts.enter(\"\") // pre-assign \"\" as ID 0\n\ts.canon = true\n\treturn s\n}", "func New(getkey func(value interface{}) interface{}, vtype string) *SSet {\n\tvar set SSet\n\tset.list = arraylist.New()\n\tset.m = hashmap.New()\n\tset.m_index = make(map[interface{}]int)\n\tset.f = getkey\n\tset.item_type = vtype\n\tset.createline = time.Now().Unix()\n\treturn &set\n}", "func TestNewSet(t *testing.T) {\n\tt.Run(\"A stack is empty on construction\", func(t *testing.T) {\n\t\ts := stack.New()\n\t\t//s := stack.New()\n\t\tassert.True(t, s.IsEmpty())\n\t})\n}", "func NewTicker(d time.Duration, f TickerFunction) *Ticker {\n\treturn &Ticker{\n\t\tf: f,\n\t\td: d,\n\t}\n}", "func NewHashSet() *HashSet {\n\tmmap := maps.NewHashMap()\n\treturn &HashSet{mmap}\n}", "func NewTransportSet(items ...string) *TransportSet {\n\tt := &TransportSet{\n\t\tTransports: map[string]struct{}{},\n\t}\n\tfor _, i := range items {\n\t\tt.Transports[i] = struct{}{}\n\t}\n\treturn t\n}", "func New(watch Watcher) *HTTPSet {\n\thttpset := &HTTPSet{\n\t\tWatcher: watch,\n\t\tHTTPClient: http.DefaultClient,\n\t\tevent: make(chan struct{}, 1),\n\t}\n\n\tif watch != nil {\n\t\t// don't trigger and event the first time\n\t\thttpset.setEndpoints(watch.Endpoints())\n\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-watch.Event():\n\t\t\t\t\thttpset.SetEndpoints(watch.Endpoints())\n\t\t\t\t}\n\n\t\t\t\tif watch.IsClosed() {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\twatcherClosed()\n\t\t}()\n\t}\n\n\treturn httpset\n}", "func New() helper.MetricSeter {\n\treturn &MetricSeter{\n\t\tredisPools: map[string]*rd.Pool{},\n\t}\n}", "func makeSet() *customSet {\n\treturn &customSet{\n\t\tcontainer: make(map[string]struct{}),\n\t}\n}", "func NewKBSet(kbList string) KBSet {\n\treturn NewKBSetFromSlice(helpers.StringToSlice(kbList))\n}", "func New(base mb.BaseMetricSet) (mb.MetricSet, error) {\n\tvar config Config\n\n\tif err := base.Module().UnpackConfig(&config); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &MetricSet{\n\t\tBaseMetricSet: base,\n\t\tcfg: config,\n\t}, nil\n}", "func newQuarksStatefulSets(c *QuarksstatefulsetV1alpha1Client, namespace string) *quarksStatefulSets {\n\treturn &quarksStatefulSets{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}", "func NewTicker(d time.Duration) (joe.Tocker, error) {\n\tp, err := NewProfiler()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := Ticker{Ticker: joe.NewTicker(d), Data: make(chan []byte), Profiler: p}\n\tgo t.Run()\n\treturn &t, nil\n}", "func NewTicker(d time.Duration) (joe.Tocker, error) {\n\tp, err := NewProfiler()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := Ticker{Ticker: joe.NewTicker(d), Data: make(chan []byte), Profiler: p}\n\tgo t.Run()\n\treturn &t, nil\n}", "func Constructor() MyHashSet {\n\treturn MyHashSet{\n\t\tSet: make([]uint8, 125000+1),\n\t}\n}", "func Constructor() MyHashSet {\n\treturn MyHashSet{}\n}", "func Constructor() MyHashSet {\n\treturn MyHashSet{}\n}", "func (c *Client) StickersCreateStickerSet(ctx context.Context, request *StickersCreateStickerSetRequest) (MessagesStickerSetClass, error) {\n\tvar result MessagesStickerSetBox\n\n\tif err := c.rpc.Invoke(ctx, request, &result); err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.StickerSet, nil\n}", "func NewStringSet() StringSet {\n\treturn make(StringSet)\n}", "func NewChainSet(t testing.TB) *ChainSet {\n\tmock := &ChainSet{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func New(items ...uint32) *Set {\n\ts := &Set{items: make(map[uint32]struct{}, len(items))}\n\ts.Add(items...)\n\treturn s\n}", "func New(base mb.BaseMetricSet) (mb.MetricSet, error) {\n\n\tconfig := struct{}{}\n\n\tif err := base.Module().UnpackConfig(&config); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &MetricSet{\n\t\tBaseMetricSet: base,\n\t}, nil\n}", "func NewStringSet() *StringSet {\n\treturn &StringSet{make(map[string]bool), make([]string, 0), false}\n}", "func New() StringSet {\n\treturn &mapStringSet{\n\t\tstorage: make(map[string]uint64),\n\t}\n}", "func New(c rest.Interface) *Clientset {\n\tvar cs Clientset\n\tcs.testsV1alpha1 = testsv1alpha1.New(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClient(c)\n\treturn &cs\n}", "func New(c rest.Interface) *Clientset {\n\tvar cs Clientset\n\tcs.scalerV1alpha1 = scalerv1alpha1.New(c)\n\tcs.sparkschedulerV1beta1 = sparkschedulerv1beta1.New(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClient(c)\n\treturn &cs\n}", "func NewTileset(base *base.Base) *Tileset {\n\treturn &Tileset{base, \"\", \"\"}\n}", "func NewTimeTicker(t testing.TB) *TimeTicker {\n\tmock := &TimeTicker{}\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewFeatureSet(features ...string) FeatureSet {\n\tset := make(FeatureSet, len(features))\n\tfor _, feature := range features {\n\t\tset[feature] = struct{}{}\n\t}\n\treturn set\n}" ]
[ "0.6389514", "0.6260035", "0.6255809", "0.62320423", "0.61772984", "0.6169277", "0.6104857", "0.60863173", "0.6085063", "0.6078854", "0.6059124", "0.6054396", "0.6039346", "0.6019574", "0.60120744", "0.5986136", "0.5985384", "0.59849", "0.59237856", "0.59184754", "0.5897813", "0.5892106", "0.5891982", "0.58918154", "0.58716726", "0.58256423", "0.58160263", "0.5804784", "0.5795901", "0.5795384", "0.57415503", "0.57282186", "0.57057685", "0.5670791", "0.56436837", "0.56327534", "0.56079286", "0.55898327", "0.5585475", "0.55847937", "0.5577222", "0.5567213", "0.5565741", "0.55333984", "0.5509611", "0.54991454", "0.5496308", "0.54947454", "0.5493555", "0.5484543", "0.5477316", "0.54616886", "0.5455676", "0.5454751", "0.54283524", "0.540482", "0.5399927", "0.5396983", "0.538711", "0.5383829", "0.53780407", "0.5336499", "0.53341025", "0.5331837", "0.5302338", "0.53014773", "0.529465", "0.52774096", "0.5251514", "0.5234201", "0.5233083", "0.5229627", "0.52226514", "0.52222145", "0.52157694", "0.52118725", "0.5211688", "0.51955056", "0.51884806", "0.5150356", "0.51436114", "0.51268137", "0.51235133", "0.5118526", "0.5118526", "0.5112286", "0.5109347", "0.5109347", "0.51004684", "0.5090904", "0.50786734", "0.50765973", "0.50719833", "0.5064128", "0.50535136", "0.5027061", "0.50217116", "0.5021499", "0.5014966", "0.49953598" ]
0.811256
0
ToSlice Converts a ticker set to a slice
func (tickerSet TickerSet) ToSlice() []string { tickerSlice := make([]string, 0) for ticker, _ := range tickerSet { tickerSlice = append(tickerSlice, ticker) } return tickerSlice }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 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 (set KeySet) ToSlice() []Key {\n\tkeys := []Key{}\n\n\tfor key := range set {\n\t\tkeys = append(keys, key)\n\t}\n\n\treturn keys\n}", "func (s *Set) ToSlice() []interface{} {\n\tvar slice []interface{}\n\tcurrElemNum := 0\n\tfor k := range s.vals {\n\t\tif currElemNum < cap(slice) {\n\t\t\tslice[currElemNum] = k\n\t\t} else {\n\t\t\tslice = append(slice, k)\n\t\t}\n\t\tcurrElemNum++\n\t}\n\treturn slice\n}", "func (set *AppleSet) ToSlice() []Apple {\n\tset.s.RLock()\n\tdefer set.s.RUnlock()\n\n\treturn set.slice()\n}", "func (set StringSet) ToSlice() []string {\n\tif n := set.Len(); n > 0 {\n\t\tresult := make([]string, 0, n)\n\t\tfor str := range set {\n\t\t\tresult = append(result, str)\n\t\t}\n\t\treturn result\n\t}\n\treturn nil\n}", "func (s StringSet) ToSlice() []string {\n\tret := make([]string, len(s))\n\tidx := 0\n\tfor v := range s {\n\t\tret[idx] = v\n\t\tidx++\n\t}\n\tsort.Strings(ret)\n\treturn ret\n}", "func (ps *FabricProviderSet) ToSlice() []*FabricProvider {\n\tif ps == nil {\n\t\treturn []*FabricProvider{}\n\t}\n\n\tslice := make([]*FabricProvider, 0, ps.Len())\n\tfor _, priority := range ps.byPriority.keys() {\n\t\tprovs := ps.byPriority[priority]\n\t\tfor _, prov := range provs.keys() {\n\t\t\tslice = append(slice, provs[prov])\n\t\t}\n\t}\n\treturn slice\n}", "func (s StringSet) ToSlice() []string {\n\tslice := []string{}\n\tfor value := range s {\n\t\tslice = append(slice, value)\n\t}\n\treturn slice\n}", "func (s *ConcurrentSet) ToSlice() []interface{} {\n\tslice := make([]interface{}, 0)\n\ts.hash.Range(func(k, v interface{}) bool {\n\t\tslice = append(slice, k)\n\t\treturn true\n\t})\n\n\treturn slice\n}", "func (s *IntSet) ToSlice() []int {\n\tr := make([]int, 0, s.Size())\n\n\tfor key := range s.elem {\n\t\tr = append(r, key)\n\t}\n\treturn r\n}", "func (set Int64Set) ToSlice() []int64 {\n\tvar s []int64\n\tfor v := range set {\n\t\ts = append(s, v)\n\t}\n\treturn s\n}", "func (btsm ByTimeSummaryMap) ToSlice() ByTimeSummarySlice {\n\ts := make(ByTimeSummarySlice, 0)\n\tfor _, summ := range btsm {\n\t\ts = append(s, summ)\n\t}\n\treturn s\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 ToStringSlice(set mapset.Set) []string {\n\tif set == nil {\n\t\treturn nil\n\t}\n\tslice := set.ToSlice()\n\tresult := make([]string, len(slice))\n\tfor i, item := range slice {\n\t\tresult[i] = item.(string)\n\t}\n\treturn result\n}", "func (ss Set) Slice() []string {\n\tslc := make([]string, 0, len(ss))\n\tfor k := range ss {\n\t\tslc = append(slc, k)\n\t}\n\n\treturn slc\n}", "func (bm tsidbitmap) ToSlice() (out []core.TractserverID) {\n\tfor idx, v := range bm {\n\t\tfor off := uint64(0); off < 64; off++ {\n\t\t\tif v&(uint64(1)<<off) != 0 {\n\t\t\t\tout = append(out, core.TractserverID(uint64(idx)*64+off))\n\t\t\t}\n\t\t}\n\t}\n\treturn\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 (s StateSet) Slice() []State {\n\tslice := make([]State, 0, len(s))\n\tfor state := range s {\n\t\tslice = append(slice, state)\n\t}\n\treturn slice\n}", "func (s Set) Slice() []string {\n\ttoReturn := make([]string, s.Len())\n\ti := 0\n\tfor st := range s {\n\t\ttoReturn[i] = st\n\t\ti++\n\t}\n\treturn toReturn\n}", "func (s StringSet) Slice() []string {\n\tt := make([]string, 0, len(s))\n\tfor k := range s {\n\t\tt = append(t, k)\n\t}\n\treturn t\n}", "func toSlice(tweet *twitter.Tweet) []string {\n\toutput := make([]string, 0, 5)\n\n\toutput = append(output, tweet.IDStr)\n\toutput = append(output, tweet.CreatedAt)\n\toutput = append(output, strconv.Itoa(tweet.FavoriteCount))\n\toutput = append(output, strconv.Itoa(tweet.RetweetCount))\n\toutput = append(output, tweet.Text)\n\n\treturn output\n}", "func (s Set) Slice() []string {\n\tvar i uint64\n\n\tk := make([]string, len(s))\n\n\tfor key := range s {\n\t\tk[i] = key\n\t\ti++\n\t}\n\n\treturn k\n}", "func (this *HashSet) ToSlice() []interface{} {\n\treturn this.mmap.Keys()\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 *SeriesIDSet) Slice() []uint64 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\ta := make([]uint64, 0, s.bitmap.GetCardinality())\n\tfor _, seriesID := range s.bitmap.ToArray() {\n\t\ta = append(a, uint64(seriesID))\n\t}\n\treturn a\n}", "func (s *Set) Slice() []string {\n\tn := len(s.m)\n\tif n == 0 {\n\t\treturn nil\n\t}\n\tarr := make([]string, 0, n)\n\tfor val := range s.m {\n\t\tarr = append(arr, val)\n\t}\n\treturn arr\n}", "func (s *Services) ToSliceKind() []Service {\n\tif s == nil {\n\t\treturn []Service{}\n\t}\n\treturn []Service(*s)\n}", "func (list *LinkedList[T]) ToSlice() []T {\n\treturn list.Enumerate(context.Background()).ToSlice()\n}", "func (s StringSet) AsSlice() []string {\n\tresult := make([]string, len(s), len(s))\n\ti := 0\n\tfor v := range s {\n\t\tresult[i] = v\n\t\ti++\n\t}\n\treturn result\n}", "func (s *IntSlicer) AsSlice() []int {\n\treturn s.slice\n}", "func (s S) SetSlice(key, value string, before, after int) (slice []string, err error) {\n\tvar vv SortedString\n\terr = s.ReadModify(key, &vv, func(_ interface{}) (r bool) {\n\t\tslice = vv.Slice(value, before, after)\n\t\treturn\n\t})\n\treturn\n}", "func (set UInt64Set) Slice(sorted bool) UInt64Slice {\n\tslice := NewUInt64Slice(0, len(set))\n\tfor x := range set {\n\t\tslice = append(slice, x)\n\t}\n\tif sorted {\n\t\tslice.Sort()\n\t}\n\treturn slice\n}", "func ToSlice(array *js.Object) []interface{} {\n\treturn array.Interface().([]interface{})\n}", "func (s *Set) Slice() []uint32 {\n\tsl := make([]uint32, len(s.items))\n\ti := 0\n\tfor item := range s.items {\n\t\tsl[i] = item\n\t\ti++\n\t}\n\treturn sl\n}", "func (set Int64Set) ToInterfaceSlice() []interface{} {\n\tvar s []interface{}\n\tfor v, _ := range set {\n\t\ts = append(s, v)\n\t}\n\treturn s\n}", "func (s Slice) ToStringSlice() []string {\n\tres := make([]string, len(s))\n\tfor i, ID := range s {\n\t\tres[i] = ID.String()\n\t}\n\treturn res\n}", "func (set *AppleSet) slice() []Apple {\n\tif set == nil {\n\t\treturn nil\n\t}\n\n\ts := make([]Apple, 0, len(set.m))\n\tfor v := range set.m {\n\t\ts = append(s, v)\n\t}\n\treturn s\n}", "func (s *Set) StringSlice() []string {\n\tslice := make([]string, 0, s.Size())\n\n\ts.mutex.Lock()\n\tfor k := range s.m {\n\t\tslice = append(slice, k.(string))\n\t}\n\ts.mutex.Unlock()\n\n\treturn slice\n}", "func SliceToSlice[A any, B any](a []A, f func(A) B) []B {\n\tb := make([]B, len(a))\n\tfor i := range a {\n\t\tb[i] = f(a[i])\n\t}\n\treturn b\n}", "func (s String) ToSlice() []string {\n\tres := make([]string, 0)\n\tfor k := range s {\n\t\tres = append(res, k)\n\t}\n\treturn res\n}", "func GetSlice() {\n\tvar slice1 []string\n\tslice1 = append(slice1, \"mi\", \"slice\", \"1\")\n\tfmt.Println(slice1)\n}", "func (s IntSet) AsSlice() []int {\n\tresult := make([]int, len(s), len(s))\n\ti := 0\n\tfor v := range s {\n\t\tresult[i] = v\n\t\ti++\n\t}\n\treturn result\n}", "func (s String) ToSlice() []string {\n\tslice := make([]string, len(s))\n\tvar i = 0\n\tfor k := range s {\n\t\tslice[i] = k\n\t\ti++\n\t}\n\treturn slice\n}", "func (s *set) Slice() []*Term {\n\treturn s.sortedKeys()\n}", "func (s SamplesC64) Slice(start, end int) Samples {\n\treturn s[start:end]\n}", "func (p *TimePanel) Slice(from, to time.Time) TimePanelRO {\n\ti := sort.Search(len(p.dates), func(i int) bool {\n\t\treturn !p.dates[i].Before(from)\n\t})\n\tj := sort.Search(len(p.dates), func(i int) bool {\n\t\treturn !p.dates[i].Before(to)\n\t})\n\treturn p.ISlice(i, j)\n}", "func ToStringSlice(i interface{}) []string {\n\treturn cast.ToStringSlice(i)\n}", "func (set *SetString) Slice() SliceString {\n\tset.lock.Lock()\n\tkeys := make(SliceString, len(set.cache))\n\ti := 0\n\tfor k := range set.cache {\n\t\tkeys[i] = k\n\t}\n\tset.lock.Unlock()\n\treturn keys\n}", "func (list *ArrayList[T]) ToSlice() []T {\n\tslice := make([]T, InitLen, InitCap)\n\tfor _, ele := range list.elems {\n\t\tslice = append(slice, ele)\n\t}\n\treturn slice\n}", "func (s *Set) ToNativeSlice() []Value {\n\titems := make([]Value, 0, s.Len())\n\ts.Range(func(item Value) bool {\n\t\titems = append(items, item)\n\t\treturn true\n\t})\n\n\treturn items\n}", "func ToSlice(v interface{}) ([]byte, error) {\n\tswitch b := v.(type) {\n\tcase []byte:\n\t\treturn b, nil\n\tcase string:\n\t\treturn []byte(b), nil\n\tcase Name:\n\t\treturn []byte(b), nil\n\tcase Byter:\n\t\treturn b.Bytes(), nil\n\t}\n\tvar buf bytes.Buffer\n\tif err := binary.Write(&buf, binary.BigEndian, v); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func ExampleIntSet_Slice() {\n\ts1 := gset.NewIntSet()\n\ts1.Add([]int{1, 2, 3, 4}...)\n\tfmt.Println(s1.Slice())\n\n\t// May Output:\n\t// [1, 2, 3, 4]\n}", "func (c StringArrayCollection) Slice(keys ...int) Collection {\n\tvar d = make([]string, len(c.value))\n\tcopy(d, c.value)\n\tif len(keys) == 1 {\n\t\treturn StringArrayCollection{\n\t\t\tvalue: d[keys[0]:],\n\t\t}\n\t} else {\n\t\treturn StringArrayCollection{\n\t\t\tvalue: d[keys[0] : keys[0]+keys[1]],\n\t\t}\n\t}\n}", "func (set *SetUI) Slice() SliceUI {\n\tset.lock.Lock()\n\tkeys := make(SliceUI, len(set.cache))\n\ti := 0\n\tfor k := range set.cache {\n\t\tkeys[i] = k\n\t}\n\tset.lock.Unlock()\n\treturn keys\n}", "func (s *SliceOfInt8) GetSlice() *[]int8 {\n\treturn &s.items\n}", "func NewFromSlice(sl []string) Set {\n\ttoReturn := New()\n\tfor _, s := range sl {\n\t\ttoReturn.Add(s)\n\t}\n\treturn toReturn\n}", "func Subset[T any](collection []T, offset int, length uint) []T {\n\tsize := len(collection)\n\n\tif offset < 0 {\n\t\toffset = size + offset\n\t\tif offset < 0 {\n\t\t\toffset = 0\n\t\t}\n\t}\n\n\tif offset > size {\n\t\treturn []T{}\n\t}\n\n\tif length > uint(size)-uint(offset) {\n\t\tlength = uint(size - offset)\n\t}\n\n\treturn collection[offset : offset+int(length)]\n}", "func (m OrderedMap[K, V]) ToSlice() []OrderedMapItem[K, V] {\n\treturn m.items\n}", "func (dataset *Dataset) AsSlice() []Vector {\r\n\treturn dataset.data\r\n}", "func (this *LinkedList) ToSlice() []interface{} {\n\tslice := make([]interface{}, INIT_LEN, INIT_CAP)\n\tpe := this.head\n\tfor pe != nil {\n\t\tslice = append(slice, pe.elem)\n\t\tpe = pe.next\n\t}\n\treturn slice\n}", "func (actionSet ActionSet) ToSlice() []authorizer.Action {\n\tactions := []authorizer.Action{}\n\tfor action := range actionSet {\n\t\tactions = append(actions, action)\n\t}\n\n\treturn actions\n}", "func (l *list) Slice(first int, last int) interface{} {\n\ttypeOf := reflect.TypeOf(l.t)\n\tsliceOf := reflect.SliceOf(typeOf)\n\tvar result = reflect.ValueOf(reflect.New(sliceOf).Interface()).Elem()\n\n\tfor _, v := range l.elements[first:last] {\n\t\tresult.Set(reflect.Append(result, reflect.ValueOf(v)))\n\t}\n\n\treturn result.Interface()\n}", "func (mm Uint64Uint64Map) ToSlice() Uint64Uint64Tuples {\n\treturn mm.slice()\n}", "func (s Series) Subset(indexes Indexes) Series {\n\tif err := s.Err; err != nil {\n\t\treturn s\n\t}\n\tidx, err := parseIndexes(s.Len(), indexes)\n\tif err != nil {\n\t\ts.Err = err\n\t\treturn s\n\t}\n\tret := Series{\n\t\tName: s.Name,\n\t\tt: s.t,\n\t}\n\tswitch s.t {\n\tcase String:\n\t\telements := make(stringElements, len(idx))\n\t\tfor k, i := range idx {\n\t\t\telements[k] = s.elements.(stringElements)[i]\n\t\t}\n\t\tret.elements = elements\n\tcase Int:\n\t\telements := make(intElements, len(idx))\n\t\tfor k, i := range idx {\n\t\t\telements[k] = s.elements.(intElements)[i]\n\t\t}\n\t\tret.elements = elements\n\tcase Uint:\n\t\telements := make(uintElements, len(idx))\n\t\tfor k, i := range idx {\n\t\t\telements[k] = s.elements.(uintElements)[i]\n\t\t}\n\t\tret.elements = elements\n\tcase Float:\n\t\telements := make(floatElements, len(idx))\n\t\tfor k, i := range idx {\n\t\t\telements[k] = s.elements.(floatElements)[i]\n\t\t}\n\t\tret.elements = elements\n\tcase Bool:\n\t\telements := make(boolElements, len(idx))\n\t\tfor k, i := range idx {\n\t\t\telements[k] = s.elements.(boolElements)[i]\n\t\t}\n\t\tret.elements = elements\n\tdefault:\n\t\tpanic(\"unknown series type\")\n\t}\n\treturn ret\n}", "func (e employee) ToSlice() []string {\n\treturn []string{\n\t\te.Name,\n\t\te.Salary,\n\t\te.Email,\n\t\te.Id,\n\t}\n}", "func ToTypedSlice[T any](slice []any) []T {\n\tif len(slice) == 0 {\n\t\treturn nil\n\t}\n\tout := make([]T, len(slice))\n\tfor i, elem := range slice {\n\t\tout[i] = elem.(T)\n\t}\n\treturn out\n}", "func (ps PlanSlice) Slice() []string {\n\ts := []string{}\n\tfor _, p := range ps {\n\t\ts = append(s, p.Name)\n\t}\n\treturn s\n}", "func makeSlice(in interface{}) []interface{} {\n\treturn in.([]interface{})\n}", "func (p *SliceOfMap) ToStringSlice() (slice *StringSlice) {\n\treturn ToStringSlice(p.O())\n}", "func (p *pipeline) ToSlice(target interface{}) {\n\ttargetValue := reflect.ValueOf(target)\n\tif targetValue.Kind() != reflect.Ptr {\n\t\tpanic(\"target slice must be a pointer\")\n\t}\n\tsliceValue := reflect.Indirect(targetValue)\n\tp.nextStage = &pipeline{\n\t\tpreviousStage: p,\n\t\tsourceStage: p.sourceStage,\n\t\tdo: func(nextStage *pipeline, v interface{}) {\n\t\t\tif p.sourceStage.parallel {\n\t\t\t\tp.lock.Lock()\n\t\t\t\tdefer p.lock.Unlock()\n\t\t\t}\n\t\t\tif v == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsliceValue.Set(reflect.Append(sliceValue, reflect.ValueOf(v)))\n\t\t},\n\t}\n\tterminal{}.evaluate(p.sourceStage)\n}", "func (t *RestPostDescriptor) ConvertToSlice() *ggt.MethodDescriptor { return t.methodConvertToSlice }", "func (s *SliceOfInt16) GetSlice() *[]int16 {\n\treturn &s.items\n}", "func (s String) ToSlice() []string {\n\tslice := make([]string, 0, len(s))\n\tfor str := range s {\n\t\tslice = append(slice, str)\n\t}\n\treturn slice\n}", "func (p *Partition) slice(from, to *time.Time) Entries {\n\t// take a snapshot to avoid concurrent modification (a slice is immutable)\n\tp.mu.RLock()\n\tentries := p.entries\n\tp.mu.RUnlock()\n\n\tstart := 0\n\tend := len(entries)\n\n\tif from != nil {\n\t\tstart = sort.Search(len(entries), func(i int) bool {\n\t\t\treturn entries[i].Timestamp.After(*from) || entries[i].Timestamp.Equal(*from)\n\t\t})\n\t}\n\tif to != nil {\n\t\tend = sort.Search(len(entries), func(i int) bool {\n\t\t\treturn entries[i].Timestamp.After(*to)\n\t\t})\n\t}\n\tif end < start {\n\t\t// should return empty slice?\n\t\treturn nil\n\t}\n\treturn entries[start:end]\n}", "func MapToSlice(m map[int64]*backends.Result) []*backends.Result {\n\ts := make([]*backends.Result, 0, len(m))\n\n\tfor _, v := range m {\n\t\ts = append(s, v)\n\t}\n\n\treturn s\n}", "func (s *SliceOfFloat64) GetSlice() *[]float64 {\n\treturn &s.items\n}", "func (s *SliceOfInt64) GetSlice() *[]int64 {\n\treturn &s.items\n}", "func Slice(slice interface{}) {\n\tswitch p := slice.(type) {\n\tcase []bool:\n\t\tBools(p)\n\tcase []uint8:\n\t\tUint8s(p)\n\tcase []uint16:\n\t\tUint16s(p)\n\tcase []uint32:\n\t\tUint32s(p)\n\tcase []uint64:\n\t\tUint64s(p)\n\tcase []int8:\n\t\tInt8s(p)\n\tcase []int16:\n\t\tInt16s(p)\n\tcase []int32:\n\t\tInt32s(p)\n\tcase []int64:\n\t\tInt64s(p)\n\tcase []float32:\n\t\tFloat32s(p)\n\tcase []float64:\n\t\tFloat64s(p)\n\tcase []complex64:\n\t\tComplex64s(p)\n\tcase []complex128:\n\t\tComplex128s(p)\n\tcase []uint:\n\t\tUints(p)\n\tcase []int:\n\t\tInts(p)\n\tcase []uintptr:\n\t\tUintptrs(p)\n\tcase []string:\n\t\tStrings(p)\n\tcase Interface:\n\t\tFlip(p)\n\tdefault:\n\t\trv := reflectValueOf(slice)\n\t\tswap := reflectSwapper(slice)\n\t\tFlip(reflectSlice{rv, swap})\n\t}\n}", "func (DummyStore) GetSlice(key string) ([]interface{}, error) {\n\treturn nil, nil\n}", "func (iobuf *buf) slice(free, base, bound uint) *Slice {\n\tatomic.AddInt32(&iobuf.refcount, 1)\n\treturn &Slice{iobuf: iobuf, free: free, base: base, Contents: iobuf.Contents[base:bound]}\n}", "func GetSlice() []int {\n\tx := []int{1, 2, 3}\n\treturn x\n}", "func (s *SliceOfUint8) GetSlice() *[]uint8 {\n\treturn &s.items\n}", "func (slice ExerciseSlice) ToDataPointSlice(matchingReads []GlucoseRead, glucoseUnit GlucoseUnit) (dataPoints []DataPoint) {\n\tdataPoints = make([]DataPoint, len(slice))\n\tfor i := range slice {\n\t\tlocalTime, err := slice[i].Time.Format()\n\t\tif err != nil {\n\t\t\tutil.Propagate(err)\n\t\t}\n\n\t\tdataPoint := DataPoint{localTime, slice.GetEpochTime(i),\n\t\t\tlinearInterpolateY(matchingReads, slice[i].Time, glucoseUnit), float32(slice[i].DurationMinutes), EXERCISE_TAG, \"minutes\"}\n\t\tdataPoints[i] = dataPoint\n\t}\n\n\treturn dataPoints\n}", "func (r Range) ToSlice() []byte {\n\tif r.length == 0 {\n\t\treturn nil\n\t}\n\tall := make([]byte, 0, r.length)\n\tr.iterate(func(v *buffer.View) {\n\t\tall = append(all, v.AsSlice()...)\n\t})\n\treturn all\n}", "func (s *slice) slice(start, stop int, elemsize uintptr) slice {\n\tif start >= s.cap_ || start < 0 || stop > s.cap_ || stop < 0 {\n\t\tpanic(\"cuda4/safe: slice index out of bounds\")\n\t}\n\tif start > stop {\n\t\tpanic(\"cuda4/safe: inverted slice range\")\n\t}\n\treturn slice{cu.DevicePtr(uintptr(s.ptr_) + uintptr(start)*elemsize), stop - start, s.cap_ - start}\n}", "func ToIntSlice(i interface{}) []int {\n\treturn cast.ToIntSlice(i)\n}", "func getSlice(p position) []byte {\n\ts, i := getChunkLocation(p.chunk)\n\tbufStart := int(i)*ChunkSize + p.chunkPos\n\tbufLen := ChunkSize - p.chunkPos\n\treturn slabs[s].memory[bufStart : bufStart+bufLen]\n}", "func wrapInSlice(s []string) [][]string {\n\toutput := make([][]string, len(s))\n\tfor i := 0; i < len(output); i++ {\n\t\telem := make([]string, 1)\n\t\telem[0] = s[i]\n\t\toutput[i] = elem\n\t}\n\treturn output\n}", "func (p *SliceOfMap) ToIntSlice() (slice *IntSlice) {\n\treturn ToIntSlice(p.O())\n}", "func (stream *TokenStream) ToSlice() ([]*Token, error) {\n\tvar result []*Token\n\n\tfor stream.Scan() {\n\t\tresult = append(result, stream.Token())\n\t}\n\n\tif err := stream.Err(); err != nil {\n\t\treturn nil, stream.Err()\n\t}\n\n\treturn result, nil\n}", "func (s *SliceOfUint64) GetSlice() *[]uint64 {\n\treturn &s.items\n}", "func (t *StringSlice) Slice(start int, length int) []string {\n\tvar ret []string\n\tif start >= 0 && start+length <= len(t.items) && start+length >= 0 {\n\t\tret = t.items[start : start+length]\n\t}\n\treturn ret\n}", "func toValidSlice(v, ov R.Value) (out R.Value, err error) {\n\terr = validateContainerValue(v.Type().Elem(), ov)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn v, nil\n}", "func (s *SliceOfByte) GetSlice() *[]byte {\n\treturn &s.items\n}", "func GetSlice(i interface{}) []interface{} {\n\tvar ret []interface{}\n\ts := reflect.ValueOf(i)\n\tfor i := 0; i < s.Len(); i++ {\n\t\tret = append(ret, s.Index(i).Interface())\n\t}\n\treturn ret\n}", "func (DummyStore) SetSlice(key string, value []interface{}) error {\n\treturn nil\n}", "func ToSliceDomain(sliceGym []Gym) []gyms.Domain {\n\tvar convertedGyms []gyms.Domain\n\tfor _, v := range sliceGym {\n\t\tconvertedGyms = append(convertedGyms, ToDomain(&v))\n\t}\n\treturn convertedGyms\n}", "func MapToSlice(boolMap map[string]bool) []string {\n\tslice := []string{}\n\tfor key := range boolMap {\n\t\tslice = append(slice, key)\n\t}\n\treturn slice\n}", "func (c CAN) ToSlice() []string {\n\tmapBytes, _ := json.Marshal(c.Data)\n\treturn []string{\n\t\tstrconv.FormatUint(uint64(c.Source), 10),\n\t\tstrconv.FormatUint(uint64(c.ID), 10),\n\t\tstrconv.FormatBool(c.RTR),\n\t\tstrconv.FormatUint(c.Timestamp, 10),\n\t\tstring(mapBytes),\n\t}\n}" ]
[ "0.67249084", "0.66531223", "0.66010636", "0.6582087", "0.6561404", "0.6293133", "0.6234093", "0.6183588", "0.615653", "0.6111297", "0.6103662", "0.6076562", "0.6037316", "0.60323817", "0.5993712", "0.5896494", "0.5833062", "0.5789647", "0.5766862", "0.57595253", "0.5736894", "0.57355994", "0.5724054", "0.5719668", "0.5715091", "0.5680518", "0.5655228", "0.5619741", "0.5565352", "0.55653197", "0.5555251", "0.55419916", "0.5535731", "0.5506154", "0.54811406", "0.5457601", "0.54560876", "0.5448304", "0.5430591", "0.5411327", "0.5410729", "0.53955394", "0.53926015", "0.53621566", "0.53509086", "0.5344362", "0.5341599", "0.5335939", "0.5332058", "0.5330243", "0.53208584", "0.5298335", "0.52881175", "0.5283855", "0.5271921", "0.52705", "0.5248314", "0.5233041", "0.52322704", "0.51988256", "0.51983994", "0.5195259", "0.51830757", "0.5157765", "0.5143509", "0.5132337", "0.5111126", "0.5107146", "0.5103501", "0.509931", "0.50952655", "0.5091583", "0.5085667", "0.5080325", "0.50788957", "0.50754476", "0.50585216", "0.50497794", "0.5040357", "0.5018911", "0.50101876", "0.49902916", "0.49823812", "0.49816778", "0.4978329", "0.4965884", "0.49598986", "0.4959315", "0.49509746", "0.49420443", "0.49401364", "0.49366695", "0.49308324", "0.49283051", "0.4927442", "0.49270096", "0.49217874", "0.49216655", "0.49189416", "0.4913301" ]
0.7821475
0
reads a bulk reply (i.e $5\r\nhello)
func readBulk(reader *bufio.Reader, head string) ([]byte, error) { var err error var data []byte if head == "" { head, err = reader.ReadString('\n') if err != nil { return nil, err } } switch head[0] { case ':': data = []byte(strings.TrimSpace(head[1:])) case '$': size, err := strconv.Atoi(strings.TrimSpace(head[1:])) if err != nil { return nil, err } if size == -1 { return nil, doesNotExist } lr := io.LimitReader(reader, int64(size)) data, err = ioutil.ReadAll(lr) if err == nil { // read end of line _, err = reader.ReadString('\n') } default: return nil, redisError("Expecting Prefix '$' or ':'") } return data, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func readBody(msg []byte, state *readState) error {\n\tline := msg[0 : len(msg)-2]\n\tvar err error\n\tif line[0] == '$' {\n\t\t// bulk reply\n\t\tstate.bulkLen, err = strconv.ParseInt(string(line[1:]), 10, 64)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"protocol error: \" + string(msg))\n\t\t}\n\t\tif state.bulkLen <= 0 { // null bulk in multi bulks\n\t\t\tstate.args = append(state.args, []byte{})\n\t\t\tstate.bulkLen = 0\n\t\t}\n\t} else {\n\t\tstate.args = append(state.args, line)\n\t}\n\treturn nil\n}", "func readReply(command int, conn *UniqueConnection) (interface{}, error) {\n\tduration := time.Second *10\n\ttimeNow := time.Now()\n\terr := conn.Connection.SetReadDeadline(timeNow.Add(duration))\n\tif err != nil {\n\t\tTimeEncodedPrint(\"Cant set read timeout\", err.Error())\n\t\treturn nil, err\n\t}\n\tlength := int32(0)\n\terr = binary.Read(conn.Connection, binary.LittleEndian, &length)\n\tif DEBUG_READING_MESSAGE {\n\t\tfmt.Println(\"TRYING TO READ MESSAGE LENGTH => \", length, \" ERROR: \", err)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif BYPASS_CONNECTION_SERVER {\n\t\tfromValue := int64(0)\n\t\terr = binary.Read(conn.Connection, binary.LittleEndian, &fromValue)\n\t\tif DEBUG_READING_MESSAGE {\n\t\t\tfmt.Println(\"Trying to read extra 8 bytes:\" , fromValue, \" PROBLEM: \", err)\n\t\t}\n\t\tif (fromValue != conn.Identifier) {\n\t\t\tif DEBUG_READING_MESSAGE {\n\t\t\t\tfmt.Println(\"Ignore this message\")\n\t\t\t}\t\t\n\t\t\t// ignore this message\n\t\t\trbuf := make([]byte, length)\n\t\t\tio.ReadFull(conn.Connection, rbuf)\n\t\t\treturn nil, nil\n\t\t}\n\t\t\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlength = length - 8\n\t}\n\n\trbuf := make([]byte, length)\n\tn, err := io.ReadFull(conn.Connection, rbuf)\n\tif int32(n) < length {\n\t\treturn nil, errors.New(\"Corrupted message\")\n\t}\n\tcmd := int(rbuf[0])\n\tif (cmd != command) {\n\t\tfmt.Println(\"Message not match\", command, rbuf)\n\t\tmessage := fmt.Sprintf(\"Message not match: %v\", rbuf)\n\t\treturn nil, errors.New(message)\n\t}\n\tswitch cmd {\n\tcase S2C_HelloInfoResult_CMD:\n\t\tres := &Auth_S2C.HelloInfoResult{}\n\t\terr := proto.Unmarshal(rbuf[1:], res)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t} else {\n\t\t\treturn res, nil\n\t\t}\n\n\tcase S2C_LoginUserInfo_CMD:\n\t\tres := &Auth_S2C.LoginUserInfo{}\n\t\terr := proto.Unmarshal(rbuf[1:], res)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t} else {\n\t\t\treturn res, nil\n\t\t}\n\t\n\tcase ERROR_ErrorInfo_CMD:\n\t\tres := &Auth_S2C.ErrorInfo{}\n\t\terr := proto.Unmarshal(rbuf[1:], res)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tmsg := fmt.Sprint(\"Server returns error: \")\n\t\treturn res, errors.New(msg) \n\tdefault:\n\t\tlog.Fatal(\"Unexpected CMD: \", cmd)\n\t}\n\treturn nil, nil\n}", "func readMultiBulk(br *bufio.Reader) ([][]byte, error) {\n\tcount, err := readInt(br)\n\tswitch {\n\tcase err != nil:\n\t\treturn nil, err\n\tcase count < 0:\n\t\treturn nil, PROTOCOL_ERROR\n\t}\n\n\tdata := make([][]byte, 0, count)\n\tfor count > 0 {\n\t\tf, err := br.ReadByte()\n\t\tvar b []byte\n\t\tswitch f {\n\t\tcase '$':\n\t\t\tb, err = readBulk(br)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tcase ':':\n\t\t\t// coerce an integer into mere bytes\n\t\t\tb, err = readLine(br)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tdefault:\n\t\t\treturn nil, PROTOCOL_ERROR\n\t\t}\n\t\tdata = append(data, b)\n\t\tcount--\n\t}\n\n\treturn data, nil\n}", "func readFromServer(conn net.Conn) {\n for {\n message, err := bufio.NewReader(conn).ReadString('\\n')\n \n if err != nil {\n fmt.Println(\"Server down:\", err)\n return\n }\n \n message = strings.Trim(string(message), \"\\n\")\n \n fmt.Println(\"\\r<<\", string(message))\n }\n}", "func ReceiveReadStrMsgResponse(n *net_node.Node, connection net.Conn) {\n\t// Get the filename\n\tfile_name_buff := make([]byte, 100)\n\tconnection.Read(file_name_buff)\n\tfilename := strings.Trim(string(file_name_buff), \" \")\n\tn.Files[filename].NumAckReading += 1\n}", "func (m *MockLibvirt) reply(buf []byte) []byte {\n\tatomic.AddUint32(&m.serial, 1)\n\tbinary.BigEndian.PutUint32(buf[20:24], m.serial)\n\n\treturn buf\n}", "func readBody(c *Connection, l int) ([]uint8, error) {\n\tb := make([]byte, l)\n\tc.setReadDeadline()\n\tn, e := io.ReadFull(c.rdr, b)\n\tif n < l && n != 0 { // Short read, e is ErrUnexpectedEOF\n\t\tc.log(\"SHORT READ\", n, l, e)\n\t\treturn b[0 : n-1], e\n\t}\n\tif c.checkReadError(e) != nil { // Other erors\n\t\treturn b, e\n\t}\n\tc.setReadDeadline()\n\t_, _ = c.rdr.ReadByte() // trailing NUL\n\tif c.checkReadError(e) != nil { // Other erors\n\t\treturn b, e\n\t}\n\treturn b, e\n}", "func ReplyDataResponse() *Reply { return &Reply{354, []string{\"End data with <CR><LF>.<CR><LF>\"}, nil} }", "func execmReaderReadResponse(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret, ret1, ret2 := args[0].(*textproto.Reader).ReadResponse(args[1].(int))\n\tp.Ret(2, ret, ret1, ret2)\n}", "func reader(r io.Reader) {\n\tbuf := make([]byte, 1024)\n\tfor {\n\t\tn, err := r.Read(buf[:])\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tprintln(\"Client got:\", string(buf[0:n]))\n\t}\n}", "func (c *connection) parseResponse() ([]string, error) {\n\treader := bufio.NewReader(c.c)\n\tline, _, _ := reader.ReadLine()\n\n\tswitch string(line) {\n\tcase replyError:\n\t\treturn nil, fmt.Errorf(\"some error\")\n\tcase replyOK:\n\t\treturn nil, nil\n\tcase replyValues:\n\t\t// reading next line containing number of values\n\t\tvalues, _, err := reader.ReadLine()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error reading from response: %v\", err)\n\t\t}\n\t\tvaluesNumber, _ := strconv.Atoi(string(values))\n\n\t\tresult := make([]string, valuesNumber)\n\t\tfor i := 0; i < valuesNumber; i++ {\n\t\t\tvalue, err := c.readValue(reader)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tresult[i] = string(value)\n\t\t}\n\n\t\treturn result, nil\n\tcase replyNotFound:\n\t\treturn nil, ErrNotFound\n\tcase replyAuthRequired:\n\t\treturn nil, ErrAuthRequired\n\tcase replyBadFormat:\n\t\treturn nil, ErrBadFormat\n\tdefault:\n\t\treturn nil, ErrServer\n\t}\n}", "func readBulk(br *bufio.Reader) ([]byte, error) {\n\tsize, err := readInt(br)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif size < 0 {\n\t\treturn nil, nil\n\t}\n\n\tdata := make([]byte, size+2)\n\t_, err = readFull(br, data)\n\n\tswitch {\n\tcase err != nil:\n\t\treturn nil, err\n\tcase data[size] != '\\r':\n\t\treturn nil, PROTOCOL_ERROR\n\tcase data[size+1] != '\\n':\n\t\treturn nil, PROTOCOL_ERROR\n\t}\n\n\treturn data[:size], nil\n}", "func newReadReply(data []byte, err error) reply {\n\treturn reply{\n\t\trepType: repRead,\n\t\tdata: data,\n\t\terr: err,\n\t}\n}", "func readResonse() (string, error) {\n\treader := bufio.NewReader(os.Stdin)\n\ttext, err := reader.ReadString('\\n')\n\n\ttext = strings.Replace(text, \"\\n\", \"\", -1)\n\treturn text, err\n}", "func sendAndGetOneLine(conn *Conn, command string) string {\n\tconn.WriteAndFlushString(command)\n\tline, _, _ := conn.bufReader.ReadLine()\n\tres := string(line)\n\tfmt.Printf(\"res : %s\\n\", res)\n\treturn res\n}", "func (p defaultReadParser) Read() ([]byte, error) {\n\tl := 0\n\tresponseLengthBuf := make([]byte, 4)\n\tfor {\n\t\tif p.timeout > 0 {\n\t\t\tp.broker.conn.SetReadDeadline(time.Now().Add(time.Duration(p.timeout) * time.Millisecond))\n\t\t}\n\t\tlength, err := p.broker.conn.Read(responseLengthBuf[l:])\n\t\tif err != nil {\n\t\t\tp.broker.Close()\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif length+l == 4 {\n\t\t\tbreak\n\t\t}\n\t\tl += length\n\t}\n\tresponseLength := int(binary.BigEndian.Uint32(responseLengthBuf))\n\tglog.V(10).Infof(\"response length in header: %d\", responseLength+4)\n\tresp := make([]byte, 4+responseLength)\n\n\treadLength := 0\n\tfor {\n\t\tif p.timeout > 0 {\n\t\t\tp.broker.conn.SetReadDeadline(time.Now().Add(time.Duration(p.timeout) * time.Millisecond))\n\t\t}\n\t\tlength, err := p.broker.conn.Read(resp[4+readLength:])\n\t\tif err != nil {\n\t\t\tp.broker.Close()\n\t\t\treturn nil, err\n\t\t}\n\n\t\treadLength += length\n\t\tif readLength > responseLength {\n\t\t\treturn nil, errors.New(\"fetch more data than needed while read response\")\n\t\t}\n\t\tif readLength == responseLength {\n\t\t\tbreak\n\t\t}\n\t}\n\tcopy(resp[0:4], responseLengthBuf)\n\tif glog.V(10) {\n\t\tglog.Infof(\"response length: %d. CorrelationID: %d\", len(resp), binary.BigEndian.Uint32(resp[4:]))\n\t}\n\treturn resp, nil\n}", "func readMsg(br *bufio.Reader) (byte, [][]byte, error) {\n\tvar b []byte\n\tvar data [][]byte\n\tflag, err := br.ReadByte()\n\n\tswitch flag {\n\tcase '+', '-', ':':\n\t\tb, err = readLine(br)\n\t\tdata = [][]byte{b}\n\tcase '$':\n\t\tb, err = readBulk(br)\n\t\tdata = [][]byte{b}\n\tcase '*':\n\t\tdata, err = readMultiBulk(br)\n\tdefault:\n\t\terr = PROTOCOL_ERROR\n\t}\n\n\treturn flag, data, err\n}", "func (r *msgReader) readString(countI32 int32) string {\n\tif r.err != nil {\n\t\treturn \"\"\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 \"\"\n\t}\n\n\ts := string(r.msgBody[r.rp : r.rp+count])\n\tr.rp += count\n\n\tif r.shouldLog(LogLevelTrace) {\n\t\tr.log(LogLevelTrace, \"msgReader.readString\", \"value\", s, \"msgType\", r.msgType, \"rp\", r.rp)\n\t}\n\n\treturn s\n}", "func (c *Client) readResponse(conn net.Conn) ([]byte, error) {\n\tif c.Timeout > 0 {\n\t\t_ = conn.SetReadDeadline(time.Now().Add(c.Timeout))\n\t}\n\n\tproto := \"udp\"\n\tif _, ok := conn.(*net.TCPConn); ok {\n\t\tproto = \"tcp\"\n\t}\n\n\tif proto == \"udp\" {\n\t\tbufSize := c.UDPSize\n\t\tif bufSize == 0 {\n\t\t\tbufSize = dns.MinMsgSize\n\t\t}\n\t\tresponse := make([]byte, bufSize)\n\t\tn, err := conn.Read(response)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn response[:n], nil\n\t}\n\n\t// If we got here, this is a TCP connection\n\t// so we should read a 2-byte prefix first\n\treturn readPrefixed(conn)\n}", "func (c *Client) readMsg(terminator string) (string, error) {\n\tconst BuffSize int = 1024\n\n\tmsg := \"\"\n\tdata := make([]byte, BuffSize)\n\n\tvar err error\n\tvar read int\n\tfor err == nil && !strings.HasSuffix(msg, terminator) {\n\t\tread, err = c.connection.Read(data)\n\t\tmsg += string(data[:read])\n\t}\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn msg, nil\n}", "func (c *Client) Retr(msg int) (m *mail.Message, err error) {\n\tif _, err = c.Cmd(\"%s %d\\r\\n\", RETR, msg); err != nil {\n\t\treturn\n\t}\n\n\tm, err = mail.ReadMessage(c.r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// mail.ReadMessage does not consume the message end dot in the buffer\n\t// so we must move the buffer along. Need to find a better way of\n\t// doing this.\n\tline, err := c.ReadLine()\n\tif err != nil {\n\t\treturn\n\t}\n\tif line != \".\" {\n\t\tif err = c.r.UnreadByte(); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func ReadLoop(d io.Reader) {\n\tfor {\n\t\tbuffer := make([]byte, goproxy.MaxTransmissionBytes)\n\t\t_, err := d.Read(buffer)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ReadLoop Read error:\", err)\n\t\t\treturn\n\t\t}\n\t\tbuffer = bytes.Trim(buffer, \"\\x00\")\n\t\tif len(buffer) > 300 {\n\t\t\tfmt.Println(\"ReadLoop Message from DataChannel:\", counter, string(buffer[:300]))\n\t\t\tfmt.Println(\"ReadLoop Message from DataChannel Len:\", counter, len(buffer))\n\t\t} else {\n\t\t\tfmt.Println(\"ReadLoop Message from DataChannel:\", counter, string(buffer))\n\t\t}\n\t\tcounter++\n\t\tgo sendResponse(buffer)\n\t}\n}", "func (cPtr *Client) read(conn net.Conn) error {\n\tvar (\n\t\tbuf json.RawMessage\n\t\tdec = json.NewDecoder(conn)\n\t)\n\treadMessage := func() (rs []*jsonrpcMsg, err error) {\n\t\tbuf = buf[:0]\n\t\tif err = decPtr.Decode(&buf); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif isBatch(buf) {\n\t\t\terr = json.Unmarshal(buf, &rs)\n\t\t} else {\n\t\t\trs = make([]*jsonrpcMsg, 1)\n\t\t\terr = json.Unmarshal(buf, &rs[0])\n\t\t}\n\t\treturn rs, err\n\t}\n\n\tfor {\n\t\tresp, err := readMessage()\n\t\tif err != nil {\n\t\t\tcPtr.readErr <- err\n\t\t\treturn err\n\t\t}\n\t\tcPtr.readResp <- resp\n\t}\n}", "func (u UnixSocketServer)readCommand(connection net.Conn){\n\tbuff:=make([]byte, 1024)\n\n\tdefer connection.Close()\t//\tclose connection on error\n\n\tfor{\n\t\tif size,err := connection.Read(buff);err == nil{\t//\tread message\n\t\tif size > 1{\n\t\t\tif data := utility.NewNotification(buff[:size]);data.Err == nil{\n\t\t\t\tconnection.Write([]byte(u.HandleReceive(data)))\t\t//send callback result\n\t\t\t}else{\n\t\t\t\tconnection.Write([]byte(data.Err.Error()+\"\\n\"))\t//\tresponse if error\n\t\t\t}\n\t\t}else{\n\t\t\tcontinue\n\t\t}\n\t\t}else{\n\t\t\tlog.Println(\"Error, incorrect read from unix domain socket, closing connection\")\n\t\t\treturn\n\t\t}\n\t}\n\n}", "func fetchData(r reader) error {\n\tfmt.Printf(\"type %T\\n\", r)\n\tdata := make([]byte, 50)\n\tlen, err := r.read(data)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(string(data[:len]))\n\treturn nil\n\n}", "func (i *Client) read() error {\n\tr := bufio.NewReader(i.conn)\n\ttp := textproto.NewReader(r)\n\n\tfor {\n\t\tl, err := tp.ReadLine()\n\t\tswitch err {\n\t\tcase io.EOF:\n\t\t\tcontinue\n\t\tcase nil:\n\t\t\tev, err := parseLine(l)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ti.events <- ev\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"Error reading from server: %s\", err)\n\t\t}\n\t}\n}", "func (s *BaseEvent) readReply( conn net.Conn ) (int,error) {\n reply,err := UnSerialiseFromSocket( conn, true )\n if err != nil { Log.Print( \"WARN readReply reply:\", reply, \" err:\", err ) }\n if err != nil { return 0, err }\n\n retVal := 1\n if reply.BExpectReply() { retVal++ }\n return retVal,nil\n}", "func (conn *Conn) recv() {\n\tfor {\n\t\ts, err := conn.io.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlogging.Error(\"irc.recv(): %s\", err.Error())\n\t\t\tconn.shutdown()\n\t\t\treturn\n\t\t}\n\t\ts = strings.Trim(s, \"\\r\\n\")\n\t\tlogging.Debug(\"<- %s\", s)\n\n\t\tif line := parseLine(s); line != nil {\n\t\t\tline.Time = time.Now()\n\t\t\tconn.in <- line\n\t\t} else {\n\t\t\tlogging.Warn(\"irc.recv(): problems parsing line:\\n %s\", s)\n\t\t}\n\t}\n}", "func (s *Server) readAndEcho(buf []byte) (error, error) {\n\tinLen, cm, addr, err := s.readPacket(buf)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading from UDP: %v\", err), err\n\t}\n\n\tn, err := s.writePacket(buf[:inLen], cm, addr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error writing to UDP: %v\", err), err\n\t}\n\n\tif n < inLen {\n\t\ts.l.Warningf(\"Reply truncated! Got %d bytes but only sent %d bytes\", inLen, n)\n\t}\n\n\treturn nil, nil\n}", "func (r *Reader) readPacket() ([]byte, error) {\n\tfor {\n\t\ts, err := r.Reader.ReadLine()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t} else if len(s) == 0 || s[len(s)-1] != lineDelim {\n\t\t\treturn nil, errors.New(\"invalid packet delimiter\")\n\t\t}\n\t\tif len(s) > 1 {\n\t\t\treturn s, nil\n\t\t}\n\t\t// clients may send message containing only 0x0a byte to keep connection alive\n\t\tif r.OnKeepAlive != nil {\n\t\t\tif err := r.OnKeepAlive(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *conn) Receive() (res []bytes.Buffer, err error) {\n\tvar bufArray = []bytes.Buffer{} //make([]bytes.Buffer,5)\n\n\tfor {\n\t\tvar sizebuf bytes.Buffer\n\t\t//read size\n\t\tfor b, er := c.reader.ReadByte(); b != '\\n'; b, er = c.reader.ReadByte() {\n\t\t\tif er != nil {\n\t\t\t\tfmt.Printf(\"%v\\n\", er)\n\t\t\t\treturn nil, er\n\t\t\t}\n\t\t\tif b != '\\r' {\n\t\t\t\tsizebuf.WriteByte(b)\n\t\t\t}\n\t\t}\n\t\t//end of packet\n\t\tif sizebuf.Len() == 0 {\n\t\t\treturn bufArray[0:], nil\n\t\t}\n\n\t\tsize, er := strconv.Atoi(sizebuf.String())\n\t\tif er != nil {\n\t\t\treturn nil, er\n\t\t}\n\n\t\tvar dataBuf bytes.Buffer\n\t\terr := readFully(c.reader, size, &dataBuf)\n\t\tif err != nil {\n\t\t\tc.err = err\n\t\t\treturn nil, err\n\t\t}\n\t\t//read \\r\\n\n\t\tfor b, er := c.reader.ReadByte(); b != '\\n'; b, er = c.reader.ReadByte() {\n\t\t\tif er != nil {\n\t\t\t\tfmt.Printf(\"%v\\n\", er)\n\t\t\t}\n\t\t}\n\t\tbufArray = append(bufArray, dataBuf)\n\t}\n\n\t//never execute here\n\tfmt.Printf(\"buf size:%d\\n\", len(bufArray))\n\treturn bufArray[0:], nil\n}", "func (th *VWClient) ask(waitResponse bool, requests ...string) ([]string, error) {\n\tsize := len(requests)\n\tresponses := make([]string, size)\n\n\tdata := []byte(strings.Join(requests, \"\\n\"))\n\tdata = append(data, endOfLine)\n\n\tconn, err := th.Pool.Get()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get connection from the pool: %s\", err)\n\t}\n\t// this doesn't close the underlying connection instead it's putting it back to the pool\n\tdefer conn.Close()\n\n\tif _, err := conn.Write(data); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to write to connection: %s\", err)\n\t}\n\n\tif !waitResponse {\n\t\treturn nil, nil\n\t}\n\n\treader := bufio.NewReader(conn)\n\tfor i := 0; i < size; i++ {\n\t\tres, err := reader.ReadString('\\n')\n\t\tif err != nil && err.Error() != \"EOF\" {\n\t\t\treturn responses, fmt.Errorf(\"failed to read response: %s\", err)\n\t\t}\n\n\t\tresponses[i] = res\n\t}\n\n\treturn responses, nil\n}", "func (s *server) readCommand(client *client) ([]byte, error) {\n\t//var input string\n\tvar err error\n\tvar bs []byte\n\t// In command state, stop reading at line breaks\n\tbs, err = client.bufin.ReadSlice('\\n')\n\tif err != nil {\n\t\treturn bs, err\n\t} else if bytes.HasSuffix(bs, []byte(commandSuffix)) {\n\t\treturn bs[:len(bs)-2], err\n\t}\n\treturn bs[:len(bs)-1], err\n}", "func readrs() []rune {\n\treturn []rune(reads())\n}", "func readrs() []rune {\n\treturn []rune(reads())\n}", "func (recv *receiver) readCommand() (cmd *Command, err error) {\n\trecv.buff.Reset()\n\n\tcmd = newCommand()\n\n\tfor {\n\t\trecv.data = recv.data[0:]\n\t\tn, err := recv.conn.Read(recv.data)\n\t\tif n > 0 {\n\t\t\t_, _ = recv.buff.Write(recv.data[:n])\n\t\t}\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\terr = fmt.Errorf(\"smtp: recv: readCommand: \" + err.Error())\n\t\t\treturn nil, err\n\t\t}\n\t\tif n == cap(recv.data) {\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\terr = cmd.unpack(recv.buff.Bytes())\n\tif err != nil {\n\t\terr = fmt.Errorf(\"smtp: cmd.unpack: \" + err.Error())\n\t\treturn nil, err\n\t}\n\n\treturn cmd, nil\n}", "func read(c net.Conn) ([]byte, error) {\n\tvar msgSize, err = messageLength(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmsgBuf := make([]byte, msgSize)\n\t_, err = io.ReadFull(c, msgBuf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn msgBuf, nil\n}", "func readersExample() {\n r := strings.NewReader(\"Hello, Reader!\")\n\n b := make([]byte, 8)\n\n for {\n n, err := r.Read(b)\n fmt.Printf(\"n = %v err = %v b = %v\\n\", n, err, b)\n fmt.Printf(\"b[:n] = %q\\n\", b[:n])\n if err == io.EOF {\n break\n }\n }\n}", "func (db *GeoDB) readReplies(qCount int, conn redis.Conn) ([]interface{}, error) {\n\tallRes := make([]interface{}, 0)\n\n\tfor i := 0; i < qCount; i++ {\n\t\tres, err := conn.Receive()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tallRes = append(allRes, res.([]interface{})...)\n\t}\n\n\treturn allRes, nil\n}", "func getCommands(c net.Conn) {\n\tfor {\n\t\t// reading from console\n\t\tr := bufio.NewReader(os.Stdin)\n\t\tt, err := r.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tpanic(\"Could not read input! \" + err.Error())\n\t\t}\n\t\t// exit if \"quit\" command was entered\n\t\tif strings.Contains(t, \"quit\") {\n\t\t\tos.Exit(0)\n\t\t}\n\t\t// send message action\n\t\tif strings.Contains(t, \"send\") {\n\t\t\tvar addr int64\n\t\t\t// split command by space symbol\n\t\t\tsendString := strings.Split(t, \" \")\n\t\t\t// asterisk means broadcast message\n\t\t\tif sendString[1] == \"*\" {\n\t\t\t\taddr = 255\n\t\t\t} else {\n\t\t\t\taddr, err = strconv.ParseInt(sendString[1], 10, 8)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"Could not parse address tag: \" + err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// form message body\n\t\t\tmessage := messages.Message{\n\t\t\t\tAction: 2,\n\t\t\t\tFrom: myTag,\n\t\t\t\tText: strings.Split(t, \"\\\"\")[1],\n\t\t\t\tAddress: byte(addr),\n\t\t\t}\n\t\t\t// send message and receive acknowledge\n\t\t\tm, err := sendAndReceive(c, message)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tif m.Action == 255 {\n\t\t\t\tfmt.Println(\"Successfully sent!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfmt.Println(\"Server did not accept message!\")\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func (client *Client) Read() {\n\tfor {\n\t\t// reads the string\n\t\tline, err := client.reader.ReadString('\\n')\n\t\t// handles error\n\t\tif err != nil {\n\t\t\tfmt.Println(\"A connection closed\")\n\t\t\treturn\n\t\t}\n\t\t// publishes message on its incoming channel\n\t\tclient.incoming <- line\n\t}\n}", "func (c *Conn) readAuthResp() string {\n\tc.conn.SetReadDeadline(time.Now().Add(c.Config.Limits.CmdInput))\n\tc.lr.N = c.Config.Limits.AuthInput\n\tline, err := c.rdr.ReadLine()\n\tif err != nil || c.lr.N == 0 {\n\t\tc.state = sAbort\n\t\tc.log(\n\t\t\t\"!\",\n\t\t\t\"auth input abort %s err: %v\",\n\t\t\tfmtBytesLeft(\n\t\t\t\tc.Config.Limits.AuthInput,\n\t\t\t\tc.lr.N,\n\t\t\t),\n\t\t\terr,\n\t\t)\n\t\treturn \"\"\n\t}\n\tc.log(\"r\", line)\n\treturn line\n}", "func (cr *ClientResponse) MultiResp() []byte {\n\treturn cr.mokBuf[:cr.nmok]\n}", "func (client *Client) Reply(conn net.Conn) ([]byte, int, string, error) {\n\tvar buffer [1024]byte\n\tvar addr string\n\tvar proxyType int\n\n\tn, err := conn.Read(buffer[:])\n\tif err != nil {\n\t\treturn nil, 0, \"\", err\n\t}\n\n\t// 去掉socks5之外的支持\n\t// select a matched proxy type\n\tinstances := []ProxyInterface{&Socks5Client{}}\n\tvar matchedInstance ProxyInterface = nil\n\tfor _, proxyInstance := range instances {\n\t\tif proxyInstance.Trigger(buffer[:n]) {\n\t\t\tmatchedInstance = proxyInstance\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif matchedInstance == nil {\n\t\treturn nil, 0, \"\", errors.New(\"only socks5 proxy\")\n\t}\n\n\t// set address and type\n\tif proxyAddr, err := matchedInstance.ParseHeader(conn, buffer[:n]); err != nil {\n\t\treturn nil, 0, \"\", err\n\t} else {\n\t\tproxyType = matchedInstance.ProxyType()\n\t\taddr = proxyAddr\n\t}\n\t// set data sent in establish step.\n\tif firstSendData, err := matchedInstance.EstablishData(buffer[:n]); err != nil {\n\t\treturn nil, 0, \"\", err\n\t} else {\n\t\t// firstSendData can be nil, which means there is no data to be send during connection establishing.\n\t\treturn firstSendData, proxyType, addr, nil\n\t}\n}", "func (c *Client) next() (rsp *Response, err error) {\n\traw, err := c.r.Next()\n\tif err == nil {\n\t\trsp, err = raw.Parse()\n\t}\n\treturn\n}", "func readLoop(lconn, rconn *net.UDPConn, ua *net.UDPAddr) error {\n\tfor {\n\t\tpkt := make([]byte, 1500)\n\t\tn, err := rconn.Read(pkt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpkt = pkt[:n]\n\t\tif _, err := lconn.WriteTo(pkt, ua); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}", "func readLoop(r server.Request, s client.Stream) error {\n\t// request to backend server\n\treq := s.Request()\n\n\tfor {\n\t\t// get data from client\n\t\t// no need to decode it\n\t\tbody, err := r.Read()\n\t\tif err == io.EOF {\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\t// get the header from client\n\t\thdr := r.Header()\n\t\tmsg := &codec.Message{\n\t\t\tType: codec.Request,\n\t\t\tHeader: hdr,\n\t\t\tBody: body,\n\t\t}\n\n\t\t// write the raw request\n\t\terr = req.Codec().Write(msg, nil)\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (conn *Conn) recv() {\n\tfor {\n\t\ts, err := conn.io.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\tlogging.Error(\"irc.recv(): %s\", err.Error())\n\t\t\t}\n\t\t\t// We can't defer this, because Close() waits for it.\n\t\t\tconn.wg.Done()\n\t\t\tconn.Close()\n\t\t\treturn\n\t\t}\n\t\ts = strings.Trim(s, \"\\r\\n\")\n\t\tlogging.Debug(\"<- %s\", s)\n\n\t\tif line := ParseLine(s); line != nil {\n\t\t\tline.Time = time.Now()\n\t\t\tconn.in <- line\n\t\t} else {\n\t\t\tlogging.Warn(\"irc.recv(): problems parsing line:\\n %s\", s)\n\t\t}\n\t}\n}", "func (client *Client) receive() {\n\tbuff := make([]byte, 4096)\n\tfor {\n\t\t_, err := client.Conn.Read(buff)\n\t\tcheckError(err)\n\t\tfmt.Printf(\"%v: %s\", client, string(bytes.Trim(buff, \"\\x00\")))\n\t}\n}", "func (s *service) readPump(conn net.Conn, quit chan struct{}) {\n\tvar buf = bufio.NewReader(conn)\n\tfor {\n\t\tconn.SetReadDeadline(time.Now().Add(10 * time.Second))\n\t\tmsgBytes, err := buf.ReadBytes(MsgDelim)\n\t\tconn.SetReadDeadline(time.Time{})\n\t\tif err != nil {\n\t\t\tif s.destroyed || s.restarted {\n\t\t\t\ts.logger.WithError(err).Warnf(\"read\")\n\t\t\t} else {\n\t\t\t\ts.logger.WithError(err).Errorf(\"read\")\n\t\t\t}\n\t\t\tclose(quit)\n\t\t\ts.connect()\n\t\t\treturn\n\t\t}\n\t\ts.lastMsgRead = time.Now()\n\t\tmsg := types.Message{}\n\t\terr = json.Unmarshal(msgBytes[:len(msgBytes)-1], &msg)\n\t\tif err != nil {\n\t\t\ts.logger.WithError(err).Errorf(\"unmarshall %s\", string(msgBytes[:len(msgBytes)-1]))\n\t\t\tcontinue\n\t\t}\n\n\t\tif msg.RouterHeader == constants.RouterHeader.Heartbeat {\n\t\t\tcontinue\n\t\t} else if msg.RouterHeader == constants.RouterHeader.Disconnect {\n\t\t\ts.logger.Info(\"got disconnect request\")\n\t\t\ts.restarted = true\n\t\t\tclose(quit)\n\t\t\ts.connect()\n\t\t\treturn\n\t\t} else {\n\t\t\ts.msgHandler(msg, s.ID, s.Name)\n\t\t}\n\t}\n}", "func TestBatchReply(t *testing.T) {\n\tdefer leaktest.Check(t)()\n\n\tcpipe, spipe := channel.Direct()\n\tsrv := NewServer(hmap{\n\t\t\"test\": Handler(func(_ context.Context, req *Request) (any, error) {\n\t\t\treturn req.Method() + \" OK\", nil\n\t\t}),\n\t}, nil).Start(spipe)\n\tdefer func() { cpipe.Close(); srv.Wait() }()\n\n\ttests := []struct {\n\t\tinput, want string\n\t}{\n\t\t// A single-element batch gets returned as a batch.\n\t\t{`[{\"jsonrpc\":\"2.0\", \"id\":1, \"method\":\"test\"}]`,\n\t\t\t`[{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"test OK\"}]`},\n\n\t\t// A single-element non-batch gets returned as a single reply.\n\t\t{`{\"jsonrpc\":\"2.0\", \"id\":2, \"method\":\"test\"}`,\n\t\t\t`{\"jsonrpc\":\"2.0\",\"id\":2,\"result\":\"test OK\"}`},\n\t}\n\tfor _, test := range tests {\n\t\tif err := cpipe.Send([]byte(test.input)); err != nil {\n\t\t\tt.Errorf(\"Send failed: %v\", err)\n\t\t}\n\t\trsp, err := cpipe.Recv()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Recv failed: %v\", err)\n\t\t}\n\t\tif got := string(rsp); got != test.want {\n\t\t\tt.Errorf(\"Batch reply:\\n got %#q\\nwant %#q\", got, test.want)\n\t\t}\n\t}\n}", "func (client *Clienter) Read() {\n\tfor {\n\t\tmessage, err := client.reader.ReadString('\\n')\n\t\t// If read error, send a signal to delete the client and drop the routine.\n\t\tif err != nil {\n\t\t\tclient.connection.Close()\n\t\t\tclient.kvs.delete <- client\n\t\t\tbreak\n\t\t}\n\t\tid := client.cid\n\t\trequest := &Request{\n\t\t\tinput: message,\n\t\t\tcid: id,\n\t\t}\n\t\tclient.kvs.req <- request\n\t}\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 (parser RedisResponseParser) parseArrayResponse(r *bufio.Reader) (common.IResponse, error) {\n\trsp := NewArrayResponse()\n\tline, err := r.ReadString('\\n')\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(line) == 0 {\n\t\treturn nil, fmt.Errorf(\"Empty line\")\n\t}\n\tvar num int\n\n\tif _, err := fmt.Sscanf(line, \"*%d\\r\\n\", &num); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid length for array \", line, err)\n\t}\n\trsp.elems = make([]common.IResponse, num)\n\tfor i := 0; i < num; i += 1 {\n\t\trsp.elems[i], err = parser.GetNextResponse(r)\n\t\t//if rsp.elems[i], err = readArgument(r); err != nil {\n\t\tif err != nil {\n\t\t\tlog.Println(\"Received error \", err)\n\t\t\treturn nil, err\n\t\t}\n\t\t//rsp.AppendArgs(elem.(common.Response))\n\t}\n\treturn rsp, nil\n}", "func (a *AGI) Command(cmd ...string) (resp *Response) {\n\tresp = &Response{}\n\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\n\tcmdString := strings.Join(cmd, \" \") + \"\\n\"\n\t_, err := a.w.Write([]byte(cmdString))\n\tif err != nil {\n\t\tresp.Error = errors.Wrap(err, \"failed to send command\")\n\t\treturn\n\t}\n\n\ts := bufio.NewScanner(a.r)\n\tfor s.Scan() {\n\t\traw := s.Text()\n\t\tif raw == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\t// Parse and store the result code\n\t\tpieces := responseRegex.FindStringSubmatch(raw)\n\t\tif pieces == nil {\n\t\t\tresp.Error = fmt.Errorf(\"failed to parse result: %s\", raw)\n\t\t\treturn\n\t\t}\n\n\t\t// Status code is the first substring\n\t\tresp.Status, err = strconv.Atoi(pieces[1])\n\t\tif err != nil {\n\t\t\tresp.Error = errors.Wrap(err, \"failed to get status code\")\n\t\t\treturn\n\t\t}\n\n\t\t// Result code is the second substring\n\t\tresp.ResultString = pieces[2]\n\t\t// FIXME: DTMF result maybe has \"#\"(35), \"*\" or \"\"(GetData #). But not perfect to just judge by contains string.\n\t\tif resp.ResultString != \"\" && !strings.Contains(resp.ResultString, \"35\") && !strings.Contains(resp.ResultString, \"*\") {\n\t\t\tresp.Result, err = strconv.Atoi(pieces[2])\n\t\t\tif err != nil {\n\t\t\t\tresp.Error = errors.Wrap(err, \"failed to parse status code as an integer\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\n\t\t// Value is the third (and optional) substring\n\t\twrappedVal := strings.TrimSpace(pieces[3])\n\t\tresp.Value = strings.TrimSuffix(strings.TrimPrefix(wrappedVal, \"(\"), \")\")\n\n\t\t// FIXME: handle multiple line return values\n\t\tbreak // nolint\n\t}\n\n\t// If the Status code is not 200, return an error\n\tif resp.Status != 200 {\n\t\tresp.Error = fmt.Errorf(\"Non-200 status code\")\n\t}\n\treturn\n}", "func readLoop(client *Client) {\n\t// Create reader for server data.\n\treader := bufio.NewReader(client.Conn)\n\tfor {\n\t\tselect {\n\t\t// If the client is done, stop the goroutine.\n\t\tcase <-client.Done:\n\t\t\treturn\n\t\t// Loop reads from server and set client to done if a timeout or error is\n\t\t// encountered.\n\t\tdefault:\n\t\t\t// Make sure a message is received in at most three minutes, since we\n\t\t\t// send a ping every two.\n\t\t\tclient.Conn.SetReadDeadline(time.Now().Add(time.Minute * 3))\n\t\t\tmsg, err := reader.ReadString('\\n')\n\t\t\tclient.Conn.SetReadDeadline(time.Time{})\n\t\t\tif err != nil {\n\t\t\t\tLog(client, err.Error())\n\t\t\t\tclose(client.Done)\n\t\t\t} else {\n\t\t\t\tparseMessage(client, msg)\n\t\t\t}\n\t\t}\n\t}\n}", "func readBody(win *acme.Win) ([]byte, error) {\n\tvar body []byte\n\tbuf := make([]byte, 8000)\n\tfor {\n\t\tn, err := win.Read(\"body\", buf)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbody = append(body, buf[0:n]...)\n\t}\n\treturn body, nil\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 res(conn net.Conn){\n reader := bufio.NewReader(conn) // set a new reader for tcp\n // for loop is used for continuos reading from port\n for {\n text,err:=reader.ReadString('\\n')\n if err != nil {\n fmt.Println(\"Client DISCONNECTED\")\n return\n } else {\n fmt.Println(\"text : \" + text) // print the recieved data\n data_to_db <- text\n }\n }\n }", "func (r *resultReader) readSlice(delimeter byte) ([]byte, error) {\n\ts, err := r.client.reader.ReadSlice(delimeter)\n\tif err != nil {\n\t\treturn nil, r.client.handleReadError(err)\n\t}\n\treturn s[:len(s)-1], nil\n}", "func (s *Session) readLines() {\n\tbReader := bufio.NewReader(s.r)\n\tfor {\n\t\tselect {\n\t\tcase <-s.closeChan:\n\t\t\t// close requested, return\n\t\t\treturn\n\n\t\tdefault:\n\t\t\t// read from the reader\n\t\t\tline, err := bReader.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\tlog.Debug(\"VTY connection closed by the remote side.\")\n\t\t\t\t} else {\n\t\t\t\t\terror := fmt.Errorf(\"error by reading from VTY: %s\", err)\n\t\t\t\t\tlog.Error(error)\n\t\t\t\t\ts.errChan <- error\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tstr := strings.Trim(line, \" \\r\\n\")\n\t\t\tlog.Debug(\"CLI: \", str)\n\n\t\t\t// write the read string to the channel\n\t\t\ts.rChan <- str\n\t\t}\n\t}\n}", "func (c *Client) Batch(cmds ...*Cmd) error {\n\t_, err := c.Exec(\"batch\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlines := make([]string, len(cmds)+1)\n\tfor i, c := range cmds {\n\t\tlines[i] = c.String()\n\t}\n\tlines[len(cmds)] = \".\\n\"\n\n\tif err = c.setDeadline(); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err = c.conn.Write([]byte(strings.Join(lines, \"\"))); err != nil {\n\t\treturn err\n\t}\n\n\tif err = c.setDeadline(); err != nil {\n\t\treturn err\n\t}\n\n\tif !c.scanner.Scan() {\n\t\treturn c.scanErr()\n\t}\n\n\tl := c.scanner.Text()\n\tmatches := respRe.FindStringSubmatch(l)\n\tif len(matches) != 3 {\n\t\treturn NewInvalidResponseError(\"batch: invalid matches\", l)\n\t}\n\n\tcnt, err := strconv.Atoi(matches[1])\n\tif err != nil {\n\t\t// This should be impossible given the regexp matched.\n\t\treturn NewInvalidResponseError(\"batch: invalid count\", l)\n\t}\n\n\tif cnt == 0 {\n\t\treturn nil\n\t}\n\n\tif err := c.setDeadline(); err != nil {\n\t\treturn err\n\t}\n\trlines := make([]string, 0, cnt)\n\tfor c.scanner.Scan() && len(rlines) < cnt {\n\t\trlines = append(rlines, c.scanner.Text())\n\t\tif err := c.setDeadline(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(rlines) != cnt {\n\t\t// Short response.\n\t\treturn c.scanErr()\n\t}\n\n\treturn NewError(0-cnt, strings.Join(rlines, \"\\n\"))\n}", "func ConnRead(c *tls.Conn, b []byte) (int, error)", "func (c *StatusResponse) Read(r io.Reader) error {\n\tcount, err := message_fields.ReadByte(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.Lines = make([]string, 0, count)\n\tfor i := 0; i < int(count); i++ {\n\t\ts, err := message_fields.ReadString(r)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.Lines = append(c.Lines, s)\n\t}\n\treturn nil\n}", "func rl(r io.Reader) (string, error) {\n\tretval := make([]byte, 1024)\n\tb := make([]byte, 1)\n\tcur := 0\n\n\tfor b[0] != '\\n' {\n\t\tn, err := r.Read(b)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif n < 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\tretval[cur] = b[0]\n\t\tcur++\n\n\t\tif cur >= cap(retval) {\n\t\t\tnewretval := make([]byte, 2*len(retval))\n\t\t\tcopy(newretval, retval)\n\t\t\tretval = newretval\n\t\t}\n\t}\n\n\treturn string(retval[:cur]), nil\n}", "func (r *RSource) RemoteRead() ([]string, error) {\n\tif r.rClient == nil {\n\t\treturn nil, errors.New(\"No R connection\")\n\t}\n\n\tout, err := r.rClient.Eval(`\n try(as.vector(unlist(nextElem(output_iter), use.names=FALSE)))\n\t`)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tswitch out.(type) {\n\tcase []string:\n\t\treturn out.([]string), nil\n\tcase string:\n\t\treturn nil, EOF\n\n\t}\n\treturn nil, nil\n}", "func (self *ShadowRedisSlave) startReadLoop() {\n\tbuf := make([]byte, 1024*8)\n\n\tfor self.runnable {\n\t\ttime.Sleep(2 * time.Second)\n\t\tn, err := self.conn.Read(buf)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Fail read loop : %v\", err)\n\t\t\tself.Close()\n\t\t\treturn\n\t\t}\n\n\t\tlog.Debugf(\"Got response : [%d] [%s]\", n, string(buf[:n]))\n\n\t\tself.offset += int64(n)\n\t}\n}", "func ReadandSendMessage(message []string) {\n\tlog.Printf(\"Router %s: Decrypting the packet\", selectedRouter.Name)\n\tlength := len(message) - 1\n\tfor i, s := range message {\n\t\ts, err := onions.Decrypt([]byte(s), gcm, nonceSize)\n\t\tmessage[i] = string(s)\n\t\tif err != nil {\n\t\t\t//log.Printf(\"Router %s: Failed to decrypt.Message %s recived\", selectedRouter.Name, message)\n\n\t\t\t//os.Exit(1)\n\t\t}\n\t}\n\n\taddr := message[length]\n\t// token := make([]byte, 32)\n\t// rand.Read(token)\n\t// randomString := string(token)\n\t// message = append(randomString, message)\n\tlog.Printf(\"Router %s: ReRouting the packet to %s\", selectedRouter.Name, addr)\n\tmessage = message[:length]\n\trandom := strconv.Itoa(rand.Int())\n\tencryptedRandom := []string{string(onions.Encrypt([]byte(random), gcm, nonceSize))}\n\n\tmessage = append(encryptedRandom, message...)\n\tSocketClient(message, addr)\n\n}", "func readRequest(reader *bufio.Reader, length int) ([]byte, int, error){\n\tbuffer := []byte(\"\")\n\tvar prev_symbol byte\n\tvar counter = 0\n\tvar token_counter = 0\n\tif length == 0 { return buffer, 0, nil }\n\tfor {\n\t\tread, err := reader.ReadByte()\n\t\tif err != nil {\n\t\t\t//fmt.Println(\"Num: \", counter,\" read: \", read, \" Err: \", err)\n\t\t\treturn buffer, counter, err\n\t\t}\n\t\tbuffer = append(buffer, read)\n\t\tcounter ++\n\t\tif length == -1 || counter - 2 == length {\n\t\t\tif read == '\\n' && prev_symbol == '\\r' {\n\t\t\t\treturn buffer[ : len(buffer) - 2], counter, nil\n\t\t\t} else {\n\t\t\t\tif length != -1 {\n\t\t\t\t\treturn buffer, counter, errors.New(\"Length was achieved, but terminator wasn't met.\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif read != ' ' && length == -1 /* in case of header of unknown length */{\n\t\t\ttoken_counter ++\n\t\t\tif token_counter > MAX_KEY_LENGTH {\n\t\t\t\treturn buffer, counter, errors.New(\"Maximal key length is exceeded.\")\n\t\t\t}\n\t\t} else {\n\t\t\ttoken_counter = 0\n\t\t}\n\t\tprev_symbol = read\n\t}\n}", "func (c *Client) constructResp(conn io.Reader, req *Request) (*Response, error) {\n\t// TODO\n\t// Receive and prase repsonse message\n\tresp := &Response{Header: make(map[string]string)}\n\treader := bufio.NewReaderSize(conn, ClientResponseBufSize)\n\tvar wholeLine []byte\n\tvar lastWait = false\n\tvar step = ResponseStepStatusLine\nLOOP:\n\tfor {\n\t\tif line, isWait, err := reader.ReadLine(); err == nil {\n\t\t\tif !isWait {\n\t\t\t\t// Complete line\n\t\t\t\tif !lastWait {\n\t\t\t\t\twholeLine = line\n\t\t\t\t} else {\n\t\t\t\t\twholeLine = append(wholeLine, line...)\n\t\t\t\t}\n\t\t\t\t// Process the line\n\t\t\t\tswitch step {\n\t\t\t\tcase ResponseStepStatusLine:\n\t\t\t\t\t{\n\t\t\t\t\t\tstatusLineWords := strings.SplitN(string(wholeLine), \" \", 3)\n\t\t\t\t\t\tresp.Proto = statusLineWords[0]\n\t\t\t\t\t\tresp.StatusCode, err = strconv.Atoi(statusLineWords[1])\n\t\t\t\t\t\tresp.Status = statusLineWords[2]\n\t\t\t\t\t\tstep = ResponseStepHeader\n\t\t\t\t\t}\n\t\t\t\tcase ResponseStepHeader:\n\t\t\t\t\t{\n\t\t\t\t\t\tif len(line) != 0 {\n\t\t\t\t\t\t\theaderWords := strings.SplitN(string(wholeLine), \": \", 2)\n\t\t\t\t\t\t\tresp.Header[headerWords[0]] = headerWords[1]\n\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// fmt.Println(resp.Header)\n\t\t\t\t\t\t\tstep = ResponseStepBody\n\t\t\t\t\t\t\tcLenStr, ok := resp.Header[HeaderContentLength]\n\t\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\t\treturn nil, errors.New(\"No Content-Length in Response header\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcLen, _ := strconv.ParseInt(cLenStr, 10, 64)\n\t\t\t\t\t\t\tresp.ContentLength = cLen\n\n\t\t\t\t\t\t\t// Transfer the body to Response\n\t\t\t\t\t\t\tresp.Body = &ResponseReader{\n\t\t\t\t\t\t\t\tc: c,\n\t\t\t\t\t\t\t\tconn: conn,\n\t\t\t\t\t\t\t\thost: req.URL.Host,\n\t\t\t\t\t\t\t\tr: &io.LimitedReader{\n\t\t\t\t\t\t\t\t\tR: reader,\n\t\t\t\t\t\t\t\t\tN: resp.ContentLength,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak LOOP\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase ResponseStepBody:\n\t\t\t\t\t{\n\t\t\t\t\t\tpanic(\"Cannot be here\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\t// Not complete\n\t\t\t\tif !lastWait {\n\t\t\t\t\twholeLine = line\n\t\t\t\t} else {\n\t\t\t\t\twholeLine = append(wholeLine, line...)\n\t\t\t\t}\n\t\t\t}\n\t\t\tlastWait = isWait\n\t\t} else if err == io.EOF {\n\t\t\tbreak\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn resp, nil\n}", "func respondToRaw(sock mangos.Socket) {\n\n\tmsg, err := sock.RecvMsg()\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tlog.Println(string(msg.Body))\n\n}", "func (c *Client) readPump() {\n\tdefer func() {\n\t\tc.conn.Close()\n\t}()\n\tc.conn.SetReadLimit(maxMessageSize)\n\tc.conn.SetReadDeadline(time.Now().Add(pongWait))\n\tc.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })\n\tfor {\n\t\t_, message, err := c.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {\n\t\t\t\tlog.Printf(\"error: %v\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tmessage = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))\n\t}\n}", "func res(conn net.Conn){\r\n reader := bufio.NewReader(conn) // set a new reader for tcp\r\n // for loop is used for continuos reading from port\r\n for {\r\n text,err:=reader.ReadString('\\n')\r\n if err != nil {\r\n fmt.Println(\"Client DISCONNECTED\")\r\n pass <- \"close\" // this will close the writer\r\n return\r\n } else {\r\n fmt.Println(\"text : \" + text) // print the recieved data\r\n }\r\n }\r\n }", "func handleStrings(rw *bufio.ReadWriter) {\r\n\t// Receive a string.\r\n\tlog.Print(\"Receive STRING message:\")\r\n\ts, err := rw.ReadString('\\n')\r\n\tif err != nil {\r\n\t\tlog.Println(\"Cannot read from connection.\\n\", err)\r\n\t}\r\n\ts = strings.Trim(s, \"\\n \")\r\n\tlog.Println(s)\r\n\t_, err = rw.WriteString(\"Thank you.\\n\")\r\n\tif err != nil {\r\n\t\tlog.Println(\"Cannot write to connection.\\n\", err)\r\n\t}\r\n\terr = rw.Flush()\r\n\tif err != nil {\r\n\t\tlog.Println(\"Flush failed.\", err)\r\n\t}\r\n}", "func (u *UnityServer) readMessage() {\n\tfor {\n\t\tdata := make([]byte, 8192)\n\t\tn, err := u.conn.Read(data)\n\t\tif err != nil {\n\t\t\tu.Logger.Errorf(\"Error: Reading socket - %v\", err)\n\t\t\tu.stop <- true\n\t\t\tbreak\n\t\t}\n\t\tu.incoming <- string(data[:n])\n\t}\n}", "func (r *Reply) Bytes() ([]byte, error) {\n\tif r.Type == ErrorReply {\n\t\treturn nil, r.Err\n\t}\n\tif !(r.Type == StatusReply || r.Type == BulkReply) {\n\t\treturn nil, errors.New(\"string value is not available for this reply type\")\n\t}\n\n\treturn r.buf, nil\n}", "func receiveRemoteServerMsgs(conn net.Conn) {\n\tfor {\n\t\tscanner := bufio.NewScanner(conn)\n\t\tfor scanner.Scan() {\n\t\t\tfmt.Print(\"\\r\")\n\t\t\tfmt.Print(scanner.Text() + \"\\n\")\n\t\t\tfmt.Print(\"> \")\n\t\t}\n\t\tif scanner.Err() != nil {\n\t\t\tlog.Printf(\"error: %s\\n\", scanner.Err())\n\t\t\tconn.Close()\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func socketRead(conn net.Conn, code uint){\n\t// read the response from the webserver\n\tfor read {\n\t\tcount, err = con.Read(data)\n\t\tread = (err == nil)\n\t\tif debug{\n\t\t\tfmt.Printf(\"S %s\\n\"string(data[0:count]))\n\t\t}\n\t}\n}", "func (c *Client) read() (Result, error) {\n\theader := make([]byte, 6)\n\t_, err := io.ReadFull(c.serial, header)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuf := make([]byte, header[4]-1)\n\t_, err = io.ReadFull(c.serial, buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := Result(append(header, buf...))\n\n\treturn res, res.CheckChecksum()\n}", "func (recv *receiver) readDATA() (err error) {\n\tfor {\n\t\trecv.data = recv.data[0:]\n\t\tn, err := recv.conn.Read(recv.data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trecv.mail.Data = append(recv.mail.Data, recv.data[:n]...)\n\n\t\tif recv.mail.isTerminated() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tl := len(recv.mail.Data)\n\n\t// Remove the end-of-mail data indicator.\n\trecv.mail.Data = recv.mail.Data[:l-5]\n\n\trecv.mail.seal(recv.clientDomain, recv.clientAddress, recv.localAddress)\n\n\treturn nil\n}", "func (b *Broker) readResponse(conn *net.TCPConn) (uint32, []byte, os.Error) {\n reader := bufio.NewReader(conn)\n length := make([]byte, 4)\n lenRead, err := io.ReadFull(reader, length)\n if err != nil {\n return 0, []byte{}, err\n }\n if lenRead != 4 || lenRead < 0 {\n return 0, []byte{}, os.NewError(\"invalid length of the packet length field\")\n }\n\n expectedLength := binary.BigEndian.Uint32(length)\n messages := make([]byte, expectedLength)\n lenRead, err = io.ReadFull(reader, messages)\n if err != nil {\n return 0, []byte{}, err\n }\n\n if uint32(lenRead) != expectedLength {\n return 0, []byte{}, os.NewError(fmt.Sprintf(\"Fatal Error: Unexpected Length: %d expected: %d\", lenRead, expectedLength))\n }\n\n errorCode := binary.BigEndian.Uint16(messages[0:2])\n if errorCode != 0 {\n return 0, []byte{}, os.NewError(strconv.Uitoa(uint(errorCode)))\n }\n return expectedLength, messages[2:], nil\n}", "func (c *Connection) reply(ctx context.Context) {\n\tdefer func() {\n\t\tc.logger.Infof(\"Replyer exiting for %s\", c.name)\n\t\tc.kill(ctx)\n\t\tc.wg.Done()\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase payload, ok := <-c.repCh:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tn, err := c.conn.Write(payload)\n\t\t\tif err != nil {\n\t\t\t\tc.logger.Infof(\n\t\t\t\t\t\"Client %s cannot write reply: %s\", c.name, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif en := len(payload); en != n {\n\t\t\t\tc.logger.Infof(\n\t\t\t\t\t\"Client %s cannot write reply: written %d instead of %d bytes\",\n\t\t\t\t\tc.name, n, en)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tatomic.AddInt64(&c.numInflight, -1) // one less in flight\n\t\t}\n\t}\n}", "func send(c *Conn, cmd string) (string, error) {\n\t_, err := sendFull(c, []byte(cmd))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t//wait for response\n\tresp, err := c.bufReader.ReadString('\\n')\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn resp, nil\n}", "func (h *RequestHeader) readLoop(r *bufio.Reader, waitForMore bool) error {\n\tn := 1\n\tfor {\n\t\terr := h.tryRead(r, n)\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\t\tif !waitForMore || err != errNeedMore {\n\t\t\th.resetSkipNormalize()\n\t\t\treturn err\n\t\t}\n\t\tn = r.Buffered() + 1\n\t}\n}", "func read(conn net.Conn) (b []byte, err error) {\n\tb, err = bufio.NewReader(conn).ReadBytes(Delimiter)\n\tif err == nil {\n\t\tb = b[:len(b)-1]\n\t}\n\n\treturn\n}", "func read(conn net.Conn) (b []byte, err error) {\n\tb, err = bufio.NewReader(conn).ReadBytes(Delimiter)\n\tif err == nil {\n\t\tb = b[:len(b)-1]\n\t}\n\n\treturn\n}", "func read(conn net.Conn) (b []byte, err error) {\n\tb, err = bufio.NewReader(conn).ReadBytes(Delimiter)\n\tif err == nil {\n\t\tb = b[:len(b)-1]\n\t}\n\n\treturn\n}", "func read(conn net.Conn) (b []byte, err error) {\n\tb, err = bufio.NewReader(conn).ReadBytes(Delimiter)\n\tif err == nil {\n\t\tb = b[:len(b)-1]\n\t}\n\n\treturn\n}", "func read(msg string) string {\n\tfmt.Print(msg)\n\tvar ret, _ = bufio.NewReader(os.Stdin).ReadString('\\n')\n\treturn ret\n}", "func readToCRLF(reader *bufio.Reader) (buffer []byte, err os.Error) {\n\t//\treader := bufio.NewReader(conn);\n\tvar buf []byte\n\tbuf, err = reader.ReadBytes(CR_BYTE)\n\tif err == nil {\n\t\tvar b byte\n\t\tb, err = reader.ReadByte()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif b != LF_BYTE {\n\t\t\terr = os.NewError(\"<BUG> Expecting a Linefeed byte here!\")\n\t\t}\n\t\t//\t\tlog.Println(\"readToCRLF: \", buf);\n\t\tbuffer = buf[0 : len(buf)-1]\n\t}\n\treturn\n}", "func receiveReply(conn *Conn, p *Packet) {\n\treply <- p.Msg\n}", "func (c *AuditClient) getReply(seq uint32) (*syscall.NetlinkMessage, error) {\n\tvar msg syscall.NetlinkMessage\n\tvar msgs []syscall.NetlinkMessage\n\tvar err error\n\n\tfor receiveMore := true; receiveMore; {\n\t\t// Retry the non-blocking read multiple times until a response is received.\n\t\tfor i := 0; i < 10; i++ {\n\t\t\tmsgs, err = c.Netlink.Receive(true, parseNetlinkAuditMessage)\n\t\t\tif err != nil {\n\t\t\t\tswitch {\n\t\t\t\tcase errors.Is(err, syscall.EINTR):\n\t\t\t\t\tcontinue\n\t\t\t\tcase errors.Is(err, syscall.EAGAIN):\n\t\t\t\t\ttime.Sleep(50 * time.Millisecond)\n\t\t\t\t\tcontinue\n\t\t\t\tdefault:\n\t\t\t\t\treturn nil, fmt.Errorf(\"error receiving audit reply: %w\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tif len(msgs) == 0 {\n\t\t\treturn nil, errors.New(\"no reply received\")\n\t\t}\n\t\tmsg = msgs[0]\n\t\t// Skip audit event that sneak between the request/response\n\t\treceiveMore = msg.Header.Seq == 0 && seq != 0\n\t}\n\tif msg.Header.Seq != seq {\n\t\treturn nil, fmt.Errorf(\"unexpected sequence number for reply (expected %v but got %v)\",\n\t\t\tseq, msg.Header.Seq)\n\t}\n\treturn &msg, nil\n}", "func (b *BaseConn) readLoop() {\n\n\tmsgBuffer := make([]byte, 1024)\n\tvar readLen uint64\n\tvar length int\n\tvar readUpTo int\n\tfor {\n\t\t// If we're still reading the length...\n\t\tif length == 0 {\n\n\t\t\t// Read up to a maximum of six bytes.\n\t\t\t// Six bytes encodes up to 2^(7*6) == 2^35,\n\t\t\t// much more than the legal maximum length.\n\t\t\t// We don't want to read too much, because we have to\n\t\t\t// copy any excess read down the buffer afterwards.\n\t\t\tif readUpTo < 6 {\n\t\t\t\tn, err := b.conn.Read(msgBuffer[readUpTo:6])\n\t\t\t\tif err != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\treadUpTo += n\n\t\t\t}\n\n\t\t\t// Try to read the length.\n\t\t\tvar used int\n\t\t\treadLen, used = proto.DecodeVarint(msgBuffer[:readUpTo])\n\t\t\tif used == 0 {\n\t\t\t\t// If we couldn't read it yet,\n\t\t\t\t// and have already read six bytes,\n\t\t\t\t// the other end is playing silly buggers.\n\t\t\t\t// Drop the connection.\n\t\t\t\tif readUpTo >= 6 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\t// Otherwise, if we weren't able to read it,\n\t\t\t\t// continue reading the length.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// If readLen is illegally huge, drop connection.\n\t\t\t// Otherwise, we've got our length.\n\t\t\tif readLen > 0x7FFFFFFF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlength = int(readLen)\n\n\t\t\t// Grow message buffer if needed.\n\t\t\tif length > len(msgBuffer) {\n\t\t\t\tnewMsgBuffer := make([]byte, length)\n\n\t\t\t\t// Copy over any excess read.\n\t\t\t\tif used != readUpTo {\n\t\t\t\t\tcopy(newMsgBuffer,\n\t\t\t\t\t\tmsgBuffer[used:readUpTo])\n\t\t\t\t}\n\n\t\t\t\tmsgBuffer = newMsgBuffer\n\t\t\t} else {\n\t\t\t\t// Copy down any excess read.\n\t\t\t\tif used != readUpTo {\n\t\t\t\t\tcopy(msgBuffer,\n\t\t\t\t\t\tmsgBuffer[used:readUpTo])\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// This leaves readUpTo set to the length of\n\t\t\t// any excess read, zero if there was none.\n\t\t\treadUpTo -= used\n\t\t}\n\n\t\t// Read the message.\n\t\t// We don't want to read too much, because we have to\n\t\t// copy any excess read down the buffer afterwards.\n\t\t// It can still happen with short messages already read past.\n\t\tif readUpTo < length {\n\t\t\tn, err := b.conn.Read(msgBuffer[readUpTo:length])\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treadUpTo += n\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// Unmarshal the message and send it for receipt.\n\t\tmsg := new(baseproto.Message)\n\t\terr := proto.Unmarshal(msgBuffer[:length], msg)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif *msg.MsgType == 1 {\n\t\t\tb.receivedCapabilities <- msg\n\t\t} else {\n\t\t\tb.received <- msg\n\t\t}\n\n\t\t// Copy down any excess read.\n\t\tif length != readUpTo {\n\t\t\tcopy(msgBuffer, msgBuffer[length:readUpTo])\n\t\t}\n\n\t\t// This leaves readUpTo set to the length of\n\t\t// any excess read, zero if there was none.\n\t\treadUpTo -= length\n\n\t\t// Set length to 0, ready to read the next length.\n\t\tlength = 0\n\t}\n\n\tclose(b.received)\n\tb.Close()\n}", "func (mc *MockConn) Read(b []byte) (int, error) {\n\tif mc.closed {\n\t\treturn 0, errors.New(\"Connection closed.\")\n\t}\n\n\ti := 0\n\tfor i < len(b) {\n\t\tif mc.outMessage == nil {\n\t\t\tselect {\n\t\t\tcase <-mc.done:\n\t\t\t\treturn 0, errors.New(\"Connection closed.\")\n\t\t\tcase mc.outMessage = <-mc.receiveChan:\n\t\t\t}\n\t\t\tmc.outPlace = 0\n\t\t}\n\n\t\tfor mc.outPlace < len(mc.outMessage) && i < len(b) {\n\t\t\tb[i] = mc.outMessage[mc.outPlace]\n\t\t\tmc.outPlace++\n\t\t\ti++\n\t\t}\n\n\t\tif mc.outPlace == len(mc.outMessage) {\n\t\t\tmc.outMessage = nil\n\t\t}\n\t}\n\n\treturn i, nil\n}", "func (lc *LuMiGatewayClient) Read(idlist []string, s *net.UDPConn, addr *net.UDPAddr) {\n\tfor {\n\t\tfor _, id := range idlist {\n\t\t\td, err := lc.PackCommand(lumiCommandTypeRead, \"\", id, 0, \"\")\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"pack read command failed: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ts.WriteToUDP(d, addr)\n\t\t}\n\n\t\ttime.Sleep(time.Second)\n\t}\n}", "func (o *PostCharactersCharacterIDMailLabelsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 201:\n\t\tresult := NewPostCharactersCharacterIDMailLabelsCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 400:\n\t\tresult := NewPostCharactersCharacterIDMailLabelsBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 401:\n\t\tresult := NewPostCharactersCharacterIDMailLabelsUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 403:\n\t\tresult := NewPostCharactersCharacterIDMailLabelsForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 420:\n\t\tresult := NewPostCharactersCharacterIDMailLabelsEnhanceYourCalm()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 500:\n\t\tresult := NewPostCharactersCharacterIDMailLabelsInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 503:\n\t\tresult := NewPostCharactersCharacterIDMailLabelsServiceUnavailable()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 504:\n\t\tresult := NewPostCharactersCharacterIDMailLabelsGatewayTimeout()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func castReadReply(reply interface{}) (bytesRead int, data []byte, err error) {\n\tarr := reply.([]interface{})\n\tad.AssertEquals(3, len(arr))\n\tbytesRead = arr[0].(int)\n\tdata = arr[1].([]byte)\n\terr = ad.AssertIsErrorOrNil(arr[2])\n\treturn bytesRead, data, err\n}", "func (sc *SnippetClient) clientReceive(timeout time.Duration) ([]byte, error) {\n\tsc.conn.SetReadDeadline(time.Now().Add(timeout))\n\tbufReader := bufio.NewReader(sc.conn)\n\tres, err := bufReader.ReadBytes('\\n')\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}", "func (u *Input) readMessage() ([]byte, net.Addr, error) {\n\tn, addr, err := u.connection.ReadFrom(u.buffer)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Remove trailing characters and NULs\n\tfor ; (n > 0) && (u.buffer[n-1] < 32); n-- { // nolint\n\t}\n\n\treturn u.buffer[:n], addr, nil\n}", "func readScript(r io.Reader, fieldName string) ([]byte, error) {\n\tcount, err := wire.ReadVarInt(r, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Prevent byte array larger than the max message size. It would\n\t// be possible to cause memory exhaustion and panics without a sane\n\t// upper bound on this count.\n\tif count > uint64(wire.MaxMessagePayload) {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"readScript: %s is larger than the max allowed size [count %d, max %d]\",\n\t\t\tfieldName, count, wire.MaxMessagePayload,\n\t\t)\n\t}\n\n\tb := make([]byte, count)\n\tif _, err := io.ReadFull(r, b); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}" ]
[ "0.65165836", "0.5854756", "0.5806837", "0.5787643", "0.5747598", "0.5715381", "0.5694573", "0.5679438", "0.56494606", "0.5607286", "0.5572244", "0.55594164", "0.5540163", "0.551188", "0.54905564", "0.54719746", "0.54376435", "0.54350746", "0.5413301", "0.5413174", "0.5398423", "0.53864646", "0.5384296", "0.53145474", "0.53033465", "0.5248621", "0.5230288", "0.520089", "0.51992", "0.5191429", "0.5183653", "0.5179885", "0.5170978", "0.5168256", "0.5168256", "0.5154843", "0.5147113", "0.51001954", "0.51001054", "0.50979495", "0.5097272", "0.507583", "0.5073024", "0.50605255", "0.506031", "0.5054082", "0.5041876", "0.5041091", "0.50360733", "0.5031751", "0.50235254", "0.50215816", "0.5015683", "0.50065213", "0.5002651", "0.5001415", "0.49983555", "0.49899018", "0.4989003", "0.49883586", "0.4986352", "0.49861175", "0.49845722", "0.4982875", "0.4979332", "0.4949408", "0.49487567", "0.49462366", "0.4925429", "0.49205723", "0.49198735", "0.4915312", "0.49135688", "0.49117392", "0.4899136", "0.489681", "0.48905668", "0.4886408", "0.48853502", "0.48767522", "0.4870978", "0.48703325", "0.48689353", "0.48682797", "0.4862633", "0.4862633", "0.4862633", "0.4862633", "0.48622435", "0.4861832", "0.48485035", "0.48460823", "0.4842902", "0.48349893", "0.48340815", "0.4833646", "0.48307687", "0.48302543", "0.48141524", "0.48129055" ]
0.5633202
9
OpenConnection open a redis connection
func (client *Client) OpenConnection() (c net.Conn, err error) { var addr = defaultAddr if client.Addr != "" { addr = client.Addr } c, err = net.Dial("tcp", addr) if err != nil { return } //handle authentication here authored by @shxsun if client.Password != "" { cmd := fmt.Sprintf("AUTH %s\r\n", client.Password) _, err = client.rawSend(c, []byte(cmd)) if err != nil { return } } if client.Db != 0 { cmd := fmt.Sprintf("SELECT %d\r\n", client.Db) _, err = client.rawSend(c, []byte(cmd)) if err != nil { return } } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cli *RedisClient) open() redis.Conn {\n\tif cli.pool == nil {\n\t\tcli.pool = cli.newPool()\n\t}\n\n\tif cli.redsync == nil {\n\t\tvar pools = []redsync.Pool{cli.pool}\n\t\tcli.redsync = redsync.New(pools)\n\t}\n\n\treturn cli.pool.Get()\n}", "func (p *RedisConnectionPool) Open() error {\n\tp.Close()\n\n\t// Default to 15s timeout\n\tif time.Duration(0) == p.Timeout {\n\t\tp.Timeout = time.Duration(15) * time.Second\n\t}\n\n\t// Lambda to iterate the urls\n\tnextUrl := loopStrings(p.Urls)\n\n\t// Lambda for creating the factories\n\tvar initfn InitFunction\n\tswitch p.Mode {\n\tcase LAZY:\n\t\t// Create the factory\n\t\t// DON'T Connect to Redis\n\t\t// DON'T Test the connection\n\t\tinitfn = func() (interface{}, error) {\n\t\t\tvalues := nextUrl()\n\t\t\treturn makeLazyRedisConnection(values[0], values[1], p.Timeout, &p.Logger)\n\t\t}\n\tcase AGRESSIVE:\n\t\t// Create the factory\n\t\t// AND Connect to Redis\n\t\t// AND Test the connection\n\t\tinitfn = func() (interface{}, error) {\n\t\t\tvalues := nextUrl()\n\t\t\treturn makeAgressiveRedisConnection(values[0], values[1], p.Timeout, &p.Logger)\n\t\t}\n\t\t// No mode specified!\n\tdefault:\n\t\treturn errors.New(fmt.Sprintf(\"Invalid connection mode: %v\", p.Mode))\n\t}\n\n\t// Create the new pool\n\tpool, err := MakeConnectionPoolWrapper(p.Size, initfn)\n\n\t// Error creating the pool?\n\tif nil != err {\n\t\treturn err\n\t}\n\n\t// Save the pointer to the pool\n\tp.myPool = pool\n\n\t// Return nil\n\treturn nil\n}", "func redisConnect() *redis.Client {\n client := redis.NewClient(&redis.Options{\n Addr: fmt.Sprintf(\"%s:6379\", redisServer),\n Password: \"\",\n DB: 0,\n })\n return client\n}", "func connect() redis.Conn{\n\tconnWithRedis,err := redis.Dial(\"tcp\",\":6379\")\n\n\tif err != nil{\n\t\tlog.Fatalln(err)\n\t}\n\n\treturn connWithRedis\n\n}", "func newCacheConnection(config *config.Config) redis.Cmdable {\n\tcacheConn := redis.NewClient(&redis.Options{\n\t\tAddr: config.Cache.Host,\n\t\tPassword: \"\",\n\t\tDB: 0,\n\t\tReadTimeout: time.Second,\n\t})\n\tif cacheConn == nil {\n\t\tlogger.Log().Fatal(\"unable to connect to redis\", zap.String(\"host\", config.Cache.Host))\n\t}\n\treturn cacheConn\n}", "func connectSrcRedis(r string, p int) *redis.Client {\n\treturn redis.NewClient(&redis.Options {\n\t\tAddr: r,\n\t\tPassword: \"\",\n\t\tDB: p,\n\t\tMaxRetries: 5,\n\t\tReadTimeout: 5 * time.Minute,\n\t\tIdleTimeout: 5 * time.Minute,\n\t\tMinIdleConns: 5,\n\t\tPoolSize: 100,\n\t})\n}", "func connectRedis() (r redis.Conn, err error) {\n\tif len(*redisPassArg) > 0 {\n\t\tr, err = redis.Dial(\"tcp\", *redisAddrArg, redis.DialDatabase(*redisDbArg))\n\t} else {\n\t\tr, err = redis.Dial(\"tcp\", *redisAddrArg, redis.DialPassword(*redisPassArg), redis.DialDatabase(*redisDbArg))\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = r.Do(\"PING\")\n\treturn r, err\n}", "func Open(redisAddr, redisPassword string) *DB {\n\treturn &DB{redisAddr, redisPassword}\n}", "func (r *CacheRedis) connect() {\n\n}", "func Open(path string) (Database, error) {\n\tif strings.HasPrefix(path, redisPrefix) {\n\t\topt, err := redis.ParseURL(path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdatabase := new(Redis)\n\t\tdatabase.client = redis.NewClient(opt)\n\t\treturn database, nil\n\t}\n\treturn nil, errors.Errorf(\"Unknown database: %s\", path)\n}", "func (c *connection) createRedisConnection(inputs input) error {\n\n\tconn, err := redis.Dial(\"tcp\", inputs.host+\":\"+inputs.port, redis.DialConnectTimeout(15*time.Second))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := conn.Do(\"CLIENT\", \"SETNAME\", \"redis-mqueue\"); err != nil {\n\t\treturn err\n\t}\n\n\tc.redis = conn\n\n\treturn nil\n\n}", "func (r *Redis) Connect() {\n\tr.client = redis.NewUniversalClient(&redis.UniversalOptions{\n\t\tAddrs: []string{r.config.Addr()},\n\t\tPassword: r.config.Password,\n\t\tDB: r.config.DB,\n\t})\n}", "func ConnectRedis(addr string, c model.Credential, timeout time.Duration) (ok bool, err error) {\n\n\t// https://pkg.go.dev/github.com/go-redis/redis/v8#Options\n\topts := &redis.Options{\n\t\tAddr: addr,\n\t\tPassword: c.Password, // no password set\n\t\tDB: 0, // use default DB\n\n\t\t// Dial timeout for establishing new connections.\n\t\t// Default is 5 seconds.\n\t\tDialTimeout: timeout,\n\t\t// Timeout for socket reads. If reached, commands will fail\n\t\t// with a timeout instead of blocking. Use value -1 for no timeout and 0 for default.\n\t\t// Default is 3 seconds.\n\t\tReadTimeout: timeout,\n\t\t// Timeout for socket writes. If reached, commands will fail\n\t\t// with a timeout instead of blocking.\n\t\t// Default is ReadTimeout.\n\t\tWriteTimeout: timeout,\n\t}\n\tif c.User != \"\" {\n\t\topts.Username = c.User\n\t}\n\n\trdb := redis.NewClient(opts)\n\tdefer rdb.Close()\n\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\tstatusCmd := rdb.Ping(ctx)\n\t_, err = statusCmd.Result()\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t// Luls\n\treturn true, nil\n}", "func InitRedisConnection(addr string) {\n\tvar err error\n\tRedisConn, err = redis.Dial(\"tcp\", addr)\n\tredisLog := logrus.WithField(\"address\", addr)\n\tif err != nil {\n\t\tredisLog.Fatal(err)\n\t} else {\n\t\tredisLog.Info(\"Connected to redis\")\n\t}\n}", "func connectRedis(redisServer string, redisPort string) *redis.Client{\n\tclient := redis.NewClient(&redis.Options{\n\t\t//Addr: \"localhost:6379\",\n\t\tAddr: (redisServer + \":\" + redisPort),\n\t\tPassword: \"\", // no password set\n\t\tDB: 0, // use default DB\n\t})\n\n\tpong, err := client.Ping().Result()\n\tCheckError(err)\n\tredisLogger.Info.Println(pong, \"from\", client.String())\n\treturn client\n}", "func (r *Rediscli) ConnectRedis(config Config) *redis.Cmdable {\n\tvar client redis.Cmdable\n\tclient = redis.NewClient(&redis.Options{\n\t\tAddr: fmt.Sprintf(\"%s:%d\", config.ServerIP, config.RedisPort), // use default Addr\n\t\tPassword: PWD, // no password set\n\t\tDB: 0, // use default DB\n\t})\n\tfmt.Printf(\"connect reids client memery address : %v ; \\n\", &client)\n\treturn &client\n}", "func Open(ctx context.Context, params planetscalev2.VitessLockserverParams) (*Conn, error) {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\topenLatency.Observe(time.Since(startTime).Seconds())\n\t}()\n\n\t// Hold the openMu RLock for as long as we're trying to get a connection,\n\t// to prevent the connection GC from closing connections.\n\t// Other Open attempts can happen concurrently, however.\n\tpool.openMu.RLock()\n\tdefer pool.openMu.RUnlock()\n\n\t// Get or start a connection attempt.\n\tconn := pool.get(params)\n\n\t// Wait for the connection attempt to finish.\n\tctx, cancel := context.WithTimeout(ctx, connectTimeout)\n\tdefer cancel()\n\treturn conn.open(ctx)\n}", "func Connection() redis.Conn {\n\tlogrus.Info(\"get new redis connection from pool\") // zap.Namespace(\"context\"),\n\t// zap.Int(\"IdleCount\", pool.IdleCount()),\n\t// zap.Int(\"ActiveCount\", pool.ActiveCount()),\n\n\t// 记录操作日志\n\tif app.Debug {\n\t\tw := logrus.StandardLogger().Writer()\n\t\treturn redis.NewLoggingConn(pool.Get(), log.New(w, \"\", 0), \"rds\")\n\t}\n\n\treturn pool.Get()\n}", "func Connection() redis.Conn {\n\tlogrus.Info(\"get new redis connection from pool\")// zap.Namespace(\"context\"),\n\t// zap.Int(\"IdleCount\", pool.IdleCount()),\n\t// zap.Int(\"ActiveCount\", pool.ActiveCount()),\n\n\t// 记录操作日志\n\tif debug {\n\t\tw := logrus.StandardLogger().Writer()\n\t\treturn redis.NewLoggingConn(pool.Get(), log.New(w, \"\", 0), \"rds\")\n\t}\n\n\treturn pool.Get()\n}", "func NewConnection(opts *Config) (cache *Client, err error) {\n\tcache = redis.NewClient(opts)\n\n\tif _, err = cache.Ping().Result(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cache, nil\n}", "func TestRedisConn(t *testing.T) {\n\t_, err := redis.Dial(\"tcp\", \"192.168.99.100:3000\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Conexao realizada\")\n}", "func (c *Cache) Connect() error {\n\tlog.Info(\"connecting to redis\", log.Pairs{\"protocol\": c.Config.Redis.Protocol, \"Endpoint\": c.Config.Redis.Endpoint})\n\n\tswitch c.Config.Redis.ClientType {\n\tcase \"sentinel\":\n\t\topts, err := c.sentinelOpts()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclient := redis.NewFailoverClient(opts)\n\t\tc.closer = client.Close\n\t\tc.client = client\n\tcase \"cluster\":\n\t\topts, err := c.clusterOpts()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclient := redis.NewClusterClient(opts)\n\t\tc.closer = client.Close\n\t\tc.client = client\n\tdefault:\n\t\topts, err := c.clientOpts()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclient := redis.NewClient(opts)\n\t\tc.closer = client.Close\n\t\tc.client = client\n\t}\n\treturn c.client.Ping().Err()\n}", "func newConnection() (*gredis.Client, error) {\n\thost = os.Getenv(\"REDIS_HOST\")\n\tport = os.Getenv(\"REDIS_PORT\")\n\trdb := gredis.NewClient(&gredis.Options{\n\t\tAddr: fmt.Sprintf(\"%s:%s\", host, port),\n\t\tPassword: password,\n\t\tDB: db,\n\t})\n\n\tstatus := rdb.Ping(rdb.Context())\n\terr := status.Err()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn rdb, nil\n}", "func Connect() (redis.Conn, error) {\n\tconn := pool.Get()\n\n\tif err := conn.Err(); err != nil {\n\t\treturn conn, err\n\t}\n\n\treturn conn, nil\n}", "func NewRedisConnection(c *redis.Client) *conn {\n\treturn &conn{\n\t\tClient: c,\n\t}\n}", "func ConnectToRedis() (*redis.Client, error) {\n\tclient = redis.NewClient(&redis.Options{\n\t\tAddr: \"redis:6379\",\n\t\tDialTimeout: 10 * time.Second,\n\t\tReadTimeout: 30 * time.Second,\n\t\tWriteTimeout: 30 * time.Second,\n\t\tPoolSize: 10,\n\t\tPoolTimeout: 30 * time.Second,\n\t})\n\n\t_, err := client.Ping().Result()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}", "func connectDstRedis(r string, p int) *redis.Client {\n\treturn redis.NewClient(&redis.Options {\n\t\tAddr: r,\n\t\tPassword: \"\",\n\t\tDB: p,\n\t\tMaxRetries: 5,\n\t\tReadTimeout: 5 * time.Minute,\n\t\tIdleTimeout: 5 * time.Minute,\n\t\tMinIdleConns: 5,\n\t\tPoolSize: 100,\n\t})\n}", "func Initialize() *redisClient {\r\n\tc := redis.NewClient(&redis.Options{\r\n\t\tAddr: constants.RedisHost + \":\" + constants.RedisPort,\r\n\t\tPassword: constants.RedisPass,\r\n\t\tDB: constants.RedisDbName,\r\n\t\tMaxConnAge: 1,\r\n\t})\r\n\t//defer c.Close()\r\n\tif err := c.Ping().Err(); err != nil {\r\n\t\tlogger.Log.Println(\"Unable to connect to redis \" + err.Error())\r\n\t\tpanic(err)\r\n\t}\r\n\tclient.c = c\r\n\treturn client\r\n}", "func GetRedisConn(redisAddrKey string) *redis.Client {\n\tredisConn.Do(func() {\n\t\tredisClient = redis.NewClient(&redis.Options{\n\t\t\tAddr: util.GetConfigValue(redisAddrKey),\n\t\t\tPassword: \"\", // no password set\n\t\t\tDB: 0, // use default DB\n\t\t})\n\t\tctx := context.Background()\n\t\tpong, err := redisClient.Ping(ctx).Result()\n\t\tif err != nil || pong != Pong {\n\t\t\treason := fmt.Sprintf(\"Error while creating Redis connection pool: %s\", err)\n\t\t\t//logger.GetLogger().Println(reason)\n\t\t\tfmt.Println(reason)\n\t\t}\n\t})\n\treturn redisClient\n}", "func Connect() (redis.Conn, error) {\n\tconn, err := sockfile.Dial(\"redisd\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn redis.NewConn(conn, Timeout, Timeout), nil\n}", "func connectRedis(url string) (*service, error) {\n\topt, err := redis.ParseURL(url)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Connect: Can't parse redis url\")\n\t}\n\n\tconnexion := redis.NewClient(opt)\n\n\tif err := connexion.Ping().Err(); err != nil {\n\t\treturn nil, errors.New(\"Connect: Can't ping redis\")\n\t}\n\n\treturn &service{\n\t\tclient: connexion,\n\t\tpubSub: nil,\n\t}, nil\n}", "func ConnectionPool(cfg *viper.Viper) *redis.Pool {\n\t// As per https://www.iana.org/assignments/uri-schemes/prov/redis\n\t// redis://user:secret@localhost:6379/0?foo=bar&qux=baz\n\n\t// Add redis user and password to connection url if they exist\n\tredisURL := \"redis://\"\n\tif cfg.IsSet(\"redis.user\") && cfg.GetString(\"redis.user\") != \"\" &&\n\t\tcfg.IsSet(\"redis.password\") && cfg.GetString(\"redis.password\") != \"\" {\n\t\tredisURL += cfg.GetString(\"redis.user\") + \":\" + cfg.GetString(\"redis.password\") + \"@\"\n\t}\n\tredisURL += cfg.GetString(\"redis.hostname\") + \":\" + cfg.GetString(\"redis.port\")\n\n\trhLog.WithFields(log.Fields{\"redisURL\": redisURL}).Debug(\"Attempting to connect to Redis\")\n\tpool := redis.Pool{\n\t\tMaxIdle: cfg.GetInt(\"redis.pool.maxIdle\"),\n\t\tMaxActive: cfg.GetInt(\"redis.pool.maxActive\"),\n\t\tIdleTimeout: cfg.GetDuration(\"redis.pool.idleTimeout\") * time.Second,\n\t\tDial: func() (redis.Conn, error) { return redis.DialURL(redisURL) },\n\t}\n\n\t// Sanity check that connection works before passing it back. Redigo\n\t// always returns a valid connection, and will just fail on the first\n\t// query: https://godoc.org/github.com/gomodule/redigo/redis#Pool.Get\n\tredisConn := pool.Get()\n\tdefer redisConn.Close()\n\t_, err := redisConn.Do(\"SELECT\", \"0\")\n\t// Encountered an issue getting a connection from the pool.\n\tif err != nil {\n\t\trhLog.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t\t\"query\": \"SELECT 0\"}).Error(\"state storage connection error\")\n\t\treturn nil\n\t}\n\n\trhLog.Info(\"Connected to Redis\")\n\treturn &pool\n}", "func Connect() redis.Conn {\n\tvar err error\n\tconnect, err = redis.Dial(\"tcp\", getDial())\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn connect\n}", "func GetRedisConnection() *redis.Client {\n\n\tredis := redis.NewClient(&redis.Options{\n\t\tAddr: viper.GetString(\"REDIS_HOST\"),\n\t\tPassword: viper.GetString(\"REDIS_PASSWORD\"),\n\t\tDB: viper.GetInt(\"REDIS_DATABASE\"),\n\t})\n\n\treturn redis\n}", "func (c *fakeRedisConn) Close() error { return nil }", "func NewRedisConnection(config config.RedisConfig) (*redis.Client, error) {\n\tredisClient := redis.NewClient(&redis.Options{\n\t\tAddr: config.RedisHost + \":\" + config.RedisPort,\n\t\tPassword: config.RedisPassword,\n\t\tDB: config.RedisDB,\n\t})\n\n\terr := redisClient.Ping(context.Background()).Err()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn redisClient, nil\n}", "func Setup_redis() {\n\n SC.Redisdb = redis.NewTCPClient(&redis.Options{\n Addr: SC.FAST_SERVER,\n Password: \"\", // no password set\n DB: 0, // use default DB\n })\n}", "func NewConnection(cfg config.Configuration) (Connection, func()) {\n\tconn := redisConn{\n\t\tclient: redis.NewClient(&redis.Options{\n\t\t\tAddr: cfg.RedisAddr,\n\t\t\tPassword: cfg.RedisPassword,\n\t\t}),\n\t}\n\n\tcleanupFunc := func() {\n\t\tconn.Close()\n\t}\n\n\treturn &conn, cleanupFunc\n}", "func testingConnect() redis.Conn {\n\ttestingDial()\n\tconn := GetConn()\n\tif err := testConn(conn); err != nil {\n\t\tpanic(err)\n\t}\n\treturn conn\n}", "func NewRedisConnection(ctx context.Context, config *config.RedisStorageConfig) (RedisConnection, error) {\n\tvar conn RedisConnection\n\tif config.SingleNode != nil {\n\t\tconn = createClientSingleNode(ctx, config)\n\t} else {\n\t\tconn = createClientCluster(ctx, config)\n\t}\n\tif err := conn.RedisCmd.Ping(ctx); err != nil {\n\t\tif err := conn.Close(); err != nil {\n\t\t\tlogger.Of(ctx).InfoError(logger.CatStorage, \"Failed to close Redis connection after initial ping failure\", err)\n\t\t}\n\t\treturn RedisConnection{}, err\n\t}\n\treturn conn, nil\n}", "func Connect(host string) (redis.Conn, error) {\n\tconn, err := redis.Dial(\"tcp\", host)\n\tif err != nil {\n\t\tlogp.Err(\"Redis connection error: %v\", err)\n\t}\n\n\treturn conn, err\n}", "func InitRedis() interfaces.RedisPool {\n\tdeferFunc := logger.LogWithDefer(\"Load Redis connection...\")\n\tdefer deferFunc()\n\n\tinst := new(redisInstance)\n\n\tinst.read = &redis.Pool{\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tredisDB, _ := strconv.Atoi(env.BaseEnv().DbRedisReadDBIndex)\n\t\t\treturn redis.Dial(\"tcp\", fmt.Sprintf(\"%s:%s\", env.BaseEnv().DbRedisReadHost, env.BaseEnv().DbRedisReadPort),\n\t\t\t\tredis.DialPassword(env.BaseEnv().DbRedisReadAuth),\n\t\t\t\tredis.DialDatabase(redisDB),\n\t\t\t\tredis.DialUseTLS(env.BaseEnv().DbRedisReadTLS))\n\t\t},\n\t}\n\n\tpingRead := inst.read.Get()\n\tdefer pingRead.Close()\n\t_, err := pingRead.Do(\"PING\")\n\tif err != nil {\n\t\tpanic(\"redis read: \" + err.Error())\n\t}\n\n\tinst.write = &redis.Pool{\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tredisDB, _ := strconv.Atoi(env.BaseEnv().DbRedisWriteDBIndex)\n\t\t\treturn redis.Dial(\"tcp\", fmt.Sprintf(\"%s:%s\", env.BaseEnv().DbRedisWriteHost, env.BaseEnv().DbRedisWritePort),\n\t\t\t\tredis.DialPassword(env.BaseEnv().DbRedisWriteAuth),\n\t\t\t\tredis.DialDatabase(redisDB),\n\t\t\t\tredis.DialUseTLS(env.BaseEnv().DbRedisWriteTLS))\n\t\t},\n\t}\n\n\tpingWrite := inst.write.Get()\n\tdefer pingWrite.Close()\n\t_, err = pingWrite.Do(\"PING\")\n\tif err != nil {\n\t\tpanic(\"redis write: \" + err.Error())\n\t}\n\n\tinst.cache = cache.NewRedisCache(inst.read, inst.write)\n\n\treturn inst\n}", "func SetupConnection() error {\n\tp := pools.NewResourcePool(func() (pools.Resource, error) {\n\t\tc, err := redis.Dial(\"tcp\", fhidConfig.Config.RedisEndpoint)\n\t\tif err != nil {\n\t\t\tfhidLogger.Loggo.Crit(\"Error connecting to Redis.\", \"Error\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\treturn ResourceConn{c}, err\n\t}, 1, 2, time.Minute)\n\tctx := context.TODO()\n\tr, err := p.Get(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tRconn = r.(ResourceConn)\n\treturn err\n}", "func New(conf *RedisConf, options ...redis.DialOption) (*RedisSession, error) {\n\ts := &RedisSession{}\n\tif len(options) == 0 {\n\t\toptions = []redis.DialOption{\n\t\t\tredis.DialReadTimeout(5 * time.Second),\n\t\t\tredis.DialWriteTimeout(time.Second),\n\t\t\tredis.DialConnectTimeout(time.Second),\n\t\t}\n\t}\n\n\toptions = append(options, redis.DialDatabase(conf.DB))\n\n\tpool := &redis.Pool{\n\t\tMaxIdle: 80,\n\t\tMaxActive: 1000,\n\t\tIdleTimeout: 30 * time.Second,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tc, err := redis.Dial(\"tcp\", conf.Server, options...)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn c, err\n\t\t},\n\t\tTestOnBorrow: func(c redis.Conn, t time.Time) error {\n\t\t\t_, err := c.Do(\"PING\")\n\t\t\treturn err\n\t\t},\n\t}\n\ts.pool = pool\n\t// when we use connection pooling\n\t// dialing and returning an error will be\n\t// with the request\n\treturn s, nil\n}", "func Redis() (redis.Conn, error) {\n\tc, err := redis.Dial(\"tcp\", \":6381\")\n\tif err != nil {\n\t\tlog.Printf(\"Failed to connect to Redis server!\")\n\t\t// Dont panic here, show user-friendly message later on webpage\n\t\treturn nil, err\n\t}\n\n\tif _, err := c.Do(\"SELECT\", 0); err != nil {\n\t\tlog.Printf(\"Failed to SELECT Redis DB! Error: %s\", err)\n\t\t// Dont panic here, show user-friendly message later on webpage\n\t\treturn nil, err\n\t}\n\n\t// defer c.Close()\n\treturn c, nil\n}", "func ConnectRedis() (*redis.Client, error) {\n\n\tif os.Getenv(\"REDIS_ADDR\") == \"\" {\n\t\tos.Setenv(\"REDIS_ADDR\", \"127.0.0.1:6379\")\n\t\tos.Setenv(\"REDIS_PASSWORD\", \"\")\n\t}\n\n\tInstance = redis.NewClient(&redis.Options{\n\t\tAddr: os.Getenv(\"REDIS_ADDR\"),\n\t\tPassword: os.Getenv(\"REDIS_PASSWORD\"),\n\t\tDB: 0,\n\t})\n\n\t_, err := Instance.Ping().Result()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn Instance, nil\n}", "func NewConn() redis.Conn {\n\treturn pool.Get()\n}", "func newRedisPoool(config *Config) *redis.Pool {\n\tserver := config.RedisURL\n\tpassword := config.RedisPassword\n\tmaxIdle := config.RedisMaxIdle\n\tidleTimeout := config.RedisIdleTimeout\n\n\tpool := &redis.Pool{\n\t\tMaxIdle: maxIdle,\n\t\tIdleTimeout: time.Duration(idleTimeout) * time.Second,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tc, err := redis.Dial(\"tcp\", server)\n\t\t\tif err != nil {\n\t\t\t\treturn c, nil\n\t\t\t}\n\t\t\tc.Do(\"AUTH\", password)\n\n\t\t\t/* the is needed only if \"gores\" is configured in Redis's configuration file redis.conf */\n\t\t\t//c.Do(\"SELECT\", \"gores\")\n\t\t\treturn c, nil\n\t\t},\n\t\tTestOnBorrow: func(c redis.Conn, t time.Time) error {\n\t\t\t_, err := c.Do(\"PING\")\n\t\t\treturn err\n\t\t},\n\t}\n\n\treturn pool\n}", "func Connect(cfg *Config) *redis.Client {\n\treturn redis.NewClient(&redis.Options{\n\t\tAddr: fmt.Sprintf(\"%s:%s\", cfg.Host, cfg.Port),\n\t\tPassword: cfg.Password,\n\t\tDB: cfg.DB,\n\t\tPoolSize: cfg.PoolSize,\n\t\tDialTimeout: cfg.DialTimeout,\n\t\tReadTimeout: cfg.ReadWriteTimeout,\n\t\tWriteTimeout: cfg.ReadWriteTimeout,\n\t\tIdleTimeout: cfg.IdleTimeout,\n\t\tIdleCheckFrequency: cfg.IdleCheckFrequency,\n\t\tMaxConnAge: cfg.MaxConnAge,\n\t})\n}", "func newRedisClient(addr string, pwd string, db int) (redis.UniversalClient, error) {\n\tclient := redis.NewUniversalClient(&redis.UniversalOptions{\n\t\tAddrs: []string{addr},\n\t\tPassword: pwd,\n\t\tDB: db,\n\t})\n\n\t_, err := client.Ping(context.Background()).Result()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}", "func GetConnection() redis.Conn {\n\treturn pool.Get()\n}", "func GetConnection() redis.Conn {\n\treturn pool.Get()\n}", "func Connect(url string, pool *redis.Pool) (c *Client) {\n\tvar cpool *redis.Pool\n\tif pool == nil {\n\t\tcpool = &redis.Pool{\n\t\t\tMaxIdle: 3,\n\t\t\tIdleTimeout: 240 * time.Second,\n\t\t\tDial: func() (redis.Conn, error) { return redis.DialURL(url) },\n\t\t}\n\t} else {\n\t\tcpool = pool\n\t}\n\n\tc = &Client{\n\t\tPool: cpool,\n\t\tPipelineActive: false,\n\t\tPipelineAutoFlushSize: 0,\n\t\tPipelinePos: 0,\n\t\tActiveConn: nil,\n\t}\n\n\treturn c\n}", "func (r *Redis) Conn(ctx context.Context) Conn {\n\treturn r.pool.Get(ctx)\n}", "func (c *Conn) open(ctx context.Context) (conn *Conn, err error) {\n\tc.mu.Lock()\n\tc.refCount++\n\tc.lastOpened = time.Now()\n\tc.mu.Unlock()\n\n\tdefer func() {\n\t\t// If we return an error, the caller is not expected to call Close().\n\t\t// We need to decrement the refCount ourselves.\n\t\tif err != nil {\n\t\t\tc.mu.Lock()\n\t\t\tc.refCount--\n\t\t\tc.mu.Unlock()\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-c.connectDone:\n\t\tif c.connectErr != nil {\n\t\t\treturn nil, c.connectErr\n\t\t}\n\t\treturn c, nil\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\t}\n}", "func (d *Driver) Open(connStr string) (driver.Conn, error) {\n\trestClient, err := NewRestClient(nil, connStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefaultDb, ok := restClient.params[\"DEFAULTDB\"]\n\tif !ok {\n\t\tdefaultDb, _ = restClient.params[\"DB\"]\n\t}\n\treturn &Conn{restClient: restClient, defaultDb: defaultDb}, nil\n}", "func GetConn() *radix.Conn {\n\tconn, err := radix.Dial(\"tcp\", os.Getenv(\"ERU_SE_REDIS_IP\"))\n\tif err != nil {\n\t\tprintln(err)\n\t\tpanic(err)\n\t} else {\n\t\treturn &conn\n\t}\n}", "func RedisInit() redis.Conn {\n\tc := pool.Get()\n\treturn c\n}", "func GetConn() (conn redis.Conn) {\n\trepo = Get()\n\tconn = repo.Get()\n\tconn.Do(\"SELECT\", config.RerestConf.RedisDatabaseData)\n\treturn\n}", "func Connect(host, port, password string, db int) *redis.Client {\n\tredisClient := redis.NewClient(&redis.Options{\n\t\tAddr: host + \":\" + port,\n\t\tPassword: password,\n\t\tDB: db,\n\t})\n\n\treturn redisClient\n}", "func initialize() *redisClient {\n\tc := redis.NewClient(&redis.Options{\n\t\tAddr: \"127.0.0.1:6379\",\n\t})\n\n\tif err := c.Ping(context.TODO()).Err(); err != nil {\n\t\tpanic(\"Unable to connect to redis \" + err.Error())\n\t}\n\tclient.c = c\n\treturn client\n}", "func InitRedisConn() {\n\tif VarsConfig.Redis.Host == \"\" {\n\t\tlog.Fatal(\"Failed init redis, empty host from env\")\n\t}\n\n\t// init object redis\n\tpoolSize, err := strconv.Atoi(VarsConfig.Redis.PoolSize)\n\tif err != nil {\n\t\tlog.Error(err, \"failed parse pool size\")\n\t\tpoolSize = 5\n\t}\n\tGlobalConfig.redis = cache.NewRedis(VarsConfig.Redis.Host, poolSize)\n}", "func (i *Instance) initConnSafe() (conn redis.Conn) {\n\tconn = i.pool.Get()\n\tif err := conn.Err(); err != nil {\n\t\tlog.WithFields(logrus.Fields{\"key\": i.Key, \"url\": i.URL, \"err\": err}).Error(\"Initializing Redis Connection Failed.\")\n\t\ti.ConnActive = false\n\t\treturn\n\t}\n\ti.ConnActive = true\n\treturn conn\n}", "func GetRedisConn() (redis.Conn, error) {\n\n\t// Connecting to the local redis DB instance\n\tconn, err := redisurl.ConnectToURL(redisURL)\n\tif err != nil {\n\t\tlog.Println(\"Could not connect to redis DB\")\n\t\tlog.Println(err)\n\n\t}\n\n\treturn conn, err\n}", "func (d *Driver) Open(uri string) (driver.Conn, error) {\n proto, addr, dbname, user, passwd, params, err := parseDSN(uri)\n\tif err != nil {\n\t return nil, err\n }\n\td.proto = proto\n d.raddr = addr\n d.user = user\n\td.passwd = passwd\n d.db = dbname\n\n\t// Establish the connection\n\tc := conn{mysql.New(d.proto, d.laddr, d.raddr, d.user, d.passwd, d.db)}\n\n if v, ok := params[\"charset\"]; ok {\n Register(\"SET NAMES \" + v)\n }\n if v, ok := params[\"keepalive\"]; ok {\n t, err := strconv.Atoi(v)\n if err != nil {\n return nil, ErrMaxIdle\n }\n RegisterFunc(func(my mysql.Conn){\n go func() {\n for my.IsConnected() {\n time.Sleep(time.Duration(t) * time.Second)\n if err := my.Ping(); err != nil {\n break\n }\n }\n }()\n })\n }\n\tfor _, q := range d.initCmds {\n\t\tc.my.Register(q) // Register initialisation commands\n\t}\n for _, f := range d.initFuncs {\n c.my.RegisterFunc(f)\n }\n\tif err := c.my.Connect(); err != nil {\n\t\treturn nil, errFilter(err)\n\t}\n\treturn &c, nil\n}", "func InitRedisConnPool() {\n\n\taddr := \"221.228.106.9:4019\"\n\tmaxIdle := 10000\n\tidleTimeout := 240 * time.Second\n\tconnTimeout := time.Duration(1000) * time.Millisecond\n\treadTimeout := time.Duration(1000) * time.Millisecond\n\twriteTimeout := time.Duration(1000) * time.Millisecond\n\n\tRedisConnPool = &redis.Pool{\n\t\tMaxIdle: maxIdle,\n\t\tIdleTimeout: idleTimeout,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tc, err := redis.DialTimeout(\"tcp\", addr, connTimeout, readTimeout, writeTimeout)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn c, err\n\t\t},\n\t\tTestOnBorrow: nil,\n\t}\n\n\tglog.Debug(\"redis connect pool init succeed\")\n}", "func NewRmqConn(redisConn *redis.Client) (rmq.Connection, error) {\n\tconnection := rmq.OpenConnectionWithRedisClient(\"redisQueue\", redisConn)\n\n\tcleaner := rmq.NewCleaner(connection)\n\tif err := cleaner.Clean(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn connection, nil\n}", "func InitRedis(appCtx appcontext.AppContext, v *viper.Viper) (*redis.Pool, error) {\n\tenabled := v.GetBool(RedisEnabledFlag)\n\tif !enabled {\n\t\treturn nil, nil\n\t}\n\n\tredisPassword := v.GetString(RedisPasswordFlag)\n\tredisHost := v.GetString(RedisHostFlag)\n\tredisPort := v.GetInt(RedisPortFlag)\n\tredisDBName := v.GetInt(RedisDBNameFlag)\n\tredisConnectTimeout := v.GetDuration(RedisConnectTimeoutFlag)\n\tredisSSLEnabled := v.GetBool(RedisSSLEnabledFlag)\n\tredisMaxIdle := v.GetInt(RedisMaxIdleFlag)\n\tredisIdleTimeout := v.GetDuration(RedisIdleTimeoutFlag)\n\n\t// Log the redis URI\n\ts := \"redis://:%s@%s:%d?db=%d\"\n\tredisURI := fmt.Sprintf(s, \"*****\", redisHost, redisPort, redisDBName)\n\tif redisPassword == \"\" {\n\t\ts = \"redis://%s:%d?db=%d\"\n\t\tredisURI = fmt.Sprintf(s, redisHost, redisPort, redisDBName)\n\t}\n\tappCtx.Logger().Info(\"Connecting to Redis\", zap.String(\"url\", redisURI))\n\n\t// Configure Redis TLS Config\n\tredisTLSConfig := tls.Config{\n\t\tMinVersion: tls.VersionTLS12,\n\t}\n\n\t// Redis Dial requires a minimal URI containing just the host and port\n\tredisURLTemplate := \"%s:%s\"\n\tredisURL := fmt.Sprintf(redisURLTemplate, redisHost, strconv.Itoa(redisPort))\n\n\tif testRedisErr := testRedisConnection(appCtx, redisURL, redisPassword, redisDBName, redisConnectTimeout, redisSSLEnabled, &redisTLSConfig); testRedisErr != nil {\n\t\treturn nil, testRedisErr\n\t}\n\n\tpool := &redis.Pool{\n\t\tMaxIdle: redisMaxIdle,\n\t\tIdleTimeout: redisIdleTimeout,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tconnection, connectionErr := redis.Dial(\n\t\t\t\t\"tcp\",\n\t\t\t\tredisURL,\n\t\t\t\tredis.DialDatabase(redisDBName),\n\t\t\t\tredis.DialPassword(redisPassword),\n\t\t\t\tredis.DialConnectTimeout(redisConnectTimeout),\n\t\t\t\tredis.DialUseTLS(redisSSLEnabled),\n\t\t\t\tredis.DialTLSConfig(&redisTLSConfig),\n\t\t\t)\n\t\t\tif connectionErr != nil {\n\t\t\t\treturn nil, connectionErr\n\t\t\t}\n\t\t\treturn connection, nil\n\t\t},\n\t}\n\n\treturn pool, nil\n}", "func InitRedis() {\n\tclient = redis.NewClient(&redis.Options{\n\t\tAddr: \"localhost:6379\", //default port of redis-server; lo-host when same machine\n\t})\n\n\ttileClient = redis.NewClient(&redis.Options{\n\t\tAddr: \"127.0.0.1:9851\",\n\t\t// OnConnect: func(conn *redis.Conn) error {\n\t\t//something here if needed on connect\n\t\t// },\n\t})\n\n}", "func NewClient(options Options) (*Client, error) {\n\trdb := redis.NewClient(&redis.Options{\n\t\tNetwork: options.Network,\n\t\tAddr: options.Addr,\n\t\tDialer: options.Dialer,\n\t\tOnConnect: options.OnConnect,\n\t\tPassword: options.Password,\n\t\tDB: options.DB,\n\t\tMaxRetries: options.MaxRetries,\n\t\tMinRetryBackoff: options.MinRetryBackoff,\n\t\tMaxRetryBackoff: options.MaxRetryBackoff,\n\t\tDialTimeout: options.DialTimeout,\n\t\tReadTimeout: options.ReadTimeout,\n\t\tWriteTimeout: options.WriteTimeout,\n\t\tPoolSize: options.PoolSize,\n\t\tMinIdleConns: options.MinIdleConns,\n\t\tMaxConnAge: options.MaxConnAge,\n\t\tPoolTimeout: options.PoolTimeout,\n\t\tIdleTimeout: options.IdleTimeout,\n\t\tIdleCheckFrequency: options.IdleCheckFrequency,\n\t\tTLSConfig: options.TLSConfig,\n\t})\n\n\t// ping test\n\tresult, err := rdb.Ping().Result()\n\n\tif err != nil {\n\t\trdb.Close()\n\t\treturn nil, fmt.Errorf(\"%w : %v\", ErrConnectionFailed, err)\n\t}\n\n\tif result != \"PONG\" {\n\t\trdb.Close()\n\t\treturn nil, ErrConnectionFailed\n\t}\n\n\tclient := &Client{\n\t\trdb: rdb,\n\t}\n\n\terr = client.init()\n\tif err != nil {\n\t\tclient.Close()\n\t\treturn nil, fmt.Errorf(\"%w : %v\", ErrDatabaseInit, err)\n\t}\n\n\treturn client, nil\n}", "func initCmdRedis() error {\n\tvar err error\n\tcmdDb, err = redis.Dial(\"tcp\", \"127.0.0.1:6379\")\n\treturn err\n}", "func (p *CockroachDriver) Open() error {\n\tvar err error\n\tp.dbConn, err = sql.Open(\"postgres\", p.connStr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (client *Client) OpenConnection(address string) error {\n\n\tif !strings.HasSuffix(address, \".sock\") {\n\t\taddress += \".sock\"\n\t}\n\n\traddr, err := net.ResolveUnixAddr(\"unix\", address)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconn, err := net.DialUnix(\"unix\", nil, raddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient.Connection = conn\n\tclient.LocalAddress = nil\n\treturn nil\n}", "func Open(options Config) (*DB, error) {\n\tbyDuration, err := resolutionsByDuration(options.Resolutions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif options.ScanSize <= 0 {\n\t\toptions.ScanSize = defaultScanSize\n\t}\n\tpool := new(redis.Pool)\n\tif err := pool.ParseURL(options.Redis); err != nil {\n\t\treturn nil, err\n\t}\n\tdb := DB{\n\t\tredis: pool,\n\t\tscanSize: options.ScanSize,\n\t\tkeyPrefix: options.KeyPrefix,\n\t\tresolutions: byDuration,\n\t}\n\tdb.Scanner = evdb.NewScanner(&db)\n\treturn &db, nil\n}", "func NewRedisConn() (*RedisPool, error) {\n\tredisPassword := redis.DialPassword(redisPassword)\n\n\tpool := &redis.Pool{\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tc, err := redis.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", redisHost, redisPort), redisPassword)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif _, err := c.Do(\"SELECT\", redisNamespace); err != nil {\n\t\t\t\tc.Close()\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn c, nil\n\t\t},\n\t\tTestOnBorrow: func(c redis.Conn, t time.Time) error {\n\t\t\tif time.Since(t) < time.Minute {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t_, err := c.Do(\"PING\")\n\t\t\treturn err\n\t\t},\n\t}\n\n\t_, err := pool.Get().Do(\"PING\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &RedisPool{\n\t\tpool: pool,\n\t}, nil\n}", "func (o *Orm) GetRedisConn() (*mantle.RedisConn, error) {\n\tsettings := getSettings(o)\n\tredisPool := redisConns(settings)\n\treturn redisPool.GetClient()\n}", "func New(connectionString string, l *zap.SugaredLogger) Client {\n\tp := &redis.Pool{\n\t\tMaxIdle: 3,\n\t\tIdleTimeout: 240 * time.Second,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tc, err := redis.DialURL(connectionString)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn c, err\n\t\t},\n\t\tTestOnBorrow: func(c redis.Conn, t time.Time) error {\n\t\t\t_, err := c.Do(\"PING\")\n\t\t\treturn err\n\t\t},\n\t}\n\n\treturn &redisClient{pool: p, logger: l}\n}", "func (r *RedisSession) Conn() *redis.Conn {\n\treturn r.Conn()\n}", "func (c *MysqlClient) OpenCon(config config.Config, logger *log.Logger) error {\n\tconStr := fmt.Sprintf(\n\t\t\"%s:%s@(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local\",\n\t\tconfig.DBUser,\n\t\tconfig.DBPassword,\n\t\tconfig.DBHost,\n\t\tconfig.DBPort,\n\t\tconfig.DBName,\n\t)\n\tdb, err := gorm.Open(config.DBDriver, conStr)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to open db connection\")\n\t}\n\tdb.LogMode(true)\n\tdb.SetLogger(NewGormLogger(logger))\n\n\tc.conn = db\n\tc.config = config\n\tc.logger = logger\n\treturn nil\n}", "func openSession() (*mgo.Session, error) {\n\thost := os.Getenv(\"MONGODB_URI\")\n\tsession, err := mgo.Dial(host)\n\treturn session, err\n}", "func (d *Driver) Open(name string) (driver.Conn, error) {\n\tc, err := Open(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.BusyTimeout(500)\n\treturn &connImpl{c}, nil\n}", "func RedisClient(addr string, password string, db int) (*redis.Client, error) {\n\tvar client *redis.Client\n\tclient = redis.NewClient(&redis.Options{\n\t\tAddr: addr,\n\t\tPassword: password,\n\t\tDB: db,\n\t})\n\t_, err := client.Ping().Result()\n\tif err != nil {\n\t\treturn client, err\n\t}\n\treturn client, nil\n}", "func (r *rds) Connect(confs config.GlobalConfig) error {\n\tvar err error\n\n\tonce.Do(func() {\n\t\tlogger = zapLogger.GetZapLogger(confs.Debug())\n\n\t\tr.db = redis.NewClient(&redis.Options{\n\t\t\tDB: confs.Redis.DB,\n\t\t\tAddr: confs.Redis.Host,\n\t\t\tUsername: confs.Redis.Username,\n\t\t\tPassword: confs.Redis.Password,\n\t\t})\n\n\t\tif err = r.db.Ping(context.Background()).Err(); err != nil {\n\t\t\tzapLogger.Prepare(logger).\n\t\t\t\tDevelopment().\n\t\t\t\tLevel(zap.ErrorLevel).\n\t\t\t\tCommit(err.Error())\n\t\t}\n\t})\n\n\treturn err\n}", "func (c *Connection) Open() (err error) {\n\t// Calculate the address of the server, as required by the Dial methods:\n\tbrokerAddress := fmt.Sprintf(\"%s:%d\", c.BrokerHost, c.BrokerPort)\n\n\t// Create the socket:\n\tvar socket io.ReadWriteCloser\n\tif c.UseTLS {\n\t\tsocket, err = tls.Dial(\"tcp\", brokerAddress, &tls.Config{\n\t\t\tServerName: c.BrokerHost,\n\t\t\tInsecureSkipVerify: c.InsecureTLS,\n\t\t})\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\n\t\t\t\t\"can't create TLS connection to host '%s' and port %d: %s\",\n\t\t\t\tc.BrokerHost,\n\t\t\t\tc.BrokerPort,\n\t\t\t\terr.Error(),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tsocket, err = net.Dial(\"tcp\", brokerAddress)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\n\t\t\t\t\"can't create TCP connection to host '%s' and port %d: %s\",\n\t\t\t\tc.BrokerHost,\n\t\t\t\tc.BrokerPort,\n\t\t\t\terr.Error(),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Prepare the options:\n\tvar options []func(*stomp.Conn) error\n\tif c.UserName != \"\" {\n\t\toptions = append(options, stomp.ConnOpt.Login(c.UserName, c.UserPassword))\n\t}\n\n\t// Create the STOMP connection:\n\tc.connection, err = stomp.Connect(socket, options...)\n\tif err != nil {\n\t\terr = fmt.Errorf(\n\t\t\t\"can't create STOMP connection to host '%s' and port %d: %s\",\n\t\t\tc.BrokerHost,\n\t\t\tc.BrokerPort,\n\t\t\terr.Error(),\n\t\t)\n\t\treturn\n\t}\n\n\treturn\n}", "func (bdm *MySQLDBManager) OpenConnection() error {\n\t//bdm.Logger.Trace.Println(\"open connection for \" + reason)\n\tif bdm.openedConn {\n\t\treturn nil\n\t}\n\t// real connection will be done when first object is created\n\tbdm.openedConn = true\n\n\tbdm.conn = nil\n\n\treturn nil\n}", "func GetConnToControlDB() (conn redis.Conn) {\n\trepo = Get()\n\tconn = repo.Get()\n\tconn.Do(\"SELECT\", config.RerestConf.RedisDatabaseControl)\n\treturn\n}", "func Connect() error {\n\tredisHost := os.Getenv(\"REDIS_HOST\")\n\tredisPassword := os.Getenv(\"REDIS_PASSWORD\")\n\tredisPort := os.Getenv(\"REDIS_PORT\")\n\n\t// create a client instance\n\tClient = redis.NewClient(&redis.Options{\n\t\tAddr: redisHost + \":\" + redisPort,\n\t\tPassword: redisPassword,\n\t\tDB: 0,\n\t})\n\n\t// ping the server\n\t_, pingError := Client.Ping(ctx).Result()\n\tif pingError != nil {\n\t\treturn pingError\n\t}\n\n\treturn nil\n}", "func (c *Client) Connect(addr string, port int, password string) error {\n\tif addr == \"\" {\n\t\treturn errors.New(\"redis.Client.Init: addr cannot be empty\")\n\t}\n\tif port < 1024 || port > 65534 {\n\t\treturn errors.New(\"redis.Client.Init: port must in range [1024, 65534]\")\n\t}\n\tif c.isConnected {\n\t\tc.Client.Close()\n\t\tc.isConnected = false\n\t}\n\tc.Client = redis.NewClient(&redis.Options{\n\t\tAddr: addr + \":\" + strconv.Itoa(port),\n\t\tPassword: password,\n\t\tDB: 0,\n\t})\n\tif err := c.Client.Ping().Err(); err != nil {\n\t\treturn err\n\t}\n\tc.isConnected = true\n\treturn nil\n}", "func (r *Ricochet) ConnectOpen(conn net.Conn, host string) (*OpenConnection, error) {\n\toc, err := r.negotiateVersion(conn, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toc.OtherHostname = host\n\tr.newconns <- oc\n\treturn oc, nil\n}", "func NewRedisConnectionCreator(schema *graphql.Schema, redisPool RedisPool, config graphqlws.ConnectionConfig) graphqlws.ConnectionFactory {\n\treturn &redisConnectionFactory{\n\t\tschema: schema,\n\t\tpool: redisPool,\n\t\tconfig: config,\n\t}\n}", "func NewRedis(\n\tnetwork string, // : \"tcp\", \"tcp4\" or \"tcp6\"\n\taddr string, // : address of Redis server\n\tconf *Config, // : configurations\n) (\n\tr *Redis, // : implements data.CXDS\n\terr error, // : error if any\n) {\n\n\tif conf == nil {\n\t\tconf = NewConfig() // use defaults\n\t}\n\n\tif err = conf.Validate(); err != nil {\n\t\treturn\n\t}\n\n\tvar pool *radix.Pool\n\tpool, err = radix.NewPool(network, addr, conf.Size, conf.Opts...)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar rs Redis\n\trs.pool = pool\n\trs.expire = int64(conf.Expire / time.Second)\n\trs.expireFunc = conf.ExpireFunc\n\trs.scanCount = conf.ScanCount\n\n\tif err = rs.loadScripts(); err != nil {\n\t\tpool.Close()\n\t\treturn\n\t}\n\n\tif err = rs.subscribeExpiredEvents(conf); err != nil {\n\t\tpool.Close()\n\t\treturn\n\t}\n\n\tif err = rs.loadStat(); err != nil {\n\t\tpool.Close()\n\t\treturn\n\t}\n\n\tif rs.isSafeClosed, err = rs.getSafeClosed(); err != nil {\n\t\tpool.Close()\n\t\treturn\n\t}\n\n\tif err = rs.setSafeClosed(false); err != nil {\n\t\tpool.Close()\n\t\treturn\n\t}\n\n\tr = &rs\n\treturn\n}", "func (db *mongoDataBase) OpenConnection() error {\n\n\tlog.Logger.Info().Msg(\"Starting MongoDB connection\")\n\tvar url = \"mongodb+srv://hola:[email protected]/test\"\n\tclientOptions := options.Client().ApplyURI(url)\n\n\tctx, cancelFunc := context.WithTimeout(context.Background(), config.Timeout)\n\tdefer cancelFunc()\n\tclient, err := mongo.Connect(ctx, clientOptions)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Error on connection to mongoDB\")\n\t}\n\terr = client.Ping(ctx, readpref.Primary())\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Error when it did the ping to mongoDB\")\n\t}\n\n\tdb.databaseConnection = client.Database(\"test\")\n\tlog.Logger.Info().Msg(\"MongoDB UP\")\n\treturn nil\n}", "func GetConnection() *gredis.Client {\n\tif connection == nil {\n\t\tvar err error\n\t\tconnection, err = newConnection()\n\t\tif err != nil {\n\t\t\t//fatal\n\t\t}\n\t}\n\treturn connection\n}", "func NewClient(ctx context.Context, redisURL string) (*Client, error) {\n\tif redisURL == \"\" {\n\t\tredisURL = os.Getenv(\"REDIS_URL\")\n\t}\n\trURL, err := url.Parse(redisURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tredisPw, _ := rURL.User.Password()\n\n\tif rURL.Host == \"\" {\n\t\treturn nil, fmt.Errorf(\"Redis URL incorrect\")\n\t}\n\n\topt := &redis.Options{\n\t\tAddr: rURL.Host,\n\t\tPassword: redisPw,\n\t\tDB: 0,\n\t\tMaxRetries: 3,\n\t}\n\n\tif rURL.Scheme == \"rediss\" {\n\t\topt.TLSConfig = &tls.Config{\n\t\t\tMinVersion: 0,\n\t\t\tInsecureSkipVerify: true,\n\t\t}\n\t}\n\n\tclient := redis.NewClient(opt)\n\n\terr = client.Ping(ctx).Err()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Client{\n\t\tclient: client,\n\t}, nil\n}", "func (rc *RedisClient) GetConn() redis.Conn {\n\treturn rc.pool.Get()\n}", "func newRedisClient(options *redis.Options) client {\n\treturn &redisClient{\n\t\tclient: redis.NewClient(options),\n\t}\n}", "func (c *JSONRPCSignalClient) Open(url string) (<-chan struct{}, error) {\n\tconn, _, err := websocket.DefaultDialer.Dial(url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.jc = jsonrpc2.NewConn(c.context, websocketjsonrpc2.NewObjectStream(conn), c)\n\treturn c.jc.DisconnectNotify(), nil\n}", "func (d *boltDriver) Open(connStr string) (driver.Conn, error) {\n\treturn newBoltConn(connStr, d) // Never use pooling when using SQL driver\n}", "func Open(dataSourceName string) (*DB, error) {\n\tdb, err := mgo.Dial(dataSourceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DB{db}, nil\n}", "func (r *Rediscli) ConnectFailoverRedis() *redis.Cmdable {\n\tvar redisdb redis.Cmdable\n\tredisdb = redis.NewFailoverClient(&redis.FailoverOptions{\n\t\tMasterName: \"mymaster\",\n\t\tSentinelAddrs: []string{\"172.16.134.20:8000\", \"172.16.134.20:8001\", \"172.16.134.20:8002\"},\n\t\tPassword: PWD,\n\t})\n\treturn &redisdb\n}" ]
[ "0.77541524", "0.73249066", "0.6974268", "0.6911695", "0.6755781", "0.6648931", "0.66248333", "0.6571725", "0.6532967", "0.64774966", "0.6466399", "0.64509517", "0.6411952", "0.6404125", "0.6399475", "0.63912493", "0.637248", "0.63523704", "0.6339209", "0.6310935", "0.63036615", "0.6274942", "0.6273089", "0.62450266", "0.6244977", "0.6218161", "0.6214822", "0.6214051", "0.61973256", "0.6181359", "0.6166794", "0.6158003", "0.6156237", "0.6146973", "0.61359334", "0.612542", "0.6121037", "0.60692596", "0.6054674", "0.60472476", "0.60230017", "0.6005054", "0.6004855", "0.5994803", "0.5994048", "0.5946102", "0.59294635", "0.5909622", "0.59085375", "0.59083897", "0.59021986", "0.59021986", "0.5887096", "0.58769083", "0.58679515", "0.58486456", "0.5843998", "0.58381695", "0.5833551", "0.583169", "0.58303356", "0.5806103", "0.58046484", "0.5801918", "0.57812774", "0.5778141", "0.57629955", "0.57571167", "0.57570183", "0.5740635", "0.57179683", "0.5716078", "0.56867576", "0.5680118", "0.5674993", "0.56712824", "0.56600016", "0.56538606", "0.56516623", "0.5651584", "0.565081", "0.564814", "0.5638729", "0.56313765", "0.56313235", "0.5611343", "0.5574807", "0.557251", "0.55717164", "0.5565377", "0.55605906", "0.5558242", "0.5555932", "0.5551439", "0.5540914", "0.5538491", "0.5521144", "0.55189806", "0.5516823", "0.55058247" ]
0.58127254
61
processCommand encode a cmd to resp and send to c
func (client *Client) processCommand(c net.Conn, cmd string, args ...string) (interface{}, error) { var b []byte b = commandBytes(cmd, args...) data, err := client.rawSend(c, b) return data, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *AGI) Command(cmd ...string) (resp *Response) {\n\tresp = &Response{}\n\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\n\tcmdString := strings.Join(cmd, \" \") + \"\\n\"\n\t_, err := a.w.Write([]byte(cmdString))\n\tif err != nil {\n\t\tresp.Error = errors.Wrap(err, \"failed to send command\")\n\t\treturn\n\t}\n\n\ts := bufio.NewScanner(a.r)\n\tfor s.Scan() {\n\t\traw := s.Text()\n\t\tif raw == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\t// Parse and store the result code\n\t\tpieces := responseRegex.FindStringSubmatch(raw)\n\t\tif pieces == nil {\n\t\t\tresp.Error = fmt.Errorf(\"failed to parse result: %s\", raw)\n\t\t\treturn\n\t\t}\n\n\t\t// Status code is the first substring\n\t\tresp.Status, err = strconv.Atoi(pieces[1])\n\t\tif err != nil {\n\t\t\tresp.Error = errors.Wrap(err, \"failed to get status code\")\n\t\t\treturn\n\t\t}\n\n\t\t// Result code is the second substring\n\t\tresp.ResultString = pieces[2]\n\t\t// FIXME: DTMF result maybe has \"#\"(35), \"*\" or \"\"(GetData #). But not perfect to just judge by contains string.\n\t\tif resp.ResultString != \"\" && !strings.Contains(resp.ResultString, \"35\") && !strings.Contains(resp.ResultString, \"*\") {\n\t\t\tresp.Result, err = strconv.Atoi(pieces[2])\n\t\t\tif err != nil {\n\t\t\t\tresp.Error = errors.Wrap(err, \"failed to parse status code as an integer\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\n\t\t// Value is the third (and optional) substring\n\t\twrappedVal := strings.TrimSpace(pieces[3])\n\t\tresp.Value = strings.TrimSuffix(strings.TrimPrefix(wrappedVal, \"(\"), \")\")\n\n\t\t// FIXME: handle multiple line return values\n\t\tbreak // nolint\n\t}\n\n\t// If the Status code is not 200, return an error\n\tif resp.Status != 200 {\n\t\tresp.Error = fmt.Errorf(\"Non-200 status code\")\n\t}\n\treturn\n}", "func sendCommand(conn *net.Conn, cmd string) []byte {\n\t//Write the command to the socket\n\tfmt.Fprintf(*conn, cmd)\n\t//Read the response\n\tresponse, err := bufio.NewReader(*conn).ReadString('\\n')\n\t//Check for any errors\n\tif err != nil {\n\t\t//Check for errors\n\t\tif err == io.EOF {\n\t\t\t/*\n\t\t\t * Cgminer sends out EOF after each call.\n\t\t\t * Catch this error because it's not really\n\t\t\t * an error that crash the program.\n\t\t\t */\n\n\t\t} else {\n\t\t\t//If the error is not EOF then warn about it\n\t\t\tlog.Println(\"Sending command error: \", err)\n\t\t}\n\t}\n\t//Create the byte array\n\tb := []byte(response)\n\n\t/*\n\t * Check for \\x00 to remove\n\t */\n\tif b[len(b)-1] == '\\x00' {\n\t\tb = b[0 : len(b)-1]\n\t}\n\n\t//Return the status we got from the server\n\treturn b\n}", "func (c *Client) ProcessRequest(req [][]byte) (err error) {\n\tvar (\n\t\tcommand Command\n\t)\n\tlog.Debugf(\"req:%v,%s\", strings.ToUpper(string(req[0])), req[1:])\n\tif len(req) == 0 {\n\t\tc.cmd = \"\"\n\t\tc.args = nil\n\t} else {\n\t\tc.cmd = strings.ToUpper(string(req[0]))\n\t\tc.args = req[1:]\n\t}\n\tif c.cmd != \"AUTH\" {\n\t\tif !c.isAuth {\n\t\t\tc.FlushResp(qkverror.ErrorNoAuth)\n\t\t\treturn nil\n\t\t}\n\t}\n\tlog.Debugf(\"command: %s argc:%d\", c.cmd, len(c.args))\n\tswitch c.cmd {\n\tcase \"AUTH\":\n\t\tif len(c.args) != 1 {\n\t\t\tc.FlushResp(qkverror.ErrorCommandParams)\n\t\t}\n\t\tif c.auth == \"\" {\n\t\t\tc.FlushResp(qkverror.ErrorServerNoAuthNeed)\n\t\t} else if string(c.args[0]) != c.auth {\n\t\t\tc.isAuth = false\n\t\t\tc.FlushResp(qkverror.ErrorAuthFailed)\n\t\t} else {\n\t\t\tc.isAuth = true\n\t\t\tc.w.FlushString(\"OK\")\n\t\t}\n\t\treturn nil\n\tcase \"MULTI\":\n\t\tlog.Debugf(\"client transaction\")\n\t\tc.txn, err = c.tdb.NewTxn()\n\t\tif err != nil {\n\t\t\tc.resetTxn()\n\t\t\tc.w.FlushBulk(nil)\n\t\t\treturn nil\n\t\t}\n\t\tc.isTxn = true\n\t\tc.cmds = []Command{}\n\t\tc.respTxn = []interface{}{}\n\t\tc.w.FlushString(\"OK\")\n\t\terr = nil\n\t\treturn\n\tcase \"EXEC\":\n\t\tlog.Debugf(\"command length : %d txn:%v\", len(c.cmds), c.isTxn)\n\t\tif len(c.cmds) == 0 || !c.isTxn {\n\t\t\tc.w.FlushBulk(nil)\n\t\t\tc.resetTxn()\n\t\t\treturn nil\n\t\t}\n\t\tfor _, cmd := range c.cmds {\n\t\t\tlog.Debugf(\"execute command: %s\", cmd.cmd)\n\t\t\tc.cmd = cmd.cmd\n\t\t\tc.args = cmd.args\n\t\t\tif err = c.execute(); err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\tc.txn.Rollback()\n\t\t\tc.w.FlushBulk(nil)\n\t\t} else {\n\t\t\terr = c.txn.Commit(context.Background())\n\t\t\tif err == nil {\n\t\t\t\tc.w.FlushArray(c.respTxn)\n\t\t\t} else {\n\t\t\t\tc.w.FlushBulk(nil)\n\t\t\t}\n\t\t}\n\t\tc.resetTxn()\n\t\treturn nil\n\tcase \"DISCARD\":\n\t\t// discard transactional commands\n\t\tif c.isTxn {\n\t\t\terr = c.txn.Rollback()\n\t\t}\n\t\tc.w.FlushString(\"OK\")\n\t\tc.resetTxn()\n\t\treturn err\n\tcase \"PING\":\n\t\tif len(c.args) != 0 {\n\t\t\tc.FlushResp(qkverror.ErrorCommandParams)\n\t\t}\n\t\tc.w.FlushString(\"PONG\")\n\t\treturn nil\n\t}\n\tif c.isTxn {\n\t\tcommand = Command{cmd: c.cmd, args: c.args}\n\t\tc.cmds = append(c.cmds, command)\n\t\tlog.Debugf(\"command:%s added to transaction queue, queue size:%d\", c.cmd, len(c.cmds))\n\t\tc.w.FlushString(\"QUEUED\")\n\t} else {\n\t\tc.execute()\n\t}\n\treturn\n\n}", "func (d *daemon) cmd(expectCode int, format string, args ...interface{}) (int, string, error) {\n\tid, err := d.text.Cmd(format, args...)\n\tif err != nil {\n\t\treturn 0, \"\", err\n\t}\n\td.text.StartResponse(id)\n\tdefer d.text.EndResponse(id)\n\tcode, msg, err := d.text.ReadResponse(expectCode)\n\treturn code, msg, err\n}", "func (gc *Gclient) ProcessCmdString(cmds []string) (string, error) {\n\tif gc.isCommunicatingToServer {\n\t\treturn \"\", ErrAnotherRequestProcessing\n\t}\n\n\tgc.commLock.Lock()\n\tgc.isCommunicatingToServer = true\n\tdefer gc.commLock.Unlock()\n\n\t// pos 0 is cmd, and pos 1,2,3... is args\n\tarrayLen := len(cmds)\n\tgc.writer.AppendArrayLength(arrayLen)\n\n\tfor _, d := range cmds {\n\t\tgc.writer.AppendBulkString(d)\n\t}\n\n\tgc.SetConnectionTimeout()\n\tgc.writer.Write()\n\n\t// Now let's wait for the response\n\tpr, err := gc.parser.Parse()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tres, err := gc.parser.FormatResultAsString(pr)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tgc.isCommunicatingToServer = false\n\treturn res, nil\n}", "func Command(cmd string, args ...string) (resp Response) {\n\tif k := len(args); k > 0 {\n\t\tif !strings.HasSuffix(cmd, \":\") {\n\t\t\tcmd += \":\"\n\t\t}\n\t\tif k%2 != 0 {\n\t\t\tlog.Fatal(\"[BUG] can't process command with odd number of arguments\")\n\t\t}\n\t\tfor i := 0; i < k; i = +2 {\n\t\t\tcmd += fmt.Sprintf(` %s=\"%s\"`, args[i], args[i+1])\n\t\t}\n\t}\n\n\t// Send a single command.\n\tsendCmd(cmd)\n\n\t// decode response\n\tjson.NewDecoder(fromPipe).Decode(&resp)\n\tfmt.Printf(\"Command: '%s'\\nResponse: %s\\n\\n\", cmd, resp)\n\n\treturn resp\n}", "func (server *Server) replyCmd(conn *ConnDriver, seq uint64, serverErr *Error, cmd string) {\n\n\trespHeader := NewResponseHeader()\n\trespHeader.Seq = seq\n\tswitch cmd {\n\tcase CmdTypePing:\n\t\trespHeader.ReplyType = ReplyTypePong\n\tcase CmdTypeAck:\n\t\trespHeader.ReplyType = ReplyTypeAck\n\tcase CmdTypeErr:\n\t\trespHeader.ReplyType = ReplyTypeAck\n\t\trespHeader.Error = serverErr\n\t\t// fmt.Println(\"replycmd send respHeader type error\")\n\t}\n\tconn.Lock()\n\terr := server.SendFrame(conn, respHeader, reflect.ValueOf(nil))\n\tconn.Unlock()\n\tif err != nil && !isNetError(err) {\n\t\tlog.Fatalln(\"encoding error:\" + err.Error())\n\t}\n\treturn\n}", "func GetCmd() (int){\n url := \"http://127.0.0.1:8080/\"\n resp, err := http.Get(url)\n if err != nil {\n //log.Fatalln(err)\n return 0\n }\n\n body, err := ioutil.ReadAll(resp.Body)\n\n if err != nil {\n //log.Fatalln(err)\n return 0\n }\n re := regexp.MustCompile(\"\\\\(cmd\\\\).*?\\\\(cmd\\\\)\")\n cmdParsed := re.FindStringSubmatch(string(body))\n cmd := strings.Join(cmdParsed, \" \")\n cmd = strings.ReplaceAll(cmd, \"(cmd)\", \"\")\n\n re = regexp.MustCompile(\"\\\\(arg\\\\).*?\\\\(arg\\\\)\")\n argParsed := re.FindStringSubmatch(string(body))\n arg := strings.Join(argParsed, \" \")\n arg = strings.ReplaceAll(arg, \"(arg)\", \"\")\n arg = html.UnescapeString(arg)\n\n\n // Debugging commmand input\n // fmt.Println(\"Command is: \" + cmd + \" \" + arg + \" \" + val)\n \n args, err := shellwords.Parse(arg)\n\n if err != nil{\n //log.Fatalln(err)\n return 0\n }\n\n var out []byte\n\n if cmd != \"\" && len(args) > 0 {\n out, err = exec.Command(cmd, args...).Output()\n\t} else if cmd != \"\" {\n out, err = exec.Command(cmd).Output()\n\t} \n\n if err != nil {\n //log.Fatalln(err)\n return 0\n }\n SendResponse(string(out))\n\n return 0\n}", "func (a *ServerQueryAPI) submitCommand(ctx context.Context, cmdObj *pendingCommand) (interface{}, error) {\n\tcmd := cmdObj.command\n\tresultObj := cmdObj.result\n\n\tselect {\n\tcase <-cmdObj.ctx.Done():\n\t\treturn nil, context.Canceled\n\tdefault:\n\t}\n\n\tif err := a.WriteCommand(cmd); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar resultBuf bytes.Buffer\n\ttimeoutTimer := time.After(defaultCommandTimeout)\n\tfor {\n\t\tvar response string\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, context.Canceled\n\t\tcase response = <-a.readQueue:\n\t\tcase <-timeoutTimer:\n\t\t\treturn nil, errors.New(\"command timed out\")\n\t\t}\n\n\t\tif strings.HasPrefix(response, \"error \") {\n\t\t\tresponse = response[len(\"error \"):]\n\t\t\trespObj := &callResult{}\n\n\t\t\tri, err := UnmarshalArguments(response[len(\"error \"):], respObj)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\trespObj = ri.(*callResult)\n\t\t\tif respObj.ErrorId != 0 {\n\t\t\t\treturn nil, errors.Wrap(errors.New(respObj.ErrorMessage), \"server error\")\n\t\t\t}\n\n\t\t\tif resultObj != nil {\n\t\t\t\tresultObj, err = UnmarshalArguments(resultBuf.String(), resultObj)\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\treturn resultObj, nil\n\t\t}\n\n\t\tresultBuf.WriteString(\" \" + response)\n\t}\n}", "func (c *Easee) CommandResponse(i json.RawMessage) {\n\tvar res easee.SignalRCommandResponse\n\n\tif err := json.Unmarshal(i, &res); err != nil {\n\t\tc.log.ERROR.Printf(\"invalid message: %s %v\", i, err)\n\t\treturn\n\t}\n\tc.log.TRACE.Printf(\"CommandResponse %s: %+v\", res.SerialNumber, res)\n\n\tselect {\n\tcase c.cmdC <- res:\n\tdefault:\n\t}\n}", "func (m *Mock) Control(c Command) (r Response) {\n\treqbytes := c.Encode()\n\treqbytes = append(reqbytes, '\\n')\n\tif _, err := m.rw.Write(reqbytes); err != nil {\n\t\tthrowMockError(\"Short write while sending command\", err)\n\t}\n\tif err := m.rw.Flush(); err != nil {\n\t\tthrowMockError(\"Short write while flushing command to writer\", err)\n\t}\n\tlog.Printf(\"Sent '%s'\", reqbytes[:len(reqbytes)-1])\n\n\tresbytes, err := m.rw.ReadBytes('\\n')\n\tlog.Printf(\"Got '%s'\", resbytes[:len(resbytes)-1])\n\tif err != nil {\n\t\tthrowMockError(\"Short read while receiving response\", err)\n\t}\n\n\tr = Response{Payload: make(map[string]interface{})}\n\tif err := json.Unmarshal(resbytes, &r.Payload); err != nil {\n\t\tthrowMockError(\"Couldn't decode response JSON\", err)\n\t}\n\treturn r\n}", "func Command() func(w http.ResponseWriter, r *http.Request) {\n\tschema := getJSONValidator(&commandSchemaStruct{})\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tbody, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\tjsonResponse(w, \"fail\", map[string]interface{}{\n\t\t\t\t\"message\": err.Error(),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\terr = validatePOSTRequest(body, schema)\n\t\tif err != nil {\n\t\t\tjsonResponse(w, \"fail\", map[string]interface{}{\n\t\t\t\t\"message\": err.Error(),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tvar responseStruct = &commandSchemaStruct{}\n\t\tjson.Unmarshal(body, responseStruct)\n\t\tif err != nil {\n\t\t\tjsonResponse(w, \"error\", map[string]interface{}{\n\t\t\t\t\"message\": err.Error(),\n\t\t\t})\n\t\t}\n\t\t// the json schema should ensure that these are the only possibilities\n\t\tif responseStruct.Command == \"start\" {\n\t\t\terr = container.ExecuteCode()\n\t\t\tif err != nil {\n\t\t\t\tjsonResponse(w, \"error\", map[string]interface{}{\n\t\t\t\t\t\"message\": err.Error(),\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tjsonResponse(w, \"success\", map[string]interface{}{\n\t\t\t\t\"message\": \"code started\",\n\t\t\t})\n\t\t\treturn\n\t\t} else if responseStruct.Command == \"kill\" {\n\t\t\terr = container.KillCode()\n\t\t\tif err != nil {\n\t\t\t\tjsonResponse(w, \"error\", map[string]interface{}{\n\t\t\t\t\t\"message\": err.Error(),\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tjsonResponse(w, \"success\", map[string]interface{}{\n\t\t\t\t\"message\": \"code killed\",\n\t\t\t})\n\t\t\treturn\n\t\t} else {\n\t\t\tjsonResponse(w, \"error\", map[string]interface{}{\n\t\t\t\t\"message\": \"need either kill or start\",\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t}\n}", "func (m *Milight) sendCommand(cmd []byte) error {\n\tm.lastActivity = time.Now()\n\tseq := m.getSeqNum()\n\tpacket := []byte{0x80, 0x00, 0x00, 0x00, 0x11, m.sessionID[0], m.sessionID[1], 0x00, seq, 0x00}\n\tpacket = append(packet, cmd...)\n\tpacket = append(packet, m.zone, 0x00)\n\tpacket = append(packet, checksum(packet))\n\t_, err := m.conn.Write(packet)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuf := make([]byte, 1024)\n\tm.conn.SetReadDeadline(time.Now().Add(defaultReadDeadline))\n\tn, err := m.conn.Read(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcommandResponse := []byte{0x88, 0x00, 0x00, 0x00, 0x03, 0x00, seq, 0x00}\n\tif n != len(commandResponse) {\n\t\treturn ErrInvalidResponse\n\t}\n\tif !bytes.Equal(commandResponse, buf[:n]) {\n\t\treturn ErrInvalidResponse\n\t}\n\treturn nil\n}", "func (proto *Protocol) ProcessCommand(line string) {\n\tline = strings.Trim(line, \"\\r\\n\")\n\tproto.logf(\"Processing line: %s\", line)\n\n\twords := strings.Split(line, \" \")\n\tif len(words) < 2 {\n\t\tproto.logf(\"Unable to parse line\")\n\t\tt := \"*\"\n\t\tif len(words) > 0 {\n\t\t\tt = words[0]\n\t\t}\n\t\tproto.Responses <- ResponseUnrecognisedCommand(t)\n\t\treturn\n\t}\n\n\ttag := words[0]\n\tcommand := strings.ToUpper(words[1])\n\targs := strings.Join(words[2:len(words)], \" \")\n\tproto.logf(\"In state %d, got tag '%s' for command '%s', args '%s'\", proto.State, tag, command, args)\n\n\tcmd := ParseCommand(strings.TrimSuffix(line, \"\\r\\n\"))\n\tproto.Command(cmd)\n}", "func (s *client) processCommand(ctx context.Context, sc *protos2.SignedCommand) (*protos2.CommandResponse, error) {\n\tlogger.Debugf(\"get view service client...\")\n\tconn, client, err := s.ViewServiceClient.CreateViewClient()\n\tlogger.Debugf(\"get view service client...done\")\n\tif conn != nil {\n\t\tlogger.Debugf(\"get view service client...got a connection\")\n\t\tdefer conn.Close()\n\t}\n\tif err != nil {\n\t\tlogger.Errorf(\"failed creating view client [%s]\", err)\n\t\treturn nil, errors.Wrap(err, \"failed creating view client\")\n\t}\n\n\tlogger.Debugf(\"process command [%s]\", sc.String())\n\tscr, err := client.ProcessCommand(ctx, sc)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed view client process command [%s]\", err)\n\t\treturn nil, errors.Wrap(err, \"failed view client process command\")\n\t}\n\n\tlogger.Debugf(\"parse answer [%s]\", hash2.Hashable(scr.Response).String())\n\tcommandResp := &protos2.CommandResponse{}\n\terr = proto.Unmarshal(scr.Response, commandResp)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to unmarshal command response [%s]\", err)\n\t\treturn nil, errors.Wrapf(err, \"failed to unmarshal command response\")\n\t}\n\tif commandResp.GetErr() != nil {\n\t\tlogger.Errorf(\"error from view during process command: %s\", commandResp.GetErr().GetMessage())\n\t\treturn nil, errors.Errorf(\"error from view during process command: %s\", commandResp.GetErr().GetMessage())\n\t}\n\n\tlogger.Debugf(\"process command [%s] done\", sc.String())\n\treturn commandResp, nil\n}", "func (c *Connection) Cmd(command string, arg string) (code uint, response string, err error) {\n\t// Format command to be sent to the server.\n\tformattedCommand := command + \" \" + arg + CRLF\n\n\t// Send command to the server.\n\t_, err = c.control.Write([]byte(formattedCommand))\n\tif err != nil {\n\t\treturn 0, \"\", err\n\t}\n\n\t// Process the response.\n\treader := bufio.NewReader(c.control)\n\tregex := regexp.MustCompile(\"[0-9][0-9][0-9] \")\n\tfor {\n\t\tln, err := reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\treturn 0, \"\", err\n\t\t}\n\n\t\tresponse += ln\n\t\tif regex.MatchString(ln) {\n\t\t\tbreak\n\t\t}\n\t}\n\tt, err := strconv.Atoi(response[0:3])\n\tif err != nil {\n\t\treturn 0, response, err\n\t}\n\treturn uint(t), response, err\n}", "func generateCommandResponse(t *testing.T) string {\n\tdataBytes := []byte{}\n\tdataBytes = append(dataBytes, []byte(\"event: message\\n\")...)\n\n\tactionObj := model.PlanOutput{\n\t\tAction: \"Command Execution\",\n\t\tActionInput: struct {\n\t\t\tCommand string `json:\"command\"`\n\t\t\tNodes []string `json:\"nodes\"`\n\t\t}{\"df -h\", []string{\"localhost\"}},\n\t}\n\tactionJson, err := json.Marshal(actionObj)\n\tif err != nil {\n\t\trequire.NoError(t, err)\n\t}\n\n\tobj := struct {\n\t\tContent string `json:\"content\"`\n\t\tRole string `json:\"role\"`\n\t}{\n\t\tContent: string(actionJson),\n\t\tRole: \"assistant\",\n\t}\n\tjson, err := json.Marshal(obj)\n\tif err != nil {\n\t\trequire.NoError(t, err)\n\t}\n\n\tdata := fmt.Sprintf(`{\"id\":\"1\",\"object\":\"completion\",\"created\":1598069254,\"model\":\"gpt-4\",\"choices\":[{\"index\": 0, \"delta\":%v}]}`, string(json))\n\tdataBytes = append(dataBytes, []byte(\"data: \"+data+\"\\n\\n\")...)\n\n\tdataBytes = append(dataBytes, []byte(\"event: done\\n\")...)\n\tdataBytes = append(dataBytes, []byte(\"data: [DONE]\\n\\n\")...)\n\n\treturn string(dataBytes)\n}", "func sendCommand(command CommandRequest) *CommandResponse {\n conn, err := net.Dial(\"tcp\", \"127.0.0.1:5000\")\n if err != nil {\n LOG[ERROR].Println(StatusText(StatusConnectionError), err, \"retrying...\")\n // Sleep to allow some time for new master startup\n time.Sleep(5 * time.Second)\n conn, err = net.Dial(\"tcp\", \"127.0.0.1:5000\")\n }\n if err != nil {\n LOG[ERROR].Println(StatusText(StatusConnectionError), err)\n return nil\n }\n defer conn.Close()\n\n encoder := gob.NewEncoder(conn)\n err = encoder.Encode(command)\n if err != nil {\n LOG[ERROR].Println(StatusText(StatusEncodeError), err)\n return nil\n }\n\n var response CommandResponse\n decoder := gob.NewDecoder(conn)\n err = decoder.Decode(&response)\n if err != nil {\n LOG[ERROR].Println(StatusText(StatusDecodeError), err)\n return nil\n }\n return &response\n}", "func (c *ServerConn) cmd(expected int, format string, args ...interface{}) (int, string, error) {\n\t_, err := c.conn.Cmd(format, args...)\n\tif err != nil {\n\t\treturn 0, \"\", err\n\t}\n\n\treturn c.conn.ReadResponse(expected)\n}", "func ProcessTCPCommands(config *Configuration, connection net.Conn) {\n Log.LogFunctionName()\n defer connection.Close()\n Log.Infof(\"Accepted C&C connection from %s.\", connection.RemoteAddr().String())\n helpString := \">>> Commands: 'status', 'stop', 'restart', 'help', 'version', 'profiles', 'goprocs'.\\n\"\n var error error\n timeout, error := time.ParseDuration(\"30s\")\n if error != nil { Log.Errorf(\"Error parsing duration: %v.\", error) }\n\n var commandBuffer string\n buffer := make([]byte, 256)\n for error == nil {\n connection.SetDeadline(time.Now().Add(timeout))\n var n int\n n, error = connection.Read(buffer)\n if n <= 0 && error != nil { break }\n Log.Debugf(\"Read %d characters.\", n)\n\n commandBuffer += string(buffer[:n])\n index := strings.Index(commandBuffer, \"\\n\")\n for index > -1 && error == nil {\n command := strings.ToLower(commandBuffer[:index])\n command = strings.TrimSpace(command)\n if index < len(commandBuffer)-1 {\n commandBuffer = commandBuffer[index+1:]\n } else {\n commandBuffer = \"\"\n }\n index = strings.Index(commandBuffer, \"\\n\")\n\n Log.Infof(\"C&C command '%s'.\", command)\n switch command {\n case \"hello\":\n _, error = connection.Write([]byte(\">>> Hello.\\n\"))\n case \"version\":\n s := fmt.Sprintf(\">>> Software version %s.\\n\", Util.CompileVersion())\n _, error = connection.Write([]byte(s))\n case \"status\":\n s := fmt.Sprintf(\"%s.\\n\", config.ServerStatusString())\n _, error = connection.Write([]byte(s))\n case \"profiles\":\n s := GetProfileNames()\n _, error = connection.Write([]byte(s))\n case \"goprocs\":\n s := GetGoprocs()\n _, error = connection.Write([]byte(s))\n case \"stop\":\n _, error = connection.Write([]byte(\">>> Stopping.\\n\"))\n myself, _ := os.FindProcess(os.Getpid())\n myself.Signal(syscall.SIGHUP)\n case \"\", \" \", \"\\n\":\n case \"help\", \"?\", \"h\":\n _, error = connection.Write([]byte(helpString))\n default:\n message := fmt.Sprintf(\">>> Unknown command '%s'.\\n\", command)\n _, error = connection.Write([]byte(message))\n if error != nil { break; }\n _, error = connection.Write([]byte(helpString))\n }\n }\n }\n if error != nil {\n Log.Debugf(\"Connection closed with error %v.\", error)\n } else {\n Log.Debugf(\"Connection closed without error.\")\n }\n}", "func encodeCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"encode\",\n\t\tShort: \"Encode a splice_info_section to binary\",\n\t\tArgs: func(cmd *cobra.Command, args []string) error {\n\t\t\tif len(args) != 1 {\n\t\t\t\treturn fmt.Errorf(\"requires a splice_info_section\")\n\t\t\t}\n\t\t\tif !strings.HasPrefix(args[0], \"<\") && !strings.HasPrefix(args[0], \"{\") {\n\t\t\t\treturn fmt.Errorf(\"splice_info_section must be in XML or JSON format\")\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tbin := args[0]\n\n\t\t\tvar sis *scte35.SpliceInfoSection\n\t\t\tvar err error\n\n\t\t\t// decode payload\n\t\t\tif strings.HasPrefix(bin, \"<\") {\n\t\t\t\terr = xml.Unmarshal([]byte(bin), &sis)\n\t\t\t} else {\n\t\t\t\terr = json.Unmarshal([]byte(bin), &sis)\n\t\t\t}\n\n\t\t\t// print encoded signal\n\t\t\t_, _ = fmt.Fprintf(os.Stdout, \"Base64: %s\\n\", sis.Base64())\n\t\t\t_, _ = fmt.Fprintf(os.Stdout, \"Hex : %s\\n\", sis.Hex())\n\n\t\t\t// and any errors\n\t\t\tif err != nil {\n\t\t\t\t_, _ = fmt.Fprintf(os.Stderr, \"Error: %s\\n\", err)\n\t\t\t}\n\t\t},\n\t}\n\treturn cmd\n}", "func (proto *Protocol) Command(command *Command) {\n\tswitch {\n\tcase proto.TLSPending && !proto.TLSUpgraded:\n\t\tproto.logf(\"Got command before TLS upgrade complete\")\n\t\tproto.Responses <- &Response{\"*\", Status(ResponseBYE), nil, \"\", nil}\n\t\tproto.State = LOGOUT\n\t\treturn\n\tcase \"CAPABILITY\" == command.command:\n\t\tproto.CAPABILITY(command)\n\t\treturn\n\tcase \"NOOP\" == command.command:\n\t\tproto.Responses <- &Response{command.tag, Status(ResponseOK), nil, \"\", nil}\n\t\treturn\n\tcase \"LOGOUT\" == command.command:\n\t\tproto.Responses <- &Response{\"*\", Status(ResponseBYE), nil, \"\", nil}\n\t\tproto.Responses <- &Response{command.tag, Status(ResponseOK), nil, \"\", nil}\n\t\tproto.State = LOGOUT\n\t\treturn\n\tcase PREAUTH == proto.State:\n\t\tswitch command.command {\n\t\tcase \"STARTTLS\":\n\t\t\tproto.STARTTLS(command)\n\t\t\treturn\n\t\tcase \"AUTHENTICATE\":\n\t\t\tproto.AUTHENTICATE(command)\n\t\t\treturn\n\t\tcase \"LOGIN\":\n\t\t\tproto.Responses <- &Response{command.tag, Status(ResponseBAD), nil, \"\", nil}\n\t\t\treturn\n\t\t}\n\t\tproto.logf(\"command not found in PREAUTH state\")\n\tcase AUTH == proto.State:\n\t\tswitch command.command {\n\t\tcase \"SELECT\":\n\t\tcase \"EXAMINE\":\n\t\tcase \"CREATE\":\n\t\tcase \"DELETE\":\n\t\tcase \"RENAME\":\n\t\tcase \"SUBSCRIBE\":\n\t\tcase \"UNSUBSCRIBE\":\n\t\tcase \"LIST\":\n\t\t\t// FIXME hook\n\t\t\tproto.Responses <- &Response{\"*\", nil, nil, `LIST (\\Noselect) \"/\" \"\"`, nil}\n\t\t\tproto.Responses <- &Response{command.tag, Status(ResponseOK), nil, \"\", nil}\n\t\t\treturn\n\t\tcase \"LSUB\":\n\t\tcase \"STATUS\":\n\t\tcase \"APPEND\":\n\t\t}\n\t\tproto.logf(\"command not found in AUTH state\")\n\tcase SELECTED == proto.State:\n\t\tswitch command.command {\n\t\tcase \"CHECK\":\n\t\tcase \"CLOSE\":\n\t\tcase \"EXPUNGE\":\n\t\tcase \"SEARCH\":\n\t\tcase \"FETCH\":\n\t\tcase \"STORE\":\n\t\tcase \"COPY\":\n\t\tcase \"UID\":\n\t\t}\n\t\tproto.logf(\"command not found in PREAUTH state\")\n\t}\n\n\tproto.logf(\"Command not recognised\")\n\tproto.Responses <- ResponseUnrecognisedCommand(\"*\") // FIXME should be tagged\n}", "func processCommand(cmd string) {\n\targs := strings.Split(strings.Trim(cmd, \"\\r\\n\"), \" \")\n\n\t//Compute distance to the customer\n\tif args[0] == \"PEERADDR\" {\n\t\tpeerAddr := args[1]\n\t\twords := strings.Split(peerAddr, \":\")\n\t\tgo dialPeer(peerAddr)\n\t\tgo dialHeart(words[0] + \":\" + nextNextPort(words[1]))\n\t}\n}", "func handleCmdResponse(cmd string, output []byte) (*DriverStatus, error) {\n\tstatus := &DriverStatus{\n\t\tVolume: v1.PersistentVolume{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\tLabels: map[string]string{},\n\t\t\t}}}\n\tif err := json.Unmarshal(output, status); err != nil {\n\t\tglog.Errorf(\"Failed to unmarshal output for command: %s, output: %q, error: %s\", cmd, string(output), err.Error())\n\t\treturn nil, err\n\t} else if status.Status == StatusNotSupported {\n\t\tglog.V(5).Infof(\"%s command is not supported by the driver\", cmd)\n\t\treturn nil, errors.New(status.Status)\n\t} else if status.Status != StatusSuccess {\n\t\terrMsg := fmt.Sprintf(\"%s command failed, status: %s, reason: %s\", cmd, status.Status, status.Message)\n\t\tglog.Errorf(errMsg)\n\t\treturn nil, fmt.Errorf(\"%s\", errMsg)\n\t}\n\n\treturn status, nil\n}", "func EncodeControlCmd(cmd OnionCommand) byte {\n\tswitch cmd {\n\tcase CREATE:\n\t\treturn byte(0)\n\tcase CREATED:\n\t\treturn byte(1)\n\tcase DESTROY:\n\t\treturn byte(2)\n\tdefault:\n\t\treturn byte(13)\n\t}\n}", "func processCommand(command string) error {\n\tcommandDelimited := strings.Split(command, \" \")\n\tlengthOfCommand := len(commandDelimited)\n\n\tvar err error\n\targuments := []string{}\n\tif lengthOfCommand < 1 {\n\t\terr := errors.New(UNSUPPORTED_COMMAND)\n\t\tfmt.Println(err.Error())\n\t\treturn err\n\t} else if lengthOfCommand == 1 {\n\t\tcommand = commandDelimited[0]\n\t} else {\n\t\tcommand = commandDelimited[0]\n\t\targuments = commandDelimited[1:]\n\t}\n\n\t// check if command is one of the allowed commands\n\tif numberOfArguments, exists := allowedCommands[command]; exists {\n\n\t\tif len(arguments) != numberOfArguments && numberOfArguments != 99 {\n\t\t\tfmt.Println(argumentsErrors[command].Error())\n\t\t\treturn argumentsErrors[command]\n\t\t}\n\n\t\tw := &ErrWrapper{}\n\n\n\t\t// after validation of number of arguments per command, perform the necessary command\n\t\tswitch command {\n\t\tcase \"login\":\n\t\t\tw.do(func() error {\n\t\t\t\tvar err error\n\t\t\t\tsessionId, err = user.Login(user.User{\n\t\t\t\t\tId: arguments[0],\n\t\t\t\t\tPassword: arguments[1],\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfmt.Println(\"Login Successfully\")\n\t\t\t\treturn nil\n\t\t\t})\n\t\tcase \"signup\":\n\t\t\treturn w.do(func () error {\n\t\t\t\terr := user.SignUp(user.UserSignUP{\n\t\t\t\t\tName: arguments[0],\n\t\t\t\t\tPassword: arguments[2],\n\t\t\t\t\tEmail: arguments[1],\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfmt.Println(\"Signup successfully\")\n\t\t\t\treturn nil\n\t\t\t})\t\t\n\t\tcase \"listjournal\":\n\t\t\treturn w.do(func() error {\n\t\t\t\tif jr == nil {\n\t\t\t\t\tif sessionId != nil {\n\t\t\t\t\t\tjr, err = journal.GetInstace(*(sessionId))\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn argumentsErrors[\"loginfirst\"]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tenteries, err := jr.ListEntries()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfor index, eachEntry := range enteries {\n\t\t\t\t\tfmt.Printf(\"%d %s %s \\n\", index, eachEntry.Time, eachEntry.ToRemeber)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\t\tcase \"createjournal\":\n\t\t\treturn w.do(func() error {\n\t\t\t\tif jr == nil {\n\t\t\t\t\tif sessionId != nil {\n\t\t\t\t\t\tjr, err = journal.GetInstace(*(sessionId))\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn argumentsErrors[\"loginfirst\"]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvar input string\n\t\t\t\tfor _, eachData := range arguments {\n\t\t\t\t\tinput = input + \" \" + eachData\n\t\t\t\t}\n\t\t\t\terr = jr.InputEntry(input)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\n\t\tcase \"removeuser\":\n\t\t\treturn w.do(func ()error{\n\t\t\t\treturn user.RemoveUser(arguments[0])\n\t\t\t})\n\t\t}\n\t} else {\n\t\terr := errors.New(UNSUPPORTED_COMMAND)\n\t\tfmt.Println(err.Error())\n\n\t\treturn err\n\t}\n\treturn errors.New(\"Not Reachable Code\")\n}", "func GetCommand(processNodePtr *nd.Node) {\n\tATA := &(*(*processNodePtr).ATAPtr)\n\tlogger := (*processNodePtr).Logger\n\tloggerByte := (*processNodePtr).LoggerByte\n\tloggerPerSec := (*processNodePtr).LoggerPerSec\n\tdestPortNum := (*processNodePtr).DestPortNum\n\tvmNumStr := (*processNodePtr).VmNumStr\n\tmyService := (*processNodePtr).MyService\n\n\tscanner := bufio.NewScanner(os.Stdin)\n\tbyteSent := 0\n\tfor {\n\t\tscanner.Scan()\n\t\tcommand := scanner.Text()\n\n\t\tif command == \"gossip\" {\n\t\t\tfmt.Println(\"Changing to Gossip\")\n\t\t\tloggerPerSec.Println(\"Changing to Gossip\")\n\t\t\tlogger.Println(\"Changing to Gossip\")\n\t\t\t*ATA = false\n\t\t\tbyteSent = PingMsg(*processNodePtr, (*processNodePtr).MsList, \"gossip\", destPortNum)\n\t\t\tloggerByte.Println(\"Command(Gossip) Ping ByteSent:\" + strconv.Itoa(byteSent) + \"bytes\")\n\n\t\t} else if command == \"ata\" {\n\t\t\tfmt.Println(\"Changing to ATA\")\n\t\t\t*ATA = true\n\t\t\tbyteSent = PingMsg(*processNodePtr, (*processNodePtr).MsList, \"ata\", destPortNum)\n\t\t\tloggerPerSec.Println(\"Changing to ATA\")\n\t\t\tlogger.Println(\"Changing to ATA\")\n\n\t\t\tloggerByte.Println(\"Command(ATA) Ping ByteSent:\" + strconv.Itoa(byteSent) + \"bytes\")\n\n\t\t} else if command == \"leave\" {\n\t\t\tfmt.Println(\"(Leave)Terminating vm_\", vmNumStr)\n\t\t\tloggerPerSec.Println(\"(Leave)Terminating vm_\" + vmNumStr)\n\t\t\tlogger.Println(\"(Leave)Terminating vm_\" + vmNumStr)\n\t\t\tos.Exit(1)\n\t\t} else if command == \"memberlist\" {\n\t\t\tfmt.Println(\"\\nMembership List: \\n\" + (*processNodePtr).MsList.PrintLog())\n\t\t\tloggerPerSec.Println(\"\\nMembership List: \\n\" + (*processNodePtr).MsList.PrintLog())\n\t\t\tlogger.Println(\"\\nMembership List: \\n\" + (*processNodePtr).PrintLog())\n\t\t} else if command == \"id\" {\n\t\t\tfmt.Println(\"Current IP and port:\", myService)\n\t\t\tloggerPerSec.Println(\"\\nCurrent IP and port: \" + myService + \"\\n\")\n\t\t\tlogger.Println(\"\\nCurrent IP and port:: \" + myService + \"\\n\")\n\t\t} else if command == \"-h\" {\n\t\t\tfmt.Println(\"gossip\t\t\t\t:\tchange the system into a gossip heartbeating\")\n\t\t\tfmt.Println(\"ata\t\t\t\t:\tchange the system into a All-to-All heartbeating\")\n\t\t\tfmt.Println(\"leave\t\t\t\t: \tvoluntarily leave the system. (halt)\")\n\t\t\tfmt.Println(\"memberlist\t\t\t: \tprint VM's memberlist to the terminal\")\n\t\t\tfmt.Println(\"id\t\t\t\t\t:\tprint current IP address and assigned Port number\")\n\t\t\tfmt.Println(\"heartbeat\t\t\t:\tprint the current heartbeat type\")\n\t\t\tfmt.Println(\"put <filename>\t\t: put a <filename> to the distributed system\")\n\t\t\tfmt.Println(\"pull <filename>\t: pull a <filename> from the distributed system and store in the the local folder\")\n\t\t\tfmt.Println(\"ls -l\t\t\t\t:\tprint the list of distributed files and its size in the current process\")\n\t\t\tfmt.Println(\"ls \t\t\t\t:\tprint the list of sdfsfile's in the system\")\n\t\t\tfmt.Println(\"ls <filename>\t\t:\tprint the list of IDs having a file <filename>\")\n\t\t\tfmt.Println(\"store\t\t\t\t:\tprint the list of distributed's in the process\")\n\t\t\tfmt.Println(\"remove <filename>\t:\tremove the <filename> from the system\")\n\t\t} else if command == \"heartbeat\" {\n\t\t\tif *ATA == true {\n\t\t\t\tfmt.Println(\"Current Heartbeating for this processor: ATA\")\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"Current Heartbeating for this processor: Gossip\")\n\t\t\t}\n\t\t} else if len(command) > 3 && command[:3] == \"put\" {\n\t\t\tfilename := command[4:]\n\t\t\tfs.Put(processNodePtr, filename, 1)\n\n\t\t} else if len(command) > 4 && command[:4] == \"pull\" {\n\t\t\tfilename := command[5:]\n\t\t\tfs.Pull(processNodePtr, filename, 1)\n\n\t\t} else if command == \"ls -l\" { // list file names and its size of the files stored in the distributed folder\n\t\t\tfiles, err := ioutil.ReadDir(processNodePtr.DistributedPath)\n\t\t\tCheckError(err)\n\n\t\t\tfor i, file := range files {\n\t\t\t\tfmt.Println(strconv.Itoa(i)+\". \"+file.Name()+\":\", file.Size(), \"bytes\")\n\t\t\t}\n\t\t} else if command[0:2] == \"ls\" {\n\t\t\tFilenames := fs.GetFileList(processNodePtr)\n\n\t\t\tif len(command) > 2 { // list all machine (VM) addresses where this file is currently being stored\n\t\t\t\tfilename := command[3:]\n\n\t\t\t\t_, exist := Filenames[filename]\n\n\t\t\t\tif !exist {\n\t\t\t\t\tfmt.Println(\"no such file exist in DFS\")\n\t\t\t\t} else {\n\t\t\t\t\tfor file, IPAddressList := range Filenames {\n\t\t\t\t\t\tif filename == file {\n\t\t\t\t\t\t\tfmt.Println(\"File \", file, \"is stored in the following Addresses:\")\n\t\t\t\t\t\t\tfor i, ID := range IPAddressList {\n\t\t\t\t\t\t\t\tfmt.Println(\"\t\", i, \":\", ID.IPAddress)\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} else { // list all file info\n\t\t\t\tfor file, IPAddressList := range Filenames {\n\t\t\t\t\tfmt.Println(\"File \", file, \"is stored in the following Addresses:\")\n\t\t\t\t\tfor i, ID := range IPAddressList {\n\t\t\t\t\t\tfmt.Println(\"\t\", i, \":\", ID.IPAddress)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else if command == \"store\" { //list all files currently being stored at this machine\n\t\t\tfmt.Println(\"Files currently stored at this machine:\")\n\t\t\tfor _, file := range *processNodePtr.DistributedFilesPtr {\n\t\t\t\tfmt.Println(file)\n\t\t\t}\n\n\t\t} else if len(command) > 6 && command[:6] == \"remove\" { // remove the file\n\t\t\tfilename := command[7:]\n\t\t\tfs.RemoveFile(processNodePtr, filename)\n\n\t\t} else {\n\t\t\tfmt.Println(\"Invalid Command\")\n\t\t}\n\t}\n}", "func processCommand(cmd string, conn net.Conn) {\n\targs := strings.Split(strings.Trim(cmd, \"\\r\\n\"), \" \")\n\n\t//Compute distance to the customer\n\tif args[0] == \"COMPUTE\" {\n\t\tvar distance float64\n\n\t\t//if not idle, return -1\n\t\tif virtualCar.Idle {\n\t\t\tpoint := util.ParseFloatCoordinates(args[1], args[2])\n\t\t\tdistance = point.DistanceTo(virtualCar.Location)\n\t\t} else {\n\t\t\tdistance = math.MaxFloat64\n\t\t}\n\t\twriter := bufio.NewWriter(conn)\n\t\tfmt.Println(args[3])\n\t\twriter.WriteString(\"COMPUTERESULT \" + virtualCar.Name + \" \" + strconv.FormatFloat(distance, 'f', 4, 64) + \" \" + args[1] + \" \" + args[2] + \" \" + args[3] + \"\\n\")\n\t\twriter.Flush()\n\t} else if args[0] == \"PICKUP\" {\n\t\t//Pickup the customer\n\t\tsource := util.ParseFloatCoordinates(args[1], args[2])\n\t\tdest := util.ParseFloatCoordinates(args[3], args[4])\n\t\tif source == nil || dest == nil {\n\t\t\tfmt.Println(\"Error: incorrect PICKUP format\")\n\t\t\tos.Exit(0)\n\t\t}\n\n\t\t//Start simulation\n\t\tgo util.DriveCustomer(&virtualCar, source, dest)\n\t}\n}", "func receiveCommand(conn net.Conn)(string, string, []Change){\n\tdec := json.NewDecoder(conn)\n p := &FrontEndRequest{}\n dec.Decode(p)\n\treturn p.Command, p.Argument, p.Changearray\n}", "func DecodeCommand(cell []byte) OnionCommand {\n\tswitch cell[0] {\n\tcase byte(0):\n\t\treturn CREATE\n\tcase byte(1):\n\t\treturn CREATED\n\tcase byte(2):\n\t\treturn DESTROY\n\tcase byte(3):\n\t\treturn EXTEND\n\tcase byte(4):\n\t\treturn EXTENDED\n\tcase byte(5):\n\t\treturn TRUNCATE\n\tcase byte(6):\n\t\treturn TRUNCATED\n\tcase byte(7):\n\t\treturn BEGIN\n\tcase byte(8):\n\t\treturn CONNECTED\n\tcase byte(9):\n\t\treturn DATA\n\tcase byte(10):\n\t\treturn RESPONSE\n\tcase byte(11):\n\t\treturn END\n\tcase byte(12):\n\t\treturn TEARDOWN\n\tdefault:\n\t\treturn UNKNOWN\n\t}\n}", "func send(c *Conn, cmd string) (string, error) {\n\t_, err := sendFull(c, []byte(cmd))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t//wait for response\n\tresp, err := c.bufReader.ReadString('\\n')\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn resp, nil\n}", "func command(c *fb.Context, w http.ResponseWriter, r *http.Request) (int, error) {\n\t// Upgrades the connection to a websocket and checks for fb.Errors.\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer conn.Close()\n\n\tvar (\n\t\tmessage []byte\n\t\tcommand []string\n\t)\n\n\t// Starts an infinite loop until a valid command is captured.\n\tfor {\n\t\t_, message, err = conn.ReadMessage()\n\t\tif err != nil {\n\t\t\treturn http.StatusInternalServerError, err\n\t\t}\n\n\t\tcommand = strings.Split(string(message), \" \")\n\t\tif len(command) != 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Check if the command is allowed\n\tallowed := false\n\n\tfor _, cmd := range c.User.Commands {\n\t\tif regexp.MustCompile(cmd).MatchString(command[0]) {\n\t\t\tallowed = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !allowed {\n\t\terr = conn.WriteMessage(websocket.TextMessage, cmdNotAllowed)\n\t\tif err != nil {\n\t\t\treturn http.StatusInternalServerError, err\n\t\t}\n\n\t\treturn 0, nil\n\t}\n\n\t// Check if the program is installed on the computer.\n\tif _, err = exec.LookPath(command[0]); err != nil {\n\t\terr = conn.WriteMessage(websocket.TextMessage, cmdNotImplemented)\n\t\tif err != nil {\n\t\t\treturn http.StatusInternalServerError, err\n\t\t}\n\n\t\treturn http.StatusNotImplemented, nil\n\t}\n\n\t// Gets the path and initializes a buffer.\n\tpath := c.User.Scope + \"/\" + r.URL.Path\n\tpath = filepath.Clean(path)\n\tbuff := new(bytes.Buffer)\n\n\t// Sets up the command executation.\n\tcmd := exec.Command(command[0], command[1:]...)\n\tcmd.Dir = path\n\tcmd.Stderr = buff\n\tcmd.Stdout = buff\n\n\t// Starts the command and checks for fb.Errors.\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, err\n\t}\n\n\t// Set a 'done' variable to check whetever the command has already finished\n\t// running or not. This verification is done using a goroutine that uses the\n\t// method .Wait() from the command.\n\tdone := false\n\tgo func() {\n\t\terr = cmd.Wait()\n\t\tdone = true\n\t}()\n\n\t// Function to print the current information on the buffer to the connection.\n\tprint := func() error {\n\t\tby := buff.Bytes()\n\t\tif len(by) > 0 {\n\t\t\terr = conn.WriteMessage(websocket.TextMessage, by)\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\t// While the command hasn't finished running, continue sending the output\n\t// to the client in intervals of 100 milliseconds.\n\tfor !done {\n\t\tif err = print(); err != nil {\n\t\t\treturn http.StatusInternalServerError, err\n\t\t}\n\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\n\t// After the command is done executing, send the output one more time to the\n\t// browser to make sure it gets the latest information.\n\tif err = print(); err != nil {\n\t\treturn http.StatusInternalServerError, err\n\t}\n\n\treturn 0, nil\n}", "func (nfo *info) sendCommand(conn *Connection) error {\n\t// Write.\n\tif _, err := conn.Write(nfo.msg.Serialize()); err != nil {\n\t\tLogger.Debug(\"Failed to send command.\")\n\t\treturn err\n\t}\n\n\t// Read - reuse input buffer.\n\theader := bytes.NewBuffer(make([]byte, MSG_HEADER_SIZE))\n\tif _, err := conn.Read(header.Bytes(), MSG_HEADER_SIZE); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Read(header, binary.BigEndian, &nfo.msg.MessageHeader); err != nil {\n\t\tLogger.Debug(\"Failed to read command response.\")\n\t\treturn err\n\t}\n\n\t// Logger.Debug(\"Header Response: %v %v %v %v\", t.Type, t.Version, t.Length(), t.DataLen)\n\tnfo.msg.Resize(nfo.msg.Length())\n\t_, err := conn.Read(nfo.msg.Data, len(nfo.msg.Data))\n\treturn err\n}", "func cmdHandler(c *Client, msg []byte) {\n\tlog.Infof(\"Received Message: %s ...\", msg[:int(math.Min(float64(len(msg)), 128))])\n\tlog.Debugf(\"Count of goroutines=%d\", runtime.NumGoroutine())\n\n\t// Decode JSON message\n\tvar cmd manager.PlayerCommand\n\terr := json.Unmarshal(msg, &cmd)\n\tif err != nil {\n\t\tsendStatusError(c, \"Message could not be decoded as JSON\", err.Error())\n\t\treturn\n\t}\n\n\tswitch cmd.Cmd {\n\tcase \"status\":\n\t\tsendStatusOKMsg(c, \"\") //, statusString[gp_daemon_status])\n\tcase \"pre_start\":\n\t\tpreStartCommand(c)\n\tcase \"start\":\n\t\tstartCommand(c)\n\tcase \"stop\":\n\t\tstopCommand(c)\n\tcase \"script\":\n\t\tscriptCommand(c, &cmd)\n\tcase \"getmd5\":\n\t\thandleGetMD5(c, &cmd)\n\tcase \"datafile\":\n\t\thandleDataFile(c, &cmd)\n\tcase \"nextchunk\":\n\t\thandleDataChunk(c, &cmd)\n\tcase \"get_results\":\n\t\tgetResultsCommand(c, &cmd)\n\tdefault:\n\t\tsendStatusError(c, fmt.Sprintf(\"Message not supported: %s ...\", msg[:int(math.Min(float64(len(msg)), 128))]), \"\")\n\t}\n\tlog.Debug(\"Message handled\")\n}", "func (s *Session) doCommand(ctx context.Context, name Name, f func(ctx context.Context, conn *grpc.ClientConn, header *headers.RequestHeader) (*headers.ResponseHeader, interface{}, error)) (interface{}, error) {\n\theader := s.nextCommandHeader(getPrimitiveID(name))\n\treturn s.doRequest(ctx, header, func(conn *grpc.ClientConn) (*headers.ResponseHeader, interface{}, error) {\n\t\treturn f(ctx, conn, header)\n\t})\n}", "func ProcessCommand(f *Context, cmd, arg, res string, l, fl int) int {\n\tcc := C.CString(cmd)\n\tdefer C.free(unsafe.Pointer(cc))\n\tca := C.CString(arg)\n\tdefer C.free(unsafe.Pointer(ca))\n\tcr := C.CString(res)\n\tdefer C.free(unsafe.Pointer(cr))\n\treturn int(C.avfilter_process_command((*C.struct_AVFilterContext)(f), cc, ca, cr, C.int(l), C.int(fl)))\n}", "func (p *Process) CmdBinary(pac teoapi.Packet) (err error) {\n\tvar request, responce cdb.KeyValue\n\terr = request.UnmarshalBinary(pac.Data())\n\tif err != nil {\n\t\treturn\n\t}\n\tresponce = request\n\tconst errNotFound = \"not found\"\n\tswitch request.Cmd {\n\n\tcase cdb.CmdSet:\n\t\tif err = p.tcdb.Set(request.Key, request.Value); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresponce.Value = nil\n\n\tcase cdb.CmdGet:\n\t\tif responce.Value, err = p.tcdb.Get(request.Key); err != nil {\n\t\t\tif err.Error() != errNotFound {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tresponce.Err = err.Error()\n\t\t}\n\n\tcase cdb.CmdList:\n\t\tvar keys cdb.KeyList\n\t\tif keys, err = p.tcdb.List(request.Key); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresponce.Value, _ = keys.MarshalBinary()\n\n\tcase cdb.CmdListBody:\n\t\tvar datas []string\n\t\tif datas, err = p.tcdb.ListBody(request.Key); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresponce.Value, _ = json.Marshal(datas)\n\n\tcase cdb.CmdDelete:\n\t\tif err = p.tcdb.Delete(request.Key); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresponce.Value = nil\n\n\tcase cdb.CmdFunc:\n\t\tif responce.Value, err = p.tcdb.PluginFunc(request.Key, request.Value); err != nil {\n\t\t\treturn\n\t\t}\n\n\tcase cdb.CmdGetID:\n\t\tif responce.Value, err = p.tcdb.GetID(request.Key); err != nil {\n\t\t\treturn\n\t\t}\n\n\tcase cdb.CmdSetID:\n\t\tif err = p.tcdb.SetID(request.Key, request.Value); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresponce.Value = nil\n\n\tcase cdb.CmdDeleteID:\n\t\tif err = p.tcdb.DeleteID(request.Key); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresponce.Value = nil\n\n\tcase cdb.CmdGetQueue:\n\t\tif responce.Value, err = p.tcdb.GetQueue(request.Key); err != nil {\n\t\t\tif err.Error() != errNotFound {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tresponce.Err = err.Error()\n\t\t}\n\n\tcase cdb.CmdSetQueue:\n\t\tif err = p.tcdb.SetQueue(request.Key, request.Value); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresponce.Value = nil\n\n\t}\n\n\tretdata, err := responce.MarshalBinary()\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = p.tcdb.con.SendAnswer(pac, pac.Cmd(), retdata)\n\treturn\n}", "func (sr *Router) HandleCommand(ctx context.Context, header http.Header, body []byte) (s int, h http.Header, b []byte, err error) {\n\tif contentType := header.Get(\"Content-Type\"); contentType != \"application/x-www-form-urlencoded\" {\n\t\treturn http.StatusBadRequest, plainResponseHeader, []byte(fmt.Sprintf(\"requires application/x-www-form-urlencoded, not %s\", contentType)), nil\n\t}\n\tif err := sr.verifyRequest(header, body); err != nil {\n\t\treturn errorResponse(ctx, http.StatusUnauthorized, err)\n\t}\n\tparams, err := url.ParseQuery(string(body))\n\tif err != nil {\n\t\treturn errorResponse(ctx, http.StatusBadRequest, fmt.Errorf(\"invalid body: %v\", err))\n\t}\n\treq := Request(params)\n\thandler, ok := sr.commands[req.Command()]\n\tif !ok {\n\t\treturn jsonResponse(ctx, sr.commandUnknownHandler(ctx, req))\n\t}\n\tlogger := loggerFromContext(ctx)\n\tlogger.Printf(\"handling command `%s` for @%s of team %s\", req.Command(), req.UserName(), req.TeamDomain())\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"panic in command handler: %v\\n%s\", r, string(debug.Stack()))\n\t\t\ts, h, b, err = jsonResponse(ctx, sr.commandFailedHandler(ctx, req))\n\t\t}\n\t}()\n\tif sr.middleware != nil {\n\t\thandler = sr.middleware(handler)\n\t}\n\treturn jsonResponse(ctx, handler(ctx, req))\n}", "func MarshalCommand(cmd Command) ([]byte, error) {\n\t// payload\n\tpl, err := cmd.MarshalBinary()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// length\n\tout := make([]byte, 2)\n\tbinary.BigEndian.PutUint16(out, uint16(len(pl))+8) // 8 bytes \"header\"\n\n\t// mystery 2 bytes\n\tout = append(out, []byte{0, 0}...)\n\n\t// slug\n\tout = append(out, []byte(cmd.Slug())[:4]...) // force to 4 bytes\n\n\tout = append(out, pl...)\n\treturn out, nil\n}", "func (r *frontendRequest) processCmd(matches [][]string, isMiCmd bool) {\n\tr.token = matches[0][1]\n\tcmdLine := matches[0][2]\n\tcmdElts := strings.Split(cmdLine, \" \")\n\tr.gdbCmd = &gdbCmd{cmd: cmdElts[0], frontendRequest: r, isMiCmd: isMiCmd}\n\tif len(cmdElts) > 1 {\n\t\tr.gdbCmd.args = cmdElts[1:]\n\t\tr.gdbCmd.argsStr = strings.Join(r.gdbCmd.args, \" \")\n\t}\n\tr.gdbCmd.process()\n}", "func Command(cmd []byte, arg []byte, previousCommand StoredCommand) (StoredCommand, string) {\n var currentCommand StoredCommand\n currentCommand = previousCommand\n if bytes.Equal(cmd, []byte(\"MAIL FROM\")) {\n if bytes.Equal(previousCommand.cmd, []byte(\"\")) {\n currentCommand.StrdSender = string(arg)\n currentCommand.cmd = cmd\n currentCommand.arg = arg\n return currentCommand, \"250 OK\\r\\n\"\n } else {\n return currentCommand, \"500 Error\\r\\n\"\n }\n } else if bytes.Equal(cmd, []byte(\"RCPT TO\")) {\n if bytes.Equal(previousCommand.cmd, []byte(\"MAIL FROM\")) || bytes.Equal(previousCommand.cmd, []byte(\"RCPT TO\")) {\n if (previousCommand.StrdRcpts == nil) {\n currentCommand.StrdRcpts = make([]string, 10)\n } else {\n currentCommand.StrdRcpts = previousCommand.StrdRcpts\n }\n currentCommand.StrdRcpts = append(currentCommand.StrdRcpts, string(arg))\n currentCommand.cmd = cmd\n currentCommand.arg = arg\n return currentCommand, \"250 OK\\r\\n\"\n } else {\n return previousCommand, \"500 Error\\r\\n\"\n }\n } else if bytes.Equal(cmd, []byte(\"DATA\")) {\n currentCommand.cmd = cmd\n currentCommand.arg = arg\n return currentCommand, \"354 Send message content; end with <CRLF>.<CRLF>\\r\\n\"\n } else {\n return currentCommand, \"500 Unknown command\\r\\n\"\n }\n}", "func (pc *PMBusClient) Command(payload string) (string, error) {\n\treturn \"\", nil\n}", "func GetCommand(input string) (string, string) {\n\tinputs := strings.Split(input, \"\\r\\n\")\n\tn1 := len(inputs)\n\tn := len(inputs[0])\n//\t\tabc := input[0:3]\n//\t\tlog.Printf(\"**%s--%s--%s--%s-\", input, inputs[0], (inputs[0])[1:3], abc)\n\t\t\n\tcom, rem := \"\", \"\"\n\tif n >= 3 && (inputs[0][0:3] == \"set\" || inputs[0][0:3] == \"cas\") {\n\t\t// start of a 2 line command\n\t\tif n1 < 3 {\t\t\t\t\t\t// includes \"\\r\\n\"\n\t\t\treturn \"\", input\t\t\t// if the command is not complete, wait for the rest of the command\n\t\t}\n\t\tvar in = strings.Index(input, \"\\r\\n\") + 2\n\t\tin += strings.Index(input[in:], \"\\r\\n\") + 2\n\t\tcom = input[:in]\n\t\trem = input[in:]\n\t} else if (n >= 3 && inputs[0][0:3] == \"get\") ||\n\t\t(n >= 4 && inputs[0][0:4] == \"getm\") ||\n\t\t(n >= 6 && inputs[0][0:6] == \"delete\") {\n\t\t// start of a 1 line command\n\t\tif n1 < 2 {\t\t\t\t\t\t// includes \"\\r\\n\"\n\t\t\treturn \"\", input\t\t\t// if the command is not complete, wait for the rest of the command\n\t\t}\n\t\tvar in = strings.Index(input, \"\\r\\n\") + 2\n\t\tcom = input[:in]\n\t\trem = input[in:]\n\t\t\n\t} else {\n\t\treturn \"\", input\n\t}\n\treturn com, rem\n}", "func (app *Application) ProcessCommand(command string) {\n\tif app.isFirst {\n\t\tapp.Robot.SendCommand(\"CONNSERV\")\n\t\tapp.isFirst = false\n\t}\n\tapp.Robot.SendCommand(command)\n}", "func getCommandResponse(cmd_hash string, templatefile string, context CommandEnv) string {\n jsondata := renderTemplate(templatefile, context)\n var objmap map[string]CommandResponse\n // Get json object\n err := json.Unmarshal(jsondata, &objmap)\n if err != nil {\n // Invalid JSON\n fmt.Println(err)\n }\n //fmt.Printf(\"Looking at %s\", cmd_hash)\n // we need to marshal again so we can just get the specific command hash\n value, ok := objmap[cmd_hash]\n if !ok {\n return renderNotFoundError()\n } else {\n cmd_json, de_err := json.Marshal(value)\n if de_err != nil {\n return renderNotFoundError()\n }\n return string(cmd_json)\n }\n}", "func buildEncodeCmd(values *url.Values, w *http.ResponseWriter) (cmd *exec.Cmd, err error) {\n\tencoding := values.Get(\"encoding\")\n\n\t// default to mp3 encoding, allow opus as well, error on all others\n\t// set the content-type header appropriately\n\tvar encode *exec.Cmd\n\tif len(encoding) == 0 || encoding == \"mp3\" {\n\t\tencode = exec.Command(\"lame\", \"-\", \"-\")\n\t\t(*w).Header().Set(\"Content-Type\", \"audio/mpeg\")\n\t} else if encoding == \"opus\" {\n\t\tencode = exec.Command(\"opusenc\", \"-\", \"-\")\n\t\t// use audio/ogg since it seems better supported by all browsers\n\t\t// than audio/opus\n\t\t(*w).Header().Set(\"Content-Type\", \"audio/ogg\")\n\t} else if encoding == \"wav\" {\n\t\t(*w).Header().Set(\"Content-Type\", \"audio/wav\")\n\t\tencode = exec.Command(\"cat\")\n\t} else {\n\t\terr := errors.New(\"Unknown encoding requested: \" + encoding)\n\t\thttp.Error(*w, err.Error(), 400)\n\t\treturn nil, err\n\t}\n\n\treturn encode, nil\n}", "func Command(commandtext string) (CommandDetails, error) {\n\n\tvar parsedCommand CommandDetails\n\n\tparsedCommand.Original = commandtext\n\n\t// Let's tokenise this using the delimiters, that'll make this parsing easier.\n\t// super fragile parsing up ahead!\n\toverlaySlice := strings.Split(commandtext, \"|\")\n\n\tif len(overlaySlice) > 1 {\n\t\tparsedCommand.OverlayText = strings.Join(overlaySlice[1:], \"\\n\")\n\t\tcommandtext = overlaySlice[0]\n\t}\n\n\tgifSlice := strings.Split(commandtext, \"/\")\n\n\tif len(gifSlice) > 1 {\n\t\tgifDetails := strings.Split(strings.TrimSpace(gifSlice[1]), \" \")\n\t\tif len(gifDetails) > 1 {\n\t\t\tparsedCommand.GifOffset = gifDetails[1]\n\n\t\t}\n\t\tparsedCommand.GifLength = gifDetails[0]\n\t\tcommandtext = gifSlice[0]\n\t}\n\n\tparsedCommand.Quote = commandtext\n\n\tif !strings.Contains(parsedCommand.GifLength, \"s\") {\n\t\tparsedCommand.GifLength += \"s\"\n\t}\n\n\tif !strings.Contains(parsedCommand.GifOffset, \"s\") {\n\t\tparsedCommand.GifOffset += \"s\"\n\t}\n\n\t// fmt.Printf(\"%+v\", result)\n\n\treturn parsedCommand, nil\n}", "func EncodeCommand(cmdToken rune, qty byte) byte {\n\tvar cmd byte\n\tq := qty\n\n\tswitch cmdToken {\n\tcase token.MoveRight:\n\t\tcmd = CmdMoveRight\n\tcase token.MoveLeft:\n\t\tcmd = CmdMoveLeft\n\tcase token.Inc:\n\t\tcmd = CmdInc\n\tcase token.Dec:\n\t\tcmd = CmdDec\n\tcase token.Output:\n\t\tcmd = CmdOutput\n\tcase token.Input:\n\t\tcmd = CmdInput\n\tcase token.Jump:\n\t\tcmd = CmdJump\n\tcase token.Return:\n\t\tcmd = CmdReturn\n\t}\n\n\tswitch cmdToken {\n\tcase token.Output:\n\t\tfallthrough\n\tcase token.Input:\n\t\tfallthrough\n\tcase token.Jump:\n\t\tfallthrough\n\tcase token.Return:\n\t\tq = 0\n\t}\n\n\treturn (cmd << 6) | q\n}", "func ServCommand(ctx *context.PrivateContext) {\n\tkeyID := ctx.ParamsInt64(\":keyid\")\n\townerName := ctx.Params(\":owner\")\n\trepoName := ctx.Params(\":repo\")\n\tmode := perm.AccessMode(ctx.FormInt(\"mode\"))\n\n\t// Set the basic parts of the results to return\n\tresults := private.ServCommandResults{\n\t\tRepoName: repoName,\n\t\tOwnerName: ownerName,\n\t\tKeyID: keyID,\n\t}\n\n\t// Now because we're not translating things properly let's just default some English strings here\n\tmodeString := \"read\"\n\tif mode > perm.AccessModeRead {\n\t\tmodeString = \"write to\"\n\t}\n\n\t// The default unit we're trying to look at is code\n\tunitType := unit.TypeCode\n\n\t// Unless we're a wiki...\n\tif strings.HasSuffix(repoName, \".wiki\") {\n\t\t// in which case we need to look at the wiki\n\t\tunitType = unit.TypeWiki\n\t\t// And we'd better munge the reponame and tell downstream we're looking at a wiki\n\t\tresults.IsWiki = true\n\t\tresults.RepoName = repoName[:len(repoName)-5]\n\t}\n\n\towner, err := user_model.GetUserByName(ctx, results.OwnerName)\n\tif err != nil {\n\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\t// User is fetching/cloning a non-existent repository\n\t\t\tlog.Warn(\"Failed authentication attempt (cannot find repository: %s/%s) from %s\", results.OwnerName, results.RepoName, ctx.RemoteAddr())\n\t\t\tctx.JSON(http.StatusNotFound, private.Response{\n\t\t\t\tUserMsg: fmt.Sprintf(\"Cannot find repository: %s/%s\", results.OwnerName, results.RepoName),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tlog.Error(\"Unable to get repository owner: %s/%s Error: %v\", results.OwnerName, results.RepoName, err)\n\t\tctx.JSON(http.StatusForbidden, private.Response{\n\t\t\tUserMsg: fmt.Sprintf(\"Unable to get repository owner: %s/%s %v\", results.OwnerName, results.RepoName, err),\n\t\t})\n\t\treturn\n\t}\n\tif !owner.IsOrganization() && !owner.IsActive {\n\t\tctx.JSON(http.StatusForbidden, private.Response{\n\t\t\tUserMsg: \"Repository cannot be accessed, you could retry it later\",\n\t\t})\n\t\treturn\n\t}\n\n\t// Now get the Repository and set the results section\n\trepoExist := true\n\trepo, err := repo_model.GetRepositoryByName(owner.ID, results.RepoName)\n\tif err != nil {\n\t\tif repo_model.IsErrRepoNotExist(err) {\n\t\t\trepoExist = false\n\t\t\tfor _, verb := range ctx.FormStrings(\"verb\") {\n\t\t\t\tif verb == \"git-upload-pack\" {\n\t\t\t\t\t// User is fetching/cloning a non-existent repository\n\t\t\t\t\tlog.Warn(\"Failed authentication attempt (cannot find repository: %s/%s) from %s\", results.OwnerName, results.RepoName, ctx.RemoteAddr())\n\t\t\t\t\tctx.JSON(http.StatusNotFound, private.Response{\n\t\t\t\t\t\tUserMsg: fmt.Sprintf(\"Cannot find repository: %s/%s\", results.OwnerName, results.RepoName),\n\t\t\t\t\t})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Error(\"Unable to get repository: %s/%s Error: %v\", results.OwnerName, results.RepoName, err)\n\t\t\tctx.JSON(http.StatusInternalServerError, private.Response{\n\t\t\t\tErr: fmt.Sprintf(\"Unable to get repository: %s/%s %v\", results.OwnerName, results.RepoName, err),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t}\n\n\tif repoExist {\n\t\trepo.Owner = owner\n\t\trepo.OwnerName = ownerName\n\t\tresults.RepoID = repo.ID\n\n\t\tif repo.IsBeingCreated() {\n\t\t\tctx.JSON(http.StatusInternalServerError, private.Response{\n\t\t\t\tErr: \"Repository is being created, you could retry after it finished\",\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\tif repo.IsBroken() {\n\t\t\tctx.JSON(http.StatusInternalServerError, private.Response{\n\t\t\t\tErr: \"Repository is in a broken state\",\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\t// We can shortcut at this point if the repo is a mirror\n\t\tif mode > perm.AccessModeRead && repo.IsMirror {\n\t\t\tctx.JSON(http.StatusForbidden, private.Response{\n\t\t\t\tUserMsg: fmt.Sprintf(\"Mirror Repository %s/%s is read-only\", results.OwnerName, results.RepoName),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Get the Public Key represented by the keyID\n\tkey, err := asymkey_model.GetPublicKeyByID(keyID)\n\tif err != nil {\n\t\tif asymkey_model.IsErrKeyNotExist(err) {\n\t\t\tctx.JSON(http.StatusNotFound, private.Response{\n\t\t\t\tUserMsg: fmt.Sprintf(\"Cannot find key: %d\", keyID),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tlog.Error(\"Unable to get public key: %d Error: %v\", keyID, err)\n\t\tctx.JSON(http.StatusInternalServerError, private.Response{\n\t\t\tErr: fmt.Sprintf(\"Unable to get key: %d Error: %v\", keyID, err),\n\t\t})\n\t\treturn\n\t}\n\tresults.KeyName = key.Name\n\tresults.KeyID = key.ID\n\tresults.UserID = key.OwnerID\n\n\t// If repo doesn't exist, deploy key doesn't make sense\n\tif !repoExist && key.Type == asymkey_model.KeyTypeDeploy {\n\t\tctx.JSON(http.StatusNotFound, private.Response{\n\t\t\tUserMsg: fmt.Sprintf(\"Cannot find repository %s/%s\", results.OwnerName, results.RepoName),\n\t\t})\n\t\treturn\n\t}\n\n\t// Deploy Keys have ownerID set to 0 therefore we can't use the owner\n\t// So now we need to check if the key is a deploy key\n\t// We'll keep hold of the deploy key here for permissions checking\n\tvar deployKey *asymkey_model.DeployKey\n\tvar user *user_model.User\n\tif key.Type == asymkey_model.KeyTypeDeploy {\n\t\tvar err error\n\t\tdeployKey, err = asymkey_model.GetDeployKeyByRepo(ctx, key.ID, repo.ID)\n\t\tif err != nil {\n\t\t\tif asymkey_model.IsErrDeployKeyNotExist(err) {\n\t\t\t\tctx.JSON(http.StatusNotFound, private.Response{\n\t\t\t\t\tUserMsg: fmt.Sprintf(\"Public (Deploy) Key: %d:%s is not authorized to %s %s/%s.\", key.ID, key.Name, modeString, results.OwnerName, results.RepoName),\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Error(\"Unable to get deploy for public (deploy) key: %d in %-v Error: %v\", key.ID, repo, err)\n\t\t\tctx.JSON(http.StatusInternalServerError, private.Response{\n\t\t\t\tErr: fmt.Sprintf(\"Unable to get Deploy Key for Public Key: %d:%s in %s/%s.\", key.ID, key.Name, results.OwnerName, results.RepoName),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tresults.DeployKeyID = deployKey.ID\n\t\tresults.KeyName = deployKey.Name\n\n\t\t// FIXME: Deploy keys aren't really the owner of the repo pushing changes\n\t\t// however we don't have good way of representing deploy keys in hook.go\n\t\t// so for now use the owner of the repository\n\t\tresults.UserName = results.OwnerName\n\t\tresults.UserID = repo.OwnerID\n\t\tif !repo.Owner.KeepEmailPrivate {\n\t\t\tresults.UserEmail = repo.Owner.Email\n\t\t}\n\t} else {\n\t\t// Get the user represented by the Key\n\t\tvar err error\n\t\tuser, err = user_model.GetUserByID(ctx, key.OwnerID)\n\t\tif err != nil {\n\t\t\tif user_model.IsErrUserNotExist(err) {\n\t\t\t\tctx.JSON(http.StatusUnauthorized, private.Response{\n\t\t\t\t\tUserMsg: fmt.Sprintf(\"Public Key: %d:%s owner %d does not exist.\", key.ID, key.Name, key.OwnerID),\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Error(\"Unable to get owner: %d for public key: %d:%s Error: %v\", key.OwnerID, key.ID, key.Name, err)\n\t\t\tctx.JSON(http.StatusInternalServerError, private.Response{\n\t\t\t\tErr: fmt.Sprintf(\"Unable to get Owner: %d for Deploy Key: %d:%s in %s/%s.\", key.OwnerID, key.ID, key.Name, ownerName, repoName),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\tif !user.IsActive || user.ProhibitLogin {\n\t\t\tctx.JSON(http.StatusForbidden, private.Response{\n\t\t\t\tUserMsg: \"Your account is disabled.\",\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\tresults.UserName = user.Name\n\t\tif !user.KeepEmailPrivate {\n\t\t\tresults.UserEmail = user.Email\n\t\t}\n\t}\n\n\t// Don't allow pushing if the repo is archived\n\tif repoExist && mode > perm.AccessModeRead && repo.IsArchived {\n\t\tctx.JSON(http.StatusUnauthorized, private.Response{\n\t\t\tUserMsg: fmt.Sprintf(\"Repo: %s/%s is archived.\", results.OwnerName, results.RepoName),\n\t\t})\n\t\treturn\n\t}\n\n\t// Permissions checking:\n\tif repoExist &&\n\t\t(mode > perm.AccessModeRead ||\n\t\t\trepo.IsPrivate ||\n\t\t\towner.Visibility.IsPrivate() ||\n\t\t\t(user != nil && user.IsRestricted) || // user will be nil if the key is a deploykey\n\t\t\tsetting.Service.RequireSignInView) {\n\t\tif key.Type == asymkey_model.KeyTypeDeploy {\n\t\t\tif deployKey.Mode < mode {\n\t\t\t\tctx.JSON(http.StatusUnauthorized, private.Response{\n\t\t\t\t\tUserMsg: fmt.Sprintf(\"Deploy Key: %d:%s is not authorized to %s %s/%s.\", key.ID, key.Name, modeString, results.OwnerName, results.RepoName),\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\t// Because of the special ref \"refs/for\" we will need to delay write permission check\n\t\t\tif git.SupportProcReceive && unitType == unit.TypeCode {\n\t\t\t\tmode = perm.AccessModeRead\n\t\t\t}\n\n\t\t\tperm, err := access_model.GetUserRepoPermission(ctx, repo, user)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"Unable to get permissions for %-v with key %d in %-v Error: %v\", user, key.ID, repo, err)\n\t\t\t\tctx.JSON(http.StatusInternalServerError, private.Response{\n\t\t\t\t\tErr: fmt.Sprintf(\"Unable to get permissions for user %d:%s with key %d in %s/%s Error: %v\", user.ID, user.Name, key.ID, results.OwnerName, results.RepoName, err),\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tuserMode := perm.UnitAccessMode(unitType)\n\n\t\t\tif userMode < mode {\n\t\t\t\tlog.Warn(\"Failed authentication attempt for %s with key %s (not authorized to %s %s/%s) from %s\", user.Name, key.Name, modeString, ownerName, repoName, ctx.RemoteAddr())\n\t\t\t\tctx.JSON(http.StatusUnauthorized, private.Response{\n\t\t\t\t\tUserMsg: fmt.Sprintf(\"User: %d:%s with Key: %d:%s is not authorized to %s %s/%s.\", user.ID, user.Name, key.ID, key.Name, modeString, ownerName, repoName),\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// We already know we aren't using a deploy key\n\tif !repoExist {\n\t\towner, err := user_model.GetUserByName(ctx, ownerName)\n\t\tif err != nil {\n\t\t\tctx.JSON(http.StatusInternalServerError, private.Response{\n\t\t\t\tErr: fmt.Sprintf(\"Unable to get owner: %s %v\", results.OwnerName, err),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\tif owner.IsOrganization() && !setting.Repository.EnablePushCreateOrg {\n\t\t\tctx.JSON(http.StatusForbidden, private.Response{\n\t\t\t\tUserMsg: \"Push to create is not enabled for organizations.\",\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tif !owner.IsOrganization() && !setting.Repository.EnablePushCreateUser {\n\t\t\tctx.JSON(http.StatusForbidden, private.Response{\n\t\t\t\tUserMsg: \"Push to create is not enabled for users.\",\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\trepo, err = repo_service.PushCreateRepo(ctx, user, owner, results.RepoName)\n\t\tif err != nil {\n\t\t\tlog.Error(\"pushCreateRepo: %v\", err)\n\t\t\tctx.JSON(http.StatusNotFound, private.Response{\n\t\t\t\tUserMsg: fmt.Sprintf(\"Cannot find repository: %s/%s\", results.OwnerName, results.RepoName),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tresults.RepoID = repo.ID\n\t}\n\n\tif results.IsWiki {\n\t\t// Ensure the wiki is enabled before we allow access to it\n\t\tif _, err := repo.GetUnit(ctx, unit.TypeWiki); err != nil {\n\t\t\tif repo_model.IsErrUnitTypeNotExist(err) {\n\t\t\t\tctx.JSON(http.StatusForbidden, private.Response{\n\t\t\t\t\tUserMsg: \"repository wiki is disabled\",\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Error(\"Failed to get the wiki unit in %-v Error: %v\", repo, err)\n\t\t\tctx.JSON(http.StatusInternalServerError, private.Response{\n\t\t\t\tErr: fmt.Sprintf(\"Failed to get the wiki unit in %s/%s Error: %v\", ownerName, repoName, err),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\t// Finally if we're trying to touch the wiki we should init it\n\t\tif err = wiki_service.InitWiki(ctx, repo); err != nil {\n\t\t\tlog.Error(\"Failed to initialize the wiki in %-v Error: %v\", repo, err)\n\t\t\tctx.JSON(http.StatusInternalServerError, private.Response{\n\t\t\t\tErr: fmt.Sprintf(\"Failed to initialize the wiki in %s/%s Error: %v\", ownerName, repoName, err),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Debug(\"Serv Results:\\nIsWiki: %t\\nDeployKeyID: %d\\nKeyID: %d\\tKeyName: %s\\nUserName: %s\\nUserID: %d\\nOwnerName: %s\\nRepoName: %s\\nRepoID: %d\",\n\t\tresults.IsWiki,\n\t\tresults.DeployKeyID,\n\t\tresults.KeyID,\n\t\tresults.KeyName,\n\t\tresults.UserName,\n\t\tresults.UserID,\n\t\tresults.OwnerName,\n\t\tresults.RepoName,\n\t\tresults.RepoID)\n\n\tctx.JSON(http.StatusOK, results)\n\t// We will update the keys in a different call.\n}", "func EncodeCmd(content string) (b []byte, err error) {\n\treturn EncodeBytes([]byte(content))\n}", "func (c *clientHandler) handleCommand(line string) {\n\tcommand, param := parseLine(line)\n\n\tif c.debug {\n\t\tc.logger.Debug(\"Received line\", \"line\", maskSensitiveLine(command, line))\n\t}\n\n\tc.command = strings.ToUpper(command)\n\tc.param = param\n\n\tcmdDesc := commandsMap[c.command]\n\tif cmdDesc == nil {\n\t\tc.writeMessage(StatusSyntaxErrorNotRecognised, \"Unknown command\")\n\t\treturn\n\t}\n\n\tif c.driver == nil && !cmdDesc.Open {\n\t\tc.writeMessage(StatusNotLoggedIn, \"Please login with USER and PASS\")\n\t\treturn\n\t}\n\n\t// Let's prepare to recover in case there's a command error\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tc.writeMessage(StatusSyntaxErrorNotRecognised, fmt.Sprintf(\"Unhandled internal error: %s\", r))\n\t\t\tc.logger.Warn(\n\t\t\t\t\"Internal command handling error\",\n\t\t\t\t\"err\", r,\n\t\t\t\t\"command\", c.command,\n\t\t\t\t\"param\", c.param,\n\t\t\t)\n\t\t}\n\t}()\n\n\tif err := cmdDesc.Fn(c); err != nil {\n\t\tc.writeMessage(StatusSyntaxErrorNotRecognised, fmt.Sprintf(\"Error: %s\", err))\n\t}\n}", "func (y *YeeLight) sendCommand(cmd *command) (*Answer, error) {\n\tif y.tcpSocket == nil {\n\t\ty.releaseAnswerChan(cmd.ID, nil)\n\t\treturn nil, errors.WithStack(ErrConnNotInitialized)\n\t}\n\ty.idMutex.RLock()\n\trespChan, ok := y.pendingCmds[cmd.ID]\n\ty.idMutex.RUnlock()\n\tif !ok {\n\t\treturn nil, errors.WithStack(ErrFailedCmd)\n\t}\n\ty.tcpSocket.Write(cmd.json())\n\tselect {\n\tcase a := <-respChan:\n\t\treturn &a, nil\n\tcase <-time.After(commandTimeout):\n\t\ty.releaseAnswerChan(cmd.ID, nil)\n\t\treturn nil, errors.Wrapf(ErrTimedOut, \"failed command %v\", cmd)\n\t}\n}", "func (b *Bulb) responseProcessor() {\n\tvar buff = make([]byte, 512)\n\tvar resp map[string]interface{}\n\n\tfor {\n\t\tn, err := b.conn.Read(buff)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tresponses := bytes.Split(buff[:n], []byte{CR, LF})\n\n\t\tfor _, r := range responses[:len(responses)-1] {\n\t\t\tresp = make(map[string]interface{})\n\n\t\t\terr = json.Unmarshal(r, &resp)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"OKResponse err: %s\\n\", r)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tswitch {\n\t\t\tcase keysExists(resp, \"id\", \"result\"): // Command success\n\t\t\t\tvar unmarshaled OKResponse\n\t\t\t\terr = json.Unmarshal(r, &unmarshaled)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"second unmarshal error: %s\\n\", r)\n\t\t\t\t}\n\t\t\t\tb.results[unmarshaled.id()] <- &unmarshaled\n\t\t\tcase keysExists(resp, \"id\", \"error\"): // Command failed\n\t\t\t\tvar unmarshaled ERRResponse\n\t\t\t\terr = json.Unmarshal(r, &unmarshaled)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"second unmarshal error: %s\\n\", r)\n\t\t\t\t}\n\t\t\t\tb.results[unmarshaled.id()] <- &unmarshaled\n\t\t\tcase keysExists(resp, \"method\", \"params\"): // Notification\n\t\t\t\t// log.Printf(\"state change%s\\n\", r)\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"unhandled response: %s\\n\", r)\n\t\t\t}\n\t\t}\n\t}\n\tlog.Printf(\"response processor exited\\n\")\n}", "func (j Jibi) RunCommand(cmd Command, resp chan string) {\n\tif cmd < cmdCPU {\n\t\tj.cpu.RunCommand(cmd, resp)\n\t} else if cmd < cmdGPU {\n\t\tj.gpu.RunCommand(cmd, resp)\n\t} else if cmd < cmdKEYPAD {\n\t\tj.kp.RunCommand(cmd, resp)\n\t} else if cmd < cmdALL {\n\t\tj.cpu.RunCommand(cmd, resp)\n\t\tj.gpu.RunCommand(cmd, resp)\n\t\tj.kp.RunCommand(cmd, resp)\n\t}\n}", "func captureCommand(args []string) CommandResponse {\n\tcommand := args[0]\n\targs = args[1:]\n\tlog.Printf(\"Command: %s %s\", command, args)\n\tvar exitcode = 0\n\tcmd := exec.Command(command, args...)\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\n\tif err := cmd.Start(); err != nil {\n\t\tlog.Fatalf(\"cmd.Start: %v\")\n\t}\n\n\tif err := cmd.Wait(); err != nil {\n\t\tif exiterr, ok := err.(*exec.ExitError); ok {\n\t\t\t// The program has exited with an exit code != 0\n\t\t\t// There is no plattform independent way to retrieve\n\t\t\t// the exit code, but the following will work on Unix\n\t\t\tif status, ok := exiterr.Sys().(syscall.WaitStatus); ok {\n\t\t\t\t// for some odd reason this is output exit status 1\n\t\t\t\texitcode = status.ExitStatus()\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Fatalf(\"cmd.Wait: %v\", err)\n\t\t}\n\t}\n\n\t//usertime := cmd.ProcessState.UserTime()\n\t//fmt.Printf(\"Milli [%v]\", usertime.Seconds())\n\n\tlog.Printf(\"Exit Status: %d\", exitcode )\n\t// store the original command call in stdin\n\tstdin := append([]string{command}, args...)\n\tcommand_response := CommandResponse{Stdout: stdout.String(),\n\t\tStderr: stderr.String(),\n\t\tExitcode: exitcode,\n\t\tDelay:0,\n\t\tStdin: strings.Join(stdin, \" \"),\n\t}\n\treturn command_response\n}", "func (self *tele) CommandTx(vmid int32, c *vender_api.Command, timeout time.Duration) (*vender_api.Response, error) {\n\tif c.Deadline == 0 {\n\t\tc.Deadline = time.Now().Add(timeout).UnixNano()\n\t}\n\tif err := self.SendCommand(vmid, c); err != nil {\n\t\treturn nil, errors.Annotate(err, \"CommandTx\")\n\t}\n\n\ttmr := time.NewTimer(timeout)\n\tdefer tmr.Stop()\n\tfor {\n\t\tselect {\n\t\tcase p := <-self.pch:\n\t\t\t// if p.Kind == tele.PacketCommandReply {\n\t\t\tif r, err := p.CommandResponse(); err == nil {\n\t\t\t\tif r.CommandId == c.Id {\n\t\t\t\t\tif r.Error == \"\" {\n\t\t\t\t\t\treturn r, nil\n\t\t\t\t\t}\n\t\t\t\t\treturn r, fmt.Errorf(r.Error)\n\t\t\t\t} else {\n\t\t\t\t\tself.log.Errorf(\"current command.id=%d unexpected response=%#v\", c.Id, r)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tself.log.Errorf(\"unexpected packet=%#v\", p)\n\t\t\t}\n\n\t\tcase <-tmr.C:\n\t\t\treturn nil, errors.Timeoutf(\"response\")\n\t\t}\n\t}\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 rpc(w http.ResponseWriter, r *http.Request) {\n\t// Parses the command into the rpc struct\n\tvar rpc rpcCall\n\tbodyBytes, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tsendHTTPResp(w, 500, err)\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(bodyBytes, &rpc)\n\tif err != nil {\n\t\tsendHTTPResp(w, 500, err)\n\t\treturn\n\t}\n\n\t// Processes the rpc opcodes\n\tif rpc.Call == \"mkdirp\" { // Opcode for creating new dirs\n\t\tpath, err := validPath(rpc.Args[0])\n\t\tif err != nil {\n\t\t\tsendHTTPResp(w, 500, err)\n\t\t\treturn\n\t\t}\n\n\t\terr = os.MkdirAll(path, os.ModePerm)\n\t\tif err != nil {\n\t\t\tsendHTTPResp(w, 500, err)\n\t\t\treturn\n\t\t}\n\n\t} else if rpc.Call == \"mv\" { // Opcode for moving/renaming files\n\t\tsrcPath, err := validPath(rpc.Args[0])\n\t\tif err != nil {\n\t\t\tsendHTTPResp(w, 500, err)\n\t\t\treturn\n\t\t}\n\t\tdstPath, err := validPath(rpc.Args[1])\n\t\tif err != nil {\n\t\t\tsendHTTPResp(w, 500, err)\n\t\t\treturn\n\t\t}\n\n\t\terr = os.Rename(srcPath, dstPath)\n\t\tif err != nil {\n\t\t\tsendHTTPResp(w, 500, err)\n\t\t\treturn\n\t\t}\n\t} else if rpc.Call == \"rm\" { // Opcode for removing files\n\t\tpath, err := validPath(rpc.Args[0])\n\t\tif err != nil {\n\t\t\tsendHTTPResp(w, 500, err)\n\t\t\treturn\n\t\t}\n\n\t\terr = os.RemoveAll(path)\n\t\tif err != nil {\n\t\t\tsendHTTPResp(w, 500, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tw.Write([]byte(\"ok\"))\n}", "func OpCommandDirectByte(cmd string) ([]byte, error) {\n\tfmt.Printf(cmd)\n\tretByte, err := OpCommandWithByteErr(\"/bin/bash\", \"-c\", cmd)\n\treturn retByte, err\n}", "func SendCommand(command []byte, address string) ([]byte, *nerr.E) {\n\tlog.L.Infof(\"Sending command %s, to %v\", command, address)\n\n\t// OPEN THE GATES\n\tconn, err := getConnection(address)\n\tif err != nil {\n\t\treturn []byte{}, err.Addf(\"Could not send command\")\n\t}\n\tdefer conn.Close()\n\n\t// Reader is what will be reading the i/o stream\n\treader := bufio.NewReader(conn)\n\n\t// This is the command we will be sending\n\tcommandToSend := append(command, carriageReturn)\n\n\tconn.Write(commandToSend)\n\t//Check to see if the lengths were the same\n\n\t// Read over the connection to get a response (resp) back. resperr is the error to check for\n\tconn.SetReadDeadline(time.Now().Add(time.Duration(timeoutInSeconds) * time.Second))\n\tresp, resperr := reader.ReadBytes('\\r')\n\tif resperr != nil {\n\t\tlog.L.Infof(color.HiRedString(\"Error: %v\", resperr))\n\t\treturn []byte{}, nerr.Translate(resperr)\n\t}\n\n\t//Misson Complete, get us outta here\n\treturn resp, nil\n}", "func HaproxyCmd(cmd string) (string, error){\n\n\n\t// connect to haproxy\n\tconn, err_conn := net.Dial(\"unix\", \"/tmp/haproxy.stats.sock\")\n\tdefer conn.Close()\n\n\tif err_conn != nil {\n\t\treturn \"\", errors.New(\"Unable to connect to Haproxy socket\")\n\t} else {\n\n\t\tfmt.Fprint(conn, cmd)\n\n\t\tresponse := \"\"\n\n\t\tscanner := bufio.NewScanner(conn)\n\t\tfor scanner.Scan() {\n\t\t\tresponse += (scanner.Text() + \"\\n\")\n\t\t}\n\t\tif err := scanner.Err(); err != nil {\n\t\t\treturn \"\", err\n\t\t} else {\n\t\t\treturn response, nil\n\t\t}\n\n\t}\n}", "func GetCommand(client Client) error{\n conn := client.Conn\n argv := client.CommandArgv\n err := checkCommandProtocol(&client)\n if err != nil {\n return err\n }\n resp := ServerInstance.Dict[argv[4]]\n\n //类型判定\n tmpValue, ok := (resp.Value).(string)\n if !ok {\n responseNil(conn)\n } else {\n responseValue(tmpValue, conn)\n }\n return nil\n}", "func processCommand(db models.DataStore, command []string) (models.StoreyResponse, error) {\n\tswitch command[0] {\n\tcase models.CmdCreateParkingLot:\n\t\tmaxSlots, err := strToInt(command[1])\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\treturn db.AddStorey(maxSlots)\n\tcase models.CmdPark:\n\t\treturn db.Park(command[1], command[2])\n\tcase models.CmdCreateParkingLot:\n\tcase models.CmdStatus:\n\t\treturn db.All()\n\tcase models.CmdLeave:\n\t\tslotPosition, err := strToInt(command[1])\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\treturn db.LeaveByPosition(slotPosition)\n\tcase models.CmdRegistrationNumberByColor:\n\t\treturn db.FindAllByColor(command[1], models.CmdRegistrationNumberByColor)\n\tcase models.CmdSlotnoByCarColor:\n\t\treturn db.FindAllByColor(command[1], models.CmdSlotnoByCarColor)\n\tcase models.CmdSlotnoByRegNumber:\n\t\treturn db.FindByRegistrationNumber(command[1])\n\tdefault:\n\t}\n\n\treturn models.StoreyResponse{}, nil\n}", "func handle(id int, cmd *json.Json, proc Processor) {\n\t// Create a response with the matching ID\n\tr, dat, err := json.MakeMap()\n\tif err != nil {\n\t\t// Echo errors to host\n\t\tfmt.Println(err)\n\t} else {\n\t\tdat[\"id\"] = id\n\t\tdat[\"data\"] = proc(cmd) // Set response data to processor result\t\n\t\tb, _ := r.Encode()\n\t\tfmt.Println(string(b)) // Send JSON result on stdout\n\t}\n}", "func (c *Client) Cmd(format string,\n\targs ...interface{}) (line string, err error) {\n\tif err = c.Send(format, args...); err != nil {\n\t\treturn\n\t}\n\n\tline, err = c.ReadLine()\n\tif err != nil {\n\t\treturn\n\t}\n\tif !IsOK(line) {\n\t\treturn \"\", errors.New(\"pop3: Server did not respond with +OK\")\n\t}\n\treturn\n}", "func (d *Connection) execGen2Cmd(method string, enable bool, res interface{}) error {\n\t// Shelly gen 2 rfc7616 authentication\n\t// https://shelly-api-docs.shelly.cloud/gen2/Overview/CommonDeviceTraits#authentication\n\t// https://datatracker.ietf.org/doc/html/rfc7616\n\n\tdata := &Gen2RpcPost{\n\t\tId: d.channel,\n\t\tOn: enable,\n\t\tSrc: \"evcc\",\n\t\tMethod: method,\n\t}\n\n\treq, err := request.New(http.MethodPost, fmt.Sprintf(\"%s/%s\", d.uri, method), request.MarshalJSON(data), request.JSONEncoding)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn d.DoJSON(req, &res)\n}", "func (self *Client) exec(request Request) error {\n\tself.logDebug.Printf(\"Client.exec: cmd=%02x flags=%04x...\", request.Cmd, request.Flags)\n\n\tmsg := self.genlFamily.Request(request.Cmd, request.Flags, nil, request.Attrs.Bytes())\n\n\tif out, err := self.genlHub.Sync(msg); err != nil {\n\t\treturn err\n\t} else {\n\t\tfor _, msg := range out {\n\t\t\tif msg.Header.Type == syscall.NLMSG_ERROR {\n\t\t\t\tif msgErr := nlgo.NlMsgerr(msg.NetlinkMessage); msgErr.Payload().Error != 0 {\n\t\t\t\t\treturn msgErr\n\t\t\t\t} else {\n\t\t\t\t\t// ack\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tself.logWarning.Printf(\"Client.exec: Unexpected response: %+v\", msg)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func processCommand(data []string) int {\n\n\tdataType := strings.ToLower(data[0])\n\tswitch dataType {\n\tcase createAParkingLot:\n\t\tnumberOfParkingLots, _ := strconv.Atoi(data[1])\n\t\tcreateParkingLot(numberOfParkingLots)\n\tcase parkVehicle:\n\t\tparkingSlots = parkAVehicle(parkingSlots, data[1:], totalNumberOfParkingLots)\n\tcase freeSlot:\n\t\tslotNumber, _ := strconv.Atoi(data[1])\n\t\tfreeAParkingSlot(parkingSlots, totalNumberOfParkingLots, slotNumber)\n\tcase statusOfParkingSlots:\n\t\tlistAllSlotDetails(parkingSlots)\n\tcase regNumbersWithColor:\n\t\tfindRegOrSlotByColor(parkingSlots, data[1], true)\n\tcase slotNumbersWithColor:\n\t\tfindRegOrSlotByColor(parkingSlots, data[1], false)\n\tcase slotNumberWithReg:\n\t\tfindSlotNumberByRegNum(parkingSlots, data[1])\n\tdefault:\n\t\tfmt.Println(\"Not a valid command\")\n\t\treturn -1\n\t}\n\n\treturn 1\n}", "func sendCmdExtResponse(p io.ReadWriter, c Cmd) (res int32, ext []byte, err error) {\n\tres, err = sendCmd(p, c)\n\tif err != nil {\n\t\treturn res, nil, err\n\t}\n\n\t// <res> indicates the length of the extended response data that follows. It should generally\n\t// be interpreted as a uint32\n\t// Unfortunately, <res> can also contain an error code when an error has occurred. Error values\n\t// are negative int32 values.\n\t// Thus, it is not possible to differentiate between a large uint32 value (indicating the length of data that follows), vs a negative int32 value (indicating an error)\n\n\t// For the moment, we will assume that if <res> is negative when interpreted as an int32, then\n\t// an error has indeed occurred, and therefore there is no extended data in the response waiting\n\t// to be read, and we should just return <res> to the caller.\n\t// The rationale for this is based on a few observations:\n\t// 1) Very large extended responses are unlikely, and so we are catering to the most common\n\t// case\n\t// 2) It's a safer strategy than assuming a large uint32 and trying to read the corresponding\n\t// data from <p>, which would block.\n\t// 3) Users who actually find they are actually getting bitten by this issue can still work\n\t// around it by reading the data from <p> themselves.\n\n\tif res < 0 {\n\t\treturn res, nil, nil\n\t}\n\n\text = make([]byte, res)\n\t_, err = io.ReadFull(p, ext)\n\treturn res, ext, err\n}", "func (sh *Shell) runCommandUnix(cmd string, timeout time.Duration) (out string, err error) {\n\n\t// Forge token and command, and send to remote\n\ttoken := randStringBytesRmndr()\n\tforgedCmd := sh.forgeCommand(cmd, token)\n\n\tif err = sh.write(forgedCmd, timeout); err != nil {\n\t\tsh.Log.Error(err)\n\t\treturn\n\t}\n\tsh.Log.Debugf(tui.Green(\"command: \") + tui.Bold(cmd))\n\n\t// 2. Read connection.\n\tdone := make(chan struct{})\n\tprocessed := make(chan string, 1)\n\tgo func(chan struct{}, chan string) {\n\t\tdefer close(done)\n\t\tfor {\n\t\t\tselect {\n\t\t\tdefault:\n\t\t\t\t// Read all output until one/both tokens are found\n\t\t\t\toutput, err := sh.readCommandOuput(cmd, token, sh.tokenIndex)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn // We already logged the error\n\t\t\t\t}\n\n\t\t\t\t// Process output\n\t\t\t\tout, err = sh.processRawLine(output, cmd, token)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn // We already logged the error\n\t\t\t\t}\n\t\t\t\tprocessed <- out\n\t\t\t\treturn\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(done, processed)\n\n\t// We wait either for the response body, or a timeout.\n\tfor {\n\t\tselect {\n\t\tcase out = <-processed:\n\t\t\tsh.Log.Debugf(tui.Dim(\"result: \") + tui.Bold(cmd))\n\t\t\treturn out, nil\n\t\tcase <-time.After(timeout):\n\t\t\tclose(done)\n\t\t\t// We still give out, in case it has something in it still.\n\t\t\treturn out, fmt.Errorf(\"reading command result from conn stream timed out\")\n\t\t}\n\t}\n}", "func executeCommandC(client helm.Interface, cmd string) (*cobra.Command, string, error) {\n\targs, err := shellwords.Parse(cmd)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tbuf := new(bytes.Buffer)\n\n\tactionConfig := &action.Configuration{\n\t\tReleases: storage.Init(driver.NewMemory()),\n\t}\n\n\troot := newRootCmd(client, actionConfig, buf, args)\n\troot.SetOutput(buf)\n\troot.SetArgs(args)\n\n\tc, err := root.ExecuteC()\n\n\treturn c, buf.String(), err\n}", "func (esh *EventSourcedServer) handleCommand(cmd *protocol.Command, server protocol.EventSourced_HandleServer) error {\n\tmsgName := strings.TrimPrefix(cmd.Payload.GetTypeUrl(), protoAnyBase+\"/\")\n\tmessageType := proto.MessageType(msgName)\n\tif messageType.Kind() != reflect.Ptr {\n\t\treturn fmt.Errorf(\"messageType: %s is of non Ptr kind\", messageType)\n\t}\n\t// get a zero-ed message of this type\n\tif message, ok := reflect.New(messageType.Elem()).Interface().(proto.Message); ok {\n\t\t// and marshal onto it what we got as an any.Any onto it\n\t\terr := proto.Unmarshal(cmd.Payload.Value, message)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%s, %w\", err, ErrMarshal)\n\t\t} else {\n\t\t\t// we're ready to handle the proto message\n\t\t\tentityContext := esh.contexts[cmd.GetEntityId()]\n\t\t\tif commandHandler, ok := entityContext.EntityInstance.Instance.(CommandHandler); ok {\n\t\t\t\t// The gRPC implementation returns the rpc return method\n\t\t\t\t// and an error as a second return value.\n\t\t\t\t_, reply, errReturned := commandHandler.HandleCommand(server.Context(), message)\n\t\t\t\t// the error\n\t\t\t\tif errReturned != nil {\n\t\t\t\t\t// TCK says: TODO Expects entity.Failure, but gets lientAction.Action.Failure(Failure(commandId, msg)))\n\t\t\t\t\treturn NewProtocolFailure(protocol.Failure{\n\t\t\t\t\t\tCommandId: cmd.GetId(),\n\t\t\t\t\t\tDescription: errReturned.Error(),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\t// the reply\n\t\t\t\tcallReply, err := marshalAny(reply)\n\t\t\t\tif err != nil { // this should never happen\n\t\t\t\t\treturn NewProtocolFailure(protocol.Failure{\n\t\t\t\t\t\tCommandId: cmd.GetId(),\n\t\t\t\t\t\tDescription: fmt.Errorf(\"called return value at index 0 is no proto.Message. %w\", err).Error(),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\t// emitted events\n\t\t\t\tevents, err := marshalEventsAny(entityContext)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn NewProtocolFailure(protocol.Failure{\n\t\t\t\t\t\tCommandId: cmd.GetId(),\n\t\t\t\t\t\tDescription: err.Error(),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\t// snapshot\n\t\t\t\tsnapshot, err := esh.handleSnapshots(entityContext)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn NewProtocolFailure(protocol.Failure{\n\t\t\t\t\t\tCommandId: cmd.GetId(),\n\t\t\t\t\t\tDescription: err.Error(),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\treturn sendEventSourcedReply(&protocol.EventSourcedReply{\n\t\t\t\t\tCommandId: cmd.GetId(),\n\t\t\t\t\tClientAction: &protocol.ClientAction{\n\t\t\t\t\t\tAction: &protocol.ClientAction_Reply{\n\t\t\t\t\t\t\tReply: &protocol.Reply{\n\t\t\t\t\t\t\t\tPayload: callReply,\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\tEvents: events,\n\t\t\t\t\tSnapshot: snapshot,\n\t\t\t\t}, server)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (h *HttpServer) execAgentCmd(w http.ResponseWriter, r *http.Request) {\n\taddr := r.FormValue(\"agent\")\n\tmutex.Lock()\n\tagent := tcpServer.FindAgentByAddr(addr)\n\tmutex.Unlock()\n\tif agent == nil {\n\t\tlog.Printf(\"No agent of addr=%s\\n\", addr)\n\t\treturn\n\t}\n\tcmd := r.FormValue(\"cmd\")\n\tlog.Printf(\"exec agent command - agent=%s,cmd=%s,\\n\", addr, cmd)\n\tp, err := net.NewMessagePacket(0x0020, &skynet.Pstring{Value: proto.String(cmd)})\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tagent.Write(p)\n}", "func (c *Conn) handle(cmd string, arg string) {\n\t// If panic happens during command handling - send 421 response\n\t// and close connection.\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tc.writeResponse(421, EnhancedCode{4, 0, 0}, \"Internal server error\")\n\t\t\tc.Close()\n\n\t\t\tstack := debug.Stack()\n\t\t\tc.server.ErrorLog.Printf(\"panic serving %v: %v\\n%s\", c.conn.RemoteAddr(), err, stack)\n\t\t}\n\t}()\n\n\tif cmd == \"\" {\n\t\tc.protocolError(500, EnhancedCode{5, 5, 2}, \"Error: bad syntax\")\n\t\treturn\n\t}\n\n\tcmd = strings.ToUpper(cmd)\n\tswitch cmd {\n\tcase \"SEND\", \"SOML\", \"SAML\", \"EXPN\", \"HELP\", \"TURN\":\n\t\t// These commands are not implemented in any state\n\t\tc.writeResponse(502, EnhancedCode{5, 5, 1}, fmt.Sprintf(\"%v command not implemented\", cmd))\n\tcase \"HELO\", \"EHLO\", \"LHLO\":\n\t\tlmtp := cmd == \"LHLO\"\n\t\tenhanced := lmtp || cmd == \"EHLO\"\n\t\tif c.server.LMTP && !lmtp {\n\t\t\tc.writeResponse(500, EnhancedCode{5, 5, 1}, \"This is a LMTP server, use LHLO\")\n\t\t\treturn\n\t\t}\n\t\tif !c.server.LMTP && lmtp {\n\t\t\tc.writeResponse(500, EnhancedCode{5, 5, 1}, \"This is not a LMTP server\")\n\t\t\treturn\n\t\t}\n\t\tc.handleGreet(enhanced, arg)\n\tcase \"MAIL\":\n\t\tc.handleMail(arg)\n\tcase \"RCPT\":\n\t\tc.handleRcpt(arg)\n\tcase \"VRFY\":\n\t\tc.writeResponse(252, EnhancedCode{2, 5, 0}, \"Cannot VRFY user, but will accept message\")\n\tcase \"NOOP\":\n\t\tc.writeResponse(250, EnhancedCode{2, 0, 0}, \"I have sucessfully done nothing\")\n\tcase \"RSET\": // Reset session\n\t\tc.reset()\n\t\tc.writeResponse(250, EnhancedCode{2, 0, 0}, \"Session reset\")\n\tcase \"BDAT\":\n\t\tc.handleBdat(arg)\n\tcase \"DATA\":\n\t\tc.handleData(arg)\n\tcase \"QUIT\":\n\t\tc.writeResponse(221, EnhancedCode{2, 0, 0}, \"Bye\")\n\t\tc.Close()\n\tcase \"AUTH\":\n\t\tif c.server.AuthDisabled {\n\t\t\tc.protocolError(500, EnhancedCode{5, 5, 2}, \"Syntax error, AUTH command unrecognized\")\n\t\t} else {\n\t\t\tc.handleAuth(arg)\n\t\t}\n\tcase \"STARTTLS\":\n\t\tc.handleStartTLS()\n\tdefault:\n\t\tmsg := fmt.Sprintf(\"Syntax errors, %v command unrecognized\", cmd)\n\t\tc.protocolError(500, EnhancedCode{5, 5, 2}, msg)\n\t}\n}", "func execCommand(cmd string, conn sql.DB) {\n\tvar id int\n\tvar response string\n\treceived := false\n\titerations := 0\n\n\tinsertSql := \"insert into requests (cmd) output inserted.ID values ('\" + cmd + \"'); select SCOPE_IDENTITY();\"\n\t\n\terr := conn.QueryRow(insertSql).Scan(&id)\n\tif err != nil {\n\t\tlog.Println(\"Unable to execute insert:\", err)\n\t\treturn\n\t}\n\tlog.Println(\"[i] Queued tasking: \", cmd)\n\tfor received == false && iterations < 10 {\n\t\ttime.Sleep(3 * time.Second)\n\n\t\tselectSql := \"select response from responses where request_id = \"\n\t\tselectErr := conn.QueryRow(selectSql + strconv.Itoa(id)).Scan(&response)\n\t\tif selectErr != nil {\n\t\t\tlog.Println(\"Waiting for response...\")\n\t\t\titerations++\n\t\t\tif iterations == 10 {\n\t\t\t\tlog.Println(\"Unable to receive response: \", selectErr)\n\t\t\t}\n\t\t} else {\n\t\t\treceived = true\n\t\t\tlog.Println(response)\n\t\t}\n\t}\n}", "func GetCommand(input string) (string, string) {\n\n\t\tinputs := strings.Split(input, \"\\r\\n\")\n\t\tn1 := len(inputs)\n\t\tn := len(inputs[0])\n\n\t\tcom, rem := \"\", \"\"\n\t\tif n >= 3 && (inputs[0][0:3] == \"set\" || inputs[0][0:3] == \"cas\") {\n\t\t\t// start of a 2 line command\n\t\t\tif n1 < 3 { // includes \"\\r\\n\"\n\t\t\t\treturn \"\", input // if the command is not complete, wait for the rest of the command\n\t\t\t}\n\t\t\tvar in = strings.Index(input, \"\\r\\n\") + 2\n\t\t\tin += strings.Index(input[in:], \"\\r\\n\") + 2\n\t\t\tcom = input[:in]\n\t\t\trem = input[in:]\n\t\t} else if (n >= 3 && inputs[0][0:3] == \"get\") || (n >= 4 && inputs[0][0:4] == \"getm\") ||(n >= 6 && inputs[0][0:6] == \"delete\") {\n\t\t\t// start of a 1 line command\n\t\t\tif n1 < 2 { // includes \"\\r\\n\"\n\t\t\t\treturn \"\", input // if the command is not complete, wait for the rest of the command\n\t\t\t}\n\t\t\tvar in = strings.Index(input, \"\\r\\n\") + 2\n\t\t\tcom = input[:in]\n\t\t\trem = input[in:]\n\t\t} else {\n\t\t\treturn \"\", input\n\t\t}\n\t\treturn com, rem\n}", "func (vsdsp *KramerVP558) SendCommand(ctx context.Context, cmd []byte, readAgain bool) ([]byte, error) {\n\tvar resp []byte\n\n\terr := vsdsp.pool.Do(ctx, func(conn connpool.Conn) error {\n\t\t_ = conn.SetWriteDeadline(time.Now().Add(5 * time.Second))\n\t\treadDur := time.Now().Add(3 * time.Second)\n\n\t\tn, err := conn.Write(cmd)\n\t\tswitch {\n\t\tcase err != nil:\n\t\t\treturn err\n\t\tcase n != len(cmd):\n\t\t\treturn fmt.Errorf(\"wrote %v/%v bytes of command 0x%x\", n, len(cmd), cmd)\n\t\t}\n\n\t\tresp, err = conn.ReadUntil(LINE_FEED, readDur)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to read response: %w\", err)\n\t\t}\n\t\tif readAgain {\n\t\t\t_, err = conn.ReadUntil(LINE_FEED, readDur)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to read response: %w\", err)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func PostCommand(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tvars := mux.Vars(r)\n\tid, err := strconv.Atoi(vars[\"id\"])\n\tcommand := vars[\"command\"]\n\n\t// This shouldn't happen since the mux only accepts numbers to this route\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid Id, please try again.\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tmodules := hardware.GetModules()\n\tmodule, err := getModuleByID(modules, id)\n\n\tif err != nil {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tsuccess := hardware.SendCommand(module.Pin, command)\n\tenc := json.NewEncoder(w)\n\terr = enc.Encode(successStruct{success})\n}", "func (httpClient *HTTPClient) send(rpcCmd common.RpcCmd, requestData interface{}, responseData interface{}) error {\n\t// Create HTTP request with command in query parameter & request data as JSON payload\n\trequestJson, err := json.Marshal(requestData)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error marshalling request payload for command type %q\", rpcCmd.String())\n\t}\n\trequest, err := http.NewRequest(\"POST\", httpClient.url, bytes.NewReader(requestJson))\n\t// adding the commandType as a query param\n\tq := request.URL.Query()\n\tq.Add(\"commandType\", rpcCmd.String())\n\trequest.URL.RawQuery = q.Encode()\n\n\tresponse, err := httpClient.client.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Read response data, deserialie it and return it (via out responseData parameter) & error\n\tresponseJson, err := ioutil.ReadAll(response.Body)\n\tresponse.Body.Close()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading response for the request\")\n\t}\n\terr = json.Unmarshal(responseJson, responseData)\n\tcommon.PanicIfErr(err)\n\treturn nil\n}", "func (client *VirtualMachineScaleSetVMRunCommandsClient) getHandleResponse(resp *http.Response) (VirtualMachineScaleSetVMRunCommandsGetResponse, error) {\n\tresult := VirtualMachineScaleSetVMRunCommandsGetResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineRunCommand); err != nil {\n\t\treturn VirtualMachineScaleSetVMRunCommandsGetResponse{}, runtime.NewResponseError(err, resp)\n\t}\n\treturn result, nil\n}", "func bytesToCmd(b []byte) interface{} {\n\tr := bytes.NewReader(b)\n\tdec := gob.NewDecoder(r)\n\tvar c Command\n\tif err := dec.Decode(&c); nil != err {\n\t\tlog.Fatalf(\"failed to decode command: %s\", err)\n\t\treturn Command{}\n\t}\n\treturn c.Cmd\n}", "func (h *Handler) CreateCommand(w http.ResponseWriter, r *http.Request) {\n\t// Decode request.\n\tvar cmd sigstat.Command\n\n\tif err := json.NewDecoder(r.Body).Decode(&cmd); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t//Create command\n\tid, errc := h.client.CommandService().CreateCommand(cmd)\n\n\t//Handle error from client\n\tif errc != nil {\n\t\tif err := json.NewEncoder(w).Encode(&createCommandResponse{Err: errc.Error()}); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\t//Handle json serialization\n\tif err := json.NewEncoder(w).Encode(&createCommandResponse{GroupID: id}); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func processAPIReq(c net.Conn) {\n\tfor {\n\t\tbuf := make([]byte, 512)\n\t\tnr, err := c.Read(buf)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tdata := buf[0:nr]\n\n\t\t// deal with the command\n\t\tcmd := string(data)\n\t\tcmd = strings.TrimSpace(cmd)\n\t\terr = CmdHandler(cmd)\n\t\tCliPrintInfo(\"emp3r0r received %s\", strconv.Quote(cmd))\n\t\tif err != nil {\n\t\t\tCliPrintError(\"Command failed: %v\", err)\n\t\t}\n\t}\n}", "func GetCommandFunction(cr *CommandReference) interface{} {\n\tswitch cr.Type {\n\tcase CommandType_cmd_vkCmdBeginRenderPass:\n\t\treturn subDovkCmdBeginRenderPass\n\tcase CommandType_cmd_vkCmdEndRenderPass:\n\t\treturn subDovkCmdEndRenderPass\n\tcase CommandType_cmd_vkCmdNextSubpass:\n\t\treturn subDovkCmdNextSubpass\n\tcase CommandType_cmd_vkCmdBindPipeline:\n\t\treturn subDovkCmdBindPipeline\n\tcase CommandType_cmd_vkCmdBindDescriptorSets:\n\t\treturn subDovkCmdBindDescriptorSets\n\tcase CommandType_cmd_vkCmdBindVertexBuffers:\n\t\treturn subDovkCmdBindVertexBuffers\n\tcase CommandType_cmd_vkCmdBindIndexBuffer:\n\t\treturn subDovkCmdBindIndexBuffer\n\tcase CommandType_cmd_vkCmdPipelineBarrier:\n\t\treturn subDovkCmdPipelineBarrier\n\tcase CommandType_cmd_vkCmdWaitEvents:\n\t\treturn subDovkCmdWaitEvents\n\tcase CommandType_cmd_vkCmdBeginQuery:\n\t\treturn subDovkCmdBeginQuery\n\tcase CommandType_cmd_vkCmdBlitImage:\n\t\treturn subDovkCmdBlitImage\n\tcase CommandType_cmd_vkCmdClearAttachments:\n\t\treturn subDovkCmdClearAttachments\n\tcase CommandType_cmd_vkCmdClearColorImage:\n\t\treturn subDovkCmdClearColorImage\n\tcase CommandType_cmd_vkCmdClearDepthStencilImage:\n\t\treturn subDovkCmdClearDepthStencilImage\n\tcase CommandType_cmd_vkCmdCopyBuffer:\n\t\treturn subDovkCmdCopyBuffer\n\tcase CommandType_cmd_vkCmdCopyBufferToImage:\n\t\treturn subDovkCmdCopyBufferToImage\n\tcase CommandType_cmd_vkCmdCopyImage:\n\t\treturn subDovkCmdCopyImage\n\tcase CommandType_cmd_vkCmdCopyImageToBuffer:\n\t\treturn subDovkCmdCopyImageToBuffer\n\tcase CommandType_cmd_vkCmdCopyQueryPoolResults:\n\t\treturn subDovkCmdCopyQueryPoolResults\n\tcase CommandType_cmd_vkCmdDispatch:\n\t\treturn subDovkCmdDispatch\n\tcase CommandType_cmd_vkCmdDispatchIndirect:\n\t\treturn subDovkCmdDispatchIndirect\n\tcase CommandType_cmd_vkCmdDraw:\n\t\treturn subDovkCmdDraw\n\tcase CommandType_cmd_vkCmdDrawIndexed:\n\t\treturn subDovkCmdDrawIndexed\n\tcase CommandType_cmd_vkCmdDrawIndexedIndirect:\n\t\treturn subDovkCmdDrawIndexedIndirect\n\tcase CommandType_cmd_vkCmdDrawIndirect:\n\t\treturn subDovkCmdDrawIndirect\n\tcase CommandType_cmd_vkCmdEndQuery:\n\t\treturn subDovkCmdEndQuery\n\tcase CommandType_cmd_vkCmdExecuteCommands:\n\t\treturn subDovkCmdExecuteCommands\n\tcase CommandType_cmd_vkCmdFillBuffer:\n\t\treturn subDovkCmdFillBuffer\n\tcase CommandType_cmd_vkCmdPushConstants:\n\t\treturn subDovkCmdPushConstants\n\tcase CommandType_cmd_vkCmdResetQueryPool:\n\t\treturn subDovkCmdResetQueryPool\n\tcase CommandType_cmd_vkCmdResolveImage:\n\t\treturn subDovkCmdResolveImage\n\tcase CommandType_cmd_vkCmdSetBlendConstants:\n\t\treturn subDovkCmdSetBlendConstants\n\tcase CommandType_cmd_vkCmdSetDepthBias:\n\t\treturn subDovkCmdSetDepthBias\n\tcase CommandType_cmd_vkCmdSetDepthBounds:\n\t\treturn subDovkCmdSetDepthBounds\n\tcase CommandType_cmd_vkCmdSetEvent:\n\t\treturn subDovkCmdSetEvent\n\tcase CommandType_cmd_vkCmdResetEvent:\n\t\treturn subDovkCmdResetEvent\n\tcase CommandType_cmd_vkCmdSetLineWidth:\n\t\treturn subDovkCmdSetLineWidth\n\tcase CommandType_cmd_vkCmdSetScissor:\n\t\treturn subDovkCmdSetScissor\n\tcase CommandType_cmd_vkCmdSetStencilCompareMask:\n\t\treturn subDovkCmdSetStencilCompareMask\n\tcase CommandType_cmd_vkCmdSetStencilReference:\n\t\treturn subDovkCmdSetStencilReference\n\tcase CommandType_cmd_vkCmdSetStencilWriteMask:\n\t\treturn subDovkCmdSetStencilWriteMask\n\tcase CommandType_cmd_vkCmdSetViewport:\n\t\treturn subDovkCmdSetViewport\n\tcase CommandType_cmd_vkCmdUpdateBuffer:\n\t\treturn subDovkCmdUpdateBuffer\n\tcase CommandType_cmd_vkCmdWriteTimestamp:\n\t\treturn subDovkCmdWriteTimestamp\n\tcase CommandType_cmd_vkCmdDebugMarkerBeginEXT:\n\t\treturn subDovkCmdDebugMarkerBeginEXT\n\tcase CommandType_cmd_vkCmdDebugMarkerEndEXT:\n\t\treturn subDovkCmdDebugMarkerEndEXT\n\tcase CommandType_cmd_vkCmdDebugMarkerInsertEXT:\n\t\treturn subDovkCmdDebugMarkerInsertEXT\n\tdefault:\n\t\tx := fmt.Sprintf(\"Should not reach here: %T\", cr)\n\t\tpanic(x)\n\t}\n}", "func rcRunCommand(ctx context.Context, in Params) (out Params, err error) {\n\tcommand, err := in.GetString(\"command\")\n\tif err != nil {\n\t\tcommand = \"\"\n\t}\n\n\tvar opt = map[string]string{}\n\terr = in.GetStructMissingOK(\"opt\", &opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar arg = []string{}\n\terr = in.GetStructMissingOK(\"arg\", &arg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturnType, err := in.GetString(\"returnType\")\n\tif err != nil {\n\t\treturnType = \"COMBINED_OUTPUT\"\n\t}\n\n\tvar httpResponse http.ResponseWriter\n\thttpResponse, err = in.GetHTTPResponseWriter()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"response object is required\\n\" + err.Error())\n\t}\n\n\tvar allArgs = []string{}\n\tif command != \"\" {\n\t\t// Add the command e.g.: ls to the args\n\t\tallArgs = append(allArgs, command)\n\t}\n\t// Add all from arg\n\tallArgs = append(allArgs, arg...)\n\n\t// Add flags to args for e.g. --max-depth 1 comes in as { max-depth 1 }.\n\t// Convert it to [ max-depth, 1 ] and append to args list\n\tfor key, value := range opt {\n\t\tif len(key) == 1 {\n\t\t\tallArgs = append(allArgs, \"-\"+key)\n\t\t} else {\n\t\t\tallArgs = append(allArgs, \"--\"+key)\n\t\t}\n\t\tallArgs = append(allArgs, value)\n\t}\n\n\t// Get the path for the current executable which was used to run rclone.\n\tex, err := os.Executable()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcmd := exec.CommandContext(ctx, ex, allArgs...)\n\n\tif returnType == \"COMBINED_OUTPUT\" {\n\t\t// Run the command and get the output for error and stdout combined.\n\n\t\tout, err := cmd.CombinedOutput()\n\n\t\tif err != nil {\n\t\t\treturn Params{\n\t\t\t\t\"result\": string(out),\n\t\t\t\t\"error\": true,\n\t\t\t}, nil\n\t\t}\n\t\treturn Params{\n\t\t\t\"result\": string(out),\n\t\t\t\"error\": false,\n\t\t}, nil\n\t} else if returnType == \"STREAM_ONLY_STDOUT\" {\n\t\tcmd.Stdout = httpResponse\n\t} else if returnType == \"STREAM_ONLY_STDERR\" {\n\t\tcmd.Stderr = httpResponse\n\t} else if returnType == \"STREAM\" {\n\t\tcmd.Stdout = httpResponse\n\t\tcmd.Stderr = httpResponse\n\t} else {\n\t\treturn nil, fmt.Errorf(\"unknown returnType %q\", returnType)\n\t}\n\n\terr = cmd.Run()\n\treturn nil, err\n}", "func proxyCommand(w http.ResponseWriter, r *http.Request) {\n\tr.ParseForm()\n\tcommand := r.FormValue(\"command\")\n\targs := strings.Split(command, \" \")\n\n\tif len(args) == 0 {\n\t\tfmt.Fprintf(w, \"Bad command (%s)\\n\", command)\n\t\treturn\n\t}\n\t// If this is \"cd\", then change working directory.\n\tif args[0] == \"cd\" {\n\t\tif len(args) < 2 {\n\t\t\tfmt.Fprintln(w, \"'cd' must be followed with new directory!\")\n\t\t} else {\n\t\t\terr := os.Chdir(args[1])\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintln(w, err.Error())\n\t\t\t} else {\n\t\t\t\tfmt.Fprintln(w, \"Switched directory to\", args[1])\n\t\t\t}\n\t\t\tshellDir = args[1]\n\t\t}\n\t\treturn\n\t}\n\t// Expand any arguments with wildcard.\n\tfullArgs := []string{}\n\tfor _, arg := range args {\n\t\tif strings.Contains(arg, \"*\") {\n\t\t\tmatches, err := filepath.Glob(arg)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Can't parse glob: %s [%s]\\n\", arg, err.Error())\n\t\t\t} else {\n\t\t\t\tfullArgs = append(fullArgs, matches...)\n\t\t\t}\n\t\t} else {\n\t\t\tfullArgs = append(fullArgs, arg)\n\t\t}\n\t}\n\n\t// Check for \"&\" at end to signify asynchronous command like server starts.\n\tlastArg := len(fullArgs) - 1\n\trunBackground := false\n\tif fullArgs[lastArg] == \"&\" {\n\t\trunBackground = true\n\t\tfullArgs = fullArgs[:lastArg]\n\t}\n\n\t// Do the command\n\tcmd := exec.Command(fullArgs[0], fullArgs[1:]...)\n\tvar out []byte\n\tvar err error\n\tif runBackground {\n\t\terr = cmd.Start()\n\t\tout = []byte(fmt.Sprintf(\"Ran background job: %s\\n\", command))\n\t} else {\n\t\tout, err = cmd.Output()\n\t}\n\tif err != nil {\n\t\tfmt.Println(\"Error: \", err.Error())\n\t\tfmt.Fprintln(w, err.Error())\n\t} else {\n\t\tfmt.Fprintln(w, string(out))\n\t}\n}", "func (d *DV4Mini) sendCmd(data []byte) {\n\tb := CmdPreamble\n\tparams := data[1:]\n\tcmd := data[0]\n\n\t// Set command\n\tb = append(b, cmd)\n\t// Set param length\n\tb = append(b, byte(len(params)))\n\t// Set params\n\tb = append(b, params...)\n\n\tif debug {\n\t\tlog.Printf(\"\\t[*] serial.write: %#v (len: %d)\\n\", b, len(b))\n\t}\n\n\t_, err := d.Port.Write(b)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func doCommand(doppelgangerState *userInfo, command string) (bool, error) {\n\t//\n\t// Find the space and break the command into command + operand.\n\t//\n\toperand := \"\"\n\tii := strings.Index(command, \" \")\n\tif ii > 0 {\n\t\toperand = trim(command[ii:])\n\t\tcommand = command[:ii]\n\t}\n\t//\n\t// We convert \"say\", \"think\", and \"sing\" into \"emote\". Everything said\n\t// is ultimate said with \"emote\".\n\t//\n\temoteParameter := \"\"\n\tswitch command {\n\tcase \"/say\":\n\t\tcommand = \"/emote\"\n\t\temoteParameter = doppelgangerState.userName + \" says, \" + `\"` + operand + `\"`\n\tcase \"/think\":\n\t\tcommand = \"/emote\"\n\t\temoteParameter = doppelgangerState.userName + \" thinks . o O ( \" + operand + \" )\"\n\tcase \"/sing\":\n\t\tcommand = \"/emote\"\n\t\temoteParameter = doppelgangerState.userName + \" sings ~ ~ \" + operand + \" ~ ~\"\n\tcase \"/emote\":\n\t\temoteParameter = doppelgangerState.userName + \" \" + operand\n\t}\n\t//\n\t// here's where we execute commands!\n\t//\n\tswitch command {\n\tcase \"/create\":\n\t\t//\n\t\t// Remove (optional) prepended \"#\" if there is one.\n\t\t//\n\t\tif len(operand) > 1 {\n\t\t\tif operand[0] == '#' {\n\t\t\t\toperand = trim(operand[1:])\n\t\t\t}\n\t\t}\n\t\tif operand == \"\" {\n\t\t\t_, err := oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\nPlease specify a channel name to create.\\r\\n\"))\n\t\t\treturn true, err // can be nil\n\t\t}\n\t\talreadyExisted, err := createChatchannel(operand)\n\t\tif err != nil {\n\t\t\t//\n\t\t\t// We can't return an error because that would indicate to the\n\t\t\t// caller that the user has dropped the connection, and it will\n\t\t\t// exit the doppelganger. But if the error occurred in the db\n\t\t\t// layer, the user is still here. So we log the error, send the\n\t\t\t// user a generic message, and try to keep going.\n\t\t\t//\n\t\t\tlog.Println(err)\n\t\t\t_, err := oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\nA database error has occurred.\\r\\n\"))\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t} else {\n\t\t\tif alreadyExisted {\n\t\t\t\t_, err = oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\nChannel already exists.\\r\\n\"))\n\t\t\t} else {\n\t\t\t\t_, err = oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\nChannel \\\"#\"+operand+\"\\\" created.\\r\\n\"))\n\t\t\t}\n\t\t\treturn true, err // err can be nil\n\t\t}\n\tcase \"/list\":\n\t\tchatChannelList, err := getChatchannelList()\n\t\tif err != nil {\n\t\t\t//\n\t\t\t// We can't return an error because that would indicate to the\n\t\t\t// caller that the user has dropped the connection, and it will exit\n\t\t\t// the doppelganger. But if the error occurred in the db layer, the\n\t\t\t// user is still here. So we log the error, send the user a generic\n\t\t\t// message, and try to keep going.\n\t\t\t//\n\t\t\tlog.Println(err)\n\t\t\t_, err = oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\nA database error has occurred.\\r\\n\"))\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\t\t//\n\t\t// User's carriage return was not echoed.\n\t\t//\n\t\t_, err = oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\n\"))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tfor _, chatChanName := range chatChannelList {\n\t\t\t_, err = oi.LongWrite(doppelgangerState.writer, []byte(\"#\"+chatChanName+\"\\r\\n\"))\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\tcase \"/join\":\n\t\tif doppelgangerState.userID == 0 {\n\t\t\t//\n\t\t\t// This should be impossible to happen because we don't let the\n\t\t\t// user type any commands unless they have successfully completed\n\t\t\t// the login. Nonetheless if they do somehow get here, we do the\n\t\t\t// sensible thing.\n\t\t\t//\n\t\t\t_, err := oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\nYou have to log in before you can join a channel.\\r\\n\"))\n\t\t\treturn true, err // err can be nil\n\t\t} else {\n\t\t\t//\n\t\t\t// Now, to make a truly user-friendly system, when the user asks\n\t\t\t// to join a channel when they are already on another channel,\n\t\t\t// we'd query the new channel to see if we can join, exit our\n\t\t\t// current channel if we can, and then join the new channel, all\n\t\t\t// automatically. But, in the interest of getting this program\n\t\t\t// done, we're going to short-cut that and require the user to\n\t\t\t// explicitly exit their current channel before allowing them to\n\t\t\t// join a new one.\n\t\t\t//\n\t\t\tif doppelgangerState.chatChannelID > 0 {\n\t\t\t\t_, err := oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\nYou have to exit your current channel before you can join a new channel.\\r\\n\"))\n\t\t\t\treturn true, err // err can be nil\n\t\t\t}\n\t\t\tvar theMessage messageFromDoppelgangerToChannelMaster\n\t\t\ttheMessage.userID = doppelgangerState.userID\n\t\t\ttheMessage.userName = doppelgangerState.userName\n\t\t\ttheMessage.doppelgangerID = doppelgangerState.doppelgangerID\n\t\t\ttheMessage.operation = fromDoppelgangerToChannelMasterOpJoin\n\t\t\ttheMessage.parameter = operand\n\t\t\ttheMessage.doppelgangerCallbackFromChannelMaster = doppelgangerState.incomingFromChannelMaster\n\t\t\ttheMessage.doppelgangerCallbackFromChatChannel = doppelgangerState.incomingFromChatChannel\n\t\t\tif global.chanMasterFromDoppelgangerGoChan == nil {\n\t\t\t\t//\n\t\t\t\t// Should never happen.\n\t\t\t\t//\n\t\t\t\tlogError(\"doppelganger ID \" + int64ToStr(doppelgangerState.doppelgangerID) + \" user ID \" + int64ToStr(doppelgangerState.userID) + \" error: global.chanMasterFromDoppelgangerGoChan == nil\")\n\t\t\t\treturn false, nil // Try and keep server up (kind of laughable if the go channel to the channel master is gone, though)\n\t\t\t}\n\t\t\t//\n\t\t\t// Here try to prevent the \"send on closed channel\" error that can\n\t\t\t// occur later on. By changing the chat channel ID here to something\n\t\t\t// OTHER than 0, we signal that we need to keep this goroutine (the\n\t\t\t// doppelganger) going until we've joined and exited the channel.\n\t\t\t// If we left it 0, then a disconnect from the user would cause the\n\t\t\t// channel to be closed and this goroutine to exit, and then AFTER\n\t\t\t// that the chat channel goroutine would receive the join request,\n\t\t\t// and try to send the response on the closed channel, causing the\n\t\t\t// \"send on closed channel\"\n\t\t\t//\n\t\t\tdoppelgangerState.chatChannelID = -1\n\t\t\tglobal.chanMasterFromDoppelgangerGoChan <- theMessage\n\t\t\treturn false, nil\n\t\t}\n\tcase \"/who\":\n\t\tif doppelgangerState.userID == 0 {\n\t\t\t//\n\t\t\t// This should be impossible to happen because we don't let the\n\t\t\t// user type any commands unless they have successfully completed\n\t\t\t// the login. Nonetheless if they do somehow get here, we do the\n\t\t\t// sensible thing.\n\t\t\t//\n\t\t\t_, err := oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\nYou are not logged in.\\r\\n\"))\n\t\t\treturn true, err // err can be nil\n\t\t} else {\n\t\t\tif doppelgangerState.chatChannelID == 0 {\n\t\t\t\t_, err := oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\nYou are not on a channel.\\r\\n\"))\n\t\t\t\treturn true, err // err can be nil\n\t\t\t} else {\n\t\t\t\t_, err := oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\n\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn true, err\n\t\t\t\t}\n\t\t\t\tvar theMessage messageFromDoppelgangerToChannelMaster\n\t\t\t\ttheMessage.userID = doppelgangerState.userID\n\t\t\t\ttheMessage.userName = doppelgangerState.userName\n\t\t\t\ttheMessage.chatChannelID = doppelgangerState.chatChannelID\n\t\t\t\ttheMessage.operation = fromDoppelgangerToChannelMasterOpWho\n\t\t\t\ttheMessage.parameter = operand\n\t\t\t\ttheMessage.doppelgangerCallbackFromChannelMaster = doppelgangerState.incomingFromChannelMaster\n\t\t\t\ttheMessage.doppelgangerCallbackFromChatChannel = doppelgangerState.incomingFromChatChannel\n\t\t\t\tif global.chanMasterFromDoppelgangerGoChan == nil {\n\t\t\t\t\t//\n\t\t\t\t\t// Should never happen.\n\t\t\t\t\t//\n\t\t\t\t\tlogError(\"doppelganger ID \" + int64ToStr(doppelgangerState.doppelgangerID) + \" user ID \" + int64ToStr(doppelgangerState.userID) + \" error: global.chanMasterFromDoppelgangerGoChan == nil\")\n\t\t\t\t\treturn false, nil // Try and keep server up (kind of laughable if the go channel to the channel master is gone, though)\n\t\t\t\t}\n\t\t\t\tglobal.chanMasterFromDoppelgangerGoChan <- theMessage\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\tcase \"/exit\":\n\t\tif doppelgangerState.userID == 0 {\n\t\t\t//\n\t\t\t// This should be impossible to happen because we don't let the\n\t\t\t// user type any commands unless they have successfully completed\n\t\t\t// the login. Nonetheless if they do somehow get here, we do the\n\t\t\t// sensible thing.\n\t\t\t//\n\t\t\t_, err := oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\nYou are not logged in.\\r\\n\"))\n\t\t\treturn true, err // err can be nil\n\t\t} else {\n\t\t\tif doppelgangerState.chatChannelID == 0 {\n\t\t\t\t_, err := oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\nYou are not on a channel. You have to join a channel before you can exit it.\\r\\n\"))\n\t\t\t\treturn true, err // err can be nil\n\t\t\t} else {\n\t\t\t\t_, err := oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\n\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn true, err\n\t\t\t\t}\n\t\t\t\tvar theMessage messageFromDoppelgangerToChannelMaster\n\t\t\t\ttheMessage.operation = fromDoppelgangerToChannelMasterOpExit\n\t\t\t\ttheMessage.userID = doppelgangerState.userID\n\t\t\t\ttheMessage.userName = doppelgangerState.userName\n\t\t\t\ttheMessage.doppelgangerID = doppelgangerState.doppelgangerID\n\t\t\t\ttheMessage.chatChannelID = doppelgangerState.chatChannelID\n\t\t\t\ttheMessage.parameter = operand // we could say the name of the channel we're leaving, but it'll be ignored so don't bother\n\t\t\t\ttheMessage.doppelgangerCallbackFromChannelMaster = doppelgangerState.incomingFromChannelMaster\n\t\t\t\ttheMessage.doppelgangerCallbackFromChatChannel = doppelgangerState.incomingFromChatChannel\n\t\t\t\tif global.chanMasterFromDoppelgangerGoChan == nil {\n\t\t\t\t\t//\n\t\t\t\t\t// Should never happen.\n\t\t\t\t\t//\n\t\t\t\t\tlogError(\"doppelganger ID \" + int64ToStr(doppelgangerState.doppelgangerID) + \" user ID \" + int64ToStr(doppelgangerState.userID) + \" error: global.chanMasterFromDoppelgangerGoChan == nil\")\n\t\t\t\t\treturn false, nil // Try and keep server up (kind of laughable if the go channel to the channel master is gone, though)\n\t\t\t\t}\n\t\t\t\tglobal.chanMasterFromDoppelgangerGoChan <- theMessage\n\t\t\t\t//\n\t\t\t\t// We go ahead and set our chat channel to 0 to pre-empt the\n\t\t\t\t// possibility of sending that chat channel goroutine any more\n\t\t\t\t// messages. HOWEVER we can't actually exit until we get the call\n\t\t\t\t// back from the chat channel telling us we're off the channel.\n\t\t\t\t//\n\t\t\t\tdoppelgangerState.chatChannelID = 0\n\t\t\t\tdoppelgangerState.chatChannelName = \"(no channel)\"\n\t\t\t\tdoppelgangerState.cantExitBeforeExitMessageFromChannel = true\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\tcase \"/emote\":\n\t\tif doppelgangerState.chatChannelID != 0 {\n\t\t\t//\n\t\t\t// If we're not on a channel, we leave what the user typed visible.\n\t\t\t// Otherwise, we backspace out so when it bounces back on the\n\t\t\t// channel, it will replace the line the user typed.\n\t\t\t//\n\t\t\t// We backspace out just what the user typed because the prompt will\n\t\t\t// get backspaced out when the speech comes back.\n\t\t\terr := backspaceOut(doppelgangerState, doppelgangerState.cursorColumn)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\t\tif doppelgangerState.userID == 0 {\n\t\t\t//\n\t\t\t// This should be impossible to happen because we don't let the user\n\t\t\t// type any commands unless they have successfully completed the\n\t\t\t// login. Nonetheless if they do somehow get here, we do the\n\t\t\t// sensible thing.\n\t\t\t//\n\t\t\t_, err := oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\nYou have to log in before you can talk on a channel.\\r\\n\"))\n\t\t\treturn false, err // err can be nil\n\t\t} else {\n\t\t\tif doppelgangerState.chatChannelID == 0 {\n\t\t\t\t//\n\t\t\t\t// Carriage return because we're not going to backspace out,\n\t\t\t\t// we're going to go to the next line and give an error message.\n\t\t\t\t//\n\t\t\t\t_, err := oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\nYou have to join a channel before you can say anything on a channel. Right now you're just talking to yourself.\\r\\n\"))\n\t\t\t\treturn true, err // err can be nil\n\t\t\t} else {\n\t\t\t\tvar newMsg messageFromDoppelgangerToChatChannel\n\t\t\t\tnewMsg.operation = fromDoppelgangerToChatChannelOpTextMessage\n\t\t\t\tnewMsg.userID = doppelgangerState.userID\n\t\t\t\tnewMsg.parameter = emoteParameter\n\t\t\t\tif doppelgangerState.chatChannelCallback == nil {\n\t\t\t\t\t//\n\t\t\t\t\t// Should never happen.\n\t\t\t\t\t//\n\t\t\t\t\tlogError(\"doppelganger ID \" + int64ToStr(doppelgangerState.doppelgangerID) + \" user ID \" + int64ToStr(doppelgangerState.userID) + \" error: doppelgangerState.chatChannelCallback == nil\")\n\t\t\t\t\treturn false, nil // Try and keep server up\n\t\t\t\t}\n\t\t\t\tdoppelgangerState.chatChannelCallback <- newMsg\n\t\t\t}\n\t\t}\n\tcase \"/help\":\n\t\t_, err := oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\n\\r\\n/list -- list channels\\r\\n/create <channelname> -- create a channel\\r\\n/join <channelname> -- join a channel\\r\\n/who -- show who is on the current channel\\r\\n/exit -- exit the current channel\\r\\n\\r\\nOnce on a channel:\\r\\n/say -- say something on the current channel\\r\\n/emote -- emote on current channel\\r\\n/think -- think something on current channel\\r\\n/sing -- sing something on current channel\\r\\n\\r\\n/help -- this command\\r\\n\\r\\nAbbreviations:\\r\\n' -- say\\r\\n; -- emote\\r\\n\\r\\n^D log off\\r\\n\\r\\n\"))\n\t\treturn true, err // err can be nil\n\tdefault:\n\t\t//\n\t\t// Carriage return needed because user's \"return\" wasn't echoed.\n\t\t//\n\t\t_, err := oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\n\"))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\t_, err = oi.LongWrite(doppelgangerState.writer, []byte(\"\\r\\nCommand \\\"\"+command+\"\\\" not recognized.\\r\\n\"))\n\t\treturn true, err // err can be nil\n\t}\n\treturn false, nil\n}", "func Process(c *Client, cmd Command) Reply {\n\tif c.State != Transaction {\n\t\treturn Reply{\n\t\t\tResult: ERR,\n\t\t\tMessage: \"invalid state\",\n\t\t}\n\t}\n\tenvs := db.List(c.GetString(\"authenticated_as\"), false)\n\tif cmd.Args == \"\" {\n\t\tcnt, sz := db.Stat(c.GetString(\"authenticated_as\"))\n\t\tmsg := []string{fmt.Sprintf(\"%v messages (%v octets)\", cnt, sz)}\n\t\tfor i, env := range envs {\n\t\t\tmsg = append(msg, fmt.Sprintf(\"%v %v\", i, len(env.Body)))\n\t\t}\n\t\tmsg = append(msg, \".\")\n\t\treturn Reply{\n\t\t\tResult: OK,\n\t\t\tMessage: strings.Join(msg, \"\\r\\n\"),\n\t\t}\n\t} else if cmd.Args != \"\" {\n\t\tfor i, env := range envs {\n\t\t\tif strconv.Itoa(i) == cmd.Args {\n\t\t\t\treturn Reply{\n\t\t\t\t\tResult: OK,\n\t\t\t\t\tMessage: fmt.Sprintf(\"%v %v\", i, len(env.Body)),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn Reply{\n\t\t\tResult: ERR,\n\t\t\tMessage: \"no such message\",\n\t\t}\n\t} else {\n\t\treturn Reply{\n\t\t\tResult: ERR,\n\t\t\tMessage: \"syntax error in command arguments\",\n\t\t}\n\t}\n}", "func (this *Device) Command(command api.ICommand) error {\n if this.commandProcessor == nil {\n return errors.New(fmt.Sprintf(ERR_NO_COMMAND_PROCESSOR, this.Info().String()))\n }\n\n var err error\n var commandString string\n\n if commandString, err = this.commandProcessor(this.Info().Mapify(), command); err == nil {\n err = this.Send([]byte(commandString))\n }\n\n return err\n}", "func (c *CmdRunner) ProcessCmd(id string, cmd *exec.Cmd) {\n\tc.Log.Debug(\"ProcessCmd got %s\", id)\n\n\t// add command to the commands map TODO close the readers\n\tc.Commands[id] = cmd\n\n\tcmdStdoutReader, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tcmdStderrReader, err := cmd.StderrPipe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tstdOutScanner := bufio.NewScanner(cmdStdoutReader)\n\tgo func() {\n\t\tfor stdOutScanner.Scan() {\n\t\t\tc.Messages <- CmdMessage{\n\t\t\t\tId: id,\n\t\t\t\tCommand: cmd.Path,\n\t\t\t\tMessage: stdOutScanner.Text(),\n\t\t\t\tError: false,\n\t\t\t\tCmd: cmd,\n\t\t\t}\n\t\t}\n\t}()\n\n\tstdErrScanner := bufio.NewScanner(cmdStderrReader)\n\tgo func() {\n\t\tfor stdErrScanner.Scan() {\n\t\t\tc.Messages <- CmdMessage{\n\t\t\t\tId: id,\n\t\t\t\tCommand: cmd.Path,\n\t\t\t\tMessage: stdErrScanner.Text(),\n\t\t\t\tError: true,\n\t\t\t\tCmd: cmd,\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = cmd.Start()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (c *SMTPClient) Cmd(expectCode int, format string, args ...interface{}) (int, string, error) {\n\tid, err := c.Text.Cmd(format, args...)\n\tif err != nil {\n\t\treturn 0, \"\", err\n\t}\n\tc.Text.StartResponse(id)\n\tdefer c.Text.EndResponse(id)\n\tcode, msg, err := c.Text.ReadResponse(expectCode)\n\treturn code, msg, err\n}", "func cmdCode(t *testing.T, conn net.Conn, cmd string, code string) {\n\tfmt.Fprintf(conn, \"%s\\r\\n\", cmd)\n\tresp, err := bufio.NewReader(conn).ReadString('\\n')\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to read response from test server: %v\", err)\n\t}\n\tif resp[0:3] != code {\n\t\tt.Errorf(\"Command \\\"%s\\\" response code is %s, want %s\", cmd, resp[0:3], code)\n\t}\n}", "func (u UnixSocketServer)readCommand(connection net.Conn){\n\tbuff:=make([]byte, 1024)\n\n\tdefer connection.Close()\t//\tclose connection on error\n\n\tfor{\n\t\tif size,err := connection.Read(buff);err == nil{\t//\tread message\n\t\tif size > 1{\n\t\t\tif data := utility.NewNotification(buff[:size]);data.Err == nil{\n\t\t\t\tconnection.Write([]byte(u.HandleReceive(data)))\t\t//send callback result\n\t\t\t}else{\n\t\t\t\tconnection.Write([]byte(data.Err.Error()+\"\\n\"))\t//\tresponse if error\n\t\t\t}\n\t\t}else{\n\t\t\tcontinue\n\t\t}\n\t\t}else{\n\t\t\tlog.Println(\"Error, incorrect read from unix domain socket, closing connection\")\n\t\t\treturn\n\t\t}\n\t}\n\n}", "func (sb *SweetieBot) ProcessCommand(m *discordgo.Message, info *GuildInfo, t int64, isdebug bool, private bool) {\n\tvar prefix byte = '!'\n\tif info != nil && len(info.Config.Basic.CommandPrefix) == 1 {\n\t\tprefix = info.Config.Basic.CommandPrefix[0]\n\t}\n\n\t// Check if this is a command. If it is, process it as a command, otherwise process it with our modules.\n\tif len(m.Content) > 1 && m.Content[0] == prefix && (len(m.Content) < 2 || m.Content[1] != prefix) { // We check for > 1 here because a single character can't possibly be a valid command\n\t\tisfree := private\n\t\tauthorid := SBatoi(m.Author.ID)\n\t\tchannelID := DiscordChannel(m.ChannelID)\n\t\tif info != nil {\n\t\t\t_, isfree = info.Config.Basic.FreeChannels[channelID]\n\t\t}\n\n\t\t// command := strings.ToLower(strings.SplitN(m.Content[1:], \" \", 2)[0])\n\t\targs, indices := ParseArguments(m.Content[1:])\n\t\targ := CommandID(strings.ToLower(args[0]))\n\t\tif info == nil {\n\t\t\tinfo = sb.GetDefaultServer(authorid)\n\t\t}\n\t\tif info == nil {\n\t\t\tgIDs := []uint64{}\n\t\t\tif _, independent := sb.EmptyGuild.commands[arg]; !independent {\n\t\t\t\tif !sb.DB.Status.Get() {\n\t\t\t\t\tsb.DG.ChannelMessageSend(m.ChannelID, StringMap[STRING_DATABASE_ERROR])\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tgIDs = sb.DB.GetUserGuilds(authorid)\n\t\t\t\tif len(gIDs) != 1 {\n\t\t\t\t\tsb.DG.ChannelMessageSend(m.ChannelID, StringMap[STRING_NO_SERVER])\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else if sb.DB.Status.Get() {\n\t\t\t\tgIDs = sb.DB.GetUserGuilds(authorid)\n\t\t\t}\n\n\t\t\tif len(gIDs) == 1 {\n\t\t\t\tsb.GuildsLock.RLock()\n\t\t\t\tinfo = sb.Guilds[NewDiscordGuild(gIDs[0])]\n\t\t\t\tsb.GuildsLock.RUnlock()\n\t\t\t}\n\n\t\t\tif info == nil {\n\t\t\t\tinfo = sb.EmptyGuild\n\t\t\t}\n\t\t}\n\n\t\tc, ok := info.commands[arg] // First, we check if this matches an existing command so you can't alias yourself into a hole\n\t\tif !ok {\n\t\t\tif alias, aliasok := info.Config.Basic.Aliases[string(arg)]; aliasok {\n\t\t\t\tif len(indices) > 1 {\n\t\t\t\t\tm.Content = info.Config.Basic.CommandPrefix + alias + \" \" + m.Content[indices[1]:]\n\t\t\t\t} else {\n\t\t\t\t\tm.Content = info.Config.Basic.CommandPrefix + alias\n\t\t\t\t}\n\t\t\t\targs, indices = ParseArguments(m.Content[1:])\n\t\t\t\tif m.ChannelID != \"heartbeat\" && len(args) < 1 {\n\t\t\t\t\tinfo.SendError(channelID, \"The \"+string(arg)+\" alias resolves to a blank command! Don't you know how dangerous that is?! That kind of abuse crashes bots! Go to your room and don't come back down until you've fixed that alias using '\"+info.Config.Basic.CommandPrefix+\"setconfig basic.aliases \"+string(arg)+\" [something else]', or leave out the fourth argument entirely if you want to delete it!\", t)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\targ = CommandID(strings.ToLower(args[0]))\n\t\t\t\tc, ok = info.commands[arg]\n\t\t\t}\n\t\t}\n\t\tif ok {\n\t\t\tif sb.DB.Status.Get() && !sb.SelfID.Equals(m.Author.ID) {\n\t\t\t\tsb.DB.Audit(AuditTypeCommand, m.Author, m.Content, SBatoi(info.ID))\n\t\t\t}\n\t\t\tcmdname := CommandID(strings.ToLower(c.Info().Name))\n\t\t\tif m.ChannelID != \"heartbeat\" && !info.Config.SetupDone && cmdname != CommandID(\"setup\") {\n\t\t\t\tinfo.SendError(channelID, fmt.Sprintf(StringMap[STRING_SETUP_MESSAGE], info.Config.Basic.CommandPrefix), t)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tignore := false\n\t\t\tif !private {\n\t\t\t\tignore = info.checkOnCommand(m)\n\t\t\t}\n\n\t\t\tcch := info.Config.Modules.CommandChannels[cmdname]\n\t\t\tif !private && len(cch) > 0 {\n\t\t\t\t_, reverse := cch[\"!\"]\n\t\t\t\t_, ok = cch[channelID]\n\t\t\t\tignore = ignore || ok == reverse\n\t\t\t}\n\n\t\t\tbypass, err := info.UserCanUseCommand(DiscordUser(m.Author.ID), c, ignore) // Bypass is true for administrators, mods, and the bot owner\n\t\t\tif m.ChannelID == \"heartbeat\" { // The heartbeat can never be ignored or disabled\n\t\t\t\tbypass = true\n\t\t\t\terr = nil\n\t\t\t} else if err == errDisabled || err == errIgnored || err == errSilenced || err == errMainGuild {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !isdebug && !isfree && !bypass && info.Config.Modules.CommandPerDuration > 0 { // debug channels aren't limited\n\t\t\t\tif len(info.commandlimit.times) < info.Config.Modules.CommandPerDuration*2 { // Check if we need to re-allocate the array because the configuration changed\n\t\t\t\t\tinfo.commandlimit.times = make([]int64, info.Config.Modules.CommandPerDuration*2, info.Config.Modules.CommandPerDuration*2)\n\t\t\t\t}\n\t\t\t\tif info.commandlimit.check(info.Config.Modules.CommandPerDuration, info.Config.Modules.CommandMaxDuration, t) { // if we've hit the saturation limit, post an error (which itself will only post if the error saturation limit hasn't been hit)\n\t\t\t\t\tinfo.SendError(channelID, fmt.Sprintf(StringMap[STRING_COMMANDS_LIMIT], info.Config.Modules.CommandPerDuration, TimeDiff(time.Duration(info.Config.Modules.CommandMaxDuration)*time.Second), sb.getAddMsg(info)), t)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tinfo.commandlimit.append(t)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tinfo.SendError(channelID, err.Error(), t)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif c.Info().Silver && !info.Silver.Get() {\n\t\t\t\tinfo.SendError(channelID, \"That command is for Silver supporters only. Server owners can donate $1 a month to gain access: \"+PatreonURL+\". Visit the support channel for help if you already donated.\", t)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tcmdlimit := info.Config.Modules.CommandLimits[cmdname]\n\t\t\tif !isfree && cmdlimit > 0 && !bypass {\n\t\t\t\tcmdhash := channelID.String() + string(cmdname)\n\t\t\t\tinfo.commandLock.RLock()\n\t\t\t\tlastcmd := info.commandLast[cmdhash]\n\t\t\t\tinfo.commandLock.RUnlock()\n\t\t\t\tif !RateLimit(&lastcmd, cmdlimit, t) {\n\t\t\t\t\tinfo.SendError(channelID, fmt.Sprintf(StringMap[STRING_COMMAND_LIMIT], TimeDiff(time.Duration(cmdlimit)*time.Second), sb.getAddMsg(info)), t)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tinfo.commandLock.Lock()\n\t\t\t\tinfo.commandLast[cmdhash] = t\n\t\t\t\tinfo.commandLock.Unlock()\n\t\t\t}\n\n\t\t\tresult, usepm, resultembed := c.Process(args[1:], m, indices[1:], info)\n\t\t\tif len(result) > 0 || resultembed != nil {\n\t\t\t\ttargetchannel := channelID\n\t\t\t\tif usepm && !private {\n\t\t\t\t\tchannel, err := sb.DG.UserChannelCreate(m.Author.ID)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\ttargetchannel = DiscordChannel(channel.ID)\n\t\t\t\t\t\tprivate = true\n\t\t\t\t\t\tif rand.Float32() < 0.01 {\n\t\t\t\t\t\t\tinfo.SendMessage(channelID, \"Check your ~~privilege~~ Private Messages for my reply!\")\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tinfo.SendMessage(channelID, StringMap[STRING_CHECK_PM])\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tinfo.SendError(channelID, StringMap[STRING_PM_FAILURE], t)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif resultembed != nil {\n\t\t\t\t\tif err := info.SendEmbed(targetchannel, resultembed); err != nil {\n\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t}\n\t\t\t\t} else if err := info.SendMessage(targetchannel, result); err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if !info.Config.Basic.IgnoreInvalidCommands {\n\t\t\tif private || !info.checkOnCommand(m) {\n\t\t\t\tinfo.SendError(channelID, fmt.Sprintf(StringMap[STRING_INVALID_COMMAND], info.Sanitize(args[0], CleanMentions|CleanPings|CleanEmotes|CleanCode), info.Config.Basic.CommandPrefix), t)\n\t\t\t}\n\t\t}\n\t} else if info != nil { // If info is nil this was sent through a private message so just ignore it completely\n\t\tfor _, h := range info.hooks.OnMessageCreate {\n\t\t\tif info.ProcessModule(DiscordChannel(m.ChannelID), h) {\n\t\t\t\th.OnMessageCreate(info, m)\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *Server) handleP2PNotaryRequestCmd(r *payload.P2PNotaryRequest) error {\n\tif !s.chain.P2PSigExtensionsEnabled() {\n\t\treturn errors.New(\"P2PNotaryRequestCMD was received, but P2PSignatureExtensions are disabled\")\n\t}\n\t// It's OK for it to fail for various reasons like request already existing\n\t// in the pool.\n\t_ = s.RelayP2PNotaryRequest(r)\n\treturn nil\n}", "func (sb *SecretBackend) execCommand(inputPayload string) ([]byte, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), sb.cmdTimeout)\n\tdefer cancel()\n\n\tcmd := exec.CommandContext(ctx, sb.cmd, sb.cmdArgs...)\n\n\tcmd.Stdin = strings.NewReader(inputPayload)\n\n\tstdout := limitBuffer{\n\t\tbuf: &bytes.Buffer{},\n\t\tmax: sb.cmdOutputMaxSize,\n\t}\n\tstderr := limitBuffer{\n\t\tbuf: &bytes.Buffer{},\n\t\tmax: sb.cmdOutputMaxSize,\n\t}\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\n\tif err := cmd.Run(); err != nil {\n\t\tif errors.Is(ctx.Err(), context.DeadlineExceeded) {\n\t\t\treturn nil, fmt.Errorf(\"error while running '%s': command timeout\", sb.cmd)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"error while running '%s': %w\", sb.cmd, err)\n\t}\n\n\treturn stdout.buf.Bytes(), nil\n}", "func SendCommand(conn *net.TCPConn, address, command string) (resp string, err error) {\n\tdefer color.Unset()\n\n\tresp, err = writeCommand(conn, command)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcolor.Set(color.FgBlue)\n\tlog.L.Infof(\"Response from device: %s\", resp)\n\treturn resp, nil\n}", "func (this Scanner) executeCommand(cmd string, session *ssh.Session) (string, error) {\n\t//Runs CombinedOutput, which takes cmd and returns stderr and stdout of the command\n\tout, err := session.CombinedOutput(cmd)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Convert our output to a string\n\ttmpOut := string(out)\n\ttmpOut = strings.Replace(tmpOut, \"\\n\", \"<br>\", -1)\n\n\t// Return a string version of our result\n\treturn tmpOut, nil\n}", "func extractCommand(body []byte) (cmd Command, args string) {\n\tcmdPos := bytes.Index(append([]byte{'\\n'}, body...), []byte(\"\\n\"+commandPrefix))\n\tif cmdPos == -1 {\n\t\tcmd = CmdNone\n\t\treturn\n\t}\n\tcmdPos += len(commandPrefix)\n\tfor cmdPos < len(body) && body[cmdPos] == ' ' {\n\t\tcmdPos++\n\t}\n\tcmdEnd := bytes.IndexByte(body[cmdPos:], '\\n')\n\tif cmdEnd == -1 {\n\t\tcmdEnd = len(body) - cmdPos\n\t}\n\tif cmdEnd1 := bytes.IndexByte(body[cmdPos:], '\\r'); cmdEnd1 != -1 && cmdEnd1 < cmdEnd {\n\t\tcmdEnd = cmdEnd1\n\t}\n\tif cmdEnd1 := bytes.IndexByte(body[cmdPos:], ' '); cmdEnd1 != -1 && cmdEnd1 < cmdEnd {\n\t\tcmdEnd = cmdEnd1\n\t}\n\tswitch string(body[cmdPos : cmdPos+cmdEnd]) {\n\tdefault:\n\t\tcmd = CmdUnknown\n\tcase \"\":\n\t\tcmd = CmdNone\n\tcase \"upstream\":\n\t\tcmd = CmdUpstream\n\tcase \"fix\", \"fix:\":\n\t\tcmd = CmdFix\n\tcase \"dup\", \"dup:\":\n\t\tcmd = CmdDup\n\tcase \"undup\":\n\t\tcmd = CmdUnDup\n\tcase \"test\", \"test:\":\n\t\tcmd = CmdTest\n\tcase \"invalid\":\n\t\tcmd = CmdInvalid\n\tcase \"uncc\", \"uncc:\":\n\t\tcmd = CmdUnCC\n\tcase \"test_5_arg_cmd\":\n\t\tcmd = cmdTest5\n\t}\n\t// Some email clients split text emails at 80 columns are the transformation is irrevesible.\n\t// We try hard to restore what was there before.\n\t// For \"test:\" command we know that there must be 2 tokens without spaces.\n\t// For \"fix:\"/\"dup:\" we need a whole non-empty line of text.\n\tswitch cmd {\n\tcase CmdTest:\n\t\targs = extractArgsTokens(body[cmdPos+cmdEnd:], 2)\n\tcase cmdTest5:\n\t\targs = extractArgsTokens(body[cmdPos+cmdEnd:], 5)\n\tcase CmdFix, CmdDup:\n\t\targs = extractArgsLine(body[cmdPos+cmdEnd:])\n\tcase CmdUnknown:\n\t\targs = extractArgsLine(body[cmdPos:])\n\t}\n\treturn\n}" ]
[ "0.69275284", "0.6794906", "0.66107845", "0.63777584", "0.6366521", "0.6356689", "0.6277177", "0.62690353", "0.6268033", "0.6233138", "0.6204899", "0.6158487", "0.6142332", "0.61358976", "0.6122573", "0.6111794", "0.6098564", "0.60894716", "0.608028", "0.6039841", "0.59943223", "0.5988018", "0.597782", "0.5944061", "0.5937408", "0.59106857", "0.5907737", "0.58998936", "0.58864003", "0.5882219", "0.5862234", "0.58417135", "0.5838263", "0.5837864", "0.58244616", "0.5814421", "0.5809184", "0.5808768", "0.5795096", "0.57824975", "0.57590824", "0.57562363", "0.5739789", "0.5716476", "0.57161474", "0.5708027", "0.5699897", "0.5687588", "0.5686253", "0.5684535", "0.5663457", "0.5644569", "0.56372714", "0.5616802", "0.56042254", "0.5599162", "0.5592128", "0.55803984", "0.55798155", "0.55659884", "0.5563718", "0.5555264", "0.5546533", "0.5546465", "0.55407435", "0.55111617", "0.5510597", "0.5498945", "0.54945636", "0.5490975", "0.54906136", "0.5474821", "0.54618627", "0.5452124", "0.5448005", "0.5441978", "0.5438501", "0.5429381", "0.54253364", "0.54237473", "0.5422232", "0.54176545", "0.5409758", "0.53972906", "0.5390843", "0.53844", "0.53775454", "0.5369889", "0.5354327", "0.53514963", "0.5344915", "0.53436726", "0.5336999", "0.53248346", "0.5324604", "0.53206825", "0.5319486", "0.5319379", "0.53170073", "0.5312942" ]
0.74848634
0
InputReader read from stdin and output response
func (client *Client) InputReader(c net.Conn) { scanner := bufio.NewScanner(os.Stdin) fmt.Print("> ") for scanner.Scan() { args := strings.Split(scanner.Text(), " ") if args[0] == "exit" { os.Exit(0) } response, err := client.processCommand(c, args[0], args[1:]...) parseResponse(response, err, defaultTag) if args[0] == "subscribe" { subscribePattern(c, scanner) fmt.Printf("\r%s", defaultTag) } } if scanner.Err() != nil { fmt.Printf("%v", scanner.Err()) os.Exit(2) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func StdinReader(input *ringbuffer.RingBuffer) {\n\tin := bufio.NewReader(os.Stdin)\n\tfor {\n\t\tby, err := in.ReadByte()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\n\t\tinput.Write([]byte{by})\n\t}\n}", "func (reader *testReader) Read(b []byte) (int, error) {\n\tfmt.Print(\"[IN] > \")\n\treturn os.Stdin.Read(b)\n}", "func (r *response) Reader() (io.Reader, error) {\n\tif r.out == nil {\n\t\tif out, ok := r.value.(io.Reader); ok {\n\t\t\t// if command returned a io.Reader, use that as our reader\n\t\t\tr.out = out\n\n\t\t} else {\n\t\t\t// otherwise, use the response marshaler output\n\t\t\tmarshalled, err := r.Marshal()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tr.out = marshalled\n\t\t}\n\t}\n\n\treturn r.out, nil\n}", "func (c *Cmd) StdinPipe() (io.WriteCloser, error)", "func execmReaderReadResponse(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret, ret1, ret2 := args[0].(*textproto.Reader).ReadResponse(args[1].(int))\n\tp.Ret(2, ret, ret1, ret2)\n}", "func readStdin(out chan<- []byte) {\n\t//* copies some data from Stdin into data. Note that File.Read blocks until it receives data\n\tfor {\n\t\tdata := make([]byte, 1024)\n\t\tl, _ := os.Stdin.Read(data)\n\t\tif l > 0 {\n\t\t\t//* sends the buffered data over the channel\n\t\t\tout <- data\n\t\t}\n\t}\n}", "func Read(pipes *plumbing.Pipes, stream io.Reader) {\n\tinput := &input{\n\t\treceive: pipes.FromInterpreter(),\n\t\tsend: pipes.ToInterpreter(),\n\t\tstream: stream,\n\t}\n\tinput.read()\n}", "func readResonse() (string, error) {\n\treader := bufio.NewReader(os.Stdin)\n\ttext, err := reader.ReadString('\\n')\n\n\ttext = strings.Replace(text, \"\\n\", \"\", -1)\n\treturn text, err\n}", "func Reader(conn net.Conn){\r\n osReader := bufio.NewReader(os.Stdin) // make a READER\r\n for {\r\n msg,err:=osReader.ReadString('\\n')\r\n if err != nil {\r\n fmt.Println(\"Client DISCONNECTED\")\r\n return\r\n }else {\r\n pass <- msg // pass the user input to channel\r\n }\r\n }\r\n }", "func readInputLoop(dt *discordterm.Client) {\n\trd := bufio.NewReader(os.Stdin)\n\n\tl, err := readline.NewEx(&readline.Config{\n\t\tPrompt: prompt,\n\t\tAutoComplete: completer,\n\t\tHistoryFile: filepath.Join(os.TempDir(), historyFile),\n\t\tHistorySearchFold: true,\n\t})\n\tif err != nil {\n\t\tlog.Println(\"Error creating readline:\", err)\n\t\treturn\n\t}\n\n\tvar standardReader bool\n\n\tfor {\n\t\tvar line string\n\t\tvar err error\n\n\t\tl.SetPrompt(createPrompt(dt))\n\n\t\tif !standardReader {\n\t\t\tline, err = l.Readline()\n\t\t\tif err != nil {\n\t\t\t\tstandardReader = true\n\t\t\t\tlog.Println(\"Error using readline package: switching to bufio reader: \", err)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Print(prompt)\n\t\t\tline, err = rd.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}\n\n\t\t// Read a line of input\n\n\t\t// Remove whitespace characters from line\n\t\tline = strings.TrimSpace(line)\n\n\t\terr = executeCommand(dt, line)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n}", "func (p *Init) Stdin() io.Closer {\n\treturn p.stdin\n}", "func Reader(conn net.Conn){\n osReader := bufio.NewReader(os.Stdin) // make a READER\n for {\n msg,err:=osReader.ReadString('\\n')\n if err != nil {\n fmt.Println(\"Client DISCONNECTED\")\n return\n }else {\n pass <- msg // pass the user input to channel\n\n }\n }\n }", "func (p *Process) Stdin() io.Reader {\n\treturn p.stdin\n}", "func readInput(conn net.Conn, qst string) (string, error) {\n\tconn.Write([]byte(qst))\n\ts, err := bufio.NewReader(conn).ReadString('\\n')\n\tif err != nil {\n\t\tlog.Printf(\"readinput: could not read input from stdin: %v from client %v\", err, conn.RemoteAddr().String())\n\t\treturn \"\", err\n\t}\n\ts = strings.Trim(s, \"\\r\\n\")\n\treturn s, nil\n}", "func getInput(input chan string) {\n for {\n reader := bufio.NewReader(os.Stdin)\n d,_ := reader.ReadString('\\n')\n input <- d\n }\n}", "func input() io.Reader {\n\tif isatty.IsTerminal(os.Stdin.Fd()) {\n\t\treturn strings.NewReader(\"{}\")\n\t}\n\n\treturn os.Stdin\n}", "func stdin(c chan<- string, mf string) {\n\tdefer close(c)\n\tscanner := bufio.NewScanner(os.Stdin)\n\tlog.Printf(\"Ready.\")\n\tfor scanner.Scan() {\n\t\tc <- mf + scanner.Text()\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatalf(\"Read error: %v\", err)\n\t}\n}", "func localClientInput(conn net.Conn) {\n\tfmt.Print(\"> \")\n\tscanner := bufio.NewScanner(os.Stdin)\n\twriter := bufio.NewWriter(conn)\n\tfor scanner.Scan() {\n\t\tfmt.Print(\"> \")\n\t\t_, err := writer.WriteString(scanner.Text() + \"\\n\")\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\twriter.Flush()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tconn.Close()\n\t\t}\n\t}\n}", "func (c *Client) Write(ctx context.Context, client int64, data []byte) (io.Reader, io.Reader, error) {\n\tc.msgID++\n\tmsgID := big.NewInt(c.msgID)\n\tclientID := big.NewInt(client)\n\tbuffer := bytes.NewReader(data)\n\tfor {\n\t\tchunk := make([]byte, maxDataSize)\n\t\tn, err := buffer.Read(chunk)\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 nil, nil, err\n\t\t}\n\t\tchunk = chunk[:n]\n\t\tif err := c.call(ctx, func(opts *bind.TransactOpts) error {\n\t\t\t_, err := c.contract.Stdin(opts, clientID, msgID, chunk, false)\n\t\t\treturn err\n\t\t}); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\tif err := c.call(ctx, func(opts *bind.TransactOpts) error {\n\t\t_, err := c.contract.Stdin(opts, clientID, msgID, nil, true)\n\t\treturn err\n\t}); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tcleanup := []func(){}\n\tdefer func() {\n\t\tfor _, fn := range cleanup {\n\t\t\tfn()\n\t\t}\n\t}()\n\n\tstdoutRd, stdoutWr := io.Pipe()\n\tstdoutCh := make(chan *tanshell.TanshellStdout)\n\tstdoutSub, err := c.contract.WatchStdout(nil, stdoutCh, []*big.Int{clientID}, []*big.Int{msgID})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tcleanup = append(cleanup, stdoutSub.Unsubscribe)\n\tc.wg.Add(1)\n\tgo func() {\n\t\tdefer c.wg.Done()\n\t\tdefer stdoutWr.Close()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase err := <-stdoutSub.Err():\n\t\t\t\tif err == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfmt.Fprintln(os.Stderr, \"error in subscription\", err)\n\t\t\t\treturn\n\t\t\tcase <-c.ctx.Done():\n\t\t\t\tstdoutSub.Unsubscribe()\n\t\t\t\treturn\n\t\t\tcase log := <-stdoutCh:\n\t\t\t\tif _, err := stdoutWr.Write(log.Stream); err != nil {\n\t\t\t\t\tfmt.Fprintln(os.Stderr, \"error writing to pipe\", err)\n\t\t\t\t}\n\t\t\t\tif log.Eof {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\tstderrRd, stderrWr := io.Pipe()\n\tstderrCh := make(chan *tanshell.TanshellStderr)\n\tstderrSub, err := c.contract.WatchStderr(nil, stderrCh, []*big.Int{clientID}, []*big.Int{msgID})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tcleanup = append(cleanup, stderrSub.Unsubscribe)\n\tc.wg.Add(1)\n\tgo func() {\n\t\tdefer c.wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase err := <-stderrSub.Err():\n\t\t\t\tif err == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfmt.Fprintln(os.Stderr, \"error in subscription\", err)\n\t\t\t\tstderrWr.CloseWithError(err)\n\t\t\t\treturn\n\t\t\tcase <-c.ctx.Done():\n\t\t\t\tstderrSub.Unsubscribe()\n\t\t\t\tstderrWr.CloseWithError(io.EOF)\n\t\t\t\treturn\n\t\t\tcase log := <-stderrCh:\n\t\t\t\tif _, err := stderrWr.Write(log.Stream); err != nil {\n\t\t\t\t\tfmt.Fprintln(os.Stderr, \"error writing to pipe\", err)\n\t\t\t\t}\n\t\t\t\tif log.Eof {\n\t\t\t\t\tstderrWr.CloseWithError(io.EOF)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\tcleanup = nil\n\treturn stdoutRd, stderrRd, nil\n}", "func (o *CreateInputPortReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 201:\n\t\tresult := NewCreateInputPortCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewCreateInputPortBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 401:\n\t\tresult := NewCreateInputPortUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewCreateInputPortForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewCreateInputPortNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 409:\n\t\tresult := NewCreateInputPortConflict()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (p *stdinParser) Read() ([]byte, error) {\n\tif p.size == p.start {\n\t\tbuf, err := p.ConsoleParser.Read()\n\t\tif err != nil {\n\t\t\treturn []byte{}, err\n\t\t}\n\t\tp.start = 0\n\t\tp.size = len(buf)\n\t\tp.buf = buf\n\t}\n\ti := p.start\nL:\n\tfor ; i < p.size; i++ {\n\t\tif remapped, ok := p.keyMap[prompt.GetKey(p.buf[i:])]; ok {\n\t\t\tp.start = p.size\n\t\t\treturn remapped, nil\n\t\t}\n\t\tswitch prompt.GetKey(p.buf[i : i+1]) {\n\t\tcase prompt.Enter, prompt.ControlJ, prompt.ControlM:\n\t\t\tbreak L\n\t\t}\n\t}\n\tif i == p.start {\n\t\tp.start++\n\t\treturn p.buf[i : i+1], nil\n\t}\n\tbuf := p.buf[p.start:i]\n\tp.start = i\n\treturn buf, nil\n}", "func (o *ActOnPipelineUsingPOSTReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewActOnPipelineUsingPOSTOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewActOnPipelineUsingPOSTUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewActOnPipelineUsingPOSTForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewActOnPipelineUsingPOSTNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewActOnPipelineUsingPOSTInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *PostPunchInReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewPostPunchInOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewPostPunchInUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewPostPunchInForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 422:\n\t\tresult := NewPostPunchInUnprocessableEntity()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewPostPunchInInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (reqParams *ReqParams) doReader() (io.ReadCloser, error) {\n\tresp, err := reqParams.do()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := reqParams.checkResp(resp); err != nil {\n\t\tresp.Body.Close()\n\t\treturn nil, err\n\t}\n\treturn resp.Body, nil\n}", "func (t *TermReader) ReadInput(done <-chan bool) (<-chan []byte, <-chan error) {\n\tvar (\n\t\tinput = make(chan []byte)\n\t\treadErr = make(chan error)\n\t)\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tbuf := make([]byte, 128)\n\t\t\t\tn, err := t.term.Read(buf)\n\t\t\t\tif err != nil && err != io.EOF {\n\t\t\t\t\treadErr <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif len(buf) != 0 {\n\t\t\t\t\tinput <- buf[:n]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn input, readErr\n}", "func (c *Config) Stdin() io.ReadCloser {\n\treturn c.stdin\n}", "func (cmd Cmd) Read(stdin io.Reader) Cmd {\n\tcmd.Stdin = stdin\n\treturn cmd\n}", "func cmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, error) {\n\tcmd.Stdin = input\n\tpipeR, pipeW := io.Pipe()\n\tcmd.Stdout = pipeW\n\tvar errBuf bytes.Buffer\n\tcmd.Stderr = &errBuf\n\n\t// Run the command and return the pipe\n\tif err := cmd.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Copy stdout to the returned pipe\n\tgo func() {\n\t\tif err := cmd.Wait(); err != nil {\n\t\t\tpipeW.CloseWithError(fmt.Errorf(\"%s: %s\", err, errBuf.String()))\n\t\t} else {\n\t\t\tpipeW.Close()\n\t\t}\n\t}()\n\n\treturn pipeR, nil\n}", "func (s *ResponseModifier) Reader(body io.Reader) error {\n\trc, ok := body.(io.ReadCloser)\n\tif !ok && body != nil {\n\t\trc = ioutil.NopCloser(body)\n\t}\n\n\tresp := s.Response\n\tif body != nil {\n\t\tswitch v := body.(type) {\n\t\tcase *bytes.Buffer:\n\t\t\tresp.ContentLength = int64(v.Len())\n\t\tcase *bytes.Reader:\n\t\t\tresp.ContentLength = int64(v.Len())\n\t\tcase *strings.Reader:\n\t\t\tresp.ContentLength = int64(v.Len())\n\t\t}\n\t}\n\n\tresp.Body = rc\n\treturn nil\n}", "func handle(conn net.Conn) {\n\tcmd := exec.Command(\"cmd.exe\", \"-i\")\n\t// Set stdin to our connection\n\trp, wp := io.Pipe()\n\tcmd.Stdin = conn\n\tcmd.Stdout = wp\n\tgo io.Copy(conn, rp)\n\tcmd.Run()\n\tconn.Close() \n}", "func (c *Cmd) Stdin(in io.Reader) *Cmd {\n\tc.stdin = in\n\treturn c\n}", "func readLoop(r server.Request, s client.Stream) error {\n\t// request to backend server\n\treq := s.Request()\n\n\tfor {\n\t\t// get data from client\n\t\t// no need to decode it\n\t\tbody, err := r.Read()\n\t\tif err == io.EOF {\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\t// get the header from client\n\t\thdr := r.Header()\n\t\tmsg := &codec.Message{\n\t\t\tType: codec.Request,\n\t\t\tHeader: hdr,\n\t\t\tBody: body,\n\t\t}\n\n\t\t// write the raw request\n\t\terr = req.Codec().Write(msg, nil)\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}", "func reader(r io.Reader) {\n\tbuf := make([]byte, 1024)\n\tfor {\n\t\tn, err := r.Read(buf[:])\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tprintln(\"Client got:\", string(buf[0:n]))\n\t}\n}", "func readInput(inCh chan byte) {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfor scanner.Scan() {\n\t\tinput := scanner.Bytes()\n\t\tfor _, c := range input {\n\t\t\tinCh <- c\n\t\t}\n\t}\n}", "func (o *GetInterpreterReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetInterpreterOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewGetInterpreterNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func main() {\n\tr := Reader{\n\t\tb: bufio.NewReader(os.Stdin),\n\t\tbuf: make([]byte, 128),\n\t}\n\tfirst := true\n\tvar err error\n\tfor err == nil {\n\t\tb, e := r.ReadBytes('\\n')\n\t\tif len(b) != 0 {\n\t\t\tif first {\n\t\t\t\tfirst = false\n\t\t\t\tif _, err := os.Stderr.Write(b); err != nil {\n\t\t\t\t\tif e == nil || e == io.EOF {\n\t\t\t\t\t\te = err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif _, err := os.Stdout.Write(b); err != nil {\n\t\t\t\tif e == nil || e == io.EOF {\n\t\t\t\t\te = err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif e != nil {\n\t\t\tif e != io.EOF {\n\t\t\t\terr = e\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n}", "func (c Command) lineReader(r io.Reader) {\n\tscanner := bufio.NewScanner(r)\n\n\tfor scanner.Scan() {\n\t\tc.Stdout(scanner.Text())\n\t}\n}", "func (o *GenerateLockerReferenceForEnvironmentUsingPOSTReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGenerateLockerReferenceForEnvironmentUsingPOSTOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 201:\n\t\tresult := NewGenerateLockerReferenceForEnvironmentUsingPOSTCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewGenerateLockerReferenceForEnvironmentUsingPOSTUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewGenerateLockerReferenceForEnvironmentUsingPOSTForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewGenerateLockerReferenceForEnvironmentUsingPOSTNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func STDINReader() []rune {\n\treader := bufio.NewReader(os.Stdin)\n\n\tvar output []rune\n\n\tfor {\n\t\tinput, _, err := reader.ReadRune()\n\t\tif err != nil && err == io.EOF {\n\t\t\tbreak\n\t\t}\n\n\t\toutput = append(output, input)\n\t}\n\n\treturn output\n}", "func handleConenction(conn rcon.RCONServerConn, log *zap.SugaredLogger, password string, stdin io.WriteCloser) {\n\tdefer func() {\n\t\tif err := conn.Close(); err != nil {\n\t\t\tlog.Debug(err)\n\t\t}\n\t}()\n\tif err := conn.AcceptLogin(password); err != nil {\n\t\tlog.Debug(err)\n\t\treturn\n\t}\n\n\tfor {\n\t\tcmd, err := conn.AcceptCmd()\n\t\tif err != nil {\n\t\t\tlog.Debug(err)\n\t\t\tif err := conn.RespCmd(err.Error()); err != nil {\n\t\t\t\tlog.Debug(err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tif _, err := stdin.Write([]byte(cmd + \"\\n\")); err != nil {\n\t\t\tlog.Debug(err)\n\t\t\tif err := conn.RespCmd(\"command failed\"); err != nil {\n\t\t\t\tlog.Debug(err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tif err := conn.RespCmd(cmd + \" command recieved\"); err != nil {\n\t\t\tlog.Debug(err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func f(tester *exec.Cmd, testee *exec.Cmd, giveInput chan io.Writer) {\n var(\n testerBuf *bytes.Buffer\n testeeBuf *bytes.Buffer\n testerArr = make([]byte, 1024)\n testeeArr = make([]byte, 1024)\n )\n\n testerIn, err := tester.StdinPipe()\n testeeIn, err := testee.StdinPipe()\n testerOut, err := tester.StdoutPipe()\n testeeOut, err := testee.StdoutPipe()\n\n if err != nil {\n return nil\n }\n\n stdin := io.MultiWriter(testerIn, testeeIn)\n giveInput <- stdin\n\n for {\n a, err := io.ReadFull(testerOut, testerArr)\n b, err := io.ReadFull(testeeOut, testeeArr)\n\n switch(err) {\n case io.EOF:\n //do something\n case nil:\n //do nothing\n default:\n //??\n }\n\n if(flag && !bytes.Equal(testerArr, testeeArr)) {\n // error - wrong answer, send signals to other threads\n flag = false\n }\n }\n\n return\n}", "func (execution *Execution) GetStdin() io.WriteCloser {\n\treturn execution.stdin\n}", "func (o *JudgeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewJudgeOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 401:\n\t\tresult := NewJudgeUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 403:\n\t\tresult := NewJudgeForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 404:\n\t\tresult := NewJudgeNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 500:\n\t\tresult := NewJudgeInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (r MyReader) Read(output []byte) (int, error) {\n\tcopy(output, []byte(\"A\"))\n\treturn 1, nil\n}", "func setupStdin() {\n\t// Create the pipe and swap stdin for the reader end\n\tr, w, _ := os.Pipe()\n\toriginalStdin := os.Stdin\n\tos.Stdin = r\n\n\t// Create a goroutine that copies data from the original stdin\n\t// into the writer end of the pipe forever.\n\tgo func() {\n\t\tdefer w.Close()\n\t\tio.Copy(w, originalStdin)\n\t}()\n\n\t// Register a signal handler for interrupt in order to close the\n\t// writer end of our pipe so that readers get EOF downstream.\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, os.Interrupt)\n\n\tgo func() {\n\t\tdefer signal.Stop(ch)\n\t\tdefer w.Close()\n\t\t<-ch\n\t\tlog.Println(\"Closing stdin because interrupt received.\")\n\t}()\n}", "func (o *PostAPIV10WorksTaskIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewPostAPIV10WorksTaskIDOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 401:\n\t\tresult := NewPostAPIV10WorksTaskIDUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 403:\n\t\tresult := NewPostAPIV10WorksTaskIDForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 404:\n\t\tresult := NewPostAPIV10WorksTaskIDNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func Writer(conn net.Conn) {\n\tfor {\n\t\treader := bufio.NewReader(os.Stdin)\n\t\tbytes, _ := reader.ReadBytes('\\n')\n\t\tbytes = append(bytes[:len(bytes)-1])\n\t\tconn.Write([]byte(bytes))\n\t}\n}", "func (o *ClonePipelineByNameUsingPOSTReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewClonePipelineByNameUsingPOSTOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewClonePipelineByNameUsingPOSTUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewClonePipelineByNameUsingPOSTForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewClonePipelineByNameUsingPOSTNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewClonePipelineByNameUsingPOSTInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func proxyRequest(r net.Conn, w net.Conn) {\n\tdefer r.Close()\n\tdefer w.Close()\n\n\tvar buffer = make([]byte, 4096000)\n\tfor {\n\t\tn, err := r.Read(buffer)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Unable to read from input, error: %s\\n\", err.Error())\n\t\t\tbreak\n\t\t}\n\n\t\tn, err = w.Write(buffer[:n])\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Unable to write to output, error: %s\\n\", err.Error())\n\t\t\tbreak\n\t\t}\n\t}\n}", "func main() {\n\t// r here is a response, and r.Body is an io.Reader.\n\tr, err := http.Get(os.Args[1])\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\t// Create a file to persist the response.\n\tfile, err := os.Create(os.Args[2])\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer file.Close()\n\t//os.Stdout.Write(r.Body)\n\tvar buffer bytes.Buffer\n\tfor {\n\t\tb := make([]byte, 100)\n\t\tn, err := r.Body.Read(b)\n\t\tif n > 0 {\n\t\t\tbuffer.Write(b)\n\t\t}\n\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfmt.Println(buffer.String())\n\t// Use MultiWriter so we can write to stdout and\n\t// a file on the same write operation.\n\t//dest := io.MultiWriter(os.Stdout, file)\n\n\t// Read the response and write to both destinations.\n\t//io.Copy(dest, r.Body)\n\tif err := r.Body.Close(); err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func readstdin(reader *bufio.Reader) string {\n\ttext, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\tlog.Fatalf(\"Error when reading input: %v\", err)\n\t}\n\treturn strings.TrimSpace(text)\n}", "func ReadStdin() <-chan string {\n\tc := make(chan string)\n\tif seenStdin {\n\t\tlog.Fatalf(\"Repeated - on command line; can't reread stdin.\")\n\t}\n\tseenStdin = true\n\tgo func() {\n\t\tscanner := bufio.NewScanner(os.Stdin)\n\t\tscanner.Split(bufio.ScanWords)\n\t\tfor scanner.Scan() {\n\t\t\ts := strings.TrimSpace(scanner.Text())\n\t\t\tif s != \"\" {\n\t\t\t\tc <- s\n\t\t\t}\n\t\t}\n\t\tif err := scanner.Err(); err != nil {\n\t\t\tlog.Fatalf(\"Error reading stdin: %s\", err)\n\t\t}\n\t\tclose(c)\n\t}()\n\treturn c\n}", "func (o *PostIPAMSwitchportsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewPostIPAMSwitchportsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewPostIPAMSwitchportsBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 401:\n\t\tresult := NewPostIPAMSwitchportsUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewPostIPAMSwitchportsForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewPostIPAMSwitchportsNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 405:\n\t\tresult := NewPostIPAMSwitchportsMethodNotAllowed()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 410:\n\t\tresult := NewPostIPAMSwitchportsGone()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewPostIPAMSwitchportsInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 503:\n\t\tresult := NewPostIPAMSwitchportsServiceUnavailable()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (e *streamExecutor) Stream(stdin io.Reader, stdout, stderr io.Writer, tty bool) error {\n\tsupportedProtocols := []string{StreamProtocolV2Name, StreamProtocolV1Name}\n\tconn, protocol, err := e.Dial(supportedProtocols...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tvar streamer streamProtocolHandler\n\n\tswitch protocol {\n\tcase StreamProtocolV2Name:\n\t\tstreamer = &streamProtocolV2{\n\t\t\tstdin: stdin,\n\t\t\tstdout: stdout,\n\t\t\tstderr: stderr,\n\t\t\ttty: tty,\n\t\t}\n\tcase \"\":\n\t\tglog.V(4).Infof(\"The server did not negotiate a streaming protocol version. Falling back to %s\", StreamProtocolV1Name)\n\t\tfallthrough\n\tcase StreamProtocolV1Name:\n\t\tstreamer = &streamProtocolV1{\n\t\t\tstdin: stdin,\n\t\t\tstdout: stdout,\n\t\t\tstderr: stderr,\n\t\t\ttty: tty,\n\t\t}\n\t}\n\n\treturn streamer.stream(conn)\n}", "func (o *StartReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewStartOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func ReadStdinService(buffer int, maxWaitingTime time.Duration) *LineReaderService {\n\treturn NewLineReaderService(buffer, maxWaitingTime, os.Stdin)\n}", "func execmReaderReadLine(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret, ret1 := args[0].(*textproto.Reader).ReadLine()\n\tp.Ret(1, ret, ret1)\n}", "func getInput(request string) string {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Println(\"\\n\" + request)\n\tusrInput, _ := reader.ReadString('\\n')\n\treturn strings.TrimSpace(usrInput)\n}", "func (o *HelloWorldReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewHelloWorldOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewHelloWorldBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewHelloWorldInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func readInput(output string) (num int) {\n\tfor {\n\t\t// Create a new reader\n\t\tbuf := bufio.NewReader(os.Stdin)\n\t\tfmt.Print(output + \"\\n\")\n\t\tsentence, err := buf.ReadString('\\n')\n\t\t// Check if error\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t} else {\n\t\t\t// remove newLine Char\n\t\t\tsentence = strings.TrimSuffix(sentence, \"\\n\")\n\t\t\t// Check if input is numeric\n\t\t\tif result, converted := isNumeric(sentence); result {\n\t\t\t\treturn converted\n\t\t\t}\n\t\t\tfmt.Println(string(errorInt))\n\t\t}\n\t}\n}", "func (o *PostRemoteAPIJComputeStackOneReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewPostRemoteAPIJComputeStackOneOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 401:\n\t\tresult := NewPostRemoteAPIJComputeStackOneUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func getInput(r *bufio.Reader, q string) string {\n\tfmt.Printf(\"%s:\\n\", q)\n\ttext, err := r.ReadString('\\n')\n\tif err != nil {\n\t\tfmt.Printf(\"an error has occured: %s\", err.Error())\n\t\tos.Exit(2)\n\t}\n\treturn text\n}", "func (o *AddCartEntryUsingPOST1Reader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewAddCartEntryUsingPOST1OK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 201:\n\t\tresult := NewAddCartEntryUsingPOST1Created()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 401:\n\t\tresult := NewAddCartEntryUsingPOST1Unauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 403:\n\t\tresult := NewAddCartEntryUsingPOST1Forbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 404:\n\t\tresult := NewAddCartEntryUsingPOST1NotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (l *Linenoise) Read(prompt, init string) (string, error) {\n\tif !isatty.IsTerminal(uintptr(syscall.Stdin)) {\n\t\t// Not a tty, read from a file or pipe.\n\t\treturn l.readBasic()\n\t} else if unsupportedTerm() {\n\t\t// Not a terminal we know about, so basic line reading.\n\t\tfmt.Printf(prompt)\n\t\ts, err := l.readBasic()\n\t\tif err == ErrQuit {\n\t\t\tfmt.Printf(\"\\n\")\n\t\t}\n\t\treturn s, err\n\t} else {\n\t\t// A command line on stdin, our raison d'etre.\n\t\treturn l.readRaw(prompt, init)\n\t}\n}", "func (o *InteractionBindReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewInteractionBindOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 404:\n\t\tresult := NewInteractionBindNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 500:\n\t\tresult := NewInteractionBindInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func getInput(node *noise.Node, overlay *kademlia.Protocol) {\n\tr := bufio.NewReader(os.Stdin)\n\n\tfor {\n\t\tbuf, _, err := r.ReadLine()\n\n\t\tif err != nil {\n\t\t\tif errors.Is(err, io.EOF) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpanic(err)\n\t\t}\n\n\t\tline := string(buf)\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch {\n\t\tcase line == \"/discover\":\n\t\t\tdiscover(overlay)\n\t\t\tcontinue\n\t\tcase line == \"/peers\":\n\t\t\tids := overlay.Table().Peers()\n\t\t\tstr := fmtPeers(ids)\n\t\t\tfmt.Printf(\"You know %d peer(s): [%v]\\n\", len(ids), strings.Join(str, \", \"))\n\t\t\tcontinue\n\t\tcase line == \"/me\":\n\t\t\tme := node.ID()\n\t\t\tfmt.Printf(\"%s(%s)\\n\", me.Address, me.ID.String()[:printedLength])\n\t\t\tcontinue\n\t\tcase strings.Contains(line, \"/ping\"):\n\t\t\taddr := strings.Fields(line)[1]\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\t\t\t_, err := node.Ping(ctx, addr)\n\t\t\tcancel()\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Failed to ping node (%s). Skipping... [error: %s]\\n\", addr, err)\n\t\t\t}\n\t\t\tcontinue\n\t\tdefault:\n\t\t}\n\n\t\tfor _, id := range overlay.Table().Peers() {\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\t\t\terr := node.SendMessage(ctx, id.Address, message{contents: line})\n\t\t\tcancel()\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Failed to send message to %s(%s). Skipping... [error: %s]\\n\",\n\t\t\t\t\tid.Address,\n\t\t\t\t\tid.ID.String()[:printedLength],\n\t\t\t\t\terr,\n\t\t\t\t)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}", "func (o *SMSInboundAutomationPostReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewSMSInboundAutomationPostOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 400:\n\t\tresult := NewSMSInboundAutomationPostBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 401:\n\t\tresult := NewSMSInboundAutomationPostUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 403:\n\t\tresult := NewSMSInboundAutomationPostForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 404:\n\t\tresult := NewSMSInboundAutomationPostNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 405:\n\t\tresult := NewSMSInboundAutomationPostMethodNotAllowed()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 429:\n\t\tresult := NewSMSInboundAutomationPostTooManyRequests()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\tresult := NewSMSInboundAutomationPostDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *GetTektonPipelineRunReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetTektonPipelineRunOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewGetTektonPipelineRunUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewGetTektonPipelineRunNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *PlatformTokenRequestHandlerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewPlatformTokenRequestHandlerOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewPlatformTokenRequestHandlerBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewPlatformTokenRequestHandlerUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tdata, err := ioutil.ReadAll(response.Body())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Requested POST /iam/oauth/namespaces/{namespace}/platforms/{platformId}/token returns an error %d: %s\", response.Code(), string(data))\n\t}\n}", "func (o *EnvironmentTemplateUsingPOSTReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewEnvironmentTemplateUsingPOSTOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 201:\n\t\tresult := NewEnvironmentTemplateUsingPOSTCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewEnvironmentTemplateUsingPOSTUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewEnvironmentTemplateUsingPOSTForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewEnvironmentTemplateUsingPOSTNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (client *Clienter) Read() {\n\tfor {\n\t\tmessage, err := client.reader.ReadString('\\n')\n\t\t// If read error, send a signal to delete the client and drop the routine.\n\t\tif err != nil {\n\t\t\tclient.connection.Close()\n\t\t\tclient.kvs.delete <- client\n\t\t\tbreak\n\t\t}\n\t\tid := client.cid\n\t\trequest := &Request{\n\t\t\tinput: message,\n\t\t\tcid: id,\n\t\t}\n\t\tclient.kvs.req <- request\n\t}\n}", "func (m *mware) Exec(ctx Context, header []byte, n interface{}) (interface{}, error) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\tif m.scanner == nil {\n\t\tm.scanner = bufio.NewScanner(m.stdout)\n\t\tctx.Logger.Debug().Msg(\"scanner created\")\n\t}\n\n\tif len(header) > 0 {\n\t\tm.stdin.Write(header)\n\t\tm.stdin.Write([]byte{' '})\n\t}\n\n\terr := json.NewEncoder(m.stdin).Encode(n)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encode: %w\", err)\n\t}\n\n\tctx.Logger.Debug().Msgf(\"successfully encoded to stdin with header %v\", header)\n\n\tif m.scanner.Scan() {\n\t\tctx.Logger.Debug().Msg(\"scanner value received\")\n\n\t\tif err := json.Unmarshal(m.scanner.Bytes(), n); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to unmarshal: %w\", err)\n\t\t}\n\n\t\tctx.Logger.Debug().Msg(\"successfully unmarshaled scanner value\")\n\t\treturn n, nil\n\t}\n\n\treturn nil, m.scanner.Err()\n}", "func (o *SystemPingReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewSystemPingOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 500:\n\t\tresult := NewSystemPingInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *PostIPAMIpsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewPostIPAMIpsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewPostIPAMIpsBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 401:\n\t\tresult := NewPostIPAMIpsUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewPostIPAMIpsForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewPostIPAMIpsNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 405:\n\t\tresult := NewPostIPAMIpsMethodNotAllowed()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 410:\n\t\tresult := NewPostIPAMIpsGone()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewPostIPAMIpsInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 503:\n\t\tresult := NewPostIPAMIpsServiceUnavailable()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func get_input(question string) string {\n\treader := bufio.NewReader(os.Stdin)\n\n\tfor {\n\t\tfmt.Printf(question)\n\t\tresponse, err := reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Err: %s\\n\", err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tresponse = cleanInput(response)\n\t\tif len(response) > 0 {\n\t\t\treturn response\n\t\t}\n\t}\n}", "func (o *KillQueryReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 204:\n\t\tresult := NewKillQueryNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewKillQueryBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewKillQueryNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 422:\n\t\tresult := NewKillQueryUnprocessableEntity()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *PostMalQueryHuntV1Reader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewPostMalQueryHuntV1OK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewPostMalQueryHuntV1BadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 401:\n\t\tresult := NewPostMalQueryHuntV1Unauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewPostMalQueryHuntV1Forbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 429:\n\t\tresult := NewPostMalQueryHuntV1TooManyRequests()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewPostMalQueryHuntV1InternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"[POST /malquery/queries/hunt/v1] PostMalQueryHuntV1\", response, response.Code())\n\t}\n}", "func (p *program) doReadInput(i *instruction) {\n var input int64\n channelReadOk := false\n\n if p.inChannel != nil {\n select {\n case <-time.After(10 * time.Second):\n fmt.Println(\"waiting for input timed-out, trying to read from dataStack\")\n case input = <-p.inChannel:\n channelReadOk = true\n }\n }\n\n if !channelReadOk {\n if len(p.dataStack) > 0 {\n input = p.dataStack[len(p.dataStack)-1]\n p.dataStack = p.dataStack[:len(p.dataStack)-1]\n } else {\n reader := bufio.NewReader(os.Stdin)\n fmt.Print(\"Enter value: \")\n value, err := reader.ReadString('\\n')\n\n if err != nil {\n fmt.Println(err)\n }\n\n inputInt, err := strconv.Atoi(strings.TrimSuffix(value, \"\\n\"))\n\n if err != nil {\n fmt.Println(err)\n }\n\n input = int64(inputInt)\n }\n }\n\n p.memory[i.params[0].value] = input\n p.position += i.length\n}", "func (o *PostInstallReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewPostInstallOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewPostInstallUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewPostInstallForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewPostInstallNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewPostInstallInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *PatchAPIPublicV1IncidentsAckReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewPatchAPIPublicV1IncidentsAckOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 400:\n\t\tresult := NewPatchAPIPublicV1IncidentsAckBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 401:\n\t\tresult := NewPatchAPIPublicV1IncidentsAckUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 403:\n\t\tresult := NewPatchAPIPublicV1IncidentsAckForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 404:\n\t\tresult := NewPatchAPIPublicV1IncidentsAckNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 500:\n\t\tresult := NewPatchAPIPublicV1IncidentsAckInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func Readline(prompt string, interfaces ...interface{}) (string, error) {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Printf(prompt, interfaces...)\n\tinput, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tinput = strings.Trim(input, \"\\n\\r\")\n\treturn input, nil\n}", "func reader() {\n\n\tvar err error\n\n\tdefer func() {\n\t\tclose(EncodeChan)\n\t\tWaitGroup.Done()\n\t}()\n\n\t// Create a 16KB input buffer\n\tstdin := bufio.NewReaderSize(os.Stdin, 16384)\n\n\t// Loop over the stdin input and pass the data to the encoder.\n\tfor {\n\n\t\tbuf := make([]int16, AudioFrameSize*AudioChannels)\n\n\t\terr = binary.Read(stdin, binary.LittleEndian, &buf)\n\t\tif err == io.EOF {\n\t\t\t// Okay! There's nothing left, time to quit.\n\t\t\treturn\n\t\t}\n\n\t\tif err == io.ErrUnexpectedEOF {\n\t\t\t// Well there's just a tiny bit left, lets encode it, then quit.\n\t\t\tEncodeChan <- buf\n\t\t\treturn\n\t\t}\n\n\t\tif err != nil {\n\t\t\t// Oh no, something went wrong!\n\t\t\tlog.Println(\"error reading from stdin,\", err)\n\t\t\treturn\n\t\t}\n\n\t\t// write pcm data to the EncodeChan\n\t\tEncodeChan <- buf\n\t}\n\n}", "func (o *ListIncidentsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewListIncidentsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 400:\n\t\tresult := NewListIncidentsBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 401:\n\t\tresult := NewListIncidentsUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 402:\n\t\tresult := NewListIncidentsPaymentRequired()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 403:\n\t\tresult := NewListIncidentsForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 429:\n\t\tresult := NewListIncidentsTooManyRequests()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func streamReader(stream io.Reader, boundary string, output *string, streamName string) error {\n\tvar buf bytes.Buffer\n\tbuffer := make([]byte, readSize)\n\tmarker := []byte(boundary + newline)\n\n\tmi := -1\n\tfor {\n\t\tn, err := stream.Read(buffer)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"cannot read from %v\", streamName)\n\t\t}\n\n\t\tbuf.Write(buffer[:n])\n\t\tif mi = bytes.Index(buf.Bytes(), marker); mi >= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t*output = string(buf.Bytes()[:mi])\n\treturn nil\n}", "func (o *PingScannerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewPingScannerOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewPingScannerBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 401:\n\t\tresult := NewPingScannerUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewPingScannerForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewPingScannerInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *UpdateRemoteProcessGroupInputPortRunStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewUpdateRemoteProcessGroupInputPortRunStatusOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewUpdateRemoteProcessGroupInputPortRunStatusBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 401:\n\t\tresult := NewUpdateRemoteProcessGroupInputPortRunStatusUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewUpdateRemoteProcessGroupInputPortRunStatusForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewUpdateRemoteProcessGroupInputPortRunStatusNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 409:\n\t\tresult := NewUpdateRemoteProcessGroupInputPortRunStatusConflict()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *UploadWorkstationJposEntriesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewUploadWorkstationJposEntriesOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 400:\n\t\tresult := NewUploadWorkstationJposEntriesBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 404:\n\t\tresult := NewUploadWorkstationJposEntriesNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func readCmd() {\n\tbzIn, err := ioutil.ReadAll(os.Stdin)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"cannot read stdin: %v\", err)\n\t\treturn\n\t}\n\tvestingData, err := unmarshalVestingData(bzIn)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"cannot decode vesting data: %v\", err)\n\t\treturn\n\t}\n\tevents, err := vestingDataToEvents(vestingData)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"cannot convert vesting data: %v\", err)\n\t}\n\tbzOut, err := marshalEvents(events)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"cannot encode events: %v\", err)\n\t\treturn\n\t}\n\tfmt.Println(string(bzOut))\n}", "func (gosh *Goshell) Open(r *bufio.Reader) {\n\tloopCtx := gosh.ctx\n\tline := make(chan string)\n\tfor {\n\t\t// start a goroutine to get input from the user\n\t\tgo func(ctx context.Context, input chan<- string) {\n\t\t\tfor {\n\t\t\t\t// TODO: future enhancement is to capture input key by key\n\t\t\t\t// to give command granular notification of key events.\n\t\t\t\t// This could be used to implement command autocompletion.\n\t\t\t\tfmt.Fprintf(ctx.Value(\"gosh.stdout\").(io.Writer), \"%s \", api.GetPrompt(loopCtx))\n\t\t\t\tline, err := r.ReadString('\\n')\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Fprintf(ctx.Value(\"gosh.stderr\").(io.Writer), \"%v\\n\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tinput <- line\n\t\t\t\treturn\n\t\t\t}\n\t\t}(loopCtx, line)\n\n\t\t// wait for input or cancel\n\t\tselect {\n\t\tcase <-gosh.ctx.Done():\n\t\t\tclose(gosh.closed)\n\t\t\treturn\n\t\tcase input := <-line:\n\t\t\tvar err error\n\t\t\tloopCtx, err = gosh.handle(loopCtx, input)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(loopCtx.Value(\"gosh.stderr\").(io.Writer), \"%v\\n\", err)\n\t\t\t}\n\t\t}\n\t}\n}", "func (o *CreateUsingPOST2Reader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewCreateUsingPOST2OK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewCreateUsingPOST2Unauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewCreateUsingPOST2Forbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewCreateUsingPOST2NotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewCreateUsingPOST2InternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (s *kabuta) frontendReadLoop() {\n\tdefer wg.Done()\n\tb := make([]byte, 1024)\n\tfor {\n\t\tn, err := os.Stdin.Read(b)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif n > 0 {\n\t\t\tstr := strings.TrimSpace(string(b[0:n]))\n\t\t\t//\t\t\ts.log(\"RECEIVED %d bytes FROM FRONTEND:\\n----------------\\n[%s]\\n------------------\", n, str)\n\t\t\tstrArr := strings.Split(str, \"\\n\")\n\t\t\tfor _, str2 := range strArr {\n\t\t\t\tstr2 = strings.TrimSpace(str2)\n\t\t\t\tif str2 == \"\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ts.frontendChannel <- str2\n\t\t\t}\n\t\t\tb = make([]byte, 1024)\n\t\t}\n\t}\n}", "func (o *FrontPutBinaryReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewFrontPutBinaryOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func listenWrite(conn net.Conn, done chan bool) {\n readerStdin := bufio.NewReader(os.Stdin)\n\n for {\n // read in input from stdin\n message, err := readerStdin.ReadString('\\n')\n\n // treat \"END\" as a keyword used by the user to terminate the connection\n if message == \"END\\n\" {\n conn.Close()\n done <- true\n break\n }\n\n if err != nil {\n fmt.Println(\"Error reading outgoing message: \", err.Error())\n }\n\n outgoing := encrypt([]byte(message))\n sendOutgoing(conn, outgoing)\n }\n}", "func (r *RPCIngressGateway) Read(req *ReadReq, resp *ReadResp) error {\n\tconn, err := r.getConn(req.ConnID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuf := make([]byte, req.BufLen)\n\n\tresp.N, err = conn.Read(buf)\n\tif resp.N != 0 {\n\t\tresp.B = make([]byte, resp.N)\n\t\tcopy(resp.B, buf[:resp.N])\n\t}\n\tif err != nil {\n\t\tif err.Error() != io.EOF.Error() {\n\t\t\t// we don't print warning if the conn is already closed\n\t\t\t_, ok := r.cm.Get(req.ConnID)\n\t\t\tif ok {\n\t\t\t\tr.log.WithError(err).Warn(\"Received unexpected error when reading from server.\")\n\t\t\t}\n\t\t}\n\t}\n\n\tif wrappedConn, ok := conn.(*appnet.WrappedConn); ok {\n\t\tif skywireConn, ok := wrappedConn.Conn.(*appnet.SkywireConn); ok {\n\t\t\tif ngErr := skywireConn.GetError(); ngErr != nil {\n\t\t\t\terr = ngErr\n\t\t\t}\n\t\t}\n\t}\n\n\tresp.Err = ioErrToRPCIOErr(err)\n\n\t// avoid error in RPC pipeline, error is included in response body\n\treturn nil\n}", "func readData(input *string) ([]byte, error) {\n\tif *input == \"-\" {\n\t\tlog.Println(\"reading bytes from stdin\")\n\t\treturn ioutil.ReadAll(os.Stdin)\n\t} else {\n\t\tlog.Println(\"reading bytes from '\" + *input + \"'\")\n\t\treturn ioutil.ReadFile(*input)\n\t}\n}", "func (o *GetAllMyScratchRecipesAndNutritionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewGetAllMyScratchRecipesAndNutritionOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 400:\n\t\tresult := NewGetAllMyScratchRecipesAndNutritionBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 403:\n\t\tresult := NewGetAllMyScratchRecipesAndNutritionForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *PostIPAMIpnatReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewPostIPAMIpnatOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewPostIPAMIpnatBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 401:\n\t\tresult := NewPostIPAMIpnatUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewPostIPAMIpnatForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewPostIPAMIpnatNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 405:\n\t\tresult := NewPostIPAMIpnatMethodNotAllowed()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 410:\n\t\tresult := NewPostIPAMIpnatGone()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewPostIPAMIpnatInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 503:\n\t\tresult := NewPostIPAMIpnatServiceUnavailable()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (pr *PushedRequest) ReadResponse(ctx context.Context) (*http.Response, error) {\n\tselect {\n\tcase <-ctx.Done():\n\t\tpr.Cancel()\n\t\tpr.pushedStream.bufPipe.CloseWithError(ctx.Err())\n\t\treturn nil, ctx.Err()\n\tcase <-pr.pushedStream.peerReset:\n\t\treturn nil, pr.pushedStream.resetErr\n\tcase resErr := <-pr.pushedStream.resc:\n\t\tif resErr.err != nil {\n\t\t\tfmt.Println(resErr.err.Error())\n\t\t\tpr.Cancel()\n\t\t\tpr.pushedStream.bufPipe.CloseWithError(resErr.err)\n\t\t\treturn nil, resErr.err\n\t\t}\n\t\tresErr.res.Request = pr.Promise\n\t\tresErr.res.TLS = pr.pushedStream.cc.tlsState\n\t\treturn resErr.res, resErr.err\n\t}\n}", "func (c *client) exec(r *http.Request) (io.ReadCloser, error) {\n\tresp, err := c.doRaw(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"bad response code: %d\\n\"+\n\t\t\t\"request was: %v\\n\",\n\t\t\tresp.StatusCode,\n\t\t\tr)\n\t}\n\n\tif resp.Body == nil {\n\t\treturn nil, fmt.Errorf(\"no body in response\")\n\t}\n\n\treturn resp.Body, nil\n}", "func (o *PostAPI24AdminsAPITokensReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewPostApi24AdminsAPITokensOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewPostApi24AdminsAPITokensBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}" ]
[ "0.6441028", "0.63901263", "0.62262696", "0.6013053", "0.59019506", "0.58822507", "0.58704776", "0.5861052", "0.5858616", "0.58128464", "0.5801528", "0.57563275", "0.57038724", "0.56415284", "0.55841076", "0.5574646", "0.55571336", "0.5547796", "0.5487941", "0.5450496", "0.54420626", "0.5437554", "0.5435918", "0.5406791", "0.54059494", "0.540109", "0.5393747", "0.5382991", "0.5381614", "0.5378201", "0.53769934", "0.53135014", "0.52994794", "0.5245643", "0.52448547", "0.5231426", "0.52033234", "0.51987356", "0.5193275", "0.5189232", "0.5186013", "0.5185451", "0.51833266", "0.5171732", "0.5161967", "0.5151416", "0.5144779", "0.51403624", "0.51395977", "0.51357156", "0.51308095", "0.51288956", "0.51248866", "0.5120173", "0.5119528", "0.51039654", "0.5092134", "0.5091951", "0.5083561", "0.50803477", "0.50800174", "0.50786674", "0.50783795", "0.50753134", "0.50719637", "0.5070599", "0.5069899", "0.5069758", "0.50369024", "0.503674", "0.50356317", "0.50308436", "0.5030118", "0.5029403", "0.5028901", "0.5023788", "0.50213736", "0.50198203", "0.5016579", "0.50109714", "0.50062865", "0.5000792", "0.50004303", "0.49984333", "0.49954817", "0.49946564", "0.49852636", "0.4984527", "0.49833655", "0.4978346", "0.49765554", "0.49721563", "0.49707133", "0.49650064", "0.49614543", "0.49607295", "0.49606487", "0.49559432", "0.49517393", "0.49506658" ]
0.733204
0
Expose passes up Prometheus metrics to the caller, based on control switches which dictate what metrics the caller wishes to use
func (m Metrics) Expose() []*prometheus.CounterVec { var exposed []*prometheus.CounterVec if m.RequestCounter { exposed = append(exposed, httpReqs) } if m.ProxyCounter { exposed = append(exposed, proxyCount) } return exposed }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ExposeMetrics(options config.Options, stopCh <-chan struct{}, wg *sync.WaitGroup, logger log.Logger) {\n\twg.Add(1)\n\tdefer wg.Done()\n\n\tlogger = log.NewLoggerWith(logger, \"component\", \"metrics\")\n\n\tif options.IsEnableAdditionalSymantecMetrics {\n\t\tregisterCollectors(NewSymantecMetricsCollector(options, logger))\n\t} else {\n\t\tregisterCollectors(nil)\n\t}\n\n\tln, err := net.Listen(\"tcp\", fmt.Sprintf(\"0.0.0.0:%v\", options.MetricPort))\n\tif err != nil {\n\t\tlogger.LogError(\"failed to open listener\", err)\n\t\treturn\n\t}\n\n\tlogger.LogInfo(\"exposing prometheus metrics\", \"host\", \"0.0.0.0\", \"port\", options.MetricPort)\n\n\tgo http.Serve(ln, promhttp.Handler())\n\t<- stopCh\n\tln.Close()\n}", "func Metrics(w http.ResponseWriter, r *http.Request) {\n\tpromhttp.Handler().ServeHTTP(w, r)\n}", "func goMetricsMiddleWare(c *gin.Context) {\n\tkey := c.Request.Method + \";\" + c.Request.URL.Path\n\n\tmetrics.GetOrRegisterMeter(\"meter;\" + key, metrics.DefaultRegistry).Mark(1)\n\tmetrics.GetOrRegisterTimer(\"timer;\" + key, metrics.DefaultRegistry).Time(c.Next)\n}", "func Metrics(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tstart := time.Now()\n\t\twrw := middleware.NewWrapResponseWriter(w, r.ProtoMajor)\n\t\tnext.ServeHTTP(wrw, r)\n\n\t\treqs.WithLabelValues(http.StatusText(wrw.Status()), r.Method, r.URL.Path).Inc()\n\t\tlatency.WithLabelValues(http.StatusText(wrw.Status()), r.Method, r.URL.Path).Observe(float64(time.Since(start).Nanoseconds()) / 1000000)\n\t}\n\n\treturn http.HandlerFunc(fn)\n}", "func produceMetrics(completeStatMap map[string]string, metricChannel chan<- prometheus.Metric) {\n\n\t// kamailio_core_request_total\n\tconvertStatToMetric(completeStatMap, \"core.drop_requests\", \"drop\", core_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.err_requests\", \"err\", core_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.fwd_requests\", \"fwd\", core_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests\", \"rcv\", core_request_total, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_core_rcv_request_total\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_ack\", \"ack\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_bye\", \"bye\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_cancel\", \"cancel\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_info\", \"info\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_invite\", \"invite\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_message\", \"message\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_notify\", \"notify\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_options\", \"options\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_prack\", \"prack\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_publish\", \"publish\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_refer\", \"refer\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_register\", \"register\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_subscribe\", \"subscribe\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_update\", \"update\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.unsupported_methods\", \"unsupported\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_core_reply_total\n\tconvertStatToMetric(completeStatMap, \"core.drop_replies\", \"drop\", core_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.err_replies\", \"err\", core_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.fwd_replies\", \"fwd\", core_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies\", \"rcv\", core_reply_total, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_core_rcv_reply_total\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_18x\", \"18x\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_1xx\", \"1xx\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_2xx\", \"2xx\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_3xx\", \"3xx\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_401\", \"401\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_404\", \"404\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_407\", \"407\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_408\", \"408\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_480\", \"480\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_486\", \"486\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_4xx\", \"4xx\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_5xx\", \"5xx\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_6xx\", \"6xx\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_shm_bytes\n\tconvertStatToMetric(completeStatMap, \"shmem.free_size\", \"free\", shmem_bytes, metricChannel, prometheus.GaugeValue)\n\tconvertStatToMetric(completeStatMap, \"shmem.max_used_size\", \"max_used\", shmem_bytes, metricChannel, prometheus.GaugeValue)\n\tconvertStatToMetric(completeStatMap, \"shmem.real_used_size\", \"real_used\", shmem_bytes, metricChannel, prometheus.GaugeValue)\n\tconvertStatToMetric(completeStatMap, \"shmem.total_size\", \"total\", shmem_bytes, metricChannel, prometheus.GaugeValue)\n\tconvertStatToMetric(completeStatMap, \"shmem.used_size\", \"used\", shmem_bytes, metricChannel, prometheus.GaugeValue)\n\n\tconvertStatToMetric(completeStatMap, \"shmem.fragments\", \"\", shmem_fragments, metricChannel, prometheus.GaugeValue)\n\tconvertStatToMetric(completeStatMap, \"dns.failed_dns_request\", \"\", dns_failed, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.bad_URIs_rcvd\", \"\", bad_uri, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.bad_msg_hdr\", \"\", bad_msg_hdr, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_sl_reply_total\n\tconvertStatToMetric(completeStatMap, \"sl.1xx_replies\", \"1xx\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.200_replies\", \"200\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.202_replies\", \"202\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.2xx_replies\", \"2xx\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.300_replies\", \"300\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.301_replies\", \"301\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.302_replies\", \"302\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.3xx_replies\", \"3xx\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.400_replies\", \"400\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.401_replies\", \"401\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.403_replies\", \"403\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.404_replies\", \"404\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.407_replies\", \"407\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.408_replies\", \"408\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.483_replies\", \"483\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.4xx_replies\", \"4xx\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.500_replies\", \"500\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.5xx_replies\", \"5xx\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.6xx_replies\", \"6xx\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_sl_type_total\n\tconvertStatToMetric(completeStatMap, \"sl.failures\", \"failure\", sl_type_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.received_ACKs\", \"received_ack\", sl_type_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.sent_err_replies\", \"sent_err_reply\", sl_type_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.sent_replies\", \"sent_reply\", sl_type_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.xxx_replies\", \"xxx_reply\", sl_type_total, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_tcp_total\n\tconvertStatToMetric(completeStatMap, \"tcp.con_reset\", \"con_reset\", tcp_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tcp.con_timeout\", \"con_timeout\", tcp_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tcp.connect_failed\", \"connect_failed\", tcp_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tcp.connect_success\", \"connect_success\", tcp_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tcp.established\", \"established\", tcp_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tcp.local_reject\", \"local_reject\", tcp_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tcp.passive_open\", \"passive_open\", tcp_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tcp.send_timeout\", \"send_timeout\", tcp_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tcp.sendq_full\", \"sendq_full\", tcp_total, metricChannel, prometheus.CounterValue)\n\t// kamailio_tcp_connections\n\tconvertStatToMetric(completeStatMap, \"tcp.current_opened_connections\", \"\", tcp_connections, metricChannel, prometheus.GaugeValue)\n\t// kamailio_tcp_writequeue\n\tconvertStatToMetric(completeStatMap, \"tcp.current_write_queue_size\", \"\", tcp_writequeue, metricChannel, prometheus.GaugeValue)\n\n\t// kamailio_tmx_code_total\n\tconvertStatToMetric(completeStatMap, \"tmx.2xx_transactions\", \"2xx\", tmx_code_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.3xx_transactions\", \"3xx\", tmx_code_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.4xx_transactions\", \"4xx\", tmx_code_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.5xx_transactions\", \"5xx\", tmx_code_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.6xx_transactions\", \"6xx\", tmx_code_total, metricChannel, prometheus.CounterValue)\n\t// kamailio_tmx_type_total\n\tconvertStatToMetric(completeStatMap, \"tmx.UAC_transactions\", \"uac\", tmx_type_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.UAS_transactions\", \"uas\", tmx_type_total, metricChannel, prometheus.CounterValue)\n\t// kamailio_tmx\n\tconvertStatToMetric(completeStatMap, \"tmx.active_transactions\", \"active\", tmx, metricChannel, prometheus.GaugeValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.inuse_transactions\", \"inuse\", tmx, metricChannel, prometheus.GaugeValue)\n\n\t// kamailio_tmx_rpl_total\n\tconvertStatToMetric(completeStatMap, \"tmx.rpl_absorbed\", \"absorbed\", tmx_rpl_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.rpl_generated\", \"generated\", tmx_rpl_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.rpl_received\", \"received\", tmx_rpl_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.rpl_relayed\", \"relayed\", tmx_rpl_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.rpl_sent\", \"sent\", tmx_rpl_total, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_dialog\n\tconvertStatToMetric(completeStatMap, \"dialog.active_dialogs\", \"active_dialogs\", dialog, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"dialog.early_dialogs\", \"early_dialogs\", dialog, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"dialog.expired_dialogs\", \"expired_dialogs\", dialog, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"dialog.failed_dialogs\", \"failed_dialogs\", dialog, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"dialog.processed_dialogs\", \"processed_dialogs\", dialog, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_usrloc\n\tconvertStatToMetric(completeStatMap, \"usrloc.location-contacts\", \"location-contacts\", usrloc, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"usrloc.location-expires\", \"location-expires\", usrloc, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"usrloc.location-users\", \"location-users\", usrloc, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"usrloc.registered_users\", \"registered_users\", usrloc, metricChannel, prometheus.CounterValue)\n}", "func (c *Client) setMetrics(status *Status, stats *Stats, logstats *LogStats) {\n\t//Status\n\tvar isRunning int = 0\n\tif status.Running == true {\n\t\tisRunning = 1\n\t}\n\tmetrics.Running.WithLabelValues(c.hostname).Set(float64(isRunning))\n\n\tvar isProtected int = 0\n\tif status.ProtectionEnabled == true {\n\t\tisProtected = 1\n\t}\n\tmetrics.ProtectionEnabled.WithLabelValues(c.hostname).Set(float64(isProtected))\n\n\t//Stats\n\tmetrics.AvgProcessingTime.WithLabelValues(c.hostname).Set(float64(stats.AvgProcessingTime))\n\tmetrics.DnsQueries.WithLabelValues(c.hostname).Set(float64(stats.DnsQueries))\n\tmetrics.BlockedFiltering.WithLabelValues(c.hostname).Set(float64(stats.BlockedFiltering))\n\tmetrics.ParentalFiltering.WithLabelValues(c.hostname).Set(float64(stats.ParentalFiltering))\n\tmetrics.SafeBrowsingFiltering.WithLabelValues(c.hostname).Set(float64(stats.SafeBrowsingFiltering))\n\tmetrics.SafeSearchFiltering.WithLabelValues(c.hostname).Set(float64(stats.SafeSearchFiltering))\n\n\tfor l := range stats.TopQueries {\n\t\tfor domain, value := range stats.TopQueries[l] {\n\t\t\tmetrics.TopQueries.WithLabelValues(c.hostname, domain).Set(float64(value))\n\t\t}\n\t}\n\n\tfor l := range stats.TopBlocked {\n\t\tfor domain, value := range stats.TopBlocked[l] {\n\t\t\tmetrics.TopBlocked.WithLabelValues(c.hostname, domain).Set(float64(value))\n\t\t}\n\t}\n\n\tfor l := range stats.TopClients {\n\t\tfor source, value := range stats.TopClients[l] {\n\t\t\tmetrics.TopClients.WithLabelValues(c.hostname, source).Set(float64(value))\n\t\t}\n\t}\n\n\t//LogQuery\n\tm = make(map[string]int)\n\tlogdata := logstats.Data\n\tfor i := range logdata {\n\t\tdnsanswer := logdata[i].Answer\n\t\tif dnsanswer != nil && len(dnsanswer) > 0 {\n\t\t\tfor j := range dnsanswer {\n\t\t\t\tvar dnsType string\n\t\t\t\t//Check the type of dnsanswer[j].Value, if string leave it be, otherwise get back the object to get the correct DNS type\n\t\t\t\tswitch v := dnsanswer[j].Value.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\tdnsType = dnsanswer[j].Type\n\t\t\t\t\tm[dnsType] += 1\n\t\t\t\tcase map[string]interface{}:\n\t\t\t\t\tvar dns65 Type65\n\t\t\t\t\tmapstructure.Decode(v, &dns65)\n\t\t\t\t\tdnsType = \"TYPE\" + strconv.Itoa(dns65.Hdr.Rrtype)\n\t\t\t\t\tm[dnsType] += 1\n\t\t\t\tdefault:\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor key, value := range m {\n\t\tmetrics.QueryTypes.WithLabelValues(c.hostname, key).Set(float64(value))\n\t}\n\n\t//clear the map\n\tfor k := range m {\n\t\tdelete(m, k)\n\t}\n}", "func addMetrics(ctx context.Context, cfg *rest.Config, namespace string) {\n\tif err := serveCRMetrics(cfg); err != nil {\n\t\tif errors.Is(err, k8sutil.ErrRunLocal) {\n\t\t\tlogrus.Infof(\"Skipping CR metrics server creation; not running in a cluster.\")\n\t\t\treturn\n\t\t}\n\t\tlogrus.Infof(\"Could not generate and serve custom resource metrics, error: %v\", err)\n\t}\n\n\t// Add to the below struct any other metrics ports you want to expose.\n\tservicePorts := []v1.ServicePort{\n\t\t{Port: metricsPort, Name: metrics.OperatorPortName, Protocol: v1.ProtocolTCP, TargetPort: intstr.IntOrString{Type: intstr.Int, IntVal: metricsPort}},\n\t\t{Port: operatorMetricsPort, Name: metrics.CRPortName, Protocol: v1.ProtocolTCP, TargetPort: intstr.IntOrString{Type: intstr.Int, IntVal: operatorMetricsPort}},\n\t}\n\n\t// Create Service object to expose the metrics port(s).\n\tservice, err := metrics.CreateMetricsService(ctx, cfg, servicePorts)\n\tif err != nil {\n\t\tlogrus.Infof(\"Could not create metrics Service error: %v\", err)\n\t}\n\n\t// CreateServiceMonitors will automatically create the prometheus-operator ServiceMonitor resources\n\t// necessary to configure Prometheus to scrape metrics from this operator.\n\tservices := []*v1.Service{service}\n\t_, err = metrics.CreateServiceMonitors(cfg, namespace, services)\n\tif err != nil {\n\t\tlogrus.Infof(\"Could not create ServiceMonitor object error: %v\", err)\n\t\t// If this operator is deployed to a cluster without the prometheus-operator running, it will return\n\t\t// ErrServiceMonitorNotPresent, which can be used to safely skip ServiceMonitor creation.\n\t\tif err == metrics.ErrServiceMonitorNotPresent {\n\t\t\tlogrus.Infof(\"Install prometheus-operator in your cluster to create ServiceMonitor objects error: %v\", err)\n\t\t}\n\t}\n}", "func Metrics(args *common.Parameters) {\n\t//Setup variables used in the code.\n\tvar historyInterval time.Duration\n\thistoryInterval = 0\n\tvar query, requestsLabel string\n\tvar result model.Value\n\tvar err error\n\n\t//Start and end time + the prometheus address used for querying\n\trange5Min := common.TimeRange(args, historyInterval)\n\n\tquery = `sum(kube_pod_container_resource_limits) by (resource)`\n\tresult, err = common.MetricCollect(args, query, range5Min)\n\tif mat, ok := result.(model.Matrix); err != nil || !ok || mat.Len() == 0 {\n\t\tquery = `sum(kube_pod_container_resource_limits_cpu_cores*1000)`\n\t\tresult, err = common.MetricCollect(args, query, range5Min)\n\t\tif err != nil {\n\t\t\targs.WarnLogger.Println(\"metric=cpuLimit query=\" + query + \" message=\" + err.Error())\n\t\t\tfmt.Println(\"[WARNING] metric=cpuLimit query=\" + query + \" message=\" + err.Error())\n\t\t} else {\n\t\t\tgetClusterMetric(result, \"cpuLimit\")\n\t\t}\n\n\t\tquery = `sum(kube_pod_container_resource_limits_memory_bytes/1024/1024)`\n\t\tresult, err = common.MetricCollect(args, query, range5Min)\n\t\tif err != nil {\n\t\t\targs.WarnLogger.Println(\"metric=memLimit query=\" + query + \" message=\" + err.Error())\n\t\t\tfmt.Println(\"[WARNING] metric=memLimit query=\" + query + \" message=\" + err.Error())\n\t\t} else {\n\t\t\tgetClusterMetric(result, \"memLimit\")\n\t\t}\n\t} else {\n\t\tgetClusterMetric(result, \"limits\")\n\t}\n\n\tquery = `sum(kube_pod_container_resource_requests) by (resource)`\n\tresult, err = common.MetricCollect(args, query, range5Min)\n\tif mat, ok := result.(model.Matrix); err != nil || !ok || mat.Len() == 0 {\n\t\tquery = `sum(kube_pod_container_resource_requests_cpu_cores*1000)`\n\t\tresult, err = common.MetricCollect(args, query, range5Min)\n\t\tif err != nil {\n\t\t\targs.WarnLogger.Println(\"metric=cpuRequest query=\" + query + \" message=\" + err.Error())\n\t\t\tfmt.Println(\"[WARNING] metric=cpuRequest query=\" + query + \" message=\" + err.Error())\n\t\t} else {\n\t\t\tgetClusterMetric(result, \"cpuRequest\")\n\t\t}\n\n\t\tquery = `sum(kube_pod_container_resource_requests_memory_bytes/1024/1024)`\n\t\tresult, err = common.MetricCollect(args, query, range5Min)\n\t\tif err != nil {\n\t\t\targs.WarnLogger.Println(\"metric=memRequest query=\" + query + \" message=\" + err.Error())\n\t\t\tfmt.Println(\"[WARNING] metric=memRequest query=\" + query + \" message=\" + err.Error())\n\t\t} else {\n\t\t\tgetClusterMetric(result, \"memRequest\")\n\t\t}\n\t} else {\n\t\tgetClusterMetric(result, \"requests\")\n\t\trequestsLabel = \"unified\"\n\t}\n\n\twriteAttributes(args)\n\twriteConfig(args)\n\n\tvar metricField []model.LabelName\n\n\tif requestsLabel == \"unified\" {\n\t\t//Query and store prometheus CPU requests\n\t\tquery = `avg(sum(kube_pod_container_resource_requests{resource=\"cpu\"}) by (node))`\n\t\tcommon.GetWorkload(\"cpu_requests\", \"CpuRequests\", query, metricField, args, entityKind)\n\n\t\t//Query and store prometheus CPU requests\n\t\tquery = `avg(sum(kube_pod_container_resource_requests{resource=\"cpu\"}) by (node) / sum(kube_node_status_capacity{resource=\"cpu\"}) by (node)) * 100`\n\t\tcommon.GetWorkload(\"cpu_reservation_percent\", \"CpuReservationPercent\", query, metricField, args, entityKind)\n\n\t\t//Query and store prometheus Memory requests\n\t\tquery = `avg(sum(kube_pod_container_resource_requests{resource=\"memory\"}/1024/1024) by (node))`\n\t\tcommon.GetWorkload(\"memory_requests\", \"MemoryRequests\", query, metricField, args, entityKind)\n\n\t\t//Query and store prometheus Memory requests\n\t\tquery = `avg(sum(kube_pod_container_resource_requests{resource=\"memory\"}/1024/1024) by (node) / sum(kube_node_status_capacity{resource=\"memory\"}/1024/1024) by (node)) * 100`\n\t\tcommon.GetWorkload(\"memory_reservation_percent\", \"MemoryReservationPercent\", query, metricField, args, entityKind)\n\t} else {\n\t\t//Query and store prometheus CPU requests\n\t\tquery = `avg(sum(kube_pod_container_resource_requests_cpu_cores) by (node))`\n\t\tcommon.GetWorkload(\"cpu_requests\", \"CpuRequests\", query, metricField, args, entityKind)\n\n\t\t//Query and store prometheus CPU requests\n\t\tquery = `avg(sum(kube_pod_container_resource_requests_cpu_cores) by (node) / sum(kube_node_status_capacity_cpu_cores) by (node)) * 100`\n\t\tcommon.GetWorkload(\"cpu_reservation_percent\", \"CpuReservationPercent\", query, metricField, args, entityKind)\n\n\t\t//Query and store prometheus Memory requests\n\t\tquery = `avg(sum(kube_pod_container_resource_requests_memory_bytes/1024/1024) by (node))`\n\t\tcommon.GetWorkload(\"memory_requests\", \"MemoryRequests\", query, metricField, args, entityKind)\n\n\t\t//Query and store prometheus Memory requests\n\t\tquery = `avg(sum(kube_pod_container_resource_requests_memory_bytes/1024/1024) by (node) / sum(kube_node_status_capacity_memory_bytes/1024/1024) by (node)) * 100`\n\t\tcommon.GetWorkload(\"memory_reservation_percent\", \"MemoryReservationPercent\", query, metricField, args, entityKind)\n\t}\n\n\t//For cluster we don't have to check instance field and convert to pod_ip as we aren't looking to map to the node names but rather just get the avg for nodes. So we can use just instance field in all cases.\n\t//Query and store prometheus total cpu uptime in seconds\n\tquery = `avg(sum(irate(node_cpu_seconds_total{mode!=\"idle\"}[` + args.SampleRateString + `m])) by (instance) / on (instance) group_left count(node_cpu_seconds_total{mode=\"idle\"}) by (instance) *100)`\n\tcommon.GetWorkload(\"cpu_utilization\", \"CpuUtilization\", query, metricField, args, entityKind)\n\n\t//Query and store prometheus node memory total in bytes\n\tquery = `avg(node_memory_MemTotal_bytes - node_memory_MemFree_bytes)`\n\tcommon.GetWorkload(\"memory_raw_bytes\", \"MemoryBytes\", query, metricField, args, entityKind)\n\n\t//Query and store prometheus node memory total free in bytes\n\tquery = `avg(node_memory_MemTotal_bytes - (node_memory_MemFree_bytes + node_memory_Cached_bytes + node_memory_Buffers_bytes))`\n\tcommon.GetWorkload(\"memory_actual_workload\", \"MemoryActualWorkload\", query, metricField, args, entityKind)\n\n\t//Query and store prometheus node disk write in bytes\n\tquery = `avg(sum(irate(node_disk_written_bytes_total{device!~\"dm-.*\"}[` + args.SampleRateString + `m])) by (instance))`\n\tcommon.GetWorkload(\"disk_write_bytes\", \"DiskWriteBytes\", query, metricField, args, entityKind)\n\n\t//Query and store prometheus node disk read in bytes\n\tquery = `avg(sum(irate(node_disk_read_bytes_total{device!~\"dm-.*\"}[` + args.SampleRateString + `m])) by (instance))`\n\tcommon.GetWorkload(\"disk_read_bytes\", \"DiskReadBytes\", query, metricField, args, entityKind)\n\n\t//Query and store prometheus total disk read uptime as a percentage\n\tquery = `avg(sum(irate(node_disk_read_time_seconds_total{device!~\"dm-.*\"}[` + args.SampleRateString + `m]) / irate(node_disk_io_time_seconds_total{device!~\"dm-.*\"}[` + args.SampleRateString + `m])) by (instance))`\n\tcommon.GetWorkload(\"disk_read_ops\", \"DiskReadOps\", query, metricField, args, entityKind)\n\n\t//Query and store prometheus total disk write uptime as a percentage\n\tquery = `avg(sum(irate(node_disk_write_time_seconds_total{device!~\"dm-.*\"}[` + args.SampleRateString + `m]) / irate(node_disk_io_time_seconds_total{device!~\"dm-.*\"}[` + args.SampleRateString + `m])) by (instance))`\n\tcommon.GetWorkload(\"disk_write_ops\", \"DiskWriteOps\", query, metricField, args, entityKind)\n\n\t//Total disk values\n\t//Query and store prometheus node disk read in bytes\n\tquery = `avg(sum(irate(node_disk_read_bytes_total{device!~\"dm-.*\"}[` + args.SampleRateString + `m]) + irate(node_disk_written_bytes_total{device!~\"dm-.*\"}[` + args.SampleRateString + `m])) by (instance))`\n\tcommon.GetWorkload(\"disk_total_bytes\", \"DiskTotalBytes\", query, metricField, args, entityKind)\n\n\t//Query and store prometheus total disk read uptime as a percentage\n\tquery = `avg(sum((irate(node_disk_read_time_seconds_total{device!~\"dm-.*\"}[` + args.SampleRateString + `m]) + irate(node_disk_write_time_seconds_total{device!~\"dm-.*\"}[` + args.SampleRateString + `m])) / irate(node_disk_io_time_seconds_total{device!~\"dm-.*\"}[` + args.SampleRateString + `m])) by (instance))`\n\tcommon.GetWorkload(\"disk_total_ops\", \"DiskTotalOps\", query, metricField, args, entityKind)\n\n\t//Query and store prometheus node received network data in bytes\n\tquery = `avg(sum(irate(node_network_receive_bytes_total{device!~\"veth.*\"}[` + args.SampleRateString + `m])) by (instance))`\n\tcommon.GetWorkload(\"net_received_bytes\", \"NetReceivedBytes\", query, metricField, args, entityKind)\n\n\t//Query and store prometheus recieved network data in packets\n\tquery = `avg(sum(irate(node_network_receive_packets_total{device!~\"veth.*\"}[` + args.SampleRateString + `m])) by (instance))`\n\tcommon.GetWorkload(\"net_received_packets\", \"NetReceivedPackets\", query, metricField, args, entityKind)\n\n\t//Query and store prometheus total transmitted network data in bytes\n\tquery = `avg(sum(irate(node_network_transmit_bytes_total{device!~\"veth.*\"}[` + args.SampleRateString + `m])) by (instance))`\n\tcommon.GetWorkload(\"net_sent_bytes\", \"NetSentBytes\", query, metricField, args, entityKind)\n\n\t//Query and store prometheus total transmitted network data in packets\n\tquery = `avg(sum(irate(node_network_transmit_packets_total{device!~\"veth.*\"}[` + args.SampleRateString + `m])) by (instance))`\n\tcommon.GetWorkload(\"net_sent_packets\", \"NetSentPackets\", query, metricField, args, entityKind)\n\n\t//Total values network\n\t//Query and store prometheus total network data in bytes\n\tquery = `avg(sum(irate(node_network_transmit_bytes_total{device!~\"veth.*\"}[` + args.SampleRateString + `m]) + irate(node_network_receive_bytes_total{device!~\"veth.*\"}[` + args.SampleRateString + `m])) by (instance))`\n\tcommon.GetWorkload(\"net_total_bytes\", \"NetTotalBytes\", query, metricField, args, entityKind)\n\n\t//Query and store prometheus total network data in packets\n\tquery = `avg(sum(irate(node_network_transmit_packets_total{device!~\"veth.*\"}[` + args.SampleRateString + `m]) + irate(node_network_receive_packets_total{device!~\"veth.*\"}[` + args.SampleRateString + `m])) by (instance))`\n\tcommon.GetWorkload(\"net_total_packets\", \"NetTotalPackets\", query, metricField, args, entityKind)\n\n}", "func setupMetrics() *Metrics {\n\t// Requests duration\n\tduration := prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\tName: \"http_request_duration\",\n\t\tHelp: \"Duration of the http requests processed.\",\n\t},\n\t\t[]string{\"status\", \"method\", \"path\"},\n\t)\n\tprometheus.MustRegister(duration)\n\n\treturn &Metrics{\n\t\tduration: duration,\n\t}\n}", "func Prommetric(input string, bot *models.Bot) {\n\tif bot.Metrics {\n\t\tif input == \"init\" {\n\t\t\t// init router\n\t\t\tpromRouter = mux.NewRouter()\n\n\t\t\t// metrics health check handler\n\t\t\tpromHealthHandle := func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tif r.Method != http.MethodGet {\n\t\t\t\t\tlog.Error().Msgf(\"prometheus server: invalid method %#q\", r.Method)\n\t\t\t\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tlog.Debug().Msg(\"prometheus server: health check hit!\")\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\n\t\t\t\t_, err := w.Write([]byte(\"OK\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error().Msg(\"unable to send response\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tpromRouter.HandleFunc(\"/metrics_health\", promHealthHandle).Methods(\"GET\")\n\n\t\t\t// metrics handler\n\t\t\tprometheus.MustRegister(botResponseCollector)\n\t\t\tpromRouter.Handle(\"/metrics\", promhttp.Handler())\n\n\t\t\t// start prometheus server\n\t\t\tgo func() {\n\t\t\t\t//nolint:gosec // fix to make sure http serve is done with timeout in place\n\t\t\t\terr := http.ListenAndServe(\":8080\", promRouter)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal().Msgf(\"Prometheus handler errored: %v\", err)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tlog.Info().Msg(\"prometheus server: serving metrics at /metrics\")\n\t\t} else {\n\t\t\tbotResponseCollector.With(prometheus.Labels{\"rulename\": input}).Inc()\n\t\t}\n\t}\n}", "func NewMetrics(name string, r prometheus.Registerer) *Metrics {\n\treg := prometheus.WrapRegistererWith(prometheus.Labels{\"controller\": name}, r)\n\tm := Metrics{\n\t\treg: reg,\n\t\treconcileErrorsCounter: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tName: \"prometheus_operator_reconcile_errors_total\",\n\t\t\tHelp: \"Number of errors that occurred while reconciling the statefulset\",\n\t\t}),\n\t\ttriggerByCounter: prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\t\tName: \"prometheus_operator_triggered_total\",\n\t\t\tHelp: \"Number of times a Kubernetes object add, delete or update event\" +\n\t\t\t\t\" triggered the Prometheus Operator to reconcile an object\",\n\t\t}, []string{\"triggered_by\", \"action\"}),\n\t\tstsDeleteCreateCounter: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tName: \"prometheus_operator_reconcile_sts_delete_create_total\",\n\t\t\tHelp: \"Number of times that reconciling a statefulset required deleting and re-creating it\",\n\t\t}),\n\t\tlistCounter: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tName: \"prometheus_operator_list_operations_total\",\n\t\t\tHelp: \"Total number of list operations\",\n\t\t}),\n\t\tlistFailedCounter: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tName: \"prometheus_operator_list_operations_failed_total\",\n\t\t\tHelp: \"Total number of list operations that failed\",\n\t\t}),\n\t\twatchCounter: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tName: \"prometheus_operator_watch_operations_total\",\n\t\t\tHelp: \"Total number of watch operations\",\n\t\t}),\n\t\twatchFailedCounter: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tName: \"prometheus_operator_watch_operations_failed_total\",\n\t\t\tHelp: \"Total number of watch operations that failed\",\n\t\t}),\n\t}\n\tm.reg.MustRegister(\n\t\tm.reconcileErrorsCounter,\n\t\tm.triggerByCounter,\n\t\tm.stsDeleteCreateCounter,\n\t\tm.listCounter,\n\t\tm.listFailedCounter,\n\t\tm.watchCounter,\n\t\tm.watchFailedCounter,\n\t)\n\treturn &m\n}", "func main() {\n\tcluster.RegisterMetrics()\n\tgo func() {\n\t\tfor {\n\t\t\tcluster.RecordMetrics()\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t}()\n\n\thttp.Handle(\"/metrics\", promhttp.Handler())\n\thttp.ListenAndServe(\":2112\", nil)\n\n}", "func setupMetrics() Metrics {\n\tm := Metrics{}\n\tm.LastBackupDuration = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"last_backup_duration\",\n\t\tHelp: \"Backup duration in nanoseconds.\",\n\t})\n\tm.LastBackupSuccess = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"last_backup_success\",\n\t\tHelp: \"Last backup success boolean: 0=failed, 1=success, 2=unknown.\",\n\t})\n\tm.LastBackupStart = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"last_backup_start\",\n\t\tHelp: \"Last backup start timestamp.\",\n\t})\n\tm.LastBackupEnd = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"last_backup_end\",\n\t\tHelp: \"Last backup end timestamp.\",\n\t})\n\tm.SuccessfulBackups = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"successful_backups\",\n\t\tHelp: \"Number of Successful Backups.\",\n\t})\n\tm.FailedBackups = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"failed_backups\",\n\t\tHelp: \"Number of Failed Backups.\",\n\t})\n\tprometheus.MustRegister(\n\t\tm.LastBackupDuration,\n\t\tm.LastBackupStart,\n\t\tm.LastBackupEnd,\n\t\tm.LastBackupSuccess,\n\t\tm.SuccessfulBackups,\n\t\tm.FailedBackups,\n\t)\n\tm.LastBackupSuccess.Set(2) // 0=failed, 1=success, 2=unknown\n\treturn m\n}", "func Metrics(before web.Handler) web.Handler {\n\n\t// Wrap this handler around the next one provided.\n\th := func(ctx context.Context, log *log.Logger, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\t\tctx, span := trace.StartSpan(ctx, \"internal.mid.Metrics\")\n\t\tdefer span.End()\n\n\t\t// If the context is missing this value, request the service\n\t\t// to be shutdown gracefully.\n\t\tv, ok := ctx.Value(web.KeyValues).(*web.Values)\n\t\tif !ok {\n\t\t\treturn web.Shutdown(\"web value missing from context\")\n\t\t}\n\n\t\terr := before(ctx, log, w, r, params)\n\n\t\t// Add one to the request counter.\n\t\tm.req.Add(1)\n\n\t\t// Include the current count for the number of goroutines.\n\t\tif m.req.Value()%100 == 0 {\n\t\t\tm.gr.Set(int64(runtime.NumGoroutine()))\n\t\t}\n\n\t\t// Add one to the errors counter if an error occured\n\t\t// on this reuqest.\n\t\tif v.Error {\n\t\t\tm.err.Add(1)\n\t\t}\n\n\t\treturn err\n\t}\n\n\treturn h\n}", "func OpMetrics(w http.ResponseWriter, r *http.Request) {\n\n\t// Init output\n\toutput := []byte(\"\")\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\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\n\t// Get Results Object\n\tres, err := metrics.GetUsageCpuMem(refStr)\n\n\tif err != nil && err.Error() != \"not found\" {\n\t\terr := APIErrQueryDatastore()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := res.ExportJSON()\n\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\toutput = []byte(resJSON)\n\trespondOK(w, output)\n\n}", "func MetricsHandler(c *gin.Context) {\n\n\tmetrics.WritePrometheus(c.Writer, true)\n\n}", "func newMetrics() metrics {\n\treturn metrics{\n\t\tsize: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"pool_size\",\n\t\t\t\tHelp: \"Size of pool\",\n\t\t\t},\n\t\t),\n\n\t\tstatus: prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"pool_status\",\n\t\t\t\tHelp: `Status of pool (0, 1, 2, 3, 4, 5, 6)= {\"Offline\", \"Online\", \"Degraded\", \"Faulted\", \"Removed\", \"Unavail\", \"NoPoolsAvailable\"}`,\n\t\t\t},\n\t\t\t[]string{\"pool\"},\n\t\t),\n\n\t\tusedCapacity: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"used_pool_capacity\",\n\t\t\t\tHelp: \"Capacity used by pool\",\n\t\t\t},\n\t\t),\n\n\t\tfreeCapacity: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"free_pool_capacity\",\n\t\t\t\tHelp: \"Free capacity in pool\",\n\t\t\t},\n\t\t),\n\n\t\tusedCapacityPercent: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"used_pool_capacity_percent\",\n\t\t\t\tHelp: \"Capacity used by pool in percent\",\n\t\t\t},\n\t\t),\n\n\t\tzpoolListparseErrorCounter: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"zpool_list_parse_error_count\",\n\t\t\t\tHelp: \"Total no of parsing errors\",\n\t\t\t},\n\t\t),\n\n\t\tzpoolRejectRequestCounter: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"zpool_reject_request_count\",\n\t\t\t\tHelp: \"Total no of rejected requests of zpool command\",\n\t\t\t},\n\t\t),\n\n\t\tzpoolCommandErrorCounter: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"zpool_command_error\",\n\t\t\t\tHelp: \"Total no of zpool command errors\",\n\t\t\t},\n\t\t),\n\n\t\tnoPoolAvailableErrorCounter: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"no_pool_available_error\",\n\t\t\t\tHelp: \"Total no of no pool available errors\",\n\t\t\t},\n\t\t),\n\n\t\tincompleteOutputErrorCounter: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"zpool_list_incomplete_stdout_error\",\n\t\t\t\tHelp: \"Total no of incomplete stdout of zpool list command errors\",\n\t\t\t},\n\t\t),\n\t}\n}", "func Metrics(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Hello, metrics!\")\n}", "func (r *HvpaReconciler) AddMetrics() error {\n\tvar (\n\t\tm = &hvpaMetrics{}\n\t\tallCollectors []prometheus.Collector\n\t)\n\tm.aggrAppliedScalingsTotal = prometheus.NewGaugeVec(\n\t\tprometheus.GaugeOpts{\n\t\t\tNamespace: metricsNamespace,\n\t\t\tSubsystem: metricsSubsystemAggregate,\n\t\t\tName: \"applied_scaling_total\",\n\t\t\tHelp: \"The number of scalings applied by the HVPA controller.\",\n\t\t},\n\t\tnil,\n\t)\n\tallCollectors = append(allCollectors, m.aggrAppliedScalingsTotal)\n\n\tm.aggrBlockedScalingsTotal = prometheus.NewGaugeVec(\n\t\tprometheus.GaugeOpts{\n\t\t\tNamespace: metricsNamespace,\n\t\t\tSubsystem: metricsSubsystemAggregate,\n\t\t\tName: \"blocked_scalings_total\",\n\t\t\tHelp: \"The number of scalings blocked by the HVPA controller.\",\n\t\t},\n\t\t[]string{labelReason},\n\t)\n\tallCollectors = append(allCollectors, m.aggrBlockedScalingsTotal)\n\n\tif r.EnableDetailedMetrics {\n\t\tm.specReplicas = prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: metricsNamespace,\n\t\t\t\tSubsystem: metricsSubsystemSpec,\n\t\t\t\tName: \"replicas\",\n\t\t\t\tHelp: \"The number of replicas in the HVPA spec (part of the Scale sub-resource).\",\n\t\t\t},\n\t\t\t[]string{labelNamespace, labelName, labelTargetRefKind, labelTargetRefName, labelHpaUpdatePolicy, labelVpaUpdatePolicy},\n\t\t)\n\t\tallCollectors = append(allCollectors, m.specReplicas)\n\n\t\tm.statusReplicas = prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: metricsNamespace,\n\t\t\t\tSubsystem: metricsSubsystemStatus,\n\t\t\t\tName: \"replicas\",\n\t\t\t\tHelp: \"The number of replicas in the HVPA status (part of the Scale sub-resource).\",\n\t\t\t},\n\t\t\t[]string{labelNamespace, labelName, labelTargetRefKind, labelTargetRefName, labelHpaUpdatePolicy, labelVpaUpdatePolicy},\n\t\t)\n\t\tallCollectors = append(allCollectors, m.statusReplicas)\n\n\t\tm.statusAppliedHPACurrentReplicas = prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: metricsNamespace,\n\t\t\t\tSubsystem: metricsSubsystemStatus,\n\t\t\t\tName: \"applied_hpa_current_replicas\",\n\t\t\t\tHelp: \"The applied current replicas recommendation from HPA.\",\n\t\t\t},\n\t\t\t[]string{labelNamespace, labelName, labelTargetRefKind, labelTargetRefName, labelHpaUpdatePolicy, labelVpaUpdatePolicy},\n\t\t)\n\t\tallCollectors = append(allCollectors, m.statusAppliedHPACurrentReplicas)\n\n\t\tm.statusAppliedHPADesiredReplicas = prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: metricsNamespace,\n\t\t\t\tSubsystem: metricsSubsystemStatus,\n\t\t\t\tName: \"applied_hpa_desired_replicas\",\n\t\t\t\tHelp: \"The applied desired replicas recommendation from HPA.\",\n\t\t\t},\n\t\t\t[]string{labelNamespace, labelName, labelTargetRefKind, labelTargetRefName, labelHpaUpdatePolicy, labelVpaUpdatePolicy},\n\t\t)\n\t\tallCollectors = append(allCollectors, m.statusAppliedHPADesiredReplicas)\n\n\t\tm.statusAppliedVPARecommendation = prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: metricsNamespace,\n\t\t\t\tSubsystem: metricsSubsystemStatus,\n\t\t\t\tName: \"applied_vpa_recommendation\",\n\t\t\t\tHelp: \"The applied recommendation from VPA.\",\n\t\t\t},\n\t\t\t[]string{labelNamespace, labelName, labelTargetRefKind, labelTargetRefName, labelHpaUpdatePolicy, labelVpaUpdatePolicy, labelContainer, labelRecommendation, labelResource},\n\t\t)\n\t\tallCollectors = append(allCollectors, m.statusAppliedVPARecommendation)\n\n\t\tm.statusBlockedHPACurrentReplicas = prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: metricsNamespace,\n\t\t\t\tSubsystem: metricsSubsystemStatus,\n\t\t\t\tName: \"blocked_hpa_current_replicas\",\n\t\t\t\tHelp: \"The blocked current replicas recommendation from HPA.\",\n\t\t\t},\n\t\t\t[]string{labelNamespace, labelName, labelTargetRefKind, labelTargetRefName, labelHpaUpdatePolicy, labelVpaUpdatePolicy, labelReason},\n\t\t)\n\t\tallCollectors = append(allCollectors, m.statusBlockedHPACurrentReplicas)\n\n\t\tm.statusBlockedHPADesiredReplicas = prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: metricsNamespace,\n\t\t\t\tSubsystem: metricsSubsystemStatus,\n\t\t\t\tName: \"blocked_hpa_desired_replicas\",\n\t\t\t\tHelp: \"The blocked desired replicas recommendation from HPA.\",\n\t\t\t},\n\t\t\t[]string{labelNamespace, labelName, labelTargetRefKind, labelTargetRefName, labelHpaUpdatePolicy, labelVpaUpdatePolicy, labelReason},\n\t\t)\n\t\tallCollectors = append(allCollectors, m.statusBlockedHPADesiredReplicas)\n\n\t\tm.statusBlockedVPARecommendation = prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: metricsNamespace,\n\t\t\t\tSubsystem: metricsSubsystemStatus,\n\t\t\t\tName: \"blocked_vpa_recommendation\",\n\t\t\t\tHelp: \"The blocked recommendation from VPA.\",\n\t\t\t},\n\t\t\t[]string{labelNamespace, labelName, labelTargetRefKind, labelTargetRefName, labelHpaUpdatePolicy, labelVpaUpdatePolicy, labelReason, labelContainer, labelRecommendation, labelResource},\n\t\t)\n\t\tallCollectors = append(allCollectors, m.statusBlockedVPARecommendation)\n\t}\n\n\tr.metrics = m\n\n\tfor _, c := range allCollectors {\n\t\tif err := metrics.Registry.Register(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *Service) prometheus(c context.Context, method string) (mts []*monitor.Monitor, err error) {\n\tvar (\n\t\tsign, ins string\n\t\tnames []string\n\t\tparams = url.Values{}\n\t)\n\tins, _ = s.GetInterfaces(c)\n\tmts = make([]*monitor.Monitor, 0)\n\tparams.Add(\"Action\", \"GetPromDataRange\")\n\tparams.Add(\"PublicKey\", s.c.Prometheus.Key)\n\tparams.Add(\"DataSource\", \"app\")\n\tsign = s.auth(params)\n\tparams.Add(\"Signature\", sign)\n\tdate := time.Now().Format(\"2006-01-02\")\n\tparams.Set(\"Start\", date+\" 23:00:00\")\n\tparams.Set(\"End\", date+\" 23:00:10\")\n\tparams.Set(\"Step\", \"30\")\n\tnames = s.c.Apps.Name\n\tfor _, name := range names {\n\t\tvar (\n\t\t\tcostRet = &PrometheusRes{}\n\t\t\tcountRet = &PrometheusRes{}\n\t\t)\n\t\tparams.Set(\"Query\", fmt.Sprintf(costQuery, method, name))\n\t\tif err = s.PrometheusProxy(c, params, costRet); err != nil {\n\t\t\treturn\n\t\t}\n\t\tparams.Set(\"Query\", fmt.Sprintf(countQuery, method, name))\n\t\tif err = s.PrometheusProxy(c, params, countRet); err != nil {\n\t\t\treturn\n\t\t}\n\t\tfor _, val := range costRet.Data {\n\t\t\tvar (\n\t\t\t\tcount float64\n\t\t\t\tapi = val.Metric.Method\n\t\t\t)\n\t\t\tif api == \"inner.Ping\" || len(val.Values) < 1 || len(val.Values[0]) < 1 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcost, _ := strconv.ParseFloat(val.Values[0][1].(string), 64)\n\t\t\tif int64(cost) < s.c.Apps.Max && !strings.Contains(ins, api) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, v := range countRet.Data {\n\t\t\t\tif api == v.Metric.Method {\n\t\t\t\t\tcount, _ = strconv.ParseFloat(v.Values[0][1].(string), 64)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tmt := &monitor.Monitor{\n\t\t\t\tAppID: name + \"-\" + method,\n\t\t\t\tInterface: api,\n\t\t\t\tCount: int64(count),\n\t\t\t\tCost: int64(cost),\n\t\t\t}\n\t\t\tmts = append(mts, mt)\n\t\t}\n\t}\n\treturn\n}", "func Metrics() von.Middleware {\n\tm := func(before von.Handler) von.Handler {\n\t\th := func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\t\t\tctx, span := trace.SpanFromContext(ctx).Tracer().Start(ctx, \"von.middlewares.Metrics\")\n\t\t\tdefer span.End()\n\n\t\t\terr := before(ctx, w, r)\n\t\t\tm.req.Add(1)\n\t\t\tif m.req.Value()%100 == 0 {\n\t\t\t\tm.gr.Set(int64(runtime.NumGoroutine()))\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tm.err.Add(1)\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\treturn h\n\t}\n\n\treturn m\n}", "func (e *Exporter) setupInternalMetrics() {\n\n\te.configFileError = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tNamespace: e.namespace,\n\t\tSubsystem: \"exporter\",\n\t\tName: \"use_config_load_error\",\n\t\tHelp: \"Whether the user config file was loaded and parsed successfully (1 for error, 0 for success).\",\n\t\tConstLabels: e.constantLabels,\n\t}, []string{\"filename\", \"hashsum\"})\n\t// exporter level metrics\n\te.exporterUp = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: e.namespace, ConstLabels: e.constantLabels,\n\t\tSubsystem: \"exporter\", Name: \"up\", Help: \"always be 1 if your could retrieve metrics\",\n\t})\n\te.exporterUptime = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: e.namespace, ConstLabels: e.constantLabels,\n\t\tSubsystem: \"exporter\", Name: \"uptime\", Help: \"seconds since exporter primary server inited\",\n\t})\n\te.scrapeTotalCount = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: e.namespace, ConstLabels: e.constantLabels,\n\t\tSubsystem: \"exporter\", Name: \"scrape_total_count\", Help: \"times exporter was scraped for metrics\",\n\t})\n\te.scrapeErrorCount = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: e.namespace, ConstLabels: e.constantLabels,\n\t\tSubsystem: \"exporter\", Name: \"scrape_error_count\", Help: \"times exporter was scraped for metrics and failed\",\n\t})\n\te.scrapeDuration = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: e.namespace, ConstLabels: e.constantLabels,\n\t\tSubsystem: \"exporter\", Name: \"scrape_duration\", Help: \"seconds exporter spending on scrapping\",\n\t})\n\te.lastScrapeTime = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: e.namespace, ConstLabels: e.constantLabels,\n\t\tSubsystem: \"exporter\", Name: \"last_scrape_time\", Help: \"seconds exporter spending on scrapping\",\n\t})\n}", "func newServerMetrics() (*serverMetrics, error) {\n\tsm := &serverMetrics{\n\t\tconnections: prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"proxy_peer\",\n\t\t\t\tSubsystem: \"server\",\n\t\t\t\tName: \"connections\",\n\t\t\t\tHelp: \"Number of currently opened connection to proxy peer clients.\",\n\t\t\t},\n\t\t\t[]string{\"local_id\", \"remote_id\", \"state\"},\n\t\t),\n\n\t\trpcs: prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"proxy_peer\",\n\t\t\t\tSubsystem: \"server\",\n\t\t\t\tName: \"rpc\",\n\t\t\t\tHelp: \"Number of current server RPC requests.\",\n\t\t\t},\n\t\t\t[]string{\"service\", \"method\"},\n\t\t),\n\n\t\trpcTotal: prometheus.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"proxy_peer\",\n\t\t\t\tSubsystem: \"server\",\n\t\t\t\tName: \"rpc_total\",\n\t\t\t\tHelp: \"Total number of server RPC requests.\",\n\t\t\t},\n\t\t\t[]string{\"service\", \"method\", \"code\"},\n\t\t),\n\n\t\trpcDuration: prometheus.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"proxy_peer\",\n\t\t\t\tSubsystem: \"server\",\n\t\t\t\tName: \"rpc_duration_seconds\",\n\t\t\t\tHelp: \"Duration in seconds of RPCs sent by the server.\",\n\t\t\t},\n\t\t\t[]string{\"service\", \"handler\", \"code\"},\n\t\t),\n\n\t\tmessageSent: prometheus.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"proxy_peer\",\n\t\t\t\tSubsystem: \"server\",\n\t\t\t\tName: \"message_sent_size\",\n\t\t\t\tHelp: \"Size of messages sent by the server.\",\n\t\t\t\tBuckets: messageByteBuckets,\n\t\t\t},\n\t\t\t[]string{\"service\", \"handler\"},\n\t\t),\n\n\t\tmessageReceived: prometheus.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"proxy_peer\",\n\t\t\t\tSubsystem: \"server\",\n\t\t\t\tName: \"message_received_size\",\n\t\t\t\tHelp: \"Size of messages received by the server.\",\n\t\t\t\tBuckets: messageByteBuckets,\n\t\t\t},\n\t\t\t[]string{\"service\", \"handler\"},\n\t\t),\n\t}\n\n\tif err := metrics.RegisterPrometheusCollectors(\n\t\tsm.connections,\n\t\tsm.rpcs,\n\t\tsm.rpcTotal,\n\t\tsm.rpcDuration,\n\t\tsm.messageSent,\n\t\tsm.messageReceived,\n\t); err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\treturn sm, nil\n}", "func setupMetrics(mf monitoring.MetricFactory) {\n\tif mf == nil {\n\t\tmf = monitoring.InertMetricFactory{}\n\t}\n\tknownSourceLogs = mf.NewGauge(\"known_logs\", \"Set to 1 for known source logs\", \"logname\")\n\treadsCounter = mf.NewCounter(\"log_reads\", \"Number of source log read requests\", \"logname\")\n\treadErrorsCounter = mf.NewCounter(\"log_read_errors\", \"Number of source log read errors\", \"logname\")\n\tlastSeenSTHTimestamp = mf.NewGauge(\"last_seen_sth_timestamp\", \"Time of last seen STH in ms since epoch\", \"logname\")\n\tlastSeenSTHTreeSize = mf.NewGauge(\"last_seen_sth_treesize\", \"Size of tree at last seen STH\", \"logname\")\n\tlastRecordedSTHTimestamp = mf.NewGauge(\"last_recorded_sth_timestamp\", \"Time of last recorded STH in ms since epoch\", \"logname\")\n\tlastRecordedSTHTreeSize = mf.NewGauge(\"last_recorded_sth_treesize\", \"Size of tree at last recorded STH\", \"logname\")\n\n\tdestPureHub = mf.NewGauge(\"dest_pure_hub\", \"Set to for known destination hubs\", \"hubname\")\n\twritesCounter = mf.NewCounter(\"hub_writes\", \"Number of destination hub submissions\", \"hubname\")\n\twriteErrorsCounter = mf.NewCounter(\"hub_write_errors\", \"Number of destination hub submission errors\", \"hubname\")\n}", "func ExposeMetricsPort() {\n\thttp.Handle(\"/\"+k8sutil.PrometheusMetricsPortName, promhttp.Handler())\n\tgo http.ListenAndServe(\":\"+strconv.Itoa(k8sutil.PrometheusMetricsPort), nil)\n\n\tservice, err := k8sutil.InitOperatorService()\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Failed to init operator service: %v\", err)\n\t}\n\terr = Create(service)\n\tif err != nil && !errors.IsAlreadyExists(err) {\n\t\tlogrus.Infof(\"Failed to create operator service: %v\", err)\n\t\treturn\n\t}\n\tlogrus.Infof(\"Metrics service %s created\", service.Name)\n}", "func pushMetrics(producer *sarama.Producer, mode string) {\n\n\t// The list of metrics we want to filter out of the total stats dump from haproxy\n\twantedMetrics := []string{ \"Scur\", \"Qcur\",\"Smax\",\"Slim\",\"Weight\",\"Qtime\",\"Ctime\",\"Rtime\",\"Ttime\",\"Req_rate\",\"Req_rate_max\",\"Req_tot\",\"Rate\",\"Rate_lim\",\"Rate_max\" }\n\n\t// get metrics every second, for ever.\n\tfor {\n\n\t\t\tstats, _ := GetStats(\"all\")\n\t\t localTime := int64(time.Now().Unix())\n\n\n\t\t// for each proxy in the stats dump, pick out the wanted metrics, parse them and send 'm to Kafka\n\t\t\tfor _,proxy := range stats {\n\n\t\t\t\t// filter out the metrics for haproxy's own stats page\n\t\t\t\tif (proxy.Pxname != \"stats\") {\n\n\t\t\t\t\t// loop over all wanted metrics for the current proxy\n\t\t\t\t\tfor _,metric := range wantedMetrics {\n\n\t\t\t\t\t\tfullMetricName := proxy.Pxname + \".\" + strings.ToLower(proxy.Svname) + \".\" + strings.ToLower(metric)\n\t\t\t\t\t\tfield := reflect.ValueOf(proxy).FieldByName(metric).String()\n\t\t\t\t\t\tif (field != \"\") {\n\n\t\t\t\t\t\t\tmetricValue,_ := strconv.Atoi(field)\n\n\t\t\t\t\t\t\tmetricObj := Metric{fullMetricName, metricValue, localTime}\n\t\t\t\t\t\t\tjsonObj, _ := json.MarshalIndent(metricObj, \"\", \" \")\n\n\t\t\t\t\t\t\terr := producer.SendMessage(mode+\".\"+\"all\", sarama.StringEncoder(\"lbmetrics\"), sarama.StringEncoder(jsonObj))\n\t\t\t\t\t\t\tif err != nil {\n\n\t\t\t\t\t\t\t\tlog.Error(\"Error sending message to Kafka \" + err.Error())\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tlog.Debug(\"Successfully sent message to Kafka on topic: \" + mode + \".\" + \"all\")\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\ttime.Sleep(3000 * time.Millisecond)\n\t}\n}", "func metricsFunction(name, spec string) accesslog.AuditFunction {\n\n\tvar meters []meter\n\n\tspcs := strings.Split(spec, \",\")\n\tfor _, spc := range spcs {\n\t\tmatched_ddd, _ := regexp.MatchString(\"\\\\d\\\\d\\\\d\", spc)\n\t\tmatched_dxx, _ := regexp.MatchString(\"\\\\d[xX]{2}\", spc)\n\t\tswitch {\n\t\tcase spc == \"time\":\n\t\t\tlog.DEBUG(\"Creating time metric\")\n\t\t\tmeter := metric.RegisterTimer(name + \".resp-time\")\n\t\t\tmeters = append(meters, &time_meter{meter: meter})\n\t\tcase spc == \"size\":\n\t\t\tlog.DEBUG(\"Creating size metric\")\n\t\t\tmeter := metric.RegisterHistogram(name + \".resp-size\")\n\t\t\tmeters = append(meters, &size_meter{meter: meter})\n\t\tcase matched_ddd:\n\t\t\ti, _ := strconv.Atoi(spc)\n\t\t\tlog.DEBUG(\"Creating status metric\", \"code\", spc)\n\t\t\tmeter := metric.RegisterCounter(name + \".code.\" + spc)\n\t\t\tmeters = append(meters, &status_meter{test: exactCodeTest(i), meter: meter})\n\t\tcase matched_dxx:\n\t\t\ti, _ := strconv.Atoi(spc[0:1])\n\t\t\tlog.DEBUG(\"Creating status metric\", \"code\", spc)\n\t\t\tmeter := metric.RegisterCounter(name + \".code.\" + spc)\n\t\t\tmeters = append(meters, &status_meter{test: rangeCodeTest(i * 100), meter: meter})\n\t\t}\n\t}\n\n\treturn accesslog.AuditFunction(func(rec rrwriter.RecordingResponseWriter) {\n\t\tfor _, mt := range meters {\n\t\t\tmt.Measure(rec)\n\t\t}\n\t})\n}", "func NewMetrics(scope tally.Scope) *Metrics {\n\tsuccessScope := scope.Tagged(map[string]string{\"result\": \"success\"})\n\tfailScope := scope.Tagged(map[string]string{\"result\": \"fail\"})\n\ttimeoutScope := scope.Tagged(map[string]string{\"result\": \"timeout\"})\n\tapiScope := scope.SubScope(\"api\")\n\tserverScope := scope.SubScope(\"server\")\n\tplacement := scope.SubScope(\"placement\")\n\trecovery := scope.SubScope(\"recovery\")\n\n\treturn &Metrics{\n\t\tAPIEnqueueGangs: apiScope.Counter(\"enqueue_gangs\"),\n\t\tEnqueueGangSuccess: successScope.Counter(\"enqueue_gang\"),\n\t\tEnqueueGangFail: failScope.Counter(\"enqueue_gang\"),\n\n\t\tAPIDequeueGangs: apiScope.Counter(\"dequeue_gangs\"),\n\t\tDequeueGangSuccess: successScope.Counter(\"dequeue_gangs\"),\n\t\tDequeueGangTimeout: timeoutScope.Counter(\"dequeue_gangs\"),\n\n\t\tAPIGetPreemptibleTasks: apiScope.Counter(\"get_preemptible_tasks\"),\n\t\tGetPreemptibleTasksSuccess: successScope.Counter(\"get_preemptible_tasks\"),\n\t\tGetPreemptibleTasksTimeout: timeoutScope.Counter(\"get_preemptible_tasks\"),\n\n\t\tAPISetPlacements: apiScope.Counter(\"set_placements\"),\n\t\tSetPlacementSuccess: successScope.Counter(\"set_placements\"),\n\t\tSetPlacementFail: failScope.Counter(\"set_placements\"),\n\n\t\tAPIGetPlacements: apiScope.Counter(\"get_placements\"),\n\t\tGetPlacementSuccess: successScope.Counter(\"get_placements\"),\n\t\tGetPlacementFail: failScope.Counter(\"get_placements\"),\n\n\t\tAPILaunchedTasks: apiScope.Counter(\"launched_tasks\"),\n\n\t\tRecoverySuccess: successScope.Counter(\"recovery\"),\n\t\tRecoveryFail: failScope.Counter(\"recovery\"),\n\t\tRecoveryRunningSuccessCount: successScope.Counter(\"task_count\"),\n\t\tRecoveryRunningFailCount: failScope.Counter(\"task_count\"),\n\t\tRecoveryEnqueueFailedCount: failScope.Counter(\"enqueue_task_count\"),\n\t\tRecoveryEnqueueSuccessCount: successScope.Counter(\"enqueue_task_count\"),\n\t\tRecoveryTimer: recovery.Timer(\"running_tasks\"),\n\n\t\tPlacementQueueLen: placement.Gauge(\"placement_queue_length\"),\n\t\tPlacementFailed: placement.Counter(\"fail\"),\n\n\t\tElected: serverScope.Gauge(\"elected\"),\n\t}\n}", "func (m *Metrics) start() error {\n\tm.once.Do(func() {\n\t\tm.define(\"\")\n\n\t\tprometheus.MustRegister(requestCount)\n\t\tprometheus.MustRegister(requestDuration)\n\t\tprometheus.MustRegister(responseLatency)\n\t\tprometheus.MustRegister(responseSize)\n\t\tprometheus.MustRegister(responseStatus)\n\n\t\tif !m.UseCaddyAddr {\n\t\t\thttp.Handle(m.Path, m.handler)\n\t\t\tgo func() {\n\t\t\t\terr := http.ListenAndServe(m.Addr, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\tm.logger.Error(\"start prometheus handler\", zap.Error(err))\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t})\n\treturn nil\n}", "func (mw BaseMetrics) GenerateMetrics(begin time.Time, module, method, action string, err error) {\n\t// converting difference to milliseconds\n\tmilliseconds := time.Since(begin).Seconds() * 1e3\n\n\t// general latency\n\tmw.metrics.Gauge(\n\t\tmw.metMap[\"latency\"],\n\t\t// value\n\t\tmilliseconds,\n\t\t// tags\n\t\t[]string{mw.getTag(\"module\", module)},\n\t\tmw.rate,\n\t)\n\t// general request\n\tmw.metrics.Count(\n\t\tfmt.Sprintf(mw.metMap[\"request\"], mw.getStatus(err)),\n\t\t// value\n\t\t1,\n\t\t// tags\n\t\t[]string{mw.getTag(\"module\", module)},\n\t\tmw.rate,\n\t)\n\t// spacific latency\n\tmw.metrics.Gauge(\n\t\tfmt.Sprintf(mw.metMap[\"mLatency\"], module),\n\t\t// value\n\t\tmilliseconds,\n\t\t// tags\n\t\t[]string{mw.getTag(\"action\", action)},\n\t\tmw.rate,\n\t)\n\t// specific request\n\tmw.metrics.Count(\n\t\tfmt.Sprintf(mw.metMap[\"mRequest\"], module, mw.getStatus(err)),\n\t\t// value\n\t\t1,\n\t\t// tags\n\t\t[]string{mw.getTag(\"action\", action)},\n\t\tmw.rate,\n\t)\n}", "func (c *PrometheusCollector) Update(r metricCollector.MetricResult) {\n\tc.RWMutex.Lock()\n\tdefer c.RWMutex.Unlock()\n\n\t// check circuit open\n\tif r.Successes > 0 {\n\t\tgauge := c.gauges[metricCircuitOpen]\n\t\tgauge.Set(0)\n\n\t\tcounter := c.counters[metricSuccesses]\n\t\tcounter.Add(r.Successes)\n\t}\n\tif r.ShortCircuits > 0 {\n\t\tgauge := c.gauges[metricCircuitOpen]\n\t\tgauge.Set(1)\n\n\t\tcounter := c.counters[metricShortCircuits]\n\t\tcounter.Add(r.ShortCircuits)\n\t}\n\t// update metric\n\tif r.Attempts > 0 {\n\t\tcounter := c.counters[metricAttempts]\n\t\tcounter.Add(r.Attempts)\n\t}\n\tif r.Errors > 0 {\n\t\tcounter := c.counters[metricErrors]\n\t\tcounter.Add(r.Errors)\n\t}\n\tif r.Failures > 0 {\n\t\tcounter := c.counters[metricFailures]\n\t\tcounter.Add(r.Failures)\n\t}\n\tif r.Rejects > 0 {\n\t\tcounter := c.counters[metricRejects]\n\t\tcounter.Add(r.Rejects)\n\t}\n\tif r.Timeouts > 0 {\n\t\tcounter := c.counters[metricTimeouts]\n\t\tcounter.Add(r.Timeouts)\n\t}\n\tif r.FallbackSuccesses > 0 {\n\t\tcounter := c.counters[metricFallbackSuccesses]\n\t\tcounter.Add(r.FallbackSuccesses)\n\t}\n\tif r.FallbackFailures > 0 {\n\t\tcounter := c.counters[metricFallbackFailures]\n\t\tcounter.Add(r.FallbackFailures)\n\t}\n\n\tgauge := c.gauges[metricTotalDuration]\n\tgauge.Set(r.TotalDuration.Seconds())\n\n\tgauge = c.gauges[metricRunDuration]\n\tgauge.Set(r.RunDuration.Seconds())\n\n\tgauge = c.gauges[metricConcurrencyInUse]\n\tgauge.Set(r.ConcurrencyInUse)\n}", "func addMetrics(ctx context.Context, cl crclient.Client, cfg *rest.Config) error {\n\tfoundService := &corev1.Service{}\n\tservice, err := opmetrics.GenerateService(metricsPort, \"http-metrics\", OperatorName+\"-metrics\", ManagedVeleroOperatorNamespace, map[string]string{\"name\": OperatorName})\n\tservice.Spec.SessionAffinity = corev1.ServiceAffinityNone // Set session affinity to None (default)\n\tservice.Spec.Type = corev1.ServiceTypeClusterIP // Set service type to ClusterIP (default)\n\tif err != nil {\n\t\tlog.Error(err, \"Could not generate metrics service\")\n\t\treturn err\n\t}\n\tif err = cl.Get(ctx, crclient.ObjectKeyFromObject(service), foundService); err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\t// Didn't find metrics service, so create it\n\t\t\tlog.Info(\"Creating metrics service\")\n\t\t\tif err = cl.Create(ctx, service); err != nil {\n\t\t\t\tlog.Error(err, \"Could not create metrics service\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Error(err, \"Could not get existing metrics service\")\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// Service exists, check if it's updated.\n\t\t// Note: We leave fields related to cluster IP address, IPv6, and\n\t\t// InternalTrafficPolicy alone.\n\t\tservice.Spec.ClusterIP = foundService.Spec.ClusterIP\n\t\tservice.Spec.ClusterIPs = foundService.Spec.ClusterIPs\n\t\tservice.Spec.IPFamilies = foundService.Spec.IPFamilies\n\t\tservice.Spec.IPFamilyPolicy = foundService.Spec.IPFamilyPolicy\n\t\tservice.Spec.InternalTrafficPolicy = foundService.Spec.InternalTrafficPolicy\n\t\tif !reflect.DeepEqual(foundService.Spec, service.Spec) {\n\t\t\t// Specs aren't equal, update and fix.\n\t\t\tlog.Info(\"Updating metrics service\", \"foundService.Spec\", foundService.Spec, \"service.Spec\", service.Spec)\n\t\t\tfoundService.Spec = *service.Spec.DeepCopy()\n\t\t\tif err = cl.Update(ctx, foundService); err != nil {\n\t\t\t\tlog.Error(err, \"Could not update metrics service\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tfoundServiceMonitor := &monitoringv1.ServiceMonitor{}\n\tserviceMonitor := opmetrics.GenerateServiceMonitor(service)\n\tif err = cl.Get(ctx, crclient.ObjectKeyFromObject(serviceMonitor), foundServiceMonitor); err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\t// Didn't find service monitor, so create it\n\t\t\tlog.Info(\"Creating service monitor\")\n\t\t\tif err = cl.Create(ctx, serviceMonitor); err != nil {\n\t\t\t\tlog.Error(err, \"Could not create service monitor\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Error(err, \"Could not get existing service monitor\")\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// ServiceMonitor exists, check if it's updated.\n\t\tif !reflect.DeepEqual(foundServiceMonitor.Spec, serviceMonitor.Spec) {\n\t\t\t// Specs aren't equal, update and fix.\n\t\t\tlog.Info(\"Updating service monitor\", \"foundServiceMonitor.Spec\", foundServiceMonitor.Spec, \"serviceMonitor.Spec\", serviceMonitor.Spec)\n\t\t\tfoundServiceMonitor.Spec = *serviceMonitor.Spec.DeepCopy()\n\t\t\tif err = cl.Update(ctx, foundServiceMonitor); err != nil {\n\t\t\t\tlog.Error(err, \"Could not update service monitor\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func MetricsMiddleware(svc exapp.Service, counter metrics.Counter, latency metrics.Histogram) exapp.Service {\n\treturn &metricsMiddleware{\n\t\tcounter: counter,\n\t\tlatency: latency,\n\t\tsvc: svc,\n\t}\n}", "func calculateMetrics(ctl *controller) error {\n\taipcMetrics, err := ctl.api.GetAppInstancesPerChannelMetrics()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get app instances per channel metrics: %w\", err)\n\t}\n\n\tfor _, metric := range aipcMetrics {\n\t\tappInstancePerChannelGaugeMetric.WithLabelValues(metric.ApplicationName, metric.Version, metric.ChannelName).Set(float64(metric.InstancesCount))\n\t}\n\n\tfuMetrics, err := ctl.api.GetFailedUpdatesMetrics()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get failed update metrics: %w\", err)\n\t}\n\n\tfor _, metric := range fuMetrics {\n\t\tfailedUpdatesGaugeMetric.WithLabelValues(metric.ApplicationName).Set(float64(metric.FailureCount))\n\t}\n\n\treturn nil\n}", "func Metrics(ctx Ctx, addr netx.Addr, reg *prometheus.Registry) error {\n\tmux := http.NewServeMux()\n\tHandleMetrics(mux, reg)\n\treturn HTTP(ctx, addr, nil, mux, \"Prometheus metrics\")\n}", "func InitMetrics(client kubernetes.Interface, scrapeInterval time.Duration) http.Handler {\n\tm := metrics{\n\t\tk8sGardenClient: client,\n\t\tinterval: scrapeInterval,\n\t}\n\tm.initShootMetrics()\n\tm.initProjectCountMetric()\n\tm.initUserCountMetric()\n\treturn promhttp.Handler()\n}", "func requestMetrics(l *log.Logger) service {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tstart := time.Now()\n\t\t\th.ServeHTTP(w, r)\n\t\t\tl.Printf(\"%s request to %s took %vns.\", r.Method, r.URL.Path, time.Since(start).Nanoseconds())\n\t\t})\n\t}\n}", "func (m *metrics) RegisterWithPrometheus() {\n\tm.configLoads = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tNamespace: applicationName,\n\t\t\tName: \"config_table_loads_total\",\n\t\t\tHelp: \"Total sum of listener/route/cluster table loads.\",\n\t\t}, []string{\"resource\"})\n\tprometheus.MustRegister(m.configLoads)\n\n\tm.connectInfoFailures = prometheus.NewCounter(\n\t\tprometheus.CounterOpts{\n\t\t\tNamespace: applicationName,\n\t\t\tName: \"connection_info_failures_total\",\n\t\t\tHelp: \"Total number of connection info failures.\",\n\t\t})\n\tprometheus.MustRegister(m.connectInfoFailures)\n\n\tm.requestsPerCountry = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tNamespace: applicationName,\n\t\t\tName: \"requests_percountry_total\",\n\t\t\tHelp: \"Total number of requests per country.\",\n\t\t}, []string{\"country\"})\n\tprometheus.MustRegister(m.requestsPerCountry)\n\n\tm.requestsApikeyNotFound = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tNamespace: applicationName,\n\t\t\tName: \"requests_apikey_notfound_total\",\n\t\t\tHelp: \"Total number of requests with an unknown apikey.\",\n\t\t}, []string{\"hostname\", \"protocol\", \"method\"})\n\tprometheus.MustRegister(m.requestsApikeyNotFound)\n\n\tm.requestsAccepted = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tNamespace: applicationName,\n\t\t\tName: \"requests_accepted_total\",\n\t\t\tHelp: \"Total number of requests accepted.\",\n\t\t}, []string{\"hostname\", \"protocol\", \"method\", \"apiproduct\"})\n\tprometheus.MustRegister(m.requestsAccepted)\n\n\tm.requestsRejected = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tNamespace: applicationName,\n\t\t\tName: \"requests_rejected_total\",\n\t\t\tHelp: \"Total number of requests rejected.\",\n\t\t}, []string{\"hostname\", \"protocol\", \"method\", \"apiproduct\"})\n\tprometheus.MustRegister(m.requestsRejected)\n\n\tm.authLatencyHistogram = prometheus.NewSummary(\n\t\tprometheus.SummaryOpts{\n\t\t\tNamespace: applicationName,\n\t\t\tName: \"request_latency\",\n\t\t\tHelp: \"Authentication latency in seconds.\",\n\t\t\tObjectives: map[float64]float64{\n\t\t\t\t0.5: 0.05, 0.9: 0.01, 0.99: 0.001, 0.999: 0.0001,\n\t\t\t},\n\t\t})\n\tprometheus.MustRegister(m.authLatencyHistogram)\n\n\tm.Policy = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tNamespace: applicationName,\n\t\t\tName: \"policy_hits_total\",\n\t\t\tHelp: \"Total number of policy hits.\",\n\t\t}, []string{\"scope\", \"policy\"})\n\tprometheus.MustRegister(m.Policy)\n\n\tm.PolicyUnknown = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tNamespace: applicationName,\n\t\t\tName: \"policy_unknown_total\",\n\t\t\tHelp: \"Total number of unknown policy hits.\",\n\t\t}, []string{\"scope\", \"policy\"})\n\tprometheus.MustRegister(m.PolicyUnknown)\n}", "func NewMetrics() *Metrics {\n\treturn &Metrics{\n\t\tInputBytesTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_input_bytes_total\",\n\t\t\t\tHelp: \"Total number of bytes received\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tOutputBytesTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_output_bytes_total\",\n\t\t\t\tHelp: \"Total number of bytes sent.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tInputPacketsTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_input_pkts_total\",\n\t\t\t\tHelp: \"Total number of packets received\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tOutputPacketsTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_output_pkts_total\",\n\t\t\t\tHelp: \"Total number of packets sent.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tDroppedPacketsTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_dropped_pkts_total\",\n\t\t\t\tHelp: \"Total number of packets dropped by the router. This metric reports \" +\n\t\t\t\t\t\"the number of packets that were dropped because of errors.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tInterfaceUp: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tName: \"router_interface_up\",\n\t\t\t\tHelp: \"Either zero or one depending on whether the interface is up.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tBFDInterfaceStateChanges: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_state_changes_total\",\n\t\t\t\tHelp: \"Total number of BFD state changes.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tBFDPacketsSent: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_sent_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets sent.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tBFDPacketsReceived: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_received_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets received.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tServiceInstanceCount: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tName: \"router_service_instance_count\",\n\t\t\t\tHelp: \"Number of service instances known by the data plane.\",\n\t\t\t},\n\t\t\t[]string{\"service\", \"isd_as\"},\n\t\t),\n\t\tServiceInstanceChanges: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_service_instance_changes_total\",\n\t\t\t\tHelp: \"Number of total service instance changes. Both addition and removal of a \" +\n\t\t\t\t\t\"service instance is accumulated.\",\n\t\t\t},\n\t\t\t[]string{\"service\", \"isd_as\"},\n\t\t),\n\t\tSiblingReachable: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tName: \"router_sibling_reachable\",\n\t\t\t\tHelp: \"Either zero or one depending on whether a sibling router \" +\n\t\t\t\t\t\"instance is reachable.\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t\tSiblingBFDPacketsSent: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_sent_sibling_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets sent to sibling router instance.\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t\tSiblingBFDPacketsReceived: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_received_sibling_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets received from sibling router instance.\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t\tSiblingBFDStateChanges: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_sibling_state_changes_total\",\n\t\t\t\tHelp: \"Total number of BFD state changes for sibling router instances\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t}\n}", "func WithMetricsResponderMiddleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == http.MethodGet && r.URL.Path == \"/metrics\" {\n\t\t\tpromhttp.Handler().ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func PrometheusMetrics(config *cfg.InstrumentationConfig) *Metrics {\n\tif !config.Prometheus {\n\t\treturn NopMetrics()\n\t}\n\n\tbondedTokenVec := stdprometheus.NewGaugeVec(stdprometheus.GaugeOpts{\n\t\tNamespace: config.Namespace,\n\t\tSubsystem: MetricsSubsystem,\n\t\tName: \"bonded_token\",\n\t\tHelp: \"bonded token\",\n\t}, []string{\"validator_address\"})\n\n\tloosenTokenVec := stdprometheus.NewGaugeVec(stdprometheus.GaugeOpts{\n\t\tNamespace: config.Namespace,\n\t\tSubsystem: MetricsSubsystem,\n\t\tName: \"loosen_token\",\n\t\tHelp: \"loosen token\",\n\t}, []string{})\n\n\tburnedTokenVec := stdprometheus.NewGaugeVec(stdprometheus.GaugeOpts{\n\t\tNamespace: config.Namespace,\n\t\tSubsystem: MetricsSubsystem,\n\t\tName: \"burned_token\",\n\t\tHelp: \"burned token\",\n\t}, []string{})\n\n\tslashedTokenVec := stdprometheus.NewCounterVec(stdprometheus.CounterOpts{\n\t\tNamespace: config.Namespace,\n\t\tSubsystem: MetricsSubsystem,\n\t\tName: \"slashed_token\",\n\t\tHelp: \"slashed token\",\n\t}, []string{\"validator_address\"})\n\n\tjailedVec := stdprometheus.NewGaugeVec(stdprometheus.GaugeOpts{\n\t\tNamespace: config.Namespace,\n\t\tSubsystem: MetricsSubsystem,\n\t\tName: \"jailed\",\n\t\tHelp: \"jailed\",\n\t}, []string{\"validator_address\"})\n\n\tpowerVec := stdprometheus.NewGaugeVec(stdprometheus.GaugeOpts{\n\t\tNamespace: config.Namespace,\n\t\tSubsystem: MetricsSubsystem,\n\t\tName: \"power\",\n\t\tHelp: \"power\",\n\t}, []string{\"validator_address\"})\n\n\tpromutil.RegisterMetrics(bondedTokenVec, loosenTokenVec, burnedTokenVec, slashedTokenVec, jailedVec, powerVec)\n\n\treturn &Metrics{\n\t\tBondedToken: prometheus.NewGauge(bondedTokenVec),\n\t\tLoosenToken: prometheus.NewGauge(loosenTokenVec),\n\t\tBurnedToken: prometheus.NewGauge(burnedTokenVec),\n\t\tSlashedToken: prometheus.NewCounter(slashedTokenVec),\n\t\tJailed: prometheus.NewGauge(jailedVec),\n\t\tPower: prometheus.NewGauge(powerVec),\n\t}\n}", "func serveMetrics(w http.ResponseWriter, r *http.Request) {\n\tvar state []byte\n\tvar stateCode int\n\tvar dev string\n\tfmt.Fprintf(w, \"# metric values: 1 - clean, 0 - degraded\\n\")\n\tfor _, file := range mdFiles {\n\t\tstate, _ = ioutil.ReadFile(fmt.Sprintf(\"%s/md/array_state\", file))\n\t\tdev = filepath.Base(file)\n\t\tif strings.TrimSpace(string(state)) == \"clean\" {\n\t\t\tstateCode = 1\n\t\t} else {\n\t\t\tstateCode = 0\n\t\t}\n\t\tfmt.Fprintf(w, \"md_state{host=\\\"%s\\\",dev=\\\"%s\\\"} %d\\n\", host, dev, stateCode)\n\t}\n}", "func newMetrics(hostAndPort string) *metrics {\n\tm := metrics{\n\t\tmetricsCh: make(chan metricType),\n\t\thostAndPort: hostAndPort,\n\t}\n\n\treturn &m\n}", "func (km *KataMonitor) ProcessMetricsRequest(w http.ResponseWriter, r *http.Request) {\n\tstart := time.Now()\n\n\tscrapeCount.Inc()\n\tdefer func() {\n\t\tscrapeDurationsHistogram.Observe(float64(time.Since(start).Nanoseconds() / int64(time.Millisecond)))\n\t}()\n\n\t// this is likely the same as `kata-runtime metrics <SANDBOX>`.\n\tsandboxID, err := getSandboxIDFromReq(r)\n\tif err == nil && sandboxID != \"\" {\n\t\tmetrics, err := GetSandboxMetrics(sandboxID)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tw.Write([]byte(err.Error()))\n\t\t\treturn\n\t\t}\n\t\tw.Write([]byte(metrics))\n\t\treturn\n\t}\n\n\t// if no sandbox provided, will get all sandbox's metrics.\n\n\t// prepare writer for writing response.\n\tcontentType := expfmt.Negotiate(r.Header)\n\n\t// set response header\n\theader := w.Header()\n\theader.Set(contentTypeHeader, string(contentType))\n\n\t// create writer\n\twriter := io.Writer(w)\n\tif mutils.GzipAccepted(r.Header) {\n\t\theader.Set(contentEncodingHeader, \"gzip\")\n\t\tgz := gzipPool.Get().(*gzip.Writer)\n\t\tdefer gzipPool.Put(gz)\n\n\t\tgz.Reset(w)\n\t\tdefer gz.Close()\n\n\t\twriter = gz\n\t}\n\n\t// create encoder to encode metrics.\n\tencoder := expfmt.NewEncoder(writer, contentType)\n\n\t// gather metrics collected for management agent.\n\tmfs, err := prometheus.DefaultGatherer.Gather()\n\tif err != nil {\n\t\tmonitorLog.WithError(err).Error(\"failed to Gather metrics from prometheus.DefaultGatherer\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\t// encode metric gathered in current process\n\tif err := encodeMetricFamily(mfs, encoder); err != nil {\n\t\tmonitorLog.WithError(err).Warnf(\"failed to encode metrics\")\n\t}\n\n\t// aggregate sandboxes metrics and write to response by encoder\n\tif err := km.aggregateSandboxMetrics(encoder); err != nil {\n\t\tmonitorLog.WithError(err).Errorf(\"failed aggregateSandboxMetrics\")\n\t\tscrapeFailedCount.Inc()\n\t}\n}", "func addMetricsRoute(opts server.Options, app *fiber.App) {\n\tif opts.MetricsEnable {\n\t\tmetricPath := opts.MetricsAPI\n\t\tif metricPath == \"\" {\n\t\t\tmetricPath = \"metrics\"\n\t\t}\n\t\tif !strings.HasPrefix(metricPath, \"/\") {\n\t\t\tmetricPath = \"/\" + metricPath\n\t\t}\n\t\topenlog.Info(\"Enabled metrics API on \" + metricPath)\n\t\tapp.Get(metricPath, adaptor.HTTPHandler(prometheusHandleFunc()))\n\t}\n}", "func (n *RouterNode) GatherMetrics() {\n\tn.Lock()\n\tdefer n.Unlock()\n\n\tlevel.Debug(n.logger).Log(\n\t\t\"msg\", \"GatherMetrics() locked\",\n\t)\n\n\tif time.Now().Unix() < n.nextCollectionTicker {\n\t\treturn\n\t}\n\tstart := time.Now()\n\tif len(n.metrics) > 0 {\n\t\tn.metrics = n.metrics[:0]\n\t\tlevel.Debug(n.logger).Log(\n\t\t\t\"msg\", \"GatherMetrics() cleared metrics\",\n\t\t)\n\t}\n\tupValue := 1\n\n\t// What is RouterID and AS number of this GoBGP server?\n\tserver, err := n.client.GetBgp(context.Background(), &gobgpapi.GetBgpRequest{})\n\tif err != nil {\n\t\tn.IncrementErrorCounter()\n\t\tlevel.Error(n.logger).Log(\n\t\t\t\"msg\", \"failed query gobgp server\",\n\t\t\t\"error\", err.Error(),\n\t\t)\n\t\tif IsConnectionError(err) {\n\t\t\tn.connected = false\n\t\t\tupValue = 0\n\t\t}\n\t} else {\n\t\tn.routerID = server.Global.RouterId\n\t\tn.localAS = server.Global.Asn\n\t\tlevel.Debug(n.logger).Log(\n\t\t\t\"msg\", \"router info\",\n\t\t\t\"router_id\", n.routerID,\n\t\t\t\"local_asn\", n.localAS,\n\t\t)\n\t\tn.connected = true\n\t}\n\n\tif n.connected {\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(2)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tn.GetRibCounters()\n\t\t}()\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tn.GetPeers()\n\t\t}()\n\t\twg.Wait()\n\n\t}\n\n\t// Generic Metrics\n\tn.metrics = append(n.metrics, prometheus.MustNewConstMetric(\n\t\trouterUp,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(upValue),\n\t))\n\n\tn.metrics = append(n.metrics, prometheus.MustNewConstMetric(\n\t\trouterErrors,\n\t\tprometheus.CounterValue,\n\t\tfloat64(n.errors),\n\t))\n\tn.metrics = append(n.metrics, prometheus.MustNewConstMetric(\n\t\trouterNextScrape,\n\t\tprometheus.CounterValue,\n\t\tfloat64(n.nextCollectionTicker),\n\t))\n\tn.metrics = append(n.metrics, prometheus.MustNewConstMetric(\n\t\trouterScrapeTime,\n\t\tprometheus.GaugeValue,\n\t\ttime.Since(start).Seconds(),\n\t))\n\n\t// Router ID and ASN\n\tif n.routerID != \"\" {\n\t\tn.metrics = append(n.metrics, prometheus.MustNewConstMetric(\n\t\t\trouterID,\n\t\t\tprometheus.GaugeValue,\n\t\t\t1,\n\t\t\tn.routerID,\n\t\t))\n\t}\n\tif n.localAS > 0 {\n\t\tn.metrics = append(n.metrics, prometheus.MustNewConstMetric(\n\t\t\trouterLocalAS,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(n.localAS),\n\t\t))\n\t}\n\n\tn.nextCollectionTicker = time.Now().Add(time.Duration(n.pollInterval) * time.Second).Unix()\n\n\tif upValue > 0 {\n\t\tn.result = \"success\"\n\t} else {\n\t\tn.result = \"failure\"\n\t}\n\tn.timestamp = time.Now().Format(time.RFC3339)\n\n\tlevel.Debug(n.logger).Log(\n\t\t\"msg\", \"GatherMetrics() returns\",\n\t)\n}", "func PrometheusMetrics(namespace string, labelsAndValues ...string) *Metrics {\n\tlabels := []string{}\n\tfor i := 0; i < len(labelsAndValues); i += 2 {\n\t\tlabels = append(labels, labelsAndValues[i])\n\t}\n\treturn &Metrics{\n\t\tPeers: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: MetricsSubsystem,\n\t\t\tName: \"peers\",\n\t\t\tHelp: \"Number of peers.\",\n\t\t}, labels).With(labelsAndValues...),\n\t\tPeerReceiveBytesTotal: prometheus.NewCounterFrom(stdprometheus.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: MetricsSubsystem,\n\t\t\tName: \"peer_receive_bytes_total\",\n\t\t\tHelp: \"Number of bytes received from a given peer.\",\n\t\t}, append(labels, \"peer_id\", \"chID\")).With(labelsAndValues...),\n\t\tPeerSendBytesTotal: prometheus.NewCounterFrom(stdprometheus.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: MetricsSubsystem,\n\t\t\tName: \"peer_send_bytes_total\",\n\t\t\tHelp: \"Number of bytes sent to a given peer.\",\n\t\t}, append(labels, \"peer_id\", \"chID\")).With(labelsAndValues...),\n\t\tPeerPendingSendBytes: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: MetricsSubsystem,\n\t\t\tName: \"peer_pending_send_bytes\",\n\t\t\tHelp: \"Number of pending bytes to be sent to a given peer.\",\n\t\t}, append(labels, \"peer_id\")).With(labelsAndValues...),\n\t\tNumTxs: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: MetricsSubsystem,\n\t\t\tName: \"num_txs\",\n\t\t\tHelp: \"Number of transactions submitted by each peer.\",\n\t\t}, append(labels, \"peer_id\")).With(labelsAndValues...),\n\t}\n}", "func callMetrics(metricsAPI *metricsAPI, clock func() time.Time, timingMetrics bool) callrules.Rule {\n\ttimed := metricsAPI.callLatency\n\tif !timingMetrics {\n\t\ttimed = nil\n\t}\n\tharness := xmetrics.NewHarness(metricsAPI.callCount, metricsAPI.callErrorCount, timed, clock)\n\treturn callrules.Metrics(harness, nil)\n}", "func (s *RestServer) getPcieMgrMetricsHandler(r *http.Request) (interface{}, error) {\n\tlog.Infof(\"Got GET request PcieMgrMetrics/%s\", mux.Vars(r)[\"Meta.Name\"])\n\treturn nil, nil\n}", "func (f *FakeVCenter) PushMetrics(context.Context, metrics.Receiver) {}", "func (f *VCenter) PushMetrics(context.Context, metrics.Receiver) {}", "func (b *Basic) EnableMetrics(collector MetricsCollector, updateFreqMillis int64) error {\n\tname := fmt.Sprintf(\"%v\", b)\n\n\tb.mux.Lock()\n\tdefer b.mux.Unlock()\n\n\tb.metrics = true\n\tb.metricsUpdateFreqMillis = updateFreqMillis\n\n\tvar err error\n\n\tif b.queueSizeGauge, err = collector.QueueSizeGauge(name); err != nil {\n\t\treturn err\n\t}\n\tif b.loggedCounter, err = collector.LoggedCounter(name); err != nil {\n\t\treturn err\n\t}\n\tif b.errorCounter, err = collector.ErrorCounter(name); err != nil {\n\t\treturn err\n\t}\n\tif b.droppedCounter, err = collector.DroppedCounter(name); err != nil {\n\t\treturn err\n\t}\n\tif b.blockedCounter, err = collector.BlockedCounter(name); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func NewMetrics(registry metrics.Registry, exchanges []openrtb_ext.BidderName, disableAccountMetrics config.DisabledMetrics, syncerKeys []string, moduleStageNames map[string][]string) *Metrics {\n\tnewMetrics := NewBlankMetrics(registry, exchanges, disableAccountMetrics, moduleStageNames)\n\tnewMetrics.ConnectionCounter = metrics.GetOrRegisterCounter(\"active_connections\", registry)\n\tnewMetrics.TMaxTimeoutCounter = metrics.GetOrRegisterCounter(\"tmax_timeout\", registry)\n\tnewMetrics.ConnectionAcceptErrorMeter = metrics.GetOrRegisterMeter(\"connection_accept_errors\", registry)\n\tnewMetrics.ConnectionCloseErrorMeter = metrics.GetOrRegisterMeter(\"connection_close_errors\", registry)\n\tnewMetrics.ImpMeter = metrics.GetOrRegisterMeter(\"imps_requested\", registry)\n\n\tnewMetrics.ImpsTypeBanner = metrics.GetOrRegisterMeter(\"imp_banner\", registry)\n\tnewMetrics.ImpsTypeVideo = metrics.GetOrRegisterMeter(\"imp_video\", registry)\n\tnewMetrics.ImpsTypeAudio = metrics.GetOrRegisterMeter(\"imp_audio\", registry)\n\tnewMetrics.ImpsTypeNative = metrics.GetOrRegisterMeter(\"imp_native\", registry)\n\n\tnewMetrics.NoCookieMeter = metrics.GetOrRegisterMeter(\"no_cookie_requests\", registry)\n\tnewMetrics.AppRequestMeter = metrics.GetOrRegisterMeter(\"app_requests\", registry)\n\tnewMetrics.DebugRequestMeter = metrics.GetOrRegisterMeter(\"debug_requests\", registry)\n\tnewMetrics.RequestTimer = metrics.GetOrRegisterTimer(\"request_time\", registry)\n\tnewMetrics.DNSLookupTimer = metrics.GetOrRegisterTimer(\"dns_lookup_time\", registry)\n\tnewMetrics.TLSHandshakeTimer = metrics.GetOrRegisterTimer(\"tls_handshake_time\", registry)\n\tnewMetrics.PrebidCacheRequestTimerSuccess = metrics.GetOrRegisterTimer(\"prebid_cache_request_time.ok\", registry)\n\tnewMetrics.PrebidCacheRequestTimerError = metrics.GetOrRegisterTimer(\"prebid_cache_request_time.err\", registry)\n\tnewMetrics.StoredResponsesMeter = metrics.GetOrRegisterMeter(\"stored_responses\", registry)\n\tnewMetrics.OverheadTimer = makeOverheadTimerMetrics(registry)\n\tnewMetrics.BidderServerResponseTimer = metrics.GetOrRegisterTimer(\"bidder_server_response_time_seconds\", registry)\n\n\tfor _, dt := range StoredDataTypes() {\n\t\tfor _, ft := range StoredDataFetchTypes() {\n\t\t\ttimerName := fmt.Sprintf(\"stored_%s_fetch_time.%s\", string(dt), string(ft))\n\t\t\tnewMetrics.StoredDataFetchTimer[dt][ft] = metrics.GetOrRegisterTimer(timerName, registry)\n\t\t}\n\t\tfor _, e := range StoredDataErrors() {\n\t\t\tmeterName := fmt.Sprintf(\"stored_%s_error.%s\", string(dt), string(e))\n\t\t\tnewMetrics.StoredDataErrorMeter[dt][e] = metrics.GetOrRegisterMeter(meterName, registry)\n\t\t}\n\t}\n\n\tnewMetrics.AmpNoCookieMeter = metrics.GetOrRegisterMeter(\"amp_no_cookie_requests\", registry)\n\n\tnewMetrics.CookieSyncMeter = metrics.GetOrRegisterMeter(\"cookie_sync_requests\", registry)\n\tfor _, s := range CookieSyncStatuses() {\n\t\tnewMetrics.CookieSyncStatusMeter[s] = metrics.GetOrRegisterMeter(fmt.Sprintf(\"cookie_sync_requests.%s\", s), registry)\n\t}\n\n\tnewMetrics.SetUidMeter = metrics.GetOrRegisterMeter(\"setuid_requests\", registry)\n\tfor _, s := range SetUidStatuses() {\n\t\tnewMetrics.SetUidStatusMeter[s] = metrics.GetOrRegisterMeter(fmt.Sprintf(\"setuid_requests.%s\", s), registry)\n\t}\n\n\tfor _, syncerKey := range syncerKeys {\n\t\tnewMetrics.SyncerRequestsMeter[syncerKey] = make(map[SyncerCookieSyncStatus]metrics.Meter)\n\t\tfor _, status := range SyncerRequestStatuses() {\n\t\t\tnewMetrics.SyncerRequestsMeter[syncerKey][status] = metrics.GetOrRegisterMeter(fmt.Sprintf(\"syncer.%s.request.%s\", syncerKey, status), registry)\n\t\t}\n\n\t\tnewMetrics.SyncerSetsMeter[syncerKey] = make(map[SyncerSetUidStatus]metrics.Meter)\n\t\tfor _, status := range SyncerSetUidStatuses() {\n\t\t\tnewMetrics.SyncerSetsMeter[syncerKey][status] = metrics.GetOrRegisterMeter(fmt.Sprintf(\"syncer.%s.set.%s\", syncerKey, status), registry)\n\t\t}\n\t}\n\n\tfor _, a := range exchanges {\n\t\tregisterAdapterMetrics(registry, \"adapter\", string(a), newMetrics.AdapterMetrics[a])\n\t}\n\n\tfor typ, statusMap := range newMetrics.RequestStatuses {\n\t\tfor stat := range statusMap {\n\t\t\tstatusMap[stat] = metrics.GetOrRegisterMeter(\"requests.\"+string(stat)+\".\"+string(typ), registry)\n\t\t}\n\t}\n\n\tfor _, cacheRes := range CacheResults() {\n\t\tnewMetrics.StoredReqCacheMeter[cacheRes] = metrics.GetOrRegisterMeter(fmt.Sprintf(\"stored_request_cache_%s\", string(cacheRes)), registry)\n\t\tnewMetrics.StoredImpCacheMeter[cacheRes] = metrics.GetOrRegisterMeter(fmt.Sprintf(\"stored_imp_cache_%s\", string(cacheRes)), registry)\n\t\tnewMetrics.AccountCacheMeter[cacheRes] = metrics.GetOrRegisterMeter(fmt.Sprintf(\"account_cache_%s\", string(cacheRes)), registry)\n\t}\n\n\tnewMetrics.RequestsQueueTimer[\"video\"][true] = metrics.GetOrRegisterTimer(\"queued_requests.video.accepted\", registry)\n\tnewMetrics.RequestsQueueTimer[\"video\"][false] = metrics.GetOrRegisterTimer(\"queued_requests.video.rejected\", registry)\n\n\tnewMetrics.TimeoutNotificationSuccess = metrics.GetOrRegisterMeter(\"timeout_notification.ok\", registry)\n\tnewMetrics.TimeoutNotificationFailure = metrics.GetOrRegisterMeter(\"timeout_notification.failed\", registry)\n\n\tnewMetrics.PrivacyCCPARequest = metrics.GetOrRegisterMeter(\"privacy.request.ccpa.specified\", registry)\n\tnewMetrics.PrivacyCCPARequestOptOut = metrics.GetOrRegisterMeter(\"privacy.request.ccpa.opt-out\", registry)\n\tnewMetrics.PrivacyCOPPARequest = metrics.GetOrRegisterMeter(\"privacy.request.coppa\", registry)\n\tnewMetrics.PrivacyLMTRequest = metrics.GetOrRegisterMeter(\"privacy.request.lmt\", registry)\n\tfor _, version := range TCFVersions() {\n\t\tnewMetrics.PrivacyTCFRequestVersion[version] = metrics.GetOrRegisterMeter(fmt.Sprintf(\"privacy.request.tcf.%s\", string(version)), registry)\n\t}\n\n\tnewMetrics.AdsCertRequestsSuccess = metrics.GetOrRegisterMeter(\"ads_cert_requests.ok\", registry)\n\tnewMetrics.AdsCertRequestsFailure = metrics.GetOrRegisterMeter(\"ads_cert_requests.failed\", registry)\n\tnewMetrics.adsCertSignTimer = metrics.GetOrRegisterTimer(\"ads_cert_sign_time\", registry)\n\n\tfor module, stages := range moduleStageNames {\n\t\tregisterModuleMetrics(registry, module, stages, newMetrics.ModuleMetrics[module])\n\t}\n\n\treturn newMetrics\n}", "func (c config) Metrics(w http.ResponseWriter, r *http.Request) {\n\tvar generated string\n\n\t// Open nft -nn dump file\n\tnftDump, err := os.Open(c.nftOutPath)\n\tif err != nil {\n\t\tklog.Errorf(\"Could not nft export file %s\", c.nftOutPath)\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(\"\"))\n\t\treturn\n\t}\n\tdefer nftDump.Close()\n\n\te, err := nftables.ExtractCounters(nftDump)\n\t// Sth went wrong, could not parse\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(\"\"))\n\t\treturn\n\t}\n\n\t// Iterate over the metrics and generate prometheus readable ones out of it\n\tfor _, metric := range e {\n\t\tgenerated += fmt.Sprintf(\"nft_counter_bytes{comment=\\\"%s\\\"} %d\\n\", metric.Name, metric.Bytes)\n\t\tgenerated += fmt.Sprintf(\"nft_counter_packets{comment=\\\"%s\\\"} %d\\n\", metric.Name, metric.Packets)\n\t}\n\n\tklog.Infof(\"Exported %d counters\", len(e))\n\n\t// Simple af but should be sufficient\n\tw.Write([]byte(generated))\n}", "func Metrics() gorouter.MiddlewareFunc {\n\thasMetrics = true\n\tgoroutines := expvar.NewInt(\"goroutines\")\n\trequests := expvar.NewInt(\"http_requests\")\n\n\tm := func(next http.Handler) http.Handler {\n\t\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t\tnext.ServeHTTP(w, r)\n\n\t\t\t// Increment the request counter.\n\t\t\trequests.Add(1)\n\n\t\t\t// Update the count for the number of active goroutines every 100 requests.\n\t\t\tif requests.Value()%100 == 0 {\n\t\t\t\tgoroutines.Set(int64(runtime.NumGoroutine()))\n\t\t\t}\n\t\t}\n\n\t\treturn http.HandlerFunc(fn)\n\t}\n\n\treturn m\n}", "func Configure(router gin.IRouter, registry *prometheus.Registry) {\n\thandler := promhttp.HandlerFor(registry, promhttp.HandlerOpts{Registry: registry})\n\trouter.GET(\"/metrics\", gin.WrapH(handler))\n}", "func metricsHandler() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tregistry := prometheus.NewRegistry()\n\t\ttarget := r.URL.Query().Get(\"target\")\n\t\tif target == \"\" {\n\t\t\thttp.Error(w, \"'target' parameter must be specified\", 400)\n\t\t\treturn\n\t\t}\n\t\ttargetLoggerCtx := rootLoggerCtx.WithField(\"target\", target)\n\t\ttargetLoggerCtx.Info(\"scraping target host\")\n\n\t\tvar (\n\t\t\thostConfig *HostConfig\n\t\t\terr error\n\t\t\tok bool\n\t\t\tgroup []string\n\t\t)\n\n\t\tgroup, ok = r.URL.Query()[\"group\"]\n\n\t\tif ok && len(group[0]) >= 1 {\n\t\t\t// Trying to get hostConfig from group.\n\t\t\tif hostConfig, err = sc.HostConfigForGroup(group[0]); err != nil {\n\t\t\t\ttargetLoggerCtx.WithError(err).Error(\"error getting credentials\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// Always falling back to single host config when group config failed.\n\t\tif hostConfig == nil {\n\t\t\tif hostConfig, err = sc.HostConfigForTarget(target); err != nil {\n\t\t\t\ttargetLoggerCtx.WithError(err).Error(\"error getting credentials\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tcollector := collector.NewRedfishCollector(target, hostConfig.Username, hostConfig.Password, targetLoggerCtx)\n\t\tregistry.MustRegister(collector)\n\t\tgatherers := prometheus.Gatherers{\n\t\t\tprometheus.DefaultGatherer,\n\t\t\tregistry,\n\t\t}\n\t\t// Delegate http serving to Prometheus client library, which will call collector.Collect.\n\t\th := promhttp.HandlerFor(gatherers, promhttp.HandlerOpts{})\n\t\th.ServeHTTP(w, r)\n\n\t}\n}", "func (c *OrchestratorCollector) Collect(ch chan<- prometheus.Metric) {\n\tc.mutex.Lock() // To protect metrics from concurrent collects\n\tdefer c.mutex.Unlock()\n\n\tstats, err := c.orchestratorClient.GetMetrics()\n\tif err != nil {\n\t\tc.upMetric.Set(serviceDown)\n\t\tch <- c.upMetric\n\t\tlog.Printf(\"Error getting Orchestrator stats: %v\", err)\n\t\treturn\n\t}\n\n\tc.upMetric.Set(serviceUp)\n\tch <- c.upMetric\n\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"cluter_size\"],\n\t\tprometheus.GaugeValue, float64(len(stats.Status.Details.AvailableNodes)))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"is_active_node\"],\n\t\tprometheus.GaugeValue, boolToFloat64(stats.Status.Details.IsActiveNode))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"problems\"],\n\t\tprometheus.GaugeValue, float64(len(stats.Problems)))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"last_failover_id\"],\n\t\tprometheus.CounterValue, float64(stats.LastFailoverID))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"is_healthy\"],\n\t\tprometheus.GaugeValue, boolToFloat64(stats.Status.Details.Healthy))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"failed_seeds\"],\n\t\tprometheus.CounterValue, float64(stats.FailedSeeds))\n}", "func RegisterMetrics() {\n\n\tprometheus.MustRegister(metrics.TiKVBackoffHistogram)\n\tprometheus.MustRegister(metrics.TiKVCoprocessorHistogram)\n\tprometheus.MustRegister(metrics.TiKVLoadSafepointCounter)\n\tprometheus.MustRegister(metrics.TiKVLockResolverCounter)\n\tprometheus.MustRegister(metrics.TiKVRawkvCmdHistogram)\n\tprometheus.MustRegister(metrics.TiKVRawkvSizeHistogram)\n\tprometheus.MustRegister(metrics.TiKVRegionCacheCounter)\n\tprometheus.MustRegister(metrics.TiKVRegionErrorCounter)\n\tprometheus.MustRegister(metrics.TiKVSecondaryLockCleanupFailureCounter)\n\tprometheus.MustRegister(metrics.TiKVSendReqHistogram)\n\tprometheus.MustRegister(metrics.TiKVTxnCmdHistogram)\n\tprometheus.MustRegister(metrics.TiKVTxnRegionsNumHistogram)\n\tprometheus.MustRegister(metrics.TiKVTxnWriteKVCountHistogram)\n\tprometheus.MustRegister(metrics.TiKVTxnWriteSizeHistogram)\n\tprometheus.MustRegister(metrics.TiKVLocalLatchWaitTimeHistogram)\n\tprometheus.MustRegister(metrics.TiKVPendingBatchRequests)\n\tprometheus.MustRegister(metrics.TiKVStatusDuration)\n\tprometheus.MustRegister(metrics.TiKVStatusCounter)\n\tprometheus.MustRegister(metrics.TiKVBatchWaitDuration)\n\tprometheus.MustRegister(metrics.TiKVBatchClientUnavailable)\n\tprometheus.MustRegister(metrics.TiKVRangeTaskStats)\n\tprometheus.MustRegister(metrics.TiKVRangeTaskPushDuration)\n\tprometheus.MustRegister(metrics.TiKVTokenWaitDuration)\n\tprometheus.MustRegister(metrics.TiKVTxnHeartBeatHistogram)\n\tprometheus.MustRegister(metrics.TiKVPessimisticLockKeysDuration)\n\tprometheus.MustRegister(metrics.TiKVTTLLifeTimeReachCounter)\n\tprometheus.MustRegister(metrics.TiKVNoAvailableConnectionCounter)\n\n\tprometheus.MustRegister(TSFutureWaitDuration)\n\n\t// grpc metrics\n\tprometheus.MustRegister(CreateSessionCounter)\n\tprometheus.MustRegister(DeleteSessionCounter)\n\tprometheus.MustRegister(ReadCounter)\n\tprometheus.MustRegister(SparseReadCounter)\n\tprometheus.MustRegister(StreamReadCounter)\n\tprometheus.MustRegister(CommitCounter)\n\tprometheus.MustRegister(MutateCounter)\n\tprometheus.MustRegister(ExecuteMutateDuration)\n\tprometheus.MustRegister(ExecuteReadDuration)\n\n\t// session metrics\n\tprometheus.MustRegister(SessionRetry)\n\tprometheus.MustRegister(SessionCounter)\n\tprometheus.MustRegister(SessionRetryErrorCounter)\n\tprometheus.MustRegister(TransactionCounter)\n\tprometheus.MustRegister(TransactionDuration)\n\tprometheus.MustRegister(SchemaLeaseErrorCounter)\n\n\t//tables metrics\n\tprometheus.MustRegister(FetchRowsCounter)\n\tprometheus.MustRegister(FetchSparseCounter)\n\tprometheus.MustRegister(FetchRowsDuration)\n\tprometheus.MustRegister(FetchSparseDuration)\n\n\tprometheus.MustRegister(ScanSparseCounter)\n\tprometheus.MustRegister(ScanSparseDuration)\n\n\tprometheus.MustRegister(BatchSparseCounter)\n\tprometheus.MustRegister(BatchSparseDuration)\n}", "func UpdateMetrics(result *Results) {\n\n\t// Publish system variables\n\tupTimeGauge.Set(float64(result.SysMonitorInfo.Uptime))\n\tcpuUsageGauge.Set(float64(result.SysMonitorInfo.CpuUsagePercent))\n\n\t// Memory\n\tmemUsagePercentGauge.Set(result.SysMonitorInfo.MemUsagePercent)\n\tmemTotalGauge.Set(float64(result.SysMonitorInfo.MemTotal))\n\tmemAvailableGauge.Set(float64(result.SysMonitorInfo.MemAvailable))\n\n\t// Bandwidth\n\tbandwidthUsageTotalGauge.Set(float64(result.SysMonitorInfo.BandwidthUsageTotal))\n\tbandwidthUsageSentGauge.Set(float64(result.SysMonitorInfo.BandwidthUsageSent))\n\tbandwidthUsageRecvGauge.Set(float64(result.SysMonitorInfo.BandwidthUsageRecv))\n\n\tfor _, driveUsage := range result.SysMonitorInfo.DriveUsage {\n\t\t// \"drive_path\", \"available\", \"growth_rate\", \"full_in\", \"physical_drive\"\n\n\t\tdays := strconv.FormatFloat(driveUsage.DaysTillFull, 'f', 3, 64)\n\n\t\tif math.IsInf(driveUsage.DaysTillFull, 0) {\n\t\t\tdays = \"10 years\"\n\t\t}\n\n\t\tdriveSpace.WithLabelValues(driveUsage.Path,\n\t\t\tstrconv.FormatFloat(driveUsage.PercentUsed, 'f', 3, 64),\n\t\t\tstrconv.FormatUint(driveUsage.GrowthPerDayBytes, 10),\n\t\t\tdays,\n\t\t\tdriveUsage.VolumeName).Set(driveUsage.PercentUsed)\n\t}\n\n\t// Publish endpoints being monitored\n\tfor _, uptimeResponse := range result.UptimeList {\n\n\t\tif uptimeResponse.ResponseCode == 200 {\n\t\t\tendpointAvailable.WithLabelValues(uptimeResponse.Endpoint).Set(1)\n\t\t} else {\n\t\t\tendpointAvailable.WithLabelValues(uptimeResponse.Endpoint).Set(0)\n\t\t}\n\n\t\tendpointDuration.WithLabelValues(uptimeResponse.Endpoint).Set(uptimeResponse.ResponseTime.Seconds())\n\t}\n\n\tfor _, backupInfo := range result.BackupInfoList {\n\n\t\t/*\n\t\t\tif backupInfo.WasBackedUp {\n\t\t\t\tbackupsDone.WithLabelValues(backupInfo.Folder).Set(1)\n\t\t\t} else {\n\t\t\t\tbackupsDone.WithLabelValues(backupInfo.Folder).Set(0)\n\t\t\t}\n\t\t*/\n\n\t\t// {\"backup_directory\", \"backup_in_last_24_hours\", \"last_backup_size\", \"last_backup_date\", \"last_backup_time\"})\n\n\t\t// backupsSize.WithLabelValues(backupInfo.Folder).Set(float64(backupInfo.BackupFileSize))\n\n\t\tbackupInfoGauge.WithLabelValues(backupInfo.Folder,\n\t\t\tbtoa(backupInfo.WasBackedUp),\n\t\t\titoa(backupInfo.LastBackupSize),\n\t\t\tttoa(backupInfo.LastBackupTime),\n\t\t\tbackupInfo.LastBackupFile).Set(btof(backupInfo.WasBackedUp))\n\t}\n\n\t// TODO: This loop is not needed, you can build the summary on the first loop\n\tvar too_many_lines = 500\n\tfor _, logLine := range result.LoglineList {\n\n\t\tsummary, ok := result.LogSummary[logLine.LogPath]\n\n\t\tif ok == false {\n\t\t\tsummary = LogSummary{}\n\t\t\tsummary.StatusCount = make(map[string]int64)\n\t\t\tsummary.SeverityLevelCount = make(map[string]int64)\n\t\t}\n\n\t\tsummary.StatusCount[logLine.StatusCode] = summary.StatusCount[logLine.StatusCode] + 1\n\n\t\tif len(logLine.Severity) > 0 {\n\t\t\tsummary.SeverityLevelCount[logLine.Severity] = summary.SeverityLevelCount[logLine.Severity] + 1\n\t\t}\n\n\t\tresult.LogSummary[logLine.LogPath] = summary\n\n\t\tif too_many_lines <= 0 {\n\t\t\t// Pending a better solution, let's not allow the processing\n\t\t\t// of too many lines, to not kill the server\n\t\t\tlLog.Print(\"Too many lines for a single tick to process\")\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\t// Set the values for the logs. We use two labels (logpath, code)\n\tfor logFilePath, logSummary := range result.LogSummary {\n\n\t\tfor s, value := range logSummary.StatusCount {\n\t\t\tstatusCodes.WithLabelValues(logFilePath, s).Set(float64(value))\n\t\t}\n\n\t\tfor s, value := range logSummary.SeverityLevelCount {\n\t\t\tseverity.WithLabelValues(logFilePath, s).Set(float64(value))\n\t\t}\n\n\t}\n}", "func Metrics() Middleware {\n\treturn func(handler http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t// increment the request counter\n\t\t\tm.req.Add(1)\n\n\t\t\t// every 25 requests get the number of goroutines, calling runtime.NumGoroutine isn't\n\t\t\t// free so we avoid doing it on each request\n\t\t\tif m.req.Value()%25 == 0 {\n\t\t\t\tm.gr.Set(int64(runtime.NumGoroutine()))\n\t\t\t}\n\n\t\t\thandler.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func PrometheusMetrics(port int) error {\n\tpr := func() *httprouter.Router {\n\t\tr := httprouter.New()\n\t\tr.Handler(\"GET\", \"/metrics\", promhttp.Handler())\n\t\treturn r\n\t}\n\n\tif err := fmt.Errorf(\"%v\", http.ListenAndServe(fmt.Sprintf(\":%v\", port), LoggingHandler(pr()))); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func serveMetrics(d device) http.Handler {\n\treg := prometheus.NewRegistry()\n\treg.MustRegister(newCollector(d))\n\n\treturn promhttp.HandlerFor(reg, promhttp.HandlerOpts{})\n}", "func (m VarnishPlugin) FetchMetrics() (map[string]interface{}, error) {\n\tvar out []byte\n\tvar err error\n\n\tif m.VarnishName == \"\" {\n\t\tout, err = exec.Command(m.VarnishStatPath, \"-1\").CombinedOutput()\n\t} else {\n\t\tout, err = exec.Command(m.VarnishStatPath, \"-1\", \"-n\", m.VarnishName).CombinedOutput()\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: %s\", err, out)\n\t}\n\n\tlineexp := regexp.MustCompile(`^([^ ]+) +(\\d+)`)\n\tsmaexp := regexp.MustCompile(`^SMA\\.([^\\.]+)\\.(.+)$`)\n\n\tstat := map[string]interface{}{\n\t\t\"requests\": float64(0),\n\t}\n\n\tvar tmpv float64\n\tfor _, line := range strings.Split(string(out), \"\\n\") {\n\t\tmatch := lineexp.FindStringSubmatch(line)\n\t\tif match == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\ttmpv, err = strconv.ParseFloat(match[2], 64)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch match[1] {\n\t\tcase \"cache_hit\", \"MAIN.cache_hit\":\n\t\t\tstat[\"cache_hits\"] = tmpv\n\t\t\tstat[\"requests\"] = stat[\"requests\"].(float64) + tmpv\n\t\tcase \"cache_miss\", \"MAIN.cache_miss\":\n\t\t\tstat[\"requests\"] = stat[\"requests\"].(float64) + tmpv\n\t\tcase \"cache_hitpass\", \"MAIN.cache_hitpass\":\n\t\t\tstat[\"requests\"] = stat[\"requests\"].(float64) + tmpv\n\t\tcase \"MAIN.backend_req\":\n\t\t\tstat[\"backend_req\"] = tmpv\n\t\tcase \"MAIN.backend_conn\":\n\t\t\tstat[\"backend_conn\"] = tmpv\n\t\tcase \"MAIN.backend_fail\":\n\t\t\tstat[\"backend_fail\"] = tmpv\n\t\tcase \"MAIN.backend_reuse\":\n\t\t\tstat[\"backend_reuse\"] = tmpv\n\t\tcase \"MAIN.backend_recycle\":\n\t\t\tstat[\"backend_recycle\"] = tmpv\n\t\tcase \"MAIN.n_object\":\n\t\t\tstat[\"n_object\"] = tmpv\n\t\tcase \"MAIN.n_objectcore\":\n\t\t\tstat[\"n_objectcore\"] = tmpv\n\t\tcase \"MAIN.n_expired\":\n\t\t\tstat[\"n_expired\"] = tmpv\n\t\tcase \"MAIN.n_objecthead\":\n\t\t\tstat[\"n_objecthead\"] = tmpv\n\t\tcase \"MAIN.busy_sleep\":\n\t\t\tstat[\"busy_sleep\"] = tmpv\n\t\tcase \"MAIN.busy_wakeup\":\n\t\t\tstat[\"busy_wakeup\"] = tmpv\n\t\tdefault:\n\t\t\tsmamatch := smaexp.FindStringSubmatch(match[1])\n\t\t\tif smamatch == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif smamatch[2] == \"g_alloc\" {\n\t\t\t\tstat[\"varnish.sma.g_alloc.\"+smamatch[1]+\".g_alloc\"] = tmpv\n\t\t\t} else if smamatch[2] == \"g_bytes\" {\n\t\t\t\tstat[\"varnish.sma.memory.\"+smamatch[1]+\".allocated\"] = tmpv\n\t\t\t} else if smamatch[2] == \"g_space\" {\n\t\t\t\tstat[\"varnish.sma.memory.\"+smamatch[1]+\".available\"] = tmpv\n\t\t\t}\n\t\t}\n\t}\n\n\treturn stat, err\n}", "func NewMetrics(app, metricsPrefix, version, hash, date string) *Metrics {\n\tlabels := map[string]string{\n\t\t\"app\": app,\n\t\t\"version\": version,\n\t\t\"hash\": hash,\n\t\t\"buildTime\": date,\n\t}\n\n\tif metricsPrefix != \"\" {\n\t\tmetricsPrefix += \"_\"\n\t}\n\n\tpm := &Metrics{\n\t\tresponseTime: prometheus.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tName: metricsPrefix + \"response_time_seconds\",\n\t\t\t\tHelp: \"Description\",\n\t\t\t\tConstLabels: labels,\n\t\t\t},\n\t\t\t[]string{\"endpoint\"},\n\t\t),\n\t\ttotalRequests: prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\t\tName: metricsPrefix + \"requests_total\",\n\t\t\tHelp: \"number of requests\",\n\t\t\tConstLabels: labels,\n\t\t}, []string{\"code\", \"method\", \"endpoint\"}),\n\t\tduration: prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\t\tName: metricsPrefix + \"requests_duration_seconds\",\n\t\t\tHelp: \"duration of a requests in seconds\",\n\t\t\tConstLabels: labels,\n\t\t}, []string{\"code\", \"method\", \"endpoint\"}),\n\t\tresponseSize: prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\t\tName: metricsPrefix + \"response_size_bytes\",\n\t\t\tHelp: \"size of the responses in bytes\",\n\t\t\tConstLabels: labels,\n\t\t}, []string{\"code\", \"method\"}),\n\t\trequestSize: prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\t\tName: metricsPrefix + \"requests_size_bytes\",\n\t\t\tHelp: \"size of the requests in bytes\",\n\t\t\tConstLabels: labels,\n\t\t}, []string{\"code\", \"method\"}),\n\t\thandlerStatuses: prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\t\tName: metricsPrefix + \"requests_statuses_total\",\n\t\t\tHelp: \"count number of responses per status\",\n\t\t\tConstLabels: labels,\n\t\t}, []string{\"method\", \"status_bucket\"}),\n\t}\n\n\terr := prometheus.Register(pm)\n\tif e := new(prometheus.AlreadyRegisteredError); errors.As(err, e) {\n\t\treturn pm\n\t} else if err != nil {\n\t\tpanic(err)\n\t}\n\n\tgrpcPrometheus.EnableHandlingTimeHistogram()\n\n\treturn pm\n}", "func (p *Prometheus) Use(e *gin.Engine) {\n\te.Use(p.handlerFunc())\n\tp.setMetricsPath(e)\n}", "func init() {\n\tpromRegistry := prometheus.NewRegistry()\n\tpromRegistry.MustRegister(uptime, reqCount, passCount, blockCount, reqDuration)\n\tgo recordUptime()\n\tpromHandler = promhttp.InstrumentMetricHandler(promRegistry, promhttp.HandlerFor(promRegistry, promhttp.HandlerOpts{}))\n}", "func metricsHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tLoggingClient.Debug(\"retrieved service names\")\n\n\tlist := vars[\"services\"]\n\tvar services []string\n\tservices = strings.Split(list, \",\")\n\n\tsend, err := invokeMetrics(services, r.Context())\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\tLoggingClient.Error(err.Error())\n\t\treturn\n\t}\n\tpkg.Encode(send, w, LoggingClient)\n}", "func newMetricsCollector(devices func() ([]*wgtypes.Device, error)) prometheus.Collector {\n\t// common labels for all metrics\n\tlabels := []string{\"device\", \"public_key\"}\n\n\treturn &collector{\n\t\tDeviceInfo: prometheus.NewDesc(\n\t\t\t\"semaphore_wg_device_info\",\n\t\t\t\"Metadata about a device.\",\n\t\t\tlabels,\n\t\t\tnil,\n\t\t),\n\t\tPeerInfo: prometheus.NewDesc(\n\t\t\t\"semaphore_wg_peer_info\",\n\t\t\t\"Metadata about a peer. The public_key label on peer metrics refers to the peer's public key; not the device's public key.\",\n\t\t\tappend(labels, []string{\"endpoint\"}...),\n\t\t\tnil,\n\t\t),\n\t\tPeerAllowedIPsInfo: prometheus.NewDesc(\n\t\t\t\"semaphore_wg_peer_allowed_ips_info\",\n\t\t\t\"Metadata about each of a peer's allowed IP subnets for a given device.\",\n\t\t\tappend(labels, []string{\"allowed_ips\"}...),\n\t\t\tnil,\n\t\t),\n\t\tPeerReceiveBytes: prometheus.NewDesc(\n\t\t\t\"semaphore_wg_peer_receive_bytes_total\",\n\t\t\t\"Number of bytes received from a given peer.\",\n\t\t\tlabels,\n\t\t\tnil,\n\t\t),\n\t\tPeerTransmitBytes: prometheus.NewDesc(\n\t\t\t\"semaphore_wg_peer_transmit_bytes_total\",\n\t\t\t\"Number of bytes transmitted to a given peer.\",\n\t\t\tlabels,\n\t\t\tnil,\n\t\t),\n\t\tPeerLastHandshake: prometheus.NewDesc(\n\t\t\t\"semaphore_wg_peer_last_handshake_seconds\",\n\t\t\t\"UNIX timestamp for the last handshake with a given peer.\",\n\t\t\tlabels,\n\t\t\tnil,\n\t\t),\n\t\tdevices: devices,\n\t}\n}", "func (*noOpConntracker) Collect(ch chan<- prometheus.Metric) {}", "func NewMetrics(reg *prometheus.Registry, namespace, subsystem string, methodsFrom interface{}) (metric Metrics) {\n\tmetric.callErrTotal = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"errors_total\",\n\t\t\tHelp: \"Amount of DAL errors.\",\n\t\t},\n\t\t[]string{methodLabel},\n\t)\n\treg.MustRegister(metric.callErrTotal)\n\tmetric.callDuration = prometheus.NewHistogramVec(\n\t\tprometheus.HistogramOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"call_duration_seconds\",\n\t\t\tHelp: \"DAL call latency.\",\n\t\t},\n\t\t[]string{methodLabel},\n\t)\n\treg.MustRegister(metric.callDuration)\n\n\tfor _, methodName := range reflectx.MethodsOf(methodsFrom) {\n\t\tl := prometheus.Labels{\n\t\t\tmethodLabel: methodName,\n\t\t}\n\t\tmetric.callErrTotal.With(l)\n\t\tmetric.callDuration.With(l)\n\t}\n\n\treturn metric\n}", "func StartMetricsListener(addr string, signal context.Context) {\n\t// These metrics get registered in controller-runtime's registry via an init in the internal/controller/metrics package.\n\t// Unregister the controller-runtime metrics, so that we can combine the controller-runtime metric's registry\n\t// with that of the ingress-operator. This shouldn't have any side effects, as long as no 2 metrics across\n\t// controller runtime or the ingress operator share the same name (which is unlikely). See\n\t// https://github.com/kubernetes/test-infra/blob/master/prow/metrics/metrics.go for additional context.\n\tctrlruntimemetrics.Registry.Unregister(prometheus.NewGoCollector())\n\tctrlruntimemetrics.Registry.Unregister(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))\n\n\t// Create prometheus handler by combining the ingress-operator registry\n\t// with the ingress-operator's controller runtime metrics registry.\n\thandler := promhttp.HandlerFor(\n\t\tprometheus.Gatherers{prometheus.DefaultGatherer, ctrlruntimemetrics.Registry},\n\t\tpromhttp.HandlerOpts{},\n\t)\n\n\tlog.Info(\"registering Prometheus metrics\")\n\tif err := registerCanaryMetrics(); err != nil {\n\t\tlog.Error(err, \"unable to register metrics\")\n\t}\n\n\tlog.Info(\"starting metrics listener on \", \"addr\", addr)\n\tmux := http.NewServeMux()\n\tmux.Handle(\"/metrics\", handler)\n\ts := http.Server{Addr: addr, Handler: mux}\n\n\tgo func() {\n\t\tif err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\t\tlog.Error(err, \"metrics listener exited\")\n\t\t}\n\t}()\n\t<-signal.Done()\n\tif err := s.Shutdown(context.Background()); err != http.ErrServerClosed {\n\t\tlog.Error(err, \"error stopping metrics listener\")\n\t}\n}", "func (r *Prunner) RegMetrics(node *cluster.Snode) {\n\tr.Core.initProm(node)\n}", "func StartMetrics(\n\taddr string,\n\tl logger.Logger,\n\tuptimeCounter func() float64,\n) *http.Server {\n\tMetrics.WithUptimeCounter(uptimeCounter)\n\t// expvar package adds a handler in to the default HTTP server (which has to be started explicitly),\n\t// and serves up the metrics at the /debug/vars endpoint.\n\t// Here we're registering both expvar and promhttp handlers in our custom server.\n\tmux := http.NewServeMux()\n\tmux.Handle(\"/metrics\", promhttp.Handler())\n\tmux.Handle(\"/debug/vars\", expvar.Handler())\n\tserver := &http.Server{Addr: addr, Handler: mux}\n\tgo func() {\n\t\tif err := server.ListenAndServe(); err != nil {\n\t\t\tif err == http.ErrServerClosed {\n\t\t\t\tl.Infof(\"Metrics http server closed\")\n\t\t\t} else {\n\t\t\t\tl.Errorf(\"Metrics error: %s\", err)\n\t\t\t}\n\n\t\t}\n\t}()\n\n\treturn server\n}", "func init() {\n\n\t// cpu\n\tRegistryMetricCreateInput(\"cpu\", \"CPU usage\", monitor.METRIC_RES_TYPE_HOST, monitor.METRIC_DATABASE_TELE, 1,\n\t\t[]monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"usage_active\", \"CPU active state utilization rate\", monitor.METRIC_UNIT_PERCENT, 1),\n\t\t\tnewMetricFieldCreateInput(\"usage_idle\", \"CPU idle state utilization rate\", monitor.METRIC_UNIT_PERCENT, 2),\n\t\t\tnewMetricFieldCreateInput(\"usage_system\", \"CPU system state utilization rate\", monitor.METRIC_UNIT_PERCENT, 3),\n\t\t\tnewMetricFieldCreateInput(\"usage_user\", \"CPU user mode utilization rate\", monitor.METRIC_UNIT_PERCENT, 4),\n\t\t\tnewMetricFieldCreateInput(\"usage_iowait\", \"CPU IO usage\", monitor.METRIC_UNIT_PERCENT, 5),\n\t\t\tnewMetricFieldCreateInput(\"usage_irq\", \"CPU IRQ usage\", monitor.METRIC_UNIT_PERCENT, 6),\n\t\t\tnewMetricFieldCreateInput(\"usage_guest\", \"CPU guest usage\", monitor.METRIC_UNIT_PERCENT, 7),\n\t\t\tnewMetricFieldCreateInput(\"usage_nice\", \"CPU priority switch utilization\", monitor.METRIC_UNIT_PERCENT, 8),\n\t\t\tnewMetricFieldCreateInput(\"usage_softirq\", \"CPU softirq usage\", monitor.METRIC_UNIT_PERCENT, 9),\n\t\t})\n\n\t// disk\n\tRegistryMetricCreateInput(\"disk\", \"Disk usage\", monitor.METRIC_RES_TYPE_HOST,\n\t\tmonitor.METRIC_DATABASE_TELE, 3,\n\t\t[]monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"used_percent\", \"Percentage of used disks\", monitor.METRIC_UNIT_PERCENT, 1),\n\t\t\tnewMetricFieldCreateInput(\"free\", \"Free space size\", monitor.METRIC_UNIT_BYTE, 2),\n\t\t\tnewMetricFieldCreateInput(\"used\", \"Used disk size\", monitor.METRIC_UNIT_BYTE, 3),\n\t\t\tnewMetricFieldCreateInput(\"total\", \"Total disk size\", monitor.METRIC_UNIT_BYTE, 4),\n\t\t\tnewMetricFieldCreateInput(\"inodes_free\", \"Available inode\", monitor.METRIC_UNIT_COUNT, 5),\n\t\t\tnewMetricFieldCreateInput(\"inodes_used\", \"Number of inodes used\", monitor.METRIC_UNIT_COUNT, 6),\n\t\t\tnewMetricFieldCreateInput(\"inodes_total\", \"Total inodes\", monitor.METRIC_UNIT_COUNT, 7),\n\t\t})\n\n\t// diskio\n\tRegistryMetricCreateInput(\"diskio\", \"Disk traffic and timing\",\n\t\tmonitor.METRIC_RES_TYPE_HOST, monitor.METRIC_DATABASE_TELE, 4, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"read_bps\", \"Disk read rate\", monitor.METRIC_UNIT_BPS, 1),\n\t\t\tnewMetricFieldCreateInput(\"write_bps\", \"Disk write rate\", monitor.METRIC_UNIT_BPS, 2),\n\t\t\tnewMetricFieldCreateInput(\"read_iops\", \"Disk read operate rate\", monitor.METRIC_UNIT_COUNT, 3),\n\t\t\tnewMetricFieldCreateInput(\"write_iops\", \"Disk write operate rate\", monitor.METRIC_UNIT_COUNT, 4),\n\t\t\tnewMetricFieldCreateInput(\"reads\", \"Number of reads\", monitor.METRIC_UNIT_COUNT, 5),\n\t\t\tnewMetricFieldCreateInput(\"writes\", \"Number of writes\", monitor.METRIC_UNIT_COUNT, 6),\n\t\t\tnewMetricFieldCreateInput(\"read_bytes\", \"Bytes read\", monitor.METRIC_UNIT_BYTE, 7),\n\t\t\tnewMetricFieldCreateInput(\"write_bytes\", \"Bytes write\", monitor.METRIC_UNIT_BYTE, 8),\n\t\t\tnewMetricFieldCreateInput(\"write_time\", \"Time to wait for write\", monitor.METRIC_UNIT_MS, 9),\n\t\t\tnewMetricFieldCreateInput(\"io_time\", \"I / O request queuing time\", monitor.METRIC_UNIT_MS, 10),\n\t\t\tnewMetricFieldCreateInput(\"weighted_io_time\", \"I / O request waiting time\", monitor.METRIC_UNIT_MS, 11),\n\t\t\tnewMetricFieldCreateInput(\"iops_in_progress\", \"Number of I / O requests issued but not yet completed\", monitor.METRIC_UNIT_COUNT, 12),\n\t\t})\n\n\t// mem\n\tRegistryMetricCreateInput(\"mem\", \"Memory\", monitor.METRIC_RES_TYPE_HOST,\n\t\tmonitor.METRIC_DATABASE_TELE, 2, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"used_percent\", \"Used memory rate\", monitor.METRIC_UNIT_PERCENT, 1),\n\t\t\tnewMetricFieldCreateInput(\"available_percent\", \"Available memory rate\", monitor.METRIC_UNIT_PERCENT, 2),\n\t\t\tnewMetricFieldCreateInput(\"used\", \"Used memory\", monitor.METRIC_UNIT_BYTE, 3),\n\t\t\tnewMetricFieldCreateInput(\"free\", \"Free memory\", monitor.METRIC_UNIT_BYTE, 4),\n\t\t\tnewMetricFieldCreateInput(\"active\", \"The amount of active memory\", monitor.METRIC_UNIT_BYTE, 5),\n\t\t\tnewMetricFieldCreateInput(\"inactive\", \"The amount of inactive memory\", monitor.METRIC_UNIT_BYTE, 6),\n\t\t\tnewMetricFieldCreateInput(\"cached\", \"Cache memory\", monitor.METRIC_UNIT_BYTE, 7),\n\t\t\tnewMetricFieldCreateInput(\"buffered\", \"Buffer memory\", monitor.METRIC_UNIT_BYTE, 7),\n\t\t\tnewMetricFieldCreateInput(\"slab\", \"Number of kernel caches\", monitor.METRIC_UNIT_BYTE, 8),\n\t\t\tnewMetricFieldCreateInput(\"available\", \"Available memory\", monitor.METRIC_UNIT_BYTE, 9),\n\t\t\tnewMetricFieldCreateInput(\"total\", \"Total memory\", monitor.METRIC_UNIT_BYTE, 10),\n\t\t})\n\n\t// net\n\tRegistryMetricCreateInput(\"net\", \"Network interface and protocol usage\",\n\t\tmonitor.METRIC_RES_TYPE_HOST, monitor.METRIC_DATABASE_TELE, 5, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"bytes_sent\", \"The total number of bytes sent by the network interface\", monitor.METRIC_UNIT_BYTE, 1),\n\t\t\tnewMetricFieldCreateInput(\"bytes_recv\", \"The total number of bytes received by the network interface\", monitor.METRIC_UNIT_BYTE, 2),\n\t\t\tnewMetricFieldCreateInput(\"packets_sent\", \"The total number of packets sent by the network interface\", monitor.METRIC_UNIT_COUNT, 3),\n\t\t\tnewMetricFieldCreateInput(\"packets_recv\", \"The total number of packets received by the network interface\", monitor.METRIC_UNIT_COUNT, 4),\n\t\t\tnewMetricFieldCreateInput(\"err_in\", \"The total number of receive errors detected by the network interface\", monitor.METRIC_UNIT_COUNT, 5),\n\t\t\tnewMetricFieldCreateInput(\"err_out\", \"The total number of transmission errors detected by the network interface\", monitor.METRIC_UNIT_COUNT, 6),\n\t\t\tnewMetricFieldCreateInput(\"drop_in\", \"The total number of received packets dropped by the network interface\", monitor.METRIC_UNIT_COUNT, 7),\n\t\t\tnewMetricFieldCreateInput(\"drop_out\", \"The total number of transmission packets dropped by the network interface\", monitor.METRIC_UNIT_COUNT, 8),\n\t\t})\n\n\t// vm_cpu\n\tRegistryMetricCreateInput(\"vm_cpu\", \"Guest CPU usage\", monitor.METRIC_RES_TYPE_GUEST,\n\t\tmonitor.METRIC_DATABASE_TELE, 1, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"usage_active\", \"CPU active state utilization rate\", monitor.METRIC_UNIT_PERCENT, 1),\n\t\t\tnewMetricFieldCreateInput(\"cpu_usage_pcore\", \"CPU utilization rate per core\", monitor.METRIC_UNIT_PERCENT, 2),\n\t\t\tnewMetricFieldCreateInput(\"cpu_usage_idle_pcore\", \"CPU idle rate per core\", monitor.METRIC_UNIT_PERCENT, 3),\n\t\t\tnewMetricFieldCreateInput(\"cpu_time_system\", \"CPU system state time\", monitor.METRIC_UNIT_MS, 4),\n\t\t\tnewMetricFieldCreateInput(\"cpu_time_user\", \"CPU user state time\", monitor.METRIC_UNIT_MS, 5),\n\t\t\tnewMetricFieldCreateInput(\"thread_count\", \"The number of threads used by the process\", monitor.METRIC_UNIT_COUNT, 6),\n\t\t})\n\n\t// vm_diskio\n\tRegistryMetricCreateInput(\"vm_diskio\", \"Guest disk traffic\", monitor.METRIC_RES_TYPE_GUEST,\n\t\tmonitor.METRIC_DATABASE_TELE, 3, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"read_bps\", \"Disk read rate\", monitor.METRIC_UNIT_BYTEPS, 1),\n\t\t\tnewMetricFieldCreateInput(\"write_bps\", \"Disk write rate\", monitor.METRIC_UNIT_BYTEPS, 2),\n\t\t\tnewMetricFieldCreateInput(\"read_iops\", \"Disk read operate rate\", monitor.METRIC_UNIT_COUNT, 3),\n\t\t\tnewMetricFieldCreateInput(\"write_iops\", \"Disk write operate rate\", monitor.METRIC_UNIT_COUNT, 4),\n\t\t\tnewMetricFieldCreateInput(\"read_bytes\", \"Bytes read\", monitor.METRIC_UNIT_BYTE, 5),\n\t\t\tnewMetricFieldCreateInput(\"write_bytes\", \"Bytes write\", monitor.METRIC_UNIT_BYTE, 6),\n\t\t})\n\n\t// vm_mem\n\tRegistryMetricCreateInput(\"vm_mem\", \"Guest memory\", monitor.METRIC_RES_TYPE_GUEST,\n\t\tmonitor.METRIC_DATABASE_TELE, 2, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"used_percent\", \"Used memory rate\", monitor.METRIC_UNIT_PERCENT, 1),\n\t\t\tnewMetricFieldCreateInput(\"vms\", \"Virtual memory consumption\", monitor.METRIC_UNIT_BYTE, 2),\n\t\t\tnewMetricFieldCreateInput(\"rss\", \"Actual use of physical memory\", monitor.METRIC_UNIT_BYTE, 3),\n\t\t})\n\n\t// vm_netio\n\tRegistryMetricCreateInput(\"vm_netio\", \"Guest network traffic\", monitor.METRIC_RES_TYPE_GUEST,\n\t\tmonitor.METRIC_DATABASE_TELE, 4, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"bps_recv\", \"Received traffic per second\", monitor.METRIC_UNIT_BPS, 1),\n\t\t\tnewMetricFieldCreateInput(\"bps_sent\", \"Send traffic per second\", monitor.METRIC_UNIT_BPS, 2),\n\t\t})\n\n\t// oss_latency\n\tRegistryMetricCreateInput(\"oss_latency\", \"Object storage latency\",\n\t\tmonitor.METRIC_RES_TYPE_OSS, monitor.METRIC_DATABASE_TELE, 1, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"req_late\", \"Request average E2E delay\", monitor.METRIC_UNIT_MS, 1),\n\t\t})\n\n\t// oss_netio\n\tRegistryMetricCreateInput(\"oss_netio\", \"Object storage network traffic\",\n\t\tmonitor.METRIC_RES_TYPE_OSS, monitor.METRIC_DATABASE_TELE, 2, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"bps_recv\", \"Receive byte\", monitor.METRIC_UNIT_BYTE, 1),\n\t\t\tnewMetricFieldCreateInput(\"bps_sent\", \"Send byte\", monitor.METRIC_UNIT_BYTE, 2),\n\t\t})\n\n\t// oss_req\n\tRegistryMetricCreateInput(\"oss_req\", \"Object store request\", monitor.METRIC_RES_TYPE_OSS,\n\t\tmonitor.METRIC_DATABASE_TELE, 3, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"req_count\", \"request count\", monitor.METRIC_UNIT_COUNT, 1),\n\t\t})\n\n\t// rds_conn\n\tRegistryMetricCreateInput(\"rds_conn\", \"Rds connect\", monitor.METRIC_RES_TYPE_RDS,\n\t\tmonitor.METRIC_DATABASE_TELE, 5, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"used_percent\", \"Connection usage\", monitor.METRIC_UNIT_PERCENT, 1),\n\t\t})\n\n\t// rds_cpu\n\tRegistryMetricCreateInput(\"rds_cpu\", \"Rds CPU usage\", monitor.METRIC_RES_TYPE_RDS,\n\t\tmonitor.METRIC_DATABASE_TELE, 1, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"usage_active\", \"CPU active state utilization rate\", monitor.METRIC_UNIT_PERCENT, 2),\n\t\t})\n\n\t// rds_mem\n\tRegistryMetricCreateInput(\"rds_mem\", \"Rds memory\", monitor.METRIC_RES_TYPE_RDS,\n\t\tmonitor.METRIC_DATABASE_TELE, 2, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"used_percent\", \"Used memory rate\", monitor.METRIC_UNIT_PERCENT, 1),\n\t\t})\n\n\t// rds_netio\n\tRegistryMetricCreateInput(\"rds_netio\", \"Rds network traffic\", monitor.METRIC_RES_TYPE_RDS,\n\t\tmonitor.METRIC_DATABASE_TELE, 4, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"bps_recv\", \"Received traffic per second\", monitor.METRIC_UNIT_BPS, 1),\n\t\t\tnewMetricFieldCreateInput(\"bps_sent\", \"Send traffic per second\", monitor.METRIC_UNIT_BPS, 2),\n\t\t})\n\n\t// rds_disk\n\tRegistryMetricCreateInput(\"rds_disk\", \"Rds disk usage\", monitor.METRIC_RES_TYPE_RDS,\n\t\tmonitor.METRIC_DATABASE_TELE, 3, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"used_percent\", \"Percentage of used disks\", monitor.METRIC_UNIT_PERCENT, 1),\n\t\t})\n\n\t// dcs_cpu\n\tRegistryMetricCreateInput(\"dcs_cpu\", \"Redis CPU usage\", monitor.METRIC_RES_TYPE_REDIS,\n\t\tmonitor.METRIC_DATABASE_TELE, 1, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"usage_percent\", \"CPU active state utilization rate\", monitor.METRIC_UNIT_PERCENT, 1),\n\t\t})\n\n\t// dcs_mem\n\tRegistryMetricCreateInput(\"dcs_mem\", \"Redis memory\", monitor.METRIC_RES_TYPE_REDIS,\n\t\tmonitor.METRIC_DATABASE_TELE, 2, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"used_percent\", \"Used memory rate\", monitor.METRIC_UNIT_PERCENT, 1),\n\t\t})\n\n\t// dcs_netio\n\tRegistryMetricCreateInput(\"dcs_netio\", \"Redis network traffic\",\n\t\tmonitor.METRIC_RES_TYPE_REDIS,\n\t\tmonitor.METRIC_DATABASE_TELE, 4, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"bps_recv\", \"Received traffic per second\", monitor.METRIC_UNIT_BPS, 1),\n\t\t\tnewMetricFieldCreateInput(\"bps_sent\", \"Send traffic per second\", monitor.METRIC_UNIT_BPS, 2),\n\t\t})\n\n\t// dcs_conn\n\tRegistryMetricCreateInput(\"dcs_conn\", \"Redis connect\", monitor.METRIC_RES_TYPE_REDIS,\n\t\tmonitor.METRIC_DATABASE_TELE, 5, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"used_percent\", \"Connection usage\", monitor.METRIC_UNIT_PERCENT, 1),\n\t\t})\n\n\t// dcs_instantopt\n\tRegistryMetricCreateInput(\"dcs_instantopt\", \"Redis operator\",\n\t\tmonitor.METRIC_RES_TYPE_REDIS, monitor.METRIC_DATABASE_TELE, 5, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"opt_sec\", \"Number of commands processed per second\", monitor.METRIC_UNIT_COUNT, 1),\n\t\t})\n\n\t// dcs_cachekeys\n\tRegistryMetricCreateInput(\"dcs_cachekeys\", \"Redis keys\", monitor.METRIC_RES_TYPE_REDIS,\n\t\tmonitor.METRIC_DATABASE_TELE, 6, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"key_count\", \"Number of cache keys\", monitor.METRIC_UNIT_COUNT, 1),\n\t\t})\n\n\t// dcs_datamem\n\tRegistryMetricCreateInput(\"dcs_datamem\", \"Redis data memory\", monitor.METRIC_RES_TYPE_REDIS,\n\t\tmonitor.METRIC_DATABASE_TELE, 3, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"used_byte\", \"Data node memory usage\", monitor.METRIC_UNIT_BYTE, 1),\n\t\t})\n\n\t// cloudaccount_balance\n\tRegistryMetricCreateInput(\"cloudaccount_balance\", \"Cloud account balance\",\n\t\tmonitor.METRIC_RES_TYPE_CLOUDACCOUNT,\n\t\tmonitor.METRIC_DATABASE_METER, 1, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"balance\", \"balance\", monitor.METRIC_UNIT_RMB, 1),\n\t\t})\n\n\t// cpu\n\tRegistryMetricCreateInput(\"agent_cpu\", \"CPU usage\", monitor.METRIC_RES_TYPE_AGENT, monitor.METRIC_DATABASE_TELE, 1,\n\t\t[]monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"usage_active\", \"CPU active state utilization rate\", monitor.METRIC_UNIT_PERCENT, 1),\n\t\t\tnewMetricFieldCreateInput(\"usage_idle\", \"CPU idle state utilization rate\", monitor.METRIC_UNIT_PERCENT, 2),\n\t\t\tnewMetricFieldCreateInput(\"usage_system\", \"CPU system state utilization rate\", monitor.METRIC_UNIT_PERCENT, 3),\n\t\t\tnewMetricFieldCreateInput(\"usage_user\", \"CPU user mode utilization rate\", monitor.METRIC_UNIT_PERCENT, 4),\n\t\t\tnewMetricFieldCreateInput(\"usage_iowait\", \"CPU IO usage\", monitor.METRIC_UNIT_PERCENT, 5),\n\t\t\tnewMetricFieldCreateInput(\"usage_irq\", \"CPU IRQ usage\", monitor.METRIC_UNIT_PERCENT, 6),\n\t\t\tnewMetricFieldCreateInput(\"usage_guest\", \"CPU guest usage\", monitor.METRIC_UNIT_PERCENT, 7),\n\t\t\tnewMetricFieldCreateInput(\"usage_nice\", \"CPU priority switch utilization\", monitor.METRIC_UNIT_PERCENT, 8),\n\t\t\tnewMetricFieldCreateInput(\"usage_softirq\", \"CPU softirq usage\", monitor.METRIC_UNIT_PERCENT, 9),\n\t\t})\n\n\t// disk\n\tRegistryMetricCreateInput(\"agent_disk\", \"Disk usage\", monitor.METRIC_RES_TYPE_AGENT,\n\t\tmonitor.METRIC_DATABASE_TELE, 3,\n\t\t[]monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"used_percent\", \"Percentage of used disks\", monitor.METRIC_UNIT_PERCENT, 1),\n\t\t\tnewMetricFieldCreateInput(\"free\", \"Free space size\", monitor.METRIC_UNIT_BYTE, 2),\n\t\t\tnewMetricFieldCreateInput(\"used\", \"Used disk size\", monitor.METRIC_UNIT_BYTE, 3),\n\t\t\tnewMetricFieldCreateInput(\"total\", \"Total disk size\", monitor.METRIC_UNIT_BYTE, 4),\n\t\t\tnewMetricFieldCreateInput(\"inodes_free\", \"Available inode\", monitor.METRIC_UNIT_COUNT, 5),\n\t\t\tnewMetricFieldCreateInput(\"inodes_used\", \"Number of inodes used\", monitor.METRIC_UNIT_COUNT, 6),\n\t\t\tnewMetricFieldCreateInput(\"inodes_total\", \"Total inodes\", monitor.METRIC_UNIT_COUNT, 7),\n\t\t})\n\n\t// diskio\n\tRegistryMetricCreateInput(\"agent_diskio\", \"Disk traffic and timing\",\n\t\tmonitor.METRIC_RES_TYPE_AGENT, monitor.METRIC_DATABASE_TELE, 4, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"read_bps\", \"Disk read rate\", monitor.METRIC_UNIT_BPS, 1),\n\t\t\tnewMetricFieldCreateInput(\"write_bps\", \"Disk write rate\", monitor.METRIC_UNIT_BPS, 2),\n\t\t\tnewMetricFieldCreateInput(\"read_iops\", \"Disk read operate rate\", monitor.METRIC_UNIT_COUNT, 3),\n\t\t\tnewMetricFieldCreateInput(\"write_iops\", \"Disk write operate rate\", monitor.METRIC_UNIT_COUNT, 4),\n\t\t\tnewMetricFieldCreateInput(\"reads\", \"Number of reads\", monitor.METRIC_UNIT_COUNT, 5),\n\t\t\tnewMetricFieldCreateInput(\"writes\", \"Number of writes\", monitor.METRIC_UNIT_COUNT, 6),\n\t\t\tnewMetricFieldCreateInput(\"read_bytes\", \"Bytes read\", monitor.METRIC_UNIT_BYTE, 7),\n\t\t\tnewMetricFieldCreateInput(\"write_bytes\", \"Bytes write\", monitor.METRIC_UNIT_BYTE, 8),\n\t\t\tnewMetricFieldCreateInput(\"write_time\", \"Time to wait for write\", monitor.METRIC_UNIT_MS, 9),\n\t\t\tnewMetricFieldCreateInput(\"io_time\", \"I / O request queuing time\", monitor.METRIC_UNIT_MS, 10),\n\t\t\tnewMetricFieldCreateInput(\"weighted_io_time\", \"I / O request waiting time\", monitor.METRIC_UNIT_MS, 11),\n\t\t\tnewMetricFieldCreateInput(\"iops_in_progress\", \"Number of I / O requests issued but not yet completed\", monitor.METRIC_UNIT_COUNT, 12),\n\t\t})\n\n\t// mem\n\tRegistryMetricCreateInput(\"agent_mem\", \"Memory\", monitor.METRIC_RES_TYPE_AGENT,\n\t\tmonitor.METRIC_DATABASE_TELE, 2, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"used_percent\", \"Used memory rate\", monitor.METRIC_UNIT_PERCENT, 1),\n\t\t\tnewMetricFieldCreateInput(\"available_percent\", \"Available memory rate\", monitor.METRIC_UNIT_PERCENT, 2),\n\t\t\tnewMetricFieldCreateInput(\"used\", \"Used memory\", monitor.METRIC_UNIT_BYTE, 3),\n\t\t\tnewMetricFieldCreateInput(\"free\", \"Free memory\", monitor.METRIC_UNIT_BYTE, 4),\n\t\t\tnewMetricFieldCreateInput(\"active\", \"The amount of active memory\", monitor.METRIC_UNIT_BYTE, 5),\n\t\t\tnewMetricFieldCreateInput(\"inactive\", \"The amount of inactive memory\", monitor.METRIC_UNIT_BYTE, 6),\n\t\t\tnewMetricFieldCreateInput(\"cached\", \"Cache memory\", monitor.METRIC_UNIT_BYTE, 7),\n\t\t\tnewMetricFieldCreateInput(\"buffered\", \"Buffer memory\", monitor.METRIC_UNIT_BYTE, 7),\n\t\t\tnewMetricFieldCreateInput(\"slab\", \"Number of kernel caches\", monitor.METRIC_UNIT_BYTE, 8),\n\t\t\tnewMetricFieldCreateInput(\"available\", \"Available memory\", monitor.METRIC_UNIT_BYTE, 9),\n\t\t\tnewMetricFieldCreateInput(\"total\", \"Total memory\", monitor.METRIC_UNIT_BYTE, 10),\n\t\t})\n\n\t// net\n\tRegistryMetricCreateInput(\"agent_net\", \"Network interface and protocol usage\",\n\t\tmonitor.METRIC_RES_TYPE_AGENT, monitor.METRIC_DATABASE_TELE, 5, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"bytes_sent\", \"The total number of bytes sent by the network interface\", monitor.METRIC_UNIT_BYTE, 1),\n\t\t\tnewMetricFieldCreateInput(\"bytes_recv\", \"The total number of bytes received by the network interface\", monitor.METRIC_UNIT_BYTE, 2),\n\t\t\tnewMetricFieldCreateInput(\"packets_sent\", \"The total number of packets sent by the network interface\", monitor.METRIC_UNIT_COUNT, 3),\n\t\t\tnewMetricFieldCreateInput(\"packets_recv\", \"The total number of packets received by the network interface\", monitor.METRIC_UNIT_COUNT, 4),\n\t\t\tnewMetricFieldCreateInput(\"err_in\", \"The total number of receive errors detected by the network interface\", monitor.METRIC_UNIT_COUNT, 5),\n\t\t\tnewMetricFieldCreateInput(\"err_out\", \"The total number of transmission errors detected by the network interface\", monitor.METRIC_UNIT_COUNT, 6),\n\t\t\tnewMetricFieldCreateInput(\"drop_in\", \"The total number of received packets dropped by the network interface\", monitor.METRIC_UNIT_COUNT, 7),\n\t\t\tnewMetricFieldCreateInput(\"drop_out\", \"The total number of transmission packets dropped by the network interface\", monitor.METRIC_UNIT_COUNT, 8),\n\t\t})\n\n\tRegistryMetricCreateInput(\"storage\", \"Storage usage\",\n\t\tmonitor.METRIC_RES_TYPE_STORAGE, monitor.METRIC_DATABASE_TELE, 1, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"usage_active\", \"Storage utilization rate\", monitor.METRIC_UNIT_PERCENT, 1),\n\t\t\tnewMetricFieldCreateInput(\"free\", \"Free storage\", monitor.METRIC_UNIT_MB, 2),\n\t\t})\n\n\t//jenkins\n\tRegistryMetricCreateInput(\"jenkins_node\", \"jenkins node\",\n\t\tmonitor.METRIC_RES_TYPE_JENKINS, monitor.METRIC_DATABASE_TELE, 1, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"disk_available\", \"disk_available\", monitor.METRIC_UNIT_BYTE, 1),\n\t\t\tnewMetricFieldCreateInput(\"temp_available\", \"temp_available\", monitor.METRIC_UNIT_BYTE, 2),\n\t\t\tnewMetricFieldCreateInput(\"memory_available\", \"memory_available\", monitor.METRIC_UNIT_BYTE, 3),\n\t\t\tnewMetricFieldCreateInput(\"memory_total\", \"memory_total\", monitor.METRIC_UNIT_BYTE, 4),\n\t\t\tnewMetricFieldCreateInput(\"swap_available\", \"swap_available\", monitor.METRIC_UNIT_BYTE, 5),\n\t\t\tnewMetricFieldCreateInput(\"swap_total\", \"swap_total\", monitor.METRIC_UNIT_BYTE, 6),\n\t\t})\n\tRegistryMetricCreateInput(\"jenkins_job\", \"jenkins job\",\n\t\tmonitor.METRIC_RES_TYPE_JENKINS, monitor.METRIC_DATABASE_TELE, 2, []monitor.MetricFieldCreateInput{\n\t\t\tnewMetricFieldCreateInput(\"duration\", \"duration\", monitor.METRIC_UNIT_MS, 1),\n\t\t\tnewMetricFieldCreateInput(\"number\", \"number\", monitor.METRIC_UNIT_COUNT, 2),\n\t\t})\n\n}", "func Metrics() mux.MiddlewareFunc {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn promhttp.InstrumentMetricHandler(prometheus.DefaultRegisterer, h)\n\t}\n}", "func initializeControllerMetrics() {\n\t// CLUSTER METRICS\n\tnumPolicies = createClusterGauge(numPoliciesName, numPoliciesHelp)\n\t// TODO include health metrics: num failures for validating policies & ipsets\n\n\t// NODE METRICS\n\taddPolicyExecTime = createNodeSummaryVec(addPolicyExecTimeName, \"\", addPolicyExecTimeHelp, addPolicyExecTimeLabels)\n\n\t// perf metrics added after v1.4.16\n\t// all these metrics have \"npm_controller_\" prepended to their name\n\tcontrollerPolicyExecTime = createControllerExecTimeSummaryVec(policyExecTimeName, controllerPolicyExecTimeHelp)\n\tcontrollerPodExecTime = createControllerExecTimeSummaryVec(podExecTimeName, controllerPodExecTimeHelp)\n\tcontrollerNamespaceExecTime = createControllerExecTimeSummaryVec(namespaceExecTimeName, controllerNamespaceExecTimeHelp)\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 NewPrometheusMetrics(namespace string, registry metrics.RegisterGatherer) *prometheusMetrics {\n\tm := &prometheusMetrics{\n\t\tregistry: registry,\n\t}\n\n\tm.AvailableIPs = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"available_ips\",\n\t\tHelp: \"Total available IPs on Node for IPAM allocation\",\n\t}, []string{LabelTargetNodeName})\n\n\tm.UsedIPs = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"used_ips\",\n\t\tHelp: \"Total used IPs on Node for IPAM allocation\",\n\t}, []string{LabelTargetNodeName})\n\n\tm.NeededIPs = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"needed_ips\",\n\t\tHelp: \"Number of IPs that are needed on the Node to satisfy IPAM allocation requests\",\n\t}, []string{LabelTargetNodeName})\n\n\tm.IPsAllocated = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"ips\",\n\t\tHelp: \"Number of IPs allocated\",\n\t}, []string{\"type\"})\n\n\tm.AllocateIpOps = prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"ip_allocation_ops\",\n\t\tHelp: \"Number of IP allocation operations\",\n\t}, []string{\"subnet_id\"})\n\n\tm.ReleaseIpOps = prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"ip_release_ops\",\n\t\tHelp: \"Number of IP release operations\",\n\t}, []string{\"subnet_id\"})\n\n\tm.AllocateInterfaceOps = prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"interface_creation_ops\",\n\t\tHelp: \"Number of interfaces allocated\",\n\t}, []string{\"subnet_id\"})\n\n\tm.AvailableInterfaces = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"available_interfaces\",\n\t\tHelp: \"Number of interfaces with addresses available\",\n\t})\n\n\tm.InterfaceCandidates = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"interface_candidates\",\n\t\tHelp: \"Number of attached interfaces with IPs available for allocation\",\n\t})\n\n\tm.EmptyInterfaceSlots = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"empty_interface_slots\",\n\t\tHelp: \"Number of empty interface slots available for interfaces to be attached\",\n\t})\n\n\tm.AvailableIPsPerSubnet = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"available_ips_per_subnet\",\n\t\tHelp: \"Number of available IPs per subnet ID\",\n\t}, []string{\"subnet_id\", \"availability_zone\"})\n\n\tm.Nodes = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"nodes\",\n\t\tHelp: \"Number of nodes by category { total | in-deficit | at-capacity }\",\n\t}, []string{\"category\"})\n\n\tm.Resync = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"resync_total\",\n\t\tHelp: \"Number of resync operations to synchronize and resolve IP deficit of nodes\",\n\t})\n\n\tm.Allocation = prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"allocation_duration_seconds\",\n\t\tHelp: \"Allocation ip or interface latency in seconds\",\n\t\tBuckets: merge(\n\t\t\tprometheus.LinearBuckets(0.25, 0.25, 2), // 0.25s, 0.50s\n\t\t\tprometheus.LinearBuckets(1, 1, 60), // 1s, 2s, 3s, ... 60s,\n\t\t),\n\t}, []string{\"type\", \"status\", \"subnet_id\"})\n\n\tm.Release = prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"release_duration_seconds\",\n\t\tHelp: \"Release ip or interface latency in seconds\",\n\t\tBuckets: merge(\n\t\t\tprometheus.LinearBuckets(0.25, 0.25, 2), // 0.25s, 0.50s\n\t\t\tprometheus.LinearBuckets(1, 1, 60), // 1s, 2s, 3s, ... 60s,\n\t\t),\n\t}, []string{\"type\", \"status\", \"subnet_id\"})\n\n\t// pool_maintainer is a more generic name, but for backward compatibility\n\t// of dashboard, keep the metric name deficit_resolver unchanged\n\tm.poolMaintainer = NewTriggerMetrics(namespace, \"deficit_resolver\")\n\tm.k8sSync = NewTriggerMetrics(namespace, \"k8s_sync\")\n\tm.resync = NewTriggerMetrics(namespace, \"resync\")\n\n\tregistry.MustRegister(m.AvailableIPs)\n\tregistry.MustRegister(m.UsedIPs)\n\tregistry.MustRegister(m.NeededIPs)\n\n\tregistry.MustRegister(m.IPsAllocated)\n\tregistry.MustRegister(m.AllocateIpOps)\n\tregistry.MustRegister(m.ReleaseIpOps)\n\tregistry.MustRegister(m.AllocateInterfaceOps)\n\tregistry.MustRegister(m.AvailableInterfaces)\n\tregistry.MustRegister(m.InterfaceCandidates)\n\tregistry.MustRegister(m.EmptyInterfaceSlots)\n\tregistry.MustRegister(m.AvailableIPsPerSubnet)\n\tregistry.MustRegister(m.Nodes)\n\tregistry.MustRegister(m.Resync)\n\tregistry.MustRegister(m.Allocation)\n\tregistry.MustRegister(m.Release)\n\tm.poolMaintainer.Register(registry)\n\tm.k8sSync.Register(registry)\n\tm.resync.Register(registry)\n\n\treturn m\n}", "func (m *Metrics) RecordBPFMetrics() {\n\tgo func() {\n\t\tfor range time.Tick(m.MetricsInterval) {\n\t\t\tBPFMetrics, err := m.fetchBPFMetrics()\n\t\t\tif err != nil {\n\t\t\t\tm.Logger.Error().Err(err).Msg(\"error fetching bpf metrics\")\n\t\t\t}\n\t\t\tfor key := range BPFMetrics {\n\t\t\t\t// If rolename is not empty, override the defaultRolename\n\t\t\t\tif m.RoleName != \"\" {\n\t\t\t\t\tdefaultRolename = m.RoleName\n\t\t\t\t}\n\t\t\t\tvfsHit := fmt.Sprintf(\"bpf.by_role.%s.%s.%s.kprobe.hit_rate.minutely\", quote(defaultRolename), quote(m.Hostname), key)\n\t\t\t\tvfsMiss := fmt.Sprintf(\"bpf.by_role.%s.%s.%s.kprobe.miss_rate.minutely\", quote(defaultRolename), quote(m.Hostname), key)\n\t\t\t\tgoMetrics.GetOrRegisterGaugeFloat64(vfsHit, m.EveryMinuteRegister).Update(BPFMetrics[key].hitRate)\n\t\t\t\tgoMetrics.GetOrRegisterGaugeFloat64(vfsMiss, m.EveryMinuteRegister).Update(BPFMetrics[key].missedRate)\n\t\t\t}\n\t\t}\n\t}()\n}", "func InitMetrics(\n\tclient *client.Client,\n\tscanner *scanner.Scanner,\n\tkube *kuber.Kube,\n\toptInAnalysisData bool,\n\targs map[string]interface{},\n) ([]MetricsSource, error) {\n\tvar (\n\t\tmetricsInterval = utils.MustParseDuration(args, \"--metrics-interval\")\n\t\tfailOnError = false // whether the agent will fail to start if an error happened during init metric source\n\n\t\tmetricsSources = make([]MetricsSource, 0)\n\t\tfoundErrors = make([]error, 0)\n\t)\n\n\tmetricsSourcesNames := []string{\"influx\", \"kubelet\"}\n\tif names, ok := args[\"--source\"].([]string); ok && len(names) > 0 {\n\t\tmetricsSourcesNames = names\n\t\tfailOnError = true\n\t}\n\n\tkubeletClient, err := NewKubeletClient(client.Logger, scanner, kube, args)\n\tif err != nil {\n\t\tfoundErrors = append(foundErrors, err)\n\t\tfailOnError = true\n\t}\n\n\tfor _, metricsSource := range metricsSourcesNames {\n\t\tswitch metricsSource {\n\t\tcase \"kubelet\":\n\t\t\tclient.Info(\"using kubelet as metrics source\")\n\n\t\t\tkubelet, err := NewKubelet(\n\t\t\t\tkubeletClient,\n\t\t\t\tclient.Logger,\n\t\t\t\tmetricsInterval,\n\t\t\t\tkubeletTimeouts{\n\t\t\t\t\tbackoff: backOff{\n\t\t\t\t\t\tsleep: utils.MustParseDuration(args, \"--kubelet-backoff-sleep\"),\n\t\t\t\t\t\tmaxRetries: utils.MustParseInt(args, \"--kubelet-backoff-max-retries\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\toptInAnalysisData,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tfoundErrors = append(foundErrors, karma.Format(\n\t\t\t\t\terr,\n\t\t\t\t\t\"unable to initialize kubelet source\",\n\t\t\t\t))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tmetricsSources = append(metricsSources, kubelet)\n\t\t}\n\t}\n\tif len(foundErrors) > 0 && (failOnError || len(metricsSources) == 0) {\n\t\treturn nil, karma.Format(foundErrors, \"unable to init metric sources\")\n\t}\n\n\tfor _, source := range metricsSources {\n\t\tgo watchMetrics(\n\t\t\tclient,\n\t\t\tsource,\n\t\t\tscanner,\n\t\t\tmetricsInterval,\n\t\t)\n\t}\n\n\treturn metricsSources, nil\n}", "func (op *Operation) emitMetrics(err *error, count, elapsed float64, labels []string) {\n\tif op.metrics == nil {\n\t\treturn\n\t}\n\n\top.metrics.Observe(elapsed, count, err, labels...)\n}", "func (op *Operation) emitMetrics(err *error, count, elapsed float64, labels []string) {\n\tif op.metrics == nil {\n\t\treturn\n\t}\n\n\top.metrics.Observe(elapsed, count, err, labels...)\n}", "func runTestcase(t *testing.T) {\n\n\tgaugeStatHandler = new(GaugeStats)\n\n\tinitGaugeStats(METRICS_CONFIG_FILE, gaugeStatHandler)\n\n\t// read raw-metrics from mock data gen, create observer and channel prometeus metric ingestion and processing\n\trawMetrics := getRawMetrics()\n\tnsWatcher := new(NamespaceWatcher)\n\tlObserver := &Observer{}\n\tch := make(chan prometheus.Metric, 1000)\n\tpass2Metrics := requestInfoNamespaces(rawMetrics)\n\n\tnsWatcher.passTwoKeys(rawMetrics)\n\n\tnsInfoKeys := createNamespacePassTwoExpectedOutputs(rawMetrics)\n\n\t// outputs := nsWatcher.passTwoKeys(pass2Metrics)\n\t// assert.Equal(t, outputs, expectedOutputs)\n\n\terr := nsWatcher.refresh(lObserver, nsInfoKeys, rawMetrics, ch)\n\n\tif err == nil {\n\t\t// map of string ==> map[\"namespace/metric-name\"][\"<VALUE>\"]\n\t\t// map of string ==> map[\"namespace/metric-name\"][\"<Label>\"]\n\t\t// both used to assert the return values from actual code against calculated values\n\t\tlOutputValues := map[string]string{}\n\t\tlOutputLabels := map[string]string{}\n\n\t\t// reads data from the Prom channel and creates a map of strings so we can assert in the below loop\n\t\tdomore := 1\n\n\t\tfor domore == 1 {\n\t\t\tselect {\n\n\t\t\tcase nsMetric := <-ch:\n\t\t\t\tdescription := nsMetric.Desc().String()\n\t\t\t\tvar protobuffer dto.Metric\n\t\t\t\terr := nsMetric.Write(&protobuffer)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\" unable to get metric \", description, \" data into protobuf \", err)\n\t\t\t\t}\n\n\t\t\t\tmetricValue := \"\"\n\t\t\t\tmetricLabel := fmt.Sprintf(\"%s\", protobuffer.Label)\n\t\t\t\tif protobuffer.Gauge != nil {\n\t\t\t\t\tmetricValue = fmt.Sprintf(\"%.0f\", *protobuffer.Gauge.Value)\n\t\t\t\t} else if protobuffer.Counter != nil {\n\t\t\t\t\tmetricValue = fmt.Sprintf(\"%.0f\", *protobuffer.Counter.Value)\n\t\t\t\t}\n\n\t\t\t\t// Desc{fqName: \"aerospike_namespac_memory_free_pct\", help: \"memory free pct\", constLabels: {}, variableLabels: [cluster_name service ns]}\n\t\t\t\tmetricNameFromDesc := extractMetricNameFromDesc(description)\n\t\t\t\tnamespaceFromLabel := extractNamespaceFromLabel(metricLabel)\n\n\t\t\t\t// key will be like namespace/<metric_name>, this we use this check during assertion\n\t\t\t\tkeyName := makeKeyname(namespaceFromLabel, metricNameFromDesc, true)\n\t\t\t\tlOutputValues[keyName] = metricValue\n\t\t\t\tlOutputLabels[keyName] = metricLabel\n\n\t\t\tcase <-time.After(1 * time.Second):\n\t\t\t\tdomore = 0\n\n\t\t\t} // end select\n\t\t}\n\n\t\t// loop each namespace and compare the label and value\n\t\tarrNames := strings.Split(pass2Metrics[\"namespaces\"], \";\")\n\n\t\tfor nsIndex := range arrNames {\n\t\t\ttnsForNamespace := arrNames[nsIndex]\n\t\t\tlExpectedMetricNamedValues, lExpectedMetricLabels := createNamespaceWatcherExpectedOutputs(tnsForNamespace, true)\n\n\t\t\tfor key := range lOutputValues {\n\t\t\t\texpectedValues := lExpectedMetricNamedValues[key]\n\t\t\t\texpectedLabels := lExpectedMetricLabels[key]\n\t\t\t\toutputMetricValues := lOutputValues[key]\n\t\t\t\toutpuMetricLabels := lOutputLabels[key]\n\n\t\t\t\t// assert - only if the value belongs to the namespace we read expected values and processing\n\t\t\t\tif strings.HasPrefix(key, tnsForNamespace) {\n\t\t\t\t\tassert.Contains(t, expectedValues, outputMetricValues)\n\t\t\t\t\tassert.Contains(t, expectedLabels, outpuMetricLabels)\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t} else {\n\t\tfmt.Println(\" Failed Refreshing, error: \", err)\n\t}\n}", "func SysMetrics() gin.HandlerFunc {\n\tb := export.NewSysExporter()\n\treturn func(c *gin.Context) {\n\t\tc.Set(\"SysExporter\", b)\n\t\tc.Next()\n\t}\n}", "func CaptureMetrics(hnd http.Handler, w http.ResponseWriter, r *http.Request) Metrics {\n\treturn CaptureMetricsFn(w, func(ww http.ResponseWriter) {\n\t\thnd.ServeHTTP(ww, r)\n\t})\n}", "func (c *Controller) CreateMetrics(ctx context.Context) error {\n\tlogger := logging.FromContext(ctx)\n\n\tlogger.Infow(\"starting metric registration\")\n\tdefer logger.Infow(\"finished metric registration\")\n\n\t// Extract the project ID.\n\tsd := c.config.Observability.Stackdriver\n\tif sd == nil {\n\t\treturn fmt.Errorf(\"observability export is not stackdriver\")\n\t}\n\tprojectID := sd.ProjectID\n\n\t// Create the metrics client.\n\tclient, err := monitoring.NewMetricClient(context.Background())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create metrics client: %w\", err)\n\t}\n\n\t// Create the Stackdriver exporter.\n\texporter, err := observability.NewStackdriver(context.Background(), &observability.StackdriverConfig{\n\t\tProjectID: projectID,\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create Stackdriver exporter: %w\", err)\n\t}\n\n\t// Register metric descriptors with Stackdriver.\n\tallViews := observability.AllViews()\n\n\tworkers := int64(runtime.NumCPU())\n\tif workers < 3 {\n\t\tworkers = 3\n\t}\n\n\tsem := semaphore.NewWeighted(workers)\n\terrCh := make(chan error, len(allViews))\n\n\tfor _, view := range allViews {\n\t\tview := view\n\n\t\tif err := sem.Acquire(ctx, 1); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to acquire semaphore: %w\", err)\n\t\t}\n\n\t\tlogger.Infow(\"registering metrics exporter\", \"view\", view.Name)\n\n\t\tgo func() {\n\t\t\tdefer sem.Release(1)\n\n\t\t\tmetricDescriptor, err := exporter.ViewToMetricDescriptor(view)\n\t\t\tif err != nil {\n\t\t\t\terrCh <- fmt.Errorf(\"failed to convert view %s to MetricDescriptor: %w\", view.Name, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\treq := &monitoringpb.CreateMetricDescriptorRequest{\n\t\t\t\tName: \"projects/\" + projectID,\n\t\t\t\tMetricDescriptor: metricDescriptor,\n\t\t\t}\n\n\t\t\tctx, done := context.WithTimeout(ctx, 10*time.Second)\n\t\t\tdefer done()\n\n\t\t\tif _, err := client.CreateMetricDescriptor(ctx, req); err != nil {\n\t\t\t\terrCh <- fmt.Errorf(\"failed to create metric descriptor for view %s: %w\", view.Name, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}()\n\t}\n\n\tif err := sem.Acquire(ctx, workers); err != nil {\n\t\treturn fmt.Errorf(\"failed to wait for semaphore: %w\", err)\n\t}\n\tclose(errCh)\n\n\tvar merr *multierror.Error\n\tfor err := range errCh {\n\t\tif err != nil {\n\t\t\tmerr = multierror.Append(merr, err)\n\t\t}\n\t}\n\treturn merr.ErrorOrNil()\n}", "func RegisterMetrics(metricsOptions MetricOptions) {\n\tprometheus.Register(metricsOptions.GatewayFunctionInvocation)\n\tprometheus.Register(metricsOptions.GatewayFunctionsHistogram)\n\tprometheus.Register(metricsOptions.ServiceReplicasCounter)\n}", "func (p *Pulley) MetricsProcessor(contextOk config.ContextChecker, trackBuildTimes bool) {\n\t// Keep track of live SHAs -- we don't need separation per repository, as SHAs are pretty unique\n\t// map[commitSHA]shaState\n\tliveSHAs := make(liveSHAMap)\n\n\tp.WG.Add(1)\n\n\tgo func(updates <-chan interface{}) {\n\t\tdefer p.WG.Done()\n\n\t\tfor update := range updates {\n\t\t\tswitch up := update.(type) {\n\t\t\tcase events.PullUpdate:\n\t\t\t\t// When a PR is opened, its tracking starts.\n\t\t\t\tlog.Printf(\"updated pr: %d to commit: %s, action=%s\\n\", up.Number, up.SHA, up.Action)\n\n\t\t\t\tprocessPullUpdate(up, &liveSHAs, p.Metrics)\n\n\t\t\tcase events.BranchUpdate:\n\t\t\t\tlog.Printf(\"updated a branch to commit: %s (from %s)\", up.SHA, up.OldSHA)\n\n\t\t\t\tprocessBranchUpdate(up, &liveSHAs, p.Metrics)\n\n\t\t\tcase events.CommitUpdate:\n\t\t\t\t// track good, bad, overall\n\t\t\t\t// Find which PRs are the ones with the status as the HEAD\n\t\t\t\t// and use that\n\t\t\t\tlog.Printf(\"updated commit: %s context: %s status: %s\", up.SHA, up.Context, up.Status)\n\n\t\t\t\tprocessCommitUpdate(up, &liveSHAs, p.Metrics, contextOk, trackBuildTimes)\n\t\t\t}\n\t\t}\n\t}(p.Updates)\n}", "func (stats *Stats) RegisterPrometheus() error {\n\terr := prometheus.Register(prometheus.NewCounterFunc(prometheus.CounterOpts{\n\t\tNamespace: \"tracee_ebpf\",\n\t\tName: \"events_total\",\n\t\tHelp: \"events collected by tracee-ebpf\",\n\t}, func() float64 { return float64(stats.EventCount.Read()) }))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = prometheus.Register(prometheus.NewCounterFunc(prometheus.CounterOpts{\n\t\tNamespace: \"tracee_ebpf\",\n\t\tName: \"netevents_total\",\n\t\tHelp: \"net events collected by tracee-ebpf\",\n\t}, func() float64 { return float64(stats.NetEvCount.Read()) }))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = prometheus.Register(prometheus.NewCounterFunc(prometheus.CounterOpts{\n\t\tNamespace: \"tracee_ebpf\",\n\t\tName: \"lostevents_total\",\n\t\tHelp: \"events lost in the submission buffer\",\n\t}, func() float64 { return float64(stats.LostEvCount.Read()) }))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = prometheus.Register(prometheus.NewCounterFunc(prometheus.CounterOpts{\n\t\tNamespace: \"tracee_ebpf\",\n\t\tName: \"write_lostevents_total\",\n\t\tHelp: \"events lost in the write buffer\",\n\t}, func() float64 { return float64(stats.LostWrCount.Read()) }))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = prometheus.Register(prometheus.NewCounterFunc(prometheus.CounterOpts{\n\t\tNamespace: \"tracee_ebpf\",\n\t\tName: \"network_lostevents_total\",\n\t\tHelp: \"events lost in the network buffer\",\n\t}, func() float64 { return float64(stats.LostNtCount.Read()) }))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = prometheus.Register(prometheus.NewCounterFunc(prometheus.CounterOpts{\n\t\tNamespace: \"tracee_ebpf\",\n\t\tName: \"errors_total\",\n\t\tHelp: \"errors accumulated by tracee-ebpf\",\n\t}, func() float64 { return float64(stats.ErrorCount.Read()) }))\n\n\treturn err\n}", "func (m DefaultMetrics) Install(c *mux.PathRecorderMux) {\n\tregister()\n\tc.Handle(\"/metrics\", legacyregistry.Handler())\n}", "func main() {\n\t// Listen an actual port.\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", 9093))\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\tdefer lis.Close()\n\n\t// Create a HTTP server for prometheus.\n\thttpServer := &http.Server{Handler: promhttp.HandlerFor(reg, promhttp.HandlerOpts{}), Addr: fmt.Sprintf(\"0.0.0.0:%d\", 9092)}\n\n\t// Create a gRPC Server with gRPC interceptor.\n\tgrpcServer := grpc.NewServer(\n\t\tgrpc.StreamInterceptor(grpcMetrics.StreamServerInterceptor()),\n\t\tgrpc.UnaryInterceptor(grpcMetrics.UnaryServerInterceptor()),\n\t)\n\n\t// Create a new api server.\n\tdemoServer := newDemoServer()\n\n\t// Register your service.\n\tpb.RegisterDemoServiceServer(grpcServer, demoServer)\n\n\t// Initialize all metrics.\n\tgrpcMetrics.InitializeMetrics(grpcServer)\n\n\t// Start your http server for prometheus.\n\tgo func() {\n\t\tif err := httpServer.ListenAndServe(); err != nil {\n\t\t\tlog.Fatal(\"Unable to start a http server.\")\n\t\t}\n\t}()\n\n\t// Start your gRPC server.\n\tlog.Fatal(grpcServer.Serve(lis))\n}", "func registerMetricsForCheck(check *Check, value float64, labels map[string]string) {\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.Warnf(\"Not able to register metric for check %s. Maybe already registered?\", check.Name)\n\t\t}\n\t}()\n\n\t// Store the result labels\n\tcheck.resultCurrent = append(check.resultCurrent, labels)\n\n\tswitch check.MetricType {\n\tcase \"Gauge\":\n\t\tif check.metric == nil {\n\t\t\tcheck.metric = prometheus.NewGaugeVec(\n\t\t\t\tprometheus.GaugeOpts{\n\t\t\t\t\tName: check.Name,\n\t\t\t\t\tHelp: check.Help,\n\t\t\t\t},\n\t\t\t\tconvertMapKeysToSlice(labels),\n\t\t\t)\n\n\t\t\t// This can be panicking and will be recovered\n\t\t\tprometheus.MustRegister(check.metric.(*prometheus.GaugeVec))\n\t\t}\n\t\tcheck.metric.(*prometheus.GaugeVec).With(labels).Set(value)\n\tcase \"Counter\":\n\t\tif check.metric == nil {\n\t\t\tcheck.metric = prometheus.NewCounterVec(\n\t\t\t\tprometheus.CounterOpts{\n\t\t\t\t\tName: check.Name,\n\t\t\t\t\tHelp: check.Help,\n\t\t\t\t},\n\t\t\t\tconvertMapKeysToSlice(labels),\n\t\t\t)\n\n\t\t\t// This can be panicking and will be recovered\n\t\t\tprometheus.MustRegister(check.metric.(*prometheus.CounterVec))\n\t\t}\n\t\tcheck.metric.(*prometheus.CounterVec).With(labels).Add(value)\n\tcase \"Histogram\":\n\t\tlog.Warn(\"Metric type Counter not implemented yet!\")\n\tcase \"Summary\":\n\t\tlog.Warn(\"Metric type Counter not implemented yet!\")\n\tdefault:\n\t\tlog.Warnf(\"Not able to register unknown metric type %s\", check.MetricType)\n\t\tcheck.metric = nil\n\t}\n\n\tlog.Tracef(\"Result from check %s -> value: %f, labels: %v\", check.Name, value, MapToString(labels))\n}", "func HandleMetrics(mux *http.ServeMux, reg *prometheus.Registry) {\n\thandler := promhttp.InstrumentMetricHandler(reg, promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))\n\tmux.Handle(\"/metrics\", handler)\n}", "func UpdateMetrics() error {\n\t// err is aggregation of errors while running each of the MetricFetchers\n\tvar err error\n\n\t// wg is go's way of concurrency control essentially a way to say when the main thread can resume execution\n\tvar wg sync.WaitGroup\n\t// main thread after spawning go routines should resume only once all go routines are done executing\n\twg.Add(len(MetricFetchers))\n\n\t// Loop over all the metric fetchers and spawn execution of each MetricFetcher as a go-routine(concurrent execution)\n\tfor _, metricFetcher := range MetricFetchers {\n\t\tgo func() {\n\t\t\t// execute the metricfetcher to get its corresponding clouwatch form\n\t\t\tnamespace, name, value, metaInfo, e := metricFetcher()\n\t\t\t// if err is not nil, accummulate it and error and later instead of failing fast...\n\t\t\t// So, that other metrics can be collected instead of failing completely for failure in collecting one/some\n\t\t\t// of the metrics\n\t\t\tif e != nil {\n\t\t\t\tif err == nil {\n\t\t\t\t\terr = e\n\t\t\t\t\treturn\n\t\t\t\t} else {\n\t\t\t\t\terr = fmt.Errorf(\"%s.%s\", err, e.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfmt.Println(namespace, name, value, metaInfo, e)\n\n\t\t\t// Push the metric just collected\n\t\t\te = PushMetricToCloudWatch(namespace, name, value, metaInfo)\n\t\t\t// If error accummulate error\n\t\t\tif e != nil {\n\t\t\t\t// ToDo(@Anmol Babu) handle the error concatenation better\n\t\t\t\tif err == nil {\n\t\t\t\t\terr = e\n\t\t\t\t\treturn\n\t\t\t\t} else {\n\t\t\t\t\terr = fmt.Errorf(\"%s.%s\", err, e.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Signal completion of one routine to be waited on\n\t\t\twg.Done()\n\t\t}()\n\t}\n\t// Wait until all go-routines are done executing\n\twg.Wait()\n\treturn err\n}", "func (cm *Docker) SetMetrics(metrics models.Metrics) {\n\tif config.GetSwitchVal(\"swarmMode\") {\n\t\ttask := cm.MustGetTask(metrics.Id)\n\t\ttask.SetMetrics(metrics)\n\t\treturn\n\t}\n\tcont := cm.MustGetContainer(metrics.Id)\n\tcont.SetMetrics(metrics)\n}", "func init() {\n\tprometheus.MustRegister(duration)\n\tprometheus.MustRegister(counter)\n\tprometheus.MustRegister(requestsTotal)\n}", "func (c *metricCollector) listener(event int, ctx interface{}) {\n\t// http events\n\tswitch event {\n\tcase rrhttp.EventResponse:\n\t\te := ctx.(*rrhttp.ResponseEvent)\n\n\t\tc.requestCounter.With(prometheus.Labels{\n\t\t\t\"status\": strconv.Itoa(e.Response.Status),\n\t\t}).Inc()\n\n\t\tc.requestDuration.With(prometheus.Labels{\n\t\t\t\"status\": strconv.Itoa(e.Response.Status),\n\t\t}).Observe(e.Elapsed().Seconds())\n\n\tcase rrhttp.EventError:\n\t\te := ctx.(*rrhttp.ErrorEvent)\n\n\t\tc.requestCounter.With(prometheus.Labels{\n\t\t\t\"status\": \"500\",\n\t\t}).Inc()\n\n\t\tc.requestDuration.With(prometheus.Labels{\n\t\t\t\"status\": \"500\",\n\t\t}).Observe(e.Elapsed().Seconds())\n\t}\n}", "func httpServePrometheusMetrics(t *testing.T) *http.Server {\n\tserver := &http.Server{\n\t\tAddr: addr,\n\t\tHandler: promhttp.Handler(),\n\t}\n\tgo server.ListenAndServe()\n\treturn server\n}", "func Instrument(router *gin.Engine, appName string) {\n\tsanitizedServiceName := strings.ReplaceAll(appName, \"-\", \"_\")\n\n\t// http localhost:3000/metrics\n\trouter.GET(\"/metrics\", gin.WrapH(promhttp.Handler()))\n\n\trouter.Use(requestMiddleware(sanitizedServiceName))\n}" ]
[ "0.62943596", "0.606935", "0.5983493", "0.5955956", "0.5936195", "0.5896313", "0.5838032", "0.5773502", "0.5761245", "0.5749618", "0.57393074", "0.571998", "0.5669712", "0.5638325", "0.56340677", "0.56271774", "0.55997336", "0.5589016", "0.55862945", "0.5579198", "0.55665874", "0.5557504", "0.55341244", "0.5527155", "0.55034065", "0.54978794", "0.5496139", "0.5456141", "0.54528964", "0.5452514", "0.54446214", "0.5417807", "0.5417351", "0.53861284", "0.5376103", "0.5372505", "0.53699535", "0.5368857", "0.5365751", "0.5360514", "0.53524965", "0.5336733", "0.53304356", "0.5325443", "0.53237104", "0.531792", "0.5305952", "0.5295697", "0.52922153", "0.5288765", "0.52750057", "0.52710485", "0.52692294", "0.5260636", "0.5250956", "0.5249851", "0.5246865", "0.5245956", "0.52449024", "0.5242228", "0.5230537", "0.52285486", "0.5216988", "0.5210362", "0.5206303", "0.52044624", "0.52002454", "0.5199946", "0.5196519", "0.51888263", "0.5184777", "0.518203", "0.51773506", "0.51735705", "0.5166064", "0.515885", "0.51531845", "0.5147363", "0.51468384", "0.5144953", "0.51442915", "0.5141522", "0.5141522", "0.513978", "0.51212996", "0.5118974", "0.51155126", "0.5113214", "0.5111011", "0.5108727", "0.5108458", "0.5107444", "0.5105698", "0.51004887", "0.5100272", "0.51000416", "0.5095995", "0.5091523", "0.50855565", "0.50747687" ]
0.57227534
11
RandProxy returns a random proxy from a Provider's list of proxies
func (p Provider) RandProxy() Proxy { s := rand.NewSource(time.Now().Unix()) r := rand.New(s) rand := r.Intn(len(p.Data)) return p.Data[rand].Proxy }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RandomProxy(hosts ...string) InterceptorFn {\n\tif len(hosts) == 0 {\n\t\tpanic(\"empty hosts list\")\n\t}\n\treturn func(rt http.RoundTripper) http.RoundTripper {\n\t\treturn RoundTripperFn(func(request *http.Request) (*http.Response, error) {\n\t\t\trequest.Host = hosts[rand.Intn(len(hosts))]\n\t\t\treturn rt.RoundTrip(request)\n\t\t})\n\t}\n}", "func (s *Set) Random() Proxy {\n\ts.m.Lock()\n\tdefer s.m.Unlock()\n\n\tfor k := range s.proxies {\n\t\treturn k\n\t}\n\n\treturn Proxy{}\n}", "func (pool *ComplexPool) Random() (Proxy, error) {\n\tlength := pool.SizeAll()\n\n\tif length == 0 {\n\t\tif !pool.Config.ReloadWhenEmpty {\n\t\t\treturn Proxy{}, fmt.Errorf(\"prox (%p): cannot select random proxy, no proxies in pool\", pool)\n\t\t}\n\n\t\terr := pool.Load()\n\t\tif err != nil {\n\t\t\treturn Proxy{}, fmt.Errorf(\"prox (%p): cannot select random proxy, error occurred while reloading empty pool: %v\", pool, err)\n\t\t}\n\n\t\tlength = pool.SizeAll()\n\t}\n\n\trawProxy := pool.All.Random()\n\tpool.Unused.Remove(rawProxy)\n\n\treturn *CastProxy(rawProxy), nil\n}", "func (r *Random) Next() (*proxy.Proxy, error) {\n\tif r.proxies.Len() > 0 {\n\t\tn := rand.Intn(r.proxies.Len())\n\t\treturn getAvailableProxy(r.proxies, n)\n\t}\n\treturn nil, fmt.Errorf(\"no proxies set\")\n}", "func NewRandom(seed func(), proxies ...*proxy.Proxy) Iterator {\n\tbunch := make(commonProxiesBunch, 0, len(proxies))\n\tfor _, p := range proxies {\n\t\tbunch = append(bunch, p)\n\t}\n\tseed()\n\treturn &Random{\n\t\tproxies: bunch,\n\t}\n}", "func NewRandomBackendReverseProxy(backends []config.HostPort) *httputil.ReverseProxy {\n\tdirector := func(req *http.Request) {\n\t\ti := rand.Intn(len(backends))\n\t\tbackend := backends[i]\n\t\treq.URL.Scheme = \"http\" // TODO: In real code this would be https\n\t\treq.URL.Host = backend.String()\n\t\tlog.Printf(\"final URL: %s\", req.URL)\n\t}\n\n\treturn &httputil.ReverseProxy{Director: director}\n}", "func random(services []*registry.ServiceURL) Next {\n\treturn func(ID uint64) (*registry.ServiceURL, error) {\n\t\tif len(services) == 0 {\n\t\t\treturn nil, ErrNoneAvailable\n\t\t}\n\n\t\ti := ((uint64)(rand.Int()) + ID) % (uint64)(len(services))\n\t\treturn services[i], nil\n\t}\n}", "func (m *Provider) Random() (string, error) {\n\t// Get random picture\n\trand.Seed(time.Now().Unix())\n\treturn getURL(m.siteurl, m.allpics[rand.Intn(len(m.allpics))], \"1920x1080\")\n}", "func randomPolicy() loadBalancerPolicy {\n\treturn func(backends []NetAddr) (NetAddr, error) {\n\t\tif len(backends) == 0 {\n\t\t\treturn NetAddr{}, trace.ConnectionProblem(nil, \"no backends\")\n\t\t}\n\t\ti := rand.Intn(len(backends))\n\t\treturn backends[i], nil\n\t}\n}", "func (pr *ProxyRoulette) Select() (*Proxy, error) {\n\tpr.once.Do(func() {\n\t\trand.Seed(time.Now().UnixNano())\n\t\t// linear normalization\n\t\tval := 1 / float32(len(pr.Proxies))\n\t\tfor _, proxy := range pr.Proxies {\n\t\t\tproxy.Weight = val\n\t\t}\n\n\t\tpr.maxWeight = val\n\t})\n\n\tvar index float32\n\tfor {\n\t\tindex = rand.Float32() * float32(len(pr.Proxies))\n\t\trr := rand.Float32()\n\t\trrr := pr.Proxies[int(index)].Weight / pr.maxWeight\n\t\tif rr < rrr {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn pr.Proxies[int(index)], nil\n}", "func RandomList(o interface{}) interface{} {\n\tv := reflect.ValueOf(o)\n\tl := v.Len()\n\ti := rand.Intn(l)\n\treturn v.Index(i).Interface()\n}", "func rndPicker(r *Route) *Target {\n\treturn r.wTargets[randIntn(len(r.wTargets))]\n}", "func (pl *Peerlist) random(count int, includePrivate bool) []Peer {\n\tkeys := pl.getAddresses(false)\n\tif includePrivate {\n\t\tkeys = append(keys, pl.getAddresses(true)...)\n\t}\n\n\tif len(keys) == 0 {\n\t\treturn []Peer{}\n\t}\n\n\tmax := count\n\tif count == 0 || count > len(keys) {\n\t\tmax = len(keys)\n\t}\n\n\tpeers := make([]Peer, 0, max)\n\tperm := rand.Perm(len(keys))\n\tfor _, i := range perm[:max] {\n\t\tpeers = append(peers, *pl.peers[keys[i]])\n\t}\n\n\treturn peers\n}", "func (r *RoundRobin) Next() (*proxy.Proxy, error) {\n\tnext := atomic.AddInt32(&r.current, 1) % int32(len(r.proxies))\n\tatomic.StoreInt32(&r.current, next)\n\treturn getAvailableProxy(r.proxies, int(next))\n}", "func (p *proxy) Provider() Provider {\n\treturn &provider{p}\n}", "func ExampleResourceGuardProxiesClient_NewGetPager() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armrecoveryservicesbackup.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpager := clientFactory.NewResourceGuardProxiesClient().NewGetPager(\"sampleVault\", \"SampleResourceGroup\", nil)\n\tfor pager.More() {\n\t\tpage, err := pager.NextPage(ctx)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to advance page: %v\", err)\n\t\t}\n\t\tfor _, v := range page.Value {\n\t\t\t// You could use page here. We use blank identifier for just demo purposes.\n\t\t\t_ = v\n\t\t}\n\t\t// If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t\t// page.ResourceGuardProxyBaseResourceList = armrecoveryservicesbackup.ResourceGuardProxyBaseResourceList{\n\t\t// \tValue: []*armrecoveryservicesbackup.ResourceGuardProxyBaseResource{\n\t\t// \t\t{\n\t\t// \t\t\tName: to.Ptr(\"swaggerExample\"),\n\t\t// \t\t\tType: to.Ptr(\"Microsoft.RecoveryServices/vaults/backupResourceGuardProxies\"),\n\t\t// \t\t\tID: to.Ptr(\"/backupmanagement/resources/sampleVault/backupResourceGuardProxies/swaggerExample\"),\n\t\t// \t\t\tProperties: &armrecoveryservicesbackup.ResourceGuardProxyBase{\n\t\t// \t\t\t\tDescription: to.Ptr(\"Please take JIT access before performing any of the critical operation\"),\n\t\t// \t\t\t\tLastUpdatedTime: to.Ptr(\"2021-02-11T12:20:47.8210031Z\"),\n\t\t// \t\t\t\tResourceGuardOperationDetails: []*armrecoveryservicesbackup.ResourceGuardOperationDetail{\n\t\t// \t\t\t\t\t{\n\t\t// \t\t\t\t\t\tDefaultResourceRequest: to.Ptr(\"/subscriptions/c999d45b-944f-418c-a0d8-c3fcfd1802c8/resourceGroups/vaultguardRGNew/providers/Microsoft.DataProtection/resourceGuards/VaultGuardTestNew/deleteResourceGuardProxyRequests/default\"),\n\t\t// \t\t\t\t\t\tVaultCriticalOperation: to.Ptr(\"Microsoft.DataProtection/resourceGuards/deleteResourceGuardProxyRequests\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t{\n\t\t// \t\t\t\t\t\tDefaultResourceRequest: to.Ptr(\"/subscriptions/c999d45b-944f-418c-a0d8-c3fcfd1802c8/resourceGroups/vaultguardRGNew/providers/Microsoft.DataProtection/resourceGuards/VaultGuardTestNew/disableSoftDeleteRequests/default\"),\n\t\t// \t\t\t\t\t\tVaultCriticalOperation: to.Ptr(\"Microsoft.DataProtection/resourceGuards/disableSoftDeleteRequests\"),\n\t\t// \t\t\t\t}},\n\t\t// \t\t\t\tResourceGuardResourceID: to.Ptr(\"/subscriptions/c999d45b-944f-418c-a0d8-c3fcfd1802c8/resourceGroups/vaultguardRGNew/providers/Microsoft.DataProtection/resourceGuards/VaultGuardTestNew\"),\n\t\t// \t\t\t},\n\t\t// \t}},\n\t\t// }\n\t}\n}", "func TestProxy(t *testing.T) {\n\tfmt.Println(GetProxyIPList())\n}", "func Random(peers ...*Peer) (p *Peer) {\n\tfor _, p = range shuffleQuorum(peers) {\n\t\treturn p\n\t}\n\n\treturn p\n}", "func Proxy(options ...Option) http.RoundTripper {\n\tp := &proxy{\n\t\tnext: http.DefaultTransport,\n\t\tscheme: \"http\",\n\t\tresolver: resolve.ResolverFunc(resolve.DNSSRV),\n\t\tpoolReporter: nil,\n\t\tfactory: pool.RoundRobin,\n\t\tregistry: nil,\n\t}\n\tp.setOptions(options...)\n\tp.registry = newRegistry(p.resolver, p.poolReporter, p.factory)\n\treturn p\n}", "func SetupProxies() {\n\tfor _, p := range proxies {\n\t\tp.SetupProxy()\n\t\t//To accomodate for multiple client communications\n\t\tp.CountCh = make(chan int, 10)\n\t\tgo p.count()\n\t}\n}", "func (pool *ComplexPool) New() (Proxy, error) {\n\tlength := pool.SizeUnused()\n\n\tif length == 0 {\n\t\tif !pool.Config.ReloadWhenEmpty {\n\t\t\treturn Proxy{}, fmt.Errorf(\"prox (%p): cannot select proxy, no unused proxies left in pool\", pool)\n\t\t}\n\n\t\terr := pool.Load()\n\t\tif err != nil {\n\t\t\treturn Proxy{}, fmt.Errorf(\"prox (%p): cannot select unused proxy, error occurred while reloading pool: %v\", pool, err)\n\t\t}\n\n\t\tlength = pool.SizeUnused()\n\t\tif length == 0 {\n\t\t\treturn Proxy{}, fmt.Errorf(\"prox (%p): cannot select proxy, no unused proxies even after reload\", pool)\n\t\t}\n\t}\n\n\trawProxy := pool.Unused.Random()\n\tpool.Unused.Remove(rawProxy)\n\n\treturn *CastProxy(rawProxy), nil\n}", "func (r *record) RandomAddr() string {\n\treturn r.addrs[rand.Intn(len(r.addrs))]\n}", "func (c *StoreCandidates) RandomPick() *core.StoreInfo {\n\tif len(c.Stores) == 0 {\n\t\treturn nil\n\t}\n\treturn c.Stores[rand.Intn(len(c.Stores))]\n}", "func getRandomEndpointsManager(t testing.TB) connection.Endpoint {\n\teps := getEndpointsFromEnv(t)\n\trand.Seed(time.Now().UnixNano())\n\tif rand.Intn(2) == 1 {\n\t\tt.Log(\"Using MaglevHashEndpoints\")\n\t\tep, err := connection.NewMaglevHashEndpoints(eps, connection.RequestDBNameValueExtractor)\n\t\trequire.NoError(t, err)\n\t\treturn ep\n\t}\n\tt.Log(\"Using RoundRobinEndpoints\")\n\treturn connection.NewRoundRobinEndpoints(eps)\n}", "func (list List) RandomChoice() interface{} {\n\trand.Seed(time.Now().Unix())\n\treturn list[rand.Intn(len(list))]\n}", "func RoundRobinProxy(hosts ...string) InterceptorFn {\n\tif len(hosts) == 0 {\n\t\tpanic(\"empty hosts list\")\n\t}\n\tvar term uint64 = 0\n\treturn func(rt http.RoundTripper) http.RoundTripper {\n\t\treturn RoundTripperFn(func(request *http.Request) (*http.Response, error) {\n\t\t\thost := hosts[atomic.AddUint64(&term, 1)%uint64(len(hosts))]\n\t\t\trequest.Host = host\n\t\t\treturn rt.RoundTrip(request)\n\t\t})\n\t}\n}", "func chooseProxyFromList(VMlist []aarch64.VM) (aarch64.VM, error) {\n\tvar VMNames []string\n\tfor _, vm := range VMlist {\n\t\tVMNames = append(VMNames, formatVMmeta(vm))\n\t}\n\n\tselectVM := promptui.Select{\n\t\tLabel: \"Select VM\",\n\t\tItems: VMNames,\n\t}\n\tselectedVMIndex, _, err := selectVM.Run()\n\tcheck.CheckErr(err, \"\")\n\treturn VMlist[selectedVMIndex], nil\n\n}", "func (group *Group) Rand() Node {\n\trand.Seed(time.Now().Unix()) // initialize global pseudo random generator\n\n\treturn group.items[rand.Intn(group.Count())]\n}", "func (api *API) ProxyGetByProxy(proxy string) (res *Proxy, err error) {\n\tproxies, err := api.ProxiesGet(Params{\"filter\": map[string]string{\"proxy\": proxy}})\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(proxies) == 1 {\n\t\tres = &proxies[0]\n\t} else {\n\t\te := ExpectedOneResult(len(proxies))\n\t\terr = &e\n\t}\n\treturn\n}", "func (inst Instance) GetRandomSpawnPortal() (Portal, error) {\n\tportals := []Portal{}\n\n\tfor _, p := range inst.portals {\n\t\tif p.name == \"sp\" {\n\t\t\tportals = append(portals, p)\n\t\t}\n\t}\n\n\tif len(portals) == 0 {\n\t\treturn Portal{}, fmt.Errorf(\"No spawn portals in map\")\n\t}\n\n\treturn portals[rand.Intn(len(portals))], nil\n}", "func NewProxy(maxLoadTestsRun int, registry backends.Registry, kubeClient *kube.Client, maxListLimit int64, allowedCustomImages bool) *Proxy {\n\treturn &Proxy{\n\t\tmaxLoadTestsRun: maxLoadTestsRun,\n\t\tregistry: registry,\n\t\tkubeClient: kubeClient,\n\t\tmaxListLimit: maxListLimit,\n\t\tallowedCustomImages: allowedCustomImages,\n\t}\n}", "func RandPort(lo, hi int) int {\n\treturn lo + rand.Intn(hi-lo)\n}", "func randStr(l int) string {\n\tbytes := make([]byte, l)\n\tfor i := 0; i < l; i++ {\n\t\tbytes[i] = pool[rand.Intn(len(pool))]\n\t}\n\treturn string(bytes)\n}", "func (p *Point) Rand(max float64) *Point {\n\tdist := rand.Float64() * max\n\trad := rand.Float64() * math.Pi * 2\n\treturn &Point{\n\t\tX: p.X + dist*math.Cos(rad),\n\t\tY: p.Y + dist*math.Sin(rad),\n\t}\n}", "func Random() Balancer {\n\tlogger.Debugf(\"Creating Random balancer\")\n\treturn func(peers []fab.Peer) []fab.Peer {\n\t\tlogger.Debugf(\"Load balancing %d peers using Random strategy...\", len(peers))\n\n\t\tbalancedPeers := make([]fab.Peer, len(peers))\n\t\tfor i, index := range rand.Perm(len(peers)) {\n\t\t\tbalancedPeers[i] = peers[index]\n\t\t}\n\t\treturn balancedPeers\n\t}\n}", "func Rand(r *rand.Rand) func(*config) {\n\treturn func(c *config) { c.rand = r }\n}", "func GetRandomUserAgent() string {\n\treturn uaPool[r.Intn(len(uaPool))]\n}", "func DefaultProxies(qtumRPCClient *qtum.Qtum, agent *notifier.Agent) []ETHProxy {\n\tfilter := eth.NewFilterSimulator()\n\tgetFilterChanges := &ProxyETHGetFilterChanges{Qtum: qtumRPCClient, filter: filter}\n\tethCall := &ProxyETHCall{Qtum: qtumRPCClient}\n\n\tethProxies := []ETHProxy{\n\t\tethCall,\n\t\t&ProxyNetListening{Qtum: qtumRPCClient},\n\t\t&ProxyETHPersonalUnlockAccount{},\n\t\t&ProxyETHChainId{Qtum: qtumRPCClient},\n\t\t&ProxyETHBlockNumber{Qtum: qtumRPCClient},\n\t\t&ProxyETHHashrate{Qtum: qtumRPCClient},\n\t\t&ProxyETHMining{Qtum: qtumRPCClient},\n\t\t&ProxyETHNetVersion{Qtum: qtumRPCClient},\n\t\t&ProxyETHGetTransactionByHash{Qtum: qtumRPCClient},\n\t\t&ProxyETHGetTransactionByBlockNumberAndIndex{Qtum: qtumRPCClient},\n\t\t&ProxyETHGetLogs{Qtum: qtumRPCClient},\n\t\t&ProxyETHGetTransactionReceipt{Qtum: qtumRPCClient},\n\t\t&ProxyETHSendTransaction{Qtum: qtumRPCClient},\n\t\t&ProxyETHAccounts{Qtum: qtumRPCClient},\n\t\t&ProxyETHGetCode{Qtum: qtumRPCClient},\n\n\t\t&ProxyETHNewFilter{Qtum: qtumRPCClient, filter: filter},\n\t\t&ProxyETHNewBlockFilter{Qtum: qtumRPCClient, filter: filter},\n\t\tgetFilterChanges,\n\t\t&ProxyETHGetFilterLogs{ProxyETHGetFilterChanges: getFilterChanges},\n\t\t&ProxyETHUninstallFilter{Qtum: qtumRPCClient, filter: filter},\n\n\t\t&ProxyETHEstimateGas{ProxyETHCall: ethCall},\n\t\t&ProxyETHGetBlockByNumber{Qtum: qtumRPCClient},\n\t\t&ProxyETHGetBlockByHash{Qtum: qtumRPCClient},\n\t\t&ProxyETHGetBalance{Qtum: qtumRPCClient},\n\t\t&ProxyETHGetStorageAt{Qtum: qtumRPCClient},\n\t\t&ETHGetCompilers{},\n\t\t&ETHProtocolVersion{},\n\t\t&ETHGetUncleByBlockHashAndIndex{},\n\t\t&ETHGetUncleCountByBlockHash{},\n\t\t&ETHGetUncleCountByBlockNumber{},\n\t\t&Web3ClientVersion{},\n\t\t&Web3Sha3{},\n\t\t&ProxyETHSign{Qtum: qtumRPCClient},\n\t\t&ProxyETHGasPrice{Qtum: qtumRPCClient},\n\t\t&ProxyETHTxCount{Qtum: qtumRPCClient},\n\t\t&ProxyETHSignTransaction{Qtum: qtumRPCClient},\n\t\t&ProxyETHSendRawTransaction{Qtum: qtumRPCClient},\n\n\t\t&ETHSubscribe{Qtum: qtumRPCClient, Agent: agent},\n\t\t&ETHUnsubscribe{Qtum: qtumRPCClient, Agent: agent},\n\n\t\t&ProxyQTUMGetUTXOs{Qtum: qtumRPCClient},\n\t\t&ProxyQTUMGenerateToAddress{Qtum: qtumRPCClient},\n\n\t\t&ProxyNetPeerCount{Qtum: qtumRPCClient},\n\t}\n\n\tpermittedQtumCalls := []string{\n\t\tqtum.MethodGetHexAddress,\n\t\tqtum.MethodFromHexAddress,\n\t}\n\n\tfor _, qtumMethod := range permittedQtumCalls {\n\t\tethProxies = append(\n\t\t\tethProxies,\n\t\t\t&ProxyQTUMGenericStringArguments{\n\t\t\t\tQtum: qtumRPCClient,\n\t\t\t\tprefix: \"dev\",\n\t\t\t\tmethod: qtumMethod,\n\t\t\t},\n\t\t)\n\t}\n\n\treturn ethProxies\n}", "func (q QuoteSlice) Random() QuoteType {\n\treturn q[rand.Intn(len(q))]\n}", "func (pl *Peerlist) randomExchg(count int, includePrivate bool) []Peer {\n\tkeys := []string{}\n\n\tif includePrivate {\n\t\tkeys = pl.getAllExchgAddr()\n\t} else {\n\t\tkeys = pl.getExchgAddr(false)\n\t}\n\n\tif len(keys) == 0 {\n\t\treturn make([]Peer, 0)\n\t}\n\n\tmax := count\n\tif count == 0 || count > len(keys) {\n\t\tmax = len(keys)\n\t}\n\n\tpeers := make([]Peer, 0, max)\n\tperm := rand.Perm(len(keys))\n\tfor _, i := range perm[:max] {\n\t\tpeers = append(peers, *pl.peers[keys[i]])\n\t}\n\n\treturn peers\n}", "func TorProxy() func(*http.Request) (*url.URL, error) {\n\t// a source of uniformly-distributed pseudo-random\n\trand.Seed(time.Now().UnixNano())\n\t// pseudo-random int value\n\tnum := rand.Intn(0x7fffffff-10000) + 10000\n\t// base url localhost for now\n\tbase := \"socks5://%d:[email protected]:9050\"\n\t// proxy url with random credentials\n\trawUrl := fmt.Sprintf(base, num)\n\t// parse proxy url\n\tproxyUrl, err := url.Parse(rawUrl)\n\tif err != nil {\n\t\tfmt.Println(\"invalid url to parse when creating proxy transport. err: \", err)\n\t\treturn nil\n\t}\n\t// setup proxy transport\n\tproxy := http.ProxyURL(proxyUrl)\n\n\treturn proxy\n}", "func randChoice(list []string) string {\n randIndex := rand.Intn(len(list))\n return list[randIndex]\n}", "func RandomRoute(client RpcClient, nodeType string, msg RpcMsg, cb Callback) {\n\tlist := client.NodeMap[nodeType]\n\tif list == nil || len(list) < 1 {\n\t\tcb(cherryUtils.Errorf(\"rpc servers not exist with nodeType:%s\", nodeType), \"\")\n\t\treturn\n\t}\n\n\tindex := int(math.Floor(float64(rand.Int() * len(list))))\n\tcb(nil, list[index])\n}", "func RandomFortune(mod string) (*Fortune, error) {\n\tconn := Pool.Get()\n\tdefer conn.Close()\n\n\t// ensure the specified module exists\n\tif mod != \"\" {\n\t\tmember, err := redis.Bool(conn.Do(\"SISMEMBER\", MODS_KEY, mod))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif member == false {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"module '%s' not found\", mod))\n\t\t}\n\t}\n\n\tif mod == \"\" {\n\t\tmod2, err := redis.String(conn.Do(\"SRANDMEMBER\", MODS_KEY))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmod = mod2\n\t}\n\n\tfid, err := redis.Int(conn.Do(\"SRANDMEMBER\", modKey(mod)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttext, err := redis.String(conn.Do(\"GET\", fortuneKey(fid)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Fortune{mod: mod, id: fid, text: text}, nil\n}", "func RandomFloat64(values ...float64) float64 {\n\tif len(values) == 0 {\n\t\treturn 0\n\t}\n\tif len(values) == 1 {\n\t\treturn values[0]\n\t}\n\treturn values[provider.Intn(len(values))]\n}", "func (p *Manager) GiveMeProxy() Proxy {\n\tp.Lock() // Diğer goroutines'lerin erişmesini engelleyelim.\n\tdefer p.Unlock() // İşlem bittikten sonra erişim engelini kaldıralım\n\n\tdefer func(p *Manager) {\n\t\tp.StepIndex++\n\t\tif p.StepIndex == p.Limit {\n\t\t\tp.StepIndex = 0\n\t\t\tp.ReadIndex++\n\t\t}\n\t}(p)\n\tif p.ReadIndex >= p.WriteIndex {\n\t\tp.ReadIndex = 0\n\t}\n\n\treturn p.List[p.ReadIndex]\n}", "func (m *MockIRepository) Random(amount int) ([]aggregates.Topic, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Random\", amount)\n\tret0, _ := ret[0].([]aggregates.Topic)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mem *Member) PickRandMemberIP() net.IP {\n\tif len(mem.membershipList) == 1 {\n\t\t// you are the only process in the list\n\t\treturn nil\n\t}\n\n\t// loop until you find a member that isn't your own\n\tfor {\n\t\ti := 0\n\t\trandVal := rand.Intn(len(mem.membershipList))\n\t\tvar randEntry membershipListEntry\n\t\tfor _, v := range mem.membershipList {\n\t\t\tif i == randVal {\n\t\t\t\trandEntry = v\n\t\t\t}\n\n\t\t\ti++\n\t\t}\n\n\t\tif randEntry.MemberID != mem.memberID {\n\t\t\treturn randEntry.IPaddr\n\t\t}\n\t}\n\treturn nil\n}", "func (ws *WhanauServer) GetRandomServers(args *SystolicMixingArgs,\n\treply *SystolicMixingReply) error {\n\t// send over the servers to the systolic mixing process\n\t//fmt.Printf(\"server %v got getrandom from server %v at ts %d\\n\",\n\t//\tws.me, args.SenderAddr, args.Timestep)\n\n\tws.recv_chan <- args\n\n\treply.Err = OK\n\treturn nil\n}", "func (ipgen *ipgenerator) randIp(cidr *net.IPNet) (net.IP, error) {\n\trand.Seed(time.Now().UnixNano())\n\tnewIp := *new(net.IP)\n\tfor i := 0; i < 4; i++ {\n\t\tnewIp = append(newIp, byte(rand.Intn(256))&^cidr.Mask[i]|cidr.IP[i])\n\t}\n\tif !cidr.Contains(newIp) {\n\t\treturn nil, fmt.Errorf(\"random IP generation failed\")\n\t}\n\treturn newIp, nil\n}", "func (manager *Manager) InitializeProxies() {\n\tlog := logging.For(\"core/proxy/init\").WithField(\"func\", \"proxy\")\n\tlog.Info(\"Initializing Proxies\")\n\n\t// Lock proxies for writing\n\tproxies.Lock()\n\tconfig.Lock()\n\tdefer proxies.Unlock()\n\tdefer config.Unlock()\n\n\t//copy loadbalancer pool\n\tloadbalancer := make(map[string]config.LoadbalancePool)\n\tfor poolname, pool := range config.GetNoLock().Loadbalancer.Pools {\n\t\tloadbalancer[poolname] = pool\n\t}\n\n\t// First time setup, start handler in background\n\tif len(proxies.pool) == 0 {\n\t\tgo manager.ProxyHandler()\n\t}\n\n\t// Get all existing proxies, and trim them to keep removableProxy list\n\tremovableProxies := make(map[string]*proxy.Listener)\n\tfor poolname, pool := range proxies.pool {\n\t\tremovableProxies[poolname] = pool\n\t}\n\n\t// Loop through pools -> proxy vip's\n\tfor poolname, pool := range loadbalancer {\n\t\tvar newProxy *proxy.Listener\n\n\t\tplog := log.WithField(\"pool\", poolname)\n\n\t\tif pool.Listener.IP == \"\" {\n\t\t\tplog.Debug(\"No listener IP for pool, skipping proxy\")\n\t\t\tcontinue\n\t\t}\n\n\t\tif existingProxy, ok := proxies.pool[poolname]; ok {\n\t\t\tplog.Debug(\"Existing proxy\")\n\t\t\t// Proxy already exists\n\t\t\t// See if we have a reason to stop it\n\n\t\t\texistingTLS := existingProxy.TLSConfig\n\t\t\t//newTLS := &tls.Config{}\n\t\t\tnewTLS, err := tlsconfig.LoadCertificate(pool.Listener.TLSConfig)\n\t\t\tif err != nil {\n\t\t\t\tplog.Warn(\"Error loading certificate\")\n\t\t\t}\n\n\t\t\t// We must go through backends in the same order each run\n\t\t\t// maps however are random, so:\n\t\t\t// lets get all backend names\n\t\t\t// order them alfabeticaly\n\t\t\t// loop over that to add Certificates\n\t\t\tvar backendSorted []string\n\t\t\tfor backendName := range pool.Backends {\n\t\t\t\tbackendSorted = append(backendSorted, backendName)\n\t\t\t}\n\t\t\tsort.Strings(backendSorted)\n\n\t\t\tfor _, backendName := range backendSorted {\n\t\t\t\tif pool.Backends[backendName].TLSConfig.CertificateFile != \"\" {\n\t\t\t\t\ttlsconfig.AddCertificate(pool.Backends[backendName].TLSConfig, newTLS)\n\t\t\t\t\tlog.Debugf(\"ADDCERT: adding cert for %s\", backendName)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Update listener if the below changed\n\t\t\tlistenerChanged := existingProxy.ListenerMode != pool.Listener.Mode ||\n\t\t\t\texistingProxy.IP != pool.Listener.IP ||\n\t\t\t\texistingProxy.Port != pool.Listener.Port ||\n\t\t\t\texistingProxy.MaxConnections != pool.Listener.MaxConnections ||\n\t\t\t\texistingProxy.ReadTimeout != pool.Listener.ReadTimeout ||\n\t\t\t\texistingProxy.WriteTimeout != pool.Listener.WriteTimeout ||\n\t\t\t\texistingProxy.OCSPStapling != pool.Listener.OCSPStapling ||\n\t\t\t\t!reflect.DeepEqual(existingTLS.CipherSuites, newTLS.CipherSuites) ||\n\t\t\t\t!reflect.DeepEqual(existingTLS.CurvePreferences, newTLS.CurvePreferences) ||\n\t\t\t\t!reflect.DeepEqual(existingTLS.Certificates, newTLS.Certificates) ||\n\t\t\t\texistingTLS.ClientAuth != newTLS.ClientAuth\n\n\t\t\t// Has listener changed?\n\t\t\tif listenerChanged {\n\t\t\t\t// Interface changes, we need to restart the proxy, lets stop it\n\t\t\t\tcertchange := !reflect.DeepEqual(existingTLS.Certificates, newTLS.Certificates)\n\t\t\t\tlog.WithField(\"pool\", poolname).Debugf(\"listener changed - mode:%t ip:%t port:%t, maxcon:%t readtimeout:%t writetimeout:%t ocsp:%t cert:%t cypher:%t curve:%t clientauth:%t\",\n\t\t\t\t\texistingProxy.ListenerMode != pool.Listener.Mode,\n\t\t\t\t\texistingProxy.IP != pool.Listener.IP,\n\t\t\t\t\texistingProxy.Port != pool.Listener.Port,\n\t\t\t\t\texistingProxy.MaxConnections != pool.Listener.MaxConnections,\n\t\t\t\t\texistingProxy.ReadTimeout != pool.Listener.ReadTimeout,\n\t\t\t\t\texistingProxy.WriteTimeout != pool.Listener.WriteTimeout,\n\t\t\t\t\texistingProxy.OCSPStapling != pool.Listener.OCSPStapling,\n\t\t\t\t\tcertchange,\n\t\t\t\t\t!reflect.DeepEqual(existingTLS.CipherSuites, newTLS.CipherSuites),\n\t\t\t\t\t!reflect.DeepEqual(existingTLS.CurvePreferences, newTLS.CurvePreferences),\n\t\t\t\t\texistingTLS.ClientAuth != newTLS.ClientAuth)\n\t\t\t\tlog.WithField(\"pool\", poolname).Info(\"Restarting existing proxy for new listener settings\")\n\t\t\t\texistingProxy.Stop()\n\t\t\t\texistingProxy.SetListener(pool.Listener.Mode, pool.Listener.SourceIP, pool.Listener.IP, pool.Listener.Port, pool.Listener.MaxConnections, newTLS, pool.Listener.ReadTimeout, pool.Listener.WriteTimeout, pool.Listener.HTTPProto, pool.Listener.OCSPStapling)\n\t\t\t\tgo existingProxy.Start()\n\t\t\t}\n\n\t\t\t// Continue with new proxy\n\t\t\tnewProxy = existingProxy\n\t\t\t// Do not remove this proxy\n\t\t\tdelete(removableProxies, poolname)\n\n\t\t} else {\n\t\t\t// We have a non existing proxy, setup a new one\n\t\t\tclog := log.WithField(\"ip\", pool.Listener.IP).WithField(\"port\", pool.Listener.Port).WithField(\"mode\", pool.Listener.Mode).WithField(\"pool\", poolname)\n\t\t\tclog.Debug(\"Creating new proxy\")\n\n\t\t\th := sha256.New()\n\t\t\th.Write([]byte(fmt.Sprintf(\"%s-%s-%s-%d\", poolname, pool.Listener.Mode, pool.Listener.IP, pool.Listener.Port)))\n\t\t\tuuid := fmt.Sprintf(\"%x\", h.Sum(nil))\n\t\t\tnewProxy = proxy.New(uuid, poolname, pool.Listener.MaxConnections)\n\n\t\t\tnewTLS, err := tlsconfig.LoadCertificate(pool.Listener.TLSConfig)\n\t\t\tif err != nil {\n\t\t\t\tplog.Warn(\"Error loading certificate\")\n\t\t\t}\n\n\t\t\tvar backendSorted []string\n\t\t\tfor backendName := range pool.Backends {\n\t\t\t\tbackendSorted = append(backendSorted, backendName)\n\t\t\t}\n\n\t\t\tsort.Strings(backendSorted)\n\n\t\t\tfor _, backendName := range backendSorted {\n\t\t\t\tif pool.Backends[backendName].TLSConfig.CertificateFile != \"\" {\n\t\t\t\t\ttlsconfig.AddCertificate(pool.Backends[backendName].TLSConfig, newTLS)\n\t\t\t\t\tlog.Debugf(\"ADDCERT: adding cert for %s\", backendName)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnewProxy.SetListener(pool.Listener.Mode, pool.Listener.SourceIP, pool.Listener.IP, pool.Listener.Port, pool.Listener.MaxConnections, newTLS, pool.Listener.ReadTimeout, pool.Listener.WriteTimeout, pool.Listener.HTTPProto, pool.Listener.OCSPStapling)\n\t\t\tgo newProxy.Start()\n\t\t\t// Register new proxy\n\t\t\tproxies.pool[poolname] = newProxy\n\t\t\tclog.Debug(\"Proxy listener started\")\n\t\t}\n\n\t\t// We now have a proxy listener ready and working, lets add its config dynamicly\n\n\t\t// Get all existing backends, we remove the ones that remain and were not configured\n\t\t//var removableBackends map[string]*proxy.Backend\n\t\tremovableBackends := make(map[string]*proxy.Backend)\n\t\tfor backendname, backendpool := range newProxy.Backends {\n\t\t\tremovableBackends[backendname] = backendpool\n\t\t}\n\n\t\tif err := newProxy.LoadErrorPage(pool.ErrorPage); err != nil {\n\t\t\t// This is checked when loading the config\n\t\t\tplog.WithField(\"file\", pool.ErrorPage.File).WithError(err).Warn(\"Unable to load Error page\")\n\t\t}\n\n\t\tif err := newProxy.LoadMaintenancePage(pool.MaintenancePage); err != nil {\n\t\t\t// This is checked when loading the config\n\t\t\tplog.WithField(\"file\", pool.MaintenancePage.File).WithError(err).Warn(\"Unable to load Maintenance page\")\n\t\t}\n\n\t\t//log.Debugf(\"proxy:%s Proxy has the following backends before init:%+v\", poolname, removableBackends)\n\t\tfor bid := range removableBackends {\n\t\t\tplog.WithField(\"backend\", bid).Debug(\"Backend before init\")\n\t\t}\n\n\t\t// Add ACL's from pool to backend\n\t\t// Backend already has its own acl's , we just merge them\n\t\tfor backendname, backendpool := range pool.Backends {\n\n\t\t\t// unmark the ones we have in our config, to not be removed\n\t\t\tif _, ok := removableBackends[backendname]; ok {\n\t\t\t\tdelete(removableBackends, backendname)\n\t\t\t\tplog.WithField(\"backend\", backendname).Debug(\"Marking backend to keep\")\n\t\t\t}\n\n\t\t\t// Add backend (will merge if exists)\n\t\t\tplog.WithField(\"backend\", backendname).Info(\"Adding/Updating backend\")\n\t\t\tnewProxy.UpdateBackend(backendpool.UUID, backendname, backendpool.BalanceMode.Method, backendpool.ConnectMode, backendpool.HostNames, pool.Listener.MaxConnections, backendpool.ErrorPage, backendpool.MaintenancePage)\n\n\t\t\t// Use backend to attach acl's\n\t\t\tbackend := newProxy.Backends[backendname]\n\n\t\t\tvar inboundACLs []proxy.ACL\n\t\t\tvar outboundACLs []proxy.ACL\n\n\t\t\t// Add pool ACL's\n\t\t\tfor _, acl := range pool.InboundACL {\n\t\t\t\tinboundACLs = append(inboundACLs, acl)\n\t\t\t}\n\t\t\tfor _, acl := range pool.OutboundACL {\n\t\t\t\toutboundACLs = append(outboundACLs, acl)\n\t\t\t}\n\t\t\t// Add backend ACL's\n\t\t\tfor _, acl := range backendpool.InboundACL {\n\t\t\t\tinboundACLs = append(inboundACLs, acl)\n\t\t\t}\n\t\t\tfor _, acl := range backendpool.OutboundACL {\n\t\t\t\toutboundACLs = append(outboundACLs, acl)\n\t\t\t}\n\t\t\t// Replace existing acls with new one\n\t\t\tif !reflect.DeepEqual(backend.InboundACL, inboundACLs) {\n\t\t\t\tfor _, acl := range inboundACLs {\n\t\t\t\t\tplog.WithField(\"backend\", backendname).WithField(\"acl\", fmt.Sprintf(\"%+v\", acl)).Debug(\"Setting inbound ACL\")\n\t\t\t\t}\n\t\t\t\tbackend.SetACL(\"in\", inboundACLs)\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(backend.OutboundACL, outboundACLs) {\n\t\t\t\tfor _, acl := range inboundACLs {\n\t\t\t\t\tplog.WithField(\"backend\", backendname).WithField(\"acl\", fmt.Sprintf(\"%+v\", acl)).Debug(\"Setting outbound ACL\")\n\t\t\t\t}\n\t\t\t\tbackend.SetACL(\"out\", outboundACLs)\n\t\t\t}\n\n\t\t\t// Use backend to attach rules\n\t\t\tvar preinboundrules []string\n\t\t\tvar inboundrules []string\n\t\t\tvar outboundrules []string\n\n\t\t\t// Add pool rules\n\t\t\tfor _, acl := range pool.PreInboundRule {\n\t\t\t\tpreinboundrules = append(preinboundrules, acl)\n\t\t\t}\n\t\t\tfor _, acl := range pool.InboundRule {\n\t\t\t\tinboundrules = append(inboundrules, acl)\n\t\t\t}\n\t\t\tfor _, acl := range pool.OutboundRule {\n\t\t\t\toutboundrules = append(outboundrules, acl)\n\t\t\t}\n\t\t\t// Add backend rules\n\t\t\tfor _, acl := range backendpool.PreInboundRule {\n\t\t\t\tpreinboundrules = append(preinboundrules, acl)\n\t\t\t}\n\t\t\tfor _, acl := range backendpool.InboundRule {\n\t\t\t\tinboundrules = append(inboundrules, acl)\n\t\t\t}\n\t\t\tfor _, acl := range backendpool.OutboundRule {\n\t\t\t\toutboundrules = append(outboundrules, acl)\n\t\t\t}\n\n\t\t\t// Replace existing rules with new one\n\t\t\tif !reflect.DeepEqual(backend.PreInboundRule, preinboundrules) {\n\t\t\t\tfor _, rule := range preinboundrules {\n\t\t\t\t\tplog.WithField(\"backend\", backendname).WithField(\"rule\", fmt.Sprintf(\"%s\", rule)).Debug(\"Setting pre-inbound Rule\")\n\t\t\t\t}\n\t\t\t\tbackend.SetRules(\"prein\", inboundrules)\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(backend.InboundRule, inboundrules) {\n\t\t\t\tfor _, rule := range inboundrules {\n\t\t\t\t\tplog.WithField(\"backend\", backendname).WithField(\"rule\", fmt.Sprintf(\"%s\", rule)).Debug(\"Setting inbound Rule\")\n\t\t\t\t}\n\t\t\t\tbackend.SetRules(\"in\", inboundrules)\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(backend.OutboundRule, outboundrules) {\n\t\t\t\tfor _, rule := range inboundrules {\n\t\t\t\t\tplog.WithField(\"backend\", backendname).WithField(\"rule\", fmt.Sprintf(\"%s\", rule)).Debug(\"Setting outbound Rule\")\n\t\t\t\t}\n\t\t\t\tbackend.SetRules(\"out\", outboundrules)\n\t\t\t}\n\n\t\t\t// Check backend Nodes\n\t\t\t// IF node is local check with local config\n\t\t\t// IF node is remote update of removal should be sent at config loading\n\t\t\tif nodes, err := backend.GetBackendsUUID(); err != nil {\n\t\t\t\tfor _, nodeid := range nodes {\n\t\t\t\t\tfound := false\n\t\t\t\t\tfor _, node := range backendpool.Nodes {\n\t\t\t\t\t\tif nodeid == node.UUID {\n\t\t\t\t\t\t\tfound = true\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif found == false {\n\t\t\t\t\t\tplog.WithField(\"backend\", backendname).WithField(\"uuid\", nodeid).Debug(\"Backend node longer exists in config\")\n\t\t\t\t\t\tbackend.RemoveNodeByID(nodeid)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t} // end of backend loop\n\n\t\t// Remove all backends which remained on the removableBackends\n\t\t// these are no longer configured and should be removed\n\t\tfor backendName := range removableBackends {\n\t\t\tplog.WithField(\"backend\", backendName).Info(\"Removing unused backend\")\n\t\t\tnewProxy.RemoveBackend(backendName)\n\t\t}\n\n\t} // end of pool loop\n\n\t// Remove all proxies which remained on the removableProxies listeners\n\t// these are no longer configured and should be removeHeader\n\tfor proxyName, proxy := range removableProxies {\n\t\tlog.WithField(\"pool\", proxyName).Info(\"Stopping unused proxy\")\n\t\tproxy.Stop()\n\t\tdelete(proxies.pool, proxyName)\n\t}\n\n}", "func (a *Alien) RandomWalk() {\n\tneighbors := a.City.GetNeighbors()\n\tif len(neighbors) > 0 {\n\t\tchoice := rand.Intn(len(neighbors))\n\t\ta.City = neighbors[choice]\n\t}\n}", "func NewProxy(\n\ttenant *clients.Tenant, wit clients.WIT, idler clients.IdlerService,\n\tstorageService storage.Store,\n\tconfig configuration.Configuration,\n\tclusters map[string]string) (Proxy, error) {\n\n\tp := Proxy{\n\t\tTenantCache: cache.New(30*time.Minute, 40*time.Minute),\n\t\tProxyCache: cache.New(15*time.Minute, 10*time.Minute),\n\t\tvisitLock: &sync.Mutex{},\n\t\ttenant: tenant,\n\t\twit: wit,\n\t\tidler: idler,\n\t\tbufferCheckSleep: 30 * time.Second,\n\t\tredirect: config.GetRedirectURL(),\n\t\tresponseTimeout: config.GetGatewayTimeout(),\n\t\tauthURL: config.GetAuthURL(),\n\t\tstorageService: storageService,\n\t\tindexPath: config.GetIndexPath(),\n\t\tmaxRequestRetry: config.GetMaxRequestRetry(),\n\t\tclusters: clusters,\n\t}\n\n\t//Initialize metrics\n\tRecorder.Initialize()\n\n\t//Spawn a routine to process buffered requests\n\tgo func() {\n\t\tp.ProcessBuffer()\n\t}()\n\treturn p, nil\n}", "func (p *BeersPlugin) randomReply(c bot.Connector, channel string) {\n\treplies := []string{\"ZIGGY! ZAGGY!\", \"HIC!\", \"Stay thirsty, my friend!\"}\n\tp.b.Send(c, bot.Message, channel, replies[rand.Intn(len(replies))])\n}", "func (c *namespaceCluster) RandLeaderRegion(storeID uint64, opts ...core.RegionOption) *core.RegionInfo {\n\tfor i := 0; i < randRegionMaxRetry; i++ {\n\t\tr := c.Cluster.RandLeaderRegion(storeID, opts...)\n\t\tif r == nil {\n\t\t\treturn nil\n\t\t}\n\t\tif c.checkRegion(r) {\n\t\t\treturn r\n\t\t}\n\t}\n\treturn nil\n}", "func NewRandomRouter(addrs ...Addr) *RandomRouter {\n\tvar service ServiceSet\n\tset := NewRandomSet()\n\n\tfor _, addr := range addrs {\n\t\tservice.Add(addr)\n\t\tset.Add(addr.Addr())\n\t}\n\n\treturn &RandomRouter{\n\t\trand: set,\n\t\taddrs: &service,\n\t}\n}", "func RandomReceiver(receivers []string) string {\n\trand.Seed(time.Now().Unix())\n\treceiver := receivers[rand.Intn(len(receivers))]\n\n\treturn receiver\n}", "func (n *Normal) Rand(x []float64) []float64 {\n\tx = reuseAs(x, n.dim)\n\ttmp := make([]float64, n.dim)\n\tif n.src == nil {\n\t\tfor i := range x {\n\t\t\ttmp[i] = rand.NormFloat64()\n\t\t}\n\t} else {\n\t\tfor i := range x {\n\t\t\ttmp[i] = n.src.NormFloat64()\n\t\t}\n\t}\n\ttmpVec := mat64.NewVector(n.dim, tmp)\n\txVec := mat64.NewVector(n.dim, x)\n\txVec.MulVec(n.chol, true, tmpVec)\n\tfloats.Add(x, n.mu)\n\treturn x\n}", "func ChooseRandomCity(cs []*world.WorldCity) (*world.WorldCity, error) {\n\tif len(cs) == 0 {\n\t\treturn nil, errors.New(\"no cities to choose from\")\n\t}\n\n\ti := rand.Intn(len(cs))\n\treturn cs[i], nil\n}", "func RandomIP() string {\n\treturn fmt.Sprintf(\"%d.%d.%d.%d\", rand.Intn(256), rand.Intn(256), rand.Intn(256), rand.Intn(256))\n}", "func (set Set) RandomMembers(ctx context.Context, count int64) ([]string, error) {\n\treq := newRequestSize(int(1+count), \"\\r\\n$11\\r\\nSRANDMEMBER\\r\\n$\")\n\treq.addStringInt(set.name, count)\n\treturn set.c.cmdStrings(ctx, req)\n}", "func GenStrategyRandom(typ Type, seed int) interface{} {\n\treturn newRandomNumber(typ)\n}", "func Shuffle(slice interface{}) {\n\trv := reflect.ValueOf(slice)\n\tswap := reflect.Swapper(slice)\n\tlength := rv.Len()\n\tfor i := length - 1; i > 0; i-- {\n\t\tj := rand.Intn(i + 1)\n\t\tswap(i, j)\n\t}\n}", "func (indis Individuals) sample(n int, generator *rand.Rand) Individuals {\n\tvar sample = indis.shuffle(generator)[:n]\n\treturn sample\n}", "func (pool *ComplexPool) Fetch() error {\n\tlogger.Debugf(\"prox (%p): attempting to fetch proxies from providers\", pool)\n\tcollector := providers.NewSet()\n\n\tfor _, provider := range pool.providers {\n\n\t\tps, err := provider.InternalProvider(collector, pool.timeout)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\n\t\t}\n\n\t\tfor _, p := range ps {\n\t\t\tpool.All.Add(p)\n\n\t\t\tif !pool.Unused.In(p) {\n\t\t\t\tpool.Unused.Add(p)\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif len(collector.All()) == 0 {\n\t\tlogger.Errorf(\"prox (%p): no proxies could be loaded from providers\", pool)\n\t\treturn fmt.Errorf(\"prox (%p): no proxies could be loaded from providers\", pool)\n\t}\n\n\tlogger.Debugf(\"prox (%p): fetched %d proxies\", pool, len(collector.All()))\n\tlogger.Debugf(\"prox (%p): updating cache with new proxies\", pool)\n\tpool.CacheAvailable = true\n\tpool.CacheAll = pool.All\n\tpool.CacheUnused = pool.Unused\n\n\treturn nil\n}", "func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int {}", "func (a *Agent) loadProxies(conf *config.RuntimeConfig) error {\n\tpersistedProxies, persistenceErr := a.loadPersistedProxies()\n\n\tfor _, svc := range conf.Services {\n\t\tif svc.Connect != nil {\n\t\t\tproxy, err := svc.ConnectManagedProxy()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed adding proxy: %s\", err)\n\t\t\t}\n\t\t\tif proxy == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trestoredToken := \"\"\n\t\t\tif persisted, ok := persistedProxies[proxy.TargetServiceID]; ok {\n\t\t\t\trestoredToken = persisted.ProxyToken\n\t\t\t}\n\n\t\t\tif err := a.addProxyLocked(proxy, true, true, restoredToken, ConfigSourceLocal); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed adding proxy: %s\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, persisted := range persistedProxies {\n\t\tproxyID := persisted.Proxy.ProxyService.ID\n\t\tif persisted.FromFile && a.State.Proxy(proxyID) == nil {\n\t\t\t// Purge proxies that were configured previously but are no longer in the config\n\t\t\ta.logger.Printf(\"[DEBUG] agent: purging stale persisted proxy %q\", proxyID)\n\t\t\tif err := a.purgeProxy(proxyID); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed purging proxy %q: %v\", proxyID, err)\n\t\t\t}\n\t\t} else if !persisted.FromFile {\n\t\t\tif a.State.Proxy(proxyID) == nil {\n\t\t\t\ta.logger.Printf(\"[DEBUG] agent: restored proxy definition %q\", proxyID)\n\t\t\t\tif err := a.addProxyLocked(persisted.Proxy, false, false, persisted.ProxyToken, ConfigSourceLocal); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed adding proxy %q: %v\", proxyID, err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ta.logger.Printf(\"[WARN] agent: proxy definition %q was overwritten by a proxy definition within a config file\", proxyID)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn persistenceErr\n}", "func NewRoundRobin(proxies ...*proxy.Proxy) Iterator {\n\tbunch := make(commonProxiesBunch, 0, len(proxies))\n\tfor _, p := range proxies {\n\t\tbunch = append(bunch, p)\n\t}\n\treturn &RoundRobin{\n\t\tproxies: bunch,\n\t\tcurrent: -1,\n\t}\n}", "func (h *Host) NextProxy() *httputil.ReverseProxy {\n\treturn <-h.proxyChannel\n}", "func randIntn(n int) int {\n\treturn prng.Intn(n)\n}", "func createRandomTour(cities []City) Tour {\n randomCities := make([]City, len(cities) + 1)\n randomOrder := rand.Perm(len(cities) - 1)\n\n first := cities[0]\n randomCities[0] = first\n var length uint64\n idx := 1\n for _, randomCityIdx := range randomOrder {\n nextCity := cities[randomCityIdx + 1]\n randomCities[idx] = nextCity\n length += nextCity.Distance(randomCities[idx - 1])\n idx++\n }\n randomCities[idx] = first\n length += first.Distance(randomCities[idx - 1])\n\n return Tour{randomCities, length}\n}", "func (state *State) getRandomPeer(avoid ...string) (*Peer, error) {\n\tstate.lock_peers.Lock()\n\tdefer state.lock_peers.Unlock()\n\n\trestricted := make(map[string]bool)\n\tfor _, a := range avoid {\n\t\trestricted[a] = true\n\t}\n\tvar peers []string\n\tfor _, name := range state.list_peers {\n\t\tif _, ok := restricted[name]; !ok {\n\t\t\tpeers = append(peers, name)\n\t\t}\n\t}\n\n\tif len(peers) == 0 {\n\t\treturn nil, errors.New(\"No peer to select from\")\n\t}\n\tk := rand.Intn(len(peers))\n\tname := peers[k]\n\treturn state.known_peers[name], nil\n}", "func ShuffleRandom(servers []types.DatabaseServer) []types.DatabaseServer {\n\trand.New(rand.NewSource(time.Now().UnixNano())).Shuffle(\n\t\tlen(servers), func(i, j int) {\n\t\t\tservers[i], servers[j] = servers[j], servers[i]\n\t\t})\n\treturn servers\n}", "func Random(amount int, from []Soil) []Soil {\n\tvar soil Soil\n\n\tsoils := []Soil{}\n\n\tif amount > len(from) {\n\t\tamount = len(from)\n\t}\n\n\tif len(from) == 0 {\n\t\treturn soils\n\t}\n\n\tfor i := 0; i < amount; i++ {\n\t\tsoil = from[rand.Intn(len(from))]\n\t\tif !InSlice(soil, soils) {\n\t\t\tsoils = append(soils, soil)\n\t\t}\n\t}\n\n\treturn soils\n}", "func randomize(it graph.Nodes, src rand.Source) graph.Nodes {\n\tnodes := graph.NodesOf(it)\n\tvar shuffle func(int, func(i, j int))\n\tif src == nil {\n\t\tshuffle = rand.Shuffle\n\t} else {\n\t\tshuffle = rand.New(src).Shuffle\n\t}\n\tshuffle(len(nodes), func(i, j int) {\n\t\tnodes[i], nodes[j] = nodes[j], nodes[i]\n\t})\n\treturn iterator.NewOrderedNodes(nodes)\n}", "func makeHTTPClient(proxyURL *url.URL, options *HTTPOptions) *retryablehttp.Client {\n\t// Multiple Host\n\tretryablehttpOptions := retryablehttp.DefaultOptionsSpraying\n\tdisableKeepAlives := true\n\tmaxIdleConns := 0\n\tmaxConnsPerHost := 0\n\tmaxIdleConnsPerHost := -1\n\n\tif options.BulkHTTPRequest.Threads > 0 {\n\t\t// Single host\n\t\tretryablehttpOptions = retryablehttp.DefaultOptionsSingle\n\t\tdisableKeepAlives = false\n\t\tmaxIdleConnsPerHost = 500\n\t\tmaxConnsPerHost = 500\n\t}\n\n\tretryablehttpOptions.RetryWaitMax = 10 * time.Second\n\tretryablehttpOptions.RetryMax = options.Retries\n\tfollowRedirects := options.BulkHTTPRequest.Redirects\n\tmaxRedirects := options.BulkHTTPRequest.MaxRedirects\n\n\ttransport := &http.Transport{\n\t\tDialContext: options.Dialer.Dial,\n\t\tMaxIdleConns: maxIdleConns,\n\t\tMaxIdleConnsPerHost: maxIdleConnsPerHost,\n\t\tMaxConnsPerHost: maxConnsPerHost,\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tRenegotiation: tls.RenegotiateOnceAsClient,\n\t\t\tInsecureSkipVerify: true,\n\t\t},\n\t\tDisableKeepAlives: disableKeepAlives,\n\t}\n\n\t// Attempts to overwrite the dial function with the socks proxied version\n\tif options.ProxySocksURL != \"\" {\n\t\tvar proxyAuth *proxy.Auth\n\n\t\tsocksURL, err := url.Parse(options.ProxySocksURL)\n\n\t\tif err == nil {\n\t\t\tproxyAuth = &proxy.Auth{}\n\t\t\tproxyAuth.User = socksURL.User.Username()\n\t\t\tproxyAuth.Password, _ = socksURL.User.Password()\n\t\t}\n\n\t\tdialer, err := proxy.SOCKS5(\"tcp\", fmt.Sprintf(\"%s:%s\", socksURL.Hostname(), socksURL.Port()), proxyAuth, proxy.Direct)\n\t\tdc := dialer.(interface {\n\t\t\tDialContext(ctx context.Context, network, addr string) (net.Conn, error)\n\t\t})\n\n\t\tif err == nil {\n\t\t\ttransport.DialContext = dc.DialContext\n\t\t}\n\t}\n\n\tif proxyURL != nil {\n\t\ttransport.Proxy = http.ProxyURL(proxyURL)\n\t}\n\n\treturn retryablehttp.NewWithHTTPClient(&http.Client{\n\t\tTransport: transport,\n\t\tTimeout: time.Duration(options.Timeout) * time.Second,\n\t\tCheckRedirect: makeCheckRedirectFunc(followRedirects, maxRedirects),\n\t}, retryablehttpOptions)\n}", "func (c combinatorics) RandomFloat64(values []float64) float64 {\n\tif len(values) == 0 {\n\t\treturn 0\n\t}\n\tif len(values) == 1 {\n\t\treturn values[0]\n\t}\n\treturn values[RandomProvider().Intn(len(values))]\n}", "func get_random_name() (name string) {\n rand.Seed(time.Now().UnixNano())\n names := []string{\n \"Bob\", \"Jane\", \"John\", \"Rob\",\n }\n name = names[rand.Intn(len(names))]\n return\n}", "func NewProxy(opts ...options.Option) proxy.Proxy {\n\tp := new(Proxy)\n\tp.Links = map[string]client.Client{}\n\tp.Options = options.NewOptions(opts...)\n\tp.Options.Init(options.WithString(\"mucp\"))\n\n\t// get endpoint\n\tep, ok := p.Options.Values().Get(\"proxy.endpoint\")\n\tif ok {\n\t\tp.Endpoint = ep.(string)\n\t}\n\n\t// get client\n\tc, ok := p.Options.Values().Get(\"proxy.client\")\n\tif ok {\n\t\tp.Client = c.(client.Client)\n\t}\n\n\t// set the default client\n\tif p.Client == nil {\n\t\tp.Client = mucp.NewClient()\n\t}\n\n\t// get client\n\tlinks, ok := p.Options.Values().Get(\"proxy.links\")\n\tif ok {\n\t\tp.Links = links.(map[string]client.Client)\n\t}\n\n\t// get router\n\tr, ok := p.Options.Values().Get(\"proxy.router\")\n\tif ok {\n\t\tp.Router = r.(router.Router)\n\t}\n\n\t// create default router and start it\n\tif p.Router == nil {\n\t\tp.Router = router.DefaultRouter\n\t}\n\n\t// routes cache\n\tp.Routes = make(map[string]map[uint64]router.Route)\n\n\tgo func() {\n\t\t// continuously attempt to watch routes\n\t\tfor {\n\t\t\t// watch the routes\n\t\t\tp.watchRoutes()\n\t\t\t// in case of failure just wait a second\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t}()\n\n\tgo func() {\n\t\t// TODO: speed up refreshing of metrics\n\t\t// without this ticking effort e.g stream\n\t\tt := time.NewTicker(time.Second * 10)\n\t\tdefer t.Stop()\n\n\t\t// we must refresh route metrics since they do not trigger new events\n\t\tfor range t.C {\n\t\t\t// refresh route metrics\n\t\t\tp.refreshMetrics()\n\t\t}\n\t}()\n\n\treturn p\n}", "func randomPick(rnd *rand.Rand, list []string, n int) (picked []string) {\n\tfor i := 0; i < n; i++ {\n\t\tindex := rnd.Intn(len(list))\n\t\tpicked = append(picked, list[index])\n\t\tlist = append(list[:index], list[index+1:]...)\n\t}\n\treturn\n}", "func (h *Handler) fakeClaimsForProxy(c *gin.Context) (*auth.JWTClaims, error) {\n\tuid := c.GetHeader(util.GetConfig().Proxy.UserHeader)\n\tlogrus.Debugf(\"Got proxy uid '%s' from header '%s'\", uid, util.GetConfig().Proxy.UserHeader)\n\tif uid == \"\" {\n\t\tlogrus.Debugf(\"No proxy uid found!\")\n\t\tif util.GetConfig().Proxy.RequireUserHeader {\n\t\t\tmsg := fmt.Sprintf(\"Required authorization header not set: %s\", util.GetConfig().Proxy.UserHeader)\n\t\t\tlogrus.Error(msg)\n\t\t\treturn nil, errors.New(msg)\n\t\t}\n\t\tlogrus.Debugf(\"Setting uid to 'anonymous'\")\n\t\tuid = \"anonymous\"\n\t}\n\t// optionally pick a display name out of the headers as well; if we\n\t// can't find it, just use the uid.\n\tdisplayName := c.GetHeader(util.GetConfig().Proxy.DisplayNameHeader)\n\tlogrus.Debugf(\"Got proxy display name '%s' from header '%s'\", displayName, util.GetConfig().Proxy.DisplayNameHeader)\n\tif displayName == \"\" {\n\t\tlogrus.Debugf(\"Setting displayname to '%s'\", uid)\n\t\tdisplayName = uid\n\t}\n\t// it's not actually oauth but the naming convention is too\n\t// deeply embedded in the code for it to be worth changing.\n\tclaims := &auth.JWTClaims{\n\t\tOAuthID: uid,\n\t\tOAuthName: displayName,\n\t\tOAuthPicture: \"/images/proxy_user.png\",\n\t\tOAuthProvider: \"proxy\",\n\t}\n\treturn claims, nil\n}", "func randomWinner(src rand.Source, input []string) string {\n\tr := rand.New(src)\n\treturn input[r.Intn(len(input))]\n}", "func randomWinner(src rand.Source, input []string) string {\n\tr := rand.New(src)\n\treturn input[r.Intn(len(input))]\n}", "func newProxy(pType ProxyType) (proxy, error) {\n\tswitch pType {\n\tcase NoopProxyType:\n\t\treturn &noopProxy{}, nil\n\tcase CCProxyType:\n\t\treturn &ccProxy{}, nil\n\tdefault:\n\t\treturn &noopProxy{}, nil\n\t}\n}", "func randomSetup(r *rand.Rand, numCandidates int) (Pool, Candidates) {\n\tpool := Pool{\n\t\tTotalSupply: 0,\n\t\tBondedShares: sdk.ZeroRat(),\n\t\tUnbondedShares: sdk.ZeroRat(),\n\t\tBondedPool: 0,\n\t\tUnbondedPool: 0,\n\t\tInflationLastTime: 0,\n\t\tInflation: sdk.NewRat(7, 100),\n\t}\n\n\tcandidates := make([]Candidate, numCandidates)\n\tfor i := 0; i < numCandidates; i++ {\n\t\tcandidate := randomCandidate(r)\n\t\tif candidate.Status == Bonded {\n\t\t\tpool.BondedShares = pool.BondedShares.Add(candidate.Assets)\n\t\t\tpool.BondedPool += candidate.Assets.Evaluate()\n\t\t} else if candidate.Status == Unbonded {\n\t\t\tpool.UnbondedShares = pool.UnbondedShares.Add(candidate.Assets)\n\t\t\tpool.UnbondedPool += candidate.Assets.Evaluate()\n\t\t}\n\t\tcandidates[i] = candidate\n\t}\n\treturn pool, candidates\n}", "func (d *Core) GetRandomHosts(nHosts int) ([]string, error) {\n\treturn getRandomHosts(nHosts, d.Scale)\n}", "func RandUA() string {\n\tidx := rand.Intn(uaLen)\n\treturn uaList[idx]\n}", "func NewProxy(opts ...ProxyOption) (*Proxy, error) {\n\tvar err error\n\tp := Proxy{\n\t\tHeaders: http.Header{},\n\t}\n\tfor _, opt := range opts {\n\t\tif err = opt(&p); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &p, nil\n}", "func (lb *RandomLoadBalancer) OneOf(addrs []Address) Address {\n\tr := rand.Rand(*lb)\n\treturn addrs[r.Intn(len(addrs))]\n}", "func (joinSession *JoinSession) randomPublisher() uint32 {\n\ti := 0\n\tvar publisher uint32\n\trandIndex := rand.Intn(len(joinSession.Peers))\n\tfor _, peer := range joinSession.Peers {\n\t\tif i == randIndex {\n\t\t\tpublisher = peer.Id\n\t\t\tbreak\n\t\t}\n\t\ti++\n\t}\n\treturn publisher\n}", "func createRandomAccounts(accNum int) []sdk.AccAddress {\n\ttestAddrs := make([]sdk.AccAddress, accNum)\n\tfor i := 0; i < accNum; i++ {\n\t\tpk := ed25519.GenPrivKey().PubKey()\n\t\ttestAddrs[i] = sdk.AccAddress(pk.Address())\n\t}\n\n\treturn testAddrs\n}", "func (z *Perplex) Generate(rand *rand.Rand, size int) reflect.Value {\n\trandomPerplex := &Perplex{\n\t\t*big.NewInt(rand.Int63()),\n\t\t*big.NewInt(rand.Int63()),\n\t}\n\treturn reflect.ValueOf(randomPerplex)\n}", "func gen(typ interface{}, rand *rand.Rand) interface{} {\n\tv, ok := quick.Value(reflect.TypeOf(typ), rand)\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"couldn't generate random value of type %T\", typ))\n\t}\n\treturn v.Interface()\n}", "func Providers() map[string]provider.ProxyProvider {\n\treturn providers\n}", "func ProxiesFromDailyProxy() []string {\n\tresp, err := http.Get(\"https://proxy-daily.com/\")\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer resp.Body.Close()\n\tdoc, err := goquery.NewDocumentFromReader(resp.Body)\n\tif err != nil {\n\t\treturn nil\n\t}\n\thttpList := doc.Find(\".centeredProxyList.freeProxyStyle\").First().Text()\n\tproxies := ipPortRegex.FindAllString(httpList, -1)\n\treturn proxies\n}", "func (o ProviderOutput) HttpProxy() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Provider) pulumi.StringPtrOutput { return v.HttpProxy }).(pulumi.StringPtrOutput)\n}", "func GetProxies() map[int]*Endpoint {\n\treturn proxies\n}", "func (p Pareto) Rand() float64 {\n\tvar rnd float64\n\tif p.Src == nil {\n\t\trnd = rand.ExpFloat64()\n\t} else {\n\t\trnd = rand.New(p.Src).ExpFloat64()\n\t}\n\treturn p.Xm * math.Exp(rnd/p.Alpha)\n}", "func getRandomNeighbour(neighbours *Neighbours, prevPoint Point) Point {\n\tswitch len(*neighbours) {\n\tcase 0:\n\t\treturn Point{0, 0}\n\tcase 1:\n\t\treturn (*neighbours)[0]\n\tcase 2:\n\t\tif (*neighbours)[1] == prevPoint {\n\t\t\treturn (*neighbours)[0]\n\t\t} else {\n\t\t\treturn (*neighbours)[1]\n\t\t}\n\tdefault:\n\t\tidx := rand.Int() % len(*neighbours)\n\t\tfor (*neighbours)[idx] == prevPoint {\n\t\t\tidx = rand.Int() % len(*neighbours)\n\t\t}\n\n\t\treturn (*neighbours)[idx]\n\t}\n}", "func Random() string {\n\treturn names[\"all\"][rand.Intn(len(names[\"all\"]))]\n}" ]
[ "0.7494706", "0.7436685", "0.72388667", "0.70245457", "0.6505623", "0.58470386", "0.58146083", "0.5790712", "0.56759715", "0.5599842", "0.5534545", "0.54924244", "0.548021", "0.53984475", "0.5289549", "0.5278287", "0.52765566", "0.5242049", "0.51393646", "0.512822", "0.5128184", "0.5087103", "0.50845724", "0.5052879", "0.5040447", "0.5028522", "0.5024578", "0.5022663", "0.50077033", "0.49874118", "0.49847704", "0.4969548", "0.4945206", "0.49306703", "0.49296385", "0.4920263", "0.49085838", "0.4896731", "0.4884557", "0.4879091", "0.48719835", "0.48652053", "0.48606622", "0.48563445", "0.4855848", "0.4850519", "0.48481604", "0.48392034", "0.4826138", "0.4823694", "0.48183528", "0.4800823", "0.4794083", "0.4792739", "0.4779458", "0.47711575", "0.47708204", "0.4765381", "0.47601664", "0.4755921", "0.4753269", "0.47531334", "0.47420302", "0.47411188", "0.47186583", "0.47158688", "0.4715834", "0.47142893", "0.47053602", "0.47042137", "0.47031906", "0.4699359", "0.4698172", "0.46871668", "0.46783757", "0.46696118", "0.46685007", "0.46640998", "0.46601444", "0.46590292", "0.46513712", "0.46500462", "0.46500462", "0.46484846", "0.46482942", "0.46427733", "0.46241924", "0.4623783", "0.4623248", "0.46221057", "0.46174833", "0.4616287", "0.46140748", "0.4610011", "0.45984507", "0.45983386", "0.45950946", "0.45900443", "0.45897573", "0.45816547" ]
0.8410278
0
NewClient returns a retryablehttp.Client configured to use a random proxy
func (p Provider) NewClient(req *retryablehttp.Request, opts RetryOptions) (*retryablehttp.Client, string, error) { proxy := p.RandProxy() proxyURL, err := url.ParseRequestURI(fmt.Sprintf("http://%s:%s", proxy.IP, proxy.PortNum)) if err != nil { return &retryablehttp.Client{}, "", fmt.Errorf("%v", err) } client := retryablehttp.NewClient() client.Logger = nil client.RetryMax = opts.Max client.RetryWaitMax = time.Second * time.Duration(opts.WaitMaxSecs) client.RetryWaitMin = time.Second * time.Duration(opts.WaitMinSecs) client.Backoff = func(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration { return (time.Second * time.Duration(opts.BackoffStepSecs)) * time.Duration((attemptNum)) } client.HTTPClient = &http.Client{ Timeout: (5 * time.Second), Transport: &http.Transport{ Proxy: http.ProxyURL(proxyURL), ProxyConnectHeader: req.Header, }} return client, proxy.IP, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newHTTPClient(cfg *Config) (*http.Client, error) {\n\t// Configure proxy if needed.\n\tvar dial func(network, addr string) (net.Conn, error)\n\tif cfg.Proxy != \"\" {\n\t\tproxy := &socks.Proxy{\n\t\t\tAddr: cfg.Proxy,\n\t\t\tUsername: cfg.ProxyUser,\n\t\t\tPassword: cfg.ProxyPass,\n\t\t}\n\t\tdial = func(network, addr string) (net.Conn, error) {\n\t\t\tc, err := proxy.Dial(network, addr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn c, nil\n\t\t}\n\t}\n\n\t// Configure TLS if needed.\n\tvar tlsConfig *tls.Config\n\tif !cfg.NoTLS {\n\t\ttlsConfig = &tls.Config{\n\t\t\tInsecureSkipVerify: cfg.TLSSkipVerify,\n\t\t}\n\t\tif !cfg.TLSSkipVerify && cfg.RPCCert != \"\" {\n\t\t\tpem, err := ioutil.ReadFile(cfg.RPCCert)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tpool := x509.NewCertPool()\n\t\t\tif ok := pool.AppendCertsFromPEM(pem); !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid certificate file: %v\",\n\t\t\t\t\tcfg.RPCCert)\n\t\t\t}\n\t\t\ttlsConfig.RootCAs = pool\n\t\t}\n\t}\n\n\ttimeout, _ := time.ParseDuration(\"30s\")\n\n\t// Create and return the new HTTP client potentially configured with a\n\t// proxy and TLS.\n\tclient := http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tDial: dial,\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t},\n\t\tTimeout: timeout,\n\t}\n\treturn &client, nil\n}", "func (r *Request) newClient() *http.Client {\n\treturn &http.Client{Timeout: r.timeout}\n}", "func NewClient(transport *http.Transport, proxyFlag string, timeout int) (*http.Client, error) {\n\tif proxyFlag != \"\" {\n\t\treturn getProxyHTTP(proxyFlag, transport)\n\t}\n\n\treturn getHTTP(transport, timeout)\n}", "func NewProxyClient(proxy string) *http.Client {\n\tc := *http.DefaultClient\n\tc.Transport = &http.Transport{\n\t\tProxy: newProxyFunc(proxy),\n\t\t// copy from \"net/http\".DefaultTransport\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout: 30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t\tDualStack: true,\n\t\t}).DialContext,\n\t\tMaxIdleConns: 100,\n\t\tIdleConnTimeout: 90 * time.Second,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t}\n\treturn &c\n}", "func NewClient(options *ClientOptions, customHTTPClient *http.Client,\r\n\tcustomEnvironment string) (c *Client) {\r\n\r\n\t// Create a client\r\n\tc = new(Client)\r\n\r\n\t// Set options (either default or user modified)\r\n\tif options == nil {\r\n\t\toptions = DefaultClientOptions()\r\n\t}\r\n\r\n\t// Set the options\r\n\tc.Options = options\r\n\r\n\t// Set the environment\r\n\tvar found bool\r\n\tif c.Environment, found = environments[customEnvironment]; !found {\r\n\t\tc.Environment = environments[EnvironmentProduction]\r\n\t}\r\n\r\n\t// Is there a custom HTTP client to use?\r\n\tif customHTTPClient != nil {\r\n\t\tc.httpClient = customHTTPClient\r\n\t\treturn\r\n\t}\r\n\r\n\t// dial is the net dialer for clientDefaultTransport\r\n\tdial := &net.Dialer{KeepAlive: options.DialerKeepAlive, Timeout: options.DialerTimeout}\r\n\r\n\t// clientDefaultTransport is the default transport struct for the HTTP client\r\n\tclientDefaultTransport := &http.Transport{\r\n\t\tDialContext: dial.DialContext,\r\n\t\tExpectContinueTimeout: options.TransportExpectContinueTimeout,\r\n\t\tIdleConnTimeout: options.TransportIdleTimeout,\r\n\t\tMaxIdleConns: options.TransportMaxIdleConnections,\r\n\t\tProxy: http.ProxyFromEnvironment,\r\n\t\tTLSHandshakeTimeout: options.TransportTLSHandshakeTimeout,\r\n\t}\r\n\r\n\t// Determine the strategy for the http client\r\n\tif options.RequestRetryCount <= 0 {\r\n\r\n\t\t// no retry enabled\r\n\t\tc.httpClient = httpclient.NewClient(\r\n\t\t\thttpclient.WithHTTPTimeout(options.RequestTimeout),\r\n\t\t\thttpclient.WithHTTPClient(&http.Client{\r\n\t\t\t\tTransport: clientDefaultTransport,\r\n\t\t\t\tTimeout: options.RequestTimeout,\r\n\t\t\t}),\r\n\t\t)\r\n\t\treturn\r\n\t}\r\n\r\n\t// Retry enabled - create exponential back-off\r\n\tc.httpClient = httpclient.NewClient(\r\n\t\thttpclient.WithHTTPTimeout(options.RequestTimeout),\r\n\t\thttpclient.WithRetrier(heimdall.NewRetrier(\r\n\t\t\theimdall.NewExponentialBackoff(\r\n\t\t\t\toptions.BackOffInitialTimeout,\r\n\t\t\t\toptions.BackOffMaxTimeout,\r\n\t\t\t\toptions.BackOffExponentFactor,\r\n\t\t\t\toptions.BackOffMaximumJitterInterval,\r\n\t\t\t))),\r\n\t\thttpclient.WithRetryCount(options.RequestRetryCount),\r\n\t\thttpclient.WithHTTPClient(&http.Client{\r\n\t\t\tTransport: clientDefaultTransport,\r\n\t\t\tTimeout: options.RequestTimeout,\r\n\t\t}),\r\n\t)\r\n\r\n\treturn\r\n}", "func newMockClient(doer func(*http.Request) (*http.Response, error)) *http.Client {\n\tv := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout: 30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t\tDualStack: true,\n\t\t}).DialContext,\n\t\tMaxIdleConns: 100,\n\t\tIdleConnTimeout: 90 * time.Second,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t}\n\tv.RegisterProtocol(\"http\", transportFunc(doer))\n\treturn &http.Client{\n\t\tTransport: http.RoundTripper(v),\n\t}\n}", "func NewClient() *Client {\n baseURL, _ := url.Parse(defaultBaseURL)\n return &Client{client: http.DefaultClient, BaseURL: baseURL, UserAgent: userAgent}\n}", "func NewClient(baseurl string) *Client {\n\treturn &Client{\n\t\tbaseurl: baseurl,\n\t\tclient: &http.Client{Timeout: 20 * time.Second},\n\t}\n}", "func makeHTTPClient(proxyURL *url.URL, options *HTTPOptions) *retryablehttp.Client {\n\t// Multiple Host\n\tretryablehttpOptions := retryablehttp.DefaultOptionsSpraying\n\tdisableKeepAlives := true\n\tmaxIdleConns := 0\n\tmaxConnsPerHost := 0\n\tmaxIdleConnsPerHost := -1\n\n\tif options.BulkHTTPRequest.Threads > 0 {\n\t\t// Single host\n\t\tretryablehttpOptions = retryablehttp.DefaultOptionsSingle\n\t\tdisableKeepAlives = false\n\t\tmaxIdleConnsPerHost = 500\n\t\tmaxConnsPerHost = 500\n\t}\n\n\tretryablehttpOptions.RetryWaitMax = 10 * time.Second\n\tretryablehttpOptions.RetryMax = options.Retries\n\tfollowRedirects := options.BulkHTTPRequest.Redirects\n\tmaxRedirects := options.BulkHTTPRequest.MaxRedirects\n\n\ttransport := &http.Transport{\n\t\tDialContext: options.Dialer.Dial,\n\t\tMaxIdleConns: maxIdleConns,\n\t\tMaxIdleConnsPerHost: maxIdleConnsPerHost,\n\t\tMaxConnsPerHost: maxConnsPerHost,\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tRenegotiation: tls.RenegotiateOnceAsClient,\n\t\t\tInsecureSkipVerify: true,\n\t\t},\n\t\tDisableKeepAlives: disableKeepAlives,\n\t}\n\n\t// Attempts to overwrite the dial function with the socks proxied version\n\tif options.ProxySocksURL != \"\" {\n\t\tvar proxyAuth *proxy.Auth\n\n\t\tsocksURL, err := url.Parse(options.ProxySocksURL)\n\n\t\tif err == nil {\n\t\t\tproxyAuth = &proxy.Auth{}\n\t\t\tproxyAuth.User = socksURL.User.Username()\n\t\t\tproxyAuth.Password, _ = socksURL.User.Password()\n\t\t}\n\n\t\tdialer, err := proxy.SOCKS5(\"tcp\", fmt.Sprintf(\"%s:%s\", socksURL.Hostname(), socksURL.Port()), proxyAuth, proxy.Direct)\n\t\tdc := dialer.(interface {\n\t\t\tDialContext(ctx context.Context, network, addr string) (net.Conn, error)\n\t\t})\n\n\t\tif err == nil {\n\t\t\ttransport.DialContext = dc.DialContext\n\t\t}\n\t}\n\n\tif proxyURL != nil {\n\t\ttransport.Proxy = http.ProxyURL(proxyURL)\n\t}\n\n\treturn retryablehttp.NewWithHTTPClient(&http.Client{\n\t\tTransport: transport,\n\t\tTimeout: time.Duration(options.Timeout) * time.Second,\n\t\tCheckRedirect: makeCheckRedirectFunc(followRedirects, maxRedirects),\n\t}, retryablehttpOptions)\n}", "func (rpc *RpcClient) newHTTPClient() (*http.Client, error) {\n\t// Configure proxy if needed.\n\tvar dial func(network, addr string) (net.Conn, error)\n\tif rpc.Cfg.OptionConfig.Proxy != \"\" {\n\t\tproxy := &socks.Proxy{\n\t\t\tAddr: rpc.Cfg.OptionConfig.Proxy,\n\t\t\tUsername: rpc.Cfg.OptionConfig.ProxyUser,\n\t\t\tPassword: rpc.Cfg.OptionConfig.ProxyPass,\n\t\t}\n\t\tdial = func(network, addr string) (net.Conn, error) {\n\t\t\tc, err := proxy.Dial(network, addr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn c, nil\n\t\t}\n\t}\n\n\t// Configure TLS if needed.\n\tvar tlsConfig *tls.Config\n\tif !rpc.Cfg.SoloConfig.NoTLS && rpc.Cfg.SoloConfig.RPCCert != \"\" {\n\t\tpem, err := ioutil.ReadFile(rpc.Cfg.SoloConfig.RPCCert)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpool := x509.NewCertPool()\n\t\tpool.AppendCertsFromPEM(pem)\n\t\ttlsConfig = &tls.Config{\n\t\t\tRootCAs: pool,\n\t\t\tInsecureSkipVerify: rpc.Cfg.SoloConfig.NoTLS,\n\t\t}\n\t} else {\n\t\ttlsConfig = &tls.Config{\n\t\t\tInsecureSkipVerify: rpc.Cfg.SoloConfig.NoTLS,\n\t\t}\n\t}\n\n\t// Create and return the new HTTP client potentially configured with a\n\t// proxy and TLS.\n\tclient := http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tDial: dial,\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t\tDialContext: (&net.Dialer{\n\t\t\t\tTimeout: time.Duration(rpc.Cfg.OptionConfig.Timeout) * time.Second,\n\t\t\t\tKeepAlive: time.Duration(rpc.Cfg.OptionConfig.Timeout) * time.Second,\n\t\t\t\tDualStack: true,\n\t\t\t}).DialContext,\n\t\t},\n\t}\n\treturn &client, nil\n}", "func NewClient(maxRetries int, waitingTime int) *http.Client {\n\tclientretry := retryablehttp.NewClient()\n\tclientretry.RetryMax = maxRetries\n\tclientretry.RetryWaitMin = time.Duration(time.Duration(waitingTime) * time.Second)\n\tclientretry.RetryWaitMax = time.Duration(time.Duration(waitingTime) * time.Second)\n\n\treturn clientretry.StandardClient()\n}", "func newMockClient(doer func(*http.Request) (*http.Response, error)) *http.Client {\n\treturn &http.Client{\n\t\tTransport: transportFunc(doer),\n\t}\n}", "func createDefaultHTTPClient(c *Client) HTTPInterface {\n\n\t// dial is the net dialer for clientDefaultTransport\n\tdial := &net.Dialer{\n\t\tKeepAlive: c.options.httpOptions.DialerKeepAlive,\n\t\tTimeout: c.options.httpOptions.DialerTimeout,\n\t}\n\n\t// clientDefaultTransport is the default transport struct for the HTTP client\n\tclientDefaultTransport := &http.Transport{\n\t\tDialContext: dial.DialContext,\n\t\tExpectContinueTimeout: c.options.httpOptions.TransportExpectContinueTimeout,\n\t\tIdleConnTimeout: c.options.httpOptions.TransportIdleTimeout,\n\t\tMaxIdleConns: c.options.httpOptions.TransportMaxIdleConnections,\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tTLSHandshakeTimeout: c.options.httpOptions.TransportTLSHandshakeTimeout,\n\t}\n\n\t// Determine the strategy for the http client (no retry enabled)\n\tif c.options.httpOptions.RequestRetryCount <= 0 {\n\t\treturn httpclient.NewClient(\n\t\t\thttpclient.WithHTTPTimeout(c.options.httpOptions.RequestTimeout),\n\t\t\thttpclient.WithHTTPClient(&http.Client{\n\t\t\t\tTransport: clientDefaultTransport,\n\t\t\t\tTimeout: c.options.httpOptions.RequestTimeout,\n\t\t\t}),\n\t\t)\n\t}\n\n\t// Create exponential back-off\n\tbackOff := heimdall.NewExponentialBackoff(\n\t\tc.options.httpOptions.BackOffInitialTimeout,\n\t\tc.options.httpOptions.BackOffMaxTimeout,\n\t\tc.options.httpOptions.BackOffExponentFactor,\n\t\tc.options.httpOptions.BackOffMaximumJitterInterval,\n\t)\n\n\treturn httpclient.NewClient(\n\t\thttpclient.WithHTTPTimeout(c.options.httpOptions.RequestTimeout),\n\t\thttpclient.WithRetrier(heimdall.NewRetrier(backOff)),\n\t\thttpclient.WithRetryCount(c.options.httpOptions.RequestRetryCount),\n\t\thttpclient.WithHTTPClient(&http.Client{\n\t\t\tTransport: clientDefaultTransport,\n\t\t\tTimeout: c.options.httpOptions.RequestTimeout,\n\t\t}),\n\t)\n}", "func NewClient(token string, client *http.Client) *Client {\n\tif client == nil {\n\t\thttpClient = &http.Client{Timeout: time.Second * 10}\n\t} else {\n\t\thttpClient = client\n\t}\n\treturn &Client{token}\n}", "func newHTTPClient() *http.Client {\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tDialContext: (&net.Dialer{\n\t\t\t\tTimeout: timeout,\n\t\t\t\tKeepAlive: 30 * time.Second,\n\t\t\t\tDualStack: true,\n\t\t\t}).DialContext,\n\n\t\t\tTLSHandshakeTimeout: timeout,\n\t\t\tResponseHeaderTimeout: timeout,\n\t\t\tExpectContinueTimeout: 1 * time.Second,\n\t\t\tMaxIdleConns: 5,\n\t\t\tIdleConnTimeout: 90 * time.Second,\n\t\t},\n\t}\n}", "func New() Client {\n\tc := http.DefaultClient\n\tc.Timeout = time.Second * 10\n\n\treturn &client{c: c}\n}", "func New(addr string) *Client {\n\treturn &Client{\n\t\taddr: addr,\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: 1 * time.Minute,\n\t\t},\n\t}\n}", "func New(p policy) (*retryablehttp.Client, error) {\n\tlogger := p.CreateLogger()\n\n\tinnerHTTPClient, err := createInnerHTTPClient(logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thttpClient := retryablehttp.NewClient()\n\tp.ConfigureHTTP(httpClient)\n\n\thttpClient.Logger = loggerAdapter{logger}\n\thttpClient.HTTPClient = innerHTTPClient\n\n\treturn httpClient, nil\n}", "func NewClient(meta *metadata.Client, acc string) *http.Client {\n\treturn &http.Client{\n\t\tTransport: newRoundTripper(meta, acc),\n\t}\n}", "func NewClient(cacher Cacher) *Client {\n\tvar newClient Client\n\n\tnewClient.BaseURL = DefaultBaseURL\n\tnewClient.Retries = 5\n\tnewClient.cacher = cacher\n\tnewClient.maxIdleConns = 2\n\n\t// Also sets up our initial http client\n\tnewClient.SetTimeout(60 * time.Second)\n\n\tif client == nil {\n\t\tclient = &newClient\n\t}\n\treturn &newClient\n}", "func NewClient(logger log.Logger) *retryablehttp.Client {\n\tclient := retryablehttp.NewClient()\n\tclient.Logger = &httpLogAdaptor{logger: logger}\n\tclient.ErrorHandler = retryablehttp.PassthroughErrorHandler\n\n\treturn client\n}", "func NewClient() *Client {\n\tclient := &Client{\n\t\turl: baseURL,\n\t\thttpClient: &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tMaxConnsPerHost: maxConnsPerHost,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn client\n}", "func newHTTPClient() *http.Client {\n\tclient := &http.Client{\n\t\tTimeout: defaultTimeout,\n\t}\n\treturn client\n}", "func NewClient(config *cfg.ProxyConfig, cancel context.CancelFunc) (client *proxy.Client) {\n\tclient, _ = proxy.NewClient(config, ns, cancel)\n\treturn\n}", "func NewClient(config *cfg.ProxyConfig, cancel context.CancelFunc) (client *proxy.Client) {\n\tclient, _ = proxy.NewClient(config, ns, cancel)\n\treturn\n}", "func New(url string, httpClient *http.Client, customHeaders http.Header) *Client {\n\tif httpClient == nil {\n\t\thttpClient = &http.Client{\n\t\t\tTimeout: defaultHTTPTimeout,\n\t\t}\n\t}\n\n\treturn &Client{\n\t\turl: url,\n\t\thttpClient: httpClient,\n\t\tcustomHeaders: customHeaders,\n\t}\n}", "func newTestClient(fn RoundTripFunc) *http.Client {\n\treturn &http.Client{\n\t\tTransport: fn,\n\t}\n}", "func New() *Client {\n\treturn &Client{*http.DefaultClient, MaxSendAttempts}\n}", "func newTestClient(fn roundTripFunc) *http.Client {\n\treturn &http.Client{\n\t\tTransport: fn,\n\t}\n}", "func initClient() *http.Client {\n\treturn &http.Client{\n\t\tTimeout: time.Duration(timeout) * time.Second,\n\t\tTransport: &http.Transport{\n\t\t\tMaxIdleConns: 10,\n\t\t\tMaxIdleConnsPerHost: 10,\n\t\t\tMaxConnsPerHost: 10,\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: true,\n\t\t\t},\n\t\t},\n\t}\n}", "func NewClient(token string) *Client {\n\tc := &http.Client{\n\t\tTimeout: 10 * time.Second,\n\t}\n\treturn &Client{\n\t\tclient: c,\n\t\ttoken: token,\n\t\tAcceptHeader: DefaultAcceptHeader,\n\t}\n}", "func NewHTTPClient(proxyNetwork, proxyAddress string, serviceNetwork, service string) http.Client {\n\tproxyClient := Client{proxyNetwork: proxyNetwork, proxyAddress: proxyAddress, serviceNetwork: serviceNetwork, service: service}\n\ttrans := &http.Transport{\n\t\tDial: proxyClient.proxyDial,\n\t\tDisableKeepAlives: false,\n\t}\n\treturn http.Client{Transport: trans}\n}", "func (cf *clientFactory) newClient(authInfo *api.AuthInfo) (ClientInterface, error) {\n\tconfig := *cf.baseIstioConfig\n\n\tconfig.BearerToken = authInfo.Token\n\n\t// There is a feature when using OpenID strategy to allow using a proxy\n\t// for the cluster API. People may want to place a proxy in\n\t// front of the cluster API when using Kubernetes-as-a-service and\n\t// the provider does not support configuring OpenID integration.\n\t// If OpenID integration is not available, people may opt into\n\t// an API proxy (like kube-oidc-proxy) as a workaround for OIDC integration.\n\t// Clearly, under this scenario, the cluster API must be accessed\n\t// through the proxy (not directly).\n\t//\n\t// So, if OpenID strategy is active, check if a proxy is configured.\n\t// If there is, use it UNLESS the token is the one of the Kiali SA. If\n\t// the token is the one of the Kiali SA, the proxy can be bypassed.\n\tcfg := kialiConfig.Get()\n\tif cfg.Auth.Strategy == kialiConfig.AuthStrategyOpenId && cfg.Auth.OpenId.ApiProxy != \"\" && cfg.Auth.OpenId.ApiProxyCAData != \"\" {\n\t\tkialiToken, err := GetKialiToken()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif kialiToken != authInfo.Token {\n\t\t\t// Using `UseRemoteCreds` function as a helper\n\t\t\tapiProxyConfig, errProxy := UseRemoteCreds(&RemoteSecret{\n\t\t\t\tClusters: []RemoteSecretClusterListItem{\n\t\t\t\t\t{\n\t\t\t\t\t\tCluster: RemoteSecretCluster{\n\t\t\t\t\t\t\tCertificateAuthorityData: cfg.Auth.OpenId.ApiProxyCAData,\n\t\t\t\t\t\t\tServer: cfg.Auth.OpenId.ApiProxy,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tName: \"api_proxy\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t})\n\n\t\t\tif errProxy != nil {\n\t\t\t\treturn nil, errProxy\n\t\t\t}\n\n\t\t\tconfig.Host = apiProxyConfig.Host\n\t\t\tconfig.TLSClientConfig = apiProxyConfig.TLSClientConfig\n\t\t}\n\t}\n\n\t// Impersonation is valid only for header authentication strategy\n\tif cfg.Auth.Strategy == kialiConfig.AuthStrategyHeader && authInfo.Impersonate != \"\" {\n\t\tconfig.Impersonate.UserName = authInfo.Impersonate\n\t\tconfig.Impersonate.Groups = authInfo.ImpersonateGroups\n\t\tconfig.Impersonate.Extra = authInfo.ImpersonateUserExtra\n\t}\n\n\treturn NewClientFromConfig(&config)\n}", "func NewClient(s ClientSettings) (*Client, error) {\n\tproxy := http.ProxyFromEnvironment\n\tif s.Proxy != nil {\n\t\tproxy = http.ProxyURL(s.Proxy)\n\t}\n\tlogger.Info(\"HTTP URL: %s\", s.URL)\n\tvar dialer, tlsDialer transport.Dialer\n\tvar err error\n\n\tdialer = transport.NetDialer(s.Timeout)\n\ttlsDialer = transport.TLSDialer(dialer, s.TLS, s.Timeout)\n\n\tif st := s.Observer; st != nil {\n\t\tdialer = transport.StatsDialer(dialer, st)\n\t\ttlsDialer = transport.StatsDialer(tlsDialer, st)\n\t}\n\tparams := s.Parameters\n\tvar encoder bodyEncoder\n\tcompression := s.CompressionLevel\n\tif compression == 0 {\n\t\tswitch s.Format {\n\t\tcase \"json\":\n\t\t\tencoder = newJSONEncoder(nil)\n\t\tcase \"json_lines\":\n\t\t\tencoder = newJSONLinesEncoder(nil)\n\t\t}\n\t} else {\n\t\tswitch s.Format {\n\t\tcase \"json\":\n\t\t\tencoder, err = newGzipEncoder(compression, nil)\n\t\tcase \"json_lines\":\n\t\t\tencoder, err = newGzipLinesEncoder(compression, nil)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tclient := &Client{\n\t\tConnection: Connection{\n\t\t\tURL: s.URL,\n\t\t\tUsername: s.Username,\n\t\t\tPassword: s.Password,\n\t\t\tContentType: s.ContentType,\n\t\t\thttp: &http.Client{\n\t\t\t\tTransport: &http.Transport{\n\t\t\t\t\tDial: dialer.Dial,\n\t\t\t\t\tDialTLS: tlsDialer.Dial,\n\t\t\t\t\tProxy: proxy,\n\t\t\t\t},\n\t\t\t\tTimeout: s.Timeout,\n\t\t\t},\n\t\t\tencoder: encoder,\n\t\t},\n\t\tparams: params,\n\t\tcompressionLevel: compression,\n\t\tproxyURL: s.Proxy,\n\t\tbatchPublish: s.BatchPublish,\n\t\theaders: s.Headers,\n\t\tformat: s.Format,\n\t}\n\n\treturn client, nil\n}", "func NewClient() *http.Client {\n\treturn &http.Client{\n\t\tTimeout: 10 * time.Second,\n\t}\n}", "func createClient(options *Options) (c *Client) {\n\n\t// Create a client\n\tc = new(Client)\n\n\t// Set options (either default or user modified)\n\tif options == nil {\n\t\toptions = ClientDefaultOptions()\n\t}\n\n\t// dial is the net dialer for clientDefaultTransport\n\tdial := &net.Dialer{KeepAlive: options.DialerKeepAlive, Timeout: options.DialerTimeout}\n\n\t// clientDefaultTransport is the default transport struct for the HTTP client\n\tclientDefaultTransport := &http.Transport{\n\t\tDialContext: dial.DialContext,\n\t\tExpectContinueTimeout: options.TransportExpectContinueTimeout,\n\t\tIdleConnTimeout: options.TransportIdleTimeout,\n\t\tMaxIdleConns: options.TransportMaxIdleConnections,\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tTLSHandshakeTimeout: options.TransportTLSHandshakeTimeout,\n\t}\n\n\t// Determine the strategy for the http client (no retry enabled)\n\tif options.RequestRetryCount <= 0 {\n\t\tc.httpClient = httpclient.NewClient(\n\t\t\thttpclient.WithHTTPTimeout(options.RequestTimeout),\n\t\t\thttpclient.WithHTTPClient(&http.Client{\n\t\t\t\tTransport: clientDefaultTransport,\n\t\t\t\tTimeout: options.RequestTimeout,\n\t\t\t}),\n\t\t)\n\t} else { // Retry enabled\n\t\t// Create exponential back-off\n\t\tbackOff := heimdall.NewExponentialBackoff(\n\t\t\toptions.BackOffInitialTimeout,\n\t\t\toptions.BackOffMaxTimeout,\n\t\t\toptions.BackOffExponentFactor,\n\t\t\toptions.BackOffMaximumJitterInterval,\n\t\t)\n\n\t\tc.httpClient = httpclient.NewClient(\n\t\t\thttpclient.WithHTTPTimeout(options.RequestTimeout),\n\t\t\thttpclient.WithRetrier(heimdall.NewRetrier(backOff)),\n\t\t\thttpclient.WithRetryCount(options.RequestRetryCount),\n\t\t\thttpclient.WithHTTPClient(&http.Client{\n\t\t\t\tTransport: clientDefaultTransport,\n\t\t\t\tTimeout: options.RequestTimeout,\n\t\t\t}),\n\t\t)\n\t}\n\n\t// Create a last Request and parameters struct\n\tc.LastRequest = new(LastRequest)\n\tc.LastRequest.Error = new(Error)\n\tc.Parameters = &Parameters{\n\t\tUserAgent: options.UserAgent,\n\t}\n\treturn\n}", "func New() (client *Client) {\n\thttpClient := &http.Client{}\n\treturn &Client{\n\t\thttpClient: httpClient,\n\t\tTimeout: 0,\n\t\tDisableKeepAlives: true,\n\t\tIdleConnectionTimeout: 0,\n\t\ttransport: &http.Transport{},\n\t\tMaxRetriesOnError: 1,\n\t}\n}", "func NewMock(r ...MockResponse) *http.Client {\n\treturn &http.Client{\n\t\tTransport: newRoundTripper(r...),\n\t}\n}", "func (rpc *RpcClient) newHTTPClient() (*http.Client, error) {\n\t// Configure proxy if needed.\n\tvar dial func(network, addr string) (net.Conn, error)\n\n\t// Configure TLS if needed.\n\tvar tlsConfig *tls.Config\n\n\t// Create and return the new HTTP client potentially configured with a\n\t// proxy and TLS.\n\tclient := http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tDial: dial,\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t\tDialContext: (&net.Dialer{\n\t\t\t\tTimeout: 5 * time.Second,\n\t\t\t\tKeepAlive: 5 * time.Second,\n\t\t\t\tDualStack: true,\n\t\t\t}).DialContext,\n\t\t},\n\t}\n\treturn &client, nil\n}", "func NewHTTPClient() *http.Client {\n\n\ttr := &http.Transport{\n\t\t//TLSClientConfig: &tls.Config{\n\t\t//\tInsecureSkipVerify: conf.InsecureSkipVerify,\n\t\t//},\n\t\tMaxIdleConnsPerHost: DefaultMaxIdleConnsPerHost,\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout: DefaultTimeout,\n\t\t\tKeepAlive: DefaultKeepAlive,\n\t\t}).Dial,\n\t\tTLSHandshakeTimeout: DefaultTimeout,\n\t}\n\n\treturn &http.Client{\n\t\tTimeout: DefaultTimeout,\n\t\tTransport: tr,\n\t}\n}", "func newBaseClient() *baseClient {\n\treturn &baseClient{\n\t\thttpClient: http.DefaultClient,\n\t\tmethod: \"GET\",\n\t\theader: make(http.Header),\n\t}\n}", "func NewClient(token string) *Client {\n\treturn &Client{\n\t\tclient: &http.Client{},\n\t\ttoken: token,\n\t\tbase: githubBase,\n\t\tdry: false,\n\t}\n}", "func NewClient(addr net.Addr, opts *retry.Options, context *Context) *Client {\n\tclientMu.Lock()\n\tif !context.DisableCache {\n\t\tif c, ok := clients[addr.String()]; ok {\n\t\t\tclientMu.Unlock()\n\t\t\treturn c\n\t\t}\n\t}\n\tc := &Client{\n\t\taddr: addr,\n\t\tReady: make(chan struct{}),\n\t\tClosed: make(chan struct{}),\n\t\tclock: context.localClock,\n\t\tremoteClocks: context.RemoteClocks,\n\t\tcached: !context.DisableCache,\n\t}\n\tif !context.DisableCache {\n\t\tclients[c.Addr().String()] = c\n\t}\n\tclientMu.Unlock()\n\n\tgo c.connect(opts, context)\n\treturn c\n}", "func New(addr string) (*Client, error) {\n\treturn &Client{\n\t\taddr: addr,\n\t\thttpClient: &http.Client{},\n\t}, nil\n}", "func New(addr string) (*Client, error) {\n\treturn &Client{\n\t\taddr: addr,\n\t\thttpClient: &http.Client{},\n\t}, nil\n}", "func NewClient(config *Config) *Client {\n\ttr := config.Transport()\n\n\treturn &Client{\n\t\tconfig: config.Clone(),\n\t\ttr: tr,\n\t\tclient: &http.Client{Transport: tr},\n\t}\n}", "func NewClient(endpoints []string) (client.Client, error) {\n\tkey := strings.Join(endpoints, \",\")\n\tif cc, ok := clientCache[key]; ok {\n\t\treturn cc, nil\n\t}\n\n\tvar transport client.CancelableTransport = &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout: DEFALUT_CLIENT_TIMEOUT,\n\t\t\tKeepAlive: DEFAULT_CLIENT_KEEPALIVE,\n\t\t}).Dial,\n\t\tTLSHandshakeTimeout: DEFALUT_CLIENT_TLS_SHAKE_TIMEOUT,\n\t}\n\n\tcfg := client.Config{\n\t\tEndpoints: endpoints,\n\t\tTransport: transport,\n\t\t// set timeout per request to fail fast when the target endpoint is unavailable\n\t\tHeaderTimeoutPerRequest: time.Second,\n\t}\n\n\tclientNew, err := client.New(cfg)\n\t//03.11 Bug the client state is ok\n\tif err == nil {\n\t\tclientCache[key] = clientNew\n\t}\n\n\treturn clientNew, err\n}", "func New(opts ...ClientOption) *Client {\n\tc := &Client{\n\t\tName: \"retriable\",\n\t\thttpClient: &http.Client{\n\t\t\tTimeout: time.Second * 30,\n\t\t},\n\t\tPolicy: NewDefaultPolicy(),\n\t}\n\n\tfor _, opt := range opts {\n\t\topt.applyOption(c)\n\t}\n\treturn c\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\tbaseURL, _ := url.Parse(baseURL)\n\n\tc := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent}\n\tc.common.client = c\n\tc.RRSet = (*RRSetService)(&c.common)\n\tc.RData = (*RDataService)(&c.common)\n\n\treturn c\n}", "func NewClient(apiToken string) *Client {\n\tbaseURL, _ := url.Parse(defaultBaseURL)\n\n\treturn &Client{\n\t\tapiToken: apiToken,\n\t\tbaseURL: baseURL,\n\t\tHTTPClient: &http.Client{Timeout: 5 * time.Second},\n\t}\n}", "func New(httpClient *http.Client, config Config) (*Client, error) {\n\tc := NewClient(httpClient)\n\tc.Config = config\n\n\tbaseURL, err := url.Parse(\"https://\" + config.Host)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.BaseURL = baseURL\n\treturn c, nil\n}", "func New(url string) *Client {\n\treturn &Client{&http.Client{}, url, func(r *http.Request) *http.Request { return r }}\n}", "func NewClient(c *http.Client, baseURL *url.URL) *client {\n\treturn &client{\n\t\tbaseURL: baseURL,\n\t\tclient: c,\n\t}\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\tcloned := *http.DefaultClient\n\t\thttpClient = &cloned\n\t}\n\n\tbaseURL, _ := url.Parse(defaultBaseURL)\n\n\tc := &Client{\n\t\tclient: httpClient,\n\t\tBaseURL: baseURL,\n\t}\n\n\tc.common.client = c\n\tc.Question = (*QuestionService)(&c.common)\n\tc.Token = (*TokenService)(&c.common)\n\n\treturn c\n}", "func NewClient(reader io.Reader, confFunc configFunc) (*http.Client, error) {\n\tb, err := ioutil.ReadAll(reader)\n\tif err != nil {\n\t\tlog.Printf(\"Unable to read client secret file: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tconf, err := confFunc(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := getClient(conf)\n\treturn client, nil\n}", "func NewClient(httpClient *http.Client, URL string, Token string, Source string, SourceType string, Index string) (*Client) {\n\t// Create a new client\n\tif httpClient == nil {\n\t\ttr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} // turn off certificate checking\n\t\thttpClient = &http.Client{Timeout: time.Second * 20, Transport: tr}\n\t}\n\n\tc := &Client{HTTPClient: httpClient, URL: URL, Token: Token, Source: Source, SourceType: SourceType, Index: Index}\n\n\treturn c\n}", "func NewClient() *Client {\n\tvar client Client\n\ttr := &http.Transport{\n\t\tDisableCompression: true,\n\t\tProxy: http.ProxyFromEnvironment,\n\t}\n\n\tclient.client = &http.Client{Transport: tr}\n\tclient.UserAgent = fmt.Sprintf(\"KUTTL/%s\", strings.TrimPrefix(version.Get().GitVersion, \"v\"))\n\treturn &client\n}", "func NewHTTPClient(retries int) HTTPClient {\n\tif retries <= 0 {\n\t\tpanic(\"retries should be greater than 0\")\n\t}\n\treturn &httpClient{\n\t\tretries: retries,\n\t}\n}", "func TestNewHttpClient(t *testing.T) {\n\t// No proxy\n\tclient := NewHttpClient()\n\n\tresp, err := client.Get(\"http://check.torproject.org\")\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to issue GET request: %v\\n\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to read the body: %v\\n\", err)\n\t}\n\tif strings.Contains(string(body), \"Congratulations. This browser is configured to use Tor.\") {\n\t\tt.Error(\"Connected through proxy when we should not have\")\n\t}\n\n\t// With Proxy\n\tdialer, err = proxy.SOCKS5(\"tcp\", \"127.0.0.1:9150\", nil, proxy.Direct)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tSetProxy(dialer)\n\tclient = NewHttpClient()\n\n\tresp, err = client.Get(\"http://check.torproject.org\")\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to issue GET request: %v\\n\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to read the body: %v\\n\", err)\n\t}\n\tif !strings.Contains(string(body), \"Congratulations. This browser is configured to use Tor.\") {\n\t\tt.Error(\"Failed to connect through Tor\")\n\t}\n}", "func NewClient(options Options) (client Client) {\n\tmergo.Merge(&options, defaultClientOptions)\n\n\tclient = Client{newDefaultClient(options)}\n\n\tif options.Proxy != \"\" {\n\t\tclient.setProxy(options.Proxy, options.ProxyConnectHeaders)\n\t}\n\n\tif options.MaxRedirects > 0 {\n\t\tclient.setLimitRedirect(options.MaxRedirects)\n\t}\n\n\treturn client\n}", "func newCloudlyckeClient() *http.Client {\n\treturn &http.Client{}\n}", "func NewClient(baseClient *httpclient.Client) *Client {\n\treturn &Client{\n\t\thttp: baseClient,\n\t}\n}", "func NewClient(token string) *Client {\n\treturn &Client{\n\t\tEndpoint: DefaultEndpoint,\n\t\tHTTPClient: http.DefaultClient,\n\t\tToken: Token(token),\n\t}\n}", "func NewClient(authToken string) Client {\n\treturn Client{AuthToken: authToken, BaseURL: defaultBaseURL}\n}", "func NewClient() *http.Client {\n\tt := &http.Transport{\n\t\tMaxIdleConns: 10,\n\t\tIdleConnTimeout: 30 * time.Second,\n\t}\n\n\treturn &http.Client{Transport: t}\n}", "func NewClient(token string) *Client {\n\treturn &Client{\n\t\tbearer: \"Bearer \" + token,\n\t\tclient: &http.Client{\n\t\t\tTimeout: 5 * time.Second,\n\t\t},\n\t}\n}", "func NewClient(token string) *Client {\n\treturn &Client{\n\t\ttoken: token,\n\t\tapiEndpoint: apiEndpoint,\n\t\tHTTPClient: &http.Client{Timeout: 5 * time.Second},\n\t}\n}", "func NewClient(config *Config) (client *Client, err error) {\n\t// bootstrap the config\n\tdefConfig := DefaultConfig()\n\n\tif len(config.ApiAddress) == 0 {\n\t\tconfig.ApiAddress = defConfig.ApiAddress\n\t}\n\n\tif len(config.Username) == 0 {\n\t\tconfig.Username = defConfig.Username\n\t}\n\n\tif len(config.Password) == 0 {\n\t\tconfig.Password = defConfig.Password\n\t}\n\n\tif len(config.Token) == 0 {\n\t\tconfig.Token = defConfig.Token\n\t}\n\n\tif len(config.UserAgent) == 0 {\n\t\tconfig.UserAgent = defConfig.UserAgent\n\t}\n\n\tif config.HttpClient == nil {\n\t\tconfig.HttpClient = defConfig.HttpClient\n\t}\n\n\tif config.HttpClient.Transport == nil {\n\t\tconfig.HttpClient.Transport = shallowDefaultTransport()\n\t}\n\n\tvar tp *http.Transport\n\n\tswitch t := config.HttpClient.Transport.(type) {\n\tcase *http.Transport:\n\t\ttp = t\n\tcase *oauth2.Transport:\n\t\tif bt, ok := t.Base.(*http.Transport); ok {\n\t\t\ttp = bt\n\t\t}\n\t}\n\n\tif tp != nil {\n\t\tif tp.TLSClientConfig == nil {\n\t\t\ttp.TLSClientConfig = &tls.Config{}\n\t\t}\n\t\ttp.TLSClientConfig.InsecureSkipVerify = config.SkipSslValidation\n\t}\n\n\tconfig.ApiAddress = strings.TrimRight(config.ApiAddress, \"/\")\n\n\tclient = &Client{\n\t\tConfig: *config,\n\t}\n\n\tif err := client.refreshEndpoint(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client, nil\n}", "func NewClient(cfg *config.Configuration) (*Client, error) {\n\trc, err := rest.New(Url)\n\tif err != nil {\n\t\treturn &Client{}, err\n\t}\n\n\tclient := &Client{\n\t\tconfig: cfg,\n\t\tclient: rc,\n\t\tlimiter: rate.NewLimiter(30, 5),\n\t}\n\n\treturn client, nil\n}", "func NewClient(addr, authToken string) (*Client, error) {\n\tc := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: true,\n\t\t\t},\n\t\t},\n\t}\n\n\tbase, err := url.Parse(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := &Client{\n\t\tc: c,\n\t\taddr: base,\n\t\tauthToken: authToken,\n\t}\n\n\treturn client, nil\n\n}", "func NewClient(with ...ClientOption) *Client {\n\ttimeout := DefaultTimeout\n\n\tclient := &Client{\n\t\tclient: &http.Client{\n\t\t\tTimeout: timeout,\n\t\t},\n\t\tbase: getBaseURL(url.URL{\n\t\t\tScheme: \"https\",\n\t\t\tHost: \"api.secrethub.io\",\n\t\t}),\n\t\tuserAgent: DefaultUserAgent,\n\t}\n\tclient.Options(with...)\n\treturn client\n}", "func NewClient(baseURL string, defaultHeaders map[string]string) *Client {\n\turl, _ := url.Parse(baseURL)\n\tif defaultHeaders == nil {\n\t\tdefaultHeaders = make(map[string]string)\n\t}\n\treturn &Client{httpClient: &http.Client{}, baseURL: url, defaultHeaders: defaultHeaders}\n}", "func NewClient(apiKey string) *Client {\n\treturn &Client{\n\t\tclient: &http.Client{Transport: &http.Transport{\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tDialContext: (&net.Dialer{\n\t\t\t\tTimeout: 30 * time.Second,\n\t\t\t\tKeepAlive: 30 * time.Second,\n\t\t\t\tDualStack: true,\n\t\t\t}).DialContext,\n\t\t\tDisableKeepAlives: true,\n\t\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\t\tExpectContinueTimeout: 1 * time.Second,\n\t\t}},\n\t\tapiKey: apiKey,\n\t\tURL: DefaultURL,\n\t}\n}", "func wrappedClient(t *testing.T, testID string) (*Client, error) {\n\tctx := context.Background()\n\tbase := http.DefaultTransport\n\n\ttrans, err := htransport.NewTransport(ctx, base, option.WithoutAuthentication(), option.WithUserAgent(\"custom-user-agent\"))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create http client: %v\", err)\n\t}\n\n\tc := http.Client{Transport: trans}\n\n\t// Add RoundTripper to the created HTTP client\n\twrappedTrans := &retryTestRoundTripper{rt: c.Transport, testID: testID, T: t}\n\tc.Transport = wrappedTrans\n\n\t// Supply this client to storage.NewClient\n\t// STORAGE_EMULATOR_HOST takes care of setting the correct endpoint\n\tclient, err := NewClient(ctx, option.WithHTTPClient(&c))\n\treturn client, err\n}", "func New(token string) Client {\n\treturn Client{\n\t\ttoken: token,\n\t\thttpClient: http.DefaultClient,\n\t\tbaseURL: baseURL,\n\t}\n}", "func NewClient(token string) *Client {\n\tc := Client{\n\t\ttoken: token,\n\t\thclient: retryablehttp.NewClient(),\n\t}\n\n\t// set up http client\n\tc.hclient.Logger = nil\n\tc.hclient.ErrorHandler = c.errorHandler\n\tc.hclient.RetryMax = retryLimit\n\tc.hclient.RetryWaitMin = maxRateLimit / 3\n\tc.hclient.RetryWaitMax = maxRateLimit\n\n\t// add services\n\tc.Account = &AccountService{&c}\n\tc.Server = &ServerService{&c}\n\tc.Transaction = &TransactionService{&c}\n\tc.CreateOptions = &CreateOptionsService{&c}\n\tc.SSHKey = &SSHKeyService{&c}\n\n\treturn &c\n}", "func New(cfg Config) (*Client, error) {\n\tif cfg.Transport == nil {\n\t\tcfg.Transport = http.DefaultTransport\n\t}\n\n\tif cfg.CACert != nil {\n\t\thttpTransport, ok := cfg.Transport.(*http.Transport)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"unable to set CA certificate for transport of type %T\", cfg.Transport)\n\t\t}\n\n\t\thttpTransport = httpTransport.Clone()\n\t\thttpTransport.TLSClientConfig.RootCAs = x509.NewCertPool()\n\n\t\tif ok := httpTransport.TLSClientConfig.RootCAs.AppendCertsFromPEM(cfg.CACert); !ok {\n\t\t\treturn nil, errors.New(\"unable to add CA certificate\")\n\t\t}\n\n\t\tcfg.Transport = httpTransport\n\t}\n\n\tif len(cfg.RetryOnStatus) == 0 {\n\t\tcfg.RetryOnStatus = defaultRetryOnStatus[:]\n\t}\n\n\tif cfg.MaxRetries == 0 {\n\t\tcfg.MaxRetries = defaultMaxRetries\n\t}\n\n\tvar conns []*Connection\n\tfor _, u := range cfg.URLs {\n\t\tconns = append(conns, &Connection{URL: u})\n\t}\n\n\tclient := Client{\n\t\turls: cfg.URLs,\n\t\tusername: cfg.Username,\n\t\tpassword: cfg.Password,\n\t\theader: cfg.Header,\n\n\t\tsigner: cfg.Signer,\n\n\t\tretryOnStatus: cfg.RetryOnStatus,\n\t\tdisableRetry: cfg.DisableRetry,\n\t\tenableRetryOnTimeout: cfg.EnableRetryOnTimeout,\n\t\tmaxRetries: cfg.MaxRetries,\n\t\tretryBackoff: cfg.RetryBackoff,\n\t\tdiscoverNodesInterval: cfg.DiscoverNodesInterval,\n\n\t\tcompressRequestBody: cfg.CompressRequestBody,\n\n\t\ttransport: cfg.Transport,\n\t\tlogger: cfg.Logger,\n\t\tselector: cfg.Selector,\n\t\tpoolFunc: cfg.ConnectionPoolFunc,\n\t}\n\n\tif client.poolFunc != nil {\n\t\tclient.pool = client.poolFunc(conns, client.selector)\n\t} else {\n\t\tclient.pool, _ = NewConnectionPool(conns, client.selector)\n\t}\n\n\tif cfg.EnableDebugLogger {\n\t\tdebugLogger = &debuggingLogger{Output: os.Stdout}\n\t}\n\n\tif cfg.EnableMetrics {\n\t\tclient.metrics = &metrics{responses: make(map[int]int)}\n\t\t// TODO(karmi): Type assertion to interface\n\t\tif pool, ok := client.pool.(*singleConnectionPool); ok {\n\t\t\tpool.metrics = client.metrics\n\t\t}\n\t\tif pool, ok := client.pool.(*statusConnectionPool); ok {\n\t\t\tpool.metrics = client.metrics\n\t\t}\n\t}\n\n\tif client.discoverNodesInterval > 0 {\n\t\ttime.AfterFunc(client.discoverNodesInterval, func() {\n\t\t\tclient.scheduleDiscoverNodes(client.discoverNodesInterval)\n\t\t})\n\t}\n\n\treturn &client, nil\n}", "func New(token string) *Client {\n\tbaseURL, err := url.Parse(DefaultBaseURL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &Client{\n\t\tBaseURL: baseURL,\n\t\tClient: &http.Client{},\n\t\tToken: token,\n\t}\n}", "func (c Config) NewClient(tok oauth2.Token) *Client {\n\tts := tokenSource{\n\t\ttoken: tok,\n\t\tconfig: c,\n\t}\n\t_ = ts\n\tb, _ := url.Parse(c.BaseURL)\n\treturn &Client{\n\t\tTokenSource: ts,\n\t\tClient: http.Client{\n\t\t\tTransport: &oauth2.Transport{\n\t\t\t\tBase: &Transport{BaseURL: b},\n\t\t\t\tSource: ts,\n\t\t\t},\n\t\t},\n\t}\n}", "func NewClient(c *Config) (*Client, error) {\n\tdef := DefaultConfig()\n\tif def == nil {\n\t\treturn nil, fmt.Errorf(\"could not create/read default configuration\")\n\t}\n\tif def.Error != nil {\n\t\treturn nil, errwrap.Wrapf(\"error encountered setting up default configuration: {{err}}\", def.Error)\n\t}\n\n\tif c == nil {\n\t\tc = def\n\t}\n\n\tc.modifyLock.Lock()\n\tdefer c.modifyLock.Unlock()\n\n\tif c.MinRetryWait == 0 {\n\t\tc.MinRetryWait = def.MinRetryWait\n\t}\n\n\tif c.MaxRetryWait == 0 {\n\t\tc.MaxRetryWait = def.MaxRetryWait\n\t}\n\n\tif c.HttpClient == nil {\n\t\tc.HttpClient = def.HttpClient\n\t}\n\tif c.HttpClient.Transport == nil {\n\t\tc.HttpClient.Transport = def.HttpClient.Transport\n\t}\n\n\taddress := c.Address\n\tif c.AgentAddress != \"\" {\n\t\taddress = c.AgentAddress\n\t}\n\n\tu, err := c.ParseAddress(address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := &Client{\n\t\taddr: u,\n\t\tconfig: c,\n\t\theaders: make(http.Header),\n\t}\n\n\tif c.ReadYourWrites {\n\t\tclient.replicationStateStore = &replicationStateStore{}\n\t}\n\n\t// Add the VaultRequest SSRF protection header\n\tclient.headers[RequestHeaderName] = []string{\"true\"}\n\n\tif token := os.Getenv(EnvVaultToken); token != \"\" {\n\t\tclient.token = token\n\t}\n\n\tif namespace := os.Getenv(EnvVaultNamespace); namespace != \"\" {\n\t\tclient.setNamespace(namespace)\n\t}\n\n\treturn client, nil\n}", "func NewClient() *http.Client {\n\treturn &http.Client{\n\t\tTransport: roundTripper,\n\t\tTimeout: TCPConnectionTimeout,\n\t}\n}", "func NewClient(token string, opts ...clientOption) *Client {\n\n\tclient := Client{\n\t\ttoken: token,\n\t\tclient: http.DefaultClient,\n\t\tbaseEndpoint: baseEndpoint,\n\t}\n\n\tif len(opts) > 0 {\n\t\tfor _, opt := range opts {\n\t\t\topt(&client)\n\t\t}\n\t}\n\n\treturn &client\n}", "func NewClient(token string, opts ...ClientOption) Client {\n\tc := &client{\n\t\ttoken: token,\n\t\tbaseUrl: defaultBaseUrl,\n\t\thttpClient: &http.Client{},\n\t}\n\n\tfor _, opt := range opts {\n\t\topt.apply(c)\n\t}\n\n\treturn c\n}", "func NewClient(prefix string, apiVersion string, version string,\n\ttoken TokenHolder, t http.RoundTripper) *Client {\n\n\trt := &registryRoundTripper{\n\t\tDefaultRequestDoer: DefaultRequestDoer{\n\t\t\tClient: &http.Client{\n\t\t\t\tTransport: t,\n\t\t\t\tTimeout: time.Minute,\n\t\t\t},\n\t\t\tHost: prefix,\n\t\t},\n\n\t\tapiVersion: apiVersion,\n\t\tversion: version,\n\t\tholder: token,\n\t}\n\n\treturn NewClientWithRoundTripper(rt)\n}", "func NewClient(addr string, opts ...ClientOption) *Client {\n\tc := &Client{\n\t\taddr: addr,\n\t\thttpClient: &http.Client{\n\t\t\tTimeout: 5 * time.Second,\n\t\t},\n\t}\n\n\tfor _, o := range opts {\n\t\to.configure(c)\n\t}\n\n\treturn c\n}", "func MakeProxyClient(timeout time.Duration, l hclog.Logger) *HTTPProxyClient {\n\tproxyClient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tDialContext: (&net.Dialer{\n\t\t\t\tTimeout: timeout,\n\t\t\t\tKeepAlive: 0,\n\t\t\t}).DialContext,\n\t\t\tMaxIdleConns: 200,\n\t\t\tDisableKeepAlives: true,\n\t\t\tIdleConnTimeout: 120 * time.Millisecond,\n\t\t\tExpectContinueTimeout: 1500 * time.Millisecond,\n\t\t},\n\t}\n\n\treturn &HTTPProxyClient{\n\t\tproxyClient: proxyClient,\n\t\tlogger: l,\n\t}\n}", "func defaultClient(skipverify bool) *http.Client {\n\tclient := &http.Client{}\n\tclient.Transport = defaultTransport(skipverify)\n\treturn client\n}", "func NewClient(httpClient *http.Client, baseURL string) (*Client, error) {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\n\tbase, err := url.Parse(baseURL)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Could not parse base URL\")\n\t}\n\n\tc := &Client{client: httpClient, baseURL: base}\n\treturn c, nil\n}", "func New(opts ClientOptions) Client {\n\taddress := opts.Address\n\tif address == \"\" {\n\t\taddress = defaultAddress\n\t}\n\n\thttpClient := opts.HTTPClient\n\tif httpClient == nil {\n\t\thttpClient = clean.DefaultPooledClient()\n\t\thttpClient.Timeout = defaultTimeout\n\t}\n\n\tlogger := opts.Logger\n\tif logger == nil {\n\t\tlogger = loggy.Discard()\n\t}\n\n\treturn &client{\n\t\taddress: address,\n\t\ttoken: opts.Token,\n\t\thttpClient: httpClient,\n\t\tlog: logger,\n\t}\n}", "func NewClient(config *ClientConfig) *Client {\n\treturn &Client{\n\t\tfmt.Sprintf(\"http://%s/%s\", config.APIHost, apiPath),\n\t\thttp.Client{\n\t\t\tTimeout: time.Second * 3,\n\t\t},\n\t}\n}", "func createHTTPClient() *http.Client {\n\tclient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tMaxIdleConnsPerHost: 15,\n\t\t},\n\t\tTimeout: time.Duration(10) * time.Second,\n\t}\n\n\treturn client\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\tbaseURL, _ := url.Parse(defaultBaseURL)\n\tc := Client{\n\t\tBaseURL: baseURL,\n\t\tclient: httpClient,\n\t\tUserAgent: userAgent,\n\t}\n\treturn &c\n}", "func NewClient(timeout time.Duration, auth Auth) Client {\n\treturn &client{\n\t\thttpClient: &http.Client{\n\t\t\tTimeout: timeout,\n\t\t\tTransport: &http.Transport{\n\t\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t\t},\n\t\t},\n\t\tauth: auth,\n\t}\n}", "func New() *Client {\n\treturn &Client{\n\t\tclient: &http.Client{},\n\t\tendpoint: *defaultEndpoint,\n\t}\n}", "func NewClient(address string) *Client {\n\t// bootstrap the config\n\tc := &Client{\n\t\tAddress: address,\n\t\tScheme: \"http\",\n\t}\n\n\t// Make sure IPAM connection is alive, with retries\n\tfor i := 0; i < 5; i++ {\n\t\t_, err := c.IndexPools()\n\t\tif err == nil {\n\t\t\treturn c\n\t\t}\n\t\tlog.Println(\"Could not connect to IPAM, retrying in 5 Seconds...\")\n\t\ttime.Sleep(5 * time.Second)\n\t}\n\n\treturn nil\n}", "func (h httpUtil) NewClient(proxy string, enableTLS bool, certificates []byte) (*http.Client, error) {\n\t// Set proxy function if there is a proxy configured.\n\tvar proxyFunc func(*http.Request) (*url.URL, error)\n\tif proxy != \"\" {\n\t\tproxyURL, err := url.Parse(proxy)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tproxyFunc = http.ProxyURL(proxyURL)\n\t}\n\n\t// Configure TLS if needed.\n\tvar tlsConfig *tls.Config\n\tif enableTLS {\n\t\tif len(certificates) > 0 {\n\t\t\tpool := x509.NewCertPool()\n\t\t\tpool.AppendCertsFromPEM(certificates)\n\t\t\ttlsConfig = &tls.Config{\n\t\t\t\tRootCAs: pool,\n\t\t\t}\n\t\t}\n\t}\n\n\tclient := http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tProxy: proxyFunc,\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t},\n\t}\n\n\treturn &client, nil\n}", "func newClient(addr string, max int, discardClientTimeout time.Duration, fn connectRPCFn) (Client, error) {\n\n\trpcClientFactory := func() (interface{}, error) {\n\t\treturn fn(addr)\n\t}\n\trpcPool, err := pool.NewPool(max, rpcClientFactory)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trc := &reconnectingClient{addr: addr, pool: rpcPool, discardClientTimeout: discardClientTimeout}\n\treturn rc, nil\n}", "func newHTTPClient(count int) *client {\n\treturn &client{\n\t\tcli: &http.Client{\n\t\t\tTimeout: time.Second * 5,\n\t\t},\n\t\tworkers: count,\n\t\t//can be different size\n\t\terrChan: make(chan error, count),\n\t\tseen: make(map[int]struct{}),\n\t\tpath: \"http://host.docker.internal:9010/objects/\",\n\t}\n}", "func NewClient(baseURL string, apiKey string) Client {\n\treturn &httpClient{\n\t\tapiKey: apiKey,\n\t\tbaseURL: baseURL,\n\t\tinst: &http.Client{},\n\t}\n}", "func NewClient(apiURL string, logger lager.Logger) Client {\n\treturn &client{\n\t\trequestGenerator: rata.NewRequestGenerator(apiURL, api.Routes),\n\t\tgivenHTTPClient: &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tDisableKeepAlives: false,\n\t\t\t\tResponseHeaderTimeout: 20 * time.Second,\n\t\t\t\tMaxIdleConns: 200,\n\t\t\t},\n\t\t},\n\t\tlogger: logger,\n\t}\n}" ]
[ "0.7370434", "0.7068887", "0.7040319", "0.70218575", "0.70028645", "0.69941664", "0.6972483", "0.6954779", "0.69186735", "0.6894859", "0.68834174", "0.68748033", "0.68671155", "0.6855859", "0.68221855", "0.6805804", "0.67977035", "0.6787757", "0.6780016", "0.67786926", "0.67697775", "0.6767639", "0.6753012", "0.6724226", "0.6724226", "0.67239296", "0.6719883", "0.67095715", "0.670693", "0.6703956", "0.6697199", "0.66967714", "0.6692586", "0.6687086", "0.66851026", "0.66837686", "0.66740555", "0.6660814", "0.6660673", "0.6634079", "0.66323924", "0.66315657", "0.65905434", "0.65882623", "0.65882623", "0.65861166", "0.6584826", "0.65841156", "0.6571179", "0.65704674", "0.6563586", "0.65629596", "0.65588677", "0.6547433", "0.6543153", "0.65418893", "0.6541269", "0.6541183", "0.65408206", "0.65308094", "0.652916", "0.6526022", "0.6522289", "0.65211046", "0.6512618", "0.6510968", "0.6500191", "0.64995563", "0.6498499", "0.6493101", "0.64875", "0.6480717", "0.64756197", "0.6474844", "0.6471345", "0.64664996", "0.64651936", "0.64617205", "0.6459213", "0.64588773", "0.64528185", "0.6452104", "0.6449588", "0.6449466", "0.64484453", "0.64483196", "0.64364254", "0.6433445", "0.6428769", "0.6422903", "0.64227366", "0.64223707", "0.64214164", "0.64196986", "0.6418875", "0.64178264", "0.64130855", "0.64098907", "0.64049846", "0.64039046" ]
0.77210724
0
Get performs an HTTP GET request against the given url, with any headers and retry options provided. It will use a random proxy to do so
func (p Provider) Get(url string, header http.Header, o RetryOptions) (http.Response, error) { req, err := retryablehttp.NewRequest("GET", url, nil) if err != nil { return http.Response{}, err } req.Header = header client, proxyIP, err := p.NewClient(req, o) if err != nil { return http.Response{}, err } resp, err := client.Do(req) if err != nil { return http.Response{}, err } httpReqs.WithLabelValues(fmt.Sprintf("%d", resp.StatusCode), "GET", proxyIP).Inc() return *resp, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Get(url string, r io.Reader, w io.Writer, clientGenerator func() *http.Client, reqTuner ...func(*http.Request)) error {\n\treturn Request(\"GET\", url, r, w, clientGenerator, reqTuner...)\n}", "func Get(url string) (resp *http.Response, err error) {\n\treturn DefaultClient.Get(url)\n}", "func httpGet(t *testing.T, url string) ([]byte, error) {\n\tclient := &http.Client{}\n\tresp, err := invokeWithRetry(\n\t\tfunc() (response *http.Response, e error) {\n\t\t\treturn client.Get(url)\n\t\t},\n\t)\n\trequire.NoError(t, err)\n\treturn handleHttpResp(t, resp)\n}", "func Get(url string) (*http.Response, error) {\n\treturn DefaultClient.Get(url)\n}", "func (m *MockClient) Get(url string) (*http.Response, error) {\n\treturn GetFunc(url)\n}", "func (c *Client) Get(url string) (*http.Response, error) {\n\tb := c.breakerLookup(url)\n\tif b == nil {\n\t\treturn c.client.Get(url)\n\t}\n\n\tctx := getGetCtx()\n\tdefer releaseGetCtx(ctx)\n\n\tctx.Client = c.client\n\tctx.ErrorOnBadStatus = c.errOnBadStatus\n\tctx.URL = url\n\tif err := b.Call(ctx, breaker.WithTimeout(c.timeout)); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ctx.Response, ctx.Error\n}", "func (g *Getter) Get(url string) (*http.Response, error) {\n\treturn g.Client.Get(url)\n}", "func (c *Client) Get(url string) (*http.Response, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"User-Agent\", c.UserAgent)\n\n\tresp, err := c.client.Do(req)\n\treturn resp, err\n}", "func (client *HTTPClient) Get(url string, opts *RequestOptions) (resp *http.Response, err error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\tresp, err = client.Do(req, opts)\n\treturn\n}", "func (c *Client) Get(url string) (*http.Response, error) {\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.Do(req)\n}", "func (client *Client) Get(\n\turl string,\n\tparams url.Values,\n\toptions ...interface{},\n) (io.ReadCloser, int, error) {\n\treply, err := client.request(\"GET\", url, params, nil, options...)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\treturn reply.Body, reply.StatusCode, nil\n}", "func Get(url string, data ...interface{}) (*ClientResponse, error) {\n\treturn DoRequest(\"GET\", url, data...)\n}", "func (c *Client) Get(headers map[string]string, queryParams map[string]string) ([]byte, error) {\n\n\t// add parameters to the url\n\tv := url.Values{}\n\tfor key, value := range queryParams {\n\t\tv.Add(key, value)\n\t}\n\turi, err := url.Parse(c.baseURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turi.RawQuery = v.Encode()\n\tc.baseURL = uri.String()\n\n\t// create a new get request\n\trequest, err := http.NewRequest(\"GET\", c.baseURL, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// add headers to the request\n\tfor key, value := range headers {\n\t\trequest.Header.Add(key, value)\n\t}\n\n\tresponse, err := c.sendRequestWithRetry(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// if response is an error (not a 200)\n\tif response.StatusCode > 299 {\n\t\treturn nil, errors.New(response.Status)\n\t}\n\t// read the body as an array of bytes\n\tresponseBody, err := ioutil.ReadAll(response.Body)\n\treturn responseBody, err\n}", "func Get(url string) *THttpClient {\r\n\treturn NewHttpClient(url).Get(\"\")\r\n}", "func (c *Client) Get(url string) (*Response, error) {\n\treq, err := c.NewRequest(\"GET\", url, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq = c.Config.AddRequestHeader(req)\n\tresponse, err := c.Do(req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn response, nil\n}", "func (c *Client) Get(url string, headers map[string]string, params map[string]interface{}) (*APIResponse, error) {\n\tfinalURL := c.baseURL + url\n\tr, err := http.NewRequest(\"GET\", finalURL, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create request: %v\", err)\n\t}\n\n\treturn c.performRequest(r, headers, params)\n}", "func Get(url string) (resp *http.Response, err error) {\n\treturn do(\"GET\", url, nil)\n}", "func (c *Client) Get(url string, headers map[string][]string) (client.Status, map[string][]string, io.ReadCloser, error) {\n\treturn c.Do(\"GET\", url, headers, nil)\n}", "func Get(dst []byte, url string) (statusCode int, body []byte, err error) {\n\treturn defaultClient.Get(dst, url)\n}", "func (c *Connection) Get(urlToGet string) (resp *http.Response, err error) {\n\tif !c.ready {\n\t\terr = NotReadyError\n\t\treturn\n\t}\n\n\tlog.Debugf(\"[%s] getting %s\", c.name, urlToGet)\n\treq, err := http.NewRequest(\"GET\", urlToGet, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor h := range c.headers {\n\t\treq.Header.Set(h, c.headers[h])\n\t}\n\tresp, err = c.client.Do(req)\n\tif err != nil || resp.StatusCode != 200 {\n\t\tif err != nil {\n\t\t\tlog.Tracef(\"[%s] got error: %s\", c.name, err.Error())\n\t\t} else {\n\t\t\tlog.Tracef(\"[%s] got status code: %d\", c.name, resp.StatusCode)\n\t\t\t// bad code received, reload\n\t\t\tgo c.Connect()\n\t\t}\n\t}\n\n\treturn\n}", "func (m *RestClientMock) Get(url string) (*http.Response, error) {\n\treturn m.GetFunc(url)\n}", "func (c *Client) Get(url string, headers, queryParams map[string][]string) (response *http.Response, err error) {\n\treturn c.makeRequest(url, http.MethodGet, headers, queryParams, nil)\n}", "func (v *DCHttpClient) Get(url string, headers map[string]string) (response *DCHttpResponse, err error) {\n\treturn v.DoWithoutContent(http.MethodGet, url, headers)\n}", "func (c *Client) Get(rawurl string, out interface{}) error {\n\treturn c.Do(rawurl, \"GET\", nil, out)\n}", "func (cl *Client) Get(c context.Context, url string, opts ...RequestOption) (*Response, error) {\n\treq, err := cl.NewRequest(c, http.MethodGet, url, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cl.Do(c, req)\n}", "func (c *Client) Get(route string) (io.ReadCloser, error) {\n\t// Prepare HTTP request\n\treq, err := http.NewRequest(\"GET\", c.url+route, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Do the request over the default client\n\treturn c.performRequest(req)\n}", "func Get(url string, ret interface{}) error {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"http get\")\n\t}\n\tdefer func() { _ = resp.Body.Close() }()\n\treturn dealResp(resp, ret)\n}", "func Get(url string) ([]byte, error) {\n\tclient := http.Client{\n\t\tTimeout: time.Second * 3,\n\t}\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tdata, err := ioutil.ReadAll(resp.Body)\n\n\treturn data, err\n}", "func (d *Downloader) Get(url string, handler protocol.ResponseHandler, eh workpool.ErrorHandler, mods ...Modifier) error {\n\toptions := &options{roptions: d.roptions}\n\tif err := Modifiers(mods).Apply(options); err != nil {\n\t\treturn err\n\t}\n\n\twork := func() error {\n\t\treturn protocol.Get(url, handler, options.ProtocolModifiers()...)\n\t}\n\n\tretrier := options.Retrier()\n\tif retrier.AtMost <= 0 {\n\t\td.pool.Add(workpool.WithError(work, eh))\n\t} else {\n\t\td.pool.Add(workpool.WithRetry(retrier, d.sched, d.pool, work, eh))\n\t}\n\treturn nil\n}", "func (c *Client) Get(ctx context.Context, url string, data ...interface{}) (*Response, error) {\n\treturn c.DoRequest(ctx, http.MethodGet, url, data...)\n}", "func get(url string) (*http.Response, error) {\n\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tresp.Body.Close()\n\t\treturn nil, fmt.Errorf(\"get failed: %s\\n\", resp.Status)\n\t}\n\n\treturn resp, nil\n}", "func (c *Client) Get(url string, header map[string]string) ([]byte, error) {\n\treq, err := c.newRequest(\"GET\", url, header)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := c.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bytes, nil\n}", "func HTTPGetWithRetry(\n\tt testing.TB,\n\tendpoint string,\n\texpectedStatus int,\n\tretryDelay time.Duration,\n\ttimeout time.Duration,\n) string {\n\tt.Helper()\n\tvar (\n\t\tr *http.Response\n\t\terr error\n\t)\n\tclient := &http.Client{\n\t\tTimeout: retryDelay,\n\t}\n\tfmt.Printf(\"\\t[%s] GET %s\\n\", t.Name(), endpoint)\n\tcheckUp := func(t poll.LogT) poll.Result {\n\t\tr, err = client.Get(endpoint)\n\t\tif err != nil {\n\t\t\treturn poll.Continue(\"reaching %q: Error %s\", endpoint, err.Error())\n\t\t}\n\t\tif r.StatusCode == expectedStatus {\n\t\t\treturn poll.Success()\n\t\t}\n\t\treturn poll.Continue(\"reaching %q: %d != %d\", endpoint, r.StatusCode, expectedStatus)\n\t}\n\tpoll.WaitOn(t, checkUp, poll.WithDelay(retryDelay), poll.WithTimeout(timeout))\n\tif r != nil {\n\t\tb, err := io.ReadAll(r.Body)\n\t\tassert.NilError(t, err)\n\t\treturn string(b)\n\t}\n\treturn \"\"\n}", "func (c *Client) Get(dst []byte, url string) (statusCode int, body []byte, err error) {\n\treturn clientGetURL(dst, url, c)\n}", "func proxyGet(endpoint, proxy string) (*http.Response, error) {\n\treq, err := http.NewRequest(\n\t\t\"GET\",\n\t\tendpoint,\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttransport := &http.Transport{Proxy: func(req *http.Request) (proxyURL *url.URL, err error) {\n\t\treturn url.Parse(proxy)\n\t}}\n\tclient := &http.Client{Transport: transport}\n\treturn client.Do(req)\n}", "func (c *HTTPClient) Get(url string, header http.Header) (*http.Response, error) {\n\t// Assemble our request and attach all headers and cookies\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif header != nil {\n\t\treq.Header = header\n\t}\n\treturn c.request(req)\n}", "func Get(url string, externalHeader ...map[string]string) ([]byte, error) {\n\t// check if request hit MaxParallel\n\tif cache.IsBurst(url) {\n\t\treturn nil, ErrMaxParallel\n\t}\n\tdefer cache.Release(url)\n\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"Accept\", \"application/json\")\n\n\tfor _, v := range externalHeader {\n\t\tfor k := range v {\n\t\t\treq.Header.Set(k, v[k])\n\t\t}\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tvar bf bytes.Buffer\n\tpooledCopy(&bf, resp.Body)\n\treturn bf.Bytes(), nil\n}", "func Get(url string) (*http.Response, error) {\n\tclient := &http.Client{}\n\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Set(\"User-Agent\", \"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.\")\n\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}", "func Get(ctx context.Context, url string, options ...RequestOption) (*Response, error) {\n\tr, err := newRequest(ctx, http.MethodGet, url, nil, options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn doRequest(http.DefaultClient, r)\n}", "func (c *httpClient) Get(url string,\n\theaders http.Header) (*Response, error) {\n\treturn c.do(http.MethodGet, url, headers, nil)\n}", "func (c *HostClient) Get(dst []byte, url string) (statusCode int, body []byte, err error) {\n\treturn clientGetURL(dst, url, c)\n}", "func (d *Doer) Get(url string, response interface{}) (*http.Response, error) {\n\treq, err := d.newRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn d.do(req, response)\n}", "func get(url string) ([]byte, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"User-Agent\", userAgent)\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"got status code: %s\", resp.Status)\n\t}\n\n\treturn ioutil.ReadAll(resp.Body)\n}", "func get(url string) (string, error) {\n\t//defer fetch.CatchPanic(\"Get()\")\n\tresp, err := httpClient.Get(url)\n\tif err != nil {\n\t\tpanic(\"Couldn't perform GET request to \" + url)\n\t}\n\tdefer resp.Body.Close()\n\tbytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(\"Unable to read the response body\")\n\t}\n\ts := string(bytes)\n\treturn s, nil\n}", "func (m *MockHTTPClient) Get(url string) (resp *http.Response, err error) {\n\ta := m.Called(url)\n\treturn a.Get(0).(*http.Response), a.Error(1)\n}", "func Get(c http.Client, url string) Result {\n\tres, err := c.Get(url)\n\tif err != nil {\n\t\treturn Result{url, \"\", nil, &ErrResult{err}}\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn Result{url, \"\", res, &ErrResult{err}}\n\t}\n\n\tif contentTypes, ok := res.Header[\"Content-Type\"]; ok {\n\t\treturn Result{url, Format(contentTypes[0], body), res, nil}\n\t} else {\n\t\treturn Result{url, Format(\"\", body), res, nil}\n\t}\n\n\tpanic(\"unreachable\")\n}", "func HTTPGet(ctx context.Context, config HTTPGetConfig) (out HTTPGetResult) {\n\taddresses := strings.Join(config.Addresses, \" \")\n\tif addresses == \"\" {\n\t\t// TODO(bassosimone): what to do in this case? We clearly\n\t\t// cannot fill the DNS cache...\n\t\treturn\n\t}\n\ttarget := config.TargetURL.String()\n\tconfig.Session.Logger().Infof(\"GET %s...\", target)\n\tdomain := config.TargetURL.Hostname()\n\tresult, err := urlgetter.Getter{\n\t\tConfig: urlgetter.Config{\n\t\t\tDNSCache: fmt.Sprintf(\"%s %s\", domain, addresses),\n\t\t},\n\t\tSession: config.Session,\n\t\tTarget: target,\n\t}.Get(ctx)\n\tconfig.Session.Logger().Infof(\"GET %s... %+v\", target, err)\n\tout.Failure = result.Failure\n\tout.TestKeys = result\n\treturn\n}", "func HTTPGet(url string, headers map[string]string, timeout ...time.Duration) ([]byte, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// custom headers\n\tif len(headers) != 0 {\n\t\tfor k, v := range headers {\n\t\t\treq.Header.Set(k, v)\n\t\t}\n\t}\n\n\t// custom timeout\n\tif len(timeout) > 0 {\n\t\thttpClient.Timeout = timeout[0]\n\t}\n\n\tresp, err := httpClient.Do(req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tio.Copy(ioutil.Discard, resp.Body)\n\n\t\treturn nil, fmt.Errorf(\"error http code: %d\", resp.StatusCode)\n\t}\n\n\tb, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n}", "func Get(ctx context.Context, URL string, headers map[string]string, timeout time.Duration) (string, error) {\n\tclient := http.Client{\n\t\tTransport: CreateHTTPTransport(),\n\t\tTimeout: timeout,\n\t}\n\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, URL, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor header, value := range headers {\n\t\treq.Header.Add(header, value)\n\t}\n\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn parseResponse(res, \"GET\", URL)\n}", "func Get(name string, url string) (*http.Response, error) {\n\treturn GetWithFallback(name, url, nil)\n}", "func (d *realDownloader) Get(url string) ([]byte, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get for %v failed: %v\", url, err)\n\t}\n\tdefer resp.Body.Close()\n\trespBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read body: %v\", err)\n\t}\n\treturn respBytes, nil\n}", "func Get (url string, args map[string]string) (*http.Response, error) {\n\t// create a client\n\tclient, req, _ := GetHttpClient(url)\n\t// build the query\n\tif len(args) > 0 {\n\t\treq = buildQuery(req, args)\n\t}\n\t// execute the request\n\t//fmt.Println(req.URL.String())\n\treturn client.Do(req)\n}", "func (hu *httpUsecase) get(url string) (*models.Response, error) {\n\tresponse := &models.Response{}\n\n\t// Lookup in cache\n\tkey := fmt.Sprintf(\"%s:%s\", coreModels.UpstreamStoreKeyPrefix, url)\n\tif err := hu.store.Get(key, response); err == nil {\n\t\t// Cache found, return\n\t\treturn response, nil\n\t}\n\n\t// Download page\n\tresponse, err := hu.repository.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Adding result in store\n\t_ = hu.store.Set(key, *response, time.Millisecond*time.Duration(hu.cacheExpiration))\n\n\treturn response, nil\n}", "func (c *FailBodyHTTPClient) Get(url string) (resp *http.Response, err error) {\n\tresp = &http.Response{\n\t\tStatusCode: http.StatusOK,\n\t\tBody: failReadCloser{Err: c.Err},\n\t}\n\treturn\n}", "func (sr *Client) get(uri string) (body []byte, err error) {\n\treq, err := http.NewRequest(\"GET\", uri, &bytes.Buffer{})\n\tif err != nil {\n\t\treturn body, fmt.Errorf(\"create new HTTP request: %v: %v\", uri, err.Error())\n\t}\n\n\tdata, err := sr.c.Do(req)\n\tif err != nil {\n\t\treturn body, fmt.Errorf(\"make request error:%v: %v\", uri, err.Error())\n\t}\n\tdefer data.Body.Close()\n\n\tif data.StatusCode != 200 {\n\t\tdata, err = sr.c.Do(req)\n\t\tif err != nil {\n\t\t\treturn body, fmt.Errorf(\"make request retry error:%v: %v\", uri, err.Error())\n\t\t}\n\t\tdefer data.Body.Close()\n\n\t\tif data.StatusCode != 200 {\n\t\t\treturn body, fmt.Errorf(\"make request retry error: unexpected response status %v\", data.StatusCode)\n\t\t}\n\t}\n\n\tbody, err = ioutil.ReadAll(data.Body)\n\tif err != nil {\n\t\treturn body, fmt.Errorf(\"read body error: %v\", err.Error())\n\t}\n\n\treturn body, nil\n}", "func (tc *tclient) get() error {\n\t// 1 -- timeout via context.\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\treq, err := http.NewRequestWithContext(ctx,\n\t\t\"GET\", tc.url+\"/ping\", nil)\n\n\tresp, err := tc.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"SUCCESS: '%s'\", string(body))\n\treturn nil\n}", "func (workCloud *WorkCloud) get(url string) (string, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq.Header.Add(\"User-Agent\", workCloud.agent)\n\n\tres, err := workCloud.client.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer res.Body.Close()\n\tb, err := ioutil.ReadAll(res.Body)\n\n\treturn string(b), nil\n}", "func getWithCB(url string) (*http.Response, error) {\n\tresp, err := cb.Execute(func() (interface{}, error) {\n\t\tresp, err := http.Get(url)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif resp.StatusCode == http.StatusInternalServerError {\n\t\t\treturn nil, fmt.Errorf(\"Internal Server Error\")\n\t\t}\n\n\t\treturn resp, nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.(*http.Response), nil\n}", "func (h *Client) Get(url string, values url.Values) (body []byte, statusCode int, err error) {\n\tif values != nil {\n\t\turl += \"?\" + values.Encode()\n\t}\n\tvar req *http.Request\n\treq, err = http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn h.do(req)\n}", "func (cli *Client) Get(targetURL *url.URL) {\n\tvar resp *resty.Response\n\tvar err error\n\n\tif cli.Config.Oauth2Enabled {\n\t\tresp, err = resty.R().\n\t\t\tSetHeader(\"Authorization\", fmt.Sprintf(\"Bearer %s\", cli.AccessToken)).\n\t\t\tGet(targetURL.String())\n\t} else {\n\t\tresp, err = resty.R().Get(targetURL.String())\n\t}\n\tif err != nil {\n\t\tfmt.Printf(\"ERR: Could not GET request, caused by: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tfmt.Print(resp)\n}", "func (c *Client) Get(url string, resType interface{}) error {\n\treturn c.CallAPI(\"GET\", url, nil, resType, true)\n}", "func (rb *RequestBuilder) Get(url string) *Response {\n\treturn rb.DoRequest(http.MethodGet, url, nil)\n}", "func Get(url string) ([]byte, error) {\n\trsp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\n\t}\n\tdefer rsp.Body.Close()\n\treturn ioutil.ReadAll(rsp.Body)\n}", "func Get(url string, opts ...RequestOption) (*Response, error) {\n\treturn DefaultSession.Get(url, opts...)\n}", "func (c *ComicClient) Get(link, hostname string) (*http.Response, error) {\n\trequest, err := c.PrepareRequest(link, hostname)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Client.Do(request)\n}", "func (s *DefaultClient) Get(endpoint string) ([]byte, *http.Response, error) {\n\treturn s.http(http.MethodGet, endpoint, nil)\n}", "func (c *Client) get(url string, result interface{}) error {\n\treq, err := c.newRequest(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp, err := c.http.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif err = checkResponse(resp); err != nil {\n\t\treturn err\n\t}\n\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = checkResults(b); err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(b, &result)\n\n\treturn err\n}", "func httpGet(url string) (resp *http.Response, err error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\treq.Header.Set(\"User-Agent\", *flagUA)\n\treturn httpClient.Do(req)\n}", "func getHttp(url url.URL) (io.ReadCloser, error) {\n\tresp, err := http.Get(url.String())\n\tif err != nil {\n\t\tlog.Printf(\"HTTP failed to GET url=%s. error=%s\\n\", url.String(), err)\n\t\treturn nil, err\n\t}\n\n\treturn resp.Body, nil\n}", "func Get(url string, data ...interface{}) (*Response, error) {\n\tr := NewRequest()\n\treturn r.Get(url, data...)\n}", "func Get(url, authToken string) (*http.Response, error) {\n\treturn get(url, authToken, 1)\n}", "func (c *Client) Get(endpoint string, params map[string]string) *grequests.Response {\n\turl := c.Endpoint + endpoint\n\tresp, err := grequests.Get(url, &grequests.RequestOptions{\n\t\tParams: params,\n\t})\n\tif err != nil {\n\t\tutilities.CheckError(resp.Error, \"Unable to make requests\")\n\t}\n\n\tif resp.Ok != true {\n\t\tlog.Println(\"Request did not return OK\")\n\t}\n\n\treturn resp\n}", "func (t transporter) Get(path string) (*http.Response, error) {\n\tresp, err := t.client.Get(t.scheme + path)\n\treturn resp, err\n}", "func (client *Client) Get(url string) (*http.Response, error) {\n\treturn client.Aws4Client.Get(url)\n}", "func (tr *Transport) Get(url string, fn HandlerFunc, options ...HandlerOption) {\n\ttr.mux.Handler(net_http.MethodGet, url, encapsulate(fn, tr.options, options))\n}", "func (c *Client) get(url string, query url.Values) (json.RawMessage, error) {\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not create get request\")\n\t}\n\treq.URL.RawQuery = query.Encode()\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"cound not get %v\", url)\n\t}\n\tdefer res.Body.Close()\n\tvar resp response\n\tif err := json.NewDecoder(res.Body).Decode(&resp); err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not decode response\")\n\t}\n\tif resp.Code != 0 {\n\t\treturn nil, errors.Errorf(\"get response code %d\", resp.Code)\n\t}\n\treturn resp.Data, nil\n}", "func (client *Client) Get(url string, JSONResponse interface{}, opts *RequestOpts) (*http.Response, error) {\n\tif opts == nil {\n\t\topts = new(RequestOpts)\n\t}\n\n\tif JSONResponse != nil {\n\t\topts.JSONResponse = JSONResponse\n\t}\n\n\treturn client.Request(\"GET\", url, opts)\n}", "func (s Session) Get(URL string, opt *Option) (*http.Response, error) {\n\treturn s.Request(\"GET\", URL, opt)\n}", "func get(url string, qparms rest.QParms) ([]byte, error) {\n\theaders := rest.Headers{\"Authorization\": \"Bearer \" + token}\n\tfor k, v := range defaultHeaders {\n\t\theaders[k] = v\n\t}\n\tclient := rest.NewClient(headers, qparms)\n\n\tbody, err := client.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn body, nil\n}", "func Get(domain, url, token, tokenKey string) (*http.Response, error) {\n\t/*\n\t * First we will initalize the client\n\t * Then we will send the get request\n\t * Then we will return the response\n\t */\n\t//initalizing the client\n\tclient := heimdallC.NewClient(\n\t\theimdallC.WithHTTPClient(&myHTTPClient{\n\t\t\ttoken: token,\n\t\t\ttokenKey: tokenKey,\n\t\t\tdomain: domain,\n\t\t}),\n\t)\n\n\t//then we will make the request\n\tres, err := client.Get(url, http.Header{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//return the response\n\treturn res, nil\n}", "func (c *Client) get(rawURL string, authenticate bool, out interface{}) error {\n\terr := c.do(rawURL, \"GET\", authenticate, http.StatusOK, nil, out)\n\treturn errio.Error(err)\n}", "func (f5 *f5LTM) get(url string, result interface{}) error {\n\treturn f5.restRequest(\"GET\", url, nil, result)\n}", "func (c *Client) Get(URL string) (resp *Response, err error) {\n\turlObj, err := url.ParseRequestURI(URL)\n\tif err != nil {\n\t\treturn\n\t}\n\theader := make(map[string]string)\n\theader[HeaderContentLength] = \"0\"\n\theader[HeaderHost] = urlObj.Host\n\treq := &Request{\n\t\tMethod: MethodGet,\n\t\tURL: urlObj,\n\t\tProto: HTTPVersion,\n\t\tHeader: header,\n\t\tContentLength: 0,\n\t\tBody: strings.NewReader(\"\"),\n\t}\n\tresp, err = c.Send(req)\n\treturn\n}", "func (c *Client) get(endpoint string, queries map[string]string) (*http.Response, error) {\n\t// Assemble request\n\treq, err := c.buildRequest(\"GET\", endpoint, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Add query strings\n\tif queries != nil {\n\t\tencodeQuery(req.URL, queries)\n\t}\n\n\tclient := buildHTTPSClient(c.verifySSL)\n\treturn client.Do(req)\n}", "func httpGet(url string, details *RunDetails) string {\n\tfmt.Printf(\"INFO: Performing http get from '%s'\\n\", url)\n\ttimeout := 120\n\n\tval := details.Getenv(v1.EnvVarOperatorTimeout)\n\tif val != \"\" {\n\t\tt, err := strconv.Atoi(val)\n\t\tif err == nil {\n\t\t\ttimeout = t\n\t\t} else {\n\t\t\tfmt.Printf(\"ERROR: Invalid value set for %s '%s' using default of 120\\n\", v1.EnvVarOperatorTimeout, val)\n\t\t}\n\t}\n\n\tclient := http.Client{\n\t\tTimeout: time.Duration(timeout) * time.Second,\n\t}\n\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: failed to get url %s - %s\\n\", url, err.Error())\n\t\treturn \"\"\n\t}\n\t//noinspection GoUnhandledErrorResult\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\tfmt.Printf(\"ERROR: filed to get 200 response from %s - %s\\n\", url, resp.Status)\n\t\treturn \"\"\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: filed to read response body from %s - %s\\n\", url, resp.Status)\n\t\treturn \"\"\n\t}\n\n\ts := string(body)\n\tfmt.Printf(\"INFO: Get response from '%s' was '%s'\\n\", url, s)\n\treturn s\n}", "func HTTPGET(url string, auth bool, authToken string) (int, []byte, error) {\n\treturn httpRequest(\"GET\", url, auth, authToken, nil)\n}", "func (ts *testServer) get(t *testing.T, urlPath string) (int, http.Header, []byte) {\n\trs, err := ts.Client().Get(ts.URL + urlPath)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer rs.Body.Close()\n\tbody, err := ioutil.ReadAll(rs.Body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn rs.StatusCode, rs.Header, body\n}", "func (w *Worker) Get(c *http.Client, url string, bind interface{}) (int, error) {\n\tr, err := c.Get(url)\n\tif err != nil {\n\t\tif r != nil {\n\t\t\tioutil.ReadAll(r.Body)\n\t\t\tr.Body.Close()\n\t\t}\n\t\treturn 0, err\n\t}\n\tdefer r.Body.Close()\n\terr = json.NewDecoder(r.Body).Decode(bind)\n\tif bind == nil {\n\t\treturn r.StatusCode, nil\n\t}\n\treturn r.StatusCode, err\n}", "func httpGet(url string, c *http.Client) (*http.Response, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq = req.WithContext(makeContext())\n\tif c == nil {\n\t\tc = http.DefaultClient\n\t}\n\treq.Header.Set(\"User-Agent\", userAgent)\n\treturn c.Do(req)\n}", "func getPage(url string, retry int) (string, error) {\n\tfor i := 0; i < retry; i++ {\n\t\tresp, err := http.Get(url)\n\t\tif err == nil && resp.StatusCode == http.StatusOK {\n\t\t\tdefer resp.Body.Close()\n\t\t\tbytes, rerr := ioutil.ReadAll(resp.Body)\n\t\t\treturn string(bytes), rerr\n\t\t}\n\n\t\ttime.Sleep(1000 * time.Millisecond)\n\t}\n\treturn \"\", fmt.Errorf(\"timed out retrieving %s\", url)\n}", "func get(cacheDir, url string) ([]byte, error) {\n\tclient := grab.NewClient()\n\treq, err := grab.NewRequest(cacheDir, url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp := client.Do(req)\n\t<-resp.Done\n\treturn ioutil.ReadFile(resp.Filename)\n}", "func (bcp *basicClientPool) Get(url, authType, accessCredential string, skipCertVerify bool) (Client, error) {\n\tk := fmt.Sprintf(\"%s:%s:%s:%v\", url, authType, accessCredential, skipCertVerify)\n\n\titem, ok := bcp.pool.Load(k)\n\tif !ok {\n\t\tnc, err := NewClient(url, authType, accessCredential, skipCertVerify)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"client pool: get\")\n\t\t}\n\n\t\t// Cache it\n\t\tnpi := &poolItem{\n\t\t\tc: nc,\n\t\t\ttimestamp: time.Now().UTC(),\n\t\t}\n\n\t\tbcp.pool.Store(k, npi)\n\t\titem = npi\n\n\t\t// dead check\n\t\tbcp.deadCheck(k, npi)\n\t}\n\n\treturn item.(*poolItem).c, nil\n}", "func (client *Client) Get(action string, params url.Values, header http.Header) (*Response, error) {\r\n\treturn client.Request(\"GET\", action, params, header, nil)\r\n}", "func Get(url string) ([]byte, error) {\n\tf := func() (interface{}, error) { // 业务处理\n\t\t// return nil,fmt.Errorf(\"tt\")\n\t\tresp, err := http.Get(url)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdefer resp.Body.Close()\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trand.Seed(time.Now().UnixNano())\n\t\tkk := rand.Intn(10000)\n\t\tratia := kk%2\n\t\t// fmt.Println(ratia)\n\t\tif ratia == 1 {\n\t\t\t// fmt.Println(\"err 111\")\n\t\t\treturn nil, fmt.Errorf(\"人为出错\")\n\t\t}\n\t\treturn body, nil\n\t}\n\tbody, err := cb.Execute(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn body.([]byte), nil\n}", "func httpGet(probe v1alpha1.ProbeAttributes, client *http.Client, resultDetails *types.ResultDetails) error {\n\t// it will retry for some retry count, in each iterations of try it contains following things\n\t// it contains a timeout per iteration of retry. if the timeout expires without success then it will go to next try\n\t// for a timeout, it will run the command, if it fails wait for the interval and again execute the command until timeout expires\n\treturn retry.Times(uint(probe.RunProperties.Retry)).\n\t\tTimeout(int64(probe.RunProperties.ProbeTimeout)).\n\t\tWait(time.Duration(probe.RunProperties.Interval) * time.Second).\n\t\tTryWithTimeout(func(attempt uint) error {\n\t\t\t// getting the response from the given url\n\t\t\tresp, err := client.Get(probe.HTTPProbeInputs.URL)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tcode := strconv.Itoa(resp.StatusCode)\n\t\t\trc := getAndIncrementRunCount(resultDetails, probe.Name)\n\n\t\t\t// comparing the response code with the expected criteria\n\t\t\tif err = cmp.RunCount(rc).\n\t\t\t\tFirstValue(code).\n\t\t\t\tSecondValue(probe.HTTPProbeInputs.Method.Get.ResponseCode).\n\t\t\t\tCriteria(probe.HTTPProbeInputs.Method.Get.Criteria).\n\t\t\t\tCompareInt(); err != nil {\n\t\t\t\tlog.Errorf(\"The %v http probe get method has Failed, err: %v\", probe.Name, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n}", "func getHTTP(uri string, sslVerify bool, timeout time.Duration) (io.ReadCloser, error) {\n\ttr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: !sslVerify}}\n\tclient := http.Client{\n\t\tTimeout: timeout,\n\t\tTransport: tr,\n\t\tCheckRedirect: redirectPolicyFunc,\n\t}\n\n\treq, err := http.NewRequest(\"GET\", uri, nil)\n\treq.Header.Add(\"Authorization\", \"Basic \"+globalBasicAuthString)\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !(resp.StatusCode >= 200 && resp.StatusCode < 300) {\n\t\tresp.Body.Close()\n\t\treturn nil, fmt.Errorf(\"HTTP status %d\", resp.StatusCode)\n\t}\n\treturn resp.Body, nil\n}", "func Get(url string, response interface{}) error {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif err := json.NewDecoder(resp.Body).Decode(response); err != nil {\n\t\treturn fmt.Errorf(\"unable to unmarshal response\")\n\t}\n\n\treturn nil\n}", "func (c *Client) get(path string) (string, error) {\n\turl := c.endpoint + path\n\tresp, err := c.httpClient.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\tbodyBytes, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbody := string(bodyBytes)\n\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\treturn body, fmt.Errorf(\"response status was %d\", resp.StatusCode)\n\t}\n\treturn body, nil\n}", "func (g *Github) Get(url string) (*http.Response, error) {\n\treturn g.Do(http.MethodGet, url, http.NoBody)\n}", "func Get(options RequestOptions) error {\n\thost, path := uriToHostAndPath(options.Uri)\n\toptions.Headers[\"Host\"] = host\n\trequest := fmt.Sprintf(\"GET %s HTTP/1.0\", path)\n\tprotocol := fmt.Sprintf(\"%s\\r\\n%s\\r\\n\", request, options.Headers)\n\treturn send(host, protocol, options)\n}" ]
[ "0.76761955", "0.74784106", "0.73909163", "0.7381686", "0.73723525", "0.73638225", "0.733259", "0.7258252", "0.72508967", "0.7219954", "0.7204669", "0.7191359", "0.7133742", "0.7132985", "0.7105667", "0.7102535", "0.70445836", "0.7036668", "0.70307475", "0.6976163", "0.6963896", "0.68871677", "0.6861302", "0.6853316", "0.68364596", "0.6834431", "0.68308085", "0.68255424", "0.6797693", "0.6779517", "0.6768251", "0.67547196", "0.67536014", "0.67422855", "0.6729024", "0.67233604", "0.66874236", "0.66845506", "0.6672232", "0.66626", "0.66587245", "0.6655538", "0.66539943", "0.66461486", "0.6638223", "0.6636235", "0.66306496", "0.6621612", "0.6593211", "0.6589183", "0.65847766", "0.6583947", "0.6549141", "0.6528721", "0.65246433", "0.6513594", "0.6512896", "0.65109354", "0.65047395", "0.6497106", "0.6489022", "0.64768493", "0.6473234", "0.6467646", "0.6454753", "0.6449443", "0.64479494", "0.64262223", "0.64149064", "0.6408881", "0.63860255", "0.6385117", "0.6373096", "0.6358909", "0.635393", "0.6330037", "0.6327413", "0.6326574", "0.63240606", "0.63196784", "0.630003", "0.6290731", "0.62820345", "0.6280782", "0.6233733", "0.62332195", "0.6231144", "0.62281513", "0.6218086", "0.6207474", "0.6195295", "0.6177433", "0.6176011", "0.6166455", "0.61630285", "0.61477655", "0.61452115", "0.61449546", "0.61407596", "0.6125589" ]
0.82963437
0
NewProvider returns a configured Provider
func NewProvider(key string) (Provider, error) { if key == "" { return Provider{}, fmt.Errorf("empty API key") } p := Provider{} client := &http.Client{Timeout: 10 * time.Second} r, err := client.Get(ghostAPI + "?key=" + key) if err != nil { return Provider{}, err } defer r.Body.Close() json.NewDecoder(r.Body).Decode(&p) for _, v := range p.Data { proxyCount.WithLabelValues( v.Proxy.IP, v.Proxy.Status, v.Proxy.CityName, v.Proxy.RegionName, v.Proxy.CountryCode, ).Inc() } return p, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewProvider(cfg Config) *Provider {\n\treturn &Provider{\n\t\tConfig: cfg,\n\t}\n}", "func NewProvider() *Provider {\n\treturn &Provider{}\n}", "func New(c *Config) *Provider {\n\treturn &Provider{\n\t\tConfig: c,\n\t}\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() provider.Provider {\n\tp := newProvider()\n\n\treturn p\n}", "func New() confmap.Provider {\n\treturn &provider{}\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 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 New(config Config) (provider *Provider, err error) {\n\tprovider = &Provider{\n\t\tconfig: config,\n\t}\n\n\tif err = provider.load(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn provider, nil\n}", "func NewProvider() (rootfs.Provider, error) {\n\treturn &provider{}, nil\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 NewProvider(log logging.Logger) *Provider {\n\treturn &Provider{\n\t\tapi: &api{},\n\t\tlog: log,\n\t}\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 NewProvider(stackConfig *kapp.StackConfig) (Provider, error) {\n\tproviderImpl, err := newProviderImpl(stackConfig.Provider)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\n\tstackConfigVars, err := stackConfigVars(providerImpl, stackConfig)\n\tif err != nil {\n\t\tlog.Warn(\"Error loading stack config variables\")\n\t\treturn nil, errors.WithStack(err)\n\t}\n\tlog.Debugf(\"Provider loaded vars: %#v\", stackConfigVars)\n\n\tif len(stackConfigVars) == 0 {\n\t\tlog.Fatal(\"No values loaded for stack\")\n\t\treturn nil, errors.New(\"Failed to load values for stack\")\n\t}\n\n\tproviderImpl.setVars(stackConfigVars)\n\n\treturn providerImpl, nil\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 New(configVarResolver *providerconfig.ConfigVarResolver) cloudprovidertypes.Provider {\n\treturn &provider{configVarResolver: configVarResolver}\n}", "func New(configVarResolver *providerconfig.ConfigVarResolver) cloudprovidertypes.Provider {\n\treturn &provider{configVarResolver: configVarResolver}\n}", "func New(configVarResolver *providerconfig.ConfigVarResolver) cloudprovidertypes.Provider {\n\treturn &provider{configVarResolver: configVarResolver}\n}", "func New(configVarResolver *providerconfig.ConfigVarResolver) cloudprovidertypes.Provider {\n\treturn &provider{configVarResolver: configVarResolver}\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 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 New(configVarResolver *providerconfig.ConfigVarResolver) cloudprovidertypes.Provider {\n\treturn &provider{configVarResolver: &providerconfig.ConfigPointerVarResolver{Cvr: configVarResolver}}\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 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 NewProvider(logger *zap.Logger, options ...ProviderOption) Provider {\n\treturn newProvider(logger, options...)\n}", "func NewProvider(logger *zap.Logger) Provider {\n\treturn newProvider(logger)\n}", "func NewProvider(ctx *pulumi.Context,\n\tname string, args *ProviderArgs, opts ...pulumi.ResourceOption) (*Provider, error) {\n\tif args == nil {\n\t\targs = &ProviderArgs{}\n\t}\n\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Provider\n\terr := ctx.RegisterResource(\"pulumi:providers:okta\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, 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 ProviderFactory(options plugin_v1.ProviderOptions) (plugin_v1.Provider, error) {\n\treturn &Provider{\n\t\tName: options.Name,\n\t}, 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(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 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 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(path string) *Provider {\n\treturn &Provider{path: path}\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 NewProvider(params ...SDKContextParams) *Provider {\n\tctxProvider := Provider{}\n\tfor _, param := range params {\n\t\tparam(&ctxProvider)\n\t}\n\treturn &ctxProvider\n}", "func New(options ...Option) *Provider {\n\tcfg := getConfig(options...)\n\treturn &Provider{\n\t\tcfg: cfg,\n\t\tlog: log.With().Str(\"service\", \"directory\").Str(\"provider\", \"onelogin\").Logger(),\n\t}\n}", "func New(config *Config) (*Provider, error) {\n\tif config.URL == \"\" {\n\t\tconfig.URL = fmt.Sprintf(\"http://%s\", config.ListenAddr)\n\t}\n\n\tif config.TOTP == \"\" {\n\t\tkey, err := totp.Generate(totp.GenerateOpts{\n\t\t\tIssuer: \"karmabot\",\n\t\t\tAccountName: \"slack\",\n\t\t})\n\n\t\tif err != nil {\n\t\t\tconfig.Log.Err(err).Fatal(\"an error occurred while generating a TOTP key\")\n\t\t} else {\n\t\t\tconfig.Log.KV(\"totpKey\", key.Secret()).Fatal(\"please use the following TOTP key\")\n\t\t}\n\t}\n\n\tprovider := &Provider{\n\t\tConfig: config,\n\t\tui: newUI(config),\n\t}\n\n\treturn provider, nil\n}", "func New() *Provider {\n\treturn &Provider{clients: make(map[string]ClientVersionProvider)}\n}", "func NewProvider() (Service, error) {\n\treturn &WinProvider{}, nil\n}", "func NewProvider(options ...ProviderOption) *Provider {\n\tp := &Provider{\n\t\tlogger: log.NoopLogger{},\n\t}\n\t// Ensure we apply the logger options first, while maintaining the order\n\t// otherwise. This way we can trivially init the internal provider with\n\t// the logger.\n\tsort.SliceStable(options, func(i, j int) bool {\n\t\t_, iIsLogger := options[i].(providerLoggerOption)\n\t\t_, jIsLogger := options[j].(providerLoggerOption)\n\t\treturn iIsLogger && !jIsLogger\n\t})\n\tfor _, o := range options {\n\t\tif o != nil {\n\t\t\to.apply(p)\n\t\t}\n\t}\n\n\tif p.provider == nil {\n\t\t// auto-detect based on what is available in path\n\t\t// default to docker for backwards compatibility\n\t\tif path, err := exec.LookPath(\"docker\"); err == nil && path != \"\" {\n\t\t\tp.provider = docker.NewProvider(p.logger)\n\t\t} else if path, err := exec.LookPath(\"podman\"); err == nil && path != \"\" {\n\t\t\tp.provider = podman.NewProvider(p.logger)\n\t\t} else {\n\t\t\tp.provider = docker.NewProvider(p.logger)\n\t\t}\n\t}\n\treturn p\n}", "func New(clientset *clusterinfo.OpenShift) (*Provider, error) {\n\treturn &Provider{\n\t\toc: clientset,\n\t}, nil\n}", "func NewProvider(ctx *pulumi.Context,\n\tname string, args *ProviderArgs, opts ...pulumi.ResourceOption) (*Provider, error) {\n\tif args == nil {\n\t\targs = &ProviderArgs{}\n\t}\n\n\tif args.AllowReauth == nil {\n\t\targs.AllowReauth = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"OS_ALLOW_REAUTH\").(bool))\n\t}\n\tif args.Cloud == nil {\n\t\targs.Cloud = pulumi.StringPtr(getEnvOrDefault(\"\", nil, \"OS_CLOUD\").(string))\n\t}\n\tif args.DelayedAuth == nil {\n\t\targs.DelayedAuth = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"OS_DELAYED_AUTH\").(bool))\n\t}\n\tif args.EndpointType == nil {\n\t\targs.EndpointType = pulumi.StringPtr(getEnvOrDefault(\"\", nil, \"OS_ENDPOINT_TYPE\").(string))\n\t}\n\tif args.Insecure == nil {\n\t\targs.Insecure = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"OS_INSECURE\").(bool))\n\t}\n\tif args.Region == nil {\n\t\targs.Region = pulumi.StringPtr(getEnvOrDefault(\"\", nil, \"OS_REGION_NAME\").(string))\n\t}\n\tif args.Swauth == nil {\n\t\targs.Swauth = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"OS_SWAUTH\").(bool))\n\t}\n\tif args.UseOctavia == nil {\n\t\targs.UseOctavia = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"OS_USE_OCTAVIA\").(bool))\n\t}\n\tvar resource Provider\n\terr := ctx.RegisterResource(\"pulumi:providers:openstack\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\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 NewProvider(respG func() (Response, error), cache time.Duration) *Provider {\n\treturn &Provider{\n\t\tapiG: provider.NewCached(func() (interface{}, error) {\n\t\t\treturn respG()\n\t\t}, cache).InterfaceGetter(),\n\t}\n}", "func New(config Config) (*Provider, error) {\n\t// Dependencies.\n\tif config.Logger == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Logger must not be empty\")\n\t}\n\n\t// Settings.\n\tif config.BridgeName == \"\" {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.BridgeName must not be empty\")\n\t}\n\n\tnewProvider := &Provider{\n\t\t// Dependencies.\n\t\tlogger: config.Logger,\n\n\t\t// Settings.\n\t\tbridgeName: config.BridgeName,\n\t}\n\n\treturn newProvider, nil\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 NewProvider(api *API, vin string, cache time.Duration) *Provider {\n\timpl := &Provider{\n\t\tstatusG: provider.Cached(func() (RechargeStatus, error) {\n\t\t\treturn api.RechargeStatus(vin)\n\t\t}, cache),\n\t}\n\treturn impl\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 NewProvider() *extblockpublisher.Provider {\n\treturn extblockpublisher.NewProvider()\n}", "func NewProvider(\n\tlogger *zap.Logger,\n\topts ...Option,\n) *Provider {\n\tcfg := providerConfig{\n\t\tqueryTimeout: 5 * time.Second,\n\t\tupdateBufferSize: 10000,\n\t\teventBufferSize: 10000,\n\t\trequestBufferSize: 10,\n\t}\n\tfor _, opt := range opts {\n\t\topt(&cfg)\n\t}\n\n\treturn &Provider{\n\t\tqueryTimeout: cfg.queryTimeout,\n\t\tlogger: logger.Named(\"store-provider\"),\n\n\t\tstreams: Streams{Map: make(map[int]*models.Stream)},\n\t\tstreamHub: hub.NewNotifyHub[*models.StreamEvent](cfg.eventBufferSize),\n\t\tentityHub: hub.NewNotifyHub[*models.EntityEvent](cfg.eventBufferSize),\n\n\t\tupdatesChan: make(chan Update, cfg.updateBufferSize),\n\t\tinternalRequestChan: make(chan internalRequest, cfg.requestBufferSize),\n\n\t\tstop: make(chan struct{}),\n\t\tstopDone: make(chan struct{}),\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 New(c *configpb.ProviderConfig, l *logger.Logger) (*Provider, error) {\n\tprojects := c.GetProject()\n\tif len(projects) == 0 {\n\t\tif !metadata.OnGCE() {\n\t\t\treturn nil, errors.New(\"rds.gcp.New(): project not configured and not running on GCE\")\n\t\t}\n\n\t\tproject, err := metadata.ProjectID()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"rds.gcp.New(): error getting the local project ID on GCE: %v\", err)\n\t\t}\n\n\t\tprojects = append(projects, project)\n\t}\n\n\tp := &Provider{\n\t\tprojects: projects,\n\t\tlisters: make(map[string]map[string]lister),\n\t}\n\n\tfor _, project := range projects {\n\t\tprojectLister, err := initGCPProject(project, c, l)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tp.listers[project] = projectLister\n\t}\n\n\treturn p, nil\n}", "func NewProvider(conf *blkstorage.Conf, indexConfig *blkstorage.IndexConfig, _ *ledger.Config, metricsProvider metrics.Provider) (extledgerapi.BlockStoreProvider, error) {\n\treturn blkstorage.NewProvider(conf, indexConfig, metricsProvider)\n}", "func NewProvider(ctx *pulumi.Context,\n\tname string, args *ProviderArgs, opts ...pulumi.ResourceOption) (*Provider, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Address == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Address'\")\n\t}\n\tif args.Token == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Token'\")\n\t}\n\tif args.MaxLeaseTtlSeconds == nil {\n\t\targs.MaxLeaseTtlSeconds = pulumi.IntPtr(getEnvOrDefault(1200, parseEnvInt, \"TERRAFORM_VAULT_MAX_TTL\").(int))\n\t}\n\tif args.MaxRetries == nil {\n\t\targs.MaxRetries = pulumi.IntPtr(getEnvOrDefault(2, parseEnvInt, \"VAULT_MAX_RETRIES\").(int))\n\t}\n\tif args.SkipTlsVerify == nil {\n\t\targs.SkipTlsVerify = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"VAULT_SKIP_VERIFY\").(bool))\n\t}\n\tvar resource Provider\n\terr := ctx.RegisterResource(\"pulumi:providers:vault\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func New(scheme SchemeType) confmap.Provider {\n\treturn &provider{scheme: scheme}\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 New(m map[string]interface{}) (app.Provider, error) {\n\tc, err := parseConfig(m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &provider{iframeUIProvider: c.IFrameUIProvider}, nil\n}", "func New() buckets.Provider {\n\treturn newWithOptions()\n}", "func NewProvider(key string) *Provider {\n\treturn &Provider{\n\t\tprops: resource.NewProperties().\n\t\t\tProp(\"token\", resource.NewStringProperty(key)),\n\t}\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 newPluginProvider(pluginBinDir string, provider kubeletconfig.CredentialProvider) (*pluginProvider, error) {\n\tmediaType := \"application/json\"\n\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unsupported media type %q\", mediaType)\n\t}\n\n\tgv, ok := apiVersions[provider.APIVersion]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid apiVersion: %q\", provider.APIVersion)\n\t}\n\n\tclock := clock.RealClock{}\n\n\treturn &pluginProvider{\n\t\tclock: clock,\n\t\tmatchImages: provider.MatchImages,\n\t\tcache: cache.NewExpirationStore(cacheKeyFunc, &cacheExpirationPolicy{clock: clock}),\n\t\tdefaultCacheDuration: provider.DefaultCacheDuration.Duration,\n\t\tlastCachePurge: clock.Now(),\n\t\tplugin: &execPlugin{\n\t\t\tname: provider.Name,\n\t\t\tapiVersion: provider.APIVersion,\n\t\t\tencoder: codecs.EncoderForVersion(info.Serializer, gv),\n\t\t\tpluginBinDir: pluginBinDir,\n\t\t\targs: provider.Args,\n\t\t\tenvVars: provider.Env,\n\t\t\tenviron: os.Environ,\n\t\t},\n\t}, nil\n}", "func NewProvider(ctx *pulumi.Context,\n\tname string, args *ProviderArgs, opts ...pulumi.ResourceOption) (*Provider, error) {\n\tif args == nil {\n\t\targs = &ProviderArgs{}\n\t}\n\n\tif args.ApiClientLogging == nil {\n\t\tif d := internal.GetEnvOrDefault(false, internal.ParseEnvBool, \"CLOUDFLARE_API_CLIENT_LOGGING\"); d != nil {\n\t\t\targs.ApiClientLogging = pulumi.BoolPtr(d.(bool))\n\t\t}\n\t}\n\tif args.MaxBackoff == nil {\n\t\tif d := internal.GetEnvOrDefault(30, internal.ParseEnvInt, \"CLOUDFLARE_MAX_BACKOFF\"); d != nil {\n\t\t\targs.MaxBackoff = pulumi.IntPtr(d.(int))\n\t\t}\n\t}\n\tif args.MinBackoff == nil {\n\t\tif d := internal.GetEnvOrDefault(1, internal.ParseEnvInt, \"CLOUDFLARE_MIN_BACKOFF\"); d != nil {\n\t\t\targs.MinBackoff = pulumi.IntPtr(d.(int))\n\t\t}\n\t}\n\tif args.Retries == nil {\n\t\tif d := internal.GetEnvOrDefault(3, internal.ParseEnvInt, \"CLOUDFLARE_RETRIES\"); d != nil {\n\t\t\targs.Retries = pulumi.IntPtr(d.(int))\n\t\t}\n\t}\n\tif args.Rps == nil {\n\t\tif d := internal.GetEnvOrDefault(4, internal.ParseEnvInt, \"CLOUDFLARE_RPS\"); d != nil {\n\t\t\targs.Rps = pulumi.IntPtr(d.(int))\n\t\t}\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Provider\n\terr := ctx.RegisterResource(\"pulumi:providers:cloudflare\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func New() provider.Provider {\n\treturn &hostingdeProvider{}\n}", "func NewProvider() (Service, error) {\n\treturn &DarwinProvider{}, nil\n}", "func New(name string, opts ...Config) (Provider, error) {\n\tvar cfg Config\n\n\tif len(opts) == 0 {\n\t\tcfg = Config{}\n\t} else {\n\t\tcfg = opts[0]\n\t}\n\n\tif cfg.Fetcher == nil {\n\t\tcfg.Fetcher = http.DefaultClient\n\t}\n\n\tif len(cfg.APIKey) == 0 {\n\t\tcfg.APIKey = APIKey(name)\n\t}\n\n\tswitch strings.ToLower(name) {\n\tcase \"google\":\n\t\treturn &googleAPI{Config: cfg, Geo: googleGeoURL, Img: googleImgURL}, nil\n\tcase \"bing\":\n\t\treturn &bingAPI{Config: cfg, Geo: bingGeoURL, Img: bingImgURL}, nil\n\tcase \"mapquest\":\n\t\treturn &mapquestAPI{Config: cfg, Geo: mapquestGeoURL, Img: mapquestImgURL}, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"not found: %s\", name)\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(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 NewProvider(t *testing.T) *Provider {\n\treturn &Provider{\n\t\tt: t,\n\t\tcounters: make(map[string]*Counter),\n\t\thistograms: make(map[string]*Histogram),\n\t\tgauges: make(map[string]*Gauge),\n\t\tcardCounters: make(map[string]*xmetrics.HLLCounter),\n\t}\n}", "func NewProvider(f util.Factory, invFactoryFunc inventory.InventoryFactoryFunc) *InventoryProvider {\n\treturn &InventoryProvider{\n\t\tfactory: f,\n\t\tinvFactoryFunc: invFactoryFunc,\n\t}\n}", "func providerFactory(meta discovery.PluginMeta, loglevel hclog.Level) providers.Factory {\n\treturn func() (providers.Interface, error) {\n\t\tclient := goPlugin.NewClient(clientConfig(meta, loglevel))\n\t\t// Request the RPC client so we can get the provider\n\t\t// so we can build the actual RPC-implemented provider.\n\t\trpcClient, err := client.Client()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\traw, err := rpcClient.Dispense(plugin.ProviderPluginName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// store the client so that the plugin can kill the child process\n\t\tp := raw.(*plugin.GRPCProvider)\n\t\tp.PluginClient = client\n\t\treturn p, nil\n\t}\n}", "func NewProvider(conf *fsblkstorage.Conf, indexConfig *blkstorage.IndexConfig, ledgerconfig *ledger.Config, metricsProvider metrics.Provider) (blkstorage.BlockStoreProvider, error) {\n\treturn cdbblkstorage.NewProvider(indexConfig, ledgerconfig)\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(fabricProvider api.FabricProvider) (*ChannelProvider, error) {\n\tcp := ChannelProvider{fabricProvider: fabricProvider}\n\treturn &cp, nil\n}", "func NewProvider(api *API, vid string, expiry, cache time.Duration) *Provider {\n\tv := &Provider{\n\t\trefreshG: func() (StatusResponse, error) {\n\t\t\treturn api.StatusPartial(vid)\n\t\t},\n\t\texpiry: expiry,\n\t}\n\n\tv.statusG = provider.Cached(func() (VehicleStatus, error) {\n\t\treturn v.status(\n\t\t\tfunc() (StatusLatestResponse, error) { return api.StatusLatest(vid) },\n\t\t)\n\t}, cache)\n\n\tv.statusLG = provider.Cached(func() (StatusLatestResponse, error) {\n\t\treturn api.StatusLatest(vid)\n\t}, cache)\n\n\treturn v\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 NewBaseProvider(no *Options) Provider {\n\treturn &BaseProvider{\n\t\tNewActions(no),\n\t\tNewDuelLinks(no),\n\t\tNewMisc(no),\n\t}\n}", "func providerFactory(meta *providercache.CachedProvider) providers.Factory {\n\treturn func() (providers.Interface, error) {\n\t\texecFile, err := meta.ExecutableFile()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tconfig := &plugin.ClientConfig{\n\t\t\tHandshakeConfig: tfplugin.Handshake,\n\t\t\tLogger: logging.NewProviderLogger(\"\"),\n\t\t\tAllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},\n\t\t\tManaged: true,\n\t\t\tCmd: exec.Command(execFile),\n\t\t\tAutoMTLS: enableProviderAutoMTLS,\n\t\t\tVersionedPlugins: tfplugin.VersionedPlugins,\n\t\t\tSyncStdout: logging.PluginOutputMonitor(fmt.Sprintf(\"%s:stdout\", meta.Provider)),\n\t\t\tSyncStderr: logging.PluginOutputMonitor(fmt.Sprintf(\"%s:stderr\", meta.Provider)),\n\t\t}\n\n\t\tclient := plugin.NewClient(config)\n\t\trpcClient, err := client.Client()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\traw, err := rpcClient.Dispense(tfplugin.ProviderPluginName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// store the client so that the plugin can kill the child process\n\t\tprotoVer := client.NegotiatedVersion()\n\t\tswitch protoVer {\n\t\tcase 5:\n\t\t\tp := raw.(*tfplugin.GRPCProvider)\n\t\t\tp.PluginClient = client\n\t\t\treturn p, nil\n\t\tcase 6:\n\t\t\tp := raw.(*tfplugin6.GRPCProvider)\n\t\t\tp.PluginClient = client\n\t\t\treturn p, nil\n\t\tdefault:\n\t\t\tpanic(\"unsupported protocol version\")\n\t\t}\n\t}\n}", "func New(p Provider) (*Config, error) {\n\tm, err := p.Provide()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := &Config{\n\t\tm: m,\n\t}\n\treturn c, nil\n}", "func NewProvider(f util.Factory) *InventoryProvider {\n\treturn &InventoryProvider{\n\t\tfactory: f,\n\t}\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 NewProvider(ctx *pulumi.Context,\n\tname string, args *ProviderArgs, opts ...pulumi.ResourceOption) (*Provider, error) {\n\tif args == nil {\n\t\targs = &ProviderArgs{}\n\t}\n\tif args.AllowUnverifiedSsl == nil {\n\t\targs.AllowUnverifiedSsl = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"VSPHERE_ALLOW_UNVERIFIED_SSL\").(bool))\n\t}\n\tif args.ClientDebug == nil {\n\t\targs.ClientDebug = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"VSPHERE_CLIENT_DEBUG\").(bool))\n\t}\n\tif args.ClientDebugPath == nil {\n\t\targs.ClientDebugPath = pulumi.StringPtr(getEnvOrDefault(\"\", nil, \"VSPHERE_CLIENT_DEBUG_PATH\").(string))\n\t}\n\tif args.ClientDebugPathRun == nil {\n\t\targs.ClientDebugPathRun = pulumi.StringPtr(getEnvOrDefault(\"\", nil, \"VSPHERE_CLIENT_DEBUG_PATH_RUN\").(string))\n\t}\n\tif args.Password == nil {\n\t\targs.Password = pulumi.StringPtr(getEnvOrDefault(\"\", nil, \"VSPHERE_PASSWORD\").(string))\n\t}\n\tif args.PersistSession == nil {\n\t\targs.PersistSession = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"VSPHERE_PERSIST_SESSION\").(bool))\n\t}\n\tif args.RestSessionPath == nil {\n\t\targs.RestSessionPath = pulumi.StringPtr(getEnvOrDefault(\"\", nil, \"VSPHERE_REST_SESSION_PATH\").(string))\n\t}\n\tif args.User == nil {\n\t\targs.User = pulumi.StringPtr(getEnvOrDefault(\"\", nil, \"VSPHERE_USER\").(string))\n\t}\n\tif args.VimKeepAlive == nil {\n\t\targs.VimKeepAlive = pulumi.IntPtr(getEnvOrDefault(0, parseEnvInt, \"VSPHERE_VIM_KEEP_ALIVE\").(int))\n\t}\n\tif args.VimSessionPath == nil {\n\t\targs.VimSessionPath = pulumi.StringPtr(getEnvOrDefault(\"\", nil, \"VSPHERE_VIM_SESSION_PATH\").(string))\n\t}\n\tif args.VsphereServer == nil {\n\t\targs.VsphereServer = pulumi.StringPtr(getEnvOrDefault(\"\", nil, \"VSPHERE_SERVER\").(string))\n\t}\n\tvar resource Provider\n\terr := ctx.RegisterResource(\"pulumi:providers:vsphere\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewProviders() *Providers {\n\treturn &Providers{\n\t\tinternal: provider.Unknown,\n\t\tproviders: map[string]Provider{},\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 NewProvider() acme.Provider {\n\treturn &autocertProvider{}\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 Provider() *schema.Provider {\n\t// TODO: log.Printf(\"[INFO] Creating Provider\")\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"username\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"TRUEMARK_CONFLUENTCLOUD_USERNAME\", \"\"),\n\t\t\t},\n\t\t\t\"password\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tSensitive: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"TRUEMARK_CONFLUENTCLOUD_PASSWORD\", \"\"),\n\t\t\t},\n\t\t},\n\t\tConfigureContextFunc: providerConfigure,\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"truemark-confluent-cloud_environment\": resourceEnvironment(),\n\t\t\t\"truemark-confluent-cloud_kafka_cluster\": resourceKafkaCluster(),\n\t\t\t\"truemark-confluent-cloud_api_key\": resourceAPIKey(),\n\t\t\t\"truemark-confluent-cloud_schema_registry\": resourceSchemaRegistry(),\n\t\t\t\"truemark-confluent-cloud_service_account\": resourceServiceAccount(),\n\t\t},\n\t}\n}", "func GetProvider() Provider {\n\treturn basicProvider{}\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}\n\tp.config = newConfig(p, scopes)\n\treturn p\n}", "func (a *App) Provider() *module.Provider {\n\treturn &module.Provider{\n\t\tConstructor: func() *App { return a },\n\t}\n}", "func newProviderConstructor(name string, fn reflection.Func) (*providerConstructor, error) {\n\tctorType := determineCtorType(fn)\n\tif ctorType == ctorUnknown {\n\t\treturn nil, fmt.Errorf(\"invalid constructor signature, got %s\", fn.Type)\n\t}\n\tprovider := &providerConstructor{\n\t\tname: name,\n\t\tcall: fn,\n\t\tctorType: ctorType,\n\t}\n\t// result type\n\trt := fn.Out(0)\n\t// constructor result with di.Inject - only addressable pointers\n\t// anonymous parameters with di.Inject - only struct\n\tif canInject(rt) && rt.Kind() != reflect.Ptr {\n\t\treturn nil, fmt.Errorf(\"di.Inject not supported for unaddressable result of constructor, use *%s instead\", rt)\n\t}\n\t// if struct is injectable, range over inject fields and parse injectable params\n\tif canInject(rt) {\n\t\tprovider.inject.fields, provider.inject.params = parseFieldParams(rt)\n\t}\n\tvar params parameterList\n\tfor i := 0; i < provider.call.NumIn(); i++ {\n\t\tin := provider.call.In(i)\n\t\tparams = append(params, parameter{\n\t\t\t// haven't found the way to specify name for type in function\n\t\t\tname: \"\",\n\t\t\ttyp: in,\n\t\t})\n\t}\n\tprovider.params = append(params, provider.inject.params...)\n\treturn provider, nil\n}", "func NewProvider(conf *pvtdatastorage.PrivateDataConfig, ledgerconfig *ledger.Config) (*PvtDataProvider, error) {\n\t// create couchdb pvt date store provider\n\tstorageProvider, err := cdbpvtdatastore.NewProvider(conf, ledgerconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// create cache pvt date store provider\n\tcacheProvider := cachedpvtdatastore.NewProvider()\n\n\tp := PvtDataProvider{\n\t\tstorageProvider: storageProvider,\n\t\tcacheProvider: cacheProvider,\n\t}\n\treturn &p, nil\n}", "func NewProviderFactory() *ProviderFactory {\n\tf := ProviderFactory{}\n\treturn &f\n}", "func Provider() *schema.Provider {\n\treturn &schema.Provider{\n\t\tSchema: providerSchema(),\n\t\tResourcesMap: providerResources(),\n\t\tDataSourcesMap: providerDataSources(),\n\t\tConfigureFunc: providerConfigure,\n\t}\n}", "func NewDataProvider() DataProvider {\n\treturn &DefaultDataProvider{}\n}", "func NewProviderFactory() *StoreProvider {\n\treturn &StoreProvider{}\n}", "func Provider() *provider.Provider {\n\treturn p\n}", "func New() *dpms.Module {\n\treturn dpms.New(&provider{})\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(v interface{}) (provider.Provider, error) {\n\ts := Spec{}\n\treturn &s, ioutil.Intermarshal(v, &s)\n}", "func NewLegacyProvider(name string) Provider {\n\treturn Provider{\n\t\tType: name,\n\t\tNamespace: \"-\",\n\t\tHostname: \"registry.terraform.io\",\n\t}\n}" ]
[ "0.8128935", "0.8107089", "0.7947731", "0.78635544", "0.7845964", "0.7836839", "0.7823974", "0.78217673", "0.781741", "0.7722126", "0.77031696", "0.76603645", "0.76545316", "0.75909805", "0.75908655", "0.75712144", "0.75712144", "0.75712144", "0.75712144", "0.7533229", "0.7530402", "0.751132", "0.7510442", "0.74564004", "0.74278265", "0.7417", "0.7394336", "0.73568916", "0.7349749", "0.73445326", "0.7341622", "0.73364246", "0.731003", "0.73093295", "0.7308365", "0.73072135", "0.7303161", "0.72719455", "0.72686034", "0.7245541", "0.7233867", "0.7226462", "0.72208816", "0.72174203", "0.7211086", "0.7200838", "0.7172893", "0.71292436", "0.7126672", "0.7109283", "0.707678", "0.70136535", "0.70089227", "0.7006088", "0.6994199", "0.6988232", "0.697398", "0.69279927", "0.69103956", "0.6901988", "0.6897959", "0.6864341", "0.6858952", "0.6854793", "0.6849328", "0.6845232", "0.68406796", "0.6828028", "0.6821588", "0.6814659", "0.6798042", "0.6779829", "0.6766693", "0.67602", "0.6723076", "0.6722633", "0.6717934", "0.67158276", "0.6707782", "0.66760254", "0.6667955", "0.66547847", "0.66415995", "0.6637253", "0.6635312", "0.66322523", "0.66109306", "0.66075003", "0.65931433", "0.6591591", "0.65854967", "0.65824115", "0.65740156", "0.6552607", "0.6526773", "0.6524054", "0.6508122", "0.6478488", "0.6478141", "0.6402618", "0.63823974" ]
0.0
-1
NewConfig returns a new RAdam Config. It panics if beta1 or beta2 are not in the range [0.0, 1.0).
func NewConfig(stepSize, beta1, beta2, epsilon float64) Config { if !(beta1 >= 0.0 && beta1 < 1.0) { panic("adam: `beta1` must be in the range [0.0, 1.0)") } if !(beta2 >= 0.0 && beta2 < 1.0) { panic("adam: `beta2` must be in the range [0.0, 1.0)") } return Config{ StepSize: stepSize, Beta1: beta1, Beta2: beta2, Epsilon: epsilon, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newConfig() *bqConfig {\n\treturn &bqConfig{\n\t\tarenaSize: cDefaultArenaSize,\n\t\tmaxInMemArenas: cMinMaxInMemArenas,\n\t}\n}", "func NewConfig() Config {\n\treturn Config{\n\t\t0.0, 0.0,\n\t\t4.0, 4.0,\n\t\t1000, 1000,\n\t\t512,\n\t\t\"ramp.json\",\n\t\t\"default.gob\",\n\t\t\"output.jpg\",\n\t\t\"000000\",\n\t\t0.0, 0.0}\n}", "func NewConfig() Config {\n\treturn Config{\"1.0.0\"}\n}", "func newConfig(old *Config, vars Vars) *Config {\n\tv := mergeVars(old.Vars, vars)\n\n\treturn &Config{\n\t\tAppID: old.AppID,\n\t\tVars: v,\n\t}\n}", "func New[T float.DType](c Config) *RAdam[T] {\n\tadam := &RAdam[T]{\n\t\tConfig: c,\n\t\tRoMax: 2.0/(1.0-c.Beta2) - 1.0,\n\t\tTimeStep: 1.0,\n\t}\n\treturn adam\n}", "func newConfigV1() *configV1 {\n\tconf := new(configV1)\n\tconf.Version = mcPreviousConfigVersion\n\t// make sure to allocate map's otherwise Golang\n\t// exits silently without providing any errors\n\tconf.Hosts = make(map[string]*hostConfig)\n\tconf.Aliases = make(map[string]string)\n\treturn conf\n}", "func NewConfig(newServices []services.ServiceConfig, newGroups []services.ServiceGroupConfig) Config {\n\tlog.Printf(\"Creating new config with %d services and %d groups.\\n\", len(newServices), len(newGroups))\n\n\t// Find Env settings common to all services\n\tvar allEnvSlices [][]string\n\tfor _, s := range newServices {\n\t\tallEnvSlices = append(allEnvSlices, s.Env)\n\t}\n\tenv := stringSliceIntersect(allEnvSlices)\n\n\t// Remove common settings from services\n\tvar svcs []services.ServiceConfig\n\tfor _, s := range newServices {\n\t\ts.Env = stringSliceRemoveCommon(env, s.Env)\n\t\tsvcs = append(svcs, s)\n\t}\n\n\tcfg := Config{\n\t\tEnv: env,\n\t\tServices: svcs,\n\t\tGroups: []GroupDef{},\n\t}\n\n\tcfg.AddGroups(newGroups)\n\n\tlog.Printf(\"Config created: %v\", cfg)\n\n\treturn cfg\n}", "func NewConfig() *Config {\n\treturn &Config{\n\t\tHosts: []string{\"localhost:10101\"},\n\t\tGenerate: true,\n\t\tVerify: \"update\",\n\t\tPrefix: \"imaginary-\",\n\t\tThreadCount: 0, // if unchanged, uses workloadspec.threadcount\n\t\t// if workloadspec.threadcount is also unset, defaults to 1\n\t}\n}", "func newConfig(opts ...Option) config {\n\tc := config{\n\t\tMeterProvider: otel.GetMeterProvider(),\n\t}\n\tfor _, opt := range opts {\n\t\topt.apply(&c)\n\t}\n\treturn c\n}", "func newConfig() Config {\n\treturn Config{\n\t\tDefaultContainerConfig: newDefaultContainerConfig(),\n\t\tContainersConfig: map[string]ContainerConfig{},\n\t\tExclude: []string{},\n\t}\n}", "func newConfig() (*config, error) {\n\tec2Metadata := ec2metadata.New(session.Must(session.NewSession()))\n\tregion, err := ec2Metadata.Region()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get region from ec2 metadata\")\n\t}\n\n\tinstanceID, err := ec2Metadata.GetMetadata(\"instance-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get instance id from ec2 metadata\")\n\t}\n\n\tmac, err := ec2Metadata.GetMetadata(\"mac\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get mac from ec2 metadata\")\n\t}\n\n\tsecurityGroups, err := ec2Metadata.GetMetadata(\"security-groups\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get security groups from ec2 metadata\")\n\t}\n\n\tinterfaces, err := ec2Metadata.GetMetadata(\"network/interfaces/macs\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get interfaces from ec2 metadata\")\n\t}\n\n\tsubnet, err := ec2Metadata.GetMetadata(\"network/interfaces/macs/\" + mac + \"/subnet-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get subnet from ec2 metadata\")\n\t}\n\n\tvpc, err := ec2Metadata.GetMetadata(\"network/interfaces/macs/\" + mac + \"/vpc-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get vpc from ec2 metadata\")\n\t}\n\n\treturn &config{region: region,\n\t\tsubnet: subnet,\n\t\tindex: int64(len(strings.Split(interfaces, \"\\n\"))),\n\t\tinstanceID: instanceID,\n\t\tsecurityGroups: strings.Split(securityGroups, \"\\n\"),\n\t\tvpc: vpc,\n\t}, nil\n}", "func NewConfig(\n\trollupCfg *rollup.Config,\n\tl2Genesis *params.ChainConfig,\n\tl1Head common.Hash,\n\tl2Head common.Hash,\n\tl2OutputRoot common.Hash,\n\tl2Claim common.Hash,\n\tl2ClaimBlockNum uint64,\n) *Config {\n\treturn &Config{\n\t\tRollup: rollupCfg,\n\t\tL2ChainConfig: l2Genesis,\n\t\tL1Head: l1Head,\n\t\tL2Head: l2Head,\n\t\tL2OutputRoot: l2OutputRoot,\n\t\tL2Claim: l2Claim,\n\t\tL2ClaimBlockNumber: l2ClaimBlockNum,\n\t\tL1RPCKind: sources.RPCKindBasic,\n\t}\n}", "func newConfig() *Config {\n\t// TODO: use config as default, allow setting some values per-job\n\t// and prevent config changes affecting already-running tasks\n\treturn &Config{\n\t\tPath: DefaultPath,\n\t\tDatastorePrefix: \"MP_\",\n\t\tDefaultQueue: \"\",\n\t\tShards: 8,\n\t\tOversampling: 32,\n\t\tLeaseDuration: time.Duration(30) * time.Second,\n\t\tLeaseTimeout: time.Duration(10)*time.Minute + time.Duration(30)*time.Second,\n\t\tTaskTimeout: time.Duration(10)*time.Minute - time.Duration(30)*time.Second,\n\t\tCursorTimeout: time.Duration(50) * time.Second,\n\t\tRetries: 31,\n\t\tLogVerbose: false,\n\t\tHost: \"\",\n\t}\n}", "func newConfig() *config {\n\treturn &config{\n\t\tAddr: \":80\",\n\t\tCacheSize: 1000,\n\t\tLogLevel: \"info\",\n\t\tRequestTimeout: 3000,\n\t\tTargetAddr: \"https://places.aviasales.ru\",\n\t}\n}", "func newConfig() *Config {\n\n\tc := &Config{}\n\tvar logLevel, bServers, dServers string\n\n\tflag.StringVar(&c.ControlAddress, \"controlAddress\", \"localhost:4000\",\n\t\t\"Control process IP address, default localhost:4000\")\n\n\tflag.BoolVar(&c.Broadcast, \"broadcast\", true,\n\t\t\"Set to false to squash actual broadcast.\")\n\n\tflag.IntVar(&c.Bclients, \"bClients\", 1,\n\t\t\"The number of broadcast clients; Default 1\")\n\n\tflag.IntVar(&c.Dclients, \"dClients\", 1,\n\t\t\"The number of deliver clients; Default 1\")\n\n\tflag.IntVar(&c.Channels, \"channels\", 1,\n\t\t\"The number of channels; Default 1\")\n\n\tflag.StringVar(&bServers, \"bServers\", \"\",\n\t\t\"A comma-separated list of IP:PORT of broadcast servers to target; Required\")\n\n\tflag.StringVar(&dServers, \"dServers\", \"\",\n\t\t\"A comma-separated list of IP:PORT of deliver servers to target; Defaults to broadcast szervers\")\n\n\tflag.IntVar(&c.Transactions, \"transactions\", 1,\n\t\t\"The number of transactions broadcast to each client's servers; Default 1\")\n\n\tflag.IntVar(&c.Payload, \"payload\", TxHeaderSize,\n\t\t\"Payload size in bytes; Minimum/default is the performance header size (56 bytes)\")\n\n\tflag.IntVar(&c.Burst, \"burst\", 1,\n\t\t\"The number of transactions burst to each server during broadcast; Dafault 1\")\n\n\tflag.DurationVar(&c.Delay, \"delay\", 0,\n\t\t\"The delay between bursts, in the form required by time.ParseDuration(); Default is no delay\")\n\n\tflag.IntVar(&c.Window, \"window\", 100,\n\t\t\"The number of blocks allowed to be delivered without an ACK; Default 100\")\n\n\tflag.IntVar(&c.AckEvery, \"ackEvery\", 70,\n\t\t\"The deliver client will ACK every (this many) blocks; Default 70\")\n\n\tflag.DurationVar(&c.Timeout, \"timeout\", 30*time.Second,\n\t\t\"The initialization timeout, in the form required by time.ParseDuration(); Default 30s\")\n\n\tflag.BoolVar(&c.LatencyAll, \"latencyAll\", false,\n\t\t\"By default, only block latencies are reported. Set -latencyAll=true to report all transaction latencies\")\n\n\tflag.StringVar(&c.LatencyDir, \"latencyDir\", \"\",\n\t\t\"The directory to contain latency files; These files are only created if -latencyDir is specified\")\n\n\tflag.StringVar(&c.LatencyPrefix, \"latencyPrefix\", \"client\",\n\t\t\"Prefix for latency file names\")\n\n\tflag.StringVar(&logLevel, \"logLevel\", \"info\",\n\t\t\"The global logging level; Default 'info'\")\n\n\tflag.StringVar(&c.ControlLogging, \"controlLogging\", \"\",\n\t\t\"Override logging level for the 'control' process\")\n\n\tflag.StringVar(&c.BroadcastLogging, \"broadcastLogging\", \"\",\n\t\t\"Override logging level for the 'broadcast' processes\")\n\n\tflag.StringVar(&c.DeliverLogging, \"deliverLogging\", \"\",\n\t\t\"Override logging level for the 'deliver' processes\")\n\n\tflag.Parse()\n\n\tif c.ControlLogging == \"\" {\n\t\tc.ControlLogging = logLevel\n\t}\n\tif c.BroadcastLogging == \"\" {\n\t\tc.BroadcastLogging = logLevel\n\t}\n\tif c.DeliverLogging == \"\" {\n\t\tc.DeliverLogging = logLevel\n\t}\n\n\tinitLogging(c.ControlLogging)\n\n\trequireUint16(\"bclients\", c.Bclients)\n\trequireUint16(\"dclients\", c.Dclients)\n\trequireUint16(\"channels\", c.Channels)\n\trequireNonEmpty(\"bServers\", bServers)\n\tif dServers == \"\" {\n\t\tdServers = bServers\n\t}\n\trequireUint32(\"transactions\", c.Transactions)\n\trequirePosInt(\"payload\", c.Payload)\n\tif c.Payload < TxHeaderSize {\n\t\tlogger.Infof(\"Payload size will be set to the default (%d bytes)\\n\",\n\t\t\tTxHeaderSize)\n\t\tc.Payload = TxHeaderSize\n\t}\n\trequirePosInt(\"burst\", c.Burst)\n\trequirePosDuration(\"delay\", c.Delay)\n\trequirePosInt(\"window\", c.Window)\n\trequirePosInt(\"ackevery\", c.AckEvery)\n\trequireLE(\"ackevery\", \"window\", c.AckEvery, c.Window)\n\trequirePosDuration(\"timeout\", c.Timeout)\n\n\tc.Bservers = strings.Split(bServers, \",\")\n\tc.NumBservers = len(c.Bservers)\n\n\tc.Dservers = strings.Split(dServers, \",\")\n\tc.NumDservers = len(c.Dservers)\n\n\tlogger.Infof(\"Configuration\")\n\tlogger.Infof(\" Broadcast Servers: %d: %v\", c.NumBservers, c.Bservers)\n\tlogger.Infof(\" Broadcast Clients: %d\", c.Bclients)\n\tlogger.Infof(\" Deliver Servers : %d: %v\", c.NumDservers, c.Dservers)\n\tlogger.Infof(\" Deliver Clients : %d\", c.Dclients)\n\tlogger.Infof(\" Channels : %d\", c.Channels)\n\tlogger.Infof(\" Transactions : %d\", c.Transactions)\n\tlogger.Infof(\" Payload : %d\", c.Payload)\n\tlogger.Infof(\" Burst : %d\", c.Burst)\n\tlogger.Infof(\" Delay : %s\", c.Delay.String())\n\tlogger.Infof(\" Window : %d\", c.Window)\n\tlogger.Infof(\" AckEvery : %d\", c.AckEvery)\n\tlogger.Infof(\" Broadcast? : %v\", c.Broadcast)\n\n\tc.TotalBroadcastClients =\n\t\tuint64(c.NumBservers) * uint64(c.Channels) * uint64(c.Bclients)\n\tc.TxBroadcastPerClient = uint64(c.Transactions)\n\tc.BytesBroadcastPerClient = c.TxBroadcastPerClient * uint64(c.Payload)\n\tc.TotalTxBroadcast = uint64(c.TotalBroadcastClients) * c.TxBroadcastPerClient\n\tc.TotalBytesBroadcast = c.TotalTxBroadcast * uint64(c.Payload)\n\n\tc.TotalDeliverClients =\n\t\tuint64(c.NumDservers) * uint64(c.Channels) * uint64(c.Dclients)\n\tc.TxDeliveredPerClient =\n\t\tuint64(c.NumBservers) * uint64(c.Bclients) * uint64(c.Transactions)\n\tc.BytesDeliveredPerClient = c.TxDeliveredPerClient * uint64(c.Payload)\n\tc.TotalTxDelivered = c.TxDeliveredPerClient * c.TotalDeliverClients\n\tc.TotalBytesDelivered = c.TotalTxDelivered * uint64(c.Payload)\n\n\treturn c\n}", "func newConfig(appName string, pathToKeybase string, log Log, ignoreSnooze bool) (*config, error) {\n\tcfg := newDefaultConfig(appName, pathToKeybase, log, ignoreSnooze)\n\terr := cfg.load()\n\treturn &cfg, err\n}", "func New() (Config, error) {\n\tconfig := Config{}\n\tif err := env.Parse(&config); err != nil {\n\t\treturn config, errors.Wrap(err, \"failed to load enviroment variables\")\n\t}\n\n\tconfig.Baker.Blacklist = cleanList(config.Baker.Blacklist)\n\tconfig.Baker.DexterLiquidityContracts = cleanList(config.Baker.DexterLiquidityContracts)\n\n\tif config.Notifications.Twilio.To != nil {\n\t\tconfig.Notifications.Twilio.To = cleanList(config.Notifications.Twilio.To)\n\t}\n\n\terr := validator.New().Struct(&config)\n\tif err != nil {\n\t\treturn config, errors.Wrap(err, \"invalid input\")\n\t}\n\n\treturn config, nil\n}", "func NewConfig(admissionV1Enabled, namespaceSelectorEnabled bool) Config {\n\treturn Config{\n\t\twebhookName: config.Datadog.GetString(\"admission_controller.webhook_name\"),\n\t\tsecretName: config.Datadog.GetString(\"admission_controller.certificate.secret_name\"),\n\t\tnamespace: common.GetResourcesNamespace(),\n\t\tadmissionV1Enabled: admissionV1Enabled,\n\t\tnamespaceSelectorEnabled: namespaceSelectorEnabled,\n\t\tsvcName: config.Datadog.GetString(\"admission_controller.service_name\"),\n\t\tsvcPort: int32(443),\n\t\ttimeout: config.Datadog.GetInt32(\"admission_controller.timeout_seconds\"),\n\t\tfailurePolicy: config.Datadog.GetString(\"admission_controller.failure_policy\"),\n\t\treinvocationPolicy: config.Datadog.GetString(\"admission_controller.reinvocation_policy\"),\n\t}\n}", "func NewConfig(logger *zap.Logger) *config {\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\tlogger.Fatal(\"Error getting current working directory.\", zap.Error(err))\n\t}\n\treturn &config{\n\t\tName: \"nakama\",\n\t\tDatadir: filepath.Join(cwd, \"data\"),\n\t\tShutdownGraceSec: 0,\n\t\tLogger: NewLoggerConfig(),\n\t\tMetrics: NewMetricsConfig(),\n\t\tSession: NewSessionConfig(),\n\t\tSocket: NewSocketConfig(),\n\t\tDatabase: NewDatabaseConfig(),\n\t\tSocial: NewSocialConfig(),\n\t\tRuntime: NewRuntimeConfig(),\n\t\tMatch: NewMatchConfig(),\n\t\tTracker: NewTrackerConfig(),\n\t\tConsole: NewConsoleConfig(),\n\t\tLeaderboard: NewLeaderboardConfig(),\n\t}\n}", "func NewConfig(opts ...Option) *Config {\n\tc := Config{\n\t\ttree: make(tree),\n\t\tParms: &Parms{\n\t\t\tDex: list{RWMutex: &sync.RWMutex{}, entry: make(entry)},\n\t\t\tExc: list{RWMutex: &sync.RWMutex{}, entry: make(entry)},\n\t\t},\n\t}\n\tfor _, opt := range opts {\n\t\topt(&c)\n\t}\n\treturn &c\n}", "func New() *Config {\n\tc := &Config{\n\t\tTargets: make([]string, 0),\n\t}\n\tsetDefaultValues(c)\n\n\treturn c\n}", "func newConfig() *Config {\n\treturn &Config{\n\t\tgeneral{\n\t\t\tVerbose: false,\n\t\t},\n\t\tserver{\n\t\t\tType: \"http\",\n\t\t\tHost: \"0.0.0.0\",\n\t\t},\n\t\tmongo{\n\t\t\tHost: \"0.0.0.0:27017\",\n\t\t\tDatabase: \"etlog\",\n\t\t\tCollection: \"logs\",\n\t\t},\n\t}\n}", "func New() *Config {\n\tc := &Config{\n\t\tAgent: &AgentConfig{\n\t\t\tEventReceiverCount: 5,\n\t\t\tEventQueueLimit: 50,\n\t\t\tHealthCheckPort: 10240,\n\t\t\tLogLevel: \"info\",\n\t\t},\n\t\tPlugins: make([]*pluginrunner.PluginRunner, 0),\n\t\tEventKinds: make(map[events.EventKind]bool),\n\t}\n\treturn c\n}", "func NewConfig(args []string) (*Config, error) {\n\tconfig := &Config{}\n\tif len(args) == 0 {\n\t\treturn config, errors.New(\"arguments cannot be empty\")\n\t}\n\n\t// load default config values\n\tconfig.FlagPort = defaultHTTPPort\n\tconfig.FlagGetRequestTimeout = defaultGETRequestTimeout\n\n\tflagSet := flag.NewFlagSet(dcosLog, flag.ContinueOnError)\n\tconfig.setFlags(flagSet)\n\n\t// override with user provided arguments\n\tif err := flagSet.Parse(args[1:]); err != nil {\n\t\treturn config, err\n\t}\n\n\t// read config file if exists.\n\tif err := readAndUpdateConfigFile(config); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// set debug level\n\tif config.FlagVerbose {\n\t\tlogrus.SetLevel(logrus.DebugLevel)\n\t\tlogrus.Debug(\"Using debug level\")\n\t}\n\n\treturn config, validateConfigStruct(config)\n}", "func NewConfig(args []string) *Config {\n\tintervalMs := defaultInterval\n\tvar c Config\n\tc.g = getopt.New()\n\tc.g.SetParameters(\"[file ...]\")\n\tc.g.FlagLong(&c.Lines, \"lines\", 'l', \"print the newline counts\")\n\tc.g.FlagLong(&c.Words, \"words\", 'w', \"print the word counts\")\n\tc.g.FlagLong(&c.Chars, \"chars\", 'm', \"print the character counts\")\n\tc.g.FlagLong(&c.Bytes, \"bytes\", 'c', \"print the byte counts\")\n\tc.g.FlagLong(&c.MaxLineLength, \"max-line-length\", 'L', \"print the maximum display width\")\n\tc.g.FlagLong(&c.Files0From, \"files0-from\", 0,\n\t\t\"read input from the files specified by NUL-terminated names in file F\",\n\t\t\"F\")\n\tc.g.FlagLong(&intervalMs, \"interval\", 'i',\n\t\tfmt.Sprintf(\"set the update interval to T ms (default %d ms)\", defaultInterval),\n\t\t\"T\")\n\tc.g.FlagLong(&c.Help, \"help\", 0, \"display this help and exit\")\n\tc.g.FlagLong(&c.Version, \"version\", 0, \"output version information and exit\")\n\tc.g.Parse(args)\n\tif intervalMs < 0 {\n\t\tlwcutil.Fatal(\"Update interval cannot be negative\")\n\t}\n\tc.Interval = time.Duration(intervalMs) * time.Millisecond\n\tc.Files = c.g.Args()\n\tif !(c.Lines || c.Words || c.Chars || c.Bytes || c.MaxLineLength) {\n\t\tc.Lines = true\n\t\tc.Words = true\n\t\tc.Bytes = true\n\t}\n\treturn &c\n}", "func NewConfig(cfgPath string, cfg *PkgrConfig) {\n\terr := loadConfigFromPath(cfgPath)\n\tif err != nil {\n\t\tlog.Fatal(\"could not detect config at supplied path: \" + cfgPath)\n\t}\n\terr = viper.Unmarshal(cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"error parsing pkgr.yml: %s\\n\", err)\n\t}\n\n\tif len(cfg.Library) == 0 {\n\t\trs := rcmd.NewRSettings(cfg.RPath)\n\t\trVersion := rcmd.GetRVersion(&rs)\n\t\tcfg.Library = getLibraryPath(cfg.Lockfile.Type, cfg.RPath, rVersion, rs.Platform, cfg.Library)\n\t}\n\n\t// For all cfg\tvalues that can be repos, make sure that ~ is expanded to the home directory.\n\tcfg.Library = expandTilde(cfg.Library)\n\tcfg.RPath = expandTilde(cfg.RPath)\n\tcfg.Tarballs = expandTildes(cfg.Tarballs)\n\tcfg.Descriptions = expandTildes(cfg.Descriptions)\n\tcfg.Repos = expandTildesRepos(cfg.Repos)\n\tcfg.Logging.All = expandTilde(cfg.Logging.All)\n\tcfg.Logging.Install = expandTilde(cfg.Logging.Install)\n\tcfg.Cache = expandTilde(cfg.Cache)\n\n\treturn\n}", "func NewConfig() *Config {\n\treturn &Config{\n\t\tMode: \t\t gin.ReleaseMode,\n\t\tMiddlewares: []string{},\n\t\tHealthz: \t true,\n\t}\n}", "func New() (*Config, error) {\n\tflags := pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)\n\tcfg := &Config{\n\t\tFlags: flags,\n\t\tHTTPAddr: flags.StringP(\"http-addr\", \"l\", \":8080\", \"http listen address\"),\n\t\tHTTPReadHeaderTimeout: flags.DurationP(\"http-timeout\", \"h\", 1*time.Second, \"http timeout for reading request headers\"),\n\t\tCallTimeout: flags.DurationP(\"call-timeout\", \"t\", 0*time.Second, \"function call timeout\"),\n\t\tReadLimit: flags.Int64(\"read-limit\", -1, \"limit the amount of data which can be contained in a requests body\"),\n\t\tFramer: flags.StringP(\"framer\", \"f\", \"\", \"afterburn framer to use: line, json or http\"),\n\t\tBuffer: flags.BoolP(\"buffer\", \"b\", false, \"buffer output before writing\"),\n\t}\n\tif err := cfg.parseCommandline(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := cfg.parseEnvironment(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn cfg, nil\n}", "func newConfig(serviceName string) config {\n\t// Use stdlib to parse. If it's an invalid value and doesn't parse, log it\n\t// and keep going. It should already be false on error but we force it to\n\t// be extra clear that it's failing closed.\n\tinsecure, err := strconv.ParseBool(os.Getenv(\"OTEL_EXPORTER_OTLP_INSECURE\"))\n\tif err != nil {\n\t\tinsecure = false\n\t\tlog.Println(\"Invalid boolean value in OTEL_EXPORTER_OTLP_INSECURE. Try true or false.\")\n\t}\n\n\treturn config{\n\t\tservicename: serviceName,\n\t\tendpoint: os.Getenv(\"OTEL_EXPORTER_OTLP_ENDPOINT\"),\n\t\tinsecure: insecure,\n\t}\n}", "func newCfg() *cfg {\n\tcfg := &cfg{}\n\n\tflag.IntVar(&cfg.pool, \"pool\", 32,\n\t\t\"count of the workers in pool (default: 32)\")\n\n\tflag.BoolVar(&cfg.greedy, \"greedy\", true,\n\t\t\"enable greedy mode (default: true)\")\n\n\tflag.DurationVar(&cfg.dur, \"duration\", time.Minute,\n\t\t\"pool's heartbeat duration\")\n\n\tflag.Parse()\n\n\treturn cfg\n}", "func NewConfig() *Config {\n\tcfg := &Config{}\n\tcfg.flagSet = flag.NewFlagSet(\"heartbeat-bench\", flag.ContinueOnError)\n\tfs := cfg.flagSet\n\tfs.ParseErrorsWhitelist.UnknownFlags = true\n\tfs.StringVar(&cfg.configFile, \"config\", \"\", \"config file\")\n\tfs.StringVar(&cfg.PDAddr, \"pd\", \"http://127.0.0.1:2379\", \"pd address\")\n\tfs.StringVar(&cfg.StatusAddr, \"status-addr\", \"http://127.0.0.1:20180\", \"status address\")\n\n\treturn cfg\n}", "func newConfig() (*rest.Config, error) {\n // try in cluster config first, it should fail quickly on lack of env vars\n cfg, err := inClusterConfig()\n if err != nil {\n cfg, err = clientcmd.BuildConfigFromFlags(\"\", clientcmd.RecommendedHomeFile)\n if err != nil {\n return nil, errors.Wrap(err, \"failed to get InClusterConfig and Config from kube_config\")\n }\n }\n return cfg, nil\n}", "func New() *Config {\n\treturn &Config{\n\t\tOptions: AppConfig{\n\t\t\tHoldtime: 12 * time.Hour, // do not retry a successful device backup before this holdtime\n\t\t\tScanInterval: 10 * time.Minute, // interval for scanning device table\n\t\t\tMaxConcurrency: 20, // limit for concurrent backup jobs\n\t\t\tMaxConfigFiles: 120, // limit for per-device saved files\n\t\t\tMaxConfigLoadSize: 10000000, // 10M limit max config file size for loading to memory\n\t\t},\n\t\tDevices: []DevConfig{},\n\t}\n}", "func NewConfig(ver string) (Config, error) {\n\tif ver == \"\" {\n\t\treturn Config{}, errors.New(\"version is required\")\n\t}\n\n\treturn Config{Version: ver}, nil\n}", "func newConfig(envParams envParams) error {\n\t// Initialize server config.\n\tsrvCfg := newServerConfigV14()\n\n\t// If env is set for a fresh start, save them to config file.\n\tif globalIsEnvCreds {\n\t\tsrvCfg.SetCredential(envParams.creds)\n\t}\n\n\tif globalIsEnvBrowser {\n\t\tsrvCfg.SetBrowser(envParams.browser)\n\t}\n\n\t// Create config path.\n\tif err := createConfigDir(); err != nil {\n\t\treturn err\n\t}\n\n\t// hold the mutex lock before a new config is assigned.\n\t// Save the new config globally.\n\t// unlock the mutex.\n\tserverConfigMu.Lock()\n\tserverConfig = srvCfg\n\tserverConfigMu.Unlock()\n\n\t// Save config into file.\n\treturn serverConfig.Save()\n}", "func NewConfig() *Config {\n\treturn &Config{\n\t\tPort: \"2000\",\n\t\tDomain: \".dev\",\n\t\tURLPattern: `.*\\.dev$`,\n\t\tServices: nil,\n\t}\n}", "func NewConfig() Config {\n\treturn Config{\n\t\tType: TypeNone,\n\t\tJaeger: NewJaegerConfig(),\n\t\tNone: struct{}{},\n\t}\n}", "func NewConfig(name string, logr klog.Logger, caller bool, callDepth int) *Config {\n\treturn &Config{\n\t\tName: name,\n\t\tLogger: logr,\n\t\tCaller: caller,\n\t\tCallDepth: callDepth,\n\t}\n}", "func NewConfig(cfg map[string]interface{}) Config {\n\treturn Config{Data: cfg}\n}", "func NewConfig(locator resource.ReadLocator, renderAPI render.API, shaders ShaderCollection) *Config {\n\treturn &Config{\n\t\tlocator: locator,\n\t\trenderAPI: renderAPI,\n\t\tshaders: shaders,\n\t}\n}", "func New(opts ...Option) Config {\n\tcfg := Config{\n\t\tFormat: gnfmt.CSV,\n\t\tLanguage: lang.English,\n\t\tWithBayes: true,\n\t\tBayesOddsThreshold: 80.0,\n\t\tTokensAround: 0,\n\t\tVerifierURL: \"https://verifier.globalnames.org/api/v1/\",\n\t\tTikaURL: \"https://tika.globalnames.org\",\n\t\tAPIDoc: \"https://apidoc.globalnames.org/gnfinder\",\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(&cfg)\n\t}\n\n\tif len(cfg.DataSources) > 0 {\n\t\tcfg.WithVerification = true\n\t}\n\treturn cfg\n}", "func New() *Config {\n\treturn &Config{\n\t\tMode: ModeDevelopment,\n\t\tconfigs: make([]map[string]string, 3),\n\t}\n}", "func NewConfig(fns []ConfigFunc) *Config {\n\t// TODO: This function returns a pointer while most of the other returns values. Decide which way to do it.\n\tconfig := &Config{}\n\tfor _, fn := range fns {\n\t\tfn(config)\n\t}\n\treturn config\n}", "func NewConfig(args ...interface{}) (*Config, error) {\n\t// Implementation note: This factory is written with future\n\t// extensibility in mind. Only specific types are supported as\n\t// input, but in the future more might be added.\n\t//\n\t// This constructor ensures that callers can't construct\n\t// invalid Config values.\n\tvar c Config\n\tfor _, arg := range args {\n\t\tif afs, ok := arg.(AccessFSSet); ok {\n\t\t\tif !c.handledAccessFS.isEmpty() {\n\t\t\t\treturn nil, errors.New(\"only one AccessFSSet may be provided\")\n\t\t\t}\n\t\t\tif !afs.valid() {\n\t\t\t\treturn nil, errors.New(\"unsupported AccessFSSet value; upgrade go-landlock?\")\n\t\t\t}\n\t\t\tc.handledAccessFS = afs\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"unknown argument %v; only AccessFSSet-type argument is supported\", arg)\n\t\t}\n\t}\n\treturn &c, nil\n}", "func NewConfig(impostersPath, host string, port int, opts ...ConfigOpt) (Config, error) {\n\tcfg := Config{\n\t\tImpostersPath: impostersPath,\n\t\tHost: host,\n\t\tPort: port,\n\t}\n\n\tfor _, opt := range opts {\n\t\tif err := opt(&cfg); err != nil {\n\t\t\treturn Config{}, err\n\t\t}\n\t}\n\n\treturn cfg, nil\n}", "func NewConfig() *Config {\n\treturn &Config{\n\t\tstderr: new(broadcaster.Unbuffered),\n\t\tstdout: new(broadcaster.Unbuffered),\n\t}\n}", "func New(opts ...Option) *Config {\n\tcfg := &Config{\n\t\tWindowWidth: 800,\n\t\tWindowHeight: 600,\n\t\tSize: 5,\n\t\tSquareSize: 48,\n\t\tDotRadius: 16,\n\t\tColor: &sdl.Color{R: 168, G: 168, B: 168, A: 255},\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(cfg)\n\t}\n\n\treturn cfg\n}", "func New() *Config {\n\treturn &Config{\n\t\tChecks: []*checkInstance{},\n\t}\n}", "func New(config *interface{}) {\n\tv := reflect.ValueOf(*config)\n\tfieldCount := v.NumField()\n\n\tfor i := 0; i < fieldCount; i++ {\n\t\tswitch v.Field(i).Kind() {\n\t\tcase reflect.Int:\n\t\t\tval := reflect.ValueOf(getIntFromEnv(v.Field(i).Type().Name()))\n\t\t\tv.Field(i).Set(val)\n\t\tcase reflect.String:\n\t\t\tval := reflect.ValueOf(getStringFromEnv(v.Field(i).Type().Name()))\n\t\t\tv.Field(i).Set(val)\n\t\tcase reflect.Bool:\n\t\t\tval := reflect.ValueOf(getBoolFromEnv(v.Field(i).Type().Name()))\n\t\t\tv.Field(i).Set(val)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"error building config -- %s is not of an acceptable type\", v.Field(i).Type().Name())\n\t\t}\n\t}\n}", "func NewConfig() Config {\n\treturn Config{\n\t\tFormat: \"auto\",\n\t\tLevel: zapcore.InfoLevel,\n\t}\n}", "func FromConfig(rows int, batchSize int, payloadBytes int, ranges int) workload.Generator {\n\tif ranges > rows {\n\t\tranges = rows\n\t}\n\tif batchSize <= 0 {\n\t\tbatchSize = defaultBatchSize\n\t}\n\treturn workload.FromFlags(bankMeta,\n\t\tfmt.Sprintf(`--rows=%d`, rows),\n\t\tfmt.Sprintf(`--batch-size=%d`, batchSize),\n\t\tfmt.Sprintf(`--payload-bytes=%d`, payloadBytes),\n\t\tfmt.Sprintf(`--ranges=%d`, ranges),\n\t)\n}", "func NewConfig() Config {\n\treturn Config{}\n}", "func NewConfig() Config {\n\treturn Config{}\n}", "func NewConfig() *Config {\n\treturn NewConfigWithID(operatorType)\n}", "func NewConfig() *Config {\n\treturn NewConfigWithID(operatorType)\n}", "func NewConfig() *Config {\n\treturn NewConfigWithID(operatorType)\n}", "func NewConfig() *Config {\n\treturn NewConfigWithID(operatorType)\n}", "func NewConfig() *Config {\n\treturn &Config{values: map[string]string{}, Color: &Color{colorSettings{}, colorFuncs{}}}\n}", "func NewConfig(cs config.Service, gm *config.GameModel, configPath string, logger log.Logger) *ConfigBridge {\n\tb := NewConfigBridge(nil)\n\n\tb.configPath = configPath\n\n\t// Setup dependencies.\n\tb.config = cs\n\tb.logger = logger\n\n\t// Setup model.\n\tb.SetGames(gm)\n\n\t// Set initial state.\n\tb.SetPrerequisitesLoaded(false)\n\tb.SetPrerequisitesError(false)\n\n\treturn b\n}", "func NewConfig(log logging.Logger) *Config {\n\n\tcfg := &Config{\n\t\tLogger: log,\n\t\tConfig: cluster.NewConfig(),\n\t\tPartition: -1,\n\t\tPartitioner: sarama.NewHashPartitioner,\n\t\tRequiredAcks: AcksUnset,\n\t}\n\n\treturn cfg\n}", "func New(name string) *Config {\n\treturn &Config{name: name}\n}", "func NewConfig() (*Config, error) {\n\tconfig := &Config{\n\t\tInterval: Interval,\n\t\tFailOnErrors: true,\n\t\tOnDuplicate: Warn,\n\t\tCtx: context.Background(),\n\t\tServing: ServingConfig{\n\t\t\tUse: false,\n\t\t\tScaleToZero: true,\n\t\t},\n\t\tTraceExportLimit: defaultTraceExportLimit,\n\t\tWathola: Wathola{\n\t\t\tImageResolver: pkgTest.ImagePath,\n\t\t\tConfigToml: ConfigToml{\n\t\t\t\tConfigTemplate: defaultConfigFilename,\n\t\t\t\tConfigMapName: defaultConfigName,\n\t\t\t\tConfigMountPoint: fmt.Sprintf(\"%s/%s\", defaultHomedir, defaultConfigHomedirPath),\n\t\t\t\tConfigFilename: defaultConfigFilename,\n\t\t\t},\n\t\t\tHealthEndpoint: defaultHealthEndpoint,\n\t\t\tSystemUnderTest: sut.NewDefault(),\n\t\t},\n\t}\n\n\tif err := envconfig.Process(prefix, config); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %v\", ErrInvalidConfig, err)\n\t}\n\n\treturn config, nil\n}", "func NewConfigs() *Configs {\n\treturn &Configs{\n\t\tPort: DefaultPort,\n\t\tShutdownTimeout: DefaultShutdownTimeout,\n\t\tReadTimeout: DefaultReadTimeout,\n\t\tWriteTimeout: DefaultWriteTimeout,\n\t\tPingEndpoint: DefaultPingEndpoint,\n\t\tHealthcheckEndpoint: DefaultHealthcheckEndpoint,\n\t\tShutdownEndpoint: DefaultShutdownEndpoint,\n\t}\n}", "func New() *Config {\n\treturn &Config{}\n}", "func New() *Config {\n\treturn &Config{}\n}", "func NewConfig() Config {\n\treturn Config{\n\t\tBindAddress: DefaultBindAddress,\n\t\tDatabase: DefaultDatabase,\n\t\tRetentionPolicy: DefaultRetentionPolicy,\n\t\tConsistencyLevel: DefaultConsistencyLevel,\n\t\tTLSEnabled: false,\n\t\tCertificate: DefaultCertificate,\n\t\tBatchSize: DefaultBatchSize,\n\t\tBatchPending: DefaultBatchPending,\n\t\tBatchTimeout: toml.Duration(DefaultBatchTimeout),\n\t\tLogPointErrors: true,\n\t}\n}", "func NewConfig() Config {\n\tmetricsConf := metrics.NewConfig()\n\tmetricsConf.Prefix = \"benthos\"\n\n\treturn Config{\n\t\tReportPeriodMS: 60000,\n\t\tHTTP: api.NewConfig(),\n\t\tInput: input.NewConfig(),\n\t\tLogger: log.NewLoggerConfig(),\n\t\tMetrics: metricsConf,\n\t\tSystemCloseTimeoutMS: 20000,\n\t}\n}", "func NewConfig(cfg map[string]interface{}) *Config {\n\tif cfg == nil {\n\t\tcfg = make(map[string]interface{})\n\t}\n\treturn &Config{\n\t\tm: cfg,\n\t}\n}", "func newConfigV101() *configV1 {\n\tconf := new(configV1)\n\tconf.Version = mcCurrentConfigVersion\n\t// make sure to allocate map's otherwise Golang\n\t// exits silently without providing any errors\n\tconf.Hosts = make(map[string]*hostConfig)\n\tconf.Aliases = make(map[string]string)\n\n\tlocalHostConfig := new(hostConfig)\n\tlocalHostConfig.AccessKeyID = \"\"\n\tlocalHostConfig.SecretAccessKey = \"\"\n\n\ts3HostConf := new(hostConfig)\n\ts3HostConf.AccessKeyID = globalAccessKeyID\n\ts3HostConf.SecretAccessKey = globalSecretAccessKey\n\n\t// Your example host config\n\texampleHostConf := new(hostConfig)\n\texampleHostConf.AccessKeyID = globalAccessKeyID\n\texampleHostConf.SecretAccessKey = globalSecretAccessKey\n\n\tplayHostConfig := new(hostConfig)\n\tplayHostConfig.AccessKeyID = \"\"\n\tplayHostConfig.SecretAccessKey = \"\"\n\n\tdlHostConfig := new(hostConfig)\n\tdlHostConfig.AccessKeyID = \"\"\n\tdlHostConfig.SecretAccessKey = \"\"\n\n\tconf.Hosts[exampleHostURL] = exampleHostConf\n\tconf.Hosts[\"localhost:*\"] = localHostConfig\n\tconf.Hosts[\"127.0.0.1:*\"] = localHostConfig\n\tconf.Hosts[\"s3*.amazonaws.com\"] = s3HostConf\n\tconf.Hosts[\"play.minio.io:9000\"] = playHostConfig\n\tconf.Hosts[\"dl.minio.io:9000\"] = dlHostConfig\n\n\taliases := make(map[string]string)\n\taliases[\"s3\"] = \"https://s3.amazonaws.com\"\n\taliases[\"play\"] = \"https://play.minio.io:9000\"\n\taliases[\"dl\"] = \"https://dl.minio.io:9000\"\n\taliases[\"localhost\"] = \"http://localhost:9000\"\n\tconf.Aliases = aliases\n\n\treturn conf\n}", "func MergeConfig(a, b *Config) *Config {\n\tresult := *a\n\n\tif b.Address != \"\" {\n\t\tresult.Address = b.Address\n\t}\n\tif b.Port != 0 {\n\t\tresult.Port = b.Port\n\t}\n\tif b.LogLevel != \"\" {\n\t\tresult.LogLevel = b.LogLevel\n\t}\n\tif b.EnableSyslog {\n\t\tresult.EnableSyslog = true\n\t}\n\tif b.SyslogFacility != \"\" {\n\t\tresult.SyslogFacility = b.SyslogFacility\n\t}\n\tif b.ConsulAddr != \"\" {\n\t\tresult.ConsulAddr = b.ConsulAddr\n\t}\n\tif b.ConsulPort != 0 {\n\t\tresult.ConsulPort = b.ConsulPort\n\t}\n\tif b.ConsulDatacenter != \"\" {\n\t\tresult.ConsulDatacenter = b.ConsulDatacenter\n\t}\n\tif b.LogstashHost != \"\" {\n\t\tresult.LogstashHost = b.LogstashHost\n\t}\n\tif b.LogstashPort != 0 {\n\t\tresult.LogstashPort = b.LogstashPort\n\t}\n\n\tif b.ResourcePath != \"\" {\n\t\tresult.ResourcePath = b.ResourcePath\n\t}\n\n\tif b.Env != \"\" {\n\t\tresult.Env = b.Env\n\t}\n\n\tif b.ConnectionString != \"\" {\n\t\tresult.ConnectionString = b.ConnectionString\n\t}\n\n\tif b.RabbitMQURI != \"\" {\n\t\tresult.RabbitMQURI = b.RabbitMQURI\n\t}\n\n\tif b.Schema != \"\" {\n\t\tresult.Schema = b.Schema\n\t}\n\n\tif b.Parameters != nil && len(b.Parameters) > 0 {\n\t\tif result.Parameters == nil {\n\t\t\tresult.Parameters = make(map[string]string)\n\t\t}\n\t\tfor k, v := range b.Parameters {\n\t\t\tresult.Parameters[k] = v\n\t\t}\n\t}\n\n\tif result.Declarations == nil {\n\t\tresult.Declarations = essentials.NewDeclarationsConfig()\n\t}\n\n\tif b.Declarations != nil && b.Declarations.Exchanges != nil && len(b.Declarations.Exchanges) > 0 {\n\t\tfor k, v := range b.Declarations.Exchanges {\n\t\t\tresult.Declarations.Exchanges[k] = v\n\t\t}\n\t}\n\n\tif b.Declarations != nil && b.Declarations.Queues != nil && len(b.Declarations.Queues) > 0 {\n\t\tfor k, v := range b.Declarations.Queues {\n\t\t\tresult.Declarations.Queues[k] = v\n\t\t}\n\t}\n\n\treturn &result\n}", "func New() *Config {\n\treturn &Config{\n\t\tdevices: make([]Device, 0),\n\t}\n}", "func NewBackoffConfig(retries, base, cap uint) backoffConfig {\n\treturn backoffConfig{\n\t\tretries: retries,\n\t\tbase: base,\n\t\tcap: cap,\n\t}\n}", "func NewConfig() Config {\n\treturn Config{\n\t\tBindAddress: DefaultBindAddress,\n\t\tDatabase: DefaultDatabase,\n\t\tProtocol: DefaultProtocol,\n\t\tNamePosition: DefaultNamePosition,\n\t\tNameSeparator: DefaultNameSeparator,\n\t\tConsistencyLevel: DefaultConsistencyLevel,\n\t}\n}", "func NewConfig() Config {\n\tc := Config{}\n\tc.Forwards = map[string][]PortMappings{}\n\treturn c\n}", "func NewConfig() *config {\n\treturn &config{}\n}", "func newValidOverrideConfig() *dc.AutomateConfig {\n\tcfg := &dc.AutomateConfig{\n\t\tGlobal: &config.GlobalConfig{\n\t\t\tV1: &config.V1{\n\t\t\t\tFqdn: w.String(\"test-fqdn\"),\n\t\t\t},\n\t\t},\n\t\tLoadBalancer: &load_balancer.ConfigRequest{\n\t\t\tV1: &load_balancer.ConfigRequest_V1{\n\t\t\t\tSys: &load_balancer.ConfigRequest_V1_System{\n\t\t\t\t\tFrontendTls: []*config.FrontendTLSCredential{\n\t\t\t\t\t\t&config.FrontendTLSCredential{\n\t\t\t\t\t\t\tServerName: \"test\",\n\t\t\t\t\t\t\tCert: \"cert\",\n\t\t\t\t\t\t\tKey: \"key\",\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},\n\t}\n\n\treturn cfg\n}", "func NewConfig(r agentConfig.Reader) (*agentConfig.Config, error) {\n\tcfg, err := r.Read()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cfg.VerifyConfig {\n\t\terr = checkConfig(cfg)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn cfg, nil\n}", "func New() *Config {\n\treturn &Config{ Modules: []*Module{} }\n}", "func NewConfig(credentials *Credentials) *Config {\n\treturn &Config{\n\t\tCredentials: credentials,\n\t\tRegion: Region[\"bj\"],\n\t}\n}", "func NewConfig() *Config {\n\tcfg := &Config{}\n\n\tif len(os.Args) <= 1 {\n\t\tfmt.Printf(\"You have to specify a subcommand: %v\\n\", []string{ActionCreate, ActionGet, ActionDelete, ActionList, ActionShow, ActionCurator})\n\t\tos.Exit(2)\n\t}\n\tcfg.Action = os.Args[1]\n\n\tif !isValidAction(cfg.Action) {\n\t\tfmt.Printf(\"You have to specify a valid subcommand: %v\\n\", []string{ActionCreate, ActionGet, ActionDelete, ActionList, ActionShow, ActionCurator})\n\t\tos.Exit(2)\n\t}\n\n\tvar err error\n\tvar argParser *arg.Parser\n\n\tswitch cfg.Action {\n\tcase ActionCreate:\n\t\tcfg.Create = &CreateConfig{\n\t\t\tGeneralConfig: GeneralConfig{\n\t\t\t\tLogLevel: \"INFO\",\n\t\t\t},\n\t\t\tDatabaseConfig: DatabaseConfig{\n\t\t\t\tDatabase: DefaultDatabase,\n\t\t\t},\n\t\t\tAWSPartSize: 1, //1MB chunk\n\t\t\tSavePassword: false,\n\t\t}\n\n\t\tcfg.Create.argParser, _ = arg.NewParser(arg.Config{}, cfg.Create)\n\t\targParser = cfg.Create.argParser\n\t\terr = cfg.Create.argParser.Parse(os.Args[2:])\n\tcase ActionGet:\n\t\tcfg.Get = &GetConfig{\n\t\t\tGeneralConfig: GeneralConfig{\n\t\t\t\tLogLevel: \"INFO\",\n\t\t\t},\n\t\t\tDatabaseConfig: DatabaseConfig{\n\t\t\t\tDatabase: DefaultDatabase,\n\t\t\t},\n\t\t\tAWSPollInterval: 30 * time.Minute,\n\t\t\tAWSTier: \"Standard\",\n\t\t}\n\n\t\tcfg.Get.argParser, _ = arg.NewParser(arg.Config{}, cfg.Get)\n\t\targParser = cfg.Get.argParser\n\t\terr = cfg.Get.argParser.Parse(os.Args[2:])\n\tcase ActionList:\n\t\tcfg.List = &ListConfig{\n\t\t\tGeneralConfig: GeneralConfig{\n\t\t\t\tLogLevel: \"INFO\",\n\t\t\t},\n\t\t\tDatabaseConfig: DatabaseConfig{\n\t\t\t\tDatabase: DefaultDatabase,\n\t\t\t},\n\t\t}\n\n\t\tcfg.List.argParser, err = arg.NewParser(arg.Config{}, cfg.List)\n\t\targParser = cfg.List.argParser\n\t\terr = cfg.List.argParser.Parse(os.Args[2:])\n\t\tif err == nil {\n\t\t\tif cfg.List.Kb {\n\t\t\t\tcfg.List.Factor = 1000\n\t\t\t} else if cfg.List.Kib {\n\t\t\t\tcfg.List.Factor = 1024\n\t\t\t} else if cfg.List.Mb {\n\t\t\t\tcfg.List.Factor = 1000 * 1000\n\t\t\t} else if cfg.List.Mib {\n\t\t\t\tcfg.List.Factor = 1024 * 1024\n\t\t\t} else if cfg.List.Gb {\n\t\t\t\tcfg.List.Factor = 1000 * 1000 * 1000\n\t\t\t} else if cfg.List.Gib {\n\t\t\t\tcfg.List.Factor = 1024 * 1024 * 1024\n\t\t\t}\n\t\t}\n\tcase ActionShow:\n\t\tcfg.Show = &ShowConfig{\n\t\t\tGeneralConfig: GeneralConfig{\n\t\t\t\tLogLevel: \"INFO\",\n\t\t\t},\n\t\t\tDatabaseConfig: DatabaseConfig{\n\t\t\t\tDatabase: DefaultDatabase,\n\t\t\t},\n\t\t}\n\n\t\tcfg.Show.argParser, _ = arg.NewParser(arg.Config{}, cfg.Show)\n\t\targParser = cfg.Show.argParser\n\t\terr = cfg.Show.argParser.Parse(os.Args[2:])\n\tcase ActionDelete:\n\t\tcfg.Delete = &DeleteConfig{\n\t\t\tGeneralConfig: GeneralConfig{\n\t\t\t\tLogLevel: \"INFO\",\n\t\t\t},\n\t\t\tDatabaseConfig: DatabaseConfig{\n\t\t\t\tDatabase: DefaultDatabase,\n\t\t\t},\n\n\t\t\tDontAsk: false,\n\t\t}\n\n\t\tcfg.Delete.argParser, _ = arg.NewParser(arg.Config{}, cfg.Delete)\n\t\targParser = cfg.Delete.argParser\n\t\terr = cfg.Delete.argParser.Parse(os.Args[2:])\n\tcase ActionCurator:\n\t\tcfg.Curator = &CuratorConfig{\n\t\t\tGeneralConfig: GeneralConfig{\n\t\t\t\tLogLevel: \"INFO\",\n\t\t\t},\n\t\t\tDatabaseConfig: DatabaseConfig{\n\t\t\t\tDatabase: DefaultDatabase,\n\t\t\t},\n\n\t\t\tDontAsk: false,\n\t\t}\n\n\t\tcfg.Curator.argParser, _ = arg.NewParser(arg.Config{}, cfg.Curator)\n\t\targParser = cfg.Curator.argParser\n\t\terr = cfg.Curator.argParser.Parse(os.Args[2:])\n\t}\n\n\tif err != nil {\n\t\tif err == arg.ErrHelp {\n\t\t\targParser.WriteHelp(os.Stdout)\n\t\t\tos.Exit(0)\n\t\t}\n\n\t\tfmt.Printf(\"Error while parsing arguments: %s\", err.Error())\n\t\tos.Exit(3)\n\t}\n\n\treturn cfg\n}", "func NewConfig(stdout, stderr io.Writer) (*Config, error) {\n\tcfg := Config{\n\t\tStdout: stdout,\n\t\tStderr: stderr,\n\t}\n\tif err := envconfig.Process(\"plugin\", &cfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := envconfig.Process(\"\", &cfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif justNumbers.MatchString(cfg.Timeout) {\n\t\tcfg.Timeout = fmt.Sprintf(\"%ss\", cfg.Timeout)\n\t}\n\n\tif cfg.Debug && cfg.Stderr != nil {\n\t\tcfg.logDebug()\n\t}\n\n\tcfg.deprecationWarn()\n\n\treturn &cfg, nil\n}", "func NewConfig() *Config {\n\treturn &Config{\n\t\tNumberSuperNodes: defaultNumberSuperNodes,\n\t}\n}", "func (c Config) Merge(newcfg *Config) *Config {\n\tif newcfg == nil {\n\t\treturn &c\n\t}\n\n\tcfg := Config{}\n\n\tif newcfg.Credentials != nil {\n\t\tcfg.Credentials = newcfg.Credentials\n\t} else {\n\t\tcfg.Credentials = c.Credentials\n\t}\n\n\tif newcfg.Endpoint != \"\" {\n\t\tcfg.Endpoint = newcfg.Endpoint\n\t} else {\n\t\tcfg.Endpoint = c.Endpoint\n\t}\n\n\tif newcfg.Region != \"\" {\n\t\tcfg.Region = newcfg.Region\n\t} else {\n\t\tcfg.Region = c.Region\n\t}\n\n\tif newcfg.DisableSSL {\n\t\tcfg.DisableSSL = newcfg.DisableSSL\n\t} else {\n\t\tcfg.DisableSSL = c.DisableSSL\n\t}\n\n\tif newcfg.ManualSend {\n\t\tcfg.ManualSend = newcfg.ManualSend\n\t} else {\n\t\tcfg.ManualSend = c.ManualSend\n\t}\n\n\tif newcfg.HTTPClient != nil {\n\t\tcfg.HTTPClient = newcfg.HTTPClient\n\t} else {\n\t\tcfg.HTTPClient = c.HTTPClient\n\t}\n\n\tif newcfg.LogHTTPBody {\n\t\tcfg.LogHTTPBody = newcfg.LogHTTPBody\n\t} else {\n\t\tcfg.LogHTTPBody = c.LogHTTPBody\n\t}\n\n\tif newcfg.LogLevel != 0 {\n\t\tcfg.LogLevel = newcfg.LogLevel\n\t} else {\n\t\tcfg.LogLevel = c.LogLevel\n\t}\n\n\tif newcfg.Logger != nil {\n\t\tcfg.Logger = newcfg.Logger\n\t} else {\n\t\tcfg.Logger = c.Logger\n\t}\n\n\tif newcfg.MaxRetries != DefaultRetries {\n\t\tcfg.MaxRetries = newcfg.MaxRetries\n\t} else {\n\t\tcfg.MaxRetries = c.MaxRetries\n\t}\n\n\tif newcfg.DisableParamValidation {\n\t\tcfg.DisableParamValidation = newcfg.DisableParamValidation\n\t} else {\n\t\tcfg.DisableParamValidation = c.DisableParamValidation\n\t}\n\n\tif newcfg.DisableComputeChecksums {\n\t\tcfg.DisableComputeChecksums = newcfg.DisableComputeChecksums\n\t} else {\n\t\tcfg.DisableComputeChecksums = c.DisableComputeChecksums\n\t}\n\n\tif newcfg.S3ForcePathStyle {\n\t\tcfg.S3ForcePathStyle = newcfg.S3ForcePathStyle\n\t} else {\n\t\tcfg.S3ForcePathStyle = c.S3ForcePathStyle\n\t}\n\n\tif newcfg.DomainMode {\n\t\tcfg.DomainMode = newcfg.DomainMode\n\t} else {\n\t\tcfg.DomainMode = c.DomainMode\n\t}\n\tif newcfg.SignerVersion != \"\" {\n\t\tcfg.SignerVersion = newcfg.SignerVersion\n\t} else {\n\t\tcfg.SignerVersion = c.SignerVersion\n\t}\n\treturn &cfg\n}", "func NewConfig(asset AssetManager, logger *Logger) *Config {\n\tconfig := &Config{\n\t\tasset: asset,\n\t\terrors: []error{},\n\t}\n\n\tmasterKey, err := parseMasterKey(asset)\n\tif err != nil {\n\t\tconfig.errors = append(config.errors, err)\n\t}\n\n\tif masterKey != nil {\n\t\tconfig.masterKey = masterKey\n\n\t\tif errs := config.decrypt(asset); len(errs) > 0 {\n\t\t\tconfig.errors = append(config.errors, errs...)\n\t\t}\n\n\t\tif err := ParseEnv(config); err != nil {\n\t\t\tconfig.errors = append(config.errors, err)\n\t\t}\n\t}\n\n\treturn config\n}", "func NewConfig() Config {\n\treturn Config{\n\t\tData: tsdb.NewConfig(),\n\t\tRetentionService: retention.NewConfig(),\n\t\tPrecreatorConfig: precreator.NewConfig(),\n\t}\n}", "func ArbitrateConfigs(c *Configure) {\n\t//check the ClusterName, ClusterName is used to Identify the clusters in the Local NetWork\n\tif c.HttpPort == c.MsgPort {\n\t\tpanic(\"port conflict\")\n\t}\n\tif c.HttpPort > math.MaxInt16 || c.HttpPort < 1024 {\n\t\tpanic(fmt.Errorf(\"illegal http port %d\", c.HttpPort))\n\t}\n\n\tif c.MsgPort > math.MaxInt16 || c.MsgPort < 1024 {\n\t\tpanic(fmt.Errorf(\"illegal msg port %d\", c.MsgPort))\n\t}\n\n\tif c.Retry > 10 {\n\t\tc.Retry = 10\n\t}\n\tif c.Retry < 1 {\n\t\tc.Retry = 1\n\t}\n\tif c.SyncType < 0 || c.SyncType > 2 {\n\t\tc.SyncType = 0\n\t}\n\tif c.Threshold < 1000 {\n\t\tc.Threshold = 1000\n\t}\n\tif c.Threshold > 1000000 {\n\t\tc.Threshold = 1000000\n\t}\n}", "func (s *cpuSource) NewConfig() source.Config { return newDefaultConfig() }", "func NewConfig() *Config {\n\treturn &Config{\n\t\tHandlerChainWaitGroup: new(waitgroup.SafeWaitGroup),\n\t\tHealthzChecks: []healthz.HealthzChecker{healthz.PingHealthz},\n\t\tBuildHandlerChainFunc: DefaultBuildHandlerChain,\n\t\tVersion: version.Get(),\n\t\tMaxRequestsInFlight: 4000,\n\t\tRequestTimeout: time.Duration(340) * time.Second,\n\n\t\tEnableProfiling: false,\n\t\tEnableContentionProfiling: false,\n\t\tEnableMetrics: true,\n\t\tSummaryOverheadMs: 1,\n\t}\n}", "func New(cfg Config) Backoff {\n\n\t// if no interval is provided (nil), set to default value\n\tvar interval int\n\tif cfg.Interval == nil {\n\t\tinterval = DefaultInterval\n\t} else {\n\t\tinterval = *cfg.Interval\n\t}\n\n\tswitch cfg.Type {\n\tcase TypeConstant:\n\t\treturn NewConstant(interval)\n\tcase TypeLinear:\n\t\treturn NewLinear(interval)\n\tcase TypeExponential:\n\t\treturn NewExponential(interval, cfg.Multiplier)\n\tdefault:\n\t\treturn NewConstant(interval)\n\t}\n}", "func ConfigNew() *Config {\n\tc := Config{\n\t\tHosts: map[string]*ConfigHost{},\n\t}\n\treturn &c\n}", "func NewConfig(iface string, protocal string, port string, metricsHost string, metricsPath string) (*Config, error) {\n\tconfig := &Config{\n\t\tiface: iface,\n\t\tport: port,\n\t\tprotocal: protocal,\n\t\tmetricsHost: metricsHost,\n\t\tmetricsPath: metricsPath,\n\t}\n\tif err := config.validate(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn config, nil\n}", "func NewConfig() *Config {\n\treturn &Config{\n\t\tBindAddr: \"127.0.0.1:8080\",\n\t\tNetwork: \"udp4\",\n\t}\n}", "func NewConfig() *Config {\n\treturn &Config{\n\t\tComma: ',',\n\t\tComment: '#',\n\t\tTrimLeadingSpace: true,\n\t\tHasHeader: true,\n\t}\n}", "func NewConfig() *Config {\n\tcfg := &Config{}\n\tcfg.FlagSet = flag.NewFlagSet(\"importer\", flag.ContinueOnError)\n\tfs := cfg.FlagSet\n\n\tfs.StringVar(&cfg.configFile, \"config\", \"\", \"Config file\")\n\n\tfs.StringVar(&cfg.TableSQL, \"t\", \"\", \"create table sql\")\n\tfs.StringVar(&cfg.IndexSQL, \"i\", \"\", \"create index sql\")\n\n\tfs.IntVar(&cfg.WorkerCount, \"c\", 1, \"parallel worker count\")\n\tfs.IntVar(&cfg.JobCount, \"n\", 1, \"total job count\")\n\tfs.IntVar(&cfg.Batch, \"b\", 1, \"insert batch commit count\")\n\n\tfs.StringVar(&cfg.DBCfg.Host, \"h\", \"127.0.0.1\", \"set the database host ip\")\n\tfs.StringVar(&cfg.DBCfg.User, \"u\", \"root\", \"set the database user\")\n\tfs.StringVar(&cfg.DBCfg.Password, \"p\", \"\", \"set the database password\")\n\tfs.StringVar(&cfg.DBCfg.Name, \"D\", \"test\", \"set the database name\")\n\tfs.IntVar(&cfg.DBCfg.Port, \"P\", 3306, \"set the database port\")\n\n\tfs.StringVar(&cfg.LogLevel, \"L\", \"info\", \"log level: debug, info, warn, error, fatal\")\n\tfs.BoolVar(&cfg.printVersion, \"V\", false, \"prints version and exit\")\n\n\treturn cfg\n}", "func NewConfig() *Config {\n\treturn &Config{\n\t\tEnable: true,\n\t\tAddress: \"0.0.0.0:30003\",\n\t}\n}", "func NewCombinedFromConfig(other map[string]interface{}) (Provider, error) {\n\tstatus, err := NewOpenWBStatusProviderFromConfig(other)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\to := &combinedProvider{status: status}\n\treturn o, nil\n}", "func (b BackendType) NewConfig() interface{} {\n\tswitch b {\n\tcase EtcdV2:\n\t\treturn &etcd.EtcdConfig{}\n\tdefault:\n\t\tlog.Errorf(\"Unknown backend type: %v\", b)\n\t\treturn nil\n\t}\n}", "func NewConfig(r bool, d *int, debug bool) *CondConfig {\n\treturn &CondConfig{\n\t\trootOnly: r,\n\t\tdepth: d,\n\t\tdebug: debug,\n\t}\n}", "func NewConfig() Config {\n\treturn Config{\n\t\tConnections: 5,\n\t}\n}", "func NewConfig(ff []ConfigFunc) Config {\n\tconf := Config{Delimiter: ','}\n\tfor _, f := range ff {\n\t\tf(&conf)\n\t}\n\treturn conf\n}" ]
[ "0.58682334", "0.5791714", "0.574422", "0.57309926", "0.56678116", "0.54747754", "0.5453819", "0.5438932", "0.5422589", "0.54104185", "0.5382655", "0.5369698", "0.5325242", "0.530093", "0.5297655", "0.52528226", "0.52506673", "0.5243341", "0.5229364", "0.52185094", "0.52181023", "0.5203029", "0.51907736", "0.51901215", "0.51724875", "0.5124269", "0.5119175", "0.5116204", "0.5105651", "0.51001644", "0.50945485", "0.5082221", "0.5079138", "0.504894", "0.5039198", "0.50386244", "0.5035445", "0.50300914", "0.50295866", "0.5028592", "0.5018301", "0.50148034", "0.50108916", "0.5010698", "0.5004892", "0.5001346", "0.49957466", "0.49930343", "0.49922034", "0.49907932", "0.498635", "0.49851513", "0.49851513", "0.49846238", "0.49846238", "0.49846238", "0.49846238", "0.49663684", "0.496467", "0.49509123", "0.49500123", "0.49429485", "0.49417177", "0.4940279", "0.4940279", "0.49319303", "0.49303025", "0.49255255", "0.49146545", "0.49129277", "0.49107873", "0.49015665", "0.48772058", "0.4875161", "0.4872508", "0.48704204", "0.48640946", "0.485505", "0.48535195", "0.4851636", "0.48419842", "0.48348475", "0.48331863", "0.48329708", "0.48319432", "0.48315284", "0.48314172", "0.48285443", "0.48267218", "0.48216662", "0.48145995", "0.4808199", "0.48079467", "0.48026124", "0.48017755", "0.4796756", "0.47950017", "0.4794916", "0.47925976", "0.47922406" ]
0.71805686
0
NewDefaultConfig returns a new Config with generically reasonable default values.
func NewDefaultConfig() Config { return Config{ StepSize: 0.001, Beta1: 0.9, Beta2: 0.999, Epsilon: 1.0e-8, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewDefault() *Config {\n\tvv := defaultConfig\n\treturn &vv\n}", "func NewDefault() *Config {\n\tvv := defaultConfig\n\treturn &vv\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tDefaultNamespace: \"default\",\n\t\tFileName: \"stdin\",\n\t\tTargetKubernetesVersion: \"master\",\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tChdir: \".\",\n\t\tCollectorTimeout: collectorTimeout,\n\t\tWaitTime: 10,\n\t}\n}", "func NewDefaultConfig() *Config {\n\tconf := &Config{\n\t\tUnicastConfig: NewDefaultUnicastConfig(),\n\t\tExtensionConfig: NewDefaultExtensionConfig(),\n\t}\n\treturn conf\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tArtifactsDir: DefaultKataArtifactsDir,\n\t}\n}", "func NewDefault() Configuration {\n\tcfg := Configuration{\n\t\tEnableSyslog: false,\n\t\tEnableSSL: false,\n\t\tHttpRequestTimeout: 5,\n\t\tConnectTimeout: 5,\n\t\tClientTimeout: 50,\n\t\tClientFinTimeout: 50,\n\t\tServerTimeout: 50,\n\t\tTunnelTimeout: 3600,\n\t\tHttpKeepAliveTimeout: 60,\n\t}\n\n\treturn cfg\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tIgnoreNamespaces: []string{\"kube-system\", \"kube-public\"},\n\t}\n}", "func NewDefaultConfig() *Config {\n\thostname, _ := os.Hostname()\n\tc := &Config{\n\t\tHostname: hostname,\n\t\tEncoder: NewAutomaticEventEncoder(),\n\t\tClient: &http.Client{},\n\t}\n\treturn c\n}", "func NewDefaultConfig() Config {\n\treturn Config{\n\t\tServer: serverConfig{\n\t\t\tUDP: defaultUDPPort,\n\t\t\tTCP: defaultTCPPort,\n\t\t\tHTTP: defaultHTTPPort,\n\t\t},\n\t\tStore: storeConfig{TTL: defaultDuration},\n\t}\n}", "func NewDefault() (*Config, error) {\n\tc := &Config{}\n\n\terr := yaml.Unmarshal([]byte(DefaultConfigFileContent), c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 2*time.Minute),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, 2*time.Second),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),\n\t\t},\n\t}\n}", "func NewDefaultConfig() Config {\n\treturn Config{\n\t\tName: \"avo\",\n\t\tPkg: pkg(),\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tTTL: env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL),\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 5*time.Minute),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, 20*time.Second),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),\n\t\t},\n\t}\n}", "func NewDefaultConfig() *Config {\n\tvar config = Config{\n\t\tCliPath: defaultCliPath,\n\t\tRefreshInterval: defaultRefreshInterval,\n\t\tInfluxDB: influxdb.NewDefaultConfig(),\n\t\tLdap: ldap.NewDefaultConfig(),\n\t}\n\treturn &config\n}", "func NewDefaultConfig(\n\tmagic, pver uint32,\n\tservices uint64,\n\tdefaultPort uint16,\n\tseeds, listenAddrs []string,\n\tonNewPeer func(IPeer) bool,\n\tonDonePeer func(IPeer),\n\tmakeEmptyMessage func(string) (p2p.Message, error),\n\tbestHeight func() uint64) *Config {\n\treturn &Config{\n\t\tMagicNumber: magic,\n\t\tProtocolVersion: pver,\n\t\tServices: services,\n\t\tDNSSeeds: seeds,\n\t\tListenAddrs: listenAddrs,\n\t\tExternalIPs: nil,\n\t\tUpnp: false,\n\t\tDefaultPort: defaultPort,\n\t\tDisableListen: false,\n\t\tDisableRelayTx: false,\n\t\tMaxPeers: defaultMaxPeers,\n\t\tDisableBanning: false,\n\t\tBanThreshold: defaultBanThreshold,\n\t\tBanDuration: defaultBanDuration,\n\t\tWhitelists: nil,\n\t\tTargetOutbound: defaultTargetOutbound,\n\t\tOnNewPeer: onNewPeer,\n\t\tOnDonePeer: onDonePeer,\n\t\tMakeEmptyMessage: makeEmptyMessage,\n\t\tBestHeight: bestHeight,\n\t\tPingNonce: bestHeight,\n\t\tPongNonce: bestHeight,\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tSequenceInterval: env.GetOrDefaultSecond(EnvSequenceInterval, dns01.DefaultPropagationTimeout),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),\n\t\t},\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tIgnoreNamespaces: []string{\"kube-system\", \"kube-admission\"},\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tIgnoreNamespaces: []string{\"kube-system\", \"kube-admission\"},\n\t}\n}", "func NewDefaultConfig() Config {\n\n\tvar config = Config{\n\t\tURL: defaultURL,\n\t\tBearerTokenFile: defaultBearerTokenFile,\n\t\tTLSConfig: &TLSConfig{\n\t\t\tInsecureSkipVerify: true,\n\t\t},\n\t}\n\treturn config\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tProxyConnectTimeout: \"60s\",\n\t\tProxyReadTimeout: \"60s\",\n\t\tClientMaxBodySize: \"1m\",\n\t\tMainServerNamesHashMaxSize: \"512\",\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tIgnoreNamespaces: []string{\"kube-system\", \"kube-admission\"},\n\t\tWhitelist: []string{string(core.ServiceTypeNodePort), string(core.ServiceTypeClusterIP)},\n\t}\n}", "func NewDefaultConfig() *GenConfig {\n\treturn &GenConfig{\n\t\tPackageName: defaultPathPackageName,\n\t\tGoImports: GoImports{\n\t\t\tYgotImportPath: genutil.GoDefaultYgotImportPath,\n\t\t\tYtypesImportPath: genutil.GoDefaultYtypesImportPath,\n\t\t\tGoyangImportPath: genutil.GoDefaultGoyangImportPath,\n\t\t\tProtoLibImportPath: defaultProtoLibImportPath,\n\t\t\tGNMIProtoPath: genutil.GoDefaultGNMIImportPath,\n\t\t\tGenUtilImportPath: defaultGenUtilImportPath,\n\t\t},\n\t\tFakeRootName: defaultFakeRootName,\n\t\tGeneratingBinary: genutil.CallerName(),\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tTTL: env.GetOrDefaultInt(EnvTTL, 300),\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),\n\t\t},\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tTTL: env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL),\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, ovh.DefaultTimeout),\n\t\t},\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tTTL: env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL),\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, ovh.DefaultTimeout),\n\t\t},\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tTTL: env.GetOrDefaultInt(EnvTTL, 600),\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tHTTPTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 10*time.Second),\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tTTL: env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL),\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 60*time.Second),\n\t\t},\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tTTL: env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL),\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 120*time.Second),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, 2*time.Second),\n\t\tServerName: env.GetOrDefaultString(EnvServerName, \"localhost\"),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),\n\t\t},\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tTTL: int64(env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL)),\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tHTTPTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 60*time.Second),\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tPublic: false,\n\t\tMemory: false, // Save to disk.\n\t\tConfigDir: \"\", // --> Action: set as '$HOME/.skybbs'\n\t\tRPC: true,\n\t\tRPCPort: defaultRPCPort,\n\t\tCXOPort: defaultCXOPort,\n\t\tCXORPC: false,\n\t\tCXORPCPort: defaultCXORPCPort,\n\t\tEnforcedMessengerAddresses: []string{},\n\t\tEnforcedSubscriptions: []string{},\n\t\tWebPort: defaultWebPort,\n\t\tWebGUI: true,\n\t\tWebGUIDir: defaultStaticSubDir, // --> Action: set as '$HOME/.skybbs/static/dist'\n\t\tBrowser: false,\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tTTL: env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL),\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tHTTPTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, session.DefaultTimeout),\n\t}\n}", "func DefaultConfig() Config {\n\tnewConfig := Config{\n\t\t// Dependencies.\n\t\tFactoryCollection: factory.MustNewCollection(),\n\t\tLog: log.New(log.DefaultConfig()),\n\t\tStorageCollection: storage.MustNewCollection(),\n\n\t\t// Settings.\n\t\tMaxSignals: 5,\n\t}\n\n\treturn newConfig\n}", "func NewDefaultConfig() *Config {\n\tcreds := NewHomeConfig()\n\toverrideFromEnv(creds)\n\treturn creds\n}", "func NewDefaultConfig(host string) Config {\n\treturn Config{GraylogPort: 12201, MaxChunkSize: 8154, GraylogHostname: host}\n}", "func DefaultConfig() Config {\n\tnewConfig := Config{\n\t\t// Dependencies.\n\t\tFactoryCollection: factory.MustNewCollection(),\n\t\tLog: log.New(log.DefaultConfig()),\n\t\tStorageCollection: storage.MustNewCollection(),\n\t}\n\n\treturn newConfig\n}", "func DefaultConfig() *Config {\n\tc := &Config{}\n\tif _, err := toml.Decode(defaultConfig, c); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := c.Validate(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn c\n}", "func NewDefaultConfig() *Config {\n\treturn (&Config{}).WithOptions(\n\t\tSnapshotSubdirectory(\".snapshots\"),\n\t\tEnvVariableName(\"UPDATE_SNAPSHOTS\"),\n\t\tFailOnUpdate(true),\n\t\tCreateNewAutomatically(true),\n\t)\n}", "func NewDefaultConfig() *Config {\n\tcf := &Config{\n\t\tDBPath: \"./\",\n\t\tTableName: \"session\",\n\t\tSetMaxOpenConn: 500,\n\t\tSetMaxIdleConn: 50,\n\t}\n\n\treturn cf\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tLager: lager.NewLogLager(nil),\n\t\tPool: new(gob.Pool),\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tBaseConfig: defaultBaseConfig(),\n\t\tP2P: p2pConfig.DefaultConfig(),\n\t\tAPI: apiConfig.DefaultConfig(),\n\t\tCONSENSUS: consensusConfig.DefaultConfig(),\n\t\tHARE: hareConfig.DefaultConfig(),\n\t\tTIME: timeConfig.DefaultConfig(),\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tK8sClient: nil,\n\t\tLogger: nil,\n\t}\n}", "func Default() *Configuration {\n\treturn &Configuration{\n\t\tSplitMax: defaultSplitMax,\n\t\tPeekMax: defaultPeekMax,\n\t\tStringMax: defaultStringMax,\n\t\tDisableTransforms: []string{},\n\t\tDisableInterpolators: []string{},\n\t}\n}", "func defaultConfig() *config {\n\treturn &config{\n\t\tOperations: operations{\n\t\t\tResize: resize{\n\t\t\t\tRaw: *resizeDefaults(),\n\t\t\t},\n\t\t\tFlip: flip{\n\t\t\t\tRaw: *flipDefaults(),\n\t\t\t},\n\t\t\tBlur: blur{\n\t\t\t\tRaw: *blurDefaults(),\n\t\t\t},\n\t\t\tRotate: rotate{\n\t\t\t\tRaw: *rotateDefaults(),\n\t\t\t},\n\t\t\tCrop: crop{\n\t\t\t\tRaw: *cropDefaults(),\n\t\t\t},\n\t\t\tLabel: label{\n\t\t\t\tRaw: *labelDefaults(),\n\t\t\t},\n\t\t},\n\t\tExport: export{\n\t\t\tRaw: *exportDefaults(),\n\t\t},\n\t}\n}", "func NewDefaultConfig(v *viper.Viper) (*Config, error) {\n\tif !v.IsSet(\"postgres\") {\n\t\treturn nil, ErrEmptyConfig\n\t}\n\n\t// v.SetDefault(\"postgres.hostname\", \"localhost\")\n\tv.SetDefault(\"postgres.options.sslmode\", \"disable\")\n\n\t// re-fetch by full key\n\toptions := v.GetStringMapString(\"postgres.options\")\n\tif len(options) > 0 {\n\t\tfor opt := range options {\n\t\t\toptions[opt] = v.GetString(\"postgres.options.\" + opt)\n\t\t}\n\t}\n\n\treturn &Config{\n\t\tHostname: v.GetString(\"postgres.hostname\"),\n\t\tUsername: v.GetString(\"postgres.username\"),\n\t\tPassword: v.GetString(\"postgres.password\"),\n\t\tDatabase: v.GetString(\"postgres.database\"),\n\t\tDebug: v.GetBool(\"postgres.debug\"),\n\t\tPoolSize: v.GetInt(\"postgres.pool_size\"),\n\t\tOptions: options,\n\t}, nil\n}", "func Default() *Config {\n\treturn &defaultConfig\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tK8sClient: nil,\n\t\tLogger: nil,\n\t\tVaultClient: nil,\n\t}\n}", "func defaultConfig() interface{} {\n\treturn &config{\n\t\tPools: make(pools),\n\t\tConfDirPath: \"/etc/cmk\",\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tFileSystem: nil,\n\t\tK8sClient: nil,\n\t\tLogger: nil,\n\n\t\t// Settings.\n\t\tFlag: nil,\n\t\tViper: nil,\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tAddr: DefaultAddr,\n\t\tDirPath: DefaultDirPath,\n\t\tBlockSize: DefaultBlockSize,\n\t\tRwMethod: storage.FileIO,\n\t\tIdxMode: KeyValueMemMode,\n\t\tMaxKeySize: DefaultMaxKeySize,\n\t\tMaxValueSize: DefaultMaxValueSize,\n\t\tSync: false,\n\t\tReclaimThreshold: DefaultReclaimThreshold,\n\t\tSingleReclaimThreshold: DefaultSingleReclaimThreshold,\n\t}\n}", "func defaultConfig() *config {\n\treturn &config{}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tBaseConfig: DefaultBaseConfig(),\n\t\tEth: DefaultEthConfig(),\n\t\tHuron: DefaultHuronConfig(),\n\t\tRaft: DefaultRaftConfig(),\n\t}\n}", "func TestNewConfigDefault(t *testing.T) {\n\tconfig, err := NewConfig(\"\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, 512, config.Clustering.RaftCacheSize)\n\trequire.Equal(t, \"liftbridge-default\", config.Clustering.Namespace)\n\trequire.Equal(t, 1024, config.BatchMaxMessages)\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tRedisURI: \"redis://127.0.0.1:6379\",\n\t\tGCP: &GCPConfig{\n\t\t\tProjectID: \"\",\n\t\t\tServiceAccountFile: \"\",\n\t\t},\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tConfigurers: nil,\n\t\tFileSystem: afero.NewMemMapFs(),\n\t\tLogger: nil,\n\n\t\t// Settings.\n\t\tHelmBinaryPath: \"\",\n\t\tOrganisation: \"\",\n\t\tPassword: \"\",\n\t\tRegistry: \"\",\n\t\tUsername: \"\",\n\t}\n}", "func MakeDefaultConfig(clusterGRPCAddress string, oauthServerAddress string, insecure bool) Config {\n\treturn Config{\n\t\tBase: conf.Base{\n\t\t\tLog: conf.Log{\n\t\t\t\tFormat: \"console\",\n\t\t\t\tLevel: log.InfoLevel,\n\t\t\t},\n\t\t},\n\t\tInputFormat: \"json\",\n\t\tOutputFormat: \"json\",\n\t\tOAuthServerAddress: oauthServerAddress,\n\t\tIdentityServerGRPCAddress: clusterGRPCAddress,\n\t\tGatewayServerEnabled: true,\n\t\tGatewayServerGRPCAddress: clusterGRPCAddress,\n\t\tNetworkServerEnabled: true,\n\t\tNetworkServerGRPCAddress: clusterGRPCAddress,\n\t\tApplicationServerEnabled: true,\n\t\tApplicationServerGRPCAddress: clusterGRPCAddress,\n\t\tJoinServerEnabled: true,\n\t\tJoinServerGRPCAddress: clusterGRPCAddress,\n\t\tDeviceTemplateConverterGRPCAddress: clusterGRPCAddress,\n\t\tDeviceClaimingServerGRPCAddress: clusterGRPCAddress,\n\t\tQRCodeGeneratorGRPCAddress: clusterGRPCAddress,\n\t\tPacketBrokerAgentGRPCAddress: clusterGRPCAddress,\n\t\tInsecure: insecure,\n\t\tRetry: defaultRetryConfig,\n\t\tTelemetry: defaultTelemetryConfig,\n\t}\n}", "func Default() *Config {\n\treturn &Config{\n\t\tEnv: &Env{Region: region, Zone: zone, DeployEnv: deployEnv, Host: host},\n\t\tDiscovery: &naming.Config{Region: region, Zone: zone, Env: deployEnv, Host: host},\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tN: 10,\n\t\tRoundDuration: 10 * time.Second,\n\t\tWakeupDelta: 10 * time.Second,\n\t\tExpectedLeaders: 5,\n\t\tLimitIterations: 5,\n\t\tLimitConcurrent: 5,\n\t\tHdist: 20,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tMaxRetries: defaultMaxRetries,\n\t\tInitialBackoff: defaultInitialBackoff,\n\t\tMaxBackoff: defaultMaxBackoff,\n\t\tBackoffFactor: defaultBackoffFactor,\n\t\tMaxMessages: defaultMaxMessages,\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tHeartbeat: defaultHeartbeat,\n\t\tLocale: defaultLocale,\n\t\tDefaultLoggerLevel: zerolog.ErrorLevel,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tShowOurLogs: true,\n\t\tDeliverLogs: defaultDeliver,\n\t\tBackoffCap: defaultBackoffCap,\n\t\tBackoffGranularity: defaultBackoffGranularity,\n\t\tTickInterval: defaultTickInterval,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tLogLevel: \"debug\",\n\t\tLogFormat: \"text\",\n\n\t\tDatabaseDriver: \"boltdb\",\n\t\tDatabasePath: \"db/eremetic.db\",\n\n\t\tName: \"Eremetic\",\n\t\tUser: \"root\",\n\t\tCheckpoint: true,\n\t\tFailoverTimeout: 2592000.0,\n\t\tQueueSize: 100,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tAppName: pkg.Name(),\n\t\tLogPath: \"/tmp/log\",\n\t\tFlowRules: make([]*flow.Rule, 0),\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tName: \"endpoint\",\n\t\tMaxPacketSize: 16 * 1024,\n\t\tFragmentAbove: 1024,\n\t\tMaxFragments: 16,\n\t\tFragmentSize: 1024,\n\t\tAckBufferSize: 256,\n\t\tSentPacketsBufferSize: 256,\n\t\tReceivedPacketsBufferSize: 256,\n\t\tFragmentReassemblyBufferSize: 64,\n\t\tRttSmoothingFactor: .0025,\n\t\tPacketLossSmoothingFactor: .1,\n\t\tBandwidthSmoothingFactor: .1,\n\t\tPacketHeaderSize: 28, // // note: UDP over IPv4 = 20 + 8 bytes, UDP over IPv6 = 40 + 8 bytes\n\t}\n}", "func Default() *Config {\n\tconf := &Config{\n\t\tProtocol: \"tcp\",\n\t\tAddr: \"0.0.0.0:25565\",\n\t\tHosts: []HostConfig{\n\t\t\t{\n\t\t\t\tName: \"Server-1\",\n\t\t\t\tAddr: \"localhost:25580\",\n\t\t\t},\n\t\t},\n\t\tLogConfig: LogConfig{\n\t\t\tLogConnections: true,\n\t\t\tLogDisconnect: false,\n\t\t},\n\t\tHealthCheckTime: 5,\n\t\tUDPTimeout: 3000,\n\t\tSaveConfigOnClose: false,\n\t\tInterfaces: []string{},\n\t}\n\tconf.fillFlags()\n\treturn conf\n}", "func defaultConfig() Config {\n\treturn Config{\n\t\tConfFileOptions: defaultFileOptions(),\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tLogLevel: \"INFO\",\n\t\tBindAddr: \"127.0.0.1\",\n\t\tPorts: &Ports{\n\t\t\tHTTP: 4646,\n\t\t\tRPC: 4647,\n\t\t\tSerf: 4648,\n\t\t},\n\t\tAddresses: &Addresses{},\n\t\tServer: &ServerConfig{\n\t\t\tEnabled: false,\n\t\t},\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tPort: 5000,\n\t\tHapHome: \"/HOME/hapadm\",\n\t\tClusterID: \"default-name\",\n\t\tSudo: true,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tinjectString: defaultInject,\n\t\tconfigString: defaultConfig,\n\t\tappProfile: newAppProfile(),\n\t\tactivateES: false,\n\t}\n}", "func DefaultConfig(hostname string) *Config {\n\treturn &Config{\n\t\thostname,\n\t\t8, // 8 vnodes\n\t\tsha1.New, // SHA1\n\t\ttime.Duration(5 * time.Second),\n\t\ttime.Duration(15 * time.Second),\n\t\t8, // 8 successors\n\t\tnil, // No delegate\n\t\t160, // 160bit hash function\n\t\t\"\",\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tLogger: nil,\n\n\t\t// Settings.\n\t\tFlag: nil,\n\t\tViper: nil,\n\n\t\tDescription: \"\",\n\t\tGitCommit: \"\",\n\t\tName: \"\",\n\t\tSource: \"\",\n\t}\n}", "func newDefaultContainerConfig() ContainerConfig {\n\treturn ContainerConfig{\n\t\tCPU: newMinMaxAllocation(),\n\t\tMemory: newMinMaxAllocation(),\n\t\tBlockRead: newMinMaxAllocation(),\n\t\tBlockWrite: newMinMaxAllocation(),\n\t\tNetworkRx: newMinMaxAllocation(),\n\t\tNetworkTx: newMinMaxAllocation(),\n\t}\n}", "func DefaultConfig() *Config {\n\tdefaultExp := model.DefaultExperimentConfig(nil)\n\tvar c CheckpointStorageConfig\n\tif err := c.FromModel(&defaultExp.CheckpointStorage); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &Config{\n\t\tConfigFile: \"\",\n\t\tLog: *logger.DefaultConfig(),\n\t\tDB: *db.DefaultConfig(),\n\t\tTaskContainerDefaults: model.TaskContainerDefaultsConfig{\n\t\t\tShmSizeBytes: 4294967296,\n\t\t\tNetworkMode: \"bridge\",\n\t\t},\n\t\tTensorBoardTimeout: 5 * 60,\n\t\tScheduler: *scheduler.DefaultConfig(),\n\t\tSecurity: SecurityConfig{\n\t\t\tDefaultTask: model.AgentUserGroup{\n\t\t\t\tUID: 0,\n\t\t\t\tGID: 0,\n\t\t\t\tUser: \"root\",\n\t\t\t\tGroup: \"root\",\n\t\t\t},\n\t\t},\n\t\t// If left unspecified, the port is later filled in with 8080 (no TLS) or 8443 (TLS).\n\t\tPort: 0,\n\t\tCheckpointStorage: c,\n\t\tHarnessPath: \"/opt/determined\",\n\t\tRoot: \"/usr/share/determined/master\",\n\t\tTelemetry: TelemetryConfig{\n\t\t\tEnabled: true,\n\t\t\tSegmentMasterKey: DefaultSegmentMasterKey,\n\t\t\tSegmentWebUIKey: DefaultSegmentWebUIKey,\n\t\t},\n\t\tEnableCors: false,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tBaseConfig: BaseConfig{\n\t\t\tMinGasPrices: defaultMinGasPrices,\n\t\t\tQueryGasLimit: 0,\n\t\t\tInterBlockCache: true,\n\t\t\tPruning: pruningtypes.PruningOptionDefault,\n\t\t\tPruningKeepRecent: \"0\",\n\t\t\tPruningInterval: \"0\",\n\t\t\tMinRetainBlocks: 0,\n\t\t\tIndexEvents: make([]string, 0),\n\t\t\tIAVLCacheSize: 781250,\n\t\t\tIAVLDisableFastNode: false,\n\t\t\tAppDBBackend: \"\",\n\t\t},\n\t\tTelemetry: telemetry.Config{\n\t\t\tEnabled: false,\n\t\t\tGlobalLabels: [][]string{},\n\t\t},\n\t\tAPI: APIConfig{\n\t\t\tEnable: false,\n\t\t\tSwagger: false,\n\t\t\tAddress: DefaultAPIAddress,\n\t\t\tMaxOpenConnections: 1000,\n\t\t\tRPCReadTimeout: 10,\n\t\t\tRPCMaxBodyBytes: 1000000,\n\t\t},\n\t\tGRPC: GRPCConfig{\n\t\t\tEnable: true,\n\t\t\tAddress: DefaultGRPCAddress,\n\t\t\tMaxRecvMsgSize: DefaultGRPCMaxRecvMsgSize,\n\t\t\tMaxSendMsgSize: DefaultGRPCMaxSendMsgSize,\n\t\t},\n\t\tGRPCWeb: GRPCWebConfig{\n\t\t\tEnable: true,\n\t\t},\n\t\tStateSync: StateSyncConfig{\n\t\t\tSnapshotInterval: 0,\n\t\t\tSnapshotKeepRecent: 2,\n\t\t},\n\t\tStreaming: StreamingConfig{\n\t\t\tABCI: ABCIListenerConfig{\n\t\t\t\tKeys: []string{},\n\t\t\t\tStopNodeOnErr: true,\n\t\t\t},\n\t\t},\n\t\tMempool: MempoolConfig{\n\t\t\tMaxTxs: 5_000,\n\t\t},\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tAddress: \"127.0.0.1\",\n\t\tPort: 5700,\n\t\tSyslogFacility: \"SYSLOG\",\n\t\tLogLevel: \"INFO\",\n\t\tConsulDatacenter: \"dc1\",\n\t\tConsulPort: 8500,\n\t\tParameters: make(map[string]string),\n\t\tDeclarations: essentials.NewDeclarationsConfig(),\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tHTTPClient: nil,\n\t\tLogger: nil,\n\n\t\t// Settings.\n\t\tFlag: nil,\n\t\tViper: nil,\n\t}\n}", "func DefaultConfig() *Config {\n\tconfig := new(Config)\n\tconfig.URL = MktmpioURL\n\treturn config\n}", "func Default() *Config {\n\treturn &Config{\n\t\tEnv: &Env{Region: region, Zone: zone, DeployEnv: deployEnv, Host: host, Weight: weight},\n\t\tDiscovery: &naming.Config{Region: region, Zone: zone, Env: deployEnv, Host: host},\n\t\tHTTPServer: &HTTPServer{\n\t\t\tNetwork: \"tcp\",\n\t\t\tAddr: \"3111\",\n\t\t\tReadTimeout: xtime.Duration(time.Second),\n\t\t\tWriteTimeout: xtime.Duration(time.Second),\n\t\t},\n\t\tRPCClient: &RPCClient{Dial: xtime.Duration(time.Second), Timeout: xtime.Duration(time.Second)},\n\t\tRPCServer: &RPCServer{\n\t\t\tNetwork: \"tcp\",\n\t\t\tAddr: \"3119\",\n\t\t\tTimeout: xtime.Duration(time.Second),\n\t\t\tIdleTimeout: xtime.Duration(time.Second * 60),\n\t\t\tMaxLifeTime: xtime.Duration(time.Hour * 2),\n\t\t\tForceCloseWait: xtime.Duration(time.Second * 20),\n\t\t\tKeepAliveInterval: xtime.Duration(time.Second * 60),\n\t\t\tKeepAliveTimeout: xtime.Duration(time.Second * 20),\n\t\t},\n\t\tBackoff: &Backoff{MaxDelay: 300, BaseDelay: 3, Factor: 1.8, Jitter: 1.3},\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tValueModifiers: nil,\n\n\t\t// Settings.\n\t\tIgnoreFields: nil,\n\t\tSelectFields: nil,\n\t}\n}", "func NewDefaultConfig(authServer string) (*BotConfig, error) {\n\t// Note: we need authServer for CheckAndSetDefaults to succeed.\n\tcfg := BotConfig{\n\t\tAuthServer: authServer,\n\t}\n\tif err := cfg.CheckAndSetDefaults(); err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\treturn &cfg, nil\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tResource: nil,\n\n\t\t// Settings.\n\t\tName: \"\",\n\t}\n}", "func DefaultConfig() Config {\n\treturn MemoryConstrainedDefaults()\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tBackOff: nil,\n\t\tFramework: nil,\n\t\tInformer: nil,\n\t\tLogger: nil,\n\t\tTPR: nil,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tLogLevel: \"debug\",\n\t\tLogFormat: \"text\",\n\n\t\tDatabase: DatabaseConfig{\n\t\t\tHost: \"127.0.0.1\",\n\t\t\tPort: 3306,\n\t\t\tName: \"fusion\",\n\t\t\tUser: \"fusion\",\n\t\t\tPassword: \"password\",\n\t\t},\n\t}\n}", "func defaultConfig() interface{} {\n\treturn &conf{\n\t\tPools: make(map[string]poolConfig),\n\t\tLabelNode: false,\n\t\tTaintNode: false,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tZapConfig: zap.NewProductionConfig(),\n\t}\n}", "func createDefaultConfig() component.Config {\n\treturn &Config{\n\t\tProtocols: Protocols{\n\t\t\tGRPC: &configgrpc.GRPCServerSettings{\n\t\t\t\tNetAddr: confignet.NetAddr{\n\t\t\t\t\tEndpoint: defaultGRPCEndpoint,\n\t\t\t\t\tTransport: \"tcp\",\n\t\t\t\t},\n\t\t\t\t// We almost write 0 bytes, so no need to tune WriteBufferSize.\n\t\t\t\tReadBufferSize: 512 * 1024,\n\t\t\t},\n\t\t\tHTTP: &HTTPConfig{\n\t\t\t\tHTTPServerSettings: &confighttp.HTTPServerSettings{\n\t\t\t\t\tEndpoint: defaultHTTPEndpoint,\n\t\t\t\t},\n\t\t\t\tTracesURLPath: defaultTracesURLPath,\n\t\t\t\tMetricsURLPath: defaultMetricsURLPath,\n\t\t\t\tLogsURLPath: defaultLogsURLPath,\n\t\t\t},\n\t\t},\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tContractQueryGasLimit: DefaultContractQueryGasLimit,\n\t\tContractDebugMode: DefaultContractDebugMode,\n\t\tWriteVMMemoryCacheSize: DefaultWriteVMMemoryCacheSize,\n\t\tReadVMMemoryCacheSize: DefaultReadVMMemoryCacheSize,\n\t\tNumReadVMs: DefaultNumReadVM,\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tBlockSize: 64,\n\t\tNumReplicas: 2,\n\t\tNumTapestry: 2,\n\t\tZkAddr: \"localhost:2181\",\n\t}\n}", "func configDefault(config ...Config) Config {\n\t// Return default config if nothing provided\n\tif len(config) < 1 {\n\t\treturn ConfigDefault\n\t}\n\n\t// Override default config\n\tcfg := config[0]\n\n\t// Set default values\n\tif cfg.Host == \"\" {\n\t\tcfg.Host = ConfigDefault.Host\n\t}\n\tif cfg.Port <= 0 {\n\t\tcfg.Port = ConfigDefault.Port\n\t}\n\tif cfg.Database == \"\" {\n\t\tcfg.Database = ConfigDefault.Database\n\t}\n\tif cfg.Table == \"\" {\n\t\tcfg.Table = ConfigDefault.Table\n\t}\n\tif int(cfg.GCInterval.Seconds()) <= 0 {\n\t\tcfg.GCInterval = ConfigDefault.GCInterval\n\t}\n\treturn cfg\n}", "func newDefaultConfig() *Config {\n\treturn &Config{\n\t\tcpuidConfig{\n\t\t\tAttributeBlacklist: []string{\n\t\t\t\t\"BMI1\",\n\t\t\t\t\"BMI2\",\n\t\t\t\t\"CLMUL\",\n\t\t\t\t\"CMOV\",\n\t\t\t\t\"CX16\",\n\t\t\t\t\"ERMS\",\n\t\t\t\t\"F16C\",\n\t\t\t\t\"HTT\",\n\t\t\t\t\"LZCNT\",\n\t\t\t\t\"MMX\",\n\t\t\t\t\"MMXEXT\",\n\t\t\t\t\"NX\",\n\t\t\t\t\"POPCNT\",\n\t\t\t\t\"RDRAND\",\n\t\t\t\t\"RDSEED\",\n\t\t\t\t\"RDTSCP\",\n\t\t\t\t\"SGX\",\n\t\t\t\t\"SGXLC\",\n\t\t\t\t\"SSE\",\n\t\t\t\t\"SSE2\",\n\t\t\t\t\"SSE3\",\n\t\t\t\t\"SSE4\",\n\t\t\t\t\"SSE42\",\n\t\t\t\t\"SSSE3\",\n\t\t\t\t\"TDX_GUEST\",\n\t\t\t},\n\t\t\tAttributeWhitelist: []string{},\n\t\t},\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tAddress: \"127.0.0.1:8080\",\n\t\tScheme: \"http\",\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: time.Duration(5 * time.Second),\n\t\t},\n\t}\n}", "func createDefaultConfig() component.Config {\n\treturn &Config{\n\t\tScraperControllerSettings: scraperhelper.ScraperControllerSettings{\n\t\t\tCollectionInterval: defaultCollectionInterval,\n\t\t\tTimeout: defaultTimeout,\n\t\t},\n\t\tEndpoint: defaultEndpoint,\n\t\tVersion: defaultVersion,\n\t\tCommunity: defaultCommunity,\n\t\tSecurityLevel: defaultSecurityLevel,\n\t\tAuthType: defaultAuthType,\n\t\tPrivacyType: defaultPrivacyType,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tPort: defaultPort,\n\t\tAutoConnect: false,\n\t\tAllowReconnect: false,\n\t\tReconnectSeconds: 5,\n\t}\n}", "func (f *factory) DefaultConfig() interface{} {\n\treturn f.newDefaultCfg()\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tPUCT: 1.0,\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tDir: DefaultConfDir,\n\t\tTimeout: xtime.Duration(\"1s\"),\n\t\tEnable: false,\n\t\tMysql: ConfDataSourceMysql{\n\t\t\tEnable: false,\n\t\t\tDsn: \"127.0.0.1:6379\",\n\t\t},\n\t\tEtcd: ConfDataSourceEtcd{\n\t\t\tEnable: false,\n\t\t\tSecure: false,\n\t\t\tEndPoints: []string{\"127.0.0.1:2379\"},\n\t\t},\n\t}\n}", "func configDefault(config ...Config) Config {\n\t// Return default config if nothing provided\n\tif len(config) < 1 {\n\t\treturn ConfigDefault\n\t}\n\n\t// Override default config\n\tcfg := config[0]\n\n\t// Set default values\n\n\tif cfg.Next == nil {\n\t\tcfg.Next = ConfigDefault.Next\n\t}\n\n\tif cfg.Lifetime.Nanoseconds() == 0 {\n\t\tcfg.Lifetime = ConfigDefault.Lifetime\n\t}\n\n\tif cfg.KeyHeader == \"\" {\n\t\tcfg.KeyHeader = ConfigDefault.KeyHeader\n\t}\n\tif cfg.KeyHeaderValidate == nil {\n\t\tcfg.KeyHeaderValidate = ConfigDefault.KeyHeaderValidate\n\t}\n\n\tif cfg.KeepResponseHeaders != nil && len(cfg.KeepResponseHeaders) == 0 {\n\t\tcfg.KeepResponseHeaders = ConfigDefault.KeepResponseHeaders\n\t}\n\n\tif cfg.Lock == nil {\n\t\tcfg.Lock = NewMemoryLock()\n\t}\n\n\tif cfg.Storage == nil {\n\t\tcfg.Storage = memory.New(memory.Config{\n\t\t\tGCInterval: cfg.Lifetime / 2, // Half the lifetime interval\n\t\t})\n\t}\n\n\treturn cfg\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tObservability: DefaultObservability(),\n\t\tWorkerHasher: DefaultHasher,\n\t\tWorkerCount: 1,\n\t\tMaxItemRetries: 10,\n\t\tWorkerQueueSize: 2000,\n\t\tLeaderElectionEnabled: true,\n\t\tDelayResolution: time.Millisecond * 250,\n\t\tDelayQueueSize: 1000,\n\t\tMaxReconcileTime: time.Second * 10,\n\t}\n}" ]
[ "0.8374629", "0.8374629", "0.8041251", "0.8026334", "0.79116195", "0.7896762", "0.78775716", "0.7861471", "0.78218305", "0.7800303", "0.77709764", "0.7767419", "0.7752707", "0.7750308", "0.7741053", "0.77397543", "0.7711731", "0.76993686", "0.76833934", "0.76833934", "0.7667832", "0.7646423", "0.76027244", "0.7586319", "0.7582227", "0.75819045", "0.75819045", "0.75807124", "0.7552221", "0.75509715", "0.75125927", "0.75053316", "0.7495439", "0.74741113", "0.74730855", "0.7463811", "0.7448521", "0.743832", "0.7392658", "0.7390346", "0.73862916", "0.7386088", "0.7351447", "0.7335186", "0.7327948", "0.73265433", "0.7325325", "0.7315692", "0.7303854", "0.7299346", "0.7283361", "0.7277849", "0.72777927", "0.7271237", "0.72576034", "0.72352993", "0.72182846", "0.7213897", "0.7208859", "0.7205424", "0.7190793", "0.71747106", "0.71660477", "0.71635073", "0.7152141", "0.71452", "0.7141329", "0.7132223", "0.7126786", "0.71214783", "0.7120801", "0.71179956", "0.71132416", "0.71088207", "0.71015227", "0.7096959", "0.7083141", "0.7073471", "0.70723313", "0.70711994", "0.7070943", "0.7069096", "0.7068008", "0.70660144", "0.7064901", "0.7062072", "0.70557827", "0.70541734", "0.7034865", "0.70324725", "0.70306987", "0.70288837", "0.7028265", "0.70193076", "0.7017933", "0.70169795", "0.6989363", "0.6971939", "0.69690293", "0.6964132" ]
0.8045895
2
New returns a new RAdam optimizer, initialized according to the given configuration.
func New[T float.DType](c Config) *RAdam[T] { adam := &RAdam[T]{ Config: c, RoMax: 2.0/(1.0-c.Beta2) - 1.0, TimeStep: 1.0, } return adam }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewAdam(lr, beta, beta2, epsilon float64) *Adam {\n\treturn &Adam{\n\t\tlr: fparam(lr, 0.001),\n\t\tbeta: fparam(beta, 0.9),\n\t\tbeta2: fparam(beta2, 0.999),\n\t\tepsilon: fparam(epsilon, 1e-8),\n\t}\n}", "func NewAdam(\n\tparams []anyvec.Vector, stepSize, beta1, beta2, epsilon float64) *Adam {\n\tadam := new(Adam)\n\tadam.v = make([]anyvec.Vector, len(params))\n\tadam.m = make([]anyvec.Vector, len(params))\n\tfor i := range adam.v {\n\t\tadam.v[i] = anyvec64.MakeVector(params[i].Len())\n\t\tadam.m[i] = anyvec64.MakeVector(params[i].Len())\n\t}\n\tadam.stepSize = stepSize\n\tadam.t = 0\n\tadam.beta1 = beta1\n\tadam.beta2 = beta2\n\tadam.epsilon = epsilon\n\treturn adam\n}", "func New(conf *aqm.Config) (s *AQM) {\n\treturn &AQM{\n\t\tlimiter: limit.New(conf),\n\t}\n}", "func (opt *SGD) New() Optimizer {\n\treturn NewSGD(opt.Lr, opt.Momentum, opt.WeightDecay)\n}", "func New(config Config) *Model {\n\treturn &Model{\n\t\tConfig: config,\n\t\tQuery: linear.New(config.InputSize, config.QuerySize),\n\t\tR: nn.NewParam(mat.NewEmptyDense(config.QuerySize, config.BucketSize)),\n\t\tValue: linear.New(config.InputSize, config.ValueSize),\n\t}\n}", "func (a *allocator) New(jobSessionName string, jobTrackerInitParams interface{}) (jobtracker.JobTracker, error) {\n\t// a job session name has no meaning in DRMAA v1.\n\treturn NewDRMAATracker()\n}", "func New(grammarString string) (*grammar.Grammar, tree.Reducer, error) {\n\tparseTree, err := runner.Run(grammarString)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tg, r := evalGrammar(parseTree.(*tree.PN))\n\treturn g, r, nil\n}", "func New(conf *Config) Rclone {\n\treturn Rclone{config: conf}\n}", "func NewRebalance(state State, gateway Gateway, schema config.Schema, options ...RebalanceOption) *Rebalance {\n\topts := newRebalanceOptions()\n\topts.state = state\n\topts.gateway = gateway\n\topts.schema = schema\n\tfor _, option := range options {\n\t\toption(opts)\n\t}\n\n\treturn &Rebalance{\n\t\tstate: opts.state,\n\t\tgateway: opts.gateway,\n\t\tschema: opts.schema,\n\t\tconfig: opts.config,\n\t\tlogger: opts.logger,\n\t\tclock: opts.clock,\n\t}\n}", "func New(config *Config) functions.Runner {\n\treturn &impl{*config}\n}", "func NewOptimizer(method OptimizationMethod, opts ...Option) *GradientDescent {\n\toptimizer := &GradientDescent{\n\t\tmethod: method,\n\t\tobserved: make(map[Optimizable]bool),\n\t}\n\tfor _, opt := range opts {\n\t\topt(optimizer)\n\t}\n\treturn optimizer\n}", "func New(config Config) (*Operator, error) {\n\t// Dependencies.\n\tif config.BackOff == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.BackOff must not be empty\")\n\t}\n\tif config.Framework == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Framework must not be empty\")\n\t}\n\tif config.Informer == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Informer must not be empty\")\n\t}\n\tif config.Logger == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Logger must not be empty\")\n\t}\n\tif config.TPR == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.TPR must not be empty\")\n\t}\n\n\tnewOperator := &Operator{\n\t\t// Dependencies.\n\t\tbackOff: config.BackOff,\n\t\tframework: config.Framework,\n\t\tinformer: config.Informer,\n\t\tlogger: config.Logger,\n\t\ttpr: config.TPR,\n\n\t\t// Internals\n\t\tbootOnce: sync.Once{},\n\t\tmutex: sync.Mutex{},\n\t}\n\n\treturn newOperator, nil\n}", "func New(context *context.AutoscalingContext, processors *processors.AutoscalingProcessors, deleteOptions simulator.NodeDeleteOptions) *Planner {\n\tresourceLimitsFinder := resource.NewLimitsFinder(processors.CustomResourcesProcessor)\n\tminUpdateInterval := context.AutoscalingOptions.NodeGroupDefaults.ScaleDownUnneededTime\n\tif minUpdateInterval == 0*time.Nanosecond {\n\t\tminUpdateInterval = 1 * time.Nanosecond\n\t}\n\treturn &Planner{\n\t\tcontext: context,\n\t\tunremovableNodes: unremovable.NewNodes(),\n\t\tunneededNodes: unneeded.NewNodes(processors.NodeGroupConfigProcessor, resourceLimitsFinder),\n\t\trs: simulator.NewRemovalSimulator(context.ListerRegistry, context.ClusterSnapshot, context.PredicateChecker, simulator.NewUsageTracker(), deleteOptions, true),\n\t\tactuationInjector: scheduling.NewHintingSimulator(context.PredicateChecker),\n\t\teligibilityChecker: eligibility.NewChecker(processors.NodeGroupConfigProcessor),\n\t\tnodeUtilizationMap: make(map[string]utilization.Info),\n\t\tresourceLimitsFinder: resourceLimitsFinder,\n\t\tcc: newControllerReplicasCalculator(context.ListerRegistry),\n\t\tscaleDownSetProcessor: processors.ScaleDownSetProcessor,\n\t\tminUpdateInterval: minUpdateInterval,\n\t}\n}", "func New(ctx context.Context, store storage.Store, stm *semantic.Statement, chanSize, bulkSize int, w io.Writer) (Executor, error) {\n\tswitch stm.Type() {\n\tcase semantic.Query:\n\t\treturn newQueryPlan(ctx, store, stm, chanSize, w)\n\tcase semantic.Insert:\n\t\treturn &insertPlan{\n\t\t\tstm: stm,\n\t\t\tstore: store,\n\t\t\ttracer: w,\n\t\t}, nil\n\tcase semantic.Delete:\n\t\treturn &deletePlan{\n\t\t\tstm: stm,\n\t\t\tstore: store,\n\t\t\ttracer: w,\n\t\t}, nil\n\tcase semantic.Create:\n\t\treturn &createPlan{\n\t\t\tstm: stm,\n\t\t\tstore: store,\n\t\t\ttracer: w,\n\t\t}, nil\n\tcase semantic.Drop:\n\t\treturn &dropPlan{\n\t\t\tstm: stm,\n\t\t\tstore: store,\n\t\t\ttracer: w,\n\t\t}, nil\n\tcase semantic.Construct:\n\t\tqp, _ := newQueryPlan(ctx, store, stm, chanSize, w)\n\t\treturn &constructPlan{\n\t\t\tstm: stm,\n\t\t\tstore: store,\n\t\t\ttracer: w,\n\t\t\tbulkSize: bulkSize,\n\t\t\tqueryPlan: qp,\n\t\t\tconstruct: true,\n\t\t}, nil\n\tcase semantic.Deconstruct:\n\t\tqp, _ := newQueryPlan(ctx, store, stm, chanSize, w)\n\t\treturn &constructPlan{\n\t\t\tstm: stm,\n\t\t\tstore: store,\n\t\t\ttracer: w,\n\t\t\tbulkSize: bulkSize,\n\t\t\tqueryPlan: qp,\n\t\t\tconstruct: false,\n\t\t}, nil\n\tcase semantic.Show:\n\t\treturn &showPlan{\n\t\t\tstm: stm,\n\t\t\tstore: store,\n\t\t\ttracer: w,\n\t\t}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"planner.New: unknown statement type in statement %v\", stm)\n\t}\n}", "func New(config Config, m marathon.Marathoner) (*Scorer, error) {\n\n\tif config.ResetInterval <= config.UpdateInterval {\n\t\treturn nil, errors.New(\"UpdateInterval should be lower than ResetInterval\")\n\t}\n\n\tif config.ResetInterval <= config.EvaluateInterval {\n\t\treturn nil, errors.New(\"ResetInterval should be lower than EvaluateInterval\")\n\t}\n\n\treturn &Scorer{\n\t\tScaleDownScore: config.ScaleDownScore,\n\t\tResetInterval: config.ResetInterval,\n\t\tUpdateInterval: config.UpdateInterval,\n\t\tEvaluateInterval: config.EvaluateInterval,\n\t\tScaleLimit: config.ScaleLimit,\n\t\tDryRun: config.DryRun,\n\t\tservice: m,\n\t\tscores: make(map[marathon.AppID]*Score),\n\t}, nil\n}", "func New(analysis reach.Analysis) *Explainer {\n\treturn &Explainer{\n\t\tanalysis: analysis,\n\t}\n}", "func New(c client.Reader, minBuilds, maxBuilds int) *Analyzer {\n\tif c == nil {\n\t\tc = client.NewReader(nil)\n\t}\n\n\treturn &Analyzer{\n\t\tReader: c,\n\t\tMaxRecentBuilds: maxBuilds,\n\t\tMinRecentBuilds: minBuilds,\n\t\tHungBuilderThresh: 3 * time.Hour,\n\t\tOfflineBuilderThresh: 90 * time.Minute,\n\t\tIdleBuilderCountThresh: 50,\n\t\tStaleMasterThreshold: 10 * time.Minute,\n\t\tStepAnalyzers: []StepAnalyzer{\n\t\t\t&TestFailureAnalyzer{Reader: c},\n\t\t\t&CompileFailureAnalyzer{Reader: c},\n\t\t},\n\t\tMasterCfgs: map[string]messages.MasterConfig{},\n\n\t\trevisionSummaries: map[string]messages.RevisionSummary{},\n\t\tNow: func() time.Time {\n\t\t\treturn time.Now()\n\t\t},\n\t}\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 New(config Config) *Minerva {\n\tif config.CachesInMem <= 0 {\n\t\t//log.Warn(\"One minerva cache must always be in memory\", \"requested\", config.CachesInMem)\n\t\tconfig.CachesInMem = 1\n\t}\n\tif config.CacheDir != \"\" && config.CachesOnDisk > 0 {\n\t\t//log.Info(\"Disk storage enabled for minerva caches\", \"dir\", config.CacheDir, \"count\", config.CachesOnDisk)\n\t}\n\tif config.DatasetDir != \"\" && config.DatasetsOnDisk > 0 {\n\t\t//log.Info(\"Disk storage enabled for minerva DAGs\", \"dir\", config.DatasetDir, \"count\", config.DatasetsOnDisk)\n\t}\n\n\tminerva := &Minerva{\n\t\tconfig: config,\n\t\t//caches: newlru(\"cache\", config.CachesInMem, newCache),\n\t\tdatasets: newlru(\"dataset\", config.DatasetsInMem, newDataset),\n\t\tupdate: make(chan struct{}),\n\t\thashrate: metrics.NewMeter(),\n\t}\n\n\t//MinervaLocal.CheckDataSetState(1)\n\tminerva.getDataset(1)\n\n\treturn minerva\n}", "func New(fn RunFunction, rates []Rate) (*rrInstance, error) {\n\tif len(rates) == 0 {\n\t\treturn nil, errors.New(\"empty rates\")\n\t}\n\n\trateRunner := &rrInstance{\n\t\tterminateRunner: make(chan bool, 1),\n\t\trestartRates: make(chan bool, 1),\n\t\trunFunction: fn,\n\t\trates: rates,\n\t\tnextRateIndex: 0,\n\t}\n\n\treturn rateRunner, nil\n}", "func NewAdder(ctx context.Context, p pin.Pinner, bs bstore.GCLocker, ds ipld.DAGService) (*Adder, error) {\n\tbufferedDS := ipld.NewBufferedDAG(ctx, ds)\n\n\treturn &Adder{\n\t\tctx: ctx,\n\t\tpinning: p,\n\t\tgcLocker: bs,\n\t\tdagService: ds,\n\t\tbufferedDS: bufferedDS,\n\t\tProgress: false,\n\t\tPin: true,\n\t\tTrickle: false,\n\t\tMetaForDirectory: false,\n\t\tMetaDagToAdd: false,\n\t\tMetadataDag: nil,\n\t\tdb: nil,\n\t\tChunker: \"\",\n\t\tTokenMetadata: \"\",\n\t\tPinDuration: 0,\n\t}, nil\n}", "func NewFromConfig(config *Config) (*Raptor, error) {\n\tr := &Raptor{}\n\terr := r.SetConfig(config)\n\treturn r, err\n}", "func New(rs *RuleSet) *Opts {\n\topts := Opts{\n\t\trs: rs,\n\t\toptions: make(map[string]bool),\n\t}\n\topts.updateOptions()\n\treturn &opts\n}", "func New(db PlanData) Planner {\n\treturn Planner{\n\t\tdata: db,\n\t}\n}", "func newRebalanceOptions() *rebalanceOptions {\n\treturn &rebalanceOptions{\n\t\tconfig: clusterConfigShim{},\n\t\tlogger: log.NewNopLogger(),\n\t\tclock: clock.New(),\n\t}\n}", "func New() *Builder {\n\treturn &Builder{\n\t\tpatterns: make(map[string]*parser.Node),\n\t}\n}", "func New(ctx context.Context, cfg Config) (types.Leases, error) {\n\tif err := cfg.sanitize(); err != nil {\n\t\treturn nil, err\n\t}\n\t_, err := cfg.Pool.Exec(ctx, fmt.Sprintf(schema, cfg.Target))\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\n\tl := &leases{cfg: cfg}\n\tl.sql.acquire = fmt.Sprintf(acquireTemplate, cfg.Target)\n\tl.sql.release = fmt.Sprintf(releaseTemplate, cfg.Target)\n\tl.sql.renew = fmt.Sprintf(renewTemplate, cfg.Target)\n\n\treturn l, nil\n}", "func NewParser(r resolver.Resolver) parser.IngressAnnotation {\n\treturn weight{r}\n}", "func New(configFile string) (Bench, error) {\n\tb := Bench{}\n\tvar err error\n\tif b.config, err = config(configFile); err != nil {\n\t\treturn b, err\n\t}\n\treturn b, nil\n}", "func (a Avg) New(_ *functions.ArgumentMap, _ ...interface{}) (out uda.AggInterface, err error) {\n\treturn &Avg{\n\t\tAvg: 0,\n\t\tCount: 0,\n\t}, nil\n}", "func New(config Config) *Model {\n\tdimOut := config.Dim / 2\n\n\tm := &Model{\n\t\tConfig: config,\n\t\tNorm: layernorm.New(dimOut),\n\t\tProj: conv1x1.New(conv1x1.Config{\n\t\t\tInputChannels: config.DimSeq,\n\t\t\tOutputChannels: config.DimSeq,\n\t\t}),\n\t\tAct: nil,\n\t}\n\n\tif config.Activation != ag.OpIdentity {\n\t\tm.Act = activation.New(config.Activation)\n\t}\n\n\treturn m\n}", "func NewOptimizer(ctx context.Context, c ChangeStreamer) (o *StreamOptimizer) {\n\to = new(StreamOptimizer)\n\to.changeQ = o.optimize(ctx, c.Changes())\n\treturn\n}", "func New(cfg Config) Module { return Module{Factory: cfg} }", "func New(\n\tmid module.MID,\n\trespParsers []module.ParseResponse,\n\tscoreCalculator module.CalculateScore) (analyzer module.Analyzer, yierr *constant.YiError) {\n\tmoduleBase, yierr := stub.NewModuleInternal(mid, scoreCalculator)\n\tif yierr != nil {\n\t\treturn\n\t}\n\tif respParsers == nil {\n\t\tyierr = constant.NewYiErrorf(constant.ERR_NEW_ANALYZER_FAIL,\n\t\t\t\"Response parsers is nil\")\n\t\treturn\n\t}\n\tif len(respParsers) == 0 {\n\t\tyierr = constant.NewYiErrorf(constant.ERR_NEW_ANALYZER_FAIL,\n\t\t\t\"Empty response parser list\")\n\t\treturn\n\t}\n\tvar innerParsers []module.ParseResponse\n\tfor i, parser := range respParsers {\n\t\tif parser == nil {\n\t\t\tyierr = constant.NewYiErrorf(constant.ERR_NEW_ANALYZER_FAIL,\n\t\t\t\t\"Nil response parser[%d]\", i)\n\t\t\treturn\n\t\t}\n\t\tinnerParsers = append(innerParsers, parser)\n\t}\n\treturn &myAnalyzer{\n\t\tModuleInternal: moduleBase,\n\t\trespParsers: innerParsers,\n\t}, nil\n}", "func New(confDate string) (module.Module, error) {\n\tvar cfg function.Config\n\terr := module.Load(&cfg, confDate)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tdefaults(&cfg)\n\tlogger.Init(cfg.Logger, \"module\", cfg.Name)\n\tman, err := function.NewManager(cfg)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tm := &mo{\n\t\tcfg: cfg,\n\t\tman: man,\n\t\trrs: []*ruler{},\n\t\tlog: logger.WithFields(),\n\t}\n\tfor _, r := range cfg.Rules {\n\t\tf, err := man.Get(r.Compute.Function)\n\t\tif err != nil {\n\t\t\tm.Close()\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\trr, err := create(r, cfg.Hub, f)\n\t\tif err != nil {\n\t\t\tm.Close()\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tm.rrs = append(m.rrs, rr)\n\t}\n\treturn m, nil\n}", "func New(r io.Reader) *Parser {\n\treturn &Parser{s: NewScanner(r)}\n}", "func NewConfig(stepSize, beta1, beta2, epsilon float64) Config {\n\tif !(beta1 >= 0.0 && beta1 < 1.0) {\n\t\tpanic(\"adam: `beta1` must be in the range [0.0, 1.0)\")\n\t}\n\tif !(beta2 >= 0.0 && beta2 < 1.0) {\n\t\tpanic(\"adam: `beta2` must be in the range [0.0, 1.0)\")\n\t}\n\treturn Config{\n\t\tStepSize: stepSize,\n\t\tBeta1: beta1,\n\t\tBeta2: beta2,\n\t\tEpsilon: epsilon,\n\t}\n}", "func New(rc *Config) *Reloader {\n\treturn &Reloader{\n\t\tconfigFile: rc.ConfigFile,\n\t\treloadURL: rc.ReloadURL,\n\t\twatchInterval: rc.WatchInterval,\n\t}\n}", "func New(r io.Reader) *Parser {\n\tp := &Parser{\n\t\ts: bufio.NewScanner(r),\n\t\thasMoreCommand: true,\n\t}\n\treturn p\n}", "func New(rate float64, iterations int, units int, activator string) *Mind {\n\tm := &Mind{\n\t\tLearningRate: rate,\n\t\tIterations: iterations,\n\t\tHiddenUnits: units,\n\t}\n\n\tswitch activator {\n\tcase \"sigmoid\":\n\t\tm.Activate = Activator(Sigmoid)\n\t\tm.ActivatePrime = Activator(SigmoidPrime)\n\tcase \"htan\":\n\t\tm.Activate = Activator(Htan)\n\t\tm.ActivatePrime = Activator(Htanprime)\n\tdefault:\n\t\tpanic(\"unknown activator \" + activator)\n\t}\n\n\treturn m\n}", "func NewASLParser(input antlr.TokenStream) *ASLParser {\n\tthis := new(ASLParser)\n\tdeserializer := antlr.NewATNDeserializer(nil)\n\tdeserializedATN := deserializer.DeserializeFromUInt16(parserATN)\n\tdecisionToDFA := make([]*antlr.DFA, len(deserializedATN.DecisionToState))\n\tfor index, ds := range deserializedATN.DecisionToState {\n\t\tdecisionToDFA[index] = antlr.NewDFA(ds, index)\n\t}\n\tthis.BaseParser = antlr.NewBaseParser(input)\n\n\tthis.Interpreter = antlr.NewParserATNSimulator(this, deserializedATN, decisionToDFA, antlr.NewPredictionContextCache())\n\tthis.RuleNames = ruleNames\n\tthis.LiteralNames = literalNames\n\tthis.SymbolicNames = symbolicNames\n\tthis.GrammarFileName = \"ASL.g4\"\n\n\treturn this\n}", "func (f StartInstructionFactory) New(name string) *AMLInstruction {\n\treturn &AMLInstruction{\n\t\tName: strings.Replace(name, \"?\", \"cond_\", -1),\n\t\tPredecessors: []*AMLInstruction{},\n\t\tNodeOptions: map[string]string{\n\t\t\t\"shape\": \"circle\",\n\t\t\t\"label\": \"\",\n\t\t\t\"style\": \"filled\",\n\t\t\t\"fillcolor\": \"#111111\",\n\t\t\t\"height\": \"0.3\",\n\t\t},\n\t\tEdgeOptions: make(map[string]string),\n\t}\n}", "func New(conf config.Config) Parser {\n\tmethods := map[string]bool{\n\t\thttp.MethodGet: true,\n\t\thttp.MethodHead: true,\n\t\thttp.MethodPost: true,\n\t\thttp.MethodPut: true,\n\t\thttp.MethodPatch: true,\n\t\thttp.MethodDelete: true,\n\t\thttp.MethodConnect: true,\n\t\thttp.MethodOptions: true,\n\t\thttp.MethodTrace: true,\n\t}\n\n\treturn Parser{\n\t\tconf: conf,\n\t\tmethods: methods,\n\t}\n}", "func New(policy *Policy) *RateLimiter {\n\trl := &RateLimiter{\n\t\tpolicy: policy,\n\t\tstartTime: nowFunc(),\n\t}\n\treturn rl\n}", "func (KNN *KNNRegressor) New(name string, labels []float64, numbers []float64, x int, y int) {\n\n\tKNN.Data = *mat.MakeDenseMatrix(numbers, x, y)\n\tKNN.Name = name\n\tKNN.Labels = labels\n}", "func fromParsedConfig(conf Config) (multilayer.MultiLayerPerceptron, error) {\n\treturn multilayer.New(\n\t\tconf.HiddenLayers,\n\t\tconf.Output,\n\t\tconf.ActFn,\n\t\tconf.OutActFn,\n\t\tconf.BatchSize,\n\t\tconf.Epochs,\n\t\tconf.LearningRate,\n\t\tconf.Reader)\n}", "func (filter *FilterConfig) New() (*Filter, error) {\n\tpatterns := make([]*regexp.Regexp, 0)\n\tfor i, pattern := range filter.Patterns {\n\t\tregexpPattern, err := regexp.Compile(pattern)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid filter: couldn't compile regexp rule number %d\", i)\n\t\t}\n\t\tpatterns = append(patterns, regexpPattern)\n\t}\n\treturn &Filter{\n\t\tRecursive: filter.Recursive,\n\t\tPatterns: patterns,\n\t}, nil\n}", "func New() *RabinKarp64 {\n\tp, err := RandomPolynomial(1)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn NewFromPol(p)\n}", "func New(o *Options) (Matcher, error) {\n\t// creates data clients\n\tdataClients, err := createDataClients(o.RoutesFile)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trouting := createRouting(dataClients, o)\n\n\treturn &matcher{\n\t\trouting,\n\t}, nil\n}", "func new() *DAG {\n\treturn &DAG{Nodes: map[string]*Node{}}\n}", "func NewReloader(config *Config) (*Reloader, error) {\n\treturn &Reloader{\n\t\tConfig: config,\n\t}, nil\n}", "func NewReaper() *Reaper {\n\treturn &Reaper{}\n}", "func New(configName string) (*Apnian, error) {\n\tapnian := ApnianConfigurer{configName, gobrick.GetGOPATH()}\n\treturn apnian.getApnian()\n}", "func New(conf config.Config) (*Rekognition, error) {\n\tsess, err := conf.Session()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsvc := NewFromSession(sess)\n\tsvc.prefix = conf.DefaultPrefix\n\treturn svc, nil\n}", "func New(cfg *Config) *Loader {\n\tvar r *regexp.Regexp\n\tif cfg.Regexp != \"\" {\n\t\tr = regexp.MustCompile(cfg.Regexp)\n\t}\n\n\tif cfg.Name == \"\" {\n\t\tcfg.Name = defaultName\n\t}\n\n\treturn &Loader{\n\t\tcfg,\n\t\tr,\n\t}\n}", "func NewAnalyzer(envoyConfig *configdump.Wrapper) (*Analyzer, error) {\n\tbootstrap, err := envoyConfig.GetBootstrapConfigDump()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get bootstrap config dump: %s\", err)\n\t}\n\tsplits := strings.Split(bootstrap.Bootstrap.Node.Id, \"~\")\n\tif len(splits) != 4 {\n\t\treturn nil, fmt.Errorf(\"invalid node ID(%q), expecting 4 '~' but found: %d\",\n\t\t\tbootstrap.Bootstrap.Node.Id, len(splits))\n\t}\n\n\tlisteners, err := envoyConfig.GetDynamicListenerDump(true)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get dynamic listener dump: %s\", err)\n\t}\n\n\tclusters, err := envoyConfig.GetDynamicClusterDump(true)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get dynamic cluster dump: %s\", err)\n\t}\n\n\treturn &Analyzer{nodeType: splits[0], nodeIP: splits[1], listenerDump: listeners, clusterDump: clusters}, nil\n}", "func New(ringWeight int) LoadBalancer {\n\t// TODO: Implement this!\n\tnewLB := new(loadBalancer)\n\tnewLB.sortedNames = make([]MMENode, 0)\n\tnewLB.weight = ringWeight\n\tnewLB.hashRing = NewRing()\n\tif 7 == 2 {\n\t\tfmt.Println(ringWeight)\n\t}\n\treturn newLB\n}", "func New(r io.Reader, useragent string) *Robots {\n\tgroup := NewGroups(r).Find(useragent)\n\tif group == nil {\n\t\treturn &Robots{}\n\t}\n\tresult := &Robots{}\n\tfor _, value := range group.Allow {\n\t\tresult.add(NewRule(TypeAllow, value))\n\t}\n\tfor _, value := range group.Disallow {\n\t\tresult.add(NewRule(TypeDisallow, value))\n\t}\n\tif group.CrawlDelay != \"\" {\n\t\tif secs, err := strconv.Atoi(group.CrawlDelay); err == nil {\n\t\t\tresult.CrawlDelay = time.Duration(secs) * time.Second\n\t\t}\n\t}\n\treturn result\n}", "func NewRadar(history int, fetch RadarImage) *Radar {\n\tq, err := queue.NewQueue(history)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tr := Radar{\n\t\tsync.Mutex{},\n\t\tq,\n\t\tnil,\n\t\tfalse,\n\t\tmake(chan struct{}),\n\t\tfetch,\n\t}\n\n\tr.populate()\n\treturn &r\n}", "func New(logger log.Logger, reloadURL *url.URL, cfgFile, cfgEnvsubstFile, ruleDir string) *Reloader {\n\treturn &Reloader{\n\t\tlogger: logger,\n\t\treloadURL: reloadURL,\n\t\tcfgFilename: cfgFile,\n\t\tcfgSubstFilename: cfgEnvsubstFile,\n\t}\n}", "func New(t *testing.T, name string, arg ...string) *Runner {\n\treturn &Runner{t, name, arg}\n}", "func New(url string) (*Raptor, error) {\n\tr := Raptor{}\n\tr.SetConfig(&Config{\n\t\tURL: url,\n\t})\n\treturn &r, nil\n}", "func New(input io.Reader) Solution {\n\treturn Solution{Passports: parse(input)}\n}", "func NewAligner(target, query *linear.Seq, k, minLength int, minId float64) *Aligner {\n\treturn &Aligner{\n\t\ttarget: target,\n\t\tquery: query,\n\t\tk: k,\n\t\tminHitLength: minLength,\n\t\tminId: minId,\n\t}\n}", "func New(config Config) *Model {\n\treturn &Model{\n\t\tConfig: config,\n\t\tQuery: linear.New(config.InputSize, config.QuerySize),\n\t\tKey: linear.New(config.InputSize, config.KeySize),\n\t\tValue: linear.New(config.InputSize, config.ValueSize),\n\t}\n}", "func New(l *lexer.Lexer) *Parser {\n\tp := &Parser{l: l}\n\n\tp.nextToken()\n\tp.nextToken()\n\n\treturn p\n}", "func New(cfg Config, logger log.Logger) (*Agent, error) {\n\treturn newAgent(cfg, logger, defaultInstanceFactory)\n}", "func New(sources, exclusions []string) *Agent {\n\t// Create the agent, insert the sources and remove the excluded sources\n\tagent := &Agent{sources: make(map[string]subscraping.Source)}\n\n\tagent.addSources(sources)\n\tagent.removeSources(exclusions)\n\n\treturn agent\n}", "func New(r io.Reader) (Scanner, error) {\n\ttoks, err := lexer.Parse(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &scanner{toks: toks}, nil\n}", "func New(config Config) (*Rigel, error) {\n\tif config.Redis.Addr == \"\" {\n\t\tconfig.Redis.Addr = \"localhost:6379\"\n\t}\n\n\tif config.Namespace == \"\" {\n\t\tconfig.Namespace = \"rigel\"\n\t}\n\n\tif config.Concurrency == 0 {\n\t\tconfig.Concurrency = 1\n\t}\n\n\tif config.Hostname == \"\" {\n\t\tconfig.Hostname, _ = os.Hostname()\n\t}\n\n\topts := redis.Options(config.Redis)\n\tclient := redis.NewClient(&opts)\n\tif err := client.Ping().Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Rigel{\n\t\tredis: client,\n\t\tnamespace: config.Namespace,\n\t\thostname: config.Hostname,\n\t\thandlers: make(map[string]Handler),\n\t\tqueues: make(map[string]bool),\n\t\tconcurrency: config.Concurrency,\n\t\tquit: make(chan struct{}),\n\t}, nil\n}", "func New(numVisibleUnits, numHiddenUnits int) *RBM {\n\trbm := new(RBM)\n\trand.Seed(time.Now().UnixNano())\n\trbm.NumVisibleUnits = numVisibleUnits\n\trbm.NumHiddenUnits = numHiddenUnits\n\trbm.W = nnet.MakeMatrix(numHiddenUnits, numVisibleUnits)\n\trbm.B = make([]float64, numVisibleUnits)\n\trbm.C = make([]float64, numHiddenUnits)\n\trbm.GradW = nnet.MakeMatrix(numHiddenUnits, numVisibleUnits)\n\trbm.GradB = make([]float64, numVisibleUnits)\n\trbm.GradC = make([]float64, numHiddenUnits)\n\trbm.InitParam()\n\treturn rbm\n}", "func NewRaid(inputPlanes ...Plane) (Raid, error) {\n\tif len(inputPlanes) == 0 {\n\t\treturn Raid{}, errors.New(\"no planes to launch\")\n\t}\n\tvar planes []Plane\n\tfor _, plane := range inputPlanes {\n\t\tplanes = append(planes, plane)\n\t}\n\treturn Raid{Planes: planes}, nil\n}", "func New(seedData map[string]map[int]string) (*Ram, error) {\n\tvar ram Ram\n\n\tif err := ram.init(seedData); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ram, nil\n}", "func newQueryPlan(ctx context.Context, store storage.Store, stm *semantic.Statement, chanSize int, w io.Writer) (*queryPlan, error) {\n\tt, err := table.New([]string{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &queryPlan{\n\t\tstm: stm,\n\t\tstore: store,\n\t\tbndgs: stm.Bindings(),\n\t\tgrfsNames: stm.InputGraphNames(),\n\t\tclauses: stm.GraphPatternClauses(),\n\t\tfilters: stm.FilterClauses(),\n\t\ttbl: t,\n\t\tchanSize: chanSize,\n\t\ttracer: w,\n\t}, nil\n}", "func newMovingAverage(sampleSize int) *movingAverage {\n\n\tif sampleSize <= 0 {\n\t\tpanic(\"sampleSize must be greather than 0.\")\n\t}\n\n\treturn &movingAverage{\n\t\tsampleSize: sampleSize,\n\t\tring: make([]float64, sampleSize),\n\t}\n}", "func New(cfg Config, k8ssvc k8s.Service, logger log.Logger) operator.Operator {\n\tlogger = logger.With(\"operator\", operatorName)\n\n\thandler := NewHandler(logger)\n\tcrd := NewMultiRoleBindingCRD(k8ssvc)\n\tctrl := controller.NewSequential(cfg.ResyncDuration, handler, crd, nil, logger)\n\treturn operator.NewOperator(crd, ctrl, logger)\n}", "func New() AgentConfig {\n\treturn AgentConfig{\n\t\tCentral: corecfg.NewCentralConfig(corecfg.TraceabilityAgent),\n\t\t//Gateway: NewGatewayConfig(),\n\t\t//Manager: apimgrcfg.APIManagerConfiguration{\n\t\t//\tPollInterval: 1 * time.Minute,\n\t\t//\tTLS: corecfg.NewTLSConfig(),\n\t\t//},\n\t\tStatus: corecfg.NewStatusConfig(),\n\t}\n}", "func CreateAdam(targetPhrase []rune) (*Offspring, error) {\n\tphrase := RandomRuneSlice( len(targetPhrase) )\n\tfitness, err := GetFitness(targetPhrase, phrase)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\n\treturn &Offspring {\n\t\tParent: nil,\n\t\tPhrase: phrase,\n\t\tTargetPhrase: targetPhrase,\n\t\tGeneration: 0,\n\t\tFitness: fitness,\n\t}, nil\n}", "func New(cfg *Config) (*Agent, error) {\n\n\tlogger := cfg.Logger\n\tif logger == nil {\n\t\tlogLevel := hlog.LevelFromString(cfg.LogLevel)\n\t\tif logLevel == hlog.NoLevel {\n\t\t\tlogLevel = hlog.Info\n\t\t}\n\t\tlogFormat := cfg.LogTimeFormat\n\t\tif logFormat == \"\" {\n\t\t\tlogFormat = rkvApi.DefaultTimeFormat\n\t\t}\n\t\tlogOpts := &hlog.LoggerOptions{\n\t\t\tName: fmt.Sprintf(\"rkv-%s\", cfg.NodeName),\n\t\t\tLevel: logLevel,\n\t\t\tIncludeLocation: cfg.LogIncludeLocation,\n\t\t\tOutput: cfg.LogOutput,\n\t\t\tTimeFormat: logFormat,\n\t\t}\n\t\tif logLevel > hlog.Debug {\n\t\t\t// to skip serf and memberlist debug logs\n\t\t\tlogOpts.Exclude = func(\n\t\t\t\tlevel hlog.Level, msg string, args ...interface{}) bool {\n\n\t\t\t\treturn strings.Index(msg, \"[DEBUG]\") > -1\n\t\t\t}\n\t\t}\n\t\tlogger = hlog.New(logOpts)\n\t}\n\tcfg.Logger = logger\n\n\thostname, _ := os.Hostname()\n\trpcAddr, _ := cfg.RPCAddr()\n\tlogger.Info(\"os\", \"hostname\", hostname)\n\tlogger.Info(\"config\", \"log-level\", cfg.LogLevel)\n\tlogger.Info(\"config\", \"node-name\", cfg.NodeName)\n\tlogger.Info(\"config\", \"data-dir\", cfg.DataDir)\n\tlogger.Info(\"config\", \"db\", cfg.Backend.DSN())\n\tlogger.Info(\"config\", \"discovery-join-address\", cfg.StartJoinAddrs)\n\tlogger.Info(\"config\", \"gRPC address\", rpcAddr)\n\tlogger.Info(\"config\", \"Raft.Heartbeat timeout\", cfg.Raft.HeartbeatTimeout)\n\tlogger.Info(\"config\", \"Raft.Election timeout\", cfg.Raft.ElectionTimeout)\n\n\ta := &Agent{\n\t\tConfig: cfg,\n\t\tlogger: logger,\n\t\tregistry: cfg.Registry,\n\t}\n\n\tif a.registry == nil {\n\t\ta.registry = registry.NewApplyRegistrator()\n\t}\n\n\tvar setup = []struct {\n\t\tname string\n\t\tfn func() error\n\t}{\n\t\t{\"setupRoute\", a.setupRoute},\n\t\t{\"setupRaft\", a.setupRaft},\n\t\t{\"setupMembership\", a.setupMembership},\n\t\t{\"setupGrpcServer\", a.setupGrpcServer},\n\t\t{\"setupHTTPServer\", a.setupHTTPServer},\n\t}\n\tfor _, s := range setup {\n\t\tif err := s.fn(); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%v: %v\", s.name, err)\n\t\t}\n\t}\n\treturn a, nil\n}", "func New() *Agent {\n\treturn &Agent{\n\t\tReporter: newReporter(),\n\t\tWarmUp: config.WarmupEnabled,\n\t\tTimeoutMargin: config.TimeoutMargin,\n\t\tPlugins: []plugin.Plugin{},\n\t}\n}", "func NewReindexer(client *Client, source string, reindexerFunc ReindexerFunc) *Reindexer {\n\treturn &Reindexer{\n\t\tsourceClient: client,\n\t\tsourceIndex: source,\n\t\treindexerFunc: reindexerFunc,\n\t\tstatsOnly: true,\n\t}\n}", "func NewDML() *DML {\n\treturn &DML{RoutingParameters: &RoutingParameters{}}\n}", "func New(modifyOptions ModifyOptions) Options {\n\toption := Options{\n\t\tSkippedPropagatingAPIs: \"cluster.karmada.io;policy.karmada.io;work.karmada.io\",\n\t\tSecurePort: 8090,\n\t\tClusterStatusUpdateFrequency: metav1.Duration{Duration: 10 * time.Second},\n\t\tClusterLeaseDuration: metav1.Duration{Duration: 10 * time.Second},\n\t\tClusterMonitorPeriod: metav1.Duration{Duration: 10 * time.Second},\n\t\tClusterMonitorGracePeriod: metav1.Duration{Duration: 10 * time.Second},\n\t\tClusterStartupGracePeriod: metav1.Duration{Duration: 10 * time.Second},\n\t}\n\n\tif modifyOptions != nil {\n\t\tmodifyOptions(&option)\n\t}\n\treturn option\n}", "func New(agent string) (*Operator, error) {\n\tcli, err := client.New(agent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Operator{cli: cli}, nil\n}", "func NewPlanner() Planner {\n\treturn &simplePlanner{}\n}", "func New(cost int) abstract.Scheme {\n\treturn &scheme{\n\t\tCost: cost,\n\t}\n}", "func newNetwork(config neuralNetConfig) *neuralNet {\n\treturn &neuralNet{config: config}\n}", "func NewAdjOperator(n int32, inOrder bool, i *InvertedIndex) adjOperator {\n\treturn adjOperator{n, inOrder, i}\n}", "func New() (ugrade.JobSolver, error) {\n\treturn &defaultSolver{\n\t\tcompiler: compiler.New(),\n\t\ttcgenerator: tcgenerator.NewGenerator(),\n\t\tsubmissionExecutor: executor.New(),\n\t\tchecker: checker.New(),\n\t}, nil\n}", "func NewReader(cfg Config, plannerCfg PlannerConfig) (*Reader, error) {\n\tplanner, err := NewPlanner(plannerCfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tscanner, err := storage.NewChunkScanner(cfg.StorageType, cfg.StorageConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tid := fmt.Sprintf(\"%d_%d\", plannerCfg.FirstShard, plannerCfg.LastShard)\n\n\t// Default to one worker if none is set\n\tif cfg.NumWorkers < 1 {\n\t\tcfg.NumWorkers = 1\n\t}\n\n\treturn &Reader{\n\t\tcfg: cfg,\n\t\tid: id,\n\t\tplanner: planner,\n\t\tscanner: scanner,\n\t\tscanRequestsChan: make(chan chunk.ScanRequest),\n\t\tquit: make(chan struct{}),\n\t}, nil\n}", "func NewRGASS() RGASS {\n\trgass := RGASS{Model: NewModel()}\n\treturn rgass\n}", "func NewPlanParser(input antlr.TokenStream) *PlanParser {\n\tthis := new(PlanParser)\n\tdeserializer := antlr.NewATNDeserializer(nil)\n\tdeserializedATN := deserializer.DeserializeFromUInt16(parserATN)\n\tdecisionToDFA := make([]*antlr.DFA, len(deserializedATN.DecisionToState))\n\tfor index, ds := range deserializedATN.DecisionToState {\n\t\tdecisionToDFA[index] = antlr.NewDFA(ds, index)\n\t}\n\tthis.BaseParser = antlr.NewBaseParser(input)\n\n\tthis.Interpreter = antlr.NewParserATNSimulator(this, deserializedATN, decisionToDFA, antlr.NewPredictionContextCache())\n\tthis.RuleNames = ruleNames\n\tthis.LiteralNames = literalNames\n\tthis.SymbolicNames = symbolicNames\n\tthis.GrammarFileName = \"Plan.g4\"\n\n\treturn this\n}", "func New(opts ...Opt) *Onpar {\n\to := Onpar{\n\t\tcurrent: &level{},\n\t\tcallCount: 1,\n\t}\n\tfor _, opt := range opts {\n\t\to = opt(o)\n\t}\n\treturn &o\n}", "func New(c *Config) (*Filter, error) {\n\n\t//\n\t// dimensions\n\t//\n\n\trF, cF := c.F.Dims()\n\trG, cG := c.G.Dims()\n\trQ, cQ := c.Q.Dims()\n\trH, cH := c.H.Dims()\n\trR, cR := c.R.Dims()\n\n\t//\n\t// validate\n\t//\n\n\tif rF != cF {\n\t\treturn nil, errors.New(\"F must be square matrix\")\n\t}\n\n\tif rQ != cQ {\n\t\treturn nil, errors.New(\"Q must be square matrix\")\n\t}\n\n\tif rR != cR {\n\t\treturn nil, errors.New(\"R must be square matrix\")\n\t}\n\n\tif rF != rG {\n\t\treturn nil, errors.New(\"row dim of F must be matched to row dim of G\")\n\t}\n\n\tif cG != rQ {\n\t\treturn nil, errors.New(\"column dim of G must be matched to row dim of Q\")\n\t}\n\n\tif cH != cF {\n\t\treturn nil, errors.New(\"column dim of H must be matched to column dim of F\")\n\t}\n\n\tif rH != rR {\n\t\treturn nil, errors.New(\"row dim of H must be matched to row dim of R\")\n\t}\n\n\t// init internal states\n\n\tx := mat64.NewVector(cF, nil)\n\tv := mat64.NewDense(rF, cF, nil)\n\tident := mat64.NewDense(rF, cF, nil)\n\tfor i := 0; i < rF; i++ {\n\t\tident.Set(i, i, 1.0)\n\t}\n\n\treturn &Filter{\n\t\tConfig: *c,\n\t\tI: ident,\n\t\tX: x,\n\t\tV: v,\n\t}, nil\n}", "func NewAnalyzer(ctx *pulumi.Context,\n\tname string, args *AnalyzerArgs, opts ...pulumi.ResourceOption) (*Analyzer, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.AnalyzerName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'AnalyzerName'\")\n\t}\n\tvar resource Analyzer\n\terr := ctx.RegisterResource(\"aws:accessanalyzer/analyzer:Analyzer\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func New(opts []Options, mode BalanceMode) *Balancer {\n\tif len(opts) == 0 {\n\t\topts = []Options{\n\t\t\tOptions{Addr: \"127.0.0.1:4150\"},\n\t\t}\n\t}\n\n\tbalancer := &Balancer{\n\t\tselector: make(pool, len(opts)),\n\t\tmode: mode,\n\t}\n\tfor i := 0; i < len(opts); i++ {\n\t\tbalancer.selector[i] = newNsqBackend(&opts[i])\n\t}\n\treturn balancer\n}", "func NewAnalyzer() *Analyzer {\n\treturn &Analyzer{}\n}", "func New() *Assassin {\n\treturn &Assassin{\n\t\tGatherers: gatherer.Init(),\n\t\tAttackers: attacker.Init(),\n\t\tPoC: poc.Init(),\n\t}\n}", "func New(config config.Config) (RateLimiter, error) {\n\n\tstorage, err := resolveBucketStore(config.Storage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlimits := []limit.Limit{}\n\tfor name, config := range config.Limits {\n\t\tlimit, err := limit.New(name, config, storage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlimits = append(limits, limit)\n\t}\n\n\trateLimiter := &rateLimiter{limits: limits}\n\treturn rateLimiter, nil\n}", "func New(exec string, opts ...option) *Benchmark {\n\tret := &Benchmark{\n\t\texecutable: exec,\n\t}\n\tfor _, opt := range opts {\n\t\topt(ret)\n\t}\n\treturn ret\n}" ]
[ "0.5821134", "0.5446745", "0.532845", "0.5318612", "0.5181388", "0.50284636", "0.5003412", "0.49892327", "0.49769872", "0.49739477", "0.49185923", "0.48619148", "0.48398253", "0.4811074", "0.48108375", "0.48083663", "0.47546217", "0.4747193", "0.4737033", "0.4735215", "0.47302166", "0.4725312", "0.47206274", "0.47137353", "0.47129124", "0.469693", "0.4684685", "0.46672696", "0.46450016", "0.46442437", "0.46414423", "0.46358883", "0.46310523", "0.462598", "0.4624391", "0.46202844", "0.46152878", "0.4612502", "0.46068147", "0.46005845", "0.4587446", "0.45752695", "0.45668146", "0.45592976", "0.45577833", "0.4549757", "0.4529555", "0.4516298", "0.45146808", "0.45084864", "0.45039514", "0.44907078", "0.44719177", "0.44707814", "0.44586438", "0.4457247", "0.4443352", "0.44376156", "0.44372043", "0.4434173", "0.44330236", "0.4430189", "0.44245923", "0.44237325", "0.44198465", "0.44141245", "0.44112688", "0.44101343", "0.44040623", "0.44011942", "0.43998912", "0.43968406", "0.43963832", "0.43934843", "0.43826777", "0.43786314", "0.43768266", "0.43730044", "0.4372939", "0.43727908", "0.43695816", "0.43691537", "0.43682718", "0.43670118", "0.43581647", "0.43554327", "0.434982", "0.43439987", "0.43401477", "0.4339118", "0.4334955", "0.4334582", "0.43314055", "0.43245953", "0.43128613", "0.4310677", "0.43092555", "0.42993537", "0.4299261", "0.42983916" ]
0.72261465
0
newState returns a new state.
func (o *RAdam[T]) newState(shape ...int) *State { r, c := shape[0], shape[1] return &State{ M: mat.NewDense[T](mat.WithShape(r, c)), V: mat.NewDense[T](mat.WithShape(r, c)), Buf1: mat.NewDense[T](mat.WithShape(r, c)), Buf2: mat.NewDense[T](mat.WithShape(r, c)), Buf3: mat.NewDense[T](mat.WithShape(r, c)), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newState(initialFmtMsg, format string) (*state, error) {\n\tclifmt, err := polyfmt.NewFormatter(polyfmt.Mode(format))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn nil, err\n\t}\n\n\tclifmt.Print(initialFmtMsg, polyfmt.Pretty)\n\n\tcfg, err := appcfg.GetConfig()\n\tif err != nil {\n\t\terrText := fmt.Sprintf(\"error reading config file %q: %v\", appcfg.ConfigFilePath(), err)\n\t\tclifmt.PrintErr(errText)\n\t\tclifmt.Finish()\n\t\treturn nil, errors.New(errText)\n\t}\n\n\treturn &state{\n\t\tfmt: clifmt,\n\t\tcfg: cfg,\n\t}, nil\n}", "func (b *ClusterUpgradeBuilder) State(value string) *ClusterUpgradeBuilder {\n\tb.state = value\n\tb.bitmap_ |= 2\n\treturn b\n}", "func (c *Client) setState(s ConnState) {\n\tprev := c.state\n\tif prev == s || prev == Closed {\n\t\treturn\n\t}\n\tc.state = s\n\tif s != Selected {\n\t\tc.Logf(LogState, \"State change: %v -> %v\", prev, s)\n\t\tc.Mailbox = nil\n\t\tif s == Closed {\n\t\t\tif c.cch != nil {\n\t\t\t\tclose(c.cch)\n\t\t\t\truntime.Gosched()\n\t\t\t}\n\t\t\tc.setCaps(nil)\n\t\t\tc.deliver(abort)\n\t\t}\n\t} else if c.debugLog.mask&LogState != 0 {\n\t\tmb, rw := c.Mailbox.Name, \"[RW]\"\n\t\tif c.Mailbox.ReadOnly {\n\t\t\trw = \"[RO]\"\n\t\t}\n\t\tc.Logf(LogState, \"State change: %v -> %v (%+q %s)\", prev, s, mb, rw)\n\t}\n}", "func newState(digest string, blob remote.Blob) *state {\n\treturn &state{\n\t\tNode: nodefs.NewDefaultNode(),\n\t\tstatFile: &statFile{\n\t\t\tNode: nodefs.NewDefaultNode(),\n\t\t\tname: digest + \".json\",\n\t\t\tstatJSON: statJSON{\n\t\t\t\tDigest: digest,\n\t\t\t\tSize: blob.Size(),\n\t\t\t},\n\t\t\tblob: blob,\n\t\t},\n\t}\n}", "func (c *Change) State(on bool) *Change {\n\tc.params[\"on\"] = on\n\treturn c\n}", "func newState(ctx context.Context, client kubernetesClient, nsName, pvcName string) (*state, error) {\n\tns, err := client.GetNamespace(ctx, nsName)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not get namespace %v\", nsName)\n\t}\n\n\ts := &state{ns: ns}\n\n\toriginalNamePVC, err := client.GetPVC(ctx, pvcName, nsName)\n\tif err != nil && !apierrors.IsNotFound(err) {\n\t\treturn nil, err\n\t}\n\tif apierrors.IsNotFound(err) {\n\t\toriginalNamePVC = nil\n\t}\n\n\trenamedPVC, err := client.GetPVC(ctx, withMigrationSuffix(pvcName), nsName)\n\tif err != nil && !apierrors.IsNotFound(err) {\n\t\treturn nil, err\n\t}\n\tif apierrors.IsNotFound(err) {\n\t\trenamedPVC = nil\n\t}\n\n\tvar pvName string\n\tswitch {\n\tcase originalNamePVC != nil:\n\t\ts.completedPhase = originalNamePVC.Annotations[completedMigrationPhase]\n\t\tpvName = originalNamePVC.Spec.VolumeName\n\n\tcase renamedPVC != nil:\n\t\ts.completedPhase = renamedPVC.Annotations[completedMigrationPhase]\n\t\tpvName = renamedPVC.Spec.VolumeName\n\n\tdefault:\n\t\treturn nil, errors.Errorf(\"could not find PVC %v\", pvcName)\n\t}\n\n\tpv, err := client.GetPV(ctx, pvName)\n\tif err != nil || pv == nil {\n\t\treturn nil, errors.Wrapf(err, \"could not get corresponding PV %s\", pvName)\n\t}\n\ts.sourcePV = pv\n\n\tswitch s.completedPhase {\n\tcase \"\", \"retainPolicy\", \"scaleDown\":\n\t\tif originalNamePVC == nil {\n\t\t\treturn nil, errors.Errorf(\"could not find PVC %v\", pvcName)\n\t\t}\n\t\tif renamedPVC != nil {\n\t\t\treturn nil, errors.Errorf(\"found renamed PVC %v, but does not match phase %q\", renamedPVC.Name, s.completedPhase)\n\t\t}\n\n\t\ts.sourcePVC = originalNamePVC\n\n\tcase \"recreatePVC\", \"switchTargetPVC\":\n\t\tif originalNamePVC != nil {\n\t\t\t// TODO: we could also proactively delete the PVC instead...\n\t\t\treturn nil, errors.Errorf(\"found original PVC %v, but does not match phase %q\", originalNamePVC.Name, s.completedPhase)\n\t\t}\n\n\t\tif renamedPVC == nil {\n\t\t\treturn nil, errors.Errorf(\"could not find renamed PVC %v\", withMigrationSuffix(pvcName))\n\t\t}\n\n\t\ts.renamedPVC = renamedPVC\n\n\tcase \"createTargetPVC\", \"migrateData\", \"scaleUp\":\n\t\tif originalNamePVC == nil {\n\t\t\treturn nil, errors.Errorf(\"PVC %v does not exist\", pvcName)\n\t\t}\n\t\tif renamedPVC == nil {\n\t\t\treturn nil, errors.Errorf(\"renamed PVC %v does not exist\", withMigrationSuffix(pvcName))\n\t\t}\n\n\t\ts.targetPVC = originalNamePVC\n\t\ts.renamedPVC = renamedPVC\n\n\tcase \"cleanUp\":\n\t\ts.targetPVC = originalNamePVC\n\n\tdefault:\n\t\treturn nil, errors.Errorf(\"unknown phase: %q\", s.completedPhase)\n\t}\n\n\treturn s, nil\n}", "func (t *trial) patchState(ctx *actor.Context, s model.StateWithReason) error {\n\tswitch {\n\tcase model.TerminalStates[t.state]:\n\t\tctx.Log().Infof(\"ignoring transition in terminal state (%s -> %s)\", t.state, s.State)\n\t\treturn nil\n\tcase model.TerminalStates[s.State]:\n\t\tctx.Log().Infof(\"ignoring patch to terminal state %s\", s.State)\n\t\treturn nil\n\tcase t.state == s.State: // Order is important, else below will prevent re-sending kills.\n\t\tctx.Log().Infof(\"resending actions for transition for %s\", t.state)\n\t\treturn t.transition(ctx, s)\n\tcase model.StoppingStates[t.state] && !model.TrialTransitions[t.state][s.State]:\n\t\tctx.Log().Infof(\"ignoring patch to less severe stopping state (%s)\", s.State)\n\t\treturn nil\n\tdefault:\n\t\tctx.Log().Debugf(\"patching state after request (%s)\", s.State)\n\t\treturn t.transition(ctx, s)\n\t}\n}", "func getNewState (x, stateChange mat.Matrix, covariances mat.Symmetric) mat.Matrix {\n\tnormal, _ := distmv.NewNormal(getConstList(numRows(covariances), 0), covariances, randSource)\n\tnormalMat := mat.NewDense(numRows(covariances), numCols(x), normal.Rand(nil))\n\tnextState := mat.NewDense(numRows(x), numCols(x), nil)\n\tnextState.Mul(stateChange, x)\n\tnextState.Add(nextState, normalMat)\n\treturn nextState\n}", "func (sm *StateMachine) SetState(in *Msg, label string) string {\n\tdesiredState := sm.states[label]\n\n\t// If we're in a state beyond the desired state, go back. There are NO\n\t// checks for state when going backward, so if you're changing state\n\t// after its been completed, you'll need to do sanity checks OnEntry.\n\tif sm.state > desiredState {\n\t\tsm.state = desiredState\n\t\tsm.stateEntered = false\n\t\tsm.plugin.SetMemory(in, StateKey, desiredState)\n\t\tsm.plugin.SetMemory(in, stateEnteredKey, false)\n\t\treturn sm.Handlers[desiredState].OnEntry(in)\n\t}\n\n\t// If we're in a state before the desired state, go forward only as far\n\t// as we're allowed by the Complete guards.\n\tfor s := sm.state; s < desiredState; s++ {\n\t\tok, _ := sm.Handlers[s].Complete(in)\n\t\tif !ok {\n\t\t\tsm.state = s\n\t\t\tsm.stateEntered = false\n\t\t\tsm.plugin.SetMemory(in, StateKey, s)\n\t\t\tsm.plugin.SetMemory(in, stateEnteredKey, false)\n\t\t\treturn sm.Handlers[s].OnEntry(in)\n\t\t}\n\t}\n\n\t// No guards were triggered (go to state), or the state == desiredState,\n\t// so reset the state and run OnEntry again unless the plugin is now\n\t// complete.\n\tsm.state = desiredState\n\tsm.stateEntered = false\n\tsm.plugin.SetMemory(in, StateKey, desiredState)\n\tsm.plugin.SetMemory(in, stateEnteredKey, false)\n\treturn sm.Handlers[desiredState].OnEntry(in)\n}", "func stateTransition(currentState State, op Operator) (nextState State, ok bool) {\n\n\tvar from, to *RiverSide\n\n\tif currentState.boat == \"left\" {\n\t\tfrom, to = &currentState.left, &currentState.right\n\t\tnextState.boat = \"right\"\n\t\tnextState.right = RiverSide{ to.m + op.m, to.c + op.c }\n\t\tnextState.left = RiverSide{ from.m - op.m, from.c - op.c }\n\t} else {\n\t\tfrom, to = &currentState.right, &currentState.left\n\t\tnextState.boat = \"left\"\n\t\tnextState.left = RiverSide{ to.m + op.m, to.c + op.c }\n\t\tnextState.right = RiverSide{ from.m - op.m, from.c - op.c }\n\t}\n\n\tok = valid(nextState)\n\n\treturn\n}", "func (s *server) setState(state string) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\t// Temporarily store previous values.\n\t//prevState := s.state\n\t//prevLeader := s.leader\n\n\t// Update state and leader.\n\ts.state = state\n\tif state == Leader {\n\t\ts.leader = s.Name()\n\t\ts.syncedPeer = make(map[string]bool)\n\t}\n\t\t//\n\t\t//// Dispatch state and leader change events.\n\t\t//s.DispatchEvent(newEvent(StateChangeEventType, s.state, prevState))\n\t\t//\n\t\t//if prevLeader != s.leader {\n\t\t//\ts.DispatchEvent(newEvent(LeaderChangeEventType, s.leader, prevLeader))\n\t\t//}\n}", "func (s *StateMgr) State(n State) State {\n\treturn s.current\n}", "func (m *StateSwitcherMock) setState(p State) {\n\tatomic.AddUint64(&m.setStatePreCounter, 1)\n\tdefer atomic.AddUint64(&m.setStateCounter, 1)\n\n\tif m.setStateMock.mockExpectations != nil {\n\t\ttestify_assert.Equal(m.t, *m.setStateMock.mockExpectations, StateSwitcherMocksetStateParams{p},\n\t\t\t\"StateSwitcher.setState got unexpected parameters\")\n\n\t\tif m.setStateFunc == nil {\n\n\t\t\tm.t.Fatal(\"No results are set for the StateSwitcherMock.setState\")\n\n\t\t\treturn\n\t\t}\n\t}\n\n\tif m.setStateFunc == nil {\n\t\tm.t.Fatal(\"Unexpected call to StateSwitcherMock.setState\")\n\t\treturn\n\t}\n\n\tm.setStateFunc(p)\n}", "func NewState(r Rules, p1, p2 Player) *State {\n\tpieces := newPieceIDMap(r.PieceCount())\n\tcs := newPieceMap(r.PieceCount())\n\tps := newCellMap(r.BoardSize())\n\tfor i := 0; i < r.PieceCount(); i++ {\n\t\tp1id := PieceID(i + 1)\n\t\tp2id := PieceID(i + r.PieceCount() + 1)\n\t\tp1 := NewPiece(p1id, r.Life(), r.Damage())\n\t\tp2 := NewPiece(p2id, r.Life(), r.Damage())\n\t\tc1 := NewCell(0, i*2+1)\n\t\tc2 := NewCell(r.BoardSize()-1, i*2+1)\n\t\tpieces.Set(p1id, p1)\n\t\tpieces.Set(p2id, p2)\n\t\tcs.Set(p1, c1)\n\t\tcs.Set(p2, c2)\n\t\tps.Set(c1, p1id)\n\t\tps.Set(c2, p2id)\n\t}\n\treturn &State{\n\t\tplayer1PiecesAlive: r.PieceCount(),\n\t\tplayer2PiecesAlive: r.PieceCount(),\n\t\tcurrentPlayer: Player1,\n\t\trules: r,\n\t\tpiecesToCells: cs,\n\t\tcellsToPieceIDs: ps,\n\t\tplayers: []Player{Player1: p1, Player2: p2},\n\t\tpieces: pieces,\n\t}\n}", "func (t *task) changeState(from, to State) bool {\n\treturn atomic.CompareAndSwapInt32(&t.state, int32(from), int32(to))\n}", "func (w *watcher) changeState(from, to int32) bool {\n\treturn atomic.CompareAndSwapInt32(&w.state, int32(from), int32(to))\n}", "func GetCurrentState() {\n\n}", "func (e HybridKFEstimate) State() *mat64.Vector {\n\treturn e.state\n}", "func (m *Machine) State() State {\n\treturn m.currentState\n}", "func (cb *Breaker) State() State {\n\tcb.mutex.Lock()\n\tdefer cb.mutex.Unlock()\n\n\tnow := time.Now()\n\tstate, _ := cb.currentState(now)\n\treturn state\n}", "func (b *ClusterBuilder) State(value ClusterState) *ClusterBuilder {\n\tb.state = value\n\tb.bitmap_ |= 274877906944\n\treturn b\n}", "func newResultState(sharedConfig jsonio.GoldResults, config *GoldClientConfig) *resultState {\n\tgoldURL := config.OverrideGoldURL\n\tif goldURL == \"\" {\n\t\tgoldURL = getGoldInstanceURL(config.InstanceID)\n\t}\n\tbucket := config.OverrideBucket\n\tif bucket == \"\" {\n\t\tbucket = getBucket(config.InstanceID)\n\t}\n\n\tret := &resultState{\n\t\tSharedConfig: sharedConfig,\n\t\tPerTestPassFail: config.PassFailStep,\n\t\tFailureFile: config.FailureFile,\n\t\tInstanceID: config.InstanceID,\n\t\tUploadOnly: config.UploadOnly,\n\t\tGoldURL: goldURL,\n\t\tBucket: bucket,\n\t}\n\n\treturn ret\n}", "func (s *ServiceManager) setState(st ManagerStateEnum) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.state = st\n}", "func SetState(newState map[string]interface{}) {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tfor key, value := range newState {\n\t\tstate[key] = value\n\t}\n}", "func newStateSetter() *stateSetter {\n\tstateSetter := new(stateSetter)\n\tstateSetter.predefinedStrategy = v1alpha1.MemcachedSpec{Interval: 30, Threshold: 20, Size: 2}\n\treturn stateSetter\n}", "func (w *World) State() State {\n\treturn State{World: w, L: w.l}\n}", "func (m *VppToken) SetState(value *VppTokenState)() {\n m.state = value\n}", "func (o *Cell) State() interface{} {\n\td := cellDiff{\n Hue: &o.Hue,\n X: &o.X,\n Y: &o.Y,\n AudioPath: &o.AudioPath,\n MapName: &o.MapName,\n Class: &o.Class,\n MidiNote: &o.MidiNote,\n }\n return d\n}", "func (o *Note) State() interface{} {\n\td := noteDiff{\n SubKey: &o.SubKey,\n Number: &o.Number,\n Velocity: &o.Velocity,\n }\n return d\n}", "func (cs *ConsensusState) updateToState(state State) {\n\tif cs.CommitRound > -1 && 0 < cs.Height && cs.Height != state.LastBlockHeight {\n\t\tpanic(fmt.Sprintf(\"updateToState expected state height of %v but found %v\", cs.Height, state.LastBlockHeight))\n\t}\n\tif !cs.state.IsEmpty() && cs.state.LastBlockHeight+1 != cs.Height {\n\t\t// This might happen when someone else is mutating cs.state.\n\t\t// Someone forgot to pass in state.Copy() somewhere?!\n\t\tpanic(fmt.Sprintf(\"Inconsistent cs.state.LastBlockHeight+1 %v vs cs.Height %v\", cs.state.LastBlockHeight+1, cs.Height))\n\t}\n\n\t// If state isn't further out than cs.state, just ignore.\n\t// This happens when SwitchToConsensus() is called in the reactor.\n\t// We don't want to reset e.g. the Votes.\n\tif !cs.state.IsEmpty() && (state.LastBlockHeight <= cs.state.LastBlockHeight) {\n\t\tqbftlog.Info(\"Ignoring updateToState()\", \"newHeight\", state.LastBlockHeight+1, \"oldHeight\", cs.state.LastBlockHeight+1)\n\t\treturn\n\t}\n\t// disable gossip votes\n\tif UseAggSig() && gossipVotes.Load().(bool) {\n\t\tgossipVotes.Store(false)\n\t}\n\n\t// Reset fields based on state.\n\tvalidators := state.Validators.Copy()\n\tlastCommit := (*ttypes.VoteSet)(nil)\n\tif cs.CommitRound > -1 && cs.Votes != nil {\n\t\tif state.LastSequence == 0 {\n\t\t\tif !cs.Votes.Precommits(cs.CommitRound).HasTwoThirdsMajority() {\n\t\t\t\tpanic(\"updateToState: last Precommit not have +2/3\")\n\t\t\t}\n\t\t\tlastCommit = cs.Votes.Precommits(cs.CommitRound)\n\t\t} else {\n\t\t\tif !cs.Votes.Prevotes(cs.CommitRound).HasTwoThirdsMajority() {\n\t\t\t\tpanic(\"updateToState: last Prevote not have +2/3\")\n\t\t\t}\n\t\t\tlastCommit = cs.Votes.Prevotes(cs.CommitRound)\n\t\t}\n\t}\n\n\t// Next desired block height\n\theight := state.LastBlockHeight + 1\n\t// RoundState fields\n\tcs.updateHeight(height)\n\tround := getStartRound(state)\n\tcs.updateRoundStep(round, ttypes.RoundStepNewHeight)\n\t// Increment validators if necessary\n\tif state.Sequence > 0 && round > 0 {\n\t\tvalidators.IncrementAccum(round)\n\t\tqbftlog.Info(\"updateToState validator change\", \"round\", round,\n\t\t\t\"proposer\", fmt.Sprintf(\"%X\", ttypes.Fingerprint(validators.Proposer.Address)))\n\t}\n\tif cs.CommitTime.IsZero() {\n\t\t// \"Now\" makes it easier to sync up dev nodes.\n\t\t// We add timeoutCommit to allow transactions\n\t\t// to be gathered for the first block.\n\t\t// And alternative solution that relies on clocks:\n\t\t// cs.StartTime = state.LastBlockTime.Add(timeoutCommit)\n\t\tcs.StartTime = cs.Commit(time.Now())\n\t} else {\n\t\tcs.StartTime = cs.Commit(cs.CommitTime)\n\t}\n\tcs.Validators = validators\n\tcs.Proposal = nil\n\tcs.ProposalBlock = nil\n\tcs.ProposalBlockHash = nil\n\tcs.LockedRound = -1\n\tcs.LockedBlock = nil\n\tcs.ValidRound = -1\n\tcs.ValidBlock = nil\n\tcs.Votes = ttypes.NewHeightVoteSet(state.ChainID, height, validators, state.Sequence)\n\tcs.CommitRound = -1\n\tcs.LastCommit = lastCommit\n\tcs.LastValidators = state.LastValidators\n\tcs.begCons = time.Time{}\n\n\tcs.state = state\n\n\t// Finally, broadcast RoundState\n\tcs.newStep()\n}", "func (o M3DbOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *M3Db) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (m *AgreementAcceptance) SetState(value *AgreementAcceptanceState)() {\n m.state = value\n}", "func (bot *ExchangeBot) updateState() error {\n\tdcrPrice, volume := bot.processState(bot.currentState.DcrBtc, true)\n\tbtcPrice, _ := bot.processState(bot.currentState.FiatIndices, false)\n\tif dcrPrice == 0 || btcPrice == 0 {\n\t\tbot.failed = true\n\t\tbot.stateCopy = nil\n\t\treturn nil\n\t}\n\n\tbot.failed = false\n\tbot.currentState.Price = dcrPrice * btcPrice\n\tbot.currentState.Volume = volume\n\tvar jsonBytes []byte\n\tvar err error\n\tif bot.config.Indent {\n\t\tjsonBytes, err = json.MarshalIndent(bot.currentState, \"\", \" \")\n\t} else {\n\t\tjsonBytes, err = json.Marshal(bot.currentState)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to write bytes\")\n\t}\n\tbot.currentStateBytes = jsonBytes\n\tbot.stateCopy = bot.currentState.copy()\n\treturn nil\n}", "func NewState(c metrics.Counter, key string) *State {\n\tk := metrics.NewTag(\"key\", key)\n\tf := metrics.NewTag(\"status\", \"failure\")\n\tt := metrics.NewTag(\"status\", \"executions\")\n\n\tif c == nil {\n\t\tc = &metrics.NullCounter{}\n\t}\n\n\treturn &State{0, 0, 0, utcFuture, c, k, f, t, &sync.Mutex{}}\n}", "func (o JobStatusOutput) State() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *string { return v.State }).(pulumi.StringPtrOutput)\n}", "func (o ConversationModelOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ConversationModel) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (nm *NodeMonitor) setState(state *models.MonitorStatus) {\n\tnm.mutex.Lock()\n\tnm.state = state\n\tnm.mutex.Unlock()\n}", "func (o KafkaMirrorMakerOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *KafkaMirrorMaker) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (tm *TuringMachine) ChangeState(output *TuringMachine_TransitionFunction_Delta_Output) {\n\t// change to next state\n\t// Notice: protobuf-defined GetStaet() returns 0 when \"state element is empty\",\n\t// same as initial state 0. But, it is different of \"State 0\" (existing state 0).\n\t// This turing-machine assumes that its state starts 0 and DOES NOT back to 0 again.\n\tif output.GetState() > 0 {\n\t\ttm.State = output.GetState()\n\t}\n\t// write symbol to tape under head-position\n\tif output.GetSymbol() != \"\" {\n\t\tcellList := tm.GetTape().GetCell()\n\t\tcellList[tm.GetHeadPosition()].Symbol = output.GetSymbol()\n\t}\n\t// move to next head position\n\tswitch output.GetHeadMove() {\n\tcase \"left\":\n\t\ttm.HeadPosition--\n\tdefault:\n\t\ttm.HeadPosition++\n\t}\n}", "func (self Source) State() State {\n\treturn State(self.Geti(AlSourceState))\n}", "func (fsm *Fsm) State() State {\n\treturn fsm.state\n}", "func (o CapacityCommitmentOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *CapacityCommitment) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (o AiFeatureStoreEntityTypeMonitoringConfigImportFeaturesAnalysisOutput) State() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AiFeatureStoreEntityTypeMonitoringConfigImportFeaturesAnalysis) *string { return v.State }).(pulumi.StringPtrOutput)\n}", "func (nm *NodeMonitor) setState(state *models.MonitorStatus) {\n\tnm.Mutex.Lock()\n\tnm.state = state\n\tnm.Mutex.Unlock()\n}", "func (device *Device) changeState(want deviceState) (err error) {\n\tdevice.state.Lock()\n\tdefer device.state.Unlock()\n\told := device.deviceState()\n\tif old == deviceStateClosed {\n\t\t// once closed, always closed\n\t\tdevice.log.Verbosef(\"Interface closed, ignored requested state %s\", want)\n\t\treturn nil\n\t}\n\tswitch want {\n\tcase old:\n\t\treturn nil\n\tcase deviceStateUp:\n\t\tdevice.state.state.Store(uint32(deviceStateUp))\n\t\terr = device.upLocked()\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\tfallthrough // up failed; bring the device all the way back down\n\tcase deviceStateDown:\n\t\tdevice.state.state.Store(uint32(deviceStateDown))\n\t\terrDown := device.downLocked()\n\t\tif err == nil {\n\t\t\terr = errDown\n\t\t}\n\t}\n\tdevice.log.Verbosef(\"Interface state was %s, requested %s, now %s\", old, want, device.deviceState())\n\treturn\n}", "func (e *localfileExec) setState(state execState, err error) {\n\te.mu.Lock()\n\te.state = state\n\te.err = err\n\te.cond.Broadcast()\n\te.mu.Unlock()\n}", "func (o VirtualNetworkRuleOutput) State() StatePtrOutput {\n\treturn o.ApplyT(func(v VirtualNetworkRule) *State { return v.State }).(StatePtrOutput)\n}", "func (e *dockerExec) setState(state execState, err error) {\n\te.mu.Lock()\n\te.State = state\n\te.err = err\n\te.cond.Broadcast()\n\te.mu.Unlock()\n}", "func newStudentState(content *Content) *studentState {\n\tstate := &studentState{content: content}\n\tstate.reset()\n\treturn state\n}", "func (r Request) State() interfaces.GameState { return r.state }", "func (ed *Editor) State() *types.State {\n\treturn &ed.state\n}", "func NewState() *State {\n\treturn &State{\n\t\tProblem: make(Problem),\n\t\tSolution: make(Solution),\n\t\tDependees: make(StringGraph),\n\t}\n}", "func (o LakeOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Lake) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (m *mover) State() string {\n\treturn m.game.State\n}", "func (m *MacOSSoftwareUpdateStateSummary) SetState(value *MacOSSoftwareUpdateState)() {\n err := m.GetBackingStore().Set(\"state\", value)\n if err != nil {\n panic(err)\n }\n}", "func (p *parser) restoreState(state storeDict) {\n\tif p.debug {\n\t\tdefer p.out(p.in(\"restoreState\"))\n\t}\n\tp.cur.state = state\n}", "func (c *Context) State() *State {\n\treturn c.state.DeepCopy()\n}", "func (p *parser) cloneState() storeDict {\n\tif p.debug {\n\t\tdefer p.out(p.in(\"cloneState\"))\n\t}\n\n\tstate := make(storeDict, len(p.cur.state))\n\tfor k, v := range p.cur.state {\n\t\tif c, ok := v.(Cloner); ok {\n\t\t\tstate[k] = c.Clone()\n\t\t} else {\n\t\t\tstate[k] = v\n\t\t}\n\t}\n\treturn state\n}", "func (o TestMatrixOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *TestMatrix) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (c *Curl) CopyState(s Trits) {\n\tcopy(s, c.state[:])\n}", "func (p *parser) cloneState() storeDict {\n\tif p.debug {\n\t\tdefer p.out(p.in(\"cloneState\"))\n\t}\n\n\tstate := statePool.Get().(storeDict)\n\tfor k, v := range p.cur.state {\n\t\tif c, ok := v.(Cloner); ok {\n\t\t\tstate[k] = c.Clone()\n\t\t} else {\n\t\t\tstate[k] = v\n\t\t}\n\t}\n\treturn state\n}", "func (p *parser) cloneState() storeDict {\n\tif p.debug {\n\t\tdefer p.out(p.in(\"cloneState\"))\n\t}\n\n\tstate := statePool.Get().(storeDict)\n\tfor k, v := range p.cur.state {\n\t\tif c, ok := v.(Cloner); ok {\n\t\t\tstate[k] = c.Clone()\n\t\t} else {\n\t\t\tstate[k] = v\n\t\t}\n\t}\n\treturn state\n}", "func (r *HumioClusterReconciler) setState(ctx context.Context, state string, hc *humiov1alpha1.HumioCluster) error {\n\tif hc.Status.State == state {\n\t\treturn nil\n\t}\n\tr.Log.Info(fmt.Sprintf(\"setting cluster state to %s\", state))\n\t// TODO: fix the logic in ensureMismatchedPodsAreDeleted() to allow it to work without doing setStateOptimistically().\n\tif err := r.setStateOptimistically(ctx, state, hc); err != nil {\n\t\terr := retry.RetryOnConflict(retry.DefaultRetry, func() error {\n\t\t\terr := r.getLatestHumioCluster(ctx, hc)\n\t\t\tif err != nil {\n\t\t\t\tif !k8serrors.IsNotFound(err) {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\thc.Status.State = state\n\t\t\treturn r.Status().Update(ctx, hc)\n\t\t})\n\t\tif err != nil {\n\t\t\treturn r.logErrorAndReturn(err, \"failed to update resource status\")\n\t\t}\n\t}\n\treturn nil\n}", "func (o LookupAgentPoolResultOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupAgentPoolResult) string { return v.State }).(pulumi.StringOutput)\n}", "func (f *filterImpl) State() mat.Vector {\n\tvar state mat.VecDense\n\tstate.CloneFromVec(f.savedState)\n\treturn &state\n}", "func (d *DBClient) StateHandler(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tvar sr stateRequest\n\n\t// this is mainly for testing, since when you create\n\tif r.Body == nil {\n\t\tr.Body = ioutil.NopCloser(bytes.NewBuffer([]byte(\"\")))\n\t}\n\n\tdefer r.Body.Close()\n\tbody, err := ioutil.ReadAll(r.Body)\n\n\tif err != nil {\n\t\t// failed to read response body\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t}).Error(\"Could not read response body!\")\n\t\thttp.Error(w, \"Failed to read request body.\", 400)\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(body, &sr)\n\n\tif err != nil {\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(400) // can't process this entity\n\t\treturn\n\t}\n\n\tavailableModes := map[string]bool{\n\t\t\"virtualize\": true,\n\t\t\"capture\": true,\n\t\t\"modify\": true,\n\t\t\"synthesize\": true,\n\t}\n\n\tif !availableModes[sr.Mode] {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"suppliedMode\": sr.Mode,\n\t\t}).Error(\"Wrong mode found, can't change state\")\n\t\thttp.Error(w, \"Bad mode supplied, available modes: virtualize, capture, modify, synthesize.\", 400)\n\t\treturn\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"newState\": sr.Mode,\n\t\t\"body\": string(body),\n\t}).Info(\"Handling state change request!\")\n\n\t// setting new state\n\td.Cfg.SetMode(sr.Mode)\n\n\tvar en Entry\n\ten.ActionType = ActionTypeConfigurationChanged\n\ten.Message = \"changed\"\n\ten.Time = time.Now()\n\ten.Data = []byte(\"sr.Mode\")\n\n\tif err := d.Hooks.Fire(ActionTypeConfigurationChanged, &en); err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t\t\"message\": en.Message,\n\t\t\t\"actionType\": ActionTypeConfigurationChanged,\n\t\t}).Error(\"failed to fire hook\")\n\t}\n\n\tvar resp stateRequest\n\tresp.Mode = d.Cfg.GetMode()\n\tresp.Destination = d.Cfg.Destination\n\tb, _ := json.Marshal(resp)\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.Write(b)\n\n}", "func setState(state *bytes.Buffer) error {\n\tcmd := exec.Command(\"stty\", state.String())\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\treturn cmd.Run()\n}", "func (r *remoteReplicator) State() *state {\n\treturn r.state.Load().(*state)\n}", "func (s *RaftStateMachine) State(ctx context.Context) *kronospb.OracleState {\n\treturn s.stateMachine.State(ctx)\n}", "func (i ImmExamplesState) IsState() {}", "func (c ChooserState) IsState() {}", "func (sm *StateMachine) State() int {\n\treturn sm.state\n}", "func (o AgentPoolOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AgentPool) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (msh *Mesh) pushLayersToState(ctx context.Context, oldPbase, newPbase types.LayerID) {\n\tlogger := msh.WithContext(ctx).WithFields(\n\t\tlog.FieldNamed(\"old_pbase\", oldPbase),\n\t\tlog.FieldNamed(\"new_pbase\", newPbase))\n\tlogger.Info(\"pushing layers to state\")\n\n\t// TODO: does this need to be hardcoded? can we use types.GetEffectiveGenesis instead?\n\t// see https://github.com/spacemeshos/go-spacemesh/issues/2670\n\tlayerTwo := types.NewLayerID(2)\n\tif oldPbase.Before(layerTwo) {\n\t\tmsh.With().Warning(\"tried to push layer < 2\",\n\t\t\tlog.FieldNamed(\"old_pbase\", oldPbase),\n\t\t\tlog.FieldNamed(\"new_pbase\", newPbase))\n\t\tif newPbase.Before(types.NewLayerID(3)) {\n\t\t\treturn\n\t\t}\n\t\toldPbase = layerTwo.Sub(1) // since we add one, below\n\t}\n\n\t// we never reapply the state of oldPbase. note that state reversions must be handled separately.\n\tfor layerID := oldPbase.Add(1); !layerID.After(newPbase); layerID = layerID.Add(1) {\n\t\tl, err := msh.GetLayer(layerID)\n\t\t// TODO: propagate/handle error\n\t\tif err != nil || l == nil {\n\t\t\tif layerID.GetEpoch().IsGenesis() {\n\t\t\t\tlogger.With().Info(\"failed to get layer (expected for genesis layers)\", layerID, log.Err(err))\n\t\t\t} else {\n\t\t\t\tlogger.With().Error(\"failed to get layer\", layerID, log.Err(err))\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tvalidBlocks, invalidBlocks := msh.BlocksByValidity(l.Blocks())\n\t\tmsh.updateStateWithLayer(ctx, types.NewExistingLayer(layerID, validBlocks))\n\t\tmsh.Event().Info(\"end of layer state root\",\n\t\t\tlayerID,\n\t\t\tlog.String(\"state_root\", util.Bytes2Hex(msh.txProcessor.GetStateRoot().Bytes())),\n\t\t)\n\t\tmsh.reInsertTxsToPool(validBlocks, invalidBlocks, l.Index())\n\t}\n}", "func NewState() State {\n\treturn State{\n\t\tTime: NewLocalTime(time.Now()),\n\t}\n}", "func (f *Fake) ModifyState(ctx context.Context, newState tree.State) {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\tif f.TreeStatus.State != newState {\n\t\tf.TreeStatus.State = newState\n\t\tf.TreeStatus.Since = clock.Now(ctx).UTC()\n\t}\n}", "func (st *State) clone() *State {\n\ts := *st\n\ts.Balance = nil\n\ts.Balance = new(big.Int).Set(st.Balance)\n\ts.VotingWeight = nil\n\ts.VotingWeight = new(big.Int).Set(st.VotingWeight)\n\tif st.CodeHash != nil {\n\t\ts.CodeHash = nil\n\t\ts.CodeHash = make([]byte, len(st.CodeHash))\n\t\tcopy(s.CodeHash, st.CodeHash)\n\t}\n\t// Voters won't be used, set to nil for simplicity\n\ts.Voters = nil\n\treturn &s\n}", "func NewState() *State {\n\tshowing := randCard()\n\tsum := showing\n\tfor dealerPolicy(sum) {\n\t\tc := randCard()\n\t\tsum += c\n\t}\n\treturn &State{\n\t\tObservable: Observable{\n\t\t\tCurrentSum: randCard(),\n\t\t\tDealerShowing: showing,\n\t\t},\n\t\tDealerSum: sum,\n\t}\n}", "func (h *StabNode) State() **linkedlist.State {\n\treturn &h.state\n}", "func (t *Changeset) State() (s ChangesetState, err error) {\n\tswitch m := t.Metadata.(type) {\n\tcase *github.PullRequest:\n\t\ts = ChangesetState(m.State)\n\tcase *bitbucketserver.PullRequest:\n\t\ts = ChangesetState(m.State)\n\tdefault:\n\t\treturn \"\", errors.New(\"unknown changeset type\")\n\t}\n\n\tif !s.Valid() {\n\t\treturn \"\", errors.Errorf(\"changeset state %q invalid\", s)\n\t}\n\n\treturn s, nil\n}", "func (a *Agent) updateState() {\n\tfor stateKey, stateVal := range a.state.states {\n\t\tif stateInfo, seen := agentStateInfos[stateKey]; seen {\n\t\t\ta.state.states[stateKey] += stateInfo.perTurn\n\t\t} else if stateVal > 0 { // experience fades away if remaining number of turns is positive\n\t\t\ta.state.states[stateKey]--\n\t\t}\n\t}\n}", "func (o VirtualNetworkRuleResponseOutput) State() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v VirtualNetworkRuleResponse) *string { return v.State }).(pulumi.StringPtrOutput)\n}", "func (b *GroupsToggleMarketBuilder) State(v GroupMarketState) *GroupsToggleMarketBuilder {\n\tb.Params[\"state\"] = v\n\treturn b\n}", "func (t *task) State() State {\n\tv := atomic.LoadInt32(&t.state)\n\treturn State(v)\n}", "func NewState(opts ...Option) *LState {\r\n\tdo := &Options{\r\n\t\tHotfixTime: DefaultHotfix,\r\n\t\tCallStackSize: DefaultCallStackSize,\r\n\t\tRegistrySize: DefaultRegistrySize,\r\n\t}\r\n\tfor _, option := range opts {\r\n\t\toption.f(do)\r\n\t}\r\n\treturn NewStateWithOpts(do)\r\n}", "func (ex *extension) changeState(s nodeState) {\n\tif s == dirtyNode && ex.state != dirtyNode {\n\t\tex.state = dirtyNode\n\t}\n}", "func (m *AccessPackageAssignment) SetState(value *AccessPackageAssignmentState)() {\n m.state = value\n}", "func (b *setStateBuilder) State(state map[string]interface{}) *setStateBuilder {\n\tb.opts.State = state\n\treturn b\n}", "func NewSecurityActionState()(*SecurityActionState) {\n m := &SecurityActionState{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func (fsm *FSM) State() string {\n\tstateChan := make(chan string)\n\tfsm.stateChan <- stateChan\n\treturn <-stateChan\n}", "func NewState(name string) *State {\n\treturn &State{\n\t\tName: name,\n\t}\n}", "func(decorator *ProcessDecorator) changeState() string {\n\treturn \"state of process changed from down to up\"\n}", "func (o LookupIndexResultOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupIndexResult) string { return v.State }).(pulumi.StringOutput)\n}", "func (lh *LoginHandler) HandleStateNew(c *Condition) (string, interface{}) {\n\tswitch pld := c.Payload.(type) {\n\tcase *PreparePayload:\n\t\tlh.userId = pld.userId\n\t\tlh.password = pld.password\n\t\tlh.illegalLoginCounter = 0\n\t\tlh.locked = false\n\n\t\tlog.Printf(\"User '%v' prepared.\", lh.userId)\n\n\t\treturn \"Authenticating\", nil\n\tcase *LoginPayload:\n\t\tlog.Printf(\"Illegal login, handler not initialized!\")\n\n\t\treturn \"New\", false\n\tcase Timeout:\n\t\tlog.Printf(\"Timeout, terminate handler!\")\n\n\t\treturn \"Terminate\", nil\n\t}\n\n\tlog.Printf(\"Illegal payload '%v' during state 'new'!\", c.Payload)\n\n\treturn \"New\", nil\n}", "func (o WorkflowOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Workflow) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func shimNewState(newState *states.State, providers map[string]terraform.ResourceProvider) (*terraform.State, error) {\n\tstate := terraform.NewState()\n\n\t// in the odd case of a nil state, let the helper packages handle it\n\tif newState == nil {\n\t\treturn nil, nil\n\t}\n\n\tfor _, newMod := range newState.Modules {\n\t\tmod := state.AddModule(newMod.Addr)\n\n\t\tfor name, out := range newMod.OutputValues {\n\t\t\toutputType := \"\"\n\t\t\tval := hcl2shim.ConfigValueFromHCL2(out.Value)\n\t\t\tty := out.Value.Type()\n\t\t\tswitch {\n\t\t\tcase ty == cty.String:\n\t\t\t\toutputType = \"string\"\n\t\t\tcase ty.IsTupleType() || ty.IsListType():\n\t\t\t\toutputType = \"list\"\n\t\t\tcase ty.IsMapType():\n\t\t\t\toutputType = \"map\"\n\t\t\t}\n\n\t\t\tmod.Outputs[name] = &terraform.OutputState{\n\t\t\t\tType: outputType,\n\t\t\t\tValue: val,\n\t\t\t\tSensitive: out.Sensitive,\n\t\t\t}\n\t\t}\n\n\t\tfor _, res := range newMod.Resources {\n\t\t\tresType := res.Addr.Type\n\t\t\tproviderType := res.ProviderConfig.ProviderConfig.Type\n\n\t\t\tresource := getResource(providers, providerType, res.Addr)\n\n\t\t\tfor key, i := range res.Instances {\n\t\t\t\tresState := &terraform.ResourceState{\n\t\t\t\t\tType: resType,\n\t\t\t\t\tProvider: res.ProviderConfig.String(),\n\t\t\t\t}\n\n\t\t\t\t// We should always have a Current instance here, but be safe about checking.\n\t\t\t\tif i.Current != nil {\n\t\t\t\t\tflatmap, err := shimmedAttributes(i.Current, resource)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, fmt.Errorf(\"error decoding state for %q: %s\", resType, err)\n\t\t\t\t\t}\n\n\t\t\t\t\tvar meta map[string]interface{}\n\t\t\t\t\tif i.Current.Private != nil {\n\t\t\t\t\t\terr := json.Unmarshal(i.Current.Private, &meta)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tresState.Primary = &terraform.InstanceState{\n\t\t\t\t\t\tID: flatmap[\"id\"],\n\t\t\t\t\t\tAttributes: flatmap,\n\t\t\t\t\t\tTainted: i.Current.Status == states.ObjectTainted,\n\t\t\t\t\t\tMeta: meta,\n\t\t\t\t\t}\n\n\t\t\t\t\tif i.Current.SchemaVersion != 0 {\n\t\t\t\t\t\tif resState.Primary.Meta == nil {\n\t\t\t\t\t\t\tresState.Primary.Meta = map[string]interface{}{}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresState.Primary.Meta[\"schema_version\"] = i.Current.SchemaVersion\n\t\t\t\t\t}\n\n\t\t\t\t\tfor _, dep := range i.Current.Dependencies {\n\t\t\t\t\t\tresState.Dependencies = append(resState.Dependencies, dep.String())\n\t\t\t\t\t}\n\n\t\t\t\t\t// convert the indexes to the old style flapmap indexes\n\t\t\t\t\tidx := \"\"\n\t\t\t\t\tswitch key.(type) {\n\t\t\t\t\tcase addrs.IntKey:\n\t\t\t\t\t\t// don't add numeric index values to resources with a count of 0\n\t\t\t\t\t\tif len(res.Instances) > 1 {\n\t\t\t\t\t\t\tidx = fmt.Sprintf(\".%d\", key)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase addrs.StringKey:\n\t\t\t\t\t\tidx = \".\" + key.String()\n\t\t\t\t\t}\n\n\t\t\t\t\tmod.Resources[res.Addr.String()+idx] = resState\n\t\t\t\t}\n\n\t\t\t\t// add any deposed instances\n\t\t\t\tfor _, dep := range i.Deposed {\n\t\t\t\t\tflatmap, err := shimmedAttributes(dep, resource)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, fmt.Errorf(\"error decoding deposed state for %q: %s\", resType, err)\n\t\t\t\t\t}\n\n\t\t\t\t\tvar meta map[string]interface{}\n\t\t\t\t\tif dep.Private != nil {\n\t\t\t\t\t\terr := json.Unmarshal(dep.Private, &meta)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tdeposed := &terraform.InstanceState{\n\t\t\t\t\t\tID: flatmap[\"id\"],\n\t\t\t\t\t\tAttributes: flatmap,\n\t\t\t\t\t\tTainted: dep.Status == states.ObjectTainted,\n\t\t\t\t\t\tMeta: meta,\n\t\t\t\t\t}\n\t\t\t\t\tif dep.SchemaVersion != 0 {\n\t\t\t\t\t\tdeposed.Meta = map[string]interface{}{\n\t\t\t\t\t\t\t\"schema_version\": dep.SchemaVersion,\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tresState.Deposed = append(resState.Deposed, deposed)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn state, nil\n}", "func (o InstanceOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (o InstanceOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (r *IntCode) State() []int { return r.prog }", "func State(v string) predicate.Location {\n\treturn predicate.Location(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldState), v))\n\t})\n}" ]
[ "0.65877527", "0.6180703", "0.6148023", "0.6133315", "0.60690695", "0.59770316", "0.59733754", "0.59265506", "0.58425134", "0.5837373", "0.58263826", "0.582111", "0.5804677", "0.57588863", "0.5746426", "0.57335806", "0.57323164", "0.57227176", "0.5702326", "0.569178", "0.56649905", "0.56559944", "0.56450886", "0.56447506", "0.56178814", "0.561112", "0.5609967", "0.5587706", "0.5582593", "0.5580899", "0.5569522", "0.5566871", "0.55588645", "0.5543336", "0.5542898", "0.55427164", "0.55205876", "0.5517886", "0.55116177", "0.5507643", "0.55067676", "0.55038816", "0.54940826", "0.5492507", "0.5490614", "0.54786855", "0.5473828", "0.54707295", "0.54618025", "0.5456872", "0.5451649", "0.5450847", "0.5449954", "0.5448853", "0.54371554", "0.5437129", "0.5430924", "0.54305476", "0.54224443", "0.54210556", "0.5411332", "0.5411332", "0.5409972", "0.540748", "0.5407338", "0.53977543", "0.5387281", "0.53657705", "0.5365521", "0.5356288", "0.5350091", "0.5348384", "0.53431994", "0.5343118", "0.5334578", "0.53274393", "0.53270006", "0.53211665", "0.5320864", "0.53056806", "0.5301529", "0.52987826", "0.52987593", "0.5298344", "0.5291727", "0.5289128", "0.5288338", "0.5279696", "0.52729166", "0.5272763", "0.52718544", "0.52691364", "0.52683693", "0.5267029", "0.5263582", "0.52576846", "0.5256676", "0.5256676", "0.52557176", "0.5255481" ]
0.6671592
0
IncBatch beats the occurrence of a new batch.
func (o *RAdam[_]) IncBatch() { o.TimeStep++ }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *GradientDescent) IncBatch() {\n\tif method, ok := o.method.(BatchScheduler); ok {\n\t\tmethod.IncBatch()\n\t}\n}", "func (_m *CIPDClient) BeginBatch(ctx context.Context) {\n\t_m.Called(ctx)\n}", "func (gc *GroupCounter) Inc() {\n\tfor _, c := range gc.counters {\n\t\tc.Inc()\n\t}\n}", "func (c *Context) Incr(stat string) {\n\tfor _, sink := range c.sinks {\n\t\tsink.Count(c, stat, 1)\n\t}\n}", "func (s *Sparse) inc(start uint, dx int32) {\n\tfor i := start + 1; i < uint(len(s.count)); i++ {\n\t\ts.count[i] += dx\n\t}\n}", "func (nsc *NilConsumerStatsCollector) UpdateBatchSize(int) {}", "func (s *DevStat) CounterInc(id DevStatType, n int64) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\ts.Counters[id] = s.Counters[id].(int) + int(n)\n}", "func (_e *AcknowledgeableInput_Expecter) AckBatch(ctx interface{}, msgs interface{}, acks interface{}) *AcknowledgeableInput_AckBatch_Call {\n\treturn &AcknowledgeableInput_AckBatch_Call{Call: _e.mock.On(\"AckBatch\", ctx, msgs, acks)}\n}", "func Increment(\n\tctx context.Context, batch engine.ReadWriter, cArgs CommandArgs, resp roachpb.Response,\n) (result.Result, error) {\n\targs := cArgs.Args.(*roachpb.IncrementRequest)\n\th := cArgs.Header\n\treply := resp.(*roachpb.IncrementResponse)\n\n\tnewVal, err := engine.MVCCIncrement(ctx, batch, cArgs.Stats, args.Key, h.Timestamp, h.Txn, args.Increment)\n\treply.NewValue = newVal\n\treturn result.Result{}, err\n}", "func (c *Client) Increment(stat string, count int, rate float64) error {\n\treturn c.send(stat, rate, \"%d|c\", count)\n}", "func (a *Counter) IncEachTransaction() {\n\ta.mu.Lock()\n\tt := time.Now().Format(\"2006-01-02T15\")\n\tcnt := a.resendTransactionCount[t]\n\tcnt.TransactionsSend += 1\n\ta.resendTransactionCount[t] = cnt\n\ta.mu.Unlock()\n}", "func (tr *traverser) Inc() {\n\ttr.idx++\n\tif tr.ConsumedAll() {\n\t\ttr.SetDone()\n\t}\n}", "func (c *standardResettingCounter) Inc(i int64) {\n\tatomic.AddInt64(&c.count, i)\n}", "func (dsc *DefaultConsumerStatsCollector) UpdateBatchSize(count int) {\n\tdsc.BatchSize.Update(int64(count))\n}", "func (lms *MessageSorter) PushBatch(logMessageBatch []*ktail.LogMessage) bool {\n\tlms.cache = append(lms.cache, logMessageBatch...)\n\treturn lms.flushCheck()\n}", "func Incr(stat string, count int64, tagsInput map[string]string) {\n\tif on {\n\t\tstdClient.Incr(stat, count, convertTags(tagsInput)...)\n\t}\n}", "func (g *Gorc) Inc() {\n\tg.Lock()\n\tg.count++\n\tg.Unlock()\n}", "func (c *Stats) Increment(name string, tags []string) {\n\tc.Count(name, 1, tags)\n}", "func (zp *ZPackIns) StartBatch(dt int64) {\n\tzp.startBatch(dt)\n}", "func (c *ConcurrencyLimiter) Increment() {\n\tr := make(chan struct{})\n\tc.inc <- r\n\t<-r\n}", "func (c *StandardCounter) Inc(i int64) {\n\tatomic.AddInt64(&c.count, i)\n}", "func (c *StandardCounter) Inc(i int64) {\n\tatomic.AddInt64(&c.count, i)\n}", "func (c *StandardCounter) Inc(i int64) {\n\tatomic.AddInt64(&c.count, i)\n}", "func (s serverImpl) nextBatchInClass(ctx types.Context, classInfo *ecocredit.ClassInfo) (uint64, error) {\n\t// Get the next value\n\tnextVal := classInfo.NumBatches + 1\n\n\t// Update the ClassInfo\n\tclassInfo.NumBatches = nextVal\n\terr := s.classInfoTable.Update(ctx, classInfo)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn nextVal, nil\n}", "func (r *PendingPodsRecorder) Inc() {\n\tr.recorder.Inc()\n}", "func (s *CacheServer) Increment(ctx context.Context, in *pb.CacheRequest) (*pb.CacheResponse, error) {\n\tin.Operation = pb.CacheRequest_INCREMENT\n\treturn s.Call(ctx, in)\n}", "func Increment(path string, val float32) {\n\tmetrics.IncrCounter(strings.Split(path, \".\"), val)\n}", "func (t *testMetricsBackend) IncrementCounter(l metricsLabels) {\n\tt.Lock()\n\tt.counters[l]++\n\tt.Unlock()\n}", "func (b *FlushingBatch) Flush() error {\n\terr := b.index.Batch(b.batch)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.batch = b.index.NewBatch()\n\treturn nil\n}", "func (w *WeightsBatch) Update(id identity.ID, diff int64) {\n\tif w.diffs[id] += diff; w.diffs[id] == 0 {\n\t\tdelete(w.diffs, id)\n\t}\n\n\tw.totalDiff += diff\n}", "func (c *Context) Inc(ctr string) {\n\tvalue := c.counters[ctr].value\n\tc.counters[ctr] = change{\n\t\tvalue: value + 1,\n\t\tlast: time.Now(),\n\t}\n}", "func (th *Throttler) incrementCounter() {\n\tatomic.AddUint64(&th.counter, 1)\n}", "func (r *Repository) UpdateInBatch(db *gorm.DB, i interface{}, batchSize int) error {\n\treturn db.Omit(clause.Associations).CreateInBatches(i, batchSize).Error\n}", "func (c *CPU6502) inc() uint8 {\n\tc.fetch()\n\tt := uint16(c.fetched) + 1\n\tc.write(c.addrAbs, uint8(t))\n\tc.setFlagZ(uint8(t))\n\tc.setFlagN(uint8(t))\n\treturn 0\n}", "func (o *GradientDescent) IncEpoch() {\n\tif method, ok := o.method.(EpochScheduler); ok {\n\t\tmethod.IncEpoch()\n\t}\n}", "func (s *Stats) Incr(stat string, count int64, tags ...Tag) {\n\tif 0 != count {\n\t\ts.trans.bufLock.Lock()\n\t\tlastLen := len(s.trans.buf)\n\n\t\ts.trans.buf = append(s.trans.buf, []byte(s.metricPrefix)...)\n\t\ts.trans.buf = append(s.trans.buf, []byte(stat)...)\n\t\tif s.trans.tagFormat.Placement == TagPlacementName {\n\t\t\ts.trans.buf = s.formatTags(s.trans.buf, tags)\n\t\t}\n\t\ts.trans.buf = append(s.trans.buf, ':')\n\t\ts.trans.buf = strconv.AppendInt(s.trans.buf, count, 10)\n\t\ts.trans.buf = append(s.trans.buf, []byte(\"|c\")...)\n\t\tif s.trans.tagFormat.Placement == TagPlacementSuffix {\n\t\t\ts.trans.buf = s.formatTags(s.trans.buf, tags)\n\t\t}\n\t\ts.trans.buf = append(s.trans.buf, '\\n')\n\n\t\ts.trans.checkBuf(lastLen)\n\t\ts.trans.bufLock.Unlock()\n\t}\n}", "func (r *Reporter) Increment(key string) {\n\tswitch key {\n\tcase \"read.fail\":\n\t\tatomic.AddInt64(&r.readFail, 1)\n\tcase \"read.success\":\n\t\tatomic.AddInt64(&r.readSuccess, 1)\n\tcase \"write.fail\":\n\t\tatomic.AddInt64(&r.writeFail, 1)\n\tcase \"write.success\":\n\t\tatomic.AddInt64(&r.writeSuccess, 1)\n\t}\n}", "func (g *Gorc) IncBy(b int) {\n\tg.Lock()\n\tg.count += b\n\tg.Unlock()\n}", "func (b *buffer) inc(n int) {\n\tb.offset += n\n}", "func (f *File) AddBatch(batch Batcher) []Batcher {\n\tf.Batches = append(f.Batches, batch)\n\treturn f.Batches\n}", "func RecordBatch(ctx context.Context, labels LabelSet, batch ...Measurement) {\n\tGlobalMeter().RecordBatch(ctx, labels, batch...)\n}", "func (g *GaugeInt64) Inc(i int64) {\n\tatomic.AddInt64(&g.val, i)\n}", "func (self *scroll) Increment() {\n\tself.offset++\n}", "func (t *limiter) Increment(count int) {\n\tt.count += int64(count)\n}", "func (s *syncMapInt64) inc(key int) {\n\ts.Lock()\n\ts.m[key]++\n\ts.Unlock()\n}", "func (u *Update) Inc(obj types.M) *Update {\n\tu.update[\"$inc\"] = obj\n\treturn u\n}", "func (buf *Buffer) Flush(now time.Time) {\n\tbatch := buf.currentBatch\n\tif batch == nil {\n\t\treturn\n\t}\n\n\tbatch.nextSend = now // immediately make available to send\n\tbuf.unleased.PushBatch(batch)\n\tbuf.batchItemsGuess.record(batch.countedItems)\n\tbuf.currentBatch = nil\n\treturn\n}", "func inc(i int, c chan int) {\n\tcount := 0\n\tfor ; count < 10; count++ {\n\t\tfmt.Println(\"int is now \", i)\n\t\tc <- i + 1 // <- is the \"send\" operator when a channel appears on the left.\n\t}\n}", "func (c *Consumer) enqueueBatch(ctx context.Context) error {\n\terr := c.reader.GetRecords(ctx,\n\t\tfunc(msg *Message) error {\n\t\t\tc.messages <- msg\n\t\t\treturn nil\n\t\t})\n\tif err != nil {\n\t\tc.handleErrorLogging(err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (_m *Reporter) Increment(name string, tags ...monitoring.Tag) {\n\t_va := make([]interface{}, len(tags))\n\tfor _i := range tags {\n\t\t_va[_i] = tags[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, name)\n\t_ca = append(_ca, _va...)\n\t_m.Called(_ca...)\n}", "func (c *Counter) IncrBy(nlines, nbytes int, active float64) {\n\tc.cur += nlines\n\tc.curBytes += nbytes\n\tc.curActiveSecs += active\n\tc.pRecords.Add(float64(nlines))\n\tc.pBytes.Add(float64(nbytes))\n\tc.pActiveSecs.Add(active)\n}", "func (r *Transformer) addToBatch(_ context.Context, e *entry.Entry, source string) {\n\tbatch, ok := r.batchMap[source]\n\tif !ok {\n\t\tbatch = r.addNewBatch(source, e)\n\t\tif len(r.batchMap) >= r.maxSources {\n\t\t\tr.Error(\"Batched source exceeds max source size. Flushing all batched logs. Consider increasing max_sources parameter\")\n\t\t\tr.flushUncombined(context.Background())\n\t\t\treturn\n\t\t}\n\t} else {\n\t\t// If the length of the batch is 0, this batch was flushed previously due to triggering size limit.\n\t\t// In this case, the firstEntryObservedTime should be updated to reset the timeout\n\t\tif len(batch.entries) == 0 {\n\t\t\tbatch.firstEntryObservedTime = e.ObservedTimestamp\n\t\t}\n\t\tbatch.entries = append(batch.entries, e)\n\t}\n\n\t// Combine the combineField of each entry in the batch,\n\t// separated by newlines\n\tvar s string\n\terr := e.Read(r.combineField, &s)\n\tif err != nil {\n\t\tr.Errorf(\"entry does not contain the combine_field\")\n\t\treturn\n\t}\n\tif batch.recombined.Len() > 0 {\n\t\tbatch.recombined.WriteString(r.combineWith)\n\t}\n\tbatch.recombined.WriteString(s)\n\n\tif (r.maxLogSize > 0 && int64(batch.recombined.Len()) > r.maxLogSize) || len(batch.entries) >= r.maxBatchSize {\n\t\tif err := r.flushSource(source, false); err != nil {\n\t\t\tr.Errorf(\"there was error flushing combined logs %s\", err)\n\t\t}\n\t}\n\n}", "func (ob *OrderBook) BatchUpdate() {\n\n}", "func (zp *ZPackIns) CommitBatch(olabels []string) {\n\tzp.commitBatch(olabels)\n}", "func (self *Cache) InsertBatch(keys []interface{}, values []interface{}, sizesBytes []uint64) int {\n\tif len(keys) != len(values) {\n\t\tpanic(fmt.Sprintf(\"keys and values are not the same len. %d keys, %d values\", len(keys), len(values)))\n\t}\n\tvalues = values[:len(keys)]\n\tself.insertLock.Lock()\n\tdefer self.insertLock.Unlock()\n\n\tfor idx := range keys {\n\t\tvar inserted bool\n\t\tkeys[idx], values[idx], inserted = self.insert(keys[idx], values[idx], sizesBytes[idx])\n\t\tif !inserted {\n\t\t\treturn idx\n\t\t}\n\t}\n\treturn len(keys)\n}", "func (r *Range) Increment(args *IncrementRequest, reply *IncrementResponse) {\n\treply.NewValue, reply.Error = increment(r.engine, args.Key, args.Increment, args.Timestamp)\n}", "func (s *InMemoryDocumentSessionOperations) IncrementRequestCount() error {\n\ts.numberOfRequests++\n\tif s.numberOfRequests > s.maxNumberOfRequestsPerSession {\n\t\treturn NewIllegalStateException(\"exceeded max number of reqeusts per session of %d\", s.maxNumberOfRequestsPerSession)\n\t}\n\treturn nil\n}", "func (c *Counter) Inc() {\n\tc.Lock()\n\tc.counter++\n\tc.Unlock()\n}", "func instrumentBatchOp(ctx context.Context, opName string, op func(context.Context) ([]Result, error)) ([]Result, error) {\n\tnewCtx, err := tag.New(ctx, tag.Insert(ocmemcache.OperationKey, opName))\n\tif err != nil {\n\t\tnewCtx = ctx\n\t}\n\n\tstartTime := time.Now()\n\tresults, err := op(newCtx)\n\tduration := float64(time.Since(startTime)) / float64(time.Millisecond)\n\n\tstats.Record(newCtx, ocmemcache.CacheOperationLatencyMetric.M(duration))\n\tif err != nil {\n\t\tstats.Record(newCtx, ocmemcache.CacheOperationFailureMetric.M(1))\n\t} else {\n\t\tstats.Record(newCtx, ocmemcache.CacheOperationSuccessMetric.M(1))\n\t}\n\n\treturn results, err\n}", "func Increment(name string) {\n\tmn := getWithNamespace(name)\n\tc := metrics.GetOrRegisterCounter(mn, nil)\n\tc.Inc(1)\n\tdebug(\"increment \" + name + \" 1\")\n}", "func (u *Update) Inc(obj utils.M) *Update {\n\tu.update[\"$inc\"] = obj\n\treturn u\n}", "func (sc *slidingCounter) Increment(i float64) {\n\tif i == 0 {\n\t\treturn\n\t}\n\tsc.mutex.RLock()\n\tdefer sc.mutex.RUnlock()\n\n\tw := sc.getCurrentWindow()\n\tw.Value += i\n\tsc.removeOldWindows()\n}", "func (cpu *Mos6502) inc() uint8 {\n\tcpu.fetch()\n\tcpu.temp = word(cpu.fetchedData) + 1\n\tcpu.write(cpu.addressAbsolute, byte(cpu.temp&0x00ff))\n\tcpu.setStatusFlag(Z, (cpu.temp&0x00ff) == 0x0000)\n\tcpu.setStatusFlag(N, (cpu.temp&0x80) > 0)\n\treturn 0\n}", "func (batch *Batch) Commit() {\n\tbatch.mutex.Lock()\n\tdefer batch.mutex.Unlock()\n\n\tfor i, msg := range batch.messages {\n\t\tif i < len(batch.messages)-1 {\n\t\t\tmsg.Mark() // mark all messages\n\t\t\tcontinue\n\t\t}\n\t\tmsg.Commit() // commit last one (will commit all marked offsets as consumed)\n\t}\n}", "func (f *framework) IncEpoch(ctx context.Context) {\n\tepoch, ok := ctx.Value(epochKey).(uint64)\n\tif !ok {\n\t\tf.log.Fatalf(\"Can not find epochKey in IncEpoch\")\n\t}\n\terr := etcdutil.CASEpoch(f.etcdClient, f.name, epoch, epoch+1)\n\tif err != nil {\n\t\tf.log.Fatalf(\"task %d Epoch CompareAndSwap(%d, %d) failed: %v\",\n\t\t\tf.taskID, epoch+1, epoch, err)\n\t}\n}", "func (b *BatchBuffer) Add(batch coldata.Batch, _ []*types.T) {\n\tb.buffer = append(b.buffer, batch)\n}", "func (b *BadgerDBStore) PutBatch(batch Batch) error {\n\tdefer batch.(*BadgerDBBatch).batch.Cancel()\n\treturn batch.(*BadgerDBBatch).batch.Flush()\n}", "func (q *UniqueQueue) inc(idx int) int {\n\treturn (idx + 1) % (q.maxDepth + 1)\n}", "func (counter *Counter) Increment() {\n\tcounter.count.Set(counter.count.Get().Int() + 1)\n}", "func (s *DogStatsdSink) IncrCounter(key []string, val float32, tags []Tag) {\n\tflatKey, t := s.getFlatkeyAndCombinedLabels(key, tags)\n\trate := 1.0\n\ts.client.Count(flatKey, int64(val), t, rate)\n}", "func incrInterceptedRequestStatDelta() {\n\tStatMu.Mutex.Lock()\n\n\t// increment the requests counter\n\t*(StatMu.InstanceStat.InterceptedRequests) = *(StatMu.InstanceStat.InterceptedRequests) + uint64(1)\n\tStatMu.Mutex.Unlock()\n\n}", "func (p *ProgressUpdateBatcher) Add(ctx context.Context, delta float32) error {\n\tp.Lock()\n\tp.completed += delta\n\tcompleted := p.completed\n\tshouldReport := p.completed-p.reported > progressFractionThreshold\n\tshouldReport = shouldReport && p.lastReported.Add(progressTimeThreshold).Before(timeutil.Now())\n\n\tif shouldReport {\n\t\tp.reported = p.completed\n\t\tp.lastReported = timeutil.Now()\n\t}\n\tp.Unlock()\n\n\tif shouldReport {\n\t\treturn p.Report(ctx, completed)\n\t}\n\treturn nil\n}", "func (s BoltStore) BatchUpdate(ids []interface{}, data []interface{}, store string, opts ObjectStoreOptions) (err error) {\n\treturn ErrNotImplemented\n}", "func (c *Count) Increment(by int64) {\n\tc.µ.Lock()\n\tc.val += by\n\tc.µ.Unlock()\n}", "func (cm *CloudMetrics) IncrementAPIRequest() {\n\tcm.APIRequestsCounter.Inc()\n}", "func (counter *Counter) Inc() {\n\tcounter.mu.Lock()\n\tdefer counter.mu.Unlock()\n\tcounter.value++\n}", "func Increment(key Type, count int) {\n\tmutex.Lock()\n\tdefer mutex.Unlock()\n\n\tcountStats[key] = countStats[key] + count\n}", "func (t *Topic) SendBatch(ctx context.Context, iterator BatchIterator) error {\n\tctx, span := t.startSpanFromContext(ctx, \"sb.Topic.SendBatch\")\n\tdefer span.End()\n\n\terr := t.ensureSender(ctx)\n\tif err != nil {\n\t\ttab.For(ctx).Error(err)\n\t\treturn err\n\t}\n\n\tfor !iterator.Done() {\n\t\tid, err := uuid.NewV4()\n\t\tif err != nil {\n\t\t\ttab.For(ctx).Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\tbatch, err := iterator.Next(id.String(), &BatchOptions{\n\t\t\tSessionID: t.sender.sessionID,\n\t\t})\n\t\tif err != nil {\n\t\t\ttab.For(ctx).Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\tif err := t.sender.trySend(ctx, batch); err != nil {\n\t\t\ttab.For(ctx).Error(err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func BenchmarkBatchCTXAddendaCount(b *testing.B) {\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\ttestBatchCTXAddendaCount(b)\n\t}\n}", "func (c ShmCounter) Inc(i int64) {\n\tatomic.AddInt64((*int64)(unsafe.Pointer(c)), i)\n}", "func (d *Dao) AdditBatch(c context.Context, aids []int64) (sMap map[int64]*archive.Addit, err error) {\n\tsMap = make(map[int64]*archive.Addit)\n\tif len(aids) == 0 {\n\t\treturn\n\t}\n\trows, err := d.rddb.Query(c, fmt.Sprintf(_additBatch, xstr.JoinInts(aids)))\n\tif err != nil {\n\t\tlog.Error(\"db.Query() error(%v)\", err)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tad := &archive.Addit{}\n\t\tif err = rows.Scan(&ad.Aid, &ad.MissionID, &ad.FromIP, &ad.UpFrom, &ad.RecheckReason, &ad.RedirectURL, &ad.Source, &ad.OrderID, &ad.DescFormatID, &ad.Dynamic, &ad.InnerAttr); err != nil {\n\t\t\tlog.Error(\"rows.Scan error(%v)\", err)\n\t\t\treturn\n\t\t}\n\t\tsMap[ad.Aid] = ad\n\t}\n\treturn\n}", "func PutBatch(c *gin.Context) {\n\tvar batch map[string]interface{}\n\tstore := c.MustGet(\"store\").(*Store)\n\ttxn, have_txn := c.Get(\"NewRelicTransaction\")\n\n\terr := c.ShouldBindJSON(&batch)\n\tif err != nil {\n\t\tif have_txn {\n\t\t\ttxn.(newrelic.Transaction).NoticeError(err)\n\t\t}\n\t\tc.JSON(http.StatusUnprocessableEntity, \"\")\n\t\treturn\n\t}\n\n\tfor k, v := range batch {\n\t\tstore.Set(k, v)\n\t}\n\n\tc.JSON(http.StatusNoContent, nil)\n}", "func BenchmarkBatchXCKAddendaCount(b *testing.B) {\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\ttestBatchXCKAddendaCount(b)\n\t}\n}", "func (cc Counter) Inc(c RGB) {\n\ti := cc[c]\n\tcc[c] = i + 1\n}", "func (c *Counter) Inc() {\n\tc.Add(1)\n}", "func (c *Counter) Increment(addend int64) {\n\tatomic.AddInt64(&c.value, addend)\n}", "func (c *PCPCounterVector) Inc(inc int64, instance string) error {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\tif inc < 0 {\n\t\treturn errors.New(\"increment cannot be negative\")\n\t}\n\n\tif inc == 0 {\n\t\treturn nil\n\t}\n\n\tv, err := c.valInstance(instance)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.setInstance(v.(int64)+inc, instance)\n}", "func (_m *AcknowledgeableInput) AckBatch(ctx context.Context, msgs []*stream.Message, acks []bool) error {\n\tret := _m.Called(ctx, msgs, acks)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, []*stream.Message, []bool) error); ok {\n\t\tr0 = rf(ctx, msgs, acks)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (be InmemBackend) Increment(key []byte, value int, create_if_not_exists bool) (int, error) {\n\treturn 0, nil\n}", "func (c *LoggerClient) Incr(name string) {\n\tc.Count(name, 1)\n}", "func incrCounter(id int) {\n\t//* Schedule the call to Done to tell main we are done\n\tdefer wgs.Done()\n\n\tfor count := 0; count < 2; count++ {\n\t\t//* Only allow one goroutine thru this critical section at a time\n\t\tmutex.Lock()\n\t\t//* the curly braces below are not necessary\n\t\t{\n\t\t\t//* Capture the value of counter\n\t\t\tvalue := counters\n\n\t\t\t//* Yield the thread and be placed back in queue\n\t\t\truntime.Gosched()\n\n\t\t\t//* Increment our local value of counter\n\t\t\tvalue++\n\n\t\t\t//* Store the value back into counter\n\t\t\tcounters = value\n\t\t}\n\t\tmutex.Unlock()\n\t\t//* Release the lock and allow any waiting goroutine through\n\t}\n}", "func IncrementCounter(ctx context.Context, metric string) {\n\t// The field name we use is the specified metric name prepended with FieldnamePrefixCounter to designate that it is a Prometheus counter metric\n\t// The collector will replace that prefix with \"fn_\" and use the result as the Prometheus metric name.\n\tfieldname := FieldnamePrefixCounter + metric\n\n\t// Spans are not processed by the collector until the span ends, so to prevent any delay\n\t// in processing the stats when the current span is long-lived we create a new span for every call.\n\t// suffix the span name with SpannameSuffixDummy to denote that it is used only to hold a metric and isn't itself of any interest\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, fieldname+SpannameSuffixDummy)\n\tdefer span.Finish()\n\n\t// counter metrics are actually float64; here we log that it should be increased by +1\n\tspan.LogFields(log.Float64(fieldname, 1.))\n}", "func (p *PromCounter) Incr(count int64) error {\n\tp.ctr.Add(float64(count))\n\treturn nil\n}", "func (e *expiringCounter) Inc() {\n\te.Counter.Inc()\n\te.lastModSec = time.Now().Unix()\n}", "func (c *Counter) Increment() { c.n++ }", "func (w *batchWriter) Flush(ctx context.Context) error {\n\tfor i, s := range w.batch {\n\t\t_, err := fmt.Fprintln(w.writer, s)\n\t\tif err != nil {\n\t\t\tw.batch = w.batch[i:]\n\t\t\tw.persistRecords = w.persistRecords[i:]\n\t\t\treturn err\n\t\t}\n\t\tw.flushed = w.persistRecords[i]\n\t}\n\tw.batch = make([]string, 0, batchSize)\n\tw.persistRecords = make([]*persistRecord, 0, batchSize)\n\treturn nil\n}", "func IncCounter(id int) {\n\tfor count := 0; count < 2; count++ {\n\t // Only allow one goroutine through this\n\t // critical section at a time.\n\t Mutex.Lock()\n\n\t\t// Capture the value of Counter.\n\t\tvalue := Counter\n\n\t\t// Yield the processor.\n\t\truntime.Gosched()\n\n\t\t// Increment our local value of counter.\n\t\tvalue++\n\n\t\t// Store the value back into counter.\n\t\tCounter = value\n\n\t\t// Release the lock and allow any\n\t\t// waiting goroutine through.\n\t\tMutex.Unlock()\n\t}\n}", "func (s *simplePromCounter) Inc() {\n\ts.c.Inc()\n}", "func (c *GormClient) IncRetryCount(j *jobinator.Job) error {\n\terr := c.db.Model(j).Update(\"retry_count\", gorm.Expr(\"retry_count + ?\", 1)).Error\n\tj.RetryCount++\n\treturn err\n}", "func (mr *MockDBStorageMockRecorder) UpdateBatch(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateBatch\", reflect.TypeOf((*MockDBStorage)(nil).UpdateBatch), arg0)\n}" ]
[ "0.7910186", "0.64050967", "0.60608524", "0.5977938", "0.5911247", "0.58961546", "0.58816797", "0.5844141", "0.5826906", "0.58016104", "0.5800821", "0.5772292", "0.57602835", "0.5751012", "0.57464874", "0.5726118", "0.5638479", "0.55962133", "0.5593387", "0.55929357", "0.5574744", "0.5574744", "0.5574744", "0.5567138", "0.55504644", "0.5537389", "0.5536458", "0.5532832", "0.55124867", "0.5492852", "0.54858565", "0.54632735", "0.5458942", "0.54381335", "0.543419", "0.54327315", "0.54218906", "0.54069865", "0.538953", "0.5373585", "0.5352822", "0.534993", "0.5340407", "0.5337246", "0.53353703", "0.5334633", "0.53224635", "0.53087515", "0.5304527", "0.5302802", "0.5302323", "0.52980745", "0.5276248", "0.5260346", "0.5249084", "0.5245563", "0.5244903", "0.523274", "0.52271664", "0.5221951", "0.5221012", "0.5213781", "0.52044284", "0.5200927", "0.5200306", "0.5196232", "0.5192543", "0.51918274", "0.51852345", "0.5175339", "0.5169528", "0.51694965", "0.51649636", "0.51597273", "0.5157376", "0.51519334", "0.5146576", "0.5140655", "0.5132788", "0.51300526", "0.51272476", "0.51155263", "0.5111561", "0.51083004", "0.51077795", "0.51070493", "0.5105208", "0.51002324", "0.5099089", "0.50988877", "0.5098709", "0.5091537", "0.50848466", "0.50795233", "0.5078052", "0.5068587", "0.50594866", "0.5044747", "0.5043497", "0.50347066" ]
0.7497945
1
m = mbeta1 + grads(1.0beta1)
func updateM(grads mat.Matrix, state *State, beta1 float64) { state.M.ProdScalarInPlace(beta1) state.Buf1.ProdMatrixScalarInPlace(grads, 1.0-beta1) state.M.AddInPlace(state.Buf1) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getBeta(fAlpha, fBeta float64) float64 {\n\tvar fA, fB float64\n\tif fAlpha > fBeta {\n\t\tfA = fAlpha\n\t\tfB = fBeta\n\t} else {\n\t\tfA = fBeta\n\t\tfB = fAlpha\n\t}\n\tconst maxGammaArgument = 171.624376956302\n\tif fA+fB < maxGammaArgument {\n\t\treturn math.Gamma(fA) / math.Gamma(fA+fB) * math.Gamma(fB)\n\t}\n\tfg := 6.024680040776729583740234375\n\tfgm := fg - 0.5\n\tfLanczos := getLanczosSum(fA)\n\tfLanczos /= getLanczosSum(fA + fB)\n\tfLanczos *= getLanczosSum(fB)\n\tfABgm := fA + fB + fgm\n\tfLanczos *= math.Sqrt((fABgm / (fA + fgm)) / (fB + fgm))\n\tfTempA := fB / (fA + fgm)\n\tfTempB := fA / (fB + fgm)\n\tfResult := math.Exp(-fA*math.Log1p(fTempA) - fB*math.Log1p(fTempB) - fgm)\n\tfResult *= fLanczos\n\treturn fResult\n}", "func Gemm(tA, tB blas.Transpose, alpha complex128, a, b General, beta complex128, c General) {\n\tvar m, n, k int\n\tif tA == blas.NoTrans {\n\t\tm, k = a.Rows, a.Cols\n\t} else {\n\t\tm, k = a.Cols, a.Rows\n\t}\n\tif tB == blas.NoTrans {\n\t\tn = b.Cols\n\t} else {\n\t\tn = b.Rows\n\t}\n\tcblas128.Zgemm(tA, tB, m, n, k, alpha, a.Data, a.Stride, b.Data, b.Stride, beta, c.Data, c.Stride)\n}", "func (g *G1) Double() {\n\t// Reference:\n\t// \"Complete addition formulas for prime order elliptic curves\" by\n\t// Costello-Renes-Batina. [Alg.9] (eprint.iacr.org/2015/1060).\n\tvar R G1\n\tX, Y, Z := &g.x, &g.y, &g.z\n\tX3, Y3, Z3 := &R.x, &R.y, &R.z\n\tvar f0, f1, f2 ff.Fp\n\tt0, t1, t2 := &f0, &f1, &f2\n\t_3B := &g1Params._3b\n\tt0.Sqr(Y) // 1. t0 = Y * Y\n\tZ3.Add(t0, t0) // 2. Z3 = t0 + t0\n\tZ3.Add(Z3, Z3) // 3. Z3 = Z3 + Z3\n\tZ3.Add(Z3, Z3) // 4. Z3 = Z3 + Z3\n\tt1.Mul(Y, Z) // 5. t1 = Y * Z\n\tt2.Sqr(Z) // 6. t2 = Z * Z\n\tt2.Mul(_3B, t2) // 7. t2 = b3 * t2\n\tX3.Mul(t2, Z3) // 8. X3 = t2 * Z3\n\tY3.Add(t0, t2) // 9. Y3 = t0 + t2\n\tZ3.Mul(t1, Z3) // 10. Z3 = t1 * Z3\n\tt1.Add(t2, t2) // 11. t1 = t2 + t2\n\tt2.Add(t1, t2) // 12. t2 = t1 + t2\n\tt0.Sub(t0, t2) // 13. t0 = t0 - t2\n\tY3.Mul(t0, Y3) // 14. Y3 = t0 * Y3\n\tY3.Add(X3, Y3) // 15. Y3 = X3 + Y3\n\tt1.Mul(X, Y) // 16. t1 = X * Y\n\tX3.Mul(t0, t1) // 17. X3 = t0 * t1\n\tX3.Add(X3, X3) // 18. X3 = X3 + X3\n\t*g = R\n}", "func pbeta(x, pin, qin float64) (ans float64) {\n\teps := d1mach(3)\n\talneps := math.Log(eps)\n\tsml := d1mach(1)\n\talnsml := math.Log(sml)\n\ty := x\n\tp := pin\n\tq := qin\n\tif p/(p+q) < x {\n\t\ty = 1.0 - y\n\t\tp = qin\n\t\tq = pin\n\t}\n\tif (p+q)*y/(p+1.0) < eps {\n\t\txb := p*math.Log(math.Max(y, sml)) - math.Log(p) - logBeta(p, q)\n\t\tif xb > alnsml && y != 0.0 {\n\t\t\tans = math.Exp(xb)\n\t\t}\n\t\tif y != x || p != pin {\n\t\t\tans = 1.0 - ans\n\t\t}\n\t} else {\n\t\tps := q - math.Floor(q)\n\t\tif ps == 0.0 {\n\t\t\tps = 1.0\n\t\t}\n\t\txb := p*math.Log(y) - logBeta(ps, p) - math.Log(p)\n\t\tif xb >= alnsml {\n\t\t\tans = math.Exp(xb)\n\t\t\tterm := ans * p\n\t\t\tif ps != 1.0 {\n\t\t\t\tn := int(math.Max(alneps/math.Log(y), 4.0))\n\t\t\t\tfor i := 1; i <= n; i++ {\n\t\t\t\t\txi := float64(i)\n\t\t\t\t\tterm = term * (xi - ps) * y / xi\n\t\t\t\t\tans = ans + term/(p+xi)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tans = pbetaRaw(alnsml, ans, eps, p, pin, q, sml, x, y)\n\t}\n\treturn ans\n}", "func (p *G1Jac) mulGLV(a *G1Jac, s *big.Int) *G1Jac {\n\n\tvar table [15]G1Jac\n\tvar res G1Jac\n\tvar k1, k2 fr.Element\n\n\tres.Set(&g1Infinity)\n\n\t// table[b3b2b1b0-1] = b3b2*phi(a) + b1b0*a\n\ttable[0].Set(a)\n\ttable[3].phi(a)\n\n\t// split the scalar, modifies +-a, phi(a) accordingly\n\tk := ecc.SplitScalar(s, &glvBasis)\n\n\tif k[0].Sign() == -1 {\n\t\tk[0].Neg(&k[0])\n\t\ttable[0].Neg(&table[0])\n\t}\n\tif k[1].Sign() == -1 {\n\t\tk[1].Neg(&k[1])\n\t\ttable[3].Neg(&table[3])\n\t}\n\n\t// precompute table (2 bits sliding window)\n\t// table[b3b2b1b0-1] = b3b2*phi(a) + b1b0*a if b3b2b1b0 != 0\n\ttable[1].Double(&table[0])\n\ttable[2].Set(&table[1]).AddAssign(&table[0])\n\ttable[4].Set(&table[3]).AddAssign(&table[0])\n\ttable[5].Set(&table[3]).AddAssign(&table[1])\n\ttable[6].Set(&table[3]).AddAssign(&table[2])\n\ttable[7].Double(&table[3])\n\ttable[8].Set(&table[7]).AddAssign(&table[0])\n\ttable[9].Set(&table[7]).AddAssign(&table[1])\n\ttable[10].Set(&table[7]).AddAssign(&table[2])\n\ttable[11].Set(&table[7]).AddAssign(&table[3])\n\ttable[12].Set(&table[11]).AddAssign(&table[0])\n\ttable[13].Set(&table[11]).AddAssign(&table[1])\n\ttable[14].Set(&table[11]).AddAssign(&table[2])\n\n\t// bounds on the lattice base vectors guarantee that k1, k2 are len(r)/2 bits long max\n\tk1.SetBigInt(&k[0]).FromMont()\n\tk2.SetBigInt(&k[1]).FromMont()\n\n\t// loop starts from len(k1)/2 due to the bounds\n\tfor i := int(math.Ceil(fr.Limbs/2. - 1)); i >= 0; i-- {\n\t\tmask := uint64(3) << 62\n\t\tfor j := 0; j < 32; j++ {\n\t\t\tres.Double(&res).Double(&res)\n\t\t\tb1 := (k1[i] & mask) >> (62 - 2*j)\n\t\t\tb2 := (k2[i] & mask) >> (62 - 2*j)\n\t\t\tif b1|b2 != 0 {\n\t\t\t\ts := (b2<<2 | b1)\n\t\t\t\tres.AddAssign(&table[s-1])\n\t\t\t}\n\t\t\tmask = mask >> 2\n\t\t}\n\t}\n\n\tp.Set(&res)\n\treturn p\n}", "func Dlagv2(a, b *mat.Matrix, alphar, alphai, beta *mat.Vector) (csl, snl, csr, snr float64) {\n\tvar anorm, ascale, bnorm, bscale, h1, h2, h3, one, qq, rr, safmin, scale1, ulp, wi, wr1, zero float64\n\n\tzero = 0.0\n\tone = 1.0\n\n\tsafmin = Dlamch(SafeMinimum)\n\tulp = Dlamch(Precision)\n\n\t// Scale A\n\tanorm = math.Max(math.Abs(a.Get(0, 0))+math.Abs(a.Get(1, 0)), math.Max(math.Abs(a.Get(0, 1))+math.Abs(a.Get(1, 1)), safmin))\n\tascale = one / anorm\n\ta.Set(0, 0, ascale*a.Get(0, 0))\n\ta.Set(0, 1, ascale*a.Get(0, 1))\n\ta.Set(1, 0, ascale*a.Get(1, 0))\n\ta.Set(1, 1, ascale*a.Get(1, 1))\n\n\t// Scale B\n\tbnorm = math.Max(math.Abs(b.Get(0, 0)), math.Max(math.Abs(b.Get(0, 1))+math.Abs(b.Get(1, 1)), safmin))\n\tbscale = one / bnorm\n\tb.Set(0, 0, bscale*b.Get(0, 0))\n\tb.Set(0, 1, bscale*b.Get(0, 1))\n\tb.Set(1, 1, bscale*b.Get(1, 1))\n\n\t// Check if A can be deflated\n\tif math.Abs(a.Get(1, 0)) <= ulp {\n\t\tcsl = one\n\t\tsnl = zero\n\t\tcsr = one\n\t\tsnr = zero\n\t\ta.Set(1, 0, zero)\n\t\tb.Set(1, 0, zero)\n\t\twi = zero\n\n\t\t// Check if B is singular\n\t} else if math.Abs(b.Get(0, 0)) <= ulp {\n\t\tcsl, snl, _ = Dlartg(a.Get(0, 0), a.Get(1, 0))\n\t\tcsr = one\n\t\tsnr = zero\n\t\ta.Off(1, 0).Vector().Rot(2, a.Off(0, 0).Vector(), a.Rows, a.Rows, csl, snl)\n\t\tb.Off(1, 0).Vector().Rot(2, b.Off(0, 0).Vector(), b.Rows, b.Rows, csl, snl)\n\t\ta.Set(1, 0, zero)\n\t\tb.Set(0, 0, zero)\n\t\tb.Set(1, 0, zero)\n\t\twi = zero\n\n\t} else if math.Abs(b.Get(1, 1)) <= ulp {\n\t\tcsr, snr, _ = Dlartg(a.Get(1, 1), a.Get(1, 0))\n\t\tsnr = -snr\n\t\ta.Off(0, 1).Vector().Rot(2, a.Off(0, 0).Vector(), 1, 1, csr, snr)\n\t\tb.Off(0, 1).Vector().Rot(2, b.Off(0, 0).Vector(), 1, 1, csr, snr)\n\t\tcsl = one\n\t\tsnl = zero\n\t\ta.Set(1, 0, zero)\n\t\tb.Set(1, 0, zero)\n\t\tb.Set(1, 1, zero)\n\t\twi = zero\n\n\t} else {\n\t\t// B is nonsingular, first compute the eigenvalues of (A,B)\n\t\tscale1, _, wr1, _, wi = Dlag2(a, b, safmin)\n\n\t\tif wi == zero {\n\t\t\t// two real eigenvalues, compute s*A-w*B\n\t\t\th1 = scale1*a.Get(0, 0) - wr1*b.Get(0, 0)\n\t\t\th2 = scale1*a.Get(0, 1) - wr1*b.Get(0, 1)\n\t\t\th3 = scale1*a.Get(1, 1) - wr1*b.Get(1, 1)\n\n\t\t\trr = Dlapy2(h1, h2)\n\t\t\tqq = Dlapy2(scale1*a.Get(1, 0), h3)\n\n\t\t\tif rr > qq {\n\t\t\t\t// find right rotation matrix to zero 1,1 element of\n\t\t\t\t// (sA - wB)\n\t\t\t\tcsr, snr, _ = Dlartg(h2, h1)\n\n\t\t\t} else {\n\t\t\t\t// find right rotation matrix to zero 2,1 element of\n\t\t\t\t// (sA - wB)\n\t\t\t\tcsr, snr, _ = Dlartg(h3, scale1*a.Get(1, 0))\n\n\t\t\t}\n\n\t\t\tsnr = -snr\n\t\t\ta.Off(0, 1).Vector().Rot(2, a.Off(0, 0).Vector(), 1, 1, csr, snr)\n\t\t\tb.Off(0, 1).Vector().Rot(2, b.Off(0, 0).Vector(), 1, 1, csr, snr)\n\n\t\t\t// compute inf norms of A and B\n\t\t\th1 = math.Max(math.Abs(a.Get(0, 0))+math.Abs(a.Get(0, 1)), math.Abs(a.Get(1, 0))+math.Abs(a.Get(1, 1)))\n\t\t\th2 = math.Max(math.Abs(b.Get(0, 0))+math.Abs(b.Get(0, 1)), math.Abs(b.Get(1, 0))+math.Abs(b.Get(1, 1)))\n\n\t\t\tif (scale1 * h1) >= math.Abs(wr1)*h2 {\n\t\t\t\t// find left rotation matrix Q to zero out B(2,1)\n\t\t\t\tcsl, snl, _ = Dlartg(b.Get(0, 0), b.Get(1, 0))\n\n\t\t\t} else {\n\t\t\t\t// find left rotation matrix Q to zero out A(2,1)\n\t\t\t\tcsl, snl, _ = Dlartg(a.Get(0, 0), a.Get(1, 0))\n\n\t\t\t}\n\n\t\t\ta.Off(1, 0).Vector().Rot(2, a.Off(0, 0).Vector(), a.Rows, a.Rows, csl, snl)\n\t\t\tb.Off(1, 0).Vector().Rot(2, b.Off(0, 0).Vector(), b.Rows, b.Rows, csl, snl)\n\n\t\t\ta.Set(1, 0, zero)\n\t\t\tb.Set(1, 0, zero)\n\n\t\t} else {\n\t\t\t// a pair of complex conjugate eigenvalues\n\t\t\t// first compute the SVD of the matrix B\n\t\t\t_, _, snr, csr, snl, csl = Dlasv2(b.Get(0, 0), b.Get(0, 1), b.Get(1, 1))\n\n\t\t\t// Form (A,B) := Q(A,B)Z**T where Q is left rotation matrix and\n\t\t\t// Z is right rotation matrix computed from DLASV2\n\t\t\ta.Off(1, 0).Vector().Rot(2, a.Off(0, 0).Vector(), a.Rows, a.Rows, csl, snl)\n\t\t\tb.Off(1, 0).Vector().Rot(2, b.Off(0, 0).Vector(), b.Rows, b.Rows, csl, snl)\n\t\t\ta.Off(0, 1).Vector().Rot(2, a.Off(0, 0).Vector(), 1, 1, csr, snr)\n\t\t\tb.Off(0, 1).Vector().Rot(2, b.Off(0, 0).Vector(), 1, 1, csr, snr)\n\n\t\t\tb.Set(1, 0, zero)\n\t\t\tb.Set(0, 1, zero)\n\n\t\t}\n\n\t}\n\n\t// Unscaling\n\ta.Set(0, 0, anorm*a.Get(0, 0))\n\ta.Set(1, 0, anorm*a.Get(1, 0))\n\ta.Set(0, 1, anorm*a.Get(0, 1))\n\ta.Set(1, 1, anorm*a.Get(1, 1))\n\tb.Set(0, 0, bnorm*b.Get(0, 0))\n\tb.Set(1, 0, bnorm*b.Get(1, 0))\n\tb.Set(0, 1, bnorm*b.Get(0, 1))\n\tb.Set(1, 1, bnorm*b.Get(1, 1))\n\n\tif wi == zero {\n\t\talphar.Set(0, a.Get(0, 0))\n\t\talphar.Set(1, a.Get(1, 1))\n\t\talphai.Set(0, zero)\n\t\talphai.Set(1, zero)\n\t\tbeta.Set(0, b.Get(0, 0))\n\t\tbeta.Set(1, b.Get(1, 1))\n\t} else {\n\t\talphar.Set(0, anorm*wr1/scale1/bnorm)\n\t\talphai.Set(0, anorm*wi/scale1/bnorm)\n\t\talphar.Set(1, alphar.Get(0))\n\t\talphai.Set(1, -alphai.Get(0))\n\t\tbeta.Set(0, one)\n\t\tbeta.Set(1, one)\n\t}\n\n\treturn\n}", "func pbetaRaw(alnsml, ans, eps, p, pin, q, sml, x, y float64) float64 {\n\tif q > 1.0 {\n\t\txb := p*math.Log(y) + q*math.Log(1.0-y) - logBeta(p, q) - math.Log(q)\n\t\tib := int(math.Max(xb/alnsml, 0.0))\n\t\tterm := math.Exp(xb - float64(ib)*alnsml)\n\t\tc := 1.0 / (1.0 - y)\n\t\tp1 := q * c / (p + q - 1.0)\n\t\tfinsum := 0.0\n\t\tn := int(q)\n\t\tif q == float64(n) {\n\t\t\tn = n - 1\n\t\t}\n\t\tfor i := 1; i <= n; i++ {\n\t\t\tif p1 <= 1 && term/eps <= finsum {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\txi := float64(i)\n\t\t\tterm = (q - xi + 1.0) * c * term / (p + q - xi)\n\t\t\tif term > 1.0 {\n\t\t\t\tib = ib - 1\n\t\t\t\tterm = term * sml\n\t\t\t}\n\t\t\tif ib == 0 {\n\t\t\t\tfinsum = finsum + term\n\t\t\t}\n\t\t}\n\t\tans = ans + finsum\n\t}\n\tif y != x || p != pin {\n\t\tans = 1.0 - ans\n\t}\n\tans = math.Max(math.Min(ans, 1.0), 0.0)\n\treturn ans\n}", "func updateV(grads mat.Matrix, state *State, beta2 float64) {\n\tstate.V.ProdScalarInPlace(beta2)\n\tsqGrad := grads.Prod(grads)\n\tstate.Buf2.ProdMatrixScalarInPlace(sqGrad, 1.0-beta2)\n\tstate.V.AddInPlace(state.Buf2)\n}", "func blastrans(g1 blas64.General) blas64.General {\n\t// first the receiver\n\tg3 := blas64.General{\n\t\tRows: g1.Cols,\n\t\tCols: g1.Rows,\n\t\tStride: g1.Rows,\n\t\tData: make([]float64, g1.Rows*g1.Cols),\n\t}\n\tblas64.Gemm(blas.NoTrans, blas.Trans, 1.0, eye(g1.Cols), g1, 0.0, g3)\n\treturn g3\n}", "func blasmul(g1, g2 blas64.General) blas64.General {\n\t// first the receiver\n\tg3 := blas64.General{\n\t\tRows: g1.Rows,\n\t\tCols: g2.Cols,\n\t\tStride: g2.Stride,\n\t\tData: make([]float64, g1.Rows*g2.Stride),\n\t}\n\tblas64.Gemm(blas.NoTrans, blas.NoTrans, 1.0, g1, g2, 0.0, g3)\n\treturn g3\n}", "func (x Vector64) Madd(alpha float64, y Vector64) Vector64 {\n\tfor i := 0; i < len(x); i++ {\n\t\tx[i] += alpha * y[i]\n\t}\n\treturn x\n}", "func blasadd(g1, g2 blas64.General) blas64.General {\n\t// first make a copy of g1\n\tg3 := blas64.General{\n\t\tRows: g1.Rows,\n\t\tCols: g1.Cols,\n\t\tStride: g1.Stride,\n\t\tData: make([]float64, len(g1.Data)),\n\t}\n\tfor i, v := range g1.Data {\n\t\tg3.Data[i] = v\n\t}\n\tblas64.Gemm(blas.NoTrans, blas.NoTrans, 1.0, eye(g1.Rows), g2, 1.0, g3)\n\treturn g3\n}", "func logG(y, e, alpha, beta float64) float64 {\n\treturn lnΓ(alpha+y) - (y+alpha)*log(e+beta) + alpha*log(beta) - lnΓ(alpha)\n}", "func zgbt02(trans mat.MatTrans, m, n, kl, ku, nrhs int, a, x, b *mat.CMatrix) (resid float64) {\n\tvar cone complex128\n\tvar anorm, bnorm, eps, one, xnorm, zero float64\n\tvar i1, i2, j, kd, n1 int\n\tvar err error\n\n\tzero = 0.0\n\tone = 1.0\n\tcone = (1.0 + 0.0*1i)\n\t// Quick return if N = 0 pr NRHS = 0\n\tif m <= 0 || n <= 0 || nrhs <= 0 {\n\t\tresid = zero\n\t\treturn\n\t}\n\n\t// Exit with RESID = 1/EPS if ANORM = 0.\n\teps = golapack.Dlamch(Epsilon)\n\tkd = ku + 1\n\tanorm = zero\n\tfor j = 1; j <= n; j++ {\n\t\ti1 = max(kd+1-j, 1)\n\t\ti2 = min(kd+m-j, kl+kd)\n\t\tanorm = math.Max(anorm, a.Off(i1-1, j-1).CVector().Asum(i2-i1+1, 1))\n\t}\n\tif anorm <= zero {\n\t\tresid = one / eps\n\t\treturn\n\t}\n\n\tif trans == Trans || trans == ConjTrans {\n\t\tn1 = n\n\t} else {\n\t\tn1 = m\n\t}\n\n\t// Compute B - A*X (or B - A'*X )\n\tfor j = 1; j <= nrhs; j++ {\n\t\tif err = b.Off(0, j-1).CVector().Gbmv(trans, m, n, kl, ku, -cone, a, x.Off(0, j-1).CVector(), 1, cone, 1); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\t// Compute the maximum over the number of right hand sides of\n\t// norm(B - A*X) / ( norm(A) * norm(X) * EPS ).\n\tresid = zero\n\tfor j = 1; j <= nrhs; j++ {\n\t\tbnorm = b.Off(0, j-1).CVector().Asum(n1, 1)\n\t\txnorm = x.Off(0, j-1).CVector().Asum(n1, 1)\n\t\tif xnorm <= zero {\n\t\t\tresid = one / eps\n\t\t} else {\n\t\t\tresid = math.Max(resid, ((bnorm/anorm)/xnorm)/eps)\n\t\t}\n\t}\n\n\treturn\n}", "func gammainv(probability, alpha, beta float64) float64 {\n\txLo, xHi := 0.0, alpha*beta*5\n\tdx, x, xNew, result := 1024.0, 1.0, 1.0, 0.0\n\tfor i := 0; math.Abs(dx) > 8.88e-016 && i <= 256; i++ {\n\t\tresult = incompleteGamma(alpha, x/beta) / math.Gamma(alpha)\n\t\te := result - probability\n\t\tif e == 0 {\n\t\t\tdx = 0\n\t\t} else if e < 0 {\n\t\t\txLo = x\n\t\t} else {\n\t\t\txHi = x\n\t\t}\n\t\tpdf := (1 / (math.Pow(beta, alpha) * math.Gamma(alpha))) * math.Pow(x, alpha-1) * math.Exp(0-(x/beta))\n\t\tif pdf != 0 {\n\t\t\tdx = e / pdf\n\t\t\txNew = x - dx\n\t\t}\n\t\tif xNew < xLo || xNew > xHi || pdf == 0 {\n\t\t\txNew = (xLo + xHi) / 2\n\t\t\tdx = xNew - x\n\t\t}\n\t\tx = xNew\n\t}\n\treturn x\n}", "func getBetaDist(fXin, fAlpha, fBeta float64) float64 {\n\tif fXin <= 0 {\n\t\treturn 0\n\t}\n\tif fXin >= 1 {\n\t\treturn 1\n\t}\n\tif fBeta == 1 {\n\t\treturn math.Pow(fXin, fAlpha)\n\t}\n\tif fAlpha == 1 {\n\t\treturn -math.Expm1(fBeta * math.Log1p(-fXin))\n\t}\n\tvar fResult float64\n\tfY, flnY := (0.5-fXin)+0.5, math.Log1p(-fXin)\n\tfX, flnX := fXin, math.Log(fXin)\n\tfA, fB := fAlpha, fBeta\n\tbReflect := fXin > fAlpha/(fAlpha+fBeta)\n\tif bReflect {\n\t\tfA = fBeta\n\t\tfB = fAlpha\n\t\tfX = fY\n\t\tfY = fXin\n\t\tflnX = flnY\n\t\tflnY = math.Log(fXin)\n\t}\n\tfResult = getBetaHelperContFrac(fX, fA, fB) / fA\n\tfP, fQ := fA/(fA+fB), fB/(fA+fB)\n\tvar fTemp float64\n\tif fA > 1 && fB > 1 && fP < 0.97 && fQ < 0.97 {\n\t\tfTemp = getBetaDistPDF(fX, fA, fB) * fX * fY\n\t} else {\n\t\tfTemp = math.Exp(fA*flnX + fB*flnY - getLogBeta(fA, fB))\n\t}\n\tfResult *= fTemp\n\tif bReflect {\n\t\tfResult = 0.5 - fResult + 0.5\n\t}\n\treturn fResult\n}", "func opt1d(m1 RegFitter, coeff float64, par Parameter, l1wgt float64, checkstep bool) float64 {\n\n\t// Quadratic approximation coefficients\n\tbv := make([]float64, 1)\n\tpar.SetCoeff([]float64{coeff})\n\tm1.Score(par, bv)\n\tb := -bv[0]\n\tcv := make([]float64, 1)\n\tm1.Hessian(par, ObsHess, cv)\n\tc := -cv[0]\n\n\t// The optimum point of the quadratic approximation\n\td := b - c*coeff\n\n\tif l1wgt > math.Abs(d) {\n\t\t// The optimum is achieved by hard thresholding to zero\n\t\treturn 0\n\t}\n\n\t// pj + h is the minimizer of Q(x) + L1_wt*abs(x)\n\tvar h float64\n\tif d >= 0 {\n\t\th = (l1wgt - b) / c\n\t} else if d < 0 {\n\t\th = -(l1wgt + b) / c\n\t} else {\n\t\tpanic(fmt.Sprintf(\"d=%f\\n\", d))\n\t}\n\n\tif !checkstep {\n\t\treturn coeff + h\n\t}\n\n\t// Check whether the new point improves the target function.\n\t// This check is a bit expensive and not necessary for OLS\n\tpar.SetCoeff([]float64{coeff})\n\tf0 := -m1.LogLike(par, false) + l1wgt*math.Abs(coeff)\n\tpar.SetCoeff([]float64{coeff + h})\n\tf1 := -m1.LogLike(par, false) + l1wgt*math.Abs(coeff+h)\n\tif f1 <= f0+1e-10 {\n\t\treturn coeff + h\n\t}\n\n\t// Wrap the log-likelihood so it takes a scalar argument.\n\tfw := func(z float64) float64 {\n\t\tpar.SetCoeff([]float64{z})\n\t\tf := -m1.LogLike(par, false) + l1wgt*math.Abs(z)\n\t\treturn f\n\t}\n\n\t// Fallback for models where the loss is not quadratic\n\tw := 1.0\n\tbtol := 1e-7\n\tnp := bisection(fw, coeff-w, coeff+w, btol)\n\treturn np\n}", "func (o *Adam) Update(value, gradient float64, t, idx int) float64 {\n\tlrt := o.lr * (math.Sqrt(1.0 - math.Pow(o.beta2, float64(t)))) /\n\t\t(1.0 - math.Pow(o.beta, float64(t)))\n\to.m[idx] = o.beta*o.m[idx] + (1.0-o.beta)*gradient\n\to.v[idx] = o.beta2*o.v[idx] + (1.0-o.beta2)*math.Pow(gradient, 2.0)\n\n\treturn -lrt * (o.m[idx] / (math.Sqrt(o.v[idx]) + o.epsilon))\n}", "func Beta(a, b float64) float64 {\n\tla, sgnla := math.Lgamma(a)\n\tlb, sgnlb := math.Lgamma(b)\n\tlc, sgnlc := math.Lgamma(a + b)\n\treturn float64(sgnla*sgnlb*sgnlc) * math.Exp(la+lb-lc)\n}", "func getLogBeta(fAlpha, fBeta float64) float64 {\n\tvar fA, fB float64\n\tif fAlpha > fBeta {\n\t\tfA, fB = fAlpha, fBeta\n\t} else {\n\t\tfA, fB = fBeta, fAlpha\n\t}\n\tfg := 6.024680040776729583740234375\n\tfgm := fg - 0.5\n\tfLanczos := getLanczosSum(fA)\n\tfLanczos /= getLanczosSum(fA + fB)\n\tfLanczos *= getLanczosSum(fB)\n\tfLogLanczos := math.Log(fLanczos)\n\tfABgm := fA + fB + fgm\n\tfLogLanczos += 0.5 * (math.Log(fABgm) - math.Log(fA+fgm) - math.Log(fB+fgm))\n\tfTempA := fB / (fA + fgm)\n\tfTempB := fA / (fB + fgm)\n\tfResult := -fA*math.Log1p(fTempA) - fB*math.Log1p(fTempB) - fgm\n\tfResult += fLogLanczos\n\treturn fResult\n}", "func GmmProbability(input *mat.Dense, inputModel *gmm, param *GmmProbabilityOptionalParam) (*mat.Dense) {\n resetTimers()\n enableTimers()\n disableBacktrace()\n disableVerbose()\n restoreSettings(\"GMM Probability Calculator\")\n\n // Detect if the parameter was passed; set if so.\n gonumToArmaMat(\"input\", input)\n setPassed(\"input\")\n\n // Detect if the parameter was passed; set if so.\n setGMM(\"input_model\", inputModel)\n setPassed(\"input_model\")\n\n // Detect if the parameter was passed; set if so.\n if param.Verbose != false {\n setParamBool(\"verbose\", param.Verbose)\n setPassed(\"verbose\")\n enableVerbose()\n }\n\n // Mark all output options as passed.\n setPassed(\"output\")\n\n // Call the mlpack program.\n C.mlpackGmmProbability()\n\n // Initialize result variable and get output.\n var outputPtr mlpackArma\n output := outputPtr.armaToGonumMat(\"output\")\n\n // Clear settings.\n clearSettings()\n\n // Return output(s).\n return output\n}", "func LRNGradBeta(value float32) LRNGradAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"beta\"] = value\n\t}\n}", "func absum(k *Kernel) float64 {\n\tvar sum float64\n\tfor _, v := range k.Matrix {\n\t\tsum += math.Abs(v)\n\t}\n\treturn sum\n}", "func calcBetainv(probability, alpha, beta, lower, upper float64) float64 {\n\tminCumulative, maxCumulative := 1.0e-300, 3.0e-308\n\tlowerBound, upperBound := maxCumulative, 1.0-2.22e-16\n\tneedSwap := false\n\tvar alpha1, alpha2, beta1, beta2, beta3, prob1, x, y float64\n\tif probability <= 0.5 {\n\t\tprob1, alpha1, beta1 = probability, alpha, beta\n\t} else {\n\t\tprob1, alpha1, beta1, needSwap = 1.0-probability, beta, alpha, true\n\t}\n\tlogBetaNum := logBeta(alpha, beta)\n\tprob2 := math.Sqrt(-math.Log(prob1 * prob1))\n\tprob3 := prob2 - (prob2*0.27061+2.3075)/(prob2*(prob2*0.04481+0.99229)+1)\n\tif alpha1 > 1 && beta1 > 1 {\n\t\talpha2, beta2, prob2 = 1/(alpha1+alpha1-1), 1/(beta1+beta1-1), (prob3*prob3-3)/6\n\t\tx = 2 / (alpha2 + beta2)\n\t\ty = prob3*math.Sqrt(x+prob2)/x - (beta2-alpha2)*(prob2+5/6.0-2/(x*3))\n\t\tbeta3 = alpha1 / (alpha1 + beta1*math.Exp(y+y))\n\t} else {\n\t\tbeta2, prob2 = 1/(beta1*9), beta1+beta1\n\t\tbeta2 = prob2 * math.Pow(1-beta2+prob3*math.Sqrt(beta2), 3)\n\t\tif beta2 <= 0 {\n\t\t\tbeta3 = 1 - math.Exp((math.Log((1-prob1)*beta1)+logBetaNum)/beta1)\n\t\t} else {\n\t\t\tbeta2 = (prob2 + alpha1*4 - 2) / beta2\n\t\t\tif beta2 <= 1 {\n\t\t\t\tbeta3 = math.Exp((logBetaNum + math.Log(alpha1*prob1)) / alpha1)\n\t\t\t} else {\n\t\t\t\tbeta3 = 1 - 2/(beta2+1)\n\t\t\t}\n\t\t}\n\t}\n\tbeta2, prob2 = 1-beta1, 1-alpha1\n\tif beta3 < lowerBound {\n\t\tbeta3 = lowerBound\n\t} else if beta3 > upperBound {\n\t\tbeta3 = upperBound\n\t}\n\talpha3 := math.Max(minCumulative, math.Pow(10.0, -13.0-2.5/(alpha1*alpha1)-0.5/(prob1*prob1)))\n\tbeta3 = betainvProbIterator(alpha1, alpha3, beta1, beta2, beta3, logBetaNum, maxCumulative, prob1, prob2)\n\tif needSwap {\n\t\tbeta3 = 1.0 - beta3\n\t}\n\treturn (upper-lower)*beta3 + lower\n}", "func remez(des, grid, bands, wt []float64, ngrid int, iext []int, alpha []float64, nfcns, itrmax int, dimsize int) (float64, error) {\n\ta := make([]float64, dimsize+1)\n\tp := make([]float64, dimsize+1)\n\tq := make([]float64, dimsize+1)\n\tad := make([]float64, dimsize+1)\n\tx := make([]float64, dimsize+1)\n\ty := make([]float64, dimsize+1)\n\n\tdevl := -1.0\n\tnz := nfcns + 1\n\tnzz := nfcns + 2\n\n\tvar comp, dev, y1 float64\n\nIterationLoop:\n\tfor niter := 0; niter <= itrmax; niter++ {\n\t\tif niter == itrmax {\n\t\t\treturn dev, errors.New(\"remez: reached max iterations\")\n\t\t}\n\n\t\tiext[nzz] = ngrid + 1\n\n\t\tfor j := 1; j <= nz; j++ {\n\t\t\tx[j] = math.Cos(grid[iext[j]] * pi2)\n\t\t}\n\n\t\tjet := (nfcns-1)/15 + 1\n\t\tfor j := 1; j <= nz; j++ {\n\t\t\tad[j] = lagrangeInterp(j, nz, jet, x)\n\t\t}\n\n\t\tdnum, dden := 0.0, 0.0\n\t\tfor j, k := 1, 1.0; j <= nz; j, k = j+1, -k {\n\t\t\tl := iext[j]\n\t\t\tdnum += ad[j] * des[l]\n\t\t\tdden += k * ad[j] / wt[l]\n\t\t}\n\t\tdev = dnum / dden\n\n\t\t/* printf(\"DEVIATION = %lg\\n\",*dev); */\n\n\t\tnu := 1.0\n\t\tif dev > 0.0 {\n\t\t\tnu = -1.0\n\t\t}\n\t\tdev = math.Abs(dev) // dev = -nu * dev\n\t\tfor j, k := 1, nu; j <= nz; j, k = j+1, -k {\n\t\t\tl := iext[j]\n\t\t\ty[j] = des[l] + k*dev/wt[l]\n\t\t}\n\t\tif dev <= devl {\n\t\t\t/* finished */\n\t\t\treturn dev, errors.New(\"remez: deviation decreased\")\n\t\t}\n\t\tdevl = dev\n\n\t\tjchnge := 0\n\t\tk1 := iext[1]\n\t\tknz := iext[nz]\n\t\tklow := 0\n\t\tnut := -nu\n\n\t\tdown := func(l, j int) {\n\t\t\tfor {\n\t\t\t\tl--\n\t\t\t\tif l <= klow {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\te := (freqEval(l, nz, grid, x, y, ad) - des[l]) * wt[l]\n\t\t\t\tif nut*e-comp <= 0.0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcomp = nut * e\n\t\t\t}\n\t\t\tklow = iext[j]\n\t\t\tiext[j] = l + 1\n\t\t\tjchnge++\n\t\t}\n\n\t\tup := func(l, j, kup int) {\n\t\t\tfor {\n\t\t\t\tl++\n\t\t\t\tif l >= kup {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\te := (freqEval(l, nz, grid, x, y, ad) - des[l]) * wt[l]\n\t\t\t\tif nut*e-comp <= 0.0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcomp = nut * e\n\t\t\t}\n\t\t\tiext[j] = l - 1\n\t\t\tklow = l - 1\n\t\t\tjchnge++\n\t\t}\n\n\t\t/*\n\t\t * SEARCH FOR THE EXTREMAL FREQUENCIES OF THE BEST APPROXIMATION\n\t\t */\n\n\t\tfor j := 1; j < nzz; j++ {\n\t\t\tkup := iext[j+1]\n\t\t\tnut = -nut\n\t\t\tif j == 2 {\n\t\t\t\ty1 = comp\n\t\t\t}\n\t\t\tcomp = dev\n\n\t\t\tl := iext[j] + 1\n\t\t\tif l < kup {\n\t\t\t\te := (freqEval(l, nz, grid, x, y, ad) - des[l]) * wt[l]\n\t\t\t\tif nut*e-comp > 0.0 {\n\t\t\t\t\tcomp = nut * e\n\t\t\t\t\tup(l, j, kup)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tl--\n\n\t\t\tfor {\n\t\t\t\tl--\n\t\t\t\tif l <= klow {\n\t\t\t\t\tl = iext[j] + 1\n\t\t\t\t\tif jchnge > 0 {\n\t\t\t\t\t\tiext[j] = l - 1\n\t\t\t\t\t\tklow = l - 1\n\t\t\t\t\t\tjchnge++\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor {\n\t\t\t\t\t\t\tl++\n\t\t\t\t\t\t\tif l >= kup {\n\t\t\t\t\t\t\t\tklow = iext[j]\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\te := (freqEval(l, nz, grid, x, y, ad) - des[l]) * wt[l]\n\t\t\t\t\t\t\tif nut*e-comp > 0.0 {\n\t\t\t\t\t\t\t\tcomp = nut * e\n\t\t\t\t\t\t\t\tup(l, j, kup)\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\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\te := (freqEval(l, nz, grid, x, y, ad) - des[l]) * wt[l]\n\t\t\t\tif nut*e-comp > 0.0 {\n\t\t\t\t\tcomp = nut * e\n\t\t\t\t\tdown(l, j)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif jchnge > 0 {\n\t\t\t\t\tklow = iext[j]\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif k1 > iext[1] {\n\t\t\tk1 = iext[1]\n\t\t}\n\t\tif knz < iext[nz] {\n\t\t\tknz = iext[nz]\n\t\t}\n\n\t\tluck := 6\n\t\tnut1 := nut\n\t\tnut = -nu\n\t\tcomp *= 1.00001\n\t\tj := nzz\n\n\t\tfor l := 1; l < k1; l++ {\n\t\t\te := (freqEval(l, nz, grid, x, y, ad) - des[l]) * wt[l]\n\t\t\tif nut*e-comp > 0.0 {\n\t\t\t\tcomp = nut * e\n\t\t\t\tup(l, j, k1)\n\t\t\t\tj = nzz + 1\n\t\t\t\tluck = 1\n\n\t\t\t\tif comp > y1 {\n\t\t\t\t\ty1 = comp\n\t\t\t\t}\n\t\t\t\tk1 = iext[nzz]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tklow = knz\n\t\tnut = -nut1\n\t\tcomp = y1 * 1.00001\n\n\t\tfor l := ngrid; l > klow; l-- {\n\t\t\te := (freqEval(l, nz, grid, x, y, ad) - des[l]) * wt[l]\n\t\t\tif nut*e-comp > 0.0 {\n\t\t\t\tcomp = nut * e\n\t\t\t\tdown(l, j)\n\n\t\t\t\tkn := iext[nzz]\n\t\t\t\tfor i := 1; i <= nfcns; i++ {\n\t\t\t\t\tiext[i] = iext[i+1]\n\t\t\t\t}\n\t\t\t\tiext[nz] = kn\n\t\t\t\tcontinue IterationLoop\n\t\t\t}\n\t\t}\n\n\t\tif luck != 6 {\n\t\t\tfor i := 1; i <= nfcns; i++ {\n\t\t\t\tiext[nzz-i] = iext[nz-i]\n\t\t\t}\n\t\t\tiext[1] = k1\n\t\t} else if jchnge <= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t/*\n\t * CALCULATION OF THE COEFFICIENTS OF THE BEST APPROXIMATION\n\t * USING THE INVERSE DISCRETE FOURIER TRANSFORM\n\t */\n\tnm1 := nfcns - 1\n\tfsh := 1.0e-06\n\tgtemp := grid[1]\n\tx[nzz] = -2.0\n\tcn := float64(2*nfcns - 1)\n\tdelf := 1.0 / cn\n\tl := 1\n\tkkk := 0\n\n\tif bands[0] == 0.0 && bands[len(bands)-1] == 0.5 {\n\t\tkkk = 1\n\t}\n\n\tif nfcns <= 3 {\n\t\tkkk = 1\n\t}\n\n\tvar aa, bb float64\n\tif kkk != 1 {\n\t\tdtemp := math.Cos(pi2 * grid[1])\n\t\tdnum := math.Cos(pi2 * grid[ngrid])\n\t\taa = 2.0 / (dtemp - dnum)\n\t\tbb = -(dtemp + dnum) / (dtemp - dnum)\n\t}\n\n\tfor j := 1; j <= nfcns; j++ {\n\t\tft := float64(j-1) * delf\n\t\txt := math.Cos(pi2 * ft)\n\t\tif kkk != 1 {\n\t\t\txt = (xt - bb) / aa\n\t\t\t// /*XX* ckeck up !! */\n\t\t\t// xt1 = sqrt(1.0-xt*xt);\n\t\t\t// ft = atan2(xt1,xt)/pi2;\n\n\t\t\tft = math.Acos(xt) / pi2\n\t\t}\n\t\tfor {\n\t\t\txe := x[l]\n\t\t\tif xt > xe {\n\t\t\t\tif (xt - xe) < fsh {\n\t\t\t\t\ta[j] = y[l]\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tgrid[1] = ft\n\t\t\t\ta[j] = freqEval(1, nz, grid, x, y, ad)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif (xe - xt) < fsh {\n\t\t\t\ta[j] = y[l]\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tl++\n\t\t}\n\t\tif l > 1 {\n\t\t\tl = l - 1\n\t\t}\n\t}\n\n\tgrid[1] = gtemp\n\tdden := pi2 / cn\n\tfor j := 1; j <= nfcns; j++ {\n\t\tdtemp := 0.0\n\t\tdnum := float64(j-1) * dden\n\t\tif nm1 >= 1 {\n\t\t\tfor k := 1; k <= nm1; k++ {\n\t\t\t\tdtemp += a[k+1] * math.Cos(dnum*float64(k))\n\t\t\t}\n\t\t}\n\t\talpha[j] = 2.0*dtemp + a[1]\n\t}\n\n\tfor j := 2; j <= nfcns; j++ {\n\t\talpha[j] *= 2.0 / cn\n\t}\n\talpha[1] /= cn\n\n\tif kkk != 1 {\n\t\tp[1] = 2.0*alpha[nfcns]*bb + alpha[nm1]\n\t\tp[2] = 2.0 * aa * alpha[nfcns]\n\t\tq[1] = alpha[nfcns-2] - alpha[nfcns]\n\t\tfor j := 2; j <= nm1; j++ {\n\t\t\tif j >= nm1 {\n\t\t\t\taa *= 0.5\n\t\t\t\tbb *= 0.5\n\t\t\t}\n\t\t\tp[j+1] = 0.0\n\t\t\tfor k := 1; k <= j; k++ {\n\t\t\t\ta[k] = p[k]\n\t\t\t\tp[k] = 2.0 * bb * a[k]\n\t\t\t}\n\t\t\tp[2] += a[1] * 2.0 * aa\n\t\t\tfor k := 1; k <= j-1; k++ {\n\t\t\t\tp[k] += q[k] + aa*a[k+1]\n\t\t\t}\n\t\t\tfor k := 3; k <= j+1; k++ {\n\t\t\t\tp[k] += aa * a[k-1]\n\t\t\t}\n\n\t\t\tif j != nm1 {\n\t\t\t\tfor k := 1; k <= j; k++ {\n\t\t\t\t\tq[k] = -a[k]\n\t\t\t\t}\n\t\t\t\tq[1] += alpha[nfcns-1-j]\n\t\t\t}\n\t\t}\n\t\tfor j := 1; j <= nfcns; j++ {\n\t\t\talpha[j] = p[j]\n\t\t}\n\t}\n\n\tif nfcns <= 3 {\n\t\talpha[nfcns+1] = 0.0\n\t\talpha[nfcns+2] = 0.0\n\t}\n\treturn dev, nil\n}", "func logBeta(a, b float64) float64 {\n\tcorr, p, q := 0.0, a, a\n\tif b < p {\n\t\tp = b\n\t}\n\tif b > q {\n\t\tq = b\n\t}\n\tif p < 0 {\n\t\treturn math.NaN()\n\t}\n\tif p == 0 {\n\t\treturn math.MaxFloat64\n\t}\n\tif p >= 10.0 {\n\t\tcorr = lgammacor(p) + lgammacor(q) - lgammacor(p+q)\n\t\tf1 := q * logrelerr(-p/(p+q))\n\t\treturn math.Log(q)*-0.5 + 0.918938533204672741780329736406 + corr + (p-0.5)*math.Log(p/(p+q)) + math.Nextafter(f1, f1)\n\t}\n\tif q >= 10 {\n\t\tcorr = lgammacor(q) - lgammacor(p+q)\n\t\tval, _ := math.Lgamma(p)\n\t\treturn val + corr + p - p*math.Log(p+q) + (q-0.5)*logrelerr(-p/(p+q))\n\t}\n\treturn math.Log(math.Gamma(p) * (math.Gamma(q) / math.Gamma(p+q)))\n}", "func (s *Kalman1State) Update(m *Measurement) {\n\tz := s.PredictMeasurement()\n\n\ty := matrix.Zeros(15, 1)\n\ty.Set(9, 0, m.B1-z.B1)\n\ty.Set(10, 0, m.B2-z.B2)\n\ty.Set(11, 0, m.B3-z.B3)\n\n\th := s.calcJacobianMeasurement()\n\n\tvar v float64\n\t_, _, v = m.Accums[9](m.B1)\n\tm.M.Set(9, 9, v)\n\t_, _, v = m.Accums[10](m.B2)\n\tm.M.Set(10, 10, v)\n\t_, _, v = m.Accums[11](m.B3)\n\tm.M.Set(11, 11, v)\n\n\tss := matrix.Sum(matrix.Product(h, matrix.Product(s.M, h.Transpose())), m.M)\n\n\tm2, err := ss.Inverse()\n\tif err != nil {\n\t\treturn\n\t}\n\tkk := matrix.Product(s.M, matrix.Product(h.Transpose(), m2))\n\tsu := matrix.Product(kk, y)\n\ts.E0 += su.Get(6, 0)\n\ts.E1 += su.Get(7, 0)\n\ts.E2 += su.Get(8, 0)\n\ts.E3 += su.Get(9, 0)\n\ts.H1 += su.Get(10, 0)\n\ts.H2 += su.Get(11, 0)\n\ts.H3 += su.Get(12, 0)\n\ts.F0 += su.Get(22, 0)\n\ts.F1 += su.Get(23, 0)\n\ts.F2 += su.Get(24, 0)\n\ts.F3 += su.Get(25, 0)\n\ts.D1 += su.Get(26, 0)\n\ts.D2 += su.Get(27, 0)\n\ts.D3 += su.Get(28, 0)\n\ts.T = m.T\n\ts.M = matrix.Product(matrix.Difference(matrix.Eye(32), matrix.Product(kk, h)), s.M)\n\ts.normalize()\n}", "func Beta(x, y float64) float64 {\n\tswitch {\n\tcase math.IsNaN(x) || math.IsNaN(y) || math.IsInf(x, -1) || math.IsInf(y, -1):\n\t\treturn math.NaN()\n\tcase math.IsInf(x, 1):\n\t\tif y <= 0 && y == math.Trunc(y) {\n\t\t\treturn float64(GammaSign(y)) * x\n\t\t}\n\t\treturn 0\n\tcase math.IsInf(y, 1):\n\t\tif x <= 0 && x == math.Trunc(x) {\n\t\t\treturn float64(GammaSign(x)) * y\n\t\t}\n\t\treturn 0\n\t}\n\treturn GammaRatio([]float64{x, y}, []float64{x + y})\n}", "func (rbm *RBM) Gradient(data [][]float64,\n\tminiBatchIndex int) ([][]float64, []float64, []float64) {\n\tgradW := nnet.MakeMatrix(rbm.NumHiddenUnits, rbm.NumVisibleUnits)\n\tgradB := make([]float64, rbm.NumVisibleUnits)\n\tgradC := make([]float64, rbm.NumHiddenUnits)\n\n\tfor i, v := range data {\n\t\t// Set start state of Gibbs-sampling\n\t\tvar gibbsStart []float64\n\t\tpersistentIndex := i + miniBatchIndex*rbm.Option.MiniBatchSize\n\t\tif rbm.Option.UsePersistent {\n\t\t\tgibbsStart = rbm.PersistentVisibleUnits[persistentIndex]\n\t\t} else {\n\t\t\tgibbsStart = v\n\t\t}\n\n\t\t// Perform reconstruction using Gibbs-sampling\n\t\treconstructedVisible, _ := rbm.Reconstruct(gibbsStart,\n\t\t\trbm.Option.OrderOfGibbsSampling)\n\n\t\t// keep recostructed visible\n\t\tif rbm.Option.UsePersistent {\n\t\t\trbm.PersistentVisibleUnits[persistentIndex] =\n\t\t\t\treconstructedVisible\n\t\t}\n\n\t\t// pre-computation that is used in gradient computation\n\t\tp_h_given_v1 := make([]float64, rbm.NumHiddenUnits)\n\t\tp_h_given_v2 := make([]float64, rbm.NumHiddenUnits)\n\t\tfor i := 0; i < rbm.NumHiddenUnits; i++ {\n\t\t\tp_h_given_v1[i] = rbm.P_H_Given_V(i, v)\n\t\t\tp_h_given_v2[i] = rbm.P_H_Given_V(i, reconstructedVisible)\n\t\t}\n\n\t\t// Gompute gradient of W\n\t\tfor i := 0; i < rbm.NumHiddenUnits; i++ {\n\t\t\tfor j := 0; j < rbm.NumVisibleUnits; j++ {\n\t\t\t\tgradW[i][j] += p_h_given_v1[i]*v[j] -\n\t\t\t\t\tp_h_given_v2[i]*reconstructedVisible[j]\n\t\t\t}\n\t\t}\n\n\t\t// Gompute gradient of B\n\t\tfor j := 0; j < rbm.NumVisibleUnits; j++ {\n\t\t\tgradB[j] += v[j] - reconstructedVisible[j]\n\t\t}\n\n\t\t// Gompute gradient of C\n\t\tfor i := 0; i < rbm.NumHiddenUnits; i++ {\n\t\t\tgradC[i] += p_h_given_v1[i] - p_h_given_v2[i]\n\t\t}\n\t}\n\n\t// Normalized by size of mini-batch\n\tfor i := 0; i < rbm.NumHiddenUnits; i++ {\n\t\tfor j := 0; j < rbm.NumVisibleUnits; j++ {\n\t\t\tgradW[i][j] /= float64(len(data))\n\t\t}\n\t}\n\n\tfor j := 0; j < rbm.NumVisibleUnits; j++ {\n\t\tgradB[j] /= float64(len(data))\n\t}\n\n\tfor i := 0; i < rbm.NumHiddenUnits; i++ {\n\t\tgradC[i] /= float64(len(data))\n\t}\n\n\treturn gradW, gradB, gradC\n}", "func Dlatm6(_type, n int, a, b, x, y *mat.Matrix, alpha, beta, wx, wy float64, s, dif *mat.Vector) {\n\tvar one, three, two, zero float64\n\tvar i, j int\n\tvar err error\n\n\twork := vf(100)\n\tz := mf(12, 12, opts)\n\n\tzero = 0.0\n\tone = 1.0\n\ttwo = 2.0\n\tthree = 3.0\n\n\t// Generate test problem ...\n\t// (Da, Db) ...\n\tfor i = 1; i <= n; i++ {\n\t\tfor j = 1; j <= n; j++ {\n\n\t\t\tif i == j {\n\t\t\t\ta.Set(i-1, i-1, float64(i)+alpha)\n\t\t\t\tb.Set(i-1, i-1, one)\n\t\t\t} else {\n\t\t\t\ta.Set(i-1, j-1, zero)\n\t\t\t\tb.Set(i-1, j-1, zero)\n\t\t\t}\n\n\t\t}\n\t}\n\n\t// Form X and Y\n\tgolapack.Dlacpy(Full, n, n, b, y)\n\ty.Set(2, 0, -wy)\n\ty.Set(3, 0, wy)\n\ty.Set(4, 0, -wy)\n\ty.Set(2, 1, -wy)\n\ty.Set(3, 1, wy)\n\ty.Set(4, 1, -wy)\n\n\tgolapack.Dlacpy(Full, n, n, b, x)\n\tx.Set(0, 2, -wx)\n\tx.Set(0, 3, -wx)\n\tx.Set(0, 4, wx)\n\tx.Set(1, 2, wx)\n\tx.Set(1, 3, -wx)\n\tx.Set(1, 4, -wx)\n\n\t// Form (A, B)\n\tb.Set(0, 2, wx+wy)\n\tb.Set(1, 2, -wx+wy)\n\tb.Set(0, 3, wx-wy)\n\tb.Set(1, 3, wx-wy)\n\tb.Set(0, 4, -wx+wy)\n\tb.Set(1, 4, wx+wy)\n\tif _type == 1 {\n\t\ta.Set(0, 2, wx*a.Get(0, 0)+wy*a.Get(2, 2))\n\t\ta.Set(1, 2, -wx*a.Get(1, 1)+wy*a.Get(2, 2))\n\t\ta.Set(0, 3, wx*a.Get(0, 0)-wy*a.Get(3, 3))\n\t\ta.Set(1, 3, wx*a.Get(1, 1)-wy*a.Get(3, 3))\n\t\ta.Set(0, 4, -wx*a.Get(0, 0)+wy*a.Get(4, 4))\n\t\ta.Set(1, 4, wx*a.Get(1, 1)+wy*a.Get(4, 4))\n\t} else if _type == 2 {\n\t\ta.Set(0, 2, two*wx+wy)\n\t\ta.Set(1, 2, wy)\n\t\ta.Set(0, 3, -wy*(two+alpha+beta))\n\t\ta.Set(1, 3, two*wx-wy*(two+alpha+beta))\n\t\ta.Set(0, 4, -two*wx+wy*(alpha-beta))\n\t\ta.Set(1, 4, wy*(alpha-beta))\n\t\ta.Set(0, 0, one)\n\t\ta.Set(0, 1, -one)\n\t\ta.Set(1, 0, one)\n\t\ta.Set(1, 1, a.Get(0, 0))\n\t\ta.Set(2, 2, one)\n\t\ta.Set(3, 3, one+alpha)\n\t\ta.Set(3, 4, one+beta)\n\t\ta.Set(4, 3, -a.Get(3, 4))\n\t\ta.Set(4, 4, a.Get(3, 3))\n\t}\n\n\t// Compute condition numbers\n\tif _type == 1 {\n\n\t\ts.Set(0, one/math.Sqrt((one+three*wy*wy)/(one+a.Get(0, 0)*a.Get(0, 0))))\n\t\ts.Set(1, one/math.Sqrt((one+three*wy*wy)/(one+a.Get(1, 1)*a.Get(1, 1))))\n\t\ts.Set(2, one/math.Sqrt((one+two*wx*wx)/(one+a.Get(2, 2)*a.Get(2, 2))))\n\t\ts.Set(3, one/math.Sqrt((one+two*wx*wx)/(one+a.Get(3, 3)*a.Get(3, 3))))\n\t\ts.Set(4, one/math.Sqrt((one+two*wx*wx)/(one+a.Get(4, 4)*a.Get(4, 4))))\n\n\t\tDlakf2(1, 4, a, a.Off(1, 1), b, b.Off(1, 1), z)\n\t\tif _, err = golapack.Dgesvd('N', 'N', 8, 8, z, work, work.Off(8).Matrix(1, opts), work.Off(9).Matrix(1, opts), work.Off(10), 40); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdif.Set(0, work.Get(7))\n\n\t\tDlakf2(4, 1, a, a.Off(4, 4), b, b.Off(4, 4), z)\n\t\tif _, err = golapack.Dgesvd('N', 'N', 8, 8, z, work, work.Off(8).Matrix(1, opts), work.Off(9).Matrix(1, opts), work.Off(10), 40); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdif.Set(4, work.Get(7))\n\n\t} else if _type == 2 {\n\n\t\ts.Set(0, one/math.Sqrt(one/three+wy*wy))\n\t\ts.Set(1, s.Get(0))\n\t\ts.Set(2, one/math.Sqrt(one/two+wx*wx))\n\t\ts.Set(3, one/math.Sqrt((one+two*wx*wx)/(one+(one+alpha)*(one+alpha)+(one+beta)*(one+beta))))\n\t\ts.Set(4, s.Get(3))\n\n\t\tDlakf2(2, 3, a, a.Off(2, 2), b, b.Off(2, 2), z)\n\t\tif _, err = golapack.Dgesvd('N', 'N', 12, 12, z, work, work.Off(12).Matrix(1, opts), work.Off(13).Matrix(1, opts), work.Off(14), 60); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdif.Set(0, work.Get(11))\n\n\t\tDlakf2(3, 2, a, a.Off(3, 3), b, b.Off(3, 3), z)\n\t\tif _, err = golapack.Dgesvd('N', 'N', 12, 12, z, work, work.Off(12).Matrix(1, opts), work.Off(13).Matrix(1, opts), work.Off(14), 60); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdif.Set(4, work.Get(11))\n\n\t}\n}", "func (obj *Hmm) Posterior(r Scalar, data HmmDataRecord, states [][]int) error {\n n := data.GetN()\n m := obj.M\n // test length of x\n if n != len(states) {\n return fmt.Errorf(\"number of states does not match number of observations\")\n }\n if n == 0 {\n r.SetValue(0.0)\n return nil\n }\n // result at time t-1 (restricted to given states)\n alpha_s := NullVector(obj.ScalarType(), m)\n // result at time t (restricted to given states)\n alpha_t := NullVector(obj.ScalarType(), m)\n // result at time t-1\n beta_s := NullVector(obj.ScalarType(), m)\n // result at time t\n beta_t := NullVector(obj.ScalarType(), m)\n // some temporary variables\n t1 := NullScalar(obj.ScalarType())\n t2 := NullScalar(obj.ScalarType())\n // initialize alpha_s\n for _, i := range states[0] {\n if err := data.LogPdf(t2, obj.StateMap[i], 0); err != nil {\n return err\n }\n alpha_s.At(i).Add(obj.Pi.At(i), t2)\n }\n for i := 0; i < m; i++ {\n if err := data.LogPdf(t2, obj.StateMap[i], 0); err != nil {\n return err\n }\n beta_s.At(i).Add(obj.Pi.At(i), t2)\n }\n // loop over x(0), ..., x(N-2)\n for k := 1; k < n-1; k++ {\n // transition to state j\n for _, j := range states[k] {\n alpha_t.At(j).SetValue(math.Inf(-1))\n // compute:\n // alpha_t(x_j) = sum_{x_i} p(x_j | x_i) alpha_s(x_i)\n // transitions from state i\n for _, i := range states[k-1] {\n t1.Add(obj.Tr.At(i, j), alpha_s.At(i))\n alpha_t.At(j).LogAdd(alpha_t.At(j), t1, t2)\n }\n // alpha_t(x_t) = p(y_t | x_t) sum_{x_s} p(x_t | x_s) alpha_s(x_s)\n if err := data.LogPdf(t2, obj.StateMap[j], k); err != nil {\n return err\n }\n alpha_t.At(j).Add(alpha_t.At(j), t2)\n }\n // swap alpha\n alpha_s, alpha_t = alpha_t, alpha_s\n // transition to state j\n for j := 0; j < m; j++ {\n beta_t.At(j).SetValue(math.Inf(-1))\n // compute:\n // beta_t(x_j) = sum_{x_i} p(x_j | x_i) beta_s(x_i)\n // transitions from state i\n for i := 0; i < m; i++ {\n t1.Add(obj.Tr.At(i, j), beta_s.At(i))\n beta_t.At(j).LogAdd(beta_t.At(j), t1, t2)\n }\n // beta_t(x_t) = p(y_t | x_t) sum_{x_s} p(x_t | x_s) beta_s(x_s)\n if err := data.LogPdf(t2, obj.StateMap[j], k); err != nil {\n return err\n }\n beta_t.At(j).Add(beta_t.At(j), t2)\n }\n // swap beta\n beta_s, beta_t = beta_t, beta_s\n }\n if n > 1 {\n // last step from x(N-2) to x(N-1)\n // transition to state j\n for _, j := range states[n-1] {\n alpha_t.At(j).SetValue(math.Inf(-1))\n // compute:\n // alpha_t(x_j) = sum_{x_i} p(x_j | x_i) alpha_s(x_i)\n // transitions from state i\n for _, i := range states[n-2] {\n t1.Add(obj.Tf.At(i, j), alpha_s.At(i))\n alpha_t.At(j).LogAdd(alpha_t.At(j), t1, t2)\n }\n // alpha_t(x_t) = p(y_t | x_t) sum_{x_s} p(x_t | x_s) alpha_s(x_s)\n if err := data.LogPdf(t2, obj.StateMap[j], n-1); err != nil {\n return err\n }\n alpha_t.At(j).Add(alpha_t.At(j), t2)\n }\n // swap beta\n alpha_s, alpha_t = alpha_t, alpha_s\n // transition to state j\n for j := 0; j < m; j++ {\n beta_t.At(j).SetValue(math.Inf(-1))\n // compute:\n // beta_t(x_j) = sum_{x_i} p(x_j | x_i) beta_s(x_i)\n // transitions from state i\n for i := 0; i < m; i++ {\n t1.Add(obj.Tf.At(i, j), beta_s.At(i))\n beta_t.At(j).LogAdd(beta_t.At(j), t1, t2)\n }\n // beta_t(x_t) = p(y_t | x_t) sum_{x_s} p(x_t | x_s) beta_s(x_s)\n if err := data.LogPdf(t2, obj.StateMap[j], n-1); err != nil {\n return err\n }\n beta_t.At(j).Add(beta_t.At(j), t2)\n }\n // swap beta\n beta_s, beta_t = beta_t, beta_s\n }\n // sum up alpha\n r.SetValue(math.Inf(-1))\n for _, j := range states[n-1] {\n r.LogAdd(r, alpha_s.At(j), t2)\n }\n // sum up beta\n t1.SetValue(math.Inf(-1))\n for j := 0; j < m; j++ {\n t1.LogAdd(t1, beta_s.At(j), t2)\n }\n // compute result\n r.Sub(r, t1)\n return nil\n}", "func VADDPS_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VADDPS_Z(mxyz, xyz, k, xyz1) }", "func BiasAddV1(scope *Scope, value tf.Output, bias tf.Output) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"BiasAddV1\",\n\t\tInput: []tf.Input{\n\t\t\tvalue, bias,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func PAVGB(mx, x operand.Op) { ctx.PAVGB(mx, x) }", "func dgsvts3(m, p, n int, a, af, b, bf, u, v, q *mat.Matrix, alpha, beta *mat.Vector, r *mat.Matrix, iwork *[]int, work *mat.Vector, lwork int, rwork, result *mat.Vector) {\n\tvar anorm, bnorm, one, resid, temp, ulp, ulpinv, unfl, zero float64\n\tvar i, j, k, l int\n\tvar err error\n\n\tzero = 0.0\n\tone = 1.0\n\n\tulp = golapack.Dlamch(Precision)\n\tulpinv = one / ulp\n\tunfl = golapack.Dlamch(SafeMinimum)\n\n\t// Copy the matrix A to the array AF.\n\tgolapack.Dlacpy(Full, m, n, a, af)\n\tgolapack.Dlacpy(Full, p, n, b, bf)\n\n\tanorm = math.Max(golapack.Dlange('1', m, n, a, rwork), unfl)\n\tbnorm = math.Max(golapack.Dlange('1', p, n, b, rwork), unfl)\n\n\t// Factorize the matrices A and B in the arrays AF and BF.\n\tif k, l, _, err = golapack.Dggsvd3('U', 'V', 'Q', m, n, p, af, bf, alpha, beta, u, v, q, work, lwork, iwork); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Copy R\n\tfor i = 1; i <= min(k+l, m); i++ {\n\t\tfor j = i; j <= k+l; j++ {\n\t\t\tr.Set(i-1, j-1, af.Get(i-1, n-k-l+j-1))\n\t\t}\n\t}\n\n\tif m-k-l < 0 {\n\t\tfor i = m + 1; i <= k+l; i++ {\n\t\t\tfor j = i; j <= k+l; j++ {\n\t\t\t\tr.Set(i-1, j-1, bf.Get(i-k-1, n-k-l+j-1))\n\t\t\t}\n\t\t}\n\t}\n\n\t// Compute A:= U'*A*Q - D1*R\n\tif err = work.Matrix(a.Rows, opts).Gemm(NoTrans, NoTrans, m, n, n, one, a, q, zero); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err = a.Gemm(Trans, NoTrans, m, n, m, one, u, work.Matrix(a.Rows, opts), zero); err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor i = 1; i <= k; i++ {\n\t\tfor j = i; j <= k+l; j++ {\n\t\t\ta.Set(i-1, n-k-l+j-1, a.Get(i-1, n-k-l+j-1)-r.Get(i-1, j-1))\n\t\t}\n\t}\n\n\tfor i = k + 1; i <= min(k+l, m); i++ {\n\t\tfor j = i; j <= k+l; j++ {\n\t\t\ta.Set(i-1, n-k-l+j-1, a.Get(i-1, n-k-l+j-1)-alpha.Get(i-1)*r.Get(i-1, j-1))\n\t\t}\n\t}\n\n\t// Compute norm( U'*A*Q - D1*R ) / ( max(1,M,N)*norm(A)*ULP ) .\n\tresid = golapack.Dlange('1', m, n, a, rwork)\n\n\tif anorm > zero {\n\t\tresult.Set(0, ((resid/float64(max(1, m, n)))/anorm)/ulp)\n\t} else {\n\t\tresult.Set(0, zero)\n\t}\n\n\t// Compute B := V'*B*Q - D2*R\n\tif err = work.Matrix(b.Rows, opts).Gemm(NoTrans, NoTrans, p, n, n, one, b, q, zero); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err = b.Gemm(Trans, NoTrans, p, n, p, one, v, work.Matrix(a.Rows, opts), zero); err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor i = 1; i <= l; i++ {\n\t\tfor j = i; j <= l; j++ {\n\t\t\tb.Set(i-1, n-l+j-1, b.Get(i-1, n-l+j-1)-beta.Get(k+i-1)*r.Get(k+i-1, k+j-1))\n\t\t}\n\t}\n\n\t// Compute norm( V'*B*Q - D2*R ) / ( max(P,N)*norm(B)*ULP ) .\n\tresid = golapack.Dlange('1', p, n, b, rwork)\n\tif bnorm > zero {\n\t\tresult.Set(1, ((resid/float64(max(1, p, n)))/bnorm)/ulp)\n\t} else {\n\t\tresult.Set(1, zero)\n\t}\n\n\t// Compute I - U'*U\n\tgolapack.Dlaset(Full, m, m, zero, one, work.Matrix(q.Rows, opts))\n\tif err = work.Matrix(u.Rows, opts).Syrk(Upper, Trans, m, m, -one, u, one); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Compute norm( I - U'*U ) / ( M * ULP ) .\n\tresid = golapack.Dlansy('1', Upper, m, work.Matrix(u.Rows, opts), rwork)\n\tresult.Set(2, (resid/float64(max(1, m)))/ulp)\n\n\t// Compute I - V'*V\n\tgolapack.Dlaset(Full, p, p, zero, one, work.Matrix(v.Rows, opts))\n\tif err = work.Matrix(v.Rows, opts).Syrk(Upper, Trans, p, p, -one, v, one); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Compute norm( I - V'*V ) / ( P * ULP ) .\n\tresid = golapack.Dlansy('1', Upper, p, work.Matrix(v.Rows, opts), rwork)\n\tresult.Set(3, (resid/float64(max(1, p)))/ulp)\n\n\t// Compute I - Q'*Q\n\tgolapack.Dlaset(Full, n, n, zero, one, work.Matrix(q.Rows, opts))\n\tif err = work.Matrix(q.Rows, opts).Syrk(Upper, Trans, n, n, -one, q, one); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Compute norm( I - Q'*Q ) / ( N * ULP ) .\n\tresid = golapack.Dlansy('1', Upper, n, work.Matrix(q.Rows, opts), rwork)\n\tresult.Set(4, (resid/float64(max(1, n)))/ulp)\n\n\t// Check sorting\n\twork.Copy(n, alpha, 1, 1)\n\tfor i = k + 1; i <= min(k+l, m); i++ {\n\t\tj = (*iwork)[i-1]\n\t\tif i != j {\n\t\t\ttemp = work.Get(i - 1)\n\t\t\twork.Set(i-1, work.Get(j-1))\n\t\t\twork.Set(j-1, temp)\n\t\t}\n\t}\n\n\tresult.Set(5, zero)\n\tfor i = k + 1; i <= min(k+l, m)-1; i++ {\n\t\tif work.Get(i-1) < work.Get(i) {\n\t\t\tresult.Set(5, ulpinv)\n\t\t}\n\t}\n\n\treturn\n}", "func BLENDVPS(x, mx, x1 operand.Op) { ctx.BLENDVPS(x, mx, x1) }", "func SrampD1(x, β float64) float64 {\n\tif -β*x > 500.0 {\n\t\treturn 0.0\n\t}\n\treturn 1.0 / (1.0 + math.Exp(-β*x))\n}", "func rprop(f func(Vector) (Scalar, error), x0 ConstVector, step_init float64 , eta []float64,\n epsilon Epsilon,\n maxIterations MaxIterations,\n hook Hook,\n constraints Constraints) (Vector, error) {\n\n n := x0.Dim()\n t := x0.ElementType()\n // copy variables\n x1 := AsDenseRealVector(x0)\n x2 := AsDenseRealVector(x0)\n // step size for each variable\n step := make([]float64, n)\n // gradients\n gradient_new := make([]float64, n)\n gradient_old := make([]float64, n)\n // initialize values\n for i := 0; i < x1.Dim(); i++ {\n step[i] = step_init\n gradient_new[i] = 1\n gradient_old[i] = 1\n }\n if err := x1.Variables(1); err != nil {\n return nil, err\n }\n gradient_is_nan := func(s Scalar) bool {\n for i := 0; i < s.GetN(); i++ {\n if math.IsNaN(s.GetDerivative(i)) {\n return true\n }\n }\n return false\n }\n // check initial value\n if constraints.Value != nil && !constraints.Value(x1) {\n return x1, fmt.Errorf(\"invalid initial value: %v\", x1)\n }\n // evaluate objective function\n s, err := f(x1)\n if err != nil {\n return x1, fmt.Errorf(\"invalid initial value: %v\", x1)\n }\n if gradient_is_nan(s) {\n return x1, fmt.Errorf(\"gradient is NaN for initial value: %v\", x1)\n }\n for i := 0; i < maxIterations.Value; i++ {\n for i := 0; i < x1.Dim(); i++ {\n gradient_old[i] = gradient_new[i]\n }\n // compute partial derivatives and update x\n for i := 0; i < x1.Dim(); i++ {\n // save derivative\n gradient_new[i] = s.GetDerivative(i)\n }\n // execute hook if available\n if hook.Value != nil && hook.Value(gradient_new, step, x1, s) {\n break;\n }\n // evaluate stop criterion\n if (Norm(gradient_new) < epsilon.Value) {\n break;\n }\n // update step size\n for i := 0; i < x1.Dim(); i++ {\n if gradient_new[i] != 0.0 {\n if ((gradient_old[i] < 0 && gradient_new[i] < 0) ||\n (gradient_old[i] > 0 && gradient_new[i] > 0)) {\n step[i] *= eta[0]\n } else {\n step[i] *= eta[1]\n }\n }\n }\n for {\n // update x\n for i := 0; i < x1.Dim(); i++ {\n if gradient_new[i] != 0.0 {\n if gradient_new[i] > 0.0 {\n x2.At(i).Sub(x1.At(i), NewScalar(t, step[i]))\n } else {\n x2.At(i).Add(x1.At(i), NewScalar(t, step[i]))\n }\n }\n if math.IsNaN(x2.At(i).GetValue()) {\n return x2, fmt.Errorf(\"NaN value detected\")\n }\n }\n // evaluate objective function\n s, err = f(x2)\n if err != nil || gradient_is_nan(s) ||\n (constraints.Value != nil && !constraints.Value(x2)) {\n // if the updated is invalid reduce step size\n for i := 0; i < x1.Dim(); i++ {\n if gradient_new[i] != 0.0 {\n step[i] *= eta[1]\n }\n }\n } else {\n // new position is valid, exit loop\n break\n }\n }\n x1.Set(x2)\n }\n return x1, nil\n}", "func gdSolver(x [][]float64, y []float64, nIter int, gamma float64) []float64 {\n\tn := len(x)\n\tw := make([]float64, len(x[0])+1)\n\terrors := make([]float64, n)\n\tfor i := 0; i < nIter; i++ {\n\t\tpredY := predY(x, w)\n\t\terrorSum := 0.0\n\t\tfor j := 0; j < n; j++ {\n\t\t\terrors[j] = y[j] - predY[j]\n\t\t\terrorSum += errors[j]\n\t\t}\n\t\tfor k := 0; k < n; k++ {\n\t\t\tfor l := 1; l < len(w); l++ {\n\t\t\t\tw[l] += gamma * x[k][l-1] * errors[k]\n\t\t\t}\n\t\t}\n\t\tw[0] += gamma * errorSum\n\t}\n\treturn w\n}", "func VFMSUBADD231PS_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VFMSUBADD231PS_Z(mxyz, xyz, k, xyz1) }", "func ADDPS(mx, x operand.Op) { ctx.ADDPS(mx, x) }", "func brandes(g graph.Graph, accumulate func(s graph.Node, stack linear.NodeStack, p map[int64][]graph.Node, delta, sigma map[int64]float64)) {\n\tvar (\n\t\tnodes = graph.NodesOf(g.Nodes())\n\t\tstack linear.NodeStack\n\t\tp = make(map[int64][]graph.Node, len(nodes))\n\t\tsigma = make(map[int64]float64, len(nodes))\n\t\td = make(map[int64]int, len(nodes))\n\t\tdelta = make(map[int64]float64, len(nodes))\n\t\tqueue linear.NodeQueue\n\t)\n\tfor _, s := range nodes {\n\t\tstack = stack[:0]\n\n\t\tfor _, w := range nodes {\n\t\t\tp[w.ID()] = p[w.ID()][:0]\n\t\t}\n\n\t\tfor _, t := range nodes {\n\t\t\tsigma[t.ID()] = 0\n\t\t\td[t.ID()] = -1\n\t\t}\n\t\tsigma[s.ID()] = 1\n\t\td[s.ID()] = 0\n\n\t\tqueue.Enqueue(s)\n\t\tfor queue.Len() != 0 {\n\t\t\tv := queue.Dequeue()\n\t\t\tvid := v.ID()\n\t\t\tstack.Push(v)\n\t\t\tto := g.From(vid)\n\t\t\tfor to.Next() {\n\t\t\t\tw := to.Node()\n\t\t\t\twid := w.ID()\n\t\t\t\t// w found for the first time?\n\t\t\t\tif d[wid] < 0 {\n\t\t\t\t\tqueue.Enqueue(w)\n\t\t\t\t\td[wid] = d[vid] + 1\n\t\t\t\t}\n\t\t\t\t// shortest path to w via v?\n\t\t\t\tif d[wid] == d[vid]+1 {\n\t\t\t\t\tsigma[wid] += sigma[vid]\n\t\t\t\t\tp[wid] = append(p[wid], v)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor _, v := range nodes {\n\t\t\tdelta[v.ID()] = 0\n\t\t}\n\n\t\t// S returns vertices in order of non-increasing distance from s\n\t\taccumulate(s, stack, p, delta, sigma)\n\t}\n}", "func (p *g1JacExtended) double(q *g1JacExtended) *g1JacExtended {\n\tvar U, V, W, S, XX, M fp.Element\n\n\tU.Double(&q.Y)\n\tV.Square(&U)\n\tW.Mul(&U, &V)\n\tS.Mul(&q.X, &V)\n\tXX.Square(&q.X)\n\tM.Double(&XX).\n\t\tAdd(&M, &XX) // -> + a, but a=0 here\n\tU.Mul(&W, &q.Y)\n\n\tp.X.Square(&M).\n\t\tSub(&p.X, &S).\n\t\tSub(&p.X, &S)\n\tp.Y.Sub(&S, &p.X).\n\t\tMul(&p.Y, &M).\n\t\tSub(&p.Y, &U)\n\tp.ZZ.Mul(&V, &q.ZZ)\n\tp.ZZZ.Mul(&W, &q.ZZZ)\n\n\treturn p\n}", "func VPADDSB_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VPADDSB_Z(mxyz, xyz, k, xyz1) }", "func VPHADDSW(mxy, xy, xy1 operand.Op) { ctx.VPHADDSW(mxy, xy, xy1) }", "func VFMSUBADD213PS_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VFMSUBADD213PS_Z(mxyz, xyz, k, xyz1) }", "func blassub(g1, g2 blas64.General) blas64.General {\n\t// first make a copy of g1\n\tg3 := blas64.General{\n\t\tRows: g1.Rows,\n\t\tCols: g1.Cols,\n\t\tStride: g1.Stride,\n\t\tData: make([]float64, len(g1.Data)),\n\t}\n\tfor i, v := range g1.Data {\n\t\tg3.Data[i] = v\n\t}\n\tblas64.Gemm(blas.NoTrans, blas.NoTrans, -1.0, eye(g1.Rows), g2, 1.0, g3)\n\treturn g3\n}", "func BiasAddGrad(scope *Scope, out_backprop tf.Output, optional ...BiasAddGradAttr) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"BiasAddGrad\",\n\t\tInput: []tf.Input{\n\t\t\tout_backprop,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func VPAVGB_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VPAVGB_Z(mxyz, xyz, k, xyz1) }", "func VPSADBW(mxyz, xyz, xyz1 operand.Op) { ctx.VPSADBW(mxyz, xyz, xyz1) }", "func VPADDW_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VPADDW_Z(mxyz, xyz, k, xyz1) }", "func Zungr2(m, n, k int, a *mat.CMatrix, tau, work *mat.CVector) (err error) {\n\tvar one, zero complex128\n\tvar i, ii, j, l int\n\n\tone = (1.0 + 0.0*1i)\n\tzero = (0.0 + 0.0*1i)\n\n\t// Test the input arguments\n\tif m < 0 {\n\t\terr = fmt.Errorf(\"m < 0: m=%v\", m)\n\t} else if n < m {\n\t\terr = fmt.Errorf(\"n < m: m=%v, n=%v\", m, n)\n\t} else if k < 0 || k > m {\n\t\terr = fmt.Errorf(\"k < 0 || k > m: m=%v, k=%v\", m, k)\n\t} else if a.Rows < max(1, m) {\n\t\terr = fmt.Errorf(\"a.Rows < max(1, m): a.Rows=%v, m=%v\", a.Rows, m)\n\t}\n\tif err != nil {\n\t\tgltest.Xerbla2(\"Zungr2\", err)\n\t\treturn\n\t}\n\n\t// Quick return if possible\n\tif m <= 0 {\n\t\treturn\n\t}\n\n\tif k < m {\n\t\t// Initialise rows 1:m-k to rows of the unit matrix\n\t\tfor j = 1; j <= n; j++ {\n\t\t\tfor l = 1; l <= m-k; l++ {\n\t\t\t\ta.Set(l-1, j-1, zero)\n\t\t\t}\n\t\t\tif j > n-m && j <= n-k {\n\t\t\t\ta.Set(m-n+j-1, j-1, one)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i = 1; i <= k; i++ {\n\t\tii = m - k + i\n\n\t\t// Apply H(i)**H to A(1:m-k+i,1:n-k+i) from the right\n\t\tZlacgv(n-m+ii-1, a.Off(ii-1, 0).CVector(), a.Rows)\n\t\ta.Set(ii-1, n-m+ii-1, one)\n\t\tZlarf(Right, ii-1, n-m+ii, a.Off(ii-1, 0).CVector(), a.Rows, tau.GetConj(i-1), a, work)\n\t\ta.Off(ii-1, 0).CVector().Scal(n-m+ii-1, -tau.Get(i-1), a.Rows)\n\t\tZlacgv(n-m+ii-1, a.Off(ii-1, 0).CVector(), a.Rows)\n\t\ta.Set(ii-1, n-m+ii-1, one-tau.GetConj(i-1))\n\n\t\t// Set A(m-k+i,n-k+i+1:n) to zero\n\t\tfor l = n - m + ii + 1; l <= n; l++ {\n\t\t\ta.Set(ii-1, l-1, zero)\n\t\t}\n\t}\n\n\treturn\n}", "func VHADDPS(mxy, xy, xy1 operand.Op) { ctx.VHADDPS(mxy, xy, xy1) }", "func matAdd(a, b [][]float64) (x[][]float64) {\n\tx = make([][]float64, len(a))\n\tfor i:=0; i<len(a); i++ {\n\t\tx[i] = make([]float64, len(a[0]))\n\t\tfor j := 0; j < len(b[0]); j++ {\n\t\t\tx[i][j] = a[i][j] + b[i][j]\n\t\t}\n\t}\n\treturn x\n}", "func (lay *Layer) Backprop(x *mat.Dense, deltaOut *mat.Dense) (deltaIn *mat.Dense, wgrad *mat.Dense) {\n\t// First, we do a partial forward calculation\n\txx := new(mat.Dense)\n\trow, _ := x.Dims()\n\txx.Augment(x, NewConstantMat(row, 1, 1.0)) // ( n x in+1 )\n\tz := new(mat.Dense)\n\tz.Mul(xx, lay.w) // (n x in + 1 ).(in +1 x out) = (n x out)\n\n\t// res = deltaOut (n x out) *elementMultiply* sigmaPrime(z) (n x out)\n\tres := mat.NewDense(row, lay.nbout, nil)\n\tres.Apply(\n\t\tfunc(i, j int, v float64) float64 {\n\t\t\treturn v * lay.act.df(z.At(i, j))\n\t\t}, deltaOut.Slice(0, row, 0, lay.nbout))\n\n\tdeltaIn = mat.NewDense(row, lay.nbin+1, nil) // row x in+1\n\tdeltaIn.Mul(res, lay.w.T()) // (row x out) . (out x in + 1)) = row x in+1\n\n\t// Compute the gradient of the weight+biais matrix\n\twgrad = mat.NewDense(lay.nbin+1, lay.nbout, nil) // in+1 x out\n\twgrad.Mul(xx.T(), res) // (in+1 x n) x (n x out) = (in+1 x out)\n\n\treturn deltaIn, wgrad // (nxin+1), (in+1 x out)\n}", "func add(a, b float64) float64 {\n\treturn a + b\n}", "func VPHADDW(mxy, xy, xy1 operand.Op) { ctx.VPHADDW(mxy, xy, xy1) }", "func VADDPD_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VADDPD_Z(mxyz, xyz, k, xyz1) }", "func VGF2P8MULB_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VGF2P8MULB_Z(mxyz, xyz, k, xyz1) }", "func SigmoidGrad(scope *Scope, y tf.Output, dy tf.Output) (z tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"SigmoidGrad\",\n\t\tInput: []tf.Input{\n\t\t\ty, dy,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func dppt01(uplo mat.MatUplo, n int, a, afac, rwork *mat.Vector) (resid float64) {\n\tvar anorm, eps, one, t, zero float64\n\tvar i, k, kc, npp int\n\tvar err error\n\n\tzero = 0.0\n\tone = 1.0\n\n\t// Quick exit if N = 0\n\tif n <= 0 {\n\t\tresid = zero\n\t\treturn\n\t}\n\n\t// Exit with RESID = 1/EPS if ANORM = 0.\n\teps = golapack.Dlamch(Epsilon)\n\tanorm = golapack.Dlansp('1', uplo, n, a, rwork)\n\tif anorm <= zero {\n\t\tresid = one / eps\n\t\treturn\n\t}\n\n\t// Compute the product U'*U, overwriting U.\n\tif uplo == Upper {\n\t\tkc = (n*(n-1))/2 + 1\n\t\tfor k = n; k >= 1; k-- {\n\t\t\t// Compute the (K,K) element of the result.\n\t\t\tt = afac.Off(kc-1).Dot(k, afac.Off(kc-1), 1, 1)\n\t\t\tafac.Set(kc+k-1-1, t)\n\n\t\t\t// Compute the rest of column K.\n\t\t\tif k > 1 {\n\t\t\t\tif err = afac.Off(kc-1).Tpmv(Upper, Trans, NonUnit, k-1, afac, 1); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tkc = kc - (k - 1)\n\t\t\t}\n\t\t}\n\n\t\t// Compute the product L*L', overwriting L.\n\t} else {\n\t\tkc = (n * (n + 1)) / 2\n\t\tfor k = n; k >= 1; k-- {\n\t\t\t// Add a multiple of column K of the factor L to each of\n\t\t\t// columns K+1 through N.\n\t\t\tif k < n {\n\t\t\t\tif err = afac.Off(kc+n-k).Spr(Lower, n-k, one, afac.Off(kc), 1); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Scale column K by the diagonal element.\n\t\t\tt = afac.Get(kc - 1)\n\t\t\tafac.Off(kc-1).Scal(n-k+1, t, 1)\n\n\t\t\tkc = kc - (n - k + 2)\n\t\t}\n\t}\n\n\t// Compute the difference L*L' - A (or U'*U - A).\n\tnpp = n * (n + 1) / 2\n\tfor i = 1; i <= npp; i++ {\n\t\tafac.Set(i-1, afac.Get(i-1)-a.Get(i-1))\n\t}\n\n\t// Compute norm( L*U - A ) / ( N * norm(A) * EPS )\n\tresid = golapack.Dlansp('1', uplo, n, afac, rwork)\n\n\tresid = ((resid / float64(n)) / anorm) / eps\n\n\treturn\n}", "func _cgoexp_e93fccc2f088_add(a *struct {\n\t\tp0 _Ctype_int\n\t\tp1 _Ctype_int\n\t\tr0 _Ctype_int\n\t}) {\n\ta.r0 = add(a.p0, a.p1)\n}", "func MM(a, b Tensor) Tensor {\n\treturn Tensor{C.MM(a.T, b.T)}\n}", "func OptimizeBeta(matches []Match, beta float64) (float64, float64, []float64) {\n\tvar betastep float64 = 0.01 // TODO: set a flag for precision for use here.\n\t// Determine if we need to go up, down, or we have the perfect beta\n\tinitialDiff, _ := AggDiff(matches, beta)\n\tleftDiff, _ := AggDiff(matches, beta-betastep)\n\trightDiff, _ := AggDiff(matches, beta+betastep)\n\n\tvar bestDiff float64\n\tif leftDiff < initialDiff {\n\t\tbetastep = betastep * -1\n\t\tbestDiff = leftDiff\n\t} else if rightDiff < initialDiff {\n\t\tbestDiff = rightDiff\n\t}\n\tbeta = beta + betastep + betastep\n\n\td, diffList := AggDiff(matches, beta)\n\tfor d < bestDiff {\n\t\tbestDiff = d\n\t\tbeta += betastep\n\t\td, diffList = AggDiff(matches, beta)\n\t}\n\treturn bestDiff, beta, diffList\n}", "func VFNMADD231PS_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VFNMADD231PS_Z(mxyz, xyz, k, xyz1) }", "func VFNMADD213PS_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VFNMADD213PS_Z(mxyz, xyz, k, xyz1) }", "func Modadd(a, b, m *ED25519.BIG) *ED25519.BIG {\n\tc := a.Plus(b)\n\tc.Mod(m)\n\treturn c\n}", "func Modadd(a, b, m *ED25519.BIG) *ED25519.BIG {\n\tc := a.Plus(b)\n\tc.Mod(m)\n\treturn c\n}", "func Modadd(a, b, m *ED25519.BIG) *ED25519.BIG {\n\tc := a.Plus(b)\n\tc.Mod(m)\n\treturn c\n}", "func VPADDSW_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VPADDSW_Z(mxyz, xyz, k, xyz1) }", "func BLENDVPD(x, mx, x1 operand.Op) { ctx.BLENDVPD(x, mx, x1) }", "func VFMSUBADD231PD_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VFMSUBADD231PD_Z(mxyz, xyz, k, xyz1) }", "func VADDPS_BCST_Z(m, xyz, k, xyz1 operand.Op) { ctx.VADDPS_BCST_Z(m, xyz, k, xyz1) }", "func VFMSUBADD213PD_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VFMSUBADD213PD_Z(mxyz, xyz, k, xyz1) }", "func LRNBeta(value float32) LRNAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"beta\"] = value\n\t}\n}", "func dot(x_i interface{} , beta interface{} ) interface{} {\n\n\tswitch x_i.(type) {\n\tcase []uint64:\n\t\tres := uint64(0)\n\t\tfor i := range x_i.([]uint64) {\n\t\t\tres += x_i.([]uint64)[i] * beta.([]uint64)[i]\n\t\t}\n\t\treturn res\n\tcase []uint8:\n\t\tres := uint8(0)\n\t\tfor i := range x_i.([]uint8) {\n\t\t\tres += x_i.([]uint8)[i] * beta.([]uint8)[i]\n\t\t}\n\t\treturn res\n\tcase []uint16:\n\t\tres := uint16(0)\n\t\tfor i := range x_i.([]uint16) {\n\t\t\tres += x_i.([]uint16)[i] * beta.([]uint16)[i]\n\t\t}\n\t\treturn res\n\n\tcase []uint32:\n\t\tres := uint32(0)\n\t\tfor i := range x_i.([]uint32) {\n\t\t\tres += x_i.([]uint32)[i] * beta.([]uint32)[i]\n\t\t}\n\t\treturn res\n\n\tcase []int64:\n\t\tres := int64(0)\n\t\tfor i := range x_i.([]int64) {\n\t\t\tres += x_i.([]int64)[i] * beta.([]int64)[i]\n\t\t}\n\t\treturn res\n\n\tcase []int32:\n\t\tres := int32(0)\n\t\tfor i := range x_i.([]int32) {\n\t\t\tres += x_i.([]int32)[i] * beta.([]int32)[i]\n\t\t}\n\t\treturn res\n\n\tcase []int16:\n\t\tres := int16(0)\n\t\tfor i := range x_i.([]int16) {\n\t\t\tres += x_i.([]int16)[i] * beta.([]int16)[i]\n\t\t}\n\t\treturn res\n\n\tcase []int8:\n\t\tres := int8(0)\n\t\tfor i := range x_i.([]int8) {\n\t\t\tres += x_i.([]int8)[i] * beta.([]int8)[i]\n\t\t}\n\t\treturn res\n\n\tcase []int:\n\t\tres := int(0)\n\t\tfor i := range x_i.([]int) {\n\t\t\tres += x_i.([]int)[i] * beta.([]int)[i]\n\t\t}\n\t\treturn res\n\n\tcase []float32:\n\t\tres := float32(0)\n\t\tfor i := range x_i.([]float32) {\n\t\t\tres += x_i.([]float32)[i] * beta.([]float32)[i]\n\t\t}\n\t\treturn res\n\n\tcase []float64:\n\t\tres := float64(0)\n\t\tfor i := range x_i.([]float64) {\n\t\t\tres += x_i.([]float64)[i] * beta.([]float64)[i]\n\t\t}\n\t\treturn res\n\n\tdefault:\n\t\t//_ = t\n\t\tpanic(0)\n\t\t//s := x_i.(t)\n\t\t//for i := range s {\n\t\t//\tfmt.Println(i, s[i], t)\n\t\t//}\n\t}\n\n\t//t := reflect.ValueOf(beta)\n\t//fmt.Println(reflect.TypeOf(x_i).Kind(),s.Len())\n\t//for i := 0; i < s.Len(); i++ {\n\t//\tfmt.Println(s.Index(i), t.Index(i))\n\t//}\n\treturn x_i\n}", "func Gt(a, b interface{}, opts ...FuncOpt) (retVal Tensor, err error) {\n\tad, adok := a.(*Dense)\n\tbd, bdok := b.(*Dense)\n\tswitch {\n\tcase adok && bdok:\n\t\treturn ad.gtDD(bd, opts...)\n\tcase adok && !bdok:\n\t\treturn ad.gtDS(b, opts...)\n\tcase !adok && bdok:\n\t\treturn bd.ltDS(a, opts...)\n\t}\n\n\tpanic(\"unreachable\")\n}", "func rationalm(x float64) float64 {\n\tconst (\n\t\ta0 = -7.81417672390744\n\t\ta1 = 253.88810188892484\n\t\ta2 = 657.9493176902304\n\n\t\tb0 = 1\n\t\tb1 = -60.43958713690808\n\t\tb2 = 99.9856708310761\n\t\tb3 = 682.6073999909428\n\t\tb4 = 962.1784396969866\n\t\tb5 = 1477.9341280760887\n\t)\n\n\treturn (a0 + x*(a1+x*a2)) / (b0 + x*(b1+x*(b2+x*(b3+x*(b4+x*b5)))))\n}", "func (e *GT) Add(a, b *GT) *GT {\n\tif e.p == nil {\n\t\te.p = &gfP12{}\n\t}\n\te.p.Mul(a.p, b.p)\n\treturn e\n}", "func Bvadd(t1 TermT, t2 TermT) TermT {\n\treturn TermT(C.yices_bvadd(C.term_t(t1), C.term_t(t2)))\n}", "func (z *Float64) Plus(y *Float64, a float64) *Float64 {\n\tz.l = y.l + a\n\tz.r = y.r\n\treturn z\n}", "func (z *Rat) Add(x, y *Rat) *Rat {}", "func sumMatrix(mat *DenseMatrix) (sum float64) {\n\tvalues := mat.Array()\n\tsum = float64(0)\n\tfor i := 0; i < len(values); i++ {\n\t\tsum += values[i]\n\t}\n\treturn\n}", "func JNG(r operand.Op) { ctx.JNG(r) }", "func Nbc(param *NbcOptionalParam) (*mat.Dense, nbcModel, *mat.Dense, *mat.Dense, *mat.Dense) {\n params := getParams(\"nbc\")\n timers := getTimers()\n\n disableBacktrace()\n disableVerbose()\n // Detect if the parameter was passed; set if so.\n if param.IncrementalVariance != false {\n setParamBool(params, \"incremental_variance\", param.IncrementalVariance)\n setPassed(params, \"incremental_variance\")\n }\n\n // Detect if the parameter was passed; set if so.\n if param.InputModel != nil {\n setNBCModel(params, \"input_model\", param.InputModel)\n setPassed(params, \"input_model\")\n }\n\n // Detect if the parameter was passed; set if so.\n if param.Labels != nil {\n gonumToArmaUrow(params, \"labels\", param.Labels)\n setPassed(params, \"labels\")\n }\n\n // Detect if the parameter was passed; set if so.\n if param.Test != nil {\n gonumToArmaMat(params, \"test\", param.Test)\n setPassed(params, \"test\")\n }\n\n // Detect if the parameter was passed; set if so.\n if param.Training != nil {\n gonumToArmaMat(params, \"training\", param.Training)\n setPassed(params, \"training\")\n }\n\n // Detect if the parameter was passed; set if so.\n if param.Verbose != false {\n setParamBool(params, \"verbose\", param.Verbose)\n setPassed(params, \"verbose\")\n enableVerbose()\n }\n\n // Mark all output options as passed.\n setPassed(params, \"output\")\n setPassed(params, \"output_model\")\n setPassed(params, \"output_probs\")\n setPassed(params, \"predictions\")\n setPassed(params, \"probabilities\")\n\n // Call the mlpack program.\n C.mlpackNbc(params.mem, timers.mem)\n\n // Initialize result variable and get output.\n var outputPtr mlpackArma\n output := outputPtr.armaToGonumUrow(params, \"output\")\n var outputModel nbcModel\n outputModel.getNBCModel(params, \"output_model\")\n var outputProbsPtr mlpackArma\n outputProbs := outputProbsPtr.armaToGonumMat(params, \"output_probs\")\n var predictionsPtr mlpackArma\n predictions := predictionsPtr.armaToGonumUrow(params, \"predictions\")\n var probabilitiesPtr mlpackArma\n probabilities := probabilitiesPtr.armaToGonumMat(params, \"probabilities\")\n // Clean memory.\n cleanParams(params)\n cleanTimers(timers)\n // Return output(s).\n return output, outputModel, outputProbs, predictions, probabilities\n}", "func VFMSUBADD132PS_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VFMSUBADD132PS_Z(mxyz, xyz, k, xyz1) }", "func NewAdam(lr, beta, beta2, epsilon float64) *Adam {\n\treturn &Adam{\n\t\tlr: fparam(lr, 0.001),\n\t\tbeta: fparam(beta, 0.9),\n\t\tbeta2: fparam(beta2, 0.999),\n\t\tepsilon: fparam(epsilon, 1e-8),\n\t}\n}", "func JG(r operand.Op) { ctx.JG(r) }", "func VHADDPD(mxy, xy, xy1 operand.Op) { ctx.VHADDPD(mxy, xy, xy1) }", "func PAVGW(mx, x operand.Op) { ctx.PAVGW(mx, x) }", "func ADDPD(mx, x operand.Op) { ctx.ADDPD(mx, x) }", "func gradient(f fn, X []float64) []float64 {\n\tvar f0, f1, x_i float64\n\tG := make([]float64, len(X))\n\tf0 = f(X)\n\tfor i := range X {\n\t\tx_i = X[i]\n\t\tX[i] += eps\n\t\tf1 = f(X)\n\t\tG[i] = (f1 - f0) / eps\n\t\tX[i] = x_i\n\t}\n\treturn G\n}", "func dsbt21(uplo mat.MatUplo, n, ka, ks int, a *mat.Matrix, d, e *mat.Vector, u *mat.Matrix, work, result *mat.Vector) {\n\tvar lower bool\n\tvar cuplo mat.MatUplo\n\tvar anorm, one, ulp, unfl, wnorm, zero float64\n\tvar ika, j, jc, jr, lw int\n\tvar err error\n\n\tzero = 0.0\n\tone = 1.0\n\n\t// Constants\n\tresult.Set(0, zero)\n\tresult.Set(1, zero)\n\tif n <= 0 {\n\t\treturn\n\t}\n\n\tika = max(0, min(n-1, ka))\n\tlw = (n * (n + 1)) / 2\n\n\tif uplo == Upper {\n\t\tlower = false\n\t\tcuplo = Upper\n\t} else {\n\t\tlower = true\n\t\tcuplo = Lower\n\t}\n\n\tunfl = golapack.Dlamch(SafeMinimum)\n\tulp = golapack.Dlamch(Epsilon) * golapack.Dlamch(Base)\n\n\t// Some Error Checks\n\t//\n\t// Do Test 1\n\t//\n\t// Norm of A:\n\tanorm = math.Max(golapack.Dlansb('1', cuplo, n, ika, a, work), unfl)\n\n\t// Compute error matrix: Error = A - U S U**T\n\t//\n\t// Copy A from SB to SP storage format.\n\tj = 0\n\tfor jc = 1; jc <= n; jc++ {\n\t\tif lower {\n\t\t\tfor jr = 1; jr <= min(ika+1, n+1-jc); jr++ {\n\t\t\t\tj = j + 1\n\t\t\t\twork.Set(j-1, a.Get(jr-1, jc-1))\n\t\t\t}\n\t\t\tfor jr = ika + 2; jr <= n+1-jc; jr++ {\n\t\t\t\tj = j + 1\n\t\t\t\twork.Set(j-1, zero)\n\t\t\t}\n\t\t} else {\n\t\t\tfor jr = ika + 2; jr <= jc; jr++ {\n\t\t\t\tj = j + 1\n\t\t\t\twork.Set(j-1, zero)\n\t\t\t}\n\t\t\tfor jr = min(ika, jc-1); jr >= 0; jr-- {\n\t\t\t\tj = j + 1\n\t\t\t\twork.Set(j-1, a.Get(ika+1-jr-1, jc-1))\n\t\t\t}\n\t\t}\n\t}\n\n\tfor j = 1; j <= n; j++ {\n\t\terr = work.Spr(cuplo, n, -d.Get(j-1), u.Off(0, j-1).Vector(), 1)\n\t}\n\n\tif n > 1 && ks == 1 {\n\t\tfor j = 1; j <= n-1; j++ {\n\t\t\terr = work.Spr2(cuplo, n, -e.Get(j-1), u.Off(0, j-1).Vector(), 1, u.Off(0, j).Vector(), 1)\n\t\t}\n\t}\n\twnorm = golapack.Dlansp('1', cuplo, n, work, work.Off(lw))\n\n\tif anorm > wnorm {\n\t\tresult.Set(0, (wnorm/anorm)/(float64(n)*ulp))\n\t} else {\n\t\tif anorm < one {\n\t\t\tresult.Set(0, (math.Min(wnorm, float64(n)*anorm)/anorm)/(float64(n)*ulp))\n\t\t} else {\n\t\t\tresult.Set(0, math.Min(wnorm/anorm, float64(n))/(float64(n)*ulp))\n\t\t}\n\t}\n\n\t// Do Test 2\n\t//\n\t// Compute U U**T - I\n\tif err = work.Matrix(n, opts).Gemm(NoTrans, ConjTrans, n, n, n, one, u, u, zero); err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor j = 1; j <= n; j++ {\n\t\twork.Set((n+1)*(j-1), work.Get((n+1)*(j-1))-one)\n\t}\n\n\tresult.Set(1, math.Min(golapack.Dlange('1', n, n, work.Matrix(n, opts), work.Off(pow(n, 2))), float64(n))/(float64(n)*ulp))\n}", "func PADDSB(mx, x operand.Op) { ctx.PADDSB(mx, x) }", "func kgv(a, b int64) int64 {\n\treturn a * b / ggt(a, b)\n}", "func VPADDSB(ops ...operand.Op) { ctx.VPADDSB(ops...) }", "func (z nat) expNN(x, y, m nat) nat {\n\tif alias(z, x) || alias(z, y) {\n\t\t// We cannot allow in place modification of x or y.\n\t\tz = nil\n\t}\n\n\tif len(y) == 0 {\n\t\tz = z.make(1)\n\t\tz[0] = 1\n\t\treturn z\n\t}\n\n\tif m != nil {\n\t\t// We likely end up being as long as the modulus.\n\t\tz = z.make(len(m))\n\t}\n\tz = z.set(x)\n\tv := y[len(y)-1]\n\t// It's invalid for the most significant word to be zero, therefore we\n\t// will find a one bit.\n\tshift := leadingZeros(v) + 1\n\tv <<= shift\n\tvar q nat\n\n\tconst mask = 1 << (_W - 1)\n\n\t// We walk through the bits of the exponent one by one. Each time we\n\t// see a bit, we square, thus doubling the power. If the bit is a one,\n\t// we also multiply by x, thus adding one to the power.\n\n\tw := _W - int(shift)\n\tfor j := 0; j < w; j++ {\n\t\tz = z.mul(z, z)\n\n\t\tif v&mask != 0 {\n\t\t\tz = z.mul(z, x)\n\t\t}\n\n\t\tif m != nil {\n\t\t\tq, z = q.div(z, z, m)\n\t\t}\n\n\t\tv <<= 1\n\t}\n\n\tfor i := len(y) - 2; i >= 0; i-- {\n\t\tv = y[i]\n\n\t\tfor j := 0; j < _W; j++ {\n\t\t\tz = z.mul(z, z)\n\n\t\t\tif v&mask != 0 {\n\t\t\t\tz = z.mul(z, x)\n\t\t\t}\n\n\t\t\tif m != nil {\n\t\t\t\tq, z = q.div(z, z, m)\n\t\t\t}\n\n\t\t\tv <<= 1\n\t\t}\n\t}\n\n\treturn z\n}", "func ADDSD(mx, x operand.Op) { ctx.ADDSD(mx, x) }", "func VPAVGB(ops ...operand.Op) { ctx.VPAVGB(ops...) }", "func RandomGammaGrad(scope *Scope, alpha tf.Output, sample tf.Output) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"RandomGammaGrad\",\n\t\tInput: []tf.Input{\n\t\t\talpha, sample,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}" ]
[ "0.57796353", "0.57367676", "0.5704809", "0.56989944", "0.56069046", "0.559405", "0.55066544", "0.54993755", "0.54840624", "0.54680145", "0.5459018", "0.5447254", "0.5434017", "0.5360158", "0.5337586", "0.5206719", "0.5186619", "0.5166022", "0.5152852", "0.51255774", "0.510653", "0.51063055", "0.50556034", "0.50214773", "0.5006485", "0.49973154", "0.49615946", "0.491971", "0.49091083", "0.48881733", "0.48790464", "0.48453796", "0.48434943", "0.48425424", "0.48393866", "0.48343784", "0.48296842", "0.48073357", "0.48027402", "0.4800802", "0.4779862", "0.47789484", "0.47728992", "0.47677982", "0.476711", "0.47641346", "0.47468385", "0.47434968", "0.47420573", "0.47410697", "0.4738879", "0.47378212", "0.47368702", "0.472103", "0.47139412", "0.46925437", "0.46913645", "0.4690364", "0.46814483", "0.4679681", "0.46468747", "0.46446267", "0.46444508", "0.46386388", "0.46340853", "0.46316406", "0.4628872", "0.4628872", "0.4628872", "0.46285293", "0.46277142", "0.46255255", "0.4619825", "0.460688", "0.4603353", "0.4603071", "0.45812875", "0.4578587", "0.45746368", "0.45731565", "0.45633298", "0.4558343", "0.4553033", "0.4552343", "0.45522758", "0.4545596", "0.4540301", "0.45400932", "0.45347327", "0.45339057", "0.4533641", "0.45174766", "0.45158476", "0.45149758", "0.45137694", "0.4511748", "0.4511304", "0.45073354", "0.45024115", "0.44974977" ]
0.6711675
0
v = vbeta2 + (gradsgrads)(1.0beta2)
func updateV(grads mat.Matrix, state *State, beta2 float64) { state.V.ProdScalarInPlace(beta2) sqGrad := grads.Prod(grads) state.Buf2.ProdMatrixScalarInPlace(sqGrad, 1.0-beta2) state.V.AddInPlace(state.Buf2) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *G1Jac) mulGLV(a *G1Jac, s *big.Int) *G1Jac {\n\n\tvar table [15]G1Jac\n\tvar res G1Jac\n\tvar k1, k2 fr.Element\n\n\tres.Set(&g1Infinity)\n\n\t// table[b3b2b1b0-1] = b3b2*phi(a) + b1b0*a\n\ttable[0].Set(a)\n\ttable[3].phi(a)\n\n\t// split the scalar, modifies +-a, phi(a) accordingly\n\tk := ecc.SplitScalar(s, &glvBasis)\n\n\tif k[0].Sign() == -1 {\n\t\tk[0].Neg(&k[0])\n\t\ttable[0].Neg(&table[0])\n\t}\n\tif k[1].Sign() == -1 {\n\t\tk[1].Neg(&k[1])\n\t\ttable[3].Neg(&table[3])\n\t}\n\n\t// precompute table (2 bits sliding window)\n\t// table[b3b2b1b0-1] = b3b2*phi(a) + b1b0*a if b3b2b1b0 != 0\n\ttable[1].Double(&table[0])\n\ttable[2].Set(&table[1]).AddAssign(&table[0])\n\ttable[4].Set(&table[3]).AddAssign(&table[0])\n\ttable[5].Set(&table[3]).AddAssign(&table[1])\n\ttable[6].Set(&table[3]).AddAssign(&table[2])\n\ttable[7].Double(&table[3])\n\ttable[8].Set(&table[7]).AddAssign(&table[0])\n\ttable[9].Set(&table[7]).AddAssign(&table[1])\n\ttable[10].Set(&table[7]).AddAssign(&table[2])\n\ttable[11].Set(&table[7]).AddAssign(&table[3])\n\ttable[12].Set(&table[11]).AddAssign(&table[0])\n\ttable[13].Set(&table[11]).AddAssign(&table[1])\n\ttable[14].Set(&table[11]).AddAssign(&table[2])\n\n\t// bounds on the lattice base vectors guarantee that k1, k2 are len(r)/2 bits long max\n\tk1.SetBigInt(&k[0]).FromMont()\n\tk2.SetBigInt(&k[1]).FromMont()\n\n\t// loop starts from len(k1)/2 due to the bounds\n\tfor i := int(math.Ceil(fr.Limbs/2. - 1)); i >= 0; i-- {\n\t\tmask := uint64(3) << 62\n\t\tfor j := 0; j < 32; j++ {\n\t\t\tres.Double(&res).Double(&res)\n\t\t\tb1 := (k1[i] & mask) >> (62 - 2*j)\n\t\t\tb2 := (k2[i] & mask) >> (62 - 2*j)\n\t\t\tif b1|b2 != 0 {\n\t\t\t\ts := (b2<<2 | b1)\n\t\t\t\tres.AddAssign(&table[s-1])\n\t\t\t}\n\t\t\tmask = mask >> 2\n\t\t}\n\t}\n\n\tp.Set(&res)\n\treturn p\n}", "func VPAVGB(ops ...operand.Op) { ctx.VPAVGB(ops...) }", "func (g *G1) Double() {\n\t// Reference:\n\t// \"Complete addition formulas for prime order elliptic curves\" by\n\t// Costello-Renes-Batina. [Alg.9] (eprint.iacr.org/2015/1060).\n\tvar R G1\n\tX, Y, Z := &g.x, &g.y, &g.z\n\tX3, Y3, Z3 := &R.x, &R.y, &R.z\n\tvar f0, f1, f2 ff.Fp\n\tt0, t1, t2 := &f0, &f1, &f2\n\t_3B := &g1Params._3b\n\tt0.Sqr(Y) // 1. t0 = Y * Y\n\tZ3.Add(t0, t0) // 2. Z3 = t0 + t0\n\tZ3.Add(Z3, Z3) // 3. Z3 = Z3 + Z3\n\tZ3.Add(Z3, Z3) // 4. Z3 = Z3 + Z3\n\tt1.Mul(Y, Z) // 5. t1 = Y * Z\n\tt2.Sqr(Z) // 6. t2 = Z * Z\n\tt2.Mul(_3B, t2) // 7. t2 = b3 * t2\n\tX3.Mul(t2, Z3) // 8. X3 = t2 * Z3\n\tY3.Add(t0, t2) // 9. Y3 = t0 + t2\n\tZ3.Mul(t1, Z3) // 10. Z3 = t1 * Z3\n\tt1.Add(t2, t2) // 11. t1 = t2 + t2\n\tt2.Add(t1, t2) // 12. t2 = t1 + t2\n\tt0.Sub(t0, t2) // 13. t0 = t0 - t2\n\tY3.Mul(t0, Y3) // 14. Y3 = t0 * Y3\n\tY3.Add(X3, Y3) // 15. Y3 = X3 + Y3\n\tt1.Mul(X, Y) // 16. t1 = X * Y\n\tX3.Mul(t0, t1) // 17. X3 = t0 * t1\n\tX3.Add(X3, X3) // 18. X3 = X3 + X3\n\t*g = R\n}", "func Bvadd(t1 TermT, t2 TermT) TermT {\n\treturn TermT(C.yices_bvadd(C.term_t(t1), C.term_t(t2)))\n}", "func VPADDSB(ops ...operand.Op) { ctx.VPADDSB(ops...) }", "func VPAVGW(ops ...operand.Op) { ctx.VPAVGW(ops...) }", "func VADDSD(ops ...operand.Op) { ctx.VADDSD(ops...) }", "func VADDSS(ops ...operand.Op) { ctx.VADDSS(ops...) }", "func VADDPD(ops ...operand.Op) { ctx.VADDPD(ops...) }", "func VADDPS(ops ...operand.Op) { ctx.VADDPS(ops...) }", "func Dlagv2(a, b *mat.Matrix, alphar, alphai, beta *mat.Vector) (csl, snl, csr, snr float64) {\n\tvar anorm, ascale, bnorm, bscale, h1, h2, h3, one, qq, rr, safmin, scale1, ulp, wi, wr1, zero float64\n\n\tzero = 0.0\n\tone = 1.0\n\n\tsafmin = Dlamch(SafeMinimum)\n\tulp = Dlamch(Precision)\n\n\t// Scale A\n\tanorm = math.Max(math.Abs(a.Get(0, 0))+math.Abs(a.Get(1, 0)), math.Max(math.Abs(a.Get(0, 1))+math.Abs(a.Get(1, 1)), safmin))\n\tascale = one / anorm\n\ta.Set(0, 0, ascale*a.Get(0, 0))\n\ta.Set(0, 1, ascale*a.Get(0, 1))\n\ta.Set(1, 0, ascale*a.Get(1, 0))\n\ta.Set(1, 1, ascale*a.Get(1, 1))\n\n\t// Scale B\n\tbnorm = math.Max(math.Abs(b.Get(0, 0)), math.Max(math.Abs(b.Get(0, 1))+math.Abs(b.Get(1, 1)), safmin))\n\tbscale = one / bnorm\n\tb.Set(0, 0, bscale*b.Get(0, 0))\n\tb.Set(0, 1, bscale*b.Get(0, 1))\n\tb.Set(1, 1, bscale*b.Get(1, 1))\n\n\t// Check if A can be deflated\n\tif math.Abs(a.Get(1, 0)) <= ulp {\n\t\tcsl = one\n\t\tsnl = zero\n\t\tcsr = one\n\t\tsnr = zero\n\t\ta.Set(1, 0, zero)\n\t\tb.Set(1, 0, zero)\n\t\twi = zero\n\n\t\t// Check if B is singular\n\t} else if math.Abs(b.Get(0, 0)) <= ulp {\n\t\tcsl, snl, _ = Dlartg(a.Get(0, 0), a.Get(1, 0))\n\t\tcsr = one\n\t\tsnr = zero\n\t\ta.Off(1, 0).Vector().Rot(2, a.Off(0, 0).Vector(), a.Rows, a.Rows, csl, snl)\n\t\tb.Off(1, 0).Vector().Rot(2, b.Off(0, 0).Vector(), b.Rows, b.Rows, csl, snl)\n\t\ta.Set(1, 0, zero)\n\t\tb.Set(0, 0, zero)\n\t\tb.Set(1, 0, zero)\n\t\twi = zero\n\n\t} else if math.Abs(b.Get(1, 1)) <= ulp {\n\t\tcsr, snr, _ = Dlartg(a.Get(1, 1), a.Get(1, 0))\n\t\tsnr = -snr\n\t\ta.Off(0, 1).Vector().Rot(2, a.Off(0, 0).Vector(), 1, 1, csr, snr)\n\t\tb.Off(0, 1).Vector().Rot(2, b.Off(0, 0).Vector(), 1, 1, csr, snr)\n\t\tcsl = one\n\t\tsnl = zero\n\t\ta.Set(1, 0, zero)\n\t\tb.Set(1, 0, zero)\n\t\tb.Set(1, 1, zero)\n\t\twi = zero\n\n\t} else {\n\t\t// B is nonsingular, first compute the eigenvalues of (A,B)\n\t\tscale1, _, wr1, _, wi = Dlag2(a, b, safmin)\n\n\t\tif wi == zero {\n\t\t\t// two real eigenvalues, compute s*A-w*B\n\t\t\th1 = scale1*a.Get(0, 0) - wr1*b.Get(0, 0)\n\t\t\th2 = scale1*a.Get(0, 1) - wr1*b.Get(0, 1)\n\t\t\th3 = scale1*a.Get(1, 1) - wr1*b.Get(1, 1)\n\n\t\t\trr = Dlapy2(h1, h2)\n\t\t\tqq = Dlapy2(scale1*a.Get(1, 0), h3)\n\n\t\t\tif rr > qq {\n\t\t\t\t// find right rotation matrix to zero 1,1 element of\n\t\t\t\t// (sA - wB)\n\t\t\t\tcsr, snr, _ = Dlartg(h2, h1)\n\n\t\t\t} else {\n\t\t\t\t// find right rotation matrix to zero 2,1 element of\n\t\t\t\t// (sA - wB)\n\t\t\t\tcsr, snr, _ = Dlartg(h3, scale1*a.Get(1, 0))\n\n\t\t\t}\n\n\t\t\tsnr = -snr\n\t\t\ta.Off(0, 1).Vector().Rot(2, a.Off(0, 0).Vector(), 1, 1, csr, snr)\n\t\t\tb.Off(0, 1).Vector().Rot(2, b.Off(0, 0).Vector(), 1, 1, csr, snr)\n\n\t\t\t// compute inf norms of A and B\n\t\t\th1 = math.Max(math.Abs(a.Get(0, 0))+math.Abs(a.Get(0, 1)), math.Abs(a.Get(1, 0))+math.Abs(a.Get(1, 1)))\n\t\t\th2 = math.Max(math.Abs(b.Get(0, 0))+math.Abs(b.Get(0, 1)), math.Abs(b.Get(1, 0))+math.Abs(b.Get(1, 1)))\n\n\t\t\tif (scale1 * h1) >= math.Abs(wr1)*h2 {\n\t\t\t\t// find left rotation matrix Q to zero out B(2,1)\n\t\t\t\tcsl, snl, _ = Dlartg(b.Get(0, 0), b.Get(1, 0))\n\n\t\t\t} else {\n\t\t\t\t// find left rotation matrix Q to zero out A(2,1)\n\t\t\t\tcsl, snl, _ = Dlartg(a.Get(0, 0), a.Get(1, 0))\n\n\t\t\t}\n\n\t\t\ta.Off(1, 0).Vector().Rot(2, a.Off(0, 0).Vector(), a.Rows, a.Rows, csl, snl)\n\t\t\tb.Off(1, 0).Vector().Rot(2, b.Off(0, 0).Vector(), b.Rows, b.Rows, csl, snl)\n\n\t\t\ta.Set(1, 0, zero)\n\t\t\tb.Set(1, 0, zero)\n\n\t\t} else {\n\t\t\t// a pair of complex conjugate eigenvalues\n\t\t\t// first compute the SVD of the matrix B\n\t\t\t_, _, snr, csr, snl, csl = Dlasv2(b.Get(0, 0), b.Get(0, 1), b.Get(1, 1))\n\n\t\t\t// Form (A,B) := Q(A,B)Z**T where Q is left rotation matrix and\n\t\t\t// Z is right rotation matrix computed from DLASV2\n\t\t\ta.Off(1, 0).Vector().Rot(2, a.Off(0, 0).Vector(), a.Rows, a.Rows, csl, snl)\n\t\t\tb.Off(1, 0).Vector().Rot(2, b.Off(0, 0).Vector(), b.Rows, b.Rows, csl, snl)\n\t\t\ta.Off(0, 1).Vector().Rot(2, a.Off(0, 0).Vector(), 1, 1, csr, snr)\n\t\t\tb.Off(0, 1).Vector().Rot(2, b.Off(0, 0).Vector(), 1, 1, csr, snr)\n\n\t\t\tb.Set(1, 0, zero)\n\t\t\tb.Set(0, 1, zero)\n\n\t\t}\n\n\t}\n\n\t// Unscaling\n\ta.Set(0, 0, anorm*a.Get(0, 0))\n\ta.Set(1, 0, anorm*a.Get(1, 0))\n\ta.Set(0, 1, anorm*a.Get(0, 1))\n\ta.Set(1, 1, anorm*a.Get(1, 1))\n\tb.Set(0, 0, bnorm*b.Get(0, 0))\n\tb.Set(1, 0, bnorm*b.Get(1, 0))\n\tb.Set(0, 1, bnorm*b.Get(0, 1))\n\tb.Set(1, 1, bnorm*b.Get(1, 1))\n\n\tif wi == zero {\n\t\talphar.Set(0, a.Get(0, 0))\n\t\talphar.Set(1, a.Get(1, 1))\n\t\talphai.Set(0, zero)\n\t\talphai.Set(1, zero)\n\t\tbeta.Set(0, b.Get(0, 0))\n\t\tbeta.Set(1, b.Get(1, 1))\n\t} else {\n\t\talphar.Set(0, anorm*wr1/scale1/bnorm)\n\t\talphai.Set(0, anorm*wi/scale1/bnorm)\n\t\talphar.Set(1, alphar.Get(0))\n\t\talphai.Set(1, -alphai.Get(0))\n\t\tbeta.Set(0, one)\n\t\tbeta.Set(1, one)\n\t}\n\n\treturn\n}", "func (s VectOp) Plusv(v []float64) VectOp {\n\treturn fs.Plusv(s, v)\n}", "func BLENDVPS(x, mx, x1 operand.Op) { ctx.BLENDVPS(x, mx, x1) }", "func _cgoexp_e93fccc2f088_add(a *struct {\n\t\tp0 _Ctype_int\n\t\tp1 _Ctype_int\n\t\tr0 _Ctype_int\n\t}) {\n\ta.r0 = add(a.p0, a.p1)\n}", "func VPADDSW(ops ...operand.Op) { ctx.VPADDSW(ops...) }", "func VPADDW(ops ...operand.Op) { ctx.VPADDW(ops...) }", "func gammainv(probability, alpha, beta float64) float64 {\n\txLo, xHi := 0.0, alpha*beta*5\n\tdx, x, xNew, result := 1024.0, 1.0, 1.0, 0.0\n\tfor i := 0; math.Abs(dx) > 8.88e-016 && i <= 256; i++ {\n\t\tresult = incompleteGamma(alpha, x/beta) / math.Gamma(alpha)\n\t\te := result - probability\n\t\tif e == 0 {\n\t\t\tdx = 0\n\t\t} else if e < 0 {\n\t\t\txLo = x\n\t\t} else {\n\t\t\txHi = x\n\t\t}\n\t\tpdf := (1 / (math.Pow(beta, alpha) * math.Gamma(alpha))) * math.Pow(x, alpha-1) * math.Exp(0-(x/beta))\n\t\tif pdf != 0 {\n\t\t\tdx = e / pdf\n\t\t\txNew = x - dx\n\t\t}\n\t\tif xNew < xLo || xNew > xHi || pdf == 0 {\n\t\t\txNew = (xLo + xHi) / 2\n\t\t\tdx = xNew - x\n\t\t}\n\t\tx = xNew\n\t}\n\treturn x\n}", "func (a Vec4) Plus(b Vec4) Vec4 {\n\treturn Vec4{a.X + b.X, a.Y + b.Y, a.Z + b.Z, a.W + b.W}\n}", "func VPHADDSW(mxy, xy, xy1 operand.Op) { ctx.VPHADDSW(mxy, xy, xy1) }", "func InvGrad(scope *Scope, y tf.Output, dy tf.Output) (z tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"InvGrad\",\n\t\tInput: []tf.Input{\n\t\t\ty, dy,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func getBeta(fAlpha, fBeta float64) float64 {\n\tvar fA, fB float64\n\tif fAlpha > fBeta {\n\t\tfA = fAlpha\n\t\tfB = fBeta\n\t} else {\n\t\tfA = fBeta\n\t\tfB = fAlpha\n\t}\n\tconst maxGammaArgument = 171.624376956302\n\tif fA+fB < maxGammaArgument {\n\t\treturn math.Gamma(fA) / math.Gamma(fA+fB) * math.Gamma(fB)\n\t}\n\tfg := 6.024680040776729583740234375\n\tfgm := fg - 0.5\n\tfLanczos := getLanczosSum(fA)\n\tfLanczos /= getLanczosSum(fA + fB)\n\tfLanczos *= getLanczosSum(fB)\n\tfABgm := fA + fB + fgm\n\tfLanczos *= math.Sqrt((fABgm / (fA + fgm)) / (fB + fgm))\n\tfTempA := fB / (fA + fgm)\n\tfTempB := fA / (fB + fgm)\n\tfResult := math.Exp(-fA*math.Log1p(fTempA) - fB*math.Log1p(fTempB) - fgm)\n\tfResult *= fLanczos\n\treturn fResult\n}", "func updateM(grads mat.Matrix, state *State, beta1 float64) {\n\tstate.M.ProdScalarInPlace(beta1)\n\tstate.Buf1.ProdMatrixScalarInPlace(grads, 1.0-beta1)\n\tstate.M.AddInPlace(state.Buf1)\n}", "func VPSRAVD(ops ...operand.Op) { ctx.VPSRAVD(ops...) }", "func rprop(f func(Vector) (Scalar, error), x0 ConstVector, step_init float64 , eta []float64,\n epsilon Epsilon,\n maxIterations MaxIterations,\n hook Hook,\n constraints Constraints) (Vector, error) {\n\n n := x0.Dim()\n t := x0.ElementType()\n // copy variables\n x1 := AsDenseRealVector(x0)\n x2 := AsDenseRealVector(x0)\n // step size for each variable\n step := make([]float64, n)\n // gradients\n gradient_new := make([]float64, n)\n gradient_old := make([]float64, n)\n // initialize values\n for i := 0; i < x1.Dim(); i++ {\n step[i] = step_init\n gradient_new[i] = 1\n gradient_old[i] = 1\n }\n if err := x1.Variables(1); err != nil {\n return nil, err\n }\n gradient_is_nan := func(s Scalar) bool {\n for i := 0; i < s.GetN(); i++ {\n if math.IsNaN(s.GetDerivative(i)) {\n return true\n }\n }\n return false\n }\n // check initial value\n if constraints.Value != nil && !constraints.Value(x1) {\n return x1, fmt.Errorf(\"invalid initial value: %v\", x1)\n }\n // evaluate objective function\n s, err := f(x1)\n if err != nil {\n return x1, fmt.Errorf(\"invalid initial value: %v\", x1)\n }\n if gradient_is_nan(s) {\n return x1, fmt.Errorf(\"gradient is NaN for initial value: %v\", x1)\n }\n for i := 0; i < maxIterations.Value; i++ {\n for i := 0; i < x1.Dim(); i++ {\n gradient_old[i] = gradient_new[i]\n }\n // compute partial derivatives and update x\n for i := 0; i < x1.Dim(); i++ {\n // save derivative\n gradient_new[i] = s.GetDerivative(i)\n }\n // execute hook if available\n if hook.Value != nil && hook.Value(gradient_new, step, x1, s) {\n break;\n }\n // evaluate stop criterion\n if (Norm(gradient_new) < epsilon.Value) {\n break;\n }\n // update step size\n for i := 0; i < x1.Dim(); i++ {\n if gradient_new[i] != 0.0 {\n if ((gradient_old[i] < 0 && gradient_new[i] < 0) ||\n (gradient_old[i] > 0 && gradient_new[i] > 0)) {\n step[i] *= eta[0]\n } else {\n step[i] *= eta[1]\n }\n }\n }\n for {\n // update x\n for i := 0; i < x1.Dim(); i++ {\n if gradient_new[i] != 0.0 {\n if gradient_new[i] > 0.0 {\n x2.At(i).Sub(x1.At(i), NewScalar(t, step[i]))\n } else {\n x2.At(i).Add(x1.At(i), NewScalar(t, step[i]))\n }\n }\n if math.IsNaN(x2.At(i).GetValue()) {\n return x2, fmt.Errorf(\"NaN value detected\")\n }\n }\n // evaluate objective function\n s, err = f(x2)\n if err != nil || gradient_is_nan(s) ||\n (constraints.Value != nil && !constraints.Value(x2)) {\n // if the updated is invalid reduce step size\n for i := 0; i < x1.Dim(); i++ {\n if gradient_new[i] != 0.0 {\n step[i] *= eta[1]\n }\n }\n } else {\n // new position is valid, exit loop\n break\n }\n }\n x1.Set(x2)\n }\n return x1, nil\n}", "func calcBetainv(probability, alpha, beta, lower, upper float64) float64 {\n\tminCumulative, maxCumulative := 1.0e-300, 3.0e-308\n\tlowerBound, upperBound := maxCumulative, 1.0-2.22e-16\n\tneedSwap := false\n\tvar alpha1, alpha2, beta1, beta2, beta3, prob1, x, y float64\n\tif probability <= 0.5 {\n\t\tprob1, alpha1, beta1 = probability, alpha, beta\n\t} else {\n\t\tprob1, alpha1, beta1, needSwap = 1.0-probability, beta, alpha, true\n\t}\n\tlogBetaNum := logBeta(alpha, beta)\n\tprob2 := math.Sqrt(-math.Log(prob1 * prob1))\n\tprob3 := prob2 - (prob2*0.27061+2.3075)/(prob2*(prob2*0.04481+0.99229)+1)\n\tif alpha1 > 1 && beta1 > 1 {\n\t\talpha2, beta2, prob2 = 1/(alpha1+alpha1-1), 1/(beta1+beta1-1), (prob3*prob3-3)/6\n\t\tx = 2 / (alpha2 + beta2)\n\t\ty = prob3*math.Sqrt(x+prob2)/x - (beta2-alpha2)*(prob2+5/6.0-2/(x*3))\n\t\tbeta3 = alpha1 / (alpha1 + beta1*math.Exp(y+y))\n\t} else {\n\t\tbeta2, prob2 = 1/(beta1*9), beta1+beta1\n\t\tbeta2 = prob2 * math.Pow(1-beta2+prob3*math.Sqrt(beta2), 3)\n\t\tif beta2 <= 0 {\n\t\t\tbeta3 = 1 - math.Exp((math.Log((1-prob1)*beta1)+logBetaNum)/beta1)\n\t\t} else {\n\t\t\tbeta2 = (prob2 + alpha1*4 - 2) / beta2\n\t\t\tif beta2 <= 1 {\n\t\t\t\tbeta3 = math.Exp((logBetaNum + math.Log(alpha1*prob1)) / alpha1)\n\t\t\t} else {\n\t\t\t\tbeta3 = 1 - 2/(beta2+1)\n\t\t\t}\n\t\t}\n\t}\n\tbeta2, prob2 = 1-beta1, 1-alpha1\n\tif beta3 < lowerBound {\n\t\tbeta3 = lowerBound\n\t} else if beta3 > upperBound {\n\t\tbeta3 = upperBound\n\t}\n\talpha3 := math.Max(minCumulative, math.Pow(10.0, -13.0-2.5/(alpha1*alpha1)-0.5/(prob1*prob1)))\n\tbeta3 = betainvProbIterator(alpha1, alpha3, beta1, beta2, beta3, logBetaNum, maxCumulative, prob1, prob2)\n\tif needSwap {\n\t\tbeta3 = 1.0 - beta3\n\t}\n\treturn (upper-lower)*beta3 + lower\n}", "func BLENDVPD(x, mx, x1 operand.Op) { ctx.BLENDVPD(x, mx, x1) }", "func VPSADBW(mxyz, xyz, xyz1 operand.Op) { ctx.VPSADBW(mxyz, xyz, xyz1) }", "func (v *Vector) Plus(a *Vector) *Vector {\n\treturn &Vector{X: v.X + a.X, Y: v.Y + a.Y, Z: v.Z + a.Z}\n}", "func BiasAddV1(scope *Scope, value tf.Output, bias tf.Output) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"BiasAddV1\",\n\t\tInput: []tf.Input{\n\t\t\tvalue, bias,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func blasadd(g1, g2 blas64.General) blas64.General {\n\t// first make a copy of g1\n\tg3 := blas64.General{\n\t\tRows: g1.Rows,\n\t\tCols: g1.Cols,\n\t\tStride: g1.Stride,\n\t\tData: make([]float64, len(g1.Data)),\n\t}\n\tfor i, v := range g1.Data {\n\t\tg3.Data[i] = v\n\t}\n\tblas64.Gemm(blas.NoTrans, blas.NoTrans, 1.0, eye(g1.Rows), g2, 1.0, g3)\n\treturn g3\n}", "func VHADDPD(mxy, xy, xy1 operand.Op) { ctx.VHADDPD(mxy, xy, xy1) }", "func VPSRLVQ(ops ...operand.Op) { ctx.VPSRLVQ(ops...) }", "func LRNGradBeta(value float32) LRNGradAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"beta\"] = value\n\t}\n}", "func add(a, b float64) float64 {\n\treturn a + b\n}", "func VHADDPS(mxy, xy, xy1 operand.Op) { ctx.VHADDPS(mxy, xy, xy1) }", "func VPADDUSW(ops ...operand.Op) { ctx.VPADDUSW(ops...) }", "func VPSRAD(ops ...operand.Op) { ctx.VPSRAD(ops...) }", "func VADDPD_RN_SAE(ops ...operand.Op) { ctx.VADDPD_RN_SAE(ops...) }", "func VPHADDW(mxy, xy, xy1 operand.Op) { ctx.VPHADDW(mxy, xy, xy1) }", "func Vadd(input1 []float32, input1Stride int, input2 []float32, input2Stride int, output []float32, outputStride int) {\n\tC.vDSP_vadd((*C.float)(&input1[0]), C.vDSP_Stride(input1Stride), (*C.float)(&input2[0]), C.vDSP_Stride(input2Stride), (*C.float)(&output[0]), C.vDSP_Stride(outputStride), minLen(len(input1)/input1Stride, len(input2)/input2Stride, len(output)/outputStride))\n}", "func VADDPD_RZ_SAE(ops ...operand.Op) { ctx.VADDPD_RZ_SAE(ops...) }", "func (a Vector3) Plus(b Vector3) Vector3 {\n\treturn Vector3{a.X + b.X, a.Y + b.Y, a.Z + b.Z}\n}", "func add(x float64,y float64) float64 {\n\treturn x+y\n}", "func VGETEXPSD(ops ...operand.Op) { ctx.VGETEXPSD(ops...) }", "func (z *Rat) Add(x, y *Rat) *Rat {}", "func OptimizeBeta(matches []Match, beta float64) (float64, float64, []float64) {\n\tvar betastep float64 = 0.01 // TODO: set a flag for precision for use here.\n\t// Determine if we need to go up, down, or we have the perfect beta\n\tinitialDiff, _ := AggDiff(matches, beta)\n\tleftDiff, _ := AggDiff(matches, beta-betastep)\n\trightDiff, _ := AggDiff(matches, beta+betastep)\n\n\tvar bestDiff float64\n\tif leftDiff < initialDiff {\n\t\tbetastep = betastep * -1\n\t\tbestDiff = leftDiff\n\t} else if rightDiff < initialDiff {\n\t\tbestDiff = rightDiff\n\t}\n\tbeta = beta + betastep + betastep\n\n\td, diffList := AggDiff(matches, beta)\n\tfor d < bestDiff {\n\t\tbestDiff = d\n\t\tbeta += betastep\n\t\td, diffList = AggDiff(matches, beta)\n\t}\n\treturn bestDiff, beta, diffList\n}", "func VPABSD(ops ...operand.Op) { ctx.VPABSD(ops...) }", "func AddV2(scope *Scope, x tf.Output, y tf.Output) (z tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"AddV2\",\n\t\tInput: []tf.Input{\n\t\t\tx, y,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func VADDPS_RN_SAE(ops ...operand.Op) { ctx.VADDPS_RN_SAE(ops...) }", "func RatAdd(z *big.Rat, x, y *big.Rat,) *big.Rat", "func brandes(g graph.Graph, accumulate func(s graph.Node, stack linear.NodeStack, p map[int64][]graph.Node, delta, sigma map[int64]float64)) {\n\tvar (\n\t\tnodes = graph.NodesOf(g.Nodes())\n\t\tstack linear.NodeStack\n\t\tp = make(map[int64][]graph.Node, len(nodes))\n\t\tsigma = make(map[int64]float64, len(nodes))\n\t\td = make(map[int64]int, len(nodes))\n\t\tdelta = make(map[int64]float64, len(nodes))\n\t\tqueue linear.NodeQueue\n\t)\n\tfor _, s := range nodes {\n\t\tstack = stack[:0]\n\n\t\tfor _, w := range nodes {\n\t\t\tp[w.ID()] = p[w.ID()][:0]\n\t\t}\n\n\t\tfor _, t := range nodes {\n\t\t\tsigma[t.ID()] = 0\n\t\t\td[t.ID()] = -1\n\t\t}\n\t\tsigma[s.ID()] = 1\n\t\td[s.ID()] = 0\n\n\t\tqueue.Enqueue(s)\n\t\tfor queue.Len() != 0 {\n\t\t\tv := queue.Dequeue()\n\t\t\tvid := v.ID()\n\t\t\tstack.Push(v)\n\t\t\tto := g.From(vid)\n\t\t\tfor to.Next() {\n\t\t\t\tw := to.Node()\n\t\t\t\twid := w.ID()\n\t\t\t\t// w found for the first time?\n\t\t\t\tif d[wid] < 0 {\n\t\t\t\t\tqueue.Enqueue(w)\n\t\t\t\t\td[wid] = d[vid] + 1\n\t\t\t\t}\n\t\t\t\t// shortest path to w via v?\n\t\t\t\tif d[wid] == d[vid]+1 {\n\t\t\t\t\tsigma[wid] += sigma[vid]\n\t\t\t\t\tp[wid] = append(p[wid], v)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor _, v := range nodes {\n\t\t\tdelta[v.ID()] = 0\n\t\t}\n\n\t\t// S returns vertices in order of non-increasing distance from s\n\t\taccumulate(s, stack, p, delta, sigma)\n\t}\n}", "func (c *Context) BLENDVPS(x, mx, x1 operand.Op) {\n\tc.addinstruction(x86.BLENDVPS(x, mx, x1))\n}", "func VPSRAVW(ops ...operand.Op) { ctx.VPSRAVW(ops...) }", "func (z *Float64) Plus(y *Float64, a float64) *Float64 {\n\tz.l = y.l + a\n\tz.r = y.r\n\treturn z\n}", "func (o *Adam) Update(value, gradient float64, t, idx int) float64 {\n\tlrt := o.lr * (math.Sqrt(1.0 - math.Pow(o.beta2, float64(t)))) /\n\t\t(1.0 - math.Pow(o.beta, float64(t)))\n\to.m[idx] = o.beta*o.m[idx] + (1.0-o.beta)*gradient\n\to.v[idx] = o.beta2*o.v[idx] + (1.0-o.beta2)*math.Pow(gradient, 2.0)\n\n\treturn -lrt * (o.m[idx] / (math.Sqrt(o.v[idx]) + o.epsilon))\n}", "func PAVGB(mx, x operand.Op) { ctx.PAVGB(mx, x) }", "func VADDSS_RN_SAE(ops ...operand.Op) { ctx.VADDSS_RN_SAE(ops...) }", "func VPSRLD(ops ...operand.Op) { ctx.VPSRLD(ops...) }", "func VADDPD_RU_SAE(ops ...operand.Op) { ctx.VADDPD_RU_SAE(ops...) }", "func PAVGW(mx, x operand.Op) { ctx.PAVGW(mx, x) }", "func VPSLLVQ(ops ...operand.Op) { ctx.VPSLLVQ(ops...) }", "func VDBPSADBW(ops ...operand.Op) { ctx.VDBPSADBW(ops...) }", "func VADDSD_RN_SAE(ops ...operand.Op) { ctx.VADDSD_RN_SAE(ops...) }", "func VPDPBUSD(ops ...operand.Op) { ctx.VPDPBUSD(ops...) }", "func blasmul(g1, g2 blas64.General) blas64.General {\n\t// first the receiver\n\tg3 := blas64.General{\n\t\tRows: g1.Rows,\n\t\tCols: g2.Cols,\n\t\tStride: g2.Stride,\n\t\tData: make([]float64, g1.Rows*g2.Stride),\n\t}\n\tblas64.Gemm(blas.NoTrans, blas.NoTrans, 1.0, g1, g2, 0.0, g3)\n\treturn g3\n}", "func value(player int, board [8][8]int, alpha float32, beta float32, depth int) float32 {\n\tval, _ := AlphaBeta(enemy(player), board, -beta, -alpha, depth-1)\n\n\treturn -val\n}", "func BiasAddGrad(scope *Scope, out_backprop tf.Output, optional ...BiasAddGradAttr) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"BiasAddGrad\",\n\t\tInput: []tf.Input{\n\t\t\tout_backprop,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func addFloat(a, b float64) float64 {\n\treturn a + b\n}", "func VPADDSB_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VPADDSB_Z(mxyz, xyz, k, xyz1) }", "func VADDPD_BCST(ops ...operand.Op) { ctx.VADDPD_BCST(ops...) }", "func Vsadd(input []float32, inputStride int, add float32, output []float32, outputStride int) {\n\tC.vDSP_vsadd((*C.float)(&input[0]), C.vDSP_Stride(inputStride), (*C.float)(&add), (*C.float)(&output[0]), C.vDSP_Stride(outputStride), C.vDSP_Length(len(output)/outputStride))\n}", "func VADDPD_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VADDPD_Z(mxyz, xyz, k, xyz1) }", "func Bvsum(t []TermT) TermT {\n\tcount := C.uint32_t(len(t))\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\tif count == 0 {\n\t\treturn NullTerm\n\t}\n\treturn TermT(C.yices_bvsum(count, (*C.term_t)(&t[0])))\n}", "func VADDPS_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VADDPS_Z(mxyz, xyz, k, xyz1) }", "func VPSHLDVQ(ops ...operand.Op) { ctx.VPSHLDVQ(ops...) }", "func pbetaRaw(alnsml, ans, eps, p, pin, q, sml, x, y float64) float64 {\n\tif q > 1.0 {\n\t\txb := p*math.Log(y) + q*math.Log(1.0-y) - logBeta(p, q) - math.Log(q)\n\t\tib := int(math.Max(xb/alnsml, 0.0))\n\t\tterm := math.Exp(xb - float64(ib)*alnsml)\n\t\tc := 1.0 / (1.0 - y)\n\t\tp1 := q * c / (p + q - 1.0)\n\t\tfinsum := 0.0\n\t\tn := int(q)\n\t\tif q == float64(n) {\n\t\t\tn = n - 1\n\t\t}\n\t\tfor i := 1; i <= n; i++ {\n\t\t\tif p1 <= 1 && term/eps <= finsum {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\txi := float64(i)\n\t\t\tterm = (q - xi + 1.0) * c * term / (p + q - xi)\n\t\t\tif term > 1.0 {\n\t\t\t\tib = ib - 1\n\t\t\t\tterm = term * sml\n\t\t\t}\n\t\t\tif ib == 0 {\n\t\t\t\tfinsum = finsum + term\n\t\t\t}\n\t\t}\n\t\tans = ans + finsum\n\t}\n\tif y != x || p != pin {\n\t\tans = 1.0 - ans\n\t}\n\tans = math.Max(math.Min(ans, 1.0), 0.0)\n\treturn ans\n}", "func BlockLSTMGradV2(scope *Scope, seq_len_max tf.Output, x tf.Output, cs_prev tf.Output, h_prev tf.Output, w tf.Output, wci tf.Output, wcf tf.Output, wco tf.Output, b tf.Output, i tf.Output, cs tf.Output, f tf.Output, o tf.Output, ci tf.Output, co tf.Output, h tf.Output, cs_grad tf.Output, h_grad tf.Output, use_peephole bool) (x_grad tf.Output, cs_prev_grad tf.Output, h_prev_grad tf.Output, w_grad tf.Output, wci_grad tf.Output, wcf_grad tf.Output, wco_grad tf.Output, b_grad tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{\"use_peephole\": use_peephole}\n\topspec := tf.OpSpec{\n\t\tType: \"BlockLSTMGradV2\",\n\t\tInput: []tf.Input{\n\t\t\tseq_len_max, x, cs_prev, h_prev, w, wci, wcf, wco, b, i, cs, f, o, ci, co, h, cs_grad, h_grad,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0), op.Output(1), op.Output(2), op.Output(3), op.Output(4), op.Output(5), op.Output(6), op.Output(7)\n}", "func VPSRLVD(ops ...operand.Op) { ctx.VPSRLVD(ops...) }", "func VacancyGSR(ctx context.Context, xbiz *XBusiness, rid int64, d1, d2 *time.Time) (float64, error) {\n\tvar err error\n\tamt := float64(0)\n\t// Console(\"*** Calling VacancyDetect: %s - %s, rid = %d\\n\", d1.Format(RRDATEFMTSQL), d2.Format(RRDATEFMTSQL), rid)\n\tm, err := VacancyDetect(ctx, xbiz, d1, d2, rid)\n\tif err != nil {\n\t\treturn amt, err\n\t}\n\n\tfor i := 0; i < len(m); i++ {\n\t\tamt += m[i].Amount\n\t}\n\n\treturn amt, err\n}", "func VPSRLVW(ops ...operand.Op) { ctx.VPSRLVW(ops...) }", "func ReluGrad(scope *Scope, gradients tf.Output, features tf.Output) (backprops tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"ReluGrad\",\n\t\tInput: []tf.Input{\n\t\t\tgradients, features,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func VPAVGB_Z(mxyz, xyz, k, xyz1 operand.Op) { ctx.VPAVGB_Z(mxyz, xyz, k, xyz1) }", "func goAdd(args ...yObj) yObj {\n\tvar (\n\t\tsumt int64 = tIntnum\n\t\tisum int64\n\t\tfsum float64\n\t\trsum rational\n\t\tcsum complex128\n\t)\n\n\targs0 := args[0]\n\tl := length(args0)\n\tif l == 0 {\n\t\treturn yZERO\n\t}\n\tif l == 1 {\n\t\treturn pair(args0).car\n\t}\n\tp := args0\n\tfor i := 0; i < l; i++ {\n\t\tval := pair(p).car\n\t\ttyp := typeOf(val)\n\n\t\tswitch typ {\n\t\tcase tIntnum:\n\t\t\tswitch sumt {\n\t\t\tcase tIntnum:\n\t\t\t\tisum += intnumVal(val)\n\t\t\tcase tFlonum:\n\t\t\t\tfsum += float64(intnumVal(val))\n\t\t\tcase tRatinum:\n\t\t\t\trsum = addRatInt(rsum, intnumVal(val))\n\t\t\tcase tCmplnum:\n\t\t\t\tcsum = complex(real(csum)+float64(intnumVal(val)), imag(csum))\n\t\t\t}\n\t\tcase tFlonum:\n\t\t\tswitch sumt {\n\t\t\tcase tIntnum:\n\t\t\t\tfsum = float64(isum) + flonumVal(val)\n\t\t\t\tsumt = tFlonum\n\t\t\tcase tFlonum:\n\t\t\t\tfsum += flonumVal(val)\n\t\t\tcase tRatinum:\n\t\t\t\tfsum = addRatFlo(rsum, flonumVal(val))\n\t\t\t\tsumt = tFlonum\n\t\t\tcase tCmplnum:\n\t\t\t\tcsum = complex(real(csum)+flonumVal(val), imag(csum))\n\t\t\t\tsumt = tCmplnum\n\t\t\t}\n\t\tcase tRatinum:\n\t\t\tswitch sumt {\n\t\t\tcase tIntnum:\n\t\t\t\trsum = addRatInt(ratinumVal(val), isum)\n\t\t\t\tsumt = tRatinum\n\t\t\tcase tFlonum:\n\t\t\t\tfsum = addRatFlo(ratinumVal(val), fsum)\n\t\t\tcase tRatinum:\n\t\t\t\trsum = addRatRat(rsum, ratinumVal(val))\n\t\t\tcase tCmplnum:\n\t\t\t\tcsum = complex(addRatFlo(ratinumVal(val), real(csum)), imag(csum))\n\t\t\t}\n\t\tcase tCmplnum:\n\t\t\tcmplx := cmplnumVal(val)\n\t\t\tswitch sumt {\n\t\t\tcase tIntnum:\n\t\t\t\tcsum = complex(real(cmplx)+float64(isum), imag(cmplx))\n\t\t\t\tsumt = tCmplnum\n\t\t\tcase tFlonum:\n\t\t\t\tcsum = complex(real(cmplx)+fsum, imag(cmplx))\n\t\t\t\tsumt = tCmplnum\n\t\t\tcase tRatinum:\n\t\t\t\tcsum = complex(addRatFlo(rsum, real(cmplx)), imag(cmplx))\n\t\t\t\tsumt = tCmplnum\n\t\t\tcase tCmplnum:\n\t\t\t\tcsum += cmplx\n\t\t\t}\n\t\t}\n\t\tp = pair(p).cdr\n\t}\n\n\tswitch sumt {\n\tcase tIntnum:\n\t\treturn mkIntnum(isum)\n\tcase tFlonum:\n\t\treturn mkFlonum(fsum)\n\tcase tRatinum:\n\t\treturn mkRatinum(rsum)\n\tcase tCmplnum:\n\t\treturn mkCmplnum(csum)\n\tdefault:\n\t\treturn mkError(mkYerror(errArgTypeMis))\n\t}\n}", "func Beta(a, b float64) float64 {\n\tla, sgnla := math.Lgamma(a)\n\tlb, sgnlb := math.Lgamma(b)\n\tlc, sgnlc := math.Lgamma(a + b)\n\treturn float64(sgnla*sgnlb*sgnlc) * math.Exp(la+lb-lc)\n}", "func (c *Context) VPAVGB(ops ...operand.Op) {\n\tc.addinstruction(x86.VPAVGB(ops...))\n}", "func (a *Vector3) Plus(b Vector3) {\n\t*a = Vector3{a.X + b.X, a.Y + b.Y, a.Z + b.Z}\n}", "func logG(y, e, alpha, beta float64) float64 {\n\treturn lnΓ(alpha+y) - (y+alpha)*log(e+beta) + alpha*log(beta) - lnΓ(alpha)\n}", "func blastrans(g1 blas64.General) blas64.General {\n\t// first the receiver\n\tg3 := blas64.General{\n\t\tRows: g1.Cols,\n\t\tCols: g1.Rows,\n\t\tStride: g1.Rows,\n\t\tData: make([]float64, g1.Rows*g1.Cols),\n\t}\n\tblas64.Gemm(blas.NoTrans, blas.Trans, 1.0, eye(g1.Cols), g1, 0.0, g3)\n\treturn g3\n}", "func AbsGradientSaturatedSum(src, dst gocvsimd.View) {\n\n\tgocvsimd.SimdSse2AbsGradientSaturatedSum(src, dst)\n}", "func (fn *formulaFuncs) vdb(cost, salvage, life, life1, period, factor formulaArg) formulaArg {\n\tvar ddb, vdb, sln, term float64\n\tendInt, cs, nowSln := math.Ceil(period.Number), cost.Number-salvage.Number, false\n\tddbArgs := list.New()\n\tfor i := 1.0; i <= endInt; i++ {\n\t\tif !nowSln {\n\t\t\tddbArgs.Init()\n\t\t\tddbArgs.PushBack(cost)\n\t\t\tddbArgs.PushBack(salvage)\n\t\t\tddbArgs.PushBack(life)\n\t\t\tddbArgs.PushBack(newNumberFormulaArg(i))\n\t\t\tddbArgs.PushBack(factor)\n\t\t\tddb = fn.DDB(ddbArgs).Number\n\t\t\tsln = cs / (life1.Number - i + 1)\n\t\t\tif sln > ddb {\n\t\t\t\tterm = sln\n\t\t\t\tnowSln = true\n\t\t\t} else {\n\t\t\t\tterm = ddb\n\t\t\t\tcs -= ddb\n\t\t\t}\n\t\t} else {\n\t\t\tterm = sln\n\t\t}\n\t\tif i == endInt {\n\t\t\tterm *= period.Number + 1 - endInt\n\t\t}\n\t\tvdb += term\n\t}\n\treturn newNumberFormulaArg(vdb)\n}", "func VADDPS_BCST(ops ...operand.Op) { ctx.VADDPS_BCST(ops...) }", "func VADDSS_Z(mx, x, k, x1 operand.Op) { ctx.VADDSS_Z(mx, x, k, x1) }", "func VPSRLW(ops ...operand.Op) { ctx.VPSRLW(ops...) }", "func VPDPBUSDS(ops ...operand.Op) { ctx.VPDPBUSDS(ops...) }", "func VADDSD_Z(mx, x, k, x1 operand.Op) { ctx.VADDSD_Z(mx, x, k, x1) }", "func VFMSUBADD231PS(ops ...operand.Op) { ctx.VFMSUBADD231PS(ops...) }", "func AccumulateNV2(scope *Scope, inputs []tf.Output, shape tf.Shape) (sum tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{\"shape\": shape}\n\topspec := tf.OpSpec{\n\t\tType: \"AccumulateNV2\",\n\t\tInput: []tf.Input{\n\t\t\ttf.OutputList(inputs),\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func VPADDQ(ops ...operand.Op) { ctx.VPADDQ(ops...) }", "func VFMSUBADD213PS(ops ...operand.Op) { ctx.VFMSUBADD213PS(ops...) }", "func VADDPS_RZ_SAE(ops ...operand.Op) { ctx.VADDPS_RZ_SAE(ops...) }" ]
[ "0.5586263", "0.5585398", "0.55512506", "0.54982704", "0.5466384", "0.54608387", "0.54496974", "0.5364682", "0.5336382", "0.53347695", "0.5324832", "0.5324584", "0.52760285", "0.52568555", "0.5233749", "0.5223149", "0.5202601", "0.520236", "0.5188375", "0.51773614", "0.5170819", "0.51333594", "0.5127843", "0.5122299", "0.5120841", "0.51192766", "0.5098905", "0.5085176", "0.50790024", "0.5063093", "0.50587636", "0.50565314", "0.5056138", "0.50552624", "0.5040113", "0.5033891", "0.5031385", "0.5018729", "0.498393", "0.49640194", "0.4950631", "0.49501082", "0.49362293", "0.4935909", "0.4927775", "0.49269196", "0.4920941", "0.49115413", "0.4909203", "0.48975214", "0.48936552", "0.488604", "0.488272", "0.48817068", "0.48807886", "0.48637837", "0.48582", "0.48571277", "0.4855735", "0.48443228", "0.4834577", "0.48233804", "0.48165235", "0.48159164", "0.4814444", "0.48126522", "0.47934628", "0.47921586", "0.47911236", "0.4788472", "0.47865522", "0.4786192", "0.47852218", "0.47784507", "0.47781974", "0.47716463", "0.47680575", "0.47636163", "0.47587666", "0.47577357", "0.4745742", "0.47340465", "0.47334623", "0.47316265", "0.47301167", "0.47260582", "0.47259843", "0.4720648", "0.47196203", "0.47195327", "0.47192448", "0.47182363", "0.47168773", "0.47113517", "0.47099897", "0.47074375", "0.47014472", "0.46986228", "0.4694263", "0.4688818" ]
0.6385673
0
GenerateImageMetaData creates some random image data
func GenerateImageMetaData(howMany int) *List { list := &List{} for i := 0; i < howMany; i++ { img := &Image{} img.Name = fmt.Sprintf("IMG_%06d.jpg", i) img.Id = CreateString(16) w, h := Resolution() img.Width = w img.Height = h img.TakenAt = Time(i, 12) img.LastMod = Time(i, 13) img.Sha256 = CreateString(16) img.FileSize = rand.Int63() img.Caption = Caption(i) img.XMP = &XMP{} img.XMP.Camera = Camera() img.XMP.Owner = FaceMe() for f := 0; f < rand.Intn(5); i++ { face := &Face{} face.Name = FaceMe() face.R = rand.NormFloat64() face.X = rand.NormFloat64() face.Y = rand.NormFloat64() img.XMP.Faces = append(img.XMP.Faces, face) } list.Images = append(list.Images, img) } list.Timestamp = Time(1, 1) return list }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (aip *ActiveIPs) GenerateMetaData() {\n\taip.Type = &ActiveIPsType\n\ty, m, d := aip.Date.Date()\n\taip.Link = fmt.Sprintf(\"/research/active_ips/%04d-%02d-%02d\", y, m, d)\n}", "func randomMetadata() Metadata {\n\tmd := Metadata{\n\t\tAggregateHealth: float64(fastrand.Intn(100)),\n\t\tAggregateLastHealthCheckTime: time.Now(),\n\t\tAggregateMinRedundancy: float64(fastrand.Intn(100)),\n\t\tAggregateModTime: time.Now(),\n\t\tAggregateNumFiles: fastrand.Uint64n(100),\n\t\tAggregateNumStuckChunks: fastrand.Uint64n(100),\n\t\tAggregateNumSubDirs: fastrand.Uint64n(100),\n\t\tAggregateRemoteHealth: float64(fastrand.Intn(100)),\n\t\tAggregateRepairSize: fastrand.Uint64n(100),\n\t\tAggregateSize: fastrand.Uint64n(100),\n\t\tAggregateStuckHealth: float64(fastrand.Intn(100)),\n\t\tAggregateStuckSize: fastrand.Uint64n(100),\n\n\t\tAggregateSkynetFiles: fastrand.Uint64n(100),\n\t\tAggregateSkynetSize: fastrand.Uint64n(100),\n\n\t\tHealth: float64(fastrand.Intn(100)),\n\t\tLastHealthCheckTime: time.Now(),\n\t\tMinRedundancy: float64(fastrand.Intn(100)),\n\t\tModTime: time.Now(),\n\t\tNumFiles: fastrand.Uint64n(100),\n\t\tNumStuckChunks: fastrand.Uint64n(100),\n\t\tNumSubDirs: fastrand.Uint64n(100),\n\t\tRemoteHealth: float64(fastrand.Intn(100)),\n\t\tRepairSize: fastrand.Uint64n(100),\n\t\tSize: fastrand.Uint64n(100),\n\t\tStuckHealth: float64(fastrand.Intn(100)),\n\t\tStuckSize: fastrand.Uint64n(100),\n\n\t\tSkynetFiles: fastrand.Uint64n(100),\n\t\tSkynetSize: fastrand.Uint64n(100),\n\t}\n\treturn md\n}", "func (meta *BundleMetaData) GenerateMetadata() error {\n\t// Create output directory\n\tif err := os.MkdirAll(meta.BundleDir, projutil.DirMode); err != nil {\n\t\treturn err\n\t}\n\n\t// Create annotation values for both bundle.Dockerfile and annotations.yaml, which should\n\t// hold the same set of values always.\n\tvalues := annotationsValues{\n\t\tBundleDir: meta.BundleDir,\n\t\tPackageName: meta.PackageName,\n\t\tChannels: meta.Channels,\n\t\tDefaultChannel: meta.DefaultChannel,\n\t\tIsScorecardConfigPresent: meta.IsScoreConfigPresent,\n\t}\n\n\tfor k, v := range meta.OtherLabels {\n\t\tvalues.OtherLabels = append(values.OtherLabels, fmt.Sprintf(\"%s=%s\", k, v))\n\t}\n\tsort.Strings(values.OtherLabels)\n\n\t// Write each file\n\tmetadataDir := filepath.Join(meta.BundleDir, defaultMetadataDir)\n\tif err := os.MkdirAll(metadataDir, projutil.DirMode); err != nil {\n\t\treturn err\n\t}\n\n\tdockerfilePath := defaultBundleDockerfilePath\n\t// If migrating from packagemanifests to bundle, bundle.Dockerfile is present\n\t// inside bundleDir, else it's in the project directory. Hence, dockerfile\n\t// should have the path specified with respect to output directory of resulting bundles.\n\t// Remove this, when pkgman-to-bundle migrate command is removed.\n\tif len(meta.PkgmanifestPath) != 0 {\n\t\tdockerfilePath = filepath.Join(filepath.Dir(meta.BundleDir), \"bundle.Dockerfile\")\n\t\tvalues.BundleDir = filepath.Base(meta.BundleDir)\n\t}\n\n\ttemplateMap := map[string]*template.Template{\n\t\tdockerfilePath: dockerfileTemplate,\n\t\tfilepath.Join(metadataDir, \"annotations.yaml\"): annotationsTemplate,\n\t}\n\n\tfor path, tmpl := range templateMap {\n\t\tlog.Info(fmt.Sprintf(\"Creating %s\", path))\n\t\tf, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif err := f.Close(); err != nil {\n\t\t\t\tlog.Error(err)\n\t\t\t}\n\t\t}()\n\t\tif err = tmpl.Execute(f, values); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tlog.Infof(\"Bundle metadata generated successfully\")\n\treturn nil\n}", "func GetImageMetaData(w http.ResponseWriter, r *http.Request) {\n\n\ttype ResponseModel struct {\n\t\tImageMetaData model.Image\n\t\tComments []model.Comment\n\t}\n\n\t//Response Parameter\n\tvars := mux.Vars(r)\n\timageID := vars[\"imageID\"]\n\n\t//Get Data and make Response\n\timage, err := model.GetImageMetaData(imageID)\n\tif err != nil {\n\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\n\t}\n\n\timage.Likes, err = image.GetLikeCounts()\n\tif err != nil {\n\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\n\t}\n\n\tcomments, err := image.GetComments()\n\tif err != nil {\n\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\n\t}\n\n\trepsoneModel := ResponseModel{\n\t\tImageMetaData: image,\n\t\tComments: comments,\n\t}\n\n\t//Create JSON\n\tresponseJSON, err := json.Marshal(repsoneModel)\n\tif err != nil {\n\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\n\t}\n\n\t//Write Response\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(responseJSON)\n\n}", "func (c *ResearchIPNsZoneCount) GenerateMetaData() {\n\tc.Type = &IPNsZoneCountType\n\tc.Link = \"/research/ipnszonecount/\" + c.IP\n}", "func (t *Template) GenerateMetadata() (string, error) {\n\ttmpl, err := template.New(\"metadata\").Parse(metadata)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbuffer := bytes.NewBufferString(\"\")\n\terr = tmpl.Execute(buffer, t)\n\treturn buffer.String(), err\n}", "func metadata(m Moby, md string) ([]byte, error) {\n\t// Make sure the Image strings are update to date with the refs\n\tupdateImages(&m)\n\tswitch md {\n\tcase \"json\":\n\t\treturn json.MarshalIndent(m, \"\", \" \")\n\tcase \"yaml\":\n\t\treturn yaml.Marshal(m)\n\tdefault:\n\t\treturn []byte{}, fmt.Errorf(\"Unsupported metadata type: %s\", md)\n\t}\n}", "func RandomDatasetMetadata(value string) RandomDatasetAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"metadata\"] = value\n\t}\n}", "func (*CreateImageMetadata) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_compute_v1_image_service_proto_rawDescGZIP(), []int{5}\n}", "func generateRandomImageName() string {\n\trand.Seed(time.Now().UTC().UnixNano())\n\tb := make([]rune, 32)\n\tfor i := range b {\n\t\tb[i] = letters[rand.Intn(len(letters))]\n\t}\n\treturn string(b)\n}", "func generateMetadataName(remote string) (newRemote string) {\n\treturn remote + metaFileExt\n}", "func GenerateMetaInfo(cfg *Config) error {\n\tif err := os.MkdirAll(cfg.DataDir, 0700); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\t// get newest ts from pd\n\tcommitTS, err := GetTSO(cfg)\n\tif err != nil {\n\t\tlog.Error(\"get tso failed\", zap.Error(err))\n\t\treturn errors.Trace(err)\n\t}\n\n\t// generate meta file\n\tmetaFileName := path.Join(cfg.DataDir, \"savepoint\")\n\terr = saveMeta(metaFileName, commitTS, cfg.TimeZone)\n\treturn errors.Trace(err)\n}", "func generateManifest(gitRepo *gitRepo, imageName, imageTag string) (*registry.ManifestData, error) {\n\tbranches, err := gitRepo.branch()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar imageChecksums []string = make([]string, len(branches))\n\tfor _, br := range branches {\n\t\tchecksum := br.imageID()\n\t\tsumTypeBytes, err := gitRepo.branchDescription(br)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\timageChecksums[br.number()] = string(sumTypeBytes) + \":\" + checksum\n\t}\n\n\tmanifest := &registry.ManifestData{\n\t\tName: imageName,\n\t\tArchitecture: \"amd64\", //unclean but so far looks ok ...\n\t\tTag: imageTag,\n\t\tSchemaVersion: 1,\n\t\tFSLayers: make([]*registry.FSLayer, 0, 4),\n\t}\n\n\tfor i, checksum := range imageChecksums {\n\t\tif tarsum.VersionLabelForChecksum(checksum) != tarsum.Version1.String() {\n\t\t\t//need to calculate the tarsum V1 for each layer ...\n\t\t\tlayerData, err := gitRepo.exportChangeSet(branches[i])\n\t\t\tif err == ErrNoChange {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdefer layerData.Close()\n\n\t\t\ttarSum, err := tarsum.NewTarSum(layerData, true, tarsum.Version1)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif _, err := io.Copy(ioutil.Discard, tarSum); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tchecksum = tarSum.Sum(nil)\n\t\t}\n\t\tmanifest.FSLayers = append(manifest.FSLayers, &registry.FSLayer{BlobSum: checksum})\n\t}\n\treturn manifest, nil\n}", "func GenerateMeta(id string, args map[string]interface{}) error {\n\tpipeline, err := GetPipeline(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := pipeline.NewMetaRequest(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn pipeline.Generate(req)\n}", "func CreateMetadata(metadata map[string]string) *Metadata {\n\tdata := &Metadata{\n\t\tDC: \"http://purl.org/dc/elements/1.1/\",\n\t}\n\tfor item, value := range metadata {\n\t\tdata.Add(item, item, value)\n\t}\n\treturn data\n}", "func (drc *DummyRegistryClient) GetImageMetadata(in, et string) (md Metadata, err error) {\n\tres := drc.Called(in, et)\n\treturn res.Get(0).(Metadata), res.Error(1)\n}", "func getTestImage(image int) string {\n\treturn imageNames[image]\n}", "func GenImage(c []uint8, n string) {\n\timg := image.NewRGBA(image.Rect(0, 0, 1024, 600))\n\n\tfor i := 0; i <= 1024; i++ {\n\t\tfor j := 0; j <= 600; j++ {\n\t\t\timg.Set(i, j, color.RGBA{c[0], c[1], c[2], 255})\n\t\t}\n\t}\n\tname := \"./img/\" + n + \".png\"\n\tf, _ := os.OpenFile(name, os.O_WRONLY|os.O_CREATE, 0600)\n\tdefer f.Close()\n\tpng.Encode(f, img)\n\n}", "func randomTileImageBimg(logger log.Logger, filePath, srcDir, dstDir string, count, resize, width, height int) error {\n\tbuffer, err := bimg.Read(filePath)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t}\n\timg := bimg.NewImage(buffer)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't open image %s %v\", filePath, err)\n\t}\n\tsize, err := img.Size()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't read sizego image %s %v\", filePath, err)\n\t}\n\n\tif resize > 1 {\n\t\tbuffer, err = img.Resize(size.Width/resize, size.Height/resize)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"can't resize image %s %v\", filePath, err)\n\t\t}\n\t\timg = bimg.NewImage(buffer)\n\n\t\tsize, err = img.Size()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"can't read resized image %s %v\", filePath, err)\n\t\t}\n\n\t\tlevel.Debug(logger).Log(\n\t\t\t\"msg\", \"resizing image\",\n\t\t\t\"sizex\", size.Width,\n\t\t\t\"sizey\", size.Height,\n\t\t\t\"src_path\", filePath,\n\t\t)\n\t}\n\n\t// generate randome tiles\n\tif size.Width < width || size.Height < height {\n\t\treturn fmt.Errorf(\"too small to be tilled %s\", filePath)\n\t}\n\n\trand.Seed(time.Now().UTC().UnixNano())\n\n\tfor i := 0; i < count; i++ {\n\t\txpos := rand.Intn(size.Width - width)\n\t\typos := rand.Intn(size.Height - height)\n\n\t\text := path.Ext(filePath)\n\t\twpath := filePath[:len(filePath)-len(ext)]\n\t\twpath = wpath[len(srcDir):]\n\t\toutFilename := fmt.Sprintf(\"%s-%d%s\", wpath, i, ext)\n\t\toutFilePath := filepath.Join(dstDir, outFilename)\n\n\t\tlevel.Debug(logger).Log(\n\t\t\t\"msg\", \"cropping random image\",\n\t\t\t\"count\", count,\n\t\t\t\"xpos\", xpos,\n\t\t\t\"ypos\", ypos,\n\t\t\t\"width\", width,\n\t\t\t\"height\", height,\n\t\t\t\"sizex\", size.Width,\n\t\t\t\"sizey\", size.Height,\n\t\t\t\"file_path\", filePath,\n\t\t\t\"src_dir\", srcDir,\n\t\t\t\"dst_dir\", dstDir,\n\t\t\t\"out_file_path\", outFilePath,\n\t\t)\n\n\t\tcrop := bimg.NewImage(buffer)\n\t\tcropb, err := crop.Extract(ypos, xpos, width, height)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"can't crop image %s %v\", filePath, err)\n\t\t}\n\n\t\terr = bimg.Write(outFilePath, cropb)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"can't save image %s %v\", outFilePath, err)\n\t\t}\n\t\tatomic.AddUint64(&tileCounter, 1)\n\t}\n\treturn nil\n}", "func GenerateBuildMetadata(componentID string) (BuildMetadata, error) {\n\tif componentID == \"\" {\n\t\treturn BuildMetadata{}, ErrEmptyComponentID\n\t}\n\tcreatedAt := time.Now()\n\tbuildID := fmt.Sprintf(\"%s%s:%d\", DockerImagePrefix, componentID, createdAt.Unix())\n\treturn BuildMetadata{ID: buildID, ComponentID: componentID, CreatedAt: createdAt}, nil\n}", "func (rss *reedSolomonSplitter) MetaData() interface{} {\n\treturn &RsMetaMap{\n\t\tNumData: rss.numData,\n\t\tNumParity: rss.numParity,\n\t\tFileSize: rss.fileSize,\n\t\tIsDir: rss.isDir,\n\t}\n}", "func RandomDatasetV2Metadata(value string) RandomDatasetV2Attr {\n\treturn func(m optionalAttr) {\n\t\tm[\"metadata\"] = value\n\t}\n}", "func applyMeta(meta *runapi.ObjectMeta, userImage string) {\n\tif meta.Annotations == nil {\n\t\tmeta.Annotations = make(map[string]string)\n\t}\n\tmeta.Annotations[\"client.knative.dev/user-image\"] = userImage\n\tmeta.Annotations[\"run.googleapis.com/client-name\"] = \"cloud-run-button\"\n}", "func (m *Meta) imageName() string {\n\treturn filepath.Join(m.Path, NameImage)\n}", "func (rawIM RawImageMetaJSON) ImageMeta() (im ImageMeta, err error) {\n\tif err = json.Unmarshal(rawIM, &im); err != nil {\n\t\treturn ImageMeta{}, fmt.Errorf(\"decoding json meta: %w\", err)\n\t}\n\n\treturn im, nil\n}", "func GenImg(file io.Reader, ext string, numshapes int, mode primitive.Mode) (string, error) {\n\toutput, err := primitive.TransformImg(file, ext, numshapes, primitive.ArgMode(mode))\n\tif err != nil {\n\t\t//http.Error(resp, err.Error(), http.StatusInternalServerError)\n\t\treturn \"\", err\n\t}\n\n\tsaveout, err := getExtFile(\"\", ext)\n\tif err != nil {\n\t\t//http.Error(resp, err.Error(), http.StatusInternalServerError)\n\t\treturn \"\", err\n\t}\n _,err = CopyFunc(saveout, output)\n if err!=nil{\n return \"\",err\n }\n\n\treturn saveout.Name(), err\n}", "func (i *Image) RandImage(width, height int) string {\n\tcategories := []string{\n\t\t\"abstract\", \"animals\", \"business\", \"cats\", \"city\",\n\t\t\"food\", \"nightlife\", \"fashion\", \"people\",\n\t\t\"nature\", \"sports\", \"technics\", \"transport\",\n\t}\n\tcategoriesFuncs := map[string]interface{}{\n\t\t\"abstract\": i.Image().Abstract,\n\t\t\"animals\": i.Image().Animals,\n\t\t\"business\": i.Image().Business,\n\t\t\"cats\": i.Image().Cats,\n\t\t\"city\": i.Image().City,\n\t\t\"food\": i.Image().Food,\n\t\t\"nightlife\": i.Image().Nightlife,\n\t\t\"fashion\": i.Image().Fashion,\n\t\t\"people\": i.Image().People,\n\t\t\"nature\": i.Image().Nature,\n\t\t\"sports\": i.Image().Sports,\n\t\t\"technics\": i.Image().Technics,\n\t\t\"transport\": i.Image().Transport,\n\t}\n\n\tfunction := selectElement(categories)\n\n\tresult, err := callFunc(categoriesFuncs, function, width, height)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn fmt.Sprintf(\"%s\", result[0])\n}", "func (i ImageAnnotatorHandlerFuncs) CreateImageAnnotations(data interface{}, name string, count int) map[string]string {\n\tif i.ImageLabelCreationFunc != nil {\n\t\treturn i.ImageAnnotationCreationFunc(data, name, count)\n\t}\n\treturn make(map[string]string)\n}", "func GenerateImageTag(defaultImage string, imageRegistries []string, registryConfig metabuilderapi.RegistryConfiguration) string {\n\tif len(imageRegistries) > 0 {\n\t\timageName, err := GetImageName(defaultImage)\n\t\tif err != nil {\n\t\t\treturn defaultImage\n\t\t}\n\t\tdefaultImage = getFullContainerNameFromImageRegistryConf(imageName, imageRegistries, defaultImage)\n\t}\n\n\tif len(registryConfig.Registry) > 0 {\n\t\treturn getRegistryConfiguration(defaultImage, registryConfig)\n\t}\n\treturn defaultImage\n}", "func seedRandomOCIImageIndex(t *testing.T, env *testEnv, repoPath string, opts ...manifestOptsFunc) *manifestlist.DeserializedManifestList {\n\tt.Helper()\n\n\tconfig := &manifestOpts{\n\t\trepoPath: repoPath,\n\t}\n\n\tfor _, o := range opts {\n\t\to(t, env, config)\n\t}\n\n\tif config.writeToFilesystemOnly {\n\t\tenv.config.Database.Enabled = false\n\t\tdefer func() { env.config.Database.Enabled = true }()\n\t}\n\n\tociImageIndex := &manifestlist.ManifestList{\n\t\tVersioned: manifest.Versioned{\n\t\t\tSchemaVersion: 2,\n\t\t\t// MediaType field for OCI image indexes is reserved to maintain compatibility and can be blank:\n\t\t\t// https://github.com/opencontainers/image-spec/blob/master/image-index.md#image-index-property-descriptions\n\t\t\tMediaType: \"\",\n\t\t},\n\t}\n\n\t// Create and push up 2 random OCI images.\n\tociImageIndex.Manifests = make([]manifestlist.ManifestDescriptor, 2)\n\n\tfor i := range ociImageIndex.Manifests {\n\t\tdeserializedManifest := seedRandomOCIManifest(t, env, repoPath, putByDigest)\n\n\t\t_, payload, err := deserializedManifest.Payload()\n\t\trequire.NoError(t, err)\n\t\tdgst := digest.FromBytes(payload)\n\n\t\tociImageIndex.Manifests[i] = manifestlist.ManifestDescriptor{\n\t\t\tDescriptor: distribution.Descriptor{\n\t\t\t\tDigest: dgst,\n\t\t\t\tMediaType: v1.MediaTypeImageManifest,\n\t\t\t},\n\t\t\tPlatform: randomPlatformSpec(),\n\t\t}\n\t}\n\n\tdeserializedManifest, err := manifestlist.FromDescriptors(ociImageIndex.Manifests)\n\trequire.NoError(t, err)\n\n\tif config.putManifest {\n\t\tmanifestDigestURL := buildManifestDigestURL(t, env, repoPath, deserializedManifest)\n\n\t\tif config.manifestURL == \"\" {\n\t\t\tconfig.manifestURL = manifestDigestURL\n\t\t}\n\n\t\tresp := putManifest(t, \"putting oci image index no error\", config.manifestURL, v1.MediaTypeImageIndex, deserializedManifest)\n\t\tdefer resp.Body.Close()\n\t\trequire.Equal(t, http.StatusCreated, resp.StatusCode)\n\t\trequire.Equal(t, \"nosniff\", resp.Header.Get(\"X-Content-Type-Options\"))\n\t\trequire.Equal(t, manifestDigestURL, resp.Header.Get(\"Location\"))\n\n\t\t_, payload, err := deserializedManifest.Payload()\n\t\trequire.NoError(t, err)\n\t\tdgst := digest.FromBytes(payload)\n\t\trequire.Equal(t, dgst.String(), resp.Header.Get(\"Docker-Content-Digest\"))\n\t}\n\n\treturn deserializedManifest\n}", "func (cli *FakeDatabaseClient) FetchServiceImageMetaData(ctx context.Context, in *dbdpb.FetchServiceImageMetaDataRequest, opts ...grpc.CallOption) (*dbdpb.FetchServiceImageMetaDataResponse, error) {\n\tatomic.AddInt32(&cli.fetchServiceImageMetaDataCnt, 1)\n\tif cli.methodToResp == nil {\n\t\treturn nil, nil\n\t}\n\tmethod := \"FetchServiceImageMetaData\"\n\tif resp, ok := cli.methodToResp[method]; ok {\n\t\treturn resp.(*dbdpb.FetchServiceImageMetaDataResponse), nil\n\t}\n\treturn nil, nil\n\n}", "func (c *Client) GetMetaData(ctx context.Context, name string) (*MetaData, error) {\n\tmetadata, err := c.getMetaDataFrom2022API(ctx, name)\n\tif err != nil {\n\t\tlog.Printf(\"[DEBUG] Falling back to ARM Metadata version 2019-05-01 for %s\", c.endpoint)\n\t\tmetadata, err = c.getMetaDataFrom2019API(ctx, name)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"retrieving metadata from the 2022-09-01 and 2019-05-01 APIs: %+v\", err)\n\t\t}\n\t}\n\n\treturn &MetaData{\n\t\tAuthentication: Authentication{\n\t\t\tAudiences: metadata.Authentication.Audiences,\n\t\t\tLoginEndpoint: metadata.Authentication.LoginEndpoint,\n\t\t\tIdentityProvider: metadata.Authentication.IdentityProvider,\n\t\t\tTenant: metadata.Authentication.Tenant,\n\t\t},\n\t\tDnsSuffixes: DnsSuffixes{\n\t\t\tAttestation: metadata.Suffixes.AttestationEndpoint,\n\t\t\tFrontDoor: metadata.Suffixes.AzureFrontDoorEndpointSuffix,\n\t\t\tKeyVault: metadata.Suffixes.KeyVaultDns,\n\t\t\tManagedHSM: metadata.Suffixes.MhsmDns,\n\t\t\tMariaDB: metadata.Suffixes.MariadbServerEndpoint,\n\t\t\tMySql: metadata.Suffixes.MysqlServerEndpoint,\n\t\t\tPostgresql: metadata.Suffixes.PostgresqlServerEndpoint,\n\t\t\tSqlServer: metadata.Suffixes.SqlServerHostname,\n\t\t\tStorage: metadata.Suffixes.Storage,\n\t\t\tStorageSync: metadata.Suffixes.StorageSyncEndpointSuffix,\n\t\t\tSynapse: metadata.Suffixes.SynapseAnalytics,\n\t\t},\n\t\tName: metadata.Name,\n\t\tResourceIdentifiers: ResourceIdentifiers{\n\t\t\tAttestation: normalizeResourceId(metadata.AttestationResourceId),\n\t\t\tBatch: normalizeResourceId(metadata.Batch),\n\t\t\tLogAnalytics: normalizeResourceId(metadata.LogAnalyticsResourceId),\n\t\t\tMedia: normalizeResourceId(metadata.Media),\n\t\t\tMicrosoftGraph: normalizeResourceId(metadata.MicrosoftGraphResourceId),\n\t\t\tOSSRDBMS: normalizeResourceId(metadata.OssrDbmsResourceId),\n\t\t\tSynapse: normalizeResourceId(metadata.SynapseAnalyticsResourceId),\n\t\t},\n\t\tResourceManagerEndpoint: metadata.ResourceManager,\n\t}, nil\n}", "func (m *Manager) CreateImage(reader io.Reader) (string, *schema.ImageManifest, error) {\n\thr := hashutil.NewSha512(reader)\n\tf, err := tempfile.New(hr)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\tdefer f.Close()\n\n\thash := fmt.Sprintf(\"sha512-%s\", hr.Sha512())\n\n\t// double check we don't already have it\n\tm.imagesLock.RLock()\n\tmanifest, exists := m.images[hash]\n\tm.imagesLock.RUnlock()\n\tif exists {\n\t\treturn hash, manifest, nil\n\t}\n\n\tdest := filepath.Join(m.Options.Directory, hash)\n\tif err := os.Mkdir(dest, os.FileMode(0755)); err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\tsuccessful := false\n\tdefer func() {\n\t\tif !successful {\n\t\t\tos.RemoveAll(dest)\n\t\t}\n\t}()\n\n\tfi, err := os.Stat(dest)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\t// untar the file\n\ttarfile := tarhelper.NewUntar(f, dest)\n\ttarfile.PreserveOwners = true\n\ttarfile.PreservePermissions = true\n\ttarfile.Compression = tarhelper.DETECT\n\ttarfile.AbsoluteRoot = dest\n\tif err := tarfile.Extract(); err != nil {\n\t\treturn \"\", nil, fmt.Errorf(\"failed to extract image filesystem: %v\", err)\n\t}\n\n\t// load the manifest and return it\n\tmanifest, err = m.loadFile(fi)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\tsuccessful = true\n\treturn hash, manifest, nil\n}", "func newMetadata(defaultLineNum int) *Metadata {\n\treturn &Metadata{\n\t\tHistogramLineNum: defaultLineNum,\n\t\tOwnerLineNum: defaultLineNum,\n\t}\n}", "func newMetadata(size int64, compressionMode int, blockData []uint32, hash []byte, mimeType string) *ObjectMetadata {\n\tmeta := new(ObjectMetadata)\n\tmeta.Size = size\n\tmeta.CompressionMode = compressionMode\n\tmeta.BlockData = blockData\n\tmeta.Hash = hash\n\tmeta.MimeType = mimeType\n\treturn meta\n}", "func (drc *DummyRegistryClient) AddMetadata(pattern string, md Metadata) {\n\tre := regexp.MustCompile(pattern)\n\tdrc.MatchMethod(\"GetImageMetadata\", func(args mock.Arguments) bool {\n\t\treturn re.MatchString(args.String(0))\n\t}, md, nil)\n}", "func CreateKogitoImageStream(kogitoApp *v1alpha1.KogitoApp, targetVersion string) imgv1.ImageStreamList {\n\tvar kogitoImageStreamList imgv1.ImageStreamList\n\n\tfor _, imageName := range ImageStreamNameList {\n\t\tcreate := false\n\t\ttagAnnotations := make(map[string]string)\n\t\ttagAnnotations[\"iconClass\"] = \"icon-jbpm\"\n\t\ttagAnnotations[\"version\"] = targetVersion\n\n\t\timageStreamAnnotations := make(map[string]string)\n\t\timageStreamAnnotations[\"openshift.io/provider-display-name\"] = \"Kie Group.\"\n\n\t\tswitch imageName {\n\t\tcase KogitoQuarkusUbi8Image:\n\t\t\timageStreamAnnotations[\"openshift.io/display-name\"] = \"Runtime image for Kogito based on Quarkus native image\"\n\t\t\ttagAnnotations[\"description\"] = \"Runtime image for Kogito based on Quarkus native image\"\n\t\t\ttagAnnotations[\"tags\"] = \"runtime,kogito,quarkus\"\n\t\t\ttagAnnotations[\"supports\"] = \"quarkus\"\n\t\t\tif kogitoApp.Spec.Runtime == v1alpha1.QuarkusRuntimeType && kogitoApp.Spec.Build.Native {\n\t\t\t\tcreate = true\n\t\t\t}\n\n\t\tcase KogitoQuarkusJVMUbi8Image:\n\t\t\timageStreamAnnotations[\"openshift.io/display-name\"] = \"Runtime image for Kogito based on Quarkus JVM image\"\n\t\t\ttagAnnotations[\"description\"] = \"Runtime image for Kogito based on Quarkus JVM image\"\n\t\t\ttagAnnotations[\"tags\"] = \"runtime,kogito,quarkus,jvm\"\n\t\t\ttagAnnotations[\"supports\"] = \"quarkus\"\n\t\t\tif kogitoApp.Spec.Runtime == v1alpha1.QuarkusRuntimeType && !kogitoApp.Spec.Build.Native {\n\t\t\t\tcreate = true\n\t\t\t}\n\n\t\tcase KogitoQuarkusUbi8s2iImage:\n\t\t\timageStreamAnnotations[\"openshift.io/display-name\"] = \"Platform for building Kogito based on Quarkus\"\n\t\t\ttagAnnotations[\"description\"] = \"Platform for building Kogito based on Quarkus\"\n\t\t\ttagAnnotations[\"tags\"] = \"builder,kogito,quarkus\"\n\t\t\ttagAnnotations[\"supports\"] = \"quarkus\"\n\t\t\tif kogitoApp.Spec.Runtime == v1alpha1.QuarkusRuntimeType {\n\t\t\t\tcreate = true\n\t\t\t}\n\n\t\tcase KogitoSpringbootUbi8Image:\n\t\t\timageStreamAnnotations[\"openshift.io/display-name\"] = \"Runtime image for Kogito based on SpringBoot\"\n\t\t\ttagAnnotations[\"description\"] = \"Runtime image for Kogito based on SpringBoot\"\n\t\t\ttagAnnotations[\"tags\"] = \"runtime,kogito,springboot\"\n\t\t\ttagAnnotations[\"supports\"] = \"springboot\"\n\t\t\tif kogitoApp.Spec.Runtime == v1alpha1.SpringbootRuntimeType {\n\t\t\t\tcreate = true\n\t\t\t}\n\n\t\tcase KogitoSpringbootUbi8s2iImage:\n\t\t\timageStreamAnnotations[\"openshift.io/display-name\"] = \"Platform for building Kogito based on SpringBoot\"\n\t\t\ttagAnnotations[\"description\"] = \"Platform for building Kogito based on SpringBoot\"\n\t\t\ttagAnnotations[\"tags\"] = \"builder,kogito,springboot\"\n\t\t\ttagAnnotations[\"supports\"] = \"springboot\"\n\t\t\tif kogitoApp.Spec.Runtime == v1alpha1.SpringbootRuntimeType {\n\t\t\t\tcreate = true\n\t\t\t}\n\t\t}\n\n\t\t// if no build type is provided, add all imagestream\n\t\tif create || kogitoApp.Spec.Runtime == \"\" {\n\t\t\tcurrentImageStream := imgv1.ImageStream{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: imageName,\n\t\t\t\t\tNamespace: kogitoApp.Namespace,\n\t\t\t\t\tAnnotations: imageStreamAnnotations,\n\t\t\t\t},\n\t\t\t\tSpec: imgv1.ImageStreamSpec{\n\t\t\t\t\tTags: []imgv1.TagReference{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: targetVersion,\n\t\t\t\t\t\t\tAnnotations: tagAnnotations,\n\t\t\t\t\t\t\tReferencePolicy: imgv1.TagReferencePolicy{\n\t\t\t\t\t\t\t\tType: imgv1.LocalTagReferencePolicy,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tFrom: &v1.ObjectReference{\n\t\t\t\t\t\t\t\tKind: \"DockerImage\",\n\t\t\t\t\t\t\t\tName: fmt.Sprintf(\"quay.io/kiegroup/%s:%s\", imageName, targetVersion),\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\tkogitoImageStreamList.Items = append(kogitoImageStreamList.Items, currentImageStream)\n\t\t}\n\t}\n\n\treturn kogitoImageStreamList\n}", "func (r *ImageRef) Metadata() *ImageMetadata {\n\treturn &ImageMetadata{\n\t\tFormat: r.Format(),\n\t\tWidth: r.Width(),\n\t\tHeight: r.Height(),\n\t\tOrientation: r.Orientation(),\n\t\tColorspace: r.ColorSpace(),\n\t\tPages: r.Pages(),\n\t}\n}", "func (a *ImagesApiService) GetImageMetadataByType(ctx context.Context, imageDigest string, mtype string) ApiGetImageMetadataByTypeRequest {\n\treturn ApiGetImageMetadataByTypeRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\timageDigest: imageDigest,\n\t\tmtype: mtype,\n\t}\n}", "func createImage(t *testing.T) (*Image, uint) {\n // Datastore ID 1 means default for image\n\tid, err := CreateImage(imageTpl, 1)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// Get Image by ID\n\timage := NewImage(id)\n\n\terr = image.Info()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\treturn image, id\n}", "func newImage(uid int64, imgname string, tag int, des string) CRImage {\n\treturn CRImage{\n\t\tUserId: uid,\n\t\tImageName: imgname,\n\t\tTag: tag,\n\t\tStar: 0,\n\t\tFork: 0,\n\t\tComm: 0,\n\t\tStatus: 0,\n\t\tDescrip: des,\n\t\tDate: time.Now().Format(\"2006-01-02\"),\n\t}\n}", "func (*UpdateImageMetadata) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_compute_v1_image_service_proto_rawDescGZIP(), []int{7}\n}", "func (f *TemplateFinder) GetMetadata(template *templatev1.Template, vm *ovirtsdk.Vm) (map[string]string, map[string]string, error) {\n\tos, err := f.osFinder.FindOperatingSystem(vm)\n\tif err != nil {\n\t\treturn map[string]string{}, map[string]string{}, err\n\t}\n\tworkload := getWorkload(vm)\n\tflavor := defaultFlavor\n\tlabels := templates.OSLabelBuilder(&os, &workload, &flavor)\n\n\tkey := fmt.Sprintf(templates.TemplateNameOsAnnotation, os)\n\tannotations := map[string]string{\n\t\tkey: template.GetAnnotations()[key],\n\t}\n\treturn labels, annotations, nil\n}", "func initImageNames() map[int]string {\n\tswitch getTestArch() {\n\tcase \"s390x\":\n\t\treturn map[int]string{\n\t\t\tbusyboxImage: \"busybox@sha256:4f47c01fa91355af2865ac10fef5bf6ec9c7f42ad2321377c21e844427972977\",\n\t\t\tregistryImage: \"ibmcom/registry:2.6.2.5\",\n\t\t\tkanikoImage: \"gcr.io/kaniko-project/executor:s390x-9ed158c1f63a059cde4fd5f8b95af51d452d9aa7\",\n\t\t\tdockerizeImage: \"ibmcom/dockerize-s390x\",\n\t\t}\n\tcase \"ppc64le\":\n\t\treturn map[int]string{\n\t\t\tbusyboxImage: \"busybox@sha256:4f47c01fa91355af2865ac10fef5bf6ec9c7f42ad2321377c21e844427972977\",\n\t\t\tregistryImage: \"ppc64le/registry:2\",\n\t\t\tkanikoImage: \"ibmcom/kaniko-project-executor-ppc64le:v0.17.1\",\n\t\t\tdockerizeImage: \"ibmcom/dockerize-ppc64le\",\n\t\t}\n\tdefault:\n\t\treturn map[int]string{\n\t\t\tbusyboxImage: \"busybox@sha256:895ab622e92e18d6b461d671081757af7dbaa3b00e3e28e12505af7817f73649\",\n\t\t\tregistryImage: \"registry\",\n\t\t\tkanikoImage: \"gcr.io/kaniko-project/executor:v1.3.0\",\n\t\t\tdockerizeImage: \"jwilder/dockerize\",\n\t\t}\n\t}\n}", "func (i ImageAnnotatorHandlerFuncs) CreateImageLabels(data interface{}, name string, count int) map[string]string {\n\tif i.ImageLabelCreationFunc != nil {\n\t\treturn i.ImageLabelCreationFunc(data, name, count)\n\t}\n\treturn make(map[string]string)\n}", "func (icon *identicon) Create() string {\n\n // TODO: create a method to determine the endianness of the machine\n v := binary.LittleEndian.Uint32(icon.hash[:]) // casts [32]uint8 to uint32\n\n // \n nrgba := color.NRGBA{\n\t\tR: uint8(v), // casts uint32 to uint8, reducing 0-4294967296 to 0-255 \n\t\tG: uint8(v >> 7), // v/2^7 => cast to uint8\n\t\tB: uint8(v >> 14), // v/2^14 => cast to uint8\n\t\tA: 0xff,\n\t}\n\n fmt.Println(nrgba)\n\n // create a new image with dimensions icon.dims x icon.dims\n idimage := image.NewNRGBA(image.Rectangle{image.Point{0,0},image.Point{icon.dims,icon.dims}})\n\n // set each pixel value, based on:\n // a) function x*y\n // b) on the string (using sha256 hash algorithm and the corresponding checksum)\n // c) RGBA colour setup\n //\n // a) determines the image pattern\n // b) and c) determine the image colour distribution\n for x := 0; x < icon.columns; x++ { // x axis\n for y := 0; y < (icon.rows); y++ { // y axis\n coef := uint8(x*y/icon.columns*icon.rows) // function governing the image pattern\n c := color.NRGBA{nrgba.R*coef, nrgba.G*coef, nrgba.B*coef, nrgba.A}\n idimage.Set(x,y,c)\n }\n }\n\n // \n var buf bytes.Buffer\n\tpng.Encode(&buf, idimage) // if buf.Bytes() are returned => set content header 'image/png'\n // then write w.Write(buf.Bytes())\n\n imgBase64Str := base64.StdEncoding.EncodeToString(buf.Bytes())\n return imgBase64Str\n}", "func (*ImageSpec) Descriptor() ([]byte, []int) {\n\treturn file_orc8r_protos_mconfig_mconfigs_proto_rawDescGZIP(), []int{3}\n}", "func imageWithMetadata(image *imagev1.Image) error {\n\t// Check if the metadata are already filled in for this image.\n\tmeta, hasMetadata := image.DockerImageMetadata.Object.(*dockerapiv10.DockerImage)\n\tif hasMetadata && meta.Size > 0 {\n\t\treturn nil\n\t}\n\n\tversion := image.DockerImageMetadataVersion\n\tif len(version) == 0 {\n\t\tversion = \"1.0\"\n\t}\n\n\tobj := &dockerapiv10.DockerImage{}\n\tif len(image.DockerImageMetadata.Raw) != 0 {\n\t\tif err := json.Unmarshal(image.DockerImageMetadata.Raw, obj); err != nil {\n\t\t\treturn err\n\t\t}\n\t\timage.DockerImageMetadata.Object = obj\n\t}\n\n\timage.DockerImageMetadataVersion = version\n\n\treturn nil\n}", "func createImageResource(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {\n\t// Warning or errors can be collected in a slice type\n\tvar diags diag.Diagnostics\n\n\tclient := (meta.(Client)).Client\n\tname := rdEntryStr(d, \"name\")\n\tid := rdEntryStr(d, \"id\")\n\terrMsgPrefix := fmt.Sprintf(\"[ERROR] Image %s (id: %s) Create Failed.\",\n\t\tname, id)\n\tif client == nil {\n\t\treturn diag.Errorf(\"%s nil Client\", errMsgPrefix)\n\t}\n\tcfg := &swagger_models.ImageConfig{\n\t\tName: &name,\n\t}\n\terr := updateImageCfgFromResourceData(cfg, d)\n\tif err != nil {\n\t\treturn diag.Errorf(\"%s %s\", errMsgPrefix, err.Error())\n\t}\n\tlog.Printf(\"[INFO] Creating Image: %s\", name)\n\tclient.XRequestIdPrefix = \"TF-image-create\"\n\trspData := &swagger_models.ZsrvResponse{}\n\t_, err = client.SendReq(\"POST\", imageUrlExtension, cfg, rspData)\n\tif err != nil {\n\t\treturn diag.Errorf(\"%s Err: %s\", errMsgPrefix, err.Error())\n\t}\n\tlog.Printf(\"Image %s (ID: %s) Successfully created\\n\",\n\t\trspData.ObjectName, rspData.ObjectID)\n\td.SetId(rspData.ObjectID)\n\treturn diags\n}", "func (i Img) generate() (*bytes.Buffer, error) {\n\t// If there are dimensions and there are no requirements for the Text, we will build the default Text.\n\tif ((i.Width > 0 || i.Height > 0) && i.Label.Text == \"\") || i.Label.Text == \"\" {\n\t\ti.Label.Text = fmt.Sprintf(\"%d x %d\", i.Width, i.Height)\n\t}\n\t// If there are no parameters for the font size, we will construct it based on the sizes of the image.\n\tif i.Label.FontSize == 0 {\n\t\ti.Label.FontSize = i.Width / 10\n\t\tif i.Height < i.Width {\n\t\t\ti.Label.FontSize = i.Height / 5\n\t\t}\n\t}\n\t// Convert the color from string to color.RGBA.\n\tclr, err := ToRGBA(i.Color)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Create an in-memory image with the desired size.\n\tm := image.NewRGBA(image.Rect(0, 0, i.Width, i.Height))\n\t//Draw a picture:\n\t// - in the sizes (Bounds)\n\t// - with color (Uniform - wrapper above color.Color with Image functions)\n\t// - based on the point (Point) as the base image\n\t// - fill with color Uniform (draw.Src)\n\tdraw.Draw(m, m.Bounds(), image.NewUniform(clr), image.Point{}, draw.Src)\n\t// add a text in the picture.\n\tif err = i.drawLabel(m); err != nil {\n\t\treturn nil, err\n\t}\n\tvar im image.Image = m\n\t// Allocate memory for our data (the bytes of the image)\n\tbuffer := &bytes.Buffer{}\n\t// Let's encode the image into our allocated memory.\n\terr = jpeg.Encode(buffer, im, nil)\n\n\treturn buffer, err\n}", "func image0(img image.Image) (Data, error) {\n\tbytes, mime, err := encodePng(img)\n\tif err != nil {\n\t\treturn Data{}, err\n\t}\n\treturn Data{\n\t\tData: BundledMIMEData{\n\t\t\tmime: bytes,\n\t\t},\n\t\tMetadata: BundledMIMEData{\n\t\t\tmime: imageMetadata(img),\n\t\t},\n\t}, nil\n}", "func seedRandomOCIManifest(t *testing.T, env *testEnv, repoPath string, opts ...manifestOptsFunc) *ocischema.DeserializedManifest {\n\tt.Helper()\n\n\tconfig := &manifestOpts{\n\t\trepoPath: repoPath,\n\t}\n\n\tfor _, o := range opts {\n\t\to(t, env, config)\n\t}\n\n\trepoRef, err := reference.WithName(repoPath)\n\trequire.NoError(t, err)\n\n\tmanifest := &ocischema.Manifest{\n\t\tVersioned: manifest.Versioned{\n\t\t\tSchemaVersion: 2,\n\t\t\tMediaType: v1.MediaTypeImageManifest,\n\t\t},\n\t}\n\n\t// Create a manifest config and push up its content.\n\tcfgPayload, cfgDesc := ociConfig()\n\tuploadURLBase, _ := startPushLayer(t, env, repoRef)\n\tpushLayer(t, env.builder, repoRef, cfgDesc.Digest, uploadURLBase, bytes.NewReader(cfgPayload))\n\tmanifest.Config = cfgDesc\n\n\t// Create and push up 2 random layers.\n\tmanifest.Layers = make([]distribution.Descriptor, 2)\n\n\tfor i := range manifest.Layers {\n\t\trs, dgst := createRandomSmallLayer()\n\n\t\tuploadURLBase, _ := startPushLayer(t, env, repoRef)\n\t\tpushLayer(t, env.builder, repoRef, dgst, uploadURLBase, rs)\n\n\t\tmanifest.Layers[i] = distribution.Descriptor{\n\t\t\tDigest: dgst,\n\t\t\tMediaType: v1.MediaTypeImageLayer,\n\t\t}\n\t}\n\n\tdeserializedManifest, err := ocischema.FromStruct(*manifest)\n\trequire.NoError(t, err)\n\n\tif config.putManifest {\n\t\tmanifestDigestURL := buildManifestDigestURL(t, env, repoPath, deserializedManifest)\n\n\t\tif config.manifestURL == \"\" {\n\t\t\tconfig.manifestURL = manifestDigestURL\n\t\t}\n\n\t\tresp := putManifest(t, \"putting manifest no error\", config.manifestURL, v1.MediaTypeImageManifest, deserializedManifest)\n\t\tdefer resp.Body.Close()\n\t\trequire.Equal(t, http.StatusCreated, resp.StatusCode)\n\t\trequire.Equal(t, \"nosniff\", resp.Header.Get(\"X-Content-Type-Options\"))\n\t\trequire.Equal(t, manifestDigestURL, resp.Header.Get(\"Location\"))\n\n\t\t_, payload, err := deserializedManifest.Payload()\n\t\trequire.NoError(t, err)\n\t\tdgst := digest.FromBytes(payload)\n\t\trequire.Equal(t, dgst.String(), resp.Header.Get(\"Docker-Content-Digest\"))\n\t}\n\n\treturn deserializedManifest\n}", "func (*Image) Descriptor() ([]byte, []int) {\n\treturn file_kit_kit_proto_rawDescGZIP(), []int{1}\n}", "func (*DilithiumMetaData) Descriptor() ([]byte, []int) {\n\treturn file_protos_metadata_proto_rawDescGZIP(), []int{0}\n}", "func NewMetadata(reader io.Reader) (Metadata, error) {\n\tformats := []string{\"UNKNOWN\", \"CUSTOM\", \"FILE\", \"TAR\", \"NULL\", \"DIRECTORY\"}\n\tyearStart := 1900\n\tmetadata := Metadata{}\n\n\tr := bufio.NewReader(reader)\n\tmagicBytes := 5\n\n\tmagicString, err := ReadExactString(r, magicBytes)\n\tif err != nil {\n\t\treturn metadata, fmt.Errorf(\"err reading magic bytes: %w\", err)\n\t}\n\n\tmetadata.Magic = magicString\n\n\tif metadata.Magic != \"PGDMP\" {\n\t\terr := fmt.Errorf(\"%w, expected=PGDMP, got=%s not a dump?\", ErrNotADump, metadata.Magic)\n\n\t\treturn metadata, err\n\t}\n\n\tmetadata.VMain = ReadExactInt(r, 1)\n\tmetadata.VMin = ReadExactInt(r, 1)\n\tmetadata.VRev = ReadExactInt(r, 1)\n\tmetadata.IntSize = ReadExactInt(r, 1)\n\tmetadata.OffSize = ReadExactInt(r, 1)\n\tmetadata.Format = formats[ReadExactInt(r, 1)]\n\tmetadata.Compression = metadata.ReadInt(r)\n\tmetadata.TimeSec = metadata.ReadInt(r)\n\tmetadata.TimeMin = metadata.ReadInt(r)\n\tmetadata.TimeHour = metadata.ReadInt(r)\n\tmetadata.TimeDay = metadata.ReadInt(r)\n\tmetadata.TimeMonth = metadata.ReadInt(r)\n\tmetadata.TimeYear = yearStart + metadata.ReadInt(r)\n\tmetadata.TimeIsDST = metadata.ReadInt(r)\n\tmetadata.DatabaseName = metadata.ReadString(r)\n\tmetadata.RemoteVersion = metadata.ReadString(r)\n\tmetadata.PGDumpVersion = metadata.ReadString(r)\n\tmetadata.TOCCount = metadata.ReadInt(r)\n\n\treturn metadata, nil\n}", "func NewMetaData(clientID UUID, clientMessageNumber uint64, transactionID UUID) MetaData {\n\tmd := make(MetaData, fb.SizeUint64*3)\n\tfb.WriteUint64(md[0:fb.SizeUint64], uint64(clientID))\n\tfb.WriteUint64(md[fb.SizeUint64:fb.SizeUint64*2], clientMessageNumber)\n\tfb.WriteUint64(md[fb.SizeUint64*2:fb.SizeUint64*3], uint64(transactionID))\n\treturn md\n}", "func Index() {\n\n\tfhnd, err := os.Open(\"testdata/the-wall-sample.jpg\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\timage, err := imgmeta.ReadJpeg(fhnd)\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\treturn\n\t}\n\n\tbasicInfo := GetBasicInfo(image)\n\tlog.Info(fmt.Sprintf(\"Title: %v\", basicInfo.Title))\n\tlog.Info(fmt.Sprintf(\"Image: width: %v, height: %v\", basicInfo.Width, basicInfo.Height))\n\tlog.Info(fmt.Sprintf(\"Keywords: %v\", basicInfo.Keywords))\n\n}", "func Metadata(name string, value ...string) {\n\tswitch def := dslengine.CurrentDefinition().(type) {\n\tcase *design.AttributeDefinition:\n\t\tif def.Metadata == nil {\n\t\t\tdef.Metadata = make(map[string][]string)\n\t\t}\n\t\tdef.Metadata[name] = append(def.Metadata[name], value...)\n\n\tcase *design.MediaTypeDefinition:\n\t\tif def.Metadata == nil {\n\t\t\tdef.Metadata = make(map[string][]string)\n\t\t}\n\t\tdef.Metadata[name] = append(def.Metadata[name], value...)\n\n\tcase *design.ActionDefinition:\n\t\tif def.Metadata == nil {\n\t\t\tdef.Metadata = make(map[string][]string)\n\t\t}\n\t\tdef.Metadata[name] = append(def.Metadata[name], value...)\n\n\tcase *design.ResourceDefinition:\n\t\tif def.Metadata == nil {\n\t\t\tdef.Metadata = make(map[string][]string)\n\t\t}\n\t\tdef.Metadata[name] = append(def.Metadata[name], value...)\n\n\tcase *design.ResponseDefinition:\n\t\tif def.Metadata == nil {\n\t\t\tdef.Metadata = make(map[string][]string)\n\t\t}\n\t\tdef.Metadata[name] = append(def.Metadata[name], value...)\n\n\tcase *design.APIDefinition:\n\t\tif def.Metadata == nil {\n\t\t\tdef.Metadata = make(map[string][]string)\n\t\t}\n\t\tdef.Metadata[name] = append(def.Metadata[name], value...)\n\n\tdefault:\n\t\tdslengine.IncompatibleDSL()\n\t}\n}", "func CreateRandomImage(namespace, name string) (*imageapiv1.Image, error) {\n\tconst layersCount = 2\n\n\tlayersDescs := make([]distribution.Descriptor, layersCount)\n\tfor i := range layersDescs {\n\t\t_, desc, err := MakeRandomLayer()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlayersDescs[i] = desc\n\t}\n\n\tmanifest, err := MakeSchema1Manifest(\"unused-name\", \"unused-tag\", layersDescs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, manifestSchema1, err := manifest.Payload()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewImageForManifest(\n\t\tfmt.Sprintf(\"%s/%s\", namespace, name),\n\t\tstring(manifestSchema1),\n\t\t\"\",\n\t\tfalse,\n\t)\n}", "func GenerateHostMetadata(metadata v2.Metadata) types.RouteMetaData {\n\trm := make(map[string]types.HashedValue, 1)\n\n\tfor k, v := range metadata {\n\t\tif vs, ok := v.(string); ok {\n\t\t\trm[k] = types.GenerateHashedValue(vs)\n\t\t}\n\t}\n\n\treturn rm\n}", "func (s *KSession) RandomWikiHow() (i WikiHowImage, err error) {\n\ti = WikiHowImage{}\n\tres, err := s.request(\"GET\", EndpointMemeWikihow(ParamWikiHow{}), nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(res, &i)\n\treturn\n}", "func getArticleMetadata(doc *goquery.Document) Metadata {\n\tmetadata := Metadata{}\n\tmapAttribute := make(map[string]string)\n\n\tdoc.Find(\"meta\").Each(func(_ int, meta *goquery.Selection) {\n\t\tmetaName, _ := meta.Attr(\"name\")\n\t\tmetaProperty, _ := meta.Attr(\"property\")\n\t\tmetaContent, _ := meta.Attr(\"content\")\n\n\t\tmetaName = strings.TrimSpace(metaName)\n\t\tmetaProperty = strings.TrimSpace(metaProperty)\n\t\tmetaContent = strings.TrimSpace(metaContent)\n\n\t\t// Fetch author name\n\t\tif strings.Contains(metaName+metaProperty, \"author\") {\n\t\t\tmetadata.Author = metaContent\n\t\t\treturn\n\t\t}\n\n\t\t// Fetch description and title\n\t\tif metaName == \"title\" ||\n\t\t\tmetaName == \"description\" ||\n\t\t\tmetaName == \"twitter:title\" ||\n\t\t\tmetaName == \"twitter:image\" ||\n\t\t\tmetaName == \"twitter:description\" {\n\t\t\tif _, exist := mapAttribute[metaName]; !exist {\n\t\t\t\tmapAttribute[metaName] = metaContent\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tif metaProperty == \"og:description\" ||\n\t\t\tmetaProperty == \"og:image\" ||\n\t\t\tmetaProperty == \"og:title\" {\n\t\t\tif _, exist := mapAttribute[metaProperty]; !exist {\n\t\t\t\tmapAttribute[metaProperty] = metaContent\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t})\n\n\t// Set final image\n\tif _, exist := mapAttribute[\"og:image\"]; exist {\n\t\tmetadata.Image = mapAttribute[\"og:image\"]\n\t} else if _, exist := mapAttribute[\"twitter:image\"]; exist {\n\t\tmetadata.Image = mapAttribute[\"twitter:image\"]\n\t}\n\n\tif metadata.Image != \"\" && strings.HasPrefix(metadata.Image, \"//\") {\n\t\tmetadata.Image = \"http:\" + metadata.Image\n\t}\n\n\t// Set final excerpt\n\tif _, exist := mapAttribute[\"description\"]; exist {\n\t\tmetadata.Excerpt = mapAttribute[\"description\"]\n\t} else if _, exist := mapAttribute[\"og:description\"]; exist {\n\t\tmetadata.Excerpt = mapAttribute[\"og:description\"]\n\t} else if _, exist := mapAttribute[\"twitter:description\"]; exist {\n\t\tmetadata.Excerpt = mapAttribute[\"twitter:description\"]\n\t}\n\n\t// Set final title\n\tmetadata.Title = getArticleTitle(doc)\n\tif metadata.Title == \"\" {\n\t\tif _, exist := mapAttribute[\"og:title\"]; exist {\n\t\t\tmetadata.Title = mapAttribute[\"og:title\"]\n\t\t} else if _, exist := mapAttribute[\"twitter:title\"]; exist {\n\t\t\tmetadata.Title = mapAttribute[\"twitter:title\"]\n\t\t}\n\t}\n\n\t// Clean up the metadata\n\tmetadata.Title = normalizeText(metadata.Title)\n\tmetadata.Excerpt = normalizeText(metadata.Excerpt)\n\n\treturn metadata\n}", "func GenRandomKindShip(nSamples int) string {\n // Prepare the seed for random\n rand.Seed(time.Now().UTC().UnixNano())\n\n ks := \"ego1,ego2,phi\\n\" // header\n for i := 0; i < nSamples; i++ {\n for j := i; j < nSamples; j++ {\n if i == j {\n ks += fmt.Sprintf(\"s_%d,s_%d,%f\\n\", i, j, 0.0)\n } else {\n ks += fmt.Sprintf(\"s_%d,s_%d,%f\\n\", i, j, float32(rand.Int31n(200))/float32(1000))\n }\n }\n }\n\n return ks\n}", "func DefImg(webpages bool) *Imgdata {\n\treturn &Imgdata{\n\t\tWebPage: webpages,\n\t}\n}", "func GenerateImageURL(name, image, date string) string {\n\tthing := url.URL{\n\t\tScheme: \"https\",\n\t\tHost: \"hackclub-birthday-bot.now.sh\",\n\t\tPath: \"/api/image\",\n\t}\n\tq := url.Values{}\n\tq.Set(\"text\", name)\n\tq.Set(\"image\", image)\n\tq.Set(\"date\", date)\n\tthing.RawQuery = q.Encode()\n\n\tmarshalled, _ := thing.MarshalBinary()\n\n\treturn string(marshalled)\n}", "func (*Images) Descriptor() ([]byte, []int) {\n\treturn file_kit_kit_proto_rawDescGZIP(), []int{0}\n}", "func headerWithFileMetaInformationGroupLength() (*headerData, error) {\n\theaderData := new(headerData)\n\n\tsopInstanceUidElement := mustNewElement(tag.SOPInstanceUID, []string{\"1.3.6.1.4.1.35190.4.1.20210608.607733549593\"})\n\telements := []*Element{\n\t\tmustNewElement(tag.FileMetaInformationVersion, []byte{0x00, 0x01}),\n\t\tmustNewElement(tag.MediaStorageSOPClassUID, []string{\"1.2.276.0.7230010.3.1.0.1\"}),\n\t\tmustNewElement(tag.MediaStorageSOPInstanceUID, []string{\"1.3.6.1.4.1.35190.4.1.20210608.607733549593\"}),\n\t\tmustNewElement(tag.TransferSyntaxUID, []string{\"=RLELossless\"}),\n\t\tmustNewElement(tag.ImplementationClassUID, []string{\"1.2.276.0.7230010.3.0.3.6.7\"}),\n\t\tmustNewElement(tag.ImplementationVersionName, []string{\"OFFIS_DCMTK_367\"}),\n\t}\n\tdataHeader, err := writeElements(elements)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfileMetaInfoElement := mustNewElement(tag.FileMetaInformationGroupLength, []int{len(dataHeader)})\n\tdataFileMetaInfo, err := writeElements([]*Element{fileMetaInfoElement})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdataSopInstanceUid, err := writeElements([]*Element{sopInstanceUidElement})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata := append(dataFileMetaInfo, dataHeader...)\n\tdata = append(data, dataSopInstanceUid...)\n\n\t// Construct valid DICOM header preamble.\n\tmagicWord := []byte(\"DICM\")\n\tpreamble := make([]byte, 128)\n\tpreamble = append(preamble, magicWord...)\n\theaderBytes := append(preamble, data...)\n\theaderData.HeaderBytes = bytes.NewBuffer(headerBytes)\n\theaderData.Elements = append([]*Element{fileMetaInfoElement}, elements...)\n\treturn headerData, nil\n}", "func (d *Driver) GetMetadata(id string) (map[string]string, error) {\n\tlogrus.Debugf(\"secureoverlay2: GetMetadata called w. id: %s\", id)\n\tdir := d.dir(id)\n\tif _, err := os.Stat(dir); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmetadata := map[string]string{\n\t\t\"WorkDir\": path.Join(dir, \"work\"),\n\t\t\"MergedDir\": path.Join(dir, \"merged\"),\n\t\t\"UpperDir\": path.Join(dir, \"diff\"),\n\t}\n\n\tlowerDirs, err := d.getLowerDirs(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(lowerDirs) > 0 {\n\t\tmetadata[\"LowerDir\"] = strings.Join(lowerDirs, \":\")\n\t}\n\n\t// additional data\n\ts, err := d.getSecurityMetaDataForID(id, \"\")\n\tswitch {\n\tcase err == nil:\n\t\tif s.RequiresConfidentiality {\n\t\t\t// embedd security meta-data if it is a secured image.\n\t\t\t// Note: only including it for secured images allows non-secured images still\n\t\t\t// to work with Manifest Schema 1 of registry. For secured images, in particular with\n\t\t\t// integrity, Schema 2 is essential to get the secure content-addressable nature of the image.\n\n\t\t\t// do some clean-up of unneeded params to declutter config/docker history\n\t\t\tif !s.RequiresConfidentiality {\n\t\t\t\ts.KeyHandle = \"\"\n\t\t\t\ts.KeyType = \"\"\n\t\t\t\ts.KeyTypeOption = \"\"\n\t\t\t\ts.KeyDesc = \"\"\n\t\t\t\ts.KeySize = \"\"\n\t\t\t\ts.KeyFilePath = \"\"\n\t\t\t\ts.CryptCipher = \"\"\n\t\t\t}\n\t\t\tbytes, _ := s.Encode()\n\t\t\tlogrus.Debugf(\"secureoverlay2: GetMetadata, adding (encoded) security meta-data %s\", s)\n\t\t\tmetadata[\"security-meta-data\"] = string(bytes)\n\t\t} else {\n\t\t\tctx = context.WithValue(context.TODO(), \"\", \"\")\n\t\t\tlogrus.Debug(\"secureoverlay2: GetMetadata, security meta-data indicates unsecured layer, skip security meta data addition\")\n\t\t}\n\tcase os.IsNotExist(err):\n\t\tlogrus.Debugf(\"secureoverlay2: GetMetadata, no security meta-data found to be added: %v\", err)\n\tdefault:\n\t\treturn nil, err\n\t}\n\n\tlogrus.Debugf(\"secureoverlay2: GetMetadata return w. metadata: %v\", metadata)\n\n\treturn metadata, nil\n}", "func (*DeleteImageMetadata) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_compute_v1_image_service_proto_rawDescGZIP(), []int{9}\n}", "func GenerateAndGetMeta(id string, args map[string]interface{}) ([]byte, error) {\n\tpipeline, err := GetPipeline(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err := pipeline.NewMetaRequest(args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pipeline.GenerateAndGet(req)\n}", "func GetMetaData(config *GCPConfig) *GCPMetadata {\n\twg := sync.WaitGroup{}\n\twg.Add(3)\n\thttpClient := &http.Client{\n\t\tTimeout: config.timeout,\n\t}\n\tmetadata := &GCPMetadata{}\n\tgo func() {\n\t\tmetadata.ContainerID = getContainerID(httpClient, config)\n\t\twg.Done()\n\t}()\n\tgo func() {\n\t\tmetadata.Region = getRegion(httpClient, config)\n\t\twg.Done()\n\t}()\n\tgo func() {\n\t\tmetadata.ProjectID = getProjectID(httpClient, config)\n\t\twg.Done()\n\t}()\n\twg.Wait()\n\treturn metadata\n}", "func (sample *SampleImage) Generate() error {\n\t\n\t// Generate the flags for the bind-mounts that we will use when running containers with Docker\n\thostdirMount := fmt.Sprintf(\"-v%s:/hostdir\", sample.RootDir)\n\tsocketMount := \"-v/var/run/docker.sock:/var/run/docker.sock\"\n\t\n\t// Remove our output directory if it already exists\n\tif sample.Exists() {\n\t\tif err := os.RemoveAll(sample.RootDir); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t\n\t// Create our output directory\n\tif err := os.MkdirAll(sample.RootDir, os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\t\n\t// Build the container image for git\n\tif err := DockerBuild(\"git:latest\", sample.DockerfilesDir, filepath.Join(sample.DockerfilesDir, \"Dockerfile.git\")); err != nil {\n\t\treturn err\n\t}\n\t\n\t// Build the container image for skopeo\n\tif err := DockerBuild(\"skopeo:latest\", sample.DockerfilesDir, filepath.Join(sample.DockerfilesDir, \"Dockerfile.skopeo\")); err != nil {\n\t\treturn err\n\t}\n\t\n\t// Build our sample container image\n\tif err := DockerBuild(\"sample-layers:latest\", sample.DockerfilesDir, filepath.Join(sample.DockerfilesDir, \"Dockerfile\")); err != nil {\n\t\treturn err\n\t}\n\t\n\t// Use skopeo to copy the sample container image to an OCI directory layout\n\tif err := DockerRun(\"skopeo:latest\", []string{\"copy\", \"docker-daemon:sample-layers:latest\", \"oci:/hostdir:latest\"}, []string{hostdirMount, socketMount}); err != nil {\n\t\treturn err\n\t}\n\t\n\t// Take ownership of the generated tarballs (since skopeo generates them as root)\n\talpineImage := \"alpine:3.13.5\"\n\tif err := DockerRun(alpineImage, []string{\"sh\", \"-c\", fmt.Sprintf(\"chown -R %d:%d /hostdir\", os.Getuid(), os.Getgid())}, []string{hostdirMount}); err != nil {\n\t\treturn err\n\t}\n\t\n\t// Parse the OCI image index\n\tindex := &oci.Index{}\n\tif err := marshal.UnmarshalJsonFile(filepath.Join(sample.RootDir, \"index.json\"), index); err != nil {\n\t\treturn err\n\t}\n\t\n\t// Verify that we have exactly one image manifest\n\tif len(index.Manifests) != 1 {\n\t\treturn errors.New(fmt.Sprint(\"expected exactly one image manifest in OCI index file, found \", len(index.Manifests)))\n\t}\n\t\n\t// Parse the image manifest\n\tmanifest := &oci.Manifest{}\n\tif err := marshal.UnmarshalJsonFile(filepath.Join(sample.BlobsDir, index.Manifests[0].Digest.Hex()), manifest); err != nil {\n\t\treturn err\n\t}\n\t\n\t// Verify that the archive blob exists for each filesystem layer\n\tfor _, layer := range manifest.Layers {\n\t\tarchive := filepath.Join(sample.BlobsDir, layer.Digest.Hex())\n\t\tif !filesystem.Exists(archive) {\n\t\t\treturn errors.New(fmt.Sprint(\"could not find archive blob for image layer with digest \", layer.Digest.Hex()))\n\t\t}\n\t}\n\t\n\t// Copy the merged view of the final filesystem layer to the host system so it can be compared to results generated by unpacking and applying the individual filesystem layers\n\tif err := DockerRun(\"sample-layers:latest\", []string{\"/bin/sh\", \"-c\", \"sleep infinity\"}, []string{\"-d\", \"--name\", \"sample-layers\"}); err != nil {\n\t\treturn err\n\t}\n\tif err := DockerCopy(\"sample-layers:/\", filepath.Join(sample.RootDir, \"ground-truth\")); err != nil {\n\t\treturn err\n\t}\n\tif err := DockerStop(\"sample-layers\"); err != nil {\n\t\treturn err\n\t}\n\t\n\treturn nil\n}", "func (factory *SevenBeeFactory) Image() string {\n\treturn factory.ID() + \".png\"\n}", "func Image(img []byte) string {\n\treturn ImageWidthHeight(img, 0, 0, true)\n}", "func (*Image) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_retail_v2_common_proto_rawDescGZIP(), []int{4}\n}", "func AutoCreate() (image.Image, string) {\n\tnum := Calc.Rand(10000000, 99999999)\n\timg, err := ManualCreate(4, Calc.Int2String(num))\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n\treturn img, Calc.Int2String(num)\n}", "func (*Image) Descriptor() ([]byte, []int) {\n\treturn file_internal_services_profile_proto_profile_proto_rawDescGZIP(), []int{4}\n}", "func Meta(asset_path string, target interface{}) error {\n pil := find(asset_path)\n if pil == nil { return os.ErrNotExist }\n return pil.asset.Meta(target)\n}", "func (*CreateMetadataStoreOperationMetadata) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_metadata_service_proto_rawDescGZIP(), []int{1}\n}", "func YearMetadata(year uint64) (m Meta, err error) {\n\treturn getMetadata(fmt.Sprintf(\"https://nvd.nist.gov/feeds/json/cve/1.0/nvdcve-1.0-%d.meta\", year))\n}", "func UniqueDatasetMetadata(value string) UniqueDatasetAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"metadata\"] = value\n\t}\n}", "func RepeatDatasetMetadata(value string) RepeatDatasetAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"metadata\"] = value\n\t}\n}", "func ImageInfo(d Ploop) (ImageInfoData, error) {\n\tvar cinfo C.struct_ploop_spec\n\tvar info ImageInfoData\n\n\tret := C.ploop_get_spec(d.d, &cinfo)\n\tif ret == 0 {\n\t\tinfo.blocks = uint64(cinfo.size)\n\t\tinfo.blocksize = uint32(cinfo.blocksize)\n\t\tinfo.version = int(cinfo.fmt_version)\n\t}\n\n\treturn info, mkerr(ret)\n}", "func (d UserData) Image() string {\n\tval := d.ModelData.Get(models.NewFieldName(\"Image\", \"image\"))\n\tif !d.Has(models.NewFieldName(\"Image\", \"image\")) {\n\t\treturn *new(string)\n\t}\n\treturn val.(string)\n}", "func (a *ImagesApiService) GetImageMetadataByTypeExecute(r ApiGetImageMetadataByTypeRequest) (*MetadataResponse, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue *MetadataResponse\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"ImagesApiService.GetImageMetadataByType\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/images/{imageDigest}/metadata/{mtype}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"imageDigest\"+\"}\", url.PathEscape(parameterToString(r.imageDigest, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"mtype\"+\"}\", url.PathEscape(parameterToString(r.mtype, \"\")), -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\tif r.xAnchoreAccount != nil {\n\t\tlocalVarHeaderParams[\"x-anchore-account\"] = parameterToString(*r.xAnchoreAccount, \"\")\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\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\tlocalVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))\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 == 500 {\n\t\t\tvar v ApiErrorResponse\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 DeleteImageMeta(key string) error {\n\terr := imageDb.Delete([]byte(key), pebble.Sync)\n\n\treturn err\n}", "func ShuffleAndRepeatDatasetMetadata(value string) ShuffleAndRepeatDatasetAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"metadata\"] = value\n\t}\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 LookupApiResultOutput) MetaData() GoogleCloudApigeeV1EntityMetadataResponseOutput {\n\treturn o.ApplyT(func(v LookupApiResult) GoogleCloudApigeeV1EntityMetadataResponse { return v.MetaData }).(GoogleCloudApigeeV1EntityMetadataResponseOutput)\n}", "func (t *Thread) GetPhotoMetaData(id string, block *repo.Block) (*model.PhotoMetadata, error) {\n\tfile, err := t.GetFileData(fmt.Sprintf(\"%s/meta\", id), block)\n\tif err != nil {\n\t\tlog.Errorf(\"error getting meta file %s: %s\", id, err)\n\t\treturn nil, err\n\t}\n\tvar data *model.PhotoMetadata\n\terr = json.Unmarshal(file, &data)\n\tif err != nil {\n\t\tlog.Errorf(\"error unmarshaling meta file: %s: %s\", id, err)\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func TestPngData(t *testing.T){\n\tsImagePath := \"./corpus/image/png-sample.png\"\n\tif oBytes, err := ioutil.ReadFile(sImagePath); err == nil{\n\t\toType := types.PNGType{}\n\t\tif bValid, oErr := IsBytesContentAValidType(oBytes, oType); bValid == false{\n\t\t\tif oErr != nil{\n\t\t\t\tt.Error(\"Image Has Less Than The Required Header Bytes\")\n\t\t\t}\n\t\t}\n\t}\n}", "func (g *Guessit) GuessMetadata(file *polochon.File, log *logrus.Entry) (*polochon.VideoMetadata, error) {\n\tfilePath := filepath.Base(file.Path)\n\tguess, err := g.client.Guess(filePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &polochon.VideoMetadata{\n\t\tQuality: polochon.Quality(guess.Quality),\n\t\tReleaseGroup: guess.ReleaseGroup,\n\t\tAudioCodec: guess.AudioCodec,\n\t\tVideoCodec: guess.VideoCodec,\n\t\tContainer: guess.Container,\n\t}, nil\n}", "func GetBasicInfo(img imgmeta.Image) (info BasicInfo) {\n\twidth, err := img.ReadTagValue(\"SOF0\", imgmeta.SOF0ImageWidth)\n\tif err == nil {\n\t\tinfo.Width = width\n\t} else {\n\t\tlog.Error(err.Error())\n\t}\n\theight, err := img.ReadTagValue(\"SOF0\", imgmeta.SOF0ImageHeight)\n\tif err == nil {\n\t\tinfo.Height = height.(uint32)\n\t} else {\n\t\tlog.Error(err.Error())\n\t}\n\tkeyword, err := img.ReadTagValue(\"IPTC\", imgmeta.IptcTagApplication2Keywords)\n\tif err == nil {\n\t\tinfo.Keywords = []string{keyword.(string)}\n\t}\n\tdatetime, err := img.ReadTagValue(\"EXIF\", imgmeta.ExifTagDateTimeOriginal)\n\tif err == nil {\n\t\tlog.Info(fmt.Sprintf(\"datetime:%v\\n\", datetime))\n\t}\n\n\timgTitle, err := img.ReadTagValue(\"IPTC\", imgmeta.IptcTagApplication2Caption)\n\tif err == nil {\n\t\tinfo.Title = imgTitle.(string)\n\t}\n\n\treturn\n}", "func GetGenericImageData() []*types.GenericImage {\n\n\treturn []*types.GenericImage{\n\t\t{\n\t\t\tID: \"fakeID0\",\n\t\t\tName: \"fakeName0\",\n\t\t},\n\t\t{\n\t\t\tID: \"fakeID1\",\n\t\t\tName: \"fakeName1\",\n\t\t},\n\t}\n}", "func ShuffleDatasetMetadata(value string) ShuffleDatasetAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"metadata\"] = value\n\t}\n}", "func (c *Compression) generateDataName(remote string, size int64, compressed bool) (newRemote string) {\n\tif compressed {\n\t\tnewRemote = remote + int64ToHex(size) + c.GetFileExtension()\n\t} else {\n\t\tnewRemote = remote + uncompressedFileExt\n\t}\n\treturn newRemote\n}", "func TestGenerator(t *testing.T) {\n\trand.Seed(1)\n\tfmt.Println(\"-------\")\n\tfmt.Println(\"Dataset with 10 examples, 4 features, 3 classes\")\n\tfmt.Println()\n\tdata, res := generator.CreateDataset(10, 4, 3)\n\tfor i, d := range data {\n\t\tfmt.Printf(\"[%.3f %.3f %.3f %.3f] => %d\\n\", d[0], d[1], d[2], d[3], res[i])\n\t}\n\n\tfmt.Println()\n\tfmt.Println(\"-------\")\n\tfmt.Println(\"Dataset with 20 examples, 6 features, 2 classes\")\n\tfmt.Println()\n\tdata, res = generator.CreateDataset(20, 6, 2)\n\tfor i, d := range data {\n\t\tfmt.Printf(\"[%.3f %.3f %.3f %.3f %.3f %.3f] => %d\\n\", d[0], d[1], d[2], d[3], d[4], d[5], res[i])\n\t}\n\n}", "func createFileMD(t *testing.T, size int, title string) *www.File {\n\tt.Helper()\n\n\tvar b bytes.Buffer\n\tb.WriteString(title + \"\\n\")\n\tr, err := util.Random(size)\n\tif err != nil {\n\t\tt.Fatalf(\"%v\", err)\n\t}\n\tb.WriteString(base64.StdEncoding.EncodeToString(r) + \"\\n\")\n\n\treturn &www.File{\n\t\tName: indexFile,\n\t\tMIME: mime.DetectMimeType(b.Bytes()),\n\t\tDigest: hex.EncodeToString(util.Digest(b.Bytes())),\n\t\tPayload: base64.StdEncoding.EncodeToString(b.Bytes()),\n\t}\n}", "func (*Image) Descriptor() ([]byte, []int) {\n\treturn file_api_proto_rawDescGZIP(), []int{1}\n}", "func GenerateMetaConfig(r io.Reader, w io.Writer) (*MetaConfig, error) {\n\tc := NewMetaConfig(bufio.NewScanner(r), w)\n\tc.InputFields()\n\treturn c, nil\n}" ]
[ "0.64154863", "0.6344503", "0.6223363", "0.6055937", "0.59988976", "0.5983204", "0.58828247", "0.5774375", "0.56949925", "0.56742597", "0.56483966", "0.5647617", "0.5611369", "0.5587889", "0.5495084", "0.54645044", "0.5394243", "0.53794676", "0.532331", "0.52885824", "0.5259388", "0.5242504", "0.5202031", "0.5182277", "0.5154097", "0.5153258", "0.5146167", "0.51331604", "0.512256", "0.5113015", "0.5111809", "0.5107735", "0.5083242", "0.50742304", "0.5071825", "0.50593376", "0.50584406", "0.50062835", "0.49813348", "0.49772772", "0.49673542", "0.49633434", "0.49604467", "0.49448535", "0.4934119", "0.49326015", "0.49239948", "0.49234697", "0.48965186", "0.4893808", "0.48891193", "0.4885871", "0.48677185", "0.4859893", "0.48574972", "0.4850534", "0.48492768", "0.48472226", "0.4836848", "0.48305959", "0.48233792", "0.48209345", "0.48055193", "0.47972345", "0.4791161", "0.4790728", "0.47905412", "0.47848073", "0.47809267", "0.47798714", "0.47764054", "0.47694746", "0.47685957", "0.47653666", "0.47643697", "0.4763398", "0.4760206", "0.47570804", "0.474889", "0.4748702", "0.47464624", "0.47462472", "0.47405773", "0.47387606", "0.47350353", "0.47331795", "0.47240746", "0.47240266", "0.47150472", "0.4711272", "0.47108668", "0.47104767", "0.4706785", "0.4705327", "0.47038966", "0.46993124", "0.4694129", "0.46894374", "0.46883988", "0.4687499" ]
0.78387123
0
Block returns the block identified on the request as a rosetta encoded block. NOTE: this is part of the BlockAPIServicer interface.
func (s *Server) Block(ctx context.Context, req *rtypes.BlockRequest) (*rtypes.BlockResponse, *rtypes.Error) { _, _, b, err := s.getBlockByPartialId(ctx, req.BlockIdentifier) if err != nil { return nil, types.DcrdError(err) } var prev *wire.MsgBlock // Fetch the previous block when the current block disapproves of its // parent, since we'll need to reverse the transactions in the parent. // We include a special check for the genesis block because it has // VoteBits == 0. approvesParent := b.Header.VoteBits&0x01 == 0x01 if !approvesParent && b.Header.Height > 0 { prev, err = s.c.GetBlock(ctx, &b.Header.PrevBlock) if err != nil { return nil, types.DcrdError(err, types.MapRpcErrCode(-5, types.ErrBlockNotFound)) } } fetchInputs := s.makeInputsFetcher(ctx, nil) rblock, err := types.WireBlockToRosetta(b, prev, fetchInputs, s.chainParams) if err != nil { return nil, types.RError(err) } return &rtypes.BlockResponse{ Block: rblock, }, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (rs *RosettaService) Block(ctx context.Context, request *rtypes.BlockRequest) (*rtypes.BlockResponse, *rtypes.Error) {\n\tvar block *rtypes.Block\n\tvar err *rtypes.Error\n\tswitch {\n\tcase request.BlockIdentifier.Index != nil:\n\t\tb, ok := rs.cs.BlockAtHeight(stypes.BlockHeight(*request.BlockIdentifier.Index))\n\t\tif !ok {\n\t\t\treturn nil, errUnknownBlock\n\t\t}\n\t\tblock, err = rs.convertBlock(b)\n\t\t// sanity check\n\t\tif err == nil && block.BlockIdentifier.Index != *request.BlockIdentifier.Index {\n\t\t\tpanic(\"block height mismatch\")\n\t\t}\n\n\tcase request.BlockIdentifier.Hash != nil:\n\t\tvar bid stypes.BlockID\n\t\tif err := bid.LoadString(*request.BlockIdentifier.Hash); err != nil {\n\t\t\treturn nil, errInvalidBlockID(err)\n\t\t}\n\t\tb, _, ok := rs.cs.BlockByID(bid)\n\t\tif !ok {\n\t\t\treturn nil, errUnknownBlock\n\t\t}\n\t\tblock, err = rs.convertBlock(b)\n\t\t// sanity check\n\t\tif err == nil && block.BlockIdentifier.Hash != *request.BlockIdentifier.Hash {\n\t\t\tpanic(\"block hash mismatch\")\n\t\t}\n\n\tdefault:\n\t\tblock, err = rs.convertBlock(rs.cs.CurrentBlock())\n\t}\n\n\treturn &rtypes.BlockResponse{\n\t\tBlock: block,\n\t}, err\n}", "func (api *Api) Block(number *int) (*models.Block, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), api.timeout)\n\tdefer cancel()\n\n\tblock, err := api.EthProxyServiceClient.Block(ctx, parseBlockGetter(number))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fetch block grpc api request: %w\", err)\n\t}\n\n\treturn models.BlockFromProto(block), nil\n}", "func (app *application) Block(additional uint) error {\n\tendpoint := fmt.Sprintf(\"%s%d\", \"/blocks/\", additional)\n\turl := fmt.Sprintf(baseFormat, app.url, endpoint)\n\n\tresp, err := app.client.R().\n\t\tSetHeader(shared.TokenHeadKeyname, app.token).\n\t\tPost(url)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp.StatusCode() == http.StatusOK {\n\t\treturn nil\n\t}\n\n\treturn errors.New(string(resp.Body()))\n}", "func (c *Client) Block() *Block {\n\treturn &Block{c}\n}", "func (api *GoShimmerAPI) GetBlock(base58EncodedID string) (*jsonmodels.Block, error) {\n\tres := &jsonmodels.Block{}\n\n\tif err := api.do(\n\t\thttp.MethodGet,\n\t\trouteBlock+base58EncodedID,\n\t\tnil,\n\t\tres,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}", "func getBlock(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {\n\n\thash, err := chainhash.NewHashFromStr(ps.ByName(\"hash\"))\n\tif err != nil {\n\t\tlog.Printf(\"could not convert string to hash: %s\\n\", err)\n\t}\n\n\tblock, err := dao.GetBlock(hash)\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Not found\")\n\t\treturn\n\t}\n\t//block.Confirmations = getBlockConfirmations(block)\n\t//block.Confirmations = getBlockConfirmations(*block) // needs dynamic calculation\n\n\t//apiblock, err := insight.ConvertToInsightBlock(block)\n\n\tjson.NewEncoder(w).Encode(&block)\n}", "func Block(b models.Block) *genModels.BlocksRow {\n\tts := b.Timestamp.Unix()\n\n\tgenBlock := genModels.BlocksRow{\n\t\tLevel: b.Level.Ptr(),\n\t\tProto: b.Proto.Ptr(),\n\t\tBlockTime: b.BlockTime,\n\t\tPredecessor: b.Predecessor.Ptr(),\n\t\tTimestamp: &ts,\n\t\tValidationPass: b.ValidationPass.Ptr(),\n\t\tFitness: b.Fitness.Ptr(),\n\t\tContext: b.Context,\n\t\tSignature: b.Signature,\n\t\tProtocol: b.Protocol.Ptr(),\n\t\tPriority: b.Priority.Ptr(),\n\t\tChainID: b.ChainID,\n\t\tHash: b.Hash.Ptr(),\n\t\tReward: &b.Reward,\n\t\tDeposit: b.Deposit,\n\t\tOperationsHash: b.OperationsHash,\n\t\tPeriodKind: b.PeriodKind,\n\t\tCurrentExpectedQuorum: b.CurrentExpectedQuorum,\n\t\tActiveProposal: b.ActiveProposal,\n\t\tBaker: b.Baker,\n\t\tBakerName: b.BakerName,\n\t\tNonceHash: b.NonceHash,\n\t\tConsumedGas: b.ConsumedGas,\n\t\tMetaLevel: b.MetaLevel,\n\t\tMetaLevelPosition: b.MetaLevelPosition,\n\t\tMetaCycle: b.MetaCycle,\n\t\tMetaCyclePosition: b.MetaCyclePosition,\n\t\tMetaVotingPeriod: b.MetaVotingPeriod,\n\t\tMetaVotingPeriodPosition: b.MetaVotingPeriodPosition,\n\t\tExpectedCommitment: b.ExpectedCommitment,\n\t}\n\n\tif b.BlockAggregation != nil {\n\t\tgenBlock.Volume = b.BlockAggregation.Volume\n\t\tgenBlock.Fees = b.BlockAggregation.Fees\n\t\tgenBlock.Endorsements = b.BlockAggregation.Endorsements\n\t\tgenBlock.Proposals = b.BlockAggregation.Proposals\n\t\tgenBlock.SeedNonceRevelations = b.BlockAggregation.SeedNonceRevelations\n\t\tgenBlock.Delegations = b.BlockAggregation.Delegations\n\t\tgenBlock.Transactions = b.BlockAggregation.Transactions\n\t\tgenBlock.ActivateAccounts = b.BlockAggregation.ActivateAccounts\n\t\tgenBlock.Ballots = b.BlockAggregation.Ballots\n\t\tgenBlock.Originations = b.BlockAggregation.Originations\n\t\tgenBlock.Reveals = b.BlockAggregation.Reveals\n\t\tgenBlock.DoubleBakingEvidence = b.BlockAggregation.DoubleBakingEvidences\n\t\tgenBlock.DoubleEndorsementEvidence = b.BlockAggregation.DoubleEndorsementEvidences\n\t\tgenBlock.NumberOfOperations = b.BlockAggregation.NumberOfOperations\n\t}\n\n\treturn &genBlock\n}", "func (rt *recvTxOut) Block() *BlockDetails {\n\treturn rt.block\n}", "func (dc *DeliverClient) RequestBlock(req *cb.Envelope) (*cb.Block, error) {\n\tde, conn, cancel, err := newAtomicBroadcastDeliverClient(dc.endpoint)\n\tif err != nil {\n\t\tlogger.Error(\"Error creating deliver client\", err)\n\t\treturn nil, err\n\t}\n\n\tdefer conn.Close()\n\tdefer de.CloseSend()\n\tdefer cancel()\n\n\terr = de.Send(req)\n\tif err != nil {\n\t\tlogger.Error(\"Error sending block request\", err)\n\t\treturn nil, err\n\t}\n\n\tmsg, err := de.Recv()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error receiving\")\n\t}\n\tswitch t := msg.Type.(type) {\n\tcase *ab.DeliverResponse_Status:\n\t\tlogger.Infof(\"Got status: %v\", t)\n\t\treturn nil, errors.Errorf(\"can't read the block: %v\", t)\n\tcase *ab.DeliverResponse_Block:\n\t\tlogger.Infof(\"Received block: %v\", t.Block.Header.Number)\n\t\tde.Recv() // Flush the success message\n\t\treturn t.Block, nil\n\tdefault:\n\t\treturn nil, errors.Errorf(\"response error: unknown type %T\", t)\n\t}\n}", "func (query *Query) GetBlock(ctx context.Context, height int64) (*model.Block, error) {\n\tresp, err := query.transport.QueryBlock(ctx, height)\n\tif err != nil {\n\t\treturn nil, errors.QueryFailf(\"GetBlock err\").AddCause(err)\n\t}\n\n\tblock := new(model.Block)\n\tblock.Header = resp.Block.Header\n\tblock.Evidence = resp.Block.Evidence\n\tblock.LastCommit = resp.Block.LastCommit\n\tblock.Data = new(model.Data)\n\tblock.Data.Txs = []model.Transaction{}\n\tfor _, txBytes := range resp.Block.Data.Txs {\n\t\tvar tx model.Transaction\n\t\tif err := query.transport.Cdc.UnmarshalJSON(txBytes, &tx); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tblock.Data.Txs = append(block.Data.Txs, tx)\n\t}\n\treturn block, nil\n}", "func (b *Block) Get(input *BlockInput) (*Block, error) {\n\tresp, err := b.c.Request(http.MethodGet, fmt.Sprintf(\"/blocks/%s\", input.ID), new(bytes.Buffer), nil)\n\tif err != nil {\n\t\treturn &Block{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar block *Block\n\terr = json.NewDecoder(resp.Body).Decode(&block)\n\tif err != nil {\n\t\treturn &Block{}, err\n\t}\n\treturn block, nil\n}", "func GetBlock(x uint64) block.Block{\r\n\t\tvar block1 block.MinBlock\r\n\t\tvar block2 block.Block\r\n\t\tblock1.BlockNumber = x\r\n\t\tblock1.ChainYear = ChainYear\r\n\t\tfmt.Println(\"ChainYear\", block1.ChainYear)\r\n\t\tdata, err:= json.Marshal(block1)\r\n\t\tif err !=nil{\r\n\t\t\tfmt.Println(\"Error Reading Block\", err)\r\n\t\t}\r\n\t\tfmt.Println(\"Block as Json\", data)\r\n\t\ttheNodes := GetNodes(block1.BlockHash())\r\n\t\t\r\n\t\tcall := \"getBlock\"\r\n\t\t\r\n\t\tfor x:=0; x < len(theNodes); x +=1{\r\n\t\t\t\t\r\n\t\t\turl1 := \"http://\"+ MyNode.Ip+ MyNode.Port+\"/\"+ call\r\n\t\t\tfmt.Println(\"url:\", url1)\r\n\t\t\t resp, err := http.Post(url1, \"application/json\", bytes.NewBuffer(data))\r\n\r\n\t\t\tif err != nil {\r\n\t\t\t\tfmt.Println(\"Error connectig to node trying next node \", err)\r\n\t\t\t}else{\r\n\t\t\t\tfmt.Println(\"Block as Json\", data)\r\n\t\t\t\tjson.NewDecoder(resp.Body).Decode(&block2)\r\n\t\t\t\treturn block2\r\n\t\t\t}\r\n\t\t}\r\nreturn block2\r\n\t\t\r\n\t\t\r\n}", "func GetBlock(hostURL string, hostPort int, hash string) *bytes.Buffer {\n\tparams := make(map[string]interface{})\n\tparams[\"hash\"] = hash\n\treturn makePostRequest(hostURL, hostPort, \"f_block_json\", params)\n}", "func (l *Channel) getBlock(blockNumber uint64) (*types.Block, error) {\n\tvar blockNumberInt *big.Int\n\tif blockNumber > 0 {\n\t\tblockNumberInt = big.NewInt(int64(blockNumber))\n\t}\n\n\td := time.Now().Add(5 * time.Second)\n\tctx, cancel := context.WithDeadline(context.Background(), d)\n\tdefer cancel()\n\n\tblock, err := l.client.BlockByNumber(ctx, blockNumberInt)\n\tif err != nil {\n\t\tif err.Error() == \"not found\" {\n\t\t\treturn nil, nil\n\t\t}\n\t\terr = errors.Wrap(err, \"Error getting block from geth\")\n\t\tl.log.WithField(\"block\", blockNumberInt.String()).Error(err)\n\t\treturn nil, err\n\t}\n\n\treturn block, nil\n}", "func (dc *PeerClient) RequestBlock(req *cb.Envelope) (*cb.Block, error) {\n\tde, conn, cancel, err := newPeerDeliverClient(dc.endpoint)\n\tif err != nil {\n\t\tlogger.Error(\"Error creating deliver client\", err)\n\t\treturn nil, err\n\t}\n\n\tdefer conn.Close()\n\tdefer de.CloseSend()\n\tdefer cancel()\n\n\terr = de.Send(req)\n\tif err != nil {\n\t\tlogger.Error(\"Error sending block request\", err)\n\t\treturn nil, err\n\t}\n\n\tmsg, err := de.Recv()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error receiving\")\n\t}\n\tswitch t := msg.Type.(type) {\n\tcase *pb.DeliverResponse_Status:\n\t\tlogger.Infof(\"Got status: %v\", t)\n\t\treturn nil, errors.Errorf(\"can't read the block: %v\", t)\n\tcase *pb.DeliverResponse_Block:\n\t\tlogger.Infof(\"Received block: %v\", t.Block.Header.Number)\n\t\tde.Recv() // Flush the success message\n\t\treturn t.Block, nil\n\tdefault:\n\t\treturn nil, errors.Errorf(\"response error: unknown type %T\", t)\n\t}\n}", "func NewBlock() *Block {\n\treturn &Block{}\n}", "func (s Store) GetBlock (hash string) (*types.FullSignedBlock, error) {\r\n\t// Open badger\r\n\tstor, err := badger.Open(badger.DefaultOptions(s.StorFileLocation))\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tdefer stor.Close()\r\n\r\n\tvar block types.FullSignedBlock\r\n\terr = stor.Update(func(txn *badger.Txn) error {\r\n\t\tbytes, err := readStringIndex (txn, hash, HashKeyPrefix)\r\n\t\tif err != nil{\r\n\t\t\treturn err\r\n\t\t}\r\n\t\terr = json.Unmarshal(bytes, &block)\r\n\r\n\t\treturn err\r\n\t})\r\n\r\n\treturn &block, err\r\n}", "func (w *FilteredBlockWrapper) Block() *pb.FilteredBlock {\r\n\treturn w.block\r\n}", "func NewBlock(tx *Transaction) *Block {\n\t\n\treturn nil\n}", "func (s *TransactionService) Block(block big.Int, limit int, cursor string) (models.TransactionPage, error) {\n\tif limit > 1000 {\n\t\tlimit = 1000\n\t}\n\treturn s.dao.Find(bson.M{\"number\": block.String()}, \"-_id\", limit, cursor)\n}", "func (obj Events) Block() Block {\n\treturn Block(obj)\n}", "func (a API) GetBlock(cmd *btcjson.GetBlockCmd) (e error) {\n\tRPCHandlers[\"getblock\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (c *Client) GetBlock(hash string) (resp *Block, e error) {\n\tif hash == \"\" || len(hash) != 64 {\n\t\treturn nil, c.err(ErrBHW)\n\t}\n\n\tresp = &Block{}\n\treturn resp, c.Do(\"/rawblock/\"+hash, resp, nil)\n}", "func (t T) Block() uint32 { return t.block }", "func getBlock(res rpc.GetBlockResponse) (GetBlockResponse, error) {\n\ttxs := make([]GetBlockTransaction, 0, len(res.Result.Transactions))\n\tfor _, rTx := range res.Result.Transactions {\n\t\tdata, ok := rTx.Transaction.([]interface{})\n\t\tif !ok {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to cast raw response to []interface{}\")\n\t\t}\n\t\tif data[1] != string(rpc.GetTransactionConfigEncodingBase64) {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"encoding mistmatch\")\n\t\t}\n\t\trawTx, err := base64.StdEncoding.DecodeString(data[0].(string))\n\t\tif err != nil {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to base64 decode data, err: %v\", err)\n\t\t}\n\t\ttx, err := types.TransactionDeserialize(rawTx)\n\t\tif err != nil {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to deserialize transaction, err: %v\", err)\n\t\t}\n\n\t\tvar transactionMeta *TransactionMeta\n\t\tif rTx.Meta != nil {\n\t\t\tinnerInstructions := make([]TransactionMetaInnerInstruction, 0, len(rTx.Meta.InnerInstructions))\n\t\t\tfor _, metaInnerInstruction := range rTx.Meta.InnerInstructions {\n\t\t\t\tcompiledInstructions := make([]types.CompiledInstruction, 0, len(metaInnerInstruction.Instructions))\n\t\t\t\tfor _, innerInstruction := range metaInnerInstruction.Instructions {\n\t\t\t\t\tdata, err := base58.Decode(innerInstruction.Data)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to base58 decode data, data: %v, err: %v\", innerInstruction.Data, err)\n\t\t\t\t\t}\n\t\t\t\t\tcompiledInstructions = append(compiledInstructions, types.CompiledInstruction{\n\t\t\t\t\t\tProgramIDIndex: innerInstruction.ProgramIDIndex,\n\t\t\t\t\t\tAccounts: innerInstruction.Accounts,\n\t\t\t\t\t\tData: data,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tinnerInstructions = append(innerInstructions, TransactionMetaInnerInstruction{\n\t\t\t\t\tIndex: metaInnerInstruction.Index,\n\t\t\t\t\tInstructions: compiledInstructions,\n\t\t\t\t})\n\t\t\t}\n\t\t\ttransactionMeta = &TransactionMeta{\n\t\t\t\tErr: rTx.Meta.Err,\n\t\t\t\tFee: rTx.Meta.Fee,\n\t\t\t\tPreBalances: rTx.Meta.PreBalances,\n\t\t\t\tPostBalances: rTx.Meta.PostBalances,\n\t\t\t\tPreTokenBalances: rTx.Meta.PreTokenBalances,\n\t\t\t\tPostTokenBalances: rTx.Meta.PostTokenBalances,\n\t\t\t\tLogMessages: rTx.Meta.LogMessages,\n\t\t\t\tInnerInstructions: innerInstructions,\n\t\t\t}\n\t\t}\n\n\t\ttxs = append(txs,\n\t\t\tGetBlockTransaction{\n\t\t\t\tMeta: transactionMeta,\n\t\t\t\tTransaction: tx,\n\t\t\t},\n\t\t)\n\t}\n\treturn GetBlockResponse{\n\t\tBlockhash: res.Result.Blockhash,\n\t\tBlockTime: res.Result.BlockTime,\n\t\tBlockHeight: res.Result.BlockHeight,\n\t\tPreviousBlockhash: res.Result.PreviousBlockhash,\n\t\tParentSLot: res.Result.ParentSLot,\n\t\tRewards: res.Result.Rewards,\n\t\tTransactions: txs,\n\t}, nil\n}", "func (b *Builder) Block() *Builder {\n\treturn new(Builder)\n}", "func (client *Client) GetBlock(blockID string) (*Response, error) {\n\tpath := \"/block\"\n\turi := fmt.Sprintf(\"%s%s/%s\", client.apiBaseURL, path, blockID)\n\n\treq, err := http.NewRequest(\"GET\", uri, bytes.NewBuffer([]byte(\"\")))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := client.performRequest(req, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar block Block\n\tif err := json.Unmarshal(resp.Response.([]byte), &block); err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Response = block\n\treturn resp, err\n}", "func (c *Client) BlockByHeight(height int64) (Block, error) {\n\ttimeout := time.Duration(10 * time.Second)\n\tclient := http.Client{\n\t\tTimeout: timeout,\n\t}\n\n\tpayload, err := json.Marshal(map[string]int64{\"height\": height})\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\n\tc.URL.Path = \"/block/at/public\"\n\treq, err := c.buildReq(nil, payload, http.MethodPost)\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\tdefer resp.Body.Close()\n\tbyteArray, err := ioutil.ReadAll(resp.Body)\n\tif resp.StatusCode != 200 {\n\t\terr := errors.New(string(byteArray))\n\t\treturn Block{}, err\n\t}\n\n\tvar data Block\n\tif err := json.Unmarshal(byteArray, &data); err != nil {\n\t\treturn Block{}, err\n\t}\n\treturn data, nil\n}", "func (rs *RosettaService) BlockTransaction(ctx context.Context, request *rtypes.BlockTransactionRequest) (*rtypes.BlockTransactionResponse, *rtypes.Error) {\n\t// all transactions are returned from /block\n\treturn nil, errNotImplemented\n}", "func (s *Server) getBlock(ctx context.Context, bh *chainhash.Hash) (*wire.MsgBlock, error) {\n\tbl, ok := s.cacheBlocks.Lookup(*bh)\n\tif ok {\n\t\treturn bl.(*wire.MsgBlock), nil\n\t}\n\n\tb, err := s.c.GetBlock(ctx, bh)\n\tif err == nil {\n\t\ts.cacheBlocks.Add(*bh, b)\n\t\treturn b, err\n\t}\n\n\tif rpcerr, ok := err.(*dcrjson.RPCError); ok && rpcerr.Code == dcrjson.ErrRPCBlockNotFound {\n\t\treturn nil, types.ErrBlockNotFound\n\t}\n\n\t// TODO: types.DcrdError()\n\treturn nil, err\n}", "func NewBlock(object dbus.BusObject) *Block {\n\treturn &Block{object}\n}", "func NewBlock(data *SPOTuple, prevBlockHash string) (*Block, error) {\n\n\tblock := &Block{\n\t\tBlockId: nuid.Next(),\n\t\tData: data,\n\t\tPrevBlockHash: prevBlockHash,\n\t\tHash: \"\",\n\t\tSig: \"\",\n\t\tAuthor: cs.PublicID(),\n\t\tSender: cs.PublicID(),\n\t}\n\n\t// assign new hash\n\tblock.setHash()\n\n\t// now sign the completed block\n\terr := block.sign()\n\tif err != nil {\n\t\tlog.Println(\"unable to sign block: \", err)\n\t\treturn nil, err\n\t}\n\n\treturn block, nil\n}", "func (p *bitsharesAPI) GetBlock(number uint64) (*objects.Block, error) {\n\tvar result *objects.Block\n\terr := p.call(p.databaseAPIID, \"get_block\", &result, number)\n\treturn result, err\n}", "func NewBlock(b *block.Block, chain blockchainer.Blockchainer) Block {\n\tres := Block{\n\t\tBlock: *b,\n\t\tBlockMetadata: BlockMetadata{\n\t\t\tSize: io.GetVarSize(b),\n\t\t\tConfirmations: chain.BlockHeight() - b.Index + 1,\n\t\t},\n\t}\n\n\thash := chain.GetHeaderHash(int(b.Index) + 1)\n\tif !hash.Equals(util.Uint256{}) {\n\t\tres.NextBlockHash = &hash\n\t}\n\n\treturn res\n}", "func NewBlock(tlvType uint32, value []byte) *Block {\n\tvar block Block\n\tblock.tlvType = tlvType\n\tblock.value = value\n\t// copy(block.value, value)\n\treturn &block\n}", "func (rs *rootResolver) Block(args *struct {\n\tNumber *hexutil.Uint64\n\tHash *types.Hash\n}) (*Block, error) {\n\t// do we have the number, or hash is not given?\n\tif args.Number != nil || args.Hash == nil {\n\t\t// get the block by the number, or get the top block\n\t\tblock, err := rs.repo.BlockByNumber(args.Number)\n\t\tif err != nil {\n\t\t\trs.log.Errorf(\"could not get the specified block\")\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn NewBlock(block, rs.repo), nil\n\t}\n\n\t// simply pull the block by hash\n\tblock, err := rs.repo.BlockByHash(args.Hash)\n\tif err != nil {\n\t\trs.log.Errorf(\"could not get the specified block\")\n\t\treturn nil, err\n\t}\n\n\treturn NewBlock(block, rs.repo), nil\n}", "func (bb blockBase) GetBlock() uint16 {\n\treturn bb.block\n}", "func NewBlock(chain uint64, producer Address) *StBlock {\n\tvar hashPowerLimit uint64\n\tvar blockInterval uint64\n\tvar pStat BaseInfo\n\tout := new(StBlock)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatHashPower}, &hashPowerLimit)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBlockInterval}, &blockInterval)\n\n\tif pStat.ID == 0 {\n\t\tlog.Println(\"fail to get the last block. chain:\", chain)\n\t\treturn nil\n\t}\n\n\thashPowerLimit = hashPowerLimit / 1000\n\tif hashPowerLimit < minHPLimit {\n\t\thashPowerLimit = minHPLimit\n\t}\n\n\tout.HashpowerLimit = hashPowerLimit\n\n\tif pStat.ID == 1 && chain > 1 {\n\t\tpStat.Time = pStat.Time + blockSyncMax + blockSyncMin + TimeSecond\n\t} else {\n\t\tpStat.Time += blockInterval\n\t}\n\n\tout.Previous = pStat.Key\n\tout.Producer = producer\n\tout.Time = pStat.Time\n\n\tout.Chain = chain\n\tout.Index = pStat.ID + 1\n\n\tif pStat.Chain > 1 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID+1), &key)\n\t\tgetDataFormLog(chain/2, logBlockInfo{}, key[:], &tmp)\n\t\tif out.Index != 2 && !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID+2), &key2)\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.Parent = key2\n\t\t\t} else {\n\t\t\t\tout.Parent = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else {\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID), &key)\n\t\t\tout.Parent = key\n\t\t}\n\t}\n\tif pStat.LeftChildID > 0 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID+1), &key)\n\t\tgetDataFormLog(2*chain, logBlockInfo{}, key[:], &tmp)\n\t\tif !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID+2), &key2)\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.LeftChild = key2\n\t\t\t} else {\n\t\t\t\tout.LeftChild = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else if pStat.LeftChildID == 1 {\n\t\t\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID), &key)\n\t\t\tout.LeftChild = key\n\t\t} else {\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID), &key)\n\t\t\tout.LeftChild = key\n\t\t}\n\t}\n\tif pStat.RightChildID > 0 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID+1), &key)\n\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, key[:], &tmp)\n\t\tif !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID+2), &key2)\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.RightChild = key2\n\t\t\t} else {\n\t\t\t\tout.RightChild = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else if pStat.RightChildID == 1 {\n\t\t\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(pStat.RightChildID), &key)\n\t\t\tout.RightChild = key\n\t\t} else {\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID), &key)\n\t\t\tout.RightChild = key\n\t\t}\n\t}\n\n\treturn out\n}", "func DecodeBlock(data []byte) *StBlock {\n\tout := new(StBlock)\n\tout.sign = data[1 : data[0]+1]\n\tbData := data[data[0]+1:]\n\tn := runtime.Decode(bData, &out.Block)\n\tstream := bData[n:]\n\tif len(stream)%HashLen != 0 {\n\t\treturn nil\n\t}\n\tif out.Index < 1 {\n\t\treturn nil\n\t}\n\n\trst := wallet.Recover(out.Producer[:], out.sign, bData)\n\tif !rst {\n\t\tlog.Printf(\"fail to recover block,producer:%x\\n\", out.Producer)\n\t\treturn nil\n\t}\n\th := runtime.GetHash(data)\n\truntime.Decode(h, &out.Key)\n\n\treturn out\n}", "func (bh *BlockHolder) GetBlock() *protos.Block2 {\n\tserBlock := protos.NewSerBlock2(bh.blockBytes)\n\tblock, err := serBlock.ToBlock2()\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Problem in deserialzing block: %s\", err))\n\t}\n\treturn block\n}", "func (s *BlocksService) Get(ctx context.Context, id string) (*GetBlock, *http.Response, error) {\n\tquery := &BlockIdQuery{Id: id}\n\n\tvar responseStruct *GetBlock\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"blocks/get\", query, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (c *Chain) GenerateBlock(when int, who string, privkey *ecdsa.PrivateKey) (*core.Block, error) {\n\tif when <= c.Gpo().Time || when != c.Gpo().Time+config.BlockInterval {\n\t\treturn nil, fmt.Errorf(\"incorrect time\")\n\t}\n\n\twitness, err := c.sdb.GetAccountByName(who)\n\tif err != nil || witness.PublicKey != utils.EncodePubKeyInPem(&privkey.PublicKey) {\n\t\treturn nil, fmt.Errorf(\"incorret witness or key\")\n\t}\n\n\tb := core.Block{\n\t\t// ID will be set later\n\t\tNum: c.Gpo().BlockNum,\n\t\tPrevBlockId: c.Gpo().BlockId,\n\t\tCreatedOn: when,\n\t\tWitness: who,\n\t}\n\n\t// move pending txs to block\n\tc.movePendingTransactionsToBlock(&b)\n\t//c.MoveTxToBlock(&b)\n\n\t// set b.ID\n\t// set b.MerkleRoot\n\treturn &b, nil\n}", "func (s Store) StoreBlock (block types.FullSignedBlock) error {\r\n\r\n\t// Open badger\r\n\tstor, err := badger.Open(badger.DefaultOptions(s.StorFileLocation))\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tdefer stor.Close()\r\n\r\n\t// Serialize all the parts: block in json\r\n\tbytes, err := json.Marshal(block)\r\n\r\n\terr = stor.Update(func(txn *badger.Txn) error {\r\n\r\n\t\tvar txErr error\r\n\t\t// Store the hash as a key. This is the main register\r\n\t\tif txErr = storeStringIndex(txn, block.Hash, bytes, HashKeyPrefix); txErr == nil {\r\n\t\t\t// And now store the indexes. Using this indexes it is possible to retrieve the hash, and next the block\r\n\t\t\tif txErr = storeUIntIndex(txn, block.Timestamp, []byte(block.Hash), TimestampKeyPrefix); txErr != nil { // By timestamp\r\n\t\t\t\treturn txErr\r\n\t\t\t}\r\n\r\n\t\t\tif txErr = storeUIntIndex(txn, block.Height, []byte(block.Hash), HeightKeyPrefix); txErr != nil { // By block Height\r\n\t\t\t\treturn txErr\r\n\t\t\t}\r\n\t\t} \r\n\r\n\t\t return txErr\r\n\t})\r\n\r\n\treturn err\r\n}", "func MineBlock(w http.ResponseWriter, r *http.Request) {\n\t// Checks for the block in data field\n\tvar data BlockData\n\terr := json.NewDecoder(r.Body).Decode(&data)\n\tif err != nil {\n\t\tlog.Println(\"MineBlock: Received block failed to prase(JSON)\")\n\t}\n\n\tsuccess := b.GenerateNextBlock(data.Data)\n\tif success {\n\t\thub.broadcastMsg(RespLatestMsg())\n\t}\n}", "func NewBlock(transactionPool *mempool, previousBlock *Block) *Block {\n\n\tcurrentBlock := Block{}\n\tcurrentBlock.PreviousBlock = previousBlock\n\n\t// First, select which transactions the block will contain\n\tselectedTransactions := selectTransactions(transactionPool)\n\tcurrentBlock.Transactions = selectedTransactions\n\n\t// Second, calculate the hash of the selected transactions\n\thashedTransaction := string(processTransactions(selectedTransactions))\n\thashedBlockData := hashedTransaction + currentBlock.Hash\n\tcurrentBlock.Hash = hashedBlockData\n\treturn &currentBlock\n}", "func NewBlock(block Block, data string) Block {\r\n\tt := time.Now().Unix()\r\n\tBlockID := block.BlockID\r\n\tBlockID++\r\n\thashed := sha256.Sum256([]byte(data))\r\n\tsignature, err := rsa.SignPKCS1v15(rand.Reader, nodeinfo.PrivateKey, crypto.SHA256, hashed[:])\r\n\tif err != nil {\r\n\t\tlog.Fatalln(err)\r\n\t}\r\n\tnonce, hash := computeHashWithProofOfWork(IntToStr(BlockID)+IntToStr(t)+data+string(signature)+nodeinfo.NodeID+block.Hash, nodeinfo.Difficulty)\r\n\treturn Block{BlockID, t, data, signature, nodeinfo.NodeID, block.Hash, hash, nonce}\r\n}", "func (bp RPCBlockProvider) GetBlock(index int) SignedBlockData {\r\n\tvar block SignedBlockData\r\n\terr := bp.Client.Call(\"BlockPropagationHandler.GetBlock\", index, &block)\r\n\tif err != nil {\r\n\t\tlog.Print(err)\r\n\t}\r\n\treturn block\r\n}", "func NewBlock(width float64, height float64) *Block {\n\tb := &Block{}\n\tb.contents = &contentstream.ContentStreamOperations{}\n\tb.resources = model.NewPdfPageResources()\n\tb.width = width\n\tb.height = height\n\treturn b\n}", "func (wc *WalletClient) NewBlock(b Block) error {\n\t_, err := wc.POST(\"/new-block\", b.Json())\n\treturn err\n}", "func (dao *blockDAO) getBlock(hash hash.Hash256) (*block.Block, error) {\n\theader, err := dao.header(hash)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get block header %x\", hash)\n\t}\n\tbody, err := dao.body(hash)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get block body %x\", hash)\n\t}\n\tfooter, err := dao.footer(hash)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get block footer %x\", hash)\n\t}\n\treturn &block.Block{\n\t\tHeader: *header,\n\t\tBody: *body,\n\t\tFooter: *footer,\n\t}, nil\n}", "func (c *DaemonClient) GetBlock(height uint, hash string) (Block, error) {\n\tvar b Block\n\treq := struct {\n\t\theight uint `json:\"height, omitempty\"`\n\t\thash string `json:\"hash, omitempty\"`\n\t}{\n\t\theight,\n\t\thash,\n\t}\n\tif err := call(c.endpoint, \"getblock\", req, &b); err != nil {\n\t\treturn b, err\n\t}\n\treturn b, nil\n}", "func NewBlock(blk *types.Block, repo repository.Repository) *Block {\n\treturn &Block{\n\t\trepo: repo,\n\t\tBlock: *blk,\n\t}\n}", "func (nc *NSBClient) GetBlock(id int64) (*BlockInfo, error) {\n\tb, err := nc.handler.Group(\"/block\").GetWithParams(request.Param{\n\t\t\"height\": id,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar bb []byte\n\tbb, err = nc.preloadJSONResponse(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar a BlockInfo\n\terr = json.Unmarshal(bb, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &a, nil\n}", "func (c *SyscallService) QueryBlock(ctx context.Context, in *pb.QueryBlockRequest) (*pb.QueryBlockResponse, error) {\n\tnctx, ok := c.ctxmgr.Context(in.GetHeader().Ctxid)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"bad ctx id:%d\", in.Header.Ctxid)\n\t}\n\n\trawBlockid, err := hex.DecodeString(in.Blockid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblock, err := nctx.Cache.QueryBlock(rawBlockid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttxids := []string{}\n\tfor _, t := range block.Transactions {\n\t\ttxids = append(txids, hex.EncodeToString(t.Txid))\n\t}\n\n\tblocksdk := &pb.Block{\n\t\tBlockid: hex.EncodeToString(block.Blockid),\n\t\tPreHash: block.PreHash,\n\t\tProposer: block.Proposer,\n\t\tSign: block.Sign,\n\t\tPubkey: block.Pubkey,\n\t\tHeight: block.Height,\n\t\tTxids: txids,\n\t\tTxCount: block.TxCount,\n\t\tInTrunk: block.InTrunk,\n\t\tNextHash: block.NextHash,\n\t}\n\n\treturn &pb.QueryBlockResponse{\n\t\tBlock: blocksdk,\n\t}, nil\n}", "func Block(ctx context.Context, opts Opts) schema.Block {\n\treturn schema.SingleNestedBlock{\n\t\tAttributes: attributesMap(opts),\n\t\tCustomType: Type{\n\t\t\tObjectType: types.ObjectType{\n\t\t\t\tAttrTypes: attrTypesMap(opts),\n\t\t\t},\n\t\t},\n\t}\n}", "func (b *BlockDAG) Block(id models.BlockID) (block *blockdag.Block, exists bool) {\n\tb.evictionMutex.RLock()\n\tdefer b.evictionMutex.RUnlock()\n\n\treturn b.block(id)\n}", "func (b *Block) Type() string {\n\treturn \"block\"\n}", "func (client *Client) QueryBlock(request *QueryBlockRequest) (response *QueryBlockResponse, err error) {\n\tresponse = CreateQueryBlockResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (_AnchorChain *AnchorChainSession) ViewBlock(i *big.Int) (string, error) {\n\treturn _AnchorChain.Contract.ViewBlock(&_AnchorChain.CallOpts, i)\n}", "func (cia *chainInfoAPI) BlockTime(ctx context.Context) time.Duration {\n\treturn cia.chain.config.BlockTime()\n}", "func NewRawBlock() *RawBlock {\n\treturn &RawBlock{}\n}", "func (c *Client) GetBlock(hash string) (block *rpctypes.ResultBlock, err error) {\n\tblock = new(rpctypes.ResultBlock)\n\terr = c.get(block, c.URL(\"block/hash/%s\", hash))\n\terr = errors.Wrap(err, \"getting block by hash\")\n\treturn\n}", "func NewBlock(oldBlock Block, data string) Block {\n\t// fmt.Println(\"******TODO: IMPLEMENT NewBlock!******\")\n\tblock := Block{Data: data, Timestamp: time.Now().Unix(), PrevHash: oldBlock.Hash, Hash: []byte{}}\n\tblock.Hash = block.calculateHash()\n\t// fmt.Println(\"data: \" + block.Data)\n\t// fmt.Printf(\"timestamp: %d\", block.Timestamp)\n\t// fmt.Println()\n\t// fmt.Printf(\"preHash: %x\", block.PrevHash)\n\t// fmt.Println()\n\t// fmt.Printf(\"currentHash: %x\", block.Hash)\n\t// fmt.Println()\n\t// fmt.Println(\"******TODO: END NewBlock!******\")\n\t// fmt.Println()\n\t// fmt.Println()\n\t// fmt.Println()\n\treturn block\n}", "func NewBlock(transactions []*Transaction, preBlockHash []byte) *Block {\n\tb := &Block{time.Now().Unix(), transactions, preBlockHash, []byte{}, 252, 0}\n\n\tpow := NewProofOfWork(b)\n\tnonce, hash := pow.Run()\n\n\tb.Nonce = nonce\n\tb.Hash = hash[:]\n\n\treturn b\n}", "func (bc BlockChain) deserializeBlock(o []byte) *Block {\r\n\tif !json.Valid(o) {\r\n\t\tpanic(\"Input is not a valid json object for block\")\r\n\t}\r\n\r\n\tvar jsonBlock Block\r\n\tvar b Block\r\n\t/**\r\n\tdec := json.NewDecoder(strings.NewReader(string(\to)))\r\n\tif err := dec.Decode(&jsonBlock); err == io.EOF {\r\n\t} else if err != nil {\r\n\t\tlog.Fatal(err)\r\n\t}\r\n\t**/\r\n\terr := json.Unmarshal(o, &jsonBlock)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\t//fmt.Println(\"new block is \" + jsonBlock.Serialize())\r\n\r\n\tbalances := make(map[string]int)\r\n\tchainLength := jsonBlock.ChainLength\r\n\ttimestamp := jsonBlock.Timestamp\r\n\r\n\tif jsonBlock.IsGenesisBlock() {\r\n\t\t//fmt.Println(\"setting balances\")\r\n\t\t//fmt.Println(jsonBlock.Balances)\r\n\t\tfor client, amount := range jsonBlock.Balances {\r\n\t\t\tbalances[client] = amount\r\n\t\t}\r\n\t\tb.Balances = balances\r\n\t} else {\r\n\t\tprevBlockHash := jsonBlock.PrevBlockHash\r\n\t\tproof := jsonBlock.Proof\r\n\t\trewardAddr := jsonBlock.RewardAddr\r\n\t\ttransactions := make(map[string]*Transaction)\r\n\t\tif jsonBlock.Transactions != nil {\r\n\t\t\tfor id, tx := range jsonBlock.Transactions {\r\n\t\t\t\ttransactions[id] = tx\r\n\t\t\t}\r\n\t\t}\r\n\t\t//GOTTA FIX THIS WHEN YOU IMPLEMENT CONSTANTS\r\n\t\tb = *bc.MakeBlock(rewardAddr, nil, nil, nil)\r\n\t\tb.ChainLength = chainLength\r\n\t\tb.Timestamp = timestamp\r\n\t\tb.PrevBlockHash = prevBlockHash\r\n\t\tb.Proof = proof\r\n\t\tb.Transactions = transactions\r\n\t}\r\n\treturn &b\r\n}", "func (bd *BlockDAG) getBlock(h *hash.Hash) IBlock {\n\tif h == nil {\n\t\treturn nil\n\t}\n\tblock, ok := bd.blocks[*h]\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn block\n}", "func NewBlock(index idx.Block, time Timestamp, events hash.Events, prevHash hash.Event) *Block {\n\treturn &Block{\n\t\tIndex: index,\n\t\tTime: time,\n\t\tEvents: events,\n\t\tPrevHash: prevHash,\n\t\tSkippedTxs: make([]uint, 0),\n\t}\n}", "func (_AnchorChain *AnchorChainCallerSession) ViewBlock(i *big.Int) (string, error) {\n\treturn _AnchorChain.Contract.ViewBlock(&_AnchorChain.CallOpts, i)\n}", "func (br *BlockRepository) constructBlockResponse(rf *recordFile, blockIndex int64) *types.Block {\n\tparentIndex := blockIndex - 1\n\tparentHash := rf.PrevHash\n\n\t// Handle the edge case for querying first block\n\tif rf.PrevHash == genesisPreviousHash {\n\t\tparentIndex = 0 //Parent index should be 0, same as current block index\n\t\tparentHash = rf.FileHash // Parent hash should be same as current block hash\n\t}\n\treturn &types.Block{\n\t\tIndex: blockIndex,\n\t\tHash: rf.FileHash,\n\t\tParentIndex: parentIndex,\n\t\tParentHash: parentHash,\n\t\tConsensusStartNanos: rf.ConsensusStart,\n\t\tConsensusEndNanos: rf.ConsensusEnd,\n\t}\n}", "func NewBlock(t *testing.T, bc blockchainer.Blockchainer, offset uint32, primary uint32, txs ...*transaction.Transaction) *block.Block {\n\twitness := transaction.Witness{VerificationScript: MultisigVerificationScript()}\n\theight := bc.BlockHeight()\n\th := bc.GetHeaderHash(int(height))\n\thdr, err := bc.GetHeader(h)\n\trequire.NoError(t, err)\n\tb := &block.Block{\n\t\tHeader: block.Header{\n\t\t\tPrevHash: hdr.Hash(),\n\t\t\tTimestamp: (uint64(time.Now().UTC().Unix()) + uint64(hdr.Index)) * 1000,\n\t\t\tIndex: hdr.Index + offset,\n\t\t\tPrimaryIndex: byte(primary),\n\t\t\tNextConsensus: witness.ScriptHash(),\n\t\t\tScript: witness,\n\t\t},\n\t\tTransactions: txs,\n\t}\n\tb.RebuildMerkleRoot()\n\n\tb.Script.InvocationScript = Sign(b)\n\treturn b\n}", "func (ds *Dsync) ReceiveBlock(sid, hash string, data []byte) ReceiveResponse {\n\tsess, ok := ds.sessionPool[sid]\n\tif !ok {\n\t\treturn ReceiveResponse{\n\t\t\tHash: hash,\n\t\t\tStatus: StatusErrored,\n\t\t\tErr: fmt.Errorf(\"sid %q not found\", sid),\n\t\t}\n\t}\n\n\t// ReceiveBlock accepts a block from the sender, placing it in the local blockstore\n\tres := sess.ReceiveBlock(hash, bytes.NewReader(data))\n\n\t// check if transfer has completed, if so finalize it, but only once\n\tif res.Status == StatusOk && sess.IsFinalizedOnce() {\n\t\tif err := ds.finalizeReceive(sess); err != nil {\n\t\t\treturn ReceiveResponse{\n\t\t\t\tHash: sess.info.RootCID().String(),\n\t\t\t\tStatus: StatusErrored,\n\t\t\t\tErr: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res\n}", "func (env *Env) CheckBlock(pdu *libcoap.Pdu) (bool, *string, *libcoap.Block) {\n blockValue, err := pdu.GetOptionIntegerValue(libcoap.OptionBlock2)\n if err != nil {\n log.WithError(err).Warn(\"Get block2 option value failed.\")\n return false, nil, nil\n\t}\n block := libcoap.IntToBlock(int(blockValue))\n\n size2Value, err := pdu.GetOptionIntegerValue(libcoap.OptionSize2)\n\tif err != nil {\n\t\tlog.WithError(err).Warn(\"Get size 2 option value failed.\")\n return false, nil, nil\n }\n\n eTag := pdu.GetOptionOpaqueValue(libcoap.OptionEtag)\n\n if block != nil {\n isMoreBlock := true\n blockKey := eTag + string(pdu.Token)\n // If block.M = 1, block is more block. If block.M = 0, block is last block\n if block.M == libcoap.MORE_BLOCK {\n log.Debugf(\"Response block is comming (eTag=%+v, block=%+v, size2=%+v) for request (token=%+v), waiting for the next block.\", eTag, block.ToString(), size2Value, pdu.Token)\n if block.NUM == 0 {\n env.responseBlocks[blockKey] = pdu\n initialBlockSize := env.InitialRequestBlockSize()\n secondBlockSize := env.SecondRequestBlockSize()\n // Check what block_size is used for block2 option\n // If the initialBlockSize is set: client will always request with block2 option\n // If the initialBlockSize is not set and the secondBlockSize is set: if the secondBlockSize is greater than the\n // recommended block size -> use the recommended block size, reversely, use the configured block size\n // If both initialBlockSize and secondBlockSize are not set -> use the recommended block size\n if initialBlockSize == nil && secondBlockSize != nil {\n if *secondBlockSize > block.SZX {\n log.Warn(\"Second block size must not greater thans block size received from server\")\n block.NUM += 1\n } else {\n block.NUM = 1 << uint(block.SZX - *secondBlockSize)\n block.SZX = *secondBlockSize\n }\n } else {\n block.NUM += 1\n }\n } else {\n if data, ok := env.responseBlocks[blockKey]; ok {\n env.responseBlocks[blockKey].Data = append(data.Data, pdu.Data...)\n block.NUM += 1\n } else {\n log.Warnf(\"The block version is not unknown. Re-request from the first block\")\n delete(env.responseBlocks, blockKey)\n block.NUM = 0\n }\n }\n block.M = 0\n return isMoreBlock, &eTag, block\n } else if block.M == libcoap.LAST_BLOCK {\n log.Debugf(\"Response block is comming (eTag=%+v, block=%+v, size2=%+v), this is the last block.\", eTag, block.ToString(), size2Value)\n isMoreBlock = false\n if data, ok := env.responseBlocks[blockKey]; ok {\n env.responseBlocks[blockKey].Data = append(data.Data, pdu.Data...)\n } else if block.NUM > 0 {\n log.Warnf(\"The block version is not unknown. Re-request from the first block\")\n delete(env.responseBlocks, blockKey)\n block.NUM = 0\n isMoreBlock = true\n }\n return isMoreBlock, &eTag, block\n }\n }\n return false, nil, nil\n}", "func (e Endpoints) BitcoincoreBlock(ctx context.Context, blockHash *chainhash.Hash) (b0 *btcjson.GetBlockVerboseResult, e1 error) {\n\trequest := BitcoincoreBlockRequest{BlockHash: blockHash}\n\tresponse, err := e.BitcoincoreBlockEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn response.(BitcoincoreBlockResponse).B0, response.(BitcoincoreBlockResponse).E1\n}", "func MockBlock(txs []*types.Tx) *types.Block {\n\treturn &types.Block{\n\t\tBlockHeader: types.BlockHeader{Timestamp: uint64(time.Now().Nanosecond())},\n\t\tTransactions: txs,\n\t}\n}", "func receiveBlock(ws *WrappedStream) (*Block, error) {\n\tvar block Block\n\terr := ws.dec.Decode(&block)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to read block from stream\")\n\t}\n\treturn &block, nil\n}", "func newBlock(lastBlock Block, seed int, npeer string, transactions []SignedTransaction) Block {\n\tvar newBlock Block\n\n\tnewBlock.Seed = seed\n\tnewBlock.Index = lastBlock.Index + 1\n\tnewBlock.LastHash = lastBlock.Hash\n\tnewBlock.Peer = npeer\n\tnewBlock.SpecialAccounts = lastBlock.SpecialAccounts\n\tnewBlock.Transactions = transactions\n\tnewBlock.Hash = blockHash(newBlock)\n\treturn newBlock\n}", "func generateRandomBlock() types.Block {\n\tblock := types.Block{\n\t\tTimestamp: types.Timestamp(rand.Uint64()),\n\t}\n\treturn block\n}", "func (ch *blockchain) GetRawBlock(h chainhash.Hash) (block []byte, err error) {\n\treturn block, ch.db.View(func(txn blockdb.DBViewTransaction) error {\n\t\tblock, err = txn.GetRawBlock(h)\n\t\treturn err\n\t})\n}", "func (d *Dataset) Block(i int) *Block {\n\tif len(d.blocks) == 0 {\n\t\t//load blocks so errors can be populated in dataset\n\t\td.loadBlocks()\n\t}\n\n\tif i <= len(d.blocks)-1 {\n\t\treturn d.blocks[i]\n\t}\n\n\treturn nil\n}", "func DeserializeBlock(d []byte) *Block {\n\n\tblock := &Block{}\n\n\terr := proto.Unmarshal(d, block)\n\tif err != nil {\n\t\tlog.Println(\"block-deserialize: protobuf decoding error: \", err)\n\t}\n\n\treturn block\n\n}", "func (_AnchorChain *AnchorChainCaller) ViewBlock(opts *bind.CallOpts, i *big.Int) (string, error) {\n\tvar (\n\t\tret0 = new(string)\n\t)\n\tout := ret0\n\terr := _AnchorChain.contract.Call(opts, out, \"viewBlock\", i)\n\treturn *ret0, err\n}", "func NewBlock(sigKey ed25519.PrivateKey, previousBlock BlockID, txs []*Transaction) (*Block, error) {\n\trand_bytes := make([]byte, 8)\n\t_, err := rand.Read(rand_bytes)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get Random data\")\n\t}\n\ttemp := binary.LittleEndian.Uint64(rand_bytes)\n\tb := &Block{\n\t\tHeader: &BlockHeader{\n\t\t\tVersion: 0,\n\t\t\tPreviousBlock: previousBlock,\n\t\t\tTimestamp: 0, // XXX: Populate this correctly.\n\t\t\tRandom: temp,\n\t\t},\n\t\tTransactions: &Transactions{Transactions: txs},\n\t}\n\n\tb.Header.MerkleRoot, err = b.MerkleRoot()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to compute merkle root\")\n\t}\n\n\tbid := b.BlockID()\n\tb.Header.Signature = ed25519.Sign(sigKey, bid[:])\n\n\treturn b, nil\n}", "func (r *RuntimeImpl) Block() {\n\t<-r.blocker\n}", "func (c *Client) LastBlock() (BlockHeight, error) {\n\ttimeout := time.Duration(10 * time.Second)\n\tclient := http.Client{\n\t\tTimeout: timeout,\n\t}\n\tc.URL.Path = \"/chain/last-block\"\n\treq, err := c.buildReq(nil, nil, http.MethodGet)\n\tif err != nil {\n\t\treturn BlockHeight{}, err\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn BlockHeight{}, err\n\t}\n\tdefer resp.Body.Close()\n\tbyteArray, err := ioutil.ReadAll(resp.Body)\n\n\tif resp.StatusCode != 200 {\n\t\terr := errors.New(string(byteArray))\n\t\treturn BlockHeight{}, err\n\t}\n\n\tvar data BlockHeight\n\tif err := json.Unmarshal(byteArray, &data); err != nil {\n\t\treturn BlockHeight{}, err\n\t}\n\treturn data, nil\n}", "func Block(c *blocker.Client, h http.Handler) http.Handler {\n\treturn BlockWithCode(c, h, http.StatusForbidden)\n}", "func DecodeBlock(wire []byte) (*Block, uint64, error) {\n\tb := new(Block)\n\n\t// Decode TLV type\n\ttlvType, tlvTypeLen, err := DecodeVarNum(wire)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tif tlvType > math.MaxUint32 {\n\t\treturn nil, 0, util.ErrOutOfRange\n\t}\n\tb.tlvType = uint32(tlvType)\n\n\t// Decode TLV length (we don't store this because it's implicit from value slice length)\n\tif tlvTypeLen == len(wire) {\n\t\treturn nil, 0, ErrMissingLength\n\t}\n\ttlvLength, tlvLengthLen, err := DecodeVarNum(wire[tlvTypeLen:])\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\t// Decode TLV value\n\tif uint64(len(wire)) < uint64(tlvTypeLen)+uint64(tlvLengthLen)+tlvLength {\n\t\treturn nil, 0, ErrBufferTooShort\n\t}\n\t// b.value = make([]byte, tlvLength)\n\tb.value = wire[tlvTypeLen+tlvLengthLen : uint64(tlvTypeLen)+uint64(tlvLengthLen)+tlvLength]\n\n\t// Add wire\n\t// b.wire = make([]byte, uint64(tlvTypeLen)+uint64(tlvLengthLen)+tlvLength)\n\tb.wire = wire[:uint64(tlvTypeLen)+uint64(tlvLengthLen)+tlvLength]\n\n\treturn b, uint64(tlvTypeLen) + uint64(tlvLengthLen) + tlvLength, nil\n}", "func NewBlock(transactions []*Transaction, prevBlockHash []byte, height int) *Block {\n\tblock := &Block{time.Now().Unix(), transactions, prevBlockHash, []byte{}, 0, height}\n\tblock.POW()\n\treturn block\n}", "func (c *Cache) GetBlock(k Key) Block {\n\tidx := uint64(0)\n\tif len(c.shards) > 1 {\n\t\th := k.hashUint64()\n\t\tidx = h % uint64(len(c.shards))\n\t}\n\tshard := c.shards[idx]\n\treturn shard.GetBlock(k)\n}", "func (_Rootchain *RootchainSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _Rootchain.Contract.Blocks(&_Rootchain.CallOpts, arg0)\n}", "func GetRandomBlock() *Block {\n\tvar newBlock *Block = new(Block)\n\tmyRand := randomGen()\n\tfor index, _ := range newBlock {\n\t\tnewBlock[index] = byte(myRand.Intn(256))\n\t}\n\treturn newBlock\n}", "func (bc *Blockchain) GetBlock(hash []byte) (*Block, error) {\n\t// TODO(student)\n\treturn nil, nil\n}", "func (h HTTPHandler) HandleBlockInfo(w http.ResponseWriter, r *http.Request) {\n\terr := processJWT(r, false, h.secret)\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"\"+err.Error()+\"\\\"}\", 401)\n\t\treturn\n\t}\n\n\tvars := mux.Vars(r)\n\tblockId, err := hex.DecodeString(vars[\"blockId\"])\n\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"invalid block ID\\\"}\", 400)\n\t\treturn\n\t}\n\n\tblockchainPeer, err := getBlockchainById(h.bf, vars[\"blockchainId\"])\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 400)\n\t\treturn\n\t}\n\n\tif blockchainPeer == nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"blockchain doesn't exist\\\"}\", 404)\n\t\treturn\n\t}\n\n\tvar block *blockchain.Block\n\n\terr = blockchainPeer.Db.View(func(dbtx *bolt.Tx) error {\n\t\tb := dbtx.Bucket([]byte(blockchain.BlocksBucket))\n\n\t\tif b == nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"route\": \"HandleBlockInfo\",\n\t\t\t\t\"address\": r.Header.Get(\"address\"),\n\t\t\t}).Warn(\"bucket doesn't exist\")\n\t\t\treturn errors.New(\"block doesn't exist\")\n\t\t}\n\n\t\tencodedBlock := b.Get(blockId)\n\n\t\tif encodedBlock == nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"route\": \"HandleBlockInfo\",\n\t\t\t\t\"address\": r.Header.Get(\"address\"),\n\t\t\t}).Error(\"block doesn't exist\")\n\t\t\treturn errors.New(\"block doesn't exist\")\n\t\t}\n\t\tblock = blockchain.DeserializeBlock(encodedBlock)\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"block doesn't exist\\\"}\", 404)\n\t\treturn\n\t}\n\n\tblockInfoResponse := BlockInfo{BlockchainId: vars[\"blockchainId\"], BlockId: fmt.Sprintf(\"%x\", block.Hash), PrevBlockId: fmt.Sprintf(\"%x\", block.PrevBlockHash), BlockHeight: block.Height, TotalTransactions: block.TotalTransactions}\n\n\tmustEncode(w, blockInfoResponse)\n}", "func (b *BlockRaw) ToBlock() (*Block, StdError) {\n\tvar (\n\t\tNumber uint64\n\t\tAvgTime int64\n\t\tTxcounts uint64\n\t\tTransactions []TransactionInfo\n\t\terr error\n\t)\n\tif Number, err = strconv.ParseUint(b.Number, 0, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tif strings.Index(b.AvgTime, \"0x\") == 0 || strings.Index(b.AvgTime, \"-0x\") == 0 {\n\t\tb.AvgTime = strings.Replace(b.AvgTime, \"0x\", \"\", 1)\n\t}\n\tif AvgTime, err = strconv.ParseInt(b.AvgTime, 16, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tif Txcounts, err = strconv.ParseUint(b.TxCounts, 0, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tfor _, t := range b.Transactions {\n\t\ttransactionInfo, err := t.ToTransaction()\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn nil, NewSystemError(err)\n\t\t}\n\t\tTransactions = append(Transactions, *transactionInfo)\n\t}\n\treturn &Block{\n\t\tVersion: b.Version,\n\t\tNumber: Number,\n\t\tHash: b.Hash,\n\t\tParentHash: b.ParentHash,\n\t\tWriteTime: b.WriteTime,\n\t\tAvgTime: AvgTime,\n\t\tTxCounts: Txcounts,\n\t\tMerkleRoot: b.MerkleRoot,\n\t\tTransactions: Transactions,\n\t}, nil\n}", "func (c *ChainIO) GetBlock(blockHash *chainhash.Hash) (*wire.MsgBlock, er.R) {\n\treturn nil, nil\n}", "func NewBlock() (*Block, error) {\n\tn, err := findLast()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th, err := ftoh(n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Hash: \" + h)\n\n\treturn &Block{Number: n + 1, PreviousHash: h}, nil\n}", "func NewBlock(typeName string, labels []string) *Block {\n\tblock := newBlock()\n\tblock.init(typeName, labels)\n\treturn block\n}", "func NewBlock(typeName string, labels []string) *Block {\n\tblock := newBlock()\n\tblock.init(typeName, labels)\n\treturn block\n}", "func (g *BlockGenerator) GenerateBlock() (*types.Block, error) {\n\tbState := g.bState\n\n\ttransactions, err := g.GatherTXs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn := len(transactions)\n\tif n == 0 && g.skipEmpty {\n\t\tlogger.Debug().Msg(\"BF: empty block is skipped\")\n\t\treturn nil, ErrBlockEmpty\n\t}\n\n\ttxs := make([]*types.Tx, n)\n\tfor i, x := range transactions {\n\t\ttxs[i] = x.GetTx()\n\t}\n\n\tblock := types.NewBlock(g.bi, bState.GetRoot(), bState.Receipts(), txs, chain.CoinbaseAccount, bState.Consensus())\n\tif n != 0 && logger.IsDebugEnabled() {\n\t\tlogger.Debug().\n\t\t\tStr(\"txroothash\", types.EncodeB64(block.GetHeader().GetTxsRootHash())).\n\t\t\tInt(\"hashed\", len(txs)).\n\t\t\tInt(\"no_receipts\", len(bState.Receipts().Get())).\n\t\t\tMsg(\"BF: tx root hash\")\n\t}\n\n\treturn block, nil\n}", "func Block(ctx context.Context, blockee *models.User) (*viewer.Viewer, error) {\n\t// function that takes a user and has the viewer block the other user\n\treturn viewer.ViewerResolver(ctx)\n}", "func NewBlock(data string, transactions []*Tx, prevBlockHash []byte) *Block {\n\tblock := &Block{\n\t\tIdentifier: internal.GenerateID(),\n\t\tData: []byte(data),\n\t\tTransactions: transactions,\n\t\tPrevBlockHash: prevBlockHash,\n\t\tTimestamp: time.Now().Unix(),\n\t}\n\n\tpow := NewPow(block)\n\tnonce, hash := pow.Run()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\treturn block\n}" ]
[ "0.8338847", "0.7633274", "0.7504522", "0.72231877", "0.7012322", "0.69668525", "0.6965455", "0.69054824", "0.68715656", "0.6862664", "0.6860121", "0.6781391", "0.6731799", "0.6723696", "0.6716859", "0.6710591", "0.66734666", "0.6613884", "0.6605735", "0.6550756", "0.6537798", "0.6537222", "0.65168476", "0.65162253", "0.6513863", "0.650928", "0.6506415", "0.6499141", "0.64560974", "0.6432476", "0.6410635", "0.6408707", "0.63966846", "0.6394532", "0.6393738", "0.63896894", "0.63892937", "0.63879603", "0.63839376", "0.63824654", "0.63806635", "0.6374161", "0.63723344", "0.63650167", "0.6364174", "0.63629293", "0.6346047", "0.63408524", "0.63371736", "0.6327078", "0.6326708", "0.6314175", "0.63138896", "0.6300234", "0.6298695", "0.629024", "0.628985", "0.6257627", "0.62527317", "0.6247439", "0.62448484", "0.6242481", "0.6203214", "0.61973906", "0.61945814", "0.61848104", "0.6182926", "0.6180829", "0.6177133", "0.6169676", "0.6156949", "0.6156476", "0.6150965", "0.61499107", "0.6144062", "0.6142408", "0.61400896", "0.6138005", "0.6132778", "0.61279887", "0.6127701", "0.61244243", "0.61218196", "0.6120289", "0.6118057", "0.61115474", "0.611035", "0.6109958", "0.610933", "0.61088544", "0.6103341", "0.6101763", "0.6099084", "0.60918176", "0.60876226", "0.6085336", "0.6085336", "0.60841507", "0.6080882", "0.60795724" ]
0.8022571
1
BlockTransaction returns additional transactions related to the specified block, not returned by the Block() call. This is currently unused in Decred given that all relevant transactions are returned by Block(). NOTE: this is part of the BlockAPIServicer interface.
func (s *Server) BlockTransaction(context.Context, *rtypes.BlockTransactionRequest, ) (*rtypes.BlockTransactionResponse, *rtypes.Error) { return nil, types.ErrUnimplemented.RError() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (rs *RosettaService) BlockTransaction(ctx context.Context, request *rtypes.BlockTransactionRequest) (*rtypes.BlockTransactionResponse, *rtypes.Error) {\n\t// all transactions are returned from /block\n\treturn nil, errNotImplemented\n}", "func (ec *Client) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) {\n\tec.Send(generalCost)\n\treturn ec.c.TransactionInBlock(ctx, blockHash, index)\n}", "func (ec *Client) TransactionInBlock(ctx context.Context, blockHash helper.Hash, index uint) (*types.Transaction, error) {\n\tvar tx *types.Transaction\n\terr := ec.c.CallContext(ctx, &tx, \"siot_getTransactionByBlockHashAndIndex\", blockHash, index)\n\tif err == nil {\n\t\tvar signer types.Signer = types.HomesteadSigner{}\n\t\tif tx.Protected() {\n\t\t\tsigner = types.NewSiotImpr1Signer(tx.ChainId())\n\t\t}\n\t\tif _, r, _ := types.SignatureValues(signer, tx); r == nil {\n\t\t\treturn nil, fmt.Errorf(\"server returned transaction without signature\")\n\t\t}\n\t}\n\treturn tx, err\n}", "func NewBlock(tx *Transaction) *Block {\n\t\n\treturn nil\n}", "func (s *Server) Block(ctx context.Context, req *rtypes.BlockRequest) (*rtypes.BlockResponse, *rtypes.Error) {\n\t_, _, b, err := s.getBlockByPartialId(ctx, req.BlockIdentifier)\n\tif err != nil {\n\t\treturn nil, types.DcrdError(err)\n\t}\n\tvar prev *wire.MsgBlock\n\n\t// Fetch the previous block when the current block disapproves of its\n\t// parent, since we'll need to reverse the transactions in the parent.\n\t// We include a special check for the genesis block because it has\n\t// VoteBits == 0.\n\tapprovesParent := b.Header.VoteBits&0x01 == 0x01\n\tif !approvesParent && b.Header.Height > 0 {\n\t\tprev, err = s.c.GetBlock(ctx, &b.Header.PrevBlock)\n\t\tif err != nil {\n\t\t\treturn nil, types.DcrdError(err, types.MapRpcErrCode(-5, types.ErrBlockNotFound))\n\t\t}\n\t}\n\n\tfetchInputs := s.makeInputsFetcher(ctx, nil)\n\trblock, err := types.WireBlockToRosetta(b, prev, fetchInputs, s.chainParams)\n\tif err != nil {\n\t\treturn nil, types.RError(err)\n\t}\n\treturn &rtypes.BlockResponse{\n\t\tBlock: rblock,\n\t}, nil\n}", "func (s *TransactionService) Block(block big.Int, limit int, cursor string) (models.TransactionPage, error) {\n\tif limit > 1000 {\n\t\tlimit = 1000\n\t}\n\treturn s.dao.Find(bson.M{\"number\": block.String()}, \"-_id\", limit, cursor)\n}", "func GetBlockBytes(block *model.Block) ([]byte, error) {\n\tvar rawBlock []byte\n\n\t// convert nounce to bytes\n\tnounceBytes := Int64ToBytes(block.Nounce)\n\trawBlock = append(rawBlock, nounceBytes...)\n\n\t// convert preHash to bytes\n\tpreHashBytes, err := HexToBytes(block.PrevHash)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trawBlock = append(rawBlock, preHashBytes...)\n\n\t// convert transactions to bytes\n\tfor i := 0; i < len(block.Txs); i++ {\n\t\ttx := block.Txs[i]\n\t\ttxBytes, err := GetTransactionBytes(tx, true /*withHash*/)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trawBlock = append(rawBlock, txBytes...)\n\t}\n\n\t// covert coinbase to bytes\n\tcoinbaseBytes, err := GetTransactionBytes(block.Coinbase, true /*withHash*/)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trawBlock = append(rawBlock, coinbaseBytes...)\n\n\treturn rawBlock, nil\n}", "func (bc *Blockchain) AddBlock(transactions []*Transaction) *Block {\n\t// TODO(student)\n\treturn nil\n}", "func (rt *recvTxOut) Block() *BlockDetails {\n\treturn rt.block\n}", "func (rs *RosettaService) Block(ctx context.Context, request *rtypes.BlockRequest) (*rtypes.BlockResponse, *rtypes.Error) {\n\tvar block *rtypes.Block\n\tvar err *rtypes.Error\n\tswitch {\n\tcase request.BlockIdentifier.Index != nil:\n\t\tb, ok := rs.cs.BlockAtHeight(stypes.BlockHeight(*request.BlockIdentifier.Index))\n\t\tif !ok {\n\t\t\treturn nil, errUnknownBlock\n\t\t}\n\t\tblock, err = rs.convertBlock(b)\n\t\t// sanity check\n\t\tif err == nil && block.BlockIdentifier.Index != *request.BlockIdentifier.Index {\n\t\t\tpanic(\"block height mismatch\")\n\t\t}\n\n\tcase request.BlockIdentifier.Hash != nil:\n\t\tvar bid stypes.BlockID\n\t\tif err := bid.LoadString(*request.BlockIdentifier.Hash); err != nil {\n\t\t\treturn nil, errInvalidBlockID(err)\n\t\t}\n\t\tb, _, ok := rs.cs.BlockByID(bid)\n\t\tif !ok {\n\t\t\treturn nil, errUnknownBlock\n\t\t}\n\t\tblock, err = rs.convertBlock(b)\n\t\t// sanity check\n\t\tif err == nil && block.BlockIdentifier.Hash != *request.BlockIdentifier.Hash {\n\t\t\tpanic(\"block hash mismatch\")\n\t\t}\n\n\tdefault:\n\t\tblock, err = rs.convertBlock(rs.cs.CurrentBlock())\n\t}\n\n\treturn &rtypes.BlockResponse{\n\t\tBlock: block,\n\t}, err\n}", "func (c *Client) Block() *Block {\n\treturn &Block{c}\n}", "func (c *Chain) GiveTxBackFromBlock() {\n\n}", "func Block(b models.Block) *genModels.BlocksRow {\n\tts := b.Timestamp.Unix()\n\n\tgenBlock := genModels.BlocksRow{\n\t\tLevel: b.Level.Ptr(),\n\t\tProto: b.Proto.Ptr(),\n\t\tBlockTime: b.BlockTime,\n\t\tPredecessor: b.Predecessor.Ptr(),\n\t\tTimestamp: &ts,\n\t\tValidationPass: b.ValidationPass.Ptr(),\n\t\tFitness: b.Fitness.Ptr(),\n\t\tContext: b.Context,\n\t\tSignature: b.Signature,\n\t\tProtocol: b.Protocol.Ptr(),\n\t\tPriority: b.Priority.Ptr(),\n\t\tChainID: b.ChainID,\n\t\tHash: b.Hash.Ptr(),\n\t\tReward: &b.Reward,\n\t\tDeposit: b.Deposit,\n\t\tOperationsHash: b.OperationsHash,\n\t\tPeriodKind: b.PeriodKind,\n\t\tCurrentExpectedQuorum: b.CurrentExpectedQuorum,\n\t\tActiveProposal: b.ActiveProposal,\n\t\tBaker: b.Baker,\n\t\tBakerName: b.BakerName,\n\t\tNonceHash: b.NonceHash,\n\t\tConsumedGas: b.ConsumedGas,\n\t\tMetaLevel: b.MetaLevel,\n\t\tMetaLevelPosition: b.MetaLevelPosition,\n\t\tMetaCycle: b.MetaCycle,\n\t\tMetaCyclePosition: b.MetaCyclePosition,\n\t\tMetaVotingPeriod: b.MetaVotingPeriod,\n\t\tMetaVotingPeriodPosition: b.MetaVotingPeriodPosition,\n\t\tExpectedCommitment: b.ExpectedCommitment,\n\t}\n\n\tif b.BlockAggregation != nil {\n\t\tgenBlock.Volume = b.BlockAggregation.Volume\n\t\tgenBlock.Fees = b.BlockAggregation.Fees\n\t\tgenBlock.Endorsements = b.BlockAggregation.Endorsements\n\t\tgenBlock.Proposals = b.BlockAggregation.Proposals\n\t\tgenBlock.SeedNonceRevelations = b.BlockAggregation.SeedNonceRevelations\n\t\tgenBlock.Delegations = b.BlockAggregation.Delegations\n\t\tgenBlock.Transactions = b.BlockAggregation.Transactions\n\t\tgenBlock.ActivateAccounts = b.BlockAggregation.ActivateAccounts\n\t\tgenBlock.Ballots = b.BlockAggregation.Ballots\n\t\tgenBlock.Originations = b.BlockAggregation.Originations\n\t\tgenBlock.Reveals = b.BlockAggregation.Reveals\n\t\tgenBlock.DoubleBakingEvidence = b.BlockAggregation.DoubleBakingEvidences\n\t\tgenBlock.DoubleEndorsementEvidence = b.BlockAggregation.DoubleEndorsementEvidences\n\t\tgenBlock.NumberOfOperations = b.BlockAggregation.NumberOfOperations\n\t}\n\n\treturn &genBlock\n}", "func NewBlock(transactionPool *mempool, previousBlock *Block) *Block {\n\n\tcurrentBlock := Block{}\n\tcurrentBlock.PreviousBlock = previousBlock\n\n\t// First, select which transactions the block will contain\n\tselectedTransactions := selectTransactions(transactionPool)\n\tcurrentBlock.Transactions = selectedTransactions\n\n\t// Second, calculate the hash of the selected transactions\n\thashedTransaction := string(processTransactions(selectedTransactions))\n\thashedBlockData := hashedTransaction + currentBlock.Hash\n\tcurrentBlock.Hash = hashedBlockData\n\treturn &currentBlock\n}", "func (g *BlockGenerator) GenerateBlock() (*types.Block, error) {\n\tbState := g.bState\n\n\ttransactions, err := g.GatherTXs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn := len(transactions)\n\tif n == 0 && g.skipEmpty {\n\t\tlogger.Debug().Msg(\"BF: empty block is skipped\")\n\t\treturn nil, ErrBlockEmpty\n\t}\n\n\ttxs := make([]*types.Tx, n)\n\tfor i, x := range transactions {\n\t\ttxs[i] = x.GetTx()\n\t}\n\n\tblock := types.NewBlock(g.bi, bState.GetRoot(), bState.Receipts(), txs, chain.CoinbaseAccount, bState.Consensus())\n\tif n != 0 && logger.IsDebugEnabled() {\n\t\tlogger.Debug().\n\t\t\tStr(\"txroothash\", types.EncodeB64(block.GetHeader().GetTxsRootHash())).\n\t\t\tInt(\"hashed\", len(txs)).\n\t\t\tInt(\"no_receipts\", len(bState.Receipts().Get())).\n\t\t\tMsg(\"BF: tx root hash\")\n\t}\n\n\treturn block, nil\n}", "func (_Gatekeeper *GatekeeperCallerSession) GetCurrentTransactionAmountForBlock() (*big.Int, error) {\n\treturn _Gatekeeper.Contract.GetCurrentTransactionAmountForBlock(&_Gatekeeper.CallOpts)\n}", "func (api *Api) Block(number *int) (*models.Block, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), api.timeout)\n\tdefer cancel()\n\n\tblock, err := api.EthProxyServiceClient.Block(ctx, parseBlockGetter(number))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fetch block grpc api request: %w\", err)\n\t}\n\n\treturn models.BlockFromProto(block), nil\n}", "func (_Gatekeeper *GatekeeperSession) GetCurrentTransactionAmountForBlock() (*big.Int, error) {\n\treturn _Gatekeeper.Contract.GetCurrentTransactionAmountForBlock(&_Gatekeeper.CallOpts)\n}", "func (tx *transaction) StoreBlock(blockKey *database.BlockKey, blockBytes []byte) error {\n\tif blockKey == nil ||\n\t\tblockBytes == nil || len(blockBytes) == 0 {\n\t\tstr := \"block key or bytes is invalid\"\n\t\treturn database.MakeError( database.ErrKeyRequired, str, nil )\n\t}\n\n\t// Ensure transaction state is valid.\n\tif err := tx.checkClosed(); err != nil {\n\t\treturn err\n\t}\n\n\t// Ensure the transaction is writable.\n\tif !tx.writable {\n\t\tstr := \"store block requires a writable database transaction\"\n\t\treturn database.MakeError(database.ErrTxNotWritable, str, nil)\n\t}\n\n\t// Reject the block if it already exists.\n\tif tx.hasBlock(blockKey) {\n\t\tstr := fmt.Sprintf(\"block %s already exists\", blockKey)\n\t\treturn database.MakeError(database.ErrBlockExists, str, nil)\n\t}\n\n\t/*blockBytes, err := block.Bytes()\n\tif err != nil {\n\t\tstr := fmt.Sprintf(\"failed to get serialized bytes for block %s\",\n\t\t\tblockHash)\n\t\treturn database.MakeError(database.ErrDriverSpecific, str, err)\n\t}*/\n\n\t// Add the block to be stored to the list of pending blocks to store\n\t// when the transaction is committed. Also, add it to pending blocks\n\t// map so it is easy to determine the block is pending based on the\n\t// block key.\n\tif tx.pendingBlocks == nil {\n\t\ttx.pendingBlocks = make(map[database.BlockKey]int)\n\t}\n\ttx.pendingBlocks[*blockKey] = len(tx.pendingBlockData)\n\ttx.pendingBlockData = append(tx.pendingBlockData, pendingBlock{\n\t\tkey: blockKey,\n\t\tbytes: blockBytes,\n\t})\n\tlog.Tracef(\"Added block %s to pending blocks\", blockKey)\n\n\treturn nil\n}", "func (_Gatekeeper *GatekeeperSession) SetTransactionAmountForBlock(_amount *big.Int) (*types.Transaction, error) {\n\treturn _Gatekeeper.Contract.SetTransactionAmountForBlock(&_Gatekeeper.TransactOpts, _amount)\n}", "func (block *Block) SerializeBlock() []byte {\n\tvar result bytes.Buffer\n\n\tencoder := gob.NewEncoder(&result)\n\terr := encoder.Encode(block)\n\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn result.Bytes()\n}", "func (_Gatekeeper *GatekeeperTransactorSession) SetTransactionAmountForBlock(_amount *big.Int) (*types.Transaction, error) {\n\treturn _Gatekeeper.Contract.SetTransactionAmountForBlock(&_Gatekeeper.TransactOpts, _amount)\n}", "func MockBlock(txs []*types.Tx) *types.Block {\n\treturn &types.Block{\n\t\tBlockHeader: types.BlockHeader{Timestamp: uint64(time.Now().Nanosecond())},\n\t\tTransactions: txs,\n\t}\n}", "func (bc *BlockChain) AddBlock(transactions []*Transaction) {\n\tvar lHash []byte\n\n\t// need get last block's hash\n\terr := bc.db.View(func(tx *bolt.Tx) error {\n\t\t_bkt := tx.Bucket([]byte(blocksBucketName))\n\t\tlHash = _bkt.Get([]byte(lastBlockKey))\n\t\treturn nil\n\t})\n\n\t_newBlock := NewBlock(transactions, lHash)\n\n\terr = bc.db.Update(func(tx *bolt.Tx) error {\n\t\t_bkt := tx.Bucket([]byte(blocksBucketName))\n\n\t\tif err := _bkt.Put(_newBlock.Hash, _newBlock.serialize()); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err = _bkt.Put([]byte(lastBlockKey), _newBlock.Hash); err != nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tbc.tip = _newBlock.Hash\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (n *Node) AddBlock(block *structures.Block) (uint, error) {\n\tbcm, err := n.GetBCManager()\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tcurLastHash, _, err := bcm.GetState()\n\n\t// we need to know how the block was added to managed transactions caches correctly\n\taddstate, err := n.NodeBC.AddBlock(block)\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif addstate == blockchain.BCBAddState_addedToParallel ||\n\t\taddstate == blockchain.BCBAddState_addedToTop ||\n\t\taddstate == blockchain.BCBAddState_addedToParallelTop {\n\n\t\tn.GetTransactionsManager().BlockAdded(block, addstate == blockchain.BCBAddState_addedToTop)\n\t}\n\n\tif addstate == blockchain.BCBAddState_addedToParallelTop {\n\t\t// get 2 blocks branches that replaced each other\n\t\tnewChain, oldChain, err := n.NodeBC.GetBranchesReplacement(curLastHash, []byte{})\n\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tif newChain != nil && oldChain != nil {\n\t\t\tfor _, block := range oldChain {\n\n\t\t\t\terr := n.GetTransactionsManager().BlockRemovedFromPrimaryChain(block)\n\n\t\t\t\tif err != nil {\n\n\t\t\t\t\treturn 0, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, block := range newChain {\n\n\t\t\t\terr := n.GetTransactionsManager().BlockAddedToPrimaryChain(block)\n\n\t\t\t\tif err != nil {\n\n\t\t\t\t\treturn 0, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn addstate, nil\n}", "func (b *Block) TransactionLog() *BlkTransactionLog {\n\tif len(b.Receipts) == 0 {\n\t\treturn nil\n\t}\n\n\tblkLog := BlkTransactionLog{\n\t\tactionLogs: []*TransactionLog{},\n\t}\n\tfor _, r := range b.Receipts {\n\t\tif log := ReceiptTransactionLog(r); log != nil {\n\t\t\tblkLog.actionLogs = append(blkLog.actionLogs, log)\n\t\t}\n\t}\n\n\tif len(blkLog.actionLogs) == 0 {\n\t\treturn nil\n\t}\n\treturn &blkLog\n}", "func (a *API) traceBlock(height rpctypes.BlockNumber, config *evmtypes.TraceConfig, block *tmrpctypes.ResultBlock) ([]*evmtypes.TxTraceResult, error) {\n\ttxs := block.Block.Txs\n\ttxsLength := len(txs)\n\n\tif txsLength == 0 {\n\t\t// If there are no transactions return empty array\n\t\treturn []*evmtypes.TxTraceResult{}, nil\n\t}\n\n\ttxDecoder := a.clientCtx.TxConfig.TxDecoder()\n\n\tvar txsMessages []*evmtypes.MsgEthereumTx\n\tfor i, tx := range txs {\n\t\tdecodedTx, err := txDecoder(tx)\n\t\tif err != nil {\n\t\t\ta.logger.Error(\"failed to decode transaction\", \"hash\", txs[i].Hash(), \"error\", err.Error())\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, msg := range decodedTx.GetMsgs() {\n\t\t\tethMessage, ok := msg.(*evmtypes.MsgEthereumTx)\n\t\t\tif !ok {\n\t\t\t\t// Just considers Ethereum transactions\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxsMessages = append(txsMessages, ethMessage)\n\t\t}\n\t}\n\n\t// minus one to get the context at the beginning of the block\n\tcontextHeight := height - 1\n\tif contextHeight < 1 {\n\t\t// 0 is a special value for `ContextWithHeight`.\n\t\tcontextHeight = 1\n\t}\n\tctxWithHeight := rpctypes.ContextWithHeight(int64(contextHeight))\n\n\ttraceBlockRequest := &evmtypes.QueryTraceBlockRequest{\n\t\tTxs: txsMessages,\n\t\tTraceConfig: config,\n\t\tBlockNumber: block.Block.Height,\n\t\tBlockTime: block.Block.Time,\n\t\tBlockHash: common.Bytes2Hex(block.BlockID.Hash),\n\t}\n\n\tres, err := a.queryClient.TraceBlock(ctxWithHeight, traceBlockRequest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdecodedResults := make([]*evmtypes.TxTraceResult, txsLength)\n\tif err := json.Unmarshal(res.Data, &decodedResults); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn decodedResults, nil\n}", "func (chain *Blockchain) AddBlock(transactions []*Transaction) (err error) {\n\tblock := NewBlock(transactions, chain.Tail)\n\tbytes, err := json.Marshal(block)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = chain.Database.Update(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket([]byte(BucketName))\n\t\terr := bucket.Put(block.Hash, bytes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = bucket.Put([]byte(LastBlockKey), block.Hash)\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\n\t}\n\tchain.Tail = block.Hash\n\treturn\n}", "func (block *Block) SerializeBlock() []byte {\n\tvar result bytes.Buffer\n\n\tencoder := gob.NewEncoder(&result)\n\n\t_ = encoder.Encode(block)\n\n\treturn result.Bytes()\n}", "func DeepCopyBlock(b *SignedBlock) (*SignedBlock, error) {\n\tres := &SignedBlock{\n\t\tSignedBlockHeader: eos.SignedBlockHeader{\n\t\t\tBlockHeader: eos.BlockHeader{\n\t\t\t\tTimestamp: BlockTimestamp{Time: b.Timestamp.UTC()},\n\t\t\t\tProducer: b.Producer,\n\t\t\t\tConfirmed: b.Confirmed,\n\t\t\t\tPrevious: CopyChecksum256(b.Previous),\n\t\t\t\tTransactionMRoot: CopyChecksum256(b.TransactionMRoot),\n\t\t\t\tActionMRoot: CopyChecksum256(b.ActionMRoot),\n\t\t\t\tScheduleVersion: b.ScheduleVersion,\n\t\t\t\tHeaderExtensions: make([]*eos.Extension, 0, len(b.HeaderExtensions)),\n\t\t\t},\n\t\t\tProducerSignature: CopySignature(b.ProducerSignature),\n\t\t},\n\t\tTransactions: make([]eos.TransactionReceipt, 0, len(b.Transactions)),\n\t\tBlockExtensions: make([]*eos.Extension, 0, len(b.BlockExtensions)),\n\t}\n\n\tif b.NewProducersV1 != nil {\n\t\tres.NewProducersV1 = &eos.ProducerSchedule{\n\t\t\tVersion: b.NewProducersV1.Version,\n\t\t\tProducers: make([]eos.ProducerKey, 0, len(b.NewProducersV1.Producers)),\n\t\t}\n\n\t\tfor _, prod := range b.NewProducersV1.Producers {\n\t\t\tres.NewProducersV1.Producers = append(res.NewProducersV1.Producers, eos.ProducerKey{\n\t\t\t\tAccountName: prod.AccountName,\n\t\t\t\tBlockSigningKey: prod.BlockSigningKey,\n\t\t\t})\n\t\t}\n\t}\n\n\tfor _, ext := range b.HeaderExtensions {\n\t\tres.HeaderExtensions = append(res.HeaderExtensions, CopyExt(ext))\n\t}\n\n\tfor _, ext := range b.BlockExtensions {\n\t\tres.BlockExtensions = append(res.BlockExtensions, CopyExt(ext))\n\t}\n\n\tfor _, trx := range b.Transactions {\n\t\ttrxCopy := eos.TransactionReceipt{\n\t\t\tTransactionReceiptHeader: trx.TransactionReceiptHeader,\n\t\t\tTransaction: eos.TransactionWithID{\n\t\t\t\tID: CopyChecksum256(trx.Transaction.ID),\n\t\t\t\tPacked: &eos.PackedTransaction{\n\t\t\t\t\tSignatures: make([]ecc.Signature, 0, len(trx.Transaction.Packed.Signatures)),\n\t\t\t\t\tCompression: trx.Transaction.Packed.Compression,\n\t\t\t\t\tPackedContextFreeData: CopyBytes(trx.Transaction.Packed.PackedContextFreeData),\n\t\t\t\t\tPackedTransaction: CopyBytes(trx.Transaction.Packed.PackedTransaction),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tfor _, s := range trx.Transaction.Packed.Signatures {\n\t\t\ttrxCopy.Transaction.Packed.Signatures = append(trxCopy.Transaction.Packed.Signatures, CopySignature(s))\n\t\t}\n\t\tres.Transactions = append(res.Transactions, trxCopy)\n\t}\n\n\treturn res, nil\n}", "func (query *Query) GetBlock(ctx context.Context, height int64) (*model.Block, error) {\n\tresp, err := query.transport.QueryBlock(ctx, height)\n\tif err != nil {\n\t\treturn nil, errors.QueryFailf(\"GetBlock err\").AddCause(err)\n\t}\n\n\tblock := new(model.Block)\n\tblock.Header = resp.Block.Header\n\tblock.Evidence = resp.Block.Evidence\n\tblock.LastCommit = resp.Block.LastCommit\n\tblock.Data = new(model.Data)\n\tblock.Data.Txs = []model.Transaction{}\n\tfor _, txBytes := range resp.Block.Data.Txs {\n\t\tvar tx model.Transaction\n\t\tif err := query.transport.Cdc.UnmarshalJSON(txBytes, &tx); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tblock.Data.Txs = append(block.Data.Txs, tx)\n\t}\n\treturn block, nil\n}", "func getBlock(res rpc.GetBlockResponse) (GetBlockResponse, error) {\n\ttxs := make([]GetBlockTransaction, 0, len(res.Result.Transactions))\n\tfor _, rTx := range res.Result.Transactions {\n\t\tdata, ok := rTx.Transaction.([]interface{})\n\t\tif !ok {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to cast raw response to []interface{}\")\n\t\t}\n\t\tif data[1] != string(rpc.GetTransactionConfigEncodingBase64) {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"encoding mistmatch\")\n\t\t}\n\t\trawTx, err := base64.StdEncoding.DecodeString(data[0].(string))\n\t\tif err != nil {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to base64 decode data, err: %v\", err)\n\t\t}\n\t\ttx, err := types.TransactionDeserialize(rawTx)\n\t\tif err != nil {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to deserialize transaction, err: %v\", err)\n\t\t}\n\n\t\tvar transactionMeta *TransactionMeta\n\t\tif rTx.Meta != nil {\n\t\t\tinnerInstructions := make([]TransactionMetaInnerInstruction, 0, len(rTx.Meta.InnerInstructions))\n\t\t\tfor _, metaInnerInstruction := range rTx.Meta.InnerInstructions {\n\t\t\t\tcompiledInstructions := make([]types.CompiledInstruction, 0, len(metaInnerInstruction.Instructions))\n\t\t\t\tfor _, innerInstruction := range metaInnerInstruction.Instructions {\n\t\t\t\t\tdata, err := base58.Decode(innerInstruction.Data)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to base58 decode data, data: %v, err: %v\", innerInstruction.Data, err)\n\t\t\t\t\t}\n\t\t\t\t\tcompiledInstructions = append(compiledInstructions, types.CompiledInstruction{\n\t\t\t\t\t\tProgramIDIndex: innerInstruction.ProgramIDIndex,\n\t\t\t\t\t\tAccounts: innerInstruction.Accounts,\n\t\t\t\t\t\tData: data,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tinnerInstructions = append(innerInstructions, TransactionMetaInnerInstruction{\n\t\t\t\t\tIndex: metaInnerInstruction.Index,\n\t\t\t\t\tInstructions: compiledInstructions,\n\t\t\t\t})\n\t\t\t}\n\t\t\ttransactionMeta = &TransactionMeta{\n\t\t\t\tErr: rTx.Meta.Err,\n\t\t\t\tFee: rTx.Meta.Fee,\n\t\t\t\tPreBalances: rTx.Meta.PreBalances,\n\t\t\t\tPostBalances: rTx.Meta.PostBalances,\n\t\t\t\tPreTokenBalances: rTx.Meta.PreTokenBalances,\n\t\t\t\tPostTokenBalances: rTx.Meta.PostTokenBalances,\n\t\t\t\tLogMessages: rTx.Meta.LogMessages,\n\t\t\t\tInnerInstructions: innerInstructions,\n\t\t\t}\n\t\t}\n\n\t\ttxs = append(txs,\n\t\t\tGetBlockTransaction{\n\t\t\t\tMeta: transactionMeta,\n\t\t\t\tTransaction: tx,\n\t\t\t},\n\t\t)\n\t}\n\treturn GetBlockResponse{\n\t\tBlockhash: res.Result.Blockhash,\n\t\tBlockTime: res.Result.BlockTime,\n\t\tBlockHeight: res.Result.BlockHeight,\n\t\tPreviousBlockhash: res.Result.PreviousBlockhash,\n\t\tParentSLot: res.Result.ParentSLot,\n\t\tRewards: res.Result.Rewards,\n\t\tTransactions: txs,\n\t}, nil\n}", "func (w *FilteredBlockWrapper) Block() *pb.FilteredBlock {\r\n\treturn w.block\r\n}", "func (b *BlockChain) AddBlock(tx *Transaction) {\n\t// construct new block and prev hash will be current tip of db\n\tblock := NewBlock([]*Transaction{tx}, b.tip)\n\n\terr := b.db.Update(func(tx *bolt.Tx) error {\n\t\tbckt := tx.Bucket([]byte(blocksBucket))\n\t\tif err := bckt.Put(block.Hash, block.Serialize()); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := bckt.Put([]byte(\"l\"), block.Hash); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tb.tip = block.Hash\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(\"AddBlock :\", err)\n\t}\n}", "func MineBlock(bc *blockchain.Blockchain, transactions []*transaction.Transaction) *blockchain.Block {\n\tvar lastHash []byte\n\tvar lastHeight int\n\n\tfor _, tx := range transactions {\n\t\t// TODO: ignore transaction if it's not valid\n\t\tif bc.VerifyTransactionSig(tx) != true {\n\t\t\tlog.Panic(\"ERROR: Invalid transaction\")\n\t\t}\n\t}\n\n\tlastBlock := bc.LastBlockInfo()\n\tlastHash = lastBlock.Hash\n\tlastHeight = lastBlock.Height\n\n\tnewBlock := blockchain.NewBlock(transactions, lastHash, lastHeight+1, blockchain.GetBlockchain().GetCurrentDifficult())\n\n\tpow := NewProofOfWork(newBlock)\n\tnonce, hash := pow.Run()\n\n\tnewBlock.Hash = hash[:]\n\tnewBlock.Nonce = nonce\n\n\tbc.AddBlock(newBlock)\n\n\treturn newBlock\n}", "func (b *Block) SerializeBlock() []byte {\n\tvar result bytes.Buffer\n\tencoder := gob.NewEncoder(&result)\n\n\tencoder.Encode(b)\n\n\treturn result.Bytes()\n}", "func (t *Transaction) Transaction() <-chan *interfaces.TxWithBlock {\n\treturn t.sendTxFound\n}", "func (_Gatekeeper *GatekeeperTransactor) SetTransactionAmountForBlock(opts *bind.TransactOpts, _amount *big.Int) (*types.Transaction, error) {\n\treturn _Gatekeeper.contract.Transact(opts, \"SetTransactionAmountForBlock\", _amount)\n}", "func (c *Context) CreateBlock() block.Block {\n\tif c.block == nil {\n\t\tif c.block = c.MakeHeader(); c.block == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\ttxx := make([]block.Transaction, len(c.TransactionHashes))\n\n\t\tfor i, h := range c.TransactionHashes {\n\t\t\ttxx[i] = c.Transactions[h]\n\t\t}\n\n\t\tc.block.SetTransactions(txx)\n\t}\n\n\treturn c.block\n}", "func (b *Block) AddTransaction(t *Transaction) {\n\tb.Transactions = append(b.Transactions, *t)\n}", "func (ctx *DefaultContext) BlockContext() *evm.Context {\n\treturn ctx.evmCtx\n}", "func (b *Builder) Block() *Builder {\n\treturn new(Builder)\n}", "func (l *Ledger) ConfirmBlock(block *pb.InternalBlock, isRoot bool) ConfirmStatus {\n\tl.mutex.Lock()\n\tdefer l.mutex.Unlock()\n\tblkTimer := timer.NewXTimer()\n\tl.xlog.Info(\"start to confirm block\", \"blockid\", utils.F(block.Blockid), \"txCount\", len(block.Transactions))\n\tvar confirmStatus ConfirmStatus\n\tdummyTransactions := []*pb.Transaction{}\n\trealTransactions := block.Transactions // 真正的交易转存到局部变量\n\tblock.Transactions = dummyTransactions // block表不保存transaction详情\n\n\tbatchWrite := l.ConfirmBatch\n\tbatchWrite.Reset()\n\tnewMeta := proto.Clone(l.meta).(*pb.LedgerMeta)\n\tsplitHeight := newMeta.TrunkHeight\n\tif isRoot { //确认创世块\n\t\tif block.PreHash != nil && len(block.PreHash) > 0 {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tl.xlog.Warn(\"genesis block shoud has no prehash\")\n\t\t\treturn confirmStatus\n\t\t}\n\t\tif len(l.meta.RootBlockid) > 0 {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tconfirmStatus.Error = ErrRootBlockAlreadyExist\n\t\t\tl.xlog.Warn(\"already hash genesis block\")\n\t\t\treturn confirmStatus\n\t\t}\n\t\tnewMeta.RootBlockid = block.Blockid\n\t\tnewMeta.TrunkHeight = 0 //代表主干上块的最大高度\n\t\tnewMeta.TipBlockid = block.Blockid\n\t\tblock.InTrunk = true\n\t\tblock.Height = 0 // 创世纪块是第0块\n\t} else { //非创世块,需要判断是在主干还是分支\n\t\tpreHash := block.PreHash\n\t\tpreBlock, findErr := l.fetchBlock(preHash)\n\t\tif findErr != nil {\n\t\t\tl.xlog.Warn(\"find pre block fail\", \"findErr\", findErr)\n\t\t\tconfirmStatus.Succ = false\n\t\t\treturn confirmStatus\n\t\t}\n\t\tblock.Height = preBlock.Height + 1 //不管是主干还是分支,height都是++\n\t\tif bytes.Equal(preBlock.Blockid, newMeta.TipBlockid) {\n\t\t\t//在主干上添加\n\t\t\tblock.InTrunk = true\n\t\t\tpreBlock.NextHash = block.Blockid\n\t\t\tnewMeta.TipBlockid = block.Blockid\n\t\t\tnewMeta.TrunkHeight++\n\t\t\t//因为改了pre_block的next_hash值,所以也要写回存储\n\t\t\tif !DisableTxDedup {\n\t\t\t\tsaveErr := l.saveBlock(preBlock, batchWrite)\n\t\t\t\tl.blockCache.Del(string(preBlock.Blockid))\n\t\t\t\tif saveErr != nil {\n\t\t\t\t\tl.xlog.Warn(\"save block fail\", \"saveErr\", saveErr)\n\t\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\t\treturn confirmStatus\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t//在分支上\n\t\t\tif preBlock.Height+1 > newMeta.TrunkHeight {\n\t\t\t\t//分支要变成主干了\n\t\t\t\toldTip := append([]byte{}, newMeta.TipBlockid...)\n\t\t\t\tnewMeta.TrunkHeight = preBlock.Height + 1\n\t\t\t\tnewMeta.TipBlockid = block.Blockid\n\t\t\t\tblock.InTrunk = true\n\t\t\t\tsplitBlock, splitErr := l.handleFork(oldTip, preBlock.Blockid, block.Blockid, batchWrite) //处理分叉\n\t\t\t\tif splitErr != nil {\n\t\t\t\t\tl.xlog.Warn(\"handle split failed\", \"splitErr\", splitErr)\n\t\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\t\treturn confirmStatus\n\t\t\t\t}\n\t\t\t\tsplitHeight = splitBlock.Height\n\t\t\t\tconfirmStatus.Split = true\n\t\t\t\tconfirmStatus.TrunkSwitch = true\n\t\t\t\tl.xlog.Info(\"handle split successfully\", \"splitBlock\", utils.F(splitBlock.Blockid))\n\t\t\t} else {\n\t\t\t\t// 添加在分支上, 对preblock没有影响\n\t\t\t\tblock.InTrunk = false\n\t\t\t\tconfirmStatus.Split = true\n\t\t\t\tconfirmStatus.TrunkSwitch = false\n\t\t\t\tconfirmStatus.Orphan = true\n\t\t\t}\n\t\t}\n\t}\n\tsaveErr := l.saveBlock(block, batchWrite)\n\tblkTimer.Mark(\"saveHeader\")\n\tif saveErr != nil {\n\t\tconfirmStatus.Succ = false\n\t\tl.xlog.Warn(\"save current block fail\", \"saveErr\", saveErr)\n\t\treturn confirmStatus\n\t}\n\t// update branch head\n\tupdateBranchErr := l.updateBranchInfo(block.Blockid, block.PreHash, block.Height, batchWrite)\n\tif updateBranchErr != nil {\n\t\tconfirmStatus.Succ = false\n\t\tl.xlog.Warn(\"update branch info fail\", \"updateBranchErr\", updateBranchErr)\n\t\treturn confirmStatus\n\t}\n\ttxExist, txData := l.parallelCheckTx(realTransactions, block)\n\tcbNum := 0\n\toldBlockCache := map[string]*pb.InternalBlock{}\n\tfor _, tx := range realTransactions {\n\t\t//在这儿解析交易存表,调用新版的接口TxOutputs不会超过4\n\t\t//理论上这儿坐过校验判断后,不会报错,目前还是写好报错码,以便调试\n\t\tif len(tx.TxInputs) >0 &&len(tx.TxOutputs) < 4 && len(tx.ContractRequests) > 0 {\n\t\t\treq := tx.ContractRequests[0]\n\t\t\ttmpReq := &InvokeRequest{\n\t\t\t\tModuleName: req.ModuleName,\n\t\t\t\tContractName: req.ContractName,\n\t\t\t\tMethodName: req.MethodName,\n\t\t\t\tArgs: map[string]string{},\n\t\t\t}\n\t\t\tfor argKey, argV := range req.Args {\n\t\t\t\ttmpReq.Args[argKey] = string(argV)\n\t\t\t}\n\t\t\tif tmpReq.ModuleName == \"xkernel\" && tmpReq.ContractName == \"$govern_token\"{\n\t\t\t\t//这里有buy和sell\n\t\t\t\tswitch tmpReq.MethodName {\n\t\t\t\tcase \"Buy\":\n\t\t\t\t\tl.WriteFreezeTable(batchWrite,tmpReq.Args[\"amount\"],string(tx.TxInputs[0].FromAddr),tx.Txid)\n\t\t\t\tcase \"Sell\":\n\t\t\t\t\tl.WriteThawTable(batchWrite,string(tx.TxInputs[0].FromAddr),tx.Desc)\n\t\t\t\tdefault:\n\t\t\t\t\tl.xlog.Warn(\"D__解析交易存表时方法异常,异常方法名:\",\"tmpReq.MethodName\",tmpReq.MethodName)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif tmpReq.ModuleName == \"xkernel\" && (tmpReq.ContractName == \"$tdpos\" || tmpReq.ContractName ==\"$xpos\" ) {\n\t\t\t\tswitch tmpReq.MethodName {\n\t\t\t\tcase \"nominateCandidate\":\n\t\t\t\t\tl.WriteCandidateTable(batchWrite,string(tx.TxInputs[0].FromAddr),tmpReq.Args)\n\t\t\t\tcase \"revokeNominate\":\n\t\t\t\t\tl.WriteReCandidateTable(batchWrite,string(tx.TxInputs[0].FromAddr),tmpReq.Args)\n\t\t\t\tcase \"voteCandidate\":\n\t\t\t\t\tl.VoteCandidateTable(batchWrite,string(tx.TxInputs[0].FromAddr),tmpReq.Args)\n\t\t\t\tcase \"revokeVote\":\n\t\t\t\t\tl.RevokeVote(batchWrite,string(tx.TxInputs[0].FromAddr),tmpReq.Args)\n\t\t\t\tdefault:\n\t\t\t\t\tl.xlog.Warn(\"D__解析tdpos交易存表时方法异常,异常方法名:\",\"tmpReq.MethodName\",tmpReq.MethodName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t\tif tx.Coinbase {\n\t\t\tcbNum = cbNum + 1\n\t\t}\n\t\tif cbNum > 1 {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tl.xlog.Warn(\"The num of Coinbase tx should not exceed one when confirm block\",\n\t\t\t\t\"BlockID\", utils.F(tx.Blockid), \"Miner\", string(block.Proposer))\n\t\t\treturn confirmStatus\n\t\t}\n\n\t\tpbTxBuf := txData[string(tx.Txid)]\n\t\tif pbTxBuf == nil {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tl.xlog.Warn(\"marshal trasaction failed when confirm block\")\n\t\t\treturn confirmStatus\n\t\t}\n\t\thasTx := txExist[string(tx.Txid)]\n\t\tif !hasTx {\n\t\t\tbatchWrite.Put(append([]byte(pb.ConfirmedTablePrefix), tx.Txid...), pbTxBuf)\n\t\t} else {\n\t\t\t//confirm表已经存在这个交易了,需要检查一下是否存在多个主干block包含同样trasnaction的情况\n\t\t\toldPbTxBuf, _ := l.ConfirmedTable.Get(tx.Txid)\n\t\t\toldTx := &pb.Transaction{}\n\t\t\tparserErr := proto.Unmarshal(oldPbTxBuf, oldTx)\n\t\t\tif parserErr != nil {\n\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\tconfirmStatus.Error = parserErr\n\t\t\t\treturn confirmStatus\n\t\t\t}\n\t\t\toldBlock := &pb.InternalBlock{}\n\t\t\tif cachedBlk, cacheHit := oldBlockCache[string(oldTx.Blockid)]; cacheHit {\n\t\t\t\toldBlock = cachedBlk\n\t\t\t} else {\n\t\t\t\toldPbBlockBuf, blockErr := l.blocksTable.Get(oldTx.Blockid)\n\t\t\t\tif blockErr != nil {\n\t\t\t\t\tif def.NormalizedKVError(blockErr) == def.ErrKVNotFound {\n\t\t\t\t\t\tl.xlog.Warn(\"old block that contains the tx has been truncated\", \"txid\", utils.F(tx.Txid), \"blockid\", utils.F(oldTx.Blockid))\n\t\t\t\t\t\tbatchWrite.Put(append([]byte(pb.ConfirmedTablePrefix), tx.Txid...), pbTxBuf) //overwrite with newtx\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\t\tconfirmStatus.Error = blockErr\n\t\t\t\t\treturn confirmStatus\n\t\t\t\t}\n\t\t\t\tparserErr = proto.Unmarshal(oldPbBlockBuf, oldBlock)\n\t\t\t\tif parserErr != nil {\n\t\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\t\tconfirmStatus.Error = parserErr\n\t\t\t\t\treturn confirmStatus\n\t\t\t\t}\n\t\t\t\toldBlockCache[string(oldBlock.Blockid)] = oldBlock\n\t\t\t}\n\t\t\tif oldBlock.InTrunk && block.InTrunk && oldBlock.Height <= splitHeight {\n\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\tconfirmStatus.Error = ErrTxDuplicated\n\t\t\t\tl.xlog.Warn(\"transaction duplicated in previous trunk block\",\n\t\t\t\t\t\"txid\", utils.F(tx.Txid),\n\t\t\t\t\t\"blockid\", utils.F(oldBlock.Blockid))\n\t\t\t\treturn confirmStatus\n\t\t\t} else if block.InTrunk {\n\t\t\t\tl.xlog.Info(\"change blockid of tx\", \"txid\", utils.F(tx.Txid), \"blockid\", utils.F(block.Blockid))\n\t\t\t\tbatchWrite.Put(append([]byte(pb.ConfirmedTablePrefix), tx.Txid...), pbTxBuf)\n\t\t\t}\n\t\t}\n\t}\n\tblkTimer.Mark(\"saveAllTxs\")\n\t//删除pendingBlock中对应的数据\n\tbatchWrite.Delete(append([]byte(pb.PendingBlocksTablePrefix), block.Blockid...))\n\t//改meta\n\tmetaBuf, pbErr := proto.Marshal(newMeta)\n\tif pbErr != nil {\n\t\tl.xlog.Warn(\"marshal meta fail\", \"pbErr\", pbErr)\n\t\tconfirmStatus.Succ = false\n\t\treturn confirmStatus\n\t}\n\tbatchWrite.Put([]byte(pb.MetaTablePrefix), metaBuf)\n\tl.xlog.Debug(\"print block size when confirm block\", \"blockSize\", batchWrite.ValueSize(), \"blockid\", utils.F(block.Blockid))\n\tkvErr := batchWrite.Write() // blocks, confirmed_transaction两张表原子写入\n\tblkTimer.Mark(\"saveToDisk\")\n\tif kvErr != nil {\n\t\tconfirmStatus.Succ = false\n\t\tconfirmStatus.Error = kvErr\n\t\tl.xlog.Warn(\"batch write failed when confirm block\", \"kvErr\", kvErr)\n\t} else {\n\t\tconfirmStatus.Succ = true\n\t\tl.meta = newMeta\n\t}\n\tblock.Transactions = realTransactions\n\tif isRoot {\n\t\t//首次confirm 创始块的时候\n\t\tlErr := l.loadGenesisBlock(false, nil)\n\t\tif lErr != nil {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tconfirmStatus.Error = lErr\n\t\t}\n\t}\n\tl.blockCache.Add(string(block.Blockid), block)\n\tl.xlog.Debug(\"confirm block cost\", \"blkTimer\", blkTimer.Print())\n\treturn confirmStatus\n}", "func NewBlock() *Block {\n\treturn &Block{}\n}", "func (b *BlockRaw) ToBlock() (*Block, StdError) {\n\tvar (\n\t\tNumber uint64\n\t\tAvgTime int64\n\t\tTxcounts uint64\n\t\tTransactions []TransactionInfo\n\t\terr error\n\t)\n\tif Number, err = strconv.ParseUint(b.Number, 0, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tif strings.Index(b.AvgTime, \"0x\") == 0 || strings.Index(b.AvgTime, \"-0x\") == 0 {\n\t\tb.AvgTime = strings.Replace(b.AvgTime, \"0x\", \"\", 1)\n\t}\n\tif AvgTime, err = strconv.ParseInt(b.AvgTime, 16, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tif Txcounts, err = strconv.ParseUint(b.TxCounts, 0, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tfor _, t := range b.Transactions {\n\t\ttransactionInfo, err := t.ToTransaction()\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn nil, NewSystemError(err)\n\t\t}\n\t\tTransactions = append(Transactions, *transactionInfo)\n\t}\n\treturn &Block{\n\t\tVersion: b.Version,\n\t\tNumber: Number,\n\t\tHash: b.Hash,\n\t\tParentHash: b.ParentHash,\n\t\tWriteTime: b.WriteTime,\n\t\tAvgTime: AvgTime,\n\t\tTxCounts: Txcounts,\n\t\tMerkleRoot: b.MerkleRoot,\n\t\tTransactions: Transactions,\n\t}, nil\n}", "func NewBlock(header *Header, txs []*Transaction, receipts []*Receipt, signs []*PbftSign) *Block {\n\tb := &Block{header: CopyHeader(header)}\n\n\t// TODO: panic if len(txs) != len(receipts)\n\tif len(txs) == 0 {\n\t\tb.header.TxHash = EmptyRootHash\n\t} else {\n\t\tb.header.TxHash = DeriveSha(Transactions(txs))\n\t\tb.transactions = make(Transactions, len(txs))\n\t\tcopy(b.transactions, txs)\n\t}\n\n\tif len(receipts) == 0 {\n\t\tb.header.ReceiptHash = EmptyRootHash\n\t} else {\n\t\tb.header.ReceiptHash = DeriveSha(Receipts(receipts))\n\t\tb.header.Bloom = CreateBloom(receipts)\n\t}\n\n\tif len(receipts) == 0 {\n\t\tb.header.ReceiptHash = EmptyRootHash\n\t} else {\n\t\tb.header.ReceiptHash = DeriveSha(Receipts(receipts))\n\t\tb.header.Bloom = CreateBloom(receipts)\n\t}\n\n\tif len(signs) != 0 {\n\t\tb.signs = make(PbftSigns, len(signs))\n\t\tcopy(b.signs, signs)\n\t}\n\n\treturn b\n}", "func NewBlock(transactions []*Transaction, preBlockHash []byte) *Block {\n\tb := &Block{time.Now().Unix(), transactions, preBlockHash, []byte{}, 252, 0}\n\n\tpow := NewProofOfWork(b)\n\tnonce, hash := pow.Run()\n\n\tb.Nonce = nonce\n\tb.Hash = hash[:]\n\n\treturn b\n}", "func (chain *BlockChain) AddBlock(txs []*Transaction) {\n\tvar lastHash []byte\n\n\t// get previous hash via database\n\terr := chain.Database.View(func(txn *badger.Txn) error {\n\t\titem, err := txn.Get([]byte(\"lasthash\"))\n\t\tHandle(err)\n\n\t\t// set lasthash as the value returned from db\n\t\tlastHash, err = item.Value()\n\n\t\treturn err\n\t})\n\n\t// create block with data and lasthash\n\tnewBlock := CreateBlock(txs, lastHash)\n\n\t// save new block to database\n\terr = chain.Database.Update(func(txn *badger.Txn) error {\n\t\t// save serialize block with hash as a key --> to disk\n\t\terr := txn.Set(newBlock.Hash, newBlock.Serialize())\n\t\tHandle(err)\n\n\t\t// save hash to database with lasthash key --> to disk\n\t\terr = txn.Set([]byte(\"lasthash\"), newBlock.Hash)\n\n\t\t// set chain lasthash in memory with hash\n\t\tchain.LastHash = newBlock.Hash\n\n\t\treturn err\n\t})\n\n\tHandle(err)\n\n\t// // get previous block\n\t// prevBlock := chain.Blocks[len(chain.Blocks)-1]\n\n\t// // get previous hash from previous chain\n\t// newBlock := CreateBlock(data, prevBlock.Hash)\n\n\t// chain.Blocks = append(chain.Blocks, newBlock)\n}", "func (c *Chain) AcceptBlock(blk block.Block) error {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tfield := logger.Fields{\"process\": \"accept block\"}\n\tl := log.WithFields(field)\n\n\tl.Trace(\"verifying block\")\n\n\t// 1. Check that stateless and stateful checks pass\n\tif err := verifiers.CheckBlock(c.db, c.prevBlock, blk); err != nil {\n\t\tl.WithError(err).Warnln(\"block verification failed\")\n\t\treturn err\n\t}\n\n\t// 2. Check the certificate\n\t// This check should avoid a possible race condition between accepting two blocks\n\t// at the same height, as the probability of the committee creating two valid certificates\n\t// for the same round is negligible.\n\tl.Trace(\"verifying block certificate\")\n\tif err := verifiers.CheckBlockCertificate(*c.p, blk); err != nil {\n\t\tl.WithError(err).Warnln(\"certificate verification failed\")\n\t\treturn err\n\t}\n\n\t// 3. Add provisioners and block generators\n\tl.Trace(\"adding consensus nodes\")\n\t// We set the stake start height as blk.Header.Height+2.\n\t// This is because, once this block is accepted, the consensus will\n\t// be 2 rounds ahead of this current block height. As a result,\n\t// if we pick the start height to just be the block height, we\n\t// run into some inconsistencies when accepting the next block,\n\t// as the certificate could've been made with a different committee.\n\tc.addConsensusNodes(blk.Txs, blk.Header.Height+2)\n\n\t// 4. Store block in database\n\tl.Trace(\"storing block in db\")\n\terr := c.db.Update(func(t database.Transaction) error {\n\t\treturn t.StoreBlock(&blk)\n\t})\n\n\tif err != nil {\n\t\tl.WithError(err).Errorln(\"block storing failed\")\n\t\treturn err\n\t}\n\n\tc.prevBlock = blk\n\n\t// 5. Gossip advertise block Hash\n\tl.Trace(\"gossiping block\")\n\tif err := c.advertiseBlock(blk); err != nil {\n\t\tl.WithError(err).Errorln(\"block advertising failed\")\n\t\treturn err\n\t}\n\n\t// 6. Remove expired provisioners and bids\n\tl.Trace(\"removing expired consensus transactions\")\n\tc.removeExpiredProvisioners(blk.Header.Height)\n\tc.removeExpiredBids(blk.Header.Height + 2)\n\n\t// 7. Notify other subsystems for the accepted block\n\t// Subsystems listening for this topic:\n\t// mempool.Mempool\n\t// consensus.generation.broker\n\tl.Trace(\"notifying internally\")\n\n\tmsg := message.New(topics.AcceptedBlock, blk)\n\tc.eventBus.Publish(topics.AcceptedBlock, msg)\n\n\tl.Trace(\"procedure ended\")\n\treturn nil\n}", "func (b *BlockChain) MineBlock(txns []*Transaction) {\n\t// construct new block and prev hash will be current tip of db\n\tblock := NewBlock(txns, b.tip)\n\n\terr := b.db.Update(func(tx *bolt.Tx) error {\n\t\tbckt := tx.Bucket([]byte(blocksBucket))\n\t\tif err := bckt.Put(block.Hash, block.Serialize()); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := bckt.Put([]byte(\"l\"), block.Hash); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tb.tip = block.Hash\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(\"AddBlock :\", err)\n\t}\n}", "func (_Gatekeeper *GatekeeperCaller) GetCurrentTransactionAmountForBlock(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Gatekeeper.contract.Call(opts, out, \"GetCurrentTransactionAmountForBlock\")\n\treturn *ret0, err\n}", "func AddBlock(block *types.Block, db *types.DB) {\n\ttxCheck := func(txs []*types.Tx) bool {\n\t\t// start = copy.deepcopy(txs)\n\t\tvar start = txs\n\t\tvar txsSource []*types.Tx\n\t\tvar startCopy []*types.Tx\n\n\t\tfor !reflect.DeepEqual(start, startCopy) {\n\t\t\t// Block passes this test\n\t\t\tif start == nil {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// startCopy = copy.deepcopy(start)\n\t\t\tstartCopy = start\n\t\t\tlast := start[len(start)-1]\n\n\t\t\t// transactions.tx_check[start[-1]['type']](start[-1], out, DB)\n\t\t\tfn := transactionVerify[last.Type]\n\t\t\tif fn(last, txsSource, db) {\n\t\t\t\t// start.pop()\n\t\t\t\tstart = start[:len(start)-1]\n\t\t\t\ttxsSource = append(txsSource, last)\n\t\t\t} else {\n\t\t\t\t// Block is invalid\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\t// Block is invalid\n\t\treturn true\n\t}\n\n\t// if \"error\" in block: return False\n\tif block.Error != nil {\n\t\treturn\n\t}\n\n\t// if \"length\" not in block: return False\n\t// NOTE: block.Length not being set means it takes its \"zero value\".\n\t// This shouldn't be a problem, check out next if stmt.\n\tif block.Length == 0 {\n\t\treturn\n\t}\n\n\tlength := db.Length\n\tif block.Length != length+1 {\n\t\treturn\n\t}\n\n\tif block.DiffLength != HexSum(db.DiffLength, HexInv(block.Target)) {\n\t\treturn\n\t}\n\n\tif length >= 0 && tools.DetHash(db.GetBlock(length)) != block.PrevHash {\n\t\treturn\n\t}\n\n\t// a = copy.deepcopy(block)\n\t// a.pop(\"nonce\")\n\tblockCopy := block\n\tblockCopy.Nonce = nil\n\n\t//if \"target\" not in block.keys(): return False\n\tif block.Target == \"\" {\n\t\treturn\n\t}\n\n\thalfWay := &types.HalfWay{\n\t\tNonce: block.Nonce,\n\t\tHalfHash: tools.DetHash(blockCopy),\n\t}\n\n\tif tools.DetHash(halfWay) > block.Target {\n\t\treturn\n\t}\n\n\tif block.Target != Target(db, block.Length) {\n\t\treturn\n\t}\n\n\t// TODO: Figure out why 8 (length)?\n\tearliestMedian := median(RecentBlockTimes(db, config.Get().Mmm, 8))\n\t// `float64` (unix epoch) back to `time.Time`\n\tsec, nsec := math.Modf(earliestMedian)\n\tearliest := time.Unix(int64(sec), int64(nsec*1e9))\n\n\t// if block.Time > time.time(): return false\n\t// if block.Time < earliest: return false\n\tif block.Time.After(time.Now()) || block.Time.Before(earliest) {\n\t\treturn\n\t}\n\n\tif txCheck(block.Txs) {\n\t\treturn\n\t}\n\n\t// block_check was unnecessary because it was only called once\n\t// and it only returned true at its end\n\n\t// if block_check(block, db):\n\tlog.Println(\"add_block:\", block)\n\tdb.Put(strconv.Itoa(block.Length), block)\n\n\tdb.Length = block.Length\n\tdb.DiffLength = block.DiffLength\n\n\torphans := db.Txs\n\tdb.Txs = nil\n\n\tfor _, tx := range block.Txs {\n\t\tdb.AddBlock = true\n\t\tfn := transactionUpdate[tx.Type]\n\t\tfn(tx, db)\n\t}\n\n\tfor _, tx := range orphans {\n\t\tAddTx(tx, db)\n\t}\n}", "func (b Blockstream) GetTransaction(txHash string) (*wire.MsgTx, error) {\n\turl := fmt.Sprintf(\"%s/tx/%s\", baseURL, txHash)\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tb, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to get a transaction: %s\", b)\n\t}\n\n\tvar tx transaction\n\tif err := json.NewDecoder(resp.Body).Decode(&tx); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmsgTx := wire.NewMsgTx(tx.Version)\n\tmsgTx.LockTime = uint32(tx.Locktime)\n\n\tfor _, vin := range tx.Vin {\n\t\tvoutHash, err := chainhash.NewHashFromStr(vin.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tsigScript, err := hex.DecodeString(vin.Scriptsig)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar witness [][]byte\n\t\tfor _, w := range vin.Witness {\n\t\t\tws, err := hex.DecodeString(w)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\twitness = append(witness, ws)\n\t\t}\n\n\t\tnewInput := wire.NewTxIn(\n\t\t\twire.NewOutPoint(voutHash, vin.Vout),\n\t\t\tsigScript,\n\t\t\twitness,\n\t\t)\n\t\tnewInput.Sequence = uint32(vin.Sequence)\n\n\t\tmsgTx.AddTxIn(newInput)\n\t}\n\n\tfor _, vout := range tx.Vout {\n\t\tpkScript, err := hex.DecodeString(vout.Scriptpubkey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmsgTx.AddTxOut(\n\t\t\twire.NewTxOut(\n\t\t\t\tvout.Value,\n\t\t\t\tpkScript,\n\t\t\t),\n\t\t)\n\t}\n\n\tif msgTx.TxHash().String() != tx.Txid {\n\t\treturn nil, fmt.Errorf(\"transaction hash doesn't match\")\n\t}\n\n\treturn msgTx, nil\n}", "func (this *Blockchain) addBlock(block Block) {\n mutex.Lock()\n this.chain = append(this.chain, block)\n mutex.Unlock()\n // reset pending Transactions\n this.pendingTransactions = nil\n}", "func NewBlock(transactions []*Transaction, prevBlockHash []byte, height int) *Block {\n\tblock := &Block{time.Now().Unix(), transactions, prevBlockHash, []byte{}, 0, height}\n\tblock.POW()\n\treturn block\n}", "func (core *coreService) TransactionLogByBlockHeight(blockHeight uint64) (*iotextypes.BlockIdentifier, *iotextypes.TransactionLogs, error) {\n\tif !core.dao.ContainsTransactionLog() {\n\t\treturn nil, nil, status.Error(codes.Unimplemented, filedao.ErrNotSupported.Error())\n\t}\n\n\ttip, err := core.dao.Height()\n\tif err != nil {\n\t\treturn nil, nil, status.Error(codes.Internal, err.Error())\n\t}\n\tif blockHeight < 1 || blockHeight > tip {\n\t\treturn nil, nil, status.Errorf(codes.InvalidArgument, \"invalid block height = %d\", blockHeight)\n\t}\n\n\th, err := core.dao.GetBlockHash(blockHeight)\n\tif err != nil {\n\t\tif errors.Cause(err) == db.ErrNotExist {\n\t\t\treturn nil, nil, status.Error(codes.NotFound, err.Error())\n\t\t}\n\t\treturn nil, nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tblockIdentifier := &iotextypes.BlockIdentifier{\n\t\tHash: hex.EncodeToString(h[:]),\n\t\tHeight: blockHeight,\n\t}\n\tsysLog, err := core.dao.TransactionLogs(blockHeight)\n\tif err != nil {\n\t\tif errors.Cause(err) == db.ErrNotExist {\n\t\t\t// should return empty, no transaction happened in block\n\t\t\treturn blockIdentifier, nil, nil\n\t\t}\n\t\treturn nil, nil, status.Error(codes.Internal, err.Error())\n\t}\n\treturn blockIdentifier, sysLog, nil\n}", "func (c *Client) AccountBlock(ctx context.Context, id ID) (*Relationship, error) {\n\tvar relationship Relationship\n\terr := c.doAPI(ctx, http.MethodPost, fmt.Sprintf(\"/api/v1/accounts/%s/block\", url.PathEscape(string(id))), nil, &relationship, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &relationship, nil\n}", "func NewBlock(t *testing.T, bc blockchainer.Blockchainer, offset uint32, primary uint32, txs ...*transaction.Transaction) *block.Block {\n\twitness := transaction.Witness{VerificationScript: MultisigVerificationScript()}\n\theight := bc.BlockHeight()\n\th := bc.GetHeaderHash(int(height))\n\thdr, err := bc.GetHeader(h)\n\trequire.NoError(t, err)\n\tb := &block.Block{\n\t\tHeader: block.Header{\n\t\t\tPrevHash: hdr.Hash(),\n\t\t\tTimestamp: (uint64(time.Now().UTC().Unix()) + uint64(hdr.Index)) * 1000,\n\t\t\tIndex: hdr.Index + offset,\n\t\t\tPrimaryIndex: byte(primary),\n\t\t\tNextConsensus: witness.ScriptHash(),\n\t\t\tScript: witness,\n\t\t},\n\t\tTransactions: txs,\n\t}\n\tb.RebuildMerkleRoot()\n\n\tb.Script.InvocationScript = Sign(b)\n\treturn b\n}", "func (bp RPCBlockProvider) GetBlock(index int) SignedBlockData {\r\n\tvar block SignedBlockData\r\n\terr := bp.Client.Call(\"BlockPropagationHandler.GetBlock\", index, &block)\r\n\tif err != nil {\r\n\t\tlog.Print(err)\r\n\t}\r\n\treturn block\r\n}", "func (bd *BlockDAG) AddBlock(b IBlockData) *list.List {\n\tbd.stateLock.Lock()\n\tdefer bd.stateLock.Unlock()\n\n\tif b == nil {\n\t\treturn nil\n\t}\n\tif bd.hasBlock(b.GetHash()) {\n\t\treturn nil\n\t}\n\tvar parents []*hash.Hash\n\tif bd.blockTotal > 0 {\n\t\tparents = b.GetParents()\n\t\tif len(parents) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\tif !bd.hasBlocks(parents) {\n\t\t\treturn nil\n\t\t}\n\t\tif !bd.isDAG(b.GetParents()) {\n\t\t\treturn nil\n\t\t}\n\t}\n\t//\n\tblock := Block{id: bd.blockTotal, hash: *b.GetHash(), layer: 0, status: StatusNone}\n\tif parents != nil {\n\t\tblock.parents = NewHashSet()\n\t\tvar maxLayer uint = 0\n\t\tfor k, h := range parents {\n\t\t\tparent := bd.getBlock(h)\n\t\t\tblock.parents.AddPair(h, parent)\n\t\t\tparent.AddChild(&block)\n\t\t\tif k == 0 {\n\t\t\t\tblock.mainParent = parent.GetHash()\n\t\t\t}\n\n\t\t\tif maxLayer == 0 || maxLayer < parent.GetLayer() {\n\t\t\t\tmaxLayer = parent.GetLayer()\n\t\t\t}\n\t\t}\n\t\tblock.SetLayer(maxLayer + 1)\n\t}\n\n\tif bd.blocks == nil {\n\t\tbd.blocks = map[hash.Hash]IBlock{}\n\t}\n\tib := bd.instance.CreateBlock(&block)\n\tbd.blocks[block.hash] = ib\n\tif bd.blockTotal == 0 {\n\t\tbd.genesis = *block.GetHash()\n\t}\n\t//\n\tif bd.blockids == nil {\n\t\tbd.blockids = map[uint]*hash.Hash{}\n\t}\n\tbd.blockids[block.GetID()] = block.GetHash()\n\t//\n\tbd.blockTotal++\n\t//\n\tbd.updateTips(&block)\n\t//\n\tt := time.Unix(b.GetTimestamp(), 0)\n\tif bd.lastTime.Before(t) {\n\t\tbd.lastTime = t\n\t}\n\t//\n\treturn bd.instance.AddBlock(ib)\n}", "func (policy *ticketPolicy) OnAddBlockTx(block *types.BlockDetail, tx *types.Transaction, index int32, dbbatch db.Batch) *types.WalletTxDetail {\n\treceipt := block.Receipts[index]\n\tamount, _ := tx.Amount()\n\twtxdetail := &types.WalletTxDetail{\n\t\tTx: tx,\n\t\tHeight: block.Block.Height,\n\t\tIndex: int64(index),\n\t\tReceipt: receipt,\n\t\tBlocktime: block.Block.BlockTime,\n\t\tActionName: tx.ActionName(),\n\t\tAmount: amount,\n\t\tPayload: nil,\n\t}\n\tif len(wtxdetail.Fromaddr) <= 0 {\n\t\tpubkey := tx.Signature.GetPubkey()\n\t\t//from addr\n\t\tfromaddress := address.PubKeyToAddr(address.DefaultID, pubkey)\n\t\tif len(fromaddress) != 0 && policy.walletOperate.AddrInWallet(fromaddress) {\n\t\t\twtxdetail.Fromaddr = fromaddress\n\t\t}\n\t}\n\tif len(wtxdetail.Fromaddr) <= 0 {\n\t\ttoaddr := tx.GetTo()\n\t\tif len(toaddr) != 0 && policy.walletOperate.AddrInWallet(toaddr) {\n\t\t\twtxdetail.Fromaddr = toaddr\n\t\t}\n\t}\n\n\tif policy.checkNeedFlushTicket(tx, receipt) {\n\t\tpolicy.needFlush = true\n\t}\n\treturn wtxdetail\n}", "func (app *application) Block(additional uint) error {\n\tendpoint := fmt.Sprintf(\"%s%d\", \"/blocks/\", additional)\n\turl := fmt.Sprintf(baseFormat, app.url, endpoint)\n\n\tresp, err := app.client.R().\n\t\tSetHeader(shared.TokenHeadKeyname, app.token).\n\t\tPost(url)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp.StatusCode() == http.StatusOK {\n\t\treturn nil\n\t}\n\n\treturn errors.New(string(resp.Body()))\n}", "func (o *Transaction) BlockHash(exec boil.Executor, mods ...qm.QueryMod) blockQuery {\n\tqueryMods := []qm.QueryMod{\n\t\tqm.Where(\"hash=?\", o.BlockHashID),\n\t}\n\n\tqueryMods = append(queryMods, mods...)\n\n\tquery := Blocks(exec, queryMods...)\n\tqueries.SetFrom(query.Query, \"`block`\")\n\n\treturn query\n}", "func (bb blockBase) GetBlock() uint16 {\n\treturn bb.block\n}", "func newBlock(lastBlock Block, seed int, npeer string, transactions []SignedTransaction) Block {\n\tvar newBlock Block\n\n\tnewBlock.Seed = seed\n\tnewBlock.Index = lastBlock.Index + 1\n\tnewBlock.LastHash = lastBlock.Hash\n\tnewBlock.Peer = npeer\n\tnewBlock.SpecialAccounts = lastBlock.SpecialAccounts\n\tnewBlock.Transactions = transactions\n\tnewBlock.Hash = blockHash(newBlock)\n\treturn newBlock\n}", "func (n *NodeBlockMaker) VerifyBlock(block *structures.Block) error {\n\t//6. Verify hash\n\n\tpow := NewProofOfWork(block)\n\n\tvalid, err := pow.Validate()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !valid {\n\t\treturn errors.New(\"Block hash is not valid\")\n\t}\n\tn.Logger.Trace.Println(\"block hash verified\")\n\t// 2. check number of TX\n\ttxnum := len(block.Transactions) - 1 /*minus coinbase TX*/\n\n\tmin, max, err := n.getTransactionNumbersLimits(block)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif txnum < min {\n\t\treturn errors.New(\"Number of transactions is too low\")\n\t}\n\n\tif txnum > max {\n\t\treturn errors.New(\"Number of transactions is too high\")\n\t}\n\n\t// 1\n\tcoinbaseused := false\n\n\tprevTXs := []*structures.Transaction{}\n\n\tfor _, tx := range block.Transactions {\n\t\tif tx.IsCoinbase() {\n\t\t\tif coinbaseused {\n\t\t\t\treturn errors.New(\"2 coin base TX in the block\")\n\t\t\t}\n\t\t\tcoinbaseused = true\n\t\t}\n\t\tvtx, err := n.getTransactionsManager().VerifyTransaction(tx, prevTXs, block.PrevBlockHash)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !vtx {\n\t\t\treturn errors.New(fmt.Sprintf(\"Transaction in a block is not valid: %x\", tx.ID))\n\t\t}\n\n\t\tprevTXs = append(prevTXs, tx)\n\t}\n\t// 1.\n\tif !coinbaseused {\n\t\treturn errors.New(\"No coinbase TX in the block\")\n\t}\n\treturn nil\n}", "func (s Store) StoreBlock (block types.FullSignedBlock) error {\r\n\r\n\t// Open badger\r\n\tstor, err := badger.Open(badger.DefaultOptions(s.StorFileLocation))\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tdefer stor.Close()\r\n\r\n\t// Serialize all the parts: block in json\r\n\tbytes, err := json.Marshal(block)\r\n\r\n\terr = stor.Update(func(txn *badger.Txn) error {\r\n\r\n\t\tvar txErr error\r\n\t\t// Store the hash as a key. This is the main register\r\n\t\tif txErr = storeStringIndex(txn, block.Hash, bytes, HashKeyPrefix); txErr == nil {\r\n\t\t\t// And now store the indexes. Using this indexes it is possible to retrieve the hash, and next the block\r\n\t\t\tif txErr = storeUIntIndex(txn, block.Timestamp, []byte(block.Hash), TimestampKeyPrefix); txErr != nil { // By timestamp\r\n\t\t\t\treturn txErr\r\n\t\t\t}\r\n\r\n\t\t\tif txErr = storeUIntIndex(txn, block.Height, []byte(block.Hash), HeightKeyPrefix); txErr != nil { // By block Height\r\n\t\t\t\treturn txErr\r\n\t\t\t}\r\n\t\t} \r\n\r\n\t\t return txErr\r\n\t})\r\n\r\n\treturn err\r\n}", "func (c *Client) Transaction() <-chan *interfaces.TxWithBlock {\n\treturn c.transactions\n}", "func (s *State) AddBlock(b Block) error {\n\tfor _, tx := range b.TXs {\n\t\tif err := s.AddTx(tx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (v *BlockTransaction) Reset() {\n\tv.BlockIdentifier.Reset()\n\tv.Transaction.Reset()\n}", "func NewBlock(blk *types.Block, repo repository.Repository) *Block {\n\treturn &Block{\n\t\trepo: repo,\n\t\tBlock: *blk,\n\t}\n}", "func (policy *ticketPolicy) OnDeleteBlockTx(block *types.BlockDetail, tx *types.Transaction, index int32, dbbatch db.Batch) *types.WalletTxDetail {\n\treceipt := block.Receipts[index]\n\tamount, _ := tx.Amount()\n\twtxdetail := &types.WalletTxDetail{\n\t\tTx: tx,\n\t\tHeight: block.Block.Height,\n\t\tIndex: int64(index),\n\t\tReceipt: receipt,\n\t\tBlocktime: block.Block.BlockTime,\n\t\tActionName: tx.ActionName(),\n\t\tAmount: amount,\n\t\tPayload: nil,\n\t}\n\tif len(wtxdetail.Fromaddr) <= 0 {\n\t\t//from addr\n\t\tfromaddress := tx.From()\n\t\tif len(fromaddress) != 0 && policy.walletOperate.AddrInWallet(fromaddress) {\n\t\t\twtxdetail.Fromaddr = fromaddress\n\t\t}\n\t}\n\tif len(wtxdetail.Fromaddr) <= 0 {\n\t\ttoaddr := tx.GetTo()\n\t\tif len(toaddr) != 0 && policy.walletOperate.AddrInWallet(toaddr) {\n\t\t\twtxdetail.Fromaddr = toaddr\n\t\t}\n\t}\n\n\tif policy.checkNeedFlushTicket(tx, receipt) {\n\t\tpolicy.needFlush = true\n\t}\n\treturn wtxdetail\n}", "func (self *ShardBlock) AddTransaction(tx metadata.Transaction) error {\n\tif self.Body.Transactions == nil {\n\t\treturn NewBlockChainError(UnExpectedError, errors.New(\"Not init tx arrays\"))\n\t}\n\tself.Body.Transactions = append(self.Body.Transactions, tx)\n\treturn nil\n}", "func NewBlock(sigKey ed25519.PrivateKey, previousBlock BlockID, txs []*Transaction) (*Block, error) {\n\trand_bytes := make([]byte, 8)\n\t_, err := rand.Read(rand_bytes)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get Random data\")\n\t}\n\ttemp := binary.LittleEndian.Uint64(rand_bytes)\n\tb := &Block{\n\t\tHeader: &BlockHeader{\n\t\t\tVersion: 0,\n\t\t\tPreviousBlock: previousBlock,\n\t\t\tTimestamp: 0, // XXX: Populate this correctly.\n\t\t\tRandom: temp,\n\t\t},\n\t\tTransactions: &Transactions{Transactions: txs},\n\t}\n\n\tb.Header.MerkleRoot, err = b.MerkleRoot()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to compute merkle root\")\n\t}\n\n\tbid := b.BlockID()\n\tb.Header.Signature = ed25519.Sign(sigKey, bid[:])\n\n\treturn b, nil\n}", "func (b Block) GetTransaction(txHash cipher.SHA256) (Transaction, bool) {\n\ttxns := b.Body.Transactions\n\tfor i := range txns {\n\t\tif txns[i].Hash() == txHash {\n\t\t\treturn txns[i], true\n\t\t}\n\t}\n\treturn Transaction{}, false\n}", "func (c *SyscallService) QueryBlock(ctx context.Context, in *pb.QueryBlockRequest) (*pb.QueryBlockResponse, error) {\n\tnctx, ok := c.ctxmgr.Context(in.GetHeader().Ctxid)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"bad ctx id:%d\", in.Header.Ctxid)\n\t}\n\n\trawBlockid, err := hex.DecodeString(in.Blockid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblock, err := nctx.Cache.QueryBlock(rawBlockid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttxids := []string{}\n\tfor _, t := range block.Transactions {\n\t\ttxids = append(txids, hex.EncodeToString(t.Txid))\n\t}\n\n\tblocksdk := &pb.Block{\n\t\tBlockid: hex.EncodeToString(block.Blockid),\n\t\tPreHash: block.PreHash,\n\t\tProposer: block.Proposer,\n\t\tSign: block.Sign,\n\t\tPubkey: block.Pubkey,\n\t\tHeight: block.Height,\n\t\tTxids: txids,\n\t\tTxCount: block.TxCount,\n\t\tInTrunk: block.InTrunk,\n\t\tNextHash: block.NextHash,\n\t}\n\n\treturn &pb.QueryBlockResponse{\n\t\tBlock: blocksdk,\n\t}, nil\n}", "func (bc *Blockchain) chainNewBlock(nonce int, previousHash [32]byte) *Block {\n\tb := NewBlock(nonce, previousHash, bc.transactionPool)\n\tbc.chain = append(bc.chain, b)\n\tbc.transactionPool = []*Transaction{}\n\treturn b\n}", "func blockDetails(block *btcutil.Block, txIndex int) *btcjson.BlockDetails {\n\tif block == nil {\n\t\treturn nil\n\t}\n\treturn &btcjson.BlockDetails{\n\t\tHeight: block.Height(),\n\t\tHash: block.Hash().String(),\n\t\tIndex: txIndex,\n\t\tTime: block.MsgBlock().Header.Timestamp.Unix(),\n\t}\n}", "func (in *Block) DeepCopy() *Block {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Block)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func GetTransaction(_db *gorm.DB, blkHash common.Hash, txHash common.Hash) *Transactions {\n\tvar tx Transactions\n\n\tif err := _db.Where(\"hash = ? and blockhash = ?\", txHash.Hex(), blkHash.Hex()).First(&tx).Error; err != nil {\n\t\treturn nil\n\t}\n\n\treturn &tx\n}", "func (b *Bitcoin) ConfirmationBlock() uint64 {\n\treturn b.confirmationBlock\n}", "func (_Rootchain *RootchainSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _Rootchain.Contract.Blocks(&_Rootchain.CallOpts, arg0)\n}", "func (_L1Block *L1BlockRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {\n\treturn _L1Block.Contract.L1BlockTransactor.contract.Transact(opts, method, params...)\n}", "func mockBlock(height uint32, txs ...*types.Transaction) *types.Block {\n\treturn &types.Block{\n\t\tHeader: types.Header{\n\t\t\tHeight: height,\n\t\t},\n\t\tTransactions: txs,\n\t}\n}", "func (b *Block) Transactions(input *BlockInput) (*Transactions, error) {\n\tresp, err := b.c.Request(http.MethodGet, fmt.Sprintf(\"/blocks/%s/transactions\", input.ID), new(bytes.Buffer), nil)\n\tif err != nil {\n\t\treturn &Transactions{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar transactions *Transactions\n\terr = json.NewDecoder(resp.Body).Decode(&transactions)\n\tif err != nil {\n\t\treturn &Transactions{}, err\n\t}\n\treturn transactions, nil\n}", "func (b *BlockStorage) StoreBlock(\n\tctx context.Context,\n\ttransaction DatabaseTransaction,\n\tblock *rosetta.Block,\n) error {\n\tbuf := new(bytes.Buffer)\n\terr := gob.NewEncoder(buf).Encode(block)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Store block\n\terr = transaction.Set(ctx, getBlockKey(block.BlockIdentifier), buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Store block hash\n\terr = b.storeHash(ctx, transaction, block.BlockIdentifier.Hash, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Store all transaction hashes\n\tfor _, txn := range block.Transactions {\n\t\terr = b.storeHash(ctx, transaction, txn.TransactionIdentifier.Hash, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func BroadcastTransaction(asset bcoins.Coin, tx bcoins.Transaction) (insightjson.Txid, bcoins.Transaction, error) {\n\n\ttx.AssetSymbol = asset.Symbol\n\ttx.AssetName = asset.Name\n\n\tjsonData := insightjson.InsightRawTx{Rawtx: tx.SignedTx}\n\tjsonValue, err := json.Marshal(jsonData)\n\tif err != nil {\n\t\treturn insightjson.Txid{}, bcoins.Transaction{}, fmt.Errorf(\"error broadcasting %s tx because jsonMarshal failed: %s\\n\", asset.Name, err)\n\t}\n\n\tinsightExplorer, _ := GetInsightExplorer(asset.Symbol)\n\tinsightExplorerBroacastApi := fmt.Sprintf(\"%s/tx/send\", insightExplorer.Api)\n\n\tresponse, err := http.Post(insightExplorerBroacastApi, \"application/json\", bytes.NewBuffer(jsonValue))\n\tif err != nil {\n\t\treturn insightjson.Txid{}, bcoins.Transaction{}, fmt.Errorf(\"Error broadcasting %s transaction with blockexplorer: %s\\n\", asset.Name, err)\n\t}\n\n\tdefer response.Body.Close()\n\n\tresult, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn insightjson.Txid{}, bcoins.Transaction{}, fmt.Errorf(\"error reading response from %s blockexplorer broadcast: %s\\n\", asset.Name, err)\n\t}\n\n\tif response.StatusCode != 200 { // some error handling if broadcasting fails\n\t\trejectReason := fmt.Sprintf(\"Error %s blockexplorer response status code: %d\\n\", asset.Name, response.StatusCode)\n\t\tswitch rejectReason {\n\t\tcase ErrNotEnoughBalance:\n\t\t\treturn insightjson.Txid{}, bcoins.Transaction{}, fmt.Errorf(\"not enough balance to cover the transaction including the required fees\")\n\t\tcase ErrNotEnoughFee:\n\t\t\treturn insightjson.Txid{}, bcoins.Transaction{}, fmt.Errorf(\"fee needs to be higher\")\n\t\tcase ErrTransactionTooSmall:\n\t\t\treturn insightjson.Txid{}, bcoins.Transaction{}, fmt.Errorf(\"transaction too small (dust transaction)\\nTx does not meet the minimal amount\")\n\t\tcase ErrTxDecodeFailed:\n\t\t\treturn insightjson.Txid{}, bcoins.Transaction{}, fmt.Errorf(\"transaction decode failed !\\n Maybe a wrong address?\")\n\t\tdefault:\n\t\t\treturn insightjson.Txid{}, bcoins.Transaction{}, fmt.Errorf(\"%s\\n\", string(result))\n\t\t}\n\t}\n\n\tvar txId = insightjson.Txid{}\n\terr = json.Unmarshal([]byte(result), &txId)\n\tif err != nil {\n\t\treturn txId, bcoins.Transaction{}, fmt.Errorf(\"something went wrong with receiving your txid\")\n\t}\n\n\ttx.TxId = txId.Txid\n\n\treturn txId, tx, nil\n}", "func (_Rootchain *RootchainCallerSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _Rootchain.Contract.Blocks(&_Rootchain.CallOpts, arg0)\n}", "func ApplyBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block) ([]byte, error) {\n\tvar eventCache types.Fireable // nil\n\t_, err := execBlockOnProxyApp(eventCache, appConnConsensus, block)\n\tif err != nil {\n\t\tlog.Warn(\"Error executing block on proxy app\", \"height\", block.Height, \"err\", err)\n\t\treturn nil, err\n\t}\n\t// Commit block, get hash back\n\tres := appConnConsensus.CommitSync()\n\tif res.IsErr() {\n\t\tlog.Warn(\"Error in proxyAppConn.CommitSync\", \"error\", res)\n\t\treturn nil, res\n\t}\n\tif res.Log != \"\" {\n\t\tlog.Info(\"Commit.Log: \" + res.Log)\n\t}\n\treturn res.Data, nil\n}", "func convertBlock(block *ethtypes.Block) *types.Block {\n\tif block == nil {\n\t\treturn nil\n\t}\n\tb := &types.Block{}\n\tb.Coinbase = hex.EncodeToString(block.Coinbase)\n\tb.Difficulty = block.Difficulty.String()\n\tb.GasLimit = block.GasLimit.String()\n\tb.GasUsed = block.GasUsed.String()\n\tb.Hash = hex.EncodeToString(block.Hash())\n\tb.MinGasPrice = block.MinGasPrice.String()\n\tb.Nonce = hex.EncodeToString(block.Nonce)\n\tb.Number = block.Number.String()\n\tb.PrevHash = hex.EncodeToString(block.PrevHash)\n\tb.Time = int(block.Time)\n\ttxs := make([]*types.Transaction, len(block.Transactions()))\n\tfor idx, tx := range block.Transactions() {\n\t\ttxs[idx] = convertTx(tx)\n\t}\n\tb.Transactions = txs\n\tb.TxRoot = hex.EncodeToString(block.TxSha)\n\tb.UncleRoot = hex.EncodeToString(block.UncleSha)\n\tb.Uncles = make([]string, len(block.Uncles))\n\tfor idx, u := range block.Uncles {\n\t\tb.Uncles[idx] = hex.EncodeToString(u.Hash())\n\t}\n\treturn b\n}", "func NewBlockFilter() Filter {\n\treturn &blockFilter{}\n}", "func (ns *EsIndexer) IndexBlock(block *types.Block) {\n\tctx := context.Background()\n\tesBlock := ConvBlock(block)\n\tput, err := ns.client.Index().Index(ns.indexNamePrefix + \"block\").Type(\"block\").Id(esBlock.id).BodyJson(esBlock).Do(ctx)\n\tif err != nil {\n\t\tns.log.Warn().Err(err).Msg(\"Failed to index block\")\n\t\treturn\n\t}\n\n\tif len(block.Body.Txs) > 0 {\n\t\ttxChannel := make(chan EsType)\n\t\tnameChannel := make(chan EsType)\n\t\tdone := make(chan struct{})\n\t\tgenerator := func() error {\n\t\t\tdefer close(txChannel)\n\t\t\tdefer close(done)\n\t\t\tns.IndexTxs(block, block.Body.Txs, txChannel, nameChannel)\n\t\t\treturn nil\n\t\t}\n\n\t\twaitForNames := func() error {\n\t\t\tdefer close(nameChannel)\n\t\t\t<-done\n\t\t\treturn nil\n\t\t}\n\t\tgo BulkIndexer(ctx, ns.log, ns.client, nameChannel, waitForNames, ns.indexNamePrefix+\"name\", \"name\", 2500, true)\n\n\t\tBulkIndexer(ctx, ns.log, ns.client, txChannel, generator, ns.indexNamePrefix+\"tx\", \"tx\", 10000, false)\n\n\t}\n\n\tns.log.Info().Uint64(\"blockNo\", block.Header.BlockNo).Int(\"txs\", len(block.Body.Txs)).Str(\"blockHash\", put.Id).Msg(\"Indexed block\")\n}", "func (bc *BlockChain)AddBlock(txs []*Transaction) {\n\tfor _, tx := range txs{\n\t\tif !bc.VerifyTransaction(tx) {\n\t\t\tfmt.Println(\"校验交易失败\")\n\t\t\treturn\n\t\t}\n\t}\n\n\n\t//found the last block's hash\n\tlastHash := bc.tail\n\tdb := bc.db\n\t//create a new block\n\t//send the new block into the blockchain\n\tdb.Update(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket([]byte(BlockBucket))\n\t\tif bucket == nil{\n\t\t\tlog.Fatal(\"no bucket\")\n\t\t}else{\n\t\t\t//Write message into database\n\t\t\tblock := NewBlock(txs, lastHash)\n\t\t\tbucket.Put(block.Hash,block.Serialize())\n\t\t\tbucket.Put([]byte(\"LastHashKey\"),block.Hash)\n\n\t\t\t//update the last hash\n\t\t\tbc.tail = block.Hash\n\n\t\t}\n\t\treturn nil\n\t})\n}", "func Test_ValidateBlockTransactions_Transactions(t *testing.T) {\n\tvar blockTransactionValidator = &BlockTransactionValidator{}\n\t// create inputs transaction\n\tvar blockIndex = 12\n\tvar transactions = []*Transaction{\n\t\t// coinbase transaction\n\t\t{\n\t\t\tID: \"ebafa7518cac709e160f201a888bdf3c969c36993eefbf852cc30c9eb1a553b8\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"\",\n\t\t\t\t\tSignature: \"\",\n\t\t\t\t\tOutputIndex: blockIndex,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: \"coinbase-address\",\n\t\t\t\t\tAmount: CoinbaseAmount,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"3e5d88c061d2b79dd2ac79daf877232203089307d4576b2c1b3851b4920eb952\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"1\",\n\t\t\t\t\tSignature: \"invalid\",\n\t\t\t\t\tOutputIndex: 10,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"7ef0ab206de97f0906adbaccb68bdd7039b86893cbeede8ef9311858b8187fdb\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"2\",\n\t\t\t\t\tSignature: \"invalid\",\n\t\t\t\t\tOutputIndex: 20,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 200,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar unspentTransactionOutputs = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"1\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 100,\n\t\t},\n\t\t{\n\t\t\tOutputID: \"2\",\n\t\t\tOutputIndex: 20,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 200,\n\t\t},\n\t}\n\n\t// create coinbase transaction\n\tresult, _ := blockTransactionValidator.ValidateBlockTransactions(transactions, unspentTransactionOutputs, blockIndex)\n\n\t// validate expected\n\tif result {\n\t\tt.Errorf(\"block transactions are not valid so the result should be false\")\n\t}\n}", "func (p *bitsharesAPI) GetBlock(number uint64) (*objects.Block, error) {\n\tvar result *objects.Block\n\terr := p.call(p.databaseAPIID, \"get_block\", &result, number)\n\treturn result, err\n}", "func LogBlock(block *util.Block) error {\n\tmtx.Lock()\n\tdefer mtx.Unlock()\n\n\treceivedLogBlocks++\n\treceivedLogTx += int64(len(block.MsgBlock().Transactions))\n\n\tnow := mstime.Now()\n\tduration := now.Sub(lastBlockLogTime)\n\tif duration < time.Second*10 {\n\t\treturn nil\n\t}\n\n\t// Truncate the duration to 10s of milliseconds.\n\ttDuration := duration.Round(10 * time.Millisecond)\n\n\t// Log information about new block blue score.\n\tblockStr := \"blocks\"\n\tif receivedLogBlocks == 1 {\n\t\tblockStr = \"block\"\n\t}\n\ttxStr := \"transactions\"\n\tif receivedLogTx == 1 {\n\t\ttxStr = \"transaction\"\n\t}\n\n\tblueScore, err := block.BlueScore()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Infof(\"Processed %d %s in the last %s (%d %s, blue score %d, %s)\",\n\t\treceivedLogBlocks, blockStr, tDuration, receivedLogTx,\n\t\ttxStr, blueScore, block.MsgBlock().Header.Timestamp)\n\n\treceivedLogBlocks = 0\n\treceivedLogTx = 0\n\tlastBlockLogTime = now\n\treturn nil\n}", "func NewBlock(data string, transactions []*Tx, prevBlockHash []byte) *Block {\n\tblock := &Block{\n\t\tIdentifier: internal.GenerateID(),\n\t\tData: []byte(data),\n\t\tTransactions: transactions,\n\t\tPrevBlockHash: prevBlockHash,\n\t\tTimestamp: time.Now().Unix(),\n\t}\n\n\tpow := NewPow(block)\n\tnonce, hash := pow.Run()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\treturn block\n}", "func New(storage Storage) *Block {\n\tb := Block{\n\t\tstorage: storage,\n\t}\n\tb.Transactions = make([]transaction.Transaction, 0, 0)\n\treturn &b\n}", "func (self *BlockChain) NewTransaction(sender string, recipient string, amount float32) {\n\tnewTransaction := Transaction{Sender: sender, Recipient: recipient, Amount: amount}\n\tself.CurrentTransactions = append(self.CurrentTransactions, newTransaction)\n\tprint(\"added. pending transactions ... \")\n\tprint(len(self.CurrentTransactions), \"\\n\")\n\n}", "func (l *Ledger) FormatBlock(txList []*pb.Transaction,\n\tproposer []byte, ecdsaPk *ecdsa.PrivateKey, /*矿工的公钥私钥*/\n\ttimestamp int64, curTerm int64, curBlockNum int64,\n\tpreHash []byte, utxoTotal *big.Int) (*pb.InternalBlock, error) {\n\treturn l.formatBlock(txList, proposer, ecdsaPk, timestamp, curTerm, curBlockNum, preHash, 0, utxoTotal, true, nil, nil, 0)\n}" ]
[ "0.76878", "0.698557", "0.67671347", "0.6700926", "0.6428531", "0.6424233", "0.64124113", "0.63116837", "0.62905055", "0.6248111", "0.6206847", "0.619386", "0.61346436", "0.61243284", "0.61152464", "0.611218", "0.60812044", "0.6079944", "0.6077914", "0.6076352", "0.605372", "0.60522217", "0.6051942", "0.6040112", "0.6034498", "0.60343546", "0.60157096", "0.5996543", "0.59921366", "0.5991675", "0.5980894", "0.59785116", "0.5944996", "0.59327394", "0.59127015", "0.591034", "0.5900532", "0.5900296", "0.58888334", "0.5865399", "0.5864185", "0.5853186", "0.5845227", "0.58411056", "0.583202", "0.58269536", "0.58242977", "0.5823324", "0.5820084", "0.58046734", "0.5802488", "0.5798986", "0.57886124", "0.57851577", "0.5768783", "0.5766602", "0.5765256", "0.57539576", "0.57404315", "0.5739846", "0.57370996", "0.5723505", "0.57136893", "0.5707872", "0.5703859", "0.570375", "0.5695094", "0.5680447", "0.56633276", "0.5653876", "0.56450504", "0.56432676", "0.56328386", "0.5618323", "0.5614502", "0.56115544", "0.5611004", "0.5604469", "0.560389", "0.5597038", "0.5573756", "0.55642843", "0.556154", "0.5557155", "0.5556635", "0.55495465", "0.5546647", "0.5545173", "0.55416", "0.5539894", "0.55370826", "0.55353624", "0.55347246", "0.55337924", "0.55318296", "0.5530792", "0.55284536", "0.5527401", "0.5518592", "0.55075145" ]
0.75958097
1
GetOrganizationSpaces returns a list of spaces in the specified org
func (actor Actor) GetOrganizationSpaces(orgGUID string) ([]Space, Warnings, error) { ccv2Spaces, warnings, err := actor.CloudControllerClient.GetSpaces(ccv2.Query{ Filter: ccv2.OrganizationGUIDFilter, Operator: ccv2.EqualOperator, Values: []string{orgGUID}, }) if err != nil { return []Space{}, Warnings(warnings), err } spaces := make([]Space, len(ccv2Spaces)) for i, ccv2Space := range ccv2Spaces { spaces[i] = Space(ccv2Space) } return spaces, Warnings(warnings), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (actor Actor) GetOrganizationSpaces(orgGUID string) ([]Space, Warnings, error) {\n\tquery := []ccv2.Query{\n\t\t{\n\t\t\tFilter: ccv2.OrganizationGUIDFilter,\n\t\t\tOperator: ccv2.EqualOperator,\n\t\t\tValue: orgGUID,\n\t\t}}\n\tccv2Spaces, warnings, err := actor.CloudControllerClient.GetSpaces(query)\n\tif err != nil {\n\t\treturn []Space{}, Warnings(warnings), err\n\t}\n\n\tvar spaces []Space\n\n\tfor _, ccv2Space := range ccv2Spaces {\n\t\tspaces = append(spaces, Space{\n\t\t\tGUID: ccv2Space.GUID,\n\t\t\tName: ccv2Space.Name,\n\t\t\tAllowSSH: ccv2Space.AllowSSH,\n\t\t})\n\t}\n\n\treturn spaces, Warnings(warnings), nil\n}", "func (actor Actor) GetOrganizationSpaces(orgGUID string) ([]resources.Space, Warnings, error) {\n\treturn actor.GetOrganizationSpacesWithLabelSelector(orgGUID, \"\")\n}", "func (client *Client) GetSpaces(query ...Query) ([]resources.Space, IncludedResources, Warnings, error) {\n\tvar returnedResources []resources.Space\n\n\tincludedResources, warnings, err := client.MakeListRequest(RequestParams{\n\t\tRequestName: internal.GetSpacesRequest,\n\t\tQuery: query,\n\t\tResponseBody: resources.Space{},\n\t\tAppendToList: func(item interface{}) error {\n\t\t\treturnedResources = append(returnedResources, item.(resources.Space))\n\t\t\treturn nil\n\t\t},\n\t})\n\n\treturn returnedResources, includedResources, warnings, err\n}", "func (client *Client) GetSpaces(query ...Query) ([]Space, IncludedResources, Warnings, error) {\n\tvar resources []Space\n\n\tincludedResources, warnings, err := client.MakeListRequest(RequestParams{\n\t\tRequestName: internal.GetSpacesRequest,\n\t\tQuery: query,\n\t\tResponseBody: Space{},\n\t\tAppendToList: func(item interface{}) error {\n\t\t\tresources = append(resources, item.(Space))\n\t\t\treturn nil\n\t\t},\n\t})\n\n\treturn resources, includedResources, warnings, err\n}", "func (client *Client) GetSpaces() (map[string]gocf.Space, error) {\n\tspaceList, err := client.gocfClient.ListSpacesByQuery(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tspaceMap := map[string]gocf.Space{}\n\tfor _, space := range spaceList {\n\t\tspaceMap[space.Guid] = space\n\t}\n\n\treturn spaceMap, nil\n}", "func (actor Actor) GetOrganizationSpacesWithLabelSelector(orgGUID string, labelSelector string) ([]resources.Space, Warnings, error) {\n\n\tqueries := []ccv3.Query{\n\t\tccv3.Query{Key: ccv3.OrganizationGUIDFilter, Values: []string{orgGUID}},\n\t\tccv3.Query{Key: ccv3.OrderBy, Values: []string{ccv3.NameOrder}},\n\t}\n\tif len(labelSelector) > 0 {\n\t\tqueries = append(queries, ccv3.Query{Key: ccv3.LabelSelectorFilter, Values: []string{labelSelector}})\n\t}\n\n\tccv3Spaces, _, warnings, err := actor.CloudControllerClient.GetSpaces(queries...)\n\tif err != nil {\n\t\treturn []resources.Space{}, Warnings(warnings), err\n\t}\n\n\tspaces := make([]resources.Space, len(ccv3Spaces))\n\tfor i, ccv3Space := range ccv3Spaces {\n\t\tspaces[i] = resources.Space(ccv3Space)\n\t}\n\n\treturn spaces, Warnings(warnings), nil\n}", "func (actor Actor) GetSpaceByOrganizationAndName(orgGUID string, spaceName string) (Space, Warnings, error) {\n\tquery := []ccv2.Query{\n\t\t{\n\t\t\tFilter: ccv2.NameFilter,\n\t\t\tOperator: ccv2.EqualOperator,\n\t\t\tValue: spaceName,\n\t\t},\n\t\t{\n\t\t\tFilter: ccv2.OrganizationGUIDFilter,\n\t\t\tOperator: ccv2.EqualOperator,\n\t\t\tValue: orgGUID,\n\t\t},\n\t}\n\n\tccv2Spaces, warnings, err := actor.CloudControllerClient.GetSpaces(query)\n\tif err != nil {\n\t\treturn Space{}, Warnings(warnings), err\n\t}\n\n\tif len(ccv2Spaces) == 0 {\n\t\treturn Space{}, Warnings(warnings), SpaceNotFoundError{Name: spaceName}\n\t}\n\n\tif len(ccv2Spaces) > 1 {\n\t\treturn Space{}, Warnings(warnings), MultipleSpacesFoundError{OrgGUID: orgGUID, Name: spaceName}\n\t}\n\n\treturn Space{\n\t\tGUID: ccv2Spaces[0].GUID,\n\t\tName: ccv2Spaces[0].Name,\n\t\tAllowSSH: ccv2Spaces[0].AllowSSH,\n\t}, Warnings(warnings), nil\n}", "func (actor Actor) GetSpaceByOrganizationAndName(orgGUID string, spaceName string) (Space, Warnings, error) {\n\tccv2Spaces, warnings, err := actor.CloudControllerClient.GetSpaces(\n\t\tccv2.Query{\n\t\t\tFilter: ccv2.NameFilter,\n\t\t\tOperator: ccv2.EqualOperator,\n\t\t\tValues: []string{spaceName},\n\t\t},\n\t\tccv2.Query{\n\t\t\tFilter: ccv2.OrganizationGUIDFilter,\n\t\t\tOperator: ccv2.EqualOperator,\n\t\t\tValues: []string{orgGUID},\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn Space{}, Warnings(warnings), err\n\t}\n\n\tif len(ccv2Spaces) == 0 {\n\t\treturn Space{}, Warnings(warnings), SpaceNotFoundError{Name: spaceName}\n\t}\n\n\tif len(ccv2Spaces) > 1 {\n\t\treturn Space{}, Warnings(warnings), MultipleSpacesFoundError{OrgGUID: orgGUID, Name: spaceName}\n\t}\n\n\treturn Space(ccv2Spaces[0]), Warnings(warnings), nil\n}", "func (c *DetaClient) ListSpaces() (ListSpacesResponse, error) {\n\ti := &requestInput{\n\t\tPath: fmt.Sprintf(\"/%s/\", \"spaces\"),\n\t\tMethod: \"GET\",\n\t\tNeedsAuth: true,\n\t}\n\n\to, err := c.request(i)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif o.Status != 200 {\n\t\tmsg := o.Error.Message\n\t\tif msg == \"\" {\n\t\t\tmsg = o.Error.Errors[0]\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to list spaces: %v\", msg)\n\t}\n\tvar resp ListSpacesResponse\n\terr = json.Unmarshal(o.Body, &resp)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list spaces: %v\", err)\n\t}\n\treturn resp, nil\n}", "func (s *service) ListStorageSpaces(ctx context.Context, req *provider.ListStorageSpacesRequest) (*provider.ListStorageSpacesResponse, error) {\n\tspaceTypes := map[string]struct{}{}\n\tvar exists = struct{}{}\n\tappendTypes := []string{}\n\tvar spaceID *provider.ResourceId\n\tfor _, f := range req.Filters {\n\t\tswitch f.Type {\n\t\tcase provider.ListStorageSpacesRequest_Filter_TYPE_SPACE_TYPE:\n\t\t\tspaceType := f.GetSpaceType()\n\t\t\tif spaceType == \"+mountpoint\" || spaceType == \"+grant\" {\n\t\t\t\tappendTypes = append(appendTypes, strings.TrimPrefix(spaceType, \"+\"))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tspaceTypes[spaceType] = exists\n\t\tcase provider.ListStorageSpacesRequest_Filter_TYPE_ID:\n\t\t\tresID, err := storagespace.ParseID(f.GetId().GetOpaqueId())\n\t\t\tif err != nil {\n\t\t\t\treturn &provider.ListStorageSpacesResponse{\n\t\t\t\t\tStatus: &rpc.Status{Code: rpc.Code_CODE_INVALID_ARGUMENT, Message: err.Error()},\n\t\t\t\t}, nil\n\t\t\t}\n\t\t\tif resID.SpaceId != utils.PublicStorageSpaceID {\n\t\t\t\treturn &provider.ListStorageSpacesResponse{\n\t\t\t\t\t// a specific id was requested, return not found instead of empty list\n\t\t\t\t\tStatus: &rpc.Status{Code: rpc.Code_CODE_NOT_FOUND},\n\t\t\t\t}, nil\n\t\t\t}\n\t\t\tspaceID = &resID\n\t\t}\n\t}\n\n\t// if there is no public scope there are no publicstorage spaces\n\tshare, ok := extractLinkFromScope(ctx)\n\tif !ok {\n\t\treturn &provider.ListStorageSpacesResponse{\n\t\t\tStatus: &rpc.Status{Code: rpc.Code_CODE_OK},\n\t\t}, nil\n\t}\n\n\tif len(spaceTypes) == 0 {\n\t\tspaceTypes[\"mountpoint\"] = exists\n\t}\n\tfor _, s := range appendTypes {\n\t\tspaceTypes[s] = exists\n\t}\n\n\tres := &provider.ListStorageSpacesResponse{\n\t\tStatus: status.NewOK(ctx),\n\t}\n\tfor k := range spaceTypes {\n\t\tswitch k {\n\t\tcase \"grant\":\n\t\t\t// when a list storage space with the resourceid of an external\n\t\t\t// resource is made we may have a grant for it\n\t\t\troot := share.ResourceId\n\t\t\tif spaceID != nil && !utils.ResourceIDEqual(spaceID, root) {\n\t\t\t\t// none of our business\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// we know a grant for this resource\n\t\t\tspace := &provider.StorageSpace{\n\t\t\t\tId: &provider.StorageSpaceId{\n\t\t\t\t\tOpaqueId: storagespace.FormatResourceID(*root),\n\t\t\t\t},\n\t\t\t\tSpaceType: \"grant\",\n\t\t\t\tOwner: &userv1beta1.User{Id: share.Owner},\n\t\t\t\t// the publicstorageprovider keeps track of mount points\n\t\t\t\tRoot: root,\n\t\t\t}\n\n\t\t\tres.StorageSpaces = append(res.StorageSpaces, space)\n\t\tcase \"mountpoint\":\n\t\t\troot := &provider.ResourceId{\n\t\t\t\tStorageId: utils.PublicStorageProviderID,\n\t\t\t\tSpaceId: utils.PublicStorageSpaceID,\n\t\t\t\tOpaqueId: share.Token, // the link share has no id, only the token\n\t\t\t}\n\t\t\tif spaceID != nil {\n\t\t\t\tswitch {\n\t\t\t\tcase utils.ResourceIDEqual(spaceID, root):\n\t\t\t\t\t// we have a virtual node\n\t\t\t\tcase utils.ResourceIDEqual(spaceID, share.ResourceId):\n\t\t\t\t\t// we have a mount point\n\t\t\t\t\troot = share.ResourceId\n\t\t\t\tdefault:\n\t\t\t\t\t// none of our business\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tspace := &provider.StorageSpace{\n\t\t\t\tId: &provider.StorageSpaceId{\n\t\t\t\t\tOpaqueId: storagespace.FormatResourceID(*root),\n\t\t\t\t},\n\t\t\t\tSpaceType: \"mountpoint\",\n\t\t\t\tOwner: &userv1beta1.User{Id: share.Owner}, // FIXME actually, the mount point belongs to no one?\n\t\t\t\t// the publicstorageprovider keeps track of mount points\n\t\t\t\tRoot: root,\n\t\t\t}\n\n\t\t\tres.StorageSpaces = append(res.StorageSpaces, space)\n\t\t}\n\t}\n\treturn res, nil\n}", "func (c *SpaceClient) List(ctx context.Context, opts *SpaceListOptions) ([]*resource.Space, *Pager, error) {\n\tif opts == nil {\n\t\topts = NewSpaceListOptions()\n\t}\n\topts.Include = resource.SpaceIncludeNone\n\n\tvar res resource.SpaceList\n\terr := c.client.get(ctx, path.Format(\"/v3/spaces?%s\", opts.ToQueryString()), &res)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tpager := NewPager(res.Pagination)\n\treturn res.Resources, pager, nil\n}", "func (r spaceRepository) ListAllSpaces(ctx context.Context, skip uint64, take uint64) ([]domain.Space, error) {\n\ts := r.session.Clone()\n\tdefer s.Close()\n\tlog.Println(\"got in repo\")\n\n\tvar spaces []domain.Space\n\n\terr := s.DB(config.MongoDB).C(config.MongoCollection).Find(nil).All(&spaces)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn spaces, nil\n}", "func (c *SpaceClient) ListIncludeOrganizations(ctx context.Context, opts *SpaceListOptions) ([]*resource.Space, []*resource.Organization, *Pager, error) {\n\tif opts == nil {\n\t\topts = NewSpaceListOptions()\n\t}\n\topts.Include = resource.SpaceIncludeOrganization\n\n\tvar res resource.SpaceList\n\terr := c.client.get(ctx, path.Format(\"/v3/spaces?%s\", opts.ToQueryString()), &res)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tpager := NewPager(res.Pagination)\n\treturn res.Resources, res.Included.Organizations, pager, nil\n}", "func (r *SpacesService) List() *SpacesListCall {\n\tc := &SpacesListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\treturn c\n}", "func (c *cfService) Spaces() Spaces {\n\treturn newSpacesAPI(c.Client)\n}", "func (a *SpacesApiService) ListSpaces(opts ...APIOption) (ListSpacesResponse, error) {\n\tvar (\n\t\tlocalVarAPIOptions = new(APIOptions)\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ListSpacesResponse\n\t)\n\n\tfor _, opt := range opts {\n\t\topt(localVarAPIOptions)\n\t}\n\n\tlocalVarOptionals, ok := localVarAPIOptions.params.(*ListSpacesParams)\n\tif localVarAPIOptions.params != nil && !ok {\n\t\treturn localVarReturnValue, reportError(\"provided params were not of type *ListSpacesParams\")\n\t}\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.basePath + \"/video/v1/spaces\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\tif localVarOptionals != nil && isSet(localVarOptionals.Limit) {\n\t\tlocalVarQueryParams.Add(\"limit\", parameterToString(localVarOptionals.Limit, \"\"))\n\t}\n\tif localVarOptionals != nil && isSet(localVarOptionals.Page) {\n\t\tlocalVarQueryParams.Add(\"page\", parameterToString(localVarOptionals.Page, \"\"))\n\t}\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\n\tr, err := a.client.prepareRequest(localVarAPIOptions, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, err\n\t}\n\n\t// Check for common HTTP error status codes\n\terr = CheckForHttpError(localVarHttpResponse.StatusCode, localVarBody)\n\tif err != nil {\n\t\treturn localVarReturnValue, err\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, newErr\n\t}\n\n\treturn localVarReturnValue, nil\n}", "func (a *Client) GetOnboardingSpaces(params *GetOnboardingSpacesParams, authInfo runtime.ClientAuthInfoWriter) (*GetOnboardingSpacesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetOnboardingSpacesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getOnboarding_Spaces\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/{baseSpaceId}/useronboarding\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetOnboardingSpacesReader{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.(*GetOnboardingSpacesOK)\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 getOnboarding_Spaces: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func orgGroups(client *chef.Client, org string) map[string]string {\n\tgroupList, err := client.Groups.List()\n\tif err != nil {\n\t\tfmt.Println(\"Issue listing groups:\", err)\n\t\tpanic(err.Error()) // proper error handling instead of panic in your app\n\t}\n\treturn groupList\n}", "func getImagespaces(hostBase string) (*http.Response, []*server.Organization, error) {\n\n\turl := fmt.Sprintf(\"%s/\", hostBase)\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Add(\"Accept\", \"application/json\")\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", \"e30K.e30K.e30K\"))\n\tclient := &http.Client{}\n\tresponse, err := client.Do(req)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\trepositories := []*server.Organization{}\n\n\tbytes, err := ioutil.ReadAll(response.Body)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tjson.Unmarshal(bytes, &repositories)\n\n\treturn response, repositories, err\n\n}", "func (m *PrinterLocation) GetOrganization()([]string) {\n val, err := m.GetBackingStore().Get(\"organization\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]string)\n }\n return nil\n}", "func (a *Client) GetAzureWebSitesListSpaces(params *GetAzureWebSitesListSpacesParams, authInfo runtime.ClientAuthInfoWriter) (*GetAzureWebSitesListSpacesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetAzureWebSitesListSpacesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getAzureWebSitesList_Spaces\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/{baseSpaceId}/accounts/{id}/websites\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetAzureWebSitesListSpacesReader{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.(*GetAzureWebSitesListSpacesOK)\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 getAzureWebSitesList_Spaces: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func getWorkspaces_(tx *bolt.Tx, typespace string,\n\tnamespace string) (*bolt.Bucket, error) {\n\n\ttypespaces := tx.Bucket(typespacesBucket)\n\n\tnamespaces, err := typespaces.CreateBucketIfNotExists([]byte(typespace))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tworkspaces, err := namespaces.CreateBucketIfNotExists([]byte(namespace))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn workspaces, nil\n}", "func (m *Manager) ListOrganization() ([]entities.Organization, derrors.Error) {\n\treturn m.Provider.List()\n}", "func GetIoTSpace(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *IoTSpaceState, opts ...pulumi.ResourceOption) (*IoTSpace, error) {\n\tvar resource IoTSpace\n\terr := ctx.ReadResource(\"azure-native:iotspaces/v20171001preview:IoTSpace\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (a *SpaceApiService) SearchSpaces(ctx _context.Context, localVarOptionals *SearchSpacesOpts) ([]Space, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []Space\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/spaces/search\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif localVarOptionals != nil && localVarOptionals.Fields.IsSet() {\n\t\tlocalVarQueryParams.Add(\"fields\", parameterToString(localVarOptionals.Fields.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Page.IsSet() {\n\t\tlocalVarQueryParams.Add(\"page\", parameterToString(localVarOptionals.Page.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.PerPage.IsSet() {\n\t\tlocalVarQueryParams.Add(\"per_page\", parameterToString(localVarOptionals.PerPage.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Limit.IsSet() {\n\t\tlocalVarQueryParams.Add(\"limit\", parameterToString(localVarOptionals.Limit.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Offset.IsSet() {\n\t\tlocalVarQueryParams.Add(\"offset\", parameterToString(localVarOptionals.Offset.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Sorts.IsSet() {\n\t\tlocalVarQueryParams.Add(\"sorts\", parameterToString(localVarOptionals.Sorts.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Name.IsSet() {\n\t\tlocalVarQueryParams.Add(\"name\", parameterToString(localVarOptionals.Name.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Id.IsSet() {\n\t\tlocalVarQueryParams.Add(\"id\", parameterToString(localVarOptionals.Id.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.ParentId.IsSet() {\n\t\tlocalVarQueryParams.Add(\"parent_id\", parameterToString(localVarOptionals.ParentId.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.CreatorId.IsSet() {\n\t\tlocalVarQueryParams.Add(\"creator_id\", parameterToString(localVarOptionals.CreatorId.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.FilterOr.IsSet() {\n\t\tlocalVarQueryParams.Add(\"filter_or\", parameterToString(localVarOptionals.FilterOr.Value(), \"\"))\n\t}\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 []Space\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 == 400 {\n\t\t\tvar v Error\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 == 404 {\n\t\t\tvar v Error\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 (a *Client) GetAzureStorageAccountsListSpaces(params *GetAzureStorageAccountsListSpacesParams, authInfo runtime.ClientAuthInfoWriter) (*GetAzureStorageAccountsListSpacesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetAzureStorageAccountsListSpacesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getAzureStorageAccountsList_Spaces\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/{baseSpaceId}/accounts/{id}/storageAccounts\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetAzureStorageAccountsListSpacesReader{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.(*GetAzureStorageAccountsListSpacesOK)\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 getAzureStorageAccountsList_Spaces: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (a *Client) GetAzureResourceGroupsListSpaces(params *GetAzureResourceGroupsListSpacesParams, authInfo runtime.ClientAuthInfoWriter) (*GetAzureResourceGroupsListSpacesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetAzureResourceGroupsListSpacesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getAzureResourceGroupsList_Spaces\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/{baseSpaceId}/accounts/{id}/resourceGroups\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetAzureResourceGroupsListSpacesReader{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.(*GetAzureResourceGroupsListSpacesOK)\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 getAzureResourceGroupsList_Spaces: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func getKeyspaces(t testing.TB, database *db.DatabaseContext) []string {\n\tvar keyspaces []string\n\tfor _, collection := range database.CollectionByID {\n\t\tkeyspaces = append(keyspaces, getRESTKeyspace(t, database.Name, collection))\n\t}\n\tsort.Strings(keyspaces)\n\treturn keyspaces\n}", "func (s *VtctldServer) GetKeyspaces(ctx context.Context, req *vtctldatapb.GetKeyspacesRequest) (*vtctldatapb.GetKeyspacesResponse, error) {\n\tnames, err := s.ts.GetKeyspaces(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkeyspaces := make([]*vtctldatapb.Keyspace, len(names))\n\n\tfor i, name := range names {\n\t\tks, err := s.GetKeyspace(ctx, &vtctldatapb.GetKeyspaceRequest{Keyspace: name})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tkeyspaces[i] = ks.Keyspace\n\t}\n\n\treturn &vtctldatapb.GetKeyspacesResponse{Keyspaces: keyspaces}, nil\n}", "func orgGroups(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tvars := mux.Vars(r)\n\torg := cleanInput(vars[\"org\"])\n\tdb := co.DbConnection(dbc)\n\tstmtQryOrgGrp, err := db.Prepare(\"SELECT group_name FROM org_groups where organization_name = ? ;\")\n\tif err != nil {\n\t\tpanic(err.Error()) // proper error handling instead of panic in your app\n\t}\n\tresults, err := stmtQryOrgGrp.Query(org)\n\tif err != nil {\n\t\tpanic(err.Error()) // proper error handling instead of panic in your app\n\t}\n\tvar groups []string\n\tfor results.Next() {\n\t\tvar name string\n\t\terr = results.Scan(&name)\n\t\tif err != nil {\n\t\t\tpanic(err.Error()) // proper error handling instead of panic in your app\n\t\t}\n\t\tgroups = append(groups, name)\n\t}\n\tresults.Close()\n stmtQryOrgGrp.Close()\n\tdb.Close()\n\tgroups = co.Unique(groups)\n\tjsonPrint(w, groups)\n return\n}", "func GetOrganization(clients *common.ClientContainer, handler common.HandlerInterface) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\torglist, err := handler.GetOrganizations(clients)\n\t\tif err != nil {\n\t\t\tlog.Logger.Error(err)\n\t\t\tcommon.WriteErrorToResponse(w, http.StatusInternalServerError,\n\t\t\t\thttp.StatusText(http.StatusInternalServerError),\n\t\t\t\t\"Internal server error occured\")\n\t\t\treturn\n\t\t}\n\t\tw.Write(orglist)\n\t}\n}", "func ListOrganization(orgID string) error {\n\tclient, err := NewPacketClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\torg, _, err := client.Organizations.Get(orgID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te := MarshallAndPrint(org)\n\treturn e\n}", "func (s *Space) GetSpaceBySpaceIds(spaceIds []string) (spaces []map[string]string, err error) {\n\tdb := G.DB()\n\tvar rs *mysql.ResultSet\n\trs, err = db.Query(db.AR().From(Table_Space_Name).Where(map[string]interface{}{\n\t\t\"space_id\": spaceIds,\n\t\t\"is_delete\": Space_Delete_False,\n\t}))\n\tif err != nil {\n\t\treturn\n\t}\n\tspaces = rs.Rows()\n\treturn\n}", "func (a *Client) GetAccountUsageListSpaces(params *GetAccountUsageListSpacesParams, authInfo runtime.ClientAuthInfoWriter) (*GetAccountUsageListSpacesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetAccountUsageListSpacesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getAccountUsageList_Spaces\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/{baseSpaceId}/accounts/{id}/usages\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetAccountUsageListSpacesReader{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.(*GetAccountUsageListSpacesOK)\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 getAccountUsageList_Spaces: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (c *SpaceClient) Get(ctx context.Context, guid string) (*resource.Space, error) {\n\tvar space resource.Space\n\terr := c.client.get(ctx, path.Format(\"/v3/spaces/%s\", guid), &space)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &space, nil\n}", "func (a *Client) GetUserGetTeamsSpaces(params *GetUserGetTeamsSpacesParams, authInfo runtime.ClientAuthInfoWriter) (*GetUserGetTeamsSpacesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetUserGetTeamsSpacesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getUserGetTeams_Spaces\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/{baseSpaceId}/users/{id}/teams\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetUserGetTeamsSpacesReader{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.(*GetUserGetTeamsSpacesOK)\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 getUserGetTeams_Spaces: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (o LookupVirtualNetworkResultOutput) AddressSpaces() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupVirtualNetworkResult) []string { return v.AddressSpaces }).(pulumi.StringArrayOutput)\n}", "func (a *SpaceApiService) AllSpaces(ctx _context.Context, localVarOptionals *AllSpacesOpts) ([]SpaceBase, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []SpaceBase\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/spaces\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif localVarOptionals != nil && localVarOptionals.Fields.IsSet() {\n\t\tlocalVarQueryParams.Add(\"fields\", parameterToString(localVarOptionals.Fields.Value(), \"\"))\n\t}\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 []SpaceBase\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 == 400 {\n\t\t\tvar v Error\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 == 404 {\n\t\t\tvar v Error\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 (s *Db) GetSessionsByOrg(orgID string, areaID string) ([]*userquery.Session, error) {\n\n\t// We retrieve it from the database\n\tvars := make(map[string]interface{})\n\tvars[\"orgID\"] = orgID\n\tvars[\"areaID\"] = areaID\n\n\tresult, err := s.ExecuteSessionQuery(\"FOR s IN Session FILTER s.orgID==@orgID AND s.areaID==@areaID RETURN s\", vars)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}", "func (s *Space) GetSpacesByKeywordAndLimit(keyword string, limit int, number int) (spaces []map[string]string, err error) {\n\n\tdb := G.DB()\n\tvar rs *mysql.ResultSet\n\tsql := db.AR().From(Table_Space_Name).Where(map[string]interface{}{\n\t\t\"is_delete\": Space_Delete_False,\n\t}).WhereWrap(map[string]interface{}{\n\t\t\"name LIKE\": \"%\" + keyword + \"%\",\n\t}, \"AND (\", \"\").WhereWrap(map[string]interface{}{\n\t\t\"description LIKE\": \"%\" + keyword + \"%\",\n\t}, \"OR\", \")\").Limit(limit, number).OrderBy(\"space_id\", \"DESC\")\n\trs, err = db.Query(sql)\n\n\tif err != nil {\n\t\treturn\n\t}\n\tspaces = rs.Rows()\n\n\treturn\n}", "func GetPagingOrgEndpoint(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tslimit := params[\"limit\"]\n\tsoffset := params[\"offset\"]\n\n\t// parser limit to int\n\tlimit, err := strconv.ParseInt(slimit, 10, 64)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 400)\n\t\treturn\n\t}\n\n\t// parser offset to int\n\toffset, err := strconv.ParseInt(soffset, 10, 64)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 400)\n\t\treturn\n\t}\n\n\tcount := db.CountOrg()\n\tscount := strconv.FormatInt(count, 10)\n\n\tpage := float64(count) / float64(limit)\n\tpage = math.Ceil(page)\n\tspage := strconv.FormatFloat(page, 'f', 0, 64)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(\"Pagination-Count\", scount)\n\tw.Header().Set(\"Pagination-Page\", spage)\n\tw.Header().Set(\"Pagination-Limit\", slimit)\n\n\tvar orgs []models.Organization\n\torgs = db.GetLimitOrg(offset, limit)\n\tjson.NewEncoder(w).Encode(orgs)\n\n}", "func (s *Space) GetSpacesByTags(tag string) (spaces []map[string]string, err error) {\n\n\tdb := G.DB()\n\tvar rs *mysql.ResultSet\n\trs, err = db.Query(db.AR().From(Table_Space_Name).Where(map[string]interface{}{\n\t\t\"tags LIKE\": \"%\" + tag + \"%\",\n\t\t\"is_delete\": Space_Delete_False,\n\t}).OrderBy(\"space_id\", \"DESC\"))\n\tif err != nil {\n\t\treturn\n\t}\n\tspaces = rs.Rows()\n\n\treturn\n}", "func (db *PSQL) GetOrganizations() ([]*models.Organization, error) {\n\treturn nil, nil\n}", "func (ps *PgStore) GetOrgGateways(ctx context.Context, orgID int64, macs []string) ([]Gateway, error) {\n\tquery := `\n\t\tSELECT mac, organization_id, stc_org_id\n\t\tFROM gateway\n\t\tWHERE organization_id = $1`\n\targs := []interface{}{orgID}\n\tif len(macs) > 0 {\n\t\tmacCond := ` AND mac IN (`\n\t\tsep := \"\"\n\t\tfor _, mac := range macs {\n\t\t\tgwMAC, err := hex.DecodeString(mac)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid MAC: %s\", gwMAC)\n\t\t\t}\n\t\t\targs = append(args, gwMAC)\n\t\t\tmacCond += fmt.Sprintf(\"%s$%d\", sep, len(args))\n\t\t\tsep = \", \"\n\t\t}\n\t\tmacCond += \")\"\n\t\tquery += macCond\n\t}\n\trows, err := ps.db.QueryContext(ctx, query, args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tvar res []Gateway\n\tfor rows.Next() {\n\t\tvar gw Gateway\n\t\tvar stcOrgID sql.NullInt64\n\t\tif err := rows.Scan(&gw.MAC, &gw.OrganizationID, &stcOrgID); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgw.STCOrgID = &stcOrgID.Int64\n\t\tres = append(res, gw)\n\t}\n\treturn res, rows.Err()\n}", "func (service *UsagesService) GetSpaceUsage(organizationID, orderBy, metric, startAt, endAt string) *Collection {\n\tpath := fmt.Sprintf(\n\t\t\"/organizations/%s/space_periodic_usages?order=%s&metric[in]=%s&dateRange.startAt=%s&dateRange.endAt=%s\",\n\t\torganizationID,\n\t\torderBy,\n\t\tmetric,\n\t\tstartAt,\n\t\tendAt,\n\t)\n\tmethod := \"GET\"\n\n\treq, err := service.c.newRequest(method, path, nil, nil)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tcol := NewCollection(&CollectionOptions{})\n\tcol.c = service.c\n\tcol.req = req\n\n\treturn col\n}", "func (rt *RestTester) GetKeyspaces() []string {\n\tdb := rt.GetDatabase()\n\tvar keyspaces []string\n\tfor _, collection := range db.CollectionByID {\n\t\tkeyspaces = append(keyspaces, getRESTKeyspace(rt.TB, db.Name, collection))\n\t}\n\tsort.Strings(keyspaces)\n\treturn keyspaces\n}", "func (actor Actor) GetOrganizationDomains(orgGUID string) ([]Domain, Warnings, error) {\n\tvar (\n\t\tallWarnings Warnings\n\t\tallDomains []Domain\n\t)\n\n\tdomains, warnings, err := actor.CloudControllerClient.GetSharedDomains()\n\tallWarnings = append(allWarnings, warnings...)\n\n\tif err != nil {\n\t\treturn []Domain{}, allWarnings, err\n\t}\n\tfor _, domain := range domains {\n\t\tallDomains = append(allDomains, Domain(domain))\n\t}\n\n\tdomains, warnings, err = actor.CloudControllerClient.GetOrganizationPrivateDomains(orgGUID)\n\tallWarnings = append(allWarnings, warnings...)\n\n\tif err != nil {\n\t\treturn []Domain{}, allWarnings, err\n\t}\n\tfor _, domain := range domains {\n\t\tallDomains = append(allDomains, Domain(domain))\n\t}\n\n\treturn allDomains, allWarnings, nil\n}", "func (c *Client) OrganizationList(owner bool, cursor string) ([]Organization, error) {\n\tresponse, err := c.APIGet(\"organizations/\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\torgs := make([]Organization, 1)\n\terr = json.Unmarshal(response, &orgs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn orgs, nil\n}", "func (g Graph) ListStorageSpacesWithFilters(ctx context.Context, filters []*storageprovider.ListStorageSpacesRequest_Filter, unrestricted bool) (*storageprovider.ListStorageSpacesResponse, error) {\n\tclient := g.GetGatewayClient()\n\n\tpermissions := make(map[string]struct{}, 1)\n\ts := settingssvc.NewPermissionService(\"com.owncloud.api.settings\", grpc.DefaultClient)\n\n\t_, err := s.GetPermissionByID(ctx, &settingssvc.GetPermissionByIDRequest{\n\t\tPermissionId: settingsServiceExt.ListAllSpacesPermissionID,\n\t})\n\n\t// No error means the user has the permission\n\tif err == nil {\n\t\tpermissions[settingsServiceExt.ListAllSpacesPermissionName] = struct{}{}\n\t}\n\tvalue, err := json.Marshal(permissions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := client.ListStorageSpaces(ctx, &storageprovider.ListStorageSpacesRequest{\n\t\tOpaque: &types.Opaque{Map: map[string]*types.OpaqueEntry{\n\t\t\t\"permissions\": {\n\t\t\t\tDecoder: \"json\",\n\t\t\t\tValue: value,\n\t\t\t},\n\t\t\t\"unrestricted\": {\n\t\t\t\tDecoder: \"plain\",\n\t\t\t\tValue: []byte(strconv.FormatBool(unrestricted)),\n\t\t\t},\n\t\t}},\n\t\tFilters: filters,\n\t})\n\treturn res, err\n}", "func (c *Cluster) GetKeyspaces(ctx context.Context) ([]*vtadminpb.Keyspace, error) {\n\tspan, ctx := trace.NewSpan(ctx, \"Cluster.GetKeyspaces\")\n\tdefer span.Finish()\n\n\tAnnotateSpan(c, span)\n\n\tif err := c.Vtctld.Dial(ctx); err != nil {\n\t\treturn nil, fmt.Errorf(\"Vtctld.Dial(cluster=%s) failed: %w\", c.ID, err)\n\t}\n\n\tresp, err := c.Vtctld.GetKeyspaces(ctx, &vtctldatapb.GetKeyspacesRequest{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar (\n\t\tm sync.Mutex\n\t\twg sync.WaitGroup\n\t\trec concurrency.AllErrorRecorder\n\t\tkeyspaces = make([]*vtadminpb.Keyspace, len(resp.Keyspaces))\n\t)\n\n\tfor i, ks := range resp.Keyspaces {\n\t\twg.Add(1)\n\t\tgo func(i int, ks *vtctldatapb.Keyspace) {\n\t\t\tdefer wg.Done()\n\n\t\t\tshards, err := c.FindAllShardsInKeyspace(ctx, ks.Name, FindAllShardsInKeyspaceOptions{SkipDial: true})\n\t\t\tif err != nil {\n\t\t\t\trec.RecordError(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tkeyspace := &vtadminpb.Keyspace{\n\t\t\t\tCluster: c.ToProto(),\n\t\t\t\tKeyspace: ks,\n\t\t\t\tShards: shards,\n\t\t\t}\n\n\t\t\tm.Lock()\n\t\t\tdefer m.Unlock()\n\t\t\tkeyspaces[i] = keyspace\n\t\t}(i, ks)\n\t}\n\n\twg.Wait()\n\tif rec.HasErrors() {\n\t\treturn nil, rec.Error()\n\t}\n\n\treturn keyspaces, nil\n}", "func (a *Client) GetAzureWebSitesSlotListSpaces(params *GetAzureWebSitesSlotListSpacesParams, authInfo runtime.ClientAuthInfoWriter) (*GetAzureWebSitesSlotListSpacesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetAzureWebSitesSlotListSpacesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getAzureWebSitesSlotList_Spaces\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/{baseSpaceId}/accounts/{id}/{resourceGroupName}/websites/{webSiteName}/slots\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetAzureWebSitesSlotListSpacesReader{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.(*GetAzureWebSitesSlotListSpacesOK)\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 getAzureWebSitesSlotList_Spaces: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (sm *SpaceManager) List(ctx context.Context) ([]string, error) {\n\tlock := sm.Lock.Get(allSpacesLockName)\n\tif !lock.RLock(sm.LockTimeout) {\n\t\treturn nil, ErrorLocking.Format(\"space manager\", allSpacesLockName)\n\t}\n\tdefer lock.RUnlock()\n\treturn list(ctx, sm.Backend, sm.Prefix, validateName, sortNames)\n}", "func (tee *Tee) GetKeyspaces(ctx context.Context) ([]string, error) {\n\treturn tee.readFrom.GetKeyspaces(ctx)\n}", "func (client *Client) GetSpaceRoutes(spaceGUID string, queryParams []Query) ([]Route, Warnings, error) {\n\trequest, err := client.newHTTPRequest(requestOptions{\n\t\tRequestName: internal.RoutesFromSpaceRequest,\n\t\tURIParams: map[string]string{\"space_guid\": spaceGUID},\n\t\tQuery: FormatQueryParameters(queryParams),\n\t})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar fullRoutesList []Route\n\twarnings, err := client.paginate(request, Route{}, func(item interface{}) error {\n\t\tif route, ok := item.(Route); ok {\n\t\t\tfullRoutesList = append(fullRoutesList, route)\n\t\t} else {\n\t\t\treturn cloudcontroller.UnknownObjectInListError{\n\t\t\t\tExpected: Route{},\n\t\t\t\tUnexpected: item,\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\treturn fullRoutesList, warnings, err\n}", "func (actor Actor) GetApplicationsBySpace(spaceGUID string) ([]Application, Warnings, error) {\n\tccApps, warnings, err := actor.CloudControllerClient.GetApplications(\n\t\tccv3.Query{Key: ccv3.SpaceGUIDFilter, Values: []string{spaceGUID}},\n\t)\n\n\tif err != nil {\n\t\treturn []Application{}, Warnings(warnings), err\n\t}\n\n\tvar apps []Application\n\tfor _, ccApp := range ccApps {\n\t\tapps = append(apps, actor.convertCCToActorApplication(ccApp))\n\t}\n\treturn apps, Warnings(warnings), nil\n}", "func (org *OrganizationService) List(ctx context.Context) ([]*Organization, error) {\n\tpath := \"me/organizations\"\n\treq, err := org.client.createRequest(\"GET\", path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := new(GetOrganizationsResponse)\n\terr = org.client.do(ctx, req, c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif strings.ToLower(c.RequestStatus) == \"success\" {\n\t\tif len(c.Organizations) > 0 {\n\t\t\treturn getOrganizationsFromResponse(c.Organizations), nil\n\t\t}\n\t\treturn nil, fmt.Errorf(\"no organizations found\")\n\t}\n\treturn nil, fmt.Errorf(`non-success status returned from snapchat api (list organizations): %s`, c.RequestStatus)\n}", "func (c *Client) OrganizationList(lr *ListRange) ([]Organization, error) {\n\treq, err := c.NewRequest(\"GET\", \"/organizations\", nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif lr != nil {\n\t\tlr.SetHeader(req)\n\t}\n\n\tvar organizationsRes []Organization\n\treturn organizationsRes, c.DoReq(req, &organizationsRes)\n}", "func (a *api) h_GET_orgs(c *gin.Context) {\n\ta.logger.Debug(\"GET /orgs\")\n\n\taCtx := a.getAuthContext(c)\n\tif aCtx.UserLogin() == \"\" {\n\t\tc.Status(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tods, err := a.Dc.GetOrgDescs(aCtx)\n\tif a.errorResponse(c, err) {\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, a.morgs2orgs(ods))\n}", "func orgShow(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tvars := mux.Vars(r)\n\torg := cleanInput(vars[\"org\"])\n\tdb := co.DbConnection(dbc)\n stmtQryOrg, err := db.Prepare(\"SELECT name FROM organizations where name = ? ;\")\n\tif err != nil {\n\t\tpanic(err.Error()) // proper error handling instead of panic in your app\n\t}\n\tresults, err := stmtQryOrg.Query(org)\n\tif err != nil {\n\t\tpanic(err.Error()) // proper error handling instead of panic in your app\n\t}\n\tvar orgs []string\n\tfor results.Next() {\n\t\tvar name string\n\t\terr = results.Scan(&name)\n\t\tif err != nil {\n\t\t\tpanic(err.Error()) // proper error handling instead of panic in your app\n\t\t}\n\t\torgs = append(orgs, name)\n\t}\n\tresults.Close()\n stmtQryOrg.Close()\n\tdb.Close()\n\torgs = co.Unique(orgs)\n\tjsonPrint(w, orgs)\n return\n}", "func (service *SpaceshipService) GetAllSpaceships() ([]*model.Spaceship, error) {\n\tif service.config.ServiceEnabled() {\n\t\treturn service.repository.GetAllSpaceships()\n\t}\n\n\treturn []*model.Spaceship{}, nil\n}", "func (a *Client) GetAccountByIDSpaces(params *GetAccountByIDSpacesParams, authInfo runtime.ClientAuthInfoWriter) (*GetAccountByIDSpacesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetAccountByIDSpacesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getAccountById_Spaces\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/{baseSpaceId}/accounts/{id}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetAccountByIDSpacesReader{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.(*GetAccountByIDSpacesOK)\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 getAccountById_Spaces: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func GetServedOrgs() {\n\tmsgPrinter := i18n.GetMessagePrinter()\n\t// set env to call agbot url\n\tif err := os.Setenv(\"HORIZON_URL\", cliutils.GetAgbotUrlBase()); err != nil {\n\t\tcliutils.Fatal(cliutils.CLI_GENERAL_ERROR, msgPrinter.Sprintf(\"unable to set env var 'HORIZON_URL', error %v\", err))\n\t}\n\n\t// Get the agbot servedorgs info\n\tservedOrgsInfo := agreementbot.ServedOrgs{} // the structure we will output\n\tcliutils.HorizonGet(\"cache/servedorg\", []int{200}, &servedOrgsInfo, false)\n\n\t// Output the combined info\n\tjsonBytes, err := json.MarshalIndent(servedOrgsInfo, \"\", cliutils.JSON_INDENT)\n\tif err != nil {\n\t\tcliutils.Fatal(cliutils.JSON_PARSING_ERROR, msgPrinter.Sprintf(\"failed to marshal 'hzn node list' output: %v\", err))\n\t}\n\tfmt.Printf(\"%s\\n\", jsonBytes)\n\n}", "func (client *Client) GetOrgs() (map[string]gocf.Org, error) {\n\torgList, err := client.gocfClient.ListOrgsByQuery(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\torgMap := map[string]gocf.Org{}\n\tfor _, org := range orgList {\n\t\torgMap[org.Guid] = org\n\t}\n\n\treturn orgMap, nil\n}", "func (o *Store) Org(mods ...qm.QueryMod) orgQuery {\n\tqueryMods := []qm.QueryMod{\n\t\tqm.Where(\"\\\"id\\\" = ?\", o.OrgID),\n\t}\n\n\tqueryMods = append(queryMods, mods...)\n\n\tquery := Orgs(queryMods...)\n\tqueries.SetFrom(query.Query, \"\\\"orgs\\\"\")\n\n\treturn query\n}", "func (s *Space) GetSpacesByVisitLevel(visitLevel string) (spaces []map[string]string, err error) {\n\n\tdb := G.DB()\n\tvar rs *mysql.ResultSet\n\trs, err = db.Query(\n\t\tdb.AR().From(Table_Space_Name).Where(map[string]interface{}{\n\t\t\t\"visit_level\": visitLevel,\n\t\t\t\"is_delete\": Space_Delete_False,\n\t\t}))\n\tif err != nil {\n\t\treturn\n\t}\n\tspaces = rs.Rows()\n\treturn\n}", "func (db *PSQL) GetOrganization(params params.M) (*models.Organization, error) {\n\treturn nil, nil\n}", "func (cr *cmdRunner) getNamespaces() (storage.ScmNamespaces, error) {\n\tif err := cr.checkNdctl(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tout, err := cr.listNamespaces()\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"list namespaces cmd\")\n\t}\n\n\tnss, err := parseNamespaces(out)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nss, nil\n}", "func (osc *Client) SearchOrganization(ctx context.Context, orgName string, websiteName string, filter string) ([]*models.Organization, error) {\n\tf := logrus.Fields{\n\t\t\"functionName\": \"organization_service.SearchOrganization\",\n\t\tutils.XREQUESTID: ctx.Value(utils.XREQUESTID),\n\t\t\"orgName\": orgName,\n\t\t\"websiteName\": websiteName,\n\t\t\"filter\": filter,\n\t}\n\ttok, err := token.GetToken()\n\tif err != nil {\n\t\tlog.WithFields(f).WithError(err).Warn(\"unable to fetch token\")\n\t\treturn nil, err\n\t}\n\tvar offset int64\n\tvar pageSize int64 = 1000\n\tclientAuth := runtimeClient.BearerToken(tok)\n\tvar orgs []*models.Organization\n\tfor {\n\t\tparams := &organizations.SearchOrgParams{\n\t\t\tName: aws.String(orgName),\n\t\t\tWebsite: aws.StringValueSlice([]*string{&websiteName}),\n\t\t\tDollarFilter: aws.String(filter),\n\t\t\tOffset: aws.String(strconv.FormatInt(offset, 10)),\n\t\t\tPageSize: aws.String(strconv.FormatInt(pageSize, 10)),\n\t\t\tContext: context.TODO(),\n\t\t}\n\t\tresult, err := osc.cl.Organizations.SearchOrg(params, clientAuth)\n\t\tif err != nil {\n\t\t\tlog.WithFields(f).WithError(err).Warnf(\"unable to search organization with params: %+v\", params)\n\t\t\treturn nil, err\n\t\t}\n\t\torgs = append(orgs, result.Payload.Data...)\n\t\tif result.Payload.Metadata.TotalSize > offset+pageSize {\n\t\t\toffset += pageSize\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn orgs, nil\n}", "func (r *spaceRolesManager) getSpaceRolesObjects(ns *corev1.Namespace, spaceRoles []toolchainv1alpha1.NSTemplateSetSpaceRole) ([]runtimeclient.Object, error) {\n\t// store by kind and name\n\tspaceRoleObjects := []runtimeclient.Object{}\n\tfor _, spaceRole := range spaceRoles {\n\t\ttierTemplate, err := getTierTemplate(r.GetHostCluster, spaceRole.TemplateRef)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, username := range spaceRole.Usernames {\n\t\t\tobjs, err := tierTemplate.process(r.Scheme, map[string]string{\n\t\t\t\tNamespace: ns.Name,\n\t\t\t\tUsername: username,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrapf(err, \"failed to process space roles template '%s' for the user '%s' in namespace '%s'\", spaceRole.TemplateRef, username, ns.Name)\n\t\t\t}\n\t\t\tspaceRoleObjects = append(spaceRoleObjects, objs...)\n\t\t}\n\t}\n\treturn spaceRoleObjects, nil\n}", "func ListOrgCustomers(c *gin.Context) {\n\tdb := c.MustGet(\"db\").(*mgo.Database)\n\tvar customers []models.Customer\n\tquery := bson.M{\n\t\t\"organizationId\": bson.ObjectIdHex(c.Param(\"_id\")),\n\t}\n\terr := db.C(models.CollectionCustomer).Find(query).All(&customers)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\"status\": 500,\n\t\t\t\"msg\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"status\": 200,\n\t\t\"msg\": \"Success\",\n\t\t\"data\": customers,\n\t})\n}", "func (m *OrganizationManager) List(opts ...RequestOption) (o *OrganizationList, err error) {\n\terr = m.Request(\"GET\", m.URI(\"organizations\"), &o, applyListDefaults(opts))\n\treturn\n}", "func (a *Client) GetOrganizations(params *GetOrganizationsParams) (*GetOrganizationsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetOrganizationsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getOrganizations\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/v1/organizations\",\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: &GetOrganizationsReader{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\treturn result.(*GetOrganizationsOK), nil\n\n}", "func (c *SpaceClient) GetIncludeOrganization(ctx context.Context, guid string) (*resource.Space, *resource.Organization, error) {\n\tvar space resource.SpaceWithIncluded\n\terr := c.client.get(ctx, path.Format(\"/v3/spaces/%s?include=%s\", guid, resource.SpaceIncludeOrganization), &space)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn &space.Space, space.Included.Organizations[0], nil\n}", "func (a *OrganizationsApiService) GetOrganizations(ctx _context.Context) ApiGetOrganizationsRequest {\n\treturn ApiGetOrganizationsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (p *Plan) GetSpace() int {\n\tif p == nil || p.Space == nil {\n\t\treturn 0\n\t}\n\treturn *p.Space\n}", "func (c *Campaigner) OrganizationList(limit int, offset int) (response ResponseOrganizationList, err error) {\n\t// Setup.\n\tqs := url.Values{}\n\tqs.Set(\"limit\", strconv.Itoa(limit))\n\tqs.Set(\"offset\", strconv.Itoa(offset))\n\tu := url.URL{Path: \"/api/3/organizations\", RawQuery: qs.Encode()}\n\n\t// GET request.\n\tr, body, err := c.get(u.String())\n\tif err != nil {\n\t\treturn response, fmt.Errorf(\"organization list failed, HTTP failure: %s\", err)\n\t}\n\n\t// Success.\n\t// TODO(doc-mismatch): 200 != 201\n\tif r.StatusCode == http.StatusOK {\n\t\terr = json.Unmarshal(body, &response)\n\t\tif err != nil {\n\t\t\treturn response, fmt.Errorf(\"organization list failed, JSON failure: %s\", err)\n\t\t}\n\n\t\treturn response, nil\n\t}\n\n\t// Failure (API docs are not clear about errors here).\n\treturn response, fmt.Errorf(\"organization list failed, unspecified error (%d): %s\", r.StatusCode, string(body))\n}", "func (api *API) GetOrgStats() (OrgStats, error) {\n\t// Return cache while valid\n\tif api.cache.statsExpiry.After(time.Now()) && api.cache.statsData != nil {\n\t\treturn *api.cache.statsData, nil\n\t}\n\n\t// Generate new stats\n\tctx := context.Background()\n\trepos, _, err := api.Repositories.ListByOrg(ctx, api.organization, nil)\n\tif err != nil {\n\t\treturn OrgStats{}, err\n\t}\n\n\t// Collect stats from repositories\n\tstats := OrgStats{\n\t\tTopics: make(map[string]int),\n\t\tLanguages: make(map[string]int),\n\t\tCommitGraph: make(map[time.Time]int),\n\t}\n\tfor _, r := range repos {\n\t\t// Collect basic repository stats\n\t\tstats.Repositories++\n\t\tstats.Stargazers += r.GetStargazersCount()\n\t\tstats.Languages[r.GetLanguage()]++\n\t\tfor _, t := range r.Topics {\n\t\t\tstats.Topics[t]++\n\t\t}\n\n\t\t// Collect activity stats\n\t\tactivity, _, err := api.Repositories.ListCommitActivity(ctx, api.organization, r.GetName())\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, week := range activity {\n\t\t\tstats.CommitGraph[week.GetWeek().Time] += week.GetTotal()\n\t\t}\n\t}\n\n\t// Store in cache\n\tapi.cache.statsExpiry = time.Now().Add(api.cache.validDuration)\n\tapi.cache.statsData = &stats\n\treturn stats, nil\n}", "func listOrganizations(client *chef.Client) map[string]string {\n\torgList, err := client.Organizations.List()\n\tif err != nil {\n\t\tfmt.Println(\"Issue listing orgs:\", err)\n\t}\n\treturn orgList\n}", "func Get(ctx context.Context) ([]*gmodel.Organization, error) {\n\tc, _ := middleware.GinContextFromContext(ctx)\n\tclaims := middleware.GetClaims(ctx)\n\n\tuser := new(model.User)\n\tif found := user.FindByID(claims.UserID); found == false {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t\treturn nil, errors.New(\"user not found\")\n\t}\n\n\tquery := new(model.MultipleOrganizations)\n\torganizations := query.GetByUser(user)\n\n\tvar resp []*gmodel.Organization\n\tfor _, org := range organizations {\n\t\tresp = append(resp, org.Convert2GraphModel())\n\t}\n\treturn resp, nil\n}", "func (s *OrganizationsService) ListOrganizations(queryParams *ListOrganizationsQueryParams) (*Organizations, *resty.Response, error) {\n\n\tpath := \"/organizations/\"\n\n\tqueryParamsString, _ := query.Values(queryParams)\n\n\tresponse, err := s.client.R().\n\t\tSetQueryString(queryParamsString.Encode()).\n\t\tSetResult(&Organizations{}).\n\t\tSetError(&Error{}).\n\t\tGet(path)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresult := response.Result().(*Organizations)\n\tif queryParams.Paginate {\n\t\titems := s.organizationsPagination(response.Header().Get(\"Link\"), 0, 0)\n\t\tfor _, organization := range items.Items {\n\t\t\tresult.AddOrganization(organization)\n\t\t}\n\t} else {\n\t\tif len(result.Items) < queryParams.Max {\n\t\t\titems := s.organizationsPagination(response.Header().Get(\"Link\"), len(result.Items), queryParams.Max)\n\t\t\tfor _, organization := range items.Items {\n\t\t\t\tresult.AddOrganization(organization)\n\t\t\t}\n\t\t}\n\t}\n\treturn result, response, err\n\n}", "func (s *Space) GetSpaceBySpaceId(spaceId string) (space map[string]string, err error) {\n\tdb := G.DB()\n\tvar rs *mysql.ResultSet\n\trs, err = db.Query(db.AR().From(Table_Space_Name).Where(map[string]interface{}{\n\t\t\"space_id\": spaceId,\n\t\t\"is_delete\": Space_Delete_False,\n\t}))\n\tif err != nil {\n\t\treturn\n\t}\n\tspace = rs.Row()\n\treturn\n}", "func (m *Client) GetOrganizations(arg0 context.Context, arg1 *zendesk.OrganizationListOptions) ([]zendesk.Organization, zendesk.Page, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetOrganizations\", arg0, arg1)\n\tret0, _ := ret[0].([]zendesk.Organization)\n\tret1, _ := ret[1].(zendesk.Page)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (o AppProjectSpecSyncWindowsOutput) Namespaces() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v AppProjectSpecSyncWindows) []string { return v.Namespaces }).(pulumi.StringArrayOutput)\n}", "func GetAllOrganization() ([]Organization, error) {\n\torgs := []Organization{}\n\terr := DB.Find(orgs).Error\n\tif err != nil {\n\t\tlog.Printf(\"Get all orgs error: %v\\n\", err)\n\t\treturn nil, err\n\t}\n\treturn orgs, 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 (c *Client) Namespaces() (models.NamespaceList, error) {\n\tresp := models.NamespaceList{}\n\n\tdata, err := c.get(api.Routes.Path(\"Namespaces\"))\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\tif err := json.Unmarshal(data, &resp); err != nil {\n\t\treturn resp, err\n\t}\n\n\treturn resp, nil\n}", "func (m *Client) GetOrganizationFields(arg0 context.Context) ([]zendesk.OrganizationField, zendesk.Page, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetOrganizationFields\", arg0)\n\tret0, _ := ret[0].([]zendesk.OrganizationField)\n\tret1, _ := ret[1].(zendesk.Page)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (s *Space) List(ctx context.Context) ([]string, error) {\n\tlock := s.SpaceManager.Lock.Get(s.Name())\n\tif !lock.RLock(s.SpaceManager.LockTimeout) {\n\t\treturn nil, ErrorLocking.Format(\"space\", s.Name())\n\t}\n\tdefer lock.RUnlock()\n\treturn list(ctx, s.SpaceManager.Backend, s.Prefix, validateName, sortNames)\n}", "func (i *IdentityProvider) GetOrganizations(uuid string, date time.Time) ([]string, error) {\n\tquery := fmt.Sprintf(`select distinct o.name \n\t\tfrom enrollments e, organizations o\n\t\twhere e.organization_id = o.id and\n\t\te.uuid = '%s' and\n '%s' between e.start and e.end order by e.id desc`,\n\t\tuuid, date.Format(time.RFC3339))\n\n\tvar multiOrg []string\n\terr := i.db.Select(&multiOrg, query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn multiOrg, nil\n}", "func GetAllOrgEndpoint(w http.ResponseWriter, r *http.Request) {\n\n\tvar orgs []models.Organization\n\torgs = db.GetAllOrg()\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(orgs)\n\n}", "func (c *ProjectsService) GetByOrg(orgUsername string) ([]Project, *Response, error) {\n\turlStr := fmt.Sprintf(\"orgs/%s/projects\", orgUsername)\n\n\treq, err := c.client.NewRequest(http.MethodGet, urlStr, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tv := new([]Project)\n\n\tresp, err := c.client.Do(req, v)\n\n\treturn *v, resp, err\n}", "func (c *Context) Organization() string { return c.orgName }", "func (o *Organizations) Get(ctx context.Context, query chronograf.OrganizationQuery) (*chronograf.Organization, error) {\n\torg, _, err := o.findOrg(query)\n\treturn org, err\n}", "func (c *cfService) SpaceQuotas() SpaceQuotas {\n\treturn newSpaceQuotasAPI(c.Client)\n}", "func NewListSpacesCommand(p *config.KfParams, client spaces.Client) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"spaces\",\n\t\tShort: \"List all kf spaces\",\n\t\tArgs: cobra.ExactArgs(0),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tcmd.SilenceUsage = true\n\n\t\t\tlist, err := client.List()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tw := tabwriter.NewWriter(cmd.OutOrStdout(), 8, 4, 1, ' ', tabwriter.StripEscape)\n\t\t\tdefer w.Flush()\n\n\t\t\t// Status is important here as spaces may be in a deleting status.\n\t\t\tfmt.Fprintln(w, \"Name\\tAge\\tReady\\tReason\")\n\t\t\tfor _, space := range list {\n\t\t\t\tready := \"\"\n\t\t\t\treason := \"\"\n\t\t\t\tif cond := space.Status.GetCondition(v1alpha1.SpaceConditionReady); cond != nil {\n\t\t\t\t\tready = fmt.Sprintf(\"%v\", cond.Status)\n\t\t\t\t\treason = cond.Reason\n\t\t\t\t}\n\n\t\t\t\tfmt.Fprintf(w, \"%s\\t%s\\t%s\\t%s\",\n\t\t\t\t\tspace.Name,\n\t\t\t\t\ttable.ConvertToHumanReadableDateType(space.CreationTimestamp),\n\t\t\t\t\tready,\n\t\t\t\t\treason,\n\t\t\t\t)\n\t\t\t\tfmt.Fprintln(w)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn cmd\n}", "func (os *OrganizationsService) List(opt *OrganizationListOptions) ([]Organization, *Response, error) {\n\tvar u string\n\n\tu = fmt.Sprintf(\"v2/organizations\")\n\n\tu, err := addOptions(u, opt)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := os.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\torgs := new([]Organization)\n\tresp, err := os.client.Do(req, orgs)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn *orgs, resp, err\n}", "func NewJSONGetOptionSpace(val string) JSONGetOption { return &getOptionSpace{val} }", "func (c *Client) ListMyOrgs() ([]*api.Org, error) {\n\tout := []*api.Org{}\n\trawURL := fmt.Sprintf(pathOrgs, c.base.String())\n\terr := c.get(rawURL, true, &out)\n\treturn out, errio.Error(err)\n}", "func (s *AccountService) ListMyOrganizations() ([]*schema.Organization, error) {\n\t// TODO: fix this\n\t// members, err := s.ListMyMemberships()\n\t// if err != nil {\n\t// \treturn nil, err\n\t// }\n\t//\n\t// orgIds := []bson.ObjectId{}\n\t// for _, member := range members {\n\t// \torgIds = append(orgIds, member.OrganizationID)\n\t// }\n\t//\n\t// orgs, err := models.Organization.FindAllIds(orgIds)\n\t// if err != nil {\n\t// \treturn nil, err\n\t// }\n\t//\n\t// return orgs, nil\n\treturn nil, nil\n}", "func ListOrganizations() error {\n\tclient, err := NewPacketClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\torgs, _, err := client.Organizations.List()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te := MarshallAndPrint(orgs)\n\treturn e\n}" ]
[ "0.836347", "0.8151213", "0.7077322", "0.70715684", "0.70504296", "0.65691507", "0.63065076", "0.6275161", "0.6266745", "0.62511164", "0.59974486", "0.5982455", "0.5811778", "0.5715128", "0.5714711", "0.5702683", "0.56988907", "0.5671041", "0.56710315", "0.56426775", "0.5638392", "0.5627489", "0.56192017", "0.5597227", "0.55801105", "0.5571028", "0.5564911", "0.5556243", "0.55459744", "0.5544364", "0.552486", "0.552346", "0.55216527", "0.55189216", "0.5498252", "0.5493917", "0.54586047", "0.54497963", "0.54470754", "0.54160404", "0.5407576", "0.5389682", "0.53701794", "0.5356403", "0.53437847", "0.52981895", "0.52971447", "0.52913725", "0.5279992", "0.5269797", "0.5267765", "0.5265789", "0.5238405", "0.52273506", "0.52031964", "0.5183678", "0.516558", "0.5150278", "0.5123287", "0.51161605", "0.50424176", "0.50403947", "0.50305516", "0.5020081", "0.49930194", "0.4992149", "0.49832597", "0.498222", "0.49685547", "0.4959021", "0.49585563", "0.49569783", "0.4954792", "0.49547422", "0.49479088", "0.49379823", "0.49375898", "0.49258563", "0.4924884", "0.49176234", "0.49137643", "0.49070022", "0.48923936", "0.4873764", "0.48685643", "0.48554096", "0.4853197", "0.4845679", "0.48382837", "0.4837976", "0.48295024", "0.48245543", "0.48167536", "0.4811426", "0.48059195", "0.4795425", "0.47952247", "0.47914207", "0.47883278", "0.4785356" ]
0.83006597
1
GetSpaceByOrganizationAndName returns an Space based on the org and name.
func (actor Actor) GetSpaceByOrganizationAndName(orgGUID string, spaceName string) (Space, Warnings, error) { ccv2Spaces, warnings, err := actor.CloudControllerClient.GetSpaces( ccv2.Query{ Filter: ccv2.NameFilter, Operator: ccv2.EqualOperator, Values: []string{spaceName}, }, ccv2.Query{ Filter: ccv2.OrganizationGUIDFilter, Operator: ccv2.EqualOperator, Values: []string{orgGUID}, }, ) if err != nil { return Space{}, Warnings(warnings), err } if len(ccv2Spaces) == 0 { return Space{}, Warnings(warnings), SpaceNotFoundError{Name: spaceName} } if len(ccv2Spaces) > 1 { return Space{}, Warnings(warnings), MultipleSpacesFoundError{OrgGUID: orgGUID, Name: spaceName} } return Space(ccv2Spaces[0]), Warnings(warnings), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (actor Actor) GetSpaceByOrganizationAndName(orgGUID string, spaceName string) (Space, Warnings, error) {\n\tquery := []ccv2.Query{\n\t\t{\n\t\t\tFilter: ccv2.NameFilter,\n\t\t\tOperator: ccv2.EqualOperator,\n\t\t\tValue: spaceName,\n\t\t},\n\t\t{\n\t\t\tFilter: ccv2.OrganizationGUIDFilter,\n\t\t\tOperator: ccv2.EqualOperator,\n\t\t\tValue: orgGUID,\n\t\t},\n\t}\n\n\tccv2Spaces, warnings, err := actor.CloudControllerClient.GetSpaces(query)\n\tif err != nil {\n\t\treturn Space{}, Warnings(warnings), err\n\t}\n\n\tif len(ccv2Spaces) == 0 {\n\t\treturn Space{}, Warnings(warnings), SpaceNotFoundError{Name: spaceName}\n\t}\n\n\tif len(ccv2Spaces) > 1 {\n\t\treturn Space{}, Warnings(warnings), MultipleSpacesFoundError{OrgGUID: orgGUID, Name: spaceName}\n\t}\n\n\treturn Space{\n\t\tGUID: ccv2Spaces[0].GUID,\n\t\tName: ccv2Spaces[0].Name,\n\t\tAllowSSH: ccv2Spaces[0].AllowSSH,\n\t}, Warnings(warnings), nil\n}", "func (s *Space) GetSpaceByName(name string) (space map[string]string, err error) {\n\tdb := G.DB()\n\tvar rs *mysql.ResultSet\n\trs, err = db.Query(db.AR().From(Table_Space_Name).Where(map[string]interface{}{\n\t\t\"name\": name,\n\t\t\"is_delete\": Space_Delete_False,\n\t}).Limit(0, 1))\n\tif err != nil {\n\t\treturn\n\t}\n\tspace = rs.Row()\n\treturn\n}", "func (am *ArtifactMap) GetSpaceByName(spaceName string) (*elasticstructs.Space, error) {\n\tvalue, found := am.spaceTitleToID.Load(spaceName)\n\tif !found {\n\t\treturn nil, SpaceNameNotFoundError(spaceName)\n\t}\n\n\tretVal, ok := value.(elasticstructs.Space)\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"space<%s>\", spaceName)\n\t}\n\n\treturn &retVal, nil\n}", "func (actor Actor) GetOrganizationSpacesWithLabelSelector(orgGUID string, labelSelector string) ([]resources.Space, Warnings, error) {\n\n\tqueries := []ccv3.Query{\n\t\tccv3.Query{Key: ccv3.OrganizationGUIDFilter, Values: []string{orgGUID}},\n\t\tccv3.Query{Key: ccv3.OrderBy, Values: []string{ccv3.NameOrder}},\n\t}\n\tif len(labelSelector) > 0 {\n\t\tqueries = append(queries, ccv3.Query{Key: ccv3.LabelSelectorFilter, Values: []string{labelSelector}})\n\t}\n\n\tccv3Spaces, _, warnings, err := actor.CloudControllerClient.GetSpaces(queries...)\n\tif err != nil {\n\t\treturn []resources.Space{}, Warnings(warnings), err\n\t}\n\n\tspaces := make([]resources.Space, len(ccv3Spaces))\n\tfor i, ccv3Space := range ccv3Spaces {\n\t\tspaces[i] = resources.Space(ccv3Space)\n\t}\n\n\treturn spaces, Warnings(warnings), nil\n}", "func (actor Actor) GetOrganizationSpaces(orgGUID string) ([]Space, Warnings, error) {\n\tquery := []ccv2.Query{\n\t\t{\n\t\t\tFilter: ccv2.OrganizationGUIDFilter,\n\t\t\tOperator: ccv2.EqualOperator,\n\t\t\tValue: orgGUID,\n\t\t}}\n\tccv2Spaces, warnings, err := actor.CloudControllerClient.GetSpaces(query)\n\tif err != nil {\n\t\treturn []Space{}, Warnings(warnings), err\n\t}\n\n\tvar spaces []Space\n\n\tfor _, ccv2Space := range ccv2Spaces {\n\t\tspaces = append(spaces, Space{\n\t\t\tGUID: ccv2Space.GUID,\n\t\t\tName: ccv2Space.Name,\n\t\t\tAllowSSH: ccv2Space.AllowSSH,\n\t\t})\n\t}\n\n\treturn spaces, Warnings(warnings), nil\n}", "func (actor Actor) GetOrganizationSpaces(orgGUID string) ([]Space, Warnings, error) {\n\tccv2Spaces, warnings, err := actor.CloudControllerClient.GetSpaces(ccv2.Query{\n\t\tFilter: ccv2.OrganizationGUIDFilter,\n\t\tOperator: ccv2.EqualOperator,\n\t\tValues: []string{orgGUID},\n\t})\n\tif err != nil {\n\t\treturn []Space{}, Warnings(warnings), err\n\t}\n\n\tspaces := make([]Space, len(ccv2Spaces))\n\tfor i, ccv2Space := range ccv2Spaces {\n\t\tspaces[i] = Space(ccv2Space)\n\t}\n\n\treturn spaces, Warnings(warnings), nil\n}", "func (s *Space) GetSpaceByLikeName(name string) (spaces []map[string]string, err error) {\n\tdb := G.DB()\n\tvar rs *mysql.ResultSet\n\trs, err = db.Query(db.AR().From(Table_Space_Name).Where(map[string]interface{}{\n\t\t\"name Like\": \"%\" + name + \"%\",\n\t\t\"is_delete\": Space_Delete_False,\n\t}).Limit(0, 1))\n\tif err != nil {\n\t\treturn\n\t}\n\tspaces = rs.Rows()\n\treturn\n}", "func (c *SpaceClient) Get(ctx context.Context, guid string) (*resource.Space, error) {\n\tvar space resource.Space\n\terr := c.client.get(ctx, path.Format(\"/v3/spaces/%s\", guid), &space)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &space, nil\n}", "func (sm *SpaceManager) Space(ctx context.Context, space string) (storage.Space, error) {\n\tif !validateName(space) {\n\t\treturn nil, ErrorInvalidParam.Format(\"space\", space)\n\t}\n\treturn NewSpace(sm, space)\n}", "func (s *Space) GetSpaceBySpaceId(spaceId string) (space map[string]string, err error) {\n\tdb := G.DB()\n\tvar rs *mysql.ResultSet\n\trs, err = db.Query(db.AR().From(Table_Space_Name).Where(map[string]interface{}{\n\t\t\"space_id\": spaceId,\n\t\t\"is_delete\": Space_Delete_False,\n\t}))\n\tif err != nil {\n\t\treturn\n\t}\n\tspace = rs.Row()\n\treturn\n}", "func (actor Actor) GetOrganizationSpaces(orgGUID string) ([]resources.Space, Warnings, error) {\n\treturn actor.GetOrganizationSpacesWithLabelSelector(orgGUID, \"\")\n}", "func (p *Provider) CreateSpace(name string, projectID int, clusterID *int) (int, error) {\n\t// Response struct\n\tresponse := struct {\n\t\tCreateSpace *struct {\n\t\t\tSpaceID int\n\t\t} `json:\"manager_createSpace\"`\n\t}{}\n\n\t// Do the request\n\terr := p.GrapqhlRequest(`\n\t\tmutation($spaceName: String!, $clusterID: Int, $projectID: Int!) {\n\t\t\tmanager_createSpace(spaceName: $spaceName, clusterID: $clusterID, projectID: $projectID) {\n\t\t\t\tSpaceID\n\t\t\t}\n\t\t}\n\t`, map[string]interface{}{\n\t\t\"spaceName\": name,\n\t\t\"projectID\": projectID,\n\t\t\"clusterID\": clusterID,\n\t}, &response)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// Check result\n\tif response.CreateSpace == nil {\n\t\treturn 0, errors.New(\"Couldn't create project: returned answer is null\")\n\t}\n\n\treturn response.CreateSpace.SpaceID, nil\n}", "func (z *Zone) GetSpaceName(guid string) string {\n\tz.muSpaces.RLock()\n\tdefer z.muSpaces.RUnlock()\n\n\tif name, ok := z.spaces[guid]; ok {\n\t\treturn name\n\t}\n\n\treturn guid\n}", "func (r *SpacesService) Get(name string) *SpacesGetCall {\n\tc := &SpacesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func NewSpace() *Space {\n\tsp := &Space{}\n\treturn sp\n}", "func (s *Store) GetOrganization(ctx context.Context, name string) (organization *Organization, err error) {\n\tif name, err = CheckName(name); err != nil {\n\t\treturn nil, err\n\t}\n\torganization = &Organization{}\n\tif err := s.store.Get(ctx, path.Join(organizationsRootKey, name), organization, true); err != nil {\n\t\treturn nil, err\n\t}\n\t// If there's no \"name\" in the answer, it means the organization has not been found, so return nil\n\tif organization.GetName() == \"\" {\n\t\treturn nil, nil\n\t}\n\treturn organization, nil\n}", "func NewSpace(spaceManager *SpaceManager, space string) (*Space, error) {\n\tif spaceManager == nil {\n\t\treturn nil, ErrorNoParameter.Format(\"spaceManager\")\n\t}\n\tif !validateName(space) {\n\t\treturn nil, ErrorInvalidParam.Format(\"space\", space)\n\t}\n\treturn &Space{spaceManager, path.Join(spaceManager.Prefix, space), space}, nil\n}", "func (a *SpaceApiService) SearchSpaces(ctx _context.Context, localVarOptionals *SearchSpacesOpts) ([]Space, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []Space\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/spaces/search\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif localVarOptionals != nil && localVarOptionals.Fields.IsSet() {\n\t\tlocalVarQueryParams.Add(\"fields\", parameterToString(localVarOptionals.Fields.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Page.IsSet() {\n\t\tlocalVarQueryParams.Add(\"page\", parameterToString(localVarOptionals.Page.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.PerPage.IsSet() {\n\t\tlocalVarQueryParams.Add(\"per_page\", parameterToString(localVarOptionals.PerPage.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Limit.IsSet() {\n\t\tlocalVarQueryParams.Add(\"limit\", parameterToString(localVarOptionals.Limit.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Offset.IsSet() {\n\t\tlocalVarQueryParams.Add(\"offset\", parameterToString(localVarOptionals.Offset.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Sorts.IsSet() {\n\t\tlocalVarQueryParams.Add(\"sorts\", parameterToString(localVarOptionals.Sorts.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Name.IsSet() {\n\t\tlocalVarQueryParams.Add(\"name\", parameterToString(localVarOptionals.Name.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Id.IsSet() {\n\t\tlocalVarQueryParams.Add(\"id\", parameterToString(localVarOptionals.Id.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.ParentId.IsSet() {\n\t\tlocalVarQueryParams.Add(\"parent_id\", parameterToString(localVarOptionals.ParentId.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.CreatorId.IsSet() {\n\t\tlocalVarQueryParams.Add(\"creator_id\", parameterToString(localVarOptionals.CreatorId.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.FilterOr.IsSet() {\n\t\tlocalVarQueryParams.Add(\"filter_or\", parameterToString(localVarOptionals.FilterOr.Value(), \"\"))\n\t}\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 []Space\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 == 400 {\n\t\t\tvar v Error\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 == 404 {\n\t\t\tvar v Error\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 (s *OrganizationsStore) Get(ctx context.Context, q chronograf.OrganizationQuery) (*chronograf.Organization, error) {\n\tif q.ID != nil {\n\t\treturn s.get(ctx, *q.ID)\n\t}\n\n\tif q.Name != nil {\n\t\tvar org *chronograf.Organization\n\t\terr := s.each(ctx, func(o *chronograf.Organization) {\n\t\t\tif org != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif o.Name == *q.Name {\n\t\t\t\torg = o\n\t\t\t}\n\t\t})\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif org == nil {\n\t\t\treturn nil, chronograf.ErrOrganizationNotFound\n\t\t}\n\n\t\treturn org, nil\n\t}\n\treturn nil, fmt.Errorf(\"must specify either ID, or Name in OrganizationQuery\")\n}", "func (actor Actor) GetApplicationByNameAndSpace(appName string, spaceGUID string) (Application, Warnings, error) {\n\tapps, warnings, err := actor.CloudControllerClient.GetApplications(\n\t\tccv3.Query{Key: ccv3.NameFilter, Values: []string{appName}},\n\t\tccv3.Query{Key: ccv3.SpaceGUIDFilter, Values: []string{spaceGUID}},\n\t)\n\tif err != nil {\n\t\treturn Application{}, Warnings(warnings), err\n\t}\n\n\tif len(apps) == 0 {\n\t\treturn Application{}, Warnings(warnings), actionerror.ApplicationNotFoundError{Name: appName}\n\t}\n\n\treturn actor.convertCCToActorApplication(apps[0]), Warnings(warnings), nil\n}", "func (m *Manager) GetByName(globalID string) (organization *Organization, err error) {\n\terr = m.collection.Find(bson.M{\"globalid\": globalID}).One(&organization)\n\treturn\n}", "func (c *SpaceClient) Create(ctx context.Context, r *resource.SpaceCreate) (*resource.Space, error) {\n\tvar space resource.Space\n\t_, err := c.client.post(ctx, \"/v3/spaces\", r, &space)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &space, nil\n}", "func (s *Space) GetSpacesByKeywordAndLimit(keyword string, limit int, number int) (spaces []map[string]string, err error) {\n\n\tdb := G.DB()\n\tvar rs *mysql.ResultSet\n\tsql := db.AR().From(Table_Space_Name).Where(map[string]interface{}{\n\t\t\"is_delete\": Space_Delete_False,\n\t}).WhereWrap(map[string]interface{}{\n\t\t\"name LIKE\": \"%\" + keyword + \"%\",\n\t}, \"AND (\", \"\").WhereWrap(map[string]interface{}{\n\t\t\"description LIKE\": \"%\" + keyword + \"%\",\n\t}, \"OR\", \")\").Limit(limit, number).OrderBy(\"space_id\", \"DESC\")\n\trs, err = db.Query(sql)\n\n\tif err != nil {\n\t\treturn\n\t}\n\tspaces = rs.Rows()\n\n\treturn\n}", "func (a *SpaceApiService) Space(ctx _context.Context, spaceId string, localVarOptionals *SpaceOpts) (Space, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Space\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/spaces/{space_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"space_id\"+\"}\", _neturl.QueryEscape(parameterToString(spaceId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif localVarOptionals != nil && localVarOptionals.Fields.IsSet() {\n\t\tlocalVarQueryParams.Add(\"fields\", parameterToString(localVarOptionals.Fields.Value(), \"\"))\n\t}\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 Space\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 == 400 {\n\t\t\tvar v Error\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 == 404 {\n\t\t\tvar v Error\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 (actor Actor) GetDomainsByNameAndOrganization(domainNames []string, orgGUID string) ([]Domain, Warnings, error) {\n\tif len(domainNames) == 0 {\n\t\treturn nil, nil, nil\n\t}\n\n\tvar domains []Domain\n\tvar allWarnings Warnings\n\n\t// TODO: If the following causes URI length problems, break domainNames into\n\t// batched (based on character length?) and loop over them.\n\n\tsharedDomains, warnings, err := actor.CloudControllerClient.GetSharedDomains(ccv2.Filter{\n\t\tType: constant.NameFilter,\n\t\tOperator: constant.InOperator,\n\t\tValues: domainNames,\n\t})\n\tallWarnings = append(allWarnings, warnings...)\n\tif err != nil {\n\t\treturn nil, allWarnings, err\n\t}\n\n\tfor _, domain := range sharedDomains {\n\t\tdomains = append(domains, Domain(domain))\n\t\tactor.saveDomain(domain)\n\t}\n\n\tprivateDomains, warnings, err := actor.CloudControllerClient.GetOrganizationPrivateDomains(\n\t\torgGUID,\n\t\tccv2.Filter{\n\t\t\tType: constant.NameFilter,\n\t\t\tOperator: constant.InOperator,\n\t\t\tValues: domainNames,\n\t\t})\n\tallWarnings = append(allWarnings, warnings...)\n\tif err != nil {\n\t\treturn nil, allWarnings, err\n\t}\n\n\tfor _, domain := range privateDomains {\n\t\tdomains = append(domains, Domain(domain))\n\t\tactor.saveDomain(domain)\n\t}\n\n\treturn domains, allWarnings, err\n}", "func (client *Client) GetSpaces(query ...Query) ([]resources.Space, IncludedResources, Warnings, error) {\n\tvar returnedResources []resources.Space\n\n\tincludedResources, warnings, err := client.MakeListRequest(RequestParams{\n\t\tRequestName: internal.GetSpacesRequest,\n\t\tQuery: query,\n\t\tResponseBody: resources.Space{},\n\t\tAppendToList: func(item interface{}) error {\n\t\t\treturnedResources = append(returnedResources, item.(resources.Space))\n\t\t\treturn nil\n\t\t},\n\t})\n\n\treturn returnedResources, includedResources, warnings, err\n}", "func GetOrgByOrgnameEndpoint(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tname := params[\"name\"]\n\n\tvar org models.Organization\n\t_ = json.NewDecoder(r.Body).Decode(&org)\n\n\torg = db.GetOrgByName(name)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(org)\n\n}", "func (a *SpaceApiService) CreateSpace(ctx _context.Context, body CreateSpace) (Space, *_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 Space\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/spaces\"\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\"}\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\t// body params\n\tlocalVarPostBody = &body\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 Space\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 == 400 {\n\t\t\tvar v Error\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 == 404 {\n\t\t\tvar v Error\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 == 409 {\n\t\t\tvar v Error\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 == 422 {\n\t\t\tvar v ValidationError\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 (client *Client) GetSpaces(query ...Query) ([]Space, IncludedResources, Warnings, error) {\n\tvar resources []Space\n\n\tincludedResources, warnings, err := client.MakeListRequest(RequestParams{\n\t\tRequestName: internal.GetSpacesRequest,\n\t\tQuery: query,\n\t\tResponseBody: Space{},\n\t\tAppendToList: func(item interface{}) error {\n\t\t\tresources = append(resources, item.(Space))\n\t\t\treturn nil\n\t\t},\n\t})\n\n\treturn resources, includedResources, warnings, err\n}", "func (am *ArtifactMap) GetSpaceByID(spaceID string) (*elasticstructs.Space, error) {\n\tvar space *elasticstructs.Space\n\tam.spaceTitleToID.Range(func(key, value interface{}) bool {\n\t\tif sp, ok := value.(elasticstructs.Space); ok && sp.ID == spaceID {\n\t\t\tspace = &sp\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n\n\tif space != nil {\n\t\treturn space, nil\n\t}\n\n\treturn nil, SpaceIdNotFoundError(spaceID)\n}", "func (t TimeUnit) Space(s SpaceUnit, dimension int8) MetricUnit {\n\treturn (&metricUnit{uint32(t)}).Space(s, dimension)\n}", "func NewSpace(t *testing.T, awaitilities wait.Awaitilities, opts ...SpaceOption) *toolchainv1alpha1.Space {\n\tnamePrefix := strings.ToLower(t.Name())\n\t// Remove all invalid characters\n\tnamePrefix = notAllowedChars.ReplaceAllString(namePrefix, \"\")\n\n\t// Trim if the length exceeds 40 chars (63 is the max)\n\tif len(namePrefix) > 40 {\n\t\tnamePrefix = namePrefix[0:40]\n\t}\n\n\tspace := &toolchainv1alpha1.Space{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: awaitilities.Host().Namespace,\n\t\t\tGenerateName: namePrefix + \"-\",\n\t\t},\n\t}\n\tfor _, apply := range opts {\n\t\tapply(space)\n\t}\n\treturn space\n}", "func (client *Client) GetSpaces() (map[string]gocf.Space, error) {\n\tspaceList, err := client.gocfClient.ListSpacesByQuery(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tspaceMap := map[string]gocf.Space{}\n\tfor _, space := range spaceList {\n\t\tspaceMap[space.Guid] = space\n\t}\n\n\treturn spaceMap, nil\n}", "func (om *OrgManager) FindByName(name string) (*Organization, error) {\n\torg := &Organization{}\n\tif err := om.DB.Where(\n\t\t\"name = ?\",\n\t\tname,\n\t).First(&org).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn org, nil\n}", "func (s *Space) GetSpaceBySpaceIds(spaceIds []string) (spaces []map[string]string, err error) {\n\tdb := G.DB()\n\tvar rs *mysql.ResultSet\n\trs, err = db.Query(db.AR().From(Table_Space_Name).Where(map[string]interface{}{\n\t\t\"space_id\": spaceIds,\n\t\t\"is_delete\": Space_Delete_False,\n\t}))\n\tif err != nil {\n\t\treturn\n\t}\n\tspaces = rs.Rows()\n\treturn\n}", "func (r *Resolver) Organization(args struct{ ID string }) *OrganizationResolver {\n\tid, err := strconv.ParseUint(args.ID, 10, 64)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tvar os service.OrganizationService\n\tresult := os.Find(id)\n\to := organization{result}\n\treturn &OrganizationResolver{&o}\n}", "func NewWorkSpace(dir string) (WorkSpace, error) {\n\tif config.IsSingleMode() {\n\t\treturn NewGitWorkSpace(dir)\n\t}\n\treturn NewRepoWorkSpace(dir)\n}", "func getOrganization(orgGroup *cb.ConfigGroup, orgName string) (Organization, error) {\n\tpolicies, err := getPolicies(orgGroup.Policies)\n\tif err != nil {\n\t\treturn Organization{}, err\n\t}\n\n\tmsp, err := getMSPConfig(orgGroup)\n\tif err != nil {\n\t\treturn Organization{}, err\n\t}\n\n\tvar anchorPeers []Address\n\t_, ok := orgGroup.Values[AnchorPeersKey]\n\tif ok {\n\t\tanchorProtos := &pb.AnchorPeers{}\n\t\terr = unmarshalConfigValueAtKey(orgGroup, AnchorPeersKey, anchorProtos)\n\t\tif err != nil {\n\t\t\treturn Organization{}, err\n\t\t}\n\n\t\tfor _, anchorProto := range anchorProtos.AnchorPeers {\n\t\t\tanchorPeers = append(anchorPeers, Address{\n\t\t\t\tHost: anchorProto.Host,\n\t\t\t\tPort: int(anchorProto.Port),\n\t\t\t})\n\t\t}\n\t}\n\n\treturn Organization{\n\t\tName: orgName,\n\t\tPolicies: policies,\n\t\tMSP: msp,\n\t\tAnchorPeers: anchorPeers,\n\t}, nil\n}", "func NewSpace() Space {\n\treturn Space{\n\t\tvspace: euclid.NewSpace(),\n\t}\n}", "func (o *IpamNetworkDataData) GetSpaceName() string {\n\tif o == nil || o.SpaceName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.SpaceName\n}", "func (in *Space) DeepCopy() *Space {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Space)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Space) DeepCopy() *Space {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Space)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Space) DeepCopy() *Space {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Space)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (db *PSQL) GetOrganization(params params.M) (*models.Organization, error) {\n\treturn nil, nil\n}", "func (osc *Client) SearchOrganization(ctx context.Context, orgName string, websiteName string, filter string) ([]*models.Organization, error) {\n\tf := logrus.Fields{\n\t\t\"functionName\": \"organization_service.SearchOrganization\",\n\t\tutils.XREQUESTID: ctx.Value(utils.XREQUESTID),\n\t\t\"orgName\": orgName,\n\t\t\"websiteName\": websiteName,\n\t\t\"filter\": filter,\n\t}\n\ttok, err := token.GetToken()\n\tif err != nil {\n\t\tlog.WithFields(f).WithError(err).Warn(\"unable to fetch token\")\n\t\treturn nil, err\n\t}\n\tvar offset int64\n\tvar pageSize int64 = 1000\n\tclientAuth := runtimeClient.BearerToken(tok)\n\tvar orgs []*models.Organization\n\tfor {\n\t\tparams := &organizations.SearchOrgParams{\n\t\t\tName: aws.String(orgName),\n\t\t\tWebsite: aws.StringValueSlice([]*string{&websiteName}),\n\t\t\tDollarFilter: aws.String(filter),\n\t\t\tOffset: aws.String(strconv.FormatInt(offset, 10)),\n\t\t\tPageSize: aws.String(strconv.FormatInt(pageSize, 10)),\n\t\t\tContext: context.TODO(),\n\t\t}\n\t\tresult, err := osc.cl.Organizations.SearchOrg(params, clientAuth)\n\t\tif err != nil {\n\t\t\tlog.WithFields(f).WithError(err).Warnf(\"unable to search organization with params: %+v\", params)\n\t\t\treturn nil, err\n\t\t}\n\t\torgs = append(orgs, result.Payload.Data...)\n\t\tif result.Payload.Metadata.TotalSize > offset+pageSize {\n\t\t\toffset += pageSize\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn orgs, nil\n}", "func (s *ProjectService) pickOrganization(\n\torganizationName string,\n\torganizationID *uint,\n) *ProjectService {\n\tif s.err != nil {\n\t\treturn s\n\t}\n\n\torganizations, err := s.cli.Organizations().GetAll()\n\tif err != nil {\n\t\ts.err = err\n\t\treturn s\n\t}\n\n\torga := models.Organization{}\n\n\tif organizationName == \"\" {\n\t\torga = prompts.OrganizationsSelect(organizations)\n\t\t*organizationID = orga.ID\n\t} else {\n\t\tfor _, o := range organizations {\n\t\t\tif organizationName == o.Name {\n\t\t\t\torga = o\n\t\t\t}\n\t\t}\n\n\t\tif orga.ID == 0 {\n\t\t\ts.err = errors.New(\"organization not found\")\n\t\t\treturn s\n\t\t}\n\n\t\t*organizationID = orga.ID\n\t}\n\n\treturn s\n}", "func (c *client) GetOrg(name string) (*Organization, error) {\n\tc.log(\"GetOrg\", name)\n\tvar retOrg Organization\n\t_, err := c.request(&request{\n\t\tmethod: http.MethodGet,\n\t\tpath: fmt.Sprintf(\"/orgs/%s\", name),\n\t\torg: name,\n\t\texitCodes: []int{200},\n\t}, &retOrg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &retOrg, nil\n}", "func GetOrganizationByName(iq IQ, organizationName string) (*Organization, error) {\n\torgs, err := GetAllOrganizations(iq)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"organization '%s' not found: %v\", organizationName, err)\n\t}\n\tfor _, org := range orgs {\n\t\tif org.Name == organizationName {\n\t\t\treturn &org, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"organization '%s' not found\", organizationName)\n}", "func (c *Connection) SpaceInfo(ctx context.Context, id api.SpaceID) (*api.SpaceInfo, error) {\n\tpath := path.Join(\"/space\", url.PathEscape(string(id)))\n\tresp, err := c.Request(ctx).\n\t\tSetResult(&api.SpaceInfo{}).\n\t\tGet(path)\n\tif err != nil {\n\t\tif r, ok := err.(*ErrorResponse); ok && r.StatusCode() == http.StatusNotFound {\n\t\t\treturn nil, ErrSpaceNotFound\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn resp.Result().(*api.SpaceInfo), nil\n}", "func (osc *Client) CreateOrg(ctx context.Context, companyName, signingEntityName, companyWebsite string) (*models.Organization, error) {\n\tf := logrus.Fields{\n\t\t\"functionName\": \"organization_service.CreateOrg\",\n\t\tutils.XREQUESTID: ctx.Value(utils.XREQUESTID),\n\t\t\"companyName\": companyName,\n\t\t\"signingEntityName\": signingEntityName,\n\t\t\"companyWebsite\": companyWebsite,\n\t}\n\n\tvar org *models.Organization\n\n\ttok, tokenErr := token.GetToken()\n\tif tokenErr != nil {\n\t\tlog.WithFields(f).WithError(tokenErr).Warn(\"unable to fetch token\")\n\t\treturn nil, tokenErr\n\t}\n\n\t// If not specified, use the company name as the signing entity name\n\tif signingEntityName == \"\" {\n\t\tsigningEntityName = companyName\n\t}\n\n\t//Lookup Org based on domain\n\tlookupOrg, lookupErr := osc.SearchOrgLookup(ctx, nil, &companyWebsite)\n\tif lookupErr != nil {\n\t\tlog.WithFields(f).WithError(lookupErr).Warn(\"unable to search for existing company using company website value\")\n\t\tif _, ok := lookupErr.(*organizations.LookupNotFound); !ok {\n\t\t\treturn nil, lookupErr\n\t\t}\n\t}\n\n\tif lookupOrg != nil && lookupOrg.Payload.ID != \"\" {\n\t\t// Get org based on ID\n\t\tvar updateErr error\n\t\texistingOrg, existingOrgErr := osc.GetOrganization(ctx, lookupOrg.Payload.ID)\n\t\tif existingOrgErr != nil {\n\t\t\tlog.WithFields(f).WithError(existingOrgErr).Warnf(\"unable to get organization : %s \", lookupOrg.Payload.ID)\n\t\t\treturn nil, existingOrgErr\n\t\t}\n\t\torg, updateErr = osc.UpdateOrg(ctx, existingOrg, signingEntityName)\n\t\tif updateErr != nil {\n\t\t\tlog.WithFields(f).WithError(updateErr).Warn(\"unable to update for existing company\")\n\t\t\treturn nil, updateErr\n\t\t}\n\n\t} else {\n\t\t// use linux foundation logo as default\n\t\tlinuxFoundation, err := osc.SearchOrganization(ctx, utils.TheLinuxFoundation, \"\", \"\")\n\t\tif err != nil || len(linuxFoundation) == 0 {\n\t\t\tlog.WithFields(f).WithError(err).Warn(\"unable to search Linux Foundation organization\")\n\t\t\treturn nil, err\n\t\t}\n\n\t\tclientAuth := runtimeClient.BearerToken(tok)\n\t\tlogoURL := linuxFoundation[0].LogoURL\n\t\tf[\"logoURL\"] = logoURL\n\n\t\tparams := &organizations.CreateOrgParams{\n\t\t\tOrg: &models.CreateOrg{\n\t\t\t\tName: &companyName,\n\t\t\t\tWebsite: &companyWebsite,\n\t\t\t\tLogoURL: logoURL,\n\t\t\t\tSigningEntityName: []string{signingEntityName},\n\t\t\t},\n\t\t\tContext: ctx,\n\t\t}\n\n\t\tlog.WithFields(f).Debugf(\"Creating organization with params: %+v\", models.CreateOrg{\n\t\t\tName: &companyName,\n\t\t\tWebsite: &companyWebsite,\n\t\t\tLogoURL: logoURL,\n\t\t\tSigningEntityName: []string{signingEntityName},\n\t\t})\n\t\tresult, err := osc.cl.Organizations.CreateOrg(params, clientAuth)\n\t\tif err != nil {\n\t\t\tlog.WithFields(f).WithError(err).Warnf(\"Failed to create salesforce Company: %s , err: %+v \", companyName, err)\n\t\t\treturn nil, err\n\t\t}\n\t\tlog.WithFields(f).Infof(\"Company: %s successfuly created \", companyName)\n\n\t\torg = result.Payload\n\t}\n\treturn org, nil\n}", "func (h *AuthHandlers) getOrgByName(ctx context.Context, userContext am.UserContext, orgName string) (*am.Organization, error) {\n\n\t_, org, err := h.orgClient.Get(ctx, userContext, orgName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn org, nil\n}", "func (z *zfsctl) GroupSpace(ctx context.Context, name, options string, fields []string, sField, SField, t string) *execute {\n\targs := []string{\"groupspace\"}\n\tif len(options) > 0 {\n\t\targs = append(args, options)\n\t}\n\tif fields != nil {\n\t\to := \"-o \"\n\t\tfor _, field := range fields {\n\t\t\to += field + \",\"\n\t\t}\n\t\to = strings.TrimSuffix(o, \",\")\n\t\targs = append(args, o)\n\t}\n\tif len(sField) > 0 {\n\t\targs = append(args, \"-s \"+sField)\n\t}\n\tif len(SField) > 0 {\n\t\targs = append(args, \"-S \"+SField)\n\t}\n\tif len(t) > 0 {\n\t\targs = append(args, \"-t \"+t)\n\t}\n\targs = append(args, name)\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func GetOrganization(ctx *pulumi.Context,\n\tname string, id pulumi.ID, state *OrganizationState, opts ...pulumi.ResourceOpt) (*Organization, error) {\n\tinputs := make(map[string]interface{})\n\tif state != nil {\n\t\tinputs[\"adminUser\"] = state.AdminUser\n\t\tinputs[\"admins\"] = state.Admins\n\t\tinputs[\"createUsers\"] = state.CreateUsers\n\t\tinputs[\"editors\"] = state.Editors\n\t\tinputs[\"name\"] = state.Name\n\t\tinputs[\"orgId\"] = state.OrgId\n\t\tinputs[\"viewers\"] = state.Viewers\n\t}\n\ts, err := ctx.ReadResource(\"grafana:index/organization:Organization\", name, id, inputs, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Organization{s: s}, nil\n}", "func (o *DeleteRequestsRequestNameParams) WithOrganization(organization string) *DeleteRequestsRequestNameParams {\n\to.SetOrganization(organization)\n\treturn o\n}", "func NewSpace() *cp.Space {\n\tspace := cp.NewSpace()\n\t// rules:\n\tspace.SetDamping(constants.Damping)\n\tspace.SetGravity(cp.Vector{0, 0}) // no gravity\n\treturn space\n}", "func (s *Space) UpdateSpaceByName(space map[string]interface{}) (affect int64, err error) {\n\tdb := G.DB()\n\tvar rs *mysql.ResultSet\n\tspace[\"update_time\"] = time.Now().Unix()\n\trs, err = db.Exec(db.AR().Update(Table_Space_Name, space, map[string]interface{}{\n\t\t\"name\": space[\"name\"],\n\t}))\n\tif err != nil {\n\t\treturn\n\t}\n\taffect = rs.RowsAffected\n\treturn\n}", "func (s *OrganizationsStore) Get(ctx context.Context, q chronograf.OrganizationQuery) (*chronograf.Organization, error) {\n\terr := validOrganization(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td, err := s.store.Get(ctx, q)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif d.ID != s.organization {\n\t\treturn nil, chronograf.ErrOrganizationNotFound\n\t}\n\n\treturn d, nil\n}", "func (o *Organizations) Get(ctx context.Context, query chronograf.OrganizationQuery) (*chronograf.Organization, error) {\n\torg, _, err := o.findOrg(query)\n\treturn org, err\n}", "func (s *DescribeAppOutput) SetSpaceName(v string) *DescribeAppOutput {\n\ts.SpaceName = &v\n\treturn s\n}", "func NewIKmsSpace(address common.Address, backend bind.ContractBackend) (*IKmsSpace, error) {\n\tcontract, err := bindIKmsSpace(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &IKmsSpace{IKmsSpaceCaller: IKmsSpaceCaller{contract: contract}, IKmsSpaceTransactor: IKmsSpaceTransactor{contract: contract}, IKmsSpaceFilterer: IKmsSpaceFilterer{contract: contract}}, nil\n}", "func (a *OrganizationsApiService) GetOrganization(ctx _context.Context, organizationGuid string) ApiGetOrganizationRequest {\n\treturn ApiGetOrganizationRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\torganizationGuid: organizationGuid,\n\t}\n}", "func CreateOrganization(clients *common.ClientContainer, handler common.HandlerInterface) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tvar org struct {\n\t\t\tName string `json:\"name\"`\n\t\t}\n\n\t\terr := json.NewDecoder(r.Body).Decode(&org)\n\t\tif err != nil {\n\t\t\tcommon.WriteErrorToResponse(w, http.StatusBadRequest,\n\t\t\t\thttp.StatusText(http.StatusBadRequest),\n\t\t\t\terr.Error())\n\t\t\treturn\n\t\t}\n\n\t\tif len(org.Name) == 0 {\n\t\t\tcommon.WriteErrorToResponse(w, http.StatusInternalServerError,\n\t\t\t\thttp.StatusText(http.StatusInternalServerError),\n\t\t\t\t\"provide Name in parameters\")\n\t\t\treturn\n\t\t}\n\n\t\tres, err := json.Marshal(org)\n\t\tif err != nil {\n\t\t\tcommon.WriteErrorToResponse(w, http.StatusInternalServerError,\n\t\t\t\thttp.StatusText(http.StatusInternalServerError),\n\t\t\t\terr.Error())\n\t\t\treturn\n\n\t\t}\n\n\t\t// Create Organization if no error\n\t\terr = handler.CreateOrganization(clients, res)\n\t\tif err != nil {\n\t\t\tswitch err.(type) {\n\t\t\t// grafanaclient.Exists means, that user provided\n\t\t\t// organization already exists. We return 409\n\t\t\tcase grafanaclient.Exists:\n\t\t\t\terrMsg := fmt.Sprintf(\"Organization Exists\")\n\t\t\t\tcommon.WriteErrorToResponse(w, http.StatusConflict,\n\t\t\t\t\terrMsg, err.Error())\n\t\t\t\treturn\n\t\t\t// If any other error happened -> return 500 error\n\t\t\tdefault:\n\t\t\t\tlog.Logger.Error(err)\n\t\t\t\tcommon.WriteErrorToResponse(w, http.StatusInternalServerError,\n\t\t\t\t\thttp.StatusText(http.StatusInternalServerError),\n\t\t\t\t\t\"Internal server error occured\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tw.WriteHeader(http.StatusOK)\n\t}\n}", "func GetIoTSpace(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *IoTSpaceState, opts ...pulumi.ResourceOption) (*IoTSpace, error) {\n\tvar resource IoTSpace\n\terr := ctx.ReadResource(\"azure-native:iotspaces/v20171001preview:IoTSpace\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (org *OrganizationService) Get(ctx context.Context, organizationId string) (*Organization, error) {\n\tpath := fmt.Sprintf(`organizations/%s`, organizationId)\n\treq, err := org.client.createRequest(\"GET\", path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ta := new(GetOrganizationsResponse)\n\terr = org.client.do(ctx, req, a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif strings.ToLower(a.RequestStatus) == \"success\" {\n\t\tif len(a.Organizations) >= 1 {\n\t\t\tif strings.ToLower(a.Organizations[0].SubRequestStatus) == \"success\" {\n\t\t\t\treturn &a.Organizations[0].Organization, nil\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(`non-success status returned from snapchat api (get organization): %s`, a.RequestStatus)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"no organizations found with organization id: %s\", organizationId)\n\t}\n\treturn nil, fmt.Errorf(`non-success status returned from snapchat api (get organization): %s`, a.RequestStatus)\n}", "func (s *DescribeAppInput) SetSpaceName(v string) *DescribeAppInput {\n\ts.SpaceName = &v\n\treturn s\n}", "func (c *Campaigner) OrganizationCreate(org Organization) (result ResponseOrganizationCreate, err error) {\n\tvar (\n\t\turi = \"/api/3/organizations\"\n\t\tdata = map[string]interface{}{\n\t\t\t\"organization\": org,\n\t\t}\n\t)\n\n\tr, body, err := c.post(uri, data)\n\tif err != nil {\n\t\treturn result, fmt.Errorf(\"organization creation failed, HTTP error: %s\", err)\n\t}\n\n\t// Response check.\n\tswitch r.StatusCode {\n\tcase http.StatusCreated:\n\t\terr = json.Unmarshal(body, &result)\n\t\tif err != nil {\n\t\t\treturn result, fmt.Errorf(\"organization creation failed, JSON error: %s\", err)\n\t\t}\n\n\t\treturn result, nil\n\tcase http.StatusUnprocessableEntity:\n\t\tvar apiError ActiveCampaignError\n\t\terr = json.Unmarshal(body, &apiError)\n\t\tif err != nil {\n\t\t\treturn result, fmt.Errorf(\"organization creation failed, API error unmarshall error: %s\", err)\n\t\t}\n\n\t\treturn result, apiError\n\tdefault:\n\t\treturn result, fmt.Errorf(\"organization creation failed, unspecified error (%d): %s\", r.StatusCode, string(body))\n\t}\n}", "func (p Place) AsOrganization() (*Organization, bool) {\n\treturn nil, false\n}", "func (a *Client) CreateAccountSpaces(params *CreateAccountSpacesParams, authInfo runtime.ClientAuthInfoWriter) (*CreateAccountSpacesCreated, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewCreateAccountSpacesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"createAccount_Spaces\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/api/{baseSpaceId}/accounts\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &CreateAccountSpacesReader{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.(*CreateAccountSpacesCreated)\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 createAccount_Spaces: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (s *workspaces) Create(ctx context.Context, organization string, options WorkspaceCreateOptions) (*Workspace, 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(\"POST\", u, &options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tw := &Workspace{}\n\terr = req.Do(ctx, w)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn w, nil\n}", "func (s *CreateAppInput) SetSpaceName(v string) *CreateAppInput {\n\ts.SpaceName = &v\n\treturn s\n}", "func (c *Client) GetOrg(name string) (*api.Org, error) {\n\tout := &api.Org{}\n\trawURL := fmt.Sprintf(pathOrg, c.base.String(), name)\n\terr := c.get(rawURL, true, out)\n\treturn out, errio.Error(err)\n}", "func CreateOrganization(iq IQ, name string) (string, error) {\n\tdoError := func(err error) error {\n\t\treturn fmt.Errorf(\"organization '%s' not created: %v\", name, err)\n\t}\n\n\trequest, err := json.Marshal(iqNewOrgRequest{Name: name})\n\tif err != nil {\n\t\treturn \"\", doError(err)\n\t}\n\n\tbody, _, err := iq.Post(restOrganization, bytes.NewBuffer(request))\n\tif err != nil {\n\t\treturn \"\", doError(err)\n\t}\n\n\tvar org Organization\n\tif err = json.Unmarshal(body, &org); err != nil {\n\t\treturn \"\", doError(err)\n\t}\n\n\treturn org.ID, nil\n}", "func (c *Campaigner) OrganizationFind(n string) (ResponseOrganizationList, error) {\n\t// Setup.\n\tvar (\n\t\tqs = fmt.Sprintf(\"%s=%s\", url.QueryEscape(\"filters[name]\"), url.QueryEscape(n))\n\t\tu = fmt.Sprintf(\"/api/3/organizations/?%s\", qs)\n\t\tresponse ResponseOrganizationList\n\t)\n\n\t// Error check.\n\tif len(strings.TrimSpace(n)) == 0 {\n\t\treturn response, fmt.Errorf(\"organization find failed, name is empty\")\n\t}\n\n\t// Send GET request.\n\tr, body, err := c.get(u)\n\tif err != nil {\n\t\treturn response, fmt.Errorf(\"organization find failed. HTTP failure: %s\", err)\n\t}\n\n\t// Response check.\n\tswitch r.StatusCode {\n\tcase http.StatusOK:\n\t\terr = json.Unmarshal(body, &response)\n\t\tif err != nil {\n\t\t\treturn response, fmt.Errorf(\"organization list failed, JSON failure: %s\", err)\n\t\t}\n\n\t\treturn response, nil\n\t}\n\n\treturn response, fmt.Errorf(\"organization find failed, unspecified error (%d); %s\", r.StatusCode, string(body))\n}", "func (s *Server) GetOrgByName(name string) gin.HandlerFunc {\n\treturn handler(func(c *gin.Context) error {\n\t\trooms, err := getRooms(c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\torg, err := database.GetOrgByName(s.db, c.Param(name), rooms...)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\torgLvl, err := getOrgLevel(c, org)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.JSON(http.StatusOK, orgLvl)\n\t\treturn nil\n\t})\n}", "func (o *IpamNetworkDataData) SetSpaceName(v string) {\n\to.SpaceName = &v\n}", "func getImagespaces(hostBase string) (*http.Response, []*server.Organization, error) {\n\n\turl := fmt.Sprintf(\"%s/\", hostBase)\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Add(\"Accept\", \"application/json\")\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", \"e30K.e30K.e30K\"))\n\tclient := &http.Client{}\n\tresponse, err := client.Do(req)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\trepositories := []*server.Organization{}\n\n\tbytes, err := ioutil.ReadAll(response.Body)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tjson.Unmarshal(bytes, &repositories)\n\n\treturn response, repositories, err\n\n}", "func (s *CreatePresignedDomainUrlInput) SetSpaceName(v string) *CreatePresignedDomainUrlInput {\n\ts.SpaceName = &v\n\treturn s\n}", "func (c CountUnit) Space(s SpaceUnit, dimension int8) MetricUnit {\n\treturn (&metricUnit{uint32(c)}).Space(s, dimension)\n}", "func (c *SpaceClient) List(ctx context.Context, opts *SpaceListOptions) ([]*resource.Space, *Pager, error) {\n\tif opts == nil {\n\t\topts = NewSpaceListOptions()\n\t}\n\topts.Include = resource.SpaceIncludeNone\n\n\tvar res resource.SpaceList\n\terr := c.client.get(ctx, path.Format(\"/v3/spaces?%s\", opts.ToQueryString()), &res)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tpager := NewPager(res.Pagination)\n\treturn res.Resources, pager, nil\n}", "func (sm *SpaceManager) Create(ctx context.Context, space string) (storage.Space, error) {\n\tlock := sm.Lock.Get(space)\n\tif !lock.Lock(sm.LockTimeout) {\n\t\treturn nil, ErrorLocking.Format(\"space\", space)\n\t}\n\tdefer lock.Unlock()\n\tnewSpace, err := sm.Space(ctx, space)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif newSpace.Exists(ctx) {\n\t\treturn nil, ErrorResourceExist.Format(space)\n\t}\n\t// space does not exist\n\tkey := path.Join(sm.Prefix, space, statusName)\n\terr = sm.Backend.PutContent(ctx, key, []byte(statusSuccess))\n\tif err != nil {\n\t\treturn nil, ErrorInternalUnknown.Format(err)\n\t}\n\treturn sm.Space(ctx, space)\n}", "func (s *Attribute) Space() *Dataspace {\n\thid := C.H5Aget_space(s.id)\n\tif int(hid) > 0 {\n\t\treturn newDataspace(hid)\n\t}\n\treturn nil\n}", "func (o *IpamAliasEditInput) GetSpaceName() string {\n\tif o == nil || o.SpaceName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.SpaceName\n}", "func (c *cfService) Spaces() Spaces {\n\treturn newSpacesAPI(c.Client)\n}", "func (g *GitHub) GetOrganization(name string) (org *Organization, err error) {\n\turi := fmt.Sprintf(\"/orgs/%s\", name)\n\terr = g.callGithubApi(\"GET\", uri, &org)\n\torg.g = g\n\treturn\n}", "func Create(name string, parameters map[string]interface{}) (SpaceManager, error) {\n\tfactoriesMu.RLock()\n\tfactory, ok := factories[name]\n\tfactoriesMu.RUnlock()\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"SpaceManagerFactory not registered: %s\", name)\n\t}\n\treturn factory.Create(parameters)\n}", "func GetOrganizationByID(id int64) (Organization, error) {\n\tdb, err := sqlx.Connect(settings.Settings.Database.DriverName, settings.Settings.GetDbConn())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\torganization := Organization{}\n\terr = db.Get(&organization, \"SELECT * FROM organization WHERE id=$1\", id)\n\tif err == sql.ErrNoRows {\n\t\treturn organization, ErrOrganizationNotFound\n\t} else if err != nil {\n\t\treturn organization, err\n\t}\n\treturn organization, nil\n}", "func (s *DescribeSpaceOutput) SetSpaceName(v string) *DescribeSpaceOutput {\n\ts.SpaceName = &v\n\treturn s\n}", "func GetOrganizationById(id int64) (o *Organization, err error) {\n\to = &Organization{}\n\terr = DB.Where(\"id = ?\", id).First(o).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn o, nil\n}", "func createSpaceWithData(t *testing.T, c *zqd.Core, spaceName, src string) {\n\tres := createSpace(t, c, spaceName, \"\")\n\twriteToSpace(t, c, res.Name, src)\n}", "func (s *AppDetails) SetSpaceName(v string) *AppDetails {\n\ts.SpaceName = &v\n\treturn s\n}", "func (a *Client) GetAccountByIDSpaces(params *GetAccountByIDSpacesParams, authInfo runtime.ClientAuthInfoWriter) (*GetAccountByIDSpacesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetAccountByIDSpacesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getAccountById_Spaces\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/{baseSpaceId}/accounts/{id}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetAccountByIDSpacesReader{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.(*GetAccountByIDSpacesOK)\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 getAccountById_Spaces: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (c *Context) Organization() string { return c.orgName }", "func (m *Manager) Get(id string) (*Organization, error) {\n\tvar organization Organization\n\n\tobjectID := bson.ObjectIdHex(id)\n\n\tif err := m.collection.FindId(objectID).One(&organization); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &organization, nil\n}", "func NewIoTSpace(ctx *pulumi.Context,\n\tname string, args *IoTSpaceArgs, opts ...pulumi.ResourceOption) (*IoTSpace, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.ResourceGroupName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ResourceGroupName'\")\n\t}\n\tif args.Sku == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Sku'\")\n\t}\n\taliases := pulumi.Aliases([]pulumi.Alias{\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:iotspaces/v20171001preview:IoTSpace\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:iotspaces:IoTSpace\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:iotspaces:IoTSpace\"),\n\t\t},\n\t})\n\topts = append(opts, aliases)\n\tvar resource IoTSpace\n\terr := ctx.RegisterResource(\"azure-native:iotspaces/v20171001preview:IoTSpace\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (db *PSQL) GetOrganizationByID(id string) (*models.Organization, error) {\n\treturn nil, nil\n}", "func (s *DescribeSpaceInput) SetSpaceName(v string) *DescribeSpaceInput {\n\ts.SpaceName = &v\n\treturn s\n}", "func (p Places) AsOrganization() (*Organization, bool) {\n\treturn nil, false\n}", "func (s *CreateSpaceInput) SetSpaceName(v string) *CreateSpaceInput {\n\ts.SpaceName = &v\n\treturn s\n}", "func (service *UsagesService) GetSpaceUsage(organizationID, orderBy, metric, startAt, endAt string) *Collection {\n\tpath := fmt.Sprintf(\n\t\t\"/organizations/%s/space_periodic_usages?order=%s&metric[in]=%s&dateRange.startAt=%s&dateRange.endAt=%s\",\n\t\torganizationID,\n\t\torderBy,\n\t\tmetric,\n\t\tstartAt,\n\t\tendAt,\n\t)\n\tmethod := \"GET\"\n\n\treq, err := service.c.newRequest(method, path, nil, nil)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tcol := NewCollection(&CollectionOptions{})\n\tcol.c = service.c\n\tcol.req = req\n\n\treturn col\n}", "func (c *SpaceClient) GetIncludeOrganization(ctx context.Context, guid string) (*resource.Space, *resource.Organization, error) {\n\tvar space resource.SpaceWithIncluded\n\terr := c.client.get(ctx, path.Format(\"/v3/spaces/%s?include=%s\", guid, resource.SpaceIncludeOrganization), &space)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn &space.Space, space.Included.Organizations[0], nil\n}" ]
[ "0.8242939", "0.61442536", "0.603013", "0.5925023", "0.58118176", "0.57149905", "0.5652524", "0.5448941", "0.5424435", "0.53659654", "0.5316954", "0.52566516", "0.523959", "0.5199702", "0.5174425", "0.5162662", "0.51054066", "0.50635743", "0.5060647", "0.50374913", "0.4994271", "0.49666455", "0.49140078", "0.48663595", "0.4821336", "0.47967893", "0.477176", "0.4760035", "0.47576168", "0.47479168", "0.47449434", "0.4739242", "0.47306892", "0.47300538", "0.47267485", "0.4724851", "0.47217292", "0.47035128", "0.47018817", "0.4690922", "0.46574482", "0.46574482", "0.46574482", "0.46382928", "0.46323362", "0.46118006", "0.46093774", "0.45884523", "0.45824316", "0.4581557", "0.45810148", "0.45743236", "0.45655835", "0.45550182", "0.45242703", "0.45239714", "0.45157272", "0.44861543", "0.44831094", "0.44783375", "0.44685972", "0.4466922", "0.44627583", "0.44558612", "0.44402108", "0.4426445", "0.4418201", "0.44147786", "0.44078028", "0.44068956", "0.44062236", "0.44042483", "0.4402655", "0.43876398", "0.4382629", "0.43821606", "0.4381335", "0.4371884", "0.436988", "0.4369206", "0.43632743", "0.43616644", "0.43610087", "0.43578732", "0.43521258", "0.43460444", "0.4344091", "0.4340984", "0.43394828", "0.4334519", "0.43333626", "0.43273398", "0.43271366", "0.4316914", "0.4312271", "0.43031707", "0.43027255", "0.43001062", "0.4294369", "0.42943403" ]
0.81762856
1
New initialize Now with time
func New(t time.Time) *Now { return &Now{t} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Now() time.Time { return now() }", "func Now() time.Time { return time.Now().UTC() }", "func Now() time.Time { return time.Now().UTC() }", "func (c stubClocker) Now() time.Time { return c.t }", "func Now() time.Time { return time.Now() }", "func Now() Time {\n\treturn NewTime(time.Now())\n}", "func (d *dummyClock) Now() time.Time {\n\treturn time.Time{}\n}", "func (defaultClock) Now() time.Time {\n\treturn time.Now()\n}", "func Now() time.Time {\n\treturn time.Date(int(Year.Status().(uint16)), time.Month(Month.Status().(uint8)), int(Day.Status().(uint16)), int(Hour.Status().(uint8)), int(Minute.Status().(uint8)), int(Second.Status().(uint8)), 0, time.FixedZone(\"custom\", int(Tz.Status().(int8)) * 3600))\n}", "func SetNow(n time.Time) {\n\tnow = n\n}", "func Now() time.Time {\n\treturn now()\n}", "func (c *ClockVal) Now() {\n\tc.CurrentTime = NowTime()\n}", "func Now() Time {\n\treturn Time{format(time.Now())}\n}", "func (realClocker) Now() time.Time { return time.Now() }", "func (c *Clock) Now() time.Time { return time.Now() }", "func Now() time.Time {\n\treturn c.Now()\n}", "func (t *DefaultClock) Now() time.Time {\n\treturn time.Now()\n}", "func Now() time.Time {\n\treturn Clock.Now()\n}", "func Now() time.Time {\n\treturn time.Now().In(_defaultLocation)\n}", "func Now() Time {\n\treturn Time(time.Now().UnixNano() / 1000)\n}", "func Now() Time {\n\treturn DefaultScheduler.Now()\n}", "func now() time.Time {\n\treturn time.Now().UTC()\n}", "func init_time() {\n\tSTARTEDON = time.Now()\n}", "func defaultNow() time.Time {\n\treturn time.Now()\n}", "func defaultNow() time.Time {\n\treturn time.Now().UTC()\n}", "func (t Time) SetNow(f fn) {\n\tnow = f\n}", "func (c *webCtx) Now() time.Time {\n\treturn c.now\n}", "func Now() *time.Time {\n\tt := time.Now()\n\treturn &t\n}", "func (fc *fakeClock) Now() time.Time {\n\treturn fc.time\n}", "func (t *Time) Now() time.Time {\n\treturn t.current\n}", "func Now() time.Time {\n\tif IsTest() {\n\t\treturn now\n\t}\n\n\treturn time.Now()\n}", "func Now() time.Time {\n\treturn CurrentClock().Now()\n}", "func Now(upToSecond ...bool) *TimeStamp {\n\treturn TimeFrom(time.Now(), upToSecond...)\n}", "func (tx *tx) SetNow(now time.Time) { tx.now = now }", "func Now() time.Time {\n\treturn time.Unix(0, time.Now().UnixNano()/1e6*1e6)\n}", "func Now() Timespec {\n\treturn NewTimespec(time.Now())\n}", "func Now() Time {\n\tvar t Time\n\tt.FromNSec(uint64(gotime.Now().UnixNano()))\n\treturn t\n}", "func TimeNow() Time {\n\treturn Time{\n\t\ttime.Now(),\n\t}\n}", "func nowTime() time.Time {\n\treturn time.Now().UTC()\n}", "func (s systemTimeSource) Now() time.Time {\n\treturn time.Now()\n}", "func (Clock) Now() time.Time {\n\treturn time.Now()\n}", "func Now() time.Time {\n\treturn Work.Now()\n}", "func (f FakeTimeSource) Now() time.Time {\n\treturn f.FakeTime\n}", "func newFakeTime() {\n\tfakeCurrentTime = fakeTime().Add(time.Hour * 24 * 2)\n}", "func ResetNow() { now = time.Now }", "func (m *timeSource) Now() mstime.Time {\n\treturn mstime.Now()\n}", "func (s SystemTimeSource) Now() time.Time {\n\treturn time.Now()\n}", "func (s SystemTimeSource) Now() time.Time {\n\treturn time.Now()\n}", "func (c *RunningClock) Now() time.Time {\n\treturn time.Now()\n}", "func (ns *Namespace) Now() _time.Time {\n\treturn _time.Now()\n}", "func (p PT) Now() int64 {\n\tif p.Seconds {\n\t\treturn time.Now().Unix()\n\t}\n\treturn time.Now().UnixNano()\n}", "func resetTimeNow() {\n\ttimeNow = time.Now\n}", "func (f *FixedTimeSource) Now() time.Time {\n\treturn f.fakeTime\n}", "func TimeNow() time.Time {\n\treturn time.Now().UTC()\n}", "func Now() DateTime {\n\treturn DateTimeFromTime(time.Now())\n}", "func (wc WallClock) Now() time.Time {\n\treturn time.Now()\n}", "func Now() Date {\n\tn := time.Now()\n\treturn Of(n)\n}", "func (c *Clock) Now() time.Time {\n\treturn time.Now().UTC().Truncate(time.Second)\n}", "func (RealClock) Now() time.Time {\n\treturn time.Now()\n}", "func (s *Scheduler) now() Time {\n\treturn s.provider.Now().Add(s.timeOffset)\n}", "func (c *FakeClock) Now() time.Time {\n\tc.steps++\n\treturn c.Time(c.steps)\n}", "func Now() time.Time {\n\treturn time.Now().In(LOCATION)\n}", "func (u *Util) Now() time.Time {\n\tif controlDuration != 0 {\n\t\treturn time.Now().Add(controlDuration).UTC()\n\t}\n\treturn time.Now().UTC()\n}", "func (tr *TextRegion) TimeNow() {\n\ttr.Time.Now()\n}", "func Now() int64 {\n\treturn time.Now().Unix()\n}", "func Now() int64 {\n\treturn time.Now().Unix()\n}", "func (t Time) ResetNow() time.Time {\n\tnow = defaultNow\n\treturn now()\n}", "func (rs *requestContext) Now() time.Time {\n\treturn rs.now\n}", "func Now(job cron.Job) {\n\tgo New(job).Run()\n}", "func (oiu *onceInUpdater) Now() Timestamp {\n\treturn Timestamp(atomic.LoadInt64((*int64)(&oiu.ts)))\n}", "func dbNow() time.Time {\n\treturn roundTime(time.Now())\n}", "func (c *Context) Now() time.Time {\n\treturn c.currentTime\n}", "func Now() *Timestamp {\n\tt := Timestamp(time.Now())\n\treturn &t\n}", "func (e Error) Now() Error {\n\te.Timestamp = time.Now().Unix()\n\treturn e\n}", "func (c *StoppedClock) Now() time.Time {\n\treturn c.t\n}", "func (c *CumulativeClock) Now() time.Time {\n\treturn c.current\n}", "func (t Time) GetNow() time.Time {\n\treturn now()\n}", "func (m *Mock) Now() time.Time {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\treturn m.now\n}", "func (m *Mock) Now() time.Time {\n\tm.Lock()\n\tdefer m.Unlock()\n\treturn m.now\n}", "func (p *PredefinedFake) Now() time.Time {\n\tadjustedTime := p.Base.Add(p.Delays[p.Next])\n\tp.Next++\n\treturn adjustedTime\n}", "func (c *MockClock) Now() time.Time {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\treturn c.now\n}", "func (c *StoppedClock) Now() time.Time {\n\treturn c.time\n}", "func Now() string {\n\treturn ToString(time.Now())\n}", "func (a *IncrementingFakeTimeSource) Now() time.Time {\n\tadjustedTime := a.BaseTime.Add(a.Increments[a.NextIncrement])\n\ta.NextIncrement++\n\n\treturn adjustedTime\n}", "func makeFakeNow() func() time.Time {\n\tvar t time.Time\n\treturn func() time.Time {\n\t\tt = t.Add(time.Second)\n\t\treturn t\n\t}\n}", "func (tc *TestClock) Now() time.Time {\n\ttc.l.RLock()\n\tdefer tc.l.RUnlock()\n\treturn tc.t\n}", "func ExampleNow() {\n\tt := gtime.Now()\n\tfmt.Println(t)\n\n\t// May Output:\n\t// 2021-11-06 13:41:08\n}", "func Now(ctx Context) time.Time {\n\treturn getWorkflowEnvironment(ctx).Now()\n}", "func (f *FakeTimeSource) Now() time.Time {\n\tf.mu.RLock()\n\tdefer f.mu.RUnlock()\n\treturn f.now\n}", "func NewTime() Widget {\n\treturn &Time{time: time.Now()}\n}", "func (t *TOTP) Now() string {\n\treturn t.At(currentTimestamp())\n}", "func Now() time.Time {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tvar now time.Time\n\tif testMode {\n\t\tnow = testNow()\n\t} else {\n\t\tnow = time.Now()\n\t}\n\treturn now.In(localtz.Get())\n}", "func GetNow() time.Time {\n\treturn time.Now().UTC()\n}", "func GetNow() time.Time {\n\treturn time.Now().UTC()\n}", "func StubNow(stub func() time.Time) { now = stub }", "func SetNow(f func() time.Time) func() time.Time {\n\tnow, f = f, now\n\treturn f\n}", "func (s *sunlightmap) Now() bool {\n\ts.zeitpunkte = []time.Time{time.Now().Local()}\n\ts.visualization = \"static\"\n\treturn true\n}", "func (t *TimeTravelCtx) now() time.Time {\n\tt.mutex.RLock()\n\tdefer t.mutex.RUnlock()\n\treturn t.ts\n}", "func (t *TimeService) Now(request *NowRequest) (*NowResponse, error) {\n\trsp := &NowResponse{}\n\treturn rsp, t.client.Call(\"time\", \"Now\", request, rsp)\n}", "func (s *Statistic) BeginNow() *Statistic {\n\ts.Running = true\n\ts.BeginAt = time.Now().Format(\"2006-01-02 15:04:05\")\n\treturn s\n}" ]
[ "0.76180404", "0.7385969", "0.7385969", "0.7371018", "0.7280752", "0.7213913", "0.7187263", "0.71849674", "0.71551025", "0.7143852", "0.7143053", "0.71301425", "0.7128633", "0.7120812", "0.7109315", "0.70917165", "0.70683783", "0.70221984", "0.7019913", "0.70187783", "0.6963649", "0.6956698", "0.69457364", "0.6940945", "0.69324905", "0.69247466", "0.6907117", "0.68743014", "0.68741405", "0.6868613", "0.68619823", "0.68525136", "0.684947", "0.6838875", "0.68265384", "0.68198955", "0.67873955", "0.6782403", "0.6771301", "0.67674196", "0.6749082", "0.67345", "0.6728201", "0.67098343", "0.66966856", "0.6674408", "0.66681516", "0.66681516", "0.66518176", "0.66457826", "0.66422427", "0.6633092", "0.6631999", "0.66070056", "0.65920025", "0.6585763", "0.65673065", "0.65633756", "0.6552731", "0.6545752", "0.65283483", "0.6518009", "0.6501517", "0.64928436", "0.649011", "0.649011", "0.64898574", "0.64797544", "0.64707726", "0.6468715", "0.6465937", "0.6441661", "0.6406424", "0.6393637", "0.6352373", "0.63472176", "0.63468194", "0.63281846", "0.6315671", "0.6301688", "0.6301539", "0.62794906", "0.6276061", "0.6268245", "0.626033", "0.6255675", "0.62435496", "0.6241725", "0.62371486", "0.6236869", "0.6234549", "0.622541", "0.6212637", "0.6212637", "0.62118584", "0.62105495", "0.62092614", "0.6207791", "0.61852926", "0.616247" ]
0.73370737
4
BeginningOfYear beginning of year
func BeginningOfYear() time.Time { return New(time.Now()).BeginningOfYear() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (now *Now) BeginningOfYear() time.Time {\n\ty, _, _ := now.Date()\n\treturn time.Date(y, time.January, 1, 0, 0, 0, 0, now.Location())\n}", "func YearStart(dt time.Time) time.Time {\n\treturn time.Date(\n\t\tdt.Year(),\n\t\t1,\n\t\t1,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\ttime.UTC,\n\t)\n}", "func StartYear(year int, layout string) string {\n\ttimeNow := time.Now().In(zoneLocal).Format(LayoutYear)\n\ttimeStart, _ := time.Parse(LayoutYear, timeNow)\n\treturn timeStart.\n\t\tAddDate(year, 0, 0).\n\t\tIn(zoneLocal).\n\t\tFormat(layout)\n}", "func GetYearStart(now time.Time) time.Time {\n\treturn time.Date(now.Year(), 1, 1, 0, 0, 0, 0, now.Location())\n}", "func PrevYearStart(dt time.Time) time.Time {\n\treturn YearStart(dt).AddDate(-1, 0, 0)\n}", "func (et ExfatTimestamp) Year() int {\n\treturn 1980 + int(et&4261412864)>>25\n}", "func (o TransferJobScheduleScheduleStartDateOutput) Year() pulumi.IntOutput {\n\treturn o.ApplyT(func(v TransferJobScheduleScheduleStartDate) int { return v.Year }).(pulumi.IntOutput)\n}", "func NextYearStart(dt time.Time) time.Time {\n\treturn YearStart(dt).AddDate(1, 0, 0)\n}", "func (c *StatsGetSearchapplicationCall) StartDateYear(startDateYear int64) *StatsGetSearchapplicationCall {\n\tc.urlParams_.Set(\"startDate.year\", fmt.Sprint(startDateYear))\n\treturn c\n}", "func (c *DateChecker) Year() int {\n\treturn commons.Now().Year()\n}", "func StartYearMicro(year int) string {\n\treturn StartYear(year, LayoutMicro)\n}", "func (dt DateTime) Year() int {\n\treturn dt.src.Year()\n}", "func (this *DosDatetime_Date) Year() (v int, err error) {\n\tif (this._f_year) {\n\t\treturn this.year, nil\n\t}\n\tthis.year = int((1980 + this.YearMinus1980))\n\tthis._f_year = true\n\treturn this.year, nil\n}", "func (dt DateTime) Year() int {\n\treturn dt.Time().Year()\n}", "func (o InstanceDenyMaintenancePeriodStartDateOutput) Year() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v InstanceDenyMaintenancePeriodStartDate) *int { return v.Year }).(pulumi.IntPtrOutput)\n}", "func (o TransferJobScheduleScheduleStartDatePtrOutput) Year() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *TransferJobScheduleScheduleStartDate) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Year\n\t}).(pulumi.IntPtrOutput)\n}", "func (ts TimeStamp) Year() int {\n\treturn ts.AsTime().Year()\n}", "func StartYearSecond(year int) string {\n\treturn StartYear(year, LayoutSecond)\n}", "func diasYear(yearInt int, year int) int {\n\n\treturn (year - yearInt) * 365\n}", "func (dt *DateTime) Year() *Number {\n\topChain := dt.chain.enter(\"Year()\")\n\tdefer opChain.leave()\n\n\tif opChain.failed() {\n\t\treturn newNumber(opChain, float64(0))\n\t}\n\n\treturn newNumber(opChain, float64(dt.value.Year()))\n}", "func (se SumEntry) Year() int {\n\treturn se.Year()\n}", "func getYearOfDate(date string) string {\n\treturn strings.Split(date, \"-\")[0]\n}", "func (o TransferJobScheduleScheduleEndDateOutput) Year() pulumi.IntOutput {\n\treturn o.ApplyT(func(v TransferJobScheduleScheduleEndDate) int { return v.Year }).(pulumi.IntOutput)\n}", "func (o InstanceDenyMaintenancePeriodStartDatePtrOutput) Year() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *InstanceDenyMaintenancePeriodStartDate) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Year\n\t}).(pulumi.IntPtrOutput)\n}", "func defaultYear() int {\n\tnow := time.Now()\n\tdefaultNflYear := now.Year()\n\tif now.Month() < time.July {\n\t\t// We actually want last year's season\n\t\tdefaultNflYear = defaultNflYear - 1\n\t}\n\treturn defaultNflYear\n}", "func (dt DateTime) YearDay() int {\n\treturn dt.src.YearDay()\n}", "func Year(s string) int {\n\tb := []byte(s)\n\n\tfound := YearRegexp.FindAll(b, -1)\n\n\tfor _, match := range found {\n\t\tyear := Int(string(match))\n\n\t\tif year > YearMin && year < YearMax {\n\t\t\treturn year\n\t\t}\n\t}\n\n\treturn 0\n}", "func (o TransferJobScheduleScheduleEndDatePtrOutput) Year() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *TransferJobScheduleScheduleEndDate) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Year\n\t}).(pulumi.IntPtrOutput)\n}", "func (t Time) YearDay() int {}", "func (dt DateTime) FloorYear() DateTime {\n\treturn dt.Replace(dt.Year(), 1, 1, 0, 0, 0, 0)\n}", "func (this *DateUtils) CalcNatureYear(date, deltaYear int) int {\n\tif date <= 0 {\n\t\tdateTime := time.Now().In(this.Loc)\n\t\tdate = this.GetYMD(&dateTime)\n\t}\n\n\ty := date / 10000\n\ty += deltaYear\n\treturn y*10000 + 1*100 + 1\n}", "func NbYear(p0 int, percent float64, aug int, p int) int {\n\tvar n int\n\tperYear := (100 + percent) / 100\n\tcurrP := p0\n\n\tfor n = 0; currP < p; n++ {\n\t\tcurrP = int(float64(currP)*perYear) + aug\n\t}\n\n\treturn n\n}", "func (o InstanceDenyMaintenancePeriodEndDateOutput) Year() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v InstanceDenyMaintenancePeriodEndDate) *int { return v.Year }).(pulumi.IntPtrOutput)\n}", "func (my *AttunedMonth) Year() int {\n\treturn my.y\n}", "func y(d time.Time, _ int) int {\n\treturn d.Year()\n}", "func (t *Time) DayOfYear() int {\n\tday := t.Day()\n\tmonth := int(t.Month())\n\tif t.IsLeapYear() {\n\t\tif month > 2 {\n\t\t\treturn dayOfMonth[month-1] + day\n\t\t}\n\t\treturn dayOfMonth[month-1] + day - 1\n\t}\n\treturn dayOfMonth[month-1] + day - 1\n}", "func leapYearsWithin(year int) int {\n\tif year > 0 {\n\t\tyear--\n\t} else {\n\t\tyear++\n\t}\n\n\treturn (year / 4) - (year / 100) + (year / 400)\n}", "func (d Date) YearDay() int {\n\treturn d.ToTime().YearDay()\n}", "func Years(n int) int {\n\treturn n * 10\n}", "func (dt DateTime) SpanYear() (DateTime, DateTime) {\n\treturn dt.FloorYear(), dt.CeilYear()\n}", "func (c Cookie) Year() Cookie {\n\treturn c.Expires(time.Now().AddDate(1, 0, 0))\n}", "func BeginningOf(t time.Time, dfmt string) time.Time {\n\tswitch timeFmt(dfmt) {\n\tcase XYear:\n\t\ty, _, _ := t.Date()\n\t\treturn time.Date(y, time.January, 1, 0, 0, 0, 0, t.Location())\n\tcase XMonth: // month\n\t\ty, m, _ := t.Date()\n\t\treturn time.Date(y, m, 1, 0, 0, 0, 0, t.Location())\n\tcase XDay: // day\n\t\ty, m, d := t.Date()\n\t\treturn time.Date(y, m, d, 0, 0, 0, 0, t.Location())\n\tcase XHour: // hour\n\t\ty, m, d := t.Date()\n\t\treturn time.Date(y, m, d, t.Hour(), 0, 0, 0, t.Location())\n\tcase XMinute: // minute\n\t\treturn t.Truncate(time.Minute)\n\n\tcase XWeek: // week\n\t\treturn BeginningOf(t.AddDate(0, 0, -Weekday(t)+1), XDay.String())\n\tcase XSeason: // season\n\t\tmonth := BeginningOf(t, XMonth.String())\n\t\toffset := (int(month.Month()) - 1) % 3\n\t\treturn month.AddDate(0, -offset, 0)\n\tcase XSemiYear: // semi\n\t\tmonth := BeginningOf(t, XMonth.String())\n\t\toffset := (int(month.Month()) - 1) % 6\n\t\treturn month.AddDate(0, -offset, 0)\n\t}\n\treturn t\n}", "func (o InstanceDenyMaintenancePeriodEndDatePtrOutput) Year() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *InstanceDenyMaintenancePeriodEndDate) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Year\n\t}).(pulumi.IntPtrOutput)\n}", "func Years(n int) int {\r\n\treturn n * 7\r\n}", "func YearRange(start, end int) YearRangeExpression {\n\treturn YearRangeExpression{Year(start), Year(end)}\n}", "func (dt *DateTime) GetYear() *Number {\n\treturn dt.Year()\n}", "func getYearValidateStartEndDate(startDate string, endDate string) (int, error) {\n\tstart, err := time.Parse(format, startDate)\n\tif err != nil {\n\t\treturn 0, errors.New(\"Start date should be in YYYY-MM-DD format\")\n\t}\n\n\tend, err := time.Parse(format, endDate)\n\tif err != nil {\n\t\treturn 0, errors.New(\"End date should be in YYYY-MM-DD format\")\n\t}\n\n\tcheckStartEnd := start.Before(end)\n\n\tif checkStartEnd == false {\n\t\treturn 0, errors.New(\"End date is before Start Date\")\n\t}\n\n\tstartYear := start.Year()\n\tendYear := end.Year()\n\n\tif startYear != endYear {\n\t\treturn 0, errors.New(\"Start date and End date must be in the same year\")\n\t}\n\n\treturn startYear, nil\n}", "func yearFracBasis1(startDate, endDate float64) (dayDiff, daysInYear float64) {\n\tstartTime, endTime := timeFromExcelTime(startDate, false), timeFromExcelTime(endDate, false)\n\tsy, smM, sd := startTime.Date()\n\tey, emM, ed := endTime.Date()\n\tsm, em := int(smM), int(emM)\n\tdayDiff = endDate - startDate\n\tisYearDifferent := sy != ey\n\tif isYearDifferent && (ey != sy+1 || sm < em || (sm == em && sd < ed)) {\n\t\tdayCount := 0\n\t\tfor y := sy; y <= ey; y++ {\n\t\t\tdayCount += getYearDays(y, 1)\n\t\t}\n\t\tdaysInYear = float64(dayCount) / float64(ey-sy+1)\n\t} else {\n\t\tif !isYearDifferent && isLeapYear(sy) {\n\t\t\tdaysInYear = 366\n\t\t} else {\n\t\t\tif isYearDifferent && yearFracBasisCond(sy, sm, sd, ey, em, ed) {\n\t\t\t\tdaysInYear = 366\n\t\t\t} else {\n\t\t\t\tdaysInYear = 365\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func Years(h int) int {\n return 7 * h\n}", "func (dt *DateTime) YearDay() *Number {\n\topChain := dt.chain.enter(\"YearDay()\")\n\tdefer opChain.leave()\n\n\tif opChain.failed() {\n\t\treturn newNumber(opChain, float64(0))\n\t}\n\n\treturn newNumber(opChain, float64(dt.value.YearDay()))\n}", "func (yc *YearCreate) SetYEAR(i int) *YearCreate {\n\tyc.mutation.SetYEAR(i)\n\treturn yc\n}", "func (CurrentYear) Apply() int {\n\treturn time.Now().Year()\n}", "func Years(n int) int {\n\treturn n * 7\n}", "func Years(n int) int {\n\treturn n * 7\n}", "func parseYear(s string) (year int) {\n\tyearString := regexp.MustCompile(`\\d+`).FindString(s)\n\tyear, err := strconv.Atoi(yearString)\n\tif err != nil {\n\t\treturn 0\n\t}\n\tif len(yearString) != 4 {\n\t\t// Not C.E.\n\t\t// Treat as ROC\n\t\tyear += 1911\n\t}\n\treturn\n}", "func Year() string {\n\tresp, err := http.Get(\"http://numbersapi.com/random/year\")\n\tif err != nil {\n\t\treturn \"I had a problem...\"\n\t}\n\tdefer resp.Body.Close()\n\n\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\n\treturn string(bodyBytes)\n}", "func YearsBeforeDesiredBalance(balance, targetBalance float64) int {\n\tvar accumulatingBalance = balance\n\tyears := 0\n\n\tfor accumulatingBalance < targetBalance {\n\t\taccumulatingBalance = AnnualBalanceUpdate(accumulatingBalance)\n\t\tyears++\n\t}\n\n\treturn years\n}", "func getYearValidateDate(date string) (int, error) {\n\ttime, err := time.Parse(format, date)\n\tif err != nil {\n\t\treturn 0, errors.New(\"Date should be in YYYY-MM-DD format\")\n\t}\n\n\tyear := time.Year()\n\n\treturn year, nil\n}", "func (s *Spanet) SetYear(year int) (int, error) {\n\treturn s.commandInt(\"S01\", year, 1970, 2037, \"year\", \"%04d\")\n}", "func (c *StatsGetIndexCall) FromDateYear(fromDateYear int64) *StatsGetIndexCall {\n\tc.urlParams_.Set(\"fromDate.year\", fmt.Sprint(fromDateYear))\n\treturn c\n}", "func (c *StatsGetIndexCall) FromDateYear(fromDateYear int64) *StatsGetIndexCall {\n\tc.urlParams_.Set(\"fromDate.year\", fmt.Sprint(fromDateYear))\n\treturn c\n}", "func GetNextYearTimeStamp() *timestamp.Timestamp {\n\tmyDates, _ := TimeToTimeStampPPB(time.Now().AddDate(1, 0, 0))\n\treturn myDates[0]\n}", "func yearTrunc(t time.Time) time.Time {\n\tt, _ = timeTrunc(t, \"day\")\n\treturn t.AddDate(0, 0, 1-t.YearDay())\n}", "func CenturytoYear(century float32) float32 {\n\treturn century / 100\n}", "func amendYear(dayOrDate *string, year string) {\n\tif year != CurrentYear {\n\t\tif strings.Contains(*dayOrDate, \"-\") {\n\t\t\tupdateDFlagSection(dayOrDate, 2, year)\n\t\t}\n\t}\n}", "func getYearDays(year, basis int) int {\n\tswitch basis {\n\tcase 1:\n\t\tif isLeapYear(year) {\n\t\t\treturn 366\n\t\t}\n\t\treturn 365\n\tcase 3:\n\t\treturn 365\n\tdefault:\n\t\treturn 360\n\t}\n}", "func (v *validator) isYear(s string) error {\n\tif s < \"00\" || s > \"99\" {\n\t\treturn ErrValidYear\n\t}\n\treturn nil\n}", "func NewYear(date sql.Expression) sql.Expression {\n\treturn &Year{expression.UnaryExpression{Child: date}}\n}", "func funcYear(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\treturn dateWrapper(vals, enh, func(t time.Time) float64 {\n\t\treturn float64(t.Year())\n\t})\n}", "func (c *StatsSessionSearchapplicationsGetCall) FromDateYear(fromDateYear int64) *StatsSessionSearchapplicationsGetCall {\n\tc.urlParams_.Set(\"fromDate.year\", fmt.Sprint(fromDateYear))\n\treturn c\n}", "func IsLeapYear(y int) bool {\n if y % 4 == 0 {\n if y % 100 == 0 {\n if y % 400 == 0 {\n return true;\n } else {\n return false;\n }\n }\n return true;\n }\n return false;\n}", "func yearFracBasis0(startDate, endDate float64) (dayDiff, daysInYear float64) {\n\tstartTime, endTime := timeFromExcelTime(startDate, false), timeFromExcelTime(endDate, false)\n\tsy, smM, sd := startTime.Date()\n\tey, emM, ed := endTime.Date()\n\tsm, em := int(smM), int(emM)\n\tif sd == 31 {\n\t\tsd--\n\t}\n\tif sd == 30 && ed == 31 {\n\t\ted--\n\t} else if leap := isLeapYear(sy); sm == 2 && ((leap && sd == 29) || (!leap && sd == 28)) {\n\t\tsd = 30\n\t\tif leap := isLeapYear(ey); em == 2 && ((leap && ed == 29) || (!leap && ed == 28)) {\n\t\t\ted = 30\n\t\t}\n\t}\n\tdayDiff = float64((ey-sy)*360 + (em-sm)*30 + (ed - sd))\n\tdaysInYear = 360\n\treturn\n}", "func AgeYear(dob time.Time, age time.Time) int{\n // Add the year of birth to current age to get the current year\n currentYear := dob.Year() + age.Year()\n return currentYear\n}", "func (c *StatsQuerySearchapplicationsGetCall) FromDateYear(fromDateYear int64) *StatsQuerySearchapplicationsGetCall {\n\tc.urlParams_.Set(\"fromDate.year\", fmt.Sprint(fromDateYear))\n\treturn c\n}", "func (c *StatsUserSearchapplicationsGetCall) FromDateYear(fromDateYear int64) *StatsUserSearchapplicationsGetCall {\n\tc.urlParams_.Set(\"fromDate.year\", fmt.Sprint(fromDateYear))\n\treturn c\n}", "func (y Year) Apply() int {\n\treturn y.YYYY\n}", "func DecadetoYear(decade float32) float32 {\n\treturn decade * 10\n}", "func Years(year int) int {\n\treturn year * 7\t\n}", "func determineYearWeek(t time.Time) int {\n\tyear, week := t.ISOWeek()\n\n\treturn (year*100 + week)\n}", "func (in *ActionUserRequestRegistrationCreateInput) SetYearOfBirth(value int64) *ActionUserRequestRegistrationCreateInput {\n\tin.YearOfBirth = value\n\n\tif in._selectedParameters == nil {\n\t\tin._selectedParameters = make(map[string]interface{})\n\t}\n\n\tin._selectedParameters[\"YearOfBirth\"] = nil\n\treturn in\n}", "func main() {\n\tborn := 1987\n\tfor {\n\t\tif born > 2020 {\n\t\t\tbreak\n\t\t}\n\t\tfmt.Println(born)\n\t\tborn++\n\t}\n}", "func (dao *Dao) GetTermBegin() time.Time {\n\tyear, month, _ := time.Now().Date()\n\tthisMonth := time.Date(year, month, 1, 0, 0, 0, 0, time.Local)\n\treturn thisMonth.AddDate(0, -1, 0)\n}", "func (c *StatsIndexDatasourcesGetCall) FromDateYear(fromDateYear int64) *StatsIndexDatasourcesGetCall {\n\tc.urlParams_.Set(\"fromDate.year\", fmt.Sprint(fromDateYear))\n\treturn c\n}", "func (c *StatsIndexDatasourcesGetCall) FromDateYear(fromDateYear int64) *StatsIndexDatasourcesGetCall {\n\tc.urlParams_.Set(\"fromDate.year\", fmt.Sprint(fromDateYear))\n\treturn c\n}", "func GetFractionalYear(year uint16, month time.Month, day uint8) float32 {\n\tvar t time.Time\n\tif year == 0 {\n\t\t// Use current date\n\t\tt = time.Now()\n\t} else {\n\t\tconst shortForm = \"2006-November-02\"\n\t\tt = time.Date(int(year), month, int(day), 0, 0, 0, 0, time.UTC)\n\t}\n\treturn float32(t.Year()) + float32(t.YearDay())/365\n}", "func yearFracBasis4(startDate, endDate float64) (dayDiff, daysInYear float64) {\n\tstartTime, endTime := timeFromExcelTime(startDate, false), timeFromExcelTime(endDate, false)\n\tsy, smM, sd := startTime.Date()\n\tey, emM, ed := endTime.Date()\n\tsm, em := int(smM), int(emM)\n\tif sd == 31 {\n\t\tsd--\n\t}\n\tif ed == 31 {\n\t\ted--\n\t}\n\tdayDiff = float64((ey-sy)*360 + (em-sm)*30 + (ed - sd))\n\tdaysInYear = 360\n\treturn\n}", "func (c Config) YearOrDefault() int {\n\tif c.Year > 0 {\n\t\treturn c.Year\n\t}\n\treturn time.Now().UTC().Year()\n}", "func (c Config) YearOrDefault() int {\n\tif c.Year > 0 {\n\t\treturn c.Year\n\t}\n\treturn time.Now().UTC().Year()\n}", "func (r *PopRow) GetYear() int32 { return r.Data.Year }", "func (dt DateTime) ReplaceYear(year int) DateTime {\n\treturn NewDateTime(\n\t\tyear,\n\t\tdt.Month(),\n\t\tdt.Day(),\n\t\tdt.Hour(),\n\t\tdt.Minute(),\n\t\tdt.Second(),\n\t\tdt.Nanosecond(),\n\t\tdt.Timezone(),\n\t)\n}", "func Years(hy int) int {\n\tdy := 10 * hy\n\tfmt.Printf(\"Number of dog years for human year %v is %v\\n\", hy, dy)\n\treturn dy\n}", "func fixYear(t time.Time, reference time.Time) time.Time {\n\tt = t.AddDate(reference.Year()-t.Year(), 0, 0)\n\tif t.After(reference) {\n\t\tt = t.AddDate(-1, 0, 0)\n\t}\n\treturn t\n}", "func (c *StatsGetQueryCall) FromDateYear(fromDateYear int64) *StatsGetQueryCall {\n\tc.urlParams_.Set(\"fromDate.year\", fmt.Sprint(fromDateYear))\n\treturn c\n}", "func (fn *formulaFuncs) YEAR(argsList *list.List) formulaArg {\n\tif argsList.Len() != 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"YEAR requires exactly 1 argument\")\n\t}\n\targ := argsList.Front().Value.(formulaArg)\n\tnum := arg.ToNumber()\n\tif num.Type != ArgNumber {\n\t\tdateString := strings.ToLower(arg.Value())\n\t\tif !isDateOnlyFmt(dateString) {\n\t\t\tif _, _, _, _, _, err := strToTime(dateString); err.Type == ArgError {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tyear, _, _, _, err := strToDate(dateString)\n\t\tif err.Type == ArgError {\n\t\t\treturn err\n\t\t}\n\t\treturn newNumberFormulaArg(float64(year))\n\t}\n\tif num.Number < 0 {\n\t\treturn newErrorFormulaArg(formulaErrorNUM, \"YEAR only accepts positive argument\")\n\t}\n\treturn newNumberFormulaArg(float64(timeFromExcelTime(num.Number, false).Year()))\n}", "func (me TdateTimeType) ToXsdtGYear() xsdt.GYear { return xsdt.GYear(me) }", "func (dt *DateTime) GetYearDay() *Number {\n\treturn dt.YearDay()\n}", "func main() {\n\tfor bd := 1985; bd <= 2020; bd++ {\n\t\tfmt.Println(bd)\n\t}\n}", "func (p *Satis) AmmountThisYear() (*Ammount, error) {\n\tnow := time.Now()\n\tprec := time.Date(now.Year(), time.Month(0), 0, 0, 0, 0, 0, now.Location())\n\tlast := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), 0, 0, now.Location())\n\tamm, err := p.getLongAmmount(prec, last)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn amm, nil\n}", "func IsLeapYear(y int) bool {\n\treturn y%400 == 0 || y%100 != 0 && y%4 == 0\n}", "func (c *StatsGetSessionCall) FromDateYear(fromDateYear int64) *StatsGetSessionCall {\n\tc.urlParams_.Set(\"fromDate.year\", fmt.Sprint(fromDateYear))\n\treturn c\n}" ]
[ "0.7899211", "0.7367037", "0.72628975", "0.7149147", "0.67440516", "0.65811616", "0.6560313", "0.6554245", "0.6499357", "0.648948", "0.6486854", "0.6461929", "0.63560194", "0.63298076", "0.6318857", "0.6294704", "0.628328", "0.6255367", "0.6227002", "0.621877", "0.62150335", "0.61688787", "0.600594", "0.6001115", "0.59593046", "0.59565157", "0.59499264", "0.5937221", "0.5915336", "0.58670425", "0.5863265", "0.584918", "0.58339804", "0.58267844", "0.5809376", "0.58014387", "0.5769962", "0.5761477", "0.5745446", "0.5717387", "0.56867355", "0.56842184", "0.5682841", "0.56751424", "0.5670503", "0.5660944", "0.5647425", "0.5632218", "0.56296456", "0.55907786", "0.55894643", "0.5582869", "0.55760455", "0.55760455", "0.55551", "0.5547879", "0.5515348", "0.54972845", "0.5489336", "0.5487313", "0.5487313", "0.54602605", "0.54501146", "0.54415745", "0.5440868", "0.54301554", "0.5426209", "0.54149276", "0.53887534", "0.5386527", "0.53790766", "0.53670955", "0.5357649", "0.5345637", "0.5339066", "0.53278667", "0.53218555", "0.5320612", "0.53087157", "0.53069955", "0.5284921", "0.5275177", "0.5266532", "0.5266532", "0.5250377", "0.5247026", "0.5242444", "0.5242444", "0.52411807", "0.5240319", "0.5238275", "0.5232818", "0.52063745", "0.5205611", "0.51734155", "0.517241", "0.51626116", "0.51562077", "0.5143334", "0.5138443" ]
0.8250332
0
BeginningOfYear BeginningOfYear beginning of year
func (now *Now) BeginningOfYear() time.Time { y, _, _ := now.Date() return time.Date(y, time.January, 1, 0, 0, 0, 0, now.Location()) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func BeginningOfYear() time.Time {\n\treturn New(time.Now()).BeginningOfYear()\n}", "func YearStart(dt time.Time) time.Time {\n\treturn time.Date(\n\t\tdt.Year(),\n\t\t1,\n\t\t1,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\ttime.UTC,\n\t)\n}", "func StartYear(year int, layout string) string {\n\ttimeNow := time.Now().In(zoneLocal).Format(LayoutYear)\n\ttimeStart, _ := time.Parse(LayoutYear, timeNow)\n\treturn timeStart.\n\t\tAddDate(year, 0, 0).\n\t\tIn(zoneLocal).\n\t\tFormat(layout)\n}", "func GetYearStart(now time.Time) time.Time {\n\treturn time.Date(now.Year(), 1, 1, 0, 0, 0, 0, now.Location())\n}", "func PrevYearStart(dt time.Time) time.Time {\n\treturn YearStart(dt).AddDate(-1, 0, 0)\n}", "func NextYearStart(dt time.Time) time.Time {\n\treturn YearStart(dt).AddDate(1, 0, 0)\n}", "func StartYearMicro(year int) string {\n\treturn StartYear(year, LayoutMicro)\n}", "func (c *StatsGetSearchapplicationCall) StartDateYear(startDateYear int64) *StatsGetSearchapplicationCall {\n\tc.urlParams_.Set(\"startDate.year\", fmt.Sprint(startDateYear))\n\treturn c\n}", "func (o TransferJobScheduleScheduleStartDateOutput) Year() pulumi.IntOutput {\n\treturn o.ApplyT(func(v TransferJobScheduleScheduleStartDate) int { return v.Year }).(pulumi.IntOutput)\n}", "func (et ExfatTimestamp) Year() int {\n\treturn 1980 + int(et&4261412864)>>25\n}", "func StartYearSecond(year int) string {\n\treturn StartYear(year, LayoutSecond)\n}", "func (dt DateTime) Year() int {\n\treturn dt.src.Year()\n}", "func (c *DateChecker) Year() int {\n\treturn commons.Now().Year()\n}", "func (this *DosDatetime_Date) Year() (v int, err error) {\n\tif (this._f_year) {\n\t\treturn this.year, nil\n\t}\n\tthis.year = int((1980 + this.YearMinus1980))\n\tthis._f_year = true\n\treturn this.year, nil\n}", "func (o TransferJobScheduleScheduleStartDatePtrOutput) Year() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *TransferJobScheduleScheduleStartDate) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Year\n\t}).(pulumi.IntPtrOutput)\n}", "func (o InstanceDenyMaintenancePeriodStartDateOutput) Year() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v InstanceDenyMaintenancePeriodStartDate) *int { return v.Year }).(pulumi.IntPtrOutput)\n}", "func diasYear(yearInt int, year int) int {\n\n\treturn (year - yearInt) * 365\n}", "func BeginningOf(t time.Time, dfmt string) time.Time {\n\tswitch timeFmt(dfmt) {\n\tcase XYear:\n\t\ty, _, _ := t.Date()\n\t\treturn time.Date(y, time.January, 1, 0, 0, 0, 0, t.Location())\n\tcase XMonth: // month\n\t\ty, m, _ := t.Date()\n\t\treturn time.Date(y, m, 1, 0, 0, 0, 0, t.Location())\n\tcase XDay: // day\n\t\ty, m, d := t.Date()\n\t\treturn time.Date(y, m, d, 0, 0, 0, 0, t.Location())\n\tcase XHour: // hour\n\t\ty, m, d := t.Date()\n\t\treturn time.Date(y, m, d, t.Hour(), 0, 0, 0, t.Location())\n\tcase XMinute: // minute\n\t\treturn t.Truncate(time.Minute)\n\n\tcase XWeek: // week\n\t\treturn BeginningOf(t.AddDate(0, 0, -Weekday(t)+1), XDay.String())\n\tcase XSeason: // season\n\t\tmonth := BeginningOf(t, XMonth.String())\n\t\toffset := (int(month.Month()) - 1) % 3\n\t\treturn month.AddDate(0, -offset, 0)\n\tcase XSemiYear: // semi\n\t\tmonth := BeginningOf(t, XMonth.String())\n\t\toffset := (int(month.Month()) - 1) % 6\n\t\treturn month.AddDate(0, -offset, 0)\n\t}\n\treturn t\n}", "func (dt DateTime) Year() int {\n\treturn dt.Time().Year()\n}", "func (ts TimeStamp) Year() int {\n\treturn ts.AsTime().Year()\n}", "func (dt *DateTime) Year() *Number {\n\topChain := dt.chain.enter(\"Year()\")\n\tdefer opChain.leave()\n\n\tif opChain.failed() {\n\t\treturn newNumber(opChain, float64(0))\n\t}\n\n\treturn newNumber(opChain, float64(dt.value.Year()))\n}", "func (se SumEntry) Year() int {\n\treturn se.Year()\n}", "func getYearOfDate(date string) string {\n\treturn strings.Split(date, \"-\")[0]\n}", "func defaultYear() int {\n\tnow := time.Now()\n\tdefaultNflYear := now.Year()\n\tif now.Month() < time.July {\n\t\t// We actually want last year's season\n\t\tdefaultNflYear = defaultNflYear - 1\n\t}\n\treturn defaultNflYear\n}", "func (o InstanceDenyMaintenancePeriodStartDatePtrOutput) Year() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *InstanceDenyMaintenancePeriodStartDate) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Year\n\t}).(pulumi.IntPtrOutput)\n}", "func (o TransferJobScheduleScheduleEndDateOutput) Year() pulumi.IntOutput {\n\treturn o.ApplyT(func(v TransferJobScheduleScheduleEndDate) int { return v.Year }).(pulumi.IntOutput)\n}", "func (o TransferJobScheduleScheduleEndDatePtrOutput) Year() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *TransferJobScheduleScheduleEndDate) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Year\n\t}).(pulumi.IntPtrOutput)\n}", "func (this *DateUtils) CalcNatureYear(date, deltaYear int) int {\n\tif date <= 0 {\n\t\tdateTime := time.Now().In(this.Loc)\n\t\tdate = this.GetYMD(&dateTime)\n\t}\n\n\ty := date / 10000\n\ty += deltaYear\n\treturn y*10000 + 1*100 + 1\n}", "func (t *Time) DayOfYear() int {\n\tday := t.Day()\n\tmonth := int(t.Month())\n\tif t.IsLeapYear() {\n\t\tif month > 2 {\n\t\t\treturn dayOfMonth[month-1] + day\n\t\t}\n\t\treturn dayOfMonth[month-1] + day - 1\n\t}\n\treturn dayOfMonth[month-1] + day - 1\n}", "func (dt DateTime) YearDay() int {\n\treturn dt.src.YearDay()\n}", "func (t Time) YearDay() int {}", "func YearsBeforeDesiredBalance(balance, targetBalance float64) int {\n\tvar accumulatingBalance = balance\n\tyears := 0\n\n\tfor accumulatingBalance < targetBalance {\n\t\taccumulatingBalance = AnnualBalanceUpdate(accumulatingBalance)\n\t\tyears++\n\t}\n\n\treturn years\n}", "func NbYear(p0 int, percent float64, aug int, p int) int {\n\tvar n int\n\tperYear := (100 + percent) / 100\n\tcurrP := p0\n\n\tfor n = 0; currP < p; n++ {\n\t\tcurrP = int(float64(currP)*perYear) + aug\n\t}\n\n\treturn n\n}", "func (dt DateTime) FloorYear() DateTime {\n\treturn dt.Replace(dt.Year(), 1, 1, 0, 0, 0, 0)\n}", "func leapYearsWithin(year int) int {\n\tif year > 0 {\n\t\tyear--\n\t} else {\n\t\tyear++\n\t}\n\n\treturn (year / 4) - (year / 100) + (year / 400)\n}", "func Year(s string) int {\n\tb := []byte(s)\n\n\tfound := YearRegexp.FindAll(b, -1)\n\n\tfor _, match := range found {\n\t\tyear := Int(string(match))\n\n\t\tif year > YearMin && year < YearMax {\n\t\t\treturn year\n\t\t}\n\t}\n\n\treturn 0\n}", "func yearFracBasis1(startDate, endDate float64) (dayDiff, daysInYear float64) {\n\tstartTime, endTime := timeFromExcelTime(startDate, false), timeFromExcelTime(endDate, false)\n\tsy, smM, sd := startTime.Date()\n\tey, emM, ed := endTime.Date()\n\tsm, em := int(smM), int(emM)\n\tdayDiff = endDate - startDate\n\tisYearDifferent := sy != ey\n\tif isYearDifferent && (ey != sy+1 || sm < em || (sm == em && sd < ed)) {\n\t\tdayCount := 0\n\t\tfor y := sy; y <= ey; y++ {\n\t\t\tdayCount += getYearDays(y, 1)\n\t\t}\n\t\tdaysInYear = float64(dayCount) / float64(ey-sy+1)\n\t} else {\n\t\tif !isYearDifferent && isLeapYear(sy) {\n\t\t\tdaysInYear = 366\n\t\t} else {\n\t\t\tif isYearDifferent && yearFracBasisCond(sy, sm, sd, ey, em, ed) {\n\t\t\t\tdaysInYear = 366\n\t\t\t} else {\n\t\t\t\tdaysInYear = 365\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (o InstanceDenyMaintenancePeriodEndDateOutput) Year() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v InstanceDenyMaintenancePeriodEndDate) *int { return v.Year }).(pulumi.IntPtrOutput)\n}", "func (dt DateTime) SpanYear() (DateTime, DateTime) {\n\treturn dt.FloorYear(), dt.CeilYear()\n}", "func y(d time.Time, _ int) int {\n\treturn d.Year()\n}", "func YearRange(start, end int) YearRangeExpression {\n\treturn YearRangeExpression{Year(start), Year(end)}\n}", "func (my *AttunedMonth) Year() int {\n\treturn my.y\n}", "func Years(n int) int {\n\treturn n * 10\n}", "func Years(n int) int {\r\n\treturn n * 7\r\n}", "func getYearValidateStartEndDate(startDate string, endDate string) (int, error) {\n\tstart, err := time.Parse(format, startDate)\n\tif err != nil {\n\t\treturn 0, errors.New(\"Start date should be in YYYY-MM-DD format\")\n\t}\n\n\tend, err := time.Parse(format, endDate)\n\tif err != nil {\n\t\treturn 0, errors.New(\"End date should be in YYYY-MM-DD format\")\n\t}\n\n\tcheckStartEnd := start.Before(end)\n\n\tif checkStartEnd == false {\n\t\treturn 0, errors.New(\"End date is before Start Date\")\n\t}\n\n\tstartYear := start.Year()\n\tendYear := end.Year()\n\n\tif startYear != endYear {\n\t\treturn 0, errors.New(\"Start date and End date must be in the same year\")\n\t}\n\n\treturn startYear, nil\n}", "func (d Date) YearDay() int {\n\treturn d.ToTime().YearDay()\n}", "func (o InstanceDenyMaintenancePeriodEndDatePtrOutput) Year() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *InstanceDenyMaintenancePeriodEndDate) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Year\n\t}).(pulumi.IntPtrOutput)\n}", "func main() {\n\tborn := 1987\n\tfor {\n\t\tif born > 2020 {\n\t\t\tbreak\n\t\t}\n\t\tfmt.Println(born)\n\t\tborn++\n\t}\n}", "func Years(h int) int {\n return 7 * h\n}", "func (dao *Dao) GetTermBegin() time.Time {\n\tyear, month, _ := time.Now().Date()\n\tthisMonth := time.Date(year, month, 1, 0, 0, 0, 0, time.Local)\n\treturn thisMonth.AddDate(0, -1, 0)\n}", "func Years(n int) int {\n\treturn n * 7\n}", "func Years(n int) int {\n\treturn n * 7\n}", "func (c Cookie) Year() Cookie {\n\treturn c.Expires(time.Now().AddDate(1, 0, 0))\n}", "func (CurrentYear) Apply() int {\n\treturn time.Now().Year()\n}", "func (yc *YearCreate) SetYEAR(i int) *YearCreate {\n\tyc.mutation.SetYEAR(i)\n\treturn yc\n}", "func (dt *DateTime) YearDay() *Number {\n\topChain := dt.chain.enter(\"YearDay()\")\n\tdefer opChain.leave()\n\n\tif opChain.failed() {\n\t\treturn newNumber(opChain, float64(0))\n\t}\n\n\treturn newNumber(opChain, float64(dt.value.YearDay()))\n}", "func yearFracBasis0(startDate, endDate float64) (dayDiff, daysInYear float64) {\n\tstartTime, endTime := timeFromExcelTime(startDate, false), timeFromExcelTime(endDate, false)\n\tsy, smM, sd := startTime.Date()\n\tey, emM, ed := endTime.Date()\n\tsm, em := int(smM), int(emM)\n\tif sd == 31 {\n\t\tsd--\n\t}\n\tif sd == 30 && ed == 31 {\n\t\ted--\n\t} else if leap := isLeapYear(sy); sm == 2 && ((leap && sd == 29) || (!leap && sd == 28)) {\n\t\tsd = 30\n\t\tif leap := isLeapYear(ey); em == 2 && ((leap && ed == 29) || (!leap && ed == 28)) {\n\t\t\ted = 30\n\t\t}\n\t}\n\tdayDiff = float64((ey-sy)*360 + (em-sm)*30 + (ed - sd))\n\tdaysInYear = 360\n\treturn\n}", "func GetNextYearTimeStamp() *timestamp.Timestamp {\n\tmyDates, _ := TimeToTimeStampPPB(time.Now().AddDate(1, 0, 0))\n\treturn myDates[0]\n}", "func amendYear(dayOrDate *string, year string) {\n\tif year != CurrentYear {\n\t\tif strings.Contains(*dayOrDate, \"-\") {\n\t\t\tupdateDFlagSection(dayOrDate, 2, year)\n\t\t}\n\t}\n}", "func (dt *DateTime) GetYear() *Number {\n\treturn dt.Year()\n}", "func getYearDays(year, basis int) int {\n\tswitch basis {\n\tcase 1:\n\t\tif isLeapYear(year) {\n\t\t\treturn 366\n\t\t}\n\t\treturn 365\n\tcase 3:\n\t\treturn 365\n\tdefault:\n\t\treturn 360\n\t}\n}", "func AgeYear(dob time.Time, age time.Time) int{\n // Add the year of birth to current age to get the current year\n currentYear := dob.Year() + age.Year()\n return currentYear\n}", "func parseYear(s string) (year int) {\n\tyearString := regexp.MustCompile(`\\d+`).FindString(s)\n\tyear, err := strconv.Atoi(yearString)\n\tif err != nil {\n\t\treturn 0\n\t}\n\tif len(yearString) != 4 {\n\t\t// Not C.E.\n\t\t// Treat as ROC\n\t\tyear += 1911\n\t}\n\treturn\n}", "func IsLeapYear(y int) bool {\n if y % 4 == 0 {\n if y % 100 == 0 {\n if y % 400 == 0 {\n return true;\n } else {\n return false;\n }\n }\n return true;\n }\n return false;\n}", "func yearTrunc(t time.Time) time.Time {\n\tt, _ = timeTrunc(t, \"day\")\n\treturn t.AddDate(0, 0, 1-t.YearDay())\n}", "func (c *StatsGetIndexCall) FromDateYear(fromDateYear int64) *StatsGetIndexCall {\n\tc.urlParams_.Set(\"fromDate.year\", fmt.Sprint(fromDateYear))\n\treturn c\n}", "func (c *StatsGetIndexCall) FromDateYear(fromDateYear int64) *StatsGetIndexCall {\n\tc.urlParams_.Set(\"fromDate.year\", fmt.Sprint(fromDateYear))\n\treturn c\n}", "func (c *StatsSessionSearchapplicationsGetCall) FromDateYear(fromDateYear int64) *StatsSessionSearchapplicationsGetCall {\n\tc.urlParams_.Set(\"fromDate.year\", fmt.Sprint(fromDateYear))\n\treturn c\n}", "func CenturytoYear(century float32) float32 {\n\treturn century / 100\n}", "func Year() string {\n\tresp, err := http.Get(\"http://numbersapi.com/random/year\")\n\tif err != nil {\n\t\treturn \"I had a problem...\"\n\t}\n\tdefer resp.Body.Close()\n\n\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\n\treturn string(bodyBytes)\n}", "func yearFracBasis4(startDate, endDate float64) (dayDiff, daysInYear float64) {\n\tstartTime, endTime := timeFromExcelTime(startDate, false), timeFromExcelTime(endDate, false)\n\tsy, smM, sd := startTime.Date()\n\tey, emM, ed := endTime.Date()\n\tsm, em := int(smM), int(emM)\n\tif sd == 31 {\n\t\tsd--\n\t}\n\tif ed == 31 {\n\t\ted--\n\t}\n\tdayDiff = float64((ey-sy)*360 + (em-sm)*30 + (ed - sd))\n\tdaysInYear = 360\n\treturn\n}", "func (s *Spanet) SetYear(year int) (int, error) {\n\treturn s.commandInt(\"S01\", year, 1970, 2037, \"year\", \"%04d\")\n}", "func fixYear(t time.Time, reference time.Time) time.Time {\n\tt = t.AddDate(reference.Year()-t.Year(), 0, 0)\n\tif t.After(reference) {\n\t\tt = t.AddDate(-1, 0, 0)\n\t}\n\treturn t\n}", "func main() {\n\tfor bd := 1985; bd <= 2020; bd++ {\n\t\tfmt.Println(bd)\n\t}\n}", "func NewYear(date sql.Expression) sql.Expression {\n\treturn &Year{expression.UnaryExpression{Child: date}}\n}", "func determineYearWeek(t time.Time) int {\n\tyear, week := t.ISOWeek()\n\n\treturn (year*100 + week)\n}", "func Years(year int) int {\n\treturn year * 7\t\n}", "func funcYear(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\treturn dateWrapper(vals, enh, func(t time.Time) float64 {\n\t\treturn float64(t.Year())\n\t})\n}", "func (c *StatsUserSearchapplicationsGetCall) FromDateYear(fromDateYear int64) *StatsUserSearchapplicationsGetCall {\n\tc.urlParams_.Set(\"fromDate.year\", fmt.Sprint(fromDateYear))\n\treturn c\n}", "func BeginningOfDay(t time.Time) time.Time {\n\tyear, month, day := t.Date()\n\treturn time.Date(year, month, day, 0, 0, 0, 0, t.Location())\n}", "func (c *StatsQuerySearchapplicationsGetCall) FromDateYear(fromDateYear int64) *StatsQuerySearchapplicationsGetCall {\n\tc.urlParams_.Set(\"fromDate.year\", fmt.Sprint(fromDateYear))\n\treturn c\n}", "func getYearValidateDate(date string) (int, error) {\n\ttime, err := time.Parse(format, date)\n\tif err != nil {\n\t\treturn 0, errors.New(\"Date should be in YYYY-MM-DD format\")\n\t}\n\n\tyear := time.Year()\n\n\treturn year, nil\n}", "func (in *ActionUserRequestRegistrationCreateInput) SetYearOfBirth(value int64) *ActionUserRequestRegistrationCreateInput {\n\tin.YearOfBirth = value\n\n\tif in._selectedParameters == nil {\n\t\tin._selectedParameters = make(map[string]interface{})\n\t}\n\n\tin._selectedParameters[\"YearOfBirth\"] = nil\n\treturn in\n}", "func main() {\n\ti := 1967\n\tfor i < 2020 {\n\t\tfmt.Println(i)\n\t\ti++\n\t} //END for\n}", "func (v *validator) isYear(s string) error {\n\tif s < \"00\" || s > \"99\" {\n\t\treturn ErrValidYear\n\t}\n\treturn nil\n}", "func (y Year) Apply() int {\n\treturn y.YYYY\n}", "func (dt DateTime) ReplaceYear(year int) DateTime {\n\treturn NewDateTime(\n\t\tyear,\n\t\tdt.Month(),\n\t\tdt.Day(),\n\t\tdt.Hour(),\n\t\tdt.Minute(),\n\t\tdt.Second(),\n\t\tdt.Nanosecond(),\n\t\tdt.Timezone(),\n\t)\n}", "func Years(hy int) int {\n\tdy := 10 * hy\n\tfmt.Printf(\"Number of dog years for human year %v is %v\\n\", hy, dy)\n\treturn dy\n}", "func DecadetoYear(decade float32) float32 {\n\treturn decade * 10\n}", "func WordBegin(bytes []byte, pos int) int {\n\tl := len(bytes)\n\tif pos < 0 || pos >= l {\n\t\treturn InvalidPos\n\t}\n\tif pos == 0 {\n\t\treturn 0\n\t}\n\n\tpos = wSequenceBegin(bytes, pos)\n\n\treturn wordBegin(bytes, pos)\n}", "func TillNextYear() time.Duration {\n\treturn Now().TillNextYear()\n}", "func NewDayOfYear(date sql.Expression) sql.Expression {\n\treturn &DayOfYear{expression.UnaryExpression{Child: date}}\n}", "func (c Config) YearOrDefault() int {\n\tif c.Year > 0 {\n\t\treturn c.Year\n\t}\n\treturn time.Now().UTC().Year()\n}", "func (c Config) YearOrDefault() int {\n\tif c.Year > 0 {\n\t\treturn c.Year\n\t}\n\treturn time.Now().UTC().Year()\n}", "func (p *Satis) AmmountThisYear() (*Ammount, error) {\n\tnow := time.Now()\n\tprec := time.Date(now.Year(), time.Month(0), 0, 0, 0, 0, 0, now.Location())\n\tlast := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), 0, 0, now.Location())\n\tamm, err := p.getLongAmmount(prec, last)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn amm, nil\n}", "func (c *StatsIndexDatasourcesGetCall) FromDateYear(fromDateYear int64) *StatsIndexDatasourcesGetCall {\n\tc.urlParams_.Set(\"fromDate.year\", fmt.Sprint(fromDateYear))\n\treturn c\n}", "func (c *StatsIndexDatasourcesGetCall) FromDateYear(fromDateYear int64) *StatsIndexDatasourcesGetCall {\n\tc.urlParams_.Set(\"fromDate.year\", fmt.Sprint(fromDateYear))\n\treturn c\n}", "func yearFrac(startDate, endDate float64, basis int) formulaArg {\n\tstartTime, endTime := timeFromExcelTime(startDate, false), timeFromExcelTime(endDate, false)\n\tif startTime == endTime {\n\t\treturn newNumberFormulaArg(0)\n\t}\n\tvar dayDiff, daysInYear float64\n\tswitch basis {\n\tcase 0:\n\t\tdayDiff, daysInYear = yearFracBasis0(startDate, endDate)\n\tcase 1:\n\t\tdayDiff, daysInYear = yearFracBasis1(startDate, endDate)\n\tcase 2:\n\t\tdayDiff = endDate - startDate\n\t\tdaysInYear = 360\n\tcase 3:\n\t\tdayDiff = endDate - startDate\n\t\tdaysInYear = 365\n\tcase 4:\n\t\tdayDiff, daysInYear = yearFracBasis4(startDate, endDate)\n\tdefault:\n\t\treturn newErrorFormulaArg(formulaErrorNUM, \"invalid basis\")\n\t}\n\treturn newNumberFormulaArg(dayDiff / daysInYear)\n}", "func GetBeginningOfDay(t time.Time) time.Time {\n\tyear, month, day := t.Date()\n\tstartOfDay := time.Date(year, month, day, 0, 0, 0, 0, t.Location())\n\treturn startOfDay\n}", "func GetFractionalYear(year uint16, month time.Month, day uint8) float32 {\n\tvar t time.Time\n\tif year == 0 {\n\t\t// Use current date\n\t\tt = time.Now()\n\t} else {\n\t\tconst shortForm = \"2006-November-02\"\n\t\tt = time.Date(int(year), month, int(day), 0, 0, 0, 0, time.UTC)\n\t}\n\treturn float32(t.Year()) + float32(t.YearDay())/365\n}" ]
[ "0.84461635", "0.7129927", "0.7125371", "0.68977463", "0.67089003", "0.6379925", "0.63039315", "0.6301062", "0.6261816", "0.6249966", "0.6124489", "0.61114603", "0.6101744", "0.6064978", "0.6049439", "0.6020882", "0.6003487", "0.5986194", "0.59538805", "0.59198457", "0.5884688", "0.58750385", "0.57525057", "0.57313424", "0.57284236", "0.5701612", "0.5689002", "0.56845367", "0.5675566", "0.5652788", "0.5652657", "0.56497097", "0.5648659", "0.5646214", "0.56388813", "0.5622514", "0.557571", "0.55272573", "0.55190825", "0.551864", "0.5515371", "0.5507311", "0.5477355", "0.546246", "0.54571223", "0.5413749", "0.54028106", "0.5386056", "0.5385328", "0.53671134", "0.5362197", "0.5362197", "0.53547025", "0.53288126", "0.53283226", "0.53078544", "0.52998275", "0.5296995", "0.5284789", "0.5265275", "0.5260625", "0.5248134", "0.52435094", "0.5231615", "0.5199871", "0.51785046", "0.51785046", "0.51662844", "0.5164361", "0.5164209", "0.5162761", "0.51609707", "0.51534015", "0.51529276", "0.51488036", "0.51449144", "0.51411647", "0.51342577", "0.5119036", "0.5110743", "0.51065904", "0.5106439", "0.5095088", "0.50939935", "0.5061152", "0.50563", "0.5048873", "0.5022062", "0.50181735", "0.49985242", "0.4990635", "0.49893484", "0.4980282", "0.4980282", "0.49795437", "0.49619293", "0.49619293", "0.4954905", "0.49457178", "0.4944827" ]
0.81009567
1
Render : run the code generation
func (r *Ris) Render() { r.render() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *ginRenderJade) Render(w http.ResponseWriter, code int, data ...interface{}) error {\n\twriteHeader(w, code, \"text/html\")\n\tfile := data[0].(string)\n\targs := data[1]\n\treturn this.Template.RenderFileW(w, file, args)\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 (sw *Swgen) Run() error {\n\tif err := os.MkdirAll(sw.Target, os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\n\ttree, err := sw.Scan(sw.Source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmetadata := &Metadata{}\n\tcontent := template.HTML(\"\")\n\treturn sw.renderAll(tree, metadata, content)\n}", "func (e *ERBRenderer) Render(inputFilePath, outputFilePath string) (returnErr error) {\n\t// Create a temporary work directory\n\ttmpDir, err := ioutil.TempDir(\"\", \"bosh-erb-renderer\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to create temporary directory in erb renderer\")\n\t}\n\tdefer func() {\n\t\tif err = os.RemoveAll(tmpDir); err != nil {\n\t\t\treturnErr = errors.Wrap(err, \"failed to cleanup erb renderer temporary directory\")\n\t\t}\n\t}()\n\n\t// Write the ruby class to a file\n\trbClassFilePath := filepath.Join(tmpDir, rbClassFileName)\n\ttemplateEvaluationContextRb, err := rice.\n\t\tMustFindBox(\"rb\").\n\t\tBytes(\"template_evaluation_context.rb\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to load ruby class\")\n\t}\n\terr = ioutil.WriteFile(rbClassFilePath, templateEvaluationContextRb, 0600)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to write the rendering ruby class file\")\n\t}\n\n\t// Marshal the evaluation context\n\tevalContextBytes, err := yaml.Marshal(e.EvaluationContext)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to marshal the evaluation context\")\n\t}\n\tevaluationContextYAMLFilePath := filepath.Join(tmpDir, evaluationContextYAMLFileName)\n\terr = ioutil.WriteFile(evaluationContextYAMLFilePath, evalContextBytes, 0600)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to write the evaluation context yaml file\")\n\t}\n\n\t// Marshal instance information\n\tinstanceInfoBytes, err := yaml.Marshal(e.InstanceInfo)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to marshal instance runtime information\")\n\t}\n\tinstanceInfoYAMLFilePath := filepath.Join(tmpDir, instanceInfoYAMLFileName)\n\terr = ioutil.WriteFile(instanceInfoYAMLFilePath, instanceInfoBytes, 0600)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to write instance runtime information yaml file\")\n\t}\n\n\t// Run rendering\n\terr = run(rbClassFilePath, evaluationContextYAMLFilePath, e.JobSpecFilePath, instanceInfoYAMLFilePath, inputFilePath, outputFilePath)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to render template\")\n\t}\n\n\treturn nil\n}", "func (r *renderer) Render(w http.ResponseWriter, p ViewModel) {\n\tif r.config.Debug {\n\t\terr := r.initTemplates()\n\t\tif err != nil {\n\t\t\tlog.Printf(err.Error())\n\t\t}\n\t}\n\terr := r.templates.ExecuteTemplate(w, templateName, p)\n\tif err != nil {\n\t\tlog.Fatalln(err.Error())\n\t}\n}", "func (v *View) Render(w http.ResponseWriter, r *http.Request, data interface{}) {\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\tvar vd Data\n\tswitch d := data.(type) {\n\tcase Data:\n\t\tvd = d\n\tdefault:\n\t\tvd = Data{\n\t\t\tYield: data,\n\t\t}\n\t}\n\tvd.User = context.User(r.Context())\n\tvar buf bytes.Buffer\n\terr := v.Template.ExecuteTemplate(&buf, v.Layout, vd)\n\tif err != nil {\n\t\thttp.Error(w, \"Something went wrong. If the problem persists, please \"+\n\t\t\t\"email [email protected]\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\t// If we get here that means our template executed correctly and we can coy\n\t// the buffer to the ResponseWriter.\n\tio.Copy(w, &buf)\n}", "func (r *R) Render(w http.ResponseWriter) {\n\tWriteJSON(w, r.Code, r)\n}", "func (r *Renderer) Render(path string) error {\n\toutPath := outPath(path, r.OutDir, r.BaseDir)\n\n\tif err := os.MkdirAll(filepath.Dir(outPath), os.ModeDir); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create %s\", filepath.Dir(outPath))\n\t}\n\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to read %s\", path)\n\t}\n\n\tmarkdowned := blackfriday.MarkdownCommon(data)\n\n\t// we need document reader to modify markdowned html text, for example,\n\t// syntax highlight.\n\tdoc, err := goquery.NewDocumentFromReader(bytes.NewReader(markdowned))\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to parse markdown contents of %s\", path)\n\t}\n\tr.highlightCode(doc)\n\tr.handleImage(doc, filepath.Dir(path))\n\n\tcontent, _ := doc.Html()\n\tcontent = strings.Replace(content, \"<html><head></head><body>\", \"\", 1)\n\tcontent = strings.Replace(content, \"</body></html>\", \"\", 1)\n\n\toutput := r.Template\n\toutput = strings.Replace(output, \"{{{style}}}\", r.Style, -1)\n\toutput = strings.Replace(output, \"{{{content}}}\", content, -1)\n\n\terr = ioutil.WriteFile(outPath, []byte(output), os.ModeAppend)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to write %s\", outPath)\n\t}\n\n\treturn nil\n}", "func render(w http.ResponseWriter, r *http.Request, tmpl string, data interface{}) {\n\tlog.Printf(\"INFO > controllers/controllers.go > render(): %s\", tmpl)\n\n\t// Set the content type.\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\n\ttemplates[tmpl].Funcs(timestampFM())\n\ttemplates[tmpl].Funcs(permissionFM(r))\n\n\t// Execute the template.\n\terr := templates[tmpl].Execute(w, data)\n\tif err != nil {\n\t\tlog.Printf(\"ERROR > controllers.go > render(): %v\", err)\n\t}\n}", "func (c *Ctx) Render(code int, b []byte) {\n\tc.W.WriteHeader(code)\n\tc.W.Write(b)\n}", "func (r *innerRenderer) Render(w io.Writer, data interface{}, ctx Context, tpl ...string) error {\n\tt, err := r.parseFiles(tpl...)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn t.Execute(w, data)\n}", "func (t *GoatsTemplate) genRenderContent(output io.Writer) string {\n\tvar headProcessor processors.Processor = processors.NewHeadProcessor()\n\n\tvar argProcessor processors.Processor = processors.NewArgProcessor(t.Args)\n\theadProcessor.SetNext(argProcessor)\n\n\tt.buildProcessorChain(argProcessor, t.RootNode)\n\n\tctx := processors.NewTagContext(t.Parser.PkgMgr, t.pkgRefs, t.Parser.Settings.OutputFormat)\n\tif t.NeedsDocType {\n\t\tdocTypeProcessor := processors.NewDocTypeProcessor(t.Parser.DocTypeTag, t.Parser.DocTypeAttrs)\n\t\tdocTypeProcessor.SetNext(headProcessor)\n\t\theadProcessor = docTypeProcessor\n\t}\n\n\tvar renderBuffer bytes.Buffer\n\theadProcessor.Process(&renderBuffer, ctx)\n\treturn renderBuffer.String()\n}", "func (rf RendererFunc) Render(w io.Writer, v interface{}) error { return rf(w, v) }", "func (t Tmpl) Render(wr io.Writer, name string, args interface{}) error {\n\t// Check if app is running on dev mode\n\tif Config.Configuration.IsDev() {\n\n\t\t// Lock mutex\n\t\tt.rw.Lock()\n\t\tdefer t.rw.Unlock()\n\n\t\t// Reload all templates\n\t\tif err := t.LoadTemplates(\"views/\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Execute template and return error\n\treturn t.Tmpl.ExecuteTemplate(wr, name, args)\n}", "func (t Tmpl) Render(wr io.Writer, name string, args interface{}) error {\n\t// Check if app is running on dev mode\n\tif Config.Configuration.IsDev() {\n\n\t\t// Lock mutex\n\t\tt.rw.Lock()\n\t\tdefer t.rw.Unlock()\n\n\t\t// Reload all templates\n\t\tif err := t.LoadTemplates(\"views/\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Execute template and return error\n\treturn t.Tmpl.ExecuteTemplate(wr, name, args)\n}", "func (c *cartridge) Render() {\n\tc.Cls()\n\tc.PrintAt(fmt.Sprintf(\"counter:%d\", c.counter), c.x, c.y)\n}", "func Render(fn string, header string, tmpl string, datas []interface{}, linters []string) {\n\n\tf, err := os.OpenFile(fn, os.O_RDWR|os.O_CREATE, 0644)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = f.Truncate(0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Fprintln(f, \"// Code generated 'by go generate ./...'; DO NOT EDIT.\")\n\tfmt.Fprintln(f, \"\")\n\tfmt.Fprintln(f, header)\n\n\tt, err := template.New(\"foo\").Parse(tmpl)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor _, d := range datas {\n\t\terr = t.Execute(f, d)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\terr = f.Sync()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = f.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor _, linter := range linters {\n\t\tvar cmds []string\n\t\tswitch linter {\n\t\tcase \"gofmt\":\n\t\t\tcmds = []string{\"gofmt\", \"-s\", \"-w\", fn}\n\t\tcase \"unconvert\":\n\t\t\tcmds = []string{\"unconvert\", \"-v\", \"-apply\", \"./\"}\n\t\tdefault:\n\t\t\tpanic(\"unknown linter:\" + linter)\n\t\t}\n\n\t\tout, err := exec.Command(cmds[0], cmds[1:]...).CombinedOutput()\n\t\tif err != nil {\n\t\t\tfmt.Println(cmds)\n\t\t\tfmt.Println(string(out))\n\t\t\tfmt.Println(err)\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func (f *Format) Render() error {\n\tmodules := sortModules(f.Config.GetSource())\n\tdocument, err := buildDocument(f.Config.ToolVersion, modules[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpackages, otherLicenses, err := f.buildPackages(modules)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, err2 := os.Create(f.Config.Filename)\n\tif err2 != nil {\n\t\treturn err2\n\t}\n\t// todo organize file generation code below\n\t//Print DOCUMENT\n\tfile.WriteString(fmt.Sprintf(\"SPDXVersion: %s\\n\", document.SPDXVersion))\n\tfile.WriteString(fmt.Sprintf(\"DataLicense: %s\\n\", document.DataLicense))\n\tfile.WriteString(fmt.Sprintf(\"SPDXID: %s\\n\", document.SPDXID))\n\tfile.WriteString(fmt.Sprintf(\"DocumentName: %s\\n\", document.DocumentName))\n\tfile.WriteString(fmt.Sprintf(\"DocumentNamespace: %s\\n\", document.DocumentNamespace))\n\tfile.WriteString(fmt.Sprintf(\"Creator: %s\\n\", document.Creator))\n\tfile.WriteString(fmt.Sprintf(\"Created: %v\\n\\n\", document.Created))\n\t//Print Package\n\tfor _, pkg := range packages {\n\t\tfile.WriteString(fmt.Sprintf(\"##### Package representing the %s\\n\\n\", pkg.PackageName))\n\t\tgeneratePackage(file, pkg)\n\t\tif pkg.RootPackage {\n\t\t\tfile.WriteString(fmt.Sprintf(\"Relationship: %s DESCRIBES %s \\n\\n\", document.SPDXID, pkg.SPDXID))\n\t\t}\n\t\t//Print DEPS ON\n\t\tif len(pkg.DependsOn) > 0 {\n\t\t\tfor _, subPkg := range pkg.DependsOn {\n\t\t\t\tfile.WriteString(fmt.Sprintf(\"Relationship: %s DEPENDS_ON %s \\n\", pkg.SPDXID, subPkg.SPDXID))\n\t\t\t}\n\t\t\tfile.WriteString(\"\\n\")\n\t\t}\n\n\t}\n\n\t//Print Other Licenses\n\tif len(otherLicenses) > 0 {\n\t\tfile.WriteString(\"##### Non-standard license\\n\\n\")\n\t\tfor lic := range otherLicenses {\n\t\t\tfile.WriteString(fmt.Sprintf(\"LicenseID: LicenseRef-%s\\n\", lic))\n\t\t\tfile.WriteString(fmt.Sprintf(\"ExtractedText: %s\\n\", otherLicenses[lic].ExtractedText))\n\t\t\tfile.WriteString(fmt.Sprintf(\"LicenseName: %s\\n\", otherLicenses[lic].Name))\n\t\t\tfile.WriteString(fmt.Sprintf(\"LicenseComment: %s\\n\\n\", otherLicenses[lic].Comments))\n\t\t}\n\t}\n\n\t// Write to file\n\tfile.Sync()\n\n\treturn nil\n}", "func (ctx *Context) Render(bytes []byte) {\n\t//debug\n\t//fmt.Println(\"response msg = \", string(bytes))\n\tctx.Writer.WriteHeader(200)\n\t_, err := ctx.Writer.Write(bytes)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func Render(files [][]byte, maxIt uint, debug bool) (\n\t[]byte, error,\n) {\n\tinfl, debugParse, err := parseFiles(files)\n\tif err != nil {\n\t\tif debug {\n\t\t\twriteDebug(\"parsing\", debugParse)\n\t\t}\n\t\treturn []byte{}, err\n\t}\n\tres, debugRender, err := renderTmpl(infl, maxIt)\n\tif err != nil {\n\t\tif debug {\n\t\t\twriteDebug(\"render\", debugRender)\n\t\t}\n\t\treturn []byte{}, err\n\t}\n\treturn res, nil\n}", "func render(w http.ResponseWriter, tmpl string, p *page.Page) {\n\tif err := page.Templates.ExecuteTemplate(w, tmpl+\".html\", p); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\tlog.Println(err)\n\t}\n}", "func (e *rawData) Render(w io.Writer) (int, error) { return w.Write([]byte(e.content)) }", "func (p *Generator) Run() {\n\tp.Title = p.ProjectTitle\n\tfileName := markdownName(p.OutputFileName, path.Base(p.ProjectTitle))\n\tp.Module = p.RootModule\n\tif err := p.CreateMarkdown(p.Templates[p.StartTemplateIndex], path.Join(p.OutputDir, fileName), p); err != nil {\n\t\tp.Log.Error(\"Error creating project markdown:\", err)\n\t}\n\n\tvar progress *pb.ProgressBar\n\tdefer func() {\n\t\tif progress != nil && progress.IsStarted() {\n\t\t\tprogress.Finish()\n\t\t\tfmt.Printf(\"The generated files are output to folder `%s`\\n\", p.OutputDir)\n\t\t}\n\t}()\n\n\tvar wg sync.WaitGroup\n\tvar diagramCreator = func(inMap map[string]string, f func(fs afero.Fs, filename string, data string) error, progress *pb.ProgressBar) {\n\t\tfor fileName, contents := range inMap {\n\t\t\twg.Add(1)\n\t\t\tgo func(fileName, contents string) {\n\t\t\t\tmaxCreators <- struct{}{}\n\t\t\t\tdefer func() { <-maxCreators }()\n\n\t\t\t\tvar err = f(p.Fs, fileName, contents)\n\t\t\t\tif err != nil {\n\t\t\t\t\tp.Log.Error(\"Error generating file:\", err)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t\tif progress != nil {\n\t\t\t\t\tprogress.Increment()\n\t\t\t\t}\n\t\t\t\twg.Done()\n\t\t\t}(fileName, contents)\n\t\t}\n\t}\n\n\tif p.Mermaid {\n\t\tprogress = pb.Full.Start(len(p.MermaidFilesToCreate))\n\t\tdiagramCreator(p.MermaidFilesToCreate, GenerateAndWriteMermaidDiagram, progress)\n\t} else {\n\t\tif strings.Contains(p.PlantumlService, \".jar\") {\n\t\t\tif !p.Server {\n\t\t\t\tdiagramCreator(p.FilesToCreate, p.PUMLFile, progress)\n\t\t\t\tstart := time.Now()\n\t\t\t\tif err := PlantUMLJava(p.PlantumlService, p.OutputDir); err != nil {\n\t\t\t\t\tp.Log.Error(err)\n\t\t\t\t}\n\t\t\t\telapsed := time.Since(start)\n\t\t\t\tfmt.Println(\"Generating took \", elapsed)\n\t\t\t}\n\t\t} else {\n\t\t\tprogress = pb.Full.Start(len(p.FilesToCreate))\n\t\t\tdiagramCreator(p.FilesToCreate, HttpToFile, progress)\n\t\t}\n\t}\n\n\tif p.Redoc {\n\t\tif progress.IsStarted() {\n\t\t\tprogress.SetTotal(progress.Total() + int64(len(p.RedocFilesToCreate)))\n\t\t} else {\n\t\t\tprogress = pb.Full.Start(len(p.RedocFilesToCreate))\n\t\t}\n\t\tdiagramCreator(p.RedocFilesToCreate, GenerateAndWriteRedoc, progress)\n\t}\n\n\tif (p.ImageTags || p.DisableImages) && !p.Redoc {\n\t\tlogrus.Info(\"Skipping Image creation\")\n\t\treturn\n\t}\n\n\twg.Wait()\n}", "func Render(c Compo) {\n\tUI(func() { render(c) })\n}", "func (r *renderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {\n\tctx := data.(pongo2.Context)\n\n\tt, err := r.TemplateSet.FromFile(name)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get template from file\")\n\t}\n\n\treturn t.ExecuteWriter(ctx, w)\n}", "func Render(rawBytes []byte, urlPrefix string, metas map[string]string, isWiki bool) []byte {\n\thtmlWriter := org.NewHTMLWriter()\n\n\trenderer := &Renderer{\n\t\tHTMLWriter: htmlWriter,\n\t\tURLPrefix: urlPrefix,\n\t\tIsWiki: isWiki,\n\t}\n\n\thtmlWriter.ExtendingWriter = renderer\n\n\tres, err := org.New().Silent().Parse(bytes.NewReader(rawBytes), \"\").Write(renderer)\n\tif err != nil {\n\t\tlog.Error(\"Panic in orgmode.Render: %v Just returning the rawBytes\", err)\n\t\treturn rawBytes\n\t}\n\treturn []byte(res)\n}", "func (t *Template) Render(ctx *gear.Context, w io.Writer, name string, data interface{}) (err error) {\n\tdir, _ := os.Getwd()\n\tname = filepath.Join(dir, \"view\", name+\".html\")\n\ttmpl := template.Must(template.ParseFiles(name))\n\n\terr = tmpl.Execute(w, data)\n\tif err != nil {\n\t\tlogging.Println(err)\n\t}\n\n\treturn\n}", "func (a *SDK) Render(domain string, dir string) {\n\tfs := http.FileServer(http.Dir(dir))\n\t//http.Handle(\"/preview/\", http.StripPrefix(\"/preview\", fs))\n\thttp.Handle(\"/\", http.StripPrefix(\"/\", fs))\n}", "func (t *Renderer) Render(\n\tw io.Writer,\n\tname string,\n\tdata interface{},\n\tc echo.Context,\n) error {\n\tif t.debug {\n\t\tt.ReloadTemplates()\n\t}\n\n\treturn t.template.ExecuteTemplate(w, name, data)\n}", "func (f *Frontend) Render(w io.Writer, name string, data interface{}) error {\n\tfuncMap := template.FuncMap{\n\t\t\"githubUrl\": func(s string) string {\n\t\t\tr := strings.NewReplacer(\"https://\", \"\", \"http://\", \"\")\n\t\t\treturn r.Replace(s)\n\t\t},\n\t}\n\n\t// TODO: implement templates caching\n\ttmpl, err := template.New(name).Funcs(funcMap).ParseFiles(path.Join(f.cfg.TemplateFolder, \"layout.html\"), path.Join(f.cfg.TemplateFolder, name))\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Template reading error. Details: %s\", name, err.Error()))\n\t}\n\n\terr = tmpl.ExecuteTemplate(w, \"layout\", data)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Template rendering error. Details: %s\", name, err.Error()))\n\t}\n\n\treturn nil\n}", "func (g *Generator) Execute(out io.Writer) error {\n\tvar b bytes.Buffer\n\tg.o = &b // becasue of post process, we need to buffer out.\n\tvar err error\n\tg.t = template.New(\"\").Funcs(g.funcs)\n\tfor _, tpl := range g.tpls {\n\t\tg.t, err = g.t.Parse(tpl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr = g.t.Execute(g.o, g.data)\n\tg.t = nil\n\tg.o = nil\n\ts := b.String()\n\tb.Truncate(0)\n\tfor _, p := range g.post {\n\t\ts = p(s)\n\t}\n\tg.post = g.post[:0]\n\tout.Write([]byte(s))\n\treturn err\n}", "func (c *Ctx) Render(f string, optionalBind ...interface{}) error {\n\tvar err error\n\tvar binding interface{}\n\tbinds := make(map[string]interface{})\n\tc.VisitUserValues(func(k []byte, v interface{}) {\n\t\tbinds[BytesToString(k)] = v\n\t})\n\n\tif len(optionalBind) > 0 {\n\t\tbinding = optionalBind[0]\n\t} else {\n\t\tbinding = binds\n\t}\n\n\tif c.Core.Views == nil {\n\t\terr = fmt.Errorf(\"Render: Not Initial Views\")\n\t\tLog.Error(err.Error())\n\t\treturn err\n\t}\n\n\tif c.theme != \"\" {\n\t\tc.Core.Views.DoTheme(c.theme)\n\t}\n\n\tc.Response.Header.SetContentType(MIMETextHTMLCharsetUTF8)\n\terr = c.Core.Views.ExecuteWriter(c.RequestCtx.Response.BodyWriter(), f, binding)\n\tif err != nil {\n\t\tc.Error(err.Error(), StatusInternalServerError)\n\t}\n\treturn err\n}", "func (v *View) Render(w http.ResponseWriter, r *http.Request, yield interface{}, ErrorMessages []string) {\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\n\tvar vd Data\n\tvd.User.ID = r.Header.Get(\"userID\")\n\tadmin, err := strconv.ParseBool(r.Header.Get(\"admin\"))\n\tif err != nil {\n\t\tvd.User.Admin = false\n\t} else {\n\t\tvd.User.Admin = admin\n\t}\n\tvd.ErrorMessages = ErrorMessages\n\tvd.Yield = yield\n\tvd.Messages.Success = flash.GetFlash(w, r, constant.Flash.Success)\n\tvd.Messages.Info = flash.GetFlash(w, r, constant.Flash.Info)\n\n\tv.Template.ExecuteTemplate(w, v.Layout, vd)\n}", "func (ri *Interpreter) Render(w io.Writer, file *parser.File, hr table.Renderer) error {\n\tvar err error\n\tbw := bufio.NewWriter(w) //buffer the writer to speed up writing\n\ttables := file.Tables()\n\t_ = hr.SetWriter(bw)\n\tif err = hr.SetSettings(ri.settings); err != nil {\n\t\treturn fmt.Errorf(\"failed to render table: %s\", err)\n\t}\n\t_ = hr.SetTables(tables)\n\tif err = hr.StartFile(); err != nil {\n\t\treturn fmt.Errorf(\"failed to render table: %s\", err)\n\t}\n\tfor i, t := range tables {\n\t\tif err = t.Run(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to run one or more commands for table: %s\", err)\n\t\t}\n\t\tri.job.UI.Logf(\"****processed contents of table %d\\n%v\\n\", i+1, t.ProcessedTableContents().DebugString())\n\t\tif err = t.Render(w, hr); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to render table %d: %s\", i+1, err)\n\t\t}\n\t}\n\tif err = hr.EndFile(); err != nil {\n\t\treturn fmt.Errorf(\"failed to render table: %s\", err)\n\t}\n\treturn bw.Flush() //flush to ensure all changes are written to the writer\n}", "func Render(c Compo) {\n\tdriver.CallOnUIGoroutine(func() {\n\t\tdriver.Render(c)\n\t})\n}", "func Render(w http.ResponseWriter, r *http.Request, v Renderer) error {\n\tif err := renderer(w, r, v); err != nil {\n\t\treturn err\n\t}\n\tRespond(w, r, v)\n\treturn nil\n}", "func Render(c *Doc) {\n\n\tfmt.Println(c.LatexTemplate)\n\n\tfiles, _ := filepath.Glob(\"templates/*.tex\")\n\tfmt.Println(files)\n\n\tt, err := template.New(c.LatexTemplate).Delims(\"[[\", \"]]\").ParseFiles(\"templates/\" + c.LatexTemplate,\n\t\t\"templates/partials/header.tex\", \"templates/partials/base.tex\", \"sections/main.tex\") //templates/doc\n\tcheckError(err)\n\n\t// get a file handle io.Writer object\n\tfileHandle, _ := os.Create(\"templates/output.tex\")\n\n\t// Template parameters are in doc\n\terr = t.Execute(fileHandle, c)\n\tdefer fileHandle.Close()\n\n\t// write to console also, Writer can do anything\n\t// we can write to an S3 bucket if we want or a socket\n\terr = t.Execute(os.Stdout, c)\n\n\tcheckError(err)\n}", "func render(fset *token.FileSet, x interface{}) string {\n\tvar buf bytes.Buffer\n\tif err := printer.Fprint(&buf, fset, x); err != nil {\n\t\tpanic(err)\n\t}\n\treturn buf.String()\n}", "func render(fset *token.FileSet, x interface{}) string {\n\tvar buf bytes.Buffer\n\tif err := printer.Fprint(&buf, fset, x); err != nil {\n\t\tpanic(err)\n\t}\n\treturn buf.String()\n}", "func (s *Server) Render(w io.Writer, name string, data interface{}, c echo.Context) error {\n\treturn s.Templates.ExecuteTemplate(w, name, data)\n}", "func (p *Generator) Run() {\n\ttype mWrap struct {\n\t\t*sysl.Module\n\t\tTitle string\n\t\tLinks map[string]string\n\t}\n\tm := mWrap{Module: p.Module, Title: p.Title}\n\tfileName := markdownName(p.OutputFileName, strings.ReplaceAll(path.Base(p.Title), \".sysl\", \"\"))\n\tif err := p.CreateMarkdown(p.ProjectTempl, path.Join(p.OutputDir, fileName), m); err != nil {\n\t\tp.Log.Error(err)\n\t}\n\tmacroPackages := p.ModuleAsMacroPackage(p.Module)\n\tvar packages map[string]*sysl.Module\n\tvar macroPackageName string\n\t// We either execute this function when we're iterating through the simple packages\n\t// or if there are \"macroPackages\" defined on the ~project app (their endpoints)\n\tpackageFunc := func() {\n\t\tfor _, packageName := range SortedKeys(packages) {\n\t\t\tpkg := packages[packageName]\n\t\t\tp.CurrentDir = path.Join(macroPackageName, packageName)\n\t\t\tfileName := markdownName(p.OutputFileName, packageName)\n\t\t\tfullOutputName := path.Join(p.OutputDir, p.CurrentDir, fileName)\n\t\t\tif err := p.CreateMarkdown(p.PackageTempl, fullOutputName, pkg); err != nil {\n\t\t\t\tp.Log.Error(errors.Wrap(err, \"error in generating \"+fullOutputName))\n\t\t\t}\n\t\t}\n\t}\n\tswitch len(macroPackages) {\n\tcase 0, 1:\n\t\tpackages = p.ModuleAsPackages(p.Module)\n\t\tpackageFunc()\n\tdefault:\n\t\tfor _, key := range SortedKeys(macroPackages) {\n\t\t\tmacroPackageName = key\n\t\t\tmoduleMap := macroPackages[macroPackageName]\n\t\t\tmodule := createModuleFromSlices(p.Module, SortedKeys(moduleMap))\n\t\t\tpackages = p.ModuleAsPackages(module)\n\t\t\tfileName := markdownName(p.OutputFileName, macroPackageName)\n\t\t\tmacroPackageFileName := path.Join(p.OutputDir, macroPackageName, fileName)\n\t\t\tp.CurrentDir = macroPackageName\n\t\t\tm := mWrap{Module: module, Title: macroPackageName, Links: map[string]string{\"Back\": \"../\" + p.OutputFileName}}\n\t\t\terr := p.CreateMarkdown(p.ProjectTempl, macroPackageFileName, m)\n\t\t\tif err != nil {\n\t\t\t\tp.Log.Error(err)\n\t\t\t}\n\t\t\tpackageFunc()\n\t\t}\n\t}\n\tvar wg sync.WaitGroup\n\tvar progress *pb.ProgressBar\n\tvar completedDiagrams int64\n\tvar diagramCreator = func(inMap map[string]string, f func(fs afero.Fs, filename string, data string) error) {\n\t\tfor fileName, contents := range inMap {\n\t\t\twg.Add(1)\n\t\t\tgo func(fileName, contents string) {\n\t\t\t\tvar err = f(p.Fs, path.Join(p.OutputDir, fileName), contents)\n\t\t\t\tif err != nil {\n\t\t\t\t\tp.Log.Error(err)\n\t\t\t\t}\n\t\t\t\tprogress.Increment()\n\t\t\t\twg.Done()\n\t\t\t\tcompletedDiagrams++\n\t\t\t}(fileName, contents)\n\t\t}\n\t}\n\n\tif p.Mermaid {\n\t\tprogress = pb.StartNew(len(p.MermaidFilesToCreate))\n\t\tfmt.Println(\"Generating Mermaid diagrams:\")\n\t\tdiagramCreator(p.MermaidFilesToCreate, GenerateAndWriteMermaidDiagram)\n\t}\n\tif p.ImageTags || p.DisableImages {\n\t\tlogrus.Info(\"Skipping Image creation\")\n\t\treturn\n\t}\n\tprogress = pb.StartNew(len(p.FilesToCreate) + len(p.MermaidFilesToCreate))\n\tprogress.SetCurrent(completedDiagrams)\n\tfmt.Println(\"Generating diagrams:\")\n\tdiagramCreator(p.FilesToCreate, HttpToFile)\n\n\twg.Wait()\n\tprogress.Finish()\n}", "func (c *Controller) Render() error {\n\tif !c.EnableRender {\n\t\treturn nil\n\t}\n\trb, err := c.RenderBytes()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.Ctx.ResponseWriter.Header().Get(\"Content-Type\") == \"\" {\n\t\tc.Ctx.Output.Header(\"Content-Type\", \"text/html; charset=utf-8\")\n\t}\n\n\treturn c.Ctx.Output.Body(rb)\n}", "func render(template string, def definition, params map[string]interface{}) (string, error) {\n\tctx := plush.NewContext()\n\tctx.Set(\"camelize_down\", camelizeDown)\n\tctx.Set(\"def\", def)\n\tctx.Set(\"params\", params)\n\ts, err := plush.Render(string(template), ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn s, nil\n}", "func (vhs *VHS) Render() error {\n\t// Apply Loop Offset by modifying frame sequence\n\tif err := vhs.ApplyLoopOffset(); err != nil {\n\t\treturn err\n\t}\n\n\t// Generate the video(s) with the frames.\n\tvar cmds []*exec.Cmd\n\tcmds = append(cmds, MakeGIF(vhs.Options.Video))\n\tcmds = append(cmds, MakeMP4(vhs.Options.Video))\n\tcmds = append(cmds, MakeWebM(vhs.Options.Video))\n\tcmds = append(cmds, MakeScreenshots(vhs.Options.Screenshot)...)\n\n\tfor _, cmd := range cmds {\n\t\tif cmd == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\tlog.Println(string(out))\n\t\t}\n\t}\n\n\treturn nil\n}", "func (v *View) Render(w http.ResponseWriter, r *http.Request, data interface{}) {\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\tvar vd Data\n\tswitch d := data.(type) {\n\tcase Data:\n\t\tvd = d\n\tdefault:\n\t\tvd = Data{\n\t\t\tYield: data,\n\t\t}\n\t}\n\t// if alert := getAlert(r); alert != nil && vd.Alert == nil {\n\tif alert := getAlert(r); alert != nil {\n\t\tvd.Alert = alert\n\t\tclearAlert(w)\n\t}\n\tvd.User = context.User(r.Context())\n\tvar buf bytes.Buffer\n\tcsrfField := csrf.TemplateField(r)\n\ttpl := v.Template.Funcs(template.FuncMap{\n\t\t\"csrfField\": func() template.HTML {\n\t\t\treturn csrfField\n\t\t},\n\t})\n\tif err := tpl.ExecuteTemplate(&buf, v.Layout, vd); err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, \"Something went wrong. Please email support\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tio.Copy(w, &buf)\n}", "func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {\n\n\t// Add global methods if data is a map\n\tif viewContext, isMap := data.(map[string]interface{}); isMap {\n\t\tviewContext[\"reverse\"] = c.Echo().Reverse\n\t}\n\n\treturn t.templates.ExecuteTemplate(w, name, data)\n}", "func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {\n\n\t// Add global methods if data is a map\n\tif viewContext, isMap := data.(map[string]interface{}); isMap {\n\t\tviewContext[\"reverse\"] = c.Echo().Reverse\n\t}\n\n\treturn t.templates.ExecuteTemplate(w, name, data)\n}", "func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {\n\n\t// Add global methods if data is a map\n\tif viewContext, isMap := data.(map[string]interface{}); isMap {\n\t\tviewContext[\"reverse\"] = c.Echo().Reverse\n\t}\n\n\treturn t.templates.ExecuteTemplate(w, name, data)\n}", "func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {\n\n\t// Add global methods if data is a map\n\tif viewContext, isMap := data.(map[string]interface{}); isMap {\n\t\tviewContext[\"reverse\"] = c.Echo().Reverse\n\t}\n\n\treturn t.templates.ExecuteTemplate(w, name, data)\n}", "func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {\n\n\t// Add global methods if data is a map\n\tif viewContext, isMap := data.(map[string]interface{}); isMap {\n\t\tviewContext[\"reverse\"] = c.Echo().Reverse\n\t}\n\n\treturn t.templates.ExecuteTemplate(w, name, data)\n}", "func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {\n\n\t// Add global methods if data is a map\n\tif viewContext, isMap := data.(map[string]interface{}); isMap {\n\t\tviewContext[\"reverse\"] = c.Echo().Reverse\n\t}\n\n\treturn t.templates.ExecuteTemplate(w, name, data)\n}", "func (c *Context) Render(content string) {\n\t// Write response\n\tc.Response.Write([]byte(content))\n}", "func Render(w http.ResponseWriter, req *http.Request, view Viewable, code int) error {\n\taccept := req.Header.Get(\"Accept\")\n\tif accept == \"\" {\n\t\treturn RenderJSON(w, view, code)\n\t}\n\tfor _, h := range strings.Split(accept, \",\") {\n\t\tmedia, _, err := mime.ParseMediaType(h)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch media {\n\t\tcase \"text/html\", \"text/*\":\n\t\t\tv, ok := view.(Renderable)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn RenderHTML(w, v, code)\n\t\tcase \"application/json\", \"application/*\", \"*/*\":\n\t\t\treturn RenderJSON(w, view, code)\n\t\tcase \"text/plain\":\n\t\t\treturn RenderPlain(w, view, code)\n\t\t}\n\t}\n\treturn Abort(w, http.StatusNotAcceptable)\n}", "func Render(w http.ResponseWriter, name string, d map[string]interface{}) {\n\tif e := tpl.ExecuteTemplate(w, name, d); e != nil {\n\t\thttp.Error(w, e.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {\n\t// Add global methods if data is a map\n\tif viewContext, isMap := data.(map[string]interface{}); isMap {\n\t\tviewContext[\"reverse\"] = c.Echo().Reverse\n\t}\n\n\ttmpl, ok := t.Templates[name]\n\tif !ok {\n\t\terr := errors.New(\"Template not found -> \" + name)\n\t\treturn err\n\t}\n\treturn tmpl.ExecuteTemplate(w, \"base.html\", data)\n}", "func (t tag) Render() string {\n return t.render()\n}", "func Render(w io.Writer, template string, data interface{}) error {\n\tif err := renderer.HTML(w, 0, template, data); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *Server) render(w http.ResponseWriter, r *http.Request, templateName string, ctx pongo2.Context) {\n\tt, err := pongo2.FromFile(path.Join(s.templateDir, templateName))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tctx[\"request\"] = r\n\tctx[\"alerts\"] = s.getAlerts(w, r)\n\tctx[\"current_user\"] = context.Get(r, contextCurrentUser).(*db.User)\n\tctx[\"site_title\"] = s.config.GetString(configSiteTitle)\n\tb, err := t.ExecuteBytes(ctx)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}", "func (p *Page) render(f *os.File) error {\n\tt, err := template.ParseFiles(p.Template)\n\n\tif (err != nil) {\n\t\treturn err\n\t}\n\n\treturn t.Execute(f, p)\n}", "func main() {\n\terr := tpl.ExecuteTemplate(os.Stdout, \"tpl.gohtml\", nil)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}", "func (c *Context) Render(code int, r render.Render) {\n\t// 设置response的content-type\n\tr.WriteContentType(c.Writer)\n\t// lt 0 不设置 http status\n\tif code > 0 {\n\t\tc.Status(code)\n\t}\n\t// 是否允许设置body\n\tif !bodyAllowForStatus(code) {\n\t\treturn\n\t}\n\t// 写上body\n\tif err := r.Render(c.Writer); err != nil {\n\t\tc.Error = err\n\t\treturn\n\t}\n}", "func (r *oauthProxy) Render(w io.Writer, name string, data interface{}) error {\n\treturn r.templates.ExecuteTemplate(w, name, data)\n}", "func (g *Generator) Generate(req *common.Req, res *common.Res) error {\n\to := &common.Op{\n\t\tName: \"js\",\n\t\tTemplate: IndexTemplate,\n\t\tPathFunc: pathfunc(\"index\"),\n\t\tDoNotFormat: true,\n\t\tRemoveNewLines: true,\n\t}\n\n\tif err := common.ProcesRoot(o, req, res); err != nil {\n\t\treturn err\n\t}\n\n\to = &common.Op{\n\t\tName: \"js\",\n\t\tTemplate: RequestTemplate,\n\t\tPathFunc: pathfunc(\"_request\"),\n\t\tDoNotFormat: true,\n\t\tRemoveNewLines: true,\n\t}\n\n\tif err := common.ProcesRoot(o, req, res); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Codegen(dir string, b *bytes.Buffer, out string) {\n\ttd := CollectTemplateData(dir)\n\tWritePackage(\"00-main.go.tmpl\", \"templates/*\", b, td, map[string]interface{}{\n\t\t\"toReceiverCase\": toReceiverCase,\n\t\t\"lowerFirst\": lowerFirst,\n\t\t\"toLower\": strings.ToLower,\n\t\t\"TStringifyField\": TStringifyField,\n\t\t\"TParseField\": TParseField,\n\t})\n\tsrc, err := format.Source(b.Bytes())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tioutil.WriteFile(out, src, 0644)\n}", "func (t *TemplateViews) Render(w io.Writer, name string, data interface{}, c echo.Context) error {\n\n\t// Add global methods if data is a map\n\tif viewContext, isMap := data.(map[string]interface{}); isMap {\n\t\tviewContext[\"reverse\"] = c.Echo().Reverse\n\t}\n\n\treturn t.templates.ExecuteTemplate(w, name, data)\n}", "func render(w http.ResponseWriter, tmpl string, context Context) {\n\ttmplList := []string{\"views/base.html\",\n\t\tfmt.Sprintf(\"views/%s.html\", tmpl)}\n\tt, err := template.ParseFiles(tmplList...)\n\tcheckErr(err)\n\tcheckErr(t.Execute(w, context))\n}", "func render(template_content string, data TemplateData) string {\n temp, err := template.New(\"html\").Parse(template_content)\n if err!=nil {\n os.Stderr.WriteString(err.Error() + \"\\n\")\n } else {\n buf := new(strings.Builder)\n err = temp.Execute(buf, data)\n if err!=nil {\n os.Stderr.WriteString(err.Error() + \"\\n\")\n }\n output := buf.String()\n return output\n }\n return \"\"\n}", "func Render(colorCode int, fontSize int, content string) string {\n\treturn \"\\033[\" + strconv.Itoa(fontSize) + \";\" + strconv.Itoa(colorCode) + \"m\" + content + reset\n}", "func ExampleRender() {\n\tconst s = `\n\tFirst Line\n\tSecond Line\n\tThird Line\n\tHello\n\tThis is go-music`\n\n\tfmt.Println(RenderText(s, Spring))\n\tfmt.Println(RenderText(s, Autumn))\n\tfmt.Println(RenderText(s, Winter))\n\tfmt.Println(RenderText(s, Rose))\n\tfmt.Println(RenderText(s, Valentine))\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 (a ArithmeticPage) Render(w http.ResponseWriter, req *http.Request) {\n\tRenderPage(a, w, req, true)\n}", "func (m KubedgeBaseManager) Render(ctx context.Context) (*av1.SubResourceList, error) {\n\treturn m.Renderer.RenderFile(m.PhaseName, m.PhaseNamespace, m.Source.Location)\n}", "func Render(typ Type, input any, urlPrefix string, metas map[string]string) []byte {\n\tvar rawBytes []byte\n\tswitch v := input.(type) {\n\tcase []byte:\n\t\trawBytes = v\n\tcase string:\n\t\trawBytes = []byte(v)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unrecognized input content type: %T\", input))\n\t}\n\n\turlPrefix = strings.TrimRight(strings.ReplaceAll(urlPrefix, \" \", \"%20\"), \"/\")\n\tvar rawHTML []byte\n\tswitch typ {\n\tcase TypeMarkdown:\n\t\trawHTML = RawMarkdown(rawBytes, urlPrefix)\n\tcase TypeOrgMode:\n\t\trawHTML = RawOrgMode(rawBytes, urlPrefix)\n\tdefault:\n\t\treturn rawBytes // Do nothing if syntax type is not recognized\n\t}\n\n\trawHTML = postProcessHTML(rawHTML, urlPrefix, metas)\n\treturn SanitizeBytes(rawHTML)\n}", "func (m *Mosaic) Render() error {\n\tif err := m.target.Load(); err != nil {\n\t\treturn err\n\t}\n\tif err := m.tiles.Load(); err != nil {\n\t\treturn err\n\t}\n\tm.out = m.generate()\n\treturn nil\n}", "func (e *Engine) Render(arg string) (string, error) {\n\n\tif len(e.fmap) == 0 {\n\t\te.initFuncMap()\n\t}\n\n\t_, err := e.template.Parse(arg)\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, renderErr)\n\t}\n\n\tvar tpl bytes.Buffer\n\terr = e.template.Execute(&tpl, \"\")\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, renderErr)\n\t}\n\n\treturn tpl.String(), nil\n}", "func Render(c http.ResponseWriter, r *http.Request, title, name string, data interface{}) {\n\tif WouldUseJson(r) {\n\t\tenc := json.NewEncoder(c)\n\t\terr := enc.Encode(data)\n\t\tif err != nil {\n\t\t\tError500(c, r, err)\n\t\t}\n\t\treturn\n\t}\n\tvar p PageInfo\n\tif title == \"\" {\n\t\ttitle = strings.ToTitle(moduleName)\n\t}\n\t// \tif moduleName == \"unknown\" {\n\t// \t\tlog.Println(\"Warning: Attempting to render a template without moduleName being set! Call SetModuleName during the initialization of your module in order to correct this (in main()).\")\n\t// \t}\n\tp.Title = title\n\t// Removed the modulename because it's not needed in the new framework. However, this will break things in the old framework. *sigh*...\n\tp.Name = /*moduleName + \"/\" + */ name\n\tp.Request = r\n\tperms, err := perms.Get(r)\n\tif err != nil {\n\t\tlog.Printf(\"Warning: Error getting page permissions for %s: %s\", r.URL, err)\n\t}\n\tp.Perms = perms\n\tp.Object = data\n\n\terr = Execute(c, &p)\n\tif err != nil {\n\t\tc.WriteHeader(500)\n\t\tfmt.Fprintln(c, \"FATAL ERROR:\", err)\n\t\treturn\n\t}\n}", "func (s *Server) Render(w ResponseWriter, r *http.Request) {\n\tif w.Written() {\n\t\treturn\n\t}\n\tif err := s.renderTemplate(w, r); err != nil {\n\t\tw.Header().Set(\"Content-Type\", \"text/plain; charset=utf-8\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"Error executing template: %s\\n\", err)\n\t}\n}", "func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {\n\treturn t.templates.ExecuteTemplate(w, name, data)\n}", "func (c *Car) Render(out chan<- string) {\n defer close(out) // Always close the channel!\n\n var vs string\n if vs = os.Getenv(\"BULLETTRAIN_CAR_VIRTUALENV_SYMBOL_ICON\"); vs == \"\" {\n vs = virtualenvSymbolIcon\n }\n\n var vsp string\n if vsp = os.Getenv(\"BULLETTRAIN_CAR_VIRTUALENV_SYMBOL_PAINT\"); vsp == \"\" {\n vsp = virtualenvSymbolPaint\n }\n\n var s string\n if s = os.Getenv(\"BULLETTRAIN_CAR_VIRTUALENV_TEMPLATE\"); s == \"\" {\n s = carTemplate\n }\n\n funcMap := template.FuncMap{\n // Pipeline functions for colouring.\n \"c\": func(t string) string { return ansi.Color(t, c.GetPaint()) },\n \"cs\": func(t string) string { return ansi.Color(t, vsp) },\n }\n\n tpl := template.Must(template.New(\"python\").Funcs(funcMap).Parse(s))\n data := struct {\n VenvIcon string\n Venv string\n }{\n VenvIcon: virtualenvSymbolIcon,\n Venv: path.Base(os.Getenv(\"VIRTUAL_ENV\")),\n }\n fromTpl := new(bytes.Buffer)\n err := tpl.Execute(fromTpl, data)\n if err != nil {\n log.Fatalf(\"Can't generate the python template: %s\", err.Error())\n }\n\n out <- fromTpl.String()\n}", "func (t *TemplateManager) Render(w io.Writer, name string, data interface{}) error {\n\tstack := []*Template{}\n\ttplSrc, err := t.getSrc(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = t.push(&stack, tplSrc, name)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttpl, err := t.assemble(stack)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif tpl == nil {\n\t\treturn Errorf(\"Nil template named %s\", name)\n\t}\n\n\terr = tpl.Execute(w, data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (script Script) RenderHTML() {\n\tsymbols := []string{}\n\ttemplateHTML := `\n<!DOCTYPE html>\n<html>\n <head>\n <title>Writing System</title>\n <style type=\"text/css\">\n body, html { font-size: 28px; }\n div.container { display: flex; flex-wrap: wrap; width: 1600px; margin: 1rem auto; }\n div.cell { width: 100px; height: 100px; margin: 1rem; text-align: center; font-weight: 700; }\n div.cell > img { display: block; }\n </style>\n </head>\n <body>\n\t\t<div class=\"container\">\n\t\t\t{{range $index, $element := .}}\n <div class=\"cell\">\n <img src=\"{{ $element }}.png\">\n <p>{{ $element }}</p>\n </div>\n {{end}}\n </div>\n </body>\n</html>\n`\n\n\twriter, err := os.Create(\"./output/index.html\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tt, err := template.New(\"htmlIndex\").Parse(templateHTML)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfor _, g := range script.Glyphs {\n\t\tsymbols = append(symbols, g.Representation)\n\t}\n\n\terr = t.Execute(writer, symbols)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tdefer writer.Close()\n}", "func (t *TemplateRenderer) Render(w io.Writer, name string, c echo.Context) error {\n\treturn t.templates.ExecuteTemplate(w, name, nil)\n}", "func Render(param ...interface{}) {\n\n\tt, err := template.ParseFiles(param[1].(string))\n\tcheckErr(err)\n\tif len(param) == 2 {\n\t\terr = t.Execute(param[0].(http.ResponseWriter), nil)\n\t\tcheckErr(err)\n\t} else if len(param) == 3 {\n\t\terr = t.Execute(param[0].(http.ResponseWriter), param[2].(User))\n\t\tcheckErr(err)\n\t}\n\t//func Render(w http.ResponseWriter, url string) {\n\n}", "func (m *Manager) Render(name string, w io.Writer, data interface{}) error {\n\tif w == nil {\n\t\treturn ErrWriterRequired\n\t}\n\tm.m.RLock()\n\tv, ok := m.views[name]\n\tm.m.RUnlock()\n\tif !ok {\n\t\treturn fmt.Errorf(\"view: View \\\"%s\\\" doesn't exist\", name)\n\t}\n\tb := m.buffers.Get()\n\t// trade-off:\n\t// when Render causes a panic, the buffer will not be reused\n\t// but the runtime overhead of defer is avoided\n\terr := v.Execute(b, data)\n\tif err != nil {\n\t\tm.buffers.Put(b)\n\t\treturn err\n\t}\n\t_, err = b.WriteTo(w)\n\tm.buffers.Put(b)\n\treturn err\n}", "func (h *htmlRender) Render(w io.Writer) error {\n\tif h.Template == nil {\n\t\treturn errors.New(\"template is nil\")\n\t}\n\n\tif h.Layout == \"\" {\n\t\treturn h.Template.Execute(w, h.ViewArgs)\n\t}\n\n\treturn h.Template.ExecuteTemplate(w, h.Layout, h.ViewArgs)\n}", "func Render(w http.ResponseWriter, name string, data interface{}) error {\n\terr := tpl.ExecuteTemplate(w, name, data)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Renderer(dir, leftDelim, rightDelim string) Middleware {\n\tfs := os.DirFS(dir)\n\tt, err := compileTemplates(fs, leftDelim, rightDelim)\n\tif err != nil {\n\t\tpanic(\"Renderer: \" + err.Error())\n\t}\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {\n\t\t\tctx := FromContext(req.Context())\n\t\t\tif Env == DEV {\n\t\t\t\tif t, err = compileTemplates(fs, leftDelim, rightDelim); err != nil {\n\t\t\t\t\tpanic(\"Context.HTML:\" + err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.template = t\n\t\t\tnext.ServeHTTP(rw, req)\n\t\t})\n\t}\n}", "func Render(tag Tagger) string {\n return tag.Render()\n}", "func Render(w http.ResponseWriter, actions ...*Action) error {\n\tbuf := new(bytes.Buffer)\n\tfor _, a := range actions {\n\t\tif err := a.appendTo(buf); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif a != nil {\n\t\t\tbuf.WriteByte('\\n')\n\t\t}\n\t}\n\tw.Header().Set(\"Content-Type\", ContentType+\"; charset=utf-8\")\n\tw.Header().Set(\"Content-Length\", strconv.Itoa(buf.Len()))\n\tio.Copy(w, buf) // ignore errors, since we already wrote\n\treturn nil\n}", "func render(ctx Config, com Component, gfx *dot.Graph) *dot.Node {\n\n\timg := iconPath(ctx, com)\n\n\tif fc := strings.TrimSpace(com.FontColor); len(fc) == 0 {\n\t\tcom.FontColor = \"#000000ff\"\n\t}\n\n\tif imp := strings.TrimSpace(com.Impl); len(imp) == 0 {\n\t\tcom.Impl = \"&nbsp;\"\n\t}\n\n\tvar sb strings.Builder\n\tsb.WriteString(`<table border=\"0\" cellborder=\"0\">`)\n\tif ctx.showImpl {\n\t\tfmt.Fprintf(&sb, `<tr><td><font point-size=\"8\">%s</font></td></tr>`, com.Impl)\n\t}\n\n\tsb.WriteString(\"<tr>\")\n\tfmt.Fprintf(&sb, `<td fixedsize=\"true\" width=\"50\" height=\"50\"><img src=\"%s\" /></td>`, img)\n\tsb.WriteString(\"</tr>\")\n\n\tlabel := \"&nbsp;\"\n\tif s := strings.TrimSpace(com.Label); len(s) > 0 {\n\t\tlabel = s\n\t}\n\tfmt.Fprintf(&sb, `<tr><td><font point-size=\"7\">%s</font></td></tr>`, label)\n\tsb.WriteString(\"</table>\")\n\n\treturn node.New(gfx, com.ID,\n\t\tnode.Label(sb.String(), true),\n\t\tnode.FillColor(\"transparent\"),\n\t\tnode.Shape(\"plain\"),\n\t)\n}", "func (a Generator) Run(root string, data makr.Data) error {\n\tg := makr.New()\n\n\tif a.AsAPI {\n\t\tdefer os.RemoveAll(filepath.Join(a.Root, \"templates\"))\n\t\tdefer os.RemoveAll(filepath.Join(a.Root, \"locales\"))\n\t\tdefer os.RemoveAll(filepath.Join(a.Root, \"public\"))\n\t}\n\tif a.Force {\n\t\tos.RemoveAll(a.Root)\n\t}\n\n\tg.Add(makr.NewCommand(makr.GoGet(\"golang.org/x/tools/cmd/goimports\", \"-u\")))\n\tif a.WithDep {\n\t\tg.Add(makr.NewCommand(makr.GoGet(\"github.com/golang/dep/cmd/dep\", \"-u\")))\n\t}\n\n\tfiles, err := generators.FindByBox(packr.NewBox(\"../newapp/templates\"))\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tfor _, f := range files {\n\t\tif !a.AsAPI {\n\t\t\tg.Add(makr.NewFile(f.WritePath, f.Body))\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.Contains(f.WritePath, \"locales\") || strings.Contains(f.WritePath, \"templates\") || strings.Contains(f.WritePath, \"public\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tg.Add(makr.NewFile(f.WritePath, f.Body))\n\t}\n\n\tdata[\"name\"] = a.Name\n\tif err := refresh.Run(root, data); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\ta.setupCI(g, data)\n\n\tif err := a.setupWebpack(root, data); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif err := a.setupPop(root, data); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif err := a.setupDocker(root, data); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tg.Add(makr.NewCommand(a.goGet()))\n\n\tg.Add(makr.Func{\n\t\tRunner: func(root string, data makr.Data) error {\n\t\t\tg.Fmt(root)\n\t\t\treturn nil\n\t\t},\n\t})\n\n\ta.setupVCS(g)\n\n\tdata[\"opts\"] = a\n\treturn g.Run(root, data)\n}", "func main() {\n\tfmt.Println(\"Generating code\")\n\treduce.GenerateDispatcher(outputPath)\n\t//reduce.GenerateDispatcher(outputPath)\n}", "func (e *Entity) Render() (string, error) {\n\treturn \"\", nil\n}", "func Execute(wr io.Writer, data *PageInfo) (err error) {\n\tif len(data.Name) < 1 {\n\t\terr = errors.New(\"PageInfo template name not specified!\")\n\t\treturn\n\t}\n\n\tdata.ModuleName = make(map[string]bool, 1)\n\tdata.ModuleName[moduleName] = true\n\n\tlog.Println(\"ModuleName:\", moduleName, \"Map:\", data.ModuleName)\n\n\tprefix := \"tmpl/desktop/\"\n\tif WouldUseMobile(data.Request) {\n\t\tprefix = \"tmpl/mobile/\"\n\t}\n\n\tstartTime := time.Now()\n\ttemplate, err := GetTemplate(prefix + data.Name)\n\tendTime := time.Now()\n\n\tdeltaTime := endTime.Sub(startTime)\n\tfmt.Println(\"Took\", float32(deltaTime)/(1000.0*1000.0*1000.0), \"seconds to parse template\", data.Name)\n\n\tif err != nil {\n\t\tlog.Println(\"Error parsing template '\", data.Name, \"':\", err)\n\t\treturn err\n\t}\n\n\tstartTime = time.Now()\n\n\ttemplate.Render(wr, data)\n\n\tendTime = time.Now()\n\tdeltaTime = endTime.Sub(startTime)\n\tlog.Println(\"Took\", float32(deltaTime)/(1000.0*1000.0*1000.0), \"seconds to render template\", data.Name)\n\treturn\n}", "func render(c *gin.Context) {\n\t// fill up the list with the current store listing\n\tfmt.Println(\"RENDER ATTACHED\")\n\t// render_active = true\n\tc.Stream(func(w io.Writer) bool {\n\t\tselect {\n\t\tcase msg := <-render_chan:\n\t\t\tdata, _ := json.Marshal(msg)\n\t\t\tc.SSEvent(\"render\", string(data))\n\t\t}\n\t\treturn true\n\t})\n\t// render_active = false\n\tfmt.Println(\"RENDERER DETACHED\")\n}", "func (app *App) Run() (err error) {\n\treturn app.Renderer.Run()\n}", "func Render(source string, context *Context) (string, error) {\n\n\twriter := &strings.Builder{}\n\n\tparsed, err := template.New(\"\").Funcs(context.Functions()).Parse(source)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error parsing template\")\n\t}\n\n\terr = parsed.Execute(writer, nil)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error executing template\")\n\t}\n\n\treturn writer.String(), nil\n}", "func (c *Context) Render(status int, name string, data interface{}) (err error) {\n\tif c.router.Renderer == nil {\n\t\treturn errors.New(\"renderer not registered\")\n\t}\n\n\tvar buf = new(bytes.Buffer)\n\tif err = c.router.Renderer.Render(buf, name, data, c); err != nil {\n\t\treturn err\n\t}\n\n\tc.HTML(status, buf.Bytes())\n\treturn\n}", "func HTMLRenderer(w http.ResponseWriter, r *http.Request) {\n\t// w http.ResponseWriter, r *http.Request\n\t// Resorts is the array of desired ski resorts\n\tvar Resorts []repo.Resort\n\tResorts = repo.BuildResortSlice()\n\n\tURLslice := repo.BuildURLslice(Resorts) // returns slice of URLinstances{URL, resortName}\n\tresponseSlice := repo.CallDarkSky(URLslice) // returns slice of DarkSkyResponses\n\trepo.PopulateResortWeather(Resorts, responseSlice) // populates resort weather info for html\n\n\t// fmt.Printf(\"%v+\", Resorts)\n\n\ttmpl, err := template.ParseFiles(\"./repository/WeatherDisplayTemplate.html\")\n\tErrorCheck(err)\n\ttmpl.Execute(w, Resorts)\n}", "func main() {\n\tdomTarget := dom.GetWindow().Document().GetElementByID(\"app\")\n\n\tr.Render(container.Container(), domTarget)\n}" ]
[ "0.69906324", "0.6711924", "0.6653557", "0.6548527", "0.64930576", "0.6455168", "0.6452924", "0.6408066", "0.6359203", "0.63572174", "0.6285732", "0.62783897", "0.6215761", "0.6215658", "0.6215658", "0.6214472", "0.62020814", "0.62014455", "0.6174", "0.6165483", "0.6152791", "0.614511", "0.61321443", "0.6114401", "0.60882396", "0.6084305", "0.6033761", "0.6026624", "0.602468", "0.6019662", "0.6002498", "0.5997512", "0.5992792", "0.599157", "0.5974587", "0.5969589", "0.5962032", "0.59504026", "0.59504026", "0.5948447", "0.5933208", "0.5922419", "0.5915972", "0.58946943", "0.58903134", "0.58902884", "0.58902884", "0.58902884", "0.58902884", "0.58902884", "0.58902884", "0.5887833", "0.5886703", "0.5879167", "0.5878368", "0.5875213", "0.58669305", "0.58612406", "0.5842516", "0.58395547", "0.582964", "0.5827038", "0.58160794", "0.5802944", "0.58026284", "0.5800119", "0.5797749", "0.5793213", "0.57827294", "0.57776684", "0.5776291", "0.5774046", "0.5765005", "0.575554", "0.57487977", "0.5745363", "0.57389563", "0.5721628", "0.57214373", "0.57181084", "0.57159466", "0.57137525", "0.5688801", "0.5688792", "0.5684233", "0.56787527", "0.5673245", "0.5670533", "0.5667489", "0.5648818", "0.564655", "0.5638462", "0.56377465", "0.56310177", "0.56180835", "0.56129974", "0.56112945", "0.5610369", "0.5601366", "0.55973274" ]
0.6269176
12
NewRateLimiter generates a RateLimiter with a given capacity.
func NewRateLimiter(capacity int) *RateLimiter { semaphore := make(chan bool, capacity) // Fill channel for i := 0; i < capacity; i++ { semaphore <- true } return &RateLimiter{semaphore} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newRateLimiter() *rateLimiter {\n\tdecayFactor := 9.0 / 8.0\n\treturn &rateLimiter{\n\t\tstats: info.RateLimiterStats{\n\t\t\tTargetRate: 1,\n\t\t},\n\t\tdecayPeriod: 5 * time.Second,\n\t\tdecayFactor: decayFactor,\n\t\texit: make(chan struct{}),\n\t}\n}", "func NewRateLimiter(rate float64, capacity int64) *Limiter {\n\treturn &Limiter{\n\t\tresponder: RateLimitResponder,\n\t\tbucket: ratelimit.NewBucketWithRate(rate, capacity),\n\t}\n}", "func NewRateLimiter(store data.Store, threshold int) *RateLimiter {\n\treturn &RateLimiter{\n\t\tstore: store,\n\t\tthreshold: threshold,\n\t}\n}", "func NewLimiter(rate float64, burst float64, initialTokens float64) *Limiter {\n\treturn &Limiter{\n\t\trate: rate,\n\t\tburst: burst,\n\t\ttokens: initialTokens,\n\t\tlast: time.Now(),\n\t}\n}", "func newRateLimiter(delay time.Duration) *rateLimiter {\n\treturn &rateLimiter{\n\t\tdelay: delay,\n\t\tops: make(map[string]time.Time),\n\t}\n}", "func NewRateLimiter(freq time.Duration, burstSize int) *Limiter {\n\treturn &Limiter{\n\t\tconnectionFreq: freq,\n\t\tconnectionBurstSize: burstSize,\n\t}\n}", "func New(policy *Policy) *RateLimiter {\n\trl := &RateLimiter{\n\t\tpolicy: policy,\n\t\tstartTime: nowFunc(),\n\t}\n\treturn rl\n}", "func NewRateLimiter(r rate.Limit, b int) *RateLimiter {\n\treturn NewRateLimiterWithValue(r, b, 0)\n}", "func NewRateLimiter(r float64, b int) *RateLimiter {\n\treturn &RateLimiter{limiter: rate.NewLimiter(rate.Limit(r), b)}\n}", "func NewRateLimiter(limit int64) *limiter {\n\treturn &limiter{\n\t\tstart: time.Now(),\n\t\tlimit: limit,\n\t\tdelay: 0.5,\n\t}\n}", "func newRateLimiter() *middlewares.Limiter {\n\treturn middlewares.NewLimiter(newRedis())\n}", "func NewRateLimiter(h cachemanager.Handler) RateLimiter {\n\treturn &rateLimiter{\n\t\tbuckets: make(map[time.Duration]int),\n\t\thandler: h,\n\t}\n}", "func NewRateLimiter(bandwidth, ops models.TokenBucket, opts ...RateLimiterOpt) *models.RateLimiter {\n\tlimiter := &models.RateLimiter{\n\t\tBandwidth: &bandwidth,\n\t\tOps: &ops,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(limiter)\n\t}\n\n\treturn limiter\n}", "func NewRateLimiter(max float64, purgeDuration time.Duration) RateLimiter {\n\trl := RateLimiter{}\n\n\tif purgeDuration == 0 {\n\t\trl = RateLimiter{\n\t\t\ttollbooth.NewLimiter(max, nil),\n\t\t\tfalse,\n\t\t}\n\t} else {\n\t\trl = RateLimiter{\n\t\t\ttollbooth.NewLimiter(max, &limiter.ExpirableOptions{DefaultExpirationTTL: purgeDuration}),\n\t\t\tfalse,\n\t\t}\n\t}\n\n\trl.Limiter.SetIPLookups([]string{\"X-Forwarded-For\", \"RemoteAddr\", \"X-Real-IP\"})\n\n\treturn rl\n}", "func NewRateLimiter(strategy RateLimiterStrategy, recheckPeriod time.Duration) *RateLimiter {\n\treturn &RateLimiter{\n\t\tstrategy: strategy,\n\t\trecheckPeriod: recheckPeriod,\n\t\ttenants: map[string]*tenantLimiter{},\n\t}\n}", "func New(quantum time.Duration) *limiter {\n\tl := &limiter{\n\t\tquantum: quantum,\n\t\tschedule: make(chan ask, 1),\n\t\tclosecap: make(chan bool, 1),\n\t\tdone: make(chan bool),\n\t}\n\tl.closecap <- true\n\tgo l.run()\n\treturn l\n}", "func New(c *aqm.Config) *Limiter {\n\tl := &Limiter{\n\t\trate: vegas.New(),\n\t\tqueue: aqm.New(c),\n\t}\n\tgo func() {\n\t\tticker := time.NewTicker(time.Second * 1)\n\t\tdefer ticker.Stop()\n\t\tfor {\n\t\t\t<-ticker.C\n\t\t\tv := l.rate.Stat()\n\t\t\tq := l.queue.Stat()\n\t\t\tlog.Info(\"rate/limit: limit(%d) inFlight(%d) minRtt(%v) rtt(%v) codel packets(%d)\", v.Limit, v.InFlight, v.MinRTT, v.LastRTT, q.Packets)\n\t\t}\n\t}()\n\treturn l\n}", "func NewRateLimiter(rateBytesPerSec, refillPeriodMicros int64, fairness int32) *RateLimiter {\n\tcR := C.rocksdb_ratelimiter_create(\n\t\tC.int64_t(rateBytesPerSec),\n\t\tC.int64_t(refillPeriodMicros),\n\t\tC.int32_t(fairness),\n\t)\n\treturn newNativeRateLimiter(cR)\n}", "func NewLimiter(\n\tlimiterGUID string,\n\trateStr string,\n\trateType string,\n\tkeyGetter KeyGetter,\n\treporter RateExceededReporter,\n\tmaxEntriesInMemory int,\n\tbehavior string,\n\terrorCode int,\n\terrorSubCode int,\n\tmetricLabel string,\n\tmetric *prometheus.CounterVec,\n\tmetricIncrementer MetricIncrementer,\n\topts ...golimiter.Option) (l RateLimiter, err error) {\n\trate, err := golimiter.NewRateFromFormatted(rateStr)\n\tif err != nil {\n\t\treturn l, err\n\t}\n\t// gotta override the default exp with the rate's exp (regardless of opts)\n\tnewOpts := append([]golimiter.Option{golimiter.WithLimiterExpiration(rate.Period)}, opts...)\n\tstore := golimiter.NewInMemoryLimiterStore(maxEntriesInMemory, newOpts...)\n\tif limiterGUID == \"\" {\n\t\tlimiterGUID = uuid.New().String()\n\t}\n\tl = RateLimiter{\n\t\tLimiterGUID: limiterGUID,\n\t\tLimiter: golimiter.New(store, rate),\n\t\tStore: store,\n\t\tKeyGetter: keyGetter,\n\t\tReporter: reporter,\n\t\tType: rateType,\n\t\tBehavior: behavior,\n\t\tRate: rateStr,\n\t\tErrorCode: errorCode,\n\t\tErrorSubCode: errorCode,\n\t\tMetricLabel: metricLabel,\n\t\tMetric: metric,\n\t\tMetricIncremeter: metricIncrementer,\n\t}\n\treturn l, nil\n}", "func NewRateLimiter(config *config.RuntimeSecurityConfig, client statsd.ClientInterface) *RateLimiter {\n\trl := &RateLimiter{\n\t\tlimiters: make(map[string]Limiter),\n\t\tstatsdClient: client,\n\t\tconfig: config,\n\t}\n\n\treturn rl\n}", "func NewLimiter() *Limiter {\n\treturn &Limiter{\n\t\tstamp: make(map[string]float64),\n\t}\n}", "func New(config config.Config) (RateLimiter, error) {\n\n\tstorage, err := resolveBucketStore(config.Storage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlimits := []limit.Limit{}\n\tfor name, config := range config.Limits {\n\t\tlimit, err := limit.New(name, config, storage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlimits = append(limits, limit)\n\t}\n\n\trateLimiter := &rateLimiter{limits: limits}\n\treturn rateLimiter, nil\n}", "func NewRateLimiter(intervalInMillis int64, maxInInterval int, client *redis.Client) *RateLimiter {\n\treturn &RateLimiter{\n\t\tintervalInMillis: intervalInMillis,\n\t\tmaxInInterval: maxInInterval,\n\t\tclient: client,\n\t}\n}", "func NewRateLimiter(interval time.Duration, n int) *RateLimiter {\n\treturn &RateLimiter{\n\t\tips: make(map[string]*rate.Limiter),\n\t\tinterval: rate.Every(interval),\n\t\tn: n,\n\t}\n}", "func NewLimiter(max int64, ttl time.Duration, conf *rate.ConfigRedis) *Limiter {\n\tlimiter := &Limiter{Max: max, TTL: ttl}\n\tlimiter.MessageContentType = \"text/plain; charset=utf-8\"\n\tlimiter.Message = \"You have reached maximum request limit.\"\n\tlimiter.StatusCode = 429\n\tlimiter.tokenBuckets = make(map[string]*rate.Limiter)\n\tlimiter.IPLookups = []string{\"RemoteAddr\", \"X-Forwarded-For\", \"X-Real-IP\"}\n\n\tif err := rate.SetRedis(conf); err != nil {\n\t\tlog.Println(\"fail to set rate limiter's redis: \", err)\n\t}\n\n\treturn limiter\n}", "func New() *Limiter {\n\tl := &Limiter{make(chan int, 1), make(chan struct{}, 1)}\n\tl.waiter <- struct{}{}\n\treturn l\n}", "func NewLimiter(limit int64, seconds int) Limiter {\n\treturn &concreteLimiter{\n\t\tRedisCli: cache.GetRedis(),\n\t\tLimit: limit,\n\t\tSeconds: seconds,\n\t}\n}", "func NewTimeLimiter(timeWindow time.Duration, capacity int64) *Limiter {\n\treturn &Limiter{\n\t\tresponder: RateLimitResponder,\n\t\tbucket: ratelimit.NewBucket(timeWindow, capacity),\n\t}\n}", "func RateLimiter(next http.RoundTripper) http.RoundTripper {\n\treturn &ratelimiter{\n\t\trt: next,\n\t\tlm: sync.Map{},\n\t}\n}", "func newLimiter() *limiter.Limiter {\n\n\tlmt := tollbooth.NewLimiter(2, &limiter.ExpirableOptions{DefaultExpirationTTL: time.Hour})\n\n\tlmt.SetIPLookups([]string{\"X-Forwarded-For\", \"RemoteAddr\", \"X-Real-IP\"})\n\tlmt.SetOnLimitReached(func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Println(\"request limit reached\")\n\t})\n\n\treturn lmt\n\n}", "func New(timeout time.Duration, cache GetSetter) Throttler {\n\tsalt, err := randomBytes(16)\n\tif err != nil {\n\t\tpanic(\"cannot initialize rate limiter\")\n\t}\n\treturn &Limiter{\n\t\tcache: cache,\n\t\ttimeout: timeout,\n\t\tsalt: salt,\n\t}\n}", "func New(qps int64) *limiter {\n\tif qps <= 0 {\n\t\treturn nil\n\t}\n\n\trl := &limiter{\n\t\tqps: qps,\n\t}\n\trl.current = make(map[string]int64, 0)\n\n\t// launch a goroutine to reset the counter every second\n\tgo rl.reset()\n\n\treturn rl\n}", "func NewRateLimit(limit int, deltat time.Duration) *RateLimit {\n\treturn &RateLimit{Rate{NewCounter(0), deltat}, limit, time.Now()}\n}", "func CreateRateLimiter(limit int) RateLimiter {\n\treturn &rateLimiter{limit: limit}\n}", "func CreateLimiter(limit rate.Limit) *rate.Limiter {\n\treturn rate.NewLimiter(limit, GetGoodBurst(limit))\n}", "func LimiterCapacity(capacity int64) Option {\n\treturn func(o *options) {\n\t\to.limiterCapacity = capacity\n\t}\n}", "func NewLimiter(maxItems int, refreshInterval time.Duration) *Limiter {\n\tl := &Limiter{\n\t\tmaxItems: maxItems,\n\t\tstopCh: make(chan struct{}),\n\t}\n\tl.v.Store(newLimiter(maxItems))\n\tl.wg.Add(1)\n\tgo func() {\n\t\tdefer l.wg.Done()\n\t\tt := time.NewTicker(refreshInterval)\n\t\tdefer t.Stop()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-t.C:\n\t\t\t\tl.v.Store(newLimiter(maxItems))\n\t\t\tcase <-l.stopCh:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn l\n}", "func NewChannelBasedRateLimiter(lps int) *ChannelBasedRateLimiter {\n\treturn &ChannelBasedRateLimiter{\n\t\tt: time.NewTicker(time.Second / time.Duration(lps)),\n\t}\n}", "func NewLimitRate(name string, options LimitRateOptions) *LimitRate {\n\tthis := LimitRate{}\n\tthis.Name = name\n\tthis.Options = options\n\treturn &this\n}", "func New(rate int, opts ...Option) Limiter {\n\treturn newAtomicBased(rate, opts...)\n}", "func NewRateLimit(client curator.CuratorFramework, username string,\n\ttotalAllowedQuota, baseQuota int64, lockTimeout time.Duration, refreshWindow time.Duration,\n\tenableOptimization bool, optimizationPctAsk float64, optimizationPctLeft float64) (*RateLimit, error) {\n\tvar err error\n\trl := &RateLimit{\n\t\tusername: username,\n\t\ttotalAllowedQuota: totalAllowedQuota,\n\t\tusableQuotaLeft: totalAllowedQuota,\n\t\tbaseQuota: baseQuota,\n\t\tlockTimeout: lockTimeout,\n\t\trefreshWindow: refreshWindow,\n\t\tclient: client,\n\t\tbaseQuotaPath: prefix + \"/\" + username + baseSuffix,\n\t\tusableQuotaPath: prefix + \"/\" + username + usableSuffix,\n\t\ttotalQuotaPath: prefix + \"/\" + username + totalSuffix,\n\t\trefreshQuotaPath: prefix + \"/\" + username + refreshSuffix,\n\t\toptimizationPctAsk: optimizationPctAsk,\n\t\toptimizationPctLeft: optimizationPctLeft,\n\t\tenableOptimization: enableOptimization,\n\t}\n\n\t// initialize the lock to be used and inject it wherever required.\n\trl.lock, err = recipe.NewInterProcessMutex(rl.client, lockPath+username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(prefix, []byte(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(prefix+\"/\"+rl.username, []byte(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.baseQuotaPath, []byte(strconv.FormatInt(rl.baseQuota, 10)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.totalQuotaPath, []byte(strconv.FormatInt(rl.totalAllowedQuota, 10)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.usableQuotaPath, []byte(strconv.FormatInt(rl.usableQuotaLeft, 10)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.refreshQuotaPath, []byte(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.addWatch()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// concurrently look to refresh quota\n\tgo rl.refreshQuota()\n\t// mimic user requests being processed with random size\n\tgo rl.startRequests()\n\t// just in case there is skewness observed through loadbalancer and\n\t// quota gets concentrated on a single rate limit node\n\tgo rl.relinquish()\n\n\treturn rl, nil\n}", "func NewMockRateLimiter(ctrl *gomock.Controller) *MockRateLimiter {\n\tmock := &MockRateLimiter{ctrl: ctrl}\n\tmock.recorder = &MockRateLimiterMockRecorder{mock}\n\treturn mock\n}", "func NewMockRateLimiter(ctrl *gomock.Controller) *MockRateLimiter {\n\tmock := &MockRateLimiter{ctrl: ctrl}\n\tmock.recorder = &MockRateLimiterMockRecorder{mock}\n\treturn mock\n}", "func New(rate int, opts ...Option) Limiter {\r\n\treturn newAtomicBased(rate, opts...)\r\n}", "func New(limits *Limits, header interface{}, c *redis.Client) *Limiter {\n\tlMap := make(limitsMap)\n\n\tif c == nil {\n\t\tvar err error\n\t\tclient, err = goredisify.Conn(os.Getenv(\"REDIS_URL\"))\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t} else {\n\t\tclient = c\n\t}\n\n\tfor _, limit := range *limits {\n\t\tkey := limit.Method + \":\" + limit.Path\n\t\tlMap[key] = limit\n\t}\n\n\treturn &Limiter{header, lMap}\n}", "func NewRateLimiter(redisURL string, prefix string, dynamicConfig bool, dynamicConfigCacheTTL time.Duration) RateLimiter {\n\treturn &redisRateLimiter{\n\t\tpool: &redis.Pool{\n\t\t\tDial: func() (redis.Conn, error) {\n\t\t\t\treturn redis.DialURL(redisURL)\n\t\t\t},\n\t\t\tTestOnBorrow: func(c redis.Conn, _ time.Time) error {\n\t\t\t\t_, err := c.Do(\"PING\")\n\t\t\t\treturn err\n\t\t\t},\n\t\t\tMaxIdle: redisRateLimiterPoolMaxIdle,\n\t\t\tMaxActive: redisRateLimiterPoolMaxActive,\n\t\t\tIdleTimeout: redisRateLimiterPoolIdleTimeout,\n\t\t\tWait: true,\n\t\t},\n\t\tprefix: prefix,\n\n\t\tdynamicConfig: dynamicConfig,\n\t\tdynamicConfigCacheTTL: dynamicConfigCacheTTL,\n\t}\n}", "func NewQuotaRateLimit(ctx *pulumi.Context,\n\tname string, args *QuotaRateLimitArgs, opts ...pulumi.ResourceOption) (*QuotaRateLimit, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Rate == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Rate'\")\n\t}\n\tvar resource QuotaRateLimit\n\terr := ctx.RegisterResource(\"vault:index/quotaRateLimit:QuotaRateLimit\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewRateLimitedLogger(logger Interface, logsPerSecond rate.Limit, burstSize int, reg prometheus.Registerer) Interface {\n\tdiscardedLogLinesCounter := promauto.With(reg).NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"logger_rate_limit_discarded_log_lines_total\",\n\t\tHelp: \"Total number of discarded log lines per level.\",\n\t}, []string{\"level\"})\n\n\treturn &RateLimitedLogger{\n\t\tnext: logger,\n\t\tlimiter: rate.NewLimiter(logsPerSecond, burstSize),\n\t\tdiscardedInfoLogLinesCounter: discardedLogLinesCounter.WithLabelValues(infoLevel),\n\t\tdiscardedDebugLogLinesCounter: discardedLogLinesCounter.WithLabelValues(debugLevel),\n\t\tdiscardedWarnLogLinesCounter: discardedLogLinesCounter.WithLabelValues(warnLevel),\n\t\tdiscardedErrorLogLinesCounter: discardedLogLinesCounter.WithLabelValues(errorLevel),\n\t}\n}", "func NewRatelimiterMiddleware(\n\tlogger *zerolog.Logger, cfg RateLimiterConfig, calculator Calculator,\n) Calculator {\n\treturn &ratelimiterMiddleware{\n\t\tlogger: logger,\n\t\tcalculator: calculator,\n\t\trls: make(map[string]*rate.Limiter),\n\t\tmu: &sync.RWMutex{},\n\t\tr: rate.Every(cfg.Interval),\n\t\tb: cfg.B,\n\t}\n}", "func newNativeRateLimiter(c *C.rocksdb_ratelimiter_t) *RateLimiter {\n\treturn &RateLimiter{c: c}\n}", "func NewRateLimit(storage store.Store, statsClient stats.Client) *RateLimit {\n\treturn &RateLimit{storage, statsClient}\n}", "func (m *Manager) NewRateLimit(conf ratelimit.Config) (ratelimit.V1, error) {\n\treturn bundle.AllRateLimits.Init(conf, m)\n}", "func ratelimiter(args map[string]interface{}) *ratelimit.Ratelimiter {\n\trate, err := strconv.Atoi(args[\"--ratelimit-max-rate\"].(string))\n\tif err != nil {\n\t\tlog.Fatalf(\"error parsing --ratelimit-max-rate: %s\", err)\n\t}\n\n\tif rate <= 0 {\n\t\treturn nil\n\t}\n\n\tkeys, err := strconv.Atoi(args[\"--ratelimit-max-keys\"].(string))\n\tif err != nil {\n\t\tlog.Fatalf(\"error parsing --ratelimit-max-keys: %s\", err)\n\t}\n\n\treturn ratelimit.New(rate, keys)\n}", "func New(capacity int) *RingBuffer {\n\treturn &RingBuffer{\n\t\tC: make(chan struct{}, 1),\n\t\tbuf: make([]byte, capacity),\n\t\tlen: 0,\n\t\tindex: 0,\n\t}\n}", "func NewDelayingLimiter(w Waiter) endpoint.Middleware {\n\treturn func(next endpoint.Endpoint) endpoint.Endpoint {\n\t\treturn func(ctx context.Context, request interface{}) (interface{}, error) {\n\t\t\tif err := w.Wait(ctx); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\treturn next(ctx, request)\n\t\t}\n\t}\n}", "func New(ctx context.Context, rate, timespan int) (Bucket, error) {\n\tq := make(chan struct{}, rate)\n\tb := Bucket{ctx: ctx, queue: q, rate: rate, timespan: timespan}\n\tgo b.leak()\n\treturn b, nil // maybe return pointer?\n}", "func (c *Limiter) Create() Limit {\n\treturn rate.NewLimiter(\n\t\trate.Every(c.connectionFreq),\n\t\tc.connectionBurstSize)\n}", "func NewRateLimitWatcher(c Client, logger log.Logger, threshold int) AroundFunctionCreator {\n\treturn &rateLimitWatcher{client: c, logger: logger, threshold: threshold}\n}", "func NewIPRateLimiter(reqLimitPerMin int) *IPRateLimiter {\n\treturn &IPRateLimiter{\n\t\tips: make(map[string]*ratelimiter.RateLimiter),\n\t\tmu: &sync.RWMutex{},\n\t\treqLimitPerMin: reqLimitPerMin,\n\t}\n}", "func NewLimiterReader(rd io.Reader, rate infounit.BitRate) (*LimiterReader, error) {\n\treturn NewLimiterReaderWithConfig(rd, rate, nil)\n}", "func newAtomicBased(rate int, opts ...Option) *atomicLimiter {\r\n\tconfig := buildConfig(opts)\r\n\tl := &atomicLimiter{\r\n\t\tperRequest: config.per / time.Duration(rate),\r\n\t\tmaxSlack: -1 * config.maxSlack * time.Second / time.Duration(rate),\r\n\t\tclock: config.clock,\r\n\t}\r\n\r\n\tinitialState := state{\r\n\t\tlast: time.Time{},\r\n\t\tsleepFor: 0,\r\n\t}\r\n\tatomic.StorePointer(&l.state, unsafe.Pointer(&initialState))\r\n\treturn l\r\n}", "func NewTokenBucket(capacity uint32, rate time.Duration, lifetime time.Duration) (*TokenBucket, error) {\n\t// To protect for inaccurate function usage. In case of rate == 0 returns - error.\n\tif rate == 0 {\n\t\treturn nil, errors.ErrTokenBucketInvalidFillRate\n\t}\n\n\ttb := &TokenBucket{\n\t\t//ctx: ctx,\n\t\tcapacity: capacity,\n\t\tcurrentAmount: capacity,\n\t\trate: rate,\n\t\tlifeTime: lifetime,\n\t\tlastAccessTime: time.Now(),\n\t\tshutDown: make(chan bool, 1),\n\t\tmx: sync.RWMutex{},\n\t}\n\t// Create a go routine with the time.Ticker to fill the bucket with desired rate.\n\tgo func(tb *TokenBucket) {\n\t\ttb.ticker = time.NewTicker(tb.rate)\n\n\t\tdefer tb.ticker.Stop()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-tb.ticker.C:\n\t\t\t\ttb.mx.RLock()\n\t\t\t\tif time.Since(tb.lastAccessTime) > tb.lifeTime {\n\t\t\t\t\t// Inactive timeout exeded - initiate the closure procedure of the bucket.\n\t\t\t\t\t// log.Println(\"Idle timeout exiting...\")\n\t\t\t\t\ttb.shutDown <- true\n\t\t\t\t\ttb.mx.RUnlock()\n\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttb.mx.RUnlock()\n\n\t\t\t\tif tb.currentAmount == tb.capacity { //Token Bucken is full all next tokens will be discarded\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\ttb.mx.Lock()\n\t\t\t\ttb.currentAmount++ // Add one token to the bucket\n\t\t\t\ttb.mx.Unlock()\n\t\t\tdefault: // Added to avoid blocking when we have looong time period for ticker\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}(tb)\n\n\treturn tb, nil\n}", "func New(capacity int) (*CBuf, error) {\n\tif capacity < 0 {\n\t\treturn nil, fmt.Errorf(\"negative capacity (%d)\",\n\t\t\tcapacity)\n\t}\n\treturn &CBuf{\n\t\tcap: capacity,\n\t\telems: make([]interface{}, capacity),\n\t}, nil\n}", "func NewRateLimiterCollector(max float64, purgeDuration time.Duration) RateLimiter {\n\trl := NewRateLimiter(max, purgeDuration)\n\trl.collectOnly = true\n\n\treturn rl\n}", "func NewIPRateLimiter(r rate.Limit, b int) *IPRateLimiter {\n\ti := &IPRateLimiter{\n\t\tips: make(map[string]*rate.Limiter),\n\t\tmu: &sync.RWMutex{},\n\t\tr: r,\n\t\tb: b,\n\t}\n\n\treturn i\n}", "func New(capacity int) (b *Ring) {\n\treturn &Ring{\n\t\tbuf: make([]interface{}, capacity),\n\t\thead: -1,\n\t}\n}", "func NewUnlimited() Limiter {\r\n\treturn unlimited{}\r\n}", "func NewConcurrencyLimiter(max int) *ConcurrencyLimiter {\n\tc := &ConcurrencyLimiter{\n\t\tinc: make(chan chan struct{}),\n\t\tdec: make(chan struct{}, max),\n\t\tmax: max,\n\t}\n\tgo c.handleLimits()\n\treturn c\n}", "func New(limit int) ConcurrencyLimit {\n\tif limit < 1 {\n\t\tlimit = 1\n\t}\n\treturn make(ConcurrencyLimit, limit)\n}", "func NewPeerRateLimiter(interval time.Duration, baseLimit int, log *logger.Logger) (*PeerRateLimiter, error) {\n\trecords := ttlcache.NewCache()\n\trecords.SetLoaderFunction(func(_ string) (interface{}, time.Duration, error) {\n\t\trecord := &limiterRecord{\n\t\t\tactivityCounter: ratecounter.NewRateCounter(interval),\n\t\t\tlimitExtensionCounter: ratecounter.NewRateCounter(interval),\n\t\t\tlimitHitReported: atomic.NewBool(false),\n\t\t}\n\n\t\treturn record, ttlcache.ItemExpireWithGlobalTTL, nil\n\t})\n\tif err := records.SetTTL(interval); err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn &PeerRateLimiter{\n\t\tEvents: newEvents(),\n\t\tinterval: interval,\n\t\tbaseLimit: atomic.NewInt64(int64(baseLimit)),\n\t\tpeersRecords: records,\n\t\tlog: log,\n\t}, nil\n}", "func NewLimit(value uint) *Limit {\r\n\treturn &Limit{\r\n\t\tmax: value,\r\n\t\tcurrent: 0,\r\n\t}\r\n}", "func NewRateLimitedClient(url string, uri string, events, bursts int) *Client {\n\tc := NewClient(url, uri)\n\tlimit := rate.Limit(events)\n\tc.limiter = rate.NewLimiter(limit, bursts)\n\treturn c\n}", "func NewUnlimited() Limiter {\n\treturn unlimited{}\n}", "func NewUnlimited() Limiter {\n\treturn unlimited{}\n}", "func New(cap int) Stack {\n\treturn Stack{capacity: cap}\n}", "func NewLimited(workers uint) Pool {\n\tif workers == 0 {\n\t\tpanic(\"invalid workers '0'\")\n\t}\n\n\tp := &limitedPool{\n\t\tworkers: workers,\n\t}\n\n\tp.initialize()\n\n\treturn p\n}", "func New(bc blockchainer.Blockchainer, capacity int) *Pool {\n\tif capacity <= 0 {\n\t\tpanic(\"invalid capacity\")\n\t}\n\n\treturn &Pool{\n\t\tverified: make(map[util.Uint256]*list.Element),\n\t\tsenders: make(map[util.Uint160]*list.List),\n\t\tsingleCap: capacity,\n\t\tchain: bc,\n\t}\n}", "func NewCapacityBuffer(capacity int) *Buffer {\n return &Buffer{data: make([]byte, capacity)}\n}", "func RateLimit(dur time.Duration) func(*Dispatcher) {\n\treturn func(d *Dispatcher) {\n\t\td.startTicker(dur)\n\t}\n}", "func NewRateLimitTransport(rt http.RoundTripper, logger log.Logger) *RateLimitTransport {\n\treturn &RateLimitTransport{\n\t\ttransport: rt,\n\t\tlogger: logger,\n\t\tdefaultAbuseSleep: defaultAbuseRetryAfter,\n\t}\n}", "func newSeriesLimiter(maxSeries int) queryrange.Middleware {\n\treturn seriesLimiterMiddleware(maxSeries)\n}", "func NewWithCapacity(workers, capacity int) Interface {\n\ti, _ := NewWithContext(context.Background(), workers, capacity)\n\treturn i\n}", "func newQuotaPool(q int) *quotaPool {\n\tqp := &quotaPool{\n\t\tacquireChannel: make(chan int, 1),\n\t}\n\tif q > 0 {\n\t\tqp.acquireChannel <- q\n\t} else {\n\t\tqp.quota = q\n\t}\n\treturn qp\n}", "func NewRateLimitedService(key string, limit float64) *Service {\n\tservice := NewService(key)\n\tservice.client = &RateLimitedClient{\n\t\tclient: service.client,\n\t\t// I don't know the accuracy of the API limit so choose a conservative burst.\n\t\tlim: rate.NewLimiter(rate.Limit(limit), 3 /* burst */),\n\t}\n\treturn service\n}", "func NewRedisRateLimiter(windowSize int, limitMap map[string]uint64, redisClient *redis.Client) *RedisRateLimiter {\n\tif windowSize == 0 {\n\t\twindowSize = 60 // seconds\n\t}\n\treturn &RedisRateLimiter{\n\t\twindowSize: windowSize,\n\t\tlimitMap: limitMap,\n\t\tredisClient: redisClient,\n\t}\n}", "func (c *Client) RateLimit() RateLimit {\n\tif c.limit != nil {\n\t\treturn *c.limit\n\t}\n\taccount, err := c.Account.Get()\n\tif err != nil {\n\t\treturn RateLimit{}\n\t}\n\tc.limit = &RateLimit{}\n\tfor _, metric := range account.Metrics {\n\t\tif metric.PlanLevel > 0 {\n\t\t\tc.limit.Limit = metric.PlanLevel\n\t\t\tc.limit.Remaining = metric.Remaining\n\t\t}\n\t}\n\treturn *c.limit\n}", "func newSamplerBackendRateCounter() *samplerBackendRateCounter {\n\treturn &samplerBackendRateCounter{\n\t\tbackend: newMemoryBackend(),\n\t\texit: make(chan struct{}),\n\t\tstopped: make(chan struct{}),\n\t}\n}", "func RateLimit(r rate.Limit, b, cap int) Allow {\n\tcap /= 2\n\tfront := make(map[string]*rate.Limiter, cap)\n\tback := make(map[string]*rate.Limiter, cap)\n\n\treturn func(conn net.Conn) (error, Cleanup) {\n\t\tremoteAddr := \"\"\n\t\tif tcpAddr, ok := conn.RemoteAddr().(*net.TCPAddr); ok {\n\t\t\tremoteAddr = tcpAddr.IP.String()\n\t\t} else {\n\t\t\tremoteAddr = conn.RemoteAddr().String()\n\t\t}\n\n\t\tallow := func(limiter *rate.Limiter) (error, func()) {\n\t\t\tif limiter.Allow() {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t\treturn ErrRateLimited, nil\n\t\t}\n\n\t\tlimiter := front[remoteAddr]\n\t\tif limiter != nil {\n\t\t\treturn allow(limiter)\n\t\t}\n\n\t\tlimiter = back[remoteAddr]\n\t\tif limiter != nil {\n\t\t\treturn allow(limiter)\n\t\t}\n\n\t\tif len(front) == cap {\n\t\t\tback = front\n\t\t\tfront = make(map[string]*rate.Limiter, cap)\n\t\t}\n\n\t\tlimiter = rate.NewLimiter(r, b)\n\t\tfront[remoteAddr] = limiter\n\t\treturn allow(limiter)\n\t}\n}", "func NewCapWriter(limit int) *CapWriter {\n\tcw := make(CapWriter, 0, limit)\n\treturn &cw\n}", "func New(capacity uint64) *lru {\n\treturn &lru{\n\t\tcapacity: capacity,\n\t\tsize: 0,\n\t\tlist: list.New(),\n\t\tcache: make(map[string]*list.Element),\n\t}\n}", "func NewRateLimiterWithValue(r rate.Limit, b int, value int64) *RateLimiter {\n\treturn &RateLimiter{\n\t\tr: r,\n\t\tb: b,\n\t\tvalue: value,\n\t\tlimiter: rate.NewLimiter(r, b),\n\t}\n}", "func NewBoundedPool(initialCap, maxCap int, timeout time.Duration, factory Factory) (pool.Pool, error) {\n\tif initialCap < 0 || maxCap <= 0 || initialCap > maxCap {\n\t\treturn nil, errors.New(\"invalid capacity settings\")\n\t}\n\n\tc := &boundedPool{\n\t\tconns: make(chan net.Conn, maxCap),\n\t\tfactory: factory,\n\t\ttimeout: timeout,\n\t}\n\n\t// create initial connections, if something goes wrong,\n\t// just close the pool error out.\n\tfor i := 0; i < initialCap; i++ {\n\t\tconn, err := factory()\n\t\tif err != nil {\n\t\t\tc.Close()\n\t\t\treturn nil, fmt.Errorf(\"factory is not able to fill the pool: %s\", err)\n\t\t}\n\t\tc.conns <- conn\n\t\tatomic.AddInt32(&c.total, 1)\n\t}\n\n\treturn c, nil\n}", "func RateLimiting() {\n\n\t// First we’ll look at basic rate limiting.\n\t// Suppose we want to limit our handling of incoming requests.\n\t// We’ll serve these requests off a channel of the same name.\n\trequests := make(chan int, 5)\n\tfor i := 1; i <= 5; i++ {\n\t\trequests <- i\n\t}\n\tclose(requests)\n\n\t// This limiter channel will receive a value every 200 milliseconds.\n\t// This is the regulator in our rate limiting scheme.\n\tlimiter := time.Tick(200 * time.Millisecond)\n\n\t// By blocking on a receive from the limiter channel before serving each request,\n\t// we limit ourselves to 1 request every 200 milliseconds.\n\tfor req := range requests {\n\t\t<-limiter\n\t\tfmt.Println(\"request\", req, time.Now())\n\t}\n\t// We may want to allow short bursts of requests in our rate limiting\n\t// scheme while preserving the overall rate limit.\n\t//We can accomplish this by buffering our limiter channel.\n\t//This burstyLimiter channel will allow bursts of up to 3 events.\n\tburstyLimiter := make(chan time.Time, 3)\n\n\t// Fill up the channel to represent allowed bursting.\n\tfor i := 0; i < 3; i++ {\n\t\tburstyLimiter <- time.Now()\n\t}\n\n\t// Every 200 milliseconds we’ll try to add a new value to burstyLimiter, up to its limit of 3.\n\tgo func() {\n\t\tfor t := range time.Tick(200 * time.Millisecond) {\n\t\t\tburstyLimiter <- t\n\t\t}\n\t}()\n\n\t// Now simulate 5 more incoming requests.\n\t// The first 3 of these will benefit from the burst capability of burstyLimiter.\n\tburstyRequests := make(chan int, 5)\n\n\tfor i := 1; i <= 5; i++ {\n\t\tburstyRequests <- i\n\t}\n\tclose(burstyRequests)\n\tfor req := range burstyRequests {\n\t\t<-burstyLimiter\n\t\tfmt.Println(\"request\", req, time.Now())\n\t}\n\t// Running our program we see the first batch of requests handled once every ~200 milliseconds as desired.\n\t// For the second batch of requests we serve the first 3 immediately\n\t// because of the burstable rate limiting, then serve the remaining 2 with ~200ms delays each.\n\n}", "func (rl *ratelimiterMiddleware) limiter(name string) *rate.Limiter {\n\trl.mu.RLock()\n\tlimiter, ok := rl.rls[name]\n\trl.mu.RUnlock()\n\n\tif !ok {\n\t\tlimiter = rate.NewLimiter(rl.r, rl.b)\n\n\t\trl.mu.Lock()\n\t\trl.rls[name] = limiter\n\t\trl.mu.Unlock()\n\t}\n\n\treturn limiter\n}", "func LimiterRate(rate float64) Option {\n\treturn func(o *options) {\n\t\to.limiterRate = rate\n\t}\n}", "func newQuota() *catalogue.Quota {\n\treturn &catalogue.Quota{\n\t\tCores: 99999,\n\t\tFloatingIPs: 99999,\n\t\tInstances: 99999,\n\t\tKeyPairs: 99999,\n\t\tRAM: 99999,\n\t\tTenant: \"test-tenant\",\n\t}\n}", "func NewTokenLimiter(count uint) *TokenLimiter {\n\ttl := &TokenLimiter{count: count, ch: make(chan *Token, count)}\n\tfor i := uint(0); i < count; i++ {\n\t\ttl.ch <- &Token{}\n\t}\n\n\treturn tl\n}", "func RateLimit(max float64) gin.HandlerFunc {\n\n\tlmt := tollbooth.NewLimiter(max, nil)\n\n\treturn func(c *gin.Context) {\n\t\thttpError := tollbooth.LimitByRequest(lmt, c.Writer, c.Request)\n\t\tif httpError != nil {\n\t\t\tc.Data(httpError.StatusCode, lmt.GetMessageContentType(), []byte(httpError.Message))\n\t\t\tc.Abort()\n\t\t} else {\n\t\t\tc.Next()\n\t\t}\n\t}\n}", "func NewQpsLimiter(opts ...QpsLimiterOpt) (*QpsLimiter, error) {\r\n\tvar qpsLimiter QpsLimiter\r\n\tif SetQpsLimiterErr := qpsLimiter.SetQpsLimiter(opts...); nil != SetQpsLimiterErr {\r\n\t\treturn nil, fmt.Errorf(\"SetQpsLimiter failed -> SetQpsLimiterErr:%v\", SetQpsLimiterErr)\r\n\t}\r\n\taddKillerCheck(killerFirstPriority, \"qpsLimiter_\"+qpsLimiter.bc.CfgData.Service, &qpsLimiter)\r\n\treturn &qpsLimiter, nil\r\n}", "func NewFixedLimiter(limit int64) *FixedLimiter {\n\treturn NewFixedLimiterWithValue(limit, 0)\n}" ]
[ "0.8107297", "0.7961854", "0.7885352", "0.7791581", "0.7787195", "0.7756457", "0.7716399", "0.7656956", "0.759678", "0.75580776", "0.75578725", "0.75571537", "0.7536802", "0.7390164", "0.7362798", "0.7298369", "0.7286124", "0.7258976", "0.72212106", "0.7175126", "0.7154756", "0.71323967", "0.7097979", "0.70607245", "0.7054532", "0.70188427", "0.6993049", "0.6962781", "0.69264627", "0.68832284", "0.68295765", "0.68288845", "0.6803783", "0.67903304", "0.66801184", "0.6663734", "0.66365844", "0.65840197", "0.65612316", "0.6524444", "0.649553", "0.6491596", "0.6491596", "0.6474134", "0.6451839", "0.6387449", "0.638083", "0.63135403", "0.62843424", "0.6268728", "0.62521744", "0.6227072", "0.6140869", "0.61044943", "0.6047673", "0.60184145", "0.60164624", "0.59510666", "0.59304833", "0.59190744", "0.5881906", "0.58550495", "0.5854143", "0.58454317", "0.58423436", "0.5832167", "0.58271444", "0.58239263", "0.5822151", "0.58068216", "0.5801317", "0.58009684", "0.57942873", "0.57942873", "0.57524455", "0.5752318", "0.5736171", "0.5712237", "0.5682505", "0.56804025", "0.5667662", "0.56667995", "0.5665169", "0.5655022", "0.5652545", "0.56512576", "0.56345886", "0.5624274", "0.56182605", "0.5576306", "0.55567616", "0.5554527", "0.5554365", "0.55466723", "0.55372095", "0.5535494", "0.5520254", "0.55171764", "0.55137795", "0.551097" ]
0.8463262
0
Limit limits the number of concurrent requests by 1 and blocks if the number of concurrent requests reached a maximum.
func (rater *RateLimiter) Limit() { <-rater.semaphore }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func lockLimitConnections() {\n\tsemaphoreMaxConnections <- struct{}{}\n}", "func LimitGoroutine() {\n\tconcurrency := 5\n\tsem := make(chan bool, concurrency)\n\turls := []string{\"http://jmoiron.net/blog/limiting-concurrency-in-go/\", \"https://github.com/go-sql-driver/mysql/tree/alloc-pool\"}\n\tfor _, url := range urls {\n\t\tsem <- true\n\t\tgo func(url string) {\n\t\t\tdefer func() {\n\t\t\t\t<-sem\n\t\t\t}()\n\t\t\tfmt.Println(\"imput url:\", url)\n\t\t\t// get the url\n\t\t}(url)\n\t}\n\tfor i := 0; i < cap(sem); i++ {\n\t\tsem <- true\n\t}\n}", "func (s ServiceLimiter) LimitRequest(r *request.Request) {\n\tif ol, ok := s.matchRequest(r); ok {\n\t\t_ = ol.Wait(r)\n\t}\n}", "func limitNumClients(f http.HandlerFunc, maxClients int) http.HandlerFunc {\n\tsema := make(chan struct{}, maxClients)\n\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\tsema <- struct{}{}\n\t\tdefer func() { <-sema }()\n\t\tf(w, req)\n\t}\n}", "func Test_Limiter_Concurrency(t *testing.T) {\n\tt.Parallel()\n\t// Test concurrency using a default store\n\n\tapp := fiber.New()\n\n\tapp.Use(New(Config{\n\t\tMax: 50,\n\t\tExpiration: 2 * time.Second,\n\t}))\n\n\tapp.Get(\"/\", func(c *fiber.Ctx) error {\n\t\treturn c.SendString(\"Hello tester!\")\n\t})\n\n\tvar wg sync.WaitGroup\n\tsingleRequest := func(wg *sync.WaitGroup) {\n\t\tdefer wg.Done()\n\t\tresp, err := app.Test(httptest.NewRequest(fiber.MethodGet, \"/\", nil))\n\t\tutils.AssertEqual(t, nil, err)\n\t\tutils.AssertEqual(t, fiber.StatusOK, resp.StatusCode)\n\n\t\tbody, err := io.ReadAll(resp.Body)\n\t\tutils.AssertEqual(t, nil, err)\n\t\tutils.AssertEqual(t, \"Hello tester!\", string(body))\n\t}\n\n\tfor i := 0; i <= 49; i++ {\n\t\twg.Add(1)\n\t\tgo singleRequest(&wg)\n\t}\n\n\twg.Wait()\n\n\tresp, err := app.Test(httptest.NewRequest(fiber.MethodGet, \"/\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 429, resp.StatusCode)\n\n\ttime.Sleep(3 * time.Second)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 200, resp.StatusCode)\n}", "func MaxInFlightLimit(c chan bool, longRunningRequestCheck LongRunningRequestCheck, handler http.Handler) http.Handler {\n\tif c == nil {\n\t\treturn handler\n\t}\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif longRunningRequestCheck(r) {\n\t\t\t// Skip tracking long running events.\n\t\t\thandler.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\t\tselect {\n\t\tcase c <- true:\n\t\t\tdefer func() { <-c }()\n\t\t\thandler.ServeHTTP(w, r)\n\t\tdefault:\n\t\t\ttooManyRequests(w)\n\t\t}\n\t})\n}", "func (r *Request) Limit(value int64) *Request {\n\tr.UnderlyingRequest.Limit(value)\n\treturn r\n}", "func (a *AQM) Limit() bm.HandlerFunc {\n\treturn func(c *bm.Context) {\n\t\tdone, err := a.limiter.Allow(c)\n\t\tif err != nil {\n\t\t\tstats.Incr(_family, c.Request.URL.Path[1:])\n\t\t\t// TODO: priority request.\n\t\t\t// c.JSON(nil, err)\n\t\t\t// c.Abort()\n\t\t\treturn\n\t\t}\n\t\tdefer func() {\n\t\t\tif c.Error != nil && !ecode.Deadline.Equal(c.Error) && c.Err() != context.DeadlineExceeded {\n\t\t\t\tdone(rate.Ignore)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdone(rate.Success)\n\t\t}()\n\t\tc.Next()\n\t}\n}", "func (m *MemLimiter) Limit(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"X-RateLimit-Limit\", strconv.Itoa(int(m.cfg.IpLimit)))\n\n\t\tip, _, _ := net.SplitHostPort(r.RemoteAddr)\n\t\turl := r.RequestURI\n\t\tipl := m.getLimiter(IpAddress, ip)\n\t\tpathl := m.getLimiter(URL, url)\n\n\t\tif ipl.Allow() == false || pathl.Allow() == false {\n\t\t\tw.Header().Set(\"X-RateLimit-Limit\", strconv.Itoa(int(m.cfg.IpLimit)))\n\t\t\thttp.Error(w, \"API rate limit exceeded\", http.StatusTooManyRequests)\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (r *Request) Limit(value int64) *Request {\n\treturn r.WithParam(common.ModifierLimit, strconv.FormatInt(value, 10))\n}", "func maxClients(h http.Handler, n int) http.Handler {\n\tsema := make(chan struct{}, n)\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tsema <- struct{}{}\n\t\tdefer func() { <-sema }()\n\n\t\th.ServeHTTP(w, r)\n\t})\n}", "func (l *ConLimiter) Limit(s *http.Server) {\n\ts.ConnState = func(c net.Conn, state http.ConnState) {\n\t\tswitch state {\n\t\tcase http.StateNew:\n\t\t\tatomic.AddInt32(&l.current, 1)\n\t\t\tif l.Max < atomic.LoadInt32(&l.current) {\n\t\t\t\tc.Close()\n\t\t\t}\n\t\tcase http.StateHijacked:\n\t\t\tatomic.AddInt32(&l.current, -1)\n\t\tcase http.StateClosed:\n\t\t\tatomic.AddInt32(&l.current, -1)\n\t\t}\n\t}\n}", "func throttled(threshold int64, h http.Handler) http.Handler {\n\tvar active int64\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tcurrent := atomic.AddInt64(&active, 1)\n\t\tdefer atomic.AddInt64(&active, -1)\n\n\t\tif current-1 >= threshold {\n\t\t\tlog.Warnf(\"Reached threshold of %d concurrent active clients\", threshold)\n\t\t\thttp.Error(w, \"429 Too Many Requests\", http.StatusTooManyRequests)\n\t\t\treturn\n\t\t}\n\n\t\th.ServeHTTP(w, r)\n\t})\n}", "func (lm *SimpleManager) Limit(l chan int) <-chan bool {\n\tdone := make(chan bool, 1)\n\tready := make(chan struct{})\n\tlm.newLimit <- &limit{\n\t\tlim: l,\n\t\tdone: done,\n\t\tready: ready,\n\t}\n\t<-ready\n\treturn done\n}", "func Limit(config *Config, limiterMap *LimitMap) gin.HandlerFunc {\r\n\tignoreMethods := config.IgnoreMethods\r\n\ttimeLimitPerAct := config.TimeLimitPerAct\r\n\tper := perOption(config.Per)\r\n\tmaxSlack := slackOption(config.MaxSlack)\r\n\tif ignoreMethods != nil {\r\n\t\tdefaultNegelectMethods = ignoreMethods\r\n\t}\r\n\tif timeLimitPerAct != 0 {\r\n\t\tdefaultTimeLimitPerAct = timeLimitPerAct\r\n\t}\r\n\tif per != 0 {\r\n\t\tdefaultPer = per\r\n\t}\r\n\tif maxSlack != 0 {\r\n\t\tdefaultMaxSlack = maxSlack\r\n\t}\r\n\treturn func(c *gin.Context) {\r\n\t\tlimiter := limiterMap.get(c.ClientIP())\r\n\t\tif limiter != nil {\r\n\t\t\tlimiter.Take()\r\n\t\t} else {\r\n\t\t\tlimiterMap.add(c.ClientIP())\r\n\t\t}\r\n\t\tc.Next()\r\n\t}\r\n}", "func (l *Limiter) limit(w http.ResponseWriter, r *http.Request, h http.Handler) {\n\tavailable := l.bucket.TakeAvailable(1)\n\n\theaders := w.Header()\n\theaders.Set(\"X-RateLimit-Limit\", strconv.Itoa(l.capacity()))\n\theaders.Set(\"X-RateLimit-Remaining\", strconv.Itoa(l.remaining()))\n\n\t// If tokens are not available, reply with error, usually with 429\n\tif available == 0 {\n\t\tl.responder(w, r)\n\t\treturn\n\t}\n\n\t// Otherwise track time and forward the request\n\th.ServeHTTP(w, r)\n}", "func UseMaxConnections(max int) {\n\tsemaphoreMaxConnections = make(chan struct{}, max)\n}", "func (l *GoLimiter) Limit(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Get the IP address for the current user.\n\t\tip, _, err := net.SplitHostPort(r.RemoteAddr)\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\thttp.Error(w, \"Internal Server Error\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tkeyName := utils.NewKeyName(r.Method, r.RequestURI, ip)\n\n\t\t// Call the getRateLimiter function to retreive the rate limiter for the current user.\n\t\trateLimiter := l.getRateLimiter(keyName)\n\n\t\tif rateLimiter.Allow() == false {\n\t\t\thttp.Error(w, http.StatusText(429), http.StatusTooManyRequests)\n\t\t\treturn\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (c *ConcurrencyLimiter) handleLimits() {\n\tfor {\n\t\tr := <-c.inc\n\t\tif c.count >= c.max {\n\t\t\t<-c.dec\n\t\t\tc.count--\n\t\t}\n\t\tc.count++\n\t\tr <- struct{}{}\n\t}\n}", "func RateLimiting() {\n\n\t// First we’ll look at basic rate limiting.\n\t// Suppose we want to limit our handling of incoming requests.\n\t// We’ll serve these requests off a channel of the same name.\n\trequests := make(chan int, 5)\n\tfor i := 1; i <= 5; i++ {\n\t\trequests <- i\n\t}\n\tclose(requests)\n\n\t// This limiter channel will receive a value every 200 milliseconds.\n\t// This is the regulator in our rate limiting scheme.\n\tlimiter := time.Tick(200 * time.Millisecond)\n\n\t// By blocking on a receive from the limiter channel before serving each request,\n\t// we limit ourselves to 1 request every 200 milliseconds.\n\tfor req := range requests {\n\t\t<-limiter\n\t\tfmt.Println(\"request\", req, time.Now())\n\t}\n\t// We may want to allow short bursts of requests in our rate limiting\n\t// scheme while preserving the overall rate limit.\n\t//We can accomplish this by buffering our limiter channel.\n\t//This burstyLimiter channel will allow bursts of up to 3 events.\n\tburstyLimiter := make(chan time.Time, 3)\n\n\t// Fill up the channel to represent allowed bursting.\n\tfor i := 0; i < 3; i++ {\n\t\tburstyLimiter <- time.Now()\n\t}\n\n\t// Every 200 milliseconds we’ll try to add a new value to burstyLimiter, up to its limit of 3.\n\tgo func() {\n\t\tfor t := range time.Tick(200 * time.Millisecond) {\n\t\t\tburstyLimiter <- t\n\t\t}\n\t}()\n\n\t// Now simulate 5 more incoming requests.\n\t// The first 3 of these will benefit from the burst capability of burstyLimiter.\n\tburstyRequests := make(chan int, 5)\n\n\tfor i := 1; i <= 5; i++ {\n\t\tburstyRequests <- i\n\t}\n\tclose(burstyRequests)\n\tfor req := range burstyRequests {\n\t\t<-burstyLimiter\n\t\tfmt.Println(\"request\", req, time.Now())\n\t}\n\t// Running our program we see the first batch of requests handled once every ~200 milliseconds as desired.\n\t// For the second batch of requests we serve the first 3 immediately\n\t// because of the burstable rate limiting, then serve the remaining 2 with ~200ms delays each.\n\n}", "func NewConcurrentLimit(n int) *ConcurrentLimit {\n\treturn &ConcurrentLimit{make(chan bool, n)}\n}", "func MaxInMultipleRequestsWithCancellation(urls []string) (int, error) {\n\tch := make(chan int)\n\terrCh := make(chan error)\n\n\tctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)\n\tdefer cancel()\n\n\tfor _, url := range urls {\n\t\tgo func(url string) {\n\t\t\tcode, err := makeRequestWithCancellationAndContext(ctx, url)\n\t\t\tif err != nil {\n\t\t\t\terrCh <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tch <- code\n\t\t}(url)\n\t}\n\n\tvar max int\n\tfor i := 0; i < len(urls); i++ {\n\t\tselect {\n\t\tcase v := <-ch:\n\t\t\tif v > max {\n\t\t\t\tmax = v\n\t\t\t}\n\t\tcase <-errCh:\n\t\t\treturn 0, errors.New(\"at least 1 failed\")\n\t\t}\n\t}\n\treturn max, nil\n}", "func (l *ConcurrencyLimit) Limit() func() {\n\tl.Use()\n\treturn func() {\n\t\tl.Free()\n\t}\n}", "func NewConcurrencyLimiter(max int) *ConcurrencyLimiter {\n\tc := &ConcurrencyLimiter{\n\t\tinc: make(chan chan struct{}),\n\t\tdec: make(chan struct{}, max),\n\t\tmax: max,\n\t}\n\tgo c.handleLimits()\n\treturn c\n}", "func RateLimit(max float64) gin.HandlerFunc {\n\n\tlmt := tollbooth.NewLimiter(max, nil)\n\n\treturn func(c *gin.Context) {\n\t\thttpError := tollbooth.LimitByRequest(lmt, c.Writer, c.Request)\n\t\tif httpError != nil {\n\t\t\tc.Data(httpError.StatusCode, lmt.GetMessageContentType(), []byte(httpError.Message))\n\t\t\tc.Abort()\n\t\t} else {\n\t\t\tc.Next()\n\t\t}\n\t}\n}", "func (lm *SimpleManager) SimpleLimit(n int, t time.Duration) <-chan bool {\n\tdone := make(chan bool, 1)\n\tready := make(chan struct{})\n\tlm.newLimit <- &limit{\n\t\trate: rate{n, t},\n\t\tdone: done,\n\t\tready: ready,\n\t}\n\t<-ready\n\treturn done\n}", "func (r *RateLimit) Limit(ctx context.Context, f request.EndpointLimit) error {\n\tswitch f {\n\t// TODO: Add futures and swap functionality\n\tcase huobiFuturesAuth:\n\t\treturn r.FuturesAuth.Wait(ctx)\n\tcase huobiFuturesUnAuth:\n\t\treturn r.FuturesUnauth.Wait(ctx)\n\tcase huobiFuturesTransfer:\n\t\treturn r.FuturesXfer.Wait(ctx)\n\tcase huobiSwapAuth:\n\t\treturn r.SwapAuth.Wait(ctx)\n\tcase huobiSwapUnauth:\n\t\treturn r.SwapUnauth.Wait(ctx)\n\tdefault:\n\t\t// Spot calls\n\t\treturn r.Spot.Wait(ctx)\n\t}\n}", "func Throttle(maxConcurrent int, timeout time.Duration) usrv.EndpointOption {\n\n\treturn func(ep *usrv.Endpoint) error {\n\n\t\tif maxConcurrent <= 0 {\n\t\t\treturn errors.New(\"maxConcurrent should be > 0\")\n\t\t}\n\n\t\t// Allocate a buffered channel and pre-fill it with tokens\n\t\ttokens := make(chan struct{}, maxConcurrent)\n\t\tfor i := 0; i < maxConcurrent; i++ {\n\t\t\ttokens <- struct{}{}\n\t\t}\n\n\t\t// Wrap original method\n\t\toriginalHandler := ep.Handler\n\t\tep.Handler = usrv.HandlerFunc(func(ctx context.Context, responseWriter usrv.ResponseWriter, request *usrv.Message) {\n\t\t\tif timeout > 0 {\n\t\t\t\tvar cancelFunc context.CancelFunc\n\t\t\t\tctx, cancelFunc = context.WithTimeout(ctx, timeout)\n\t\t\t\tdefer cancelFunc()\n\t\t\t}\n\n\t\t\tselect {\n\t\t\tcase <-tokens:\n\t\t\t\t// We got a token, execute request\n\t\t\t\toriginalHandler.Serve(ctx, responseWriter, request)\n\n\t\t\t\t// Return back token\n\t\t\t\ttokens <- struct{}{}\n\t\t\tcase <-ctx.Done():\n\t\t\t\tresponseWriter.WriteError(ctx.Err())\n\t\t\t}\n\n\t\t})\n\n\t\treturn nil\n\t}\n}", "func TestRateLimitHandler(t *testing.T) {\n\t// save the global Max connections\n\tsaveGlobalMaxConn := globalMaxConn\n\n\tglobalMaxConn = 1\n\ttestHandler := func(w http.ResponseWriter, r *http.Request) {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\tfmt.Fprintln(w, \"Hello client!\")\n\t}\n\trlh := setRateLimitHandler(http.HandlerFunc(testHandler))\n\tts := httptest.NewServer(rlh)\n\trespCh := make(chan int)\n\tstartTime := time.Now()\n\tfor i := 0; i < 6; i++ {\n\t\tgo func(ch chan<- int) {\n\t\t\tresp, err := http.Get(ts.URL)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\n\t\t\t\t\t\"Got error requesting test server - %v\\n\",\n\t\t\t\t\terr,\n\t\t\t\t)\n\t\t\t}\n\t\t\trespCh <- resp.StatusCode\n\t\t}(respCh)\n\t}\n\n\ttooManyReqErrCount := 0\n\tfor i := 0; i < 6; i++ {\n\t\tcode := <-respCh\n\t\tif code == 429 {\n\t\t\ttooManyReqErrCount++\n\t\t} else if code != 200 {\n\t\t\tt.Errorf(\"Got non-200 resp code - %d\\n\", code)\n\t\t}\n\t}\n\tduration := time.Since(startTime)\n\tif duration < time.Duration(500*time.Millisecond) {\n\t\t// as globalMaxConn is 1, only 1 request will execute\n\t\t// at a time, and the five allowed requested will take\n\t\t// at least 500 ms.\n\t\tt.Errorf(\"Expected all requests to take at least 500ms, but it was done in %v\\n\",\n\t\t\tduration)\n\t}\n\tif tooManyReqErrCount != 1 {\n\t\tt.Errorf(\"Expected to get 1 error, but got %d\",\n\t\t\ttooManyReqErrCount)\n\t}\n\tts.Close()\n\n\t// restore the global Max connections\n\tglobalMaxConn = saveGlobalMaxConn\n}", "func Limit(val int) Argument {\n\treturn func(request *requests.Request) error {\n\t\tif val < 20 || 100 < val {\n\t\t\treturn errors.New(\"limit must be an integer greater or equal to 20 and lesser or equal to 100\")\n\t\t}\n\t\trequest.AddArgument(\"limit\", strconv.Itoa(val))\n\t\treturn nil\n\t}\n}", "func ParallelRequest(reqs []Request, N int) []datastructure.Response {\n\tvar wg sync.WaitGroup\n\tvar results = make([]datastructure.Response, len(reqs))\n\t// Need to fix the hardcoded limit\n\tulimitCurr := 512\n\tif N >= ulimitCurr {\n\t\tN = int(float64(ulimitCurr) * 0.7)\n\t\tlog.Warning(\"Provided a thread factor greater than current ulimit size, setting at MAX [\", N, \"] requests\")\n\t}\n\tfor i := range reqs {\n\t\treqs[i].Tr.MaxIdleConns = N\n\t\t// FIXME: Understand if can cause error on delay network\n\t\treqs[i].Tr.IdleConnTimeout = time.Duration(1) * time.Second\n\t\treqs[i].Tr.MaxIdleConnsPerHost = N\n\t\treqs[i].Tr.MaxConnsPerHost = N\n\t}\n\n\tsemaphore := make(chan struct{}, N)\n\twg.Add(len(reqs))\n\tclient := &http.Client{\n\t\tTransport: reqs[0].Tr,\n\t}\n\tfor i := 0; i < len(reqs); i++ {\n\t\tgo func(i int) {\n\t\t\tsemaphore <- struct{}{}\n\t\t\tresults[i] = reqs[i].ExecuteRequest(client)\n\t\t\twg.Done()\n\t\t\tfunc() { <-semaphore }()\n\t\t}(i)\n\t}\n\twg.Wait()\n\treturn results\n}", "func TestConcurrencyLimit(t *testing.T) {\n\tt.Parallel()\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tt.Cleanup(cancel)\n\n\tconfig := Config{MaxConcurrency: 4}\n\tcountdown := NewCountdown(config.MaxConcurrency * 2)\n\tprocess := NewMockEventsProcess(ctx, t, config, func(ctx context.Context, event types.Event) error {\n\t\tdefer countdown.Decrement()\n\t\ttime.Sleep(time.Second)\n\t\treturn trace.Wrap(ctx.Err())\n\t})\n\n\ttimeBefore := time.Now()\n\tfor i := 0; i < config.MaxConcurrency; i++ {\n\t\tresource, err := types.NewAccessRequest(fmt.Sprintf(\"REQ-%v\", i+1), \"foo\", \"admin\")\n\t\trequire.NoError(t, err)\n\n\t\tfor j := 0; j < 2; j++ {\n\t\t\tprocess.Events.Fire(types.Event{Type: types.OpPut, Resource: resource})\n\t\t}\n\t}\n\trequire.NoError(t, countdown.Wait(ctx))\n\n\ttimeAfter := time.Now()\n\tassert.InDelta(t, 4*time.Second, timeAfter.Sub(timeBefore), float64(750*time.Millisecond))\n}", "func (c *ReconcileCall) Limit(limit int64) *ReconcileCall {\n\tc.urlParams_.Set(\"limit\", fmt.Sprint(limit))\n\treturn c\n}", "func Example_httpRequestThroughputLimitation() {\n\tlimiter := func(limit int, timeout time.Duration, handler http.HandlerFunc) http.HandlerFunc {\n\t\tthroughput := semaphore.New(limit)\n\t\treturn func(rw http.ResponseWriter, req *http.Request) {\n\t\t\tdeadline := semaphore.WithTimeout(timeout)\n\n\t\t\trelease, err := throughput.Acquire(deadline)\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(rw, err.Error(), http.StatusTooManyRequests)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer release()\n\n\t\t\thandler.ServeHTTP(rw, req)\n\t\t}\n\t}\n\n\tvar race int\n\tts := httptest.NewServer(limiter(1, sla, http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {\n\t\t// do some limited work\n\t\trace++\n\t})))\n\tdefer ts.Close()\n\n\tok, fail := sendParallelHTTPRequestsToURL(5, ts.URL)\n\n\tfmt.Printf(\"success: %d, failure: %d, race: %t \\n\", ok, fail, race != 5)\n\t// Output: success: 5, failure: 0, race: false\n}", "func runRequests(rate float64, req *http.Request, res chan Result, total uint64) {\n\tthrottle := time.Tick(time.Duration(1e9 / rate))\n\tfmt.Println(\"Throttle:\", time.Duration(1e9/rate))\n\n\tfor i := 0; uint64(i) < total; i++ {\n\t\tgo runRequest(req, res)\n\t\tif total > 1 {\n\t\t\t<-throttle\n\t\t}\n\t}\n}", "func UpdateConcurrencyLimit(limits map[string]int) {\n\tfor name, ins := range insList {\n\t\tv := limits[name]\n\t\tlimit := int32(v)\n\t\tif ins.Config.MaxConcurrency != limit {\n\t\t\tins.SetMaxConcurrency(limit)\n\t\t}\n\t}\n}", "func (c *LimitedConnection) rateLimitLoop(notBefore *time.Time,\n\tdeadline *time.Time, innerAct func([]byte) (int, error),\n\tb []byte) (cntr int, err error) {\n\tif len(b) == 0 {\n\t\treturn\n\t}\n\n\tnow := time.Now()\n\tvar until time.Time\n\n\t// Grab the limiter and abortwait until end of operation.\n\tc.limiterMu.RLock()\n\tlimiter := c.limiter\n\tabortWait := c.abortWait\n\tif now.Before(*notBefore) {\n\t\tuntil = *notBefore\n\t\tif !deadline.IsZero() && deadline.Before(until) {\n\t\t\tuntil = *deadline\n\t\t}\n\t}\n\tc.limiterMu.RUnlock()\n\n\tif !until.IsZero() {\n\t\tif c.waitUntil(abortWait, until) {\n\t\t\terr = io.ErrClosedPipe\n\t\t\treturn\n\t\t}\n\t}\n\n\tburst := limiter.Burst()\n\tfor cntr < len(b) && err == nil {\n\t\tvar n int\n\t\tif burst > len(b)-cntr {\n\t\t\tburst = len(b) - cntr\n\t\t}\n\t\tn, err = innerAct(b[cntr:][:burst])\n\t\tif n == 0 {\n\t\t\treturn\n\t\t}\n\n\t\tcntr += n\n\t\tuntil = time.Time{}\n\n\t\tnow = time.Now()\n\t\tr := limiter.ReserveN(now, n)\n\t\tact := now.Add(r.DelayFrom(now))\n\t\tif now.Before(act) {\n\t\t\tif !deadline.IsZero() && deadline.Before(act) {\n\t\t\t\tc.limiterMu.RLock()\n\t\t\t\t// What I want to avoid here is the case when limiter got updated and\n\t\t\t\t// \"Not before\"s got reset during limiter update, but we don't know\n\t\t\t\t// about it and are going to write outdated value to notBefore.\n\t\t\t\t// A good test for this is checking if our cached abortWait is closed\n\t\t\t\tselect {\n\t\t\t\tcase <-abortWait:\n\t\t\t\t\t// Do nothing, our limits are no longer valid\n\t\t\t\tdefault:\n\t\t\t\t\t*notBefore = act\n\t\t\t\t}\n\t\t\t\tc.limiterMu.RUnlock()\n\t\t\t\terr = timeoutError{}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tuntil = act\n\t\t}\n\t\tif !until.IsZero() {\n\t\t\tif c.waitUntil(abortWait, act) {\n\t\t\t\terr = io.ErrClosedPipe\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (r *Responder) TooManyRequests() { r.write(http.StatusTooManyRequests) }", "func Max(n int) PoolOption {\n\treturn func(p *GoroutinePool) {\n\t\tp.maxChan = make(chan struct{}, n)\n\t}\n}", "func (s *Server) Limit(limiter Limiter) grpc.UnaryServerInterceptor {\n\treturn func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {\n\t\tif limiter.Allow(info.FullMethod) {\n\t\t\tif s.Proba.TrueOrNot() {\n\t\t\t\ts.Logger.Error(\"Limit exceed\", zap.String(\"method\", info.FullMethod))\n\t\t\t}\n\t\t\t//在触发RPC调用前就return了,所以其他需要捕获错误的中间件需要设置在limiter之前\n\t\t\t//return nil, status.Errorf(codes.ResourceExhausted, \"%s is rejected by ratelimit middleware\", info.FullMethod)\n\t\t\t//for short metrics:atreusns_atreusss_server_counter_total{code=\"ErrRatelimit\",method=\"/proto.GreeterService/SayHello\",type=\"unary\"} 2\n\t\t\treturn nil, status.Error(codes.ResourceExhausted, pyerrors.RatelimiterServiceReject)\n\t\t}\n\n\t\treturn handler(ctx, req)\n\t}\n}", "func main() {\n\tvar limiter *ratelimit.Bucket\n\tlimiter = ratelimit.NewBucket(time.Second, 10)\n\tfor i := 0; i < 100; i++ {\n\t\tfmt.Println(limiter.TakeAvailable(1))\n\t\tif i%10 == 0 {\n\t\t\ttime.Sleep(500 * time.Millisecond)\n\t\t}\n\t}\n}", "func WithMaxRequestCount(c uint32) OptionFunc {\n\treturn func(opts *poolOptions) {\n\t\topts.maxRequestCount = c\n\t}\n}", "func TooManyRequests(w http.ResponseWriter, message ...interface{}) {\n\tboom(w, 429, message...)\n}", "func (r *Request) LimitBytes(n int64) *Request {\n\tpanic(\"TODO\")\n\treturn r\n}", "func (o CircuitBreakersResponseOutput) MaxRequests() pulumi.IntOutput {\n\treturn o.ApplyT(func(v CircuitBreakersResponse) int { return v.MaxRequests }).(pulumi.IntOutput)\n}", "func (o CircuitBreakersOutput) MaxRequests() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v CircuitBreakers) *int { return v.MaxRequests }).(pulumi.IntPtrOutput)\n}", "func MaxConn(n int) server.Option {\n\treturn server.SetOption(maxConnKey{}, n)\n}", "func ActLimit(ctx echo.Context, id, action string, maxCount, period int) int {\n\treqTimeSec, err := strconv.ParseInt(ctx.Request().Header.Get(\"REQUEST_TIME\"), 10, 64)\n\treqTime := time.Now()\n\tif err == nil {\n\t\treqTime = time.Unix(reqTimeSec, 0)\n\t}\n\n\treqTimeUnix := int(reqTime.Unix())\n\tttl := reqTimeUnix/period*period + period - reqTimeUnix\n\tkey := fmt.Sprintf(\"mdclubgo_throttle_%s_%s\", action, id)\n\tcurrentCount, err := strconv.Atoi(cache.Get(key, \"0\"))\n\tcurrentCount++\n\tif err != nil || currentCount > maxCount {\n\t\tif err != nil {\n\t\t\tlog.Error(fmt.Errorf(\"act limit get cache: %w\", err).Error())\n\t\t}\n\n\t\treturn 0\n\t}\n\n\terr = cache.Set(key, fmt.Sprintf(\"%d\", currentCount), ttl)\n\tif err != nil {\n\t\tlog.Error(fmt.Errorf(\"act limit set cache: %w\", err).Error())\n\t}\n\n\treturn maxCount - currentCount + 1\n}", "func (ch *Chain) WaitForRequestsThrough(numReq int, maxWait ...time.Duration) bool {\n\tmaxw := 5 * time.Second\n\tvar deadline time.Time\n\tif len(maxWait) > 0 {\n\t\tmaxw = maxWait[0]\n\t}\n\tdeadline = time.Now().Add(maxw)\n\tfor {\n\t\tmstats := ch.mempool.Info()\n\t\tif mstats.InBufCounter == numReq && mstats.OutPoolCounter == numReq {\n\t\t\treturn true\n\t\t}\n\t\tif time.Now().After(deadline) {\n\t\t\tch.Log.Errorf(\"WaitForRequestsThrough. failed waiting max %v for %d requests through . Current IN: %d, OUT: %d\",\n\t\t\t\tmaxw, numReq, mstats.InBufCounter, mstats.OutPoolCounter)\n\t\t\treturn false\n\t\t}\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n}", "func (b *Backend) ConcurrentRequestCount() int {\n\treturn (int)(atomic.LoadInt32(&b.requestCounter))\n}", "func TestRequestRateLimiter(t *testing.T) {\n\toverLimitCallCount := 5 // number of requests that will exceed the rate limits\n\tserverAddress := \"127.0.0.1:3598\"\n\n\t// Setup a mock audit logger, audit logger is used for logging over limit calls\n\tctrl := gomock.NewController(t)\n\tdefer ctrl.Finish()\n\tauditLogger := mock_audit.NewMockAuditLogger(ctrl)\n\tauditLogger.EXPECT().\n\t\tLog(gomock.Any(), http.StatusTooManyRequests, \"\").\n\t\tTimes(overLimitCallCount).\n\t\tReturn()\n\n\t// Setup a simple router with a simple handler\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"/\", helloWorldHandler())\n\n\t// Setup the server with a low rate limit for testing\n\tserver, err := NewServer(auditLogger,\n\t\tWithHandler(router),\n\t\tWithListenAddress(serverAddress),\n\t\tWithSteadyStateRate(1),\n\t\tWithBurstRate(1),\n\t)\n\trequire.NoError(t, err)\n\n\t// Start the server\n\tstartServer(t, server)\n\tdefer server.Close()\n\n\tclient := http.DefaultClient\n\terr = waitForServer(client, serverAddress)\n\trequire.NoError(t, err)\n\n\t// send quick requests to exceed the rate limit and assert that they fail with 429\n\tfor i := 0; i < overLimitCallCount; i++ {\n\t\tres, err := client.Get(\"http://\" + serverAddress)\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, http.StatusTooManyRequests, res.StatusCode)\n\t}\n}", "func defaultMaxInflightRequests(n int) option.ClientOption {\n\treturn &defaultInflightRequestsSetting{maxRequests: n}\n}", "func DefaultLimitReachedHandler(w http.ResponseWriter, r *http.Request) {\n\thttp.Error(w, \"Limit exceeded\", http.StatusTooManyRequests)\n}", "func limit(n int64) int {\n\tif n < 0 || maxio < n {\n\t\tFatal(\"bad io size:\", n)\n\t}\n\treturn int(n)\n}", "func (c *metricMetadataAPI) MaximumLiveRequests() int {\n\treturn cap(c.backgroundQueue)\n}", "func Test_Limiter_Sliding_Window_Skip_Successful_Requests(t *testing.T) {\n\tt.Parallel()\n\t// Test concurrency using a default store\n\n\tapp := fiber.New()\n\n\tapp.Use(New(Config{\n\t\tMax: 1,\n\t\tExpiration: 2 * time.Second,\n\t\tSkipSuccessfulRequests: true,\n\t\tLimiterMiddleware: SlidingWindow{},\n\t}))\n\n\tapp.Get(\"/:status\", func(c *fiber.Ctx) error {\n\t\tif c.Params(\"status\") == \"fail\" {\n\t\t\treturn c.SendStatus(400)\n\t\t}\n\t\treturn c.SendStatus(200)\n\t})\n\n\tresp, err := app.Test(httptest.NewRequest(fiber.MethodGet, \"/success\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 200, resp.StatusCode)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 400, resp.StatusCode)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 429, resp.StatusCode)\n\n\ttime.Sleep(4 * time.Second)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 400, resp.StatusCode)\n}", "func (m *RateLimitedMux) rateLimit(c web.C, w http.ResponseWriter, r *http.Request, limits []int, handler web.Handler) {\n\tif m.limiter == nil || r.Header.Get(IsAdminHeader) == IsAdminHeaderValue {\n\t\thandler.ServeHTTPC(c, w, r)\n\t\treturn\n\t}\n\n\tlimit := 0\n\tfor _, v := range limits {\n\t\tlimit += v\n\t}\n\n\tif limit == 0 {\n\t\thandler.ServeHTTPC(c, w, r)\n\t\treturn\n\t}\n\n\tkey := r.Header.Get(signcontrol.PublicKeyHeader)\n\n\tlimited, context, err := m.limiter.RateLimit(key, limit)\n\n\tif err != nil {\n\t\tlog.WithField(\"service\", \"rate-limiter\").WithError(err).Error(\"failed to rate limit\")\n\t\thandler.ServeHTTPC(c, w, r)\n\t\treturn\n\t}\n\n\tif v := context.Limit; v >= 0 {\n\t\tw.Header().Add(\"X-RateLimit-Limit\", strconv.Itoa(v))\n\t}\n\n\tif v := context.Remaining; v >= 0 {\n\t\tw.Header().Add(\"X-RateLimit-Remaining\", strconv.Itoa(v))\n\t}\n\n\tif v := context.ResetAfter; v >= 0 {\n\t\tvi := int(math.Ceil(v.Seconds()))\n\t\tw.Header().Add(\"X-RateLimit-Reset\", strconv.Itoa(vi))\n\t}\n\n\tif v := context.RetryAfter; v >= 0 {\n\t\tvi := int(math.Ceil(v.Seconds()))\n\t\tw.Header().Add(\"Retry-After\", strconv.Itoa(vi))\n\t}\n\n\tif !limited {\n\t\thandler.ServeHTTPC(c, w, r)\n\t} else {\n\t\tproblem.Render(nil, w, &problem.RateLimitExceeded)\n\t\treturn\n\t}\n\n}", "func (r *Search) MaxConcurrentShardRequests(maxconcurrentshardrequests string) *Search {\n\tr.values.Set(\"max_concurrent_shard_requests\", maxconcurrentshardrequests)\n\n\treturn r\n}", "func (rp *Pool) NextRequests(maxCount int, maxSizeBytes uint64, check bool) (batch [][]byte, full bool) {\n\trp.lock.Lock()\n\tdefer rp.lock.Unlock()\n\n\tif check {\n\t\tif (len(rp.existMap) < maxCount) && (rp.sizeBytes < maxSizeBytes) {\n\t\t\treturn nil, false\n\t\t}\n\t}\n\n\tcount := minInt(rp.fifo.Len(), maxCount)\n\tvar totalSize uint64\n\tbatch = make([][]byte, 0, count)\n\telement := rp.fifo.Front()\n\tfor i := 0; i < count; i++ {\n\t\treq := element.Value.(*requestItem).request\n\t\treqLen := uint64(len(req))\n\t\tif totalSize+reqLen > maxSizeBytes {\n\t\t\trp.logger.Debugf(\"Returning batch of %d requests totalling %dB as it exceeds threshold of %dB\",\n\t\t\t\tlen(batch), totalSize, maxSizeBytes)\n\t\t\treturn batch, true\n\t\t}\n\t\tbatch = append(batch, req)\n\t\ttotalSize += reqLen\n\t\telement = element.Next()\n\t}\n\n\tfullS := totalSize >= maxSizeBytes\n\tfullC := len(batch) == maxCount\n\tfull = fullS || fullC\n\tif len(batch) > 0 {\n\t\trp.logger.Debugf(\"Returning batch of %d requests totalling %dB\",\n\t\t\tlen(batch), totalSize)\n\t}\n\treturn batch, full\n}", "func (n *Globals) RateLimit(url string) {\n\tif rateLimiter, ok := n.rateLimiters[url]; ok {\n\t\trateLimiter.Wait()\n\t}\n}", "func (o CircuitBreakersOutput) MaxRequestsPerConnection() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v CircuitBreakers) *int { return v.MaxRequestsPerConnection }).(pulumi.IntPtrOutput)\n}", "func ThrottleConcurrency(f OnMissHandler, maxconcurrent uint) OnMissHandler {\n\tblock := make(chan int, maxconcurrent)\n\treturn func(key string) (Cacheable, error) {\n\t\tblock <- 58008\n\t\tres, err := f(key)\n\t\t<-block\n\t\treturn res, err\n\t}\n}", "func Max(maxConns int) Allow {\n\tconnsMu := new(sync.RWMutex)\n\tconns := 0\n\n\treturn func(conn net.Conn) (error, Cleanup) {\n\t\tif maxConns < 0 {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\t// Pre-emptive read-lock check.\n\t\tconnsMu.RLock()\n\t\tallow := conns < maxConns\n\t\tconnsMu.RUnlock()\n\t\tif !allow {\n\t\t\treturn ErrMaxConnectionsExceeded, nil\n\t\t}\n\n\t\t// Concurrent-safe write-lock check.\n\t\tconnsMu.Lock()\n\t\tif conns < maxConns {\n\t\t\tconns++\n\t\t} else {\n\t\t\tallow = false\n\t\t}\n\t\tconnsMu.Unlock()\n\t\tif !allow {\n\t\t\treturn ErrMaxConnectionsExceeded, nil\n\t\t}\n\n\t\treturn nil, func() {\n\t\t\tconnsMu.Lock()\n\t\t\tconns--\n\t\t\tconnsMu.Unlock()\n\t\t}\n\t}\n}", "func Limit(limit int) DeviceRequestOption {\n\treturn func(opts *deviceRequestOpts) error {\n\t\tif limit > 1000 {\n\t\t\treturn errors.New(\"limit must not be higher than 1000\")\n\t\t}\n\t\topts.Limit = limit\n\t\treturn nil\n\t}\n}", "func (s *TestingSemaphore) SetLimit(n int) {\n\ts.limit = n\n}", "func (r *Reader) Limit(lch chan int) <-chan bool {\n\tdone := make(chan bool, 1)\n\tready := make(chan struct{})\n\tr.newLimit <- &limit{\n\t\tlim: lch,\n\t\tdone: done,\n\t\tready: ready,\n\t}\n\t<-ready\n\treturn done\n}", "func serveRequest(w http.ResponseWriter, r *http.Request) {\n\tconcurrentRequests++\n\tif concurrentRequests > maxConcurrentRequest {\n\t\tdieOvercapacity(fmt.Sprintf(\"More than %02d concurrentRequests: dying!\\n\", maxConcurrentRequest))\n\t}\n\n\tsemaphore <- true\n\ttotalRequestsProcessed++\n\treqSerialNumber := totalRequestsProcessed\n\tinProgress[reqSerialNumber] = true\n\t<-semaphore\n\tnapTime, napFunc := randomSleep(999)\n\tfmt.Fprintf(w, \"INFO:\\n====\\n\")\n\tfmt.Fprintf(w, \"Request #%04d for '%+v'. Currently %02d requests\\n\", reqSerialNumber,\n\t\tr.URL, concurrentRequests)\n\tfmt.Fprintf(w, \"#%04d: Milliseconds until completion:\\t%04d.\\n\", reqSerialNumber, napTime/time.Millisecond)\n\tlog.Printf(\"INFO:\\n====\\n\")\n\tlog.Printf(\"Request #%04d for '%+v'. Currently %02d requests\\n\", reqSerialNumber,\n\t\tr.URL, concurrentRequests)\n\tlog.Printf(\"#%04d: Milliseconds until completion:\\t%04d.\\n\", reqSerialNumber, napTime/time.Millisecond)\n\tnapFunc()\n\tsemaphore <- true\n\tconcurrentRequests--\n\tdelete (inProgress, reqSerialNumber)\n\t<-semaphore\n\tfmt.Fprintf(w, \"Request #%04d: Done. Currently %02d requests\\n\\n\",\n\t\treqSerialNumber, concurrentRequests)\n\tlog.Printf(\"Request #%04d: Done. Currently %02d requests\\n\\n\",\n\t\treqSerialNumber, concurrentRequests)\n\treturn\n}", "func (rl *RateLimiter) AllowRequest(id string) (bool, error) {\n\tnow := time.Now().UnixNano() / 1000 //microseconds\n\tclearBefore := now - (rl.intervalInMillis * 1000) //microseconds\n\tlog.Debug(\"clearBefore \", clearBefore)\n\n\telement, err := uuid()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tlog.Debug(\"new element \", element)\n\n\tnewZSetExpireTime := rl.intervalInMillis/1000\n\n\tcmd := rl.client.Eval(concurrent_requests_limiter_lua, []string{id},rl.maxInInterval, now,element, clearBefore, newZSetExpireTime)\n\tif cmd.Err() != nil {\n\t\tlog.Warn(\"script execution error\", cmd.Err().Error())\n\t\treturn false, cmd.Err()\n\t}\n\n\tcmdOutput := cmd.Val()\n\tlog.Debug(\"script output \", cmdOutput)\n\toutputSlice, ok := cmdOutput.([]interface{})\n\tif !ok {\n\t\treturn false, errors.New(\"Unexcepted result type from Redis script execution\")\n\t}\n\n\treturn outputSlice[0] != nil, nil\n}", "func rateLimit(limit int) func(next http.Handler) http.Handler {\n\tlimiter := rate.NewLimiter(rate.Every(time.Second/time.Duration(limit)), limit*2)\n\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tif !limiter.Allow() {\n\t\t\t\terrRateLimitExceeded.Write(w)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func (s *Setup) RateLimit(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tip, _, err := net.SplitHostPort(r.RemoteAddr)\n\t\tif err != nil {\n\t\t\terrhandler.DecodeError(w, r, s.logger, errInternal, http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tlimiter := ratelimit.GetVisitor(ip)\n\t\tif !limiter.Allow() {\n\t\t\terrhandler.DecodeError(\n\t\t\t\tw,\n\t\t\t\tr,\n\t\t\t\ts.logger,\n\t\t\t\thttp.StatusText(http.StatusTooManyRequests),\n\t\t\t\thttp.StatusTooManyRequests,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (s *Swarm) limitedDial(ctx context.Context, p peer.ID, a ma.Multiaddr, resp chan dialResult) {\n\ttimeout := s.dialTimeout\n\tif lowTimeoutFilters.AddrBlocked(a) && s.dialTimeoutLocal < s.dialTimeout {\n\t\ttimeout = s.dialTimeoutLocal\n\t}\n\ts.limiter.AddDialJob(&dialJob{\n\t\taddr: a,\n\t\tpeer: p,\n\t\tresp: resp,\n\t\tctx: ctx,\n\t\ttimeout: timeout,\n\t})\n}", "func (a *Application) Limit() int64 {\n\tif a.InProduction {\n\t\treturn rateLimitProduction\n\t}\n\n\treturn rateLimitStaging\n}", "func (rl *redisRateLimiter) RateLimit(ctx gocontext.Context, name string, maxCalls uint64, per time.Duration) (bool, error) {\n\tif trace.FromContext(ctx) != nil {\n\t\tvar span *trace.Span\n\t\tctx, span = trace.StartSpan(ctx, \"Redis.RateLimit\")\n\t\tdefer span.End()\n\t}\n\n\tpoolCheckoutStart := time.Now()\n\n\tconn := rl.pool.Get()\n\tdefer conn.Close()\n\n\tcontext.TimeSince(ctx, \"rate_limit_redis_pool_wait\", poolCheckoutStart)\n\n\tif trace.FromContext(ctx) != nil {\n\t\tvar span *trace.Span\n\t\tctx, span = trace.StartSpan(ctx, \"Redis.RateLimit.WithPool\")\n\t\tdefer span.End()\n\t}\n\n\tif rl.dynamicConfig {\n\t\terr := rl.loadDynamicConfig(ctx, conn, name, &maxCalls, &per)\n\t\tif err != nil && err != redis.ErrNil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\tnow := time.Now()\n\ttimestamp := now.Unix() - (now.Unix() % int64(per.Seconds()))\n\n\tkey := fmt.Sprintf(\"%s:%s:%d\", rl.prefix, name, timestamp)\n\n\tcur, err := redis.Int64(conn.Do(\"GET\", key))\n\tif err != nil && err != redis.ErrNil {\n\t\treturn false, err\n\t}\n\n\tif err != redis.ErrNil && uint64(cur) >= maxCalls {\n\t\treturn false, nil\n\t}\n\n\t_, err = conn.Do(\"WATCH\", key)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tconnSend := func(commandName string, args ...interface{}) {\n\t\tif err != nil && err != redis.ErrNil {\n\t\t\treturn\n\t\t}\n\t\terr = conn.Send(commandName, args...)\n\t}\n\tconnSend(\"MULTI\")\n\tconnSend(\"INCR\", key)\n\tconnSend(\"EXPIRE\", key, int64(per.Seconds()))\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treply, err := conn.Do(\"EXEC\")\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif reply == nil {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}", "func (r *Semaphore) Process(maxConcurrent int, urls []string) {\n\tboundChan := make(chan struct{}, maxConcurrent)\n\tresultChan := make(chan response)\n\n\tgo func() {\n\t\tdefer close(boundChan)\n\t\tdefer close(resultChan)\n\t\twg := sync.WaitGroup{}\n\t\tfor _, u := range urls {\n\t\t\tboundChan <- struct{}{}\n\t\t\twg.Add(1)\n\t\t\tgo func(url string) {\n\t\t\t\tr.requester.MakeRequest(url, resultChan)\n\t\t\t\t<-boundChan\n\t\t\t\twg.Done()\n\t\t\t}(u)\n\t\t}\n\t\twg.Wait()\n\t}()\n\n\tfor res := range resultChan {\n\t\tr.printer.Println(fmt.Sprintf(\"%v %v\", res.url, r.hasher.GetMD5(res.body)))\n\t}\n}", "func (t *ThrottledReadCloser) SetLimit(r rate.Limit, b int) error {\n\treturn t.pool.SetLimitByID(r, b, t.id)\n}", "func (l *RateLimiter) Limit() rate.Limit {\n\treturn l.limiter.Limit()\n}", "func getConnectionLimit(connectionLimit int) int {\n\tif connectionLimit >= LB_LARGE_150000_CONNECTIONS {\n\t\treturn LB_LARGE_150000_CONNECTIONS\n\t} else if connectionLimit >= LB_SMALL_15000_CONNECTIONS &&\n\t\tconnectionLimit < LB_LARGE_150000_CONNECTIONS {\n\t\treturn LB_SMALL_15000_CONNECTIONS\n\t} else {\n\t\treturn connectionLimit\n\t}\n}", "func increaseLimit() {\n\tvar rlimit syscall.Rlimit\n\tif err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit); err != nil {\n\t\tpanic(err)\n\t}\n\trlimit.Cur = rlimit.Max\n\tif err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rlimit); err != nil {\n\t\tpanic(err)\n\t}\n\tlog.Printf(\"rlimit.Max = %d\\n\", rlimit.Max)\n\tlog.Printf(\"rlimit.Cur = %d\\n\", rlimit.Cur)\n}", "func increaseLimit() {\n\tvar rlimit syscall.Rlimit\n\tif err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit); err != nil {\n\t\tpanic(err)\n\t}\n\trlimit.Cur = rlimit.Max\n\tif err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rlimit); err != nil {\n\t\tpanic(err)\n\t}\n\tlog.Printf(\"rlimit.Max = %d\\n\", rlimit.Max)\n\tlog.Printf(\"rlimit.Cur = %d\\n\", rlimit.Cur)\n}", "func (o CircuitBreakersResponseOutput) MaxRequestsPerConnection() pulumi.IntOutput {\n\treturn o.ApplyT(func(v CircuitBreakersResponse) int { return v.MaxRequestsPerConnection }).(pulumi.IntOutput)\n}", "func WithLimit(l int) Opts {\n\treturn func(r *retryable) {\n\t\tif l > 0 {\n\t\t\tr.limit = l\n\t\t}\n\t}\n}", "func newLimiter() *limiter.Limiter {\n\n\tlmt := tollbooth.NewLimiter(2, &limiter.ExpirableOptions{DefaultExpirationTTL: time.Hour})\n\n\tlmt.SetIPLookups([]string{\"X-Forwarded-For\", \"RemoteAddr\", \"X-Real-IP\"})\n\tlmt.SetOnLimitReached(func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Println(\"request limit reached\")\n\t})\n\n\treturn lmt\n\n}", "func expectRequestsGranted(t *testing.T, rateLimiter RateLimiter, numRequests int, minDelay time.Duration, maxDelay time.Duration) {\n\tfor i := 0; i < numRequests; i++ {\n\t\trequestedAt := time.Now()\n\t\tctx, cancel := context.WithTimeout(context.Background(), maxDelay)\n\t\tdefer cancel()\n\t\terr := rateLimiter.Wait(ctx)\n\t\trequire.NoError(t, err, \"unexpected error for request %d: possible context timeout meaning the request took too long (max delay was %s, actual delay was >%s)\", i, maxDelay, time.Since(requestedAt))\n\t\tactualDelay := time.Since(requestedAt)\n\t\tassert.True(t, actualDelay <= maxDelay, \"waited too long to grant request %d (max delay was %s, actual delay was %s)\", i, maxDelay, actualDelay)\n\t\tassert.True(t, actualDelay >= minDelay, \"request %d was granted too quickly (min delay was %s, actual delay was %s)\", i, minDelay, actualDelay)\n\t}\n}", "func Test_Limiter_Fixed_Window_Skip_Successful_Requests(t *testing.T) {\n\tt.Parallel()\n\t// Test concurrency using a default store\n\n\tapp := fiber.New()\n\n\tapp.Use(New(Config{\n\t\tMax: 1,\n\t\tExpiration: 2 * time.Second,\n\t\tSkipSuccessfulRequests: true,\n\t\tLimiterMiddleware: FixedWindow{},\n\t}))\n\n\tapp.Get(\"/:status\", func(c *fiber.Ctx) error {\n\t\tif c.Params(\"status\") == \"fail\" {\n\t\t\treturn c.SendStatus(400)\n\t\t}\n\t\treturn c.SendStatus(200)\n\t})\n\n\tresp, err := app.Test(httptest.NewRequest(fiber.MethodGet, \"/success\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 200, resp.StatusCode)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 400, resp.StatusCode)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 429, resp.StatusCode)\n\n\ttime.Sleep(3 * time.Second)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 400, resp.StatusCode)\n}", "func (o CircuitBreakersOutput) MaxPendingRequests() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v CircuitBreakers) *int { return v.MaxPendingRequests }).(pulumi.IntPtrOutput)\n}", "func (lm *SimpleManager) limit(l Limiter) {\n\tlm.m[l] = make(chan int)\n\tdone := l.Limit(lm.m[l])\n\tgo func() {\n\t\t//If `true` passed on channel, limiter is closed\n\t\tif <-done {\n\t\t\tlm.Unmanage(l)\n\t\t}\n\t}()\n}", "func (e *Lint) MaxConcurrency() int {\n\tvar limit syscall.Rlimit\n\terr := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\toldLimit := limit.Cur\n\tlimit.Cur = limit.Max\n\terr = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limit)\n\tif err != nil {\n\t\tlog.Debug(err)\n\t\treturn convertLimit(oldLimit)\n\t}\n\n\treturn convertLimit(limit.Cur)\n}", "func (o CircuitBreakersResponseOutput) MaxPendingRequests() pulumi.IntOutput {\n\treturn o.ApplyT(func(v CircuitBreakersResponse) int { return v.MaxPendingRequests }).(pulumi.IntOutput)\n}", "func (rl *RateLimit) startRequests() {\n\tfor {\n\t\t// start a user request every 1 second\n\t\tgo func() {\n\t\t\tsize := rl.requestSize()\n\t\t\terr := make(chan error)\n\t\t\tgo rl.VerifyQuota(size, err)\n\t\t\tif e := <-err; e != nil {\n\t\t\t\t// respond to the user about quota exhaustion\n\t\t\t\tlog.Println(e)\n\t\t\t} else {\n\t\t\t\tlog.Println(\"request OK to be sent downstream\")\n\t\t\t}\n\t\t}()\n\t\ttime.Sleep(500 * time.Millisecond)\n\t}\n}", "func ConcurrentWriteLimit(n int) LoggerOption { return concurrentWriteLimit(n) }", "func Test_Limiter_Sliding_Window_No_Skip_Choices(t *testing.T) {\n\tt.Parallel()\n\tapp := fiber.New()\n\n\tapp.Use(New(Config{\n\t\tMax: 2,\n\t\tExpiration: 2 * time.Second,\n\t\tSkipFailedRequests: false,\n\t\tSkipSuccessfulRequests: false,\n\t\tLimiterMiddleware: SlidingWindow{},\n\t}))\n\n\tapp.Get(\"/:status\", func(c *fiber.Ctx) error {\n\t\tif c.Params(\"status\") == \"fail\" {\n\t\t\treturn c.SendStatus(400)\n\t\t}\n\t\treturn c.SendStatus(200)\n\t})\n\n\tresp, err := app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 400, resp.StatusCode)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/success\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 200, resp.StatusCode)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/success\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 429, resp.StatusCode)\n\n\ttime.Sleep(4 * time.Second)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/success\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 200, resp.StatusCode)\n}", "func (c *ConcurrentRetrier) Throttle() {\n\tc.throttleInternal()\n}", "func TooManyRequests() echo.Checker {\n\tcodeStr := strconv.Itoa(http.StatusTooManyRequests)\n\treturn func(result echo.CallResult, _ error) error {\n\t\tfor _, r := range result.Responses {\n\t\t\tif codeStr == r.Code {\n\t\t\t\t// Successfully received too many requests.\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn errors.New(\"no request received StatusTooManyRequest error\")\n\t}\n}", "func retryWhenRateLimited(cb func() error) error {\n\tretries := 0\n\tfor {\n\t\tif retries > 5 {\n\t\t\treturn errors.New(\"To many retries, stopping\")\n\t\t}\n\t\tretries++\n\n\t\terr := cb()\n\t\tif err != nil {\n\t\t\trerr, ok := err.(*github.RateLimitError)\n\t\t\tif ok {\n\t\t\t\tvar d = time.Until(rerr.Rate.Reset.Time)\n\t\t\t\tlog.Warnf(\"Hit rate limit, sleeping for %.0f min\", d.Minutes())\n\t\t\t\ttime.Sleep(d)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\taerr, ok := err.(*github.AbuseRateLimitError)\n\t\t\tif ok {\n\t\t\t\tvar d = aerr.GetRetryAfter()\n\t\t\t\tlog.Warnf(\"Hit abuse mechanism, sleeping for %.f min\", d.Minutes())\n\t\t\t\ttime.Sleep(d)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn errors.Wrap(err, \"Error calling github web-api\")\n\t\t}\n\t\treturn nil\n\t}\n}", "func (r *Ratelimit) Limited(key string, max int64) (bool, error) {\n\t// TODO make it possible to use a prate limit per minute, hour or day\n\t// minute is 04\n\thour := time.Now().Format(\"15\")\n\tk := key + \":\" + hour\n\n\ts, err := r.redis.GetInt64(k)\n\tif err != nil {\n\t\t// fail closed so if redis is down we don't run without rate limit enforcement\n\t\treturn true, err\n\t}\n\n\tif s == -1 {\n\t\tr.log.Printf(\"%s is not set\", k)\n\t} else {\n\t\tr.log.Printf(\"%s is %d\", k, s)\n\t\tif s > max {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\ti, err := r.redis.Incr(k)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tok, err := r.redis.Expire(k, time.Minute)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif !ok {\n\t\tr.log.Printf(\"failed to set expiration on %s\", k)\n\t}\n\n\treturn i <= max, nil\n}", "func (l *RateLimiter) AllowN(n int) bool {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\tnow := time.Now()\n\treturn l.limiter.AllowN(now, n)\n}", "func (r *Reader) SimpleLimit(n int, t time.Duration) <-chan bool {\n\tdone := make(chan bool, 1)\n\tready := make(chan struct{})\n\tr.newLimit <- &limit{\n\t\trate: rate{n, t},\n\t\tdone: done,\n\t\tready: ready,\n\t}\n\t<-ready\n\treturn done\n}", "func (r *ListMessagesRequest) Limit(limit int) *ListMessagesRequest {\n\tr.request.Add(\"limit\", strconv.Itoa(limit))\n\treturn r\n}", "func TestV3Curl_MaxStreams_BelowLimit_NoTLS_Small(t *testing.T) {\n\ttestV3CurlMaxStream(t, false, withCfg(*e2e.NewConfigNoTLS()), withMaxConcurrentStreams(3))\n}", "func LimitRate(timeFun func(time.Time) time.Time, limit int) pipes.Middleware {\n\tvar rateWindow string\n\tentry := &rateEntry{\n\t\tIPs: map[string]int{},\n\t}\n\n\treturn func(ctx context.Context, w http.ResponseWriter, r *http.Request, next pipes.Next) {\n\t\tip := r.RemoteAddr\n\t\tcurrentWindow := timeFun(getNow()).String()\n\n\t\tif currentWindow != rateWindow {\n\t\t\trateWindow = currentWindow\n\t\t\tentry = &rateEntry{\n\t\t\t\tIPs: map[string]int{\n\t\t\t\t\tip: 1,\n\t\t\t\t},\n\t\t\t}\n\t\t} else if entry.IPs[ip] > limit {\n\t\t\tw.WriteHeader(http.StatusTooManyRequests)\n\t\t\treturn\n\t\t} else {\n\t\t\tentry.IPs[ip]++\n\t\t}\n\t\tnext(ctx)\n\t}\n}" ]
[ "0.68766797", "0.6779762", "0.67135614", "0.6662659", "0.652928", "0.6507631", "0.64878035", "0.6459614", "0.64153814", "0.63881266", "0.6387182", "0.6327414", "0.6253636", "0.6235691", "0.6194677", "0.6182699", "0.61767733", "0.61741817", "0.61554265", "0.6143212", "0.61048883", "0.60415685", "0.60116875", "0.5988425", "0.5980267", "0.5979251", "0.5971323", "0.59681636", "0.59674895", "0.5940455", "0.5929514", "0.59251475", "0.5916765", "0.58761686", "0.5875223", "0.5863433", "0.586222", "0.58538395", "0.5843371", "0.58418334", "0.58382744", "0.5830765", "0.5819065", "0.5816595", "0.57889444", "0.5785374", "0.57748264", "0.5764552", "0.57607085", "0.57601774", "0.5754352", "0.57418543", "0.5741219", "0.5720669", "0.5720585", "0.57137096", "0.57131", "0.57109666", "0.5705388", "0.56982", "0.56969506", "0.56923234", "0.56851053", "0.56848055", "0.56810725", "0.56666327", "0.5660412", "0.5652458", "0.5651683", "0.56478375", "0.5637597", "0.563488", "0.5633862", "0.56294733", "0.56264055", "0.56176424", "0.5616678", "0.5605", "0.5605", "0.5600197", "0.5589999", "0.55887", "0.5563957", "0.55639315", "0.55574083", "0.5557269", "0.5551319", "0.5537845", "0.5536188", "0.55313796", "0.5525876", "0.552187", "0.5520542", "0.55181056", "0.55101204", "0.5508598", "0.55055165", "0.55050737", "0.55034274", "0.55004275" ]
0.64634264
7
Free increases the number of concurrent requests by 1 This function must be called after a Limit call or it will block.
func (rater *RateLimiter) Free() { rater.semaphore <- true }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *Pool) Free() int {\n\treturn p.Cap() - p.Running()\n}", "func Free() int {\n\treturn defaultRoutinePool.Free()\n}", "func TestFreelist_free(t *testing.T) {\n\tf := newFreelist()\n\tf.free(100, &page{id: 12})\n\tif !reflect.DeepEqual([]pgid{12}, f.pending[100]) {\n\t\tt.Fatalf(\"exp=%v; got=%v\", []pgid{12}, f.pending[100])\n\t}\n}", "func (nc NvmeController) Free() (tb uint64) {\n\tfor _, d := range nc.SmdDevices {\n\t\ttb += d.AvailBytes\n\t}\n\treturn\n}", "func (l *Limiter) Release(n int) {\n\tif l == nil {\n\t\treturn\n\t}\n\tif n == 0 {\n\t\treturn\n\t}\n\tfor {\n\t\tselect {\n\t\tcase l.c <- n:\n\t\t\treturn\n\t\tcase have := <-l.c:\n\t\t\tn += have\n\t\t}\n\t}\n}", "func (i *IPAM) Free(a net.IP) {\n\tdefer i.save()\n\tdelete(i.allocated, ip2int(a))\n}", "func (pkt *Packet) Free() {\n\tpkt.mtx.Lock()\n\tif *pkt.refCount <= 0 {\n\t\tpanic(\"reference count underflow\")\n\t}\n\t*pkt.refCount--\n\tif *pkt.refCount == 0 {\n\t\tpkt.reset()\n\t\tpkt.mtx.Unlock()\n\t\tpacketPool.Put(pkt)\n\t} else {\n\t\tpkt.mtx.Unlock()\n\t}\n}", "func Free() {\n\tflags = nil // Any future call to Get() will panic on a nil dereference.\n}", "func (p *request) Release() {\n\tp.ctx = nil\n\tp.Entry = nil\n\tp.read = false\n\trequestPool.Put(p)\n}", "func (m *Message) Free() {\n\tvar ch chan *Message\n\tif v := atomic.AddInt32(&m.refcnt, -1); v > 0 {\n\t\treturn\n\t}\n\tfor i := range messageCache {\n\t\tif m.bsize == messageCache[i].maxbody {\n\t\t\tch = messageCache[i].cache\n\t\t\tbreak\n\t\t}\n\t}\n\tm.Port = nil\n\tselect {\n\tcase ch <- m:\n\tdefault:\n\t}\n}", "func TestFreelist_free_overflow(t *testing.T) {\n\tf := newFreelist()\n\tf.free(100, &page{id: 12, overflow: 3})\n\tif exp := []pgid{12, 13, 14, 15}; !reflect.DeepEqual(exp, f.pending[100]) {\n\t\tt.Fatalf(\"exp=%v; got=%v\", exp, f.pending[100])\n\t}\n}", "func (loader *segmentLoader) freeRequest(resource LoadResource) {\n\tloader.mut.Lock()\n\tdefer loader.mut.Unlock()\n\n\tloader.committedResource.Sub(resource)\n}", "func (p *Pool) Free() {\n\tif p.done {\n\t\tpanic(\"Free() called in go-routine on completed pool\")\n\t}\n\n\t<-p.threads\n}", "func (o *StorageBaseCapacity) SetFree(v int64) {\n\to.Free = &v\n}", "func (pool *SyncPool) Free(mem []byte) {\r\n\tif size := cap(mem); size <= pool.maxSize {\r\n\t\tfor i := 0; i < len(pool.classesSize); i++ {\r\n\t\t\tif pool.classesSize[i] >= size {\r\n\t\t\t\tpool.classes[i].Put(&mem)\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "func (c *lru) Free() {\n\tfor k, _ := range c.cache {\n\t\tdelete(c.cache, k)\n\t}\n\tc.list.Init()\n\tc.size = 0\n}", "func (m *MIDs) Free(i uint16) {\n\tm.Lock()\n\tm.index[i] = nil\n\tm.Unlock()\n}", "func (ncs NvmeControllers) Free() (tb uint64) {\n\tfor _, c := range ncs {\n\t\ttb += (*NvmeController)(c).Free()\n\t}\n\treturn\n}", "func (b *Buffer) Free() int {\n\treturn b.size - b.used\n}", "func (l *RateLimiter) Available(n int) bool {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\tnow := time.Now()\n\tr := l.limiter.ReserveN(now, n)\n\tdelay := r.DelayFrom(now)\n\tr.CancelAt(now)\n\treturn delay == 0\n}", "func (c *Collection) Free() (*types.Object, error) {\n\treturn c.Pause()\n}", "func (rater *RateLimiter) Limit() {\n\t<-rater.semaphore\n}", "func (r *RequestPool) Release(req *Request) {\n\treq.Reset()\n\tr.pool.Put(req)\n}", "func (br *BufReader) Free() {\n\t// decrease the underlying netconn object holding\n\tbr.Reset(nil)\n\tif br.pool != nil {\n\t\tbr.pool.put(br)\n\t}\n}", "func (pool *Pool) Free(mem []byte) {\n\tcapacity := cap(mem)\n\tfor i := 0; i < len(pool.classes); i++ {\n\t\tif pool.classes[i].size >= capacity {\n\t\t\tpool.classes[i].Push(mem)\n\t\t}\n\t}\n}", "func (i *DeviceAccounterInstance) FreeCount() int {\n\tcount := 0\n\tfor _, c := range i.Instances {\n\t\tif c == 0 {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}", "func ReleaseRequest(req *Request) {\n\treq.Reset()\n\trequestPool.Put(req)\n}", "func (server *Server) free_chan(){\n\tserver.threads --\n\tserver.ThreadSync <- true\n}", "func (stack *StackAllocator) Free(size int32) {\n\tstack.alloc -= size\n\tif stack.alloc < 0 {\n\t\tstack.alloc = 0\n\t}\n\treturn\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 (s *Storage) Free(pooled []byte) {\n\n}", "func (p *ResourcePool) Free(a Alloc) error {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\treturn p.doFree(a)\n}", "func (in *InBuffer) free() {\n\tif enableBufferPool {\n\t\tif in.isFreed {\n\t\t\tpanic(\"link.InBuffer: double free\")\n\t\t}\n\t\tin.pool.PutInBuffer(in)\n\t}\n}", "func Free(f freer) {\n\tf.Free()\n}", "func (l *Limiter) Acquire(ctx context.Context, need int) error {\n\tif l == nil {\n\t\treturn ctx.Err()\n\t}\n\tselect {\n\tcase <-l.waiter:\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n\tdefer func() {\n\t\tl.waiter <- struct{}{}\n\t}()\n\n\tvar have int\n\tfor {\n\t\tselect {\n\t\tcase n := <-l.c:\n\t\t\thave += n\n\t\t\tif m := have - need; m >= 0 {\n\t\t\t\tl.Release(m)\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\tl.Release(have)\n\t\t\treturn ctx.Err()\n\t\t}\n\t}\n}", "func newFreeClientPool(db ethdb.Database, connectedLimit, totalLimit int, clock mclock.Clock) *freeClientPool {\n\tpool := &freeClientPool{\n\t\tdb: db,\n\t\tclock: clock,\n\t\taddressMap: make(map[string]*freeClientPoolEntry),\n\t\tconnPool: prque.New(poolSetIndex),\n\t\tdisconnPool: prque.New(poolSetIndex),\n\t\tconnectedLimit: connectedLimit,\n\t\ttotalLimit: totalLimit,\n\t}\n\tpool.loadFromDb()\n\treturn pool\n}", "func (db *DB) freePages() {\n\t// Free all pending pages prior to earliest open transaction.\n\tsort.Sort(txsById(db.txs))\n\tminid := txid(0xFFFFFFFFFFFFFFFF)\n\tif len(db.txs) > 0 {\n\t\tminid = db.txs[0].meta.txid\n\t}\n\tif minid > 0 {\n\t\tdb.freelist.release(minid - 1)\n\t}\n\t// Release unused txid extents.\n\tfor _, t := range db.txs {\n\t\tdb.freelist.releaseRange(minid, t.meta.txid-1)\n\t\tminid = t.meta.txid + 1\n\t}\n\tdb.freelist.releaseRange(minid, txid(0xFFFFFFFFFFFFFFFF))\n\t// Any page both allocated and freed in an extent is safe to release.\n}", "func (g *Server) PeriodicFree(d time.Duration) {\n\ttick := time.Tick(d)\n\tfor _ = range tick {\n\t\tdebug.FreeOSMemory()\n\t}\n}", "func (qp *quotaPool) reset(v int) {\n\tqp.lock.Lock()\n\tdefer qp.lock.Unlock()\n\tselect {\n\tcase n := <-qp.acquireChannel:\n\t\tqp.quota += n\n\tdefault:\n\t}\n\tqp.quota += v\n\tif qp.quota <= 0 {\n\t\treturn\n\t}\n\tselect {\n\tcase qp.acquireChannel <- qp.quota:\n\t\tqp.quota = 0\n\tdefault:\n\t}\n}", "func (i *Inode) Free(t *jrnl.TxnHandle) error {\n\tif i.Refcnt == 0 {\n\t\tlog.Fatal(\"double free\")\n\t}\n\n\ti.Refcnt--\n\tif err := i.EnqWrite(t); err != nil {\n\t\treturn err\n\t}\n\ti.Relse()\n\tfmt.Printf(\"Freed inode w/ serial num %d, refcnt %d\\n\", i.Serialnum, i.Refcnt)\n\treturn nil\n}", "func serveRequest(w http.ResponseWriter, r *http.Request) {\n\tconcurrentRequests++\n\tif concurrentRequests > maxConcurrentRequest {\n\t\tdieOvercapacity(fmt.Sprintf(\"More than %02d concurrentRequests: dying!\\n\", maxConcurrentRequest))\n\t}\n\n\tsemaphore <- true\n\ttotalRequestsProcessed++\n\treqSerialNumber := totalRequestsProcessed\n\tinProgress[reqSerialNumber] = true\n\t<-semaphore\n\tnapTime, napFunc := randomSleep(999)\n\tfmt.Fprintf(w, \"INFO:\\n====\\n\")\n\tfmt.Fprintf(w, \"Request #%04d for '%+v'. Currently %02d requests\\n\", reqSerialNumber,\n\t\tr.URL, concurrentRequests)\n\tfmt.Fprintf(w, \"#%04d: Milliseconds until completion:\\t%04d.\\n\", reqSerialNumber, napTime/time.Millisecond)\n\tlog.Printf(\"INFO:\\n====\\n\")\n\tlog.Printf(\"Request #%04d for '%+v'. Currently %02d requests\\n\", reqSerialNumber,\n\t\tr.URL, concurrentRequests)\n\tlog.Printf(\"#%04d: Milliseconds until completion:\\t%04d.\\n\", reqSerialNumber, napTime/time.Millisecond)\n\tnapFunc()\n\tsemaphore <- true\n\tconcurrentRequests--\n\tdelete (inProgress, reqSerialNumber)\n\t<-semaphore\n\tfmt.Fprintf(w, \"Request #%04d: Done. Currently %02d requests\\n\\n\",\n\t\treqSerialNumber, concurrentRequests)\n\tlog.Printf(\"Request #%04d: Done. Currently %02d requests\\n\\n\",\n\t\treqSerialNumber, concurrentRequests)\n\treturn\n}", "func (r *RingBuffer) Free() int {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tif r.wPos == r.rPos {\n\t\tif r.isFull {\n\t\t\treturn 0\n\t\t}\n\t\treturn r.size\n\t}\n\n\tif r.wPos < r.rPos {\n\t\treturn r.rPos - r.wPos\n\t}\n\n\treturn r.size - r.wPos + r.rPos\n}", "func (p *PCIDs) free(id uint16) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif id != 0 {\n\t\tp.available[id] = struct{}{}\n\t}\n}", "func (l *Limiter) limit(w http.ResponseWriter, r *http.Request, h http.Handler) {\n\tavailable := l.bucket.TakeAvailable(1)\n\n\theaders := w.Header()\n\theaders.Set(\"X-RateLimit-Limit\", strconv.Itoa(l.capacity()))\n\theaders.Set(\"X-RateLimit-Remaining\", strconv.Itoa(l.remaining()))\n\n\t// If tokens are not available, reply with error, usually with 429\n\tif available == 0 {\n\t\tl.responder(w, r)\n\t\treturn\n\t}\n\n\t// Otherwise track time and forward the request\n\th.ServeHTTP(w, r)\n}", "func (c *Cache[K, T]) Free(n int) {\n\tc.mux.Lock()\n\tdefer c.mux.Unlock()\n\n\tif n <= 0 {\n\t\treturn\n\t}\n\tif n >= len(c.s) {\n\t\tif c.ef != nil {\n\t\t\tfor _, cell := range c.s {\n\t\t\t\tc.ef(cell.key, cell.val)\n\t\t\t}\n\t\t}\n\t\tc.m = map[K]int{}\n\t\tc.s = nil\n\t\treturn\n\t}\n\n\tif c.ef != nil {\n\t\tfor i := 0; i < n; i++ {\n\t\t\tc.ef(c.s[i].key, c.s[i].val)\n\t\t\tdelete(c.m, c.s[i].key)\n\t\t}\n\t} else {\n\t\tfor i := 0; i < n; i++ {\n\t\t\tdelete(c.m, c.s[i].key)\n\t\t}\n\t}\n\tc.s = c.s[n:]\n}", "func (qp *quotaPool) add(n int) {\n\tqp.lock.Lock()\n\tdefer qp.lock.Unlock()\n\tqp.quota += n\n\tif qp.quota <= 0 {\n\t\treturn\n\t}\n\tselect {\n\tcase qp.acquireChannel <- qp.quota:\n\t\tqp.quota = 0\n\tdefault:\n\t}\n}", "func (cm GoPlanner) Free() {\n\tC.PlannerFree(cm.planner)\n}", "func (r *ringBufferRateLimiter) reserve() {\n\tr.ring[r.cursor] = now()\n\tr.advance()\n}", "func (it *Dprdpr1intspareMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (r *PortAllocator) Free() int {\n\treturn r.alloc.Free()\n}", "func (acker *acker) Free() {\n\tfor k, _ := range acker.fmap {\n\t\tacker.fmap[k] = nil\n\t}\n\tacker.fmap = nil\n\tacker.mutex = nil\n}", "func (it *Dppdpp0intspareMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (it *Dprdpr0intspareMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (px *Paxos) freeMemory() {\n // Assertion: px is already locked by the callee\n\n // reproduction of Min() without requesting a lock\n // Question: Can I do this without duplciating code?\n min := px.done[px.me]\n for i := 0; i < len(px.done); i++ {\n if px.done[i] < min {\n min = px.done[i]\n }\n }\n min += 1\n\n for i, _ := range px.Instances {\n if i < min {\n delete(px.Instances, i)\n }\n }\n}", "func (wrapper driverWrapper) FreeNetwork(request *network.FreeNetworkRequest) error {\n\tlogutils.JSONMessage(\"FreeNetwork request\", request)\n\treturn nil\n}", "func (it *Dppdpp1intspareMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func incRequest() {\n\tnumRequests++\n}", "func (la *Allocator) Free(lc eal.LCore) {\n\tif la.allocated[lc.ID()] == \"\" {\n\t\tpanic(\"lcore double free\")\n\t}\n\tlogger.Info(\"lcore freed\",\n\t\tlc.ZapField(\"lc\"),\n\t\tzap.String(\"role\", la.allocated[lc.ID()]),\n\t\tla.provider.NumaSocketOf(lc).ZapField(\"socket\"),\n\t)\n\tla.allocated[lc.ID()] = \"\"\n}", "func (l *ConcurrencyLimit) Limit() func() {\n\tl.Use()\n\treturn func() {\n\t\tl.Free()\n\t}\n}", "func (api *PrivateLightServerAPI) FreeClientCapacity() hexutil.Uint64 {\n\treturn hexutil.Uint64(api.server.freeClientCap)\n}", "func (x *PDFMrange) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}", "func (px *Paxos) Min() int {\n px.mu.Lock()\n defer px.mu.Unlock()\n\n min := px.done[px.me]\n for i := 0; i < len(px.done); i++ {\n if px.done[i] < min {\n min = px.done[i]\n }\n }\n\n // Question: Why not freeMemory() here?\n\n return min + 1\n}", "func (x *FzTuningContext) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}", "func (out *OutBuffer) free() {\n\tif enableBufferPool {\n\t\tif out.isFreed {\n\t\t\tpanic(\"link.OutBuffer: double free\")\n\t\t}\n\t\tout.pool.PutOutBuffer(out)\n\t}\n}", "func (s *f64) Free(p *PoolAllocator) {\n\tmustSameCapacity(s.Cap(), p.Channels*p.Capacity)\n\tfor i := range s.buffer {\n\t\ts.buffer[i] = 0\n\t}\n\tp.f64.Put(s)\n}", "func GatherRemainingRequests() {\r\n\r\n}", "func (x *FzPool) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\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 (mp *Mempool) Free(objs interface{}) {\n\tptr, count := cptr.ParseCptrArray(objs)\n\tif count == 0 {\n\t\treturn\n\t}\n\tC.rte_mempool_put_bulk(mp.ptr(), (*unsafe.Pointer)(ptr), C.uint(count))\n}", "func (rx *Rx) Free() error {\n\treturn err(C.go_rd_free((*C.struct_rx_port)(rx)))\n}", "func (rp *Pool) NextRequests(maxCount int, maxSizeBytes uint64, check bool) (batch [][]byte, full bool) {\n\trp.lock.Lock()\n\tdefer rp.lock.Unlock()\n\n\tif check {\n\t\tif (len(rp.existMap) < maxCount) && (rp.sizeBytes < maxSizeBytes) {\n\t\t\treturn nil, false\n\t\t}\n\t}\n\n\tcount := minInt(rp.fifo.Len(), maxCount)\n\tvar totalSize uint64\n\tbatch = make([][]byte, 0, count)\n\telement := rp.fifo.Front()\n\tfor i := 0; i < count; i++ {\n\t\treq := element.Value.(*requestItem).request\n\t\treqLen := uint64(len(req))\n\t\tif totalSize+reqLen > maxSizeBytes {\n\t\t\trp.logger.Debugf(\"Returning batch of %d requests totalling %dB as it exceeds threshold of %dB\",\n\t\t\t\tlen(batch), totalSize, maxSizeBytes)\n\t\t\treturn batch, true\n\t\t}\n\t\tbatch = append(batch, req)\n\t\ttotalSize += reqLen\n\t\telement = element.Next()\n\t}\n\n\tfullS := totalSize >= maxSizeBytes\n\tfullC := len(batch) == maxCount\n\tfull = fullS || fullC\n\tif len(batch) > 0 {\n\t\trp.logger.Debugf(\"Returning batch of %d requests totalling %dB\",\n\t\t\tlen(batch), totalSize)\n\t}\n\treturn batch, full\n}", "func (p *ResourcePool) Available() reflow.Resources {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tvar reserved reflow.Resources\n\tfor _, alloc := range p.allocs {\n\t\tif !AllocExpired(alloc) {\n\t\t\treserved.Add(reserved, alloc.Resources())\n\t\t}\n\t}\n\tvar avail reflow.Resources\n\tavail.Sub(p.resources, reserved)\n\treturn avail\n}", "func (w *Worker) Free() bool { return w.free }", "func (a *Allocator) Free(off int64) error {\n\tif off < szFile+szPage {\n\t\treturn fmt.Errorf(\"invalid argument: %T.Free(%v)\", a, off)\n\t}\n\n\ta.allocs--\n\tp, err := a.openPage((off-szFile)&^pageMask + szFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif p.rank > maxSharedRank {\n\t\tif err := a.freePage(p); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn a.flush()\n\t}\n\n\tp.setUsed(p.used - 1)\n\tif err := a.insertSlot(int(p.rank), off); err != nil {\n\t\treturn err\n\t}\n\n\tif p.used == 0 {\n\t\tif err := a.freePage(p); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn a.flush()\n\t}\n\n\tif err := p.flush(); err != nil {\n\t\treturn err\n\t}\n\n\treturn a.flush()\n}", "func (s *inMemSpannerServer) Freeze() {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.freezed = make(chan struct{})\n}", "func (a *ResourceAllocator) Free(b []byte) {\n\tif a == nil {\n\t\tDefaultAllocator.Free(b)\n\t\treturn\n\t}\n\n\tsize := len(b)\n\n\t// Release the memory to the allocator first.\n\talloc := a.allocator()\n\talloc.Free(b)\n\n\t// Release the memory in our accounting.\n\tatomic.AddInt64(&a.bytesAllocated, int64(-size))\n}", "func (enc *jsonEncoder) Free() {\n\tjsonPool.Put(enc)\n}", "func (lm *SimpleManager) Unlimit() {\n\tlm.newLimit <- nil\n}", "func (conn *Connection) Free() {\n\n\tif conn.done() {\n\t\treturn\n\t}\n\tconn.setDone()\n\n\tconn.wGroup.Wait()\n\n\t// dont delete. conn = nil make pointer nil, but other pointers\n\t// arent nil. If conn.disconnected = true it is mean that all\n\t// resources are cleared, but pointer alive, so we only make pointer = nil\n\tif conn.lobby == nil {\n\t\treturn\n\t}\n\n\tconn.setDisconnected()\n\n\tconn.ws.Close()\n\tclose(conn.send)\n\tclose(conn.actionSem)\n\t// dont delete. conn = nil make pointer nil, but other pointers\n\t// arent nil and we make 'conn.disconnected = true' for them\n\n\tconn.lobby = nil\n\tconn.setRoom(nil)\n\n\t//fmt.Println(\"conn free memory\")\n}", "func freeBuffer(buf *bytes.Buffer) {\n\tbuf.Reset()\n\tbufferPool.Put(buf)\n}", "func (it *Mcmc1intmcMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (x *Size) Free() {\n\tif x != nil && x.allocs626288d != nil {\n\t\tx.allocs626288d.(*cgoAllocMap).Free()\n\t\tx.ref626288d = nil\n\t}\n}", "func (room *Room) Free() {\n\n\tif room.done() {\n\t\treturn\n\t}\n\troom.setDone()\n\n\troom.wGroup.Wait()\n\n\troom.Status = StatusFinished\n\tgo room.historyFree()\n\tgo room.messagesFree()\n\tgo room.Players.Free()\n\tgo room.Observers.Free()\n\tgo room.Field.Free()\n\n\tclose(room.chanFinish)\n\tclose(room.chanStatus)\n}", "func (it *Dprdpr1intfifoMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (it *Mcmc0intmcMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (rl *RateLimit) relinquish() {\n\tfor {\n\t\tif rl.quotaLeft > 2*rl.baseQuota {\n\t\t\tok, err := rl.lock.Acquire()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\terr = rl.lock.Release()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tif ok {\n\t\t\t\trl.quotaLock.Lock()\n\t\t\t\trl.usableQuotaLeft = rl.usableQuotaLeft + rl.quotaLeft - rl.baseQuota\n\t\t\t\trl.quotaLeft = rl.baseQuota\n\t\t\t\tlog.Println(\"had too much quota, relinquising \", rl.quotaLeft-rl.baseQuota)\n\t\t\t\terr := rl.set(rl.usableQuotaPath, []byte(strconv.FormatInt(rl.usableQuotaLeft, 10)))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"updating usable quota failed \", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(15 * time.Second)\n\t}\n}", "func (a *AQM) Limit() bm.HandlerFunc {\n\treturn func(c *bm.Context) {\n\t\tdone, err := a.limiter.Allow(c)\n\t\tif err != nil {\n\t\t\tstats.Incr(_family, c.Request.URL.Path[1:])\n\t\t\t// TODO: priority request.\n\t\t\t// c.JSON(nil, err)\n\t\t\t// c.Abort()\n\t\t\treturn\n\t\t}\n\t\tdefer func() {\n\t\t\tif c.Error != nil && !ecode.Deadline.Equal(c.Error) && c.Err() != context.DeadlineExceeded {\n\t\t\t\tdone(rate.Ignore)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdone(rate.Success)\n\t\t}()\n\t\tc.Next()\n\t}\n}", "func GetFree(ctx context.Context, client *selvpcclient.ServiceClient) ([]*Quota, *selvpcclient.ResponseResult, error) {\n\turl := strings.Join([]string{client.Endpoint, resourceURL, \"free\"}, \"/\")\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 quotas from the response body.\n\tvar result ResourcesQuotas\n\terr = responseResult.ExtractResult(&result)\n\tif err != nil {\n\t\treturn nil, responseResult, err\n\t}\n\n\treturn result.Quotas, responseResult, nil\n}", "func (it *Mcmc0mchintmcMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (x *FzIcclink) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}", "func (it *Mcmc5intmcMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func lockLimitConnections() {\n\tsemaphoreMaxConnections <- struct{}{}\n}", "func (it *Mcmc1mchintmcMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (it *Dppdpp0intfifoMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (prop *properties) NumFreeMintedTokens() int64 {\n\tif prop.isOrigin {\n\t\treturn 0\n\t}\n\treturn prop.numTotalMintedTokens - int64(prop.numRequests)\n}", "func (q *HTTP) Release() {\n\tq.HumanLabel = q.HumanLabel[:0]\n\tq.HumanDescription = q.HumanDescription[:0]\n\tq.id = 0\n\tq.Method = q.Method[:0]\n\tq.Path = q.Path[:0]\n\tq.Body = q.Body[:0]\n\tq.StartTimestamp = 0\n\tq.EndTimestamp = 0\n\n\tHTTPPool.Put(q)\n}", "func (m *MemLimiter) Limit(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"X-RateLimit-Limit\", strconv.Itoa(int(m.cfg.IpLimit)))\n\n\t\tip, _, _ := net.SplitHostPort(r.RemoteAddr)\n\t\turl := r.RequestURI\n\t\tipl := m.getLimiter(IpAddress, ip)\n\t\tpathl := m.getLimiter(URL, url)\n\n\t\tif ipl.Allow() == false || pathl.Allow() == false {\n\t\t\tw.Header().Set(\"X-RateLimit-Limit\", strconv.Itoa(int(m.cfg.IpLimit)))\n\t\t\thttp.Error(w, \"API rate limit exceeded\", http.StatusTooManyRequests)\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (it *Dppdpp1intfifoMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (it *Mcmc6intmcMetricsIterator) Free() {\n\tit.iter.Free()\n}", "func (it *Mcmc4intmcMetricsIterator) Free() {\n\tit.iter.Free()\n}" ]
[ "0.6866443", "0.6678183", "0.6493432", "0.630607", "0.62864053", "0.6243849", "0.61974216", "0.6071971", "0.6030552", "0.60024", "0.5996387", "0.5909297", "0.5899765", "0.5899695", "0.5894417", "0.58930266", "0.58856153", "0.58820987", "0.58708996", "0.5844449", "0.5824323", "0.58242184", "0.5820572", "0.58147246", "0.58144706", "0.5805284", "0.57976866", "0.5746901", "0.5707313", "0.57004994", "0.56862813", "0.5654045", "0.56489325", "0.5636128", "0.56353563", "0.5630985", "0.5626165", "0.56225646", "0.56204385", "0.56088686", "0.5600589", "0.55930406", "0.557075", "0.55646664", "0.5562033", "0.5554659", "0.55501676", "0.55277115", "0.54790115", "0.54698294", "0.546746", "0.54653406", "0.5465284", "0.54638016", "0.5462086", "0.5454381", "0.54458356", "0.54291874", "0.5410328", "0.54046625", "0.5402306", "0.539258", "0.53740805", "0.5366588", "0.53585356", "0.5358268", "0.5346037", "0.5343534", "0.5330069", "0.5324741", "0.5318169", "0.531516", "0.5312606", "0.53113014", "0.53066766", "0.52954084", "0.52920437", "0.5279574", "0.52686095", "0.526847", "0.52677166", "0.5267246", "0.526009", "0.5258603", "0.52578425", "0.52405673", "0.5238481", "0.52348936", "0.5222104", "0.52159786", "0.5206009", "0.52056164", "0.5203968", "0.52030414", "0.52026457", "0.52021325", "0.520053", "0.5195052", "0.5191662", "0.51889735" ]
0.73970497
0
Create initializes the builder
func (app *applicationBuilder) Create() ApplicationBuilder { return createApplicationBuilder() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (app *builder) Create() Builder {\n\treturn createBuilder(app.hashAdapter, app.immutableBuilder)\n}", "func (app *builder) Create() Builder {\n\treturn createBuilder(app.hashAdapter)\n}", "func (app *builder) Create() Builder {\n\treturn createBuilder(app.hashAdapter)\n}", "func (app *builder) Create() Builder {\n\treturn createBuilder(app.hashAdapter, app.minPubKeysInOwner)\n}", "func (fac *BuilderFactory) Create() met.Builder {\n\tout := createBuilder()\n\treturn out\n}", "func (app *builder) Create() Builder {\n\treturn createBuilder()\n}", "func (app *builder) Create() Builder {\n\treturn createBuilder()\n}", "func (app *builder) Create() Builder {\n\treturn createBuilder(app.immutableBuilder)\n}", "func (app *builder) Create() Builder {\n\treturn createBuilder(app.immutableBuilder)\n}", "func (app *builder) Create() Builder {\n\treturn createBuilder(\n\t\tapp.hashAdapter,\n\t\tapp.pkAdapter,\n\t)\n}", "func New() Builder {\n\treturn newBuilder()\n}", "func (app *builder) Create() Builder {\n\treturn createBuilder(app.eventsAdapter)\n}", "func (app *externalBuilder) Create() ExternalBuilder {\n\treturn createExternalBuilder()\n}", "func (c *BuildingClient) Create() *BuildingCreate {\n\tmutation := newBuildingMutation(c.config, OpCreate)\n\treturn &BuildingCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (app *operationBuilder) Create() OperationBuilder {\n\treturn createOperationBuilder()\n}", "func (app *contentBuilder) Create() ContentBuilder {\n\treturn createContentBuilder(app.hashAdapter)\n}", "func New(params *infrav1.BuildParams, opts ...BuilderOption) *Builder {\n\tbuilder := &Builder{\n\t\tparams: params,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(builder)\n\t}\n\n\treturn builder\n}", "func (app *contentBuilder) Create() ContentBuilder {\n\treturn createContentBuilder(app.hashAdapter, app.pubKeyAdapter)\n}", "func (build *hashTreeBuilder) Create() hashtrees.HashTreeBuilder {\n\tbuild.blocks = nil\n\treturn build\n}", "func (build *blockBuilder) Create() chained.BlockBuilder {\n\tbuild.id = nil\n\tbuild.met = nil\n\tbuild.blk = nil\n\tbuild.prevID = nil\n\tbuild.crOn = nil\n\treturn build\n}", "func (app *adapterBuilder) Create() AdapterBuilder {\n\treturn createAdapterBuilder()\n}", "func (app *accessBuilder) Create() AccessBuilder {\n\treturn createAccessBuilder()\n}", "func (app *elementsBuilder) Create() ElementsBuilder {\n\treturn createElementsBuilder(app.hashAdapter)\n}", "func (app *propertyBuilder) Create() PropertyBuilder {\n\treturn createPropertyBuilder()\n}", "func (build *signedBlockBuilder) Create() stored_blocks.SignedBlockBuilder {\n\tbuild.metaData = nil\n\tbuild.sig = nil\n\tbuild.blk = nil\n\treturn build\n}", "func (b *Builder) Create() (Harvester, error) {\n\tif b.err != nil {\n\t\treturn nil, b.err\n\t}\n\tsd := seed.New(b.seedParams...)\n\n\tvar mon Monitor\n\tif len(b.watchers) == 0 {\n\t\treturn &harvester{seeder: sd, cfg: b.cfg}, nil\n\t}\n\tmon, err := monitor.New(b.cfg, b.watchers...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &harvester{seeder: sd, monitor: mon, cfg: b.cfg}, nil\n}", "func (app *valueBuilder) Create() ValueBuilder {\n\treturn createValueBuilder()\n}", "func (app *fetchRegistryBuilder) Create() FetchRegistryBuilder {\n\treturn createFetchRegistryBuilder()\n}", "func (app *specificCardinalityBuilder) Create() SpecificCardinalityBuilder {\n\treturn createSpecificCardinalityBuilder()\n}", "func (build *signedBlockBuilder) Create() validated.SignedBlockBuilder {\n\tbuild.id = nil\n\tbuild.met = nil\n\tbuild.blk = nil\n\tbuild.sig = nil\n\tbuild.crOn = nil\n\treturn build\n}", "func (app *factory) Create() (Blocks, error) {\n\treturn app.builder.Create().Now()\n}", "func (fac *TransactionsBuilderFactory) Create() signed_transactions.TransactionsBuilder {\n\tout := createTransactionsBuilder(fac.htBuilderFactory, fac.metBuilderFactory)\n\treturn out\n}", "func New() *Builder {\n\treturn &Builder{\n\t\tID: getulid(),\n\t}\n}", "func (app *instructionAdapterBuilder) Create() InstructionAdapterBuilder {\n\treturn createInstructionAdapterBuilder(\n\t\tapp.testInstructionBuilder,\n\t\tapp.assertBuilder,\n\t\tapp.readFileBuilder,\n\t\tapp.relativePathBuilder,\n\t\tapp.labelInstructionBuilder,\n\t\tapp.instructionBuilder,\n\t\tapp.exitBuilder,\n\t\tapp.callBuilder,\n\t\tapp.moduleBuilder,\n\t\tapp.printBuilder,\n\t\tapp.operationBuilder,\n\t\tapp.arythmeticBuilder,\n\t\tapp.relationalBuilder,\n\t\tapp.logicalBuilder,\n\t\tapp.variableBuilder,\n\t\tapp.declarationBuilder,\n\t\tapp.typeBuilder,\n\t\tapp.valueRepresentationBuilder,\n\t\tapp.valueBuilder,\n\t\tapp.numericValueBuilder,\n\t\tapp.assignmentBuilder,\n\t\tapp.concatenationBuilder,\n\t\tapp.remainingOperationBuilder,\n\t\tapp.standardOperationBuilder,\n\t\tapp.jumpBuilder,\n\t\tapp.stackFrameBuilder,\n\t\tapp.indexBuilder,\n\t\tapp.skipBuilder,\n\t\tapp.intPointBuilder,\n\t)\n}", "func (app *fileBuilder) Create() FileBuilder {\n\treturn createFileBuilder()\n}", "func New() *Builder {\n\treturn &Builder{\n\t\tHeaders: make(map[string]string),\n\t\tQuerys: make(map[string]string),\n\t\tlogger: log.New(os.Stdout, \"\", log.LstdFlags),\n\t\ttimeout: time.Duration(20 * time.Second),\n\t}\n}", "func (app *scriptCommandBuilder) Create() ScriptCommandBuilder {\n\treturn createScriptCommandBuilder()\n}", "func (app *mainSectionBuilder) Create() MainSectionBuilder {\n\treturn createMainSectionBuilder()\n}", "func (c *BeerClient) Create() *BeerCreate {\n\tmutation := newBeerMutation(c.config, OpCreate)\n\treturn &BeerCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (app *folderNameBuilder) Create() FolderNameBuilder {\n\treturn createFolderNameBuilder()\n}", "func (app *languageTestSectionBuilder) Create() LanguageTestSectionBuilder {\n\treturn createLanguageTestSectionBuilder()\n}", "func (c *BedtypeClient) Create() *BedtypeCreate {\n\tmutation := newBedtypeMutation(c.config, OpCreate)\n\treturn &BedtypeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func NewBuilder() Builder {\n\treturn createBuilder()\n}", "func NewBuilder() Builder {\n\treturn createBuilder()\n}", "func NewBuilder() Builder {\n\treturn createBuilder()\n}", "func NewBuilder() Builder {\n\treturn createBuilder()\n}", "func NewBuilder() Builder {\n\treturn createBuilder()\n}", "func (f *factory) Builder() *resource.Builder {\n\treturn resource.NewBuilder(f.kubeConfigFlags)\n}", "func (app *exitBuilder) Create() ExitBuilder {\n\treturn createExitBuilder()\n}", "func New(ctx context.Context, opt Opt) (*Builder, error) {\n\treqHandler := newReqBodyHandler(tracing.DefaultTransport)\n\n\tc, err := newController(ctx, reqHandler, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb := &Builder{\n\t\tcontroller: c,\n\t\tdnsconfig: opt.DNSConfig,\n\t\treqBodyHandler: reqHandler,\n\t\tjobs: map[string]*buildJob{},\n\t\tuseSnapshotter: opt.UseSnapshotter,\n\t}\n\treturn b, nil\n}", "func (app *updateBuilder) Create() UpdateBuilder {\n\treturn createUpdateBuilder()\n}", "func (b *MockPrBuilder) Create() *PrMock {\n\tfor _, mock := range b.mockCreators {\n\t\tmock(b)\n\t}\n\tgomega.Expect(b.errors).To(gomega.BeEmpty())\n\n\treturn &PrMock{PullRequest: b.pullRequest}\n}", "func New(b builder.Builder, tracker, hosted string) *Builder {\n\t//create our new builder\n\tn := &Builder{\n\t\tb: b,\n\t\tbase: hosted,\n\t\trpc: gorpc.NewServer(),\n\t\ttcl: client.New(tracker, http.DefaultClient, client.JsonCodec),\n\t\tbq: rpc.NewBuilderQueue(),\n\t\tmux: http.NewServeMux(),\n\t\tdler: newDownloader(),\n\t}\n\n\t//register the build service in the rpc\n\tif err := n.rpc.RegisterService(n.bq, \"\"); err != nil {\n\t\tpanic(err)\n\t}\n\n\t//make sure we respond to pings\n\tif err := n.rpc.RegisterService(pinger.Pinger{}, \"\"); err != nil {\n\t\tpanic(err)\n\t}\n\n\t//register the codec\n\tn.rpc.RegisterCodec(json.NewCodec(), \"application/json\")\n\n\t//add the handlers to our mux\n\tn.mux.Handle(\"/\", n.rpc)\n\tn.mux.Handle(\"/download/\", http.StripPrefix(\"/download/\", n.dler))\n\n\t//start processing tasks\n\tgo n.run()\n\n\treturn n\n}", "func (r *RootCommandNode) CreateBuilder() NodeBuilder {\n\treturn nil\n}", "func (b *Builder) Initialise() {\n\tb.builders = make(map[string]AtomBuilder)\n\tb.builders[\"ftyp\"] = buildFTYP /**/\n\tb.builders[\"free\"] = buildFREE /**/\n\tb.builders[\"moov\"] = buildMOOV /**/\n\tb.builders[\"mvhd\"] = buildMVHD /**/\n\tb.builders[\"mvex\"] = buildMVEX /**/\n\tb.builders[\"trex\"] = buildTREX /**/\n\tb.builders[\"trak\"] = buildTRAK /**/\n\tb.builders[\"tkhd\"] = buildTKHD /**/\n\tb.builders[\"mdia\"] = buildMDIA /**/\n\tb.builders[\"mdhd\"] = buildMDHD /**/\n\tb.builders[\"hdlr\"] = buildHDLR /**/\n\tb.builders[\"minf\"] = buildMINF /**/\n\tb.builders[\"dinf\"] = buildDINF /**/\n\tb.builders[\"dref\"] = buildDREF /**/\n\tb.builders[\"stbl\"] = buildSTBL /**/\n\tb.builders[\"vmhd\"] = buildVMHD /**/\n\tb.builders[\"smhd\"] = buildSMHD /**/\n\tb.builders[\"stsd\"] = buildSTSD /**/\n\tb.builders[\"stts\"] = buildSTTS /**/\n\tb.builders[\"stsc\"] = buildSTSC /**/\n\tb.builders[\"stco\"] = buildSTCO /**/\n\tb.builders[\"stsz\"] = buildSTSZ /**/\n\tb.builders[\"stss\"] = buildSTSS /**/\n\tb.builders[\"styp\"] = buildSTYP /**/\n\tb.builders[\"sidx\"] = buildSIDX /**/\n\tb.builders[\"moof\"] = buildMOOF /**/\n\tb.builders[\"mfhd\"] = buildMFHD /**/\n\tb.builders[\"traf\"] = buildTRAF /**/\n\tb.builders[\"tfhd\"] = buildTFHD /**/\n\tb.builders[\"tfdt\"] = buildTFDT /**/\n\tb.builders[\"trun\"] = buildTRUN /**/\n\tb.builders[\"mdat\"] = buildMDAT /**/\n\tb.builders[\"mp4a\"] = buildMP4AENCA /**/\nb.builders[\"esds\"] = buildESDS /**/\n\tb.builders[\"avcC\"] = buildAVCC /**/\n\tb.builders[\"avc1\"] = buildAVC1ENCV /**/\n\tb.builders[\"sinf\"] = buildSINF /**/\n\tb.builders[\"frma\"] = buildFRMA /**/\n\tb.builders[\"schm\"] = buildSCHM /**/\n\tb.builders[\"schi\"] = buildSCHI /**/\n\tb.builders[\"tenc\"] = buildTENC /**/\n\tb.builders[\"enca\"] = buildMP4AENCA /**/\n\tb.builders[\"encv\"] = buildAVC1ENCV /**/\n\tb.builders[\"senc\"] = buildSENC\n\tb.builders[\"saiz\"] = buildSAIZ\n\tb.builders[\"saio\"] = buildSAIO\n}", "func (app *ruleSectionBuilder) Create() RuleSectionBuilder {\n\treturn createRuleSectionBuilder()\n}", "func Create(conf *config.Config, logger *logrus.Logger) (Runner, error) {\n\tvar srv Runner\n\n\tswitch conf.Server.Type {\n\tcase \"grpc\":\n\t\tsrv = grpc.NewRunner(conf,logger)\n\tdefault:\n\t\treturn nil, errors.New(\"InvalidServerTypeError(#{conf.Server.Type})\")\n\t}\n\treturn srv, nil\n}", "func (app *specificTokenCodeBuilder) Create() SpecificTokenCodeBuilder {\n\treturn createSpecificTokenCodeBuilder()\n}", "func NewBuilder(watcher Watcher, buildCommand, runCommand string) *Builder {\n\treturn &Builder{\n\t\twatcher: watcher,\n\t\tstartChannel: make(chan bool),\n\t\tstopChannel: make(chan bool),\n\t\tbuildCommand: buildCommand,\n\t\trunCommand: runCommand,\n\t}\n}", "func (c *CleaningroomClient) Create() *CleaningroomCreate {\n\tmutation := newCleaningroomMutation(c.config, OpCreate)\n\treturn &CleaningroomCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func New(p *config.Pipeline, opts ...OptFunc) *Builder {\n\tb := &Builder{pipeline: p}\n\tfor _, opt := range opts {\n\t\topt(b)\n\t}\n\n\treturn b\n}", "func (d *WorkFlowDefinition) Create() {\n\td.nodes = make(map[string]WorkFlowNodeInterface)\n\td.edges = make(map[string][]string)\n\td.joinFork = make(map[string]string)\n}", "func (d *WorkFlowDefinition) Create() {\n\td.nodes = make(map[string]WorkFlowNodeInterface)\n\td.edges = make(map[string][]string)\n\td.joinFork = make(map[string]string)\n}", "func (c *ToolClient) Create() *ToolCreate {\n\tmutation := newToolMutation(c.config, OpCreate)\n\treturn &ToolCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func NewBuilder() *Builder {\n\treturn &Builder{\n\t\tpath: \"\",\n\t\tchecks: make(map[*Predicate]string),\n\t}\n}", "func NewBuilder() Builder {\n\treturn &builder{}\n}", "func (c *PharmacistClient) Create() *PharmacistCreate {\n\tmutation := newPharmacistMutation(c.config, OpCreate)\n\treturn &PharmacistCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (b *stateServiceBuilder) Create() *stateService {\n\tif b.state == nil {\n\t\tpanic(\"state adapter is required\")\n\t}\n\n\tinstance := &stateService{\n\t\tstate: b.state,\n\t\tsettings: b.settings,\n\t}\n\n\tinstance.cb = b.cbSettings.ToCircuitBreaker(\"state service\", instance.onCircuitOpen)\n\n\tinstance.initialize()\n\n\treturn instance\n}", "func (c *BillClient) Create() *BillCreate {\n\tmutation := newBillMutation(c.config, OpCreate)\n\treturn &BillCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *BillClient) Create() *BillCreate {\n\tmutation := newBillMutation(c.config, OpCreate)\n\treturn &BillCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *BillClient) Create() *BillCreate {\n\tmutation := newBillMutation(c.config, OpCreate)\n\treturn &BillCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func NewBuilder(ra RunnableActions) *Builder {\n\treturn &Builder{\n\t\tblk: Block{\n\t\t\tHeader: Header{\n\t\t\t\tversion: version.ProtocolVersion,\n\t\t\t\theight: ra.blockHeight,\n\t\t\t\ttimestamp: ra.blockTimeStamp,\n\t\t\t\ttxRoot: ra.txHash,\n\t\t\t},\n\t\t\tActions: ra.actions,\n\t\t},\n\t}\n}", "func New(tableName string) *Builder {\n\tb := &Builder{\n\t\tstrToBucket: map[string]stringInfo{},\n\t\tbuckets: [][]byte{nil}, // initialize with first bucket.\n\t}\n\tb.rootMeta = &metaData{\n\t\tb: b,\n\t\ttypeInfo: &typeInfo{},\n\t}\n\treturn b\n}", "func Create(\n\tcontext contexts.Contextable,\n\tlogger *logger.Logger,\n\tconnection *golastic.Connection,\n\tqueue *notifications.Queue,\n\tctx context.Context,\n) (Actionable, error) {\n\taction, err := build(context.Action())\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := action.Init(context, logger, connection, queue, ctx); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := action.ApplyOptions().ApplyFilters(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn action, nil\n}", "func (c *QueueClient) Create() *QueueCreate {\n\tmutation := newQueueMutation(c.config, OpCreate)\n\treturn &QueueCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (factory) Create(cfg config.NodeHostConfig,\n\tcb config.LogDBCallback, dirs []string, wals []string) (raftio.ILogDB, error) {\n\treturn CreateTan(cfg, cb, dirs, wals)\n}", "func New() *Builder {\n\treturn &Builder{\n\t\tpatterns: make(map[string]*parser.Node),\n\t}\n}", "func (c *DNSBLQueryClient) Create() *DNSBLQueryCreate {\n\tmutation := newDNSBLQueryMutation(c.config, OpCreate)\n\treturn &DNSBLQueryCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func Builder(dataset string) *libhoney.Builder {\n\tb := libhoney.NewBuilder()\n\tb.Dataset = dataset\n\treturn b\n}", "func (c *RoomdetailClient) Create() *RoomdetailCreate {\n\tmutation := newRoomdetailMutation(c.config, OpCreate)\n\treturn &RoomdetailCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func New(r *registry.R) *FlowBuilder {\n\treturn &FlowBuilder{\n\t\tregistry: r,\n\t\tOperationMap: map[string]flow.Operation{},\n\t\tnodeTrack: map[string]bool{},\n\t}\n}", "func (c *RoomuseClient) Create() *RoomuseCreate {\n\tmutation := newRoomuseMutation(c.config, OpCreate)\n\treturn &RoomuseCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (cupBuilder *CupBuilder) Build() *Cup {\n return cupBuilder.cup\n}", "func (c *OperationroomClient) Create() *OperationroomCreate {\n\tmutation := newOperationroomMutation(c.config, OpCreate)\n\treturn &OperationroomCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func TestProbeInfo_Create(t *testing.T) {\n\tassert := assert.New(t)\n\tprobeinfo := new(ProbeInfo)\n\tbuilder := &ProbeInfoBuilder{\n\t\tprobeInfo: probeinfo,\n\t}\n\tpi := builder.Create()\n\tassert.Equal(probeinfo, pi)\n\tassert.Equal(*probeinfo, *pi)\n\n}", "func (batch *BatchTEL) Create() error {\n\t// generates sequence numbers and batch control\n\tif err := batch.build(); err != nil {\n\t\treturn err\n\t}\n\n\treturn batch.Validate()\n}", "func (b *Buddy) Build() Builder {\n\treturn Builder{b}\n}", "func NewBuilder() *Builder {\n\tid := uuid.New()\n\tb := &Builder{\n\t\tDir: flags.Dir,\n\t\trunning: map[*Runner]struct{}{},\n\t}\n\tif b.Dir == \"\" {\n\t\tb.Dir = filepath.Join(os.TempDir(), \"testbuild.\"+id.String())\n\t} else {\n\t\tb.Preserve = true\n\t\tif flags.Force {\n\t\t\tos.RemoveAll(b.Dir)\n\t\t}\n\t\tif _, err := os.Stat(b.Dir); err == nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%s already exists\\n\", b.Dir)\n\t\t\tos.Exit(1)\n\t\t}\n\t\t// Try to make this directory now to handle permission errors.\n\t\tif err := os.MkdirAll(b.Dir, 0700); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\treturn b\n}", "func (b *builderCreator) Create(dir, containerRegistry string) (string, error) {\n\tif dir == \"\" {\n\t\treturn \"\", kf.ConfigErr{\"dir must not be empty\"}\n\t}\n\tif containerRegistry == \"\" {\n\t\treturn \"\", kf.ConfigErr{\"containerRegistry must not be empty\"}\n\t}\n\n\tif filepath.Base(dir) != \"builder.toml\" {\n\t\tdir = filepath.Join(dir, \"builder.toml\")\n\t}\n\n\timageName := path.Join(containerRegistry, fmt.Sprintf(\"buildpack-builder:%d\", time.Now().UnixNano()))\n\tif err := b.f(pack.CreateBuilderFlags{\n\t\tPublish: true,\n\t\tBuilderTomlPath: dir,\n\t\tRepoName: imageName,\n\t}); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn imageName, nil\n}", "func (c *StatusdClient) Create() *StatusdCreate {\n\tmutation := newStatusdMutation(c.config, OpCreate)\n\treturn &StatusdCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (t *Target) Create(n usm.Number) usm.String {\n\treturn fmt.Sprintf(`make([]byte, %v)`, n)\n}", "func (c *UnitOfMedicineClient) Create() *UnitOfMedicineCreate {\n\tmutation := newUnitOfMedicineMutation(c.config, OpCreate)\n\treturn &UnitOfMedicineCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func New() CodeBuilder {\n\treturn &codeBuilder{}\n}", "func (d *DBGenerator) Create() (*KObjs, error) {\n\tctx := context.Background()\n\td.setParmsFromOptions()\n\n\tcollectors := []func(ctx context.Context) error{\n\t\td.readLicense,\n\t\td.connect,\n\t\td.setShardCount,\n\t\td.setCommunalEndpoint,\n\t\td.setLocalPaths,\n\t\td.setSubclusterDetail,\n\t\td.setCommunalPath,\n\t\td.setLicense,\n\t\td.setPasswordSecret,\n\t}\n\n\tfor _, collector := range collectors {\n\t\tif err := collector(ctx); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &d.Objs, nil\n}", "func (c *ClubapplicationClient) Create() *ClubapplicationCreate {\n\tmutation := newClubapplicationMutation(c.config, OpCreate)\n\treturn &ClubapplicationCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *FoodmenuClient) Create() *FoodmenuCreate {\n\tmutation := newFoodmenuMutation(c.config, OpCreate)\n\treturn &FoodmenuCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *EmptyClient) Create() *EmptyCreate {\n\tmutation := newEmptyMutation(c.config, OpCreate)\n\treturn &EmptyCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func NewBuilder() *Builder {\n\treturn &Builder{\n\t\tcon: &container{},\n\t}\n}", "func (b *Blueprint) Create() {\n\tb.addCommand(\"create\", nil)\n}", "func (h *Http) Create(wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\tapp := fiber.New()\n\n\t// Swagger\n\tapp.Get(\"/\", func (c *fiber.Ctx) error { return c.Redirect(\"/docs/index.html\") })\n\tapp.Get(\"/docs/*\", swagger.New(swagger.Config{DeepLinking: true, URL:\"/swagger.yaml\"}))\n\tapp.Static(\"/swagger.yaml\", \"./swagger.yaml\")\n\n\t// Routes\n\tapp.Get(\"/top/confirmed\", getTopConfirmed(&cont.TopConfirmed{}))\n\n\t// Run http server\n\tapp.Listen(fmt.Sprintf(\":%d\", h.Port))\n}" ]
[ "0.69202626", "0.6912449", "0.6912449", "0.6899315", "0.6793273", "0.67767155", "0.67767155", "0.6755811", "0.6755811", "0.67423236", "0.6639238", "0.6593561", "0.65597653", "0.64317507", "0.63935584", "0.6364446", "0.6348599", "0.63432586", "0.6327977", "0.6309385", "0.6305605", "0.62686497", "0.6234305", "0.6206128", "0.6182837", "0.61761814", "0.61050314", "0.60910803", "0.6090738", "0.60845655", "0.6062511", "0.60532874", "0.6051739", "0.604827", "0.5995996", "0.5978173", "0.5962127", "0.59478146", "0.59367967", "0.592953", "0.59024894", "0.5893997", "0.58905303", "0.58905303", "0.58905303", "0.58905303", "0.58905303", "0.58727205", "0.5858045", "0.58524483", "0.58476", "0.58375996", "0.5787204", "0.57760644", "0.57672584", "0.5731799", "0.57177794", "0.56959784", "0.5682114", "0.56470317", "0.56333053", "0.56326485", "0.56326485", "0.5631981", "0.56317055", "0.56047463", "0.5603636", "0.559189", "0.55888367", "0.55888367", "0.55888367", "0.55883056", "0.5588106", "0.5581199", "0.5575075", "0.55694944", "0.5554263", "0.55300415", "0.55200976", "0.5517834", "0.5516264", "0.55096596", "0.55080736", "0.550698", "0.55046344", "0.5496133", "0.54918414", "0.547106", "0.5463963", "0.5463377", "0.5461274", "0.545902", "0.54553056", "0.54515797", "0.54504097", "0.54502714", "0.5445536", "0.5437007", "0.5436961", "0.54311615" ]
0.59235173
40
WithHead adds an headSection to the builder
func (app *applicationBuilder) WithHead(head HeadSection) ApplicationBuilder { app.head = head return app }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (hb *dsHeadBook) AddHead(t thread.ID, p peer.ID, head cid.Cid) error {\n\treturn hb.AddHeads(t, p, []cid.Cid{head})\n}", "func (b *Builder) Head(url string) *Builder {\n\tb.Url = url\n\tb.Method = http.MethodHead\n\treturn b\n}", "func (app *adapter) ToHead(parsed parsers.HeadSection) (Head, error) {\n\tname := parsed.Name()\n\tversion := parsed.Version()\n\tbuilder := app.builder.Create().WithName(name).WithVersion(version)\n\tif parsed.HasImport() {\n\t\tparsedImports := parsed.Import()\n\t\tbuilder.WithImports(parsedImports)\n\t}\n\n\tif parsed.HasLoad() {\n\t\tparsedLoads := parsed.Load()\n\t\tloads := []LoadSingle{}\n\t\tfor _, oneParsedLoad := range parsedLoads {\n\t\t\tinternal := oneParsedLoad.Internal()\n\t\t\texternal := oneParsedLoad.External()\n\t\t\tload, err := app.loadSingleBuilder.Create().WithInternal(internal).WithExternal(external).Now()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tloads = append(loads, load)\n\t\t}\n\n\t\tbuilder.WithLoads(loads)\n\t}\n\n\treturn builder.Now()\n}", "func Head(props *HeadProps, children ...Element) *HeadElem {\n\trProps := &_HeadProps{\n\t\tBasicHTMLElement: newBasicHTMLElement(),\n\t}\n\n\tif props != nil {\n\t\tprops.assign(rProps)\n\t}\n\n\treturn &HeadElem{\n\t\tElement: createElement(\"head\", rProps, children...),\n\t}\n}", "func NewHead(charset string, metas ...*Element) *Head {\n\th := new(Head)\n\th.Element = NewElement(\"head\")\n\tif charset != \"\" {\n\t\th.Charset = charset\n\t}\n\th.AddMetas(metas...)\n\treturn h\n}", "func Head(attrs []htmlgo.Attribute, children ...HTML) HTML {\n\treturn &htmlgo.Tree{Tag: \"head\", Attributes: attrs, Children: children}\n}", "func newHead(vres *salesviews.HeadView) *Head {\n\tres := &Head{}\n\tif vres.ID != nil {\n\t\tres.ID = *vres.ID\n\t}\n\tif vres.Name != nil {\n\t\tres.Name = *vres.Name\n\t}\n\treturn res\n}", "func (w *FileLogWriter) SetHeadFoot(head, foot string) *FileLogWriter {\n\tw.header, w.trailer = head, foot\n\tif w.maxlines_curlines == 0 {\n\t\tfmt.Fprint(w.file, FormatLogRecord(w.header, &LogRecord{Created: time.Now()}))\n\t}\n\treturn w\n}", "func SetHead(name string) func(*types.Cmd) {\n\treturn func(g *types.Cmd) {\n\t\tg.AddOptions(\"set-head\")\n\t\tg.AddOptions(name)\n\t}\n}", "func NewHead(children ...Element) Element {\n\treturn newWithChildren(\"head\", children)\n}", "func WithHeader(header string) Option {\n\treturn func(o *options) {\n\t\to.header = header\n\t}\n}", "func (z *Zoidberg) Head(title, underline string) {\n\tfmt.Fprintf(z.w, \"%s\\n\", title)\n\tfmt.Fprintf(z.w, \"%s\\n\\n\", strings.Repeat(underline, len(title)))\n}", "func (cfg *Config) Header() *branch.Branch {\n\thead := branch.NewBranch(cHead)\n\n\tif len(cfg.title) > 0 {\n\t\ttitle, _ := head.AddBranch(-1, cTitle)\n\t\ttitle.Add(-1, cfg.title)\n\t}\n\n\tmeta, _ := head.AddBranch(-1, cMeta)\n\tmeta.Info = \"charset=\\\"utf-8\\\"\"\n\tmeta.Add(-1, \"\")\n\n\tmeta, _ = head.AddBranch(-1, cMeta)\n\tmeta.Info = \"name=\\\"generator\\\" content=\\\"md2html\\\"\"\n\tmeta.Add(-1, \"\")\n\n\tmeta, _ = head.AddBranch(-1, cMeta)\n\tmeta.Info = \"http-equiv=\\\"Content-Style-Type\\\" content=\\\"text/css\\\"\"\n\tmeta.Add(-1, \"\")\n\n\tif len(cfg.style) > 0 {\n\t\tstyle, _ := head.AddBranch(-1, cLink)\n\t\tstyle.Info = fmt.Sprintf(\"rel=\\\"stylesheet\\\" href=\\\"%s\\\" type=\\\"text/css\\\"\",\n\t\t\tcfg.style)\n\t\tstyle.Add(-1, \"\")\n\t}\n\n\treturn head\n}", "func (rb *RequestBuilder) WithHeader(k, v string) *RequestBuilder {\n\tif rb.hdr == nil {\n\t\trb.hdr = http.Header{}\n\t}\n\n\trb.hdr.Add(k, v)\n\treturn rb\n}", "func (c *Client) HeadWithContext(ctx context.Context, name string, opts *HeadOpts) FileIterator {\n\tvar hopts HeadOpts\n\tif opts != nil {\n\t\thopts = *opts\n\t}\n\tif hopts.BatchSize == 0 {\n\t\thopts.BatchSize = 1000\n\t}\n\treturn &headIterator{ctx: ctx, opts: hopts, name: name, iclient: c.iclient}\n}", "func (p *FakeProvider) SetHead(head block.TipSetKey) {\n\t_, e := p.GetTipSet(head)\n\trequire.NoError(p.t, e)\n\tp.head = head\n}", "func (b *Baa) Head(pattern string, h ...HandlerFunc) RouteNode {\n\treturn b.Router().Add(\"HEAD\", pattern, h)\n}", "func (mm *Middleman) Head(path string, middleware Middleware) error {\r\n\treturn mm.addMiddleware(path, http.MethodHead, middleware)\r\n}", "func (d *Display) AddSection(header string) *Section {\n\td.mutex.Lock()\n\tdefer d.mutex.Unlock()\n\n\ts := newSection(header, func(handler DisplayUpdateHandler) {\n\t\td.gui.Update(func(g *gocui.Gui) (err error) {\n\t\t\tv, err := g.View(header)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tv.Clear()\n\t\t\thandler(v)\n\t\t\treturn\n\t\t})\n\t})\n\n\td.sections = append(d.sections, s)\n\tsort.Slice(d.sections, func(i int, j int) bool {\n\t\treturn d.sections[i].Header < d.sections[j].Header\n\t})\n\n\td.gui.Update(d.Layout)\n\treturn s\n}", "func (this *MarkupConfluence) sectionHeader(level int, text string) string {\n\treturn fmt.Sprintf(\"\\nh%v. %s\\n\", level, text)\n}", "func Thead(props *TheadProps, children ...Element) *TheadElem {\n\trProps := &_TheadProps{\n\t\tBasicHTMLElement: newBasicHTMLElement(),\n\t}\n\n\tif props != nil {\n\t\tprops.assign(rProps)\n\t}\n\n\treturn &TheadElem{\n\t\tElement: createElement(\"thead\", rProps, children...),\n\t}\n}", "func Header(title string) {\n\toptions = append(options, &Option{\n\t\tShortName: headerName,\n\t\tDescription: title,\n\t})\n}", "func TestHead(t *testing.T) {\n\ttf.UnitTest(t)\n\n\tctx := context.TODO()\n\tbuilder := chain.NewBuilder(t, address.Undef)\n\tgenTS := builder.Genesis()\n\tr := builder.Repo()\n\tbs := builder.BlockStore()\n\tcs := chain.NewStore(r.ChainDatastore(), bs, genTS.At(0).Cid(), chain.NewMockCirculatingSupplyCalculator())\n\tcboreStore := &CborBlockStore{\n\t\tStore: chain.NewStore(r.ChainDatastore(), bs, genTS.At(0).Cid(), chain.NewMockCirculatingSupplyCalculator()),\n\t}\n\t// Construct test chain data\n\tlink1 := builder.AppendOn(ctx, genTS, 2)\n\tlink2 := builder.AppendOn(ctx, link1, 3)\n\tlink3 := builder.AppendOn(ctx, link2, 1)\n\tlink4 := builder.BuildOn(ctx, link3, 2, func(bb *chain.BlockBuilder, i int) { bb.IncHeight(2) })\n\n\t// Head starts as an empty cid set\n\tassert.Equal(t, types.UndefTipSet, cs.GetHead())\n\n\t// Set Head\n\tassertSetHead(t, cboreStore, genTS)\n\tassert.ObjectsAreEqualValues(genTS.Key(), cs.GetHead())\n\n\t// Move head forward\n\tassertSetHead(t, cboreStore, link4)\n\tassert.ObjectsAreEqualValues(link4.Key(), cs.GetHead())\n\n\t// Move head back\n\tassertSetHead(t, cboreStore, link1)\n\tassert.ObjectsAreEqualValues(link1.Key(), cs.GetHead())\n}", "func (tr *Transport) Head(url string, fn HandlerFunc, options ...HandlerOption) {\n\ttr.mux.Handler(net_http.MethodHead, url, encapsulate(fn, tr.options, options))\n}", "func Head_(children ...HTML) HTML {\n return Head(nil, children...)\n}", "func WithHeader(key, value string) Option {\n\treturn func(p *Protocol) error {\n\t\tif p == nil {\n\t\t\treturn fmt.Errorf(\"http header option can not set nil protocol\")\n\t\t}\n\t\tkey = strings.TrimSpace(key)\n\t\tif key != \"\" {\n\t\t\tif p.RequestTemplate == nil {\n\t\t\t\tp.RequestTemplate = &nethttp.Request{\n\t\t\t\t\tMethod: nethttp.MethodPost,\n\t\t\t\t}\n\t\t\t}\n\t\t\tif p.RequestTemplate.Header == nil {\n\t\t\t\tp.RequestTemplate.Header = nethttp.Header{}\n\t\t\t}\n\t\t\tp.RequestTemplate.Header.Add(key, value)\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"http header option was empty string\")\n\t}\n}", "func (cia *chainInfoAPI) ChainSetHead(ctx context.Context, key types.TipSetKey) error {\n\tts, err := cia.chain.ChainReader.GetTipSet(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn cia.chain.ChainReader.SetHead(ctx, ts)\n}", "func withHeader(key, value string) Adapter {\n\treturn func(client gokismet.Client) gokismet.Client {\n\t\treturn gokismet.ClientFunc(func(req *http.Request) (*http.Response, error) {\n\t\t\treq.Header.Set(key, value)\n\t\t\treturn client.Do(req)\n\t\t})\n\t}\n}", "func SetHead(ref string) error {\n\terr := ioutil.WriteFile(UGIT_DIR+\"/\"+HEAD_PATH, []byte(ref), 0777)\n\treturn err\n}", "func (h *Head) AddMeta(meta *Element) {\n\tif meta != nil {\n\t\th.Meta = append(h.Meta, meta)\n\t\th.AddElement(meta)\n\t}\n}", "func (this *MyLinkedList) AddAtHead(val int) {\n\tthis.AddAtIndex(0, val)\n}", "func (s *Nap) Head(pathURL string) *Nap {\n\ts.method = MethodHead\n\treturn s.Path(pathURL)\n}", "func (r *Route) Head(handler http.Handler) *Route {\n\tr.handlers[http.MethodHead] = handler\n\treturn r\n}", "func (F *Frisby) Head(url string) *Frisby {\n\tF.Method = \"HEAD\"\n\tF.Url = url\n\treturn F\n}", "func (b *Builder) Header(key, value string) *Builder {\n\tb.Headers[key] = value\n\treturn b\n}", "func newHeadView(res *Head) *salesviews.HeadView {\n\tvres := &salesviews.HeadView{\n\t\tID: &res.ID,\n\t\tName: &res.Name,\n\t}\n\treturn vres\n}", "func WithtHeader(hdr map[string]string) Option {\n\treturn func(c *gate.Configuration) {\n\t\tc.DefaultHeader = hdr\n\t}\n}", "func (c *Context) setHead(key, value string) {\n\tc.f.Response.Header.Set(key, value)\n}", "func (bc *BlockChain) SetHead(head uint64) error {\n\tlog.Fatal(\"Rewinding blockchain\", \"target\", head)\n\n\tbc.mu.Lock()\n\tdefer bc.mu.Unlock()\n\n\t/// Rewind the header chain, deleting all block bodies until then\n\tdelFn := func(db rawdb.DatabaseDeleter, hash common.Hash, num uint64) {\n\t\trawdb.DeleteBody(db, hash, num)\n\t}\n\tbc.hc.SetHead(head, delFn)\n\tcurrentHeader := bc.hc.CurrentHeader()\n\n\t// Clear out any stale content from the caches\n\tbc.bodyCache.Purge()\n\tbc.bodyRLPCache.Purge()\n\n\t// Rewind the block chain, ensuring we don't end up with a stateless head block\n\tif currentBlock := bc.CurrentBlock(); currentBlock != nil && currentHeader.Number.Uint64() < currentBlock.NumberU64() {\n\t\tbc.currentBlock.Store(bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64()))\n\t}\n\n\n\t// If either blocks reached nil, reset to the genesis state\n\tif currentBlock := bc.CurrentBlock(); currentBlock == nil {\n\t\tbc.currentBlock.Store(bc.genesisBlock)\n\t}\n\n\tcurrentBlock := bc.CurrentBlock()\n\n\trawdb.WriteHeadBlockHash(bc.db, currentBlock.Hash())\n\n\treturn nil\n}", "func WithHeader(key, value string) Option {\n\treturn func(r *RequestClient) {\n\t\tr.headers.Set(key, value)\n\t}\n}", "func (rb *RequestBuilder) Head(url string) *Response {\n\treturn rb.DoRequest(http.MethodHead, url, nil)\n}", "func (c *Client) Head(ctx context.Context, url string, data ...interface{}) (*Response, error) {\n\treturn c.DoRequest(ctx, http.MethodHead, url, data...)\n}", "func (b *Builder) AddHeader(headers ...string) *Builder {\n\tfor i := range headers {\n\t\tb.headers = append(b.headers, headers[i]+\"\\r\\n\")\n\t}\n\treturn b\n}", "func AddHeader(key, value string, otherValues ...string) AdditionalAttribute {\n return func(rb *Builder) error {\n rb.AddHeader(key, value, otherValues...)\n return nil\n }\n}", "func Head(url string) *THttpClient {\r\n\treturn NewHttpClient(url).Head(\"\")\r\n}", "func NewHeadBook(ds ds.TxnDatastore) core.HeadBook {\n\treturn &dsHeadBook{\n\t\tds: ds,\n\t}\n}", "func (this *MyLinkedList) AddAtHead(val int) {\n\n\tif !this.use {\n\t\tthis.val = val\n\t\tthis.next = nil\n\t\tthis.use = true\n\t\treturn\n\t}\n\tnode := &MyLinkedList{\n\t\tval: this.val,\n\t\tnext: this.next,\n\t}\n\tthis.val = val\n\tthis.next = node\n\n}", "func (cl *Client) Head(c context.Context, url string, opts ...RequestOption) (*Response, error) {\n\treq, err := cl.NewRequest(c, http.MethodHead, url, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cl.Do(c, req)\n}", "func putSectionHeader(buf []byte, t sectionType, len uint32) {\n\tbuf[0] = byte(t<<4) | byte(len>>20)\n\tbuf[1] = byte(len >> 12)\n\tbuf[2] = byte(len >> 4)\n\tbuf[3] = byte(len)\n}", "func (c *Client) Head(name string, opts *HeadOpts) FileIterator {\n\treturn c.HeadWithContext(context.Background(), name, opts)\n}", "func WithHeader(key string, values []string) OptsReq {\n\treturn func(req *request) {\n\t\tfor _, v := range values {\n\t\t\treq.header.Add(key, v)\n\t\t}\n\t}\n}", "func (r *Route) Head(h http.Handler) *Route {\n\tr.Add(\"HEAD\", h)\n\n\treturn r\n}", "func (hb *dsHeadBook) AddHeads(t thread.ID, p peer.ID, heads []cid.Cid) error {\n\ttxn, err := hb.ds.NewTransaction(false)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error when creating txn in datastore: %w\", err)\n\t}\n\tdefer txn.Discard()\n\tkey := dsLogKey(t, p, hbBase)\n\thr := pb.HeadBookRecord{}\n\tv, err := txn.Get(key)\n\tif err == nil {\n\t\tif err := proto.Unmarshal(v, &hr); err != nil {\n\t\t\treturn fmt.Errorf(\"error unmarshaling headbookrecord proto: %w\", err)\n\t\t}\n\t}\n\tif err != nil && err != ds.ErrNotFound {\n\t\treturn fmt.Errorf(\"error when getting current heads from log %v: %w\", key, err)\n\t}\n\n\tset := make(map[cid.Cid]struct{})\n\tfor i := range hr.Heads {\n\t\tset[hr.Heads[i].Cid.Cid] = struct{}{}\n\t}\n\tfor i := range heads {\n\t\tif !heads[i].Defined() {\n\t\t\tlog.Warnf(\"ignoring head %s is is undefined for %s\", heads[i], key)\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := set[heads[i]]; !ok {\n\t\t\tentry := &pb.HeadBookRecord_HeadEntry{Cid: &pb.ProtoCid{Cid: heads[i]}}\n\t\t\thr.Heads = append(hr.Heads, entry)\n\t\t}\n\t}\n\tdata, err := proto.Marshal(&hr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error when marshaling headbookrecord proto for %v: %w\", key, err)\n\t}\n\tif err = txn.Put(key, data); err != nil {\n\t\treturn fmt.Errorf(\"error when saving new head record in datastore for %v: %v\", key, err)\n\t}\n\treturn txn.Commit()\n}", "func WithHeader(k string, v interface{}) LogBufferOption {\n\treturn func(o *logBufferOptions) {\n\t\tif o.withHeaders == nil {\n\t\t\to.withHeaders = make(map[string]interface{})\n\t\t}\n\t\to.withHeaders[k] = v\n\t}\n}", "func (c Client) WithHeader(key, value string) Client {\n\tc.headers[key] = value\n\n\treturn c\n}", "func (t *Target) AddHeader(key, value string) {\n t.header.Add(key, value)\n}", "func (app *App) HEAD(url string, handler ...Handler) *App {\n\tapp.routeANY = false\n\tapp.AppendReqAndResp(url, \"head\", handler)\n\treturn app\n}", "func NewHeadListener(lggr logger.Logger, ethClient evmclient.Client, config Config, chStop chan struct{}) httypes.HeadListener {\n\treturn &headListener{\n\t\tconfig: config,\n\t\tethClient: ethClient,\n\t\tlogger: lggr.Named(logger.HeadListener),\n\t\tchStop: chStop,\n\t}\n}", "func WithHeader(ctx context.Context, header *liverpc.Header) (ret context.Context) {\n\tret = context.WithValue(ctx, liverpc.KeyHeader, header)\n\treturn\n}", "func (al *LinkedList) AppendToHead(item int) {\n\tan := &node.Node{item, nil}\n\n\tif al.head == nil {\n\t\tal.head = an\n\t\tal.curr = an\n\t} else {\n\t\tcurrHead := al.head \n\t\tal.head = an\n\t\tan.Next = currHead\n\t}\n}", "func AddHeader(header *types.Header) {\n\tDefLedgerPid.Tell(&ledger.AddHeaderReq{Header: header})\n}", "func (g *RouterGroup) HEAD(url string, handler ...Handler) *RouterGroup {\n\tg.app.routeANY = false\n\tg.AppendReqAndResp(url, \"head\", handler)\n\treturn g\n}", "func (this *MyLinkedList) AddAtHead(val int) {\n\tnode := &ListNode{val, this.head}\n\tthis.head = node\n\tif this.size == 0 {\n\t\tthis.tail = this.head\n\t}\n\tthis.listMap = append([]*ListNode{node}, this.listMap...)\n\tthis.size++\n}", "func (db *DB) setHead(newHead Commit) error {\n\tdefer db.lock()()\n\t_, err := db.noms.FastForward(db.noms.GetDataset(MASTER_DATASET), newHead.Ref())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdb.head = newHead\n\treturn nil\n}", "func WithHeaders(headers map[string]string) Option {\n\treturn wrappedOption{otlpconfig.WithHeaders(headers)}\n}", "func (r *Router) Head(path string, handle HandleFunc) {\n\tr.register(path, http.MethodHead, handle)\n}", "func (this *MyLinkedList) AddAtHead(val int) {\n\tnewHead := &NodeList{\n\t\tVal: val,\n\t\tPrev: nil,\n\t\tNext: this.head,\n\t}\n\n\tif this.head != nil {\n\t\tthis.head.Prev = newHead\n\n\t} else {\n\t\tthis.tail = newHead\n\n\t}\n\n\tthis.head = newHead\n\n\tthis.length = this.length + 1\n}", "func (h *Head) AddNewMeta(meta map[string]string) {\n\tm := NewMeta(meta)\n\th.AddMeta(m)\n}", "func WithHeaders(headers goka.Headers) EmitOption {\n\treturn func(opts *emitOption) {\n\t\topts.headers = opts.headers.Merged(headers)\n\t}\n}", "func (h *Header) Add(key, value string) {\n\th.slice = append(h.slice, key, value)\n}", "func NewHeader(color color.Color, labels ...string) *Header {\n\th := &Header{widget.BaseWidget{}, labels, color}\n\th.ExtendBaseWidget(h)\n\treturn h\n}", "func CreateHead(samples []*MetricSample, chunkRange int64, logger log.Logger) (*Head, error) {\n\thead, err := NewHead(nil, logger, nil, chunkRange)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tapp := head.Appender()\n\tfor _, sample := range samples {\n\t\t_, err = app.Add(sample.Labels, sample.TimestampMs, sample.Value)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\terr = app.Commit()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn head, nil\n}", "func WithHeaders(addHeadersFunc addHeaders) Option {\n\treturn func(opts *Client) {\n\t\topts.headersFunc = addHeadersFunc\n\t}\n}", "func (rule *Rule) Head() *Head {\n\treturn &Head{\n\t\tName: rule.Name,\n\t\tKey: rule.Key,\n\t\tValue: rule.Value,\n\t}\n}", "func (ll *LinkedList) AddHead(e string) {\n\thead := ll.Head\n\tnn := NewNode(e)\n\tif head == nil {\n\t\tll.Head = nn\n\t} else {\n\t\tnn.Next = head\n\t\thead.Prev = nn\n\t\tll.Head = nn\n\t}\n\tll.Length++\n}", "func (c *Client) WithHeader(h http.Header) *Client {\n\tc.h = h\n\treturn c\n}", "func (client *ClientImpl) HeadClient(ctx context.Context, args HeadClientArgs) error {\n\tlocationId, _ := uuid.Parse(\"79c83865-4de3-460c-8a16-01be238e0818\")\n\t_, err := client.Client.Send(ctx, http.MethodHead, locationId, \"6.0-preview.1\", nil, nil, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (h *atomicHeadTailIndex) incHead() headTailIndex {\n\treturn headTailIndex(h.u.Add(1 << 32))\n}", "func (h *Headline) Merge(override *Headline) {\n\tif override.Title != \"\" && h.Title != override.Title {\n\t\th.Title = override.Title\n\t}\n\n\tif override.Content != \"\" && h.Content != override.Content {\n\t\th.Content = override.Content\n\t}\n\n\tif override.Hash != \"\" && h.Hash != override.Hash {\n\t\th.Hash = override.Hash\n\t}\n\n\tif override.Url != \"\" && h.Url != override.Url {\n\t\th.Url = override.Url\n\t}\n\n\tif override.VisaType != \"\" && h.VisaType != override.VisaType {\n\t\th.VisaType = override.VisaType\n\t}\n\n\tif override.CategoryID != 0 && h.CategoryID != override.CategoryID {\n\t\th.CategoryID = override.CategoryID\n\t}\n\n\tif override.CountryID != 0 && h.CountryID != override.CountryID {\n\t\th.CountryID = override.CountryID\n\t}\n}", "func (o Chapter) AddSection(i int, name string, apiVersion *string) (outputs.Section, error) {\n\terr := o.hugo.addSection(o.part.name, o.name, name)\n\tif err != nil {\n\t\treturn Section{}, err\n\t}\n\treturn Section{\n\t\thugo: o.hugo,\n\t\tpart: o.part,\n\t\tchapter: &o,\n\t}, nil\n}", "func ReadSectionHead(section io.Reader) (head SectionHead, err error) {\n\tvar length uint32\n\terr = binary.Read(section, binary.BigEndian, &length)\n\tif err != nil {\n\t\treturn head, fmt.Errorf(\"Read of Length failed: %s\", err.Error())\n\t}\n\tif length == EndSectionLength {\n\t\treturn SectionHead{\n\t\t\tByteLength: 4,\n\t\t\tNumber: 8,\n\t\t}, nil\n\t}\n\tvar sectionNumber uint8\n\terr = binary.Read(section, binary.BigEndian, &sectionNumber)\n\tif err != nil {\n\t\treturn head, err\n\t}\n\n\treturn SectionHead{\n\t\tByteLength: length,\n\t\tNumber: sectionNumber,\n\t}, nil\n}", "func NewHeadline() *Headline {\n\treturn &Headline{}\n}", "func (f *fakeDiskUpdateWatchServer) SetHeader(metadata.MD) error { return nil }", "func (i *queueIndex) putHead(aid, pos int) {\n\ti.indexArena.WriteUint64(0, uint64(aid))\n\ti.indexArena.WriteUint64(8, uint64(pos))\n}", "func (rb *RequestBuilder) WithHeaders(pairs ...string) *RequestBuilder {\n\tfor i := 0; i < len(pairs); i += 2 {\n\t\trb = rb.WithHeader(pairs[i], pairs[i+1])\n\t}\n\n\treturn rb\n}", "func WithHeader(ctx Context, header abci.Header) Context {\n\tif _, ok := GetHeader(ctx); ok {\n\t\tpanic(\"Header already set\")\n\t}\n\treturn context.WithValue(ctx, contextKeyHeader, header)\n}", "func (client *graphqlClient)AddHeader(headerName string, headerValue string){\n client.header.Add(headerName,headerValue)\n}", "func WithHeaders(hdrs jws.Headers) Option {\n\treturn option.New(optkeyHeaders, hdrs)\n}", "func (g *Group) HEAD(path string, handler Handler, middleware ...Middleware) *Group {\n\treturn g.Add(http.MethodHead, path, handler, middleware...)\n}", "func (r *Router) HEAD(url string, viewFn View) *Path {\n\treturn r.Path(fasthttp.MethodHead, url, viewFn)\n}", "func Head(path string, fn http.HandlerFunc, c ...alice.Constructor) {\n\trecord(\"HEAD\", path)\n\n\tinfoMutex.Lock()\n\tr.HEAD(path, Handler(alice.New(c...).ThenFunc(fn)))\n\tinfoMutex.Unlock()\n}", "func (d *DoublyLinkedList) AddToHead(val interface{}) {\n\tnode := &DoublyLinkedNode{val, nil, nil}\n\tif d.Count == 0 {\n\t\td.Tail = node\n\t\td.Head = node\n\t} else {\n\t\td.Head.Prev = node\n\t\tnode.Next = d.Head\n\t\td.Head = node\n\t}\n\td.Count += 1\n}", "func (list *MyLinkedList) AddAtHead(val int) {\n\tnode := &Node{val, nil}\n\n\tif 0 == list.len {\n\t\tlist.head = node\n\t\tlist.tail = node\n\t} else {\n\t\tnode.next = list.head\n\t\tlist.head = node\n\t}\n\n\tlist.len++\n}", "func Header(settings *Settings, taskSettings *TaskSettings) {\n\ttaskSettings.Format = formatHeader\n\tFetch(settings, taskSettings)\n}", "func (bldr *stackBuilder) buildByHead(ctx context.Context, head bool) error {\n\tvar (\n\t\tstack = bldr.stack\n\t\terr error\n\t)\n\n\t// Start build containers after\n\tfor _, comp := range stack.Components {\n\t\tif !comp.IsBuildable() {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Build based on whether head was requested\n\t\tif comp.Head != head {\n\t\t\tcontinue\n\t\t}\n\n\t\tbldr.doBuild(ctx, comp)\n\n\t\t// Start container from image that was just built, if this component\n\t\t// is not the head\n\t\tif !comp.Head {\n\t\t\terr = bldr.run.startContainer(ctx, stack.ID, comp)\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn err\n}", "func WithHeaderTags(headers []string) Option {\n\theaderTagsMap := normalizer.HeaderTagSlice(headers)\n\treturn func(cfg *config) {\n\t\tcfg.headerTags = internal.NewLockMap(headerTagsMap)\n\t}\n}", "func (this *MyLinkedList) AddAtHead(val int) {\n\tthis.head = &ListNode{val: val, next: this.head}\n\tif this.tail == nil {\n\t\tthis.tail = this.head\n\t}\n}", "func (this *MyLinkedList) AddAtHead(val int) {\n\thead := this.Head\n\tthis.Head = &MyNode{\n\t\tVal: val,\n\t\tPrev: nil,\n\t\tNext: head,\n\t}\n\tif head != nil {\n\t\thead.Prev = this.Head\n\t} else {\n\t\tthis.Tail = this.Head\n\t}\n\tthis.size += 1\n}", "func (p *PluginClient) Header(key, value string) OptionFunc {\n\treturn HeaderOpts(key, value)\n}", "func (s *summary) HeadSum(idx int) (sum float64) {\n\treturn float64(sumUntilIndex(s.counts, idx))\n}" ]
[ "0.611557", "0.60735554", "0.601188", "0.5821925", "0.56226987", "0.5559988", "0.547994", "0.5464441", "0.54019463", "0.5343665", "0.533313", "0.532674", "0.52113295", "0.51794606", "0.5169951", "0.51491785", "0.5082635", "0.5077762", "0.50730515", "0.50532407", "0.50119066", "0.49960744", "0.4987141", "0.4980972", "0.49647564", "0.49596786", "0.49520957", "0.494286", "0.49406758", "0.4938691", "0.4903268", "0.49019694", "0.486015", "0.48487964", "0.48308718", "0.4827033", "0.48115486", "0.48058954", "0.48022747", "0.47917232", "0.47835588", "0.47755253", "0.4773907", "0.47596207", "0.4754497", "0.47456682", "0.47290438", "0.47258824", "0.47210136", "0.47203845", "0.4706357", "0.46990559", "0.46739113", "0.4665429", "0.46558067", "0.46518528", "0.46488202", "0.46318612", "0.46314156", "0.4622354", "0.46113893", "0.45979285", "0.45936868", "0.45915613", "0.45768222", "0.4574589", "0.45739266", "0.4570815", "0.45677075", "0.4567114", "0.45606694", "0.4558469", "0.45576048", "0.4557053", "0.45536593", "0.45527413", "0.45517823", "0.45504123", "0.45333555", "0.45306823", "0.451844", "0.45036596", "0.45023358", "0.45019332", "0.45016822", "0.44929403", "0.44828495", "0.4481622", "0.44782895", "0.44726548", "0.44723958", "0.44720536", "0.44641748", "0.4460702", "0.4446599", "0.44453123", "0.44403282", "0.44395646", "0.4434288", "0.44206" ]
0.8069159
0
WithLabel adds a labelSection to the builder
func (app *applicationBuilder) WithLabel(label LabelSection) ApplicationBuilder { app.label = label return app }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func WithLabel(k string, v interface{}) Option {\n\treturn labelOption{key: k, value: v}\n}", "func WithLabel(key, value string) Option {\n\treturn func(meta metav1.Object) {\n\t\tlabels := meta.GetLabels()\n\t\tlabels = k8slabels.AddLabel(labels, key, value)\n\t\tmeta.SetLabels(labels)\n\t}\n}", "func (g Gen) WithLabel(label string) Gen {\n\treturn func(genParams *GenParameters) *GenResult {\n\t\tresult := g(genParams)\n\t\tresult.Labels = append(result.Labels, label)\n\t\treturn result\n\t}\n}", "func (m OpenShiftMachineV1Beta1TemplateBuilder) WithLabel(key, value string) OpenShiftMachineV1Beta1TemplateBuilder {\n\tif m.labels == nil {\n\t\tm.labels = make(map[string]string)\n\t}\n\n\tm.labels[key] = value\n\n\treturn m\n}", "func (j *AuroraJob) AddLabel(key string, value string) Job {\n\tif _, ok := j.metadata[key]; !ok {\n\t\tj.metadata[key] = &aurora.Metadata{Key: key}\n\t\tj.jobConfig.TaskConfig.Metadata = append(j.jobConfig.TaskConfig.Metadata, j.metadata[key])\n\t}\n\n\tj.metadata[key].Value = value\n\treturn j\n}", "func (app *controlsTestApplication) ForLabel() *controls.LabelBuilder {\n\tbuilder := controls.NewLabelBuilder(app.uiFontPainter, app.Texturize, app.uiTextRenderer)\n\tbuilder.SetScale(2.0)\n\treturn builder\n}", "func (t *AuroraTask) AddLabel(key string, value string) *AuroraTask {\n\tt.task.Metadata = append(t.task.Metadata, &aurora.Metadata{Key: key, Value: value})\n\treturn t\n}", "func (p *Builder) Label(l *Label) *Builder {\n\tif v, ok := p.labels[l]; ok && v >= 0 {\n\t\tlog.Panicln(\"Label failed: label is defined already -\", l.Name)\n\t}\n\tp.labels[l] = p.code.Len()\n\treturn p\n}", "func AddLabel(ctx context.Context, obj *Object, key, value string, override bool) error {\n\tif key == \"\" || value == \"\" {\n\t\treturn fmt.Errorf(\"key and value cannot be empty\")\n\t}\n\n\tif err := addToNestedMap(obj, key, value, override, \"metadata\", \"labels\"); err != nil {\n\t\treturn err\n\t}\n\n\tvar nestedFields []string\n\tswitch kind := ObjectKind(obj); kind {\n\tcase \"CronJob\":\n\t\tnestedFields = []string{\"spec\", \"jobTemplate\", \"spec\", \"template\", \"metadata\", \"labels\"}\n\tcase \"DaemonSet\", \"Deployment\", \"Job\", \"ReplicaSet\", \"ReplicationController\", \"StatefulSet\":\n\t\tnestedFields = []string{\"spec\", \"template\", \"metadata\", \"labels\"}\n\tdefault:\n\t\treturn nil\n\t}\n\tif err := addToNestedMap(obj, key, value, override, nestedFields...); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (fc *fakeClient) AddLabel(owner, repo string, number int, label string) error {\n\tfc.added = append(fc.added, label)\n\tfc.labels = append(fc.labels, label)\n\treturn nil\n}", "func (i *Icon) AddLabel(label string) {\n\ti.Config.Label = label\n}", "func (d *DeviceInfo) AddLabel(name, value string) *DeviceInfo {\n\tm := d.Labels\n\tif m == nil {\n\t\tm = make(map[string]string)\n\t\td.Labels = m\n\t}\n\tm[name] = value\n\treturn d\n}", "func AddLabel(obj mftest.Object, label string, value string) mftest.Object {\n\tlabels := obj.GetLabels()\n\tif labels == nil {\n\t\tobj.SetLabels(make(map[string]string))\n\t}\n\tobj.GetLabels()[label] = value\n\treturn obj\n}", "func Label(label string) Option {\n\treturn func(o *Options) {\n\t\to.label = label\n\t}\n}", "func Label(opts render.TagOpts) render.TagBuilder {\n\treturn render.NewTag(\"label\").WithOpts(opts)\n}", "func (b *Builder) WithJobLabel(l string) *Builder {\n\tb.sm.Spec.JobLabel = l\n\treturn b\n}", "func (t *Test) Label(labels ...label.Instance) *Test {\n\tt.labels = append(t.labels, labels...)\n\treturn t\n}", "func OptLabel(label string) Option {\n\treturn func(w *Wallet) {\n\t\tw.Meta[\"label\"] = label\n\t}\n}", "func NewLabel(text string) *Label {\n\tw := &Label{\n\t\tText: text,\n\t}\n\tw.Wrapper = w\n\treturn w\n}", "func (f Form) Label(value string, opts tags.Options) *tags.Tag {\n\topts[\"body\"] = value\n\treturn tags.New(\"label\", opts)\n}", "func (c *client) AddLabel(org, repo string, number int, label string) error {\n\treturn c.AddLabelWithContext(context.Background(), org, repo, number, label)\n}", "func (b *buffer) Label(label string, indent int) {\n\tb.Write(fmt.Sprintf(\"%s:\\n\", strings.TrimSpace(label)), indent)\n}", "func (b *button) label(eng vu.Engine, part vu.Part, text string) {\n\tcolour := \"weblySleek22Black\"\n\tif b.banner == nil {\n\t\tb.banner = part.AddPart()\n\t\tb.banner.SetBanner(text, \"uv\", \"weblySleek22\", colour)\n\t\tb.banner.SetLocation(float64(b.x), float64(b.y), 0)\n\t} else {\n\t\tb.banner.UpdateBanner(text)\n\t}\n}", "func (b *Builder) WithLabels(labels map[string]string) *Builder {\n\tif len(labels) == 0 {\n\t\tb.errs = append(\n\t\t\tb.errs,\n\t\t\terrors.New(\"failed to build PVC object: missing labels\"),\n\t\t)\n\t\treturn b\n\t}\n\n\tif b.pvc.object.Labels == nil {\n\t\tb.pvc.object.Labels = map[string]string{}\n\t}\n\n\tfor key, value := range labels {\n\t\tb.pvc.object.Labels[key] = value\n\t}\n\treturn b\n}", "func NewLabeler(opts ...Option) Labeler {\n\to := newOptions(opts)\n\tlbl := Labeler{\n\t\toptions: o,\n\t}\n\treturn lbl\n}", "func WithLabels(labels map[string]string) Option {\n\treturn func(o *options) {\n\t\to.labels = labels\n\t}\n}", "func (e *HTTPResponseEvent) WithLabel(key, value string) *HTTPResponseEvent {\n\te.AddLabelValue(key, value)\n\treturn e\n}", "func (zc *Zcounter) Label(l string) {\n\tzc.label = l\n}", "func (g *Generator) AddConfigLabel(label, value string) {\n\tg.image.Config.Labels[label] = value\n}", "func (p *Parser) Label(label string) *Parser {\n\tp.nextLabel = label\n\treturn p\n}", "func (k *Item) SetLabel(l string) {\n\tk.SetString(LabelKey, l)\n}", "func (s *Service) AddLabel(label *model.Label) (err error) {\n\tif _, err = s.dao.QueryLabel(label); err == nil {\n\t\terr = ecode.MelloiLabelExistErr\n\t\treturn\n\t}\n\tlabel.Active = 1\n\treturn s.dao.AddLabel(label)\n}", "func NewLabel(str string, btnFont font.Face) *Label {\n\tl := &Label{text: str, font: btnFont}\n\tbound, _ := font.BoundString(l.font, l.text)\n\tl.width = (bound.Max.X - bound.Min.X).Ceil()\n\tl.height = (bound.Max.Y - bound.Min.Y).Ceil()\n\treturn l\n}", "func WithServiceLabel(key, value string) ServiceOption {\n\treturn func(service *v1.Service) {\n\t\tif service.Labels == nil {\n\t\t\tservice.Labels = make(map[string]string, 1)\n\t\t}\n\t\tservice.Labels[key] = value\n\t}\n}", "func (p *plugin) Label(instance instance.ID, labels map[string]string) error {\n\treturn fmt.Errorf(\"VMware vSphere VM label updates are not implemented yet\")\n}", "func (l Label) Label() string { return string(l) }", "func (b *button) label(part *vu.Ent, keyCode int) {\n\tif keysym := vu.Symbol(keyCode); keysym > 0 {\n\t\tif b.banner == nil {\n\t\t\tb.banner = part.AddPart().SetAt(float64(b.x), float64(b.y), 0)\n\t\t\tb.banner.MakeLabel(\"labeled\", \"lucidiaSu22\")\n\t\t\tb.banner.SetColor(0, 0, 0)\n\t\t}\n\t\tif keyCode == 0 {\n\t\t\tkeyCode = vu.KSpace\n\t\t}\n\t\tb.banner.SetStr(string(keysym))\n\t}\n}", "func Label(name string) string {\n\treturn fmt.Sprintf(\"%s/%s\", LabelPrefix, name)\n}", "func WithLabels(labels map[string]string) Opt {\n\treturn func(object client.Object) {\n\t\tobject.SetLabels(labels)\n\t}\n}", "func (b *profileBuilder) pbLabel(tag int, key, str string, num int64) {\n\tstart := b.pb.startMessage()\n\tb.pb.int64Opt(tagLabel_Key, b.stringIndex(key))\n\tb.pb.int64Opt(tagLabel_Str, b.stringIndex(str))\n\tb.pb.int64Opt(tagLabel_Num, num)\n\tb.pb.endMessage(tag, start)\n}", "func (tags Tags) With(label string, obj interface{}) Tags {\n\tif obj != nil {\n\t\ttags.M[label] = obj\n\t}\n\treturn tags\n}", "func Label(attrs []htmlgo.Attribute, children ...HTML) HTML {\n\treturn &htmlgo.Tree{Tag: \"label\", Attributes: attrs, Children: children}\n}", "func (o *HyperflexVmSnapshotInfoAllOf) SetLabel(v string) {\n\to.Label = &v\n}", "func (e Edge) Label(value interface{}) Edge {\n\te.AttributesMap.Attr(\"label\", value)\n\treturn e\n}", "func (o *FormField) SetLabel(v string) {\n\to.Label = &v\n}", "func (o *TppCredentialsParams) SetLabel(v string) {\n\to.Label = v\n}", "func (m *Manager) SetLabel(k, v string) {\n\tm.b.SetLabel(k, v)\n}", "func newLabel(value string, g *Graph) *Label {\n Assert(nilGraph, g != nil)\n Assert(nilTextStore, g.textStore != nil)\n \n l := new(Label)\n t := newText(value)\n l.value = g.textStore.addText(t)\n \n return l\n}", "func (n Node) Label(label string) Node {\n\treturn n.Attr(\"label\", label)\n}", "func (pc *programCode) createLabel(name string) {\n\tcode := \"\"\n\tcode += \"\\n\" + name + \":\\n\"\n\tpc.funcSlice = append(pc.funcSlice, name)\n\tpc.indentLevel += 1 // dive deeper -> next buffer.\n\t// Please have a look to FIXME: Where can I find what?\n\tpc.appendCode(code)\n\n}", "func UseLabel(label string) Option {\n\treturn func(p *Plugin) {\n\t\tp.MicroserviceLabel = label\n\t}\n}", "func (in *ActionVpsConfigCreateInput) SetLabel(value string) *ActionVpsConfigCreateInput {\n\tin.Label = value\n\n\tif in._selectedParameters == nil {\n\t\tin._selectedParameters = make(map[string]interface{})\n\t}\n\n\tin._selectedParameters[\"Label\"] = nil\n\treturn in\n}", "func (b *Builder) WithLabelsNew(labels map[string]string) *Builder {\n\tif len(labels) == 0 {\n\t\tb.errs = append(\n\t\t\tb.errs,\n\t\t\terrors.New(\"failed to build PVC object: missing labels\"),\n\t\t)\n\t\treturn b\n\t}\n\n\t// copy of original map\n\tnewlbls := map[string]string{}\n\tfor key, value := range labels {\n\t\tnewlbls[key] = value\n\t}\n\n\t// override\n\tb.pvc.object.Labels = newlbls\n\treturn b\n}", "func (api *configurationsnapshotAPI) Label(obj *api.Label) 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 err\n\t\t}\n\n\t\t_, err = apicl.ClusterV1().ConfigurationSnapshot().Label(context.Background(), obj)\n\t\treturn err\n\t}\n\n\tctkitObj, err := api.Find(obj.GetObjectMeta())\n\tif err != nil {\n\t\treturn err\n\t}\n\twriteObj := ctkitObj.ConfigurationSnapshot\n\twriteObj.Labels = obj.Labels\n\n\tapi.ct.handleConfigurationSnapshotEvent(&kvstore.WatchEvent{Object: &writeObj, Type: kvstore.Updated})\n\treturn nil\n}", "func (p libvirtPlugin) Label(instance instance.ID, labels map[string]string) error {\n\t//l := log.WithField(\"instance\", instance)\n\n\tconn, err := libvirt.NewConnect(p.URI)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Connecting to libvirt\")\n\t}\n\tdefer conn.Close()\n\n\td, err := p.lookupInstanceByID(conn, instance)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Looking up domain\")\n\t}\n\n\tmeta := infrakitMetadata{}\n\tm, err := d.GetMetadata(libvirt.DOMAIN_METADATA_ELEMENT,\n\t\t\"https://github.com/docker/infrakit\",\n\t\tlibvirt.DOMAIN_AFFECT_LIVE)\n\tif err == nil {\n\t\tif err := meta.Unmarshal(m); err != nil {\n\t\t\treturn errors.Wrap(err, \"Unmarshalling domain metadata XML\")\n\t\t}\n\t} else {\n\t\tmeta.LogicalID = string(instance)\n\t}\n\n\tmetaSetTags(&meta, labels)\n\n\txmlbytes, err := xml.MarshalIndent(meta, \"\", \" \")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Marshalling infrakitMetadata\")\n\t}\n\tm = string(xmlbytes)\n\n\terr = d.SetMetadata(libvirt.DOMAIN_METADATA_ELEMENT,\n\t\tm,\n\t\t\"infrakit\",\n\t\t\"https//github.com/docker/infrakit\",\n\t\tlibvirt.DOMAIN_AFFECT_LIVE)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Setting domain metadata\")\n\t}\n\n\treturn nil\n}", "func NewLabel(s string) *Label {\n\treturn &Label{Text: s, Align: 6}\n}", "func (issue *Issue) AddLabel(labels []string) error {\n\tfor i, val := range labels {\n\t\tlabels[i] = fmt.Sprintf(`{\"add\": \"%s\"}`, val)\n\t}\n\treturn updateLabelsHelper(labels, issue.Key)\n}", "func (issue *Issue) AddLabel(labels []string) error {\n\tfor i, val := range labels {\n\t\tlabels[i] = fmt.Sprintf(`{\"add\": \"%s\"}`, val)\n\t}\n\treturn updateLabelsHelper(labels, issue.Key)\n}", "func NewLabelCommand(k string, v string, NoExp bool) *LabelCommand {\n\tkvp := KeyValuePair{Key: k, Value: v}\n\tc := \"LABEL \"\n\tc += kvp.String()\n\tnc := withNameAndCode{code: c, name: \"label\"}\n\tcmd := &LabelCommand{\n\t\twithNameAndCode: nc,\n\t\tLabels: KeyValuePairs{\n\t\t\tkvp,\n\t\t},\n\t\tnoExpand: NoExp,\n\t}\n\treturn cmd\n}", "func (b *Builder) JumpLabel(label uint32) {\n\tb.instructions = append(b.instructions, asm.JumpLabel{\n\t\tLabel: label,\n\t})\n}", "func (s ProxyClaimRequestRequest) NewLabel() (util.LocalizedText, error) {\n\tss, err := util.NewLocalizedText(s.Struct.Segment())\n\tif err != nil {\n\t\treturn util.LocalizedText{}, err\n\t}\n\terr = s.Struct.SetPtr(2, ss.Struct.ToPtr())\n\treturn ss, err\n}", "func (api *licenseAPI) Label(obj *api.Label) 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 err\n\t\t}\n\n\t\t_, err = apicl.ClusterV1().License().Label(context.Background(), obj)\n\t\treturn err\n\t}\n\n\tctkitObj, err := api.Find(obj.GetObjectMeta())\n\tif err != nil {\n\t\treturn err\n\t}\n\twriteObj := ctkitObj.License\n\twriteObj.Labels = obj.Labels\n\n\tapi.ct.handleLicenseEvent(&kvstore.WatchEvent{Object: &writeObj, Type: kvstore.Updated})\n\treturn nil\n}", "func (o *WorkflowServiceItemDefinitionAllOf) SetLabel(v string) {\n\to.Label = &v\n}", "func (m *Media) SetLabel(value *string)() {\n m.label = value\n}", "func WithPodLabel(key, value string) PodWaitCriterion {\n\treturn func(a *MemberAwaitility, pod v1.Pod) bool {\n\t\treturn pod.Labels[key] == value\n\t}\n}", "func (s *htmlState) recordLabel(id string) {\n\ts.labelFor = append(s.labelFor, id)\n}", "func (f *TagField) SetLabel(l string) {\n\tf.label = l\n}", "func (o *TppCertificateParams) SetLabel(v string) {\n\to.Label = v\n}", "func (b *Bot) Label(ctx context.Context) error {\n\tfiles, err := b.c.GitHub.ListFiles(ctx,\n\t\tb.c.Environment.Organization,\n\t\tb.c.Environment.Repository,\n\t\tb.c.Environment.Number)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\tlabels, err := b.labels(ctx, files)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tif len(labels) == 0 {\n\t\treturn nil\n\t}\n\n\terr = b.c.GitHub.AddLabels(ctx,\n\t\tb.c.Environment.Organization,\n\t\tb.c.Environment.Repository,\n\t\tb.c.Environment.Number,\n\t\tlabels)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\treturn nil\n}", "func (m OpenShiftMachineV1Beta1TemplateBuilder) WithLabels(labels map[string]string) OpenShiftMachineV1Beta1TemplateBuilder {\n\tm.labels = labels\n\treturn m\n}", "func (wlt *Wallet) SetLabel(label string) {\n\twlt.Meta[\"label\"] = label\n}", "func (o *WidgetMarker) SetLabel(v string) {\n\to.Label = &v\n}", "func (c *GlPushGroupMarkerEXT) Label(ctx context.Context, s *api.GlobalState) string {\n\treturn readString(ctx, c, s, c.Marker(), c.Length())\n}", "func AddMetadataLabel(pod *corev1.Pod, labelName, labelContent string) *corev1.Pod {\n\tif nil == pod.ObjectMeta.Labels {\n\t\tpod.ObjectMeta.Labels = make(map[string]string)\n\t}\n\n\tpod.ObjectMeta.Labels[labelName] = labelContent\n\n\treturn pod\n}", "func (m *TransposableMatrix) SetLabel(x, y int, slt Slot) {\n\tbefore := m.Get(x, y)\n\tbefore.Label = slt.Label\n\tm.Set(x, y, before)\n}", "func (o *WorkflowWorkflowDefinitionAllOf) SetLabel(v string) {\n\to.Label = &v\n}", "func (l *LocalSDKServer) SetLabel(_ context.Context, kv *sdk.KeyValue) (*sdk.Empty, error) {\n\tlogrus.WithField(\"values\", kv).Info(\"Setting label\")\n\tl.gsMutex.Lock()\n\tdefer l.gsMutex.Unlock()\n\n\tif l.gs.ObjectMeta == nil {\n\t\tl.gs.ObjectMeta = &sdk.GameServer_ObjectMeta{}\n\t}\n\tif l.gs.ObjectMeta.Labels == nil {\n\t\tl.gs.ObjectMeta.Labels = map[string]string{}\n\t}\n\n\tl.gs.ObjectMeta.Labels[metadataPrefix+kv.Key] = kv.Value\n\tl.update <- struct{}{}\n\treturn &sdk.Empty{}, nil\n}", "func (gauo *GithubAssetUpdateOne) SetLabel(s string) *GithubAssetUpdateOne {\n\tgauo.mutation.SetLabel(s)\n\treturn gauo\n}", "func Label(x, y, width int, fg, bg termbox.Attribute, text string) {\n\t// We cannot rely on range index because it shows byte position\n\t// instead of rune position\n\ti := -1\n\tfor _, r := range text {\n\t\ti++\n\t\tif width > 0 && i >= width {\n\t\t\tbreak\n\t\t}\n\t\ttermbox.SetCell(x+i, y, r, fg, bg)\n\t}\n\t// Fill the rest of the width with spaces\n\tfor i = i + 1; width > 0 && i < width; i++ {\n\t\ttermbox.SetCell(x+i, y, ' ', fg, bg)\n\t}\n}", "func (v *vertex) HasLabel(vertexLabel ...string) interfaces.Vertex {\n\tquery := multiParamQuery(\".hasLabel\", vertexLabel...)\n\treturn v.Add(query)\n}", "func (l *Logger) SetLabel(level LogLevel, label string) {\n\tswitch level {\n\tcase Info:\n\t\tl.logInfo.SetPrefix(label)\n\tcase Notice:\n\t\tl.logNotice.SetPrefix(label)\n\tcase Warning:\n\t\tl.logWarning.SetPrefix(label)\n\tcase Debug:\n\t\tl.logDebug.SetPrefix(label)\n\tcase Trace:\n\t\tl.logTrace.SetPrefix(label)\n\tcase Error:\n\t\tl.logError.SetPrefix(label)\n\tcase Critical:\n\t\tl.logCritical.SetPrefix(label)\n\tcase All:\n\t\tl.logInfo.SetPrefix(label)\n\t\tl.logNotice.SetPrefix(label)\n\t\tl.logWarning.SetPrefix(label)\n\t\tl.logDebug.SetPrefix(label)\n\t\tl.logTrace.SetPrefix(label)\n\t\tl.logError.SetPrefix(label)\n\t\tl.logCritical.SetPrefix(label)\n\t}\n}", "func AppendNamespaceLabel(namespace string, labels map[string]string) map[string]string {\n\tfinal := labels\n\n\tif final == nil {\n\t\tfinal = make(map[string]string)\n\t}\n\n\tif final[NamespaceLabelKey] == \"\" {\n\t\tfinal[NamespaceLabelKey] = namespace\n\t}\n\n\treturn final\n}", "func (c *STableField) Label(label string) IQueryField {\n\tif len(label) > 0 {\n\t\tc.alias = label\n\t}\n\treturn c\n}", "func Label(key string, value interface{}, args ...context.Context) {\n\tcurrentTracer := ExtractTracer(args)\n\tif currentTracer != nil {\n\t\tcurrentTracer.AddLabel(key, value)\n\t}\n}", "func (nv *NetView) ConfigLabels(labs []string) bool {\n\tvs := nv.Scene()\n\tlgp, err := vs.ChildByNameTry(\"Labels\", 1)\n\tif err != nil {\n\t\tlgp = gi3d.AddNewGroup(vs, vs, \"Labels\")\n\t}\n\n\tlbConfig := kit.TypeAndNameList{}\n\tfor _, ls := range labs {\n\t\tlbConfig.Add(gi3d.KiT_Text2D, ls)\n\t}\n\tmods, updt := lgp.ConfigChildren(lbConfig)\n\tif mods {\n\t\tfor i, ls := range labs {\n\t\t\tlb := lgp.ChildByName(ls, i).(*gi3d.Text2D)\n\t\t\tlb.Defaults(vs)\n\t\t\tlb.SetText(vs, ls)\n\t\t\tlb.SetProp(\"text-align\", gist.AlignLeft)\n\t\t\tlb.SetProp(\"vertical-align\", gist.AlignTop)\n\t\t\tlb.SetProp(\"white-space\", gist.WhiteSpacePre)\n\t\t}\n\t}\n\tlgp.UpdateEnd(updt)\n\treturn mods\n}", "func Label_(children ...HTML) HTML {\n return Label(nil, children...)\n}", "func (s *BaseGraffleParserListener) EnterLabel(ctx *LabelContext) {}", "func (d *DeviceInfo) AddLabels(labels map[string]string) *DeviceInfo {\n\tif d.Labels == nil {\n\t\td.Labels = labels\n\t} else {\n\t\tfor k, v := range labels {\n\t\t\td.Labels[k] = v\n\t\t}\n\t}\n\treturn d\n}", "func (p *Parser) label() {\n\tlabel := p.previous.Literal\n\tif offset, ok := p.labels[label]; ok {\n\t\tp.emitByte(byte(offset))\n\t} else {\n\t\tdata := Label{offset: p.chunk.count, token: p.previous}\n\t\tp.backpatch[label] = append(p.backpatch[label], data)\n\t\tp.emitByte(0)\n\t}\n}", "func writeLabelWithText(pdf *gofpdf.Fpdf, label string, labelFontStyle string,\n\tcontent string, contentFontStyle string, ratio float64) {\n\n\tpdf.SetFontSize(11)\n\tpdf.SetFontStyle(labelFontStyle)\n\t_, lineH := pdf.GetFontSize()\n\tmL, _, _, _ := pdf.GetMargins()\n\tpdf.CellFormat(getContentWidth(pdf)*ratio, lineH*1.5, label, \"\", 0, \"L\", false, 0, \"\")\n\tpdf.SetFontStyle(contentFontStyle)\n\tstartX := pdf.GetX()\n\thtml := pdf.HTMLBasicNew()\n\tfor _, line := range strings.Split(content, \"\\n\") {\n\t\thtml.Write(lineH*1.25, line)\n\t\tpdf.SetY(pdf.GetY() + lineH*1.25)\n\t\tpdf.SetX(startX)\n\t}\n\tpdf.SetX(mL)\n\n}", "func (gau *GithubAssetUpdate) SetLabel(s string) *GithubAssetUpdate {\n\tgau.mutation.SetLabel(s)\n\treturn gau\n}", "func AddPhotoLabel(router *gin.RouterGroup) {\n\trouter.POST(\"/photos/:uid/label\", func(c *gin.Context) {\n\t\ts := Auth(SessionID(c), acl.ResourcePhotos, acl.ActionUpdate)\n\n\t\tif s.Invalid() {\n\t\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, ErrUnauthorized)\n\t\t\treturn\n\t\t}\n\n\t\tm, err := query.PhotoByUID(c.Param(\"uid\"))\n\n\t\tif err != nil {\n\t\t\tc.AbortWithStatusJSON(http.StatusNotFound, ErrPhotoNotFound)\n\t\t\treturn\n\t\t}\n\n\t\tvar f form.Label\n\n\t\tif err := c.BindJSON(&f); err != nil {\n\t\t\tc.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\"error\": txt.UcFirst(err.Error())})\n\t\t\treturn\n\t\t}\n\n\t\tlabelEntity := entity.FirstOrCreateLabel(entity.NewLabel(f.LabelName, f.LabelPriority))\n\n\t\tif labelEntity == nil {\n\t\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{\"error\": \"failed creating label\"})\n\t\t\treturn\n\t\t}\n\n\t\tif err := labelEntity.Restore(); err != nil {\n\t\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{\"error\": \"could not restore label\"})\n\t\t}\n\n\t\tphotoLabel := entity.FirstOrCreatePhotoLabel(entity.NewPhotoLabel(m.ID, labelEntity.ID, f.Uncertainty, \"manual\"))\n\n\t\tif photoLabel == nil {\n\t\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{\"error\": \"failed updating photo label\"})\n\t\t\treturn\n\t\t}\n\n\t\tif photoLabel.Uncertainty > f.Uncertainty {\n\t\t\tif err := photoLabel.Updates(map[string]interface{}{\n\t\t\t\t\"Uncertainty\": f.Uncertainty,\n\t\t\t\t\"LabelSrc\": entity.SrcManual,\n\t\t\t}); err != nil {\n\t\t\t\tlog.Errorf(\"label: %s\", err)\n\t\t\t}\n\t\t}\n\n\t\tp, err := query.PhotoPreloadByUID(c.Param(\"uid\"))\n\n\t\tif err != nil {\n\t\t\tc.AbortWithStatusJSON(http.StatusNotFound, ErrPhotoNotFound)\n\t\t\treturn\n\t\t}\n\n\t\tif err := p.Save(); err != nil {\n\t\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{\"error\": txt.UcFirst(err.Error())})\n\t\t\treturn\n\t\t}\n\n\t\tPublishPhotoEvent(EntityUpdated, c.Param(\"uid\"), c)\n\n\t\tevent.Success(\"label updated\")\n\n\t\tc.JSON(http.StatusOK, p)\n\t})\n}", "func AddLabel(label types.Label) ([]byte, error) {\n\tlog.Trace.Printf(\"Adding the following label: %+v\", label)\n\tvar ret []byte\n\tvar err error\n\n\tif err = store.DB.Create(&label).Error; err == nil {\n\t\tlog.Trace.Printf(\"Successfully added the label to the database: %+v\", label)\n\t\tret, err = json.Marshal(label)\n\t} else {\n\t\tlog.Warning.Printf(err.Error())\n\t}\n\n\treturn ret, err\n}", "func (o *Filesystem) SetLabel(ctx context.Context, label string, options map[string]dbus.Variant) (err error) {\n\terr = o.object.CallWithContext(ctx, InterfaceFilesystem+\".SetLabel\", 0, label, options).Store()\n\treturn\n}", "func (api *clusterAPI) Label(obj *api.Label) 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 err\n\t\t}\n\n\t\t_, err = apicl.ClusterV1().Cluster().Label(context.Background(), obj)\n\t\treturn err\n\t}\n\n\tctkitObj, err := api.Find(obj.GetObjectMeta())\n\tif err != nil {\n\t\treturn err\n\t}\n\twriteObj := ctkitObj.Cluster\n\twriteObj.Labels = obj.Labels\n\n\tapi.ct.handleClusterEvent(&kvstore.WatchEvent{Object: &writeObj, Type: kvstore.Updated})\n\treturn nil\n}", "func (o *DeployKey) SetLabel(v string) {\n\to.Label = &v\n}", "func (o *HyperflexVmSnapshotInfoAllOf) HasLabel() bool {\n\tif o != nil && o.Label != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (api *versionAPI) Label(obj *api.Label) 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 err\n\t\t}\n\n\t\t_, err = apicl.ClusterV1().Version().Label(context.Background(), obj)\n\t\treturn err\n\t}\n\n\tctkitObj, err := api.Find(obj.GetObjectMeta())\n\tif err != nil {\n\t\treturn err\n\t}\n\twriteObj := ctkitObj.Version\n\twriteObj.Labels = obj.Labels\n\n\tapi.ct.handleVersionEvent(&kvstore.WatchEvent{Object: &writeObj, Type: kvstore.Updated})\n\treturn nil\n}", "func WithLabelSelector(labelSelector *metav1.LabelSelector) func(opts *Options) {\n\treturn func(opts *Options) {\n\t\topts.labelSelector = labelSelector\n\t}\n}", "func (element *Element) Label(value string) *Element {\n\treturn element.Attr(\"label\", value)\n}" ]
[ "0.7042802", "0.6714825", "0.6645144", "0.6584446", "0.62846386", "0.6190551", "0.6139383", "0.61151904", "0.60762894", "0.60660005", "0.60486287", "0.6003239", "0.596394", "0.5875127", "0.5818254", "0.57637286", "0.57486284", "0.573727", "0.5729538", "0.5707006", "0.56715226", "0.5648635", "0.56041044", "0.5592596", "0.5561379", "0.5551715", "0.55279565", "0.55275035", "0.5519748", "0.5504988", "0.55032986", "0.54140705", "0.54020876", "0.5390498", "0.5383508", "0.53572375", "0.5356956", "0.5332143", "0.5290437", "0.5288289", "0.52747864", "0.52684087", "0.5236533", "0.52009994", "0.5191879", "0.5187444", "0.51867425", "0.5152321", "0.51428753", "0.51389414", "0.5133435", "0.5132416", "0.5126804", "0.5124018", "0.5103979", "0.50902104", "0.5087724", "0.5087724", "0.5078648", "0.5065072", "0.50623065", "0.5043534", "0.5042078", "0.5038626", "0.50281435", "0.502299", "0.50179946", "0.5017284", "0.50142395", "0.5013664", "0.4959845", "0.49547097", "0.49307227", "0.49250394", "0.4918806", "0.4908597", "0.49071187", "0.49067014", "0.49054924", "0.49028596", "0.4901203", "0.4896319", "0.48954287", "0.48873937", "0.48772255", "0.48742747", "0.48742747", "0.48741496", "0.48711267", "0.4869594", "0.48649803", "0.48625034", "0.48599768", "0.48537308", "0.4839299", "0.4837662", "0.48342317", "0.4823955", "0.48137605", "0.48108968" ]
0.7461231
0
WithMain adds a mainSection to the builder
func (app *applicationBuilder) WithMain(main MainSection) ApplicationBuilder { app.main = main return app }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t *targetBuilder) setMain(main string) *targetBuilder {\n\tt.main = &main\n\treturn t\n}", "func (app *mainSectionBuilder) WithInstructions(ins []Instruction) MainSectionBuilder {\n\tapp.instructions = ins\n\treturn app\n}", "func (app *mainSectionBuilder) Create() MainSectionBuilder {\n\treturn createMainSectionBuilder()\n}", "func (o *LinkRouteTable) SetMain(v bool) {\n\to.Main = &v\n}", "func Main(props *MainProps, children ...Element) *MainElem {\n\trProps := &_MainProps{\n\t\tBasicHTMLElement: newBasicHTMLElement(),\n\t}\n\n\tif props != nil {\n\t\tprops.assign(rProps)\n\t}\n\n\treturn &MainElem{\n\t\tElement: createElement(\"main\", rProps, children...),\n\t}\n}", "func NewMain() *Main {\n\tm := &Main{\n\t\tnexter: pdk.NewNexter(),\n\t\ttotalRecs: &Counter{},\n\t}\n\treturn m\n}", "func Main(attrs []htmlgo.Attribute, children ...HTML) HTML {\n\treturn &htmlgo.Tree{Tag: \"main\", Attributes: attrs, Children: children}\n}", "func NewMainRoutineBuilder() *MainRoutineBuilder {\n\treturn &MainRoutineBuilder{}\n}", "func NewMain(name string, c *cobra.Command, cleanup CleanupFunc) *Main {\n\tb, _ := c.Flags().GetBool(printReportFlagName)\n\td, _ := c.Flags().GetBool(deferDelete)\n\tif d {\n\t\tcleanup = NoCleanupFunc\n\t}\n\n\tm := &Main{\n\t\tName: name,\n\t\tReport: &Report{\n\t\t\tTestName: name,\n\t\t\tTimeStart: time.Now(),\n\t\t},\n\t\tCleanup: cleanup,\n\t\tprintReport: b,\n\t\tDeferDelete: d,\n\t}\n\tm.PrintStart()\n\treturn m\n}", "func (s *GetWorkflowOutput) SetMain(v string) *GetWorkflowOutput {\n\ts.Main = &v\n\treturn s\n}", "func (b *MainRoutineBuilder) MainRoutine() string {\n\treturn b.routine\n}", "func returnGoMainMiddlewareSection() (string, error) {\n\ttopString := models.TopCommentBlock +\n\t\tfmt.Sprintf(\"\\n/\tMiddleware\\n\") +\n\t\tmodels.BottomCommentBlock +\n\t\tfmt.Sprintf(\"\\n\\n\")\n\n\treturn topString, nil\n}", "func (s *CreateWorkflowInput) SetMain(v string) *CreateWorkflowInput {\n\ts.Main = &v\n\treturn s\n}", "func (app *applicationBuilder) WithTest(test TestSection) ApplicationBuilder {\n\tapp.test = test\n\treturn app\n}", "func (app *mainSectionBuilder) Now() (MainSection, error) {\n\tif app.instructions == nil {\n\t\treturn nil, errors.New(\"the []Instruction are mandatory in order to build a MainSection instance\")\n\t}\n\n\treturn createMainSection(app.instructions), nil\n}", "func MakeMain(app *App) (string, error) {\n\tbuf := new(bytes.Buffer)\n\tif err := mainTemplate.Execute(buf, app); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn buf.String(), nil\n}", "func returnGoMainRouterSection(hasDB bool, routeHandler []string) (string, error) {\n\ttopString := models.TopCommentBlock +\n\t\tfmt.Sprintf(\"\\n/\tInitialize router and controllers\\n\") +\n\t\tmodels.BottomCommentBlock +\n\t\tfmt.Sprintf(\"\\n\\n\tr := mux.NewRouter()\\n\\n\")\n\tfor _, v := range routeHandler {\n\t\ttopString += fmt.Sprintf(\"\t%sRH := routeHandlers.New%s(\\n\", strings.ToLower(v), strings.Title(v)) +\n\t\t\tfmt.Sprintf(\"\t\tsrvcs.%s,\\n\t)\\n\", strings.Title(v))\n\t}\n\ttopString += fmt.Sprintf(\"\\n\")\n\n\treturn topString, nil\n}", "func (g *Generator) FMain() *GeneratorFile {\n\treturn g.F(FILEID_MAIN)\n}", "func Main(mainrun func()) {\n\tDebugEnumSizes()\n\tdriver.Main(func(app oswin.App) {\n\t\tmainrun()\n\t})\n}", "func (c *ConfigParser) addSection(section string) {\n\toptions := make(map[string]string)\n\tinterpolate := make(map[string]InterpolateObj)\n\tsd := SectionData{options, interpolate}\n\tc.sections[section] = sd\n}", "func NewMain() *Main {\n\tvar config Config\n\treturn &Main{\n\t\tConfig: config,\n\n\t\tDB: pg.NewDB(\"\"),\n\t\tHTTPServer: http.NewServer(),\n\t}\n}", "func mainStartGtk(winTitle string, width, height int, center bool) {\n\tobj = new(MainControlsObj)\n\tgtk.Init(nil)\n\tif newBuilder(mainGlade) == nil {\n\t\t// Init tempDir and Remove it on quit if requested.\n\t\tif doTempDir {\n\t\t\ttempDir = tempMake(Name)\n\t\t\tdefer os.RemoveAll(tempDir)\n\t\t}\n\t\t// Parse Gtk objects\n\t\tgladeObjParser()\n\t\t// Objects Signals initialisations\n\t\tsignalsPropHandler()\n\t\t/* Fill control with images */\n\t\tassignImages()\n\t\t// Set Window Properties\n\t\tif center {\n\t\t\tobj.MainWindow.SetPosition(gtk.WIN_POS_CENTER)\n\t\t}\n\t\tobj.MainWindow.SetTitle(winTitle)\n\t\tobj.MainWindow.SetDefaultSize(width, height)\n\t\tobj.MainWindow.Connect(\"delete-event\", windowDestroy)\n\t\t// Start main application ...\n\t\tmainApplication()\n\t\t//\tStart Gui loop\n\t\tobj.MainWindow.ShowAll()\n\t\tgtk.Main()\n\t} else {\n\t\tlog.Fatal(\"Builder initialisation error.\")\n\t}\n}", "func (t *Target) Main(body usm.Block) {\n\tt.WriteStatement(\"func main() {\\n\")\n\tt.WriteStatement(\"\\tvar r = new(Runtime)\\n\")\n\tt.Indent(body)\n\tt.WriteStatement(\"}\\n\")\n}", "func returnGoMainConfigurationSection(hasDB bool, serviceArray []string) (string, error) {\n\ttopString := fmt.Sprintf(\"func main() {\\n\\n\") +\n\t\tmodels.TopCommentBlock +\n\t\tfmt.Sprintf(\"\\n/\tConfiguration\\n\") +\n\t\tmodels.BottomCommentBlock +\n\t\tfmt.Sprintf(\"\\n\\n\t// load application configuration\\n\") +\n\t\tfmt.Sprintf(\"\tcfg := LoadConfig()\\n\\n\") +\n\t\tfmt.Sprintf(\"\t// default application port\\n\") +\n\t\tfmt.Sprintf(\"\tport := cfg.Port\\n\\n\") +\n\t\tfmt.Sprintf(\"\t// set db config to pass to service intialization\\n\") +\n\t\tfmt.Sprintf(\"\tdbCfg := cfg.Database\\n\\n\")\n\n\tserviceDeclarationString := fmt.Sprintf(\"\tsrvcs, err := services.NewServices(\\n\")\n\tif hasDB {\n\t\tserviceDeclarationString += fmt.Sprintf(\"\tservices.WithPostgres(dbCfg.Dialect(), dbCfg.Connection()),\\n\")\n\t}\n\tfor _, v := range serviceArray {\n\t\tserviceDeclarationString += fmt.Sprintf(\"\t\tservices.With%s(),\\n\", strings.Title(v))\n\t}\n\tserviceDeclarationString += fmt.Sprintf(\"\t)\\n\") +\n\t\tfmt.Sprintf(\"\tif err != nil {\\n\") +\n\t\tfmt.Sprintf(\"\t\t// services couldnt be made, should probably panic?\\n\") +\n\t\tfmt.Sprintf(\"\t\t// something here\\n\") +\n\t\tfmt.Sprintf(\"\t\tlog.Println(err)\\n\") +\n\t\tfmt.Sprintf(\"\t\treturn\\n\t}\\n\")\n\tif hasDB {\n\t\tserviceDeclarationString += fmt.Sprintf(\"\tdefer srvcs.Close()\\n\") +\n\t\t\tfmt.Sprintf(\"\t//run migrates\\n\") +\n\t\t\tfmt.Sprintf(\"\terr = srvcs.MigrateDBUP()\\n\") +\n\t\t\tfmt.Sprintf(\"\tif err != nil {\\n\") +\n\t\t\tfmt.Sprintf(\"\t\t// migrations couldn't happen\\n\") +\n\t\t\tfmt.Sprintf(\"\t\tlog.Println(err)\\n\t}\\n\\n\")\n\t}\n\n\treturn topString + serviceDeclarationString, nil\n}", "func NewMainView(graph *models.SystemGraph, g *gocui.Gui) (*MainView, error) {\n\tmv := &MainView{\n\t\tgraph: graph,\n\t\tshow: map[string]bool{},\n\t\tsubsystem: models.RootSystem,\n\t}\n\tfor _, comp := range graph.Components(mv.subsystem) {\n\t\tmv.show[comp.Kind] = false\n\t}\n\tmv.show[\"struct\"] = true\n\treturn mv, nil\n}", "func returnGoMainRoutesSection(hasDB bool, routeHandlerArray []string) (string, error) {\n\ttopString := \"\"\n\tfor _, v := range routeHandlerArray {\n\t\ttopString += models.TopCommentBlock +\n\t\t\tfmt.Sprintf(\"\\n/\t%s routes\\n\", strings.Title(v)) +\n\t\t\tmodels.BottomCommentBlock +\n\t\t\tfmt.Sprintf(\"\\n\\n\") +\n\t\t\tfmt.Sprintf(\"\t// r.HandleFunc(\\\"/route-path\\\", routeHandler.routeMethod).Methods(\\\"GET\\\")\\n\\n\")\n\t}\n\n\treturn topString, nil\n}", "func SetMainFile(newFile string) {\n\tmainConfigFile = newFile\n}", "func Main(m rv.RenderModel) {\n\tmain(m)\n}", "func Main(use string, options ...RootCommandOption) {\n\tappcmd.Main(context.Background(), newRootCommand(use, options...), version)\n}", "func (c *Config) Main(ctx context.Context, opts ...ExecOption) ([]proto.Message, error) {\n\tparsedOpts := &execOptions{\n\t\tvars: &starlark.Dict{},\n\t\tfuncName: \"main\",\n\t}\n\tfor _, opt := range opts {\n\t\topt.applyExec(parsedOpts)\n\t}\n\tmainVal, ok := c.locals[parsedOpts.funcName]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"no %q function found in %q\", parsedOpts.funcName, c.filename)\n\t}\n\tmain, ok := mainVal.(starlark.Callable)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%q must be a function (got a %s)\", parsedOpts.funcName, mainVal.Type())\n\t}\n\n\tthread := &starlark.Thread{\n\t\tPrint: skyPrint,\n\t}\n\tthread.SetLocal(\"context\", ctx)\n\tmainCtx := &starlarkstruct.Module{\n\t\tName: \"skycfg_ctx\",\n\t\tMembers: starlark.StringDict(map[string]starlark.Value{\n\t\t\t\"vars\": parsedOpts.vars,\n\t\t}),\n\t}\n\targs := starlark.Tuple([]starlark.Value{mainCtx})\n\tmainVal, err := starlark.Call(thread, main, args, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmainList, ok := mainVal.(*starlark.List)\n\tif !ok {\n\t\tif _, isNone := mainVal.(starlark.NoneType); isNone {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, fmt.Errorf(\"%q didn't return a list (got a %s)\", parsedOpts.funcName, mainVal.Type())\n\t}\n\tvar msgs []proto.Message\n\tfor ii := 0; ii < mainList.Len(); ii++ {\n\t\tmaybeMsg := mainList.Index(ii)\n\t\t// Only flatten but not flatten deep. This will flatten out, in order, lists within main list and append the\n\t\t// message into msgs\n\t\tif maybeMsgList, ok := maybeMsg.(*starlark.List); parsedOpts.flattenLists && ok {\n\t\t\tfor iii := 0; iii < maybeMsgList.Len(); iii++ {\n\t\t\t\tmaybeNestedMsg := maybeMsgList.Index(iii)\n\t\t\t\tmsg, ok := AsProtoMessage(maybeNestedMsg)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"%q returned something that's not a protobuf (a %s) within a nested list\", parsedOpts.funcName, maybeNestedMsg.Type())\n\t\t\t\t}\n\t\t\t\tmsgs = append(msgs, msg)\n\t\t\t}\n\t\t} else {\n\t\t\tmsg, ok := AsProtoMessage(maybeMsg)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"%q returned something that's not a protobuf (a %s)\", parsedOpts.funcName, maybeMsg.Type())\n\t\t\t}\n\t\t\tmsgs = append(msgs, msg)\n\t\t}\n\t}\n\treturn msgs, nil\n}", "func NewSection(title string, index int) *Section {\n\treturn &Section{\n\t\tTitle: title,\n\t\tIndex: index,\n\t\tMaxExits: pickMaxExit(),\n\t}\n}", "func (b *PhotosGetMarketUploadServerBuilder) MainPhoto(v bool) *PhotosGetMarketUploadServerBuilder {\n\tb.Params[\"main_photo\"] = v\n\treturn b\n}", "func (o *LinkRouteTable) HasMain() bool {\n\tif o != nil && o.Main != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func RunMain(cmd *cobra.Command, args []string) {\n\tcmd.Help()\n}", "func (app *DockApp) Main() {\n\tapp.win.Map()\n\txevent.Main(app.x)\n}", "func NewSection() *Section {\n\treturn &Section{\n\t\tParams: make(Params, 0),\n\t}\n}", "func Main(ctx context.Context, cancelFunc func(), title string, showMainWindow bool) error {\n\tlog.WithFields(log.Fields{\"title\": title, \"showMainWindow\": showMainWindow}).Info(\"Initializing GUI.\")\n\t// Note: ui.Main() calls any functions queued with ui.QueueMain() before the one we provide via parameter.\n\treturn ui.Main(func() {\n\t\twindowTitle = title\n\t\twindow = ui.NewWindow(windowTitle, 600, 50, false)\n\t\tapplyIconToWindow(window.Handle())\n\t\tapplyWindowStyle(window.Handle())\n\n\t\twindow.OnClosing(func(*ui.Window) bool {\n\t\t\tlog.Info(\"User tries to close the window.\")\n\t\t\tcancelFunc()\n\t\t\treturn false\n\t\t})\n\n\t\tpanelDownloadStatus = makeContent()\n\t\twindow.SetChild(panelDownloadStatus)\n\t\twindow.SetMargined(true)\n\n\t\tui.OnShouldQuit(func() bool {\n\t\t\tlog.Info(\"OnShouldQuit().\")\n\t\t\tcancelFunc()\n\t\t\treturn false\n\t\t})\n\n\t\tif showMainWindow {\n\t\t\tcenterWindow(window.Handle())\n\t\t\twindow.Show()\n\t\t\tcenterWindow(window.Handle())\n\t\t}\n\n\t\tgo updateProgressPeriodically(ctx)\n\n\t\tguiInitWaitGroup.Done()\n\t})\n}", "func (c *ExampleController) Main(ctx *app.MainExampleContext) error {\n\t// ExampleController_Main: start_implement\n\n\t// Put your logic here\n\n\t// ExampleController_Main: end_implement\n\tres := &app.Messagetype{}\n\treturn ctx.OK(res)\n}", "func (ini *INI) AddSection(name string) *INISection {\n\tsec := &INISection{\n\t\tFields: make(map[string]*INIField),\n\t}\n\tini.Sections[name] = sec\n\tini.Order = append(ini.Order, name)\n\treturn sec\n}", "func Main() error {\n\tapp, err := New(context.Background())\n\tif err != nil {\n\t\treturn skerr.Wrap(err)\n\t}\n\n\treturn app.Run()\n}", "func Main() {\n\tfullCmd := kingpin.MustParse(app.Parse(os.Args[1:])) // 解析用户命令行\n\n\t// \"version\" command\n\tif fullCmd == version.FullCommand() {\n\t\tfmt.Println(metadata.GetVersionInfo())\n\t\treturn\n\t}\n\n\tconf, err := localconfig.Load() // 记载orderer配置文件\n\tif err != nil {\n\t\tlogger.Error(\"failed to parse config: \", nil)\n\t\tos.Exit(1)\n\t}\n\tinitializeLogging()\n\n\tprettyPrintStruct(conf)\n}", "func NewMain() *Main {\n\tpath, err := ioutil.TempDir(\"\", \"pilosa-\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tm := &Main{Command: server.NewCommand(os.Stdin, os.Stdout, os.Stderr)}\n\tm.Config.DataDir = path\n\tm.Config.Host = \"localhost:0\"\n\tm.Command.Stdin = &m.Stdin\n\tm.Command.Stdout = &m.Stdout\n\tm.Command.Stderr = &m.Stderr\n\n\tif testing.Verbose() {\n\t\tm.Command.Stdout = io.MultiWriter(os.Stdout, m.Command.Stdout)\n\t\tm.Command.Stderr = io.MultiWriter(os.Stderr, m.Command.Stderr)\n\t}\n\n\treturn m\n}", "func Main(name string) {\n\tappcmd.Main(context.Background(), NewRootCommand(name))\n}", "func (self *CGenerator) genMainFunc(parent *Gen, gram Gram) {\n\tfuncGen := parent.NewGram(C_FUNC, \"main\", nil)\n\tparent.children.PushBack(funcGen)\n\n\ttypeGen := parent.NewGram(C_TYPE, \"\", nil)\n\ttypeGen.PushToken(\"int\")\n\tfuncGen.children.PushBack(typeGen)\n\n\tfuncGen.AddSpace().PushToken(\"main\").PushToken(\"(int argc, char ** argv)\")\n\tfuncGen.AddSpace().PushToken(\"{ return 0; }\")\n\tfuncGen.AddLine().AddLine()\n\n\tself.genLanguageDetails(parent)\n}", "func (app *appImpl) GoRunOnMain(f func()) {\n\tgo func() {\n\t\tapp.mainQueue <- funcRun{f: f, done: nil}\n\t}()\n}", "func (o Chapter) AddSection(i int, name string, apiVersion *string) (outputs.Section, error) {\n\terr := o.hugo.addSection(o.part.name, o.name, name)\n\tif err != nil {\n\t\treturn Section{}, err\n\t}\n\treturn Section{\n\t\thugo: o.hugo,\n\t\tpart: o.part,\n\t\tchapter: &o,\n\t}, nil\n}", "func handleMain(c context.Context, w http.ResponseWriter, r *http.Request) error {\n\thdr, err := commonHeader(c, r, w, \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\taccessLevel := accessLevel(c, r)\n\tfilter, err := MakeBugFilter(r)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%w: failed to parse URL parameters\", ErrClientBadRequest)\n\t}\n\tmanagers, err := loadManagers(c, accessLevel, hdr.Namespace, filter)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgroups, err := fetchNamespaceBugs(c, accessLevel, hdr.Namespace, filter)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, group := range groups {\n\t\tif config.Namespaces[hdr.Namespace].DisplayDiscussions {\n\t\t\tgroup.DispDiscuss = true\n\t\t} else {\n\t\t\tgroup.DispLastAct = true\n\t\t}\n\t}\n\tdata := &uiMainPage{\n\t\tHeader: hdr,\n\t\tDecommissioned: config.Namespaces[hdr.Namespace].Decommissioned,\n\t\tNow: timeNow(c),\n\t\tGroups: groups,\n\t\tManagers: makeManagerList(managers, hdr.Namespace),\n\t\tBugFilter: makeUIBugFilter(c, filter),\n\t}\n\n\tif isJSONRequested(r) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\treturn writeJSONVersionOf(w, data)\n\t}\n\n\treturn serveTemplate(w, \"main.html\", data)\n}", "func TestMain(m *testing.M) {\n\tsetup.WrapTestMain(m, config)\n}", "func NewMain() *Main {\n\treturn &Main{\n\t\tStdin: os.Stdin,\n\t\tStdout: os.Stdout,\n\t\tStderr: os.Stderr,\n\t}\n}", "func (d *Display) AddSection(header string) *Section {\n\td.mutex.Lock()\n\tdefer d.mutex.Unlock()\n\n\ts := newSection(header, func(handler DisplayUpdateHandler) {\n\t\td.gui.Update(func(g *gocui.Gui) (err error) {\n\t\t\tv, err := g.View(header)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tv.Clear()\n\t\t\thandler(v)\n\t\t\treturn\n\t\t})\n\t})\n\n\td.sections = append(d.sections, s)\n\tsort.Slice(d.sections, func(i int, j int) bool {\n\t\treturn d.sections[i].Header < d.sections[j].Header\n\t})\n\n\td.gui.Update(d.Layout)\n\treturn s\n}", "func (ref *UIElement) IsMain() bool {\n\tret, _ := ref.BoolAttr(MainAttribute)\n\treturn ret\n}", "func (s *BaseAspidaListener) EnterMain(ctx *MainContext) {}", "func usageMain(w io.Writer, set *flag.FlagSet) error {\n\toutputPara(w, usageLineLength, 0, usageShort)\n\toutputPara(w, usageLineLength, 0, usageMainPara)\n\n\tcmdNames := commands.Names()\n\n\tfieldWidth := 0\n\tfor _, name := range cmdNames {\n\t\tif n := len(name); n+4 > fieldWidth {\n\t\t\tfieldWidth = n + 4\n\t\t}\n\t}\n\n\tfmt.Fprintln(w, \"Commands:\")\n\tfor _, name := range cmdNames {\n\t\tcmd, _ := commands[name]\n\t\tfmt.Fprintf(w, \"%s%-*s %s\\n\", strings.Repeat(\" \", usageIndent), fieldWidth, name, cmd.shortDesc)\n\t}\n\tfmt.Fprintln(w)\n\toutputPara(w, usageLineLength, 0, usageCommandPara)\n\n\tif !isFlagPassed(set, commonFlag) {\n\t\toutputPara(w, usageLineLength, 0, usageCommonPara)\n\n\t\treturn nil\n\t}\n\n\tfmt.Fprintln(w, \"Configuration file:\")\n\toutputPara(w, usageLineLength, usageIndent, usageConfigIntroPara)\n\toutputPara(w, usageLineLength, usageIndent, usageConfigLocationPara)\n\toutputPara(w, usageLineLength, usageIndent, usageConfigKeysPara)\n\n\tfmt.Fprintln(w, \"Explicit and implicit anchors:\")\n\toutputPara(w, usageLineLength, usageIndent, usageAnchorsIntroPara)\n\toutputPara(w, usageLineLength, usageIndent, usageAnchorsFormatPara)\n\toutputPara(w, usageLineLength, usageIndent, usageAnchorsInsecurePara)\n\n\tfmt.Fprintln(w, \"Additional path segment:\")\n\toutputPara(w, usageLineLength, usageIndent, usageAPSIntroPara)\n\n\tfmt.Fprintln(w, \"TLS client certificates:\")\n\toutputPara(w, usageLineLength, usageIndent, usageCertsIntroPara)\n\toutputPara(w, usageLineLength, usageIndent, usageCertsFormatPara)\n\toutputPara(w, usageLineLength, usageIndent, usageCertsKeyPara)\n\n\tfmt.Fprintln(w, \"Additional HTTP headers:\")\n\toutputPara(w, usageLineLength, usageIndent, usageHeadersPara)\n\toutputPara(w, usageLineLength, usageIndent*2, usageHeadersExample)\n\n\tfmt.Fprintln(w, \"HTTP Host header:\")\n\toutputPara(w, usageLineLength, usageIndent, usageHostHeaderPara)\n\n\tfmt.Fprintln(w, \"Request timeout:\")\n\toutputPara(w, usageLineLength, usageIndent, usageTimeoutPara)\n\n\treturn nil\n}", "func SharedMain() *Main {\n\tonce.Do(func() {\n\t\tinstance = &Main{\n\t\t\tCallback: map[string]EventCallback{},\n\t\t}\n\t})\n\n\treturn instance\n}", "func (b CreateIndexBuilder) RunWith(runner squirrel.BaseRunner) CreateIndexBuilder {\n\treturn builder.Set(b, \"RunWith\", runner).(CreateIndexBuilder)\n}", "func Main(args map[string]interface{}) map[string]interface{} {\n\tname, ok := args[\"name\"].(string)\n\tif !ok {\n\t\tname = \"world\"\n\t}\n\treturn map[string]interface{}{\n\t\t\"body\": \"Go: Hello \" + name,\n\t}\n}", "func createMain() error {\n\tpath := \"./\" + Name + \"/main.go\"\n\n\t// Create the main.go file content\n\tmain := fmt.Sprintf(`package main\n\nimport (\n\t\"%s/cmd/server\"\n\t\"%s/pkg/logs\"\n)\n\t\nfunc main() {\n\tlogs.StartLogger()\n\t\t\n\tserver := server.NewServer()\n\n\tserver.StartServer()\n}\n\t`, Repo, Repo)\n\n\t// Create the main.go file\n\treturn util.CreateFile(path, main)\n}", "func main_init()", "func returnGoMainTopSection(projectName string) (string, error) {\n\ttopString := fmt.Sprintf(\"package main\\n\\n\") +\n\t\tfmt.Sprintf(\"import (\\n\") +\n\t\tfmt.Sprintf(\"\trouteHandlers \\\"%s/pkg/route-handlers\\\"\\n\", projectName) +\n\t\tfmt.Sprintf(\"\tservices \\\"%s/pkg/sub-services\\\"\\n\\n\", projectName) +\n\t\tfmt.Sprintf(\"\t\\\"fmt\\\"\\n\") +\n\t\tfmt.Sprintf(\"\t\\\"log\\\"\\n\") +\n\t\tfmt.Sprintf(\"\t\\\"net/http\\\"\\n\") +\n\t\tfmt.Sprintf(\"\t\\\"time\\\"\\n\\n\") +\n\t\tfmt.Sprintf(\"\t\\\"github.com/gorilla/handlers\\\"\\n\") +\n\t\tfmt.Sprintf(\"\t\\\"github.com/gorilla/mux\\\"\\n)\\n\\n\")\n\n\tinitString := fmt.Sprintf(\"func init() {\\n\") +\n\t\tfmt.Sprintf(\"\t// run the secrets, hidden with the .gitignore\\n\") +\n\t\tfmt.Sprintf(\"\t// basically just sets the ENV vars for:\\n\") +\n\t\tfmt.Sprintf(\"\t// DBHOST, DBNAME, DBUSER, DBPASS, PORT, ENVIRONMENT\\n\") +\n\t\tfmt.Sprintf(\"\tsetTheSecrets()\\n}\\n\\n\")\n\n\treturn topString + initString, nil\n}", "func Main() {\n\tC.gtk_main()\n}", "func Main() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: rootcmd.TopLevelCommand,\n\t\tShort: \"commands for stashing results\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\terr := cmd.Help()\n\t\t\tif err != nil {\n\t\t\t\tlog.Logger().Errorf(err.Error())\n\t\t\t}\n\t\t},\n\t}\n\n\tcmd.AddCommand(cobras.SplitCommand(initcmd.NewCmdMinkInit()))\n\tcmd.AddCommand(cobras.SplitCommand(resolve.NewCmdMinkResolve()))\n\treturn cmd\n}", "func returnGoMainHealthSection() (string, error) {\n\ttopString := models.TopCommentBlock +\n\t\tfmt.Sprintf(\"\\n/\tHealth Check & Container routes\\n\") +\n\t\tmodels.BottomCommentBlock +\n\t\tfmt.Sprintf(\"\\n\\n\tr.HandleFunc(\\\"/health\\\", func(rw http.ResponseWriter, r *http.Request) { rw.WriteHeader(http.StatusOK) })\\n\\n\")\n\n\treturn topString, nil\n}", "func returnGoMainServerSection() (string, error) {\n\ttopString := models.TopCommentBlock +\n\t\tfmt.Sprintf(\"\\n/\tServer\\n\") +\n\t\tmodels.BottomCommentBlock +\n\t\tfmt.Sprintf(\"\\n\\n\tvar srv *http.Server\\n\\n\") +\n\t\tfmt.Sprintf(\"\t// establishes the server contraints and information\\n\") +\n\t\tfmt.Sprintf(\"\tsrv = &http.Server{\\n\") +\n\t\tfmt.Sprintf(\"\t\tHandler: handlers.CORS(handlers.AllowedHeaders([]string{\\\"origin\\\", \\\"X-Requested-With\\\", \\\"Content-Type\\\", \\\"Authorization\\\"}), handlers.AllowedMethods([]string{\\\"GET\\\", \\\"POST\\\", \\\"PUT\\\", \\\"HEAD\\\", \\\"OPTIONS\\\"}),\\n\") +\n\t\tfmt.Sprintf(\"\t\t\thandlers.AllowedOrigins([]string{\\\"*\\\"}),\\n\") +\n\t\tfmt.Sprintf(\"\t\t\thandlers.AllowCredentials())(r),\\n\") +\n\t\tfmt.Sprintf(\"\t\tAddr: fmt.Sprintf(\\\":%%s\\\", port),\\n\") +\n\t\tfmt.Sprintf(\"\t\tWriteTimeout: 15 * time.Minute,\\n\") +\n\t\tfmt.Sprintf(\"\t\tReadTimeout: 15 * time.Minute,\\n\t}\\n\\n\") +\n\t\tfmt.Sprintf(\"\t// runs the server\\n\") +\n\t\tfmt.Sprintf(\"\tlog.Println(\\\"Running local on port: \\\", port)\\n\") +\n\t\tfmt.Sprintf(\"\tlog.Fatal(srv.ListenAndServe())\\n}\")\n\n\treturn topString, nil\n}", "func NewMain() *Main {\n\t// Create a temporary data directory.\n\tdataDir, err := ioutil.TempDir(\"\", \"flynn-redis-\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Create test wrapper with random port and temporary data directory.\n\tm := &Main{\n\t\tMain: main.NewMain(),\n\t\tDiscoverdClient: NewDiscoverdClient(),\n\t}\n\tm.Main.Addr = \"127.0.0.1:0\"\n\tm.Main.DataDir = dataDir\n\tm.Main.DiscoverdClient = m.DiscoverdClient\n\n\tm.Main.Stdin = &m.Stdin\n\tm.Main.Stdout = &m.Stdout\n\tm.Main.Stderr = &m.Stderr\n\n\tif testing.Verbose() {\n\t\tm.Main.Stdout = io.MultiWriter(os.Stdout, m.Main.Stdout)\n\t\tm.Main.Stderr = io.MultiWriter(os.Stderr, m.Main.Stderr)\n\t}\n\n\treturn m\n}", "func (s *BaseAspidaListener) EnterDescriptionMain(ctx *DescriptionMainContext) {}", "func (s *BaseAspidaListener) EnterMain_content(ctx *Main_contentContext) {}", "func (cfg *Config) Main(c context.Context, argv []string, env environ.Env) int {\n\tif len(argv) == 0 {\n\t\tpanic(\"zero-length argument slice\")\n\t}\n\n\t// Implementation of \"checkWrapper\": if CheckWrapperENV is set, we immediately\n\t// exit with a non-zero value.\n\tif wrapperCheck(env) {\n\t\treturn 1\n\t}\n\n\tdefaultLogLevel := logging.Error\n\tif env.Get(LogTraceENV) != \"\" {\n\t\tdefaultLogLevel = logging.Debug\n\t}\n\n\tc = gologger.StdConfig.Use(c)\n\tc = logging.SetLevel(c, defaultLogLevel)\n\n\ta := application{\n\t\tConfig: cfg,\n\t\topts: vpython.Options{\n\t\t\tEnvConfig: venv.Config{\n\t\t\t\tBaseDir: \"\", // (Determined below).\n\t\t\t\tMaxHashLen: 6,\n\t\t\t\tSetupEnv: env,\n\t\t\t\tPackageMap: cfg.VENVPackageMap,\n\t\t\t\tPython: cfg.InterpreterPaths,\n\t\t\t\tPruneThreshold: cfg.PruneThreshold,\n\t\t\t\tMaxPrunesPerSweep: cfg.MaxPrunesPerSweep,\n\t\t\t\tLoader: cfg.PackageLoader,\n\t\t\t},\n\t\t\tBaseWheels: cfg.BaseWheels,\n\t\t\tWaitForEnv: true,\n\t\t\tSpecLoader: cfg.SpecLoader,\n\t\t\tEnviron: env,\n\t\t\tDefaultSpec: cfg.DefaultSpec,\n\t\t\tVpythonOptIn: cfg.VpythonOptIn,\n\t\t},\n\t\tlogConfig: logging.Config{\n\t\t\tLevel: defaultLogLevel,\n\t\t},\n\t}\n\n\treturn run(c, func(c context.Context) error {\n\t\treturn a.mainImpl(c, argv[0], argv[1:])\n\t})\n}", "func Main(rootCommand *Command, version string) {\n\tos.Exit(Run(rootCommand, version, internal.NewOSRunEnv()))\n}", "func main() {\n\ttheApp = app.NewApp()\n\tdefer theApp.Close()\n\n\ttheApp.Open()\n\n\ttheApp.SetFont(\"Roboto-Bold.ttf\", 24)\n\ttheApp.Configure()\n\n\ttheApp.Run()\n}", "func (m *Machine) SetMainCollective(collective string) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tm.mainCollective = collective\n}", "func newSection(tm *TimedMap, sec int) *section {\n\treturn &section{\n\t\ttm: tm,\n\t\tsec: sec,\n\t}\n}", "func Main(f func(oswin.App)) {\n\tlog.Println(\"in Main\")\n\tgi.DialogsSepWindow = false\n\tmainCallback = f\n\ttheApp.initVk()\n\toswin.TheApp = theApp\n\tgo func() {\n\t\tmainCallback(theApp)\n\t\tlog.Println(\"main callback done\")\n\t\ttheApp.stopMain()\n\t}()\n\ttheApp.eventLoop()\n\tlog.Println(\"main loop done\")\n}", "func NewSection(name string) *Section {\n\treturn &Section{Name: name, Options: []*OptionValue{}}\n}", "func (h *Handler) Main() http.Handler {\n\tr := chi.NewRouter()\n\tr.Get(\"/\", h.GetRoot())\n\tr.Get(\"/favicon.ico\", h.GetFavicon())\n\tr.Get(\"/_all_dbs\", h.GetAllDBs())\n\tr.Get(\"/{db}\", h.GetDB())\n\tr.Put(\"/{db}\", h.PutDB())\n\tr.Head(\"/{db}\", h.HeadDB())\n\tr.Post(\"/{db}/_ensure_full_commit\", h.Flush())\n\tr.Get(\"/_session\", h.GetSession())\n\treturn r\n}", "func (ini INI) SectionUpdate(sectionName string, data map[string]string) {\n\tif _, exist := ini[sectionName]; !exist {\n\t\tini[sectionName] = make(kvMap)\n\t}\n\tfor k, v := range data {\n\t\tini[sectionName][k] = v\n\t}\n}", "func (gn *Gen) ConfigGui() *gi.Window {\n\twidth := 1600\n\theight := 1200\n\n\tgi.SetAppName(\"Gen\")\n\tgi.SetAppAbout(`Gen concatenated strings of syllables`)\n\n\twin := gi.NewMainWindow(\"one\", \"Gen ...\", width, height)\n\n\tvp := win.WinViewport2D()\n\tupdt := vp.UpdateStart()\n\n\tmfr := win.SetMainFrame()\n\n\ttbar := gi.AddNewToolBar(mfr, \"tbar\")\n\ttbar.SetStretchMaxWidth()\n\t// vi.ToolBar = tbar\n\n\tsplit := gi.AddNewSplitView(mfr, \"split\")\n\tsplit.Dim = gi.X\n\tsplit.SetStretchMaxWidth()\n\tsplit.SetStretchMaxHeight()\n\n\tsv := giv.AddNewStructView(split, \"sv\")\n\tsv.SetStruct(gn)\n\tgn.StructView = sv\n\n\t// tv := gi.AddNewTabView(split, \"tv\")\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Gen cat string\", Icon: \"new\", Tooltip: \"Generate a new initial random seed to get different results. By default, Init re-establishes the same initial seed every time.\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.CatNoRepeat(gn.syls1)\n\t\t})\n\n\tvp.UpdateEndNoSig(updt)\n\n\t// main menu\n\tappnm := gi.AppName()\n\tmmen := win.MainMenu\n\tmmen.ConfigMenus([]string{appnm, \"File\", \"Edit\", \"Window\"})\n\n\tamen := win.MainMenu.ChildByName(appnm, 0).(*gi.Action)\n\tamen.Menu.AddAppMenu(win)\n\n\temen := win.MainMenu.ChildByName(\"Edit\", 1).(*gi.Action)\n\temen.Menu.AddCopyCutPaste(win)\n\n\tvp.UpdateEndNoSig(updt)\n\n\twin.MainMenuUpdated()\n\treturn win\n}", "func LoadMainConfiguration() (map[string]map[string]string, error) {\n\n\t// Decode and read file containing Main API information\n\tif err := ini.DecodeFile(mainConfigFile, &confMain); err != nil {\n\t\tlgr.Error.Println(err)\n\t\treturn nil, err\n\t}\n\treturn confMain, nil\n}", "func main() {\n\tgo func() {\n\t\tw := app.NewWindow(\n\t\t\tapp.Title(\"Gopher-Garden\"),\n\t\t\tapp.Size(unit.Dp(ui.WidthPx+500), unit.Dp(ui.HeightPx)))\n\t\tu := ui.NewUi(w)\n\t\tif err := u.Loop(); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tos.Exit(0)\n\t}()\n\tapp.Main()\n}", "func Section(attrs []htmlgo.Attribute, children ...HTML) HTML {\n\treturn &htmlgo.Tree{Tag: \"section\", Attributes: attrs, Children: children}\n}", "func mainConfig(ctx *cli.Context) error {\n\tcli.ShowCommandHelp(ctx, ctx.Args().First())\n\treturn nil\n}", "func InitMain() func() {\n\tif calledInitMain {\n\t\tpanic(\"v23test: already called v23test.TestMain or v23test.InitMain\")\n\t}\n\tcalledInitMain = true\n\tgosh.InitMain()\n\tvar err error\n\tbinDir, err = os.MkdirTemp(\"\", \"bin-\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn func() {\n\t\tos.RemoveAll(binDir)\n\t}\n}", "func createMainConfig(file *string, paths *string, basename *string) *viper.Viper {\n\tconfig := viper.New()\n\n\tconfig.SetEnvPrefix(utils.ConfigPrefix) // Env vars start with 'SLA_'\n\tconfig.AutomaticEnv()\n\tconfig.SetDefault(utils.CheckPeriodPropertyName, utils.DefaultCheckPeriod)\n\tconfig.SetDefault(utils.RepositoryTypePropertyName, utils.DefaultRepositoryType)\n\tconfig.SetDefault(utils.ExternalIDsPropertyName, utils.DefaultExternalIDs)\n\n\tif *file != \"\" {\n\t\tconfig.SetConfigFile(*file)\n\t} else {\n\t\tconfig.SetConfigName(*basename)\n\t\tfor _, path := range strings.Split(*paths, \":\") {\n\t\t\tconfig.AddConfigPath(path)\n\t\t}\n\t}\n\n\terrConfig := config.ReadInConfig()\n\tif errConfig != nil {\n\t\tlog.Println(\"Can't find configuration file: \" + errConfig.Error())\n\t\tlog.Println(\"Using defaults\")\n\t}\n\treturn config\n}", "func Main(p Params, args []string) int {\n\treturn subcommands.Run(application(p), fixflagpos.FixSubcommands(args))\n}", "func (s *Server) generateMain() error {\n\tfilename := path.Join(s.TargetDir, \"main.lua\")\n\treturn commons.GenerateFile(s, \"./templates/tarantool/server_main.tmpl\", \"server_main\", filename, true)\n}", "func TestMain(m *testing.M) {\n\tkubeconfig := flag.String(\n\t\t\"kubeconfig\",\n\t\t\"\",\n\t\t\"path to kubeconfig\",\n\t)\n\tflag.Parse()\n\n\tvar err error\n\tsuite, err = kubetest.NewSuiteFromKubeconfig(*kubeconfig)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tos.Exit(m.Run())\n}", "func TestMain(m *testing.M) {\n\ttestsuite.RevelTestHelper(m, \"dev\", run.Run)\n}", "func AddInsideAppBlock(expressions ...string) error {\n\tsrc, err := ioutil.ReadFile(\"actions/app.go\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfset := token.NewFileSet()\n\tf, err := parser.ParseFile(fset, \"actions/app.go\", string(src), 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrcContent := string(src)\n\tfileLines := strings.Split(srcContent, \"\\n\")\n\n\tend := findClosingRouteBlockEnd(f, fset, fileLines)\n\tif end < 0 {\n\t\treturn errors.New(\"could not find desired block on the app.go file\")\n\t}\n\n\tel := fileLines[end:]\n\tsl := []string{}\n\tsf := []string{}\n\tfor _, l := range fileLines[:end] {\n\t\t// if there's a app.ServeFiles(\"/\", foo) line it needs to be the last added to the router\n\t\tif strings.Contains(l, \"ServeFiles(\\\"/\\\"\") {\n\t\t\tsf = append(sf, l)\n\t\t\tcontinue\n\t\t}\n\t\tsl = append(sl, l)\n\t}\n\n\tfor i := 0; i < len(expressions); i++ {\n\t\texpressions[i] = fmt.Sprintf(\"\\t\\t%s\", expressions[i])\n\t}\n\n\tel = append(sf, el...)\n\tfileLines = append(sl, append(expressions, el...)...)\n\n\tfileContent := strings.Join(fileLines, \"\\n\")\n\terr = ioutil.WriteFile(\"actions/app.go\", []byte(fileContent), 0755)\n\treturn err\n}", "func main() {\n\t//Clears screen for better readability\n\tCallClear()\n\t//Calls function to start program\n\tmenu()\n}", "func WithRun() Option {\n\treturn func(o *Options) {\n\t\to.run = true\n\t}\n}", "func Main(handler Handler) {\n\tos.Exit(Run(handler, internal.NewOSRunEnv()))\n}", "func ReadMain(r io.Reader) (Main, error) {\n\tcfg := MakeDefault()\n\n\t_, err := toml.DecodeReader(r, &cfg)\n\tif err != nil {\n\t\treturn cfg, errors.Wrap(err, \"parsing error\")\n\t}\n\tif cfg.PprofPort == cfg.PromPort {\n\t\treturn cfg, errors.New(\"PromPort and PprofPort can't have the same value\")\n\t}\n\treturn cfg, nil\n}", "func (g *GenData) ReadJsonFileMain() error {\n\tvar err error\n\n\tif err = mainData.ReadJsonFileMain(sharedData.MainPath()); err != nil {\n\t\treturn errors.New(fmt.Sprintln(\"Error: Reading Main Json Input:\", sharedData.MainPath(), err))\n\t}\n\tg.TmplData.Main = mainData.MainJson()\n\n\treturn nil\n}", "func Section() UISection {\n\treturn &section{\n\t\tIclass: \"uk-section\",\n\t}\n}", "func (c *Compiler) funcDecl_main() *dst.FuncDecl {\n\treturn &dst.FuncDecl{\n\t\tName: &dst.Ident{Name: maine},\n\t\tType: &dst.FuncType{},\n\t\tBody: &dst.BlockStmt{\n\t\t\tList: []dst.Stmt{\n\t\t\t\tc.declStmt_underscore(),\n\t\t\t\tc.assignStmt_ctx(),\n\t\t\t\tc.assignStmt_resourceNames(),\n\t\t\t\tc.assignStmt_resourcesLen(),\n\t\t\t\tc.assignStmt_resources(),\n\t\t\t\tc.rangeStmt_resources(),\n\t\t\t\tc.assignStmt_pb(),\n\t\t\t\t&dst.ExprStmt{\n\t\t\t\t\tX: &dst.CallExpr{\n\t\t\t\t\t\tFun: &dst.Ident{Name: startCLIMethod},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (d *webData) mainPage(w http.ResponseWriter, r *http.Request) {\n\t//start a web page based on template\n\terr := d.tpl.ExecuteTemplate(w, \"mainCompletePage\", d)\n\tif err != nil {\n\t\tlog.Println(\"mainPage: template execution error = \", err)\n\t}\n}", "func (b CreateTableBuilder) RunWith(runner squirrel.BaseRunner) CreateTableBuilder {\n\treturn builder.Set(b, \"RunWith\", runner).(CreateTableBuilder)\n}", "func (gn *Gen) ConfigGui() *gi.Window {\n\twidth := 1600\n\theight := 1200\n\n\tgi.SetAppName(\"Gen\")\n\tgi.SetAppAbout(`Gen concatenated strings of syllables`)\n\n\twin := gi.NewMainWindow(\"one\", \"Gen ...\", width, height)\n\n\tvp := win.WinViewport2D()\n\tupdt := vp.UpdateStart()\n\n\tmfr := win.SetMainFrame()\n\n\ttbar := gi.AddNewToolBar(mfr, \"tbar\")\n\ttbar.SetStretchMaxWidth()\n\t// vi.ToolBar = tbar\n\n\tsplit := gi.AddNewSplitView(mfr, \"split\")\n\tsplit.Dim = gi.X\n\tsplit.SetStretchMaxWidth()\n\tsplit.SetStretchMaxHeight()\n\n\tsv := giv.AddNewStructView(split, \"sv\")\n\tsv.SetStruct(gn)\n\tgn.StructView = sv\n\n\t// tv := gi.AddNewTabView(split, \"tv\")\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Reset\", Icon: \"new\", Tooltip: \"\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.Reset()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Load Params\", Icon: \"new\", Tooltip: \"\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.LoadParams()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Gen Wavs\", Icon: \"new\", Tooltip: \"Generate the .wav files\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.GenWavs()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Split Wavs\", Icon: \"new\", Tooltip: \"\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.SplitWavs()\n\t\t})\n\n\tvp.UpdateEndNoSig(updt)\n\n\t// main menu\n\tappnm := gi.AppName()\n\tmmen := win.MainMenu\n\tmmen.ConfigMenus([]string{appnm, \"File\", \"Edit\", \"Window\"})\n\n\tamen := win.MainMenu.ChildByName(appnm, 0).(*gi.Action)\n\tamen.Menu.AddAppMenu(win)\n\n\temen := win.MainMenu.ChildByName(\"Edit\", 1).(*gi.Action)\n\temen.Menu.AddCopyCutPaste(win)\n\n\tvp.UpdateEndNoSig(updt)\n\n\twin.MainMenuUpdated()\n\treturn win\n}", "func main() {\n\tapplication.Application()\n}", "func (o *TenantWithOfferWeb) SetMainUserId(v string) {\n\to.MainUserId = &v\n}", "func RealMain(opts types.Options, d types.Deployer, tester types.Tester) error {\n\t// Now for the core kubetest2 logic:\n\t// - build\n\t// - cluster up\n\t// - test\n\t// - cluster down\n\t// TODO(bentheelder): write out structured metadata\n\t// TODO(bentheelder): signal handling & timeoutf\n\n\t// build if specified\n\tif opts.ShouldBuild() {\n\t\tbuild := d.GetBuilder()\n\t\tif build == nil {\n\t\t\tbuild = defaultBuild\n\t\t}\n\t\t// TODO(bentheelder): this should write out to JUnit\n\t\tif err := build(); err != nil {\n\t\t\t// we do not continue to up / test etc. if build fails\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// up a cluster\n\tif opts.ShouldUp() {\n\t\t// TODO(bentheelder): this should write out to JUnit\n\t\tif err := d.Up(); err != nil {\n\t\t\t// we do not continue to test if build fails\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// ensure tearing down the cluster happens last\n\tdefer func() {\n\t\tif opts.ShouldDown() {\n\t\t\t// TODO(bentheelder): this should write out to JUnit\n\t\t\td.Down()\n\t\t}\n\t}()\n\n\t// and finally test, if a test was specified\n\tif opts.ShouldTest() {\n\t\t// TODO(bentheelder): this should write out to JUnit\n\t\ttester.Test()\n\t}\n\n\treturn nil\n}" ]
[ "0.60540175", "0.5744275", "0.5715339", "0.556082", "0.5553542", "0.5511685", "0.5460612", "0.53178746", "0.52588576", "0.5224122", "0.51961803", "0.5177115", "0.5175806", "0.5088678", "0.50730175", "0.50573367", "0.5002134", "0.49979734", "0.49948007", "0.49303952", "0.49156192", "0.49093354", "0.4880979", "0.48360613", "0.4822858", "0.48151544", "0.4810388", "0.4802686", "0.4758777", "0.46800265", "0.4669844", "0.46672475", "0.46410456", "0.4637709", "0.46315652", "0.46261528", "0.46128607", "0.46067852", "0.4592003", "0.45748118", "0.4573297", "0.45711926", "0.45658347", "0.455719", "0.45511436", "0.45500663", "0.45436367", "0.450748", "0.44999674", "0.44951838", "0.44911996", "0.44828525", "0.44670233", "0.44473505", "0.44321266", "0.43986186", "0.43911633", "0.4376251", "0.43754625", "0.4369444", "0.43538174", "0.43519408", "0.43493327", "0.43433827", "0.4338429", "0.4333086", "0.43321353", "0.4322471", "0.43066028", "0.43014973", "0.4300208", "0.42999727", "0.42986903", "0.42982334", "0.4293842", "0.42911148", "0.42749602", "0.42739362", "0.42735276", "0.4271564", "0.42595166", "0.42593908", "0.4249367", "0.42391527", "0.422388", "0.42209825", "0.42201498", "0.4204916", "0.42002442", "0.4198125", "0.4185903", "0.418365", "0.4182566", "0.4176721", "0.4176253", "0.41725802", "0.4170645", "0.416645", "0.41633335", "0.41615546" ]
0.82291776
0
WithTest adds a testSection to the builder
func (app *applicationBuilder) WithTest(test TestSection) ApplicationBuilder { app.test = test return app }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func WithTestdata() Option {\n\treturn func(c *config) {\n\t\tc.testdata = true\n\t}\n}", "func (m *Main) AddTest(t *Test) {\n\tm.Tests = append(m.Tests, t)\n}", "func WithTestName(ctx context.Context, id string) context.Context {\n\treturn context.WithValue(ctx, testNameKey{}, id)\n}", "func AddGenesisTest(appPath, appName, modulePath, moduleName string, isIBC bool) (*genny.Generator, error) {\n\tvar (\n\t\tg = genny.New()\n\t\ttemplate = xgenny.NewEmbedWalker(fsGenesisTest, \"genesistest/\", appPath)\n\t)\n\n\tctx := plush.NewContext()\n\tctx.Set(\"moduleName\", moduleName)\n\tctx.Set(\"modulePath\", modulePath)\n\tctx.Set(\"appName\", appName)\n\tctx.Set(\"isIBC\", isIBC)\n\tctx.Set(\"title\", xstrings.Title)\n\n\tplushhelpers.ExtendPlushContext(ctx)\n\tg.Transformer(plushgen.Transformer(ctx))\n\tg.Transformer(genny.Replace(\"{{moduleName}}\", moduleName))\n\n\tif err := xgenny.Box(g, template); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn g, nil\n}", "func TestCreateSectionWithKey(T *testing.T) {\n\n\tvar db etcdDB\n\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, `{\"action\":\"set\",\"node\":{\"key\":\"/testDir\",\"value\":\"Hello\",\"modifiedIndex\":4,\"createdIndex\":4}}`)\n\t}))\n\tdefer ts.Close()\n\n\tconfig := ts.URL\n\n\tdb.Cfg = cli.Config{\n\t\tEndpoints: []string{config},\n\t\tTransport: cli.DefaultTransport,\n\t\t// set timeout per request to fail fast when the target endpoint is unavailable\n\t\tHeaderTimeoutPerRequest: time.Second,\n\t}\n\n\tdb.C, _ = cli.New(db.Cfg)\n\n\tdb.Kapi = cli.NewKeysAPI(db.C)\n\tdb.Ctx = context.Background()\n\n\terr := db.CreateSection(\"/testDir\")\n\n\tif err != nil {\n\t\tT.Fail()\n\t}\n}", "func WithTestAppName(testAppName string) Opt {\n\treturn func(f *Fortio) {\n\t\tf.testApp = testAppName\n\t}\n}", "func WithTestDatabase(t *testing.T, closure func(db *sql.DB)) {\n\n\tt.Helper()\n\n\t// new context derived from background\n\tctx := context.Background()\n\n\tdoOnce.Do(func() {\n\n\t\tt.Helper()\n\t\tinitializeTestDatabaseTemplate(ctx, t)\n\t})\n\n\ttestDatabase, err := client.GetTestDatabase(ctx, hash)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to obtain test database: %v\", err)\n\t}\n\n\tconnectionString := testDatabase.Config.ConnectionString()\n\n\tdb, err := sql.Open(\"postgres\", connectionString)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to setup test database for connectionString %q: %v\", connectionString, err)\n\t}\n\n\t// this database object is managed and should close automatically after running the test\n\tdefer db.Close()\n\n\tif err := db.PingContext(ctx); err != nil {\n\t\tt.Fatalf(\"Failed to ping test database for connectionString %q: %v\", connectionString, err)\n\t}\n\n\tt.Logf(\"WithTestDatabase: %q\", testDatabase.Config.Database)\n\n\tclosure(db)\n}", "func WithTesterImage(image string) Opt {\n\treturn func(f *Fortio) {\n\t\tf.testerImage = image\n\t}\n}", "func (b *BootstrapClient) WithTestGenericData() *BootstrapClient {\n\tgenericData, err := ioutil.ReadFile(\"../vault/testdata/genericdata.json\")\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Failed to read generic data from ../vault/testdata/genericdata.json Error: %v\", err))\n\t}\n\tb.BootstrapConfig.GenericData = string(genericData)\n\treturn b\n}", "func IncludeTests() Option {\n\treturn func(o *options) {\n\t\to.tests = true\n\t}\n}", "func Test(b bool) Option {\n\treturn func(c *Config) Option {\n\t\tprevious := c.Test\n\t\tc.Test = b\n\t\treturn Test(previous)\n\t}\n}", "func (test *singleFileTest) addTestCase(moduleNameSpace, contents string) {\n\tfileName := fmt.Sprintf(\"file%d\", test.testCaseNum)\n\ttest.cases = append(test.cases, singleFileTestCase{fileName, contents, false,\n\t\tnew(mojom_files.MojomFile), new(mojom_files.MojomFileGraph)})\n\n\ttest.expectedFile().FileName = fileName\n\ttest.expectedFile().ModuleNamespace = &moduleNameSpace\n\n\ttest.expectedGraph().ResolvedTypes = make(map[string]mojom_types.UserDefinedType)\n\ttest.expectedGraph().ResolvedValues = make(map[string]mojom_types.UserDefinedValue)\n}", "func (c *ConfigParser) addSection(section string) {\n\toptions := make(map[string]string)\n\tinterpolate := make(map[string]InterpolateObj)\n\tsd := SectionData{options, interpolate}\n\tc.sections[section] = sd\n}", "func WithTestCtx(defaultDbName string, fn func(ctx *TestCtx)) {\n\tdbConn, session := db(defaultDbName)\n\n\tctx := TestCtx{Db: dbConn, S: session}\n\tfn(&ctx)\n\tsession.Close()\n}", "func (b *BootstrapClient) WithTestTransitData() *BootstrapClient {\n\ttransitData, err := ioutil.ReadFile(\"../vault/testdata/transitdata.json\")\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Failed to read generic data from ../vault/testdata/transitdata.json Error: %v\", err))\n\t}\n\treturn b.WithTransitData(string(transitData))\n}", "func TestSection(t *testing.T) {\n\tm := map[string]string{\"root\": \"/tmp\",\n\t\t\"PROC\": \"4\",\n\t}\n\tconf := New(m)\n\tstr := \" # Comment \\nsome = true\\nother = false \\n [ section ] \\nitem=2 \\n[ section.sub ]\\n item = 3\"\n\terr := conf.Load(strings.NewReader(str))\n\tif err != nil {\n\t\tt.Error(\"Echec Load\", err)\n\t} else {\n\t\t// Lecture section existante\n\t\tsection := conf.Section(\"section\")\n\t\tif section == nil {\n\t\t\tt.Error(\"Section 'section' not found\")\n\t\t}\n\n\t\tv, ok := section.Raw(\"item\")\n\t\tif !ok || v == \"\" || v != \"2\" {\n\t\t\tt.Error(\"Section.Raw('item') error : found \", v, \" expected 2, ok :\", ok, \" for :\", conf)\n\t\t}\n\n\t\tv, ok = conf.Raw(\"section.sub.item\")\n\t\tif !ok || v == \"\" || v != \"3\" {\n\t\t\tt.Error(\"Raw('section.sub.item') error : found \", v, \" expected 3, ok :\", ok, \" for :\", conf)\n\t\t}\n\n\t\tv, ok = section.Raw(\"sub.item\")\n\t\tif !ok || v == \"\" || v != \"3\" {\n\t\t\tt.Error(\"Section.Raw('sub.item') error : found \", v, \" expected 3, ok :\", ok, \" for :\", conf)\n\t\t}\n\n\t\tsection = conf.Section(\"none\")\n\t\tif section == nil {\n\t\t\tt.Error(\"Section 'none' not found\")\n\t\t}\n\n\t}\n}", "func (t *targetBuilder) setTestonly() *targetBuilder {\n\tt.testonly = true\n\treturn t\n}", "func (resource *ResourceType) WithTestCase(testcase TestCase) *ResourceType {\n\tresult := resource.copy()\n\tresult.testcases[testcase.Name()] = testcase\n\treturn result\n}", "func (b CreateTableBuilder) RunWith(runner squirrel.BaseRunner) CreateTableBuilder {\n\treturn builder.Set(b, \"RunWith\", runner).(CreateTableBuilder)\n}", "func (app *languageTestSectionBuilder) Create() LanguageTestSectionBuilder {\n\treturn createLanguageTestSectionBuilder()\n}", "func (t MockPluginTemplate) AddConfig(configMock func(builder *MockPrBuilder)) *SubMockBuilder {\n\tbuilder := &SubMockBuilder{prBuilder: &MockPrBuilder{pluginName: t.pluginName}}\n\tbuilder.prBuilder.WithConfigFile(configMock)\n\treturn builder\n}", "func (b *BootstrapClient) WithTestTLSCertData() *BootstrapClient {\n\tcertData, err := ioutil.ReadFile(\"../vault/testdata/test_cert.pem\")\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Failed create read TLS cert file from path pointed to by %s. Error: %v\", EnvTLSCertFilePath, err))\n\t}\n\tb.BootstrapConfig.TLSCertData = string(certData)\n\treturn b\n}", "func WithTestHTTPClient(ctx context.Context, client *http.Client) context.Context {\n\treturn context.WithValue(ctx, &httpClientCtxKey, client)\n}", "func (suite *testSuite) SetupTest() {\n\tvar err error\n\tsuite.testID = xid.New().String()\n\n\tsuite.builder, err = NewBuilder(suite.logger, nil)\n\tif err != nil {\n\t\tsuite.Fail(\"Instantiating Builder failed:\", err)\n\t}\n\n\tcreateFunctionOptions := &platform.CreateFunctionOptions{\n\t\tLogger: suite.logger,\n\t\tFunctionConfig: *functionconfig.NewConfig(),\n\t}\n\n\tcreateFunctionBuildOptions := &platform.CreateFunctionBuildOptions{\n\t\tLogger: createFunctionOptions.Logger,\n\t\tFunctionConfig: createFunctionOptions.FunctionConfig,\n\t}\n\n\tsuite.builder.options = createFunctionBuildOptions\n}", "func (b CreateIndexBuilder) RunWith(runner squirrel.BaseRunner) CreateIndexBuilder {\n\treturn builder.Set(b, \"RunWith\", runner).(CreateIndexBuilder)\n}", "func NewTestBlockBuilder(baseBlockBuilder model.BlockBuilder, testConsensus testapi.TestConsensus) testapi.TestBlockBuilder {\n\treturn &testBlockBuilder{\n\t\tblockBuilder: baseBlockBuilder.(*blockBuilder),\n\t\ttestConsensus: testConsensus,\n\t}\n}", "func NewTestVoucherWith(data string) datamodel.Node {\n\tn, err := qp.BuildList(basicnode.Prototype.Any, 1, func(ma datamodel.ListAssembler) {\n\t\tqp.ListEntry(ma, qp.String(data))\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn n\n}", "func (app *languageTestSectionBuilder) WithDeclarations(declarations []LanguageTestDeclaration) LanguageTestSectionBuilder {\n\tapp.declarations = declarations\n\treturn app\n}", "func FromTest(workspace string, testfile string, casenr int, prepareVM VMPrepareFunc) (*Helper, error) {\n\ttestfile = JoinPath(workspace, testfile)\n\ttestfilecontent, err := ioutil.ReadFile(testfile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tt, err := testing.Parse(testfilecontent, testfile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th := &Helper{\n\t\tScriptNames: make([]string, len(t.Scripts)),\n\t\tScripts: make([]string, len(t.Scripts)),\n\t\tVariableTranslations: make([]map[string]string, len(t.Scripts)),\n\t\tVms: make([]*vm.VM, len(t.Scripts)),\n\t\tCurrentScript: 0,\n\t\tCoordinator: vm.NewCoordinator(),\n\t\tWorspace: filepath.Dir(testfile),\n\t\tFinishedVMs: make(map[int]bool),\n\t\tValidBreakpoints: make(map[int]map[int]bool),\n\t\tCompiledCode: make(map[int]string),\n\t\tIgnoreErrs: t.IgnoreErrs,\n\t\tLocalVars: make([][]string, len(t.Scripts)),\n\t\tGlobalVars: make([]string, 0, 10),\n\t}\n\n\tfor i, script := range t.Scripts {\n\t\th.ScriptNames[i] = script\n\t\th.Scripts[i], err = t.GetScriptCode(i)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif casenr < 1 || casenr > len(t.Cases) {\n\t\treturn nil, fmt.Errorf(\"The test-file does not contain a case number %d!\", casenr)\n\t}\n\n\trunner, err := t.GetRunner(casenr - 1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th.Vms = runner.VMs\n\th.Coordinator = runner.Coordinator\n\th.VariableTranslations = runner.VarTranslations\n\n\tfor i, iv := range h.Vms {\n\t\tprepareVM(iv, h.ScriptNames[i])\n\t\tif strings.HasSuffix(h.ScriptNames[i], \".nolol\") {\n\t\t\th.ValidBreakpoints[i] = findValidBreakpoints(iv.GetProgram())\n\t\t\tpri := parser.Printer{\n\t\t\t\tMode: parser.PrintermodeReadable,\n\t\t\t}\n\t\t\tyololcodestr, _ := pri.Print(iv.GetProgram())\n\t\t\th.CompiledCode[i] = yololcodestr\n\t\t}\n\t}\n\th.findReferencedVariables()\n\treturn h, nil\n}", "func (b *BootstrapClient) WithTestTLSCertKeyData() *BootstrapClient {\n\tcertKeyData, err := ioutil.ReadFile(\"../vault/testdata/test_cert_key.pem\")\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Failed create read TLS cert key file from path pointed to by %s. Error: %v\", EnvTLSCertKeyFilePath, err))\n\t}\n\tb.BootstrapConfig.TLSCertKeyData = string(certKeyData)\n\treturn b\n}", "func (c *TestProjectConfig) AddFeatureTest(f entities.Feature) *TestProjectConfig {\n\texperimentID := c.getNextID()\n\tvariationID := c.getNextID()\n\tlayerID := c.getNextID()\n\n\tvariation := entities.Variation{\n\t\tKey: variationID,\n\t\tID: variationID,\n\t\tFeatureEnabled: true,\n\t}\n\n\texperiment := entities.Experiment{\n\t\tKey: experimentID,\n\t\tLayerID: layerID,\n\t\tID: experimentID,\n\t\tVariations: map[string]entities.Variation{variationID: variation},\n\t\tVariationKeyToIDMap: map[string]string{variation.Key: variationID},\n\t\tTrafficAllocation: []entities.Range{\n\t\t\tentities.Range{EntityID: variationID, EndOfRange: 10000},\n\t\t},\n\t}\n\n\tf.FeatureExperiments = []entities.Experiment{experiment}\n\tc.FeatureMap[f.Key] = f\n\tc.ExperimentMap[experiment.Key] = experiment\n\treturn c\n}", "func TestSections(t *testing.T) {\n\tm := map[string]string{\"root\": \"/tmp\",\n\t\t\"PROC\": \"4\",\n\t}\n\tconf := New(m)\n\tstr := \" # Comment \\nsome = true\\nother = false \\n [ section ] \\nitem=2 \\n[ section2 ]\\n item = 3\"\n\terr := conf.Load(strings.NewReader(str))\n\tif err != nil {\n\t\tt.Error(\"Echec Load\", err)\n\t} else {\n\t\tv := conf.Sections()\n\t\tif len(v) != 2 {\n\t\t\tt.Error(\"Sections() error : found \", v, \" expected len == 2\")\n\t\t}\n\n\t\tc := v[\"section\"]\n\t\tif c == nil {\n\t\t\tt.Error(\"Sections() error : subsection 'section' not found \", v)\n\t\t} else {\n\t\t\tv, err := c.String(\"item\")\n\t\t\tif err != nil || v != \"2\" {\n\t\t\t\tt.Error(\"Section('section2.item') error : found \", v, \" expected 2, for :\", c)\n\t\t\t}\n\t\t}\n\n\t\tc = v[\"section2\"]\n\t\tif c == nil {\n\t\t\tt.Error(\"Sections() error : subsection 'section2' not found \", v)\n\t\t}\n\n\t\tc = v[\"section3\"]\n\t\tif c != nil {\n\t\t\tt.Error(\"Sections() error : subsection 'section3' found \", v)\n\t\t}\n\t}\n}", "func (sb *spanishBot) setTest(s string) {\n\tsb.test = s\n}", "func (b *Builder) BuildTest(pkg string) error {\n\tif err := os.MkdirAll(b.Dir, 0700); err != nil {\n\t\treturn err\n\t}\n\tif b.Binary == \"\" {\n\t\tb.Binary = filepath.Join(b.Dir, \"test.binary\")\n\t}\n\tif err := os.Chdir(pkg); err != nil {\n\t\tb.Cleanup()\n\t\treturn err\n\t}\n\tcmd := exec.Command(\"go\", \"test\", \"-c\", \"-o\", b.Binary)\n\tvar bout, berr bytes.Buffer\n\tcmd.Stdout = &bout\n\tcmd.Stderr = &berr\n\terr := cmd.Run()\n\tb.Stdout = bout.Bytes()\n\tb.Stderr = berr.Bytes()\n\tif err != nil {\n\t\tb.Cleanup()\n\t}\n\treturn err\n}", "func WithTestServer(t *testing.T, closure func(s *api.Server)) {\n\n\tt.Helper()\n\n\tWithTestDatabase(t, func(db *sql.DB) {\n\n\t\tt.Helper()\n\n\t\tdefaultConfig := api.DefaultServiceConfigFromEnv()\n\n\t\t// https://stackoverflow.com/questions/43424787/how-to-use-next-available-port-in-http-listenandserve\n\t\t// You may use port 0 to indicate you're not specifying an exact port but you want a free, available port selected by the system\n\t\tdefaultConfig.Echo.ListenAddress = \":0\"\n\n\t\ts := api.NewServer(defaultConfig)\n\n\t\t// attach the already initalized db\n\t\ts.DB = db\n\n\t\tif err := s.InitMailer(true); err != nil {\n\t\t\tt.Fatalf(\"failed to initialize mailer: %v\", err)\n\t\t}\n\n\t\trouter.Init(s)\n\n\t\t// no need to actually start echo!\n\t\t// see https://github.com/labstack/echo/issues/659\n\n\t\tclosure(s)\n\t})\n}", "func WriteTestKustomizationWith(fSys filesys.FileSystem, bytes []byte) {\n\tfSys.WriteFile(konfig.DefaultKustomizationFileName(), bytes)\n}", "func (this *SelecterConfig) TestConfig() error {\n\n\tif this.Name == \"\" {\n\t\tthis.Name = \"img\"\n\t}\n\tif this.Attr == \"\" {\n\t\tthis.Attr = \"src\"\n\t}\n\tif this.Pattern == \"\" {\n\t\tthis.Pattern = \"\\\\.png\"\n\t}\n\treturn nil\n}", "func CreateBlockForTests(gen genesis.Genesis, additional uint, buckets []buckets.Bucket) Block {\n\tcreatedOn := time.Now().UTC()\n\tins, err := NewBuilder().Create().\n\t\tWithGenesis(gen).\n\t\tWithAdditional(additional).\n\t\tWithBuckets(buckets).\n\t\tCreatedOn(createdOn).\n\t\tNow()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn ins\n}", "func WithTestVars(vars starlark.StringDict) TestOption {\n\treturn fnTestOption(func(opts *testOptions) {\n\t\tfor key, value := range vars {\n\t\t\topts.vars.SetKey(starlark.String(key), value)\n\t\t}\n\t})\n}", "func (e Engine) AddTestConfig(backend *storage.Backend) (storage.Alias, error) {\n\talias := storage.Alias(\"filelog\")\n\tif backend.DefaultLog == \"\" {\n\t\tbackend.DefaultLog = alias\n\t}\n\tif backend.Stores == nil {\n\t\tbackend.Stores = make(map[storage.Alias]dvid.StoreConfig)\n\t}\n\ttc := map[string]interface{}{\n\t\t\"path\": fmt.Sprintf(\"dvid-test-filelog-%x\", uuid.NewV4().Bytes()),\n\t\t\"testing\": true,\n\t}\n\tvar c dvid.Config\n\tc.SetAll(tc)\n\tbackend.Stores[alias] = dvid.StoreConfig{Config: c, Engine: \"filelog\"}\n\treturn alias, nil\n}", "func newTestChain(t testing.TB) *Blockchain {\n\treturn newTestChainWithCustomCfg(t, nil)\n}", "func (set *Set) Test(testOptions ...string) (bool, error) {\n\t_, err := set.Parent.run(append([]string{\"test\", set.name()}, testOptions...)...)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}", "func WithVFSTest(vfsTest avfs.VFS) Option {\n\treturn func(sfs *SuiteFS) {\n\t\tsfs.vfsTest = vfsTest\n\t\tif vfsTest.HasFeature(avfs.FeatReadOnly) {\n\t\t\tsfs.canTestPerm = false\n\t\t}\n\t}\n}", "func NewSection() *Section {\n\treturn &Section{\n\t\tParams: make(Params, 0),\n\t}\n}", "func (m *MockAdminSectionRepo) AddSection(arg0 context.Context, arg1 models.Section) (int, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddSection\", arg0, arg1)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func withDiscoveryService(t *testing.T, discoveryGroup string, awsMatchers ...types.AWSMatcher) testOptionsFunc {\n\tt.Helper()\n\treturn func(options *testOptions) {\n\t\toptions.serviceConfigFuncs = append(options.serviceConfigFuncs, func(cfg *servicecfg.Config) {\n\t\t\tcfg.Discovery.Enabled = true\n\t\t\tcfg.Discovery.DiscoveryGroup = discoveryGroup\n\t\t\t// Reduce the polling interval to speed up the test execution\n\t\t\t// in the case of a failure of the first attempt.\n\t\t\t// The default polling interval is 5 minutes.\n\t\t\tcfg.Discovery.PollInterval = 1 * time.Minute\n\t\t\tcfg.Discovery.AWSMatchers = append(cfg.Discovery.AWSMatchers, awsMatchers...)\n\t\t})\n\t}\n}", "func TestSetUpWithConfig(T *testing.T) {\n\tvar db etcdDB\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, `{\"action\":\"set\",\"node\":{\"dir\": true,\"key\":\"/test\",\"value\":\"Hello\",\"modifiedIndex\":4,\"createdIndex\":4}}`)\n\t}))\n\tdefer ts.Close()\n\n\tconfig := ts.URL\n\n\tdb.Setup(config)\n}", "func makeTestConfig(tests []test) *Config {\n\tnum := numberOfSources(tests)\n\tsrcs := make([]Source, num)\n\tfor i := range srcs {\n\t\tsrcs[i] = NewSrcMap()\n\t}\n\n\tfor _, p := range tests {\n\t\tlevel := p.srcLevel\n\t\tif level > 0 {\n\t\t\tsrc := srcs[level-1].(*SrcMap)\n\t\t\tsrc.Put(p.propName, p.propVal)\n\t\t}\n\t}\n\n\tconfig := &Config{}\n\tconfig.AppendSource(srcs...)\n\treturn config\n}", "func (b *builder) With(feat string) FeaturesBuilder {\n\tkv := strings.Split(feat, \":\")\n\tif len(kv) == 1 {\n\t\tkey := strings.TrimSpace(kv[0])\n\t\tif key == \"\" {\n\t\t\treturn b\n\t\t}\n\t\tb.fs[key] = \"\"\n\t} else if len(kv) == 2 {\n\t\tkey := strings.TrimSpace(kv[0])\n\t\tval := strings.TrimSpace(kv[1])\n\t\tif key == \"\" {\n\t\t\treturn b\n\t\t}\n\t\tb.fs[key] = val\n\t}\n\treturn b\n}", "func NewWith(t *testing.T, w Wrap) *T {\n\treturn &T{\n\t\tT: t,\n\t\tAssertions: assert.New(t),\n\t\twrap: w,\n\t}\n}", "func withUserRole(t *testing.T, name string, spec types.RoleSpecV6) testOptionsFunc {\n\tt.Helper()\n\t// Create a new role with full access to all databases.\n\trole, err := types.NewRole(name, spec)\n\trequire.NoError(t, err)\n\treturn func(options *testOptions) {\n\t\toptions.userRoles = append(options.userRoles, role)\n\t}\n}", "func withKubeService(t *testing.T, matchers ...services.ResourceMatcher) testOptionsFunc {\n\tt.Helper()\n\tmustGetEnv(t, kubeSvcRoleARNEnv)\n\treturn func(options *testOptions) {\n\t\toptions.serviceConfigFuncs = append(options.serviceConfigFuncs, func(cfg *servicecfg.Config) {\n\t\t\t// Enable kubernetes proxy\n\t\t\tcfg.Proxy.Kube.Enabled = true\n\t\t\tcfg.Proxy.Kube.ListenAddr = *utils.MustParseAddr(helpers.NewListener(t, service.ListenerProxyKube, &(cfg.FileDescriptors)))\n\t\t\t// set kubernetes specific parameters\n\t\t\tcfg.Kube.Enabled = true\n\t\t\tcfg.Kube.ListenAddr = utils.MustParseAddr(helpers.NewListener(t, service.ListenerKube, &(cfg.FileDescriptors)))\n\t\t\tcfg.Kube.ResourceMatchers = matchers\n\t\t})\n\t}\n}", "func (s *SignSuite) SetUpTest(c *C) {\n}", "func (app *builder) WithTable(table Table) Builder {\n\tapp.table = table\n\treturn app\n}", "func HelmInstallTestOpt(path string) features.Func {\n\treturn func(ctx context.Context, t *testing.T, envConf *envconf.Config) context.Context {\n\t\treleaseName := strings.ReleaseNameFromT(t)\n\t\treturn HelmInstallOpt(path, releaseName)(ctx, t, envConf)\n\t}\n}", "func NewTestNode(options ...Option) *Node {\n\tops := DefaultOptions()\n\tfor _, o := range options {\n\t\to(ops)\n\t}\n\n\treturn NewTestNodeFromOptions(ops)\n}", "func TestConfiguration(t *testing.T) { TestingT(t) }", "func test(t *testing.T, scene string, f func(*testing.T)) {\n\tif t.Failed() {\n\t\treturn\n\t}\n\tConvey(scene, t, func() {\n\t\tf(t)\n\t})\n}", "func (suite *LegacyTestSuite) SetupTest() {\n\tsuite.coordinator = ibctesting.NewCoordinator(suite.T(), 2)\n\tsuite.chainA = suite.coordinator.GetChain(ibctesting.GetChainID(0))\n\tsuite.chainB = suite.coordinator.GetChain(ibctesting.GetChainID(1))\n\t// commit some blocks so that QueryProof returns valid proof (cannot return valid query if height <= 1)\n\tsuite.coordinator.CommitNBlocks(suite.chainA, 2)\n\tsuite.coordinator.CommitNBlocks(suite.chainB, 2)\n}", "func WithCleanup(fn func()) {\n\ttestsStarted = true\n\n\t// Initialize the fixture directory. If we were the ones to initialize it, set the env\n\t// var so that child processes inherit this directory and take responsibility for\n\t// cleaning it up after we exit.\n\tfixtureDir, init := fixtureDirectory()\n\tif init {\n\t\tos.Setenv(\"OS_TEST_FIXTURE_DIR\", fixtureDir)\n\t\tdefer func() {\n\t\t\tos.Setenv(\"OS_TEST_FIXTURE_DIR\", \"\")\n\t\t\tos.RemoveAll(fixtureDir)\n\t\t}()\n\t}\n\n\tfn()\n}", "func SetTest() {\n\tgin.SetMode(gin.TestMode)\n}", "func SetHelmOptionsTestOpt() features.Func {\n\treturn func(ctx context.Context, t *testing.T, envConf *envconf.Config) context.Context {\n\t\tvaluesFilePath := path.Join(\"values\", strings.ValueFileFromT(t))\n\t\treturn SetHelmOptionsOpt(valuesFilePath)(ctx, t, envConf)\n\t}\n}", "func (i *Invoice) SetTest(value bool) {\n\tif value {\n\t\ti.Flags.Set(0)\n\t\ti.Test = true\n\t} else {\n\t\ti.Flags.Unset(0)\n\t\ti.Test = false\n\t}\n}", "func setupTest(mt *mtest.T, testFile *testFile, testCase *testCase) {\n\tmt.Helper()\n\n\t// key vault data\n\tif len(testFile.KeyVaultData) > 0 {\n\t\t// Drop the key vault collection in case it exists from a prior test run.\n\t\terr := mt.Client.Database(\"keyvault\").Collection(\"datakeys\").Drop(context.Background())\n\t\tassert.Nil(mt, err, \"error dropping key vault collection\")\n\n\t\tkeyVaultColl := mt.CreateCollection(mtest.Collection{\n\t\t\tName: \"datakeys\",\n\t\t\tDB: \"keyvault\",\n\t\t}, false)\n\n\t\tinsertDocuments(mt, keyVaultColl, testFile.KeyVaultData)\n\t}\n\n\t// regular documents\n\tif testFile.Data.Documents != nil {\n\t\tinsertDocuments(mt, mt.Coll, testFile.Data.Documents)\n\t\treturn\n\t}\n\n\t// GridFS data\n\tgfsData := testFile.Data.GridFSData\n\n\tif gfsData.Chunks != nil {\n\t\tchunks := mt.CreateCollection(mtest.Collection{\n\t\t\tName: gridFSChunks,\n\t\t}, false)\n\t\tinsertDocuments(mt, chunks, gfsData.Chunks)\n\t}\n\tif gfsData.Files != nil {\n\t\tfiles := mt.CreateCollection(mtest.Collection{\n\t\t\tName: gridFSFiles,\n\t\t}, false)\n\t\tinsertDocuments(mt, files, gfsData.Files)\n\n\t\tcsVal, err := gfsData.Files[0].LookupErr(\"chunkSize\")\n\t\tif err == nil {\n\t\t\ttestCase.chunkSize = csVal.Int32()\n\t\t}\n\t}\n}", "func (suite *HandlerTestSuite) SetupTest() {\n\tsuite.coordinator = ibctesting.NewCoordinator(suite.T(), 2)\n\tsuite.chainA = suite.coordinator.GetChain(ibctesting.GetChainID(0))\n\tsuite.chainB = suite.coordinator.GetChain(ibctesting.GetChainID(1))\n}", "func ConfigureTestOptionsWithResources(o *controller.RoleOptions, k8sObjects, jxObjects []runtime.Object) {\n\tcurrentNamespace := \"jx\"\n\to.TeamNs = currentNamespace\n\n\tnamespacesRequired := []string{currentNamespace}\n\tnamespaceMap := map[string]*corev1.Namespace{}\n\n\tfor _, ro := range k8sObjects {\n\t\tns, ok := ro.(*corev1.Namespace)\n\t\tif ok {\n\t\t\tnamespaceMap[ns.Name] = ns\n\t\t}\n\t}\n\thasDev := false\n\tfor _, ro := range jxObjects {\n\t\tenv, ok := ro.(*v1.Environment)\n\t\tif ok {\n\t\t\tns := env.Spec.Namespace\n\t\t\tif ns != \"\" && util.StringArrayIndex(namespacesRequired, ns) < 0 {\n\t\t\t\tnamespacesRequired = append(namespacesRequired, ns)\n\t\t\t}\n\t\t\tif env.Name == \"dev\" {\n\t\t\t\thasDev = true\n\t\t\t}\n\t\t}\n\t}\n\n\t// ensure we've the dev environment\n\tif !hasDev {\n\t\tdevEnv := kube.NewPermanentEnvironment(\"dev\")\n\t\tdevEnv.Spec.Namespace = currentNamespace\n\t\tdevEnv.Spec.Kind = v1.EnvironmentKindTypeDevelopment\n\n\t\tjxObjects = append(jxObjects, devEnv)\n\t}\n\n\t// add any missing namespaces\n\tfor _, ns := range namespacesRequired {\n\t\tif namespaceMap[ns] == nil {\n\t\t\tk8sObjects = append(k8sObjects, &corev1.Namespace{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: ns,\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"tag\": \"\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t}\n\n\tclient := fake.NewSimpleClientset(k8sObjects...)\n\to.KubeClient = client\n\to.JxClient = v1fake.NewSimpleClientset(jxObjects...)\n}", "func (controller TestController) RunTest() (setupErr error, testErr error) {\n\ttests := controller.testSuite.GetTests()\n\tlogrus.Debugf(\"Test configs: %v\", tests)\n\ttest, found := tests[controller.testName]\n\tif !found {\n\t\treturn stacktrace.NewError(\"Nonexistent test: %v\", controller.testName), nil\n\t}\n\n\tnetworkLoader, err := test.GetNetworkLoader()\n\tif err != nil {\n\t\treturn stacktrace.Propagate(err, \"Could not get network loader\"), nil\n\t}\n\n\tlogrus.Info(\"Connecting to Docker environment...\")\n\t// Initialize a Docker client\n\tdockerClient, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())\n\tif err != nil {\n\t\treturn stacktrace.Propagate(err,\"Failed to initialize Docker client from environment.\"), nil\n\t}\n\tdockerManager, err := docker.NewDockerManager(logrus.StandardLogger(), dockerClient)\n\tif err != nil {\n\t\treturn stacktrace.Propagate(err, \"An error occurred when constructing the Docker manager\"), nil\n\t}\n\tlogrus.Info(\"Connected to Docker environment\")\n\n\tlogrus.Infof(\"Configuring test network in Docker network %v...\", controller.networkId)\n\talreadyTakenIps := map[string]bool{\n\t\tcontroller.gatewayIp: true,\n\t\tcontroller.testControllerIp: true,\n\t}\n\tfreeIpTracker, err := networks.NewFreeIpAddrTracker(logrus.StandardLogger(), controller.subnetMask, alreadyTakenIps)\n\tif err != nil {\n\t\treturn stacktrace.Propagate(err, \"An error occurred creating the free IP address tracker\"), nil\n\t}\n\n\tbuilder := networks.NewServiceNetworkBuilder(\n\t\t\tdockerManager,\n\t\t\tcontroller.networkId,\n\t\t\tfreeIpTracker,\n\t\t\tcontroller.testVolumeName,\n\t\t\tcontroller.testVolumeFilepath)\n\tif err := networkLoader.ConfigureNetwork(builder); err != nil {\n\t\treturn stacktrace.Propagate(err, \"Could not configure test network in Docker network %v\", controller.networkId), nil\n\t}\n\tnetwork := builder.Build()\n\tdefer func() {\n\t\tlogrus.Info(\"Stopping test network...\")\n\t\terr := network.RemoveAll(CONTAINER_STOP_TIMEOUT)\n\t\tif err != nil {\n\t\t\tlogrus.Error(\"An error occurred stopping the network\")\n\t\t\tfmt.Fprintln(logrus.StandardLogger().Out, err)\n\t\t} else {\n\t\t\tlogrus.Info(\"Successfully stopped the test network\")\n\t\t}\n\t}()\n\tlogrus.Info(\"Test network configured\")\n\n\tlogrus.Info(\"Initializing test network...\")\n\tavailabilityCheckers, err := networkLoader.InitializeNetwork(network);\n\tif err != nil {\n\t\treturn stacktrace.Propagate(err, \"An error occurred initialized the network to its starting state\"), nil\n\t}\n\tlogrus.Info(\"Test network initialized\")\n\n\t// Second pass: wait for all services to come up\n\tlogrus.Info(\"Waiting for test network to become available...\")\n\tfor serviceId, availabilityChecker := range availabilityCheckers {\n\t\tlogrus.Debugf(\"Waiting for service %v to become available...\", serviceId)\n\t\tif err := availabilityChecker.WaitForStartup(); err != nil {\n\t\t\treturn stacktrace.Propagate(err, \"An error occurred waiting for service with ID %v to start up\", serviceId), nil\n\t\t}\n\t\tlogrus.Debugf(\"Service %v is available\", serviceId)\n\t}\n\tlogrus.Info(\"Test network is available\")\n\n\tlogrus.Info(\"Executing test...\")\n\tuntypedNetwork, err := networkLoader.WrapNetwork(network)\n\tif err != nil {\n\t\treturn stacktrace.Propagate(err, \"Error occurred wrapping network in user-defined network type\"), nil\n\t}\n\n\ttestResultChan := make(chan error)\n\n\tgo func() {\n\t\ttestResultChan <- runTest(test, untypedNetwork)\n\t}()\n\n\t// Time out the test so a poorly-written test doesn't run forever\n\ttestTimeout := test.GetExecutionTimeout()\n\tvar timedOut bool\n\tvar testResultErr error\n\tselect {\n\tcase testResultErr = <- testResultChan:\n\t\tlogrus.Tracef(\"Test returned result before timeout: %v\", testResultErr)\n\t\ttimedOut = false\n\tcase <- time.After(testTimeout):\n\t\tlogrus.Tracef(\"Hit timeout %v before getting a result from the test\", testTimeout)\n\t\ttimedOut = true\n\t}\n\n\tlogrus.Tracef(\"After running test w/timeout: resultErr: %v, timedOut: %v\", testResultErr, timedOut)\n\n\tif timedOut {\n\t\treturn nil, stacktrace.NewError(\"Timed out after %v waiting for test to complete\", testTimeout)\n\t}\n\n\tlogrus.Info(\"Test execution completed\")\n\n\tif testResultErr != nil {\n\t\treturn nil, stacktrace.Propagate(testResultErr, \"An error occurred when running the test\")\n\t}\n\n\treturn nil, nil\n}", "func (suite *AnteTestSuite) CreateTestTxBuilder(\n\tmsg *evmtypes.MsgEthereumTx, priv cryptotypes.PrivKey, accNum uint64, signCosmosTx bool,\n\tunsetExtensionOptions ...bool,\n) client.TxBuilder {\n\tvar option *codectypes.Any\n\tvar err error\n\tif len(unsetExtensionOptions) == 0 {\n\t\toption, err = codectypes.NewAnyWithValue(&evmtypes.ExtensionOptionsEthereumTx{})\n\t\tsuite.Require().NoError(err)\n\t}\n\n\ttxBuilder := suite.clientCtx.TxConfig.NewTxBuilder()\n\tbuilder, ok := txBuilder.(authtx.ExtensionOptionsTxBuilder)\n\tsuite.Require().True(ok)\n\n\tif len(unsetExtensionOptions) == 0 {\n\t\tbuilder.SetExtensionOptions(option)\n\t}\n\n\terr = msg.Sign(suite.ethSigner, tests.NewSigner(priv))\n\tsuite.Require().NoError(err)\n\n\tmsg.From = \"\"\n\terr = builder.SetMsgs(msg)\n\tsuite.Require().NoError(err)\n\n\ttxData, err := evmtypes.UnpackTxData(msg.Data)\n\tsuite.Require().NoError(err)\n\n\tfees := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewIntFromBigInt(txData.Fee())))\n\tbuilder.SetFeeAmount(fees)\n\tbuilder.SetGasLimit(msg.GetGas())\n\n\tif signCosmosTx {\n\t\t// First round: we gather all the signer infos. We use the \"set empty\n\t\t// signature\" hack to do that.\n\t\tsigV2 := signing.SignatureV2{\n\t\t\tPubKey: priv.PubKey(),\n\t\t\tData: &signing.SingleSignatureData{\n\t\t\t\tSignMode: suite.clientCtx.TxConfig.SignModeHandler().DefaultMode(),\n\t\t\t\tSignature: nil,\n\t\t\t},\n\t\t\tSequence: txData.GetNonce(),\n\t\t}\n\n\t\tsigsV2 := []signing.SignatureV2{sigV2}\n\n\t\terr = txBuilder.SetSignatures(sigsV2...)\n\t\tsuite.Require().NoError(err)\n\n\t\t// Second round: all signer infos are set, so each signer can sign.\n\n\t\tsignerData := authsigning.SignerData{\n\t\t\tChainID: suite.ctx.ChainID(),\n\t\t\tAccountNumber: accNum,\n\t\t\tSequence: txData.GetNonce(),\n\t\t}\n\t\tsigV2, err = tx.SignWithPrivKey(\n\t\t\tsuite.clientCtx.TxConfig.SignModeHandler().DefaultMode(), signerData,\n\t\t\ttxBuilder, priv, suite.clientCtx.TxConfig, txData.GetNonce(),\n\t\t)\n\t\tsuite.Require().NoError(err)\n\n\t\tsigsV2 = []signing.SignatureV2{sigV2}\n\n\t\terr = txBuilder.SetSignatures(sigsV2...)\n\t\tsuite.Require().NoError(err)\n\t}\n\n\treturn txBuilder\n}", "func (o *TestEmailConfigurationParams) WithBody(body string) *TestEmailConfigurationParams {\n\to.SetBody(body)\n\treturn o\n}", "func TestTableAdd(t *testing.T) {\n\n\t//iterate over test array\n\tfor _, test := range testingArray {\n\n\t\t//call Add and get the result\n\t\tresult := Add(test.x, test.y)\n\n\t\t//compare the result to expected. return error if failed\n\t\tif result != test.expected {\n\t\t\tt.Error(\"Testing failed\")\n\t\t}\n\t}\n\n}", "func ProviderTest(initial Initial, observer invoker.Observer, settings Settings) (Configurator, func(), error) {\n\tc, e := NewMockConfigurator(initial, observer, settings)\n\treturn c, func() {}, e\n}", "func (fs *FileSystem) addTestSiaFileWithErr(siaPath modules.SiaPath) error {\n\tec, err := modules.NewRSSubCode(10, 20, crypto.SegmentSize)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = fs.NewSiaFile(siaPath, \"\", ec, crypto.GenerateSiaKey(crypto.TypeDefaultRenter), uint64(fastrand.Intn(100)), persist.DefaultDiskPermissionsTest, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (b *BootstrapClient) WithTestAWSIAMRolePolicy() *BootstrapClient {\n\tpolicyData, err := ioutil.ReadFile(\"../vault/testdata/aws_invite_email_role_policy.json\")\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Failed to read AWS IAM role policy file from path from ../vault/testdata/aws_invite_email_role_policy.json. Error: %v\", err))\n\t}\n\tb.BootstrapConfig.AWSRolePolicyJSON = string(policyData) // TODO: what if we need multiple role policies?\n\treturn b\n}", "func (fs *FileSystem) addTestSiaFile(siaPath modules.SiaPath) {\n\tif err := fs.addTestSiaFileWithErr(siaPath); err != nil {\n\t\tpanic(err)\n\t}\n}", "func NewTestbed(behavior Behavior, tester func(evt Event) bool) *Testbed {\n\tctx, cancel := context.WithCancel(context.Background())\n\ttb := &Testbed{\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tdonec: make(chan struct{}),\n\t\tcell: goTestbedCell(ctx, behavior),\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-tb.ctx.Done():\n\t\t\t\treturn\n\t\t\tcase evt := <-tb.cell.outc:\n\t\t\t\tif tester(evt) {\n\t\t\t\t\tclose(tb.donec)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\treturn tb\n}", "func (b *networkHarness) WithSetup(f func(ctx context.Context, network *Network)) *networkHarness {\n\tb.setupFunc = f\n\treturn b\n}", "func newSection(tm *TimedMap, sec int) *section {\n\treturn &section{\n\t\ttm: tm,\n\t\tsec: sec,\n\t}\n}", "func Suite(name string, test Test) *suite {\n\tsuite := &suite{\n\t\tName: name,\n\t\tTest: test,\n\t\tStats: &stats{},\n\t}\n\tsuite.ctx = &C{\n\t\tsuite: suite,\n\t}\n\tDefaultRunner.Add(suite)\n\treturn suite\n}", "func TestListSection(T *testing.T) {\n\n\tvar db etcdDB\n\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, `{\"action\":\"get\",\"node\":{\"key\":\"/testDir\",\"value\":\"Hello\",\"modifiedIndex\":4,\"createdIndex\":4}}`)\n\t}))\n\tdefer ts.Close()\n\n\tconfig := ts.URL\n\n\tdb.Cfg = cli.Config{\n\t\tEndpoints: []string{config},\n\t\tTransport: cli.DefaultTransport,\n\t\t// set timeout per request to fail fast when the target endpoint is unavailable\n\t\tHeaderTimeoutPerRequest: time.Second,\n\t}\n\n\tdb.C, _ = cli.New(db.Cfg)\n\n\tdb.Kapi = cli.NewKeysAPI(db.C)\n\tdb.Ctx = context.Background()\n\n\tdb.ListSection(\"/testDir\", true)\n\n}", "func (app *applicationBuilder) WithMain(main MainSection) ApplicationBuilder {\n\tapp.main = main\n\treturn app\n}", "func NewTestAppender(name string) *TestAppender {\n\treturn &TestAppender{\n\t\tname: name,\n\t}\n}", "func GenerateSectionWithImage(text string, imageurl string, alttext string) (section Blocks) {\n\n\tSection := Blocks{Type: \"section\",\n\t\tText: &Text{\n\t\t\tText: text,\n\t\t\tType: \"mrkdwn\",\n\t\t},\n\t\tAccessory: &Accessory{\n\t\t\tType: \"image\",\n\t\t\tImageURL: imageurl,\n\t\t\tAltText: alttext,\n\t\t},\n\t}\n\n\treturn Section\n\n}", "func NewSection(title string, index int) *Section {\n\treturn &Section{\n\t\tTitle: title,\n\t\tIndex: index,\n\t\tMaxExits: pickMaxExit(),\n\t}\n}", "func (m *Main) NewTest(name, command string, run func(t *Test) error) *Test {\n\tt := NewTest(name, command, run)\n\tm.AddTest(t)\n\treturn t\n}", "func newTestConfig() (*Config, *test.LndMockServices) {\n\tlnd := test.NewMockLnd()\n\n\t// Set our fee estimate for the default number of confirmations to our\n\t// limit so that our fees will be ok by default.\n\tlnd.SetFeeEstimate(\n\t\tdefaultParameters.SweepConfTarget, defaultSweepFeeRateLimit,\n\t)\n\n\treturn &Config{\n\t\tRestrictions: func(_ context.Context, _ swap.Type, initiator string) (*Restrictions,\n\t\t\terror) {\n\n\t\t\treturn testRestrictions, nil\n\t\t},\n\t\tLnd: &lnd.LndServices,\n\t\tClock: clock.NewTestClock(testTime),\n\t\tListLoopOut: func(context.Context) ([]*loopdb.LoopOut, error) {\n\t\t\treturn nil, nil\n\t\t},\n\t\tListLoopIn: func(context.Context) ([]*loopdb.LoopIn, error) {\n\t\t\treturn nil, nil\n\t\t},\n\t\tLoopOutQuote: func(_ context.Context,\n\t\t\t_ *loop.LoopOutQuoteRequest) (*loop.LoopOutQuote,\n\t\t\terror) {\n\n\t\t\treturn testQuote, nil\n\t\t},\n\t}, lnd\n}", "func WithBuilder(builder BuilderFn) Option {\n\treturn func(c *Config) {\n\t\tc.Builder = builder\n\t}\n}", "func (mr *MockDBMockRecorder) AddTest(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddTest\", reflect.TypeOf((*MockDB)(nil).AddTest), arg0, arg1)\n}", "func NewTestClient(cfg *app.Configuration) (*TestClient, error) {\n\tvar cli TestClient\n\n\tbase := url.URL{}\n\tcli.baseURL = &base\n\n\tif cfg == nil {\n\t\tcfg = &app.Configuration{}\n\t}\n\n\tif len(cfg.UserSecret) == 0 {\n\t\tcfg.UserSecret = apptest.TestSecret\n\t}\n\tif cfg.IPPerMinute == 0 {\n\t\tcfg.IPPerMinute = 100000\n\t}\n\tif cfg.IPRateBurst == 0 {\n\t\tcfg.IPRateBurst = 100000\n\t}\n\n\tif cfg.DBDSN == \"\" {\n\t\ttdb, db, err := dbutil.NewTestDB()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// We don't need the db handle\n\t\tif err := db.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcli.closers = append(cli.closers, tdb)\n\n\t\tcfg.DBDSN = dbutil.DefaultDataSource + \" dbname=\" + tdb.Name()\n\t}\n\n\ta, err := app.New(cfg)\n\tif err != nil {\n\t\tcli.Close()\n\t\treturn nil, err\n\t}\n\tcli.closers = append(cli.closers, a)\n\n\tcli.do = func(req *http.Request) (*http.Response, error) {\n\t\trr := httptest.NewRecorder()\n\t\ta.ServeHTTP(rr, req)\n\n\t\tresp := http.Response{\n\t\t\tStatus: fmt.Sprintf(\"%d %s\", rr.Code, http.StatusText(rr.Code)),\n\t\t\tStatusCode: rr.Code,\n\t\t\tBody: ioutil.NopCloser(rr.Body),\n\t\t\tHeader: rr.HeaderMap,\n\t\t\tContentLength: int64(rr.Body.Len()),\n\t\t\tRequest: req,\n\t\t}\n\n\t\treturn &resp, nil\n\t}\n\n\treturn &cli, nil\n}", "func (suite *KeeperTestSuite) SetupTest() {\n\tsuite.coordinator = ibctesting.NewCoordinator(suite.T(), 2)\n\tsuite.chainA = suite.coordinator.GetChain(ibctesting.GetChainID(0))\n\tsuite.chainB = suite.coordinator.GetChain(ibctesting.GetChainID(1))\n\t// commit some blocks so that QueryProof returns valid proof (cannot return valid query if height <= 1)\n\tsuite.coordinator.CommitNBlocks(suite.chainA, 2)\n\tsuite.coordinator.CommitNBlocks(suite.chainB, 2)\n}", "func (suite *KeeperTestSuite) SetupTest() {\n\tsuite.coordinator = tibctesting.NewCoordinator(suite.T(), 2)\n\tsuite.chainA = suite.coordinator.GetChain(tibctesting.GetChainID(0))\n\tsuite.chainB = suite.coordinator.GetChain(tibctesting.GetChainID(1))\n\t// commit some blocks so that QueryProof returns valid proof (cannot return valid query if height <= 1)\n\tsuite.coordinator.CommitNBlocks(suite.chainA, 2)\n\tsuite.coordinator.CommitNBlocks(suite.chainB, 2)\n}", "func (mr *MockAdminSectionRepoMockRecorder) AddSection(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddSection\", reflect.TypeOf((*MockAdminSectionRepo)(nil).AddSection), arg0, arg1)\n}", "func buildTestGrp(tBaseGrp *TestGrp, addTests []string) error {\n\tavgColStr := \"\"\n\t// add to SQLtest group from the filter tests one at a time\n\tfor _, tst := range addTests {\n\t\tif _, ok := tBaseGrp.Tests[tst]; !ok {\n\t\t\ttBaseGrp.Tests[tst] = 0 // register exist. Actual value can be used in the future\n\t\t\ttBaseGrp.TotalTest++\n\t\t\ttBaseGrp.TestParamValue[tst] = make([]interface{}, len(txTestCache[tst].Params)) // initialize the value array\n\t\t\tfor _, para := range txTestCache[tst].Params { // going through each parameter in a test\n\t\t\t\tif para.QueryType == 4 || para.QueryType == 5 { // only process the logic for SQL types of the parameter\n\t\t\t\t\t// iCol := tBaseGrp.SQLColIdx // Current group column index\n\t\t\t\t\tif len(tBaseGrp.SQLStr) == 0 {\n\t\t\t\t\t\tif para.QueryType == 5 { // process for AVG type parameter\n\t\t\t\t\t\t\tif txTestCache[tst].CustOrAcct == \"c\" {\n\t\t\t\t\t\t\t\tavgColStr = paramColMap[\"CNT(\"+para.CName+\")\"].CustCol\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tavgColStr = paramColMap[\"CNT(\"+para.CName+\")\"].AcctCol\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttBaseGrp.SQLStr += para.SqlColStr + \",\" + avgColStr\n\t\t\t\t\t\t\ttBaseGrp.EmptyRowStr += \"0,0\"\n\t\t\t\t\t\t\ttBaseGrp.GrpParamIdx[para.SqlColStr] = tBaseGrp.SQLColIdx\n\t\t\t\t\t\t\ttBaseGrp.SQLColIdx++\n\t\t\t\t\t\t\ttBaseGrp.GrpParamIdx[avgColStr] = tBaseGrp.SQLColIdx\n\t\t\t\t\t\t\ttBaseGrp.SQLColIdx++\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttBaseGrp.SQLStr += para.SqlColStr\n\t\t\t\t\t\t\ttBaseGrp.EmptyRowStr += \"0\"\n\t\t\t\t\t\t\ttBaseGrp.GrpParamIdx[para.SqlColStr] = tBaseGrp.SQLColIdx\n\t\t\t\t\t\t\ttBaseGrp.SQLColIdx++\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif _, ok := tBaseGrp.GrpParamIdx[para.SqlColStr]; !ok { // column doesn't exist\n\t\t\t\t\t\t\tif para.QueryType == 5 { // process for AVG type parameter\n\t\t\t\t\t\t\t\tif txTestCache[tst].CustOrAcct == \"c\" {\n\t\t\t\t\t\t\t\t\tavgColStr = paramColMap[\"CNT(\"+para.CName+\")\"].CustCol\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tavgColStr = paramColMap[\"CNT(\"+para.CName+\")\"].AcctCol\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif _, ok := tBaseGrp.GrpParamIdx[avgColStr]; !ok { // if the avg cnt column doesn't exist\n\t\t\t\t\t\t\t\t\ttBaseGrp.SQLStr += \",\" + para.SqlColStr + \",\" + avgColStr\n\t\t\t\t\t\t\t\t\ttBaseGrp.EmptyRowStr += \",0,0\"\n\t\t\t\t\t\t\t\t\ttBaseGrp.GrpParamIdx[para.SqlColStr] = tBaseGrp.SQLColIdx\n\t\t\t\t\t\t\t\t\ttBaseGrp.SQLColIdx++\n\t\t\t\t\t\t\t\t\ttBaseGrp.GrpParamIdx[avgColStr] = tBaseGrp.SQLColIdx\n\t\t\t\t\t\t\t\t\ttBaseGrp.SQLColIdx++\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\ttBaseGrp.SQLStr += \",\" + para.SqlColStr\n\t\t\t\t\t\t\t\t\ttBaseGrp.EmptyRowStr += \",0\"\n\t\t\t\t\t\t\t\t\ttBaseGrp.GrpParamIdx[para.SqlColStr] = tBaseGrp.SQLColIdx\n\t\t\t\t\t\t\t\t\ttBaseGrp.SQLColIdx++\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\ttBaseGrp.SQLStr += \",\" + para.SqlColStr\n\t\t\t\t\t\t\t\ttBaseGrp.EmptyRowStr += \",0\"\n\t\t\t\t\t\t\t\ttBaseGrp.GrpParamIdx[para.SqlColStr] = tBaseGrp.SQLColIdx\n\t\t\t\t\t\t\t\ttBaseGrp.SQLColIdx++\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 para.QueryType == 4 || para.QueryType == 5 { // only count period for querytype 4 or 5\n\t\t\t\t\t\tif _, ok := tBaseGrp.SQLPeriodIdx[txTestCache[tst].PeriodStr]; !ok { // column period index\n\t\t\t\t\t\t\ttBaseGrp.SQLPeriodIdx[txTestCache[tst].PeriodStr] = &PeriodIdx{txTestCache[tst].Period, -1}\n\t\t\t\t\t\t\ttBaseGrp.SQLColPeriodIdx++\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}\n\t}\n\treturn nil\n}", "func (s *JobApiTestSuite) SetupTest() {\n\tif !*runIntegrationTests {\n\t\ts.T().SkipNow()\n\t\treturn\n\t}\n\n\tif !*isDevMode {\n\t\terr := test.WaitForReady(*namespace, *initializeTimeout)\n\t\tif err != nil {\n\t\t\tglog.Exitf(\"Failed to initialize test. Error: %s\", err.Error())\n\t\t}\n\t}\n\ts.namespace = *namespace\n\n\tvar newExperimentClient func() (*api_server.ExperimentClient, error)\n\tvar newPipelineUploadClient func() (*api_server.PipelineUploadClient, error)\n\tvar newPipelineClient func() (*api_server.PipelineClient, error)\n\tvar newRunClient func() (*api_server.RunClient, error)\n\tvar newJobClient func() (*api_server.JobClient, error)\n\n\tif *isKubeflowMode {\n\t\ts.resourceNamespace = *resourceNamespace\n\n\t\tnewExperimentClient = func() (*api_server.ExperimentClient, error) {\n\t\t\treturn api_server.NewKubeflowInClusterExperimentClient(s.namespace, *isDebugMode)\n\t\t}\n\t\tnewPipelineUploadClient = func() (*api_server.PipelineUploadClient, error) {\n\t\t\treturn api_server.NewKubeflowInClusterPipelineUploadClient(s.namespace, *isDebugMode)\n\t\t}\n\t\tnewPipelineClient = func() (*api_server.PipelineClient, error) {\n\t\t\treturn api_server.NewKubeflowInClusterPipelineClient(s.namespace, *isDebugMode)\n\t\t}\n\t\tnewRunClient = func() (*api_server.RunClient, error) {\n\t\t\treturn api_server.NewKubeflowInClusterRunClient(s.namespace, *isDebugMode)\n\t\t}\n\t\tnewJobClient = func() (*api_server.JobClient, error) {\n\t\t\treturn api_server.NewKubeflowInClusterJobClient(s.namespace, *isDebugMode)\n\t\t}\n\t} else {\n\t\tclientConfig := test.GetClientConfig(*namespace)\n\n\t\tnewExperimentClient = func() (*api_server.ExperimentClient, error) {\n\t\t\treturn api_server.NewExperimentClient(clientConfig, *isDebugMode)\n\t\t}\n\t\tnewPipelineUploadClient = func() (*api_server.PipelineUploadClient, error) {\n\t\t\treturn api_server.NewPipelineUploadClient(clientConfig, *isDebugMode)\n\t\t}\n\t\tnewPipelineClient = func() (*api_server.PipelineClient, error) {\n\t\t\treturn api_server.NewPipelineClient(clientConfig, *isDebugMode)\n\t\t}\n\t\tnewRunClient = func() (*api_server.RunClient, error) {\n\t\t\treturn api_server.NewRunClient(clientConfig, *isDebugMode)\n\t\t}\n\t\tnewJobClient = func() (*api_server.JobClient, error) {\n\t\t\treturn api_server.NewJobClient(clientConfig, *isDebugMode)\n\t\t}\n\t}\n\n\tvar err error\n\ts.experimentClient, err = newExperimentClient()\n\tif err != nil {\n\t\tglog.Exitf(\"Failed to get experiment client. Error: %v\", err)\n\t}\n\ts.pipelineUploadClient, err = newPipelineUploadClient()\n\tif err != nil {\n\t\tglog.Exitf(\"Failed to get pipeline upload client. Error: %s\", err.Error())\n\t}\n\ts.pipelineClient, err = newPipelineClient()\n\tif err != nil {\n\t\tglog.Exitf(\"Failed to get pipeline client. Error: %s\", err.Error())\n\t}\n\ts.runClient, err = newRunClient()\n\tif err != nil {\n\t\tglog.Exitf(\"Failed to get run client. Error: %s\", err.Error())\n\t}\n\ts.jobClient, err = newJobClient()\n\tif err != nil {\n\t\tglog.Exitf(\"Failed to get job client. Error: %s\", err.Error())\n\t}\n\ts.swfClient = client.NewScheduledWorkflowClientOrFatal(time.Second*30, util.ClientParameters{QPS: 5, Burst: 10})\n\n\ts.cleanUp()\n}", "func (_obj *LacService) TestWithContext(ctx context.Context, _opt ...map[string]string) (ret int32, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\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\terr = _obj.s.Tars_invoke(ctx, 0, \"test\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\n\terr = _is.Read_int32(&ret, 0, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t_obj.setMap(len(_opt), _resp, _context, _status)\n\t_ = length\n\t_ = have\n\t_ = ty\n\treturn ret, nil\n}", "func TestConfig(key []byte, now time.Time) *Config {\n\treturn &Config{\n\t\tsigningKey: key,\n\t\tclock: &utils.TestClock{Time: now},\n\t}\n}", "func (p *PlainTextBuilder) CreateSection(section string) {\n\t// ˅\n\tp.buffer.WriteString(\"* \" + section + \"\\n\") // Section\n\tp.buffer.WriteString(\"\\n\") // Blank line\n\t// ˄\n}", "func makeTestKuberhealthy(t *testing.T) *Kuberhealthy {\n\tif testing.Short() {\n\t\tt.Skip()\n\t}\n\n\tkh := NewKuberhealthy()\n\n\t// override the client with a blank config\n\tconfig := &rest.Config{}\n\tclient, _ := kubernetes.NewForConfig(config)\n\tkh.overrideKubeClient = client\n\n\treturn kh\n}", "func (o *RiskRulesListAllOfData) HasIsTest() bool {\n\tif o != nil && !IsNil(o.IsTest) {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func TestCfg(url string) *Cfg {\n\tif url == \"\" {\n\t\turl = \"http://127.0.0.1/\"\n\t} else if !strings.HasSuffix(url, \"/\") {\n\t\turl += \"/\"\n\t}\n\treturn &Cfg{\n\t\tSrc: \"test\",\n\t\tEnvironment: azure.Environment{\n\t\t\tName: azure.PublicCloud.Name,\n\t\t\tManagementPortalURL: url,\n\t\t\tPublishSettingsURL: url + \"publishsettings/index\",\n\t\t\tServiceManagementEndpoint: url,\n\t\t\tResourceManagerEndpoint: url,\n\t\t\tActiveDirectoryEndpoint: url,\n\t\t\tGalleryEndpoint: url,\n\t\t\tKeyVaultEndpoint: url,\n\t\t\tGraphEndpoint: url,\n\t\t\tServiceBusEndpoint: url,\n\t\t\tBatchManagementEndpoint: url,\n\t\t\tTokenAudience: url,\n\t\t},\n\t\tTenantID: NilGUID,\n\t\tSubscriptionID: NilGUID,\n\t\tLocation: \"eastus\",\n\t\tnewAuthz: func(string) autorest.Authorizer {\n\t\t\treturn autorest.NullAuthorizer{}\n\t\t},\n\t}\n}", "func TestBuilder4(t *testing.T) {\n\tbuilder := NewBuilder(\"Ctx_\", nil)\n\tstr := \"{ \\\"nope\\\": true, \\\"key\\\":\\\"value\\\", \\\"sub\\\": { \\\"bool\\\": false }}\"\n\tstr2 := \"# test \\nnope = false \\nkey2=value2 \\t \\nsub.string = test \\n\\n\"\n\t_, err := builder.LoadJSON(strings.NewReader(str))\n\n\tif nil != err {\n\t\tt.Error(\"LoadJSON Failed\", err)\n\t}\n\tconfig, serr := builder.LoadTxt(strings.NewReader(str2))\n\n\tif nil != serr {\n\t\tt.Error(\"LoadTxt Failed\", serr)\n\t}\n\n\t// previous key should still exists\n\tstr, serr = config.GetString(\"key\")\n\tif nil != serr {\n\t\tt.Error(\"Key 'key' not found\", serr)\n\t}\n\tif \"value\" != str {\n\t\tt.Error(\"Wrong value found :\", str)\n\t}\n\n\t// previous key should still exists\n\tstr, serr = config.GetString(\"key2\")\n\tif nil != serr {\n\t\tt.Error(\"Key 'key2' not found\", serr)\n\t}\n\tif \"value2\" != str {\n\t\tt.Error(\"Wrong value found :\", str)\n\t}\n\n\t// New key should not overide existing one\n\tval, serr := config.GetBool(\"sub.bool\")\n\tif nil != serr {\n\t\tt.Error(\"Key 'sub.bool' not found\", serr)\n\t}\n\tif val {\n\t\tt.Error(\"Wrong value found :\", val)\n\t}\n\n\t// New key in sub map\n\tstr, serr = config.GetString(\"sub.string\")\n\tif nil != serr {\n\t\tt.Error(\"Key 'sub.string' not found\", serr)\n\t}\n\tif \"test\" != str {\n\t\tt.Error(\"Wrong value found :\", str)\n\t}\n\n}" ]
[ "0.6369727", "0.5422354", "0.54128635", "0.5392826", "0.5236523", "0.5211328", "0.5191266", "0.5152483", "0.5080173", "0.5068737", "0.501173", "0.49871865", "0.4952959", "0.49069577", "0.49036428", "0.48856345", "0.4885214", "0.48723263", "0.48336744", "0.4815657", "0.4802564", "0.47969773", "0.47940955", "0.47638485", "0.47529864", "0.47270977", "0.47217235", "0.46975473", "0.46597326", "0.465083", "0.46285427", "0.46266413", "0.46105978", "0.46014723", "0.45934936", "0.4586457", "0.4582638", "0.45752966", "0.45632845", "0.4561331", "0.45338276", "0.45145884", "0.4496878", "0.44780242", "0.44648957", "0.44509956", "0.44434795", "0.44427967", "0.442934", "0.4423526", "0.4413397", "0.44123253", "0.4410402", "0.43992764", "0.43871093", "0.43835565", "0.43823022", "0.4375909", "0.4373951", "0.43643013", "0.43618497", "0.4359195", "0.4355355", "0.43500635", "0.43498734", "0.43370554", "0.4323103", "0.43211237", "0.43186834", "0.43186066", "0.4315211", "0.43099257", "0.4291833", "0.42902333", "0.42879796", "0.42846817", "0.4283754", "0.42820567", "0.426783", "0.42630935", "0.42592964", "0.42568433", "0.42552727", "0.4253543", "0.42522836", "0.42507574", "0.4249162", "0.42422748", "0.42386237", "0.42344156", "0.4228271", "0.42264658", "0.4221963", "0.42197943", "0.42191112", "0.42160124", "0.421047", "0.4209174", "0.4208253", "0.42056927" ]
0.8302626
0
WithVariables add definition to the builder
func (app *applicationBuilder) WithDefinition(def DefinitionSection) ApplicationBuilder { app.def = def return app }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (builder QueryBuilder) Variable(queryBuilder QueryBuilder) QueryBuilder {\n\tbuilder.variables = append(builder.variables, queryBuilder)\n\treturn builder\n}", "func WithVariables(variables []string) CompilerOption {\n\treturn func(c *compiler) {\n\t\tc.variables = variables\n\t}\n}", "func WithVariables(variables []string) CompilerOption {\n\treturn func(c *compiler) {\n\t\tc.variables = variables\n\t}\n}", "func TestAccBuildDefinition_WithVariables(t *testing.T) {\n\tname := testutils.GenerateResourceName()\n\ttfNode := \"azuredevops_build_definition.test\"\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck: func() { testutils.PreCheck(t, nil) },\n\t\tProviders: testutils.GetProviders(),\n\t\tCheckDestroy: checkBuildDefinitionDestroyed,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: hclBuildDefinitionVariable(\"foo1\", \"bar1\", name),\n\t\t\t\tCheck: checkForVariableValues(tfNode, \"foo1\", \"bar1\"),\n\t\t\t}, {\n\t\t\t\tConfig: hclBuildDefinitionVariable(\"foo2\", \"bar2\", name),\n\t\t\t\tCheck: checkForVariableValues(tfNode, \"foo2\", \"bar2\"),\n\t\t\t},\n\t\t},\n\t})\n}", "func (b *Builder) AddVariable(varname string, typ dwarf.Offset, loc interface{}) dwarf.Offset {\n\tr := b.TagOpen(dwarf.TagVariable, varname)\n\tb.Attr(dwarf.AttrType, typ)\n\tb.Attr(dwarf.AttrLocation, loc)\n\tb.TagClose()\n\treturn r\n}", "func WithVariables(vars Variables) UnmarshalOption {\n\treturn func(d *decoder) {\n\t\td.vars = vars\n\t}\n}", "func Variables(vars map[string]string) Option {\n\treturn func(t *Task) {\n\t\tif t.Variables == nil {\n\t\t\tt.Variables = make(map[string]string)\n\t\t}\n\n\t\tfor k, v := range vars {\n\t\t\tt.Variables[k] = v\n\t\t}\n\t}\n}", "func (dec *Decoder) Variables(vars Variables) {\n\tdec.d.vars = vars\n}", "func (app *scriptCommandBuilder) WithVariable(variable string) ScriptCommandBuilder {\n\tapp.variable = variable\n\treturn app\n}", "func TestAccBuildDefinition_WithVariables_CreateAndUpdate(t *testing.T) {\n\tname := testutils.GenerateResourceName()\n\ttfNode := \"azuredevops_build_definition.build\"\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck: func() { testutils.PreCheck(t, nil) },\n\t\tProviders: testutils.GetProviders(),\n\t\tCheckDestroy: checkBuildDefinitionDestroyed,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testutils.HclBuildDefinitionWithVariables(\"foo1\", \"bar1\", name),\n\t\t\t\tCheck: checkForVariableValues(tfNode, \"foo1\", \"bar1\"),\n\t\t\t}, {\n\t\t\t\tConfig: testutils.HclBuildDefinitionWithVariables(\"foo2\", \"bar2\", name),\n\t\t\t\tCheck: checkForVariableValues(tfNode, \"foo2\", \"bar2\"),\n\t\t\t},\n\t\t},\n\t})\n}", "func (s *BaseAspidaListener) EnterVariables(ctx *VariablesContext) {}", "func (svc *ServiceDefinition) BindVariables(instance models.ServiceInstanceDetails, bindingID string, details brokerapi.BindDetails) (*varcontext.VarContext, error) {\n\tdefaults := svc.bindDefaults()\n\n\totherDetails := make(map[string]interface{})\n\tif instance.OtherDetails != \"\" {\n\t\tif err := json.Unmarshal(json.RawMessage(instance.OtherDetails), &otherDetails); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tappGuid := \"\"\n\tif details.BindResource != nil {\n\t\tappGuid = details.BindResource.AppGuid\n\t}\n\n\t// The namespaces of these values roughly align with the OSB spec.\n\tconstants := map[string]interface{}{\n\t\t// specified in the URL\n\t\t\"request.binding_id\": bindingID,\n\t\t\"request.instance_id\": instance.ID,\n\n\t\t// specified in the request body\n\t\t// Note: the value in instance is considered the official record so values\n\t\t// are pulled from there rather than the request. In a future version of OSB\n\t\t// the duplicate sending of fields is likely to be removed.\n\t\t\"request.plan_id\": instance.PlanId,\n\t\t\"request.service_id\": instance.ServiceId,\n\t\t\"request.app_guid\": appGuid,\n\n\t\t// specified by the existing instance\n\t\t\"instance.name\": instance.Name,\n\t\t\"instance.details\": otherDetails,\n\t}\n\n\treturn varcontext.Builder().\n\t\tSetEvalConstants(constants).\n\t\tMergeMap(svc.BindDefaultOverrides()).\n\t\tMergeJsonObject(details.GetRawParameters()).\n\t\tMergeDefaults(defaults).\n\t\tMergeDefaults(svc.BindComputedVariables).\n\t\tBuild()\n}", "func (ic *InstanceCreate) AddVars(v ...*VarRef) *InstanceCreate {\n\tids := make([]uuid.UUID, len(v))\n\tfor i := range v {\n\t\tids[i] = v[i].ID\n\t}\n\treturn ic.AddVarIDs(ids...)\n}", "func (p *PKGBUILD) AddVariable(name string, array bool, values ...string) (info *atom.Info, ok bool) {\n\tif ok = len(name) > 0 && runes.CheckString(name, runes.IsAlphaNum); !ok {\n\t\treturn\n\t}\n\tvar a *atom.AtomVar\n\tif array {\n\t\ta = atom.NewArrayVar()\n\t} else {\n\t\ta = atom.NewStringVar()\n\t}\n\ta.SetName(name)\n\tb := position.Position{Line: 1}\n\tif l := len(p.atoms); l > 0 {\n\t\tb = atom.GetEnd(p.atoms[l-1]).Next('\\n')\n\t}\n\te := b.NextString(name)\n\ta.SetNamePositions(b, e)\n\tif e, ok = setValues(a, values...); !ok {\n\t\treturn\n\t}\n\ta.SetPositions(b, e)\n\ta.RecomputRaw()\n\tp.atoms.Push(a)\n\tp.RecomputeInfos(true)\n\treturn p.info.Get(a)\n}", "func (this *Actions) AddVariable(key, value string) {\n\tthis.Variables[key] = value\n}", "func (r *Response) buildInVars(params ...map[string]interface{}) map[string]interface{} {\n\tm := gutil.MapMergeCopy(r.Request.viewParams)\n\tif len(params) > 0 {\n\t\tgutil.MapMerge(m, params[0])\n\t}\n\t// Retrieve custom template variables from request object.\n\tsessionMap := gconv.MapDeep(r.Request.Session.MustData())\n\tgutil.MapMerge(m, map[string]interface{}{\n\t\t\"Form\": r.Request.GetFormMap(),\n\t\t\"Query\": r.Request.GetQueryMap(),\n\t\t\"Request\": r.Request.GetMap(),\n\t\t\"Cookie\": r.Request.Cookie.Map(),\n\t\t\"Session\": sessionMap,\n\t})\n\t// Note that it should assign no Config variable to a template\n\t// if there's no configuration file.\n\tif v, _ := gcfg.Instance().Data(r.Request.Context()); len(v) > 0 {\n\t\tm[\"Config\"] = v\n\t}\n\treturn m\n}", "func WithVars(ctx context.Context, vars map[string]string) context.Context {\n\treturn context.WithValue(ctx, varsKey, vars)\n}", "func WithVars(ctx context.Context, vars map[string]string) context.Context {\n\treturn context.WithValue(ctx, varsKey, vars)\n}", "func Variable(rootQueryFn *FilterFn) QueryBuilder {\n\tquery := Query(rootQueryFn)\n\tquery.rootEdge.IsVariable = true\n\treturn query\n}", "func (t Task) Variables(\n\tctx context.Context,\n\tafter *string,\n\tbefore *string,\n\tfirst *int,\n\tlast *int,\n) (VariableConnection, error) {\n\treturn PaginateVariableIDSliceContext(ctx, t.VariableIDs, after, before, first, last)\n}", "func (b *builder) With(feat string) FeaturesBuilder {\n\tkv := strings.Split(feat, \":\")\n\tif len(kv) == 1 {\n\t\tkey := strings.TrimSpace(kv[0])\n\t\tif key == \"\" {\n\t\t\treturn b\n\t\t}\n\t\tb.fs[key] = \"\"\n\t} else if len(kv) == 2 {\n\t\tkey := strings.TrimSpace(kv[0])\n\t\tval := strings.TrimSpace(kv[1])\n\t\tif key == \"\" {\n\t\t\treturn b\n\t\t}\n\t\tb.fs[key] = val\n\t}\n\treturn b\n}", "func (p *Planner) addVariableDefinitionsRecursively(value ast.Value, sourcePath []string, fieldName []byte) {\n\tswitch value.Kind {\n\tcase ast.ValueKindObject:\n\t\tprevArgTypeRef := p.argTypeRef\n\t\tp.argTypeRef = p.resolveNestedArgumentType(fieldName)\n\t\tfor _, objectFieldRef := range p.visitor.Operation.ObjectValues[value.Ref].Refs {\n\t\t\tp.addVariableDefinitionsRecursively(p.visitor.Operation.ObjectFields[objectFieldRef].Value, sourcePath, p.visitor.Operation.ObjectFieldNameBytes(objectFieldRef))\n\t\t}\n\t\tp.argTypeRef = prevArgTypeRef\n\t\treturn\n\tcase ast.ValueKindList:\n\t\tfor _, i := range p.visitor.Operation.ListValues[value.Ref].Refs {\n\t\t\tp.addVariableDefinitionsRecursively(p.visitor.Operation.Values[i], sourcePath, nil)\n\t\t}\n\t\treturn\n\tcase ast.ValueKindVariable:\n\t\t// continue after switch\n\tdefault:\n\t\treturn\n\t}\n\n\tvariableName := p.visitor.Operation.VariableValueNameBytes(value.Ref)\n\tvariableNameStr := p.visitor.Operation.VariableValueNameString(value.Ref)\n\tvariableDefinition, exists := p.visitor.Operation.VariableDefinitionByNameAndOperation(p.visitor.Walker.Ancestors[0].Ref, variableName)\n\tif !exists {\n\t\treturn\n\t}\n\timportedVariableDefinition := p.visitor.Importer.ImportVariableDefinition(variableDefinition, p.visitor.Operation, p.upstreamOperation)\n\tp.upstreamOperation.AddImportedVariableDefinitionToOperationDefinition(p.nodes[0].Ref, importedVariableDefinition)\n\n\tfieldType := p.resolveNestedArgumentType(fieldName)\n\tcontextVariable := &resolve.ContextVariable{\n\t\tPath: append(sourcePath, variableNameStr),\n\t\tRenderAsGraphQLValue: true,\n\t}\n\tcontextVariable.SetJsonValueType(p.visitor.Definition, p.visitor.Definition, fieldType)\n\n\tcontextVariableName, variableExists := p.variables.AddVariable(contextVariable)\n\tif variableExists {\n\t\treturn\n\t}\n\tp.upstreamVariables, _ = sjson.SetRawBytes(p.upstreamVariables, variableNameStr, []byte(contextVariableName))\n}", "func (app *specificTokenCodeBuilder) WithVariableName(variableName string) SpecificTokenCodeBuilder {\n\tapp.variableName = variableName\n\treturn app\n}", "func (ctb *CreateTableBuilder) Define(def ...string) *CreateTableBuilder {\n\tctb.defs = append(ctb.defs, def)\n\tctb.marker = createTableMarkerAfterDefine\n\treturn ctb\n}", "func (wq *WorkflowQuery) WithVars(opts ...func(*VarRefQuery)) *WorkflowQuery {\n\tquery := &VarRefQuery{config: wq.config}\n\tfor _, opt := range opts {\n\t\topt(query)\n\t}\n\twq.withVars = query\n\treturn wq\n}", "func (l *configLoader) FillVariables(preparedConfig map[interface{}]interface{}, vars []*latest.Variable) error {\n\t// Find out what vars are really used\n\tvarsUsed := map[string]bool{}\n\terr := walk.Walk(preparedConfig, varMatchFn, func(path, value string) (interface{}, error) {\n\t\tvarspkg.ParseString(value, func(v string) (interface{}, error) {\n\t\t\tvarsUsed[v] = true\n\t\t\treturn \"\", nil\n\t\t})\n\n\t\treturn value, nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Parse cli --var's\n\tvarsParsed, err := ParseVarsFromOptions(l.options)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Fill used defined variables\n\tif len(vars) > 0 {\n\t\tnewVars := []*latest.Variable{}\n\t\tfor _, variable := range vars {\n\t\t\tif varsUsed[strings.TrimSpace(variable.Name)] {\n\t\t\t\tnewVars = append(newVars, variable)\n\t\t\t}\n\t\t}\n\n\t\tif len(newVars) > 0 {\n\t\t\terr = l.askQuestions(newVars, varsParsed)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Walk over data and fill in variables\n\tl.resolvedVars = map[string]string{}\n\terr = walk.Walk(preparedConfig, varMatchFn, func(path, value string) (interface{}, error) {\n\t\treturn l.VarReplaceFn(path, value, varsParsed)\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DeclareVariables() {\r\n // OK\r\n word := 1\r\n multipleWords := 2\r\n // Not OK\r\n multiplewords\r\n multiple_words\r\n}", "func fillVariableMap() {\n\tvariableMap = make(map[string]string)\n\t// add regular variables, if any\n\tfor _, v := range *variables {\n\t\ts := strings.SplitN(v, \"=\", 2)\n\t\tvariableMap[s[0]] = s[1]\n\t}\n\t// add JSON variables, if provided\n\tif *jsonPath != \"\" {\n\t\t// JSON parameter provided\n\t\tif jsonFile, err := os.Open(*jsonPath); err != nil {\n\t\t\t// parse JSON file\n\t\t\tif err := json.NewDecoder(jsonFile).Decode(&variableMap); err != nil {\n\t\t\t\tfmt.Printf(\"Error parsing JSON: %v\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t} else {\n\t\t\t// something went wrong opening the file\n\t\t\tfmt.Printf(\"Could not open the JSON file at %v: %v\\n\", jsonPath, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\t// add YAML variables, if provided\n\tif *yamlPath != \"\" {\n\t\t// YAML parameter provided\n\t\tif content, err := ioutil.ReadFile(*yamlPath); err == nil {\n\t\t\t// read file\n\t\t\t// parse YAML file\n\t\t\tif err := yaml.Unmarshal(content, &variableMap); err != nil {\n\t\t\t\tfmt.Printf(\"Error parsing YAML: %v\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t} else {\n\t\t\t// something went wrong opening the file\n\t\t\tfmt.Printf(\"Could not open the YAML file at %v: %v\\n\", yamlPath, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func WithVars(vars starlark.StringDict) ExecOption {\n\treturn fnExecOption(func(opts *execOptions) {\n\t\tfor key, value := range vars {\n\t\t\topts.vars.SetKey(starlark.String(key), value)\n\t\t}\n\t})\n}", "func (s *BasevhdlListener) EnterVariable_declaration(ctx *Variable_declarationContext) {}", "func (ctb *CreateTableBuilder) Var(arg interface{}) string {\n\treturn ctb.args.Add(arg)\n}", "func (c *Variable) Set(tmpl, ts string, e ...Entry) error {\n var err error\n\n if len(e) == 0 {\n return nil\n } else if tmpl == \"\" && ts == \"\" {\n return fmt.Errorf(\"tmpl or ts must be specified\")\n }\n\n _, fn := c.versioning()\n names := make([]string, len(e))\n\n // Build up the struct with the given configs.\n d := util.BulkElement{XMLName: xml.Name{Local: \"variable\"}}\n for i := range e {\n d.Data = append(d.Data, fn(e[i]))\n names[i] = e[i].Name\n }\n c.con.LogAction(\"(set) template variables: %v\", names)\n\n // Set xpath.\n path := c.xpath(tmpl, ts, names)\n if len(e) == 1 {\n path = path[:len(path) - 1]\n } else {\n path = path[:len(path) - 2]\n }\n\n // Create the template variables.\n _, err = c.con.Set(path, d.Config(), nil, nil)\n return err\n}", "func (g *GraphQL) QueryWithVars(ctx context.Context, command string, queryString string, queryVars map[string]interface{}, response interface{}) error {\n\trequest := struct {\n\t\tQuery string `json:\"query\"`\n\t\tVariables map[string]interface{} `json:\"variables\"`\n\t}{\n\t\tQuery: queryString,\n\t\tVariables: queryVars,\n\t}\n\n\tvar b bytes.Buffer\n\tif err := json.NewEncoder(&b).Encode(request); err != nil {\n\t\treturn fmt.Errorf(\"graphql encoding error: %w\", err)\n\t}\n\n\treturn g.Do(ctx, command, &b, response)\n}", "func (c *swagJoiner) AddDefinition(buf []byte) error {\n\tdef := map[string]interface{}{}\n\n\terr := json.Unmarshal(buf, &def)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"couldn't unmarshal JSON def\")\n\t}\n\tif c.result == nil {\n\t\tc.result = def\n\t}\n\n\tpaths, _ := def[\"paths\"].(map[string]interface{})\n\tstructs, _ := def[\"definitions\"].(map[string]interface{})\n\tif c.paths == nil {\n\t\tc.paths = paths\n\t\tc.defs = structs\n\t\treturn nil\n\t}\n\tfor path, sym := range paths {\n\t\tc.paths[path] = sym\n\t}\n\tfor name, s := range structs {\n\t\tc.defs[name] = s\n\t}\n\treturn nil\n}", "func (f *FilterParams) AddVariable(nv string) {\n\tfor _, v := range f.Variables {\n\t\tif v == nv {\n\t\t\treturn\n\t\t}\n\t}\n\tf.Variables = append(f.Variables, nv)\n}", "func (r *Room) SetVariables(values map[string]interface{}) {\n\tr.mux.Lock()\n\tif r.usersMap == nil {\n\t\tr.mux.Unlock()\n\t\treturn\n\t}\n\tfor key, val := range values {\n\t\tr.vars[key] = val\n\t}\n\tr.mux.Unlock()\n\n\t//\n\treturn\n}", "func Builder() builder {\n\treturn builder{\n\t\tfields: make(map[string]interface{}),\n\t\tcontextFields: make(map[string]interface{}),\n\t}\n}", "func (p *Parser) varadd(defs *oop.DefMap, inf varInfo, tokens []obj.Token) {\n\tnameTk := tokens[0]\n\tif !isValidName(nameTk.Val) {\n\t\tfract.IPanic(nameTk, obj.SyntaxPanic, \"Invalid name!\")\n\t}\n\t// Name is already defined?\n\tvar ln int\n\tif &p.defs == defs { // Variable added to defmap of parser.\n\t\tln = p.defIndexByName(nameTk.Val)\n\t} else { // Variable added to another defmap.\n\t\tln = defs.DefIndexByName(nameTk.Val)\n\t}\n\tif ln != -1 {\n\t\tfract.IPanic(nameTk, obj.NamePanic, \"\\\"\"+nameTk.Val+\"\\\" is already defined at line: \"+fmt.Sprint(ln))\n\t}\n\n\ttokensLen := len(tokens)\n\t// Setter is not defined?\n\tif tokensLen < 2 {\n\t\tfract.IPanicC(nameTk.File, nameTk.Line, nameTk.Column+len(nameTk.Val), obj.SyntaxPanic, \"Setter is not found!\")\n\t}\n\tsetter := tokens[1]\n\t// Setter is not a setter operator?\n\tif setter.Type != fract.Operator || (setter.Val != \"=\" && !inf.shortDeclaration || setter.Val != \":=\" && inf.shortDeclaration) {\n\t\tfract.IPanic(setter, obj.SyntaxPanic, \"Invalid setter operator: \"+setter.Val)\n\t}\n\t// Value is not defined?\n\tif tokensLen < 3 {\n\t\tfract.IPanicC(setter.File, setter.Line, setter.Column+len(setter.Val), obj.SyntaxPanic, \"Value is not given!\")\n\t}\n\tval := *p.processValTokens(tokens[2:])\n\tif val.Data == nil {\n\t\tfract.IPanic(tokens[2], obj.ValuePanic, \"Invalid value!\")\n\t}\n\tif p.funcTempVars != -1 {\n\t\tp.funcTempVars++\n\t}\n\tval.Mut = inf.mut\n\tval.Const = inf.constant\n\tdefs.Vars = append(defs.Vars, oop.Var{\n\t\tName: nameTk.Val,\n\t\tVal: val,\n\t\tLine: nameTk.Line,\n\t})\n}", "func (l *Loader) Variables() map[string]interface{} {\n\treturn l.cache.BuildContext().Variables\n}", "func (s *BaseAspidaListener) EnterVarDef(ctx *VarDefContext) {}", "func (t *Task) MergeVariables(vars map[string]string) {\n\tfor k, v := range vars {\n\t\tt.Variables[k] = v\n\t}\n}", "func Variables() {\n\tvar i int\n\tfmt.Println(i, c, python, java)\n}", "func (a *AllColumnsSelector) Variable() {}", "func (svc *ServiceDefinition) ProvisionVariables(instanceId string, details brokerapi.ProvisionDetails, plan ServicePlan) (*varcontext.VarContext, error) {\n\tdefaults := svc.provisionDefaults()\n\n\t// The namespaces of these values roughly align with the OSB spec.\n\tconstants := map[string]interface{}{\n\t\t\"request.plan_id\": details.PlanID,\n\t\t\"request.service_id\": details.ServiceID,\n\t\t\"request.instance_id\": instanceId,\n\t\t\"request.default_labels\": utils.ExtractDefaultLabels(instanceId, details),\n\t}\n\n\treturn varcontext.Builder().\n\t\tSetEvalConstants(constants).\n\t\tMergeMap(svc.ProvisionDefaultOverrides()).\n\t\tMergeJsonObject(details.GetRawParameters()).\n\t\tMergeDefaults(defaults).\n\t\tMergeMap(plan.GetServiceProperties()).\n\t\tMergeDefaults(svc.ProvisionComputedVariables).\n\t\tBuild()\n}", "func (a *api) DefineVar(name string, x *big.Int) {\n\ta.Printf(\"var %s = %s\", a.Name(name), a.Type())\n\ta.ByteArrayValue(bigint.BytesLittleEndian(x))\n}", "func (it *Logger) With(keysAndValues ...interface{}) (log *Logger) {\n\tlog = new(Logger)\n\tlog.level = it.level\n\tlog.sugar = it.sugar.With(keysAndValues...)\n\treturn\n}", "func newVarDeclaration(variable *Param) *Instruction {\n\treturn &Instruction{\n\t\tType: VarDeclarationInst,\n\t\tName: variable.Name,\n\t\tVariable: variable,\n\t}\n}", "func (s *BasePlSqlParserListener) EnterVariable_declaration(ctx *Variable_declarationContext) {}", "func (t *Target) Define(arguments int, body usm.Block) usm.Label {\n\tt.Labels++\n\n\tvar args = make([]string, arguments)\n\tfor i := 0; i < arguments; i++ {\n\t\targs[i] = fmt.Sprintf(\"a%v\", i)\n\t}\n\n\tvar backup = t.Buffer\n\tvar old = t.Tabs\n\tt.Tabs = 0\n\n\tt.Buffer = bytes.Buffer{}\n\n\tif arguments > 0 {\n\t\tt.WriteStatement(\"func f%v(r *Runtime, %v Value) {\\n\", t.Labels, strings.Join(args, \",\"))\n\t} else {\n\t\tt.WriteStatement(\"func f%v(r *Runtime) {\\n\", t.Labels)\n\t}\n\n\tt.Indent(body)\n\n\tt.WriteStatement(\"}\\n\")\n\n\tt.Head.Write(t.Buffer.Bytes())\n\n\tt.Tabs = old\n\tt.Buffer = backup\n\n\treturn t.Labels\n}", "func MakeVariableRef(explode bool, ns string, name string) string {\n\tprefix := \"\"\n\tif explode {\n\t\tprefix = \"@\"\n\t}\n\tif ns != \"\" {\n\t\tprefix += ns + \":\"\n\t}\n\treturn prefix + name\n}", "func (s *BaserpnListener) EnterVariable(ctx *VariableContext) {}", "func (bo BinaryOperator) Variables() []string {\n\tset := make(map[string]struct{})\n\tfor _, x := range bo.Left.Variables() {\n\t\tset[x] = struct{}{}\n\t}\n\tfor _, x := range bo.Right.Variables() {\n\t\tset[x] = struct{}{}\n\t}\n\tattrs := make([]string, 0, len(set))\n\tfor x := range set {\n\t\tattrs = append(attrs, x)\n\t}\n\treturn attrs\n}", "func (ub *UpdateBuilder) Add(field string, value interface{}) string {\n\tf := Escape(field)\n\treturn fmt.Sprintf(\"%s = %s + %s\", f, f, ub.args.Add(value))\n}", "func (s *BaseGraffleParserListener) EnterVariable(ctx *VariableContext) {}", "func (e *Environment) Define(name string, value interface{}) {\n\te.Values[name] = value\n}", "func (s *BaseLittleDuckListener) EnterVars(ctx *VarsContext) {}", "func (args *Arguments) define() {\n\n\tflag.BoolVar(\n\t\t&args.Version,\n\t\t\"Version\",\n\t\tfalse,\n\t\t\"Prints the version number of this utility and exits.\",\n\t)\n\n\tflag.BoolVar(\n\t\t&args.Licence,\n\t\t\"Licence\",\n\t\tfalse,\n\t\t\"Prints the copyright licence this software is released under.\",\n\t)\n\n\tflag.BoolVar(\n\t\t&args.AllProblems,\n\t\t\"AllProblems\",\n\t\tfalse,\n\t\t\"Answer all problems for which there is code.\",\n\t)\n\n\tflag.UintVar(\n\t\t&args.Problem,\n\t\t\"Problem\",\n\t\t0,\n\t\t\"Numeric Id of problem as per Projecteuler.net\",\n\t)\n\n\tflag.BoolVar(\n\t\t&args.Concurrent,\n\t\t\"Concurrent\",\n\t\tfalse,\n\t\t\"Solves problems concurrently (may be faster)\",\n\t)\n\n\tflag.Usage = usageMessage\n\n\tflag.Parse()\n}", "func (s *BasearithmeticListener) EnterVariable(ctx *VariableContext) {}", "func (t *targetBuilder) addVisibility(visibility string) *targetBuilder {\n\tt.visibility.Add(visibility)\n\treturn t\n}", "func (ic *InstanceCreate) AddVarIDs(ids ...uuid.UUID) *InstanceCreate {\n\tic.mutation.AddVarIDs(ids...)\n\treturn ic\n}", "func (d *Definition) UpdateWith(other Definition) {\n\tif len(other.Arn) > 0 {\n\t\td.Arn = other.Arn\n\t}\n\tif len(other.DefinitionID) > 0 {\n\t\td.DefinitionID = other.DefinitionID\n\t}\n\tif len(other.Image) > 0 {\n\t\td.Image = other.Image\n\t}\n\tif len(other.GroupName) > 0 {\n\t\td.GroupName = other.GroupName\n\t}\n\tif len(other.ContainerName) > 0 {\n\t\td.ContainerName = other.ContainerName\n\t}\n\tif len(other.User) > 0 {\n\t\td.User = other.User\n\t}\n\tif len(other.Alias) > 0 {\n\t\td.Alias = other.Alias\n\t}\n\tif other.Memory != nil {\n\t\td.Memory = other.Memory\n\t}\n\tif other.Gpu != nil {\n\t\td.Gpu = other.Gpu\n\t}\n\tif other.Cpu != nil {\n\t\td.Cpu = other.Cpu\n\t}\n\tif other.AdaptiveResourceAllocation != nil {\n\t\td.AdaptiveResourceAllocation = other.AdaptiveResourceAllocation\n\t}\n\tif len(other.Command) > 0 {\n\t\td.Command = other.Command\n\t}\n\tif len(other.TaskType) > 0 {\n\t\td.TaskType = other.TaskType\n\t}\n\tif other.Env != nil {\n\t\td.Env = other.Env\n\t}\n\tif other.Ports != nil {\n\t\td.Ports = other.Ports\n\t}\n\tif other.Tags != nil {\n\t\td.Tags = other.Tags\n\t}\n\tif other.Privileged != nil {\n\t\td.Privileged = other.Privileged\n\t}\n}", "func (b *BaseHandler) setVars(v map[string]string, w http.ResponseWriter, req *http.Request) {\n\tb.Vars = v\n\tb.response = w\n\tb.request = req\n}", "func (c *AccountsContainersVariablesCreateCall) Fields(s ...googleapi.Field) *AccountsContainersVariablesCreateCall {\n\tc.params_.Set(\"fields\", googleapi.CombineFields(s))\n\treturn c\n}", "func applyVariablesFromContext(filter string, ctx map[string]interface{}) (string, []interface{}) {\n\tre := regexp.MustCompile(\"\\\\$[a-zA-Z_]+\")\n\tvar args []interface{}\n\tapplied := re.ReplaceAllStringFunc(filter, func (match string) string {\n\t\tmapping, ok := ctx[match[1:]] // skip $ prefix\n\t\tif mapping == nil || !ok {\n\t\t\targs = append(args, nil)\n\t\t} else {\n\t\t\targs = append(args, mapping)\t\t\t\n\t\t}\n\n\t\t{{ if database.dialect == \"postgres\" }}\n\t\treturn fmt.Sprintf(\"$%d\", len(args))\n\t\t{{ else if database.dialect == \"mysql\" || database.dialect == \"sqlite\" }}\n\t\treturn \"?\"\n\t\t{{ end }}\n\t})\n\n\treturn applied, args\n}", "func (s *BaseLittleDuckListener) EnterVars_more(ctx *Vars_moreContext) {}", "func (s *BasevhdlListener) EnterInterface_variable_declaration(ctx *Interface_variable_declarationContext) {\n}", "func (lb *Leaderboard) Variables() *VariableCollection {\n\treturn toVariableCollection(lb.VariablesData)\n}", "func NewVariables() *Variables {\n\treturn &Variables{\n\t\tm: make(map[Variablename]Variable),\n\t}\n}", "func (l *MemoryLogger) With(keyvals ...interface{}) log.Logger {\n\tlogger := &MemoryLogger{\n\t\tlines: l.lines,\n\t}\n\n\tif l.globalKeyvals != \"\" {\n\t\tlogger.globalKeyvals = l.globalKeyvals + \" \"\n\t}\n\n\tlogger.globalKeyvals += strings.TrimSuffix(fmt.Sprintln(keyvals...), \"\\n\")\n\n\treturn logger\n}", "func (g *Game) Variables(sort *Sorting) (*VariableCollection, *Error) {\n\tif g.VariablesData == nil {\n\t\treturn fetchVariablesLink(firstLink(g, \"variables\"), nil, sort)\n\t}\n\n\treturn toVariableCollection(g.VariablesData), nil\n}", "func NewVariables(lc logger.LoggingClient) *Variables {\n\tosEnv := os.Environ()\n\te := &Variables{\n\t\tvariables: make(map[string]string, len(osEnv)),\n\t\tlc: lc,\n\t}\n\n\tfor _, env := range osEnv {\n\t\t// Can not use Split() on '=' since the value may have an '=' in it, so changed to use Index()\n\t\tindex := strings.Index(env, \"=\")\n\t\tif index == -1 {\n\t\t\tcontinue\n\t\t}\n\t\tkey := env[:index]\n\t\tvalue := env[index+1:]\n\t\te.variables[key] = value\n\t}\n\n\treturn e\n}", "func (b *TaskBuilder) With(params interface{}) *TaskBuilder {\n\tb.Params = params\n\treturn b\n}", "func (b *Builder) WithLabels(labels map[string]string) *Builder {\n\tif len(labels) == 0 {\n\t\tb.errs = append(\n\t\t\tb.errs,\n\t\t\terrors.New(\"failed to build PVC object: missing labels\"),\n\t\t)\n\t\treturn b\n\t}\n\n\tif b.pvc.object.Labels == nil {\n\t\tb.pvc.object.Labels = map[string]string{}\n\t}\n\n\tfor key, value := range labels {\n\t\tb.pvc.object.Labels[key] = value\n\t}\n\treturn b\n}", "func (model *Model) AddVar(vtype int8, obj float64, lb float64, ub float64, name string, constrs []*Constr, columns []float64) (*Var, error) {\n\tif model == nil {\n\t\treturn nil, errors.New(\"model is not initialized\")\n\t}\n\n\tif len(constrs) != len(columns) {\n\t\treturn nil, errors.New(\"either the length of constrs or columns are wrong\")\n\t}\n\n\tind := make([]int32, len(constrs), 0)\n\tfor i, c := range constrs {\n\t\tif c.idx < 0 {\n\t\t\treturn nil, errors.New(\"Invalid index in constrs\")\n\t\t}\n\t\tind[i] = c.idx\n\t}\n\n\tpind := (*C.int)(nil)\n\tpval := (*C.double)(nil)\n\tif len(ind) > 0 {\n\t\tpind = (*C.int)(&ind[0])\n\t\tpval = (*C.double)(&columns[0])\n\t}\n\n\terr := C.GRBaddvar(model.model, C.int(len(constrs)), pind, pval, C.double(obj), C.double(lb), C.double(ub), C.char(vtype), C.CString(name))\n\tif err != 0 {\n\t\treturn nil, model.makeError(err)\n\t}\n\n\tif err := model.Update(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmodel.vars = append(model.vars, Var{model, int32(len(model.vars))})\n\treturn &model.vars[len(model.vars)-1], nil\n}", "func addEnv(s *scope, arg pyObject, target *core.BuildTarget) {\n\tenvPy, ok := asDict(arg)\n\ts.Assert(ok, \"env must be a dict\")\n\n\tenv := make(map[string]string, len(envPy))\n\tfor name, val := range envPy {\n\t\tv, ok := val.(pyString)\n\t\ts.Assert(ok, \"Values of env must be strings, found %v at key %v\", val.Type(), name)\n\t\tenv[name] = string(v)\n\t}\n\n\ttarget.Env = env\n}", "func (f *Figurator) With(hooks ...Hooks) *Figurator {\n\tmerged := Hooks{}\n\tfor _, partial := range hooks {\n\t\tfor key, hook := range partial {\n\t\t\tmerged[key] = hook\n\t\t}\n\t}\n\tf.hooks = merged\n\treturn f\n}", "func (e *Env) Define(k string, v interface{}) error {\n\t// builtin\n\tbt := reflect.TypeOf(e.builtin).Elem()\n\tif _, ok := bt.FieldByName(k); ok && k == strings.ToUpper(k) {\n\t\t//if _, ok := bt.FieldByName(k); ok {\n\t\treturn fmt.Errorf(\"cannot define builtin variable '%v'\", k)\n\t}\n\tif isGlobalVarName(k) {\n\t\t// global var\n\t\te.global[k] = v\n\t} else {\n\t\t// local var\n\t\te.env[k] = v\n\t}\n\treturn nil\n}", "func (gf *genericFramework) Env(key, value string) error {\n\tif gf.adam.Variables == nil {\n\t\tgf.adam.Variables = jsonutil.NewVariableMap(\"\", nil)\n\t}\n\tif _, ok := gf.adam.Variables.Get(key); ok {\n\t\treturn fmt.Errorf(\"%v has been defined\", key)\n\t}\n\tgf.adam.Variables.Set(key, jsonutil.NewStringVariable(key, value))\n\treturn nil\n}", "func (s *BasejossListener) EnterVariable(ctx *VariableContext) {}", "func NewVariable(managementDirPath, dataDirectoryName, projectName, goPath, goRootPath string) *Variable {\n\tv := &Variable{\n\t\tManagementDirectoryPath: managementDirPath,\n\t\tDataDirectoryName: dataDirectoryName,\n\t\tProjectName: projectName,\n\t\tGoPath: goPath,\n\t\tGoRootPath: goRootPath}\n\n\treturn v\n}", "func (e *Environment) Define(name string, value interface{}, index int) {\n\tif index == -1 {\n\t\te.values[name] = value\n\t} else {\n\t\te.indexedValues[index] = value\n\t}\n}", "func (vs *Variables) Register(s string) Variable {\n\tvn := VariablenameParse(s)\n\treturn vs.Variable(vn)\n}", "func (pc *programCode) initVar(s, k string) {\n\tpc.code += \"\\tmov rax, \" + k + \"\\t; newVar \\n\\tmov [\" + s + \"], rax\\n\" // start with these instructions\n}", "func Var(name string) Formula {\n\treturn pbVar(name)\n}", "func (s *BasemumpsListener) EnterVariable(ctx *VariableContext) {}", "func Builder(dataset string) *libhoney.Builder {\n\tb := libhoney.NewBuilder()\n\tb.Dataset = dataset\n\treturn b\n}", "func (a *PipelineControllerApiService) EvaluateVariablesUsingPOST(ctx _context.Context) apiEvaluateVariablesUsingPOSTRequest {\n\treturn apiEvaluateVariablesUsingPOSTRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (v *View) WithDefinition(def Node) *View {\n\tret := *v\n\tret.definition = def\n\treturn &ret\n}", "func (s *BaseLittleDuckListener) EnterPrograma_vars(ctx *Programa_varsContext) {}", "func (pc *programCode) addVar(name string, val int64) {\n\t// the following line checks if an element exists inside the map element.\n\tif _, ok := pc.intMap[name]; ok {\n\t\tpc.setVar(name, val)\n\t} else {\n\t\tpc.intMap[name] = val\n\t}\n\n}", "func main(){\n\n \n var (\n a = 5\n b = 10\n c = \"Helo World\"\n\n )\n\n fmt.Println(a, b, c)\n}", "func (txn *tikvTxn) SetVars(vars interface{}) {\n\tif vs, ok := vars.(*tikv.Variables); ok {\n\t\ttxn.KVTxn.SetVars(vs)\n\t}\n}", "func (r *RoomUser) SetVariables(values map[string]interface{}, connID string) {\n\tif multiConnect && len(connID) == 0 {\n\t\treturn\n\t} else if !multiConnect {\n\t\tconnID = \"1\"\n\t}\n\t(*r.mux).Lock()\n\tif conn, ok := r.conns[connID]; ok {\n\t\tfor key, val := range values {\n\t\t\t(*(*conn).vars)[key] = val\n\t\t}\n\t}\n\t(*r.mux).Unlock()\n}", "func newVariable(name, paramType string) *Param {\n\treturn &Param{\n\t\tParameterKind: variable,\n\t\tName: name,\n\t\tParameterType: paramType,\n\t}\n}", "func (c Command) WithFunc(name string, function interface{}) *Builder {\n\tb := c.builder()\n\tb.funcs[name] = function\n\treturn b\n}", "func (a *Aliases) Define(gvr string, aliases ...string) {\n\ta.mx.Lock()\n\tdefer a.mx.Unlock()\n\n\t// BOZO!! Could not get full events struct using this api group??\n\tif gvr == \"events.k8s.io/v1/events\" || gvr == \"extensions/v1beta1\" {\n\t\treturn\n\t}\n\n\tfor _, alias := range aliases {\n\t\tif _, ok := a.Alias[alias]; ok {\n\t\t\tcontinue\n\t\t}\n\t\ta.Alias[alias] = gvr\n\t}\n}", "func (c *Configurator) Var(value Value, name string, usage string) {\n\tc.env().Var(value, name, usage)\n\tc.flag().Var(value, name, usage)\n}", "func (i *Interpreter) tryToAddVars(w *eval.World, fileSet *token.FileSet, vars []string) {\n\tfor _, name := range vars {\n\t\t_, err := w.Compile(fileSet, name /*sourceCode*/)\n\t\tif err == nil {\n\t\t\t// The variable exists, add its name to 'i.vars'\n\t\t\ti.vars[name] = true\n\t\t} else {\n\t\t\t// Ignore the error. Conclude that no such variable exists.\n\t\t}\n\t}\n}", "func VariablesPrefix(vars []Variable, prefix string) []Variable {\n\tres := make([]Variable, len(vars))\n\tfor i := range vars {\n\t\ts := vars[i]\n\t\ts.Name = prefix + s.Name\n\t\tres[i] = s\n\t}\n\treturn res\n}", "func setVariables(args []Any, env *environment.Env) (Any, error) {\n\tvar val Any\n\n\tn := len(args)\n\tif (n % 2) != 0 {\n\t\treturn nil, fmt.Errorf(\"invalid variable bindings %v\", args)\n\t}\n\n\tfor i := 0; i < n; i += 2 {\n\t\tname, ok := args[i].(Symbol)\n\t\tif !ok {\n\t\t\treturn nil, &ErrWrongType{args[i]}\n\t\t}\n\t\tval, err := eval(args[i+1], env)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tenv.Set(name, val)\n\t}\n\n\treturn val, nil\n}" ]
[ "0.60826826", "0.5945396", "0.5945396", "0.5622157", "0.5578041", "0.5568355", "0.55566686", "0.5549164", "0.5427744", "0.5359938", "0.5208214", "0.5185076", "0.5166366", "0.5034822", "0.49868807", "0.49719235", "0.4950178", "0.4950178", "0.4889872", "0.478144", "0.47600535", "0.4737085", "0.47003058", "0.46956772", "0.4690566", "0.4660634", "0.46497414", "0.46436724", "0.46374068", "0.46327066", "0.45995072", "0.4597377", "0.45865783", "0.4573338", "0.45537585", "0.45523706", "0.45373163", "0.45306003", "0.44925672", "0.44848034", "0.44812822", "0.44705823", "0.44550526", "0.44185314", "0.44141525", "0.44029233", "0.44026983", "0.439528", "0.43932083", "0.4385435", "0.43457142", "0.43327305", "0.43288454", "0.43243986", "0.43218923", "0.43003595", "0.42929432", "0.4288362", "0.42846385", "0.4283844", "0.4272893", "0.4270367", "0.42651927", "0.42623517", "0.42417312", "0.42412037", "0.42394143", "0.4238247", "0.42356282", "0.42344964", "0.4228931", "0.42281473", "0.42143372", "0.42129606", "0.42101768", "0.42085204", "0.42068252", "0.4205893", "0.41976643", "0.41786107", "0.41761962", "0.4169273", "0.41688845", "0.41666108", "0.41613418", "0.41540822", "0.41521272", "0.41487274", "0.4143696", "0.413823", "0.413552", "0.41347682", "0.4132216", "0.41295022", "0.41285804", "0.41276106", "0.4113985", "0.4113514", "0.41116503", "0.41116053" ]
0.42398193
66
Now builds a new Application instance
func (app *applicationBuilder) Now() (Application, error) { if app.head == nil { return nil, errors.New("the HeadSection is mandatory in order to build a Application instance") } if app.main == nil { return nil, errors.New("the MainSection is mandatory in order to build a Application instance") } if app.test != nil && app.def != nil && app.label != nil { return createApplicationWithDefinitionAndLabelAndTest(app.head, app.main, app.def, app.label, app.test), nil } if app.def != nil && app.label != nil { return createApplicationWithDefinitionAndLabel(app.head, app.main, app.def, app.label), nil } if app.test != nil && app.label != nil { return createApplicationWithLabelAndTest(app.head, app.main, app.label, app.test), nil } if app.test != nil && app.def != nil { return createApplicationWithDefinitionAndTest(app.head, app.main, app.def, app.test), nil } if app.test != nil { return createApplicationWithTest(app.head, app.main, app.test), nil } if app.def != nil { return createApplicationWithDefinition(app.head, app.main, app.def), nil } if app.label != nil { return createApplicationWithLabel(app.head, app.main, app.label), nil } return createApplication(app.head, app.main), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CreateApplication() *Alpha {\n app := &Alpha{}\n app.Request = &Request{}\n app.Response = &Response{}\n app.init()\n return app\n}", "func New(\n\tfactories config.Factories,\n\tappInfo ApplicationStartInfo,\n) (*Application, error) {\n\n\tif err := configcheck.ValidateConfigFromFactories(factories); err != nil {\n\t\treturn nil, err\n\t}\n\n\tapp := &Application{\n\t\tinfo: appInfo,\n\t\tv: viper.New(),\n\t\treadyChan: make(chan struct{}),\n\t\tfactories: factories,\n\t}\n\n\trootCmd := &cobra.Command{\n\t\tUse: appInfo.ExeName,\n\t\tLong: appInfo.LongName,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tapp.init()\n\t\t\tapp.execute()\n\t\t},\n\t}\n\n\t// TODO: coalesce this code and expose this information to other components.\n\tflagSet := new(flag.FlagSet)\n\taddFlagsFns := []func(*flag.FlagSet){\n\t\ttelemetryFlags,\n\t\tbuilder.Flags,\n\t\tloggerFlags,\n\t}\n\tfor _, addFlags := range addFlagsFns {\n\t\taddFlags(flagSet)\n\t}\n\trootCmd.Flags().AddGoFlagSet(flagSet)\n\n\tapp.rootCmd = rootCmd\n\n\treturn app, nil\n}", "func NewApplication() Application {\n\treturn app\n}", "func newApp(name string) (app *App, err error) {\n\tapp = &App{\n\t\tName: name,\n\t\tID: uuid.NewV5(namespace, \"org.homealone.\"+name).String(),\n\t\thandler: make(map[queue.Topic]message.Handler),\n\t\tdebug: *debug,\n\t\tfilterMessages: true,\n\t}\n\tapp.Log = log.NewLogger().With(log.Fields{\"app\": name, \"id\": app.ID})\n\treturn app, errors.Wrap(err, \"newApp failed\")\n}", "func New() App {\n\treturn App{}\n}", "func New(cfg *conf.Config) *Application {\n\tapp := new(Application)\n\n\t// init db\n\tapp.DB = model.Init()\n\n\t// init redis\n\tapp.RedisClient = redis2.Init()\n\n\t// init router\n\tapp.Router = gin.Default()\n\n\t// init log\n\tconf.InitLog()\n\n\tif viper.GetString(\"app.run_mode\") == ModeDebug {\n\t\tapp.Debug = true\n\t}\n\n\treturn app\n}", "func CreateApp(appoptions *options.App) (*App, error) {\n\tvar err error\n\n\tctx := context.Background()\n\n\t// Merge default options\n\toptions.MergeDefaults(appoptions)\n\n\tdebug := IsDebug()\n\tdevtools := IsDevtoolsEnabled()\n\tctx = context.WithValue(ctx, \"debug\", debug)\n\tctx = context.WithValue(ctx, \"devtools\", devtools)\n\n\t// Set up logger\n\tmyLogger := logger.New(appoptions.Logger)\n\tif IsDebug() {\n\t\tmyLogger.SetLogLevel(appoptions.LogLevel)\n\t} else {\n\t\tmyLogger.SetLogLevel(appoptions.LogLevelProduction)\n\t}\n\tctx = context.WithValue(ctx, \"logger\", myLogger)\n\tctx = context.WithValue(ctx, \"obfuscated\", IsObfuscated())\n\n\t// Preflight Checks\n\terr = PreflightChecks(appoptions, myLogger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create the menu manager\n\tmenuManager := menumanager.NewManager()\n\n\t// Process the application menu\n\tif appoptions.Menu != nil {\n\t\terr = menuManager.SetApplicationMenu(appoptions.Menu)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Create binding exemptions - Ugly hack. There must be a better way\n\tbindingExemptions := []interface{}{\n\t\tappoptions.OnStartup,\n\t\tappoptions.OnShutdown,\n\t\tappoptions.OnDomReady,\n\t\tappoptions.OnBeforeClose,\n\t}\n\tappBindings := binding.NewBindings(myLogger, appoptions.Bind, bindingExemptions, IsObfuscated())\n\teventHandler := runtime.NewEvents(myLogger)\n\tctx = context.WithValue(ctx, \"events\", eventHandler)\n\t// Attach logger to context\n\tif debug {\n\t\tctx = context.WithValue(ctx, \"buildtype\", \"debug\")\n\t} else {\n\t\tctx = context.WithValue(ctx, \"buildtype\", \"production\")\n\t}\n\n\tmessageDispatcher := dispatcher.NewDispatcher(ctx, myLogger, appBindings, eventHandler, appoptions.ErrorFormatter)\n\tappFrontend := desktop.NewFrontend(ctx, appoptions, myLogger, appBindings, messageDispatcher)\n\teventHandler.AddFrontend(appFrontend)\n\n\tctx = context.WithValue(ctx, \"frontend\", appFrontend)\n\tresult := &App{\n\t\tctx: ctx,\n\t\tfrontend: appFrontend,\n\t\tlogger: myLogger,\n\t\tmenuManager: menuManager,\n\t\tstartupCallback: appoptions.OnStartup,\n\t\tshutdownCallback: appoptions.OnShutdown,\n\t\tdebug: debug,\n\t\tdevtools: devtools,\n\t\toptions: appoptions,\n\t}\n\n\treturn result, nil\n\n}", "func (b BotAppNotModified) construct() BotAppClass { return &b }", "func New() *Application {\n\tbrizo := new(Application)\n\tbrizo.serverListener = http.ListenAndServe\n\tbrizo.serverHandler = routes.BuildRouter()\n\tbrizo.healthChecks = []ChecksHealth{\n\t\tdatabase.Health,\n\t}\n\tbrizo.migrator = migrations.Run\n\n\treturn brizo\n}", "func init() {\n\tApp = New()\n}", "func (b BotApp) construct() BotAppClass { return &b }", "func NewApp(listenAddr string, ghClient *githubclient.Client, cache cache.Cache, objTTL time.Duration) App {\n\treturn App{\n\t\tlistenAddr: listenAddr,\n\t\tghClient: ghClient,\n\t\tcache: cache,\n\t\tcacheObjTTL: objTTL,\n\t}\n}", "func NewApplication(logger *logger.Logger) *Application {\n\t// Load skeefree-specific config:\n\tcfg := &skconfig.Config{}\n\tif err := config.Load(cfg); err != nil {\n\t\tpanic(fmt.Sprintf(\"error loading skeefree configuration: %s\", err))\n\t}\n\tbackend, err := db.NewBackend(cfg)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"error creating backend: %s\", err))\n\t}\n\tghAPI, err := ghapi.NewGitHubAPI(cfg)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"error creating github client: %s\", err))\n\t}\n\tsitesAPI, err := gh.NewSitesAPI(cfg)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"error creating sites api client: %s\", err))\n\t}\n\tmysqlDiscoveryAPI, err := gh.NewMySQLDiscoveryAPI(cfg)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"error creating mysql discovery api client: %s\", err))\n\t}\n\tscheduler := NewScheduler(cfg, logger, backend, sitesAPI, mysqlDiscoveryAPI)\n\tdirectApplier := NewDirectApplier(cfg, logger, backend, mysqlDiscoveryAPI)\n\treturn &Application{\n\t\tLogger: logger,\n\t\tcfg: cfg,\n\t\tbackend: backend,\n\t\tghAPI: ghAPI,\n\t\tsitesAPI: sitesAPI,\n\t\tmysqlDiscoveryAPI: mysqlDiscoveryAPI,\n\t\tscheduler: scheduler,\n\t\tdirectApplier: directApplier,\n\t}\n}", "func NewApplication() *Application {\n\treturn &Application{\n\t\tevents: make(chan tcell.Event, queueSize),\n\t\tupdates: make(chan func(), queueSize),\n\t\tscreenReplacement: make(chan tcell.Screen, 1),\n\t}\n}", "func App() *Application {\n\treturn &app\n}", "func NewApp() App {\n\treturn App{}\n}", "func NewApp() App {\n\treturn App{}\n}", "func makeApp(def pchannel.App, data pchannel.Data) perun.App {\n\treturn perun.App{\n\t\tDef: def,\n\t\tData: data,\n\t}\n}", "func NewApplication(aOptrions Options) (*Application, error) {\n\tservices := []startable{}\n\n\ttools := processing.NewTools(aOptrions.UploadLocation, aOptrions.PreviewSize)\n\n\tsrv := newServer(aOptrions.Listen, aOptrions.Port, tools)\n\n\tif srv == nil {\n\t\treturn nil, fmt.Errorf(\"Can't create server\")\n\t}\n\n\tservices = append(services, srv)\n\n\treturn &Application{\n\t\tservices: services,\n\t}, nil\n}", "func New() *Application {\n\tapp := &Application{\n\t\tmiddlewares: []Handler{logging, respond},\n\t\tconfigs: map[string]string{},\n\t}\n\treturn app\n}", "func NewApplication(s IdentitiesStore) *App {\n\tapp := &App{store : s, Server: fiber.New()}\n\n\tSetupRoutes(app)\n\n\treturn app\n}", "func NewApp() *App {\n\tlogger := Log.With(zap.String(\"type\", \"app\")).Sugar()\n\tetcd := embed.NewServer(Config, Log)\n\tws := ws.NewServer(Config, Log)\n\tapp := &App{\n\t\tcfg: Config,\n\t\tlogger: logger,\n\t\tetcd: etcd,\n\t\tws: ws,\n\t\trepo: repository.NewRepo(),\n\t\tstopch: make(chan struct{}),\n\t}\n\tapp.scheduler = NewScheduler(Log, app)\n\treturn app\n}", "func App(name string) *AppBuilder {\n\treturn &AppBuilder{Name: name, startFunc: []func(context.Context) error{}}\n}", "func NewApp(f interface{}, args Arguments, info *debug.Info) App {\n\treturn App{f, args, info}\n}", "func New(prj *project.Project) *Application {\n\tcli := &Application{\n\t\tLog: log.NewStdout(log.NOTICE),\n\t\tProject: prj,\n\t\tcommands: make(map[string]Command),\n\t\tflags: make(map[int]flags.Interface),\n\t\tflagAliases: make(map[string]int),\n\t\tosArgs: os.Args[1:],\n\t}\n\t// set initial startup time\n\tcli.started = time.Now()\n\tcli.Log.TsDisabled()\n\tif prj.Config.InitTerm {\n\t\tcli.Log.InitTerm()\n\t}\n\tcli.Log.SetPrimaryColor(prj.Config.Color)\n\tcli.Log.SetLogLevel(prj.Config.LogLevel)\n\tcli.addInternalFlags()\n\tif prj.Config.Color != \"\" {\n\t\tcli.Log.Colors()\n\t}\n\n\t// Set log level to debug and lock the log level, but only if --debug\n\t// flag was found before any command. If --debug flag was found later\n\t// then we want to set debugging later for that command only.\n\tif cli.flag(\"debug\").IsGlobal() && cli.flag(\"debug\").Present() {\n\t\tcli.Log.SetLogLevel(log.DEBUG)\n\t\tcli.Log.LockLevel()\n\t\tcli.flag(\"verbose\").Unset()\n\t}\n\n\t// Only lock log level to verbose if no --debug flag was set\n\tif !cli.flag(\"debug\").Present() && cli.flag(\"verbose\").Present() {\n\t\tcli.Log.SetLogLevel(log.INFO)\n\t\tcli.Log.LockLevel()\n\t}\n\n\tcli.Log.Debugf(\"CLI:Create - accepting configuration changes debugging(%t)\",\n\t\tcli.flag(\"debug\").Present())\n\n\t// Add internal commands besides help\n\tcli.AddCommand(cmdAbout())\n\tcli.rootCmd = NewCommand(prj.Name)\n\tcli.Header.Defaults()\n\tcli.Footer.Defaults()\n\treturn cli\n}", "func App() *Application {\r\n\r\n\t// Return singleton if already created\r\n\tif a != nil {\r\n\t\treturn a\r\n\t}\r\n\ta = new(Application)\r\n\t// Initialize window\r\n\terr := window.Init(width, height, title)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\ta.IWindow = window.Get()\r\n\ta.openDefaultAudioDevice() // Set up audio\r\n\ta.keyState = window.NewKeyState(a) // Create KeyState\r\n\t// Create renderer and add default shaders\r\n\ta.renderer = renderer.NewRenderer(a.Gls())\r\n\terr = a.renderer.AddDefaultShaders()\r\n\tif err != nil {\r\n\t\tpanic(fmt.Errorf(\"AddDefaultShaders:%v\", err))\r\n\t}\r\n\treturn a\r\n}", "func NewApp(opts ...AppOptions) *App {\n\toptions := AppOptions{}\n\tfor _, i := range opts {\n\t\toptions = i\n\t\tbreak\n\t}\n\n\toptions.init()\n\n\t// Parse config yaml string from ./conf.go\n\tconf, err := config.ParseYaml(confString)\n\tMust(err)\n\n\t// Set config variables delivered from main.go:11\n\t// Variables defined as ./conf.go:3\n\tconf.Set(\"debug\", debug)\n\tconf.Set(\"commitHash\", commitHash)\n\n\t// Parse environ variables for defined\n\t// in config constants\n\tconf.Env()\n\n\t// Make an engine\n\tengine := echo.New()\n\n\t// Set up echo debug level\n\tengine.Debug = conf.UBool(\"debug\")\n\n\t// Regular middlewares\n\tengine.Use(middleware.Recover())\n\n\tengine.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{\n\t\tFormat: `${method} | ${status} | ${uri} -> ${latency_human}` + \"\\n\",\n\t}))\n\n\t// Initialize the application\n\tapp := &App{\n\t\tConf: conf,\n\t\tEngine: engine,\n\t\tAPI: &API{},\n\t}\n\n\tapp.API.Bind(app.Engine.Group(\n\t\tapp.Conf.UString(\"api.prefix\"),\n\t))\n\n\t// Create file http server from bindata\n\tfileServerHandler := http.FileServer(&assetfs.AssetFS{\n\t\tAsset: Asset,\n\t\tAssetDir: AssetDir,\n\t\tAssetInfo: AssetInfo,\n\t})\n\n\t// Serve static via bindata and handle via react app\n\t// in case when static file was not found\n\tapp.Engine.Use(func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\t// execute echo handlers chain\n\t\t\terr := next(c)\n\t\t\t// if page(handler) for url/method not found\n\t\t\tif err != nil {\n\t\t\t\thttpErr, ok := err.(*echo.HTTPError)\n\t\t\t\tif ok && httpErr.Code == http.StatusNotFound {\n\t\t\t\t\t// check if file exists\n\t\t\t\t\t// omit first `/`\n\t\t\t\t\tfileServerHandler.ServeHTTP(\n\t\t\t\t\t\tc.Response(),\n\t\t\t\t\t\tc.Request())\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Move further if err is not `Not Found`\n\t\t\treturn err\n\t\t}\n\t})\n\n\treturn app\n}", "func New() (App, error) {\n\tcfg := config.New()\n\n\tdb, err := database.New(cfg)\n\tif err != nil {\n\t\treturn App{}, err\n\t}\n\n\tm, err := metrics.New(metrics.Config{\n\t\tEnvironment: cfg.Environment,\n\t\tHostname: cfg.Hostname,\n\t\tNamespace: \"pharos-api-server\",\n\t\tStatsdHost: cfg.StatsdHost,\n\t\tStatsdPort: cfg.StatsdPort,\n\t})\n\tif err != nil {\n\t\treturn App{}, errors.Wrap(err, \"application\")\n\t}\n\n\ts, err := sentry.New(cfg.SentryDSN)\n\tif err != nil {\n\t\treturn App{}, errors.Wrap(err, \"application\")\n\t}\n\n\tv := token.NewVerifier()\n\n\treturn App{cfg, db, m, s, v}, nil\n}", "func NewApplication(pgsql postgres.Client, redis core.Application) core.Application {\n\treturn &application{\n\t\tpg: pgsql,\n\t\tmainPg: pgsql.MainDatastore(),\n\t\tredis: redis,\n\t}\n}", "func New() *App {\n\treturn &App{}\n}", "func NewApplication() application.Application {\n\treturn &app{}\n}", "func New(config config.Config) *App {\n\treturn &App{\n\t\tconfig: config,\n\t\tlog: config.Log(),\n\t}\n}", "func NewApplication() *Application {\n\treturn &Application{}\n}", "func New() *Application {\n\tapp := &Application{}\n\treturn app\n}", "func NewApplication(app sdk.Application, keys []EncryptedKey) (a Application, err error) {\n\ta.Version = ApplicationVersion1\n\ta.Name = app.Name\n\ta.Description = app.Description\n\n\tif app.VCSServer != \"\" {\n\t\ta.VCSServer = app.VCSServer\n\t\ta.RepositoryName = app.RepositoryFullname\n\t}\n\n\ta.Variables = make(map[string]VariableValue, len(app.Variables))\n\tfor _, v := range app.Variables {\n\t\tat := v.Type\n\t\tif at == \"string\" {\n\t\t\tat = \"\"\n\t\t}\n\t\ta.Variables[v.Name] = VariableValue{\n\t\t\tType: at,\n\t\t\tValue: v.Value,\n\t\t}\n\t}\n\n\ta.Keys = make(map[string]KeyValue, len(keys))\n\tfor _, e := range keys {\n\t\ta.Keys[e.Name] = KeyValue{\n\t\t\tType: e.Type,\n\t\t\tValue: e.Content,\n\t\t}\n\t}\n\n\ta.VCSPGPKey = app.RepositoryStrategy.PGPKey\n\ta.VCSConnectionType = app.RepositoryStrategy.ConnectionType\n\tif app.RepositoryStrategy.ConnectionType == \"ssh\" {\n\t\ta.VCSSSHKey = app.RepositoryStrategy.SSHKey\n\t\ta.VCSUser = \"\"\n\t\ta.VCSPassword = \"\"\n\t} else {\n\t\ta.VCSSSHKey = \"\"\n\t\ta.VCSUser = app.RepositoryStrategy.User\n\t\ta.VCSPassword = app.RepositoryStrategy.Password\n\t}\n\n\tif app.RepositoryStrategy.ConnectionType != \"https\" {\n\t\ta.VCSConnectionType = app.RepositoryStrategy.ConnectionType\n\t}\n\ta.VCSPGPKey = app.RepositoryStrategy.PGPKey\n\n\ta.DeploymentStrategies = make(map[string]map[string]VariableValue, len(app.DeploymentStrategies))\n\tfor name, config := range app.DeploymentStrategies {\n\t\tvars := make(map[string]VariableValue, len(config))\n\t\tfor k, v := range config {\n\t\t\tvars[k] = VariableValue{\n\t\t\t\tType: v.Type,\n\t\t\t\tValue: v.Value,\n\t\t\t}\n\t\t}\n\t\ta.DeploymentStrategies[name] = vars\n\t}\n\n\treturn a, nil\n}", "func New(opts ...Option) *App {\n\tlogger := fxlog.New()\n\tlc := &lifecycleWrapper{lifecycle.New(logger)}\n\n\tapp := &App{\n\t\tcontainer: dig.New(),\n\t\tlifecycle: lc,\n\t\tlogger: logger,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt.apply(app)\n\t}\n\n\tfor _, p := range app.provides {\n\t\tapp.provide(p)\n\t}\n\tapp.provide(func() Lifecycle { return app.lifecycle })\n\treturn app\n}", "func New(Store store.Store, options Options) *Application {\n\n\treturn &Application{\n\t\tConfig: &Config{\n\t\t\tStore: Store,\n\t\t\tOMDB: omdb.New(),\n\t\t\tOptions: options,\n\t\t\tDownloader: &imdbPosterDownloader{},\n\t\t},\n\t}\n}", "func New() *App {\n\treturn NewApp(newDefaultApp())\n}", "func Instance() *application {\n\tloadAppOnce.Do(func() {\n\t\tapp = &application{}\n\t})\n\treturn app\n}", "func NewApplication(ctx context.Context, flags *cliFlags) (*application, func(), error) {\n\twire.Build(\n\t\twire.FieldsOf(new(*cliFlags), \"Log\", \"Census\", \"MySQL\", \"Event\", \"Orc8r\"),\n\t\tlog.Provider,\n\t\tnewApplication,\n\t\tnewTenancy,\n\t\tnewHealthChecks,\n\t\tnewMySQLTenancy,\n\t\tnewAuthURL,\n\t\tmysql.Open,\n\t\tevent.Set,\n\t\tgraphhttp.NewServer,\n\t\twire.Struct(new(graphhttp.Config), \"*\"),\n\t\tgraphgrpc.NewServer,\n\t\twire.Struct(new(graphgrpc.Config), \"*\"),\n\t)\n\treturn nil, nil, nil\n}", "func NewApp(dbname, dburl, slackSetLocationToken, slackWhereIsToken, slackReqToken string) *App {\n\ta := App{}\n\n\ta.Router = gin.Default()\n\n\ta.SlackSetLocationToken = slackSetLocationToken\n\n\ta.SlackWhereIsToken = slackWhereIsToken\n\n\ta.SlackRequestToken = slackReqToken\n\n\ta.initialiseRoutes()\n\n\tdialled := false\n\tcount := 1\n\n\tfor dialled == false {\n\t\tfmt.Printf(\"Connecting to database, attempt %v\\n\", count)\n\t\ts, err := mgo.Dial(dburl)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error: \" + err.Error())\n\t\t\tfmt.Println(\"Retrying...\")\n\t\t} else {\n\t\t\tfmt.Println(\"Connected!\")\n\t\t\tdialled = true\n\t\t\ta.DB = s.DB(dbname)\n\t\t}\n\n\t\ttime.Sleep(2 * time.Second)\n\n\t\tif count > 5 {\n\t\t\tfmt.Printf(\"Tried to connect %v times. Exiting program\\n\", count)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tcount++\n\t}\n\n\treturn &a\n}", "func newApp(infile, outfile string) *App {\n\treturn &App{\n\t\tAddressFile: infile,\n\t\tGeoDecodeFile: outfile,\n\t\tClient: &http.Client{},\n\t}\n}", "func NewApp(mode string, cfg *Config) (app *App, err error) {\n\tif cfg == nil {\n\t\tcfg = DefaultConfig()\n\t}\n\tv := &App{\n\t\tobjs: make(map[int]*_object),\n\t\teventMux: newMux(),\n\t\ttrans: newFnMgr(mode),\n\t\tcfg: *cfg,\n\t}\n\tv.b = newBridge(mode, v.trans)\n\n\t// refer to 'ReadMostly' example in sync/atomic\n\tv.eventOut.Store(make(map[int]*_eventListener))\n\tv.eventMux.Handle(func(val interface{}, _ int) {\n\t\te := val.(*Event)\n\t\tm := v.eventOut.Load().(map[int]*_eventListener)\n\t\t// to the channel containing everythin errors\n\t\tfor _, eln := range m {\n\t\t\tif (eln.targets&e.Origin) == 0 || eln.level > e.Level {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// non-blocking channel sending\n\t\t\tselect {\n\t\t\tcase eln.events <- e:\n\t\t\tdefault:\n\t\t\t\t// drop this event\n\t\t\t\t// TODO: log it?\n\t\t\t}\n\t\t}\n\t})\n\n\tremain, err := v.eventMux.More(1)\n\tif err != nil || remain != 0 {\n\t\terr = fmt.Errorf(\"Unable to allocate mux routine: %v\", remain)\n\t}\n\n\t// init mappers\n\tif v.mappers, err = newMappers(v.trans, v.b.(exHooks)); err != nil {\n\t\treturn\n\t}\n\tif err = v.attachObject(v.mappers, ObjT.Mapper); err != nil {\n\t\treturn\n\t}\n\t// 'local' mode\n\tif err = v.allocateMappers(); err != nil {\n\t\treturn\n\t}\n\n\t// init workers\n\tif v.workers, err = newWorkers(v.trans, v.b.(exHooks)); err != nil {\n\t\treturn\n\t}\n\tif err = v.attachObject(v.workers, ObjT.Worker); err != nil {\n\t\treturn\n\t}\n\n\tapp = v\n\treturn\n}", "func NewApp() App {\n\treturn new(app)\n}", "func NewApp(databaseName, password string) *App {\n\t// Setup db:\n\tdb, err := newDatabase(databaseName, password)\n\tif err != nil {\n\t\tif err, ok := err.(*mysql.MySQLError); ok && err.Number == 1049 { // unknown database\n\t\t\tfmt.Printf(\"Creating and reconnecting to %s\", databaseName)\n\t\t\t// Create and use `ElasticJury`\n\t\t\tdbRoot, err := newDatabase(\"\", password) // as root\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdbRoot.mustExec(fmt.Sprintf(\"CREATE DATABASE IF NOT EXISTS %s DEFAULT CHARACTER SET utf8\", databaseName))\n\t\t\tdb, err = newDatabase(databaseName, password)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdb.mustExecScriptFile(InitTableScriptPath)\n\t\t} else {\n\t\t\tpanic(err) // unknown err\n\t\t}\n\t}\n\tprintln(\"[Info] Database initialized.\")\n\n\t// Setup router:\n\t// Disable Console Color\n\t// gin.DisableConsoleColor()\n\t// Release mode is faster\n\tgin.SetMode(gin.ReleaseMode)\n\trouter := gin.Default()\n\t{\n\t\t// Ping test\n\t\trouter.GET(\"/ping\", func(context *gin.Context) {\n\t\t\tcontext.String(http.StatusOK, \"pong\")\n\t\t})\n\t\t// Retrieve case id by tag, law, judge\n\t\trouter.POST(\"/search\", db.makeSearchHandler())\n\t\t// Retrieve case info by case id\n\t\trouter.POST(\"/info\", db.makeCaseInfoHandler())\n\t\t// Associate\n\t\trouter.GET(\"/associate/:field/:item\", natural.MakeAssociateHandler())\n\t\t// Retrieve case detail by one case id\n\t\trouter.GET(\"/detail/:id\", db.makeCaseDetailHandler())\n\t}\n\tprintln(\"[Info] Search engine initialized.\")\n\n\treturn &App{\n\t\tEngine: router,\n\t\tdb: db,\n\t}\n}", "func New(name string) *Application {\n\tif name == \"\" {\n\t\tpanic(\"can't construct an app without a name\")\n\t}\n\n\treturn &Application{Name: name}\n}", "func newApp() (*app, error) {\n\tapp := &app{}\n\n\tgd, err := newGDrive(\"\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable initializate Google Drive configuration: %v\", err)\n\t}\n\tapp.gDrive = gd\n\n\tsrv, err := app.gDrive.getService()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to retrieve Drive client: %v\", err)\n\t}\n\tapp.srv = srv\n\n\treturn app, nil\n}", "func Create (appName string) {\n\n checkGopath ()\n checkContainer (appName)\n\n app := Application { Name: appName }\n\n app.createContainer ()\n\n err := app.copyFileTree (\n GOPATH + slash + applicationTemplatesPath,\n GOPATH_SRC + app.Name,\n )\n\n if err != nil {\n log.Fatal (err)\n }\n}", "func CreateApp(conf *config.Config) *TelegramBotApp {\n\n\t// Init the telegram bot\n\tbot, err := botFactory.BotFactory(conf)\n\tif err != nil {\n\t\tlog.Fatal(\"Can't create a telegram bot: \", err)\n\t}\n\n\t// Init the database\n\tdb, err := dbFactory.DatabaseFactory(conf)\n\tif err != nil {\n\t\tlog.Fatal(\"Couldn't create database: \", err)\n\t}\n\n\t// Init the database storage\n\tstorage, err := storages.CreateStorages(db)\n\tif err != nil {\n\t\tlog.Fatal(\"Couldn't setup database: \", err)\n\t}\n\n\t// Init the database Repository\n\trepository, err := repositories.CreateRepository(db)\n\tif err != nil {\n\t\tlog.Fatal(\"Couldn't setup database: \", err)\n\t}\n\n\treturn &TelegramBotApp{conf, bot, storage, repository}\n}", "func New(cfg config.Configuration) *App {\n\tapp := &App{\n\t\tcommonApp.New(cfg),\n\t}\n\n\treturn app\n}", "func NewApplication() {\n\tlog.Info(\"Setting up a new application\")\n\tapp := &application{\n\t\trouter: mux.NewRouter().StrictSlash(true),\n\t\tdb: datastore.NewDBConnection(),\n\t}\n\tapp.routes()\n\tapp.start()\n}", "func NewApp(cfg *Config) *App {\n\treturn &App{\n\t\tl: log.With().Str(\"m\", \"app\").Logger(),\n\t\tcfg: cfg,\n\t\tgui: gui.NewGui(&cfg.Gui),\n\t}\n}", "func App() *kingpin.Application {\n\treturn app\n}", "func NewApp() *App {\n\treturn &App{\n\t\tConfig: &Config{},\n\t}\n}", "func New(opt *Options) *Application {\n\tr := mux.NewRouter()\n\treturn &Application{\n\t\tr: r,\n\t\tserv: &http.Server{\n\t\t\tAddr: \":8120\",\n\t\t\tReadTimeout: time.Duration(opt.Serv.ReadTimeout),\n\t\t\tIdleTimeout: time.Duration(opt.Serv.IdleTimeout),\n\t\t\tWriteTimeout: time.Duration(opt.Serv.WriteTimeout),\n\t\t\tHandler: r,\n\t\t},\n\t\thashSum: opt.HashSum,\n\t\tsvc: opt.Svc,\n\t\tpr: opt.Pr,\n\t\tlogger: opt.Logger,\n\t}\n}", "func NewCmdNewApplication(f kcmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewAppOptions(streams)\n\n\tcmd := &cobra.Command{\n\t\tUse: \"new-app (IMAGE | IMAGESTREAM | TEMPLATE | PATH | URL ...)\",\n\t\tShort: \"Create a new application\",\n\t\tLong: newAppLong,\n\t\tExample: newAppExample,\n\t\tSuggestFor: []string{\"app\", \"application\"},\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tkcmdutil.CheckErr(o.Complete(f, c, args))\n\t\t\tkcmdutil.CheckErr(o.RunNewApp())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmd.Flags().BoolVar(&o.Config.AsTestDeployment, \"as-test\", o.Config.AsTestDeployment, \"If true create this application as a test deployment, which validates that the deployment succeeds and then scales down.\")\n\tcmd.Flags().BoolVar(&o.Config.DeploymentConfig, \"as-deployment-config\", o.Config.DeploymentConfig, \"If true create this application as a deployment config, which allows for hooks and custom strategies.\")\n\tcmd.Flags().StringSliceVar(&o.Config.SourceRepositories, \"code\", o.Config.SourceRepositories, \"Source code to use to build this application.\")\n\tcmd.Flags().StringVar(&o.Config.ContextDir, \"context-dir\", o.Config.ContextDir, \"Context directory to be used for the build.\")\n\tcmd.Flags().StringSliceVarP(&o.Config.ImageStreams, \"image-stream\", \"i\", o.Config.ImageStreams, \"Name of an existing image stream to use to deploy an app.\")\n\tcmd.Flags().StringSliceVar(&o.Config.DockerImages, \"image\", o.Config.DockerImages, \"Name of a container image to include in the app. Note: not specifying a registry or repository means defaults in place for client image pulls are employed.\")\n\tcmd.Flags().StringSliceVar(&o.Config.DockerImages, \"docker-image\", o.Config.DockerImages, \"\")\n\tcmd.Flags().MarkDeprecated(\"docker-image\", \"Deprecated flag use --image\")\n\tcmd.Flags().StringSliceVar(&o.Config.Templates, \"template\", o.Config.Templates, \"Name of a stored template to use in the app.\")\n\tcmd.Flags().StringSliceVarP(&o.Config.TemplateFiles, \"file\", \"f\", o.Config.TemplateFiles, \"Path to a template file to use for the app.\")\n\tcmd.MarkFlagFilename(\"file\", \"yaml\", \"yml\", \"json\")\n\tcmd.Flags().StringArrayVarP(&o.Config.TemplateParameters, \"param\", \"p\", o.Config.TemplateParameters, \"Specify a key-value pair (e.g., -p FOO=BAR) to set/override a parameter value in the template.\")\n\tcmd.Flags().StringArrayVar(&o.Config.TemplateParameterFiles, \"param-file\", o.Config.TemplateParameterFiles, \"File containing parameter values to set/override in the template.\")\n\tcmd.MarkFlagFilename(\"param-file\")\n\tcmd.Flags().StringSliceVar(&o.Config.Groups, \"group\", o.Config.Groups, \"Indicate components that should be grouped together as <comp1>+<comp2>.\")\n\tcmd.Flags().StringArrayVarP(&o.Config.Environment, \"env\", \"e\", o.Config.Environment, \"Specify a key-value pair for an environment variable to set into each container.\")\n\tcmd.Flags().StringArrayVar(&o.Config.EnvironmentFiles, \"env-file\", o.Config.EnvironmentFiles, \"File containing key-value pairs of environment variables to set into each container.\")\n\tcmd.MarkFlagFilename(\"env-file\")\n\tcmd.Flags().StringArrayVar(&o.Config.BuildEnvironment, \"build-env\", o.Config.BuildEnvironment, \"Specify a key-value pair for an environment variable to set into each build image.\")\n\tcmd.Flags().StringArrayVar(&o.Config.BuildEnvironmentFiles, \"build-env-file\", o.Config.BuildEnvironmentFiles, \"File containing key-value pairs of environment variables to set into each build image.\")\n\tcmd.MarkFlagFilename(\"build-env-file\")\n\tcmd.Flags().StringVar(&o.Config.Name, \"name\", o.Config.Name, \"Set name to use for generated application artifacts\")\n\tcmd.Flags().Var(&o.Config.Strategy, \"strategy\", \"Specify the build strategy to use if you don't want to detect (docker|pipeline|source). NOTICE: the pipeline strategy is deprecated; consider using Jenkinsfiles directly on Jenkins or OpenShift Pipelines.\")\n\tcmd.Flags().StringP(\"labels\", \"l\", \"\", \"Label to set in all resources for this application.\")\n\tcmd.Flags().BoolVar(&o.Config.IgnoreUnknownParameters, \"ignore-unknown-parameters\", o.Config.IgnoreUnknownParameters, \"If true, will not stop processing if a provided parameter does not exist in the template.\")\n\tcmd.Flags().BoolVar(&o.Config.InsecureRegistry, \"insecure-registry\", o.Config.InsecureRegistry, \"If true, indicates that the referenced container images are on insecure registries and should bypass certificate checking\")\n\tcmd.Flags().BoolVarP(&o.Config.AsList, \"list\", \"L\", o.Config.AsList, \"List all local templates and image streams that can be used to create.\")\n\tcmd.Flags().BoolVarP(&o.Config.AsSearch, \"search\", \"S\", o.Config.AsSearch, \"Search all templates, image streams, and container images that match the arguments provided. Note: the container images search is run on the OpenShift cluster via the ImageStreamImport API.\")\n\tcmd.Flags().BoolVar(&o.Config.AllowMissingImages, \"allow-missing-images\", o.Config.AllowMissingImages, \"If true, indicates that referenced container images that cannot be found locally or in a registry should still be used.\")\n\tcmd.Flags().BoolVar(&o.Config.AllowMissingImageStreamTags, \"allow-missing-imagestream-tags\", o.Config.AllowMissingImageStreamTags, \"If true, indicates that image stream tags that don't exist should still be used.\")\n\tcmd.Flags().BoolVar(&o.Config.AllowSecretUse, \"grant-install-rights\", o.Config.AllowSecretUse, \"If true, a component that requires access to your account may use your token to install software into your project. Only grant images you trust the right to run with your token.\")\n\tcmd.Flags().StringVar(&o.Config.SourceSecret, \"source-secret\", o.Config.SourceSecret, \"The name of an existing secret that should be used for cloning a private git repository.\")\n\tcmd.Flags().BoolVar(&o.Config.SkipGeneration, \"no-install\", o.Config.SkipGeneration, \"Do not attempt to run images that describe themselves as being installable\")\n\tcmd.Flags().BoolVar(&o.Config.BinaryBuild, \"binary\", o.Config.BinaryBuild, \"Instead of expecting a source URL, set the build to expect binary contents. Will disable triggers.\")\n\tcmd.Flags().StringVar(&o.Config.ImportMode, \"import-mode\", o.Config.ImportMode, \"Imports the full manifest list of a tag when set to 'PreserveOriginal'. Defaults to 'Legacy'.\")\n\n\to.Action.BindForOutput(cmd.Flags(), \"output\", \"template\")\n\tcmd.Flags().String(\"output-version\", \"\", \"The preferred API versions of the output objects\")\n\n\treturn cmd\n}", "func NewApp(cfg config.Config, opts ...Option) *App {\n\tapp := &App{\n\t\tcfg: cfg,\n\t\tlogger: zap.NewNop(),\n\t\tstopCommandChan: make(chan struct{}),\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(app)\n\t}\n\n\treturn app\n}", "func NewApp(clientService ClientService, lobby Lobby) *App {\n\treturn &App{clientService, lobby}\n}", "func Build(mongoClient *mongo.Client) *App {\n\treturn &App{\n\t\tmongoClient: mongoClient,\n\t}\n}", "func NewApp() *App {\n\tv := new(App)\n\tv.opened = false\n\tv.simType = \"runreset\"\n\tv.status = \"Stopped\"\n\tv.mode = \"Main\"\n\tv.incSize = 10.0\n\tv.decSize = 10.0\n\tv.keyMaps = make([]IKeyMap, 10)\n\tv.keyMaps[0] = NewKeyMap0(v)\n\tv.keyMaps[1] = NewKeyMap1(v)\n\n\treturn v\n}", "func NewApp(config *config.Config) (*App, error) {\n\tapp := &App{Config: config}\n\tapp.Log = logger.NewLogger(config)\n\tapp.Gui = gui.NewGui()\n\treturn app, nil\n\n}", "func NewApp(root string) *App {\n\n CheckEnv()\n\n // Use negroni for middleware\n ne := negroni.New()\n\n // Use gorilla/mux for routing\n ro := mux.NewRouter()\n\n // Use Render for template. Pass in path to templates folder\n // as well as asset helper functions.\n re := render.New(render.Options{\n Directory: filepath.Join(root, \"templates\"),\n Layout: \"layouts/layout\",\n Extensions: []string{\".html\"},\n Funcs: []template.FuncMap{\n\t\t\tAssetHelpers(root),\n\t\t},\n })\n qre := render.New(render.Options{\n Directory: filepath.Join(root, \"templates\"),\n Layout: \"layouts/message\",\n Extensions: []string{\".html\"},\n Funcs: []template.FuncMap{\n\t\t\tAssetHelpers(root),\n\t\t},\n })\n\n // Establish connection to DB as specificed in database.go\n db := NewDB()\n\n // Add middleware to the stack\n ne.Use(negroni.NewRecovery())\n ne.Use(negroni.NewLogger())\n ne.Use(NewAssetHeaders())\n ne.Use(negroni.NewStatic(http.Dir(\"public\")))\n ne.UseHandler(ro)\n\n train.Config.SASS.DebugInfo = true\n train.Config.SASS.LineNumbers = true\n train.Config.Verbose = true\n train.Config.BundleAssets = true\n //ZZZtrain.ConfigureHttpHandler(ro)\n\n // Return a new App struct with all these things.\n return &App{ne, ro, re, qre, db}\n}", "func newTestApp() *App {\n\treturn &App{\n\t\tstorage: storage.NewMemory(),\n\t}\n}", "func NewApplication(\n\tconfig Config,\n\ttemplate TemplateEngine,\n) Application {\n\tkbyte := 1024\n\tapp := fiber.New(fiber.Config{\n\t\tPrefork: config.Server.Prefork,\n\t\tStrictRouting: config.Server.Strict,\n\t\tCaseSensitive: config.Server.Case,\n\t\tETag: config.Server.Etag,\n\t\tBodyLimit: config.Server.BodyLimit * kbyte * kbyte,\n\t\tConcurrency: config.Server.Concurrency * kbyte,\n\t\tReadTimeout: config.Server.Timeout.Read * time.Second,\n\t\tWriteTimeout: config.Server.Timeout.Write * time.Second,\n\t\tIdleTimeout: config.Server.Timeout.Idel * time.Second,\n\t\tReadBufferSize: config.Server.Buffer.Read * kbyte,\n\t\tWriteBufferSize: config.Server.Buffer.Write * kbyte,\n\t\tViews: template.Engine,\n\t})\n\treturn Application{\n\t\tApp: app,\n\t\tConfig: config,\n\t}\n}", "func NewApp(queue QueueService) *App {\n\tapp := &App{queue: queue}\n\tapp.init()\n\treturn app\n}", "func New(service string, appConfig interface{}) (*App, error) {\n\t// Get config store\n\tconfigStore, err := config.NewStore(os.Getenv(\"CONFIG_URI\"))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"config store error: %s\", err)\n\t}\n\n\t// Load config from store\n\tc := &config.Config{App: appConfig}\n\terr = configStore.Load(c)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot load config: %s\", err)\n\t}\n\n\t// Convert potential environment variables\n\tc.Node = config.ValueOf(c.Node)\n\tc.Version = config.ValueOf(c.Version)\n\n\t// Create logger\n\tl, err := logger.New(service, &c.Log)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"logger error: %s\", err)\n\t}\n\n\t// Build stats\n\ts, err := statsAdapter.New(&c.Stats)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"stats error: %s\", err)\n\t}\n\ts.SetLogger(l)\n\n\t// Build app context\n\tctx := app.NewCtx(service, c, l, s)\n\n\t// Build ready cond flag\n\tlock := &sync.Mutex{}\n\tlock.Lock()\n\tready := sync.NewCond(lock)\n\n\t// Build app struct\n\tapp := &App{\n\t\tservice: service,\n\t\tready: ready,\n\t\tctx: ctx,\n\t\tconfig: c,\n\t\thandlers: handler.NewReg(ctx),\n\t\tdone: make(chan bool, 1),\n\t}\n\n\t// Start background services\n\tctx.BG().Dispatch(s)\n\tctx.BG().Dispatch(&hearbeat{app: app})\n\n\t// Trap OS signals\n\tgo trapSignals(app)\n\n\treturn app, nil\n}", "func New(config *Config) *App {\n\treturn &App{Config: config}\n}", "func New(c Config) *App {\n\treturn &App{\n\t\tName: c.Name,\n\t}\n}", "func NewApp() *App {\n\treturn &App{}\n}", "func NewApp() *App {\n\treturn &App{}\n}", "func NewApp() *App {\n\treturn &App{}\n}", "func New(appName, version string) *App {\n\treturn createApp(appName, version)\n}", "func New() *App {\n\ta = App{\n\t\tEnv: Development,\n\t\tServer: new(http.Server),\n\t\tredis: NewRedis(\"localhost:6379\", \"\", 0), // TODO: move redis configuration to .env\n\t\tSummery: make(map[string]*prometheus.SummaryVec),\n\t\tCounter: make(map[string]prometheus.Counter),\n\t\tDefaultHandler: func(c *Ctx) error {\n\t\t\treturn c.NotFound()\n\t\t},\n\t}\n\treturn &a\n}", "func NewApp(reader reader.Reader) (*App, error) {\n\tapp := &App{}\n\terr := app.configure(reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn app, nil\n}", "func NewApplication(\n\tname,\n\tappID,\n\tkey,\n\tsecret string,\n\tonlySSL,\n\tenabled,\n\tuserEvents,\n\twebHooks bool,\n\twebHookURL string,\n) *Application {\n\n\ta := &Application{\n\t\tName: name,\n\t\tAppID: appID,\n\t\tKey: key,\n\t\tSecret: secret,\n\t\tOnlySSL: onlySSL,\n\t\tEnabled: enabled,\n\t\tUserEvents: userEvents,\n\t\tWebHooks: webHooks,\n\t\tURLWebHook: webHookURL,\n\t}\n\n\ta.connections = make(map[string]*connection.Connection)\n\ta.channels = make(map[string]*channel.Channel)\n\ta.Stats = expvar.NewMap(fmt.Sprintf(\"%s (%s)\", a.Name, a.AppID))\n\n\treturn a\n}", "func New() *App {\n\tapp := &App{}\n\tapp.readConfig()\n\tapp.container = newContainer(app.Config)\n\n\tapp.initTracer()\n\t// HTTP Server\n\tport, err := strconv.Atoi(app.Config.Get(\"HTTP_PORT\"))\n\tif err != nil || port <= 0 {\n\t\tport = defaultHTTPPort\n\t}\n\n\tapp.httpServer = &httpServer{\n\t\trouter: gofrHTTP.NewRouter(),\n\t\tport: port,\n\t}\n\n\treturn app\n}", "func NewApplication(\n\tpeersRepository peers.Repository,\n\tpeersService peers.Service,\n) Application {\n\tpeerBuilder := peer.NewBuilder()\n\tpeersBuilder := peers.NewBuilder()\n\treturn createApplication(\n\t\tpeerBuilder,\n\t\tpeersBuilder,\n\t\tpeersRepository,\n\t\tpeersService,\n\t)\n}", "func (c config) App() *model.App { return c.app }", "func New(repo Repo, cfg Config) *App {\n\ta := &App{\n\t\tcfg: cfg,\n\t\trepo: repo,\n\t}\n\treturn a\n}", "func NewApp() *App {\n\treturn &App{\n\t\tName: filepath.Base(os.Args[0]),\n\t\tUsage: \"A new cli application\",\n\t\tVersion: \"0.0.0\",\n\t\tShowHelp: showHelp,\n\t\tShowVersion: showVersion,\n\t}\n}", "func New(options ...Option) Application {\n\topts := &Options{}\n\tfor _, opt := range options {\n\t\topt(opts)\n\t}\n\n\tif opts.StartupTimeout == 0 {\n\t\topts.StartupTimeout = 1000\n\t}\n\tif opts.ShutdownTimeout == 0 {\n\t\topts.ShutdownTimeout = 5000\n\t}\n\n\tif opts.AutoMaxProcs == nil || *opts.AutoMaxProcs {\n\t\tprocsutil.EnableAutoMaxProcs()\n\t}\n\n\tconfig.AppendServiceTag(opts.Tags...)\n\n\tapp := &application{\n\t\tquit: make(chan os.Signal),\n\t\tstartupTimeout: opts.StartupTimeout,\n\t\tshutdownTimeout: opts.ShutdownTimeout,\n\t\tboxes: append(opts.Boxes, &boxMetric{}),\n\t}\n\n\tsignal.Notify(app.quit, syscall.SIGINT, syscall.SIGTERM)\n\n\treturn app\n}", "func New(db *db.DB, gameService game.Service, userService user.Service) *App {\n\treturn &App{\n\t\tdb: db,\n\t\tgameService: gameService,\n\t\tuserService: userService,\n\t}\n}", "func NewApplication(app *kingpin.Application) ApplicationArguments {\n\treturn ApplicationArguments{\n\t\tApplication: app,\n\t\tlongs: map[string]bool{\n\t\t\t\"help-man\": true,\n\t\t\t\"help-long\": true,\n\t\t\t\"completion-bash\": true,\n\t\t\t\"completion-script-bash\": true,\n\t\t\t\"completion-script-zsh\": true,\n\t\t},\n\t\tshorts: map[rune]bool{},\n\t}\n}", "func NewApp() *App {\n\tapp := App{}\n\treturn &app\n}", "func newManifestApp() *types.App {\n\treturn &types.App{\n\t\tUser: \"0\",\n\t\tGroup: \"0\",\n\t}\n}", "func newManifestApp() *types.App {\n\treturn &types.App{\n\t\tUser: \"0\",\n\t\tGroup: \"0\",\n\t}\n}", "func New(descr string) App {\n\treturn &app{descr: descr}\n}", "func NewApp(host string, port int, log logger.Logger, config *viper.Viper) (*App, error) {\n\ta := &App{\n\t\thost: host,\n\t\tport: port,\n\t\tlog: log,\n\t\tconfig: config,\n\t}\n\terr := a.configure()\n\treturn a, err\n}", "func NewApplication(configPath *string) (*Application, error) {\n\n\tconfig, err := config.Load(configPath)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Load pulseaudio DBus module if needed. This module is mandatory, but it\n\t// can also be configured in system files. See package doc.\n\tisLoaded, err := pulseaudio.ModuleIsLoaded()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !isLoaded {\n\t\terr = pulseaudio.LoadModule()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Connect to the pulseaudio dbus service.\n\tclient, err := pulseaudio.New()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// defer pulse.Close()\n\n\taudio, err := audio.NewAudio(config, client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapplication := Application{client, isLoaded, audio, config}\n\n\tapplication.iniTrayIcon()\n\n\treturn &application, nil\n}", "func NewApp() *cli.App {\n\tif os.Getenv(\"HEROGATE_DEBUG\") == \"1\" || os.Getenv(\"HEROGATE_DEBUG\") == \"true\" {\n\t\tlogrus.SetLevel(logrus.DebugLevel)\n\t}\n\n\tapp := cli.NewApp()\n\tapp.Name = Name\n\tapp.Usage = \"Deploy and manage containerized applications like Heroku on AWS\"\n\tapp.Version = Version\n\n\tapp.Commands = []cli.Command{\n\t\tcommand.AppsCommand(),\n\t\tcommand.AppsCreateCommand(),\n\t\tcommand.AppsInfoCommand(),\n\t\tcommand.AppsOpenCommand(),\n\t\tcommand.AppsDestroyCommand(),\n\t\tcommand.ConfigCommand(),\n\t\tcommand.ConfigGetCommand(),\n\t\tcommand.ConfigSetCommand(),\n\t\tcommand.ConfigUnsetCommand(),\n\t\tcommand.PsCommand(),\n\t\tcommand.LogsCommand(),\n\t\tcommand.InternalCommand(),\n\t}\n\n\treturn app\n}", "func New(opts ...Option) *App {\n\toptions := options{\n\t\tctx: context.Background(),\n\t\tsigns: []os.Signal{syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT},\n\t}\n\n\tif id, err := uuid.NewUUID(); err == nil {\n\t\toptions.id = id.String()\n\t}\n\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\tctx, cancel := context.WithCancel(options.ctx)\n\treturn &App{\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\topts: options,\n\t}\n}", "func NewApp(g Generator) *App {\n\treturn &App{gene: g}\n}", "func NewApp(name string, basename string, opts ...Option) *App {\n\ta := &App{\n\t\tname: name,\n\t\tbasename: basename,\n\t}\n\n\tfor _, o := range opts {\n\t\to(a)\n\t}\n\n\treturn a\n}", "func initApp() *app {\n\tmainTimer := _wireRealTimeValue\n\tmainGreeter := greeter{\n\t\tT: mainTimer,\n\t}\n\tmainApp := &app{\n\t\tg: mainGreeter,\n\t}\n\treturn mainApp\n}", "func NewApp() App {\n\tapp := App{}\n\tapp.craterRequestHandler = newCraterHandler()\n\tapp.htmlTemplates = &craterTemplate{}\n\tapp.middleware = make([]handlerFunc, 0)\n\tapp.craterRouter = new(router)\n\tapp.settings = DefaultSettings()\n\n\treturn app\n}", "func (c *Container) CreateApp(appName string) (*Application, error) {\n\tappDataPath := fmt.Sprintf(\"%s/%s\", c.config.DataDir, util.SafeFilename(appName))\n\n\tif err := os.MkdirAll(appDataPath, 0700); err != nil {\n\t\treturn nil, errors.Wrap(err, \"create data dir\")\n\t}\n\tlevelDBStore, err := store.NewLevelDBStore(appDataPath)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"create data store dir\")\n\t}\n\n\tjsStore, err := store.NewJetstreamStore(c.clusterConn, fmt.Sprintf(\"%s_%s\", c.config.ClusterNatsPrefix, appName), levelDBStore)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"create jetstream store\")\n\t}\n\n\tif err := jsStore.Connect(c.config.DatastoreSyncTimeout); err != nil {\n\t\treturn nil, errors.Wrap(err, \"jetstream store connect\")\n\t}\n\n\tapp, err := NewApplication(c.config, appName, jsStore, cluster.NewClusterEventBus(c.clusterConn, fmt.Sprintf(\"%s.%s\", c.config.ClusterNatsPrefix, appName)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.apps[appName] = app\n\n\treturn app, nil\n}", "func New(opt *Options) *Application {\n\trouter := fasthttprouter.New()\n\n\treturn &Application{\n\t\tr: router,\n\t\tserv: &fasthttp.Server{\n\t\t\tReadTimeout: time.Second * 5,\n\t\t\tIdleTimeout: time.Second * 5,\n\t\t\tWriteTimeout: time.Second * 5,\n\t\t\tHandler: cors.AllowAll().Handler(router.Handler),\n\t\t},\n\t\tuc: opt.Uc,\n\t}\n}", "func New(config *Config, modules *Modules) *App {\n\teosws.DisabledWsMessage = config.DisabledWsMessage\n\treturn &App{\n\t\tShutter: shutter.New(),\n\t\tConfig: config,\n\t\tModules: modules,\n\t}\n\n}", "func NewApp() *App {\n\treturn &App{ver: \"v0\"}\n}", "func NewApp(host string, port int) (*App, error) {\n\ta := &App{\n\t\tHost: host,\n\t\tPort: port,\n\t}\n\t// setup DB\n\tdb, err := newDB(\"hades.db\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta.DB = db\n\t// setup Sessions\n\ts, err := newSessions(a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta.Sessions = s\n\t// setup Hades\n\th, err := hades.NewHades(db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta.Hades = h\n\t// setup Listener\n\tln, err := newListener(a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta.Listener = ln\n\t// setup Templates\n\tt, err := newTemplates(\"../../templates\")\n\ta.Templates = t\n\t// setup Router\n\tr := mux.NewRouter().StrictSlash(true)\n\t// static file handler\n\tsbox := packr.NewBox(\"../../static\")\n\tfsHandler := http.StripPrefix(\"/static/\", http.FileServer(sbox))\n\tr.PathPrefix(\"/static/\").Handler(fsHandler).Methods(\"GET\")\n\t// application routes\n\tr.HandleFunc(\"/\", a.getIndexHandler).Methods(\"GET\")\n\tr.HandleFunc(\"/error\", a.getErrorHandler).Methods(\"GET\")\n\tr.HandleFunc(\"/login\", a.getLoginHandler).Methods(\"GET\")\n\tr.HandleFunc(\"/login\", a.postLoginHandler).Methods(\"POST\")\n\tr.HandleFunc(\"/logout\", a.getLogoutHandler).Methods(\"POST\")\n\tr.HandleFunc(\"/add\", a.getAddHandler).Methods(\"GET\")\n\tr.HandleFunc(\"/add\", a.postAddHandler).Methods(\"POST\")\n\tr.HandleFunc(\"/{id}/action\", a.postActionHandler).Methods(\"POST\")\n\ta.Router = r\n\treturn a, nil\n}" ]
[ "0.746471", "0.72537917", "0.7247702", "0.7063687", "0.7057017", "0.6966784", "0.69611853", "0.6944947", "0.68381363", "0.68372166", "0.6823613", "0.6797753", "0.67797875", "0.67708886", "0.67537725", "0.67292297", "0.67292297", "0.6720004", "0.67192185", "0.67133147", "0.6685371", "0.66824573", "0.66758204", "0.6662521", "0.66218436", "0.6606069", "0.66033626", "0.66007805", "0.657977", "0.65772295", "0.656903", "0.65665984", "0.65386397", "0.6527058", "0.6523228", "0.65217084", "0.65138143", "0.6509107", "0.64898115", "0.64862514", "0.6473055", "0.64610845", "0.64566475", "0.64518833", "0.64506674", "0.6437825", "0.64254683", "0.64154583", "0.6405341", "0.6404544", "0.6402206", "0.6401852", "0.6395645", "0.6388439", "0.6387468", "0.63867915", "0.63846606", "0.63822836", "0.63791853", "0.6364491", "0.6364162", "0.6356938", "0.63534164", "0.63488466", "0.6346717", "0.6345235", "0.63421994", "0.63089013", "0.630623", "0.630623", "0.630623", "0.6300944", "0.6293743", "0.62889314", "0.6274539", "0.62718517", "0.6267122", "0.6263461", "0.62504876", "0.62472725", "0.62425375", "0.6240437", "0.62357193", "0.6232237", "0.62206876", "0.62206876", "0.6216921", "0.62159234", "0.6206874", "0.62068415", "0.6205372", "0.62032896", "0.6194192", "0.6189923", "0.6187908", "0.6183898", "0.61673576", "0.6165809", "0.6153781", "0.61529154" ]
0.7047488
5
Init initialises the function
func (o *Cos) Init(prms Prms) (err error) { for _, p := range prms { switch p.N { case "a": o.a = p.V case "b": o.b = p.V case "c": o.c = p.V case "b/pi": // b/π => b = b/pi * π o.b = p.V * math.Pi default: return chk.Err("cos: parameter named %q is invalid", p.N) } } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Init() {}", "func Init() {}", "func Init() error {\n\n}", "func init() {\n\t// init func\n}", "func Init() {\n\n}", "func init() {\n\t//todo...\n}", "func init() {}", "func init() {}", "func init() {}", "func init() {}", "func init() {\n\t// Initialization goes here\n}", "func init(){\n\n\tcustomers = loadAllCustomers()\n\tBuildRank()\n\tBuildTable()\n\n}", "func Init() {\n}", "func Init() {\n\tC.al_init()\n}", "func (o *CallbackOperator) Init() {}", "func init() {\n\n}", "func init() {\n\n}", "func initAll()", "func (s *GenerializedSystem)Init(f GenerializedFunctioner,r GenerializedRestrictioner,b bool,size int){\n\ts.fun = f\n\ts.restrict = r \n\ts.isMin = b\n\ts.size = size\n}", "func init() {\n}", "func init() {\n}", "func init() {\n}", "func init() {\n}", "func init() {\n}", "func init() {\n\tvar fnm string\n\n\t//This is the way to initialize a struct.\n\tConf = Config{}\n\n\t//Pass the variable as a pointer.\n\treadFlags(&fnm)\n\t\n\t//Call the function defined in config.\n\tConf.SetFileName(fnm)\n}", "func main_init()", "func (f *Fast) Init() (err error) {\n\tdata, err := getJSFile(f.client)\n\tif err != nil {\n\t\treturn\n\t}\n\n\turl, err := getAPIEndpoint(data)\n\tif err != nil {\n\t\treturn\n\t}\n\tf.url = \"https://\" + url\n\n\ttoken, err := getToken(data)\n\tif err != nil {\n\t\treturn\n\t}\n\tf.token = token\n\n\turlCount, err := getURLCount(data)\n\tif err != nil {\n\t\treturn\n\t}\n\tf.urlCount = urlCount\n\n\treturn\n}", "func Init() {\n\tonce.Do(initialize)\n}", "func (u *CidaasUtils) Init() error {\n\trefreshInterval := time.Hour\n\tif u.options.RefreshInterval != 0 {\n\t\trefreshInterval = u.options.RefreshInterval\n\t}\n\n\toptions := keyfunc.Options{\n\t\tRefreshInterval: &refreshInterval,\n\t\tRefreshErrorHandler: func(err error) {\n\t\t\tlog.Printf(\"There was an error with the jwt.KeyFunc\\nError: %s\", err.Error())\n\t\t},\n\t}\n\n\tjwks, err := keyfunc.Get(u.buildUrl(jwkEndpoint), options)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu.jwks = jwks\n\n\treturn nil\n}", "func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tfmt.Println(\"invoke Init Method\")\n\t\n\tvar tranHld TRAN_Holder\n\t \n if len(args) != 1 {\n return nil, errors.New(\"Incorrect number of arguments. Expecting 1\")\n }\n\n bytes, err := json.Marshal(tranHld)\n\n if err != nil { \n \treturn nil, errors.New(\"Error creating TRAN_Holder record\") \n }\n\n\terr = stub.PutState(\"tranIDs\", bytes)\n\t\n return nil, nil\n}", "func (l *Logs) Init(name string) {\n\tl.funcName = name\n\tl.startTime = time.Now()\n}", "func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\n\tif len(args) != 0 {\n\t\treturn nil, errors.New(\"incorrect number of arguments. Expecting 0\")\n\t}\n\n\treturn nil, nil\n}", "func init(){\n\tcaller=Te\n}", "func (t *UFAChainCode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tlogger.Info(\"Init called\")\n\t//Place an empty arry\n\tstub.PutState(ALL_ELEMENENTS, []byte(\"[]\"))\n\tstub.PutState(ALL_INVOICES, []byte(\"[]\"))\n\tts := time.Now().Format(time.UnixDate)\n\tstub.PutState(CHAIN_CODE_VERSION, []byte(ts))\n\treturn nil, nil\n}", "func (t *UFAChainCode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\r\n\tlogger.Info(\"Init called\")\r\n\t//Place an empty arry\r\n\tstub.PutState(ALL_ELEMENENTS, []byte(\"[]\"))\r\n\tstub.PutState(ALL_INVOICES, []byte(\"[]\"))\r\n\treturn nil, nil\r\n}", "func Init() {\n\tbtc()\n\tbch()\n\teth()\n\tltc()\n\tusdt()\n\n\tada()\n}", "func (c *Carta) Init(id, tipo, era, puntos, edificioGratis, cartaRequerida int, nombre string, produce, requiere [CANTIDAD_RECURSOS]int){\n c.Id = id\n c.Tipo = tipo\n c.era = era\n c.puntos = puntos\n c.edificioGratis = edificioGratis\n c.Nombre = nombre\n c.Produce = produce\n c.requiere = requiere\n c.cartaRequerida = cartaRequerida\n}", "func (c *Collector) Init() error { return nil }", "func (t *SimpleChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {\n\treturn nil, nil\n}", "func (w *wrapper) Init() {\n}", "func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error){\n\t//generate params\n\tvar params = C.CCParamsGen()\n\tstub.PutState( \"params\", []byte( C.GoString(params) ) )\n\n\t//get params obj\n\toParams := C.CCParamsLoad( params )\n\tC.CCStrDel(params)\n\n\t//init commit counter\n\tcounter := 0\n\tstub.PutState( \"counter\", []byte( strconv.Itoa(counter) ) )\n\n\t//generate accumulator\n\taccum := C.CCAccumGen( oParams )\n\tstub.PutState( \"accumlator\", []byte( C.GoString(accum) ) )\n\tC.CCStrDel(accum)\n\n\t//release object params\n\t//defer C.free( oParams )//??\n\tC.CCParamsDel( oParams )\n\n\treturn nil, nil\n}", "func (s *Flattener) Init(conf map[string]string) error {\n\treturn nil\n}", "func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error){\n\t//generate params\n\tvar params = C.CCParamsGen()\n\tstub.PutState( \"params\", []byte( C.GoString(params) ) )\n\n\t//get params obj\n\toParams := C.CCParamsLoad( params )\n\tC.CCStrDel(param)\n\n\t//init commit counter\n\tcounter := 0\n\tstub.PutState( \"counter\", []byte( strconv.Itoa(counter) ) )\n\n\t//generate accumulator\n\taccum := C.CCAccumGen( oParams )\n\tstub.PutState( \"accumlator\", []byte( C.GoString(accum) ) )\n\tC.CCStrDel(accum)\n\n\t//release object params\n\t//defer C.free( oParams )//??\n\tC.CCParamsDel( oParams )\n\n\treturn nil, nil\n}", "func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\treturn nil, nil\n}", "func (t *CarInsuranceChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tfmt.Println(\"Init..\")\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 1 argument.\")\n\t}\n\n\treturn nil, nil\n}", "func Init() {\n\t// noop for now\n}", "func Init() {\n\t// noop for now\n}", "func init() {\n\tSetup()\n}", "func (node *Node) Init(function ModuleFunction, arg interface{}) *Node {\n\tmodule := node.newModule(function, arg)\n\tnode.Lock()\n\t\tnode.Module = module\n\tnode.Unlock()\n\treturn node\n}", "func (c *Cmd) Init() {}", "func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\treturn nil, nil\n}", "func (t *Subrogationcode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tvar Aval int\n\tvar err error\n\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\t// Initialize the chaincode\n\tAval, err = strconv.Atoi(args[0])\n\tif err != nil {\n\t\treturn nil, errors.New(\"Expecting integer value for asset holding\")\n\t}\n\n\t// Write the state to the ledger\n\terr = stub.PutState(\"start\", []byte(strconv.Itoa(Aval))) //making a test var \"start\", I find it handy to read/write to it right away to test the network\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar empty []string\n\tjsonAsBytes, _ := json.Marshal(empty) //marshal an emtpy array of strings to clear the index\n\terr = stub.PutState(certIndexStr, jsonAsBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}", "func (si *ScanIterator) Init() {\n\t// Initialization\n}", "func Init() {\n\n\tprometheus.MustRegister(FunctionDurations)\n\tprometheus.MustRegister(FunctionCountTotal)\n\n}", "func (s *Sim) Init() {\n\ts.System = make([]*poly.Chain,0)\n\ts.solver = new(solver.RK4)\n\ts.solver.Mods = make([]solver.Modifier,0)\n\ts.solverInit = false\n}", "func (cc *Chaincode) Init(stub shim.ChaincodeStubInterface) sc.Response {\n\tfcn, params := stub.GetFunctionAndParameters()\n\tfmt.Println(\"Init()\", fcn, params)\n\treturn shim.Success(nil)\n}", "func (cc *Chaincode) Init(stub shim.ChaincodeStubInterface) sc.Response {\n\tfcn, params := stub.GetFunctionAndParameters()\n\tfmt.Println(\"Init()\", fcn, params)\n\treturn shim.Success(nil)\n}", "func (cc *Chaincode) Init(stub shim.ChaincodeStubInterface) sc.Response {\n\tfcn, params := stub.GetFunctionAndParameters()\n\tfmt.Println(\"Init()\", fcn, params)\n\treturn shim.Success(nil)\n}", "func (l *Logger) Init() {}", "func (i *InvariantsChecker) Init() {\n\ti.initStatus = colexecop.OperatorInitialized\n\ti.Input.Init()\n}", "func Init() {\n\tif initialized {\n\t\treturn\n\t}\n\tinitialized = true\n\tpopulatecnamechain()\n\tensureresourcefinder()\n\tloadphantomjs()\n}", "func init() {\n\tExample_invoke()\n}", "func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tfmt.Printf(\"Init called\")\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\t//return t.writeDummyProvider(stub)\n\treturn nil, nil\n}", "func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\n\tvar err error\n\tvar empty []string\n\tjsonAsBytes, _ := json.Marshal(empty)\n\terr = stub.PutState(assestIndexstr, jsonAsBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}", "func init() {\n\ti = New()\n}", "func (s *RepeatableBatchSource) Init() {}", "func (d *Default) Init(params map[interface{}]interface{}) error {\n\treturn nil\n}", "func (m *Main) Init() error {\n\n\tlog.Printf(\"Loading GeoCode data ...\")\n\t//u.LoadGeoCodes()\n\n\tvar err error\n\tm.indexer, err = pdk.SetupPilosa(m.Hosts, m.IndexName, u.Frames, m.BufferSize)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error setting up Pilosa '%v'\", err)\n\t}\n\t//m.client = m.indexer.Client()\n\n\t// Initialize S3 client\n\tsess, err2 := session.NewSession(&aws.Config{\n\t\tRegion: aws.String(m.AWSRegion)},\n\t)\n\n\tif err2 != nil {\n\t\treturn fmt.Errorf(\"Creating S3 session: %v\", err2)\n\t}\n\n\t// Create S3 service client\n\tm.S3svc = s3.New(sess)\n\n\treturn nil\n}", "func (c *ExternalityChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tmyLogger.Debug(\"Init Chaincode...\")\n\n\tfunction, args = dealParam(function, args)\n\tmyLogger.Debugf(\"Init function:%s ,args:%s\", function, args)\n\n\tc.stub = stub\n\tc.args = args\n\n\tif len(args) != 0 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 0\")\n\t}\n\n\terr := c.CreateTable()\n\tif err != nil {\n\t\tmyLogger.Errorf(\"Init error [CreateTable]:%s\", err)\n\t\treturn nil, err\n\t}\n\n\terr = c.InitTable()\n\tif err != nil {\n\t\tmyLogger.Errorf(\"Init error [InitTable]:%s\", err)\n\t\treturn nil, err\n\t}\n\tmyLogger.Debug(\"Init Chaincode...done\")\n\n\treturn nil, nil\n}", "func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\n\t//_, args := stub.GetFunctionAndParameters()\n\tvar Aval int\n\tvar err error\n\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\t// Initialize the chaincode\n\tAval, err = strconv.Atoi(args[0])\n\tif err != nil {\n\t\treturn nil, errors.New(\"Expecting integer value for asset holding\")\n\t}\n\n\t// Write the state to the ledger\n\terr = stub.PutState(\"abc\", []byte(strconv.Itoa(Aval))) //making a test var \"abc\" to read/write into ledger to test the network\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar empty []string\n\tjsonAsBytes, _ := json.Marshal(empty) //marshal an emtpy array of strings to clear the index\n\terr = stub.PutState(userIndexStr, jsonAsBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}", "func (_e *MockDataCoord_Expecter) Init() *MockDataCoord_Init_Call {\n\treturn &MockDataCoord_Init_Call{Call: _e.mock.On(\"Init\")}\n}", "func Init() error {\n\treturn Error(C.hackrf_init())\n}", "func Init() {\n\n\ttpl = template.Must(template.New(\"main\").Parse(\"{{define `contract`}}\" + contract + \"{{end}}\"))\n\t_ = template.Must(tpl.Parse(\"{{define `signature`}}\" + signature + \"{{end}}\"))\n\t_ = template.Must(tpl.Parse(\"{{define `invitation`}}\" + invitation + \"{{end}}\"))\n\t_ = template.Must(tpl.Parse(\"{{define `contractDetails`}}\" + contractDetails + \"{{end}}\"))\n\t_ = template.Must(tpl.Parse(\"{{define `verificationMail`}}\" + verificationMail + \"{{end}}\"))\n\tready = true\n\n}", "func (_e *MockQueryCoord_Expecter) Init() *MockQueryCoord_Init_Call {\n\treturn &MockQueryCoord_Init_Call{Call: _e.mock.On(\"Init\")}\n}", "func init() {\n fmt.Println(\"call init\")\n}", "func (d *Default) Init() error {\n\treturn nil\n}", "func Init() {\n\tC.yices_init()\n}", "func (uni *UniformMatrix3f) Init(name string) {\n\n\tuni.name = name\n}", "func (t *SmartLendingChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\n\tfmt.Println(\"Smart lending chaincode initiated\")\n\n\treturn nil, nil\n}", "func (c *Controller) Init() error { return nil }", "func (cc *Chaincode) Init(stub shim.ChaincodeStubInterface) sc.Response {\n\t_, _ = stub.GetFunctionAndParameters()\n\n\treturn shim.Success(nil)\n}", "func Init() {\n\trand.Seed(time.Now().Unix())\n}", "func Init() PTR {\n\treturn PTR(C.init())\n}", "func (ps *PrjnStru) Init(prjn emer.Prjn) {\n\tps.LeabraPrj = prjn.(LeabraPrjn)\n}", "func Init() {\n\twebservice.AppendToFunctionMap(configs.CTL, CTLFunctionMap)\n}", "func initConfig() {\n}", "func initConfig() {\n}", "func initConfig() {\n}", "func initConfig() {\n}", "func initConfig() {\n}", "func initConfig() {\n}", "func Init() error {\n\treturn InitWithProcAddrFunc(getProcAddress)\n}", "func Init() error {\n\treturn InitWithProcAddrFunc(getProcAddress)\n}", "func Init() error {\n\treturn InitWithProcAddrFunc(getProcAddress)\n}", "func Init() error {\n\treturn InitWithProcAddrFunc(getProcAddress)\n}", "func Init() error {\n\treturn InitWithProcAddrFunc(getProcAddress)\n}", "func init() {\n\t// <<-- Creer-Merge: init -->>\n\t// package initialization logic can go here\n\t// <<-- /Creer-Merge: init -->>\n}", "func (t *SBITransaction) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tfmt.Println(\"Inside INIT for test chaincode\")\n\treturn nil, nil\n}", "func init() {\n\tfmt.Println(\"Initialized\")\n}", "func (r *Ricochet) Init() {\n\tr.newconns = make(chan *OpenConnection)\n\tr.networkResolver = utils.NetworkResolver{}\n\tr.rni = new(utils.RicochetNetwork)\n}", "func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\terr := stub.PutState(\"contract_json\", []byte(args[0]))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}" ]
[ "0.7448294", "0.7448294", "0.73375386", "0.7336218", "0.7174763", "0.7160326", "0.71554255", "0.71554255", "0.71554255", "0.71554255", "0.70886326", "0.70496726", "0.7007015", "0.6971261", "0.686479", "0.6837379", "0.6837379", "0.6788343", "0.67447656", "0.6629871", "0.6629871", "0.6629871", "0.6629871", "0.6629871", "0.66291517", "0.6604161", "0.6576058", "0.652042", "0.6513453", "0.65110296", "0.6510533", "0.6488873", "0.64621216", "0.645187", "0.6450919", "0.64465564", "0.64368355", "0.64332086", "0.6432236", "0.6430959", "0.6427443", "0.6413165", "0.6413122", "0.64095455", "0.64087766", "0.6384089", "0.6384089", "0.6381881", "0.6375577", "0.6372622", "0.6362033", "0.636038", "0.6350849", "0.6348642", "0.63440096", "0.6339915", "0.6339915", "0.6339915", "0.63093954", "0.6306068", "0.630027", "0.6291978", "0.62917745", "0.62872297", "0.6279182", "0.6274999", "0.6262011", "0.625697", "0.62364024", "0.6235142", "0.6224711", "0.62094945", "0.6205024", "0.61813134", "0.61785394", "0.6143954", "0.614094", "0.61384594", "0.6136527", "0.61308527", "0.61247647", "0.61173165", "0.6113068", "0.6111614", "0.61101377", "0.6109894", "0.6109894", "0.6109894", "0.6109894", "0.6109894", "0.6109894", "0.6107969", "0.6107969", "0.6107969", "0.6107969", "0.6107969", "0.61043614", "0.609651", "0.6089926", "0.60878736", "0.6085769" ]
0.0
-1
F returns y = F(t, x)
func (o Cos) F(t float64, x []float64) float64 { return o.a*math.Cos(o.b*t) + o.c }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (i I) F() F {\n\treturn F{float64(i.X), float64(i.Y)}\n}", "func f(t float64, w float64) float64 {\n\treturn (-1 - 0.02*w + (acc * t))\n}", "func (o Mul) F(t float64, x []float64) float64 {\n\tif o.Fa != nil && o.Fb != nil {\n\t\treturn o.Fa.F(t, x) * o.Fb.F(t, x)\n\t}\n\tchk.Panic(\"mul: fa and fb functions are <nil>\\n\")\n\treturn 0\n}", "func (t *T) F() {}", "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 (o *ODE) F(x matrix.MatrixRO, t float64, beta matrix.MatrixRO) (matrix.Matrix, error) {\n\t//checking dimensions of input\n\tif x.Rows() != o.P || x.Cols() != 1 {\n\t\treturn nil, NewDimensionError(\"x\", o.P, 1, x.Rows(), x.Cols())\n\t}\n\n\tif o.Q != 0 && (beta.Rows() != o.Q || beta.Cols() != 1) {\n\t\treturn nil, NewDimensionError(\"beta\", o.Q, 1, beta.Rows(), beta.Cols())\n\t}\n\n\treturn o.f(x, t, beta), nil\n}", "func (p *CubicPolynomial) f0(t float64) float64 {\n\treturn p.a + t*(p.b+t*(p.c+p.d*t))\n}", "func f ( a int , a float64) int {\r\n\r\n}", "func Fp2f(x *float64) float64 {\n\tif x == nil {\n\t\t// this is not initialized yet - return NaN\n\t\treturn math.Log(-1.0)\n\t} else {\n\t\treturn *x\n\t}\n}", "func (p *CubicPolynomial) f1(t float64) float64 {\n\treturn p.b + t*(2*p.c+3*p.d*t)\n}", "func F(x int) {\n\t// fmt.Printf(\"f(%d)\\n\", x+0/x)\n\n\tdefer fmt.Printf(\"defer f(%d)\\n\", x)\n\n\tF(x - 1)\n}", "func (w *QWriter) F(f float64) {\n\tn := int(f)\n\tif float64(n) == f {\n\t\t// Fast path - just int.\n\t\tw.D(n)\n\t\treturn\n\t}\n\n\t// Slow path.\n\tw.FPrec(f, -1)\n}", "func (s *CubicSplineSDF2) f1(t float64) v2.Vec {\n\tcs, t := s.find(t)\n\treturn cs.f1(t)\n}", "func invoke(f func(float64, float64) float64) float64 {\n\treturn f(0.23, 0.9)\n}", "func (s *CubicSpline) f1(t float64) v2.Vec {\n\treturn v2.Vec{s.px.f1(t), s.py.f1(t)}\n}", "func TrapzF(x []float64, y Cb_yx) (A float64) {\n\tfor i := 1; i < len(x); i++ {\n\t\tA += (x[i] - x[i-1]) * (y(x[i]) + y(x[i-1])) / 2.0\n\t}\n\treturn A\n}", "func (s *CubicSplineSDF2) f0(t float64) v2.Vec {\n\tcs, t := s.find(t)\n\treturn cs.f0(t)\n}", "func Fx(params *Params, xs ...Num) Num {\n\tswitch len(xs) {\n\tcase 1: // f1(x1)\n\t\treturn Aprime(params, xs[0])\n\tcase 2: // f2(x1,x2)\n\t\treturn Trunc(\n\t\t\tA(\n\t\t\t\tC(params, xs[0]),\n\t\t\t\tC(params, xs[1]),\n\t\t\t\tFx(params, xs[0])),\n\t\t\tuint(params.fsize))\n\tcase 4: // f3(x1, x2, x3, x4)\n\t\treturn Trunc(\n\t\t\tA(\n\t\t\t\tC(params, xs[:2]...),\n\t\t\t\tC(params, xs[2:]...),\n\t\t\t\tFx(params, xs[:2]...)),\n\t\t\tuint(params.fsize))\n\tcase 8: // f4(x1, ... x8)\n\t\treturn Trunc(\n\t\t\tA(\n\t\t\t\tC(params, xs[:4]...),\n\t\t\t\tC(params, xs[4:]...),\n\t\t\t\tFx(params, xs[:4]...)),\n\t\t\tuint(params.fsize))\n\tcase 16:\n\t\treturn Trunc(\n\t\t\tA(\n\t\t\t\tC(params, xs[:8]...),\n\t\t\t\tC(params, xs[8:]...),\n\t\t\t\tFx(params, xs[:8]...)),\n\t\t\tuint(params.fsize))\n\tcase 32:\n\t\treturn Trunc(\n\t\t\tA(\n\t\t\t\tC(params, xs[:16]...),\n\t\t\t\tC(params, xs[16:]...),\n\t\t\t\tFx(params, xs[:16]...)),\n\t\t\tuint(params.fsize))\n\tcase 64:\n\t\treturn Trunc(\n\t\t\tA(\n\t\t\t\tC(params, xs[:32]...),\n\t\t\t\tC(params, xs[32:]...),\n\t\t\t\tFx(params, xs[:32]...)),\n\t\t\tuint(params.fsize))\n\tdefault:\n\t\tpanic(\"pos: fx called with unexpected nr of x-values: \" + strconv.Itoa(len(xs)))\n\t}\n}", "func AboveF(x, y float64, f F) int {\n\tif y > f(x) { // f(x) = x\n\t\treturn 1\n\t}\n\treturn -1\n}", "func logF(k, eta float64, y, n []float64) []float64 {\n\tv := make([]float64, len(y))\n\tfor i, _ := range v {\n\t\tv[i] = lnB(k*eta+y[i], k*(1-eta)+n[i]-y[i]) - lnB(k*eta, k*(1-eta))\n\t}\n\treturn v\n}", "func (s *CubicSpline) f0(t float64) v2.Vec {\n\treturn v2.Vec{s.px.f0(t), s.py.f0(t)}\n}", "func t(i int) float64 {\n\treturn t_0 + *deltaT*float64(i)\n}", "func F2fp(x float64) *float64 {\n\tif math.IsNaN(x) {\n\t\treturn nil\n\t} else {\n\t\treturn &x\n\t}\n}", "func Tsfn(phi, sinphi, e float64) float64 {\n\tsinphi *= e\n\n\t/* avoid zero division, fail gracefully */\n\tdenominator := 1.0 + sinphi\n\tif denominator == 0.0 {\n\t\treturn math.MaxFloat64\n\t}\n\n\treturn (math.Tan(.5*(PiOverTwo-phi)) /\n\t\tmath.Pow((1.-sinphi)/(denominator), .5*e))\n}", "func (s *Serializer) F(f func(s *Serializer)) *Serializer { return s.FC(f, true) }", "func F(p int) {}", "func F() {}", "func F() {}", "func (neuralNet *NeuralNet) f(theta []float64) (sum float64) {\n\tneuralNet.setAllWeights(theta)\n\n\tneuralNet.doBackPropagation(neuralNet.getInputs(), neuralNet.guess)\n\n\tfor _, outputNeuron := range neuralNet.outputLayer.neurons {\n\t\t// fmt.Println(\"outputNeuron\", outputNeuron)\n\t\tsum += math.Pow(outputNeuron.delta, 2.0)\n\t}\n\treturn\n}", "func F(f string, v ...interface{}) {}", "func funcLastOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tel := vals[0].(Matrix)[0]\n\n\tvar f FPoint\n\tif len(el.Floats) > 0 {\n\t\tf = el.Floats[len(el.Floats)-1]\n\t}\n\n\tvar h HPoint\n\tif len(el.Histograms) > 0 {\n\t\th = el.Histograms[len(el.Histograms)-1]\n\t}\n\n\tif h.H == nil || h.T < f.T {\n\t\treturn append(enh.Out, Sample{\n\t\t\tMetric: el.Metric,\n\t\t\tF: f.F,\n\t\t})\n\t}\n\treturn append(enh.Out, Sample{\n\t\tMetric: el.Metric,\n\t\tH: h.H,\n\t})\n}", "func (p *CubicPolynomial) f2(t float64) float64 {\n\treturn 2*p.c + 6*p.d*t\n}", "func future_value_formula(pv float64, i float64, n int64) float64 {\n\tif n < 0 {\n\t\t// should throw an error\n\t}\n\n\tvar fv float64 = math.Pow( float64(1) + i, float64(n)) * pv\n\treturn fv\n}", "func (f F) Survival(x float64) float64 {\n\treturn 1 - f.CDF(x)\n}", "func IFFT(scope *Scope, input tf.Output) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"IFFT\",\n\t\tInput: []tf.Input{\n\t\t\tinput,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func TempFromF(f int) Temp {\n\tc := math.Floor(float64((f - 32)) / 1.8)\n\treturn Temp(c)\n\n}", "func FMod(arg float64, arg2 float64) float64 {\n\tflooRit := Floor(arg / arg2)\n\treturn arg - (flooRit * arg2)\n}", "func fibonacci() func() int {\n\txN := 0\n\tyN := 1\n\tfN := 0\n\tcnt := 0\n\t\n\treturn func() int {\n\t\tif cnt <= 0 {\n\t\t\tcnt++\n\t\t\treturn xN\n\t\t} else if cnt <= 1 {\n\t\t\tcnt++\n\t\t\treturn yN\n\t\t} else {\n\t\t\tcnt++\n\t\t\t// tracing the iterations, the values rotate around,\n\t\t\t// shift through the variables..\n\t\t\tfN = xN /*0, 1, 1, 2, 3, */ + yN /*1, 1, 2, 3, 5*/\n\t\t\t\n\t\t\txN = yN /*1, 1, 2, 3, 5, */\n\t\t\tyN = fN /*1, 2, 3, 5, 8, */\n\t\t\t\n\t\t\treturn fN /*1, 2, 3, 5, 8, ...*/\n\t\t}\n\t}\n}", "func (g *F) Call(p ...float64) []float64 {\n\tcoords := make([]float64, len(p))\n\tfor i := 0; i < len(p); i++ {\n\t\tcoords[i] = g.f[i](p...)\n\t}\n\treturn coords\n}", "func (x *Float) Acc() Accuracy {}", "func Fv(rate decimal.Decimal, nper int64, pmt decimal.Decimal, pv decimal.Decimal, when paymentperiod.Type) decimal.Decimal {\n\tone := decimal.NewFromInt(1)\n\tminusOne := decimal.NewFromInt(-1)\n\tdWhen := decimal.NewFromInt(when.Value())\n\tdRateWithWhen := rate.Mul(dWhen)\n\tdNper := decimal.NewFromInt(nper)\n\n\tfactor := one.Add(rate).Pow(dNper)\n\tsecondFactor := factor.Sub(one).Mul(one.Add(dRateWithWhen)).Div(rate)\n\n\treturn pv.Mul(factor).Add(pmt.Mul(secondFactor)).Mul(minusOne)\n}", "func f1(x int) int {\n\treturn x / 3 * 3\n}", "func (dt *StdTask) Func() func(id int64) {\n return dt.F\n}", "func (s *CubicSpline) f2(t float64) v2.Vec {\n\treturn v2.Vec{s.px.f2(t), s.py.f2(t)}\n}", "func f6(ctx *Context, l0 int32) {\n\tctx.f.F6(ctx, l0)\n}", "func MToF(m Meter) Foot { return Foot(m / 0.3048) }", "func f(n int) int {\n\tif n == 0 {\n\t\treturn 1\n\t}\n\treturn n * f(n-1)\n}", "func FEQUAL(x float64, y float64) float64 {\n\tif x == y {\n\t\treturn x\n\t} else {\n\t\treturn math.NaN()\n\t}\n}", "func (nch *NvmeHealth) TempF() float32 {\n\treturn (nch.TempC() * (9.0 / 5.0)) + 32.0\n}", "func replaceCalculateTxFee(f func(*withdrawalTx) btcutil.Amount) func() {\n\torig := calculateTxFee\n\tcalculateTxFee = f\n\treturn func() { calculateTxFee = orig }\n}", "func t1f0(b bool) int {\n\tif b {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func MToF(m Meter) Feet { return Feet(m / 0.3048) }", "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 gradient(f fn, X []float64) []float64 {\n\tvar f0, f1, x_i float64\n\tG := make([]float64, len(X))\n\tf0 = f(X)\n\tfor i := range X {\n\t\tx_i = X[i]\n\t\tX[i] += eps\n\t\tf1 = f(X)\n\t\tG[i] = (f1 - f0) / eps\n\t\tX[i] = x_i\n\t}\n\treturn G\n}", "func naiveDFT(x []complex128) (y []complex128) {\n\ty = make([]complex128, len(x))\n\tdt := -2 * math.Pi / float64(len(x))\n\tfor i := range x {\n\t\targ1 := float64(i) * dt\n\t\tfor k, xv := range x {\n\t\t\targ2 := float64(k) * arg1\n\t\t\ty[i] += complex(math.Cos(arg2), math.Sin(arg2)) * xv\n\t\t}\n\t}\n\treturn y\n}", "func (ob *Observation) run(f interface{}, args ...interface{}) []interface{} {\n\tfv := reflect.ValueOf(f)\n\tif len(ob.Name) == 0 {\n\t\tif rf := runtime.FuncForPC(fv.Pointer()); rf != nil {\n\t\t\tob.Name = rf.Name()\n\t\t}\n\t}\n\n\tfvtype := fv.Type()\n\tif len(args) != fvtype.NumIn() {\n\t\tpanic(fmt.Errorf(\"Incorrect number of inputs to %v\", ob.Name))\n\t}\n\n\tinputs := []reflect.Value{}\n\tfor i, a := range args {\n\t\ttmp := reflect.ValueOf(a)\n\t\ttmptype := tmp.Type()\n\t\tin := fvtype.In(i)\n\t\tif tmptype != in {\n\t\t\tpanic(fmt.Errorf(\"Invalid input (%v) to function (expected %v)\",\n\t\t\t\ttmptype.Kind(),\n\t\t\t\tin.Kind(),\n\t\t\t))\n\t\t}\n\t\tinputs = append(inputs, tmp)\n\t}\n\n\tret := ob.make_call(fv, inputs)\n\tif ob.Panic != nil {\n\t\treturn nil\n\t}\n\n\tfor _, r := range ret {\n\t\tob.Outputs = append(ob.Outputs, r.Interface())\n\t}\n\treturn ob.Outputs\n}", "func newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {\n\treturn func(time float64) float64 {\n\t\treturn ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)\n\t}\n}", "func newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {\n\treturn func(time float64) float64 {\n\t\treturn ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)\n\t}\n}", "func CtoF(t float32) float32 {\n\treturn (t*9/5 + 32)\n}", "func (s *CubicSplineSDF2) f2(t float64) v2.Vec {\n\tcs, t := s.find(t)\n\treturn cs.f2(t)\n}", "func f1(n int) int {\n\tif n == 0 {\n\t\treturn 0\n\t}\n\tif n == 1 {\n\t\treturn 1\n\t}\n\treturn f1(n-1) + f1(n-2)\n}", "func Dfct(n int, a []float64, t []float64, ip []int, w []float64) {\n\tvar j, k, l, m, mh, nw, nc int\n\tvar xr, xi, yr, yi float64\n\n\tnw = ip[0]\n\tif n > (nw << 3) {\n\t\tnw = n >> 3\n\t\tmakewt(nw, ip, w)\n\t}\n\tnc = ip[1]\n\tif n > (nc << 1) {\n\t\tnc = n >> 1\n\t\tmakect(nc, ip, w[nw:])\n\t}\n\tm = n >> 1\n\tyi = a[m]\n\txi = a[0] + a[n]\n\ta[0] -= a[n]\n\tt[0] = xi - yi\n\tt[m] = xi + yi\n\tif n > 2 {\n\t\tmh = m >> 1\n\t\tfor j = 1; j < mh; j++ {\n\t\t\tk = m - j\n\t\t\txr = a[j] - a[n-j]\n\t\t\txi = a[j] + a[n-j]\n\t\t\tyr = a[k] - a[n-k]\n\t\t\tyi = a[k] + a[n-k]\n\t\t\ta[j] = xr\n\t\t\ta[k] = yr\n\t\t\tt[j] = xi - yi\n\t\t\tt[k] = xi + yi\n\t\t}\n\t\tt[mh] = a[mh] + a[n-mh]\n\t\ta[mh] -= a[n-mh]\n\t\tdctsub(m, a, nc, w[nw:])\n\t\tif m > 4 {\n\t\t\tcftfsub(m, a, ip, nw, w)\n\t\t\trftfsub(m, a, nc, w[nw:])\n\t\t} else if m == 4 {\n\t\t\tcftfsub(m, a, ip, nw, w)\n\t\t}\n\t\ta[n-1] = a[0] - a[1]\n\t\ta[1] = a[0] + a[1]\n\t\tfor j = m - 2; j >= 2; j -= 2 {\n\t\t\ta[2*j+1] = a[j] + a[j+1]\n\t\t\ta[2*j-1] = a[j] - a[j+1]\n\t\t}\n\t\tl = 2\n\t\tm = mh\n\t\tfor m >= 2 {\n\t\t\tdctsub(m, t, nc, w[nw:])\n\t\t\tif m > 4 {\n\t\t\t\tcftfsub(m, t, ip, nw, w)\n\t\t\t\trftfsub(m, t, nc, w[nw:])\n\t\t\t} else if m == 4 {\n\t\t\t\tcftfsub(m, t, ip, nw, w)\n\t\t\t}\n\t\t\ta[n-l] = t[0] - t[1]\n\t\t\ta[l] = t[0] + t[1]\n\t\t\tk = 0\n\t\t\tfor j = 2; j < m; j += 2 {\n\t\t\t\tk += l << 2\n\t\t\t\ta[k-l] = t[j] - t[j+1]\n\t\t\t\ta[k+l] = t[j] + t[j+1]\n\t\t\t}\n\t\t\tl <<= 1\n\t\t\tmh = m >> 1\n\t\t\tfor j = 0; j < mh; j++ {\n\t\t\t\tk = m - j\n\t\t\t\tt[j] = t[m+k] - t[m+j]\n\t\t\t\tt[k] = t[m+k] + t[m+j]\n\t\t\t}\n\t\t\tt[mh] = t[m+mh]\n\t\t\tm = mh\n\t\t}\n\t\ta[l] = t[0]\n\t\ta[n] = t[2] - t[1]\n\t\ta[0] = t[2] + t[1]\n\t} else {\n\t\ta[1] = a[0]\n\t\ta[2] = t[0]\n\t\ta[0] = t[1]\n\t}\n}", "func computeFwd(_ context.Context, n *node) stateFn {\n\tv, err := n.op.Do(n.inputValues...)\n\tif err != nil {\n\t\tn.err = err\n\t\treturn nil\n\t}\n\tn.output = v\n\treturn emitOutput\n}", "func fqSqrt(c, u, v *Fq, s int) {\n\tt0, t1, t, r := &Fp{}, &Fp{}, &Fp{}, &Fp{}\n\ta, b, g := &Fp{}, &Fp{}, &Fp{}\n\n\t// a = u0*v0 + u1*v1\n\tfpMul(a, &u[0], &v[0])\n\tfpMul(t0, &u[1], &v[1])\n\tfpAdd(a, a, t0)\n\n\t// b = v0^2 + v1^2\n\tfpSqr(b, &v[0])\n\tfpSqr(t0, &v[1])\n\tfpAdd(b, b, t0)\n\n\t// g = u1*v0 - u0*v1\n\tfpMul(g, &u[1], &v[0])\n\tfpMul(t0, &u[0], &v[1])\n\tfpSub(g, g, t0)\n\n\t// t = 2(a + sqrt(a^2+g^2)) = 2*(a + (a^2+g^2)^(2^125))\n\t// if t=0; then t = 2*(a - (a^2+g^2)^(2^125))\n\tfpSqr(t0, a)\n\tfpSqr(t1, g)\n\tfpAdd(t0, t0, t1)\n\tfor i := 0; i < 125; i++ {\n\t\tfpSqr(t0, t0)\n\t}\n\tfpAdd(t, a, t0)\n\tif t.isZero() {\n\t\tfpSub(t, a, t0)\n\t}\n\tfpAdd(t, t, t)\n\n\t// r = (t*b^3)^(2^125-1)\n\tfpSqr(r, b)\n\tfpMul(r, r, b)\n\tfpMul(r, r, t)\n\tfpTwo1251(r, r)\n\n\t// x0 = (r*b*t)/2\n\t// x1 = (r*b*g)\n\tfpMul(&c[1], r, b)\n\tfpMul(&c[0], &c[1], t)\n\tfpHlf(&c[0], &c[0])\n\tfpMul(&c[1], &c[1], g)\n\n\t// if b*(2*x0)^2 == t then (x0,x1) <- (x1,x0)\n\tfpAdd(t0, &c[0], &c[0])\n\tfpSqr(t0, t0)\n\tfpMul(t0, t0, b)\n\tfpSub(t0, t0, t)\n\tif !t0.isZero() {\n\t\t*t0 = c[0]\n\t\tc[0] = c[1]\n\t\tc[1] = *t0\n\t}\n\n\tif fqSgn(c) != s {\n\t\tfqNeg(c, c)\n\t}\n}", "func (v Vec) FFill(f func() float64) Vec {\n\tfor i := range v {\n\t\tv[i] = f()\n\t}\n\treturn v\n}", "func (c *Correlation) FSFA() {\n\t/*\n\t\tWill check whether the length of the metrics array is\n\t\t2. Can check correlation between only two variables.\n\t\tThen it will check whether the data types of the variables\n\t\tare float.\n\t*/\n\t//Checking the length between the metrics\n\tif len(c.ms) != 2 {\n\t\tc.relevant = false\n\t\treturn\n\t}\n\n\t//checking the data types of the metrics\n\tif c.ms[0].DataType != Float || c.ms[1].DataType != Float {\n\t\tc.relevant = false\n\t\treturn\n\t}\n\n\t//Everything is fine\n\tc.relevant = true\n}", "func (fn *formulaFuncs) FV(argsList *list.List) formulaArg {\n\tif argsList.Len() < 3 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"FV requires at least 3 arguments\")\n\t}\n\tif argsList.Len() > 5 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"FV allows at most 5 arguments\")\n\t}\n\trate := argsList.Front().Value.(formulaArg).ToNumber()\n\tif rate.Type != ArgNumber {\n\t\treturn rate\n\t}\n\tnper := argsList.Front().Next().Value.(formulaArg).ToNumber()\n\tif nper.Type != ArgNumber {\n\t\treturn nper\n\t}\n\tpmt := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()\n\tif pmt.Type != ArgNumber {\n\t\treturn pmt\n\t}\n\tpv, typ := newNumberFormulaArg(0), newNumberFormulaArg(0)\n\tif argsList.Len() >= 4 {\n\t\tif pv = argsList.Front().Next().Next().Next().Value.(formulaArg).ToNumber(); pv.Type != ArgNumber {\n\t\t\treturn pv\n\t\t}\n\t}\n\tif argsList.Len() == 5 {\n\t\tif typ = argsList.Back().Value.(formulaArg).ToNumber(); typ.Type != ArgNumber {\n\t\t\treturn typ\n\t\t}\n\t}\n\tif typ.Number != 0 && typ.Number != 1 {\n\t\treturn newErrorFormulaArg(formulaErrorNA, formulaErrorNA)\n\t}\n\tif rate.Number != 0 {\n\t\treturn newNumberFormulaArg(-pv.Number*math.Pow(1+rate.Number, nper.Number) - pmt.Number*(1+rate.Number*typ.Number)*(math.Pow(1+rate.Number, nper.Number)-1)/rate.Number)\n\t}\n\treturn newNumberFormulaArg(-pv.Number - pmt.Number*nper.Number)\n}", "func (af *filtBase) Run(d []float64, x [][]float64) ([]float64, []float64, [][]float64, error) {\n\t//TODO\n\t//measure the data and check if the dimension agree\n\tN := len(x)\n\tif len(d) != N {\n\t\treturn nil, nil, nil, errors.New(\"the length of slice d and x must agree\")\n\t}\n\taf.n = len(x[0])\n\n\ty := make([]float64, N)\n\te := make([]float64, N)\n\tw := make([]float64, af.n)\n\twHist := make([][]float64, N)\n\t//adaptation loop\n\tfor i := 0; i < N; i++ {\n\t\tw = af.w.RawRowView(0)\n\t\ty[i] = floats.Dot(w, x[i])\n\t\te[i] = d[i] - y[i]\n\t\tcopy(wHist[i], w)\n\t}\n\treturn y, e, wHist, nil\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 (f *Filter) Do(x float64) float64 {\n\tx = x * f.Gain\n\ty := f.B[0]*x + f.d1\n\tf.d1 = f.B[1]*x - f.A[1]*y + f.d2\n\tf.d2 = f.B[2]*x - f.A[2]*y\n\treturn y\n}", "func Erf(x float64) float64 {\n\t// Constants\n\ta1 := 0.254829592\n\ta2 := -0.284496736\n\ta3 := 1.421413741\n\ta4 := -1.453152027\n\ta5 := 1.061405429\n\tp := 0.3275911\n\n\t// Save the sign of x\n\tvar sign float64\n\tif x < 0.0 {\n\t\tsign = -1.0\n\t} else {\n\t\tsign = 1.0\n\t}\n\tx = math.Abs(x)\n\n\t// Formula 7.1.26 given in Abramowitz and Stegun\n\tt := 1.0 / (1.0 + p*x)\n\ty := 1.0 - ((((a5*t+a4)*t+a3)*t+a2)*t+a1)*t*math.Pow(math.E, -x*x)\n\treturn sign * y\n}", "func PublishF(callback func(interface{}, error)) FuncF {\n\treturn func(f Func) Func {\n\t\treturn func(value interface{}) (interface{}, error) {\n\t\t\tvalue, err := f(value)\n\t\t\tcallback(value, err)\n\t\t\treturn value, err\n\t\t}\n\t}\n}", "func Map(f func(float64) float64, x []float64) []float64 {\n\ty := make([]float64, len(x))\n\tfor n, xn := range x {\n\t\ty[n] = f(xn)\n\t}\n\treturn y\n}", "func newton(f []int, f_length int, x, xtol, ftol float64, itermax int) float64{\n fx := feval(f, f_length, x)\n var df = deriv(f, f_length);\n var root float64\n var fdx float64;\n var d float64;\n if abs(fx) <= ftol {\n root = x\n } else{\n for i := 1; i < itermax; i++ {\n fdx = feval(df, f_length-1, x)\n d = float64(fx)/fdx;\n x = x - d\n fx = feval(f, f_length, x)\n if (abs(d) <= xtol) || (abs(fx) <= ftol) {\n root = x\n break\n }\n }\n }\n return root\n}", "func eulerStep(f fdy, x, y, h float64) float64 {\n\treturn y + h*f(x, y)\n}", "func eulerStep(f fdy, x, y, h float64) float64 {\n\treturn y + h*f(x, y)\n}", "func Fahrenheit(f float64) Temperature {\n\treturn Temperature(f)\n}", "func FuncPass(a, x Edge) Node {\n\n\tnode := MakeNode(\"pass\", []*Edge{&a}, []*Edge{&x}, nil, func(n *Node) error { n.Dsts[0].DstPut(n.Srcs[0].SrcGet()); return nil })\n\treturn node\n\n}", "func (t Temperature) Fahrenheit() float64 {\n\treturn float64(t)\n}", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9.0/5.0 + 32.0) }", "func mathFmod(ctx phpv.Context, args []*phpv.ZVal) (*phpv.ZVal, error) {\n\tvar x, y phpv.ZFloat\n\t_, err := core.Expand(ctx, args, &x, &y)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn phpv.ZFloat(math.Mod(float64(x), float64(y))).ZVal(), nil\n}", "func NewF(f float64) Fixed {\n\tif math.IsNaN(f) {\n\t\treturn Fixed{fp: nan}\n\t}\n\tif f >= MAX || f <= -MAX {\n\t\treturn NaN\n\t}\n\tround := .5\n\tif f < 0 {\n\t\tround = -0.5\n\t}\n\n\treturn Fixed{fp: int64(f*float64(scale) + round)}\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 (t *Table) Getf(row, col int) float64 {\n\tif row >= len(t.Row) || col >= len(t.ColDefs) {\n\t\treturn float64(0)\n\t}\n\treturn t.Row[row].Col[col].Fval\n}", "func (dt *StdTask) SetFunc(f func(id int64)) {\n dt.F = f\n}", "func polynomialFunction(a ...float64) Y {\n\treturn func(x ...float64) float64 {\n\t\tvar y float64\n\t\tfor i, aa := range a {\n\t\t\ty += aa * math.Pow(x[0], float64(i))\n\t\t}\n\t\treturn y\n\t}\n}", "func pass[T any](f func(T)) func(T) error {\n\treturn func(v T) error {\n\t\tf(v)\n\t\treturn nil\n\t}\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 AddF(n ...float64) float64 {\n\ts := 0.\n\tfor _, v := range n {\n\t\ts += v\n\t}\n\treturn s\n}", "func KToF(k Kelvin) Fahrenheit { return Fahrenheit((k-273.15)*9.0/5.0 + 32.0) }", "func (re *RandomEqualize) Forward(x *ts.Tensor) *ts.Tensor {\n\tr := randPvalue()\n\tvar out *ts.Tensor\n\tswitch {\n\tcase r < re.pvalue:\n\t\tout = equalize(x)\n\tdefault:\n\t\tout = x.MustShallowClone()\n\t}\n\n\treturn out\n}", "func funcChanges(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tfloats := vals[0].(Matrix)[0].Floats\n\tchanges := 0\n\n\tif len(floats) == 0 {\n\t\t// TODO(beorn7): Only histogram values, still need to add support.\n\t\treturn enh.Out\n\t}\n\n\tprev := floats[0].F\n\tfor _, sample := range floats[1:] {\n\t\tcurrent := sample.F\n\t\tif current != prev && !(math.IsNaN(current) && math.IsNaN(prev)) {\n\t\t\tchanges++\n\t\t}\n\t\tprev = current\n\t}\n\n\treturn append(enh.Out, Sample{F: float64(changes)})\n}", "func (logger *Logger) Ftracef(w io.Writer, format string, a ...any) {\n\tlogger.echo(w, level.Trace, format, a...)\n}", "func F(x interface{}) bool {\n\t_, ok := x.(interface {\n\t\tf()\n\t})\n\treturn ok\n}", "func (f *Float) Set(x *Float) *Float {\n\tf.doinit()\n\tC.mpf_set(&f.i[0], &x.i[0])\n\treturn f\n}", "func funcDelta(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\treturn extrapolatedRate(vals, args, enh, false, false)\n}", "func Z(f L) L {\n\thelp := func(x L) L {\n\t\treturn f(func(v L) L {\n\t\t\treturn x(x)(v)\n\t\t})\n\t}\n\treturn help(help)\n}", "func FTick(d Doner, f func()) {\n\tfor _ = range Tick(d) {\n\t\tf()\n\t}\n}", "func evenFib() func() float64 {\n\tx := float64(0)\n\ty := float64(1)\n\treturn func() float64 {\n\t\tx, y = y, x+y\n\t\treturn y\n\t}\n}", "func (_Precompiledbn256 *Precompiledbn256Caller) F(opts *bind.CallOpts, rounds uint32, h [2][32]byte, m [4][32]byte, t [2][8]byte, f bool) ([2][32]byte, error) {\n\tvar (\n\t\tret0 = new([2][32]byte)\n\t)\n\tout := ret0\n\terr := _Precompiledbn256.contract.Call(opts, out, \"F\", rounds, h, m, t, f)\n\treturn *ret0, err\n}" ]
[ "0.642726", "0.63500917", "0.6322419", "0.62878615", "0.62501085", "0.6243732", "0.6014716", "0.5920861", "0.5854409", "0.5807788", "0.5751894", "0.56997144", "0.5676256", "0.5650777", "0.56495255", "0.5641937", "0.5522204", "0.549365", "0.548898", "0.54700804", "0.5442039", "0.532279", "0.5315114", "0.53115356", "0.52721184", "0.5242887", "0.52421665", "0.52421665", "0.52077544", "0.5189799", "0.51837045", "0.51659656", "0.50767446", "0.5050554", "0.5046847", "0.5018776", "0.5017069", "0.49853504", "0.49778715", "0.49616832", "0.4955448", "0.4955403", "0.494922", "0.49474892", "0.49431202", "0.4933246", "0.49176022", "0.4912461", "0.49029723", "0.48940802", "0.4889192", "0.48507062", "0.4844699", "0.48222533", "0.48140022", "0.4813327", "0.48117316", "0.48117316", "0.48112398", "0.48088655", "0.48052666", "0.47999018", "0.479118", "0.47864202", "0.47593933", "0.47446716", "0.47409907", "0.47366884", "0.47342128", "0.4733719", "0.47329834", "0.47310475", "0.47252867", "0.47243345", "0.47222972", "0.47222972", "0.4705684", "0.47018325", "0.46994954", "0.46981534", "0.4694472", "0.4691805", "0.46854234", "0.46811226", "0.4659044", "0.4657116", "0.46550706", "0.46452665", "0.46450543", "0.46397132", "0.46361548", "0.4612672", "0.46121994", "0.4607349", "0.4604368", "0.4598993", "0.45965502", "0.4595009", "0.45936877", "0.45763463" ]
0.69339114
0
SetName sets the name field.
func (ac *AppCreate) SetName(s string) *AppCreate { ac.mutation.SetName(s) return ac }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cli *SetWrapper) SetName(name string) error {\n\treturn cli.set.SetValue(fieldSetName, name)\n}", "func (s UserSet) SetName(value string) {\n\ts.RecordCollection.Set(models.NewFieldName(\"Name\", \"name\"), value)\n}", "func (f *Flow) setName(n string) {\n\tf.Name = n\n}", "func (s *MyTestStruct) SetName(n string) *MyTestStruct {\n\tif s.mutable {\n\t\ts.field_Name = n\n\t\treturn s\n\t}\n\n\tres := *s\n\tres.field_Name = n\n\treturn &res\n}", "func (m *LabelActionBase) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *SDKScriptCollectorAttribute) SetName(val string) {\n\n}", "func (k *Kitten) SetName(name string) {\n k.Name = name\n}", "func (b *TestDriver) SetName(n string) { b.name = n }", "func (m *CalendarGroup) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (d *Driver) SetName(n string) { d.name = n }", "func (fp MockProvider) SetName(name string) {\n\tfp.faux.SetName(name)\n}", "func (m *PolicyRule) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (suo *SettingUpdateOne) SetName(s string) *SettingUpdateOne {\n\tsuo.mutation.SetName(s)\n\treturn suo\n}", "func (muo *ModelUpdateOne) SetName(s string) *ModelUpdateOne {\n\tmuo.mutation.SetName(s)\n\treturn muo\n}", "func (_Contract *ContractTransactor) SetName(opts *bind.TransactOpts, node [32]byte, name string) (*types.Transaction, error) {\n\treturn _Contract.contract.Transact(opts, \"setName\", node, name)\n}", "func (w *Worker) SetName(n string) {\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\tw.wr.name = n\n}", "func (nc *NodeCreate) SetName(s string) *NodeCreate {\n\tnc.mutation.SetName(s)\n\treturn nc\n}", "func (e *ObservableEditableBuffer) SetName(name string) {\n\tif e.Name() == name {\n\t\treturn\n\t}\n\n\t// SetName always forces an update of the tag.\n\t// TODO(rjk): This reset of filtertagobservers might now be unnecessary.\n\te.filtertagobservers = false\n\tbefore := e.getTagStatus()\n\tdefer e.notifyTagObservers(before)\n\n\tif e.seq > 0 {\n\t\t// TODO(rjk): Pass in the name, make the function name better reflect its purpose.\n\t\te.f.UnsetName(e.Name(), e.seq)\n\t}\n\te.setfilename(name)\n}", "func (e *Entry) SetName(name string) {\n\tif utf8.ValidString(name) {\n\t\te.Name = name\n\t} else {\n\t\te.NameRaw = []byte(name)\n\t}\n}", "func (m *WorkbookPivotTable) SetName(value *string)() {\n m.name = value\n}", "func (c *Mock) SetName(v string) interfaces.Client {\n\treturn c.FakeSetName(v)\n}", "func (m *AgedAccountsPayable) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func SetName(name string) {\n\tcname := C.CString(name)\n\t/*if Name() != \"\" {\n\t\tC.free(unsafe.Pointer(C.rl_readline_name))\n\t}*/\n\tC.rl_readline_name = cname\n}", "func (mu *ModelUpdate) SetName(s string) *ModelUpdate {\n\tmu.mutation.SetName(s)\n\treturn mu\n}", "func (m *DeviceManagementApplicabilityRuleOsEdition) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func SetName(name string) { note.Name = name }", "func (m *WorkbookWorksheet) SetName(value *string)() {\n m.name = value\n}", "func (p *MockPeer) SetName(name string) {\r\n\tp.MockName = name\r\n}", "func (m *ParentLabelDetails) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Resource) SetName(name string) error {\n\tif len(m.name) > 0 {\n\t\treturn errors.New(\"name already set\")\n\t}\n\tn := Name(name)\n\tok, err := n.IsValid()\n\tif err == nil && ok {\n\t\tm.name = n\n\t\treturn nil\n\t} else {\n\t\treturn err\n\t}\n}", "func (k keeper) SetName(ctx sdk.Context, name string, value, string){\n\twhois := k.GetWhois(ctx, name)\n\twhois.Value = value\n\tk.SetWhois(ctx, name, whois)\n}", "func (nuo *NodeUpdateOne) SetName(s string) *NodeUpdateOne {\n\tnuo.mutation.SetName(s)\n\treturn nuo\n}", "func (m *ExternalConnection) SetName(value *string)() {\n m.name = value\n}", "func (m *WorkbookNamedItem) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (b *ClientAdaptor) SetName(n string) { b.name = n }", "func (_SweetToken *SweetTokenTransactor) SetName(opts *bind.TransactOpts, name_ string) (*types.Transaction, error) {\n\treturn _SweetToken.contract.Transact(opts, \"setName\", name_)\n}", "func (xdc *XxxDemoCreate) SetName(s string) *XxxDemoCreate {\n\txdc.mutation.SetName(s)\n\treturn xdc\n}", "func (ktuo *KqiTargetUpdateOne) SetName(s string) *KqiTargetUpdateOne {\n\tktuo.mutation.SetName(s)\n\treturn ktuo\n}", "func (n *ACName) Set(s string) error {\n\tnn, err := NewACName(s)\n\tif err == nil {\n\t\t*n = *nn\n\t}\n\treturn err\n}", "func (m *DeviceManagementConfigurationSettingDefinition) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (n *Node) SetName(name string) {\n\tn.name = name\n\tif n.cf != nil && n.cf.unquotedKey && (strings.IndexFunc(name, unicode.IsSpace) != -1 || strings.ContainsAny(name, \"\\\"{}\")) {\n\t\tn.cf.unquotedKey = false\n\t}\n}", "func (request *DomainRegisterRequest) SetName(value *string) {\n\trequest.SetStringProperty(\"Name\", value)\n}", "func (e *Engine) setName(name string) error {\n\tindex, err := naming.ExtractIndex(name, \"-\", 1)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"couldn't get index from device name: %v\", err)\n\t\treturn err\n\t}\n\te.Name = name\n\te.Index = index\n\treturn nil\n}", "func (bc *BeerCreate) SetName(s string) *BeerCreate {\n\tbc.mutation.SetName(s)\n\treturn bc\n}", "func (m *ChatMessageAttachment) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (_ResolverContract *ResolverContractTransactor) SetName(opts *bind.TransactOpts, node [32]byte, name string) (*types.Transaction, error) {\n\treturn _ResolverContract.contract.Transact(opts, \"setName\", node, name)\n}", "func (m *etcdMinion) SetName(name string) error {\n\tnameKey := filepath.Join(m.rootDir, \"name\")\n\topts := &etcdclient.SetOptions{\n\t\tPrevExist: etcdclient.PrevIgnore,\n\t}\n\n\t_, err := m.kapi.Set(context.Background(), nameKey, name, opts)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to set name of minion: %s\\n\", err)\n\t}\n\n\treturn err\n}", "func (kcuo *K8sContainerUpdateOne) SetName(s string) *K8sContainerUpdateOne {\n\tkcuo.mutation.SetName(s)\n\treturn kcuo\n}", "func (su *SettingUpdate) SetName(s string) *SettingUpdate {\n\tsu.mutation.SetName(s)\n\treturn su\n}", "func (m *DeviceManagementConfigurationPolicy) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (nu *NodeUpdate) SetName(s string) *NodeUpdate {\n\tnu.mutation.SetName(s)\n\treturn nu\n}", "func ExamplePerson_SetName() {\n\tperson := NewPerson(\"alice\")\n\tperson.SetName(\"bob\")\n}", "func (v VirtualSwitch) SetName(newName string) error {\n\t// Get fresh settings info\n\tswitchSettingsResult, err := v.virtualSwitch.Get(\"associators_\", nil, VMSwitchSettings)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"associators_\")\n\t}\n\n\tresult, err := switchSettingsResult.ItemAtIndex(0)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"ItemAtIndex\")\n\t}\n\n\tif err := result.Set(\"ElementName\", newName); err != nil {\n\t\treturn errors.Wrap(err, \"ElementName\")\n\t}\n\n\ttext, err := result.GetText(1)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"GetText\")\n\t}\n\tif err := v.modifySwitchSettings(text); err != nil {\n\t\treturn errors.Wrap(err, \"modifySwitchSettings\")\n\t}\n\n\tif err := v.setInternalPortName(newName); err != nil {\n\t\treturn errors.Wrap(err, \"setInternalPortName\")\n\t}\n\treturn nil\n}", "func (entry *Entry) SetName(name ndn.Name) error {\n\tnameV, _ := name.MarshalBinary()\n\tnameL := len(nameV)\n\tif nameL > MaxNameLength {\n\t\treturn fmt.Errorf(\"FIB entry name cannot exceed %d octets\", MaxNameLength)\n\t}\n\n\tc := (*CEntry)(entry)\n\tc.NameL = uint16(copy(c.NameV[:], nameV))\n\tc.NComps = uint8(len(name))\n\treturn nil\n}", "func (ktu *KqiTargetUpdate) SetName(s string) *KqiTargetUpdate {\n\tktu.mutation.SetName(s)\n\treturn ktu\n}", "func (s *Server) setName(c *client.Client, args []string) {\n\t// validate arg input\n\tc.Name = args[1]\n\tc.Msg(fmt.Sprintf(\"name changed to %s\", c.Name))\n}", "func (h *MPU6050Driver) SetName(n string) { h.name = n }", "func (c *Configurator) SetName(name string) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tc.name = name\n}", "func (m *AttachmentItem) SetName(value *string)() {\n m.name = value\n}", "func (dc *DentistCreate) SetName(s string) *DentistCreate {\n\tdc.mutation.SetName(s)\n\treturn dc\n}", "func (p *MockPeer) SetName(name string) {\n\tp.MockName = name\n}", "func (puo *PharmacistUpdateOne) SetName(s string) *PharmacistUpdateOne {\n\tpuo.mutation.SetName(s)\n\treturn puo\n}", "func (k Keeper) SetName(ctx sdk.Context, name string, value string) {\n\twhois := k.GetWhois(ctx, name)\n\twhois.Value = value\n\tk.SetWhois(ctx, name, whois)\n}", "func (luo *LibraryUpdateOne) SetName(s string) *LibraryUpdateOne {\n\tluo.mutation.SetName(s)\n\treturn luo\n}", "func (n *Node) SetName(name string) bool {\n\tif n.Nm == name {\n\t\treturn false\n\t}\n\tn.Nm = name\n\tn.UniqueNm = name\n\tif n.Par != nil {\n\t\tn.Par.UniquifyNames()\n\t}\n\treturn true\n}", "func (gsc *GameServerCreate) SetName(s string) *GameServerCreate {\n\tgsc.mutation.SetName(s)\n\treturn gsc\n}", "func (m *Mobile) SetName(username string) error {\n\tif !m.node.Online() {\n\t\treturn core.ErrOffline\n\t}\n\n\treturn m.node.SetName(username)\n}", "func (tc *TokenCreate) SetName(s string) *TokenCreate {\n\ttc.mutation.SetName(s)\n\treturn tc\n}", "func (e *Element) SetName(value string) {\n\tif e.Parent != nil {\n\t\te.Parent.children.Rename(e.name, value)\n\t}\n\te.name = value\n}", "func (puo *PatientrecordUpdateOne) SetName(s string) *PatientrecordUpdateOne {\n\tpuo.mutation.SetName(s)\n\treturn puo\n}", "func (p *Provider) SetName(name string) {\n\tp.name = name\n}", "func (iuo *ItemUpdateOne) SetName(s string) *ItemUpdateOne {\n\tiuo.mutation.SetName(s)\n\treturn iuo\n}", "func (mc *ManagerCreate) SetName(s string) *ManagerCreate {\n\tmc.mutation.SetName(s)\n\treturn mc\n}", "func (atuo *ActivityTypeUpdateOne) SetName(s string) *ActivityTypeUpdateOne {\n\tatuo.mutation.SetName(s)\n\treturn atuo\n}", "func (guo *GroupUpdateOne) SetName(s string) *GroupUpdateOne {\n\tguo.mutation.SetName(s)\n\treturn guo\n}", "func (puo *ProductUpdateOne) SetName(s string) *ProductUpdateOne {\n\tpuo.mutation.SetName(s)\n\treturn puo\n}", "func (rc *RuleCreate) SetName(s string) *RuleCreate {\n\trc.mutation.SetName(s)\n\treturn rc\n}", "func (e *AnotherType) SetName(n string) {\r\n\te.name = n\r\n}", "func (oc *OAuth2ClientCreate) SetName(s string) *OAuth2ClientCreate {\n\toc.mutation.SetName(s)\n\treturn oc\n}", "func (o *Partition) SetName(ctx context.Context, name string, options map[string]dbus.Variant) (err error) {\n\terr = o.object.CallWithContext(ctx, InterfacePartition+\".SetName\", 0, name, options).Store()\n\treturn\n}", "func (c *Channel) SetName(name string) {\n\tpacket := MumbleProto.ChannelState{\n\t\tChannelId: &c.id,\n\t\tName: &name,\n\t}\n\tc.client.Send(protoMessage{&packet})\n}", "func (xs *Sheet) SetName(name string) {\n\txs.xb.lib.NewProc(\"xlSheetSetNameW\").\n\t\tCall(xs.self, S(name))\n}", "func (d UserData) SetName(value string) m.UserData {\n\td.ModelData.Set(models.NewFieldName(\"Name\", \"name\"), value)\n\treturn d\n}", "func (ms MetricDescriptor) SetName(v string) {\n\t(*ms.orig).Name = v\n}", "func (ocuo *OAuthConnectionUpdateOne) SetName(s string) *OAuthConnectionUpdateOne {\n\tocuo.mutation.SetName(s)\n\treturn ocuo\n}", "func (n *FnInvNode) SetName(a string) {\n\tn.name = a\n}", "func (mc *MenuCreate) SetName(s string) *MenuCreate {\n\tmc.mutation.SetName(s)\n\treturn mc\n}", "func (gsuo *GameServerUpdateOne) SetName(s string) *GameServerUpdateOne {\n\tgsuo.mutation.SetName(s)\n\treturn gsuo\n}", "func (dc *DatasourceCreate) SetName(s string) *DatasourceCreate {\n\tdc.mutation.SetName(s)\n\treturn dc\n}", "func (ctc *ClubTypeCreate) SetName(s string) *ClubTypeCreate {\n\tctc.mutation.SetName(s)\n\treturn ctc\n}", "func (kcu *K8sContainerUpdate) SetName(s string) *K8sContainerUpdate {\n\tkcu.mutation.SetName(s)\n\treturn kcu\n}", "func (m *endpoint) SetName(val *string) {\n\tm.nameField = val\n}", "func (iu *ItemUpdate) SetName(s string) *ItemUpdate {\n\tiu.mutation.SetName(s)\n\treturn iu\n}", "func (d *APA102Driver) SetName(n string) { d.name = n }", "func (puo *PhoneUpdateOne) SetName(s string) *PhoneUpdateOne {\n\tpuo.mutation.SetName(s)\n\treturn puo\n}", "func (gsu *GameServerUpdate) SetName(s string) *GameServerUpdate {\n\tgsu.mutation.SetName(s)\n\treturn gsu\n}", "func (gc *GroupCreate) SetName(s string) *GroupCreate {\n\tgc.mutation.SetName(s)\n\treturn gc\n}", "func (tuo *TeamUpdateOne) SetName(s string) *TeamUpdateOne {\n\ttuo.mutation.SetName(s)\n\treturn tuo\n}", "func (n *FnDeclNode) SetName(a string) {\n\tn.name = a\n}", "func (duo *DeviceUpdateOne) SetName(s string) *DeviceUpdateOne {\n\tduo.mutation.SetName(s)\n\treturn duo\n}", "func (h *Handler) SetName(name string) {\n\th.name = name\n}" ]
[ "0.81129515", "0.78825146", "0.7534317", "0.7523171", "0.73899966", "0.73698646", "0.73400325", "0.73141974", "0.7256551", "0.72248316", "0.7196492", "0.7190641", "0.71832526", "0.71805173", "0.7158975", "0.71449256", "0.7139063", "0.711154", "0.7105229", "0.70985585", "0.7055368", "0.70480424", "0.70436895", "0.70324105", "0.700515", "0.6997586", "0.69906944", "0.6990649", "0.6986479", "0.69792473", "0.6971116", "0.69669896", "0.696218", "0.69584906", "0.694906", "0.69478023", "0.69464004", "0.69457424", "0.6933821", "0.69317794", "0.69271576", "0.6926319", "0.6924965", "0.69219613", "0.6917922", "0.6910805", "0.6905856", "0.68995893", "0.689012", "0.6888461", "0.6886549", "0.68759686", "0.6864721", "0.6857874", "0.685776", "0.6851842", "0.6845288", "0.6844805", "0.6842568", "0.6838781", "0.68364525", "0.6812523", "0.68086135", "0.6794353", "0.6793014", "0.67923677", "0.67773134", "0.67741084", "0.67725295", "0.67644423", "0.6764206", "0.6760264", "0.67525494", "0.67517585", "0.67274207", "0.6724554", "0.6713072", "0.67109793", "0.67100644", "0.6709988", "0.66956997", "0.66897565", "0.66669494", "0.6666404", "0.6665694", "0.6664444", "0.6657766", "0.6652148", "0.6645812", "0.6644857", "0.6642217", "0.6638142", "0.6629328", "0.66276664", "0.6626264", "0.6614873", "0.66119856", "0.6602672", "0.65956384", "0.6593556", "0.6587316" ]
0.0
-1
SetVersion sets the version field.
func (ac *AppCreate) SetVersion(s string) *AppCreate { ac.mutation.SetVersion(s) return ac }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func SetVersion(ver string) {\n\tversion = ver\n}", "func (info *Metadata) SetVersion(version int32) {\n\tinfo.version = version\n}", "func (s *Server) SetVersion(newVersion uint32) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.version = newVersion\n}", "func SetVersion(v string, os string, arch string, commit string, date string, goVersion string) {\n\tversion = data{\n\t\tversion: v,\n\t\tos: os,\n\t\tarch: arch,\n\t\tcommit: commit,\n\t\tdate: date,\n\t\tgoVersion: strings.ReplaceAll(goVersion, \"go\", \"\"),\n\t}\n}", "func (a *Action) SetVersion(version interface{}) { a.version = version }", "func (h *Headers) SetVersion(version string) { h.version = version }", "func (scl *SimpleConfigurationLayer) SetVersion(version *string) {\n\tscl.Version = version\n}", "func (obj *Edge) SetVersion(version int) {\n\tobj.setVersion(version)\n}", "func (cfg *Config) SetVersion(version int) {\n\tcfg.Version = version\n}", "func (o *LoraNetworkTrigger) SetVersion(v int32) {\n\to.Version = v\n}", "func (_PlasmaFramework *PlasmaFrameworkTransactor) SetVersion(opts *bind.TransactOpts, _version string) (*types.Transaction, error) {\n\treturn _PlasmaFramework.contract.Transact(opts, \"setVersion\", _version)\n}", "func (c *Current) SetVersion(version string) {\n\tswitch c.selectedRadio {\n\tcase FocusOnInvolved, FocusOnCurrentNamespace:\n\t\tif curr.resourceVersion < version {\n\t\t\tcurr.resourceVersion = version\n\t\t}\n\tcase FocusOnAllNamespace:\n\t\tif curr.resourceVersionAllNamespace < version {\n\t\t\tcurr.resourceVersionAllNamespace = version\n\t\t}\n\t}\n}", "func (m *msg) SetVersion(v byte) {\n\tm.LiVnMode = (m.LiVnMode & 0xc7) | v<<3\n}", "func (rr *OPT) SetVersion(v uint8) {\n\trr.Hdr.Ttl = rr.Hdr.Ttl&0xFF00FFFF | uint32(v)<<16\n}", "func (h *Header) SetVersion(version byte) {\n\th[1] = version\n}", "func SetVersion(version string, commit string) {\n\tif version == \"\" {\n\t\tmainSemver = \"0.0.0\"\n\t} else {\n\t\tmainSemver = version\n\t}\n\tif commit == \"\" {\n\t\tmainCommit = \"0000\"\n\t} else {\n\t\tmainCommit = commit\n\t}\n}", "func (d *Deej) SetVersion(version string) {\n\td.version = version\n}", "func (o *GetClientConfigV1ConfigByNameParams) SetVersion(version *string) {\n\to.Version = version\n}", "func (o *GetActionTemplateLogoVersionParams) SetVersion(version int32) {\n\to.Version = version\n}", "func (b *Builder) SetVersion(v uint32) *Builder {\n\tb.blk.Header.version = v\n\treturn b\n}", "func (m *GoMod) SetVersion(v string) error {\n\treturn nil\n}", "func (e *EPub) SetVersion(version float64) error {\n\tif version != 2 && version != 3 {\n\t\treturn fmt.Errorf(\"EPub version %v is unsupported\", version)\n\t}\n\te.version = version\n\treturn nil\n}", "func (m *SynchronizationSchema) SetVersion(value *string)() {\n err := m.GetBackingStore().Set(\"version\", value)\n if err != nil {\n panic(err)\n }\n}", "func (requestHeader *RequestHeader) SetVersion(version uint16) {\n\t// if requestHeader.APIVersion == -1 {\n\t// \treturn\n\t// }\n\trequestHeader.APIVersion = version\n}", "func (o *TransactionResult) SetVersion(v int32) {\n\to.Version.Set(&v)\n}", "func (swagger *MgwSwagger) SetVersion(version string) {\n\tswagger.version = version\n}", "func (i *Config) SetVersion(version string) {\n\ti.version = version\n}", "func (st *State) SetVersion(tag string, v version.Binary) error {\n\tvar results params.ErrorResults\n\targs := params.EntitiesVersion{\n\t\tAgentTools: []params.EntityVersion{{\n\t\t\tTag: tag,\n\t\t\tTools: &params.Version{v},\n\t\t}},\n\t}\n\terr := st.call(\"SetTools\", args, &results)\n\tif err != nil {\n\t\t// TODO: Not directly tested\n\t\treturn err\n\t}\n\treturn results.OneError()\n}", "func (f *FacebookRequestResponse) SetVersion(v string) *FacebookRequestResponse {\n\tif f.Fields == nil {\n\t\tf.Fields = &FacebookFields{}\n\t}\n\tf.Fields.Version = v\n\treturn f\n}", "func (o *PostHAProxyConfigurationParams) SetVersion(version *int64) {\n\to.Version = version\n}", "func (o *EntityWatchlistScreeningSearchTerms) SetVersion(v int32) {\n\to.Version = v\n}", "func (o *NiaapiNewReleaseDetailAllOf) SetVersion(v string) {\n\to.Version = &v\n}", "func (o *WorkflowWorkflowDefinitionAllOf) SetVersion(v int64) {\n\to.Version = &v\n}", "func (p *EtcdClientV3) SetVersion(version *PersistentStateVersion) error {\n\tversionJSON, err := json.Marshal(version)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn p.Set(config.StoreURL, string(versionJSON))\n}", "func (o *GetProductUpgradeURLUsingGETParams) SetVersion(version string) {\n\to.Version = version\n}", "func (o *HyperflexServerFirmwareVersionEntryAllOf) SetVersion(v string) {\n\to.Version = &v\n}", "func (in *ActionIpAddressIndexInput) SetVersion(value int64) *ActionIpAddressIndexInput {\n\tin.Version = value\n\n\tif in._selectedParameters == nil {\n\t\tin._selectedParameters = make(map[string]interface{})\n\t}\n\n\tin._selectedParameters[\"Version\"] = nil\n\treturn in\n}", "func (m *ManagedAppPolicy) SetVersion(value *string)() {\n m.version = value\n}", "func (o *WorkflowServiceItemDefinitionAllOf) SetVersion(v int64) {\n\to.Version = &v\n}", "func (mi *MeshInfo) SetVersion(v *string) {\n\tmi.version = v\n}", "func (o *DeviceStatusTrigger) SetVersion(v int32) {\n\to.Version = v\n}", "func (o *UpdateMetricRulesetRequest) SetVersion(v int64) {\n\to.Version = &v\n}", "func (o *VirtualizationIweHost) SetVersion(v string) {\n\to.Version = &v\n}", "func (_options *GetConfigOptions) SetVersion(version string) *GetConfigOptions {\n\t_options.Version = core.StringPtr(version)\n\treturn _options\n}", "func (m *LocalNodeInfoResponse_Body) SetVersion(v *refs.Version) {\n\tif m != nil {\n\t\tm.Version = v\n\t}\n}", "func (o *GetInstancesDocsParams) SetVersion(version *string) {\n\to.Version = version\n}", "func (av *AppVersion) SetVersion(rw http.ResponseWriter, r *http.Request) {\n\tvar passwd, version, downloadURL string\n\n\tif len(r.URL.Query()[\"passwd\"]) > 0 {\n\t\tpasswd = r.URL.Query()[\"passwd\"][0]\n\t} else {\n\t\tav.l.Printf(\"failed to get passwd\")\n\t\treturn\n\t}\n\tif len(r.URL.Query()[\"version\"]) > 0 {\n\t\tversion = r.URL.Query()[\"version\"][0]\n\t} else {\n\t\tav.l.Printf(\"failed to get version\")\n\t\treturn\n\t}\n\tif len(r.URL.Query()[\"downloadurl\"]) > 0 {\n\t\tdownloadURL = r.URL.Query()[\"downloadurl\"][0]\n\t} else {\n\t\tav.l.Printf(\"failed to get downloadurl\")\n\t\treturn\n\t}\n\t//fmt.Println(passwd, version, downloadURL)\n\n\tappVersion, _ := av.db.QueryAppVersion()\n\tif appVersion.ID == 0 {\n\t\tappVersion.Passwd = passwd\n\t\tappVersion.Version = version\n\t\tappVersion.DownloadURL = downloadURL\n\t\terr := av.db.InsertAppVerion(&appVersion)\n\t\tif err != nil {\n\t\t\tav.l.Printf(\"failed to insert AppVersion : %s\", err)\n\t\t\treturn\n\t\t}\n\t\tutils.Respond(rw, true)\n\t\treturn\n\t} else if appVersion.Passwd != passwd {\n\t\tav.l.Printf(\"failed to set AppVersion : passwd wrong\")\n\t\treturn\n\t}\n\tappVersion.Version = version\n\tappVersion.DownloadURL = downloadURL\n\terr := av.db.UpdateAppVerion(&appVersion)\n\tif err != nil {\n\t\tav.l.Printf(\"failed to insert AppVersion : %s\", err)\n\t\treturn\n\t}\n\n\tutils.Respond(rw, true)\n\treturn\n}", "func (f *FacebookMessage) SetVersion(v string) *FacebookMessage {\n\tif f.Fields == nil {\n\t\tf.Fields = &FacebookFields{}\n\t}\n\tf.Fields.Version = v\n\treturn f\n}", "func (opt *optionalAttributes) SetVersion(version int) *Builder {\n\topt.Builder.optional.VersionIndex = version\n\treturn opt.Builder\n}", "func (o *SchemaDefinitionRestDto) SetVersion(v string) {\n\to.Version = &v\n}", "func (o *VersionedFlowCoordinates) SetVersion(v int32) {\n\to.Version = &v\n}", "func (m *Migrate) SetVersion(version uint64, description string) error {\n\trec := versionRecord{\n\t\tVersion: version,\n\t\tTimestamp: time.Now().UTC(),\n\t\tDescription: description,\n\t}\n\n\t_, err := m.db.Collection(m.migrationsCollection).InsertOne(context.TODO(), rec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o *ConnectorTypeAllOf) SetVersion(v string) {\n\to.Version = &v\n}", "func (o *ConnectorTypeAllOf) SetVersion(v string) {\n\to.Version = &v\n}", "func (r *GraphRequest) SetVersion(v GraphAPIVersion) *GraphRequest {\n\tr.Version = v\n\treturn r\n}", "func (duo *DatumUpdateOne) SetVersion(i int) *DatumUpdateOne {\n\tduo.mutation.ResetVersion()\n\tduo.mutation.SetVersion(i)\n\treturn duo\n}", "func (options *CreateSharedDatasetOptions) SetVersion(version string) *CreateSharedDatasetOptions {\n\toptions.Version = core.StringPtr(version)\n\treturn options\n}", "func (_options *GetCostEstimateOptions) SetVersion(version string) *GetCostEstimateOptions {\n\t_options.Version = core.StringPtr(version)\n\treturn _options\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 *EquipmentIoCardBase) SetVersion(v string) {\n\to.Version = &v\n}", "func (du *DatumUpdate) SetVersion(i int) *DatumUpdate {\n\tdu.mutation.ResetVersion()\n\tdu.mutation.SetVersion(i)\n\treturn du\n}", "func (luo *LibraryUpdateOne) SetVersion(s string) *LibraryUpdateOne {\n\tluo.mutation.SetVersion(s)\n\treturn luo\n}", "func (s *Server) SetVersion(ctx context.Context, in *pb.SetVersionRequest) (*pb.SetVersionResponse, error) {\n\ts.writeMutex.Lock()\n\tdefer s.writeMutex.Unlock()\n\n\tfound := false\n\tfor _, v := range s.versions {\n\t\tif v.GetKey() == in.GetSet().GetKey() {\n\t\t\tv.Value = in.GetSet().GetValue()\n\t\t\tv.Setter = in.GetSet().GetSetter()\n\t\t\tfound = true\n\t\t}\n\t}\n\n\tif !found {\n\t\ts.versions = append(s.versions, in.GetSet())\n\t}\n\n\terr := s.saveVersions()\n\tif err != nil {\n\t\ts.Log(fmt.Sprintf(\"Error writing: %v -> %v\", in, err))\n\t\treturn nil, err\n\t}\n\treturn &pb.SetVersionResponse{Response: in.GetSet()}, nil\n}", "func (o *InterfaceCapability) SetVersion(v int32) {\n\to.Version = &v\n}", "func (_PlasmaFramework *PlasmaFrameworkSession) SetVersion(_version string) (*types.Transaction, error) {\n\treturn _PlasmaFramework.Contract.SetVersion(&_PlasmaFramework.TransactOpts, _version)\n}", "func (o *KubernetesAddonDefinitionAllOf) SetVersion(v string) {\n\to.Version = &v\n}", "func (o *ExportProductsUsingGETParams) SetVersion(version *string) {\n\to.Version = version\n}", "func (o *SoftwarerepositoryCategoryMapper) SetVersion(v string) {\n\to.Version = &v\n}", "func (m *DeviceManagementConfigurationSettingDefinition) SetVersion(value *string)() {\n err := m.GetBackingStore().Set(\"version\", value)\n if err != nil {\n panic(err)\n }\n}", "func (options *ReplaceSharedDatasetOptions) SetVersion(version string) *ReplaceSharedDatasetOptions {\n\toptions.Version = core.StringPtr(version)\n\treturn options\n}", "func (o *SoftwareTechs) SetVersion(v string) {\n\to.Version = &v\n}", "func (o *TeamConfiguration) SetVersion(v string) {\n\to.Version = v\n}", "func (r *Readme) SetVersion(v string) *Readme {\n\tr.version = v\n\treturn r\n}", "func (s *Task) SetVersion(v int64) *Task {\n\ts.Version = &v\n\treturn s\n}", "func (duo *DeviceUpdateOne) SetVersion(s string) *DeviceUpdateOne {\n\tduo.mutation.SetVersion(s)\n\treturn duo\n}", "func (o *SwarmUpdateParams) SetVersion(version int64) {\n\to.Version = version\n}", "func (o *NetworkElementSummaryAllOf) SetVersion(v string) {\n\to.Version = &v\n}", "func (o *EnvironmentAutoUpdateConfig) SetVersion(v string) {\n\to.Version = &v\n}", "func (o *Version) SetVersion(v string) {\n\to.Version = &v\n}", "func (_options *CheckConfigOptions) SetVersion(version string) *CheckConfigOptions {\n\t_options.Version = core.StringPtr(version)\n\treturn _options\n}", "func (o *MicrosoftGraphSharedPcConfiguration) SetVersion(v int32) {\n\to.Version = &v\n}", "func SetVersion(version string) func(*AviSession) error {\n\treturn func(sess *AviSession) error {\n\t\treturn sess.setVersion(version)\n\t}\n}", "func SetVersion(version string) {\n\trootCmd.Cmd.Version = version\n}", "func (o *MicrosoftGraphWindows10CompliancePolicy) SetVersion(v int32) {\n\to.Version = &v\n}", "func (b *ChaincodeDataBuilder) Version(value string) *ChaincodeDataBuilder {\n\tb.version = value\n\treturn b\n}", "func (s *Record) SetVersion(v int64) *Record {\n\ts.Version = &v\n\treturn s\n}", "func (o *RemoveUserGroupParams) SetVersion(version string) {\n\to.Version = version\n}", "func (_PlasmaFramework *PlasmaFrameworkTransactorSession) SetVersion(_version string) (*types.Transaction, error) {\n\treturn _PlasmaFramework.Contract.SetVersion(&_PlasmaFramework.TransactOpts, _version)\n}", "func (s *ListAliasesInput) SetVersion(v int64) *ListAliasesInput {\n\ts.Version = &v\n\treturn s\n}", "func (s *Connector) SetVersion(v string) *Connector {\n\ts.Version = &v\n\treturn s\n}", "func (o *ApplianceImageBundleAllOf) SetVersion(v string) {\n\to.Version = &v\n}", "func (s *State) SetVersion(version int) {\n\ts.sessionVersion = version\n}", "func (o *WebhooksJsonWebhook) SetVersion(v string) {\n\to.Version = &v\n}", "func (o *HyperflexHealthCheckPackageChecksum) SetVersion(v string) {\n\to.Version = &v\n}", "func (o *DeleteChartrepoRepoChartsNameVersionLabelsIDParams) SetVersion(version string) {\n\to.Version = version\n}", "func (o *ZoneZone) SetVersion(v string) {\n\to.Version = &v\n}", "func (du *DeviceUpdate) SetVersion(s string) *DeviceUpdate {\n\tdu.mutation.SetVersion(s)\n\treturn du\n}", "func (bc *BouncerCreate) SetVersion(s string) *BouncerCreate {\n\tbc.mutation.SetVersion(s)\n\treturn bc\n}", "func (o *DeletePackageVersionParams) SetVersion(version string) {\n\to.Version = version\n}", "func (s *View) SetVersion(v int64) *View {\n\ts.Version = &v\n\treturn s\n}" ]
[ "0.8282522", "0.7993682", "0.7818151", "0.7816626", "0.7574834", "0.75651526", "0.7559927", "0.7523605", "0.75083274", "0.74630666", "0.74577516", "0.745642", "0.7442571", "0.7441765", "0.743878", "0.7420126", "0.73809814", "0.7380753", "0.7371691", "0.73631924", "0.7354351", "0.73413837", "0.7306218", "0.7284797", "0.7262988", "0.7261245", "0.72418195", "0.721838", "0.7209897", "0.7207842", "0.71965504", "0.7185246", "0.71822155", "0.71768266", "0.7158826", "0.71402943", "0.71365047", "0.7134511", "0.71265197", "0.71216273", "0.7100098", "0.7085359", "0.7072744", "0.70486104", "0.7045285", "0.7043967", "0.7036756", "0.70358986", "0.70177686", "0.7015978", "0.7001404", "0.69886655", "0.69764394", "0.69764394", "0.6973168", "0.696342", "0.69510686", "0.693511", "0.6928641", "0.6920318", "0.6918378", "0.6916623", "0.6911593", "0.69092435", "0.6888919", "0.68838143", "0.68594563", "0.6843537", "0.6835665", "0.6832223", "0.6825956", "0.6823691", "0.68233633", "0.6822671", "0.6816693", "0.68129534", "0.6811481", "0.68085855", "0.68060267", "0.6802746", "0.67848706", "0.67643386", "0.6761984", "0.6761891", "0.67583257", "0.6755779", "0.67501837", "0.67457163", "0.67322254", "0.6712422", "0.671213", "0.6710211", "0.6706131", "0.6691933", "0.6671997", "0.6654434", "0.66189", "0.66135484", "0.6602895", "0.65996444" ]
0.70406353
46
SetNillableVersion sets the version field if the given value is not nil.
func (ac *AppCreate) SetNillableVersion(s *string) *AppCreate { if s != nil { ac.SetVersion(*s) } return ac }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (lu *LibraryUpdate) SetNillableVersion(s *string) *LibraryUpdate {\n\tif s != nil {\n\t\tlu.SetVersion(*s)\n\t}\n\treturn lu\n}", "func (luo *LibraryUpdateOne) SetNillableVersion(s *string) *LibraryUpdateOne {\n\tif s != nil {\n\t\tluo.SetVersion(*s)\n\t}\n\treturn luo\n}", "func (au *AppUpdate) SetNillableVersion(s *string) *AppUpdate {\n\tif s != nil {\n\t\tau.SetVersion(*s)\n\t}\n\treturn au\n}", "func (auo *AppUpdateOne) SetNillableVersion(s *string) *AppUpdateOne {\n\tif s != nil {\n\t\tauo.SetVersion(*s)\n\t}\n\treturn auo\n}", "func (du *DeviceUpdate) SetNillableVersion(s *string) *DeviceUpdate {\n\tif s != nil {\n\t\tdu.SetVersion(*s)\n\t}\n\treturn du\n}", "func (duo *DatumUpdateOne) SetNillableVersion(i *int) *DatumUpdateOne {\n\tif i != nil {\n\t\tduo.SetVersion(*i)\n\t}\n\treturn duo\n}", "func (duo *DeviceUpdateOne) SetNillableVersion(s *string) *DeviceUpdateOne {\n\tif s != nil {\n\t\tduo.SetVersion(*s)\n\t}\n\treturn duo\n}", "func (du *DatumUpdate) SetNillableVersion(i *int) *DatumUpdate {\n\tif i != nil {\n\t\tdu.SetVersion(*i)\n\t}\n\treturn du\n}", "func (bc *BouncerCreate) SetNillableVersion(s *string) *BouncerCreate {\n\tif s != nil {\n\t\tbc.SetVersion(*s)\n\t}\n\treturn bc\n}", "func (o *TransactionResult) SetVersionNil() {\n\to.Version.Set(nil)\n}", "func (o *Content) SetPyVersionNil() {\n\to.PyVersion.Set(nil)\n}", "func (luo *LocationUpdateOne) SetNillableSiteSurveyNeeded(b *bool) *LocationUpdateOne {\n\tif b != nil {\n\t\tluo.SetSiteSurveyNeeded(*b)\n\t}\n\treturn luo\n}", "func (nuo *NodeUpdateOne) SetNillableValue(i *int) *NodeUpdateOne {\n\tif i != nil {\n\t\tnuo.SetValue(*i)\n\t}\n\treturn nuo\n}", "func (o *Content) SetRVersionNil() {\n\to.RVersion.Set(nil)\n}", "func (lu *LocationUpdate) SetNillableSiteSurveyNeeded(b *bool) *LocationUpdate {\n\tif b != nil {\n\t\tlu.SetSiteSurveyNeeded(*b)\n\t}\n\treturn lu\n}", "func (nu *NodeUpdate) SetNillableValue(i *int) *NodeUpdate {\n\tif i != nil {\n\t\tnu.SetValue(*i)\n\t}\n\treturn nu\n}", "func (tu *TransactionfactorUpdate) SetNillableDate(s *string) *TransactionfactorUpdate {\n\tif s != nil {\n\t\ttu.SetDate(*s)\n\t}\n\treturn tu\n}", "func (gauo *GithubAssetUpdateOne) SetNillableState(s *string) *GithubAssetUpdateOne {\n\tif s != nil {\n\t\tgauo.SetState(*s)\n\t}\n\treturn gauo\n}", "func (tuo *TransactionfactorUpdateOne) SetNillableDate(s *string) *TransactionfactorUpdateOne {\n\tif s != nil {\n\t\ttuo.SetDate(*s)\n\t}\n\treturn tuo\n}", "func (vuu *VacUserUpdate) SetNillablePassword(s *string) *VacUserUpdate {\n\tif s != nil {\n\t\tvuu.SetPassword(*s)\n\t}\n\treturn vuu\n}", "func (scsu *SurveyCellScanUpdate) SetNillableTimestamp(t *time.Time) *SurveyCellScanUpdate {\n\tif t != nil {\n\t\tscsu.SetTimestamp(*t)\n\t}\n\treturn scsu\n}", "func (wouo *WorkOrderUpdateOne) SetNillableInstallDate(t *time.Time) *WorkOrderUpdateOne {\n\tif t != nil {\n\t\twouo.SetInstallDate(*t)\n\t}\n\treturn wouo\n}", "func (scsuo *SurveyCellScanUpdateOne) SetNillableTimestamp(t *time.Time) *SurveyCellScanUpdateOne {\n\tif t != nil {\n\t\tscsuo.SetTimestamp(*t)\n\t}\n\treturn scsuo\n}", "func (gau *GithubAssetUpdate) SetNillableState(s *string) *GithubAssetUpdate {\n\tif s != nil {\n\t\tgau.SetState(*s)\n\t}\n\treturn gau\n}", "func (vuuo *VacUserUpdateOne) SetNillablePassword(s *string) *VacUserUpdateOne {\n\tif s != nil {\n\t\tvuuo.SetPassword(*s)\n\t}\n\treturn vuuo\n}", "func (wou *WorkOrderUpdate) SetNillableInstallDate(t *time.Time) *WorkOrderUpdate {\n\tif t != nil {\n\t\twou.SetInstallDate(*t)\n\t}\n\treturn wou\n}", "func (vuu *VacUserUpdate) SetNillableToken(s *string) *VacUserUpdate {\n\tif s != nil {\n\t\tvuu.SetToken(*s)\n\t}\n\treturn vuu\n}", "func (cc *ConstructionCreate) SetNillableLastUpdated(t *time.Time) *ConstructionCreate {\n\tif t != nil {\n\t\tcc.SetLastUpdated(*t)\n\t}\n\treturn cc\n}", "func (gau *GithubAssetUpdate) SetNillableLabel(s *string) *GithubAssetUpdate {\n\tif s != nil {\n\t\tgau.SetLabel(*s)\n\t}\n\treturn gau\n}", "func (uuo *UserUpdateOne) SetNillableLevel(i *int) *UserUpdateOne {\n\tif i != nil {\n\t\tuuo.SetLevel(*i)\n\t}\n\treturn uuo\n}", "func (uu *UserUpdate) SetNillableLevel(i *int) *UserUpdate {\n\tif i != nil {\n\t\tuu.SetLevel(*i)\n\t}\n\treturn uu\n}", "func (vuuo *VacUserUpdateOne) SetNillableToken(s *string) *VacUserUpdateOne {\n\tif s != nil {\n\t\tvuuo.SetToken(*s)\n\t}\n\treturn vuuo\n}", "func (upvc *UnsavedPostVideoCreate) SetNillableValidity(u *unsavedpostvideo.Validity) *UnsavedPostVideoCreate {\n\tif u != nil {\n\t\tupvc.SetValidity(*u)\n\t}\n\treturn upvc\n}", "func (vc *VehicleCreate) SetNillableVin(s *string) *VehicleCreate {\n\tif s != nil {\n\t\tvc.SetVin(*s)\n\t}\n\treturn vc\n}", "func (vc *VehicleCreate) SetNillableUpdatedWith(s *string) *VehicleCreate {\n\tif s != nil {\n\t\tvc.SetUpdatedWith(*s)\n\t}\n\treturn vc\n}", "func (gsc *GameServerCreate) SetNillableUpdatedWith(s *string) *GameServerCreate {\n\tif s != nil {\n\t\tgsc.SetUpdatedWith(*s)\n\t}\n\treturn gsc\n}", "func (cc *ConstructionCreate) SetNillableModifier(f *float64) *ConstructionCreate {\n\tif f != nil {\n\t\tcc.SetModifier(*f)\n\t}\n\treturn cc\n}", "func (gsuo *GameServerUpdateOne) SetNillableUpdatedWith(s *string) *GameServerUpdateOne {\n\tif s != nil {\n\t\tgsuo.SetUpdatedWith(*s)\n\t}\n\treturn gsuo\n}", "func (auo *AppUpdateOne) SetNillableBuild(s *string) *AppUpdateOne {\n\tif s != nil {\n\t\tauo.SetBuild(*s)\n\t}\n\treturn auo\n}", "func (suo *StateUpdateOne) SetNillableUpdatedWith(s *string) *StateUpdateOne {\n\tif s != nil {\n\t\tsuo.SetUpdatedWith(*s)\n\t}\n\treturn suo\n}", "func (puo *PostUpdateOne) SetNillableViewCount(i *int) *PostUpdateOne {\n\tif i != nil {\n\t\tpuo.SetViewCount(*i)\n\t}\n\treturn puo\n}", "func (oiu *OrderInfoUpdate) SetNillableStatus(i *int8) *OrderInfoUpdate {\n\tif i != nil {\n\t\toiu.SetStatus(*i)\n\t}\n\treturn oiu\n}", "func (gauo *GithubAssetUpdateOne) SetNillableUpdatedAt(t *time.Time) *GithubAssetUpdateOne {\n\tif t != nil {\n\t\tgauo.SetUpdatedAt(*t)\n\t}\n\treturn gauo\n}", "func (gauo *GithubAssetUpdateOne) SetNillableLabel(s *string) *GithubAssetUpdateOne {\n\tif s != nil {\n\t\tgauo.SetLabel(*s)\n\t}\n\treturn gauo\n}", "func (oiuo *OrderInfoUpdateOne) SetNillableStatus(i *int8) *OrderInfoUpdateOne {\n\tif i != nil {\n\t\toiuo.SetStatus(*i)\n\t}\n\treturn oiuo\n}", "func (pu *PostUpdate) SetNillableViewCount(i *int) *PostUpdate {\n\tif i != nil {\n\t\tpu.SetViewCount(*i)\n\t}\n\treturn pu\n}", "func (squo *SurveyQuestionUpdateOne) SetNillableDateData(t *time.Time) *SurveyQuestionUpdateOne {\n\tif t != nil {\n\t\tsquo.SetDateData(*t)\n\t}\n\treturn squo\n}", "func (au *AppUpdate) SetNillableBuild(s *string) *AppUpdate {\n\tif s != nil {\n\t\tau.SetBuild(*s)\n\t}\n\treturn au\n}", "func (vc *VehicleCreate) SetNillableUpdatedAt(t *time.Time) *VehicleCreate {\n\tif t != nil {\n\t\tvc.SetUpdatedAt(*t)\n\t}\n\treturn vc\n}", "func (pu *PostUpdate) SetNillableStatus(i *int8) *PostUpdate {\n\tif i != nil {\n\t\tpu.SetStatus(*i)\n\t}\n\treturn pu\n}", "func (pu *PostUpdate) SetNillablePin(i *int8) *PostUpdate {\n\tif i != nil {\n\t\tpu.SetPin(*i)\n\t}\n\treturn pu\n}", "func (tuo *TransactionfactorUpdateOne) SetNillableUpdateDate(t *time.Time) *TransactionfactorUpdateOne {\n\tif t != nil {\n\t\ttuo.SetUpdateDate(*t)\n\t}\n\treturn tuo\n}", "func (puo *PostUpdateOne) SetNillableStatus(i *int8) *PostUpdateOne {\n\tif i != nil {\n\t\tpuo.SetStatus(*i)\n\t}\n\treturn puo\n}", "func (wouo *WorkOrderUpdateOne) SetNillableStatus(s *string) *WorkOrderUpdateOne {\n\tif s != nil {\n\t\twouo.SetStatus(*s)\n\t}\n\treturn wouo\n}", "func (biu *BlockInstanceUpdate) SetNillableStatus(b *blockinstance.Status) *BlockInstanceUpdate {\n\tif b != nil {\n\t\tbiu.SetStatus(*b)\n\t}\n\treturn biu\n}", "func (uu *UserUpdate) SetNillableStatus(u *user.Status) *UserUpdate {\n\tif u != nil {\n\t\tuu.SetStatus(*u)\n\t}\n\treturn uu\n}", "func (uu *UserUpdate) SetNillableStatus(u *user.Status) *UserUpdate {\n\tif u != nil {\n\t\tuu.SetStatus(*u)\n\t}\n\treturn uu\n}", "func (sc *SessionCreate) SetNillableUpdated(t *time.Time) *SessionCreate {\n\tif t != nil {\n\t\tsc.SetUpdated(*t)\n\t}\n\treturn sc\n}", "func (gau *GithubAssetUpdate) SetNillableUpdatedAt(t *time.Time) *GithubAssetUpdate {\n\tif t != nil {\n\t\tgau.SetUpdatedAt(*t)\n\t}\n\treturn gau\n}", "func (ftuo *FieldTypeUpdateOne) SetNillableState(f *fieldtype.State) *FieldTypeUpdateOne {\n\tif f != nil {\n\t\tftuo.SetState(*f)\n\t}\n\treturn ftuo\n}", "func (uuo *UserUpdateOne) SetNillableStatus(u *user.Status) *UserUpdateOne {\n\tif u != nil {\n\t\tuuo.SetStatus(*u)\n\t}\n\treturn uuo\n}", "func (uuo *UserUpdateOne) SetNillableStatus(u *user.Status) *UserUpdateOne {\n\tif u != nil {\n\t\tuuo.SetStatus(*u)\n\t}\n\treturn uuo\n}", "func (duo *DealUpdateOne) SetNillablePrice(i *int) *DealUpdateOne {\n\tif i != nil {\n\t\tduo.SetPrice(*i)\n\t}\n\treturn duo\n}", "func (uuo *UserUpdateOne) SetNillableViews(i *int) *UserUpdateOne {\n\tif i != nil {\n\t\tuuo.SetViews(*i)\n\t}\n\treturn uuo\n}", "func (su *StateUpdate) SetNillableUpdatedWith(s *string) *StateUpdate {\n\tif s != nil {\n\t\tsu.SetUpdatedWith(*s)\n\t}\n\treturn su\n}", "func (ocuo *OAuthConnectionUpdateOne) SetNillableUpdatedWith(s *string) *OAuthConnectionUpdateOne {\n\tif s != nil {\n\t\tocuo.SetUpdatedWith(*s)\n\t}\n\treturn ocuo\n}", "func (gsu *GameServerUpdate) SetNillableUpdatedWith(s *string) *GameServerUpdate {\n\tif s != nil {\n\t\tgsu.SetUpdatedWith(*s)\n\t}\n\treturn gsu\n}", "func (tu *TransactionfactorUpdate) SetNillableUpdateDate(t *time.Time) *TransactionfactorUpdate {\n\tif t != nil {\n\t\ttu.SetUpdateDate(*t)\n\t}\n\treturn tu\n}", "func (vuu *VacUserUpdate) SetNillableWatcherEnabled(b *bool) *VacUserUpdate {\n\tif b != nil {\n\t\tvuu.SetWatcherEnabled(*b)\n\t}\n\treturn vuu\n}", "func (ocu *OAuthConnectionUpdate) SetNillableUpdatedWith(s *string) *OAuthConnectionUpdate {\n\tif s != nil {\n\t\tocu.SetUpdatedWith(*s)\n\t}\n\treturn ocu\n}", "func (vuuo *VacUserUpdateOne) SetNillableWatcherEnabled(b *bool) *VacUserUpdateOne {\n\tif b != nil {\n\t\tvuuo.SetWatcherEnabled(*b)\n\t}\n\treturn vuuo\n}", "func (squ *SurveyQuestionUpdate) SetNillableDateData(t *time.Time) *SurveyQuestionUpdate {\n\tif t != nil {\n\t\tsqu.SetDateData(*t)\n\t}\n\treturn squ\n}", "func (wou *WorkOrderUpdate) SetNillableStatus(s *string) *WorkOrderUpdate {\n\tif s != nil {\n\t\twou.SetStatus(*s)\n\t}\n\treturn wou\n}", "func (luo *LocationUpdateOne) SetNillableExternalID(s *string) *LocationUpdateOne {\n\tif s != nil {\n\t\tluo.SetExternalID(*s)\n\t}\n\treturn luo\n}", "func (vuu *VacUserUpdate) SetNillablePartition(s *string) *VacUserUpdate {\n\tif s != nil {\n\t\tvuu.SetPartition(*s)\n\t}\n\treturn vuu\n}", "func (rc *RentalCreate) SetNillableDate(t *time.Time) *RentalCreate {\n\tif t != nil {\n\t\trc.SetDate(*t)\n\t}\n\treturn rc\n}", "func (pu *ProfileUpdate) SetNillableStatus(b *bool) *ProfileUpdate {\n\tif b != nil {\n\t\tpu.SetStatus(*b)\n\t}\n\treturn pu\n}", "func (du *DealUpdate) SetNillablePrice(i *int) *DealUpdate {\n\tif i != nil {\n\t\tdu.SetPrice(*i)\n\t}\n\treturn du\n}", "func (uu *UserUpdate) SetNillablePhoneNumber(s *string) *UserUpdate {\n\tif s != nil {\n\t\tuu.SetPhoneNumber(*s)\n\t}\n\treturn uu\n}", "func (uu *UserUpdate) SetNillableViews(i *int) *UserUpdate {\n\tif i != nil {\n\t\tuu.SetViews(*i)\n\t}\n\treturn uu\n}", "func (pu *ProfileUpdate) SetNillableBirthDate(s *string) *ProfileUpdate {\n\tif s != nil {\n\t\tpu.SetBirthDate(*s)\n\t}\n\treturn pu\n}", "func (rc *ResourceCreate) SetNillableUpdatedAt(t *time.Time) *ResourceCreate {\n\tif t != nil {\n\t\trc.SetUpdatedAt(*t)\n\t}\n\treturn rc\n}", "func (suo *SkillUpdateOne) SetNillableUpdatedAt(t *time.Time) *SkillUpdateOne {\n\tif t != nil {\n\t\tsuo.SetUpdatedAt(*t)\n\t}\n\treturn suo\n}", "func (buo *BookingUpdateOne) SetNillableBOOKINGDATE(t *time.Time) *BookingUpdateOne {\n\tif t != nil {\n\t\tbuo.SetBOOKINGDATE(*t)\n\t}\n\treturn buo\n}", "func (puo *ProfileUpdateOne) SetNillableStatus(b *bool) *ProfileUpdateOne {\n\tif b != nil {\n\t\tpuo.SetStatus(*b)\n\t}\n\treturn puo\n}", "func (fuo *FriendshipUpdateOne) SetNillableWeight(i *int) *FriendshipUpdateOne {\n\tif i != nil {\n\t\tfuo.SetWeight(*i)\n\t}\n\treturn fuo\n}", "func (biuo *BlockInstanceUpdateOne) SetNillableStatus(b *blockinstance.Status) *BlockInstanceUpdateOne {\n\tif b != nil {\n\t\tbiuo.SetStatus(*b)\n\t}\n\treturn biuo\n}", "func (gsc *GameServerCreate) SetNillableUpdatedAt(t *time.Time) *GameServerCreate {\n\tif t != nil {\n\t\tgsc.SetUpdatedAt(*t)\n\t}\n\treturn gsc\n}", "func (puo *PostUpdateOne) SetNillablePin(i *int8) *PostUpdateOne {\n\tif i != nil {\n\t\tpuo.SetPin(*i)\n\t}\n\treturn puo\n}", "func (cc *CompanyCreate) SetNillableUpdatedAt(t *time.Time) *CompanyCreate {\n\tif t != nil {\n\t\tcc.SetUpdatedAt(*t)\n\t}\n\treturn cc\n}", "func (bu *BookingUpdate) SetNillableBOOKINGDATE(t *time.Time) *BookingUpdate {\n\tif t != nil {\n\t\tbu.SetBOOKINGDATE(*t)\n\t}\n\treturn bu\n}", "func (vc *VehicleCreate) SetNillableStyle(s *string) *VehicleCreate {\n\tif s != nil {\n\t\tvc.SetStyle(*s)\n\t}\n\treturn vc\n}", "func (ftuo *FieldTypeUpdateOne) SetNillableNillableInt64(i *int64) *FieldTypeUpdateOne {\n\tif i != nil {\n\t\tftuo.SetNillableInt64(*i)\n\t}\n\treturn ftuo\n}", "func (lu *LocationUpdate) SetNillableExternalID(s *string) *LocationUpdate {\n\tif s != nil {\n\t\tlu.SetExternalID(*s)\n\t}\n\treturn lu\n}", "func (puo *ProfileUpdateOne) SetNillableBirthDate(s *string) *ProfileUpdateOne {\n\tif s != nil {\n\t\tpuo.SetBirthDate(*s)\n\t}\n\treturn puo\n}", "func (squo *SurveyQuestionUpdateOne) SetNillableFloatData(f *float64) *SurveyQuestionUpdateOne {\n\tif f != nil {\n\t\tsquo.SetFloatData(*f)\n\t}\n\treturn squo\n}", "func (au *AppUpdate) SetNillableNamespace(s *string) *AppUpdate {\n\tif s != nil {\n\t\tau.SetNamespace(*s)\n\t}\n\treturn au\n}", "func (vuuo *VacUserUpdateOne) SetNillablePartition(s *string) *VacUserUpdateOne {\n\tif s != nil {\n\t\tvuuo.SetPartition(*s)\n\t}\n\treturn vuuo\n}", "func (upu *UnsavedPostUpdate) SetNillableSlug(s *string) *UnsavedPostUpdate {\n\tif s != nil {\n\t\tupu.SetSlug(*s)\n\t}\n\treturn upu\n}", "func (fu *FriendshipUpdate) SetNillableWeight(i *int) *FriendshipUpdate {\n\tif i != nil {\n\t\tfu.SetWeight(*i)\n\t}\n\treturn fu\n}" ]
[ "0.8551493", "0.8505628", "0.8406956", "0.84064615", "0.832453", "0.8303488", "0.8296725", "0.8289717", "0.82554096", "0.67345166", "0.64931744", "0.60176975", "0.59949774", "0.5966361", "0.5960429", "0.5939814", "0.5910575", "0.5881628", "0.5873669", "0.58630395", "0.58485425", "0.5828972", "0.5825968", "0.5813327", "0.57833624", "0.57766724", "0.5774684", "0.5770019", "0.57401586", "0.57354516", "0.5730715", "0.5728624", "0.5709526", "0.56721073", "0.56659853", "0.5638642", "0.5618884", "0.5615323", "0.55986315", "0.559733", "0.55902606", "0.55892736", "0.5580004", "0.5577594", "0.5574708", "0.5562036", "0.5559365", "0.5559063", "0.5541497", "0.55260944", "0.55244803", "0.5513896", "0.5508183", "0.55005676", "0.5498155", "0.54961044", "0.54961044", "0.54938346", "0.5490925", "0.5490394", "0.5482838", "0.5482838", "0.5472057", "0.5466135", "0.5462678", "0.54592675", "0.5451161", "0.54481316", "0.54437685", "0.54397506", "0.5436935", "0.5436771", "0.543561", "0.54262507", "0.5425093", "0.5420166", "0.54118276", "0.54101616", "0.5408392", "0.5404365", "0.54034406", "0.5397034", "0.53916085", "0.53896505", "0.5389144", "0.5388423", "0.53877956", "0.5377929", "0.5374595", "0.53743935", "0.537113", "0.5367377", "0.53669125", "0.536257", "0.5360522", "0.535095", "0.53490984", "0.53460616", "0.53390574", "0.5336489" ]
0.8401697
4
SetBuild sets the build field.
func (ac *AppCreate) SetBuild(s string) *AppCreate { ac.mutation.SetBuild(s) return ac }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (e *Executor) SetBuild(v Build) {\n\t// return if Executor type is nil\n\tif e == nil {\n\t\treturn\n\t}\n\n\te.Build = &v\n}", "func (au *AppUpdate) SetBuild(s string) *AppUpdate {\n\tau.mutation.SetBuild(s)\n\treturn au\n}", "func (auo *AppUpdateOne) SetBuild(s string) *AppUpdateOne {\n\tauo.mutation.SetBuild(s)\n\treturn auo\n}", "func (l *Log) SetBuildID(v int64) {\n\t// return if Log type is nil\n\tif l == nil {\n\t\treturn\n\t}\n\n\tl.BuildID = &v\n}", "func (bc *MockBuildConnector) SetBuildPriority(buildId string, priority int64) error {\n\tif bc.FailOnChangePriority {\n\t\treturn errors.New(\"manufactured fail\")\n\t}\n\treturn nil\n}", "func (o *ApplianceSetupInfoAllOf) SetBuildType(v string) {\n\to.BuildType = &v\n}", "func (o *Cluster) SetBuildVersion(v string) {\n\to.BuildVersion = &v\n}", "func (o *GetBuildPropertiesParams) SetBuildID(buildID int32) {\n\to.BuildID = buildID\n}", "func (o *UpdateBuildPropertiesParams) SetBuildID(buildID int32) {\n\to.BuildID = buildID\n}", "func (bc *DBBuildConnector) SetBuildPriority(buildId string, priority int64) error {\n\treturn model.SetBuildPriority(buildId, priority)\n}", "func SetToBuilding(ctx context.Context, db gorp.SqlExecutor, workerID string, jobRunID int64, key []byte) error {\n\tw, err := LoadByID(ctx, db, workerID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tw.Status = sdk.StatusBuilding\n\tw.JobRunID = &jobRunID\n\tw.PrivateKey = key\n\n\tdbData := &dbWorker{Worker: *w}\n\tif err := gorpmapping.UpdateAndSign(ctx, db, dbData); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (bc *MockBuildConnector) SetBuildActivated(buildId string, user string, activated bool) error {\n\tb, err := bc.FindBuildById(buildId)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.Activated = activated\n\tb.ActivatedBy = user\n\treturn nil\n}", "func SetBuildstamp(bstamp string) {\n\tbuildstamp = bstamp\n}", "func SetBuildActivation(buildId string, active bool, caller string) error {\n\tif err := build.UpdateActivation([]string{buildId}, active, caller); err != nil {\n\t\treturn errors.Wrapf(err, \"can't set build activation to %t for build '%s'\", active, buildId)\n\t}\n\n\treturn errors.Wrapf(setTaskActivationForBuilds([]string{buildId}, active, nil, caller),\n\t\t\"can't set task activation for build '%s'\", buildId)\n}", "func SetBuildInformation(version, revision, branch string) {\n\tedition := \"oss\"\n\tif setting.IsEnterprise {\n\t\tedition = \"enterprise\"\n\t}\n\n\tgrafanaBuildVersion.WithLabelValues(version, revision, branch, runtime.Version(), edition).Set(1)\n}", "func (ac *AppCreate) SetNillableBuild(s *string) *AppCreate {\n\tif s != nil {\n\t\tac.SetBuild(*s)\n\t}\n\treturn ac\n}", "func WithBuild(cfg *v1alpha1.Configuration) {\n\tcfg.Spec.Build = &v1alpha1.RawExtension{\n\t\tObject: &unstructured.Unstructured{\n\t\t\tObject: map[string]interface{}{\n\t\t\t\t\"apiVersion\": \"testing.build.knative.dev/v1alpha1\",\n\t\t\t\t\"kind\": \"Build\",\n\t\t\t\t\"spec\": map[string]interface{}{\n\t\t\t\t\t\"steps\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"image\": \"foo\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"image\": \"bar\",\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},\n\t}\n}", "func (s *StoreState) SetMinBuildNumber(minBuild uint64) {\n\tbuildBytes := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(buildBytes, minBuild)\n\ts.store.Set([]byte(MinBuildKey), buildBytes)\n}", "func (o *PostDeviceRackParams) SetBuilding(building *string) {\n\to.Building = building\n}", "func (bc *DBBuildConnector) SetBuildActivated(buildId string, user string, activated bool) error {\n\treturn model.SetBuildActivation(buildId, activated, user)\n}", "func (b *BuildVersionClient) SetBuildVersion(\n\tbranch, jobPath string,\n\texcludeSuites []string,\n) (foundVersion string, err error) {\n\tlogrus.Infof(\"Setting build version for branch %q\", branch)\n\n\tif branch == git.Master {\n\t\tbranch = \"release-master\"\n\t\tlogrus.Infof(\"Changing %s branch to %q\", git.Master, branch)\n\t}\n\n\tallJobs, err := b.testGridClient.BlockingTests(branch)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"getting all test jobs\")\n\t}\n\tlogrus.Infof(\"Got testgrid jobs for branch %q: %v\", branch, allJobs)\n\n\tif len(allJobs) == 0 {\n\t\treturn \"\", errors.Errorf(\n\t\t\t\"No sig-%s-blocking list found in the testgrid config.yaml\", branch,\n\t\t)\n\t}\n\n\t// Filter out excluded suites\n\tsecondaryJobs := []string{}\n\tfor i, job := range allJobs {\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\texcluded := false\n\t\tfor _, pattern := range excludeSuites {\n\t\t\tmatched, err := regexp.MatchString(pattern, job)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", errors.Wrapf(err,\n\t\t\t\t\t\"regex compile failed: %s\", pattern,\n\t\t\t\t)\n\t\t\t}\n\t\t\texcluded = matched\n\t\t}\n\n\t\tif !excluded {\n\t\t\tsecondaryJobs = append(secondaryJobs, job)\n\t\t}\n\t}\n\n\t// Update main cache\n\t// We dedup the mainJob's list of successful runs and just run through\n\t// that unique list. We then leave the full state of secondaries below so\n\t// we have finer granularity at the Jenkin's job level to determine if a\n\t// build is ok.\n\tmainJob := allJobs[0]\n\n\tmainJobCache, err := b.jobCacheClient.GetJobCache(mainJob, true)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"building job cache for main job\")\n\t}\n\tif mainJobCache == nil {\n\t\treturn \"\", errors.Errorf(\"main job cache for job %q is nil\", mainJob)\n\t}\n\n\t// Update secondary caches limited by main cache last build number\n\tsecondaryJobCaches := []*JobCache{}\n\tfor _, job := range secondaryJobs {\n\t\tcache, err := b.jobCacheClient.GetJobCache(job, true)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrapf(err, \"building job cache for job: %s\", job)\n\t\t}\n\t\tif cache != nil {\n\t\t\tsecondaryJobCaches = append(secondaryJobCaches, cache)\n\t\t}\n\t}\n\n\tfor i, version := range mainJobCache.Versions {\n\t\tsb := strings.Builder{}\n\t\ttw := tabwriter.NewWriter(&sb, 0, 0, 2, ' ', 0)\n\t\tfmt.Fprintln(tw, \"Job\\tRun\\tBuild\\tDate/Status\")\n\n\t\tbuildVersion := mainJobCache.BuildNumbers[i]\n\n\t\tlogrus.Infof(\"Trying version %q for build %q\", version, buildVersion)\n\n\t\tif i > jobLimit {\n\t\t\treturn \"\", errors.Errorf(\"job count limit of %d exceeded\", jobLimit)\n\t\t}\n\n\t\tmatches := regex.ReleaseAndBuildRegex.FindStringSubmatch(version)\n\t\tif matches == nil || len(matches) < 8 {\n\t\t\treturn \"\", errors.Errorf(\"invalid build version: %v\", version)\n\t\t}\n\n\t\tbuildRun := matches[6]\n\t\tbuildSHA := matches[7]\n\n\t\tdate, err := b.githubClient.GetCommitDate(buildSHA)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrapf(err, \"retrieve repository commit %s\", buildSHA)\n\t\t}\n\n\t\tfmt.Fprint(&sb, \"(*) Primary job (-) Secondary jobs\\n\\n\")\n\t\tfmt.Fprintf(tw,\n\t\t\t\"%s\\t%s\\t%s\\t%s\\t\\n\",\n\t\t\t\"* \"+strings.TrimPrefix(mainJob, jobPrefix),\n\t\t\tbuildVersion, buildRun, date,\n\t\t)\n\n\t\ttype BuildStatus string\n\t\tconst (\n\t\t\tBuildStatusNotExisting BuildStatus = \"NOT EXISTING\"\n\t\t\tBuildStatusFailed BuildStatus = \"FAILED\"\n\t\t\tBuildStatusSucceeded BuildStatus = \"SUCCEEDED\"\n\t\t)\n\t\t// Check secondaries to ensure that build number is green across all\n\t\tsuccess := true\n\t\tfoundBuildNumber := \"\"\n\t\tfor _, secondaryJob := range secondaryJobs {\n\t\t\tstatus := BuildStatusNotExisting\n\t\t\tfor _, secondaryJobCache := range secondaryJobCaches {\n\t\t\t\tif secondaryJobCache.Name == secondaryJob {\n\t\t\t\t\tstatus = BuildStatusFailed\n\n\t\t\t\t\tfor j, secVersion := range secondaryJobCache.Versions {\n\t\t\t\t\t\tmatches := regex.ReleaseAndBuildRegex.FindStringSubmatch(secVersion)\n\t\t\t\t\t\tif matches == nil || len(matches) < 8 {\n\t\t\t\t\t\t\tlogrus.Errorf(\n\t\t\t\t\t\t\t\t\"Invalid build version %s for job %s\",\n\t\t\t\t\t\t\t\tsecVersion, secondaryJob,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Verify that we have the same build number\n\t\t\t\t\t\tif buildRun == matches[6] {\n\t\t\t\t\t\t\tstatus = BuildStatusSucceeded\n\t\t\t\t\t\t\tfoundBuildNumber = secondaryJobCache.BuildNumbers[j]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif status == BuildStatusSucceeded {\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\tfmt.Fprintf(tw,\n\t\t\t\t\"%s\\t%s\\t%s\\t%s\\t\\n\",\n\t\t\t\t\"- \"+strings.TrimPrefix(secondaryJob, jobPrefix),\n\t\t\t\tfoundBuildNumber, buildRun, status,\n\t\t\t)\n\n\t\t\tif status == BuildStatusFailed {\n\t\t\t\tsuccess = false\n\t\t\t}\n\t\t}\n\n\t\ttw.Flush()\n\t\tfmt.Println(sb.String())\n\n\t\tif success {\n\t\t\treturn version, nil\n\t\t}\n\t}\n\n\treturn \"\", errors.New(\"unable to find successful build version\")\n}", "func (c DQLConfig) MakeBuild(test bool) {\n\tc.make(\"bin\", \"build\", test)\n}", "func (au *AppUpdate) SetNillableBuild(s *string) *AppUpdate {\n\tif s != nil {\n\t\tau.SetBuild(*s)\n\t}\n\treturn au\n}", "func (o *GetRacksParams) SetBuilding(building *string) {\n\to.Building = building\n}", "func (m *PrinterLocation) SetBuilding(value *string)() {\n err := m.GetBackingStore().Set(\"building\", value)\n if err != nil {\n panic(err)\n }\n}", "func (mr *MockPackClientMockRecorder) Build(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Build\", reflect.TypeOf((*MockPackClient)(nil).Build), arg0, arg1)\n}", "func (auo *AppUpdateOne) SetNillableBuild(s *string) *AppUpdateOne {\n\tif s != nil {\n\t\tauo.SetBuild(*s)\n\t}\n\treturn auo\n}", "func (mr *MockDeploymentControllerFactoryMockRecorder) Build(mgr, clusterName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Build\", reflect.TypeOf((*MockDeploymentControllerFactory)(nil).Build), mgr, clusterName)\n}", "func (f *ManufacturingDirector) SetBuilder(b BuildProcess) {\n\tf.builder = b\n}", "func (o *VirtualizationIweClusterAllOf) SetHypervisorBuild(v string) {\n\to.HypervisorBuild = &v\n}", "func (mr *MockBackendMockRecorder) Build(fs, image, devfilePath interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Build\", reflect.TypeOf((*MockBackend)(nil).Build), fs, image, devfilePath)\n}", "func GetBuild() string {\n\treturn Build\n}", "func (mr *MockBuilderMockRecorder) Build() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Build\", reflect.TypeOf((*MockBuilder)(nil).Build))\n}", "func SetBuildPriority(buildId string, priority int64, caller string) error {\n\t_, err := task.UpdateAll(\n\t\tbson.M{task.BuildIdKey: buildId},\n\t\tbson.M{\"$set\": bson.M{task.PriorityKey: priority}},\n\t)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"problem setting build '%s' priority\", buildId)\n\t}\n\n\t// negative priority - these tasks should never run, so unschedule now\n\tif priority < 0 {\n\t\ttasks, err := task.FindAll(db.Query(bson.M{task.BuildIdKey: buildId}).\n\t\t\tWithFields(task.IdKey, task.ExecutionKey))\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"can't get tasks for build '%s'\", buildId)\n\t\t}\n\t\tif err = task.DeactivateTasks(tasks, caller); err != nil {\n\t\t\treturn errors.Wrapf(err, \"can't deactivate tasks for build '%s'\", buildId)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o *ServeBuildFieldShortParams) SetBuildLocator(buildLocator string) {\n\to.BuildLocator = buildLocator\n}", "func (mr *MockPodControllerFactoryMockRecorder) Build(mgr, clusterName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Build\", reflect.TypeOf((*MockPodControllerFactory)(nil).Build), mgr, clusterName)\n}", "func (mr *MockMeshServiceControllerFactoryMockRecorder) Build(mgr, clusterName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Build\", reflect.TypeOf((*MockMeshServiceControllerFactory)(nil).Build), mgr, clusterName)\n}", "func (mr *MockMeshWorkloadControllerFactoryMockRecorder) Build(mgr, clusterName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Build\", reflect.TypeOf((*MockMeshWorkloadControllerFactory)(nil).Build), mgr, clusterName)\n}", "func (d *remoteDB) PutBuild(b *Build) error {\n\tvar buf bytes.Buffer\n\tif err := gob.NewEncoder(&buf).Encode(b); err != nil {\n\t\treturn err\n\t}\n\treq := &rpc.Build{\n\t\tBuild: buf.Bytes(),\n\t}\n\tif _, err := d.client.PutBuild(context.Background(), req); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (mr *MockServiceControllerFactoryMockRecorder) Build(mgr, clusterName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Build\", reflect.TypeOf((*MockServiceControllerFactory)(nil).Build), mgr, clusterName)\n}", "func (ts *Tester) Build() error {\n\t// no-op\n\treturn nil\n}", "func (fft FeatureFlagToggles) SetDockerfileBuilds(enabled bool) {\n\tfft[dockerfileBuildsFlag] = enabled\n}", "func SetBuildEnv(build *buildapi.Build, env []kapi.EnvVar) {\n\tvar oldEnv *[]kapi.EnvVar\n\n\tswitch {\n\tcase build.Spec.Strategy.SourceStrategy != nil:\n\t\toldEnv = &build.Spec.Strategy.SourceStrategy.Env\n\tcase build.Spec.Strategy.DockerStrategy != nil:\n\t\toldEnv = &build.Spec.Strategy.DockerStrategy.Env\n\tcase build.Spec.Strategy.CustomStrategy != nil:\n\t\toldEnv = &build.Spec.Strategy.CustomStrategy.Env\n\tcase build.Spec.Strategy.JenkinsPipelineStrategy != nil:\n\t\toldEnv = &build.Spec.Strategy.JenkinsPipelineStrategy.Env\n\tdefault:\n\t\treturn\n\t}\n\t*oldEnv = env\n}", "func (builder *Builder) BuildSetenv() {\n\tif builder.Meta.Arch != \"\" {\n\t\tos.Setenv(\"ARCH\", builder.Meta.Arch)\n\t\tos.Setenv(\"CROSS_COMPILE\", builder.Meta.Target+\"-\")\n\t}\n}", "func (fs *BaseFs) LockBuild() (unlock func(), err error) {\n\treturn fs.buildMu.Lock()\n}", "func Build() BuildResponse {\n\treturn BuildResponse{\n\t\tVersion: version,\n\t\tCommit: commit,\n\t\tBuiltAt: date,\n\t\tBuiltBy: builtBy,\n\t}\n}", "func RunBuild(projCfg *aws.Project, buildCfg *aws.Build, branch string, extraParams aws.BuildParameters) (*CIBuildResponse, error) {\n\tcib, err := TriggerBuildDo(projCfg, buildCfg, branch, extraParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &cib, nil\n}", "func (mr *MockAPIMockRecorder) GetBuild(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetBuild\", reflect.TypeOf((*MockAPI)(nil).GetBuild), arg0, arg1, arg2)\n}", "func (o Other) Build() error {\n\tbt := BuildToolchain{\n\t\tautoYes: o.autoYes,\n\t\tbuildFn: o.Shell.Build,\n\t\tbuildScript: o.build,\n\t\terrlog: o.errlog,\n\t\tin: o.input,\n\t\tnonInteractive: o.nonInteractive,\n\t\tout: o.output,\n\t\tpostBuild: o.postBuild,\n\t\tspinner: o.spinner,\n\t\ttimeout: o.timeout,\n\t\tverbose: o.verbose,\n\t}\n\treturn bt.Build()\n}", "func (o *PostWebhook) SetBuildStatus(v bool) {\n\to.BuildStatus = &v\n}", "func Build() error {\n\treturn devtools.Build(devtools.DefaultBuildArgs())\n}", "func (b *OGame) BuildBuilding(celestialID ogame.CelestialID, buildingID ogame.ID) error {\n\treturn b.WithPriority(taskRunner.Normal).BuildBuilding(celestialID, buildingID)\n}", "func BuildVersion() string {\n\tif version == \"\" {\n\t\treturn \"1.0-dev\"\n\t}\n\treturn version\n}", "func (mr *MockRenderClientMockRecorder) BuildPage(w, pageModel, templateName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"BuildPage\", reflect.TypeOf((*MockRenderClient)(nil).BuildPage), w, pageModel, templateName)\n}", "func BuildSet(key, value string) *Cmd {\n\treturn Build(key, \"SET\", key, value)\n}", "func WithBuildRef(name string) RevisionOption {\n\treturn func(rev *v1alpha1.Revision) {\n\t\trev.Spec.BuildRef = &corev1.ObjectReference{\n\t\t\tAPIVersion: \"testing.build.knative.dev/v1alpha1\",\n\t\t\tKind: \"Build\",\n\t\t\tName: name,\n\t\t}\n\t}\n}", "func (sv *SV) SetBuildIDs(ids []string) error {\n\terr := CheckAllBuildIDs(ids)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsv.buildIDs = ids\n\treturn nil\n}", "func (t *Target) Build() error {\n\tbuild := exec.Command(\"go\", \"build\", \"-o\", t.BinaryPath)\n\tdata, err := build.CombinedOutput()\n\n\tif err != nil {\n\t\treturn errors.New(string(data))\n\t}\n\n\treturn nil\n}", "func (mr *MockDependencyBuilderMockRecorder) Build(ctx, manifests interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Build\", reflect.TypeOf((*MockDependencyBuilder)(nil).Build), ctx, manifests)\n}", "func (runtime *Runtime) Build(claset tabula.ClasetInterface) (e error) {\n\t// Re-check input configuration.\n\tswitch runtime.SplitMethod {\n\tcase SplitMethodGini:\n\t\t// Do nothing.\n\tdefault:\n\t\t// Set default split method to Gini index.\n\t\truntime.SplitMethod = SplitMethodGini\n\t}\n\n\truntime.Tree.Root, e = runtime.splitTreeByGain(claset)\n\n\treturn\n}", "func (vpc *VipPriceConfig) FilterBuild(build int64) bool {\n\tif (vpc.StartBuild != 0 && vpc.StartBuild > build) || (vpc.EndBuild != 0 && vpc.EndBuild < build) {\n\t\treturn false\n\t}\n\treturn true\n}", "func (p *TestPackage) Build() error {\n\tif p.build != nil {\n\t\treturn nil\n\t}\n\tif err := p.write(); err != nil {\n\t\treturn err\n\t}\n\tbasePackage, err := build.Default.ImportDir(p.Path, build.ImportComment)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar packageFiles []string\n\tfor _, filename := range basePackage.GoFiles {\n\t\tpackageFiles = append(packageFiles, path.Join(p.Path, filename))\n\t}\n\n\tconf := &packages.Config{\n\t\tMode: gosec.LoadMode,\n\t\tTests: false,\n\t}\n\tpkgs, err := packages.Load(conf, packageFiles...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.build = &buildObj{\n\t\tpkg: basePackage,\n\t\tconfig: conf,\n\t\tpkgs: pkgs,\n\t}\n\treturn nil\n}", "func (a *Client) ServeBuild(params *ServeBuildParams, authInfo runtime.ClientAuthInfoWriter) (*ServeBuildOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewServeBuildParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"serveBuild\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/app/rest/builds/{buildLocator}\",\n\t\tProducesMediaTypes: []string{\"application/json\", \"application/xml\", \"text/plain\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/xml\", \"text/plain\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ServeBuildReader{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.(*ServeBuildOK), nil\n\n}", "func InvokeBuild(yamlConfig string, options InvokeBuildOptions) error {\n\t// Parse a graph from the YAML build config.\n\tgraph, err := buildgraph.ParseGraphFromYAML([]byte(yamlConfig))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Find the initial set of units to build.\n\tinitialJobs, err := graph.GetDependants(nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(initialJobs) == 0 {\n\t\treturn errors.New(\"No independent build units defined\")\n\t}\n\n\t// Load the build package.\n\tbuildPackageDirectory, err := CreateBuildPackageDirectory(options.BuildPackage)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Start the initial build units.\n\treturn invokeBuild(graph, initialJobs, buildPackageDirectory, options)\n}", "func (p *Process) BuildVersion() string {\n\treturn p.buildVersion\n}", "func (o *GetRoomsParams) SetBuilding(building *string) {\n\to.Building = building\n}", "func (o *SetFinishedTimeParams) SetBuildLocator(buildLocator string) {\n\to.BuildLocator = buildLocator\n}", "func ProjectBuild(p project.APIProject, c *cli.Context) error {\n\tconfig := options.Build{\n\t\tNoCache: c.Bool(\"no-cache\"),\n\t\tForceRemove: c.Bool(\"force-rm\"),\n\t\tPull: c.Bool(\"pull\"),\n\t}\n\terr := p.Build(context.Background(), config, c.Args()...)\n\tif err != nil {\n\t\treturn cli.NewExitError(err.Error(), 1)\n\t}\n\treturn nil\n}", "func (d Builder) Build(contextPath string) (builders.ArtifactPath, error) {\n\treturn d.execute(\"build\", \"-t\", d.artifactName, contextPath)\n}", "func (o FunctionBuildConfigOutput) Build() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FunctionBuildConfig) *string { return v.Build }).(pulumi.StringPtrOutput)\n}", "func (o *UpdateBuildPropertiesParams) WithBuildID(buildID int32) *UpdateBuildPropertiesParams {\n\to.SetBuildID(buildID)\n\treturn o\n}", "func (m *MockBackend) Build(fs filesystem.Filesystem, image *v1alpha2.ImageComponent, devfilePath string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Build\", fs, image, devfilePath)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (t DefaultBuildManager) LaunchBuild(buildEvent v1.UserBuildEvent) error {\n\n\tif !t.QueueIsOpen() {\n\t\tt.logger.Printf(\"Build queue closed: %+v\\n\", buildEvent)\n\t\treturn nil\n\t}\n\n\tprojectKey := buildEvent.ProjectKey()\n\n\tproject := t.projectManager.Get(projectKey)\n\tif project == nil {\n\t\treturn fmt.Errorf(\"Project %s is missing from build scripts repository.\\n\", projectKey)\n\t}\n\n\tif !project.Descriptor.IsRefManaged(buildEvent.Ref) {\n\t\treturn fmt.Errorf(\"Ref %s is not managed on project %s. Not launching a build.\\n\", buildEvent.Ref, projectKey)\n\t}\n\n\tbuildEvent.ID = uuid.Uuid()\n\n\tif err := t.lockService.Acquire(buildEvent); err != nil {\n\t\tt.logger.Printf(\"Failed to acquire lock for project %s, branch %s: %v\\n\", projectKey, buildEvent.Ref, err)\n\t\tif err := t.deferralService.Defer(buildEvent); err != nil {\n\t\t\tt.logger.Printf(\"Failed to defer build: %s/%s\\n\", projectKey, buildEvent.Ref)\n\t\t} else {\n\t\t\tt.logger.Printf(\"Deferred build: %s/%s\\n\", projectKey, buildEvent.Ref)\n\t\t}\n\t\treturn nil\n\t}\n\n\tt.logger.Printf(\"Acquired lock on build %s for project %s, branch %s\\n\", buildEvent.ID, projectKey, buildEvent.Ref)\n\n\tcontainers := t.makeContainers(buildEvent)\n\tpod := t.makePod(buildEvent, containers)\n\n\tif err := t.CreatePod(pod); err != nil {\n\t\tif err := t.lockService.Release(buildEvent); err != nil {\n\t\t\tt.logger.Printf(\"Failed to release lock on build %s, project %s, branch %s. No deferral will be attempted.\\n\", buildEvent.ID, projectKey, buildEvent.Ref)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tt.logger.Printf(\"Created pod %s\\n\", buildEvent.ID)\n\n\treturn nil\n}", "func (t *Track) InitialiseBuild(path string) error {\n\tt.builder = Builder{}\n\tt.chunksDepth = 30\n\t/* Initialise builder */\n\tt.builder.Initialise()\n\t/* Create destination directory if it does not exist */\n\tif !utils.FileExist(path) {\n\t\tos.MkdirAll(path, os.ModeDir|os.ModePerm)\n\t} else if !utils.IsDirectory(path) {\n\t\treturn errors.New(\"Path '\" + path + \"' is not a directory\")\n\t}\n\treturn nil\n}", "func (b *Build) Get() error {\n\tappendum := \"/builds('\" + b.BuildID + \"')\"\n\tbody, err := b.Connector.Get(appendum)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar jBuild jsonBuild\n\tjson.Unmarshal(body, &jBuild)\n\tb.RunState = jBuild.Build.RunState\n\tb.ResultState = jBuild.Build.ResultState\n\tb.Phase = jBuild.Build.Phase\n\tb.Entitytype = jBuild.Build.Entitytype\n\tb.Startedby = jBuild.Build.Startedby\n\tb.StartedAt = jBuild.Build.StartedAt\n\tb.FinishedAt = jBuild.Build.FinishedAt\n\treturn nil\n}", "func (c *ApplicationCredentials) UpdateBuild(sv *ApplicationServer, addAlloc []int, removeAlloc []int) (err error) {\n\ttype build struct {\n\t\tAllocation int `json:\"allocation,omitempty\"`\n\t\tOOM bool `json:\"oom_disabled\"`\n\t\tLimits *Limits `json:\"limits,omitempty\"`\n\t\tAddAllocations []int `json:\"add_allocations,omitempty\"`\n\t\tRemoveAllocations []int `json:\"remove_allocations,omitempty\"`\n\t\tFeatureLimits struct {\n\t\t\tDatabases int `json:\"databases\"`\n\t\t\tAllocations int `json:\"allocations,omitempty\"`\n\t\t} `json:\"feature_limits\"`\n\t}\n\n\tb := build{\n\t\tOOM: true,\n\t\tAllocation: sv.Allocation,\n\t\tLimits: &sv.Limits,\n\t\tAddAllocations: addAlloc,\n\t\tRemoveAllocations: removeAlloc,\n\t}\n\n\tb.FeatureLimits.Allocations = sv.Limits.Allocations\n\tb.FeatureLimits.Databases = sv.Limits.Databases\n\n\tbytes, err := json.Marshal(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = c.query(fmt.Sprintf(\"servers/%d/build\", sv.ID), \"PATCH\", bytes)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn nil\n}", "func BuildDate() time.Time {\n\tt, _ := time.Parse(time.RFC3339, buildDate)\n\treturn t\n}", "func (gw2 *GW2Api) Build() (v int, err error) {\n\tver := \"v2\"\n\ttag := \"build\"\n\n\tvar res version\n\tif err = gw2.fetchEndpoint(ver, tag, nil, &res); err != nil {\n\t\treturn 0, err\n\t}\n\treturn res.ID, nil\n}", "func BuildVersion() int {\n\treturn int(C.getBuildVersion())\n\n}", "func Build(conf *entity.JenkinsConfig, job gojenkins.Job, params url.Values) (err error) {\n\tdebug(\"[Build]conf\", *conf)\n\tdebug(\"[Build]job\", job)\n\tdebug(\"[Build]params\", params)\n\n\tauth := &gojenkins.Auth{\n\t\tUsername: conf.User,\n\t\tApiToken: conf.Token,\n\t}\n\tjenkins := gojenkins.NewJenkins(auth, conf.URL)\n\terr = jenkins.Build(job, params)\n\n\tif err != nil {\n\t\tFatalf(\"error exec command: %s\", err)\n\t\treturn\n\t}\n\n\treturn\n}", "func (builder *GoBuider) Build() {\n\tbuilder.compileMtx.Lock()\n\tdefer builder.compileMtx.Unlock()\n\n\tgoProjectPath := builder.GoProjectPath\n\toutputFolderPath := builder.OutputFolderPath\n\tintegration.MakeDirs(outputFolderPath)\n\n\ttarget := builder.Executable()\n\tif integration.FileExists(target) {\n\t\tdeleteOutputExecutable(builder)\n\t\tintegration.DeRegisterDisposableAsset(builder)\n\t}\n\n\t// check project path\n\tpkg, err := build.ImportDir(goProjectPath, build.FindOnly)\n\tintegration.CheckTestSetupMalfunction(err)\n\tgoProjectPath = pkg.ImportPath\n\n\trunBuildCommand(builder, goProjectPath)\n\tintegration.RegisterDisposableAsset(builder)\n}", "func expireBuild(c context.Context, b *buildbotBuild) error {\n\tfinished := float64(clock.Now(c).Unix())\n\tif b.TimeStamp != nil {\n\t\tfinished = float64(*b.TimeStamp)\n\t}\n\tresults := int(4) // Exception\n\tb.Times[1] = &finished\n\tb.Finished = true\n\tb.Results = &results\n\tb.Currentstep = nil\n\tb.Text = append(b.Text, \"Build expired on Milo\")\n\treturn ds.Put(c, b)\n}", "func (fft FeatureFlagToggles) SetAppDevExperienceBuilds(enabled bool) {\n\tfft[adxBuildsFlag] = enabled\n}", "func (query *Query) Build() {\n\tquery.isBuilt = true\n}", "func Build() error {\n\tif strings.Contains(runtime.Version(), \"1.8\") {\n\t\t// Go 1.8 doesn't play along with go test ./... and /vendor.\n\t\t// We could fix that, but that would take time.\n\t\tfmt.Printf(\"Skip Build on %s\\n\", runtime.Version())\n\t\treturn nil\n\t}\n\n\t// TODO: Add lint after fixing errors\n\tmg.Deps(Fmt, Vet, TestRace)\n\treturn nil\n}", "func (a *Client) PinBuild(params *PinBuildParams, authInfo runtime.ClientAuthInfoWriter) error {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewPinBuildParams()\n\t}\n\n\t_, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"pinBuild\",\n\t\tMethod: \"PUT\",\n\t\tPathPattern: \"/app/rest/builds/{buildLocator}/pin\",\n\t\tProducesMediaTypes: []string{\"application/json\", \"application/xml\", \"text/plain\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/xml\", \"text/plain\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &PinBuildReader{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 err\n\t}\n\treturn nil\n\n}", "func Build() error {\n\n\t// ldf, err := flags()\n\t// if err != nil {\n\t// \treturn err\n\t// }\n\n\tlog.Print(\"running go build\")\n\t// use -tags make so we can have different behavior for when we know we've built with mage.\n\t// return sh.Run(\"go\", \"build\", \"-tags\", \"make\", \"--ldflags=\"+ldf, \"gnorm.org/gnorm\")\n\treturn sh.RunWith(flagEnv(), \"go\", \"build\", \"-o\", \"build/unichem2index\", \"-ldflags\", ldflags, packageName)\n}", "func (e *OptTester) OptBuild() (memo.ExprView, error) {\n\treturn e.optimizeExpr(false /* allowOptimizations */)\n}", "func (m *MockRenderClient) BuildPage(w io.Writer, pageModel interface{}, templateName string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"BuildPage\", w, pageModel, templateName)\n}", "func updateBuild(args []string) {\n\tproject := args[0]\n\toldName := args[1]\n\tnewName := args[2]\n\tdata, klocworkURL := formBaseRequest(\"builds\")\n\n\tdata.Set(\"action\", \"update_build\")\n\tdata.Set(\"project\", project)\n\tdata.Set(\"name\", oldName)\n\tdata.Set(\"new_name\", newName)\n\t_, body := sendRequest(klocworkURL, data)\n\n\tif body != nil {\n\t\tfmt.Println(\"Done.\")\n\t}\n}", "func (b *GlogLoggerBuilder) Build() (logger *GlogLogger, err error) {\n\t// Allocate and populate the object:\n\tlogger = new(GlogLogger)\n\tlogger.debugV = b.debugV\n\tlogger.infoV = b.infoV\n\tlogger.warnV = b.warnV\n\tlogger.errorV = b.errorV\n\n\treturn\n}", "func TriggerBuildDo(projConfig *aws.Project, buildCfg *aws.Build, branch string, extraParams aws.BuildParameters) (build CIBuildResponse, err error) {\n\taws.FetchTokenIfMissing(projConfig)\n\tvar b strings.Builder\n\tfmt.Fprint(&b, projConfig.CircleCIURL)\n\tif projConfig.CircleCIURL[len(projConfig.CircleCIURL)-1] == '/' {\n\t\tfmt.Fprint(&b, \"tree/\")\n\t} else {\n\t\tfmt.Fprint(&b, \"/tree/\")\n\t}\n\tfmt.Fprint(&b, branch)\n\tvar params aws.BuildParameters\n\tparams = make(aws.BuildParameters)\n\tfor key, val := range buildCfg.RunBuildParameters {\n\t\tparams[key] = val\n\t}\n\tfor key, val := range extraParams {\n\t\tparams[key] = val\n\t}\n\treq, err := TriggerBuildRequest(b.String(), projConfig.CircleCIToken, params)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = api.NoRedirectClientDo(req, &build)\n\treturn\n}", "func (au *AppUpdate) ClearBuild() *AppUpdate {\n\tau.mutation.ClearBuild()\n\treturn au\n}", "func (m *MockPackClient) Build(arg0 context.Context, arg1 client.BuildOptions) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Build\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (o *UpdateBuildPropertiesParams) SetProject(project string) {\n\to.Project = project\n}", "func setVersion() {\n\tgitTag = GitCommit\n\n\t// A development build is one that's not at a tag or has uncommitted changes\n\tdevBuild = gitTag == \"\" || gitShortStat != \"\"\n\n\t// Only set the appVersion if -ldflags was used\n\tif gitNearestTag != \"\" || gitTag != \"\" {\n\t\tif devBuild && gitNearestTag != \"\" {\n\t\t\tappVersion = fmt.Sprintf(\"%s (+%s %s)\", strings.TrimPrefix(gitNearestTag, \"v\"), GitCommit, buildDate)\n\t\t} else if gitTag != \"\" {\n\t\t\tappVersion = strings.TrimPrefix(gitTag, \"v\")\n\t\t}\n\t}\n}", "func Build() error {\n\ts := TermSpinner(\"building modware-import binary ...\")\n\tdefer s.Stop()\n\ts.Start()\n\treturn sh.Run(\"go\", \"build\", \"-o\", Command, \"cmd/import/main.go\")\n}", "func (c *CommandBuild) Build() (string, error) {\n\tc.buildOnce.Do(func() {\n\t\tbasename := filepath.Base(c.ImportPath)\n\t\texe, err := ioutil.TempFile(\"\", basename+\"-\")\n\t\tif err != nil {\n\t\t\tc.buildErr = err\n\t\t\treturn\n\t\t}\n\t\tc.buildPath = exe.Name()\n\t\t_ = os.Remove(c.buildPath) // the build tool will create this\n\t\toptions := Options{\n\t\t\tImportPaths: []string{c.ImportPath},\n\t\t\tOutput: c.buildPath,\n\t\t}\n\t\tif _, err = options.Command(\"build\"); err != nil {\n\t\t\tc.buildErr = err\n\t\t\treturn\n\t\t}\n\t})\n\treturn c.buildPath, c.buildErr\n}", "func (b *WeaveBuilder) Build(c *fi.ModelBuilderContext) error {\n\tif b.Cluster.Spec.Networking.Weave == nil {\n\t\treturn nil\n\t}\n\n\tb.AddCNIBinAssets(c, []string{\"portmap\"})\n\n\treturn nil\n}", "func (m *MockDeploymentControllerFactory) Build(mgr mc_manager.AsyncManager, clusterName string) (controller0.DeploymentController, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Build\", mgr, clusterName)\n\tret0, _ := ret[0].(controller0.DeploymentController)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}" ]
[ "0.8008988", "0.76756823", "0.76625735", "0.6384204", "0.62636846", "0.611718", "0.60730314", "0.60614896", "0.6038821", "0.5954646", "0.5927414", "0.5866466", "0.5788885", "0.5745907", "0.5707158", "0.5696907", "0.56841594", "0.5680812", "0.56798065", "0.5637473", "0.561991", "0.5613286", "0.5584833", "0.5583547", "0.5581239", "0.55335265", "0.5530045", "0.55247337", "0.55018413", "0.5461744", "0.54362744", "0.54351664", "0.5430513", "0.53966916", "0.538228", "0.5372543", "0.5370068", "0.53666097", "0.5321315", "0.53045034", "0.52745056", "0.5254779", "0.5236942", "0.5223789", "0.5204058", "0.5143376", "0.5139378", "0.51261854", "0.5115654", "0.51071864", "0.50924444", "0.5081299", "0.5050418", "0.5048932", "0.5047053", "0.502122", "0.502051", "0.5010595", "0.50005406", "0.49778664", "0.49652684", "0.4963637", "0.49479213", "0.494461", "0.49235976", "0.4914404", "0.49081102", "0.49065277", "0.48943457", "0.48862013", "0.486887", "0.48668075", "0.48665562", "0.4851727", "0.48318243", "0.48314416", "0.48137724", "0.4806812", "0.48065445", "0.48012188", "0.48009643", "0.47993428", "0.47957787", "0.47952956", "0.47918987", "0.47908354", "0.47830206", "0.47765017", "0.4756646", "0.47367173", "0.47264415", "0.47252056", "0.47246563", "0.47200012", "0.47137946", "0.46900633", "0.46790037", "0.46718723", "0.46675897", "0.46660706" ]
0.7721887
1
SetNillableBuild sets the build field if the given value is not nil.
func (ac *AppCreate) SetNillableBuild(s *string) *AppCreate { if s != nil { ac.SetBuild(*s) } return ac }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (auo *AppUpdateOne) SetNillableBuild(s *string) *AppUpdateOne {\n\tif s != nil {\n\t\tauo.SetBuild(*s)\n\t}\n\treturn auo\n}", "func (au *AppUpdate) SetNillableBuild(s *string) *AppUpdate {\n\tif s != nil {\n\t\tau.SetBuild(*s)\n\t}\n\treturn au\n}", "func (pu *PendingloanbindingUpdate) SetNillableDateGenLB(t *time.Time) *PendingloanbindingUpdate {\n\tif t != nil {\n\t\tpu.SetDateGenLB(*t)\n\t}\n\treturn pu\n}", "func (rec *RawEventCreate) SetNillablePlatform(s *string) *RawEventCreate {\n\tif s != nil {\n\t\trec.SetPlatform(*s)\n\t}\n\treturn rec\n}", "func (puo *PendingloanbindingUpdateOne) SetNillableDateGenLB(t *time.Time) *PendingloanbindingUpdateOne {\n\tif t != nil {\n\t\tpuo.SetDateGenLB(*t)\n\t}\n\treturn puo\n}", "func (wouo *WorkOrderUpdateOne) SetNillableInstallDate(t *time.Time) *WorkOrderUpdateOne {\n\tif t != nil {\n\t\twouo.SetInstallDate(*t)\n\t}\n\treturn wouo\n}", "func (ggc *GithubGistCreate) SetNillableLanguage(s *string) *GithubGistCreate {\n\tif s != nil {\n\t\tggc.SetLanguage(*s)\n\t}\n\treturn ggc\n}", "func (wou *WorkOrderUpdate) SetNillableInstallDate(t *time.Time) *WorkOrderUpdate {\n\tif t != nil {\n\t\twou.SetInstallDate(*t)\n\t}\n\treturn wou\n}", "func (luo *LocationUpdateOne) SetNillableSiteSurveyNeeded(b *bool) *LocationUpdateOne {\n\tif b != nil {\n\t\tluo.SetSiteSurveyNeeded(*b)\n\t}\n\treturn luo\n}", "func (gauo *GithubAssetUpdateOne) SetNillableState(s *string) *GithubAssetUpdateOne {\n\tif s != nil {\n\t\tgauo.SetState(*s)\n\t}\n\treturn gauo\n}", "func (lu *LibraryUpdate) SetNillableVersion(s *string) *LibraryUpdate {\n\tif s != nil {\n\t\tlu.SetVersion(*s)\n\t}\n\treturn lu\n}", "func (wouo *WorkOrderUpdateOne) SetNillableProjectID(id *string) *WorkOrderUpdateOne {\n\tif id != nil {\n\t\twouo = wouo.SetProjectID(*id)\n\t}\n\treturn wouo\n}", "func (luo *LibraryUpdateOne) SetNillableVersion(s *string) *LibraryUpdateOne {\n\tif s != nil {\n\t\tluo.SetVersion(*s)\n\t}\n\treturn luo\n}", "func (wc *WalletCreate) SetNillableWork(b *bool) *WalletCreate {\n\tif b != nil {\n\t\twc.SetWork(*b)\n\t}\n\treturn wc\n}", "func (wou *WorkOrderUpdate) SetNillableProjectID(id *string) *WorkOrderUpdate {\n\tif id != nil {\n\t\twou = wou.SetProjectID(*id)\n\t}\n\treturn wou\n}", "func (bc *BouncerCreate) SetNillableVersion(s *string) *BouncerCreate {\n\tif s != nil {\n\t\tbc.SetVersion(*s)\n\t}\n\treturn bc\n}", "func (gau *GithubAssetUpdate) SetNillableState(s *string) *GithubAssetUpdate {\n\tif s != nil {\n\t\tgau.SetState(*s)\n\t}\n\treturn gau\n}", "func (lu *LocationUpdate) SetNillableSiteSurveyNeeded(b *bool) *LocationUpdate {\n\tif b != nil {\n\t\tlu.SetSiteSurveyNeeded(*b)\n\t}\n\treturn lu\n}", "func (qiuo *QueueItemUpdateOne) SetNillableConstructionID(id *int) *QueueItemUpdateOne {\n\tif id != nil {\n\t\tqiuo = qiuo.SetConstructionID(*id)\n\t}\n\treturn qiuo\n}", "func (rec *RawEventCreate) SetNillableChannel(s *string) *RawEventCreate {\n\tif s != nil {\n\t\trec.SetChannel(*s)\n\t}\n\treturn rec\n}", "func (cc *ConstructionCreate) SetNillableNeedRefresh(b *bool) *ConstructionCreate {\n\tif b != nil {\n\t\tcc.SetNeedRefresh(*b)\n\t}\n\treturn cc\n}", "func (cc *ConstructionCreate) SetNillableLastUpdated(t *time.Time) *ConstructionCreate {\n\tif t != nil {\n\t\tcc.SetLastUpdated(*t)\n\t}\n\treturn cc\n}", "func (qiu *QueueItemUpdate) SetNillableConstructionID(id *int) *QueueItemUpdate {\n\tif id != nil {\n\t\tqiu = qiu.SetConstructionID(*id)\n\t}\n\treturn qiu\n}", "func (duo *DeviceUpdateOne) SetNillableVersion(s *string) *DeviceUpdateOne {\n\tif s != nil {\n\t\tduo.SetVersion(*s)\n\t}\n\treturn duo\n}", "func (tu *TransactionfactorUpdate) SetNillablePaymentChannel(s *string) *TransactionfactorUpdate {\n\tif s != nil {\n\t\ttu.SetPaymentChannel(*s)\n\t}\n\treturn tu\n}", "func (ac *AppCreate) SetNillableVersion(s *string) *AppCreate {\n\tif s != nil {\n\t\tac.SetVersion(*s)\n\t}\n\treturn ac\n}", "func (duo *DealUpdateOne) SetNillablePhone(s *string) *DealUpdateOne {\n\tif s != nil {\n\t\tduo.SetPhone(*s)\n\t}\n\treturn duo\n}", "func (tu *TransactionfactorUpdate) SetNillableDate(s *string) *TransactionfactorUpdate {\n\tif s != nil {\n\t\ttu.SetDate(*s)\n\t}\n\treturn tu\n}", "func (tuo *TransactionfactorUpdateOne) SetNillableDate(s *string) *TransactionfactorUpdateOne {\n\tif s != nil {\n\t\ttuo.SetDate(*s)\n\t}\n\treturn tuo\n}", "func (buo *BookingUpdateOne) SetNillableBOOKINGDATE(t *time.Time) *BookingUpdateOne {\n\tif t != nil {\n\t\tbuo.SetBOOKINGDATE(*t)\n\t}\n\treturn buo\n}", "func (tuo *TransactionfactorUpdateOne) SetNillablePaymentChannel(s *string) *TransactionfactorUpdateOne {\n\tif s != nil {\n\t\ttuo.SetPaymentChannel(*s)\n\t}\n\treturn tuo\n}", "func (ggc *GithubGistCreate) SetNillableDescription(s *string) *GithubGistCreate {\n\tif s != nil {\n\t\tggc.SetDescription(*s)\n\t}\n\treturn ggc\n}", "func (bu *BookingUpdate) SetNillableBOOKINGDATE(t *time.Time) *BookingUpdate {\n\tif t != nil {\n\t\tbu.SetBOOKINGDATE(*t)\n\t}\n\treturn bu\n}", "func (cc *ConstructionCreate) SetNillableLevel(i *int) *ConstructionCreate {\n\tif i != nil {\n\t\tcc.SetLevel(*i)\n\t}\n\treturn cc\n}", "func (du *DeviceUpdate) SetNillableVersion(s *string) *DeviceUpdate {\n\tif s != nil {\n\t\tdu.SetVersion(*s)\n\t}\n\treturn du\n}", "func (du *DealUpdate) SetNillablePhone(s *string) *DealUpdate {\n\tif s != nil {\n\t\tdu.SetPhone(*s)\n\t}\n\treturn du\n}", "func (guo *GroupUpdateOne) SetNillableType(s *string) *GroupUpdateOne {\n\tif s != nil {\n\t\tguo.SetType(*s)\n\t}\n\treturn guo\n}", "func (gsu *GameServerUpdate) SetNillableCreatedWith(s *string) *GameServerUpdate {\n\tif s != nil {\n\t\tgsu.SetCreatedWith(*s)\n\t}\n\treturn gsu\n}", "func (au *AppUpdate) SetNillableVersion(s *string) *AppUpdate {\n\tif s != nil {\n\t\tau.SetVersion(*s)\n\t}\n\treturn au\n}", "func (rc *RentalCreate) SetNillableDate(t *time.Time) *RentalCreate {\n\tif t != nil {\n\t\trc.SetDate(*t)\n\t}\n\treturn rc\n}", "func (cc *ConstructionCreate) SetNillableProduction(f *float64) *ConstructionCreate {\n\tif f != nil {\n\t\tcc.SetProduction(*f)\n\t}\n\treturn cc\n}", "func (pu *PendingloanbindingUpdate) SetNillableDateTime(t *time.Time) *PendingloanbindingUpdate {\n\tif t != nil {\n\t\tpu.SetDateTime(*t)\n\t}\n\treturn pu\n}", "func (lc *LoanbindingCreate) SetNillableDateTime(t *time.Time) *LoanbindingCreate {\n\tif t != nil {\n\t\tlc.SetDateTime(*t)\n\t}\n\treturn lc\n}", "func (gau *GithubAssetUpdate) SetNillableLabel(s *string) *GithubAssetUpdate {\n\tif s != nil {\n\t\tgau.SetLabel(*s)\n\t}\n\treturn gau\n}", "func (nuo *NodeUpdateOne) SetNillableValue(i *int) *NodeUpdateOne {\n\tif i != nil {\n\t\tnuo.SetValue(*i)\n\t}\n\treturn nuo\n}", "func (duo *DeviceUpdateOne) SetNillableType(s *string) *DeviceUpdateOne {\n\tif s != nil {\n\t\tduo.SetType(*s)\n\t}\n\treturn duo\n}", "func (ac *AnswerCreate) SetNillableValid(b *bool) *AnswerCreate {\n\tif b != nil {\n\t\tac.SetValid(*b)\n\t}\n\treturn ac\n}", "func (duo *DeviceUpdateOne) SetNillableMobile(b *bool) *DeviceUpdateOne {\n\tif b != nil {\n\t\tduo.SetMobile(*b)\n\t}\n\treturn duo\n}", "func (auo *AppUpdateOne) SetNillableVersion(s *string) *AppUpdateOne {\n\tif s != nil {\n\t\tauo.SetVersion(*s)\n\t}\n\treturn auo\n}", "func (puo *PendingloanbindingUpdateOne) SetNillableDateTime(t *time.Time) *PendingloanbindingUpdateOne {\n\tif t != nil {\n\t\tpuo.SetDateTime(*t)\n\t}\n\treturn puo\n}", "func (su *StateUpdate) SetNillableCreatedWith(s *string) *StateUpdate {\n\tif s != nil {\n\t\tsu.SetCreatedWith(*s)\n\t}\n\treturn su\n}", "func (gu *GroupUpdate) SetNillableType(s *string) *GroupUpdate {\n\tif s != nil {\n\t\tgu.SetType(*s)\n\t}\n\treturn gu\n}", "func (pu *PostUpdate) SetNillablePin(i *int8) *PostUpdate {\n\tif i != nil {\n\t\tpu.SetPin(*i)\n\t}\n\treturn pu\n}", "func (suo *StateUpdateOne) SetNillableCreatedWith(s *string) *StateUpdateOne {\n\tif s != nil {\n\t\tsuo.SetCreatedWith(*s)\n\t}\n\treturn suo\n}", "func (puo *PostUpdateOne) SetNillablePublishedAt(t *time.Time) *PostUpdateOne {\n\tif t != nil {\n\t\tpuo.SetPublishedAt(*t)\n\t}\n\treturn puo\n}", "func (oupuo *OrgUnitPositionUpdateOne) SetNillableDuty(s *string) *OrgUnitPositionUpdateOne {\n\tif s != nil {\n\t\toupuo.SetDuty(*s)\n\t}\n\treturn oupuo\n}", "func (duo *DatumUpdateOne) SetNillableVersion(i *int) *DatumUpdateOne {\n\tif i != nil {\n\t\tduo.SetVersion(*i)\n\t}\n\treturn duo\n}", "func (gauo *GithubAssetUpdateOne) SetNillableLabel(s *string) *GithubAssetUpdateOne {\n\tif s != nil {\n\t\tgauo.SetLabel(*s)\n\t}\n\treturn gauo\n}", "func (ftuo *FieldTypeUpdateOne) SetNillableState(f *fieldtype.State) *FieldTypeUpdateOne {\n\tif f != nil {\n\t\tftuo.SetState(*f)\n\t}\n\treturn ftuo\n}", "func (guo *GroupUpdateOne) SetNillableActive(b *bool) *GroupUpdateOne {\n\tif b != nil {\n\t\tguo.SetActive(*b)\n\t}\n\treturn guo\n}", "func (wouo *WorkOrderUpdateOne) SetNillableTechnicianID(id *string) *WorkOrderUpdateOne {\n\tif id != nil {\n\t\twouo = wouo.SetTechnicianID(*id)\n\t}\n\treturn wouo\n}", "func (du *DatumUpdate) SetNillableVersion(i *int) *DatumUpdate {\n\tif i != nil {\n\t\tdu.SetVersion(*i)\n\t}\n\treturn du\n}", "func (gsuo *GameServerUpdateOne) SetNillableCreatedWith(s *string) *GameServerUpdateOne {\n\tif s != nil {\n\t\tgsuo.SetCreatedWith(*s)\n\t}\n\treturn gsuo\n}", "func (upu *UnsavedPostUpdate) SetNillableSlug(s *string) *UnsavedPostUpdate {\n\tif s != nil {\n\t\tupu.SetSlug(*s)\n\t}\n\treturn upu\n}", "func (upuo *UnsavedPostUpdateOne) SetNillableSlug(s *string) *UnsavedPostUpdateOne {\n\tif s != nil {\n\t\tupuo.SetSlug(*s)\n\t}\n\treturn upuo\n}", "func (uc *UserCreate) SetNillableCity(s *string) *UserCreate {\n\tif s != nil {\n\t\tuc.SetCity(*s)\n\t}\n\treturn uc\n}", "func (puo *PostUpdateOne) SetNillablePin(i *int8) *PostUpdateOne {\n\tif i != nil {\n\t\tpuo.SetPin(*i)\n\t}\n\treturn puo\n}", "func (cc *CustomerCreate) SetNillablePhone(s *string) *CustomerCreate {\n\tif s != nil {\n\t\tcc.SetPhone(*s)\n\t}\n\treturn cc\n}", "func (oupu *OrgUnitPositionUpdate) SetNillableDuty(s *string) *OrgUnitPositionUpdate {\n\tif s != nil {\n\t\toupu.SetDuty(*s)\n\t}\n\treturn oupu\n}", "func (upvc *UnsavedPostVideoCreate) SetNillableValidity(u *unsavedpostvideo.Validity) *UnsavedPostVideoCreate {\n\tif u != nil {\n\t\tupvc.SetValidity(*u)\n\t}\n\treturn upvc\n}", "func (nu *NodeUpdate) SetNillableValue(i *int) *NodeUpdate {\n\tif i != nil {\n\t\tnu.SetValue(*i)\n\t}\n\treturn nu\n}", "func (wou *WorkOrderUpdate) SetNillableTechnicianID(id *string) *WorkOrderUpdate {\n\tif id != nil {\n\t\twou = wou.SetTechnicianID(*id)\n\t}\n\treturn wou\n}", "func (du *DeviceUpdate) SetNillableType(s *string) *DeviceUpdate {\n\tif s != nil {\n\t\tdu.SetType(*s)\n\t}\n\treturn du\n}", "func (cc *CheckoutCreate) SetNillableRoomID(id *int) *CheckoutCreate {\n\tif id != nil {\n\t\tcc = cc.SetRoomID(*id)\n\t}\n\treturn cc\n}", "func (uc *UserCreate) SetNillableSlackID(s *string) *UserCreate {\n\tif s != nil {\n\t\tuc.SetSlackID(*s)\n\t}\n\treturn uc\n}", "func (puo *PendingloanbindingUpdateOne) SetNillableStatusGenLB(b *bool) *PendingloanbindingUpdateOne {\n\tif b != nil {\n\t\tpuo.SetStatusGenLB(*b)\n\t}\n\treturn puo\n}", "func (squo *SurveyQuestionUpdateOne) SetNillableDateData(t *time.Time) *SurveyQuestionUpdateOne {\n\tif t != nil {\n\t\tsquo.SetDateData(*t)\n\t}\n\treturn squo\n}", "func (du *DeviceUpdate) SetNillableMobile(b *bool) *DeviceUpdate {\n\tif b != nil {\n\t\tdu.SetMobile(*b)\n\t}\n\treturn du\n}", "func (puo *ProfileUpdateOne) SetNillableBirthDate(s *string) *ProfileUpdateOne {\n\tif s != nil {\n\t\tpuo.SetBirthDate(*s)\n\t}\n\treturn puo\n}", "func (uuo *UserUpdateOne) SetNillableSchool(s *string) *UserUpdateOne {\n\tif s != nil {\n\t\tuuo.SetSchool(*s)\n\t}\n\treturn uuo\n}", "func (pu *ProfileUpdate) SetNillableBirthDate(s *string) *ProfileUpdate {\n\tif s != nil {\n\t\tpu.SetBirthDate(*s)\n\t}\n\treturn pu\n}", "func (uuo *UserUpdateOne) SetNillableLevel(i *int) *UserUpdateOne {\n\tif i != nil {\n\t\tuuo.SetLevel(*i)\n\t}\n\treturn uuo\n}", "func (pu *PendingloanbindingUpdate) SetNillableStatusGenLB(b *bool) *PendingloanbindingUpdate {\n\tif b != nil {\n\t\tpu.SetStatusGenLB(*b)\n\t}\n\treturn pu\n}", "func (gsc *GameServerCreate) SetNillableCreatedWith(s *string) *GameServerCreate {\n\tif s != nil {\n\t\tgsc.SetCreatedWith(*s)\n\t}\n\treturn gsc\n}", "func (cc *CompanyCreate) SetNillableSize(c *company.Size) *CompanyCreate {\n\tif c != nil {\n\t\tcc.SetSize(*c)\n\t}\n\treturn cc\n}", "func (uc *UserCreate) SetNillablePhone(s *string) *UserCreate {\n\tif s != nil {\n\t\tuc.SetPhone(*s)\n\t}\n\treturn uc\n}", "func (uc *UserCreate) SetNillablePhone(s *string) *UserCreate {\n\tif s != nil {\n\t\tuc.SetPhone(*s)\n\t}\n\treturn uc\n}", "func (pu *PostUpdate) SetNillablePublishedAt(t *time.Time) *PostUpdate {\n\tif t != nil {\n\t\tpu.SetPublishedAt(*t)\n\t}\n\treturn pu\n}", "func (gc *GroupCreate) SetNillableType(s *string) *GroupCreate {\n\tif s != nil {\n\t\tgc.SetType(*s)\n\t}\n\treturn gc\n}", "func (upu *UnsavedPostUpdate) SetNillableAccessLevel(ul *unsavedpost.AccessLevel) *UnsavedPostUpdate {\n\tif ul != nil {\n\t\tupu.SetAccessLevel(*ul)\n\t}\n\treturn upu\n}", "func (fc *FeedCreate) SetNillablePrivacy(f *feed.Privacy) *FeedCreate {\n\tif f != nil {\n\t\tfc.SetPrivacy(*f)\n\t}\n\treturn fc\n}", "func (bc *BouncerCreate) SetNillableType(s *string) *BouncerCreate {\n\tif s != nil {\n\t\tbc.SetType(*s)\n\t}\n\treturn bc\n}", "func (squ *SurveyQuestionUpdate) SetNillableDateData(t *time.Time) *SurveyQuestionUpdate {\n\tif t != nil {\n\t\tsqu.SetDateData(*t)\n\t}\n\treturn squ\n}", "func (upuo *UnsavedPostUpdateOne) SetNillableAccessLevel(ul *unsavedpost.AccessLevel) *UnsavedPostUpdateOne {\n\tif ul != nil {\n\t\tupuo.SetAccessLevel(*ul)\n\t}\n\treturn upuo\n}", "func (tuo *TransactionfactorUpdateOne) SetNillableUpdateDate(t *time.Time) *TransactionfactorUpdateOne {\n\tif t != nil {\n\t\ttuo.SetUpdateDate(*t)\n\t}\n\treturn tuo\n}", "func (gsc *GameServerCreate) SetNillableUpdatedWith(s *string) *GameServerCreate {\n\tif s != nil {\n\t\tgsc.SetUpdatedWith(*s)\n\t}\n\treturn gsc\n}", "func (duo *DeviceUpdateOne) SetNillableManufacturer(s *string) *DeviceUpdateOne {\n\tif s != nil {\n\t\tduo.SetManufacturer(*s)\n\t}\n\treturn duo\n}", "func (uu *UserUpdate) SetNillableSchool(s *string) *UserUpdate {\n\tif s != nil {\n\t\tuu.SetSchool(*s)\n\t}\n\treturn uu\n}", "func (ftu *FieldTypeUpdate) SetNillableState(f *fieldtype.State) *FieldTypeUpdate {\n\tif f != nil {\n\t\tftu.SetState(*f)\n\t}\n\treturn ftu\n}", "func (uu *UserUpdate) SetNillableLevel(i *int) *UserUpdate {\n\tif i != nil {\n\t\tuu.SetLevel(*i)\n\t}\n\treturn uu\n}" ]
[ "0.8304011", "0.8224735", "0.5783829", "0.5779206", "0.5730435", "0.5600772", "0.55846643", "0.5577679", "0.55747837", "0.55399686", "0.5527202", "0.55259156", "0.5508183", "0.5485951", "0.5464295", "0.54510814", "0.5450909", "0.54472756", "0.5418234", "0.54154587", "0.5412246", "0.5408652", "0.53881", "0.53863424", "0.5386102", "0.5383548", "0.53777844", "0.53737974", "0.5364755", "0.5364513", "0.5358201", "0.5334849", "0.5327434", "0.5325757", "0.5322311", "0.5319872", "0.5318231", "0.53154224", "0.53082037", "0.53004664", "0.52881145", "0.52583003", "0.52513677", "0.5245663", "0.5236953", "0.52335674", "0.5230302", "0.52287817", "0.5225926", "0.52135", "0.51996815", "0.5198524", "0.5194792", "0.51914454", "0.518286", "0.5181635", "0.5180756", "0.51671803", "0.5160044", "0.5157266", "0.51564056", "0.51502436", "0.514879", "0.5139597", "0.5133382", "0.5133225", "0.5132814", "0.5132246", "0.5131512", "0.5127808", "0.5121289", "0.51171845", "0.5109104", "0.51055825", "0.50924164", "0.50790673", "0.5077857", "0.5076924", "0.5075104", "0.5069406", "0.50680035", "0.5062871", "0.506009", "0.5059524", "0.50580066", "0.5056593", "0.5056593", "0.5053434", "0.50467455", "0.50453293", "0.5039602", "0.5021546", "0.50209737", "0.50146854", "0.5006238", "0.49957734", "0.49903506", "0.49847063", "0.4983411", "0.4977624" ]
0.8159586
2
SetNamespace sets the namespace field.
func (ac *AppCreate) SetNamespace(s string) *AppCreate { ac.mutation.SetNamespace(s) return ac }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t *Tracker) SetNamespace(namespace string) {\n\tt.Namespace = namespace\n}", "func (o *SparseCloudSnapshotAccount) SetNamespace(namespace string) {\n\n\to.Namespace = &namespace\n}", "func (o *SparseClaims) SetNamespace(namespace string) {\n\n\to.Namespace = &namespace\n}", "func (o *GetModerationRulesParams) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (p *Pipeline) SetNamespace(namespace string) {\n\tp.Namespace = namespace\n}", "func (c *Client) SetNamespace(namespace string) {\n\tc.modifyLock.Lock()\n\tdefer c.modifyLock.Unlock()\n\tc.setNamespace(namespace)\n}", "func (o *ImportStore1Params) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *SparseSSHAuthorizationPolicy) SetNamespace(namespace string) {\n\n\to.Namespace = &namespace\n}", "func (auo *AppUpdateOne) SetNamespace(s string) *AppUpdateOne {\n\tauo.mutation.SetNamespace(s)\n\treturn auo\n}", "func (o *CloudSnapshotAccount) SetNamespace(namespace string) {\n\n\to.Namespace = namespace\n}", "func (o *GetItemByAppIDParams) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (au *AppUpdate) SetNamespace(s string) *AppUpdate {\n\tau.mutation.SetNamespace(s)\n\treturn au\n}", "func (c *Client) SetNamespace(namespace string) {\n\tc.config.Namespace = namespace\n}", "func (c *Current) SetNamespace(ns string) {\n\tcurr.namespace = ns\n}", "func (o *Claims) SetNamespace(namespace string) {\n\n\to.Namespace = namespace\n}", "func (o *SSHAuthorizationPolicy) SetNamespace(namespace string) {\n\n\to.Namespace = namespace\n}", "func (o *QueryEntitlementsParams) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *UpdateMemberRoleAdminV1Params) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *BulkEnableCodesParams) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *SparseTag) SetNamespace(namespace string) {\n\n\to.Namespace = &namespace\n}", "func (o *AdminSearchUserV3Params) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *Tag) SetNamespace(namespace string) {\n\n\to.Namespace = namespace\n}", "func (s *CustomizedMetricSpecification) SetNamespace(v string) *CustomizedMetricSpecification {\n\ts.Namespace = &v\n\treturn s\n}", "func (o *PublicPlatformLinkV3Params) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *ShowPackageParams) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *LastUserActivityTimeHandlerParams) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (s *RestoreFromSnapshotOutput) SetNamespace(v *Namespace) *RestoreFromSnapshotOutput {\n\ts.Namespace = v\n\treturn s\n}", "func (o *RevokeUserEntitlementsParams) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *UpdateSingleGroupPublicV1Params) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *PublicRemoveTrustedDeviceV4Params) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *AdminDeleteProfanityFilterParams) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *QueryUserExpGrantHistoryParams) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *InstanceStatusKubernetes) SetNamespace(v string) {\n\to.Namespace = &v\n}", "func (o *AdminGetBannedDevicesV4Params) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (s *RestoreFromRecoveryPointOutput) SetNamespace(v *Namespace) *RestoreFromRecoveryPointOutput {\n\ts.Namespace = v\n\treturn s\n}", "func (o *AdminSearchUsersV2Params) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *AdminCreateJusticeUserParams) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *GetRelationTuplesParams) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *TicketStatisticParams) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *DeleteGroupConfigurationAdminV1Params) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *DeleteUserMetaTagsParams) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *CheckTransactionCreditLimitParams) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (o *PublicWebLinkPlatformEstablishParams) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (s *SystemControl) SetNamespace(v string) *SystemControl {\n\ts.Namespace = &v\n\treturn s\n}", "func (s *ListComponentTypesFilter) SetNamespace(v string) *ListComponentTypesFilter {\n\ts.Namespace = &v\n\treturn s\n}", "func SetNamespace(iops *v1alpha1.IstioOperatorSpec, namespace string) {\n\tif namespace != \"\" {\n\t\tiops.Namespace = namespace\n\t}\n\tif iops.Values == nil {\n\t\tiops.Values = make(map[string]interface{})\n\t}\n\tif iops.Values[globalKey] == nil {\n\t\tiops.Values[globalKey] = make(map[string]interface{})\n\t}\n\tv := iops.Values[globalKey].(map[string]interface{})\n\tv[istioNamespaceKey] = namespace\n}", "func (s *ClusterServiceConnectDefaultsRequest) SetNamespace(v string) *ClusterServiceConnectDefaultsRequest {\n\ts.Namespace = &v\n\treturn s\n}", "func (ic *InstanceCreate) SetNamespace(n *Namespace) *InstanceCreate {\n\treturn ic.SetNamespaceID(n.ID)\n}", "func (s *ClusterServiceConnectDefaults) SetNamespace(v string) *ClusterServiceConnectDefaults {\n\ts.Namespace = &v\n\treturn s\n}", "func (s *GetNamespaceOutput) SetNamespace(v *Namespace) *GetNamespaceOutput {\n\ts.Namespace = v\n\treturn s\n}", "func (s *ServiceConnectConfiguration) SetNamespace(v string) *ServiceConnectConfiguration {\n\ts.Namespace = &v\n\treturn s\n}", "func (o *GetAdminUsersByRoleIDV3Params) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (s *DeleteNamespaceOutput) SetNamespace(v *Namespace) *DeleteNamespaceOutput {\n\ts.Namespace = v\n\treturn s\n}", "func (s *UpdateNamespaceOutput) SetNamespace(v *Namespace) *UpdateNamespaceOutput {\n\ts.Namespace = v\n\treturn s\n}", "func (s *CreateNamespaceOutput) SetNamespace(v *Namespace) *CreateNamespaceOutput {\n\ts.Namespace = v\n\treturn s\n}", "func (s *ListServicesByNamespaceInput) SetNamespace(v string) *ListServicesByNamespaceInput {\n\ts.Namespace = &v\n\treturn s\n}", "func (b *OperatorIAMRoleBuilder) Namespace(value string) *OperatorIAMRoleBuilder {\n\tb.namespace = value\n\tb.bitmap_ |= 2\n\treturn b\n}", "func (config *Config) SetNamespace() {\n\tif config.Namespace != \"\" {\n\t\tlog.Infof(\"setting namespace to %s\", config.Namespace)\n\t\tcmd := exec.Command(\n\t\t\t\"kubectl\", \"config\", \"set-context\", \"--current\",\n\t\t\t\"--namespace\", config.Namespace,\n\t\t)\n\t\tcmd.Stderr = os.Stderr\n\t\tif err := cmd.Run(); err != nil {\n\t\t\tpanic(fmt.Errorf(\"failed to set namespace\"))\n\t\t}\n\t} else {\n\t\tlog.Debugf(\"config has no namespace\")\n\t}\n}", "func (e *Encoder) SetNamespacePrefix(namespacePrefix string) {\n\te.namespacePrefix = namespacePrefix\n}", "func WithNamespace(namespace string) Opt {\n\treturn func(object client.Object) {\n\t\tobject.SetNamespace(namespace)\n\t}\n}", "func (m *MockDocumentHandler) WithNamespace(ns string) *MockDocumentHandler {\n\tm.namespace = ns\n\n\treturn m\n}", "func WithNamespace(namespace string) Option {\n\treturn func(meta metav1.Object) {\n\t\tmeta.SetNamespace(namespace)\n\t}\n}", "func WithNamespace(namespace string) Option {\n\treturn func(meta metav1.Object) {\n\t\tmeta.SetNamespace(namespace)\n\t}\n}", "func (r *RoleV2) SetNamespaces(namespaces []string) {\n\tr.Spec.Namespaces = namespaces\n}", "func (client *Client) SetNamespaceAccess(project, namespace, username string, access model.UserGroupAccess) error {\n\treturn client.RestAPI.Put(rest.Rq{\n\t\tBody: model.ResourceUpdateUserAccess{\n\t\t\tUsername: username,\n\t\t\tAccess: access,\n\t\t},\n\t\tURL: rest.URL{\n\t\t\tPath: namespaceAccessPath,\n\t\t\tParams: rest.P{\n\t\t\t\t\"namespace\": namespace,\n\t\t\t\t\"project\": project,\n\t\t\t},\n\t\t},\n\t})\n}", "func WithNamespace(namespace string) Option {\n\treturn func(o *options) {\n\t\to.namespace = namespace\n\t}\n}", "func (o *PutClientConfigV2NamespaceChangesParams) SetNamespaces(namespaces *models.ClientConfigConfigNamespaceUpdate) {\n\to.Namespaces = namespaces\n}", "func (b *Builder) WithNamespace(namespace string) *Builder {\n\tif len(namespace) == 0 {\n\t\tnamespace = \"default\"\n\t}\n\tb.pvc.object.Namespace = namespace\n\treturn b\n}", "func (c *Client) Namespace() *NamespaceCommand {\n\tcmd := &NamespaceCommand{}\n\tc.beginCommand(\"NAMESPACE\", cmd).end()\n\treturn cmd\n}", "func (c *Clientset) UpdateNamespace(namespace *corev1.Namespace) (*corev1.Namespace, error) {\n\treturn c.kubernetes.CoreV1().Namespaces().Update(namespace)\n}", "func (o *SearchIngredientsParams) SetNamespaces(namespaces *string) {\n\to.Namespaces = namespaces\n}", "func WithNamespace(name string) Option {\n\treturn func(o *options) {\n\t\to.namespace = name\n\t}\n}", "func (e *Encoder) SetNamespaceSuffix(namespaceSuffix string) {\n\te.namespaceSuffix = namespaceSuffix\n}", "func (ic *InstanceCreate) SetNamespaceID(id uuid.UUID) *InstanceCreate {\n\tic.mutation.SetNamespaceID(id)\n\treturn ic\n}", "func (c *configuration) Namespace(clientSet ClientSet) *Namespace {\n\tif clientSet != nil {\n\t\treturn NewNamespace(clientSet)\n\t}\n\treturn nil\n\n}", "func (o MfaPingidOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *MfaPingid) pulumi.StringPtrOutput { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (b *ImageStreamMappingApplyConfiguration) WithNamespace(value string) *ImageStreamMappingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = &value\n\treturn b\n}", "func WithNamespace(namespace state.Key) StateMappingOpt {\n\treturn func(sm *StateMapping, smm StateMappings) {\n\t\tsm.namespace = namespace\n\t}\n}", "func WithNamespace(namespace string) Option {\n\treturn weightedOptionFunc(1, func(c *config) error {\n\t\tc.namespace = namespace\n\t\treturn nil\n\t})\n}", "func (c *Client) WithNamespace(namespace string) *Client {\n\tc2 := *c\n\tc2.modifyLock = sync.RWMutex{}\n\tc2.headers = c.Headers()\n\tif namespace == \"\" {\n\t\tc2.ClearNamespace()\n\t} else {\n\t\tc2.SetNamespace(namespace)\n\t}\n\treturn &c2\n}", "func (qb QueryBuilder) WithNamespace(namespace string) QueryBuilder {\n\tqb.namespace = namespace\n\treturn qb\n}", "func (o ForwardingRuleServiceDirectoryRegistrationResponseOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ForwardingRuleServiceDirectoryRegistrationResponse) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (p *TProgram) SetNamespaceWithLang(language string, name_space string) {\n\tp.Namespace_ = name_space\n\tp.Language_ = language\n}", "func (c *Client) Namespace() string {\n\treturn \"testNamespace\"\n}", "func WithNamespace(namespace string) BuilderOptionFunc {\n\treturn func(b *Builder) error {\n\t\tb.namespace = namespace\n\t\treturn nil\n\t}\n}", "func (m *MockDocumentHandler) Namespace() string {\n\treturn m.namespace\n}", "func (o FluxConfigurationOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FluxConfiguration) pulumi.StringOutput { return v.Namespace }).(pulumi.StringOutput)\n}", "func (o AppV2Output) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AppV2) pulumi.StringOutput { return v.Namespace }).(pulumi.StringOutput)\n}", "func (m *ModelClient) Namespace(namespace string) *ModelClient {\n\tcopyModelJobClient := &ModelClient{\n\t\tnamespace: namespace,\n\t\tconfiger: m.configer,\n\t}\n\treturn copyModelJobClient\n}", "func OptionNamespace(namespace string) func(t *Tracker) {\n\treturn func(t *Tracker) { t.Namespace = namespace }\n}", "func (this *KeyspaceTerm) SetDefaultNamespace(namespace string) {\n\tif this.path != nil {\n\t\tthis.path.SetDefaultNamespace(namespace)\n\t}\n}", "func setNamespace(nnms []string, item *yaml.RNode, meta yaml.ResourceMeta) error {\n\t// The namespace to set is the leaf namespace (the last element of the namespaces slice)\n\tnnm := nnms[len(nnms)-1]\n\n\tif meta.APIVersion == \"v1\" && meta.Kind == \"Namespace\" {\n\t\t// don't set the namespace field on the namespace object. However, do validate that the names\n\t\t// match!\n\t\tif meta.Name != nnm {\n\t\t\treturn fmt.Errorf(\"namespace directory %q contains namespace config for %q\", nnm, meta.Name)\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn item.PipeE(yaml.SetK8sNamespace(nnm))\n}", "func WithNamespace(namespace string) MetadataOption {\n\treturn &metadataNamespaceOption{\n\t\tnamespace: namespace,\n\t}\n}", "func (o ParamRefPatchOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ParamRefPatch) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o ApplicationStatusServicesScopesOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusServicesScopes) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o *PostApplyManifestParams) SetTillerNamespace(tillerNamespace *string) {\n\to.TillerNamespace = tillerNamespace\n}", "func SetDefaults_Namespace(obj *v1.Namespace) {\n\t// we can't SetDefaults for nameless namespaces (generateName).\n\t// This code needs to be kept in sync with the implementation that exists\n\t// in Namespace Canonicalize strategy (pkg/registry/core/namespace)\n\n\t// note that this can result in many calls to feature enablement in some cases, but\n\t// we assume that there's no real cost there.\n\tif len(obj.Name) > 0 {\n\t\tif obj.Labels == nil {\n\t\t\tobj.Labels = map[string]string{}\n\t\t}\n\t\tobj.Labels[v1.LabelMetadataName] = obj.Name\n\t}\n}", "func SetNamespaces(namespaces []string) UpdateSettingsFunc {\n\treturn func(cache *clusterCache) {\n\t\tif !reflect.DeepEqual(cache.namespaces, namespaces) {\n\t\t\tlog.WithField(\"server\", cache.config.Host).Infof(\"Changing cluster namespaces to: %v\", namespaces)\n\t\t\tcache.namespaces = namespaces\n\t\t}\n\t}\n}", "func (o ForwardingRuleServiceDirectoryRegistrationOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ForwardingRuleServiceDirectoryRegistration) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (m Metadata) Namespace() string {\n\tif !m.HasNamespace() {\n\t\treturn \"\"\n\t}\n\treturn m[\"namespace\"].(string)\n}" ]
[ "0.8266545", "0.82182395", "0.81653154", "0.8156894", "0.8152071", "0.8144666", "0.81119764", "0.80577594", "0.80455834", "0.8020759", "0.79911023", "0.7982452", "0.79671055", "0.7964713", "0.79346156", "0.78891546", "0.78879726", "0.7821699", "0.7776216", "0.77732295", "0.77370936", "0.7730363", "0.77292883", "0.7715237", "0.77149165", "0.7694255", "0.7686989", "0.76793414", "0.7675963", "0.7661578", "0.7644443", "0.76295704", "0.76188123", "0.7609423", "0.76039463", "0.7598591", "0.7590069", "0.7573777", "0.75293046", "0.74728036", "0.7466948", "0.74489087", "0.74327147", "0.73830074", "0.73053426", "0.72951895", "0.7236069", "0.7229743", "0.72293305", "0.714864", "0.7090217", "0.7057133", "0.69448817", "0.69090277", "0.68981695", "0.6873085", "0.6820776", "0.6732047", "0.6587554", "0.6577886", "0.6465581", "0.64068663", "0.64068663", "0.6242925", "0.6133173", "0.6114776", "0.6109122", "0.6091806", "0.6053993", "0.60417074", "0.60385364", "0.6032145", "0.6001532", "0.5982169", "0.5973576", "0.58717245", "0.58661664", "0.58465534", "0.5824655", "0.582465", "0.5802547", "0.57997984", "0.5758244", "0.57456994", "0.57426137", "0.57344353", "0.5727056", "0.5715201", "0.5711529", "0.5709358", "0.5704954", "0.5698276", "0.5686797", "0.5673884", "0.56547284", "0.5649589", "0.5647321", "0.5614171", "0.5601342", "0.5597183" ]
0.8061413
7
SetNillableNamespace sets the namespace field if the given value is not nil.
func (ac *AppCreate) SetNillableNamespace(s *string) *AppCreate { if s != nil { ac.SetNamespace(*s) } return ac }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (auo *AppUpdateOne) SetNillableNamespace(s *string) *AppUpdateOne {\n\tif s != nil {\n\t\tauo.SetNamespace(*s)\n\t}\n\treturn auo\n}", "func (au *AppUpdate) SetNillableNamespace(s *string) *AppUpdate {\n\tif s != nil {\n\t\tau.SetNamespace(*s)\n\t}\n\treturn au\n}", "func (gau *GithubAssetUpdate) SetNillableLabel(s *string) *GithubAssetUpdate {\n\tif s != nil {\n\t\tgau.SetLabel(*s)\n\t}\n\treturn gau\n}", "func (gauo *GithubAssetUpdateOne) SetNillableLabel(s *string) *GithubAssetUpdateOne {\n\tif s != nil {\n\t\tgauo.SetLabel(*s)\n\t}\n\treturn gauo\n}", "func (scsu *SurveyCellScanUpdate) SetNillableNetworkID(s *string) *SurveyCellScanUpdate {\n\tif s != nil {\n\t\tscsu.SetNetworkID(*s)\n\t}\n\treturn scsu\n}", "func (scsuo *SurveyCellScanUpdateOne) SetNillableNetworkID(s *string) *SurveyCellScanUpdateOne {\n\tif s != nil {\n\t\tscsuo.SetNetworkID(*s)\n\t}\n\treturn scsuo\n}", "func (scsu *SurveyCellScanUpdate) SetNillableUarfcn(i *int) *SurveyCellScanUpdate {\n\tif i != nil {\n\t\tscsu.SetUarfcn(*i)\n\t}\n\treturn scsu\n}", "func (fc *FileCreate) SetNillableAnnotation(s *string) *FileCreate {\n\tif s != nil {\n\t\tfc.SetAnnotation(*s)\n\t}\n\treturn fc\n}", "func (wou *WorkOrderUpdate) SetNillableStatus(s *string) *WorkOrderUpdate {\n\tif s != nil {\n\t\twou.SetStatus(*s)\n\t}\n\treturn wou\n}", "func (scsuo *SurveyCellScanUpdateOne) SetNillableUarfcn(i *int) *SurveyCellScanUpdateOne {\n\tif i != nil {\n\t\tscsuo.SetUarfcn(*i)\n\t}\n\treturn scsuo\n}", "func (pc *PetCreate) SetNillableNickname(s *string) *PetCreate {\n\tif s != nil {\n\t\tpc.SetNickname(*s)\n\t}\n\treturn pc\n}", "func (fc *FeedCreate) SetNillablePrivacy(f *feed.Privacy) *FeedCreate {\n\tif f != nil {\n\t\tfc.SetPrivacy(*f)\n\t}\n\treturn fc\n}", "func (au *AntenatalinformationUpdate) SetNillablePregnancystatusID(id *int) *AntenatalinformationUpdate {\n\tif id != nil {\n\t\tau = au.SetPregnancystatusID(*id)\n\t}\n\treturn au\n}", "func (wouo *WorkOrderUpdateOne) SetNillableStatus(s *string) *WorkOrderUpdateOne {\n\tif s != nil {\n\t\twouo.SetStatus(*s)\n\t}\n\treturn wouo\n}", "func (squo *SurveyQuestionUpdateOne) SetNillableLongitude(f *float64) *SurveyQuestionUpdateOne {\n\tif f != nil {\n\t\tsquo.SetLongitude(*f)\n\t}\n\treturn squo\n}", "func (sou *SubjectsOfferedUpdate) SetNillableYearID(id *int) *SubjectsOfferedUpdate {\n\tif id != nil {\n\t\tsou = sou.SetYearID(*id)\n\t}\n\treturn sou\n}", "func (pu *PendingloanbindingUpdate) SetNillableNameLB(s *string) *PendingloanbindingUpdate {\n\tif s != nil {\n\t\tpu.SetNameLB(*s)\n\t}\n\treturn pu\n}", "func (o *SignalPersonName) SetPrefixNil() {\n\to.Prefix.Set(nil)\n}", "func SetNsNodeSelectorConfigMapNil() {\n\tnsNodeSelectorConfigMap = nil\n\tnsNodeSelectorConfigMapUpdateTime = time.Date(2017, 1, 1, 1, 1, 1, 1, time.UTC)\n}", "func (squ *SurveyQuestionUpdate) SetNillableLongitude(f *float64) *SurveyQuestionUpdate {\n\tif f != nil {\n\t\tsqu.SetLongitude(*f)\n\t}\n\treturn squ\n}", "func (ac *AnswerCreate) SetNillableValid(b *bool) *AnswerCreate {\n\tif b != nil {\n\t\tac.SetValid(*b)\n\t}\n\treturn ac\n}", "func (squ *SurveyQuestionUpdate) SetNillableQuestionFormat(s *string) *SurveyQuestionUpdate {\n\tif s != nil {\n\t\tsqu.SetQuestionFormat(*s)\n\t}\n\treturn squ\n}", "func (pu *PendingloanbindingUpdate) SetNillableCAWalletID(s *string) *PendingloanbindingUpdate {\n\tif s != nil {\n\t\tpu.SetCAWalletID(*s)\n\t}\n\treturn pu\n}", "func (fc *FileCreate) SetNillableCategory(s *string) *FileCreate {\n\tif s != nil {\n\t\tfc.SetCategory(*s)\n\t}\n\treturn fc\n}", "func (ugu *UsersGroupUpdate) SetNillableStatus(u *usersgroup.Status) *UsersGroupUpdate {\n\tif u != nil {\n\t\tugu.SetStatus(*u)\n\t}\n\treturn ugu\n}", "func (ggc *GithubGistCreate) SetNillableLanguage(s *string) *GithubGistCreate {\n\tif s != nil {\n\t\tggc.SetLanguage(*s)\n\t}\n\treturn ggc\n}", "func (ugu *UsersGroupUpdate) SetNillableDescription(s *string) *UsersGroupUpdate {\n\tif s != nil {\n\t\tugu.SetDescription(*s)\n\t}\n\treturn ugu\n}", "func (ac *ActivityCreate) SetNillableActiYearID(id *int) *ActivityCreate {\n\tif id != nil {\n\t\tac = ac.SetActiYearID(*id)\n\t}\n\treturn ac\n}", "func (vc *VehicleCreate) SetNillableStyle(s *string) *VehicleCreate {\n\tif s != nil {\n\t\tvc.SetStyle(*s)\n\t}\n\treturn vc\n}", "func (auo *AntenatalinformationUpdateOne) SetNillablePregnancystatusID(id *int) *AntenatalinformationUpdateOne {\n\tif id != nil {\n\t\tauo = auo.SetPregnancystatusID(*id)\n\t}\n\treturn auo\n}", "func (souo *SubjectsOfferedUpdateOne) SetNillableYearID(id *int) *SubjectsOfferedUpdateOne {\n\tif id != nil {\n\t\tsouo = souo.SetYearID(*id)\n\t}\n\treturn souo\n}", "func (puo *PendingloanbindingUpdateOne) SetNillableCAWalletID(s *string) *PendingloanbindingUpdateOne {\n\tif s != nil {\n\t\tpuo.SetCAWalletID(*s)\n\t}\n\treturn puo\n}", "func (fu *FriendshipUpdate) SetNillableWeight(i *int) *FriendshipUpdate {\n\tif i != nil {\n\t\tfu.SetWeight(*i)\n\t}\n\treturn fu\n}", "func (wou *WorkOrderUpdate) SetNillableProjectID(id *string) *WorkOrderUpdate {\n\tif id != nil {\n\t\twou = wou.SetProjectID(*id)\n\t}\n\treturn wou\n}", "func (lc *LoanbindingCreate) SetNillableStatus(s *string) *LoanbindingCreate {\n\tif s != nil {\n\t\tlc.SetStatus(*s)\n\t}\n\treturn lc\n}", "func (uu *UserUpdate) SetNillableRole(u *user.Role) *UserUpdate {\n\tif u != nil {\n\t\tuu.SetRole(*u)\n\t}\n\treturn uu\n}", "func (fc *FeedCreate) SetNillableTranscript(s *string) *FeedCreate {\n\tif s != nil {\n\t\tfc.SetTranscript(*s)\n\t}\n\treturn fc\n}", "func (oiu *OrderInfoUpdate) SetNillableStatus(i *int8) *OrderInfoUpdate {\n\tif i != nil {\n\t\toiu.SetStatus(*i)\n\t}\n\treturn oiu\n}", "func (scsu *SurveyCellScanUpdate) SetNillableLongitude(f *float64) *SurveyCellScanUpdate {\n\tif f != nil {\n\t\tscsu.SetLongitude(*f)\n\t}\n\treturn scsu\n}", "func (gu *GroupUpdate) SetNillableType(s *string) *GroupUpdate {\n\tif s != nil {\n\t\tgu.SetType(*s)\n\t}\n\treturn gu\n}", "func (puo *PendingloanbindingUpdateOne) SetNillableNameLB(s *string) *PendingloanbindingUpdateOne {\n\tif s != nil {\n\t\tpuo.SetNameLB(*s)\n\t}\n\treturn puo\n}", "func (guo *GroupUpdateOne) SetNillableActive(b *bool) *GroupUpdateOne {\n\tif b != nil {\n\t\tguo.SetActive(*b)\n\t}\n\treturn guo\n}", "func (fc *FeedCreate) SetNillableCaption(s *string) *FeedCreate {\n\tif s != nil {\n\t\tfc.SetCaption(*s)\n\t}\n\treturn fc\n}", "func (tu *TransactionfactorUpdate) SetNillablePaymentChannel(s *string) *TransactionfactorUpdate {\n\tif s != nil {\n\t\ttu.SetPaymentChannel(*s)\n\t}\n\treturn tu\n}", "func (scsuo *SurveyCellScanUpdateOne) SetNillableLongitude(f *float64) *SurveyCellScanUpdateOne {\n\tif f != nil {\n\t\tscsuo.SetLongitude(*f)\n\t}\n\treturn scsuo\n}", "func (o *GetModerationRulesParams) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (squo *SurveyQuestionUpdateOne) SetNillableQuestionFormat(s *string) *SurveyQuestionUpdateOne {\n\tif s != nil {\n\t\tsquo.SetQuestionFormat(*s)\n\t}\n\treturn squo\n}", "func (ftu *FieldTypeUpdate) SetNillableNillableInt64(i *int64) *FieldTypeUpdate {\n\tif i != nil {\n\t\tftu.SetNillableInt64(*i)\n\t}\n\treturn ftu\n}", "func (pu *PendingloanbindingUpdate) SetNillableWalletID(s *string) *PendingloanbindingUpdate {\n\tif s != nil {\n\t\tpu.SetWalletID(*s)\n\t}\n\treturn pu\n}", "func (guo *GroupUpdateOne) SetNillableType(s *string) *GroupUpdateOne {\n\tif s != nil {\n\t\tguo.SetType(*s)\n\t}\n\treturn guo\n}", "func (fuo *FriendshipUpdateOne) SetNillableWeight(i *int) *FriendshipUpdateOne {\n\tif i != nil {\n\t\tfuo.SetWeight(*i)\n\t}\n\treturn fuo\n}", "func (oiuo *OrderInfoUpdateOne) SetNillableStatus(i *int8) *OrderInfoUpdateOne {\n\tif i != nil {\n\t\toiuo.SetStatus(*i)\n\t}\n\treturn oiuo\n}", "func (wou *WorkOrderUpdate) SetNillablePriority(s *string) *WorkOrderUpdate {\n\tif s != nil {\n\t\twou.SetPriority(*s)\n\t}\n\treturn wou\n}", "func (gauo *GithubAssetUpdateOne) SetNillableState(s *string) *GithubAssetUpdateOne {\n\tif s != nil {\n\t\tgauo.SetState(*s)\n\t}\n\treturn gauo\n}", "func (du *DealUpdate) SetNillableUID(i *int64) *DealUpdate {\n\tif i != nil {\n\t\tdu.SetUID(*i)\n\t}\n\treturn du\n}", "func (gau *GithubAssetUpdate) SetNillableState(s *string) *GithubAssetUpdate {\n\tif s != nil {\n\t\tgau.SetState(*s)\n\t}\n\treturn gau\n}", "func (vuu *VacUserUpdate) SetNillablePartition(s *string) *VacUserUpdate {\n\tif s != nil {\n\t\tvuu.SetPartition(*s)\n\t}\n\treturn vuu\n}", "func (squo *SurveyQuestionUpdateOne) SetNillableLatitude(f *float64) *SurveyQuestionUpdateOne {\n\tif f != nil {\n\t\tsquo.SetLatitude(*f)\n\t}\n\treturn squo\n}", "func (gu *GroupUpdate) SetNillableActive(b *bool) *GroupUpdate {\n\tif b != nil {\n\t\tgu.SetActive(*b)\n\t}\n\treturn gu\n}", "func (scsu *SurveyCellScanUpdate) SetNillableArfcn(i *int) *SurveyCellScanUpdate {\n\tif i != nil {\n\t\tscsu.SetArfcn(*i)\n\t}\n\treturn scsu\n}", "func (wou *WorkOrderUpdate) SetNillableDescription(s *string) *WorkOrderUpdate {\n\tif s != nil {\n\t\twou.SetDescription(*s)\n\t}\n\treturn wou\n}", "func (scsuo *SurveyCellScanUpdateOne) SetNillableArfcn(i *int) *SurveyCellScanUpdateOne {\n\tif i != nil {\n\t\tscsuo.SetArfcn(*i)\n\t}\n\treturn scsuo\n}", "func (o *SparseClaims) SetNamespace(namespace string) {\n\n\to.Namespace = &namespace\n}", "func (rec *RawEventCreate) SetNillableSessionID(s *string) *RawEventCreate {\n\tif s != nil {\n\t\trec.SetSessionID(*s)\n\t}\n\treturn rec\n}", "func (wouo *WorkOrderUpdateOne) SetNillableProjectID(id *string) *WorkOrderUpdateOne {\n\tif id != nil {\n\t\twouo = wouo.SetProjectID(*id)\n\t}\n\treturn wouo\n}", "func (uguo *UsersGroupUpdateOne) SetNillableStatus(u *usersgroup.Status) *UsersGroupUpdateOne {\n\tif u != nil {\n\t\tuguo.SetStatus(*u)\n\t}\n\treturn uguo\n}", "func (cc *ClusterContext) LabelNamespace(label string, value string) (err error) {\n\n\tpayload := fmt.Sprintf(`{\"metadata\": {\"labels\": {\"%v\": \"%v\"}}}`, label, value)\n\n\t_, err = cc.VanClient.KubeClient.CoreV1().Namespaces().Patch(context.TODO(), cc.Namespace, types.MergePatchType, []byte(payload), metav1.PatchOptions{})\n\n\treturn\n}", "func (ftuo *FieldTypeUpdateOne) SetNillableNillableInt64(i *int64) *FieldTypeUpdateOne {\n\tif i != nil {\n\t\tftuo.SetNillableInt64(*i)\n\t}\n\treturn ftuo\n}", "func (o *PublicPlatformLinkV3Params) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (oupu *OrgUnitPositionUpdate) SetNillableDuty(s *string) *OrgUnitPositionUpdate {\n\tif s != nil {\n\t\toupu.SetDuty(*s)\n\t}\n\treturn oupu\n}", "func (bu *BookingUpdate) SetNillableUsingID(id *int) *BookingUpdate {\n\tif id != nil {\n\t\tbu = bu.SetUsingID(*id)\n\t}\n\treturn bu\n}", "func (duo *DealUpdateOne) SetNillableUID(i *int64) *DealUpdateOne {\n\tif i != nil {\n\t\tduo.SetUID(*i)\n\t}\n\treturn duo\n}", "func (o *SparseCloudSnapshotAccount) SetNamespace(namespace string) {\n\n\to.Namespace = &namespace\n}", "func (puo *PendingloanbindingUpdateOne) SetNillableWalletID(s *string) *PendingloanbindingUpdateOne {\n\tif s != nil {\n\t\tpuo.SetWalletID(*s)\n\t}\n\treturn puo\n}", "func (sc *SourceCreate) SetNillableLanguage(s *source.Language) *SourceCreate {\n\tif s != nil {\n\t\tsc.SetLanguage(*s)\n\t}\n\treturn sc\n}", "func (sou *SubjectsOfferedUpdate) SetNillableTermID(id *int) *SubjectsOfferedUpdate {\n\tif id != nil {\n\t\tsou = sou.SetTermID(*id)\n\t}\n\treturn sou\n}", "func (vuuo *VacUserUpdateOne) SetNillablePartition(s *string) *VacUserUpdateOne {\n\tif s != nil {\n\t\tvuuo.SetPartition(*s)\n\t}\n\treturn vuuo\n}", "func (uc *UserCreate) SetNillableRole(i *int) *UserCreate {\n\tif i != nil {\n\t\tuc.SetRole(*i)\n\t}\n\treturn uc\n}", "func (uc *UserCreate) SetNillableRole(i *int) *UserCreate {\n\tif i != nil {\n\t\tuc.SetRole(*i)\n\t}\n\treturn uc\n}", "func (ac *AreahistoryCreate) SetNillableRankArea(i *int) *AreahistoryCreate {\n\tif i != nil {\n\t\tac.SetRankArea(*i)\n\t}\n\treturn ac\n}", "func (squ *SurveyQuestionUpdate) SetNillableLatitude(f *float64) *SurveyQuestionUpdate {\n\tif f != nil {\n\t\tsqu.SetLatitude(*f)\n\t}\n\treturn squ\n}", "func (luo *LocationUpdateOne) SetNillableLongitude(f *float64) *LocationUpdateOne {\n\tif f != nil {\n\t\tluo.SetLongitude(*f)\n\t}\n\treturn luo\n}", "func (uguo *UsersGroupUpdateOne) SetNillableDescription(s *string) *UsersGroupUpdateOne {\n\tif s != nil {\n\t\tuguo.SetDescription(*s)\n\t}\n\treturn uguo\n}", "func (nuo *NodeUpdateOne) SetNillableValue(i *int) *NodeUpdateOne {\n\tif i != nil {\n\t\tnuo.SetValue(*i)\n\t}\n\treturn nuo\n}", "func (au *ArticleUpdate) SetNillableIsAvailable(b *bool) *ArticleUpdate {\n\tif b != nil {\n\t\tau.SetIsAvailable(*b)\n\t}\n\treturn au\n}", "func (upu *UnsavedPostUpdate) SetNillableSlug(s *string) *UnsavedPostUpdate {\n\tif s != nil {\n\t\tupu.SetSlug(*s)\n\t}\n\treturn upu\n}", "func (wouo *WorkOrderUpdateOne) SetNillablePriority(s *string) *WorkOrderUpdateOne {\n\tif s != nil {\n\t\twouo.SetPriority(*s)\n\t}\n\treturn wouo\n}", "func (duo *DeviceUpdateOne) SetNillableTablet(b *bool) *DeviceUpdateOne {\n\tif b != nil {\n\t\tduo.SetTablet(*b)\n\t}\n\treturn duo\n}", "func (o *AdminCreateJusticeUserParams) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (uuo *UserUpdateOne) SetNillableRole(u *user.Role) *UserUpdateOne {\n\tif u != nil {\n\t\tuuo.SetRole(*u)\n\t}\n\treturn uuo\n}", "func (pu *PendingloanbindingUpdate) SetNillablePointLB(i *int) *PendingloanbindingUpdate {\n\tif i != nil {\n\t\tpu.SetPointLB(*i)\n\t}\n\treturn pu\n}", "func (ftu *FieldTypeUpdate) SetNillableInt64(i int64) *FieldTypeUpdate {\n\tftu.nillable_int64 = &i\n\tftu.addnillable_int64 = nil\n\treturn ftu\n}", "func (wou *WorkOrderUpdate) SetNillableLocationID(id *string) *WorkOrderUpdate {\n\tif id != nil {\n\t\twou = wou.SetLocationID(*id)\n\t}\n\treturn wou\n}", "func (tc *TokenCreate) SetNillablePermissions(t *token.Permissions) *TokenCreate {\n\tif t != nil {\n\t\ttc.SetPermissions(*t)\n\t}\n\treturn tc\n}", "func (uu *UserUpdate) SetNillableJobpositionID(id *int) *UserUpdate {\n\tif id != nil {\n\t\tuu = uu.SetJobpositionID(*id)\n\t}\n\treturn uu\n}", "func (o *PublicRemoveTrustedDeviceV4Params) SetNamespace(namespace string) {\n\to.Namespace = namespace\n}", "func (upuo *UnsavedPostUpdateOne) SetNillableSlug(s *string) *UnsavedPostUpdateOne {\n\tif s != nil {\n\t\tupuo.SetSlug(*s)\n\t}\n\treturn upuo\n}", "func (du *DeviceUpdate) SetNillableType(s *string) *DeviceUpdate {\n\tif s != nil {\n\t\tdu.SetType(*s)\n\t}\n\treturn du\n}", "func (ac *ActivityCreate) SetNillableActiTermID(id *int) *ActivityCreate {\n\tif id != nil {\n\t\tac = ac.SetActiTermID(*id)\n\t}\n\treturn ac\n}", "func (wouo *WorkOrderUpdateOne) SetNillableDescription(s *string) *WorkOrderUpdateOne {\n\tif s != nil {\n\t\twouo.SetDescription(*s)\n\t}\n\treturn wouo\n}" ]
[ "0.83842903", "0.838323", "0.6178913", "0.602143", "0.5942123", "0.5861777", "0.5855511", "0.58375657", "0.5750382", "0.57123023", "0.5694858", "0.567392", "0.5647735", "0.56414014", "0.5624071", "0.5614129", "0.56009907", "0.55871195", "0.5582391", "0.5577921", "0.55773294", "0.5570444", "0.5564511", "0.55558795", "0.5542744", "0.5531298", "0.55285645", "0.5521076", "0.55188304", "0.55061466", "0.5502345", "0.55000347", "0.54988694", "0.54924285", "0.5485691", "0.54849494", "0.5484271", "0.54811406", "0.5477223", "0.54714125", "0.54611707", "0.5458052", "0.5455504", "0.5440923", "0.54408085", "0.54385924", "0.543537", "0.54352075", "0.54348403", "0.54343605", "0.54321426", "0.5427603", "0.54265183", "0.542387", "0.5419011", "0.54189944", "0.54148996", "0.5410199", "0.54077363", "0.54070044", "0.5399369", "0.5388964", "0.5388852", "0.5387702", "0.5381284", "0.53790176", "0.53736955", "0.5372336", "0.5369613", "0.53684044", "0.53665894", "0.5366413", "0.5364365", "0.53558755", "0.5355812", "0.5355527", "0.53475505", "0.5330799", "0.5330799", "0.53306675", "0.53297085", "0.5321038", "0.5319043", "0.5308966", "0.53049064", "0.530303", "0.53005207", "0.52989316", "0.529868", "0.52960855", "0.52952933", "0.52929634", "0.52912253", "0.5289958", "0.5289257", "0.52879804", "0.5287862", "0.5287764", "0.5285249", "0.5278812" ]
0.8311508
2
SetProperties sets the properties field.
func (ac *AppCreate) SetProperties(m map[string]interface{}) *AppCreate { ac.mutation.SetProperties(m) return ac }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Rietveld) SetProperties(issue, lastPatchset int64, props map[string]string) error {\n\tdata := url.Values{}\n\tfor k, v := range props {\n\t\tdata.Add(k, v)\n\t}\n\tdata.Add(\"last_patchset\", fmt.Sprintf(\"%d\", lastPatchset))\n\treturn r.post(fmt.Sprintf(\"/%d/edit_flags\", issue), data)\n}", "func (m *Schema) SetProperties(value []Propertyable)() {\n m.properties = value\n}", "func (m *Set) SetProperties(value []iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.KeyValueable)() {\n err := m.GetBackingStore().Set(\"properties\", value)\n if err != nil {\n panic(err)\n }\n}", "func (option *Mount) SetProperties(value map[string]string) {\n\toption.Properties = value\n}", "func (c *vertexCollection) SetProperties(ctx context.Context, options SetCollectionPropertiesOptions) error {\n\tif err := c.rawCollection().SetProperties(ctx, options); err != nil {\n\t\treturn WithStack(err)\n\t}\n\treturn nil\n}", "func (m *WebPartData) SetProperties(value Jsonable)() {\n err := m.GetBackingStore().Set(\"properties\", value)\n if err != nil {\n panic(err)\n }\n}", "func (o *CostEstimate) SetProperties(m map[string]interface{}) {\n\to.additionalProperties = make(map[string]interface{})\n\tfor k, v := range m {\n\t\to.additionalProperties[k] = v\n\t}\n}", "func (m *SchemaExtension) SetProperties(value []ExtensionSchemaPropertyable)() {\n err := m.GetBackingStore().Set(\"properties\", value)\n if err != nil {\n panic(err)\n }\n}", "func (o *NotificationCreate) SetProperties(m map[string]interface{}) {\n\to.additionalProperties = make(map[string]interface{})\n\tfor k, v := range m {\n\t\to.additionalProperties[k] = v\n\t}\n}", "func (o *TenantExternalView) SetProperties(v map[string]string) {\n\to.Properties = &v\n}", "func (du *DeviceUpdate) SetProperties(m map[string]interface{}) *DeviceUpdate {\n\tdu.mutation.SetProperties(m)\n\treturn du\n}", "func (o *Subscription) SetProperties(m map[string]interface{}) {\n\to.additionalProperties = make(map[string]interface{})\n\tfor k, v := range m {\n\t\to.additionalProperties[k] = v\n\t}\n}", "func (au *AppUpdate) SetProperties(m map[string]interface{}) *AppUpdate {\n\tau.mutation.SetProperties(m)\n\treturn au\n}", "func (o *VersionedControllerService) SetProperties(v map[string]string) {\n\to.Properties = &v\n}", "func (auo *AppUpdateOne) SetProperties(m map[string]interface{}) *AppUpdateOne {\n\tauo.mutation.SetProperties(m)\n\treturn auo\n}", "func (o *TenantWithOfferWeb) SetProperties(v map[string]string) {\n\to.Properties = &v\n}", "func (duo *DeviceUpdateOne) SetProperties(m map[string]interface{}) *DeviceUpdateOne {\n\tduo.mutation.SetProperties(m)\n\treturn duo\n}", "func (level *Level) SetProperties(properties model.LevelProperties) {\n\t{\n\t\tinfoStore := level.store.Get(res.ResourceID(4000 + level.id*100 + 4))\n\t\tinfoData := infoStore.BlockData(0)\n\t\tinfoReader := bytes.NewReader(infoData)\n\t\tinfoWriter := bytes.NewBuffer(nil)\n\t\tvar info data.LevelInformation\n\n\t\tbinary.Read(infoReader, binary.LittleEndian, &info)\n\t\tif properties.CyberspaceFlag != nil {\n\t\t\tinfo.CyberspaceFlag = 0\n\t\t\tif *properties.CyberspaceFlag {\n\t\t\t\tinfo.CyberspaceFlag = 1\n\t\t\t}\n\t\t}\n\t\tif properties.HeightShift != nil {\n\t\t\tinfo.HeightShift = uint32(*properties.HeightShift)\n\t\t}\n\t\tbinary.Write(infoWriter, binary.LittleEndian, &info)\n\t\tinfoStore.SetBlockData(0, infoWriter.Bytes())\n\t}\n\t{\n\t\tvarsStore := level.store.Get(res.ResourceID(4000 + level.id*100 + 45))\n\t\tvarsData := varsStore.BlockData(0)\n\t\tvarsReader := bytes.NewReader(varsData)\n\t\tvarsWriter := bytes.NewBuffer(nil)\n\t\tvar vars data.LevelVariables\n\n\t\tbinary.Read(varsReader, binary.LittleEndian, &vars)\n\t\tif properties.CeilingHasRadiation != nil {\n\t\t\tvars.RadiationRegister = 0\n\t\t\tif *properties.CeilingHasRadiation {\n\t\t\t\tvars.RadiationRegister = 2\n\t\t\t}\n\t\t}\n\t\tif properties.CeilingEffectLevel != nil {\n\t\t\tvars.Radiation = byte(*properties.CeilingEffectLevel)\n\t\t}\n\t\tif properties.FloorHasBiohazard != nil {\n\t\t\tvars.BioRegister = 0\n\t\t\tif *properties.FloorHasBiohazard {\n\t\t\t\tvars.BioRegister = 2\n\t\t\t}\n\t\t}\n\t\tif properties.FloorHasGravity != nil {\n\t\t\tvars.GravitySwitch = 0\n\t\t\tif *properties.FloorHasGravity {\n\t\t\t\tvars.GravitySwitch = 1\n\t\t\t}\n\t\t}\n\t\tif properties.FloorEffectLevel != nil {\n\t\t\tvars.BioOrGravity = byte(*properties.FloorEffectLevel)\n\t\t}\n\t\tbinary.Write(varsWriter, binary.LittleEndian, &vars)\n\t\tvarsStore.SetBlockData(0, varsWriter.Bytes())\n\t}\n}", "func (c Client) SetProperties(ctx context.Context, fileSystemName string, input SetPropertiesInput) (resp SetPropertiesResponse, err error) {\n\n\tif fileSystemName == \"\" {\n\t\treturn resp, fmt.Errorf(\"`fileSystemName` cannot be an empty string\")\n\t}\n\n\topts := client.RequestOptions{\n\t\tContentType: \"application/xml; charset=utf-8\",\n\t\tExpectedStatusCodes: []int{\n\t\t\thttp.StatusOK,\n\t\t},\n\t\tHttpMethod: http.MethodPatch,\n\t\tOptionsObject: setPropertiesOptions{\n\t\t\tproperties: input.Properties,\n\t\t\tifUnmodifiedSince: input.IfUnmodifiedSince,\n\t\t\tifModifiedSince: input.IfModifiedSince,\n\t\t},\n\n\t\tPath: fmt.Sprintf(\"/%s\", fileSystemName),\n\t}\n\n\treq, err := c.Client.NewRequest(ctx, opts)\n\n\tif err != nil {\n\t\terr = fmt.Errorf(\"building request: %+v\", err)\n\t\treturn\n\t}\n\tresp.HttpResponse, err = req.Execute(ctx)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"executing request: %+v\", err)\n\t\treturn\n\t}\n\n\treturn\n}", "func SetServerProperties(mc *clients.ManagementClient, serverName string, groupID string, properties handle.Handle, response handle.ResponseHandle) error {\n\tif groupID == \"\" {\n\t\tgroupID = \"Default\"\n\t}\n\treq, err := util.BuildRequestFromHandle(mc, \"GET\", \"/servers/\"+serverName+\"/properties?group-id=\"+groupID, properties)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn util.Execute(mc, req, response)\n}", "func (o *SchemaDefinitionRestDto) SetProperties(v map[string]PropertyDefinition) {\n\to.Properties = &v\n}", "func (endpoint *VirtualEndpoint) SetProperties(properties NetworkInfo) {\n\tendpoint.EndpointProperties = properties\n}", "func (o *ControllerServiceReferencingComponentDTO) SetProperties(v map[string]string) {\n\to.Properties = &v\n}", "func (obj *Object) SetProperties(properties *enigma.GenericObjectProperties) {\n\tobj.lockData.Lock()\n\tdefer obj.lockData.Unlock()\n\tif obj.data == nil {\n\t\tobj.data = &objectData{\n\t\t\tproperties: properties,\n\t\t}\n\t\treturn\n\t}\n\tobj.data.properties = properties\n}", "func (s *QueryFilters) SetProperties(v map[string]*string) *QueryFilters {\n\ts.Properties = v\n\treturn s\n}", "func (o *SubscriptionAttributesWebhookAttributesResponse) SetProperties(m map[string]interface{}) {\n\to.additionalProperties = make(map[string]interface{})\n\tfor k, v := range m {\n\t\to.additionalProperties[k] = v\n\t}\n}", "func (o *SubscriptionAttributesSlackAttributesResponse) SetProperties(m map[string]interface{}) {\n\to.additionalProperties = make(map[string]interface{})\n\tfor k, v := range m {\n\t\to.additionalProperties[k] = v\n\t}\n}", "func (endpoint *VhostUserEndpoint) SetProperties(properties NetworkInfo) {\n\tendpoint.EndpointProperties = properties\n}", "func (s *UpdateContextInput) SetProperties(v map[string]*string) *UpdateContextInput {\n\ts.Properties = v\n\treturn s\n}", "func (endpoint *PhysicalEndpoint) SetProperties(properties NetworkInfo) {\n\tendpoint.EndpointProperties = properties\n}", "func (s *UpdateActionInput) SetProperties(v map[string]*string) *UpdateActionInput {\n\ts.Properties = v\n\treturn s\n}", "func (endpoint *BridgedMacvlanEndpoint) SetProperties(properties NetworkInfo) {\n\tendpoint.EndpointProperties = properties\n}", "func (o *SubscriptionAttributes) SetProperties(m map[string]interface{}) {\n\to.additionalProperties = make(map[string]interface{})\n\tfor k, v := range m {\n\t\to.additionalProperties[k] = v\n\t}\n}", "func (s *CreateActionInput) SetProperties(v map[string]*string) *CreateActionInput {\n\ts.Properties = v\n\treturn s\n}", "func (endpoint *MacvtapEndpoint) SetProperties(properties NetworkInfo) {\n\tendpoint.EndpointProperties = properties\n}", "func setProperties(putMsgHandle ibmmq.MQMessageHandle) error {\n\tvar err error\n\n\t// Create the descriptor structures needed to set a property. In most cases,\n\t// the default values for these descriptors are sufficient.\n\tsmpo := ibmmq.NewMQSMPO()\n\tpd := ibmmq.NewMQPD()\n\n\t// And now set several properties of different types\n\n\t// Note how the \"value\" of each property can change datatype\n\t// without needing to be explicitly stated.\n\tname := \"PROP1STRING\"\n\tv1 := \"helloStringProperty\"\n\terr = putMsgHandle.SetMP(smpo, name, pd, v1)\n\tif err != nil {\n\t\tfmt.Printf(\"PROP1: %v\\n\", err)\n\t}\n\n\tname = \"PROP2INT\"\n\tv2 := 42\n\terr = putMsgHandle.SetMP(smpo, name, pd, int(v2))\n\tif err != nil {\n\t\tfmt.Printf(\"PROP2: %v\\n\", err)\n\t}\n\n\tname = \"PROP2AINT32\"\n\tv2a := 4242\n\terr = putMsgHandle.SetMP(smpo, name, pd, int32(v2a))\n\tif err != nil {\n\t\tfmt.Printf(\"PROP2: %v\\n\", err)\n\t}\n\n\tname = \"PROP2BINT64\"\n\tv2b := 424242\n\terr = putMsgHandle.SetMP(smpo, name, pd, int64(v2b))\n\tif err != nil {\n\t\tfmt.Printf(\"PROP2: %v\\n\", err)\n\t}\n\n\tname = \"PROP2CINT16\"\n\tv2c := 4242\n\terr = putMsgHandle.SetMP(smpo, name, pd, int16(v2c))\n\tif err != nil {\n\t\tfmt.Printf(\"PROP2: %v\\n\", err)\n\t}\n\n\tname = \"PROP3BOOL\"\n\tv3 := true\n\terr = putMsgHandle.SetMP(smpo, name, pd, v3)\n\tif err != nil {\n\t\tfmt.Println(\"PROP3: %v\\n\", err)\n\t}\n\n\tname = \"PROP4BYTEARRAY\"\n\tv4 := make([]byte, 6)\n\tfor i := 0; i < 6; i++ {\n\t\tv4[i] = byte(0x64 + i)\n\t}\n\terr = putMsgHandle.SetMP(smpo, name, pd, v4)\n\tif err != nil {\n\t\tfmt.Println(\"PROP4: %v\\n\", err)\n\t}\n\n\tname = \"PROP5NULL\"\n\terr = putMsgHandle.SetMP(smpo, name, pd, nil)\n\tif err != nil {\n\t\tfmt.Println(\"PROP5: %v\\n\", err)\n\t}\n\n\tname = \"PROP6DELETED\"\n\tv6 := 10101\n\terr = putMsgHandle.SetMP(smpo, name, pd, v6)\n\tif err != nil {\n\t\tfmt.Println(\"PROP6: %v\\n\", err)\n\t}\n\n\t// Use the DltMP function to remove a property from the set. So we should\n\t// end up with 1 fewer properties on the message\n\tdmpo := ibmmq.NewMQDMPO()\n\terr = putMsgHandle.DltMP(dmpo, name)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tname = \"PROP7BYTE\"\n\tv7 := (byte)(36)\n\terr = putMsgHandle.SetMP(smpo, name, pd, v7)\n\tif err != nil {\n\t\tfmt.Printf(\"PROP7: %v\\n\", err)\n\t}\n\n\tname = \"PROP8FLOAT32\"\n\tv8 := (float32)(3.14159)\n\terr = putMsgHandle.SetMP(smpo, name, pd, v8)\n\tif err != nil {\n\t\tfmt.Printf(\"PROP8: %v\\n\", err)\n\t}\n\n\tname = \"PROP9FLOAT64\"\n\tv9 := (float64)(3.14159)\n\terr = putMsgHandle.SetMP(smpo, name, pd, v9)\n\tif err != nil {\n\t\tfmt.Printf(\"PROP9: %v\\n\", err)\n\t}\n\n\treturn err\n}", "func (s *ComponentRequest) SetProperties(v map[string]*PropertyRequest) *ComponentRequest {\n\ts.Properties = v\n\treturn s\n}", "func (s *ProxyConfiguration) SetProperties(v []*KeyValuePair) *ProxyConfiguration {\n\ts.Properties = v\n\treturn s\n}", "func (o *SubscriptionAttributesServiceNowAttributesResponse) SetProperties(m map[string]interface{}) {\n\to.additionalProperties = make(map[string]interface{})\n\tfor k, v := range m {\n\t\to.additionalProperties[k] = v\n\t}\n}", "func (s *CreateContextInput) SetProperties(v map[string]*string) *CreateContextInput {\n\ts.Properties = v\n\treturn s\n}", "func (o *SubscriptionAttributesSmsAttributesResponse) SetProperties(m map[string]interface{}) {\n\to.additionalProperties = make(map[string]interface{})\n\tfor k, v := range m {\n\t\to.additionalProperties[k] = v\n\t}\n}", "func (s *ComponentResponse) SetProperties(v map[string]*PropertyResponse) *ComponentResponse {\n\ts.Properties = v\n\treturn s\n}", "func (o *TemplateApplyAction) SetProperties(v TemplateApplyActionProperties) {\n\to.Properties = v\n}", "func (s *DescribeActionOutput) SetProperties(v map[string]*string) *DescribeActionOutput {\n\ts.Properties = v\n\treturn s\n}", "func (s *UpdateArtifactInput) SetProperties(v map[string]*string) *UpdateArtifactInput {\n\ts.Properties = v\n\treturn s\n}", "func (s *Resource) SetProperties(v []*ResourceProperty) *Resource {\n\ts.Properties = v\n\treturn s\n}", "func (c *Client) SetItemProperties(repo string, path string, properties map[string][]string) error {\n\tvar propertyString string\n\tvar index int\n\tfor k, v := range properties {\n\t\tindex++\n\t\tif len(v) == 1 {\n\t\t\tpropertyString = propertyString + fmt.Sprintf(\"%s=%s\", k, v[0])\n\t\t} else {\n\t\t\tpropertyString = propertyString + fmt.Sprintf(\"%s=[%s]\", k, strings.Join(v, \",\"))\n\t\t}\n\n\t\tif index != len(properties) {\n\t\t\tpropertyString = propertyString + \";\"\n\t\t}\n\t}\n\n\t_, err := c.Put(fmt.Sprintf(\"/api/storage/%s/%s?properties=%s&recursive=1\", repo, path, propertyString), nil, make(map[string]string))\n\treturn err\n}", "func (b *ClusterBuilder) Properties(value map[string]string) *ClusterBuilder {\n\tb.properties = value\n\tif value != nil {\n\t\tb.bitmap_ |= 34359738368\n\t} else {\n\t\tb.bitmap_ &^= 34359738368\n\t}\n\treturn b\n}", "func (o *Metric) SetProperties(v MetricProperties) {\n\to.Properties = &v\n}", "func (s *DescribeContextOutput) SetProperties(v map[string]*string) *DescribeContextOutput {\n\ts.Properties = v\n\treturn s\n}", "func (o *SubscriptionAttributesEmailAttributesResponse) SetProperties(m map[string]interface{}) {\n\to.additionalProperties = make(map[string]interface{})\n\tfor k, v := range m {\n\t\to.additionalProperties[k] = v\n\t}\n}", "func (s *CreateArtifactInput) SetProperties(v map[string]*string) *CreateArtifactInput {\n\ts.Properties = v\n\treturn s\n}", "func SetProp(name string, props map[string]interface{}, source PropSource) error {\n\tcmd := &Cmd{\n\t\tCookie: uint64(source),\n\t}\n\terrList := make(map[string]int64)\n\treturn NvlistIoctl(zfsHandle.Fd(), ZFS_IOC_SET_PROP, name, cmd, props, errList, nil)\n\t// TODO: Distinguish between partial and complete failures using errList\n}", "func (s *DescribeArtifactOutput) SetProperties(v map[string]*string) *DescribeArtifactOutput {\n\ts.Properties = v\n\treturn s\n}", "func (self *Tween) SetPropertiesA(member interface{}) {\n self.Object.Set(\"properties\", member)\n}", "func initProperties() {\n\tproperties := config.NewProperties()\n\tfor _, v := range cfg.ConfigFiles {\n\t\tif err := properties.Load(v); err == nil {\n\t\t\tcfg.ClientLogger.Debugf(\"initProperties[%s] success: %v\", v, properties)\n\t\t\tbreak\n\t\t} else {\n\t\t\tcfg.ClientLogger.Debugf(\"initProperties[%s] fail: %v\", v, err)\n\t\t}\n\t}\n\n\tif cfg.Node == nil {\n\t\tcfg.Node = properties.Nodes\n\t}\n\n\tif cfg.LocalLimit == 0 {\n\t\tcfg.LocalLimit = properties.LocalLimit\n\t}\n\n\tif cfg.TotalLimit == 0 {\n\t\tcfg.TotalLimit = properties.TotalLimit\n\t}\n\n\tif cfg.ClientQueueSize == 0 {\n\t\tcfg.ClientQueueSize = properties.ClientQueueSize\n\t}\n}", "func SetDisplayProperties(ctx context.Context, c *chrome.Conn, id string, dp DisplayProperties) error {\n\tb, err := json.Marshal(&dp)\n\tif err != nil {\n\t\treturn err\n\t}\n\texpr := fmt.Sprintf(\n\t\t`new Promise(function(resolve, reject) {\n\t\t\tchrome.system.display.setDisplayProperties(\n\t\t\t\t%q, %s, function() {\n\t\t\t\t\tresolve(chrome.runtime.lastError ? chrome.runtime.lastError.message : \"\");\n\t\t\t\t});\n\t\t})`, id, string(b))\n\n\tmsg := \"\"\n\tif err = c.EvalPromise(ctx, expr, &msg); err != nil {\n\t\treturn err\n\t} else if msg != \"\" {\n\t\treturn errors.New(msg)\n\t}\n\treturn nil\n}", "func (a *API) RegisterProperties(properties map[string]*PropertyConfig) error {\n\treturn a.Call(\"register_properties\", properties, &emptyResponse{})\n}", "func (o *DatatypeObject) Properties(properties ...Datatype) *DatatypeObject {\n\to.properties = append(o.properties, properties...)\n\treturn o\n}", "func (o *FakeObject) Set(key string, value interface{}) { o.Properties[key] = value }", "func (o *WorkflowWorkflowDefinitionAllOf) SetProperties(v WorkflowWorkflowProperties) {\n\to.Properties.Set(&v)\n}", "func (mr *MockCoreClientMockRecorder) SetProjectProperties(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SetProjectProperties\", reflect.TypeOf((*MockCoreClient)(nil).SetProjectProperties), arg0, arg1)\n}", "func AssignProperties(ent entity3.IEntity, fs *filesystem.FileSystem) {\n\tif DoesEntityReferenceStudioModel(ent) {\n\t\tAssignStudioModelToEntity(ent, fs)\n\t}\n}", "func (recv *Object) SetProperty(propertyName string, value *Value) {\n\tc_property_name := C.CString(propertyName)\n\tdefer C.free(unsafe.Pointer(c_property_name))\n\n\tc_value := (*C.GValue)(C.NULL)\n\tif value != nil {\n\t\tc_value = (*C.GValue)(value.ToC())\n\t}\n\n\tC.g_object_set_property((*C.GObject)(recv.native), c_property_name, c_value)\n\n\treturn\n}", "func (a *Label_Properties) Set(fieldName string, value string) {\n\tif a.AdditionalProperties == nil {\n\t\ta.AdditionalProperties = make(map[string]string)\n\t}\n\ta.AdditionalProperties[fieldName] = value\n}", "func (t *Tickets) WithProperties(props []string) *Tickets {\n\tt.Properties = props\n\treturn t\n}", "func NewProperties() *Properties {\n\treturn &Properties{}\n}", "func (level *Level) SetTileProperties(x, y int, properties model.TileProperties) {\n\tlevel.mutex.Lock()\n\tdefer level.mutex.Unlock()\n\tisCyberspace := level.isCyberspace()\n\n\tentry := level.tileMap.Entry(logic.AtTile(uint16(x), uint16(y)))\n\tflags := uint32(entry.Flags)\n\tif properties.Type != nil {\n\t\tentry.Type = tileType(*properties.Type)\n\t}\n\tif properties.FloorHeight != nil {\n\t\tentry.Floor = (entry.Floor & 0xE0) | (byte(*properties.FloorHeight) & 0x1F)\n\t}\n\tif properties.CeilingHeight != nil {\n\t\tentry.Ceiling = (entry.Ceiling & 0xE0) | (byte(*properties.CeilingHeight) & 0x1F)\n\t}\n\tif properties.SlopeHeight != nil {\n\t\tentry.SlopeHeight = byte(*properties.SlopeHeight)\n\t}\n\tif properties.SlopeControl != nil {\n\t\tflags = (flags & ^uint32(0x00000C00)) | (uint32(slopeControl(*properties.SlopeControl)) << 10)\n\t}\n\tif properties.MusicIndex != nil {\n\t\tflags = uint32(data.TileFlag(flags).WithMusicIndex(*properties.MusicIndex))\n\t}\n\tif !isCyberspace && (properties.RealWorld != nil) {\n\t\tvar textureIDs = uint16(entry.Textures)\n\n\t\tif properties.RealWorld.FloorTexture != nil && (*properties.RealWorld.FloorTexture < 0x20) {\n\t\t\ttextureIDs = (textureIDs & 0x07FF) | (uint16(*properties.RealWorld.FloorTexture) << 11)\n\t\t}\n\t\tif properties.RealWorld.FloorTextureRotations != nil {\n\t\t\tentry.Floor = (entry.Floor & 0x9F) | ((byte(*properties.RealWorld.FloorTextureRotations) & 0x3) << 5)\n\t\t}\n\t\tif properties.RealWorld.CeilingTexture != nil && (*properties.RealWorld.CeilingTexture < 0x20) {\n\t\t\ttextureIDs = (textureIDs & 0xF83F) | (uint16(*properties.RealWorld.CeilingTexture) << 6)\n\t\t}\n\t\tif properties.RealWorld.CeilingTextureRotations != nil {\n\t\t\tentry.Ceiling = (entry.Ceiling & 0x9F) | ((byte(*properties.RealWorld.CeilingTextureRotations) & 0x3) << 5)\n\t\t}\n\t\tif properties.RealWorld.WallTexture != nil && (*properties.RealWorld.WallTexture < 0x40) {\n\t\t\ttextureIDs = (textureIDs & 0xFFC0) | uint16(*properties.RealWorld.WallTexture)\n\t\t}\n\t\tif properties.RealWorld.UseAdjacentWallTexture != nil {\n\t\t\tflags = flags & ^uint32(0x00000100)\n\t\t\tif *properties.RealWorld.UseAdjacentWallTexture {\n\t\t\t\tflags |= 0x00000100\n\t\t\t}\n\t\t}\n\t\tif properties.RealWorld.WallTextureOffset != nil && *properties.RealWorld.WallTextureOffset < 0x20 {\n\t\t\tflags = (flags & ^uint32(0x0000001F)) | uint32(*properties.RealWorld.WallTextureOffset)\n\t\t}\n\t\tif properties.RealWorld.WallTexturePattern != nil {\n\t\t\tflags = (flags & ^uint32(0x00000060) | (uint32(*properties.RealWorld.WallTexturePattern) << 5))\n\t\t}\n\t\tif properties.RealWorld.FloorHazard != nil {\n\t\t\tentry.Floor &= 0x7F\n\t\t\tif *properties.RealWorld.FloorHazard {\n\t\t\t\tentry.Floor |= 0x80\n\t\t\t}\n\t\t}\n\t\tif properties.RealWorld.CeilingHazard != nil {\n\t\t\tentry.Ceiling &= 0x7F\n\t\t\tif *properties.RealWorld.CeilingHazard {\n\t\t\t\tentry.Ceiling |= 0x80\n\t\t\t}\n\t\t}\n\t\tif properties.RealWorld.FloorShadow != nil {\n\t\t\tflags = uint32(data.TileFlag(flags).WithFloorShadow(*properties.RealWorld.FloorShadow))\n\t\t}\n\t\tif properties.RealWorld.CeilingShadow != nil {\n\t\t\tflags = uint32(data.TileFlag(flags).WithCeilingShadow(*properties.RealWorld.CeilingShadow))\n\t\t}\n\t\tif properties.RealWorld.SpookyMusic != nil {\n\t\t\tflags = flags & ^uint32(0x00000200)\n\t\t\tif *properties.RealWorld.SpookyMusic {\n\t\t\t\tflags |= 0x00000200\n\t\t\t}\n\t\t}\n\n\t\tentry.Textures = data.TileTextureInfo(textureIDs)\n\t} else if isCyberspace && properties.Cyberspace != nil {\n\t\tvar colors = uint16(entry.Textures)\n\n\t\tif properties.Cyberspace.FloorColorIndex != nil {\n\t\t\tcolors = (colors & 0xFF00) | (uint16(*properties.Cyberspace.FloorColorIndex) << 0)\n\t\t}\n\t\tif properties.Cyberspace.CeilingColorIndex != nil {\n\t\t\tcolors = (colors & 0x00FF) | (uint16(*properties.Cyberspace.CeilingColorIndex) << 8)\n\t\t}\n\t\tif properties.Cyberspace.FlightPullType != nil {\n\t\t\tflags = (flags & ^uint32(0x010F0000)) |\n\t\t\t\t((uint32(*properties.Cyberspace.FlightPullType) & 0xF) << 16) |\n\t\t\t\t((uint32(*properties.Cyberspace.FlightPullType) & 0x10) << 20)\n\t\t}\n\t\tif properties.Cyberspace.GameOfLifeSet != nil {\n\t\t\tflags = flags & ^uint32(0x00000040)\n\t\t\tif *properties.Cyberspace.GameOfLifeSet {\n\t\t\t\tflags |= 0x00000040\n\t\t\t}\n\t\t}\n\n\t\tentry.Textures = data.TileTextureInfo(colors)\n\t}\n\tentry.Flags = data.TileFlag(flags)\n\n\tlevel.onTileDataChanged()\n}", "func (obj *Device) SetCursorProperties(\n\txHotSpot uint,\n\tyHotSpot uint,\n\tcursorBitmap *Surface,\n) Error {\n\tret, _, _ := syscall.Syscall6(\n\t\tobj.vtbl.SetCursorProperties,\n\t\t4,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(xHotSpot),\n\t\tuintptr(yHotSpot),\n\t\tuintptr(unsafe.Pointer(cursorBitmap)),\n\t\t0,\n\t\t0,\n\t)\n\treturn toErr(ret)\n}", "func (client *FileServicesClient) SetServiceProperties(ctx context.Context, resourceGroupName string, accountName string, parameters FileServiceProperties, options *FileServicesSetServicePropertiesOptions) (FileServicePropertiesResponse, error) {\n\treq, err := client.setServicePropertiesCreateRequest(ctx, resourceGroupName, accountName, parameters, options)\n\tif err != nil {\n\t\treturn FileServicePropertiesResponse{}, err\n\t}\n\tresp, err := client.con.Pipeline().Do(req)\n\tif err != nil {\n\t\treturn FileServicePropertiesResponse{}, err\n\t}\n\tif !resp.HasStatusCode(http.StatusOK) {\n\t\treturn FileServicePropertiesResponse{}, client.setServicePropertiesHandleError(resp)\n\t}\n\treturn client.setServicePropertiesHandleResponse(resp)\n}", "func (l *List) SetProperty(p sparta.Property, v interface{}) {\n\tswitch p {\n\tcase sparta.Childs:\n\t\tif v == nil {\n\t\t\tl.scroll = nil\n\t\t}\n\tcase sparta.Data:\n\t\tl.data = v\n\tcase sparta.Geometry:\n\t\tval := v.(image.Rectangle)\n\t\tif !l.geometry.Eq(val) {\n\t\t\tl.win.SetProperty(sparta.Geometry, val)\n\t\t}\n\tcase sparta.Parent:\n\t\tif v == nil {\n\t\t\tl.parent = nil\n\t\t}\n\tcase sparta.Name:\n\t\tval := v.(string)\n\t\tif l.name != val {\n\t\t\tl.name = val\n\t\t}\n\tcase sparta.Foreground:\n\t\tval := v.(color.RGBA)\n\t\tif l.fore != val {\n\t\t\tl.fore = val\n\t\t\tl.win.SetProperty(sparta.Foreground, val)\n\t\t}\n\tcase sparta.Background:\n\t\tval := v.(color.RGBA)\n\t\tif l.back != val {\n\t\t\tl.back = val\n\t\t\tl.win.SetProperty(sparta.Background, val)\n\t\t}\n\tcase sparta.Target:\n\t\tval := v.(sparta.Widget)\n\t\tif val == nil {\n\t\t\tval = l.parent\n\t\t}\n\t\tif l.target == val {\n\t\t\tbreak\n\t\t}\n\t\tl.target = val\n\tcase ListList:\n\t\tif v == nil {\n\t\t\tl.list = nil\n\t\t\tl.scroll.SetProperty(ScrollSize, 0)\n\t\t} else {\n\t\t\tval := v.(ListData)\n\t\t\tl.list = val\n\t\t\tl.scroll.SetProperty(ScrollSize, 0)\n\t\t\tl.scroll.SetProperty(ScrollSize, val.Len())\n\t\t}\n\t\tl.scroll.SetProperty(ScrollPage, l.geometry.Dy()/sparta.HeightUnit)\n\t\tl.Update()\n\t}\n}", "func (p *AccumuloProxyClient) SetTableProperty(login []byte, tableName string, property string, value string) (err error) {\n\tif err = p.sendSetTableProperty(login, tableName, property, value); err != nil {\n\t\treturn\n\t}\n\treturn p.recvSetTableProperty()\n}", "func (jo *Object) SetParameters(params *Object) *Object {\n\tvar set Object\n\n\tfor _, jp := range jo.Properties {\n\t\tvar (\n\t\t\tname = jp.Name\n\t\t\tvalue = jp.Value\n\t\t)\n\t\tif len(jp.namep) > 0 {\n\t\t\tname, _ = setStringParameters(fmt.Sprintf(\"\\\"%s\\\"\", jp.Name), jp.namep, params)\n\t\t\tif len(name) < 3 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tname = string(name[1 : len(name)-1])\n\t\t}\n\n\t\tvalue = setValueParameters(value, jp.valuep, params)\n\t\tif value == nil {\n\t\t\tcontinue\n\t\t}\n\t\tswitch value.Type() {\n\t\tcase StringType:\n\t\t\tif value.Value() == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase ObjectType:\n\t\t\to, ok := value.(*Object)\n\t\t\tif !ok || len(o.Properties) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase ArrayType:\n\t\t\ta, ok := value.(*Array)\n\t\t\tif !ok || len(a.Values) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tset.Add(name, value)\n\t}\n\n\treturn &set\n}", "func (m *Application) SetExtensionProperties(value []ExtensionPropertyable)() {\n m.extensionProperties = value\n}", "func (c *Client) SetProperty(name string, value interface{}) error {\n\t_, err := c.Exec(\"set_property\", name, value)\n\treturn err\n}", "func (sp *Properties) Properties() api.Properties {\n\treturn api.Properties(sp)\n}", "func (z *ZfsH) SetProperty(d *Dataset, key, val string) error {\n\tprop := strings.Join([]string{key, val}, \"=\")\n\t_, err := z.zfs(\"set\", prop, d.Name)\n\treturn err\n}", "func (e *Edge) SetProperty(key string, value interface{}) {\n\te.Properties[key] = value\n}", "func (_class PIFClass) SetProperty(sessionID SessionRef, self PIFRef, name string, value string) (_err error) {\n\t_method := \"PIF.set_property\"\n\t_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf(\"%s(%s)\", _method, \"session_id\"), sessionID)\n\tif _err != nil {\n\t\treturn\n\t}\n\t_selfArg, _err := convertPIFRefToXen(fmt.Sprintf(\"%s(%s)\", _method, \"self\"), self)\n\tif _err != nil {\n\t\treturn\n\t}\n\t_nameArg, _err := convertStringToXen(fmt.Sprintf(\"%s(%s)\", _method, \"name\"), name)\n\tif _err != nil {\n\t\treturn\n\t}\n\t_valueArg, _err := convertStringToXen(fmt.Sprintf(\"%s(%s)\", _method, \"value\"), value)\n\tif _err != nil {\n\t\treturn\n\t}\n\t_, _err = _class.client.APICall(_method, _sessionIDArg, _selfArg, _nameArg, _valueArg)\n\treturn\n}", "func NewProperties() *Properties {\n\treturn &Properties{\n\t\tm: make(map[string]string),\n\t}\n}", "func (node *Node) SwapProperties(p1, p2 *Property) {\n\tnode.SwapPropertiesAt(node.propertyIndex(p1), node.propertyIndex(p2))\n}", "func (v *vertex) Properties(keys ...string) interfaces.Property {\n\n\tquery := NewSimpleQB(\".properties()\")\n\tif len(keys) > 0 {\n\t\tquotedKeys := make([]string, 0, len(keys))\n\t\tfor _, key := range keys {\n\t\t\tquotedKeys = append(quotedKeys, fmt.Sprintf(`\"%s\"`, key))\n\t\t}\n\t\tkeyList := strings.Join(quotedKeys, `,`)\n\n\t\tquery = NewSimpleQB(\".properties(%s)\", keyList)\n\t}\n\n\tv.Add(query)\n\treturn NewPropertyV(v)\n}", "func (t *TableServiceClient) SetServiceProperties(props ServiceProperties) error {\n\treturn t.client.setServiceProperties(props, tableServiceName, t.auth)\n}", "func (p *AccumuloProxyClient) SetProperty(login []byte, property string, value string) (err error) {\n\tif err = p.sendSetProperty(login, property, value); err != nil {\n\t\treturn\n\t}\n\treturn p.recvSetProperty()\n}", "func (a *LabelUpdate_Properties) Set(fieldName string, value string) {\n\tif a.AdditionalProperties == nil {\n\t\ta.AdditionalProperties = make(map[string]string)\n\t}\n\ta.AdditionalProperties[fieldName] = value\n}", "func (rc *ResourceCreate) AddProperties(p ...*Property) *ResourceCreate {\n\tids := make([]int, len(p))\n\tfor i := range p {\n\t\tids[i] = p[i].ID\n\t}\n\treturn rc.AddPropertyIDs(ids...)\n}", "func (c *cookRun) reportProperties(ctx context.Context, realm string, props interface{}) error {\n\tpropsJSON, err := json.MarshalIndent(props, \"\", \" \")\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"could not marshal properties to JSON\").Err()\n\t}\n\tlog.Infof(ctx, \"using %s properties:\\n%s\", realm, propsJSON)\n\treturn nil\n}", "func (m *MockCoreClient) SetProjectProperties(arg0 context.Context, arg1 core.SetProjectPropertiesArgs) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SetProjectProperties\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func propertySet(properties []Property) []Property {\n\tvar (\n\t\tset []Property\n\t\tvisited = map[string]struct{}{}\n\t)\n\tfor _, p := range properties {\n\t\tif _, ok := visited[p.String()]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tvisited[p.String()] = struct{}{}\n\t\tset = append(set, p)\n\t}\n\n\treturn set\n}", "func (a *AdditionalPropertiesObject3) Set(fieldName string, value interface{}) {\n\tif a.AdditionalProperties == nil {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t}\n\ta.AdditionalProperties[fieldName] = value\n}", "func (a *AdditionalPropertiesObject3) Set(fieldName string, value interface{}) {\n\tif a.AdditionalProperties == nil {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t}\n\ta.AdditionalProperties[fieldName] = value\n}", "func (lu *LocationUpdate) AddProperties(p ...*Property) *LocationUpdate {\n\tids := make([]string, len(p))\n\tfor i := range p {\n\t\tids[i] = p[i].ID\n\t}\n\treturn lu.AddPropertyIDs(ids...)\n}", "func (a *AdditionalPropertiesObject4_Inner) Set(fieldName string, value interface{}) {\n\tif a.AdditionalProperties == nil {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t}\n\ta.AdditionalProperties[fieldName] = value\n}", "func (a *AdditionalPropertiesObject4_Inner) Set(fieldName string, value interface{}) {\n\tif a.AdditionalProperties == nil {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t}\n\ta.AdditionalProperties[fieldName] = value\n}", "func (o *NotificationCreate) SetProperty(key string, value interface{}) {\n\tif o.additionalProperties == nil {\n\t\to.additionalProperties = make(map[string]interface{})\n\t}\n\to.additionalProperties[key] = value\n}", "func (a *AdditionalPropertiesObject4) Set(fieldName string, value interface{}) {\n\tif a.AdditionalProperties == nil {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t}\n\ta.AdditionalProperties[fieldName] = value\n}", "func (a *AdditionalPropertiesObject4) Set(fieldName string, value interface{}) {\n\tif a.AdditionalProperties == nil {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t}\n\ta.AdditionalProperties[fieldName] = value\n}", "func (a *AdditionalPropertiesObject1) Set(fieldName string, value int) {\n\tif a.AdditionalProperties == nil {\n\t\ta.AdditionalProperties = make(map[string]int)\n\t}\n\ta.AdditionalProperties[fieldName] = value\n}", "func (a *AdditionalPropertiesObject1) Set(fieldName string, value int) {\n\tif a.AdditionalProperties == nil {\n\t\ta.AdditionalProperties = make(map[string]int)\n\t}\n\ta.AdditionalProperties[fieldName] = value\n}", "func (euo *EquipmentUpdateOne) AddProperties(p ...*Property) *EquipmentUpdateOne {\n\tids := make([]string, len(p))\n\tfor i := range p {\n\t\tids[i] = p[i].ID\n\t}\n\treturn euo.AddPropertyIDs(ids...)\n}" ]
[ "0.7214836", "0.72038245", "0.71145713", "0.7034423", "0.70218915", "0.68943685", "0.6838208", "0.67702264", "0.6716018", "0.6649501", "0.6591657", "0.65702873", "0.6552207", "0.6527473", "0.6492894", "0.64357823", "0.6418739", "0.6364624", "0.63023174", "0.6281613", "0.62651443", "0.6201876", "0.6158131", "0.61338854", "0.6095846", "0.60946953", "0.6091845", "0.60833263", "0.60764617", "0.6056755", "0.6044908", "0.60322684", "0.6027084", "0.60187876", "0.6018451", "0.6003507", "0.5967194", "0.5892644", "0.588892", "0.5885663", "0.58821493", "0.5862154", "0.5861097", "0.5761813", "0.57481813", "0.5727075", "0.5708743", "0.57041496", "0.57018816", "0.5696778", "0.5695055", "0.5660176", "0.55813646", "0.5574436", "0.5574127", "0.5494508", "0.5485999", "0.54729295", "0.5385946", "0.53802234", "0.53754663", "0.5372831", "0.5370639", "0.5297851", "0.52614295", "0.52555466", "0.52439594", "0.5231652", "0.52137035", "0.52078325", "0.51755047", "0.51650494", "0.5129913", "0.51199985", "0.5090832", "0.50764465", "0.50709236", "0.5065186", "0.5058243", "0.5030185", "0.5028794", "0.50212854", "0.5009657", "0.50079966", "0.49707815", "0.49639755", "0.49602965", "0.49523675", "0.4952358", "0.49425182", "0.49425182", "0.49386528", "0.49337012", "0.49337012", "0.493254", "0.4930219", "0.4930219", "0.49265304", "0.49265304", "0.4920118" ]
0.6662494
9
AddEventIDs adds the events edge to Event by ids.
func (ac *AppCreate) AddEventIDs(ids ...uuid.UUID) *AppCreate { ac.mutation.AddEventIDs(ids...) return ac }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *InviteeMutation) AddEventIDs(ids ...int) {\n\tif m.events == nil {\n\t\tm.events = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.events[ids[i]] = struct{}{}\n\t}\n}", "func (au *AppUpdate) AddEventIDs(ids ...uuid.UUID) *AppUpdate {\n\tau.mutation.AddEventIDs(ids...)\n\treturn au\n}", "func (auo *AppUpdateOne) AddEventIDs(ids ...uuid.UUID) *AppUpdateOne {\n\tauo.mutation.AddEventIDs(ids...)\n\treturn auo\n}", "func (lu *LibraryUpdate) AddEventIDs(ids ...uuid.UUID) *LibraryUpdate {\n\tlu.mutation.AddEventIDs(ids...)\n\treturn lu\n}", "func (luo *LibraryUpdateOne) AddEventIDs(ids ...uuid.UUID) *LibraryUpdateOne {\n\tluo.mutation.AddEventIDs(ids...)\n\treturn luo\n}", "func (du *DeviceUpdate) AddEventIDs(ids ...uuid.UUID) *DeviceUpdate {\n\tdu.mutation.AddEventIDs(ids...)\n\treturn du\n}", "func (duo *DeviceUpdateOne) AddEventIDs(ids ...uuid.UUID) *DeviceUpdateOne {\n\tduo.mutation.AddEventIDs(ids...)\n\treturn duo\n}", "func (tuo *TimingUpdateOne) AddEventIDs(ids ...uuid.UUID) *TimingUpdateOne {\n\ttuo.mutation.AddEventIDs(ids...)\n\treturn tuo\n}", "func (uc *UserCreate) AddEventIDs(ids ...uuid.UUID) *UserCreate {\n\tuc.mutation.AddEventIDs(ids...)\n\treturn uc\n}", "func (mnuo *MetricNameUpdateOne) AddEventIDs(ids ...int) *MetricNameUpdateOne {\n\tmnuo.mutation.AddEventIDs(ids...)\n\treturn mnuo\n}", "func (tu *TimingUpdate) AddEventIDs(ids ...uuid.UUID) *TimingUpdate {\n\ttu.mutation.AddEventIDs(ids...)\n\treturn tu\n}", "func (ic *InstanceCreate) AddEventlistenerIDs(ids ...uuid.UUID) *InstanceCreate {\n\tic.mutation.AddEventlistenerIDs(ids...)\n\treturn ic\n}", "func (mnu *MetricNameUpdate) AddEventIDs(ids ...int) *MetricNameUpdate {\n\tmnu.mutation.AddEventIDs(ids...)\n\treturn mnu\n}", "func (lu *LibraryUpdate) AddEvents(e ...*Event) *LibraryUpdate {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn lu.AddEventIDs(ids...)\n}", "func (au *AppUpdate) AddEvents(e ...*Event) *AppUpdate {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn au.AddEventIDs(ids...)\n}", "func (auo *AppUpdateOne) AddEvents(e ...*Event) *AppUpdateOne {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn auo.AddEventIDs(ids...)\n}", "func (luo *LibraryUpdateOne) AddEvents(e ...*Event) *LibraryUpdateOne {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn luo.AddEventIDs(ids...)\n}", "func (ac *AppCreate) AddEvents(e ...*Event) *AppCreate {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn ac.AddEventIDs(ids...)\n}", "func (du *DeviceUpdate) AddEvents(e ...*Event) *DeviceUpdate {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn du.AddEventIDs(ids...)\n}", "func (duo *DeviceUpdateOne) AddEvents(e ...*Event) *DeviceUpdateOne {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn duo.AddEventIDs(ids...)\n}", "func (tu *TimingUpdate) AddEvents(e ...*Event) *TimingUpdate {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn tu.AddEventIDs(ids...)\n}", "func (tuo *TimingUpdateOne) AddEvents(e ...*Event) *TimingUpdateOne {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn tuo.AddEventIDs(ids...)\n}", "func (mnuo *MetricNameUpdateOne) AddEvents(e ...*Event) *MetricNameUpdateOne {\n\tids := make([]int, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn mnuo.AddEventIDs(ids...)\n}", "func (m *InviteePartyMutation) AddInviteeIDs(ids ...int) {\n\tif m.invitees == nil {\n\t\tm.invitees = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.invitees[ids[i]] = struct{}{}\n\t}\n}", "func (uc *UserCreate) AddEvents(e ...*Event) *UserCreate {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn uc.AddEventIDs(ids...)\n}", "func (mnu *MetricNameUpdate) AddEvents(e ...*Event) *MetricNameUpdate {\n\tids := make([]int, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn mnu.AddEventIDs(ids...)\n}", "func (tru *TradeRecordUpdate) AddExchangeIDs(ids ...int) *TradeRecordUpdate {\n\ttru.mutation.AddExchangeIDs(ids...)\n\treturn tru\n}", "func (truo *TradeRecordUpdateOne) AddExchangeIDs(ids ...int) *TradeRecordUpdateOne {\n\ttruo.mutation.AddExchangeIDs(ids...)\n\treturn truo\n}", "func (euo *EquipmentUpdateOne) AddFileIDs(ids ...string) *EquipmentUpdateOne {\n\tif euo.files == nil {\n\t\teuo.files = make(map[string]struct{})\n\t}\n\tfor i := range ids {\n\t\teuo.files[ids[i]] = struct{}{}\n\t}\n\treturn euo\n}", "func (m *EmployeeMutation) AddEmployeeIDs(ids ...int) {\n\tif m.employees == nil {\n\t\tm.employees = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.employees[ids[i]] = struct{}{}\n\t}\n}", "func (m *EmployeeMutation) AddEmployeeIDs(ids ...int) {\n\tif m.employees == nil {\n\t\tm.employees = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.employees[ids[i]] = struct{}{}\n\t}\n}", "func (m *TradeRecordMutation) AddExchangeIDs(ids ...int) {\n\tif m.exchange == nil {\n\t\tm.exchange = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.exchange[ids[i]] = struct{}{}\n\t}\n}", "func (m *PlaceMutation) AddEmployeeIDs(ids ...int) {\n\tif m.employee == nil {\n\t\tm.employee = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.employee[ids[i]] = struct{}{}\n\t}\n}", "func (wou *WorkOrderUpdate) AddFileIDs(ids ...string) *WorkOrderUpdate {\n\tif wou.files == nil {\n\t\twou.files = make(map[string]struct{})\n\t}\n\tfor i := range ids {\n\t\twou.files[ids[i]] = struct{}{}\n\t}\n\treturn wou\n}", "func (m *EventRSVPMutation) AddedIDs(name string) []ent.Value {\n\tswitch name {\n\tcase eventrsvp.EdgeEvent:\n\t\tif id := m.event; id != nil {\n\t\t\treturn []ent.Value{*id}\n\t\t}\n\tcase eventrsvp.EdgeInvitee:\n\t\tif id := m.invitee; id != nil {\n\t\t\treturn []ent.Value{*id}\n\t\t}\n\t}\n\treturn nil\n}", "func (wouo *WorkOrderUpdateOne) AddFileIDs(ids ...string) *WorkOrderUpdateOne {\n\tif wouo.files == nil {\n\t\twouo.files = make(map[string]struct{})\n\t}\n\tfor i := range ids {\n\t\twouo.files[ids[i]] = struct{}{}\n\t}\n\treturn wouo\n}", "func (ic *InstanceCreate) AddEventlisteners(e ...*Events) *InstanceCreate {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn ic.AddEventlistenerIDs(ids...)\n}", "func (eu *EquipmentUpdate) AddFileIDs(ids ...string) *EquipmentUpdate {\n\tif eu.files == nil {\n\t\teu.files = make(map[string]struct{})\n\t}\n\tfor i := range ids {\n\t\teu.files[ids[i]] = struct{}{}\n\t}\n\treturn eu\n}", "func (m *NametitleMutation) AddEmployeeIDs(ids ...int) {\n\tif m.employee == nil {\n\t\tm.employee = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.employee[ids[i]] = struct{}{}\n\t}\n}", "func (m *PositionMutation) AddEmployeeIDs(ids ...int) {\n\tif m.employee == nil {\n\t\tm.employee = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.employee[ids[i]] = struct{}{}\n\t}\n}", "func (objectIDs *DbObjectIDs) AddIDs(extraObjectIds map[ExternalIDKey]string) *DbObjectIDs {\n\tids := deepcopyMap(objectIDs.objectIDs)\n\tfor key, value := range extraObjectIds {\n\t\tids[key] = value\n\t}\n\treturn &DbObjectIDs{objectIDs.idsType, objectIDs.ownerControllerName, ids}\n}", "func (m *EntityMutation) AddExchangeIDs(ids ...int) {\n\tif m.exchanges == nil {\n\t\tm.exchanges = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.exchanges[ids[i]] = struct{}{}\n\t}\n}", "func (oiuo *OrderInfoUpdateOne) AddOrderAddresIDs(ids ...int) *OrderInfoUpdateOne {\n\toiuo.mutation.AddOrderAddresIDs(ids...)\n\treturn oiuo\n}", "func (oiu *OrderInfoUpdate) AddOrderAddresIDs(ids ...int) *OrderInfoUpdate {\n\toiu.mutation.AddOrderAddresIDs(ids...)\n\treturn oiu\n}", "func (gc *GroupCreate) AddFileIDs(ids ...string) *GroupCreate {\n\tif gc.files == nil {\n\t\tgc.files = make(map[string]struct{})\n\t}\n\tfor i := range ids {\n\t\tgc.files[ids[i]] = struct{}{}\n\t}\n\treturn gc\n}", "func (m *DepartmentMutation) AddEmployeeIDs(ids ...int) {\n\tif m.employee == nil {\n\t\tm.employee = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.employee[ids[i]] = struct{}{}\n\t}\n}", "func (m *JobpositionMutation) AddEmployeeIDs(ids ...int) {\n\tif m.employees == nil {\n\t\tm.employees = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.employees[ids[i]] = struct{}{}\n\t}\n}", "func (luo *LocationUpdateOne) AddFileIDs(ids ...string) *LocationUpdateOne {\n\tif luo.files == nil {\n\t\tluo.files = make(map[string]struct{})\n\t}\n\tfor i := range ids {\n\t\tluo.files[ids[i]] = struct{}{}\n\t}\n\treturn luo\n}", "func (otuo *OutboundTransactionUpdateOne) AddDealIDs(ids ...int) *OutboundTransactionUpdateOne {\n\totuo.mutation.AddDealIDs(ids...)\n\treturn otuo\n}", "func (m *UserMutation) AddAddresIDs(ids ...int64) {\n\tif m.address == nil {\n\t\tm.address = make(map[int64]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.address[ids[i]] = struct{}{}\n\t}\n}", "func (auo *ArticleUpdateOne) AddTagIDs(ids ...int) *ArticleUpdateOne {\n\tauo.mutation.AddTagIDs(ids...)\n\treturn auo\n}", "func (m *AgeMutation) AddEmployeeIDs(ids ...int) {\n\tif m.employee == nil {\n\t\tm.employee = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.employee[ids[i]] = struct{}{}\n\t}\n}", "func (otu *OutboundTransactionUpdate) AddDealIDs(ids ...int) *OutboundTransactionUpdate {\n\totu.mutation.AddDealIDs(ids...)\n\treturn otu\n}", "func (m *SalaryMutation) AddEmployeeIDs(ids ...int) {\n\tif m.employee == nil {\n\t\tm.employee = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.employee[ids[i]] = struct{}{}\n\t}\n}", "func (ac *ArticleCreate) AddTagIDs(ids ...int64) *ArticleCreate {\n\tac.mutation.AddTagIDs(ids...)\n\treturn ac\n}", "func (wouo *WorkOrderUpdateOne) AddLinkIDs(ids ...string) *WorkOrderUpdateOne {\n\tif wouo.links == nil {\n\t\twouo.links = make(map[string]struct{})\n\t}\n\tfor i := range ids {\n\t\twouo.links[ids[i]] = struct{}{}\n\t}\n\treturn wouo\n}", "func (wou *WorkOrderUpdate) AddLinkIDs(ids ...string) *WorkOrderUpdate {\n\tif wou.links == nil {\n\t\twou.links = make(map[string]struct{})\n\t}\n\tfor i := range ids {\n\t\twou.links[ids[i]] = struct{}{}\n\t}\n\treturn wou\n}", "func (lu *LocationUpdate) AddFileIDs(ids ...string) *LocationUpdate {\n\tif lu.files == nil {\n\t\tlu.files = make(map[string]struct{})\n\t}\n\tfor i := range ids {\n\t\tlu.files[ids[i]] = struct{}{}\n\t}\n\treturn lu\n}", "func (au *ArticleUpdate) AddTagIDs(ids ...int) *ArticleUpdate {\n\tau.mutation.AddTagIDs(ids...)\n\treturn au\n}", "func (m *EmployeeMutation) AddEmployeestockIDs(ids ...int) {\n\tif m.employeestock == nil {\n\t\tm.employeestock = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.employeestock[ids[i]] = struct{}{}\n\t}\n}", "func (m *RestaurantMutation) AddOrderIDs(ids ...int) {\n\tif m.orders == nil {\n\t\tm.orders = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.orders[ids[i]] = struct{}{}\n\t}\n}", "func (gu *GroupUpdate) AddFileIDs(ids ...int) *GroupUpdate {\n\tgu.mutation.AddFileIDs(ids...)\n\treturn gu\n}", "func (guo *GroupUpdateOne) AddFileIDs(ids ...int) *GroupUpdateOne {\n\tguo.mutation.AddFileIDs(ids...)\n\treturn guo\n}", "func (m *InviteeMutation) AddedIDs(name string) []ent.Value {\n\tswitch name {\n\tcase invitee.EdgeEvents:\n\t\tids := make([]ent.Value, 0, len(m.events))\n\t\tfor id := range m.events {\n\t\t\tids = append(ids, id)\n\t\t}\n\t\treturn ids\n\tcase invitee.EdgeParty:\n\t\tif id := m.party; id != nil {\n\t\t\treturn []ent.Value{*id}\n\t\t}\n\t}\n\treturn nil\n}", "func (duo *DocUpdateOne) AddRelatedIDs(ids ...schema.DocID) *DocUpdateOne {\n\tduo.mutation.AddRelatedIDs(ids...)\n\treturn duo\n}", "func (m *EmployeeMutation) AddLeasesIDs(ids ...int) {\n\tif m.leasess == nil {\n\t\tm.leasess = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.leasess[ids[i]] = struct{}{}\n\t}\n}", "func (du *DocUpdate) AddRelatedIDs(ids ...schema.DocID) *DocUpdate {\n\tdu.mutation.AddRelatedIDs(ids...)\n\treturn du\n}", "func (euo *ExtradoctorUpdateOne) AddOfficeIDs(ids ...int) *ExtradoctorUpdateOne {\n\teuo.mutation.AddOfficeIDs(ids...)\n\treturn euo\n}", "func (eu *ExtradoctorUpdate) AddOfficeIDs(ids ...int) *ExtradoctorUpdate {\n\teu.mutation.AddOfficeIDs(ids...)\n\treturn eu\n}", "func (m *HistoryMutation) AddOfIDs(ids ...int) {\n\tif m.of == nil {\n\t\tm.of = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.of[ids[i]] = struct{}{}\n\t}\n}", "func (m *EmployeeMutation) AddDrugIDs(ids ...int) {\n\tif m.drug == nil {\n\t\tm.drug = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.drug[ids[i]] = struct{}{}\n\t}\n}", "func (euo *EquipmentUpdateOne) AddPositionIDs(ids ...string) *EquipmentUpdateOne {\n\tif euo.positions == nil {\n\t\teuo.positions = make(map[string]struct{})\n\t}\n\tfor i := range ids {\n\t\teuo.positions[ids[i]] = struct{}{}\n\t}\n\treturn euo\n}", "func (m *EventRSVPMutation) EventIDs() (ids []int) {\n\tif id := m.event; id != nil {\n\t\tids = append(ids, *id)\n\t}\n\treturn\n}", "func (m *EmployeeMutation) AddDiseaseIDs(ids ...int) {\n\tif m.disease == nil {\n\t\tm.disease = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.disease[ids[i]] = struct{}{}\n\t}\n}", "func (uc *UserCreate) AddFriendIDs(ids ...int) *UserCreate {\n\tif uc.friends == nil {\n\t\tuc.friends = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tuc.friends[ids[i]] = struct{}{}\n\t}\n\treturn uc\n}", "func (m *TradeTimeRangeMutation) AddRecordIDs(ids ...int) {\n\tif m.records == nil {\n\t\tm.records = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.records[ids[i]] = struct{}{}\n\t}\n}", "func (m *InviteeMutation) RemoveEventIDs(ids ...int) {\n\tif m.removedevents == nil {\n\t\tm.removedevents = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.removedevents[ids[i]] = struct{}{}\n\t}\n}", "func (jc *JobpositionCreate) AddEmployeeIDs(ids ...int) *JobpositionCreate {\n\tjc.mutation.AddEmployeeIDs(ids...)\n\treturn jc\n}", "func (space *Space) AddEntityIDs(ids []string) {\n\tcheckMap := make(map[string]bool)\n\tentityList := append(space.EntityIDs, ids...)\n\tspace.EntityIDs = nil\n\tfor _, item := range entityList {\n\t\tif _, value := checkMap[item]; !value {\n\t\t\tcheckMap[item] = true\n\t\t\tspace.EntityIDs = append(space.EntityIDs, item)\n\t\t}\n\t}\n}", "func (euo *EquipmentUpdateOne) AddPortIDs(ids ...string) *EquipmentUpdateOne {\n\tif euo.ports == nil {\n\t\teuo.ports = make(map[string]struct{})\n\t}\n\tfor i := range ids {\n\t\teuo.ports[ids[i]] = struct{}{}\n\t}\n\treturn euo\n}", "func (ec *EmployeeCreate) AddMedicalfileIDs(ids ...int) *EmployeeCreate {\n\tec.mutation.AddMedicalfileIDs(ids...)\n\treturn ec\n}", "func (du *DayUpdate) AddWhatdayIDs(ids ...int) *DayUpdate {\n\tdu.mutation.AddWhatdayIDs(ids...)\n\treturn du\n}", "func (m *EmployeeMutation) AddAreaIDs(ids ...int) {\n\tif m.area == nil {\n\t\tm.area = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.area[ids[i]] = struct{}{}\n\t}\n}", "func (m *EmployeeMutation) AddAreaIDs(ids ...int) {\n\tif m.area == nil {\n\t\tm.area = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.area[ids[i]] = struct{}{}\n\t}\n}", "func (dc *DepartmentCreate) AddOfficeIDs(ids ...int) *DepartmentCreate {\n\tdc.mutation.AddOfficeIDs(ids...)\n\treturn dc\n}", "func (eu *EquipmentUpdate) AddPositionIDs(ids ...string) *EquipmentUpdate {\n\tif eu.positions == nil {\n\t\teu.positions = make(map[string]struct{})\n\t}\n\tfor i := range ids {\n\t\teu.positions[ids[i]] = struct{}{}\n\t}\n\treturn eu\n}", "func (m *EventMutation) AddedIDs(name string) []ent.Value {\n\tswitch name {\n\tcase event.EdgeRsvps:\n\t\tids := make([]ent.Value, 0, len(m.rsvps))\n\t\tfor id := range m.rsvps {\n\t\t\tids = append(ids, id)\n\t\t}\n\t\treturn ids\n\t}\n\treturn nil\n}", "func (puo *PetUpdateOne) AddFriendIDs(ids ...int) *PetUpdateOne {\n\tif puo.friends == nil {\n\t\tpuo.friends = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tpuo.friends[ids[i]] = struct{}{}\n\t}\n\treturn puo\n}", "func (ftc *FileTypeCreate) AddFileIDs(ids ...int) *FileTypeCreate {\n\tftc.mutation.AddFileIDs(ids...)\n\treturn ftc\n}", "func (m *SettlementMutation) AddHexIDs(ids ...int) {\n\tif m.hexes == nil {\n\t\tm.hexes = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.hexes[ids[i]] = struct{}{}\n\t}\n}", "func (dc *DentistCreate) AddAppointmentIDs(ids ...int) *DentistCreate {\n\tdc.mutation.AddAppointmentIDs(ids...)\n\treturn dc\n}", "func (du *DoctorUpdate) AddOfficeIDs(ids ...int) *DoctorUpdate {\n\tdu.mutation.AddOfficeIDs(ids...)\n\treturn du\n}", "func (bc *BlobCreate) AddLinkIDs(ids ...uuid.UUID) *BlobCreate {\n\tif bc.links == nil {\n\t\tbc.links = make(map[uuid.UUID]struct{})\n\t}\n\tfor i := range ids {\n\t\tbc.links[ids[i]] = struct{}{}\n\t}\n\treturn bc\n}", "func (m *DayMutation) AddWhatdayIDs(ids ...int) {\n\tif m.whatday == nil {\n\t\tm.whatday = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.whatday[ids[i]] = struct{}{}\n\t}\n}", "func (ttruo *TradeTimeRangeUpdateOne) AddRecordIDs(ids ...int) *TradeTimeRangeUpdateOne {\n\tttruo.mutation.AddRecordIDs(ids...)\n\treturn ttruo\n}", "func (duo *DayUpdateOne) AddWhatdayIDs(ids ...int) *DayUpdateOne {\n\tduo.mutation.AddWhatdayIDs(ids...)\n\treturn duo\n}", "func (m *DiseasetypeMutation) AddDiseaseIDs(ids ...int) {\n\tif m.disease == nil {\n\t\tm.disease = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.disease[ids[i]] = struct{}{}\n\t}\n}", "func (m *InviteePartyMutation) AddedIDs(name string) []ent.Value {\n\tswitch name {\n\tcase inviteeparty.EdgeInvitees:\n\t\tids := make([]ent.Value, 0, len(m.invitees))\n\t\tfor id := range m.invitees {\n\t\t\tids = append(ids, id)\n\t\t}\n\t\treturn ids\n\t}\n\treturn nil\n}", "func (m *PlaceMutation) AddedIDs(name string) []ent.Value {\n\tswitch name {\n\tcase place.EdgeEmployee:\n\t\tids := make([]ent.Value, 0, len(m.employee))\n\t\tfor id := range m.employee {\n\t\t\tids = append(ids, id)\n\t\t}\n\t\treturn ids\n\t}\n\treturn nil\n}", "func (pu *PetUpdate) AddFriendIDs(ids ...int) *PetUpdate {\n\tif pu.friends == nil {\n\t\tpu.friends = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tpu.friends[ids[i]] = struct{}{}\n\t}\n\treturn pu\n}" ]
[ "0.7959147", "0.7650785", "0.764343", "0.7574909", "0.7552359", "0.74618393", "0.7425623", "0.72158563", "0.72071666", "0.7135826", "0.713082", "0.7017985", "0.6889757", "0.67267936", "0.66681826", "0.6618952", "0.66037005", "0.6595512", "0.65914345", "0.65448225", "0.6507337", "0.6475952", "0.6454484", "0.63596165", "0.63408494", "0.6271009", "0.61881566", "0.615501", "0.6135905", "0.6097821", "0.6097821", "0.60771346", "0.6061708", "0.6061218", "0.6052823", "0.6047753", "0.6004384", "0.60038465", "0.59832406", "0.5958783", "0.5947494", "0.59322155", "0.5912124", "0.5904756", "0.5885826", "0.5885581", "0.5875436", "0.58678746", "0.58658653", "0.58629215", "0.58614457", "0.58594126", "0.58547115", "0.5849355", "0.5842881", "0.5837935", "0.5832597", "0.5829006", "0.5825436", "0.5784312", "0.5770432", "0.576794", "0.5757802", "0.57416195", "0.5732181", "0.5710047", "0.57019746", "0.56969154", "0.5692374", "0.5690834", "0.56880337", "0.56775093", "0.5647469", "0.5647423", "0.56370425", "0.5634456", "0.5627934", "0.5622214", "0.56197727", "0.5619034", "0.56130266", "0.56103456", "0.559478", "0.559478", "0.55929637", "0.55792475", "0.5576015", "0.5573719", "0.55594975", "0.5558037", "0.55341697", "0.5522941", "0.55170196", "0.550634", "0.5505548", "0.55045897", "0.5496806", "0.5491437", "0.54774487", "0.5469815" ]
0.7611659
3
AddEvents adds the events edges to Event.
func (ac *AppCreate) AddEvents(e ...*Event) *AppCreate { ids := make([]uuid.UUID, len(e)) for i := range e { ids[i] = e[i].ID } return ac.AddEventIDs(ids...) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func AddEvent(event Event) {\n\tEvents = append(Events, event)\n}", "func (lu *LibraryUpdate) AddEvents(e ...*Event) *LibraryUpdate {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn lu.AddEventIDs(ids...)\n}", "func (mnuo *MetricNameUpdateOne) AddEvents(e ...*Event) *MetricNameUpdateOne {\n\tids := make([]int, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn mnuo.AddEventIDs(ids...)\n}", "func (auo *AppUpdateOne) AddEvents(e ...*Event) *AppUpdateOne {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn auo.AddEventIDs(ids...)\n}", "func (luo *LibraryUpdateOne) AddEvents(e ...*Event) *LibraryUpdateOne {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn luo.AddEventIDs(ids...)\n}", "func (au *AppUpdate) AddEvents(e ...*Event) *AppUpdate {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn au.AddEventIDs(ids...)\n}", "func (mnu *MetricNameUpdate) AddEvents(e ...*Event) *MetricNameUpdate {\n\tids := make([]int, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn mnu.AddEventIDs(ids...)\n}", "func (o *SpanTagRemoval) AddEvents(ctx context.Context, events []*event.Event) error {\n\treturn o.next.AddEvents(ctx, events)\n}", "func (tuo *TimingUpdateOne) AddEvents(e ...*Event) *TimingUpdateOne {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn tuo.AddEventIDs(ids...)\n}", "func (tu *TimingUpdate) AddEvents(e ...*Event) *TimingUpdate {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn tu.AddEventIDs(ids...)\n}", "func (h *HistoCounter) AddEvents(ctx context.Context, events []*event.Event, next Sink) error {\n\th.EventBucket.Add(float64(len(events)))\n\treturn h.sink.AddEvents(ctx, events, next)\n}", "func (uc *UserCreate) AddEvents(e ...*Event) *UserCreate {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn uc.AddEventIDs(ids...)\n}", "func (duo *DeviceUpdateOne) AddEvents(e ...*Event) *DeviceUpdateOne {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn duo.AddEventIDs(ids...)\n}", "func (s *Simulation) AddEvent(e Event) {\n\ts.events = append(s.events, e)\n}", "func (du *DeviceUpdate) AddEvents(e ...*Event) *DeviceUpdate {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn du.AddEventIDs(ids...)\n}", "func (e *Event) AddEdge(ctx *Context) {\n\tC.oboe_event_add_edge(&e.event, &ctx.metadata)\n}", "func (events *Events) AddEvent(eventName string) *Listeners {\n\tlisteners := make(Listeners, 0)\n\teventsMutex.Lock()\n\t(*events)[eventName] = &listeners\n\teventsMutex.Unlock()\n\treturn &listeners\n}", "func (c *Counter) AddEvents(ctx context.Context, events []*event.Event, next Sink) error {\n\tatomic.AddInt64(&c.TotalEvents, int64(len(events)))\n\tatomic.AddInt64(&c.TotalProcessCalls, 1)\n\tatomic.AddInt64(&c.CallsInFlight, 1)\n\tstart := time.Now()\n\terr := next.AddEvents(ctx, events)\n\tatomic.AddInt64(&c.TotalProcessTimeNs, time.Since(start).Nanoseconds())\n\tatomic.AddInt64(&c.CallsInFlight, -1)\n\tif err != nil {\n\t\tatomic.AddInt64(&c.TotalProcessErrors, 1)\n\t\tatomic.AddInt64(&c.ProcessErrorEvents, int64(len(events)))\n\t\tc.logErrMsg(ctx, err, \"Unable to process events\")\n\t}\n\treturn err\n}", "func (_m *Entity) AddEvent(events ...core.Event) {\n\t_va := make([]interface{}, len(events))\n\tfor _i := range events {\n\t\t_va[_i] = events[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, _va...)\n\t_m.Called(_ca...)\n}", "func AddNewEvent(event eventinfo.Info) {\n\teventList = append(eventList, event)\n}", "func (tr *EventRepository) AddEvent(ev *model.Event) {\n\ttr.locationCountry.Incr(ev.Location.Country)\n\ttr.locationCity.Incr(ev.Location.City)\n\ttr.deviceType.Incr(ev.Device.Type)\n\ttr.devicePlatform.Incr(ev.Device.Platform)\n\ttr.deviceOS.Incr(ev.Device.OS)\n\ttr.deviceBrowser.Incr(ev.Device.Browser)\n\ttr.deviceLanguage.Incr(ev.Device.Language)\n\ttr.referral.Incr(ev.Referral)\n}", "func (c *TestProjectConfig) AddEvent(e entities.Event) *TestProjectConfig {\n\tc.EventMap[e.Key] = e\n\treturn c\n}", "func (e *eventProcessor) AddEvent(eventType string, table string, old Model, new Model) {\n\t// We don't need to check for error here since there\n\t// is only a single writer. RPC is run in blocking mode\n\tevent := event{\n\t\teventType: eventType,\n\t\ttable: table,\n\t\told: old,\n\t\tnew: new,\n\t}\n\tselect {\n\tcase e.events <- event:\n\t\t// noop\n\t\treturn\n\tdefault:\n\t\tlog.Print(\"dropping event because event buffer is full\")\n\t}\n}", "func (ic *InstanceCreate) AddEventlisteners(e ...*Events) *InstanceCreate {\n\tids := make([]uuid.UUID, len(e))\n\tfor i := range e {\n\t\tids[i] = e[i].ID\n\t}\n\treturn ic.AddEventlistenerIDs(ids...)\n}", "func (t *Timeline) addEvents(events []*pb.TimelineEvent) {\n\tt.events = append(t.events, events...)\n\tt.filterDuplicates()\n\tsort.Sort(byTimestamp(t.events))\n\n\t// remove events oldest events if timeline is over capacity.\n\tindex := len(t.events) - t.capacity\n\tif index > 0 {\n\t\tt.events = t.events[index:]\n\t}\n}", "func (c *Calendar) Add(e Event) {\n\tc.Events = append(c.Events, e)\n}", "func (el *Log) AddEvent(eventType Type, srv server.Server, bootType string, script string, params map[string]interface{}) {\n\tif el.Events == nil {\n\t\tel.Events = make(map[string][]Event)\n\t}\n\n\tel.Events[srv.Mac] = append(el.Events[srv.Mac], New(eventType, srv, bootType, script, params))\n}", "func (s *Schedule) AddEvent(event Event) {\n\tif s.events == nil {\n\t\ts.events = make(map[string][]Event)\n\t}\n\ts.events[event.Type] = append(s.events[event.Type], event)\n}", "func AddEvent(event Event) Event {\n\tsession, _ := mgo.Dial(\"127.0.0.1\")\n\tdefer session.Close()\n\tsession.SetMode(mgo.Monotonic, true)\n\tdb := session.DB(\"insapp\").C(\"event\")\n\tdb.Insert(event)\n\tvar result Event\n\tdb.Find(bson.M{\"name\": event.Name, \"datestart\": event.DateStart}).One(&result)\n\tAddEventToAssociation(result.Association, result.ID)\n\treturn result\n}", "func (l *ChainLedger) AddEvent(event *pb.Event) {\n\thash := event.TxHash.Hex()\n\tl.events[hash] = append(l.events[hash], event)\n}", "func (l *ChainLedger) AddEvent(event *pb.Event) {\n\thash := event.TxHash.Hex()\n\tl.events[hash] = append(l.events[hash], event)\n}", "func (c *ContractMD) AddEvent(name string, ps ...manifest.Parameter) {\n\tc.Manifest.ABI.Events = append(c.Manifest.ABI.Events, manifest.Event{\n\t\tName: name,\n\t\tParameters: ps,\n\t})\n}", "func AddEvent(event *entity.Event)(*entity.Event, error){\n\touput,err:= json.MarshalIndent(event,\"\",\"\\t\\t\")\n\n\tclient := &http.Client{}\n\tURL := fmt.Sprintf(\"%s%s\",baseEventURL,\"create\")\n\n\treq,_ := http.NewRequest(\"POST\",URL,bytes.NewBuffer(ouput) )\n\tres,err := client.Do(req)\n\t\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tevvent := &entity.Event{}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(body,evvent)\n\tif err != nil{\n\t\treturn nil,err\n\t}\n\treturn evvent,nil\n}", "func AddEvent(c *gin.Context) {\n\tvar inp model.Event\n\n\tc.BindJSON(&inp)\n\tc.JSON(http.StatusOK, serviceEvent.AddEvent(&inp))\n}", "func (c *Collection) AddEvent(\n\tkey, typ string, value interface{},\n) (*Event, error) {\n\treturn c.innerAddEvent(key, typ, nil, value)\n}", "func (evts *Events) Add(t string, qk geonet.Quake, updatedFields ...[]string) {\n\tevt := Event{\n\t\tType: t,\n\t\tQuake: qk,\n\t}\n\n\tif len(updatedFields) > 0 {\n\t\tevt.UpdatedFields = updatedFields[0]\n\t}\n\n\t*evts = append(*evts, evt)\n}", "func (e *RateLimitErrorLogging) AddEvents(ctx context.Context, points []*event.Event, next Sink) error {\n\terr := next.AddEvents(ctx, points)\n\tif err != nil {\n\t\tnow := time.Now()\n\t\tlastLogTimeNs := atomic.LoadInt64(&e.lastLogTimeNs)\n\t\tsinceLastLogNs := now.UnixNano() - lastLogTimeNs\n\t\tif sinceLastLogNs > e.LogThrottle.Nanoseconds() {\n\t\t\tnowUnixNs := now.UnixNano()\n\t\t\tif atomic.CompareAndSwapInt64(&e.lastLogTimeNs, lastLogTimeNs, nowUnixNs) {\n\t\t\t\te.Callback(err)\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}", "func (domain *Domain) AddEvent(event *Event) error {\n\t// check if event has already been defined\n\tdomain.EventsX.RLock()\n\t_, ok := domain.Events[event.UUID]\n\tdomain.EventsX.RUnlock()\n\n\tif ok {\n\t\treturn errors.New(\"event already exists\")\n\t}\n\n\tdomain.EventsX.Lock()\n\tdomain.Events[event.UUID] = event\n\tdomain.EventsX.Unlock()\n\n\t// register with tasks\n\tdomain.TasksX.Lock()\n\ttask := domain.Tasks[event.Task]\n\ttask.AddEvent(event)\n\tdomain.TasksX.Unlock()\n\n\t// register with tasks\n\tif event.Source != \"\" {\n\t\tdomain.TasksX.Lock()\n\t\ttask = domain.Tasks[event.Source]\n\t\ttask.AddEvent(event)\n\t\tdomain.TasksX.Unlock()\n\t}\n\n\t// success\n\treturn nil\n}", "func (hc *HandleCalendar) AddEvent(w http.ResponseWriter, r *http.Request) {\n\tdefer r.Body.Close()\n\n\tvar evt event.Event\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\terr = json.Unmarshal(b, &evt)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tjson.NewEncoder(w).Encode(err.Error())\n\t\treturn\n\t}\n\t_, err = hc.Calendar.AddEvent(evt)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(err.Error())\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n\tjson.NewEncoder(w).Encode(evt)\n}", "func NewEvents() *Events {\n\treturn &Events{\n\t\tdeploymentSubscribers: make(map[int64]chan Deployment),\n\t}\n}", "func (app *manager) Add(evt Event) error {\n\tlength := len(app.evts)\n\tid := evt.Identifier()\n\tkeyname := evt.Hash().String()\n\n\tif id < length {\n\t\tif _, ok := app.evts[id][keyname]; ok {\n\t\t\tstr := fmt.Sprintf(\"the event (identifier: %d, hash: %s) already exists\", id, keyname)\n\t\t\treturn errors.New(str)\n\t\t}\n\n\t\tapp.evts[id][keyname] = evt\n\t\treturn nil\n\t}\n\n\tdiff := (id - length) + 1\n\tfor i := 0; i < diff; i++ {\n\t\tapp.evts = append(app.evts, map[string]Event{})\n\t}\n\n\tapp.evts[id][keyname] = evt\n\treturn nil\n}", "func (auo *AppUpdateOne) AddEventIDs(ids ...uuid.UUID) *AppUpdateOne {\n\tauo.mutation.AddEventIDs(ids...)\n\treturn auo\n}", "func AddEvent(ctx context.Context, evt *model.Event) (err error) {\n\t_, err = EventsCollection.InsertOne(ctx, evt)\n\treturn err\n}", "func (m *Metrics) AddEvent(e *log.Event, outlier bool) {\n\n\tfor metric, val := range e.TimeMetrics {\n\t\tstats, seenMetric := m.TimeMetrics[metric]\n\t\tif !seenMetric {\n\t\t\tm.TimeMetrics[metric] = &TimeStats{\n\t\t\t\tvals: []float64{},\n\t\t\t}\n\t\t\tstats = m.TimeMetrics[metric]\n\t\t}\n\t\tif outlier {\n\t\t\tstats.outlierSum += val\n\t\t} else {\n\t\t\tstats.Sum += val\n\t\t}\n\t\tstats.vals = append(stats.vals, float64(val))\n\t}\n\n\tfor metric, val := range e.NumberMetrics {\n\t\tstats, seenMetric := m.NumberMetrics[metric]\n\t\tif !seenMetric {\n\t\t\tm.NumberMetrics[metric] = &NumberStats{\n\t\t\t\tvals: []uint64{},\n\t\t\t}\n\t\t\tstats = m.NumberMetrics[metric]\n\t\t}\n\t\tif outlier {\n\t\t\tstats.outlierSum += val\n\t\t} else {\n\t\t\tstats.Sum += val\n\t\t}\n\t\tstats.vals = append(stats.vals, val)\n\t}\n\n\tfor metric, val := range e.BoolMetrics {\n\t\tstats, seenMetric := m.BoolMetrics[metric]\n\t\tif !seenMetric {\n\t\t\tstats = &BoolStats{}\n\t\t\tm.BoolMetrics[metric] = stats\n\t\t}\n\t\tif val {\n\t\t\tif outlier {\n\t\t\t\tstats.outlierSum += 1\n\t\t\t} else {\n\t\t\t\tstats.Sum += 1\n\t\t\t}\n\t\t}\n\t\tstats.vals = append(stats.vals, val)\n\t}\n}", "func (store Manager) AddEvent(eventtype, details string, ip string, expiresafter time.Duration) (Event, error) {\n\t//\tOur return item\n\tretval := Event{}\n\n\tnewEvent := Event{\n\t\tID: xid.New().String(), // Generate a new id\n\t\tCreated: time.Now(),\n\t\tSourceIP: ip,\n\t\tEventType: eventtype,\n\t\tDetails: details,\n\t}\n\n\t//\tSerialize to JSON format\n\tencoded, err := json.Marshal(newEvent)\n\tif err != nil {\n\t\treturn retval, fmt.Errorf(\"problem serializing the data: %s\", err)\n\t}\n\n\t//\tSave it to the database:\n\terr = store.systemdb.Update(func(tx *buntdb.Tx) error {\n\t\t_, _, err := tx.Set(GetKey(\"Event\", newEvent.ID), string(encoded), &buntdb.SetOptions{Expires: true, TTL: expiresafter})\n\t\treturn err\n\t})\n\n\t//\tIf there was an error saving the data, report it:\n\tif err != nil {\n\t\treturn retval, fmt.Errorf(\"problem saving the event: %s\", err)\n\t}\n\n\t//\tSet our retval:\n\tretval = newEvent\n\n\t//\tReturn our data:\n\treturn retval, nil\n}", "func (b *BaseElement) SetEvents(e Events) {\n\tb.Events = e\n}", "func (luo *LibraryUpdateOne) AddEventIDs(ids ...uuid.UUID) *LibraryUpdateOne {\n\tluo.mutation.AddEventIDs(ids...)\n\treturn luo\n}", "func AddEventReqToEventModels(addRequests []AddEventRequest) (events []models.Event) {\n\tfor _, a := range addRequests {\n\t\tvar e models.Event\n\t\treadings := make([]models.Reading, len(a.Event.Readings))\n\t\tfor i, r := range a.Event.Readings {\n\t\t\treadings[i] = dtos.ToReadingModel(r)\n\t\t}\n\n\t\ttags := make(map[string]string)\n\t\tfor tag, value := range a.Event.Tags {\n\t\t\ttags[tag] = value\n\t\t}\n\n\t\te.Id = a.Event.Id\n\t\te.DeviceName = a.Event.DeviceName\n\t\te.Origin = a.Event.Origin\n\t\te.Readings = readings\n\t\te.Tags = tags\n\t\tevents = append(events, e)\n\t}\n\treturn events\n}", "func (o *InlineResponse20075Stats) SetEvents(v InlineResponse20075StatsEvents) {\n\to.Events = &v\n}", "func (hook Webhook) RegisterEvents(fn webhooks.ProcessPayloadFunc, events ...Event) {\n\n\tfor _, event := range events {\n\t\thook.eventFuncs[event] = fn\n\t}\n}", "func (m *InviteeMutation) AddEventIDs(ids ...int) {\n\tif m.events == nil {\n\t\tm.events = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.events[ids[i]] = struct{}{}\n\t}\n}", "func (r *Report) AddEvent(event *Event) {\n\tfor _, e := range r.Events {\n\t\tif e.Question == event.Question {\n\t\t\te.Response = event.Response\n\t\t\te.TS = event.TS\n\t\t\treturn\n\t\t}\n\t}\n\tr.Events = append(r.Events, event)\n}", "func (d *DbHandle) AddEvent(n NotifRec) error {\n\t// convert hub time to UTC\n\tn.EvTime = time.Unix(n.EvTime, 0).Unix()\n\tlog.WithField(\"rec\", n).Debug(\"insert record\")\n\t_, err := d.addStmt.Exec(n.Device, n.EvTime, n.Event, n.Value, n.Description)\n\treturn err\n}", "func (gc *GameCreate) SetEvents(s []string) *GameCreate {\n\tgc.mutation.SetEvents(s)\n\treturn gc\n}", "func (g *EWgraph) AddEdge(e Edge) {\n\tg.edges = append(g.edges, e)\n\tv := e.Either()\n\tw := e.Other(v)\n\tg.adj[v] = append(g.adj[v], e)\n\tg.adj[w] = append(g.adj[w], e)\n}", "func (_VinTracker *VinTrackerTransactor) AddEvent(opts *bind.TransactOpts, vin string, action string) (*types.Transaction, error) {\n\treturn _VinTracker.contract.Transact(opts, \"addEvent\", vin, action)\n}", "func (lu *LibraryUpdate) AddEventIDs(ids ...uuid.UUID) *LibraryUpdate {\n\tlu.mutation.AddEventIDs(ids...)\n\treturn lu\n}", "func (ac *AppCreate) AddEventIDs(ids ...uuid.UUID) *AppCreate {\n\tac.mutation.AddEventIDs(ids...)\n\treturn ac\n}", "func (d TinkDB) AddEvent(resourceID string, resourceType, eventType int32, data []byte) {\n\ttx, err := d.instance.BeginTx(context.TODO(), &sql.TxOptions{Isolation: sql.LevelSerializable})\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\n\t_, err = tx.Exec(`\n\tINSERT INTO\n\t\tevents (id, resource_id, resource_type, event_type, data, created_at)\n\tVALUES\n\t\t($1, $2, $3, $4, $5, $6)\n\t`, uuid.New(), resourceID, resourceType, eventType, data, time.Now())\n\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n}", "func (au *AppUpdate) AddEventIDs(ids ...uuid.UUID) *AppUpdate {\n\tau.mutation.AddEventIDs(ids...)\n\treturn au\n}", "func AddEvent(startTime time.Time, endTime time.Time, place int, description string, lections []int) (int, error) {\n\ttx, err := dbConn.Begin()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar eventID int\n\tqEvents := \"INSERT INTO events (starttime, endtime, place, description) VALUES ($1, $2, $3, $4) RETURNING id\"\n\terr = tx.QueryRow(qEvents, startTime, endTime, place, description).Scan(&eventID)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn 0, err\n\t}\n\tfor _, lection := range lections {\n\t\t_, err = tx.Exec(\"INSERT INTO event_lections (id_event, id_lection) VALUES ($1, $2)\", eventID, lection)\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn 0, err\n\t\t}\n\t}\n\terr = tx.Commit()\n\treturn eventID, err\n}", "func (s *Service) SetEvents(v []*ServiceEvent) *Service {\n\ts.Events = v\n\treturn s\n}", "func (_VinTracker *VinTrackerSession) AddEvent(vin string, action string) (*types.Transaction, error) {\n\treturn _VinTracker.Contract.AddEvent(&_VinTracker.TransactOpts, vin, action)\n}", "func (_VinTracker *VinTrackerTransactorSession) AddEvent(vin string, action string) (*types.Transaction, error) {\n\treturn _VinTracker.Contract.AddEvent(&_VinTracker.TransactOpts, vin, action)\n}", "func NewEvents(eventManager interfaces.EventManager) *Events {\n\treturn &Events{\n\t\teventManager: eventManager,\n\t}\n}", "func (client *Client) AddEventsListener(channel EventsChannel, filter int) error {\n\tclient.Lock()\n\tdefer client.Unlock()\n\t// step: someone has asked to start listening to event, we need to register for events\n\t// if we haven't done so already\n\tif err := client.RegisterSubscription(); err != nil {\n\t\treturn err\n\t}\n\n\tif _, found := client.listeners[channel]; !found {\n\t\tclient.log(\"AddEventsListener() Adding a watch for events: %d, channel: %v\", filter, channel)\n\t\tclient.listeners[channel] = filter\n\t}\n\treturn nil\n}", "func (s *ListTransactionEventsOutput) SetEvents(v []*TransactionEvent) *ListTransactionEventsOutput {\n\ts.Events = v\n\treturn s\n}", "func AddEvent(Event model.Event) EventResponse {\n\tlog.Println(\"Add event service initialize\")\n\tRequiredEventType := []string{\"warning\", \"error\"}\n\n\t// call model to create a event\n\teventData := model.AddEvent(Event)\n\n\t_, found := Find(RequiredEventType, Event.EventType)\n\n\tif found {\n\t\t// sending notification\n\t\tgo SendNotification()\n\n\t\t// call instance api\n\t\tutilitieEventString, _ := json.Marshal(eventData)\n\t\tgo utilities.CallInstanceAPI(utilitieEventString)\n\n\t}\n\n\t//create response to send a controller\n\teventsResponse := EventResponse{true, eventData}\n\n\treturn eventsResponse\n\n}", "func AddEdge(caller *Node, site ssa.CallInstruction, callee *Node) {\n\te := &Edge{caller, site, callee}\n\tcallee.In = append(callee.In, e)\n\tcaller.Out = append(caller.Out, e)\n}", "func (engine *ECE) AddEvent(message string) (err error) {\n\twaf, err := UnmarshalWaf(message) // Try to unmarshal the message into a WAF event\n\tif err != nil { // It didn't unmarshal. It's either a req event, or garbage\n\t\treq, err := UnmarshalWeb(message)\n\n\t\tif err != nil { // It didn't unmarshal as a req event either.\n\t\t\terr = fmt.Errorf(\"unparsable data: %s\", message)\n\t\t\treturn err\n\t\t}\n\n\t\t//log.Printf(\"WEb Event ID: %q\", waf.RequestId)\n\n\t\tevent := engine.RetrieveEvent(req.RequestId)\n\n\t\tif event == nil { // It doesn't exist, create it and set it's lifetime\n\t\t\tevent := Event{\n\t\t\t\tWafEntries: make([]WafEntry, 0),\n\t\t\t\tRequestEntries: make([]RequestEntry, 0),\n\t\t\t}\n\n\t\t\tevent.RequestEntries = append(event.RequestEntries, req)\n\n\t\t\t//fmt.Printf(\"New Web %q\\n\", req.RequestId)\n\t\t\tengine.Lock()\n\t\t\tengine.Events[req.RequestId] = &event\n\t\t\tengine.Unlock()\n\n\t\t\t// then set it to notify after ttl expires\n\t\t\tgo DelayNotify(engine, req.RequestId)\n\n\t\t\treturn err\n\t\t}\n\n\t\t// it does exist, add to it's req list\n\t\tengine.Lock()\n\t\t//fmt.Printf(\"\\tAdding Web to %q\\n\", req.RequestId)\n\t\tevent.RequestEntries = append(event.RequestEntries, req)\n\t\tengine.Unlock()\n\n\t\treturn err\n\t}\n\n\t// Ok, it's a Waf event. Process it as such.\n\tevent := engine.RetrieveEvent(waf.RequestId)\n\n\tif event == nil { // It doesn't exist, create it and set it's lifetime\n\t\tevent := Event{\n\t\t\tWafEntries: make([]WafEntry, 0),\n\t\t\tRequestEntries: make([]RequestEntry, 0),\n\t\t}\n\n\t\tevent.WafEntries = append(event.WafEntries, waf)\n\n\t\t//fmt.Printf(\"New Waf %q\\n\", waf.RequestId)\n\t\tengine.Lock()\n\t\tengine.Events[waf.RequestId] = &event\n\t\tengine.Unlock()\n\n\t\t// then set it to notify after ttl expires\n\t\tgo DelayNotify(engine, waf.RequestId)\n\n\t\treturn err\n\t}\n\n\t// it does exist, add to it's waf list\n\t//fmt.Printf(\"\\tAdding Waf to %q\\n\", waf.RequestId)\n\tengine.Lock()\n\tevent.WafEntries = append(event.WafEntries, waf)\n\tengine.Unlock()\n\n\treturn err\n}", "func (c *AnalyticsController) AddEvent(ev *analyticsEvent) error {\n\tqLog := log.WithFields(log.Fields{\n\t\t\"name\": ev.event,\n\t\t\"objectName\": ev.objectName,\n\t\t\"objectKind\": ev.objectKind,\n\t\t\"objectNamespace\": ev.objectNamespace,\n\t\t\"objectUID\": ev.objectUID,\n\t\t\"eventTimestamp\": ev.timestamp,\n\t})\n\n\tif len(c.queue.ListKeys()) > c.maximumQueueLength {\n\t\treturn fmt.Errorf(\"analyticEvent rejected, exceeds maximum queue length: %d - %#v\", c.maximumQueueLength, ev)\n\t}\n\tif ev.timestamp.UnixNano() < c.startTime {\n\t\tqLog.WithFields(log.Fields{\"started\": c.startTime}).Debug(\"skipping analytic event older than controller start time\")\n\t\treturn nil\n\t}\n\n\tfor destName := range c.destinations {\n\t\tev.destination = destName // needed here to find default ID by destination\n\t\tuserId, err := c.getUserId(ev)\n\n\t\tif err != nil {\n\t\t\tswitch err.reason {\n\t\t\tcase missingProjectError, requesterAnnotationNotFoundError:\n\t\t\t\t// TODO: maintain a list of projects we exclude from analytics,\n\t\t\t\t// and consider this expected for those, a warning for others:\n\t\t\t\tqLog.Infoln(err.message)\n\t\t\tcase userNotFoundError, noIDFoundError:\n\t\t\t\tqLog.Debugln(err.message)\n\t\t\tdefault:\n\t\t\t\tqLog.WithFields(log.Fields{\n\t\t\t\t\t\"reason\": err.reason,\n\t\t\t\t\t\"message\": err.message,\n\t\t\t\t}).Warn(\"unexpected error getting user ID\")\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tqLog = qLog.WithFields(log.Fields{\"user\": userId})\n\t\tqLog.Debug(\"adding analytic event to queue\")\n\n\t\te := &analyticsEvent{\n\t\t\tuserID: userId,\n\t\t\tevent: ev.event,\n\t\t\tobjectKind: ev.objectKind,\n\t\t\tobjectName: ev.objectName,\n\t\t\tobjectNamespace: ev.objectNamespace,\n\t\t\tobjectUID: ev.objectUID,\n\t\t\tproperties: make(map[string]string),\n\t\t\tannotations: make(map[string]string),\n\t\t\ttimestamp: ev.timestamp,\n\t\t\tdestination: destName,\n\t\t\tclusterName: c.clusterName,\n\t\t\tcontrollerID: c.controllerID,\n\t\t}\n\t\tfor key, value := range ev.properties {\n\t\t\te.properties[key] = value\n\t\t}\n\t\tfor key, value := range ev.annotations {\n\t\t\te.annotations[key] = value\n\t\t}\n\n\t\tc.queue.Add(e)\n\t}\n\n\treturn nil\n}", "func (g *Graph) AddEdge(e *Edge) {\n\tg.Edges[e.ID] = e\n\n\tfor from := range e.Froms {\n\t\tif g.hasVertex(from) {\n\t\t\tg.Connect(from, e.ID, e.Label)\n\t\t\tg.Connect(e.ID, from, \"~\"+e.Label) // store inverse relation\n\t\t}\n\t}\n\n\tfor to := range e.Tos {\n\t\tif g.hasVertex(to) {\n\t\t\tg.Connect(e.ID, to, e.Label)\n\t\t\tg.Connect(to, e.ID, \"~\"+e.Label) // store inverse relation\n\t\t}\n\t}\n}", "func (g *mutableUndirected) AddEdges(edges ...Edge) {\n\tif len(edges) == 0 {\n\t\treturn\n\t}\n\n\tg.mu.Lock()\n\tdefer g.mu.Unlock()\n\n\tg.addEdges(edges...)\n}", "func (app *builder) WithEventParams(params []ToEventsParams) Builder {\n\tapp.params = params\n\treturn app\n}", "func (es *EventService) Add(e *Event) (string, error) {\n\t// POST: /events\n\tif e == nil {\n\t\treturn \"\", fmt.Errorf(\"nil Event\")\n\t}\n\treq, err := es.c.NewRequest(\"POST\", \"/events\", e)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresp := struct {\n\t\tStatus string\n\t\tData struct {\n\t\t\tID string\n\t\t}\n\t\tMessage string\n\t}{}\n\n\terr = es.c.Do(req, &resp)\n\treturn resp.Data.ID, err\n}", "func (mr *MockHandlerMockRecorder) AddEvent(ctx, clusterID, hostID, severity, msg, eventTime interface{}, props ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx, clusterID, hostID, severity, msg, eventTime}, props...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddEvent\", reflect.TypeOf((*MockHandler)(nil).AddEvent), varargs...)\n}", "func (l *Linear) AppendTrackingEvents(trackingEvents []Tracking) {\n\tl.TrackingEvents = append(l.TrackingEvents, trackingEvents...)\n}", "func (duo *DeviceUpdateOne) AddEventIDs(ids ...uuid.UUID) *DeviceUpdateOne {\n\tduo.mutation.AddEventIDs(ids...)\n\treturn duo\n}", "func (er *EventRouter) addEvent(obj interface{}) {\n\te := obj.(*v1.Event)\n\tprometheusEvent(e, er)\n\n\t// e returns true before t\n\t// 如果时间的创建时间再当前时间之前\n\tif (e.CreationTimestamp).Before(&nowtime) {\n\t\treturn\n\t}\n\n\terr := store.DefaultMongoStore.Insert(er.Clustername, e)\n\tif nil != err {\n\t\tlog.Warn(\"insert event %s error %s\", e.Name, err.Error())\n\t}\n}", "func (es *EventStore) AddEvent(event *UnaddedEvent) (string, error) {\n\tstart := time.Now()\n\tdefer func() {\n\t\tmetrics.EventStoreLatency(\"AddEvent\", start)\n\t}()\n\n\tevt, err := es.augmentEvent(event)\n\tif err != nil {\n\t\treturn \"\", jh.NewError(errors.Wrap(err, \"augmenting event\").Error(), http.StatusBadRequest)\n\t}\n\n\tif err = es.ds.AddEvent(evt); err != nil {\n\t\tmetrics.DBError(\"write\")\n\t\treturn \"\", errors.Wrap(err, \"Error executing insert query\")\n\t}\n\n\treturn evt.EventID, nil\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 AddEvent(startTime time.Time, endTime time.Time, place int, description string, lectures []int) (int, error) {\n\ttx, err := dbConn.Begin()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar eventID int\n\tqEvents := \"INSERT INTO events (starttime, endtime, place, description) VALUES ($1, $2, $3, $4) RETURNING id\"\n\terr = tx.QueryRow(qEvents, startTime, endTime, place, description).Scan(&eventID)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn 0, err\n\t}\n\tfor _, lecture := range lectures {\n\t\t_, err = tx.Exec(\"INSERT INTO event_lectures (id_event, id_lecture) VALUES ($1, $2)\", eventID, lecture)\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn 0, err\n\t\t}\n\t}\n\terr = tx.Commit()\n\treturn eventID, err\n}", "func (s *RepositorySyncAttempt) SetEvents(v []*RepositorySyncEvent) *RepositorySyncAttempt {\n\ts.Events = v\n\treturn s\n}", "func (wg *WeightGraph) AddEdge(e Edge) {\n\twg.adj[e.from] = append(wg.adj[e.from], e)\n\twg.adj[e.to] = append(wg.adj[e.to], e)\n\twg.e++\n}", "func (G *Graph) AddEdge(n1, n2 *Node) {\r\n\tif G.edges == nil {\r\n\t\tG.edges = make(map[Node][]*Node)\r\n\t}\r\n\t// for undirected graph, execute both statements - undirected edges are a two-way street\r\n\t// for a directed graph, only run the first statement - directed edges only go one direction\r\n\tG.edges[*n1] = append(G.edges[*n1], n2)\r\n\t// G.edges[*n2] = append(G.edges[*n2], n1)\r\n}", "func (m *EventRSVPMutation) AddedEdges() []string {\n\tedges := make([]string, 0, 2)\n\tif m.event != nil {\n\t\tedges = append(edges, eventrsvp.EdgeEvent)\n\t}\n\tif m.invitee != nil {\n\t\tedges = append(edges, eventrsvp.EdgeInvitee)\n\t}\n\treturn edges\n}", "func AddEventToCalendar(reoccurance string, attendies []string) error {\n\tvar (\n\t\tsummary string\n\t\tlocation string\n\t\tdescription string\n\t\tstartTime string\n\t\tendTime string\n\t)\n\ttokFile := \"token.json\"\n\t_, err := tokenFromFile(tokFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient, err := GetClientToken()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"gCalendar\")\n\tfmt.Println(\"Creating a new event.... \\n\")\n\tfmt.Println(\"What is the summary of the event?\")\n\treader := bufio.NewReader(os.Stdin)\n\tsummary, err = reader.ReadString('\\n')\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"Where is the event going to take place?\")\n\tlocation, err = reader.ReadString('\\n')\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"Please enter the description of the event\")\n\tdescription, err = reader.ReadString('\\n')\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"What time does the event start? eg. 2006-01-02 15:00:00\")\n\tstartTime, err = reader.ReadString('\\n')\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"What time does the event end? eg. 2006-01-02 15:00:00\")\n\tendTime, err = reader.ReadString('\\n')\n\tif err != nil {\n\t\treturn err\n\t}\n\tsrv, err := calendar.New(client)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to retrieve Calendar client: %v\", err)\n\t}\n\tlayout := \"2006-01-02 15:04:05\"\n\tstartDate, err := time.Parse(layout, startTime[:len(startTime)-1])\n\tif err != nil {\n\t\treturn err\n\t}\n\tendDate, err := time.Parse(layout, endTime[:len(endTime)-1])\n\tif err != nil {\n\t\treturn err\n\t}\n\tevent := &calendar.Event{\n\t\tSummary: summary,\n\t\tLocation: location,\n\t\tDescription: description,\n\t\tStart: &calendar.EventDateTime{\n\t\t\tDateTime: startDate.Format(time.RFC3339),\n\t\t\tTimeZone: \"America/Los_Angeles\",\n\t\t},\n\t\tEnd: &calendar.EventDateTime{\n\t\t\tDateTime: endDate.Format(time.RFC3339),\n\t\t\tTimeZone: \"America/Los_Angeles\",\n\t\t},\n\t}\n\tif reoccurance != \"\" {\n\t\tevent.Recurrence = []string{reoccurance}\n\t}\n\tif len(attendies) > 0 {\n\t\tvar emails []*calendar.EventAttendee\n\t\tfor _, attendie := range attendies {\n\t\t\temails = append(emails, &calendar.EventAttendee{\n\t\t\t\tEmail: attendie,\n\t\t\t})\n\t\t}\n\t\tevent.Attendees = emails\n\t}\n\t_, err = srv.Events.Insert(\"primary\", event).Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Print(\"\\nEvent is being added.. \\n\")\n\treturn nil\n}", "func (g *Graph) AddEdge(node1, node2 *GraphNode) {\n\tnode1.edges = append(node1.edges, node2)\n}", "func (du *DeviceUpdate) AddEventIDs(ids ...uuid.UUID) *DeviceUpdate {\n\tdu.mutation.AddEventIDs(ids...)\n\treturn du\n}", "func (s *Store) AddEvent(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\tdefer closeBody(ctx, r.Body)\n\n\tvars := mux.Vars(r)\n\tinstanceID := vars[\"instance_id\"]\n\teTag := getIfMatch(r)\n\tdata := log.Data{\"instance_id\": instanceID, \"action\": AddInstanceEventAction}\n\n\tevent, err := unmarshalEvent(r.Body)\n\tif err != nil {\n\t\tlog.Error(ctx, \"add instance event: failed to unmarshal request body\", err, data)\n\t\thandleInstanceErr(ctx, err, w, data)\n\t\treturn\n\t}\n\n\tif err = event.Validate(); err != nil {\n\t\tlog.Error(ctx, \"add instance event: failed to validate event object\", err, data)\n\t\thandleInstanceErr(ctx, err, w, data)\n\t\treturn\n\t}\n\n\t// Acquire instance lock to make sure that this call does not interfere with any other 'write' call against the same instance\n\tlockID, err := s.AcquireInstanceLock(ctx, instanceID)\n\tif err != nil {\n\t\thandleInstanceErr(ctx, err, w, data)\n\t}\n\tdefer s.UnlockInstance(ctx, lockID)\n\n\tinstance, err := s.GetInstance(ctx, instanceID, eTag)\n\tif err != nil {\n\t\tlog.Error(ctx, \"add instance event: failed to get instance from datastore\", err, data)\n\t\thandleInstanceErr(ctx, err, w, data)\n\t\treturn\n\t}\n\n\tnewETag, err := s.AddEventToInstance(ctx, instance, event, eTag)\n\tif err != nil {\n\t\tlog.Error(ctx, \"add instance event: failed to add event to instance in datastore\", err, data)\n\t\thandleInstanceErr(ctx, err, w, data)\n\t\treturn\n\t}\n\n\tlog.Info(ctx, \"add instance event: request successful\", data)\n\tdpresponse.SetETag(w, newETag)\n}", "func (b *Builder) addEventRelation(srcName string, dstName string, eventType proto.EventType) error {\n\tsrcInfo, err := b.getProcessorInfo(srcName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdstInfo, err := b.getProcessorInfo(dstName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsink := processor.NewSink(dstInfo.instance.GetTap())\n\terr = srcInfo.instance.AddEventSink(eventType, sink)\n\treturn err\n}", "func (mnuo *MetricNameUpdateOne) AddEventIDs(ids ...int) *MetricNameUpdateOne {\n\tmnuo.mutation.AddEventIDs(ids...)\n\treturn mnuo\n}", "func EventCreate(ctx *gin.Context) {\n\tvar user *model.User\n\tif userInterface, exists := ctx.Get(\"User\"); !exists {\n\t\tmisc.ReturnStandardError(ctx, http.StatusForbidden, \"you have to be a registered user to create event\")\n\t\treturn\n\t} else {\n\t\tuser = userInterface.(*model.User)\n\t}\n\tevent := &model.Event{}\n\tphysicalLocation := &model.PhysicalLocation{}\n\tonlineLocation := &model.OnlineLocation{}\n\tif err := jsonapi.UnmarshalPayload(ctx.Request.Body, event); err != nil {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"cannot unmarshal JSON of request: \"+err.Error())\n\t\treturn\n\t} else if event.Title == nil ||\n\t\tevent.TimeBegin == nil ||\n\t\tevent.TimeEnd == nil ||\n\t\tevent.Type == nil ||\n\t\treflect.ValueOf(event.Location).IsNil() {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"not all fields required are provided\")\n\t\treturn\n\t} else if eventType, exists := event.Location.(map[string]interface{})[\"type\"]; !exists || (eventType != \"physical\" && eventType != \"online\") {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"illegal event type\")\n\t\treturn\n\t} else if eventType == \"physical\" &&\n\t\t(mapstructure.Decode(event.Location, physicalLocation) != nil ||\n\t\t\tphysicalLocation.Address == \"\" ||\n\t\t\tphysicalLocation.ZipCode == \"\") {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"illegal physical location\")\n\t\treturn\n\t} else if eventType == \"online\" &&\n\t\t(mapstructure.Decode(event.Location, onlineLocation) != nil ||\n\t\t\tonlineLocation.Platform == \"\" ||\n\t\t\tonlineLocation.Link == \"\") {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"illegal online location\")\n\t\treturn\n\t}\n\tevent.OrganizerID = &user.ID\n\tevent.Organizer = user\n\timages := event.Images\n\tdb := ctx.MustGet(\"DB\").(*gorm.DB)\n\ttx := db.Begin()\n\t// we must omit images as inspection has to be gone through before they are linked\n\tif err := tx.Omit(\"Images\").Save(event).Error; err != nil {\n\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\t// link images to this event\n\teventString := \"events\"\n\tfor _, image := range images {\n\t\tif image.ID <= 0 {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"invalid image file ID\")\n\t\t} else if err := db.Where(image).Find(image).Error; errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusNotFound, \"image specified not found\")\n\t\t} else if err != nil {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t\t} else if *image.Status != \"active\" || *image.Type != \"images\" {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"image specified is not active or is not an image\")\n\t\t} else if image.LinkType != nil {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"image has been linked to some other resource object\")\n\t\t} else if err := db.Model(&image).Updates(model.File{LinkID: &event.ID, LinkType: &eventString}).Error; err != nil {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t\t} else {\n\t\t\tcontinue\n\t\t}\n\t\t// roll back the action of event creation if any of the images cannot pass integrity check\n\t\ttx.Rollback()\n\t\treturn\n\t}\n\tif err := tx.Commit().Error; err != nil {\n\t\ttx.Rollback()\n\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tctx.Status(http.StatusCreated)\n\tif err := jsonapi.MarshalPayload(ctx.Writer, event); err != nil {\n\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n}", "func (mr *MockSenderMockRecorder) AddEvent(ctx, clusterID, hostID, severity, msg, eventTime interface{}, props ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx, clusterID, hostID, severity, msg, eventTime}, props...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddEvent\", reflect.TypeOf((*MockSender)(nil).AddEvent), varargs...)\n}", "func (t *OpenconfigOfficeAp_System_Aaa_Accounting_Events) NewEvent(EventType E_OpenconfigAaaTypes_AAA_ACCOUNTING_EVENT_TYPE) (*OpenconfigOfficeAp_System_Aaa_Accounting_Events_Event, error) {\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Event == nil {\n\t\tt.Event = make(map[E_OpenconfigAaaTypes_AAA_ACCOUNTING_EVENT_TYPE]*OpenconfigOfficeAp_System_Aaa_Accounting_Events_Event)\n\t}\n\n\tkey := EventType\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Event[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Event\", key)\n\t}\n\n\tt.Event[key] = &OpenconfigOfficeAp_System_Aaa_Accounting_Events_Event{\n\t\tEventType: EventType,\n\t}\n\n\treturn t.Event[key], nil\n}", "func (l *Loop) Add(e *Event) {\n\t*l = append(*l, e)\n}", "func (a *AllApiService) EventGetProxyEvents(ctx _context.Context, body EventGetProxyEvents) (EventGetProxyEventsResult, *_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 EventGetProxyEventsResult\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/event/getProxyEvents\"\n\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{}\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\t// body params\n\tlocalVarPostBody = &body\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 EventGetProxyEventsResult\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 == 400 {\n\t\t\tvar v ModelError\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 == 500 {\n\t\t\tvar v ModelError\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 (g *Graph) AddEdge (start, end int) {\n\tnewEdge := edge{start, end}\n\tg.Edges = append(g.Edges, newEdge)\n}", "func (store *Store) AppendEvent(sessionID string, event *models.Event) error {\n\treturn store.connection.XAdd(event.SerializeRedisStream()).Err()\n}", "func (b *eventBuffer) Append(events *structs.Events) {\n\tb.appendItem(newBufferItem(events))\n}" ]
[ "0.6704259", "0.6652266", "0.6595114", "0.65947115", "0.6588073", "0.65375155", "0.6529956", "0.6430668", "0.637782", "0.63765407", "0.6348559", "0.6312045", "0.62506163", "0.6233655", "0.6188273", "0.6109361", "0.60342705", "0.6020177", "0.59109396", "0.589762", "0.58864474", "0.5876137", "0.58738995", "0.5855079", "0.58371276", "0.5815639", "0.58004475", "0.57980186", "0.57968736", "0.5737005", "0.5737005", "0.5587384", "0.55756575", "0.55360585", "0.5428237", "0.5407525", "0.5383419", "0.53820366", "0.53707755", "0.53665864", "0.5354338", "0.53260803", "0.5322069", "0.5279524", "0.5241831", "0.5238039", "0.5236192", "0.5233246", "0.522982", "0.5229222", "0.5217044", "0.5213474", "0.5171289", "0.5150063", "0.5143954", "0.5134143", "0.5132542", "0.51302564", "0.5128851", "0.51130843", "0.5104363", "0.5096351", "0.5054202", "0.5040637", "0.50396544", "0.5038165", "0.5019219", "0.5017646", "0.5010977", "0.49825117", "0.49790466", "0.49763155", "0.49679083", "0.49630514", "0.49595892", "0.49554354", "0.49239558", "0.49225917", "0.49223915", "0.48973173", "0.48949224", "0.48947778", "0.48931518", "0.4889639", "0.48890907", "0.48762926", "0.48727667", "0.48683146", "0.48594996", "0.48581627", "0.485754", "0.485669", "0.48516953", "0.48507443", "0.48462912", "0.48374644", "0.48147714", "0.48124087", "0.48090872", "0.47864965" ]
0.67074853
0
Mutation returns the AppMutation object of the builder.
func (ac *AppCreate) Mutation() *AppMutation { return ac.mutation }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (au *AppUpdate) Mutation() *AppMutation {\n\treturn au.mutation\n}", "func (auo *AppUpdateOne) Mutation() *AppMutation {\n\treturn auo.mutation\n}", "func (aru *AppointmentResultsUpdate) Mutation() *AppointmentResultsMutation {\n\treturn aru.mutation\n}", "func (aruo *AppointmentResultsUpdateOne) Mutation() *AppointmentResultsMutation {\n\treturn aruo.mutation\n}", "func (fc *FixbrandCreate) Mutation() *FixbrandMutation {\n\treturn fc.mutation\n}", "func (arc *AppointmentResultsCreate) Mutation() *AppointmentResultsMutation {\n\treturn arc.mutation\n}", "func (bc *BeerCreate) Mutation() *BeerMutation {\n\treturn bc.mutation\n}", "func (au *AdministratorUpdate) Mutation() *AdministratorMutation {\n\treturn au.mutation\n}", "func (ac *AnswerCreate) Mutation() *AnswerMutation {\n\treturn ac.mutation\n}", "func (auo *AdministratorUpdateOne) Mutation() *AdministratorMutation {\n\treturn auo.mutation\n}", "func (au *AdminUpdate) Mutation() *AdminMutation {\n\treturn au.mutation\n}", "func (bu *BookingUpdate) Mutation() *BookingMutation {\n\treturn bu.mutation\n}", "func (bu *BookingUpdate) Mutation() *BookingMutation {\n\treturn bu.mutation\n}", "func (buo *BookingUpdateOne) Mutation() *BookingMutation {\n\treturn buo.mutation\n}", "func (buo *BookingUpdateOne) Mutation() *BookingMutation {\n\treturn buo.mutation\n}", "func (auo *AdminUpdateOne) Mutation() *AdminMutation {\n\treturn auo.mutation\n}", "func (ou *OperationroomUpdate) Mutation() *OperationroomMutation {\n\treturn ou.mutation\n}", "func (s *Schema) Mutation() *Object {\n\treturn s.Object(\"Mutation\", mutation{})\n}", "func (mc *ManagerCreate) Mutation() *ManagerMutation {\n\treturn mc.mutation\n}", "func (ru *RoomUpdate) Mutation() *RoomMutation {\n\treturn ru.mutation\n}", "func (lu *LibraryUpdate) Mutation() *LibraryMutation {\n\treturn lu.mutation\n}", "func (aru *AuthRequestUpdate) Mutation() *AuthRequestMutation {\n\treturn aru.mutation\n}", "func (aruo *AuthRequestUpdateOne) Mutation() *AuthRequestMutation {\n\treturn aruo.mutation\n}", "func (au *AntenatalinformationUpdate) Mutation() *AntenatalinformationMutation {\n\treturn au.mutation\n}", "func (ou *OrganizationUpdate) Mutation() *OrganizationMutation {\n\treturn ou.mutation\n}", "func (ou *OrganizationUpdate) Mutation() *OrganizationMutation {\n\treturn ou.mutation\n}", "func (ouo *OperationroomUpdateOne) Mutation() *OperationroomMutation {\n\treturn ouo.mutation\n}", "func (bc *BadgeCreate) Mutation() *BadgeMutation {\n\treturn bc.mutation\n}", "func (fu *FriendshipUpdate) Mutation() *FriendshipMutation {\n\treturn fu.mutation\n}", "func (wu *WechatUpdate) Mutation() *WechatMutation {\n\treturn wu.mutation\n}", "func (bc *BillCreate) Mutation() *BillMutation {\n\treturn bc.mutation\n}", "func (pc *PhoneCreate) Mutation() *PhoneMutation {\n\treturn pc.mutation\n}", "func (luo *LibraryUpdateOne) Mutation() *LibraryMutation {\n\treturn luo.mutation\n}", "func (ouo *OrganizationUpdateOne) Mutation() *OrganizationMutation {\n\treturn ouo.mutation\n}", "func (ouo *OrganizationUpdateOne) Mutation() *OrganizationMutation {\n\treturn ouo.mutation\n}", "func (fuo *FriendshipUpdateOne) Mutation() *FriendshipMutation {\n\treturn fuo.mutation\n}", "func (wuo *WechatUpdateOne) Mutation() *WechatMutation {\n\treturn wuo.mutation\n}", "func (ruo *RoomUpdateOne) Mutation() *RoomMutation {\n\treturn ruo.mutation\n}", "func (otu *OutboundTransactionUpdate) Mutation() *OutboundTransactionMutation {\n\treturn otu.mutation\n}", "func (auo *AntenatalinformationUpdateOne) Mutation() *AntenatalinformationMutation {\n\treturn auo.mutation\n}", "func (pu *PhoneUpdate) Mutation() *PhoneMutation {\n\treturn pu.mutation\n}", "func (ac *AreahistoryCreate) Mutation() *AreahistoryMutation {\n\treturn ac.mutation\n}", "func (oc *OrganizationCreate) Mutation() *OrganizationMutation {\n\treturn oc.mutation\n}", "func (puo *PhoneUpdateOne) Mutation() *PhoneMutation {\n\treturn puo.mutation\n}", "func (atuo *ActivityTypeUpdateOne) Mutation() *ActivityTypeMutation {\n\treturn atuo.mutation\n}", "func (atu *ActivityTypeUpdate) Mutation() *ActivityTypeMutation {\n\treturn atu.mutation\n}", "func (hc *HospitalCreate) Mutation() *HospitalMutation {\n\treturn hc.mutation\n}", "func (ac *ActivityCreate) Mutation() *ActivityMutation {\n\treturn ac.mutation\n}", "func (ac *ActivityCreate) Mutation() *ActivityMutation {\n\treturn ac.mutation\n}", "func (asc *AlarmStatusCreate) Mutation() *AlarmStatusMutation {\n\treturn asc.mutation\n}", "func (buo *BillUpdateOne) Mutation() *BillMutation {\n\treturn buo.mutation\n}", "func (ec *EquipmentCreate) Mutation() *EquipmentMutation {\n\treturn ec.mutation\n}", "func (ec *EquipmentCreate) Mutation() *EquipmentMutation {\n\treturn ec.mutation\n}", "func (ac *AlertCreate) Mutation() *AlertMutation {\n\treturn ac.mutation\n}", "func (su *SkillUpdate) Mutation() *SkillMutation {\n\treturn su.mutation\n}", "func (wc *WordCreate) Mutation() *WordMutation {\n\treturn wc.mutation\n}", "func (rc *RestaurantCreate) Mutation() *RestaurantMutation {\n\treturn rc.mutation\n}", "func (bu *BillUpdate) Mutation() *BillMutation {\n\treturn bu.mutation\n}", "func (sc *SpecCreate) Mutation() *SpecMutation {\n\treturn sc.mutation\n}", "func (fc *FeedCreate) Mutation() *FeedMutation {\n\treturn fc.mutation\n}", "func (ouo *OrganUpdateOne) Mutation() *OrganMutation {\n\treturn ouo.mutation\n}", "func (lc *LoanbindingCreate) Mutation() *LoanbindingMutation {\n\treturn lc.mutation\n}", "func (bbc *BasicBannerCreate) Mutation() *BasicBannerMutation {\n\treturn bbc.mutation\n}", "func (muo *ModelUpdateOne) Mutation() *ModelMutation {\n\treturn muo.mutation\n}", "func (wc *WalletCreate) Mutation() *WalletMutation {\n\treturn wc.mutation\n}", "func (mu *ModelUpdate) Mutation() *ModelMutation {\n\treturn mu.mutation\n}", "func (otuo *OutboundTransactionUpdateOne) Mutation() *OutboundTransactionMutation {\n\treturn otuo.mutation\n}", "func (ou *OrganUpdate) Mutation() *OrganMutation {\n\treturn ou.mutation\n}", "func (rc *RoominfoCreate) Mutation() *RoominfoMutation {\n\treturn rc.mutation\n}", "func (fc *FinancierCreate) Mutation() *FinancierMutation {\n\treturn fc.mutation\n}", "func (upu *UnsavedPostUpdate) Mutation() *UnsavedPostMutation {\n\treturn upu.mutation\n}", "func (jc *JobpositionCreate) Mutation() *JobpositionMutation {\n\treturn jc.mutation\n}", "func (pu *PendingloanbindingUpdate) Mutation() *PendingloanbindingMutation {\n\treturn pu.mutation\n}", "func (bc *BouncerCreate) Mutation() *BouncerMutation {\n\treturn bc.mutation\n}", "func (iuo *ItemUpdateOne) Mutation() *ItemMutation {\n\treturn iuo.mutation\n}", "func (suo *SkillUpdateOne) Mutation() *SkillMutation {\n\treturn suo.mutation\n}", "func (mc *MenuCreate) Mutation() *MenuMutation {\n\treturn mc.mutation\n}", "func (cc *CompanyCreate) Mutation() *CompanyMutation {\n\treturn cc.mutation\n}", "func (eu *EmployeeUpdate) Mutation() *EmployeeMutation {\n\treturn eu.mutation\n}", "func (puo *ProductUpdateOne) Mutation() *ProductMutation {\n\treturn puo.mutation\n}", "func (puo *ProductUpdateOne) Mutation() *ProductMutation {\n\treturn puo.mutation\n}", "func (ic *ItemCreate) Mutation() *ItemMutation {\n\treturn ic.mutation\n}", "func (ru *RevisionUpdate) Mutation() *RevisionMutation {\n\treturn ru.mutation\n}", "func (du *DocUpdate) Mutation() *DocMutation {\n\treturn du.mutation\n}", "func (ktu *KqiTargetUpdate) Mutation() *KqiTargetMutation {\n\treturn ktu.mutation\n}", "func (duo *DocUpdateOne) Mutation() *DocMutation {\n\treturn duo.mutation\n}", "func (su *SettingUpdate) Mutation() *SettingMutation {\n\treturn su.mutation\n}", "func (ktuo *KqiTargetUpdateOne) Mutation() *KqiTargetMutation {\n\treturn ktuo.mutation\n}", "func (upuo *UnsavedPostUpdateOne) Mutation() *UnsavedPostMutation {\n\treturn upuo.mutation\n}", "func (tuo *TagUpdateOne) Mutation() *TagMutation {\n\treturn tuo.mutation\n}", "func (eu *ExtradoctorUpdate) Mutation() *ExtradoctorMutation {\n\treturn eu.mutation\n}", "func (gsu *GameServerUpdate) Mutation() *GameServerMutation {\n\treturn gsu.mutation\n}", "func (pu *ProductUpdate) Mutation() *ProductMutation {\n\treturn pu.mutation\n}", "func (pu *ProductUpdate) Mutation() *ProductMutation {\n\treturn pu.mutation\n}", "func (gc *GameCreate) Mutation() *GameMutation {\n\treturn gc.mutation\n}", "func (tu *TagUpdate) Mutation() *TagMutation {\n\treturn tu.mutation\n}", "func (iu *ItemUpdate) Mutation() *ItemMutation {\n\treturn iu.mutation\n}", "func (pc *PhysicaltherapyroomCreate) Mutation() *PhysicaltherapyroomMutation {\n\treturn pc.mutation\n}", "func (buo *BankUpdateOne) Mutation() *BankMutation {\n\treturn buo.mutation\n}", "func (xdc *XxxDemoCreate) Mutation() *XxxDemoMutation {\n\treturn xdc.mutation\n}" ]
[ "0.762948", "0.7490448", "0.6560429", "0.654045", "0.6499935", "0.64826035", "0.6443473", "0.64350283", "0.6410878", "0.63917685", "0.6360468", "0.6325174", "0.6325174", "0.6323004", "0.6323004", "0.6321316", "0.63093674", "0.6289354", "0.6258522", "0.6256568", "0.62235224", "0.6220789", "0.6206745", "0.6206519", "0.62034035", "0.62034035", "0.6200127", "0.61974144", "0.618785", "0.61763346", "0.61747736", "0.6169159", "0.6159684", "0.61518955", "0.61518955", "0.6141893", "0.6139067", "0.6126477", "0.6108115", "0.6107639", "0.610616", "0.6099556", "0.60967124", "0.6092256", "0.60817504", "0.6081259", "0.6076608", "0.60760325", "0.60760325", "0.6069626", "0.60663193", "0.6064131", "0.6064131", "0.6059416", "0.6052894", "0.6052059", "0.60433394", "0.60348094", "0.60341674", "0.6032309", "0.60193694", "0.60180825", "0.6017951", "0.60176575", "0.60084784", "0.6005427", "0.59954035", "0.5993121", "0.59930784", "0.5992788", "0.5990619", "0.5988513", "0.5985468", "0.59844935", "0.5983158", "0.59794134", "0.5977378", "0.5972062", "0.5971009", "0.59682137", "0.59682137", "0.5964384", "0.59580415", "0.5953278", "0.5949933", "0.59479773", "0.5947393", "0.59470296", "0.59409016", "0.59398717", "0.5939841", "0.59377927", "0.59376687", "0.59376687", "0.5935193", "0.5935012", "0.59341794", "0.5929655", "0.592317", "0.59213036" ]
0.7838271
0
Save creates the App in the database.
func (ac *AppCreate) Save(ctx context.Context) (*App, error) { if err := ac.preSave(); err != nil { return nil, err } var ( err error node *App ) if len(ac.hooks) == 0 { node, err = ac.sqlSave(ctx) } else { var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*AppMutation) if !ok { return nil, fmt.Errorf("unexpected mutation type %T", m) } ac.mutation = mutation node, err = ac.sqlSave(ctx) mutation.done = true return node, err }) for i := len(ac.hooks) - 1; i >= 0; i-- { mut = ac.hooks[i](mut) } if _, err := mut.Mutate(ctx, ac.mutation); err != nil { return nil, err } } return node, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (app *App) Save(db *pg.DB) error {\n\t_, err := db.Model(app).\n\t\tOnConflict(\"(id) DO UPDATE\").\n\t\tSet(\"name= ?name\").\n\t\tSet(\"url= ?url\").\n\t\tSet(\"icon= ?icon\").\n\t\tSet(\"kind= ?kind\").\n\t\tSet(\"version= ?version\").\n\t\tSet(\"bundle_id= ?bundle_id\").\n\t\tSet(\"author_id= ?author_id\").\n\t\tSet(\"author_name= ?author_name\").\n\t\tSet(\"author_url= ?author_url\").\n\t\tSet(\"vendor_name= ?vendor_name\").\n\t\tSet(\"vendor_url= ?vendor_url\").\n\t\tSet(\"copyright= ?copyright\").\n\t\tSet(\"genre_id= ?genre_id\").\n\t\tSet(\"genre_id_list= ?genre_id_list\").\n\t\tSet(\"genre= ?genre\").\n\t\tSet(\"genre_list= ?genre_list\").\n\t\tSet(\"icon60= ?icon60\").\n\t\tSet(\"icon100= ?icon100\").\n\t\tSet(\"price= ?price\").\n\t\tSet(\"currency= ?currency\").\n\t\tSet(\"system= ?system\").\n\t\tSet(\"features= ?features\").\n\t\tSet(\"devices= ?devices\").\n\t\tSet(\"languages= ?languages\").\n\t\tSet(\"platforms= ?platforms\").\n\t\tSet(\"rating= ?rating\").\n\t\tSet(\"reasons= ?reasons\").\n\t\tSet(\"size= ?size\").\n\t\tSet(\"cnt_rating= ?cnt_rating\").\n\t\tSet(\"avg_rating= ?avg_rating\").\n\t\tSet(\"cnt_rating_current= ?cnt_rating_current\").\n\t\tSet(\"avg_rating_current= ?avg_rating_current\").\n\t\tSet(\"vpp_device= ?vpp_device\").\n\t\tSet(\"game_center= ?game_center\").\n\t\tSet(\"screenshots= ?screenshots\").\n\t\tSet(\"in_app_purchase= ?in_app_purchase\").\n\t\tSet(\"sibling_apps= ?sibling_apps\").\n\t\tSet(\"related_apps= ?related_apps\").\n\t\tSet(\"support_sites= ?support_sites\").\n\t\tSet(\"reviews= ?reviews\").\n\t\tSet(\"extra= ?extra\").\n\t\tSet(\"description= ?description\").\n\t\tSet(\"release_notes= ?release_notes\").\n\t\tSet(\"release_time= ?release_time\").\n\t\tSet(\"publish_time= ?publish_time\").\n\t\tSet(\"crawled_time= ?crawled_time\").\n\t\tInsert()\n\treturn err\n}", "func (a *appHandler) CreateApp(w http.ResponseWriter, r *http.Request) {\n\tvar app model.App\n\terr := json.NewDecoder(r.Body).Decode(&app)\n\tif err != nil {\n\t\ta.httpUtil.WriteJSONBadRequestResponse(w, err)\n\t\treturn\n\t}\n\n\t// TODO : Create\n\n\tjsonR, err := json.Marshal(app)\n\tif err != nil {\n\t\ta.httpUtil.WriteJSONInternalServerErrorResponse(w, err)\n\t}\n\n\ta.httpUtil.WriteJSONSuccessResponse(w, jsonR)\n}", "func (auo *AppUpdateOne) Save(ctx context.Context) (*App, error) {\n\n\tvar (\n\t\terr error\n\t\tnode *App\n\t)\n\tif len(auo.hooks) == 0 {\n\t\tnode, err = auo.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*AppMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tauo.mutation = mutation\n\t\t\tnode, err = auo.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn node, err\n\t\t})\n\t\tfor i := len(auo.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = auo.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, auo.mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn node, err\n}", "func (store *managerStore) SaveApplication(application *types.Application) error {\n\n\tdata, err := json.Marshal(application)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpath := getApplicationRootPath() + application.RunAs + \"/\" + application.ID\n\treturn store.Db.Insert(path, string(data))\n}", "func (m *ApplicationModule) Save(fields ...string) (err error) {\n\to := orm.NewOrm()\n\tif m.ID > 0 {\n\t\t_, err = o.Update(m, fields...)\n\t} else {\n\t\tm.ID, err = o.Insert(m)\n\t}\n\treturn\n}", "func (d *DB) CreateApp(ctx context.Context, name string, claims ScopeClaims) (*App, error) {\n\tlog := logger.FromContext(ctx)\n\n\tif d.verbose {\n\t\tlog.Log(\n\t\t\t\"msg\", \"creating app\",\n\t\t\t\"name\", name,\n\t\t\t\"claims\", claims,\n\t\t)\n\t}\n\n\tif !areKnownClaims(claims) {\n\t\treturn nil, errors.New(\"invalid scope claims\")\n\t}\n\n\tb, err := randomBytes(keyLength)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get random bytes when creating app\")\n\t}\n\n\tuid, err := randomUID(10)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create random UID when creating app\")\n\t}\n\n\tapp := &App{\n\t\tUID: uid,\n\t\tName: name,\n\t\tHash: fmt.Sprintf(\"%x\", b),\n\t\tRoles: claims,\n\t\tKey: fmt.Sprintf(\"%s-%x\", uid, b),\n\t}\n\n\ttx, err := d.DB.Beginx()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create transaction to save app\")\n\t}\n\n\tsql := `INSERT INTO applications\n\t\t(uid, app_name, key_hash, scope)\n\tVALUES (:uid, :app_name, crypt(:key_hash, gen_salt('bf', 5)), :scope)`\n\n\tsql, args, err := tx.BindNamed(sql, app)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn nil, errors.Wrap(err, \"failed to bind named query\")\n\t}\n\n\t_, err = tx.Exec(sql, args...)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\tif pqErr, ok := err.(*pq.Error); ok {\n\t\t\tif pqErr.Code == pqUniqueViolation {\n\t\t\t\treturn nil, errors.New(\"duplicate application name error. an application with this name is already registered\")\n\t\t\t}\n\t\t}\n\t\treturn nil, errors.Wrap(err, \"failed to execute query\")\n\t}\n\n\treturn app, tx.Commit()\n}", "func (controller AppsController) Create(c *gin.Context) {\n\tvar configE entities.App\n\terr := c.BindJSON(&configE)\n\n\tif err != nil {\n\t\tfmt.Printf(\"error %v\", err)\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"message\": \"Invalid Parameters\"})\n\t\treturn\n\t}\n\n\tconfig, err := mongodb.Create(controller.MongoDBClient, Collections[\"apps\"], &configE)\n\tif err != nil {\n\t\tfmt.Printf(\"error %v\", err)\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"message\": \"Unable to save data\"})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\"apps\": config})\n}", "func (s *Signup) Save(db XODB) error {\n\tif s.Exists() {\n\t\treturn s.Update(db)\n\t}\n\n\treturn s.Insert(db)\n}", "func (post *Post) Save(app *state.AppState) error {\n\tsession := app.MgoSession.Clone()\n\tdefer session.Close()\n\n\tif post.ID == \"\" {\n\t\tpost.ID = bson.NewObjectId()\n\t}\n\n\treturn session.DB(dbName).C(\"posts\").Insert(post)\n}", "func (as *AppStorage) CreateApp(app model.AppData) (model.AppData, error) {\n\tres, ok := app.(*AppData)\n\tif !ok || res == nil {\n\t\treturn nil, model.ErrorWrongDataFormat\n\t}\n\tresult, err := as.addNewApp(res)\n\treturn result, err\n}", "func ApplicationCreate(w http.ResponseWriter, r *http.Request) {\n\tdb, err := database.Connect()\n\tdefer db.Close()\n\tif err != nil {\n\t\tlog.Printf(\"Database error: '%s'\\n\", err)\n\t\thttp.Error(w, \"there was an error when attempting to connect to the database\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvar createForm struct {\n\t\tName string\n\t}\n\tdecoder := json.NewDecoder(r.Body)\n\terr = decoder.Decode(&createForm)\n\tdefer r.Body.Close()\n\tif err != nil {\n\t\tlog.Printf(\"decoding error: '%s'\\n\", err)\n\t\thttp.Error(w, \"there was an error when attempting to parse the form\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tapp := resources.Application{\n\t\tName: createForm.Name,\n\t}\n\t_, err = resources.CreateApplication(db, &app)\n\t// @todo handle failed save w/out error?\n\tif err != nil {\n\t\tlog.Printf(\"Error when retrieving application: '%s'\\n\", err)\n\t\thttp.Error(w, \"there was an error when retrieving application\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// @todo return some sort of content?\n\tw.WriteHeader(http.StatusCreated)\n\treturn\n}", "func (db *DB) insertApp(app *App) error {\n\tres, err := db.NamedExec(`\n\t\tinsert into app(\n\t\t\talias, name, platform, bundle_id\n\t\t)\n\t\tvalues(\n\t\t\t:alias, :name, :platform, :bundle_id\n\t\t)\n\t\t\t`, app)\n\n\tif err == nil {\n\t\tid, _ := res.LastInsertId()\n\t\tapp.ID = int(id)\n\t}\n\n\treturn err\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(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 (ds *MySQLDatastore) InsertApp(ctx context.Context, app *models.App) (*models.App, error) {\n\tvar cbyte []byte\n\tvar err error\n\n\tif app.Config != nil {\n\t\tcbyte, err = json.Marshal(app.Config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tstmt, err := ds.db.Prepare(\"INSERT apps SET name=?,config=?\")\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = stmt.Exec(app.Name, string(cbyte))\n\n\tif err != nil {\n\t\tmysqlErr := err.(*mysql.MySQLError)\n\t\tif mysqlErr.Number == 1062 {\n\t\t\treturn nil, models.ErrAppsAlreadyExists\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn app, nil\n}", "func AppCreate(ctx *Context, name string, typ DeviceType) (*Application, error) {\n\th := authHeader(ctx.Config.AuthToken)\n\turi := ctx.Config.APIEndpoint(\"application\")\n\tdata := make(map[string]interface{})\n\tdata[\"app_name\"] = name\n\tdata[\"device_type\"] = typ.String()\n\tbody, err := marhsalReader(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb, err := doJSON(ctx, \"POST\", uri, h, nil, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trst := &Application{}\n\terr = json.Unmarshal(b, rst)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn rst, nil\n}", "func (b *Book) Save(db XODB) error {\n\tif b.Exists() {\n\t\treturn b.Update(db)\n\t}\n\n\treturn b.Insert(db)\n}", "func (s *AppStorage) Insert(ctx context.Context, app *types.App) error {\n\n\tlog.V(logLevel).Debug(\"Storage: App: insert app: %#v\", app)\n\n\tif app == nil {\n\t\terr := errors.New(\"app can not be nil\")\n\t\tlog.V(logLevel).Errorf(\"Storage: App: insert app err: %s\", err.Error())\n\t\treturn err\n\t}\n\n\tclient, destroy, err := s.Client()\n\tif err != nil {\n\t\tlog.V(logLevel).Errorf(\"Storage: App: create client err: %s\", err.Error())\n\t\treturn err\n\t}\n\tdefer destroy()\n\n\tkeyMeta := keyCreate(appStorage, app.Meta.Name, \"meta\")\n\tif err := client.Create(ctx, keyMeta, app.Meta, nil, 0); err != nil {\n\t\tlog.V(logLevel).Errorf(\"Storage: App: insert app err: %s\", err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *Store) Save(db *gorm.DB) (*Store, error) {\n\tvar err error\n\n\terr = db.Debug().Create(&s).Error\n\tif err != nil {\n\t\treturn &Store{}, err\n\t}\n\treturn s, nil\n}", "func Save() {\n\tgo db.save()\n}", "func (ai *AppInteractor) Create(app domain.App) (string, error) {\n\treturn ai.AppRepository.Create(app)\n}", "func (p *APIView) Save(result interface{}, context *Context) error {\n\tdb := context.GetDB()\n\tif db == nil {\n\t\treturn errors.New(\"db is nil\")\n\t}\n\tif db.NewScope(result).PrimaryKeyZero() {\n\t\treturn db.Create(result).Error\n\t}\n\treturn db.Save(result).Error\n}", "func (a *App) save() {\n\ta.TodoStore.Save(a.TodoList.Data)\n\tif a.TodoList.IsSynced {\n\t\ta.EventLogger.ProcessEvents()\n\n\t\tsynchronizer := NewQuietSynchronizer()\n\t\tsynchronizer.ExecSyncInBackground()\n\t}\n}", "func (s *siteData) save() error {\n\tvar err error\n\tif err = db.open(); err != nil {\n\t\treturn err\n\t}\n\tdefer db.close()\n\n\tsiteConf := []string{\"site\"}\n\tif err = db.bolt.SetValue(siteConf, \"title\", s.Title); err != nil {\n\t\treturn err\n\t}\n\tif err = db.bolt.SetInt(siteConf, \"port\", s.Port); err != nil {\n\t\treturn err\n\t}\n\tif err = db.bolt.SetValue(siteConf, \"session-name\", s.SessionName); err != nil {\n\t\treturn err\n\t}\n\treturn db.bolt.SetValue(siteConf, \"server-dir\", s.ServerDir)\n}", "func (r *ItemsRepository) save(i *Item) error {\n\tif query := r.databaseHandler.DB().Create(&i); query.Error != nil {\n\t\treturn query.Error\n\t}\n\treturn nil\n}", "func (c Client) createApp(body io.Reader) (*App, error) {\n\treq, err := http.NewRequest(\"POST\", c.getURL(\"/apps\"), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar marshalled map[string]*App\n\terr = c.executeRequestAndMarshal(req, &marshalled)\n\treturn marshalled[\"app\"], err\n}", "func (app *service) Save(genesis Genesis) error {\n\t_, err := app.repository.Retrieve()\n\tif err == nil {\n\t\treturn errors.New(\"there is already a Genesis instance\")\n\t}\n\n\tbill := genesis.Bill()\n\terr = app.billService.Save(bill)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttrGenesis, err := app.adapter.ToTransfer(genesis)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn app.trService.Save(trGenesis)\n}", "func seedDatabase(db *sql.DB) {\n\t_, err := db.Exec(`INSERT INTO app\n\t\t\t(id, app_id, app_name, deleted_at)\n\t\tVALUES \n\t\t\t('1b9e7a5f-af7c-4055-b488-72f2b5f72266', 'com.aerogear.foobar', 'Foobar', NULL),\n\t\t\t('ae2da1f5-a9c4-4305-84bc-80da683fbc36', 'com.test.app1', 'App One', '2019-02-18 14:36:35'),\n\t\t\t('0890506c-3dd1-43ad-8a09-21a4111a65a6', 'com.aerogear.testapp', 'Test App', NULL);\n\n\t\tINSERT INTO version\n\t\t\t(id, version, app_id, disabled, disabled_message, num_of_app_launches)\n\t\tVALUES \n\t\t\t('f6fe70a3-8c99-429c-8c77-a2efa7d0b458', '1', 'com.aerogear.testapp', FALSE, '', 5000),\n \t('9bc87235-6bcb-40ab-993c-8722d86e2201', '1.1', 'com.aerogear.testapp', TRUE, 'Please contact an administrator', 1000),\n\t\t\t('def3c38b-5765-4041-a8e1-b2b60d58bece', '1', 'com.test.app1', FALSE, '', 10000);\n\t\t\t\t\n\t\tINSERT INTO device\n\t\t\t(id, version_id, app_id, device_id, device_type, device_version)\n\t\tVALUES \n\t\t\t('d19feeb4-fb21-44e8-9990-473bf97a0a3f', 'f6fe70a3-8c99-429c-8c77-a2efa7d0b458', 'com.aerogear.testapp', 'a742f8b7-5e2f-43f3-a3c8-073da858420f', 'iOS', '10.2'),\n\t\t\t('00cb8957-db04-4ab6-8fd8-14b9fc516dbd', '9bc87235-6bcb-40ab-993c-8722d86e2201', 'com.aerogear.testapp', 'd1895cc1-28d7-4283-932d-8bcab9e4a461', 'Android', '3.2'),\n\t\t\t('e3b43b01-167b-48ef-8ff4-caf2e6613dee', '9bc87235-6bcb-40ab-993c-8722d86e2201', 'com.aerogear.testapp', 'feee7f81-0e33-4548-abbb-17a681c12f3b', 'Android', '4.1'),\n\t\t\t('ab411c3e-29f8-4e70-9ddc-8bafbba3fc4c', 'def3c38b-5765-4041-a8e1-b2b60d58bece', 'com.test.app1', '94da9833-093e-4f4c-9a93-b11600ce46b7', 'iOS', '2.0'),\n\t\t\t('a42a128a-dfb6-435c-8653-8f66ab3a5a1c', 'def3c38b-5765-4041-a8e1-b2b60d58bece', 'com.test.app1', '94132b0c-d7b1-4419-bcce-fc6760c59e3a', 'Android', '4.1');\n\t`)\n\n\tif err != nil {\n\t\tlogrus.Println(err)\n\t}\n}", "func (bb *BooktestBook) Save(ctx context.Context, db DB) error {\n\tif bb.Exists() {\n\t\treturn bb.Update(ctx, db)\n\t}\n\treturn bb.Insert(ctx, db)\n}", "func (ps *VacancySkill) Save() bool {\n\tvar err error\n\tvar action string\n\n\tif ps.ID == 0 {\n\t\t_, err = DB.Insert(ps)\n\t\taction = \"create\"\n\t} else {\n\t\t_, err = DB.Update(ps)\n\t\taction = \"update\"\n\t}\n\treturn utils.ProcessError(err, action+\" a vacancy`s skill\")\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 (as *AppStorage) addNewApp(app model.AppData) (model.AppData, error) {\n\ta, ok := app.(*AppData)\n\tif !ok || a == nil {\n\t\treturn nil, model.ErrorWrongDataFormat\n\t}\n\t// generate new ID if it's not set\n\tif len(a.ID()) == 0 {\n\t\ta.appData.ID = xid.New().String()\n\t}\n\n\tav, err := dynamodbattribute.MarshalMap(a)\n\tif err != nil {\n\t\tlog.Println(\"Error marshalling app:\", err)\n\t\treturn nil, ErrorInternalError\n\t}\n\n\tinput := &dynamodb.PutItemInput{\n\t\tItem: av,\n\t\tTableName: aws.String(appsTableName),\n\t}\n\n\tif _, err = as.db.C.PutItem(input); err != nil {\n\t\tlog.Println(\"Error putting app to storage:\", err)\n\t\treturn nil, ErrorInternalError\n\t}\n\treturn a, nil\n}", "func Save() error {\n\treturn instance.Save()\n}", "func Save() error {\n\treturn nil\n}", "func (r *Room) Save(db XODB) error {\n\tif r.Exists() {\n\t\treturn r.Update(db)\n\t}\n\n\treturn r.Replace(db)\n}", "func (c *Control) Save(db models.DBInterface) error {\n\tif c.existsInDB {\n\t\treturn c.update(db)\n\t}\n\n\treturn c.insert(db)\n}", "func (g *Group) Save(db *gorm.DB) *gorm.DB {\r\n\treturn db.Create(&g)\r\n\r\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 (d *DB) Save() (err error) {\n\tb, err := json.MarshalIndent(d, \"\", \" \")\n\tif err != nil {\n\t\treturn\n\t}\n\terr = ioutil.WriteFile(d.filePath, b, os.ModePerm)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Can't save the DB at path %q: %v\", d.filePath, err)\n\t\treturn\n\t}\n\treturn\n}", "func (app *service) Save(genesis Genesis) error {\n\tjs, err := app.adapter.ToJSON(genesis)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn app.fileService.Save(app.fileNameWithExt, js)\n}", "func (us *UserAppSession) Create() error {\n\tif err := db().Create(&us).Error; err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *AppsServices) Create(opt *AppsOpt) (interface{}, error) {\n\tu, err := url.Parse(c.client.BaseURL.String() + \"apps\")\n\tif err != nil {\n\t\treturn Success{}, err\n\t}\n\n\tb, err := EncodeBody(opt)\n\tif err != nil {\n\t\treturn Success{}, err\n\t}\n\n\tc.client.UseAuthKey = true\n\tresp, err := POST(u.String(), b, c.client)\n\tif err != nil {\n\t\treturn Success{}, err\n\t}\n\n\treturn resp, nil\n}", "func (yt *YhTeam) Save(db XODB) error {\n\tif yt.Exists() {\n\t\treturn yt.Update(db)\n\t}\n\n\treturn yt.Insert(db)\n}", "func (au *AppUpdate) Save(ctx context.Context) (int, error) {\n\n\tvar (\n\t\terr error\n\t\taffected int\n\t)\n\tif len(au.hooks) == 0 {\n\t\taffected, err = au.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*AppMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tau.mutation = mutation\n\t\t\taffected, err = au.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn affected, err\n\t\t})\n\t\tfor i := len(au.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = au.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, au.mutation); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn affected, err\n}", "func (acb *AppCreateBulk) Save(ctx context.Context) ([]*App, error) {\n\tspecs := make([]*sqlgraph.CreateSpec, len(acb.builders))\n\tnodes := make([]*App, len(acb.builders))\n\tmutators := make([]Mutator, len(acb.builders))\n\tfor i := range acb.builders {\n\t\tfunc(i int, root context.Context) {\n\t\t\tbuilder := acb.builders[i]\n\t\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\t\tif err := builder.preSave(); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tmutation, ok := m.(*AppMutation)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t\t}\n\t\t\t\tbuilder.mutation = mutation\n\t\t\t\tnodes[i], specs[i] = builder.createSpec()\n\t\t\t\tvar err error\n\t\t\t\tif i < len(mutators)-1 {\n\t\t\t\t\t_, err = mutators[i+1].Mutate(root, acb.builders[i+1].mutation)\n\t\t\t\t} else {\n\t\t\t\t\t// Invoke the actual operation on the latest mutation in the chain.\n\t\t\t\t\tif err = sqlgraph.BatchCreate(ctx, acb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {\n\t\t\t\t\t\tif cerr, ok := isSQLConstraintError(err); ok {\n\t\t\t\t\t\t\terr = cerr\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmutation.done = true\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tid := specs[i].ID.Value.(int64)\n\t\t\t\tnodes[i].ID = int(id)\n\t\t\t\treturn nodes[i], nil\n\t\t\t})\n\t\t\tfor i := len(builder.hooks) - 1; i >= 0; i-- {\n\t\t\t\tmut = builder.hooks[i](mut)\n\t\t\t}\n\t\t\tmutators[i] = mut\n\t\t}(i, ctx)\n\t}\n\tif len(mutators) > 0 {\n\t\tif _, err := mutators[0].Mutate(ctx, acb.builders[0].mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn nodes, nil\n}", "func (sch *schema) Save(doc interface{}) error {\n\terr := sch.Collection.Insert(doc)\n\tif err != nil {\n\t\tlog.Printf(\"ERROR! %s\\n\", err)\n\t}\n\treturn err\n}", "func SaveToDB(table, resourceID string, data interface{}) error {\n\tdataByte, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"while marshalling data, got: %v\", err)\n\t}\n\treturn db.Connector.Create(table, resourceID, string(dataByte))\n}", "func (p *Page) save() error {\n\t// Save to database\n\treturn pages.Insert(p)\n}", "func (ac *AppCreate) SaveX(ctx context.Context) *App {\n\tv, err := ac.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (c *Client) CreateApp(user, name string) (*App, error) {\n\tlog.Printf(\"[INFO] creating application %s/%s\", user, name)\n\n\tbody, err := json.Marshal(&appWrapper{&App{\n\t\tUser: user,\n\t\tName: name,\n\t}})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tendpoint := \"/api/v1/vagrant/applications\"\n\trequest, err := c.Request(\"POST\", endpoint, &RequestOptions{\n\t\tBody: bytes.NewReader(body),\n\t\tHeaders: map[string]string{\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse, err := checkResp(c.HTTPClient.Do(request))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar app App\n\tif err := decodeJSON(response, &app); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &app, nil\n}", "func (d *Daytype) Save(db models.DBInterface) error {\n\tif d.existsInDB {\n\t\treturn d.update(db)\n\t}\n\n\treturn d.insert(db)\n}", "func (r *app) Create(appPayload AppRequest, opts ...bool) (*AppFields, error) {\n\tasync := true\n\tif len(opts) > 0 {\n\t\tasync = opts[0]\n\t}\n\trawURL := fmt.Sprintf(\"/v2/apps?async=%t\", async)\n\tappFields := AppFields{}\n\t_, err := r.client.Post(rawURL, appPayload, &appFields)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &appFields, nil\n}", "func (srv *Server) Create(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"PUT\" {\n\t\thttp.Error(w, \"Please use a PUT request to create an application.\", http.StatusBadRequest)\n\t\treturn\n\t}\n\t// Read in body\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, \"Failed to read body of request\", http.StatusInternalServerError)\n\t}\n\t// Try to parse the metadata content\n\tmetadata := &types.ApplicationMetadata{}\n\terr = yaml.Unmarshal(body, metadata)\n\tif err != nil {\n\t\thttp.Error(w, \"Failed to parse YAML input. This likely indicates malformed request body. Verify the payload fields and parameter types are correct.\", http.StatusBadRequest)\n\t\tlog.Info(\"YAML parse error\")\n\t\treturn\n\t}\n\n\t// Validate input\n\terr = srv.Validate.Struct(metadata)\n\tif err != nil {\n\t\t// If we fail to validate, automatically return 400\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"Failed to validate input of the following parameters:\\n\"))\n\n\t\t// Be helpful and tell users what fails in their request\n\t\tfor _, err := range err.(validator.ValidationErrors) {\n\t\t\tfmt.Fprintf(w, \"%s has invalid value %s\\n\", err.Namespace(), err.Value())\n\t\t}\n\t\tlog.Info(\"Rejected invalid input.\")\n\t\treturn\n\t}\n\n\t// Check if a conflicting application already exists\n\tif util.CheckTitle(srv.Applications, metadata.Title) {\n\t\tw.WriteHeader(http.StatusConflict)\n\t\tfmt.Fprintf(w, \"An application with title %s already exists, please use a unique title.\", metadata.Title)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n\tsrv.Applications = append(srv.Applications, metadata)\n\tlog.WithFields(log.Fields{\"name\": metadata.Title}).Info(\"Object added\")\n\treturn\n}", "func (oee *OtxEpubEpub) Save(db XODB) error {\n\tif oee.Exists() {\n\t\treturn oee.Update(db)\n\t}\n\n\treturn oee.Insert(db)\n}", "func (analytics *Analytics) Save() {\n\tDB.Set(\"Analytics\", analytics.UserID, analytics)\n}", "func (i *Instantprofile) Save(db models.DBInterface) error {\n\tif i.existsInDB {\n\t\treturn i.update(db)\n\t}\n\n\treturn i.insert(db)\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 (a *Actor) Save(db XODB) error {\n\tif a.Exists() {\n\t\treturn a.Update(db)\n\t}\n\n\treturn a.Insert(db)\n}", "func (t *Title) Save() error {\n\tvar op = dbi.DB.Operation()\n\top.Dbg = dbi.Debug\n\treturn t.SaveOp(op)\n}", "func SaveBook(book Book) Book {\n\tutility.DB().Create(&book)\n\treturn book\n}", "func Save(dst interface{}) {\n\tif datastore != nil {\n\t\tresult := datastore.Session(&gorm.Session{FullSaveAssociations: true}).Debug().Save(dst)\n\t\tif result.Error != nil {\n\t\t\tlog.Error().Err(result.Error).Msg(\"Failed to save\")\n\t\t}\n\t} else {\n\t\tlog.Info().Msgf(\"No database configured, not saving %v\", dst)\n\t}\n}", "func (s *State) Save(db XODB) error {\n\tif s.Exists() {\n\t\treturn s.Update(db)\n\t}\n\n\treturn s.Insert(db)\n}", "func (ds *DjangoSession) Save(ctx context.Context, db DB) error {\n\tif ds.Exists() {\n\t\treturn ds.Update(ctx, db)\n\t}\n\treturn ds.Insert(ctx, db)\n}", "func (payment *PayPalPayment) Save() {\n\tDB.Set(\"PayPalPayment\", payment.ID, payment)\n}", "func (s *Server) ensureApp(ctx context.Context, wroute *models.RouteWrapper, method string) error {\n\tapp, err := s.Datastore.GetApp(ctx, wroute.Route.AppName)\n\tif err != nil && err != models.ErrAppsNotFound {\n\t\treturn err\n\t} else if app == nil {\n\t\t// Create a new application\n\t\tnewapp := &models.App{Name: wroute.Route.AppName}\n\t\tif err = newapp.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = s.FireBeforeAppCreate(ctx, newapp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = s.Datastore.InsertApp(ctx, newapp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = s.FireAfterAppCreate(ctx, newapp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\treturn nil\n}", "func (user *User) Save() {\n\tdb := common.GetDatabase()\n\n\tdb.Save(&user)\n}", "func (cache *LedisCacheStorage) StoreApp(appID string, name string) {\n\terr := cache.db.Set([]byte(\"app:\"+appID), []byte(name))\n\n\tif err != nil {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"Ledis Cache: failed to store cached app %v\\n\", err)\n\t}\n}", "func (env *Env) Save(res http.ResponseWriter, req *http.Request, title string) {\n\tenv.Log.V(1, \"beginning hanlding of Save.\")\n\ttitle = strings.Replace(strings.Title(title), \" \", \"_\", -1)\n\tbody := []byte(req.FormValue(\"body\"))\n\tpage := &webAppGo.Page{Title: title, Body: body}\n\terr := env.Cache.SaveToCache(page)\n\tif err != nil {\n\t\tenv.Log.V(1, \"notifying client that an internal error occured. Error is associated with Cache.SaveToCache.\")\n\t\thttp.Error(res, err.Error(), 500)\n\t}\n\terr = env.DB.SavePage(page)\n\tif err != nil {\n\t\tenv.Log.V(1, \"notifying client that an internal error occured. Error is associated with Cache.SavePage.\")\n\t\thttp.Error(res, err.Error(), 500)\n\t}\n\tenv.Log.V(1, \"The requested new page was successully saved, redirecting client to /view/PageTitle.\")\n\thttp.Redirect(res, req, \"/view/\"+title, http.StatusFound)\n}", "func (v *Voto) Save() error {\n\tif v.ID == 0 {\n\t\treturn v.insert()\n\t}\n\treturn v.update()\n}", "func (client MongoClient) Store(ctx context.Context, app apps.App) error {\n\n\tdata, err := bson.Marshal(app)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcoll := client.conn.Database(nameDB).Collection(nameColl)\n\t_, err = coll.InsertOne(ctx, data)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (wj *WsubJob) Save(db XODB) error {\n\tif wj.Exists() {\n\t\treturn wj.Update(db)\n\t}\n\n\treturn wj.Insert(db)\n}", "func (bdb *StormDBInstance) Save(data interface{}) error {\n\terr := bdb.DB.Save(data)\n\tif err != nil && err == storm.ErrAlreadyExists {\n\t\terr = bdb.DB.Update(data)\n\t}\n\treturn err\n}", "func (mapping *ApplicationAccountStoreMapping) Save() error {\n\turl := buildRelativeURL(\"accountStoreMappings\")\n\tif mapping.Href != \"\" {\n\t\turl = mapping.Href\n\t}\n\n\treturn client.post(url, mapping, mapping)\n}", "func (company *Company) Save() {\n\tDB.Set(\"Company\", company.ID, company)\n}", "func (sc *ScCategory) Save(db XODB) error {\n\tif sc.Exists() {\n\t\treturn sc.Update(db)\n\t}\n\n\treturn sc.Insert(db)\n}", "func (t *Todo) Save() error {\n\tif err := t.validate(); err != nil {\n\t\treturn err\n\t}\n\n\tsql := `INSERT INTO todos(list_id, todo) VALUES($1, $2) RETURNING id`\n\terr := db.QueryRow(sql, t.ListID, t.Todo).Scan(&t.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (a *Activity) Save(ctx context.Context) error {\n\tif a.Exists() {\n\t\treturn a.Update(ctx)\n\t}\n\n\treturn a.Insert(ctx)\n}", "func SetApp(v string) { appType.Store(v) }", "func (builder *Builder) Save() *Builder {\n\treturn builder.With(Save)\n}", "func Save() {\n\tdata := Savedata{\n\t\tName: GS.current.name,\n\t\tGamestate: GS.current,\n\t}\n\n\tf, err := json.MarshalIndent(data, \"\", \" \")\n\tcheck(err)\n\tioutil.WriteFile(\"data/savegame.json\", f, 0644)\n}", "func (d *Database) Save() error {\n\tb, err := json.Marshal(d.State)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Save\n\tif err := ioutil.WriteFile(d.FilePath, b, os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (ar AlbumDbRepository) Save(entity *domain.Album) (err error) {\n\tif entity.Id != 0 {\n\t\t// Update.\n\t\t_, err = ar.AppContext.DB.Update(entity)\n\t\treturn\n\t} else {\n\t\t// Insert new entity.\n\t\tentity.DateAdded = time.Now().Unix()\n\t\terr = ar.AppContext.DB.Insert(entity)\n\t\treturn\n\t}\n}", "func (in *Database) save(table string, rec interface{}) error {\n\ttxn := in.db.Txn(true)\n\tif err := txn.Insert(table, rec); err != nil {\n\t\ttxn.Abort()\n\t\treturn err\n\t}\n\ttxn.Commit()\n\treturn nil\n}", "func (driver *SQLDriver) Save(paste *pastes.Paste) error {\n\t// Execute an INSERT statement to create the paste\n\t_, err := driver.database.Exec(\"INSERT INTO ? (?, ?, ?, ?, ?, ?)\", driver.table, paste.ID, paste.Content, paste.SuggestedSyntaxType, paste.DeletionToken, paste.Created, paste.AutoDelete)\n\treturn err\n}", "func (hr *HelpRequest) Save(db XODB) error {\n\tif hr.Exists() {\n\t\treturn hr.Update(db)\n\t}\n\n\treturn hr.Insert(db)\n}", "func (u *Ayaneru) Save() error {\n\ttable := u.database.Init()\n\tdefer table.Close()\n\n\tresult, err := table.Exec(\"insert into ayanerus (source, url, created_at) values (?, ?, now());\", u.Source, u.URL)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"sql execute error\")\n\t}\n\n\tu.ID, _ = result.LastInsertId()\n\treturn nil\n}", "func (a *AppConf) Save(c LocalConf) (err error) {\n\terr = a.cc.Save(&c)\n\treturn\n}", "func (db *MongoDB) Save(project, kind, key string, data interface{}) error {\n\treturn nil\n}", "func (owwb *OtxWeblinkWeblinkBasket) Save(db XODB) error {\n\tif owwb.Exists() {\n\t\treturn owwb.Update(db)\n\t}\n\n\treturn owwb.Insert(db)\n}", "func (m Db) Save(n int, p architecture.Version) {\n\tm.Dbm[n] = p\n}", "func (db *DatabaseConnection) Save(obj DataObject) error {\n\tpk := db.getPrimaryKeyValue(obj)\n\tif pk > 0 {\n\t\treturn db.update(obj)\n\t}\n\treturn db.insert(obj)\n}", "func (v *Vessel) Save() error {\n\tdb := adaptors.DBConnector()\n\tdefer db.Close()\n\n\terr := db.Table(\"vessels\").Create(&Vessel{\n\t\tv.ID,\n\t\tv.Name,\n\t\tv.Beam,\n\t\tv.LOA,\n\t\tv.Draft,\n\t\tv.Status,\n\t}).Error\n\n\treturn err\n}", "func (wu *WsubUpdate) Save(db XODB) error {\n\tif wu.Exists() {\n\t\treturn wu.Update(db)\n\t}\n\n\treturn wu.Insert(db)\n}", "func (n *Notify) Save(db XODB) error {\n\tif n.Exists() {\n\t\treturn n.Update(db)\n\t}\n\n\treturn n.Replace(db)\n}", "func Save(gw Gateway) (*mgo.ChangeInfo, error) {\n\treturn collection().UpsertId(gw.MAC, gw)\n}", "func (at *AuthtokenToken) Save(db XODB) error {\n\tif at.Exists() {\n\t\treturn at.Update(db)\n\t}\n\n\treturn at.Insert(db)\n}", "func (s *server) Create(ctx context.Context, body *pb.RequestBody) (*pb.ResponseBody, error) {\n\tlanguage := body.GetLanguage()\n\tapp := &types.ApplicationConfig{}\n\n\terr := json.Unmarshal(body.GetData(), app)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser, err := mongo.FetchSingleUser(body.GetOwner())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmaxCount := configs.ServiceConfig.AppMaker.AppLimit\n\trateCount := configs.ServiceConfig.RateLimit\n\ttimeInterval := configs.ServiceConfig.RateInterval\n\tif !user.IsAdmin() && maxCount >= 0 {\n\t\trateLimitCount := mongo.CountInstanceInTimeFrame(body.GetOwner(), mongo.AppInstance, timeInterval)\n\t\ttotalCount := mongo.CountInstancesByUser(body.GetOwner(), mongo.AppInstance)\n\t\tif totalCount < maxCount {\n\t\t\tif rateLimitCount >= rateCount && rateCount >= 0 {\n\t\t\t\treturn nil, fmt.Errorf(\"cannot deploy more than %d app instances in %d hours\", rateCount, timeInterval)\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"cannot deploy more than %d app instances\", maxCount)\n\t\t}\n\t}\n\n\tapp.SetLanguage(language)\n\tapp.SetOwner(body.GetOwner())\n\tapp.SetInstanceType(mongo.AppInstance)\n\tapp.SetHostIP(utils.HostIP)\n\tapp.SetNameServers(configs.GasperConfig.DNSServers)\n\tapp.SetDateTime()\n\n\tgendnsNameServers, _ := redis.FetchServiceInstances(types.GenDNS)\n\tfor _, nameServer := range gendnsNameServers {\n\t\tif strings.Contains(nameServer, \":\") {\n\t\t\tapp.AddNameServers(strings.Split(nameServer, \":\")[0])\n\t\t} else {\n\t\t\tutils.LogError(\"AppMaker-Controller-1\", fmt.Errorf(\"GenDNS instance %s is of invalid format\", nameServer))\n\t\t}\n\t}\n\n\tif pipeline[language] == nil {\n\t\treturn nil, fmt.Errorf(\"language `%s` is not supported\", language)\n\t}\n\tresErr := pipeline[language].create(app)\n\tif resErr != nil {\n\t\tif resErr.Message() != \"repository already exists\" && resErr.Message() != \"container already exists\" {\n\t\t\tgo diskCleanup(app.GetName())\n\t\t}\n\t\treturn nil, fmt.Errorf(resErr.Error())\n\t}\n\n\tsshEntrypointIP := configs.ServiceConfig.GenSSH.EntrypointIP\n\tif len(sshEntrypointIP) == 0 {\n\t\tsshEntrypointIP = utils.HostIP\n\t}\n\tapp.SetSSHCmd(configs.ServiceConfig.GenSSH.Port, app.GetName(), sshEntrypointIP)\n\n\tapp.SetAppURL(fmt.Sprintf(\"%s.%s.%s\", app.GetName(), cloudflare.ApplicationInstance, configs.GasperConfig.Domain))\n\n\tif configs.CloudflareConfig.PlugIn {\n\t\tresp, err := cloudflare.CreateApplicationRecord(app.GetName())\n\t\tif err != nil {\n\t\t\tgo diskCleanup(app.GetName())\n\t\t\treturn nil, err\n\t\t}\n\t\tapp.SetCloudflareID(resp.Result.ID)\n\t\tapp.SetPublicIP(configs.CloudflareConfig.PublicIP)\n\t}\n\n\terr = mongo.UpsertInstance(\n\t\ttypes.M{\n\t\t\tmongo.NameKey: app.GetName(),\n\t\t\tmongo.InstanceTypeKey: mongo.AppInstance,\n\t\t}, app)\n\n\tif err != nil && err != mongo.ErrNoDocuments {\n\t\tgo diskCleanup(app.GetName())\n\t\tgo stateCleanup(app.GetName())\n\t\treturn nil, err\n\t}\n\n\terr = redis.RegisterApp(\n\t\tapp.GetName(),\n\t\tfmt.Sprintf(\"%s:%d\", utils.HostIP, configs.ServiceConfig.AppMaker.Port),\n\t\tfmt.Sprintf(\"%s:%d\", utils.HostIP, app.GetContainerPort()),\n\t)\n\n\tif err != nil {\n\t\tgo diskCleanup(app.GetName())\n\t\tgo stateCleanup(app.GetName())\n\t\treturn nil, err\n\t}\n\n\terr = redis.IncrementServiceLoad(\n\t\tServiceName,\n\t\tfmt.Sprintf(\"%s:%d\", utils.HostIP, configs.ServiceConfig.AppMaker.Port),\n\t)\n\n\tif err != nil {\n\t\tgo diskCleanup(app.GetName())\n\t\tgo stateCleanup(app.GetName())\n\t\treturn nil, err\n\t}\n\n\tapp.SetSuccess(true)\n\n\tresponse, err := json.Marshal(app)\n\treturn &pb.ResponseBody{Data: response}, err\n}", "func (pc *PageCreate) Save(ctx context.Context) (*Page, error) {\n\tpc.defaults()\n\treturn withHooks(ctx, pc.sqlSave, pc.mutation, pc.hooks)\n}", "func (f *Fermentor) Save(db *sqlx.DB) error {\n\tif f.Id != nil && *f.Id != 0 {\n\t\treturn UpdateFermentor(db, f)\n\t} else {\n\t\treturn InsertFermentor(db, f)\n\t}\n}", "func (d *Database) Save(db DB, table string, src interface{}) error {\n\tpkName, pkValue, err := d.PrimaryKey(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif pkName != \"\" && pkValue != 0 {\n\t\treturn d.Update(db, table, src)\n\t}\n\n\treturn d.Insert(db, table, src)\n}" ]
[ "0.7453346", "0.66413695", "0.649484", "0.6487268", "0.647283", "0.645859", "0.62722695", "0.6225815", "0.62228966", "0.6155802", "0.6148145", "0.61172324", "0.6110149", "0.60899836", "0.6068699", "0.6046805", "0.60159725", "0.6009806", "0.5972341", "0.59609294", "0.59307957", "0.59293187", "0.59255433", "0.59086585", "0.58815074", "0.5871457", "0.5850665", "0.5830638", "0.58298963", "0.58155394", "0.5778309", "0.57595444", "0.57565933", "0.57502556", "0.57424057", "0.5736464", "0.5701955", "0.57014066", "0.5688682", "0.5678193", "0.5677226", "0.56741023", "0.56648", "0.56450397", "0.5643636", "0.5633723", "0.56323427", "0.56246996", "0.56157875", "0.5612399", "0.56049037", "0.5597197", "0.55953926", "0.55902296", "0.5589454", "0.5588583", "0.55875534", "0.5587464", "0.5583163", "0.5574128", "0.55562353", "0.5515459", "0.5504059", "0.55007243", "0.5476163", "0.54733", "0.54695314", "0.54652303", "0.54644257", "0.5461238", "0.5460153", "0.54594237", "0.5457919", "0.5456273", "0.54479015", "0.54389155", "0.54362434", "0.54334354", "0.5431617", "0.54274887", "0.54239786", "0.5412922", "0.54074305", "0.5397323", "0.5395853", "0.5392388", "0.5383807", "0.53798103", "0.53771555", "0.5353157", "0.5352661", "0.5348913", "0.5335812", "0.53346074", "0.53340244", "0.53333193", "0.53323597", "0.53316665", "0.5331441", "0.5328507" ]
0.7422816
1
SaveX calls Save and panics if Save returns an error.
func (ac *AppCreate) SaveX(ctx context.Context) *App { v, err := ac.Save(ctx) if err != nil { panic(err) } return v }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (muo *MedicalfileUpdateOne) SaveX(ctx context.Context) *Medicalfile {\n\tm, err := muo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn m\n}", "func (fc *FileCreate) SaveX(ctx context.Context) *File {\n\tv, err := fc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (bc *BeerCreate) SaveX(ctx context.Context) *Beer {\n\tv, err := bc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (bc *BengkelCreate) SaveX(ctx context.Context) *Bengkel {\n\tv, err := bc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (mu *MedicalfileUpdate) SaveX(ctx context.Context) int {\n\taffected, err := mu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (wc *WritelogCreate) SaveX(ctx context.Context) *Writelog {\n\tv, err := wc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (fuo *FlowUpdateOne) SaveX(ctx context.Context) *Flow {\n\tf, err := fuo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}", "func (euo *ExtradoctorUpdateOne) SaveX(ctx context.Context) *Extradoctor {\n\te, err := euo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn e\n}", "func (fc *FinancierCreate) SaveX(ctx context.Context) *Financier {\n\tv, err := fc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (auo *AppUpdateOne) SaveX(ctx context.Context) *App {\n\ta, err := auo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn a\n}", "func (su *StateUpdate) SaveX(ctx context.Context) int {\n\taffected, err := su.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (ac *AlertCreate) SaveX(ctx context.Context) *Alert {\n\tv, err := ac.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (rc *RentalCreate) SaveX(ctx context.Context) *Rental {\n\tv, err := rc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (fu *FlowUpdate) SaveX(ctx context.Context) int {\n\taffected, err := fu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (du *DeviceUpdate) SaveX(ctx context.Context) int {\n\taffected, err := du.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (sc *StockCreate) SaveX(ctx context.Context) *Stock {\n\tv, err := sc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (mc *ManagerCreate) SaveX(ctx context.Context) *Manager {\n\tv, err := mc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (lu *LibraryUpdate) SaveX(ctx context.Context) int {\n\taffected, err := lu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (euo *EquipmentUpdateOne) SaveX(ctx context.Context) *Equipment {\n\te, err := euo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn e\n}", "func (pu *PatientrecordUpdate) SaveX(ctx context.Context) int {\n\taffected, err := pu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (ec *ExpertiseCreate) SaveX(ctx context.Context) *Expertise {\n\tv, err := ec.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (du *DatumUpdate) SaveX(ctx context.Context) int {\n\taffected, err := du.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (dc *DentistCreate) SaveX(ctx context.Context) *Dentist {\n\tv, err := dc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (ftc *FileTypeCreate) SaveX(ctx context.Context) *FileType {\n\tv, err := ftc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (bc *BillCreate) SaveX(ctx context.Context) *Bill {\n\tv, err := bc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (au *AppUpdate) SaveX(ctx context.Context) int {\n\taffected, err := au.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (swc *StartWorkCreate) SaveX(ctx context.Context) *StartWork {\n\tv, err := swc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (puo *PharmacistUpdateOne) SaveX(ctx context.Context) *Pharmacist {\n\tph, err := puo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ph\n}", "func (etc *ExportTaskCreate) SaveX(ctx context.Context) *ExportTask {\n\tv, err := etc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (sc *SpecCreate) SaveX(ctx context.Context) *Spec {\n\tv, err := sc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (muo *MannerUpdateOne) SaveX(ctx context.Context) *Manner {\n\tm, err := muo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn m\n}", "func (puo *PatientrecordUpdateOne) SaveX(ctx context.Context) *Patientrecord {\n\tpa, err := puo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn pa\n}", "func (pu *PharmacistUpdate) SaveX(ctx context.Context) int {\n\taffected, err := pu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (buo *BillUpdateOne) SaveX(ctx context.Context) *Bill {\n\tb, err := buo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn b\n}", "func (eu *EquipmentUpdate) SaveX(ctx context.Context) int {\n\taffected, err := eu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (bc *BlobCreate) SaveX(ctx context.Context) *Blob {\n\tv, err := bc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (wec *WorkExperienceCreate) SaveX(ctx context.Context) *WorkExperience {\n\tv, err := wec.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (pu *PhoneUpdate) SaveX(ctx context.Context) int {\n\taffected, err := pu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (rec *RawEventCreate) SaveX(ctx context.Context) *RawEvent {\n\tv, err := rec.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (eu *ExtradoctorUpdate) SaveX(ctx context.Context) int {\n\taffected, err := eu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (upu *UnsavedPostUpdate) SaveX(ctx context.Context) int {\n\taffected, err := upu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (puo *PrenameUpdateOne) SaveX(ctx context.Context) *Prename {\n\tpr, err := puo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn pr\n}", "func (mu *MedicalrecordstaffUpdate) SaveX(ctx context.Context) int {\n\taffected, err := mu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (pu *PostUpdate) SaveX(ctx context.Context) int {\n\taffected, err := pu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (pu *PostUpdate) SaveX(ctx context.Context) int {\n\taffected, err := pu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (mu *MannerUpdate) SaveX(ctx context.Context) int {\n\taffected, err := mu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (bc *BouncerCreate) SaveX(ctx context.Context) *Bouncer {\n\tv, err := bc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (otu *OutboundTransactionUpdate) SaveX(ctx context.Context) int {\n\taffected, err := otu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (tu *TransactionUpdate) SaveX(ctx context.Context) int {\n\taffected, err := tu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (du *DocUpdate) SaveX(ctx context.Context) int {\n\taffected, err := du.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (pu *PrenameUpdate) SaveX(ctx context.Context) int {\n\taffected, err := pu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (eptu *EquipmentPortTypeUpdate) SaveX(ctx context.Context) int {\n\taffected, err := eptu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (eptu *EquipmentPortTypeUpdate) SaveX(ctx context.Context) int {\n\taffected, err := eptu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (cc *CheckoutCreate) SaveX(ctx context.Context) *Checkout {\n\tv, err := cc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (bu *BankUpdate) SaveX(ctx context.Context) int {\n\taffected, err := bu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (mu *ModelUpdate) SaveX(ctx context.Context) int {\n\taffected, err := mu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (pc *PhoneCreate) SaveX(ctx context.Context) *Phone {\n\tv, err := pc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (ic *InstanceCreate) SaveX(ctx context.Context) *Instance {\n\tv, err := ic.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (squ *SurveyQuestionUpdate) SaveX(ctx context.Context) int {\n\taffected, err := squ.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (sc *SourceCreate) SaveX(ctx context.Context) *Source {\n\tv, err := sc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (souo *SubjectsOfferedUpdateOne) SaveX(ctx context.Context) *SubjectsOffered {\n\tso, err := souo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn so\n}", "func (ic *InsuranceCreate) SaveX(ctx context.Context) *Insurance {\n\tv, err := ic.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (bu *BillUpdate) SaveX(ctx context.Context) int {\n\taffected, err := bu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (tu *TypetreatmentUpdate) SaveX(ctx context.Context) int {\n\taffected, err := tu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (bu *BankdetailUpdate) SaveX(ctx context.Context) int {\n\taffected, err := bu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (au *AntenatalinformationUpdate) SaveX(ctx context.Context) int {\n\taffected, err := au.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (luo *LibraryUpdateOne) SaveX(ctx context.Context) *Library {\n\tl, err := luo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn l\n}", "func (pc *ProblemCreate) SaveX(ctx context.Context) *Problem {\n\tv, err := pc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (ou *OrganizationUpdate) SaveX(ctx context.Context) int {\n\taffected, err := ou.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (ou *OrganizationUpdate) SaveX(ctx context.Context) int {\n\taffected, err := ou.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (du *DayUpdate) SaveX(ctx context.Context) int {\n\taffected, err := du.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (xdc *XxxDemoCreate) SaveX(ctx context.Context) *XxxDemo {\n\tv, err := xdc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (ru *RevisionUpdate) SaveX(ctx context.Context) int {\n\taffected, err := ru.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (ic *ItemCreate) SaveX(ctx context.Context) *Item {\n\tv, err := ic.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (iu *ItemUpdate) SaveX(ctx context.Context) int {\n\taffected, err := iu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (tu *TransactionfactorUpdate) SaveX(ctx context.Context) int {\n\taffected, err := tu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (tdc *TypeDiseaseCreate) SaveX(ctx context.Context) *TypeDisease {\n\tv, err := tdc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (ec *EquipmentCreate) SaveX(ctx context.Context) *Equipment {\n\tv, err := ec.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (ec *EquipmentCreate) SaveX(ctx context.Context) *Equipment {\n\tv, err := ec.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (du *DoctorinfoUpdate) SaveX(ctx context.Context) int {\n\taffected, err := du.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (sc *SessionCreate) SaveX(ctx context.Context) *Session {\n\tv, err := sc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (ouo *OperationroomUpdateOne) SaveX(ctx context.Context) *Operationroom {\n\to, err := ouo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn o\n}", "func (eptuo *EquipmentPortTypeUpdateOne) SaveX(ctx context.Context) *EquipmentPortType {\n\tept, err := eptuo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ept\n}", "func (luu *LastUpdatedUpdate) SaveX(ctx context.Context) int {\n\taffected, err := luu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (puo *PhoneUpdateOne) SaveX(ctx context.Context) *Phone {\n\tnode, err := puo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn node\n}", "func (tu *TeamUpdate) SaveX(ctx context.Context) int {\n\taffected, err := tu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (mpc *MedicalProcedureCreate) SaveX(ctx context.Context) *MedicalProcedure {\n\tv, err := mpc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (du *DoctorUpdate) SaveX(ctx context.Context) int {\n\taffected, err := du.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (scsu *SurveyCellScanUpdate) SaveX(ctx context.Context) int {\n\taffected, err := scsu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (tru *TradeRecordUpdate) SaveX(ctx context.Context) int {\n\taffected, err := tru.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (bu *BookingUpdate) SaveX(ctx context.Context) int {\n\taffected, err := bu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (bu *BookingUpdate) SaveX(ctx context.Context) int {\n\taffected, err := bu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (wou *WorkOrderUpdate) SaveX(ctx context.Context) int {\n\taffected, err := wou.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (hu *HistorytakingUpdate) SaveX(ctx context.Context) int {\n\taffected, err := hu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (mu *MoneytransferUpdate) SaveX(ctx context.Context) int {\n\taffected, err := mu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (lu *LessonplanUpdate) SaveX(ctx context.Context) int {\n\taffected, err := lu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (_pc *PCCreate) SaveX(ctx context.Context) *PC {\n\tv, err := _pc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (su *SettingUpdate) SaveX(ctx context.Context) int {\n\taffected, err := su.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (huo *HistorytakingUpdateOne) SaveX(ctx context.Context) *Historytaking {\n\th, err := huo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn h\n}", "func (du *DealUpdate) SaveX(ctx context.Context) int {\n\taffected, err := du.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}" ]
[ "0.74172425", "0.73636734", "0.7356518", "0.73294014", "0.7282916", "0.7188979", "0.71573126", "0.7123369", "0.7083495", "0.7079091", "0.7077559", "0.70773494", "0.70764124", "0.7075264", "0.7073959", "0.7069399", "0.7066063", "0.70648736", "0.7054327", "0.70509976", "0.7049738", "0.7047714", "0.7044408", "0.7044101", "0.7040935", "0.70402837", "0.7040124", "0.70390373", "0.70332474", "0.7029804", "0.702548", "0.70233285", "0.70203364", "0.7014441", "0.70077235", "0.70071423", "0.70031106", "0.7002794", "0.7000426", "0.6994189", "0.69938976", "0.6992994", "0.6982582", "0.6981698", "0.6981698", "0.69809794", "0.6980227", "0.6971769", "0.6970218", "0.696511", "0.6962925", "0.69591045", "0.69591045", "0.6957132", "0.6956592", "0.694944", "0.69461626", "0.69435847", "0.69427574", "0.69337547", "0.69316375", "0.6929832", "0.6927595", "0.69201684", "0.6916382", "0.6912782", "0.6912004", "0.6911988", "0.69105905", "0.69105905", "0.69091725", "0.6905886", "0.6905831", "0.69056636", "0.6904557", "0.690373", "0.69007736", "0.6899132", "0.6899132", "0.6897289", "0.6894849", "0.68920815", "0.68889654", "0.6888895", "0.68877715", "0.68874806", "0.68872744", "0.68828833", "0.6882849", "0.6882156", "0.6879244", "0.6879244", "0.68745565", "0.68729824", "0.68720365", "0.6867878", "0.6867713", "0.686378", "0.68628377", "0.68625855" ]
0.69970447
39
Save creates the App entities in the database.
func (acb *AppCreateBulk) Save(ctx context.Context) ([]*App, error) { specs := make([]*sqlgraph.CreateSpec, len(acb.builders)) nodes := make([]*App, len(acb.builders)) mutators := make([]Mutator, len(acb.builders)) for i := range acb.builders { func(i int, root context.Context) { builder := acb.builders[i] var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { if err := builder.preSave(); err != nil { return nil, err } mutation, ok := m.(*AppMutation) if !ok { return nil, fmt.Errorf("unexpected mutation type %T", m) } builder.mutation = mutation nodes[i], specs[i] = builder.createSpec() var err error if i < len(mutators)-1 { _, err = mutators[i+1].Mutate(root, acb.builders[i+1].mutation) } else { // Invoke the actual operation on the latest mutation in the chain. if err = sqlgraph.BatchCreate(ctx, acb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil { if cerr, ok := isSQLConstraintError(err); ok { err = cerr } } } mutation.done = true if err != nil { return nil, err } id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { mut = builder.hooks[i](mut) } mutators[i] = mut }(i, ctx) } if len(mutators) > 0 { if _, err := mutators[0].Mutate(ctx, acb.builders[0].mutation); err != nil { return nil, err } } return nodes, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (app *App) Save(db *pg.DB) error {\n\t_, err := db.Model(app).\n\t\tOnConflict(\"(id) DO UPDATE\").\n\t\tSet(\"name= ?name\").\n\t\tSet(\"url= ?url\").\n\t\tSet(\"icon= ?icon\").\n\t\tSet(\"kind= ?kind\").\n\t\tSet(\"version= ?version\").\n\t\tSet(\"bundle_id= ?bundle_id\").\n\t\tSet(\"author_id= ?author_id\").\n\t\tSet(\"author_name= ?author_name\").\n\t\tSet(\"author_url= ?author_url\").\n\t\tSet(\"vendor_name= ?vendor_name\").\n\t\tSet(\"vendor_url= ?vendor_url\").\n\t\tSet(\"copyright= ?copyright\").\n\t\tSet(\"genre_id= ?genre_id\").\n\t\tSet(\"genre_id_list= ?genre_id_list\").\n\t\tSet(\"genre= ?genre\").\n\t\tSet(\"genre_list= ?genre_list\").\n\t\tSet(\"icon60= ?icon60\").\n\t\tSet(\"icon100= ?icon100\").\n\t\tSet(\"price= ?price\").\n\t\tSet(\"currency= ?currency\").\n\t\tSet(\"system= ?system\").\n\t\tSet(\"features= ?features\").\n\t\tSet(\"devices= ?devices\").\n\t\tSet(\"languages= ?languages\").\n\t\tSet(\"platforms= ?platforms\").\n\t\tSet(\"rating= ?rating\").\n\t\tSet(\"reasons= ?reasons\").\n\t\tSet(\"size= ?size\").\n\t\tSet(\"cnt_rating= ?cnt_rating\").\n\t\tSet(\"avg_rating= ?avg_rating\").\n\t\tSet(\"cnt_rating_current= ?cnt_rating_current\").\n\t\tSet(\"avg_rating_current= ?avg_rating_current\").\n\t\tSet(\"vpp_device= ?vpp_device\").\n\t\tSet(\"game_center= ?game_center\").\n\t\tSet(\"screenshots= ?screenshots\").\n\t\tSet(\"in_app_purchase= ?in_app_purchase\").\n\t\tSet(\"sibling_apps= ?sibling_apps\").\n\t\tSet(\"related_apps= ?related_apps\").\n\t\tSet(\"support_sites= ?support_sites\").\n\t\tSet(\"reviews= ?reviews\").\n\t\tSet(\"extra= ?extra\").\n\t\tSet(\"description= ?description\").\n\t\tSet(\"release_notes= ?release_notes\").\n\t\tSet(\"release_time= ?release_time\").\n\t\tSet(\"publish_time= ?publish_time\").\n\t\tSet(\"crawled_time= ?crawled_time\").\n\t\tInsert()\n\treturn err\n}", "func (ac *AppCreate) Save(ctx context.Context) (*App, error) {\n\tif err := ac.preSave(); err != nil {\n\t\treturn nil, err\n\t}\n\tvar (\n\t\terr error\n\t\tnode *App\n\t)\n\tif len(ac.hooks) == 0 {\n\t\tnode, err = ac.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*AppMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tac.mutation = mutation\n\t\t\tnode, err = ac.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn node, err\n\t\t})\n\t\tfor i := len(ac.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = ac.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, ac.mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn node, err\n}", "func (m *ApplicationModule) Save(fields ...string) (err error) {\n\to := orm.NewOrm()\n\tif m.ID > 0 {\n\t\t_, err = o.Update(m, fields...)\n\t} else {\n\t\tm.ID, err = o.Insert(m)\n\t}\n\treturn\n}", "func (auo *AppUpdateOne) Save(ctx context.Context) (*App, error) {\n\n\tvar (\n\t\terr error\n\t\tnode *App\n\t)\n\tif len(auo.hooks) == 0 {\n\t\tnode, err = auo.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*AppMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tauo.mutation = mutation\n\t\t\tnode, err = auo.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn node, err\n\t\t})\n\t\tfor i := len(auo.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = auo.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, auo.mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn node, err\n}", "func (store *managerStore) SaveApplication(application *types.Application) error {\n\n\tdata, err := json.Marshal(application)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpath := getApplicationRootPath() + application.RunAs + \"/\" + application.ID\n\treturn store.Db.Insert(path, string(data))\n}", "func (controller AppsController) Create(c *gin.Context) {\n\tvar configE entities.App\n\terr := c.BindJSON(&configE)\n\n\tif err != nil {\n\t\tfmt.Printf(\"error %v\", err)\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"message\": \"Invalid Parameters\"})\n\t\treturn\n\t}\n\n\tconfig, err := mongodb.Create(controller.MongoDBClient, Collections[\"apps\"], &configE)\n\tif err != nil {\n\t\tfmt.Printf(\"error %v\", err)\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"message\": \"Unable to save data\"})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\"apps\": config})\n}", "func (a *appHandler) CreateApp(w http.ResponseWriter, r *http.Request) {\n\tvar app model.App\n\terr := json.NewDecoder(r.Body).Decode(&app)\n\tif err != nil {\n\t\ta.httpUtil.WriteJSONBadRequestResponse(w, err)\n\t\treturn\n\t}\n\n\t// TODO : Create\n\n\tjsonR, err := json.Marshal(app)\n\tif err != nil {\n\t\ta.httpUtil.WriteJSONInternalServerErrorResponse(w, err)\n\t}\n\n\ta.httpUtil.WriteJSONSuccessResponse(w, jsonR)\n}", "func (app *service) Save(genesis Genesis) error {\n\t_, err := app.repository.Retrieve()\n\tif err == nil {\n\t\treturn errors.New(\"there is already a Genesis instance\")\n\t}\n\n\tbill := genesis.Bill()\n\terr = app.billService.Save(bill)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttrGenesis, err := app.adapter.ToTransfer(genesis)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn app.trService.Save(trGenesis)\n}", "func (post *Post) Save(app *state.AppState) error {\n\tsession := app.MgoSession.Clone()\n\tdefer session.Close()\n\n\tif post.ID == \"\" {\n\t\tpost.ID = bson.NewObjectId()\n\t}\n\n\treturn session.DB(dbName).C(\"posts\").Insert(post)\n}", "func (db *DB) insertApp(app *App) error {\n\tres, err := db.NamedExec(`\n\t\tinsert into app(\n\t\t\talias, name, platform, bundle_id\n\t\t)\n\t\tvalues(\n\t\t\t:alias, :name, :platform, :bundle_id\n\t\t)\n\t\t\t`, app)\n\n\tif err == nil {\n\t\tid, _ := res.LastInsertId()\n\t\tapp.ID = int(id)\n\t}\n\n\treturn err\n}", "func (s *Signup) Save(db XODB) error {\n\tif s.Exists() {\n\t\treturn s.Update(db)\n\t}\n\n\treturn s.Insert(db)\n}", "func (s *Store) Save(db *gorm.DB) (*Store, error) {\n\tvar err error\n\n\terr = db.Debug().Create(&s).Error\n\tif err != nil {\n\t\treturn &Store{}, err\n\t}\n\treturn s, nil\n}", "func (ds *MySQLDatastore) InsertApp(ctx context.Context, app *models.App) (*models.App, error) {\n\tvar cbyte []byte\n\tvar err error\n\n\tif app.Config != nil {\n\t\tcbyte, err = json.Marshal(app.Config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tstmt, err := ds.db.Prepare(\"INSERT apps SET name=?,config=?\")\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = stmt.Exec(app.Name, string(cbyte))\n\n\tif err != nil {\n\t\tmysqlErr := err.(*mysql.MySQLError)\n\t\tif mysqlErr.Number == 1062 {\n\t\t\treturn nil, models.ErrAppsAlreadyExists\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn app, nil\n}", "func (s *AppStorage) Insert(ctx context.Context, app *types.App) error {\n\n\tlog.V(logLevel).Debug(\"Storage: App: insert app: %#v\", app)\n\n\tif app == nil {\n\t\terr := errors.New(\"app can not be nil\")\n\t\tlog.V(logLevel).Errorf(\"Storage: App: insert app err: %s\", err.Error())\n\t\treturn err\n\t}\n\n\tclient, destroy, err := s.Client()\n\tif err != nil {\n\t\tlog.V(logLevel).Errorf(\"Storage: App: create client err: %s\", err.Error())\n\t\treturn err\n\t}\n\tdefer destroy()\n\n\tkeyMeta := keyCreate(appStorage, app.Meta.Name, \"meta\")\n\tif err := client.Create(ctx, keyMeta, app.Meta, nil, 0); err != nil {\n\t\tlog.V(logLevel).Errorf(\"Storage: App: insert app err: %s\", err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (d *DB) CreateApp(ctx context.Context, name string, claims ScopeClaims) (*App, error) {\n\tlog := logger.FromContext(ctx)\n\n\tif d.verbose {\n\t\tlog.Log(\n\t\t\t\"msg\", \"creating app\",\n\t\t\t\"name\", name,\n\t\t\t\"claims\", claims,\n\t\t)\n\t}\n\n\tif !areKnownClaims(claims) {\n\t\treturn nil, errors.New(\"invalid scope claims\")\n\t}\n\n\tb, err := randomBytes(keyLength)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get random bytes when creating app\")\n\t}\n\n\tuid, err := randomUID(10)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create random UID when creating app\")\n\t}\n\n\tapp := &App{\n\t\tUID: uid,\n\t\tName: name,\n\t\tHash: fmt.Sprintf(\"%x\", b),\n\t\tRoles: claims,\n\t\tKey: fmt.Sprintf(\"%s-%x\", uid, b),\n\t}\n\n\ttx, err := d.DB.Beginx()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create transaction to save app\")\n\t}\n\n\tsql := `INSERT INTO applications\n\t\t(uid, app_name, key_hash, scope)\n\tVALUES (:uid, :app_name, crypt(:key_hash, gen_salt('bf', 5)), :scope)`\n\n\tsql, args, err := tx.BindNamed(sql, app)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn nil, errors.Wrap(err, \"failed to bind named query\")\n\t}\n\n\t_, err = tx.Exec(sql, args...)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\tif pqErr, ok := err.(*pq.Error); ok {\n\t\t\tif pqErr.Code == pqUniqueViolation {\n\t\t\t\treturn nil, errors.New(\"duplicate application name error. an application with this name is already registered\")\n\t\t\t}\n\t\t}\n\t\treturn nil, errors.Wrap(err, \"failed to execute query\")\n\t}\n\n\treturn app, tx.Commit()\n}", "func (ar AlbumDbRepository) Save(entity *domain.Album) (err error) {\n\tif entity.Id != 0 {\n\t\t// Update.\n\t\t_, err = ar.AppContext.DB.Update(entity)\n\t\treturn\n\t} else {\n\t\t// Insert new entity.\n\t\tentity.DateAdded = time.Now().Unix()\n\t\terr = ar.AppContext.DB.Insert(entity)\n\t\treturn\n\t}\n}", "func (au *AppUpdate) Save(ctx context.Context) (int, error) {\n\n\tvar (\n\t\terr error\n\t\taffected int\n\t)\n\tif len(au.hooks) == 0 {\n\t\taffected, err = au.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*AppMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tau.mutation = mutation\n\t\t\taffected, err = au.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn affected, err\n\t\t})\n\t\tfor i := len(au.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = au.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, au.mutation); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn affected, err\n}", "func Save(dst interface{}) {\n\tif datastore != nil {\n\t\tresult := datastore.Session(&gorm.Session{FullSaveAssociations: true}).Debug().Save(dst)\n\t\tif result.Error != nil {\n\t\t\tlog.Error().Err(result.Error).Msg(\"Failed to save\")\n\t\t}\n\t} else {\n\t\tlog.Info().Msgf(\"No database configured, not saving %v\", dst)\n\t}\n}", "func (p *APIView) Save(result interface{}, context *Context) error {\n\tdb := context.GetDB()\n\tif db == nil {\n\t\treturn errors.New(\"db is nil\")\n\t}\n\tif db.NewScope(result).PrimaryKeyZero() {\n\t\treturn db.Create(result).Error\n\t}\n\treturn db.Save(result).Error\n}", "func (s *siteData) save() error {\n\tvar err error\n\tif err = db.open(); err != nil {\n\t\treturn err\n\t}\n\tdefer db.close()\n\n\tsiteConf := []string{\"site\"}\n\tif err = db.bolt.SetValue(siteConf, \"title\", s.Title); err != nil {\n\t\treturn err\n\t}\n\tif err = db.bolt.SetInt(siteConf, \"port\", s.Port); err != nil {\n\t\treturn err\n\t}\n\tif err = db.bolt.SetValue(siteConf, \"session-name\", s.SessionName); err != nil {\n\t\treturn err\n\t}\n\treturn db.bolt.SetValue(siteConf, \"server-dir\", s.ServerDir)\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 (r *ItemsRepository) save(i *Item) error {\n\tif query := r.databaseHandler.DB().Create(&i); query.Error != nil {\n\t\treturn query.Error\n\t}\n\treturn nil\n}", "func seedDatabase(db *sql.DB) {\n\t_, err := db.Exec(`INSERT INTO app\n\t\t\t(id, app_id, app_name, deleted_at)\n\t\tVALUES \n\t\t\t('1b9e7a5f-af7c-4055-b488-72f2b5f72266', 'com.aerogear.foobar', 'Foobar', NULL),\n\t\t\t('ae2da1f5-a9c4-4305-84bc-80da683fbc36', 'com.test.app1', 'App One', '2019-02-18 14:36:35'),\n\t\t\t('0890506c-3dd1-43ad-8a09-21a4111a65a6', 'com.aerogear.testapp', 'Test App', NULL);\n\n\t\tINSERT INTO version\n\t\t\t(id, version, app_id, disabled, disabled_message, num_of_app_launches)\n\t\tVALUES \n\t\t\t('f6fe70a3-8c99-429c-8c77-a2efa7d0b458', '1', 'com.aerogear.testapp', FALSE, '', 5000),\n \t('9bc87235-6bcb-40ab-993c-8722d86e2201', '1.1', 'com.aerogear.testapp', TRUE, 'Please contact an administrator', 1000),\n\t\t\t('def3c38b-5765-4041-a8e1-b2b60d58bece', '1', 'com.test.app1', FALSE, '', 10000);\n\t\t\t\t\n\t\tINSERT INTO device\n\t\t\t(id, version_id, app_id, device_id, device_type, device_version)\n\t\tVALUES \n\t\t\t('d19feeb4-fb21-44e8-9990-473bf97a0a3f', 'f6fe70a3-8c99-429c-8c77-a2efa7d0b458', 'com.aerogear.testapp', 'a742f8b7-5e2f-43f3-a3c8-073da858420f', 'iOS', '10.2'),\n\t\t\t('00cb8957-db04-4ab6-8fd8-14b9fc516dbd', '9bc87235-6bcb-40ab-993c-8722d86e2201', 'com.aerogear.testapp', 'd1895cc1-28d7-4283-932d-8bcab9e4a461', 'Android', '3.2'),\n\t\t\t('e3b43b01-167b-48ef-8ff4-caf2e6613dee', '9bc87235-6bcb-40ab-993c-8722d86e2201', 'com.aerogear.testapp', 'feee7f81-0e33-4548-abbb-17a681c12f3b', 'Android', '4.1'),\n\t\t\t('ab411c3e-29f8-4e70-9ddc-8bafbba3fc4c', 'def3c38b-5765-4041-a8e1-b2b60d58bece', 'com.test.app1', '94da9833-093e-4f4c-9a93-b11600ce46b7', 'iOS', '2.0'),\n\t\t\t('a42a128a-dfb6-435c-8653-8f66ab3a5a1c', 'def3c38b-5765-4041-a8e1-b2b60d58bece', 'com.test.app1', '94132b0c-d7b1-4419-bcce-fc6760c59e3a', 'Android', '4.1');\n\t`)\n\n\tif err != nil {\n\t\tlogrus.Println(err)\n\t}\n}", "func (a *App) save() {\n\ta.TodoStore.Save(a.TodoList.Data)\n\tif a.TodoList.IsSynced {\n\t\ta.EventLogger.ProcessEvents()\n\n\t\tsynchronizer := NewQuietSynchronizer()\n\t\tsynchronizer.ExecSyncInBackground()\n\t}\n}", "func (g *Group) Save(db *gorm.DB) *gorm.DB {\r\n\treturn db.Create(&g)\r\n\r\n}", "func Save() error {\n\treturn instance.Save()\n}", "func (yt *YhTeam) Save(db XODB) error {\n\tif yt.Exists() {\n\t\treturn yt.Update(db)\n\t}\n\n\treturn yt.Insert(db)\n}", "func (b *Book) Save(db XODB) error {\n\tif b.Exists() {\n\t\treturn b.Update(db)\n\t}\n\n\treturn b.Insert(db)\n}", "func (app *service) Save(genesis Genesis) error {\n\tjs, err := app.adapter.ToJSON(genesis)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn app.fileService.Save(app.fileNameWithExt, js)\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 (as *AppStorage) CreateApp(app model.AppData) (model.AppData, error) {\n\tres, ok := app.(*AppData)\n\tif !ok || res == nil {\n\t\treturn nil, model.ErrorWrongDataFormat\n\t}\n\tresult, err := as.addNewApp(res)\n\treturn result, err\n}", "func (i *Instantprofile) Save(db models.DBInterface) error {\n\tif i.existsInDB {\n\t\treturn i.update(db)\n\t}\n\n\treturn i.insert(db)\n}", "func Save() {\n\tgo db.save()\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 (r *Room) Save(db XODB) error {\n\tif r.Exists() {\n\t\treturn r.Update(db)\n\t}\n\n\treturn r.Replace(db)\n}", "func (c *Control) Save(db models.DBInterface) error {\n\tif c.existsInDB {\n\t\treturn c.update(db)\n\t}\n\n\treturn c.insert(db)\n}", "func (d *Daytype) Save(db models.DBInterface) error {\n\tif d.existsInDB {\n\t\treturn d.update(db)\n\t}\n\n\treturn d.insert(db)\n}", "func Save(entity Entity) error {\n\tvar buffer bytes.Buffer\n\n\tencoder := gob.NewEncoder(&buffer)\n\tkey := entity.Key()\n\terr := encoder.Encode(entity)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsetKey := entity.AreaSet()\n\n\tconn := db.Pool.Get()\n\tdefer conn.Close()\n\n\treturn db.Save(conn, key, setKey, buffer.Bytes())\n}", "func (oee *OtxEpubEpub) Save(db XODB) error {\n\tif oee.Exists() {\n\t\treturn oee.Update(db)\n\t}\n\n\treturn oee.Insert(db)\n}", "func (db *DbSaveEvent) Save(m domain.EventModel) error {\n\terr := db.repository.Save(m)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (a *Actor) Save(db XODB) error {\n\tif a.Exists() {\n\t\treturn a.Update(db)\n\t}\n\n\treturn a.Insert(db)\n}", "func (s *Service) Save(p *entity.Project) (entity.ID, error) {\n\tp.ID = entity.NewID()\n\tp.CreatedAt = time.Now()\n\treturn s.repo.Save(p)\n}", "func (e *Entity) Save() {\n\tif err := ecol.Update(bson.M{\"_id\": e.Id()}, e.data); err != nil {\n\t\tlog.Printf(\"Entity.Save(): ecol.Update(): %s\", err)\n\t}\n}", "func (bb *BooktestBook) Save(ctx context.Context, db DB) error {\n\tif bb.Exists() {\n\t\treturn bb.Update(ctx, db)\n\t}\n\treturn bb.Insert(ctx, db)\n}", "func (analytics *Analytics) Save() {\n\tDB.Set(\"Analytics\", analytics.UserID, analytics)\n}", "func (explenation *Explenation) Save() error {\n\t_, err := govalidator.ValidateStruct(explenation)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdataStore, dataStoreErr := CreateDataStore()\n\tif err != nil {\n\t\treturn dataStoreErr\n\t}\n\texplenationsCol := dataStore.GetCollection(CollectionExplenationsProperty)\n\tdefer dataStore.Close()\n\n\texplenation.SetID()\n\texplenation.UpdatedAt = time.Now()\n\n\t_, err = explenationsCol.UpsertId(explenation.ID, bson.M{\"$set\": explenation})\n\treturn err\n}", "func (b *Backend) Save(root internal.Root) ([]internal.Game, error) {\n\tvar gameJSON []byte\n\tvar games []internal.Game\n\terr := b.DB.Update(func(txn *badger.Txn) error {\n\t\tvar err error\n\t\tfor _, date := range root.Dates {\n\t\t\tdateString := date.DateString\n\t\t\tfor _, game := range date.Games {\n\t\t\t\tkey := fmt.Sprintf(\"%s:%d:%d\", dateString, game.Teams[\"away\"].Team.ID, game.Teams[\"home\"].Team.ID)\n\t\t\t\tgameJSON, err = json.Marshal(game)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ttxn.Set([]byte(key), gameJSON)\n\t\t\t\tgames = append(games, game)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn games, err\n}", "func (o *ORM) Save(model interface{}) error {\n\tt := time.Now()\n\t_, clauses := o.clauses(model, true)\n\n\tstmt, args, err := o.builder.Insert(\"articles\").\n\t\tSetMap(clauses).\n\t\tSuffix(\"RETURNING *\").\n\t\tToSql()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer o.log(t, stmt, args)\n\n\treturn o.conn.QueryRowx(stmt, args...).StructScan(model)\n}", "func (v *Voto) Save() error {\n\tif v.ID == 0 {\n\t\treturn v.insert()\n\t}\n\treturn v.update()\n}", "func (f *Fermentor) Save(db *sqlx.DB) error {\n\tif f.Id != nil && *f.Id != 0 {\n\t\treturn UpdateFermentor(db, f)\n\t} else {\n\t\treturn InsertFermentor(db, f)\n\t}\n}", "func (e *Account) Save() error { return ent.SaveEnt(e) }", "func (e *Account) Save() error { return ent.SaveEnt(e) }", "func (mapping *ApplicationAccountStoreMapping) Save() error {\n\turl := buildRelativeURL(\"accountStoreMappings\")\n\tif mapping.Href != \"\" {\n\t\turl = mapping.Href\n\t}\n\n\treturn client.post(url, mapping, mapping)\n}", "func (s *State) Save(db XODB) error {\n\tif s.Exists() {\n\t\treturn s.Update(db)\n\t}\n\n\treturn s.Insert(db)\n}", "func (c *Cliente) Save(db XODB) error {\n\tif c.Exists() {\n\t\treturn c.Update(db)\n\t}\n\n\treturn c.Insert(db)\n}", "func (tablePreeCheck *TablePreeCheck) SaveModel() {\n\tdb := db.GetPostgresDb()\n\tdb.Create(tablePreeCheck)\n}", "func (company *Company) Save() {\n\tDB.Set(\"Company\", company.ID, company)\n}", "func SaveToDB(table, resourceID string, data interface{}) error {\n\tdataByte, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"while marshalling data, got: %v\", err)\n\t}\n\treturn db.Connector.Create(table, resourceID, string(dataByte))\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 ApplicationCreate(w http.ResponseWriter, r *http.Request) {\n\tdb, err := database.Connect()\n\tdefer db.Close()\n\tif err != nil {\n\t\tlog.Printf(\"Database error: '%s'\\n\", err)\n\t\thttp.Error(w, \"there was an error when attempting to connect to the database\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvar createForm struct {\n\t\tName string\n\t}\n\tdecoder := json.NewDecoder(r.Body)\n\terr = decoder.Decode(&createForm)\n\tdefer r.Body.Close()\n\tif err != nil {\n\t\tlog.Printf(\"decoding error: '%s'\\n\", err)\n\t\thttp.Error(w, \"there was an error when attempting to parse the form\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tapp := resources.Application{\n\t\tName: createForm.Name,\n\t}\n\t_, err = resources.CreateApplication(db, &app)\n\t// @todo handle failed save w/out error?\n\tif err != nil {\n\t\tlog.Printf(\"Error when retrieving application: '%s'\\n\", err)\n\t\thttp.Error(w, \"there was an error when retrieving application\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// @todo return some sort of content?\n\tw.WriteHeader(http.StatusCreated)\n\treturn\n}", "func (sch *schema) Save(doc interface{}) error {\n\terr := sch.Collection.Insert(doc)\n\tif err != nil {\n\t\tlog.Printf(\"ERROR! %s\\n\", err)\n\t}\n\treturn err\n}", "func Save() error {\n\treturn nil\n}", "func (ai *AppInteractor) Create(app domain.App) (string, error) {\n\treturn ai.AppRepository.Create(app)\n}", "func (e *Department) Save() error { return ent.SaveEnt(e) }", "func (user *User) Save() {\n\tdb := common.GetDatabase()\n\n\tdb.Save(&user)\n}", "func (ds *DjangoSession) Save(ctx context.Context, db DB) error {\n\tif ds.Exists() {\n\t\treturn ds.Update(ctx, db)\n\t}\n\treturn ds.Insert(ctx, db)\n}", "func (r *Entity) Save() (result sql.Result, err error) {\n\treturn Model.Data(r).Save()\n}", "func (r *Entity) Save() (result sql.Result, err error) {\n\treturn Model.Data(r).Save()\n}", "func (r *Entity) Save() (result sql.Result, err error) {\n\treturn Model.Data(r).Save()\n}", "func (r *Entity) Save() (result sql.Result, err error) {\n\treturn Model.Data(r).Save()\n}", "func (r *Entity) Save() (result sql.Result, err error) {\n\treturn Model.Data(r).Save()\n}", "func (r *Entity) Save() (result sql.Result, err error) {\n\treturn Model.Data(r).Save()\n}", "func (e empresaService) Save(empresa model.Empresa) (model.Empresa, error) {\n\tempresa.CriadoEm = time.Now()\n\tempresa.AtualizadoEm = empresa.CriadoEm\n\n\tfor i := range empresa.Usuarios {\n\t\tempresa.Usuarios[i].CriadoEm = empresa.CriadoEm\n\t\tempresa.Usuarios[i].AtualizadoEm = empresa.AtualizadoEm\n\t}\n\n\treturn e.empresaRepository.Save(empresa)\n}", "func (a *Activity) Save(ctx context.Context) error {\n\tif a.Exists() {\n\t\treturn a.Update(ctx)\n\t}\n\n\treturn a.Insert(ctx)\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 (s *CreateUserEndpoint) saveToDB(user *User) (int, error) {\n\t// implementation removed\n\treturn 0, nil\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 (p *Page) save() error {\n\t// Save to database\n\treturn pages.Insert(p)\n}", "func (as *AppStorage) addNewApp(app model.AppData) (model.AppData, error) {\n\ta, ok := app.(*AppData)\n\tif !ok || a == nil {\n\t\treturn nil, model.ErrorWrongDataFormat\n\t}\n\t// generate new ID if it's not set\n\tif len(a.ID()) == 0 {\n\t\ta.appData.ID = xid.New().String()\n\t}\n\n\tav, err := dynamodbattribute.MarshalMap(a)\n\tif err != nil {\n\t\tlog.Println(\"Error marshalling app:\", err)\n\t\treturn nil, ErrorInternalError\n\t}\n\n\tinput := &dynamodb.PutItemInput{\n\t\tItem: av,\n\t\tTableName: aws.String(appsTableName),\n\t}\n\n\tif _, err = as.db.C.PutItem(input); err != nil {\n\t\tlog.Println(\"Error putting app to storage:\", err)\n\t\treturn nil, ErrorInternalError\n\t}\n\treturn a, nil\n}", "func (db *DatabaseConnection) Save(obj DataObject) error {\n\tpk := db.getPrimaryKeyValue(obj)\n\tif pk > 0 {\n\t\treturn db.update(obj)\n\t}\n\treturn db.insert(obj)\n}", "func (bdb *StormDBInstance) Save(data interface{}) error {\n\terr := bdb.DB.Save(data)\n\tif err != nil && err == storm.ErrAlreadyExists {\n\t\terr = bdb.DB.Update(data)\n\t}\n\treturn err\n}", "func (repo PostgresRepository) Save(document entity.Document) error {\n\t_, err := repo.db.Table(\"documents\").Insert(&document)\n\treturn err\n}", "func (ps *VacancySkill) Save() bool {\n\tvar err error\n\tvar action string\n\n\tif ps.ID == 0 {\n\t\t_, err = DB.Insert(ps)\n\t\taction = \"create\"\n\t} else {\n\t\t_, err = DB.Update(ps)\n\t\taction = \"update\"\n\t}\n\treturn utils.ProcessError(err, action+\" a vacancy`s skill\")\n}", "func (entity *MilitaryForeign) Save(context *pg.DB, account int64) (int, error) {\n\tentity.AccountID = account\n\n\tvar err error\n\tlistID, err := entity.List.Save(context, account)\n\tif err != nil {\n\t\treturn listID, err\n\t}\n\tentity.ListID = listID\n\n\terr = context.CreateTable(&MilitaryForeign{}, &orm.CreateTableOptions{\n\t\tTemp: false,\n\t\tIfNotExists: true,\n\t})\n\tif err != nil {\n\t\treturn entity.ID, err\n\t}\n\n\tif entity.ID == 0 {\n\t\terr = context.Insert(entity)\n\t} else {\n\t\terr = context.Update(entity)\n\t}\n\n\treturn entity.ID, err\n}", "func (s *SleepService) Save(ctx context.Context, sleep *goparent.Sleep) error {\r\n\tvar sleepKey *datastore.Key\r\n\tfamilyKey := datastore.NewKey(ctx, FamilyKind, sleep.FamilyID, 0, nil)\r\n\tchildKey := datastore.NewKey(ctx, ChildKind, sleep.ChildID, 0, familyKey)\r\n\tif sleep.ID == \"\" {\r\n\t\tu := uuid.New()\r\n\t\tsleepKey = datastore.NewKey(ctx, SleepKind, u.String(), 0, childKey)\r\n\t\tsleep.CreatedAt = time.Now()\r\n\t\tsleep.LastUpdated = sleep.CreatedAt\r\n\t\tsleep.ID = u.String()\r\n\t} else {\r\n\t\tsleepKey = datastore.NewKey(ctx, SleepKind, sleep.ID, 0, childKey)\r\n\t\tsleep.LastUpdated = time.Now()\r\n\t}\r\n\r\n\t_, err := datastore.Put(ctx, sleepKey, sleep)\r\n\tif err != nil {\r\n\t\treturn NewError(\"SleepService.Save\", err)\r\n\t}\r\n\treturn nil\r\n}", "func (ac *AppCreate) SaveX(ctx context.Context) *App {\n\tv, err := ac.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (s *Set) Save(db XODB) error {\n\tif s.Exists() {\n\t\treturn s.Update(db)\n\t}\n\n\treturn s.Insert(db)\n}", "func (d *Database) Save(db DB, table string, src interface{}) error {\n\tpkName, pkValue, err := d.PrimaryKey(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif pkName != \"\" && pkValue != 0 {\n\t\treturn d.Update(db, table, src)\n\t}\n\n\treturn d.Insert(db, table, src)\n}", "func (g *GamePlayerHand) Save() error {\n\tif g.ID == 0 {\n\t\treturn g.insert()\n\t}\n\n\treturn g.update()\n}", "func AppCreate(ctx *Context, name string, typ DeviceType) (*Application, error) {\n\th := authHeader(ctx.Config.AuthToken)\n\turi := ctx.Config.APIEndpoint(\"application\")\n\tdata := make(map[string]interface{})\n\tdata[\"app_name\"] = name\n\tdata[\"device_type\"] = typ.String()\n\tbody, err := marhsalReader(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb, err := doJSON(ctx, \"POST\", uri, h, nil, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trst := &Application{}\n\terr = json.Unmarshal(b, rst)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn rst, nil\n}", "func (at *AuthtokenToken) Save(db XODB) error {\n\tif at.Exists() {\n\t\treturn at.Update(db)\n\t}\n\n\treturn at.Insert(db)\n}", "func (sc *ScCategory) Save(db XODB) error {\n\tif sc.Exists() {\n\t\treturn sc.Update(db)\n\t}\n\n\treturn sc.Insert(db)\n}", "func (s *Session) Save(q db.Queryable) error {\n\tif s == nil {\n\t\treturn apperror.NewServerError(\"session is nil\")\n\t}\n\n\treturn s.Create(q)\n}", "func (m *User) Save(fields ...string) (err error) {\n\to := orm.NewOrm()\n\tif m.ID > 0 {\n\t\t_, err = o.Update(m, fields...)\n\t} else {\n\t\tm.ID, err = o.Insert(m)\n\t}\n\treturn\n}", "func (m *User) Save(fields ...string) (err error) {\n\to := orm.NewOrm()\n\tif m.ID > 0 {\n\t\t_, err = o.Update(m, fields...)\n\t} else {\n\t\tm.ID, err = o.Insert(m)\n\t}\n\treturn\n}", "func (e *Employee) Save() error {\n\n\terr := database.DBCon.QueryRow(\"INSERT into incidents.employees(first_name, last_name, email, customer_id) VALUES($1, $2, $3, $4)\", e.FirstName, e.LastName, e.Email, e.CustomerID).Scan()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (t *Testzzz) Save(ctx context.Context) error {\n\tif t.Exists() {\n\t\treturn t.Update(ctx)\n\t}\n\n\treturn t.Insert(ctx)\n}", "func (v *Vessel) Save() error {\n\tdb := adaptors.DBConnector()\n\tdefer db.Close()\n\n\terr := db.Table(\"vessels\").Create(&Vessel{\n\t\tv.ID,\n\t\tv.Name,\n\t\tv.Beam,\n\t\tv.LOA,\n\t\tv.Draft,\n\t\tv.Status,\n\t}).Error\n\n\treturn err\n}", "func Save(db DB, table string, src interface{}) error {\n\treturn SaveContext(context.Background(), db, table, src)\n}", "func (db *MongoDB) Save(project, kind, key string, data interface{}) error {\n\treturn nil\n}" ]
[ "0.71042067", "0.70797807", "0.67084944", "0.6399019", "0.6269228", "0.6188564", "0.6159549", "0.60583955", "0.6049131", "0.5908031", "0.58675456", "0.58582735", "0.58488023", "0.58297443", "0.58230525", "0.5806245", "0.5761058", "0.5754687", "0.57519376", "0.57504725", "0.5748676", "0.57052016", "0.5666404", "0.5655491", "0.5646997", "0.563561", "0.5627806", "0.5625927", "0.5624433", "0.56185555", "0.5605647", "0.5602968", "0.55780894", "0.5566938", "0.55554235", "0.5554971", "0.55355865", "0.54952633", "0.54889977", "0.5487653", "0.546636", "0.544066", "0.54404074", "0.5439618", "0.5427856", "0.54190063", "0.5418639", "0.54178625", "0.54159665", "0.54151314", "0.54096", "0.54096", "0.5407412", "0.5385998", "0.5382855", "0.5380693", "0.5364786", "0.5360683", "0.535039", "0.53459907", "0.53437", "0.5343335", "0.533903", "0.5330154", "0.53226626", "0.53209823", "0.531219", "0.531219", "0.531219", "0.531219", "0.531219", "0.531219", "0.53064096", "0.5304065", "0.5303923", "0.5285971", "0.5280893", "0.5280097", "0.52756006", "0.52755904", "0.5263937", "0.52595836", "0.5259016", "0.5258561", "0.52556026", "0.5250482", "0.5249785", "0.5242386", "0.52332515", "0.52249324", "0.5222403", "0.5204365", "0.5200611", "0.5197856", "0.5197856", "0.51912004", "0.51899385", "0.5189723", "0.5178699", "0.517003" ]
0.6269101
5
SaveX calls Save and panics if Save returns an error.
func (acb *AppCreateBulk) SaveX(ctx context.Context) []*App { v, err := acb.Save(ctx) if err != nil { panic(err) } return v }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (muo *MedicalfileUpdateOne) SaveX(ctx context.Context) *Medicalfile {\n\tm, err := muo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn m\n}", "func (fc *FileCreate) SaveX(ctx context.Context) *File {\n\tv, err := fc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (bc *BeerCreate) SaveX(ctx context.Context) *Beer {\n\tv, err := bc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (bc *BengkelCreate) SaveX(ctx context.Context) *Bengkel {\n\tv, err := bc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (mu *MedicalfileUpdate) SaveX(ctx context.Context) int {\n\taffected, err := mu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (wc *WritelogCreate) SaveX(ctx context.Context) *Writelog {\n\tv, err := wc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (fuo *FlowUpdateOne) SaveX(ctx context.Context) *Flow {\n\tf, err := fuo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}", "func (euo *ExtradoctorUpdateOne) SaveX(ctx context.Context) *Extradoctor {\n\te, err := euo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn e\n}", "func (fc *FinancierCreate) SaveX(ctx context.Context) *Financier {\n\tv, err := fc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (auo *AppUpdateOne) SaveX(ctx context.Context) *App {\n\ta, err := auo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn a\n}", "func (ac *AlertCreate) SaveX(ctx context.Context) *Alert {\n\tv, err := ac.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (su *StateUpdate) SaveX(ctx context.Context) int {\n\taffected, err := su.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (rc *RentalCreate) SaveX(ctx context.Context) *Rental {\n\tv, err := rc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (fu *FlowUpdate) SaveX(ctx context.Context) int {\n\taffected, err := fu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (du *DeviceUpdate) SaveX(ctx context.Context) int {\n\taffected, err := du.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (sc *StockCreate) SaveX(ctx context.Context) *Stock {\n\tv, err := sc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (mc *ManagerCreate) SaveX(ctx context.Context) *Manager {\n\tv, err := mc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (lu *LibraryUpdate) SaveX(ctx context.Context) int {\n\taffected, err := lu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (euo *EquipmentUpdateOne) SaveX(ctx context.Context) *Equipment {\n\te, err := euo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn e\n}", "func (pu *PatientrecordUpdate) SaveX(ctx context.Context) int {\n\taffected, err := pu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (ec *ExpertiseCreate) SaveX(ctx context.Context) *Expertise {\n\tv, err := ec.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (du *DatumUpdate) SaveX(ctx context.Context) int {\n\taffected, err := du.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (dc *DentistCreate) SaveX(ctx context.Context) *Dentist {\n\tv, err := dc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (ftc *FileTypeCreate) SaveX(ctx context.Context) *FileType {\n\tv, err := ftc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (bc *BillCreate) SaveX(ctx context.Context) *Bill {\n\tv, err := bc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (au *AppUpdate) SaveX(ctx context.Context) int {\n\taffected, err := au.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (swc *StartWorkCreate) SaveX(ctx context.Context) *StartWork {\n\tv, err := swc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (puo *PharmacistUpdateOne) SaveX(ctx context.Context) *Pharmacist {\n\tph, err := puo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ph\n}", "func (etc *ExportTaskCreate) SaveX(ctx context.Context) *ExportTask {\n\tv, err := etc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (sc *SpecCreate) SaveX(ctx context.Context) *Spec {\n\tv, err := sc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (muo *MannerUpdateOne) SaveX(ctx context.Context) *Manner {\n\tm, err := muo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn m\n}", "func (puo *PatientrecordUpdateOne) SaveX(ctx context.Context) *Patientrecord {\n\tpa, err := puo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn pa\n}", "func (pu *PharmacistUpdate) SaveX(ctx context.Context) int {\n\taffected, err := pu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (buo *BillUpdateOne) SaveX(ctx context.Context) *Bill {\n\tb, err := buo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn b\n}", "func (eu *EquipmentUpdate) SaveX(ctx context.Context) int {\n\taffected, err := eu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (bc *BlobCreate) SaveX(ctx context.Context) *Blob {\n\tv, err := bc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (wec *WorkExperienceCreate) SaveX(ctx context.Context) *WorkExperience {\n\tv, err := wec.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (pu *PhoneUpdate) SaveX(ctx context.Context) int {\n\taffected, err := pu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (rec *RawEventCreate) SaveX(ctx context.Context) *RawEvent {\n\tv, err := rec.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (ac *AppCreate) SaveX(ctx context.Context) *App {\n\tv, err := ac.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (eu *ExtradoctorUpdate) SaveX(ctx context.Context) int {\n\taffected, err := eu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (upu *UnsavedPostUpdate) SaveX(ctx context.Context) int {\n\taffected, err := upu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (puo *PrenameUpdateOne) SaveX(ctx context.Context) *Prename {\n\tpr, err := puo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn pr\n}", "func (mu *MedicalrecordstaffUpdate) SaveX(ctx context.Context) int {\n\taffected, err := mu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (pu *PostUpdate) SaveX(ctx context.Context) int {\n\taffected, err := pu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (pu *PostUpdate) SaveX(ctx context.Context) int {\n\taffected, err := pu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (mu *MannerUpdate) SaveX(ctx context.Context) int {\n\taffected, err := mu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (bc *BouncerCreate) SaveX(ctx context.Context) *Bouncer {\n\tv, err := bc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (otu *OutboundTransactionUpdate) SaveX(ctx context.Context) int {\n\taffected, err := otu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (tu *TransactionUpdate) SaveX(ctx context.Context) int {\n\taffected, err := tu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (du *DocUpdate) SaveX(ctx context.Context) int {\n\taffected, err := du.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (pu *PrenameUpdate) SaveX(ctx context.Context) int {\n\taffected, err := pu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (eptu *EquipmentPortTypeUpdate) SaveX(ctx context.Context) int {\n\taffected, err := eptu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (eptu *EquipmentPortTypeUpdate) SaveX(ctx context.Context) int {\n\taffected, err := eptu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (cc *CheckoutCreate) SaveX(ctx context.Context) *Checkout {\n\tv, err := cc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (bu *BankUpdate) SaveX(ctx context.Context) int {\n\taffected, err := bu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (mu *ModelUpdate) SaveX(ctx context.Context) int {\n\taffected, err := mu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (pc *PhoneCreate) SaveX(ctx context.Context) *Phone {\n\tv, err := pc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (ic *InstanceCreate) SaveX(ctx context.Context) *Instance {\n\tv, err := ic.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (squ *SurveyQuestionUpdate) SaveX(ctx context.Context) int {\n\taffected, err := squ.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (sc *SourceCreate) SaveX(ctx context.Context) *Source {\n\tv, err := sc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (souo *SubjectsOfferedUpdateOne) SaveX(ctx context.Context) *SubjectsOffered {\n\tso, err := souo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn so\n}", "func (ic *InsuranceCreate) SaveX(ctx context.Context) *Insurance {\n\tv, err := ic.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (bu *BillUpdate) SaveX(ctx context.Context) int {\n\taffected, err := bu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (tu *TypetreatmentUpdate) SaveX(ctx context.Context) int {\n\taffected, err := tu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (bu *BankdetailUpdate) SaveX(ctx context.Context) int {\n\taffected, err := bu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (au *AntenatalinformationUpdate) SaveX(ctx context.Context) int {\n\taffected, err := au.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (pc *ProblemCreate) SaveX(ctx context.Context) *Problem {\n\tv, err := pc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (luo *LibraryUpdateOne) SaveX(ctx context.Context) *Library {\n\tl, err := luo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn l\n}", "func (ou *OrganizationUpdate) SaveX(ctx context.Context) int {\n\taffected, err := ou.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (ou *OrganizationUpdate) SaveX(ctx context.Context) int {\n\taffected, err := ou.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (du *DayUpdate) SaveX(ctx context.Context) int {\n\taffected, err := du.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (ru *RevisionUpdate) SaveX(ctx context.Context) int {\n\taffected, err := ru.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (ic *ItemCreate) SaveX(ctx context.Context) *Item {\n\tv, err := ic.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (xdc *XxxDemoCreate) SaveX(ctx context.Context) *XxxDemo {\n\tv, err := xdc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (iu *ItemUpdate) SaveX(ctx context.Context) int {\n\taffected, err := iu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (tu *TransactionfactorUpdate) SaveX(ctx context.Context) int {\n\taffected, err := tu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (tdc *TypeDiseaseCreate) SaveX(ctx context.Context) *TypeDisease {\n\tv, err := tdc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (ec *EquipmentCreate) SaveX(ctx context.Context) *Equipment {\n\tv, err := ec.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (ec *EquipmentCreate) SaveX(ctx context.Context) *Equipment {\n\tv, err := ec.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (du *DoctorinfoUpdate) SaveX(ctx context.Context) int {\n\taffected, err := du.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (sc *SessionCreate) SaveX(ctx context.Context) *Session {\n\tv, err := sc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (ouo *OperationroomUpdateOne) SaveX(ctx context.Context) *Operationroom {\n\to, err := ouo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn o\n}", "func (luu *LastUpdatedUpdate) SaveX(ctx context.Context) int {\n\taffected, err := luu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (eptuo *EquipmentPortTypeUpdateOne) SaveX(ctx context.Context) *EquipmentPortType {\n\tept, err := eptuo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ept\n}", "func (tu *TeamUpdate) SaveX(ctx context.Context) int {\n\taffected, err := tu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (puo *PhoneUpdateOne) SaveX(ctx context.Context) *Phone {\n\tnode, err := puo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn node\n}", "func (mpc *MedicalProcedureCreate) SaveX(ctx context.Context) *MedicalProcedure {\n\tv, err := mpc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (scsu *SurveyCellScanUpdate) SaveX(ctx context.Context) int {\n\taffected, err := scsu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (du *DoctorUpdate) SaveX(ctx context.Context) int {\n\taffected, err := du.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (tru *TradeRecordUpdate) SaveX(ctx context.Context) int {\n\taffected, err := tru.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (bu *BookingUpdate) SaveX(ctx context.Context) int {\n\taffected, err := bu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (bu *BookingUpdate) SaveX(ctx context.Context) int {\n\taffected, err := bu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (wou *WorkOrderUpdate) SaveX(ctx context.Context) int {\n\taffected, err := wou.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (hu *HistorytakingUpdate) SaveX(ctx context.Context) int {\n\taffected, err := hu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (mu *MoneytransferUpdate) SaveX(ctx context.Context) int {\n\taffected, err := mu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (lu *LessonplanUpdate) SaveX(ctx context.Context) int {\n\taffected, err := lu.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (_pc *PCCreate) SaveX(ctx context.Context) *PC {\n\tv, err := _pc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}", "func (su *SettingUpdate) SaveX(ctx context.Context) int {\n\taffected, err := su.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}", "func (huo *HistorytakingUpdateOne) SaveX(ctx context.Context) *Historytaking {\n\th, err := huo.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn h\n}", "func (du *DealUpdate) SaveX(ctx context.Context) int {\n\taffected, err := du.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn affected\n}" ]
[ "0.7415374", "0.7362068", "0.7355115", "0.73282033", "0.7281354", "0.7187514", "0.715555", "0.7121415", "0.70820653", "0.707749", "0.70763016", "0.7076269", "0.70750177", "0.70738536", "0.7072377", "0.70679885", "0.70646185", "0.7063686", "0.7052814", "0.7049591", "0.7048603", "0.70459384", "0.70427495", "0.70427126", "0.7039593", "0.70389324", "0.70385927", "0.7036981", "0.7032344", "0.7027742", "0.7023658", "0.7021725", "0.7018729", "0.7012866", "0.7006456", "0.70055413", "0.70018715", "0.7001172", "0.6999238", "0.69956857", "0.6992691", "0.6992384", "0.6990541", "0.69811773", "0.69801", "0.69801", "0.6979496", "0.69787407", "0.6970659", "0.6969086", "0.69633067", "0.6960791", "0.69578433", "0.69578433", "0.69556075", "0.6955355", "0.69480634", "0.6944537", "0.6942303", "0.69408333", "0.69323", "0.69295245", "0.6928443", "0.6926297", "0.69188815", "0.6915136", "0.6911445", "0.6910814", "0.6910675", "0.69091433", "0.69091433", "0.6907723", "0.690447", "0.69042015", "0.69041955", "0.69031054", "0.6902078", "0.6899411", "0.68978745", "0.68978745", "0.68956393", "0.68934023", "0.68900585", "0.6887725", "0.6887363", "0.68861926", "0.6885781", "0.68855673", "0.6881116", "0.6881", "0.6880796", "0.6877898", "0.6877898", "0.6872925", "0.6871636", "0.6870619", "0.68666404", "0.6866054", "0.68624645", "0.68611234", "0.6861046" ]
0.0
-1
InitOsStore init Store as an OpenStack Storer
func InitOsStore() error { if err := context.InitKeyring(viper.GetString("openstack.user"), viper.GetString("openstack.password"), viper.GetString("openstack.tenant.name"), viper.GetString("openstack.authurl"), viper.GetString("openstack.tenant.id"), viper.GetString("openstack.region")); err != nil { return err } if err := identity.DoAuth(); err != nil { return err } // auto update Token each 30 minutes logger := log.New(logger.Log.Writer(), "osstore", 0) Store = Storer(OsStore{}) ///store = &storee identity.AutoUpdate(30, logger) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func InitStore(s Store) {\n\tstore = s\n}", "func InitStore(s Store) {\n\tstore = s\n}", "func InitStore(s Store) {\n\tstore = s\n}", "func InitStore() {\n\tdb, err := storm.Open(config.DatabaseFile)\n\tif err != nil {\n\t\tpanic(xerrors.Errorf(\"Cannot open database: %w\", err))\n\t}\n\tAuth = newAuthStore(db)\n\tComments = newCommentsStore(db)\n\tReviews = newReviewsStore(db)\n}", "func Init(ctx context.Context, alias, path string) (*Store, error) {\n\tdebug.Log(\"Initializing %s at %s\", alias, path)\n\n\ts := &Store{\n\t\talias: alias,\n\t\tpath: path,\n\t}\n\n\tst, err := backend.InitStorage(ctx, backend.GetStorageBackend(ctx), path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize storage for %s at %s: %w\", alias, path, err)\n\t}\n\n\ts.storage = st\n\tdebug.Log(\"Storage for %s => %s initialized as %s\", alias, path, st.Name())\n\n\tcrypto, err := backend.NewCrypto(ctx, backend.GetCryptoBackend(ctx))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize crypto for %s at %s: %w\", alias, path, err)\n\t}\n\n\ts.crypto = crypto\n\tdebug.Log(\"Crypto for %q => %q initialized as %s\", alias, path, crypto.Name())\n\n\treturn s, nil\n}", "func (c *StateStore) Init(metadata state.Metadata) error {\n\tconnInfo := metadata.Properties\n\tb, err := json.Marshal(connInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar creds credentials\n\terr = json.Unmarshal(b, &creds)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient := documentdb.New(creds.URL, &documentdb.Config{\n\t\tMasterKey: &documentdb.Key{\n\t\t\tKey: creds.MasterKey,\n\t\t},\n\t})\n\n\tdbs, err := client.QueryDatabases(&documentdb.Query{\n\t\tQuery: fmt.Sprintf(\"SELECT * FROM ROOT r WHERE r.id='%s'\", creds.Database),\n\t})\n\tif err != nil {\n\t\treturn err\n\t} else if len(dbs) == 0 {\n\t\treturn fmt.Errorf(\"Database %s for CosmosDB state store not found\", creds.Database)\n\t}\n\n\tc.db = &dbs[0]\n\tcolls, err := client.QueryCollections(c.db.Self, &documentdb.Query{\n\t\tQuery: fmt.Sprintf(\"SELECT * FROM ROOT r WHERE r.id='%s'\", creds.Collection),\n\t})\n\tif err != nil {\n\t\treturn err\n\t} else if len(colls) == 0 {\n\t\treturn fmt.Errorf(\"Collection %s for CosmosDB state store not found\", creds.Collection)\n\t}\n\n\tc.collection = &colls[0]\n\tc.client = client\n\n\treturn nil\n}", "func InitStore(s StoreInterface) {\n\tDocsStore = s\n}", "func InitStore(s KVStore) {\n\tdbConn = s\n\tscheduleCleanup(s)\n}", "func (s *Store) Init(ctx context.Context, metadataRaw secretstores.Metadata) error {\n\tmetadata, err := s.parseSecretManagerMetadata(metadataRaw)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient, err := s.getClient(ctx, metadata)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to setup secretmanager client: %s\", err)\n\t}\n\n\ts.client = client\n\ts.ProjectID = metadata.ProjectID\n\n\treturn nil\n}", "func Init(ctx context.Context, config *types.Config) {\n\tonce.Do(func() {\n\t\tvar err error\n\t\tcoreStore, err = New(ctx, config)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"[Init] failed to create core store, err: %v\", err)\n\t\t\treturn\n\t\t}\n\t})\n}", "func (a *App) initStore(host, port string) {}", "func initStore(logger *logging.Logger, connectionString string) *db.Store {\n\tlogger.Debug(\"Initializing Store\")\n\t// establish a store and connection to the db\n\tstore, err := db.NewStore(connectionString)\n\tif err != nil {\n\t\tsentry.CaptureException(err)\n\t\tlogger.Fatal(\"Failed to initialize store:\" + err.Error())\n\t}\n\tlogger.Debug(\"Store established with database connection\")\n\treturn store\n}", "func NewStore(\n\tkubeconfig *rest.Config,\n\tclientset kubernetes.Interface,\n\tkatoClient katoversioned.Interface,\n\tdbmanager db.Manager,\n\tconf option.Config) Storer {\n\tctx, cancel := context.WithCancel(context.Background())\n\tstore := &appRuntimeStore{\n\t\tkubeconfig: kubeconfig,\n\t\tclientset: clientset,\n\t\tkatoClient: katoClient,\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tinformers: &Informer{CRS: make(map[string]cache.SharedIndexInformer)},\n\t\tlisters: &Lister{},\n\t\tappServices: sync.Map{},\n\t\tconf: conf,\n\t\tdbmanager: dbmanager,\n\t\tcrClients: make(map[string]interface{}),\n\t\tresourceCache: NewResourceCache(),\n\t\tpodUpdateListeners: make(map[string]chan<- *corev1.Pod, 1),\n\t\tvolumeTypeListeners: make(map[string]chan<- *model.TenantServiceVolumeType, 1),\n\t}\n\tcrdClient, err := internalclientset.NewForConfig(kubeconfig)\n\tif err != nil {\n\t\tlogrus.Errorf(\"create crd client failure %s\", err.Error())\n\t}\n\tif crdClient != nil {\n\t\tstore.crdClient = crdClient\n\t\tcrdFactory := internalinformers.NewSharedInformerFactory(crdClient, 5*time.Minute)\n\t\tstore.informers.CRD = crdFactory.Apiextensions().V1().CustomResourceDefinitions().Informer()\n\t\tstore.listers.CRD = crdFactory.Apiextensions().V1().CustomResourceDefinitions().Lister()\n\t}\n\n\t// create informers factory, enable and assign required informers\n\tinfFactory := informers.NewSharedInformerFactoryWithOptions(conf.KubeClient, 10*time.Second,\n\t\tinformers.WithNamespace(corev1.NamespaceAll))\n\n\tstore.informers.Namespace = infFactory.Core().V1().Namespaces().Informer()\n\n\tstore.informers.Deployment = infFactory.Apps().V1().Deployments().Informer()\n\tstore.listers.Deployment = infFactory.Apps().V1().Deployments().Lister()\n\n\tstore.informers.StatefulSet = infFactory.Apps().V1().StatefulSets().Informer()\n\tstore.listers.StatefulSet = infFactory.Apps().V1().StatefulSets().Lister()\n\n\tstore.informers.Service = infFactory.Core().V1().Services().Informer()\n\tstore.listers.Service = infFactory.Core().V1().Services().Lister()\n\n\tstore.informers.Pod = infFactory.Core().V1().Pods().Informer()\n\tstore.listers.Pod = infFactory.Core().V1().Pods().Lister()\n\n\tstore.informers.Secret = infFactory.Core().V1().Secrets().Informer()\n\tstore.listers.Secret = infFactory.Core().V1().Secrets().Lister()\n\n\tstore.informers.ConfigMap = infFactory.Core().V1().ConfigMaps().Informer()\n\tstore.listers.ConfigMap = infFactory.Core().V1().ConfigMaps().Lister()\n\n\tstore.informers.Ingress = infFactory.Extensions().V1beta1().Ingresses().Informer()\n\tstore.listers.Ingress = infFactory.Networking().V1().Ingresses().Lister()\n\n\tstore.informers.ReplicaSet = infFactory.Apps().V1().ReplicaSets().Informer()\n\tstore.listers.ReplicaSets = infFactory.Apps().V1().ReplicaSets().Lister()\n\n\tstore.informers.Endpoints = infFactory.Core().V1().Endpoints().Informer()\n\tstore.listers.Endpoints = infFactory.Core().V1().Endpoints().Lister()\n\n\tstore.informers.Nodes = infFactory.Core().V1().Nodes().Informer()\n\tstore.listers.Nodes = infFactory.Core().V1().Nodes().Lister()\n\n\tstore.informers.StorageClass = infFactory.Storage().V1().StorageClasses().Informer()\n\tstore.listers.StorageClass = infFactory.Storage().V1().StorageClasses().Lister()\n\n\tstore.informers.Claims = infFactory.Core().V1().PersistentVolumeClaims().Informer()\n\tstore.listers.Claims = infFactory.Core().V1().PersistentVolumeClaims().Lister()\n\n\tstore.informers.Events = infFactory.Core().V1().Events().Informer()\n\n\tstore.informers.HorizontalPodAutoscaler = infFactory.Autoscaling().V2beta2().HorizontalPodAutoscalers().Informer()\n\tstore.listers.HorizontalPodAutoscaler = infFactory.Autoscaling().V2beta2().HorizontalPodAutoscalers().Lister()\n\n\t// kato custom resource\n\tkatoInformer := externalversions.NewSharedInformerFactoryWithOptions(katoClient, 10*time.Second,\n\t\texternalversions.WithNamespace(corev1.NamespaceAll))\n\tstore.listers.HelmApp = katoInformer.Kato().V1alpha1().HelmApps().Lister()\n\tstore.informers.HelmApp = katoInformer.Kato().V1alpha1().HelmApps().Informer()\n\tstore.listers.ThirdComponent = katoInformer.Kato().V1alpha1().ThirdComponents().Lister()\n\tstore.informers.ThirdComponent = katoInformer.Kato().V1alpha1().ThirdComponents().Informer()\n\tstore.listers.ComponentDefinition = katoInformer.Kato().V1alpha1().ComponentDefinitions().Lister()\n\tstore.informers.ComponentDefinition = katoInformer.Kato().V1alpha1().ComponentDefinitions().Informer()\n\tstore.informers.ComponentDefinition.AddEventHandlerWithResyncPeriod(componentdefinition.GetComponentDefinitionBuilder(), time.Second*300)\n\n\t// Endpoint Event Handler\n\tepEventHandler := cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tep := obj.(*corev1.Endpoints)\n\n\t\t\tserviceID := ep.Labels[\"service_id\"]\n\t\t\tversion := ep.Labels[\"version\"]\n\t\t\tcreaterID := ep.Labels[\"creater_id\"]\n\t\t\tif serviceID != \"\" && createrID != \"\" {\n\t\t\t\tappservice, err := store.getAppService(serviceID, version, createrID, true)\n\t\t\t\tif err == conversion.ErrServiceNotFound {\n\t\t\t\t\tlogrus.Debugf(\"ServiceID: %s; Action: AddFunc; service not found\", serviceID)\n\t\t\t\t}\n\t\t\t\tif appservice != nil {\n\t\t\t\t\tappservice.AddEndpoints(ep)\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tep := obj.(*corev1.Endpoints)\n\t\t\tserviceID := ep.Labels[\"service_id\"]\n\t\t\tversion := ep.Labels[\"version\"]\n\t\t\tcreaterID := ep.Labels[\"creater_id\"]\n\t\t\tif serviceID != \"\" && createrID != \"\" {\n\t\t\t\tappservice, _ := store.getAppService(serviceID, version, createrID, false)\n\t\t\t\tif appservice != nil {\n\t\t\t\t\tappservice.DelEndpoints(ep)\n\t\t\t\t\tif appservice.IsClosed() {\n\t\t\t\t\t\tlogrus.Debugf(\"ServiceID: %s; Action: DeleteFunc;service is closed\", serviceID)\n\t\t\t\t\t\tstore.DeleteAppService(appservice)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tUpdateFunc: func(old, cur interface{}) {\n\t\t\tcep := cur.(*corev1.Endpoints)\n\n\t\t\tserviceID := cep.Labels[\"service_id\"]\n\t\t\tversion := cep.Labels[\"version\"]\n\t\t\tcreaterID := cep.Labels[\"creater_id\"]\n\t\t\tif serviceID != \"\" && createrID != \"\" {\n\t\t\t\tappservice, err := store.getAppService(serviceID, version, createrID, true)\n\t\t\t\tif err == conversion.ErrServiceNotFound {\n\t\t\t\t\tlogrus.Debugf(\"ServiceID: %s; Action: UpdateFunc; service not found\", serviceID)\n\t\t\t\t}\n\t\t\t\tif appservice != nil {\n\t\t\t\t\tappservice.AddEndpoints(cep)\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}\n\n\tstore.informers.Namespace.AddEventHandler(store.nsEventHandler())\n\tstore.informers.Deployment.AddEventHandlerWithResyncPeriod(store, time.Second*10)\n\tstore.informers.StatefulSet.AddEventHandlerWithResyncPeriod(store, time.Second*10)\n\tstore.informers.Pod.AddEventHandlerWithResyncPeriod(store.podEventHandler(), time.Second*10)\n\tstore.informers.Secret.AddEventHandlerWithResyncPeriod(store, time.Second*10)\n\tstore.informers.Service.AddEventHandlerWithResyncPeriod(store, time.Second*10)\n\tstore.informers.Ingress.AddEventHandlerWithResyncPeriod(store, time.Second*10)\n\tstore.informers.ConfigMap.AddEventHandlerWithResyncPeriod(store, time.Second*10)\n\tstore.informers.ReplicaSet.AddEventHandlerWithResyncPeriod(store, time.Second*10)\n\tstore.informers.Endpoints.AddEventHandlerWithResyncPeriod(epEventHandler, time.Second*10)\n\tstore.informers.Nodes.AddEventHandlerWithResyncPeriod(store, time.Second*10)\n\tstore.informers.StorageClass.AddEventHandlerWithResyncPeriod(store, time.Second*300)\n\tstore.informers.Claims.AddEventHandlerWithResyncPeriod(store, time.Second*10)\n\tstore.informers.Events.AddEventHandlerWithResyncPeriod(store.evtEventHandler(), time.Second*10)\n\tstore.informers.HorizontalPodAutoscaler.AddEventHandlerWithResyncPeriod(store, time.Second*10)\n\tstore.informers.ThirdComponent.AddEventHandlerWithResyncPeriod(store, time.Second*10)\n\n\treturn store\n}", "func (e *SqliteEndorsementStore) Init(args common.EndorsementStoreParams) error {\n\tdbPath := retrieveDbPath(args)\n\tif dbPath == \"\" {\n\t\treturn fmt.Errorf(\"dbPath not specified inside FetcherParams\")\n\t}\n\tdbConfig := fmt.Sprintf(\"file:%s?cache=shared\", dbPath)\n\tdb, err := sql.Open(\"sqlite3\", dbConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te.db = db\n\te.path = dbPath\n\n\te.Queries = map[string]common.Query{\n\t\t\"hardware_id\": e.GetHardwareID,\n\t\t\"software_components\": e.GetSoftwareComponents,\n\t}\n\n\te.Adders = map[string]common.QueryAdder{\n\t\t\"hardware_id\": e.AddHardwareID,\n\t\t\"software_components\": e.AddSoftwareComponents,\n\t}\n\n\treturn nil\n}", "func initializeStore(fhandler *flowHandler) (stateSDefined bool, dataSOverride bool, err error) {\n\n\tstateSDefined = false\n\tdataSOverride = false\n\n\t// Initialize the stateS\n\tstateS, err := function.DefineStateStore()\n\tif err != nil {\n\t\treturn\n\t}\n\tif stateS != nil {\n\t\tfhandler.stateStore = stateS\n\t\tstateSDefined = true\n\t\tfhandler.stateStore.Configure(flowName, fhandler.id)\n\t\t// If request is not partial initialize the stateStore\n\t\tif !fhandler.partial {\n\t\t\terr = fhandler.stateStore.Init()\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// Initialize the dataS\n\tdataS, err := function.DefineDataStore()\n\tif err != nil {\n\t\treturn\n\t}\n\tif dataS != nil {\n\t\tfhandler.dataStore = dataS\n\t\tdataSOverride = true\n\t}\n\tfhandler.dataStore.Configure(flowName, fhandler.id)\n\t// If request is not partial initialize the dataStore\n\tif !fhandler.partial {\n\t\terr = fhandler.dataStore.Init()\n\t}\n\n\treturn\n}", "func (rs *redisStore)InitStore(sc storeConfig) error{\n\n\tvar addr, password string\n\tvar poolsize, dbnum int\n\n\tconfigs := strings.Split(sc.extraConfig, \",\")\n\tif len(configs) > 0 {\n\t\taddr = configs[0]\n\t}\n\tif len(configs) > 1 {\n\t\tpoolsize, err := strconv.Atoi(configs[1])\n\t\tif err != nil || poolsize < 0 {\n\t\t\tpoolsize = MaxPoolSize\n\t\t}\n\t} else {\n\t\tpoolsize = MaxPoolSize\n\t}\n\tif len(configs) > 2 {\n\t\tpassword = configs[2]\n\t}\n\tif len(configs) > 3 {\n\t\tdbnum, err := strconv.Atoi(configs[3])\n\t\tif err != nil || dbnum < 0 {\n\t\t\tdbnum = 0\n\t\t}\n\t} else {\n\t\tdbnum = 0\n\t}\n\n\tpool := &redis.Pool{\n\t\tMaxIdle:poolsize,\n\t\tDial:func() (redis.Conn, error) {\n\t\t\tc, err := redis.Dial(\"tcp\", addr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif password != \"\" {\n\t\t\t\tif _, err = c.Do(\"AUTH\", password); err != nil {\n\t\t\t\t\tc.Close()\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\t_, err = c.Do(\"SELECT\", dbnum)\n\t\t\tif err != nil {\n\t\t\t\tc.Close()\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn c, err\n\t\t},\n\t}\n\trs.p = pool\n\trs.expire = sc.expire\n\treturn rs.p.Get().Err()\n}", "func (engine *Engine) InitStore() {\n\tengine.storeIndexDocChans = make(\n\t\t[]chan storeIndexDocReq, engine.initOptions.StoreShards)\n\n\tfor shard := 0; shard < engine.initOptions.StoreShards; shard++ {\n\t\tengine.storeIndexDocChans[shard] = make(\n\t\t\tchan storeIndexDocReq)\n\t}\n\tengine.storeInitChan = make(\n\t\tchan bool, engine.initOptions.StoreShards)\n}", "func (backend *ESClient) InitializeStore(ctx context.Context) {\n\tlogrus.Info(\"Initialize elastic with mappings\")\n\tif !backend.initialized {\n\t\tfor _, esMap := range mappings.AllMappings {\n\t\t\tbackend.CreateTemplate(ctx, esMap.Index, esMap.Mapping)\n\t\t\tif !esMap.Timeseries {\n\t\t\t\tbackend.createStoreIfNotExists(ctx, esMap.Index, esMap.Mapping)\n\t\t\t\tbackend.createStoreAliasIfNotExists(ctx, esMap.Alias, esMap.Index)\n\t\t\t}\n\t\t}\n\t}\n\tbackend.initialized = true\n}", "func NewStore(init StoreInit) (s *Store, err error) {\r\n\tvar initialCapacity int\r\n\tif utils.IsSet(init.InitCapacity) {\r\n\t\tinitialCapacity = init.InitCapacity\r\n\t} else {\r\n\t\tinitialCapacity = len(init.Args)\r\n\t}\r\n\r\n\tlocalStore := Store{\r\n\t\tstore: make(map[string]string, initialCapacity),\r\n\t\tparent: init.Parent,\r\n\t}\r\n\r\n\tfor _, arg := range init.Args {\r\n\t\tkey, value, err := splitArgument(arg)\r\n\t\tif err != nil {\r\n\t\t\treturn nil, err\r\n\t\t}\r\n\r\n\t\tif value, err = encode.ConvertStringToUtf8(value); err != nil {\r\n\t\t\treturn nil, fmt.Errorf(\"Error converting value for key '%v' to UTF-8: %v\", key, err)\r\n\t\t}\r\n\r\n\t\tif !localStore.hasKey(key) {\r\n\t\t\tlocalStore.Set(key, value)\r\n\t\t} else {\r\n\t\t\treturn nil, fmt.Errorf(\"Duplicate key '%v' found\", key)\r\n\t\t}\r\n\t}\r\n\r\n\treturn &localStore, nil\r\n}", "func (sp *StoreProvider) OpenStore(ledgerID string) (storeapi.Store, error) {\n\treturn &store{}, nil\n}", "func Init() (s Storer, err error) {\n\turi := config.ReadEnvString(\"DB_URI\")\n\tname := config.ReadEnvString(\"DB_NAME\")\n\n\tclient, err := mongo.NewClient(options.Client().ApplyURI(uri))\n\tif err != nil {\n\t\tlogger.Error(\"Cannot initialize database\", err)\n\t\treturn\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\tdefer cancel()\n\n\terr = client.Connect(ctx)\n\tif err != nil {\n\t\tlogger.Error(\"Cannot initialize database context\", err)\n\t\treturn\n\t}\n\n\terr = client.Ping(ctx, readpref.Primary())\n\n\tif err != nil {\n\t\tlogger.Error(\"Cannot connect to database\", err)\n\t\treturn\n\t}\n\n\tlogger.Info(\"Connected To MongoDB\")\n\tdb := client.Database(name)\n\n\treturn &mongoStore{db}, nil\n}", "func InitStore(username string, password string, migrationDir string) error{\r\n\t//Connect to database\r\n\tdbURL := fmt.Sprint(username, \":\", password, \"@tcp(localhost:3306)/indecision\")\r\n\tdb, err := sql.Open(\"mysql\", dbURL)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\terr = db.Ping()\r\n\tif err != nil {\r\n\t\treturn err\r\n\t} else {\r\n\t\tfmt.Println(\"Successfully connected\")\r\n\t}\r\n\t\t//database migrations\r\n\tdriver, err := mysql.WithInstance(db, &mysql.Config{})\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\tm, err := migrate.NewWithDatabaseInstance(\r\n\t\tfmt.Sprintf(\"file://%s\", migrationDir), // file://path/to/directory\r\n\t\t\"mysql\", driver)\r\n\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\tif err := m.Up(); err != nil && err != migrate.ErrNoChange {\r\n\t\treturn err\r\n\t}\r\n\r\n\tfmt.Println(\"Database migrated\")\r\n\tstore = &dbStore{db: db}\r\n\treturn nil\r\n}", "func (s *Store) Init(option Option) error {\n\treturn option.ApplyTo(s)\n}", "func initStore(ctx context.Context, opts *Opts) (*sqlx.DB, scanner.Store, error) {\n\tvar store scanner.Store\n\tswitch opts.DataStore {\n\tcase Postgres:\n\t\t// we are going to use pgx for more control over connection pool and\n\t\t// and a cleaner api around bulk inserts\n\t\tcfg, err := pgxpool.ParseConfig(opts.ConnString)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to parse ConnString: %v\", err)\n\t\t}\n\t\tcfg.MaxConns = 30\n\t\tpool, err := pgxpool.ConnectConfig(ctx, cfg)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to create ConnPool: %v\", err)\n\t\t}\n\n\t\t// setup sqlx\n\t\tdb, err := sqlx.Open(\"pgx\", opts.ConnString)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to open db: %v\", err)\n\t\t}\n\n\t\tstore = postgres.NewStore(db, pool)\n\t\treturn db, store, nil\n\tdefault:\n\t\treturn nil, nil, fmt.Errorf(\"provided unknown DataStore\")\n\t}\n}", "func (store *Store) SysInit(app *ecomapp.Application) {\n}", "func InitStore() *Store {\n\tself := &Store{\n\t\tItems: make(map[string][][]byte),\n\t\tMarked: make(map[string]int64),\n\t}\n\tgo self.runGC(GC_RATE)\n\treturn self\n}", "func newStore(ts service.Service, config *Config) (*Store, error) {\n\tif config.Datastore == nil {\n\t\tdatastore, err := newDefaultDatastore(config.RepoPath, config.LowMem)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfig.Datastore = datastore\n\t}\n\tif config.EventCodec == nil {\n\t\tconfig.EventCodec = newDefaultEventCodec(config.JsonMode)\n\t}\n\tif !managedDatastore(config.Datastore) {\n\t\tif config.Debug {\n\t\t\tif err := util.SetLogLevels(map[string]logging.LogLevel{\"store\": logging.LevelDebug}); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\ts := &Store{\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tdatastore: config.Datastore,\n\t\tdispatcher: newDispatcher(config.Datastore),\n\t\teventcodec: config.EventCodec,\n\t\tmodelNames: make(map[string]*Model),\n\t\tjsonMode: config.JsonMode,\n\t\tlocalEventsBus: &localEventsBus{bus: broadcast.NewBroadcaster(0)},\n\t\tstateChangedNotifee: &stateChangedNotifee{},\n\t\tservice: ts,\n\t}\n\n\tif s.jsonMode {\n\t\tif err := s.reregisterSchemas(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\ts.dispatcher.Register(s)\n\treturn s, nil\n}", "func (e *ExternalServiceStore) ensureStore() {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\n\tif e.Store == nil {\n\t\te.Store = basestore.NewWithDB(dbconn.Global, sql.TxOptions{})\n\t}\n}", "func (r *StateStore) Init(metadata state.Metadata) error {\n\tmeta, err := getBlobStorageMetadata(metadata.Properties)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcredential, env, err := azauth.GetAzureStorageBlobCredentials(r.logger, meta.accountName, metadata.Properties)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid credentials with error: %s\", err.Error())\n\t}\n\n\tuserAgent := \"dapr-\" + logger.DaprVersion\n\toptions := azblob.PipelineOptions{\n\t\tTelemetry: azblob.TelemetryOptions{Value: userAgent},\n\t}\n\tp := azblob.NewPipeline(credential, options)\n\n\tvar URL *url.URL\n\tcustomEndpoint, ok := mdutils.GetMetadataProperty(metadata.Properties, azauth.StorageEndpointKeys...)\n\tif ok && customEndpoint != \"\" {\n\t\tURL, err = url.Parse(fmt.Sprintf(\"%s/%s/%s\", customEndpoint, meta.accountName, meta.containerName))\n\t} else {\n\t\tURL, err = url.Parse(fmt.Sprintf(\"https://%s.blob.%s/%s\", meta.accountName, env.StorageEndpointSuffix, meta.containerName))\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontainerURL := azblob.NewContainerURL(*URL, p)\n\n\t_, err = net.LookupHost(URL.Hostname())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx := context.Background()\n\t_, err = containerURL.Create(ctx, azblob.Metadata{}, azblob.PublicAccessNone)\n\tr.logger.Debugf(\"error creating container: %s\", err)\n\n\tr.containerURL = containerURL\n\tr.logger.Debugf(\"using container '%s'\", meta.containerName)\n\n\treturn nil\n}", "func Init(endpoint, region, secretKeySecretPath, accessKeySecretPath string, tlsEnabled bool) (faasflow.DataStore, error) {\n\tminioDataStore := &MinioDataStore{}\n\n\tminioDataStore.region = region\n\n\tminioClient, connectErr := connectToMinio(endpoint, secretKeySecretPath, accessKeySecretPath, tlsEnabled)\n\tif connectErr != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to initialize minio, error %s\", connectErr.Error())\n\t}\n\tminioDataStore.minioClient = minioClient\n\n\treturn minioDataStore, nil\n}", "func OpenStorager(cfg string) (store storage.Storager, err error) {\n\terrorMessage := \"coreutils OpenStorager [%s]: <%w>\"\n\n\t_, store, err = Open(cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(errorMessage, cfg, err)\n\t}\n\tif store == nil {\n\t\treturn nil, fmt.Errorf(errorMessage, cfg, ErrServiceNamespaceNotGiven)\n\t}\n\treturn\n}", "func Init(es endpointStore) (*Keystone, error) {\n\tkeystone := &Keystone{\n\t\tendpointStore: es,\n\t\tapiClient: client.NewHTTPFromConfig(),\n\t\tlog: logutil.NewLogger(\"keystone-api\"),\n\t}\n\tassignmentType := viper.GetString(\"keystone.assignment.type\")\n\tif assignmentType == \"static\" {\n\t\tvar staticAssignment asfkeystone.StaticAssignment\n\t\terr := config.LoadConfig(\"keystone.assignment.data\", &staticAssignment)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"creating local keystone server: failed to parse keystone assignment configuration\")\n\t\t}\n\t\tkeystone.staticAssignment = &staticAssignment\n\t\tkeystone.Assignment = &staticAssignment\n\t}\n\tstoreType := viper.GetString(\"keystone.store.type\")\n\tif storeType == \"memory\" {\n\t\texpire := viper.GetInt64(\"keystone.store.expire\")\n\t\tkeystone.store = MakeInMemoryStore(time.Duration(expire) * time.Second)\n\t}\n\n\treturn keystone, nil\n}", "func NewStore() *Store {\n\tvar st Store\n\tst.Records = make(map[string]HostSet)\n\tst.Netviews = make(map[string]string)\n\tst.Cidrs = make(map[string]string)\n\treturn &st\n}", "func Open(ns walletdb.ReadBucket, chainParams *chaincfg.Params) (*Store, er.R) {\n\t// Open the store.\n\terr := openStore(ns)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts := &Store{chainParams, clock.NewDefaultClock(), nil} // TODO: set callbacks\n\treturn s, nil\n}", "func newStore(c *Config) (*Store, error) {\n\tif c == nil {\n\t\tc = defaultConfig()\n\t}\n\tmutex := &sync.RWMutex{}\n\tstore := new(Store)\n\tstartTime := time.Now().UTC()\n\tfileWatcher, err := newWatcher(\".\")\n\tif err != nil {\n\t\tlog.Info(fmt.Sprintf(\"unable to init file watcher: %v\", err))\n\t}\n\tif c.Monitoring {\n\t\tmonitoring.Init()\n\t}\n\tstore.fileWatcher = fileWatcher\n\tstore.store = makeStorage(\"\")\n\tstore.keys = []string{}\n\tstore.compression = c.Compression\n\tstore.dbs = make(map[string]*DB)\n\tstore.lock = mutex\n\tstore.stat = new(stats.Statistics)\n\tstore.stat.Start = startTime\n\tstore.indexes = make(map[string]*index)\n\tc.setMissedValues()\n\tstore.config = c\n\tif c.LoadPath != \"\" {\n\t\terrLoad := loadData(store, c.LoadPath)\n\t\tif errLoad != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to load data: %v\", errLoad)\n\t\t}\n\t}\n\tstore.writer, err = newWriter(c.LoadPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create writer: %v\", err)\n\t}\n\treturn store, nil\n}", "func InitializeStoreHydrate(ctx context.Context) {\n\n\twsDepthHandler := func(event *WsDepthEvent) {\n\t event.CreateImage()\n\t}\n\n\terrHandler := func(err error) {\n\t fmt.Println(err)\n\t}\n\tdoneC, stopC, err := WsDepthServe(\"BNBBTC\", wsDepthHandler, errHandler)\n\tif err != nil {\n\t fmt.Println(err)\n\t return\n\t}\n\n\t// use stopC to exit\n\tgo func() {\n\t time.Sleep(5 * time.Second)\n\t stopC <- struct{}{}\n\t}()\n\t\n\t_ = <-doneC\n\t\n}", "func NewStore() *Store {\n\treturn &Store{commands: make(map[string]*Config, 0)}\n}", "func New(ctx context.Context, alias, path string, cfgdir string) (*Store, error) {\n\tpath = fsutil.CleanPath(path)\n\ts := &Store{\n\t\talias: alias,\n\t\tpath: path,\n\t\tsync: gitmock.New(),\n\t}\n\n\t// init store backend\n\tswitch backend.GetStoreBackend(ctx) {\n\tcase backend.FS:\n\t\ts.store = fs.New(path)\n\t\tout.Debug(ctx, \"Using Store Backend: fs\")\n\tcase backend.KVMock:\n\t\ts.store = kvmock.New()\n\t\tout.Debug(ctx, \"Using Store Backend: kvmock\")\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown store backend\")\n\t}\n\n\t// init sync backend\n\tswitch backend.GetSyncBackend(ctx) {\n\tcase backend.GoGit:\n\t\tout.Cyan(ctx, \"WARNING: Using experimental sync backend 'go-git'\")\n\t\tgit, err := gogit.Open(path)\n\t\tif err != nil {\n\t\t\tout.Debug(ctx, \"Failed to initialize sync backend 'gogit': %s\", err)\n\t\t} else {\n\t\t\ts.sync = git\n\t\t\tout.Debug(ctx, \"Using Sync Backend: go-git\")\n\t\t}\n\tcase backend.GitCLI:\n\t\tgpgBin, _ := gpgcli.Binary(ctx, \"\")\n\t\tgit, err := gitcli.Open(path, gpgBin)\n\t\tif err != nil {\n\t\t\tout.Debug(ctx, \"Failed to initialize sync backend 'git': %s\", err)\n\t\t} else {\n\t\t\ts.sync = git\n\t\t\tout.Debug(ctx, \"Using Sync Backend: git-cli\")\n\t\t}\n\tcase backend.GitMock:\n\t\t// no-op\n\t\tout.Debug(ctx, \"Using Sync Backend: git-mock\")\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown Sync Backend\")\n\t}\n\n\t// init crypto backend\n\tswitch backend.GetCryptoBackend(ctx) {\n\tcase backend.GPGCLI:\n\t\tgpg, err := gpgcli.New(ctx, gpgcli.Config{\n\t\t\tUmask: fsutil.Umask(),\n\t\t\tArgs: gpgcli.GPGOpts(),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts.crypto = gpg\n\t\tout.Debug(ctx, \"Using Crypto Backend: gpg-cli\")\n\tcase backend.XC:\n\t\t//out.Red(ctx, \"WARNING: Using highly experimental crypto backend!\")\n\t\tcrypto, err := xc.New(cfgdir, client.New(cfgdir))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts.crypto = crypto\n\t\tout.Debug(ctx, \"Using Crypto Backend: xc\")\n\tcase backend.GPGMock:\n\t\t//out.Red(ctx, \"WARNING: Using no-op crypto backend (NO ENCRYPTION)!\")\n\t\ts.crypto = gpgmock.New()\n\t\tout.Debug(ctx, \"Using Crypto Backend: gpg-mock\")\n\tcase backend.OpenPGP:\n\t\tcrypto, err := openpgp.New(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts.crypto = crypto\n\t\tout.Debug(ctx, \"Using Crypto Backend: openpgp\")\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"no valid crypto backend selected\")\n\t}\n\n\treturn s, nil\n}", "func Init(db *badger.DB) *Store {\n\treturn &Store{db: db}\n}", "func NewStore(c *Config) *Store {\n\t// create a new store\n\tstore := Store{}\n\tstore.config = c\n\tstore.DBname = c.DBname\n\t// check if the file exists\n\tvar build bool\n\t_, err := os.Stat(c.DBname)\n\tif err != nil {\n\t\tlogger.Critical(\"error on stat , %s\", err)\n\t\tbuild = true\n\t}\n\t// if it is a new file build some tables\n\tif build {\n\t\tstore.Build(c)\n\t}\n\tstore.leases = Load(c.DBname)\n\treturn &store\n}", "func Init() error {\n\ts, err := newStore()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcached = s\n\treturn nil\n}", "func newStore(c *Config, httpAddr, raftAddr string) *store {\n\tinternalData := meta.Data{\n\t\tIndex: 1,\n\t}\n\ts := store{\n\t\tdata: &Data{\n\t\t\tData: internalData,\n\t\t},\n\t\tclosing: make(chan struct{}),\n\t\tdataChanged: make(chan struct{}),\n\t\tpath: c.Dir,\n\t\tconfig: c,\n\t\thttpAddr: httpAddr,\n\t\traftAddr: raftAddr,\n\t\tlogger: zap.New(zap.NullEncoder()),\n\t}\n\n\treturn &s\n}", "func New(provider storage.Provider) (*Store, error) {\n\tstore, err := provider.OpenStore(nameSpace)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open unpublished operation store: %w\", err)\n\t}\n\n\treturn &Store{\n\t\tstore: store,\n\t}, nil\n}", "func (b *BadgerStore) init(dir string) error {\n\n\topts := badger.DefaultOptions(dir)\n\tif dir == \"\" {\n\t\topts = opts.WithInMemory(true)\n\t}\n\topts.Logger = &common.NoopLogger{}\n\tdb, err := badger.Open(opts)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to open database\")\n\t}\n\n\t// Set the database\n\tb.db = db\n\n\t// Initialize the default transaction that auto commits\n\t// on success ops or discards on failure.\n\t// It also enables the renewal of the underlying transaction\n\t// after executing a read/write operation\n\tb.Tx = NewTx(db, true, true)\n\n\treturn nil\n}", "func Open(ns walletdb.ReadBucket, chainParams *chaincfg.Params) (*Store, error) {\n\n\t// Open the store.\n\terr := openStore(ns)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts := &Store{chainParams, clock.NewDefaultClock(), nil} // TODO: set callbacks\n\treturn s, nil\n}", "func NewStore() *Store {\n\treturn &Store{\n\t\tls: make(map[string]InitFunc),\n\t}\n}", "func createStore(storeType, storeDir string) (core.Store, error) {\n\tswitch storeType {\n\tcase \"InMemory\":\n\t\tstore := new(core.InMemoryStore)\n\t\treturn store, core.InitializeStore(store, nil)\n\tcase \"BadgerDB\":\n\t\topts := badger.DefaultOptions\n\t\topts.Dir = storeDir\n\t\topts.ValueDir = storeDir\n\t\tstore := new(core.BadgerStore)\n\t\treturn store, core.InitializeStore(store, opts)\n\tcase \"BoltDB\":\n\t\tos.Mkdir(storeDir, os.ModePerm)\n\t\tstorePath := filepath.Join(storeDir, \"boltdbstore\")\n\t\topts := &core.BoltStoreConfig{Path: storePath, Mode: 600, Options: nil}\n\t\tstore := new(core.BoltStore)\n\t\treturn store, core.InitializeStore(store, opts)\n\t}\n\tstore := new(core.InMemoryStore)\n\treturn store, core.InitializeStore(store, nil)\n}", "func InitRedisStore(conf *viper.Viper) {\n\tpool := &redis.Pool{\n\t\tMaxIdle: 10,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\treturn redis.Dial(\n\t\t\t\t\"tcp\",\n\t\t\t\tconf.GetString(\"redis.address\"),\n\t\t\t\tredis.DialPassword(conf.GetString(\"redis.password\")),\n\t\t\t)\n\t\t},\n\t}\n\tredisStore = &RedisStore{pool}\n}", "func (ctx *Context) InitializeStores() error {\n\tvar err error\n\tctx.stores = make(map[string]*CoreStores)\n\tfor _, store := range ctx.config.Stores {\n\t\t// Initialize primary in memory store\n\t\tlog.Printf(\"Initializing Primary InMemoryStore %s\\n\", store.Name)\n\t\tnewstore := &CoreStores{}\n\t\tvar localerr error\n\t\tif newstore.primary, localerr = createStore(\"InMemory\", \"\"); localerr != nil {\n\t\t\terr = localerr\n\t\t}\n\t\t// Initialize backup store if defined\n\t\tif len(store.Backup) > 0 {\n\t\t\tlog.Printf(\"Initializing Backup Store %s of type %s, backup directory %s\\n\", store.Name, store.Backup, store.Backupdir)\n\t\t\tvar localerr error\n\t\t\tif newstore.backup, localerr = createStore(store.Backup, store.Backupdir); localerr != nil {\n\t\t\t\terr = localerr\n\t\t\t} else {\n\t\t\t\t// Once initialized we need to restore the primary store from backup store\n\t\t\t\tjsStore, serr := core.SerializeStore(newstore.backup)\n\t\t\t\tif serr != nil {\n\t\t\t\t\terr = serr\n\t\t\t\t} else {\n\t\t\t\t\tif dserr := core.DeSerializeStore(newstore.primary, jsStore); dserr != nil {\n\t\t\t\t\t\terr = dserr\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif len(store.AggregateURLs) > 0 {\n\t\t\tnewstore.shutdown = make(chan bool)\n\t\t\tgo ctx.SyncAggregateURLs(newstore, store.AggregateURLs, time.Duration(store.SyncIntervalSec)*time.Second)\n\t\t}\n\t\tctx.stores[store.Name] = newstore\n\t}\n\treturn err\n}", "func (store *Store) Init(app *ecomapp.Application) {\n\t// app.URIHandler.AddURI(\"/cart\", store.Cart)\n\tapp.URIHandler.AddURI(\"/__addtocart\", store.AddToCart)\n\tapp.URIHandler.AddURI(\"/__removefromcart\", store.RemoveFromCart)\n\tapp.URIHandler.AddURI(\"/__emptycart\", store.EmptyCart)\n\n\t// Add base data\n\tapp.ListenToHook(\"ROUTER_WILDCARD\", store.AddBaseData)\n\n\t// Load seourl's from product\n\tproductCollection := app.DB.Client.Database(\"shop\").Collection(\"product\")\n\tproductCursor, productErr := productCollection.Find(context.TODO(), bson.M{})\n\tif productErr == nil {\n\t\tfor productCursor.Next(context.TODO()) {\n\t\t\tvar seourl SEOURL\n\t\t\tproductCursor.Decode(&seourl)\n\t\t\tif len(seourl.SEOURL) > 0 {\n\t\t\t\tapp.URIHandler.AddURI(seourl.SEOURL, store.HandleProduct)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Load seourl's from category\n\tcategoryCollection := app.DB.Client.Database(\"shop\").Collection(\"category\")\n\tcategoryCursor, categoryErr := categoryCollection.Find(context.TODO(), bson.M{})\n\tif categoryErr == nil {\n\t\tfor categoryCursor.Next(context.TODO()) {\n\t\t\tvar seourl SEOURL\n\t\t\tcategoryCursor.Decode(&seourl)\n\t\t\tif len(seourl.SEOURL) > 0 {\n\t\t\t\tapp.URIHandler.AddURI(seourl.SEOURL, store.HandleCategory)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Load seourl's from brand\n\tbrandCollection := app.DB.Client.Database(\"shop\").Collection(\"brand\")\n\tbrandCursor, brandErr := brandCollection.Find(context.TODO(), bson.M{})\n\tif brandErr == nil {\n\t\tfor brandCursor.Next(context.TODO()) {\n\t\t\tvar seourl SEOURL\n\t\t\tbrandCursor.Decode(&seourl)\n\t\t\tif len(seourl.SEOURL) > 0 {\n\t\t\t\tapp.URIHandler.AddURI(seourl.SEOURL, store.HandleBrand)\n\t\t\t}\n\t\t}\n\t}\n}", "func initConfigStore(ctx context.Context, name string) error {\n\t//override default store name\n\tif name != \"\" {\n\t\tstoreName = name\n\t}\n\n\tlogger := logging.FromContext(ctx)\n\tlogger.Info(\"Initializing ConfigStore...\")\n\n\terr := loadConfigMapData(ctx)\n\tswitch {\n\tcase err == nil:\n\t\tlogger.Info(\"Config loaded succsesfully\")\n\tcase apierrors.IsNotFound(err):\n\t\tif err := createEmptyConfigMapData(ctx); err != nil {\n\t\t\tlogger.Error(\"Failed to create empty configmap\", zap.Error(err))\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\tlogger.Error(\"Failed to load configmap data:\", zap.Error(err))\n\t}\n\n\treturn nil\n}", "func NewStore(config Config) *Store {\n\terr := os.MkdirAll(config.RootDir, os.FileMode(0700))\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n\torm := models.NewORM(config.RootDir)\n\tethrpc, err := rpc.Dial(config.EthereumURL)\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n\tkeyStore := NewKeyStore(config.KeysDir())\n\n\tht, err := NewHeadTracker(orm)\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n\n\tstore := &Store{\n\t\tORM: orm,\n\t\tConfig: config,\n\t\tKeyStore: keyStore,\n\t\tExiter: os.Exit,\n\t\tClock: Clock{},\n\t\tHeadTracker: ht,\n\t\tTxManager: &TxManager{\n\t\t\tConfig: config,\n\t\t\tEthClient: &EthClient{ethrpc},\n\t\t\tKeyStore: keyStore,\n\t\t\tORM: orm,\n\t\t},\n\t}\n\treturn store\n}", "func newStoreComposerFromDataStore(store tusd.DataStore) *tusd.StoreComposer {\n composer := tusd.NewStoreComposer()\n composer.UseCore(store)\n\n if mod, ok := store.(tusd.TerminaterDataStore); ok {\n composer.UseTerminater(mod)\n }\n if mod, ok := store.(tusd.FinisherDataStore); ok {\n composer.UseFinisher(mod)\n }\n if mod, ok := store.(tusd.LockerDataStore); ok {\n composer.UseLocker(mod)\n }\n if mod, ok := store.(tusd.GetReaderDataStore); ok {\n composer.UseGetReader(mod)\n }\n if mod, ok := store.(tusd.ConcaterDataStore); ok {\n composer.UseConcater(mod)\n }\n if mod, ok := store.(tusd.LengthDeferrerDataStore); ok {\n composer.UseLengthDeferrer(mod)\n }\n\n return composer\n}", "func NewStore(schema Schema, options ...CeousOption) *BaseStore {\n\tstore := &BaseStore{\n\t\tschema: schema,\n\t}\n\tfor _, option := range options {\n\t\toption(store)\n\t}\n\tif !store.disableCache {\n\t\tstore.runner = store._runner\n\t} else {\n\t\tstore.runner = sq.NewStmtCacher(store._runner)\n\t}\n\treturn store\n}", "func initStore(ctx context.Context, opts *Opts) (*sqlx.DB, vulnstore.Store, error) {\n\t// we are going to use pgx for more control over connection pool and\n\t// and a cleaner api around bulk inserts\n\tcfg, err := pgxpool.ParseConfig(opts.ConnString)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse ConnString: %v\", err)\n\t}\n\t// set conn pool size via libvuln.Opts\n\tcfg.MaxConns = opts.MaxConnPool\n\tpool, err := pgxpool.ConnectConfig(ctx, cfg)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to create ConnPool: %v\", err)\n\t}\n\n\tdb, err := sqlx.Open(\"pgx\", opts.ConnString)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to Open db: %v\", err)\n\t}\n\n\t// do migrations if requested\n\tif opts.Migrations {\n\t\tmigrator := migrate.NewPostgresMigrator(db.DB)\n\t\tmigrator.Table = migrations.MigrationTable\n\t\terr := migrator.Exec(migrate.Up, migrations.Migrations...)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to perform migrations: %w\", err)\n\t\t}\n\t}\n\n\tstore := postgres.NewVulnStore(db, pool)\n\treturn db, store, nil\n}", "func (s *MongoStore) Initialize() error {\n\treturn nil\n}", "func ListStoreInit(treeView *gtk.TreeView) *gtk.ListStore {\n\tlistStore, err := gtk.ListStoreNew(glib.TYPE_STRING, glib.TYPE_STRING, glib.TYPE_STRING)\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to create list store:\", err)\n\t}\n\ttreeView.SetModel(listStore)\n\treturn listStore\n}", "func Init(e *echo.Echo, es *endpoint.Store) (*Keystone, error) {\n\tkeystone := &Keystone{\n\t\tendpointStore: es,\n\t\tapiClient: client.NewHTTPFromConfig(),\n\t\tlog: logutil.NewLogger(\"keystone-api\"),\n\t}\n\tassignmentType := viper.GetString(\"keystone.assignment.type\")\n\tif assignmentType == \"static\" {\n\t\tvar staticAssignment StaticAssignment\n\t\terr := config.LoadConfig(\"keystone.assignment.data\", &staticAssignment)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tkeystone.staticAssignment = &staticAssignment\n\t\tkeystone.Assignment = &staticAssignment\n\t}\n\tstoreType := viper.GetString(\"keystone.store.type\")\n\tif storeType == \"memory\" {\n\t\texpire := viper.GetInt64(\"keystone.store.expire\")\n\t\tkeystone.store = MakeInMemoryStore(time.Duration(expire) * time.Second)\n\t}\n\te.POST(\"/keystone/v3/auth/tokens\", keystone.CreateTokenAPI)\n\te.GET(\"/keystone/v3/auth/tokens\", keystone.ValidateTokenAPI)\n\n\t// TODO: Remove this, since \"/keystone/v3/projects\" is a keystone endpoint\n\te.GET(\"/keystone/v3/auth/projects\", keystone.ListProjectsAPI)\n\te.GET(\"/keystone/v3/auth/domains\", keystone.listDomainsAPI)\n\n\te.GET(\"/keystone/v3/projects\", keystone.ListProjectsAPI)\n\te.GET(\"/keystone/v3/projects/:id\", keystone.GetProjectAPI)\n\te.GET(\"/keystone/v3/domains\", keystone.listDomainsAPI)\n\n\treturn keystone, nil\n}", "func NewLibstore(masterServerHostPort, myHostPort string, mode LeaseMode) (Libstore, error) {\n\tLOGV.Println(\"[LIB]\", \"NewLibstore:\", \"Initializing....\")\n\tls := new(libstore)\n\n\tls.mode = mode\n\tls.masterServer = masterServerHostPort\n\tls.hostport = myHostPort\n\tls.storageLock = sync.Mutex{}\n\n\tqm := new(queryMaster)\n\n\tqm.queryMap = make(map[string]*queryCell)\n\tqm.deleteChan = make(chan string)\n\tqm.queryChan = make(chan *queryRequest)\n\n\tgo qm.startQueryMaster()\n\n\tcm := new(cacheMaster)\n\n\tcm.cacheMap = make(map[string]*cacheCell)\n\tcm.cacheChan = make(chan *cacheRequest)\n\tcm.newCacheChan = make(chan *cacheCell)\n\tcm.revokeCacheChan = make(chan *revokeRequest)\n\tcm.deleteCacheChan = make(chan string)\n\n\tgo cm.startCacheMaster()\n\n\tls.queryMaster = qm\n\tls.cacheMaster = cm\n\n\targs := new(storagerpc.GetServersArgs) //It's an empty struct\n\treply := new(storagerpc.GetServersReply)\n\n\tfor i := 0; i < 5; i++ {\n\t\t//Get storage server addresses, and sort them by NodeID\n\t\tclient, err := rpc.DialHTTP(\"tcp\", masterServerHostPort) //This should attempt to make contact with the master storage server\n\n\t\tif err != nil {\n\t\t\tLOGE.Println(\"[LIB]\", \"NewLibstore:\", \"Failed to connect to storage server\", err)\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\t\tdefer client.Close()\n\n\t\terr = client.Call(\"StorageServer.GetServers\", args, reply) //Make an rpc to the master server for the other nodes\n\n\t\tif err != nil { //If the call failed then return an error\n\t\t\tLOGE.Println(\"[LIB]\", \"NewLibstore:\", \"Error calling GetServers\", err)\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\n\t\tif reply.Status == storagerpc.OK {\n\t\t\tLOGV.Println(\"[LIB]\", \"NewLibstore:\", \"Recieved list of servers\")\n\t\t\tsort.Sort(Nodes(reply.Servers))\n\t\t\tls.storageservers = reply.Servers\n\t\t\tls.storageclients = make([]*rpc.Client, len(ls.storageservers))\n\n\t\t\trpc.RegisterName(\"LeaseCallbacks\", librpc.Wrap(ls))\n\n\t\t\tLOGV.Println(\"[LIB]\", \"NewLibstore:\", \"Done!\")\n\t\t\treturn ls, nil\n\t\t}\n\n\t\ttime.Sleep(time.Second)\n\t}\n\n\tLOGE.Println(\"[LIB]\", \"NewLibstore:\", \"failed to connect to server 5 times\")\n\treturn nil, errors.New(\"failed to connect to storage server 5 times\")\n}", "func (n *Node) InitStableStore() {\n\tn.StoreLog(&LogEntry{\n\t\tIndex: 0,\n\t\tTermId: 0,\n\t\tType: CommandType_NOOP,\n\t\tData: []byte{},\n\t})\n}", "func StartStoreHostService() {\n\tserviceName := common.StoreServiceName\n\tcfg := common.SetupServerConfig(configure.NewCommonConfigure())\n\tif e := os.Setenv(\"port\", fmt.Sprintf(\"%d\", cfg.GetServiceConfig(serviceName).GetPort())); e != nil {\n\t\tlog.Panic(e)\n\t}\n\n\tmeta, err := metadata.NewCassandraMetadataService(cfg.GetMetadataConfig())\n\tif err != nil {\n\t\tlog.WithField(common.TagErr, err).Fatal(`storehost: unable to instantiate metadata client`)\n\t}\n\n\thwInfoReader := common.NewHostHardwareInfoReader(meta)\n\treporter := common.NewMetricReporterWithHostname(cfg.GetServiceConfig(serviceName))\n\tdClient := dconfigclient.NewDconfigClient(cfg.GetServiceConfig(serviceName), serviceName)\n\tsCommon := common.NewService(serviceName, cfg.GetStorageConfig().GetHostUUID(), cfg.GetServiceConfig(serviceName), common.NewUUIDResolver(meta), hwInfoReader, reporter, dClient, common.NewBypassAuthManager())\n\n\t// parse args and pass them into NewStoreHost\n\tvar storeStr, baseDir string\n\n\tflag.StringVar(&storeStr, \"store\", cfg.GetStorageConfig().GetStore(), \"store to use\")\n\tflag.StringVar(&baseDir, \"dir\", \"\", \"base directory for storage\")\n\tflag.Parse()\n\n\topts := &storehost.Options{BaseDir: baseDir}\n\n\tswitch storeStr = strings.ToLower(storeStr); {\n\tcase strings.Contains(storeStr, \"rockstor\"):\n\t\topts.Store = storehost.Rockstor\n\n\tcase strings.Contains(storeStr, \"chunky\"):\n\t\topts.Store = storehost.Chunky\n\n\tcase strings.Contains(storeStr, \"manyrocks\"):\n\t\topts.Store = storehost.ManyRocks\n\n\tcase strings.Contains(storeStr, \"rockcfstor\"):\n\t\topts.Store = storehost.RockCFstor\n\n\tdefault:\n\t\t// don't set a default here; leave it to storehost\n\t}\n\n\t// BaseDir will be set from one of the following (in order):\n\tswitch {\n\tcase baseDir != \"\": // 1. if specified as command-line arg\n\t\topts.BaseDir = baseDir\n\n\tcase os.Getenv(\"CHERAMI_STORE\") != \"\": // 2. if set in env-var\n\t\topts.BaseDir = os.Getenv(\"CHERAMI_STORE\")\n\n\tcase cfg.GetStorageConfig().GetBaseDir() != \"\": // 3. yaml config \"StorageConfig.BaseDir\"\n\t\topts.BaseDir = cfg.GetStorageConfig().GetBaseDir()\n\n\tdefault:\n\t\t// if none of the above, let storehost pick default\n\t}\n\n\t// initialize and start storehost\n\th, tc := storehost.NewStoreHost(serviceName, sCommon, meta, opts)\n\n\th.Start(tc)\n\n\t// start websocket server\n\tcommon.WSStart(cfg.GetServiceConfig(serviceName).GetListenAddress().String(),\n\t\tcfg.GetServiceConfig(serviceName).GetWebsocketPort(), h)\n\n\t// start diagnosis local http server\n\tcommon.ServiceLoop(cfg.GetServiceConfig(serviceName).GetPort()+diagnosticPortOffset, cfg, sCommon)\n}", "func SeedInitialData(store store.Store) (err error) {\n\tinitializer, _ := store.NewInitializer()\n\tlogger := logger.WithField(\"component\", \"backend.seeds\")\n\n\t// Lock initialization key to avoid competing installations\n\tif err := initializer.Lock(); err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\te := initializer.Close()\n\t\tif err == nil {\n\t\t\terr = e\n\t\t}\n\t}()\n\n\t// Initialize the JWT secret. This method is idempotent and needs to be ran\n\t// at every startup so the JWT signatures remain valid\n\tif err := jwt.InitSecret(store); err != nil {\n\t\treturn err\n\t}\n\n\t// Check that the store hasn't already been seeded\n\tif initialized, err := initializer.IsInitialized(); err != nil {\n\t\treturn err\n\t} else if initialized {\n\t\treturn nil\n\t}\n\tlogger.Info(\"seeding etcd store w/ intial data\")\n\n\t// Create the default namespace\n\tif err := setupDefaultNamespace(store); err != nil {\n\t\tlogger.WithError(err).Error(\"unable to setup 'default' namespace\")\n\t\treturn err\n\t}\n\n\t// Create the default users\n\tif err := setupUsers(store); err != nil {\n\t\tlogger.WithError(err).Error(\"could not initialize the default users\")\n\t\treturn err\n\t}\n\n\t// Create the default ClusterRoles\n\tif err := setupClusterRoles(store); err != nil {\n\t\tlogger.WithError(err).Error(\"could not initialize the default ClusterRoles and Roles\")\n\t\treturn err\n\t}\n\n\t// Create the default ClusterRoleBindings\n\tif err := setupClusterRoleBindings(store); err != nil {\n\t\tlogger.WithError(err).Error(\"could not initialize the default ClusterRoles and Roles\")\n\t\treturn err\n\t}\n\n\t// Set initialized flag\n\treturn initializer.FlagAsInitialized()\n}", "func (c *Cluster) StartStore(storeID uint64) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tif store := c.stores[storeID]; store != nil {\n\t\tstore.meta.State = metapb.StoreState_Up\n\t}\n}", "func (r *StoreRepository) CreateStore(store *model.Store) error {\n\t_id := bson.NewObjectId()\n\tstore.Id = _id\n\terr := r.C.Insert(&store)\n\n\treturn err\n\n}", "func NewStore(b backend.Backend, le lease.Lessor, ig ConsistentIndexGetter) *store {\n\ts := &store{\n\t\tb: b,\n\t\tig: ig,\n\t\tkvindex: newTreeIndex(),\n\n\t\tle: le,\n\n\t\tcurrentRev: revision{main: 1},\n\t\tcompactMainRev: -1,\n\n\t\tbytesBuf8: make([]byte, 8, 8),\n\t\tfifoSched: schedule.NewFIFOScheduler(),\n\n\t\tstopc: make(chan struct{}),\n\t}\n\n\tif s.le != nil {\n\t\ts.le.SetRangeDeleter(s)\n\t}\n\n\ttx := s.b.BatchTx()\n\ttx.Lock()\n\ttx.UnsafeCreateBucket(keyBucketName)\n\ttx.UnsafeCreateBucket(metaBucketName)\n\ttx.Unlock()\n\ts.b.ForceCommit()\n\n\tif err := s.restore(); err != nil {\n\t\t// TODO: return the error instead of panic here?\n\t\tpanic(\"failed to recover store from backend\")\n\t}\n\n\treturn s\n}", "func (app *BaseApp) initFromStore() error {\n\tapp.setCheckState(abci.Header{})\n\tapp.Seal()\n\treturn nil\n}", "func NewStore(storeType string) Store {\n\tns := Store{}\n\tns.Name = \"Shop with no Sign\"\n\towner := character.NewCharacter(\"\", \"\", \"\")\n\tns.Owner = owner.Name\n\tns.Location = \"Heldheim\"\n\tns.StoreType = storeType\n\t//ns.Inventory = generateInventoryForStore()\n\tcp := 0\n\tss := 0\n\tgc := 0\n\tns.Money = NewMoney(cp, ss, gc)\n\n\treturn ns\n}", "func New(ownerRef v1.OwnerReference) Store {\n\treturn &store{\n\t\tref: ownerRef,\n\t\tours: make(map[string]*v1alpha3.ServiceEntry),\n\t\ttheirs: make(map[string]*v1alpha3.ServiceEntry),\n\t}\n}", "func (engine *Engine) storeInitWorker(shard int) {\n\tengine.dbs[shard].ForEach(func(k, v []byte) error {\n\t\tkey, value := k, v\n\t\t// 得到 docID\n\t\tdocId, _ := binary.Uvarint(key)\n\n\t\t// 得到 data\n\t\tbuf := bytes.NewReader(value)\n\t\tdec := gob.NewDecoder(buf)\n\t\tvar data types.DocData\n\t\terr := dec.Decode(&data)\n\t\tif err == nil {\n\t\t\t// 添加索引\n\t\t\tengine.internalIndexDoc(docId, data, false)\n\t\t}\n\t\treturn nil\n\t})\n\tengine.storeInitChan <- true\n}", "func NewStore()(*Store) {\n m := &Store{\n Entity: *iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.NewEntity(),\n }\n return m\n}", "func New(provider storage.Provider) (*Store, error) {\n\tstore, err := provider.OpenStore(nameSpace)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open did anchor store: %w\", err)\n\t}\n\n\treturn &Store{\n\t\tstore: store,\n\t}, nil\n}", "func Init() {\n\tif store != nil {\n\t\treturn\n\t}\n\n\tvar err error\n\tsystemDb := filepath.Join(cfg.DataDir(), \"system.db\")\n\tstore, err = bolt.Open(systemDb, 0666, nil)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\terr = store.Update(func(tx *bolt.Tx) error {\n\t\t// initialize db with all content type buckets & sorted bucket for type\n\t\tfor t := range item.Types {\n\t\t\t_, err := tx.CreateBucketIfNotExists([]byte(t))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t_, err = tx.CreateBucketIfNotExists([]byte(t + \"__sorted\"))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// init db with other buckets as needed\n\t\tbuckets = append(buckets, bucketsToAdd...)\n\n\t\tfor _, name := range buckets {\n\t\t\t_, err := tx.CreateBucketIfNotExists([]byte(name))\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\tlog.Fatalln(\"Coudn't initialize db with buckets.\", err)\n\t}\n\n\terr = LoadCacheConfig()\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to load config cache.\", err)\n\t}\n\n\tclientSecret := ConfigCache(\"client_secret\").(string)\n\n\tif clientSecret != \"\" {\n\t\tjwt.Secret([]byte(clientSecret))\n\t}\n\n\t// invalidate cache on system start\n\terr = InvalidateCache()\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to invalidate cache.\", err)\n\t}\n}", "func (s *fsStore) Init(kinds []string) error {\n\tfor _, k := range kinds {\n\t\ts.kinds[k] = true\n\t}\n\ts.checkAndUpdate()\n\tgo func() {\n\t\ttick := time.NewTicker(s.checkDuration)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-s.donec:\n\t\t\t\ttick.Stop()\n\t\t\t\treturn\n\t\t\tcase <-tick.C:\n\t\t\t\ts.checkAndUpdate()\n\t\t\t}\n\t\t}\n\t}()\n\treturn nil\n}", "func (sp *StoreProvider) Initialize() {\n\t// Noop by default\n}", "func New(ctx context.Context, alias, path string) (*Store, error) {\n\tdebug.Log(\"Instantiating %q at %q\", alias, path)\n\n\ts := &Store{\n\t\talias: alias,\n\t\tpath: path,\n\t}\n\n\t// init storage and rcs backend\n\tif err := s.initStorageBackend(ctx); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to init storage backend: %w\", err)\n\t}\n\n\tdebug.Log(\"Storage for %s => %s initialized as %v\", alias, path, s.storage)\n\n\t// init crypto backend\n\tif err := s.initCryptoBackend(ctx); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to init crypto backend: %w\", err)\n\t}\n\n\tdebug.Log(\"Crypto for %s => %s initialized as %v\", alias, path, s.crypto)\n\n\treturn s, nil\n}", "func (p *Provider) OpenStore(name string) (storage.Store, error) {\n\tp.mux.Lock()\n\tdefer p.mux.Unlock()\n\n\tif p.dbPrefix != \"\" {\n\t\tname = p.dbPrefix + \"_\" + name\n\t}\n\n\t// Check cache first\n\tcachedStore, existsInCache := p.dbs[name]\n\tif existsInCache {\n\t\treturn cachedStore, nil\n\t}\n\n\t// If it's not in the cache, then let's ask the CouchDB server if it exists\n\texistsOnServer, err := p.couchDBClient.DBExists(context.Background(), name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(dbExistsCheckFailure, err)\n\t}\n\n\tif !existsOnServer {\n\t\treturn nil, storage.ErrStoreNotFound\n\t}\n\n\tdb := p.couchDBClient.DB(context.Background(), name)\n\n\t// db.Err() won't return an error if the database doesn't exist, hence the need for the explicit DBExists call above\n\tif dbErr := db.Err(); dbErr != nil {\n\t\treturn nil, fmt.Errorf(failureWhileConnectingToDBErrMsg, dbErr)\n\t}\n\n\tstore := &CouchDBStore{db: db, marshal: json.Marshal, readAll: ioutil.ReadAll, unquote: strconv.Unquote}\n\n\tp.dbs[name] = store\n\n\treturn store, nil\n}", "func setup() (sdk.Context, store.DataStore) {\n\tdb := db.NewMemDB()\n\tms := cosmosStore.NewCommitMultiStore(db)\n\n\tctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger())\n\n\tdataStoreKey := sdk.NewKVStoreKey(\"data\")\n\n\tms.MountStoreWithDB(dataStoreKey, sdk.StoreTypeIAVL, db)\n\tms.LoadLatestVersion()\n\n\tdataStore := store.NewDataStore(dataStoreKey)\n\treturn ctx, dataStore\n}", "func NewStore(si *StoreInput) *Store {\n\tif si.Enhancer != nil {\n\t\treturn si.Enhancer(NewStore)(si.Reducer, si.State)\n\t}\n\n\tstore := &Store{\n\t\tstate: si.State,\n\t\treducer: si.Reducer,\n\n\t\tlisteners: NewListenerSet(),\n\t\tnextListeners: NewListenerSet(),\n\t}\n\n\tstore.dispatcher = makeDispatcher(store)\n\n\tstore.Dispatch(INITAction())\n\n\treturn store\n}", "func Init(ctx context.Context, s Store) error {\n\t_, _, err := s.Put(ctx, TypeTypeBlob, &TypeTypeRef)\n\treturn err\n}", "func (store *DynamoDBFeatureStore) Init(allData map[ld.VersionedDataKind]map[string]ld.VersionedData) error {\n\t// FIXME: deleting all items before storing new ones is racy, or isn't it?\n\tif err := store.truncateTable(); err != nil {\n\t\tstore.Logger.Printf(\"ERROR: Failed to truncate table: %s\", err)\n\t\treturn err\n\t}\n\n\tvar requests []*dynamodb.WriteRequest\n\n\tfor kind, items := range allData {\n\t\tfor k, v := range items {\n\t\t\tav, err := marshalItem(kind, v)\n\t\t\tif err != nil {\n\t\t\t\tstore.Logger.Printf(\"ERROR: Failed to marshal item (key=%s): %s\", k, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\trequests = append(requests, &dynamodb.WriteRequest{\n\t\t\t\tPutRequest: &dynamodb.PutRequest{Item: av},\n\t\t\t})\n\t\t}\n\t}\n\n\tif err := store.batchWriteRequests(requests); err != nil {\n\t\tstore.Logger.Printf(\"ERROR: Failed to write %d item(s) in batches: %s\", len(requests), err)\n\t\treturn err\n\t}\n\n\tstore.Logger.Printf(\"INFO: Initialized table %q with %d item(s)\", store.Table, len(requests))\n\n\tstore.initialized = true\n\n\treturn nil\n}", "func (is *ObjectStorage) InitRepo(name string) error {\n\tvar lockLatency time.Time\n\n\tis.Lock(&lockLatency)\n\tdefer is.Unlock(&lockLatency)\n\n\treturn is.initRepo(name)\n}", "func TestStoreInitAndBootstrap(t *testing.T) {\n\tmanual := hlc.ManualClock(0)\n\tclock := hlc.NewHLClock(manual.UnixNano)\n\tengine := NewInMem(Attributes{}, 1<<20)\n\tstore := NewStore(clock, engine, nil)\n\tdefer store.Close()\n\n\t// Can't init as haven't bootstrapped.\n\tif err := store.Init(); err == nil {\n\t\tt.Error(\"expected failure init'ing un-bootstrapped store\")\n\t}\n\n\t// Bootstrap with a fake ident.\n\tif err := store.Bootstrap(testIdent); err != nil {\n\t\tt.Errorf(\"error bootstrapping store: %v\", err)\n\t}\n\n\t// Try to get 1st range--non-existent.\n\tif _, err := store.GetRange(1); err == nil {\n\t\tt.Error(\"expected error fetching non-existent range\")\n\t}\n\n\t// Create range and fetch.\n\tif _, err := store.CreateRange(KeyMin, KeyMax, []Replica{}); err != nil {\n\t\tt.Errorf(\"failure to create first range: %v\", err)\n\t}\n\tif _, err := store.GetRange(1); err != nil {\n\t\tt.Errorf(\"failure fetching 1st range: %v\", err)\n\t}\n\n\t// Now, attempt to initialize a store with a now-bootstrapped engine.\n\tstore = NewStore(clock, engine, nil)\n\tif err := store.Init(); err != nil {\n\t\tt.Errorf(\"failure initializing bootstrapped store: %v\", err)\n\t}\n\t// 1st range should be available.\n\tif _, err := store.GetRange(1); err != nil {\n\t\tt.Errorf(\"failure fetching 1st range: %v\", err)\n\t}\n}", "func (m *MemEDVProvider) OpenStore(name string) (edvprovider.EDVStore, error) {\n\tcoreStore, err := m.coreProvider.OpenStore(name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open store in core provider: %w\", err)\n\t}\n\n\treturn &MemEDVStore{coreStore: coreStore}, nil\n}", "func NewStore(conf *aws.Config) Store {\n\tsess := session.Must(session.NewSession(conf))\n\tapi := s3.New(sess)\n\n\treturn Store{\n\t\tapi: api,\n\t}\n}", "func NewStore() *Store {\n\treturn &Store{\n\t\tstore: make(map[workloadmeta.Kind]map[string]workloadmeta.Entity),\n\t}\n}", "func NewStore(\n\ttracer trace.Tracer,\n\tlogger log.Logger,\n\tmetadata MetadataManager,\n\tbucket objstore.Bucket,\n\tdebuginfodClients DebuginfodClients,\n\tsignedUpload SignedUpload,\n\tmaxUploadDuration time.Duration,\n\tmaxUploadSize int64,\n) (*Store, error) {\n\treturn &Store{\n\t\ttracer: tracer,\n\t\tlogger: log.With(logger, \"component\", \"debuginfo\"),\n\t\tbucket: bucket,\n\t\tmetadata: metadata,\n\t\tdebuginfodClients: debuginfodClients,\n\t\tsignedUpload: signedUpload,\n\t\tmaxUploadDuration: maxUploadDuration,\n\t\tmaxUploadSize: maxUploadSize,\n\t\ttimeNow: time.Now,\n\t}, nil\n}", "func InitFromEnv() (faasflow.DataStore, error) {\n\n\tminioDataStore := &MinioDataStore{}\n\n\tminioDataStore.region = regionName()\n\n\tendpoint := os.Getenv(\"s3_url\")\n\n\ttlsEnabled := tlsEnabled()\n\n\tminioClient, connectErr := connectToMinio(endpoint, \"s3-secret-key\", \"s3-access-key\", tlsEnabled)\n\tif connectErr != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to initialize minio, error %s\", connectErr.Error())\n\t}\n\tminioDataStore.minioClient = minioClient\n\n\treturn minioDataStore, nil\n}", "func init() {\n\tawsSession := session.Must(session.NewSession(&aws.Config{\n\t\tRegion: aws.String(os.Getenv(\"REGION\")),\n\t}))\n\n\tif len(os.Getenv(\"DYNAMO_URL\")) > 0 {\n\t\tawsSession.Config.Endpoint = aws.String(os.Getenv(\"DYNAMO_URL\"))\n\t}\n\n\tdbs = dynamodb.New(awsSession)\n}", "func newStore() storage.Store {\n\tdata := `{\n \"management_chain\": {\n \"bob\": [\n \"ken\",\n \"janet\"\n ],\n \"alice\": [\n \"janet\"\n ]\n }\n}`\n\n\tvar json map[string]interface{}\n\n\terr := util.UnmarshalJSON([]byte(data), &json)\n\tif err != nil {\n\t\t// Handle error.\n\t}\n\n\t// Manually create the storage layer. inmem.NewFromObject returns an\n\t// in-memory store containing the supplied data.\n\tstore := inmem.NewFromObject(json)\n\treturn store\n}", "func (idx *Autoincrement) Init() error {\n\ttokenManager, err := jwt.New(map[string]interface{}{\n\t\t\"secret\": idx.cs3conf.JWTSecret,\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tidx.tokenManager = tokenManager\n\n\tclient, err := pool.GetStorageProviderServiceClient(idx.cs3conf.ProviderAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tidx.storageProvider = client\n\n\tctx, err := idx.getAuthenticatedContext(context.Background())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := idx.makeDirIfNotExists(ctx, idx.indexBaseDir); err != nil {\n\t\treturn err\n\t}\n\n\tif err := idx.makeDirIfNotExists(ctx, idx.indexRootDir); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (h *Salute) SetStore(_ PluginStore) {}", "func NewStore(lg *zap.Logger, b backend.Backend, le lease.Lessor, cfg StoreConfig) *store {\n\tif lg == nil {\n\t\tlg = zap.NewNop()\n\t}\n\tif cfg.CompactionBatchLimit == 0 {\n\t\tcfg.CompactionBatchLimit = defaultCompactBatchLimit\n\t}\n\ts := &store{\n\t\tcfg: cfg,\n\t\tb: b,\n\t\tkvindex: newTreeIndex(lg),\n\n\t\tle: le,\n\n\t\tcurrentRev: 1,\n\t\tcompactMainRev: -1,\n\n\t\tfifoSched: schedule.NewFIFOScheduler(),\n\n\t\tstopc: make(chan struct{}),\n\n\t\tlg: lg,\n\t}\n\ts.hashes = newHashStorage(lg, s)\n\ts.ReadView = &readView{s}\n\ts.WriteView = &writeView{s}\n\tif s.le != nil {\n\t\ts.le.SetRangeDeleter(func() lease.TxnDelete { return s.Write(traceutil.TODO()) })\n\t}\n\n\ttx := s.b.BatchTx()\n\ttx.LockOutsideApply()\n\ttx.UnsafeCreateBucket(buckets.Key)\n\ttx.UnsafeCreateBucket(buckets.Meta)\n\ttx.Unlock()\n\ts.b.ForceCommit()\n\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif err := s.restore(); err != nil {\n\t\t// TODO: return the error instead of panic here?\n\t\tpanic(\"failed to recover store from backend\")\n\t}\n\n\treturn s\n}", "func (es *etcdStore) Init(configBytes []byte) error {\n\tconfig := &EtcdConfig{}\n\n\t// Parse the config json\n\tif err := json.Unmarshal(configBytes, config); err != nil {\n\t\tlog.WithFields(etcdLogFields).WithFields(log.Fields{\n\t\t\t\"error\": err,\n\t\t\t\"json\": string(configBytes),\n\t\t}).Error(\"failed to unmarshal config json\")\n\t\treturn err\n\t}\n\n\tif err := config.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tes.config = config\n\tlog.WithFields(etcdLogFields).WithFields(log.Fields{\n\t\t\"config\": es.config,\n\t}).Info(\"config loaded\")\n\n\tes.prefix = path.Join(es.config.Prefix, \"images\")\n\n\t// Create the etcd client\n\tvar client *etcd.Client\n\tvar err error\n\tswitch es.config.clientNewType {\n\tcase \"file\":\n\t\tclient, err = etcd.NewClientFromFile(es.config.Filepath)\n\tcase \"tls\":\n\t\tclient, err = etcd.NewTLSClient(es.config.Machines, es.config.Cert, es.config.Key, es.config.CaCert)\n\tdefault:\n\t\tclient = etcd.NewClient(es.config.Machines)\n\t}\n\tif err != nil {\n\t\tlog.WithFields(etcdLogFields).WithFields(log.Fields{\n\t\t\t\"error\": err,\n\t\t\t\"config\": es.config,\n\t\t}).Error(\"failed to create client\")\n\t\treturn err\n\t}\n\n\tes.client = client\n\n\tif _, err := es.client.CreateDir(es.prefix, 0); err != nil {\n\t\tetcdErr, ok := err.(*etcd.EtcdError)\n\t\tif !ok || etcdErr.ErrorCode != etcderr.EcodeNodeExist {\n\t\t\tlog.WithFields(etcdLogFields).WithFields(log.Fields{\n\t\t\t\t\"error\": err,\n\t\t\t\t\"key\": es.prefix,\n\t\t\t}).Error(\"failed to create images dir\")\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func NewStore(c Config) *Store {\n\treturn &Store{\n\t\tpath: c.Dir,\n\t\thost: c.Hostname,\n\t\taddr: c.BindAddress,\n\t\tdata: &Data{},\n\t\tHeartbeatTimeout: time.Duration(c.HeartbeatTimeout),\n\t\tElectionTimeout: time.Duration(c.ElectionTimeout),\n\t\tLeaderLeaseTimeout: time.Duration(c.LeaderLeaseTimeout),\n\t\tCommitTimeout: time.Duration(c.CommitTimeout),\n\t\tLogger: log.New(os.Stderr, \"\", log.LstdFlags),\n\t}\n}", "func (idx *Unique) Init() error {\n\ttokenManager, err := jwt.New(map[string]interface{}{\n\t\t\"secret\": idx.cs3conf.JWTSecret,\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tidx.tokenManager = tokenManager\n\n\tclient, err := pool.GetStorageProviderServiceClient(idx.cs3conf.ProviderAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tidx.storageProvider = client\n\n\tctx := context.Background()\n\ttk, err := idx.authenticate(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tctx = metadata.AppendToOutgoingContext(ctx, revactx.TokenHeader, tk)\n\n\tif err := idx.makeDirIfNotExists(ctx, idx.indexBaseDir); err != nil {\n\t\treturn err\n\t}\n\n\tif err := idx.makeDirIfNotExists(ctx, idx.indexRootDir); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (engine *Engine) Store() {\n\t// if engine.initOptions.UseStore {\n\terr := os.MkdirAll(engine.initOptions.StoreFolder, 0700)\n\tif err != nil {\n\t\tlog.Fatalf(\"Can not create directory: %s ; %v\",\n\t\t\tengine.initOptions.StoreFolder, err)\n\t}\n\n\t// 打开或者创建数据库\n\tengine.dbs = make([]store.Store, engine.initOptions.StoreShards)\n\tfor shard := 0; shard < engine.initOptions.StoreShards; shard++ {\n\t\tdbPath := engine.initOptions.StoreFolder + \"/\" +\n\t\t\tStoreFilePrefix + \".\" + strconv.Itoa(shard)\n\n\t\tdb, err := store.OpenStore(dbPath, engine.initOptions.StoreEngine)\n\t\tif db == nil || err != nil {\n\t\t\tlog.Fatal(\"Unable to open database \", dbPath, \": \", err)\n\t\t}\n\t\tengine.dbs[shard] = db\n\t}\n\n\t// 从数据库中恢复\n\tfor shard := 0; shard < engine.initOptions.StoreShards; shard++ {\n\t\tgo engine.storeInitWorker(shard)\n\t}\n\n\t// 等待恢复完成\n\tfor shard := 0; shard < engine.initOptions.StoreShards; shard++ {\n\t\t<-engine.storeInitChan\n\t}\n\n\tfor {\n\t\truntime.Gosched()\n\n\t\tengine.loc.RLock()\n\t\tnumDoced := engine.numIndexingReqs == engine.numDocsIndexed\n\t\tengine.loc.RUnlock()\n\n\t\tif numDoced {\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\t// 关闭并重新打开数据库\n\tfor shard := 0; shard < engine.initOptions.StoreShards; shard++ {\n\t\tengine.dbs[shard].Close()\n\t\tdbPath := engine.initOptions.StoreFolder + \"/\" +\n\t\t\tStoreFilePrefix + \".\" + strconv.Itoa(shard)\n\n\t\tdb, err := store.OpenStore(dbPath, engine.initOptions.StoreEngine)\n\t\tif db == nil || err != nil {\n\t\t\tlog.Fatal(\"Unable to open database \", dbPath, \": \", err)\n\t\t}\n\t\tengine.dbs[shard] = db\n\t}\n\n\tfor shard := 0; shard < engine.initOptions.StoreShards; shard++ {\n\t\tgo engine.storeIndexDocWorker(shard)\n\t}\n\t// }\n}", "func NewStore() *Store {\n\treturn &Store{\n\t\topaStore: inmem.New(),\n\t}\n}", "func New(cfg *config.Config, ssmSvc ssmiface.SSMAPI) *Store {\n\treturn &Store{\n\t\tssmSvc: ssmSvc,\n\t\tcfg: cfg,\n\t}\n}", "func (s *Storage) Init() error {\n\n\tvar err error\n\n\tif s.client, err = mongo.NewClient(options.Client().ApplyURI(s.URI)); err != nil {\n\n\t\treturn err\n\n\t}\n\tif err = s.client.Connect(context.Background()); err != nil {\n\n\t\treturn err\n\n\t}\n\n\ts.db = s.client.Database(s.Database)\n\n\ts.visited = s.db.Collection(\"colly_visited\")\n\n\ts.cookies = s.db.Collection(\"colly_cookies\")\n\n\treturn nil\n\n}", "func NewStore(\n\tctx context.Context, cfg StoreConfig, eng storage.Engine, nodeDesc *roachpb.NodeDescriptor,\n) *Store {\n\t// TODO(tschottdorf): find better place to set these defaults.\n\tcfg.SetDefaults()\n\n\tif !cfg.Valid() {\n\t\tlog.Fatalf(ctx, \"invalid store configuration: %+v\", &cfg)\n\t}\n\ts := &Store{\n\t\tcfg: cfg,\n\t\tdb: cfg.DB, // TODO(tschottdorf): remove redundancy.\n\t\tengine: eng,\n\t\tnodeDesc: nodeDesc,\n\t\tmetrics: newStoreMetrics(cfg.HistogramWindowInterval),\n\t\tctSender: cfg.ClosedTimestampSender,\n\t}\n\tif cfg.RPCContext != nil {\n\t\ts.allocator = MakeAllocator(cfg.StorePool, cfg.RPCContext.RemoteClocks.Latency)\n\t} else {\n\t\ts.allocator = MakeAllocator(cfg.StorePool, func(string) (time.Duration, bool) {\n\t\t\treturn 0, false\n\t\t})\n\t}\n\ts.replRankings = newReplicaRankings()\n\n\ts.draining.Store(false)\n\ts.scheduler = newRaftScheduler(s.metrics, s, storeSchedulerConcurrency)\n\n\ts.raftEntryCache = raftentry.NewCache(cfg.RaftEntryCacheSize)\n\ts.metrics.registry.AddMetricStruct(s.raftEntryCache.Metrics())\n\n\ts.coalescedMu.Lock()\n\ts.coalescedMu.heartbeats = map[roachpb.StoreIdent][]RaftHeartbeat{}\n\ts.coalescedMu.heartbeatResponses = map[roachpb.StoreIdent][]RaftHeartbeat{}\n\ts.coalescedMu.Unlock()\n\n\ts.mu.Lock()\n\ts.mu.replicaPlaceholders = map[roachpb.RangeID]*ReplicaPlaceholder{}\n\ts.mu.replicasByKey = newStoreReplicaBTree()\n\ts.mu.uninitReplicas = map[roachpb.RangeID]*Replica{}\n\ts.mu.Unlock()\n\n\ts.unquiescedReplicas.Lock()\n\ts.unquiescedReplicas.m = map[roachpb.RangeID]struct{}{}\n\ts.unquiescedReplicas.Unlock()\n\n\ts.rangefeedReplicas.Lock()\n\ts.rangefeedReplicas.m = map[roachpb.RangeID]struct{}{}\n\ts.rangefeedReplicas.Unlock()\n\n\ts.tsCache = tscache.New(cfg.Clock)\n\ts.metrics.registry.AddMetricStruct(s.tsCache.Metrics())\n\n\ts.txnWaitMetrics = txnwait.NewMetrics(cfg.HistogramWindowInterval)\n\ts.metrics.registry.AddMetricStruct(s.txnWaitMetrics)\n\ts.snapshotApplySem = make(chan struct{}, cfg.concurrentSnapshotApplyLimit)\n\n\ts.renewableLeasesSignal = make(chan struct{})\n\n\ts.limiters.BulkIOWriteRate = rate.NewLimiter(rate.Limit(bulkIOWriteLimit.Get(&cfg.Settings.SV)), bulkIOWriteBurst)\n\tbulkIOWriteLimit.SetOnChange(&cfg.Settings.SV, func() {\n\t\ts.limiters.BulkIOWriteRate.SetLimit(rate.Limit(bulkIOWriteLimit.Get(&cfg.Settings.SV)))\n\t})\n\ts.limiters.ConcurrentImportRequests = limit.MakeConcurrentRequestLimiter(\n\t\t\"importRequestLimiter\", int(importRequestsLimit.Get(&cfg.Settings.SV)),\n\t)\n\timportRequestsLimit.SetOnChange(&cfg.Settings.SV, func() {\n\t\ts.limiters.ConcurrentImportRequests.SetLimit(int(importRequestsLimit.Get(&cfg.Settings.SV)))\n\t})\n\ts.limiters.ConcurrentExportRequests = limit.MakeConcurrentRequestLimiter(\n\t\t\"exportRequestLimiter\", int(ExportRequestsLimit.Get(&cfg.Settings.SV)),\n\t)\n\n\t// The snapshot storage is usually empty at this point since it is cleared\n\t// after each snapshot application, except when the node crashed right before\n\t// it can clean it up. If this fails it's not a correctness issue since the\n\t// storage is also cleared before receiving a snapshot.\n\ts.sstSnapshotStorage = NewSSTSnapshotStorage(s.engine, s.limiters.BulkIOWriteRate)\n\tif err := s.sstSnapshotStorage.Clear(); err != nil {\n\t\tlog.Warningf(ctx, \"failed to clear snapshot storage: %v\", err)\n\t}\n\ts.protectedtsCache = cfg.ProtectedTimestampCache\n\n\t// On low-CPU instances, a default limit value may still allow ExportRequests\n\t// to tie up all cores so cap limiter at cores-1 when setting value is higher.\n\texportCores := runtime.GOMAXPROCS(0) - 1\n\tif exportCores < 1 {\n\t\texportCores = 1\n\t}\n\tExportRequestsLimit.SetOnChange(&cfg.Settings.SV, func() {\n\t\tlimit := int(ExportRequestsLimit.Get(&cfg.Settings.SV))\n\t\tif limit > exportCores {\n\t\t\tlimit = exportCores\n\t\t}\n\t\ts.limiters.ConcurrentExportRequests.SetLimit(limit)\n\t})\n\ts.limiters.ConcurrentAddSSTableRequests = limit.MakeConcurrentRequestLimiter(\n\t\t\"addSSTableRequestLimiter\", int(addSSTableRequestLimit.Get(&cfg.Settings.SV)),\n\t)\n\taddSSTableRequestLimit.SetOnChange(&cfg.Settings.SV, func() {\n\t\ts.limiters.ConcurrentAddSSTableRequests.SetLimit(int(addSSTableRequestLimit.Get(&cfg.Settings.SV)))\n\t})\n\ts.limiters.ConcurrentRangefeedIters = limit.MakeConcurrentRequestLimiter(\n\t\t\"rangefeedIterLimiter\", int(concurrentRangefeedItersLimit.Get(&cfg.Settings.SV)),\n\t)\n\tconcurrentRangefeedItersLimit.SetOnChange(&cfg.Settings.SV, func() {\n\t\ts.limiters.ConcurrentRangefeedIters.SetLimit(\n\t\t\tint(concurrentRangefeedItersLimit.Get(&cfg.Settings.SV)))\n\t})\n\n\ts.tenantRateLimiters = tenantrate.NewLimiterFactory(cfg.Settings, &cfg.TestingKnobs.TenantRateKnobs)\n\ts.metrics.registry.AddMetricStruct(s.tenantRateLimiters.Metrics())\n\n\ts.systemConfigUpdateQueueRateLimiter = quotapool.NewRateLimiter(\n\t\t\"SystemConfigUpdateQueue\",\n\t\tquotapool.Limit(queueAdditionOnSystemConfigUpdateRate.Get(&cfg.Settings.SV)),\n\t\tqueueAdditionOnSystemConfigUpdateBurst.Get(&cfg.Settings.SV))\n\tupdateSystemConfigUpdateQueueLimits := func() {\n\t\ts.systemConfigUpdateQueueRateLimiter.UpdateLimit(\n\t\t\tquotapool.Limit(queueAdditionOnSystemConfigUpdateRate.Get(&cfg.Settings.SV)),\n\t\t\tqueueAdditionOnSystemConfigUpdateBurst.Get(&cfg.Settings.SV))\n\t}\n\tqueueAdditionOnSystemConfigUpdateRate.SetOnChange(&cfg.Settings.SV,\n\t\tupdateSystemConfigUpdateQueueLimits)\n\tqueueAdditionOnSystemConfigUpdateBurst.SetOnChange(&cfg.Settings.SV,\n\t\tupdateSystemConfigUpdateQueueLimits)\n\n\tif s.cfg.Gossip != nil {\n\t\t// Add range scanner and configure with queues.\n\t\ts.scanner = newReplicaScanner(\n\t\t\ts.cfg.AmbientCtx, s.cfg.Clock, cfg.ScanInterval,\n\t\t\tcfg.ScanMinIdleTime, cfg.ScanMaxIdleTime, newStoreReplicaVisitor(s),\n\t\t)\n\t\ts.gcQueue = newGCQueue(s, s.cfg.Gossip)\n\t\ts.mergeQueue = newMergeQueue(s, s.db, s.cfg.Gossip)\n\t\ts.splitQueue = newSplitQueue(s, s.db, s.cfg.Gossip)\n\t\ts.replicateQueue = newReplicateQueue(s, s.cfg.Gossip, s.allocator)\n\t\ts.replicaGCQueue = newReplicaGCQueue(s, s.db, s.cfg.Gossip)\n\t\ts.raftLogQueue = newRaftLogQueue(s, s.db, s.cfg.Gossip)\n\t\ts.raftSnapshotQueue = newRaftSnapshotQueue(s, s.cfg.Gossip)\n\t\ts.consistencyQueue = newConsistencyQueue(s, s.cfg.Gossip)\n\t\t// NOTE: If more queue types are added, please also add them to the list of\n\t\t// queues on the EnqueueRange debug page as defined in\n\t\t// pkg/ui/src/views/reports/containers/enqueueRange/index.tsx\n\t\ts.scanner.AddQueues(\n\t\t\ts.gcQueue, s.mergeQueue, s.splitQueue, s.replicateQueue, s.replicaGCQueue,\n\t\t\ts.raftLogQueue, s.raftSnapshotQueue, s.consistencyQueue)\n\t\ttsDS := s.cfg.TimeSeriesDataStore\n\t\tif s.cfg.TestingKnobs.TimeSeriesDataStore != nil {\n\t\t\ttsDS = s.cfg.TestingKnobs.TimeSeriesDataStore\n\t\t}\n\t\tif tsDS != nil {\n\t\t\ts.tsMaintenanceQueue = newTimeSeriesMaintenanceQueue(\n\t\t\t\ts, s.db, s.cfg.Gossip, tsDS,\n\t\t\t)\n\t\t\ts.scanner.AddQueues(s.tsMaintenanceQueue)\n\t\t}\n\t}\n\n\tif cfg.TestingKnobs.DisableGCQueue {\n\t\ts.setGCQueueActive(false)\n\t}\n\tif cfg.TestingKnobs.DisableMergeQueue {\n\t\ts.setMergeQueueActive(false)\n\t}\n\tif cfg.TestingKnobs.DisableRaftLogQueue {\n\t\ts.setRaftLogQueueActive(false)\n\t}\n\tif cfg.TestingKnobs.DisableReplicaGCQueue {\n\t\ts.setReplicaGCQueueActive(false)\n\t}\n\tif cfg.TestingKnobs.DisableReplicateQueue {\n\t\ts.SetReplicateQueueActive(false)\n\t}\n\tif cfg.TestingKnobs.DisableSplitQueue {\n\t\ts.setSplitQueueActive(false)\n\t}\n\tif cfg.TestingKnobs.DisableTimeSeriesMaintenanceQueue {\n\t\ts.setTimeSeriesMaintenanceQueueActive(false)\n\t}\n\tif cfg.TestingKnobs.DisableRaftSnapshotQueue {\n\t\ts.setRaftSnapshotQueueActive(false)\n\t}\n\tif cfg.TestingKnobs.DisableConsistencyQueue {\n\t\ts.setConsistencyQueueActive(false)\n\t}\n\tif cfg.TestingKnobs.DisableScanner {\n\t\ts.setScannerActive(false)\n\t}\n\n\treturn s\n}" ]
[ "0.71370965", "0.71370965", "0.71370965", "0.6942518", "0.684196", "0.68171936", "0.6753748", "0.674269", "0.6553233", "0.6540563", "0.6507531", "0.64896905", "0.64125925", "0.63303596", "0.6284118", "0.62639946", "0.6252602", "0.62092555", "0.6164684", "0.61394686", "0.6137611", "0.61290437", "0.6125149", "0.61110175", "0.610801", "0.6094927", "0.6072663", "0.6060061", "0.6025701", "0.5984077", "0.5981437", "0.59500444", "0.5901952", "0.589839", "0.5893285", "0.5883137", "0.586933", "0.5846014", "0.5844672", "0.58436996", "0.583593", "0.5833193", "0.5831905", "0.5824745", "0.58232784", "0.5819017", "0.58107233", "0.5799893", "0.57838327", "0.57824135", "0.57722646", "0.5771465", "0.5769153", "0.5766014", "0.57555413", "0.57359535", "0.5719661", "0.5699926", "0.5685907", "0.56773216", "0.5676747", "0.5645803", "0.564457", "0.5623743", "0.562348", "0.56201077", "0.5617908", "0.5615156", "0.5613594", "0.56073105", "0.5605411", "0.55981743", "0.55962175", "0.5595085", "0.5593413", "0.5589901", "0.55885124", "0.55855453", "0.55806315", "0.5578547", "0.55780524", "0.5561366", "0.5560255", "0.55518025", "0.5548622", "0.553979", "0.5535263", "0.55209893", "0.551997", "0.55178905", "0.5516556", "0.5510972", "0.55108297", "0.550412", "0.5502088", "0.5495242", "0.54923314", "0.5485834", "0.5483127", "0.5480471" ]
0.83667094
0
StoreCopyImageFromURL copy image form URL to Store
func StoreCopyImageFromURL(basePath, fromURL string) (key, URL string, err error) { parts := strings.Split(fromURL, "/") fileName := parts[len(parts)-1] // DL image resp, err := http.Get(fromURL) if err != nil { return } defer resp.Body.Close() key = fmt.Sprintf("%s/%s", basePath, url.QueryEscape(fileName)) URL = viper.GetString("openstack.container.url") + "/" + key // push to object storage filePath := viper.GetString("temppath") + "/image_" + uuid.NewV4().String() fd, err := os.Create(filePath) if err != nil { return } defer fd.Close() _, err = io.Copy(fd, resp.Body) if err != nil { return } fd.Seek(0, 0) if err = Store.Put(key, fd); err != nil { return } // Remove temp file os.Remove(filePath) return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d *Dao) Capture(c context.Context, url string) (loc string, size int, err error) {\n\tif err = checkURL(url); err != nil {\n\t\treturn\n\t}\n\tbs, ct, err := d.download(c, url)\n\tif err != nil {\n\t\treturn\n\t}\n\tsize = len(bs)\n\tif size == 0 {\n\t\tlog.Error(\"capture image size(%d)|url(%s)\", size, url)\n\t\treturn\n\t}\n\tif ct != \"image/jpeg\" && ct != \"image/jpg\" && ct != \"image/png\" && ct != \"image/gif\" {\n\t\tlog.Error(\"capture not allow image file type(%s)\", ct)\n\t\terr = ecode.CreativeArticleImageTypeErr\n\t\treturn\n\t}\n\tloc, err = d.Upload(c, ct, bs)\n\treturn loc, size, err\n}", "func (s *SharemeService) ImageURL(c *gae.Context, key string) string {\n\tobj := s.Get(c, key)\n\tif bb, ok := obj.(*BlobBinary); ok && strings.HasPrefix(bb.MimeType(), \"image\") {\n\t\tif url, _, err := imgurl.UrlifyR(bb, bb.MimeType(), 0, 0); err == nil {\n\t\t\treturn url\n\t\t} else {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn \"\"\n}", "func (a RegMan) Copy(imgSrc, imgDst string) error {\n\n\tsourceURL, err := getRegistryURL(a.Config.SourceRegistry.Type, a.Config.SourceRegistry.URL, imgSrc)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tdestinationURL, err := getRegistryURL(a.Config.DestinationRegistry.Type, a.Config.DestinationRegistry.URL, imgDst)\n\n\tsrcRef, err := alltransports.ParseImageName(sourceURL)\n\tif err != nil {\n\t\tlog.Errorf(\"Invalid source name %s: %v\", sourceURL, err)\n\t}\n\tdestRef, err := alltransports.ParseImageName(destinationURL)\n\tif err != nil {\n\t\tlog.Errorf(\"Invalid destination name %s: %v\", destinationURL, err)\n\t}\n\n\tlog.Debugf(\"Copy %s to %s\", sourceURL, destinationURL)\n\n\t//signBy := context.String(\"sign-by\")\n\tremoveSignatures := true\n\n\tlog.Debug(\"Start copy\")\n\terr = copy.Image(a.policy, destRef, srcRef, &copy.Options{\n\t\tRemoveSignatures: removeSignatures,\n\t\tReportWriter: os.Stdout,\n\t\tSourceCtx: a.srcCtx,\n\t\tDestinationCtx: a.dstCtx,\n\t})\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\treturn err\n}", "func (r *Repository) addImage(url string) error {\n\tif !isImage(url) {\n\t\treturn fmt.Errorf(\"not a supported image type\")\n\t}\n\n\tfilename, err := getFilename(url)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error parsing url: %w\", err)\n\t}\n\tfilename = filepath.Join(r.root, filename)\n\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error fetching image: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\timage, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading image: %w\", err)\n\t}\n\terr = os.WriteFile(filename, image, 0666)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error saving image: %w\", err)\n\t}\n\n\treturn nil\n}", "func (i *ImageStore) Save(\n\tctx context.Context, ref types.ImageReference,\n) (types.ImageReference, func(), error) {\n\tdstref, cleanup, err := i.NewLocalReference()\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error creating temp file: %w\", err)\n\t}\n\n\t_, err = imgcopy.Image(\n\t\tctx, i.polctx, dstref, ref, &imgcopy.Options{\n\t\t\tSourceCtx: i.regctx,\n\t\t},\n\t)\n\tif err != nil {\n\t\tcleanup()\n\t\treturn nil, nil, fmt.Errorf(\"unable to copy image: %w\", err)\n\t}\n\n\treturn dstref, cleanup, nil\n}", "func (pr *PhotosRepo) Upload(imageUrl string) (int64, error) {\n\tinsertQuery := `INSERT INTO photos(image_url) VALUES(?)`\n\tstatement, err := pr.db.Prepare(insertQuery)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tres, err := statement.Exec(imageUrl)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn id, nil\n}", "func (b *Executor) copyExistingImage(ctx context.Context, cacheID string) error {\n\t// Get the destination Image Reference\n\tdest, err := b.resolveNameToImageRef()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpolicyContext, err := util.GetPolicyContext(b.systemContext)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer policyContext.Destroy()\n\n\t// Look up the source image, expecting it to be in local storage\n\tsrc, err := is.Transport.ParseStoreReference(b.store, cacheID)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"error getting source imageReference for %q\", cacheID)\n\t}\n\tif _, err := cp.Image(ctx, policyContext, dest, src, nil); err != nil {\n\t\treturn errors.Wrapf(err, \"error copying image %q\", cacheID)\n\t}\n\tb.log(\"COMMIT %s\", b.output)\n\treturn nil\n}", "func (c *Client) copyImage(src, dst string) error {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Duration(c.copyTimeoutSeconds)*time.Second)\n\tdefer cancel()\n\tcmdStr := c.skopeoCopyCmd(src, dst)\n\tlogf.Log.WithName(\"registry_client\").V(1).Info(\"Command\", cmdStr)\n\tcmdSl := strings.Split(cmdStr, \" \")\n\treturn exec.CommandContext(ctx, cmdSl[0], cmdSl[1:]...).Run()\n}", "func StoreImages(idPath string) error {\n respProc := func(id string, bodyRdr io.Reader) error {\n body, err := ioutil.ReadAll(bodyRdr)\n if err != nil { return importError{err} }\n return ioutil.WriteFile(imagePath(id), body, STORE_PERM)\n }\n\n return downloadImages(idPath, respProc)\n}", "func (t Tasker) ImageCreation(url, assetID string, w, h int) error {\n\tb, err := t.Download(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\timg, _, _ := image.Decode(bytes.NewReader(b))\n\n\tanalyzer := smartcrop.NewAnalyzer(nfnt.NewDefaultResizer())\n\ttopCrop, _ := analyzer.FindBestCrop(img, w, h)\n\n\t// The crop will have the requested aspect ratio, but you need to copy/scale it yourself\n\tt.logger.Infof(\"Top crop: %+v\\n\", topCrop)\n\n\ttype SubImager interface {\n\t\tSubImage(r image.Rectangle) image.Image\n\t}\n\tcroppedimg := img.(SubImager).SubImage(topCrop)\n\n\twr, err := t.bucket.NewWriter(context.Background(), assetID+\"/thumbnail.jpg\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer wr.Close()\n\n\tif err = jpeg.Encode(wr, croppedimg, &jpeg.Options{Quality: 85}); err != nil {\n\t\treturn err\n\t}\n\n\tthumbnail := opendamclient.Asset{\n\t\tAssetId: uuid.New().String(),\n\t\tKind: \"image\",\n\t\tVersion: opendamclient.Version{},\n\t\tFile: opendamclient.AssetFile{\n\t\t\tName: \"thumbnail.jpg\",\n\t\t\tSource: assetID + \"/thumbnail.jpg\",\n\t\t\tContentType: \"image/jpeg\",\n\t\t\tWidth: float32(w),\n\t\t\tHeight: float32(h),\n\t\t\tSize: 0,\n\t\t},\n\t}\n\tjob, resp, err := t.api.PutAsset(context.Background(), assetID, opendamclient.AssetUpdate{\n\t\tFormats: []opendamclient.Asset{thumbnail},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.logger.WithFields(logrus.Fields{\n\t\t\"job\": job,\n\t\t\"resp\": resp,\n\t}).Debug(\"asset put response\")\n\treturn nil\n}", "func (app *Application) URLHandler() http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {\n\t\tvars := mux.Vars(request)\n\t\tstorage := app.Config.Storages[vars[\"bucket\"]]\n\n\t\trequest.ParseForm()\n\n\t\turl := request.FormValue(\"url\")\n\t\tparts := strings.Split(url, \"/\")\n\t\tfilename := parts[len(parts)-1]\n\n\t\tfmt.Println(\"fetching\", url)\n\n\t\t// fetch the image from the URL specified\n\t\tresponse, err := http.Get(url)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(w, \"Unable to fetch the url. Check it exists.\")\n\t\t\treturn\n\t\t}\n\t\tdefer response.Body.Close()\n\t\tfmt.Println(response.Status)\n\n\t\t// TODO: way too much code duplication from here on with UploadHandler\n\n\t\tout, err := ioutil.TempFile(\"\", \"fetched_image_\")\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(w, \"Unable to create the file for writing. Check your write access privilege\")\n\t\t\treturn\n\t\t}\n\n\t\tdefer out.Close()\n\n\t\t_, err = io.Copy(out, response.Body)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(w, err)\n\t\t}\n\n\t\timage, err := app.StoreFile(storage, out, out.Name(), filename)\n\n\t\tif err != nil {\n\t\t\tapp.logger.Println(\"Error storing file\", err)\n\t\t\treturn\n\t\t}\n\n\t\timage.Identify()\n\n\t\tcontent, err := json.Marshal(map[string]string{\n\t\t\t\"id\": image.Key,\n\t\t\t\"filename\": filename,\n\t\t\t\"format\": image.MimeType,\n\t\t\t\"size\": strconv.FormatInt(image.Size, 10),\n\t\t})\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(content)\n\t})\n}", "func ImageSaveHandler(rw http.ResponseWriter, req *http.Request) {\n\trw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\trw.Header().Set(\"Access-Control-Allow-Headers\", \"Origin, X-Requested-With, Content-Type, Accept, Authorization\")\n\trw.Header().Set(\"Access-Control-Allow-Methods\", \"POST\")\n\tvar m Upload\n\tb, _ := ioutil.ReadAll(req.Body)\n\tjson.Unmarshal(b, &m)\n\n\tbs := base64StringtoByte(m.Image)\n\n\tnowTime := time.Now().Unix()\n\tfilename := fmt.Sprintf(\"%d.png\", nowTime)\n\n\timg := NewUpload(bs, filename)\n\n\tthumb, err := imageupload.ThumbnailPNG(img, 300, 300)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ts3FileName, err := uploadS3(filename, thumb.Data)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdb := ConectDB()\n\tdefer db.Close()\n\n\tstmtIns, err := db.Prepare(fmt.Sprintf(\"INSERT INTO photos ( `lat`, `title`, `long`, `region`, `season`, `era`, `image`, `get_type`,`created_at`, `updated_at`) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\"))\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tdefer stmtIns.Close()\n\n\tt, err := strconv.ParseFloat(m.Date, 64)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(t / 1000)\n\tdateU := time.Unix(int64(t)/1000, 0)\n\tfmt.Println(dateU)\n\t_, err = stmtIns.Exec(m.Lat, m.Title, m.Long, \"Aizu\", getSeason(dateU), string(dateU.Year()), s3FileName, \"remote_test\", time.Now(), time.Now())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n}", "func (c *cache) store(src, key string) {\n\tlog.Debug(\"Storing blob %s (from %s) in local cache\", key, src)\n\tdest := c.path(key)\n\tif _, err := os.Stat(dest); err == nil {\n\t\tlog.Debug(\"Artifact %s already exists in cache, not storing\", key)\n\t} else if err := os.MkdirAll(path.Dir(dest), os.ModeDir|0755); err != nil {\n\t\tlog.Warning(\"Failed to store %s in cache: %s\", src, err)\n\t} else if err := c.copier.LinkMode(src, dest, 0555); err != nil {\n\t\tlog.Warning(\"Failed to store %s in cache: %s\", src, err)\n\t}\n}", "func StoreUrl(c *gin.Context) {\n\torigin := c.PostForm(\"long_url\")\n\tfmt.Println(origin)\n\tstr := storage.RedisPool.StoreLongUrl2Redis(origin)\n\tif str == \"\" {\n\t\tc.JSON(500, gin.H{\n\t\t\t\"surl\": \"\",\n\t\t\t\"msg\": \"failed\",\n\t\t})\n\t} else {\n\t\tc.JSON(200, gin.H{\n\t\t\t\"surl\": str,\n\t\t\t\"msg\": \"success\",\n\t\t})\n\t}\n}", "func Store(key string, i image.Image, maxsize int, storename string) (image.Image) {\n\t// store big image\n\ti = resizeImage(i, maxsize) // Масштабируем пропорционально до maxsize пикселей, если какая-либо сторона больше. \n\n // Encode as a new JPEG image.\n\tbuf := new(bytes.Buffer)\n\tbuf.Reset()\n\terr := jpeg.Encode(buf, i, nil)\n\terrors.Check(err)\n\n\tvar barray []byte = buf.Bytes()\n\tmu.Lock()\n\tstorage, _ :=gocask.NewGocask(\"images/\" + storename)\n\terr = storage.Put(key, barray)\n\tstorage.Close()\n\tmu.Unlock()\n\terrors.Check(err)\n\treturn i\n}", "func CopyURL(i *url.URL) *url.URL {\n\tout := *i\n\tif i.User != nil {\n\t\tout.User = &(*i.User)\n\t}\n\treturn &out\n}", "func (client *APIClient) ImageSave(ctx context.Context, imageName string) (io.ReadCloser, error) {\n\tq := url.Values{}\n\tq.Set(\"name\", imageName)\n\n\tresp, err := client.get(ctx, \"/images/save\", q, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp.Body, nil\n}", "func uploadToS3(data urlbox.ShotData) (s3Link string) {\n\tif data.URL != \"\" && data.Width > 0 && data.Height > 0 {\n\t\tawsSecret := os.Getenv(\"SNAPMAKER_AWS_ACCESS_SECRET\")\n\t\tawsKey := os.Getenv(\"SNAPMAKER_AWS_ACCESS_KEY\")\n\n\t\tif awsSecret == \"\" || awsKey == \"\" {\n\t\t\tlog.Fatal(\"[!]invalid AWS credentials\")\n\t\t}\n\t\tauth, _ := aws.GetAuth(awsKey, awsSecret)\n\t\tclient := s3.New(auth, aws.USEast)\n\n\t\tsnapBucket := client.Bucket(BUCKETNAME)\n\n\t\tfileName := urlbox.GetFileName(data)\n\t\tbytes, filetype := getFile(fileName)\n\t\tsnapBucket.Put(fileName, bytes, filetype, s3.PublicRead)\n\t\ts3Link = snapBucket.URL(fileName)\n\t\tos.Remove(fileName)\n\t}\n\treturn\n}", "func (s *SharemeService) UploadURL(c *gae.Context, cont *Container) string {\n\turl, err := s.storageService.UploadURL(c)\n\tlog.Printf(\"Generated url :'%s'\", url.String())\n\tif err != nil {\n\t\tlog.Printf(\"Could not generate UpladURL %s\", err)\n\t}\n\n\treturn url.String()\n}", "func saveTagImage(tidx tagindex) (*os.File, func(), error) {\n\tfsh := fs.New(\"\")\n\tfp, cleanup, err := fsh.TempFile()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstr := fmt.Sprintf(\"docker-archive:%s\", fp.Name())\n\tdstref, err := alltransports.ParseImageName(str)\n\tif err != nil {\n\t\tcleanup()\n\t\treturn nil, nil, err\n\t}\n\n\tsrcref, err := tidx.localref()\n\tif err != nil {\n\t\tcleanup()\n\t\treturn nil, nil, err\n\t}\n\n\tpol := &signature.Policy{\n\t\tDefault: signature.PolicyRequirements{\n\t\t\tsignature.NewPRInsecureAcceptAnything(),\n\t\t},\n\t}\n\tpctx, err := signature.NewPolicyContext(pol)\n\tif err != nil {\n\t\tcleanup()\n\t\treturn nil, nil, err\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Minute)\n\tdefer cancel()\n\n\tif _, err := imgcopy.Image(\n\t\tctx, pctx, dstref, srcref, &imgcopy.Options{},\n\t); err != nil {\n\t\tcleanup()\n\t\treturn nil, nil, err\n\t}\n\n\treturn fp, cleanup, err\n}", "func (a *API) CopyImage(source_id, dest_name, dest_region, dest_description, kms_key_id string, encrypted bool) (string, error) {\n\trequest := ecs.CreateCopyImageRequest()\n\trequest.Scheme = \"https\"\n\trequest.ImageId = source_id\n\trequest.DestinationImageName = dest_name\n\trequest.DestinationRegionId = dest_region\n\trequest.DestinationDescription = dest_description\n\trequest.KMSKeyId = kms_key_id\n\trequest.Encrypted = requests.NewBoolean(encrypted)\n\trequest.Tag = &[]ecs.CopyImageTag{\n\t\t{\n\t\t\tKey: \"created-by\",\n\t\t\tValue: \"mantle\",\n\t\t},\n\t}\n\n\tresponse, err := a.ecs.CopyImage(request)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"copying image: %v\", err)\n\t}\n\treturn response.ImageId, nil\n}", "func DownloadAndCacheImage(imageURL string, storageDriver storage.Driver, async bool, logger *log.Logger) error {\n\tjob, err := createJobFromImageURL(imageURL)\n\tif err != nil {\n\t\tlogger.Printf(\"Error: URL could not be parsed: %s\", imageURL)\n\t\treturn err\n\t}\n\n\tcurrentTime := time.Now()\n\texist, err := storageDriver.Exists(job.Source.Hash, \"source/\")\n\texistTime := time.Since(currentTime).Seconds()\n\tif exist == true {\n\t\tlogger.Printf(\"Image URL is already cached: %s\\n\\t=> CACHE %0.5fs\", imageURL, existTime)\n\t} else if err != nil {\n\t\tlogger.Printf(\"Error: Could not acces to google cloud storage with image url: \\\"%s\\\". Error %s\", imageURL, err)\n\t\traven.CaptureErrorAndWait(err, nil)\n\t\treturn err\n\t} else {\n\t\tcurrentTime := time.Now()\n\t\tbody, err := job.Source.Download()\n\t\tdownloadTime := time.Since(currentTime).Seconds()\n\t\tif err != nil {\n\t\t\tlogger.Printf(\"Image could not be downloaded: %s \\n\\t=> CACHE %0.5fs - DOWNLOAD %0.5fs\",\n\t\t\t\timageURL, existTime, downloadTime)\n\t\t\treturn nil\n\t\t}\n\t\tif async {\n\t\t\tgo func() {\n\t\t\t\traven.CapturePanic(func() {\n\t\t\t\t\tstoreImageAndPrintLogs(job, body, storageDriver, logger, existTime, downloadTime)\n\t\t\t\t}, nil)\n\t\t\t}()\n\t\t} else {\n\t\t\tstoreImageAndPrintLogs(job, body, storageDriver, logger, existTime, downloadTime)\n\t\t}\n\t}\n\treturn nil\n}", "func (f *UniqueFetcher) uniqueFetch(c chan FetchResult) {\n\turl := f.Source\n\tdestination := f.Destination\n\tvar err error\n\n\tmu.Lock()\n\t_, present := ImageDownloads[url]\n\tif present {\n\t\tImageDownloads[url] = append(ImageDownloads[url], c)\n\t\tmu.Unlock()\n\t} else {\n\t\tImageDownloads[url] = []chan FetchResult{c}\n\t\tmu.Unlock()\n\n\t\tdefer func() {\n\t\t\tmu.Lock()\n\t\t\tdelete(ImageDownloads, url)\n\t\t\tmu.Unlock()\n\t\t}()\n\n\t\t// only copy image if does not exist\n\t\tif _, err = os.Stat(destination); os.IsNotExist(err) {\n\t\t\tdir := filepath.Dir(destination)\n\t\t\tos.MkdirAll(dir, 0700)\n\n\t\t\tfetcher := &httpFetcher.Fetcher{}\n\t\t\terr = fetcher.Fetch(url, destination)\n\t\t}\n\n\t\tmu.Lock()\n\t\tif err == nil {\n\t\t\tglog.Infof(\"Notifying download complete for path %s\", destination)\n\t\t\tf.notifyDownloadComplete(url)\n\t\t} else {\n\t\t\tglog.Infof(\"Unable to download image %s\", err)\n\t\t\tf.notifyDownloadFailed(url, err)\n\t\t}\n\t\tmu.Unlock()\n\t}\n}", "func (image Image) Store(data []byte, root string) (string, error) {\n\tvar i = 1\n\tvar originFileBase = path.Base(image.FileName)\n\tvar extension = path.Ext(originFileBase)\n\tvar fileName = originFileBase[0 : len(originFileBase)-len(extension)]\n\troot = strings.TrimRight(root, \"/\")\n\n\tvar err = saveTo(root+\"/\"+image.FileName, data)\n\tfor ; err == os.ErrExist; err = saveTo(root+\"/\"+image.FileName, data) {\n\t\timage.FileName = fmt.Sprintf(\"%s_%d%s\", fileName, i, extension)\n\t\ti++\n\t}\n\treturn image.FileName, err\n}", "func (f *Frontend) fetchImage(i *img.Image) (*img.Image, error) {\n\tvar err error\n\n\t// go through image proxy to resize and cache the image\n\tkey := hmacKey(i.ID)\n\tu := fmt.Sprintf(\"%v/image/225x,s%v/%v\", f.Host, key, i.ID)\n\tfmt.Println(u)\n\n\tresp, err := f.Images.Client.Get(u)\n\tif err != nil {\n\t\treturn i, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tbdy, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn i, err\n\t}\n\n\ti.Base64 = base64.StdEncoding.EncodeToString(bdy)\n\treturn i, err\n}", "func (m *InMemoryRepository) Copy(source, destination fyne.URI) error {\n\treturn repository.GenericCopy(source, destination)\n}", "func saveImage(issue Issue) (string, error) {\n\t// We take the string's hash to be the directory we will be using to save the issue\n\t// The reason why we are hashing the link is as they will generally be unique from issue to issue and that reduces the number of possible hash collisions\n\timageSaveDir := util.HashString(issue.Link)\n\n\t// Create the directory that will be used to save the image\n\tfourUDir := fmt.Sprintf(\"/4U/%s/%s/%s\", issue.TypePost, imageSaveDir, issue.Name)\n\tfile, err := filesint.CreateFile(\"assets\", fourUDir, issue.PictureHeader.Filename)\n\tif err != nil {\n\t\treturn \"\", errors.New(\"could not create image\")\n\t}\n\n\t// Copy the actual image into the file object\n\tio.Copy(file, issue.Picture)\n\n\treturn fourUDir, nil\n}", "func (m Mux) Transfer(ctx context.Context, dsturl, srcurl string) error {\n\tsrcB, src, err := m.Bucket(ctx, srcurl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdstB, dst, err := m.Bucket(ctx, dsturl)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn dstB.CopyFrom(ctx, srcB, src, dst)\n}", "func (gcs *StorageConnection) StoreInBucket(ctx context.Context, fileName, url string) (err error) {\n\tvar response *http.Response\n\t//TODO add more filename validation\n\tif fileName == \"\" {\n\t\treturn fmt.Errorf(\"Filename is empty.\")\n\t}\n\t// Get HTTP response\n\tresponse, err = http.Get(url)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"HTTP response returned an error: %v\", err)\n\t}\n\tdefer response.Body.Close()\n\n\tif response.StatusCode == http.StatusOK {\n\t\tobj := gcs.bucket.Object(fileName)\n\n\t\t// w implements io.Writer.\n\t\tw := obj.NewWriter(ctx)\n\n\t\t// Copy file into storage\n\t\t_, err = io.Copy(w, response.Body)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to copy %v to bucket with the error: %v\", fileName, err)\n\t\t}\n\n\t\tif err = w.Close(); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to close storage connection: %v\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Client) ProductImageUploadByURL(productID ID, imageURL string) (ID, error) {\n\tresponse, err := c.R().\n\t\tSetQueryParam(\"externalUrl\", imageURL).\n\t\tPost(fmt.Sprintf(\"/products/%d/image\", productID))\n\n\treturn responseAdd(response, err)\n}", "func (s Store) AddURL(url string) (string, error) {\n\turl = strings.TrimSpace(url)\n\tif url == \"\" {\n\t\treturn \"\", fmt.Errorf(\"Empty url is not allowed\")\n\t}\n\tid := s.getID(url)\n\tif id != \"\" {\n\t\treturn id, nil\n\t}\n\n\tid = newID()\n\tif err := s.put(id, url); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn id, nil\n}", "func (u *uploadToDiskProgress) transferImage(transfer imageTransfer, transferURL string) error {\n\treturn retry(\n\t\tfmt.Sprintf(\n\t\t\t\"transferring image for disk %s via HTTP request to %s\",\n\t\t\tu.disk.ID(),\n\t\t\ttransferURL,\n\t\t),\n\t\tu.client.logger,\n\t\tu.retries,\n\t\tfunc() error {\n\t\t\treturn u.putRequest(transferURL, transfer)\n\t\t},\n\t)\n}", "func (p *Provider) Store(url, alias string) error {\n\texists, _ := p.Exists(alias)\n\tif exists {\n\t\treturn storage.ErrAlreadyExists\n\t}\n\n\tp.mutex.Lock()\n\terr := ioutil.WriteFile(filepath.Join(p.Config.Path, alias), bytes.TrimSpace([]byte(url)), 0644)\n\tp.mutex.Unlock()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func getImageURL(hostBase string, organization string, application string, revision string) string {\n\treturn fmt.Sprintf(\"%s/version/%s\", getApplicationURL(hostBase, organization, application), revision)\n}", "func (store *DiskImageStore) Save(laptopID string, imageType string, imageData bytes.Buffer) (string, error) {\n\timageID, err := uuid.NewRandom()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"cannot generate image id : %w\", err)\n\t}\n\n\t// imagePath := fmt.Sprintf(\"image path %s/%s%s\", store.imageFolder, imageID, imageType)\n\timagePath := filepath.Join(store.imageFolder, imageID.String()+imageType)\n\tfile, err := os.Create(imagePath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"cannot create image file: %w\", err)\n\t}\n\n\tlog.Print(\"filepath is: \", imagePath)\n\t_, err = imageData.WriteTo(file)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"cannot write image to file: %w\", err)\n\t}\n\n\tstore.mutex.Lock()\n\tdefer store.mutex.Unlock()\n\n\tstore.images[imageID.String()] = &ImageInfo{\n\t\tLaptopID: laptopID,\n\t\tType: imageType,\n\t\tPath: imagePath,\n\t}\n\n\treturn imageID.String(), nil\n}", "func SendImageToServer(im *gdk.Pixbuf, url string) (string, error) {\n\tfilename := GetConfig().TmpFolder + \"/temp_img_buf\"\n\tif err := im.SavePNG(filename, 9); err != nil {\n\t\treturn \"\", err\n\t}\n\tcontent, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif fileUrl, err := postFile(content, \"png\", url); err != nil {\n\t\treturn \"\", err\n\t} else {\n\t\treturn fileUrl, nil\n\t}\n}", "func (ui *URLInserter) Save(ctx context.Context, url *entity.URL) error {\n\tif url == nil {\n\t\treturn entity.ErrEmptyURL()\n\t}\n\n\tif err := ui.database.Insert(ctx, url); err != nil {\n\t\treturn err\n\t}\n\t_ = ui.cache.Save(ctx, url)\n\treturn nil\n}", "func (o *Object) ImageURL() string {\n\treturn o.Get(\"og:image\")\n}", "func AddImage(config AddConfig) error {\n\terr := config.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgridDirPath, _, err := config.ResultDetails.DataVerifier.GridDirPath(config.ResultDetails.OwnerUserId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgameId := naming.LegacyNonSteamGameId(config.ResultDetails.GameName, config.ResultDetails.GameExecutablePath)\n\n\tresultingFilePath := path.Join(gridDirPath, gameId)\n\n\textensionIndex := strings.LastIndex(config.ImageSourcePath, \".\")\n\tif extensionIndex > 0 {\n\t\tresultingFilePath = resultingFilePath + config.ImageSourcePath[extensionIndex:]\n\t}\n\n\tif !config.OverwriteExisting {\n\t\t_, statErr := os.Stat(resultingFilePath)\n\t\tif statErr == nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tsource, err := os.Open(config.ImageSourcePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer source.Close()\n\n\tdest, err := os.OpenFile(resultingFilePath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, config.Mode)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer dest.Close()\n\n\t_, err = io.Copy(dest, source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *Client) Image(fileID string, page int) (file []byte, err error) {\n\tif page <= 0 {\n\t\tpage = 1\n\t}\n\tqueryParam := fmt.Sprintf(\"?page=%d\", page)\n\turl := strings.Join([]string{s.config.apiBaseURL, \"/result/image/\", fileID, queryParam}, \"\")\n\n\tlog.Printf(\"get image url %s\", url)\n\treq, err := http.NewRequest(\"GET\", url, strings.NewReader(\"\"))\n\tif err != nil {\n\t\treturn\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"Authorization\", strings.Join([]string{\"Bearer \", s.getToken()}, \"\"))\n\n\tres, err := s.httpClient.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\tfile, err = ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func RemoteCopyImage(cli bce.Client, imageId string, args *RemoteCopyImageArgs) error {\n\t// Build the request\n\treq := &bce.BceRequest{}\n\treq.SetUri(getImageUriWithId(imageId))\n\treq.SetMethod(http.POST)\n\n\treq.SetParam(\"remoteCopy\", \"\")\n\n\tjsonBytes, err := json.Marshal(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbody, err := bce.NewBodyFromBytes(jsonBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.SetBody(body)\n\n\t// Send request and get response\n\tresp := &bce.BceResponse{}\n\tif err := cli.SendRequest(req, resp); err != nil {\n\t\treturn err\n\t}\n\tif resp.IsFail() {\n\t\treturn resp.ServiceError()\n\t}\n\n\tdefer func() { resp.Body().Close() }()\n\treturn nil\n}", "func uploadImage(ctx context.Context, bucket *storage.BucketHandle, extension string, content []byte) (string, error) {\n\t// use a hash of the image content as the filename\n\thash := sha256.Sum256(content)\n\thexhash := hex.EncodeToString(hash[:8]) // we just take the first 8 bytes for brevity\n\tname := hexhash + extension\n\tobj := bucket.Object(name)\n\n\t// write the image to the storage bucket\n\twr := obj.NewWriter(ctx)\n\tdefer wr.Close()\n\n\t_, err := wr.Write(content)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error writing image to cloud storage: %w\", err)\n\t}\n\terr = wr.Close()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error writing image to cloud storage: %w\", err)\n\t}\n\n\t// construct URL for the uploaded image\n\turl := fmt.Sprintf(\"https://storage.googleapis.com/%s/%s\", obj.BucketName(), obj.ObjectName())\n\treturn url, nil\n}", "func (c *Client) Image(ctx context.Context, number int) (io.Reader, string, error) {\n\tcomic, err := c.Get(ctx, number)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", comic.ImageURL, nil)\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"failed to build image request: %s\", err)\n\t}\n\treq = req.WithContext(ctx)\n\n\trsp, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"failed to do image request: %s\", err)\n\t}\n\tdefer drainAndClose(rsp.Body)\n\n\tif rsp.StatusCode != 200 {\n\t\treturn nil, \"\", StatusError{Code: rsp.StatusCode}\n\t}\n\n\tvar buf bytes.Buffer\n\tif _, err := io.Copy(&buf, rsp.Body); err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"failed to do copy image: %s\", err)\n\t}\n\n\treturn &buf, rsp.Header.Get(\"Content-Type\"), nil\n}", "func (i *ImageStore) Load(\n\tctx context.Context,\n\tsrcref types.ImageReference,\n\tsrcctx *types.SystemContext,\n\trepo string,\n\tname string,\n) (types.ImageReference, error) {\n\ttostr := fmt.Sprintf(\"docker://%s/%s/%s\", i.regaddr, repo, name)\n\ttoref, err := alltransports.ParseImageName(tostr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid destination reference: %w\", err)\n\t}\n\n\tmanblob, err := imgcopy.Image(\n\t\tctx, i.polctx, toref, srcref, &imgcopy.Options{\n\t\t\tImageListSelection: imgcopy.CopyAllImages,\n\t\t\tSourceCtx: srcctx,\n\t\t\tDestinationCtx: i.regctx,\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to load image: %w\", err)\n\t}\n\n\tdgst, err := manifest.Digest(manblob)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error calculating manifest digest: %w\", err)\n\t}\n\n\trefstr := fmt.Sprintf(\"docker://%s@%s\", toref.DockerReference().Name(), dgst)\n\thashref, err := alltransports.ParseImageName(refstr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn hashref, nil\n}", "func storeURL(c *gin.Context, url string) {\n\tapiKey := os.Getenv(\"API_KEY\")\n\tapiKeyParam := c.Query(\"api_key\")\n\tif apiKey == apiKeyParam {\n\t\tresponse, err := handleDownload(url)\n\t\tif err == nil {\n\t\t\tc.JSON(http.StatusOK, response)\n\t\t} else {\n\t\t\tc.JSON(http.StatusUnprocessableEntity, response)\n\t\t}\n\t} else {\n\t\tc.String(http.StatusUnauthorized, fmt.Sprintf(\"invalid api key %s\", apiKeyParam))\n\t}\n}", "func (c *APIContext) ImagePut(res web.ResponseWriter, req *web.Request) {\n\n\tid := req.PathParams[\"image_id\"]\n\n\tdata, err := ioutil.ReadAll(req.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Invalid data for image %s from user %s\", id, c.User)\n\t\tres.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\timg := &models.Image{}\n\tif err := json.Unmarshal(data, img); err != nil {\n\t\tlog.Printf(\"Invalid JSON for image %s from user %s (%s)\", id, c.User, err)\n\t\tres.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif img.Exists(c.Database) {\n\t\tlog.Printf(\"Ignoring previously uploaded image %s\", id)\n\t\tres.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprint(res, JSON{\"error\": \"Image already exists\"})\n\t\treturn\n\t}\n\n\tif err := img.Create(c.Database); err != nil {\n\t\tlog.Printf(\"Error while saving image %s for user %s (%s)\", id, c.User, err)\n\t\tres.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tres.WriteHeader(http.StatusOK)\n\tlog.Printf(\"Created image %s\", req.PathParams[\"image_id\"])\n\n\treturn\n\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 (server *LaptopServer) UploadImage(stream pb.LaptopService_UploadImageServer) error {\n\treq, err := stream.Recv()\n\tif err != nil {\n\t\tlog.Print(\"cannot recieve image info: \", err)\n\t\treturn status.Error(codes.Unknown, \"cannot recieve image info\")\n\t}\n\n\tlaptopID := req.GetInfo().GetLaptopId()\n\timageType := req.GetInfo().GetImageType()\n\n\tlog.Printf(\"recieved a upload image request with laptop ID %v and image type %v\", laptopID, imageType)\n\n\tlaptop, found := server.LaptopStore.Find(laptopID)\n\tif !found {\n\t\treturn status.Error(codes.Internal, \"cannot find laptop\")\n\t}\n\tif laptop == nil {\n\t\treturn status.Errorf(codes.InvalidArgument, \"laptop %v doesn't exist\", laptopID)\n\t}\n\n\timageData := bytes.Buffer{}\n\timageSize := 0\n\n\tfor {\n\t\t// Check error\n\t\tif err := contextError(stream.Context()); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Print(\"waiting to recieve more data\")\n\n\t\treq, err := stream.Recv()\n\t\tif err == io.EOF {\n\t\t\tlog.Print(\"no more data\")\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn status.Errorf(codes.Unknown, \"cannot recieve chunk: %v\", laptopID)\n\t\t}\n\n\t\tchunk := req.GetChunk()\n\t\tsize := len(chunk)\n\n\t\t// time.Sleep(time.Second)\n\n\t\timageSize += size\n\n\t\tif imageSize > maxImageSize {\n\t\t\treturn status.Error(codes.InvalidArgument, \"image size too big: maximum 1mb\")\n\t\t}\n\n\t\t_, err = imageData.Write(chunk)\n\t\tif err != nil {\n\t\t\treturn status.Errorf(codes.Internal, \"cannot write chunk to data: %v\", err)\n\t\t}\n\t}\n\n\timageID, err := server.ImageStore.Save(laptopID, imageType, imageData)\n\tif err != nil {\n\t\treturn status.Errorf(codes.Internal, \"cannot save image to the store: %v\", err)\n\t}\n\n\tres := &pb.UploadImageResponse{\n\t\tId: imageID,\n\t\tSize: strconv.Itoa(imageSize),\n\t}\n\n\terr = stream.SendAndClose(res)\n\tif err != nil {\n\t\treturn status.Errorf(codes.Internal, \"unable to send response: %v\", err)\n\t}\n\n\tlog.Printf(\"image successfully saved with ID: %v and Size: %v\", imageID, imageSize)\n\treturn nil\n}", "func (ac *AmiCopyImpl) Copy(ui *packer.Ui) (err error) {\n\tif err = ac.input.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tif ac.output, err = ac.EC2.CopyImage(ac.input); err != nil {\n\t\treturn err\n\t}\n\n\tif err = ac.Tag(); err != nil {\n\t\treturn err\n\t}\n\n\tif ac.EnsureAvailable {\n\t\t(*ui).Say(\"Going to wait for image to be in available state\")\n\t\tfor i := 1; i <= 30; i++ {\n\t\t\timage, err := LocateSingleAMI(*ac.output.ImageId, ac.EC2)\n\t\t\tif err != nil && image == nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif *image.State == ec2.ImageStateAvailable {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t(*ui).Say(fmt.Sprintf(\"Waiting one minute (%d/30) for AMI to become available, current state: %s for image %s on account %s\", i, *image.State, *image.ImageId, ac.targetAccountID))\n\t\t\ttime.Sleep(time.Duration(1) * time.Minute)\n\t\t}\n\t\treturn fmt.Errorf(\"Timed out waiting for image %s to copy to account %s\", *ac.output.ImageId, ac.targetAccountID)\n\t}\n\n\treturn nil\n}", "func SaveURL(ctx context.Context, db *DB, url string) (context.Context, string, error) {\n\t//create the short url\n\turlShort := GenURLStringRndm(URLShortLength)\n\n\t//save\n\tstmt := fmt.Sprintf(\"INSERT INTO %s(id,url_short,url) VALUES (UUID_TO_BIN(UUID()),?,?)\", dbTableURLShort)\n\tctx, result, err := db.Exec(ctx, stmt, urlShort, url)\n\tif err != nil {\n\t\treturn ctx, urlShort, errors.Wrap(err, \"insert url short\")\n\t}\n\tcount, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn ctx, urlShort, errors.Wrap(err, \"insert url short rows affected\")\n\t}\n\tif count != 1 {\n\t\treturn ctx, urlShort, fmt.Errorf(\"unable to insert url short: %s\", url)\n\t}\n\treturn ctx, urlShort, nil\n}", "func (s *UsersService) StorageImageUser(image_url string) (string, error) {\n\tif image_url == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\turl := os.Getenv(\"APP_URL_JUSTICIA\")\n\tdirectory := \"/imagenes/usuariosRegistrados/\"\n\n\tvalue := strings.TrimPrefix(image_url, \"public\")\n\timageName := strings.TrimPrefix(value, directory)\n\trouteFile := url + directory + imageName + \".jpg\"\n\n\timageDownloaded, err := files.DownloadFileOnline(routeFile, imageName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Minio archivos\n\tminioClient, err := minio.New(os.Getenv(\"MINIO_ENDPOINT\"), os.Getenv(\"MINIO_ACCESS_KEY_ID\"), os.Getenv(\"MINIO_SECRET_ACCESS_KEY\"), true)\n\tif err != nil {\n\t\tlog.Fatalf(\"El minioClient ha arrojado un error: %v\", err)\n\t}\n\n\t/*\n\t\tCarpeta de almacenamiento en Minio\n\t\tEl nombre de la carpeta no debe tener caracteres especiales\n\t*/\n\tbucketName := \"sasusersprofile\"\n\t_, err = files.CheckBucket(*minioClient, bucketName)\n\tif err != nil {\n\t\tlog.Fatalf(\"Bucket invalido - error: %s\", err)\n\t}\n\n\t// Data archivo a almacenar\n\tcontentType := \"image/jpeg\"\n\tlog.Println(\"**********************************************************\")\n\tfilePath := imageDownloaded // path image\n\tif _, err := os.Stat(filePath); errors.Is(err, os.ErrNotExist) {\n\t\tlog.Fatal(\"la imagen guardada no existe en la api go.\")\n\t}\n\n\tobjectName := imageDownloaded // Nombre del archivo\n\t_, err = minioClient.FPutObject(bucketName, objectName, filePath, minio.PutObjectOptions{ContentType: contentType})\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\treturn imageDownloaded, nil\n}", "func UploadPictureToOSS(file multipart.File, _ *multipart.FileHeader) (string, error) {\n\tclient, err := oss.New(conf.Upload.AliyunEndpoint, conf.Upload.AliyunAccessID, conf.Upload.AliyunAccessSecret)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"new oss client\")\n\t}\n\n\tbucket, err := client.Bucket(conf.Upload.AliyunBucket)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"bucket\")\n\t}\n\n\tnow := time.Now()\n\tyear := now.Year()\n\tmonth := int(now.Month())\n\tday := now.Day()\n\n\tkey := fmt.Sprintf(\"%s%d/%02d/%02d/%s\", OSSPictureKeyPrefix, year, month, day, randstr.Hex(15))\n\n\tif err := gadget.Retry(5, func() error {\n\t\tif err := bucket.PutObject(key, file); err != nil {\n\t\t\treturn errors.Wrap(err, \"put object\")\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"retry 5 times\")\n\t}\n\n\tif conf.Upload.AliyunBucketCDNHost != \"\" {\n\t\treturn fmt.Sprintf(\"https://%s/%s\", conf.Upload.AliyunBucketCDNHost, key), nil\n\t}\n\treturn fmt.Sprintf(\"https://%s.%s/%s\", conf.Upload.AliyunBucket, conf.Upload.AliyunEndpoint, key), nil\n}", "func getRemoteImage(url string) ([]byte, error) {\n\tvar image []byte\n\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn image, err\n\t}\n\tdefer resp.Body.Close()\n\n\timage, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn image, err\n\t}\n\n\treturn image, nil\n}", "func coverURL(uri string) (cover string) {\n\tif uri == \"\" {\n\t\tcover = \"http://static.hdslb.com/images/transparent.gif\"\n\t\treturn\n\t}\n\tcover = uri\n\tif strings.Index(uri, \"http://\") == 0 {\n\t\treturn\n\t}\n\tif len(uri) >= 10 && uri[:10] == \"/templets/\" {\n\t\treturn\n\t}\n\tif strings.HasPrefix(uri, \"group1\") {\n\t\tcover = \"http://i0.hdslb.com/\" + uri\n\t\treturn\n\t}\n\tif pos := strings.Index(uri, \"/uploads/\"); pos != -1 && (pos == 0 || pos == 3) {\n\t\tcover = uri[pos+8:]\n\t}\n\tcover = strings.Replace(cover, \"{IMG}\", \"\", -1)\n\tcover = \"http://i\" + strconv.FormatInt(int64(crc32.ChecksumIEEE([]byte(cover)))%3, 10) + \".hdslb.com\" + cover\n\treturn\n}", "func (i *Image) ImageURL(width, height int, category string) string {\n\tprotocol := \"http://\"\n\tw := strconv.Itoa(width)\n\th := strconv.Itoa(height)\n\n\turl := protocol + \"lorempixel.com/\" + w + \"/\" + h + \"/\" + category\n\n\turl = url + \"?\" + strconv.Itoa(random(999))\n\n\treturn url\n}", "func GetAndStoreImages(sites map[string][]string, c *cli.Context) {\n\timages := []Image{}\n\n\tlist, ok := sites[\"unsplash\"]\n\tif ok {\n\t\tfor _, site := range list {\n\t\t\timages = append(images, GetUnsplashImages(site)...)\n\t\t}\n\t}\n\n\tvar wg sync.WaitGroup\n\tfor _, image := range images {\n\t\twg.Add(1)\n\t\tgo DownloadFile(c.String(\"directory\"), image.Name(), image.URL(), &wg)\n\t}\n\twg.Wait()\n\n\treturn\n}", "func (m *ModuleManager) GetCopyDestination(item modules.DataInfo, destinationInterface *app.InterfaceDetails, geo string) (*app.DataStore, error) {\n\t// provisioned storage for COPY\n\toriginalAssetName := item.DataDetails.Name\n\tbucket := FindAvailableBucket(m.Client, m.Log, m.Owner, item.Context.DataSetID, originalAssetName, false, geo)\n\tif bucket == nil {\n\t\treturn nil, errors.New(app.InsufficientStorage)\n\t}\n\tconnection, err := serde.ToRawExtension(&pb.DataStore{\n\t\tType: pb.DataStore_S3,\n\t\tName: \"S3\",\n\t\tS3: &pb.S3DataStore{\n\t\t\tBucket: bucket.Spec.Name,\n\t\t\tEndpoint: bucket.Spec.Endpoint,\n\t\t\tObjectKey: bucket.Status.AssetPrefixPerDataset[item.Context.DataSetID],\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &app.DataStore{\n\t\tCredentialLocation: utils.GetFullCredentialsPath(bucket.Spec.VaultPath),\n\t\tConnection: *connection,\n\t\tFormat: string(destinationInterface.DataFormat),\n\t}, nil\n}", "func (w *Worker) getImage(u string) ([]byte, error) {\n\t// Image in data url\n\tif strings.HasPrefix(u, \"data:\") {\n\t\tdataURL, err := dataurl.DecodeString(u)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn dataURL.Data, nil\n\t}\n\n\t// Download image using url provided\n\tresp, err := w.hg.Get(u)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode == http.StatusOK {\n\t\treturn ioutil.ReadAll(resp.Body)\n\t}\n\treturn nil, fmt.Errorf(\"unexpected status code received: %d\", resp.StatusCode)\n}", "func UploadPicture(w http.ResponseWriter, r *http.Request) *appError {\n session, err := store.Get(r, \"session-name\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n s3 := S3{\n EndPointString: session.Values[\"Endpoint\"].(string),\n AccessKey: session.Values[\"AccessKey\"].(string),\n SecretKey: session.Values[\"SecretKey\"].(string),\n Namespace: session.Values[\"Namespace\"].(string),\n }\n\n decoder := json.NewDecoder(r.Body)\n var s map[string]string\n err = decoder.Decode(&s)\n if err != nil {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Can't decode JSON data\"}\n }\n bucketName := s[\"bucket\"]\n retention := s[\"retention\"]\n fileName := s[\"file_name\"]\n imageWidth := s[\"image_width\"]\n imageHeight := s[\"image_height\"]\n gpsLatitude := s[\"gps_latitude\"]\n gpsLongitude := s[\"gps_longitude\"]\n datetime := s[\"datetime\"]\n\n contentType := \"binary/octet-stream\"\n pictureHeaders := make(map[string][]string)\n thumbnailHeaders := make(map[string][]string)\n pictureHeaders[\"Content-Type\"] = []string{contentType}\n thumbnailHeaders[\"Content-Type\"] = []string{contentType}\n if retention != \"\" {\n i, err := strconv.Atoi(retention)\n if err != nil {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Can't use this retention value\"}\n }\n pictureHeaders[\"x-emc-retention-period\"] = []string{strconv.Itoa(i * 24 * 3600)}\n thumbnailHeaders[\"x-emc-retention-period\"] = []string{strconv.Itoa(i * 24 * 3600)}\n }\n pictureHeaders[\"x-amz-meta-image-width\"] = []string{imageWidth}\n pictureHeaders[\"x-amz-meta-image-height\"] = []string{imageHeight}\n if gpsLatitude != \"\" {\n pictureHeaders[\"x-amz-meta-gps-latitude\"] = []string{gpsLatitude}\n }\n if gpsLongitude != \"\" {\n pictureHeaders[\"x-amz-meta-gps-longitude\"] = []string{gpsLongitude}\n }\n if datetime != \"\" {\n pictureHeaders[\"x-amz-meta-datetime\"] = []string{datetime}\n }\n preparedPictureS3Request, _ := prepareS3Request(s3, bucketName, \"PUT\", \"/pictures/\" + fileName, pictureHeaders, true)\n preparedThumbnailS3Request, _ := prepareS3Request(s3, bucketName, \"PUT\", \"/thumbnails/\" + fileName, thumbnailHeaders, true)\n delete(pictureHeaders, \"host\")\n delete(thumbnailHeaders, \"host\")\n\n rendering.JSON(w, http.StatusOK, struct {\n PictureHeaders map[string][]string `json:\"picture_headers\"`\n PictureUrl string `json:\"picture_url\"`\n ThumbnailHeaders map[string][]string `json:\"thumbnail_headers\"`\n ThumbnailUrl string `json:\"thumbnail_url\"`\n } {\n PictureHeaders: pictureHeaders,\n PictureUrl: preparedPictureS3Request.Url,\n ThumbnailHeaders: thumbnailHeaders,\n ThumbnailUrl: preparedThumbnailS3Request.Url,\n })\n return nil\n}", "func (s *Server) getIMGURL(url string) string {\n\tif url == \"\" {\n\t\treturn \"\"\n\t}\n\n\tend := strings.LastIndex(url, \"-\")\n\tif end == -1 {\n\t\treturn url + \"-t500x500.jpg\"\n\t}\n\treturn string([]rune(url)[0:strings.LastIndex(url, \"-\")]) + \"-t500x500.jpg\"\n}", "func IMAGE_API_PlaceImageIntoCS(res http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\tif validPerm, _ := HasPermission(res, req, image_Make_Permission); !validPerm {\n\t\t// User Must be at least Writer.\n\t\thttp.Redirect(res, req, \"/image/uploader?status=failure&message=invalid_login\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\tmultipartFile, multipartHeader, fileError := req.FormFile(\"upload\") // pull uploaded image.\n\tif fileError != nil { // handle error in a stable way, this will be a part of another page.\n\t\thttp.Redirect(res, req, \"/image/uploader?status=failure\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tdefer multipartFile.Close()\n\n\tprefix := req.FormValue(\"oid\")\n\tif prefix == \"\" {\n\t\tprefix = \"global\"\n\t}\n\n\t_, prepareError := IMAGE_API_SendToCloudStorage(req, multipartFile, multipartHeader, prefix)\n\tif prepareError != nil { // send to CS and same as above.\n\t\thttp.Redirect(res, req, \"/image/uploader?status=failure\", http.StatusSeeOther)\n\t\treturn\n\t}\n\t// success, let user know that their image is waiting.\n\thttp.Redirect(res, req, \"/image/uploader?status=success\", http.StatusSeeOther)\n}", "func (o GetRegistryImageResultOutput) ImageUrl() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetRegistryImageResult) string { return v.ImageUrl }).(pulumi.StringOutput)\n}", "func getLaboStorePageImages(s *goquery.Selection, l *Labo) {\n\tconst (\n\t\tCSS string = \"#main-content #product-thumbs img\"\n\t)\n\tvar (\n\t\tok bool\n\t)\n\ts = s.Find(CSS)\n\tok = (s.Length() > 0)\n\tif !ok {\n\t\treturn\n\t}\n\tl.StoreImages = newImages(s)\n}", "func copyDiskImage(dst, src string) (err error) {\n\t// Open source disk image\n\tsrcImg, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif ee := srcImg.Close(); ee != nil {\n\t\t\terr = ee\n\t\t}\n\t}()\n\tdstImg, err := os.Create(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif ee := dstImg.Close(); ee != nil {\n\t\t\terr = ee\n\t\t}\n\t}()\n\t_, err = io.Copy(dstImg, srcImg)\n\treturn err\n}", "func ExampleFileURL_StartCopy() {\n\t// From the Azure portal, get your Storage account file service URL endpoint.\n\taccountName, accountKey := accountInfo()\n\tcredential, err := azfile.NewSharedKeyCredential(accountName, accountKey)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Create a ShareURL object to a share where we'll create a file and its snapshot.\n\t// Create a BlockFileURL object to a file in the share.\n\tu, _ := url.Parse(fmt.Sprintf(\"https://%s.file.core.windows.net/myshare/CopiedFile.bin\", accountName))\n\tfileURL := azfile.NewFileURL(*u, azfile.NewPipeline(credential, azfile.PipelineOptions{}))\n\n\tctx := context.Background() // This example uses a never-expiring context\n\n\tsrc, _ := url.Parse(\"https://cdn2.auth0.com/docs/media/addons/azure_file.svg\") // Suppose this is an accessible source resource\n\tstartCopy, err := fileURL.StartCopy(ctx, *src, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tcopyID := startCopy.CopyID()\n\tcopyStatus := startCopy.CopyStatus()\n\tfor copyStatus == azfile.CopyStatusPending {\n\t\ttime.Sleep(time.Second * 2)\n\t\tproperties, err := fileURL.GetProperties(ctx)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tcopyStatus = properties.CopyStatus()\n\t}\n\tfmt.Printf(\"StartCopy from %s to %s: ID=%s, Status=%s\\n\", src.String(), fileURL, copyID, copyStatus)\n}", "func (c *CloudStorage) Stage(ctx context.Context, url string) (*url.URL, error) {\n\tc.once.Do(func() {\n\t\tc.cl, c.initErr = c.newClient(ctx)\n\t})\n\tif c.initErr != nil {\n\t\treturn nil, c.initErr\n\t}\n\tbuildArtifactPrefix := \"build-artifact:///\"\n\tif strings.HasPrefix(url, buildArtifactPrefix) {\n\t\turl = c.buildArtifactsURL + strings.TrimPrefix(url, buildArtifactPrefix)\n\t}\n\treturn c.cl.Stage(ctx, url)\n}", "func CopyImage(srcDir string, dstDir string, copyPath string) error {\n\tif _, err := os.Stat(copyPath); os.IsNotExist(err) {\n\t\tos.MkdirAll(copyPath, 0755)\n\t}\n\n\tsrc, err := DecodeImage(srcDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = EncodeImage(dstDir, src)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func getImage(imageId string) string {\n\turl := WorkerInfo.Api + \"/images/\" + imageId\n\t//fmt.Println(url)\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Add(\"Authorization\", \"Bearer \"+WorkerInfo.Token)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn \"\"\n\t}\n\tif resp.StatusCode != 200 {\n\t\tfmt.Println(\"bad status: %s\", resp.Status)\n\t\treturn \"\"\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn \"\"\n\t}\n\n\t// download image\n\tpermissions := 0775\n\tname := \"tmp_image\" + imageId\n\terr = ioutil.WriteFile(name, body, os.FileMode(permissions))\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn \"\"\n\t}\n\treturn name\n}", "func (p *OnPrem) SyncImage(config *Config, target Provider, image string) error {\n\timagePath := path.Join(localImageDir, image+\".img\")\n\t_, err := os.Stat(imagePath)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tconfig.RunConfig.Imagename = imagePath\n\tconfig.CloudConfig.ImageName = image\n\n\t// customizes image for target\n\tctx := NewContext(config, &target)\n\tarchive, err := target.customizeImage(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = target.GetStorage().CopyToBucket(config, archive)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn target.CreateImage(ctx)\n}", "func SavePhoto(name string, username string, path string, date string) *Photo {\n\tdir := packageTools.GetWD()\n\thash := packageTools.HashSHAFile(dir + \"/static\" + path)\n\n\tfmt.Println(\"Hashing \" + name + \" Path: \" + path + \" Hash: \" + hash)\n\n\tcurrentPhotos := *GetAllPhotosByUser(username)\n\n\tif GetPhotoByUserAndHash(&currentPhotos, hash) != nil {\n\t\treturn nil\n\t}\n\n\tphoto := Photo{\n\t\tName: name,\n\t\tPath: path,\n\t\tHash: hash,\n\t\tDate: date,\n\t}\n\n\tcurrentPhotos = append(currentPhotos, photo)\n\n\tsavePhotos(username, &currentPhotos)\n\n\treturn &photo\n}", "func (d *dockerImageDestination) putOneSignature(url *url.URL, signature []byte) error {\n\tswitch url.Scheme {\n\tcase \"file\":\n\t\tlogrus.Debugf(\"Writing to %s\", url.Path)\n\t\terr := os.MkdirAll(filepath.Dir(url.Path), 0755)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = ioutil.WriteFile(url.Path, signature, 0644)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\n\tcase \"http\", \"https\":\n\t\treturn errors.Errorf(\"Writing directly to a %s sigstore %s is not supported. Configure a sigstore-staging: location\", url.Scheme, url.String())\n\tdefault:\n\t\treturn errors.Errorf(\"Unsupported scheme when writing signature to %s\", url.String())\n\t}\n}", "func (client ListManagementImageClient) AddImageURLInput(ctx context.Context, listID string, contentType string, imageURL BodyModel, tag *int32, label string) (result Image, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ListManagementImageClient.AddImageURLInput\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.AddImageURLInputPreparer(ctx, listID, contentType, imageURL, tag, label)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementImageClient\", \"AddImageURLInput\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.AddImageURLInputSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementImageClient\", \"AddImageURLInput\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.AddImageURLInputResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementImageClient\", \"AddImageURLInput\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (s3s *S3Store) Store(a *artifact.Artifact) error {\n\tdestination := a.FullDestination()\n\tctype := a.ContentType\n\tsize := a.Size\n\n\ts3s.log.WithFields(logrus.Fields{\n\t\t\"source\": a.Source,\n\t\t\"dest\": destination,\n\t\t\"bucket\": s3s.b.Name,\n\t\t\"content_type\": ctype,\n\t}).Debug(\"more artifact details\")\n\n\terr := s3s.b.PutReaderHeader(destination, a.Instream, int64(size),\n\t\tmap[string][]string{\n\t\t\t\"Content-Type\": []string{ctype},\n\t\t}, s3.Private)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmd := artifactToMetadata(a)\n\terr = s3s.md.Save(md)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func DownloadImage(url string, imgName string) {\n\tresp, err := http.Get(url)\n\tcheckError(err)\n\tdefer resp.Body.Close()\n\tfile, _ := os.Create(imgName + \".jpg\")\n\tdefer file.Close()\n\t_, err = io.Copy(file, resp.Body)\n\tcheckError(err)\n}", "func downloadImage(url string, imageChan chan ImageResultDownload) {\n\n\t// GET FILE NAME\n\tfilename := filepath.Base(url)\n\n\t// \tDOWNLOAD IMAGE\n\tres, err := http.Get(url)\n\tif err != nil {\n\t\tfmt.Printf(\"%s\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, err := os.Create(IMAGE_OUTPUT_DIR + filename)\n\tif err != nil {\n\t\tfmt.Printf(\"%s\", err)\n\t}\n\tdefer out.Close()\n\t_, err = io.Copy(out, res.Body)\n\n\t//\tPUSH ImageResultDownload TO CHANNELS\n\tif err != nil{\n\t\tfmt.Printf(\"%s\", err)\n\t\timageChan <- ImageResultDownload{url, filename, nil , \"Failed\" }\n\t} else{\n\t\timageChan <- ImageResultDownload{url, filename, err, \"Successul\"}\n\t}\n}", "func AddImage(name string, IsUser int, ID int, r *http.Request) error {\n\tfile, fileheader, err := r.FormFile(\"FileImage\")\n\tif fileheader == nil || file == nil {\n\t\treturn errors.New(\"No image\")\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\tif err := AllowedImages(file, fileheader); err != nil {\n\t\treturn err\n\t}\n\n\tcurImage := Image{path: name, IsUser: IsUser, ID: ID}\n\tDb.Exec(\"delete from Images where Path = $1\", curImage.path)\n\t_, err = Db.Exec(\"insert into Images(Path, IsUser, ID) values ($1, $2, $3)\", curImage.path, curImage.IsUser, curImage.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.OpenFile(\"./public/images/\"+name, os.O_WRONLY|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tio.Copy(f, file)\n\treturn nil\n}", "func (rc *RegClient) BlobCopy(ctx context.Context, refSrc ref.Ref, refTgt ref.Ref, d types.Descriptor) error {\n\ttDesc := d\n\ttDesc.URLs = []string{} // ignore URLs when pushing to target\n\t// for the same repository, there's nothing to copy\n\tif ref.EqualRepository(refSrc, refTgt) {\n\t\trc.log.WithFields(logrus.Fields{\n\t\t\t\"src\": refTgt.Reference,\n\t\t\t\"tgt\": refTgt.Reference,\n\t\t\t\"digest\": d.Digest,\n\t\t}).Debug(\"Blob copy skipped, same repo\")\n\t\treturn nil\n\t}\n\t// check if layer already exists\n\tif _, err := rc.BlobHead(ctx, refTgt, tDesc); err == nil {\n\t\trc.log.WithFields(logrus.Fields{\n\t\t\t\"tgt\": refTgt.Reference,\n\t\t\t\"digest\": d,\n\t\t}).Debug(\"Blob copy skipped, already exists\")\n\t\treturn nil\n\t}\n\t// try mounting blob from the source repo is the registry is the same\n\tif ref.EqualRegistry(refSrc, refTgt) {\n\t\terr := rc.BlobMount(ctx, refSrc, refTgt, d)\n\t\tif err == nil {\n\t\t\trc.log.WithFields(logrus.Fields{\n\t\t\t\t\"src\": refTgt.Reference,\n\t\t\t\t\"tgt\": refTgt.Reference,\n\t\t\t\t\"digest\": d,\n\t\t\t}).Debug(\"Blob copy performed server side with registry mount\")\n\t\t\treturn nil\n\t\t}\n\t\trc.log.WithFields(logrus.Fields{\n\t\t\t\"err\": err,\n\t\t\t\"src\": refSrc.Reference,\n\t\t\t\"tgt\": refTgt.Reference,\n\t\t}).Warn(\"Failed to mount blob\")\n\t}\n\t// fast options failed, download layer from source and push to target\n\tblobIO, err := rc.BlobGet(ctx, refSrc, d)\n\tif err != nil {\n\t\trc.log.WithFields(logrus.Fields{\n\t\t\t\"err\": err,\n\t\t\t\"src\": refSrc.Reference,\n\t\t\t\"digest\": d,\n\t\t}).Warn(\"Failed to retrieve blob\")\n\t\treturn err\n\t}\n\tdefer blobIO.Close()\n\tif _, err := rc.BlobPut(ctx, refTgt, blobIO.GetDescriptor(), blobIO); err != nil {\n\t\trc.log.WithFields(logrus.Fields{\n\t\t\t\"err\": err,\n\t\t\t\"src\": refSrc.Reference,\n\t\t\t\"tgt\": refTgt.Reference,\n\t\t}).Warn(\"Failed to push blob\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func (f *SourceFetcher) uniqueFetchSource(c chan FetchResult, url string, namespace string) {\n\t// download temp source\n\ttmpOriginalPath, downloaded, err := f.downloadTempSource(url)\n\tif err != nil {\n\t\tf.notifyDownloadSourceFailed(c, err)\n\t\treturn\n\t}\n\n\t// file hash the image url\n\tmd5, err := info.Info{Path: tmpOriginalPath}.FileHash()\n\tif err != nil {\n\t\tf.notifyDownloadSourceFailed(c, err)\n\t\treturn\n\t}\n\n\t// move file to destination\n\tdestination := f.Paths.LocalOriginalPath(namespace, md5)\n\terr = f.copyImageFromTmp(tmpOriginalPath, destination)\n\tif err != nil {\n\t\tf.notifyDownloadSourceFailed(c, err)\n\t\treturn\n\t}\n\n\t// generate image details\n\timageDetails, err := info.Info{Path: destination}.ImageDetails()\n\tif err != nil {\n\t\tf.notifyDownloadSourceFailed(c, err)\n\t\treturn\n\t}\n\n\tc <- FetchResult{nil, imageDetails, downloaded}\n\tclose(c)\n}", "func (d *Daemon) ImageDownload(op *operation, server string, certificate string, secret string, fp string, forContainer bool, directDownload bool) error {\n\tif _, _, err := dbImageGet(d.db, fp, false, false); err == nil {\n\t\tshared.Log.Debug(\"Image already exists in the db\", log.Ctx{\"image\": fp})\n\t\t// already have it\n\t\treturn nil\n\t}\n\n\tshared.Log.Info(\n\t\t\"Image not in the db, downloading it\",\n\t\tlog.Ctx{\"image\": fp, \"server\": server})\n\n\t// Now check if we already downloading the image\n\td.imagesDownloadingLock.RLock()\n\tif waitChannel, ok := d.imagesDownloading[fp]; ok {\n\t\t// We already download the image\n\t\td.imagesDownloadingLock.RUnlock()\n\n\t\tshared.Log.Info(\n\t\t\t\"Already downloading the image, waiting for it to succeed\",\n\t\t\tlog.Ctx{\"image\": fp})\n\n\t\t// Wait until the download finishes (channel closes)\n\t\tif _, ok := <-waitChannel; ok {\n\t\t\tshared.Log.Warn(\"Value transmitted over image lock semaphore?\")\n\t\t}\n\n\t\tif _, _, err := dbImageGet(d.db, fp, false, true); err != nil {\n\t\t\tshared.Log.Error(\n\t\t\t\t\"Previous download didn't succeed\",\n\t\t\t\tlog.Ctx{\"image\": fp})\n\n\t\t\treturn fmt.Errorf(\"Previous download didn't succeed\")\n\t\t}\n\n\t\tshared.Log.Info(\n\t\t\t\"Previous download succeeded\",\n\t\t\tlog.Ctx{\"image\": fp})\n\n\t\treturn nil\n\t}\n\n\td.imagesDownloadingLock.RUnlock()\n\n\tshared.Log.Info(\n\t\t\"Downloading the image\",\n\t\tlog.Ctx{\"image\": fp})\n\n\t// Add the download to the queue\n\td.imagesDownloadingLock.Lock()\n\td.imagesDownloading[fp] = make(chan bool)\n\td.imagesDownloadingLock.Unlock()\n\n\t// Unlock once this func ends.\n\tdefer func() {\n\t\td.imagesDownloadingLock.Lock()\n\t\tif waitChannel, ok := d.imagesDownloading[fp]; ok {\n\t\t\tclose(waitChannel)\n\t\t\tdelete(d.imagesDownloading, fp)\n\t\t}\n\t\td.imagesDownloadingLock.Unlock()\n\t}()\n\n\texporturl := server\n\n\tvar info shared.ImageInfo\n\tinfo.Fingerprint = fp\n\n\tif !directDownload {\n\t\t/* grab the metadata from /1.0/images/%s */\n\t\tvar url string\n\t\tif secret != \"\" {\n\t\t\turl = fmt.Sprintf(\n\t\t\t\t\"%s/%s/images/%s?secret=%s\",\n\t\t\t\tserver, shared.APIVersion, fp, secret)\n\t\t} else {\n\t\t\turl = fmt.Sprintf(\"%s/%s/images/%s\", server, shared.APIVersion, fp)\n\t\t}\n\n\t\tresp, err := d.httpGetSync(url, certificate)\n\t\tif err != nil {\n\t\t\tshared.Log.Error(\n\t\t\t\t\"Failed to download image metadata\",\n\t\t\t\tlog.Ctx{\"image\": fp, \"err\": err})\n\n\t\t\treturn err\n\t\t}\n\n\t\tif err := json.Unmarshal(resp.Metadata, &info); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t/* now grab the actual file from /1.0/images/%s/export */\n\t\tif secret != \"\" {\n\t\t\texporturl = fmt.Sprintf(\n\t\t\t\t\"%s/%s/images/%s/export?secret=%s\",\n\t\t\t\tserver, shared.APIVersion, fp, secret)\n\n\t\t} else {\n\t\t\texporturl = fmt.Sprintf(\n\t\t\t\t\"%s/%s/images/%s/export\",\n\t\t\t\tserver, shared.APIVersion, fp)\n\t\t}\n\t}\n\n\traw, err := d.httpGetFile(exporturl, certificate)\n\tif err != nil {\n\t\tshared.Log.Error(\n\t\t\t\"Failed to download image\",\n\t\t\tlog.Ctx{\"image\": fp, \"err\": err})\n\t\treturn err\n\t}\n\tinfo.Size = raw.ContentLength\n\n\tdestDir := shared.VarPath(\"images\")\n\tdestName := filepath.Join(destDir, fp)\n\tif shared.PathExists(destName) {\n\t\td.Storage.ImageDelete(fp)\n\t}\n\n\tctype, ctypeParams, err := mime.ParseMediaType(raw.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tctype = \"application/octet-stream\"\n\t}\n\n\tbody := &Progress{Reader: raw.Body, length: raw.ContentLength, op: op}\n\n\tif ctype == \"multipart/form-data\" {\n\t\t// Parse the POST data\n\t\tmr := multipart.NewReader(body, ctypeParams[\"boundary\"])\n\n\t\t// Get the metadata tarball\n\t\tpart, err := mr.NextPart()\n\t\tif err != nil {\n\t\t\tshared.Log.Error(\n\t\t\t\t\"Invalid multipart image\",\n\t\t\t\tlog.Ctx{\"image\": fp, \"err\": err})\n\n\t\t\treturn err\n\t\t}\n\n\t\tif part.FormName() != \"metadata\" {\n\t\t\tshared.Log.Error(\n\t\t\t\t\"Invalid multipart image\",\n\t\t\t\tlog.Ctx{\"image\": fp, \"err\": err})\n\n\t\t\treturn fmt.Errorf(\"Invalid multipart image\")\n\t\t}\n\n\t\tdestName = filepath.Join(destDir, info.Fingerprint)\n\t\tf, err := os.Create(destName)\n\t\tif err != nil {\n\t\t\tshared.Log.Error(\n\t\t\t\t\"Failed to save image\",\n\t\t\t\tlog.Ctx{\"image\": fp, \"err\": err})\n\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = io.Copy(f, part)\n\t\tf.Close()\n\n\t\tif err != nil {\n\t\t\tshared.Log.Error(\n\t\t\t\t\"Failed to save image\",\n\t\t\t\tlog.Ctx{\"image\": fp, \"err\": err})\n\n\t\t\treturn err\n\t\t}\n\n\t\t// Get the rootfs tarball\n\t\tpart, err = mr.NextPart()\n\t\tif err != nil {\n\t\t\tshared.Log.Error(\n\t\t\t\t\"Invalid multipart image\",\n\t\t\t\tlog.Ctx{\"image\": fp, \"err\": err})\n\n\t\t\treturn err\n\t\t}\n\n\t\tif part.FormName() != \"rootfs\" {\n\t\t\tshared.Log.Error(\n\t\t\t\t\"Invalid multipart image\",\n\t\t\t\tlog.Ctx{\"image\": fp})\n\t\t\treturn fmt.Errorf(\"Invalid multipart image\")\n\t\t}\n\n\t\tdestName = filepath.Join(destDir, info.Fingerprint+\".rootfs\")\n\t\tf, err = os.Create(destName)\n\t\tif err != nil {\n\t\t\tshared.Log.Error(\n\t\t\t\t\"Failed to save image\",\n\t\t\t\tlog.Ctx{\"image\": fp, \"err\": err})\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = io.Copy(f, part)\n\t\tf.Close()\n\n\t\tif err != nil {\n\t\t\tshared.Log.Error(\n\t\t\t\t\"Failed to save image\",\n\t\t\t\tlog.Ctx{\"image\": fp, \"err\": err})\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tdestName = filepath.Join(destDir, info.Fingerprint)\n\n\t\tf, err := os.Create(destName)\n\t\tif err != nil {\n\t\t\tshared.Log.Error(\n\t\t\t\t\"Failed to save image\",\n\t\t\t\tlog.Ctx{\"image\": fp, \"err\": err})\n\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = io.Copy(f, body)\n\t\tf.Close()\n\n\t\tif err != nil {\n\t\t\tshared.Log.Error(\n\t\t\t\t\"Failed to save image\",\n\t\t\t\tlog.Ctx{\"image\": fp, \"err\": err})\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif directDownload {\n\t\timageMeta, err := getImageMetadata(destName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tinfo.Architecture = imageMeta.Architecture\n\t\tinfo.CreationDate = time.Unix(imageMeta.CreationDate, 0)\n\t\tinfo.ExpiryDate = time.Unix(imageMeta.ExpiryDate, 0)\n\t\tinfo.Properties = imageMeta.Properties\n\t}\n\n\t// By default, make all downloaded images private\n\tinfo.Public = false\n\n\t_, err = imageBuildFromInfo(d, info)\n\tif err != nil {\n\t\tshared.Log.Error(\n\t\t\t\"Failed to create image\",\n\t\t\tlog.Ctx{\"image\": fp, \"err\": err})\n\n\t\treturn err\n\t}\n\n\tshared.Log.Info(\n\t\t\"Download succeeded\",\n\t\tlog.Ctx{\"image\": fp})\n\n\tif forContainer {\n\t\treturn dbImageLastAccessInit(d.db, fp)\n\t}\n\n\treturn nil\n}", "func (g GridfsStorage) StoreChildImage(\n\tdatabase,\n\timageFormat string,\n\treader io.Reader,\n\timageWidth,\n\timageHeight int,\n\toriginal Cacheable,\n\tentry *Entry,\n) (Cacheable, error) {\n\tcon := g.Connection.Copy()\n\tdefer con.Close()\n\tcon.EnsureSafe(&mgo.Safe{W: 1, J: true})\n\n\tgridfs := con.DB(database).GridFS(\"fs\")\n\ttargetfile, err := gridfs.Create(getRandomFilename(imageFormat))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer targetfile.Close()\n\n\t_, err = io.Copy(targetfile, reader)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error for filename %s with size %dx%d\\n\", original.Name(), entry.Width, entry.Height)\n\t\tlog.Printf(\"Could not write file completely, cleaning %s\\n\", targetfile.Name())\n\t\ttargetfile.Abort()\n\t\treturn nil, err\n\t}\n\n\tmetadata := bson.M{\n\t\t\"width\": imageWidth,\n\t\t\"height\": imageHeight,\n\t\t\"originalFilename\": original.Name(),\n\t\t\"resizeType\": entry.Type,\n\t\t\"size\": fmt.Sprintf(\"%dx%d\", entry.Width, entry.Height)}\n\n\tif identifier, ok := original.(Identity); ok {\n\t\tmetadata[\"original\"] = mgo.DBRef{Collection: \"fs.files\", Id: identifier.ID()}\n\t}\n\n\tif metaContainer, ok := original.(MetaContainer); ok {\n\t\tparentMeta := metaContainer.Meta()\n\t\tfor k, v := range parentMeta {\n\t\t\tif _, exists := metadata[k]; !exists {\n\t\t\t\tmetadata[k] = v\n\t\t\t}\n\t\t}\n\t}\n\n\ttargetfile.SetContentType(\"image/\" + imageFormat)\n\ttargetfile.SetMeta(metadata)\n\n\treturn &gridFileCacheable{mf: targetfile}, nil\n}", "func saveImage(file *multipart.FileHeader) (img *models.Picture, err error) {\n\tf, err := file.Open()\n\n\tdefer f.Close()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfileExt := filepath.Ext(file.Filename)\n\tfileName := hash(file.Filename) + fileExt\n\n\timgSrc, _, err := image.Decode(f)\n\tif err != nil {\n\t\treturn\n\t}\n\n\timgDst240 := imaging.Fit(imgSrc, 240, 180, imaging.Lanczos)\n\terr = imaging.Save(imgDst240, thumbnailsFolder+fileName)\n\tif err != nil {\n\t\treturn\n\t}\n\n\timgDst640 := imaging.Fit(imgSrc, 640, 480, imaging.Lanczos)\n\terr = imaging.Save(imgDst640, imagesFolder+fileName)\n\tif err != nil {\n\t\treturn\n\t}\n\n\timg = &models.Picture{\n\t\tThumbnailURL: thumbnailsPath + fileName,\n\t\tURL: imagesPath + fileName,\n\t}\n\treturn\n}", "func copySlug(containerID string, config cfg.Config, app cfg.AppConfig) string {\n\ttmpDir, err := ioutil.TempDir(\"\", \"\")\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error creating TempDir\")\n\t}\n\n\tsource := fmt.Sprintf(\"%s:/tmp/slug.tgz\", containerID)\n\toutput, err := exec.Command(\"docker\", \"cp\", source, tmpDir).CombinedOutput()\n\n\tif err != nil {\n\t\tlog.Fatalf(string(output))\n\t}\n\n\treturn path.Join(tmpDir, \"slug.tgz\")\n}", "func PixHost(f string) (fp *UploadedImageLink, err error) {\n\n\tfp = &UploadedImageLink{\n\t\tDirect: \"\",\n\t\tThumb: \"\",\n\t}\n\n\turlUpload := \"https://api.pixhost.to/images\"\n\tmethod := \"POST\"\n\n\tpayload := &bytes.Buffer{}\n\twriter := multipart.NewWriter(payload)\n\tfile, errFile1 := os.Open(f)\n\n\tif errFile1 != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": errFile1,\n\t\t\t\"handler\": \"Error coping file\",\n\t\t\t\"url\": \"https://api.pixhost.to/images\",\n\t\t}).Errorf(\"Uploader[PixHost] - Error coping file\")\n\t\treturn fp, err\n\t}\n\n\tdefer file.Close()\n\tpart1,\n\t\terrFile1 := writer.CreateFormFile(\"img\", filepath.Base(f))\n\t_, errFile1 = io.Copy(part1, file)\n\n\tif errFile1 != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": errFile1,\n\t\t\t\"handler\": \"Error creating form\",\n\t\t\t\"url\": \"https://api.pixhost.to/images\",\n\t\t}).Errorf(\"Uploader[PixHost] - Error creating form\")\n\t\treturn fp, err\n\t}\n\n\t_ = writer.WriteField(\"content_type\", \"1\")\n\terr = writer.Close()\n\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": err.Error(),\n\t\t\t\"handler\": \"Error closing file\",\n\t\t\t\"url\": \"https://api.pixhost.to/images\",\n\t\t}).Errorf(\"Uploader[PixHost] - Error closing file\")\n\t\treturn fp, err\n\t}\n\n\tvar client *http.Client\n\tif os.Getenv(\"proxy\") != \"\" {\n\t\tproxyURL, err := url.Parse(os.Getenv(\"proxy\"))\n\t\tif err != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"event\": \"FastPic Close File\",\n\t\t\t\t\"File\": f,\n\t\t\t\t\"err\": err,\n\t\t\t}).Error(\"Upload Image\")\n\t\t\treturn fp, err\n\t\t}\n\n\t\tclient = &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}}\n\t} else {\n\t\tclient = &http.Client{}\n\t}\n\n\treq, err := http.NewRequest(method, urlUpload, payload)\n\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": err.Error(),\n\t\t\t\"handler\": \"Error Request\",\n\t\t\t\"url\": \"https://api.pixhost.to/images\",\n\t\t}).Errorf(\"Uploader[PixHost] - Error Request\")\n\t\treturn fp, err\n\t}\n\n\treq.Header.Add(\"Accept\", \"application/json\")\n\n\treq.Header.Set(\"Content-Type\", writer.FormDataContentType())\n\tres, err := client.Do(req)\n\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": err.Error(),\n\t\t\t\"handler\": \"Error Make Request\",\n\t\t\t\"url\": \"https://api.pixhost.to/images\",\n\t\t}).Errorf(\"Uploader[PixHost] - Error Make Request\")\n\t\treturn fp, err\n\t}\n\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": err.Error(),\n\t\t\t\"handler\": \"Error Read Body\",\n\t\t\t\"url\": \"https://api.pixhost.to/images\",\n\t\t}).Errorf(\"Uploader[PixHost] - Error Read Body\")\n\t\treturn fp, err\n\t}\n\n\tlog.Debugln(\"ImageHostUploader[PixHost] - Upload Response\", string(body))\n\n\tif res.StatusCode != 200 {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"status code\": res.StatusCode,\n\t\t\t\"handler\": \"Response error\",\n\t\t\t\"url\": \"https://api.pixhost.to/images\",\n\t\t}).Errorf(\"Uploader[PixHost] - Upload\")\n\t\treturn fp, fmt.Errorf(\"ImageHostUploader[PixHost] - Error Response Code: %d for https://api.pixhost.to/images\", res.StatusCode)\n\t}\n\n\tvar image PixHostUpload\n\n\terr = json.Unmarshal(body, &image)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": err.Error(),\n\t\t\t\"handler\": \"Reading body to json\",\n\t\t\t\"url\": \"https://api.pixhost.to/images\",\n\t\t}).Errorf(\"Uploader[PixHost] - Reading json\")\n\t\treturn fp, err\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"Name\": image.Name,\n\t\t\"ShowURl\": image.ShowURL,\n\t\t\"Thumb\": image.ThURL,\n\t\t\"url\": \"https://api.pixhost.to/images\",\n\t}).Debugf(\"Uploader[PixHost] - Response json\")\n\n\t// Load SHOWURL's url to get direct image\n\t// AND\n\t// Extract direct link\n\n\tdoc, err := goquery.NewDocument(image.ShowURL)\n\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": err.Error(),\n\t\t\t\"handler\": \"Query\",\n\t\t\t\"url\": image.ShowURL,\n\t\t}).Errorf(\"Uploader[PimpAndHost] - Error reading homepage\")\n\t\treturn fp, err\n\t}\n\n\t// Get <img id=\"image\" data-zoom=\"out\" class=\"image-img\" src=\"https://img43.pixhost.to/images/286/222.jpg\" alt=\"222.jpg\"/>\n\tlink, found := doc.Find(\"#image\").Attr(\"src\")\n\n\tif !found {\n\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"handler\": \"Find Link\",\n\t\t\t\"url\": image.ShowURL,\n\t\t}).Errorf(\"Uploader[PimpAndHost] - Image's link not found\")\n\n\t\treturn fp, fmt.Errorf(\"Image's link not found\")\n\n\t}\n\n\tfp = &UploadedImageLink{\n\t\tDirect: link,\n\t\tThumb: image.ThURL,\n\t}\n\n\treturn fp, err\n}", "func (p *Page) Save() error {\n\terr := p.requestHTML()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = db.Update(func(tx *bolt.Tx) error {\n\t\terr := p.txDelete(tx)\n\t\tif err != nil && err != ErrPageNotFound {\n\t\t\treturn err\n\t\t}\n\t\treturn p.txPut(tx)\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tfor k, v := range p.Images {\n\t\tf, err := os.Open(path.Join(opts.RepoDir, p.ID, k))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// upload the high res image\n\t\tctx := context.Background()\n\t\tw := storageBucket.Object(v.ID).NewWriter(ctx)\n\t\tw.ACL = []storage.ACLRule{{Entity: storage.AllUsers, Role: storage.RoleReader}}\n\t\tw.ContentType = \"image/jpeg\"\n\t\tw.CacheControl = fmt.Sprintf(\"public, max-age=%d\", storageMaxAge)\n\n\t\tif _, err = io.Copy(w, f); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tf.Close()\n\t\tw.Close()\n\n\t\t// upload the preview image\n\t\tr := bufio.NewReader(&v.buffer)\n\t\tw = storageBucket.Object(\"preview_\" + v.ID).NewWriter(ctx)\n\t\tw.ACL = []storage.ACLRule{{Entity: storage.AllUsers, Role: storage.RoleReader}}\n\t\tw.ContentType = \"image/jpeg\"\n\t\tw.CacheControl = fmt.Sprintf(\"public, max-age=%d\", storageMaxAge)\n\t\tif _, err = io.Copy(w, r); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tw.Close()\n\t}\n\n\treturn nil\n}", "func (s *SharemeService) ThumbnailURL(c *gae.Context, key string) string {\n\treturn s.Stat(c, key).Thumbnail\n}", "func DownloadNaplesImage(ctx context.Context, resolver resolver.Interface, version string, destFileName string) error {\n\tlog.Info(\"DownloadNaplesImage request from \", ctxutils.GetPeerAddress(ctx))\n\tif version == \"\" {\n\t\tlog.Errorf(\"Version is needed to download a naples image from objstore\")\n\t\treturn fmt.Errorf(\"Version is needed to download a naples image from objstore\")\n\t}\n\n\tobjectStoreFileName := \"Naples/\" + version + \"_img/\" + naplesImageName\n\treturn downloadImage(ctx, resolver, objectStoreFileName, destFileName)\n}", "func catURL(sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error {\n\tvar reader io.ReadCloser\n\tsize := int64(-1)\n\tswitch sourceURL {\n\tcase \"-\":\n\t\treader = os.Stdin\n\tdefault:\n\t\tvar err *probe.Error\n\t\t// Try to stat the object, the purpose is to extract the\n\t\t// size of S3 object so we can check if the size of the\n\t\t// downloaded object is equal to the original one. FS files\n\t\t// are ignored since some of them have zero size though they\n\t\t// have contents like files under /proc.\n\t\tclient, content, err := url2Stat(sourceURL, false, false, encKeyDB)\n\t\tif err == nil && client.GetURL().Type == objectStorage {\n\t\t\tsize = content.Size\n\t\t}\n\t\tif reader, err = getSourceStreamFromURL(sourceURL, encKeyDB); err != nil {\n\t\t\treturn err.Trace(sourceURL)\n\t\t}\n\t\tdefer reader.Close()\n\t}\n\treturn catOut(reader, size).Trace(sourceURL)\n}", "func (i Image) ImageURL() string {\n\tregistry := i.ContainerRegistryURL\n\tif i.ContainerRepositoryPath != \"\" {\n\t\tregistry += \"/\" + i.ContainerRepositoryPath\n\t}\n\treturn fmt.Sprintf(\"%s/%s\", registry, i.Name)\n}", "func (c *ProfileController) uploadImage(ctx iris.Context, id string) (string, error) {\n\tfile, info, err := ctx.FormFile(\"image_profile\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer file.Close()\n\t// replacer.Replace digunakan untuk mereplace karakter uncommon di file name\n\tfilename := fmt.Sprintf(\"%s%s%s\", id, \"_\", replacer.Replace(info.Filename, \"_\"))\n\tout, err := os.OpenFile(\"./web/public/images/profile/\"+filename, os.O_WRONLY|os.O_CREATE, 0666)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer out.Close()\n\n\tio.Copy(out, file)\n\n\treturn filename, nil\n}", "func (h *S3Handler) uploadToS3(p *Project, wg *sync.WaitGroup) {\n\n\tdefer recovery()\n\t// get image content\n\tdefer wg.Done()\n\tvar arr []string\n\n\tfor _, url := range(p.Image) {\n\n\t\tbuffer:= img(url)\n\t\tif len(*buffer) > 0 {\n\t\t\t// upload to s3\n\n\t\t\ts := strings.Split(url, \"/\")\n\t\t\turl_key := s[len(s)-1]\n\n\t\t\tmyurl := fmt.Sprintf(\"https://%s.s3.ap-south-1.amazonaws.com/%s\", S3_BUCKET, url_key)\n\n\t\t\t_, err := s3.New(h.Session).PutObject(&s3.PutObjectInput{\n\n\t\t\t\tBucket: aws.String(S3_BUCKET),\n\t\t\t\tKey: aws.String(url_key),\n\t\t\t\tACL: aws.String(\"public-read\"),\n\t\t\t\tBody: bytes.NewReader(*buffer),\n\t\t\t\tContentLength: aws.Int64(int64(len(*buffer))),\n\t\t\t\tContentType: aws.String(http.DetectContentType(*buffer)),\n\t\t\t\tContentDisposition: aws.String(\"attachment\"),\n\t\t\t})\n\n\t\t\tif err != nil{\n\t\t\t\tpanic(\"********************************************************************************************************************************************\")\n\n\n\t\t\t}else {\n\t\t\t\tarr = append(arr, myurl)\n\t\t\t\t//fmt.Println(akki)\n\n\t\t\t}\n\t\t}\n\n\n\t}\n\n\t// update to mongodb\n\tobjID, _ := primitive.ObjectIDFromHex(p.ID)\n\n\tfilter := bson.M{\"_id\": bson.M{\"$eq\": objID}}\n\n\n\tupdate := bson.M{\n\t\t\"$set\": bson.M{\n\t\t\t\"new_image_urlss\": arr,\n\n\t\t},\n\t}\n\tupdateResult, _ := h.Collection.UpdateOne(context.TODO(), filter, update)\n\n\tfmt.Println(updateResult)\n\n\n}", "func (m *MemDiffStore) ImageHandler(urlPrefix string) (http.Handler, error) {\n\thandlerFunc := func(w http.ResponseWriter, r *http.Request) {\n\t\t// Go's image package has no color profile support and we convert to 8-bit NRGBA to diff,\n\t\t// but our source images may have embedded color profiles and be up to 16-bit. So we must\n\t\t// at least take care to serve the original .pngs unaltered.\n\t\t//\n\t\t// TODO(lovisolo): Diff in NRGBA64?\n\t\t// TODO(lovisolo): Make sure each pair of images is in the same color space before diffing?\n\t\t// (They probably are today but it'd be a good correctness check to make sure.)\n\n\t\tdotExt := \".\" + common.IMG_EXTENSION\n\t\turlPath := r.URL.Path\n\t\tsklog.Debugf(\"diffstore handling %s\", urlPath)\n\t\tidx := strings.Index(urlPath, \"/\")\n\t\tif idx == -1 {\n\t\t\tnoCacheNotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\tdir := urlPath[:idx]\n\n\t\t// Limit the requests to directories with the images and diff images.\n\t\tif dir != diffsWebPath && dir != imgWebPath {\n\t\t\tnoCacheNotFound(w, r)\n\t\t\treturn\n\t\t}\n\n\t\t// Get the file that was requested and verify that it's a valid PNG file.\n\t\tfile := urlPath[idx+1:]\n\t\tif (len(file) <= len(dotExt)) || (!strings.HasSuffix(file, dotExt)) {\n\t\t\tnoCacheNotFound(w, r)\n\t\t\treturn\n\t\t}\n\n\t\t// Trim the image extension to get the image ID.\n\t\timgID := urlPath[idx+1 : len(urlPath)-len(dotExt)]\n\t\timgDigest := types.Digest(imgID)\n\n\t\t// Cache images for 12 hours.\n\t\tw.Header().Set(\"Cache-Control\", \"public, max-age=43200\")\n\n\t\tif dir == imgWebPath {\n\t\t\t// Validate the requested image ID.\n\t\t\tif !validation.IsValidDigest(imgID) {\n\t\t\t\tnoCacheNotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Retrieve the image from the in-memory cache.\n\t\t\timgs, err := m.imgLoader.Get(r.Context(), types.DigestSlice{imgDigest})\n\t\t\tif err != nil {\n\t\t\t\tsklog.Errorf(\"Error retrieving digest: %s\", imgID)\n\t\t\t\tnoCacheNotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Write output image to the http.ResponseWriter. Content-Type is set automatically\n\t\t\t// based on the first 512 bytes of written data. See docs for ResponseWriter.Write()\n\t\t\t// for details.\n\t\t\tif _, err := w.Write(imgs[0]); err != nil {\n\t\t\t\tsklog.Errorf(\"Error writing image to http.ResponseWriter: %s\", err)\n\t\t\t\tnoCacheNotFound(w, r)\n\t\t\t}\n\t\t} else {\n\t\t\t// Validate the requested diff image ID.\n\t\t\tif !validation.IsValidDiffImgID(imgID) {\n\t\t\t\tnoCacheNotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Extract the left and right image digests.\n\t\t\tleftDigest, rightDigest := common.SplitDiffID(imgID)\n\n\t\t\t// Retrieve the images from the in-memory cache.\n\t\t\timgs, err := m.decodedImageCache.GetAll(r.Context(), []string{string(leftDigest), string(rightDigest)})\n\t\t\tif err != nil {\n\t\t\t\tsklog.Errorf(\"Error retrieving and decoding digests to compute diff: %s\", imgID)\n\t\t\t\tnoCacheNotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Compute the diff image.\n\t\t\tleftImg, rightImg := imgs[0].(*image.NRGBA), imgs[1].(*image.NRGBA)\n\t\t\t_, diffImg := diff.PixelDiff(leftImg, rightImg)\n\n\t\t\t// Write output image to the http.ResponseWriter. Content-Type is set automatically\n\t\t\t// based on the first 512 bytes of written data. See docs for ResponseWriter.Write()\n\t\t\t// for details.\n\t\t\t//\n\t\t\t// The encoding step below does not take color profiles into account. This is fine since\n\t\t\t// both the left and right images used to compute the diff are in the same color space,\n\t\t\t// and also because the resulting diff image is just a visual approximation of the\n\t\t\t// differences between the left and right images.\n\t\t\tif err := common.EncodeImg(w, diffImg); err != nil {\n\t\t\t\tsklog.Errorf(\"Error encoding diff image: %s\", err)\n\t\t\t\tnoCacheNotFound(w, r)\n\t\t\t}\n\t\t}\n\t}\n\n\tsklog.Infof(\"Created diffstore\")\n\n\t// The above function relies on the URL prefix being stripped.\n\treturn http.StripPrefix(urlPrefix, http.HandlerFunc(handlerFunc)), nil\n}", "func (bucket CryptoBucket) DoPutObjectWithURL(signedURL string, reader io.Reader, options []oss.Option) (*oss.Response, error) {\n\treturn nil, fmt.Errorf(\"CryptoBucket doesn't support DoPutObjectWithURL\")\n}", "func (c *Client) SaveImage(ctx context.Context, image, format string, writer io.WriteCloser) error {\n\t// Parse the image name and tag.\n\tnamed, err := reference.ParseNormalizedNamed(image)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing image name %q failed: %v\", image, err)\n\t}\n\t// Add the latest lag if they did not provide one.\n\tnamed = reference.TagNameOnly(named)\n\timage = named.String()\n\n\t// Create the worker opts.\n\topt, err := c.createWorkerOpt(false)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating worker opt failed: %v\", err)\n\t}\n\n\tif opt.ImageStore == nil {\n\t\treturn errors.New(\"image store is nil\")\n\t}\n\n\texportOpts := []archive.ExportOpt{\n\t\tarchive.WithImage(opt.ImageStore, image),\n\t}\n\n\tswitch format {\n\tcase \"docker\":\n\n\tcase \"oci\":\n\t\texportOpts = append(exportOpts, archive.WithSkipDockerManifest())\n\n\tdefault:\n\t\treturn fmt.Errorf(\"%q is not a valid format\", format)\n\t}\n\n\tif err := archive.Export(ctx, opt.ContentStore, writer, exportOpts...); err != nil {\n\t\treturn fmt.Errorf(\"exporting image %s failed: %v\", image, err)\n\t}\n\n\treturn writer.Close()\n}", "func (i Image) UploadImage(c echo.Context) error {\n\t// Get image\n\timage, err := c.FormFile(\"image\")\n\tif err != nil {\n\t\treturn c.JSON(http.StatusBadRequest, nil)\n\t}\n\n\t// source\n\tsrc, err := image.Open()\n\tif err != nil {\n\t\tc.Logger().Error(err)\n\t\treturn err\n\t}\n\tdefer src.Close()\n\n\t// create image on bdd\n\tdst, err := i.session.DB(\"test\").GridFS(\"fs\").Create(image.Filename)\n\tif err != nil {\n\t\tc.Logger().Error(err)\n\t\treturn err\n\t}\n\n\t// save content on bdd\n\tif _, err = io.Copy(dst, src); err != nil {\n\t\tc.Logger().Error(err)\n\t\treturn err\n\t}\n\n\t// get id image\n\tid := dst.Id()\n\n\tif err = dst.Close(); err != nil {\n\t\tc.Logger().Error(err)\n\t\treturn c.JSON(http.StatusExpectationFailed, id)\n\t}\n\n\t// return id\n\treturn c.JSON(http.StatusOK, id)\n}", "func PullImage(image, cacheDir string) (v1.Image, error) {\n var options []crane.Option\n\n // options = append(options, crane.Insecure)\n\n // Use current built OS and architecture\n options = append(options, crane.WithPlatform(&v1.Platform{\n OS: runtime.GOOS,\n Architecture: runtime.GOARCH,\n }))\n\n // Grab the remote manifest\n manifest, err := crane.Manifest(image, options...)\n if err != nil {\n return nil, fmt.Errorf(\"failed fetching manifest for %s: %v\", image, err)\n }\n\n if !gjson.Valid(string(manifest)) {\n return nil, fmt.Errorf(\"Cannot parse manifest: %s\", string(manifest))\n }\n\n value := gjson.Get(string(manifest), \"config.digest\").Value().(string)\n if value == \"\" {\n return nil, fmt.Errorf(\"Malformed manifest: %s\", string(manifest))\n }\n \n digest := strings.Split(value, \":\")[1]\n tarball := fmt.Sprintf(\"%s/%s.tar.gz\", cacheDir, digest)\n\n // Download the tarball of the image if not available in the cache\n if _, err := os.Stat(tarball); os.IsNotExist(err) {\n // Create the cacheDir if it does not already exist\n if cacheDir != \"\" {\n if _, err := os.Stat(cacheDir); os.IsNotExist(err) {\n os.MkdirAll(cacheDir, os.ModePerm)\n }\n }\n \n // Pull the image\n img, err := crane.Pull(image, options...)\n if err != nil {\n return nil, fmt.Errorf(\"Could not pull image: %s\", err)\n }\n \n f, err := os.Create(tarball)\n if err != nil {\n return nil, fmt.Errorf(\"Failed to open %s: %v\", tarball, err)\n }\n \n defer f.Close()\n \n err = crane.Save(img, image, tarball)\n if err != nil {\n return nil, fmt.Errorf(\"Could not save image: %s\", err)\n }\n }\n\n img, err := crane.Load(tarball)\n if err != nil {\n return nil, fmt.Errorf(\"Could not load image: %s\", err)\n }\n\n return img, nil\n}", "func (f *File) URL() (url string, err error) {\n\tif f.url != \"\" {\n\t\treturn f.url, nil\n\t}\n\turl, err = f.Store.URL(f.ID)\n\tif err != nil {\n\t\treturn url, err\n\t}\n\tf.SetURL(url)\n\treturn url, nil\n}", "func postImage(name string) {\n\turl := WorkerInfo.Api + \"/images\"\n\tclient := &http.Client{}\n\t//prepare the reader instances to encode\n\tvalues := map[string]io.Reader{\n\t\t\"data\": mustOpen(name), // lets assume its this file\n\t\t\"type\": strings.NewReader(\"filtered\"),\n\t}\n\terr := Upload(client, url, values)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\te := os.Remove(name)\n\tif e != nil {\n\t\tfmt.Println(\"[WARN] couldnt delete tmp file\")\n\t}\n}", "func (adp *s3Storage) URL(ctx context.Context, filename string) string {\n\treturn adp.dsn.URL(filename)\n}", "func (i *Image) URL() string {\n\treturn fmt.Sprintf(\"projects/%s/global/images/%s\", i.Project, i.Name)\n}", "func uploadImageToS3(p string) (string, string, error) {\n\tlog.Infof(\"handling %s\", p)\n\n\tfileName, _ := filepath.Rel(workingDir, p)\n\tbaseFolder := strings.Split(fileName, \"/\")[0]\n\text := strings.TrimPrefix(filepath.Ext(p), \".\")\n\n\tallowed := false\n\tfor _, e := range allowedExts {\n\t\tallowed = e == ext\n\t\tif allowed {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !allowed {\n\t\treturn \"\", \"\", fmt.Errorf(\"only file with extensions %v are uploaded\", allowedExts)\n\t}\n\n\tb, err := ioutil.ReadFile(p)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tif err = bucket.Put(fileName, b, filepath.Join(\"image\", ext), \"public-read-write\"); err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tlog.Infof(\"file %s uploaded to S3\", p)\n\tos.Remove(p)\n\treturn baseFolder, bucket.URL(fileName), nil\n}" ]
[ "0.5790747", "0.56708217", "0.5627612", "0.5470807", "0.54444057", "0.52890503", "0.52813643", "0.5211332", "0.51526403", "0.51466984", "0.5146554", "0.51073426", "0.50793624", "0.5038151", "0.5023785", "0.49964434", "0.49963558", "0.49876392", "0.49376187", "0.49367034", "0.4920963", "0.49069893", "0.48937786", "0.48879412", "0.4883869", "0.48791477", "0.48592964", "0.48585996", "0.48338217", "0.4829671", "0.4824773", "0.48047128", "0.47918314", "0.47499976", "0.47454998", "0.47307345", "0.47178036", "0.4707649", "0.4700432", "0.46935993", "0.4682827", "0.4679101", "0.46757492", "0.46699044", "0.4667599", "0.46569857", "0.46558768", "0.4645576", "0.46407127", "0.46393993", "0.46299663", "0.4625719", "0.4625396", "0.4618016", "0.46051815", "0.4597846", "0.45929334", "0.45927015", "0.4587066", "0.45870578", "0.4583319", "0.45820168", "0.457386", "0.4573472", "0.45724228", "0.45719835", "0.45643488", "0.45635992", "0.455227", "0.4548981", "0.4541804", "0.45382902", "0.45308936", "0.4529262", "0.4524029", "0.4517123", "0.4516878", "0.45161402", "0.45144042", "0.45104086", "0.45075023", "0.4505406", "0.45048898", "0.45009357", "0.44978333", "0.44890347", "0.44821522", "0.44766185", "0.44766167", "0.4473251", "0.44633603", "0.44626713", "0.44569385", "0.44560492", "0.44532573", "0.4448403", "0.4446764", "0.44425678", "0.44356447", "0.4430438" ]
0.7884488
0
Validate validates that the message is valid.
func (m *Message) Validate() bool { return len(m.Key) > 0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (msg *Message) Validate() error {\n\tswitch {\n\tcase msg == nil:\n\t\treturn ErrInvalidMessage\n\tcase msg.Token == \"\" && len(msg.RegistrationIDs) == 0:\n\t\treturn ErrInvalidToken\n\tcase len(msg.RegistrationIDs) > 1000:\n\t\treturn ErrToManyRegIDs\n\tcase msg.TimeToLive > 2419200:\n\t\treturn ErrInvalidTimeToLive\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (m *Message) validate() error {\n\tif m == nil {\n\t\treturn fmt.Errorf(\"the message must not be nil\")\n\t}\n\n\tif m.RegistrationIDs == nil {\n\t\treturn fmt.Errorf(\"the message's RegistrationIDs field must not be nil\")\n\t}\n\n\tif len(m.RegistrationIDs) == 0 {\n\t\treturn fmt.Errorf(\"the message must specify at least one registration ID\")\n\t}\n\n\tif len(m.RegistrationIDs) > maxRegistrationIDs {\n\t\treturn fmt.Errorf(\"the message may specify at most %d registration IDs\",\n\t\t\tmaxRegistrationIDs)\n\t}\n\n\tif m.TimeToLive < 0 || maxTimeToLive < m.TimeToLive {\n\t\treturn fmt.Errorf(\n\t\t\t\"the message's TimeToLive field must be an integer between 0 and %d (4 weeks)\",\n\t\t\tmaxTimeToLive,\n\t\t)\n\t}\n\n\tif m.Priority != \"\" && m.Priority != fcmPushPriorityHigh && m.Priority != fcmPushPriorityNormal {\n\t\treturn fmt.Errorf(\"priority must be %s or %s\", fcmPushPriorityHigh, fcmPushPriorityNormal)\n\t}\n\n\treturn nil\n}", "func (mt *Message) Validate() (err error) {\n\tif mt.GoogleUserID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"googleUserID\"))\n\t}\n\tif mt.Body == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"body\"))\n\t}\n\n\tif utf8.RuneCountInString(mt.Body) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.body`, mt.Body, utf8.RuneCountInString(mt.Body), 1, true))\n\t}\n\tif utf8.RuneCountInString(mt.Body) > 400 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.body`, mt.Body, utf8.RuneCountInString(mt.Body), 400, false))\n\t}\n\treturn\n}", "func validate(msg *ssmmds.Message) error {\n\tif msg == nil {\n\t\treturn errors.New(\"Message is nil\")\n\t}\n\tif empty(msg.Topic) {\n\t\treturn errors.New(\"Topic is missing\")\n\t}\n\tif empty(msg.Destination) {\n\t\treturn errors.New(\"Destination is missing\")\n\t}\n\tif empty(msg.MessageId) {\n\t\treturn errors.New(\"MessageId is missing\")\n\t}\n\tif empty(msg.CreatedDate) {\n\t\treturn errors.New(\"CreatedDate is missing\")\n\t}\n\treturn nil\n}", "func (pm PushMessage) Validate() error {\n\tif pm.Message.Data == \"\" {\n\t\treturn fmt.Errorf(\"push message has no data\")\n\t}\n\tif pm.Message.ID == \"\" {\n\t\treturn fmt.Errorf(\"push message has no ID\")\n\t}\n\tif pm.Subscription == \"\" {\n\t\treturn fmt.Errorf(\"push message has no subscription\")\n\t}\n\treturn nil\n}", "func (*GenericFramework) ValidateMessage(ctx *MessageContext) bool { return true }", "func validateMessage(data []byte) (message, error) {\n\tvar msg message\n\n\tif err := json.Unmarshal(data, &msg); err != nil {\n\t\treturn msg, errors.Wrap(err, \"Unmarshaling message\")\n\t}\n\n\tif msg.Handle == \"\" && msg.Text == \"\" {\n\t\treturn msg, errors.New(\"Message has no Handle or Text\")\n\t}\n\n\treturn msg, nil\n}", "func (m *Message) Validate() error {\n\tif m.Recipient == \"\" {\n\t\treturn ErrMissingRecipient\n\t}\n\tif m.MailServer == \"\" {\n\t\treturn ErrMissingMailServer\n\t}\n\treturn nil\n}", "func (m *CreateMessageMessage) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateContent(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateMediaType(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSeverity(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m Message) Validate() error {\n\tmDict := m.ToDict()\n\n\t// validate presence of required fields\n\tfor _, field := range RequiredFields {\n\t\tvalue, present := mDict[field]\n\t\tif !present || value == \"\" {\n\t\t\treturn fmt.Errorf(\"missing required field *%s*\", field)\n\t\t}\n\t}\n\n\t// validate format of From and To emails\n\temailFields := []string{\"from\", \"to\"}\n\tfor _, emailField := range emailFields {\n\t\tvalue := mDict[emailField]\n\t\tif !emailRegexp.MatchString(value) {\n\t\t\treturn fmt.Errorf(\"field %s has an invalid value %s\", emailField, value)\n\t\t}\n\t}\n\n\t// required fields are present and email fields are well formed.\n\treturn nil\n}", "func validateMessage(ch *persistence.Channel, msg *ChannelSyncMsg) error {\n\tv := ch.CurrentTX().Version\n\tmv := msg.CurrentTX.Version\n\n\tif msg.CurrentTX.ID != ch.ID() {\n\t\treturn errors.New(\"channel ID mismatch\")\n\t}\n\tif mv == v {\n\t\tif err := msg.CurrentTX.State.Equal(ch.CurrentTX().State); err != nil {\n\t\t\treturn errors.WithMessage(err, \"different states for same version\")\n\t\t}\n\t} else if mv > v {\n\t\t// Validate the received message first.\n\t\tif len(msg.CurrentTX.Sigs) != len(ch.Params().Parts) {\n\t\t\treturn errors.New(\"sigs length mismatch\")\n\t\t}\n\t\tfor i, sig := range msg.CurrentTX.Sigs {\n\t\t\tok, err := channel.Verify(ch.Params().Parts[i], msg.CurrentTX.State, sig)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.WithMessagef(err, \"validating sig %d\", i)\n\t\t\t}\n\t\t\tif !ok {\n\t\t\t\treturn errors.Errorf(\"invalid sig %d\", i)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (msg *Message) Validate() error {\n\tif msg == nil {\n\t\treturn ErrInvalidMessage\n\t}\n\n\tvar targets = 0\n\t// validate target: `topic` or `condition`, or `token`, or fcm options\n\tif msg.Topic != \"\" {\n\t\ttargets = targets + 1\n\t}\n\n\tif msg.Condition != \"\" {\n\t\ttargets = targets + 1\n\t}\n\n\topCnt := strings.Count(msg.Condition, \"&&\") + strings.Count(msg.Condition, \"||\")\n\tif opCnt > 2 {\n\t\treturn ErrInvalidTarget\n\t}\n\n\tif msg.Token != \"\" {\n\t\ttargets = targets + 1\n\t}\n\n\tif targets == 0 || targets > 1 {\n\t\treturn ErrInvalidTarget\n\t}\n\n\tif msg.Android != nil && msg.Android.TTL != \"\" {\n\t\tif _, err := time.ParseDuration(msg.Android.TTL); err != nil {\n\t\t\treturn ErrInvalidTimeToLive\n\t\t}\n\t}\n\n\tif msg.Apns != nil {\n\t\tb, err := json.Marshal(msg.Apns.Payload)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar payload ApnsPayload\n\t\terr = json.Unmarshal(b, &payload)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif msg.Apns.Headers != nil {\n\t\t\tif payload.Aps.ContentAvailable == int(ApnsContentAvailable) &&\n\t\t\t\tmsg.Apns.Headers.Priority == string(ApnsHighPriority) {\n\t\t\t\treturn ErrInvalidApnsPriority\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (payload *CreateMessagePayload) Validate() (err error) {\n\n\tif payload.Text == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"text\"))\n\t}\n\treturn\n}", "func (payload *createMessagePayload) Validate() (err error) {\n\tif payload.OfferID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"offer_id\"))\n\t}\n\tif payload.Text == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"text\"))\n\t}\n\treturn\n}", "func validateMessage(msg *protocol.SendInputMessage) bool {\n\n\tplayer := entityHolder.GetEntity(msg.PlayerId)\n\tif player == nil {\n\t\tlog.Printf(\"Trying to validate message from disconnected player: %v\", msg.PlayerId)\n\t\treturn false\n\t}\n\n\ttimeDiff := shared.MDuration{msg.GetRcvdTime().Sub(player.lastSeqTime)}\n\n\tif msg.Dt.Milliseconds() > timeDiff.Milliseconds()+shared.MAX_DT_DIFF_MILLIS {\n\t\tlog.Printf(\"Message from player %v with seq: %v rejected because delta %v ms is longer than diff between last msg rcv %v + max added %v.\",\n\t\t\tmsg.PlayerId, msg.Seq, msg.Dt.Milliseconds(), timeDiff.Milliseconds(), shared.MAX_DT_DIFF_MILLIS)\n\t\treturn false\n\t}\n\treturn true\n}", "func (m *Message) Validate() bool {\n\tm.Errors = make(map[string]interface{})\n\n\tre := regexp.MustCompile(\".+@.+\\\\..+\")\n\tmatched := re.Match([]byte(m.From))\n\n\tif matched == false {\n\t\tm.Errors[\"from\"] = \"Please enter a valid email address\"\n\t}\n\n\tif strings.TrimSpace(m.Body) == \"\" {\n\t\tm.Errors[\"body\"] = \"Please write a message\"\n\t}\n\n\treturn len(m.Errors) == 0\n}", "func (m *Message100Message) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateMessageArgs(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateRelatedProperties(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func ValidateMsg(pb proto.Message) error {\n\tif pb == nil {\n\t\treturn errors.New(\"message cannot be nil\")\n\t}\n\n\tswitch msg := pb.(type) {\n\tcase *bcproto.BlockRequest:\n\t\tif msg.Height < 0 {\n\t\t\treturn errors.New(\"negative Height\")\n\t\t}\n\tcase *bcproto.BlockResponse:\n\t\t_, err := types.BlockFromProto(msg.Block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase *bcproto.NoBlockResponse:\n\t\tif msg.Height < 0 {\n\t\t\treturn errors.New(\"negative Height\")\n\t\t}\n\tcase *bcproto.StatusResponse:\n\t\tif msg.Base < 0 {\n\t\t\treturn errors.New(\"negative Base\")\n\t\t}\n\t\tif msg.Height < 0 {\n\t\t\treturn errors.New(\"negative Height\")\n\t\t}\n\t\tif msg.Base > msg.Height {\n\t\t\treturn fmt.Errorf(\"base %v cannot be greater than height %v\", msg.Base, msg.Height)\n\t\t}\n\tcase *bcproto.StatusRequest:\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown message type %T\", msg)\n\t}\n\treturn nil\n}", "func (SelfValidator) Validate(\n\tctx context.Context,\n\tm ax.Message,\n) error {\n\n\t// check if message can perform self-validation\n\tif s, ok := m.(SelfValidatingMessage); ok {\n\t\treturn s.Validate()\n\t}\n\n\treturn nil\n}", "func (clientMessage *ClientMessage) Validate() error {\n\tif clientMessage.HeaderLength == 0 {\n\t\treturn errors.New(\"HeaderLength cannot be zero\")\n\t}\n\tif clientMessage.MessageType == \"\" {\n\t\treturn errors.New(\"MessageType is missing\")\n\t}\n\tif clientMessage.CreatedDate == 0 {\n\t\treturn errors.New(\"CreatedDate is missing\")\n\t}\n\tif clientMessage.PayloadLength != 0 {\n\t\thasher := sha256.New()\n\t\thasher.Write(clientMessage.Payload)\n\t\tif !bytes.Equal(hasher.Sum(nil), clientMessage.PayloadDigest) {\n\t\t\treturn errors.New(\"payload Hash is not valid\")\n\t\t}\n\t}\n\treturn nil\n}", "func (m *Message) Valid() bool {\n\tswitch m.Code {\n\tcase Run, Pause, Release, Checkpoint, Complete, Kill:\n\t\treturn true\n\tcase Sleep:\n\t\treturn m.Until != nil\n\tcase Error:\n\t\treturn m.Err != nil\n\tdefault:\n\t\treturn false\n\t}\n}", "func (em *EncryptedMessage) Validate() error {\n\tif em.SessionKey == nil || len(em.SessionKey) == 0 {\n\t\treturn errors.New(\"invalid session id in encrypted message\")\n\t}\n\tif em.IV == nil || len(em.IV) == 0 {\n\t\treturn errors.New(\"invalid iv in encrypted message\")\n\t}\n\tif em.CipherText == nil || len(em.CipherText)%aes.BlockSize != 0 {\n\t\treturn errors.New(\"invalid ciphertext in encrypted message\")\n\t}\n\treturn nil\n}", "func checkMessage(msg *Message) error {\n\tif msg == nil {\n\t\treturn errors.New(\"the message must not be nil\")\n\t} else if msg.RegistrationIDs == nil && msg.To == \"\" {\n\t\treturn errors.New(\"the message's RegistrationIDs field must not be nil\")\n\t} else if len(msg.RegistrationIDs) > 1000 {\n\t\treturn errors.New(\"the message may specify at most 1000 registration IDs\")\n\t} else if msg.TimeToLive < 0 || 2419200 < msg.TimeToLive {\n\t\treturn errors.New(\"the message's TimeToLive field must be an integer \" +\n\t\t\t\"between 0 and 2419200 (4 weeks)\")\n\t}\n\treturn nil\n}", "func (l *OnionMessage) Validate(id peer.ID) error {\n\tif l.IsLastHop() {\n\t\treturn l.validateLastHop()\n\t}\n\n\treturn l.validateIntermediateHop(id)\n}", "func (m *MessageF) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif val := m.GetField1(); val <= 0 || val > 1000 {\n\t\treturn MessageFValidationError{\n\t\t\tfield: \"Field1\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\tif val := m.GetField2(); val <= 0 || val > 1000 {\n\t\treturn MessageFValidationError{\n\t\t\tfield: \"Field2\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\tif val := m.GetField3(); val <= 0 || val > 1000 {\n\t\treturn MessageFValidationError{\n\t\t\tfield: \"Field3\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\tif val := m.GetField4(); val <= 0 || val > 1000 {\n\t\treturn MessageFValidationError{\n\t\t\tfield: \"Field4\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\tif val := m.GetField5(); val <= 0 || val > 1000 {\n\t\treturn MessageFValidationError{\n\t\t\tfield: \"Field5\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\treturn nil\n}", "func (t *OpenconfigMessages_Messages_State_Message) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigMessages_Messages_State_Message\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func SchemaValidateMessage(w http.ResponseWriter, r *http.Request) {\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\t// Get url path variables\n\turlVars := mux.Vars(r)\n\tschemaName := urlVars[\"schema\"]\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\n\t// Get project UUID First to use as reference\n\tprojectUUID := gorillaContext.Get(r, \"auth_project_uuid\").(string)\n\tschemasList, err := schemas.Find(projectUUID, \"\", schemaName, refStr)\n\tif err != nil {\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\tif schemasList.Empty() {\n\t\terr := APIErrorNotFound(\"Schema\")\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\tbuf := bytes.Buffer{}\n\t_, err = buf.ReadFrom(r.Body)\n\tif err != nil {\n\t\terr := APIErrorInvalidData(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\tmsgList := messages.MsgList{}\n\n\tswitch schemasList.Schemas[0].Type {\n\tcase schemas.JSON:\n\t\tmsg := messages.Message{\n\t\t\tData: base64.StdEncoding.EncodeToString(buf.Bytes()),\n\t\t}\n\n\t\tmsgList.Msgs = append(msgList.Msgs, msg)\n\n\tcase schemas.AVRO:\n\n\t\tbody := map[string]string{}\n\t\terr := json.Unmarshal(buf.Bytes(), &body)\n\t\tif err != nil {\n\t\t\terr := APIErrorInvalidRequestBody()\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\t// check to find the payload field\n\t\tif val, ok := body[\"data\"]; ok {\n\n\t\t\tmsg := messages.Message{\n\t\t\t\tData: val,\n\t\t\t}\n\n\t\t\tmsgList.Msgs = append(msgList.Msgs, msg)\n\n\t\t} else {\n\n\t\t\terr := APIErrorInvalidArgument(\"Schema Payload\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\terr = schemas.ValidateMessages(schemasList.Schemas[0], msgList)\n\tif err != nil {\n\t\tif err.Error() == \"500\" {\n\t\t\terr := APIErrGenericInternal(schemas.GenericError)\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t} else {\n\t\t\terr := APIErrorInvalidData(err.Error())\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tres, _ := json.MarshalIndent(map[string]string{\"message\": \"Message validated successfully\"}, \"\", \" \")\n\n\trespondOK(w, res)\n}", "func (msg *Data) Validate() map[string]string {\n\tvar rxEmail = regexp.MustCompile(\".+@.+\\\\..+\")\n\tmsg.Errors = make(map[string]string)\n\n\tmatch := rxEmail.Match([]byte(msg.Email))\n\tif match == false {\n\t\tmsg.Errors[\"email\"] = \"Please enter a valid email\"\n\t}\n\tif strings.TrimSpace(msg.FName) == \"\" {\n\t\tmsg.Errors[\"fname\"] = \"First name is required\"\n\t}\n\tif strings.TrimSpace(msg.FName) == \"\" {\n\t\tmsg.Errors[\"lname\"] = \"First name is required\"\n\t}\n\tif len(msg.Password) < 6 {\n\t\tmsg.Errors[\"pwd\"] = \"Password must be at least 6 characters\"\n\t}\n\treturn msg.Errors\n}", "func (c *Message) Validate(action string) map[string]string {\n\tvar errorMessages = make(map[string]string)\n\tvar err error\n\n\tswitch strings.ToLower(action) {\n\tcase \"update\":\n\t\tif c.Body == \"\" {\n\t\t\terr = errors.New(\"Required Body in a Message\")\n\t\t\terrorMessages[\"Required_body\"] = err.Error()\n\t\t}\n\tdefault:\n\t\tif c.Body == \"\" {\n\t\t\terr = errors.New(\"Required body to Message\")\n\t\t\terrorMessages[\"Required_body\"] = err.Error()\n\t\t}\n\t}\n\treturn errorMessages\n}", "func (m *MessageC) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif val := m.GetField1(); val <= 0 || val > 1000 {\n\t\treturn MessageCValidationError{\n\t\t\tfield: \"Field1\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\tif val := m.GetField2(); val <= 0 || val > 1000 {\n\t\treturn MessageCValidationError{\n\t\t\tfield: \"Field2\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\tif val := m.GetField3(); val <= 0 || val > 1000 {\n\t\treturn MessageCValidationError{\n\t\t\tfield: \"Field3\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\tif v, ok := interface{}(m.GetField4()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn MessageCValidationError{\n\t\t\t\tfield: \"Field4\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := interface{}(m.GetField5()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn MessageCValidationError{\n\t\t\t\tfield: \"Field5\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *MsgPing) Validate(interfaces.IState) int {\n\treturn 0\n}", "func (nS *PostMessageBody) Validate() error {\n\treturn validator.New().Struct(nS)\n}", "func (ps *PrjnStru) Validate(logmsg bool) error {\n\temsg := \"\"\n\tif ps.Pat == nil {\n\t\temsg += \"Pat is nil; \"\n\t}\n\tif ps.Recv == nil {\n\t\temsg += \"Recv is nil; \"\n\t}\n\tif ps.Send == nil {\n\t\temsg += \"Send is nil; \"\n\t}\n\tif emsg != \"\" {\n\t\terr := errors.New(emsg)\n\t\tif logmsg {\n\t\t\tlog.Println(emsg)\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}", "func (otpm OTPMessage) Validate() error {\n\treturn validation.ValidateStruct(&otpm,\n\t\tvalidation.Field(&otpm.Phone, validation.Required),\n\t\tvalidation.Field(&otpm.Code, validation.Required),\n\t\tvalidation.Field(&otpm.Provider, validation.Required),\n\t)\n}", "func (m Msg) ValidateWireMessage() error {\n\tif int(m.MsgHeader.MessageLength) != m.Len() {\n\t\treturn errors.New(\"incorrect header: message length is not correct\")\n\t}\n\tif m.MsgHeader.OpCode != OpMsg {\n\t\treturn errors.New(\"incorrect header: opcode is not OpMsg\")\n\t}\n\n\treturn nil\n}", "func (m *EventStatusMessage) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (mc *MessageCard) Validate() error {\n\tif mc.ValidateFunc != nil {\n\t\treturn mc.ValidateFunc()\n\t}\n\n\t// Falling back to a default implementation\n\tif (mc.Text == \"\") && (mc.Summary == \"\") {\n\t\t// This scenario results in:\n\t\t// 400 Bad Request\n\t\t// Summary or Text is required.\n\t\treturn fmt.Errorf(\"invalid message card: summary or text field is required\")\n\t}\n\n\treturn nil\n}", "func (m *MaxofMessageProtocolTests) Validate() error {\n\treturn m.validate(false)\n}", "func (t *OpenconfigMessages_Messages) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigMessages_Messages\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (e *Envelope) ValidateMessage() error {\n\tif e.msg == nil {\n\t\treturn ErrNoMessage\n\t}\n\n\tif e.msg.Id == \"\" {\n\t\treturn ErrNoEnvelopeId\n\t}\n\n\tif e.msg.Timestamp == \"\" {\n\t\treturn ErrNoTimestamp\n\t}\n\n\t// The message should have either an error or an encrypted payload\n\tif len(e.msg.Payload) == 0 {\n\t\tif e.msg.Error == nil || e.msg.Error.IsZero() {\n\t\t\treturn ErrNoMessageData\n\t\t}\n\t\treturn nil\n\t}\n\n\t// If there is a payload then all payload fields should be set\n\tif len(e.msg.EncryptionKey) == 0 || e.msg.EncryptionAlgorithm == \"\" {\n\t\treturn ErrNoEncryptionInfo\n\t}\n\n\tif len(e.msg.Hmac) == 0 || len(e.msg.HmacSecret) == 0 || e.msg.HmacAlgorithm == \"\" {\n\t\treturn ErrNoHMACInfo\n\t}\n\n\t// Note: not validating public_key_signature or sealed fields\n\treturn nil\n}", "func (m *MsgReject) Validate(interfaces.IState) int {\n\treturn 0\n}", "func (o *MediaConnectionStatusBadRequestBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateCommandType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateParams(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *CreateChannelBadRequestBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *MessageD) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif val := m.GetField1(); val <= 0 || val > 1000 {\n\t\treturn MessageDValidationError{\n\t\t\tfield: \"Field1\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\tif val := m.GetField2(); val <= 0 || val > 1000 {\n\t\treturn MessageDValidationError{\n\t\t\tfield: \"Field2\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\tif val := m.GetField3(); val <= 0 || val > 1000 {\n\t\treturn MessageDValidationError{\n\t\t\tfield: \"Field3\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\tif v, ok := interface{}(m.GetField4()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn MessageDValidationError{\n\t\t\t\tfield: \"Field4\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := interface{}(m.GetField5()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn MessageDValidationError{\n\t\t\t\tfield: \"Field5\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Chat) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.NewErrors(), nil\n}", "func (m *DeleteMessageRequest) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for OrderId\n\n\t// no validation rules for ItemId\n\n\t// no validation rules for Id\n\n\treturn nil\n}", "func ValidateRedisMessage(data []byte) error {\n\t_, e := validateMessage(data)\n\treturn e\n}", "func ValidateMsg(m *Message) error {\n\tif !validTopic.MatchString(m.Topic) {\n\t\treturn fmt.Errorf(\"The specified topic[%s] contains illegal characters or has invalid length\", m.Topic)\n\t}\n\tif AutoCreateTopicKeyTopic == m.Topic {\n\t\treturn fmt.Errorf(\"The topic[%s] is conflict with AUTO_CREATE_TOPIC_KEY_TOPIC\", m.Topic)\n\t}\n\tif m.Body == nil || len(m.Body) == 0 || len(m.Body) > MaxMessageSize {\n\t\treturn errors.New(\"The message body is nil or exceed the max allowed length\")\n\t}\n\treturn nil\n}", "func (r *Rule) Validate() error {\n\tif len(r.From) == 0 && len(r.Subject) == 0 {\n\t\treturn errors.New(\"Need to set From or Subject\")\n\t}\n\n\tif len(r.Channels) == 0 {\n\t\treturn errors.New(\"Need to set at least one channel or user for destination\")\n\t}\n\n\tfor _, channel := range r.Channels {\n\t\tif channel != \"\" && !validateChannel(channel) {\n\t\t\treturn errors.New(\"Need to set #channel or @user\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o *DeleteCustomPropertyForDeviceBadRequestBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateMessage(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func ValidateMAR(msg *diam.Message) error {\n\tif msg == nil {\n\t\treturn errors.New(\"Message is nil\")\n\t}\n\t_, err := msg.FindAVP(avp.UserName, dict.UndefinedVendorID)\n\tif err != nil {\n\t\treturn errors.New(\"Missing IMSI in message\")\n\t}\n\t_, err = msg.FindAVP(avp.SIPNumberAuthItems, diameter.Vendor3GPP)\n\tif err != nil {\n\t\treturn errors.New(\"Missing SIP-Number-Auth-Items in message\")\n\t}\n\t_, err = msg.FindAVP(avp.SIPAuthDataItem, diameter.Vendor3GPP)\n\tif err != nil {\n\t\treturn errors.New(\"Missing SIP-Auth-Data-Item in message\")\n\t}\n\t_, err = msg.FindAVP(avp.SIPAuthenticationScheme, diameter.Vendor3GPP)\n\tif err != nil {\n\t\treturn errors.New(\"Missing SIP-Authentication-Scheme in message\")\n\t}\n\t_, err = msg.FindAVP(avp.RATType, diameter.Vendor3GPP)\n\tif err != nil {\n\t\treturn errors.New(\"Missing RAT type in message\")\n\t}\n\treturn nil\n}", "func (t *OpenconfigSystem_System_Messages_State_Message) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Messages_State_Message\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (cr CommandReply) ValidateWireMessage() error {\r\n\tpanic(\"not implemented\")\r\n}", "func (m *MessageE) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif val := m.GetField1(); val <= 0 || val > 1000 {\n\t\treturn MessageEValidationError{\n\t\t\tfield: \"Field1\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\tif val := m.GetField2(); val <= 0 || val > 1000 {\n\t\treturn MessageEValidationError{\n\t\t\tfield: \"Field2\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\tif val := m.GetField3(); val <= 0 || val > 1000 {\n\t\treturn MessageEValidationError{\n\t\t\tfield: \"Field3\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\tif val := m.GetField4(); val <= 0 || val > 1000 {\n\t\treturn MessageEValidationError{\n\t\t\tfield: \"Field4\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\tif v, ok := interface{}(m.GetField5()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn MessageEValidationError{\n\t\t\t\tfield: \"Field5\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func ValidatorMessage(w http.ResponseWriter, err error) {\n\tw.WriteHeader(http.StatusBadRequest)\n\n\tapiValidator := &APIValidator{}\n\n\tfor _, err := range err.(validator.ValidationErrors) {\n\t\tapiValidator.Errors = append(apiValidator.Errors, validationMap(err))\n\t}\n\n\tif err := json.NewEncoder(w).Encode(apiValidator); err != nil {\n\t\tw.Write([]byte(\"Could not encode the payload\"))\n\t\treturn\n\t}\n}", "func TestMimeMessageValidity(t *testing.T) {\n\tm := MimeMessage{\n\t\tToAddress: \"[email protected]\",\n\t\tContent: []byte(\"This is my body. There are many like it but this one is mine.\")}\n\n\tif m.IsValid() != true {\n\t\tt.Error(\"Message should have been valid!\")\n\t}\n\n\tm.ToAddress = \"\"\n\tif m.IsValid() != false {\n\t\tt.Error(\"Message(2) should have been invalid!\")\n\t}\n\n\tm = MimeMessage{ToAddress: \"[email protected]\"}\n\tif m.IsValid() != false {\n\t\tt.Error(\"Message(3) should have been invalid!\")\n\t}\n}", "func (m *CreatMessageResponse) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for Id\n\n\treturn nil\n}", "func Validate(params Params) (err error) {\n\tif params.Length <= 0 {\n\t\treturn errors.New(\"Length must be more than 0\")\n\t}\n\tif params.Square <= 0 {\n\t\treturn errors.New(\"Square must be more than 0\")\n\t}\n\treturn nil\n}", "func (m *GetMessageRequest) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for OrderId\n\n\t// no validation rules for ItemId\n\n\t// no validation rules for Id\n\n\treturn nil\n}", "func (m *PublishRequest) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for Message\n\n\treturn nil\n}", "func (m *MessageB) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif val := m.GetField1(); val <= 0 || val > 1000 {\n\t\treturn MessageBValidationError{\n\t\t\tfield: \"Field1\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\tif val := m.GetField2(); val <= 0 || val > 1000 {\n\t\treturn MessageBValidationError{\n\t\t\tfield: \"Field2\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\tif val := m.GetField3(); val <= 0 || val > 1000 {\n\t\treturn MessageBValidationError{\n\t\t\tfield: \"Field3\",\n\t\t\treason: \"value must be inside range (0, 1000]\",\n\t\t}\n\t}\n\n\tif v, ok := interface{}(m.GetField4()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn MessageBValidationError{\n\t\t\t\tfield: \"Field4\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := interface{}(m.GetField5()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn MessageBValidationError{\n\t\t\t\tfield: \"Field5\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *CreatMessageRequest) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for OrderId\n\n\t// no validation rules for ItemId\n\n\tif v, ok := interface{}(m.GetMessage()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn CreatMessageRequestValidationError{\n\t\t\t\tfield: \"Message\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func Validate(msg *api.SecureEnvelope) (err error) {\n\tvar env *Envelope\n\tif env, err = Wrap(msg); err != nil {\n\t\treturn err\n\t}\n\treturn env.ValidateMessage()\n}", "func (o *MediaConnectionStatusBadRequestBodyParams) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateErrors(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m Name) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := validate.Pattern(\"\", \"body\", string(m), `^[A-Za-z0-1.\\-_]*$`); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *StreamAccessLogsMessage) Validate() error {\n\treturn m.validate(false)\n}", "func (m *Participant422Error) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (message *EditProfileMessage) Validate() bool {\n\tmatch, _ := regexp.MatchString(\"[a-zA-Z0-9_]{3,}@[a-zA-Z0-9_]{3,}.[a-zA-Z0-9_]{3,}\", message.Email)\n\treturn match && common.StringInSlice(message.Province, provincesList)\n}", "func (o *PostChannelsEmailBadRequestBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Error400Data\n\tif err := o.Error400Data.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func ValidateIndividualMessage(astarteInterface AstarteInterface, path string, value interface{}) error {\n\t// Get the corresponding mapping\n\tmapping, err := InterfaceMappingFromPath(astarteInterface, path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Validate type and return result\n\treturn validateType(mapping.Type, value)\n}", "func (m *DeleteMessageResponse) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for Deleted\n\n\treturn nil\n}", "func (payload *listMessagePayload) Validate() (err error) {\n\tif payload.OfferID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"offer_id\"))\n\t}\n\treturn\n}", "func (o *DeleteCustomPropertyForTenantBadRequestBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateMessage(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (p LedgerChannelProposalMsg) Valid() error {\n\tif err := p.BaseChannelProposal.Valid(); err != nil {\n\t\treturn err\n\t}\n\tif p.Participant == nil {\n\t\treturn errors.New(\"invalid nil participant\")\n\t}\n\treturn nil\n}", "func (m *MailMessage) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCc(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReplyBy(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReplyTo(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSections(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTo(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *MsgVpn) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAuthenticationBasicType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAuthenticationClientCertRevocationCheckMode(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAuthenticationClientCertUsernameSource(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAuthorizationType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventConnectionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventEgressFlowCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventEgressMsgRateThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventEndpointCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventIngressFlowCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventIngressMsgRateThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventMsgSpoolUsageThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventPublishSubscriptionMode(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventServiceAmqpConnectionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventServiceMqttConnectionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventServiceRestIncomingConnectionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventServiceSmfConnectionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventServiceWebConnectionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventSubscriptionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventTransactedSessionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventTransactionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePreferIPVersion(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReplicationBridgeAuthenticationScheme(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReplicationEnabledQueueBehavior(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReplicationRole(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReplicationTransactionMode(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateServiceRestMode(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (s *Validator) Validate() error {\n\treturn errors.Wrap(s.h.Trigger(), \"validation webhook failed\")\n}", "func (mt *Room) Validate() (err error) {\n\tif mt.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"name\"))\n\t}\n\tif mt.Description == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"description\"))\n\t}\n\tif utf8.RuneCountInString(mt.Description) > 400 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.description`, mt.Description, utf8.RuneCountInString(mt.Description), 400, false))\n\t}\n\treturn\n}", "func (gm GetMore) ValidateWireMessage() error {\n\tif int(gm.MsgHeader.MessageLength) != gm.Len() {\n\t\treturn errors.New(\"incorrect header: message length is not correct\")\n\t}\n\tif gm.MsgHeader.OpCode != OpGetMore {\n\t\treturn errors.New(\"incorrect header: op code is not OpGetMore\")\n\t}\n\tif strings.Index(gm.FullCollectionName, \".\") == -1 {\n\t\treturn errors.New(\"incorrect header: collection name does not contain a dot\")\n\t}\n\n\treturn nil\n}", "func (m *Expect) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAmqp(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGrpc(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHTTP(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateKafka(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *RemovePolicyOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateMessage(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m ValidationStatus) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// value enum\n\tif err := m.validateValidationStatusEnum(\"\", \"body\", m); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (t *OpenconfigMessages_Messages_State) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigMessages_Messages_State\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *CommandError) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateArguments(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *UpdateMessageResponse) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for Updated\n\n\treturn nil\n}", "func (o *GetGatewayUsingGETBadRequestBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateMessage(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (message *ChangePasswordMessage) Validate() bool {\n\treturn len(message.OldPassword) >= 8 && len(message.NewPassword) >= 8\n}", "func (e *Event) Validate() error {\n\tif e.Message == \"\" || e.MessageOffset == \"\" || e.Time == nil || e.Type == \"\" {\n\t\treturn errs.ErrMissingParameters\n\t}\n\treturn nil\n}", "func (m *notification) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (h CreateEscrowHandler) validate(ctx weave.Context, db weave.KVStore, tx weave.Tx) (*CreateMsg, error) {\n\tvar msg CreateMsg\n\tif err := weave.LoadMsg(tx, &msg); err != nil {\n\t\treturn nil, errors.Wrap(err, \"load msg\")\n\t}\n\tif weave.IsExpired(ctx, msg.Timeout) {\n\t\treturn nil, errors.Wrap(errors.ErrInput, \"timeout in the past\")\n\t}\n\tif !h.auth.HasAddress(ctx, msg.Source) {\n\t\treturn nil, errors.ErrUnauthorized\n\t}\n\treturn &msg, nil\n}", "func (o *DataDeleteBadRequestBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateCommandType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateParams(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func TestMsgAddSuperValidation(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\texpectPass bool\n\t\tmsg *MsgAddSuper\n\t}{\n\t\t{\"pass\", true, NewMsgAddSuper(description, testAddr, sender)},\n\t\t{\"invalid Description\", false, NewMsgAddSuper(nilDescription, testAddr, sender)},\n\t\t{\"invalid Address\", false, NewMsgAddSuper(description, nilAddr, sender)},\n\t\t{\"invalid AddedBy\", false, NewMsgAddSuper(description, testAddr, nilAddr)},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\terr := tc.msg.ValidateBasic()\n\t\t\tif tc.expectPass {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.Error(t, err)\n\t\t\t}\n\t\t})\n\t}\n}", "func (r *Room) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.NewErrors(), nil\n}", "func (t Transition) Validate() error {\n\tif _, err := sdk.AccAddressFromBech32(t.Subject); err != nil {\n\t\treturn errors.Wrap(err, \"invalid subject address\")\n\t}\n\tif _, err := sdk.AccAddressFromBech32(t.Destination); err != nil {\n\t\treturn errors.Wrap(err, \"invalid destination address\")\n\t}\n\treturn nil\n}", "func (m *SentEmail) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func ValidateAddRequest(message *taskspb.AddRequest) (err error) {\n\tif utf8.RuneCountInString(message.Title) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(\"message.title\", message.Title, utf8.RuneCountInString(message.Title), 200, false))\n\t}\n\tif utf8.RuneCountInString(message.Description) > 5000 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(\"message.description\", message.Description, utf8.RuneCountInString(message.Description), 5000, false))\n\t}\n\terr = goa.MergeErrors(err, goa.ValidateFormat(\"message.created_date\", message.CreatedDate, goa.FormatDateTime))\n\n\terr = goa.MergeErrors(err, goa.ValidateFormat(\"message.updated_date\", message.UpdatedDate, goa.FormatDateTime))\n\n\tif message.DueDate != \"\" {\n\t\terr = goa.MergeErrors(err, goa.ValidateFormat(\"message.due_date\", message.DueDate, goa.FormatDateTime))\n\t}\n\tif !(message.Status == \"Open\" || message.Status == \"Closed\" || message.Status == \"Pending\") {\n\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(\"message.status\", message.Status, []interface{}{\"Open\", \"Closed\", \"Pending\"}))\n\t}\n\tif message.Owner != nil {\n\t\tif err2 := ValidateStoredUser(message.Owner); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\tif message.Assignee != nil {\n\t\tif err2 := ValidateStoredUser(message.Assignee); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\treturn\n}", "func TestValidateSetDesiredSizeMessage(t *testing.T) {\n\t// SetDesiredSizeMessage with desiredSize => should pass validation\n\tdesiredSize := 1\n\tm := SetDesiredSizeMessage{DesiredSize: &desiredSize}\n\terr := m.Validate()\n\trequire.Nil(t, err, \"expected validation to succeed\")\n\n\t// SetDesiredSizeMessage missing desiredSize => should fail validation\n\tm = SetDesiredSizeMessage{}\n\terr = m.Validate()\n\trequire.NotNil(t, err, \"expected validation to fail due to missing desiredSize\")\n\trequire.Equal(t, fmt.Errorf(\"setDesiredSize message did not specify a desiredSize\"), err, \"unexpected validation error\")\n\n\t// SetDesiredSizeMessage with negative desiredSize => should fail validation\n\tdesiredSize = -1\n\tm = SetDesiredSizeMessage{DesiredSize: &desiredSize}\n\terr = m.Validate()\n\trequire.NotNil(t, err, \"expected validation to fail due to negative desiredSize\")\n\trequire.Equal(t, fmt.Errorf(\"setDesiredSize message: desiredSize must be non-negative\"), err, \"unexpected validation error\")\n}", "func (m *GiftMessageDataMessageExtensionInterface) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func ValidateInputLength(cepRaw interface{}) observable.Observable {\n\treturn observable.Create(func(emitter *observer.Observer, disposed bool) {\n\t\tcep, _ := cepRaw.(string)\n\t\tcepLength := len(cep)\n\t\tif cepLength <= cepSize {\n\t\t\temitter.OnNext(cep)\n\t\t\temitter.OnDone()\n\t\t} else {\n\t\t\temitter.OnError(errors.New(\"Cep length is less than 8 characters\"))\n\t\t}\n\t})\n}", "func (r *NotifyRequest) Validate() error {\n\tif r.Credentials == nil && r.OAuthToken.Token == \"\" {\n\t\treturn errors.New(\"secret was empty\")\n\t}\n\tif len(r.Channels) == 0 {\n\t\treturn errors.New(\"channels was empty\")\n\t}\n\tif r.Title == \"\" {\n\t\treturn errors.New(\"title was empty\")\n\t}\n\treturn nil\n}" ]
[ "0.7358442", "0.71898216", "0.71188724", "0.70728076", "0.7068548", "0.6982173", "0.6902308", "0.679386", "0.6727855", "0.66492987", "0.66470295", "0.660603", "0.65974987", "0.6574964", "0.64521635", "0.64391905", "0.64344645", "0.6430751", "0.64243865", "0.64128774", "0.64044964", "0.6397957", "0.6388908", "0.6375554", "0.6342253", "0.6317806", "0.6261644", "0.6245553", "0.6208494", "0.62081945", "0.6198753", "0.6187401", "0.61679924", "0.61058813", "0.60912997", "0.6043768", "0.6042723", "0.6035947", "0.60346824", "0.60338", "0.60058016", "0.60031736", "0.59985906", "0.5956836", "0.5944313", "0.59356594", "0.59300154", "0.59029967", "0.5901414", "0.58810437", "0.58618176", "0.585366", "0.5835867", "0.5802501", "0.57909393", "0.5787181", "0.57809603", "0.5780334", "0.5750607", "0.57485175", "0.574381", "0.57352453", "0.57278335", "0.56924593", "0.569187", "0.568792", "0.56765294", "0.5667728", "0.56452036", "0.5629847", "0.5616431", "0.5600836", "0.5597601", "0.55947095", "0.5575165", "0.55709577", "0.5561012", "0.5551406", "0.5550468", "0.55474997", "0.55460036", "0.5523286", "0.5511992", "0.5510429", "0.5509296", "0.55090016", "0.5508985", "0.55076385", "0.5504298", "0.5503001", "0.5499014", "0.5496266", "0.5485363", "0.54837674", "0.54816973", "0.54786634", "0.54743385", "0.5471786", "0.5468088", "0.546154" ]
0.6104094
34
write writes data to the connection & then closes.
func (c *context) write(data []byte) error { defer c.close() _, err := c.conn.Write(data) return err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *RESPConn) write(raw []byte) error {\n\tif c.conn == nil {\n\t\treturn ErrConnClosed\n\t}\n\n\tc.conn.SetWriteDeadline(time.Now().Add(c.timeout))\n\t_, err := c.conn.Write(raw)\n\terr = wrapErr(err)\n\tif err == ErrConnClosed {\n\t\tc.close()\n\t}\n\n\treturn err\n}", "func ConnCloseWrite(c *tls.Conn,) error", "func (c *connection) write(opCode int, payload []byte) error {\n\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\treturn c.ws.WriteMessage(opCode, payload)\n}", "func (c *connection) write(mt int, payload []byte) error {\n\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\treturn c.ws.WriteMessage(mt, payload)\n}", "func (c *connection) write(mt int, payload []byte) error {\n\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\treturn c.ws.WriteMessage(mt, payload)\n}", "func (c *Client) write(mt int, payload []byte) error {\n\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\treturn c.conn.WriteMessage(mt, payload)\n}", "func (c *Conn) write(mt int, payload []byte) error {\n\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\treturn c.ws.WriteMessage(mt, payload)\n}", "func (c *Conn) write(t int, buf []byte) error {\n\tc.ws.SetWriteDeadline(time.Now().Add(c.WriteTimeout * time.Second))\n\treturn c.ws.WriteMessage(t, buf)\n}", "func (c *connectSvr) write(mt int, payload []byte) error {\n\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\treturn c.ws.WriteMessage(mt, payload)\n}", "func (c *Conn) write(messageType int, p []byte) (n int, err error) {\n\tc.wmutex.Lock()\n\tdefer c.wmutex.Unlock()\n\tselect {\n\tcase <-c.done:\n\t\terr = ErrClosing\n\tdefault:\n\t\terr = c.ws.SetWriteDeadline(time.Now().Add(WriteTimeout))\n\t\tif err == nil {\n\t\t\terr = c.ws.WriteMessage(messageType, p)\n\t\t}\n\t}\n\tif err == nil {\n\t\tn = len(p)\n\t}\n\treturn n, err\n}", "func (conn *Connection) write(mt int, payload []byte, wsc config.WebSocketSettings) error {\n\tconn.ws.SetWriteDeadline(time.Now().Add(wsc.WriteWait))\n\treturn conn.ws.WriteMessage(mt, payload)\n}", "func (v *HVsockConn) write(buf []byte) (int, error) {\n\tvar b syscall.WSABuf\n\tvar f uint32\n\n\tif len(buf) == 0 {\n\t\treturn 0, nil\n\t}\n\n\tf = 0\n\tb.Len = uint32(len(buf))\n\tb.Buf = &buf[0]\n\n\tc, err := v.prepareIo()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif v.writeDeadline.timedout.isSet() {\n\t\treturn 0, ErrTimeout\n\t}\n\n\tvar bytes uint32\n\terr = syscall.WSASend(v.fd, &b, 1, &bytes, f, &c.o, nil)\n\tn, err := v.asyncIo(c, &v.writeDeadline, bytes, err)\n\truntime.KeepAlive(buf)\n\treturn n, err\n}", "func (c *client) write(mt int, message []byte) error {\n\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\treturn c.ws.WriteMessage(mt, message)\n}", "func (c *Client) write(mt int, payload []byte) error {\n\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\treturn c.ws.WriteMessage(mt, payload)\n}", "func (network *tcp_net) write(buffer []byte, conn *net.TCPConn) error {\n\t// if we don't have specific connection to write\n\t// just choosing from available channels using round rubin algorithm\n\tif conn == nil {\n\t\tnetwork.connection_locker.Lock()\n\t\tif len(network.connections) == 0 {\n\t\t\treturn errors.New(\"There is no available channels to write to!\")\n\t\t}\n\n\t\t// getting one of the connections\n\t\tif network.connection_index >= len(network.connections) {\n\t\t\tnetwork.connection_index = 0\n\t\t}\n\t\tconn = network.connections[network.connection_index]\n\t\tnetwork.connection_index++\n\t\tnetwork.connection_locker.Unlock()\n\t}\n\n\twrite_offset := 0\n\tdata_len := len(buffer)\n\n\tfor {\n\t\tn, err := conn.Write(buffer[write_offset:])\n\t\tif err != nil {\n\t\t\t// if we have EOF, then we need to return from write functionality\n\t\t\t// connection would be closed from reader\n\t\t\tif err == io.EOF {\n\t\t\t\treturn errors.New(\"Connection channel closed!\")\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tif n+write_offset < data_len {\n\t\t\twrite_offset += n\n\t\t\tcontinue\n\t\t}\n\n\t\t// if we got here, then all data have been written\n\t\t// so just breaking loop to return\n\t\tbreak\n\t}\n\n\treturn nil\n}", "func (s *SubmissionHandler) write(d string) error {\n\tif _, e := s.conn.Write([]byte(d)); e != nil {\n\t\treturn e\n\t}\n\t_, e := s.conn.Write([]byte(util.EOT))\n\treturn e\n}", "func (c *Connection) writeData(data []byte) error {\n\t_, err := c.Conn.Write(data[:])\n\n\treturn err\n}", "func (k *Link) closeWrite() {\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\tif k.writeClosed {\n\t\treturn\n\t}\n\tk.writeClosed = true\n\n\tif k.kconn != nil {\n\t\tk.kconn.CloseWrite()\n\t}\n\n\tclose(k.wchannel)\n\tdrain := func() {\n\t\tfor data := range k.wchannel {\n\t\t\tmpool.Put(data)\n\t\t}\n\t}\n\tdrain()\n\tCT(T_Channel, OP_Decrease)\n\tk.tryToCloseKConn()\n\n}", "func (connection *Connection) Write(b []byte) (int, error) {\n\t//TODO\n}", "func (c *Connection) Write(b []byte) (int, error) {\n\twt := config.Get().Timeout.TimeoutReadWrite\n\tif wt == 0 {\n\t\twt = 1\n\t}\n\n\twriteTimeout := time.Duration(wt) * time.Second // Max idle time for a peer\n\n\tc.lock.Lock()\n\t_ = c.Conn.SetWriteDeadline(time.Now().Add(writeTimeout))\n\tn, err := c.Conn.Write(b)\n\tc.lock.Unlock()\n\n\treturn n, err\n}", "func (c *client) write() {\n\tfor msg := range c.send {\n\t\tif err := c.socket.WriteMessage(websocket.TextMessage, msg); err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tc.socket.Close()\n}", "func write(msg string, conn net.Conn) error {\n\tlog.Print(msg)\n\tconn.Write([]byte(msg))\n\treturn errors.New(msg)\n}", "func writer(conn net.Conn){\r\n writer:= bufio.NewWriter(conn) // makes a new writer for port\r\n for {\r\n select{\r\n case values := <- pass :{\r\n if (values != \"close\"){\r\n writer.WriteString(values) //write string to port\r\n writer.Flush() // clear the buffer\r\n } else if (values == \"close\"){ // if reading error is found then close the connection\r\n return\r\n }\r\n }\r\n }\r\n }\r\n }", "func (client *Client) write() {\n\tfor data := range client.Outgoing {\n\t\tclient.writer.WriteString(data)\n\t\tclient.writer.Flush()\n\t}\n}", "func (dc *dummyConn) Write(p []byte) (int, error) { return len(p), nil }", "func ConnWrite(c *tls.Conn, b []byte) (int, error)", "func writer(conn net.Conn){\n writer:= bufio.NewWriter(conn) // makes a new writer for port\n for {\n select{\n case values := <- pass :{\n if (values != \"close\"){\n writer.WriteString(values) //write string to port\n writer.Flush() // clear the buffer\n } else if (values == \"close\"){ // if reading error is found then close the connection\n conn.Close() // closes the connection\n return\n }\n }\n }\n }\n }", "func (c *WrappedConn) Write(b []byte) (n int, err error) {\n\t//c.Conn is certainly not nil\n\tn, err = c.Conn.Write(b)\n\tif err != nil {\n\t\tc.unusable = true\n\t} else {\n\t\tc.lastAccess = time.Now()\n\t}\n\treturn\n}", "func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error) {\n\tif w.conn.hijacked() {\n\t\tif lenData > 0 {\n\t\t\tcaller := relevantCaller()\n\t\t\tw.conn.server.logf(\"http: response.Write on hijacked connection from %s (%s:%d)\", caller.Function, path.Base(caller.File), caller.Line)\n\t\t}\n\t\treturn 0, ErrHijacked\n\t}\n\n\tif w.canWriteContinue.isSet() {\n\t\t// Body reader wants to write 100 Continue but hasn't yet.\n\t\t// Tell it not to. The store must be done while holding the lock\n\t\t// because the lock makes sure that there is not an active write\n\t\t// this very moment.\n\t\tw.writeContinueMu.Lock()\n\t\tw.canWriteContinue.setFalse()\n\t\tw.writeContinueMu.Unlock()\n\t}\n\n\tif !w.wroteHeader {\n\t\tw.WriteHeader(StatusOK)\n\t}\n\tif lenData == 0 {\n\t\treturn 0, nil\n\t}\n\tif !w.bodyAllowed() {\n\t\treturn 0, ErrBodyNotAllowed\n\t}\n\n\tw.written += int64(lenData) // ignoring errors, for errorKludge\n\tif w.contentLength != -1 && w.written > w.contentLength {\n\t\treturn 0, ErrContentLength\n\t}\n\tif dataB != nil {\n\t\treturn w.w.Write(dataB)\n\t} else {\n\t\treturn w.w.WriteString(dataS)\n\t}\n}", "func (c *client) write() {\n\tfor {\n\t\ttoWrite := <-c.send\n\t\t_ = c.conn.WriteMessage(websocket.BinaryMessage, toWrite)\n\t}\n}", "func (c *Conn) Write(b []byte) (int, error) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\treturn c.Conn.Write(b)\n}", "func (p *Conn) Write(b []byte) (int, error) {\n\treturn p.conn.Write(b)\n}", "func (d *Driver) write(data []byte) error {\n\t// d.log(\"write\", time.Now(), data)\n\tn, err := d.device.Write(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n != len(data) {\n\t\treturn errors.New(\"unexpected write size\")\n\t}\n\treturn nil\n}", "func (c udpConn) CloseWrite() error {\n\treturn fmt.Errorf(\"Unimplemented\")\n}", "func (e *agentEndpoint) write(msg *submitws.Message) {\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\tif e.isClosed {\n\t\treturn\n\t}\n\tif err := e.conn.WriteMessage(websocket.BinaryMessage, msg.ToBinary()); err != nil {\n\t\tlogger.WithError(err).Errorf(\"error sending message to agent with id == %s: %v\", e.id, err)\n\t\tif err := e.conn.Close(); err != nil {\n\t\t\tlogger.WithError(err).Errorf(\"error closing connection to agent with id == %s after write error: %v\", e.id, err)\n\t\t}\n\t\te.isClosed = true\n\t}\n}", "func (b *Bricker) write(e *event.Event) {\n\tif e != nil {\n\t\tif conn, ok := b.connection[e.ConnectorName]; ok {\n\t\t\tconn.Send(e)\n\t\t} else {\n\t\t\te.Err = NewError(ErrorConnectorNameNotExists)\n\t\t\tgo b.dispatch(e)\n\t\t}\n\t}\n}", "func (v *vsockConn) CloseWrite() error {\n\treturn syscall.Shutdown(int(v.fd), syscall.SHUT_WR)\n}", "func (dc DeadlineConn) Write(data []byte) (int, error) {\n\tcount := 0\n\terr := dc.Conn.SetWriteDeadline(time.Now().Add(dc.timeout))\n\tif err != nil {\n\t\treturn count, err\n\t}\n\t// don't bother with resetting the deadline since it will be set\n\t// again next time we call Write()\n\treturn dc.Conn.Write(data)\n}", "func (c *Conn) Write(b []byte) (int, error) {\n\tif c.writeTimeout > 0 {\n\t\tif err := c.Conn.SetWriteDeadline(time.Now().Add(c.writeTimeout)); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\tn, err := c.Conn.Write(b)\n\tif err == nil && c.Stats != nil {\n\t\tc.Stats.WriteTotal.Add(uint64(n))\n\t}\n\tc.incBytesOut(n)\n\treturn n, err\n}", "func (c *Conn) Write(b []byte) (n int, err error) {\n\treturn syscall.Write(c.fd, b)\n}", "func (obj *Client) WriteClose(clNum int, mgs string) {\n\tif err := obj.Conn.WriteControl(websocket.CloseMessage,\n\t\twebsocket.FormatCloseMessage(clNum, mgs),\n\t\ttime.Time{}); err != nil {\n\t\tlog.Printf(\"Can't close connection: %s\", mgs)\n\t}\n}", "func (c *Conn) Write(b []byte) (int, error) {\n\terr := c.Conn.SetWriteDeadline(time.Now().Add(c.WriteTimeout))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn c.Conn.Write(b)\n}", "func (c *Connection) Write(mt int, payload []byte) error {\n\tc.Conn.SetWriteDeadline(time.Now().Add(WriteWait))\n\treturn c.Conn.WriteMessage(mt, payload)\n}", "func (c *Conn) CloseWrite() error {\n\tif closer, ok := c.Conn.(interface {\n\t\tCloseWrite() error\n\t}); ok {\n\t\treturn closer.CloseWrite()\n\t}\n\treturn nil\n}", "func (c *Connection) write(msg interface{}) {\n c.mutex.Lock()\n c.log(fmt.Sprintf(\"Sending message: %+v\", msg))\n c.socket.WriteJSON(msg)\n c.mutex.Unlock()\n}", "func (s *Stream) write(b []byte) (n int, err error) {\n\tvar flags uint16\n\tvar max uint32\n\tvar body []byte\nSTART:\n\ts.stateLock.Lock()\n\tswitch s.state {\n\tcase streamLocalClose:\n\t\tfallthrough\n\tcase streamClosed:\n\t\ts.stateLock.Unlock()\n\t\treturn 0, ErrStreamClosed\n\tcase streamReset:\n\t\ts.stateLock.Unlock()\n\t\treturn 0, ErrConnectionReset\n\t}\n\ts.stateLock.Unlock()\n\n\t// If there is no data available, block\n\twindow := atomic.LoadUint32(&s.sendWindow)\n\tif window == 0 {\n\t\tgoto WAIT\n\t}\n\n\t// Determine the flags if any\n\tflags = s.sendFlags()\n\n\t// Send up to our send window\n\tmax = min(window, uint32(len(b)))\n\tbody = b[:max]\n\n\t// Send the header\n\ts.sendHdr.encode(typeData, flags, s.id, max)\n\tif err = s.session.waitForSendErr(s.sendHdr, body, s.sendErr); err != nil {\n\t\treturn 0, err\n\t}\n\n\t// Reduce our send window\n\tatomic.AddUint32(&s.sendWindow, ^uint32(max-1))\n\n\t// Unlock\n\treturn int(max), err\n\nWAIT:\n\tvar timeout <-chan time.Time\n\twriteDeadline := s.writeDeadline.Load().(time.Time)\n\tif !writeDeadline.IsZero() {\n\t\tdelay := writeDeadline.Sub(time.Now())\n\t\ttimeout = time.After(delay)\n\t}\n\tselect {\n\tcase <-s.sendNotifyCh:\n\t\tgoto START\n\tcase <-timeout:\n\t\treturn 0, ErrTimeout\n\t}\n\treturn 0, nil\n}", "func (clientConn *Conn) Write(p []byte) (n int, err error) {\n\treturn clientConn.dataWriter.Write(p)\n}", "func (mc *MockConn) Write(b []byte) (n int, err error) {\n\tif mc.closed {\n\t\treturn 0, errors.New(\"Connection closed.\")\n\t}\n\n\tdata := make([]byte, len(b))\n\tcopy(data, b)\n\tmc.sendChan <- data\n\treturn len(b), nil\n}", "func (s *Subscriber) write(mt int, payload []byte) error {\n s.ws.SetWriteDeadline(time.Now().Add(writeWait))\n return s.ws.WriteMessage(mt, payload)\n}", "func (c *connection) Write(mt int, payload []byte) error {\r\n\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\r\n\treturn c.ws.WriteMessage(mt, payload)\r\n}", "func (e errorConnection) Write(b []byte) (n int, err error) {\n\treturn 0, e.err\n}", "func (c *Client) writeRoutine() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(ws.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(ws.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tmsg, err := json.Marshal(message)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"error:\", err)\n\t\t\t}\n\n\t\t\tw.Write(msg)\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(ws.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *conn) Write(p []byte) (int, error) {\n\terr := binary.Write(c.Conn, binary.BigEndian, uint32(len(p)))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn c.Conn.Write(p)\n}", "func (c *LimitedConnection) Write(b []byte) (written int, err error) {\n\treturn c.rateLimitLoop(&c.writeNotBefore, &c.writeDeadline, c.inner.Write, b)\n}", "func (w *WriterHttpConn) Write(b []byte) (n int, err error) {\n\treader := bytes.NewReader(b)\n\treq, err := http.NewRequest(w.Method, w.url.Scheme+\"://\"+w.url.Host+w.url.Path, reader)\n\t//log.Debug(w.url.Scheme+\"://\"+w.url.Host+w.url.Path)\n\tif err != nil {\n\t\tlog.Error(\"Request failed to construct: %s\", err)\n\t\treturn 0, err\n\t}\n\n\tres, err := w.client.Do(req)\n\n\tif err != nil {\n\t\tlog.Error(\"post request failed: `%s`\", err)\n\t\treturn 0, err\n\t}\n\tio.Copy(ioutil.Discard, res.Body)\n\tres.Body.Close()\n\treturn len(b), nil\n}", "func write(text string, channel chan string) {\n\ttime.Sleep(time.Second * 5)\n\tfor i := 0; i < 5; i++ {\n\t\t// this is the line that sends a value to the channel\n\t\tchannel <- text\n\t\ttime.Sleep(time.Second)\n\t}\n\n\t// we can use close() to close connections\n}", "func (conn *Conn) write(line string) {\n\tif !conn.Flood {\n\t\tif t := conn.rateLimit(len(line)); t != 0 {\n\t\t\t// sleep for the current line's time value before sending it\n\t\t\tlogging.Debug(\"irc.rateLimit(): Flood! Sleeping for %.2f secs.\",\n\t\t\t\tt.Seconds())\n\t\t\t<-time.After(t)\n\t\t}\n\t}\n\n\tif _, err := conn.io.WriteString(line + \"\\r\\n\"); err != nil {\n\t\tlogging.Error(\"irc.send(): %s\", err.Error())\n\t\tconn.shutdown()\n\t\treturn\n\t}\n\tif err := conn.io.Flush(); err != nil {\n\t\tlogging.Error(\"irc.send(): %s\", err.Error())\n\t\tconn.shutdown()\n\t\treturn\n\t}\n\tlogging.Debug(\"-> %s\", line)\n}", "func (b *BaseConn) writeLoop() {\n\n\tb.writeCapabilities()\n\n\tvar negotiationDone bool\n\tvar waitingMsgs []*baseproto.Message\n\nmainloop:\n\tfor {\n\t\tif !negotiationDone {\n\t\t\tselect {\n\t\t\tcase <-b.stop:\n\t\t\t\t// The stop channel closing indicates a close.\n\t\t\t\tbreak mainloop\n\n\t\t\tcase msg := <-b.send:\n\t\t\t\t// Put messages to send into the waiting queue.\n\t\t\t\twaitingMsgs = append(waitingMsgs, msg)\n\n\t\t\tcase msg := <-b.receivedCapabilities:\n\n\t\t\t\t// Unmarshal the capabilities message.\n\t\t\t\t// This node has an empty capabilities set,\n\t\t\t\t// so we always leave the connection's\n\t\t\t\t// capabilities empty.\n\t\t\t\tcapMsg := new(baseproto.Capabilities)\n\t\t\t\terr := proto.Unmarshal(msg.Content, capMsg)\n\t\t\t\tif err != nil {\n\t\t\t\t\tbreak mainloop\n\t\t\t\t}\n\t\t\t\tnegotiationDone = true\n\n\t\t\t\t// Send waiting messages.\n\t\t\t\tfor _, msg := range waitingMsgs {\n\t\t\t\t\tif err := b.writeMsg(msg); err != nil {\n\t\t\t\t\t\tbreak mainloop\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\twaitingMsgs = nil\n\t\t\t}\n\t\t} else {\n\n\t\t\tselect {\n\t\t\tcase <-b.stop:\n\t\t\t\t// The stop channel closing indicates a close.\n\t\t\t\tbreak mainloop\n\n\t\t\tcase msg := <-b.send:\n\t\t\t\t// Send requested messages.\n\t\t\t\terr := b.writeMsg(msg)\n\t\t\t\tif err != nil {\n\t\t\t\t\tbreak mainloop\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Kills the connection and receiver, if it hasn't died already.\n\tb.conn.Close()\n\n\t// Tell code using this connection that it is dead.\n\t// Cancels any currently blocked attempts to send to the connection.\n\tclose(b.disconnected)\n}", "func (rw *NopConn) SetWriteDeadline(time.Time) error { return nil }", "func (ctn *Connection) Write(buf []byte) (total int, err error) {\n\t// make sure all bytes are written\n\t// Don't worry about the loop, timeout has been set elsewhere\n\tlength := len(buf)\n\tfor total < length {\n\t\tvar r int\n\t\tif err = ctn.updateDeadline(); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tr, err = ctn.conn.Write(buf[total:])\n\t\ttotal += r\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If all bytes are written, ignore any potential error\n\t// The error will bubble up on the next network io if it matters.\n\tif total == len(buf) {\n\t\treturn total, nil\n\t}\n\n\tif ctn.node != nil {\n\t\tctn.node.incrErrorCount()\n\t\tatomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1)\n\t}\n\n\t// the line should happen before .Close()\n\terr = errToTimeoutErr(ctn, err)\n\tctn.Close()\n\n\treturn total, err\n}", "func (c *conn) processWrite(b []byte) bool {\n\tincrement(&writingWriting)\n\tn, err := c.rs.write(b)\n\tdecrement(&writingWriting)\n\n\tincrement(&writingPostingResponse)\n\tc.writeResponsesCh <- rwResponse{n, err}\n\tdecrement(&writingPostingResponse)\n\n\treturn err == nil\n}", "func (c *TestConnection) Write(b []byte) (n int, err error) {\n if c.WriteError != nil && c.ThrowWriteErrorAfter == c.TimesWriteCalled {\n return 0, c.WriteError\n }\n\n if c.WriteCount > -1 {\n return c.WriteCount, nil\n }\n\n c.TimesWriteCalled++\n c.Written = append(c.Written, string(b))\n return len(b), nil\n}", "func (c *Conn) Write(p []byte) (n int, err error) {\n\tn, err = c.bufw.Write(p)\n\tc.bufw.Flush()\n\treturn n, err\n}", "func (fwd *QuestdbForwarder) Write(b []byte) (n int, err error) {\n\tvar (\n\t\tlogp = `QuestdbForwarder.Write`\n\t\tnow = time.Now()\n\t)\n\n\terr = fwd.conn.SetWriteDeadline(now.Add(5 * time.Second))\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(`%s: SetWriteDeadline: %s`, logp, err)\n\t}\n\n\t_, err = fwd.conn.Write(b)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(`%s: %s`, logp, err)\n\t}\n\n\treturn n, nil\n}", "func (c *minecraftConn) flush() (err error) {\n\tdefer func() { c.closeOnErr(err) }()\n\tdeadline := time.Now().Add(time.Millisecond * time.Duration(c.config().ConnectionTimeout))\n\tif err = c.c.SetWriteDeadline(deadline); err != nil {\n\t\t// Handle err in case the connection is\n\t\t// already closed and can't write to.\n\t\treturn err\n\t}\n\t// Must flush in sync with encoder or we may get an\n\t// io.ErrShortWrite when flushing while encoder is already writing.\n\treturn c.encoder.Sync(c.writeBuf.Flush)\n}", "func (c *TCPConn) CloseWrite() error {\n\tif !c.ok() {\n\t\treturn syscall.EINVAL\n\t}\n\treturn c.fd.closeWrite()\n}", "func (c *conn) Write(data []byte) (n int, err error) {\n\treq := &client.Packet{\n\t\tType: client.PacketType_DATA,\n\t\tPayload: &client.Packet_Data{\n\t\t\tData: &client.Data{\n\t\t\t\tConnectID: c.connID,\n\t\t\t\tData: data,\n\t\t\t},\n\t\t},\n\t}\n\n\tklog.V(5).InfoS(\"[tracing] send req\", \"type\", req.Type)\n\n\terr = c.tunnel.Send(req)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn len(data), err\n}", "func (c *Client) serveWrite() {\n\tfor {\n\t\tmessage, ok := <-c.send\n\t\tif !ok {\n\t\t\tlog.Printf(\"Stopping write goroutine for client %s due to connection close\", c.conn.RemoteAddr())\n\t\t\tbreak\n\t\t}\n\t\terr := c.conn.WriteMessage(websocket.TextMessage, message)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error writing message: %s\", message)\n\t\t}\n\t}\n}", "func (ctn *Connection) Write(buf []byte) (total int, aerr Error) {\n\tvar err error\n\n\t// make sure all bytes are written\n\t// Don't worry about the loop, timeout has been set elsewhere\n\tif err = ctn.updateDeadline(); err == nil {\n\t\tif total, err = ctn.conn.Write(buf); err == nil {\n\t\t\treturn total, nil\n\t\t}\n\n\t\t// If all bytes are written, ignore any potential error\n\t\t// The error will bubble up on the next network io if it matters.\n\t\tif total == len(buf) {\n\t\t\treturn total, nil\n\t\t}\n\t}\n\n\taerr = chainErrors(errToAerospikeErr(ctn, err), aerr)\n\n\tif ctn.node != nil {\n\t\tctn.node.incrErrorCount()\n\t\tatomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1)\n\t}\n\n\tctn.Close()\n\n\treturn total, aerr\n}", "func writeLoop(conn Connection, finish *sync.WaitGroup) {\n defer func() {\n if p := recover(); p != nil {\n holmes.Error(\"panics: %v\", p)\n }\n // write all pending messages before close\n for packet := range conn.GetMessageSendChannel() {\n if packet != nil {\n if _, err := conn.GetRawConn().Write(packet); err != nil {\n holmes.Error(\"Error writing data %v\", err)\n }\n }\n }\n finish.Done()\n conn.Close()\n }()\n\n for conn.IsRunning() {\n select {\n case <-conn.GetCloseChannel():\n return\n\n case packet := <-conn.GetMessageSendChannel():\n if packet != nil {\n if _, err := conn.GetRawConn().Write(packet); err != nil {\n holmes.Error(\"Error writing data %v\", err)\n return\n }\n }\n }\n }\n}", "func (s *SRTOutbound) Write(data []byte) (int, error) {\n\ts.channelsMux.Lock()\n\tfor addr, c := range s.channels {\n\t\tselect {\n\t\tcase c <- data:\n\t\tdefault:\n\t\t\ts.logger.WithFields(log.Fields{\"addr\": addr}).Warn(\"Connection blocked\")\n\t\t}\n\t}\n\ts.channelsMux.Unlock()\n\treturn len(data), nil\n}", "func (bc BufConn) Write(p []byte) (int, error) {\n\tif bc.IgnoreWrite {\n\t\treturn len(p), nil\n\t}\n\tif bc.OnWrite != nil {\n\t\tbc.OnWrite(p)\n\t\treturn len(p), nil\n\t}\n\treturn bc.Buf.Write(p)\n}", "func (c *minecraftConn) Write(payload []byte) (err error) {\n\tif c.Closed() {\n\t\treturn ErrClosedConn\n\t}\n\tdefer func() { c.closeOnErr(err) }()\n\tif _, err = c.encoder.Write(payload); err != nil {\n\t\treturn err\n\t}\n\treturn c.flush()\n}", "func (e *Encoder) write(p []byte) error {\n\tn, err := e.w.Write(p)\n\tif n != len(p) && err == nil {\n\t\treturn io.ErrShortWrite\n\t}\n\treturn err\n}", "func (c *minecraftConn) close() error {\n\treturn c.closeKnown(true)\n}", "func (sh *Shell) write(line []byte, timeout time.Duration) (err error) {\n\n\t// Channel controls\n\tdone := make(chan struct{})\n\terrWrite := make(chan error, 1)\n\n\t// Asynchronous, timed writing\n\tgo func() {\n\t\tdefer close(done)\n\t\tilength, err := sh.Stream.Write([]byte(line))\n\t\tif ilength != len(line) {\n\t\t\tsh.Log.Warnf(\"length of bytes written to stream and returned\"+\n\t\t\t\t\" output length don't match: sendt:%d != returned:%d\", len(line), ilength)\n\t\t} else if err != nil {\n\t\t\terrWrite <- err\n\t\t}\n\t}()\n\n\t// Handle errors and timeouts\n\tselect {\n\tcase err := <-errWrite:\n\t\treturn err\n\tcase <-time.After(timeout):\n\t\treturn errors.New(\"write operation timed out\")\n\tcase <-done:\n\t\tsh.Log.Debugf(\"Done writing line: %s\", line)\n\t\treturn nil\n\t}\n}", "func (rc *OneByteWriteConn) Close() error {\n\treturn rc.conn.Close()\n}", "func (ch *clientSecureChannel) Write(p []byte) (int, error) {\n\treturn ch.conn.Write(p)\n}", "func (c *Conn) Write(b []byte) (written int, err error) {\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\terr = tryAgain\n\tfor err == tryAgain {\n\t\tn, errcb := c.write(b)\n\t\terr = c.handleError(errcb)\n\t\tif err == nil {\n\t\t\treturn n, c.flushOutputBuffer()\n\t\t}\n\t}\n\treturn 0, err\n}", "func (s *Conn) Write(b []byte) (int, error) {\n\tnow := s.timeFn()\n\tn := 0\n\tfor n < len(b) {\n\t\tif s.state >= stateDraining {\n\t\t\t// Closing\n\t\t\tbreak\n\t\t}\n\t\ti, err := s.recv(b[n:], now)\n\t\tn += i\n\t\t// Keep track bytes received from peer to limit bytes sending back\n\t\t// until its address is verified.\n\t\ts.recvPackets++\n\t\ts.recvBytes += uint64(i)\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\t}\n\tif n == 0 || !s.handshakeConfirmed {\n\t\t// Check probe timeout when the connection does not receive anything or\n\t\t// during handshake where there are multiple packet number spaces.\n\t\t// FIXME: What if peer does not send ACK?\n\t\ts.checkTimeout(now)\n\t}\n\treturn n, nil\n}", "func (s *session) Write(w pdu.Body) error {\n\treturn s.conn.Write(w)\n}", "func (w *Worker) write() {\n\tvar id = w.ID\n\n\tw.Swarm.Logchan.Info <- \"Worker [\" + id + \"] started listening to write channel.\"\n\nloop:\n\tfor {\n\t\tw.Swarm.Logchan.Info <- \"Worker [\" + id + \"] listening to write...\"\n\t\tselect {\n\t\tcase <-w.killedWrite:\n\t\t\tbreak loop\n\n\t\tcase data := <-w.WriteData:\n\t\t\tw.Swarm.Logchan.Message <- string(log.NewMessage(id, data, false).JSON())\n\t\t\tw.Writer.WriteString(data)\n\t\t\tw.Writer.Flush()\n\t\t}\n\t}\n\n\tw.Swarm.Logchan.Info <- \"Worker [\" + id + \"] write channel closed.\"\n}", "func (c *conn) submitWrite(b []byte) bool {\n\tc.closingMutex.RLock()\n\tdefer c.closingMutex.RUnlock()\n\tif c.closing {\n\t\treturn false\n\t} else {\n\t\tincrement(&blockedOnWrite)\n\t\tc.writeRequestsCh <- b\n\t\treturn true\n\t}\n}", "func (c *conn) put(b []byte) (err error) {\n\t// Let's ensure our connection is not closed or idle\n\tswitch c.state {\n\tcase stateClosed:\n\t\treturn errors.ErrIsClosed\n\tcase stateIdle:\n\t\treturn ErrIsIdle\n\t}\n\n\tblen := uint64(len(b))\n\tif blen < noCopySize {\n\t\treturn c.smallWrite(b, blen)\n\t}\n\n\treturn c.largeWrite(b, blen)\n\n}", "func (l *lazyConn) Write(p []byte) (n int, err error) {\n\tl.m.Lock()\n\tdefer l.m.Unlock()\n\n\tif l.conn == nil {\n\t\tif err := l.connect(); err != nil {\n\t\t\treturn 0, io.ErrClosedPipe\n\t\t}\n\t}\n\n\tn, err = l.withTimeout().Write(p)\n\tif n == 0 && err != io.ErrClosedPipe {\n\t\tl.conn = nil\n\t}\n\treturn n, err\n}", "func (c *conn) closeWriteAndWait() {\n\tc.finalFlush()\n\tif tcp, ok := c.rwc.(closeWriter); ok {\n\t\ttcp.CloseWrite()\n\t}\n\ttime.Sleep(rstAvoidanceDelay)\n}", "func (cw *chanWriter) Write(b []byte) (int, error) {\n cw.downstream <- b\n\n return len(b), nil\n}", "func TcpServerWriter(conn net.Conn){\n writer:= bufio.NewWriter(conn) // makes a new writer for port\n\n for {\n select{\n case values := <- passServer :{\n if (values != \"close\"){\n writer.WriteString(values +\"\\n\") //write string to port\n writer.Flush() // clear the buffer\n } else if (values == \"close\"){ // if reading error is found then close the connection\n conn.Close() // closes the connection\n indicator = 0 // server DISCONNECTED\n return\n }\n }\n }\n }\n}", "func (c *Conn) writeWithRetry(p []byte, timeout time.Duration) (n int, err error) {\n\tvar retryDelay = time.Microsecond\n\n\tc.SetWriteDeadline(time.Now().Add(timeout))\n\tn, err = c.write(p)\n\tfor err != nil {\n\t\te, ok := err.(net.Error)\n\t\tif ok && e.Timeout() {\n\t\t\tc.setClose(Policy, \"write timeout\")\n\t\t\treturn\n\t\t}\n\t\tif !ok || !e.Temporary() {\n\t\t\treturn\n\t\t}\n\n\t\ttime.Sleep(retryDelay)\n\t\tif retryDelay < time.Second {\n\t\t\tretryDelay *= 2\n\t\t}\n\n\t\tvar more int\n\t\tmore, err = c.write(p[n:])\n\t\tn += more\n\t}\n\n\treturn\n}", "func (dc *DebugConn) Write(p []byte) (int, error) {\n\tif dc.isClosed() {\n\t\treturn 0, ErrClosed\n\t}\n\n\tn, err := dc.Conn.Write(p)\n\n\tif dc.writeDebug != nil {\n\t\tdc.readDebug(dc.logger, false, dc.isClient, dc.id, p, n, err)\n\t}\n\n\treturn n, err\n}", "func (t *tcp) close() error {\n\tif !t.isopen {\n\t\treturn nil\n\t}\n\tt.isopen = false\n\t// closing this channel means that anyone readong from the channel is auto-selected in a Select statement\n\tclose(t.closed)\n\tt.conn.Close()\n\treturn nil\n}", "func (c *Client) Write(data []byte) (err error) {\n\tif c.conn == nil {\n\t\treturn errors.New(\"connection is not defined\")\n\t}\n\n\tif c.crypto != nil {\n\t\tdata, err = c.crypto.Encrypt(data)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to encrypt data\")\n\t\t}\n\t}\n\n\tdataLen := uint32(len(data))\n\n\terr = binary.Write(c.conn, binary.LittleEndian, dataLen)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to write data len\")\n\t}\n\n\terr = binary.Write(c.conn, binary.LittleEndian, Magic)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to write magic\")\n\t}\n\n\tn, err := c.conn.Write(data)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to write data\")\n\t}\n\n\tif uint32(n) != dataLen {\n\t\treturn errors.Wrap(err, \"data wasn't fully sent\")\n\t}\n\n\treturn nil\n}", "func (c *WSClient) writeRoutine(ctx context.Context) {\n\tvar ticker *time.Ticker\n\tif c.pingPeriod > 0 {\n\t\t// ticker with a predefined period\n\t\tticker = time.NewTicker(c.pingPeriod)\n\t} else {\n\t\t// ticker that never fires\n\t\tticker = &time.Ticker{C: make(<-chan time.Time)}\n\t}\n\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t\tc.wg.Done()\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase request := <-c.send:\n\t\t\tif c.writeWait > 0 {\n\t\t\t\tif err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {\n\t\t\t\t\tc.Logger.Error(\"failed to set write deadline\", \"err\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err := c.conn.WriteJSON(request); err != nil {\n\t\t\t\tc.Logger.Error(\"failed to send request\", \"err\", err)\n\t\t\t\tc.reconnectAfter <- err\n\t\t\t\t// add request to the backlog, so we don't lose it\n\t\t\t\tc.backlog <- request\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tif c.writeWait > 0 {\n\t\t\t\tif err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {\n\t\t\t\t\tc.Logger.Error(\"failed to set write deadline\", \"err\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {\n\t\t\t\tc.Logger.Error(\"failed to write ping\", \"err\", err)\n\t\t\t\tc.reconnectAfter <- err\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-c.readRoutineQuit:\n\t\t\treturn\n\t\tcase <-ctx.Done():\n\t\t\tif err := c.conn.WriteMessage(\n\t\t\t\twebsocket.CloseMessage,\n\t\t\t\twebsocket.FormatCloseMessage(websocket.CloseNormalClosure, \"\"),\n\t\t\t); err != nil {\n\t\t\t\tc.Logger.Error(\"failed to write message\", \"err\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}", "func (n *NetConn) Write([]byte) (numBytes int, err error) {\n\treturn 1, n.errOnWrite\n}", "func (c *Conn) Write(buf []byte) (int, error) {\n\tc.WriteToHash(buf)\n\treturn c.w.Write(buf)\n}", "func (c *Conn) Close() error {\n\tif c.closed {\n\t\treturn nil\n\t}\n\tc.closed = true\n\n\t// Flush any remaining data to be written.\n\terr := c.Flush()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = c.closeFlushFunc()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx := context.Background()\n\tif !c.stanzaWriter.writeDeadline.IsZero() {\n\t\tvar cancel context.CancelFunc\n\t\tctx, cancel = context.WithDeadline(ctx, c.stanzaWriter.writeDeadline)\n\t\tdefer cancel()\n\t}\n\trespReadCloser, err := c.s.SendIQElement(ctx, closePayload(c.stanzaWriter.sid), stanza.IQ{\n\t\tTo: c.stanzaWriter.to,\n\t\tType: stanza.SetIQ,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tclose(c.readReady)\n\treturn respReadCloser.Close()\n}", "func (conn *extHost) stopWrite(drainTimeout time.Duration) error {\n\tconn.lk.Lock()\n\tstopped := conn.stopWritePump()\n\tconn.lk.Unlock()\n\tif stopped {\n\t\tconn.waitForDrain(drainTimeout)\n\t}\n\treturn nil\n}", "func (std *ReaderService) Write(in <-chan []byte) error {\n\treturn ErrNotSupported\n}", "func (ctx *storyReadCtx) writeShutdown() {\n\tvar log = ctx.logger.Info().\n\t\tStr(\"story\", ctx.story).\n\t\tUint64(\"connId\", ctx.httpCtx.ConnID())\n\tvar msg strings.Builder\n\tmsgId := ctx.uuidSupplier()\n\tmsg.WriteString(\"id: \")\n\tmsg.WriteString(msgId)\n\tmsg.WriteString(\"\\nevent: shutdown\\ndata: 0\\n\\n\")\n\tlog.Msg(\"Closing connection\")\n\tif ctx.httpWriter != nil {\n\t\tctx.httpWriter.WriteString(msg.String())\n\t}\n}", "func (conn *Conn) Write(b []byte) (n int, err error) {\n\terr = conn.Handler.WriteMessage(conn.FrameType, b)\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn len(b), nil\n}" ]
[ "0.76194173", "0.7471342", "0.73997265", "0.72639143", "0.72639143", "0.7225192", "0.71538943", "0.71193266", "0.7019101", "0.69907564", "0.6952195", "0.6934218", "0.67729527", "0.67097056", "0.6698059", "0.66804695", "0.6639902", "0.66116256", "0.6572542", "0.65663767", "0.6536888", "0.65316015", "0.6515369", "0.65136755", "0.65034026", "0.6487505", "0.64795315", "0.64400405", "0.6388115", "0.6365688", "0.6346067", "0.6333175", "0.6322168", "0.63152766", "0.6314631", "0.6306572", "0.6297036", "0.6290612", "0.6282069", "0.62583065", "0.6252495", "0.6247972", "0.62473816", "0.62373006", "0.6232948", "0.6224066", "0.61934423", "0.61635995", "0.61576784", "0.6135266", "0.60958534", "0.6065349", "0.60294664", "0.6028289", "0.6017652", "0.59920126", "0.5991082", "0.5982732", "0.5982588", "0.5981592", "0.5977038", "0.5974962", "0.5972472", "0.59662527", "0.5964732", "0.5959177", "0.59555334", "0.5955487", "0.59464675", "0.5941868", "0.5936486", "0.59353524", "0.592932", "0.59100664", "0.5902867", "0.59016216", "0.5900949", "0.58910406", "0.5862141", "0.5860095", "0.58493835", "0.584324", "0.5832713", "0.58247626", "0.577486", "0.57565725", "0.5755683", "0.5754998", "0.5746209", "0.5735273", "0.572944", "0.57276875", "0.57217425", "0.57175636", "0.57158136", "0.57148534", "0.5711076", "0.5702148", "0.5700998", "0.5700223" ]
0.76070374
1
close closes the connection.
func (c *context) close() error { if c.Protocol != protocolUDP { return c.conn.Close() } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Conn) Close() error { return nil }", "func (self *Client) close() {\n\t// TODO: Cleanly close connection to remote\n}", "func (c *minecraftConn) close() error {\n\treturn c.closeKnown(true)\n}", "func (c *client) Close() error { return c.c.Close() }", "func (this *Connection) close() {\n\tif kConnStatus_Connected != this.status {\n\t\treturn\n\t}\n\n\tthis.conn.Close()\n\tthis.status = kConnStatus_Disconnected\n}", "func (mb *tcpTransporter) close() (err error) {\n\tif mb.conn != nil {\n\t\terr = mb.conn.Close()\n\t\tmb.conn = nil\n\t}\n\treturn\n}", "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 (b *BIRDClient) Close() error { return b.conn.Close() }", "func (c *Client) Close() {}", "func (c *Client) Close() {}", "func (c *Conn) Close() error { return c.pc.Close() }", "func (bc BufConn) Close() error { return nil }", "func (c *conn) close(err error) {\n\tc.l.Debugf(\"close livereload socket with error: %s\", err)\n\tc.closer.Do(func() {\n\t\tc.l.Debugf(\"actually closing livereload socket\")\n\t\tcloseCode := websocket.CloseInternalServerErr\n\t\tif closeErr, ok := err.(*websocket.CloseError); ok {\n\t\t\tcloseCode = closeErr.Code\n\t\t}\n\n\t\tmsg := err.Error()\n\t\tcloseMsg := websocket.FormatCloseMessage(closeCode, msg)\n\t\tdeadline := time.Now().Add(time.Second)\n\n\t\twriteErr := c.ws.WriteControl(websocket.CloseMessage, closeMsg, deadline)\n\t\tif writeErr != nil && !errors.Is(writeErr, websocket.ErrCloseSent) {\n\t\t\tc.l.Debugf(\"failed to write websocket close message: %s\", writeErr)\n\t\t}\n\t\tcloseErr := c.ws.Close()\n\t\tif closeErr != nil {\n\t\t\tc.l.Errorf(\"failed to close websocket: :%s\", closeErr)\n\t\t}\n\t\tclose(c.send)\n\t})\n}", "func (rw *NopConn) Close() error { return nil }", "func (t *tcp) close() error {\n\tif !t.isopen {\n\t\treturn nil\n\t}\n\tt.isopen = false\n\t// closing this channel means that anyone readong from the channel is auto-selected in a Select statement\n\tclose(t.closed)\n\tt.conn.Close()\n\treturn nil\n}", "func ConnClose(c *tls.Conn,) error", "func (c *Conn) close() {\n\tc.evaction = evio.Close\n\tc.wake()\n}", "func (c *TestConnection) Close() error {\n if c.CloseError != nil {\n return c.CloseError\n }\n \n c.Closed = true\n return nil\n}", "func (clt *client) close() {\n\t// Apply exclusive lock\n\tclt.statusLock.Lock()\n\n\tif clt.status != StatusConnected {\n\t\tclt.status = StatusDisabled\n\t\tclt.statusLock.Unlock()\n\t\treturn\n\t}\n\tclt.status = StatusDisabled\n\tclt.statusLock.Unlock()\n\n\tif err := clt.conn.Close(); err != nil {\n\t\tclt.options.ErrorLog.Printf(\"Failed closing connection: %s\", err)\n\t}\n\n\t// Wait for the reader goroutine to die before returning\n\t<-clt.readerClosing\n}", "func (c *client) close() {\n\tc.leave()\n\tc.Conn.Close()\n\tc.Message <- \"/quit\"\n}", "func Close() {\n\tconn.Close()\n}", "func (c *Client) close(reason string) (err error) {\n\tc.closer.Do(func() {\n\t\tif reason != \"\" {\n\t\t\tc.Logln(LogConn, \"Close reason:\", reason)\n\t\t}\n\t\tif err = c.t.Close(false); err != nil {\n\t\t\tc.Logln(LogConn, \"Close error:\", err)\n\t\t}\n\t})\n\treturn\n}", "func (c *conn) Close() error {\n\treturn c.s.Close()\n}", "func (c *Client) close(err error) error {\n\tif c.session == nil {\n\t\treturn nil\n\t}\n\treturn c.session.Close(err)\n}", "func (c *client) close() {\n\tc.user.Close()\n\tc.conn.Close()\n\n\tc.sysConn.Exec(\"DROP DATABASE IF EXISTS \" + c.connConfig.Database)\n\tc.sysConn.Close()\n}", "func (c *Conn) closed() {\n\tc.done = true\n}", "func (c *SodaClient) Close() {\n\tc.conn.Close()\n}", "func (c *UDPClientProvider) close() error {\n\tc.quit <- true\n\tc.conn.Close()\n\treturn nil\n}", "func (r ResourceConn) Close() {\n\tr.Conn.Close()\n}", "func (r *Connection) Close() {\n\t// no-op\n}", "func (v *connection) Close() error {\n\tconnectionLogger.Trace(\"connection.Close()\")\n\n\tv.sendMessage(&msgs.FETerminateMsg{})\n\n\tvar result error = nil\n\n\tif v.conn != nil {\n\t\tresult = v.conn.Close()\n\t\tv.conn = nil\n\t}\n\n\treturn result\n}", "func (c *Client) Close() { c.streamLayer.Close() }", "func (c *Client) Close() {\n}", "func (c *Client) Close() {\n}", "func (t *Client) Close() error { return nil }", "func (st *fakeConn) Close() {\n}", "func (c Connection) Close() error {\n\tpanic(\"TODO\")\n}", "func (c *CryptoStreamConn) Close() error {\n\treturn nil\n}", "func (c *conn) Close() error {\n\tif atomic.CompareAndSwapInt32(&c.closed, 0, 1) {\n\t\tc.log(\"close connection\", c.url.Scheme, c.url.Host, c.url.Path)\n\t\tcancel := c.cancel\n\t\ttransport := c.transport\n\t\tc.transport = nil\n\t\tc.cancel = nil\n\n\t\tif cancel != nil {\n\t\t\tcancel()\n\t\t}\n\t\tif transport != nil {\n\t\t\ttransport.CloseIdleConnections()\n\t\t}\n\t}\n\treturn nil\n}", "func (c *connection) Close() {\n\tbaseurl := \"http://fritz.box/webservices/homeautoswitch.lua\"\n\tparameters := make(map[string]string)\n\tparameters[\"sid\"] = c.sid\n\tparameters[\"logout\"] = \"logout\"\n\tUrl := prepareRequest(baseurl, parameters)\n\tsendRequest(Url)\n}", "func (s *Server) CloseConnection() {}", "func (c *Client) Close() {\n\t_ = c.conn.Close()\n}", "func (c *ManetConnection) Close() {\n\tc.conn.Close()\n}", "func (rc *OneByteWriteConn) Close() error {\n\treturn rc.conn.Close()\n}", "func (c *Connection) Close() {\n\tc.conn.Close()\n}", "func (runner *statementRunner) closeConnection() error {\n\tif runner.connection != nil {\n\t\trunner.lastBookmark = runner.connection.LastBookmark()\n\n\t\terr := runner.connection.Close()\n\t\trunner.connection = nil\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Connector) Close() {\n\tc.conn.Close()\n\tclose(c.die)\n}", "func (self *SQL_Client) Close() {\n\tself.cc.Close()\n}", "func (c *Conn) Close(ctx context.Context) error {\n\treturn c.redfishwrapper.Close(ctx)\n}", "func (r *ResourceConn) Close() {\n\tr.ClientConn.Close()\n}", "func (c *connect) closeConn() {\n\n\tif c.stream != nil {\n\t\tif err := c.stream.CloseSend(); err != nil {\n\t\t\tlog.Fatalf(\"Can't close stream: %v\\n\", err)\n\t\t}\n\n\t\tif err := c.connect.Close(); err != nil {\n\t\t\tlog.Fatalf(\"Can't disconnect to the server.\\n\")\n\t\t}\n\t\tc.client = nil\n\t}\n}", "func (c *Conn) Close() error {\n\treturn nil // TODO(TimSatke): implement\n}", "func (conn *Connection) Close() error {\n\tconn.connected = false\n\treturn nil\n}", "func (c *Connection) Close() error { return c.pump.Close() }", "func (r *Response) Close() error {\n\treturn r.conn.Close()\n}", "func (replayer *replayer) closeConnection(ctx context.Context) {\n\t// Call Shutdown RCP on the replayer\n\tif replayer.rpcClient != nil {\n\t\t// Use a clean context, since ctx is most likely already cancelled.\n\t\tsdCtx := attachAuthToken(context.Background(), replayer.deviceConnectionInfo.authToken)\n\t\t_, err := replayer.rpcClient.Shutdown(sdCtx, &replaysrv.ShutdownRequest{})\n\t\tif err != nil {\n\t\t\tlog.E(ctx, \"Sending replayer Shutdown request: %v\", err)\n\t\t}\n\t}\n\treplayer.rpcClient = nil\n\n\tif replayer.rpcStream != nil {\n\t\treplayer.rpcStream.CloseSend()\n\t}\n\treplayer.rpcStream = nil\n\n\tif replayer.conn != nil {\n\t\treplayer.conn.Close()\n\t}\n\treplayer.conn = nil\n\n\treplayer.deviceConnectionInfo.cleanupFunc()\n}", "func (cs *connset) close() {\n\tcs.m.Range(func(_, value any) bool {\n\t\tlookErr(value.(Conn).Close())\n\t\treturn true\n\t})\n}", "func (r *client) Close() error {\n\treturn r.conn.Close()\n}", "func (s *session) Close() error {\n\treturn s.conn.Close()\n}", "func (ts *Stream) Close() error {\n\tif ts.err != nil {\n\t\treturn ts.err\n\t}\n\treturn ts.conn.Close()\n}", "func (gc *GokuyamaClient) Close() error {\n\tvar err error\n\terr = gc.conn.Close()\n\treturn err\n}", "func (j *JSONWebsocketCodec) Close() error {\n\treturn j.conn.Close()\n}", "func (s *server) close() error {\n\treturn s.ln.Close()\n}", "func (cl *Client) Close() (err error) {\n\tcl.url = nil\n\treturn cl.conn.Close()\n}", "func (c *Connection) Close() error {\n\trerr := c.ReadCloser.Close()\n\twerr := c.WriteCloser.Close()\n\tif rerr != nil {\n\t\treturn rerr\n\t}\n\treturn werr\n}", "func (c *baseConn) Close() error {\n\treturn c.c.Close()\n}", "func (c *Conn) Close() error {\n\t// Resets client\n\tc.client = nil\n\treturn nil\n}", "func (c *Connection) Close() error {\n\tc.identity = nil\n\tif c.clientConn != nil {\n\t\terr := c.clientConn.Close()\n\t\tc.clientConn = nil\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *Session) close(ctx context.Context) error {\n\treturn s.doSession(ctx, func(ctx context.Context, conn *grpc.ClientConn, header *headers.RequestHeader) (*headers.ResponseHeader, interface{}, error) {\n\t\trequest := &api.CloseSessionRequest{\n\t\t\tHeader: header,\n\t\t}\n\t\tclient := api.NewSessionServiceClient(conn)\n\t\tresponse, err := client.CloseSession(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\treturn response.Header, response, nil\n\t})\n}", "func (f *fetcher) Close() error {\n\treturn f.conn.Close()\n}", "func (c *RuntimeSecurityClient) Close() {\n\tc.conn.Close()\n}", "func (c *NOOPConnection) Close() {\n}", "func (r *response) Close() error {\n\terr := r.conn.Close()\n\t_, _, err2 := r.c.conn.ReadResponse(StatusClosingDataConnection)\n\tif err2 != nil {\n\t\terr = err2\n\t}\n\treturn err\n}", "func (rc *OneByteReadConn) Close() error {\n\treturn rc.conn.Close()\n}", "func (conn *Conn) Close() {\n\tconn.conn.Close()\n}", "func (rd *RemoteDB) Close() {\n}", "func (conn *Connection) close(force bool) error {\n\tconn.l.Lock()\n\tdefer conn.l.Unlock()\n\n\tif !force && conn.numOpenedChannel > 0 {\n\t\treturn ErrChannelNotAllClosed\n\t}\n\n\tif conn.conn != nil {\n\t\terr := conn.conn.Close()\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"Connection.close: %s\\n\", err)\n\t\t}\n\t}\n\tconn.conn = nil\n\treturn nil\n}", "func (p *Conn) Close() error {\n\treturn p.conn.Close()\n}", "func (r *repository) Close() {\n\tr.conn.Close()\n}", "func (c *Conn) Close() {\n\tc.conn.Close()\n}", "func closeConnection(c net.Conn) {\n\tif nil != c {\n\t\tc.Close()\n\t}\n}", "func (mconn *MConn) close() {\n\tclose(mconn.interrupter)\n\tclose(mconn.smonitor)\n\tmconn.bindWaitGroup.Done()\n\n\t// notify the connection is closed\n\tmconn.notify(connectionClosed{mconn.connId})\n}", "func (i ios) Close(ctx context.Context) error {\n\ti.Connection.Close(ctx)\n\n\treturn nil\n}", "func (c *conn) close() (err error) {\n\tc.mux.Lock()\n\tdefer c.mux.Unlock()\n\n\tif c.state == stateClosed {\n\t\t// conn is already closed\n\t\treturn errors.ErrIsClosed\n\t}\n\n\tc.state = stateClosed\n\treturn\n}", "func (hd *hostDownloader) Close() error {\n\t// don't care about these errors\n\t_, _ = verifySettings(hd.conn, hd.host, hd.contractor.hdb)\n\t_ = modules.WriteNegotiationStop(hd.conn)\n\treturn hd.conn.Close()\n}", "func (conn *WSConnection) Close() error {\n\treturn conn.conn.Close()\n}", "func (s *server) close() error {\n\treturn s.server.Close()\n}", "func (c *Client) Close() {\n\tc.conn.Close()\n}", "func (c *Client) Close() {\n\tc.conn.Close()\n}", "func (c *Client) Close() {\n\tc.conn.Close()\n}", "func (c *Client) Close() {\n\tc.conn.Close()\n}", "func (c *Client) Close() {\n\tc.conn.Close()\n}", "func (c *Client) Close() {\n\tc.conn.Close()\n}", "func (c *minecraftConn) closeWith(packet proto.Packet) (err error) {\n\tif c.Closed() {\n\t\treturn ErrClosedConn\n\t}\n\tdefer func() {\n\t\terr = c.close()\n\t}()\n\n\t//c.mu.Lock()\n\t//p := c.protocol\n\t//s := c.state\n\t//c.mu.Unlock()\n\n\t//is18 := p.GreaterEqual(proto.Minecraft_1_8)\n\t//isLegacyPing := s == state.Handshake || s == state.Status\n\t//if is18 || isLegacyPing {\n\tc.knownDisconnect.Store(true)\n\t_ = c.WritePacket(packet)\n\t//} else {\n\t// ??? 1.7.x versions have a race condition with switching protocol versions,\n\t// so just explicitly close the connection after a short while.\n\t// c.setAutoReading(false)\n\t//go func() {\n\t//\ttime.Sleep(time.Millisecond * 250)\n\t//\tc.knownDisconnect.Store(true)\n\t//\t_ = c.WritePacket(packet)\n\t//}()\n\t//}\n\treturn\n}", "func (w *reply) Close() (err error) {\n\treturn w.conn.Close()\n}", "func (c *Conn) Close() {\n\tc.c.Close()\n}", "func (p *packetConn) Close() error {\n\treturn ErrNotImplemented\n}", "func (c *resultsConn) Close() error {\n\treturn c.c.Close()\n}", "func (cha *Channel) close() {\n\t// not care about channel close error, because it's the client action\n\tcha.cha.Close()\n\n\tcha.conn.decrNumOpenedChannel()\n\tcha.cha = nil\n\tcha.conn = nil\n}", "func (gw *Gateway) Close() error {\n\treturn gw.conn.Close()\n}" ]
[ "0.7299285", "0.7268717", "0.720415", "0.691512", "0.68707407", "0.6851059", "0.6849651", "0.68028086", "0.6764501", "0.6764501", "0.67074233", "0.66832507", "0.6660245", "0.6645073", "0.6637454", "0.66290194", "0.66056883", "0.65101445", "0.64646", "0.64549863", "0.6434904", "0.6424228", "0.64236295", "0.641696", "0.6406933", "0.6399805", "0.6394342", "0.6386739", "0.6353974", "0.63469195", "0.6346045", "0.63428026", "0.63342136", "0.63342136", "0.632769", "0.63237196", "0.6318493", "0.63078463", "0.63064975", "0.63013476", "0.629312", "0.6289918", "0.6267256", "0.6266032", "0.6243536", "0.62318575", "0.6227913", "0.62206805", "0.61944765", "0.61932975", "0.61781514", "0.61717343", "0.61705035", "0.61602515", "0.6159705", "0.6158881", "0.61541456", "0.61519295", "0.61507237", "0.61427873", "0.6132079", "0.6118569", "0.6114911", "0.6107499", "0.6105919", "0.61046326", "0.61044323", "0.6097179", "0.60961866", "0.60960937", "0.60942256", "0.60850835", "0.6080935", "0.60745287", "0.6073525", "0.6052841", "0.605033", "0.60479677", "0.6043133", "0.6041468", "0.6034323", "0.602663", "0.6010067", "0.60094607", "0.6002786", "0.5998806", "0.59874564", "0.5984602", "0.5984602", "0.5984602", "0.5984602", "0.5984602", "0.5984602", "0.59804595", "0.5975323", "0.59711933", "0.59696245", "0.59693086", "0.59645456", "0.5963128" ]
0.6431226
21
Write writes a response to the connection.
func (c *context) Write(res Response) error { data, err := json.Marshal(res) if err != nil { return err } return c.write(data) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Response) Write(w io.Writer) error", "func (r *response) Write(b []byte) (int, error) {\n\tr.wrote = true\n\treturn r.rw.Write(b)\n}", "func (cr ConnectResponse) Write(connWriter *bufio.Writer) error {\n\n\terr := connWriter.WriteByte(cr.Ver)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = connWriter.WriteByte(cr.Method)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn connWriter.Flush()\n}", "func (res *Response) Write(p []byte) (n int, err error) {\n\treturn res.c.Write(p)\n}", "func (r *Response) Write(data []byte) (int, error) {\n\treturn r.rw.Write(data)\n}", "func (r *Response) Write(b []byte) (int, error) {\n\treturn r.Writer.Write(b)\n}", "func (w *responseWriter) Write(p []byte) (int, error) {\n\tw.started = true\n\treturn w.writer.Write(p)\n}", "func (w *responseWriter) Write(p []byte) (int, error) {\n\tw.started = true\n\treturn w.writer.Write(p)\n}", "func (w *responseWrapper) Write(p []byte) (int, error) {\n\treturn w.buffer.Write(p)\n}", "func (w *responseWriter) Write(b []byte) (int, error) {\n\tif w.Status == 0 {\n\t\tw.Status = 200\n\t}\n\tn, err := w.ResponseWriter.Write(b)\n\tw.Length += n\n\treturn n, err\n}", "func (r *Response) Write(p []byte) (int, error) {\n\tr.Started = true\n\treturn r.ResponseWriter.Write(p)\n}", "func (j *JSendWriterBuffer) Write(b []byte) (int, error) {\n\treturn j.responseWriter.Write(b)\n}", "func (r *ResponseReverter) Write(buf []byte) (int, error) {\n\tn, err := r.ResponseWriter.Write(buf)\n\treturn n, err\n}", "func (r *response) Write(b []byte) (n int, err error) {\n\tif !r.headersSend {\n\t\tif r.status == 0 {\n\t\t\tr.status = http.StatusOK\n\t\t}\n\t\tr.WriteHeader(r.status)\n\t}\n\tn, err = r.ResponseWriter.Write(b)\n\tr.size += int64(n)\n\treturn\n}", "func (rw *responseWriter) Write(b []byte) (int, error) {\n\tn, err := rw.ResponseWriter.Write(b)\n\trw.written += n\n\n\treturn n, err\n}", "func (w *responseWriter) Write(data []byte) (int, error) {\n\tn, err := w.ResponseWriter.Write(data)\n\tif w.resp.StatusCode == 0 {\n\t\tw.resp.StatusCode = http.StatusOK\n\t}\n\treturn n, err\n}", "func (c *Operation) writeResponse(rw http.ResponseWriter, status int, data []byte) { // nolint: unparam\n\trw.WriteHeader(status)\n\n\tif _, err := rw.Write(data); err != nil {\n\t\tlogger.Errorf(\"Unable to send error message, %s\", err)\n\t}\n}", "func (w *responseWriter) Write(data []byte) (int, error) {\n\tif w.status == 0 {\n\t\tw.status = http.StatusOK\n\t}\n\tsize, err := w.rw.Write(data)\n\tw.size += size\n\treturn size, err\n}", "func (res Responder) Write(p []byte) (int, error) {\n\treturn res.b.Write(p)\n}", "func (rec *responseRecorder) Write(b []byte) (int, error) {\n\treturn rec.body.Write(b)\n}", "func (r *Response) Write(w io.Writer) error {\n\n\t// Status line\n\ttext := r.Status\n\tif text == \"\" {\n\t\tvar ok bool\n\t\ttext, ok = StatusText[r.StatusCode]\n\t\tif !ok {\n\t\t\ttext = \"status code \" + strconv.Itoa(r.StatusCode)\n\t\t}\n\t}\n\tprotoMajor, protoMinor := strconv.Itoa(r.ProtoMajor), strconv.Itoa(r.ProtoMinor)\n\tstatusCode := strconv.Itoa(r.StatusCode) + \" \"\n\ttext = strings.TrimPrefix(text, statusCode)\n\tio.WriteString(w, \"HTTP/\"+protoMajor+\".\"+protoMinor+\" \"+statusCode+text+\"\\r\\n\")\n\n\t// Process Body,ContentLength,Close,Trailer\n\ttw, err := newTransferWriter(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = tw.WriteHeader(w)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Rest of header\n\terr = r.Header.WriteSubset(w, respExcludeHeader)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// End-of-header\n\tio.WriteString(w, \"\\r\\n\")\n\n\t// Write body and trailer\n\t_, err = tw.WriteBody(w)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Success\n\treturn nil\n}", "func (r *responseInfoRecorder) Write(b []byte) (int, error) {\n\tr.ContentLength += int64(len(b))\n\tif r.statusCode == 0 {\n\t\tr.statusCode = http.StatusOK\n\t}\n\treturn r.ResponseWriter.Write(b)\n}", "func (c *WSCodec) Write(res interface{}) error {\n\tresult, err := json.Marshal(res)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.client.SendMessage(result, nil)\n\treturn nil\n}", "func (rl *ResponseLogger) Write(b []byte) (int, error) {\n\t// If no status has been written default to OK\n\tif rl.Status == 0 {\n\t\trl.Status = http.StatusOK\n\t}\n\n\tsize, err := rl.ResponseWriter.Write(b)\n\trl.Length += size\n\treturn size, err\n}", "func (w *WriterHttpConn) Write(b []byte) (n int, err error) {\n\treader := bytes.NewReader(b)\n\treq, err := http.NewRequest(w.Method, w.url.Scheme+\"://\"+w.url.Host+w.url.Path, reader)\n\t//log.Debug(w.url.Scheme+\"://\"+w.url.Host+w.url.Path)\n\tif err != nil {\n\t\tlog.Error(\"Request failed to construct: %s\", err)\n\t\treturn 0, err\n\t}\n\n\tres, err := w.client.Do(req)\n\n\tif err != nil {\n\t\tlog.Error(\"post request failed: `%s`\", err)\n\t\treturn 0, err\n\t}\n\tio.Copy(ioutil.Discard, res.Body)\n\tres.Body.Close()\n\treturn len(b), nil\n}", "func (r *responseWriter) Write(b []byte) (int, error) {\n\tif r.buf == nil {\n\t\treturn 0, ErrReqNotSupp\n\t}\n\tif len(b) > r.buf.Cap()-r.buf.Len() {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\n\treturn r.buf.Write(b)\n}", "func (cr CmdResponse) Write(connWriter *bufio.Writer) error {\n\tvar err error\n\terr = connWriter.WriteByte(cr.Ver)\n\terr = connWriter.WriteByte(cr.Rep)\n\terr = connWriter.WriteByte(cr.Rsv)\n\terr = connWriter.WriteByte(cr.Bnd.Atyp)\n\t_, err = connWriter.Write(cr.Bnd.Ipv4Addr[:])\n\t_, err = connWriter.Write(cr.Bnd.Port[:])\n\terr = connWriter.Flush()\n\treturn err\n}", "func (handler Handler) Write(w http.ResponseWriter, b []byte) (int, error) {\n\treturn w.Write(b)\n}", "func (rw *responseWriter) Write(b []byte) (int, error) {\n\tsize, err := rw.ResponseWriter.Write(b)\n\trw.size += size\n\treturn size, err\n}", "func (w *logResponseWritter) Write(data []byte) (int, error) {\n\n\twritten, err := w.ResponseWriter.Write(data)\n\tw.size += written\n\n\treturn written, err\n}", "func (c *CodecRequest) WriteResponse(w http.ResponseWriter, reply interface{}) {\n\tif c.request.Id != nil {\n\t\t// Id is null for notifications and they don't have a response.\n\t\tres := &serverResponse{\n\t\t\tResult: reply,\n\t\t\tError: &null,\n\t\t\tId: c.request.Id,\n\t\t}\n\t\tc.writeServerResponse(w, 200, res)\n\t}\n}", "func (resp *response) Write(b []byte) (int, error) {\n\tsize, err := resp.ResponseWriter.Write(b)\n\tresp.size += size\n\treturn size, err\n}", "func (req *Request) Write(b []byte) (int, error) {\n\treturn req.res.Write(b)\n}", "func writeResponse(w io.Writer, resp *Response) (n int, err error) {\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(fmt.Sprintf(\"%s %d %s\\r\\n\", resp.protocol, resp.Status, resp.Status.String()))\n\tfor header, value := range resp.Headers {\n\t\tbuffer.WriteString(fmt.Sprintf(\"%s: %s\\r\\n\", header, value))\n\t}\n\tif len(resp.Body) > 0 {\n\t\tbuffer.WriteString(fmt.Sprintf(\"%s: %d\\r\\n\", \"Content-Length\", len(resp.Body)))\n\n\t}\n\tbuffer.WriteString(\"\\r\\n\")\n\n\tif len(resp.Body) > 0 {\n\t\tbuffer.Write(resp.Body)\n\t}\n\treturn w.Write(buffer.Bytes())\n}", "func (c *SwitchVersion) WriteResponse(rw http.ResponseWriter, rp runtime.Producer) {\n\tswitch c.Request.Method {\n\tcase http.MethodPost:\n\t\tc.postSwitchVersion(rw, rp)\n\tdefault:\n\t\tc.notSupported(rw, rp)\n\t}\n}", "func (w responseWriter) Write(b []byte) (int, error) {\n\t// 向一个bytes.buffer中写一份数据来为获取body使用\n\tw.b.Write(b)\n\t// 完成http.ResponseWriter.Write()原有功能\n\treturn w.ResponseWriter.Write(b)\n}", "func (w *multiWriter) Write(b []byte) (int, error) {\n\tvar resp logrus.Fields\n\tif w.isJSONResponse() {\n\t\tif err := json.Unmarshal(b, &resp); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tw.ctx.Set(\"response\", resp)\n\t} else {\n\t\tw.ctx.Set(\"response\", b)\n\t}\n\treturn w.ResponseWriter.Write(b)\n}", "func (cl *DoHClient) Write(packet []byte) (n int, err error) {\n\tn, err = cl.w.Write(packet)\n\tif err != nil {\n\t\tcl.responded <- false\n\t\treturn\n\t}\n\tcl.responded <- true\n\treturn\n}", "func (c *UpdateSwitch) WriteResponse(rw http.ResponseWriter, rp runtime.Producer) {\n\tswitch c.Request.Method {\n\tcase http.MethodPost:\n\t\tc.postUpdateSwitch(rw, rp)\n\tdefault:\n\t\tc.notSupported(rw, rp)\n\t}\n}", "func (c *UpdateSwitch) WriteResponse(rw http.ResponseWriter, rp runtime.Producer) {\n\tswitch c.Request.Method {\n\tcase http.MethodPost:\n\t\tc.postUpdateSwitch(rw, rp)\n\tdefault:\n\t\tc.notSupported(rw, rp)\n\t}\n}", "func writeResponse(status int, w http.ResponseWriter, out io.Reader) error {\n\t// hijack the connection so we can write our own chunked output and trailers\n\thijacker, ok := w.(http.Hijacker)\n\tif !ok {\n\t\tlog.Error(\"Failed to create hijacker! cannot continue!\")\n\t\treturn errors.New(\"Could not create hijacker\")\n\t}\n\tconn, writer, err := hijacker.Hijack()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\t// write status\n\twriter.WriteString(fmt.Sprintf(\"HTTP/1.1 %d %s\\r\\n\", status, http.StatusText(status)))\n\n\t// Write out headers\n\tw.Header().Write(writer)\n\n\t// end of headers\n\twriter.WriteString(\"\\r\\n\")\n\n\t// write body\n\tstreamErr := writeChunks(out, writer)\n\n\t// close body\n\twriter.WriteString(\"0\\r\\n\")\n\n\t// if there was a stream error, write out an error trailer. hopefully\n\t// the client will pick it up!\n\tif streamErr != nil {\n\t\twriter.WriteString(StreamErrHeader + \": \" + sanitizedErrStr(streamErr) + \"\\r\\n\")\n\t}\n\twriter.WriteString(\"\\r\\n\") // close response\n\twriter.Flush()\n\treturn streamErr\n}", "func (w *customResponseWriter) Write(b []byte) (int, error) {\n\tif w.status == 0 {\n\t\tw.status = http.StatusOK\n\t}\n\tn, err := w.ResponseWriter.Write(b)\n\tw.length += n\n\treturn n, err\n}", "func (o *Output) writeResponse(response string) error {\r\n\t// write the response\r\n\tif _, err := o.writer.WriteString(response + \"\\n\"); err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\treturn nil\r\n}", "func (grh *GRPCResponseHandler) Write(data []byte) (int, error) {\n\tgrh.body = append(grh.body, data...)\n\treturn 0, nil\n}", "func (s *session) Write(w pdu.Body) error {\n\treturn s.conn.Write(w)\n}", "func (rt *rtuTransport) WriteResponse(res *pdu) (err error) {\n\t// build an RTU ADU out of the request object and\n\t// send the final ADU+CRC on the wire\n\t_, err\t= rt.link.Write(rt.assembleRTUFrame(res))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// observe inter-frame delays\n\ttime.Sleep(rt.interFrameDelay())\n\n\treturn\n}", "func (client *Clienter) Write() {\n\tfor {\n\t\tselect {\n\t\tcase <-client.stopWriter:\n\t\t\treturn\n\t\tcase data := <-client.response:\n\t\t\tclient.connection.Write([]byte(data))\n\t\t}\n\t}\n}", "func (connection *Connection) Write(b []byte) (int, error) {\n\t//TODO\n}", "func (o *PingOK) WriteResponse(rw http.ResponseWriter, producer httpkit.Producer) {\n\n\trw.WriteHeader(200)\n}", "func WriteResponse(rw io.Writer, v interface{}) {\n\terr := json.NewEncoder(rw).Encode(v)\n\tif err != nil {\n\t\tlogger.Errorf(\"Unable to send error response, %s\", err)\n\t}\n}", "func WriteResponse(r *Response, w io.Writer) error {\n\tif r.Type == InvalidResponse || r.Type >= lastResponse {\n\t\treturn ErrInvalidResponse\n\t}\n\n\tif err := bin.WriteUint16(w, uint16(r.Type)); err != nil {\n\t\treturn err\n\t}\n\n\tswitch r.Type {\n\tcase Ok, Error:\n\t\tif err := bin.WriteUint32(w, uint32(len(r.Data))); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif _, err := w.Write(r.Data); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o *Operation) writeResponse(rw io.Writer, v interface{}) {\n\terr := json.NewEncoder(rw).Encode(v)\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to send error response, %s\", err)\n\t}\n}", "func (r *Tracker) Write(b []byte) (int, error) {\n\tif !r.Written() {\n\t\tr.WriteHeader(http.StatusOK)\n\t}\n\tif !r.Response.Discard {\n\t\tr.Response.Body.Write(b)\n\t}\n\treturn r.ResponseWriter.Write(b)\n}", "func (w *ResponseWriter) Write(data []byte) (int, error) {\n\tif w.code == 0 {\n\t\tw.WriteHeader(http.StatusOK)\n\t}\n\tif w.writeError != nil {\n\t\treturn -1, w.writeError\n\t}\n\tw.buffer = append(w.buffer, data...)\n\treturn len(data), nil\n}", "func (c *connection) Write(mt int, payload []byte) error {\r\n\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\r\n\treturn c.ws.WriteMessage(mt, payload)\r\n}", "func (o *Operation) writeResponse(rw io.Writer, v interface{}) {\n\terr := json.NewEncoder(rw).Encode(v)\n\t// as of now, just log errors for writing response\n\tif err != nil {\n\t\tlogger.Errorf(\"Unable to send error response, %s\", err)\n\t}\n}", "func (res *ResponseRecorder) Write(contents []byte) (int, error) {\n\tif res.statusCode == 0 { // if not setted set it here\n\t\tres.WriteHeader(http.StatusOK)\n\t}\n\tres.chunks = append(res.chunks, contents)\n\treturn res.underline.Write(contents)\n}", "func (p *Conn) Write(b []byte) (int, error) {\n\treturn p.conn.Write(b)\n}", "func (clt HTTPClient) Write(msg []byte, args *WriteArgs) (err error) {\n\tvar readWriteTimeout uint\n\tif args.TmoRdS > args.TmoWrS {\n\t\treadWriteTimeout = args.TmoRdS\n\t} else {\n\t\treadWriteTimeout = args.TmoWrS\n\t}\n\n\thttpClt := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tDial: timeoutDialer(args.TmoCxn, readWriteTimeout),\n\t\t},\n\t\tTimeout: time.Duration(args.TmoSec) * time.Second,\n\t}\n\n\tvar resp *http.Response\n\tif args.CltType == conf.HTTPPost {\n\t\t// Post request\n\t\tresp, err = httpClt.Post(args.IPAddress, \"application/x-www-form-urlencoded\", bytes.NewBuffer(msg))\n\t\tif err != nil {\n\t\t\tclt.logger.Out(logrus.ErrorLevel, logrus.Fields{\"error\": err}, \"HTTP client failed to send the request.\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tclt.logger.Out(logrus.InfoLevel, logrus.Fields{\"numBytes\": len(body)}, \"Successfully received msg reply.\")\n\n\t// Save response to a file.\n\tif args.SaveRes {\n\t\tif args.SaveResFilepath, err = clt.filer.BuildFilePath(args.SaveResDir, fmt.Sprintf(\"%03d\", args.ReqID)+\".res\"); err != nil {\n\t\t\tclt.logger.Out(logrus.ErrorLevel, logrus.Fields{\"filepath\": args.SaveResFilepath}, \"Cannot save the request.\")\n\t\t\terr = errors.Wrap(err, \"os.Stat\")\n\t\t}\n\n\t\tbuf := bytes.NewBuffer(body)\n\n\t\tgo args.SaveResCallback(args.SaveResFilepath, buf)\n\t}\n\treturn\n}", "func (w *ResponseWriterTee) Write(b []byte) (int, error) {\n\tw.Buffer.Write(b)\n\treturn w.w.Write(b)\n}", "func (w *writerWrapper) Write(buf []byte) (int, error) {\n\tif !w.wroteHeader {\n\t\tw.WriteHeader(http.StatusOK)\n\t}\n\tn, err := w.ResponseWriter.Write(buf)\n\tw.bytes += n\n\treturn n, err\n}", "func WriteResponse(w http.ResponseWriter, mensaje string, code int) {\n\tmessage := myTypes.Respuesta{\n\t\tMessage: mensaje,\n\t}\n\tresponse, _ := json.Marshal(message)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(code)\n\tw.Write(response)\n}", "func (o *ConnectCoreV1OptionsNodeProxyOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tpayload := o.Payload\n\tif err := producer.Produce(rw, payload); err != nil {\n\t\tpanic(err) // let the recovery middleware deal with this\n\t}\n}", "func (wsc *WSConnection) writeResponseMessage(id int64, resp *bytes.Buffer) {\n\n\tlog := wsc.tun.log\n\t// Get writer's lock\n\twsWriterMutex.Lock()\n\tdefer wsWriterMutex.Unlock()\n\t// Write response into the tunnel\n\twsc.ws.SetWriteDeadline(time.Now().Add(time.Minute))\n\twriter, err := wsc.ws.NextWriter(websocket.BinaryMessage)\n\t// got an error, reply with a \"hey, retry\" to the request handler\n\tif err != nil {\n\t\tlog.Errorf(\"[id=%d] WS could not find writer: %s\", id, err.Error())\n\t\twsc.ws.Close()\n\t\treturn\n\t}\n\n\t// write the request Id\n\t_, err = fmt.Fprintf(writer, \"%04x\", id)\n\tif err != nil {\n\t\twsc.ws.Close()\n\t\treturn\n\t}\n\n\t// write the response itself\n\tnum, err := io.Copy(writer, resp)\n\tif err != nil {\n\t\tlog.Errorf(\"WS cannot write response: %s\", err.Error())\n\t\twsc.ws.Close()\n\t\treturn\n\t}\n\tlog.Tracef(\"[id=%d] Completed writing response of length: %d\", id, num)\n\n\t// done\n\terr = writer.Close()\n\tif err != nil {\n\t\twsc.ws.Close()\n\t\treturn\n\t}\n}", "func (h *HttpReadWriter) Write(r io.Writer) (readLen int, err error) {\n\treturn r.Write(h.writeBytes)\n}", "func (r *Response) WriteResponse(ctx echo.Context) error {\n\treturn ctx.JSON(r.Status, r)\n}", "func (rwp *ResponseWriterProxy) Write(bs []byte) (int, error) {\n\trwp.buffer.Write(bs)\n\treturn rwp.under.Write(bs)\n}", "func (r *RPCIngressGateway) Write(req *WriteReq, resp *WriteResp) error {\n\tconn, err := r.getConn(req.ConnID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp.N, err = conn.Write(req.B)\n\tresp.Err = ioErrToRPCIOErr(err)\n\n\t// avoid error in RPC pipeline, error is included in response body\n\treturn nil\n}", "func (r tokenResponseWriter) Write(b []byte) (int, error) {\n\treturn r.w.Write(b) // pass it to the original ResponseWriter\n}", "func (clientConn *Conn) Write(p []byte) (n int, err error) {\n\treturn clientConn.dataWriter.Write(p)\n}", "func (c *RESPConn) write(raw []byte) error {\n\tif c.conn == nil {\n\t\treturn ErrConnClosed\n\t}\n\n\tc.conn.SetWriteDeadline(time.Now().Add(c.timeout))\n\t_, err := c.conn.Write(raw)\n\terr = wrapErr(err)\n\tif err == ErrConnClosed {\n\t\tc.close()\n\t}\n\n\treturn err\n}", "func (o *GetPingOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n}", "func WriteResponse(w io.Writer, r *Response) (err error) {\n\tdefer essentials.AddCtxTo(\"write response\", &err)\n\tdata, err := bson.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsize := uint32(len(data))\n\tif err := binary.Write(w, binary.LittleEndian, size); err != nil {\n\t\treturn err\n\t}\n\t_, err = w.Write(data)\n\treturn err\n}", "func (o *WeaviateThingsGetNotImplemented) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(501)\n}", "func (o *GetChatroomsIDOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func (c *Connection) Write(mt int, payload []byte) error {\n\tc.Conn.SetWriteDeadline(time.Now().Add(WriteWait))\n\treturn c.Conn.WriteMessage(mt, payload)\n}", "func WriteResponse(w http.ResponseWriter, v interface{}, statusCode int) {\n\tresBody, err := json.Marshal(v)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(statusCode)\n\t_, _ = w.Write(resBody)\n}", "func WriteResponse(w http.ResponseWriter, object interface{}, rerr *irma.RemoteError) {\n\tstatus, bts := JsonResponse(object, rerr)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(status)\n\t_, err := w.Write(bts)\n\tif err != nil {\n\t\tLogWarning(errors.WrapPrefix(err, \"failed to write response\", 0))\n\t}\n}", "func (w *responseWriter) WriteResponse(resp Response) (int, error) {\n\treturn w.formatter.WriteResponse(resp)\n}", "func (c *Ctx) Write(p []byte) (int, error) {\n\tc.Response.AppendBody(p)\n\treturn len(p), nil\n}", "func (s *ServerCodec) WriteResponse(resp *rpc.Response, obj interface{}) error {\n\tpb, ok := obj.(proto.Message)\n\tif !ok {\n\t\treturn fmt.Errorf(\"%T does not implement proto.Message\", obj)\n\t}\n\n\t// Write the header\n\theader := wire.Header{\n\t\tMethod: &resp.ServiceMethod,\n\t\tSeq: &resp.Seq,\n\t}\n\tif resp.Error != \"\" {\n\t\theader.Error = &resp.Error\n\t}\n\tif err := WriteProto(s.w, &header); err != nil {\n\t\treturn nil\n\t}\n\n\t// Write the proto\n\treturn WriteProto(s.w, pb)\n}", "func WriteResponse(w http.ResponseWriter, code int, err error, data interface{}, t0 time.Time) {\n\tw.WriteHeader(code)\n\tresp := &Response{Data: data, Dur: fmt.Sprint(time.Since(t0)), OK: false}\n\tif code < 300 {\n\t\tresp.OK = true\n\t}\n\tif err != nil {\n\t\tresp.Err = err.Error()\n\t}\n\terr = json.NewEncoder(w).Encode(resp)\n\tif err != nil {\n\t\tlog.Infof(\"failed to json encode response: %v\", err)\n\t\tif _, err = w.Write([]byte(spew.Sdump(resp))); err != nil {\n\t\t\tlog.Infof(\"failed to write dump of response: %v\", err)\n\t\t}\n\t}\n}", "func (o *ConnectCoreV1GetNodeProxyOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tpayload := o.Payload\n\tif err := producer.Produce(rw, payload); err != nil {\n\t\tpanic(err) // let the recovery middleware deal with this\n\t}\n}", "func (c *conn) Write(response *Response) {\n\terr := c.outboxQueue.Enqueue(response)\n\tif err != nil {\n\t\tif err == ErrQueueFull {\n\t\t\tc.CloseWithError(ErrSlowConsumer)\n\t\t\treturn\n\t\t}\n\t\tpanic(fmt.Sprintf(\"Unknown error: %s\", err))\n\t}\n}", "func (rw *ResponseWriter) Write(bytes []byte) (int, error) {\n\tbytesOut, err := rw.ResponseWriter.Write(bytes)\n\trw.BytesOut += bytesOut\n\treturn bytesOut, err\n}", "func writeResponse(data interface{}, w http.ResponseWriter) error {\n\tvar (\n\t\tenc []byte\n\t\terr error\n\t)\n\tenc, err = json.Marshal(data)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn fmt.Errorf(\"Failure to marshal, err = %s\", err)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tn, err := w.Write(enc)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn fmt.Errorf(\"Failure to write, err = %s\", err)\n\t}\n\tif n != len(enc) {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn fmt.Errorf(\"Short write sent = %d, wrote = %d\", len(enc), n)\n\t}\n\treturn nil\n}", "func (response *JSONResponse) Write(w *http.ResponseWriter, r *http.Request) {\n\t// Deref writer\n\twriter := *w\n\n\twriter.Header().Set(\"Content-Type\", \"application/json\")\n\n\t// Add string Status if it doesn't exist, add appropriate headers\n\tif response.OK {\n\t\tif response.Status == \"\" {\n\t\t\tresponse.Status = \"success\"\n\t\t}\n\t\twriter.WriteHeader(http.StatusOK)\n\t} else {\n\t\tif response.Status == \"\" {\n\t\t\tresponse.Status = \"fail\"\n\t\t\twriter.WriteHeader(http.StatusBadRequest)\n\t\t} else if response.Status == \"error\" {\n\t\t\twriter.WriteHeader(http.StatusNoContent)\n\t\t} else {\n\t\t\twriter.WriteHeader(http.StatusBadRequest)\n\t\t}\n\t}\n\n\t// Log this to debug\n\tlog.Debug().\n\t\tStr(\"Path\", r.URL.Path).\n\t\tStr(\"Method\", r.Method).\n\t\tStr(\"Output\", fmt.Sprintf(\"%v\", response.Output)).\n\t\tStr(\"Status\", response.Status).\n\t\tBool(\"OK\", response.OK).\n\t\tMsg(\"Full Response:\")\n\n\t// Write out this response\n\tjson.NewEncoder(writer).Encode(response.Output)\n}", "func (o *GetPingDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(o._statusCode)\n}", "func (c *Call) Write(code int, r io.Reader) error {\n\tc.code = code\n\tc.writer.WriteHeader(c.code)\n\t_, err := io.Copy(c.writer, r)\n\tc.done = true\n\treturn err\n}", "func (c *conn) Write(data []byte) (n int, err error) {\n\treq := &client.Packet{\n\t\tType: client.PacketType_DATA,\n\t\tPayload: &client.Packet_Data{\n\t\t\tData: &client.Data{\n\t\t\t\tConnectID: c.connID,\n\t\t\t\tData: data,\n\t\t\t},\n\t\t},\n\t}\n\n\tklog.V(5).InfoS(\"[tracing] send req\", \"type\", req.Type)\n\n\terr = c.tunnel.Send(req)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn len(data), err\n}", "func writeResponse(body []byte, w *http.ResponseWriter) {\n\t(*w).Header().Set(\"Content-Type\", \"text/plain; charset=utf-8\")\n\t_, err := (*w).Write(body)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\t(*w).WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func (w responseWriterNoBody) Write(data []byte) (int, error) {\n\treturn 0, nil\n}", "func (w *HttpWriter) Write(p []byte) (n int, err error) {\n\tif w.buffer == nil {\n\t\tw.buffer = new(bytes.Buffer)\n\t}\n\n\treturn w.buffer.Write(p)\n}", "func WriteResponse(w io.Writer, resp *http.Response) error {\n\t_, err := w.Write(FormatResponse(resp))\n\treturn err\n}", "func writeResponse(w http.ResponseWriter, response Response) {\n\tjson, err := json.Marshal(&response)\n\n\tif err != nil {\n\t\tfmt.Fprint(w, \"There was an error processing the request.\")\n\t}\n\n\tcommon.Log(fmt.Sprintf(\"Returning response %s\", json))\n\tfmt.Fprintf(w, \"%s\", json)\n}", "func writeResponse(writer http.ResponseWriter, response *http.Response) (int64, error) {\n\tdefer response.Body.Close()\n\twriteResponseHeaders(writer, response, false)\n\treturn io.Copy(writer, response.Body)\n}", "func (c *Conn) Write(b []byte) (int, error) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\treturn c.Conn.Write(b)\n}", "func (r *LogRecord) Write(p []byte) (int, error) {\n\twritten, err := r.ResponseWriter.Write(p)\n\tr.responseBytes += int64(written)\n\treturn written, err\n}", "func (mc *MockConn) Write(b []byte) (n int, err error) {\n\tif mc.closed {\n\t\treturn 0, errors.New(\"Connection closed.\")\n\t}\n\n\tdata := make([]byte, len(b))\n\tcopy(data, b)\n\tmc.sendChan <- data\n\treturn len(b), nil\n}", "func WriteResponse(w http.ResponseWriter, code int, resp interface{}) error {\n\tj, err := json.Marshal(resp)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn err\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(code)\n\n\t_, err = w.Write(j)\n\treturn err\n}", "func (c *Connection) Write(b []byte) (int, error) {\n\twt := config.Get().Timeout.TimeoutReadWrite\n\tif wt == 0 {\n\t\twt = 1\n\t}\n\n\twriteTimeout := time.Duration(wt) * time.Second // Max idle time for a peer\n\n\tc.lock.Lock()\n\t_ = c.Conn.SetWriteDeadline(time.Now().Add(writeTimeout))\n\tn, err := c.Conn.Write(b)\n\tc.lock.Unlock()\n\n\treturn n, err\n}" ]
[ "0.79967237", "0.7723631", "0.76393795", "0.7597352", "0.75598305", "0.7522643", "0.74341476", "0.74341476", "0.72941643", "0.7269729", "0.7255387", "0.7188882", "0.71846604", "0.7128272", "0.7125962", "0.7093482", "0.70601535", "0.7023675", "0.7008508", "0.6976754", "0.6915895", "0.6907197", "0.6899488", "0.6897102", "0.68948317", "0.68787354", "0.68643224", "0.6825855", "0.6822053", "0.68188965", "0.6807778", "0.680461", "0.68034077", "0.6794409", "0.67876804", "0.6787194", "0.67844206", "0.67827827", "0.6775691", "0.6775691", "0.6719179", "0.6716045", "0.67123437", "0.67109776", "0.670793", "0.6701849", "0.6680244", "0.6674963", "0.6670459", "0.66672075", "0.66588974", "0.6651715", "0.66513175", "0.66478664", "0.6646416", "0.6632789", "0.662964", "0.6628281", "0.66268635", "0.6617528", "0.6616106", "0.66096085", "0.6608721", "0.659667", "0.6575513", "0.656267", "0.65579045", "0.6551826", "0.6548573", "0.65479934", "0.6546912", "0.6536152", "0.65348035", "0.65296954", "0.6526847", "0.65206087", "0.6519899", "0.65171766", "0.65092945", "0.6508956", "0.6504295", "0.6499319", "0.6495693", "0.6493635", "0.64878047", "0.64799005", "0.6466318", "0.64652586", "0.64647746", "0.64639306", "0.6457767", "0.64555866", "0.64523387", "0.6447819", "0.64458895", "0.64452714", "0.6432146", "0.6422057", "0.64138186", "0.64036137", "0.6401321" ]
0.0
-1
NewDefaultConfig initialises default config.
func NewDefaultConfig() Config { return Config{ Server: serverConfig{ UDP: defaultUDPPort, TCP: defaultTCPPort, HTTP: defaultHTTPPort, }, Store: storeConfig{TTL: defaultDuration}, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewDefault() *Config {\n\tvv := defaultConfig\n\treturn &vv\n}", "func NewDefault() *Config {\n\tvv := defaultConfig\n\treturn &vv\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tDefaultNamespace: \"default\",\n\t\tFileName: \"stdin\",\n\t\tTargetKubernetesVersion: \"master\",\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tArtifactsDir: DefaultKataArtifactsDir,\n\t}\n}", "func NewDefaultConfig() *Config {\n\tconf := &Config{\n\t\tUnicastConfig: NewDefaultUnicastConfig(),\n\t\tExtensionConfig: NewDefaultExtensionConfig(),\n\t}\n\treturn conf\n}", "func NewDefaultConfig() Config {\n\treturn Config{\n\t\tName: \"avo\",\n\t\tPkg: pkg(),\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tChdir: \".\",\n\t\tCollectorTimeout: collectorTimeout,\n\t\tWaitTime: 10,\n\t}\n}", "func NewDefaultConfig() *Config {\n\thostname, _ := os.Hostname()\n\tc := &Config{\n\t\tHostname: hostname,\n\t\tEncoder: NewAutomaticEventEncoder(),\n\t\tClient: &http.Client{},\n\t}\n\treturn c\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tIgnoreNamespaces: []string{\"kube-system\", \"kube-public\"},\n\t}\n}", "func NewDefaultConfig() Config {\n\n\tvar config = Config{\n\t\tURL: defaultURL,\n\t\tBearerTokenFile: defaultBearerTokenFile,\n\t\tTLSConfig: &TLSConfig{\n\t\t\tInsecureSkipVerify: true,\n\t\t},\n\t}\n\treturn config\n}", "func NewDefaultConfig() *Config {\n\tcreds := NewHomeConfig()\n\toverrideFromEnv(creds)\n\treturn creds\n}", "func NewDefaultConfig() *Config {\n\treturn (&Config{}).WithOptions(\n\t\tSnapshotSubdirectory(\".snapshots\"),\n\t\tEnvVariableName(\"UPDATE_SNAPSHOTS\"),\n\t\tFailOnUpdate(true),\n\t\tCreateNewAutomatically(true),\n\t)\n}", "func NewDefaultConfig() *Config {\n\tvar config = Config{\n\t\tCliPath: defaultCliPath,\n\t\tRefreshInterval: defaultRefreshInterval,\n\t\tInfluxDB: influxdb.NewDefaultConfig(),\n\t\tLdap: ldap.NewDefaultConfig(),\n\t}\n\treturn &config\n}", "func NewDefaultConfig() Config {\n\treturn Config{\n\t\tStepSize: 0.001,\n\t\tBeta1: 0.9,\n\t\tBeta2: 0.999,\n\t\tEpsilon: 1.0e-8,\n\t}\n}", "func NewDefault() (*Config, error) {\n\tc := &Config{}\n\n\terr := yaml.Unmarshal([]byte(DefaultConfigFileContent), c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tIgnoreNamespaces: []string{\"kube-system\", \"kube-admission\"},\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tIgnoreNamespaces: []string{\"kube-system\", \"kube-admission\"},\n\t}\n}", "func NewDefaultConfig() *GenConfig {\n\treturn &GenConfig{\n\t\tPackageName: defaultPathPackageName,\n\t\tGoImports: GoImports{\n\t\t\tYgotImportPath: genutil.GoDefaultYgotImportPath,\n\t\t\tYtypesImportPath: genutil.GoDefaultYtypesImportPath,\n\t\t\tGoyangImportPath: genutil.GoDefaultGoyangImportPath,\n\t\t\tProtoLibImportPath: defaultProtoLibImportPath,\n\t\t\tGNMIProtoPath: genutil.GoDefaultGNMIImportPath,\n\t\t\tGenUtilImportPath: defaultGenUtilImportPath,\n\t\t},\n\t\tFakeRootName: defaultFakeRootName,\n\t\tGeneratingBinary: genutil.CallerName(),\n\t}\n}", "func defaultConfig() interface{} {\n\treturn &config{\n\t\tPools: make(pools),\n\t\tConfDirPath: \"/etc/cmk\",\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tPublic: false,\n\t\tMemory: false, // Save to disk.\n\t\tConfigDir: \"\", // --> Action: set as '$HOME/.skybbs'\n\t\tRPC: true,\n\t\tRPCPort: defaultRPCPort,\n\t\tCXOPort: defaultCXOPort,\n\t\tCXORPC: false,\n\t\tCXORPCPort: defaultCXORPCPort,\n\t\tEnforcedMessengerAddresses: []string{},\n\t\tEnforcedSubscriptions: []string{},\n\t\tWebPort: defaultWebPort,\n\t\tWebGUI: true,\n\t\tWebGUIDir: defaultStaticSubDir, // --> Action: set as '$HOME/.skybbs/static/dist'\n\t\tBrowser: false,\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tProxyConnectTimeout: \"60s\",\n\t\tProxyReadTimeout: \"60s\",\n\t\tClientMaxBodySize: \"1m\",\n\t\tMainServerNamesHashMaxSize: \"512\",\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tAppName: pkg.Name(),\n\t\tLogPath: \"/tmp/log\",\n\t\tFlowRules: make([]*flow.Rule, 0),\n\t}\n}", "func NewDefaultConfig(\n\tmagic, pver uint32,\n\tservices uint64,\n\tdefaultPort uint16,\n\tseeds, listenAddrs []string,\n\tonNewPeer func(IPeer) bool,\n\tonDonePeer func(IPeer),\n\tmakeEmptyMessage func(string) (p2p.Message, error),\n\tbestHeight func() uint64) *Config {\n\treturn &Config{\n\t\tMagicNumber: magic,\n\t\tProtocolVersion: pver,\n\t\tServices: services,\n\t\tDNSSeeds: seeds,\n\t\tListenAddrs: listenAddrs,\n\t\tExternalIPs: nil,\n\t\tUpnp: false,\n\t\tDefaultPort: defaultPort,\n\t\tDisableListen: false,\n\t\tDisableRelayTx: false,\n\t\tMaxPeers: defaultMaxPeers,\n\t\tDisableBanning: false,\n\t\tBanThreshold: defaultBanThreshold,\n\t\tBanDuration: defaultBanDuration,\n\t\tWhitelists: nil,\n\t\tTargetOutbound: defaultTargetOutbound,\n\t\tOnNewPeer: onNewPeer,\n\t\tOnDonePeer: onDonePeer,\n\t\tMakeEmptyMessage: makeEmptyMessage,\n\t\tBestHeight: bestHeight,\n\t\tPingNonce: bestHeight,\n\t\tPongNonce: bestHeight,\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tIgnoreNamespaces: []string{\"kube-system\", \"kube-admission\"},\n\t\tWhitelist: []string{string(core.ServiceTypeNodePort), string(core.ServiceTypeClusterIP)},\n\t}\n}", "func defaultConfig() *config {\n\treturn &config{\n\t\tOperations: operations{\n\t\t\tResize: resize{\n\t\t\t\tRaw: *resizeDefaults(),\n\t\t\t},\n\t\t\tFlip: flip{\n\t\t\t\tRaw: *flipDefaults(),\n\t\t\t},\n\t\t\tBlur: blur{\n\t\t\t\tRaw: *blurDefaults(),\n\t\t\t},\n\t\t\tRotate: rotate{\n\t\t\t\tRaw: *rotateDefaults(),\n\t\t\t},\n\t\t\tCrop: crop{\n\t\t\t\tRaw: *cropDefaults(),\n\t\t\t},\n\t\t\tLabel: label{\n\t\t\t\tRaw: *labelDefaults(),\n\t\t\t},\n\t\t},\n\t\tExport: export{\n\t\t\tRaw: *exportDefaults(),\n\t\t},\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 2*time.Minute),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, 2*time.Second),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),\n\t\t},\n\t}\n}", "func NewDefault() Configuration {\n\tcfg := Configuration{\n\t\tEnableSyslog: false,\n\t\tEnableSSL: false,\n\t\tHttpRequestTimeout: 5,\n\t\tConnectTimeout: 5,\n\t\tClientTimeout: 50,\n\t\tClientFinTimeout: 50,\n\t\tServerTimeout: 50,\n\t\tTunnelTimeout: 3600,\n\t\tHttpKeepAliveTimeout: 60,\n\t}\n\n\treturn cfg\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 5*time.Minute),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, 20*time.Second),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),\n\t\t},\n\t}\n}", "func NewDefaultConfig(host string) Config {\n\treturn Config{GraylogPort: 12201, MaxChunkSize: 8154, GraylogHostname: host}\n}", "func DefaultConfig() Config {\n\tnewConfig := Config{\n\t\t// Dependencies.\n\t\tFactoryCollection: factory.MustNewCollection(),\n\t\tLog: log.New(log.DefaultConfig()),\n\t\tStorageCollection: storage.MustNewCollection(),\n\n\t\t// Settings.\n\t\tMaxSignals: 5,\n\t}\n\n\treturn newConfig\n}", "func createDefaultConfig() component.Config {\n\treturn &Config{\n\t\tScraperControllerSettings: scraperhelper.ScraperControllerSettings{\n\t\t\tCollectionInterval: defaultCollectionInterval,\n\t\t\tTimeout: defaultTimeout,\n\t\t},\n\t\tEndpoint: defaultEndpoint,\n\t\tVersion: defaultVersion,\n\t\tCommunity: defaultCommunity,\n\t\tSecurityLevel: defaultSecurityLevel,\n\t\tAuthType: defaultAuthType,\n\t\tPrivacyType: defaultPrivacyType,\n\t}\n}", "func DefaultConfig() Config {\n\tnewConfig := Config{\n\t\t// Dependencies.\n\t\tFactoryCollection: factory.MustNewCollection(),\n\t\tLog: log.New(log.DefaultConfig()),\n\t\tStorageCollection: storage.MustNewCollection(),\n\t}\n\n\treturn newConfig\n}", "func TestNewConfigDefault(t *testing.T) {\n\tconfig, err := NewConfig(\"\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, 512, config.Clustering.RaftCacheSize)\n\trequire.Equal(t, \"liftbridge-default\", config.Clustering.Namespace)\n\trequire.Equal(t, 1024, config.BatchMaxMessages)\n}", "func MakeDefaultConfig(clusterGRPCAddress string, oauthServerAddress string, insecure bool) Config {\n\treturn Config{\n\t\tBase: conf.Base{\n\t\t\tLog: conf.Log{\n\t\t\t\tFormat: \"console\",\n\t\t\t\tLevel: log.InfoLevel,\n\t\t\t},\n\t\t},\n\t\tInputFormat: \"json\",\n\t\tOutputFormat: \"json\",\n\t\tOAuthServerAddress: oauthServerAddress,\n\t\tIdentityServerGRPCAddress: clusterGRPCAddress,\n\t\tGatewayServerEnabled: true,\n\t\tGatewayServerGRPCAddress: clusterGRPCAddress,\n\t\tNetworkServerEnabled: true,\n\t\tNetworkServerGRPCAddress: clusterGRPCAddress,\n\t\tApplicationServerEnabled: true,\n\t\tApplicationServerGRPCAddress: clusterGRPCAddress,\n\t\tJoinServerEnabled: true,\n\t\tJoinServerGRPCAddress: clusterGRPCAddress,\n\t\tDeviceTemplateConverterGRPCAddress: clusterGRPCAddress,\n\t\tDeviceClaimingServerGRPCAddress: clusterGRPCAddress,\n\t\tQRCodeGeneratorGRPCAddress: clusterGRPCAddress,\n\t\tPacketBrokerAgentGRPCAddress: clusterGRPCAddress,\n\t\tInsecure: insecure,\n\t\tRetry: defaultRetryConfig,\n\t\tTelemetry: defaultTelemetryConfig,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tLager: lager.NewLogLager(nil),\n\t\tPool: new(gob.Pool),\n\t}\n}", "func createDefaultConfig() component.Config {\n\treturn &Config{}\n}", "func createDefaultConfig() component.Config {\n\treturn &Config{}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tK8sClient: nil,\n\t\tLogger: nil,\n\t}\n}", "func defaultConfig() *config {\n\treturn &config{}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tK8sClient: nil,\n\t\tLogger: nil,\n\t\tVaultClient: nil,\n\t}\n}", "func NewDefaultConfig() *Config {\n\tcf := &Config{\n\t\tDBPath: \"./\",\n\t\tTableName: \"session\",\n\t\tSetMaxOpenConn: 500,\n\t\tSetMaxIdleConn: 50,\n\t}\n\n\treturn cf\n}", "func createDefaultConfig() component.Config {\n\treturn &Config{\n\t\tProtocols: Protocols{\n\t\t\tGRPC: &configgrpc.GRPCServerSettings{\n\t\t\t\tNetAddr: confignet.NetAddr{\n\t\t\t\t\tEndpoint: defaultGRPCEndpoint,\n\t\t\t\t\tTransport: \"tcp\",\n\t\t\t\t},\n\t\t\t\t// We almost write 0 bytes, so no need to tune WriteBufferSize.\n\t\t\t\tReadBufferSize: 512 * 1024,\n\t\t\t},\n\t\t\tHTTP: &HTTPConfig{\n\t\t\t\tHTTPServerSettings: &confighttp.HTTPServerSettings{\n\t\t\t\t\tEndpoint: defaultHTTPEndpoint,\n\t\t\t\t},\n\t\t\t\tTracesURLPath: defaultTracesURLPath,\n\t\t\t\tMetricsURLPath: defaultMetricsURLPath,\n\t\t\t\tLogsURLPath: defaultLogsURLPath,\n\t\t\t},\n\t\t},\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tSequenceInterval: env.GetOrDefaultSecond(EnvSequenceInterval, dns01.DefaultPropagationTimeout),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),\n\t\t},\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tinjectString: defaultInject,\n\t\tconfigString: defaultConfig,\n\t\tappProfile: newAppProfile(),\n\t\tactivateES: false,\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tConfigurers: nil,\n\t\tFileSystem: afero.NewMemMapFs(),\n\t\tLogger: nil,\n\n\t\t// Settings.\n\t\tHelmBinaryPath: \"\",\n\t\tOrganisation: \"\",\n\t\tPassword: \"\",\n\t\tRegistry: \"\",\n\t\tUsername: \"\",\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tTTL: env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL),\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tPort: 5000,\n\t\tHapHome: \"/HOME/hapadm\",\n\t\tClusterID: \"default-name\",\n\t\tSudo: true,\n\t}\n}", "func NewDefaultConfig(v *viper.Viper) (*Config, error) {\n\tif !v.IsSet(\"postgres\") {\n\t\treturn nil, ErrEmptyConfig\n\t}\n\n\t// v.SetDefault(\"postgres.hostname\", \"localhost\")\n\tv.SetDefault(\"postgres.options.sslmode\", \"disable\")\n\n\t// re-fetch by full key\n\toptions := v.GetStringMapString(\"postgres.options\")\n\tif len(options) > 0 {\n\t\tfor opt := range options {\n\t\t\toptions[opt] = v.GetString(\"postgres.options.\" + opt)\n\t\t}\n\t}\n\n\treturn &Config{\n\t\tHostname: v.GetString(\"postgres.hostname\"),\n\t\tUsername: v.GetString(\"postgres.username\"),\n\t\tPassword: v.GetString(\"postgres.password\"),\n\t\tDatabase: v.GetString(\"postgres.database\"),\n\t\tDebug: v.GetBool(\"postgres.debug\"),\n\t\tPoolSize: v.GetInt(\"postgres.pool_size\"),\n\t\tOptions: options,\n\t}, nil\n}", "func defaultConfig() Config {\n\treturn Config{\n\t\tConfFileOptions: defaultFileOptions(),\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tRedisURI: \"redis://127.0.0.1:6379\",\n\t\tGCP: &GCPConfig{\n\t\t\tProjectID: \"\",\n\t\t\tServiceAccountFile: \"\",\n\t\t},\n\t}\n}", "func DefaultConfig() *Config {\n\tconfig := new(Config)\n\tconfig.URL = MktmpioURL\n\treturn config\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tFileSystem: nil,\n\t\tK8sClient: nil,\n\t\tLogger: nil,\n\n\t\t// Settings.\n\t\tFlag: nil,\n\t\tViper: nil,\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tBaseConfig: defaultBaseConfig(),\n\t\tP2P: p2pConfig.DefaultConfig(),\n\t\tAPI: apiConfig.DefaultConfig(),\n\t\tCONSENSUS: consensusConfig.DefaultConfig(),\n\t\tHARE: hareConfig.DefaultConfig(),\n\t\tTIME: timeConfig.DefaultConfig(),\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tResource: nil,\n\n\t\t// Settings.\n\t\tName: \"\",\n\t}\n}", "func DefaultConfig(storageType string, factories config.Factories) *configmodels.Config {\n\texporters := createExporters(storageType, factories)\n\ttypes := []string{}\n\tfor _, v := range exporters {\n\t\ttypes = append(types, v.Type())\n\t}\n\treturn &configmodels.Config{\n\t\tReceivers: createReceivers(factories),\n\t\tExporters: exporters,\n\t\tProcessors: createProcessors(factories),\n\t\tService: configmodels.Service{\n\t\t\tPipelines: map[string]*configmodels.Pipeline{\n\t\t\t\t\"traces\": {\n\t\t\t\t\tInputType: configmodels.TracesDataType,\n\t\t\t\t\tReceivers: []string{\"jaeger\"},\n\t\t\t\t\tExporters: types,\n\t\t\t\t\tProcessors: []string{\"batch\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tBlockchainInfo: types.DefaultBlockchainInfo(),\n\n\t\tAPIPassword: \"\",\n\n\t\tAPIaddr: \"localhost:23110\",\n\t\tRPCaddr: \":23112\",\n\t\tAllowAPIBind: false,\n\n\t\tNoBootstrap: false,\n\t\tRequiredUserAgent: RivineUserAgent,\n\t\tAuthenticateAPI: false,\n\n\t\tProfile: false,\n\t\tProfileDir: \"profiles\",\n\t\tRootPersistentDir: \"\",\n\t\tVerboseLogging: false,\n\n\t\tBootstrapPeers: nil,\n\n\t\tDebugConsensusDB: \"\",\n\t}\n}", "func DefaultConfig() *Config {\n\tconfig := &Config{\n\t\tOwnerProcName: \"\",\n\t\tOwnerReleaseInterval: 1 * time.Second,\n\t\tOwnerReleaseTimeout: 5 * time.Minute,\n\t\tSourcePattern: \"/tmp/rotate/source\",\n\t\tTempStorage: \"/tmp/rotate/tmp\",\n\t\tArchiveStorage: \"/tmp/rotate/archive\",\n\t\tFinalizeCommands: []string{},\n\t}\n\treturn config\n}", "func (c ComponentSettings) CreateDefaultConfig() (*configmodels.Config, error) {\n\texporters, err := createExporters(c.ComponentType, c.StorageType, c.Factories)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treceivers := createReceivers(c.ComponentType, c.ZipkinHostPort, c.Factories)\n\tprocessors, processorNames := createProcessors(c.Factories)\n\thc := c.Factories.Extensions[\"health_check\"].CreateDefaultConfig()\n\treturn &configmodels.Config{\n\t\tReceivers: receivers,\n\t\tProcessors: processors,\n\t\tExporters: exporters,\n\t\tExtensions: configmodels.Extensions{hc.Name(): hc},\n\t\tService: configmodels.Service{\n\t\t\tExtensions: []string{hc.Name()},\n\t\t\tPipelines: configmodels.Pipelines{\n\t\t\t\tstring(configmodels.TracesDataType): {\n\t\t\t\t\tInputType: configmodels.TracesDataType,\n\t\t\t\t\tReceivers: receiverNames(receivers),\n\t\t\t\t\tProcessors: processorNames,\n\t\t\t\t\tExporters: exporterNames(exporters),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func DefaultConfig() *Config {\n\tc := &Config{}\n\tif _, err := toml.Decode(defaultConfig, c); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := c.Validate(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn c\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tAddr: DefaultAddr,\n\t\tDirPath: DefaultDirPath,\n\t\tBlockSize: DefaultBlockSize,\n\t\tRwMethod: storage.FileIO,\n\t\tIdxMode: KeyValueMemMode,\n\t\tMaxKeySize: DefaultMaxKeySize,\n\t\tMaxValueSize: DefaultMaxValueSize,\n\t\tSync: false,\n\t\tReclaimThreshold: DefaultReclaimThreshold,\n\t\tSingleReclaimThreshold: DefaultSingleReclaimThreshold,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tZapConfig: zap.NewProductionConfig(),\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tTTL: env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL),\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 120*time.Second),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, 2*time.Second),\n\t\tServerName: env.GetOrDefaultString(EnvServerName, \"localhost\"),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),\n\t\t},\n\t}\n}", "func DefaultConfig() *Config {\n\tdefaultExp := model.DefaultExperimentConfig(nil)\n\tvar c CheckpointStorageConfig\n\tif err := c.FromModel(&defaultExp.CheckpointStorage); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &Config{\n\t\tConfigFile: \"\",\n\t\tLog: *logger.DefaultConfig(),\n\t\tDB: *db.DefaultConfig(),\n\t\tTaskContainerDefaults: model.TaskContainerDefaultsConfig{\n\t\t\tShmSizeBytes: 4294967296,\n\t\t\tNetworkMode: \"bridge\",\n\t\t},\n\t\tTensorBoardTimeout: 5 * 60,\n\t\tScheduler: *scheduler.DefaultConfig(),\n\t\tSecurity: SecurityConfig{\n\t\t\tDefaultTask: model.AgentUserGroup{\n\t\t\t\tUID: 0,\n\t\t\t\tGID: 0,\n\t\t\t\tUser: \"root\",\n\t\t\t\tGroup: \"root\",\n\t\t\t},\n\t\t},\n\t\t// If left unspecified, the port is later filled in with 8080 (no TLS) or 8443 (TLS).\n\t\tPort: 0,\n\t\tCheckpointStorage: c,\n\t\tHarnessPath: \"/opt/determined\",\n\t\tRoot: \"/usr/share/determined/master\",\n\t\tTelemetry: TelemetryConfig{\n\t\t\tEnabled: true,\n\t\t\tSegmentMasterKey: DefaultSegmentMasterKey,\n\t\t\tSegmentWebUIKey: DefaultSegmentWebUIKey,\n\t\t},\n\t\tEnableCors: false,\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tTTL: env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL),\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, ovh.DefaultTimeout),\n\t\t},\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tTTL: env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL),\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, ovh.DefaultTimeout),\n\t\t},\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tName: \"endpoint\",\n\t\tMaxPacketSize: 16 * 1024,\n\t\tFragmentAbove: 1024,\n\t\tMaxFragments: 16,\n\t\tFragmentSize: 1024,\n\t\tAckBufferSize: 256,\n\t\tSentPacketsBufferSize: 256,\n\t\tReceivedPacketsBufferSize: 256,\n\t\tFragmentReassemblyBufferSize: 64,\n\t\tRttSmoothingFactor: .0025,\n\t\tPacketLossSmoothingFactor: .1,\n\t\tBandwidthSmoothingFactor: .1,\n\t\tPacketHeaderSize: 28, // // note: UDP over IPv4 = 20 + 8 bytes, UDP over IPv6 = 40 + 8 bytes\n\t}\n}", "func GenerateDefaultConfig(c *Config) {\n\tpk, sk := cipher.GenerateKeyPair()\n\n\tc.Path = DefaultConfigPath\n\tc.PubKey = pk\n\tc.SecKey = sk\n\tc.Discovery = defaultDiscoveryURL\n\tc.PublicAddress = defaultPublicAddress\n\tc.LocalAddress = defaultLocalAddress\n\tc.HTTPAddress = defaultHTTPAddress\n\tc.LogLevel = \"info\"\n\tc.MaxSessions = 2048\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tBackOff: nil,\n\t\tFramework: nil,\n\t\tInformer: nil,\n\t\tLogger: nil,\n\t\tTPR: nil,\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tLogger: nil,\n\n\t\t// Settings.\n\t\tBridgeName: \"\",\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tAddress: \"127.0.0.1\",\n\t\tPort: 5700,\n\t\tSyslogFacility: \"SYSLOG\",\n\t\tLogLevel: \"INFO\",\n\t\tConsulDatacenter: \"dc1\",\n\t\tConsulPort: 8500,\n\t\tParameters: make(map[string]string),\n\t\tDeclarations: essentials.NewDeclarationsConfig(),\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tTTL: env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL),\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 60*time.Second),\n\t\t},\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tTTL: env.GetOrDefaultInt(EnvTTL, 300),\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),\n\t\t},\n\t}\n}", "func defaultConfig() interface{} {\n\treturn &conf{\n\t\tPools: make(map[string]poolConfig),\n\t\tLabelNode: false,\n\t\tTaintNode: false,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tLogLevel: \"debug\",\n\t\tLogFormat: \"text\",\n\n\t\tDatabaseDriver: \"boltdb\",\n\t\tDatabasePath: \"db/eremetic.db\",\n\n\t\tName: \"Eremetic\",\n\t\tUser: \"root\",\n\t\tCheckpoint: true,\n\t\tFailoverTimeout: 2592000.0,\n\t\tQueueSize: 100,\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tLogger: nil,\n\n\t\t// Settings.\n\t\tFlag: nil,\n\t\tViper: nil,\n\n\t\tDescription: \"\",\n\t\tGitCommit: \"\",\n\t\tName: \"\",\n\t\tSource: \"\",\n\t}\n}", "func Default() *Config {\n\treturn &Config{\n\t\tEnv: &Env{Region: region, Zone: zone, DeployEnv: deployEnv, Host: host},\n\t\tDiscovery: &naming.Config{Region: region, Zone: zone, Env: deployEnv, Host: host},\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tBaseConfig: BaseConfig{\n\t\t\tMinGasPrices: defaultMinGasPrices,\n\t\t\tQueryGasLimit: 0,\n\t\t\tInterBlockCache: true,\n\t\t\tPruning: pruningtypes.PruningOptionDefault,\n\t\t\tPruningKeepRecent: \"0\",\n\t\t\tPruningInterval: \"0\",\n\t\t\tMinRetainBlocks: 0,\n\t\t\tIndexEvents: make([]string, 0),\n\t\t\tIAVLCacheSize: 781250,\n\t\t\tIAVLDisableFastNode: false,\n\t\t\tAppDBBackend: \"\",\n\t\t},\n\t\tTelemetry: telemetry.Config{\n\t\t\tEnabled: false,\n\t\t\tGlobalLabels: [][]string{},\n\t\t},\n\t\tAPI: APIConfig{\n\t\t\tEnable: false,\n\t\t\tSwagger: false,\n\t\t\tAddress: DefaultAPIAddress,\n\t\t\tMaxOpenConnections: 1000,\n\t\t\tRPCReadTimeout: 10,\n\t\t\tRPCMaxBodyBytes: 1000000,\n\t\t},\n\t\tGRPC: GRPCConfig{\n\t\t\tEnable: true,\n\t\t\tAddress: DefaultGRPCAddress,\n\t\t\tMaxRecvMsgSize: DefaultGRPCMaxRecvMsgSize,\n\t\t\tMaxSendMsgSize: DefaultGRPCMaxSendMsgSize,\n\t\t},\n\t\tGRPCWeb: GRPCWebConfig{\n\t\t\tEnable: true,\n\t\t},\n\t\tStateSync: StateSyncConfig{\n\t\t\tSnapshotInterval: 0,\n\t\t\tSnapshotKeepRecent: 2,\n\t\t},\n\t\tStreaming: StreamingConfig{\n\t\t\tABCI: ABCIListenerConfig{\n\t\t\t\tKeys: []string{},\n\t\t\t\tStopNodeOnErr: true,\n\t\t\t},\n\t\t},\n\t\tMempool: MempoolConfig{\n\t\t\tMaxTxs: 5_000,\n\t\t},\n\t}\n}", "func DefaultConfig(hostname string) *Config {\n\treturn &Config{\n\t\thostname,\n\t\t8, // 8 vnodes\n\t\tsha1.New, // SHA1\n\t\ttime.Duration(5 * time.Second),\n\t\ttime.Duration(15 * time.Second),\n\t\t8, // 8 successors\n\t\tnil, // No delegate\n\t\t160, // 160bit hash function\n\t\t\"\",\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tBaseConfig: DefaultBaseConfig(),\n\t\tEth: DefaultEthConfig(),\n\t\tHuron: DefaultHuronConfig(),\n\t\tRaft: DefaultRaftConfig(),\n\t}\n}", "func (f *factory) DefaultConfig() interface{} {\n\treturn f.newDefaultCfg()\n}", "func Default() *Config {\n\treturn &defaultConfig\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tTTL: env.GetOrDefaultInt(EnvTTL, 600),\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tHTTPTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 10*time.Second),\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tShowOurLogs: true,\n\t\tDeliverLogs: defaultDeliver,\n\t\tBackoffCap: defaultBackoffCap,\n\t\tBackoffGranularity: defaultBackoffGranularity,\n\t\tTickInterval: defaultTickInterval,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tLogLevel: \"INFO\",\n\t\tBindAddr: \"127.0.0.1\",\n\t\tPorts: &Ports{\n\t\t\tHTTP: 4646,\n\t\t\tRPC: 4647,\n\t\t\tSerf: 4648,\n\t\t},\n\t\tAddresses: &Addresses{},\n\t\tServer: &ServerConfig{\n\t\t\tEnabled: false,\n\t\t},\n\t}\n}", "func Default() *Config {\n\trootDir := \"/\"\n\tswitch runtime.GOOS {\n\tcase \"windows\":\n\t\trootDir = `C:\\`\n\t}\n\treturn &Config{\n\t\tFile: File{\n\t\t\tProxyNetwork: \"unix\",\n\t\t\tProxyAddress: filepath.Join(client.Namespace(), \"acme-lsp.rpc\"),\n\t\t\tAcmeNetwork: \"unix\",\n\t\t\tAcmeAddress: filepath.Join(client.Namespace(), \"acme\"),\n\t\t\tWorkspaceDirectories: nil,\n\t\t\tRootDirectory: rootDir,\n\t\t\tFormatOnPut: true,\n\t\t\tCodeActionsOnPut: []protocol.CodeActionKind{\n\t\t\t\tprotocol.SourceOrganizeImports,\n\t\t\t},\n\t\t\tServers: nil,\n\t\t\tFilenameHandlers: nil,\n\t\t},\n\t}\n}", "func DefaultConfig() *config.Config {\n\treturn &config.Config{\n\t\tDebug: config.Debug{\n\t\t\tAddr: \"127.0.0.1:9174\",\n\t\t},\n\t\tService: config.Service{\n\t\t\tName: \"notifications\",\n\t\t},\n\t\tNotifications: config.Notifications{\n\t\t\tSMTP: config.SMTP{\n\t\t\t\tHost: \"127.0.0.1\",\n\t\t\t\tPort: \"1025\",\n\t\t\t\tSender: \"[email protected]\",\n\t\t\t},\n\t\t\tEvents: config.Events{\n\t\t\t\tEndpoint: \"127.0.0.1:9233\",\n\t\t\t\tCluster: \"ocis-cluster\",\n\t\t\t\tConsumerGroup: \"notifications\",\n\t\t\t},\n\t\t\tRevaGateway: \"127.0.0.1:9142\",\n\t\t},\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tLogLevel: \"debug\",\n\t\tLogFormat: \"text\",\n\n\t\tDatabase: DatabaseConfig{\n\t\t\tHost: \"127.0.0.1\",\n\t\t\tPort: 3306,\n\t\t\tName: \"fusion\",\n\t\t\tUser: \"fusion\",\n\t\t\tPassword: \"password\",\n\t\t},\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tHeartbeat: defaultHeartbeat,\n\t\tLocale: defaultLocale,\n\t\tDefaultLoggerLevel: zerolog.ErrorLevel,\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tTTL: int64(env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL)),\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tHTTPTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 60*time.Second),\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tSFCRenderer: defaultSFCRenderer,\n\t}\n}", "func NewConfig() *Config {\n\treturn &Config{config.New(\"default\")}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tTTL: env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL),\n\t\tPropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout),\n\t\tPollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),\n\t\tHTTPTimeout: env.GetOrDefaultSecond(EnvHTTPTimeout, session.DefaultTimeout),\n\t}\n}", "func createDefaultConfig() configmodels.Processor {\n\treturn &Config{\n\t\tProcessorSettings: configmodels.ProcessorSettings{\n\t\t\tTypeVal: typeStr,\n\t\t\tNameVal: typeStr,\n\t\t},\n\t}\n}", "func NewDefaultConfig(authServer string) (*BotConfig, error) {\n\t// Note: we need authServer for CheckAndSetDefaults to succeed.\n\tcfg := BotConfig{\n\t\tAuthServer: authServer,\n\t}\n\tif err := cfg.CheckAndSetDefaults(); err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\treturn &cfg, nil\n}", "func TestNewConfigDefaultAndFile(t *testing.T) {\n\tconfig, err := NewConfig(\"configs/simple.yaml\")\n\trequire.NoError(t, err)\n\t// Ensure custom configs are loaded\n\trequire.Equal(t, true, config.LogRecovery)\n\trequire.Equal(t, int64(1024), config.Streams.RetentionMaxBytes)\n\n\t// Ensure also default values are loaded at the same time\n\trequire.Equal(t, 512, config.Clustering.RaftCacheSize)\n\trequire.Equal(t, \"liftbridge-default\", config.Clustering.Namespace)\n\trequire.Equal(t, 1024, config.BatchMaxMessages)\n}", "func ConfigDefault() Config {\n\tc := Config{\n\t\tCache: true,\n\t\tCacheRefresh: 3,\n\t\tCachePath: \"./.hpy\",\n\t\tMotd: true,\n\t\tMotdPath: \"/tmp/hpy.json\",\n\t\tLogging: true,\n\t\tLoggingPath: \"/var/log/hpy.log\",\n\t\tIgnoreLogging: false,\n\t\tDebug: false,\n\t}\n\treturn c\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tHTTPClient: nil,\n\t\tLogger: nil,\n\n\t\t// Settings.\n\t\tFlag: nil,\n\t\tViper: nil,\n\t}\n}", "func configDefault(config ...Config) Config {\n\t// Return default config if nothing provided\n\tif len(config) < 1 {\n\t\treturn ConfigDefault\n\t}\n\n\t// Override default config\n\tcfg := config[0]\n\n\t// Set default values\n\n\tif cfg.Next == nil {\n\t\tcfg.Next = ConfigDefault.Next\n\t}\n\n\tif cfg.Lifetime.Nanoseconds() == 0 {\n\t\tcfg.Lifetime = ConfigDefault.Lifetime\n\t}\n\n\tif cfg.KeyHeader == \"\" {\n\t\tcfg.KeyHeader = ConfigDefault.KeyHeader\n\t}\n\tif cfg.KeyHeaderValidate == nil {\n\t\tcfg.KeyHeaderValidate = ConfigDefault.KeyHeaderValidate\n\t}\n\n\tif cfg.KeepResponseHeaders != nil && len(cfg.KeepResponseHeaders) == 0 {\n\t\tcfg.KeepResponseHeaders = ConfigDefault.KeepResponseHeaders\n\t}\n\n\tif cfg.Lock == nil {\n\t\tcfg.Lock = NewMemoryLock()\n\t}\n\n\tif cfg.Storage == nil {\n\t\tcfg.Storage = memory.New(memory.Config{\n\t\t\tGCInterval: cfg.Lifetime / 2, // Half the lifetime interval\n\t\t})\n\t}\n\n\treturn cfg\n}", "func DefaultConfig() Config {\n\tencoding := cosmoscmd.MakeEncodingConfig(app.ModuleBasics)\n\n\treturn Config{\n\t\tCodec: encoding.Marshaler,\n\t\tTxConfig: encoding.TxConfig,\n\t\tLegacyAmino: encoding.Amino,\n\t\tInterfaceRegistry: encoding.InterfaceRegistry,\n\t\tAccountRetriever: dclauthtypes.AccountRetriever{},\n\t\tAppConstructor: func(val Validator) servertypes.Application {\n\t\t\treturn app.New(\n\t\t\t\tval.Ctx.Logger, tmdb.NewMemDB(), nil, true, map[int64]bool{}, val.Ctx.Config.RootDir, 0,\n\t\t\t\tencoding,\n\t\t\t\tsimapp.EmptyAppOptions{},\n\t\t\t\tbaseapp.SetPruning(storetypes.NewPruningOptionsFromString(val.AppConfig.Pruning)),\n\t\t\t\tbaseapp.SetMinGasPrices(val.AppConfig.MinGasPrices),\n\t\t\t)\n\t\t},\n\t\tGenesisState: app.ModuleBasics.DefaultGenesis(encoding.Marshaler),\n\t\tTimeoutCommit: 2 * time.Second,\n\t\tChainID: \"chain-\" + tmrand.NewRand().Str(6),\n\t\tNumValidators: 1,\n\t\tBondDenom: sdk.DefaultBondDenom,\n\t\tMinGasPrices: fmt.Sprintf(\"0.000006%s\", sdk.DefaultBondDenom),\n\t\tAccountTokens: sdk.TokensFromConsensusPower(1000, sdk.DefaultPowerReduction),\n\t\tStakingTokens: sdk.TokensFromConsensusPower(500, sdk.DefaultPowerReduction),\n\t\tBondedTokens: sdk.TokensFromConsensusPower(100, sdk.DefaultPowerReduction),\n\t\tPruningStrategy: storetypes.PruningOptionNothing,\n\t\tCleanupDir: true,\n\t\tSigningAlgo: string(hd.Secp256k1Type),\n\t\tKeyringOptions: []keyring.Option{},\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tPort: defaultPort,\n\t\tAutoConnect: false,\n\t\tAllowReconnect: false,\n\t\tReconnectSeconds: 5,\n\t}\n}" ]
[ "0.82165116", "0.82165116", "0.8035891", "0.8004708", "0.7986573", "0.7867194", "0.7859926", "0.77937293", "0.77280927", "0.7680712", "0.7674229", "0.76511985", "0.76475525", "0.7631691", "0.7625517", "0.76140577", "0.76140577", "0.76090723", "0.7561858", "0.7539901", "0.75247675", "0.74651974", "0.74280655", "0.742669", "0.74092627", "0.7389038", "0.73845404", "0.73801976", "0.73758096", "0.7373121", "0.73622066", "0.7358584", "0.7354139", "0.73532", "0.73526585", "0.73411727", "0.73411727", "0.7331997", "0.7329912", "0.7325245", "0.732361", "0.73147994", "0.7289", "0.72848314", "0.7278805", "0.7278614", "0.72576934", "0.7255748", "0.72448945", "0.7231625", "0.72078484", "0.7204477", "0.71701616", "0.7157884", "0.7156015", "0.7138554", "0.7122233", "0.71189225", "0.7114926", "0.7110643", "0.71099865", "0.71000564", "0.70906967", "0.7089082", "0.7089082", "0.7071135", "0.7063573", "0.70608175", "0.70574", "0.70532525", "0.705314", "0.70529956", "0.70433646", "0.7042433", "0.7041327", "0.7039472", "0.70365864", "0.70365345", "0.7036172", "0.7032617", "0.7031417", "0.7029519", "0.70233923", "0.701933", "0.7006772", "0.69978607", "0.6996627", "0.6984176", "0.698013", "0.69752055", "0.69744164", "0.6973384", "0.6971566", "0.6970857", "0.69681114", "0.6966287", "0.69587475", "0.69444", "0.6939996", "0.6939426" ]
0.743386
22
this is the initial request we direct the user's browser to. It is sent to the oidc auth endpoint and starts the whole flow.
func GenerateAuthURL(state, redirectURL string) (authUrl string) { base, _ := url.Parse(discoveryCache.AuthEndpoint) // construct query params params := url.Values{} params.Set("response_type", "code") params.Set("scope", "openid foundation_profile") params.Set("client_id", viper.GetString("oidc.client_id")) params.Set("state", state) params.Set("request", createRequestJWT(state, redirectURL)) base.RawQuery = params.Encode() log.Debugf("auth URL was constructed with state: %s", state) return base.String() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Request(wellKnownConfig oidc.WellKnownConfiguration, client OidcClient) error {\n\t// from original code\n\tcodeVerifier := \"\"\n\tcodeChallenge := \"\"\n\n\tstate, stateErr := oidc.GenerateRandomStringURLSafe(24)\n\tif stateErr != nil {\n\t\treturn fmt.Errorf(\"failed to generate random state. Check that your OS has a crypto implementation available\")\n\t}\n\n\tauthorisationURL, err := oidc.BuildCodeAuthorisationRequest(\n\t\twellKnownConfig,\n\t\tclient.ClientID,\n\t\tclient.RedirectURL.String(),\n\t\tclient.Scopes,\n\t\tstate,\n\t\tcodeChallenge,\n\t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to build authorisation request %w\", err)\n\t}\n\n\tm := http.NewServeMux()\n\ts := http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", client.RedirectURL.Port()),\n\t\tHandler: m,\n\t}\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tdefer cancel()\n\n\t// Open a web server to receive the redirect\n\tm.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\thandleOidcCallback(w, r,\n\t\t\tclient.Alias,\n\t\t\tclient.ClientID,\n\t\t\tclient.ClientSecret,\n\t\t\tclient.RedirectURL.String(),\n\t\t\twellKnownConfig,\n\t\t\tstate,\n\t\t\tcodeVerifier,\n\t\t\tcancel,\n\t\t)\n\t})\n\n\tfmt.Println(\"Open browser to\", authorisationURL)\n\n\tgo func() {\n\t\tif err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\t// Shutdown the server when the context is canceled\n\t\terr := s.Shutdown(ctx)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func beginAuth(w http.ResponseWriter, r *http.Request) {\n\tgothic.BeginAuthHandler(w, r)\n}", "func rootHandler(w http.ResponseWriter, r *http.Request) {\n\n\tif !verifyLogin(r) {\n\t\turl := LoginCfg.AuthCodeURL(\"\")\n\t\turl = url + OauthURLParams\n\t\t// this will preseve the casenumber in the URI path during Oauth2 redirect\n\t\tparams := r.URL.Query()\n\t\tparamkeys := make([]string, 0)\n\t\tfor k := range params {\n\t\t\tfor i := range params[k] {\n\t\t\t\tparamkeys = append(paramkeys, k+\"=\"+params[k][i])\n\t\t\t}\n\t\t}\n\t\tif len(paramkeys) > 0 {\n\t\t\turl = url + \"&state=\" + base64.StdEncoding.EncodeToString([]byte(strings.Join(paramkeys, \"?\")))\n\t\t}\n\n\t\thttp.Redirect(w, r, url, http.StatusFound)\n\t\treturn\n\t}\n\n\t// if user is not using https then redirect them\n\tif ( r.Header.Get(\"x-forwarded-proto\") != \"https\" && BASEURL != LOCALBASEURL) {\n\t\tfmt.Printf(\"TLS handshake is https=false x-forwarded-proto=%s\\n\", r.Header.Get(\"x-forwarded-proto\"))\n\t\thttp.Redirect(w, r, BASEURL, http.StatusFound)\n\t\treturn\n\t}\n\n startPageTemplate.Execute(w, \"\")\n}", "func StartAuthFlow(u user.User, w http.ResponseWriter, r *http.Request) {\n\ttype request struct {\n\t\tAuthHost string `json:\"authHost\"`\n\t}\n\n\ttype response struct {\n\t\tRedirect string `json:\"redirect\"`\n\t}\n\n\tvar authRequest request\n\tp, err := io.ReadAll(r.Body)\n\tif err != nil {\n\t\tcontrollers.WriteSimpleResponse(w, false, err.Error())\n\t\treturn\n\t}\n\n\tif err := json.Unmarshal(p, &authRequest); err != nil {\n\t\tcontrollers.WriteSimpleResponse(w, false, err.Error())\n\t\treturn\n\t}\n\n\taccessToken := r.URL.Query().Get(\"accessToken\")\n\n\tredirectURL, err := ia.StartAuthFlow(authRequest.AuthHost, u.ID, accessToken, u.DisplayName)\n\tif err != nil {\n\t\tcontrollers.WriteSimpleResponse(w, false, err.Error())\n\t\treturn\n\t}\n\n\tredirectResponse := response{\n\t\tRedirect: redirectURL.String(),\n\t}\n\tcontrollers.WriteResponse(w, redirectResponse)\n}", "func BeginAuthHandler(res http.ResponseWriter, req *http.Request) {\n\turl, err := GetAuthURL(res, req)\n\tif err != nil {\n\t\tres.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintln(res, err)\n\t\treturn\n\t}\n\n\thttp.Redirect(res, req, url, http.StatusTemporaryRedirect)\n}", "func (o *oidcServer) Authenticate(w http.ResponseWriter, r *http.Request) {\n\n\to.Lock()\n\tdefer o.Unlock()\n\n\tzap.L().Debug(\"Authenticating\")\n\n\tif o.serverFlow == ServerFlowTypeAuthFailure {\n\t\thttp.Error(w, \"Authentication failure\", http.StatusUnauthorized)\n\t\tzap.L().Warn(\"Authentication failure\", zap.Reflect(\"type\", o.serverFlow))\n\t\treturn\n\t}\n\n\tstate := r.URL.Query().Get(\"state\")\n\tredURI := r.URL.Query().Get(\"redirect_uri\")\n\n\treqURI, err := url.ParseRequestURI(redURI)\n\tif err != nil {\n\t\tzap.L().Error(\"Unable to parse redirect uri\", zap.Error(err))\n\t\treturn\n\t}\n\n\tq := reqURI.Query()\n\tq.Add(\"state\", state)\n\tq.Add(\"redirect_uri\", redURI)\n\treqURI.RawQuery = q.Encode()\n\n\thttp.Redirect(w, r, reqURI.String(), http.StatusTemporaryRedirect)\n}", "func (a *AuthService) BeginAuthorization(res http.ResponseWriter, req *http.Request) {\n\tsession := a.getSession(req)\n\tstate := a.getState(req)\n\tsession.Values[stateValue] = state\n\tsession.Save(req, res)\n\turl := a.OAuthConfig.AuthCodeURL(state, oauth2.AccessTypeOnline)\n\thttp.Redirect(res, req, url, http.StatusTemporaryRedirect)\n}", "func (s *Server) HandlerInitiate(w http.ResponseWriter, r *http.Request) {\n\t// ignore error because we don't need previous session values.\n\tsession, _ := s.SessionStore.Get(r, s.Config.SessionName)\n\n\tconf := s.ProviderConfigs[s.DefaultProvider].Config()\n\tcallback := r.Header.Get(\"x-ngx-omniauth-initiate-callback\")\n\tnext := r.Header.Get(\"x-ngx-omniauth-initiate-back-to\")\n\tstate := generateNewState()\n\n\tconf.RedirectURL = callback\n\tsession.Values = map[interface{}]interface{}{}\n\tsession.Values[\"provider\"] = s.DefaultProvider\n\tsession.Values[\"callback\"] = callback\n\tsession.Values[\"next\"] = next\n\tsession.Values[\"state\"] = state\n\tif err := session.Save(r, w); err != nil {\n\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\"err\": err.Error(),\n\t\t}).Error(\"failed to save session\")\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t}\n\n\thttp.Redirect(w, r, conf.AuthCodeURL(state), http.StatusFound)\n}", "func (p *Proxy) OAuthStart(w http.ResponseWriter, r *http.Request) {\n\trequestURI := r.URL.String()\n\tcallbackURL := p.GetRedirectURL(r.Host)\n\n\t// state prevents cross site forgery and maintain state across the client and server\n\tstate := &StateParameter{\n\t\tSessionID: fmt.Sprintf(\"%x\", cryptutil.GenerateKey()), // nonce\n\t\tRedirectURI: requestURI, // where to redirect the user back to\n\t}\n\n\t// we encrypt this value to be opaque the browser cookie\n\t// this value will be unique since we always use a randomized nonce as part of marshaling\n\tencryptedCSRF, err := p.cipher.Marshal(state)\n\tif err != nil {\n\t\tlog.FromRequest(r).Error().Err(err).Msg(\"proxy: failed to marshal csrf\")\n\t\thttputil.ErrorResponse(w, r, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tp.csrfStore.SetCSRF(w, r, encryptedCSRF)\n\n\t// we encrypt this value to be opaque the uri query value\n\t// this value will be unique since we always use a randomized nonce as part of marshaling\n\tencryptedState, err := p.cipher.Marshal(state)\n\tif err != nil {\n\t\tlog.FromRequest(r).Error().Err(err).Msg(\"proxy: failed to encrypt cookie\")\n\t\thttputil.ErrorResponse(w, r, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tsigninURL := p.GetSignInURL(p.AuthenticateURL, callbackURL, encryptedState)\n\tlog.FromRequest(r).Info().Str(\"SigninURL\", signinURL.String()).Msg(\"proxy: oauth start\")\n\t// redirect the user to the authenticate provider along with the encrypted state which\n\t// contains a redirect uri pointing back to the proxy\n\thttp.Redirect(w, r, signinURL.String(), http.StatusFound)\n}", "func (p *Proxy) startAuthN(w http.ResponseWriter, r *http.Request) error {\n\tstate := p.state.Load()\n\turiString := r.FormValue(urlutil.QueryForwardAuthURI)\n\tif uriString == \"\" {\n\t\turiString = \"https://\" + // always use HTTPS for external urls\n\t\t\tr.Header.Get(httputil.HeaderForwardedHost) +\n\t\t\tr.Header.Get(httputil.HeaderForwardedURI)\n\t}\n\turi, err := urlutil.ParseAndValidateURL(uriString)\n\tif err != nil {\n\t\treturn httputil.NewError(http.StatusBadRequest, err)\n\t}\n\t// add any non-empty existing path from the forwarded URI\n\tif xfu := r.Header.Get(httputil.HeaderForwardedURI); xfu != \"\" && xfu != \"/\" {\n\t\turi.Path = xfu\n\t}\n\n\tauthN := *state.authenticateSigninURL\n\tq := authN.Query()\n\tq.Set(urlutil.QueryCallbackURI, uri.String())\n\tq.Set(urlutil.QueryRedirectURI, uri.String()) // final destination\n\tq.Set(urlutil.QueryForwardAuth, urlutil.StripPort(r.Host)) // add fwd auth to trusted audience\n\tauthN.RawQuery = q.Encode()\n\thttputil.Redirect(w, r, urlutil.NewSignedURL(state.sharedKey, &authN).String(), http.StatusFound)\n\treturn nil\n}", "func (p *OAuthProxy) OAuthStart(rw http.ResponseWriter, req *http.Request, tags []string) {\n\t// The proxy redirects to the authenticator, and provides it with redirectURI (which points\n\t// back to the sso proxy).\n\tlogger := log.NewLogEntry()\n\tremoteAddr := getRemoteAddr(req)\n\n\tif p.isXHR(req) {\n\t\tlogger.WithRemoteAddress(remoteAddr).Error(\"aborting start of oauth flow on XHR\")\n\t\tp.XHRError(rw, req, http.StatusUnauthorized, errors.New(\"cannot continue oauth flow on xhr\"))\n\t\treturn\n\t}\n\n\trequestURI := req.URL.String()\n\tcallbackURL := p.GetRedirectURL(req.Host)\n\n\t// We redirect the browser to the authenticator with a 302 status code. The target URL is\n\t// constructed using the GetSignInURL() method, which encodes the following data:\n\t//\n\t// * client_id: Defined by the OAuth2 RFC https://tools.ietf.org/html/rfc6749.\n\t// Identifies the application requesting authentication information,\n\t// from our perspective this will always be static since the client\n\t// will always be sso proxy\n\t//\n\t// * redirect_uri: Defined by the OAuth2 RFC https://tools.ietf.org/html/rfc6749.\n\t// Informs the authenticator _where_ to redirect the user back to once\n\t// they have authenticated with the auth provider and given us permission\n\t// to access their auth information\n\t//\n\t// * response_type: Defined by the OAuth2 RFC https://tools.ietf.org/html/rfc6749.\n\t// Required by the spec and must be set to \"code\"\n\t//\n\t// * scope: Defined by the OAuth2 RFC https://tools.ietf.org/html/rfc6749.\n\t// Used to offer different auth scopes, but will be unnecessary in the context of SSO.\n\t//\n\t// * state: Defined by the OAuth2 RFC https://tools.ietf.org/html/rfc6749.\n\t// Used to prevent cross site forgery and maintain state across the client and server.\n\n\tkey := aead.GenerateKey()\n\n\tstate := &StateParameter{\n\t\tSessionID: fmt.Sprintf(\"%x\", key),\n\t\tRedirectURI: requestURI,\n\t}\n\n\t// we encrypt this value to be opaque the browser cookie\n\t// this value will be unique since we always use a randomized nonce as part of marshaling\n\tencryptedCSRF, err := p.cookieCipher.Marshal(state)\n\tif err != nil {\n\t\ttags = append(tags, \"csrf_token_error\")\n\t\tp.StatsdClient.Incr(\"application_error\", tags, 1.0)\n\t\tlogger.Error(err, \"failed to marshal state parameter for CSRF token\")\n\t\tp.ErrorPage(rw, req, http.StatusInternalServerError, \"Internal Error\", err.Error())\n\t\treturn\n\t}\n\tp.csrfStore.SetCSRF(rw, req, encryptedCSRF)\n\n\t// we encrypt this value to be opaque the uri query value\n\t// this value will be unique since we always use a randomized nonce as part of marshaling\n\tencryptedState, err := p.cookieCipher.Marshal(state)\n\tif err != nil {\n\t\ttags = append(tags, \"error:marshaling_state_parameter\")\n\t\tp.StatsdClient.Incr(\"application_error\", tags, 1.0)\n\t\tlogger.Error(err, \"failed to marshal state parameter for state query parameter\")\n\t\tp.ErrorPage(rw, req, http.StatusInternalServerError, \"Internal Error\", err.Error())\n\t\treturn\n\t}\n\n\tsigninURL := p.provider.GetSignInURL(callbackURL, encryptedState)\n\tlogger.WithSignInURL(signinURL).Info(\"starting OAuth flow\")\n\thttp.Redirect(rw, req, signinURL.String(), http.StatusFound)\n}", "func (a *Authenticator) Start(w http.ResponseWriter, r *http.Request, destinationPath string) error {\n\n\tif destinationPath[0] != '/' {\n\t\treturn fmt.Errorf(\"googlelogin: destinationPath must be absolute\")\n\t}\n\n\t// generate state to prevent CSRF: https://tools.ietf.org/html/rfc6749#section-10.12\n\tstate, err := makeState()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsession := &authState{nil, state, destinationPath}\n\terr = a.saveSession(w, session)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstateSerialized := base64.RawURLEncoding.EncodeToString(session.State)\n\tlog.Printf(\"oauth state param = %s\", stateSerialized)\n\n\t// AccessTypeOnline only gives us an access token without a refresh token (lower security risk)\n\t// use \"auto\" to get no prompt on \"refresh\"\n\turl := a.oauthConfig.AuthCodeURL(stateSerialized, oauth2.AccessTypeOnline,\n\t\toauth2.SetAuthURLParam(\"approval_prompt\", \"auto\"))\n\thttp.Redirect(w, r, url, http.StatusFound)\n\treturn nil\n}", "func askForLogin(w http.ResponseWriter, r *http.Request) {\n\thttp.Redirect(w, r, oauthProviderConfig.oauthConfig.AuthCodeURL(\"\"), http.StatusFound)\n}", "func (a *loginAPI) HandleOIDCLogin(w http.ResponseWriter, r *http.Request) error {\n\tctx := context.Background()\n\n\t// read the stateParam again\n\tstate := a.appCookie.Get(stateParam, r)\n\tlog.WithField(\"func\", \"server.HandleOIDCLogin\").Debugf(\"got state param: %s\", state)\n\n\tif query(r, stateParam) != state {\n\t\treturn errors.BadRequestError{Err: fmt.Errorf(\"state did not match\"), Request: r}\n\t}\n\ta.appCookie.Del(stateParam, w)\n\n\t// is this an auth/flow request\n\tvar (\n\t\tauthFlow bool\n\t\tsite, redirect string\n\t)\n\tauthFlowParams := a.appCookie.Get(authFlowCookie, r)\n\tif authFlowParams != \"\" {\n\t\tlog.WithField(\"func\", \"server.HandleOIDCLogin\").Debugf(\"auth/flow login-mode\")\n\t\tparts := strings.Split(authFlowParams, \"|\")\n\t\tsite = parts[0]\n\t\tredirect = parts[1]\n\t\tauthFlow = true\n\t}\n\ta.appCookie.Del(authFlowCookie, w)\n\n\toauth2Token, err := a.oauthConfig.Exchange(ctx, query(r, codeParam))\n\tif err != nil {\n\t\treturn errors.ServerError{Err: fmt.Errorf(\"failed to exchange token: %v\", err), Request: r}\n\t}\n\trawIDToken, ok := oauth2Token.Extra(idTokenParam).(string)\n\tif !ok {\n\t\treturn errors.ServerError{Err: fmt.Errorf(\"no id_token field in oauth2 token\"), Request: r}\n\t}\n\tidToken, err := a.oauthVerifier.VerifyToken(ctx, rawIDToken)\n\tif err != nil {\n\t\treturn errors.ServerError{Err: fmt.Errorf(\"failed to verify ID Token: %v\", err), Request: r}\n\t}\n\n\tvar oidcClaims struct {\n\t\tEmail string `json:\"email\"`\n\t\tEmailVerified bool `json:\"email_verified\"`\n\t\tDisplayName string `json:\"name\"`\n\t\tPicURL string `json:\"picture\"`\n\t\tGivenName string `json:\"given_name\"`\n\t\tFamilyName string `json:\"family_name\"`\n\t\tLocale string `json:\"locale\"`\n\t\tUserID string `json:\"sub\"`\n\t}\n\n\tif err := idToken.GetClaims(&oidcClaims); err != nil {\n\t\treturn errors.ServerError{Err: fmt.Errorf(\"claims error: %v\", err), Request: r}\n\t}\n\n\t// the user was authenticated successfully, check if sites are available for the given user!\n\tsuccess := true\n\tsites, err := a.repo.GetSitesByUser(oidcClaims.Email)\n\tif err != nil {\n\t\tlog.WithField(\"func\", \"server.HandleOIDCLogin\").Warnf(\"successfull login by '%s' but error fetching sites! %v\", oidcClaims.Email, err)\n\t\tsuccess = false\n\t}\n\n\tif len(sites) == 0 {\n\t\tlog.WithField(\"func\", \"server.HandleOIDCLogin\").Warnf(\"successfull login by '%s' but no sites availabel!\", oidcClaims.Email)\n\t\tsuccess = false\n\t}\n\n\tif authFlow {\n\t\tlog.WithField(\"func\", \"server.HandleOIDCLogin\").Debugf(\"auth/flow - check for specific site '%s'\", site)\n\t\tsuccess = false\n\t\t// check specific site\n\t\tfor _, e := range sites {\n\t\t\tif e.Name == site {\n\t\t\t\tsuccess = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif !success {\n\t\ta.appCookie.Set(errors.FlashKeyError, fmt.Sprintf(\"User '%s' is not allowed to login!\", oidcClaims.Email), cookieExpiry, w)\n\t\thttp.Redirect(w, r, \"/error\", http.StatusTemporaryRedirect)\n\t\treturn nil\n\t}\n\n\t// create the token using the claims of the database\n\tvar siteClaims []string\n\tfor _, s := range sites {\n\t\tsiteClaims = append(siteClaims, fmt.Sprintf(\"%s|%s|%s\", s.Name, s.URL, s.PermList))\n\t}\n\tclaims := security.Claims{\n\t\tType: \"login.User\",\n\t\tDisplayName: oidcClaims.DisplayName,\n\t\tEmail: oidcClaims.Email,\n\t\tUserID: oidcClaims.UserID,\n\t\tUserName: oidcClaims.Email,\n\t\tGivenName: oidcClaims.GivenName,\n\t\tSurname: oidcClaims.FamilyName,\n\t\tClaims: siteClaims,\n\t}\n\ttoken, err := security.CreateToken(a.jwt.JwtIssuer, []byte(a.jwt.JwtSecret), a.jwt.Expiry, claims)\n\tif err != nil {\n\t\tlog.WithField(\"func\", \"server.HandleOIDCLogin\").Errorf(\"could not create a JWT token: %v\", err)\n\t\treturn errors.ServerError{Err: fmt.Errorf(\"error creating JWT: %v\", err), Request: r}\n\t}\n\n\tlogin := persistence.Login{\n\t\tUser: oidcClaims.Email,\n\t\tCreated: time.Now().UTC(),\n\t\tType: persistence.DIRECT,\n\t}\n\n\tif authFlow {\n\t\tlogin.Type = persistence.FLOW\n\t}\n\n\terr = a.repo.StoreLogin(login, per.Atomic{})\n\tif err != nil {\n\t\tlog.WithField(\"func\", \"server.HandleOIDCLogin\").Errorf(\"the login could not be saved: %v\", err)\n\t\treturn errors.ServerError{Err: fmt.Errorf(\"error storing the login: %v\", err), Request: r}\n\t}\n\n\t// set the cookie\n\texp := a.jwt.Expiry * 24 * 3600\n\ta.setJWTCookie(a.jwt.CookieName, token, exp, w)\n\n\tredirectURL := a.jwt.LoginRedirect\n\tif authFlow {\n\t\tlog.WithField(\"func\", \"server.HandleOIDCLogin\").Debugf(\"auth/flow - redirect to specific URL: '%s'\", redirect)\n\t\tredirectURL = redirect\n\t}\n\n\t// redirect to provided URL\n\thttp.Redirect(w, r, redirectURL, http.StatusTemporaryRedirect)\n\treturn nil\n}", "func (g *Google) BeginAuth(c *gin.Context) {\n\tdestination := c.Query(\"destination\")\n\n\tg.InitOauthConfig(destination)\n\n\turl := g.oauthConf.AuthCodeURL(utils.Cfg.OauthSettings.GoogleSettings.Statestr)\n\n\tc.Redirect(http.StatusTemporaryRedirect, url)\n}", "func handleAuthorize(rw http.ResponseWriter, req *http.Request) {\n\n\t// Get the Google URL which shows the Authentication page to the user.\n\turl := oauthCfg.AuthCodeURL(\"\")\n\n\t// Redirect user to that page.\n\thttp.Redirect(rw, req, url, http.StatusFound)\n}", "func (a *App) AuthWorkflow() {\n\twebapp := &Webapp{}\n\tbackend := NewBackend()\n\n\topen.Start(backend.AuthURL())\n\tfmt.Println(\"Head to your browser to complete authorization steps.\")\n\tfmt.Println(\"Listening for response...\")\n\twebapp.Run()\n}", "func OauthRequest(rData *pages.RequestData) {\n\n\tstate := StateInfo{\n\t\tDestination: rData.HttpRequest.FormValue(\"dest\"),\n\t\tScheme: rData.HttpRequest.FormValue(\"scheme\"),\n\t\tProvider: rData.HttpRequest.FormValue(\"provider\"),\n\t\tRequest: rData.HttpRequest.FormValue(\"request\"),\n\t\tRequestMeta: rData.HttpRequest.FormValue(\"meta\"),\n\t}\n\n\tif !slice.StringInSlice(state.Destination, OAUTH_ALLOWED_DESTINATIONS) || !slice.StringInSlice(state.Scheme, rData.SiteConfig.OAUTH_ALLOWED_SCHEMES) || !slice.StringInSlice(state.Provider, OAUTH_ALLOWED_PROVIDERS) || !slice.StringInSlice(state.Request, OAUTH_ALLOWED_REQUESTS) {\n\t\trData.SetJsonErrorCodeResponse(statuscodes.TECHNICAL)\n\t\treturn\n\t}\n\n\tstateBytes, err := json.Marshal(state)\n\tif err != nil {\n\t\trData.SetJsonErrorCodeResponse(statuscodes.TECHNICAL)\n\t\treturn\n\t}\n\n\t_, stateJwtString, err := auth.GetNewSystemsOobJWT(rData, auth.SYSTEM_ID_OAUTH, jwt_scopes.OAUTH_STATE, string(stateBytes))\n\tif err != nil {\n\t\trData.SetJsonErrorCodeResponse(statuscodes.TECHNICAL)\n\t\treturn\n\t}\n\n\tendpoint := getEndpointConfig(rData, &state)\n\tif endpoint == nil {\n\t\trData.SetJsonErrorCodeResponse(statuscodes.TECHNICAL)\n\t\treturn\n\t}\n\n\tauthUrl := endpoint.AuthCodeURL(stateJwtString, oauth2.ApprovalForce, oauth2.AccessTypeOnline)\n\n\tauthUrlFormatted := fmt.Sprintf(\"%s\", authUrl)\n\trData.LogInfo(authUrlFormatted)\n\n\trData.SetJsonSuccessResponse(pages.JsonMapGeneric{\n\t\t\"url\": authUrlFormatted,\n\t})\n}", "func OAUTHRedirect(ctx *fiber.Ctx) error {\n\n\tmodels.SYSLOG.Tracef(\"entering OAUTHRedirect; original URL: %v\", ctx.OriginalURL())\n\tdefer models.SYSLOG.Trace(\"exiting OAUTHRedirect\")\n\n\t// First, we need to get the value of the `code` query param\n\tcode := ctx.Query(\"code\", \"\")\n\tif len(code) < 1 {\n\t\treturn ctx.SendStatus(fiber.StatusBadRequest)\n\t}\n\n\t// Next, lets for the HTTP request to call the github oauth enpoint\tto get our access token\n\n\ta := fiber.AcquireAgent()\n\treq := a.Request()\n\treq.Header.SetMethod(fiber.MethodPost)\n\treq.Header.Set(\"accept\", \"application/json\")\n\treq.SetRequestURI(fmt.Sprintf(\"https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s\", models.ClientID, models.ClientSecret, code))\n\tif err := a.Parse(); err != nil {\n\t\tmodels.SYSLOG.Errorf(\"could not create HTTP request: %v\", err)\n\t}\n\n\tvar retCode int\n\tvar retBody []byte\n\tvar errs []error\n\t// Send out the HTTP request\n\tvar t *models.OAuthAccessResponse\n\n\tif retCode, retBody, errs = a.Struct(&t); len(errs) > 0 {\n\t\tmodels.SYSLOG.Tracef(\"received: %v\", string(retBody))\n\t\tmodels.SYSLOG.Errorf(\"could not send HTTP request: %v\", errs)\n\t\treturn ctx.SendStatus(fiber.StatusInternalServerError)\n\t}\n\tmodels.SYSLOG.Tracef(\"received : %v %v %v\", retCode, string(retBody), errs)\n\n\tvar sess *session.Session\n\tvar err error\n\t// Finally, send a response to redirect the user to the \"welcome\" page with the access token\n\tif sess, err = models.MySessionStore.Get(ctx); err == nil {\n\t\tsess.Set(\"token\", t.AccessToken)\n\t\tmodels.SYSLOG.Tracef(\"setting session token %v\", t.AccessToken)\n\t\tsessData, _ := models.MySessionStore.Get(ctx)\n\t\tdefer sessData.Save()\n\t\t//models.MySessionStore.RegisterType(models.OAuthAccessResponse)\n\t\tsessData.Set(\"oauth-scope\", t.Scope)\n\t\tsessData.Set(\"oauth-token-type\", t.TokenType)\n\t\tsessData.Set(\"oauth-token\", t.AccessToken)\n\n\t\tif err != nil {\n\t\t\tmodels.SYSLOG.Errorf(\"session saving exception %v\", err)\n\t\t}\n\t\tmodels.SYSLOG.Tracef(\"redirecting to /welcome.html?access_token=%v\", t.AccessToken)\n\t\t//\t\treturn ctx.Redirect(\"/welcome.html?access_token=\"+t.AccessToken, fiber.StatusFound)\n\t\treturn ctx.Redirect(\"/welcome.html\", fiber.StatusFound)\n\t}\n\n\tmodels.SYSLOG.Tracef(\"redirecting to /\")\n\treturn ctx.Redirect(\"/\", fiber.StatusTemporaryRedirect)\n}", "func authEndpoint(rw http.ResponseWriter, req *http.Request) {\n\n\t// request has to be POST\n\tif req.Method != \"POST\" {\n\t\thttp.Error(rw, \"bad method, only post allowed\", http.StatusBadRequest)\n\t}\n\n\t// has to be authenticated, in a real we would use soemthing more\n\t// secure like certificates etc.\n\tuser, _, ok := req.BasicAuth()\n\n\tif !ok {\n\t\thttp.Error(rw, \"authentication required\", http.StatusForbidden)\n\t}\n\n\tlog.Println(\"basic authentication successful for \", user)\n\n\t// now we issue token and return it\n\n\t// This context will be passed to all methods.\n\tctx := req.Context()\n\n\t// Create an empty session object which will be passed to the request handlers\n\tmySessionData := newSession(\"\")\n\n\t// This will create an access request object and iterate through the registered TokenEndpointHandlers to validate the request.\n\taccessRequest, err := fositeInstance.NewAccessRequest(ctx, req, mySessionData)\n\n\t// Catch any errors, e.g.:\n\t// * unknown client\n\t// * invalid redirect\n\t// * ...\n\tif err != nil {\n\t\tlog.Printf(\"Error occurred in NewAccessRequest: %+v\", err)\n\t\tfositeInstance.WriteAccessError(rw, accessRequest, err)\n\t\treturn\n\t}\n\n\t// If this is a client_credentials grant, grant all requested scopes\n\t// NewAccessRequest validated that all requested scopes the client is allowed to perform\n\t// based on configured scope matching strategy.\n\tif accessRequest.GetGrantTypes().ExactOne(\"client_credentials\") {\n\t\tfor _, scope := range accessRequest.GetRequestedScopes() {\n\t\t\taccessRequest.GrantScope(scope)\n\t\t}\n\t}\n\n\t// Next we create a response for the access request. Again, we iterate through the TokenEndpointHandlers\n\t// and aggregate the result in response.\n\tresponse, err := fositeInstance.NewAccessResponse(ctx, accessRequest)\n\tif err != nil {\n\t\tlog.Printf(\"Error occurred in NewAccessResponse: %+v\", err)\n\t\tfositeInstance.WriteAccessError(rw, accessRequest, err)\n\t\treturn\n\t}\n\n\t// All done, send the response.\n\tfositeInstance.WriteAccessResponse(rw, accessRequest, response)\n\n}", "func (p *OAuthProxy) Authenticate(rw http.ResponseWriter, req *http.Request) (err error) {\n\tlogger := log.NewLogEntry().WithRemoteAddress(getRemoteAddr(req))\n\n\tremoteAddr := getRemoteAddr(req)\n\ttags := []string{\"action:authenticate\"}\n\n\tallowedGroups := p.upstreamConfig.AllowedGroups\n\n\t// Clear the session cookie if anything goes wrong.\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tp.sessionStore.ClearSession(rw, req)\n\t\t}\n\t}()\n\n\tsession, err := p.sessionStore.LoadSession(req)\n\tif err != nil {\n\t\t// We loaded a cookie but it wasn't valid, clear it, and reject the request\n\t\tlogger.Error(err, \"error authenticating user\")\n\t\treturn err\n\t}\n\n\t// check if this session belongs to the correct identity provider application.\n\t// this case exists primarly to allow us to gracefully manage a clean ux during\n\t// transitions from one provider to another by gracefully restarting the authentication process.\n\tif session.ProviderSlug != p.provider.Data().ProviderSlug {\n\t\tlogger.WithUser(session.Email).Info(\n\t\t\t\"authenticated with incorrect identity provider; restarting authentication\")\n\t\treturn ErrWrongIdentityProvider\n\t}\n\n\t// check that the user has been authorized against the requested upstream\n\t// this is primarily to combat against a user authorizing with one upstream and attempting to use\n\t// the session cookie for a different upstream.\n\tif req.Host != session.AuthorizedUpstream {\n\t\tlogger.WithProxyHost(req.Host).WithAuthorizedUpstream(session.AuthorizedUpstream).WithUser(session.Email).Warn(\n\t\t\t\"session authorized against different upstream; restarting authentication\")\n\t\treturn ErrUnauthorizedUpstreamRequested\n\t}\n\n\t// Lifetime period is the entire duration in which the session is valid.\n\t// This should be set to something like 14 to 30 days.\n\tif session.LifetimePeriodExpired() {\n\t\t// session lifetime has expired, we reject the request and clear the cookie\n\t\tlogger.WithUser(session.Email).Info(\n\t\t\t\"lifetime has expired; restarting authentication\")\n\t\treturn ErrLifetimeExpired\n\t} else if session.RefreshPeriodExpired() {\n\t\t// Refresh period is the period in which the access token is valid. This is ultimately\n\t\t// controlled by the upstream provider and tends to be around 1 hour.\n\t\tok, err := p.provider.RefreshSession(session, allowedGroups)\n\t\t// We failed to refresh the session successfully\n\t\t// clear the cookie and reject the request\n\t\tif err != nil {\n\t\t\tlogger.WithUser(session.Email).Error(err, \"refreshing session failed\")\n\t\t\treturn err\n\t\t}\n\n\t\tif !ok {\n\t\t\t// User is not authorized after refresh\n\t\t\t// clear the cookie and reject the request\n\t\t\tlogger.WithUser(session.Email).Info(\n\t\t\t\t\"not authorized after refreshing session\")\n\t\t\treturn ErrUserNotAuthorized\n\t\t}\n\n\t\terr = p.sessionStore.SaveSession(rw, req, session)\n\t\tif err != nil {\n\t\t\t// We refreshed the session successfully, but failed to save it.\n\t\t\t//\n\t\t\t// This could be from failing to encode the session properly.\n\t\t\t// But, we clear the session cookie and reject the request!\n\t\t\tlogger.WithUser(session.Email).Error(\n\t\t\t\terr, \"could not save refreshed session\")\n\t\t\treturn err\n\t\t}\n\t} else if session.ValidationPeriodExpired() {\n\t\t// Validation period has expired, this is the shortest interval we use to\n\t\t// check for valid requests. This should be set to something like a minute.\n\t\t// This calls up the provider chain to validate this user is still active\n\t\t// and hasn't been de-authorized.\n\t\tok := p.provider.ValidateSessionState(session, allowedGroups)\n\t\tif !ok {\n\t\t\t// This user is now no longer authorized, or we failed to\n\t\t\t// validate the user.\n\t\t\t// Clear the cookie and reject the request\n\t\t\tlogger.WithUser(session.Email).Error(\n\t\t\t\terr, \"no longer authorized after validation period\")\n\t\t\treturn ErrUserNotAuthorized\n\t\t}\n\n\t\terr = p.sessionStore.SaveSession(rw, req, session)\n\t\tif err != nil {\n\t\t\t// We validated the session successfully, but failed to save it.\n\n\t\t\t// This could be from failing to encode the session properly.\n\t\t\t// But, we clear the session cookie and reject the request!\n\t\t\tlogger.WithUser(session.Email).Error(\n\t\t\t\terr, \"could not save validated session\")\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// We revalidate group membership whenever the session is refreshed or revalidated\n\t// just above in the call to ValidateSessionState and RefreshSession.\n\t// To reduce strain on upstream identity providers we only revalidate email domains and\n\t// addresses on each request here.\n\tfor _, v := range p.Validators {\n\t\t_, EmailGroupValidator := v.(validators.EmailGroupValidator)\n\n\t\tif !EmailGroupValidator {\n\t\t\terr := v.Validate(session)\n\t\t\tif err != nil {\n\t\t\t\ttags = append(tags, \"error:validation_failed\")\n\t\t\t\tp.StatsdClient.Incr(\"application_error\", tags, 1.0)\n\t\t\t\tlogger.WithRemoteAddress(remoteAddr).WithUser(session.Email).Info(\n\t\t\t\t\tfmt.Sprintf(\"permission denied: unauthorized: %q\", err))\n\t\t\t\treturn ErrUserNotAuthorized\n\t\t\t}\n\t\t}\n\t}\n\n\tlogger.WithRemoteAddress(remoteAddr).WithUser(session.Email).Info(\n\t\tfmt.Sprintf(\"authentication: user validated\"))\n\n\tfor key, val := range p.upstreamConfig.InjectRequestHeaders {\n\t\treq.Header.Set(key, val)\n\t}\n\n\treq.Header.Set(\"X-Forwarded-User\", session.User)\n\n\tif p.upstreamConfig.PassAccessToken && session.AccessToken != \"\" {\n\t\treq.Header.Set(\"X-Forwarded-Access-Token\", session.AccessToken)\n\t}\n\n\treq.Header.Set(\"X-Forwarded-Email\", session.Email)\n\treq.Header.Set(\"X-Forwarded-Groups\", strings.Join(session.Groups, \",\"))\n\n\t// stash authenticated user so that it can be logged later (see func logRequest)\n\trw.Header().Set(loggingUserHeader, session.Email)\n\n\t// This user has been OK'd. Allow the request!\n\treturn nil\n}", "func AuthHandler(c *gin.Context) {\r\n\tvar state utils.State\r\n\tdecoded, err := utils.B64Decode(c.Query(\"state\"))\r\n\terr = json.Unmarshal([]byte(decoded), &state)\r\n\tif err != nil {\r\n\t\tc.JSON(http.StatusConflict, gin.H{\"code\": http.StatusConflict, \"message\": err})\r\n\t\treturn\r\n\t}\r\n\r\n\tAccessKey := state.AccessKey\r\n\tif AccessKey == \"\" {\r\n\t\tAccessKey = state.Token\r\n\t}\r\n\r\n\tAPPUserID, _, err := utils.LoadAccessKey(AccessKey)\r\n\r\n\tif err != nil || APPUserID == \"\" {\r\n\t\tc.JSON(http.StatusNonAuthoritativeInfo, gin.H{\"code\": http.StatusNonAuthoritativeInfo, \"message\": err})\r\n\t\treturn\r\n\t}\r\n\r\n\tfmt.Println(\"redirURL\", state.URL)\r\n\r\n\tcode := c.Query(\"code\")\r\n\tuserID, _ := utils.VerifyCode(code)\r\n\tuserInfo, _ := utils.GetUserInfo(userID)\r\n\r\n\tu := url.Values{}\r\n\tdata, _ := json.Marshal(userInfo)\r\n\tu.Set(\"state\", utils.B64Encode(string(data)))\r\n\tu.Set(\"timestamp\", fmt.Sprintln(time.Now().Unix()))\r\n\tc.Redirect(http.StatusFound, state.URL+\"?\"+u.Encode())\r\n}", "func CanvasOAuth2RequestHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tintent := r.URL.Query().Get(\"intent\")\n\tdest := r.URL.Query().Get(\"dest\")\n\tswitch intent {\n\tcase \"auth\":\n\t\tutil.SendRedirect(w, getCanvasOAuth2AuthURI(intent, dest))\n\tcase \"reauth\":\n\t\tutil.SendRedirect(w, getCanvasOAuth2AuthURI(intent, dest))\n\tdefault:\n\t\tutil.SendRedirect(w, getCanvasOAuth2AuthURI(\"auth\", dest))\n\t}\n}", "func (c *KeycloakClient) do(req *http.Request) (*http.Response, error) {\n\tlog.Println(req.Method + \" \" + req.URL.String())\n\treq.Header.Set(\"Authorization\", \"Bearer \"+c.token)\n\treturn http.DefaultClient.Do(req)\n}", "func (endpoints *endpointDetails) requestToken(w http.ResponseWriter, req *http.Request) {\n\tauthReq := endpoints.osinOAuthClient.NewAuthorizeRequest(osincli.CODE)\n\toauthURL := authReq.GetAuthorizeUrl()\n\n\thttp.Redirect(w, req, oauthURL.String(), http.StatusFound)\n}", "func RequestCredentials(w http.ResponseWriter, r *http.Request) {\n\tvar (\n\t\tidentity AuthIdentity\n\t\tcredentials AuthCredentials\n\t)\n\n\teaaCtx := r.Context().Value(contextKey(\"appliance-ctx\")).(*Context)\n\n\tconst fName = \"/Auth RequestCredentials \"\n\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\n\terr := json.NewDecoder(r.Body).Decode(&identity)\n\tif err != nil {\n\t\tlog.Errf(fName+\"decode failed: %v\", err.Error())\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thost, port, err := net.SplitHostPort(r.RemoteAddr)\n\tif err != nil {\n\t\tlog.Errf(fName+\"Cannot retrieve IP from RemoteAddr: %v [%v:%v] %v\",\n\t\t\tr.RemoteAddr, host, port, err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tcert, err := SignCSR(identity.Csr, eaaCtx)\n\tif err != nil {\n\t\tlog.Errf(fName+\"failed: %v\", err.Error())\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tsignedCertBlock := pem.EncodeToMemory(\n\t\t&pem.Block{Type: \"CERTIFICATE\", Bytes: cert.Raw})\n\tif signedCertBlock == nil {\n\t\tlog.Err(fName + \"/failed to enode signed cert\")\n\t\treturn\n\t}\n\trcaBlock := pem.EncodeToMemory(\n\t\t&pem.Block{Type: \"CERTIFICATE\",\n\t\t\tBytes: eaaCtx.certsEaaCa.rca.x509Cert.Raw})\n\tif rcaBlock == nil {\n\t\tlog.Err(fName + \"failed to enode rca cert\")\n\t\treturn\n\t}\n\n\tcredentials.ID = cert.Subject.CommonName\n\tcredentials.Certificate = string(signedCertBlock)\n\tcredentials.CaChain = []string{string(rcaBlock)}\n\tcredentials.CaPool = []string{string(rcaBlock)}\n\n\tencoder := json.NewEncoder(w)\n\terr = encoder.Encode(credentials)\n\tif err != nil {\n\t\tlog.Errf(fName+\"encoding output to JSON failed: %s\",\n\t\t\terr.Error())\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tlog.Info(fName + \" request from CN: \" + credentials.ID + \", from IP: \" +\n\t\thost + \" properly handled\")\n}", "func authHandler(w http.ResponseWriter, r *http.Request) {\n\turl := config(r.Host).AuthCodeURL(r.URL.RawQuery)\n\thttp.Redirect(w, r, url, http.StatusFound)\n}", "func (o *oidcClient) do(req *http.Request) (*http.Response, error) {\n\tresp, err := o.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Return immediately if the error is not HTTP status unauthorized.\n\tif resp.StatusCode != http.StatusUnauthorized {\n\t\treturn resp, nil\n\t}\n\n\tissuer := resp.Header.Get(\"X-Incus-OIDC-issuer\")\n\tclientID := resp.Header.Get(\"X-Incus-OIDC-clientid\")\n\taudience := resp.Header.Get(\"X-Incus-OIDC-audience\")\n\n\terr = o.refresh(issuer, clientID)\n\tif err != nil {\n\t\terr = o.authenticate(issuer, clientID, audience)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Set the new access token in the header.\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", o.tokens.AccessToken))\n\n\tresp, err = o.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func Connect(w http.ResponseWriter, r *http.Request) error {\n\tloggedIn, err := IsLoggedIn(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif loggedIn {\n\t\tglog.V(1).Infof(\"already logged in\\n\")\n\t\treturn nil\n\t}\n\n\t// Ensure that the request is not a forgery and that the user sending this\n\t// connect request is the expected user.\n\tsession, err := getSession(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tq := r.URL.Query()\n\tif session.Values[\"state\"] == nil {\n\t\treturn fmt.Errorf(\"missing %q variable in session for user trying to log in? bug, or user is trying to spoof log in\", \"state\")\n\t}\n\tsessionState := session.Values[\"state\"].(string)\n\tif q.Get(\"state\") != sessionState {\n\t\t// Note: This can happen if CheckLogIn is called multiple times\n\t\t// for the same session, e.g. when several tabs are loading\n\t\t// protected resources.\n\t\treturn fmt.Errorf(\"state mismatch, got %q from form, but had %q in session\\n\", r.FormValue(\"state\"), sessionState)\n\t}\n\tsession.Values[\"state\"] = nil\n\n\tcode := q.Get(\"code\")\n\tif code == \"\" {\n\t\treturn fmt.Errorf(\"missing %q value in request body\", \"code\")\n\t}\n\tglog.V(1).Infof(\"code=%v\\n\", code)\n\t// We got back matching state from user as well as auth code from\n\t// login button, exchange the one-time auth code for access token +\n\t// user id.\n\taccessToken, idToken, err := exchange(code)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't exchange code for access token: %v\", err)\n\t}\n\tglog.V(1).Infof(\"id token: %v\\n\", idToken)\n\tgplusId, err := decodeIdToken(idToken)\n\tglog.V(1).Infof(\"decoded G+ token: %v\\n\", gplusId)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't decode ID token: %v\", err)\n\t}\n\n\tif !isAllowed(gplusId) {\n\t\tglog.Infof(\"user with G+ %v is not allowed access\\n\", gplusId)\n\t\treturn accessDeniedErr\n\t}\n\tglog.V(1).Infof(\"User %v is allowed to log in\\n\", gplusId)\n\n\t// Store the access token in the session for later use.\n\tsession.Values[\"accessToken\"] = accessToken\n\tsession.Values[\"gplusID\"] = gplusId\n\terr = session.Save(r, w)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to save state in session: %v\", err)\n\t}\n\treturn nil\n}", "func (p *Provider) BeginAuth(state string) (goth.Session, error) {\n\turl := p.config.AuthCodeURL(state)\n\tsession := &Session{\n\t\tAuthURL: url,\n\t}\n\treturn session, nil\n}", "func (p *Provider) BeginAuth(state string) (goth.Session, error) {\n\turl := p.config.AuthCodeURL(state)\n\tsession := &Session{\n\t\tAuthURL: url,\n\t}\n\treturn session, nil\n}", "func (p *Provider) BeginAuth(state string) (goth.Session, error) {\n\turl := p.config.AuthCodeURL(state)\n\tsession := &Session{\n\t\tAuthURL: url,\n\t}\n\treturn session, nil\n}", "func (l *RemoteProvider) InitiateLogin(w http.ResponseWriter, r *http.Request, _ bool) {\n\ttu := viper.GetString(\"MESHERY_SERVER_CALLBACK_URL\")\n\tif tu == \"\" {\n\t\ttu = \"http://\" + r.Host + \"/api/user/token\" // Hard coding the path because this is what meshery expects\n\t}\n\n\t_, err := r.Cookie(tokenName)\n\t// logrus.Debugf(\"url token: %v %v\", token, err)\n\tif err != nil {\n\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\tName: l.RefCookieName,\n\t\t\tValue: \"/\",\n\t\t\tExpires: time.Now().Add(l.LoginCookieDuration),\n\t\t\tPath: \"/\",\n\t\t\tHttpOnly: true,\n\t\t})\n\t\thttp.Redirect(w, r, l.RemoteProviderURL+\"?source=\"+base64.RawURLEncoding.EncodeToString([]byte(tu))+\"&provider_version=\"+l.ProviderVersion, http.StatusFound)\n\t\treturn\n\t}\n\n\t// TODO: go to ref cookie\n\thttp.Redirect(w, r, \"/\", http.StatusFound)\n}", "func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\n\t// Extract auth code\n\tauthReq := h.client.NewAuthorizeRequest(osincli.CODE)\n\tauthData, err := authReq.HandleRequest(req)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Error handling request: %v\", err)\n\t\th.handleError(err, w, req)\n\t\treturn\n\t}\n\n\tglog.V(4).Infof(\"Got auth data\")\n\n\t// Validate state before making any server-to-server calls\n\tok, err := h.state.Check(authData.State, req)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Error verifying state: %v\", err)\n\t\th.handleError(err, w, req)\n\t\treturn\n\t}\n\tif !ok {\n\t\tglog.V(4).Infof(\"State is invalid\")\n\t\terr := errors.New(\"State is invalid\")\n\t\th.handleError(err, w, req)\n\t\treturn\n\t}\n\n\t// Exchange code for a token\n\taccessReq := h.client.NewAccessRequest(osincli.AUTHORIZATION_CODE, authData)\n\taccessData, err := accessReq.GetToken()\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Error getting access token: %v\", err)\n\t\th.handleError(err, w, req)\n\t\treturn\n\t}\n\n\tglog.V(5).Infof(\"Got access data\")\n\n\tidentity, ok, err := h.provider.GetUserIdentity(accessData)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Error getting userIdentityInfo info: %v\", err)\n\t\th.handleError(err, w, req)\n\t\treturn\n\t}\n\tif !ok {\n\t\tglog.V(4).Infof(\"Could not get userIdentityInfo info from access token\")\n\t\terr := errors.New(\"Could not get userIdentityInfo info from access token\")\n\t\th.handleError(err, w, req)\n\t\treturn\n\t}\n\n\tuser, err := h.mapper.UserFor(identity)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Error creating or updating mapping for: %#v due to %v\", identity, err)\n\t\th.handleError(err, w, req)\n\t\treturn\n\t}\n\tglog.V(4).Infof(\"Got userIdentityMapping: %#v\", user)\n\n\t_, err = h.success.AuthenticationSucceeded(user, authData.State, w, req)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Error calling success handler: %v\", err)\n\t\th.handleError(err, w, req)\n\t\treturn\n\t}\n}", "func (endpoints *endpointDetails) requestToken(w http.ResponseWriter, req *http.Request) {\n\tauthReq := endpoints.originOAuthClient.NewAuthorizeRequest(osincli.CODE)\n\toauthURL := authReq.GetAuthorizeUrlWithParams(\"\")\n\n\thttp.Redirect(w, req, oauthURL.String(), http.StatusFound)\n}", "func (p *Provider) BeginAuth(state string) (goth.Session, error) {\n\treturn &Session{\n\t\tAuthURL: p.oauthConfig.AuthCodeURL(state),\n\t}, nil\n}", "func (a *Auth) Authenticate(handler http.Handler) http.Handler {\n\tif handler == nil {\n\t\tpanic(\"auth: nil handler\")\n\t}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif a.cfg.Disable {\n\t\t\thandler.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\ttoken, err := a.getCookie(r)\n\t\tif token == nil && err == nil {\n\t\t\t// Cookie is missing, invalid. Fetch new token from OAuth2 provider.\n\t\t\t// Redirect user to the OAuth2 consent page to ask for permission for the scopes specified\n\t\t\t// above.\n\t\t\t// Set the scope to the current request URL, it will be used by the redirect handler to\n\t\t\t// redirect back to the url that requested the authentication.\n\t\t\turl := a.cfg.AuthCodeURL(r.RequestURI)\n\t\t\thttp.Redirect(w, r, url, http.StatusTemporaryRedirect)\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\ta.clearCookie(w)\n\t\t\thttp.Error(w, \"Unauthorized\", http.StatusUnauthorized)\n\t\t\ta.logf(\"Get cookie error: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\t// Source token, in case the token needs a renewal.\n\t\tnewOauth2Token, err := a.cfg.TokenSource(r.Context(), token.toOauth2()).Token()\n\t\tif err != nil {\n\t\t\ta.clearCookie(w)\n\t\t\thttp.Error(w, \"Internal error\", http.StatusInternalServerError)\n\t\t\ta.logf(\"Failed token source: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tnewToken := fromOauth2(newOauth2Token)\n\n\t\tif newToken.IDToken != token.IDToken {\n\t\t\ta.logf(\"Refreshed token\")\n\t\t\ttoken = newToken\n\t\t\ta.setCookie(w, token)\n\t\t}\n\n\t\t// Validate the id_token.\n\t\tpayload, err := a.validator.Validate(r.Context(), token.IDToken, a.cfg.ClientID)\n\t\tif err != nil {\n\t\t\ta.clearCookie(w)\n\t\t\thttp.Error(w, \"Invalid auth.\", http.StatusUnauthorized)\n\t\t\ta.logf(\"Invalid token, reset cookie: %s\", err)\n\t\t\treturn\n\t\t}\n\t\t// User is authenticated.\n\t\t// Store email and name in context, and call the inner handler.\n\t\tcreds := &Creds{\n\t\t\tEmail: payload.Claims[\"email\"].(string),\n\t\t\tName: payload.Claims[\"name\"].(string),\n\t\t}\n\t\tr = r.WithContext(context.WithValue(r.Context(), credsKey, creds))\n\t\thandler.ServeHTTP(w, r)\n\t})\n}", "func HandleRedirect(w http.ResponseWriter, r *http.Request) {\n\tstate := r.URL.Query().Get(\"state\")\n\tcode := r.URL.Query().Get(\"code\")\n\trequest, response, err := ia.HandleCallbackCode(code, state)\n\tif err != nil {\n\t\tlog.Debugln(err)\n\t\tmsg := `Unable to complete authentication. <a href=\"/\">Go back.</a><hr/>`\n\t\t_ = controllers.WriteString(w, msg, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Check if a user with this auth already exists, if so, log them in.\n\tif u := auth.GetUserByAuth(response.Me, auth.IndieAuth); u != nil {\n\t\t// Handle existing auth.\n\t\tlog.Debugln(\"user with provided indieauth already exists, logging them in\")\n\n\t\t// Update the current user's access token to point to the existing user id.\n\t\taccessToken := request.CurrentAccessToken\n\t\tuserID := u.ID\n\t\tif err := user.SetAccessTokenToOwner(accessToken, userID); err != nil {\n\t\t\tcontrollers.WriteSimpleResponse(w, false, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tif request.DisplayName != u.DisplayName {\n\t\t\tloginMessage := fmt.Sprintf(\"**%s** is now authenticated as **%s**\", request.DisplayName, u.DisplayName)\n\t\t\tif err := chat.SendSystemAction(loginMessage, true); err != nil {\n\t\t\t\tlog.Errorln(err)\n\t\t\t}\n\t\t}\n\n\t\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n\n\t\treturn\n\t}\n\n\t// Otherwise, save this as new auth.\n\tlog.Debug(\"indieauth token does not already exist, saving it as a new one for the current user\")\n\tif err := auth.AddAuth(request.UserID, response.Me, auth.IndieAuth); err != nil {\n\t\tcontrollers.WriteSimpleResponse(w, false, err.Error())\n\t\treturn\n\t}\n\n\t// Update the current user's authenticated flag so we can show it in\n\t// the chat UI.\n\tif err := user.SetUserAsAuthenticated(request.UserID); err != nil {\n\t\tlog.Errorln(err)\n\t}\n\n\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n}", "func AuthController(res http.ResponseWriter, req *http.Request) {\n\tgothic.BeginAuthHandler(res, req)\n}", "func (a *loginAPI) HandleAuthFlow(w http.ResponseWriter, r *http.Request) error {\n\tstate := randToken()\n\ta.appCookie.Set(stateParam, state, cookieExpiry, w)\n\tlog.WithField(\"func\", \"server.HandleAuthFlow\").Debugf(\"initiate using state '%s'\", state)\n\n\tsite, redirect := query(r, siteParam), query(r, redirectParam)\n\tif site == \"\" || redirect == \"\" {\n\t\treturn errors.BadRequestError{Err: fmt.Errorf(\"missing or invalid parameters supplied\"), Request: r}\n\t}\n\ta.appCookie.Set(authFlowCookie, fmt.Sprintf(\"%s%s%s\", site, authFlowSep, redirect), cookieExpiry, w)\n\thttp.Redirect(w, r, a.GetOIDCRedirectURL(), http.StatusTemporaryRedirect)\n\treturn nil\n}", "func RequestTokenUsingAuthorizationCode(env *Environment) gin.HandlerFunc {\n fn := func(c *gin.Context) {\n log := c.MustGet(env.Constants.LogKey).(*logrus.Entry)\n log = log.WithFields(logrus.Fields{\n \"func\": \"RequestTokenUsingAuthorizationCode\",\n })\n\n error := c.Query(\"error\"); // Hydra specific error handling\n if error != \"\" {\n c.AbortWithStatus(http.StatusBadRequest)\n return\n }\n\n oauth2Config := FetchOAuth2Config(env, c)\n if oauth2Config == nil {\n log.Debug(\"Missing oauth2 config. Hint: Oauth2 config is missing from context. Did you call ConfigureOauth2 before calling RequestTokenUsingAuthorizationCode?\")\n c.AbortWithStatus(http.StatusInternalServerError)\n return\n }\n\n code := c.Query(\"code\")\n if code == \"\" {\n // Unauthorized, request an access token for required scopes only using authorization code flow.\n // TODO: Add pkce\n\n idTokenHint := IdTokenHint(env, c)\n\n // Use precalculated state iff present\n state := FetchPrecalculatedState(env, c)\n\n initUrl, err := StartAuthenticationSession(env, c, oauth2Config, idTokenHint, state)\n if err != nil {\n log.Debug(err.Error())\n c.AbortWithStatus(http.StatusInternalServerError)\n return\n }\n\n // This is not allowed by ORY Hydra even though the url (without params) is registered to the client\n /*emailChallenge := c.Query(\"email_challenge\")\n if emailChallenge != \"\" {\n q := initUrl.Query()\n\n redirectUri := q.Get(\"redirect_uri\")\n if redirectUri != \"\" {\n _redirect, err := url.Parse(redirectUri)\n if err != nil {\n log.Debug(err.Error())\n c.AbortWithStatus(http.StatusInternalServerError)\n return\n }\n\n rq := _redirect.Query()\n rq.Add(\"email_challenge\", emailChallenge)\n _redirect.RawQuery = rq.Encode()\n q.Set(\"redirect_uri\", _redirect.String())\n initUrl.RawQuery = q.Encode()\n }\n\n }*/\n\n c.Redirect(http.StatusFound, initUrl.String())\n c.Abort()\n return\n }\n\n // We recived a code request, try and exchange it for a token.\n\n requestState := c.Query(\"state\")\n if requestState == \"\" {\n log.Debug(\"Missing state in query\")\n c.AbortWithStatus(http.StatusBadRequest)\n return\n }\n log = log.WithFields(logrus.Fields{ \"state\":requestState })\n\n valid := ValidateSessionState(env, c, requestState)\n if valid == false {\n log.Debug(\"Request state invalid\")\n c.AbortWithStatus(http.StatusBadRequest)\n return\n }\n\n // Require redirect_to registered to session exchange state\n redirectTo, exists := FetchSessionRedirect(env, c, requestState)\n if exists == false {\n log.Debug(\"Session redirect not found\")\n c.AbortWithStatus(http.StatusBadRequest)\n return\n }\n log = log.WithFields(logrus.Fields{ \"session.redirect_to\":redirectTo })\n\n token, err := oauth2Config.Exchange(context.Background(), code)\n if err != nil {\n log.Debug(err.Error())\n c.AbortWithStatus(http.StatusBadRequest) // FIXME: Maybe we should redirect back reboot the process. Since the access token was not aquired.\n return\n }\n\n if token.Valid() == false {\n c.AbortWithStatus(http.StatusForbidden)\n return\n }\n\n // Optional extract IdToken iff present.\n idToken, idTokenHint, err := fetchIdTokenFromAccessToken(env, oauth2Config, token)\n if err != nil {\n log.Debug(err.Error())\n c.AbortWithStatus(http.StatusBadRequest)\n return\n }\n\n if idToken != nil {\n c.Set(env.Constants.ContextIdTokenKey, idToken)\n }\n\n if idTokenHint != \"\" {\n c.Set(env.Constants.ContextIdTokenHintKey, idTokenHint)\n }\n\n c.Set(env.Constants.ContextAccessTokenKey, token)\n c.Next()\n return\n }\n return gin.HandlerFunc(fn)\n}", "func handleNaturalistLogin(w http.ResponseWriter, r *http.Request) {\n\turl := authenticator.AuthUrl()\n\n\tlog.Printf(\"Redirecting: %s\", url)\n\n\thttp.Redirect(w, r, url, http.StatusTemporaryRedirect)\n}", "func (h *Handler) serveAuthenticateDBUser(w http.ResponseWriter, r *http.Request) {}", "func RealAuthorize(c *gin.Context) {\n\n\tsessid := c.DefaultQuery(\"sess\", \"\")\n\tif sessid == \"\" {\n\t\tc.AbortWithStatus(500)\n\t\treturn\n\t}\n\n\tsess := models.NewSession(ginject.Deps(c))\n\tif err := sess.FromSessionID(sessid); err != nil {\n\t\tlog.Println(err)\n\t\tc.AbortWithStatus(500)\n\t\treturn\n\t}\n\n\tmanager := models.NewManager(ginject.Deps(c))\n\n\tserver.InitServer(manager)\n\tserver.SetAllowedGrantType(oauth2.AuthorizationCode, oauth2.Refreshing)\n\tserver.SetAllowedResponseType(oauth2.Code, oauth2.Token)\n\n\tserver.SetUserAuthorizationHandler(func(w http.ResponseWriter, r *http.Request) (userID string, err error) {\n\n\t\treturn sess.GetUserID(), nil\n\t})\n\n\tserver.HandleAuthorizeRequest(c)\n}", "func main() {\n\n\tapp := &appVars{}\n\n\t// get top-level context\n\tapp.ctx = context.Background()\n\n\t// get Microsoft client id and secret stored in environment\n\t// variables to avoid adding to source code repository\n\tmsClientId, present := os.LookupEnv(\"MSCLIENTID\")\n\tif !present {\n\t\tlog.Panic(\"Must set MSCLIENTID\")\n\t}\n\tmsClientSecret, present := os.LookupEnv(\"MSCLIENTSECRET\")\n\tif !present {\n\t\tlog.Panic(\"Must set MSCLIENTSECRET\")\n\t}\n\n\t// setup configuration for OAuth2\n\tapp.conf = &oauth2.Config{\n\t\tClientID: msClientId,\n\t\tClientSecret: msClientSecret,\n\t\tScopes: []string{\"Notes.Read\"},\n\t\tEndpoint: oauth2.Endpoint{\n\t\t\tAuthURL: msAuthURL,\n\t\t\tTokenURL: msTokenURL,\n\t\t},\n\t\tRedirectURL: myRedirectURL,\n\t}\n\n\t// generate a random token to prevent CSRF attacks\n\tapp.state = randomToken(32)\n\n\turl := \"http://localhost:9999/login\"\n\n\t// prompt user to visit the URL in a browser\n\t// once authorization, the remote site will redirect back\n\tfmt.Printf(\"Visit the following URL to login:\\n\\n%v\\n\\n\", url)\n\n\t// if possible, open the link for the user\n\tswitch os := runtime.GOOS; os {\n\tcase \"darwin\":\n\t\tcmd := exec.Command(\"open\", url)\n\t\terr := cmd.Run()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Command Run failed: %v\", err)\n\t\t}\n\tcase \"windows\":\n\t\tcmd := exec.Command(\"rundll32\", \"url.dll,FileProtocolHandler\",\n\t\t\turl)\n\t\terr := cmd.Run()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Command Run failed: %v\", err)\n\t\t}\n\t}\n\n\t// setup local server for redirect\n\thttpServer := &http.Server{Addr: \":9999\"}\n\n\t// register handlers\n\thttp.HandleFunc(\"/login\", app.login)\n\thttp.HandleFunc(\"/listPages\", app.listPages)\n\thttp.HandleFunc(\"/listNotebooks\", app.listNotebooks)\n\thttp.HandleFunc(\"/oauth/callback\", app.oauthRedirect)\n\n\t// channel for authorization status\n\tapp.authChan = make(chan bool)\n\n\t// startup local http server\n\tlog.Fatal(httpServer.ListenAndServe())\n}", "func bungieAuth(c *gin.Context) {\n discordID := c.Query(\"id\")\n\n bungieAuthURL := \"https://www.bungie.net/en/OAuth/Authorize?client_id=\" +\n os.Getenv(\"CLIENT_ID\") +\n \"&response_type=code\" +\n \"&state=\" + discordID\n\n c.Redirect(http.StatusMovedPermanently, bungieAuthURL)\n}", "func AuthRequired(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tsession.Set(\"user\", \"aoki\")\n\tuser := session.Get(userKey)\n\tif user == nil {\n\t\t// Abort the request with the appropriate error code\n\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\"error\": \"unauthorized\"})\n\t\treturn\n\t}\n\t// Continue down the chain to handler etc\n\tc.Next()\n}", "func (c *ActionController) Request(ctx *app.RequestActionContext) error {\n\t// ActionController_Request: start_implement\n\n\t// Put your logic here\n\n\t// Retrieve the token claims\n\ttoken := jwt.ContextJWT(ctx)\n\tif token == nil {\n\t\treturn fmt.Errorf(\"JWT token is missing from context\") // internal error\n\t}\n\tclaims := token.Claims.(jwtgo.MapClaims)\n\tfmt.Println(claims)\n\t// Use the claims to authorize\n\tsubject := claims[\"user\"]\n\tif subject != \"subject\" {\n\t\t// A real app would probably use an \"Unauthorized\" response here\n\n\t\treturn ctx.OK([]byte(\"OK Unauthorized\"))\n\t}\n\n\treturn ctx.OK([]byte(\"OK\"))\n\t// ActionController_Request: end_implement\n}", "func (c *clientInfo) BeginAuthorize(ctx context.Context, domain string) (*HTTPAuthChallenge, error) {\n\t// start domain authorization and get the challenge\n\tauthz, err := c.client.Authorize(ctx, domain)\n\tif err != nil {\n\t\tlogger.Error(\"error starting authorization for domain\", golog.String(\"domain\", domain))\n\t\treturn nil, logger.Errore(err)\n\t}\n\t// don't need to authorize\n\tif authz.Status == acme.StatusValid {\n\t\treturn nil, nil\n\t}\n\t// pick a challenge\n\tvar challenge *acme.Challenge\n\tfor _, c := range authz.Challenges {\n\t\tif c.Type == \"http-01\" {\n\t\t\tchallenge = c\n\t\t\tbreak\n\t\t}\n\t}\n\tif challenge == nil {\n\t\treturn nil, logger.Error(\"no supported challenge provided by server\")\n\t}\n\t// get the response params\n\tchallengePath := c.client.HTTP01ChallengePath(challenge.Token)\n\tchallengeResponse, err := c.client.HTTP01ChallengeResponse(challenge.Token)\n\tif err != nil {\n\t\treturn nil, logger.Errore(err)\n\t}\n\n\treturn &HTTPAuthChallenge{\n\t\tAuthChallenge: AuthChallenge{\n\t\t\tchallenge: challenge,\n\t\t\tURI: authz.URI,\n\t\t},\n\t\tPath: challengePath,\n\t\tResponse: challengeResponse,\n\t}, nil\n}", "func (r *requestHandler) Authenticate(domain, clientID, clientSecret string) Session {\n\n\tpayload := clientID + \":\" + clientSecret\n\tencodedToken := b64.StdEncoding.EncodeToString([]byte(payload))\n\tresp, err := r.client.R().\n\t\tEnableTrace().\n\t\tSetHeader(\"Accept\", \"application/json\").\n\t\tSetHeader(\"Content-Type\", \"application/x-www-form-urlencoded\").\n\t\tSetHeader(\"Accept\", \"application/json\").\n\t\tSetHeader(\"Authorization\", \"Basic \"+encodedToken).\n\t\tSetBody([]byte(`grant_type=client_credentials`)).\n\t\tPost(\"https://\" + domain + \"/oauth/token\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr.session = NewSession(domain, resp.Body())\n\treturn r.session\n}", "func Authentication(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Printf(\"Authentication: checking for existing authenticated session\\n\")\n\t\tauthenticated, ok := r.Context().Value(session.AuthenticatedKey).(bool)\n\t\tlog.Printf(\"Authentication: authenticated?: %b\\n\", authenticated)\n\t\tif (ok == false || authenticated == false) {\n\t\t\tstate := r.Context().Value(session.StateKey).(string)\n\t\t\tlog.Printf(\"Authentication: using state: %v\\n\", state)\n\t\t\tauthorizeURL := oauth2Config.AuthCodeURL(state, oauth2.AccessTypeOnline)\n\t\t\tlog.Printf(\"Authentication: redirecting to %s\\n\", authorizeURL)\n\t\t\thttp.Redirect(w, r, authorizeURL, http.StatusFound)\n\t\t\treturn\n\t\t} else { // authenticated == true\n log.Printf(\"Authentication: user is authenticated, done\\n\")\n next.ServeHTTP(w, r)\n }\n\t})\n}", "func (proto *Protocol) Start() *Response {\n\tproto.logf(\"Started session, switching to PREAUTH state\")\n\tproto.State = PREAUTH\n\treturn ResponseIdent(proto.Revision, proto.Hostname, proto.Ident)\n}", "func genericRequestHandler(w http.ResponseWriter, r *http.Request) {\n\temail := getUser(r)\n\tif email != \"\" {\n\t\tlog.Println(email, r.URL.String())\n\t\tproxy(w, r)\n\t} else {\n\t\tsession, _ := store.Get(r, serverConfig.CookieName)\n\t\tsession.Values[\"next\"] = r.URL.String()\n\t\tsession.Save(r, w)\n\t\tlog.Println(\"Asking for login, request from unknown user to:\", r.URL.String())\n\t\taskForLogin(w, r)\n\t}\n}", "func handleHome(w http.ResponseWriter, _ *http.Request) {\n\tvar config = client.GetOAuth2Config()\n\tconfig.RedirectURL = \"http://localhost:3500/callback\"\n\tconfig.Scopes = []string{\"offline\", \"openid\"}\n\n\tvar authURL = client.GetOAuth2Config().AuthCodeURL(state) + \"&nonce=\" + state\n\tlog.Println(\"AuthURL is \" + authURL)\n\trenderTemplate(w, \"home.html\", authURL)\n}", "func (a *auth) Request(ctx context.Context, c *swift.Connection) (*http.Request, error) {\n\tif a.parentAuth == nil {\n\t\treturn nil, nil\n\t}\n\treturn a.parentAuth.Request(ctx, c)\n}", "func (h *AuthCodeHandler) OnRequest(log *zerolog.Logger, request *http.Request) error {\n\tif request.Header.Get(\"Authorization\") == \"\" {\n\t\t// No auth is set, so let's get the token either from a cache\n\t\t// or generate a new one from the issuing server.\n\t\tprofile := cli.GetProfile()\n\n\t\tparams := url.Values{}\n\t\tif h.getParamsFunc != nil {\n\t\t\t// Backward-compatibility with old call style, only used internally.\n\t\t\tparams = h.getParamsFunc(profile)\n\t\t}\n\t\tfor _, name := range h.Params {\n\t\t\tparams.Add(name, profile[name])\n\t\t}\n\n\t\tsource := &AuthorizationCodeTokenSource{\n\t\t\tClientID: h.ClientID,\n\t\t\tAuthorizeURL: h.AuthorizeURL,\n\t\t\tTokenURL: h.TokenURL,\n\t\t\tEndpointParams: &params,\n\t\t\tScopes: h.Scopes,\n\t\t}\n\n\t\t// Try to get a cached refresh token from the current profile and use\n\t\t// it to wrap the auth code token source with a refreshing source.\n\t\trefreshKey := \"profiles.\" + viper.GetString(\"profile\") + \".refresh\"\n\t\trefreshSource := RefreshTokenSource{\n\t\t\tClientID: h.ClientID,\n\t\t\tTokenURL: h.TokenURL,\n\t\t\tEndpointParams: &params,\n\t\t\tRefreshToken: cli.Cache.GetString(refreshKey),\n\t\t\tTokenSource: source,\n\t\t}\n\n\t\treturn TokenHandler(refreshSource, log, request)\n\t}\n\n\treturn nil\n}", "func completeAuth(w http.ResponseWriter, r *http.Request) {\n\tuser, err := gothic.CompleteUserAuth(w, r)\n\tif err != nil {\n\t\tfmt.Fprintln(w, err)\n\t\treturn\n\t}\n\tuserSession.Values[\"user\"] = user\n\thttp.Redirect(w, r, \"/\", 301)\n}", "func (p *Provider) BeginAuth(state string) (goth.Session, error) {\n\trequestToken, url, err := p.consumer.GetRequestTokenAndUrl(p.CallbackURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsession := &Session{\n\t\tAuthURL: url,\n\t\tRequestToken: requestToken,\n\t}\n\treturn session, err\n}", "func (c *certManager) BeginAuthorize(domain string) (*acmelib.HTTPAuthChallenge, error) {\n\tlogger.Info(\"begin authorization of domain\", golog.String(\"domain\", domain))\n\tctx := context.Background()\n\n\tchallenge, err := c.client.BeginAuthorize(ctx, domain)\n\tif err != nil {\n\t\treturn nil, logger.Errore(err)\n\t}\n\n\tif challenge == nil {\n\t\tlogger.Debug(\"no authorization required\", golog.String(\"domain\", domain))\n\t\treturn nil, nil\n\t}\n\n\tlogger.Debug(\"challenge received\",\n\t\tgolog.String(\"URI\", challenge.URI),\n\t\tgolog.String(\"path\", challenge.Path),\n\t\tgolog.String(\"response\", challenge.Response),\n\t)\n\n\thost, err := c.store.GetHost(domain)\n\tif err != nil {\n\t\treturn nil, logger.Errore(err)\n\t}\n\n\tif host == nil {\n\t\thost = &store.Host{\n\t\t\tHost: domain,\n\t\t}\n\t}\n\n\thost.ACMEChallenge.ChallengePath = challenge.Path\n\thost.ACMEChallenge.Response = challenge.Response\n\n\terr = c.store.PutHost(host)\n\tif err != nil {\n\t\treturn nil, logger.Errore(err)\n\t}\n\n\treturn challenge, nil\n}", "func (a API) Auth(w http.ResponseWriter, r *http.Request, state string, redirect_url string) {\r\n\thttp.Redirect(w, r, a.AuthUrl(state, redirect_url), http.StatusFound)\r\n}", "func (a *loginAPI) HandleOIDCRedirectFinal(w http.ResponseWriter, r *http.Request) error {\n\tstate := a.appCookie.Get(stateParam, r)\n\tif state == \"\" {\n\t\tlog.WithField(\"func\", \"server.HandleOIDCRedirectFinal\").Debugf(\"emptiy state from cookie, referrer: '%s'\", r.Referer())\n\t\treturn errors.BadRequestError{Err: fmt.Errorf(\"missing state, cannot initiate OIDC\"), Request: r}\n\t}\n\tlog.WithField(\"func\", \"server.HandleOIDCRedirectFinal\").Debugf(\"initiate OIDC redirect using state: '%s'\", state)\n\thttp.Redirect(w, r, a.oauthConfig.AuthCodeURL(state), http.StatusFound)\n\treturn nil\n}", "func (service Service) BeginTOTPEnrollment(rw http.ResponseWriter, req *http.Request) {\n\n\t//\treq.Body is a ReadCloser -- we need to remember to close it:\n\tdefer req.Body.Close()\n\n\t//\tGet the authorization header:\n\tauthHeader := req.Header.Get(\"Authorization\")\n\n\t//\tIf the auth header wasn't supplied, return an error\n\tif authHeaderValid(authHeader) != true {\n\t\tsendErrorResponse(rw, fmt.Errorf(\"Bearer token was not supplied\"), http.StatusForbidden)\n\t\treturn\n\t}\n\n\t//\tGet just the bearer token itself:\n\ttoken := getBearerTokenFromAuthHeader(authHeader)\n\n\t//\tGet the user from the token:\n\tuser, err := service.DB.GetUserForToken(token)\n\tif err != nil {\n\t\tsendErrorResponse(rw, fmt.Errorf(\"Token not authorized or not valid\"), http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t//\tPerform the action with the context user\n\t_, err = service.DB.BeginTOTPEnrollment(user.Name, 1*time.Hour)\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t//\tCreate our response and send information back:\n\tresponse := SystemResponse{\n\t\tStatus: http.StatusAccepted,\n\t\tMessage: \"Enrollment started\",\n\t\tData: \"\",\n\t}\n\n\t//\tSerialize to JSON & return the response:\n\trw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tjson.NewEncoder(rw).Encode(response)\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 interactiveBrowserLogin(authorityHost string, tenantID string, clientID string, redirectURL string, scopes []string) (*interactiveConfig, error) {\n\tconst authURLFormat = \"%s/%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&client_id=%s&redirect_uri=%s&state=%s&scope=%s&prompt=select_account\"\n\tstate := func() string {\n\t\trand.Seed(time.Now().Unix())\n\t\t// generate a 20-char random alpha-numeric string\n\t\tconst charset = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n\t\tbuff := make([]byte, 20)\n\t\tfor i := range buff {\n\t\t\tbuff[i] = charset[rand.Intn(len(charset))]\n\t\t}\n\t\treturn string(buff)\n\t}()\n\t// start local redirect server so login can call us back\n\trs := newServer()\n\tif redirectURL == \"\" {\n\t\tredirectURL = rs.Start(state)\n\t}\n\tdefer rs.Stop()\n\tauthURL := fmt.Sprintf(authURLFormat, authorityHost, tenantID, clientID, redirectURL, state, strings.Join(scopes, \" \"))\n\t// open browser window so user can select credentials\n\terr := browser.OpenURL(authURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// now wait until the logic calls us back\n\trs.WaitForCallback()\n\n\tauthCode, err := rs.AuthorizationCode()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &interactiveConfig{\n\t\tauthCode: authCode,\n\t\tredirectURI: redirectURL,\n\t}, nil\n}", "func (c *Client) Login(urlStr string, auth *AuthRequest) (err error) {\n\tvar (\n\t\tres *http.Response\n\t\tresult *AuthResponse\n\t)\n\n\tif res, err = c.authRequest(urlStr, auth); err != nil {\n\t\treturn err\n\t}\n\n\tresult = &AuthResponse{}\n\tif err = ReadResponse(res, &result); err != nil {\n\t\treturn err\n\t}\n\n\t// Connection is authorized\n\tif result.Success {\n\t\treturn nil\n\t}\n\n\t// Otherwise send authentication\n\t// Create login with challenge\n\tauth.Authorize = authKey(auth, result.Challenge)\n\tif res, err = c.authRequest(urlStr, auth); err != nil {\n\t\treturn err\n\t}\n\tauth.Authorize = auth.Login\n\n\tresult = &AuthResponse{}\n\tif err = ReadResponse(res, &result); err != nil {\n\t\treturn err\n\t}\n\n\tif !result.Success {\n\t\terr = errors.New(\"Not authorized\")\n\t}\n\n\treturn\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 DoAuth(ctx *gin.Context) {\n\t// Handle the exchange code to initiate a transport.\n\tsession := sessions.Default(ctx)\n\tretrievedState := session.Get(\"state\")\n\n\tif session.Get(\"userid\") != nil {\n\t\treturn\n\t}\n\n\tif retrievedState != ctx.Query(\"state\") {\n\t\tctx.AbortWithError(http.StatusUnauthorized, fmt.Errorf(\"Invalid session state: %s\", retrievedState))\n\t\treturn\n\t}\n\n\ttok, err := conf.Exchange(oauth2.NoContext, ctx.Query(\"code\"))\n\tif err != nil {\n\t\tctx.AbortWithError(http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tclient := conf.Client(oauth2.NoContext, tok)\n\temail, err := client.Get(\"https://www.googleapis.com/oauth2/v3/userinfo\")\n\tif err != nil {\n\t\tctx.AbortWithError(http.StatusBadRequest, err)\n\t\treturn\n\t}\n\tdefer email.Body.Close()\n\tdata, err := ioutil.ReadAll(email.Body)\n\tif err != nil {\n\t\tglog.Errorf(\"[Gin-OAuth] Could not read Body: %s\", err)\n\t\tctx.AbortWithError(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tvar user User\n\terr = json.Unmarshal(data, &user)\n\tif err != nil {\n\t\tglog.Errorf(\"[Gin-OAuth] Unmarshal userinfo failed: %s\", err)\n\t\tctx.AbortWithError(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\t// save userinfo, which could be used in Handlers\n\tctx.Set(\"user\", user)\n\n\tvals := map[string]string{\n\t\t\"Name\": user.Name,\n\t\t\"Email\": user.Email,\n\t\t\"Picture\": user.Picture,\n\t\t\"GivenName\": user.GivenName,\n\t\t\"FamilyName\": user.FamilyName,\n\t\t\"EmailVerified\": fmt.Sprintf(\"%v\", user.EmailVerified),\n\t\t\"Gender\": user.Gender,\n\t\t\"Sub\": user.Sub,\n\t\t\"Profile\": user.Profile,\n\t}\n\tseccookie.StoreSecureCookie(ctx, vals, scookie)\n\n\t// Redirect to root after auth\n\tctx.Redirect(http.StatusTemporaryRedirect, \"/\")\n}", "func (c *Operation) login(w http.ResponseWriter, r *http.Request) {\n\tu := c.tokenIssuer.AuthCodeURL(w)\n\n\texpire := time.Now().AddDate(0, 0, 1)\n\n\tif len(r.URL.Query()[\"vcsProfile\"]) == 0 {\n\t\tlogger.Errorf(\"vcs profile is empty\")\n\t\tc.writeErrorResponse(w, http.StatusBadRequest, \"vcs profile is empty\")\n\n\t\treturn\n\t}\n\n\tscope := r.URL.Query()[\"scope\"]\n\tif len(scope) > 0 {\n\t\tu += \"&scope=\" + scope[0]\n\t}\n\n\tcookie := http.Cookie{Name: vcsProfileCookie, Value: r.URL.Query()[\"vcsProfile\"][0], Expires: expire}\n\thttp.SetCookie(w, &cookie)\n\n\thttp.SetCookie(w, &http.Cookie{Name: callbackURLCookie, Value: \"\", Expires: expire})\n\n\thttp.Redirect(w, r, u, http.StatusTemporaryRedirect)\n}", "func (r *oauthProxy) oauthAuthorizationHandler(w http.ResponseWriter, req *http.Request) {\n\tctx, span, logger := r.traceSpan(req.Context(), \"authorization handler\")\n\tif span != nil {\n\t\tdefer span.End()\n\t}\n\n\tif r.config.SkipTokenVerification {\n\t\tr.errorResponse(w, req.WithContext(ctx), \"\", http.StatusNotAcceptable, nil)\n\t\treturn\n\t}\n\n\tclient, err := r.getOAuthClient(r.getRedirectionURL(w, req.WithContext(ctx)))\n\tif err != nil {\n\t\tr.errorResponse(w, req.WithContext(ctx), \"failed to retrieve the oauth client for authorization\", http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\t// step: set the access type of the session\n\tvar accessType string\n\tif containedIn(\"offline\", r.config.Scopes, false) {\n\t\taccessType = \"offline\"\n\t}\n\n\tauthURL := client.AuthCodeURL(req.URL.Query().Get(\"state\"), accessType, \"\")\n\tlogger.Debug(\"incoming authorization request from client address\",\n\t\tzap.String(\"access_type\", accessType),\n\t\tzap.String(\"auth_url\", authURL),\n\t\tzap.String(\"client_ip\", req.RemoteAddr))\n\n\t// step: if we have a custom sign in page, lets display that\n\tif r.config.hasCustomSignInPage() {\n\t\tmodel := make(map[string]string)\n\t\tmodel[\"redirect\"] = authURL\n\t\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_ = r.Render(w, path.Base(r.config.SignInPage), mergeMaps(model, r.config.Tags))\n\n\t\treturn\n\t}\n\n\tr.redirectToURL(authURL, w, req.WithContext(ctx), http.StatusTemporaryRedirect)\n}", "func (c *Client) BeginUsernamePasswordAuth(username string, password string) (*duo.Challenge, error) {\n\tredirectResp, err := c.HTTPClient.Get(authStartURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbaseURL, err := url.Parse(baseURLString)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif redirectResp.Request.URL.Host != baseURL.Host {\n\t\treturn nil, fmt.Errorf(\"touchstone: auth start page redirected to unknown host '%s', expected '%s'\", redirectResp.Request.URL.Host, baseURL.Host)\n\t}\n\n\tloginDoc, err := html.Parse(redirectResp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// get the login form\n\t// TODO: make this code suck less\n\tloginBody := loginDoc.FirstChild.NextSibling.FirstChild.NextSibling.NextSibling\n\tloginBox := loginBody.FirstChild.NextSibling.NextSibling.NextSibling\n\tcertLoginForm := loginBox.FirstChild.NextSibling.NextSibling.NextSibling\n\tusernamePasswordLoginForm := certLoginForm.NextSibling.NextSibling\n\n\tinputs := map[string]string{}\n\n\t// get all inputs\n\tvar f func(*html.Node)\n\tf = func(n *html.Node) {\n\t\t// check for different form\n\t\tif n.Type == html.ElementNode && n.Data == \"form\" {\n\t\t\tfoundID := false\n\t\t\tfor _, attr := range n.Attr {\n\t\t\t\tif attr.Key == \"id\" && attr.Val == \"loginform\" {\n\t\t\t\t\tfoundID = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !foundID {\n\t\t\t\t// we escaped, stop\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// get input\n\t\tif n.Type == html.ElementNode && n.Data == \"input\" {\n\t\t\tname := \"\"\n\t\t\tvalue := \"\"\n\t\t\tinputType := \"\"\n\t\t\tfor _, attr := range n.Attr {\n\t\t\t\tif attr.Key == \"name\" {\n\t\t\t\t\tname = attr.Val\n\t\t\t\t}\n\t\t\t\tif attr.Key == \"value\" {\n\t\t\t\t\tvalue = attr.Val\n\t\t\t\t}\n\t\t\t\tif attr.Key == \"type\" {\n\t\t\t\t\tinputType = attr.Val\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif inputType != \"submit\" {\n\t\t\t\tinputs[name] = value\n\t\t\t}\n\t\t}\n\n\t\t// continue\n\t\tfor c := n.FirstChild; c != nil; c = c.NextSibling {\n\t\t\tf(c)\n\t\t}\n\t}\n\tf(usernamePasswordLoginForm)\n\n\tformAction := \"\"\n\tfor _, attr := range usernamePasswordLoginForm.Attr {\n\t\tif attr.Key == \"action\" {\n\t\t\tformAction = attr.Val\n\t\t}\n\t}\n\n\terr = redirectResp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// ok, now make the request\n\tformData := url.Values{}\n\tfor key, val := range inputs {\n\t\tformData.Add(key, val)\n\t}\n\tformData.Set(\"j_username\", username)\n\tformData.Set(\"j_password\", password)\n\tloginResp, err := c.HTTPClient.PostForm(formAction, formData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tduoBody, err := ioutil.ReadAll(loginResp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !strings.Contains(string(duoBody), \"Duo second-factor authentication is required.\") {\n\t\t// didn't work, oof\n\t\treturn nil, ErrBadCreds\n\t}\n\n\tcaptureGroups := duoInitRegex.FindAllStringSubmatch(string(duoBody), -1)[0]\n\n\thost := captureGroups[1]\n\tsigRequest := captureGroups[2]\n\tpostAction := captureGroups[3]\n\n\terr = loginResp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.conversation = formData.Get(\"conversation\")\n\tc.sigRequest = sigRequest\n\n\treturn duo.BeginChallenge(c.HTTPClient, loginResp.Request.URL.String(), host, sigRequest, postAction)\n}", "func handleOidcCallback(\n\tw http.ResponseWriter,\n\tr *http.Request,\n\tclientName string,\n\tclientID string,\n\tclientSecret string,\n\tredirectURI string,\n\twellKnownConfig oidc.WellKnownConfiguration,\n\tstate string,\n\tcodeVerifier string,\n\tcancel context.CancelFunc,\n) {\n\tvar authorisationResponse, err = oidc.ValidateAuthorisationResponse(r.URL, state)\n\tif err != nil {\n\t\trenderAndLogError(w, cancel, fmt.Sprintf(\"%v\", err))\n\t\treturn\n\t}\n\n\tviewModel, err := VerifyCode(clientID, clientSecret, redirectURI, wellKnownConfig, codeVerifier, authorisationResponse.Code)\n\tif err != nil {\n\t\trenderAndLogError(w, cancel, fmt.Sprintf(\"%v\", err))\n\t\treturn\n\t}\n\n\t// show webpage\n\tt := template.New(\"credentials\")\n\t_, parseErr := t.Parse(TokenResultView())\n\tif parseErr != nil {\n\t\trenderAndLogError(w, cancel, fmt.Sprintf(\"%v\", parseErr))\n\t\treturn\n\t}\n\ttplErr := t.Execute(w, viewModel)\n\tif tplErr != nil {\n\t\trenderAndLogError(w, cancel, fmt.Sprintf(\"%v\", tplErr))\n\t\treturn\n\t}\n\n\tcancel()\n}", "func (a *loginAPI) HandleOIDCRedirect(w http.ResponseWriter, r *http.Request) error {\n\tstate := randToken()\n\ta.appCookie.Set(stateParam, state, cookieExpiry, w)\n\tlog.WithField(\"func\", \"server.HandleOIDCRedirect\").Debugf(\"GetRedirect: initiate using state '%s'\", state)\n\thttp.Redirect(w, r, a.GetOIDCRedirectURL(), http.StatusTemporaryRedirect)\n\treturn nil\n}", "func Authenticate(h route.Handle) route.Handle {\n\treturn func(r *http.Request) (route.HandleObject, error) {\n\t\tv1reponse := new(route.V1)\n\n\t\tlog.Debugf(\"Authenticating %s\", r.URL.String())\n\t\tuser := User{}\n\t\tcookie, err := r.Cookie(\"_SID_TXNAPP_\")\n\t\tif err != nil {\n\t\t\treturn v1reponse, err\n\t\t}\n\t\terr = apicalls.Auth.Authenticate(cookie, &user)\n\t\tif err != nil {\n\t\t\treturn v1reponse, err\n\t\t}\n\n\t\tif user.UserID == 0 {\n\t\t\treturn v1reponse, errors.New(\"User is not authenticated\", http.StatusForbidden)\n\t\t}\n\t\tctx := context.WithValue(r.Context(), \"user\", user)\n\t\tr = r.WithContext(ctx)\n\t\treturn h(r)\n\t}\n}", "func (o *oidcClient) authenticate(issuer string, clientID string, audience string) error {\n\t// Store the old transport and restore it in the end.\n\toldTransport := o.httpClient.Transport\n\to.oidcTransport.audience = audience\n\to.httpClient.Transport = o.oidcTransport\n\n\tdefer func() {\n\t\to.httpClient.Transport = oldTransport\n\t}()\n\n\tprovider, err := o.getProvider(issuer, clientID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.oidcTransport.deviceAuthorizationEndpoint = provider.GetDeviceAuthorizationEndpoint()\n\n\tresp, err := rp.DeviceAuthorization(oidcScopes, provider)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"Code: %s\\n\\n\", resp.UserCode)\n\n\tu, _ := url.Parse(resp.VerificationURIComplete)\n\n\terr = openBrowser(u.String())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGINT)\n\tdefer stop()\n\n\ttoken, err := rp.DeviceAccessToken(ctx, resp.DeviceCode, time.Duration(resp.Interval)*time.Second, provider)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif o.tokens.Token == nil {\n\t\to.tokens.Token = &oauth2.Token{}\n\t}\n\n\to.tokens.Expiry = time.Now().Add(time.Duration(token.ExpiresIn))\n\to.tokens.IDToken = token.IDToken\n\to.tokens.Token.AccessToken = token.AccessToken\n\to.tokens.TokenType = token.TokenType\n\n\tif token.RefreshToken != \"\" {\n\t\to.tokens.Token.RefreshToken = token.RefreshToken\n\t}\n\n\treturn nil\n}", "func (p Service) authHandler(w http.ResponseWriter, r *http.Request) {\n\toauthClaims, _, err := p.JwtService.Get(r)\n\tif err != nil {\n\t\trest.SendErrorJSON(w, r, http.StatusInternalServerError, err, \"failed to get token\")\n\t\treturn\n\t}\n\n\tif oauthClaims.Handshake == nil {\n\t\trest.SendErrorJSON(w, r, http.StatusForbidden, nil, \"finvalid handshake token\")\n\t\treturn\n\t}\n\n\tretrievedState := oauthClaims.Handshake.State\n\tif retrievedState == \"\" || retrievedState != r.URL.Query().Get(\"state\") {\n\t\trest.SendErrorJSON(w, r, http.StatusForbidden, nil, \"unexpected state\")\n\t\treturn\n\t}\n\n\tp.Logf(\"[DEBUG] token with state %s\", retrievedState)\n\ttok, err := p.conf.Exchange(context.Background(), r.URL.Query().Get(\"code\"))\n\tif err != nil {\n\t\trest.SendErrorJSON(w, r, http.StatusInternalServerError, err, \"exchange failed\")\n\t\treturn\n\t}\n\n\tclient := p.conf.Client(context.Background(), tok)\n\tuinfo, err := client.Get(p.InfoURL)\n\tif err != nil {\n\t\trest.SendErrorJSON(w, r, http.StatusServiceUnavailable, err, \"failed to get client info\")\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\tif e := uinfo.Body.Close(); e != nil {\n\t\t\tp.Logf(\"[WARN] failed to close response body, %s\", e)\n\t\t}\n\t}()\n\n\tdata, err := ioutil.ReadAll(uinfo.Body)\n\tif err != nil {\n\t\trest.SendErrorJSON(w, r, http.StatusInternalServerError, err, \"failed to read user info\")\n\t\treturn\n\t}\n\n\tjData := map[string]interface{}{}\n\tif e := json.Unmarshal(data, &jData); e != nil {\n\t\trest.SendErrorJSON(w, r, http.StatusInternalServerError, err, \"failed to unmarshal user info\")\n\t\treturn\n\t}\n\tp.Logf(\"[DEBUG] got raw user info %+v\", jData)\n\n\tu := p.MapUser(jData, data)\n\tu = p.setAvatar(u)\n\n\tcid, err := p.randToken()\n\tif err != nil {\n\t\trest.SendErrorJSON(w, r, http.StatusInternalServerError, err, \"failed to make claim's id\")\n\t\treturn\n\t}\n\tclaims := token.Claims{\n\t\tUser: &u,\n\t\tStandardClaims: jwt.StandardClaims{\n\t\t\tIssuer: p.Issuer,\n\t\t\tId: cid,\n\t\t\tAudience: oauthClaims.Audience,\n\t\t},\n\t\tSessionOnly: oauthClaims.SessionOnly,\n\t}\n\n\tif err = p.JwtService.Set(w, claims); err != nil {\n\t\trest.SendErrorJSON(w, r, http.StatusInternalServerError, err, \"failed to set token\")\n\t\treturn\n\t}\n\n\tp.Logf(\"[DEBUG] user info %+v\", u)\n\n\t// redirect to back url if presented in login query params\n\tif oauthClaims.Handshake != nil && oauthClaims.Handshake.From != \"\" {\n\t\thttp.Redirect(w, r, oauthClaims.Handshake.From, http.StatusTemporaryRedirect)\n\t\treturn\n\t}\n\trest.RenderJSON(w, r, &u)\n}", "func (p DirectHandler) AuthHandler(http.ResponseWriter, *http.Request) {}", "func mockTestUserInteraction(ctx context.Context, pro providerParams, username, password string) (string, error) {\n\tctx, cancel := context.WithTimeout(ctx, 10*time.Second)\n\tdefer cancel()\n\n\tprovider, err := oidc.NewProvider(ctx, pro.providerURL)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to create provider: %v\", err)\n\t}\n\n\t// Configure an OpenID Connect aware OAuth2 client.\n\toauth2Config := oauth2.Config{\n\t\tClientID: pro.clientID,\n\t\tClientSecret: pro.clientSecret,\n\t\tRedirectURL: pro.redirectURL,\n\n\t\t// Discovery returns the OAuth2 endpoints.\n\t\tEndpoint: provider.Endpoint(),\n\n\t\t// \"openid\" is a required scope for OpenID Connect flows.\n\t\tScopes: []string{oidc.ScopeOpenID, \"groups\"},\n\t}\n\n\tstate := \"xxx\"\n\tauthCodeURL := oauth2Config.AuthCodeURL(state)\n\t// fmt.Printf(\"authcodeurl: %s\\n\", authCodeURL)\n\n\tvar lastReq *http.Request\n\tcheckRedirect := func(req *http.Request, via []*http.Request) error {\n\t\t// fmt.Printf(\"CheckRedirect:\\n\")\n\t\t// fmt.Printf(\"Upcoming: %s %#v\\n\", req.URL.String(), req)\n\t\t// for _, c := range via {\n\t\t// \tfmt.Printf(\"Sofar: %s %#v\\n\", c.URL.String(), c)\n\t\t// }\n\t\t// Save the last request in a redirect chain.\n\t\tlastReq = req\n\t\t// We do not follow redirect back to client application.\n\t\tif req.URL.Path == \"/oauth_callback\" {\n\t\t\treturn http.ErrUseLastResponse\n\t\t}\n\t\treturn nil\n\t}\n\n\tdexClient := http.Client{\n\t\tCheckRedirect: checkRedirect,\n\t}\n\n\tu, err := url.Parse(authCodeURL)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"url parse err: %v\", err)\n\t}\n\n\t// Start the user auth flow. This page would present the login with\n\t// email or LDAP option.\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"new request err: %v\", err)\n\t}\n\t_, err = dexClient.Do(req)\n\t// fmt.Printf(\"Do: %#v %#v\\n\", resp, err)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"auth url request err: %v\", err)\n\t}\n\n\t// Modify u to choose the ldap option\n\tu.Path += \"/ldap\"\n\t// fmt.Println(u)\n\n\t// Pick the LDAP login option. This would return a form page after\n\t// following some redirects. `lastReq` would be the URL of the form\n\t// page, where we need to POST (submit) the form.\n\treq, err = http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"new request err (/ldap): %v\", err)\n\t}\n\t_, err = dexClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"request err: %v\", err)\n\t}\n\n\t// Fill the login form with our test creds:\n\t// fmt.Printf(\"login form url: %s\\n\", lastReq.URL.String())\n\tformData := url.Values{}\n\tformData.Set(\"login\", username)\n\tformData.Set(\"password\", password)\n\treq, err = http.NewRequestWithContext(ctx, http.MethodPost, lastReq.URL.String(), strings.NewReader(formData.Encode()))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"new request err (/login): %v\", err)\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\t_, err = dexClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"post form err: %v\", err)\n\t}\n\t// fmt.Printf(\"resp: %#v %#v\\n\", resp.StatusCode, resp.Header)\n\t// fmt.Printf(\"lastReq: %#v\\n\", lastReq.URL.String())\n\n\t// On form submission, the last redirect response contains the auth\n\t// code, which we now have in `lastReq`. Exchange it for a JWT id_token.\n\tq := lastReq.URL.Query()\n\tcode := q.Get(\"code\")\n\toauth2Token, err := oauth2Config.Exchange(ctx, code)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to exchange code for id token: %v\", err)\n\t}\n\n\trawIDToken, ok := oauth2Token.Extra(\"id_token\").(string)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"id_token not found!\")\n\t}\n\n\t// fmt.Printf(\"TOKEN: %s\\n\", rawIDToken)\n\treturn rawIDToken, nil\n}", "func (handler *AuthHandler) Auth(c *gin.Context) {\n\tc.Redirect(http.StatusMovedPermanently, handler.Oauth2Conf.AuthCodeURL(handler.Oauth2StateString, oauth2.AccessTypeOffline))\n\tc.Abort()\n}", "func Handler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tgob.Register(map[string]interface{}{})\n\n\t// ensure state in callback matches state saved in cookie (to prevent CSRF)\n\tstate, _ := r.Cookie(\"google-oauth-state\")\n\tif r.FormValue(\"state\") != state.Value {\n\t\tlog.Printf(\"no dice \\n\")\n\t\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n\t}\n\t// get user info from google user info api using state and code\n\t// passed in the callback\n\tuserInfo, err := getUserInfo(r.FormValue(\"state\"), r.FormValue(\"code\"))\n\tif err != nil {\n\t\tlog.Printf(\"error: %s\", err.Error())\n\t\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n\t}\n\n\t// set user in session\n\tsession, err := store.Get(r, \"currentUser\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tsession.Options = &sessions.Options{\n\t\tPath: \"/\", // the root of the app\n\t\tMaxAge: 86400 * 7, // 1 week\n\t\tHttpOnly: true, // prevent XSS vulnerabilities\n\t}\n\tsession.Values[\"user\"] = userInfo\n\terr = session.Save(r, w)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n}", "func (o *SlackOAuthHandlers) Auth(w http.ResponseWriter, r *http.Request) {\n\tparams, err := url.ParseQuery(r.URL.RawQuery)\n\tif err != nil {\n\t\thlog.FromRequest(r).Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"parsing query params\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// An error is received when a user declines to install\n\t// or an unexpected issue occurs. The app treats a\n\t// declined install gracefully.\n\tif params[\"error\"] != nil {\n\t\tswitch params[\"error\"][0] {\n\t\tcase errAccessDenied:\n\t\t\thlog.FromRequest(r).Info().\n\t\t\t\tErr(errors.New(params[\"error\"][0])).\n\t\t\t\tMsg(\"user declined install\")\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\treturn\n\t\tdefault:\n\t\t\thlog.FromRequest(r).Error().\n\t\t\t\tErr(errors.New(params[\"error\"][0])).\n\t\t\t\tMsg(\"failed install\")\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\n\tcode := params[\"code\"]\n\tif len(code) != 1 {\n\t\thlog.FromRequest(r).Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"code not provided\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// TODO: inject an http client with http logging.\n\tresp, err := http.Get(fmt.Sprintf(\n\t\to.AccessURLTemplate,\n\t\to.ClientID,\n\t\to.ClientSecret,\n\t\tcode[0],\n\t))\n\tif err != nil {\n\t\thlog.FromRequest(r).Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"oauth req error\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvar access accessResponse\n\tif err := json.NewDecoder(resp.Body).Decode(&access); err != nil {\n\t\thlog.FromRequest(r).Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"unable to decode slack access response\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif !access.OK {\n\t\thlog.FromRequest(r).Warn().\n\t\t\tMsg(\"access not ok\")\n\t\tw.WriteHeader(http.StatusForbidden)\n\t\treturn\n\t}\n\n\terr = o.TokenWriter.Store(&TokenData{\n\t\tTeamID: access.TeamID,\n\t\tUserID: access.UserID,\n\t\tBotToken: access.Bot.BotAccessToken,\n\t\tBotUserID: access.Bot.BotUserID,\n\t\tAccessToken: access.AccessToken,\n\t})\n\tif err != nil {\n\t\thlog.FromRequest(r).Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"unable to store token\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tredirect := fmt.Sprintf(\"https://slack.com/app_redirect?app=%s\", o.AppID)\n\thttp.Redirect(w, r, redirect, http.StatusFound)\n}", "func DoSignin(w http.ResponseWriter, r *http.Request) {\n\n\tvar id int\n\n\tif r.Method == \"POST\" {\n\t\t// Handles login when it is hit as a post request\n\t\tr.ParseForm()\n\t\tstmt, err := db.Prepare(\"select id from users where username=? and password=?\")\n\t\tres := stmt.QueryRow(r.FormValue(\"username\"), r.FormValue(\"password\"))\n\t\terr = res.Scan(&id)\n\n\t\tif err == nil {\n\t\t\tsess, _ := globalSessions.SessionStart(w, r)\n\t\t\tdefer sess.SessionRelease(w)\n\t\t\tsetUserCookies(w, id, sess.SessionID())\n\t\t\t_ = sess.Set(\"user_id\", id)\n\t\t\t_ = sess.Set(\"username\", r.FormValue(\"username\"))\n\t\t\tif r.FormValue(\"remember-me\") == \"on\" {\n\t\t\t\tsaveSession(w, r, sess.SessionID(), id)\n\n\t\t\t}\n\t\t\taddRemoteAddress(r, id)\n\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t} else {\n\t\t\tlog.Println(\"Database connection failed: \", err)\n\t\t}\n\t} else {\n\t\tanonsess, _ := anonSessions.SessionStart(w, r)\n\t\tdefer anonsess.SessionRelease(w)\n\t\t// Handles auto login when it is hit as a GET request\n\t\tsessionIdCookie, err := r.Cookie(\"userSession_id\")\n\t\tif err == nil {\n\t\t\tstmt, err := db.Prepare(\"select id, username from users where session_id=?\")\n\t\t\tres := stmt.QueryRow(sessionIdCookie.Value)\n\t\t\tvar username string\n\t\t\terr = res.Scan(&id, &username)\n\t\t\tif err == nil {\n\t\t\t\tif checkRemoteAddress(r, id) {\n\t\t\t\t\tsess, _ := globalSessions.SessionStart(w, r)\n\t\t\t\t\tdefer sess.SessionRelease(w)\n\t\t\t\t\terr = sess.Set(\"user_id\", id)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Println(err)\n\t\t\t\t\t}\n\t\t\t\t\t_ = sess.Set(\"username\", username)\n\t\t\t\t\tsaveSession(w, r, sess.SessionID(), id)\n\t\t\t\t\tsetUserCookies(w, id, sess.SessionID())\n\t\t\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t\t\t} else {\n\t\t\t\t\thttp.Redirect(w, r, \"/newAddress\", 302)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thttp.Redirect(w, r, \"/userNotFound\", 302)\n\t\t\t}\n\t\t} else {\n\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t}\n\t}\n}", "func AuthRequired(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tuser := session.Get(userkey)\n\tif user == nil {\n\t\t// Abort the request with the appropriate error code\n\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\"error\": \"unauthorized\"})\n\t\treturn\n\t}\n\t// Continue down the chain to handler etc\n\tc.Next()\n}", "func (w Web) Auth(c *gin.Context) {\n\tif expectedHash, ok := c.GetQuery(\"hash\"); ok {\n\t\tvar errorMessage string\n\t\tvar datas []string\n\t\tfor k, v := range c.Request.URL.Query() {\n\t\t\tif k == \"hash\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdatas = append(datas, fmt.Sprintf(\"%s=%s\", k, v[0]))\n\t\t}\n\t\tsort.Strings(datas)\n\t\tmac := hmac.New(sha256.New, w.SecretKey[:])\n\t\tauthDataStr := strings.Join(datas, \"\\n\")\n\t\tio.WriteString(mac, authDataStr)\n\t\thash := fmt.Sprintf(\"%x\", mac.Sum(nil))\n\t\tif expectedHash != hash {\n\t\t\terrorMessage = \"data is not from Telegram\"\n\t\t} else if authDate, err := strconv.Atoi(c.Query(\"auth_date\")); err == nil {\n\t\t\tif int64(time.Now().Sub(time.Unix(int64(authDate), 0)).Seconds()) > 86400 {\n\t\t\t\terrorMessage = \"Data is outdated\"\n\t\t\t} else {\n\t\t\t\tw.setCookie(c, \"auth_data_str\", authDataStr)\n\t\t\t\tw.setCookie(c, \"auth_data_hash\", hash)\n\t\t\t\tuserid, err := strconv.ParseInt(c.Query(\"id\"), 10, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\t_logger.Printf(\"can not convert %s to int. err* %v\", c.Query(\"id\"), err)\n\t\t\t\t}\n\t\t\t\tmsg := tgbotapi.NewMessage(userid, fmt.Sprintf(\"hello https://t.me/%d, welcome to NS_FC_bot.\", userid))\n\t\t\t\t_, err = w.TgBotClient.Send(msg)\n\t\t\t\tif err != nil {\n\t\t\t\t\t_logger.Printf(\"send message to user telegram failed. err: %v\", err)\n\t\t\t\t}\n\t\t\t\tw.setCookie(c, \"authed\", \"true\")\n\t\t\t\tc.Redirect(http.StatusTemporaryRedirect, \"/user/\"+c.Query(\"id\"))\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\terrorMessage = err.Error()\n\t\t}\n\t\tc.Redirect(http.StatusTemporaryRedirect, \"/login?error=\"+errorMessage)\n\t\treturn\n\t}\n}", "func AuthRequired(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tuser := session.Get(UserKey)\n\tif user == nil {\n\t\t// Abort the request with the appropriate error code\n\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\"error\": \"unauthorized\"})\n\t\treturn\n\t}\n\t// Continue down the chain to handler etc\n\tc.Next()\n}", "func (req *Request) GenerateAuth(creds *Credentials) error {\r\n\thawkcreds := &hawk.Credentials{\r\n\t\tID: creds.UserID,\r\n\t\tKey: creds.APIKey,\r\n\t\tHash: sha256.New,\r\n\t}\r\n\r\n\tclientAuth := hawk.NewRequestAuth(req.request, hawkcreds, 0)\r\n\tclientAuth.Ext = creds.OrganizationID\r\n\r\n\tif req.request.Body != nil {\r\n\t\treqBody, err := ioutil.ReadAll(req.request.Body)\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t\treq.request.Body = ioutil.NopCloser(bytes.NewBuffer(reqBody))\r\n\t\tif len(reqBody) > 0 {\r\n\t\t\tlog.Debugf(\"[DEBUG] Payload: %s\", string(reqBody))\r\n\t\t\tpayloadHash := clientAuth.PayloadHash(\"application/json\")\r\n\t\t\tpayloadHash.Write(reqBody)\r\n\t\t\tclientAuth.SetHash(payloadHash)\r\n\t\t\treq.request.Header.Set(\"Content-Type\", \"application/json\")\r\n\t\t}\r\n\t}\r\n\r\n\treq.request.Header.Set(\"Authorization\", clientAuth.RequestHeader())\r\n\treq.request.Header.Set(\"Accept\", \"application/json\")\r\n\r\n\treturn nil\r\n}", "func (h *AuthHandlers) Login(w http.ResponseWriter, req *http.Request) {\n\tvar err error\n\tvar data []byte\n\n\tsystemContext, err := h.getSystemContext(req)\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"request context retrevial failure\")\n\t\tmiddleware.ReturnError(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\tif data, err = ioutil.ReadAll(req.Body); err != nil {\n\t\tlog.Error().Err(err).Msg(\"read body error\")\n\t\tmiddleware.ReturnError(w, \"error reading login data\", 500)\n\t\treturn\n\t}\n\tdefer req.Body.Close()\n\n\tloginDetails := &authz.LoginDetails{}\n\tif err := json.Unmarshal(data, loginDetails); err != nil {\n\t\tlog.Error().Err(err).Msg(\"marshal body error\")\n\t\tmiddleware.ReturnError(w, \"error reading login data\", 500)\n\t\treturn\n\t}\n\n\tif err := h.validate.Struct(loginDetails); err != nil {\n\t\tmiddleware.ReturnError(w, \"validation failure \"+err.Error(), 500)\n\t\treturn\n\t}\n\tloginDetails.OrgName = strings.ToLower(loginDetails.OrgName)\n\tloginDetails.Username = strings.ToLower(loginDetails.Username)\n\n\tlog.Info().Str(\"org\", loginDetails.OrgName).Str(\"user\", loginDetails.Username).Msg(\"login attempt\")\n\n\torgData, err := h.getOrgByName(req.Context(), systemContext, loginDetails.OrgName)\n\tif err != nil {\n\t\tlog.Error().Err(err).Str(\"org\", loginDetails.OrgName).Str(\"user\", loginDetails.Username).Msg(\"failed to get organization from name\")\n\t\tmiddleware.ReturnError(w, \"login failed\", 403)\n\t\treturn\n\t}\n\n\tresults, err := h.authenticator.Login(req.Context(), orgData, loginDetails)\n\tif err != nil {\n\t\tlog.Error().Err(err).Str(\"org\", loginDetails.OrgName).Str(\"user\", loginDetails.Username).Msg(\"login failed\")\n\t\tif req.Context().Err() != nil {\n\t\t\tmiddleware.ReturnError(w, \"internal server error\", 500)\n\t\t\treturn\n\t\t}\n\t\tmiddleware.ReturnError(w, \"login failed\", 403)\n\t\treturn\n\t}\n\t// add subscription id to response\n\tresults[\"subscription_id\"] = fmt.Sprintf(\"%d\", orgData.SubscriptionID)\n\n\trespData, err := json.Marshal(results)\n\tif err != nil {\n\t\tmiddleware.ReturnError(w, \"marshal auth response failed\", 500)\n\t\treturn\n\t}\n\n\tlog.Info().Str(\"org\", loginDetails.OrgName).Str(\"user\", loginDetails.Username).Str(\"OrgCID\", orgData.OrgCID).Msg(\"setting orgCID in cookie\")\n\tif err := h.secureCookie.SetAuthCookie(w, results[\"access_token\"], orgData.OrgCID, orgData.SubscriptionID); err != nil {\n\t\tmiddleware.ReturnError(w, \"internal cookie failure\", 500)\n\t\treturn\n\t}\n\tw.WriteHeader(200)\n\tfmt.Fprint(w, string(respData))\n}", "func loginHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := context.Background()\n\tif b.authenticator == nil {\n\t\tvar err error\n\t\tb.authenticator, err = initAuth(ctx)\n\t\tif err != nil {\n\t\t\tlog.Print(\"loginHandler authenticator could not be initialized\")\n\t\t\thttp.Error(w, \"Server error\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\tsessionInfo := identity.InvalidSession()\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tlog.Printf(\"loginHandler: error parsing form: %v\", err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tusername := r.PostFormValue(\"UserName\")\n\tlog.Printf(\"loginHandler: username = %s\", username)\n\tpassword := r.PostFormValue(\"Password\")\n\tusers, err := b.authenticator.CheckLogin(ctx, username, password)\n\tif err != nil {\n\t\tlog.Printf(\"main.loginHandler checking login, %v\", err)\n\t\thttp.Error(w, \"Error checking login\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif len(users) != 1 {\n\t\tlog.Printf(\"loginHandler: user %s not found or password does not match\", username)\n\t} else {\n\t\tcookie, err := r.Cookie(\"session\")\n\t\tif err == nil {\n\t\t\tlog.Printf(\"loginHandler: updating session: %s\", cookie.Value)\n\t\t\tsessionInfo = b.authenticator.UpdateSession(ctx, cookie.Value, users[0], 1)\n\t\t}\n\t\tif (err != nil) || !sessionInfo.Valid {\n\t\t\tsessionid := identity.NewSessionId()\n\t\t\tdomain := config.GetSiteDomain()\n\t\t\tlog.Printf(\"loginHandler: setting new session %s for domain %s\",\n\t\t\t\tsessionid, domain)\n\t\t\tcookie := &http.Cookie{\n\t\t\t\tName: \"session\",\n\t\t\t\tValue: sessionid,\n\t\t\t\tDomain: domain,\n\t\t\t\tPath: \"/\",\n\t\t\t\tMaxAge: 86400 * 30, // One month\n\t\t\t}\n\t\t\thttp.SetCookie(w, cookie)\n\t\t\tsessionInfo = b.authenticator.SaveSession(ctx, sessionid, users[0], 1)\n\t\t}\n\t}\n\tif strings.Contains(r.Header.Get(\"Accept\"), \"application/json\") {\n\t\tsendJSON(w, sessionInfo)\n\t} else {\n\t\tif sessionInfo.Authenticated == 1 {\n\t\t\ttitle := b.webConfig.GetVarWithDefault(\"Title\", defTitle)\n\t\t\tcontent := htmlContent{\n\t\t\t\tTitle: title,\n\t\t\t}\n\t\t\tb.pageDisplayer.DisplayPage(w, \"index.html\", content)\n\t\t} else {\n\t\t\tloginFormHandler(w, r)\n\t\t}\n\t}\n}", "func gwLogin(c *gin.Context) {\n\ts := getHostServer(c)\n\treqId := getRequestId(s, c)\n\tvar err error\n\tvar hasCheckPass = false\n\tvar checker = s.AuthParamChecker\n\tvar authParam AuthParameter\n\tfor _, resolver := range s.AuthParamResolvers {\n\t\tauthParam = resolver.Resolve(c)\n\t\tif err = checker.Check(authParam); err == nil {\n\t\t\thasCheckPass = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !hasCheckPass {\n\t\tc.JSON(http.StatusBadRequest, s.RespBodyBuildFunc(http.StatusBadRequest, reqId, err, nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\t// Login\n\tuser, err := s.AuthManager.Login(authParam)\n\tif err != nil || user.IsEmpty() {\n\t\tc.JSON(http.StatusNotFound, s.RespBodyBuildFunc(http.StatusNotFound, reqId, err.Error(), nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tsid, credential, ok := encryptSid(s, authParam)\n\tif !ok {\n\t\tc.JSON(http.StatusInternalServerError, s.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"Create session ID fail.\", nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tif err := s.SessionStateManager.Save(sid, user); err != nil {\n\t\tc.JSON(http.StatusInternalServerError, s.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"Save session fail.\", err.Error()))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tvar userPerms []gin.H\n\tfor _, p := range user.Permissions {\n\t\tuserPerms = append(userPerms, gin.H{\n\t\t\t\"Key\": p.Key,\n\t\t\t\"Name\": p.Name,\n\t\t\t\"Desc\": p.Descriptor,\n\t\t})\n\t}\n\tcks := s.conf.Security.Auth.Cookie\n\texpiredAt := time.Duration(cks.MaxAge) * time.Second\n\tvar userRoles = gin.H{\n\t\t\"Id\": 0,\n\t\t\"name\": \"\",\n\t\t\"desc\": \"\",\n\t}\n\tpayload := gin.H{\n\t\t\"Credentials\": gin.H{\n\t\t\t\"Token\": credential,\n\t\t\t\"ExpiredAt\": time.Now().Add(expiredAt).Unix(),\n\t\t},\n\t\t\"Roles\": userRoles,\n\t\t\"Permissions\": userPerms,\n\t}\n\tbody := s.RespBodyBuildFunc(0, reqId, nil, payload)\n\tc.SetCookie(cks.Key, credential, cks.MaxAge, cks.Path, cks.Domain, cks.Secure, cks.HttpOnly)\n\tc.JSON(http.StatusOK, body)\n}", "func (au *Authenticator) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tsesSt, errGST := au.cx.getSessionStateFromRequest(r)\n\tif errGST != nil {\n\t\tvar authErrorReason string = \"\"\n\t\tvar wasError bool = false\n\t\tif errGST != session.ErrNoSessionId {\n\t\t\tif errGST == session.ErrInvalidScheme {\n\t\t\t\tauthErrorReason = WWWAuthenticateErrorInvalidRequest + \",\\n\" + \"error_description=\\\"Bearer scheme not provided\\\"\"\n\t\t\t\twasError = true\n\t\t\t} else if errGST == session.ErrInvalidSessionId {\n\t\t\t\tauthErrorReason = WWWAuthenticateErrorInvalidToken + \",\\n\" + \"error_description=\\\"token extracted not a valid session token\\\"\"\n\t\t\t\twasError = true\n\t\t\t}\n\t\t\tau.cx.logError(errGST, \"issue getting session from request\", \"\",\n\t\t\t\thttp.StatusInternalServerError)\n\t\t}\n\t\tcxWithAuthError := context.WithValue(r.Context(), authSessionErrorKey, wasError)\n\t\tcxWithAuthErrorValue := context.WithValue(cxWithAuthError, authSessionErrorValueKey, authErrorReason)\n\t\tcxWithSessionActive := context.WithValue(cxWithAuthErrorValue, authSessionActiveKey, false)\n\t\tcxWithUserAuthFalse := context.WithValue(cxWithSessionActive, authUserAuthenticatedKey, false)\n\n\t\trWithUserAuthFalse := r.WithContext(cxWithUserAuthFalse)\n\t\tau.handler.ServeHTTP(w, rWithUserAuthFalse)\n\t\treturn\n\t}\n\n\t//create a new request context containing the authenticated user\n\tcxWithSessionActive := context.WithValue(r.Context(), authSessionActiveKey, true)\n\tcxWithSessionState := context.WithValue(cxWithSessionActive, authSessionStateKey, sesSt)\n\n\tcxWithKey := context.WithValue(cxWithSessionState, authUserAuthenticatedKey, sesSt.Authenticated)\n\n\t//create a new request using that new context\n\trWithSession := r.WithContext(cxWithKey)\n\n\t//call the real handler, passing the new request\n\tau.handler.ServeHTTP(w, rWithSession)\n}", "func (h *GitHubOAuth) Login(c *router.Control) {\n\turl := h.oAuthConf.AuthCodeURL(h.state, oauth2.AccessTypeOnline)\n\thttp.Redirect(c.Writer, c.Request, url, http.StatusTemporaryRedirect)\n}", "func (pca Client) browserLogin(ctx context.Context, redirectURI *url.URL, params authority.AuthParams, openURL func(string) error) (interactiveAuthResult, error) {\n\t// start local redirect server so login can call us back\n\tport, err := parsePort(redirectURI)\n\tif err != nil {\n\t\treturn interactiveAuthResult{}, err\n\t}\n\tsrv, err := local.New(params.State, port)\n\tif err != nil {\n\t\treturn interactiveAuthResult{}, err\n\t}\n\tdefer srv.Shutdown()\n\tparams.Scopes = accesstokens.AppendDefaultScopes(params)\n\tauthURL, err := pca.base.AuthCodeURL(ctx, params.ClientID, srv.Addr, params.Scopes, params)\n\tif err != nil {\n\t\treturn interactiveAuthResult{}, err\n\t}\n\t// open browser window so user can select credentials\n\tif err := openURL(authURL); err != nil {\n\t\treturn interactiveAuthResult{}, err\n\t}\n\t// now wait until the logic calls us back\n\tres := srv.Result(ctx)\n\tif res.Err != nil {\n\t\treturn interactiveAuthResult{}, res.Err\n\t}\n\treturn interactiveAuthResult{\n\t\tauthCode: res.Code,\n\t\tredirectURI: srv.Addr,\n\t}, nil\n}", "func (c *client) Login(w http.ResponseWriter, r *http.Request) (string, error) {\n\tlogrus.Trace(\"Processing login request\")\n\n\t// generate a random string for creating the OAuth state\n\toAuthState, err := random.GenerateRandomString(32)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// temporarily redirect request to Github to begin workflow\n\thttp.Redirect(w, r, c.OConfig.AuthCodeURL(oAuthState), http.StatusTemporaryRedirect)\n\n\treturn oAuthState, nil\n}", "func AuthenticateRequest(req *http.Request, rw http.ResponseWriter) (acct *Account, err error) {\n\tif mockAccount != nil {\n\t\treturn mockAccount, nil\n\t}\n\tctx := appengine.NewContext(req)\n\n\tif slug := req.Header.Get(Headers[\"account\"]); slug != \"\" {\n\t\tapiKey := req.Header.Get(Headers[\"key\"])\n\t\tacct, err = authenticateAccount(ctx, slug, apiKey)\n\t\tif err == nil {\n\t\t\tsession, _ := GetSession(ctx)\n\t\t\tsendSession(req, rw, session)\n\t\t}\n\t\treturn\n\t} else if username := req.Header.Get(Headers[\"slug\"]); username != \"\" {\n\t\tpassword := req.Header.Get(Headers[\"password\"])\n\t\tacct, err = authenticateAccountByUser(ctx, username, password)\n\t\tif err == nil {\n\t\t\tsession, _ := GetSession(ctx)\n\t\t\tsendSession(req, rw, session)\n\t\t}\n\t\treturn\n\t} else {\n\t\tsessionKey := sessionKeyFromRequest(req)\n\t\tif sessionKey == \"\" {\n\t\t\treturn nil, Unauthenticated\n\t\t}\n\t\tacct, _, err := authenticateSession(ctx, sessionKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn acct, nil\n\t}\n}", "func (s *Server) Authenticate(wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\ts.Session = grequests.NewSession(nil)\n\tresp, err := s.Session.Get(s.URL+loginURL, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tlog.Fatalln(\"Failed to get csrf: \" + s.Name)\n\t}\n\n\tdoc, err := goquery.NewDocumentFromReader(strings.NewReader((resp.String())))\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tlog.Fatalln(\"Failed to parse html: \" + s.Name)\n\t}\n\n\tcsrfToken := \"\"\n\tdoc.Find(\"meta\").Each(func(i int, s *goquery.Selection) {\n\t\tif name, _ := s.Attr(\"name\"); name == \"csrf-token\" {\n\t\t\tcsrfToken, _ = s.Attr(\"content\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tresp, err = s.Session.Get(s.URL+verifyURL, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tlog.Fatalln(\"Failed to verify: \" + s.Name)\n\t}\n\n\ts.Headers = &map[string]string{\n\t\t\"csrf-token\": csrfToken,\n\t\t\"Connection\": \"keep-alive\",\n\t\t\"Content-Type\": \"application/json\",\n\t\t\"Accept\": \"application/x-www-form-urlencoded; charset=utf-8\",\n\t}\n\n\tresp, err = s.Session.Post(s.URL+passwordURL, &grequests.RequestOptions{\n\t\tJSON: map[string]string{\n\t\t\t\"username\": s.Username,\n\t\t\t\"password\": s.Password,\n\t\t},\n\t\t// Cookies: cookies.Cookies,\n\t\tHeaders: *s.Headers,\n\t})\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tlog.Fatalln(\"Failed to login: \" + s.Name)\n\t}\n\n\t// pretty.Println(resp.String())\n\tif !s.IsThirdParty {\n\t\t// log.Println(\"TOTP logic here...\")\n\t\ttotp := gotp.NewDefaultTOTP(s.Seed)\n\t\t// log.Println(totp.Now())\n\t\tresp, err = s.Session.Post(s.URL+challengeURL, &grequests.RequestOptions{\n\t\t\tJSON: map[string]string{\n\t\t\t\t\"username\": s.Username,\n\t\t\t\t\"password\": s.Password,\n\t\t\t\t\"challenge\": totp.Now(),\n\t\t\t},\n\t\t\t// Cookies: cookies.Cookies,\n\t\t\tHeaders: *s.Headers,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tlog.Fatalln(\"Failed to login: \" + s.Name)\n\t\t}\n\t\t// pretty.Println(resp.String())\n\t}\n}", "func authHandler(c *fb.Context, w http.ResponseWriter, r *http.Request) (int, error) {\n\tif c.Auth.Method == \"none\" {\n\t\t// NoAuth instances shouldn't call this method.\n\t\treturn 0, nil\n\t}\n\n\tif c.Auth.Method == \"proxy\" {\n\t\t// Receive the Username from the Header and check if it exists.\n\t\tu, err := c.Store.Users.GetByUsername(r.Header.Get(c.Auth.Header), c.NewFS)\n\t\tif err != nil {\n\t\t\treturn http.StatusForbidden, nil\n\t\t}\n\n\t\tc.User = u\n\t\treturn printToken(c, w)\n\t}\n\n\t// Receive the credentials from the request and unmarshal them.\n\tvar cred cred\n\n\tif r.Body == nil {\n\t\treturn http.StatusForbidden, nil\n\t}\n\n\terr := json.NewDecoder(r.Body).Decode(&cred)\n\tif err != nil {\n\t\treturn http.StatusForbidden, err\n\t}\n\n\t// Wenkun, Validate the token of user from cloud server and return JWT token.\n\tif c.Auth.Method != \"none\" {\n\t\tok, u := validateAuthByUserId(c, cred.Username)\n\t\tif !ok {\n\t\t\treturn http.StatusForbidden, nil\n\t\t}\n\n\t\tc.User = u\n\t\treturn printToken(c, w)\n\t}\n\n\t// If ReCaptcha is enabled, check the code.\n\tif len(c.ReCaptcha.Secret) > 0 {\n\t\tok, err := reCaptcha(c.ReCaptcha.Host, c.ReCaptcha.Secret, cred.ReCaptcha)\n\t\tif err != nil {\n\t\t\treturn http.StatusForbidden, err\n\t\t}\n\n\t\tif !ok {\n\t\t\treturn http.StatusForbidden, nil\n\t\t}\n\t}\n\n\t// Checks if the user exists.\n\tu, err := c.Store.Users.GetByUsername(cred.Username, c.NewFS)\n\tif err != nil {\n\t\treturn http.StatusForbidden, nil\n\t}\n\n\t// Checks if the password is correct.\n\tif !fb.CheckPasswordHash(cred.Password, u.Password) {\n\t\treturn http.StatusForbidden, nil\n\t}\n\n\tc.User = u\n\treturn printToken(c, w)\n}", "func (o *Okta) Authorize(authCodeURLCh chan string) error {\n\n\tstate, err := GenerateRandomString(16)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnonce, err := GenerateRandomString(16)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar authCodeURL string\n\tscopes := o.Scopes\n\n\t// handle offline\n\tif o.offlineAsScope() {\n\t\tscopes = append(scopes, \"offline_access\")\n\t\tauthCodeURL = o.OAuth2Config(scopes).AuthCodeURL(state)\n\t} else {\n\t\tauthCodeURL = o.OAuth2Config(scopes).AuthCodeURL(state, oauth2.AccessTypeOffline)\n\t}\n\n\tauthCodeURLParsed, err := url.Parse(authCodeURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tq := authCodeURLParsed.Query()\n\tq.Set(\"nonce\", nonce)\n\tq.Set(\"response_mode\", \"form_post\")\n\tauthCodeURLParsed.RawQuery = q.Encode()\n\tauthCodeURL = authCodeURLParsed.String()\n\n\ttokenCh, err := o.retrieveToken(state, nonce)\n\n\tfmt.Printf(\"\\nPlease navigate to the following URL and login to your Okta account:\\n\\n%s\\n\", authCodeURL)\n\t// publish URL in channel\n\tif authCodeURLCh != nil {\n\t\tauthCodeURLCh <- authCodeURL\n\t}\n\n\ttoken := <-tokenCh\n\n\to.printApiserverConfiguration()\n\n\to.printKubectlConfiguration(token.RefreshToken)\n\n\treturn nil\n\n}", "func (h *Handler) oidcCallback(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {\n\tresult, err := h.GetConfig().Auth.ValidateOIDCAuthCallback(r.URL.Query())\n\tif err != nil {\n\t\th.Warnf(\"Error validating callback: %v.\", err)\n\t\thttp.Redirect(w, r, \"/web/msg/error/login_failed\", http.StatusFound)\n\t\treturn nil, nil\n\t}\n\th.Infof(\"Callback: %v %v %v.\", result.Username, result.Identity, result.Req.Type)\n\treturn nil, h.CallbackHandler(w, r, webapi.CallbackParams{\n\t\tUsername: result.Username,\n\t\tIdentity: result.Identity,\n\t\tSession: result.Session,\n\t\tCert: result.Cert,\n\t\tTLSCert: result.TLSCert,\n\t\tHostSigners: result.HostSigners,\n\t\tType: result.Req.Type,\n\t\tCreateWebSession: result.Req.CreateWebSession,\n\t\tCSRFToken: result.Req.CSRFToken,\n\t\tPublicKey: result.Req.PublicKey,\n\t\tClientRedirectURL: result.Req.ClientRedirectURL,\n\t})\n}", "func init() {\n\tvanguard.AddAuthRoute(\"GET\", \"/U/bootstrapEveAuth\", bootstrapEveSSO)\n\tvanguard.AddAuthRoute(\"GET\", \"/U/bootstrapEveSSOAnswer\", bootstrapEveSSOAnswer)\n}", "func (c *MockController) Authenticate(sid string, env *common.SessionEnv) (*common.ConnectResult, error) {\n\tif env.URL == \"/failure\" {\n\t\treturn &common.ConnectResult{Transmissions: []string{\"unauthorized\"}}, errors.New(\"Auth Failed\")\n\t}\n\n\tif env.URL == \"/error\" {\n\t\treturn nil, errors.New(\"Unknown\")\n\t}\n\n\tres := common.ConnectResult{Identifier: (*env.Headers)[\"id\"], Transmissions: []string{\"welcome\"}}\n\n\tif (*env.Headers)[\"x-session-test\"] != \"\" {\n\t\tres.CState = map[string]string{\"_s_\": (*env.Headers)[\"x-session-test\"]}\n\t}\n\n\treturn &res, nil\n}", "func (app *application) requireAuthentication(next http.Handler) http.Handler {\r\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\r\n\t\t// If the client is not authenticated, redirect\r\n\t\tif loggedin := app.isAuthenticated(r); !loggedin {\r\n\t\t\thttp.Redirect(w, r, \"/login\", http.StatusSeeOther)\r\n\t\t\treturn\r\n\t\t}\r\n\t\t// If the client is not a verified user, redirect\r\n\t\tif verified := app.isVerified(r); !verified {\r\n\t\t\thttp.Redirect(w, r, \"/verifyuser\", http.StatusSeeOther)\r\n\t\t\treturn\r\n\t\t}\r\n\r\n\t\t/* This section should be reviewed */\r\n\t\t// Else, set the \"Cache-Control: no-store\" header so pages\r\n\t\t// which require authentication are not stored in cache\r\n\t\tw.Header().Add(\"Cache-Control\", \"no-store\")\r\n\r\n\t\t// and call the next handler in the chain.\r\n\t\tnext.ServeHTTP(w, r)\r\n\t})\r\n}", "func Login(c *gin.Context) {\n\t// check if request was a POST\n\tif strings.EqualFold(c.Request.Method, \"POST\") {\n\t\t// assume all POST requests are coming from the CLI\n\t\tAuthenticateCLI(c)\n\n\t\treturn\n\t}\n\n\t// capture an error if present\n\terr := c.Request.FormValue(\"error\")\n\tif len(err) > 0 {\n\t\t// redirect to initial login screen with error code\n\t\tc.Redirect(http.StatusTemporaryRedirect, \"/login/error?code=\"+err)\n\t}\n\n\t// redirect to our authentication handler\n\tc.Redirect(http.StatusTemporaryRedirect, \"/authenticate\")\n}" ]
[ "0.6855226", "0.62462103", "0.6234224", "0.6185395", "0.6133289", "0.60019743", "0.5928162", "0.58865625", "0.5875764", "0.58580756", "0.58038515", "0.57983834", "0.57867306", "0.5758774", "0.5740568", "0.5711506", "0.57114923", "0.57037616", "0.5664262", "0.5615334", "0.5576734", "0.55713916", "0.5565868", "0.5530536", "0.5522244", "0.55220455", "0.5519842", "0.55169815", "0.5456486", "0.5456198", "0.5456198", "0.5456198", "0.54527175", "0.5444984", "0.54343295", "0.5424753", "0.5401351", "0.53940976", "0.5375211", "0.5372447", "0.53622246", "0.5354", "0.53467137", "0.53150517", "0.5312027", "0.5309152", "0.53007317", "0.5300629", "0.52962905", "0.529557", "0.52901196", "0.5288546", "0.5278476", "0.52760434", "0.5272867", "0.5271669", "0.52707547", "0.5265359", "0.5254279", "0.5250907", "0.5248516", "0.5246875", "0.5236477", "0.52360344", "0.5223969", "0.52175933", "0.52172756", "0.521249", "0.5199328", "0.5190476", "0.51818776", "0.5174607", "0.5162935", "0.5159594", "0.51572174", "0.515302", "0.5146995", "0.5144141", "0.51361173", "0.5131672", "0.513002", "0.51160103", "0.51073515", "0.5107058", "0.5102673", "0.5085426", "0.5078216", "0.50705785", "0.5070557", "0.506702", "0.5066716", "0.5061604", "0.50598776", "0.5055585", "0.50498927", "0.5046348", "0.5044389", "0.50349265", "0.5033204", "0.5031861", "0.50315577" ]
0.0
-1
Creates a new empty Tuple of length n
func NewTuple(n int) *Tuple { t := &Tuple{} t.data = make([]interface{}, n) return t }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New(args ...float64) Tuple {\n\treturn args\n}", "func PyTuple_New(len int) *PyObject {\n\treturn c2go(C.__PyTuple_New(C.Py_ssize_t(len)))\n}", "func CloneValTuple(n ValTuple) ValTuple {\n\tres := make(ValTuple, 0, len(n))\n\tfor _, x := range n {\n\t\tres = append(res, CloneExpr(x))\n\t}\n\treturn res\n}", "func CloneTuple(t Tuple) Tuple {\n\tnewTuple := make(Tuple, len(t))\n\tfor i := range t {\n\t\tv := reflect.New(reflect.TypeOf(t[i]).Elem())\n\t\tv.Elem().Set(reflect.ValueOf(t[i]).Elem())\n\t\tnewTuple[i] = v.Interface()\n\t}\n\treturn newTuple\n}", "func execNewTuple(arity int, p *gop.Context) {\n\targs := p.GetArgs(arity)\n\tconv := func(args []interface{}) []*types.Var {\n\t\tret := make([]*types.Var, len(args))\n\t\tfor i, arg := range args {\n\t\t\tret[i] = arg.(*types.Var)\n\t\t}\n\t\treturn ret\n\t}\n\tret := types.NewTuple(conv(args[0:])...)\n\tp.Ret(arity, ret)\n}", "func CreateTuple(types ...Type) Type {\n\treturn tupleType(types)\n}", "func NewTupleFromSlice(slice []interface{}) *Tuple {\n\tt := &Tuple{}\n\tt.data = slice\n\treturn t\n}", "func New(namespace string, name string) (t TupleType) {\n\thash := syncHash.Hash([]byte(name))\n\tns_hash := syncHash.Hash([]byte(namespace))\n\tt = TupleType{namespace, name, ns_hash, hash, make([][]Field, 0), make(map[string]int)}\n\treturn\n}", "func NewProperties(n int) Properties { return make([]Property, n) }", "func NewFiveTuple(data []byte) *FiveTuple {\n\treturn &FiveTuple{data: data}\n}", "func New(n int) *Stack {\n\treturn &Stack{\n\t\tlength: n,\n\t\ttop: -1,\n\t\tarray: make([]int, n),\n\t}\n}", "func NewTupleFromItems(items ...interface{}) *Tuple {\n\tt := NewTuple(len(items))\n\tfor i, item := range items {\n\t\tt.Set(i, item)\n\t}\n\treturn t\n}", "func New(n int) *BitMap {\n\tbyteIndex := n >> 6\n\n\treturn &BitMap{\n\t\tdata: make([]uint64, byteIndex+1),\n\t\tbitsCount: n,\n\t}\n}", "func Constructor(n int) TicTacToe {\n return TicTacToe{\n n,\n 0,\n 0,\n make([]int, n),\n make([]int, n),\n }\n}", "func NewVector(x, y, z float64) *Tuple {\n\treturn &Tuple{x, y, z, 0.0}\n}", "func (this *Tuple) Left(n int) *Tuple {\n\treturn this.Slice(0, n)\n}", "func genN(value byte, n int) []byte {\n\tvalues := make([]byte, n, n)\n\n\tfor i := 0; i < n; i++ {\n\t\tvalues = append(values, value)\n\t}\n\n\treturn values\n}", "func Create(n int) UnionFind {\n var id = make([]int, n)\n for i, _ := range id { id[i] = i }\n var size = make([] int, n)\n for i, _ := range size { size[i] = 1 }\n\n return UnionFind { id: id, size: size, Count: n }\n}", "func New(n int) *BitSet {\n\tb := new(BitSet)\n\tb.length = n\n\tb.data = make([]byte, (n+7)>>3)\n\treturn b\n}", "func NewLIFO(ts ...T) *LIFO {\n\ts := &LIFO{}\n\tfor i := range ts {\n\t\ts.Push(ts[i])\n\t}\n\treturn s\n}", "func Multiply(t Tuplelike, n float64) Tuplelike {\n\tresult := []float64{}\n\n\tfor _, value := range t.Values() {\n\t\tresult = append(result, value*n)\n\t}\n\n\treturn Tuple(result)\n}", "func CloneValues(n Values) Values {\n\tres := make(Values, 0, len(n))\n\tfor _, x := range n {\n\t\tres = append(res, CloneValTuple(x))\n\t}\n\treturn res\n}", "func bitVecNew(n uint) *bitVec {\n\tvar b *bitVec = new(bitVec)\n\tb.bits = make([]uint64, n)\n\tb.length = n\n\treturn b\n}", "func New(n int) Ranges {\n\tif n < 0 || n > 1024 {\n\t\tpanic(\"invalid range\")\n\t}\n\tparts := big.NewInt(int64(n))\n\tchunk := big.NewInt(0).Div(maxuuid, parts)\n\n\tranges := make(Ranges, n)\n\tfor i := 0; i < n; i++ {\n\t\tlow := big.NewInt(0).Mul(chunk, big.NewInt(int64(i)))\n\t\tlastInRange := big.NewInt(0).Mul(chunk, big.NewInt(int64(i+1)))\n\t\thigh := big.NewInt(0).Sub(lastInRange, big.NewInt(1))\n\t\tranges[i] = Range{From: toUUID(low), To: toUUID(high)}\n\t}\n\treturn ranges\n}", "func NewPoint(x, y, z float64) *Tuple {\n\treturn &Tuple{x, y, z, 1.0}\n}", "func NewTransactionN(n int) *Transaction {\n\treturn &Transaction{Deltas: make([]Delta, 0, n), deltas: make(map[Delta]struct{}, n)}\n}", "func NewWeightedQuickUnion(n int) *wQuickUnion {\n\twqu := &wQuickUnion{}\n\twqu.id = make([]int, n)\n\twqu.sz = make([]int, n)\n\tfor i := 0; i < n; i++ {\n\t\twqu.id[i] = i\n\t\twqu.sz[i] = 1\n\t}\n\treturn wqu\n}", "func Constructor(n int) TicTacToe {\n\ttable := make([][]int, n)\n\tfor i := 0; i < n; i++ {\n\t\ttable[i] = make([]int, n)\n\t}\n\treturn TicTacToe{table: table}\n}", "func (this *Tuple) Set(n int, item interface{}) {\n\tthis.data[this.Offset(n)] = item\n}", "func Constructor(n int) TicTacToe {\n\treturn TicTacToe{make([]int, n), make([]int, n), 0, 0, n, 0}\n}", "func MakeTuple(v []interface{}) (skylark.Tuple, error) {\n\tvals := make([]skylark.Value, len(v))\n\tfor i := range v {\n\t\tval, err := ToValue(v[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvals[i] = val\n\t}\n\treturn skylark.Tuple(vals), nil\n}", "func (s Record) NewPairs(n int32) (Pair_List, error) {\n\tl, err := NewPair_List(s.Struct.Segment(), n)\n\tif err != nil {\n\t\treturn Pair_List{}, err\n\t}\n\terr = s.Struct.SetPtr(7, l.List.ToPtr())\n\treturn l, err\n}", "func NewPoint(x, y, z float64) Tuple {\n\treturn Tuple{\n\t\tX: x,\n\t\tY: y,\n\t\tZ: z,\n\t\tW: pointW,\n\t}\n}", "func VariadicTupleType(types []interface{}) dgo.TupleType {\n\tn := len(types)\n\tif n == 0 {\n\t\tpanic(errors.New(`a variadic tuple must have at least one element`))\n\t}\n\treturn newTupleType(types, true)\n}", "func NewStack(n int) (*Stack, error) {\n\tif n < 1 {\n\t\treturn nil, fmt.Errorf(\"stack size must be larger than 0\")\n\t}\n\ts := &Stack{\n\t\tdata: make([]Elem, 0, n),\n\t\ttop: -1,\n\t}\n\n\treturn s, nil\n}", "func New(n, k int) *Tree {\n\tvar t *Tree\n\tfor _, v := range rand.Perm(n) {\n\t\tt = insert(t, (1+v)*k)\n\t}\n\treturn t\n}", "func Tuple(argv []TermT) TermT {\n\tcount := C.uint32_t(len(argv))\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\tif count == 0 {\n\t\treturn NullTerm\n\t}\n\treturn TermT(C.yices_tuple(count, (*C.term_t)(&argv[0])))\n}", "func (b *BlockingForwardBox) EmitTuples(n int) {\n\tb.m.Lock()\n\tdefer b.m.Unlock()\n\tb.cnt += n\n\tb.c.Broadcast()\n}", "func New(length int) (nid string) {\n nid = \"\"\n\n for i := 0; i < length; i++ {\n var (\n r1 int\n )\n\n r1 = rnd.Intn(9)\n\n if i == 0 {\n for r1 == 0 {\n r1 = rnd.Intn(9)\n }\n }\n\n nid += strconv.Itoa(r1)\n }\n return\n}", "func newBuckets(n int) *buckets {\n\treturn &buckets{counts: make([]uint64, n)}\n}", "func (this *Tuple) Get(n int) interface{} {\n\titem := this.data[this.Offset(n)]\n\treturn item\n}", "func (s Stream) NewTimes(n int32) (capnp.Int64List, error) {\n\tl, err := capnp.NewInt64List(s.Struct.Segment(), n)\n\tif err != nil {\n\t\treturn capnp.Int64List{}, err\n\t}\n\terr = s.Struct.SetPtr(0, l.List.ToPtr())\n\treturn l, err\n}", "func New(x, y, z *big.Int) *Chunk {\n\tconst shift = 6 // 1<<6 == 64\n\n\tc := &Chunk{}\n\n\tc.X.Set(x)\n\tc.Y.Set(y)\n\tc.Z.Set(z)\n\n\treturn c\n}", "func Grow[S ~[]E, E any](s S, n int) S {\n\tif n <= 0 {\n\t\treturn s\n\t}\n\treturn append(s, make(S, n)...)\n}", "func Repeat[T any](t T, n int) (tt []T) {\n\tfor i := 0; i < n; i++ {\n\t\ttt = append(tt, t)\n\t}\n\treturn tt\n}", "func New(n int, size int) Number {\n\tz2n := zero2nine.FromInt(n)\n\tnum := &number{size: size}\n\tswitch z2n {\n\tcase zero2nine.Zero:\n\t\treturn &zero{num}\n\tcase zero2nine.One:\n\t\treturn &one{num}\n\tcase zero2nine.Two:\n\t\treturn &two{num}\n\tcase zero2nine.Three:\n\t\treturn &three{num}\n\tcase zero2nine.Four:\n\t\treturn &four{num}\n\tcase zero2nine.Five:\n\t\treturn &five{num}\n\tcase zero2nine.Six:\n\t\treturn &six{num}\n\tcase zero2nine.Seven:\n\t\treturn &seven{num}\n\tcase zero2nine.Eight:\n\t\treturn &eight{num}\n\tcase zero2nine.Nine:\n\t\treturn &nine{num}\n\tdefault:\n\t\treturn nil\n\t}\n}", "func New() (*T) {\n\n\tme := T{\n\t\tcount: 0,\n\t\tdatum: \"\",\n\t}\n\n\treturn &me\n}", "func Constructor(n int) TicTacToe {\n\tgrid := make([][]int, n)\n\tfor i:=0; i< n;i++ {\n\t\tgrid[i] = make([]int, n)\n\t}\n\treturn TicTacToe{\n\t\tgrid: grid,\n\t\tn: n,\n\t}\n}", "func New(size int) Vec {\n\treturn Vec(make([]float64, size))\n}", "func New(num int) Bits {\n\tif num < 0 {\n\t\tpanic(\"negative number of bits\")\n\t}\n\treturn Bits{num, make([]uint64, (num+63)>>6)}\n}", "func CreateString(n int) Generator {\n\tif n <= 0 {\n\t\treturn new(stringParens)\n\t}\n\tstate := make([]byte, 2*n+1, 2*n+1)\n\tfor k := 1; k <= n; k++ {\n\t\tstate[2*k-1] = '('\n\t\tstate[2*k] = ')'\n\t}\n\tstate[0] = ')' // Sentinel\n\treturn &stringParens{n, 2*n - 1, true, state}\n}", "func NewBitmask(n int) Bitmask {\n\treturn make(Bitmask, (n+63)/64)\n}", "func (sym *symtab) buildTuple(tuple *types.Tuple, varnm string, methvar string) (string, error) {\n\tsz := tuple.Len()\n\tif sz == 0 {\n\t\treturn \"\", fmt.Errorf(\"buildTuple: no elements\")\n\t}\n\t// TODO: https://www.reddit.com/r/Python/comments/3618cd/calling_back_python_instance_methods_from_c/\n\t// could not get this to work across threads for methods -- and furthermore the basic version with\n\t// CallObject works fine within the same thread, so all this extra work seems unnecessary.\n\t//\n\t// bstr := fmt.Sprintf(\"var %s *C.PyObject\\n\", varnm)\n\t// bstr += fmt.Sprintf(\"_pyargstidx := 0\\n\")\n\t// bstr += fmt.Sprintf(\"_pyargidx := C.long(0)\\n\")\n\t// if methvar != \"\" {\n\t// \tbstr += fmt.Sprintf(\"if C.gopy_method_check(%s) != 0 {\\n\", methvar)\n\t// \tbstr += fmt.Sprintf(\"\\tC.gopy_incref(%s)\\n\", methvar)\n\t// \tbstr += fmt.Sprintf(\"\\t%s = C.PyTuple_New(%d)\\n\", varnm, sz+1)\n\t// \tbstr += fmt.Sprintf(\"\\tC.PyTuple_SetItem(%s, 0, C.PyMethod_Self(%s))\\n\", varnm, methvar)\n\t// \tbstr += fmt.Sprintf(\"\\t_pyargstidx = 1\\n\")\n\t// \tbstr += fmt.Sprintf(\"\\t%[1]s = C.PyMethod_Function(%[1]s)\\n\", methvar)\n\t// \tbstr += fmt.Sprintf(\"} else {\\n\")\n\t// \tbstr += fmt.Sprintf(\"\\t%s = C.PyTuple_New(%d)\\n\", varnm, sz)\n\t// \tbstr += fmt.Sprintf(\"}\\n\")\n\t// }\n\n\t// TODO: more efficient to use strings.Builder here..\n\tbstr := fmt.Sprintf(\"%s := C.PyTuple_New(%d)\\n\", varnm, sz)\n\tfor i := 0; i < sz; i++ {\n\t\tv := tuple.At(i)\n\t\ttyp := v.Type()\n\t\tanm := pySafeArg(v.Name(), i)\n\t\tvsym := sym.symtype(typ)\n\t\tif vsym == nil {\n\t\t\terr := sym.addType(v, typ)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tvsym = sym.symtype(typ)\n\t\t\tif vsym == nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"buildTuple: type still not found: %s\", typ.String())\n\t\t\t}\n\t\t}\n\t\t// bstr += fmt.Sprintf(\"_pyargidx = C.long(_pyargstidx + %d)\\n\", i)\n\n\t\tbt, isb := typ.Underlying().(*types.Basic)\n\t\tswitch {\n\t\tcase vsym.goname == \"interface{}\":\n\t\t\tbstr += fmt.Sprintf(\"C.PyTuple_SetItem(%s, %d, C.gopy_build_string(%s(%s)%s))\\n\", varnm, i, vsym.go2py, anm, vsym.go2pyParenEx)\n\t\tcase vsym.hasHandle(): // note: assuming int64 handles\n\t\t\tbstr += fmt.Sprintf(\"C.PyTuple_SetItem(%s, %d, C.gopy_build_int64(C.int64_t(%s(%s)%s)))\\n\", varnm, i, vsym.go2py, anm, vsym.go2pyParenEx)\n\t\tcase isb:\n\t\t\tbk := bt.Kind()\n\t\t\tswitch {\n\t\t\tcase types.Int <= bk && bk <= types.Int64:\n\t\t\t\tbstr += fmt.Sprintf(\"C.PyTuple_SetItem(%s, %d, C.gopy_build_int64(C.int64_t(%s)))\\n\", varnm, i, anm)\n\t\t\tcase types.Uint <= bk && bk <= types.Uintptr:\n\t\t\t\tbstr += fmt.Sprintf(\"C.PyTuple_SetItem(%s, %d, C.gopy_build_uint64(C.uint64_t(%s)))\\n\", varnm, i, anm)\n\t\t\tcase types.Float32 <= bk && bk <= types.Float64:\n\t\t\t\tbstr += fmt.Sprintf(\"C.PyTuple_SetItem(%s, %d, C.gopy_build_float64(C.double(%s)))\\n\", varnm, i, anm)\n\t\t\tcase bk == types.String:\n\t\t\t\tbstr += fmt.Sprintf(\"C.PyTuple_SetItem(%s, %d, C.gopy_build_string(C.CString(%s)))\\n\", varnm, i, anm)\n\t\t\tcase bk == types.Bool:\n\t\t\t\tbstr += fmt.Sprintf(\"C.PyTuple_SetItem(%s, %d, C.gopy_build_bool(C.uint8_t(boolGoToPy(%s))))\\n\", varnm, i, anm)\n\t\t\t}\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"buildTuple: type not handled: %s\", typ.String())\n\t\t}\n\t}\n\treturn bstr, nil\n}", "func New(value ...interface{}) Stack {\n\ts := Stack{}\n\tfor _, e := range value {\n\t\ts.Push(e)\n\t}\n\treturn s\n}", "func NewSlice(n sort.Interface) *Slice {\n\ts := &Slice{Interface: n, idx: make([]int, n.Len())}\n\tfor i := range s.idx {\n\t\ts.idx[i] = i\n\t}\n\treturn s\n}", "func NewNil() NilVal { return NilVal{} }", "func (s *BaseSyslParserListener) EnterEmpty_tuple(ctx *Empty_tupleContext) {}", "func (s StreamCollection) NewTimes(n int32) (capnp.Int64List, error) {\n\tl, err := capnp.NewInt64List(s.Struct.Segment(), n)\n\tif err != nil {\n\t\treturn capnp.Int64List{}, err\n\t}\n\terr = s.Struct.SetPtr(0, l.List.ToPtr())\n\treturn l, err\n}", "func New(elems ...interface{}) List {\n\tl := Mzero()\n\tfor _, elem := range elems {\n\t\tl = Cons(elem, l)\n\t}\n\treturn Reverse(l)\n}", "func New(k int) *Tree {\n\tvar t *Tree\n\tfor _, v := range []int{6, 4, 5, 2, 9, 8, 7, 3, 1} {\n\t\tt = insert(t, v)\n\t}\n\treturn t\n}", "func (this *Tuple) Right(n int) *Tuple {\n\tlength := this.Len()\n\tn = max(0, length-n)\n\treturn this.Slice(n, length)\n}", "func New(size uint64) *BitMap {\n\n\tlength := size / 64\n\n\tif size%64 > 0 {\n\t\tlength = length + 1\n\t}\n\n\treturn &BitMap{make([]uint64, length), size}\n\n}", "func (s Stream) NewValues(n int32) (capnp.Float64List, error) {\n\tl, err := capnp.NewFloat64List(s.Struct.Segment(), n)\n\tif err != nil {\n\t\treturn capnp.Float64List{}, err\n\t}\n\terr = s.Struct.SetPtr(1, l.List.ToPtr())\n\treturn l, err\n}", "func NewStringSlice(n ...string) *Slice { return NewSlice(sort.StringSlice(n)) }", "func NewBlank() Square {\n\treturn Square{\n\t\tArea: 0,\n\t\tPossible: make([]Rect, 0, 5),\n\t}\n}", "func (this *Tuple) Copy() *Tuple {\n\tt := NewTuple(this.Len())\n\tcopy(t.data, this.data)\n\treturn t\n}", "func (s *TupleIncrementalEmitterSource) EmitTuplesNB(n int) {\n\ts.m.Lock()\n\tdefer s.m.Unlock()\n\ts.cnt += n\n\ts.state.cond.Broadcast()\n}", "func NewArray(n int) *Array {\n\tif n < 0 {\n\t\tpanic(\"bit: array size must be greater than or equal 0\")\n\t}\n\n\tb := make([]uint64, 1, (n>>6)+1)\n\treturn &Array{b, 0}\n}", "func initVector(n int, value float64) []float64 {\n\tx := make([]float64, n)\n\tfor i := 0; i < n; i++ {\n\t\tx[i] = value\n\t}\n\treturn x\n}", "func New(values ...uint16) (l *List) {\n\tl = &List{} // init the ptr\n\tfor _, value := range values {\n\t\tl.Insert(value)\n\t}\n\treturn l\n}", "func Vector(x, y, z float64) *Tuple {\n\treturn &Tuple{x, y, z, 0.0}\n}", "func DefineTuple(types []*IHType) *HTuple {\n\treturn &HTuple{types: types}\n}", "func New(l int) Bitset {\n\treturn Bitset{\n\t\tbitvec: make([]int32, l),\n\t\tlength: (l / 32) + 1,\n\t\tbitlength: l,\n\t}\n}", "func NewTree(n int) *Tree {\n\treturn &Tree{\n\t\tn: n,\n\t\tbit: make([]int, n+1),\n\t}\n}", "func New(i int) *Buffer {\n\treturn &Buffer{\n\t\tsize: i,\n\t}\n}", "func duplicateElement(value, n int) []int {\n\tarr := make([]int, n)\n\tfor i := 0; i < n; i++ {\n\t\tarr[i] = value\n\t}\n\n\treturn arr\n}", "func (t *dataType) Length(n int) *dataType {\n\tt.str.Length(n)\n\treturn t\n}", "func Vector(x, y, z float64) Tuple {\n\treturn Tuple{x, y, z, 0}\n}", "func New(items ...uint32) *Set {\n\ts := &Set{items: make(map[uint32]struct{}, len(items))}\n\ts.Add(items...)\n\treturn s\n}", "func New(k int) *Tree {\n\tvar t *Tree\n\tfor _, v := range rand.Perm(10) {\n\t\tt = insert(t, (1+v)*k)\n\t}\n\treturn t\n}", "func New(k int) *Tree {\n\tvar t *Tree\n\tfor _, v := range rand.Perm(10) {\n\t\tt = insert(t, (1+v)*k)\n\t}\n\treturn t\n}", "func New(length int) *BitArray {\n\tlenpad := nwords(length) * _BytesPW\n\treturn &BitArray{\n\t\tlenpad: lenpad,\n\t\tlength: length,\n\t\tbytes: make([]byte, lenpad, lenpad),\n\t}\n}", "func New() *List {\n return &List{size:0}\n}", "func NewVecN(n int) *VecN {\n\tif shouldPool {\n\t\treturn &VecN{vec: grabFromPool(n)}\n\t} else {\n\t\treturn &VecN{vec: make([]float64, n)}\n\t}\n}", "func New(elements []int) LinkedList {\n\tll := LinkedList{}\n\n\tfor _, item := range elements {\n\t\tll.Append(item)\n\t}\n\n\treturn ll\n}", "func GenerateEmpty(n, m int) Matrix {\n\tout := make([]Row, n)\n\n\tfor i := 0; i < n; i++ {\n\t\tout[i] = NewRow(m)\n\t}\n\n\treturn Matrix(out)\n}", "func NEW_VECTOR(indices []int, values []float64, n int) VECTOR_TYPE {\n if len(indices) != len(values) {\n panic(\"number of indices does not match number of values\")\n }\n r := NIL_VECTOR(n)\n for i, k := range indices {\n if k >= n {\n panic(\"index larger than vector dimension\")\n }\n if _, ok := r.values[k]; ok {\n panic(\"index appeared multiple times\")\n } else {\n if values[i] != 0.0 {\n r.values[k] = NEW_SCALAR(values[i])\n r.indexInsert(k)\n }\n }\n }\n return r\n}", "func (td TupleDesc) WithoutFixedAccess() TupleDesc {\n\treturn TupleDesc{Types: td.Types, cmp: td.cmp}\n}", "func (a *DatumAlloc) NewDTuple(v tree.DTuple) *tree.DTuple {\n\tif a.AllocSize == 0 {\n\t\ta.AllocSize = defaultDatumAllocSize\n\t}\n\tbuf := &a.dtupleAlloc\n\tif len(*buf) == 0 {\n\t\t*buf = make([]tree.DTuple, a.AllocSize)\n\t}\n\tr := &(*buf)[0]\n\t*r = v\n\t*buf = (*buf)[1:]\n\treturn r\n}", "func NewPattern(length int) Pattern {\n return Pattern{ length }\n}", "func MakeNString(n int, s string) string {\n\tresString := \"\"\n\tfor i := 0; i < n; i++ {\n\t\tresString += s\n\t}\n\treturn resString\n}", "func TupleType(tau []TypeT) TypeT {\n\ttauLen := len(tau)\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\tif tauLen == 0 {\n\t\treturn NullType\n\t}\n\treturn TypeT(C.yices_tuple_type(C.uint32_t(tauLen), (*C.type_t)(&tau[0])))\n}", "func NewListNode(values ...int) *ListNode {\n\tif len(values) == 0 {\n\t\treturn nil\n\t}\n\troot := &ListNode{Val: values[0]}\n\tl1 := root\n\n\tfor _, i := range values[1:] {\n\t\tl2 := l1.Append(i)\n\t\tl1 = l2\n\t}\n\n\treturn root\n\n}", "func Point(x, y, z float64) Tuple {\n\treturn Tuple{x, y, z, 1}\n}", "func New() Type {\n\treturn Type(0)\n}", "func New(seed uint64) nhash.Hash64 {\n\ts := n(seed)\n\treturn s\n}", "func createNGrams(words []string, n int) ([]NGram, error) {\n\tif n < 0 {\n\t\treturn nil, errors.New(\"n of n-gram needs to be > 0\")\n\t}\n\t// n reduces total number of n-grams but even if n equals the number of\n\t// words, one n-gram is created.\n\tnumberOfNGrams := len(words) - (n - 1)\n\tnGramList := make([]NGram, numberOfNGrams)\n\tfor i := 0; i < numberOfNGrams; i++ {\n\t\tnGram := make(NGram, n)\n\t\tfor j := 0; j < n; j++ {\n\t\t\tnGram[j] = words[i+j]\n\t\t}\n\t\tnGramList[i] = nGram\n\t}\n\treturn nGramList, nil\n}", "func New(n uint) *Swing {\n\treturn &Swing{Sieve: sieve.New(uint64(n))}\n}", "func appendRepeat(buf []byte, s string, n int) []byte {\n\tfor i := 0; i < n; i++ {\n\t\tbuf = append(buf, s...)\n\t}\n\treturn buf\n}", "func (s *BaseSyslParserListener) ExitEmpty_tuple(ctx *Empty_tupleContext) {}" ]
[ "0.6322758", "0.6155864", "0.5810423", "0.5676568", "0.5622864", "0.5439409", "0.54283744", "0.5407682", "0.53979015", "0.53659743", "0.53174645", "0.53048897", "0.5283917", "0.5263617", "0.5229603", "0.51696014", "0.5165112", "0.5083791", "0.5040847", "0.5009695", "0.500642", "0.50028574", "0.50006425", "0.49978283", "0.4982859", "0.49621555", "0.49360427", "0.49337998", "0.49256632", "0.49161834", "0.49007708", "0.48837075", "0.4873057", "0.48564807", "0.4856147", "0.48427626", "0.48395577", "0.48393264", "0.4820383", "0.48164964", "0.48140708", "0.47881043", "0.47748035", "0.47590998", "0.47555083", "0.47553474", "0.47538558", "0.4746093", "0.4726585", "0.47041017", "0.46991906", "0.46903294", "0.46580365", "0.46495697", "0.46425992", "0.46397173", "0.4626006", "0.46254525", "0.46241865", "0.46075067", "0.4604725", "0.45996526", "0.4594109", "0.458951", "0.45863524", "0.45852697", "0.45849296", "0.45673272", "0.45661244", "0.4565526", "0.45618075", "0.45596725", "0.45505056", "0.45471948", "0.45255223", "0.4521459", "0.45196325", "0.45185328", "0.45161507", "0.45154694", "0.45154694", "0.45114854", "0.45070753", "0.45058578", "0.4503434", "0.449985", "0.44942054", "0.44900903", "0.44852254", "0.44844204", "0.44813895", "0.44784135", "0.4477165", "0.4474286", "0.44685796", "0.44676515", "0.444868", "0.44369203", "0.44357574", "0.44353694" ]
0.7744698
0
Creates a new Tuple from an existing slice
func NewTupleFromSlice(slice []interface{}) *Tuple { t := &Tuple{} t.data = slice return t }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *Tuple) Slice(start int, end int) *Tuple {\n\tc := this.Copy()\n\tmax := this.Len()\n\tstart = min(c.Offset(start), max)\n\tend = min(c.Offset(end), max)\n\tc.data = c.data[start:end]\n\treturn c\n}", "func CloneTuple(t Tuple) Tuple {\n\tnewTuple := make(Tuple, len(t))\n\tfor i := range t {\n\t\tv := reflect.New(reflect.TypeOf(t[i]).Elem())\n\t\tv.Elem().Set(reflect.ValueOf(t[i]).Elem())\n\t\tnewTuple[i] = v.Interface()\n\t}\n\treturn newTuple\n}", "func NewTuple(n int) *Tuple {\n\tt := &Tuple{}\n\tt.data = make([]interface{}, n)\n\treturn t\n}", "func MakeTuple(v []interface{}) (skylark.Tuple, error) {\n\tvals := make([]skylark.Value, len(v))\n\tfor i := range v {\n\t\tval, err := ToValue(v[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvals[i] = val\n\t}\n\treturn skylark.Tuple(vals), nil\n}", "func (s PointBuffer) SubSlice(low int, high int) PointBuffer {\n\tinBounds := low >= 0 && low <= high && high <= s.cap\n\tif !inBounds {\n\t\tpanic(fmt.Errorf(\n\t\t\t\"runtime error: slice bounds out of range [%d:%d] with capacity %d\",\n\t\t\tlow, high, s.cap,\n\t\t))\n\t}\n\tvar tVar Point\n\ttSize := unsafe.Sizeof(tVar)\n\ttype internalPtr struct {\n\t\toffset uintptr\n\t\tbucketIdx uint8\n\t\tarenaMask uint16\n\t}\n\tcurrentPtr := *(*internalPtr)(unsafe.Pointer(&s.data))\n\tnewPtr := internalPtr{\n\t\toffset: currentPtr.offset + uintptr(low*int(tSize)),\n\t\tbucketIdx: currentPtr.bucketIdx,\n\t\tarenaMask: currentPtr.arenaMask,\n\t}\n\treturn PointBuffer{\n\t\tdata: *(*arena.Ptr)(unsafe.Pointer(&newPtr)),\n\t\tlen: high - low,\n\t\tcap: s.cap - low,\n\t}\n}", "func NewTupleFromItems(items ...interface{}) *Tuple {\n\tt := NewTuple(len(items))\n\tfor i, item := range items {\n\t\tt.Set(i, item)\n\t}\n\treturn t\n}", "func Slice(t *Tensor) interface{} {\n\tlength := int(DimProduct(t.Dims))\n\tsliceHeader := reflect.SliceHeader{\n\t\tData: uintptr(unsafe.Pointer(&t.Buffer[0])),\n\t\tCap: length,\n\t\tLen: length,\n\t}\n\tval := reflect.NewAt(DtypeToSliceType[t.Dtype], unsafe.Pointer(&sliceHeader)).Elem()\n\treturn val.Interface()\n}", "func (this *Tuple) Copy() *Tuple {\n\tt := NewTuple(this.Len())\n\tcopy(t.data, this.data)\n\treturn t\n}", "func SelectFeatures(tuples []base.Tuple, features []int) []base.Tuple {\n if (len(features) <= 0) {\n return tuples;\n }\n\n var tupleType reflect.Type = reflect.TypeOf(tuples[0]);\n\n var rtn []base.Tuple = make([]base.Tuple, len(tuples));\n for tupleIndex, tuple := range(tuples) {\n var data []interface{} = make([]interface{}, len(features));\n for featurePosition, featureIndex := range(features) {\n data[featurePosition] = tuple.GetData(featureIndex);\n }\n\n rtn[tupleIndex] = base.NewTypedTuple(tupleType, data, tuple.GetClass());\n }\n\n return rtn;\n}", "func newPtrFromSlice(basics interface{}) reflect.Value {\n\tany := reflect.ValueOf(basics)\n\treturn reflect.New(any.Type().Elem())\n}", "func (items IntSlice) SubSlice(i, j int) Interface { return items[i:j] }", "func genericSliceOf(slice interface{}) reflect.Value {\n\tsliceValue := reflect.ValueOf(slice)\n\tlength := sliceValue.Len()\n\tsliceAddr := reflect.New(reflect.MakeSlice(\n\t\treflect.TypeOf(slice),\n\t\tlength,\n\t\tlength,\n\t).Type())\n\tfor i := 0; i < length; i++ {\n\t\tvalue := sliceValue.Index(i)\n\t\tap := reflect.Append(sliceAddr.Elem(), value)\n\t\tsliceAddr.Elem().Set(ap)\n\t}\n\treturn sliceAddr.Elem()\n}", "func (s *VectorImplSlice) Slice(start, stop int) *VectorImplSlice {\n\tassertSliceOk(start, stop, s.stop-s.start)\n\treturn &VectorImplSlice{vector: s.vector, start: s.start + start, stop: s.start + stop}\n}", "func PyTuple_New(len int) *PyObject {\n\treturn c2go(C.__PyTuple_New(C.Py_ssize_t(len)))\n}", "func Sub(el ...tuple.TupleElement) Subspace {\n\treturn subspace{tuple.Tuple(el).Pack()}\n}", "func (t *Tuple) Sub(o *Tuple) *Tuple {\n\treturn &Tuple{\n\t\tt.x - o.x,\n\t\tt.y - o.y,\n\t\tt.z - o.z,\n\t\tt.w - o.w,\n\t}\n\n}", "func (l *list) Slice(first int, last int) interface{} {\n\ttypeOf := reflect.TypeOf(l.t)\n\tsliceOf := reflect.SliceOf(typeOf)\n\tvar result = reflect.ValueOf(reflect.New(sliceOf).Interface()).Elem()\n\n\tfor _, v := range l.elements[first:last] {\n\t\tresult.Set(reflect.Append(result, reflect.ValueOf(v)))\n\t}\n\n\treturn result.Interface()\n}", "func NewSlice() Slice {\n\torig := []otlpcommon.AnyValue(nil)\n\treturn Slice(internal.NewSlice(&orig))\n}", "func NewSlice(basic Basic) *Slice {\n\treturn &Slice{basic, basic.String()}\n}", "func (t *Dense) Slice(slices ...Slice) (retVal Tensor, err error) {\n\tvar newAP *AP\n\tvar ndStart, ndEnd int\n\n\tif newAP, ndStart, ndEnd, err = t.AP.S(t.len(), slices...); err != nil {\n\t\treturn\n\t}\n\n\tview := new(Dense)\n\tview.t = t.t\n\tview.viewOf = t\n\tview.AP = newAP\n\tview.hdr = new(reflect.SliceHeader)\n\tview.data = t.data\n\tview.hdr.Data = t.hdr.Data\n\tview.hdr.Len = t.hdr.Len\n\tview.hdr.Cap = t.hdr.Cap\n\tview.slice(ndStart, ndEnd)\n\n\tif t.IsMasked() {\n\t\tview.mask = t.mask[ndStart:ndEnd]\n\t}\n\treturn view, err\n}", "func NewSubstring(args ...sql.Expression) (sql.Expression, error) {\n\tvar str, start, ln sql.Expression\n\tswitch len(args) {\n\tcase 2:\n\t\tstr = args[0]\n\t\tstart = args[1]\n\t\tln = nil\n\tcase 3:\n\t\tstr = args[0]\n\t\tstart = args[1]\n\t\tln = args[2]\n\tdefault:\n\t\treturn nil, sql.ErrInvalidArgumentNumber.New(\"SUBSTRING\", \"2 or 3\", len(args))\n\t}\n\treturn &Substring{str, start, ln}, nil\n}", "func New(args ...float64) Tuple {\n\treturn args\n}", "func (s *slice) slice(start, stop int, elemsize uintptr) slice {\n\tif start >= s.cap_ || start < 0 || stop > s.cap_ || stop < 0 {\n\t\tpanic(\"cuda4/safe: slice index out of bounds\")\n\t}\n\tif start > stop {\n\t\tpanic(\"cuda4/safe: inverted slice range\")\n\t}\n\treturn slice{cu.DevicePtr(uintptr(s.ptr_) + uintptr(start)*elemsize), stop - start, s.cap_ - start}\n}", "func NewSlice(n sort.Interface) *Slice {\n\ts := &Slice{Interface: n, idx: make([]int, n.Len())}\n\tfor i := range s.idx {\n\t\ts.idx[i] = i\n\t}\n\treturn s\n}", "func (q *Query) buildSlice(sliceResult []int, t *Table, rt reflect.Type, sliceRv reflect.Value) (e error) {\n\tif len(sliceResult) < 1 {\n\t\treturn\n\t}\n\tfor _, pk := range sliceResult {\n\t\trv := reflect.New(rt)\n\t\tif pk < 1 {\n\t\t\tcontinue\n\t\t}\n\t\t_, iftValue, e := t.Get(pk)\n\t\tif e != nil {\n\t\t\treturn e\n\t\t}\n\t\tif iftValue == nil {\n\t\t\tcontinue\n\t\t}\n\t\te = q.s.saver.ToStruct(iftValue, rv.Interface())\n\t\tif e != nil {\n\t\t\treturn e\n\t\t}\n\t\tsliceRv.Elem().Set(reflect.Append(sliceRv.Elem(), rv))\n\t}\n\treturn\n}", "func sliceToETHADDR(s []byte) ETHAddr {\n\tvar e ETHAddr\n\te[0] = s[0]\n\te[1] = s[1]\n\te[2] = s[2]\n\te[3] = s[3]\n\te[4] = s[4]\n\te[5] = s[5]\n\treturn e\n}", "func CreateTuple(types ...Type) Type {\n\treturn tupleType(types)\n}", "func (p *IntVector) Slice(i, j int) *IntVector {\n\treturn &IntVector{*p.Vector.Slice(i, j)}\n}", "func execNewTuple(arity int, p *gop.Context) {\n\targs := p.GetArgs(arity)\n\tconv := func(args []interface{}) []*types.Var {\n\t\tret := make([]*types.Var, len(args))\n\t\tfor i, arg := range args {\n\t\t\tret[i] = arg.(*types.Var)\n\t\t}\n\t\treturn ret\n\t}\n\tret := types.NewTuple(conv(args[0:])...)\n\tp.Ret(arity, ret)\n}", "func (fr *frame) makeSlice(sliceType types.Type, length, capacity *govalue) *govalue {\n\tlength = fr.convert(length, types.Typ[types.Uintptr])\n\tcapacity = fr.convert(capacity, types.Typ[types.Uintptr])\n\truntimeType := fr.types.ToRuntime(sliceType)\n\tllslice := fr.runtime.makeSlice.call(fr, runtimeType, length.value, capacity.value)\n\treturn newValue(llslice[0], sliceType)\n}", "func CopySliceToTable(L *lua.State, vslice reflect.Value) int {\n if vslice.IsValid() && vslice.Type().Kind() == reflect.Slice {\n n := vslice.Len()\n L.CreateTable(n, 0)\n for i := 0; i < n; i++ {\n L.PushInteger(int64(i + 1))\n GoToLua(L, nil, vslice.Index(i))\n L.SetTable(-3)\n }\n return 1\n } else {\n L.PushNil()\n L.PushString(\"not a slice!\")\n }\n return 2\n}", "func UnpackTuple(args Tuple, kwargs StringDict, name string, min int, max int, results ...*Object) error {\n\tif len(kwargs) != 0 {\n\t\treturn ExceptionNewf(TypeError, \"%s() does not take keyword arguments\", name)\n\t}\n\n\t// Check number of arguments\n\terr := checkNumberOfArgs(name, len(args), len(results), min, max)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Copy the results in\n\tfor i := range args {\n\t\t*results[i] = args[i]\n\t}\n\treturn nil\n}", "func NewFromByteSlice(items []byte) *SliceOfByte {\n\tslicy := &SliceOfByte{items}\n\treturn slicy\n}", "func Shift(slice []interface{}) (interface{}, []interface{}) {\n\telm := slice[0]\n\tcpy := make([]interface{}, len(slice)-1)\n\tcopy(cpy, slice[1:])\n\treturn elm, cpy\n}", "func (s SampleList) Slice(start, end int) anysgd.SampleList {\n\treturn append(SampleList{}, s[start:end]...)\n}", "func NewFromInterfaceSlice(items []interface{}) *SliceOfInterface {\n\tslicy := &SliceOfInterface{items}\n\treturn slicy\n}", "func NewFromUintSlice(items []uint) *SliceOfUint {\n\tslicy := &SliceOfUint{items}\n\treturn slicy\n}", "func (v *VectorImpl) Slice(start, stop int) *VectorImplSlice {\n\tassertSliceOk(start, stop, v.Len())\n\treturn &VectorImplSlice{vector: v, start: start, stop: stop}\n}", "func NewSlice(bigSlice [][]string, title string) ([]float64, error) {\n\tfloatValues := make([]float64, len(bigSlice)-1)\n\tvar column int\n\tfor i, v := range bigSlice {\n\t\tif i == 0 {\n\t\t\tvar err error\n\t\t\tcolumn, err = stringPositionInSlice(title, v)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tvalue, _ := strconv.ParseFloat(bigSlice[i][column], 64)\n\t\tfloatValues[i-1] = value\n\t}\n\treturn floatValues, nil\n}", "func CloneValTuple(n ValTuple) ValTuple {\n\tres := make(ValTuple, 0, len(n))\n\tfor _, x := range n {\n\t\tres = append(res, CloneExpr(x))\n\t}\n\treturn res\n}", "func (vp *baseVectorParty) Slice(startRow, numRows int) common.SlicedVector {\n\tsize := vp.length - startRow\n\tif size < 0 {\n\t\tsize = 0\n\t}\n\tif size > numRows {\n\t\tsize = numRows\n\t}\n\tvector := common.SlicedVector{\n\t\tValues: make([]interface{}, size),\n\t\tCounts: make([]int, size),\n\t}\n\tfor i := 0; i < size; i++ {\n\t\tvector.Values[i] = vp.getDataValueFn(startRow + i).ConvertToHumanReadable(vp.dataType)\n\t\tvector.Counts[i] = i + 1\n\t}\n\n\treturn vector\n}", "func Slice(d Dense, start, end int) (Dense, error) {\n\tif end-start > d.len {\n\t\treturn Dense{}, fmt.Errorf(\"slicing bitmap of len %d up to %d\", d.len, end-start)\n\t}\n\tif start < 0 {\n\t\treturn Dense{}, fmt.Errorf(\"slicing bitmap with negative start: %d\", start)\n\t}\n\tif end < start {\n\t\treturn Dense{}, fmt.Errorf(\"slicing bitmap to negative length: %d\", end-start)\n\t}\n\n\tr := Dense{}\n\tfor ; start%byteSize != 0; start++ {\n\t\tr.AppendBit(d.Get(start))\n\t}\n\tj := start / byteSize\n\ttmp := NewDense(d.bits[j:j+BytesFor(end-start)], end-start)\n\tr.Append(tmp)\n\treturn r, nil\n}", "func NewFromSlice(sl []string) Set {\n\ttoReturn := New()\n\tfor _, s := range sl {\n\t\ttoReturn.Add(s)\n\t}\n\treturn toReturn\n}", "func NewSlice(a ...Name) []Name {\n\treturn a\n}", "func Slice(s Stream, start int, end int) Stream {\n return &sliceStream{Stream: s, start: start, end: end}\n}", "func NewFromUint8Slice(items []uint8) *SliceOfUint8 {\n\tslicy := &SliceOfUint8{items}\n\treturn slicy\n}", "func (t *Dense) slice(start, end int) {\n\tswitch t.t.Kind() {\n\tcase reflect.Bool:\n\t\tdata := t.bools()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Int:\n\t\tdata := t.ints()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Int8:\n\t\tdata := t.int8s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Int16:\n\t\tdata := t.int16s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Int32:\n\t\tdata := t.int32s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Int64:\n\t\tdata := t.int64s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uint:\n\t\tdata := t.uints()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uint8:\n\t\tdata := t.uint8s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uint16:\n\t\tdata := t.uint16s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uint32:\n\t\tdata := t.uint32s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uint64:\n\t\tdata := t.uint64s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uintptr:\n\t\tdata := t.uintptrs()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Float32:\n\t\tdata := t.float32s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Float64:\n\t\tdata := t.float64s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Complex64:\n\t\tdata := t.complex64s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Complex128:\n\t\tdata := t.complex128s()[start:end]\n\t\tt.fromSlice(data)\n\n\tcase reflect.String:\n\t\tdata := t.strings()[start:end]\n\t\tt.fromSlice(data)\n\n\tcase reflect.UnsafePointer:\n\t\tdata := t.unsafePointers()[start:end]\n\t\tt.fromSlice(data)\n\tdefault:\n\t\tv := reflect.ValueOf(t.v)\n\t\tv = v.Slice(start, end)\n\t\tt.fromSlice(v.Interface())\n\t}\n}", "func getPizzaSlice(a, b Coordinate) stl.Triangle {\n\treturn stl.Triangle {\n\t\tNormal: stl.Vec3{ 0,0,1 },\n\t\tVertices: [3]stl.Vec3{\n\t\t\tstl.Vec3{ 0,0,0 },\n\t\t\tstl.Vec3{ float32(a.X), float32(a.Y), 0 },\n\t\t\tstl.Vec3{ float32(b.X), float32(b.Y), 0 },\n\t\t},\n\t}\n}", "func (items Float64Slice) SubSlice(i, j int) Interface { return items[i:j] }", "func sliceTest03() {\n list := []int { 1, 0, 3, 4, 5 }\n l1 := list[0:2]\n l1[0], l1[1] = 0, 1\n fmt.Printf(\"Original: %d, %d\\nNew: %d, %d\\n\", list[0], list[1], l1[0], l1[1])\n}", "func (ns Nodes) Slice(pos ...int) Nodes {\n\tplen := len(pos)\n\tl := len(ns)\n\tif plen == 1 && pos[0] < l-1 && pos[0] > 0 {\n\t\treturn ns[pos[0]:]\n\t} else if len(pos) == 2 && pos[0] < l-1 && pos[1] < l-1 && pos[0] > 0 && pos[1] > 0 {\n\t\treturn ns[pos[0]:pos[1]]\n\t}\n\treturn Nodes{}\n}", "func Slice(slice interface{}) {\n\trv := reflect.ValueOf(slice)\n\tswap := reflect.Swapper(slice)\n\trand.Shuffle(rv.Len(), swap)\n}", "func (s *internalPointSliceView) Make(len int) ([]Point, error) {\n\tsliceHdr, allocErr := s.makeGoSlice(len)\n\tif allocErr != nil {\n\t\treturn nil, allocErr\n\t}\n\treturn *(*[]Point)(unsafe.Pointer(sliceHdr)), nil\n}", "func (t Tuple) Sub(o Tuple) Tuple {\n\tif t.IsVector() && o.IsPoint() {\n\t\tpanic(\"cannot subtract point from vector\")\n\t}\n\treturn Tuple{t.X - o.X, t.Y - o.Y, t.Z - o.Z, t.W - o.W}\n}", "func (s *internalPointBufferView) Make(len int) (PointBuffer, error) {\n\tsliceHdr, allocErr := s.state.makeSlice(len)\n\tif allocErr != nil {\n\t\treturn PointBuffer{}, allocErr\n\t}\n\treturn sliceHdr, nil\n}", "func NewFromStringSlice(items []string) *SliceOfString {\n\tslicy := &SliceOfString{items}\n\treturn slicy\n}", "func (args PyArgs) GetSlice(n uint8) ([]interface{}, error) {\n\tob := C.PyArg_ParseList((*C.PyObject)(unsafe.Pointer(args)), C.int(n))\n\tif ob == nil {\n\t\treturn nil, errTypeNotList\n\t}\n\tl := int(C.PyList_Size(ob))\n\tif l < 0 {\n\t\treturn nil, nil\n\t}\n\ts := make([]interface{}, l)\n\tfor i := 0; i < l; i++ {\n\t\titem := C.PyList_GetItem(ob, C.longlong(i))\n\t\tif item == nil {\n\t\t\tcontinue\n\t\t}\n\t\tswitch {\n\t\tcase bool(C.Py_IsUnicode(item)):\n\t\t\ts[i] = fromRawOb(item).String()\n\t\tcase bool(C.Py_IsInteger(item)):\n\t\t\ts[i] = fromRawOb(item).Int()\n\t\tcase bool(C.Py_IsDateTime(item)):\n\t\t\ts[i] = fromRawOb(item).Time()\n\t\tdefault:\n\t\t\tif ipv4Class != nil {\n\t\t\t\tif !ipv4Class.IsNull() && C.PyObject_IsInstance(item, ipv4Class.rawptr) > 0 {\n\t\t\t\t\ts[i] = net.ParseIP(fromRawOb(item).String())\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ipv6Class != nil {\n\t\t\t\tif !ipv6Class.IsNull() && C.PyObject_IsInstance(item, ipv6Class.rawptr) > 0 {\n\t\t\t\t\ts[i] = net.ParseIP(fromRawOb(item).String())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn s, nil\n}", "func NewFromUint64Slice(items []uint64) *SliceOfUint64 {\n\tslicy := &SliceOfUint64{items}\n\treturn slicy\n}", "func (ss HHMSecondary) Slice(start, end int) HHMSecondary {\n\tvar ssdssp, sadssp, sspred, ssconf, ssconsensus *seq.Sequence\n\n\tif ss.SSdssp != nil {\n\t\tt := ss.SSdssp.Slice(start, end)\n\t\tssdssp = &t\n\t}\n\tif ss.SAdssp != nil {\n\t\tt := ss.SAdssp.Slice(start, end)\n\t\tsadssp = &t\n\t}\n\tif ss.SSpred != nil {\n\t\tt := ss.SSpred.Slice(start, end)\n\t\tsspred = &t\n\t}\n\tif ss.SSconf != nil {\n\t\tt := ss.SSconf.Slice(start, end)\n\t\tssconf = &t\n\t}\n\tif ss.Consensus != nil {\n\t\tt := ss.Consensus.Slice(start, end)\n\t\tssconsensus = &t\n\t}\n\treturn HHMSecondary{\n\t\tSSdssp: ssdssp,\n\t\tSAdssp: sadssp,\n\t\tSSpred: sspred,\n\t\tSSconf: ssconf,\n\t\tConsensus: ssconsensus,\n\t}\n}", "func Slice(seq Sequence, start, end int) Sequence {\n\tseqlen := Len(seq)\n\tif start < 0 {\n\t\tstart += seqlen\n\t}\n\n\tif end < 0 {\n\t\tend += seqlen\n\t}\n\n\tif end < start {\n\t\tlength := seqlen - start + end\n\t\tseq = Rotate(seq, -start)\n\t\treturn Slice(seq, 0, length)\n\t}\n\n\tinfo := seq.Info()\n\tinfo = trySlice(info, start, end)\n\n\tff := seq.Features().Filter(Overlap(start, end))\n\n\tfor i, f := range ff {\n\t\tloc := f.Loc.Expand(end, end-seqlen).Expand(0, -start)\n\t\tif f.Key == \"source\" {\n\t\t\tloc = asComplete(loc)\n\t\t}\n\t\tff[i].Loc = loc\n\t}\n\n\tp := make([]byte, end-start)\n\tcopy(p, seq.Bytes()[start:end])\n\n\tseq = WithInfo(seq, info)\n\tseq = WithFeatures(seq, ff)\n\tseq = WithBytes(seq, p)\n\tseq = WithTopology(seq, Linear)\n\n\treturn seq\n}", "func Slice(slice interface{}) {\n\tswitch p := slice.(type) {\n\tcase []bool:\n\t\tBools(p)\n\tcase []uint8:\n\t\tUint8s(p)\n\tcase []uint16:\n\t\tUint16s(p)\n\tcase []uint32:\n\t\tUint32s(p)\n\tcase []uint64:\n\t\tUint64s(p)\n\tcase []int8:\n\t\tInt8s(p)\n\tcase []int16:\n\t\tInt16s(p)\n\tcase []int32:\n\t\tInt32s(p)\n\tcase []int64:\n\t\tInt64s(p)\n\tcase []float32:\n\t\tFloat32s(p)\n\tcase []float64:\n\t\tFloat64s(p)\n\tcase []complex64:\n\t\tComplex64s(p)\n\tcase []complex128:\n\t\tComplex128s(p)\n\tcase []uint:\n\t\tUints(p)\n\tcase []int:\n\t\tInts(p)\n\tcase []uintptr:\n\t\tUintptrs(p)\n\tcase []string:\n\t\tStrings(p)\n\tcase Interface:\n\t\tFlip(p)\n\tdefault:\n\t\trv := reflectValueOf(slice)\n\t\tswap := reflectSwapper(slice)\n\t\tFlip(reflectSlice{rv, swap})\n\t}\n}", "func New(namespace string, name string) (t TupleType) {\n\thash := syncHash.Hash([]byte(name))\n\tns_hash := syncHash.Hash([]byte(namespace))\n\tt = TupleType{namespace, name, ns_hash, hash, make([][]Field, 0), make(map[string]int)}\n\treturn\n}", "func (iobuf *buf) slice(free, base, bound uint) *Slice {\n\tatomic.AddInt32(&iobuf.refcount, 1)\n\treturn &Slice{iobuf: iobuf, free: free, base: base, Contents: iobuf.Contents[base:bound]}\n}", "func NewIntSlice(n ...int) *Slice {\n\treturn NewSlice(sort.IntSlice(n))\n}", "func (node *selfNode) packToSlice(field reflect.Value) (err error) {\n\tsliceType := field.Type().Elem()\n\tsliceKind := sliceType.Kind()\n\n\tvar value reflect.Value\n\tfor _, n := range node.values {\n\n\t\tswitch sliceKind {\n\t\tcase reflect.Slice, reflect.Array, reflect.Struct, reflect.Map:\n\t\t\tif _, ok := n.(*selfNode); !ok {\n\t\t\t\treturn n.newPackError(\"compound kind `\" + sliceKind.String() + \"` expected a list of values\")\n\t\t\t}\n\n\t\t\tsubNode := n.(*selfNode)\n\t\t\tif err = subNode.checkMetaHeader(sliceType); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tif value, err = n.makeValue(sliceType); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tfield.Set(reflect.Append(field, value))\n\t}\n\n\treturn nil\n}", "func NewFromUint32Slice(items []uint32) *SliceOfUint32 {\n\tslicy := &SliceOfUint32{items}\n\treturn slicy\n}", "func SequenceTuple(v Object) (Tuple, error) {\n\tswitch x := v.(type) {\n\tcase Tuple:\n\t\treturn x, nil\n\tcase *List:\n\t\treturn Tuple(x.Items).Copy(), nil\n\tdefault:\n\t\tt := Tuple{}\n\t\terr := Iterate(v, func(item Object) bool {\n\t\t\tt = append(t, item)\n\t\t\treturn false\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn t, nil\n\t}\n}", "func NewVector(x, y, z float64) *Tuple {\n\treturn &Tuple{x, y, z, 0.0}\n}", "func StructSliceFromByteSlice(b []byte, out interface{}) {\n\tptr := reflect.ValueOf(out)\n\tif ptr.Kind() != reflect.Ptr {\n\t\tpanic(\"expected pointer to a slice of structs (*[]X)\")\n\t}\n\tslice := ptr.Elem()\n\tif slice.Kind() != reflect.Slice {\n\t\tpanic(\"expected pointer to a slice of structs (*[]X)\")\n\t}\n\t// TODO: More checks, such as ensuring that:\n\t// - elements are NOT pointers\n\t// - structs do not contain pointers, slices or maps\n\tstride := int(slice.Type().Elem().Size())\n\tif len(b)%stride != 0 {\n\t\tpanic(\"size of byte buffer is not a multiple of struct size\")\n\t}\n\tsh := (*reflect.SliceHeader)(unsafe.Pointer(slice.UnsafeAddr()))\n\tnewRawSliceHeader(sh, b, stride)\n}", "func (slice ExerciseSlice) ToDataPointSlice(matchingReads []GlucoseRead, glucoseUnit GlucoseUnit) (dataPoints []DataPoint) {\n\tdataPoints = make([]DataPoint, len(slice))\n\tfor i := range slice {\n\t\tlocalTime, err := slice[i].Time.Format()\n\t\tif err != nil {\n\t\t\tutil.Propagate(err)\n\t\t}\n\n\t\tdataPoint := DataPoint{localTime, slice.GetEpochTime(i),\n\t\t\tlinearInterpolateY(matchingReads, slice[i].Time, glucoseUnit), float32(slice[i].DurationMinutes), EXERCISE_TAG, \"minutes\"}\n\t\tdataPoints[i] = dataPoint\n\t}\n\n\treturn dataPoints\n}", "func (r *Random) ElementFromSlice(slice interface{}) interface{} {\n\treturn r.SliceElement(slice)\n}", "func (*Base) Slice(p ASTPass, node *ast.Slice, ctx Context) {\n\tp.Visit(p, &node.Target, ctx)\n\tp.Fodder(p, &node.LeftBracketFodder, ctx)\n\tif node.BeginIndex != nil {\n\t\tp.Visit(p, &node.BeginIndex, ctx)\n\t}\n\tp.Fodder(p, &node.EndColonFodder, ctx)\n\tif node.EndIndex != nil {\n\t\tp.Visit(p, &node.EndIndex, ctx)\n\t}\n\tp.Fodder(p, &node.StepColonFodder, ctx)\n\tif node.Step != nil {\n\t\tp.Visit(p, &node.Step, ctx)\n\t}\n\tp.Fodder(p, &node.RightBracketFodder, ctx)\n}", "func MakeSlice(slicePtr interface{}) Slice {\n\tptr := reflect.ValueOf(slicePtr)\n\tif ptr.Kind() != reflect.Ptr {\n\t\tpanic(fmt.Sprintf(\"MakeSlice: argument must be pointer to slice, found %v\", ptr.Type()))\n\t}\n\tsl := ptr.Elem()\n\tif sl.Kind() != reflect.Slice {\n\t\tpanic(fmt.Sprintf(\"MakeSlice: argument must point to a slice, found %v\", sl.Type()))\n\t}\n\tintf := reflect.TypeOf((*Elem)(nil)).Elem()\n\tif !sl.Type().Elem().Implements(intf) {\n\t\tpanic(fmt.Sprintf(\"MakeSlice: element type of slice (%v) does not implement Elem\", sl.Type().Elem()))\n\t}\n\tnsl := reflect.MakeSlice(sl.Type(), sl.Len(), sl.Len())\n\treflect.Copy(nsl, sl)\n\tsl.Set(nsl)\n\treturn Slice{\n\t\tptr: ptr,\n\t\ttyp: sl.Type().Elem().Elem(),\n\t}\n}", "func FromSlice(s []interface{}) Observable {\n\treturn newObservableFromSlice(s)\n}", "func (expr *TupleLiteralExpr) Clone() *TupleLiteralExpr {\n\tif expr == nil {\n\t\treturn nil\n\t}\n\tother := *expr\n\tother.Members = cloneExprs(expr.Members)\n\treturn &other\n}", "func Slice(slicePtr interface{}, title, id, class string, min, max, step float64, valid Validator) (jquery.JQuery, error) {\n\tt, v := reflect.TypeOf(slicePtr), reflect.ValueOf(slicePtr)\n\tif t.Kind() != reflect.Ptr {\n\t\treturn jq(), fmt.Errorf(\"slicePtr should be a pointer, got %s instead\", t.Kind())\n\t}\n\tif t.Elem().Kind() != reflect.Slice {\n\t\treturn jq(), fmt.Errorf(\"slicePtr should be a pointer to slice, got pointer to %s instead\", t.Elem().Kind())\n\t}\n\tsliceType, sliceValue := t.Elem(), v.Elem()\n\tsliceElemType := sliceType.Elem()\n\n\tj := jq(\"<list>\").AddClass(ClassPrefix + \"-slice\").AddClass(class)\n\tj.SetAttr(\"title\", title).SetAttr(\"id\", id)\n\n\tvar populate func() error\n\tpopulate = func() error {\n\t\tnewLi := func(j, ji jquery.JQuery) jquery.JQuery {\n\t\t\tli := jq(\"<li>\").Append(ji)\n\t\t\tdelBtn := jq(\"<button>\").SetText(SliceDelText)\n\t\t\tdelBtn.Call(jquery.CLICK, func() {\n\t\t\t\ti := li.Call(\"index\").Get().Int()\n\t\t\t\tli.Remove()\n\t\t\t\tbegin := sliceValue.Slice(0, i)\n\t\t\t\tend := sliceValue.Slice(i+1, sliceValue.Len())\n\t\t\t\tsliceValue.Set(reflect.AppendSlice(begin, end))\n\t\t\t\t// Just delete and redo everything to work with non-pointers when the slice resizes\n\t\t\t\tj.Empty()\n\t\t\t\te := populate()\n\t\t\t\tif e != nil {\n\t\t\t\t\tpanic(e)\n\t\t\t\t}\n\t\t\t})\n\t\t\tli.Append(delBtn)\n\t\t\treturn li\n\t\t}\n\n\t\tfor i := 0; i < sliceValue.Len(); i++ {\n\t\t\telem := sliceValue.Index(i)\n\t\t\tji, e := convert(elem, \"\", \"\", \"\", \"\", min, max, step, valid)\n\t\t\tif e != nil {\n\t\t\t\treturn fmt.Errorf(\"converting slice element %d (%s): %s\", i, elem.Type().Kind(), e)\n\t\t\t}\n\t\t\tj.Append(newLi(j, ji))\n\t\t}\n\t\taddBtn := jq(\"<button>\").SetText(SliceAddText)\n\t\taddBtn.Call(jquery.CLICK, func() {\n\t\t\tif sliceElemType.Kind() == reflect.Ptr {\n\t\t\t\tnewElem := reflect.New(sliceElemType.Elem())\n\t\t\t\tsliceValue.Set(reflect.Append(sliceValue, newElem))\n\t\t\t} else {\n\t\t\t\tnewElem := reflect.New(sliceElemType)\n\t\t\t\tsliceValue.Set(reflect.Append(sliceValue, newElem.Elem()))\n\t\t\t}\n\t\t\t// Just delete and redo everything to work with non-pointers when the slice resizes\n\t\t\tj.Empty()\n\t\t\te := populate()\n\t\t\tif e != nil {\n\t\t\t\tpanic(e)\n\t\t\t}\n\t\t})\n\t\tj.Append(addBtn)\n\t\treturn nil\n\t}\n\n\te := populate()\n\tif e != nil {\n\t\treturn jq(), e\n\t}\n\n\treturn j, nil\n}", "func toValueSlice(slice reflect.Value) []reflect.Value {\n\tsliceCopy := reflect.MakeSlice(slice.Type(), slice.Len(), slice.Len())\n\treflect.Copy(sliceCopy, slice)\n\tvalues := make([]reflect.Value, sliceCopy.Len())\n\tfor i := 0; i < sliceCopy.Len(); i++ {\n\t\tvalues[i] = sliceCopy.Index(i)\n\t}\n\treturn values\n}", "func makeslice(len_ int, elemsize int) slice {\n\tbytes := int64(len_) * int64(elemsize)\n\ts := slice{0, len_, len_}\n\tif bytes > 0 {\n\t\ts.ptr_ = cu.MemAlloc(bytes)\n\t\tcu.MemsetD8(s.ptr_, 0, bytes)\n\t\tcu.CtxSynchronize()\n\t}\n\treturn s\n}", "func tcMakeSliceCopy(n *ir.MakeExpr) ir.Node {\n\t// Errors here are Fatalf instead of Errorf because only the compiler\n\t// can construct an OMAKESLICECOPY node.\n\t// Components used in OMAKESCLICECOPY that are supplied by parsed source code\n\t// have already been typechecked in OMAKE and OCOPY earlier.\n\tt := n.Type()\n\n\tif t == nil {\n\t\tbase.Fatalf(\"no type specified for OMAKESLICECOPY\")\n\t}\n\n\tif !t.IsSlice() {\n\t\tbase.Fatalf(\"invalid type %v for OMAKESLICECOPY\", n.Type())\n\t}\n\n\tif n.Len == nil {\n\t\tbase.Fatalf(\"missing len argument for OMAKESLICECOPY\")\n\t}\n\n\tif n.Cap == nil {\n\t\tbase.Fatalf(\"missing slice argument to copy for OMAKESLICECOPY\")\n\t}\n\n\tn.Len = Expr(n.Len)\n\tn.Cap = Expr(n.Cap)\n\n\tn.Len = DefaultLit(n.Len, types.Types[types.TINT])\n\n\tif !n.Len.Type().IsInteger() && n.Type().Kind() != types.TIDEAL {\n\t\tbase.Errorf(\"non-integer len argument in OMAKESLICECOPY\")\n\t}\n\n\tif ir.IsConst(n.Len, constant.Int) {\n\t\tif ir.ConstOverflow(n.Len.Val(), types.Types[types.TINT]) {\n\t\t\tbase.Fatalf(\"len for OMAKESLICECOPY too large\")\n\t\t}\n\t\tif constant.Sign(n.Len.Val()) < 0 {\n\t\t\tbase.Fatalf(\"len for OMAKESLICECOPY must be non-negative\")\n\t\t}\n\t}\n\treturn n\n}", "func NewSliceIter(slice interface{}) SliceIter {\n\treturn SliceIter{slice}\n}", "func NewAttributeValueSlice(len int) []AttributeValue {\n\t// Allocate 2 slices, one for AttributeValues, another for underlying OTLP structs.\n\t// TODO: make one allocation for both slices.\n\torigs := make([]otlpcommon.AttributeKeyValue, len)\n\twrappers := make([]AttributeValue, len)\n\tfor i := range origs {\n\t\twrappers[i].orig = &origs[i]\n\t}\n\treturn wrappers\n}", "func (t *TupleType) Builder(buffer []byte) TupleBuilder {\n\treturn NewBuilder(*t, buffer)\n}", "func makeSlice(offset dvid.Point3d, size dvid.Point2d) []byte {\n\tnumBytes := size[0] * size[1] * 8\n\tslice := make([]byte, numBytes, numBytes)\n\ti := 0\n\tmodz := offset[2] % int32(len(zdata))\n\tfor y := int32(0); y < size[1]; y++ {\n\t\tsy := y + offset[1]\n\t\tmody := sy % int32(len(ydata))\n\t\tsx := offset[0]\n\t\tfor x := int32(0); x < size[0]; x++ {\n\t\t\tmodx := sx % int32(len(xdata))\n\t\t\tbinary.BigEndian.PutUint64(slice[i:i+8], xdata[modx]+ydata[mody]+zdata[modz])\n\t\t\ti += 8\n\t\t\tsx++\n\t\t}\n\t}\n\treturn slice\n}", "func (b *Blob) Slice(start, end int, contenttype string) *Blob {\n\tnewBlobObject := b.Call(\"slice\", start, end, contenttype)\n\treturn &Blob{\n\t\tObject: newBlobObject,\n\t}\n}", "func Slice2Interface(slice []string) (uniqueslice []interface{}) {\n\tfor _, v := range slice {\n\t\tuniqueslice = append(uniqueslice, v)\n\t}\n\treturn\n}", "func Retind(inslice []float64, elems []float64) []int {\n\tif len(inslice) < 1 || len(elems) != 2 {\n\t\terr := errors.New(\"Array of more than one element is required for inslice while a tuple is required for elems.\")\n\t\tpanic(err)\n\t}\n\tvar inind []int\n\tfor i, v := range inslice {\n\t\tif v == elems[0] || v == elems[1] {\n\t\t\tinind = append(inind, i)\n\t\t}\n\t}\n\tif inind[1] > inind[0] {\n\t\tinind[0], inind[1] = inind[1], inind[0]\n\t}\n\treturn inind\n}", "func newObservableFromSlice(s []interface{}) Observable {\n\treturn &observable{\n\t\tobservableType: cold,\n\t\titerable: newIterableFromSlice(s),\n\t}\n}", "func remapTuple(tuple val.Tuple, desc val.TupleDesc, mapping val.OrdinalMapping) [][]byte {\n\tresult := make([][]byte, len(mapping))\n\tfor to, from := range mapping {\n\t\tif from == -1 {\n\t\t\tcontinue\n\t\t}\n\t\tresult[to] = desc.GetField(from, tuple)\n\t}\n\n\treturn result\n}", "func NewVector(slice interface{}) *Tensor {\n\tv := reflect.ValueOf(slice)\n\tlength := v.Len()\n\tdtype := SliceTypeToDtype[reflect.TypeOf(slice)]\n\tbytelen := length * int(DtypeSize[dtype])\n\tif v.Len() != length {\n\t\treturn nil\n\t}\n\tsliceHeader := reflect.SliceHeader{\n\t\tData: uintptr(unsafe.Pointer(v.Pointer())),\n\t\tCap: int(bytelen),\n\t\tLen: int(bytelen),\n\t}\n\treturn &Tensor{\n\t\tBuffer: *(*[]byte)(unsafe.Pointer(&sliceHeader)),\n\t\tDims: []int64{int64(length)},\n\t\tDtype: dtype,\n\t}\n}", "func grow(s reflect.Value, extra int) (reflect.Value, int, int) {\n\ti0 := s.Len()\n\ti1 := i0 + extra\n\tif i1 < i0 {\n\t\tpanic(\"reflect.Append: slice overflow\")\n\t}\n\tm := s.Cap()\n\tif i1 <= m {\n\t\treturn s.Slice(0, i1), i0, i1\n\t}\n\tif m == 0 {\n\t\tm = extra\n\t} else {\n\t\tfor m < i1 {\n\t\t\tif i0 < 1024 {\n\t\t\t\tm += m\n\t\t\t} else {\n\t\t\t\tm += m / 4\n\t\t\t}\n\t\t}\n\t}\n\tt := reflect.MakeSlice(s.Type(), i1, m)\n\treflect.Copy(t, s)\n\treturn t, i0, i1\n}", "func (s *internalPointSliceView) MakeWithCapacity(length int, capacity int) ([]Point, error) {\n\tif capacity < length {\n\t\treturn nil, arena.AllocationInvalidArgumentError\n\t}\n\tsliceHdr, allocErr := s.makeGoSlice(capacity)\n\tif allocErr != nil {\n\t\treturn nil, allocErr\n\t}\n\tsliceHdr.Len = length\n\treturn *(*[]Point)(unsafe.Pointer(sliceHdr)), nil\n}", "func (s *f64) Slice(start, end int) Floating {\n\tstart = s.BufferIndex(0, start)\n\tend = s.BufferIndex(0, end)\n\treturn &f64{\n\t\tchannels: s.channels,\n\t\tbuffer: s.buffer[start:end],\n\t}\n}", "func NewPair[T1, T2 any](first T1, second T2) Pair[T1, T2] {\n\treturn Pair[T1, T2]{First: first, Second: second}\n}", "func (p *SliceOfMap) Slice(indices ...int) ISlice {\n\tif p == nil || len(*p) == 0 {\n\t\treturn NewSliceOfMapV()\n\t}\n\n\t// Handle index manipulation\n\ti, j, err := absIndices(len(*p), indices...)\n\tif err != nil {\n\t\treturn NewSliceOfMapV()\n\t}\n\n\tslice := SliceOfMap((*p)[i:j])\n\treturn &slice\n}", "func NewSliceIterator(rowIDs, columnIDs []uint64) *SliceIterator {\n\tif len(columnIDs) != len(rowIDs) {\n\t\tpanic(fmt.Sprintf(\"pilosa.SliceIterator: pair length mismatch: %d != %d\", len(rowIDs), len(columnIDs)))\n\t}\n\n\treturn &SliceIterator{\n\t\trowIDs: rowIDs,\n\t\tcolumnIDs: columnIDs,\n\n\t\tn: len(rowIDs),\n\t}\n}", "func IntSlice(k string, v []int) KeyValue {\n\treturn Key(k).IntSlice(v)\n}", "func (p *SliceOfMap) Take(indices ...int) (new ISlice) {\n\tnew = p.Copy(indices...)\n\tp.Drop(indices...)\n\treturn\n}", "func (t *StringSlice) Slice(start int, length int) []string {\n\tvar ret []string\n\tif start >= 0 && start+length <= len(t.items) && start+length >= 0 {\n\t\tret = t.items[start : start+length]\n\t}\n\treturn ret\n}", "func (req *UpsertRequest) Tuple(tuple Tuple) *UpsertRequest {\n\treq.tuple = tuple\n\treturn req\n}", "func NewByteSlice(b []byte) ByteSlice {\n\tif b == nil {\n\t\treturn NullByteSlice()\n\t}\n\treturn ByteSlice{\n\t\tByteSlice: append([]byte{}, b...),\n\t\tValid: true,\n\t}\n}" ]
[ "0.67775756", "0.59362", "0.5725369", "0.5587828", "0.545664", "0.5448951", "0.5422909", "0.5401333", "0.5379334", "0.52723455", "0.525213", "0.5218558", "0.5152185", "0.51271045", "0.5120096", "0.51112926", "0.5099456", "0.5089693", "0.5085051", "0.5079558", "0.5077202", "0.50635874", "0.50585437", "0.50408393", "0.5028071", "0.5026956", "0.5021889", "0.49864158", "0.49863538", "0.49861708", "0.49829698", "0.49791828", "0.49741605", "0.49695623", "0.4961742", "0.49498463", "0.4944921", "0.49443212", "0.49247625", "0.49081504", "0.4907522", "0.48886707", "0.48885638", "0.48752862", "0.48427036", "0.47849095", "0.47819933", "0.47815338", "0.47699443", "0.4763798", "0.47625935", "0.4761481", "0.4760103", "0.47402164", "0.4722738", "0.47191608", "0.46968248", "0.46918106", "0.468978", "0.46854082", "0.46846008", "0.46824062", "0.46774277", "0.46750227", "0.46585095", "0.46357343", "0.46287417", "0.4628539", "0.4628423", "0.4621213", "0.4620973", "0.46198994", "0.46148828", "0.46082905", "0.46008983", "0.45993128", "0.45969704", "0.45963314", "0.4593812", "0.45912713", "0.45871875", "0.45850146", "0.45759463", "0.45738107", "0.4571089", "0.45648882", "0.45644358", "0.4553104", "0.45449975", "0.45431972", "0.45375544", "0.45314494", "0.45245302", "0.4509447", "0.44978753", "0.44930053", "0.44924453", "0.44917375", "0.44896415", "0.44876227" ]
0.762169
0
Creates a new tuple from a literal sequence of items
func NewTupleFromItems(items ...interface{}) *Tuple { t := NewTuple(len(items)) for i, item := range items { t.Set(i, item) } return t }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func SequenceTuple(v Object) (Tuple, error) {\n\tswitch x := v.(type) {\n\tcase Tuple:\n\t\treturn x, nil\n\tcase *List:\n\t\treturn Tuple(x.Items).Copy(), nil\n\tdefault:\n\t\tt := Tuple{}\n\t\terr := Iterate(v, func(item Object) bool {\n\t\t\tt = append(t, item)\n\t\t\treturn false\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn t, nil\n\t}\n}", "func MakeTuple(v []interface{}) (skylark.Tuple, error) {\n\tvals := make([]skylark.Value, len(v))\n\tfor i := range v {\n\t\tval, err := ToValue(v[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvals[i] = val\n\t}\n\treturn skylark.Tuple(vals), nil\n}", "func NewTupleFromSlice(slice []interface{}) *Tuple {\n\tt := &Tuple{}\n\tt.data = slice\n\treturn t\n}", "func execNewTuple(arity int, p *gop.Context) {\n\targs := p.GetArgs(arity)\n\tconv := func(args []interface{}) []*types.Var {\n\t\tret := make([]*types.Var, len(args))\n\t\tfor i, arg := range args {\n\t\t\tret[i] = arg.(*types.Var)\n\t\t}\n\t\treturn ret\n\t}\n\tret := types.NewTuple(conv(args[0:])...)\n\tp.Ret(arity, ret)\n}", "func Tuple(argv []TermT) TermT {\n\tcount := C.uint32_t(len(argv))\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\tif count == 0 {\n\t\treturn NullTerm\n\t}\n\treturn TermT(C.yices_tuple(count, (*C.term_t)(&argv[0])))\n}", "func CreateTuple(types ...Type) Type {\n\treturn tupleType(types)\n}", "func TupleType3(tau1 TypeT, tau2 TypeT, tau3 TypeT) TypeT {\n\tcarr := []C.type_t{C.type_t(tau1), C.type_t(tau2), C.type_t(tau3)}\n\treturn TypeT(C.yices_tuple_type(C.uint32_t(3), (*C.type_t)(&carr[0])))\n}", "func CloneTuple(t Tuple) Tuple {\n\tnewTuple := make(Tuple, len(t))\n\tfor i := range t {\n\t\tv := reflect.New(reflect.TypeOf(t[i]).Elem())\n\t\tv.Elem().Set(reflect.ValueOf(t[i]).Elem())\n\t\tnewTuple[i] = v.Interface()\n\t}\n\treturn newTuple\n}", "func NewTuple(n int) *Tuple {\n\tt := &Tuple{}\n\tt.data = make([]interface{}, n)\n\treturn t\n}", "func New(args ...float64) Tuple {\n\treturn args\n}", "func New(strs ...string) Sequence {\n\ts := Sequence{\n\t\tstr: strings.Join(strs, \" \"),\n\t\tlimit: 0,\n\t\tmode: DefaultMode,\n\t\tclipboard: SystemClipboard,\n\t\top: SetOperation,\n\t}\n\treturn s\n}", "func CloneValTuple(n ValTuple) ValTuple {\n\tres := make(ValTuple, 0, len(n))\n\tfor _, x := range n {\n\t\tres = append(res, CloneExpr(x))\n\t}\n\treturn res\n}", "func (this *Tuple) AppendItems(items ...interface{}) {\n\tthis.data = append(this.data, items...)\n}", "func (this *Tuple) InsertItems(start int, items ...interface{}) {\n\tstart = this.Offset(start)\n\trhs := this.Copy().data[start:]\n\tthis.data = append(this.data[:start], items...)\n\tthis.data = append(this.data, rhs...)\n}", "func (s *BaseSyslParserListener) EnterInplace_tuple(ctx *Inplace_tupleContext) {}", "func (item Item) GetTuple(name string) sugar.Tuple {\n\ttuple := sugar.Tuple{}\n\n\tswitch item[name].(type) {\n\tcase map[string]interface{}:\n\t\tfor k, _ := range item[name].(map[string]interface{}) {\n\t\t\ttuple[k] = item[name].(map[string]interface{})[k]\n\t\t}\n\tcase sugar.Tuple:\n\t\ttuple = item[name].(sugar.Tuple)\n\t}\n\n\treturn tuple\n}", "func TupleType(tau []TypeT) TypeT {\n\ttauLen := len(tau)\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\tif tauLen == 0 {\n\t\treturn NullType\n\t}\n\treturn TypeT(C.yices_tuple_type(C.uint32_t(tauLen), (*C.type_t)(&tau[0])))\n}", "func (req *UpsertRequest) Tuple(tuple Tuple) *UpsertRequest {\n\treq.tuple = tuple\n\treturn req\n}", "func Vector(x, y, z float64) Tuple {\n\treturn Tuple{x, y, z, 0}\n}", "func TupleUpdate(tuple TermT, index uint32, value TermT) TermT {\n\treturn TermT(C.yices_tuple_update(C.term_t(tuple), C.uint32_t(index), C.term_t(value)))\n}", "func prepareList(stringreps []string) []*Item {\n\tvar list []*Item\n\n\tfor _, str := range stringreps {\n\t\tn, err := strconv.Atoi(str)\n\t\tvar item *Item\n\t\tif err == nil {\n\t\t\titem = &Item{Typ: Number, Value: n}\n\t\t} else {\n\t\t\titem = &Item{Typ: Operation, Operation: str}\n\t\t}\n\t\tlist = append(list, item)\n\t}\n\n\treturn list\n}", "func DefineTuple(types []*IHType) *HTuple {\n\treturn &HTuple{types: types}\n}", "func VariadicTupleType(types []interface{}) dgo.TupleType {\n\tn := len(types)\n\tif n == 0 {\n\t\tpanic(errors.New(`a variadic tuple must have at least one element`))\n\t}\n\treturn newTupleType(types, true)\n}", "func versionTuple(ver string) starlark.Tuple {\n\tvar major, minor, rev int\n\t_, err := fmt.Sscanf(ver, \"%d.%d.%d\", &major, &minor, &rev)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn starlark.Tuple{\n\t\tstarlark.MakeInt(major),\n\t\tstarlark.MakeInt(minor),\n\t\tstarlark.MakeInt(rev),\n\t}\n}", "func UnpackTuple(args Tuple, kwargs StringDict, name string, min int, max int, results ...*Object) error {\n\tif len(kwargs) != 0 {\n\t\treturn ExceptionNewf(TypeError, \"%s() does not take keyword arguments\", name)\n\t}\n\n\t// Check number of arguments\n\terr := checkNumberOfArgs(name, len(args), len(results), min, max)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Copy the results in\n\tfor i := range args {\n\t\t*results[i] = args[i]\n\t}\n\treturn nil\n}", "func TupleType1(tau1 TypeT) TypeT {\n\tcarr := []C.type_t{C.type_t(tau1)}\n\treturn TypeT(C.yices_tuple_type(C.uint32_t(1), (*C.type_t)(&carr[0])))\n}", "func Tuples(a []int, fn func([]int)) {\n\tp := make([]int, 2)\n\tfor i := 0; i < len(a); i++ {\n\t\tfor j := i + 1; j < len(a); j++ {\n\t\t\tp[0], p[1] = a[i], a[j]\n\t\t\tfn(p)\n\t\t}\n\t}\n}", "func PyTuple_New(len int) *PyObject {\n\treturn c2go(C.__PyTuple_New(C.Py_ssize_t(len)))\n}", "func Vector(x, y, z float64) *Tuple {\n\treturn &Tuple{x, y, z, 0.0}\n}", "func Swapitems(intuple []float64) []float64 {\n\tif len(intuple) != 2 {\n\t\terr := errors.New(\"Tuple (slice of length 2) is required for swapping.\")\n\t\tpanic(err)\n\t}\n\tintuple[0], intuple[1] = intuple[1], intuple[0]\n\treturn intuple\n}", "func TupleQueryArgs(argCount int) (query string) {\n\tif argCount == 0 {\n\t\treturn\n\t}\n\tquery = strings.Repeat(\"?,\", argCount)\n\tquery = query[0 : len(query)-1]\n\treturn \"(\" + query + \")\"\n}", "func (t Tuple3[A, B, C]) Unpack() (A, B, C) {\n\treturn t.A, t.B, t.C\n}", "func TupleType(types []interface{}) dgo.TupleType {\n\treturn newTupleType(types, false)\n}", "func newLeafListString(values []string) *TypedLeafListString {\n\tfirst := true\n\tbytes := make([]byte, 0)\n\tfor _, v := range values {\n\t\tif first {\n\t\t\tfirst = false\n\t\t} else {\n\t\t\tbytes = append(bytes, 0x1D) // Group separator\n\t\t}\n\t\tbytes = append(bytes, []byte(v)...)\n\t}\n\ttypedLeafListString := TypedLeafListString{\n\t\tBytes: bytes,\n\t\tType: ValueType_LEAFLIST_STRING,\n\t}\n\treturn &typedLeafListString\n}", "func Unpack(b []byte) (Tuple, error) {\n\tvar t Tuple\n\n\tvar i int\n\n\tfor i < len(b) {\n\t\tvar el interface{}\n\t\tvar off int\n\n\t\tswitch {\n\t\tcase b[i] == 0x00:\n\t\t\tel = nil\n\t\t\toff = 1\n\t\tcase b[i] == 0x01:\n\t\t\tel, off = decodeBytes(b[i:])\n\t\tcase b[i] == 0x02:\n\t\t\tel, off = decodeString(b[i:])\n\t\tcase 0x0c <= b[i] && b[i] <= 0x1c:\n\t\t\tel, off = decodeInt(b[i:])\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unable to decode tuple element with unknown typecode %02x\", b[i])\n\t\t}\n\n\t\tt = append(t, el)\n\t\ti += off\n\t}\n\n\treturn t, nil\n}", "func NewVector(x, y, z float64) *Tuple {\n\treturn &Tuple{x, y, z, 0.0}\n}", "func Item(typ lex.ItemType, val string) lex.Item {\n\treturn lex.Item{\n\t\tType: typ,\n\t\tValue: val,\n\t}\n}", "func SelectFeatures(tuples []base.Tuple, features []int) []base.Tuple {\n if (len(features) <= 0) {\n return tuples;\n }\n\n var tupleType reflect.Type = reflect.TypeOf(tuples[0]);\n\n var rtn []base.Tuple = make([]base.Tuple, len(tuples));\n for tupleIndex, tuple := range(tuples) {\n var data []interface{} = make([]interface{}, len(features));\n for featurePosition, featureIndex := range(features) {\n data[featurePosition] = tuple.GetData(featureIndex);\n }\n\n rtn[tupleIndex] = base.NewTypedTuple(tupleType, data, tuple.GetClass());\n }\n\n return rtn;\n}", "func get_three_things() (string, string, string) {\n return \"thing 1\", \"thing 2\", \"thing 3\"\n}", "func NewSequence(gid int, elements ...Element) *Sequence {\n\treturn &Sequence{\n\t\telement: element{gid},\n\t\telements: elements,\n\t}\n}", "func createLALRSet(items ...lalrItem) (set *lalrSet) {\n\tset = new(lalrSet)\n\tset.items = make(map[uint32][]lalrItem)\n\tset.gotos = make(map[Token]*lalrSet)\n\n\tfor _, item := range(items) {\n\t\tset.addItem(item)\n\t}\n\n\treturn\n}", "func Pair(children ...Element) *CompoundElement { return newCE(\"Pair\", children) }", "func From[T any](x T) Seq[T] { return element[T]{x} }", "func ValExpandTuple(model ModelT, yval *YvalT, child []YvalT) int32 {\n\treturn int32(C.yices_val_expand_tuple(ymodel(model), (*C.yval_t)(yval), (*C.yval_t)(&child[0])))\n}", "func newPair(key, value []byte) *item {\n\treturn &item{key: key, value: value}\n}", "func (s *BaseSyslParserListener) ExitInplace_tuple(ctx *Inplace_tupleContext) {}", "func NewFiveTuple(data []byte) *FiveTuple {\n\treturn &FiveTuple{data: data}\n}", "func PyTuple_SetItem(o *PyObject, pos int, item *PyObject) error {\n\tif rc := int(C.__PyTuple_SetItem(go2c(o), C.Py_ssize_t(pos), go2c(item))); rc != 0 {\n\t\treturn fmt.Errorf(\"cpython: error to set item to PyTuple, pos: %v\", pos)\n\t}\n\treturn nil\n}", "func Of(i interface{}) Item {\n\treturn Item{V: i}\n}", "func (t Tuple9[A, B, C, D, E, F, G, H, I]) Unpack() (A, B, C, D, E, F, G, H, I) {\n\treturn t.A, t.B, t.C, t.D, t.E, t.F, t.G, t.H, t.I\n}", "func MakeVector(first LangType, rest ...LangType) Vector {\n\tvec := make(Vector, 1+len(rest))\n\n\tvec[0] = first\n\n\tfor i, item := range rest {\n\t\tvec[i+1] = item\n\t}\n\n\treturn vec\n}", "func (sym *symtab) buildTuple(tuple *types.Tuple, varnm string, methvar string) (string, error) {\n\tsz := tuple.Len()\n\tif sz == 0 {\n\t\treturn \"\", fmt.Errorf(\"buildTuple: no elements\")\n\t}\n\t// TODO: https://www.reddit.com/r/Python/comments/3618cd/calling_back_python_instance_methods_from_c/\n\t// could not get this to work across threads for methods -- and furthermore the basic version with\n\t// CallObject works fine within the same thread, so all this extra work seems unnecessary.\n\t//\n\t// bstr := fmt.Sprintf(\"var %s *C.PyObject\\n\", varnm)\n\t// bstr += fmt.Sprintf(\"_pyargstidx := 0\\n\")\n\t// bstr += fmt.Sprintf(\"_pyargidx := C.long(0)\\n\")\n\t// if methvar != \"\" {\n\t// \tbstr += fmt.Sprintf(\"if C.gopy_method_check(%s) != 0 {\\n\", methvar)\n\t// \tbstr += fmt.Sprintf(\"\\tC.gopy_incref(%s)\\n\", methvar)\n\t// \tbstr += fmt.Sprintf(\"\\t%s = C.PyTuple_New(%d)\\n\", varnm, sz+1)\n\t// \tbstr += fmt.Sprintf(\"\\tC.PyTuple_SetItem(%s, 0, C.PyMethod_Self(%s))\\n\", varnm, methvar)\n\t// \tbstr += fmt.Sprintf(\"\\t_pyargstidx = 1\\n\")\n\t// \tbstr += fmt.Sprintf(\"\\t%[1]s = C.PyMethod_Function(%[1]s)\\n\", methvar)\n\t// \tbstr += fmt.Sprintf(\"} else {\\n\")\n\t// \tbstr += fmt.Sprintf(\"\\t%s = C.PyTuple_New(%d)\\n\", varnm, sz)\n\t// \tbstr += fmt.Sprintf(\"}\\n\")\n\t// }\n\n\t// TODO: more efficient to use strings.Builder here..\n\tbstr := fmt.Sprintf(\"%s := C.PyTuple_New(%d)\\n\", varnm, sz)\n\tfor i := 0; i < sz; i++ {\n\t\tv := tuple.At(i)\n\t\ttyp := v.Type()\n\t\tanm := pySafeArg(v.Name(), i)\n\t\tvsym := sym.symtype(typ)\n\t\tif vsym == nil {\n\t\t\terr := sym.addType(v, typ)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tvsym = sym.symtype(typ)\n\t\t\tif vsym == nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"buildTuple: type still not found: %s\", typ.String())\n\t\t\t}\n\t\t}\n\t\t// bstr += fmt.Sprintf(\"_pyargidx = C.long(_pyargstidx + %d)\\n\", i)\n\n\t\tbt, isb := typ.Underlying().(*types.Basic)\n\t\tswitch {\n\t\tcase vsym.goname == \"interface{}\":\n\t\t\tbstr += fmt.Sprintf(\"C.PyTuple_SetItem(%s, %d, C.gopy_build_string(%s(%s)%s))\\n\", varnm, i, vsym.go2py, anm, vsym.go2pyParenEx)\n\t\tcase vsym.hasHandle(): // note: assuming int64 handles\n\t\t\tbstr += fmt.Sprintf(\"C.PyTuple_SetItem(%s, %d, C.gopy_build_int64(C.int64_t(%s(%s)%s)))\\n\", varnm, i, vsym.go2py, anm, vsym.go2pyParenEx)\n\t\tcase isb:\n\t\t\tbk := bt.Kind()\n\t\t\tswitch {\n\t\t\tcase types.Int <= bk && bk <= types.Int64:\n\t\t\t\tbstr += fmt.Sprintf(\"C.PyTuple_SetItem(%s, %d, C.gopy_build_int64(C.int64_t(%s)))\\n\", varnm, i, anm)\n\t\t\tcase types.Uint <= bk && bk <= types.Uintptr:\n\t\t\t\tbstr += fmt.Sprintf(\"C.PyTuple_SetItem(%s, %d, C.gopy_build_uint64(C.uint64_t(%s)))\\n\", varnm, i, anm)\n\t\t\tcase types.Float32 <= bk && bk <= types.Float64:\n\t\t\t\tbstr += fmt.Sprintf(\"C.PyTuple_SetItem(%s, %d, C.gopy_build_float64(C.double(%s)))\\n\", varnm, i, anm)\n\t\t\tcase bk == types.String:\n\t\t\t\tbstr += fmt.Sprintf(\"C.PyTuple_SetItem(%s, %d, C.gopy_build_string(C.CString(%s)))\\n\", varnm, i, anm)\n\t\t\tcase bk == types.Bool:\n\t\t\t\tbstr += fmt.Sprintf(\"C.PyTuple_SetItem(%s, %d, C.gopy_build_bool(C.uint8_t(boolGoToPy(%s))))\\n\", varnm, i, anm)\n\t\t\t}\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"buildTuple: type not handled: %s\", typ.String())\n\t\t}\n\t}\n\treturn bstr, nil\n}", "func (ts Uint64Uint64Tuples) Append3(k1 uint64, v1 uint64, k2 uint64, v2 uint64, k3 uint64, v3 uint64) Uint64Uint64Tuples {\n\treturn append(ts, Uint64Uint64Tuple{k1, v1}, Uint64Uint64Tuple{k2, v2}, Uint64Uint64Tuple{k3, v3})\n}", "func (s *BaseSyslParserListener) EnterEmpty_tuple(ctx *Empty_tupleContext) {}", "func ListItemType(value string) *SimpleElement { return newSEString(\"listItemType\", value) }", "func (bbox *Bbox) AsTuple() []float64 {\r\n\treturn []float64{bbox.LonMin, bbox.LatMin, bbox.LonMax, bbox.LatMax}\r\n}", "func NewPairFromStrings(baseCurrency, quoteCurrency string) Pair {\n\treturn Pair{\n\t\tBase: NewCode(baseCurrency),\n\t\tQuote: NewCode(quoteCurrency),\n\t}\n}", "func newTestSequenceCursor3(items [][][]int) *sequenceCursor {\n\ttop := &sequenceCursor{nil, items, 0, len(items), func(item sequenceItem, idx int) sequenceItem {\n\t\treturn item.([][][]int)[idx] // item should be == items\n\t}, func(item sequenceItem) (sequenceItem, int) {\n\t\tpanic(\"not reachable\")\n\t}}\n\n\tmiddle := &sequenceCursor{top, items[0], 0, len(items[0]), func(item sequenceItem, idx int) sequenceItem {\n\t\treturn item.([][]int)[idx]\n\t}, func(item sequenceItem) (sequenceItem, int) {\n\t\treturn item, len(item.([][]int))\n\t}}\n\n\treturn &sequenceCursor{middle, items[0][0], 0, len(items[0][0]), func(item sequenceItem, idx int) sequenceItem {\n\t\treturn item.([]int)[idx]\n\t}, func(item sequenceItem) (sequenceItem, int) {\n\t\treturn item, len(item.([]int))\n\t}}\n}", "func blListInit(obj *BlTypeObject, args ...BlObject) BlObject {\n var arg BlObject\n if blParseArguments(\"|o\", args, &arg) == -1 {\n return nil\n }\n lobj := NewBlList(0)\n if arg == nil {\n return lobj\n }\n typeobj := arg.BlType()\n if seq := typeobj.Sequence; seq != nil {\n if seq.SqItem == nil || seq.SqSize == nil {\n goto err\n }\n for i := 0; i < seq.SqSize(arg); i++ {\n lobj.Append(seq.SqItem(arg, i))\n }\n return lobj\n }\nerr:\n errpkg.SetErrmsg(\"'%s' object is not iterable\",\n typeobj.Name)\n return nil\n}", "func New(namespace string, name string) (t TupleType) {\n\thash := syncHash.Hash([]byte(name))\n\tns_hash := syncHash.Hash([]byte(namespace))\n\tt = TupleType{namespace, name, ns_hash, hash, make([][]Field, 0), make(map[string]int)}\n\treturn\n}", "func (e *ObservableEditableBuffer) RuneTuple(q int) OffsetTuple {\n\treturn e.f.RuneTuple(q)\n}", "func StringFromItems(name string, id [2]byte, sequence [2]byte, persist byte, value []byte) *String {\n\tvalLen, sizeLen := util.ReadULeb128(bytes.NewReader(value))\n\tval := string(value[sizeLen : valLen-1])\n\tpersistant := (persist == flagPersist)\n\treturn &String{\n\t\ttrueValue: val,\n\t\tisPersistant: persistant,\n\t\tBase: Base{\n\t\t\teName: name,\n\t\t\teType: typeString,\n\t\t\teID: id,\n\t\t\teSeq: sequence,\n\t\t\teFlag: persist,\n\t\t\teValue: value,\n\t\t},\n\t}\n}", "func Multiply(t Tuplelike, n float64) Tuplelike {\n\tresult := []float64{}\n\n\tfor _, value := range t.Values() {\n\t\tresult = append(result, value*n)\n\t}\n\n\treturn Tuple(result)\n}", "func add[Type IntOrString](items []Type) (result Type) {\n\tfor _, item := range items {\n\t\tresult = result + item\n\t}\n\treturn\n}", "func Make(e1, e2 interface{}) (p Pair) {\n\tp[0] = e1\n\tp[1] = e2\n\n\treturn p\n}", "func NewRelationExpr(names []string, tuples ...[]Expr) (Expr, error) {\n\telements := make([]Expr, len(tuples))\n\tfor i, tuple := range tuples {\n\t\tif len(tuple) != len(names) {\n\t\t\treturn nil, errors.Errorf(\n\t\t\t\t\"heading-tuple mismatch: %v vs %v\", names, tuple)\n\t\t}\n\t\tattrs := make([]AttrExpr, len(names))\n\t\tfor i, name := range names {\n\t\t\tattrs[i] = AttrExpr{name, tuple[i]}\n\t\t}\n\t\telements[i] = NewTupleExpr(attrs...)\n\t}\n\treturn NewSetExpr(elements...), nil\n}", "func fieldliterals(fields ...string) []Field {\n\tfs := make([]Field, len(fields))\n\tfor i := range fields {\n\t\tfs[i] = FieldLiteral(fields[i])\n\t}\n\treturn fs\n}", "func Item(key, value *Term) [2]*Term {\n\treturn [2]*Term{key, value}\n}", "func PyTuple_GetItem(o *PyObject, pos int) *PyObject {\n\treturn c2go(C.__PyTuple_GetItem(go2c(o), C.Py_ssize_t(pos)))\n}", "func NewLIFO(ts ...T) *LIFO {\n\ts := &LIFO{}\n\tfor i := range ts {\n\t\ts.Push(ts[i])\n\t}\n\treturn s\n}", "func (s *Statement) Lit(v interface{}) *Statement {\n\tt := token{\n\t\ttyp: literalToken,\n\t\tcontent: v,\n\t}\n\t*s = append(*s, t)\n\treturn s\n}", "func New(initial ...string) Set {\n\ts := make(Set)\n\n\tfor _, v := range initial {\n\t\ts.Insert(v)\n\t}\n\n\treturn s\n}", "func (i StringHashMap[T, V]) Items() []struct {\n\tKey T\n\tVal V\n} {\n\tresult := make([]struct {\n\t\tKey T\n\t\tVal V\n\t}, 0, len(i.hashToKey))\n\tfor hash, key := range i.hashToKey {\n\t\tval := i.hashToVal[hash]\n\t\tresult = append(result, struct {\n\t\t\tKey T\n\t\t\tVal V\n\t\t}{key, val})\n\t}\n\treturn result\n}", "func (p *PlainTextBuilder) CreateItems(items []string) {\n\t// ˅\n\tfor _, item := range items {\n\t\tp.buffer.WriteString(\" - \" + item + \"\\n\") // Item\n\t}\n\tp.buffer.WriteString(\"\\n\") // Blank line\n\t// ˄\n}", "func FromTKs(tks []commonStorage.TypeAndKey) []*EntityID {\n\tids := []*EntityID{}\n\tfor _, tk := range tks {\n\t\tids = append(ids, &EntityID{Type: tk.Type, Id: tk.Key})\n\t}\n\treturn ids\n}", "func (t Tuple6[A, B, C, D, E, F]) Unpack() (A, B, C, D, E, F) {\n\treturn t.A, t.B, t.C, t.D, t.E, t.F\n}", "func itemFactory(path proto.Path, v interface{}) (validationItem, error) {\n\t// We need to special case for no-type fields in yaml (e.g. empty item in list)\n\tif v == nil {\n\t\treturn nil, InvalidObjectTypeError{Type: \"nil\", Path: path.String()}\n\t}\n\tkind := reflect.TypeOf(v).Kind()\n\tswitch kind {\n\tcase reflect.Bool:\n\t\treturn &primitiveItem{\n\t\t\tbaseItem: baseItem{path: path},\n\t\t\tValue: v,\n\t\t\tKind: proto.Boolean,\n\t\t}, nil\n\tcase reflect.Int,\n\t\treflect.Int8,\n\t\treflect.Int16,\n\t\treflect.Int32,\n\t\treflect.Int64,\n\t\treflect.Uint,\n\t\treflect.Uint8,\n\t\treflect.Uint16,\n\t\treflect.Uint32,\n\t\treflect.Uint64:\n\t\treturn &primitiveItem{\n\t\t\tbaseItem: baseItem{path: path},\n\t\t\tValue: v,\n\t\t\tKind: proto.Integer,\n\t\t}, nil\n\tcase reflect.Float32,\n\t\treflect.Float64:\n\t\treturn &primitiveItem{\n\t\t\tbaseItem: baseItem{path: path},\n\t\t\tValue: v,\n\t\t\tKind: proto.Number,\n\t\t}, nil\n\tcase reflect.String:\n\t\treturn &primitiveItem{\n\t\t\tbaseItem: baseItem{path: path},\n\t\t\tValue: v,\n\t\t\tKind: proto.String,\n\t\t}, nil\n\tcase reflect.Array,\n\t\treflect.Slice:\n\t\treturn &arrayItem{\n\t\t\tbaseItem: baseItem{path: path},\n\t\t\tArray: v.([]interface{}),\n\t\t}, nil\n\tcase reflect.Map:\n\t\treturn &mapItem{\n\t\t\tbaseItem: baseItem{path: path},\n\t\t\tMap: v.(map[string]interface{}),\n\t\t}, nil\n\t}\n\treturn nil, InvalidObjectTypeError{Type: kind.String(), Path: path.String()}\n}", "func CloneColTuple(in ColTuple) ColTuple {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tswitch in := in.(type) {\n\tcase ListArg:\n\t\treturn CloneListArg(in)\n\tcase *Subquery:\n\t\treturn CloneRefOfSubquery(in)\n\tcase ValTuple:\n\t\treturn CloneValTuple(in)\n\tdefault:\n\t\t// this should never happen\n\t\treturn nil\n\t}\n}", "func convertPtrToStr(items []*string) []string {\n\tvar sl []string\n\tfor _, n := range items {\n\t\tsl = append(sl, *n)\n\t}\n\treturn sl\n}", "func quotedItems(items ...interface{}) []string {\n\tstrItems := stringSlice(items...)\n\tquoted := []string{}\n\tfor _, str := range strItems {\n\t\tif str[0:1] != \"\\\"\" {\n\t\t\tstr = \"\\\"\" + str + \"\\\"\"\n\t\t}\n\t\tquoted = append(quoted, str)\n\t}\n\treturn quoted\n}", "func NewLogItem(b []byte) *LogItem {\n\tspace := []byte(\" \")\n\tvar l LogItem\n\n\tcols := bytes.Split(b[:len(b)-1], space)\n\tl.Timestamp = string(cols[0])\n\tl.Bytes = bytes.Join(cols[1:], space)\n\n\treturn &l\n}", "func (s *SliceOfString) Unshift(item string) *SliceOfString {\n\ts.items = append([]string{item}, s.items...)\n\treturn s\n}", "func Item(items ...string) string {\n\tvar bytes = make([]byte, 1)\n\t_, err := rand.Read(bytes)\n\tif err != nil {\n\t\t// TODO(v5): Return this error instead?\n\t\tpanic(fmt.Errorf(\"while reading random bytes: %w\", err))\n\t}\n\n\treturn items[bytes[0]%byte(len(items))]\n}", "func remapTuple(tuple val.Tuple, desc val.TupleDesc, mapping val.OrdinalMapping) [][]byte {\n\tresult := make([][]byte, len(mapping))\n\tfor to, from := range mapping {\n\t\tif from == -1 {\n\t\t\tcontinue\n\t\t}\n\t\tresult[to] = desc.GetField(from, tuple)\n\t}\n\n\treturn result\n}", "func New(value ...interface{}) Stack {\n\ts := Stack{}\n\tfor _, e := range value {\n\t\ts.Push(e)\n\t}\n\treturn s\n}", "func execmTupleAt(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := args[0].(*types.Tuple).At(args[1].(int))\n\tp.Ret(2, ret)\n}", "func LinearRing(children ...Element) *CompoundElement { return newCE(\"LinearRing\", children) }", "func (t Tuple2[A, B]) Unpack() (A, B) {\n\treturn t.A, t.B\n}", "func _SplitStatementItems(db *sql.DB, udn_schema map[string]interface{}, source_array []string) []string {\n\t//UdnLog(udn_schema, \"\\nSplit: Items: %v\\n\\n\", source_array)\n\n\t// Split Open Compound\n\tsplit_result := _SplitStringArray(source_array, \".\")\n\n\treturn split_result\n}", "func (t Tuple7[A, B, C, D, E, F, G]) Unpack() (A, B, C, D, E, F, G) {\n\treturn t.A, t.B, t.C, t.D, t.E, t.F, t.G\n}", "func Seq(x interface{}, args ...interface{}) Node {\n\treturn Node{&ast.Set{\n\t\tStartOp: \"[\",\n\t\tEndOp: \"]\",\n\t\tX: ToNode(x).Node,\n\t\tY: ArgsList(args...).Node,\n\t}}\n}", "func New(items ...uint32) *Set {\n\ts := &Set{items: make(map[uint32]struct{}, len(items))}\n\ts.Add(items...)\n\treturn s\n}", "func createItem(name string) Item {\n\tnewItem := Item{}\n\tnewItem.Id = createXid()\n\tnewItem.Name = name\n\titems = append(items, newItem)\n\treturn newItem\n}", "func (t Tuple5[A, B, C, D, E]) Unpack() (A, B, C, D, E) {\n\treturn t.A, t.B, t.C, t.D, t.E\n}", "func decodeTuple(a *DatumAlloc, tupTyp *types.T, b []byte) (tree.Datum, []byte, error) {\n\tb, _, _, err := encoding.DecodeNonsortingUvarint(b)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresult := tree.DTuple{\n\t\tD: a.NewDatums(len(tupTyp.TupleContents())),\n\t}\n\n\tvar datum tree.Datum\n\tfor i := range tupTyp.TupleContents() {\n\t\tdatum, b, err = DecodeTableValue(a, tupTyp.TupleContents()[i], b)\n\t\tif err != nil {\n\t\t\treturn nil, b, err\n\t\t}\n\t\tresult.D[i] = datum\n\t}\n\treturn a.NewDTuple(result), b, nil\n}", "func (a Args) from(i int) Args {\n\tif i >= len(a.All) {\n\t\ti = len(a.All) - 1\n\t}\n\ta.All = a.All[i+1:]\n\n\tif i >= len(a.Completed) {\n\t\ti = len(a.Completed) - 1\n\t}\n\ta.Completed = a.Completed[i+1:]\n\treturn a\n}", "func encodeTuple(t *tree.DTuple, appendTo []byte, colID uint32, scratch []byte) ([]byte, error) {\n\tappendTo = encoding.EncodeValueTag(appendTo, colID, encoding.Tuple)\n\tappendTo = encoding.EncodeNonsortingUvarint(appendTo, uint64(len(t.D)))\n\n\tvar err error\n\tfor _, dd := range t.D {\n\t\tappendTo, err = EncodeTableValue(appendTo, descpb.ColumnID(encoding.NoColumnID), dd, scratch)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn appendTo, nil\n}", "func (t Tuple) Pack() []byte {\n\tbuf := new(bytes.Buffer)\n\n\tfor i, e := range t {\n\t\tswitch e := e.(type) {\n\t\tcase nil:\n\t\t\tbuf.WriteByte(0x00)\n\t\tcase int64:\n\t\t\tencodeInt(buf, e)\n\t\tcase uint32:\n\t\t\tencodeInt(buf, int64(e))\n\t\tcase uint64:\n\t\t\tencodeInt(buf, int64(e))\n\t\tcase int:\n\t\t\tencodeInt(buf, int64(e))\n\t\tcase byte:\n\t\t\tencodeInt(buf, int64(e))\n\t\tcase []byte:\n\t\t\tencodeBytes(buf, 0x01, e)\n\t\tcase lex.KeyConvertible:\n\t\t\tencodeBytes(buf, 0x01, []byte(e.LexKey()))\n\t\tcase string:\n\t\t\tencodeBytes(buf, 0x02, []byte(e))\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"unencodable element at index %d (%v, type %T)\", i, t[i], t[i]))\n\t\t}\n\t}\n\n\treturn buf.Bytes()\n}", "func (e *ObservableEditableBuffer) ByteTuple(q int) OffsetTuple {\n\treturn e.f.ByteTuple(q)\n}", "func (executor *ExecutorImpl) projection(tlist []*parser.TargetEntry,\n\ttlistDesc *access.TupleDesc) access.Tuple {\n\tvalues := make([]string, len(tlist))\n\tfor i, tle := range tlist {\n\t\tvalues[i] = executor.ExecExpr(tle.Expr).ToString()\n\t}\n\n\treturn access.Tuple(&access.CSVTuple{\n\t\tTupleDesc: tlistDesc,\n\t\tValues: values,\n\t})\n}" ]
[ "0.6122976", "0.587197", "0.5459759", "0.5458699", "0.54445183", "0.52178156", "0.5008375", "0.49721578", "0.49097043", "0.4898114", "0.48744923", "0.4856354", "0.48446503", "0.4836814", "0.4760752", "0.4740713", "0.4699276", "0.46946263", "0.46731538", "0.46618026", "0.46540937", "0.46425328", "0.46379137", "0.4628374", "0.46262285", "0.4614362", "0.4577438", "0.4576753", "0.45620686", "0.45515797", "0.45400402", "0.45373842", "0.4497317", "0.44686767", "0.44503143", "0.4448532", "0.44378597", "0.44289982", "0.4394015", "0.43780005", "0.4365263", "0.4348443", "0.43341258", "0.43075964", "0.4279064", "0.4267111", "0.42636055", "0.42635223", "0.4257656", "0.42540148", "0.4249299", "0.4248976", "0.42447743", "0.42422733", "0.42396256", "0.42343646", "0.42326283", "0.42171523", "0.4211181", "0.41915575", "0.418803", "0.41812947", "0.4178417", "0.41732538", "0.41447067", "0.41309574", "0.41271424", "0.41207927", "0.41148812", "0.41143513", "0.41132224", "0.41093537", "0.40988803", "0.40816453", "0.40767214", "0.40658632", "0.40654445", "0.4065418", "0.4063983", "0.4062737", "0.4057988", "0.40528607", "0.40492147", "0.4046027", "0.40406126", "0.4038518", "0.4029831", "0.40293112", "0.4024483", "0.40227485", "0.4016761", "0.40085173", "0.40069336", "0.4002269", "0.40008563", "0.39959672", "0.39935395", "0.39916176", "0.39786", "0.3966891" ]
0.7194172
0
Returns a new tuple with a copy of this tuple's data
func (this *Tuple) Copy() *Tuple { t := NewTuple(this.Len()) copy(t.data, this.data) return t }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CloneTuple(t Tuple) Tuple {\n\tnewTuple := make(Tuple, len(t))\n\tfor i := range t {\n\t\tv := reflect.New(reflect.TypeOf(t[i]).Elem())\n\t\tv.Elem().Set(reflect.ValueOf(t[i]).Elem())\n\t\tnewTuple[i] = v.Interface()\n\t}\n\treturn newTuple\n}", "func (expr *TupleLiteralExpr) Clone() *TupleLiteralExpr {\n\tif expr == nil {\n\t\treturn nil\n\t}\n\tother := *expr\n\tother.Members = cloneExprs(expr.Members)\n\treturn &other\n}", "func CloneValTuple(n ValTuple) ValTuple {\n\tres := make(ValTuple, 0, len(n))\n\tfor _, x := range n {\n\t\tres = append(res, CloneExpr(x))\n\t}\n\treturn res\n}", "func (this *Tuple) Append(other *Tuple) {\n\tthis.AppendItems(other.data...)\n}", "func CloneColTuple(in ColTuple) ColTuple {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tswitch in := in.(type) {\n\tcase ListArg:\n\t\treturn CloneListArg(in)\n\tcase *Subquery:\n\t\treturn CloneRefOfSubquery(in)\n\tcase ValTuple:\n\t\treturn CloneValTuple(in)\n\tdefault:\n\t\t// this should never happen\n\t\treturn nil\n\t}\n}", "func (t Topology) Copy() Topology {\n\treturn Topology{\n\t\tNodes: t.Nodes.Copy(),\n\t}\n}", "func (original *Place) Copy() *Place {\n\treturn &Place{original.latitude, original.longitude, original.Name}\n}", "func (t *Type) Copy() *Type", "func (pk PacketBuffer) Clone() PacketBuffer {\n\tpk.Data = pk.Data.Clone(nil)\n\treturn pk\n}", "func (d data) copyWith(newVal string) data {\n\td.val = newVal\n\treturn d\n}", "func (this *Tuple) Data() []interface{} {\n\treturn this.data\n}", "func (t *Tuple) Sub(o *Tuple) *Tuple {\n\treturn &Tuple{\n\t\tt.x - o.x,\n\t\tt.y - o.y,\n\t\tt.z - o.z,\n\t\tt.w - o.w,\n\t}\n\n}", "func (v Data) Clone() Data {\n\tnv := make(Data, len(v))\n\tcopy(nv, v)\n\n\treturn nv\n}", "func (t *Tuple) Add(o *Tuple) *Tuple {\n\treturn &Tuple{\n\t\tt.x + o.x,\n\t\tt.y + o.y,\n\t\tt.z + o.z,\n\t\tt.w + o.w,\n\t}\n}", "func (tdw *TokenDataWitness) Clone() *TokenDataWitness {\n\treturn &TokenDataWitness{\n\t\tType: tdw.Type,\n\t\tValue: tdw.Value.Copy(),\n\t\tBlindingFactor: tdw.BlindingFactor.Copy(),\n\t}\n}", "func (ctx *Ciphertext) CopyNew() BfvElement {\n\n\tctxCopy := new(Ciphertext)\n\n\tctxCopy.value = make([]*ring.Poly, ctx.Degree()+1)\n\tfor i := range ctx.value {\n\t\tctxCopy.value[i] = ctx.value[i].CopyNew()\n\t}\n\tctxCopy.bfvcontext = ctx.bfvcontext\n\tctxCopy.isNTT = ctx.isNTT\n\n\treturn ctxCopy\n}", "func cloneTask(t *Task) *Task {\n c := *t\n return &c\n}", "func (rb *RingBuffer) Clone() *RingBuffer {\n\trb.lock.RLock()\n\tdefer rb.lock.RUnlock()\n\tcp := make([]stats.Record, len(rb.data))\n\tcopy(cp, rb.data)\n\treturn &RingBuffer{seq: rb.seq, data: cp}\n}", "func (p *Point) Copy() Point {\n\treturn Point{\n\t\tX: p.X,\n\t\tY: p.Y,\n\t}\n}", "func (a *Assignment) Clone() *Assignment {\n\tif a == nil {\n\t\treturn nil\n\t}\n\tother := *a\n\tother.Columns = cloneIdents(a.Columns)\n\tother.Expr = CloneExpr(a.Expr)\n\treturn &other\n}", "func (t *Transaction) Clone() *Transaction {\n\tclone := *t\n\tclone.res = t.res.Clone()\n\treturn &clone\n}", "func (t Token) Copy() PropValue {\n\treturn t\n}", "func (req *UpsertRequest) Tuple(tuple Tuple) *UpsertRequest {\n\treq.tuple = tuple\n\treturn req\n}", "func (t Tuple2[A, B]) Unpack() (A, B) {\n\treturn t.A, t.B\n}", "func (ctx context) clone() context {\n\treturn context{\n\t\tkeyvals: safeSlice(ctx.keyvals),\n\t}\n}", "func NewTuple(n int) *Tuple {\n\tt := &Tuple{}\n\tt.data = make([]interface{}, n)\n\treturn t\n}", "func (t *Dense) Clone() interface{} {\n\tretVal := recycledDense(t.t, t.Shape().Clone())\n\tReturnAP(retVal.AP)\n\tretVal.AP = t.AP.Clone()\n\n\tif t.old != nil {\n\t\tretVal.old = t.old.Clone()\n\t}\n\n\tcopyDense(retVal, t)\n\tretVal.lock()\n\treturn retVal\n}", "func (geom Geometry) Clone() Geometry {\n\tnewGeom := C.OGR_G_Clone(geom.cval)\n\treturn Geometry{newGeom}\n}", "func (ms *MySlice) Clone() Data {\n\tscopy := make([]int, len(ms.Slice))\n\tcopy(scopy, ms.Slice)\n\tmyslice := new(MySlice)\n\tmyslice.Slice = scopy\n\treturn Data(myslice)\n}", "func (d UserData) Copy() m.UserData {\n\treturn &UserData{\n\t\td.ModelData.Copy(),\n\t}\n}", "func (this *Tuple) Set(n int, item interface{}) {\n\tthis.data[this.Offset(n)] = item\n}", "func (mr MutRow) Clone() MutRow {\n\tnewChk := mr.c\n\tif mr.c != nil {\n\t\tnewChk = mr.c.CopyConstruct()\n\t}\n\treturn MutRow{\n\t\tc: newChk,\n\t\tidx: mr.idx,\n\t}\n}", "func NewTupleFromSlice(slice []interface{}) *Tuple {\n\tt := &Tuple{}\n\tt.data = slice\n\treturn t\n}", "func (d *DataPacket) copy() DataPacket {\n\tcopySlice := make([]byte, len(d.data))\n\tcopy(copySlice, d.data)\n\treturn DataPacket{\n\t\tdata: copySlice,\n\t\tlength: d.length,\n\t}\n}", "func (self Mset) Copy () interface{} {\n\th := self.h.Copy()\n\treturn Mset{&h, self.size}\n}", "func (n Node) Copy() Node {\n\tcp := MakeNode()\n\tcp.Metadata = n.Metadata.Copy()\n\tcp.Counters = n.Counters.Copy()\n\tcp.Adjacency = n.Adjacency.Copy()\n\tcp.Edges = n.Edges.Copy()\n\treturn cp\n}", "func (f *Feature) Clone() *Feature {\n\treturn NewFeature(f.chr, f.element, f.location)\n}", "func (t *Tuple) Reflect(normal *Tuple) *Tuple {\n\treturn t.Sub(normal.Mul(2).Mul(t.Dot(normal)))\n}", "func (c *UsingConstraint) Clone() *UsingConstraint {\n\tif c == nil {\n\t\treturn nil\n\t}\n\tother := *c\n\tother.Columns = cloneIdents(c.Columns)\n\treturn &other\n}", "func (ts Tokens) Clone() Tokens {\n\tv := make([]Token, len(ts))\n\tcopy(v, ts)\n\treturn v\n}", "func (this *Tuple) Slice(start int, end int) *Tuple {\n\tc := this.Copy()\n\tmax := this.Len()\n\tstart = min(c.Offset(start), max)\n\tend = min(c.Offset(end), max)\n\tc.data = c.data[start:end]\n\treturn c\n}", "func (stmt *statement) Clone() Statement {\n\tnewstmt := getStmt(stmt.dialect)\n\tnewstmt.parts = append(newstmt.parts, stmt.parts...)\n\n\tnewstmt.args = insertAt(newstmt.args, stmt.args, 0)\n\tnewstmt.dest = insertAt(newstmt.dest, stmt.dest, 0)\n\tnewstmt.buffer.Write(stmt.buffer.B)\n\tif stmt.sql != nil {\n\t\tnewstmt.sql = getBuffer()\n\t\tnewstmt.sql.Write(stmt.sql.B)\n\t}\n\n\treturn newstmt\n}", "func (t *Changeset) Clone() *Changeset {\n\ttt := *t\n\ttt.CampaignIDs = t.CampaignIDs[:len(t.CampaignIDs):len(t.CampaignIDs)]\n\treturn &tt\n}", "func (v Value) Clone() *Value {\n\treturn newValue(v.native, v.negative, v.num, v.offset)\n}", "func (packet *ReliablePacket) Copy() *ReliablePacket {\n\tnewPacket := new(ReliablePacket)\n\tnewPacket.Reliability = packet.Reliability\n\tnewPacket.HasSplitPacket = packet.HasSplitPacket\n\tnewPacket.OrderingChannel = packet.OrderingChannel\n\tnewPacket.OrderingIndex = packet.OrderingIndex\n\tnewPacket.ReliableMessageNumber = packet.ReliableMessageNumber\n\tnewPacket.SequencingIndex = packet.SequencingIndex\n\tnewPacket.SplitPacketCount = packet.SplitPacketCount\n\tnewPacket.SplitPacketID = packet.SplitPacketID\n\tnewPacket.SplitPacketIndex = packet.SplitPacketIndex\n\tnewPacket.SplitBuffer = packet.SplitBuffer\n\n\treturn newPacket\n}", "func (d Decimal) Copy() Decimal {\n\td.ensureInitialized()\n\treturn Decimal{\n\t\tvalue: &(*d.value),\n\t\texp: d.exp,\n\t}\n}", "func (g *altsTC) Clone() credentials.TransportCredentials {\n\treturn &altsTC{\n\t\tinfo: g.info,\n\t\tside: g.side,\n\t}\n}", "func (d *dataUsageCache) clone() dataUsageCache {\n\tclone := dataUsageCache{\n\t\tInfo: d.Info,\n\t\tCache: make(map[string]dataUsageEntry, len(d.Cache)),\n\t}\n\tfor k, v := range d.Cache {\n\t\tclone.Cache[k] = v\n\t}\n\treturn clone\n}", "func (t *Today) CopyWithEncodedData() *Today {\n\tcp := t.Copy()\n\t// https://github.com/go101/go101/wiki/How-to-perfectly-clone-a-slice\n\tcp.AsJson = append(t.AsJson[:0:0], t.AsJson...)\n\tcp.AsYourOwn1 = append(t.AsYourOwn1[:0:0], t.AsYourOwn1...)\n\treturn cp\n}", "func (t Tuple3[A, B, C]) Unpack() (A, B, C) {\n\treturn t.A, t.B, t.C\n}", "func (c Cell) Copy() Cell {\n\tvar newCell Cell\n\n\tnewCell.SetAlive(c.Alive())\n\n\treturn newCell\n}", "func (lit *NullLit) Clone() *NullLit {\n\tif lit == nil {\n\t\treturn nil\n\t}\n\tother := *lit\n\treturn &other\n}", "func copyTeam(team storage.Team) storage.Team {\n\tcopyTeam := storage.Team{\n\t\tID: team.ID,\n\t\tName: team.Name,\n\t\tProjects: team.Projects,\n\t}\n\treturn copyTeam\n}", "func (lit *DateLit) Clone() *DateLit {\n\tif lit == nil {\n\t\treturn nil\n\t}\n\tother := *lit\n\treturn &other\n}", "func (c *UniqueConstraint) Clone() *UniqueConstraint {\n\tif c == nil {\n\t\treturn c\n\t}\n\tother := *c\n\tother.Name = c.Name.Clone()\n\tother.Columns = cloneIdents(c.Columns)\n\treturn &other\n}", "func (st *State) clone() *State {\n\ts := *st\n\ts.Balance = nil\n\ts.Balance = new(big.Int).Set(st.Balance)\n\ts.VotingWeight = nil\n\ts.VotingWeight = new(big.Int).Set(st.VotingWeight)\n\tif st.CodeHash != nil {\n\t\ts.CodeHash = nil\n\t\ts.CodeHash = make([]byte, len(st.CodeHash))\n\t\tcopy(s.CodeHash, st.CodeHash)\n\t}\n\t// Voters won't be used, set to nil for simplicity\n\ts.Voters = nil\n\treturn &s\n}", "func (w *Wrapper) Copy() *Wrapper {\n\treturn w.cloning(true)\n}", "func (t Header) Clone() Header {\n\tt.Key = append([]KeyField{}, t.Key...)\n\tt.Data = append([]Field{}, t.Data...)\n\treturn t\n}", "func (v *Values) Clone() *Values {\n\tv.lock.RLock()\n\tdefer v.lock.RUnlock()\n\n\treturn newValues(v.root)\n}", "func (tri *Triangle) Clone() *Triangle {\n\tnewTri := NewTriangle(tri.Mesh)\n\tfor _, vertex := range tri.Vertices {\n\t\tnewTri.SetVertices(vertex.Clone())\n\t}\n\tnewTri.RecalculateCenter()\n\treturn newTri\n}", "func (lit *StringLit) Clone() *StringLit {\n\tif lit == nil {\n\t\treturn nil\n\t}\n\tother := *lit\n\treturn &other\n}", "func (entry *UtxoEntry) Clone() *UtxoEntry {\n\tif entry == nil {\n\t\treturn nil\n\t}\n\n\tnewEntry := &UtxoEntry{\n\t\tamount: entry.amount,\n\t\tpkScript: entry.pkScript,\n\t\tticketMinOuts: entry.ticketMinOuts,\n\t\tblockHeight: entry.blockHeight,\n\t\tblockIndex: entry.blockIndex,\n\t\tscriptVersion: entry.scriptVersion,\n\t\tstate: entry.state,\n\t\tpackedFlags: entry.packedFlags,\n\t}\n\n\treturn newEntry\n}", "func (s *CreateViewStatement) Clone() *CreateViewStatement {\n\tif s == nil {\n\t\treturn nil\n\t}\n\tother := *s\n\tother.Name = s.Name.Clone()\n\t// other.Columns = cloneIdents(s.Columns)\n\tother.Select = s.Select.Clone()\n\treturn &other\n}", "func (a *Attributes) Clone() *Attributes {\n\treturn NewAttributesFrom(a)\n}", "func (lit *FloatLit) Clone() *FloatLit {\n\tif lit == nil {\n\t\treturn nil\n\t}\n\tother := *lit\n\treturn &other\n}", "func (i *Item) Copy() Item {\n\treturn Item{\n\t\ti.value,\n\t\tnil, nil,\n\t}\n}", "func (n *Node) copy() *Node {\n\tcopy := *n\n\tif n.Orig == n {\n\t\tcopy.Orig = &copy\n\t}\n\treturn &copy\n}", "func (cur *sequenceCursor) clone() *sequenceCursor {\n\tvar parent *sequenceCursor\n\tif cur.parent != nil {\n\t\tparent = cur.parent.clone()\n\t}\n\tcl := newSequenceCursor(parent, cur.seq, cur.idx)\n\treturn cl\n}", "func Copy(seq Sequence) BasicSequence {\n\treturn New(seq.Info(), seq.Features(), seq.Bytes())\n}", "func (ft *FieldType) Clone() *FieldType {\n\tret := *ft\n\treturn &ret\n}", "func (v Vector) clone() Vector {\n\tclone := v\n\tclone.data = make(map[int]float64)\n\tfor n, d := range v.data {\n\t\tclone.data[n] = d\n\t}\n\n\treturn clone\n}", "func (t Tuple9[A, B, C, D, E, F, G, H, I]) Unpack() (A, B, C, D, E, F, G, H, I) {\n\treturn t.A, t.B, t.C, t.D, t.E, t.F, t.G, t.H, t.I\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 (bv Values) Clone() Values {\n\tif n := len(bv); n > 0 {\n\t\tvalues := make(Values, n)\n\t\tcopy(values, bv)\n\t\treturn values\n\t}\n\n\treturn NewValues()\n}", "func (t *TupleType) Builder(buffer []byte) TupleBuilder {\n\treturn NewBuilder(*t, buffer)\n}", "func (lm *LevelMetadata) clone() LevelMetadata {\n\treturn LevelMetadata{\n\t\tlevel: lm.level,\n\t\ttree: lm.tree.Clone(),\n\t}\n}", "func New(namespace string, name string) (t TupleType) {\n\thash := syncHash.Hash([]byte(name))\n\tns_hash := syncHash.Hash([]byte(namespace))\n\tt = TupleType{namespace, name, ns_hash, hash, make([][]Field, 0), make(map[string]int)}\n\treturn\n}", "func (g LabeledAdjacencyList) Copy() (c LabeledAdjacencyList, ma int) {\n\tc = make(LabeledAdjacencyList, len(g))\n\tfor n, to := range g {\n\t\tc[n] = append([]Half{}, to...)\n\t\tma += len(to)\n\t}\n\treturn\n}", "func (this *Tuple) Reverse() {\n\tfor i, j := 0, this.Len()-1; i < j; i, j = i+1, j-1 {\n\t\tthis.data[i], this.data[j] = this.data[j], this.data[i]\n\t}\n}", "func (pos *Position) Copy() *Position {\n\treturn &Position{\n\t\tLine: pos.Line,\n\t\tColumn: pos.Column,\n\t\tfile: pos.file,\n\t}\n}", "func (a *Graph) copy() *Graph {\n\tthis := &Graph{}\n\tthis.n = a.n\n\tthis.e = a.e\n\tthis.edge = make([]int, this.n*this.n)\n\tfor i, v := range a.edge {\n\t\tthis.edge[i] = v\n\t}\n\treturn this\n}", "func (c *Call) Clone() *Call {\n\tif c == nil {\n\t\treturn nil\n\t}\n\tother := *c\n\tother.Name = c.Name.Clone()\n\tother.Args = cloneExprs(c.Args)\n\tother.Filter = c.Filter.Clone()\n\tother.Over = c.Over.Clone()\n\treturn &other\n}", "func (t *Type) Clone() *Type {\n\tif t == nil {\n\t\treturn nil\n\t}\n\tother := *t\n\tother.Name = t.Name.Clone()\n\tother.Precision = t.Precision.Clone()\n\tother.Scale = t.Scale.Clone()\n\treturn &other\n}", "func (r *Record) Copy() *Record {\n\tdataCopy := make(M, len(r.Data))\n\tfor k, v := range r.Data {\n\t\tdataCopy[k] = v\n\t}\n\n\tfieldsCopy := make(M, len(r.Fields))\n\tfor k, v := range r.Fields {\n\t\tfieldsCopy[k] = v\n\t}\n\n\textraCopy := make(M, len(r.Extra))\n\tfor k, v := range r.Extra {\n\t\textraCopy[k] = v\n\t}\n\n\treturn &Record{\n\t\tlogger: r.logger,\n\t\tChannel: r.Channel,\n\t\tTime: r.Time,\n\t\tLevel: r.Level,\n\t\tlevelName: r.levelName,\n\t\tMessage: r.Message,\n\t\tData: dataCopy,\n\t\tExtra: extraCopy,\n\t\tFields: fieldsCopy,\n\t}\n}", "func (t *TransactionPayload) Copy() *TransactionPayload {\n\tpayload := make([]byte, len(t.Data))\n\tcopy(payload, t.Data)\n\n\treturn &TransactionPayload{\n\t\tData: payload,\n\t}\n}", "func (blk *Block) duplicate() *Block {\n\tdup := &Block{}\n\n\t// Copy over.\n\t*dup = *blk\n\n\tdupContents := contentstream.ContentStreamOperations{}\n\tfor _, op := range *blk.contents {\n\t\tdupContents = append(dupContents, op)\n\t}\n\tdup.contents = &dupContents\n\n\treturn dup\n}", "func (r *View) Clone() *View {\n\treturn r.CloneLimit(r.size)\n}", "func (obj VECTOR_TYPE) Clone() VECTOR_TYPE {\n r := NIL_VECTOR(obj.n)\n for i, v := range obj.values {\n r.values[i] = v.Clone()\n }\n r.vectorSparseIndex = obj.indexClone()\n return r\n}", "func (item *splitItem) Clone() *splitItem {\n\treturn &splitItem{\n\t\tmetaType: item.metaType,\n\t\titemType: item.itemType,\n\t\titemID: item.itemID,\n\t\tdirection: item.direction,\n\t\toffset: item.offset,\n\t\tbit: item.bit,\n\t\tkey: item.key,\n\t\tvalue: item.value,\n\t}\n}", "func (c *CheckConstraint) Clone() *CheckConstraint {\n\tif c == nil {\n\t\treturn c\n\t}\n\tother := *c\n\tother.Name = c.Name.Clone()\n\tother.Expr = CloneExpr(c.Expr)\n\treturn &other\n}", "func (p *Point) Clone() *Point {\n\treturn &Point{p.X, p.Y}\n}", "func (c *Compound) Copy() Modifiable {\n\tnewC := new(Compound)\n\tnewC.LayeredPoint = c.LayeredPoint.Copy()\n\tnewSubRenderables := make(map[string]Modifiable)\n\tc.lock.RLock()\n\tfor k, v := range c.subRenderables {\n\t\tnewSubRenderables[k] = v.Copy()\n\t}\n\tc.lock.RUnlock()\n\tnewC.subRenderables = newSubRenderables\n\tnewC.curRenderable = c.curRenderable\n\tnewC.lock = sync.RWMutex{}\n\treturn newC\n}", "func (op RollupOp) Clone() RollupOp {\n\tidClone := make([]byte, len(op.ID))\n\tcopy(idClone, op.ID)\n\treturn RollupOp{ID: idClone, AggregationID: op.AggregationID}\n}", "func (t Tuple8[A, B, C, D, E, F, G, H]) Unpack() (A, B, C, D, E, F, G, H) {\n\treturn t.A, t.B, t.C, t.D, t.E, t.F, t.G, t.H\n}", "func (gene *Gene) Copy() *Gene {\n\treturn &Gene{\n\t\tgene.A,\n\t\tgene.B,\n\t\tgene.C,\n\t\tgene.F,\n\t\tgene.Format,\n\t}\n}", "func (e *ObservableEditableBuffer) ByteTuple(q int) OffsetTuple {\n\treturn e.f.ByteTuple(q)\n}", "func (s Sequence) Clone() Sequence {\n\tv := Sequence{s.Title, make([]Token, len(s.Tokens))}\n\tcopy(v.Tokens, s.Tokens)\n\treturn v\n}", "func (md Metadata) Copy() Metadata {\n\treturn New(md)\n}", "func (vertex *Vertex) Clone() *Vertex {\n\tnewVert := NewVertex(vertex.Position[0], vertex.Position[1], vertex.Position[2], vertex.UV[0], vertex.UV[1])\n\tnewVert.Color = vertex.Color.Clone()\n\treturn newVert\n}", "func Dup(d DataType) DataType {\n\treturn newDupper().DupType(d)\n}" ]
[ "0.67432994", "0.60998666", "0.58188397", "0.56445384", "0.5599843", "0.5591076", "0.5422837", "0.5415148", "0.5377441", "0.5333629", "0.53312135", "0.5314242", "0.5120695", "0.51174414", "0.5106553", "0.50935715", "0.5092923", "0.5070351", "0.5063902", "0.5044667", "0.5036437", "0.5030728", "0.5015646", "0.50060785", "0.49839005", "0.49747512", "0.49535033", "0.49429554", "0.49276018", "0.49096018", "0.49028832", "0.4897156", "0.4887234", "0.48862648", "0.48776308", "0.4876199", "0.48672846", "0.4855672", "0.48382443", "0.4833685", "0.48336402", "0.48250437", "0.4819482", "0.4815451", "0.4815118", "0.4811076", "0.48083872", "0.48040423", "0.4790577", "0.47904024", "0.47850734", "0.47819698", "0.4780458", "0.4778105", "0.47721604", "0.47623473", "0.47615728", "0.47575456", "0.47505897", "0.4739793", "0.47351906", "0.47322577", "0.47293532", "0.4726348", "0.47235644", "0.4722989", "0.47093907", "0.47073293", "0.4705684", "0.47038415", "0.469978", "0.4693462", "0.46926644", "0.4692364", "0.46901736", "0.46864173", "0.46847254", "0.46825457", "0.46807024", "0.46781152", "0.46765864", "0.46706823", "0.46701157", "0.46693403", "0.466293", "0.46606505", "0.46594703", "0.46474025", "0.464473", "0.46373475", "0.46347648", "0.46324775", "0.46301842", "0.46222612", "0.46200487", "0.46193153", "0.461878", "0.46179724", "0.460996", "0.46089643" ]
0.7735376
0
Returns the number of elements in the Tuple
func (this *Tuple) Len() int { return len(this.data) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *Tuple) Count(item interface{}, start int) int {\n\tctr := 0\n\tfor i := start; i < this.Len(); i++ {\n\t\tif TupleElemEq(this.Get(i), item) {\n\t\t\tctr += 1\n\t\t}\n\t}\n\treturn ctr\n}", "func (td TupleDesc) Count() int {\n\treturn len(td.Types)\n}", "func NumColumns(t sql.Type) int {\n\tv, ok := t.(TupleType)\n\tif !ok {\n\t\treturn 1\n\t}\n\treturn len(v)\n}", "func GetNumElements(results []string) int {\n\ti := 0\n for _, _ = range results {\n\t\t\ti++\n }\n return i\n}", "func (dict *Dictionary) NumberOfElements() int {\n\tdict.lock.RLock()\n\tdefer dict.lock.RUnlock()\n\treturn len(dict.elements)\n}", "func (o SecurityPolicyRuleResponseOutput) RuleTupleCount() pulumi.IntOutput {\n\treturn o.ApplyT(func(v SecurityPolicyRuleResponse) int { return v.RuleTupleCount }).(pulumi.IntOutput)\n}", "func len(v Type) int32 {}", "func (o FirewallPolicyRuleResponseOutput) RuleTupleCount() pulumi.IntOutput {\n\treturn o.ApplyT(func(v FirewallPolicyRuleResponse) int { return v.RuleTupleCount }).(pulumi.IntOutput)\n}", "func (list *ArrayList[T]) Size() int {\n\treturn len(list.elems)\n}", "func (i IntHashMap[T, V]) Len() int {\n\t// DEBUG:\n\tif len(i.hashToKey) != len(i.hashToVal) {\n\t\tpanic(\"hashToKey and hashToVal have different lengths\")\n\t}\n\treturn len(i.hashToKey)\n}", "func (el Elements) Len() int {\n\tswitch el.Type {\n\tcase part3.Int32:\n\t\treturn len(el.I32)\n\tcase part3.Float32:\n\t\treturn len(el.F32)\n\tcase part3.Float64:\n\t\treturn len(el.F64)\n\tdefault:\n\t\treturn -1\n\t}\n}", "func (m *Mapping) Len() int { return len(m.Pairs) }", "func (x uints) Len() int { return len(x) }", "func (x uints) Len() int { return len(x) }", "func (x uints) Len() int { return len(x) }", "func size(v Type) int32 {}", "func (vs variableSet) count() int {\n\tc := 0\n\tif vs[0] != nil {\n\t\tc++\n\t}\n\tif vs[1] != nil {\n\t\tc++\n\t}\n\tif vs[2] != nil {\n\t\tc++\n\t}\n\tif vs[3] != nil {\n\t\tc++\n\t}\n\treturn c\n}", "func (s sortedPairs) Len() int {\n\treturn len(s)\n}", "func (b *Bag) Len() int {\n\tsum := 0\n\tfor _, v := range *b {\n\t\tsum += int(v)\n\t}\n\treturn sum\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 (t *TupleType) NumVersions() int {\n\treturn len(t.versions)\n}", "func (mp *Mempool) SizeofElement() int {\n\treturn int(mp.ptr().elt_size)\n}", "func (m *Map[K, V]) Len() int {\n\tm.mu.RLock()\n\tdefer m.mu.RUnlock()\n\n\treturn len(m.inner)\n}", "func (a byCount) Len() int { return len(a) }", "func (arr *ArrayList) Len() uint32 {\n return arr.length\n}", "func (p Pair) Len() int {\n\treturn len(p.Base.String()) + len(p.Quote.String())\n}", "func (c *IfPair) Len() int {\n\treturn 0\n}", "func (hm *HashMap) Len() int {\n\treturn hm.np.elemNum()\n}", "func (n Nodes) Len() int", "func sizeOfValues(valueList []interface{}) uint32 {\n\tvar totalLen, lenBytes uint32\n\tfor _, val := range valueList {\n\t\tswitch v := val.(type) {\n\t\tcase uint8, int8, bool:\n\t\t\tlenBytes = 1\n\t\tcase uint32, int32, float32:\n\t\t\tlenBytes = 4\n\t\tcase uint64, int64, float64:\n\t\t\tlenBytes = 8\n\t\tcase string:\n\t\t\tlenBytes = 4 // length prefix\n\t\t\tlenBytes += uint32(len(v))\n\t\t}\n\t\ttotalLen += lenBytes\n\t}\n\treturn totalLen\n}", "func (r *RingT[T]) Len() int {\n\treturn int((r.head - r.tail) & r.mask)\n}", "func (a byScore) Len() int { return len(a) }", "func (args *Args) len() int {\n\treturn len(args.items)\n}", "func (set *lalrSet) size() (count int) {\n\tfor _, list := range(set.items) {\n\t\tcount = count + len(list)\n\t}\n\treturn\n}", "func (ips IntPairSlice) Len() int {\n\treturn len(ips)\n}", "func (m *HashMap) Len() int {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\treturn len(m.data)\n}", "func (i StringHashMap[T, V]) Len() int {\n\t// DEBUG:\n\tif len(i.hashToKey) != len(i.hashToVal) {\n\t\tpanic(\"hashToKey and hashToVal have different lengths\")\n\t}\n\treturn len(i.hashToKey)\n}", "func (n nodes) Len() int { return len(n) }", "func (self params) Count() int { return len(self) }", "func (a ASTNode) Len() int {\n\tif !a.IsArr() {\n\t\tpanic(ConfErr{a.pos, errors.New(\"Not an array\")})\n\t}\n\treturn len(a.val.(astArr))\n}", "func (s *SliceOfUint) Len() int {\n\treturn len(s.items)\n}", "func (list elemlist) Len() int {\n\treturn len(list.elements)\n}", "func (this *parameter) Count() int {\n\treturn len(this.Values)\n}", "func (l *SList) Len() int { return l.n }", "func (e Elements) Len() int {\n\treturn len(e)\n}", "func (vp *baseVectorParty) GetElemCount(row int) uint32 {\n\tif vp.offsets == nil || row < 0 || row >= vp.length {\n\t\treturn 0\n\t}\n\treturn *(*uint32)(vp.offsets.GetValue(2*row + 1))\n}", "func (c *AssertionImpl) Len() int {\n\treturn c.counter.Value()\n}", "func (t *AreaTopology) Len() int {\n\tn := 0\n\tfor _, area := range t.areas {\n\t\tn += len(area.nodes)\n\t}\n\treturn n\n}", "func (t *T) Len() int {\n\treturn t.words\n}", "func (a *ArrayList) Len() int {\n\treturn len(a.elements)\n}", "func (a Slice[T]) CountElement(element T) (count int) {\n\tfor _, o := range a {\n\t\tif o == element {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}", "func Len(set Interface) int {\n\treturn len(set.Members())\n}", "func (p *Packet) Size() (int, int, error) {\n\tvar size int\n\tif p.Primitive {\n\t\tif p.Value == nil {\n\t\t\treturn 0, 0, errors.New(\"ldap: nil value in Packet.Size\")\n\t\t}\n\t\tswitch v := p.Value.(type) {\n\t\tcase []byte:\n\t\t\tsize = len(v)\n\t\tcase string:\n\t\t\tsize = len(v)\n\t\tcase int:\n\t\t\tsize = intSize(int64(v))\n\t\tcase bool:\n\t\t\tsize = 1\n\t\tdefault:\n\t\t\treturn 0, 0, fmt.Errorf(\"ldap: unknown type in Packet.Size: %T\", p.Value)\n\t\t}\n\t} else {\n\t\tfor _, it := range p.Items {\n\t\t\t_, n, err := it.Size()\n\t\t\tif err != nil {\n\t\t\t\treturn 0, 0, err\n\t\t\t}\n\t\t\tsize += n\n\t\t}\n\t}\n\tif size < 128 {\n\t\treturn size, size + 2, nil\n\t}\n\tn := 0\n\tfor x := size; x != 0; x >>= 8 {\n\t\tn++\n\t}\n\treturn size, size + 2 + n, nil\n}", "func (l lit) Len() int {\n\treturn 1\n}", "func (t *Array) Size() int32 { return t.T.Size() * t.N }", "func (s *StringArray) Len() int {\n\tl := 4\n\tfor _, ss := range s.Strings {\n\t\tl += ss.Len()\n\t}\n\n\treturn l\n}", "func OnesCount(x uint) int {\n\tif UintSize == 32 {\n\t\treturn OnesCount32(uint32(x))\n\t}\n\treturn OnesCount64(uint64(x))\n}", "func (t *Tags) Len() int { return len(t.keyvals) }", "func (*Integer) NKeys() int { return 2 }", "func (s *shard) len() uint64 {\n\ts.rwMutex.RLock()\n\tlength := uint64(len(s.entryIndexes))\n\ts.rwMutex.RUnlock()\n\n\treturn length\n}", "func GetListItemCount(list *List) uint64 {\n return list.itemCount;\n}", "func (p Polygon) NumVertices() int {\n\tnum := 0\n\tfor _, c := range p {\n\t\tnum += len(c)\n\t}\n\treturn num\n}", "func (a infoSlice) Len() int { return len(a) }", "func (s *SliceOfInt) Len() int {\n\treturn len(s.items)\n}", "func (p *Puzzle) Len() int {\r\n\treturn 4 + 4 + len(p.Random) + len(p.Padding)\r\n}", "func (p priorities) Len() int { return len(p) }", "func (fi *FastIntegerHashMap) Len() uint64 {\n\treturn fi.count\n}", "func sizeof(v reflect.Value, t reflect.Type) int {\n\tswitch t.Kind() {\n\tcase reflect.Array:\n\t\tif s := sizeof(v, t.Elem()); s >= 0 {\n\t\t\treturn s * t.Len()\n\t\t}\n\n\tcase reflect.Struct:\n\t\tsum := 0\n\t\tfor i, n := 0, t.NumField(); i < n; i++ {\n\t\t\ts := dataSize(v.Field(i))\n\t\t\tif s < 0 {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\tsum += s\n\t\t}\n\t\treturn sum\n\n\tcase reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint,\n\t\treflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int,\n\t\treflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128,\n\t\treflect.Uintptr, reflect.Ptr:\n\t\treturn int(t.Size())\n\n\tcase reflect.String:\n\t\treturn len(v.String())\n\n\tcase reflect.Map:\n\t\tsum := 0\n\t\tfor _, mapKey := range v.MapKeys() {\n\t\t\tkeySize := dataSize(mapKey)\n\t\t\tvalueSize := dataSize(v.MapIndex(mapKey))\n\t\t\tif keySize < 0 || valueSize < 0 {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\tsum += keySize + valueSize\n\t\t}\n\t\treturn sum\n\t}\n\n\treturn -1\n}", "func (h *Hypotheses) Len() int {\n\treturn len(h.beams)\n}", "func (ne nodeEntries) Len() int { return len(ne) }", "func (n Name) Len() int {\n\tvar length int\n\tfor _, l := range n {\n\t\tlength += l.Len()\n\t}\n\treturn length\n}", "func (ti *TimeIndex) Len() int {\n ti.lock.RLock()\n defer ti.lock.RUnlock()\n return len(ti.entries)\n}", "func (e *metaMultiArgElement) length() int {\n\tif e.size >= 0 {\n\t\treturn e.size\n\t}\n\treturn 1\n}", "func (s *SliceOfInt8) Len() int {\n\treturn len(s.items)\n}", "func (tt PMap) Len() int {\n\treturn len(tt)\n}", "func nodeLen(data interface{}) int {\n\tif data == nil {\n\t\treturn 0\n\t}\n\tswitch d := data.(type) {\n\tcase []interface{}:\n\t\treturn len(d)\n\tcase map[string]interface{}:\n\t\treturn len(d)\n\tcase string, int, float64, bool:\n\t\treturn 1\n\t}\n\treturn 0\n}", "func (t *Trace) Len() int {\n\treturn t.n\n}", "func (p PartialAttributeList) size() (size int) {\n\tfor _, att := range p {\n\t\tsize += att.size()\n\t}\n\tsize += sizeTagAndLength(tagSequence, size)\n\treturn\n}", "func (p PartialAttributeList) size() (size int) {\n\tfor _, att := range p {\n\t\tsize += att.size()\n\t}\n\tsize += sizeTagAndLength(tagSequence, size)\n\treturn\n}", "func (o VertexSet) Len() int { return len(o) }", "func countScalars(input []interface{}) int {\n\tfor i := 0; i < len(input); i++ {\n\t\tswitch input[i].(type) {\n\t\tcase keyvalser:\n\t\t\treturn i\n\t\t}\n\t}\n\treturn len(input)\n}", "func (set *SetThreadSafe) Size() int {\n\ti := 0\n\tset.Items.Range(func(k, v interface{}) bool {\n\t\ti++\n\t\treturn true\n\t})\n\treturn i\n}", "func (ts tagMap) Len() int {\n\treturn len(ts)\n}", "func (nl *nodeList) size() int {\n\treturn len(nl.elements)\n}", "func (v Var) Len() (uint64, error) {\n\tdims, err := v.Dims()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tn := uint64(1)\n\tfor _, d := range dims {\n\t\tlen, err := d.Len()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tn *= len\n\t}\n\treturn n, nil\n}", "func (items IntSlice) Len() int { return len(items) }", "func countElements(arr []int) int {\n\tcount := 0\n\tif len(arr) == 1 {\n\t\treturn 0\n\t}\n\tfor i := 1; i < len(arr); i++ {\n\t\tif arr[i] == arr[i-1]+1 {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count\n}", "func (ht *ValueHashtable) Size() int {\r\n\tht.lock.RLock()\r\n\tdefer ht.lock.RUnlock()\r\n\treturn len(ht.items)\r\n}", "func (el Elements) Len() int {\n\treturn len(el)\n}", "func Len(m Map) int {\n\treturn m.count()\n}", "func (h *Hash) Len() int {\n\tsum := 0\n\tfor _, bucket := range h.buckets {\n\t\tsum += len(bucket)\n\t}\n\treturn sum\n}", "func (m MessageID) size() int {\n\treturn INTEGER(m).size()\n}", "func (m *Map) Len() int {\n\tm.store.RLock()\n\tdefer m.store.RUnlock()\n\tn := len(m.store.kv)\n\treturn n\n}", "func (tt *TtTable) Len() uint64 {\n\treturn tt.numberOfEntries\n}", "func (l *sampleList) Len() int { return len(l.samples) - len(l.free) }", "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 (t *OptimizedTimes) Len() int {\n\treturn t.arrIdx + len(t.slice)\n}", "func (p FunctionCallSlice) Len() int { return len(p) }", "func (ll *Doubly[T]) Count() int {\n\tvar ctr int = 0\n\n\tif ll.Head.Next == nil {\n\t\treturn 0\n\t}\n\n\tfor cur := ll.Head.Next; cur != ll.Head; cur = cur.Next {\n\t\tctr += 1\n\t}\n\n\treturn ctr\n}", "func (t *RbTree[K, V]) Size() int {\n\treturn t.size\n}" ]
[ "0.69410515", "0.6893016", "0.6410716", "0.6153475", "0.61361754", "0.610362", "0.6076785", "0.60695654", "0.6045291", "0.6018257", "0.59564084", "0.5934482", "0.58451253", "0.58451253", "0.58451253", "0.58381146", "0.5813469", "0.5806193", "0.5801226", "0.5790625", "0.5786606", "0.5771976", "0.57667077", "0.5755541", "0.57497394", "0.5715994", "0.5706886", "0.570539", "0.56997055", "0.5696727", "0.5691726", "0.5686997", "0.56855613", "0.5683595", "0.5680705", "0.5637937", "0.56274265", "0.56209296", "0.5618026", "0.5605394", "0.55997694", "0.5595303", "0.55929947", "0.55902356", "0.5587841", "0.55728054", "0.55536324", "0.55499727", "0.55477905", "0.55453193", "0.5538858", "0.55253947", "0.5522906", "0.551913", "0.5511527", "0.5499939", "0.54978466", "0.5496074", "0.5494979", "0.54905266", "0.5490495", "0.54835427", "0.54826325", "0.5482041", "0.5477547", "0.54768616", "0.54745907", "0.5469454", "0.5463387", "0.54628044", "0.54597723", "0.54523623", "0.54488516", "0.544755", "0.54450226", "0.5442891", "0.54332715", "0.5432491", "0.5432491", "0.5431329", "0.5419186", "0.5418565", "0.54185194", "0.54165566", "0.5410552", "0.54083705", "0.54081607", "0.54021883", "0.53994316", "0.5392918", "0.5390574", "0.5388492", "0.53793126", "0.53790486", "0.537736", "0.53737855", "0.5369393", "0.5365729", "0.5365132", "0.53612447" ]
0.7210012
0
Returns the internal slice
func (this *Tuple) Data() []interface{} { return this.data }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getSlice(p position) []byte {\n\ts, i := getChunkLocation(p.chunk)\n\tbufStart := int(i)*ChunkSize + p.chunkPos\n\tbufLen := ChunkSize - p.chunkPos\n\treturn slabs[s].memory[bufStart : bufStart+bufLen]\n}", "func (iobuf *buf) slice(free, base, bound uint) *Slice {\n\tatomic.AddInt32(&iobuf.refcount, 1)\n\treturn &Slice{iobuf: iobuf, free: free, base: base, Contents: iobuf.Contents[base:bound]}\n}", "func (w *Window) Slice() []float64 {\n\tw.mx.RLock()\n\t// 4 Times faster than \"defer Unlock\"\n\tret := w.base[w.start : w.start+w.Len]\n\tw.mx.RUnlock()\n\treturn ret\n}", "func (s *slice) slice(start, stop int, elemsize uintptr) slice {\n\tif start >= s.cap_ || start < 0 || stop > s.cap_ || stop < 0 {\n\t\tpanic(\"cuda4/safe: slice index out of bounds\")\n\t}\n\tif start > stop {\n\t\tpanic(\"cuda4/safe: inverted slice range\")\n\t}\n\treturn slice{cu.DevicePtr(uintptr(s.ptr_) + uintptr(start)*elemsize), stop - start, s.cap_ - start}\n}", "func (items IntSlice) SubSlice(i, j int) Interface { return items[i:j] }", "func (s *SliceOfInt8) GetSlice() *[]int8 {\n\treturn &s.items\n}", "func (s *SliceOfByte) GetSlice() *[]byte {\n\treturn &s.items\n}", "func (s *SliceOfUint16) GetSlice() *[]uint16 {\n\treturn &s.items\n}", "func (s *SliceOfInt16) GetSlice() *[]int16 {\n\treturn &s.items\n}", "func (s *SliceOfUint8) GetSlice() *[]uint8 {\n\treturn &s.items\n}", "func (b *Buffer) Slice() []byte {\n\t// Skip IP and UDP headers\n\treturn b[(ipv4HeaderSize + udp4HeaderSize):]\n}", "func GetSlice() {\n\tvar slice1 []string\n\tslice1 = append(slice1, \"mi\", \"slice\", \"1\")\n\tfmt.Println(slice1)\n}", "func (h *MaxHeap) Slice() (result []int) {\n\tresult = make([]int, h.used)\n\n\tfor i := 1; i <= h.used; i++ {\n\t\tresult[i-1] = h.data[i]\n\t}\n\treturn result\n}", "func (items Float64Slice) SubSlice(i, j int) Interface { return items[i:j] }", "func (s *SliceOfUint64) GetSlice() *[]uint64 {\n\treturn &s.items\n}", "func (s SamplesC64) Slice(start, end int) Samples {\n\treturn s[start:end]\n}", "func (h *MinHeap) Slice() (result []int) {\n\tresult = make([]int, h.used)\n\n\tfor i := 1; i <= h.used; i++ {\n\t\tresult[i-1] = h.data[i]\n\t}\n\treturn result\n}", "func (s *SliceOfInt64) GetSlice() *[]int64 {\n\treturn &s.items\n}", "func (s *SliceOfUint) GetSlice() *[]uint {\n\treturn &s.items\n}", "func (in *InBuffer) Slice(n int) []byte {\n\tr := in.Data[in.ReadPos : in.ReadPos+n]\n\tin.ReadPos += n\n\treturn r\n}", "func (in *InBuffer) Slice(n int) []byte {\n\tr := in.Data[in.ReadPos : in.ReadPos+n]\n\tin.ReadPos += n\n\treturn r\n}", "func (s *f64) Slice(start, end int) Floating {\n\tstart = s.BufferIndex(0, start)\n\tend = s.BufferIndex(0, end)\n\treturn &f64{\n\t\tchannels: s.channels,\n\t\tbuffer: s.buffer[start:end],\n\t}\n}", "func (n Nodes) Slice() []*Node", "func (b *Slice) Sub(top, bot int) *Slice {\n\tif top < 0 || bot < top {\n\t\treturn nil\n\t}\n\treturn &Slice{\n\t\tbuffer: b.buffer,\n\t\ttop: b.top + top,\n\t\tbot: b.top + bot,\n\t\tcap: b.cap,\n\t}\n}", "func (self *T) Slice() []float32 {\n\treturn []float32{\n\t\tself[0][0], self[0][1],\n\t\tself[1][0], self[1][1],\n\t}\n}", "func (self *T) Slice() []float64 {\n\treturn []float64{self[0], self[1]}\n}", "func (s *VectorImplSlice) Slice(start, stop int) *VectorImplSlice {\n\tassertSliceOk(start, stop, s.stop-s.start)\n\treturn &VectorImplSlice{vector: s.vector, start: s.start + start, stop: s.start + stop}\n}", "func (arr *Array) Slice(i, j int) *Array {\n\tvar elems []*Term\n\tvar hashs []int\n\tif j == -1 {\n\t\telems = arr.elems[i:]\n\t\thashs = arr.hashs[i:]\n\t} else {\n\t\telems = arr.elems[i:j]\n\t\thashs = arr.hashs[i:j]\n\t}\n\t// If arr is ground, the slice is, too.\n\t// If it's not, the slice could still be.\n\tgr := arr.ground || termSliceIsGround(elems)\n\n\ts := &Array{elems: elems, hashs: hashs, ground: gr}\n\ts.rehash()\n\treturn s\n}", "func (d *Decoder) Slice(n int) ([]byte, error) {\n\tif d.s != nil {\n\t\treturn d.s.Slice(n)\n\t}\n\n\t// If we don't have a slicer, we can just allocate and read\n\tbuffer := make([]byte, n, n)\n\tif _, err := d.Read(buffer); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buffer, nil\n}", "func Slice(d Dense, start, end int) (Dense, error) {\n\tif end-start > d.len {\n\t\treturn Dense{}, fmt.Errorf(\"slicing bitmap of len %d up to %d\", d.len, end-start)\n\t}\n\tif start < 0 {\n\t\treturn Dense{}, fmt.Errorf(\"slicing bitmap with negative start: %d\", start)\n\t}\n\tif end < start {\n\t\treturn Dense{}, fmt.Errorf(\"slicing bitmap to negative length: %d\", end-start)\n\t}\n\n\tr := Dense{}\n\tfor ; start%byteSize != 0; start++ {\n\t\tr.AppendBit(d.Get(start))\n\t}\n\tj := start / byteSize\n\ttmp := NewDense(d.bits[j:j+BytesFor(end-start)], end-start)\n\tr.Append(tmp)\n\treturn r, nil\n}", "func (vp *baseVectorParty) Slice(startRow, numRows int) common.SlicedVector {\n\tsize := vp.length - startRow\n\tif size < 0 {\n\t\tsize = 0\n\t}\n\tif size > numRows {\n\t\tsize = numRows\n\t}\n\tvector := common.SlicedVector{\n\t\tValues: make([]interface{}, size),\n\t\tCounts: make([]int, size),\n\t}\n\tfor i := 0; i < size; i++ {\n\t\tvector.Values[i] = vp.getDataValueFn(startRow + i).ConvertToHumanReadable(vp.dataType)\n\t\tvector.Counts[i] = i + 1\n\t}\n\n\treturn vector\n}", "func (bm ByteMap) Slice(includeKeys map[string]bool) ByteMap {\n\tresult, _ := bm.doSplit(false, includeKeys)\n\treturn result\n}", "func (this *Tuple) Slice(start int, end int) *Tuple {\n\tc := this.Copy()\n\tmax := this.Len()\n\tstart = min(c.Offset(start), max)\n\tend = min(c.Offset(end), max)\n\tc.data = c.data[start:end]\n\treturn c\n}", "func (obj *Code) GetSlice() interface{} {\n\treturn new([]Code)\n}", "func (n *Node) SliceBounds() (low, high, max *Node)", "func (s *SliceOfInt) GetSlice() *[]int {\n\treturn &s.items\n}", "func (h PacketHeader) Slice() []byte {\n\tview := h.pk.headerView(h.typ)\n\treturn view.AsSlice()\n}", "func (q *SensorStack) Slice(start int, end int) (top []*SensorReading, err error) {\n\ttop = []*SensorReading{&errorReading}\n\tif q.Len() == 0 {\n\t\terr = errors.New(\"Empty Stack\")\n\t\treturn\n\t}\n\tif end > q.Len()-1 || start > q.Len()-1 {\n\t\terr = errors.New(\"Slice Range Out Of Bounds\")\n\t\treturn\n\t}\n\ttop = (*q)[start:end]\n\treturn\n}", "func (f *file) Slice(off int64, l int) ([]byte, error) {\n\t// return EOF if offset is larger than the file size\n\tif off >= f.sz {\n\t\treturn nil, io.EOF\n\t}\n\t// shorten the length, if necessary\n\tvar err error\n\tif off+int64(l) > f.sz {\n\t\tl = int(f.sz - off)\n\t\terr = io.EOF\n\t}\n\t// the slice falls entirely in the bof segment\n\tif off+int64(l) <= int64(initialRead) {\n\t\treturn f.peek[int(off) : int(off)+l], err\n\t}\n\tf.once.Do(func() {\n\t\tf.data = f.pool.get(f)\n\t})\n\tret := f.slice(off, l)\n\treturn ret, err\n}", "func (seq *Sequence) Slice() (s []interface{}) {\n\ts = make([]interface{}, len(seq.Nodes))\n\tfor i, n := range seq.Nodes {\n\t\ts[i] = n.Data()\n\t}\n\treturn\n}", "func (s *IntSlicer) AsSlice() []int {\n\treturn s.slice\n}", "func (i *Iter) returnSlice(a, b int) []byte {\n\tif i.rb.src.bytes == nil {\n\t\treturn i.buf[:copy(i.buf[:], i.rb.src.str[a:b])]\n\t}\n\treturn i.rb.src.bytes[a:b]\n}", "func (f *IOFile) Slice(start int64, end int64) ([]byte, error) {\n\tbuf := make([]byte, end-start)\n\t_, err := f.ReadAt(buf, start)\n\treturn buf, err\n}", "func (v View) Slice() []bool {\n\t// TODO: This forces an alloc, as an alternative a slice could be taken\n\t// as input that can be (re)used by the client. Are there use cases\n\t// where this would actually make sense?\n\tresult := make([]bool, v.Len())\n\tfor i, j := range v.index {\n\t\tresult[i] = v.data[j]\n\t}\n\treturn result\n}", "func (b Bits) Slice() (s []int) {\n\tfor x, w := range b.Bits {\n\t\tif w == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tt := mb.TrailingZeros64(w)\n\t\ti := t // index in w of next 1 bit\n\t\tfor {\n\t\t\tn := x<<6 | i\n\t\t\tif n >= b.Num {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ts = append(s, n)\n\t\t\tw >>= uint(t + 1)\n\t\t\tif w == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tt = mb.TrailingZeros64(w)\n\t\t\ti += 1 + t\n\t\t}\n\t}\n\treturn\n}", "func (v *VectorImpl) Slice(start, stop int) *VectorImplSlice {\n\tassertSliceOk(start, stop, v.Len())\n\treturn &VectorImplSlice{vector: v, start: start, stop: stop}\n}", "func (b *Blob) Slice(start, end int, contenttype string) *Blob {\n\tnewBlobObject := b.Call(\"slice\", start, end, contenttype)\n\treturn &Blob{\n\t\tObject: newBlobObject,\n\t}\n}", "func (s *SliceOfFloat64) GetSlice() *[]float64 {\n\treturn &s.items\n}", "func (ns Nodes) Slice(pos ...int) Nodes {\n\tplen := len(pos)\n\tl := len(ns)\n\tif plen == 1 && pos[0] < l-1 && pos[0] > 0 {\n\t\treturn ns[pos[0]:]\n\t} else if len(pos) == 2 && pos[0] < l-1 && pos[1] < l-1 && pos[0] > 0 && pos[1] > 0 {\n\t\treturn ns[pos[0]:pos[1]]\n\t}\n\treturn Nodes{}\n}", "func (l *list) Slice(first int, last int) interface{} {\n\ttypeOf := reflect.TypeOf(l.t)\n\tsliceOf := reflect.SliceOf(typeOf)\n\tvar result = reflect.ValueOf(reflect.New(sliceOf).Interface()).Elem()\n\n\tfor _, v := range l.elements[first:last] {\n\t\tresult.Set(reflect.Append(result, reflect.ValueOf(v)))\n\t}\n\n\treturn result.Interface()\n}", "func (*Base) Slice(p ASTPass, node *ast.Slice, ctx Context) {\n\tp.Visit(p, &node.Target, ctx)\n\tp.Fodder(p, &node.LeftBracketFodder, ctx)\n\tif node.BeginIndex != nil {\n\t\tp.Visit(p, &node.BeginIndex, ctx)\n\t}\n\tp.Fodder(p, &node.EndColonFodder, ctx)\n\tif node.EndIndex != nil {\n\t\tp.Visit(p, &node.EndIndex, ctx)\n\t}\n\tp.Fodder(p, &node.StepColonFodder, ctx)\n\tif node.Step != nil {\n\t\tp.Visit(p, &node.Step, ctx)\n\t}\n\tp.Fodder(p, &node.RightBracketFodder, ctx)\n}", "func Slice(t *Tensor) interface{} {\n\tlength := int(DimProduct(t.Dims))\n\tsliceHeader := reflect.SliceHeader{\n\t\tData: uintptr(unsafe.Pointer(&t.Buffer[0])),\n\t\tCap: length,\n\t\tLen: length,\n\t}\n\tval := reflect.NewAt(DtypeToSliceType[t.Dtype], unsafe.Pointer(&sliceHeader)).Elem()\n\treturn val.Interface()\n}", "func (s PointBuffer) SubSlice(low int, high int) PointBuffer {\n\tinBounds := low >= 0 && low <= high && high <= s.cap\n\tif !inBounds {\n\t\tpanic(fmt.Errorf(\n\t\t\t\"runtime error: slice bounds out of range [%d:%d] with capacity %d\",\n\t\t\tlow, high, s.cap,\n\t\t))\n\t}\n\tvar tVar Point\n\ttSize := unsafe.Sizeof(tVar)\n\ttype internalPtr struct {\n\t\toffset uintptr\n\t\tbucketIdx uint8\n\t\tarenaMask uint16\n\t}\n\tcurrentPtr := *(*internalPtr)(unsafe.Pointer(&s.data))\n\tnewPtr := internalPtr{\n\t\toffset: currentPtr.offset + uintptr(low*int(tSize)),\n\t\tbucketIdx: currentPtr.bucketIdx,\n\t\tarenaMask: currentPtr.arenaMask,\n\t}\n\treturn PointBuffer{\n\t\tdata: *(*arena.Ptr)(unsafe.Pointer(&newPtr)),\n\t\tlen: high - low,\n\t\tcap: s.cap - low,\n\t}\n}", "func (l *AutoscalerResourceLimitsGPULimitList) Slice() []*AutoscalerResourceLimitsGPULimit {\n\tvar slice []*AutoscalerResourceLimitsGPULimit\n\tif l == nil {\n\t\tslice = make([]*AutoscalerResourceLimitsGPULimit, 0)\n\t} else {\n\t\tslice = make([]*AutoscalerResourceLimitsGPULimit, len(l.items))\n\t\tcopy(slice, l.items)\n\t}\n\treturn slice\n}", "func (hhm *HHM) Slice(start, end int) *HHM {\n\thmm := hhm.HMM.Slice(start, end)\n\n\tmeta := hhm.Meta\n\tmeta.Neff = 0\n\tfor _, node := range hmm.Nodes {\n\t\tmeta.Neff += node.NeffM\n\t}\n\tmeta.Neff /= seq.Prob(len(hmm.Nodes))\n\n\treturn &HHM{\n\t\tMeta: meta,\n\t\tSecondary: hhm.Secondary.Slice(start, end),\n\t\tMSA: hhm.MSA.Slice(start, end),\n\t\tHMM: hmm,\n\t}\n}", "func (ml *MemoryLogger) Slice() []string {\n\tsl := ml.RingBuffer.Slice()\n\tret := make([]string, len(sl))\n\tfor i, lm := range sl {\n\t\tret[i] = lm.(string)\n\t}\n\treturn ret\n}", "func (s *SliceOfUint32) GetSlice() *[]uint32 {\n\treturn &s.items\n}", "func (this *Iter_UServ_Drop) Slice() []*Row_UServ_Drop {\n\tvar results []*Row_UServ_Drop\n\tfor {\n\t\tif i, ok := this.Next(); ok {\n\t\t\tresults = append(results, i)\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn results\n}", "func (n NoOp) Slice(start, end int) PrimitiveOp {\n\treturn NoOp{}\n}", "func (lf LevelFile) Slice() LevelSlice {\n\treturn lf.slice\n}", "func (s SampleList) Slice(start, end int) anysgd.SampleList {\n\treturn append(SampleList{}, s[start:end]...)\n}", "func (s *SliceOfFloat32) GetSlice() *[]float32 {\n\treturn &s.items\n}", "func makeslice(len_ int, elemsize int) slice {\n\tbytes := int64(len_) * int64(elemsize)\n\ts := slice{0, len_, len_}\n\tif bytes > 0 {\n\t\ts.ptr_ = cu.MemAlloc(bytes)\n\t\tcu.MemsetD8(s.ptr_, 0, bytes)\n\t\tcu.CtxSynchronize()\n\t}\n\treturn s\n}", "func (jbobject *JavaNioCharBuffer) Slice() *JavaNioCharBuffer {\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"slice\", \"java/nio/CharBuffer\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tretconv := javabind.NewJavaToGoCallable()\n\tdst := &javabind.Callable{}\n\tretconv.Dest(dst)\n\tif err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {\n\t\tpanic(err)\n\t}\n\tretconv.CleanUp()\n\tunique_x := &JavaNioCharBuffer{}\n\tunique_x.Callable = dst\n\treturn unique_x\n}", "func (s *TreeMap) Slice() *[]interface{} {\n\ts.CheckInit()\n\n\tif s.Threadsafe() {\n\t\ts.Lockb.RLock()\n\t\tdefer s.Lockb.RUnlock()\n\t}\n\n\tslice := make([]interface{}, 0, s.Size())\n\n s.Map(func(kv interface{}) bool {\n kvc, _ := kv.(*KeyValue)\n slice = append(slice, kvc)\n return true\n })\n\treturn &slice\n}", "func (l *PendingDeleteClusterList) Slice() []*PendingDeleteCluster {\n\tvar slice []*PendingDeleteCluster\n\tif l == nil {\n\t\tslice = make([]*PendingDeleteCluster, 0)\n\t} else {\n\t\tslice = make([]*PendingDeleteCluster, len(l.items))\n\t\tcopy(slice, l.items)\n\t}\n\treturn slice\n}", "func main() {\n\ts := []int{2, 3, 5, 7, 11, 13}\n\tprintSlice(s)\n\n\tb := s[:0]\n\tprintSlice(b)\n\n\tc := s[:4]\n\tprintSlice(c)\n\n\td := s[2:]\n\tprintSlice(d)\n}", "func Slice(s Stream, start int, end int) Stream {\n return &sliceStream{Stream: s, start: start, end: end}\n}", "func Slice[T any](ptr *T, length int) []T {\n\treturn unsafe.Slice(ptr, length)\n}", "func (s *Uint64) Slice() []uint64 {\n\tres := make([]uint64, 0, len(s.m))\n\n\tfor val := range s.m {\n\t\tres = append(res, val)\n\t}\n\treturn res\n}", "func (s *Set) Slice() []uint32 {\n\tsl := make([]uint32, len(s.items))\n\ti := 0\n\tfor item := range s.items {\n\t\tsl[i] = item\n\t\ti++\n\t}\n\treturn sl\n}", "func (t *StringSlice) Slice(start int, length int) []string {\n\tvar ret []string\n\tif start >= 0 && start+length <= len(t.items) && start+length >= 0 {\n\t\tret = t.items[start : start+length]\n\t}\n\treturn ret\n}", "func (t *Indexed) Slice() [][]int {\n\tresult := make([][]int, 0, t.size)\n\tt.inOrder(t.root, func(cur *Node) {\n\t\tresult = append(result, []int{cur.key, cur.value})\n\t})\n\treturn result\n}", "func (p *parser) sliceFrom(start savepoint) []byte {\n\treturn p.data[start.position.offset:p.pt.position.offset]\n}", "func (p *parser) sliceFrom(start savepoint) []byte {\n\treturn p.data[start.position.offset:p.pt.position.offset]\n}", "func (p *parser) sliceFrom(start savepoint) []byte {\n\treturn p.data[start.position.offset:p.pt.position.offset]\n}", "func (p *parser) sliceFrom(start savepoint) []byte {\n\treturn p.data[start.position.offset:p.pt.position.offset]\n}", "func (p *parser) sliceFrom(start savepoint) []byte {\n\treturn p.data[start.position.offset:p.pt.position.offset]\n}", "func (m *Matrix) Slice() []float64 {\n\treturn nil\n}", "func GetSlice() []int {\n\tx := []int{1, 2, 3}\n\treturn x\n}", "func Reslice(slc []byte, lidx int, uidx int) []byte {\n\tslice := AllocateMake(uidx)\n\tslice = slc[lidx:uidx]\n\treturn slice\n}", "func (p PageGroup) Slice(in any) (any, error) {\n\tswitch items := in.(type) {\n\tcase PageGroup:\n\t\treturn items, nil\n\tcase []any:\n\t\tgroups := make(PagesGroup, len(items))\n\t\tfor i, v := range items {\n\t\t\tg, ok := v.(PageGroup)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"type %T is not a PageGroup\", v)\n\t\t\t}\n\t\t\tgroups[i] = g\n\t\t}\n\t\treturn groups, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid slice type %T\", items)\n\t}\n}", "func (t *Dense) slice(start, end int) {\n\tswitch t.t.Kind() {\n\tcase reflect.Bool:\n\t\tdata := t.bools()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Int:\n\t\tdata := t.ints()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Int8:\n\t\tdata := t.int8s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Int16:\n\t\tdata := t.int16s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Int32:\n\t\tdata := t.int32s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Int64:\n\t\tdata := t.int64s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uint:\n\t\tdata := t.uints()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uint8:\n\t\tdata := t.uint8s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uint16:\n\t\tdata := t.uint16s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uint32:\n\t\tdata := t.uint32s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uint64:\n\t\tdata := t.uint64s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uintptr:\n\t\tdata := t.uintptrs()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Float32:\n\t\tdata := t.float32s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Float64:\n\t\tdata := t.float64s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Complex64:\n\t\tdata := t.complex64s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Complex128:\n\t\tdata := t.complex128s()[start:end]\n\t\tt.fromSlice(data)\n\n\tcase reflect.String:\n\t\tdata := t.strings()[start:end]\n\t\tt.fromSlice(data)\n\n\tcase reflect.UnsafePointer:\n\t\tdata := t.unsafePointers()[start:end]\n\t\tt.fromSlice(data)\n\tdefault:\n\t\tv := reflect.ValueOf(t.v)\n\t\tv = v.Slice(start, end)\n\t\tt.fromSlice(v.Interface())\n\t}\n}", "func (f *Fields) Slice() []*Field", "func (DummyStore) GetSlice(key string) ([]interface{}, error) {\n\treturn nil, nil\n}", "func (s *SliceOfInt32) GetSlice() *[]int32 {\n\treturn &s.items\n}", "func (t *Dense) Slice(slices ...Slice) (retVal Tensor, err error) {\n\tvar newAP *AP\n\tvar ndStart, ndEnd int\n\n\tif newAP, ndStart, ndEnd, err = t.AP.S(t.len(), slices...); err != nil {\n\t\treturn\n\t}\n\n\tview := new(Dense)\n\tview.t = t.t\n\tview.viewOf = t\n\tview.AP = newAP\n\tview.hdr = new(reflect.SliceHeader)\n\tview.data = t.data\n\tview.hdr.Data = t.hdr.Data\n\tview.hdr.Len = t.hdr.Len\n\tview.hdr.Cap = t.hdr.Cap\n\tview.slice(ndStart, ndEnd)\n\n\tif t.IsMasked() {\n\t\tview.mask = t.mask[ndStart:ndEnd]\n\t}\n\treturn view, err\n}", "func (l *AutoscalerScaleDownConfigList) Slice() []*AutoscalerScaleDownConfig {\n\tvar slice []*AutoscalerScaleDownConfig\n\tif l == nil {\n\t\tslice = make([]*AutoscalerScaleDownConfig, 0)\n\t} else {\n\t\tslice = make([]*AutoscalerScaleDownConfig, len(l.items))\n\t\tcopy(slice, l.items)\n\t}\n\treturn slice\n}", "func (p *SliceOfMap) Slice(indices ...int) ISlice {\n\tif p == nil || len(*p) == 0 {\n\t\treturn NewSliceOfMapV()\n\t}\n\n\t// Handle index manipulation\n\ti, j, err := absIndices(len(*p), indices...)\n\tif err != nil {\n\t\treturn NewSliceOfMapV()\n\t}\n\n\tslice := SliceOfMap((*p)[i:j])\n\treturn &slice\n}", "func (s *slice) Pointer() cu.DevicePtr { return s.ptr_ }", "func (b BoardFeature) Slice() []string {\n\treturn _BoardFeature.slice(uint64(b))\n}", "func (g *GeoTIFF) GetSlice(offset uint, size uint) (*DataSlice, error) {\n\tbuffer := make([]byte, size)\n\t_, err := g.source.ReadAt(buffer, int64(offset))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot read data from file due to %v\", err)\n\t}\n\tdataSlice := NewDataSlice(buffer, offset, g.littleEndian, g.bigTiff)\n\treturn dataSlice, nil\n}", "func (lm *LevelMetadata) Slice() LevelSlice {\n\treturn newLevelSlice(lm.tree.Iter())\n}", "func (list *List) Slice() *Slice {\n\tslice := NewSlice()\n\tfor _, e := range list.m {\n\t\tslice.Add(e)\n\t}\n\treturn slice\n}", "func slice1() {\n\tx := []float64{324234.23423, 232423.2342, 23423.2432, 23423.234, 23423.5556, 435634563.45634563456, 34564356.3456456}\n\n\t// this will check the type for the variable with \"%T\"\n\tfmt.Printf(\"%T \\n\", x)\n\n\t// this will start frm index value 2nd and show all the value prior to 4th place (excluding 4th place)\n\tfmt.Println(\"slicing the slice... by getting the values from index 2 to 4\", x[2:4])\n\n\t// printing the length of the slice, Slice is dynamic in memory allocation\n\tfmt.Println(len(x))\n\n}", "func (l *HandoffList) Slice() []*Handoff {\n\tvar slice []*Handoff\n\tif l == nil {\n\t\tslice = make([]*Handoff, 0)\n\t} else {\n\t\tslice = make([]*Handoff, len(l.items))\n\t\tcopy(slice, l.items)\n\t}\n\treturn slice\n}", "func (gd Grid) Slice(rg Range) Grid {\n\tif rg.Min.X < 0 {\n\t\trg.Min.X = 0\n\t}\n\tif rg.Min.Y < 0 {\n\t\trg.Min.Y = 0\n\t}\n\tmax := gd.Rg.Size()\n\tif rg.Max.X > max.X {\n\t\trg.Max.X = max.X\n\t}\n\tif rg.Max.Y > max.Y {\n\t\trg.Max.Y = max.Y\n\t}\n\tmin := gd.Rg.Min\n\trg.Min = rg.Min.Add(min)\n\trg.Max = rg.Max.Add(min)\n\treturn Grid{innerGrid{Ug: gd.Ug, Rg: rg}}\n}", "func (p *IntVector) Slice(i, j int) *IntVector {\n\treturn &IntVector{*p.Vector.Slice(i, j)}\n}", "func Get(size int) *[]byte { return slice.Bytes.Get(size).(*[]byte) }", "func (object MQObject) GetSlice(gomd *MQMD,\n\tgogmo *MQGMO, buffer []byte) ([]byte, int, error) {\n\trealDatalen, err := object.getInternal(gomd, gogmo, buffer, true)\n\n\t// The datalen will be set even if the buffer is too small - there\n\t// will be one of MQRC_TRUNCATED_MSG_ACCEPTED or _FAILED depending on the\n\t// GMO options. In any case, we return the available data along with the\n\t// error code but need to make sure that the real untruncated\n\t// message length is also returned. Also ensure we don't try to read past the\n\t// end of the buffer.\n\tdatalen := realDatalen\n\tif datalen > cap(buffer) {\n\t\tdatalen = cap(buffer)\n\t}\n\treturn buffer[0:datalen], realDatalen, err\n}", "func (s *SeriesIDSet) Slice() []uint64 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\ta := make([]uint64, 0, s.bitmap.GetCardinality())\n\tfor _, seriesID := range s.bitmap.ToArray() {\n\t\ta = append(a, uint64(seriesID))\n\t}\n\treturn a\n}" ]
[ "0.7117276", "0.70721287", "0.69470376", "0.67563283", "0.6729937", "0.66651917", "0.664598", "0.661597", "0.6594772", "0.65443593", "0.6540125", "0.6516164", "0.64883", "0.6446062", "0.6403788", "0.6391032", "0.63553524", "0.6261668", "0.6251471", "0.6234408", "0.6234408", "0.62244326", "0.6207633", "0.6205227", "0.6202907", "0.6202611", "0.6200996", "0.6157162", "0.6148346", "0.61482215", "0.6132905", "0.6131049", "0.6127529", "0.6110001", "0.61027825", "0.6094409", "0.6082389", "0.60753214", "0.60691524", "0.60607797", "0.6059792", "0.6051746", "0.6046922", "0.6044522", "0.6032682", "0.6026214", "0.6022514", "0.6021595", "0.60143834", "0.599286", "0.5989873", "0.597929", "0.5968567", "0.5965985", "0.59574276", "0.59568775", "0.5947753", "0.5934573", "0.5922286", "0.59178746", "0.5905413", "0.59022355", "0.5902209", "0.5896016", "0.58793306", "0.5870936", "0.58658683", "0.5830975", "0.5825933", "0.5816016", "0.58157754", "0.57814956", "0.57747865", "0.57581896", "0.57581896", "0.57581896", "0.57581896", "0.57581896", "0.5757422", "0.57495505", "0.574953", "0.5735519", "0.5732451", "0.57318014", "0.5731013", "0.5718405", "0.5717335", "0.5714641", "0.5690545", "0.5687047", "0.5685342", "0.5680232", "0.56751126", "0.56664777", "0.5664287", "0.56355", "0.5634562", "0.5624373", "0.56193435", "0.5615916", "0.56080747" ]
0.0
-1
Returns a new tuple with copy of n leftmost items
func (this *Tuple) Left(n int) *Tuple { return this.Slice(0, n) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *Tuple) Right(n int) *Tuple {\n\tlength := this.Len()\n\tn = max(0, length-n)\n\treturn this.Slice(n, length)\n}", "func shift(n pair, s []pair) (pair, []pair) {\n\tif len(s) == 0 {\n\t\treturn pair{}, append(s, n)\n\t}\n\tif len(s) == cap(s) {\n\t\treturn s[0], append(s[1:], n)\n\t}\n\treturn s[0], append(s, n)\n}", "func (this *Tuple) PopLeft() interface{} {\n\tif this.Len() < 1 {\n\t\treturn nil\n\t}\n\tret := this.data[0]\n\tthis.data = this.data[1:]\n\treturn ret\n}", "func (builder *Builder) Left(n uint) *Builder {\n\treturn builder.With(Left(n))\n}", "func CutTopN(h HitList, n uint) HitList {\n\n\tif len(h) <= int(n) {\n\t\treturn h\n\t}\n\n\tout := HitList{}\n\tfor i := 0; i < int(n); i++ {\n\t\tout[i] = h[i]\n\t}\n\n\treturn out\n}", "func (p *SliceOfMap) ShiftN(n int) (new ISlice) {\n\tif n == 0 {\n\t\treturn NewSliceOfMapV()\n\t}\n\tnew = p.Copy(0, abs(n)-1)\n\tp.DropFirstN(n)\n\treturn\n}", "func GetLeftIndex(n int) int {\n\treturn 2*n + 1\n}", "func (p *SliceOfMap) DropLastN(n int) ISlice {\n\tif n == 0 {\n\t\treturn p\n\t}\n\treturn p.Drop(absNeg(n), -1)\n}", "func (nl *nodeList) unshift(n *Node) {\n\tnl.insert(0, n)\n}", "func (c *Chain) PopPreviousNBlocks(n int) (*Chain, error) {\n\tc.mux.Lock()\n\tdefer c.mux.Unlock()\n\tc.LengthElements = len(c.Chain)\n\tl := c.LengthElements\n\tif c.Chain[l-1].NextBlock != nil || c.Chain[0].PrevBlock != nil {\n\t\treturn c, errors.New(\"Chain corrupted\")\n\t} else if l < n {\n\t\treturn c, errors.New(\"Deletion will cause underflow\")\n\t}\n\tc.Chain = c.Chain[:len(c.Chain)-n]\n\tc.Chain[l-n-1].NextBlock = nil\n\tc.LengthElements = l - n\n\tc.Size = unsafe.Sizeof(c)\n\treturn c, nil\n}", "func (snapshots EBSSnapshots) TrimHead(n int) EBSSnapshots {\n\tif n > len(snapshots) {\n\t\treturn EBSSnapshots{}\n\t}\n\treturn snapshots[n:]\n}", "func (p *Stack) PopNArgs(arity int) []interface{} {\n\n\tpstk := p.data\n\tn := len(pstk)\n\tif n >= arity {\n\t\targs := make([]interface{}, arity)\n\t\tn -= arity\n\t\tfor i := 0; i < arity; i++ {\n\t\t\targs[i] = pstk[n+i]\n\t\t}\n\t\tp.data = pstk[:n]\n\t\treturn args\n\t}\n\tpanic(\"unexpected argument count\")\n}", "func (p *SliceOfMap) DropFirstN(n int) ISlice {\n\tif n == 0 {\n\t\treturn p\n\t}\n\treturn p.Drop(0, abs(n)-1)\n}", "func (s *exprStack) popN(n int) []Expression {\n\ttrace_util_0.Count(_util_00000, 166)\n\tif n > s.len() || n < 0 {\n\t\ttrace_util_0.Count(_util_00000, 168)\n\t\tn = s.len()\n\t}\n\ttrace_util_0.Count(_util_00000, 167)\n\tidx := s.len() - n\n\texprs := s.stack[idx:]\n\ts.stack = s.stack[:idx]\n\treturn exprs\n}", "func CloneValTuple(n ValTuple) ValTuple {\n\tres := make(ValTuple, 0, len(n))\n\tfor _, x := range n {\n\t\tres = append(res, CloneExpr(x))\n\t}\n\treturn res\n}", "func (p *SliceOfMap) LastN(n int) ISlice {\n\tif n == 0 {\n\t\treturn NewSliceOfMapV()\n\t}\n\treturn p.Slice(absNeg(n), -1)\n}", "func NthRest(seq Seq, n uint) Seq {\n\treturn Drop(seq, n)\n}", "func (p *SliceOfMap) PopN(n int) (new ISlice) {\n\tif n == 0 {\n\t\treturn NewSliceOfMapV()\n\t}\n\tnew = p.Copy(absNeg(n), -1)\n\tp.DropLastN(n)\n\treturn\n}", "func (n Nodes) Slice() []*Node", "func onlyN(a []string, n int) []string {\n\tn = -n\n\tif n > 0 {\n\t\tif n > len(a) {\n\t\t\tn = len(a)\n\t\t}\n\t\ta = a[:n]\n\t} else {\n\t\tif -n > len(a) {\n\t\t\tn = -len(a)\n\t\t}\n\t\ta = a[len(a)+n:]\n\t}\n\treturn a\n}", "func (l List) GetTopElements(n int) []Item {\n\tvar temp []Item\n\tfor k, v := range l.Set {\n\t\ttemp = append(temp, Item{k, v})\n\t}\n\tsort.Slice(temp, func(i, j int) bool {\n\t\treturn temp[i].Weight > temp[j].Weight\n\t})\n\treturn temp[0:n]\n}", "func NewTuple(n int) *Tuple {\n\tt := &Tuple{}\n\tt.data = make([]interface{}, n)\n\treturn t\n}", "func (f fieldElement) leftShift(i uint) (result fieldElement) {\n\t// 0 <= i < 128\n\tif i < 64 {\n\t\tcopy(result[:], f[:])\n\t} else if i < 128 {\n\t\tresult[1] = f[0]\n\t\tresult[2] = f[1]\n\t\tresult[3] = f[2]\n\t\ti -= 64\n\t} else {\n\t\tpanic(\"leftShift argument out of range\")\n\t}\n\n\tresult[3] = result[3]<<i | result[2]>>(64-i)\n\tresult[2] = result[2]<<i | result[1]>>(64-i)\n\tresult[1] = result[1]<<i | result[0]>>(64-i)\n\tresult[0] = result[0] << i\n\n\treturn result\n}", "func DropRight[T any](collection []T, n int) []T {\n\tif len(collection) <= n {\n\t\treturn make([]T, 0)\n\t}\n\n\tresult := make([]T, len(collection)-n)\n\tfor i := len(collection) - 1 - n; i >= 0; i-- {\n\t\tresult[i] = collection[i]\n\t}\n\n\treturn result\n}", "func (p *Permutator) NextN(count int) interface{} { \n\tif count <= 0 || p.left() == 0 {\n\t\treturn reflect.MakeSlice(reflect.SliceOf(p.value.Type()), 0, 0).Interface()\n\t}\n \n cap := p.left()\n\tif cap > count {\n\t\tcap = count\n\t}\n\n result := reflect.MakeSlice(reflect.SliceOf(p.value.Type()), cap, cap)\n\n length := 0 \n for index := 0; index < cap; index++ { \n if _, ok := p.Next(); ok {\n length++\n list := p.copySliceValue()\n result.Index(index).Set(list)\n }\n }\n\n list := reflect.MakeSlice(result.Type(), length, length)\n reflect.Copy(list, result)\n \n return list.Interface()\n}", "func (this *Tuple) Get(n int) interface{} {\n\titem := this.data[this.Offset(n)]\n\treturn item\n}", "func SliceNTokens(b []byte, tok byte, n int) (s []byte, nLeft int) {\n\tfor i := range b {\n\t\tif b[i] == tok {\n\t\t\tn--\n\t\t\tif n == 0 { return b[:i+1], 0 }\n\t\t}\n\t}\n\n\treturn b, n\n}", "func (c *ChainPing) PopPreviousNBlocksPing(n int) (*ChainPing, error) {\n\tc.mux.Lock()\n\tdefer c.mux.Unlock()\n\tc.LengthElements = len(c.Chain)\n\tl := c.LengthElements\n\tif c.Chain[l-1].NextBlock != nil || c.Chain[0].PrevBlock != nil {\n\t\treturn c, errors.New(\"Chain corrupted\")\n\t} else if l < n {\n\t\treturn c, errors.New(\"Deletion will cause underflow\")\n\t}\n\tc.Chain = c.Chain[:len(c.Chain)-n]\n\tc.Chain[l-n-1].NextBlock = nil\n\tc.LengthElements = l - n\n\tc.Size = unsafe.Sizeof(c)\n\treturn c, nil\n}", "func (nl *nodeList) shift() *Node {\n\tif len(nl.elements) == 0 {\n\t\treturn nil\n\t}\n\n\t// This method of deletion is used instead of calling nl.Delete(), because it's faster.\n\tn := nl.elements[0]\n\tnl.elements[0] = nil\n\tnl.elements = nl.elements[1:]\n\treturn n\n}", "func Drop[T any](collection []T, n int) []T {\n\tif len(collection) <= n {\n\t\treturn make([]T, 0)\n\t}\n\n\tresult := make([]T, len(collection)-n)\n\tfor i := n; i < len(collection); i++ {\n\t\tresult[i-n] = collection[i]\n\t}\n\n\treturn result\n}", "func (l *list) Shift() {\n\tl.elements = l.elements[1:]\n}", "func (q *OperationQueue) Top(n int) []*SignedOperation {\n\tanswer := []*SignedOperation{}\n\tfor _, item := range q.set.Values() {\n\t\tanswer = append(answer, item.(*SignedOperation))\n\t\tif len(answer) == n {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn answer\n}", "func lvalTake(v *LVal, i int) *LVal {\n\tx := lvalPop(v, i)\n\treturn x\n}", "func (ts TrickSlice) Last(n int) TrickSlice {\n\tv := reflect.Value(ts)\n\tif n > v.Len() {\n\t\tn = v.Len()\n\t}\n\treturn TrickSlice(v.Slice3(v.Len()-n, v.Len(), v.Len()))\n}", "func (n *nodeHeader) leftTrimPrefix(l uint16) {\n\tif l < 1 {\n\t\treturn\n\t}\n\tpLen, pBytes := n.prefixFields()\n\tif l > *pLen {\n\t\tl = *pLen\n\t}\n\tnewLen := *pLen - uint16(l)\n\tcopy(pBytes[0:newLen], pBytes[l:*pLen])\n\t*pLen = newLen\n}", "func Top(items []Value, count int) []Value {\n\tif len(items) <= count || count == 0 {\n\t\treturn items\n\t}\n\tvalues := valueSlice(items)\n\tsort.Sort(values)\n\treturn values[len(values)-count:]\n}", "func (p *SliceOfMap) FirstN(n int) ISlice {\n\tif n == 0 {\n\t\treturn NewSliceOfMapV()\n\t}\n\treturn p.Slice(0, abs(n)-1)\n}", "func left(index int) int {\n\treturn 2*index + 1\n}", "func Shift(slice []interface{}) (interface{}, []interface{}) {\n\telm := slice[0]\n\tcpy := make([]interface{}, len(slice)-1)\n\tcopy(cpy, slice[1:])\n\treturn elm, cpy\n}", "func (ctx *Context) shift(n int) {\n\tbuf := ctx.buf[ctx.off : ctx.off+n]\n\tfor i := range buf {\n\t\tbuf[i] = 0\n\t}\n\tctx.off += n\n}", "func (a Args) SetLast(count int32) { a[2] = &count }", "func TakeStrPtr(n int, list []*string) []*string {\n\tif n < 0 {\n\t\treturn []*string{}\n\t}\n\n\tnewListLen := len(list)\n\n\tif n < newListLen {\n\t\tnewListLen = n\n\t}\n\tnewList := make([]*string, newListLen)\n\tfor i := 0; i < newListLen; i++ {\n\t\tnewList[i] = list[i]\n\t}\n\treturn newList\n}", "func (n *node) split(i int) (Item, *node) {\n\titem := n.items[i]\n\tnext := n.t.newNode()\n\tnext.items = append(next.items, n.items[i+1:]...)\n\tn.items = n.items[:i]\n\tif len(n.children) > 0 {\n\t\tnext.children = append(next.children, n.children[i+1:]...)\n\t\tn.children = n.children[:i+1]\n\t}\n\treturn item, next\n}", "func (a Slice[T]) Shift() (T, Slice[T]) {\n\tif len(a) == 0 {\n\t\treturn *new(T), a\n\t}\n\treturn a[0], a[1:]\n}", "func (a Args) from(i int) Args {\n\tif i >= len(a.All) {\n\t\ti = len(a.All) - 1\n\t}\n\ta.All = a.All[i+1:]\n\n\tif i >= len(a.Completed) {\n\t\ti = len(a.Completed) - 1\n\t}\n\ta.Completed = a.Completed[i+1:]\n\treturn a\n}", "func (t *Tuple) Negate() *Tuple {\n\treturn &Tuple{-t.x, -t.y, -t.z, -t.w}\n}", "func (r Result) KeepN(match ...int) Result {\n\tout := Result{die: r.die}\n\n\tfor _, d := range r.rolls {\n\t\tfor _, m := range match {\n\t\t\tif d.N == m {\n\t\t\t\tout.rolls = append(out.rolls, d)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn out\n}", "func (p Permutator) left() int {\n\treturn (p.amount - p.index) + 1\n}", "func DropTop[T any](ss []T, n int) (drop []T) {\n\tif n < 0 || n >= len(ss) {\n\t\treturn\n\t}\n\n\t// Copy ss, to make sure no memory is overlapping between input and\n\t// output. See issue #145.\n\tdrop = make([]T, len(ss)-n)\n\tcopy(drop, ss[n:])\n\n\treturn\n}", "func (a Slice[T]) Lasts(count int) Slice[T] {\n\treturn a[len(a)-count:]\n}", "func (r EventStorageAdapter) PopN(n int64) ([]api.RedisStoredEventDTO, error) {\n\n\ttoReturn := make([]api.RedisStoredEventDTO, 0)\n\n\telMutex.Lock()\n\tlrange := r.client.LRange(r.eventsListNamespace(), 0, n-1)\n\tif lrange.Err() != nil {\n\t\tlog.Error.Println(\"Fetching events\", lrange.Err().Error())\n\t\telMutex.Unlock()\n\t\treturn nil, lrange.Err()\n\t}\n\ttotalFetchedEvents := int64(len(lrange.Val()))\n\n\tidxFrom := n\n\tif totalFetchedEvents < n {\n\t\tidxFrom = totalFetchedEvents\n\t}\n\n\tres := r.client.LTrim(r.eventsListNamespace(), idxFrom, -1)\n\tif res.Err() != nil {\n\t\tlog.Error.Println(\"Trim events\", res.Err().Error())\n\t\telMutex.Unlock()\n\t\treturn nil, res.Err()\n\t}\n\telMutex.Unlock()\n\n\t//JSON unmarshal\n\tlistOfEvents := lrange.Val()\n\tfor _, se := range listOfEvents {\n\t\tstoredEventDTO := api.RedisStoredEventDTO{}\n\t\terr := json.Unmarshal([]byte(se), &storedEventDTO)\n\t\tif err != nil {\n\t\t\tlog.Error.Println(\"Error decoding event JSON\", err.Error())\n\t\t\tcontinue\n\t\t}\n\t\ttoReturn = append(toReturn, storedEventDTO)\n\t}\n\n\treturn toReturn, nil\n}", "func (this *Tuple) PopRight() interface{} {\n\tif this.Len() < 1 {\n\t\treturn nil\n\t}\n\tidx := this.Offset(-1)\n\tret := this.data[idx]\n\tthis.data = this.data[:idx]\n\treturn ret\n}", "func leftP(s []*Point) []*Point {\n\tvar r []*Point\n\tfor i := range s {\n\t\tif i&1 == 0 { // even\n\t\t\tr = append(r, s[i])\n\t\t}\n\t}\n\treturn r\n}", "func (root *TreeNode) topN(n int) (res []interface{}) {\n\tif root == nil {\n\t\treturn res\n\t}\n\n\tif root.right != nil {\n\t\ttmp := root.right.topN(n)\n\t\tfor _, k := range tmp {\n\t\t\tif len(res) == n {\n\t\t\t\treturn res\n\t\t\t}\n\n\t\t\tres = append(res, k)\n\t\t}\n\t}\n\n\tif len(res) < n {\n\t\tres = append(res, root.Values...)\n\t}\n\n\tif len(res) == n {\n\t\treturn res\n\t}\n\n\tif root.left != nil {\n\t\ttmp := root.left.topN(n - len(res))\n\t\tfor _, k := range tmp {\n\t\t\tif len(res) == n {\n\t\t\t\treturn res\n\t\t\t}\n\t\t\tres = append(res, k)\n\t\t}\n\t}\n\treturn res\n}", "func Take(seq Seq, n uint) Seq {\n\treturn SubSeq(seq, 0, n)\n}", "func (m Menu) Limit(n int) Menu {\n\tif len(m) > n {\n\t\treturn m[0:n]\n\t}\n\treturn m\n}", "func (s *stack) DupN(n int) error {\n\tfor n > 0 {\n\t\ts.stk = append(s.stk, s.stk[len(s.stk)-1])\n\t\tn--\n\t}\n\treturn nil\n}", "func split148(head *linkedlist.ListNode, n int) *linkedlist.ListNode {\n\tfor n-1 > 0 && head != nil {\n\t\tn--\n\t\thead = head.Next\n\t}\n\tvar restHead *linkedlist.ListNode\n\tif head != nil {\n\t\trestHead = head.Next\n\t\thead.Next = nil\n\t}\n\treturn restHead\n}", "func (s *SliceOfUint32) Shift() *SliceOfUint32 {\n\ts.items = s.items[1:]\n\treturn s\n}", "func lastRemaining(n int, m int) int {\n\ts := make([]int, n)\n\tfor i := 0; i < n; i++ {\n\t\ts[i] = i\n\t}\n\tresult := 0\n\tindex := 1\n\tpoint := 0 //指向数组\n\tfor {\n\t\tif len(s) == 1 {\n\t\t\tresult = s[0]\n\t\t\tbreak\n\t\t}\n\t\tif index == m {\n\t\t\ttemp := make([]int, point)\n\t\t\tcopy(temp, s[:point])\n\t\t\ts = append(temp, s[point+1:]...)\n\t\t\tindex = 1\n\t\t\tpoint--\n\t\t} else {\n\t\t\tindex++\n\t\t}\n\t\tif point + 1 >= len(s) {\n\t\t\tpoint = 0\n\t\t} else {\n\t\t\tpoint++\n\t\t}\n\t}\n\treturn result\n}", "func (ts TrickSlice) First(n int) TrickSlice {\n\tv := reflect.Value(ts)\n\tif n > v.Len() {\n\t\tn = v.Len()\n\t}\n\treturn TrickSlice(v.Slice3(0, n, n))\n}", "func (s *SliceOfUint) Shift() *SliceOfUint {\n\ts.items = s.items[1:]\n\treturn s\n}", "func TakeStr(n int, list []string) []string {\n\tif n < 0 {\n\t\treturn []string{}\n\t}\n\n\tnewListLen := len(list)\n\n\tif n < newListLen {\n\t\tnewListLen = n\n\t}\n\tnewList := make([]string, newListLen)\n\tfor i := 0; i < newListLen; i++ {\n\t\tnewList[i] = list[i]\n\t}\n\treturn newList\n}", "func Left(s string, n int) string {\n\tif n < 1 {\n\t\treturn \"\"\n\t}\n\trunes := []rune(s)\n\tif n >= len(runes) {\n\t\treturn s\n\t}\n\n\treturn string(runes[:n])\n\n}", "func removeN(head *node, n int) *node {\n\tret := head.next\n\n\tcur := head\n\tfor i := 0; i < n; i++ {\n\t\tcur = cur.next\n\t}\n\t// cur is now the last node we need to extract\n\thead.next = cur.next\n\tcur.next = ret\n\n\treturn ret\n}", "func PopAndTop(in []int) (top int, out []int) {\n\ttop = Top(in)\n\tout = Pop(in)\n\treturn\n}", "func (m *Model) SelectTopNAfterMe(n int) []string {\n\tm.pMutex.RLock()\n\tdefer m.pMutex.RUnlock()\n\n\tif len(m.peersList) == 1 {\n\t\treturn make([]string, 0, 0)\n\t}\n\t// remember who am I\n\tvar me string\n\t// create sort list\n\tpeers := make([]string, 0, len(m.peersList))\n\tfor address, isMe := range m.peersList {\n\t\tif isMe {\n\t\t\tme = address\n\t\t}\n\t\tpeers = append(peers, address)\n\t}\n\tsort.Strings(peers)\n\t// find me\n\tidx := sort.SearchStrings(peers, me)\n\t// select 10 after me, maybe less\n\tfSelection := make([]string, 1, Min(len(peers)-idx, n))\n\tfor i := 0; i < len(fSelection); i++ {\n\t\tfSelection[i] = peers[(i+idx+1)%len(peers)]\n\t}\n\treturn fSelection\n}", "func NewWeightedQuickUnion(n int) *wQuickUnion {\n\twqu := &wQuickUnion{}\n\twqu.id = make([]int, n)\n\twqu.sz = make([]int, n)\n\tfor i := 0; i < n; i++ {\n\t\twqu.id[i] = i\n\t\twqu.sz[i] = 1\n\t}\n\treturn wqu\n}", "func Nth(seq Seq, n uint) interface{} {\n\treturn First(NthRest(seq, n))\n}", "func split(n *mapNode, key interface{}, less func(a, b interface{}) bool, requireMid bool) (left, mid, right *mapNode) {\n\tif n == nil {\n\t\treturn nil, nil, nil\n\t}\n\n\tif less(n.key, key) {\n\t\tleft, mid, right := split(n.right, key, less, requireMid)\n\t\tif requireMid && mid == nil {\n\t\t\treturn nil, nil, nil\n\t\t}\n\t\tnewN := n.shallowCloneWithRef()\n\t\tnewN.left = n.left.incref()\n\t\tnewN.right = left\n\t\treturn newN, mid, right\n\t} else if less(key, n.key) {\n\t\tleft, mid, right := split(n.left, key, less, requireMid)\n\t\tif requireMid && mid == nil {\n\t\t\treturn nil, nil, nil\n\t\t}\n\t\tnewN := n.shallowCloneWithRef()\n\t\tnewN.left = right\n\t\tnewN.right = n.right.incref()\n\t\treturn left, mid, newN\n\t}\n\tmid = n.shallowCloneWithRef()\n\treturn n.left.incref(), mid, n.right.incref()\n}", "func right(x uint, n uint) uint {\n\tif level(x) == 0 {\n\t\treturn x\n\t}\n\n\tr := x ^ (0x03 << (level(x) - 1))\n\tfor r > 2*(n-1) {\n\t\tr = left(r)\n\t}\n\treturn r\n}", "func left(s []*big.Int) []*big.Int {\n\tvar r []*big.Int\n\tfor i := range s {\n\t\tif i&1 == 0 { // even\n\t\t\tr = append(r, s[i])\n\t\t}\n\t}\n\treturn r\n}", "func (n *nodeBlock) split(i int) (Metadata, *nodeBlock) {\n\titem := n.items[i]\n\tnext := n._super.newNode()\n\tnext.appendItems(n.items[i+1:]...)\n\tn.itemsSize = uint16(i)\n\tif n.childrenSize > 0 {\n\t\tnext.appendChildrenAndOffsets(n._children[i+1:], n.childrenOffset[i+1:])\n\t\tn.childrenSize = uint16(i + 1)\n\t}\n\tnext.markDirty()\n\tn.markDirty()\n\treturn item, next\n}", "func (c Counter) Top(n int, order string) CounterList {\n\tp := make(CounterList, len(c.Data))\n\ti := 0\n\tfor k, v := range c.Data {\n\t\tp[i] = CounterEntry{k, v}\n\t\ti++\n\t}\n\tswitch order {\n\tcase \"asc\":\n\t\tsort.Sort(p)\n\tcase \"desc\":\n\t\tsort.Sort(sort.Reverse(p))\n\tdefault:\n\t\tlog.Fatal(fmt.Sprintf(\n\t\t\t\"error: unrecognized order argument '%s'\", order))\n\t}\n\n\tif n > 0 && n < len(p) {\n\t\treturn p[:n]\n\t}\n\treturn p\n}", "func (*Null) NKeys() int { return 2 }", "func removeNthFromEndSlice(head *ListNode, n int) *ListNode {\n\tif head == nil || head.Next == nil {\n\t\treturn nil\n\t}\n\ts := []*ListNode{}\n\tfor {\n\t\ts = append(s, head)\n\t\thead = head.Next\n\t\tif head == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tx := len(s) - n\n\tif x > 0 {\n\t\ts[x-1].Next = s[x].Next\n\t\treturn s[0]\n\t}\n\treturn s[1]\n}", "func splitArgs(n int, args []string) ( /*positional*/ []string /*flags*/, []string) {\n\tif len(args) == 0 {\n\t\treturn nil, nil\n\t}\n\n\t// no positional, or user passed only flags (e.g. \"cmd -h\")\n\tif n == 0 || (args[0] != \"\" && args[0][0] == '-') {\n\t\treturn nil, args\n\t}\n\n\tif len(args) <= n {\n\t\treturn args, nil\n\t}\n\n\treturn args[:n], args[n:]\n}", "func (s *SliceOfUint32) Unshift(item uint32) *SliceOfUint32 {\n\ts.items = append([]uint32{item}, s.items...)\n\treturn s\n}", "func LeftSpan(index, depth uint) uint {\n\tif index&1 == 0 {\n\t\treturn index\n\t}\n\tif depth == 0 {\n\t\tdepth = Depth(index)\n\t}\n\n\treturn Offset(index, depth) * twoPow(depth+1)\n}", "func (td TupleDesc) WithoutFixedAccess() TupleDesc {\n\treturn TupleDesc{Types: td.Types, cmp: td.cmp}\n}", "func Fourth(seq Seq) interface{} {\n\treturn Nth(seq, 3)\n}", "func StrictPrepend(vs []Value, l Value) Value {\n\tfor i := len(vs) - 1; i >= 0; i-- {\n\t\tl = cons(vs[i], l)\n\t}\n\n\treturn l\n}", "func CloneTuple(t Tuple) Tuple {\n\tnewTuple := make(Tuple, len(t))\n\tfor i := range t {\n\t\tv := reflect.New(reflect.TypeOf(t[i]).Elem())\n\t\tv.Elem().Set(reflect.ValueOf(t[i]).Elem())\n\t\tnewTuple[i] = v.Interface()\n\t}\n\treturn newTuple\n}", "func removeNthFromEnd(head *ListNode, n int) *ListNode {\n\tdummyHead := ListNode{Next: head}\n\n\tvar length int\n\tfor cursor := &dummyHead; cursor.Next != nil; cursor = cursor.Next {\n\t\tlength++\n\t}\n\n\tif n <= 0 || n > length {\n\t\treturn dummyHead.Next\n\t}\n\n\tpreIdx := length - n\n\tpreNode := &dummyHead\n\tfor i := 0; i < preIdx; i++ {\n\t\tpreNode = preNode.Next\n\t}\n\n\tdelNode := preNode.Next\n\tpreNode.Next = delNode.Next\n\tdelNode.Next = nil // avoid memory leaks\n\n\treturn dummyHead.Next\n}", "func NewTupleFromItems(items ...interface{}) *Tuple {\n\tt := NewTuple(len(items))\n\tfor i, item := range items {\n\t\tt.Set(i, item)\n\t}\n\treturn t\n}", "func (this *BigInteger) ShiftLeft(n int64) *BigInteger {\n\tvar r *BigInteger = NewBigInteger()\n\tif n < 0 {\n\t\tthis.RShiftTo(-n, r)\n\t} else {\n\t\tthis.LShiftTo(n, r)\n\t}\n\treturn r\n}", "func (t Tuple9[A, B, C, D, E, F, G, H, I]) Unpack() (A, B, C, D, E, F, G, H, I) {\n\treturn t.A, t.B, t.C, t.D, t.E, t.F, t.G, t.H, t.I\n}", "func (t Tuple7[A, B, C, D, E, F, G]) Unpack() (A, B, C, D, E, F, G) {\n\treturn t.A, t.B, t.C, t.D, t.E, t.F, t.G\n}", "func (s *SliceOfInt) Unshift(item int) *SliceOfInt {\n\ts.items = append([]int{item}, s.items...)\n\treturn s\n}", "func (s Sequence) FirstN(n int) []interface{} {\n\tr := make([]interface{}, n)\n\tx := 0\n\ts.Find(func(el El)bool{\n\t\tr[x] = el\n\t\tx++\n\t\treturn x == n\n\t})\n\treturn r\n}", "func Head(n int, operand []string) []string {\n\tif len(operand) < n {\n\t\treturn operand\n\t}\n\treturn operand[:n]\n}", "func (x *Lazy) Take(n int, ar AnyValue) {\n\toar := reflect.ValueOf(ar)\n\tfor i := 0; i < n; i++ {\n\t\tif v, ok := x.omap[i]; ok {\n\t\t\toar.Index(i).Set(v)\n\t\t\tcontinue\n\t\t}\n\t\tvar v = []reflect.Value{x.iar.Index(i)}\n\t\tfor j := 0; j < len(x.fns); j++ {\n\t\t\tv = x.fns[j].Call(v)\n\t\t}\n\t\toar.Index(i).Set(v[0])\n\t\tx.omap[i] = oar.Index(i)\n\t}\n}", "func sliceTest03() {\n list := []int { 1, 0, 3, 4, 5 }\n l1 := list[0:2]\n l1[0], l1[1] = 0, 1\n fmt.Printf(\"Original: %d, %d\\nNew: %d, %d\\n\", list[0], list[1], l1[0], l1[1])\n}", "func (t *Text) IdentLeft(n int) *Text {\n\tif n < 0 {\n\t\treturn t\n\t}\n\tt.addMethod(func() {\n\t\tt.buffer.WriteString(strings.Repeat(\" \", n))\n\t})\n\treturn t\n}", "func LevelPop() {\n len := len(logLevelStack)\n logLevel, logLevelStack = logLevelStack[len-1], logLevelStack[:len-1] \n}", "func (board *Board) Left() *Board {\n\tblankPosition := board.PositionOfBlank()\n\tif blankPosition%board.Dimension == 0 {\n\t\treturn nil\n\t}\n\n\tclone := board.Clone()\n\tclone.move = LEFT\n\ttile := clone.GetTileAt(blankPosition - 1)\n\tclone.SetTileAt(blankPosition-1, BLANK)\n\tclone.SetTileAt(blankPosition, tile)\n\tclone.cost = clone.g + clone.Cost()\n\treturn clone\n}", "func (b *BHeap) left(i int) int {\n\treturn i<<1 + 1\n}", "func (s *SliceOfInt32) Unshift(item int32) *SliceOfInt32 {\n\ts.items = append([]int32{item}, s.items...)\n\treturn s\n}", "func removeNthFromEnd19(head *ListNode, n int) *ListNode {\n\tdummy := &ListNode{\n\t\tVal: 0,\n\t\tNext: head,\n\t}\n\tslow, fast := dummy, dummy\n\tfor i := 0; i < n; i++ {\n\t\tfast = fast.Next\n\t}\n\tfor fast.Next != nil {\n\t\tfast = fast.Next\n\t\tslow = slow.Next\n\t}\n\tnext := slow.Next.Next\n\tslow.Next = next\n\tslow.Next.Next = nil\n\treturn head\n}", "func (unpacker *BitUnpacker) Left() uint32 {\n\treturn unpacker.size - (unpacker.pbyte*8 + unpacker.pbit)\n}" ]
[ "0.5799978", "0.56568867", "0.55627984", "0.55599815", "0.54982084", "0.53724915", "0.52624273", "0.51948875", "0.5152906", "0.51211774", "0.5107011", "0.50483096", "0.5029621", "0.50194687", "0.49727842", "0.49342182", "0.49304894", "0.49280798", "0.4927612", "0.49073404", "0.48982662", "0.4898084", "0.48850778", "0.48492846", "0.48452806", "0.4776698", "0.4775429", "0.47679737", "0.4748407", "0.47401765", "0.47304672", "0.47231188", "0.47070572", "0.47059438", "0.46961492", "0.4647545", "0.46056175", "0.46046925", "0.46032676", "0.45967275", "0.45941472", "0.45897368", "0.45773375", "0.45682293", "0.45646253", "0.4553758", "0.45497644", "0.45369238", "0.4536344", "0.4534806", "0.45260763", "0.45251477", "0.45200303", "0.4518687", "0.45167845", "0.4515134", "0.45113295", "0.45104903", "0.4499468", "0.44979155", "0.449167", "0.448787", "0.44736883", "0.4470582", "0.44622633", "0.4459304", "0.444983", "0.444932", "0.44417867", "0.44367692", "0.4431653", "0.4427211", "0.44226342", "0.44202763", "0.4415002", "0.4402598", "0.44010934", "0.43990543", "0.43943176", "0.43942782", "0.4394156", "0.4391417", "0.43900898", "0.43892777", "0.43825012", "0.4379589", "0.43634576", "0.43573245", "0.43552092", "0.435252", "0.43479997", "0.43453634", "0.43446", "0.4332901", "0.43300384", "0.43238437", "0.43227652", "0.43195835", "0.43178532", "0.43096563" ]
0.702268
0
Returns a new tuple with copy of n rightmost items
func (this *Tuple) Right(n int) *Tuple { length := this.Len() n = max(0, length-n) return this.Slice(n, length) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *Tuple) Left(n int) *Tuple {\n\treturn this.Slice(0, n)\n}", "func shift(n pair, s []pair) (pair, []pair) {\n\tif len(s) == 0 {\n\t\treturn pair{}, append(s, n)\n\t}\n\tif len(s) == cap(s) {\n\t\treturn s[0], append(s[1:], n)\n\t}\n\treturn s[0], append(s, n)\n}", "func DropRight[T any](collection []T, n int) []T {\n\tif len(collection) <= n {\n\t\treturn make([]T, 0)\n\t}\n\n\tresult := make([]T, len(collection)-n)\n\tfor i := len(collection) - 1 - n; i >= 0; i-- {\n\t\tresult[i] = collection[i]\n\t}\n\n\treturn result\n}", "func CutTopN(h HitList, n uint) HitList {\n\n\tif len(h) <= int(n) {\n\t\treturn h\n\t}\n\n\tout := HitList{}\n\tfor i := 0; i < int(n); i++ {\n\t\tout[i] = h[i]\n\t}\n\n\treturn out\n}", "func (s *exprStack) popN(n int) []Expression {\n\ttrace_util_0.Count(_util_00000, 166)\n\tif n > s.len() || n < 0 {\n\t\ttrace_util_0.Count(_util_00000, 168)\n\t\tn = s.len()\n\t}\n\ttrace_util_0.Count(_util_00000, 167)\n\tidx := s.len() - n\n\texprs := s.stack[idx:]\n\ts.stack = s.stack[:idx]\n\treturn exprs\n}", "func (p *Permutator) NextN(count int) interface{} { \n\tif count <= 0 || p.left() == 0 {\n\t\treturn reflect.MakeSlice(reflect.SliceOf(p.value.Type()), 0, 0).Interface()\n\t}\n \n cap := p.left()\n\tif cap > count {\n\t\tcap = count\n\t}\n\n result := reflect.MakeSlice(reflect.SliceOf(p.value.Type()), cap, cap)\n\n length := 0 \n for index := 0; index < cap; index++ { \n if _, ok := p.Next(); ok {\n length++\n list := p.copySliceValue()\n result.Index(index).Set(list)\n }\n }\n\n list := reflect.MakeSlice(result.Type(), length, length)\n reflect.Copy(list, result)\n \n return list.Interface()\n}", "func CloneValTuple(n ValTuple) ValTuple {\n\tres := make(ValTuple, 0, len(n))\n\tfor _, x := range n {\n\t\tres = append(res, CloneExpr(x))\n\t}\n\treturn res\n}", "func (p *SliceOfMap) LastN(n int) ISlice {\n\tif n == 0 {\n\t\treturn NewSliceOfMapV()\n\t}\n\treturn p.Slice(absNeg(n), -1)\n}", "func NewTuple(n int) *Tuple {\n\tt := &Tuple{}\n\tt.data = make([]interface{}, n)\n\treturn t\n}", "func (p *SliceOfMap) DropLastN(n int) ISlice {\n\tif n == 0 {\n\t\treturn p\n\t}\n\treturn p.Drop(absNeg(n), -1)\n}", "func (p *Stack) PopNArgs(arity int) []interface{} {\n\n\tpstk := p.data\n\tn := len(pstk)\n\tif n >= arity {\n\t\targs := make([]interface{}, arity)\n\t\tn -= arity\n\t\tfor i := 0; i < arity; i++ {\n\t\t\targs[i] = pstk[n+i]\n\t\t}\n\t\tp.data = pstk[:n]\n\t\treturn args\n\t}\n\tpanic(\"unexpected argument count\")\n}", "func (this *Tuple) PopRight() interface{} {\n\tif this.Len() < 1 {\n\t\treturn nil\n\t}\n\tidx := this.Offset(-1)\n\tret := this.data[idx]\n\tthis.data = this.data[:idx]\n\treturn ret\n}", "func (p *SliceOfMap) ShiftN(n int) (new ISlice) {\n\tif n == 0 {\n\t\treturn NewSliceOfMapV()\n\t}\n\tnew = p.Copy(0, abs(n)-1)\n\tp.DropFirstN(n)\n\treturn\n}", "func NthRest(seq Seq, n uint) Seq {\n\treturn Drop(seq, n)\n}", "func right(x uint, n uint) uint {\n\tif level(x) == 0 {\n\t\treturn x\n\t}\n\n\tr := x ^ (0x03 << (level(x) - 1))\n\tfor r > 2*(n-1) {\n\t\tr = left(r)\n\t}\n\treturn r\n}", "func (ts TrickSlice) Last(n int) TrickSlice {\n\tv := reflect.Value(ts)\n\tif n > v.Len() {\n\t\tn = v.Len()\n\t}\n\treturn TrickSlice(v.Slice3(v.Len()-n, v.Len(), v.Len()))\n}", "func (this *Tuple) Get(n int) interface{} {\n\titem := this.data[this.Offset(n)]\n\treturn item\n}", "func (builder *Builder) Right(n uint) *Builder {\n\treturn builder.With(Right(n))\n}", "func Right(arr []int, n int) {\n\tmisc.Reverse(arr[n:])\n\tmisc.Reverse(arr[:n])\n\tmisc.Reverse(arr[:])\n}", "func (p *SliceOfMap) PopN(n int) (new ISlice) {\n\tif n == 0 {\n\t\treturn NewSliceOfMapV()\n\t}\n\tnew = p.Copy(absNeg(n), -1)\n\tp.DropLastN(n)\n\treturn\n}", "func Drop[T any](collection []T, n int) []T {\n\tif len(collection) <= n {\n\t\treturn make([]T, 0)\n\t}\n\n\tresult := make([]T, len(collection)-n)\n\tfor i := n; i < len(collection); i++ {\n\t\tresult[i-n] = collection[i]\n\t}\n\n\treturn result\n}", "func SliceNTokens(b []byte, tok byte, n int) (s []byte, nLeft int) {\n\tfor i := range b {\n\t\tif b[i] == tok {\n\t\t\tn--\n\t\t\tif n == 0 { return b[:i+1], 0 }\n\t\t}\n\t}\n\n\treturn b, n\n}", "func (l List) GetTopElements(n int) []Item {\n\tvar temp []Item\n\tfor k, v := range l.Set {\n\t\ttemp = append(temp, Item{k, v})\n\t}\n\tsort.Slice(temp, func(i, j int) bool {\n\t\treturn temp[i].Weight > temp[j].Weight\n\t})\n\treturn temp[0:n]\n}", "func (c *Chain) PopPreviousNBlocks(n int) (*Chain, error) {\n\tc.mux.Lock()\n\tdefer c.mux.Unlock()\n\tc.LengthElements = len(c.Chain)\n\tl := c.LengthElements\n\tif c.Chain[l-1].NextBlock != nil || c.Chain[0].PrevBlock != nil {\n\t\treturn c, errors.New(\"Chain corrupted\")\n\t} else if l < n {\n\t\treturn c, errors.New(\"Deletion will cause underflow\")\n\t}\n\tc.Chain = c.Chain[:len(c.Chain)-n]\n\tc.Chain[l-n-1].NextBlock = nil\n\tc.LengthElements = l - n\n\tc.Size = unsafe.Sizeof(c)\n\treturn c, nil\n}", "func TakeUint64(n int, list []uint64) []uint64 {\n\tif n < 0 {\n\t\treturn []uint64{}\n\t}\n\n\tnewListLen := len(list)\n\n\tif n < newListLen {\n\t\tnewListLen = n\n\t}\n\tnewList := make([]uint64, newListLen)\n\tfor i := 0; i < newListLen; i++ {\n\t\tnewList[i] = list[i]\n\t}\n\treturn newList\n}", "func (root *TreeNode) topN(n int) (res []interface{}) {\n\tif root == nil {\n\t\treturn res\n\t}\n\n\tif root.right != nil {\n\t\ttmp := root.right.topN(n)\n\t\tfor _, k := range tmp {\n\t\t\tif len(res) == n {\n\t\t\t\treturn res\n\t\t\t}\n\n\t\t\tres = append(res, k)\n\t\t}\n\t}\n\n\tif len(res) < n {\n\t\tres = append(res, root.Values...)\n\t}\n\n\tif len(res) == n {\n\t\treturn res\n\t}\n\n\tif root.left != nil {\n\t\ttmp := root.left.topN(n - len(res))\n\t\tfor _, k := range tmp {\n\t\t\tif len(res) == n {\n\t\t\t\treturn res\n\t\t\t}\n\t\t\tres = append(res, k)\n\t\t}\n\t}\n\treturn res\n}", "func (a Slice[T]) Lasts(count int) Slice[T] {\n\treturn a[len(a)-count:]\n}", "func Tail(n int, operand []string) []string {\n\tif len(operand) < n {\n\t\treturn operand\n\t}\n\treturn operand[len(operand)-n:]\n}", "func (a Args) SetLast(count int32) { a[2] = &count }", "func (t Tuple9[A, B, C, D, E, F, G, H, I]) Unpack() (A, B, C, D, E, F, G, H, I) {\n\treturn t.A, t.B, t.C, t.D, t.E, t.F, t.G, t.H, t.I\n}", "func (q *OperationQueue) Top(n int) []*SignedOperation {\n\tanswer := []*SignedOperation{}\n\tfor _, item := range q.set.Values() {\n\t\tanswer = append(answer, item.(*SignedOperation))\n\t\tif len(answer) == n {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn answer\n}", "func TakeStrPtr(n int, list []*string) []*string {\n\tif n < 0 {\n\t\treturn []*string{}\n\t}\n\n\tnewListLen := len(list)\n\n\tif n < newListLen {\n\t\tnewListLen = n\n\t}\n\tnewList := make([]*string, newListLen)\n\tfor i := 0; i < newListLen; i++ {\n\t\tnewList[i] = list[i]\n\t}\n\treturn newList\n}", "func (n Nodes) Slice() []*Node", "func (this *Tuple) PopLeft() interface{} {\n\tif this.Len() < 1 {\n\t\treturn nil\n\t}\n\tret := this.data[0]\n\tthis.data = this.data[1:]\n\treturn ret\n}", "func onlyN(a []string, n int) []string {\n\tn = -n\n\tif n > 0 {\n\t\tif n > len(a) {\n\t\t\tn = len(a)\n\t\t}\n\t\ta = a[:n]\n\t} else {\n\t\tif -n > len(a) {\n\t\t\tn = -len(a)\n\t\t}\n\t\ta = a[len(a)+n:]\n\t}\n\treturn a\n}", "func removeNthFromEndSlice(head *ListNode, n int) *ListNode {\n\tif head == nil || head.Next == nil {\n\t\treturn nil\n\t}\n\ts := []*ListNode{}\n\tfor {\n\t\ts = append(s, head)\n\t\thead = head.Next\n\t\tif head == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tx := len(s) - n\n\tif x > 0 {\n\t\ts[x-1].Next = s[x].Next\n\t\treturn s[0]\n\t}\n\treturn s[1]\n}", "func removeNthFromEnd(head *ListNode, n int) *ListNode {\n\tdummyHead := ListNode{Next: head}\n\n\tvar length int\n\tfor cursor := &dummyHead; cursor.Next != nil; cursor = cursor.Next {\n\t\tlength++\n\t}\n\n\tif n <= 0 || n > length {\n\t\treturn dummyHead.Next\n\t}\n\n\tpreIdx := length - n\n\tpreNode := &dummyHead\n\tfor i := 0; i < preIdx; i++ {\n\t\tpreNode = preNode.Next\n\t}\n\n\tdelNode := preNode.Next\n\tpreNode.Next = delNode.Next\n\tdelNode.Next = nil // avoid memory leaks\n\n\treturn dummyHead.Next\n}", "func (s *stack) DupN(n int) error {\n\tfor n > 0 {\n\t\ts.stk = append(s.stk, s.stk[len(s.stk)-1])\n\t\tn--\n\t}\n\treturn nil\n}", "func TakeUint64Ptr(n int, list []*uint64) []*uint64 {\n\tif n < 0 {\n\t\treturn []*uint64{}\n\t}\n\n\tnewListLen := len(list)\n\n\tif n < newListLen {\n\t\tnewListLen = n\n\t}\n\tnewList := make([]*uint64, newListLen)\n\tfor i := 0; i < newListLen; i++ {\n\t\tnewList[i] = list[i]\n\t}\n\treturn newList\n}", "func (nl *nodeList) unshift(n *Node) {\n\tnl.insert(0, n)\n}", "func (i *Index) GetNextN(n int) *Index {\n\tresult := &Index{\n\t\tFiles: map[string]Sourcefile{},\n\t}\n\n\tif len(i.Files) == 0 {\n\t\treturn result\n\t}\n\n\tfor f, src := range i.Files {\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tresult.Add(f, src)\n\t\tn--\n\t}\n\n\treturn result\n}", "func (r EventStorageAdapter) PopN(n int64) ([]api.RedisStoredEventDTO, error) {\n\n\ttoReturn := make([]api.RedisStoredEventDTO, 0)\n\n\telMutex.Lock()\n\tlrange := r.client.LRange(r.eventsListNamespace(), 0, n-1)\n\tif lrange.Err() != nil {\n\t\tlog.Error.Println(\"Fetching events\", lrange.Err().Error())\n\t\telMutex.Unlock()\n\t\treturn nil, lrange.Err()\n\t}\n\ttotalFetchedEvents := int64(len(lrange.Val()))\n\n\tidxFrom := n\n\tif totalFetchedEvents < n {\n\t\tidxFrom = totalFetchedEvents\n\t}\n\n\tres := r.client.LTrim(r.eventsListNamespace(), idxFrom, -1)\n\tif res.Err() != nil {\n\t\tlog.Error.Println(\"Trim events\", res.Err().Error())\n\t\telMutex.Unlock()\n\t\treturn nil, res.Err()\n\t}\n\telMutex.Unlock()\n\n\t//JSON unmarshal\n\tlistOfEvents := lrange.Val()\n\tfor _, se := range listOfEvents {\n\t\tstoredEventDTO := api.RedisStoredEventDTO{}\n\t\terr := json.Unmarshal([]byte(se), &storedEventDTO)\n\t\tif err != nil {\n\t\t\tlog.Error.Println(\"Error decoding event JSON\", err.Error())\n\t\t\tcontinue\n\t\t}\n\t\ttoReturn = append(toReturn, storedEventDTO)\n\t}\n\n\treturn toReturn, nil\n}", "func TakeStr(n int, list []string) []string {\n\tif n < 0 {\n\t\treturn []string{}\n\t}\n\n\tnewListLen := len(list)\n\n\tif n < newListLen {\n\t\tnewListLen = n\n\t}\n\tnewList := make([]string, newListLen)\n\tfor i := 0; i < newListLen; i++ {\n\t\tnewList[i] = list[i]\n\t}\n\treturn newList\n}", "func TakeRight(data interface{}, size int) (interface{}, error) {\n\tvar err error\n\n\tresult := func(err *error) interface{} {\n\t\tdefer catch(err)\n\n\t\tif !isNonNilData(err, \"data\", data) {\n\t\t\treturn nil\n\t\t}\n\n\t\tdataValue, dataType, _, dataValueLen := inspectData(data)\n\n\t\tif !isSlice(err, \"data\", dataValue) {\n\t\t\treturn nil\n\t\t}\n\n\t\tif !isZeroOrPositiveNumber(err, \"size\", size) {\n\t\t\treturn data\n\t\t}\n\n\t\tresult := makeSlice(dataType)\n\n\t\tif dataValueLen == 0 {\n\t\t\treturn result.Interface()\n\t\t}\n\n\t\tforEachSlice(dataValue, dataValueLen, func(each reflect.Value, i int) {\n\t\t\tif i >= (dataValueLen - size) {\n\t\t\t\tresult = reflect.Append(result, each)\n\t\t\t}\n\t\t})\n\n\t\treturn result.Interface()\n\t}(&err)\n\n\treturn result, err\n}", "func NewWeightedQuickUnion(n int) *wQuickUnion {\n\twqu := &wQuickUnion{}\n\twqu.id = make([]int, n)\n\twqu.sz = make([]int, n)\n\tfor i := 0; i < n; i++ {\n\t\twqu.id[i] = i\n\t\twqu.sz[i] = 1\n\t}\n\treturn wqu\n}", "func (r *ObjectsListingXact) nextN(n uint) (result []*cmn.BucketEntry, err error) {\n\tresult, err = r.peekN(n)\n\tr.discardN(uint(len(result)))\n\treturn result, err\n}", "func GetRightIndex(n int) int {\n\treturn 2*n + 2\n}", "func (tp *Tiles) TakeLast() *TilePlacement {\n\tlength := len(*tp)\n\tif length == 0 {\n\t\treturn nil\n\t}\n\n\tp := &(*tp)[length-1]\n\t*tp = (*tp)[:length-1]\n\treturn p\n}", "func Take(seq Seq, n uint) Seq {\n\treturn SubSeq(seq, 0, n)\n}", "func CloneValues(n Values) Values {\n\tres := make(Values, 0, len(n))\n\tfor _, x := range n {\n\t\tres = append(res, CloneValTuple(x))\n\t}\n\treturn res\n}", "func TakeUint(n int, list []uint) []uint {\n\tif n < 0 {\n\t\treturn []uint{}\n\t}\n\n\tnewListLen := len(list)\n\n\tif n < newListLen {\n\t\tnewListLen = n\n\t}\n\tnewList := make([]uint, newListLen)\n\tfor i := 0; i < newListLen; i++ {\n\t\tnewList[i] = list[i]\n\t}\n\treturn newList\n}", "func (n *node) split(i int) (Item, *node) {\n\titem := n.items[i]\n\tnext := n.t.newNode()\n\tnext.items = append(next.items, n.items[i+1:]...)\n\tn.items = n.items[:i]\n\tif len(n.children) > 0 {\n\t\tnext.children = append(next.children, n.children[i+1:]...)\n\t\tn.children = n.children[:i+1]\n\t}\n\treturn item, next\n}", "func CutRodBottomUpRecordResult(p []int, n int) (int, int) {\n\tc := []int{0} // cache\n\ts := make([]int, n+1) // list of first cut length for each starting length\n\n\tfor i := 1; i <= n; i++ {\n\t\tmaxResultForRodOfLengthI := 0\n\t\tfor j := 1; j <= i; j++ {\n\t\t\tmaxResultFromFollowingThisSubtree := p[j] + c[i-j]\n\t\t\tif maxResultFromFollowingThisSubtree > maxResultForRodOfLengthI {\n\t\t\t\tmaxResultForRodOfLengthI = maxResultFromFollowingThisSubtree\n\t\t\t\ts[i] = j\n\t\t\t}\n\t\t}\n\t\tc = append(c, maxResultForRodOfLengthI)\n\t}\n\treturn c[n], s[n]\n}", "func lvalTake(v *LVal, i int) *LVal {\n\tx := lvalPop(v, i)\n\treturn x\n}", "func removeNthFromEnd19(head *ListNode, n int) *ListNode {\n\tdummy := &ListNode{\n\t\tVal: 0,\n\t\tNext: head,\n\t}\n\tslow, fast := dummy, dummy\n\tfor i := 0; i < n; i++ {\n\t\tfast = fast.Next\n\t}\n\tfor fast.Next != nil {\n\t\tfast = fast.Next\n\t\tslow = slow.Next\n\t}\n\tnext := slow.Next.Next\n\tslow.Next = next\n\tslow.Next.Next = nil\n\treturn head\n}", "func (r Result) KeepN(match ...int) Result {\n\tout := Result{die: r.die}\n\n\tfor _, d := range r.rolls {\n\t\tfor _, m := range match {\n\t\t\tif d.N == m {\n\t\t\t\tout.rolls = append(out.rolls, d)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn out\n}", "func removeN(head *node, n int) *node {\n\tret := head.next\n\n\tcur := head\n\tfor i := 0; i < n; i++ {\n\t\tcur = cur.next\n\t}\n\t// cur is now the last node we need to extract\n\thead.next = cur.next\n\tcur.next = ret\n\n\treturn ret\n}", "func removeNthFromEnd(head *ListNode, n int) *ListNode {\n\ttemp := head\n\tlist := []*ListNode{}\n\tfor temp != nil {\n\t\tlist = append(list, temp)\n\t\ttemp = temp.Next\n\t}\n\tlength := len(list)\n\tthisOne := list[length - n]\n\tbeforeIdx := length - n - 1;\n\tif beforeIdx < 0 {\n\t\treturn thisOne.Next\n\t}\n\tlist[beforeIdx].Next = thisOne.Next\n\treturn head\n}", "func lastRemaining(n int, m int) int {\n\ts := make([]int, n)\n\tfor i := 0; i < n; i++ {\n\t\ts[i] = i\n\t}\n\tresult := 0\n\tindex := 1\n\tpoint := 0 //指向数组\n\tfor {\n\t\tif len(s) == 1 {\n\t\t\tresult = s[0]\n\t\t\tbreak\n\t\t}\n\t\tif index == m {\n\t\t\ttemp := make([]int, point)\n\t\t\tcopy(temp, s[:point])\n\t\t\ts = append(temp, s[point+1:]...)\n\t\t\tindex = 1\n\t\t\tpoint--\n\t\t} else {\n\t\t\tindex++\n\t\t}\n\t\tif point + 1 >= len(s) {\n\t\t\tpoint = 0\n\t\t} else {\n\t\t\tpoint++\n\t\t}\n\t}\n\treturn result\n}", "func (t Tuple7[A, B, C, D, E, F, G]) Unpack() (A, B, C, D, E, F, G) {\n\treturn t.A, t.B, t.C, t.D, t.E, t.F, t.G\n}", "func (this *Tuple) Reverse() {\n\tfor i, j := 0, this.Len()-1; i < j; i, j = i+1, j-1 {\n\t\tthis.data[i], this.data[j] = this.data[j], this.data[i]\n\t}\n}", "func Bottom(items []Value, count int) []Value {\n\tif len(items) <= count || count == 0 {\n\t\treturn items\n\t}\n\tvalues := valueSlice(items)\n\tsort.Sort(sort.Reverse(values))\n\treturn values[0:count]\n}", "func (card *Card) N() []*cell { return card.columns[N-1] }", "func CloneTuple(t Tuple) Tuple {\n\tnewTuple := make(Tuple, len(t))\n\tfor i := range t {\n\t\tv := reflect.New(reflect.TypeOf(t[i]).Elem())\n\t\tv.Elem().Set(reflect.ValueOf(t[i]).Elem())\n\t\tnewTuple[i] = v.Interface()\n\t}\n\treturn newTuple\n}", "func Top(items []Value, count int) []Value {\n\tif len(items) <= count || count == 0 {\n\t\treturn items\n\t}\n\tvalues := valueSlice(items)\n\tsort.Sort(values)\n\treturn values[len(values)-count:]\n}", "func Nth(seq Seq, n uint) interface{} {\n\treturn First(NthRest(seq, n))\n}", "func (r Result) DropN(match ...int) Result {\n\tout := Result{die: r.die}\n\n\tfor _, d := range r.rolls {\n\t\tisMatch := false\n\t\tfor _, m := range match {\n\t\t\tif d.N == m {\n\t\t\t\tisMatch = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !isMatch {\n\t\t\tout.rolls = append(out.rolls, d)\n\t\t}\n\t}\n\n\treturn out\n}", "func (p *SliceOfMap) DropFirstN(n int) ISlice {\n\tif n == 0 {\n\t\treturn p\n\t}\n\treturn p.Drop(0, abs(n)-1)\n}", "func TestNth(t *T) {\n\t// Normal case, in bounds\n\tintl := []interface{}{0, 2, 4, 6, 8}\n\tl := NewList(intl...)\n\tr, ok := l.Nth(3)\n\tassertSaneList(l, t)\n\tassertSeqContents(l, intl, t)\n\tassertValue(r, 6, t)\n\tassertValue(ok, true, t)\n\n\t// Normal case, out of bounds\n\tr, ok = l.Nth(8)\n\tassertSaneList(l, t)\n\tassertSeqContents(l, intl, t)\n\tassertValue(r, nil, t)\n\tassertValue(ok, false, t)\n\n\t// Degenerate case\n\tl = NewList()\n\tr, ok = l.Nth(0)\n\tassertEmpty(l, t)\n\tassertValue(r, nil, t)\n\tassertValue(ok, false, t)\n}", "func (t Tuple3[A, B, C]) Unpack() (A, B, C) {\n\treturn t.A, t.B, t.C\n}", "func right(index int) int {\n\treturn 2*index + 2\n}", "func (a Args) from(i int) Args {\n\tif i >= len(a.All) {\n\t\ti = len(a.All) - 1\n\t}\n\ta.All = a.All[i+1:]\n\n\tif i >= len(a.Completed) {\n\t\ti = len(a.Completed) - 1\n\t}\n\ta.Completed = a.Completed[i+1:]\n\treturn a\n}", "func (x *Lazy) Take(n int, ar AnyValue) {\n\toar := reflect.ValueOf(ar)\n\tfor i := 0; i < n; i++ {\n\t\tif v, ok := x.omap[i]; ok {\n\t\t\toar.Index(i).Set(v)\n\t\t\tcontinue\n\t\t}\n\t\tvar v = []reflect.Value{x.iar.Index(i)}\n\t\tfor j := 0; j < len(x.fns); j++ {\n\t\t\tv = x.fns[j].Call(v)\n\t\t}\n\t\toar.Index(i).Set(v[0])\n\t\tx.omap[i] = oar.Index(i)\n\t}\n}", "func (c *Cursor) Backward(n int) {\n\t(*c).Index -= n\n}", "func (n *nodeBlock) split(i int) (Metadata, *nodeBlock) {\n\titem := n.items[i]\n\tnext := n._super.newNode()\n\tnext.appendItems(n.items[i+1:]...)\n\tn.itemsSize = uint16(i)\n\tif n.childrenSize > 0 {\n\t\tnext.appendChildrenAndOffsets(n._children[i+1:], n.childrenOffset[i+1:])\n\t\tn.childrenSize = uint16(i + 1)\n\t}\n\tnext.markDirty()\n\tn.markDirty()\n\treturn item, next\n}", "func NewTupleFromItems(items ...interface{}) *Tuple {\n\tt := NewTuple(len(items))\n\tfor i, item := range items {\n\t\tt.Set(i, item)\n\t}\n\treturn t\n}", "func BackwardsN(typ DateRangeType, n int) []time.Time {\n\tend := time.Now()\n\treturn Backwards(typ, end, n)\n}", "func (b *BlockingForwardBox) EmitTuples(n int) {\n\tb.m.Lock()\n\tdefer b.m.Unlock()\n\tb.cnt += n\n\tb.c.Broadcast()\n}", "func (snapshots EBSSnapshots) TrimHead(n int) EBSSnapshots {\n\tif n > len(snapshots) {\n\t\treturn EBSSnapshots{}\n\t}\n\treturn snapshots[n:]\n}", "func (arr *ArrayList) Pop() ItemType {\n if arr.length > 0 {\n // shrink by half if only a third is used - dampening resize operations\n if arr.length < arr.capacity / 3 {\n arr.resize(arr.capacity / 2)\n }\n arr.length--\n return arr.data[arr.length]\n }\n panic(\"out of bounds\")\n}", "func (t Tuple6[A, B, C, D, E, F]) Unpack() (A, B, C, D, E, F) {\n\treturn t.A, t.B, t.C, t.D, t.E, t.F\n}", "func TestNth(t *T) {\n\t// Normal case, in bounds\n\tintl := []interface{}{0, 2, 4, 6, 8}\n\tl := NewList(intl...)\n\tr, ok := l.Nth(3)\n\tassertSaneList(l, t)\n\tassert.Equal(t, intl, ToSlice(l))\n\tassert.Equal(t, 6, r)\n\tassert.Equal(t, true, ok)\n\n\t// Normal case, out of bounds\n\tr, ok = l.Nth(8)\n\tassertSaneList(l, t)\n\tassert.Equal(t, intl, ToSlice(l))\n\tassert.Equal(t, nil, r)\n\tassert.Equal(t, false, ok)\n\n\t// Degenerate case\n\tl = NewList()\n\tr, ok = l.Nth(0)\n\tassert.Equal(t, 0, Size(l))\n\tassert.Equal(t, nil, r)\n\tassert.Equal(t, false, ok)\n}", "func (m Menu) Limit(n int) Menu {\n\tif len(m) > n {\n\t\treturn m[0:n]\n\t}\n\treturn m\n}", "func (t *Tree) TopN(n int) (res []interface{}) {\n\tif t == nil {\n\t\treturn\n\t}\n\n\tt.lock.RLock()\n\tdefer t.lock.RUnlock()\n\treturn t.root.topN(n)\n}", "func (b *BHeap) right(i int) int {\n\treturn i<<1 + 2\n}", "func (t Tuple5[A, B, C, D, E]) Unpack() (A, B, C, D, E) {\n\treturn t.A, t.B, t.C, t.D, t.E\n}", "func (ctx *Context) shift(n int) {\n\tbuf := ctx.buf[ctx.off : ctx.off+n]\n\tfor i := range buf {\n\t\tbuf[i] = 0\n\t}\n\tctx.off += n\n}", "func (builder *Builder) Left(n uint) *Builder {\n\treturn builder.With(Left(n))\n}", "func KthToLast(l *list.List, k int) []interface{} {\n\tc := l.Count() - k\n\tif c <= 0 {\n\t\treturn []interface{}{}\n\t}\n\n\tat := l.First()\n\tfor i := 0; i < k && at != nil; i++ {\n\t\tat = at.Next()\n\t}\n\n\tresult := make([]interface{}, 0, c)\n\tfor ; at != nil; at = at.Next() {\n\t\tresult = append(result, at.Value)\n\t}\n\treturn result\n}", "func (this *BigInteger) ShiftRight(n int64) *BigInteger {\n\tvar r *BigInteger = NewBigInteger()\n\tif n < 0 {\n\t\tthis.LShiftTo(-n, r)\n\t} else {\n\t\tthis.RShiftTo(n, r)\n\t}\n\treturn r\n}", "func (t Tuple8[A, B, C, D, E, F, G, H]) Unpack() (A, B, C, D, E, F, G, H) {\n\treturn t.A, t.B, t.C, t.D, t.E, t.F, t.G, t.H\n}", "func (s *SliceOfUint64) Unshift(item uint64) *SliceOfUint64 {\n\ts.items = append([]uint64{item}, s.items...)\n\treturn s\n}", "func TakeUintPtr(n int, list []*uint) []*uint {\n\tif n < 0 {\n\t\treturn []*uint{}\n\t}\n\n\tnewListLen := len(list)\n\n\tif n < newListLen {\n\t\tnewListLen = n\n\t}\n\tnewList := make([]*uint, newListLen)\n\tfor i := 0; i < newListLen; i++ {\n\t\tnewList[i] = list[i]\n\t}\n\treturn newList\n}", "func (s *SinglyLinkedList) RemoveNthFromEnd(n int) *Node {\n\tdummy := &Node{0, nil}\n\tdummy = s.Head\n\tfirst := dummy\n\tsecond := dummy\n\tfor i := 1; i <= n+1; i++ {\n\t\tfirst = first.Next\n\t}\n\n\tfor first != nil {\n\t\tfirst = first.Next\n\t\tsecond = second.Next\n\t}\n\tsecond.Next = second.Next.Next\n\treturn dummy.Next\n}", "func atMost(n int, parser lineParser) lineParser {\n\tf := func(ctx *parseContext, cmd string, args []string) (node, error) {\n\n\t\tcmdNode, err := parser(ctx, cmd, args)\n\t\tif err == nil {\n\t\t\tcount := 0\n\t\t\tfor _, previousNode := range ctx.nodes {\n\t\t\t\tif previousNode.cmd == cmd {\n\t\t\t\t\tcount += 1\n\t\t\t\t\tif count >= n {\n\t\t\t\t\t\tctx.addErrorf(\"line %d: extra %s: %s\", ctx.lineNum, cmd, ctx.line)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn cmdNode, err\n\t}\n\treturn f\n}", "func PopUint64(slice []uint64) (uint64, []uint64) {\n\treturn slice[0], slice[1:]\n}", "func LastRemaining2(n, m int) (int, bool) {\n\tif n < 1 || m < 1 || n < m {\n\t\treturn 0, false\n\t}\n\n\tnumRing := ring.New(n)\n\tfor i := 0; i < n; i++ {\n\t\tnumRing.Value = i\n\t\tnumRing = numRing.Next()\n\t}\n\n\tfor numRing.Len() > 1 {\n\t\tfor i := 1; i < m-1; i++ {\n\t\t\tnumRing = numRing.Next()\n\t\t}\n\n\t\tnumRing.Unlink(1)\n\t\tnumRing = numRing.Next()\n\t}\n\treturn numRing.Value.(int), true\n}", "func DropTop[T any](ss []T, n int) (drop []T) {\n\tif n < 0 || n >= len(ss) {\n\t\treturn\n\t}\n\n\t// Copy ss, to make sure no memory is overlapping between input and\n\t// output. See issue #145.\n\tdrop = make([]T, len(ss)-n)\n\tcopy(drop, ss[n:])\n\n\treturn\n}", "func Pop[T any](h Interface[T]) T {\n\tn := h.Len() - 1\n\th.Swap(0, n)\n\tdown(h, 0, n)\n\treturn h.Pop()\n}", "func (t *Tuple) Sub(o *Tuple) *Tuple {\n\treturn &Tuple{\n\t\tt.x - o.x,\n\t\tt.y - o.y,\n\t\tt.z - o.z,\n\t\tt.w - o.w,\n\t}\n\n}" ]
[ "0.58376974", "0.5726538", "0.5519268", "0.5385514", "0.5381859", "0.5310312", "0.529799", "0.52790415", "0.5270423", "0.52695614", "0.526774", "0.5189787", "0.5161007", "0.51163256", "0.51103437", "0.5089906", "0.50748026", "0.5026603", "0.5006796", "0.49989578", "0.4968389", "0.49028474", "0.48574364", "0.48186618", "0.4816549", "0.48010832", "0.47774768", "0.4770702", "0.47668785", "0.47499427", "0.4733285", "0.47259533", "0.47244117", "0.46960062", "0.46938005", "0.46843693", "0.46777362", "0.46699157", "0.4664575", "0.46580815", "0.46574745", "0.46559638", "0.46557614", "0.4655035", "0.46426916", "0.46404085", "0.46392015", "0.4635334", "0.46313837", "0.46307883", "0.4630052", "0.46159312", "0.46063927", "0.4603589", "0.46020383", "0.45978755", "0.45896366", "0.45827222", "0.45729214", "0.45712993", "0.45677403", "0.45671576", "0.4565911", "0.45658746", "0.45533183", "0.4540557", "0.45287552", "0.4528364", "0.45128945", "0.45014375", "0.44965547", "0.4494881", "0.4482359", "0.44789284", "0.4469766", "0.44693655", "0.44689974", "0.44585478", "0.44545245", "0.4449669", "0.4440451", "0.44371015", "0.44340843", "0.44335234", "0.4423323", "0.44213262", "0.4416954", "0.441346", "0.44111606", "0.4407643", "0.44073328", "0.44067508", "0.43990555", "0.43989304", "0.43955052", "0.43947178", "0.43933204", "0.43808454", "0.43718305", "0.43677145" ]
0.6711538
0
Returns a new tuple with slice of this tuple's data
func (this *Tuple) Slice(start int, end int) *Tuple { c := this.Copy() max := this.Len() start = min(c.Offset(start), max) end = min(c.Offset(end), max) c.data = c.data[start:end] return c }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *Tuple) Copy() *Tuple {\n\tt := NewTuple(this.Len())\n\tcopy(t.data, this.data)\n\treturn t\n}", "func NewTupleFromSlice(slice []interface{}) *Tuple {\n\tt := &Tuple{}\n\tt.data = slice\n\treturn t\n}", "func (t *Tuple) Sub(o *Tuple) *Tuple {\n\treturn &Tuple{\n\t\tt.x - o.x,\n\t\tt.y - o.y,\n\t\tt.z - o.z,\n\t\tt.w - o.w,\n\t}\n\n}", "func (s PointBuffer) SubSlice(low int, high int) PointBuffer {\n\tinBounds := low >= 0 && low <= high && high <= s.cap\n\tif !inBounds {\n\t\tpanic(fmt.Errorf(\n\t\t\t\"runtime error: slice bounds out of range [%d:%d] with capacity %d\",\n\t\t\tlow, high, s.cap,\n\t\t))\n\t}\n\tvar tVar Point\n\ttSize := unsafe.Sizeof(tVar)\n\ttype internalPtr struct {\n\t\toffset uintptr\n\t\tbucketIdx uint8\n\t\tarenaMask uint16\n\t}\n\tcurrentPtr := *(*internalPtr)(unsafe.Pointer(&s.data))\n\tnewPtr := internalPtr{\n\t\toffset: currentPtr.offset + uintptr(low*int(tSize)),\n\t\tbucketIdx: currentPtr.bucketIdx,\n\t\tarenaMask: currentPtr.arenaMask,\n\t}\n\treturn PointBuffer{\n\t\tdata: *(*arena.Ptr)(unsafe.Pointer(&newPtr)),\n\t\tlen: high - low,\n\t\tcap: s.cap - low,\n\t}\n}", "func (this *Tuple) Get(n int) interface{} {\n\titem := this.data[this.Offset(n)]\n\treturn item\n}", "func (this *Tuple) Data() []interface{} {\n\treturn this.data\n}", "func (this *Tuple) Left(n int) *Tuple {\n\treturn this.Slice(0, n)\n}", "func (items IntSlice) SubSlice(i, j int) Interface { return items[i:j] }", "func CloneTuple(t Tuple) Tuple {\n\tnewTuple := make(Tuple, len(t))\n\tfor i := range t {\n\t\tv := reflect.New(reflect.TypeOf(t[i]).Elem())\n\t\tv.Elem().Set(reflect.ValueOf(t[i]).Elem())\n\t\tnewTuple[i] = v.Interface()\n\t}\n\treturn newTuple\n}", "func Sub(el ...tuple.TupleElement) Subspace {\n\treturn subspace{tuple.Tuple(el).Pack()}\n}", "func Slice(t *Tensor) interface{} {\n\tlength := int(DimProduct(t.Dims))\n\tsliceHeader := reflect.SliceHeader{\n\t\tData: uintptr(unsafe.Pointer(&t.Buffer[0])),\n\t\tCap: length,\n\t\tLen: length,\n\t}\n\tval := reflect.NewAt(DtypeToSliceType[t.Dtype], unsafe.Pointer(&sliceHeader)).Elem()\n\treturn val.Interface()\n}", "func (self *T) Slice() []float64 {\n\treturn []float64{self[0], self[1]}\n}", "func NewTuple(n int) *Tuple {\n\tt := &Tuple{}\n\tt.data = make([]interface{}, n)\n\treturn t\n}", "func (iobuf *buf) slice(free, base, bound uint) *Slice {\n\tatomic.AddInt32(&iobuf.refcount, 1)\n\treturn &Slice{iobuf: iobuf, free: free, base: base, Contents: iobuf.Contents[base:bound]}\n}", "func (this *Tuple) Right(n int) *Tuple {\n\tlength := this.Len()\n\tn = max(0, length-n)\n\treturn this.Slice(n, length)\n}", "func (t Tuple) Sub(o Tuple) Tuple {\n\tif t.IsVector() && o.IsPoint() {\n\t\tpanic(\"cannot subtract point from vector\")\n\t}\n\treturn Tuple{t.X - o.X, t.Y - o.Y, t.Z - o.Z, t.W - o.W}\n}", "func (s SampleList) Slice(start, end int) anysgd.SampleList {\n\treturn append(SampleList{}, s[start:end]...)\n}", "func Slice(d Dense, start, end int) (Dense, error) {\n\tif end-start > d.len {\n\t\treturn Dense{}, fmt.Errorf(\"slicing bitmap of len %d up to %d\", d.len, end-start)\n\t}\n\tif start < 0 {\n\t\treturn Dense{}, fmt.Errorf(\"slicing bitmap with negative start: %d\", start)\n\t}\n\tif end < start {\n\t\treturn Dense{}, fmt.Errorf(\"slicing bitmap to negative length: %d\", end-start)\n\t}\n\n\tr := Dense{}\n\tfor ; start%byteSize != 0; start++ {\n\t\tr.AppendBit(d.Get(start))\n\t}\n\tj := start / byteSize\n\ttmp := NewDense(d.bits[j:j+BytesFor(end-start)], end-start)\n\tr.Append(tmp)\n\treturn r, nil\n}", "func (e *ObservableEditableBuffer) ByteTuple(q int) OffsetTuple {\n\treturn e.f.ByteTuple(q)\n}", "func (self *T) Slice() []float32 {\n\treturn []float32{\n\t\tself[0][0], self[0][1],\n\t\tself[1][0], self[1][1],\n\t}\n}", "func (b *Slice) Sub(top, bot int) *Slice {\n\tif top < 0 || bot < top {\n\t\treturn nil\n\t}\n\treturn &Slice{\n\t\tbuffer: b.buffer,\n\t\ttop: b.top + top,\n\t\tbot: b.top + bot,\n\t\tcap: b.cap,\n\t}\n}", "func (items Float64Slice) SubSlice(i, j int) Interface { return items[i:j] }", "func (t *Dense) Slice(slices ...Slice) (retVal Tensor, err error) {\n\tvar newAP *AP\n\tvar ndStart, ndEnd int\n\n\tif newAP, ndStart, ndEnd, err = t.AP.S(t.len(), slices...); err != nil {\n\t\treturn\n\t}\n\n\tview := new(Dense)\n\tview.t = t.t\n\tview.viewOf = t\n\tview.AP = newAP\n\tview.hdr = new(reflect.SliceHeader)\n\tview.data = t.data\n\tview.hdr.Data = t.hdr.Data\n\tview.hdr.Len = t.hdr.Len\n\tview.hdr.Cap = t.hdr.Cap\n\tview.slice(ndStart, ndEnd)\n\n\tif t.IsMasked() {\n\t\tview.mask = t.mask[ndStart:ndEnd]\n\t}\n\treturn view, err\n}", "func (f *Fields) Slice() []*Field", "func (s *VectorImplSlice) Slice(start, stop int) *VectorImplSlice {\n\tassertSliceOk(start, stop, s.stop-s.start)\n\treturn &VectorImplSlice{vector: s.vector, start: s.start + start, stop: s.start + stop}\n}", "func (this *Tuple) Append(other *Tuple) {\n\tthis.AppendItems(other.data...)\n}", "func (l *list) Slice(first int, last int) interface{} {\n\ttypeOf := reflect.TypeOf(l.t)\n\tsliceOf := reflect.SliceOf(typeOf)\n\tvar result = reflect.ValueOf(reflect.New(sliceOf).Interface()).Elem()\n\n\tfor _, v := range l.elements[first:last] {\n\t\tresult.Set(reflect.Append(result, reflect.ValueOf(v)))\n\t}\n\n\treturn result.Interface()\n}", "func Slice(s Stream, start int, end int) Stream {\n return &sliceStream{Stream: s, start: start, end: end}\n}", "func (b *Blob) Slice(start, end int, contenttype string) *Blob {\n\tnewBlobObject := b.Call(\"slice\", start, end, contenttype)\n\treturn &Blob{\n\t\tObject: newBlobObject,\n\t}\n}", "func (ss HHMSecondary) Slice(start, end int) HHMSecondary {\n\tvar ssdssp, sadssp, sspred, ssconf, ssconsensus *seq.Sequence\n\n\tif ss.SSdssp != nil {\n\t\tt := ss.SSdssp.Slice(start, end)\n\t\tssdssp = &t\n\t}\n\tif ss.SAdssp != nil {\n\t\tt := ss.SAdssp.Slice(start, end)\n\t\tsadssp = &t\n\t}\n\tif ss.SSpred != nil {\n\t\tt := ss.SSpred.Slice(start, end)\n\t\tsspred = &t\n\t}\n\tif ss.SSconf != nil {\n\t\tt := ss.SSconf.Slice(start, end)\n\t\tssconf = &t\n\t}\n\tif ss.Consensus != nil {\n\t\tt := ss.Consensus.Slice(start, end)\n\t\tssconsensus = &t\n\t}\n\treturn HHMSecondary{\n\t\tSSdssp: ssdssp,\n\t\tSAdssp: sadssp,\n\t\tSSpred: sspred,\n\t\tSSconf: ssconf,\n\t\tConsensus: ssconsensus,\n\t}\n}", "func (b *Buffer) Slice() []byte {\n\t// Skip IP and UDP headers\n\treturn b[(ipv4HeaderSize + udp4HeaderSize):]\n}", "func (v *VectorImpl) Slice(start, stop int) *VectorImplSlice {\n\tassertSliceOk(start, stop, v.Len())\n\treturn &VectorImplSlice{vector: v, start: start, stop: stop}\n}", "func (s *f64) Slice(start, end int) Floating {\n\tstart = s.BufferIndex(0, start)\n\tend = s.BufferIndex(0, end)\n\treturn &f64{\n\t\tchannels: s.channels,\n\t\tbuffer: s.buffer[start:end],\n\t}\n}", "func (vp *baseVectorParty) Slice(startRow, numRows int) common.SlicedVector {\n\tsize := vp.length - startRow\n\tif size < 0 {\n\t\tsize = 0\n\t}\n\tif size > numRows {\n\t\tsize = numRows\n\t}\n\tvector := common.SlicedVector{\n\t\tValues: make([]interface{}, size),\n\t\tCounts: make([]int, size),\n\t}\n\tfor i := 0; i < size; i++ {\n\t\tvector.Values[i] = vp.getDataValueFn(startRow + i).ConvertToHumanReadable(vp.dataType)\n\t\tvector.Counts[i] = i + 1\n\t}\n\n\treturn vector\n}", "func (n Nodes) Slice() []*Node", "func Slice(seq Sequence, start, end int) Sequence {\n\tseqlen := Len(seq)\n\tif start < 0 {\n\t\tstart += seqlen\n\t}\n\n\tif end < 0 {\n\t\tend += seqlen\n\t}\n\n\tif end < start {\n\t\tlength := seqlen - start + end\n\t\tseq = Rotate(seq, -start)\n\t\treturn Slice(seq, 0, length)\n\t}\n\n\tinfo := seq.Info()\n\tinfo = trySlice(info, start, end)\n\n\tff := seq.Features().Filter(Overlap(start, end))\n\n\tfor i, f := range ff {\n\t\tloc := f.Loc.Expand(end, end-seqlen).Expand(0, -start)\n\t\tif f.Key == \"source\" {\n\t\t\tloc = asComplete(loc)\n\t\t}\n\t\tff[i].Loc = loc\n\t}\n\n\tp := make([]byte, end-start)\n\tcopy(p, seq.Bytes()[start:end])\n\n\tseq = WithInfo(seq, info)\n\tseq = WithFeatures(seq, ff)\n\tseq = WithBytes(seq, p)\n\tseq = WithTopology(seq, Linear)\n\n\treturn seq\n}", "func (t *TupleType) Builder(buffer []byte) TupleBuilder {\n\treturn NewBuilder(*t, buffer)\n}", "func (a Slice[T]) Pop() (Slice[T], T) {\n\treturn a[:len(a)-1], a[len(a)-1]\n}", "func (in *InBuffer) Slice(n int) []byte {\n\tr := in.Data[in.ReadPos : in.ReadPos+n]\n\tin.ReadPos += n\n\treturn r\n}", "func (in *InBuffer) Slice(n int) []byte {\n\tr := in.Data[in.ReadPos : in.ReadPos+n]\n\tin.ReadPos += n\n\treturn r\n}", "func (this *Tuple) Set(n int, item interface{}) {\n\tthis.data[this.Offset(n)] = item\n}", "func SelectFeatures(tuples []base.Tuple, features []int) []base.Tuple {\n if (len(features) <= 0) {\n return tuples;\n }\n\n var tupleType reflect.Type = reflect.TypeOf(tuples[0]);\n\n var rtn []base.Tuple = make([]base.Tuple, len(tuples));\n for tupleIndex, tuple := range(tuples) {\n var data []interface{} = make([]interface{}, len(features));\n for featurePosition, featureIndex := range(features) {\n data[featurePosition] = tuple.GetData(featureIndex);\n }\n\n rtn[tupleIndex] = base.NewTypedTuple(tupleType, data, tuple.GetClass());\n }\n\n return rtn;\n}", "func (ms *MySlice) Clone() Data {\n\tscopy := make([]int, len(ms.Slice))\n\tcopy(scopy, ms.Slice)\n\tmyslice := new(MySlice)\n\tmyslice.Slice = scopy\n\treturn Data(myslice)\n}", "func (s *slice) slice(start, stop int, elemsize uintptr) slice {\n\tif start >= s.cap_ || start < 0 || stop > s.cap_ || stop < 0 {\n\t\tpanic(\"cuda4/safe: slice index out of bounds\")\n\t}\n\tif start > stop {\n\t\tpanic(\"cuda4/safe: inverted slice range\")\n\t}\n\treturn slice{cu.DevicePtr(uintptr(s.ptr_) + uintptr(start)*elemsize), stop - start, s.cap_ - start}\n}", "func makeslice(len_ int, elemsize int) slice {\n\tbytes := int64(len_) * int64(elemsize)\n\ts := slice{0, len_, len_}\n\tif bytes > 0 {\n\t\ts.ptr_ = cu.MemAlloc(bytes)\n\t\tcu.MemsetD8(s.ptr_, 0, bytes)\n\t\tcu.CtxSynchronize()\n\t}\n\treturn s\n}", "func (this *Tuple) PopLeft() interface{} {\n\tif this.Len() < 1 {\n\t\treturn nil\n\t}\n\tret := this.data[0]\n\tthis.data = this.data[1:]\n\treturn ret\n}", "func Slice[T any](ptr *T, length int) []T {\n\treturn unsafe.Slice(ptr, length)\n}", "func Shift(slice []interface{}) (interface{}, []interface{}) {\n\telm := slice[0]\n\tcpy := make([]interface{}, len(slice)-1)\n\tcopy(cpy, slice[1:])\n\treturn elm, cpy\n}", "func (p *IntVector) Slice(i, j int) *IntVector {\n\treturn &IntVector{*p.Vector.Slice(i, j)}\n}", "func (t Tuple9[A, B, C, D, E, F, G, H, I]) Unpack() (A, B, C, D, E, F, G, H, I) {\n\treturn t.A, t.B, t.C, t.D, t.E, t.F, t.G, t.H, t.I\n}", "func (s *internalPointBufferView) Make(len int) (PointBuffer, error) {\n\tsliceHdr, allocErr := s.state.makeSlice(len)\n\tif allocErr != nil {\n\t\treturn PointBuffer{}, allocErr\n\t}\n\treturn sliceHdr, nil\n}", "func (a myArray) splice(start int, data ...string) myArray {\n\tcopy(a[start:], data)\n\treturn a\n}", "func (id GID) slice(start, end int) []byte {\n\tif len(id) != 12 {\n\t\tpanic(fmt.Sprintf(\"Invalid GID: %q\", string(id)))\n\t}\n\n\treturn id[start:end]\n}", "func (seq *Sequence) Slice() (s []interface{}) {\n\ts = make([]interface{}, len(seq.Nodes))\n\tfor i, n := range seq.Nodes {\n\t\ts[i] = n.Data()\n\t}\n\treturn\n}", "func (p *parser) sliceFrom(start savepoint) []byte {\n\treturn p.data[start.position.offset:p.pt.position.offset]\n}", "func (p *parser) sliceFrom(start savepoint) []byte {\n\treturn p.data[start.position.offset:p.pt.position.offset]\n}", "func (p *parser) sliceFrom(start savepoint) []byte {\n\treturn p.data[start.position.offset:p.pt.position.offset]\n}", "func (p *parser) sliceFrom(start savepoint) []byte {\n\treturn p.data[start.position.offset:p.pt.position.offset]\n}", "func (p *parser) sliceFrom(start savepoint) []byte {\n\treturn p.data[start.position.offset:p.pt.position.offset]\n}", "func (t Tuple8[A, B, C, D, E, F, G, H]) Unpack() (A, B, C, D, E, F, G, H) {\n\treturn t.A, t.B, t.C, t.D, t.E, t.F, t.G, t.H\n}", "func (fr *frame) makeSlice(sliceType types.Type, length, capacity *govalue) *govalue {\n\tlength = fr.convert(length, types.Typ[types.Uintptr])\n\tcapacity = fr.convert(capacity, types.Typ[types.Uintptr])\n\truntimeType := fr.types.ToRuntime(sliceType)\n\tllslice := fr.runtime.makeSlice.call(fr, runtimeType, length.value, capacity.value)\n\treturn newValue(llslice[0], sliceType)\n}", "func (this *Tuple) Insert(start int, other *Tuple) {\n\tthis.InsertItems(start, other.data...)\n}", "func (ns Nodes) Slice(pos ...int) Nodes {\n\tplen := len(pos)\n\tl := len(ns)\n\tif plen == 1 && pos[0] < l-1 && pos[0] > 0 {\n\t\treturn ns[pos[0]:]\n\t} else if len(pos) == 2 && pos[0] < l-1 && pos[1] < l-1 && pos[0] > 0 && pos[1] > 0 {\n\t\treturn ns[pos[0]:pos[1]]\n\t}\n\treturn Nodes{}\n}", "func (this *Iter_UServ_GetFriends) Slice() []*Row_UServ_GetFriends {\n\tvar results []*Row_UServ_GetFriends\n\tfor {\n\t\tif i, ok := this.Next(); ok {\n\t\t\tresults = append(results, i)\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn results\n}", "func (s *internalPointBufferView) MakeWithCapacity(length int,\n\tcapacity int) (PointBuffer, error) {\n\tif capacity < length {\n\t\treturn PointBuffer{}, arena.AllocationInvalidArgumentError\n\t}\n\tsliceHdr, allocErr := s.state.makeSlice(capacity)\n\tif allocErr != nil {\n\t\treturn PointBuffer{}, allocErr\n\t}\n\tsliceHdr.len = length\n\treturn sliceHdr, nil\n}", "func (s *SliceOfInt8) GetSlice() *[]int8 {\n\treturn &s.items\n}", "func (hhm *HHM) Slice(start, end int) *HHM {\n\thmm := hhm.HMM.Slice(start, end)\n\n\tmeta := hhm.Meta\n\tmeta.Neff = 0\n\tfor _, node := range hmm.Nodes {\n\t\tmeta.Neff += node.NeffM\n\t}\n\tmeta.Neff /= seq.Prob(len(hmm.Nodes))\n\n\treturn &HHM{\n\t\tMeta: meta,\n\t\tSecondary: hhm.Secondary.Slice(start, end),\n\t\tMSA: hhm.MSA.Slice(start, end),\n\t\tHMM: hmm,\n\t}\n}", "func (s *SliceOfByte) GetSlice() *[]byte {\n\treturn &s.items\n}", "func (this *Tuple) PopRight() interface{} {\n\tif this.Len() < 1 {\n\t\treturn nil\n\t}\n\tidx := this.Offset(-1)\n\tret := this.data[idx]\n\tthis.data = this.data[:idx]\n\treturn ret\n}", "func (t *StringSlice) Slice(start int, length int) []string {\n\tvar ret []string\n\tif start >= 0 && start+length <= len(t.items) && start+length >= 0 {\n\t\tret = t.items[start : start+length]\n\t}\n\treturn ret\n}", "func (this *Tuple) Offset(n int) int {\n\t// allow negative indexing as in Python\n\tif n < 0 {\n\t\tn = this.Len() + n\n\t}\n\treturn n\n}", "func (a Slice[T]) At(index int) *T {\n\tlen := len(a)\n\n\tif index < 0 {\n\t\tif -index <= len {\n\t\t\treturn &a[len+index]\n\t\t}\n\t\treturn nil\n\t}\n\n\tif index < len {\n\t\treturn &a[index]\n\t}\n\n\treturn nil\n}", "func grow(s reflect.Value, extra int) (reflect.Value, int, int) {\n\ti0 := s.Len()\n\ti1 := i0 + extra\n\tif i1 < i0 {\n\t\tpanic(\"reflect.Append: slice overflow\")\n\t}\n\tm := s.Cap()\n\tif i1 <= m {\n\t\treturn s.Slice(0, i1), i0, i1\n\t}\n\tif m == 0 {\n\t\tm = extra\n\t} else {\n\t\tfor m < i1 {\n\t\t\tif i0 < 1024 {\n\t\t\t\tm += m\n\t\t\t} else {\n\t\t\t\tm += m / 4\n\t\t\t}\n\t\t}\n\t}\n\tt := reflect.MakeSlice(s.Type(), i1, m)\n\treflect.Copy(t, s)\n\treturn t, i0, i1\n}", "func (t Tuple7[A, B, C, D, E, F, G]) Unpack() (A, B, C, D, E, F, G) {\n\treturn t.A, t.B, t.C, t.D, t.E, t.F, t.G\n}", "func (p *TimePanel) Slice(from, to time.Time) TimePanelRO {\n\ti := sort.Search(len(p.dates), func(i int) bool {\n\t\treturn !p.dates[i].Before(from)\n\t})\n\tj := sort.Search(len(p.dates), func(i int) bool {\n\t\treturn !p.dates[i].Before(to)\n\t})\n\treturn p.ISlice(i, j)\n}", "func Reslice(slc []byte, lidx int, uidx int) []byte {\n\tslice := AllocateMake(uidx)\n\tslice = slc[lidx:uidx]\n\treturn slice\n}", "func (t Tuple) At(idx int) float64 {\n\treturn t[idx]\n}", "func (s *SliceOfUint8) GetSlice() *[]uint8 {\n\treturn &s.items\n}", "func (s SamplesC64) Slice(start, end int) Samples {\n\treturn s[start:end]\n}", "func (t Tuple3[A, B, C]) Unpack() (A, B, C) {\n\treturn t.A, t.B, t.C\n}", "func (w *Window) Slice() []float64 {\n\tw.mx.RLock()\n\t// 4 Times faster than \"defer Unlock\"\n\tret := w.base[w.start : w.start+w.Len]\n\tw.mx.RUnlock()\n\treturn ret\n}", "func getPizzaSlice(a, b Coordinate) stl.Triangle {\n\treturn stl.Triangle {\n\t\tNormal: stl.Vec3{ 0,0,1 },\n\t\tVertices: [3]stl.Vec3{\n\t\t\tstl.Vec3{ 0,0,0 },\n\t\t\tstl.Vec3{ float32(a.X), float32(a.Y), 0 },\n\t\t\tstl.Vec3{ float32(b.X), float32(b.Y), 0 },\n\t\t},\n\t}\n}", "func (a Slice[T]) Fill(element T, start int, length int) Slice[T] {\n\tfor length--; length >= 0; length-- {\n\t\ta[start+length] = element\n\t}\n\treturn a\n}", "func (v View) Slice() []bool {\n\t// TODO: This forces an alloc, as an alternative a slice could be taken\n\t// as input that can be (re)used by the client. Are there use cases\n\t// where this would actually make sense?\n\tresult := make([]bool, v.Len())\n\tfor i, j := range v.index {\n\t\tresult[i] = v.data[j]\n\t}\n\treturn result\n}", "func (expr *TupleLiteralExpr) Clone() *TupleLiteralExpr {\n\tif expr == nil {\n\t\treturn nil\n\t}\n\tother := *expr\n\tother.Members = cloneExprs(expr.Members)\n\treturn &other\n}", "func (a Slice[T]) Unshift(element T) Slice[T] {\n\treturn append(Slice[T]{element}, a...)\n}", "func (a Slice[T]) Shift() (T, Slice[T]) {\n\tif len(a) == 0 {\n\t\treturn *new(T), a\n\t}\n\treturn a[0], a[1:]\n}", "func genericSliceOf(slice interface{}) reflect.Value {\n\tsliceValue := reflect.ValueOf(slice)\n\tlength := sliceValue.Len()\n\tsliceAddr := reflect.New(reflect.MakeSlice(\n\t\treflect.TypeOf(slice),\n\t\tlength,\n\t\tlength,\n\t).Type())\n\tfor i := 0; i < length; i++ {\n\t\tvalue := sliceValue.Index(i)\n\t\tap := reflect.Append(sliceAddr.Elem(), value)\n\t\tsliceAddr.Elem().Set(ap)\n\t}\n\treturn sliceAddr.Elem()\n}", "func (t Tuple2[A, B]) Unpack() (A, B) {\n\treturn t.A, t.B\n}", "func (s *internalPointSliceView) MakeWithCapacity(length int, capacity int) ([]Point, error) {\n\tif capacity < length {\n\t\treturn nil, arena.AllocationInvalidArgumentError\n\t}\n\tsliceHdr, allocErr := s.makeGoSlice(capacity)\n\tif allocErr != nil {\n\t\treturn nil, allocErr\n\t}\n\tsliceHdr.Len = length\n\treturn *(*[]Point)(unsafe.Pointer(sliceHdr)), nil\n}", "func (t *Dense) slice(start, end int) {\n\tswitch t.t.Kind() {\n\tcase reflect.Bool:\n\t\tdata := t.bools()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Int:\n\t\tdata := t.ints()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Int8:\n\t\tdata := t.int8s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Int16:\n\t\tdata := t.int16s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Int32:\n\t\tdata := t.int32s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Int64:\n\t\tdata := t.int64s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uint:\n\t\tdata := t.uints()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uint8:\n\t\tdata := t.uint8s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uint16:\n\t\tdata := t.uint16s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uint32:\n\t\tdata := t.uint32s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uint64:\n\t\tdata := t.uint64s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Uintptr:\n\t\tdata := t.uintptrs()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Float32:\n\t\tdata := t.float32s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Float64:\n\t\tdata := t.float64s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Complex64:\n\t\tdata := t.complex64s()[start:end]\n\t\tt.fromSlice(data)\n\tcase reflect.Complex128:\n\t\tdata := t.complex128s()[start:end]\n\t\tt.fromSlice(data)\n\n\tcase reflect.String:\n\t\tdata := t.strings()[start:end]\n\t\tt.fromSlice(data)\n\n\tcase reflect.UnsafePointer:\n\t\tdata := t.unsafePointers()[start:end]\n\t\tt.fromSlice(data)\n\tdefault:\n\t\tv := reflect.ValueOf(t.v)\n\t\tv = v.Slice(start, end)\n\t\tt.fromSlice(v.Interface())\n\t}\n}", "func (reading_EntityInfo) MakeSlice(capacity int) interface{} {\n\treturn make([]*Reading, 0, capacity)\n}", "func (at *ArrayType) Copy() *ArrayType { copied := *at; return &copied }", "func CloneValTuple(n ValTuple) ValTuple {\n\tres := make(ValTuple, 0, len(n))\n\tfor _, x := range n {\n\t\tres = append(res, CloneExpr(x))\n\t}\n\treturn res\n}", "func (r *RecordSlice) Pop() interface{} {\n\trec := r.zvals[len(r.zvals)-1]\n\tr.zvals = r.zvals[:len(r.zvals)-1]\n\treturn &rec\n}", "func (bm ByteMap) Slice(includeKeys map[string]bool) ByteMap {\n\tresult, _ := bm.doSplit(false, includeKeys)\n\treturn result\n}", "func (n NoOp) Slice(start, end int) PrimitiveOp {\n\treturn NoOp{}\n}", "func (h PacketHeader) Slice() []byte {\n\tview := h.pk.headerView(h.typ)\n\treturn view.AsSlice()\n}", "func sliceTest03() {\n list := []int { 1, 0, 3, 4, 5 }\n l1 := list[0:2]\n l1[0], l1[1] = 0, 1\n fmt.Printf(\"Original: %d, %d\\nNew: %d, %d\\n\", list[0], list[1], l1[0], l1[1])\n}", "func (node *selfNode) packToSlice(field reflect.Value) (err error) {\n\tsliceType := field.Type().Elem()\n\tsliceKind := sliceType.Kind()\n\n\tvar value reflect.Value\n\tfor _, n := range node.values {\n\n\t\tswitch sliceKind {\n\t\tcase reflect.Slice, reflect.Array, reflect.Struct, reflect.Map:\n\t\t\tif _, ok := n.(*selfNode); !ok {\n\t\t\t\treturn n.newPackError(\"compound kind `\" + sliceKind.String() + \"` expected a list of values\")\n\t\t\t}\n\n\t\t\tsubNode := n.(*selfNode)\n\t\t\tif err = subNode.checkMetaHeader(sliceType); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tif value, err = n.makeValue(sliceType); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tfield.Set(reflect.Append(field, value))\n\t}\n\n\treturn nil\n}" ]
[ "0.64027596", "0.6047759", "0.5692293", "0.5661918", "0.54960763", "0.5457293", "0.54339534", "0.5367511", "0.5316403", "0.5278541", "0.51971835", "0.51925355", "0.5191372", "0.5167452", "0.5150317", "0.5085428", "0.5074085", "0.5072393", "0.5060345", "0.5042252", "0.5022979", "0.501431", "0.5008105", "0.50035155", "0.4992699", "0.49763268", "0.49619734", "0.49574235", "0.4940647", "0.49395713", "0.49383804", "0.49379435", "0.49336147", "0.48758227", "0.48680228", "0.4864215", "0.48507404", "0.48371458", "0.4833305", "0.4833305", "0.4830456", "0.48101157", "0.4801052", "0.47712097", "0.4764983", "0.47603005", "0.47309464", "0.47251198", "0.47067684", "0.47037864", "0.47036573", "0.4691552", "0.4680525", "0.4673128", "0.46647647", "0.46647647", "0.46647647", "0.46647647", "0.46647647", "0.46615744", "0.46425152", "0.46397483", "0.46284533", "0.46145698", "0.46142524", "0.46032807", "0.45959973", "0.45915297", "0.4585755", "0.45851994", "0.45831466", "0.45824537", "0.4575002", "0.45748875", "0.4572515", "0.45676202", "0.4551786", "0.45451388", "0.4539854", "0.45387763", "0.45373344", "0.4534811", "0.452035", "0.4518316", "0.45166913", "0.45156246", "0.45140257", "0.4513982", "0.45129254", "0.45084348", "0.4506336", "0.44824946", "0.4479454", "0.44738126", "0.44698256", "0.44679785", "0.44660628", "0.446605", "0.4462331", "0.44611174" ]
0.74307245
0
Convert n to an index into the internal slice. Negative numbers are supported, e.g. 1 points to the last item
func (this *Tuple) Offset(n int) int { // allow negative indexing as in Python if n < 0 { n = this.Len() + n } return n }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (n Nodes) Index(i int) *Node", "func IndexN(b, sep []byte, n int) (index int) {\n\tindex, idx, sepLen := 0, -1, len(sep)\n\tfor i := 0; i < n; i++ {\n\t\tif idx = bytes.Index(b, sep); idx == -1 {\n\t\t\tbreak\n\t\t}\n\t\tb = b[idx+sepLen:]\n\t\tindex += idx\n\t}\n\n\tif idx == -1 {\n\t\tindex = -1\n\t} else {\n\t\tindex += (n - 1) * sepLen\n\t}\n\n\treturn\n}", "func IndexLookup(x *suffixarray.Index, s []byte, n int) []int", "func (l *LinkedList) Index(n int) rtype.ListElement {\n\tvar e rtype.ListElement\n\n\tif n >= 0 {\n\t\te = l.Front()\n\t\tfor i := 0; e != nil && i < n; i++ {\n\t\t\te = e.Next()\n\t\t}\n\t} else {\n\t\te = l.Back()\n\t\tfor i := -1; e != nil && i > n; i-- {\n\t\t\te = e.Prev()\n\t\t}\n\t}\n\n\treturn e\n}", "func NewSlice(n sort.Interface) *Slice {\n\ts := &Slice{Interface: n, idx: make([]int, n.Len())}\n\tfor i := range s.idx {\n\t\ts.idx[i] = i\n\t}\n\treturn s\n}", "func processIndex(length, index int) int {\n\tif index >= 0 {\n\t\tif index >= length {\n\t\t\treturn -1\n\t\t}\n\t\treturn index\n\t}\n\tindex = length + index\n\tif index < 0 || index >= length {\n\t\treturn -1\n\t}\n\treturn index\n}", "func (p *SliceOfMap) ShiftN(n int) (new ISlice) {\n\tif n == 0 {\n\t\treturn NewSliceOfMapV()\n\t}\n\tnew = p.Copy(0, abs(n)-1)\n\tp.DropFirstN(n)\n\treturn\n}", "func Slice[T any](n int, f func(int) T) []T {\n\ts := make([]T, n)\n\tfor i := range s {\n\t\ts[i] = f(i)\n\t}\n\treturn s\n}", "func (p IntArray) Index(n int) int {\n\tfor i, v := range p {\n\t\tif v == n {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (in *InBuffer) Slice(n int) []byte {\n\tr := in.Data[in.ReadPos : in.ReadPos+n]\n\tin.ReadPos += n\n\treturn r\n}", "func (in *InBuffer) Slice(n int) []byte {\n\tr := in.Data[in.ReadPos : in.ReadPos+n]\n\tin.ReadPos += n\n\treturn r\n}", "func get1N(indices *[]uint16, start, end int) []uint16 {\n\tif end > cap(*indices) {\n\t\t*indices = make([]uint16, end)\n\t\tfor i := range *indices {\n\t\t\t(*indices)[i] = uint16(i)\n\t\t}\n\t}\n\treturn (*indices)[start:end]\n}", "func toIndex(arrayLength int, term *ast.Term) (int, error) {\n\ti := 0\n\tvar ok bool\n\tswitch v := term.Value.(type) {\n\tcase ast.Number:\n\t\tif i, ok = v.Int(); !ok {\n\t\t\treturn 0, fmt.Errorf(\"invalid number type for indexing\")\n\t\t}\n\tcase ast.String:\n\t\tif v == \"-\" {\n\t\t\treturn arrayLength, nil\n\t\t}\n\t\tnum := ast.Number(v)\n\t\tif i, ok = num.Int(); !ok {\n\t\t\treturn 0, fmt.Errorf(\"invalid string for indexing\")\n\t\t}\n\t\tif v != \"0\" && strings.HasPrefix(string(v), \"0\") {\n\t\t\treturn 0, fmt.Errorf(\"leading zeros are not allowed in JSON paths\")\n\t\t}\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"invalid type for indexing\")\n\t}\n\n\treturn i, nil\n}", "func Index(i, head, size, capacity int) int {\n\t// size=0 is a failure.\n\tif size == 0 {\n\t\treturn -1\n\t}\n\t// first fold i values into ]-size , size[\n\ti = i % size\n\t// then translate negative parts\n\tif i < 0 {\n\t\ti += size\n\t}\n\n\t// this way -1 is interpreted as size-1 etc.\n\n\t// now I've got the real i>=0\n\t// actual theoretical index is simply\n\t// last write minus the required offset.\n\t// last write is lastest\n\t// offset is i, because i==0 means exactly the last written.\n\t//\n\tpos := head - i\n\n\t//pos might be negative. this is the actual index in the ring buffer.\n\t// if head = 0, previous read is at len(buf)-1\n\t// if head == 0 (and i was zero), pos=-1 (as the above calculation)\n\t//so this is the same as before, negative indexes are added the actual size\n\tfor pos < 0 {\n\t\tpos += capacity\n\t}\n\n\t// yehaa, pos is the head position.\n\treturn pos\n}", "func (a ASTNode) Index(n int) ASTNode {\n\tif n >= a.Len() {\n\t\tpanic(ConfErr{a.pos, errors.New(\"Index out of bounds\")})\n\t}\n\treturn a.val.(astArr)[n]\n}", "func (c *compiler) numIndex(n float64) int {\n\tif index, ok := c.indexes.nums[n]; ok {\n\t\treturn index // reuse existing constant\n\t}\n\tindex := len(c.program.Nums)\n\tc.program.Nums = append(c.program.Nums, n)\n\tc.indexes.nums[n] = index\n\treturn index\n}", "func (n Nodes) Slice() []*Node", "func SliceNTokens(b []byte, tok byte, n int) (s []byte, nLeft int) {\n\tfor i := range b {\n\t\tif b[i] == tok {\n\t\t\tn--\n\t\t\tif n == 0 { return b[:i+1], 0 }\n\t\t}\n\t}\n\n\treturn b, n\n}", "func (x *Index) Lookup(s []byte, n int) (result []int) {}", "func (e *Element) projectIndex(i *int) {\n\tv := *i\n\tl := len(e.children.Slice())\n\tif l == 0 {\n\t\tpanic(errCannotIndex)\n\t}\n\n\tif v < 0 {\n\t\tv += l\n\t\tif v < 0 {\n\t\t\tpanic(errIndexOutOfBounds.Args(-l, l-1, v))\n\t\t}\n\t\t*i = v\n\t} else if v >= l {\n\t\tpanic(errIndexOutOfBounds.Args(-l, l-1, v))\n\t}\n}", "func useInts(slice []int, n int, clear bool) []int {\n\tif n <= cap(slice) {\n\t\tslice = slice[:n]\n\t\tif clear {\n\t\t\tfor i := range slice {\n\t\t\t\tslice[i] = 0\n\t\t\t}\n\t\t}\n\t\treturn slice\n\t}\n\treturn make([]int, n)\n}", "func (x *Index) Lookup(s []byte, n int) (result []int)", "func IndexFixer(index int, listSize int) int {\n\tindex = index - 1\n\n\tif index <= 0 {\n\t\tindex = 0\n\t} else if index > listSize-1 {\n\t\tindex = listSize - 1\n\t}\n\n\treturn index\n}", "func indexInSlice(slice []*html.Node, node *html.Node) int {\n\tif node != nil {\n\t\tfor i, n := range slice {\n\t\t\tif n == node {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t}\n\treturn -1\n}", "func mySliceFunc(slice []int) {\n\tslice[0] = slice[0] + 1\n}", "func walkIndex(n *ir.IndexExpr, init *ir.Nodes) ir.Node {\n\tn.X = walkExpr(n.X, init)\n\n\t// save the original node for bounds checking elision.\n\t// If it was a ODIV/OMOD walk might rewrite it.\n\tr := n.Index\n\n\tn.Index = walkExpr(n.Index, init)\n\n\t// if range of type cannot exceed static array bound,\n\t// disable bounds check.\n\tif n.Bounded() {\n\t\treturn n\n\t}\n\tt := n.X.Type()\n\tif t != nil && t.IsPtr() {\n\t\tt = t.Elem()\n\t}\n\tif t.IsArray() {\n\t\tn.SetBounded(bounded(r, t.NumElem()))\n\t\tif base.Flag.LowerM != 0 && n.Bounded() && !ir.IsConst(n.Index, constant.Int) {\n\t\t\tbase.Warn(\"index bounds check elided\")\n\t\t}\n\t\tif ir.IsSmallIntConst(n.Index) && !n.Bounded() {\n\t\t\tbase.Errorf(\"index out of bounds\")\n\t\t}\n\t} else if ir.IsConst(n.X, constant.String) {\n\t\tn.SetBounded(bounded(r, int64(len(ir.StringVal(n.X)))))\n\t\tif base.Flag.LowerM != 0 && n.Bounded() && !ir.IsConst(n.Index, constant.Int) {\n\t\t\tbase.Warn(\"index bounds check elided\")\n\t\t}\n\t\tif ir.IsSmallIntConst(n.Index) && !n.Bounded() {\n\t\t\tbase.Errorf(\"index out of bounds\")\n\t\t}\n\t}\n\n\tif ir.IsConst(n.Index, constant.Int) {\n\t\tif v := n.Index.Val(); constant.Sign(v) < 0 || ir.ConstOverflow(v, types.Types[types.TINT]) {\n\t\t\tbase.Errorf(\"index out of bounds\")\n\t\t}\n\t}\n\treturn n\n}", "func (x IntSlice) Get(i int) interface{} {return x[i]}", "func loc(index int) int {\n\treturn index % 1000\n}", "func inversePrefixIndex(idx int) (addr uint8, len int) {\n\tlz := bits.LeadingZeros(uint(idx))\n\tlen = strconv.IntSize - lz - 1\n\taddr = uint8(idx&(0xFF>>(8-len))) << (8 - len)\n\treturn addr, len\n}", "func (op *Operation) replaceIndex(\n\tinput string,\n\tcount int,\n\tnv numberVar,\n) string {\n\tif len(op.numberOffset) == 0 {\n\t\tfor range nv.submatches {\n\t\t\top.numberOffset = append(op.numberOffset, 0)\n\t\t}\n\t}\n\n\tfor i := range nv.submatches {\n\t\tcurrent := nv.values[i]\n\n\t\top.startNumber = current.startNumber\n\t\tnum := op.startNumber + (count * current.step) + op.numberOffset[i]\n\t\tif len(current.skip) != 0 {\n\t\touter:\n\t\t\tfor {\n\t\t\t\tfor _, v := range current.skip {\n\t\t\t\t\tif num >= v.min && num <= v.max {\n\t\t\t\t\t\tnum += current.step\n\t\t\t\t\t\top.numberOffset[i] += current.step\n\t\t\t\t\t\tcontinue outer\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tn := int64(num)\n\t\tvar r string\n\t\tswitch current.format {\n\t\tcase \"r\":\n\t\t\tr = integerToRoman(num)\n\t\tcase \"h\":\n\t\t\tr = strconv.FormatInt(n, 16)\n\t\tcase \"o\":\n\t\t\tr = strconv.FormatInt(n, 8)\n\t\tcase \"b\":\n\t\t\tr = strconv.FormatInt(n, 2)\n\t\tdefault:\n\t\t\tr = fmt.Sprintf(current.index, num)\n\t\t}\n\n\t\tinput = current.regex.ReplaceAllString(input, r)\n\t}\n\n\treturn input\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 appendIndex(is []int, i int) []int {\n\t// Make a new slice with capacity for a single additional element.\n\tx := make([]int, 0, len(is)+1)\n\t// Append the old slice to the new slice and then append the new\n\t// element.\n\treturn append(append(x, is...), i)\n}", "func (src *Source) CopyN(n int) []byte {\n\tspace := src.ClaimSpace()\n\tfor {\n\t\tif n <= len(src.current) {\n\t\t\tspace = append(space, src.current[:n]...)\n\t\t\tsrc.current = src.current[n:]\n\t\t\tif len(src.current) == 0 {\n\t\t\t\tsrc.Consume()\n\t\t\t}\n\t\t\treturn space\n\t\t}\n\t\tif src.err != nil {\n\t\t\tif src.err == io.EOF {\n\t\t\t\tsrc.err = io.ErrUnexpectedEOF\n\t\t\t}\n\t\t\treturn space\n\t\t}\n\t\tn -= len(src.current)\n\t\tspace = append(space, src.current...)\n\t\tsrc.Consume()\n\t}\n}", "func remove(slice []int, i int) []int{\n\tcopy(slice[i:],slice[i+1:])\n\treturn slice[:len(slice)-1]\n}", "func (na *NArray) ReverseIndex(idx int) []int {\n\n\tres := make([]int, na.Rank, na.Rank)\n\ttemp := idx\n\tp := 1\n\tfor k := 1; k < na.Rank; k++ {\n\t\tp *= na.Shape[k]\n\t}\n\tfor i := 0; i < na.Rank; i++ {\n\t\tres[i] = temp / p\n\t\ttemp = temp % p\n\t\tif (i + 1) < na.Rank {\n\t\t\tp /= na.Shape[i+1]\n\t\t}\n\t}\n\treturn res\n}", "func (n Noop) Index() int {\n\treturn 0\n}", "func removeNthFromEndSlice(head *ListNode, n int) *ListNode {\n\tif head == nil || head.Next == nil {\n\t\treturn nil\n\t}\n\ts := []*ListNode{}\n\tfor {\n\t\ts = append(s, head)\n\t\thead = head.Next\n\t\tif head == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tx := len(s) - n\n\tif x > 0 {\n\t\ts[x-1].Next = s[x].Next\n\t\treturn s[0]\n\t}\n\treturn s[1]\n}", "func (p *SliceOfMap) LastN(n int) ISlice {\n\tif n == 0 {\n\t\treturn NewSliceOfMapV()\n\t}\n\treturn p.Slice(absNeg(n), -1)\n}", "func (i *Index) GetNextN(n int) *Index {\n\tresult := &Index{\n\t\tFiles: map[string]Sourcefile{},\n\t}\n\n\tif len(i.Files) == 0 {\n\t\treturn result\n\t}\n\n\tfor f, src := range i.Files {\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tresult.Add(f, src)\n\t\tn--\n\t}\n\n\treturn result\n}", "func (d *Decoder) Slice(n int) ([]byte, error) {\n\tif d.s != nil {\n\t\treturn d.s.Slice(n)\n\t}\n\n\t// If we don't have a slicer, we can just allocate and read\n\tbuffer := make([]byte, n, n)\n\tif _, err := d.Read(buffer); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buffer, nil\n}", "func remove2(slice []int, i int) []int{\n\tslice[i] = slice[len(slice)-1]\n return slice[:len(slice)-1]\n}", "func GetItem(slice []int, index int) int {\n\tif checkOutOfBounds(index, len(slice)) {\n\t\treturn -1\n\t}\n\treturn slice[index]\n}", "func GetParentIndex(n int) int {\n\treturn (n - 1) / 2\n}", "func appendInt(dst []byte, n uint8, nn uint64) []byte {\n\tnu := uint64(1<<n - 1)\n\tm := len(dst) - 1\n\tif m == -1 {\n\t\tdst = append(dst, 0)\n\t\tm++\n\t}\n\n\tif nn < nu {\n\t\tdst[m] |= byte(nn)\n\t} else {\n\t\tnn -= nu\n\t\tdst[m] |= byte(nu)\n\t\tm = len(dst)\n\t\tnu = 1 << (n + 1)\n\t\ti := 0\n\t\tfor nn > 0 {\n\t\t\ti++\n\t\t\tif i == m {\n\t\t\t\tdst = append(dst, 0)\n\t\t\t\tm++\n\t\t\t}\n\t\t\tdst[i] = byte(nn | 128)\n\t\t\tnn >>= 7\n\t\t}\n\t\tdst[i] &= 127\n\t}\n\treturn dst\n}", "func wrapPlaneExtension(index, limit int) int { return index % limit }", "func sliceForAppend(in []byte, n int) (head, tail []byte) {\n\tif total := len(in) + n; cap(in) >= total {\n\t\thead = in[:total]\n\t} else {\n\t\thead = make([]byte, total)\n\t\tcopy(head, in)\n\t}\n\ttail = head[len(in):]\n\treturn\n}", "func onlyN(a []string, n int) []string {\n\tn = -n\n\tif n > 0 {\n\t\tif n > len(a) {\n\t\t\tn = len(a)\n\t\t}\n\t\ta = a[:n]\n\t} else {\n\t\tif -n > len(a) {\n\t\t\tn = -len(a)\n\t\t}\n\t\ta = a[len(a)+n:]\n\t}\n\treturn a\n}", "func insert(slice []int, index, value int) []int {\n // Grow the slice by one element.\n slice = slice[0 : len(slice)+1]\n // Use copy to move the upper part of the slice out of the way and open a hole.\n copy(slice[index+1:], slice[index:])\n // Store the new value.\n slice[index] = value\n // Return the result.\n return slice\n}", "func removeIndex(slice []int, index int) []int {\n\tret := make([]int, 0)\n\tret = append(ret, slice[:index]...)\n\treturn append(ret, slice[index+1:]...)\n}", "func (b *buffer) index(i uint32) *unsafe.Pointer {\n\treturn risky.Index(unsafe.Pointer(&b.data), ptrSize, uintptr(i))\n}", "func remove(slice []int, i int) []int {\n // copy(dst, src)\n copy(slice[i:], slice[i+1:]) // over writes the slice from i to end with slice from i+1 to end\n return slice[:len(slice)-1]\n}", "func IndexFindAllIndex(x *suffixarray.Index, r *regexp.Regexp, n int) [][]int", "func (n NoOp) Slice(start, end int) PrimitiveOp {\n\treturn NoOp{}\n}", "func (items IntSlice) SubSlice(i, j int) Interface { return items[i:j] }", "func Index(idx uint, l List) interface{} {\n\tfor cur := uint(0); cur < idx; cur++ {\n\t\tif IsEmpty(l) {\n\t\t\treturn Mzero()\n\t\t}\n\t\tl = Tail(l)\n\t}\n\tif IsEmpty(l) {\n\t\treturn Mzero()\n\t}\n\treturn Head(l)\n}", "func GetRightIndex(n int) int {\n\treturn 2*n + 2\n}", "func (vec Vector) Nth(n Number) LangType {\n\tindex := int(n)\n\treturn vec[index]\n}", "func TestNth(t *T) {\n\t// Normal case, in bounds\n\tintl := []interface{}{0, 2, 4, 6, 8}\n\tl := NewList(intl...)\n\tr, ok := l.Nth(3)\n\tassertSaneList(l, t)\n\tassert.Equal(t, intl, ToSlice(l))\n\tassert.Equal(t, 6, r)\n\tassert.Equal(t, true, ok)\n\n\t// Normal case, out of bounds\n\tr, ok = l.Nth(8)\n\tassertSaneList(l, t)\n\tassert.Equal(t, intl, ToSlice(l))\n\tassert.Equal(t, nil, r)\n\tassert.Equal(t, false, ok)\n\n\t// Degenerate case\n\tl = NewList()\n\tr, ok = l.Nth(0)\n\tassert.Equal(t, 0, Size(l))\n\tassert.Equal(t, nil, r)\n\tassert.Equal(t, false, ok)\n}", "func Index(depth, offset uint) uint {\n\treturn (1+2*offset)*twoPow(depth) - 1\n}", "func TakeInt(n int, list []int) []int {\n\tif n < 0 {\n\t\treturn []int{}\n\t}\n\n\tnewListLen := len(list)\n\n\tif n < newListLen {\n\t\tnewListLen = n\n\t}\n\tnewList := make([]int, newListLen)\n\tfor i := 0; i < newListLen; i++ {\n\t\tnewList[i] = list[i]\n\t}\n\treturn newList\n}", "func NodeSlicePosition(sl []*Node, nd *Node) (x int) {\n\tx = -1\n\tfor p, v := range sl {\n\t\tif v == nd {\n\t\t\tx = p\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func main() {\n\tnums := []int{1, 7, 3, 6, 5, 6}\n\tfmt.Println(pivotIndex(nums))\n\n\tnums2 := []int{-1,-1,-1,0,1,1}\n\tfmt.Println(pivotIndex(nums2))\n\n\tnums3 := []int{-1,-1,1,1,0,0}\n\tfmt.Println(pivotIndex(nums3))\n\n\tnums4 := []int{-1,-1,-1,1,1,1}\n\tfmt.Println(pivotIndex(nums4))\n}", "func (s Stream) Offset(n int) Stream {\n\treturn s.Pipe(func() func(r Record) (Record, error) {\n\t\tvar skipped int\n\n\t\treturn func(r Record) (Record, error) {\n\t\t\tif skipped < n {\n\t\t\t\tskipped++\n\t\t\t\treturn nil, nil\n\t\t\t}\n\n\t\t\treturn r, nil\n\t\t}\n\t})\n}", "func (a *ArrayObject) normalizeIndex(objectIndex *IntegerObject) int {\n\taLength := len(a.Elements)\n\tindex := objectIndex.value\n\n\t// out of bounds\n\n\tif index >= aLength {\n\t\treturn -1\n\t}\n\n\tif index < 0 && -index > aLength {\n\t\treturn -1\n\t}\n\n\t// within bounds\n\n\tif index < 0 {\n\t\treturn aLength + index\n\t}\n\n\treturn index\n}", "func nthUglyNumber(n int) int {\n\treturn foundNumbers[n-1]\n}", "func Slice(inmaps map[int]*task.Task, n int) map[int]*task.Task {\n\tif n < 2 {\n\t\treturn inmaps\n\t}\n\n\tvar (\n\t\tgap = len(inmaps)\n\t\toutmaps = make(map[int]*task.Task)\n\t)\n\tfor k, t := range inmaps {\n\t\tvar (\n\t\t\tsgap = len(t.Source)\n\t\t\ti = 0\n\t\t)\n\n\t\tfor ; i < n-1; i++ {\n\t\t\tsource := t.Source[i*sgap/n : (i+1)*sgap/n]\n\t\t\toutmaps[(k+1)*gap+i] = &task.Task{t.Type, t.Priority, t.Consumable, source, t.Result, t.Context, t.Stage}\n\t\t}\n\n\t\tsource := t.Source[i*sgap/n:]\n\t\toutmaps[(k+1)*gap+i] = &task.Task{t.Type, t.Priority, t.Consumable, source, t.Result, t.Context, t.Stage}\n\t}\n\n\treturn outmaps\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 (ts TrickSlice) Last(n int) TrickSlice {\n\tv := reflect.Value(ts)\n\tif n > v.Len() {\n\t\tn = v.Len()\n\t}\n\treturn TrickSlice(v.Slice3(v.Len()-n, v.Len(), v.Len()))\n}", "func (v IntVec) Rewrite(o IntVec, idx int) {\n\tcopy(v[idx:], o)\n}", "func GetLeftIndex(n int) int {\n\treturn 2*n + 1\n}", "func IntGetUniqueN(start, endp1, n int) (selected []int) {\n\tif n < 1 {\n\t\treturn\n\t}\n\tsize := endp1 - start\n\tif n >= size {\n\t\tselected = utl.IntRange2(start, endp1)\n\t\tIntShuffle(selected)\n\t\treturn\n\t}\n\tselected = make([]int, n)\n\tfor i := 0; i < n; i++ {\n\t\tselected[i] = start + i\n\t}\n\tvar j int\n\tfor i := n; i < size; i++ {\n\t\tj = rand.Intn(i + 1)\n\t\tif j < n {\n\t\t\tselected[j] = start + i\n\t\t}\n\t}\n\treturn\n}", "func NewIntSlice(n ...int) *Slice {\n\treturn NewSlice(sort.IntSlice(n))\n}", "func (s *SliceOfInt) Shift() *SliceOfInt {\n\ts.items = s.items[1:]\n\treturn s\n}", "func (p *SliceOfMap) PopN(n int) (new ISlice) {\n\tif n == 0 {\n\t\treturn NewSliceOfMapV()\n\t}\n\tnew = p.Copy(absNeg(n), -1)\n\tp.DropLastN(n)\n\treturn\n}", "func Delete(slice []int, index int) []int {\n\treturn append(slice[:index], slice[index+1:]...)\n}", "func GetIndexToIns(arr []int, num int) int {\n\tsort.Ints(arr)\n\tif len(arr) == 0 || arr[0] >= num {\n\t\treturn 0\n\t} else if arr[len(arr)-1] < num {\n\t\treturn len(arr)\n\t}\n\tfor i := 0; i < len(arr); i++ {\n\t\tif arr[i] == num || arr[i] > num {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn 0\n}", "func randSlice(n int) []int {\n\ts := make([]int, n)\n\tfor i := range s {\n\t\ts[i] = rand.Int()\n\t}\n\treturn s\n}", "func TakeIntPtr(n int, list []*int) []*int {\n\tif n < 0 {\n\t\treturn []*int{}\n\t}\n\n\tnewListLen := len(list)\n\n\tif n < newListLen {\n\t\tnewListLen = n\n\t}\n\tnewList := make([]*int, newListLen)\n\tfor i := 0; i < newListLen; i++ {\n\t\tnewList[i] = list[i]\n\t}\n\treturn newList\n}", "func (s *Series) index(t time.Time) int64 {\n\treturn int64(math.Mod(float64(s.floor(t).Unix()), float64(s.Duration.Seconds())))\n}", "func TestNth(t *T) {\n\t// Normal case, in bounds\n\tintl := []interface{}{0, 2, 4, 6, 8}\n\tl := NewList(intl...)\n\tr, ok := l.Nth(3)\n\tassertSaneList(l, t)\n\tassertSeqContents(l, intl, t)\n\tassertValue(r, 6, t)\n\tassertValue(ok, true, t)\n\n\t// Normal case, out of bounds\n\tr, ok = l.Nth(8)\n\tassertSaneList(l, t)\n\tassertSeqContents(l, intl, t)\n\tassertValue(r, nil, t)\n\tassertValue(ok, false, t)\n\n\t// Degenerate case\n\tl = NewList()\n\tr, ok = l.Nth(0)\n\tassertEmpty(l, t)\n\tassertValue(r, nil, t)\n\tassertValue(ok, false, t)\n}", "func (p Pointer) Offset(n uint64) Pointer {\n\treturn Pointer{Address: p.Address + n, Pool: p.Pool}\n}", "func Int(slice ...[]int) *IntSlicer {\n\tif len(slice) > 0 {\n\t\treturn &IntSlicer{slice: slice[0]}\n\t}\n\treturn &IntSlicer{}\n}", "func Nth(data interface{}, i int) (interface{}, error) {\n\tvar err error\n\n\tresult := func(err *error) interface{} {\n\t\tdefer catch(err)\n\n\t\tif !isNonNilData(err, \"data\", data) {\n\t\t\treturn nil\n\t\t}\n\n\t\tdataValue, _, _, dataValueLen := inspectData(data)\n\n\t\tif !isSlice(err, \"data\", dataValue) {\n\t\t\treturn nil\n\t\t}\n\n\t\tif dataValueLen == 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\tif i < 0 {\n\t\t\ti = dataValueLen + i\n\t\t}\n\n\t\tif i < dataValueLen {\n\t\t\treturn dataValue.Index(i).Interface()\n\t\t}\n\n\t\treturn nil\n\t}(&err)\n\n\treturn result, err\n}", "func (a *ArrayObject) index(t *thread, args []Object, sourceLine int) Object {\n\tif len(args) != 1 {\n\t\treturn t.vm.initErrorObject(errors.ArgumentError, sourceLine, \"Expect 1 arguments. got=%d\", len(args))\n\t}\n\n\ti := args[0]\n\tindex, ok := i.(*IntegerObject)\n\n\tif !ok {\n\t\treturn t.vm.initErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.IntegerClass, args[0].Class().Name)\n\t}\n\n\tnormalizedIndex := a.normalizeIndex(index)\n\n\tif normalizedIndex == -1 {\n\t\treturn NULL\n\t}\n\n\treturn a.Elements[normalizedIndex]\n}", "func NewIndicesUintSlice(n ...uint) *IndicesSlice { return NewIndicesSlice(UintSlice(n)) }", "func main(){\n\tnumslice:=[]int{1,2,3,4,5}\n\tnumslice2 := numslice[0:4] //4 is not the index but the total no. of elements\n\tfmt.Println(numslice2)\n\t// 5 is considered as 4 as the total no. of elements are 5(index from 0 to 4)\n\tfmt.Println(\"numslice2[1]=\",numslice2[1])\n\tfmt.Println(\"numslice3[:2]=\",numslice[:2]) //Starting from 0 to 1 (till 2 u want and not include 2)\n\tfmt.Println(\"numslice4[2:]=\",numslice[2:]) //After 2 all you want (include 2)\n\n\tnumslice3:=make([]int,5,10) //make a slice whose elements are not known where 5 is the size and 10 is the till what it can extend\n\tfmt.Println(numslice3) // prints the full array, no need of for loop\n\tcopy(numslice3,numslice) //copy of elements of numslice to numslice 3\n\tfmt.Println(numslice3[2])\n\tnumslice3=append(numslice3,0,-1) //adding two elements 0 and -1 in numslice 3 position after index4 and size 5\n\tfmt.Println(numslice3)\n\tfmt.Println(numslice3[6])\n}", "func SlotIndex(slotEnd time.Time, step time.Duration, size int64) int64 {\n\treturn ((slotEnd.UnixNano() / 1e6) / (step.Nanoseconds() / 1e6)) % size\n}", "func makeSlice(n int) []byte {\n\tif n <= 64 {\n\t\treturn pool64.Get().([]byte)[0:n]\n\t}\n\n\tpn := poolNum(n)\n\n\tif pn != -1 {\n\t\treturn pools[pn].Get().([]byte)[0:n]\n\t} else {\n\t\treturn make([]byte, n)\n\t}\n}", "func (ctx *Context) shift(n int) {\n\tbuf := ctx.buf[ctx.off : ctx.off+n]\n\tfor i := range buf {\n\t\tbuf[i] = 0\n\t}\n\tctx.off += n\n}", "func (c *Cursor) Backward(n int) {\n\t(*c).Index -= n\n}", "func (n Nodes) SetIndex(i int, node *Node)", "func initCache(n int) []int {\n\n\tcache := make([]int, n+1)\n\n\tfor i := range cache {\n\t\tcache[i] = -1\n\t}\n\n\treturn cache\n}", "func remove(slice []int, s int) []int {\n\treturn append(slice[:s], slice[s+1:]...)\n}", "func first_n_of_five(arr [5]int, n int) []int {\n // If n is out of range, return a slice of full array\n if n > 5 || n < 0 {\n fmt.Println(\"n must be between 0 and 5. Full array:\")\n return arr[:]\n }\n // Look at slice of array\n return arr[0:n]\n}", "func (a Slice[T]) At(index int) *T {\n\tlen := len(a)\n\n\tif index < 0 {\n\t\tif -index <= len {\n\t\t\treturn &a[len+index]\n\t\t}\n\t\treturn nil\n\t}\n\n\tif index < len {\n\t\treturn &a[index]\n\t}\n\n\treturn nil\n}", "func Idx(e, slice interface{}) int {\n\tv := rValueOf(slice)\n\tL, I := v.Len(), -1\n\tfor i := 0; i < L; i++ {\n\t\tif v.Index(i).Interface() == e {\n\t\t\tI = i\n\t\t\tbreak\n\t\t}\n\t}\n\treturn I\n}", "func SliceInt(i interface{}) []int {\n\treturn Ints(i)\n}", "func (alph RangeAlphabet) ToIndex(symbol rune) int {\n\treturn int(symbol-alph.startSymbol) % alph.size\n}", "func (l *DList) get(i int) *dnode {\n\tif i < l.n/2 {\n\t\tn := l.r.n\n\t\tfor j := 0; j < i; j++ {\n\t\t\tn = n.n\n\t\t}\n\t\treturn n\n\t}\n\tn := l.r\n\tfor j := l.n; j > i; j-- {\n\t\tn = n.p\n\t}\n\treturn n\n}", "func (p *program) getAddrIndex(n int) int {\n\tparameter := p.mem[p.pc+n]\n\tmode := p.instructionMode(n)\n\n\tif mode == 0 {\n\t\treturn parameter\n\t} else if mode == 2 {\n\t\treturn p.base + parameter\n\t} else {\n\t\tpanic(\"unsupported immediate mode for writing\")\n\t}\n}" ]
[ "0.6139645", "0.60067254", "0.5855295", "0.58331335", "0.5774126", "0.5684", "0.56789446", "0.56658876", "0.5651992", "0.5557862", "0.5557862", "0.54764515", "0.54653597", "0.54514575", "0.5435891", "0.54302675", "0.54021513", "0.53586125", "0.53472817", "0.533107", "0.53203404", "0.53186333", "0.5308598", "0.53005165", "0.5259933", "0.5223594", "0.5218761", "0.52160484", "0.52157074", "0.5214983", "0.5208588", "0.5205023", "0.5195053", "0.5193755", "0.51896536", "0.51770216", "0.516939", "0.51561695", "0.51500565", "0.5119705", "0.5111721", "0.50934845", "0.5075411", "0.5064989", "0.50567764", "0.50489837", "0.50469553", "0.50436187", "0.5031131", "0.50150734", "0.5013754", "0.50122446", "0.49992993", "0.49876875", "0.4958039", "0.4951183", "0.4947083", "0.4945778", "0.49281496", "0.4919741", "0.49196103", "0.49146163", "0.49090275", "0.49086028", "0.49085805", "0.49062967", "0.48926523", "0.488986", "0.48840883", "0.4883542", "0.48768628", "0.48716164", "0.48688942", "0.48638737", "0.4860746", "0.48403093", "0.4828558", "0.48282728", "0.48170117", "0.4814573", "0.48035666", "0.47948676", "0.47903213", "0.47869745", "0.47841066", "0.47796604", "0.47751844", "0.47740906", "0.47721174", "0.4769224", "0.47649443", "0.47642356", "0.47641376", "0.47583845", "0.47467804", "0.47383046", "0.47330517", "0.4732291", "0.47313645", "0.47210675" ]
0.496398
54
Set the item at index n
func (this *Tuple) Set(n int, item interface{}) { this.data[this.Offset(n)] = item }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (n Nodes) SetIndex(i int, node *Node)", "func (aa *Array) Set(idx int, node interface{}) error {\n\t// do not lock if not needed\n\tif idx < 0 || idx >= aa.length {\n\t\treturn fmt.Errorf(\"index %d is larger than array size (%d)\", idx, aa.length)\n\t}\n\n\taa.mutex.Lock()\n\taa.items[idx] = node\n\taa.mutex.Unlock()\n\treturn nil\n}", "func (arr *ArrayList) Set(index uint32, newItem ItemType) {\n if index < arr.length {\n arr.data[index] = newItem\n } else {\n panic(\"out of bounds\")\n }\n}", "func (v Vector) Set(n int, data float64) {\n\tv.data[n] = data\n}", "func (list *List) Set(index int, value interface{}) {\n\n\tif !list.withinRange(index) {\n\t\t// Append\n\t\tif index == list.size {\n\t\t\tlist.Add(value)\n\t\t}\n\t\treturn\n\t}\n\n\tfoundElement := list.first\n\tfor e := 0; e != index; {\n\t\te, foundElement = e+1, foundElement.next\n\t}\n\tfoundElement.value = value\n}", "func (vn *VecN) Set(i int, val float64) {\n\tvn.vec[i] = val\n}", "func SetItem(slice []int, index, value int) []int {\n\tif checkOutOfBounds(index, len(slice)) {\n\t\treturn append(slice, value)\n\t}\n\tslice[index] = value\n\treturn slice\n}", "func (ll *LinkedList) Set(index uint, data interface{}) {\n\tll.Lock()\n\tdefer ll.Unlock()\n\n\tif index >= ll.size {\n\t\tpanic(&IndexOutOfRangeError{size: ll.size})\n\t}\n\n\tnode := ll.findNode(index)\n\tnode.data = data\n}", "func testSetN(n int, hm HashMaper) {\n\tfor i := 0; i < n; i++ {\n\t\thm.Set(Key(i), i)\n\t}\n}", "func (v *VectorImpl) Set(i int, item Value) *VectorImpl {\n\tif i < 0 || uint(i) >= v.len {\n\t\tpanic(\"Index out of bounds\")\n\t}\n\n\tif uint(i) >= v.tailOffset() {\n\t\tnewTail := make([]Value, len(v.tail))\n\t\tcopy(newTail, v.tail)\n\t\tnewTail[i&shiftBitMask] = item\n\t\treturn &VectorImpl{root: v.root, tail: newTail, len: v.len, shift: v.shift}\n\t}\n\n\treturn &VectorImpl{root: v.doAssoc(v.shift, v.root, uint(i), item), tail: v.tail, len: v.len, shift: v.shift}\n}", "func (buf *ListBuffer) Set(idx BufferIndex, item Item) (*error.Error) {\n\tinRange, initialized := buf.legalIndex(idx)\n\tif !inRange {\n\t\tdesc := fmt.Sprintf(\n\t\t\t\"idx, %d, is out of range for IndexBuffer of length %d.\",\n\t\t\tidx, len(buf.Buffer),\n\t\t)\n\t\treturn error.New(error.Value, desc)\n\t} else if !initialized {\n\t\tdesc := fmt.Sprintf(\n\t\t\t\"Item at idx, %d, has the Type value Uninitialized.\", idx,\n\t\t)\n\t\treturn error.New(error.Value, desc)\n\t}\n\n\tbuf.Buffer[idx].Item = item\n\treturn nil\n}", "func (s *VectorImplSlice) Set(i int, item Value) *VectorImplSlice {\n\tif i < 0 || s.start+i >= s.stop {\n\t\tpanic(\"Index out of bounds\")\n\t}\n\n\treturn s.vector.Set(s.start+i, item).Slice(s.start, s.stop)\n}", "func (d *DynamicArr) Set(index int, value interface{}) error {\n\tif index < 0 {\n\t\treturn errors.New(\"Index has to be greater than or equal to zero\")\n\t}\n\n\tfor index > d.capacity {\n\t\td.growSize()\n\t\td.length = d.capacity\n\t}\n\n\td.array[index] = value\n\td.length++\n\treturn nil\n}", "func (o *FakeObject) SetIndex(i int, value interface{}) {\n\treflect.ValueOf(o.Value).Index(i).Set(reflect.ValueOf(value))\n}", "func (sa *SnapshotArray) Set(index int, val int) {\n\tsa.current[index] = val\n}", "func (s *SGTree) Set(i int, e interface{}) {\n\ts.data[i] = e\n\ts.set(0, 0, len(s.data)-1, i, e)\n}", "func (v Value) SetIndex(i int, x interface{}) {\n\tpanic(message)\n}", "func (ms Float64Slice) SetAt(i int, val float64) {\n\t(*ms.getOrig())[i] = val\n}", "func (_m *MockMutableSeriesIterators) SetAt(idx int, iter SeriesIterator) {\n\t_m.ctrl.Call(_m, \"SetAt\", idx, iter)\n}", "func (t *Type) SetNumElem(n int64)", "func set(l *foo, i byte, to *foo) {\n\tif i == Next {\n\t\tl.next = to\n\t\treturn\n\t}\n\tl.prev = to\n}", "func (this *SnapshotArray) Set(index int, val int) {\n\tif len(this.arr[index]) < this.snapId+1 {\n\t\tfor len(this.arr[index]) < this.snapId+1 {\n\t\t\tthis.arr[index] = append(this.arr[index], this.arr[index][len(this.arr[index])-1])\n\t\t}\n\t}\n\tthis.arr[index][this.snapId] = val\n}", "func (n *Node) SetInt(i int64)", "func (list *PyList) SetItem(index int, obj *PyObject) error {\n\tif C.PyList_SetItem(list.ptr, C.long(index), obj.ptr) == -1 {\n\t\treturn ErrCouldNotInsert\n\t}\n\n\treturn nil\n}", "func (m *Mailboxes) Set(n int, val string) error {\n\tif n > len(m.mem)-1 {\n\t\treturn ErrInvalidMemory{n}\n\t}\n\n\tif n < 0 {\n\t\treturn ErrInvalidMemory{n}\n\t}\n\n\tm.mem[n] = val\n\treturn nil\n}", "func (na *NArray) Set(v float32, indices ...int) {\n\n\tna.Data[na.Index(indices...)] = v\n}", "func poolSetIndex(a interface{}, i int) {\n\ta.(*freeClientPoolEntry).index = i\n}", "func (lo *LuaObject) Set(idx interface{}, val interface{}) interface{} {\n L := lo.L\n lo.Push() // the table\n GoToLua(L, nil, valueOf(idx))\n GoToLua(L, nil, valueOf(val))\n L.SetTable(-3)\n L.Pop(1) // the table\n return val\n}", "func (t *FenwickTreeSimple) Set(index int, value int) {\n\tt.Update(index, value-t.Get(index))\n}", "func (cpu *CPU) set_N(i uint16) {\r\n\tcpu.regs[2] = (cpu.regs[2] & 0xfb) | ((i & 1) << 2)\r\n}", "func (self *SinglePad) SetIndexA(member int) {\n self.Object.Set(\"index\", member)\n}", "func (l *ListItem) SetElem(n int, elem Element) {\n\tleng := len(l.contents)\n\tif n > leng-1 {\n\t\tl.AddElem(elem)\n\t} else {\n\t\tl.contents[n] = elem\n\t}\n}", "func (v *V) SetAt(i int, f float64) Vector {\n\tif i < 0 || i >= v.Dim() {\n\t\tpanic(ErrIndex)\n\t}\n\tv.Data[i] = f\n\treturn v\n}", "func (bitmap *bitmap) Set(index int) {\n\tbitmap.set(index, 1)\n}", "func (self *TileSprite) SetChildIndex(child *DisplayObject, index int) {\n self.Object.Call(\"setChildIndex\", child, index)\n}", "func (p *IntVector) Set(i int, x int)\t{ p.a[i] = x }", "func (b *Bar) Set(n int) error {\n\tb.mtx.Lock()\n\tdefer b.mtx.Unlock()\n\n\tif n > b.Total {\n\t\treturn ErrMaxCurrentReached\n\t}\n\tb.current = n\n\treturn nil\n}", "func modifyUsingSlice(sls []int){\n\tsls[0] = 500\n}", "func (access IntAccess) Set(row int, val int) {\n access.rawData[access.indices[row]] = val\n}", "func (hat *HashedArrayTree) Set(index int, value interface{}) error {\n\tif !hat.validIndex(index) {\n\t\treturn ErrIndexOutOfRange\n\t}\n\tti, li := hat.topIndex(index), hat.leafIndex(index)\n\that.top[ti][li] = value\n\treturn nil\n}", "func (cache *cache) SetValue(index, value int) error {\n\tbs := []byte(strconv.Itoa(value))\n\tsetItem := memcache.Item{\n\t\tKey: strconv.Itoa(index),\n\t\tValue: bs}\n\tif err := cache.client.Set(&setItem); err != nil {\n\t\treturn err\n\t}\n\tif MaxCalculatedIndex < index {\n\t\tMaxCalculatedIndex = index\n\t}\n\treturn nil\n}", "func (t *Tensor) ItemSet(v *Tensor, pos ...int) *Tensor {\n\tif !t.idx.Validate(pos) {\n\t\tpanic(errorc.New(\"invalid position %v for %v\", pos, t.idx))\n\t}\n\n\tif v.Size() != 1 {\n\t\tpanic(errorc.New(\"invalid non scalar argument (shape:%v)\", v.Shape()))\n\t}\n\n\tt.buf.Setptr()(t.idx.At()(pos), v.buf.DType(), v.buf.At()(0))\n\n\treturn t\n}", "func (pool *FixedBytePool) Set(index int32, key []byte) error {\n\tif int(index) >= pool.maxElemNum {\n\t\treturn fmt.Errorf(\"index out of range %d %d\", index, pool.maxElemNum)\n\t}\n\n\tif len(key) != pool.elemSize {\n\t\treturn fmt.Errorf(\"length must be %d while %d\", pool.elemSize, len(key))\n\t}\n\tstart := int(index) * pool.elemSize\n\tcopy(pool.buf[start:], key)\n\n\treturn nil\n}", "func (q *Queue) SetIndexed(repoName string, opts IndexOptions, state indexState) {\n\tq.mu.Lock()\n\titem := q.get(repoName)\n\titem.setIndexState(state)\n\tif state != indexStateFail {\n\t\titem.indexed = reflect.DeepEqual(opts, item.opts)\n\t}\n\tif item.heapIdx >= 0 {\n\t\t// We only update the position in the queue, never add it.\n\t\theap.Fix(&q.pq, item.heapIdx)\n\t}\n\tq.mu.Unlock()\n}", "func (m *spiralMemory) set(x int, y int, i int) {\n\trx := x + m.offset\n\try := y + m.offset\n\tif ry < 0 || ry > len(m.grid)-1 || rx < 0 || rx > len(m.grid[ry])-1 {\n\t\tm.grow()\n\t\tm.set(x, y, i)\n\t} else {\n\t\tm.grid[ry][rx] = i\n\t}\n}", "func (m *RecurrencePattern) SetIndex(value *WeekIndex)() {\n m.index = value\n}", "func (iter *Iterator) SetPosition(pos uint64) { iter.impl.SetValue(pos) }", "func (this *LinkedList) Set(index int, ele interface{}) bool {\n\tif index < 0 || index >= this.Size() {\n\t\tpanic(\"index out of bound\")\n\t}\n\tpe := this.head\n\tfor i := 0; i < index; i++ {\n\t\tpe = pe.next\n\t}\n\tpe.elem = ele\n\treturn true\n}", "func (bitmap *bitmap) set(index int, bit int) {\n\tif index >= bitmap.Size {\n\t\tpanic(\"index out of range\")\n\t}\n\n\tdiv, mod := index/8, index%8\n\tshift := byte(1 << uint(7-mod))\n\n\tbitmap.data[div] &= ^shift\n\tif bit > 0 {\n\t\tbitmap.data[div] |= shift\n\t}\n}", "func (self *TileSprite) SetChildIndexI(args ...interface{}) {\n self.Object.Call(\"setChildIndex\", args)\n}", "func (n Nodes) Index(i int) *Node", "func (list *ArrayList[T]) Set(index int, ele T) bool {\n\tif index < 0 || index >= list.Size() {\n\t\treturn false\n\t}\n\tlist.elems[index] = ele\n\treturn true\n}", "func (b *fixedResolutionValues) SetValueAt(n int, v float64) {\n\tb.values[n] = v\n}", "func (uni *Uniform3fv) Set(idx int, v0, v1, v2 float32) {\n\n\tpos := idx * 3\n\tuni.v[pos] = v0\n\tuni.v[pos+1] = v1\n\tuni.v[pos+2] = v2\n}", "func (self *Graphics) SetChildIndex(child *DisplayObject, index int) {\n self.Object.Call(\"setChildIndex\", child, index)\n}", "func (uni *UniformMatrix3f) Set(pos int, v float32) {\n\n\tuni.v[pos] = v\n}", "func (O ObjectCollection) SetItem(i int, data *Data) error {\n\tif C.dpiObject_setElementValueByIndex(O.dpiObject, C.int32_t(i), data.NativeTypeNum, &data.dpiData) == C.DPI_FAILURE {\n\t\treturn errors.Errorf(\"set(%d[%d]): %w\", i, data.NativeTypeNum, O.getError())\n\t}\n\treturn nil\n}", "func (bs *byteSliceBitSet) Set(index int) {\n\tif index < 0 {\n\t\treturn\n\t}\n\t// Check capacity\n\tbs.checkAndIncreaseCapacity(index)\n\t// Locate byte and bit\n\tbyteIndex, bitIndex := bs.locateBit(index)\n\t// Set value\n\tbs.bytes[byteIndex] = bs.bytes[byteIndex] | (1 << byte(bitIndex))\n\t// Increase word in use counter\n\tbs.wordInUse += 1\n}", "func (ps *PrjnStru) SetNIdxSt(n *[]int32, avgmax *minmax.AvgMax32, idxst *[]int32, tn *etensor.Int32) int32 {\n\tln := tn.Len()\n\ttnv := tn.Values\n\t*n = make([]int32, ln)\n\t*idxst = make([]int32, ln)\n\tidx := int32(0)\n\tavgmax.Init()\n\tfor i := 0; i < ln; i++ {\n\t\tnv := tnv[i]\n\t\t(*n)[i] = nv\n\t\t(*idxst)[i] = idx\n\t\tidx += nv\n\t\tavgmax.UpdateVal(float32(nv), int32(i))\n\t}\n\tavgmax.CalcAvg()\n\treturn idx\n}", "func (r *Ring) set(p int, v interface{}) {\n\tr.buff[r.mod(p)] = v\n}", "func (r *SlidingWindow) Set(index int, value interface{}) bool {\n\tindex -= r.base\n\tif index < 0 || index >= r.Capacity() {return false}\n\tindex = r.normalize(index + r.start)\n\tr.values[index].value = value\n\tif !r.values[index].present {\n\t\tr.values[index].present = true\n\t\tr.count++\n\t}\n\treturn true\n}", "func (l *List) Set(i *Item, value interface{}) {\n\ti.value = l.valueToPointer(value)\n}", "func (ba *FilterBitArray) Set(i uint) {\n\t// Location of i in the array index is floor(i/byte_size) + 1. If it exceeds the\n\t// current byte array, we'll make a new one large enough to include the\n\t// specified bit-index\n\tif i >= ba.Capacity() {\n\t\tba.expand(i/byteSize + 1)\n\t}\n\t(*ba)[i/byteSize] |= 1 << (i % byteSize)\n}", "func (v *Posit16x2) Put(i int, x Posit16) { v.impl[i] = x }", "func (spriteBatch *SpriteBatch) Set(index int, args ...float32) error {\n\treturn spriteBatch.addv(spriteBatch.texture.getVerticies(), generateModelMatFromArgs(args), index)\n}", "func (mmSetIndex *mIndexModifierMockSetIndex) Set(f func(ctx context.Context, pn insolar.PulseNumber, index record.Index) (err error)) *IndexModifierMock {\n\tif mmSetIndex.defaultExpectation != nil {\n\t\tmmSetIndex.mock.t.Fatalf(\"Default expectation is already set for the IndexModifier.SetIndex method\")\n\t}\n\n\tif len(mmSetIndex.expectations) > 0 {\n\t\tmmSetIndex.mock.t.Fatalf(\"Some expectations are already set for the IndexModifier.SetIndex method\")\n\t}\n\n\tmmSetIndex.mock.funcSetIndex = f\n\treturn mmSetIndex.mock\n}", "func (i *MyInt) set(x int) {\n\t*i = MyInt(x)\n}", "func (b *BTree) insertInNodeAtIdx(n *memNode, item *Item, i int) {\n\ts := n.node.Items\n\ts = append(s, nil)\n\tif i < len(s) {\n\t\tcopy(s[i+1:], s[i:])\n\t}\n\ts[i] = item\n\tn.node.Items = s\n}", "func (arr *Array) set(i int, v *Term) {\n\tarr.ground = arr.ground && v.IsGround()\n\tarr.elems[i] = v\n\tarr.hashs[i] = v.Value.Hash()\n}", "func (b Bits) Set(n int) Bits {\n\treturn b | (1 << uint64(n))\n}", "func PyTuple_SetItem(o *PyObject, pos int, item *PyObject) error {\n\tif rc := int(C.__PyTuple_SetItem(go2c(o), C.Py_ssize_t(pos), go2c(item))); rc != 0 {\n\t\treturn fmt.Errorf(\"cpython: error to set item to PyTuple, pos: %v\", pos)\n\t}\n\treturn nil\n}", "func (b *BitSet) Set(n int) {\n\tb.checkRange(n)\n\tm := uint(n)\n\tb.data[n>>3] |= 1 << (7 - m%8)\n}", "func (access ObjectAccess) Set(row int, val interface{}) {\n access.rawData[access.indices[row]] = val\n}", "func (l *List) SetKey(key Item, to Item) (err error) {\n\tval, ok := castNumeric(key)\n\tif !ok {\n\t\treturn newError(ErrType, \"can only index a list with a numeric type\")\n\t}\n\n\tindex := int(val)\n\n\tif index < 0 || index >= len(l.value) {\n\t\treturn newError(ErrIndex, \"index out of bounds\")\n\t}\n\n\tl.value[index] = to\n\treturn nil\n}", "func (s *items) insertAt(index int, item Item) {\n\t*s = append(*s, nil)\n\tif index < len(*s) {\n\t\tcopy((*s)[index+1:], (*s)[index:])\n\t}\n\t(*s)[index] = item\n}", "func (d *Device1Receiver) SetN(n int) {\n\td.n = n\n}", "func (item *queueItem) setIndexState(state indexState) {\n\tif state == item.indexState {\n\t\treturn\n\t}\n\tif item.indexState != \"\" {\n\t\tmetricIndexState.WithLabelValues(string(item.indexState)).Dec()\n\t}\n\titem.indexState = state\n\tif item.indexState != \"\" {\n\t\tmetricIndexState.WithLabelValues(string(item.indexState)).Inc()\n\t}\n}", "func (A *Matrix) Set(i, j int, v float64){\n\tA.data[i * A.stride + j] = v\n}", "func (a Args) SetFirst(count int32) { a[0] = &count }", "func (O ObjectCollection) Set(i int, v interface{}) error {\n\tif data, ok := v.(*Data); ok {\n\t\treturn O.SetItem(i, data)\n\t}\n\td := scratch.Get()\n\tdefer scratch.Put(d)\n\tif err := d.Set(v); err != nil {\n\t\treturn err\n\t}\n\treturn O.SetItem(i, d)\n}", "func process(s []int) {\n s[0] = 100\n}", "func (d *V8interceptor) SetByindex(index int32, object, value *V8value, exception *string) int32 {\n\texception_ := C.cef_string_userfree_alloc()\n\tsetCEFStr(*exception, exception_)\n\tdefer func() {\n\t\t*exception = cefstrToString(exception_)\n\t\tC.cef_string_userfree_free(exception_)\n\t}()\n\treturn int32(C.gocef_v8interceptor_set_byindex(d.toNative(), C.int(index), object.toNative(), value.toNative(), (*C.cef_string_t)(exception_), d.set_byindex))\n}", "func (n *Node) setSuccIndex(node shared.NodeInfo, index int) {\n\tn.update.Lock()\n\n\tn.succList[index] = node\n\n\tn.update.Unlock()\n}", "func (na *NArray) SetValue(v float32) *NArray {\n\n\tfor i := range na.Data {\n\t\tna.Data[i] = v\n\t}\n\treturn na\n}", "func (blood *bloodGeneral) SetByIndex(index int, value float64) {\n\te := reflect.ValueOf(blood).Elem()\n\tfield := e.Field(index)\n\tif field.IsValid() && field.CanSet() && field.Kind() == reflect.Float64 {\n\t\tfield.SetFloat(value)\n\t} else {\n\t\tlog.Panicf(\"Cannot find element with index %d in BloodGeneral struct\", index)\n\t}\n\n\treturn\n}", "func (def *Definition) SetValueWithIndex(name string, index []uint32, x interface{}) error {\n\ttyp, err := def.SearchType(name)\n\tif err != nil {\n\t\tCentral.Log.Debugf(\"Search type error: %v\", err)\n\t\treturn err\n\t}\n\tif len(index) == 2 && typ.Type() != FieldTypeMultiplefield && index[1] > 0 {\n\t\treturn NewGenericError(62)\n\t}\n\tif Central.IsDebugLevel() {\n\t\tCentral.Log.Debugf(\"Set value %s with index=%#v value=%v\", name, index, x)\n\t}\n\tvar val IAdaValue\n\tif !typ.HasFlagSet(FlagOptionPE) {\n\t\tCentral.Log.Debugf(\"Search name ....%s\", name)\n\t\tval = def.Search(name)\n\t\tif val == nil {\n\t\t\treturn NewGenericError(63, name)\n\t\t}\n\t} else {\n\t\tCentral.Log.Debugf(\"Search indexed period group ....%s %d\", name, index)\n\t\tval, err = def.SearchByIndex(name, index, true)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif val == nil {\n\t\t\treturn NewGenericError(127, name)\n\t\t}\n\t}\n\tif Central.IsDebugLevel() {\n\t\tCentral.Log.Debugf(\"Found value to add to %s[%d,%d] type=%v %T %T index=%#v\", val.Type().Name(),\n\t\t\tval.PeriodIndex(), val.MultipleIndex(), val.Type().Type().name(), val, val.Type(), index)\n\t}\n\tswitch val.Type().Type() {\n\tcase FieldTypeMultiplefield:\n\t\tsv := val.(*StructureValue)\n\t\tst := sv.Type().(*StructureType)\n\t\t//sv.Type().\n\t\t//\tsv.Elements = append(sv.Elements, subValue)\n\t\t// if len(sv.Elements) == 0 {\n\t\t// \te := &structureElement{}\n\t\t// \tCentral.Log.Debugf(\"Add empty element to %s\",sv.Type().Name())\n\t\t// \tsv.Elements = append(sv.Elements, e)\n\t\t// }\n\t\t// if len(sv.Elements[0].Values) >= int(index[0]) {\n\t\t// \tCentral.Log.Debugf(\"Adapt %#v\", st.SubTypes)\n\t\t// \tsubValue := sv.Elements[0].Values[int(index[0]-1)]\n\t\t// \terr = subValue.SetValue(x)\n\t\t// } else {\n\t\tsubValue, serr := st.SubTypes[0].Value()\n\t\tif serr != nil {\n\t\t\treturn serr\n\t\t}\n\t\terr = subValue.SetValue(x)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpeIndex := uint32(0)\n\t\tcurIndex := 0\n\t\tif typ.HasFlagSet(FlagOptionPE) {\n\t\t\tif len(index) > 0 {\n\t\t\t\tpeIndex = index[curIndex]\n\t\t\t\tcurIndex++\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"XXX\")\n\t\t\t}\n\t\t}\n\t\tmuIndex := uint32(0)\n\t\tif typ.Type() == FieldTypeMultiplefield || typ.HasFlagSet(FlagOptionMUGhost) {\n\t\t\tif len(index) > curIndex {\n\t\t\t\tmuIndex = index[curIndex]\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"XXX\")\n\t\t\t}\n\t\t}\n\t\tCentral.Log.Debugf(\"Set indexes to PE=%d MU=%d current=%d\", peIndex, muIndex, curIndex)\n\t\terr = sv.addValue(subValue, peIndex, muIndex)\n\t\t// subValue.setMultipleIndex(index[0])\n\t\t// sv.Elements[0].Values = append(sv.Elements[0].Values, subValue)\n\t\t// }\n\t\tif Central.IsDebugLevel() {\n\t\t\tCentral.Log.Debugf(\"Add Multiple field, elements=%d\", len(sv.Elements))\n\t\t}\n\tdefault:\n\t\terr = val.SetValue(x)\n\t}\n\treturn err\n}", "func (k *ArrayKeyring) Set(i Item) error {\n\tif k.items == nil {\n\t\tk.items = map[string]Item{}\n\t}\n\tk.items[i.Key] = i\n\treturn nil\n}", "func (m NMap) Set(key uint32, value interface{}) {\n\tinterMap := m.getInternalNMap(key)\n\tinterMap.Lock()\n\tinterMap.objs[key] = value\n\tinterMap.Unlock()\n}", "func (self *Graphics) SetChildIndexI(args ...interface{}) {\n self.Object.Call(\"setChildIndex\", args)\n}", "func (node *GoValueNode) SetArrayValueAt(index int, value reflect.Value) (err error) {\n\tif node.IsArray() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\terr = fmt.Errorf(\"recovered : %v\", r)\n\t\t\t}\n\t\t}()\n\t\tval := node.thisValue.Index(index)\n\t\tif val.CanAddr() && val.CanSet() {\n\t\t\tif pkg.IsNumber(val) && pkg.IsNumber(value) {\n\n\t\t\t\treturn SetNumberValue(val, value)\n\t\t\t}\n\t\t\tval.Set(value)\n\n\t\t\treturn nil\n\t\t}\n\n\t\treturn fmt.Errorf(\"this node identified as \\\"%s\\\" can not set value on array index %d\", node.IdentifiedAs(), index)\n\t}\n\n\treturn fmt.Errorf(\"this node identified as \\\"%s\\\" is not referencing an array or slice\", node.IdentifiedAs())\n}", "func (s *nodeBlock) insertItemAt(index int, item Metadata) {\n\t_ = s.items[maxItems-1-s.itemsSize]\n\tcopy(s.items[index+1:], s.items[index:])\n\ts.items[index] = item\n\ts.itemsSize++\n\ts.markDirty()\n}", "func (iter *SliceIterator) SetValue(val interface{}) {\n\titer.s.Set(iter.position, val)\n}", "func (f *BatchFuture) Set(index uint64, err error) {\n\tf.index = index\n\tf.err = err\n\tclose(f.waitCh)\n}", "func (e *SkillList) Set(slot uint16, skill Skill) {\n\te.List[int(slot)] = skill\n}", "func lset(writer *reply.Reply, command *resp.Command, store *storage.Storage) {\n if len(command.Key) < 1 || len(command.Args) < 2 {\n writer.SendError(fmt.Errorf(\"LSET expects 3 argument(s)\"))\n return\n }\n value := store.Get(command.Key)\n if value == nil {\n writer.SendNull()\n return\n }\n index, error := strconv.Atoi(command.Args[0])\n if error == nil {\n value.(*structs.List).Set(index, command.Args[1])\n writer.SendString(\"OK\")\n } else {\n writer.SendError(fmt.Errorf(\"Index is not integer\"))\n }\n}", "func (r *Root) Set(ctx context.Context, i uint64, val cbg.CBORMarshaler) error {\n\tif i > MaxIndex {\n\t\treturn fmt.Errorf(\"index %d is out of range for the amt\", i)\n\t}\n\n\tvar d cbg.Deferred\n\tif val == nil {\n\t\td.Raw = cbg.CborNull\n\t} else {\n\t\tvalueBuf := new(bytes.Buffer)\n\t\tif err := val.MarshalCBOR(valueBuf); err != nil {\n\t\t\treturn err\n\t\t}\n\t\td.Raw = valueBuf.Bytes()\n\t}\n\n\t// where the index is greater than the number of elements we can fit into the\n\t// current AMT, grow it until it will fit.\n\tfor i >= nodesForHeight(r.bitWidth, r.height+1) {\n\t\t// if we have existing data, perform the re-height here by pushing down\n\t\t// the existing tree into the left-most portion of a new root\n\t\tif !r.node.empty() {\n\t\t\tnd := r.node\n\t\t\t// since all our current elements fit in the old height, we _know_ that\n\t\t\t// they will all sit under element [0] of this new node.\n\t\t\tr.node = &node{links: make([]*link, 1<<r.bitWidth)}\n\t\t\tr.node.links[0] = &link{\n\t\t\t\tdirty: true,\n\t\t\t\tcached: nd,\n\t\t\t}\n\t\t}\n\t\t// else we still need to add new nodes to form the right height, but we can\n\t\t// defer that to our set() call below which will lazily create new nodes\n\t\t// where it expects there to be some\n\t\tr.height++\n\t}\n\n\taddVal, err := r.node.set(ctx, r.store, r.bitWidth, r.height, i, &d)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif addVal {\n\t\t// Something is wrong, so we'll just do our best to not overflow.\n\t\tif r.count >= (MaxIndex - 1) {\n\t\t\treturn errInvalidCount\n\t\t}\n\t\tr.count++\n\t}\n\n\treturn nil\n}", "func (q *quartileIndex) Set(at int, val bool) {\n\tcur := q.bits.Get(at)\n\tif cur && val {\n\t\treturn\n\t}\n\tif !cur && !val {\n\t\treturn\n\t}\n\tq.bits.Set(at, val)\n\tvar delta int\n\tif val {\n\t\tdelta = 1\n\t} else {\n\t\tdelta = -1\n\t}\n\tfor i, o := range q.offsets {\n\t\tif at < o {\n\t\t\tq.counts[i] += delta\n\t\t}\n\t}\n}", "func (i IndexBlock) Set(blockNum byte, block uint16) {\n\ti[blockNum] = byte(block)\n\ti[256+int(blockNum)] = byte(block >> 8)\n}", "func (d *Deque[T]) Set(pos int, val T) error {\n\tif pos < 0 || pos >= d.size {\n\t\treturn ErrOutOfRange\n\t}\n\tseg, pos := d.pos(pos)\n\td.segmentAt(seg).set(pos, val)\n\treturn nil\n}", "func (matrix *Matrix) setElementAt(row, col, value int) error {\n\tif row < 0 || row >= matrix.getNumRows() || col < 0 || col >= matrix.getNumCols() {\n\t\treturn errors.New(\"index out of bound\")\n\t}\n\tmatrix.Elements[row][col] = value\n\treturn nil\n}" ]
[ "0.7097894", "0.6712408", "0.6652571", "0.66395664", "0.63676316", "0.61507577", "0.61393917", "0.6106026", "0.60874915", "0.603987", "0.602419", "0.60147", "0.5999586", "0.58260477", "0.58074677", "0.57984996", "0.5764004", "0.57576597", "0.57326776", "0.57191527", "0.5716411", "0.57162845", "0.57035315", "0.56765133", "0.56606317", "0.56554043", "0.56433237", "0.5641676", "0.56330305", "0.56278825", "0.5621646", "0.5618114", "0.5594596", "0.55790275", "0.5537019", "0.55193156", "0.5510507", "0.55070615", "0.5483181", "0.54806745", "0.5480396", "0.54735637", "0.5440551", "0.5404083", "0.5384138", "0.53795123", "0.5370791", "0.53696734", "0.5350054", "0.5346634", "0.5333731", "0.53154755", "0.52953416", "0.5278439", "0.52529806", "0.52414316", "0.5231576", "0.5213053", "0.5212095", "0.52004457", "0.51995486", "0.519849", "0.518323", "0.5174477", "0.5160307", "0.5158557", "0.51336193", "0.5120292", "0.5118913", "0.5118623", "0.5107516", "0.50903547", "0.50806326", "0.5078491", "0.5076023", "0.5061938", "0.5051555", "0.5045723", "0.5041599", "0.50403976", "0.5038138", "0.50308037", "0.50211966", "0.50141716", "0.50062484", "0.49924254", "0.49906218", "0.4961639", "0.49569368", "0.49558052", "0.4950193", "0.49460793", "0.49454013", "0.4943914", "0.4942887", "0.49422017", "0.4920673", "0.49083936", "0.4902136", "0.49019727" ]
0.71877056
0
Get the item at index n
func (this *Tuple) Get(n int) interface{} { item := this.data[this.Offset(n)] return item }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 (x IntSlice) Get(i int) interface{} {return x[i]}", "func (vec Vector) Nth(n Number) LangType {\n\tindex := int(n)\n\treturn vec[index]\n}", "func (v Vector) Get(n int) float64 {\n\treturn v.data[n]\n}", "func (arr *ArrayList) Get(index uint32) ItemType {\n if index < arr.length {\n return arr.data[index]\n }\n panic(\"out of bounds\")\n}", "func (n *items) get(i uint32) (*list, error) {\n\tif i > n.len {\n\t\treturn nil, ErrIndexRange\n\t}\n\treturn n.data[i], nil\n}", "func Nth(data interface{}, i int) (interface{}, error) {\n\tvar err error\n\n\tresult := func(err *error) interface{} {\n\t\tdefer catch(err)\n\n\t\tif !isNonNilData(err, \"data\", data) {\n\t\t\treturn nil\n\t\t}\n\n\t\tdataValue, _, _, dataValueLen := inspectData(data)\n\n\t\tif !isSlice(err, \"data\", dataValue) {\n\t\t\treturn nil\n\t\t}\n\n\t\tif dataValueLen == 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\tif i < 0 {\n\t\t\ti = dataValueLen + i\n\t\t}\n\n\t\tif i < dataValueLen {\n\t\t\treturn dataValue.Index(i).Interface()\n\t\t}\n\n\t\treturn nil\n\t}(&err)\n\n\treturn result, err\n}", "func (l *DList) get(i int) *dnode {\n\tif i < l.n/2 {\n\t\tn := l.r.n\n\t\tfor j := 0; j < i; j++ {\n\t\t\tn = n.n\n\t\t}\n\t\treturn n\n\t}\n\tn := l.r\n\tfor j := l.n; j > i; j-- {\n\t\tn = n.p\n\t}\n\treturn n\n}", "func (aa *Array) Get(idx int) interface{} {\n\t// do not lock if not needed\n\tif idx < 0 || idx >= aa.length {\n\t\treturn nil\n\t}\n\n\taa.mutex.RLock()\n\tres := aa.items[idx]\n\taa.mutex.RUnlock()\n\treturn res\n}", "func (list *RecentlyUsedList) Get(index uint) string {\n return list.items[index]\n}", "func (s *Stack) Get(index int) (interface{}, error) {\n\tif index < 0 || index >= s.count {\n\t\treturn nil, fmt.Errorf(\"Requested index %d outside stack, length %d\", index, s.count)\n\t}\n\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tn := s.top\n\tfor i := 1; i < s.count-index; i++ {\n\t\tn = n.next\n\t}\n\n\treturn n.data, nil\n}", "func (t *FenwickTreeSimple) Get(index int) int {\n\treturn t.QueryRange(index, index)\n}", "func (args *Args) at(index int) *Arg {\n\tif len(args.items) > index && index >= 0 {\n\t\treturn args.items[index]\n\t}\n\treturn nil\n}", "func (vn VecN) Get(i int) float64 {\n\treturn vn.vec[i]\n}", "func GetItem(slice []int, index int) int {\n\tif checkOutOfBounds(index, len(slice)) {\n\t\treturn -1\n\t}\n\treturn slice[index]\n}", "func (n Nodes) Index(i int) *Node", "func (sp *Space) Get(index int) Shape {\n\treturn (*sp)[index]\n}", "func (l LinkedList) GetNth(n int) (val datatype, found bool) {\n\tval = errorVal\n\tfound = false\n\tif l.head != nil {\n\t\tcur := l.head\n\t\ti := 0\n\t\tfor {\n\t\t\tif i == n {\n\t\t\t\tval = cur.data\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tif cur.next != nil {\n\t\t\t\t\tcur = cur.next\n\t\t\t\t\ti++\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}\n\treturn val, found\n}", "func (m NumSeriesDistribution) Get(index int) *NumSeries {\n\tif index > -1 {\n\t\tif s, ok := m[index]; ok {\n\t\t\treturn s\n\t\t}\n\t}\n\treturn nil\n}", "func (recv *ValueArray) GetNth(index uint32) *Value {\n\tc_index_ := (C.guint)(index)\n\n\tretC := C.g_value_array_get_nth((*C.GValueArray)(recv.native), c_index_)\n\tretGo := ValueNewFromC(unsafe.Pointer(retC))\n\n\treturn retGo\n}", "func (r *CompanyItemsCollectionRequest) GetN(ctx context.Context, n int) ([]Item, error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\treturn r.Paging(ctx, \"GET\", query, nil, n)\n}", "func (q *Queue) Peek(n int) (item interface{}) {\n item = q.queue[n]\n return\n}", "func (this *MyLinkedList) Get(index int) int {\n\tif index < 0 || index >= this.length {\n\t\treturn -1\n\t}\n\n\treturn this.getNode(index).Val\n\n}", "func (c *Consistent) GetN(name string, n int) ([]string, error) {\n\tc.RLock()\n\tdefer c.RUnlock()\n\n\tif len(c.circle) == 0 {\n\t\treturn nil, ErrEmptyCircle\n\t}\n\n\tif c.count < int64(n) {\n\t\tn = int(c.count)\n\t}\n\n\tvar (\n\t\tkey = c.hashKey(name)\n\t\ti = c.search(key)\n\t\tstart = i\n\t\tres = make([]string, 0, n)\n\t\telem = c.circle[c.sortedHashes[i]]\n\t)\n\n\tres = append(res, elem)\n\n\tif len(res) == n {\n\t\treturn res, nil\n\t}\n\n\tfor i = start + 1; i != start; i++ {\n\t\tif i >= len(c.sortedHashes) {\n\t\t\ti = 0\n\t\t}\n\t\telem = c.circle[c.sortedHashes[i]]\n\t\tif !sliceContainsMember(res, elem) {\n\t\t\tres = append(res, elem)\n\t\t}\n\t\tif len(res) == n {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn res, nil\n}", "func (rw *ReadWrite) GetN(n int) string {\n\tbuf := make([]byte, n)\n\t_, err := io.ReadFull(rw.r, buf)\n\trw.ck(err)\n\treturn hacks.BStoS(buf) // safe since buf doesn't escape\n}", "func (c *Consistent) GetN(name string, n int) ([]string, error) {\n\tc.Mu.RLock()\n\tdefer c.Mu.RUnlock()\n\n\tif len(c.circle) == 0 {\n\t\treturn nil, ErrEmptyCircle\n\t}\n\n\tif c.count < int64(n) {\n\t\tn = int(c.count)\n\t}\n\n\tvar (\n\t\tkey = c.hashKey(name)\n\t\ti = c.search(key)\n\t\tstart = i\n\t\tres = make([]string, 0, n)\n\t\telem = c.circle[c.sortedHashes[i]]\n\t)\n\n\tres = append(res, elem)\n\n\tif len(res) == n {\n\t\treturn res, nil\n\t}\n\n\tfor i = start + 1; i != start; i++ {\n\t\tif i >= len(c.sortedHashes) {\n\t\t\ti = 0\n\t\t}\n\t\telem = c.circle[c.sortedHashes[i]]\n\t\tif !sliceContainsMember(res, elem) {\n\t\t\tres = append(res, elem)\n\t\t}\n\t\tif len(res) == n {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn res, nil\n}", "func (s *IntStack) Get(n int) int{\n\treturn s.stack[n]\n}", "func GetItemAt(list *List, index uint64) *uint64 {\n var returnPtr *uint64;\n if (list.itemCount <= index) { //Check if there are enough items in the list\n PrintString(\"Tried to GetItemAt(\");\n PrintNumber(index);\n PrintString(\") from a list with only \");\n PrintNumber(list.itemCount);\n ExitError(\" items - out of bounds error\", 125);\n }\n returnPtr = ToUint64PtrFromUint64(list.baseAddress + index * list.itemSize);\n return returnPtr; //Get the value on position i of the list (e.g. its corresponding memory) into the return variable\n}", "func (l *List) Get(index int) interface{} {\n\tif index < 0 || index >= l.len {\n\t\treturn -1\n\t}\n\n\tvar cur *Node\n\tif index < l.len/2 { // 从head开始查询\n\t\tcur = l.head\n\t\t// 空节点head的index是0\n\t\tfor i := 0; i < index; i++ {\n\t\t\tcur = cur.next\n\t\t}\n\t} else { // 从tail开始查询\n\t\tcur = l.tail\n\t\tfor i := l.len + 1; i > index; i-- {\n\t\t\tcur = cur.prev\n\t\t}\n\t}\n\n\treturn cur.value\n}", "func (this *MyLinkedList) Get(index int) int {\n\n\tnode := this\n\ti := 0\n\tfor node != nil {\n\t\tif i == index {\n\t\t\treturn node.val\n\t\t}\n\t\ti++\n\t\tnode = node.next\n\t}\n\treturn -1\n}", "func Nth(seq Seq, n uint) interface{} {\n\treturn First(NthRest(seq, n))\n}", "func (l *LinkedList) Index(n int) rtype.ListElement {\n\tvar e rtype.ListElement\n\n\tif n >= 0 {\n\t\te = l.Front()\n\t\tfor i := 0; e != nil && i < n; i++ {\n\t\t\te = e.Next()\n\t\t}\n\t} else {\n\t\te = l.Back()\n\t\tfor i := -1; e != nil && i > n; i-- {\n\t\t\te = e.Prev()\n\t\t}\n\t}\n\n\treturn e\n}", "func (this *LinkedList) Get(index int) interface{} {\n\tif index < 0 || index >= this.Size() {\n\t\tpanic(\"index out of bound\")\n\t}\n\tpe := this.head\n\tfor i := 0; i < index; i++ {\n\t\tpe = pe.next\n\t}\n\treturn pe.elem\n}", "func (a *Array) Get(index int) interface{} {\n\treturn a.Data[index]\n}", "func getNthStash(ctx context.Context, am prolly.AddressMap, count, idx int) (*stashHead, error) {\n\tvar stashList = getStashListOrdered(ctx, am, count)\n\tif count <= idx {\n\t\treturn nil, fmt.Errorf(\"error: stash list only has %v entries\", idx)\n\t}\n\treturn stashList[idx], nil\n}", "func (l *list) get(i int) string {\n\tif i < 0 || i >= l.size {\n\t\tpanic(\"list index out of bounds\")\n\t}\n\tn := l.root\n\tfor ; i!=0; i-- {\n\t\tn = n.next\n\t}\n\treturn n.v\n}", "func (b *Ring) Get(i int) (interface{}, error) {\n\tb.lock.RLock()\n\tdefer b.lock.RUnlock()\n\tif b.size == 0 {\n\t\treturn 0, ErrEmpty\n\t}\n\tposition := Index(i, b.head, b.size, len(b.buf))\n\treturn b.buf[position], nil\n}", "func (this *MyLinkedList) Get(index int) int {\n\tif index < 0 || index > this.size-1 {\n\t\treturn -1\n\t}\n\treturn this.listMap[index].Val\n}", "func (items IntSlice) Value(index int) interface{} { return items[index] }", "func (rb *RingBuffer) Get(index int) (ans stats.Record) {\n\trb.lock.RLock()\n\tdefer rb.lock.RUnlock()\n\tif index < 0 {\n\t\tindex = len(rb.data) + index\n\t}\n\treturn rb.data[(rb.seq+uint64(index))%uint64(len(rb.data))]\n}", "func (q *PriorityQueue) Get(i int) interface{} {\n\t// If indexing backwards, convert to positive index.\n\tif i < 0 {\n\t\ti += q.count\n\t}\n\tif i < 0 || i >= q.count {\n\t\tpanic(\"queue: Get() called with index out of range\")\n\t}\n\t// bitwise modulus\n\treturn q.buf[(q.head+i)&(len(q.buf)-1)]\n}", "func (b *Buffer) Get(n int) []interface{} {\n\t// reset any invalid values\n\tif n > b.size || n < 0 {\n\t\tn = b.size\n\t}\n\n\tb.RLock()\n\tdefer b.RUnlock()\n\n\t// create a delta\n\tdelta := b.size - n\n\n\t// if all the values are less than delta\n\tif len(b.vals) < delta {\n\t\treturn b.vals\n\t}\n\n\t// return the delta set\n\treturn b.vals[delta:]\n}", "func (items *items) get(number int) []interface{} {\n\treturnItems := make([]interface{}, 0, number)\n\tindex := 0\n\n\tfor i := 0; i < number; i++ {\n\t\tif i >= len(*items) {\n\t\t\tbreak\n\t\t}\n\n\t\treturnItems = append(returnItems, (*items)[i])\n\t\t(*items)[i] = nil\n\t\tindex++\n\t}\n\n\t*items = (*items)[index:]\n\treturn returnItems\n}", "func TestNth(t *T) {\n\t// Normal case, in bounds\n\tintl := []interface{}{0, 2, 4, 6, 8}\n\tl := NewList(intl...)\n\tr, ok := l.Nth(3)\n\tassertSaneList(l, t)\n\tassertSeqContents(l, intl, t)\n\tassertValue(r, 6, t)\n\tassertValue(ok, true, t)\n\n\t// Normal case, out of bounds\n\tr, ok = l.Nth(8)\n\tassertSaneList(l, t)\n\tassertSeqContents(l, intl, t)\n\tassertValue(r, nil, t)\n\tassertValue(ok, false, t)\n\n\t// Degenerate case\n\tl = NewList()\n\tr, ok = l.Nth(0)\n\tassertEmpty(l, t)\n\tassertValue(r, nil, t)\n\tassertValue(ok, false, t)\n}", "func TestNth(t *T) {\n\t// Normal case, in bounds\n\tintl := []interface{}{0, 2, 4, 6, 8}\n\tl := NewList(intl...)\n\tr, ok := l.Nth(3)\n\tassertSaneList(l, t)\n\tassert.Equal(t, intl, ToSlice(l))\n\tassert.Equal(t, 6, r)\n\tassert.Equal(t, true, ok)\n\n\t// Normal case, out of bounds\n\tr, ok = l.Nth(8)\n\tassertSaneList(l, t)\n\tassert.Equal(t, intl, ToSlice(l))\n\tassert.Equal(t, nil, r)\n\tassert.Equal(t, false, ok)\n\n\t// Degenerate case\n\tl = NewList()\n\tr, ok = l.Nth(0)\n\tassert.Equal(t, 0, Size(l))\n\tassert.Equal(t, nil, r)\n\tassert.Equal(t, false, ok)\n}", "func (c *Consistent) GetN(name string, n int) ([]string, error) {\n\tc.RLock()\n\tdefer c.RUnlock()\n\n\tif len(c.virtualMap) == 0 {\n\t\treturn nil, ErrEmptyCircle\n\t}\n\n\tif c.GetMachineNum() < n {\n\t\tn = int(c.GetMachineNum())\n\t}\n\n\tvar (\n\t\tkey = c.hashKey(name)\n\t\ti = c.search(key)\n\t\tstart = i\n\t\tres = make([]string, 0, n)\n\t\telem = c.virtualMap[c.circle[i]]\n\t)\n\n\tres = append(res, elem)\n\n\tif len(res) == n {\n\t\treturn res, nil\n\t}\n\n\tfor i = start + 1; i != start; i++ {\n\t\tif i >= len(c.circle) {\n\t\t\ti = 0\n\t\t}\n\t\telem = c.virtualMap[c.circle[i]]\n\t\tif !sliceContainsMember(res, elem) {\n\t\t\tres = append(res, elem)\n\t\t}\n\t\tif len(res) == n {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn res, nil\n}", "func (v *VectorImpl) Get(i int) Value {\n\tif i < 0 || uint(i) >= v.len {\n\t\tpanic(\"Index out of bounds\")\n\t}\n\n\treturn v.sliceFor(uint(i))[i&shiftBitMask]\n}", "func (v variable) At(index int) interface{} {\n\tm, ok := v.store.Get(v.Name)\n\tif !ok {\n\t\treturn nil\n\t}\n\tif intArray, ok := m.([]interface{}); ok {\n\t\tif index < 1 || index > len(intArray) {\n\t\t\treturn nil\n\t\t}\n\t\treturn intArray[index-1]\n\t}\n\tif indexable, ok := m.(core.Indexable); ok {\n\t\treturn indexable.At(index)\n\t}\n\tif sequenceable, ok := m.(core.Sequenceable); ok {\n\t\treturn core.BuildSequence(sequenceable.S().At(index))\n\t}\n\treturn nil\n}", "func (ri *rawItemList) item(i int) []byte {\n\tstartOff := ri.firstOff\n\tif i > 0 {\n\t\tstartOff += ri.cumSize[i-1]\n\t}\n\tlimitOff := ri.firstOff + ri.cumSize[i]\n\treturn ri.bytes[startOff:limitOff]\n}", "func (list *List) Get(index int) (interface{}, bool) {\n\n\tif !list.withinRange(index) {\n\t\treturn nil, false\n\t}\n\n\telement := list.first\n\tfor e := 0; e != index; e, element = e+1, element.next {\n\t}\n\n\treturn element.value, true\n}", "func (this *MyLinkedList) Get(index int) int {\n\n\tfor i := 1; i <= index; i++ {\n\t\tif this.next !=nil {\n\t\t\tthis = this.next\n\t\t}else{\n\t\t\treturn -1\n\t\t}\n\n\t}\n\treturn *this.val\n}", "func (args Arguments) Get(index int) interface{} {\n\tif index+1 > len(args) {\n\t\tpanic(fmt.Sprintf(\"assert: arguments: Cannot call Get(%d) because there are %d argument(s).\", index, len(args)))\n\t}\n\treturn args[index]\n}", "func (l *LinkedList) Get(index int) (interface{}, error) {\n\t// Abort if index is not valid\n\tif index > l.length || index <= 0 {\n\t\treturn -1, errors.New(\"index is not valid. It should be between 1 and the length of the list + 1\")\n\t}\n\n\tp := l.head\n\tfor i := 0; i < index-1; i++ {\n\t\tp = p.next\n\t}\n\treturn p.value, nil\n}", "func(list *List) Get(index int) (interface{}, bool) {\n\tif !list.withinRange(index){\n\t\treturn nil, false\n\t}\n\n\treturn list.elements[index], true\n}", "func (lst List) Nth(n Number) LangType {\n\tnode := lst.head\n\tN := int(n)\n\tfor i := 0; i < N; i++ {\n\t\tnode = node.next\n\t}\n\treturn node.value\n}", "func (pool *FixedBytePool) Get(index int32) []byte {\n\tstart := int(index) * pool.elemSize\n\tend := start + pool.elemSize\n\n\treturn pool.buf[start:end]\n}", "func (p Posts) Get(i int) *Post {\n\treturn p[i]\n}", "func Nth(seq Sequence, n Number) (LangType, error) {\n\tif n < 0 || n >= seq.Len() {\n\t\treturn nil, fmt.Errorf(\"Number out of bounds\")\n\t}\n\treturn seq.Nth(n), nil\n}", "func (ll *LinkedList) Get(index uint) interface{} {\n\tll.RLock()\n\tdefer ll.RUnlock()\n\n\tif index >= ll.size {\n\t\treturn nil\n\t}\n\n\tif index == 0 {\n\t\treturn ll.head.data\n\t}\n\n\tif index == (ll.size - 1) {\n\t\treturn ll.tail.data\n\t}\n\n\tnode := ll.findNode(index)\n\treturn node.data\n}", "func (r *PolicySetItemsCollectionRequest) GetN(ctx context.Context, n int) ([]PolicySetItem, error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\treturn r.Paging(ctx, \"GET\", query, nil, n)\n}", "func (list *MyLinkedList) Get(index int) int {\n\tif index < 0 || index >= list.len {\n\t\treturn -1\n\t}\n\n\tp := list.head\n\tfor i := 0; i < index; i++ {\n\t\tp = p.next\n\t}\n\treturn p.val\n}", "func (sll *SingleLinkedList) Get(index int) interface{} {\n\treturn sll.getNode(index).value\n}", "func (x *Index) Lookup(s []byte, n int) (result []int) {}", "func (a ASTNode) Index(n int) ASTNode {\n\tif n >= a.Len() {\n\t\tpanic(ConfErr{a.pos, errors.New(\"Index out of bounds\")})\n\t}\n\treturn a.val.(astArr)[n]\n}", "func (d *DynamicArr) Get(index int) (interface{}, error) {\n\tif index < 0 || index > (d.capacity-1) {\n\t\treturn nil, errors.New(\"Index out of range\")\n\t}\n\treturn d.array[index], nil\n}", "func (s *VectorImplSlice) Get(i int) Value {\n\tif i < 0 || s.start+i >= s.stop {\n\t\tpanic(\"Index out of bounds\")\n\t}\n\n\treturn s.vector.Get(s.start + i)\n}", "func (seq List) Value(i int) interface{} { return seq[i] }", "func (list elemlist) At(index int) interface{} {\n\tvar foundItem interface{}\n\n\tif index < len(list.elements) {\n\t\tfoundItem = list.elements[index]\n\t}\n\n\treturn foundItem\n}", "func (list *PyList) GetItem(index int) *PyObject {\n\tptr := C.PyList_GetItem(list.ptr, C.long(index))\n\tif ptr != nil {\n\t\treturn &PyObject{ptr}\n\t}\n\n\treturn nil\n}", "func (l *log) get(index int) *Entry {\n\tif index < len(l.entries) {\n\t\treturn l.entries[index]\n\t}\n\treturn nil\n}", "func get(i int, b [][]byte) (res []byte, err error) {\n\terr = nil\n\tif len(b) > i {\n\t\tres = b[i]\n\t\treturn\n\t}\n\terr = errors.New(\"invalid index\")\n\treturn\n}", "func (this *MyLinkedList) Get(index int) int {\n\tif this.head == nil {\n\t\treturn -1\n\t}\n\ttail, i := this.head, 0\n\tfor tail != nil && i < index {\n\t\ttail = tail.next\n\t\ti++\n\t}\n\tif i == index && tail != nil {\n\t\treturn tail.val\n\t}\n\treturn -1\n}", "func (r *Ring) get(p int) interface{} {\n\treturn r.buff[r.mod(p)]\n}", "func (this *MyLinkedList) Get(index int) int {\n\tcurr := this.GetNode(index)\n\tif curr != nil {\n\t\treturn curr.Val\n\t}\n\treturn -1\n}", "func (r *ScheduleOpenShiftsCollectionRequest) GetN(ctx context.Context, n int) ([]OpenShift, error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\treturn r.Paging(ctx, \"GET\", query, nil, n)\n}", "func (m *Mailboxes) Get(n int) (string, error) {\n\tif n > len(m.mem)-1 {\n\t\treturn \"\", ErrInvalidMemory{n}\n\t}\n\n\tif n < 0 {\n\t\treturn \"\", ErrInvalidMemory{n}\n\t}\n\n\treturn m.mem[n], nil\n}", "func (c *Termination) Get(n int) Value {\n\tif n >= c.pushIndex {\n\t\treturn NilValue\n\t}\n\treturn c.args[n]\n}", "func (buf *ListBuffer) Get(idx BufferIndex) (Item, *error.Error) {\n\tinRange, initialized := buf.legalIndex(idx)\n\tif !inRange {\n\t\tdesc := fmt.Sprintf(\n\t\t\t\"idx, %d, is out of range for IndexBuffer of length %d.\",\n\t\t\tidx, len(buf.Buffer),\n\t\t)\n\t\treturn Item{}, error.New(error.Value, desc)\n\t} else if !initialized {\n\t\tdesc := fmt.Sprintf(\n\t\t\t\"Item at idx, %d, has the Type value Uninitialized.\", idx,\n\t\t)\n\t\treturn Item{}, error.New(error.Value, desc)\n\t}\n\n\treturn buf.Buffer[idx].Item, nil\n}", "func (list *ArrayList[T]) Get(index int) (T, bool) {\n\tif index < 0 || index >= list.Size() {\n\t\tvar zero T\n\t\treturn zero, false\n\t}\n\treturn list.elems[index], true\n}", "func (ss *SharedStrings) get(index int) *ml.StringItem {\n\tss.file.LoadIfRequired(ss.afterLoad)\n\n\tif index < len(ss.ml.StringItem) {\n\t\treturn ss.ml.StringItem[index]\n\t}\n\n\treturn nil\n}", "func (i *NthInt) Nth(n int64) int64 {\n\tresult, ok := i.SafeNth(n)\n\tif !ok {\n\t\tpanic(kNoMoreValues)\n\t}\n\treturn result\n}", "func (v *Posit16x2) Get(i int) Posit16 { return v.impl[i] }", "func (r *PostExtensionsCollectionRequest) GetN(ctx context.Context, n int) ([]Extension, error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\treturn r.Paging(ctx, \"GET\", query, nil, n)\n}", "func (r *Result) GetxN(index int) Nullable {\n\tif index < 0 || index >= len(r.val.columns) {\n\t\tpanic(ErrorColumnNotFound{At: \"GetxN\", Index: index})\n\t}\n\treturn r.val.buffer[index]\n}", "func (x *Index) Lookup(s []byte, n int) (result []int)", "func (this *MyLinkedList) Get(index int) int {\n\tif index < 0 || index >= this.Length {\n\t\treturn -1\n\t}\n\tnode := this.Head\n\tfor i := 0; i < index+1; i++ {\n\t\tnode = node.Next\n\t}\n\treturn node.Val\n}", "func (b *Bag) ItemAt(index int) *Item {\n\treturn &b.items[index]\n}", "func (bits *BitArray) Get(n int) (int, error) {\n\tif err := bits.indexOutOfRange(n); err != nil {\n\t\treturn 0, err\n\t}\n\treturn int((bits.bytes[n/8] >> byte(n%8)) & 1), nil\n}", "func (nl *nodeList) at(i int) *Node {\n\tif i > len(nl.elements) - 1 || i < 0 {\n\t\treturn nil\n\t}\n\n\treturn nl.elements[i]\n}", "func (r *ObjectsListingXact) PeekN(n uint) (result []*cmn.BucketEntry, err error) {\n\tr.mtx.Lock()\n\tdefer r.mtx.Unlock()\n\treturn r.peekN(n)\n}", "func (list *ArrayList) Get(index int) (interface{}, bool) {\n\n\tif !list.withinRange(index) {\n\t\treturn nil, false\n\t}\n\n\treturn list.elements[index], true\n}", "func (list *ArrayList) Get(index int) (interface{}, bool) {\n\tif !list.boundCheck(index) {\n\t\treturn nil, false\n\t}\n\n\treturn list.elements[index], true\n}", "func (l *list) ElementAt(index int) interface{} {\n\treturn l.elements[index]\n}", "func (a *Args) Get(i int) string {\n\tif i < 0 || i >= a.Size() {\n\t\tfmt.Fprintf(os.Stderr, \"Args: Index out of range: %d [0, %d)\\n\", i, a.Size())\n\t\tos.Exit(1)\n\t}\n\n\treturn a.vals[i]\n}", "func (lst *List) GetAt(idx int) *ListNode{\n\tif(idx < 0 || idx > lst.Len){\n\t\tpanic(\"index is out of boundary\")\n\t}\n\n\tcur := lst.Head\n\tfor idx > 0{\n\t\tcur = cur.Next\n\t\tidx--\n\t}\n\treturn cur\n}", "func (wl *W3CNodeList) Item(i int) w3cdom.Node {\n\tif wl == nil {\n\t\treturn nil\n\t}\n\tif i >= len(wl.nodes) || i < 0 {\n\t\treturn nil\n\t}\n\treturn wl.nodes[i]\n}", "func (array *Array) GetAtIndex(index int) interface{} {\n\treturn array.data[index]\n}", "func (column *ColumnInt) GetItem(i int) interface{} {\n\treturn interface{}(column.data[i])\n}", "func (r *OrganizationExtensionsCollectionRequest) GetN(ctx context.Context, n int) ([]Extension, error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\treturn r.Paging(ctx, \"GET\", query, nil, n)\n}", "func (cache *Cache) GetAt(seqno uint16, index uint16, result []byte) uint16 {\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\n\tif int(index) >= len(cache.entries) {\n\t\treturn 0\n\t}\n\tif cache.entries[index].seqno != seqno {\n\t\treturn 0\n\t}\n\treturn uint16(copy(\n\t\tresult[:cache.entries[index].length()],\n\t\tcache.entries[index].buf[:]),\n\t)\n}" ]
[ "0.69591784", "0.68500954", "0.6801328", "0.67986214", "0.6686829", "0.6668928", "0.6519483", "0.64061666", "0.6406025", "0.63965154", "0.6371232", "0.6356444", "0.63045317", "0.62474483", "0.6244136", "0.6197162", "0.6170432", "0.61660874", "0.61195743", "0.60703903", "0.60677075", "0.60665745", "0.6062595", "0.6055664", "0.60419", "0.60410017", "0.60112834", "0.59822893", "0.5979816", "0.5975759", "0.5967656", "0.59480816", "0.59152126", "0.59040713", "0.58889586", "0.58860576", "0.5876022", "0.5864145", "0.58572847", "0.58553135", "0.58451605", "0.5832449", "0.5819559", "0.58074343", "0.57985437", "0.5791186", "0.57806605", "0.5777719", "0.57722527", "0.5763171", "0.57607716", "0.57594204", "0.5757458", "0.5752499", "0.57517666", "0.5746817", "0.57419014", "0.57411486", "0.5731371", "0.57138866", "0.5710705", "0.57054126", "0.5688943", "0.568619", "0.56861734", "0.5681413", "0.56726164", "0.56684345", "0.56664777", "0.5665923", "0.5665829", "0.5665217", "0.5662454", "0.5660011", "0.56571066", "0.56547487", "0.5648527", "0.5636294", "0.56352746", "0.56346875", "0.56296384", "0.5609803", "0.559539", "0.55887455", "0.5587799", "0.5584063", "0.5575796", "0.557564", "0.55738544", "0.55624205", "0.5561472", "0.55600214", "0.55521876", "0.5547367", "0.5545621", "0.5539399", "0.5534553", "0.55298555", "0.55177844", "0.5514908" ]
0.7399889
0