_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q25700
GetPV
train
func (cache *VolumeCache) GetPV(pvName string) (*v1.PersistentVolume, bool) { cache.mutex.Lock() defer cache.mutex.Unlock() pv, exists := cache.pvs[pvName] return pv, exists }
go
{ "resource": "" }
q25701
AddPV
train
func (cache *VolumeCache) AddPV(pv *v1.PersistentVolume) { cache.mutex.Lock() defer cache.mutex.Unlock() cache.pvs[pv.Name] = pv glog.Infof("Added pv %q to cache", pv.Name) }
go
{ "resource": "" }
q25702
DeletePV
train
func (cache *VolumeCache) DeletePV(pvName string) { cache.mutex.Lock() defer cache.mutex.Unlock() delete(cache.pvs, pvName) glog.Infof("Deleted pv %q from cache", pvName) }
go
{ "resource": "" }
q25703
ListPVs
train
func (cache *VolumeCache) ListPVs() []*v1.PersistentVolume { cache.mutex.Lock() defer cache.mutex.Unlock() pvs := []*v1.PersistentVolume{} for _, pv := range cache.pvs { pvs = append(pvs, pv) } return pvs }
go
{ "resource": "" }
q25704
Setup
train
func Setup(ganeshaConfig string, gracePeriod uint) error { // Start rpcbind if it is not started yet cmd := exec.Command("/usr/sbin/rpcinfo", "127.0.0.1") if err := cmd.Run(); err != nil { cmd = exec.Command("/usr/sbin/rpcbind", "-w") if out, err := cmd.CombinedOutput(); err != nil { return fmt.Errorf("Starti...
go
{ "resource": "" }
q25705
NewGlusterBlockProvisioner
train
func NewGlusterBlockProvisioner(client kubernetes.Interface, id string) controller.Provisioner { return &glusterBlockProvisioner{ client: client, identity: id, } }
go
{ "resource": "" }
q25706
createVolume
train
func (p *glusterBlockProvisioner) createVolume(volSizeInt int, blockVol string, config *provisionerConfig) (*glusterBlockVolume, error) { blockRes := &glusterBlockVolume{} sizeStr := strconv.Itoa(volSizeInt) haCountStr := strconv.Itoa(config.haCount) klog.V(2).Infof("create block volume of size %d and configurat...
go
{ "resource": "" }
q25707
sortTargetPortal
train
func (p *glusterBlockProvisioner) sortTargetPortal(vol *iscsiSpec) error { if len(vol.Portals) == 0 { return fmt.Errorf("portal is empty") } if len(vol.Portals) == 1 && vol.Portals[0] != "" { vol.TargetPortal = vol.Portals[0] vol.Portals = nil } else { portals := vol.Portals vol.Portals = nil for _, v ...
go
{ "resource": "" }
q25708
IsBlock
train
func (u *volumeUtil) IsBlock(fullPath string) (bool, error) { return false, fmt.Errorf("IsBlock is unsupported in this build") }
go
{ "resource": "" }
q25709
mapToAWSVolumeID
train
func (name KubernetesVolumeID) mapToAWSVolumeID() (awsVolumeID, error) { // name looks like aws://availability-zone/awsVolumeId // The original idea of the URL-style name was to put the AZ into the // host, so we could find the AZ immediately from the name without // querying the API. But it turns out we don't ac...
go
{ "resource": "" }
q25710
LoadBalancer
train
func (os *OpenStack) LoadBalancer() (cloudprovider.LoadBalancer, bool) { glog.V(4).Info("openstack.LoadBalancer() called") // TODO: Search for and support Rackspace loadbalancer API, and others. network, err := os.NewNetworkV2() if err != nil { return nil, false } compute, err := os.NewComputeV2() if err != ...
go
{ "resource": "" }
q25711
Routes
train
func (os *OpenStack) Routes() (cloudprovider.Routes, bool) { glog.V(4).Info("openstack.Routes() called") network, err := os.NewNetworkV2() if err != nil { return nil, false } netExts, err := networkExtensions(network) if err != nil { glog.Warningf("Failed to list neutron extensions: %v", err) return nil, ...
go
{ "resource": "" }
q25712
Zones
train
func (os *OpenStack) Zones() (cloudprovider.Zones, bool) { glog.V(1).Info("Claiming to support Zones") return os, true }
go
{ "resource": "" }
q25713
GetZone
train
func (os *OpenStack) GetZone() (cloudprovider.Zone, error) { md, err := getMetadata() if err != nil { return cloudprovider.Zone{}, err } zone := cloudprovider.Zone{ FailureDomain: md.AvailabilityZone, Region: os.region, } glog.V(1).Infof("Current zone is %v", zone) return zone, nil }
go
{ "resource": "" }
q25714
NewVolumeSnapshotter
train
func NewVolumeSnapshotter( restClient *rest.RESTClient, scheme *runtime.Scheme, clientset kubernetes.Interface, asw cache.ActualStateOfWorld, volumePlugins *map[string]volume.Plugin) VolumeSnapshotter { return &volumeSnapshotter{ restClient: restClient, coreClient: clientset, scheme: ...
go
{ "resource": "" }
q25715
getPVFromVolumeSnapshot
train
func (vs *volumeSnapshotter) getPVFromVolumeSnapshot(uniqueSnapshotName string, snapshot *crdv1.VolumeSnapshot) (*v1.PersistentVolume, error) { pvcName := snapshot.Spec.PersistentVolumeClaimName if pvcName == "" { return nil, fmt.Errorf("The PVC name is not specified in snapshot %s", uniqueSnapshotName) } pvc, e...
go
{ "resource": "" }
q25716
getPVFromName
train
func (vs *volumeSnapshotter) getPVFromName(pvName string) (*v1.PersistentVolume, error) { return vs.coreClient.CoreV1().PersistentVolumes().Get(pvName, metav1.GetOptions{}) }
go
{ "resource": "" }
q25717
getSnapshotDataFromSnapshot
train
func (vs *volumeSnapshotter) getSnapshotDataFromSnapshot(snapshot *crdv1.VolumeSnapshot) (*crdv1.VolumeSnapshotData, error) { var snapshotDataObj crdv1.VolumeSnapshotData snapshotDataName := snapshot.Spec.SnapshotDataName if snapshotDataName == "" { return nil, fmt.Errorf("Could not find snapshot data object: Snap...
go
{ "resource": "" }
q25718
updateSnapshotIfExists
train
func (vs *volumeSnapshotter) updateSnapshotIfExists(uniqueSnapshotName string, snapshot *crdv1.VolumeSnapshot) (string, *crdv1.VolumeSnapshot, error) { snapshotName := snapshot.Metadata.Name var snapshotDataObj *crdv1.VolumeSnapshotData var snapshotDataSource *crdv1.VolumeSnapshotDataSource var conditions *[]crdv1....
go
{ "resource": "" }
q25719
syncSnapshot
train
func (vs *volumeSnapshotter) syncSnapshot(uniqueSnapshotName string, snapshot *crdv1.VolumeSnapshot) func() error { return func() error { snapshotObj := snapshot status := vs.getSimplifiedSnapshotStatus(snapshot.Status.Conditions) var err error // When the condition is new, it is still possible that snapshot i...
go
{ "resource": "" }
q25720
createSnapshot
train
func (vs *volumeSnapshotter) createSnapshot(uniqueSnapshotName string, snapshot *crdv1.VolumeSnapshot) error { var snapshotDataSource *crdv1.VolumeSnapshotDataSource var snapStatus *[]crdv1.VolumeSnapshotCondition var err error var tags *map[string]string glog.Infof("createSnapshot: Creating snapshot %s through th...
go
{ "resource": "" }
q25721
updateVolumeSnapshotMetadata
train
func (vs *volumeSnapshotter) updateVolumeSnapshotMetadata(snapshot *crdv1.VolumeSnapshot, pvName string) (*map[string]string, error) { glog.Infof("In updateVolumeSnapshotMetadata") var snapshotObj crdv1.VolumeSnapshot // Need to get a fresh copy of the VolumeSnapshot from the API server err := vs.restClient.Get(). ...
go
{ "resource": "" }
q25722
propagateVolumeSnapshotCondition
train
func (vs *volumeSnapshotter) propagateVolumeSnapshotCondition(snapshotDataName string, condition *crdv1.VolumeSnapshotCondition) error { var snapshotDataObj crdv1.VolumeSnapshotData err := vs.restClient.Get(). Name(snapshotDataName). Resource(crdv1.VolumeSnapshotDataResourcePlural). Do().Into(&snapshotDataObj) ...
go
{ "resource": "" }
q25723
UpdateVolumeSnapshotStatus
train
func (vs *volumeSnapshotter) UpdateVolumeSnapshotStatus(snapshot *crdv1.VolumeSnapshot, condition *crdv1.VolumeSnapshotCondition) (*crdv1.VolumeSnapshot, error) { var snapshotObj crdv1.VolumeSnapshot err := vs.restClient.Get(). Name(snapshot.Metadata.Name). Resource(crdv1.VolumeSnapshotResourcePlural). Namespa...
go
{ "resource": "" }
q25724
bindandUpdateVolumeSnapshot
train
func (vs *volumeSnapshotter) bindandUpdateVolumeSnapshot(snapshot *crdv1.VolumeSnapshot, snapshotDataName string, status *[]crdv1.VolumeSnapshotCondition) (*crdv1.VolumeSnapshot, error) { var snapshotObj crdv1.VolumeSnapshot glog.Infof("In bindVolumeSnapshotDataToVolumeSnapshot") // Get a fresh copy of the VolumeSn...
go
{ "resource": "" }
q25725
getClassForVolume
train
func (p *nfsProvisioner) getClassForVolume(pv *v1.PersistentVolume) (*storage.StorageClass, error) { if p.client == nil { return nil, fmt.Errorf("Cannot get kube client") } className := helper.GetPersistentVolumeClass(pv) if className == "" { return nil, fmt.Errorf("Volume has no storage class") } class, err ...
go
{ "resource": "" }
q25726
NewDesiredStateOfWorldPopulator
train
func NewDesiredStateOfWorldPopulator( loopSleepDuration time.Duration, listSnapshotsRetryDuration time.Duration, snapshotStore k8scache.Store, desiredStateOfWorld cache.DesiredStateOfWorld) DesiredStateOfWorldPopulator { return &desiredStateOfWorldPopulator{ loopSleepDuration: loopSleepDuration, listS...
go
{ "resource": "" }
q25727
NewDriverCall
train
func (plugin *flexProvisioner) NewDriverCall(execPath, command string) *DriverCall { return plugin.NewDriverCallWithTimeout(execPath, command, 0) }
go
{ "resource": "" }
q25728
NewDriverCallWithTimeout
train
func (plugin *flexProvisioner) NewDriverCallWithTimeout(execPath, command string, timeout time.Duration) *DriverCall { return &DriverCall{ Execpath: execPath, Command: command, Timeout: timeout, plugin: plugin, args: []string{command}, } }
go
{ "resource": "" }
q25729
AppendSpec
train
func (dc *DriverCall) AppendSpec(volumeOptions, extraOptions map[string]string) error { optionsForDriver, err := NewOptionsForDriver(volumeOptions, extraOptions) if err != nil { return err } jsonBytes, err := json.Marshal(optionsForDriver) if err != nil { return fmt.Errorf("Failed to marshal spec, error: %s",...
go
{ "resource": "" }
q25730
Run
train
func (dc *DriverCall) Run() (*DriverStatus, error) { cmd := dc.plugin.runner.Command(dc.Execpath, dc.args...) timeout := false if dc.Timeout > 0 { timer := time.AfterFunc(dc.Timeout, func() { timeout = true cmd.Stop() }) defer timer.Stop() } output, execErr := cmd.CombinedOutput() if execErr != nil ...
go
{ "resource": "" }
q25731
NewOptionsForDriver
train
func NewOptionsForDriver(volumeOptions, extraOptions map[string]string) (OptionsForDriver, error) { options := map[string]string{} for key, value := range extraOptions { options[key] = value } for key, value := range volumeOptions { options[key] = value } return OptionsForDriver(options), nil }
go
{ "resource": "" }
q25732
NewJobController
train
func NewJobController(labelmap map[string]string, config *common.RuntimeConfig) (JobController, error) { namespace := config.Namespace queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()) labelset := labels.Set(labelmap) optionsModifier := func(options *meta_v1.ListOptions) { options....
go
{ "resource": "" }
q25733
processNextItem
train
func (c *jobController) processNextItem() bool { key, quit := c.queue.Get() if quit { return false } defer c.queue.Done(key) err := c.processItem(key.(string)) if err == nil { // No error, tell the queue to stop tracking history c.queue.Forget(key) } else if c.queue.NumRequeues(key) < maxRetries { glog...
go
{ "resource": "" }
q25734
IsCleaningJobRunning
train
func (c *jobController) IsCleaningJobRunning(pvName string) bool { jobName := generateCleaningJobName(pvName) job, err := c.jobLister.Jobs(c.namespace).Get(jobName) if errors.IsNotFound(err) { return false } if err != nil { glog.Warningf("Failed to check whether job %s is running (%s). Assuming its still runn...
go
{ "resource": "" }
q25735
RemoveJob
train
func (c *jobController) RemoveJob(pvName string) (CleanupState, *time.Time, error) { jobName := generateCleaningJobName(pvName) job, err := c.jobLister.Jobs(c.namespace).Get(jobName) if err != nil { if errors.IsNotFound(err) { return CSNotFound, nil, nil } return CSUnknown, nil, fmt.Errorf("Failed to check ...
go
{ "resource": "" }
q25736
NewCleanupJob
train
func NewCleanupJob(pv *apiv1.PersistentVolume, volMode apiv1.PersistentVolumeMode, imageName string, nodeName string, namespace string, mountPath string, config common.MountConfig) (*batch_v1.Job, error) { priv := true // Container definition jobContainer := apiv1.Container{ Name: JobContainerName, Image: imag...
go
{ "resource": "" }
q25737
IsCleaningJobRunning
train
func (c *FakeJobController) IsCleaningJobRunning(pvName string) bool { c.IsRunningCount++ _, exists := c.pvCleanupRunning[pvName] return exists }
go
{ "resource": "" }
q25738
RemoveJob
train
func (c *FakeJobController) RemoveJob(pvName string) (CleanupState, *time.Time, error) { c.RemoveCompletedCount++ status, exists := c.pvCleanupRunning[pvName] if !exists { return CSNotFound, nil, nil } if status != CSSucceeded { return CSUnknown, nil, fmt.Errorf("cannot remove job that has not yet completed %s...
go
{ "resource": "" }
q25739
NewOpenEBSProvisioner
train
func NewOpenEBSProvisioner(client kubernetes.Interface) controller.Provisioner { nodeName := os.Getenv("NODE_NAME") if nodeName == "" { glog.Errorf("ENV variable 'NODE_NAME' is not set") } var openebsObj mApiv1.OpenEBSVolume //Get maya-apiserver IP address from cluster addr, err := openebsObj.GetMayaClusterIP...
go
{ "resource": "" }
q25740
AddSnapshot
train
func (asw *actualStateOfWorld) AddSnapshot(snapshot *crdv1.VolumeSnapshot) error { asw.Lock() defer asw.Unlock() snapshotName := MakeSnapshotName(snapshot) glog.Infof("Adding new snapshot to actual state of world: %s", snapshotName) asw.snapshots[snapshotName] = snapshot return nil }
go
{ "resource": "" }
q25741
DeleteSnapshot
train
func (asw *actualStateOfWorld) DeleteSnapshot(snapshotName string) error { asw.Lock() defer asw.Unlock() glog.Infof("Deleting snapshot from actual state of world: %s", snapshotName) delete(asw.snapshots, snapshotName) return nil }
go
{ "resource": "" }
q25742
Each
train
func Each(array []interface{}, iterator Iterator) { for index, data := range array { iterator(data, index) } }
go
{ "resource": "" }
q25743
Map
train
func Map(array []interface{}, iterator ResultIterator) []interface{} { var result = make([]interface{}, len(array)) for index, data := range array { result[index] = iterator(data, index) } return result }
go
{ "resource": "" }
q25744
Find
train
func Find(array []interface{}, iterator ConditionIterator) interface{} { for index, data := range array { if iterator(data, index) { return data } } return nil }
go
{ "resource": "" }
q25745
Filter
train
func Filter(array []interface{}, iterator ConditionIterator) []interface{} { var result = make([]interface{}, 0) for index, data := range array { if iterator(data, index) { result = append(result, data) } } return result }
go
{ "resource": "" }
q25746
Count
train
func Count(array []interface{}, iterator ConditionIterator) int { count := 0 for index, data := range array { if iterator(data, index) { count = count + 1 } } return count }
go
{ "resource": "" }
q25747
LeftTrim
train
func LeftTrim(str, chars string) string { if chars == "" { return strings.TrimLeftFunc(str, unicode.IsSpace) } r, _ := regexp.Compile("^[" + chars + "]+") return r.ReplaceAllString(str, "") }
go
{ "resource": "" }
q25748
RightTrim
train
func RightTrim(str, chars string) string { if chars == "" { return strings.TrimRightFunc(str, unicode.IsSpace) } r, _ := regexp.Compile("[" + chars + "]+$") return r.ReplaceAllString(str, "") }
go
{ "resource": "" }
q25749
Trim
train
func Trim(str, chars string) string { return LeftTrim(RightTrim(str, chars), chars) }
go
{ "resource": "" }
q25750
WhiteList
train
func WhiteList(str, chars string) string { pattern := "[^" + chars + "]+" r, _ := regexp.Compile(pattern) return r.ReplaceAllString(str, "") }
go
{ "resource": "" }
q25751
ReplacePattern
train
func ReplacePattern(str, pattern, replace string) string { r, _ := regexp.Compile(pattern) return r.ReplaceAllString(str, replace) }
go
{ "resource": "" }
q25752
Reverse
train
func Reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) }
go
{ "resource": "" }
q25753
GetLine
train
func GetLine(s string, index int) (string, error) { lines := GetLines(s) if index < 0 || index >= len(lines) { return "", errors.New("line index out of bounds") } return lines[index], nil }
go
{ "resource": "" }
q25754
SafeFileName
train
func SafeFileName(str string) string { name := strings.ToLower(str) name = path.Clean(path.Base(name)) name = strings.Trim(name, " ") separators, err := regexp.Compile(`[ &_=+:]`) if err == nil { name = separators.ReplaceAllString(name, "-") } legal, err := regexp.Compile(`[^[:alnum:]-.]`) if err == nil { n...
go
{ "resource": "" }
q25755
Truncate
train
func Truncate(str string, length int, ending string) string { var aftstr, befstr string if len(str) > length { words := strings.Fields(str) before, present := 0, 0 for i := range words { befstr = aftstr before = present aftstr = aftstr + words[i] + " " present = len(aftstr) if present > length &&...
go
{ "resource": "" }
q25756
PadLeft
train
func PadLeft(str string, padStr string, padLen int) string { return buildPadStr(str, padStr, padLen, true, false) }
go
{ "resource": "" }
q25757
PadBoth
train
func PadBoth(str string, padStr string, padLen int) string { return buildPadStr(str, padStr, padLen, true, true) }
go
{ "resource": "" }
q25758
buildPadStr
train
func buildPadStr(str string, padStr string, padLen int, padLeft bool, padRight bool) string { // When padded length is less then the current string size if padLen < utf8.RuneCountInString(str) { return str } padLen -= utf8.RuneCountInString(str) targetLen := padLen targetLenLeft := targetLen targetLenRight...
go
{ "resource": "" }
q25759
TruncatingErrorf
train
func TruncatingErrorf(str string, args ...interface{}) error { n := strings.Count(str, "%s") return fmt.Errorf(str, args[:n]...) }
go
{ "resource": "" }
q25760
ToJSON
train
func ToJSON(obj interface{}) (string, error) { res, err := json.Marshal(obj) if err != nil { res = []byte("") } return string(res), err }
go
{ "resource": "" }
q25761
ToFloat
train
func ToFloat(str string) (float64, error) { res, err := strconv.ParseFloat(str, 64) if err != nil { res = 0.0 } return res, err }
go
{ "resource": "" }
q25762
ToInt
train
func ToInt(value interface{}) (res int64, err error) { val := reflect.ValueOf(value) switch value.(type) { case int, int8, int16, int32, int64: res = val.Int() case uint, uint8, uint16, uint32, uint64: res = int64(val.Uint()) case string: if IsInt(val.String()) { res, err = strconv.ParseInt(val.String(),...
go
{ "resource": "" }
q25763
InRange
train
func InRange(value interface{}, left interface{}, right interface{}) bool { reflectValue := reflect.TypeOf(value).Kind() reflectLeft := reflect.TypeOf(left).Kind() reflectRight := reflect.TypeOf(right).Kind() if reflectValue == reflect.Int && reflectLeft == reflect.Int && reflectRight == reflect.Int { return In...
go
{ "resource": "" }
q25764
IsExistingEmail
train
func IsExistingEmail(email string) bool { if len(email) < 6 || len(email) > 254 { return false } at := strings.LastIndex(email, "@") if at <= 0 || at > len(email)-3 { return false } user := email[:at] host := email[at+1:] if len(user) > 64 { return false } if userDotRegexp.MatchString(user) || !userReg...
go
{ "resource": "" }
q25765
IsRequestURL
train
func IsRequestURL(rawurl string) bool { url, err := url.ParseRequestURI(rawurl) if err != nil { return false //Couldn't even parse the rawurl } if len(url.Scheme) == 0 { return false //No Scheme found } return true }
go
{ "resource": "" }
q25766
IsRequestURI
train
func IsRequestURI(rawurl string) bool { _, err := url.ParseRequestURI(rawurl) return err == nil }
go
{ "resource": "" }
q25767
IsLowerCase
train
func IsLowerCase(str string) bool { if IsNull(str) { return true } return str == strings.ToLower(str) }
go
{ "resource": "" }
q25768
IsUpperCase
train
func IsUpperCase(str string) bool { if IsNull(str) { return true } return str == strings.ToUpper(str) }
go
{ "resource": "" }
q25769
HasLowerCase
train
func HasLowerCase(str string) bool { if IsNull(str) { return true } return rxHasLowerCase.MatchString(str) }
go
{ "resource": "" }
q25770
HasUpperCase
train
func HasUpperCase(str string) bool { if IsNull(str) { return true } return rxHasUpperCase.MatchString(str) }
go
{ "resource": "" }
q25771
IsInt
train
func IsInt(str string) bool { if IsNull(str) { return true } return rxInt.MatchString(str) }
go
{ "resource": "" }
q25772
IsFullWidth
train
func IsFullWidth(str string) bool { if IsNull(str) { return true } return rxFullWidth.MatchString(str) }
go
{ "resource": "" }
q25773
IsHalfWidth
train
func IsHalfWidth(str string) bool { if IsNull(str) { return true } return rxHalfWidth.MatchString(str) }
go
{ "resource": "" }
q25774
IsVariableWidth
train
func IsVariableWidth(str string) bool { if IsNull(str) { return true } return rxHalfWidth.MatchString(str) && rxFullWidth.MatchString(str) }
go
{ "resource": "" }
q25775
IsFilePath
train
func IsFilePath(str string) (bool, int) { if rxWinPath.MatchString(str) { //check windows path limit see: // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath if len(str[3:]) > 32767 { return false, Win } return true, Win } else if rxUnixPath.MatchString(str) { return true, Unix } ...
go
{ "resource": "" }
q25776
IsDataURI
train
func IsDataURI(str string) bool { dataURI := strings.Split(str, ",") if !rxDataURI.MatchString(dataURI[0]) { return false } return IsBase64(dataURI[1]) }
go
{ "resource": "" }
q25777
IsISO3166Alpha2
train
func IsISO3166Alpha2(str string) bool { for _, entry := range ISO3166List { if str == entry.Alpha2Code { return true } } return false }
go
{ "resource": "" }
q25778
IsISO3166Alpha3
train
func IsISO3166Alpha3(str string) bool { for _, entry := range ISO3166List { if str == entry.Alpha3Code { return true } } return false }
go
{ "resource": "" }
q25779
IsISO693Alpha2
train
func IsISO693Alpha2(str string) bool { for _, entry := range ISO693List { if str == entry.Alpha2Code { return true } } return false }
go
{ "resource": "" }
q25780
IsISO693Alpha3b
train
func IsISO693Alpha3b(str string) bool { for _, entry := range ISO693List { if str == entry.Alpha3bCode { return true } } return false }
go
{ "resource": "" }
q25781
IsPort
train
func IsPort(str string) bool { if i, err := strconv.Atoi(str); err == nil && i > 0 && i < 65536 { return true } return false }
go
{ "resource": "" }
q25782
IsIPv4
train
func IsIPv4(str string) bool { ip := net.ParseIP(str) return ip != nil && strings.Contains(str, ".") }
go
{ "resource": "" }
q25783
IsRsaPublicKey
train
func IsRsaPublicKey(str string, keylen int) bool { bb := bytes.NewBufferString(str) pemBytes, err := ioutil.ReadAll(bb) if err != nil { return false } block, _ := pem.Decode(pemBytes) if block != nil && block.Type != "PUBLIC KEY" { return false } var der []byte if block != nil { der = block.Bytes } els...
go
{ "resource": "" }
q25784
ValidateStruct
train
func ValidateStruct(s interface{}) (bool, error) { if s == nil { return true, nil } result := true var err error val := reflect.ValueOf(s) if val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { val = val.Elem() } // we only accept structs if val.Kind() != reflect.Struct { return false, fmt.Err...
go
{ "resource": "" }
q25785
IsSSN
train
func IsSSN(str string) bool { if str == "" || len(str) != 11 { return false } return rxSSN.MatchString(str) }
go
{ "resource": "" }
q25786
IsTime
train
func IsTime(str string, format string) bool { _, err := time.Parse(format, str) return err == nil }
go
{ "resource": "" }
q25787
IsISO4217
train
func IsISO4217(str string) bool { for _, currency := range ISO4217List { if str == currency { return true } } return false }
go
{ "resource": "" }
q25788
ByteLength
train
func ByteLength(str string, params ...string) bool { if len(params) == 2 { min, _ := ToInt(params[0]) max, _ := ToInt(params[1]) return len(str) >= int(min) && len(str) <= int(max) } return false }
go
{ "resource": "" }
q25789
IsRsaPub
train
func IsRsaPub(str string, params ...string) bool { if len(params) == 1 { len, _ := ToInt(params[0]) return IsRsaPublicKey(str, int(len)) } return false }
go
{ "resource": "" }
q25790
StringMatches
train
func StringMatches(s string, params ...string) bool { if len(params) == 1 { pattern := params[0] return Matches(s, pattern) } return false }
go
{ "resource": "" }
q25791
Range
train
func Range(str string, params ...string) bool { if len(params) == 2 { value, _ := ToFloat(str) min, _ := ToFloat(params[0]) max, _ := ToFloat(params[1]) return InRange(value, min, max) } return false }
go
{ "resource": "" }
q25792
IsIn
train
func IsIn(str string, params ...string) bool { for _, param := range params { if str == param { return true } } return false }
go
{ "resource": "" }
q25793
ErrorByField
train
func ErrorByField(e error, field string) string { if e == nil { return "" } return ErrorsByField(e)[field] }
go
{ "resource": "" }
q25794
ErrorsByField
train
func ErrorsByField(e error) map[string]string { m := make(map[string]string) if e == nil { return m } // prototype for ValidateStruct switch e.(type) { case Error: m[e.(Error).Name] = e.(Error).Err.Error() case Errors: for _, item := range e.(Errors).Errors() { n := ErrorsByField(item) for k, v := r...
go
{ "resource": "" }
q25795
buildDebug
train
func buildDebug() (string, error) { args := []string{"-gcflags", "-N -l", "-o", "debug"} args = append(args, utils.SplitQuotedFields("-ldflags='-linkmode internal'")...) args = append(args, packageName) if err := utils.GoCommand("build", args...); err != nil { return "", err } fp, err := filepath.Abs("./debug"...
go
{ "resource": "" }
q25796
loadPathsToWatch
train
func loadPathsToWatch(paths *[]string) error { directory, err := os.Getwd() if err != nil { return err } filepath.Walk(directory, func(path string, info os.FileInfo, _ error) error { if strings.HasSuffix(info.Name(), "docs") { return filepath.SkipDir } if strings.HasSuffix(info.Name(), "swagger") { re...
go
{ "resource": "" }
q25797
startDelveDebugger
train
func startDelveDebugger(addr string, ch chan int) int { beeLogger.Log.Info("Starting Delve Debugger...") fp, err := buildDebug() if err != nil { beeLogger.Log.Fatalf("Error while building debug binary: %v", err) } defer os.Remove(fp) abs, err := filepath.Abs("./debug") if err != nil { beeLogger.Log.Fatalf(...
go
{ "resource": "" }
q25798
startWatcher
train
func startWatcher(paths []string, ch chan int) { watcher, err := fsnotify.NewWatcher() if err != nil { beeLogger.Log.Fatalf("Could not start the watcher: %v", err) } defer watcher.Close() // Feed the paths to the watcher for _, path := range paths { if err := watcher.Add(path); err != nil { beeLogger.Log....
go
{ "resource": "" }
q25799
ParsePackagesFromDir
train
func ParsePackagesFromDir(dirpath string) { c := make(chan error) go func() { filepath.Walk(dirpath, func(fpath string, fileInfo os.FileInfo, err error) error { if err != nil { return nil } if !fileInfo.IsDir() { return nil } // skip folder if it's a 'vendor' folder within dirpath or its ch...
go
{ "resource": "" }